diff --git "a/1479.jsonl" "b/1479.jsonl" new file mode 100644--- /dev/null +++ "b/1479.jsonl" @@ -0,0 +1,685 @@ +{"seq_id":"632951424","text":"from Pokemon import *\nfrom Item import *\nfrom Ability import *\nfrom team import *\n\n\nclass game_session(object):\n def __init__(self,my_team,opponent_team):\n self.my_team=my_team\n self.opponent_team=opponent_team\n self.my_on_court=0\n self.opponent_on_court=0\n\n def __str__(self):\n return self.my_team.my_team_detail(),self.opponent_team.opponent_team_detail()\n\n\n @property\n def on_court(self):\n my_pokemon=self.my_team[self.my_on_court]\n opponent_pokemon=self.opponent_team[self.opponent_on_court]\n print(\"\"\"\n {}\\n\n\n\n {}\n\n \"\"\".format(my_pokemon,opponent_pokemon)\n )\n return my_pokemon,opponent_pokemon\n\n\n\n\n\n\n\n\n\n\n\n\n#def turn(i:int,pokemon_team1,pokemon_team2):\n #start of the turns\n# if i==1:\n# start_turn_message=\n# '''\n# Turn {} starts \\n\n# Begin Battle: \\n\n# Chose your pokemon: \\n\n\n# {} {}\\n\n# {} {}\\n\n# {} {}\\n\n\n\n# '''.format(i,pokemon_team1[0].getName,pokemon_team1[0].getType,pokemon_team1[1].getName,pokemon_team1[1].getType,pokemon_team1[2].getName,pokemon_team1[2].getType)\n# else:\n# start_turn_message=\n# ''' Turn {} starts \\n\n#\n# {}\\n\n\n# select an available move for {}:\\n\n# Battle\\n\n# Substitude \\n\n# Give up\n# '''.format(i,pokemon1.battle_stats,pokemon1.getName()))\n\n #check who will move first\n #check which pokemon is on on_court\n #check which pokemon is in the bag\n #check begin of the turn item effect/ability effect\n #check begin of the turn field and weather effect\n #check moves from each pokemon\n #check substitution\n\n #pokemon1 move1\n\n #check move type\n #check if move is valid(still has pp)\n #check success or miss\n #check critical or not if successful\n #check damage/stats change effect\n #check post move status change (toxic, paralysis, etc)\n #check post move item/abiliity effect\n\n #check if pokemon1 dies\n #check if pokemon2 dies\n\n #check move type\n #check if move is valid(still has pp)\n #check success or miss\n #check critical or not if successful\n #check damage/stats change effect\n #check post move status change (toxic, paralysis, etc)\n #check post move item/abiliity effect\n\n #check if pokemon1 dies\n #check if pokemon2 dies\n\n #start of turn end\n #check which pokemon is on on_court\n #check which pokemon is in the bag\n #check end of the turn move damage\n #check end of the turn item effect/ability effect\n #check end of the turn field and weather effect\n #check if pokemon1 dies\n #check if pokemon2 dies\n","sub_path":"gameplay.py","file_name":"gameplay.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"646591173","text":"# Jump Game II \n# Given an array of non-negative integers, you are initially positioned at the first index of the array.\n# \n# Each element in the array represents your maximum jump length at that position.\n# \n# Your goal is to reach the last index in the minimum number of jumps.\n# \n# For example:\n# Given array A = [2,3,1,1,4]\n# \n# The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)\n\n\n# Solutions:\n# - Original bruteforce solution is too slow. \n# - A greedy solution is working\n\n# Bugs:\n# - Didn't considered the [0] boundary case\n# - The terminate clause and initial steps value\n\nclass Solution:\n # @param A, a list of integers\n # @return an integer\n def jump(self, A):\n if len(A) == 1:\n return 0\n steps = 1\n i = 0\n while A[i] + i < len(A) -1:\n next_step = i + 1\n for j in range(i+1, i+A[i]+1):\n if A[j] + j > A[next_step] + next_step:\n next_step = j \n i = next_step\n steps += 1\n return steps\n \n \nclass Solution_Slow:\n # @param A, a list of integers\n # @return an integer\n def jump(self, A):\n length = len(A)\n A[-1] = 1\n for i in reversed(range(length)):\n if A[i] == 0:\n A[i] = length\n elif A[i] + i >= length - 1:\n A[i] = 1\n else:\n A[i] = min(A[i+1:i+A[i]+1]) + 1\n return A[0]\n\n\n \n\n\n","sub_path":"045_JumpGame2/jump.py","file_name":"jump.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"573859121","text":"import sqlite3\nfrom capteurs_test import *\n#from capteurs import *\nfrom datetime import date, datetime, time\n\n# INSERT __________________________________________________________________________________________\n# insert_data_req() inserts temperature, sensor ID, and date data into the database \"vivariumbdd.db\"\n\n\ndef insert_data_req():\n \n try:\n capteur_list = return_data()\n connex = sqlite3.connect(\"vivariumbdd.db\")\n cursor = connex.cursor()\n #print(\"coucou\") \n \n \n for each_capteur in capteur_list:\n cursor.execute('INSERT INTO vivariumtable(temperature, id_capteur, current_date) VALUES(?,?,?)', each_capteur)\n connex.commit()\n #print (\"coucou 2\")\n except Exception as e:\n print(\"[ERREUR]\", e) # Comment bien gérer exception ??\n connex.rollback()\n finally:\n connex.close()\n\n\n","sub_path":"vivarium_bdd.py","file_name":"vivarium_bdd.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"248728082","text":"#!/usr/bin/python\n\nimport os\nimport sys\nfrom constants import *\nsys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../../lib')\nfrom checker import Checker\n\ndef main():\n ch = Checker()\n\n d = ch.readInt()\n for _ in xrange(d):\n n,m,a = ch.readInts(3)\n ch.checkRange(n, N_MIN, N_MAX, 'N')\n ch.checkRange(m, M_MIN, M_MAX, 'M')\n ch.checkRange(a, A_MIN, A_MAX, 'A')\n\n s = ch.readInts(m)\n for v in s:\n ch.checkRange(v, S_MIN, S_MAX, 'S')\n\nif __name__ == '__main__':\n main()\n","sub_path":"welcome/tests/validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"64739872","text":"# Exercise 2-02: The number of cats\n\n# Open \"alice.txt\" and assign the file to \"file\"\nwith open('input/alice.txt') as file:\n text = file.read()\n\nn = 0\nfor word in text.split():\n if word.lower() in ['cat', 'cats']:\n n += 1\n\nprint('Lewis Carroll uses the word \"cat\" {} times'.format(n))\n","sub_path":"06_Writing-Functions-in-Python/06_ex_2-02.py","file_name":"06_ex_2-02.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"348910621","text":"from tkinter import *\nfrom tkinter import ttk\nimport tkinter.font as font\nfrom Organizer import *\n\n###################################Root of Project###################################\n\nroot=Tk()\nroot.resizable(height = None, width = None)\nroot.title(\"Delta Calander\")\nroot.minsize(500, 500) \n\n##########################Setting a Gradient Background##############################\n\n\nfilename = PhotoImage(file = \"gradient1.png\")\nbackground_label = Label(root, image=filename)\nbackground_label.place(x=0, y=0, relwidth=1, relheight=1)\n\n############################Creating a new window functions#############################\n\ndef create_window():\n global list2, list1, i, button\n list2 = sorting(list1)\n for i in range(10 - i):\n list2.append(\"\")\n \n next_window=Tk()\n next_window.minsize(500, 500)\n filename = PhotoImage(file = \"gradient1.png\")\n background_label = Label(next_window, image=filename)\n background_label.place(x=0, y=0, relwidth=1, relheight=1)\n next_window.title(\"Delta Calender\")\n\n myFont = font.Font(family='Courier', size=20, weight=\"bold\")\n title2 = Label(next_window, text = \"Your Organized Goal List\", bg = '#B4D7D1')\n title2['font'] = myFont\n title2.place(relwidth = 0.9, relheight= 0.1, relx= 0.05, rely=0.01)\n\n \n myFont2 = font.Font(family='Courier', size=10, weight='bold')\n\n one = ttk.Label(next_window, text= (\"1. \" + (str(list2[0])).split(\"|\")[0]).upper(),background = '#B4D7D1')\n one[\"font\"] = myFont2\n one.place(relx=0.10, rely=0.15, relwidth=0.80, relheight=0.05)\n two = ttk.Label(next_window, text= \"2. \"+ str(list2[1]).split(\"|\")[0].upper(),background = '#B4D7D1')\n two[\"font\"] = myFont2\n two.place(relx=0.10, rely=0.22, relwidth=0.8, relheight=0.05)\n three = ttk.Label(next_window, text=\"3. \" + str(list2[2]).split(\"|\")[0].upper(),background = '#B4D7D1')\n three[\"font\"] = myFont2\n three.place(relx=0.10, rely=0.29, relwidth=0.8, relheight=0.05)\n four = ttk.Label(next_window, text=\"4. \" + str(list2[3]).split(\"|\")[0].upper(),background = '#B4D7D1')\n four[\"font\"] = myFont2\n four.place(relx=0.10, rely=0.36, relwidth=0.8, relheight=0.05)\n five = ttk.Label(next_window, text=\"5. \" + str(list2[4]).split(\"|\")[0].upper(),background = '#B4D7D1')\n five[\"font\"] = myFont2\n five.place(relx=0.10, rely=0.43, relwidth=0.8, relheight=0.05)\n six = ttk.Label(next_window, text=\"6. \" + str(list2[5]).split(\"|\")[0].upper(),background = '#B4D7D1')\n six[\"font\"] = myFont2\n six.place(relx=0.10, rely=0.50, relwidth=0.8, relheight=0.05)\n seven = ttk.Label(next_window, text=\"7. \" + str(list2[6]).split(\"|\")[0].upper(),background = '#B4D7D1')\n seven[\"font\"] = myFont2\n seven.place(relx=0.10, rely=0.57, relwidth=0.8, relheight=0.05)\n eight = ttk.Label(next_window, text=\"8. \" + str(list2[7]).split(\"|\")[0].upper(),background = '#B4D7D1')\n eight[\"font\"] = myFont2\n eight.place(relx=0.10, rely=0.64, relwidth=0.8, relheight=0.05)\n nine = ttk.Label(next_window, text=\"9. \" + str(list2[8]).split(\"|\")[0].upper(),background = '#B4D7D1')\n nine[\"font\"] = myFont2\n nine.place(relx=0.10, rely=0.71, relwidth=0.8, relheight=0.05)\n ten = ttk.Label(next_window, text=\"10. \" + str(list2[9]).split(\"|\")[0].upper(),background = '#B4D7D1')\n ten[\"font\"] = myFont2\n ten.place(relx=0.10, rely=0.78, relwidth=0.8, relheight=0.05)\n\n button = ttk.Button(next_window, text=\"Upload to Google Calander\", command=uploadToCalender)\n button.place(relx=0.25, rely=0.90, relwidth=0.5, relheight=0.07)\n \n next_window.mainloop()\n\ndef uploadToCalender():\n global button\n button.config(state = DISABLED)\n list3 = []\n for x in range(len(list1)):\n if list1[x] != \"\":\n list3.append(str(list1[x]))\n APICalendar(list3)\n\ndef To_the_nextwindow():\n global i, shmoke, var \n content = shmoke.get()\n content2 = var.get()\n list1.append( str(content) + \"|\" + str(content2))\n root.destroy()\n create_window()\n\nnextButton = ttk.Button(root,text=\"Submit\",command=To_the_nextwindow)\nnextButton.place(relwidth = 0.3, relheight= 0.05, relx= 0.35, rely=0.9)\n\n#############################Creating a Title############################################\n\nmyFont = font.Font(family='Courier', size=20, weight='bold')\ntitlel = Label(root, text = \"Enter Daily Goals\", bg = '#B4D7D1')\ntitlel['font'] = myFont\ntitlel.place(relwidth = 1, relheight= 0.15, relx= 0, rely=0)\n\n#############################Creating input interface#####################################\n\nglobal count, i, list1\ncount = 0.20\nlist1 = []\ni = 0\n\ndef adder():\n global count,i, list1, var\n content = shmoke.get()\n content2 = var.get()\n list1.append( str(content) + \"|\" + str(content2))\n i = i + 1\n if (count < 0.80):\n count = count + 0.07\n createEntry(count)\n \ndef createEntry(count):\n global shmoke, shmoke1, var\n shmoke = ttk.Entry(root)\n shmoke1=OptionMenu\n shmoke.place( relwidth = 0.4, relheight= 0.05, relx= 0.05, rely= count)\n var = StringVar(root)\n var.set(\"\")\n choices = [ \"\", \"Fitness-Priority 1\",\"Fitness-Priority 2\", \"Fitness-Priority 3\" ,\n \"Leisure-Priority 1\" , \"Leisure-Priority 2\" , \"Leisure-Priority 3\", \"Academic Work-Priority 1\", \"Academic Work-Priority 2\" , \"Academic Work-Priority 3\",\n \"Extracurricular-Priority 1\", \"Extracurricular-Priority 2\", \"Extracurricular-Priority 3\", \"Career-Priority 1\", \"Career-Priority 2\" , \"Career-Priority 3\", \"Errands-Priority 1\",\n \"Errands-Priority 2\", \"Errands-Priority 3\",]\n shmoke1 = ttk.OptionMenu(root, var, *choices)\n shmoke1.place( relwidth = 0.4, relheight= 0.05, relx= 0.55, rely= count )\n\n\ndef Destroyers():\n root.destroy()\n\nmyFont1 = font.Font(family='Courier', size=10, weight='bold')\nLabel_1 = Label(root, text=\"Activites\",background = '#B4D7D1')\nLabel_1.place(relwidth = 0.4, relheight= 0.05, relx= 0.05, rely=0.15)\nLabel_1[\"font\"] = myFont1\n\nLabel_2 = Label(root, text=\"Catogory/Priority\",background = '#B4D7D1')\nLabel_2.place(relwidth = 0.4, relheight= 0.05, relx= 0.55, rely=0.15)\nLabel_2[\"font\"] = myFont1\n \n#inital goal entry\nshmoke = ttk.Entry(root)\nshmoke.place( relwidth = 0.4, relheight= 0.05, relx= 0.05, rely=0.20 )\n\n#Add another goal button\nb1 = ttk.Button(root, text=\"Add another goal\", command=adder)\nb1.place(relwidth = 0.3, relheight= 0.05, relx= 0.05, rely=0.9)\n\n#Add clear all button\nb2 = ttk.Button(root, text=\"Quit Application\", command=Destroyers)\nb2.place(relwidth = 0.3, relheight= 0.05, relx= 0.65, rely=0.9)\n\n#Add drop down menue\nvar = StringVar(root)\nchoices = [ \"\", \"Fitness-Priority 1\",\"Fitness-Priority 2\", \"Fitness-Priority 3\" ,\n \"Leisure-Priority 1\" , \"Leisure-Priority 2\" , \"Leisure-Priority 3\", \"Academic Work-Priority 1\", \"Academic Work-Priority 2\" , \"Academic Work-Priority 3\",\n \"Extracurricular-Priority 1\", \"Extracurricular-Priority 2\", \"Extracurricular-Priority 3\", \"Career-Priority 1\", \"Career-Priority 2\" , \"Career-Priority 3\", \"Errands-Priority 1\",\n \"Errands-Priority 2\", \"Errands-Priority 3\",]\nshmoke1 = ttk.OptionMenu(root, var, *choices)\nshmoke1.place( relwidth = 0.4, relheight= 0.05, relx= 0.55, rely=0.20 )\n\nroot.mainloop()\n","sub_path":"delta.py","file_name":"delta.py","file_ext":"py","file_size_in_byte":7227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"281144309","text":"from sqsHandler import SqsHandler\n\nmensagens = []\nnumMsgsToCreate = 3000\nfor num in range(numMsgsToCreate):\n mensagens.append({'Id':str(num), 'MessageBody': str(num)})\n\nsplitMsg = [mensagens[x:x+10] for x in range(0, len(mensagens), 10)]\nsqs = SqsHandler('')\nfor lista in splitMsg: \n print(type(lista))\n print(str(lista))\n sqs.sendBatch(lista)","sub_path":"05-SQS/01 - Standart Queue/put.py","file_name":"put.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"466768492","text":"\nimport sys, os\nsys.path.append(r\"/usr/local/lib/python2.7/dist-packages\")\nfrom pymongo import MongoClient\n\nREGIONS = [\"br\", \"eune\", \"euw\", \"kr\", \"lan\", \"las\", \"na\", \"oce\", \"ru\", \"tr\"]\nSUMMONER_ID_FIELD = \"summonerId\"\nSUMMONER_ID_IN_GAME = \"fellowPlayers.\" + SUMMONER_ID_FIELD\n\ndef query_missing_sids():\n client = MongoClient()\n missing_dict = get_missing(client)\n for region in REGIONS:\n process_missing(region, missing_dict[region])\n\ndef get_missing(client):\n missing_dict={}\n for region in REGIONS:\n db = get_db(client, region)\n sids = get_sids_from_games(db)\n missing_dict[region] = find_missing_sids(db, sids)\n return missing_dict\n\ndef get_db(client, region):\n db_name = \"lol_\" + region\n return client[db_name]\n\ndef get_sids_from_games(db):\n games = db.games.find({}, {\"_id\":False , SUMMONER_ID_IN_GAME: True})\n return extract_sids_from_games(games)\n\ndef extract_sids_from_games(games):\n sids=[]\n for game in games:\n if not u'fellowPlayers' in game:\n continue\n for sid in game[u'fellowPlayers']:\n sids.append(sid[u'summonerId'])\n return sids\n \ndef find_missing_sids(db, sids):\n missing_sids=[]\n for sid in sids:\n if db.summoners.find_one({'summonerId': sid}) == None:\n missing_sids.append(sid)\n return missing_sids\n\ndef process_missing(region, sids):\n while len(sids)>0:\n sids_for_request = sids[:20]\n sids = sids[21:]\n poll_summoners(region, sids_for_request)\n \ndef poll_summoners(region, sids):\n sids_string = \", \".join([str(sid) for sid in sids])\n cmd = \"curl --data \\\"region=%s&sids=%s\\\" http://localhost/lol/internal/post_summoners.php\" % ( region, sids_string )\n os.system(cmd)\n\nif __name__ == \"__main__\":\n query_missing_sids()\n","sub_path":"scripts/find_missing_summoners.py","file_name":"find_missing_summoners.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"320720145","text":"\n##################################\n# fichier 04-fonction-min-obligatoire.py\n# nom de l'exercice : Fonction min\n# url : http://www.france-ioi.org/algo/task.php?idChapter=509&idTask=0&sTab=task&iOrder=7\n# type : obligatoire\n#\n# Chapitre : chapitre-4-fonctions\n#\n# Compétence développée : \n#\n# auteur : \n##################################\n\n# chargement des modules\n\n\n# mettre votre code ici\n\n#fonction mini et pas min car min et déjà utilisé par python !\ndef mini(entier1, entier2):\n \"\"\"fonction qui prend 2 entiers en paramètre et\n renvoie le plus petit des deux.\"\"\"\n\n if entier1 > entier2:\n return entier2\n else:\n return entier1\n\n#coprs du programme\nliste = [0,1,2,3,4,5,6,7,8,9] #une liste de base \"pseudo-quelconque\"\nfor i in liste:\n liste[i] = int(input()) #actualisation de la liste\n \nminimum = 1000 #minimum de base très grand pour éviter d'avoir un minim plus petit que le vrai minimum\nfor nbr in liste:\n var = mini(minimum,nbr)\n if var == minimum:\n minimum = var #actualistation du minimum\n else:\n minimum = nbr #actualistation du minimum\n \nprint(minimum)","sub_path":"niveau-02/chapitre-4-fonctions/04-fonction-min-obligatoire.py","file_name":"04-fonction-min-obligatoire.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"264071944","text":"import configparser\nimport xml.etree.ElementTree as ET\nimport requests\nfrom html2text import html2text\nfrom tinydb import TinyDB, Query\n\nconfig = configparser.RawConfigParser()\nconfig.read('config.ini')\n\ndb = TinyDB(config.get('store', 'path'))\n\n\nr = requests.get(config.get('source', 'url'))\n\nroot = ET.fromstring(r.text)\n\nchannel = root.find('channel')\n\nQ = Query()\n\nfor item in channel.findall('item'):\n apt = dict()\n\n apt_id = item.find('link').text.split('/')[-1]\n\n #if item.find('geo:long')\n\n if db.contains(Q.id == apt_id):\n continue\n\n apt['id'] = apt_id\n apt['title'] = html2text(item.find('title').text)\n apt['desc'] = html2text(item.find('description').text)\n\n apt['pub_date'] = item.find('{http://purl.org/dc/elements/1.1/}date').text\n\n lat = item.find('{http://www.w3.org/2003/01/geo/wgs84_pos#}lat')\n apt['lat'] = None if lat is None else float(lat.text)\n\n lon = item.find('{http://www.w3.org/2003/01/geo/wgs84_pos#}long')\n apt['lon'] = None if lon is None else float(lon.text)\n\n price = item.find('{http://base.google.com/ns/1.0}price')\n apt['price'] = None if price is None else float(price.text)\n\n\n print(apt['title'])\n print(apt_id + ' created')\n\n db.insert(apt)\n","sub_path":"scrapper.py","file_name":"scrapper.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"61348496","text":"# catNames = []\r\n# while True:\r\n# print('Enter the name of cat ' + str(len(catNames) + 1) + ' (Or enter nothing to stop.):')\r\n# name = input()\r\n# if name == '':\r\n# break\r\n# catNames = catNames + [name] # list concatenation\r\n# print('The cat names are:')\r\n# for name in catNames:\r\n# print(' ' + name)\r\n\r\n# method = any action we can take upon an object\r\n# property = a characteristic/descriptor\r\n# object = any thing that can be in memory\r\n\r\n# products = [19.99, \"Computer 1\", 27]\r\n# while True:\r\n# price = (input(\"Enter the product price or press enter to continue: \"))\r\n# prod_desc = input(\"Enter the product name or press enter to continue: \")\r\n# monitor = (input(\"Enter the product size or press enter to continue: \"))\r\n# if price == '' or prod_desc == '' or monitor == '':\r\n# break\r\n# products = products + [price] + [prod_desc] + [monitor]\r\n# print(products)\r\n\r\nnames = [\"John\", \"Betty\", \"Zak\", \"Mark\", \"Mary\", \"Kylie\"]\r\n\r\n# Returns the index value of an element in the list\r\n# a = names.index('Zak')\r\n# print(a)\r\n\r\n# This is a ValueError message because 'Charles' is not in the list\r\n# b = names.index(\"Charles\")\r\n# print(b)\r\n\r\n# The append() will insert an element at the end of a list\r\nnames.append(\"Amos\")\r\n# print(names)\r\n\r\n# The insert() method will allow the programmer to target a position in the list to insert a value\r\nnames.insert(3, \"Steve\")\r\n# print(names)\r\n\r\nnames.remove(\"Mark\")\r\n# print(names)\r\n\r\n# When performing a sort(), it will not work on a mixed list(ie. integers/alpha chars.)\r\nnames.sort()\r\n# print(names)\r\n\r\n# names.sort(reverse=True)\r\n# print(names)\r\n\r\n# userInput = input(\"Search for a name here: \")\r\n# if userInput in names:\r\n# print('The name of ' + userInput + ' was found and will be removed.')\r\n# names.remove(userInput)\r\n# elif userInput not in names:\r\n# print('The name of ' + userInput + ' was not found.')\r\n\r\n# or\r\n\r\n# def findName():\r\n# print('Here are the names in the list: ')\r\n# print(names)\r\n# j = 0\r\n# my_name = input('What name do you want removed: ')\r\n# for i in range(len(names)):\r\n# if my_name in names:\r\n# names.remove(my_name)\r\n# j = 1\r\n# else:\r\n# continue\r\n# if j == 1:\r\n# print('The value of ' + my_name + ' was found and removed: ')\r\n# print(names)\r\n# else:\r\n# print('The value of ' + my_name + ' was not found')\r\n\r\n# findName()\r\n\r\n# Nested loop is a loop in a loop\r\nnumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]\r\npeople = [\"Andy\", \"Betsy\", \"Charles\", \"David\", \"George\", \"Harry\", \"Larry\", \"Mary\", \"Rose\"]\r\n\r\nfor i in range(len(numbers)):\r\n for j in range(len(people)):\r\n # print(\"Person Num. \" + str(numbers[i]) + ' is ' + people[j] + '.')\r\n placeOfPeople = str(numbers[i]) + \". \" + people[i]\r\n print(placeOfPeople)\r\n\r\n","sub_path":"Python/PycharmProjects_1718/Class Notes/Week6_Notes.py","file_name":"Week6_Notes.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"162058290","text":"import logging\nimport pickle\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport torch\nfrom torch.utils import data\nimport torchvision\nfrom torchvision import datasets, transforms\n\nfrom models.cifar.resnet import resnet\nfrom py3simplex import plotSimplex\n\nlogger = logging.getLogger(__name__)\n\n\ndef main():\n\n logger.info('Loading SVHN test data')\n transform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n inv_transform = transforms.Normalize((-0.4914 / 0.2023, -0.4822 / 0.1994, -0.4465 / 0.2010),\n (1 / 0.2023, 1 / 0.1994, 1/ 0.2010))\n\n dataset = datasets.SVHN(root='data/', split='test', download=True,\n transform=transform)\n dataloader = data.DataLoader(dataset, batch_size=1000, shuffle=False,\n num_workers=4)\n\n logger.info('Loading model')\n model = resnet(num_classes=10, depth=152)\n model = torch.nn.DataParallel(model).cuda()\n # checkpoint = torch.load('resnet-110/model_best.pth.tar')\n checkpoint = torch.load('checkpoint/model_best.pth.tar')\n model.load_state_dict(checkpoint['state_dict'])\n\n model.eval()\n\n i = 0\n print('Index Correct Predicted Confidence')\n for inputs, targets in dataloader:\n inputs, targets = inputs.cuda(), targets.cuda()\n with torch.no_grad():\n logits = model(inputs)\n probs = torch.softmax(logits, dim=-1)\n values, indices = torch.max(probs, 1)\n for target, logit in zip(targets, logits):\n tgt_string = '%i ' % target.item()\n prediction_strings = ['%0.8f' % x for x in logit.tolist()]\n print(tgt_string + ' '.join(prediction_strings))\n # incorrect = indices != targets\n # high_confidence = values > 0.90\n # idx = incorrect & high_confidence\n\n # misses = inputs[idx]\n # y_hats = indices[idx]\n # ys = targets[idx]\n # confs = values[idx]\n\n # import pdb; pdb.set_trace()\n # preds_0 = probs[:,0].cpu().numpy()\n # preds_1 = probs[:,1].cpu().numpy()\n # preds_2 = probs[:,2:].sum(dim=1).cpu().numpy()\n # points = np.vstack([preds_0, preds_1, preds_2]).T\n # colors = targets.cpu().numpy()\n # colors[colors>1] = 2\n\n # plotSimplex(points, c=colors)\n # plt.savefig('simplex.png')\n\n\n # for tensor, y, y_hat, conf in zip(inputs, targets, indices, values):\n # image = inv_transform(tensor)\n # image.squeeze_()\n # torchvision.utils.save_image(image, filename='img_svhn/%i.png' % i)\n # correct = y.item()\n # predicted = y_hat.item()\n # print('%i %s %s %0.4f' % (i, correct, predicted, conf))\n # i+=1\n\n\nif __name__ == '__main__':\n\n logging.basicConfig(level=logging.INFO)\n\n main()\n\n","sub_path":"predict_svhn.py","file_name":"predict_svhn.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"145159991","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nwhile True:\n x,y,s = map(int,input().split())\n if (x,y,s) == (0,0,0):\n break\n ans = 0\n count = 0\n for i in range(1,s//2 + 1):\n for j in range(1,s-i + 1):\n count += 1\n if i*(100+x)//100 + j*(100+x)//100== s:\n ans = max(ans,i*(100+y)//100 + j*(100+y)//100)\n print(ans,count)\n","sub_path":"AOJ/ICPC/100/1192_.py","file_name":"1192_.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"58581167","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# IMPORT STANDARD LIBRARIES\nimport sys\nimport unittest\n\n\n# Works with unittest in Python 2.7\nclass ExpectingTestCase(unittest.TestCase):\n def run(self, result=None):\n self._result = result\n self._num_expectations = 0\n super(ExpectingTestCase, self).run(result)\n\n def _fail(self, failure):\n try:\n raise failure\n except failure.__class__:\n self._result.addFailure(self, sys.exc_info())\n\n def expect_true(self, a, msg):\n if not a:\n self._fail(self.failureException(msg))\n self._num_expectations += 1\n\n def expect_equal(self, a, b, msg=''):\n if a != b:\n msg = '({}) Expected {} to equal {}. '\\\n ''.format(self._num_expectations, a, b) + msg\n self._fail(self.failureException(msg))\n self._num_expectations += 1\n\n\n","sub_path":"tests/test_common.py","file_name":"test_common.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"610817234","text":"uurwaarden = \"673,1449,82,100019341,13,996308,53,7,4711,2,189320\"\n\nuurwaarden = uurwaarden.split(\",\")\ntotaal = 0\n\n# eerst de breedte van het grootste getal bepalen:\n# het totaal van alle uren\n\nfor uur in uurwaarden:\n totaal+=int(uur)\n\nlengte = len(str(totaal))\n\n# nu de gevonde lengte (7) gebruiken \n# om de variabele melding mee samen te stellen:\n\nmelding = \"Uur %%2d: %%%dd\" % lengte # resultaat: \"Uur %2d: %7d\"\nprint(\"DEBUG - melding is nu:\", melding) # even controleren of het klopt\n\n# nu de melding gebruiken bij het printen van de uren in nette kolommen:\n\nfor nr, uur in enumerate(uurwaarden):\n uur = int(uur)\n print(melding % (nr+1, uur))\n\t\nprint(\"Totaal:\", totaal)\n","sub_path":"opgave25a.py","file_name":"opgave25a.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"269457504","text":"# Start from a directory with 1+ subdir repos,\n# Navigates into each and tries to update (git pull)\n# Handles non git repo dirs and non dirs,\n# Handles optional reset changes to be overwritten by merge\n\nimport os\nimport logging\nimport git\nimport requests\nimport shutil\nimport stat\nfrom git import Repo\n\nlogging.basicConfig(level=20)\nlogging.info('start')\nstartingDir = os.getcwd()\n# logging.info(startingDir)\n# repoDirs = os.listdir(startingDir)\n# logging.info(repoDirs)\n\ndef updateAllRepos ():\n for repoDir in repoDirs:\n os.chdir(startingDir)\n logging.info('Going to %s' %repoDir)\n if not os.path.isdir(repoDir):\n logging.info('%s is not a directory. Skipping.' %repoDir)\n continue\n os.chdir(repoDir)\n cwd = os.getcwd()\n try:\n repo = Repo(cwd)\n origin = repo.remotes.origin\n assert not repo.bare\n assert origin.exists()\n logging.info('Pulling: ' + repo.remotes.origin.url)\n\n if repo.is_dirty():\n reset = input('Reset all changes in %s and pull? (Y/N) ' %repoDir)\n if reset == 'N':\n continue\n repo.head.reset(index=True, working_tree=True)\n\n origin.pull()\n logging.info('Pull OK')\n except git.exc.InvalidGitRepositoryError:\n logging.warn('%s is not a git repo. Skipping' %repoDir)\n continue\n except:\n logging.warn(\"Unexpected error\")\n raise\n\nupdateAllRepos();\nlogging.info('Done')\n","sub_path":"updateAllControllers.py","file_name":"updateAllControllers.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"277648983","text":"#Version 3.0 create by Vassia Bonandrini\r\n#Last release : 07/04/2020\r\n\r\nimport json\r\nimport urllib.request\r\nimport time\r\nimport requests\r\nimport os\r\nfrom pytube import YouTube\r\n\r\n#import for twitter\r\nimport sys\r\nfrom requests_oauthlib import OAuth1\r\n\r\ncount =50\r\nAPI_KEY = ''\r\nsearchTerm=\"lofi\"\r\nwaittime=3600.0*24\r\ntime_video = 0.49 #in secondes\r\n\r\nOAUTH_TOKEN = \"\"\r\nOAUTH_SECRET = \"\"\r\nCONSUMER_KEY = \"\"\r\nCONSUMER_SECRET = \"\"\r\n\r\nwhile(True):\t\r\n\tstarttime=time.time()\r\n\tvideoId=\"\"\r\n\tcontenu=\"\"\r\n\tpage=\"\"\r\n\tLINK=\"\"\r\n\tNOM_VID=\"\"\r\n\r\n\t#get Youtube link\r\n\tprint(\"-------------SEARCH YOUTUBE LINK-------------\\n\")\r\n\r\n\tfile=open(\"liens.txt\",\"r\")\r\n\ttry:\r\n\t\tcontenu=file.read()\r\n\texcept:\r\n\t\tprint(\"le fichier est vide\")\r\n\tfile.close()\r\n\t\r\n\twhile(True):\r\n\r\n\t\turlData = \"https://www.googleapis.com/youtube/v3/search?key={}&maxResults={}&part=snippet&type=video&q={}&pageToken={}\".format(API_KEY,count,searchTerm,page)\r\n\t\twebURL = urllib.request.urlopen(urlData)\r\n\t\tdata = webURL.read()\r\n\t\tencoding = webURL.info().get_content_charset('utf-8')\r\n\t\tresults = json.loads(data.decode(encoding))\r\n\t\tpage=results['nextPageToken']\r\n\r\n\t\tfor data in results['items']:\r\n\t\t\tvideoId = (data['id']['videoId'])\r\n\t\t\tif ((videoId not in contenu) and (data['snippet']['liveBroadcastContent']=='none')):\r\n\t\t\t\tLINK=\"https://www.youtube.com/watch?v=\"+videoId\r\n\t\t\t\ttry:\r\n\t\t\t\t\tyt=YouTube(LINK)\r\n\t\t\t\texcept:\r\n\t\t\t\t\tcontinue\r\n\t\t\t\tNOM_VID=data['snippet']['title']\r\n\t\t\t\tprint(LINK)\r\n\t\t\t\tfile=open(\"liens.txt\",\"a\")\r\n\t\t\t\tfile.write(videoId+\"\\n\")\r\n\t\t\t\tfile.close()\r\n\t\t\t\tbreak\r\n\t\telse:\r\n\t\t\tprint(\"changement de page !\\n\")\r\n\t\t\tcontinue\r\n\t\tbreak\r\n\r\n\tprint(\"-------------DOWNLOAD VIDEO-------------\\n\")\r\n\tt=yt.streams.filter(subtype='mp4')\r\n\tt[0].download(filename='video')\r\n\r\n\tprint(\"-------------CUT VIDEO-------------\\n\")\r\n\tfrom moviepy.editor import *\r\n\r\n\tclip=VideoFileClip(\"video.mp4\").subclip(0,(time_video,0))\r\n\tclip.write_videofile(\"temp.mp4\",audio_codec='aac')\r\n\tclip.close()\r\n\r\n\t#os.remove(\"video.mp4\")\r\n\t#post on twitter\r\n\tprint(\"-------------Post on Twitter-------------\\n\")\r\n\t\r\n\tNOM_VID=NOM_VID+\" #lofi #study #chill \"+LINK\r\n\tMEDIA_ENDPOINT_URL = 'https://upload.twitter.com/1.1/media/upload.json'\r\n\tPOST_TWEET_URL = 'https://api.twitter.com/1.1/statuses/update.json'\r\n\r\n\toauth = OAuth1(CONSUMER_KEY,\r\n\t client_secret=CONSUMER_SECRET,\r\n\t resource_owner_key=OAUTH_TOKEN,\r\n\t resource_owner_secret=OAUTH_SECRET)\r\n\r\n\tclass VideoTweet(object):\r\n\t\tdef __init__(self, file_name):\r\n\t\t\t'''\r\n\t\t\tDefines video tweet properties\r\n\t\t\thttps://github.com/twitterdev/large-video-upload-python/blob/master/async-upload.py\r\n\t\t\t'''\r\n\t\t\tself.video_filename = file_name\r\n\t\t\tself.total_bytes = os.path.getsize(self.video_filename)\r\n\t\t\tself.media_id = None\r\n\t\t\tself.processing_info = None\r\n\r\n\t\tdef upload_init(self):\r\n\t\t\t'''\r\n\t\t\tInitializes Upload\r\n\t\t\t'''\r\n\t\t\tprint('INIT')\r\n\r\n\t\t\trequest_data = {\r\n\t\t\t 'command': 'INIT',\r\n\t\t\t 'media_type': 'video/mp4',\r\n\t\t\t 'total_bytes': self.total_bytes,\r\n\t\t\t 'media_category': 'tweet_video'\r\n\t\t\t}\r\n\r\n\t\t\treq = requests.post(url=MEDIA_ENDPOINT_URL, data=request_data, auth=oauth)\r\n\t\t\tmedia_id = req.json()['media_id']\r\n\r\n\t\t\tself.media_id = media_id\r\n\r\n\t\t\tprint('Media ID: %s' % str(media_id))\r\n\r\n\r\n\t\tdef upload_append(self):\r\n\t\t\t'''\r\n\t\t\tUploads media in chunks and appends to chunks uploaded\r\n\t\t\t'''\r\n\t\t\tsegment_id = 0\r\n\t\t\tbytes_sent = 0\r\n\t\t\tfile = open(self.video_filename, 'rb')\r\n\r\n\t\t\twhile bytes_sent < self.total_bytes:\r\n\t\t\t chunk = file.read(4*1024*1024)\r\n\t\t\t \r\n\t\t\t print('APPEND')\r\n\r\n\t\t\t request_data = {\r\n\t\t\t\t'command': 'APPEND',\r\n\t\t\t\t'media_id': self.media_id,\r\n\t\t\t\t'segment_index': segment_id\r\n\t\t\t }\r\n\r\n\t\t\t files = {\r\n\t\t\t\t'media':chunk\r\n\t\t\t }\r\n\r\n\t\t\t req = requests.post(url=MEDIA_ENDPOINT_URL, data=request_data, files=files, auth=oauth)\r\n\r\n\t\t\t if req.status_code < 200 or req.status_code > 299:\r\n\t\t\t print(req.status_code)\r\n\t\t\t print(req.text)\r\n\t\t\t sys.exit(0)\r\n\r\n\t\t\t segment_id = segment_id + 1\r\n\t\t\t bytes_sent = file.tell()\r\n\r\n\t\t\t print('%s of %s bytes uploaded' % (str(bytes_sent), str(self.total_bytes)))\r\n\r\n\t\t\tprint('Upload chunks complete.')\r\n\r\n\r\n\t\tdef upload_finalize(self):\r\n\t\t\t'''\r\n\t\t\tFinalizes uploads and starts video processing\r\n\t\t\t'''\r\n\t\t\tprint('FINALIZE')\r\n\r\n\t\t\trequest_data = {\r\n\t\t\t 'command': 'FINALIZE',\r\n\t\t\t 'media_id': self.media_id\r\n\t\t\t}\r\n\r\n\t\t\treq = requests.post(url=MEDIA_ENDPOINT_URL, data=request_data, auth=oauth)\r\n\r\n\t\t\tself.processing_info = req.json().get('processing_info', None)\r\n\t\t\tself.check_status()\r\n\r\n\t\tdef check_status(self):\r\n\t\t\t'''\r\n\t\t\tChecks video processing status\r\n\t\t\t'''\r\n\t\t\tif self.processing_info is None:\r\n\t\t\t return\r\n\r\n\t\t\tstate = self.processing_info['state']\r\n\r\n\t\t\tprint('Media processing status is %s ' % state)\r\n\r\n\t\t\tif state == u'succeeded':\r\n\t\t\t return\r\n\r\n\t\t\tif state == u'failed':\r\n\t\t\t sys.exit(0)\r\n\r\n\t\t\tcheck_after_secs = self.processing_info['check_after_secs']\r\n\t\t\t\r\n\t\t\tprint('Checking after %s seconds' % str(check_after_secs))\r\n\t\t\ttime.sleep(check_after_secs)\r\n\r\n\t\t\tprint('STATUS')\r\n\r\n\t\t\trequest_params = {\r\n\t\t\t 'command': 'STATUS',\r\n\t\t\t 'media_id': self.media_id\r\n\t\t\t}\r\n\r\n\t\t\treq = requests.get(url=MEDIA_ENDPOINT_URL, params=request_params, auth=oauth)\r\n\t\t\t\r\n\t\t\tself.processing_info = req.json().get('processing_info', None)\r\n\t\t\tself.check_status()\r\n\r\n\r\n\t\tdef tweet(self):\r\n\t\t\t'''\r\n\t\t\tPublishes Tweet with attached video\r\n\t\t\t'''\r\n\t\t\trequest_data = {\r\n\t\t\t 'status': NOM_VID,\r\n\t\t\t 'media_ids': self.media_id\r\n\t\t\t}\r\n\r\n\t\t\treq = requests.post(url=POST_TWEET_URL, data=request_data, auth=oauth)\r\n\r\n\tvideoTweet = VideoTweet(\"temp.mp4\")\r\n\tvideoTweet.upload_init()\r\n\tvideoTweet.upload_append()\r\n\tvideoTweet.upload_finalize()\r\n\tvideoTweet.tweet()\r\n\t\t\r\n\tos.remove(\"temp.mp4\")\r\n\tos.remove(\"video.mp4\")\r\n\ttime.sleep(waittime- ((time.time() - starttime) % waittime))\r\n","sub_path":"TotoroXLofiBot.py","file_name":"TotoroXLofiBot.py","file_ext":"py","file_size_in_byte":5737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"154730870","text":"\n\n#calss header\nclass _PURSUIT():\n\tdef __init__(self,): \n\t\tself.name = \"PURSUIT\"\n\t\tself.definitions = [u'an activity that you spend time doing, usually when you are not working: ', u'the act of following someone or something to try to catch him, her, or it: ', u'the act of trying to achieve a plan, activity, or situation, usually over a long period of time: ']\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/_pursuit.py","file_name":"_pursuit.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"604573571","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport json\nfrom datetime import datetime\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import db\n\n\nclass TakealotSpider(scrapy.Spider):\n name = 'takealot'\n\n custom_settings = {\n 'ITEM_PIPELINES': {\n 'hifi_project.pipelines.TakealotProjectPipeline': 400,\n },\n\n # \"FEED_URI\": \"file:///users/takealot.csv\",\n }\n\n\n url = \"https://api.takealot.com/rest/v-1-9-1/searches/products,filters,facets,sort_options,breadcrumbs,slots_audience,context,seo?department_slug=computers&category_slug=components-26415&sort=Relevance\"\n\n \n def start_requests(self):\n yield scrapy.Request(self.url,self.parse)\n\n\n def parse(self, response):\n data = json.loads(response.body)\n\n for item in data.get(\"sections\").get(\"products\").get(\"results\"):\n yield {\n \"title\": item.get(\"product_views\").get(\"core\").get(\"title\"),\n \"brand\": item.get(\"product_views\").get(\"core\").get(\"brand\"),\n \"price\": item.get(\"product_views\").get(\"buybox_summary\").get(\"prices\"),\n # \"pretty_price\": item.get(\"product_views\").get(\"buybox_summary\").get(\"pretty_price\")[0],\n \"listing_price\": item.get(\"product_views\").get(\"buybox_summary\").get(\"listing_price\"),\n \"savings\": item.get(\"product_views\").get(\"buybox_summary\").get(\"saving\"),\n \"image_url\":item.get(\"product_views\").get(\"gallery\").get(\"images\")[0], #check takealot to see what can be put under size\n \"date\": str(datetime.now()),\n }\n\n \n next_page_code = data.get(\"sections\").get(\"products\").get(\"paging\").get(\"next_is_after\")\n\n if next_page_code != \"\":\n yield scrapy.Request(self.url + f\"&after={next_page_code}\", self.parse)\n\n\n \n\n","sub_path":"hifi_project/spiders/takealot.py","file_name":"takealot.py","file_ext":"py","file_size_in_byte":1865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"505060394","text":"alphabet = \"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz\"\r\nencrypt = input(\"Enter a clear message\")\r\nkey = int(input(\"Please enter a key (number from 1-25): \"))\r\nencrypted = \"\"\r\nfor letter in encrypt:\r\n position = alphabet.find(letter)\r\n newPosition = position + key\r\n if letter in alphabet:\r\n encrypted = encrypted + alphabet [newPosition]\r\n else:\r\n encrypted = encrypted + letter\r\nprint(\"Your clipher is: \", encrypted)\r\n\r\n","sub_path":"Desktop/lab vstup/шриф цезаря.py","file_name":"шриф цезаря.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"341144055","text":"\n\"\"\"\nThis program loads in the raw ACS files, creates the necessary variables\nfor the simulation and saves a master dataset to be used in the simulations.\n\n2 March 2018\nhautahi\n\nTo do:\n- The biggest missing piece is the imputation of ACS variables using the CPS. These are currently just randomly generated.\n- Check if the ACS variables are the same as those in the C++ code\n\n\"\"\"\n\n# -------------------------- #\n# Housekeeping\n# -------------------------- #\n\nimport pandas as pd\nimport numpy as np\n\n# -------------------------- #\n# ACS Household File\n# -------------------------- #\n\n# Load data\nd_hh = pd.read_csv(\"./data/ss15hma_short.csv\")\n\n# Create Variables\nd_hh[\"nochildren\"] = pd.get_dummies(d_hh[\"FPARC\"])[4]\nd_hh[\"lnfaminc\"] = np.log(d_hh[\"FINCP\"])\n\n# -------------------------- #\n# ACS Personal File\n# -------------------------- #\n\n# Load data\nd = pd.read_csv(\"./data/ss15pma_short.csv\")\n\n# Merge with the household level variables\nd = pd.merge(d,d_hh[['SERIALNO', 'nochildren', 'lnfaminc']],\n on='SERIALNO')\n\n# Rename ACS variables to be consistent with FMLA data\nrename_dic = {'AGEP': 'age'}\nd.rename(columns=rename_dic, inplace=True)\n\n# duplicating age column for meshing with CPS estimate output\nd['a_age']=d['age']\n\n# Create new ACS Variables\nd[\"widowed\"] = pd.get_dummies(d[\"MAR\"])[2]\nd[\"divorced\"] = pd.get_dummies(d[\"MAR\"])[3]\nd[\"separated\"] = pd.get_dummies(d[\"MAR\"])[4]\nd[\"nevermarried\"] = pd.get_dummies(d[\"MAR\"])[5]\nd[\"male\"] = pd.get_dummies(d[\"SEX\"])[1]\nd[\"female\"] = 1 - d[\"male\"]\nd[\"agesq\"] = d[\"age\"]**2\n\n# Educational level\nd['lths'] = np.where(d['SCHL']<=15,1,0)\nd['somcol'] = np.where((d['SCHL']>=18) & (d['SCHL']<=20),1,0)\nd[\"ba\"] = np.where(d['SCHL']==21,1,0)\nd[\"baplus\"] = np.where(d['SCHL']>=21,1,0)\nd[\"maplus\"] = np.where(d['SCHL']>=22,1,0)\n\n# race\nd['black']= d.loc[d['RAC1P']==2, 'RAC1P']\nd['asian']= d.loc[d['RAC1P']==6, 'RAC1P']\nd['other race']= d.loc[d['RAC1P']!=1, 'RAC1P']\nd['hispanic']= d.loc[d['HISP']>1, 'HISP']\n\n# Occupation\nd['occ_1']=0\nd['occ_2']=0\nd['occ_3']=0\nd['occ_4']=0\nd['occ_5']=0\nd['occ_6']=0\nd['occ_7']=0\nd['occ_8']=0\nd['occ_9']=0\nd['occ_10']=0\nd['maj_occ']=0\nd.loc[(d['OCCP10']>=10) & (d['OCCP10']<=950), 'occ_1'] =1\nd.loc[(d['OCCP10']>=1000) & (d['OCCP10']<=3540), 'occ_2'] =1\nd.loc[(d['OCCP10']>=3600) & (d['OCCP10']<=4650), 'occ_3'] =1\nd.loc[(d['OCCP10']>=4700) & (d['OCCP10']<=4965), 'occ_4'] =1\nd.loc[(d['OCCP10']>=5000) & (d['OCCP10']<=5940), 'occ_5'] =1\nd.loc[(d['OCCP10']>=6000) & (d['OCCP10']<=6130), 'occ_6'] =1\nd.loc[(d['OCCP10']>=6200) & (d['OCCP10']<=6940), 'occ_7'] =1\nd.loc[(d['OCCP10']>=7000) & (d['OCCP10']<=7630), 'occ_8'] =1\nd.loc[(d['OCCP10']>=7700) & (d['OCCP10']<=8965), 'occ_9'] =1\nd.loc[(d['OCCP10']>=9000) & (d['OCCP10']<=9750), 'occ_10'] =1\n\n# Industry\nd['ind_1']=0\nd['ind_2']=0\nd['ind_3']=0\nd['ind_4']=0\nd['ind_5']=0\nd['ind_6']=0\nd['ind_7']=0\nd['ind_8']=0\nd['ind_9']=0\nd['ind_10']=0\nd['ind_11']=0\nd['ind_12']=0\nd['ind_13']=0\nd.loc[(d['INDP']>=170) & (d['INDP']<=290), 'ind_1'] =1\nd.loc[(d['INDP']>=370) & (d['INDP']<=490), 'ind_2'] =1\nd.loc[(d['INDP']==770), 'ind_3'] =1\nd.loc[(d['INDP']>=1070) & (d['INDP']<=3990), 'ind_4'] =1\nd.loc[(d['INDP']>=4070) & (d['INDP']<=5790), 'ind_5'] =1\nd.loc[((d['INDP']>=6070) & (d['INDP']<=6390))|((d['INDP']>=570) & (d['INDP']<=690)), 'ind_6'] =1\nd.loc[(d['INDP']>=6470) & (d['INDP']<=6780), 'ind_7'] =1\nd.loc[(d['INDP']>=6870) & (d['INDP']<=7190), 'ind_8'] =1\nd.loc[(d['INDP']>=7270) & (d['INDP']<=7790), 'ind_9'] =1\nd.loc[(d['INDP']>=7860) & (d['INDP']<=8470), 'ind_10'] =1\nd.loc[(d['INDP']>=8560) & (d['INDP']<=8690), 'ind_11'] =1\nd.loc[(d['INDP']>=8770) & (d['INDP']<=9290), 'ind_12'] =1\nd.loc[(d['INDP']>=9370) & (d['INDP']<=9590), 'ind_13'] =1\n\n# -------------------------- #\n# Remove ineligible workers\n# -------------------------- #\n\n# Restrict dataset to civilian employed workers (check this)\nd = d[(d['ESR'] == 1) | (d['ESR'] == 2)]\n\n# Restrict dataset to those that are not self-employed\nd = d[(d['COW'] != 6) & (d['COW'] != 7)]\n\n# -------------------------- #\n# CPS Imputation\n# -------------------------- #\n\n\"\"\"\nNot all the required behavioral independent variables are available\nwithin the ACS. These therefore need to be imputed CPS\n\nd[\"weeks_worked\"] = \nd[\"weekly_earnings\"] = \n\"\"\"\n\n# These are just randomly generated placeholders for now\nd[\"coveligd\"] = np.random.randint(2, size=d.shape[0])\n\n# adding in the prhourly worker imputation\n# Double checked C++ code, and confirmed this is how they did hourly worker imputation.\nhr_est=pd.read_csv('estimates/CPS_paid_hrly.csv').set_index('var').to_dict()['est']\nd['prhourly']=0\nfor dem in hr_est.keys():\n if dem!='intercept':\n d['prhourly']+=d[dem].fillna(0)*hr_est[dem]\nd['prhourly']+=hr_est['intercept']\nd['prhourly']=np.exp(d['prhourly'])/(1+np.exp(d['prhourly']))\nd['rand']=pd.Series(np.random.rand(d.shape[0]), index=d.index)\nd['hourly']= np.where(d['prhourly']>d['rand'],1,0)\nd=d.drop('rand', axis=1)\n\n# -------------------------- #\n# Save the resulting dataset\n# -------------------------- #\n\nd.to_csv(\"./data/ACS_cleaned_forsimulation.csv\", index=False, header=True)\n","sub_path":"4.clean_ACS.py","file_name":"4.clean_ACS.py","file_ext":"py","file_size_in_byte":5148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"3242683","text":"from django.shortcuts import render\nfrom django.template.response import HttpResponse\nimport braintree\nfrom django.conf import settings\nfrom django.http import JsonResponse\n# Create your views here.\n\n\n\ndef index(request):\n\n return render(request, 'index.html')\n\n\ndef checkout(request):\n price = request.GET.get(\"price\",\"\")\n print(price)\n #generate all other required data that you may need on the #checkout page and add them to context. \n if settings.BRAINTREE_PRODUCTION:\n braintree_env = braintree.Environment.Production\n else:\n braintree_env = braintree.Environment.Sandbox\n\n # Configure Braintree\n braintree.Configuration.configure(\n braintree_env,\n merchant_id=settings.BRAINTREE_MERCHANT_ID,\n public_key=settings.BRAINTREE_PUBLIC_KEY,\n private_key=settings.BRAINTREE_PRIVATE_KEY,\n )\n \n try:\n braintree_client_token = braintree.ClientToken.generate({ \"customer_id\": user.id })\n except:\n braintree_client_token = braintree.ClientToken.generate({})\n\n context = {\n 'braintree_client_token': braintree_client_token,\n 'price':price,\n }\n return render(request, 'checkout.html', context)\n\n\n\ndef payment(request):\n price= request.POST.get('price','')\n nonce_from_the_client = request.POST['paymentMethodNonce']\n customer_kwargs = {\n \"first_name\": request.user.first_name,\n \"last_name\": request.user.last_name,\n \"email\": request.user.email,\n }\n customer_create = braintree.Customer.create(customer_kwargs)\n customer_id = customer_create.customer.id\n result = braintree.Transaction.sale({\n \"amount\": price,\n \"payment_method_nonce\": nonce_from_the_client,\n \"options\": {\n \"submit_for_settlement\": True\n }\n })\n print(result)\n return JsonResponse({'message':1})","sub_path":"payment_gateway/payment_gateway/payment_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"379666346","text":"import asyncio\nimport collections\nimport contextlib\nimport datetime\nimport io\nimport math\nimport os\nimport sys\nimport textwrap\nimport traceback\nimport typing\nfrom contextlib import redirect_stdout\n\n\nimport discord\nimport mystbin\nimport tabulate\nimport utils.json_loader\nfrom discord.ext import commands, flags\nfrom jishaku.models import copy_context_with\nfrom jishaku.modules import package_version\nfrom utils.chat_formatting import box, hyperlink\nfrom utils.useful import *\ntry:\n import psutil\nexcept ImportError:\n psutil = None\nimport humanize\n\nCommandTask = collections.namedtuple(\"CommandTask\", \"index ctx task\")\n\n\nclass admin(commands.Cog):\n \"\"\"admin-only commands that make the bot dynamic.\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n self._last_result = None\n self.sessions = set()\n self.task_count: int = 0\n self.tasks = collections.deque()\n\n @staticmethod\n def cleanup_code(content):\n \"\"\"Automatically removes code blocks from the code.\"\"\"\n\n if content.startswith('```') and content.endswith('```'):\n return '\\n'.join(content.split('\\n')[1:-1])\n\n\n return content.strip('` \\n')\n\n async def cog_check(self, ctx):\n return await self.bot.is_owner(ctx.author)\n\n @contextlib.contextmanager\n def submit(self, ctx: commands.Context):\n \"\"\"\n A context-manager that submits the current task to jishaku's task list\n and removes it afterwards.\n\n Parameters\n -----------\n ctx: commands.Context\n A Context object used to derive information about this command task.\n \"\"\"\n\n self.task_count += 1\n\n if sys.version_info < (3, 7, 0):\n cmdtask = CommandTask(self.task_count, ctx, asyncio.Task.current_task()) \n try:\n current_task = asyncio.current_task()\n except RuntimeError:\n current_task = None\n\n cmdtask = CommandTask(self.task_count, ctx, current_task)\n\n self.tasks.append(cmdtask)\n\n try:\n yield cmdtask\n finally:\n if cmdtask in self.tasks:\n self.tasks.remove(cmdtask)\n\n @staticmethod\n def clean_code(content):\n if content.startswith(\"```\") and content.endswith(\"```\"):\n return \"\\n\".join(content.split(\"\\n\")[1:][:-3])\n\n\n \n @commands.group(name=\"mod\", invoke_without_command=True, case_insensitive=True)\n @commands.is_owner()\n async def mod(self, ctx):\n cmd = self.bot.get_command(\"help\")\n await ctx.invoke(cmd, command=\"mod\")\n\n @mod.command(name=\"blacklist\", hidden=True, aliases=[\"bl\", \"poo\"])\n async def _blacklist(self, ctx, target: typing.Union[discord.User, discord.Guild], *, mode:str=\"add\"):\n \n if mode != 'remove' and mode != 'add':\n return await ctx.send(f\"{self.bot.redTick} Accepted values are `add/remove` for `mode`\")\n \n target_type = \"user\" if isinstance(target, discord.User) else \"guild\"\n\n blacklist = \"TRUE\" if mode == 'add' else \"FALSE\"\n query = 'UPDATE users_data SET blacklisted = ? WHERE user_id = ?' if target_type == \"user\" else 'UPDATE guild_config SET blacklisted = ? WHERE guild_id = ?'\n\n cur = await self.bot.db.execute(query, (blacklist, target.id))\n if mode == \"add\":\n msg = f\"**{target.name}** now got blacklisted! bad bad bad\"\n self.bot.blacklist.add(target.id)\n else:\n msg = f\"**{target.name}** now got unblacklisted! phew...\"\n try:\n self.bot.blacklist.remove(target.id)\n except KeyError:\n msg = f\"{target.name} is not blacklisted!\"\n \n await ctx.send(msg)\n \n\n @mod.command(name=\"givepremium\", hidden=True, aliases=[\"givep\"])\n async def _givepremium(self, ctx, target: typing.Union[discord.User, discord.Guild], *, mode:str=\"add\"):\n \n if mode != 'remove' and mode != 'add':\n return await ctx.send(f\"{self.bot.redTick} Accepted values are `add/remove` for `mode`\")\n \n target_type = \"user\" if isinstance(target, discord.User) else \"guild\"\n\n premium = \"TRUE\" if mode == 'add' else \"FALSE\"\n query = 'UPDATE users_data SET premium = ? WHERE user_id = ?' if target_type == \"user\" else 'UPDATE guild_config SET premium = ? WHERE guild_id = ?'\n\n cur = await self.bot.db.execute(query, (premium, target.id))\n if mode == \"add\":\n msg = f\"<:Boosters:814930829461553152> **{target.name}** now got premium perks!\"\n self.bot.premiums.add(target.id)\n else:\n msg = f\"<:Boosters:814930829461553152> **{target.name}** got their premium removed. oof...\"\n try:\n self.bot.premiums.remove(target.id)\n except KeyError:\n msg = f\"{target.name} is not premium!\"\n\n await ctx.send(msg)\n \n @mod.command(name=\"edit\")\n async def _edit_(self, ctx, action, user: typing.Union[discord.Member, discord.User], amount:int):\n self.bot.cached_users[user.id][action] += amount\n return await ctx.send(f\"{self.bot.greenTick} Successfully gave {user.mention} {amount:,} `{action}`.\")\n \n @mod.command(name=\"create\")\n async def _create_item_for_shop(self, ctx):\n q = [\n \"What should the item be called?\", \n \"What should it's price be?\", \n \"Write a brief description of the item.\", \n \"Write a long and detailed description of the item.\", \n \"Give it an ID.\"\n ]\n \n a = []\n for question in q:\n question += \"\\nType `stop` to stop this process. Timeout is 300 seconds.\"\n await ctx.send(question)\n try:\n response = await self.bot.wait_for('message', timeout=300, check=lambda m: m.author == ctx.author and m.channel == ctx.channel)\n except asyncio.TimeoutError:\n await ctx.reply(\"Okay, I'm leaving. Bye.\")\n else:\n if response.content.lower() == \"stop\":\n return await ctx.send(\"Terminated\")\n a.append(response.content)\n \n query = \"\"\"\n INSERT INTO item_info\n VALUES (?,?,?,?,?)\n \"\"\"\n await self.bot.db.execute(query, (a[4], a[1], a[0], a[3], a[2]))\n await self.bot.db.commit()\n cmd = self.bot.get_command(\"shop\")\n return await ctx.invoke(cmd, item=a[0])\n \n @mod.command(name=\"delete\")\n async def _delete_item_from_shop(self, ctx, *, item):\n item = item.lower()\n query = \"\"\"\n DELETE FROM item_info\n WHERE lower(item_name) = ?\n \"\"\"\n await self.bot.db.execute(query, (item,))\n await self.bot.db.commit()\n return await ctx.send(f\"{self.bot.greenTick} Deleted item `{item}` from shop.\")\n \n @commands.group(invoke_without_command=True, case_insensitive=True)\n async def dev(self, ctx):\n return\n\n @staticmethod\n async def run_shell(code: str) -> bytes:\n proc = await asyncio.create_subprocess_shell(\n code,\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE\n )\n\n stdout, stderr = await proc.communicate()\n\n if stdout:\n stdout = f\"```$ {code}\\n{stdout.decode()}```\"\n if stderr:\n stderr = f\"```$ {code}\\n{stdout.decode()}```\"\n\n return stderr if stderr else stdout\n\n @dev.command(name='update')\n async def _update(self, ctx, link: str, *, message: str):\n await ctx.send(\"Are you sure you want update me? `(y/n)`\")\n\n msg = await self.bot.wait_for('message', timeout=10, check=lambda m: m.author == ctx.author)\n if msg.content.lower() == 'y':\n async with ctx.typing():\n data = utils.json_loader.read_json('updates')\n data['upDATE'] = str(datetime.datetime.utcnow())\n data['update'] = message\n data['link'] = link\n utils.json_loader.write_json(data, 'updates')\n\n @dev.command(name='eval')\n async def _eval(self, ctx, *, code: str):\n \"\"\"Evaluates a code\"\"\"\n\n env = {\n 'bot': self.bot,\n 'ctx': ctx,\n 'channel': ctx.channel,\n 'author': ctx.author,\n 'guild': ctx.guild,\n 'message': ctx.message,\n '_': self._last_result\n }\n\n env.update(globals())\n\n code = self.cleanup_code(code)\n stdout = io.StringIO()\n\n to_compile = f'async def func():\\n{textwrap.indent(code, \" \")}'\n\n try:\n exec(to_compile, env)\n except Exception as e:\n emb = Embed(title='', description=\"Evaluated your code\", color=0x2F3136)\n emb.add_field(name=\"Output:\", value=f'```py\\n{e.__class__.__name__}: {e}\\n```')\n return await ctx.send(embed=emb)\n\n func = env['func']\n try:\n with redirect_stdout(stdout):\n self.bot.ret = await func()\n except Exception:\n self.bot.value = stdout.getvalue()\n emb = Embed(title='', description=\"Evaluated your code\", color=0x2F3136)\n emb.add_field(name=\"Output:\", value=f'```py\\n{self.bot.value}{traceback.format_exc()}\\n```')\n return await ctx.send(embed=emb)\n\n else:\n self.bot.value = stdout.getvalue()\n try:\n await ctx.message.add_reaction('\\u2705')\n except:\n pass\n\n if self.bot.ret is None:\n if self.bot.value:\n emb = Embed(title='', description=\"Evaluated your code\", color=0x2F3136)\n emb.add_field(name=\"Output:\", value=f'```py\\n{self.bot.value}\\n```')\n return await ctx.send(embed=emb)\n\n else:\n self._last_result = self.bot.ret\n emb = Embed(title='', description=\"Evaluated your code\", color=0x2F3136)\n emb.add_field(name=\"Output:\", value=f'```py\\n{self.bot.value}{self.bot.ret}\\n```')\n return await ctx.send(embed=emb)\n\n @_eval.error\n async def _eval_error(self, ctx, error):\n if isinstance(error, commands.CommandInvokeError):\n error = getattr(error, 'original', error)\n if error.code == 50035:\n output = self.bot.value + self.bot.ret if self.bot.ret else self.bot.value\n mystbin_client = mystbin.Client()\n paste = await mystbin_client.post(f\"{output}\", syntax=\"python\")\n await mystbin_client.close()\n em = Embed(color=0x2F3136)\n em.add_field(name=\"Output:\", value=f\"{box(output[0:10] + '... # Truncated', 'py')}\")\n em.add_field(name=\"Your output was too long!\\n\",\n value=f\"I pasted your output {hyperlink('here', paste)}\",\n inline=False)\n em.set_author(name=\"Evaluated your code!\")\n await ctx.send(embed=em)\n\n\n @dev.command(name='guilds')\n async def _guilds(self, ctx, page:int=1):\n GUILDSa = self.bot.guilds\n alist = []\n for GUILDS in GUILDSa:\n alist.append(self.bot.get_guild(GUILDS.id))\n\n alist = [(guild.name, guild.id, guild.owner_id, len(guild.members)) for i, guild in enumerate(alist)]\n alist = sorted(alist, key=lambda guild: guild[3], reverse=True)\n\n page = page\n\n items_per_page = 5\n pages = math.ceil(len(alist) / items_per_page)\n\n start = (page - 1) * items_per_page\n end = start + items_per_page\n\n queue = ''\n embed = (Embed(description='**Servers [{}]**\\n\\n{}'.format(len(GUILDSa), queue),\n color=0x2F3136)\n .set_footer(text='Viewing page {}/{}'.format(page, pages),\n icon_url=self.bot.user.avatar_url)\n .set_author(name=f\"{ctx.author}\", icon_url=f\"{ctx.author.avatar_url}\")\n )\n\n for i, guild in enumerate(alist[start:end], start=start):\n owner = await self.bot.fetch_user(int(guild[2]))\n owner = owner.mention\n embed.add_field(name=f'{guild[0]}\\n',\n value=f'Members: {guild[3]:,}\\nGuild ID: `{guild[1]}`\\nOwner: {owner}\\n\\n', inline=False)\n msg = await ctx.send(embed=embed)\n\n @dev.command(name='inviteme')\n async def _inviteme(self, ctx, *, guildid: int):\n guild = self.bot.get_guild(guildid)\n await ctx.author.send(f\"{await guild.text_channels[0].create_invite()}\")\n\n @dev.command(name='sync')\n async def _sync(self, ctx, extension: str = None):\n fail = ''\n\n if extension is None:\n async with ctx.typing():\n for file in os.listdir(f\"{self.bot.cwd}/cogs\"):\n if file.endswith(\".py\"):\n try:\n self.bot.reload_extension(f\"cogs.{file[:-3]}\")\n except discord.ext.commands.ExtensionNotLoaded as e:\n fail += f'```diff\\n- {e.name} is not loaded```'\n except discord.ext.commands.ExtensionFailed as e:\n exc_info = type(e), e.original, e.__traceback__\n etype, value, trace = exc_info\n traceback_content = \"\".join(traceback.format_exception(etype, value, trace, 10)).replace(\n \"``\", \"`\\u200b`\")\n fail += (f'```diff\\n- {e.name} failed to reload.```' + f'```py\\n{traceback_content}```')\n\n if fail == '':\n em = Embed(color=0x3CA374)\n em.add_field(name=f\"{self.bot.greenTick} Cogs Reloading\",\n value=\"```diff\\n+ All cogs were reloaded successfully```\")\n\n await ctx.reply(embed=em, mention_author=False)\n else:\n em = Embed(color=0xFFCC33)\n em.add_field(name=\"<:idle:817035319165059102> \"\n \"**Failed to reload all cogs**\",\n value=fail\n )\n await ctx.reply(embed=em, mention_author=False)\n\n else:\n try:\n self.bot.reload_extension(f\"cogs.{extension}\")\n em = Embed(description=f\"{self.bot.greenTick} \"\n f\"**Reloaded cogs.{extension}**\",\n color=0x3CA374)\n\n await ctx.reply(embed=em, mention_author=False)\n\n except discord.ext.commands.ExtensionFailed as e:\n exc_info = type(e), e.original, e.__traceback__\n etype, value, trace = exc_info\n traceback_content = \"\".join(traceback.format_exception(etype, value, trace, 10)).replace(\"``\",\n \"`\\u200b`\")\n\n em = Embed(color=0xF04D4B)\n em.add_field(name=f\"{self.bot.redTick} \"\n f\"Failed to reload {e.name}\",\n value=f\"```py\\n{traceback_content}```\")\n await ctx.reply(embed=em, mention_author=False)\n\n\n @dev.command(name=\"sudo\")\n async def _sudo(self, ctx: commands.Context, *, command_string: str):\n \"\"\"\n Run a command bypassing all checks and cooldowns.\n\n This also bypasses permission checks so this has a high possibility of making commands raise exceptions.\n \"\"\"\n\n alt_ctx = await copy_context_with(ctx, content=ctx.prefix + command_string)\n\n if alt_ctx.command is None:\n return await ctx.send(f'Command \"{alt_ctx.invoked_with}\" is not found')\n\n return await alt_ctx.command.reinvoke(alt_ctx)\n\n @dev.command(name=\"reload\")\n async def _reloadmodule(self, ctx, *, module:str):\n cmd = self.bot.get_command(\"dev eval\")\n await ctx.invoke(cmd, code=\n \"import imp\\n\"\n f\"import {module}\\n\"\n f\"print(imp.reload({module}))\")\n\n @dev.command()\n async def tables(self, ctx):\n cmd = self.bot.get_command(\"dev sql\")\n await ctx.invoke(cmd, query=\"SELECT name FROM sqlite_master WHERE type ='table' AND name NOT LIKE 'sqlite_%';\")\n \n @dev.command()\n async def sql(self, ctx, *, query: str):\n async with self.bot.db.execute(query) as cur:\n await self.bot.db.commit()\n if cur.description:\n \tcolumns = [tuple[0] for tuple in cur.description]\n else:\n columns = \"keys\"\n thing = await cur.fetchall()\n if len(thing) == 0:\n return await ctx.message.add_reaction(f'{self.bot.greenTick}')\n thing = tabulate.tabulate(thing, headers=columns, tablefmt='psql')\n byte = io.BytesIO(str(thing).encode('utf-8'))\n return await ctx.send(file=discord.File(fp=byte, filename='table.txt'))\n \n @sql.error\n async def sql_error(self, ctx, error):\n if isinstance(error, commands.CommandInvokeError):\n await ctx.message.add_reaction(f'{self.bot.redTick}')\n await ctx.send(str.capitalize(str(error.original)))\n\n @commands.command(name='delete',aliases=['del','d'])\n async def delete_bot_message(self,ctx):\n try:\n message = ctx.channel.get_partial_message(ctx.message.reference.message_id)\n except AttributeError:\n await ctx.message.add_reaction('❌') \n return \n try:\n await message.delete()\n await ctx.message.add_reaction('✅')\n except discord.Forbidden:\n await ctx.message.add_reaction('❌')\n \n @commands.command(name=\"close\")\n async def _close(self, ctx):\n await self.bot.logout()\n for user in self.bot.cached_users:\n query = \"UPDATE currency_data SET wallet = ?, bank = ?, max_bank = ?, boost = ?, exp = ?, lvl = ? WHERE user_id = ?\"\n await self.bot.db.execute(query, (self.bot.cached_users[user]['wallet'], self.bot.cached_users[user]['bank'], self.bot.cached_users[user]['max_bank'], round(self.bot.cached_users[user]['boost'], 2), self.bot.cached_users[user]['exp'], self.bot.cached_users[user]['lvl'], user))\n\n await self.bot.db.commit()\n \n \ndef setup(bot):\n bot.add_cog(admin(bot))\n","sub_path":"main/cogs/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":18583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"413399756","text":"from os.path import join, dirname\r\nfrom ovos_workshop.skills.common_play import OVOSCommonPlaybackSkill, common_play_search\r\nfrom ovos_workshop.frameworks.playback import CommonPlayMediaType, CommonPlayPlaybackType, \\\r\n CommonPlayMatchConfidence\r\nfrom ovos_utils.parse import fuzzy_match, MatchStrategy\r\n\r\nfrom youtube_searcher import search_youtube\r\n\r\n\r\nclass SimpleYoutubeSkill(OVOSCommonPlaybackSkill):\r\n def __init__(self):\r\n super(SimpleYoutubeSkill, self).__init__(\"Simple Youtube\")\r\n self.supported_media = [CommonPlayMediaType.GENERIC,\r\n CommonPlayMediaType.MUSIC,\r\n CommonPlayMediaType.PODCAST,\r\n CommonPlayMediaType.DOCUMENTARY,\r\n CommonPlayMediaType.VIDEO]\r\n self._search_cache = {}\r\n self.skill_icon = join(dirname(__file__), \"ui\", \"ytube.jpg\")\r\n if \"fallback_mode\" not in self.settings:\r\n self.settings[\"fallback_mode\"] = False\r\n if \"audio_only\" not in self.settings:\r\n self.settings[\"audio_only\"] = False\r\n if \"video_only\" not in self.settings:\r\n self.settings[\"video_only\"] = True\r\n\r\n # common play\r\n @common_play_search()\r\n def search_youtube(self, phrase, media_type=CommonPlayMediaType.GENERIC):\r\n \"\"\"Analyze phrase to see if it is a play-able phrase with this skill.\r\n\r\n Arguments:\r\n phrase (str): User phrase uttered after \"Play\", e.g. \"some music\"\r\n media_type (CommonPlayMediaType): requested CPSMatchType to search for\r\n\r\n Returns:\r\n search_results (list): list of dictionaries with result entries\r\n {\r\n \"match_confidence\": CommonPlayMatchConfidence.HIGH,\r\n \"media_type\": CPSMatchType.MUSIC,\r\n \"uri\": \"https://audioservice.or.gui.will.play.this\",\r\n \"playback\": CommonPlayPlaybackType.VIDEO,\r\n \"image\": \"http://optional.audioservice.jpg\",\r\n \"bg_image\": \"http://optional.audioservice.background.jpg\"\r\n }\r\n \"\"\"\r\n # match the request media_type\r\n base_score = 0\r\n if media_type == CommonPlayMediaType.MUSIC:\r\n base_score += 15\r\n elif media_type == CommonPlayMediaType.VIDEO:\r\n base_score += 25\r\n\r\n explicit_request = False\r\n if self.voc_match(phrase, \"youtube\"):\r\n # explicitly requested youtube\r\n base_score += 50\r\n phrase = self.remove_voc(phrase, \"youtube\")\r\n explicit_request = True\r\n\r\n # playback_type defines if results should be VIDEO / AUDIO / AUDIO + VIDEO\r\n # this could be done at individual match level instead if needed\r\n if media_type == CommonPlayMediaType.AUDIO or not self.gui.connected:\r\n playback = [CommonPlayPlaybackType.AUDIO]\r\n elif media_type != CommonPlayMediaType.VIDEO:\r\n playback = [CommonPlayPlaybackType.VIDEO,\r\n CommonPlayPlaybackType.AUDIO]\r\n else:\r\n playback = [CommonPlayPlaybackType.VIDEO]\r\n\r\n # search youtube, cache results for speed in repeat queries\r\n if phrase in self._search_cache:\r\n results = self._search_cache[phrase]\r\n else:\r\n try:\r\n results = search_youtube(phrase)[\"videos\"]\r\n except Exception as e:\r\n # youtube can break at any time... they also love AB testing\r\n # often only some queries will break...\r\n self.log.error(\"youtube search failed!\")\r\n self.log.exception(e)\r\n return []\r\n self._search_cache[phrase] = results\r\n\r\n # filter results\r\n def parse_duration(video):\r\n # parse duration into (int) seconds\r\n # {'length': '3:49'\r\n if not video.get(\"length\"):\r\n return 0\r\n length = 0\r\n nums = video[\"length\"].split(\":\")\r\n if len(nums) == 1 and nums[0].isdigit():\r\n # seconds\r\n length = int(nums[0])\r\n elif len(nums) == 2:\r\n # minutes : seconds\r\n length = int(nums[0]) * 60 + \\\r\n int(nums[0])\r\n elif len(nums) == 3:\r\n # hours : minutes : seconds\r\n length = int(nums[0]) * 60 * 60 + \\\r\n int(nums[0]) * 60 + \\\r\n int(nums[0])\r\n # better-common_play expects milliseconds\r\n return length * 1000\r\n\r\n def is_music(match):\r\n return self.voc_match(match[\"title\"], \"music\")\r\n\r\n def is_podcast(match):\r\n # lets require duration above 30min to exclude trailers and such\r\n dur = parse_duration(match) / 1000 # convert ms to seconds\r\n if dur < 30 * 60:\r\n return False\r\n return self.voc_match(match[\"title\"], \"podcast\")\r\n\r\n def is_documentary(match):\r\n # lets require duration above 20min to exclude trailers and such\r\n dur = parse_duration(match) / 1000 # convert ms to seconds\r\n if dur < 20 * 60:\r\n return False\r\n return self.voc_match(match[\"title\"], \"documentary\")\r\n\r\n if media_type == CommonPlayMediaType.MUSIC:\r\n # only return videos assumed to be music\r\n # music.voc contains things like \"full album\" and \"music\"\r\n # if any of these is present in the title, the video is valid\r\n results = [r for r in results if is_music(r)]\r\n\r\n if media_type == CommonPlayMediaType.PODCAST:\r\n # only return videos assumed to be podcasts\r\n # podcast.voc contains things like \"podcast\"\r\n results = [r for r in results if is_podcast(r)]\r\n\r\n if media_type == CommonPlayMediaType.DOCUMENTARY:\r\n # only return videos assumed to be documentaries\r\n # podcast.voc contains things like \"documentary\"\r\n results = [r for r in results if is_documentary(r)]\r\n\r\n # score\r\n def calc_score(match, idx=0):\r\n # idx represents the order from youtube\r\n score = base_score - idx * 5 # - 5% as we go down the results list\r\n\r\n # this will give score of 100 if query is included in video title\r\n score += 100 * fuzzy_match(\r\n phrase.lower(), match[\"title\"].lower(),\r\n strategy=MatchStrategy.TOKEN_SET_RATIO)\r\n\r\n # small penalty to not return 100 and allow better disambiguation\r\n if media_type == CommonPlayMediaType.GENERIC:\r\n score -= 10\r\n if score >= 100:\r\n if media_type == CommonPlayMediaType.AUDIO:\r\n score -= 20 # likely don't want to answer most of these\r\n elif media_type != CommonPlayMediaType.VIDEO:\r\n score -= 10\r\n elif media_type == CommonPlayMediaType.MUSIC and not is_music(match):\r\n score -= 5\r\n\r\n # youtube gives pretty high scores in general, so we allow it\r\n # to run as fallback mode, which assigns lower scores and gives\r\n # preference to matches from other skills\r\n if self.settings[\"fallback_mode\"]:\r\n if not explicit_request:\r\n score -= 25\r\n return min(100, score)\r\n\r\n matches = []\r\n if self.settings[\"audio_only\"]:\r\n matches += [{\r\n \"match_confidence\": calc_score(r, idx),\r\n \"media_type\": CommonPlayMediaType.VIDEO,\r\n \"length\": parse_duration(r),\r\n \"uri\": r[\"url\"],\r\n \"playback\": CommonPlayPlaybackType.AUDIO,\r\n \"image\": r[\"thumbnails\"][-1][\"url\"].split(\"?\")[0],\r\n \"bg_image\": r[\"thumbnails\"][-1][\"url\"].split(\"?\")[0],\r\n \"skill_icon\": self.skill_icon,\r\n \"skill_logo\": self.skill_icon, # backwards compat\r\n \"title\": r[\"title\"] + \" (audio only)\",\r\n \"skill_id\": self.skill_id\r\n } for idx, r in enumerate(results)]\r\n else:\r\n matches += [{\r\n \"match_confidence\": calc_score(r, idx),\r\n \"media_type\": CommonPlayMediaType.VIDEO,\r\n \"length\": parse_duration(r),\r\n \"uri\": r[\"url\"],\r\n \"playback\": CommonPlayPlaybackType.VIDEO,\r\n \"image\": r[\"thumbnails\"][-1][\"url\"].split(\"?\")[0],\r\n \"bg_image\": r[\"thumbnails\"][-1][\"url\"].split(\"?\")[0],\r\n \"skill_icon\": self.skill_icon,\r\n \"skill_logo\": self.skill_icon, # backwards compat\r\n \"title\": r[\"title\"],\r\n \"skill_id\": self.skill_id\r\n } for idx, r in enumerate(results)]\r\n\r\n if not self.settings[\"video_only\"]:\r\n # add audio only duplicate results\r\n matches += [{\r\n \"match_confidence\": calc_score(r, idx) - 1,\r\n \"media_type\": CommonPlayMediaType.VIDEO,\r\n \"length\": parse_duration(r),\r\n \"uri\": r[\"url\"],\r\n \"playback\": CommonPlayPlaybackType.AUDIO,\r\n \"image\": r[\"thumbnails\"][-1][\"url\"].split(\"?\")[0],\r\n \"bg_image\": r[\"thumbnails\"][-1][\"url\"].split(\"?\")[0],\r\n \"skill_icon\": self.skill_icon,\r\n \"skill_logo\": self.skill_icon, # backwards compat\r\n \"title\": r[\"title\"] + \" (audio only)\",\r\n \"skill_id\": self.skill_id\r\n } for idx, r in enumerate(results)]\r\n\r\n return matches\r\n\r\n\r\ndef create_skill():\r\n return SimpleYoutubeSkill()\r\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"589667629","text":"import environments.envs as envs \nimport policies.ind.cem as cem\nimport argparse\nimport torch\nimport torch.nn.functional as F\nimport math\nimport utils\nimport numpy as np\nfrom collections import deque\nimport csv\nimport os\n\n\nclass Trainer:\n def __init__(self, env_name, params):\n self.env_name = env_name\n self.env = envs.make(env_name)\n self.action_bound = self.env.action_bound[1]\n\n self.iterations = params[\"iterations\"]\n self.gamma = params[\"gamma\"]\n self.seed = params[\"seed\"]\n self.pop_size = params[\"pop_size\"]\n self.elite_frac = params[\"elite_frac\"]\n self.sigma = params[\"sigma\"]\n self.render = params[\"render\"]\n self.log_interval = params[\"log_interval\"]\n self.save = params[\"save\"]\n\n state_dim = self.env.observation_space\n action_dim = self.env.action_space\n hidden_dim = params[\"hidden_dim\"]\n cuda = params[\"cuda\"]\n\n self.agent = cem.CEM(state_dim, hidden_dim, action_dim, GPU=cuda)\n\n if cuda:\n self.Tensor = torch.cuda.FloatTensor\n self.agent = self.agent.cuda()\n else:\n self.Tensor = torch.Tensor\n \n if self.render:\n self.env.init_rendering()\n \n # initialize experiment logging\n self.logging = params[\"logging\"]\n if self.logging:\n directory = os.getcwd()\n filename = directory + \"/data/cem.csv\"\n with open(filename, \"w\") as csvfile:\n self.writer = csv.writer(csvfile)\n self.writer.writerow([\"episode\", \"reward\"])\n self.train()\n else:\n self.train()\n\n def train(self):\n def evaluate(weights, rend):\n self.agent.set_weights(weights)\n episode_return = 0.0\n state = self.env.reset()\n if rend:\n self.env.render()\n for t in range(self.env.H):\n state = self.Tensor(state)\n action = self.agent(state)\n state, reward, done, _ = self.env.step(action*self.action_bound)\n if rend:\n self.env.render()\n episode_return += reward*math.pow(self.gamma, t)\n if done:\n break\n return episode_return\n n_elite=int(self.pop_size*self.elite_frac)\n scores_deque = deque(maxlen=100)\n best_weight = self.sigma*np.random.randn(self.agent.get_weights_dim())\n for i_iteration in range(1, self.iterations+1):\n weights_pop = [best_weight+(self.sigma*np.random.randn(self.agent.get_weights_dim())) for i in range(self.pop_size)]\n rewards = np.array([evaluate(weights, False) for weights in weights_pop])\n elite_idxs = rewards.argsort()[-n_elite:]\n elite_weights = [weights_pop[i] for i in elite_idxs]\n best_weight = np.array(elite_weights).mean(axis=0)\n if i_iteration % self.log_interval == 0:\n reward = evaluate(best_weight, True)\n else:\n reward = evaluate(best_weight, False)\n scores_deque.append(reward)\n if i_iteration % self.log_interval == 0:\n print('Episode {}\\tAverage Score: {:.2f}'.format(i_iteration, np.mean(scores_deque)))\n if self.logging:\n self.writer.writerow([i_iteration, np.mean(scores_deque).item()])","sub_path":"trainers/cem.py","file_name":"cem.py","file_ext":"py","file_size_in_byte":3441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"319078032","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nProject Euler Problem 308\n=======================\n\nA program written in the programming language Fractran consists of a list\nof fractions.\n\nThe internal state of the Fractran Virtual Machine is a positive integer,\nwhich is initially set to a seed value. Each iteration of a Fractran\nprogram multiplies the state integer by the first fraction in the list\nwhich will leave it an integer.\n\nFor example, one of the Fractran programs that John Horton Conway wrote\nfor prime-generation consists of the following 14 fractions:\n\n17 , 78 , 19 , 23 , 29 , 77 , 95 , 77 , 1 , 11 , 13 , 15 , 1 , 55 .\n91 85 51 38 33 29 23 19 17 13 11 2 7 1\n\nStarting with the seed integer 2, successive iterations of the program\nproduce the sequence:\n15, 825, 725, 1925, 2275, 425, ..., 68, 4, 30, ..., 136, 8, 60, ..., 544,\n32, 240, ...\n\nThe powers of 2 that appear in this sequence are 2^2, 2^3, 2^5, ...\nIt can be shown that all the powers of 2 in this sequence have prime\nexponents and that all the primes appear as exponents of powers of 2, in\nproper order!\n\nIf someone uses the above Fractran program to solve Project Euler Problem\n7 (find the 10001^st prime), how many iterations would be needed until the\nprogram produces 2^10001st prime?\n\n\"\"\"\n\n\ndef main():\n return \"unimplemented\"\n\n\nif __name__ == \"__main__\":\n import ntpath\n import time\n from common.shared_functions import verify_solution\n\n problem_number = int(ntpath.basename(__file__).replace(\"euler\", \"\").replace(\".py\", \"\"))\n print(\"Retrieving my answer to Euler Problem {0} ...\".format(problem_number))\n\n ts = time.time()\n my_answer = main()\n te = time.time()\n\n print(\"My answer: {1}\".format(problem_number, my_answer))\n\n verification_type = verify_solution(problem_number, my_answer)\n print(\"Verification: {0}\".format(verification_type.name))\n print(\"Took {0} seconds.\".format(te - ts))\n","sub_path":"project-euler/solvers/euler308.py","file_name":"euler308.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"503417171","text":"#!/usr/bin/env python3\n\nimport json\n\nimport boto3\nfrom botocore.config import Config\nimport os\n\nregions = [\n 'eu-central-1',\n]\n\nfilters = [\n {'Name': 'tag:Environment', 'Values': ['testnet']},\n {'Name': 'tag:Project', 'Values': ['example']},\n {'Name': 'tag:Team', 'Values': ['eth2']},\n {'Name': 'instance-state-name', 'Values': ['running']},\n]\n\nboto3_session = boto3.session.Session(profile_name='sso')\n\ndef fetch_client_type(eth2client_type):\n if eth2_node_index == 104:\n I['explorer']['hosts'].append(node)\n I['forkmon']['hosts'].append(node)\n if eth2_node_index == 110:\n I['bootnode']['hosts'].append(node)\n if eth2_node_index % 4 == 0:\n eth2client_type = 'lighthouse'\n elif local_index % 4 == 1:\n eth2client_type = 'prysm'\n elif local_index % 4 == 2:\n eth2client_type = 'teku'\n else:\n eth2client_type = 'nimbus'\n return eth2client_type\n\nI = {\n '_meta': {\n 'hostvars': {}\n },\n 'all': {\n 'hosts': [\n\n ],\n 'children': [\n 'ungrouped',\n 'metrics',\n 'eth2stats_server',\n 'bootnode',\n 'forkmon'\n 'eth2client',\n 'beacon',\n 'validator',\n ]\n },\n 'metrics': {\n 'hosts': [],\n 'vars': {}\n },\n 'eth2stats_server': {\n 'hosts': []\n },\n 'explorer': {\n 'hosts': []\n },\n 'forkmon': {\n 'hosts': []\n },\n 'bootnode': {\n 'hosts': []\n },\n 'beacon': {\n 'hosts': [],\n },\n 'validator': {\n 'hosts': [],\n },\n 'eth2client': {\n 'hosts': [],\n 'children': [\n 'eth2client_lighthouse',\n 'eth2client_nimbus',\n 'eth2client_prysm',\n 'eth2client_teku'\n ]\n },\n 'eth2client_lighthouse': {\n 'hosts': [],\n },\n 'eth2client_nimbus': {\n 'hosts': [],\n },\n 'eth2client_prysm': {\n 'hosts': [],\n },\n 'eth2client_teku': {\n 'hosts': [],\n },\n 'ungrouped': {\n 'children': [\n ]\n }\n}\n\neth2_clients = [\n 'lighthouse',\n 'nimbus',\n 'prysm',\n 'teku'\n]\n\nfor reg in regions:\n for cl in eth2_clients:\n I[f'eth2client_{cl}_{reg.replace(\"-\", \"_\")}'] = {'hosts': []}\n I[f'eth2client_all_{reg.replace(\"-\", \"_\")}'] = {'hosts': []}\n\n\n\ndef get_instances():\n for r in regions:\n ec2 = boto3_session.resource('ec2', region_name=r)\n instances = ec2.instances.filter(Filters=filters)\n for i in instances:\n yield i\n\nfor i in get_instances():\n name = i.id\n role = 'unknown'\n node_size = None\n for tag in i.tags:\n if tag['Key'] == 'Name':\n name = tag['Value']\n if tag['Key'] == 'Role':\n role = tag['Value']\n if tag['Key'] == 'NodeSize':\n node_size = tag['Value']\n\n\n # TODO: filter nodes by tag, so we can have more than just beacon nodes in this dynamic inventory.\n if role == 'eth2_bootnode':\n I['bootnode']['hosts'].append(name)\n else:\n I['beacon']['hosts'].append(name)\n I['validator']['hosts'].append(name)\n\n I['all']['hosts'].append(name)\n region = str(i.placement['AvailabilityZone'])\n region = region[:region.rindex('-') + 2] # strip of the a, b, whatever zone suffix from the region\n\n parts = name.split('-')\n node_id = int(parts[-1])\n\n I['_meta']['hostvars'][name] = {\n 'ansible_host': i.public_ip_address, # ip that we use for ansible work.\n 'public_ip_address': i.public_ip_address, # ip that we use for p2p / configs / etc., generally the same\n 'region': region,\n # store the node_id, used later for building eth2stats display names etc.\n 'eth2_node_index': node_id,\n 'node_size': node_size,\n 'display_emoji': \"example\" + str(node_id),\n }\n\nbeacons = I['beacon']['hosts']\n\nfor node in beacons:\n eth2_node_index = I['_meta']['hostvars'][node]['eth2_node_index']\n group_index = (eth2_node_index // 100)\n local_index = (eth2_node_index % 100)\n\n eth2client_type = fetch_client_type(eth2_node_index)\n\n I['eth2client_' + eth2client_type]['hosts'].append(node)\n\nbootnodes = I['bootnode']['hosts']\nfor node in bootnodes:\n # Node names are formatted like 'eth2-inventory-example-402'\n # hundreds = match region index (starting at 1)\n # rest is node index within region.\n parts = node.split('-')\n node_id = int(parts[-1])\n # make sure we correctly identify the node region\n assert node_id // 100 == regions.index(region) + 1\n # store the node_id, used later for building eth2stats display names etc.\n I['_meta']['hostvars'][node]['bootnode_index'] = node_id\n I['_meta']['hostvars'][node]['bootnode_p2p_priv_key'] = os.getenv(f\"BOOTNODE_PRIV\")\n\n\ndef get_node_public_ips(groupname):\n for n in I[groupname]['hosts']:\n yield n, I['_meta']['hostvars'][n]['public_ip_address']\n\ndef get_client_ips(client):\n return get_node_public_ips('eth2client_' + client)\n\ndef get_client_metrics_targets(client):\n for node, ip in get_client_ips(client):\n yield f'{ip}:8100'\n yield f'{ip}:8080'\n\nprint(json.dumps(I, indent=4))","sub_path":"example-testnet/inventory/dynamic.py","file_name":"dynamic.py","file_ext":"py","file_size_in_byte":5197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"118714477","text":"from django.shortcuts import render\n\nfrom rest_framework import status\nfrom rest_framework import generics\nfrom rest_framework.decorators import api_view\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\n# Create your views here.\n\nfrom .models import Item\nfrom .serializer import ItemSerializer\n\n@api_view(['GET', 'POST'])\ndef item_list(request):\n\tif(request.method == 'GET'):\n\t\titems = Item.objects.all()\n\t\tserializers = ItemSerializer(items, many=True)\n\t\treturn Response(serializers.data)\n\n\telif(request.method == 'POST'):\n\t\tserializer = ItemSerializer(data=request.data)\n\t\tif(serializer.is_valid()):\n\t\t\tserializer.save()\n\t\t\treturn Response(serializer.data, status=status.HTTP_201_CREATED)\n\t\telse:\n\t\t\treturn Response(\n\t\t\t\tserializer.errors, status=status.status.HTTP_400_BAD_REQUEST)\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef item_detail(request, pk):\n\ttry:\n\t\titem = Item.objects.get(pk=pk)\n\texcept Item.DoesNotExist:\n\t\tResponse(status=status.HTTP_400_BAD_REQUEST)\n\n\tif(request.method == 'GET'):\n\t\tserializer = ItemSerializer(item)\n\t\treturn Response(serializer.data)\n\t\n\telif(request.method == 'PUT'):\n\t\tserializer = ItemSerializer(task, data=request.data)\n\t\tif(serializer.is_valid()):\n\t\t\tserializer.save()\n\t\t\treturn Response(serializer.data)\n\t\telse:\n\t\t\treturn Response(\n\t\t\t\tserializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\t\n\telif(request.method == 'DELETE'):\n\t\titem.delete()\n\t\treturn Response(status=status.HTTP_204_NO_CONTENT)","sub_path":"items/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"382272776","text":"#!/usr/bin/env python3\n# -*- coding=utf-8 -*-\n\"\"\"\n@author:Wllen\n@file:06互斥锁.py\n@time:2018/8/25 20:58\n\"\"\"\nfrom multiprocessing import Process,Lock\nimport time\ndef tsak(name,lock):\n lock.acquire() # 加锁\n print('%s 1'%name)\n time.sleep(1)\n print('%s 2'%name)\n time.sleep(1)\n print('%s 3'%name)\n lock.release() # 释放锁\n\nif __name__ == '__main__':\n lock = Lock()\n for i in range(3):\n p = Process(target=tsak, args=('进程 %s'%i,lock))\n p.start()","sub_path":"learning/第七章/06互斥锁.py","file_name":"06互斥锁.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"373838796","text":"#assignment 3\nimport csv\nimport math\nimport cmath\nimport more_itertools as mit\n\ndata = []\nsum = [0,0]\n\n\n# import data from csv\nwith open('sound.csv', 'rt') as csvfile:\n reader = csv.reader(csvfile, dialect = 'excel', delimiter = ',', quoting=csv.QUOTE_NONNUMERIC)\n for line in reader:\n data.append(line)\n\n# sum up each line\nfor line in data:\n sum = [sum[0]+ line[0], sum[1]+ line[1]]\n\n\n# Get mean by dividing sums by length of the dataset\nmean = [sum[0]/len(data), sum[1]/len(data)]\n\n\n# Normalize the data by subtraction the mean\nfor line in data:\n line = [line[0] - mean[0], line[1] - mean[1]]\n\n\n# Training that network technically\n\n#randomish weights\nweights = [1,1];\ndeltaW = [0,0];\n\n# learning rate\nc = 0.1\n\n# apply math to data, single iteration\nfor line in data:\n # get dot product\n y = mit.dotproduct(line, weights)\n\n # make K\n K = y * y\n\n # get deltaW\n deltaW[0] = c * ((line[0] * y) - (K * weights[0]));\n deltaW[1] = c * ((line[1] * y) - (K * weights[1]));\n\n # update weights\n weights[0] = weights[0] + deltaW[0];\n weights[1] = weights[1] + deltaW[1];\n\ntogether = []\n\n# dot product with the input data and new weights\n\nf = open(\"Readme.txt\", \"w+\")\nf.write('Final Weights')\nf.write('\\n%f, %f\\n\\n' % (weights[0], weights[1]))\nf.close()\nfor line in data:\n together.append(mit.dotproduct(line, weights))\n\n# writing csv value\nwith open('output.csv', 'w', newline='\\n') as csvfile:\n spamwriter = csv.writer(csvfile, delimiter=',',\n quotechar='|', quoting=csv.QUOTE_MINIMAL)\n for line in together:\n spamwriter.writerow([line])\n\n","sub_path":"Sound_Cleaning/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"245949373","text":"from collections import defaultdict\n\nimport elasticsearch\nfrom elasticsearch import helpers\n\nfrom monolith.aggregator.plugins import Plugin\n\n\nclass ESSetup(object):\n\n def __init__(self, client):\n self.client = client\n\n def _default_settings(self):\n return {\n 'settings': {\n 'refresh_interval': '10s',\n 'default_field': '_id',\n 'analysis': {\n 'analyzer': {\n 'default': {\n 'type': 'custom',\n 'tokenizer': 'keyword',\n },\n },\n },\n 'store': {\n 'compress': {\n 'stored': 'true',\n 'tv': 'true',\n },\n },\n 'cache': {\n 'field': {\n 'type': 'soft',\n },\n },\n },\n 'mappings': {\n '_default_': {\n '_all': {'enabled': False},\n 'dynamic_templates': [{\n 'disable_string_analyzing': {\n 'match': '*',\n 'match_mapping_type': 'string',\n 'mapping': {\n 'type': 'string',\n 'index': 'not_analyzed',\n },\n },\n }],\n },\n },\n }\n\n def configure_templates(self):\n # setup template for time-slice index\n try:\n res = self.client.indices.get_template(name='time_1')\n except elasticsearch.ElasticsearchException:\n res = None\n if res: # pragma: no cover\n try:\n self.client.indices.delete_template(name='time_1')\n except elasticsearch.ElasticsearchException:\n pass\n time_settings = self._default_settings()\n time_settings['template'] = '*time_*'\n time_settings['settings']['number_of_shards'] = 1\n time_settings['settings']['number_of_replicas'] = 1\n self.client.indices.put_template(name='time_1', body=time_settings)\n\n def optimize_index(self, index):\n \"\"\"Fully optimize an index down to one segment.\"\"\"\n return self.client.indices.optimize(\n index=index, max_num_segments=1, wait_for_merge=True)\n\n\nclass ESWrite(Plugin):\n\n def __init__(self, **options):\n self.options = options\n self.url = options['url']\n self.prefix = options.get('prefix', '')\n self.client = elasticsearch.Elasticsearch(hosts=[self.url])\n self.setup = ESSetup(self.client)\n self.setup.configure_templates()\n\n def _index_name(self, date):\n return '%stime_%.4d-%.2d' % (self.prefix, date.year, date.month)\n\n def _bulk_index(self, index, doc_type, docs, id_field='id'):\n actions = [\n {'_index': index, '_type': doc_type, '_id': doc.pop(id_field),\n '_source': doc} for doc in docs]\n\n return helpers.bulk(self.client, actions)\n\n def inject(self, batch):\n holder = defaultdict(list)\n # sort data into index/type buckets\n for source_id, item in batch:\n # XXX use source_id as a key with dates for updates\n item = dict(item)\n date = item['date']\n index = self._index_name(date)\n _type = item.pop('_type')\n holder[(index, _type)].append(item)\n\n # submit one bulk request per index/type combination\n for key, docs in holder.items():\n actions = [\n {'_index': key[0], '_type': key[1], '_id': doc.pop('_id'),\n '_source': doc} for doc in docs]\n resp = helpers.bulk(self.client, actions)\n for res in resp[1]:\n if res['index'].get('ok'):\n continue\n error = res['index'].get('error')\n if error is not None:\n msg = 'Could not index %s' % str(docs[index])\n msg += '\\nES Error:\\n'\n msg += error\n msg += '\\n The data may have been partially imported.'\n raise ValueError(msg)\n\n def clear(self, start_date, end_date, source_ids):\n start_date_str = start_date.strftime('%Y-%m-%d')\n end_date_str = end_date.strftime('%Y-%m-%d')\n\n query = {'filtered': {\n 'query': {'match_all': {}},\n 'filter': {\n 'and': [\n {'range': {\n 'date': {\n 'gte': start_date_str,\n 'lte': end_date_str,\n },\n '_cache': False,\n }},\n {'terms': {\n 'source_id': source_ids,\n '_cache': False,\n }},\n ]\n }\n }}\n self.client.indices.refresh(index='%stime_*' % self.prefix)\n self.client.delete_by_query(index='%stime_*' % self.prefix, body=query)\n","sub_path":"monolith/aggregator/plugins/es.py","file_name":"es.py","file_ext":"py","file_size_in_byte":5235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"65164389","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#\tCopyright 2009-2012, 2014, Marten de Vries\n#\tCopyright 2008-2011, Milan Boers\n#\n#\tThis file is part of OpenTeacher.\n#\n#\tOpenTeacher is free software: you can redistribute it and/or modify\n#\tit under the terms of the GNU General Public License as published by\n#\tthe Free Software Foundation, either version 3 of the License, or\n#\t(at your option) any later version.\n#\n#\tOpenTeacher is distributed in the hope that it will be useful,\n#\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n#\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n#\tGNU General Public License for more details.\n#\n#\tYou should have received a copy of the GNU General Public License\n#\talong with OpenTeacher. If not, see .\n\nimport weakref\n\ndef installQtClasses():\n\tglobal CharsKeyboardWidget, KeyboardsWidget\n\n\tclass CharsKeyboardWidget(QtGui.QWidget):\n\t\t\"\"\"A keyboard widget that displays all characters passed to it\n\t\t in the constructor, and emits the letterChosen signal when\n\t\t one is clicked.\n\n\t\t\"\"\"\n\t\tletterChosen = QtCore.pyqtSignal([object])\n\n\t\tdef __init__(self, characters, *args, **kwargs):\n\t\t\tsuper(CharsKeyboardWidget, self).__init__(*args, **kwargs)\n\n\t\t\ttopWidget = QtGui.QWidget()\n\n\t\t\tlayout = QtGui.QGridLayout()\n\t\t\tlayout.setSpacing(1)\n\t\t\tlayout.setContentsMargins(0, 0, 0, 0)\n\n\t\t\ti = 0\n\t\t\tfor line in characters:\n\t\t\t\tj = 0\n\t\t\t\tfor item in line:\n\t\t\t\t\tb = QtGui.QPushButton(item)\n\t\t\t\t\tb.clicked.connect(self._letterChosen)\n\t\t\t\t\tb.setMinimumSize(1, 1)\n\t\t\t\t\tb.setFlat(True)\n\t\t\t\t\tb.setAutoFillBackground(True)\n\t\t\t\t\tpalette = b.palette()\n\t\t\t\t\tif i % 2 == 0:\n\t\t\t\t\t\tbrush = palette.brush(QtGui.QPalette.Base)\n\t\t\t\t\telse:\n\t\t\t\t\t\tbrush = palette.brush(QtGui.QPalette.AlternateBase)\n\t\t\t\t\tpalette.setBrush(QtGui.QPalette.Button, brush)\n\t\t\t\t\tb.setPalette(palette)\n\t\t\t\t\tif not item:\n\t\t\t\t\t\tb.setEnabled(False)\n\t\t\t\t\tlayout.addWidget(b, i, j)\n\t\t\t\t\tj += 1\n\t\t\t\ti+= 1\n\t\t\ttopWidget.setLayout(layout)\n\t\t\tpalette = topWidget.palette()\n\t\t\tbrush = palette.brush(QtGui.QPalette.WindowText)\n\t\t\tpalette.setBrush(QtGui.QPalette.Window, QtCore.Qt.darkGray)\n\t\t\ttopWidget.setPalette(palette)\n\t\t\ttopWidget.setAutoFillBackground(True)\n\n\t\t\tmainLayout = QtGui.QVBoxLayout()\n\t\t\tmainLayout.addWidget(topWidget)\n\t\t\tmainLayout.addStretch()\n\t\t\tmainLayout.setContentsMargins(0, 0, 0, 0)\n\t\t\tself.setLayout(mainLayout)\n\n\t\t\ttopWidget.setSizePolicy(\n\t\t\t\tQtGui.QSizePolicy.Expanding,\n\t\t\t\tQtGui.QSizePolicy.Maximum\n\t\t\t)\n\n\t\tdef _letterChosen(self):\n\t\t\ttext = unicode(self.sender().text())\n\t\t\tself.letterChosen.emit(text)\n\n\tclass KeyboardsWidget(QtGui.QTabWidget):\n\t\t\"\"\"A container of keyboard widgets, it has one keyboard widget\n\t\t for every different table of characters.\n\n\t\t\"\"\"\n\t\tdef __init__(self, createEvent, data, *args, **kwargs):\n\t\t\tsuper(KeyboardsWidget, self).__init__(*args, **kwargs)\n\n\t\t\tself.letterChosen = createEvent()\n\t\t\tself._data = data\n\t\t\tself.update()\n\n\t\tdef update(self):\n\t\t\t#clean the widget, needed if this method has been called before.\n\t\t\tself.clear()\n\t\t\tfor module in self._data:\n\t\t\t\t#create tab and add it to the widget\n\t\t\t\ttab = CharsKeyboardWidget(module.data)\n\t\t\t\tself.addTab(tab, module.name)\n\t\t\t\t#connect the event that handles letter selection\n\t\t\t\ttab.letterChosen.connect(self.letterChosen.send)\n\nclass CharsKeyboardModule(object):\n\t\"\"\"This module offers an onscreen character keyboard widget, which\n\t makes use of the char modules as its data source.\n\n\t\"\"\"\n\tdef __init__(self, moduleManager, *args, **kwargs):\n\t\tsuper(CharsKeyboardModule, self).__init__(*args, **kwargs)\n\n\t\tself._mm = moduleManager\n\t\tself.type = \"charsKeyboard\"\n\t\tself.requires = (\n\t\t\tself._mm.mods(type=\"ui\"),\n\t\t\tself._mm.mods(type=\"event\"),\n\t\t\tself._mm.mods(type=\"chars\"),\n\t\t\tself._mm.mods(type=\"translator\"),\n\t\t)\n\n\tdef enable(self):\n\t\tglobal QtCore, QtGui\n\t\ttry:\n\t\t\tfrom PyQt4 import QtCore, QtGui\n\t\texcept ImportError:\n\t\t\treturn\n\t\tinstallQtClasses()\n\n\t\tself._modules = set(self._mm.mods(type=\"modules\")).pop()\n\t\tself._widgets = set()\n\n\t\ttry:\n\t\t\ttranslator = self._modules.default(\"active\", type=\"translator\")\n\t\texcept IndexError:\n\t\t\tpass\n\t\telse:\n\t\t\ttranslator.languageChangeDone.handle(self._update)\n\n\t\t#to make sure the widgets are updated when their data sources\n\t\t#are updated.\n\t\tfor dataMod in self._mm.mods(\"active\", type=\"chars\"):\n\t\t\tif hasattr(dataMod, \"updated\"):\n\t\t\t\tdataMod.updated.handle(self._update)\n\n\t\tself.active = True\n\n\tdef disable(self):\n\t\tself.active = False\n\n\t\tdel self._modules\n\t\tdel self._widgets\n\n\tdef createWidget(self):\n\t\t\"\"\"Creates a keyboard widget. It has one OT-style event:\n\t\t letterChosen. Handlers should add the as argument passed char\n\t\t to their input box.\n\n\t\t\"\"\"\n\t\tkw = KeyboardsWidget(\n\t\t\tself._modules.default(type=\"event\").createEvent,\n\t\t\tself._modules.sort(\"active\", type=\"chars\")\n\t\t)\n\t\tself._widgets.add(weakref.ref(kw))\n\t\treturn kw\n\n\tdef _update(self):\n\t\tfor ref in self._widgets:\n\t\t\twidget = ref()\n\t\t\tif widget is not None:\n\t\t\t\twidget.update()\n\ndef init(moduleManager):\n\treturn CharsKeyboardModule(moduleManager)\n","sub_path":"modules/org/openteacher/interfaces/qt/charsKeyboard/charsKeyboard.py","file_name":"charsKeyboard.py","file_ext":"py","file_size_in_byte":5019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"157108390","text":"import numpy\nimport h5py\nimport os, sys\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom matplotlib.collections import PatchCollection\nimport argparse\nimport glob\nfrom handle_data import CutMask\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\", \"--input_file\",default=None,\n type=str,dest=\"input_files\", help=\"names for input file\")\nparser.add_argument(\"-d\", \"--path\",type=str,default='/mnt/scratch/micall12/training_files/',\n dest=\"path\", help=\"path to input files\")\nparser.add_argument(\"-o\", \"--outdir\",type=str,default='/mnt/home/micall12/LowEnergyNeuralNetwork/output_plots/',\n dest=\"outdir\", help=\"out directory for plots\")\nparser.add_argument(\"-n\", \"--name\",default=None,\n dest=\"name\", help=\"name for output folder\")\nparser.add_argument(\"--large_charge\",type=float,default=40.,\n dest=\"large_charge\", help=\"Max charge to distinguish for statistics\")\nparser.add_argument(\"--large_numpulses\",type=int,default=20,\n dest=\"large_numpulses\", help=\"Max number of pulses to distinguish for statistics\")\nparser.add_argument(\"--emax\",type=float,default=100.0,\n dest=\"emax\",help=\"Cut anything greater than this energy (in GeV)\")\nparser.add_argument(\"--emin\",type=float,default=5.0,\n dest=\"emin\",help=\"Cut anything less than this energy (in GeV)\")\nparser.add_argument(\"-c\", \"--cuts\",type=str, default=\"CC\",\n dest=\"cuts\", help=\"Type of events to keep (all, cascade, track, CC, NC, etc.)\")\nargs = parser.parse_args()\n\n\ninput_file = args.path + args.input_files\n\noutput_path = args.outdir\nname = args.name\noutdir = output_path + name\nif os.path.isdir(outdir) != True:\n os.mkdir(outdir)\nprint(\"Saving plots to %s\"%outdir)\n \n\nlarge_number_pulses = args.large_numpulses\nlarge_charge = args.large_charge\nenergy_min = args.emin\nenergy_max = args.emax\ncut_name = args.cuts\n\ncheck_charge = True\ncheck_numpulses = True\n\n### Import Files ###\nf = h5py.File(input_file, 'r')\nlabels = f['labels'][:]\nstats = f['initial_stats'][:]\nnum_pulses = f['num_pulses_per_dom'][:]\ntry:\n trig_time = f['trigger_times'][:]\nexcept:\n trig_time = None\nf.close()\ndel f\n\n# Apply Cuts\nmask = CutMask(labels)\ncut_energy = numpy.logical_and(labels[:,0] > energy_min, labels[:,0] < energy_max)\nall_cuts = numpy.logical_and(mask[cut_name], cut_energy)\nlabels = labels[all_cuts]\nstats = stats[all_cuts]\nnum_pulses = num_pulses[all_cuts]\ntrig_time = trig_time[all_cuts]\n\n## WHAT EACH ARRAY CONTAINS! ##\n# reco: (energy, zenith, azimuth, time, x, y, z) \n# stats: (count_outside, charge_outside, count_inside, charge_inside) \n# num_pulses: [ string num, dom index, num pulses]\n# trig_time: [DC_trigger_time]\n\nnum_events = stats.shape[0]\nprint(\"Checking %i events\"%num_events)\n\n# Charge outside vs inside\nif check_charge:\n count_outside = stats[:,0]\n charge_outside = stats[:,1]\n count_inside = stats[:,2]\n charge_inside = stats[:,3]\n fraction_count_inside = count_inside/(count_outside + count_inside)\n fraction_charge_inside = charge_inside/(charge_outside + charge_inside)\n mask_large_charge = charge_inside > large_charge\n fraction_large_charge = sum(charge_inside[mask_large_charge])/sum(charge_inside)\n print(\"Median of counts inside is %f with median total charge inside is %f, in the subset of chosen strings over all events\"%(numpy.median(fraction_count_inside),numpy.median(fraction_charge_inside)))\n print(\"PERCENTAGE of charge that is greater than %i inside subset of strings over all events: %f percent\"%(large_charge,fraction_large_charge*100))\n\n plt.figure()\n plt.title(\"Fraction of # pulses inside subset strings\")\n plt.hist(fraction_count_inside,bins=50,alpha=0.5);\n plt.xlabel(\"# pulses inside subset strings / total # pulses in event\")\n plt.savefig(\"%s/FractionPulsesInside.png\"%outdir)\n\n plt.figure()\n plt.title(\"Fraction of charge inside subset strings\")\n plt.hist(fraction_charge_inside,bins=50,alpha=0.5);\n plt.xlabel(\"charge recorded inside subset strings / total charge recorded in event\")\n plt.savefig(\"%s/FractionChargeInside.png\"%outdir)\n\n# Number of pulses on all DOMS\nif check_numpulses:\n num_pulses_all = num_pulses[:,:,:,0].flatten()\n large_mask = num_pulses_all > large_number_pulses\n large_num = sum(num_pulses_all[large_mask])\n fraction_large = large_num/len(num_pulses_all)\n print(\"PERCENTAGE of DOMS that see more pulses than %i over all events: %f percent\"%(large_number_pulses,fraction_large*100))\n\n gt0 = num_pulses_all > 0\n plt.figure()\n plt.title(\"Number of pulses > 0 on ALL DOMS for ALL events\")\n plt.hist(num_pulses_all[gt0],bins=50,alpha=0.5);\n plt.xlabel(\"# pulses per dom\")\n plt.yscale('log')\n plt.savefig(\"%s/NumberPulsesAllDOMS.png\"%outdir)\n\n plt.figure()\n for i in range(0,10):\n num_pulses_one_evt = num_pulses[i,:,:,0].flatten()\n gt0 = num_pulses_one_evt > 0\n plt.hist(num_pulses_one_evt[gt0],bins=5,alpha=0.5);\n plt.title(\"Number of pulses > 0 on ALL DOMS per 10 events\")\n plt.xlabel(\"# pulses per dom\")\n plt.yscale('log')\n plt.savefig(\"%s/NumberPulsesAllDOMS_10Events.png\"%outdir)\n\n","sub_path":"check_charge_numberpulses.py","file_name":"check_charge_numberpulses.py","file_ext":"py","file_size_in_byte":5285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"197814642","text":"def insert(n,arr):\n counter=0\n for i in range(1,len(arr)):\n k=arr[i]\n x=i-1\n while x>=0 and k\\d*)$', redirect_performance, name=\"redirect_performance\"),\n url(r'^unsubscribe/$', unsubscribe, name=\"unsubscribe\"),\n url(r'^verify_mail/(?P[a-f0-9]{32})$', verify_email, name=\"verify_email\"),\n url(r'^verify_push/(?P[a-f0-9]{32})$', verify_push, name=\"verify_push\"),\n url(r'^impressum/$', impressum, name=\"impressum\"),\n url(r'^$', index, name=\"index\"),\n]","sub_path":"django/app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"307880948","text":"class Solution:\n def reverse(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n \"\"\"\n sign = -1 if x < 0 else 1\n result = sign * int(str(abs(x))[::-1])\n return result if -2 ** 31 < result < 2 ** 31 - 1 else 0\n\n def reverse1(self, x):\n sign = -1 if x < 0 else 1\n x = abs(x)\n result = 0\n while x > 0:\n result = result * 10 + x % 10\n x //= 10\n result *= sign\n return result if -2 ** 31 < result < 2 ** 31 - 1 else 0\n","sub_path":"algorithms/007. Reverse Integer/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"231706585","text":"from django.urls import path\nfrom . import views\n\napp_name = \"students\"\nurlpatterns = [\n # Url patterns for students\n path(\"\", views.students, name=\"students\"),\n path(\"new-student\", views.new_student, name=\"new_student\"),\n path(\"new-student-sheet\", views.new_student_sheet, name=\"new_student_sheet\"),\n path(\"student-edit/\", views.edit_student, name=\"edit_student\"),\n path(\"delete-student\", views.delete_student, name=\"delete_student\"),\n path(\"student-detail/\", views.student_detail, name=\"student_detail\"),\n path(\"promotion\", views.promotion, name=\"promotion\"),\n\n # Url patterns for classes\n path(\"classes\", views.classes, name=\"classes\"),\n path(\"new-class\", views.new_class, name=\"new_class\"),\n path(\"class-edit/\", views.edit_class, name=\"edit_class\"),\n path(\"delete-class\", views.delete_class, name=\"delete_class\"),\n path(\"class-detail/\", views.class_detail, name=\"class_detail\"),\n\n # Url patterns for subjects\n path(\"subjects\", views.subjects, name=\"subjects\"),\n path(\"new-subject\", views.new_subject, name=\"new_subject\"),\n path(\"new-subject-sheet\", views.new_subject_sheet, name=\"new_subject_sheet\"),\n path(\"delete-subject\", views.delete_subject, name=\"delete_subject\"),\n path(\"subject-detail/\", views.subject_detail, name=\"subject_detail\"),\n path(\"subject-edit/\", views.edit_subject, name=\"edit_subject\"),\n\n # Url patterns for courses\n path(\"courses\", views.courses, name=\"courses\"),\n path(\"new-course\", views.new_course, name=\"new_course\"),\n path(\"new-course-sheet\", views.new_course_sheet, name=\"new_course_sheet\"),\n path(\"delete-course\", views.delete_course, name=\"delete_course\"),\n path(\"course-detail/\", views.course_detail, name=\"course_detail\"),\n path(\"course-edit/\", views.edit_course, name=\"edit_course\"),\n\n # Url patterns for house_masters\n path(\"house_masters\", views.house_masters, name=\"house_masters\"),\n path(\"new-house-master\", views.new_house_master, name=\"new_house_master\"),\n path(\"new-house_master-sheet\", views.new_house_master_sheet, name=\"new_house_master_sheet\"),\n path(\"delete-house-master\", views.delete_house_master, name=\"delete_house_master\"),\n path(\"house-master-detail/\", views.house_master_detail, name=\"house_master_detail\"),\n path(\"house-master-edit/\", views.edit_house_master, name=\"edit_house_master\"),\n\n # Url patterns for records\n path(\"records\", views.records, name=\"records\"),\n path(\"generate-record-sheet\", views.generate_record_sheet, name=\"generate_record_sheet\"),\n path(\"download-generated-record-sheet\", views.download_generated_record_sheet, name=\"download_generated_record_sheet\"),\n path(\"upload-record-sheet\", views.upload_record_sheet, name=\"upload_record_sheet\"),\n path(\"edit-record\", views.edit_record, name=\"edit_record\"),\n \n # Url patterns for grading systems\n path(\"grading-systems\", views.grading_systems, name=\"grading_systems\"),\n path(\"new-grading-system\", views.new_grading_system, name=\"new_grading_system\"),\n path(\"grading-system-edit/\", views.edit_grading_system, name=\"edit_grading_system\"),\n path(\"delete-grading-system\", views.delete_grading_system, name=\"delete_grading_system\"),\n]\n\n\n\n\n\n\n","sub_path":"students/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"465140331","text":"from tornado import gen\nfrom tornado.ioloop import IOLoop, PeriodicCallback\nfrom tornado.httpclient import AsyncHTTPClient\n\n\n@gen.coroutine\ndef fetch(urls):\n http = AsyncHTTPClient()\n resp = yield list(map(http.fetch, urls))\n return resp\n\n\nif __name__ == '__main__':\n import pprint\n urls = [\n 'http://python.jobbole.com/',\n 'http://www.baidu.com/',\n 'http://www.sohu.com/',\n 'http://www.sina.com/',\n 'http://www.ruanyifeng.com',\n 'http://cnodejs.org/',\n 'http://www.pythontab.com/',\n 'http://docs.jinkan.org/docs/jinja2/',\n 'https://www.djangoproject.com/start/overview/',\n 'http://www.semantic-ui.cn/',\n ]\n future = fetch(urls)\n\n io_loop = IOLoop.current()\n io_loop.add_future(future, lambda f: io_loop.stop())\n\n def callback():\n pprint.pprint(io_loop._handlers)\n\n period = PeriodicCallback(callback=callback, callback_time=200, io_loop=io_loop)\n period.start()\n\n io_loop.start()\n","sub_path":"demos/http_client2.py","file_name":"http_client2.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"487620509","text":"import pandas as pd\nimport geopandas as gpd\nfrom django.db import connection\n\nfrom historical.models import Historical\n\ndf = pd.read_csv('data/historical_data.csv')\ndf_geo = gpd.read_file('data/illinois.json').set_index('COUNTY_NAM')\n\n# should always find the lookup\ndef county_to_id(county):\n county = county.upper()\n if county == 'DE WITT':\n county = 'DEWITT'\n elif county == 'JO DAVIESS':\n county = 'JODAVIESS'\n if county not in df_geo.index:\n raise ValueError(\"missing county: {}\".format(county))\n return df_geo.loc[county].DISTRICT\n\ndf['county'] = df['county'].apply(county_to_id)\nfor _, r in df.iterrows():\n query = \"INSERT INTO historical VALUES ({}, '{}', '{}', {}, {})\".format(r.year, r.party.title(), r.candidate, r.county, r.candidatevotes)\n with connection.cursor() as cursor:\n cursor.execute(query)\n","sub_path":"webApp/ElectionViz/push_historical.py","file_name":"push_historical.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"117621407","text":"# SPDX-FileCopyrightText: 2017 Radomir Dopieralski for Adafruit Industries\n#\n# SPDX-License-Identifier: MIT\n\n\"\"\"\n`adafruit_rgb_display.ili9341`\n====================================================\n\nA simple driver for the ILI9341/ILI9340-based displays.\n\n* Author(s): Radomir Dopieralski, Michael McWethy\n\"\"\"\n\ntry:\n import struct\nexcept ImportError:\n import ustruct as struct\nfrom rgb_display.rgb import DisplayDevice\n\n__version__ = \"0.0.0-auto.0\"\n__repo__ = \"https://github.com/jrmoser/RGB_Display.git\"\n\n\nclass ILI9341(DisplayDevice):\n \"\"\"\n A simple driver for the ILI9341/ILI9340-based displays.\n\n >>> import busio\n >>> import digitalio\n >>> import board\n >>> from adafruit_rgb_display import color565\n >>> import adafruit_rgb_display.ili9341 as ili9341\n >>> spi = busio.SPI(clock=board.SCK, MOSI=board.MOSI, MISO=board.MISO)\n >>> display = ili9341.ILI9341(spi, cs=digitalio.DigitalInOut(board.GPIO0),\n ... dc=digitalio.DigitalInOut(board.GPIO15))\n >>> display.fill(color565(0xff, 0x11, 0x22))\n >>> display.pixel(120, 160, 0)\n \"\"\"\n\n _COLUMN_SET = 0x2A\n _PAGE_SET = 0x2B\n _RAM_WRITE = 0x2C\n _RAM_READ = 0x2E\n _INIT = (\n (0xEF, b\"\\x03\\x80\\x02\"),\n (0xCF, b\"\\x00\\xc1\\x30\"),\n (0xED, b\"\\x64\\x03\\x12\\x81\"),\n (0xE8, b\"\\x85\\x00\\x78\"),\n (0xCB, b\"\\x39\\x2c\\x00\\x34\\x02\"),\n (0xF7, b\"\\x20\"),\n (0xEA, b\"\\x00\\x00\"),\n (0xC0, b\"\\x23\"), # Power Control 1, VRH[5:0]\n (0xC1, b\"\\x10\"), # Power Control 2, SAP[2:0], BT[3:0]\n (0xC5, b\"\\x3e\\x28\"), # VCM Control 1\n (0xC7, b\"\\x86\"), # VCM Control 2\n (0x36, b\"\\x48\"), # Memory Access Control\n (0x3A, b\"\\x55\"), # Pixel Format\n (0xB1, b\"\\x00\\x18\"), # FRMCTR1\n (0xB6, b\"\\x08\\x82\\x27\"), # Display Function Control\n (0xF2, b\"\\x00\"), # 3Gamma Function Disable\n (0x26, b\"\\x01\"), # Gamma Curve Selected\n (\n 0xE0, # Set Gamma\n b\"\\x0f\\x31\\x2b\\x0c\\x0e\\x08\\x4e\\xf1\\x37\\x07\\x10\\x03\\x0e\\x09\\x00\",\n ),\n (\n 0xE1, # Set Gamma\n b\"\\x00\\x0e\\x14\\x03\\x11\\x07\\x31\\xc1\\x48\\x08\\x0f\\x0c\\x31\\x36\\x0f\",\n ),\n (0x11, None),\n (0x29, None),\n )\n _ENCODE_PIXEL = \">H\"\n _ENCODE_POS = \">HH\"\n _DECODE_PIXEL = \">BBB\"\n\n # pylint: disable-msg=too-many-arguments\n def __init__(\n self,\n port,\n dc,\n rst=None,\n width=240,\n height=320,\n rotation=0,\n ):\n super().__init__(\n port,\n dc,\n rst=rst,\n width=width,\n height=height,\n rotation=rotation,\n )\n self._scroll = 0\n\n # pylint: enable-msg=too-many-arguments\n\n def scroll(self, dy=None): # pylint: disable-msg=invalid-name\n \"\"\"Scroll the display by delta y\"\"\"\n if dy is None:\n return self._scroll\n self._scroll = (self._scroll + dy) % self.height\n self.write(0x37, struct.pack(\">H\", self._scroll))\n return None\n","sub_path":"rgb_display/ili9341.py","file_name":"ili9341.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"443965600","text":"def exchangeCoin(money):\n result = [0, 0, 0, 0]\n result[0] = money // 500\n money %= 500\n result[1] = money // 100\n money %= 100\n result[2] = money // 50\n money %= 50\n result[3] = money // 10\n money %= 10\n print (result, money)\n\n\ndef main():\n money = int(input(\"교환할 돈은 얼마?\"))\n exchangeCoin(money)\n\n\nmain()","sub_path":"study/ch04operator/ch04_changeCoin.py","file_name":"ch04_changeCoin.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"12879446","text":"# the relative path of the folder containing the dataset\nrelative_path = \"../../Dataset\"\n\n# model_tag is the name of the folder that the checkpoints folders will be saved in\n\nmodel_tag = \"baseline_cell\"\n\n# tunable parameters\nout_channels_structural = 512 # number of channels\nout_channels_cell_content = 512 # number of channels\nstructural_hidden_size = 128 # dimensions of hidden layer in structural decoder\nstructural_attention_size = 128 # dimensions of context vector in structural decoder\ncell_content_hidden_size = 256 # dimensions of hidden layer in cell decoder\ncell_content_attention_size = 128 # dimensions of ontext vector in structural decoder\n\n# fixed parameters\nin_channels = 512 # fixed in output from resnet, do not change\nstructural_embedding_size = 16 # determined from preprocessing, do not change\ncell_content_embedding_size = 80 # determined from preprocessing, do not change\n\n\n# set number of epochs\nepochs = 10\n#epochs = 25\n\n\n# make list of lambdas to use for each epoch in training\nlambda_ratio = 0.4\nlambdas = int(lambda_ratio * epochs) * [1.0] + int((1-lambda_ratio) * epochs) * [0.5]\n\n#lambdas = [1.0]*25 + 25*[1, 1, 0.5, 0.5]# for n in range(epochs)] # LAMBDA = 1 turns OFF cell decoder\n# if you want to run WITH cell decoder, you can uncomment the line below, remember to change epochs to 25\n#lambdas = [1 for _ in range(30)] + [0.5 for _ in range(70)]#+ [0.5 for _ in range(10)] + [0.5 for _ in range(2)]\n\n\n# make list of learning rate to use for each epoch in training\nlrs = [0.001 for _ in range(epochs)] #+ [0.001]*25\n#lrs =[0.001 for n in range(20)]+ [0.0001 for _ in range(30)] + [0.00001 for _ in range(50)]# + [0.001 for _ in range(10)] + [0.0001 for _ in range(2)]\n#if you want to run WITH cell decoder, you can uncomment the line below, rembember to change epochs to 25\n#lrs = [0.001 for _ in range(10)] + [0.0001 for _ in range(3)] + [0.001 for _ in range(10)] + [0.0001 for _ in range(2)]\n\n# Number of examples to include in the training set\nnumber_examples=10\n\n# Number of examples to include in validation set\nnumber_examples_val=10 # not used if val==None\n\n# size of batches\nbatch_size=10\nbatch_size_val = 10\n\n# number of examples in each preprocessed file\nstorage_size=1000 # fixed, do not change\n\n# whether to calculate the validation loss\nf = 0\nval = f*[False]+(epochs-f)*[True]#, False, True, True]\n\nmaxT_val = 200\n\nalpha_c_struc = 0.0\nalpha_c_cell_content = 0.0\n\n# import model\nfrom Model import Model\n\n# instantiate model\nmodel = Model(relative_path,\n model_tag,\n in_channels = in_channels,\n out_channels_structural = out_channels_structural,\n out_channels_cell_content = out_channels_cell_content,\n structural_embedding_size=structural_embedding_size,\n structural_hidden_size=structural_hidden_size,\n structural_attention_size=structural_attention_size,\n cell_content_embedding_size=cell_content_embedding_size,\n cell_content_hidden_size=cell_content_hidden_size,\n cell_content_attention_size=cell_content_attention_size)\n\n#model.load_checkpoint(file_path=\"overtrained1example.pth.tar\")\n\n# train model\n\nloss,loss_s, loss_cc, loss_val, loss_s_val, loss_cc_val = model.train(epochs=epochs,\n lambdas=lambdas,\n lrs=lrs,\n number_examples=number_examples,\n number_examples_val=number_examples_val,\n batch_size=batch_size,\n batch_size_val = batch_size_val,\n storage_size=storage_size,\n val = val,\n maxT_val = maxT_val,\n alpha_c_struc = alpha_c_struc,\n alpha_c_cell_content = alpha_c_cell_content)\n\n\n\nfrom matplotlib import pylab as plt\nplt.plot(loss, label = 'training loss')\nplt.plot(loss_val, label = 'validation loss')\nplt.legend()\nplt.savefig('epochs_loss.png')\n","sub_path":"BaseModel_pytorch/Test-Model.py","file_name":"Test-Model.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"19216473","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport sys\nfrom PySide import QtGui\nfrom formAnimal import Ui_DialogAgregarAnimal\nimport controlador\nimport model as db_model\nimport sys\nimport os\n\n\nclass FormAnimal(QtGui.QDialog):\n\t\"\"\"\n\tClase que muestra el formulario para crear un animal\n\t\"\"\"\n\tid_animal = None # Primary Key\n\tdireccion_imagen = None\n\ttemp_direccion = \"\"\n\n\tdef __init__(self, id_animal = None):\n\t\tQtGui.QDialog.__init__(self)\n\t\tself.id_animal = id_animal\n\t\tself.direccion_imagen = None\n\n\t\tself.ui = Ui_DialogAgregarAnimal()\n\t\tself.ui.setupUi(self)\n\t\tif self.id_animal is not None:\n\t\t\tself.llenarFormularioEditar()\n\t\telse:\n\t\t\tself.imagenInicial()\n\n\t\tself.setSenales()\n\n\tdef imagenInicial(self):\n\t\tself.ui.labelImagen.setPixmap(QtGui.QPixmap(\n\t\t\t\"imgAnimal/no_disponible.jpg\"))\n\n\tdef llenarFormularioEditar(self):\n\t\tself.setWindowTitle(\"Editar Animal\")\n\t\tanimal = controlador.obtenerAnimalId(self.id_animal)\n\n\t\tself.ui.lineNombre.setText(animal.nombre)\n\t\tself.ui.lineFNacimiento.setText(animal.fecha_nac)\n\t\tif \"Macho\" in animal.sexo:\n\t\t\tself.ui.radioButtonMacho.setChecked(True)\n\t\telse:\n\t\t\tself.ui.radioButtonHembra.setChecked(True)\n\n\t\timagenes = os.listdir(\"imgAnimal/\")\n\t\timg = str(self.id_animal) + \".jpg\" in imagenes\n\t\tif img is True:\n\t\t\tdireccion = \"imgAnimal/{}\".format(str(self.id_animal) + \".jpg\")\n\t\t\tself.temp_direccion = direccion\n\t\telse:\n\t\t\tdireccion = \"imgZoo/no_disponible.jpg\"\n\t\tself.ui.labelImagen.setPixmap(QtGui.QPixmap(direccion))\n\t\tself.direccion_imagen = direccion\n\n\tdef setSenales(self):\n\t\tself.ui.botonAgregarImagen.clicked.connect(self.agregarImagen)\n\t\tself.ui.botonAceptar.clicked.connect(self.aceptarAnimal)\n\t\t#self.ui.botonCancelar.clicked.connect(self.cancelarAnimal)\n\n\tdef agregarImagen(self):\n\t\tnueva_imagen = QtGui.QFileDialog.getOpenFileNames(self, \"Abrir Imagenes\",\n\t\t\t'', \"Imagenes (*.jpg)\")\n\t\ttry:\n\t\t\tself.direccion_imagen = nueva_imagen[0][0]\n\t\texcept:\n\t\t\tself.direccion_imagen = None\n\t\ttry: \n\t\t\tself.ui.labelImagen.setPixmap(QtGui.QPixmap(self.direccion_imagen))\n\t\texcept:\n\t\t\tpass\n\n\tdef aceptarAnimal(self):\n\t\tnombre = self.ui.lineNombre.text()\n\t\tfecha_nac = self.ui.lineFNacimiento.text()\n\t\tespecie = self.ui.lineEspecie.text()\n\t\tzoologico = self.ui.lineZoologico.text()\n\t\tmacho = self.ui.radioButtonMacho.isChecked()\n\t\tif macho is True:\n\t\t\tsexo = \"Macho\"\n\t\telse:\n\t\t\thembra = self.ui.radioButtonHembra.isChecked()\n\t\t\tif hembra is True:\n\t\t\t\tsexo = \"Hembra\"\n\t\t\telse:\n\t\t\t\tsexo = \"No definido\"\n\n\t\tmensaje = controlador.crearAnimal(self.id_animal, zoologico, especie, nombre, sexo, fecha_nac)\n\n\t\tif mensaje is not True:\n\t\t\tself.mensajeError(mensaje)\n\t\telse:\n\t\t\ttry:\n\t\t\t\tos.remove(self.temp_direccion)\n\t\t\texcept:\n\t\t\t\tpass\n\n\t\t\tdireccion_destino = \"imgAnimal/{}\".format(self.id_animal)\n\t\t\tif \"imgZoo/no_disponible.jpg\" != self.direccion_imagen:\n\t\t\t\tcontrolador.almacenarImagen(self.direccion_imagen, direccion_destino)\n\n\t\t\tmensaje = \"Animal agregado correctamente.\"\n\t\t\tcorrectoQMessageBox = QtGui.QMessageBox()\n\t\t\tcorrectoQMessageBox.setText(mensaje)\n\t\t\tcorrectoQMessageBox.exec_()\n\n\t\t\tself.close()\n\n\tdef mensajeError(self, mensaje):\n\t\tcorrectoQMessageBox = QtGui.QMessageBox()\n\t\tcorrectoQMessageBox.setWindowTitle(\"ERROR!\")\n\t\tcorrectoQMessageBox.setText(mensaje)\n\t\tcorrectoQMessageBox.exec_()\n\"\"\"\nif __name__ == '__main__':\n\tapp = QtGui.QApplication(sys.argv)\n\tmain = FormAnimal()\n\tmain.show()\n\tsys.exit(app.exec_())\n\t\"\"\" \n\t","sub_path":"ctrl_formAnimal.py","file_name":"ctrl_formAnimal.py","file_ext":"py","file_size_in_byte":3364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"624696333","text":"from django import forms\nimport datetime\n\nfrom django.forms import SelectDateWidget\n\nfrom .models import Image,Test,Product,Pcomment,Category\n\n\nclass RstForm(forms.Form):\n\n subject = forms.CharField(\n max_length=20,\n widget=forms.TextInput(attrs={\n \"class\": \"form-control\",\n \"placeholder\": \"Your Name\"\n })\n )\n\n summary = forms.CharField(\n widget=forms.Textarea(\n attrs={\n \"class\": \"form-control\",\n \"placeholder\": \"Leave a comment!\",\n 'cols': 10, 'rows': 10\n })\n )\n # upload_date=forms.DateField(initial=datetime.date.today)\n upload_date=forms.DateField(widget=SelectDateWidget(empty_label=\"Nothing\"))\n #image = forms.ImageField(label=('Company Logo'), required=False, error_messages={'invalid':(\"Image files only\")}, widget=forms.FileInput)\n image=forms.ImageField()\n #sender = forms.EmailField(help_text='A valid email address, please.')\n\n METHOD = (\n ('C', 'cash'),\n ('B', 'card'),\n ('P', 'point'),\n )\n acount = forms.CharField(label='What is your bill?', widget=forms.Select(choices=METHOD))\n\n \"\"\"class Meta: #이 방식은 fields를 지정해 줘야 한다.\n model = Test\n fields = ('subject', 'image','summary','upload_date','acount')\"\"\" #forms.Form 을 상속했기에 meta는 필요없다.\n #하지만, forms.Form 을 상속했기에 일일이 widget을 지정해야 한다.\n\n\n\nclass ImageForm(forms.ModelForm):\n \"\"\"Form for the image model\"\"\"\n\n class Meta: #이 방식은 fields를 지정해 줘야 한다.\n model = Image\n fields = ('title', 'image')\n\n\nclass ProductForm(forms.ModelForm):\n \"\"\"serial_number = forms.CharField()\n name = forms.CharField(\n max_length=20,\n widget=forms.TextInput(attrs={\n \"class\": \"form-control\",\n \"placeholder\": \"Your Name\"\n })\n )\n\n body = forms.CharField(\n widget=forms.Textarea(\n attrs={\n \"class\": \"form-control\",\n \"placeholder\": \"Leave a comment!\",\n 'cols': 10, 'rows': 10\n })\n )\n # image = forms.ImageField(label=('Company Logo'), required=False, error_messages={'invalid':(\"Image files only\")}, widget=forms.FileInput)\n image = forms.ImageField()\n # sender = forms.EmailField(help_text='A valid email address, please.')\n price=forms.IntegerField()\n \"\"\"\n class Meta:\n model=Product\n fields=('serial_number','name','image','content','price','categories')\n\nclass PcommentForm(forms.ModelForm):\n class Meta:\n model=Pcomment\n fields=('name','content')\n\nclass CommentForm(forms.Form):\n author = forms.CharField(\n max_length=20,\n widget=forms.TextInput(attrs={\n 'size': 20,\n \"class\": \"form-control\",\n \"placeholder\": \"Your Name\"\n })\n )\n body = forms.CharField(\n widget=forms.Textarea(\n attrs={\n \"class\": \"form-control\",\n \"placeholder\": \"Leave a comment!\"\n })\n )\n","sub_path":"mysqltest/realtest/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"610356789","text":"__author__ = 'Rushil'\r\n\r\nimport random\r\n\r\nglobal arr\r\narr = []\r\n\r\n\"\"\"\r\nInstead of pairwise swaps I can also do a Binary Search on the array and do it O(N logN) complexity instead of O(N)\r\n\"\"\"\r\n\r\ndef InsertionSort(arr, elem):\r\n\r\n arr.append(elem)\r\n\r\n for i in range(len(arr) - 1, 0, -1):\r\n\r\n if arr[i] < arr[i - 1]:\r\n arr[i], arr[i - 1] = arr[i - 1], arr[i] #Pairwise Swaps\r\n\r\n else:\r\n break\r\n\r\n return arr\r\n\r\nfor i in range(100):\r\n num = random.randint(0, 100)\r\n InsertionSort(arr, num)\r\n\r\n","sub_path":"InsertionSort.py","file_name":"InsertionSort.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"189356064","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# -*- author:liuguanyu -*-\n# json.loads的补丁\n\nclass JsonPatch :\n @staticmethod\n def decode_list(data):\n rv = []\n for item in data:\n if isinstance(item, unicode):\n item = item.encode('utf-8')\n elif isinstance(item, list):\n item = JsonPatch.decode_list(item)\n elif isinstance(item, dict):\n item = JsonPatch.decode_dict(item)\n rv.append(item)\n return rv\n\n @staticmethod\n def decode_dict(data):\n rv = {}\n for key, value in data.iteritems():\n if isinstance(key, unicode):\n key = key.encode('utf-8')\n if isinstance(value, unicode):\n value = value.encode('utf-8')\n elif isinstance(value, list):\n value = JsonPatch.decode_list(value)\n elif isinstance(value, dict):\n value = JsonPatch.decode_dict(value)\n rv[key] = value\n return rv ","sub_path":"Util/jsonpatch.py","file_name":"jsonpatch.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"128686090","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n\ndef get_drink_dataframe():\n\n columnList = [\"출처지역\", \"종류\", \"도수(%)\", \"가격\", \"원재료\", \"단맛\", \"산미\", \"탁도\",\n \"탄산감\", \"담백\", \"바디\", \"씁쓸\", \"화려\", \"스파이시\", \"고소\", \"신맛\", \"타닌\", \"향\", \"설명\"]\n indexList = [\"1\", \"0\", '오매백주', '오산막걸리', '세종대왕어주 탁주', '술공방 9.0', '수제탁주 바랑', '백년향', '문희 가향주', '구름을 벗삼아', '문희 탁주', '오미자 생막걸리', '오희', '복순도가 손 막걸리', '담은', '펀치 쌀바나나', '세종 알밤주', '괴산 세종 찰옥수수', '조은술 세종 바나나', '우도 땅콩 전통주', '우리술 오늘 탁주', '기다림 34', '기다림 25', '기다림 16', '택이', '천비향 탁주', '술그리다 ', '술예쁘다', '술취한 원숭이', '삼양춘 생탁주', '토박이 한산소곡주', '삼양춘 청주', '복단지', '경성과하주', '세종대왕어주 약주', '구기홍주', '하타', '단상지교', '고흥 유자주', '수제 약주 별바랑', '삼양춘 생약주', '순향주', '우렁이쌀 청주', '술아 국화주', '맑은 문희주', '대윤가야곡 왕주', '니모메', '오메기술13 세트', '청명주 약주', '술아 순곡주', '우리술 오늘 약주', '술아 연화주', '술아 매화주', '솔송주', '천비향 약주', '살아있는 기운 한 모금! 홍삼명주', '감사', '면천두견주', '부자진', '꿀샘16', '독산53', '독산30', '신례명주',\n '진맥소주22', '진맥소주40', '진맥소주53', '귀감', '겨울소주', '설성사또', '병영소주', '문배술 헤리티지23', '문배술 헤리티지25', '문배술 헤리티지40', '안동소주', '설레온', '고소리술', '이도', '고구마증류주', '담솔', '고울달오크', '고울달백자', '문경바람백자', '문경바람오크', '화주', '추사40', '매실원주13', '서울의밤', '미르25', '미르40', '미르54', '술샘16', '오미로제연', '2016크라테산머루레드와인스위트', '혼다주', '요새로제', '더그런치', '스위마마', '댄싱파파', '마셔블랑', '젤코바프리미엄레드', '고도리프리미엄청수화이트', '젤코바스위트와인', '씨엘고도리와이너리화이트', '고도리복숭아와인', 'LESDOM 내���럴 스파클링 로제', 'LESDOM 로제시드르', 'LESDOM 시드르', '참뽕와인', '세인트하우스 아로니아와인', '세인트하우스 오미자와인', '세인트하우스 모과와인', '세인트하우스 가시오가피와인', '세인트하우스 딸기와인', '한스오차드 애플', '애피소드애플', '애피소드상그리아', '오미로제프리미엄와인', '허니비와인', '오미로제스파클링결', '허니문와인', '추사애플와인', '추사블루스위트']\n DrinkDf = pd.read_excel(\n \"술 데이터 분류.xlsx\", sheet_name=\"시트1\", header=None, index_col=1)\n DrinkDf.drop(columns=0, inplace=True)\n DrinkDf.index = indexList\n DrinkDf.columns = columnList\n DrinkDf.drop(index=[\"1\", \"0\"], inplace=True)\n DrinkDf.dropna(axis=1, inplace=True)\n return DrinkDf\n\n\ndef recommendation_drink_of_contents_based(keyword=\"\", stopword=[], top=6):\n # 실제 각행렬간 유사도 계산된것은 이미 DB에 있거나 pickle에 저장된상태\n # 새로운술이 들어오거나 기존의 술이 삭제되었을때에, 계산해둔다.\n\n drink_dataframe = get_drink_dataframe()\n\n # 사용자가 못먹는 원재료가 들어간 술은 추천에서 제외\n drink_dataframe.drop(index=[indexList[i+2] for i, item in enumerate(\n DrinkDf[\"원재료\"]) if len(list(set(stopword) & set(item.split(\",\")))) > 0], inplace=True)\n\n # 출처지역,종류,원재료를 제외한 숫자데이터에서 유사도 추출\n\n drink_dataframe_without_literal = drink_dataframe.drop(\n columns=[\"출처지역\", \"종류\", \"원재료\"])\n\n # MinMax Scaling을 통한 데이터 정규화\n\n scaler = MinMaxScaler()\n scaleList = [\"도수(%)\", \"가격\", \"단맛\", \"산미\", \"탁도\", \"탄산감\", \"담백\",\n \"바디\", \"씁쓸\", \"화려\", \"스파이시\", \"고소\", \"신맛\", \"타닌\", \"향\"]\n drink_dataframe_without_literal[scaleList] = scaler.fit_transform(\n drink_dataframe_without_literal[scaleList])\n\n drink_datafrmae_with_normalization = drink_dataframe_without_literal[scaleList]\n\n # 피어슨&코사인 유사도 계산 dictionary\n similarity_dict = dict()\n\n # 피어스 유사도 추출 후 가장 항목이 높은 5가지 전통주 추천\n pearson_similarity_metrix = drink_datafrmae_with_normalization.T.corr(\n method=\"pearson\").to_numpy()\n index = indexList.index(keyword)-2\n\n topid = sorted(range(len(\n pearson_similarity_metrix[index])), key=lambda i: pearson_similarity_metrix[index][i])[-top:]\n recommendation_drink_of_contents_based_top_five = []\n for i in range(top-2, 0, -1):\n recommendation_drink_of_contents_based_top_five.append([np.array(indexList[2:])[\n topid][:-1][i], round(pearson_similarity_metrix[index][topid][:-1][i]*100, 3)])\n similarity_dict[\"pearson\"] = recommendation_drink_of_contents_based_top_five\n\n # 코사인 유사도 추출후 가장 항목이 높은 5가지 전통주 추천\n\n cosine_similarity_metrix = cosine_similarity(\n drink_datafrmae_with_normalization)\n\n # Test용 index 한개 similarity metrix의 행 번호\n index = indexList.index(keyword)-2\n\n topid = sorted(range(len(\n cosine_similarity_metrix[index])), key=lambda i: cosine_similarity_metrix[index][i])[-top:]\n recommendation_drink_of_contents_based_top_five = []\n for i in range(top-2, 0, -1):\n recommendation_drink_of_contents_based_top_five.append([np.array(indexList[2:])[\n topid][:-1][i], round(cosine_similarity_metrix[index][topid][:-1][i]*100, 3)])\n similarity_dict[\"cosine\"] = recommendation_drink_of_contents_based_top_five\n return similarity_dict\n","sub_path":"sub2/backend/backend/RecommendationSystem/Content_Based_Recommendation.py","file_name":"Content_Based_Recommendation.py","file_ext":"py","file_size_in_byte":6275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"102639054","text":"import matplotlib.pyplot as plt\nimport torch\nimport PIL\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\nimport json\nfrom PIL import Image\nimport Helper\nimport numpy as np\nimport seaborn as sns\nfrom collections import OrderedDict\nimport argparse\n\nparser = argparse.ArgumentParser()\n\ndata_dir = 'flowers'\ntrain_dir = data_dir + '/train'\nvalid_dir = data_dir + '/valid'\ntest_dir = data_dir + '/test'\n\n\n\nparser.add_argument('--hidden_layers',\n action='store',\n default=4096,\n type=int,\n help='Define the amount of hidden layers on the classifier structure')\n\nparser.add_argument('--learning_rate',\n action='store',\n default=0.001,\n type=float,\n help='Define learning rate gradient descent')\n\n\nparser.add_argument('--epochs',\n action='store',\n type=int,\n default=10,\n help='Define epochs for training')\n\nparser.add_argument('--gpu',\n action='store',\n dest='gpu',\n help='Use GPU for training')\n\n\nparser.add_argument('--save-dir',\n action='store',\n dest='save_dir',\n type=str,\n help='Set directory for the checkpoint, if not done all work will be lost')\n\nparser.add_argument('--arch',\n action='store',\n default='vgg16',\n help='Define which learning architectutre will be used')\n\nin_args=parser.parse_args()\narch =in_args.arch\nhidden_layers =in_args.hidden_layers\nepochs =in_args.epochs \nlearning_rate =in_args.learning_rate\ngpu=in_args.gpu\n\n \ntrain_transforms=transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\ntest_validate_transforms = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\n \ntrain_data=datasets.ImageFolder(data_dir +'/train',transform=train_transforms)\ntest_data=datasets.ImageFolder(data_dir + '/test', transform=test_validate_transforms)\nvalid_data = datasets.ImageFolder(data_dir + '/valid', transform=test_validate_transforms)\ntrainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)\ntestloader = torch.utils.data.DataLoader(test_data, batch_size=64)\nvalidloader= torch.utils.data.DataLoader(valid_data, batch_size=64)\n\nif arch == 'densenet121':\n model = models.densenet121(pretrained=True)\n input = 1024\nelif arch == 'vgg16':\n model = models.vgg13(pretrained=True)\n input = 25088\n\nfor param in model.parameters():\n param.requires_grad = False\n \nif in_args.gpu:\n if torch.cuda.is_available():\n device = torch.device(\"cuda\")\n print(\"Training network will be using CUDA as specified\")\n else:\n device = torch.device(\"cpu\")\n print(\"Cuda device is not availabe. Training will continue using CPU\")\n\nimport json\nwith open('cat_to_name.json', 'r') as f:\n cat_to_name = json.load(f)\n\n\nclassifier = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(input,hidden_layers)),\n ('relu1', nn.ReLU()),\n ('drop1', nn.Dropout(0.0)),\n ('fc2', nn.Linear(hidden_layers,102)),\n ('logsoftmax', nn.LogSoftmax(dim=1))]))\n\nmodel.classifier = classifier\n\n\nprint(model)\n\noptimizer = optim.Adam(model.classifier.parameters(), learning_rate)\n\nmodel.to(device)\ncriterion = nn.NLLLoss()\n\n# Implement a function for the validation pass\ndef validation(model, testloader, criterion):\n test_loss = 0\n accuracy = 0\n \n for ii, (inputs, labels) in enumerate(testloader):\n \n inputs, labels = inputs.to(device), labels.to(device)\n \n output = model.forward(inputs)\n test_loss += criterion(output, labels).item()\n \n ps = torch.exp(output)\n equality = (labels.data == ps.max(dim=1)[1])\n accuracy += equality.type(torch.FloatTensor).mean()\n \n return test_loss, accuracy\n\nprint_every=32\nsteps =0\nprint(\"Initialize training .....\\n\")\n\nfor e in range(epochs):\n running_loss = 0\n model.train() \n \n for ii, (inputs, labels) in enumerate(trainloader):\n steps += 1\n \n inputs, labels = inputs.to(device), labels.to(device)\n \n optimizer.zero_grad()\n \n \n outputs = model.forward(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n \n running_loss += loss.item()\n \n if steps % print_every == 0:\n model.eval()\n\n with torch.no_grad():\n valid_loss, accuracy = validation(model, validloader, criterion)\n \n print(\"Epoch: {}/{} | \".format(e+1, epochs),\n \"Training Loss: {:.4f} | \".format(running_loss/print_every),\n \"Validation Loss: {:.4f} | \".format(valid_loss/len(testloader)),\n \"Validation Accuracy: {:.4f}\".format(accuracy/len(testloader)))\n \n running_loss = 0\n model.train()\n \n # TODO: Do validation on the test set\nmodel.eval()\n \nwith torch.no_grad():\n _, accuracy = validation(model, testloader, criterion)\n \nprint(\"Test Accuracy on the model: {:.2f}%\".format(accuracy*100/len(testloader)))\n\nmodel.class_to_idx = train_data.class_to_idx\n\ncheckpoint = {\n 'model': model,\n 'classifier': model.classifier,\n 'input_size': model.classifier[0].in_features,\n 'state_dict': model.state_dict(),\n 'class_to_idx': model.class_to_idx,\n 'learning_rate': learning_rate,\n 'optimizer': optimizer.state_dict(),\n 'epoch': epochs,\n }\n\ntorch.save(checkpoint, 'project_checkpoint.pth')\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"120951826","text":"from __future__ import annotations\n\nfrom datetime import datetime\n\nfrom requests import get\nfrom sqlalchemy import Boolean, String, Table, ForeignKey\nfrom sqlalchemy import Column, DateTime\nfrom sqlalchemy.orm import Session, relationship\nfrom sqlalchemy_utils import UUIDType\nfrom urllib3.exceptions import NewConnectionError\n\nfrom app.models.base import Base, db_session\nfrom app.models.mixins import CreatedAtMixin, UpdatedAtMixin\n\nds_host_relation = Table('ds_host_relation', Base.metadata,\n Column('host', String(),\n ForeignKey(f'hosts.url', ondelete=\"CASCADE\", )),\n Column('device', UUIDType(),\n ForeignKey(f'device_switch.identifier', ondelete=\"CASCADE\"))\n )\n\n\nclass Host(CreatedAtMixin, UpdatedAtMixin, Base):\n __tablename__ = 'hosts'\n url = Column(String(), primary_key=True)\n is_online = Column(Boolean(), nullable=False, default=False)\n last_time_was_saw_online = Column(DateTime, default=datetime.utcnow, index=True)\n device_switch = relationship(\"DeviceSwitch\", secondary=ds_host_relation,\n back_populates=\"hosts\")\n\n def check_online(self, db: Session = db_session):\n\n try:\n response = get(url=f'http://{self.url}/0')\n print(response.status_code)\n print(f'http://{self.url}/0')\n if response.status_code == 200:\n self.last_time_was_saw_online = datetime.utcnow()\n self.is_online = True\n db.commit()\n return\n except Exception as e:\n pass\n self.is_online = False\n db.commit()\n time_delta = (datetime.utcnow() - self.last_time_was_saw_online )\n total_seconds = time_delta.total_seconds()\n minutes = total_seconds / 60\n print(minutes)\n if minutes > 2:\n self.delete(db=db)\n\n def add(self, db: Session = db_session):\n try:\n db.add(self)\n db.commit()\n except Exception as e:\n db.rollback()\n raise e\n\n @classmethod\n def query_by_url(cls, url, db: Session = db_session) -> Host:\n return db.query(cls).filter(cls.url == url).first()\n\n def delete(self, db: Session = db_session):\n db.delete(self)\n db.commit()\n\n @classmethod\n def get_all(cls, db: Session = db_session):\n return db.query(cls).all()\n","sub_path":"src/app/models/Hosts.py","file_name":"Hosts.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"364694377","text":"from inspect import getmembers, ismethod\nfrom server.arbuz.base import *\nfrom django import template\nregister = template.Library()\n\nclass Base_Tag_Manager(Dynamic_Base):\n\n def __init__(self, task, values, request=None):\n Dynamic_Base.__init__(self, request)\n self.values = values\n\n methods = getmembers(self, predicate=ismethod)\n methods = [method[0] for method in methods]\n\n for method in methods:\n if task in method:\n self.OUT = getattr(self.__class__, method)(self)\n","sub_path":"server/arbuz/templatetags/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"42224031","text":"import json\nfrom collections import OrderedDict\n\nfrom coverage.html import escape\n\nfrom mangrove.datastore.entity import get_all_entities\nfrom mangrove.errors.MangroveException import DataObjectNotFound\nfrom mangrove.form_model.field import UniqueIdUIField, field_attributes\n\n\ndef geo_jsons(manager, entity_type, filters, details, specials):\n entity_fields = manager.view.registration_form_model_by_entity_type(key=[entity_type], include_docs=True)[0][\"doc\"][\"json_fields\"]\n\n geo_jsons = [{\n \"name\": entity_type.capitalize(),\n \"data\": _geo_json(manager, entity_type, entity_fields, dict(filters), details),\n \"color\": \"rgb(104, 174, 59)\"\n }]\n\n for special in specials:\n field = [field for field in entity_fields if field['code'] == special][0]\n group = {\"group\": field['label'], \"data\": []}\n for choice in specials[special]:\n filters_with_special = dict(filters)\n filters_with_special.update({special: choice['value']})\n is_geojson_for_special_required = True\n if special in filters.keys() and choice['value'] not in dict(filters).get(special):\n is_geojson_for_special_required = False\n matched_choices = [c['text'] for c in field['choices'] if c['val'] == choice['value']]\n if matched_choices:\n data = _geo_json(manager, entity_type, entity_fields, filters_with_special,\n details) if is_geojson_for_special_required else {'features': [],\n 'type': 'FeatureCollection'}\n group[\"data\"].append({\n \"name\": matched_choices[0],\n \"data\": data,\n \"color\": choice['color']\n })\n geo_jsons.append(group)\n\n return json.dumps(geo_jsons)\n\n\ndef get_first_geocode_field_for_entity_type(entity_all_fields):\n geocode_fields = [f for f in\n entity_all_fields if\n f[\"type\"] == \"geocode\"]\n return geocode_fields[0] if len(geocode_fields) > 0 else None\n\n\ndef get_location_list_for_entities(first_geocode_field, unique_ids):\n location_list = []\n for entity in unique_ids:\n value_dict = entity.data.get(first_geocode_field[\"name\"])\n if value_dict and value_dict.has_key('value'):\n value = value_dict[\"value\"]\n location_list.append(_to_json_point(value))\n return location_list\n\n\ndef get_location_list_for_datasenders(datasenders):\n location_list = []\n for entity in datasenders:\n geocode = entity.geometry\n if geocode:\n value = (geocode[\"coordinates\"][0], geocode[\"coordinates\"][1])\n location_list.append(_to_json_point(value))\n return location_list\n\n\ndef _geo_json(dbm, entity_type, entity_fields, filters, details):\n location_list = []\n\n try:\n forward_filters, reverse_filters = _transform_filters(filters, entity_fields)\n first_geocode_field = get_first_geocode_field_for_entity_type(entity_fields)\n if first_geocode_field:\n unique_ids = get_all_entities(\n dbm, [entity_type], 1000, forward_filters, reverse_filters\n )\n details.extend(['q2'])\n fields_to_show = filter(lambda field: field['code'] in details, entity_fields)\n location_list.extend(_get_detail_list_for_entities(\n _get_field_labels(fields_to_show),\n first_geocode_field,\n unique_ids\n ))\n\n except DataObjectNotFound:\n pass\n\n return {\"type\": \"FeatureCollection\", \"features\": location_list}\n\n\ndef _transform_filters(filters, entity_all_fields):\n d = dict((field['code'], field) for field in entity_all_fields)\n forward_filters = {}\n reverse_filters = {}\n for f in filters:\n if len(f.split(\",\")) > 1 or d[f][\"type\"] == field_attributes.UNIQUE_ID_FIELD:\n if \"\" not in filters[f]:\n if len(f.split(\",\")) > 1:\n reverse_filters[filters[f][0]] = [d[qn]['name'] for qn in f.split(\",\")]\n else:\n forward_filters[d[f]['name']] = filters[f][0]\n else:\n forward_filters[d[f]['name']] = \\\n [choice['text'] for choice in d[f]['choices'] if choice['val'] in filters[f]]\n return forward_filters, reverse_filters\n\n\ndef _get_entity_options(dbm, entity_type):\n return [(entity.short_code, escape(entity.data['name']['value'])) for entity in get_all_entities(dbm, [entity_type])]\n\n\ndef _get_field_labels(entity_fields):\n dict_simplified = OrderedDict()\n for field in entity_fields :\n dict_simplified[field['name']] = field['label']\n return dict_simplified\n\n\ndef _get_detail_list_for_entities(entity_field_labels, first_geocode_field, unique_ids):\n detail_list = []\n for entity in unique_ids:\n value_dict = entity.data.get(first_geocode_field[\"name\"])\n if value_dict and value_dict.has_key('value'):\n value = value_dict[\"value\"]\n detail_list.append(_to_json_detail(value, entity_field_labels, entity.data, entity.type_string))\n return detail_list\n\n\ndef _to_json_detail(value, entity_field_labels, data=None, entity_type=None):\n detail_json = _to_json_point(value)\n detail_json['properties'] = _simplify_field_data(data, entity_field_labels, entity_type)\n return detail_json\n\n\ndef _to_json_point(value):\n point_json = { \"type\": \"Feature\", \"geometry\":\n {\n \"type\": \"Point\",\n \"coordinates\": [\n value[1],\n value[0]\n ]\n }\n }\n return point_json\n\n\ndef _simplify_field_data(data, entity_field_labels, entity_type=None):\n simple_data = OrderedDict()\n\n if entity_type is not None:\n simple_data['entity_type'] = {}\n simple_data['entity_type'][\"value\"] = entity_type\n simple_data['entity_type'][\"label\"] = \"\"\n\n entity_details = [(key, data.get(key)) for key in entity_field_labels if key in data.keys()]\n\n for key, value_field in entity_details:\n one_field_data = {}\n one_field_data[\"value\"]= value_field[\"value\"]\n\n if key != \"entity_type\":\n if key == \"mobile_number\" and entity_type is None:\n one_field_data[\"label\"]= entity_field_labels[\"telephone_number\"]\n else:\n one_field_data[\"label\"]= entity_field_labels[key]\n else:\n one_field_data[\"label\"] = \"\"\n\n simple_data[key] = one_field_data\n\n return simple_data\n","sub_path":"datawinners/entity/geo_data.py","file_name":"geo_data.py","file_ext":"py","file_size_in_byte":6599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"237396576","text":"##\n## Imprima la suma de la columna 2 por cada letra \n## de la columna 4, ordnados alfabeticamente.\n##\n## a,114\n## b,40\n## c,91\n## d,65\n## e,79\n## f,110\n## g,35\n##\ndata2=open('data.csv','r').readlines()\ndata3 = [row[0:-1] for row in data2]\ndata4 = [row.split('\\t') for row in data3]\ndata5 = [z[0:3] + [ z[3].split(',')] + z[4:] for z in data4]\ngrupoletras = [row[3] for row in data5]\ncolsololetras=[]\nfor fila in grupoletras:\n for x in fila:\n colsololetras.append(x)\nsololetrasord = sorted(set(colsololetras))\n##\nfor w in sololetrasord:\n sum=0\n for row in data5:\n for x in row[3]:\n if x == w:\n sum = sum + int(row[1]) \n print(w+','+str(sum))\n##","sub_path":"q12.py","file_name":"q12.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"495150788","text":"\n# MULTI STOP ROUTE OPTIMIZATION DEMO\n\n#%%\nimport geopandas as gpd\nimport utils.travel_times as tts\nimport utils.routes_tt as rtts\n\ndigitransit = False\n\n#%%\n# read and filter test data (cinemas as stops)\ncinemas = gpd.read_file('data/temp/cinemas.shp')\nlarge_cinemas = cinemas.loc[cinemas['rooms'] > 1]\ntarget_points = large_cinemas[:8]\n\n#%%\n# get and gather target_info (ykr_ids, names & addresses)\ntarget_info = tts.gather_target_info(target_points, 'name', 'address_y', digitransit)\nprint(target_info)\n\n#%%\n# read and gather only relevant travel time dataframes to a dictionary\ntts_dict = tts.get_tt_between_targets_matrix(target_info, 'data/HelsinkiTravelTimeMatrix2018/')\n\n#%%\n# find and collect all possible route options\ntarget_perms = rtts.get_target_permutations(tts_dict)\n\n#%%\n# extract and collect travel times between stops for all route options\nperms_ttimes = rtts.get_all_ttimes(target_perms, tts_dict)\n\n#%%\n# calculate total travel times for all route options\nall_ttimes_summary = rtts.calculate_total_ttimes(perms_ttimes, target_info)\n\n#%%\n# get best routes from all route options by minimizing total travel time\nbest_routes = rtts.get_best_routes(all_ttimes_summary, '', '')\n\n#%%\n# print 8 best routes\nrtts.print_best_route_info(best_routes, target_info)\n\n#%%\n","sub_path":"demo/optimize_route.py","file_name":"optimize_route.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"495011728","text":"# #!/usr/bin/env python3\n\n# create a list\nmy_list = [\"192.168.0.5\", 5060, \"UP\"]\n\n# display first item of list\nprint(\"The first item in the list (IP): \" + my_list[0])\n\n# display second item of list\nprint(\"The second item in the list (port): \" + str(my_list[1]))\n\n# display third item of list\nprint(\"The last item in the list (state): \" + my_list[2])\n\nnew_list = [5060, \"80\", 55, \"10.0.0.1\", \"10.20.30.1\", \"ssh\"]\n\n\n# When I ssh into IP addresses 10.0.0.1 or 10.20.30.1 I am unable to ping ports 5060, 80, or 55.\nssh = new_list[-1]\nportOne = str(new_list[0])\nportTwo = new_list[1]\nportThree = str(new_list[2])\nipAddressOne = new_list[3]\nipAddressTwo = new_list[4]\nprint(\"When I ssh into an IP addresses \" + ipAddressOne + \" or \" + ipAddressTwo + \" I am unable to ping ports \" + portOne\n + \", \" + portTwo + \", \" + portThree)\n\n\n\n","sub_path":"mix-list/mixlist01.py","file_name":"mixlist01.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"59190716","text":"import os\nimport mock\nimport httplib2\n\nfrom keystoneclient import shell as x7_shell\nfrom keystoneclient import exceptions\nfrom tests import utils\n\n\nclass ShellTest(utils.TestCase):\n\n # Patch os.environ to avoid required auth info.\n def setUp(self):\n global _old_env\n fake_env = {\n 'OS_USERNAME': 'username',\n 'OS_PASSWORD': 'password',\n 'OS_TENANT_ID': 'tenant_id',\n 'OS_AUTH_URL': 'http://127.0.0.1:5000/v2.0',\n }\n _old_env, os.environ = os.environ, fake_env.copy()\n\n # Make a fake shell object, a helping wrapper to call it, and a quick\n # way of asserting that certain API calls were made.\n global shell, _shell, assert_called, assert_called_anytime\n _shell = x7_shell.X7IdentityShell()\n shell = lambda cmd: _shell.main(cmd.split())\n\n def tearDown(self):\n global _old_env\n os.environ = _old_env\n\n def test_help_unknown_command(self):\n self.assertRaises(exceptions.CommandError, shell, 'help foofoo')\n\n def test_debug(self):\n httplib2.debuglevel = 0\n shell('--debug help')\n assert httplib2.debuglevel == 1\n","sub_path":"x7-src-client/python-keystoneclient/tests/test_shell.py","file_name":"test_shell.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"599527102","text":"from chx_xpcs.io.eiger.compress_file import compress_file\nimport time\nfrom chx_xpcs.io.eiger.compress_file2 import compress_file as compress_file2\n\nfilename = \"../../sample_data/flow10crlT0_EGhtd_011_66/flow10crlT0_EGhtd_011_66_master.h5\".encode(\"utf-8\")\ndataset_prefix = \"entry/data_\".encode(\"utf-8\")\ndataset_root = \"/entry\".encode(\"utf-8\")\nout_filename = \"out_version1_small.bin\".encode(\"utf-8\")\n\nprint(\"begin compression\")\nt1 = time.time()\ncompress_file(filename, dataset_root, dataset_prefix, out_filename)\nt2 = time.time()\nprint(\"end. took {} seconds\".format(t2-t1))\n\nprint(\"begin compression version 2 (python API)\")\nt1 = time.time()\ncompress_file2(filename, dset_min=0, dset_max=9, dset_pref=\"data_\",\n dset_root=\"/entry\", outfile=\"out_version2_small.bin\")\nt2 = time.time()\nprint(\"end. took {} seconds\".format(t2-t1))\n\n","sub_path":"tests/test_compress_fast.py","file_name":"test_compress_fast.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"505471797","text":"#FIRST PART FUNCTION---------------\ndef myMin(targetList):\n a=targetList[0]\n for item in targetList:\n if itema:\n a=item\n return a\n\ndef mySum(targetList):\n s=0\n for item in targetList:\n s=item+s\n return s\n\ndef myAvge(targetList):\n return sum(targetList)/len(targetList)\n#END---------------\n\n#SECOND PART FUNCTION---------------\ndef findPosition(myArray):\n retVal = []\n for i in range(len(myArray)):\n for j in range(len(myArray[i])):\n if(myArray[i][j]==-2):\n retVal.append([i,j])\n return retVal\n\ndef findExits(myArray):\n retVal = []\n for i in range(len(myArray)):\n for j in range(len(myArray[i])):\n if i == 0 or j==0 or i==len(myArray)-1 or j == len(myArray)-1:\n if(myArray[i][j]==0):\n retVal.append([i,j])\n return retVal\n\ndef getDistance(pointOne,pointTwo):\n x=abs(pointOne[0]-pointTwo[0])\n y=abs(pointOne[1]-pointTwo[1])\n return x+y\n\ndef readFromFile(filePath):\n with open(filePath, 'r') as f:\n l = [[int(num) for num in line.split(' ')] for line in f]\n print(l)\n\n#END---------------\n\n#THIRD PART FUNCTIONS-----------------------------\ndef isCoordValid(coord,matrix):\n width = len(matrix[0])\n height = len(matrix)\n if coord[0]>=width or coord[0]<0 or coord[1]>=height or coord[1]<0 or matrix[coord[0]][coord[1]]!=0:\n return False\n return True\n\ndef printMatrix(targetMatrix):\n for item in targetMatrix:\n print(item)\ndef lee(matrix,startCoord,endCoord):\n listToBeSearched =[]\n listToBeSearched.append(startCoord)\n matrix[startCoord[0]][startCoord[1]]=1\n while len(listToBeSearched)!=0 and not endCoord in listToBeSearched:\n # print(\"A2 \"+str(listToBeSearched))\n # printMatrix(matrix)\n targetCoord = listToBeSearched.pop(0)\n \n upCoord = [targetCoord[0],targetCoord[1]+1]\n rightCoord =[targetCoord[0]+1,targetCoord[1]]\n downCoord = [targetCoord[0],targetCoord[1]-1]\n lefCoord = [targetCoord[0]-1,targetCoord[1]]\n\n if isCoordValid(upCoord,matrix):\n matrix[upCoord[0]][upCoord[1]] = matrix[targetCoord[0]][targetCoord[1]]+1\n listToBeSearched.append(upCoord)\n if isCoordValid(rightCoord,matrix):\n matrix[rightCoord[0]][rightCoord[1]] =matrix[targetCoord[0]][targetCoord[1]]+1\n listToBeSearched.append(rightCoord)\n if isCoordValid(downCoord,matrix):\n matrix[downCoord[0]][downCoord[1]] =matrix[targetCoord[0]][targetCoord[1]]+1\n listToBeSearched.append(downCoord)\n if isCoordValid(lefCoord,matrix):\n matrix[lefCoord[0]][lefCoord[1]] =matrix[targetCoord[0]][targetCoord[1]]+1\n listToBeSearched.append(lefCoord)\n matrix[endCoord[0]][endCoord[1]]=15 \n return matrix\n\ndef traceBack(matrix, endPoint,startPoint):\n steps = []\n steps.append(endPoint)\n currentCoord = endPoint\n while currentCoord!=startPoint:\n currentCoord=getLowestNeighboor(matrix,currentCoord)\n steps.append(currentCoord)\n return steps\n\ndef getLowestNeighboor(matrix, targetCoord):\n\n minValue = matrix[targetCoord[0]][targetCoord[1]]\n\n upCoord = [targetCoord[0],targetCoord[1]+1]\n rightCoord =[targetCoord[0]+1,targetCoord[1]]\n downCoord = [targetCoord[0],targetCoord[1]-1]\n lefCoord = [targetCoord[0]-1,targetCoord[1]]\n\n upValue = matrix[upCoord[0]][upCoord[1]]\n rightValue = matrix[rightCoord[0]][rightCoord[1]]\n downValue = matrix[downCoord[0]][downCoord[1]]\n leftValue = matrix[lefCoord[0]][lefCoord[1]]\n if upValue 0 else 0\n r = hits / r_sum if r_sum > 0 else 0\n f1 = 2 * p * r / (p + r) if (p + r) > 0 else 0\n return p, r, f1\n\ndef eval(gold_data, pred_data):\n \"\"\"评估F1值\"\"\"\n assert len(gold_data) == len(pred_data)\n golds = []\n preds = []\n eids = list(gold_data.keys())\n for eid in eids:\n gold_type = gold_data[eid]\n pred_type = pred_data[eid]\n golds.append(gold_type)\n preds.append(pred_type)\n assert len(golds) == len(preds)\n _, _, f1 = cal_f1_score(preds, golds)\n print('Test F1 score {}%'.format(round(f1 * 100, 4)))\n\n# calculate f1\ngold_test = load_json('dev_label.json') \npred_test = load_json('dev_torch.json')\neval(gold_test, pred_test)\n","sub_path":"call_f1.py","file_name":"call_f1.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"303909996","text":"u\"\"\"Message definitions to be passed to SciterProcX function.\n\n\"\"\"\nfrom __future__ import absolute_import\nimport enum\n\nfrom ctypes import Structure, Union, c_void_p\nfrom sciter.capi.sctypes import UINT, BOOL, HDC\nfrom sciter.capi.scdef import ELEMENT_BITMAP_RECEIVER\nfrom sciter.capi.scdom import HELEMENT\n\n\nclass SCITER_X_MSG_CODE(enum.IntEnum):\n u\"\"\"SCITER_X_MSG message/function identifier.\"\"\"\n SXM_CREATE = 0\n SXM_DESTROY = 1\n SXM_SIZE = 2\n SXM_PAINT = 3\n# end\n\n\nclass SCITER_X_MSG(Structure):\n u\"\"\"Common header of message structures passed to SciterProcX.\"\"\"\n _fields_ = [\n (u\"msg\", UINT), # SCITER_X_MSG_CODE\n ]\n\n\nclass SCITER_X_MSG_CREATE(Structure):\n u\"\"\"Create event passed to Sciter.\"\"\"\n _fields_ = [\n (u\"header\", SCITER_X_MSG),\n (u\"backend\", UINT),\n (u\"transparent\", BOOL),\n ]\n\n\nclass SCITER_X_MSG_DESTROY(Structure):\n u\"\"\"Destroy event passed to Sciter.\"\"\"\n _fields_ = [\n (u\"header\", SCITER_X_MSG),\n ]\n\n\nclass SCITER_X_MSG_SIZE(Structure):\n _fields_ = [\n (u\"header\", SCITER_X_MSG),\n (u\"width\", UINT),\n (u\"height\", UINT),\n ]\n\n\nclass SCITER_PAINT_TARGET_TYPE(enum.IntEnum):\n SPT_DEFAULT = 0 # default rendering target - window surface\n SPT_RECEIVER = 1 # target::receiver fields are valid\n SPT_DC = 2 # target::hdc is valid\n\n\nclass SCITER_X_MSG_PAINT_RECEIVER(Structure):\n _fields_ = [\n (u\"param\", c_void_p),\n (u\"callback\", ELEMENT_BITMAP_RECEIVER),\n ]\n\n\nclass SCITER_X_MSG_PAINT_TARGET(Union):\n _fields_ = [\n (u\"hdc\", HDC),\n (u\"receiver\", SCITER_X_MSG_PAINT_RECEIVER),\n ]\n\n\nclass SCITER_X_MSG_PAINT(Structure):\n _fields_ = [\n (u\"header\", SCITER_X_MSG),\n (u\"element\", HELEMENT), # layer #HELEMENT, can be NULL if whole tree (document) needs to be rendered.\n (u\"isFore\", BOOL), # if element is not null tells if that element is fore-layer.\n (u\"targetType\", UINT), # one of SCITER_PAINT_TARGET_TYPE values.\n (u\"target\", SCITER_X_MSG_PAINT_TARGET)\n ]\n","sub_path":"sciter/capi/scmsg.py","file_name":"scmsg.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"77735257","text":"import argparse\nimport configparser\nimport sys\nimport yaml\nfrom datetime import datetime\n\ndef add_numbers(number, other_number, output):\n result = number * other_number\n print(f'[{datetime.utcnow().isoformat()}] The result is {result}', file=output)\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(formatter_class=argparse.rgumentDefaultsHelpFormatter)\n\n parser.add_argument('--config', '-c', type=argparse.FileType('r'), help='config file', default='/etc/automate.ini')\n # Added Argument Parsing Functionality\n parser.add_argument('-o', dest='output', type=argparse.FileType('w'), help='output file', default=sys.stdout)\n\n args = parser.parse_args()\n\n if args.config:\n config = configparser.ConfigParser()\n config.read_file(args.config)\n # Transforming values into integers\n args.n1 = int(config['ARGUMENTS']['n1'])\n args.n2 = int(config['ARGUMENTS']['n2'])\n\n add_numbers(args.n1, args.n2, args.output)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"537420343","text":"from pandas import read_excel, read_sql\nfrom sqlite3 import connect\nfrom openpyxl import load_workbook\nfrom datetime import datetime, timedelta\nfrom logUtil import init_logging\nlogger = init_logging()\n\n\nclass PdUtilV2(object):\n def __init__(self):\n self.db = 'atthelper.db'\n\n def db_operator(self, sql, op):\n \"\"\"\n 数据库操作,\n :param sql: sql语句\n :param op: 操作类型, s:查询, iu:insert update\n :return: query result or None\n \"\"\"\n logger.info('SQL语句为: %s' % sql)\n conn = connect(self.db)\n cursor = conn.cursor()\n res = ''\n if 's' == op:\n logger.info('走查询流程-------------------------')\n res = cursor.execute(sql).fetchall()\n logger.info('SQL查询结果为: %s' % res)\n elif 'iu' == op:\n logger.info('走insert、update流程-------------------------')\n cursor.execute(sql)\n conn.commit()\n res = None\n cursor.close()\n conn.close()\n return res\n\n def read_excel_to_sqlite(self, excel, sheet):\n \"\"\"\n 将excel读取到sqlite\n :param excel: excel路径\n :param sheet: 工作表名称\n :return: 无\n \"\"\"\n df = read_excel(io=excel, sheet_name=sheet, header=0, engine='openpyxl')\n engine = connect(self.db)\n df.to_sql(name='attendance', con=engine, if_exists='replace')\n\n def update_yesterday(self, atttuple):\n \"\"\"\n 将当天打卡时间早于5点的打卡数据作为头一天的下班打卡记录\n :param atttuple:\n :return:\n \"\"\"\n # 将传入的日期减一,并只取日期\n to_datetime = datetime.strptime(atttuple[-1], '%Y-%m-%d %H:%M:%S') + timedelta(days=-1)\n yesterday = to_datetime.date()\n logger.info('头一天的日期为: %s' % yesterday)\n\n # 查询传入的人员头一天的考勤记录sql\n yesterday_his_sql = \"select name, service, end from attendance_result where name='{name}' and service='{service}' and strftime('%Y-%m-%d', end) = '{yest}';\".format(\n name=atttuple[0], service=atttuple[1], yest=yesterday)\n query_res = self.db_operator(sql=yesterday_his_sql, op='s')\n logger.info('头一天的考勤记录查询结果为: %s' % query_res)\n\n if len(query_res) == 1:\n update_sql = \"update attendance_result set end='{endtime}' where name='{name}' and service='{service}' and strftime('%Y-%m-%d %H:%M:%S', end)='{attime}';\".format(\n endtime=atttuple[-1], name=atttuple[0], service=atttuple[1], attime=query_res[0][-1])\n self.db_operator(sql=update_sql, op='iu')\n else:\n logger.error('头一天的考勤记录查询结果不唯一')\n\n def deal_bf5(self):\n bf5_sql = \"select name, service, start from attendance_result where strftime('%H', start) < '05';\"\n res = self.db_operator(sql=bf5_sql, op='s')\n\n # [('剁椒', 'Z00003', '2021-09-08 04:19:31')]\n if res is not None and len(res) != 0:\n for i in range(len(res)):\n self.update_yesterday(res[i])\n\n def deal_to_result_table(self):\n \"\"\"\n 查同时有上班打卡和下班打开记录的考勤信息\n :param excel:\n :param sheetname:\n :return:\n \"\"\"\n sql = \"\"\"select t2.name, t2.company, t2.service, t2.start, t2.end, t2.terminal, t2.attdate\n from (select t.name, t.company, t.service, min(t.atttime) as start, max(t.atttime) as end, t.terminal, strftime('%Y-%m-%d', t.atttime) as attdate\n from attendance t\n group by name, strftime('%Y%m%d', t.atttime)\n order by name) t2\n order by name;\"\"\"\n\n engine = connect(self.db)\n df = read_sql(sql=sql, con=engine)\n df.to_sql(name='attendance_result', con=engine, if_exists='replace')\n\n def update_start_or_end(self):\n \"\"\"\n 更新只有一次打卡记录的数据\n 早于18点按上班打卡处理\n 晚于18点按下班打卡处理\n :return:\n \"\"\"\n conn = connect(self.db)\n cursor = conn.cursor()\n update_start = \"\"\"update attendance_result set start=null where start=end and strftime('%H', start) >= 18;\"\"\"\n update_end = \"\"\"update attendance_result set end=null where start=end and strftime('%H', start)<18;\"\"\"\n\n self.db_operator(sql=update_start, op='iu')\n self.db_operator(sql=update_end, op='iu')\n\n def write_to_excel(self, excel, sheetname='打卡记录', startrow=1):\n sql = \"\"\"select t2.name as 姓名, t2.company as 公司, t2.service as 外包服务编号, t2.start as 上班时间, t2.end as 下班时间, t2.terminal as 终端, t2.attdate as 打卡日期\n from attendance_result t2\n order by t2.name;\"\"\"\n\n conn = connect(self.db)\n\n df = read_sql(sql=sql, con=conn)\n df.to_excel(excel_writer=excel, sheet_name=sheetname)\n\n\nif __name__ == '__main__':\n pd2 = PdUtilV2()\n pd2.deal_bf5()","sub_path":"pdUtilV2.py","file_name":"pdUtilV2.py","file_ext":"py","file_size_in_byte":5051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"392995405","text":"## Simply outputs a video of bounding boxes\n\nimport cv2\nimport scipy as sp\nimport numpy as np\n\ncap = cv2.VideoCapture()\n#http://www.chart.state.md.us/video/video.php?feed=13015dbd01210075004d823633235daa\n#Use this until we find a better traffic camera\ncap.open('./highway/input/in%06d.jpg')\nw = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\nh = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\nout = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc('X','V','I','D'), 60, (w,h), True)\n#bg subtractor\nfgbg = cv2.createBackgroundSubtractorKNN()\n#parameters for blob detector\nparams = cv2.SimpleBlobDetector_Params()\nparams.minThreshold = 0\nparams.maxThreshold = 123\nparams.filterByArea = True\nparams.minArea = 5\nparams.maxArea = 3384\nparams.filterByConvexity = True\nparams.minConvexity = 0.5622\ndetector = cv2.SimpleBlobDetector_create(params)\n\ncv2.namedWindow(\"Stream\", cv2.WINDOW_NORMAL)\ncv2.resizeWindow(\"Stream\", w, h)\n\nconfmat = np.zeros((2,2))\nscore = float(0)\nwhile(cap.isOpened()):\n ret, frame = cap.read()\n if ret == True:\n img1 = sp.zeros(frame.size, sp.uint8)\n img1 = frame\n #bg subtract\n img2 = fgbg.apply(frame)\n #invert image\n cv2.bitwise_not(img2, img2)\n #gaussian\n img2 = cv2.GaussianBlur(img2,(19, 19),6.5)\n #blob detect\n points = detector.detect(img2)\n #draw bounding boxes\n for p in points:\n x1 = int(p.pt[0]-p.size/2)\n y1 = int(p.pt[1]-p.size/2)\n x2 = int(p.pt[0]+p.size/2)\n y2 = int(p.pt[1]+p.size/2)\n cv2.rectangle(img1,(x1,y1),(x2,y2),(0,0,255),1)\n\n cv2.imshow(\"Stream\", img1)\n out.write(img1)\n #cv2.waitKey(67) waits for 0.067 seconds making this ~15fps\n #Stop loop with \"q\"\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n else: break\n\ncap.release()\nout.release()\ncv2.destroyAllWindows()\n","sub_path":"createvid.py","file_name":"createvid.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"331455710","text":"# Copyright (c) Facebook, Inc., its affiliates and Kakao Brain. All Rights Reserved\n\nimport contextlib\nimport itertools as it\n\nimport torch\nimport torch.nn as nn\nfrom fairseq.models import FairseqEncoder\nfrom fairseq.models.wav2vec.wav2vec2_asr import (\n Linear,\n Wav2VecCtc,\n base_architecture,\n)\nfrom fairseq.tasks.audio_pretraining import AudioPretrainingTask\nfrom wav2letter.criterion import CpuViterbiPath, get_data_ptr_as_bytes\nfrom wav2letter.decoder import CriterionType\n\n\nclass BrainWav2VecEncoder(FairseqEncoder): # build wav2vec model w/ pretrained args?\n \"\"\" Modified from https://github.com/pytorch/fairseq \"\"\"\n\n def __init__(self, args, tgt_dict=None, pretrain_args=None): # run when BrainWav2VecEncoder is initialized (as w2v_encoder when BrainWav2VecCtc is initialized in submodules.py: 126)\n self.apply_mask = args.apply_mask\n\n arg_overrides = {\n \"dropout\": args.dropout,\n \"activation_dropout\": args.activation_dropout,\n \"dropout_input\": args.dropout_input,\n \"attention_dropout\": args.attention_dropout,\n \"mask_length\": args.mask_length,\n \"mask_prob\": args.mask_prob,\n \"mask_selection\": args.mask_selection,\n \"mask_other\": args.mask_other,\n \"no_mask_overlap\": args.no_mask_overlap,\n \"mask_channel_length\": args.mask_channel_length,\n \"mask_channel_prob\": args.mask_channel_prob,\n \"mask_channel_selection\": args.mask_channel_selection,\n \"mask_channel_other\": args.mask_channel_other,\n \"no_mask_channel_overlap\": args.no_mask_channel_overlap,\n \"encoder_layerdrop\": args.layerdrop,\n \"feature_grad_mult\": args.feature_grad_mult,\n }\n\n w2v_args = pretrain_args # w2v_args = pretrain_args\n assert (args.normalize == w2v_args.normalize\n ), \"Fine-tuning works best when data normalization is the same\"\n\n for arg_name, arg_val in arg_overrides.items():\n setattr(args, arg_name, arg_val)\n\n w2v_args.data = args.data\n task = AudioPretrainingTask.setup_task(w2v_args) # set up AudioPretrainingTask; # w2v_args.arch='wav2vec2'\n model = task.build_model(w2v_args) # Build the :class:`~fairseq.models.BaseFairseqModel` instance for task 'AudioPretrainingTask' # build model (AudioPretrainingTask.build_model) by using info: w2v_args.arch='wav2vec2'\n # model (checked structure and type via log) = Wav2Vec2Model\n model.remove_pretraining_modules()\n super().__init__(task.source_dictionary) # task.source_dictionary: None\n\n d = w2v_args.encoder_embed_dim # d = 1024\n\n self.w2v_model = model # w2v_model = Wav2Vec2Model (l53)\n\n self.final_dropout = nn.Dropout(args.final_dropout) # set up dropout (to prevent overfitting)\n self.freeze_finetune_updates = args.freeze_finetune_updates\n self.num_updates = 0\n\n if tgt_dict is not None:\n self.proj = Linear(d, len(tgt_dict)) # changes this to vocab size so that we can run argmax (create learnable variables (out_features, in_features) to fit length of tgt_dict)\n elif getattr(args, \"decoder_embed_dim\", d) != d: # self.proj.weight.shape: torch.Size([108, 1024])\n self.proj = Linear(d, args.decoder_embed_dim)\n else:\n self.proj = None\n\n def set_num_updates(self, num_updates):\n \"\"\"Set the number of parameters updates.\"\"\"\n super().set_num_updates(num_updates)\n self.num_updates = num_updates\n\n def forward(self, source, padding_mask, tbc=True, **kwargs): # Gets run automatically when BrainWav2VecEncoder class called, b/c nn.Module works like that\n w2v_args = {\n \"source\": source, # 'source' = signal tensor; 'padding_mask' = same-sized tensor as 'source' but filled w/ False; 'mask' = bool\n \"padding_mask\": padding_mask,\n \"mask\": self.apply_mask and self.training,\n }\n\n ft = self.freeze_finetune_updates <= self.num_updates # ft: False, self.freeze_finetune_updates: 10000, self.num_updates: 0\n\n with torch.no_grad() if not ft else contextlib.ExitStack(): # disables gradient calculations (since inferring, no need for backtracking)\n x, padding_mask = self.w2v_model.extract_features(**w2v_args) # w2v_model (Wav2Vec2Model (fairseq.models.wav2vec.wav2vec2) -> extract_features\n\n if tbc: # default: True\n # B x T x C -> T x B x C # TODO: check if B = Batch size, T = length of output representation from encoder (timesteps?), C = input size (num of tokens)\n x = x.transpose(0, 1) # x before: torch.Size([1, 95, 1024]), after: [95, 1, 1024], padding_mask.shape: torch.Size([1, 95])\n\n x = self.final_dropout(x) # x.shape: [95, 1, 1024]\n\n if self.proj: # if applicable, change size to vocab size (len(tgt_dict)) so that we can run argmax\n x = self.proj(x) # after projection, x.shape: [95, 1, 108], padding_mask.shape: [1, 95]\n\n return {\n \"encoder_out\": x, # T x B x C # [95, 1, 108]\n \"encoder_padding_mask\": padding_mask, # B x 2T # B x 2T # ?\n \"padding_mask\": padding_mask, # 'padding_mask' = same-sized tensor as 'source' but filled w/ False\n }\n\n def reorder_encoder_out(self, encoder_out, new_order):\n if encoder_out[\"encoder_out\"] is not None:\n encoder_out[\"encoder_out\"] = encoder_out[\n \"encoder_out\"].index_select(1, new_order)\n if encoder_out[\"encoder_padding_mask\"] is not None:\n encoder_out[\"encoder_padding_mask\"] = encoder_out[\n \"encoder_padding_mask\"].index_select(0, new_order)\n return encoder_out\n\n def max_positions(self):\n \"\"\"Maximum input length supported by the encoder.\"\"\"\n return None\n\n def upgrade_state_dict_named(self, state_dict, name):\n return state_dict\n\n\nclass BrainWav2VecCtc(Wav2VecCtc): # BrainWav2VecCtc.forward -> uses the instance 'forward' from superclass Wav2VecCtc, which returns result of running through w2v_encoder!\n \"\"\" Modified from https://github.com/pytorch/fairseq \"\"\"\n\n @classmethod\n def build_model(cls, args, target_dict, pretrain_args): # returns new instance of class # args: w2v[\"args\"], target_dict: target_dict, pretrain_args: w2v[\"pretrain_args\"]\n \"\"\"Build a new model instance.\"\"\"\n base_architecture(args)\n w2v_encoder = BrainWav2VecEncoder(args, target_dict, pretrain_args) # w2v_encoder = BrainWav2VecEncoder(args, target_dict, pretrain_args)\n return cls(w2v_encoder, args) # constructs + returns a BrainWav2VecCtc model\n\n\nclass W2lDecoder(object):\n\n def __init__(self, tgt_dict):\n self.tgt_dict = tgt_dict\n self.vocab_size = len(tgt_dict)\n self.nbest = 1\n\n self.criterion_type = CriterionType.CTC\n self.blank = (tgt_dict.index(\"\")\n if \"\" in tgt_dict.indices else tgt_dict.bos())\n self.asg_transitions = None\n\n def generate(self, models, sample, **unused): # == self.model of recognizer.py 170)\n \"\"\"Generate a batch of inferences.\"\"\"\n # model.forward normally channels prev_output_tokens into the decoder\n # separately, but SequenceGenerator directly calls model.encoder\n encoder_input = { # if multiple sections: encoder_input: dict {'padding_mask': tensor([[False, False, False, ..., False, False, False]], device='cuda:0'), 'source': tensor([[ 6.4412e-05, -1.0509e-04, 6.4412e-05, ..., -1.2988e-02, -1.2818e-02, -1.3835e-02]], device='cuda:0')}, source.shape: torch.Size([1, 30720]), padding_mask.shape: torch.Size([1, 30720]) # if in one piece: encoder_input: dict {'source': tensor([[ 0.0001, -0.0002, 0.0001, ..., -0.0038, -0.0035, -0.0045]], device='cuda:0') of shape [1, 211883] (signal), 'padding_mask': tensor([[False, False, False, ..., False, False, False]], device='cuda:0') of shape [1, 211883]}\n k: v\n for k, v in sample[\"net_input\"].items()\n if k != \"prev_output_tokens\"\n }\n emissions = self.get_emissions(models, encoder_input) # 'emissions': normalized output produced by encoder; pass tensors through encoder # emissions (encoder output): tensor; shape: [1, 95, 108]\n return self.decode(emissions) # now send to decoder 'W2lViterbiDecoder'.decode -> return [[{\"tokens\": tensor([ 8, 11, 14, 11, 10, 5, 8, 48, 10, 32, 6, 37, 7, 11, 10, 5, 32, 12, 26, 22, 6, 18, 27, 8, 13, 5]), \"score\": 0}]]\n\n def get_emissions(self, models, encoder_input): # models: a list just containing BrainWav2VecCtc model; encoder_input: dict {'padding_mask': tensor, 'source': tensor (both sized same (e.g. [1, 30720]))\n \"\"\"Run encoder and normalize emissions\"\"\" # models[0]: BrainWav2VecCtc; when calling on model, forward fn automatically gets run\n encoder_out = models[0](**encoder_input) # BrainWav2VecCtc(**encoder_input) # **encoder_input: unpacks and passes in 'source' and 'padding_mask' tensors into dict 'encoder_input' # 'encoder_out': result of running BrainWav2VecCtc on {'source': tensor([[ 0.0001, -0.0002, 0.0001, ..., -0.0038, -0.0035, -0.0045]], device='cuda:0'), 'padding_mask': tensor([[False, False, False, ..., False, False, False]], device='cuda:0')}\n # encoder_out = dict {'encoder_out': tensor [95, 1, 108], 'padding_mask'/'encoder_padding_mask': BoolTensor filled w/ False [1, 95]}\n\n if self.criterion_type == CriterionType.CTC: # if True: (set to True earlier in file) -->\n emissions = models[0].get_normalized_probs( # emissions: normalized version of encoder output encoder_out['encoder_output'] (done by log softmax layer)\n encoder_out, # emissions: torch.cuda.FloatTensor; shape: [95, 1, 108] (same as BrainWav2VecEncoder.forward 'x')\n log_probs=True,\n )\n # emissions (normalized (0%(text)s\" % {\n \"url\": reverse('render_form_data', args=[self.domain, instance_id]),\n \"text\": _(\"View Form\")\n }\n\n\nclass CaseListFilter(CouchFilter):\n view = \"case/all_cases\"\n\n def __init__(self, domain, case_owner=None, case_type=None, open_case=None):\n\n self.domain = domain\n\n key = [self.domain]\n prefix = [open_case] if open_case else [\"all\"]\n\n if case_type:\n prefix.append(\"type\")\n key = key+[case_type]\n if case_owner:\n prefix.append(\"owner\")\n key = key+[case_owner]\n\n key = [\" \".join(prefix)]+key\n\n self._kwargs = dict(\n startkey=key,\n endkey=key+[{}],\n reduce=False\n )\n\n def get_total(self):\n if 'reduce' in self._kwargs:\n self._kwargs['reduce'] = True\n all_records = get_db().view(self.view,\n **self._kwargs).first()\n return all_records.get('value', 0) if all_records else 0\n\n def get(self, count):\n if 'reduce' in self._kwargs:\n self._kwargs['reduce'] = False\n return get_db().view(self.view,\n include_docs=True,\n limit=count,\n **self._kwargs).all()\n\nclass CaseDisplay(object):\n def __init__(self, report, case):\n \"\"\"\n case is a dict object of the case doc\n \"\"\"\n self.case = case\n self.report = report\n\n def parse_date(self, date_string):\n try:\n date_obj = dateutil.parser.parse(date_string)\n return date_obj\n except:\n return date_string\n\n def user_not_found_display(self, user_id):\n return _(\"Unknown [%s]\") % user_id\n\n @memoized\n def _get_username(self, user_id):\n username = self.report.usernames.get(user_id)\n if not username:\n mc = cache.get_cache('default')\n cache_key = \"%s.%s\" % (CouchUser.__class__.__name__, user_id)\n try:\n if mc.has_key(cache_key):\n user_dict = simplejson.loads(mc.get(cache_key))\n else:\n user_obj = CouchUser.get_by_user_id(self.owner_id) if user_id else None\n if user_obj:\n user_dict = user_obj.to_json()\n else:\n user_dict = {}\n cache_payload = simplejson.dumps(user_dict)\n mc.set(cache_key, cache_payload)\n if user_dict == {}:\n return self.user_not_found_display(user_id)\n else:\n user_obj = CouchUser.wrap(user_dict)\n username = user_obj.username\n except Exception:\n return None\n return username\n\n @property\n def owner_display(self):\n if self.owning_group and self.owning_group.name:\n return '%s' % self.owning_group.name\n else:\n return self._get_username(self.user_id)\n\n @property\n def closed_display(self):\n return yesno(self.case['closed'], \"closed,open\")\n\n @property\n def case_link(self):\n case_id, case_name = self.case['_id'], self.case['name']\n try:\n return html.mark_safe(\"%s\" % (\n html.escape(reverse('case_details', args=[self.report.domain, case_id])),\n html.escape(case_name),\n ))\n except NoReverseMatch:\n return \"%s (bad ID format)\" % case_name\n\n @property\n def case_type(self):\n return self.case['type']\n\n @property\n def opened_on(self):\n return self.report.date_to_json(self.parse_date(self.case['opened_on']))\n\n @property\n def modified_on(self):\n return self.report.date_to_json(self.modified_on_dt)\n\n @property\n def modified_on_dt(self):\n return self.parse_date(self.case['modified_on'])\n\n @property\n def owner_id(self):\n if 'owner_id' in self.case:\n return self.case['owner_id']\n elif 'user_id' in self.case:\n return self.case['user_id']\n else:\n return ''\n\n @property\n @memoized\n def owner_doc(self):\n try:\n doc = get_db().get(self.owner_id)\n except ResourceNotFound:\n return None, None\n else:\n return {\n 'CommCareUser': CommCareUser,\n 'Group': Group,\n }.get(doc['doc_type']), doc\n\n @property\n def owner_type(self):\n owner_class, _ = self.owner_doc\n if owner_class == CommCareUser:\n return 'user'\n elif owner_class == Group:\n return 'group'\n else:\n return None\n\n @property\n def owner(self):\n klass, doc = self.owner_doc\n if klass:\n return klass.wrap(doc)\n\n @property\n def owning_group(self):\n mc = cache.get_cache('default')\n cache_key = \"%s.%s\" % (Group.__class__.__name__, self.owner_id)\n try:\n if mc.has_key(cache_key):\n cached_obj = simplejson.loads(mc.get(cache_key))\n wrapped = Group.wrap(cached_obj)\n return wrapped\n else:\n group_obj = Group.get(self.owner_id)\n mc.set(cache_key, simplejson.dumps(group_obj.to_json()))\n return group_obj\n except Exception:\n return None\n\n @property\n def user_id(self):\n return self.report.individual or self.owner_id\n\n @property\n def creating_user(self):\n creator_id = None\n for action in self.case['actions']:\n if action['action_type'] == 'create':\n action_doc = CommCareCaseAction.wrap(action)\n creator_id = action_doc.get_user_id()\n break\n if not creator_id:\n return _(\"No data\")\n return self._get_username(creator_id)\n\n\nclass CaseSearchFilter(SearchFilter):\n search_help_inline = mark_safe(ugettext_noop(\"\"\"Search any text, or use a targeted query. For more info see the Case Search help page\"\"\"))\n\n\nclass CaseListMixin(ElasticProjectInspectionReport, ProjectReportParametersMixin):\n fields = [\n 'corehq.apps.reports.fields.FilterUsersField',\n 'corehq.apps.reports.fields.SelectCaseOwnerField',\n 'corehq.apps.reports.fields.CaseTypeField',\n 'corehq.apps.reports.fields.SelectOpenCloseField',\n 'corehq.apps.reports.standard.inspect.CaseSearchFilter',\n ]\n\n case_filter = {}\n ajax_pagination = True\n asynchronous = True\n\n @property\n @memoized\n def case_es(self):\n return CaseES(self.domain)\n\n\n def build_query(self, case_type=None, filter=None, status=None, owner_ids=[], search_string=None):\n # there's no point doing filters that are like owner_id:(x1 OR x2 OR ... OR x612)\n # so past a certain number just exclude\n MAX_IDS = 50\n\n def _filter_gen(key, flist):\n if flist and len(flist) < MAX_IDS:\n yield {\"terms\": {\n key: [item.lower() if item else \"\" for item in flist]\n }}\n\n # demo user hack\n elif flist and \"demo_user\" not in flist:\n yield {\"not\": {\"term\": {key: \"demo_user\"}}}\n\n def _domain_term():\n return {\"term\": {\"domain.exact\": self.domain}}\n\n subterms = [_domain_term(), filter] if filter else [_domain_term()]\n if case_type:\n subterms.append({\"term\": {\"type.exact\": case_type}})\n\n if status:\n subterms.append({\"term\": {\"closed\": (status == 'closed')}})\n\n user_filters = list(_filter_gen('owner_id', owner_ids)) + \\\n list(_filter_gen('user_id', owner_ids))\n if user_filters:\n subterms.append({'or': user_filters})\n\n if search_string:\n query_block = {\n \"query_string\": {\"query\": search_string}} # todo, make sure this doesn't suck\n else:\n query_block = {\"match_all\": {}}\n\n and_block = {'and': subterms} if subterms else {}\n\n es_query = {\n 'query': {\n 'filtered': {\n 'query': query_block,\n 'filter': and_block\n }\n },\n 'sort': self.get_sorting_block(),\n 'from': self.pagination.start,\n 'size': self.pagination.count,\n }\n\n return es_query\n\n @property\n @memoized\n def es_results(self):\n case_es = self.case_es\n query = self.build_query(case_type=self.case_type, filter=self.case_filter,\n status=self.case_status, owner_ids=self.case_owners,\n search_string=SearchFilter.get_value(self.request, self.domain))\n return case_es.run_query(query)\n\n @property\n @memoized\n def case_owners(self):\n if self.individual:\n group_owners = self.case_sharing_groups\n else:\n group_owners = Group.get_case_sharing_groups(self.domain)\n group_owners = [group._id for group in group_owners]\n return self.user_ids + group_owners\n\n @property\n @memoized\n def case_sharing_groups(self):\n try:\n user = CommCareUser.get_by_user_id(self.individual)\n user = user if user.username_in_report else None\n return user.get_case_sharing_groups()\n except Exception:\n try:\n group = Group.get(self.individual)\n assert(group.doc_type == 'Group')\n return [group]\n except Exception:\n return []\n\n def get_case(self, row):\n if '_source' in row:\n case_dict = row['_source']\n else:\n raise ValueError(\"Case object is not in search result %s\" % row)\n\n if case_dict['domain'] != self.domain:\n raise Exception(\"case.domain != self.domain; %r and %r, respectively\" % (case_dict['domain'], self.domain))\n\n return case_dict\n\n @property\n def shared_pagination_GET_params(self):\n shared_params = super(CaseListMixin, self).shared_pagination_GET_params\n shared_params.append(dict(\n name=SelectOpenCloseField.slug,\n value=self.request.GET.get(SelectOpenCloseField.slug, '')\n ))\n return shared_params\n\n\nclass CaseListReport(CaseListMixin, ProjectInspectionReport):\n name = ugettext_noop('Case List')\n slug = 'case_list'\n\n @property\n def user_filter(self):\n return super(CaseListReport, self).user_filter\n\n @property\n def report_context(self):\n rep_context = super(CaseListReport, self).report_context\n return rep_context\n\n @property\n @memoized\n def rendered_report_title(self):\n if not self.individual:\n self.name = _(\"%(report_name)s for %(worker_type)s\") % {\n \"report_name\": _(self.name),\n \"worker_type\": _(SelectMobileWorkerField.get_default_text(self.user_filter))\n }\n return self.name\n\n @property\n def headers(self):\n headers = DataTablesHeader(\n DataTablesColumn(_(\"Case Type\"), prop_name=\"type.exact\"),\n DataTablesColumn(_(\"Name\"), prop_name=\"name.exact\"),\n DataTablesColumn(_(\"Owner\"), prop_name=\"owner_display\", sortable=False),\n DataTablesColumn(_(\"Created Date\"), prop_name=\"opened_on\"),\n DataTablesColumn(_(\"Created By\"), prop_name=\"opened_by_display\", sortable=False),\n DataTablesColumn(_(\"Modified Date\"), prop_name=\"modified_on\"),\n DataTablesColumn(_(\"Status\"), prop_name=\"get_status_display\", sortable=False)\n )\n return headers\n\n @property\n def rows(self):\n def _format_row(row):\n case = self.get_case(row)\n display = CaseDisplay(self, case)\n\n return [\n display.case_type,\n display.case_link,\n display.owner_display,\n display.opened_on,\n display.creating_user,\n display.modified_on,\n display.closed_display\n ]\n\n try:\n return [_format_row(item) for item in self.es_results['hits'].get('hits', [])]\n except RequestFailed:\n pass\n\n def date_to_json(self, date):\n return tz_utils.adjust_datetime_to_timezone\\\n (date, pytz.utc.zone, self.timezone.zone).strftime\\\n ('%Y-%m-%d %H:%M:%S') if date else \"\"\n\nclass MapReport(ProjectReport, ProjectReportParametersMixin):\n \"\"\"\nHOW TO CONFIGURE THIS REPORT\n\ncreate a couch doc as such:\n\n{\n \"doc_type\": \"MapsReportConfig\",\n \"domain\": ,\n \"config\": {\n \"case_types\": [\n // for each case type\n\n {\n \"case_type\": ,\n \"display_name\": ,\n\n // either of the following two fields\n \"geo_field\": ,\n \"geo_linked_to\": ,\n\n \"fields\": [\n // for each reportable field\n\n \"field\": , // or one of the following magic values:\n // \"_count\" -- report on the number of cases of this type\n \"display_name\": ,\n \"type\": , // can be \"numeric\", \"enum\", or \"num_discrete\" (enum with numeric values)\n\n // if type is \"numeric\" or \"num_discrete\"\n // these control the rendering of numeric data points (all are optional)\n \"scale\": , // if absent, scale is calculated dynamically based on the max value in the field\n \"color\": ,\n\n // if type is \"enum\" or \"num_discrete\" (optional, but recommended)\n \"values\": [\n // for each multiple-choice value\n\n {\n \"value\": ,\n \"label\": , //optional\n \"color\": , //optional\n },\n ]\n ]\n },\n ]\n }\n}\n\"\"\"\n\n name = ugettext_noop(\"Maps Sandbox\")\n slug = \"maps\"\n # todo: support some of these filters -- right now this report\n hide_filters = True\n # is more of a playground, so all the filtering is done in its\n # own ajax sidebar\n report_partial_path = \"reports/partials/maps.html\"\n asynchronous = False\n flush_layout = True\n\n @classmethod\n @memoized\n def get_config(cls, domain):\n try:\n config = get_db().view('reports/maps_config', key=[domain], include_docs=True).one()\n if config:\n config = config['doc']['config']\n except Exception:\n config = None\n return config\n\n @property\n def config(self):\n return self.get_config(self.domain)\n\n @property\n def report_context(self):\n return dict(\n maps_api_key=settings.GMAPS_API_KEY,\n case_api_url=reverse('cloudcare_get_cases', kwargs={'domain': self.domain}),\n config=json.dumps(self.config)\n )\n\n @classmethod\n def show_in_navigation(cls, domain=None, project=None, user=None):\n return cls.get_config(domain)\n","sub_path":"corehq/apps/reports/standard/inspect.py","file_name":"inspect.py","file_ext":"py","file_size_in_byte":18843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"440878629","text":"from numpy import *\nimport matplotlib.pyplot as plt\n\nx = arange(0., 10, 0.3)\na = sin(x)\nb = cos(x)\nc = exp(x/10); d = exp(-x/10)\nplt.plot(x, a, 'b-', label='sine')\nplt.plot(x, b, 'r--', label='cosine')\nplt.plot(x, c, 'c-.', label='exp(+x)')\nplt.plot(x, d, 'gx-', linewidth=1.5, label='exp(-x)')\nplt.legend(loc='upper le]')\nplt.grid()\nplt.xlabel('x-axis')\nplt.ylabel('y-axis')\nplt.pause(1)\nplt.show()\n","sub_path":"src/csx_433_3/__class_2__.py","file_name":"__class_2__.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"167479193","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\ndef print_coords_by_name(name):\n xpath = \"//tr[td[text() ='name']]/td[3]\".replace(\"name\",name)\n coords = driver.find_element(By.XPATH, xpath).text\n print(coords)\n\ndef coords_by_name(name):\n xpath = \"//tr[td[text() ='name']]/td[3]\".replace(\"name\", name)\n coords = driver.find_element(By.XPATH, xpath).text\n return coords\n\n\ndef name_by_azonosito(azonosito):\n xpath = \"//tr[td[text() ='azonosito']]/td[2]\".replace(\"azonosito\", azonosito)\n name = driver.find_element(By.XPATH, xpath).text\n return name\n\ndef coords_by_azonosito(azonosito):\n xpath = \"//tr[td[text() ='azonosito']]/td[3]\".replace(\"azonosito\", azonosito)\n name = driver.find_element(By.XPATH, xpath).text\n return name\n\ndef hely_felvetele(nev, koordinata):\n input_name = driver.find_element_by_id(\"nameInput\")\n input_coords = driver.find_element_by_id(\"coordsInput\")\n button = driver.find_element_by_xpath(\"//button[@class = 'btn btn-primary']\")\n print(button)\n input_name.send_keys(nev)\n input_coords.send_keys(koordinata)\n button.click()\n return\n\n\n\n\ndriver = webdriver.Chrome()\n\ndriver.get(\"http://www.learnwebservices.com/locations/server\")\nprint('Írj egy függvényt, ami paraméterül kap egy nevet, és kiírja a település koordinátáját!')\nprint_coords_by_name(\"Abádszalók\")\nprint_coords_by_name(\"Abasár\")\nprint_coords_by_name(\"Báta\")\nprint('Írj egy függvényt, ami paraméterül kap egy nevet, és visszaadja a település koordinátáját!')\nprint(coords_by_name(\"Abádszalók\"))\nprint('Írj egy függvényt, mely paraméterül kap egy azonosítót, és kikeresi a nevet!')\nprint(name_by_azonosito('9277'))\nprint('Írj egy függvényt, mely paraméterül kap egy azonosítót, és kikeresi a koordinátáját!')\nprint(coords_by_azonosito('8369'))\nprint('Írj egy függvényt, mely a paraméterül kapott értékekkel (név, koordináta kitölti az űrlapot, és felvesz egy kedvenc helyet!')\nhely_felvetele('SDKedvencHely','10,20')\n\n\n\ndriver.close()\n\n\n\n\n\n","sub_path":"functions_locations.py","file_name":"functions_locations.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"242206413","text":"import secrets\nimport string\nfrom database import EPSDatabase\n\n\nclass Account():\n def __init__(self):\n\n self.ban = 0\n self.pin = 0\n self.balance = 0.0\n self.counter = 0\n self.choice = \"\"\n\n def create_pin(self):\n pin = \"\"\n while len(pin) != 4:\n pin = ''.join((secrets.choice(string.digits) for i in range(4)))\n self.pin = pin\n return self.pin\n\n def create_number(self):\n number = EPSDatabase.hightest().fetchall()\n if number != None:\n if len(number) != 0:\n number = int(number[0][0])\n self.counter = number\n curr = 0\n for value in EPSDatabase.print_table().fetchall():\n if int(value[0]) > curr:\n curr = int(value[0])\n print(curr)\n \n ban = self.counter+1\n ban = str(ban)\n ban = ban.zfill(8)\n self.ban = ban\n return self.ban\n\n def show_balance(self):\n # print(self.balance)\n return self.balance\n\n\nif __name__ == \"__main__\":\n\n a = Account()\n print(a.create_number())\n print(a.create_pin())\n print(f\"Your Current Balance: {a.show_balance()}€\")\n\n #print(f\"Your Current Balance: {a.show_balance()}€\")\n","sub_path":"Teilschritt3/eps_base.py","file_name":"eps_base.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"172930539","text":"# Creates: Bi2Se3_bands.png\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom gpaw import GPAW\nfrom gpaw.spinorbit import get_spinorbit_eigenvalues, set_calculator\n\n#plt.rc('text', usetex=True)\n\ncalc1 = GPAW('Bi2Te3_bands.gpw', txt=None)\ncalc2 = GPAW('gs_Bi2Te3.gpw', txt=None)\nx = np.loadtxt('kpath.dat')\nX = np.loadtxt('highsym.dat')\n\n# No spin-orbit\n\nef = calc2.get_fermi_level()\ne_kn = np.array([calc1.get_eigenvalues(kpt=k)\n for k in range(len(calc1.get_ibz_k_points()))])\ne_nk = e_kn.T\ne_nk -= ef\n\nfor e_k in e_nk:\n plt.plot(x, e_k, '--', c='0.5')\n\n# Spin-orbit calculation\n\ne_nk = get_spinorbit_eigenvalues(calc2)\nset_calculator(calc2, e_nk.T)\nef = calc2.get_fermi_level()\ne_nk = get_spinorbit_eigenvalues(calc1, scale=1.0)\ne_nk -= ef\n\nplt.xticks(X, [r'$\\Gamma$', 'Z', 'F', r'$\\Gamma$', 'L'], size=24)\nplt.yticks(size=20)\nfor i in range(len(X))[1:-1]:\n plt.plot(2 * [X[i]], [1.1 * np.min(e_nk), 1.1 * np.max(e_nk)],\n c='0.5', linewidth=0.5)\nfor e_k in e_nk:\n plt.plot(x, e_k, c='b')\nplt.ylabel(r'$\\varepsilon_n(k)$ [eV]', size=24)\nplt.axis([0, x[-1], -1.7, 1.7])\nplt.tight_layout()\n# plt.show()\nplt.savefig('Bi2Te3_bands.png')\n","sub_path":"Bi2Te3_band/plot_Bi2Te3_bands.py","file_name":"plot_Bi2Te3_bands.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"518396175","text":"import json\nimport keyword\n\n\nclass ColorizeMixin(object):\n def __repr__(self):\n return f'\\033[0;{self.repr_color_code};49m {self.title} | {self.price} ₽\\033[0;39;48m'\n\nclass Object:\n def __init__(self, json_dict):\n for key, value in json_dict.items():\n if keyword.iskeyword(key):\n key += '_'\n if isinstance(value, dict):\n self.__dict__[key] = Object(value)\n else:\n self.__dict__[key] = value\n\n\nclass Advert():\n def __init__(self, json_str):\n json_dict = json.loads(json_str)\n self.__dict__ = Object(json_dict).__dict__\n self.repr_color_code = 32\n\n title = self.__dict__.get('title', False)\n if not title:\n raise ValueError\n price = self.__dict__.get('price', False)\n if not price:\n self._price = 0\n elif price < 0:\n raise ValueError\n else:\n self._price = price\n\n @property\n def price(self):\n return self._price\n\n @price.setter\n def price(self, new_price):\n if new_price < 0:\n raise ValueError\n else:\n self._price = new_price\n\n def __repr__(self):\n return f'{self.title} | {self.price} ₽'\n\n\nclass Advert_Color(ColorizeMixin, Advert):\n pass\n\n\n","sub_path":"05-samoe-neobhodimoe-o-klassah/advert.py","file_name":"advert.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"493244389","text":"from flask import Flask, Response, request\nimport base64\nimport random\nfrom os import path\nfrom string import ascii_letters\nimport subprocess\n\napp = Flask(__name__)\n\nINPUT_PATH = \"/home/faebser/workspace/maps-backend/input\" # CHANGE THIS\nOUTPUT_PATH = \"/home/faebser/workspace/maps-backend/output\" # CHANGE THIS\nCOMMAND = \"cp {} {}\" # CHANGE THIS\n\n\n@app.route(\"/\", methods=['GET'])\ndef main():\n return app.send_static_file('index.html')\n\n\n@app.route(\"/sketch-me\", methods=[\"POST\"])\ndef sketch():\n image_string = request.get_json(force=True).get('img', None)\n if image_string is None:\n return Response(\"property img missing in json\", status=500)\n\n image_data = base64.b64decode(image_string)\n file_name = \"\".join([random.choice(ascii_letters) for _ in range(0, 40)]) + \".jpeg\"\n input_path = path.join(INPUT_PATH, file_name)\n output_path = path.join(OUTPUT_PATH, file_name)\n with open(input_path, 'wb') as f:\n f.write(image_data)\n\n # this will block\n process = subprocess.Popen(COMMAND.format(input_path, output_path).split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n output, error = process.communicate()\n if error is not None and error != '':\n return Response(str(error), status=500)\n else:\n return Response(output_path)\n\nif __name__ == \"__main__\":\n app.run(processes=5)","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"201003692","text":"import click\nimport gym\nimport tensorflow as tf\n\nfrom sac.networks import MlpAgent\nfrom sac.train import Trainer\n\n\ndef check_probability(ctx, param, value):\n if not (0 <= value <= 1):\n raise click.BadParameter(\"Param {} should be between 0 and 1\".format(value))\n return value\n\n\n@click.command()\n@click.option('--env', default='CartPole-v0')\n@click.option('--seed', default=0, type=int)\n@click.option('--n-layers', default=3, type=int)\n@click.option('--layer-size', default=256, type=int)\n@click.option('--learning-rate', default=3e-4, type=float)\n@click.option('--buffer-size', default=1e5, type=int)\n@click.option('--num-train-steps', default=1, type=int)\n@click.option('--batch-size', default=32, type=int)\n@click.option('--reward-scale', default=1., type=float)\n@click.option('--entropy-scale', default=1., type=float)\n@click.option('--logdir', default=None, type=str)\n@click.option('--save-path', default=None, type=str)\n@click.option('--load-path', default=None, type=str)\n@click.option('--render', is_flag=True)\ndef cli(env, seed, buffer_size, n_layers, layer_size, learning_rate, reward_scale,\n entropy_scale, batch_size, num_train_steps, logdir, save_path, load_path, render):\n Trainer(\n env=gym.make(env),\n base_agent=MlpAgent,\n seq_len=0,\n device_num=1,\n seed=seed,\n buffer_size=buffer_size,\n activation=tf.nn.relu,\n n_layers=n_layers,\n layer_size=layer_size,\n learning_rate=learning_rate,\n entropy_scale=entropy_scale,\n reward_scale=reward_scale,\n batch_size=batch_size,\n grad_clip=None,\n num_train_steps=num_train_steps)\n\n\nif __name__ == '__main__':\n cli()\n","sub_path":"scripts/gym_env.py","file_name":"gym_env.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"646931172","text":"# 第一种方法简单直接粗暴有效,就是用print()把可能有问题的变量打印出来看看\n\n# 用print()最大的坏处是将来还得删掉它,想想程序里到处都是print(),\n# 运行结果也会包含很多垃圾信息。所以,我们又有第二种方法。\n\n\n# 断言\n\n# 凡是用print()来辅助查看的地方,都可以用断言(assert)来替代:\n\n\ndef foo(s):\n n = int(s)\n assert n != 0, 'n is zero!' # 如果断言失败,assert语句本身就会抛出AssertionError\n # AssertionError: n is zero!\n return 10 / n\n\n\ndef main():\n foo('0')\n\n# main()\n# 执行结果:\n# Traceback (most recent call last):\n# File \"D:/Swap/Code/PycharmProjects/LearnPython/error_debugging_testing/debug.py\", line 21, in \n# main()\n# File \"D:/Swap/Code/PycharmProjects/LearnPython/error_debugging_testing/debug.py\", line 19, in main\n# foo('0')\n# File \"D:/Swap/Code/PycharmProjects/LearnPython/error_debugging_testing/debug.py\", line 14, in foo\n# assert n != 0, 'n is zero!'\n# AssertionError: n is zero!\n\n# assert的意思是,表达式n != 0应该是True,否则,根据程序运行的逻辑,后面的代码肯定会出错。\n\n\n\n# 一键关闭断言\n\n# 启动Python解释器时可以用-O参数来关闭assert\n\n# python -O err.py\n\n# 关闭后,你可以把所有的assert语句当成pass来看。\n\n\n# logging\n\n# 把print()替换为logging是第3种方式,和assert比,logging不会抛出错误,而且可以输出到文件:\n\nimport logging\nlogging.basicConfig(level=logging.INFO) # logging 需要配置\n# llogging允许你指定记录信息的级别,\n# 有debug,info,warning,error等几个级别,\n# 当我们指定level=INFO时,logging.debug就不起作用了。\n# 同理,指定level=WARNING后,debug和info就不起作用了。\n# 这样一来,你可以放心地输出不同级别的信息,也不用删除,\n# 最后统一控制输出哪个级别的信息。\n\ns = '0'\nn = int(s)\nlogging.info('n = %d' % n) # INFO:root:n = 0\nprint(10 / n)\n\n\n# pdb\n\n# 第4种方式是启动Python的调试器pdb,让程序以单步方式运行,可以随时查看运行状态。我们先准备好程序:\n\n","sub_path":"error_debugging_testing/debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"650983575","text":"#!/usr/bin/python\n# Copyright 2015 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n\"\"\"Runs unit tests on test_runner.py.\n\nUsage:\n ./test_runner_test.py\n\"\"\"\n\n# pylint: disable=relative-import\nimport environment_setup\n\nimport mock\nimport os\nimport tempfile\nimport unittest\n\nfrom slave.ios import test_runner\n\nclass TestRunnerTest(unittest.TestCase):\n \"\"\"Unit tests for test_runner.TestRunner.\"\"\"\n\n def testRaisesAppNotFoundError(self):\n \"\"\"Ensures invalid app_path raises AppNotFoundError.\"\"\"\n self.assertRaises(\n test_runner.AppNotFoundError, test_runner.TestRunner, '/tmp/fakepath')\n\n def testRaisesUnexpectedAppExtensionError(self):\n \"\"\"Ensures invalid app_path raises UnexpectedAppExtensionError.\"\"\"\n self.assertRaises(\n test_runner.UnexpectedAppExtensionError,\n test_runner.TestRunner,\n tempfile.mkdtemp(),\n )\n\n def testDoesNotRaiseAppNotFoundError(self):\n \"\"\"Ensures valid app_path does not raise AppNotFoundError.\"\"\"\n self.failUnless(test_runner.TestRunner(tempfile.mkdtemp('.app')))\n self.failUnless(test_runner.TestRunner(tempfile.mkdtemp('.ipa')))\n\n def testRequireTearDown(self):\n \"\"\"Ensures methods decorated with RequireTearDown call TearDown last.\"\"\"\n class TearDownTestRunner(test_runner.TestRunner):\n def __init__(self):\n super(TearDownTestRunner, self).__init__(tempfile.mkdtemp('.ipa'))\n self.values = []\n\n def TearDown(self):\n self.values.append('teardown')\n\n def GetLaunchCommand(self, test_filter=None, blacklist=None):\n pass\n\n def Launch(self):\n pass\n\n def NoTearDown(self, value):\n self.values.append(value)\n\n @test_runner.TestRunner.RequireTearDown\n def RequiresTearDown(self, value):\n self.values.append(value)\n\n @test_runner.TestRunner.RequireTearDown\n def ExceptionRaiser(self):\n raise NotImplementedError\n\n t = TearDownTestRunner()\n self.failIf(t.values)\n\n t.NoTearDown('abc')\n self.assertListEqual(t.values, ['abc'])\n\n t.RequiresTearDown('123')\n self.assertListEqual(t.values, ['abc', '123', 'teardown'])\n\n self.assertRaises(NotImplementedError, t.ExceptionRaiser)\n self.assertListEqual(t.values, ['abc', '123', 'teardown', 'teardown'])\n\n def testGetFilter(self):\n \"\"\"Tests the results of GetGTestFilter and GetKIFTestFilter.\"\"\"\n tests = [\n 'Test 1',\n 'Test 2',\n 'KIF.Test A',\n 'KIF.Test B',\n ]\n\n expected_gtest = 'Test 1:Test 2:KIF.Test A:KIF.Test B'\n expected_inverted_gtest = '-Test 1:Test 2:KIF.Test A:KIF.Test B'\n expected_kif = 'NAME:Test 1|Test 2|Test A|Test B'\n expected_inverted_kif = '-NAME:Test 1|Test 2|Test A|Test B'\n\n self.assertEqual(\n test_runner.TestRunner.GetGTestFilter(tests, False),\n expected_gtest,\n )\n self.assertEqual(\n test_runner.TestRunner.GetGTestFilter(tests, True),\n expected_inverted_gtest,\n )\n self.assertEqual(\n test_runner.TestRunner.GetKIFTestFilter(tests, False),\n expected_kif,\n )\n self.assertEqual(\n test_runner.TestRunner.GetKIFTestFilter(tests, True),\n expected_inverted_kif,\n )\n\n\nclass SimulatorTestRunnerTest(unittest.TestCase):\n \"\"\"Unit tests for test_runner.SimulatorTestRunner.\"\"\"\n def testRaisesSimulatorNotFoundError(self):\n \"\"\"Ensures SimulatorNotFoundError is raised when iossim doesn't exist.\"\"\"\n self.assertRaises(\n test_runner.SimulatorNotFoundError,\n test_runner.SimulatorTestRunner,\n tempfile.mkdtemp('.app'),\n '/tmp/fake/path/to/iossim',\n 'iPhone 5',\n '8.0',\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"scripts/slave/ios/test_runner_test.py","file_name":"test_runner_test.py","file_ext":"py","file_size_in_byte":3717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"596158244","text":"class Node:\n def __init__(self,data=None):\n self.data=data\n self.next=None\n\n\nclass LinkList:\n def __init__(self):\n self.head=None\n\n\n def countNode(self,head):\n count=1\n current=self.head\n while(current.next!=None): #second.next jodi null na hoy\n current=current.next\n count=count+1\n return count\n\n\nllist = LinkList()\nllist.head=Node(5)\nsecond = Node(4)\nthird = Node(11)\nfour=Node(12)\n\nllist.head.next=second #>4\nsecond.next=third #>11\nthird.next=four\n\nprint(llist.countNode(llist.head))\nprint(llist.printList(second))\n\n\n\n","sub_path":"DataStructure&Algo/LinkedList.py","file_name":"LinkedList.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"84184302","text":"from cs50 import get_int\n\n# prompt user for credit card number\nwhile True:\n card = get_int(\"Credit Card number: \")\n if card > 0:\n break\n\n# Luhn algorithm to check validity of the number 4003600000000014\ncard = str(card)\nsum = 0\n\n# multiply every other digit, and then sum them together according to the algorithm\nfor digit in card[-2::-2]:\n digit = str(int(digit) * 2)\n if int(digit) < 10:\n sum += int(digit)\n else:\n sum += int(digit[0]) + int(digit[1])\n\n# add the other digits not multiplied to the sum\nfor digit in card[::-2]:\n sum += int(digit)\n\n# Print the type of credit card if valid\nif sum % 10 == 0:\n if (len(card) == 15) and (card[:2] in ['34', '37']):\n print(\"AMEX\")\n elif (len(card) == 16) and (card[:2] in ['51', '52', '53', '54', '55']):\n print(\"MASTERCARD\")\n elif (len(card) in [13, 16]) and (card[0] == '4'):\n print(\"VISA\")\n else:\n print(\"INVALID\")\nelse:\n print(\"INVALID\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"pset6/credit/credit.py","file_name":"credit.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"613314873","text":"# 导入库\nimport pandas as pd \n# 导入数据\ndf = pd.read_csv('../data/weibo.csv', header=None, names=['name', 'number', 'day'])\ndf.head() \ndf.shape\nfrom datetime import datetime\n\ndef transform_day(x): \n x = '2020年' + x \n date_format = datetime.strptime(x, '%Y年%m月%d日')\n return datetime.strftime(date_format, '%Y-%m-%d') \n \n \ndf['day'] = df.day.apply(transform_day)\ndf.head() \n\n# 筛选数据\n# df_sel = df[df['day'] >= '2020-10-02']\n# df_sel.head() \n\ndf_resuluts = pd.pivot_table(data=df, \n index='name', \n columns='day', \n values='number', \n aggfunc='mean', \n fill_value=0\n )\ndf_resuluts.head() \ndf_resuluts.to_csv('../data/df_resuluts.csv') \n","sub_path":"演员请就位2代码+数据/代码/可视化动态图.py","file_name":"可视化动态图.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"57853653","text":"from tkinter import *\r\nroot=Tk()\r\nroot.title(\"somesh sharma\")\r\nroot.geometry(\"1000x700\")\r\n\r\nframe1=Frame(bg=\"orange\")\r\nframe1.pack(side=TOP,fill=BOTH,expand=True)\r\n\r\nframe2=Frame(frame1,height=\"400\",width=\"200\")\r\nframe2.pack(side=RIGHT,padx=\"200\")\r\n\r\nframe3=Frame(frame2,height=\"50\")\r\nframe3.pack(side=TOP)\r\n\r\nimage1=PhotoImage(file=\"rest.png\")\r\nlabel=Label(frame2,image=image1,width=400,height=250)\r\nlabel.pack(side=TOP,padx=\"10\")\r\n\r\nlabel1=Label(frame2,text=\"Username:\",font=(\"calibri\",18,\"bold\"))\r\nlabel1.pack(anchor=\"nw\",padx=10)\r\n\r\nuserEntry=Entry(frame2,font=(\"calibri\",14,\"bold\"))\r\nuserEntry.pack(anchor=\"nw\",padx=10)\r\n\r\nlabel1=Label(frame2,text=\"Password:\",font=(\"calibri\",18,\"bold\"))\r\nlabel1.pack(anchor=\"nw\",padx=10)\r\n\r\nuserEntry=Entry(frame2,show='*',font=(\"calibri\",14,\"bold\"))\r\nuserEntry.pack(anchor=\"nw\",padx=10)\r\n\r\nbuttonok=Button(frame2,text=\"OK\",bg=\"green\",height=2,width=6,bd=2)\r\nbuttonok.pack(side=LEFT,padx=\"10\",pady=\"10\")\r\n\r\nbuttonexit=Button(frame2,text=\"EXIT\",bg=\"red\",height=2,width=6,bd=2)\r\nbuttonexit.pack(side=RIGHT,padx=\"10\",pady=\"10\")\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\nroot.mainloop()","sub_path":"rm1.py","file_name":"rm1.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"127291019","text":"\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect, HttpResponseNotFound\nfrom Product.models import Product\n\n\n\n\ndef Goods(request):\n Goods = Product.objects.all()\n return render(request, \"Product/index.html\", {\"Goods\": Goods})\n\n\ndef create(request):\n if request.method == \"POST\":\n Product1 = Product()\n Product1.name = request.POST.get(\"name\")\n Product1.price = request.POST.get(\"price\")\n Product1.Description = request.POST.get(\"Description\")\n Product1.save()\n return HttpResponseRedirect(\"/\")\n\n\ndef edit(request, id):\n try:\n Product1 = Product.objects.get(id=id)\n\n if request.method == \"POST\":\n Product1.name = request.POST.get(\"name\")\n Product1.price = request.POST.get(\"price\")\n Product1.Description = request.POST.get(\"Description\")\n Product1.save()\n return HttpResponseRedirect(\"/\")\n else:\n return render(request, \"Product/edit.html\", {\"Product1\": Product})\n except Product.DoesNotExist:\n return HttpResponseNotFound(\"

Товар не найден

\")\n\n\ndef delete(request, id):\n try:\n Product1 = Product.objects.get(id=id)\n Product1.delete()\n return HttpResponseRedirect(\"/\")\n except Product.DoesNotExist:\n return HttpResponseNotFound(\"

Товар не найден

\")\n","sub_path":"Product/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"400905899","text":"import turtle\nimport time\nfrom random import *\n\nDELAY = 0.15\nWIDTH = 800\nHEIGHT = 600\nSPEED = 20\n\nwindow = turtle.Screen()\nwindow.title(\"snake\")\nwindow.bgcolor(\"black\")\nwindow.setup(WIDTH, HEIGHT)\nwindow.tracer(0) #stop window from updating\n\ndef setupKeyListener(window):\n window.listen()\n window.onkeypress(headS.move_up, \"Up\")\n window.onkeypress(headS.move_down, \"Down\")\n window.onkeypress(headS.move_left, \"Left\")\n window.onkeypress(headS.move_right, \"Right\")\n\n# Snake\nclass Snake():\n def __init__(self, head = None, direction = None):\n self.head = turtle.Turtle()\n self.head.speed(0)\n self.head.shape(\"square\")\n self.head.color(\"white\")\n self.head.setposition(0,0)\n self.head.penup()\n self.direction = \"down\"\n \n def xcor(self):\n return self.head.xcor()\n def ycor(self):\n return self.head.ycor()\n def setposition(self, x, y):\n self.head.setposition(x, y)\n def move_up(self):\n self.direction = \"up\"\n def move_down(self):\n self.direction = \"down\"\n def move_left(self):\n self.direction = \"left\"\n def move_right(self):\n self.direction = \"right\"\n\n def move(self):\n if self.direction == \"up\":\n y = self.head.ycor()\n self.head.sety(y + SPEED)\n if self.direction == \"down\":\n y = self.head.ycor()\n self.head.sety(y - SPEED)\n if self.direction == \"left\":\n x = self.head.xcor()\n self.head.setx(x - SPEED)\n if self.direction == \"right\":\n x = self.head.xcor()\n self.head.setx(x + SPEED)\n\nheadS = Snake()\ntailS = headS\nsnake = []\nsnake.append(headS)\nsetupKeyListener(window)\n\ndef resetGame():\n global snake, headS, tailS\n for s in snake:\n s.head.reset()\n snake.clear()\n headS = Snake()\n headS.setposition(0,0)\n tailS = headS\n snake.append(headS)\n setupKeyListener(window)\n\n# End of Snake\n\n# Food\nfood = turtle.Turtle()\nfood.shape(\"circle\")\nfood.color(\"red\")\nfood.penup()\nfood.speed(0)\nfood.setposition(randrange(-WIDTH/2+20, WIDTH/2-20, 20), randrange(-HEIGHT/2+20, HEIGHT/2-20, 20))\n\ndef randomFood():\n x = randrange(-WIDTH/2+20, WIDTH/2-20, 20)\n y = randrange(-HEIGHT/2+20, HEIGHT/2-20, 20)\n flag = spaceAvailable(x,y)\n while flag == False:\n x = randrange(-WIDTH/2+20, WIDTH/2-20, 20)\n y = randrange(-HEIGHT/2+20, HEIGHT/2-20, 20)\n flag = spaceAvailable(x, y)\n return (x, y)\n \ndef spaceAvailable(x, y):\n for s in snake:\n if (x == s.head.xcor() and y == s.head.ycor()):\n return False\n return True\n\ndef eaten():\n global tailS, snake\n food.setposition(randomFood())\n \n #increase snake length\n newSnake = Snake()\n\n # if tail of snake is going:\n # 'up', new tail is added to the bottom, 'down' -> added on top\n # 'left' -> added right side, 'right' -> added left side\n if(tailS.direction == \"up\"):\n newSnake.head.setposition(tailS.head.xcor(), tailS.head.ycor()-20)\n elif (tailS.direction == \"down\"):\n newSnake.head.setposition(tailS.head.xcor(), tailS.head.ycor()+20)\n elif (tailS.direction == \"right\"):\n newSnake.head.setposition(tailS.head.xcor()-20, tailS.head.ycor())\n elif (tailS.direction == \"left\"):\n newSnake.head.setposition(tailS.head.xcor()+20, tailS.head.ycor())\n\n newSnake.direction = tailS.direction\n tailS = newSnake\n snake.append(newSnake)\n# End of Food\n\ndef moveSnake():\n global snake, headS\n for s in snake:\n s.move()\n if(s.xcor() == WIDTH/2 or s.xcor() == -WIDTH/2):\n s.setposition(-s.xcor(), s.ycor())\n if(s.ycor() == HEIGHT/2 or s.ycor() == -HEIGHT/2):\n s.setposition(s.xcor(), -s.ycor())\n\n if(s is not headS and (headS.xcor() == s.head.xcor() and headS.ycor() == s.head.ycor())):\n resetGame()\n break\n\ndef updateSnakeDirection():\n global snake, headS\n hDir = headS.direction\n i = 1\n while i < len(snake):\n tmp = snake[i].direction\n snake[i].direction = hDir\n hDir = tmp\n i+=1\n \nwhile True:\n window.update()\n time.sleep(DELAY)\n\n moveSnake()\n updateSnakeDirection()\n\n # snake eats food\n if(snake[0].head.xcor() == food.xcor() and snake[0].head.ycor() == food.ycor()):\n eaten()\n print(len(snake))\n","sub_path":"snake_v2.py","file_name":"snake_v2.py","file_ext":"py","file_size_in_byte":4385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"81983396","text":"import os, sys, ConfigParser\n\nconfigFilesPaths = ['paths.cfg', 'enabled.cfg']\n\ndef updateLinks():\n\tconfig = ConfigParser.ConfigParser()\n\tconfig.read(configFilesPaths)\n\tfor fileName, path in config.items('Path'):\n\t\tif config.getboolean('Enabled', fileName):\n\t\t\tlinkFile(os.path.abspath(fileName), path)\n\ndef linkFile(target, linkName):\n\tos.system('ln -sf {0} {1}'.format(target, linkName))\n\nif __name__ == '__main__':\n\tupdateLinks()","sub_path":"updateLinks.py","file_name":"updateLinks.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"397015568","text":"def copyTSNominalFiles(caseNames,nSeeds,nomDataPath,windName):\n import os, subprocess\n nCases = len(caseNames)\n for b in range(nCases):\n name2=caseNames[b]\n if not os.path.exists(name2):\n os.makedirs(name2)\n os.chdir(name2)\n for seed in range(0,nSeeds):\n name3='Seed_'+str(seed)\n if not os.path.exists(name3):\n os.makedirs(name3)\n os.chdir(name3)\n print(os.getcwd())\n\n NomWindFiles1=str(nomDataPath)+os.sep+str(windName)+'_'+str(name2)+'.txt'#'Turbsim_'+str(name2)+'.txt'\n print('WindFile: ',NomWindFiles1)\n subprocess.call([\"cp\", NomWindFiles1, str(windName)+'.txt'])\n os.chdir('../')\n \n os.chdir('../')\n\ndef copyFFNominalFiles(caseNames,nSeeds,nTurbs,nomDataPath,rootname):\n import os\n from shutil import copyfile\n nCases = len(caseNames)\n for b in range(nCases):\n name2=caseNames[b]\n if not os.path.exists(name2):\n os.makedirs(name2)\n os.chdir(name2)\n #src=str(nomDataPath)+os.sep+str(rootname)+'ElastoDyn.dat'\n #dst='.'+os.sep+str(rootname)+'ElastoDyn.dat'\n #copyfile(src,dst)\n\n for wt in range(nTurbs):\n #src=str(nomDataPath)+os.sep+str(rootname)+'ServoDyn.'+str(wt)+'.dat'\n #dst='.'+os.sep+str(rootname)+'ServoDyn.'+str(wt)+'.dat'\n #copyfile(src, dst)\n \n src=str(nomDataPath)+os.sep+str(rootname)+'WT'+str(wt+1)+'.fst'\n dst='.'+os.sep+str(rootname)+'WT'+str(wt+1)+'.fst'\n copyfile(src, dst)\n\n for seed in range(nSeeds):\n name3='Seed_'+str(seed)\n if not os.path.exists(name3):\n os.makedirs(name3)\n os.chdir(name3)\n src='../../TurbSim_mod.bts'\n copyfile(src,'./TurbSim_mod.bts')\n print(os.getcwd())\n os.chdir('../')\n \n os.chdir('../')\n \ndef createTSParamFiles(caseNames,nSeeds,data,D,HubHt,fileOut):\n import numpy as np\n import os, subprocess\n import pandas as pd\n import random\n from InputSetup import TSInputCreation as inputCreation\n \n nCases = len(caseNames)\n nTurbs=int(data[3:].shape[0]/2)\n seedNum = ['None']*nSeeds\n \n for seed in range(nSeeds):\n seedNum[seed] = random.randint(-2147483648,2147483647)\n \n for b in range(nCases):\n name2=caseNames[b]\n #os.chdir(name2)\n \n xlocs=['None']*nTurbs\n ylocs=['None']*nTurbs\n for turb in range(nTurbs):\n xlocs[turb]=data[caseNames[b]][3+turb*2]\n ylocs[turb]=data[caseNames[b]][4+turb*2] \n xmin=min(xlocs); xmax=max(xlocs)\n ymin=min(ylocs); ymax=max(ylocs)\n for seed in range(nSeeds):\n name3='Seed_'+str(seed)\n #os.chdir(name3)\n print(os.getcwd())\n print('Writing TurbSim input file: ', fileOut)\n with open(fileOut, 'w') as f:\n f.write('Seed\\t{0}\\n'.format(seedNum[seed]))\n f.write('D\\t{0}\\n'.format(D))\n f.write('HubHt\\t{0}\\n'.format(HubHt))\n f.write('Vhub\\t{0}\\n'.format(data[name2][1]))\n f.write('TI\\t{0}\\n'.format(data[name2][0]))\n f.write('Shear\\t{0}\\n'.format(data[name2][2]))\n f.write('xlocs\\t{0}\\t{1}\\n'.format(xmin,xmax))\n f.write('ylocs\\t{0}\\t{1}\\n'.format(ymin,ymax))\n \n #os.chdir('TurbSim')\n inputCreation(os.getcwd(),nTurbs)\n \n os.chdir('../..')\n \n os.chdir('../')\n\n\ndef createFFParamFiles(caseNames,nSeeds,data,HubHt,D,fileOut):\n import os, subprocess\n import pandas as pd\n \n import sys\n from InputSetup import FFInputCreation as inputCreation\n sys.path.append('/home/kshaler/PostProcessing/General')\n from stochasticTurbulenceTools_mod import stochasticTurbulence\n \n nCases = len(caseNames)\n nTurbs = int(data[3:].shape[0]/3)\n for b in range(nCases):\n name2=caseNames[b]\n #os.chdir(name2)\n \n xlocs=['None']*nTurbs\n ylocs=['None']*nTurbs\n zlocs=['None']*nTurbs\n for turb in range(nTurbs):\n xlocs[turb]=data[caseNames[b]][turb*3]\n ylocs[turb]=data[caseNames[b]][1+turb*3]\n zlocs[turb]=data[caseNames[b]][2+turb*3]\n\n ReadTS = True\n\n ReadINP = False\n\n #if caseNames[b] == 'Case000':\n if ReadTS == True:\n if ReadINP == True:\n TSFile = os.path.join('.'+os.sep+Case.prefix+'.inp')\n\n else:\n print(os.getcwd())\n HubHt_HighTS = 148.5\n \n IFdata = stochasticTurbulence(D,prefix='Low')\n IFdata.readBTS(os.getcwd(), HubHt)\n\n IFdata.kHub = IFdata.z2k(HubHt)\n\n Vhub = IFdata.u[:,IFdata.jHub,IFdata.kHub].mean()\n \n IFdata = stochasticTurbulence(D,prefix='Low')\n HubHt_LowTS = 119 #change this\n IFdata.readBTS(os.getcwd(), HubHt_LowTS)\n\n IFdata.kHub = IFdata.z2k(HubHt_LowTS)\n\n Vhub_Low = IFdata.u[:,IFdata.jHub,IFdata.kHub].mean()\n \n IFdata = stochasticTurbulence(D,prefix='HighT1')\n IFdata.readBTS(os.getcwd(), HubHt_HighTS)\n\n IFdata.kHub = IFdata.z2k(HubHt_HighTS)\n\n Vhub_High = IFdata.u[:,IFdata.jHub,IFdata.kHub].mean()\n else:\n print('TurbSim parameters must be entered directly.')\n\n for seed in range(nSeeds):\n name3='Seed_'+str(seed)\n #os.chdir(name3)\n print(os.getcwd())\n print('Writing FFarm input file: ', fileOut)\n with open(fileOut, 'w') as f:\n f.write('D\\t{0}\\n'.format(D))\n f.write('HubHt\\t{0}\\n'.format(HubHt))\n f.write('high_extent_X\\t1.2\\n')\n f.write('high_extent_Y\\t1.2\\n')\n f.write('xlocs')\n for turb in range(nTurbs):\n f.write('\\t{:.3}'.format(xlocs[turb]))\n f.write('\\n')\n f.write('ylocs')\n for turb in range(nTurbs):\n f.write('\\t{:.3}'.format(ylocs[turb]))\n f.write('\\n')\n f.write('zlocs')\n for turb in range(nTurbs):\n f.write('\\t{:.3}'.format(zlocs[turb]))\n \n inputCreation('.','../NREL5MW.T',os.getcwd(),Vhub,Vhub_Low,Vhub_High)\n \n os.chdir('../')\n \n os.chdir('../')\n \ndef copyNominalFiles(NumSeeds,NumTurbs):\n import os\n import subprocess\n \n NomDataPath=os.getcwd()+'/SampleFiles/Nominal'\n TurbineDataPath=os.getcwd()+'/'\n \n for wt in range(NumTurbs):\n fstFile=NomDataPath+'/NREL5MW_ElastoDyn.{0}.dat'.format(wt)\n subprocess.call([\"cp\", fstFile, TurbineDataPath])\n\n fstFile=NomDataPath+'/NREL5MW_ServoDyn.{0}.dat'.format(wt)\n subprocess.call([\"cp\", fstFile, TurbineDataPath])\n\n for seed in range(NumSeeds):\n name='Seed_'+str(seed)\n if not os.path.exists(name):\n os.makedirs(name)\n os.chdir(name)\n print(os.getcwd())\n\n TurbineDataPath=os.getcwd()+'/.'\n\n os.makedirs('TurbSim')\n\n for wt in range(NumTurbs):\n fstFile=NomDataPath+'/NREL5MW_WT{0}.fst'.format(wt+1)\n subprocess.call([\"cp\", fstFile, TurbineDataPath])\n\n fstFile=NomDataPath+'/FFarm.fstf'\n subprocess.call([\"cp\", fstFile, TurbineDataPath])\n\n fstFile=NomDataPath+'/InflowWind.dat'\n subprocess.call([\"cp\", fstFile, TurbineDataPath])\n\n os.chdir('../')\n \n","sub_path":"pyFAST/fastfarm/ParameterManipulation.py","file_name":"ParameterManipulation.py","file_ext":"py","file_size_in_byte":7826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"284812872","text":"from itertools import combinations as c\n\nn = int(input())\nif n <= 9:\n print(n)\nelif n >= 1023:\n print(-1)\nelse:\n count = 10\n for i in range(2, 11):\n for j in range(i-1, 10):\n sortlist = []\n for d in c([str(x) for x in range(j)], i-1):\n sortlist.append(''.join(reversed(d)))\n sortlist.sort()\n for num in sortlist:\n if count == n:\n print(str(j)+num)\n exit()\n count += 1\n","sub_path":"1000-1999/1038/1038.py","file_name":"1038.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"115267308","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport time\nimport os\nimport re\nimport sys\nfrom config.configuration import get_sale_price, init_files_manager, price_special_case_manager, filter_price_data\n\n\nclass PriceSplitHelper:\n def __init__(self):\n self.default_value = False\n self.site_to_store_dict = {\"BK\": \"BL\", \"WL\": \"WL\", \"TS\": \"TS\"}\n self.date_str = time.strftime(\"%Y%m%d\", time.localtime())\n self.root_path = os.path.dirname(__file__)\n self.price_save_name = None\n self.local_price_dir = None\n\n def _filter_merge_files(self, shop_name_abbr):\n files_manager = init_files_manager(self.root_path, shop_name_abbr, self.date_str)\n local_dir = files_manager.get(\"DownloadFilesDir\")\n self.local_price_dir = files_manager.get(\"PriceFilesDir\")\n self.price_save_name = files_manager.get(\"PriceSave\")\n price_columns = files_manager.get(\"PriceColumns\")\n reference_columns = files_manager.get(\"ReferenceColumns\")\n mix_price_list = pd.DataFrame(columns=price_columns)\n mix_reference_list = pd.DataFrame(columns=reference_columns)\n price_filter = \"{}_{}_{}.csv\".format(shop_name_abbr, \"price\", self.date_str).lower()\n\n reference_filter = \"{}_{}_{}.csv\".format(shop_name_abbr, \"reference\", self.date_str).lower()\n\n if os.path.exists(local_dir):\n all_files = os.listdir(local_dir)\n files = []\n for f in all_files:\n if re.search(r\"{}\".format(self.date_str), f):\n files.append(f)\n price_data_list = []\n reference_data_list = []\n for f in files:\n # if re.search(r\"price\", f):\n # price_file = os.path.join(local_dir, f)\n # price_data = pd.read_csv(price_file, delimiter=\"\\t\")\n # price_data_list.append(price_data)\n # # os.remove(price_file)\n # elif re.search(r\"reference\", f):\n # reference_file = os.path.join(local_dir, f)\n # reference_data = pd.read_csv(reference_file, delimiter=\"\\t\")\n # reference_data_list.append(reference_data)\n # # os.remove(reference_file)\n # else:\n # pass\n\n if f == price_filter:\n price_file = os.path.join(local_dir, f)\n price_data = pd.read_csv(price_file, delimiter=\"\\t\")\n price_data_list.append(price_data)\n os.remove(price_file)\n elif f == reference_filter:\n reference_file = os.path.join(local_dir, f)\n reference_data = pd.read_csv(reference_file, delimiter=\"\\t\")\n reference_data_list.append(reference_data)\n os.remove(reference_file)\n else:\n pass\n\n for price_data in price_data_list:\n if mix_price_list.empty:\n mix_price_list = price_data\n else:\n mix_price_list = pd.merge(mix_price_list, price_data, how=\"outer\")\n\n for reference_data in reference_data_list:\n if mix_reference_list.empty:\n mix_reference_list = reference_data\n else:\n mix_reference_list = pd.merge(mix_reference_list, reference_data, how=\"outer\")\n\n # mix_price_list.columns = price_columns\n # mix_reference_list.columns = reference_columns\n return mix_price_list, mix_reference_list\n\n else:\n return mix_price_list, mix_reference_list\n\n def split_price(self, shop_name_abbr, gap_price=2, compare=\">\", plus_limit=None, minus_limit=-8, query_code=None):\n # price columns = [\"id\",\"site\",\"isbn\", \"product_id\",\"variant_id\",\"sku\",\"basic_price\",\"price_note\",\"crawl_time\"]\n # reference columns = [\"product_id\", \"variant_id\", \"sku\", \"condition_isbn\", \"old_price\", \"quantity\", \"filter\"]\n price_list, reference = self._filter_merge_files(shop_name_abbr)\n price_list[[\"product_id\", \"variant_id\"]] = price_list[[\"product_id\", \"variant_id\"]].astype(str)\n reference[[\"product_id\", \"variant_id\"]] = reference[[\"product_id\", \"variant_id\"]].astype(str)\n store_grouped = price_list.groupby(by=\"site\")\n price_list_num = price_list.shape[0]\n reference_num = reference.shape[0]\n print(\"Price / Reference : {} / {}\".format(price_list_num, reference_num))\n #sys.exit()\n mix_price_list = pd.DataFrame()\n for site, price_info in store_grouped:\n if not self.site_to_store_dict or not self.site_to_store_dict.get(site):\n store_name = site\n else:\n store_name = self.site_to_store_dict.get(site)\n\n if store_name == shop_name_abbr:\n\n price_detail = price_info.loc[:, [\"product_id\", \"variant_id\", \"basic_price\"]]\n\n # no price info\n zero_price = price_detail[price_detail.loc[:, 'basic_price'] == 0]\n null_price = price_detail.loc[price_detail['basic_price'].isnull(), :]\n null_zero_list = pd.merge(zero_price, null_price, how=\"outer\")\n\n # normal price data\n price_detail = price_detail.dropna(subset=['basic_price'])\n price_detail.loc[:, 'new_price'] = pd.Series((get_sale_price(store_name, x)\n for x in price_detail['basic_price']), index=price_detail.index)\n\n # old price info\n reference_price = reference.loc[:, [\"product_id\", \"variant_id\", \"old_price\", \"quantity\"]]\n merged_null_zero_price = pd.merge(null_zero_list, reference_price, how=\"left\", on=[\"product_id\", \"variant_id\"])\n merged_price_detail = pd.merge(price_detail, reference_price, how=\"left\",\n on=[\"product_id\", \"variant_id\"])\n\n # deal with old price missing data - no inventory info\n merged_null_zero_price = price_special_case_manager(merged_null_zero_price, \"OldPriceMissing\")\n init_size = merged_null_zero_price.shape[0]\n merged_price_detail = price_special_case_manager(merged_price_detail, \"OldPriceMissing\", init_size)\n\n # filter null zero data to decrease update number by quantity\n merged_null_zero_price = merged_null_zero_price[merged_null_zero_price[\"quantity\"] > 0]\n\n # deal normal price data---create \"gas_price\" to filter and reset columns\n merged_price_detail.loc[:, \"gap_price\"] = merged_price_detail[\"new_price\"] - merged_price_detail[\"old_price\"]\n export_null_price = merged_null_zero_price.loc[:, [\"product_id\", \"variant_id\", \"basic_price\", \"old_price\"]]\n export_null_price.rename(columns={'old_price': 'sort_value'}, inplace=True)\n export_price_detail = merged_price_detail.loc[:, [\"product_id\", \"variant_id\", \"basic_price\", \"gap_price\", \"quantity\"]]\n\n # filter and split normal data to get \"filtered price data\" & \"out-of-filter price data-minus gap price\"\n export_price_detail, minus_gap_price_list = filter_price_data(export_price_detail, gap_price, compare,\n plus_limit, minus_limit, query_code)\n if not minus_gap_price_list.empty:\n # merge price data to satisfy max-update-number\n merged_data = (export_price_detail, minus_gap_price_list)\n init_size = export_price_detail.shape[0] + export_null_price.shape[0]\n case = \"AddMinusPrice\"\n export_price_detail = price_special_case_manager(merged_data, case, init_size)\n\n export_price_detail.rename(columns={'gap_price': 'sort_value'}, inplace=True)\n if not os.path.exists(self.local_price_dir):\n os.makedirs(self.local_price_dir)\n mix_price_list = pd.merge(export_null_price, export_price_detail, how=\"outer\")\n mix_price_list = mix_price_list.drop_duplicates()\n save_file_path = os.path.join(self.local_price_dir, self.price_save_name)\n mix_price_list.to_csv(save_file_path, sep=\"\\t\", index=False)\n null_price_size = null_price.shape[0]\n zero_price_size = zero_price.shape[0]\n normal_price_size = merged_price_detail.shape[0]\n print(\"NULL/ZERO/NORMAL: {} / {} / {}\".format(null_price_size, zero_price_size, normal_price_size))\n break\n return mix_price_list\n\n","sub_path":"remote_download/price_split_helper.py","file_name":"price_split_helper.py","file_ext":"py","file_size_in_byte":8825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"102509607","text":"#!/usr/bin/env python3.6\n# -*- coding: utf-8 -*-\n# tim.lansen@gmail.com\n\n# Workers monitor\n# Periodically pings workers, checks their statuses and unregisters in case of pong timeout\n\nimport time\nfrom modules.models import Task, Job, Node\nfrom modules.utils.log_console import Logger\nfrom modules.utils.database import DBInterface\n\n\n# 1. Get all NEW jobs\n# 1. Get all nodes -> nodes1\n# 3. Offer jobs to idle nodes\n# 2. Send 'ping' notifications\n# 3. Pause\n# 4. Get all nodes -> list2\n# 5. If list2[node].mtime - list1[node].mtime > timeout: remove node; remove it from list2\n# 6. list2 -> list1\n# 7. Goto 1\n\n\nMAX_PARALLEL_TASKS = 3\n\n\ndef dispatch(nodes, jobs):\n \"\"\"\n\n :param dobj: {'jobs': [jobs], 'nodes': [nodes], 'notifications': [notifications]}\n :return:\n \"\"\"\n notifications = []\n while len(jobs) and len(nodes):\n node = nodes.pop(-1)\n job = jobs.pop(0)\n # if test_job_condition(job):\n if not DBInterface.Job.set_status(job['guid'], Job.Status.OFFERED):\n Logger.debug('Failed to change job status\\n', Logger.LogLevel.LOG_WARNING)\n continue\n notifications.append([node['channel'], 'offer {}'.format(job['guid'])])\n if len(notifications):\n DBInterface.notify_list(notifications)\n\n\ndef run(period=5):\n def test_job_condition(_job_):\n # First, check dependencies\n _dog_ = _job_['dependsongroupid']\n if _dog_ is not None and _dog_ != '00000000-0000-0000-0000-000000000000':\n # Job depends on group\n # Request jobs included to the group and have status != FINISHED\n _jobs_ = DBInterface.get_records(\n 'Job',\n fields=['status'],\n cond=[\n \"'{}'=ANY(groupids)\".format(_dog_),\n \"guid<>'{}'\".format(_dog_),\n \"status<>{}\".format(Job.Status.FINISHED)\n ]\n )\n if len(_jobs_):\n return False\n # Check condition\n # if 'condition' in _job_:\n # _c_ = _job_['condition']\n # if _c_ is None:\n # return True\n return True\n\n def archive_job(uid):\n # TODO: Archive job\n # Remove job from DB\n Logger.debug('Archive job: {}\\n'.format(uid), Logger.LogLevel.LOG_NOTICE)\n # DBInterface.Job.delete(uid)\n\n while True:\n\n tasks = DBInterface.get_records('Task', fields=['guid'], status=Task.Status.EXECUTING, sort=['ctime'])\n task_slots = MAX_PARALLEL_TASKS - len(tasks)\n # Get idle nodes\n nodes = DBInterface.get_records('Node', fields=['guid', 'channel'], status=Node.Status.IDLE)\n\n for task in tasks:\n # Check if task have no pending jobs\n jobs = DBInterface.get_records(\n 'Job',\n fields=['guid'],\n status=[Job.Status.NEW, Job.Status.WAITING, Job.Status.OFFERED, Job.Status.EXECUTING, Job.Status.FAILED],\n cond=[\"task='{}'\".format(task['guid'])]\n )\n if len(jobs) == 0:\n # DBInterface.Task.set_status(task['guid'], Task.Status.FINISHED)\n continue\n\n # Get all NEW jobs, change their status to WAITING if condition test is True\n jobs = DBInterface.get_records('Job', fields=['guid', 'dependsongroupid', 'condition'], status=Job.Status.NEW, cond=[\"task='{}'\".format(task['guid'])])\n for job in jobs:\n if test_job_condition(job):\n DBInterface.Job.set_status(job['guid'], Job.Status.WAITING)\n\n # Monitor jobs: there must not be OFFERED jobs, FINISHED jobs must be archived, FAILED jobs must be relaunched\n jobs = DBInterface.get_records(\n 'Job',\n fields=['guid', 'status', 'fails', 'offers'],\n status=[Job.Status.OFFERED, Job.Status.FAILED]\n )\n for job in jobs:\n if job['status'] == Job.Status.OFFERED:\n # Something wrong happened during offer, reset status to WAITING\n DBInterface.Job.set_fields(job['guid'], {'status': Job.Status.WAITING, 'offers': job['offers'] + 1})\n elif job['status'] == Job.Status.FAILED:\n # Job execution failed, reset status to NEW\n DBInterface.Job.set_fields(job['guid'], {'status': Job.Status.NEW, 'offers': job['fails'] + 1})\n\n # Get waiting jobs\n task_jobs = DBInterface.get_records('Job', fields=['guid'], status=Job.Status.WAITING, cond=[\"task='{}'\".format(task['guid'])], sort=['priority'])\n dispatch(nodes, task_jobs)\n\n if task_slots > 0:\n tasks = DBInterface.get_records('Task', fields=['guid'], status=Task.Status.WAITING, sort=['priority', 'ctime'], limit=task_slots)\n for task in tasks:\n DBInterface.Task.set_status(task['guid'], Task.Status.EXECUTING)\n\n # Get all WAITING jobs sorted by priority and creation time, and IDLE nodes\n # jobs = DBInterface.get_records('Job', fields=['guid'], status=Job.Status.WAITING, sort=['priority', 'ctime'])\n\n # Monitor nodes\n nodes = DBInterface.get_records('Node', ['mtime', 'guid', 'channel'])\n if len(nodes):\n notifications = [[n['channel'], 'ping'] for n in nodes]\n DBInterface.notify_list(notifications)\n time.sleep(period)\n check = \"EXTRACT(EPOCH FROM AGE(localtimestamp, mtime))>{timeout}\".format(timeout=5*period)\n suspicious_nodes = DBInterface.get_records('Node', fields=['guid', 'job'], cond=[check])\n if len(suspicious_nodes):\n Logger.debug(\"Unregister node(s):\\n{}\\n\".format('\\n'.join([str(sn['guid']) for sn in suspicious_nodes])), Logger.LogLevel.LOG_WARNING)\n DBInterface.delete_records('Node', [sn['guid'] for sn in suspicious_nodes])\n Logger.debug(\"Check jobs were being executed on these nodes...\\n\", Logger.LogLevel.LOG_INFO)\n jobs = DBInterface.get_records(\n 'Job',\n fields=['guid', 'fails'],\n status=Job.Status.EXECUTING,\n # use str() for sn['job'] to convert UUID() to string\n cond=[\"guid=ANY('{{{}}}'::uuid[])\".format(','.join([str(sn['job']) for sn in suspicious_nodes if sn['job']]))]\n )\n for job in jobs:\n Logger.debug('Reset job {}\\n'.format(job['guid']), Logger.LogLevel.LOG_WARNING)\n DBInterface.Job.set_fields(job['guid'], {'status': Job.Status.NEW, 'offers': job['fails'] + 1})\n time.sleep(period)\n else:\n time.sleep(period)\n\n\nif __name__ == '__main__':\n run(1)\n","sub_path":"backend/dispatcher.py","file_name":"dispatcher.py","file_ext":"py","file_size_in_byte":6791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"239758399","text":"import json\nimport os\n\nresources = os.path.join(\"resources\", \"transcripts\")\ntranscript_dir = os.listdir(resources)\n\ntranscript_series = []\nepisodes = []\n\nfor trans in transcript_dir:\n trans_backup = trans\n episodes = os.listdir(os.path.join(resources, trans))\n serie_obj = dict()\n episodes_array = []\n if trans == \"NextGen\":\n serie_obj[\"name\"] = \"Star Trek: The Next Generation\"\n elif trans == \"Voyager\":\n serie_obj[\"name\"] = \"Star Trek: Voyager\"\n elif trans == \"TOS\":\n serie_obj[\"name\"] = \"Star Trek: The Original Series\"\n elif trans == \"DS9\":\n serie_obj[\"name\"] = \"Star Trek: Deep Space Nine\"\n elif trans == \"Enterprise\":\n serie_obj[\"name\"] = \"Star Trek: Enterprise\"\n elif trans == \"Animated Serie\":\n serie_obj[\"name\"] = \"Star Trek: The Animated Series\"\n else:\n serie_obj['name'] = trans\n\n for ep in episodes:\n raw_episode_text = open(os.path.join(resources, trans_backup, ep)).read()\n episodes_array.append(open(os.path.join(resources, trans_backup, ep)).read())\n serie_obj[\"episodes\"] = episodes_array\n transcript_series.append(serie_obj)\n\nseries = []\nserie_obj = dict()\nepisodes = []\n\nfor serie in transcript_series:\n episode_number = 0\n for episode_element in serie[\"episodes\"]:\n episode_obj = dict()\n serie_name = episode_element.split(\"Transcripts\")[0].replace(\"\\n\", \"\").replace(\"The\", \"\")\n episode_number += 1\n splitted_airdate = episode_element.split(\"Original Airdate:\")\n before_stardate, stardate_, after_stardate = episode_element.partition(\"Stardate:\")\n stardate = after_stardate[:8].replace(\"\\n\", \"\")\n ep_title = before_stardate\n episode_obj[\"episode_title\"] = ep_title.split(\"-\")[1]\n if len(splitted_airdate) > 1:\n airdate_end = splitted_airdate[1].split(\"Captain's log\")[0].split(\"\\n\\n\\n\")\n airdate = airdate_end[0]\n bef, now, pure_text = episode_element.partition(\"\\n\\n\\n\\n\\n\\n\")\n episode_obj[\"text\"] = json.dumps({\"text\": pure_text})\n episode_obj[\"serie_name\"] = serie[\"name\"]\n episode_obj[\"number\"] = episode_number\n if airdate:\n episode_obj[\"airdate\"] = airdate\n episode_obj[\"stardate\"] = stardate\n episodes.append(episode_obj)\n episode_obj = None\n\nfile_path = os.path.join(\"resources\", \"jsonModels\", \"episodes_test.json\")\n\nwith open(file_path, \"w\") as episodes_file:\n json.dump(episodes, episodes_file)\n","sub_path":"resources/extractors/transcript_extractor.py","file_name":"transcript_extractor.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"641745686","text":"from pymongo import MongoClient\r\ndef displayCursor(cursor):\r\n words = ''\r\n for doc in cursor:\r\n words += doc[\"word\"] + \",\"\r\n if len(words) > 65:\r\n words = words[:65] + \"...\"\r\n print (words)\r\ndef over12(collection):\r\n print (\"\\n\\nWords with more than 12 characters:\")\r\n query = {'size': {'$gt': 12}}\r\n cursor = collection.find(query)\r\n displayCursor(cursor)\r\ndef startingABC(collection):\r\n print (\"\\nWords starting with A, B or C:\")\r\n query = {'first': {'$in': [\"a\",\"b\",\"c\"]}}\r\n cursor = collection.find(query)\r\n displayCursor(cursor)\r\ndef startEndVowels(collection):\r\n print (\"\\nWords starting and ending with a vowel:\")\r\n query = {'$and': [\r\n {'first': {'$in': [\"a\",\"e\",\"i\",\"o\",\"u\"]}},\r\n {'last': {'$in': [\"a\",\"e\",\"i\",\"o\",\"u\"]}}]}\r\n cursor = collection.find(query)\r\n displayCursor(cursor)\r\ndef over6Vowels(collection):\r\n print (\"\\nWords with more than 5 vowels:\")\r\n query = {'stats.vowels': {'$gt': 5}}\r\n cursor = collection.find(query)\r\n displayCursor(cursor)\r\ndef nonAlphaCharacters(collection):\r\n print (\"\\nWords with 1 non-alphabet characters:\")\r\n query = {'charsets': \r\n {'$elemMatch': \r\n {'$and': [\r\n {'type': 'other'},\r\n {'chars': {'$size': 1}}]}}}\r\n cursor = collection.find(query)\r\n displayCursor(cursor)\r\nif __name__==\"__main__\":\r\n mongo = MongoClient('mongodb://localhost:27017/')\r\n db = mongo['words']\r\n collection = db['word_stats']\r\n over12(collection)\r\n startEndVowels(collection)\r\n over6Vowels(collection)\r\n nonAlphaCharacters(collection)","sub_path":"hour16/PythonFindSpecific.py","file_name":"PythonFindSpecific.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"97518992","text":"from tkinter import Tk, Canvas\r\n\r\nclass CanvasContainer():\r\n def __init__(self, total_W, total_H):\r\n self.master = Tk()\r\n self.canvas = Canvas(self.master, width=total_W, height=total_H)\r\n self.canvas.pack()\r\n self.elements = dict()\r\n def updateCanvas(self, is_alive):\r\n if is_alive:\r\n self.canvas.update()\r\n self.master.update_idletasks()\r\n else:\r\n self.canvas.destroy()\r\n self.master.destroy()\r\n def getElements(self):\r\n ret = list()\r\n for key in self.elements:\r\n ret.append([str(key),self.elements[key]])\r\n return ret\r\n def remove(self, key):\r\n if key in self.elements.keys():\r\n for val in self.elements[key]:\r\n self.canvas.delete(val)\r\n self.elements.pop(key)\r\n return True\r\n else:\r\n return False\r\n def removeMany(self, keylist):\r\n ks = [\"\"]\r\n if \"*\" in keylist:\r\n ks = list(self.elements.keys())\r\n else:\r\n ks = keylist.copy()\r\n count = 0\r\n for key in ks:\r\n count += 1 if self.remove(key) else 0\r\n return count\r\n def create_border(self, prepad):\r\n pad = prepad-3\r\n width = int(self.canvas.config()[\"width\"][4])\r\n height = int(self.canvas.config()[\"height\"][4])\r\n self.canvas.create_line(pad,pad, width-pad,pad, width-pad,height-pad, pad,height-pad, pad,pad )\r\n def create_line(self, plist, name):\r\n if str(name) not in self.elements.keys():\r\n newval = list()\r\n newval.append(self.canvas.create_line(*plist))\r\n self.elements[str(name)] = newval\r\n else:\r\n self.elements[str(name)].append(self.canvas.create_line(*plist))\r\n def create_oval(self, plist, name=\"dots\"):\r\n if str(name) not in self.elements.keys():\r\n newval = list()\r\n newval.append(self.canvas.create_oval(*plist))\r\n self.elements[str(name)] = newval\r\n else:\r\n self.elements[str(name)].append(self.canvas.create_oval(*plist))\r\n","sub_path":"cxtk.py","file_name":"cxtk.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"244621529","text":"\"\"\"Add tables aaaa\n\nRevision ID: d87761df646f\nRevises: 8cfe5befdaec\nCreate Date: 2016-07-21 00:21:30.939974\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'd87761df646f'\ndown_revision = '8cfe5befdaec'\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('server',\n sa.Column('id', sa.BigInteger(), autoincrement=False, nullable=False),\n sa.Column('name', sa.String(), nullable=True),\n sa.Column('owner_id', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('user',\n sa.Column('id', sa.BigInteger(), autoincrement=False, nullable=False),\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('member',\n sa.Column('id', sa.BigInteger(), nullable=False),\n sa.Column('joined_at', sa.DateTime(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('server_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['server_id'], ['server.id'], ),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('message',\n sa.Column('id', sa.BigInteger(), autoincrement=False, nullable=False),\n sa.Column('content', sa.String(), nullable=True),\n sa.Column('deleted', sa.Boolean(), nullable=True),\n sa.Column('channel_id', sa.Integer(), nullable=True),\n sa.Column('member_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['channel_id'], ['channel.id'], ),\n sa.ForeignKeyConstraint(['member_id'], ['member.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('nickname_change',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('before', sa.String(), nullable=True),\n sa.Column('after', sa.String(), nullable=True),\n sa.Column('member_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['member_id'], ['member.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('username_change',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('before', sa.String(), nullable=True),\n sa.Column('after', sa.String(), nullable=True),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.add_column('channel', sa.Column('server_id', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'channel', 'server', ['server_id'], ['id'])\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'channel', type_='foreignkey')\n op.drop_column('channel', 'server_id')\n op.drop_table('username_change')\n op.drop_table('user')\n op.drop_table('server')\n op.drop_table('nickname_change')\n op.drop_table('message')\n op.drop_table('member')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/d87761df646f_add_tables_aaaa.py","file_name":"d87761df646f_add_tables_aaaa.py","file_ext":"py","file_size_in_byte":3035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"240284392","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n\nimport argparse\nimport dace\nimport numpy as np\n\nM = dace.symbol('M')\nK = dace.symbol('K')\nN = dace.symbol('N')\n\n\n@dace.program(dace.float64[M, K], dace.float64[K, N], dace.float64[M, N])\ndef gemm(A, B, C):\n # Transient variable\n tmp = dace.define_local([M, N, K], dtype=A.dtype)\n\n @dace.map(_[0:M, 0:N, 0:K])\n def multiplication(i, j, k):\n in_A << A[i, k]\n in_B << B[k, j]\n out >> tmp[i, j, k]\n\n out = in_A * in_B\n\n dace.reduce(lambda a, b: a + b, tmp, C, axis=2, identity=0)\n\n\nif __name__ == \"__main__\":\n print(\"==== Program start ====\")\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"M\", type=int, nargs=\"?\", default=24)\n parser.add_argument(\"K\", type=int, nargs=\"?\", default=24)\n parser.add_argument(\"N\", type=int, nargs=\"?\", default=24)\n args = vars(parser.parse_args())\n\n M.set(args[\"M\"])\n K.set(args[\"K\"])\n N.set(args[\"N\"])\n\n print('Matrix multiplication %dx%dx%d' % (M.get(), K.get(), N.get()))\n\n # Initialize arrays: Randomize A and B, zero C\n A = np.random.rand(M.get(), K.get()).astype(np.float64)\n B = np.random.rand(K.get(), N.get()).astype(np.float64)\n C = np.zeros([M.get(), N.get()], dtype=np.float64)\n C_regression = np.zeros_like(C)\n\n gemm(A, B, C)\n\n if dace.Config.get_bool('profiling'):\n dace.timethis('gemm', 'numpy', (2 * M.get() * K.get() * N.get()),\n np.dot, A, B, C_regression)\n else:\n np.dot(A, B, C_regression)\n\n diff = np.linalg.norm(C_regression - C) / (M.get() * N.get())\n print(\"Difference:\", diff)\n print(\"==== Program end ====\")\n exit(0 if diff <= 1e-5 else 1)\n","sub_path":"samples/simple/gemm.py","file_name":"gemm.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"600198458","text":"#! /usr/bin/env python\n\nfrom os import listdir\nfrom os.path import isfile, join\nfrom jsonschema import validate, exceptions \nimport json\n\njson_dump = {\n\t\"missing_description\": [],\n\t\"invalid_description\": []\n\t}\n\nschema = json.load(open(\"../../schemas/moduleDescription.json\",\"r\"))\n\nfor moduleFolder in listdir(\"../\"):\n\tif not isfile(moduleFolder):\n\t\tmoduleDescPath = join(\"..\",moduleFolder, \"module.json\")\n\t\tif isfile(moduleDescPath):\n\t\t\ttry:\n\t\t\t\tvalidate(json.load(open(moduleDescPath,\"r\")), schema)\n\t\t\texcept exceptions.ValidationError as error:\n\t\t\t\tjson_dump[\"invalid_description\"].append({\"name\":moduleFolder, \"error_message\": error.message})\n\t\telse:\n\t\t\tjson_dump[\"missing_description\"].append(moduleFolder)\n\ndump_file = open(\"../../../101web/data/dumps/validateModuleDescriptions.json\", \"w\")\ndump_file.write(json.dumps(json_dump, sort_keys=True, indent=4, separators=(',', ': ')))\ndump_file.close()","sub_path":"101worker/modules/validateModuleDescriptions/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"580650415","text":"import unittest\nimport wencai as wc\n\nclass TestWenCai(unittest.TestCase):\n\n\n\n def test_get_cookies(self):\n cookies = wc.getHeXinVByCookies(ktype='strategy',execute_path=\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe\")\n print(cookies)\n globals()['cookies'] = cookies\n\n\n def test_get_scrape_transaction(self):\n global cookies\n r = wc.get_scrape_transaction('跳空高开,平台突破,非涨停,股价大于ma120,ma30ma120ma250上移,股价大于前30日最高价,非银行版块',\n cookies=cookies)\n print(r)\n\n def test_get_strategy(self):\n global cookies\n r = wc.get_strategy('非银行版块',cookies=cookies)\n print(r)\n\n def test_get_scrape_report(self):\n global cookies\n r= wc.get_scrape_report('跳空高开,平台突破,非涨停,股价大于ma120,ma30ma120ma250上移,股价大于前30日最高价,非银行版块',\n cookies=cookies)\n print(r)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_wencai.py","file_name":"test_wencai.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"277443809","text":"from time import sleep\nfrom datetime import datetime\nfrom datetime import date\n\ndias = ['Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-Feira', 'Sexta-feira', 'Sábado', 'Domingo']\n\n\nespetinho = [('ESPETO DE CARNE - R$:8,00', 8.00), ('ESPETO DE CARNE (com creme de alho) - R$:9,50', 9.50),\n ('ESPETO DE PICAHNHA - R$:15,00', 15.00), ('ESPETO DE CUPIM - R$:13,00', 13.00),\n ('ESPETO DE CALABRESA DEFUMADA - R$7,00', 7.00), ('ESPETO DE FRANGO - R$:8,00', 8.00),\n ('ESPETO DE COXINHA DE FRANGO - R$:9,50', 9.50), ('ESPETO DE CORAÇÃO - R$:8,00', 8.00),\n ('ESPETO DE KAFTA - R$:10,00', 10.00), ('ESPETO DE TOSCANA R$:9,00', 9.00),\n ('MEDALHÃO DE CARNE - R$:13,50', 13.50), ('MEDALHÃO DE FRANGO - R$:11,50', 11.50)]\n\nacompanhamento = [('PÃO DE ALHO - R$:6,00', 6.00), ('BATATA FRITA (P) - R$:8,00', 8.00),\n ('BATATA FRITA (M) - R$:14,00', 14.00), ('BATATA FRITA (G) - R$:24,00', 24.00),\n ('QUEIJO ASSADO c/MELAÇO OU s/MELAÇO - R$:8,00', 8.00)]\n\nbebidas = [('COCA-COLA 350ml (lata) - R$:5,00', 5.00), ('COCA-COLA (1 litro) - R$:9,00', 9.00),\n ('GUARANÁ 269ml (lata) - R$:3,00', 3.00), ('GUARANÁ 350ml (lata) - R$:3,50', 3.50),\n ('GUARANÁ (1 litro) - R$:9,00', 9.00),('ÁGUA 300ml (sem gás) - R$:3,00', 3.00),\n ('ÁGUA 300ml (com gás) - R$:4,00', 4.00), ('DEVASSA PURO MALTE 350ml (lata) - R$:5,00', 5.00),\n ('HEINEKEN (long neck) - R$:9,00', 9.00)]\n\ncombos = [('COMBO 1 - R$:28,00', 28.00), ('COMBO 2 - R$:22,00', 22.00), ('COMBO 3 - R$:35,00', 33.00),\n ('COMBO 4 - R$:22,00', 22.00), ('COMBO 5 - R$:22,00', 22.00), ('COMBO 6 - R$:35,00', 35.00),\n ('COMBO 7 - R$:35,00', 35.00)]\n\npromoção_do_dia = ['COMBO 1 - R$:28,00\\n(Batata Frita (P) + 1 Espeto de Picanha + Pão de Alho + 1 Guaraná 269ml (lata)',\n'COMBO 2 - R$:17,00\\n(1 Espeto de Picanha + Batata Frita (P) + 1 Guaraná 269ml (lata))',\n'COMBO 3 - R$:28,00\\n(File Acebolado + Batata Frita (M) + 1 Guaraná 269ml (lata))',\n'COMBO 4 - R$:17,00\\n(1 Espeto de Carne + 1 Espeto de Frango + 1 Espeto de Calabresa Defumada + 1 Guaraná 269ml (lata)',\n'COMBO 5 - R$:17,00\\n(1 Pão de Alho + 1 Espeto de Carne + 1 Espeto de Frango + 1 Guaraná 269ml (lata))',\n'COMBO 6 - R$:30,00\\n(Carne do Sol Acebolada + Batata Frita (M) + 1 Guaraná 269ml (lata))',\n'COMBO 7 - R$:30,00\\n(1 Pão de Alho + 1 Espeto de Carne + 1 Espeto de Frango + 1 Espeto de Calabresa Defumada + 1 Guaraná 269ml (lata))']\n\n\nlista_itens_factura = []\nlista_precos_factura = []\ncont_esp = 0\ndata = date.today()\nindice_da_semana = data.weekday()\ndia_da_semana = dias[indice_da_semana]\n\n\n\n\ndef car_esp():\n print(\"\"\"---------------------------------------------------\n ESPETINHOS\n---------------------------------------------------\"\"\")\n print(\"\"\"[1]- ESPETO DE CARNE - R$:8,00\n[2]- ESPETO DE CARNE (com creme de alho) - R$:9,50\n[3]- ESPETO DE PICAHNHA - R$:15,00\n[4]- ESPETO DE CUPIM - R$:13,00\n[5]- ESPETO DE CALABRESA DEFUMADA - R$:7,00\n[6]- ESPETO DE FRANGO - R$:8,00\n[7]- ESPETO DE COXINHA DE FRANGO - R$:9,50\n[8]- ESPETO DE CORAÇÃO - R$:8,00\n[9]- ESPETO DE KAFTA - R$:10,00\n[10]- ESPETO DE TOSCANA - R$:9,00\n[11]- MEDALHÃO DE CARNE - R$:13,50\n[12]- MEDALHÃO DE FRANGO - R$:11,50\n---------------------------------------------------\"\"\")\n\n\ndef car_acom():\n print(\"\"\"------------------------------------------------\n ACOMPANHAMENTOS\n------------------------------------------------\"\"\")\n print(\"\"\"[1]- PÃO DE ALHO - R$:6,00\n[2]- BATATA FRITA (P) - R$:8,00\n[3]- BATATA FRITA (M) - R$:14,00\n[4]- BATATA FRITA (G) - R$:24,00\n[5]- QUEIJO ASSADO c/MELAÇO OU s/MELAÇO R$:8,00\n------------------------------------------------\"\"\")\n\n\ndef car_bebida():\n print(\"\"\"-----------------------------------------------\n BEBIDAS\n-----------------------------------------------\"\"\")\n print(\"\"\"[1]- COCA-COLA 350ml (lata) - R$:5,00\n[2]- COCA-COLA (1 litro) - R$:9,00\n[3]- GUARANÁ 269ml (lata) - R$:3,00\n[4]- GUARANÁ 350ml (lata) - R$:3,50\n[5]- GUARANÁ (1 litro) - R$:9,00\n[6]- ÁGUA 300ml (sem gás) - R$:3,00\n[7]- ÁGUA 300ml (com gás) - R$:4,00\n[8]- DEVASSA PURO MALTE 350ml (lata) - R$:5,00\n[9]- HEINEKEN (long neck) - R$:9,00\n-----------------------------------------------\"\"\")\n\n\ndef car_combo():\n print(\"\"\"--------------------------------------\n COMBOS \n--------------------------------------\"\"\")\n print(f\"\"\"O COMBO {promoção_do_dia [indice_da_semana].split()[1]} ESTÁ EM PROMOÇÃO!!\nEstá custando {promoção_do_dia [indice_da_semana].split()[3]}\"\"\")\n print('--------------------------------------')\n print(\"\"\"[1]- COMBO 1 - R$:28,00\n(Batata Frita (P) + 1 Espeto de Picanha + Pão de Alho + 1 Guaraná 269ml (lata))\n[2]- COMBO 2 - R$:22,00\n(1 Espeto de Picanha + Batata Frita (P) + 1 Guaraná 269ml (lata))\n[3]- COMBO 3 - R$:33,00\n(File Acebolado + Batata Frita (M) + 1 Guaraná 269ml (lata))\n[4]- COMBO 4 - R$:22,00\n(1 Espeto de Carne + 1 Espeto de Frango + 1 Espeto de Calabresa Defumada + 1 Guaraná 269ml (lata))\n[5]- COMBO 5 - R$:22,00\n(1 Pão de Alho + 1 Espeto de Carne + 1 Espeto de Frango + 1 Guaraná 269ml (lata))\n[6]- COMBO 6 - R$:35,00\n(Carne do Sol Acebolada + Batata Frita (M) + 1 Guaraná 269ml (lata))\n[7]- COMBO 7 - R$:35,00\n(1 Pão de Alho + 1 Espeto de Carne + 1 Espeto de Frango + 1 Espeto de Calabresa Defumada + 1 Guaraná 269ml (lata))\n-------------------------------------------------------------------------------------------------------------------\"\"\")\n\n\ndef conta():\n global lista_itens_factura\n global lista_precos_factura\n\n print(\"\"\"|--------------------------------------|\n| SUA CONTA |\n|--------------------------------------|\"\"\")\n preco_final = 0\n\n for i in range(0, len(lista_itens_factura)):\n print(f'{lista_itens_factura[i]}')\n preco_final += lista_precos_factura[i]\n print('|--------------------------------------|')\n print()\n print('|--------------------------------------|')\n print(f'|Total a pagar: R$ {preco_final:.2f}|')\n print('|--------------------------------------|')\n print()\n print('Digite o endereço para a entrega.')\n\n\ndef verificar_tipo_pedido(valor='0', limite=1):\n while not valor.isdigit():\n print('Digite um número inteiro por-favor')\n valor = input(': ')\n valor = int(valor)\n\n if valor > limite or valor <= 0:\n print('A opção que você digitou não é válida! Por-favor tente novamente')\n return verificar_tipo_pedido(input(': '), limite)\n return valor\n\n\ndef verificar_quant_pedida(valor='0'):\n while not valor.isdigit():\n print('Digite um número inteiro por-favor')\n valor = input(': ')\n valor = int(valor)\n\n if valor <= 0:\n print('A opção que você digitou não é válida! Por-favor tente novamente')\n return verificar_tipo_pedido(input(': '))\n return valor\n\n\ndef efetuar_pedidos():\n global lista_itens_factura\n global lista_precos_factura\n print(\"\"\"---------------------------\n SUAS OPÇÕES:\n---------------------------\n[1]- ESPETINHOS\n[2]- ACOMPANHAMENTO\n[3]- BEBIDAS\n[4]- COMBOS\n[5]- CANCERLAR PEDIDO\n[6]- EFETUAR PEDIDO\n---------------------------\"\"\")\n\n op_pedido = input('Digite a opção: ').strip()[0]\n\n if op_pedido == '1':\n quant_esp = verificar_quant_pedida(input('Quantos você deseja? '))\n while quant_esp > 0:\n car_esp()\n sabor = verificar_tipo_pedido(input(f'Dígite o sabor do Espetinho: '), 12)\n quant = verificar_quant_pedida(input(f'Quantos {espetinho[sabor - 1][0]} você deseja: '))\n while quant > quant_esp:\n print(f'Infelizmente você pediu uma quantidade inferior a essa!'\n f'\\nDigite uma quantidade que vai de 1 até {quant_esp}')\n quant = verificar_quant_pedida(input(f'Quantos {espetinho[sabor - 1][0]} você deseja: '))\n quant_esp -= quant\n lista_itens_factura.append(espetinho[sabor - 1][0])\n lista_precos_factura.append(espetinho[sabor - 1][1] * quant)\n elif op_pedido == '2':\n quant_acom = verificar_quant_pedida(input('Quantos você deseja? '))\n while quant_acom > 0:\n car_acom()\n op_acom = verificar_tipo_pedido(input(f'Dígite o Acompanhamento: '), 5)\n quant = verificar_quant_pedida(input(f'Quantos {acompanhamento[op_acom - 1][0]} você deseja: '))\n while quant > quant_acom:\n print(f'Infelizmente você pediu uma quantidade inferior a essa!'\n f'\\nDigite uma quantidade que vai de 1 até {quant_acom}')\n quant = verificar_quant_pedida(input(f'Quantos {acompanhamento[op_acom - 1][0]} você deseja: '))\n quant_acom -= quant\n lista_itens_factura.append(acompanhamento[op_acom - 1][0])\n lista_precos_factura.append(acompanhamento[op_acom - 1][1] * quant)\n elif op_pedido == '3':\n quant_bebi = int(input('Quantos você deseja? '))\n while quant_bebi > 0:\n car_bebida()\n op_bebi = verificar_tipo_pedido(input(f'Dígite a Bebida: '), 9)\n quant = verificar_quant_pedida(input(f'Quantos {bebidas[op_bebi - 1][0]} você deseja: '))\n while quant > quant_bebi:\n print(f'Infelizmente você pediu uma quantidade inferior a essa!'\n f'\\nDigite uma quantidade que vai de 1 até {quant_bebi}')\n quant = verificar_quant_pedida(input(f'Quantas {bebidas[op_bebi - 1][0]} você deseja: '))\n quant_bebi -= quant\n lista_itens_factura.append(bebidas[op_bebi - 1][0])\n lista_precos_factura.append(bebidas[op_bebi - 1][1] * quant)\n elif op_pedido == '4':\n quant_combo = verificar_quant_pedida(input('Quantos você deseja? '))\n while quant_combo > 0:\n car_combo()\n op_combo = verificar_tipo_pedido(input(f'Dígite o Combo: '), 7)\n quant = verificar_quant_pedida(input(f'Quantos {combos[op_combo - 1][0]} você deseja: '))\n while quant > quant_combo:\n print(f'Infelizmente você pediu uma quantidade inferior a essa!'\n f'\\nDigite uma quantidade que vai de 1 até {quant_combo}')\n quant = verificar_quant_pedida(input(f'Quantas {combos[op_combo - 1][0]} você deseja: '))\n quant_combo -= quant\n lista_itens_factura.append(combos[op_combo - 1][0])\n\n if indice_da_semana == op_combo - 1:\n print(f'O combo {op_combo}: {combos[op_combo - 1][0]} está custando R$ {combos[op_combo - 1][1] - 5}\\nPorque está em promoção')\n lista_precos_factura.append((combos[op_combo - 1][1] - 5) * quant)\n else:\n lista_precos_factura.append(combos[op_combo - 1][1] * quant)\n elif op_pedido == '5':\n lista_itens_factura.clear()\n lista_precos_factura.clear()\n elif op_pedido == '6':\n return False\n return True\n\n\ndef op_pedi():\n flag = efetuar_pedidos()\n while True:\n flag = efetuar_pedidos()\n\n if flag == False:\n print(\"\"\"-------------------------------------------\n Seu pedido foi realizado com sucesso!\n -------------------------------------------\"\"\")\n conta()\n break\n exit()\n\n\ndef vol_car():\n print(\"\"\"[1]- IR PARA O CARDÁPIO\n[2]- FAZER SEU PEDIDO\n[3]- VOLTAR AO MENU INICIAL\n--------------------------------------\"\"\")\n voltar = input('Dígite sua opção: ').strip()[0]\n if voltar != '1' and voltar != '2' and voltar != '3':\n print(\"\"\"------------------------------\n Não entendi.\n Dígite uma das opções:\n------------------------------\n[1]- IR PARA O CARDÁPIO\n[2]- FAZER SEU PEDIDO\n[3]- VOLTAR AO MENU PRINCIPAL\n------------------------------\"\"\")\n voltar = input('Dígite uma das opção: ').strip()[0]\n if voltar == '1':\n cardapio()\n elif voltar == '2':\n efetuar_pedidos()\n elif voltar == '3':\n main()\n\n\ndef menu_principal():\n print(\"\"\"--------------------------\nDígite uma das opções:\n--------------------------\n[1]- PROMOÇÕES DO DIA\n[2]- CARDÁPIO\n[3]- FAZER SEU PEDIDO\n[4]- FINALIZAR ATENDIMENTO\n---------------------------\"\"\")\n\n\ndef promocao_do_dia():\n print(f\"\"\"--------------------------------------\nPROMOÇÃO DO DIA ({dia_da_semana})\n--------------------------------------\n{promoção_do_dia[indice_da_semana]}\n--------------------------------------\"\"\")\n vol_car()\n\n\ndef cardapio():\n print(\"\"\"---------------------------\n CARDÁPIO\n---------------------------\n[1]- ESPETINHOS\n[2]- ACOMPANHAMENTO\n[3]- BEBIDAS\n[4]- COMBOS\n[5]- VOLTAR AO MENU INICIAL\n---------------------------\"\"\")\n\n car = input('Dígite sua Opção: ')\n print(\"\"\"----------------------------\"\"\")\n\n while car != '1' and car != '2' and car != '3' and car != '4' and car != '5':\n print(\"\"\"----------------------------\n Não entendi\n Dígite uma das opções\n----------------------------\n[1]- ESPETINHOS\n[2]- ACOMPANHAMENTO\n[3]- BEBIDAS\n[4]- COMBOS\n[5]- VOLTAR AO MENU INICIAL\n----------------------------\"\"\")\n car = input('Dígite sua Opção: ').strip()[0]\n\n if car == '1':\n car_esp()\n vol_car()\n elif car == '2':\n car_acom()\n vol_car()\n elif car == '3':\n car_bebida()\n vol_car()\n elif car == '4':\n car_combo()\n vol_car()\n elif car == '5':\n main()\n\n\ndef pedido():\n print('----------------------------------')\n pronto = input('Pronto para fazer seu pedido [S/N]: ').upper().strip()[0]\n\n if pronto != 'S' and pronto != 'N':\n print(\"\"\"Não entendi\nDígite [S] para SIM | [N] para NÃO \"\"\")\n pronto = str(input('Pronto para fazer seu pedido [S/N]: ')).upper().strip()[0]\n elif pronto == 'S':\n op_pedi()\n print(\"\"\"-----------------------------------\n Deseja fazer mais um pedido?\nDígite [S] para SIM e [N] para NÃO\n-----------------------------------\"\"\")\n else:\n menu_principal()\n\ndef main():\n menu_principal()\n op1 = input('Digite a opção: ').strip()[0]\n if op1 != '1' and op1 != '2' and op1 != '3' and op1 != '4':\n print(\"\"\"--------------------------\nNão entendi a opção dígitada.\"\"\")\n menu_principal()\n op1 = input('Digite a opção: ').strip()[0]\n if op1 == '1':\n promocao_do_dia()\n elif op1 == '2':\n cardapio()\n elif op1 == '3':\n pedido()\n elif op1 == '4':\n return False\n return True\n\n\nif __name__ == '__main__':\n hora = datetime.today().hour\n print(\"\"\"---------------------------- \n-- ESTAÇÃO DO ESPETINHO -- \n----------------------------\"\"\")\n sleep(0.5)\n\n if hora < 12:\n print('Olá Bom Dia!')\n elif hora < 18:\n print('Olá Boa Tarde!')\n else:\n print('Olá Boa Noite!')\n print(\"\"\"Seja Bem-vindo! \nSou sua atendente virtual!\neu me chamo Ana.\nirei passar agora suas opções\"\"\")\n sleep(1)\n while True:\n flag = main()\n\n if flag == False:\n break\n print(\"\"\"-----------------------------\n Obrigado, volte sempre.\n -----------------------------\"\"\")\n","sub_path":"App/ProjetoPython.py","file_name":"ProjetoPython.py","file_ext":"py","file_size_in_byte":15287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"360966554","text":"from selenium import webdriver\nimport time\n\ntry:\n browser = webdriver.Chrome() #将会拉起我们的chrome浏览器\n\n browser.get('https://www.douban.com') #接入我们的网址\n time.sleep(1)\n\n browser.switch_to.frame(browser.find_elements_by_tag_name('iframe')[0])\n btm1 = browser.find_element_by_xpath('/html/body/div[1]/div[1]/ul[1]/li[2]')\n btm1.click()\n time.sleep(1)\n\n browser.find_element_by_xpath('//*[@id=\"username\"]').send_keys('1249200310@qq.com')\n browser.find_element_by_id('password').send_keys('hkjlkjnkljn')\n time.sleep(1)\n browser.find_element_by_xpath('/html/body/div[1]/div[2]/div[1]/div[5]/a').click()\n\n cookies = browser.get_cookies()\n print(cookies)\n time.sleep(3)\n\nexcept Exception as e:\n print(e)\nfinally:\n browser.close()","sub_path":"week02/cookie_webdriver.py","file_name":"cookie_webdriver.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"465438501","text":"from re import compile\nfrom django.contrib.auth.views import redirect_to_login\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.conf import settings\n\n\nEXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]\nif hasattr(settings, 'LOGIN_EXEMPT_URLS'):\n EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]\n\n \n\nclass LoginRequiredMiddleware:\n \"\"\"\"\"\"\n def process_request(self, request):\n assert hasattr(request, 'user')\n if not request.user.is_authenticated():\n path = request.path_info.lstrip('/') or \"/\"\n if not any(m.match(path) for m in EXEMPT_URLS) and not path == \"/\":\n path = request.get_full_path()\n return redirect_to_login(path, settings.LOGIN_URL, REDIRECT_FIELD_NAME)","sub_path":"level_auth/level_auth/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"496078813","text":"from django.conf import settings\nfrom django.conf.urls import include, url\nfrom django.conf.urls.static import static\n\n\nfrom django.contrib import admin\n\nfrom carts.views import CartView, CheckoutView, ItemCountView\nfrom orders.views import AddressSelectFormView\n\nurlpatterns = [\n # Examples:\n\n url(r'^$', 'newsletter.views.home', name='home'),\n\n url(r'^contact/$', 'newsletter.views.contact', name='contact'),\n url(r'^about/$', 'ecomerce2.views.about', name='about'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^accounts/', include('registration.backends.default.urls')),\n\n\n url(r'^cart/$', CartView.as_view(), name='cart'),\n url(r'^cart/count/$', ItemCountView.as_view(), name='item_count'),\n url(r'^checkout/$', CheckoutView.as_view(), name='checkout'),\n url(r'^checkout/address/$', AddressSelectFormView.as_view(), name='address'),\n\n url(r'^products/', include('products.urls')),\n #url(r'^carts/', include('carts.urls')),\n\n\n]#nai h oraha muj se kaam its deadly slow...u need to restart systemok. waisay ap ne CartView ko quotes main present kiyaa thaa\n#muje b samaj naai aaya...aur????????????????\n\nif settings.DEBUG:\n\turlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\turlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"ecomerce2/src/ecomerce2/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"379473757","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Created by imoyao at 2019/11/13 15:31\n\n\n# def bubble_sort(alist):\n# length = len(alist)\n# for i in range(length - 1):\n# swapped = False\n# for j in range(length - 1 - i):\n# if alist[j] > alist[j + 1]:\n# swapped = True\n# alist[j], alist[j + 1] = alist[j + 1], alist[j]\n# while not swapped:\n# break\n# return alist\ndef bubble_sort(alist):\n length = len(alist)\n for i in range(length - 1):\n swapped = False\n for j in range(length - i - 1):\n if alist[j] > alist[j + 1]:\n swapped = True\n alist[j], alist[j + 1] = alist[j + 1], alist[j]\n while not swapped:\n break\n return alist\n\n\n# def select_sort(alist):\n# length = len(alist)\n# for i in range(length - 1):\n# min_item_index = i\n# for j in range(i + 1, length):\n# if a[j] < a[min_item_index]:\n# min_item_index = j\n# alist[min_item_index], a[i] = alist[i], a[min_item_index]\n# return alist\ndef select_sort(alist):\n length = len(alist)\n while length <= 1:\n return alist\n for i in range(length - 1):\n min_item_index = i\n for j in range(i, length):\n if alist[j] < alist[min_item_index]:\n min_item_index = j\n\n\ndef insert_sort(alist):\n length = len(alist)\n for index in range(1, length):\n while index > 0 and alist[index - 1] > alist[index]:\n alist[index], alist[index - 1] = alist[index - 1], alist[index]\n return alist\n\n\nif __name__ == '__main__':\n a = [12, 5, 2, 4, 1, 5, 7, 0, 23]\n print(bubble_sort(a))\n print(select_sort(a))\n print(insert_sort(a))\n","sub_path":"codes/foo.py","file_name":"foo.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"227431315","text":"# https://leetcode.com/problems/merge-k-sorted-lists/\n'''\nMerge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.\n\nHide Tags Divide and Conquer Linked List Heap\n'''\nimport heapq\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param {ListNode[]} lists\n # @return {ListNode}\n def mergeKLists(self, lists):\n heap = []\n dummy_head = ListNode(None)\n p = dummy_head\n\n for node in lists:\n if node is not None:\n heap.append((node.val, node))\n heapq.heapify(heap)\n while heap:\n ignore, f = heapq.heappop(heap)\n p.next = f\n f = f.next\n if f is not None:\n heapq.heappush(heap, (f.val, f))\n p = p.next\n return dummy_head.next\n","sub_path":"merge_k_sorted_lists/solution2.py","file_name":"solution2.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"85950934","text":"from PyQt5.QtWidgets import QApplication\r\nfrom function.ui_function.ui_dialog_readXfile import ChildWin\r\n\r\n\r\ndef main():\r\n import sys\r\n app = QApplication(sys.argv)\r\n window = ChildWin()\r\n window.show()\r\n app.exec_()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"main/main_readXfile.py","file_name":"main_readXfile.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"409864616","text":"from machine import Pin, I2C, reset, unique_id, freq\nfrom time import sleep, time, localtime\nfrom ubinascii import hexlify\nfrom boot import load_config\nfrom umqttsimple import MQTTClient\nfrom ssd1306_flipped import SSD1306_I2C\nfrom ahtx0 import AHT20\nfrom sht30 import SHT30\nfrom bme280 import BME280\nfrom mq9 import MQ\nfrom ds1307 import DS1307\nimport bh1750fvi\nfrom writer_minimal import Writer\nimport Arial11\n\n\nQOS=1\n# select GPIO pins\nif freq() > 80000000: # ESP32\n pin_scl = 22\n pin_sda = 21\n pin_sens = 16\nelse: # ESP8266\n pin_scl = 5\n pin_sda = 4\n pin_sens = 2\n\nfrequency = 100000\nwidth = 64\nheight = 48\nBME280_OSAMPLE_16 = 5\nOP_SINGLE_HRES2 = 0x21\n\n\ndisplay_address1 = 0x3C\nahtx0_address = 0x38\nsht3x_address1 = 0x44\nbmx_address1 = 0x76\nlight_address1 = 0x23\ndisplay_address2 = 0x3D\nsht3x_address2 = 0x45\nbmx_address2 = 0x77\nlight_address2 = 0x5C\nds1307_address = 0x68\n\n# mq9_present needs to be set Ture or False manually\nmq9_present = False\ndisplay_present1 = False\nahtx0_present = False\nsht3x_present1 = False\nbmx_present1 = False\nlight_present1 = False\ndisplay_present2 = False\nsht3x_present2 = False\nbmx_present2 = False\nlight_present2 = False\nds1307_present = False\n\ni2c = I2C(scl=Pin(pin_scl), sda=Pin(pin_sda), freq=frequency)\ndevices = i2c.scan()\n\nfor device in devices:\n if device == display_address1:\n display_present1 = True\n if device == ahtx0_address:\n ahtx0_present = True\n if device == sht3x_address1:\n sht3x_present1 = True\n if device == bmx_address1:\n bmx_present1 = True\n if device == light_address1:\n light_present1 = True \n if device == display_address2:\n display_present2 = True\n if device == sht3x_address2:\n sht3x_present2 = True\n if device == bmx_address2:\n bmx_present2 = True\n if device == light_address2:\n light_present2 = True\n if device == ds1307_address:\n ds1307_present = True \n \nif display_present2:\n oled = SSD1306_I2C(width, height, i2c, addr=display_address2)\nif display_present1:\n oled = SSD1306_I2C(width, height, i2c, addr=display_address1)\nif ahtx0_present: \n sensor = AHT20(i2c)\nif sht3x_present2: \n sensor = SHT30(scl_pin=pin_scl, sda_pin=pin_sda, i2c_address=sht3x_address2) \nif sht3x_present1: \n sensor = SHT30(scl_pin=pin_scl, sda_pin=pin_sda, i2c_address=sht3x_address1)\nif bmx_present2:\n sensor2 = BME280(mode=BME280_OSAMPLE_16, address=bmx_address2,i2c=i2c)\nif bmx_present1:\n sensor2 = BME280(mode=BME280_OSAMPLE_16, address=bmx_address1,i2c=i2c)\nif ds1307_present:\n rtc = DS1307(i2c)\n \ntopic1 = b'TempDHT22'\ntopic2 = b'HumidDHT22'\ntopic3 = b'Press'\ntopic4 = b'Light'\ntopic5 = b'LPG'\ntopic6 = b'CO'\ntopic7 = b'ME'\n\nclient_id = hexlify(unique_id())\n\ndef connect_to_mqtt(config):\n client = MQTTClient(client_id, config['mqtt']['broker'])\n client.connect()\n print('Connected to %s MQTT broker' % (config['mqtt']['broker']))\n return client\n \ndef restart_and_reconnect():\n print('Failed to connect to MQTT broker. Restarting and reconnecting...')\n sleep(10)\n reset()\n \n# Main loop that will run forever:\ndef main(config):\n \n try:\n client = connect_to_mqtt(config)\n except OSError:\n sleep(10)\n restart_and_reconnect()\n \n if (display_present1 or display_present2):\n writer = Writer(oled, Arial11)\n while True:\n if (display_present1 or display_present2):\n oled.fill(0)\n oled.show()\n if ahtx0_present:\n temperature = sensor.temperature\n humidity = sensor.relative_humidity\n if (sht3x_present1 or sht3x_present2):\n temperature, humidity = sensor.measure() \n if (bmx_present1 or bmx_present2):\n temperature = sensor2.temperature\n if (ahtx0_present or sht3x_present1 or sht3x_present2 or bmx_present1 or bmx_present2): \n temp_only = (\"%.4s\" % temperature)\n if (sht3x_present1 or sht3x_present2 or ahtx0_present):\n humid_only = (\"%.4s\" % humidity)\n if (bmx_present1 or bmx_present2):\n pressure = sensor2.pressure \n press_float = float(pressure[:-3]) \n press_only = (\"%.0f\" % press_float)\n if (light_present1 or light_present2): \n light = bh1750fvi.sample(i2c, mode=OP_SINGLE_HRES2)\n if ((display_present1 or display_present2) and (light_present1 or light_present2) and light > 0): \n writer.set_textpos(0,0)\n writer.printstring(\"T: \"+temp_only+\"°C\")\n writer.set_textpos(12,0)\n writer.printstring(\"H: \"+humid_only+\" %\")\n if (bmx_present1 or bmx_present2):\n writer.set_textpos(24,0)\n writer.printstring(press_only+\" hPa\")\n if (light_present1 or light_present2):\n writer.set_textpos(36,0)\n writer.printstring((\"%.4s\" % light) +\" lux\")\n oled.show()\n if (ahtx0_present or sht3x_present1 or sht3x_present2 or bmx_present1 or bmx_present2): \n print(\"Temperature: \"+temp_only+\"°C\")\n if (sht3x_present1 or sht3x_present2 or ahtx0_present): \n print(\"Humidity: \"+humid_only+\" %\")\n if (bmx_present1 or bmx_present2):\n print(\"Pressure: \"+press_only+\" hPa\") \n if (light_present1 or light_present2):\n print(\"Light Intensity: \"+(\"%.4s\" % light)+\" lux\")\n sleep(25)\n if (display_present1 or display_present2):\n oled.fill(0)\n oled.show()\n if mq9_present: \n mq = MQ()\n perc = mq.MQPercentage()\n gas_lpg = perc[\"GAS_LPG\"]\n co = perc[\"CO\"]\n methane = perc[\"SMOKE\"]\n print(\"Gas_LPG: \"+str(float(\"%.2g\" % gas_lpg)))\n print(\"CO: \"+str(float(\"%.2g\" % co)))\n print(\"Methane: \"+str(float(\"%.2g\" % methane))) \n if (light_present1 or light_present2): \n light = bh1750fvi.sample(i2c, mode=OP_SINGLE_HRES2) \n if ((display_present1 or display_present2) and (light_present1 or light_present2) and light > 0):\n writer.set_textpos(0,0)\n writer.printstring(\"LP \"+str(float(\"%.2g\" % gas_lpg))) \n writer.set_textpos(12,0)\n writer.printstring(\"CO \"+str(float(\"%.2g\" % co))) \n writer.set_textpos(24,0)\n writer.printstring(\"ME \"+str(float(\"%.2g\" % methane))) \n oled.show() \n if ds1307_present: \n rtc.halt(False) # power-up RTC oscillator \n datetime = rtc.datetime()\n date_str = str(datetime[1])+\"-\"+str(datetime[2])+\"-\"+str(datetime[0])[-2:] \n time_str = str(datetime[4])+\"h:\"+\"{:0>{w}}\".format(str(datetime[5]), w=2)+\"m\"\n if (display_present1 or display_present2):\n sleep(25)\n oled.fill(0)\n oled.show()\n writer.set_textpos(0,0)\n writer.printstring(date_str)\n writer.set_textpos(12,0)\n writer.printstring(time_str)\n oled.show() \n print(date_str)\n print(time_str)\n try: \n client.publish(topic1, str(temp_only), qos=QOS)\n if (sht3x_present1 or sht3x_present2 or ahtx0_present):\n client.publish(topic2, str(humid_only), qos=QOS)\n if (bmx_present1 or bmx_present2): \n client.publish(topic3, str(press_only), qos=QOS)\n if (light_present1 or light_present2):\n client.publish(topic4, str(light), qos=QOS)\n if mq9_present: \n client.publish(topic5, str(gas_lpg), qos=QOS)\n client.publish(topic6, str(co), qos=QOS)\n client.publish(topic7, str(methane), qos=QOS) \n except OSError:\n restart_and_reconnect() \n sleep(25)\n if (display_present1 or display_present2):\n oled.fill(0)\n oled.show() \n sleep(25)\n \nif __name__ == \"__main__\":\n main(load_config())","sub_path":"main_AHT20_SHT30_BMP280_1750_DS1307.py","file_name":"main_AHT20_SHT30_BMP280_1750_DS1307.py","file_ext":"py","file_size_in_byte":8277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"245692612","text":"import logging\nfrom sima import config\nlogging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] %(message)s')\n\nmy_config = config.Config()\nerror = my_config.setconfig()\n\nif type(error) is str:\n log(3, error)\n sys.exit(1)\n\nif not my_config.debug_mode:\n\tlogging.getLogger(\"requests\").setLevel(logging.WARNING)\n\tlogging.getLogger(\"urllib3\").setLevel(logging.WARNING)\n\nGREEN = ('\\033[92m') #green\nYELLOW = ('\\033[93m') #yellow\nRED = ('\\033[91m') #red\nEND = ('\\033[0m') #reset\n\ndef log(code, msg):\n\tmsg = str(msg)\n\tif code == 0 and my_config.debug_mode:\n\t\tlogging.debug(msg)\n\tif code == 1:\n\t\tlogging.info(GREEN + msg + END)\n\tif code == 2:\n\t\tlogging.warning(YELLOW + msg + END)\n\tif code == 3:\n\t\tlogging.error(RED + msg + END)","sub_path":"SimaSLI/sima/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"408662871","text":"from acturialcapital.pyStrap import os\r\nfrom acturialcapital.pyStrap import webbrowser\r\nfrom acturialcapital.pyStrap import markup\r\n# Note: We import \"add\" and \"grid\" to allow the user to get directly these\r\n# modules by typing pystrap.add and pystrap.grid without having to remember it. \r\n# Improve functionality, but implies redundancy in the code... \r\n# The user will still have the choice to import modules \"add\" to\r\n# get a lighter synthax.\r\nfrom acturialcapital.pyStrap import add, grid # imported but unused here\r\n\r\nclass Doc:\r\n\r\n def __init__(self, path, doc_name):\r\n \"\"\"\r\n Launch pyStrap JS, HTML and CSS tag appender.\r\n Main functions are insert, save and show.\r\n \r\n Parameters\r\n ----------\r\n path : str\r\n Location where to file will be saved.\r\n \r\n doc_name : str\r\n Name of the file.\r\n \"\"\" \r\n self.path=path\r\n self.doc_name=doc_name + '.html'\r\n self.components=[]\r\n \r\n def insert(self, *args):\r\n \"\"\"\r\n Add item to components iterator.\r\n \r\n Parameters\r\n ----------\r\n *args : function\r\n Item(s) to be interated through the figure.\r\n \"\"\" \r\n if not len(args)==0: \r\n for arg in args: return self.components.append(arg)\r\n \r\n def save(self, title='pyStrap'):\r\n \"\"\"\r\n save Doc.\r\n \r\n Parameters\r\n ----------\r\n title : str\r\n Item(s) to be interated through the figure.\r\n \"\"\" \r\n with open(os.path.join(self.path, self.doc_name), 'w') as f:\r\n f.write(''.join(markup.standard_open(title=title)))\r\n f.write(''.join(self.components))\r\n f.write(''.join(markup.standard_close()))\r\n \r\n def show(self, title='pyStrap'):\r\n \"\"\"\r\n save and show Doc.\r\n \r\n Parameters\r\n ----------\r\n *args : function\r\n Item(s) to be interated through the figure. \r\n \"\"\" \r\n self.save(title)\r\n webbrowser.open(os.path.join(self.path, self.doc_name), new=2)","sub_path":"pystrap.py","file_name":"pystrap.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"573027636","text":"# Logistics\n# First unlock some tests:\n# python3 ok -u\n\n# Part I: The reader\n\n# Problem 1 > Suite 1 > Case 2\nfrom scheme_reader import *\ntokens = tokenize_lines([\"(+ 1 \", \"(23 4)) (\"])\nsrc = Buffer(tokens)\n\nsrc.current()\n# >>> \"(\"\n\nsrc.remove_front()\n# >>> \"(\"\n\nsrc.current()\n# >>> \"+\"\n\nsrc.remove_front()\n# >>> \"+\"\n\nsrc.remove_front()\n# >>> 1\n\nscheme_read(src) # Returns and removes the next complete expression in src\n# >>> Pair(23, Pair(4, nil))\n\nsrc.current()\n# >>> \")\"\n\n\n# Problem 1 > Suite 1 > Case 3\nfrom scheme_reader import *\n\nscheme_read(Buffer(tokenize_lines([\"(23 4)\"])))\n# >>> Pair(23, Pair(4, nil))\n\nread_line(\"(23 4)\") # Shorter version of above!\n# >>> Pair(23, Pair(4, nil))\n\n\n# Problem 1 > Suite 1 > Case 4\nfrom scheme_reader import *\n\nread_tail(Buffer(tokenize_lines([\")\"])))\n# >>> nil\n\nread_tail(Buffer(tokenize_lines([\"1 2 3)\"])))\n# >>> Pair(1, Pair(2, Pair(3, nil)))\n\nread_tail(Buffer(tokenize_lines([\"2 (3 4))\"])))\n# >>> Pair(2, Pair(Pair(3, Pair(4, nil)), nil))\n\n# Problem 1 > Suite 1 > Case 7\nread_line(\"(+ (- 2 3) 1)\")\n# >>> Pair(\"+\", Pair(Pair(\"-\", Pair(2, Pair(3, nil))), Pair(1, nil)))\n# 相当于一个分叉链表\n\n\n# Problem 2 > Suite 1 > Case 1 - Case 4, Case 6-8 omitted\nfrom scheme_reader import *\n\nread_line(\"(a . b)\")\n# >>> Pair(\"a\", \"b\")\n\nread_line(\"(a b . c)\")\n# >>> Pair(\"a\", Pair(\"b\", \"c\"))\n\nread_line(\"(a b . c d)\")\n# >>> Syntax Error # 若\".\"不在末尾, 则不行, 必须是 (a (b . c) d)\n\nread_line(\"(a . (b . (c . ())))\")\n# >>> Pair(\"a\", Pair(\"b\", Pair(\"c\", nil))) # 就是标准链表\n\nread_line(\"(a . ((b . (c))))\")\n# >>> Pair(\"a\", Pair(Pair(\"b\", Pair(\"c\", nil)), nil)) # 双括号则又相当于分叉链表了\n\n\n\n\n\n\n# Part II: The evaluator\n\n# Understanding scheme.py > Suite 1 > Case 1 - Case\n# Q: A Scheme expression can be either...\n# A: A primitive expression or a list expression\n\n# Q: What expression in the body of scheme_eval finds the value of a name?\n# A: env.lookup(expr)\n\n# Q: How do we know if a given list expression is a special form?\n# A: Check if the first element in the list is a symbol and that that symbol is in the dictionary SPECIAL_FORMS\n\n# Q: What exception should be raised for the expression (1)?\n# SchemeError(\"1 is not callable\")\n\n\n# Problem 3 > Suite 1 > Case 1\nfrom scheme import *\nglobal_frame = create_global_frame()\nglobal_frame.define(\"x\", 3)\nglobal_frame.parent is None\n# >>> True\n\nglobal_frame.lookup(\"x\")\n# >>> 3\n\nglobal_frame.define(\"x\", 2)\nglobal_frame.lookup(\"x\")\n# >>> 2\n\nglobal_frame.lookup(\"foo\")\n# >>> SchemeError\n\n# Problem 3 > Suite 1 > Case 2\nfrom scheme import *\n\nfirst_frame = create_global_frame()\nfirst_frame.define(\"x\", 3)\nsecond_frame = Frame(first_frame)\nsecond_frame.parent == first_frame\n# >>> True\n\nsecond_frame.lookup(\"x\")\n# >>> 3\n\n\n# Problem 4 > Suite 1 > Case 1\nfrom scheme import *\n\nenv = create_global_frame()\ntwos = Pair(2, Pair(2, nil))\nplus = PrimitiveProcedure(scheme_add) # + procedure\nscheme_apply(plus, twos, env) # Type SchemeError if you think this errors\n# >>> 4\n\n# Problem 4 > Suite 1 > Case 2\nenv = create_global_frame()\ntwos = Pair(2, Pair(2, nil))\noddp = PrimitiveProcedure(scheme_oddp) # odd? procedure\nscheme_apply(oddp, twos, env) # Type SchemeError if you think this errors\n# >>> SchemeError\n\n\n# Problem 5 > Suite 1 > Case 1\nfrom scheme_reader import *\nfrom scheme import *\n\nexpr = read_line(\"(+ 2 2)\")\nscheme_eval(expr, create_global_frame()) # Type SchemeError if you think this errors\n# >>> 4\n\nexpr = read_line(\"(+ (+ 2 2) (+ 1 3) (* 1 4))\")\nscheme_eval(expr, create_global_frame()) # Type SchemeError if you think this errors\n# >>> 12\n\nexpr = read_line(\"(yolo)\")\nscheme_eval(expr, create_global_frame()) # Type SchemeError if you think this errors\n# >>> SchemeError\n\n# scm> (+ 2 3) ; Type SchemeError if you think this errors\n# >>> 5\n\n# scm> (* (+ 3 2) (+ 1 7)) ; Type SchemeError if you think this errors\n# >>> 40\n\n# scm> (1 2) ; Type SchemeError if you think this errors\n# >>> SchemeError\n\n# scm> (1 (print 0)) ; check_procedure should be called before operands are evaluated\n# >>> SchemeError\n\n\n# Problem 6 > Suite 1 > Case 1 - Case 2\n\n# Q: What is the structure of the expressions argument to do_define_form?\n# A: Pair(A, Pair(B, nil)), where:\n# A is the symbol being bound,\n# B is an expression whose value should be bound to A\n\n# Q: What method of a Frame instance will binda value to a symbol in that frame?\n# A: define\n\n\n# Problem 6 > Suite 2 > Case 1 - Case 4\n\n# scm> (define size 2)\n# >>> size\n\n# scm> size\n# >>> 2\n\n# scm> (define x (+ 2 3))\n# >>> x\n\n# scm> x\n# >>> 5\n\n# scm> (define x (+ 2 7))\n# >>> x\n\n# scm> x\n# >>> 9\n\n# scm> (eval (define tau 6.28))\n# >>> 6.28\n\n\n# Problem 7 > Suite 1 > Case 1\n\n# Q: What is the structure of the expressions argument to do_quote_form?\n# A: Pair(A, nil), where:\n# A is the quoted expression\n\n# Problem 7 > Suite 2 > Case 1\n\n# scm> (quote hello)\n# >>> hello\n\n# scm> 'hello\n# >>> hello\n\n# scm> \"\"hello\n# >>> (quote hello)\n\n# scm> (quote (1 2))\n# >>> (1 2)\n\n# scm> '(1 2)\n# >>> (1 2)\n\n# scm> (quote (1 . 2))\n# >>> (1 . 2)\n\n# scm> '(1 . (2))\n# >>> (1 2)\n\n# scm> (car '(1 2 3))\n# >>> 1\n\n# scm> (cdr '(1 2))\n# >>> (2)\n\n# scm> (car (car '((1))))\n# >>> 1\n\n# scm> (quote 3)\n# >>> 3\n\n# scm> (eval (cons \"car \"('(4 2))))\n# >>> 4\n\n# Problem 7 > Suite 3 > Case 1\nfrom scheme_reader import *\n\nread_line(\" (quote x) \")\n# >>> Pair(\"quote\", Pair(\"x\", nil))\n\nread_line(\" 'x \")\n# >>> Pair(\"quote\", Pair(\"x\", nil))\n\nread_line(\" (a b) \")\n# >>> Pair(\"a\", Pair(\"b\", nil))\n\nread_line(\" '(a b) \")\n# >>> Pair(\"quote\", Pair(Pair(\"a\", Pair(\"b\", nil)), nil))\n\nread_line(\" '((a)) \")\n# Pair(\"quote\", Pair(Pair(Pair(\"a\", nil), nil), nil))\n\n\n# Problem 8 > Suite 1 > Case 1\nfrom scheme import *\n\nenv = create_global_frame()\neval_all(Pair(2, nil), env)\n# >>> (0)\n\neval_all(Pair(4, Pair(5, nil)), env) # 从末尾开始\n# >>> (5)\n\n# Problem 8 > Suite 2 > Case 1\n\n\n# scm> (begin (+ 2 3) (+ 5 6)) # 从末尾开始\n# >>> 11\n\n# scm> (begin (define x 3) x)\n# >>> 3\n\n# scm> (begin 30 '(+ 2 2))\n# >>> (+ 2 2)\n\n# scm> (define x 0)\n# >>> x\n\n# scm> (begin 42 (define x (+ x 1)))\n# >>> x\n\n# scm> x\n# >>> 1 # 之前定义了x=0\n\n\n# Problem 9 > Suite 1 > Case 1\n\n# scm> (lambda (x y) (+ x y)\n# >>> (lambda (x y) (+ x y))\n\n\n# Problem 10 > Suite 1 > Case 1\n\n# scm> (define (f x y) (+ x y))\n# >>> f\n\n# scm> f\n# >>> (lambda (x y) (+ x y))\n\n\n# Problem 11 > Suite 1 > Case 1\nfrom scheme import *\n\nglobal_frame = create_global_frame()\nframe = global_frame.make_child_frame(Pair(\"a\", Pair(\"b\", Pair(\"c\", nil))), Pair(1, Pair(2, Pair(3, nil))))\nglobal_frame.lookup(\"a\") # Type SchemeError if you think this errors\n# >>> SchemeError\n\nframe.lookup(\"a\") # Type SchemeError if you think this errors\n# >>> 1\n\nframe.lookup(\"b\") # Type SchemeError if you think this errors\n# >>> 2\n\nframe.lookup(\"c\") # Type SchemeError if you think this errors\n# >>> 3\n\n# Problem 11 > Suite 1 > Case 2\n\nfrom scheme import *\nglobal_frame = create_global_frame()\nframe = global_frame.make_child_frame(nil, nil)\nframe.parent is global_frame\n# >>> True\n\n\n# Problem 12 > Suite 2 > Case 1\n# scm> (define (outer x y)\n# .... (define (inner z x)\n# .... (+ x (* y 2) (* z 3)))\n# .... (inner x 10))\n# >>> outer # 只是一个定义方程\n\n# scm> (outer 1 2)\n# 相当于执行 (inner 1 10)\n# (+ 10 (* 2 2) (* 1 3))\n# >>> 17\n\n# scm> (define (outer-func x y)\n# .... (define (inner z x)\n# .... (+ x (* y 2) (* z 3)))\n# .... inner)\n# >>> outer-func\n\n# scm> ((outer-func 1 2) 1 10)\n# 相当于(inner 1 10), x为inner的参数, 所以是10\n# (+ 10 (* 2 2) (* 1 3))\n# >>> 17\n\n\n\n\n# Special Forms\n\n# Problem 13 > Suite 1 > Case 1\n\n# Your interpreter should evaluate each sub-expression from left to right\n# and if any of these evaluates to a false value, then #f is returned.\n# Otherwise, it should return the value of the last sub-expression.\n# If there are no sub-expressions in an and expression, it evaluates to #t\n\n# scm> (and)\n# >>> #t\n\n# (and 1 False)\n# >>> #f\n\n# scm> (and (+ 1 1) 1)\n# >>> 1\n#\n\n# scm> (and False 5)\n# >>> #t\n\n# scm> (and 4 5 (+ 3 3))\n# >>> 6\n\n# scm> (and True False 42 (/ 1 0))\n# >>> #f\n# 忽略error直接给False\n\n# scm> (or)\n# >>> #f\n\n# scm> (or (+ 1 1))\n# >>> 2\n\n# scm> (or False (- 1 1) 1) ; 0 is a true value in Scheme\n# >>> 0\n\n# scm> (or False)\n# >>> #f\n\n# scm> (define (t) True)\n# >>> t\n\n# scm> (or (t) 3)\n# >>> #t\n\n# scm> (or 5 2 1)\n# >>> 5\n\n# scm> (or False (- 1 1) 1)\n# >>> 0\n\n# scm> (or 4 True (/ 1 0))\n# >>> 4\n\n\n# Problem 14 > Suite 1 > Case 1\n# scm> (cond ((> 2 3) 5)\n# .... ((> 2 4) 6)\n# .... ((< 2 5) 7)\n# .... (else 8))\n# >>> 7\n\n# scm> (cond ((> 2 3) 5)\n# .... ((> 2 4) 6)\n# .... (else 8))\n# >>> 8\n\n\n# Problem 15 > Suite 1 > Case 1\n# The let special form binds symbols to values locally, giving them their initial values\n\n# scm> (define x 1)\n# >>> x\n\n# scm> (let ((x 5))\n# .... (+ x 3))\n# >>> 8\n\n# scm> x\n# >>> 1\n\n# Problem 15 > Suite 1 > Case 2\n\n# scm> (let ((a 1) (b a)) b)\n# >>> 1\n#\n# scm> (let ((x 5))\n# .... (let ((x 2)\n# .... (y x))\n# .... (+ y (* x 2)))) # 此时y = 5, x = 2\n# >>> 9\n\n\n# Problem 16 > Suite 1 > Case 1\n# A mu expression is similar to a lambda expression,\n# but evaluates to a MuProcedure instance that is dynamically scoped\n\n# scm> (define y 1)\n# >>> y\n\n# scm> (define f (mu (x) (+ x y)))\n# >>> f\n\n# scm> (define g (lambda (x y) (f (+ x x))))\n# >>> g\n\n# scm> (g 3 7)\n# g is lambda fucntion (g 3 8) = f(+ 3 3) = f 6\n# but when mu(x) look for y, y is found in last scope y=7 instead of y in global y=1.\n# therefore, f(6) = 6 + 7 = 13\n# >>> 13\n\n# In Python:\ny = 5\n\ndef foo(bar):\n y = 10\n return bar()\n\ndef bar():\n return y\n\nprint(foo(bar)) # >>> 5\n# not 10, because it does not look scope up, but start from global\n# it will raise error if can't find y in global, instead of binding to 5\n\n\n\n\n# Part III: Write Some Scheme\n# See questions.scm\n","sub_path":"ProgrammingCourses/CS61A/project/scheme/wb.py","file_name":"wb.py","file_ext":"py","file_size_in_byte":9811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"593037424","text":"# -*- coding: utf-8 -*-\r\n# @Time : 9:55 2020/10/20 \r\n# @Author : Haohao Song\r\n# @Email : songhaohao2018@cqu.edu.cn\r\n# @File : ijcai_spider.py\r\nimport json\r\nfrom urllib import request\r\n\r\nimport lxml.html as lh\r\n\r\nresponse=request.urlopen('http://static.ijcai.org/2020-accepted_papers.html')\r\ntext_html=response.read().decode('utf8')\r\n\r\nhtml=lh.document_fromstring(text_html)\r\nsections=html.xpath('/html/body/main/section')\r\n\r\nijcai20_accepted_dict=dict()\r\nfor one_section in sections:\r\n section_title=one_section.xpath('./div/h3/text()')[0]\r\n section_title=section_title.replace('\\'','').strip()\r\n\r\n ijcai20_accepted_dict[section_title]=list()\r\n\r\n print(section_title)\r\n\r\n all_papers=one_section.xpath('./div/li')\r\n\r\n for one_paper in all_papers:\r\n one_paper_title=one_paper.xpath('./strong/text()')[0]\r\n one_paper_title=one_paper_title.replace('\\'','').strip()\r\n\r\n one_paper_authors=one_paper.xpath('./em/text()')[0]\r\n one_paper_authors=one_paper_authors.replace('\\'','').strip()\r\n\r\n ijcai20_accepted_dict[section_title].append((one_paper_title,one_paper_authors))\r\n\r\n print(one_paper_title)\r\n print(one_paper_authors)\r\n\r\n\r\nwith open('./data/ijcai20.json','w',encoding='utf8') as fw:\r\n fw.write(json.dumps(ijcai20_accepted_dict,ensure_ascii=False))\r\n\r\n","sub_path":"Titles/20/ijcai/ijcai_tilte_collector.py","file_name":"ijcai_tilte_collector.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"538556759","text":"#! /usr/bin/env python\n# ______________________________________________________________________\n'''cfg\n\nDefines the ControlFlowGraph class, which is used by the Numba\ntranslator to perform accurate phi node generation.\n\nWhen used as the main module, displays the control flow graph for\narguments of the form . Example:\n\n% python -m numba.cfg test_while.while_loop_fn_0\n'''\n# ______________________________________________________________________\n\nimport opcode\nimport pprint\n\nfrom .utils import itercode\n\nimport sys\n\n# ______________________________________________________________________\n\nclass ControlFlowGraph (object):\n def __init__ (self):\n self.blocks = {}\n self.blocks_in = {}\n self.blocks_out = {}\n self.blocks_reads = {}\n self.blocks_writes = {}\n self.blocks_writer = {}\n self.blocks_dom = {}\n self.blocks_reaching = {}\n\n def add_block (self, key, value = None):\n self.blocks[key] = value\n if key not in self.blocks_in:\n self.blocks_in[key] = set()\n self.blocks_out[key] = set()\n self.blocks_reads[key] = set()\n self.blocks_writes[key] = set()\n self.blocks_writer[key] = {}\n\n def add_edge (self, from_block, to_block):\n self.blocks_out[from_block].add(to_block)\n self.blocks_in[to_block].add(from_block)\n\n @classmethod\n def build_cfg (cls, code_obj, *args, **kws):\n ret_val = cls(*args, **kws)\n opmap = opcode.opname\n ret_val.crnt_block = 0\n ret_val.code_len = len(code_obj.co_code)\n ret_val.add_block(0)\n ret_val.blocks_writes[0] = set(range(code_obj.co_argcount))\n last_was_jump = True # At start there is no prior basic block\n # to link up with, so skip building a\n # fallthrough edge.\n for i, op, arg in itercode(code_obj.co_code):\n if i in ret_val.blocks:\n if not last_was_jump:\n ret_val.add_edge(ret_val.crnt_block, i)\n ret_val.crnt_block = i\n last_was_jump = False\n method_name = \"op_\" + opmap[op]\n if hasattr(ret_val, method_name):\n last_was_jump = getattr(ret_val, method_name)(i, op, arg)\n del ret_val.crnt_block, ret_val.code_len\n return ret_val\n\n # NOTE: The following op_OPNAME methods are correct for Python\n # semantics, but may be overloaded for Numba-specific semantics.\n\n def op_FOR_ITER (self, i, op, arg):\n self.add_block(i)\n self.add_edge(self.crnt_block, i)\n self.add_block(i + arg + 3)\n self.add_edge(i, i + arg + 3)\n self.add_block(i + 3)\n self.add_edge(i, i + 3)\n self.crnt_block = i\n return False\n\n def op_JUMP_ABSOLUTE (self, i, op, arg):\n self.add_block(arg)\n self.add_edge(self.crnt_block, arg)\n self.add_block(i + 3)\n return True\n\n def op_JUMP_FORWARD (self, i, op, arg):\n target = i + arg + 3\n self.add_block(target)\n self.add_edge(self.crnt_block, target)\n self.add_block(i + 3)\n return True\n\n def op_JUMP_IF_FALSE_OR_POP (self, i, op, arg):\n raise NotImplementedError('FIXME')\n\n op_JUMP_IF_TRUE_OR_POP = op_JUMP_IF_FALSE_OR_POP\n\n def op_LOAD_FAST (self, i, op, arg):\n self.blocks_reads[self.crnt_block].add(arg)\n return False\n\n def op_POP_JUMP_IF_FALSE (self, i, op, arg):\n self.add_block(i + 3)\n self.add_block(arg)\n self.add_edge(self.crnt_block, i + 3)\n self.add_edge(self.crnt_block, arg)\n return True\n\n op_POP_JUMP_IF_TRUE = op_POP_JUMP_IF_FALSE\n\n def op_RETURN_VALUE (self, i, op, arg):\n if i + 1 < self.code_len:\n self.add_block(i + 1)\n return True\n\n def op_SETUP_LOOP (self, i, op, arg):\n self.add_block(i + 3)\n self.add_edge(self.crnt_block, i + 3)\n return True # This is not technically a jump, but we've\n # already built the proper CFG edges, so skip the\n # fallthrough plumbing.\n\n def _writes_local (self, block, write_instr_index, local_index):\n self.blocks_writes[block].add(local_index)\n block_writers = self.blocks_writer[block]\n old_index = block_writers.get(local_index, -1)\n # This checks for a corner case that would impact\n # numba.translate.Translate.build_phi_nodes().\n assert old_index != write_instr_index, (\n \"Found corner case for STORE_FAST at a CFG join!\")\n block_writers[local_index] = max(write_instr_index, old_index)\n\n def op_STORE_FAST (self, i, op, arg):\n self._writes_local(self.crnt_block, i, arg)\n return False\n\n def compute_dataflow (self):\n '''Compute the dominator and reaching dataflow relationships\n in the CFG.'''\n blocks = set(self.blocks.keys())\n nonentry_blocks = blocks.copy()\n for block in blocks:\n self.blocks_dom[block] = blocks\n self.blocks_reaching[block] = set((block,))\n if len(self.blocks_in[block]) == 0:\n self.blocks_dom[block] = set((block,))\n nonentry_blocks.remove(block)\n changed = True\n while changed:\n changed = False\n for block in nonentry_blocks:\n olddom = self.blocks_dom[block]\n newdom = set.intersection(*[self.blocks_dom[pred]\n for pred in self.blocks_in[block]])\n newdom.add(block)\n if newdom != olddom:\n changed = True\n self.blocks_dom[block] = newdom\n oldreaching = self.blocks_reaching[block]\n newreaching = set.union(\n *[self.blocks_reaching[pred]\n for pred in self.blocks_in[block]])\n newreaching.add(block)\n if newreaching != oldreaching:\n changed = True\n self.blocks_reaching[block] = newreaching\n return self.blocks_dom, self.blocks_reaching\n\n def update_for_ssa (self):\n '''Modify the blocks_writes map to reflect phi nodes inserted\n for static single assignment representations.'''\n joins = [block for block in self.blocks.iterkeys()\n if len(self.blocks_in[block]) > 1]\n changed = True\n while changed:\n changed = False\n for block in joins:\n phis_needed = self.phi_needed(block)\n for affected_local in phis_needed:\n if affected_local not in self.blocks_writes[block]:\n changed = True\n # NOTE: For this to work, we assume that basic\n # blocks are indexed by their instruction\n # index in the VM bytecode.\n self._writes_local(block, block, affected_local)\n\n def idom (self, block):\n '''Compute the immediate dominator (idom) of the given block\n key. Returns None if the block has no in edges.\n\n Note that in the case where there are multiple immediate\n dominators (a join after a non-loop branch), this returns one\n of the predecessors, but is not guaranteed to reliably select\n one over the others (depends on the ordering of the set type\n iterator).'''\n preds = self.blocks_in[block]\n npreds = len(preds)\n if npreds == 0:\n ret_val = None\n elif npreds == 1:\n ret_val = tuple(preds)[0]\n else:\n ret_val = [pred for pred in preds\n if block not in self.blocks_dom[pred]][0]\n return ret_val\n\n def block_writes_to_writer_map (self, block):\n ret_val = {}\n for local in self.blocks_writes[block]:\n ret_val[local] = block\n return ret_val\n\n def get_reaching_definitions (self, block):\n '''Return a nested map for the given block\n s.t. ret_val[pred][local] equals the block key for the\n definition of local that reaches the argument block via that\n predecessor.\n\n Useful for actually populating phi nodes, once you know you\n need them.'''\n has_memoized = hasattr(self, 'reaching_definitions')\n if has_memoized and block in self.reaching_definitions:\n ret_val = self.reaching_definitions[block]\n else:\n preds = self.blocks_in[block]\n ret_val = {}\n for pred in preds:\n ret_val[pred] = self.block_writes_to_writer_map(pred)\n crnt = self.idom(pred)\n while crnt != None:\n crnt_writer_map = self.block_writes_to_writer_map(crnt)\n # This order of update favors the first definitions\n # encountered in the traversal since the traversal\n # visits blocks in reverse execution order.\n crnt_writer_map.update(ret_val[pred])\n ret_val[pred] = crnt_writer_map\n crnt = self.idom(crnt)\n if not has_memoized:\n self.reaching_definitions = {}\n self.reaching_definitions[block] = ret_val\n return ret_val\n\n def nreaches (self, block):\n '''For each local, find the number of unique reaching\n definitions the current block has.'''\n # Slice and dice the idom tree so that each predecessor claims\n # at most one definition so we don't end up over or\n # undercounting.\n preds = self.blocks_in[block]\n idoms = {}\n idom_writes = {}\n # Fib a little here to truncate traversal in loops if they are\n # being chased before the actual idom of the current block has\n # been handled.\n visited = preds.copy()\n for pred in preds:\n idoms[pred] = set((pred,))\n idom_writes[pred] = self.blocks_writes[pred].copy()\n # Traverse up the idom tree, adding sets of writes as we\n # go.\n crnt = self.idom(pred)\n while crnt != None and crnt not in visited:\n idoms[pred].add(crnt)\n idom_writes[pred].update(self.blocks_writes[crnt])\n visited.add(crnt)\n crnt = self.idom(crnt)\n all_writes = set.union(*[idom_writes[pred] for pred in preds])\n ret_val = {}\n for local in all_writes:\n ret_val[local] = sum((1 if local in idom_writes[pred] else 0\n for pred in preds))\n return ret_val\n\n def phi_needed (self, join):\n '''Return the set of locals that will require a phi node to be\n generated at the given join.'''\n nreaches = self.nreaches(join)\n return set([local for local in nreaches.iterkeys()\n if nreaches[local] > 1])\n\n def pprint (self, *args, **kws):\n pprint.pprint(self.__dict__)\n\n def to_dot (self, graph_name = None):\n '''Return a dot (digraph visualizer in Graphviz) graph\n description as a string.'''\n if graph_name is None:\n graph_name = 'CFG_%d' % id(self)\n lines_out = []\n for block_index in self.blocks:\n lines_out.append(\n 'BLOCK_%r [shape=box, label=\"BLOCK_%r\\\\nr: %r, w: %r\"];' %\n (block_index, block_index,\n tuple(self.blocks_reads[block_index]),\n tuple(self.blocks_writes[block_index])))\n for block_index in self.blocks:\n for out_edge in self.blocks_out[block_index]:\n lines_out.append('BLOCK_%r -> BLOCK_%r;' %\n (block_index, out_edge))\n return 'digraph %s {\\n%s\\n}\\n' % (graph_name, '\\n'.join(lines_out))\n\n# ______________________________________________________________________\n\ndef main (*args, **kws):\n import getopt, importlib\n def get_module_member (member_path):\n ret_val = None\n module_split = member_path.rsplit('.', 1)\n if len(module_split) > 1:\n module = importlib.import_module(module_split[0])\n ret_val = getattr(module, module_split[1])\n return ret_val\n opts, args = getopt.getopt(args, 'dC:D:')\n kws.update(opts)\n dot_out = None\n cls = ControlFlowGraph\n for opt_key, opt_val in kws.iteritems():\n if opt_key == '-d':\n dot_out = sys.stdout\n elif opt_key in ('-D', 'dot'):\n dot_out = open(opt_val, \"w\")\n elif opt_key in ('-C', 'cfg_cls'):\n cls = get_module_member(opt_val)\n for arg in args:\n func = get_module_member(arg)\n if func is None:\n print(\"Don't know how to handle %r, expecting \"\n \"arguments. Skipping...\" % (arg,))\n elif not hasattr(func, 'func_code'):\n print(\"Don't know how to handle %r, module member does not \"\n \"have a code object. Skipping...\" % (arg,))\n else:\n cfg = cls.build_cfg(func.func_code)\n cfg.compute_dataflow()\n if dot_out is not None:\n dot_out.write(cfg.to_dot())\n else:\n cfg.pprint()\n\n# ______________________________________________________________________\n\nif __name__ == \"__main__\":\n import sys\n main(*sys.argv[1:])\n\n# ______________________________________________________________________\n# End of cfg.py\n","sub_path":"numba/cfg.py","file_name":"cfg.py","file_ext":"py","file_size_in_byte":13544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"269508773","text":"import sys\nimport datetime\nimport random\nimport os\n\nPROB = 0.5\n\nif __name__ == '__main__':\n\n path = '/home/ubuntu/mail/new/'\n log_file = open(\"filter.txt\", 'a')\n\n try:\n with open('/home/ubuntu/mailpath.txt') as f:\n mv_path = f.readline().strip()\n if mv_path[-1] != '/':\n mv_path = mv_path + '/'\n except:\n mv_path = '/home/ubuntu/mail/new/'\n\n for file in os.listdir(path):\n if (os.path.isfile(path + file)):\n try:\n log_file.write(str(datetime.datetime.now()) + '\\n')\n if (random.random() < PROB):\n log_file.write(\"phishing email detected in \" + str(path) + '\\n')\n os.remove(path + file);\n log_file.write(\"phishing email deleted\\n\")\n else:\n os.rename(path + file, mv_path + file)\n log_file.write(\"move email\\n\")\n except:\n pass\n\n log_file.close()\n","sub_path":"scripts/contractor/filterEmail.py","file_name":"filterEmail.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"373475390","text":"#! /usr/bin/python\nimport pygal\nimport string\nfrom boto.s3.connection import S3Connection\n\nsent_def_pos = 0\nsent_def_neg = 0\nsent_movie_pos = 0\nsent_movie_neg = 0\nAWS_KEY = 'KEY'\nAWS_SECRET = 'SECRET'\n\ndef traverse_data(data):\n\tout = 0\n\tfor item in data:\n\t\tif item.find(\"positive\") != -1:\n\t\t\tout = map(string.strip, filter(None, item.split(\"\\t\")))\n\t\t\t\n\t\telif item.find(\"negative\") != -1:\n\t\t\tout = map(string.strip, filter(None, item.split(\"\\t\")))\n\treturn out\n\ndef parse_default(str):\n\tglobal sent_def_pos\n\tglobal sent_def_neg\n\n\tdata = str.split(' ')\n\tout = traverse_data(data)\n\tif out == 0:\n\t\treturn\n\tif out[0].find('positive') != -1:\n\t\tsent_def_pos = int(out[1])\n\telif out[0].find('negative') != -1:\n\t\tsent_def_neg = int(out[1])\n\ndef parse_movie(str):\n\tglobal sent_movie_pos\n\tglobal sent_movie_neg\n\n\tdata = str.split(' ')\n\tout = traverse_data(data)\n\tif out[0].find('positive') != -1:\n\t\tsent_movie_pos = int(out[1])\n\telif out[0].find('negative') != -1:\n\t\tsent_movie_neg = int(out[1])\n\n# Get the s3 buckets that contain the output file\ndef crawl_s3_data(): \n\taws_connection = S3Connection(AWS_KEY, AWS_SECRET)\n\tbucket = aws_connection.get_bucket('mysentimentjob-sl3774')\n\tfor key in bucket.list():\n\t\tif (key.name.find(\"output_mov1\") != -1) and (key.size > 0):\n\t\t\tstr = key.get_contents_as_string()\n\t\t\tparse_movie(str)\n\t\telif (key.name.find(\"output_mov_0\") != -1) and (key.size > 0):\n\t\t\tstr = key.get_contents_as_string()\n\t\t\tparse_default(str)\n\n# Gen graph for keyword movie\ndef gen_graph():\n\tcrawl_s3_data()\n\tbar_chart = pygal.Bar()\n\tbar_chart.title = 'Sentiment Trend of 2015/05/14, keyword: movie'\n\tbar_chart.x_labels = [\"Default\", \"Movie Group\"] \n\tbar_chart.add('Negative', [sent_def_neg, sent_movie_neg])\n\tbar_chart.add('Positive', [sent_def_pos, sent_movie_pos])\n\tbar_chart.render_to_file('trend.svg')\n\nif __name__ == '__main__':\n\tgen_graph()\n","sub_path":"gen_svg.py","file_name":"gen_svg.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"315887159","text":"import random\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\n\nimport numpy as np\nimport matplotlib.patches as mpatches\n\n\n\nwidth = 0.35 # the width of the bars\n\nmy_xticks = ['0.0625',\n'0.125',\n'0.25',\n'0.375',\n'0.5',\n'0.75',\n'1',\n'1.25',\n'1.75',\n'2',\n'3',\n'4',\n'6',\n'8'\n]\n\n\nfig = plt.figure()\nax = fig.add_subplot(121)\nax1 = fig.add_subplot(122)\n\n\n#fig = plt.gcf()\n#fig.set_size_inches(5.5, 3.5)\n\n#fig_size = plt.rcParams[\"figure.figsize\"]\n\n#fig_size[0] = 6\n#fig_size[1] = 6\n\n\n#rects1 = ax.bar(x, stand_alone, width, label='Stand Alone')\n#rects1 = ax.bar(x - width/2, stand_alone, width, color='cornflowerblue')\nrects1 = ax.bar(x - width/2, stand_alone, width)\n#rects1 = ax.bar(x - width/2, stand_alone, width, label='Stand Alone')\n#rects2 = ax.bar(x, collocated, width, label='Collocated')\nrects2 = ax.bar(x + width/2, collocated, width)\n#rects2 = ax.bar(x + width/2, collocated, width, color='orange')\n#rects2 = ax.bar(x + width/2, collocated, width, label='Collocated')\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\nax.set_ylabel('Watt', fontsize=12)\n#ax.set_title('Memory Contention impact on Average Power', fontsize=16)\nax.set_title('Power', fontsize=16)\nax.set_xticks(x)\nax.set_ylim([4.00,11.00])\nax.set_xticklabels(labels, fontsize=12)\n#ax.legend(loc=1, bbox_to_anchor=(0.5, 0., 0.5, 0.99))\n\n#autolabel(rects1)\n#autolabel(rects2)\n\nax.set_xticks(np.arange(14), my_xticks, rotation='vertical')\n\n#plt.xticks(rotation=45)\n#plt.plot(data)\n\nplt.title('GPU vs CPU: Energy(mWatt-uSec)/flop comparison')\nplt.ylabel('mWatt-uSec/Flop(log)')\nplt.xlabel('Operational Intensity')\nplt.yscale('log')\nplt.legend(loc='lower center')\nplt.legend(['GPU', 'CPU'])\nplt.tight_layout()\n\n\n\n\n\nlabels = ['GPU', 'CPU']\nstand_alone = [6.316, 10.702]\ncollocated = [17.416, 17.416]\n\nx = np.arange(len(labels)) # the label locations\n#y = np.arange(len(labels)) # the label locations\n \nwidth = 0.35 # the width of the bars\n\n#rects1 = ax.bar(x, stand_alone, width, label='Stand Alone') \nrects1 = ax1.bar(x - width/2, stand_alone, width)\n#rects1 = ax1.bar(x - width/2, stand_alone, width, label='Stand Alone')\n#rects2 = ax.bar(x, collocated, width, label='Collocated')\nrects2 = ax1.bar(x + width/2, collocated, width)\n#rects2 = ax1.bar(x + width/2, collocated, width, label='Collocated')\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\nax1.set_ylabel('Second', fontsize=12)\nax1.set_title('Time', fontsize=16)\nax1.set_xticks(x)\nax1.set_yticks(np.arange(0, 20, 2))\n#ax1.set_ylim([0,2.0])\nax1.set_xticklabels(labels, fontsize=12)\n#ax1.legend(loc=1, bbox_to_anchor=(0.5, 0., 0.5, 0.99))\n\ndef autolabel(rects):\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 3), # 3 points vertical offset textcoords=\"offset points\",\n ha='center', va='bottom')\n\n\n#autolabel(rects1)\n#autolabel(rects2)\n\n\nlabels = ['GPU', 'CPU']\nstand_alone = [1.133433, 2.076453]\ncollocated = [1.877243, 3.570875]\n\nx = np.arange(len(labels)) # the label locations\n#y = np.arange(len(labels)) # the label locations\n \nwidth = 0.35 # the width of the bars\n\n#rects1 = ax.bar(x, stand_alone, width, label='Stand Alone') \n#rects1 = ax2.bar(x - width/2, stand_alone, width)\nrects1 = ax2.bar(x - width/2, stand_alone, width, label='Stand Alone')\n#rects2 = ax.bar(x, collocated, width, label='Collocated')\n#rects2 = ax2.bar(x + width/2, collocated, width)\nrects2 = ax2.bar(x + width/2, collocated, width, label='Collocated')\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\nax2.set_ylabel('Watt-Second', fontsize=12)\nax2.set_title('Energy', fontsize=16)\nax2.set_xticks(x)\nax2.set_yticks(np.arange(0, 6, 1))\n#ax2.set_ylim([0,4.500000])\nax2.set_xticklabels(labels, fontsize=12)\n#red_patch = mpatches.Patch(color='red', label='The red data')\n#plt.legend(handles=[red_patch])\nax2.legend(loc=1, bbox_to_anchor=(0.5, 0., 0.5, 0.99), facecolor='lightgrey', framealpha=1 )\n\ndef autolabel(rects):\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 3), # 3 points vertical offset textcoords=\"offset points\",\n ha='center', va='bottom')\n\n\n#autolabel(rects1)\n#autolabel(rects2)\n\nfig.subplots_adjust(wspace=.5)\n\n\n#ax1 = fig.add_subplot(121)\n#ax2 = fig.add_subplot(122)\n\n#x,y = create_plots()\n#ax1.plot(x,y)\n\n#x,y = create_plots()\n#ax2.plot(x,y)\n\n#x,y = create_plots()\n#ax3.plot(x,y)\n\n\nplt.show()\nfig.savefig('stream_combined.png', dpi=100)\n","sub_path":"python_plot/placement/combined_subplot.py","file_name":"combined_subplot.py","file_ext":"py","file_size_in_byte":4866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"427935176","text":"x=input().split()\ns=list(input())\nres={}\nfreq={}\nflag=1\nfor item in s: \n if item in freq: \n freq[item] += 1\n flag=0\n else:\n freq[item] =1\ntry:\n if freq[x[1]]>1:\n print(freq[x[1]])\n else:\n \tprint(\"0\")\nexcept:\n print(\"-1\")\n","sub_path":"check repeat.py","file_name":"check repeat.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"465884258","text":"import pygubu\nimport random\nimport numpy as np\nimport tkinter as tk \nimport matplotlib.pyplot as plt\nfrom tkinter import messagebox as msg\nimport time;\n\nclass Application:\n def __init__(self, master):\n\n #1: Create a builder\n self.builder = builder = pygubu.Builder()\n\n #2: Load an ui file\n builder.add_from_file('UI.ui')\n\n #3: Create the widget using a master as parent\n self.mainwindow = builder.get_object('AG', master)\n \n builder.connect_callbacks(self)\n\n def start(self):\n size_chromosome = int(self.builder.get_variable('size_knapsack').get())\n main_weight = int(self.builder.get_variable('main_weight').get())\n amoun_population = int(self.builder.get_variable('amount_population').get()) \n amount_generation = int(self.builder.get_variable('amount_generation').get()) \n\n if(self.get_values_main(size_chromosome, main_weight, amoun_population)):\n msg.showerror(\"Error\", \"Valores faltantes\")\n else:\n if(main_weight >= 300 ):\n self.start_generic_algorithms(size_chromosome, main_weight, amoun_population, amount_generation)\n else:\n msg.showwarning(\"Warning\",\"Ingresa una cantidad mayor a 100\")\n\n def get_values_main(self, size_chromosome, main_weight, amoun_population):\n if(size_chromosome == 0 or main_weight == 0 or amoun_population == 0):\n return True\n else:\n return False\n\n def create_population(self, size_chromosome, main_weight):\n return np.random.randint(low=10, high=main_weight-100, size=size_chromosome)\n\n def create_individuals(self, size_chromosome, amoun_population):\n flag, exit_zero = True, False\n array = []\n while (flag):\n array = np.random.randint(2, size=(amoun_population, size_chromosome))\n exit_zero = False\n for i in range(len(array)):\n sum_array = sum(array[i])\n if(sum_array == 0):\n exit_zero = True\n if(exit_zero):\n flag = True\n else:\n flag = False\n \n return array\n\n def get_individuals_converted(self, population, individuals):\n amount_indivuals = len(individuals)\n lenght_population = len(population)\n individuals_converted_list = []\n\n for i in range(amount_indivuals):\n individual_converted = []\n for j in range(lenght_population):\n # print('ALL GENE: {}'.format(individuals))\n # print('\\n')\n # print('ALL-GENE-2: {}'.format(individuals[i]))\n # print('\\n')\n gen = individuals[i][j]\n # print('Gen: {} \\n'.format(gen))\n if(gen == 1):\n individual_converted.append(population[j])\n individuals_converted_list.append(( individuals[i], individual_converted ))\n return individuals_converted_list\n \n def start_generic_algorithms(self, size_chromosome, main_weight, amoun_population, amount_generation = 100):\n flag, generation, i = True, 0, 0\n list_fitness, list_fiteness_wrong, list_fitness_mean = [], [], []\n #Initial population\n population = self.create_population(size_chromosome, main_weight)\n\n \n individuals = self.create_individuals(size_chromosome, amoun_population)\n\n while(flag and (i < amount_generation)):\n i += 1\n #Fitness function\n individuals = self.get_individuals_converted(population, individuals)\n individuals = self.get_fitness(individuals, main_weight, sum(population))\n individuals.sort(key = lambda x: x[1], reverse=True) \n\n # print('Indivuals')\n # # self.print_indivuals(individuals)\n # print(individuals)\n # print('\\n\\n')\n\n #Crossover\n children = self.crossover(individuals)\n\n print('\\n\\nHijos')\n print(children)\n\n #Mutacion\n children = self.mutacion(children, 0.8, 0.8)\n \n # print('\\n\\nHijos-mutados')\n # print(children)\n\n children = self.get_individuals_converted(population, children)\n children = self.get_fitness(children, main_weight, sum(population))\n\n # print('Hijos con fitness')\n # # self.print_indivuals(children)\n # print(children)\n # print('\\n\\n')\n\n individuals = individuals + children\n\n individuals.sort(key = lambda x: x[1], reverse=True) \n aux_individuals = list(map(lambda x: x[1], individuals))\n\n\n # print('Max: {}'.format(max(aux_individuals)))\n # print('Min: {}'.format(min(aux_individuals)))\n # print('Promedio: {}'.format(sum(aux_individuals)/len(aux_individuals)))\n \n \n individuals = individuals[:10]\n generation += 1\n list_fitness.append(max(aux_individuals))\n list_fiteness_wrong.append(min(aux_individuals))\n list_fitness_mean.append(sum(aux_individuals)/len(aux_individuals))\n\n\n if(max(aux_individuals) >= 0.8):\n flag = False\n else:\n individuals = list(map(lambda x: x[0], individuals))\n\n # print('\\nPoblacion con fitness-ordenados')\n # # self.print_indivuals(individuals)\n # print(individuals)\n\n print('M: {}'.format(len(list_fitness)))\n print('m: {}'.format(len(list_fiteness_wrong)))\n print('X: {}'.format(len(list_fitness_mean)))\n\n print('Better fitness: {}'.format(max(list_fitness)))\n print('Generacions: {}'.format(generation))\n print('s: {}'.format(len(list_fitness)))\n print('Termine')\n # self.draw_chart(list_fitness, generation)\n self.draw_chart_all(list_fitness_mean, list_fitness, list_fiteness_wrong, generation)\n def get_fitness(self, indivuals, main_weight, sum_population):\n amount_indivuals = len(indivuals)\n individuals_fitness = []\n for i in range(amount_indivuals):\n sum_indivuals = sum(indivuals[i][1])\n if(sum_indivuals <= main_weight):\n fitness = 1 - (((main_weight - sum_indivuals) / main_weight)**0.5)\n else:\n dividend = sum_indivuals - main_weight\n divisor = max(main_weight, (sum_population - main_weight))\n quotient = ((dividend / divisor) ** 0.0625)\n fitness = 1 - quotient \n\n # individuals_fitness.append((indivuals[i][0], indivuals[i][1], fitness))\n individuals_fitness.append((indivuals[i][0], fitness))\n return individuals_fitness\n \n def crossover(self, list_individuals):\n LENGTH_LIST = len(list_individuals)\n children = []\n\n for i in range (LENGTH_LIST-1):\n binaries_father, fitness_father = list_individuals[i]\n\n j = i + 1\n\n while j < LENGTH_LIST:\n probability_random = random.random()\n if(fitness_father > probability_random):\n # print('\\nApareamiento')\n binaries_mother, fitness_mother = list_individuals[j]\n # print('P_f:{} , F_f: {}'.format(binaries_father, fitness_father))\n # print('P_m:{} , F_m: {}'.format(binaries_mother, fitness_mother))\n first_children, second_children = self.get_children(binaries_father, binaries_mother)\n children.append(first_children); children.append(second_children)\n\n j += 1\n\n return children\n\n def get_children(self, binarie_father, binarie_mother):\n first_children, second_children, counter, i = [], [], 0, 0\n list_point_crossover = self.get_point_crossover(len(binarie_father))\n leght_size_pc = len(list_point_crossover) + 1\n\n while i < leght_size_pc:\n j = 0\n if(i == ( leght_size_pc - 1 )):\n part_father, part_mother = binarie_father[counter:], binarie_mother[counter:]\n j = 1\n else:\n jump = counter + list_point_crossover[i]\n part_father, part_mother = binarie_father[counter:jump], binarie_mother[counter:jump]\n \n counter = counter + list_point_crossover[i - j]\n\n # print('c1: {}, c2: {}'.format(part_father, part_mother))\n\n if(((i+1) % 2) != 0):\n # first_children, second_children = first_children + self.convert(part_father), second_children + self.convert(part_mother) \n # first_children += part_father; second_children += part_mother\n first_children = np.append(first_children, part_father); second_children = np.append(second_children, part_mother)\n if(((i+1) % 2) == 0):\n # first_children, second_children = first_children + self.convert(part_mother), second_children + self.convert(part_father) \n # first_children += part_mother; second_children += part_father\n first_children = np.append(first_children, part_mother); second_children = np.append(second_children, part_father)\n i = i + 1\n\n # print(\"Hijos:\")\n # print('uno: {}, dos: {} '.format(first_children, second_children))\n\n return first_children, second_children\n\n def get_point_crossover(self, AMOUNT_CROMOSOMA):\n amount_point_crossover, counter_cut, i = random.randint(1, 5), 0, 0\n\n list_point_crossover = []\n\n while i < amount_point_crossover:\n length_cut = random.randint(3, AMOUNT_CROMOSOMA-10)\n # print('Lenght_cut: {}'.format(length_cut))\n counter_cut = counter_cut + length_cut\n difference = AMOUNT_CROMOSOMA - counter_cut\n\n if(difference > 0 and i < amount_point_crossover):\n list_point_crossover.append(length_cut)\n else:\n i = amount_point_crossover\n \n i = i + 1\n\n # print('# cruzes: {}'.format(amount_point_crossover))\n # print('Cantidad de cruza: {}'.format(list_point_crossover))\n\n return list_point_crossover\n\n def mutacion(self, _lista_hijos_binarios, probabilidad_mutar_individuo, probabilidad_mutar_gen):\n lista_hijos_binarios, TAMANIO_LISTA_HIJOS, lista_hijos_binarios_mutados = np.copy(_lista_hijos_binarios), len(_lista_hijos_binarios), []\n\n for i in range(TAMANIO_LISTA_HIJOS):\n random_probabilidad_mutacion = random.random()\n if(probabilidad_mutar_individuo > random_probabilidad_mutacion):\n #print(\"Hm: {}\".format(lista_hijos_binarios[i]))\n list_individuo = list(map(lambda individuo: self.mutar_gen(individuo, probabilidad_mutar_gen), lista_hijos_binarios[i]))\n # print('LHC: {}'.format(list_individuo))\n list_individuo = ''.join(str(individuo) for individuo in list_individuo)\n list_individuo = list(map(int, list_individuo))\n lista_hijos_binarios_mutados.append(np.asarray(list_individuo))\n #print('LHC: {}'.format(lista_hijos_binarios_mutados))\n else:\n list_individuo = list(map(int, lista_hijos_binarios[i]))\n lista_hijos_binarios_mutados.append(np.asarray(list_individuo))\n\n #print(\"Mutados: {}\".format(lista_hijos_binarios_mutados))\n\n return lista_hijos_binarios_mutados\n \n def mutar_gen(self, individuo, probabilidad_mutar_gen):\n random_probabilidad = random.random()\n #print('Individuo:{}'.format(individuo))\n #print(\"PG:{}, RP:{}\".format(probabilidad_mutar_gen, random_probabilidad))\n individuo = int(individuo)\n if(probabilidad_mutar_gen > random_probabilidad):\n if individuo == 0:\n #print(\"Ahora es: 1\")\n return 1\n else: \n #print(\"Ahora es: 0\")\n return 0\n #print(\"Lo mismo: {}\".fomat(individuo))\n return individuo \n\n def mutation(self, least_value, indivuals):\n \n # print('\\n\\nIndivuals actuales')\n # print(indivuals)\n\n for i in range(len(least_value)):\n if(random.random() > 0.6):\n if(least_value[i] == 0):\n least_value[i] = 1\n else:\n least_value[i] = 0\n\n for i in range(len(indivuals)):\n for j in range(len(least_value)):\n if(random.random() > 0.5):\n if(indivuals[i][j] == 0):\n indivuals[i][j] = 1\n else:\n indivuals[i][j] = 0\n\n indivuals.append(least_value)\n\n return indivuals\n\n def print_indivuals(self, indivuals):\n length_indivuals = len(indivuals)\n for i in range(length_indivuals):\n binaries, fitness = indivuals[i]\n # print('P:{}, F: {}'.format(binaries, fitness))\n\n def draw_chart(self, list_fitness, amount_generation):\n amount_generation = len(list_fitness)\n list_generation = []\n\n for i in range(amount_generation):\n list_generation.append(i+1)\n\n value_min = min(list_fitness)\n value_max = max(list_fitness)\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n plt.title('Valor de la media')\n plt.xlabel('Generaciones')\n plt.ylabel('Fitness')\n ax.set_ylim(bottom=value_min, top=value_max)\n plt.plot(list_generation, list_fitness, 'go-')\n plt.legend(loc='upper left')\n plt.show()\n\n def draw_chart_all(self, list_media, list_media_mejor, list_media_peor, CANTIDAD_GENERACIONES):\n lista_generaciones = []\n\n #print('Cantidad:{}, CANTIDAD_MEDIA: {} '.format(CANTIDAD_GENERACIONES, CANTIDAD_MEDIA))\n\n for i in range(CANTIDAD_GENERACIONES):\n lista_generaciones.append(i+1)\n\n print('CG: {}'.format(lista_generaciones))\n\n #print('Min: {}'.format(min(list_media_mejor + list_media_peor + list_media)))\n #print('Max: {}'.format(max(list_media_mejor + list_media_peor + list_media)))\n\n valor_minimo = min(list_media_peor)\n valor_maximo = max(list_media_mejor)\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n plt.title('Valor de la media')\n plt.xlabel('Generaciones')\n plt.ylabel('Fitness')\n ax.set_ylim(bottom=valor_minimo, top=valor_maximo)\n plt.plot(lista_generaciones, list_media_peor, 'ro-', label='Peores individuos')\n plt.plot(lista_generaciones, list_media_mejor, 'go-', label='Mejores individuos')\n plt.plot(lista_generaciones, list_media,'bo-', label='Promedios individuos')\n plt.legend(loc='upper left')\n plt.show()\n\nif __name__ == '__main__':\n root = tk.Tk()\n app = Application(root)\n root.mainloop()","sub_path":"main_2.py","file_name":"main_2.py","file_ext":"py","file_size_in_byte":15019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"453642064","text":"from lviv_game import game, actions, balance\n\n\n# Room Creation, preparing the game environment\nbank = game.Location(name=\"UCU Bank\", action=actions.get_money)\nbank.set_action_weight(balance.weights[\"bank\"])\ncampus = game.Location(name=\"Kozelnytska Campus\")\nbfs = game.Location(name=\"Trapezna Building\", action=actions.eat)\nbfs.set_action_weight(balance.weights[\"bfs\"])\nchurch = game.Location(name=\"The Church\", action=actions.pray)\nchurch.set_action_weight(balance.weights[\"church\"])\ncenter = game.Location(name=\"Sheptytsky Center\", action=actions.study)\ncenter.set_action_weight(balance.weights[\"center\"])\nkolegium = game.Location(name=\"UCU Kolegium\")\n\n# Linking the rooms\ncampus.link_location({\"BFS Entrance\": bfs,\n \"Center Door\": center,\n \"Church Door\": church,\n \"Kolegium Door\": kolegium,\n \"Road to Bank\": bank})\ncenter.link_location({\"Underground Tunnel\": church})\n\n\n# Player Creation\nyou = game.Player(name=input(\"Enter your name: \"))\n\n\n# Starting parameters\nday = 0\ncurrent_location = campus\nprint(f'''\nWelcome to my dungeon-crawler RPG!!!\nIt is based in the setting of the Kozelnytska UCU campus.\n--------------------\nYou are a student studying computer science, and you are determined to become the best.\nBut it's not that easy. Quantum computing is your weakness, and just in {balance.DAYS} days\nyou are having the final exam on it. Can you do what it takes to pass the exam?\n--------------------\nType \"help\" or \"h\" to view possible commands.\n''')\n\n\n# Main game loop. Continues while you are alive.\nwhile you.energy > 0 and you.fitness > 0:\n print(f'Day {day}.')\n\n # Scary stuff. End goal of the game. Triggers when the\n if day == balance.DAYS:\n result = you.activate_session()\n if result:\n print(\"\\n\\n\\nVICTORY :D\")\n else:\n print(\"\\n\\n\\nDEFEAT :(\")\n break\n\n # Where are you right now?\n name = current_location.get_name()\n print(f'You are in {name}.')\n\n # Does this location have an associated action?\n action_name = None\n if current_location.action is not None:\n action_name = actions.get_function_name(current_location.action).replace(\"_\", \" \")\n print(f'In this location you can {action_name}. (type \"{action_name}\" to do so)')\n\n print('-' * 20)\n\n # Where can you go from here?\n gateways = current_location.linked_locations.keys()\n\n # Input a command.\n command = input(\"> \")\n\n # From here I describe different command options\n if command.lower() == \"character\" or command.lower() == \"c\":\n # View your character stats.\n you.get_stats()\n\n elif command.lower() == \"stats\" or command.lower() == \"s\":\n # Explain the meaning of the stats.\n you.explain_stats()\n\n elif command.lower() == \"help\" or command.lower() == \"h\":\n # List of possible commands.\n you.help()\n\n elif command.lower() == \"directions\" or command.lower() == \"d\":\n # View all directions you can go from here.\n for via, location in current_location.linked_locations.items():\n print(f'You can get to {location.get_name()} via {via}')\n\n elif command in gateways:\n # Can go anywhere if you're out of fitness.\n if you.fitness < balance.MOVE_COST:\n print('You are too tired to go somewhere else. Try to get some sleep.')\n # Else, move there.\n current_location = current_location.move(command)\n you.fitness -= balance.MOVE_COST\n\n elif action_name is not None and command == action_name:\n # If there's an action, do it.\n print(f'You decided to {action_name}.')\n current_location.do_action(you, current_location.action_weight)\n\n elif command == \"sleep\":\n # You sleep till the morning.\n day += 1\n\n if name == \"UCU Kolegium\":\n # Sleep is best in Kolegium, although that is not told to the player by default.\n print(\"You slept well in your dorm. You're full of energy!\")\n you.energy = 100\n elif name == \"Kozelnytska Campus\":\n # On the contrary, sleeping on the street is really bad for you.\n print(\"\"\"You were hardly able to fall asleep on the grass.\nBesides, your muscles are now sore. Fitness decreased.\"\"\")\n you.energy += 20\n you.fitness -= 20\n else:\n # Anywhere else is fine, but not great.\n print(\"\"\"You've had a good rest on a couch.\nNot as good as you could've had on your trusty bed though.\"\"\")\n you.energy += 50\n you.energy = min(you.energy, 100)\n\n elif command == \"quit\":\n # Quit the game.\n break\n\n else:\n # What did you even type?\n print(\"This command does not exist.\")\n\n print('\\n')\n\nelse:\n # If you exit out of the loop normally, it means your energy or fitness dropped to 0. You die.\n print(\"\"\"YOU DIED\"\"\")\n","sub_path":"lviv_game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"28601121","text":"import numpy as np\nfrom ase.build import bulk\nfrom ase import units\nfrom ase.md.velocitydistribution import MaxwellBoltzmannDistribution\nfrom ase.calculators.harmonic import SpringCalculator\nfrom ase.md.switch_langevin import SwitchLangevin\n\n\n# params\nsize = 6\nT = 300\nn_steps = 500\nk1 = 2.0\nk2 = 4.0\ndt = 10\n\n# for reproducibility\nnp.random.seed(42)\n\n# setup atoms and calculators\natoms = bulk('Al').repeat(size)\ncalc1 = SpringCalculator(atoms.positions, k1)\ncalc2 = SpringCalculator(atoms.positions, k2)\n\n# theoretical diff\nn_atoms = len(atoms)\ncalc1.atoms = atoms\ncalc2.atoms = atoms\nF1 = calc1.get_free_energy(T) / n_atoms\nF2 = calc2.get_free_energy(T) / n_atoms\ndF_theory = F2 - F1\n\n# switch_forward\ndyn_forward = SwitchLangevin(atoms, calc1, calc2, dt * units.fs, T * units.kB, 0.01, n_steps, n_steps)\nMaxwellBoltzmannDistribution(atoms, 2 * T * units.kB)\ndyn_forward.run()\ndF_forward = dyn_forward.get_free_energy_difference() / len(atoms)\n\n# switch_backwards\ndyn_backward = SwitchLangevin(atoms, calc2, calc1, dt * units.fs, T * units.kB, 0.01, n_steps, n_steps)\nMaxwellBoltzmannDistribution(atoms, 2 * T * units.kB)\ndyn_backward.run()\ndF_backward = -dyn_backward.get_free_energy_difference() / len(atoms)\n\n# summary\ndF_switch = (dF_forward + dF_backward) / 2.0\nerror = dF_switch - dF_theory\n\n# print('delta_F analytical: {:12.6f} eV/atom'.format(dF_theory))\n# print('delta_F forward: {:12.6f} eV/atom'.format(dF_forward))\n# print('delta_F backward: {:12.6f} eV/atom'.format(dF_backward))\n# print('delta_F average: {:12.6f} eV/atom'.format(dF_switch))\n# print('delta_F error: {:12.6f} eV/atom'.format(error))\nassert abs(error) < 1e-3\n","sub_path":"test/langevin_switching.py","file_name":"langevin_switching.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"116426967","text":"import sublime, sublime_plugin\nimport subprocess\nimport os\nimport re\n\ndef get_full_path_to_file(levels, file_found, path):\n path_strings = [s for s in file_found.split(\"/\") if s]\n dest_path = os.sep.join(path.split(os.sep)[:levels])\n return os.path.join(dest_path,*path_strings)\n\ndef get_levels(line_under_cursor):\n # if empty between parenthesis quicly set to 0, else let regex find it.\n levels = None\n if \"me.dir()\" in line_under_cursor:\n levels = 0\n else:\n try:\n dir_pattern = \"me.dir\\((.*?)\\)\"\n m = re.search(dir_pattern, line_under_cursor)\n levels = int(m.groups(0)[0])\n except:\n print(\"malformed me.dir(), remove spaces..\")\n\n return levels\n\ndef open_file(line_under_cursor, path, levels, file_type):\n \"\"\"\n accepts: me.dir() , me.dir(0), me.dir(-1) , me.dir(-n)\n \n opens a sound file if the following is on a line:\n me.dir(-1) + \"/audio/hihat_02.wav\";\n\n opens a .ck file if it finds\n Machine.add(me.dir() + \"/some_path.ck)\";\n \"\"\"\n\n try:\n pattern = \"\\\"(.*\" + file_type + \")\\\"?\"\n m = re.search(pattern, line_under_cursor)\n file_found = m.groups(0)[0]\n full_path = get_full_path_to_file(levels, file_found, path)\n\n except:\n print(\"failure! \", file_type)\n return\n\n finally:\n if file_type == \".ck\":\n window = sublime.active_window() \n window.open_file(full_path)\n\n # has to be a sound file\n else:\n settings = sublime.load_settings(\"ChucK.sublime-settings\")\n wave_editor = settings.get(\"wave_editor\")\n subprocess.call(\"{0} {1}\".format(wave_editor, full_path))\n\n\ndef check_file(line_under_cursor, path):\n \"\"\" figures out if the line contains a file in the expected notation.\"\"\"\n\n # does it have a path? if not, ditch return no ifs ands or buts\n levels = get_levels(line_under_cursor)\n if levels == None:\n print(\"please let us know in what context you get this error.\")\n return \n\n # is it a sound?\n file_types = [\".wav\", \".aiff\", \".mat\", \".ck\"] # extend if needed\n found_types = [(s in line_under_cursor) for s in file_types]\n\n # enters here if the filetype is recognized.\n if any(found_types):\n for i, file_type in enumerate(found_types):\n if file_type:\n open_file(line_under_cursor, path, levels, file_types[i])\n return\n\n\n\nclass ChuckOpener(sublime_plugin.TextCommand):\n def run(self, edit):\n view = self.view\n selections = view.sel()\n sel = view.line(selections[0])\n\n line_under_cursor = view.substr(sel)\n sublime.status_message(line_under_cursor)\n\n file_path = view.file_name()\n path = os.path.dirname(file_path)\n\n if not \"me.dir(\" in line_under_cursor:\n sublime.status_message(\"line must contain some form of me.dir()\")\n else:\n check_file(line_under_cursor, path)\n\n\n def enabled(self):\n view = self.view\n selections = view.sel()\n\n if selections[0].a == selections[0].b:\n return True \n \n","sub_path":"chuck_util_functions.py","file_name":"chuck_util_functions.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"287134103","text":"#@HEADER\n# ************************************************************************\n# \n# Torchbraid v. 0.1\n# \n# Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC \n# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. \n# Government retains certain rights in this software.\n# \n# Torchbraid is licensed under 3-clause BSD terms of use:\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# \n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# \n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# \n# 3. Neither the name National Technology & Engineering Solutions of Sandia, \n# LLC nor the names of the contributors may be used to endorse or promote \n# products derived from this software without specific prior written permission.\n# \n# Questions? Contact Eric C. Cyr (eccyr@sandia.gov)\n# \n# ************************************************************************\n#@HEADER\n\n# cython: profile=True\n# cython: linetrace=True\n\nimport torch\nimport traceback\nimport numpy as np\n\nfrom braid_vector import BraidVector\n\nimport torchbraid_app as parent\nimport utils\n\nimport sys\n\nfrom mpi4py import MPI\n\nclass ForwardBraidApp(parent.BraidApp):\n\n def __init__(self,comm,RNN_models,local_num_steps,hidden_size,num_layers,Tf,max_levels,max_iters,timer_manager,abs_tol):\n parent.BraidApp.__init__(self,'RNN',comm,local_num_steps,Tf,max_levels,max_iters,spatial_ref_pair=None,require_storage=True,abs_tol=abs_tol)\n\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n\n self.RNN_models = RNN_models\n\n comm = self.getMPIComm()\n my_rank = self.getMPIComm().Get_rank()\n num_ranks = self.getMPIComm().Get_size()\n\n # build up the core\n self.py_core = self.initCore()\n\n # force evaluation of gradients at end of up-cycle\n self.finalRelax()\n\n self.timer_manager = timer_manager\n self.use_deriv = False\n\n self.user_dt_ratio = self._dt_ratio_\n\n self.seq_shapes = None\n self.backpropped = dict()\n # end __init__\n\n def _dt_ratio_(self,level,tstart,tstop,fine_dt): \n return np.sqrt(np.sqrt((tstop-tstart)/fine_dt))\n\n def setDtRatio(self,user_dt_ratio):\n self.user_dt_ratio = user_dt_ratio\n\n def dt_ratio(self,level,tstart,tstop):\n return self.user_dt_ratio(level,tstart,tstop,self.dt)\n # end dt_ratio\n\n def getTensorShapes(self):\n return list(self.shape0)+self.seq_shapes\n\n def getSequenceVector(self,t,tf,level):\n index = self.getLocalTimeStepIndex(t,tf,level)\n if index<0: \n pre_str = \"\\n{}: WARNING: getSequenceVector index negative at {}: {}\\n\".format(self.my_rank,t,index)\n stack_str = utils.stack_string('{}: |- '.format(self.my_rank))\n print(pre_str+stack_str)\n \n if index0:\n send_request = comm.Isend(np.ascontiguousarray(self.x[:,0,:].numpy()),dest=my_rank-1,tag=22)\n\n if recv_request:\n recv_request.Wait()\n self.x = torch.cat((self.x,neighbor_x.unsqueeze(1)), 1)\n\n if send_request:\n send_request.Wait()\n # end wit htimer\n\n # run the braid solver\n y = self.runBraid(h_c)\n\n with self.timer(\"run:postcomm\"):\n y = comm.bcast(y,root=num_ranks-1)\n\n # y is a tuple with the final h,c components\n return y\n # end forward\n\n def timer(self,name):\n return self.timer_manager.timer(\"ForWD::\"+name)\n\n def eval(self,g0,tstart,tstop,level,done):\n \"\"\"\n Method called by \"my_step\" in braid. This is\n required to propagate from tstart to tstop, with the initial\n condition x. The level is defined by braid\n \"\"\"\n\n with self.timer(\"eval\"):\n # there are two paths by which eval is called:\n # 1. x is a BraidVector: my step has called this method\n # 2. x is a torch tensor: called internally (probably at the behest\n # of the adjoint)\n \n seq_x = g0.weightTensors()[0]\n \n t_h,t_c = g0.tensors()\n if not done:\n with torch.no_grad():\n t_yh,t_yc = self.RNN_models(seq_x,t_h,t_c)\n \n if level!=0:\n dt_ratio = self.dt_ratio(level,tstart,tstop)\n \n t_yh = (1.0-dt_ratio)*t_h + dt_ratio*t_yh\n t_yc = (1.0-dt_ratio)*t_c + dt_ratio*t_yc\n else:\n with torch.enable_grad():\n h = t_h.detach()\n c = t_c.detach()\n h.requires_grad = True\n c.requires_grad = True\n t_yh,t_yc = self.RNN_models(seq_x,h,c)\n \n if level!=0:\n dt_ratio = self.dt_ratio(level,tstart,tstop)\n \n t_yh = (1.0-dt_ratio)*h + dt_ratio*t_yh\n t_yc = (1.0-dt_ratio)*c + dt_ratio*t_yc\n self.backpropped[tstart,tstop] = ((h,c),(t_yh,t_yc))\n \n seq_x = self.getSequenceVector(tstop,None,level)\n \n g0.addWeightTensors((seq_x,))\n g0.replaceTensor(t_yh,0)\n g0.replaceTensor(t_yc,1)\n # end eval\n\n def getPrimalWithGrad(self,tstart,tstop,level):\n \"\"\" \n Get the forward solution associated with this\n time step and also get its derivative. This is\n used by the BackwardApp in computation of the\n adjoint (backprop) state and parameter derivatives.\n Its intent is to abstract the forward solution\n so it can be stored internally instead of\n being recomputed.\n \"\"\"\n \n if level==0 and (tstart,tstop) in self.backpropped:\n with self.timer(\"getPrimalWithGrad-short\"):\n x,y = self.backpropped[(tstart,tstop)]\n return y,x\n\n with self.timer(\"getPrimalWithGrad-long\"):\n b_x = self.getUVector(0,tstart)\n t_x = b_x.tensors()\n \n x = tuple([v.detach() for v in t_x])\n \n xh,xc = x \n xh.requires_grad = True\n xc.requires_grad = True\n \n seq_x = b_x.weightTensors()[0]\n \n with torch.enable_grad():\n yh,yc = self.RNN_models(seq_x,xh,xc)\n \n if level!=0:\n dt_ratio = self.dt_ratio(level,tstart,tstop)\n \n yh = (1.0-dt_ratio)*xh + dt_ratio*yh\n yc = (1.0-dt_ratio)*xc + dt_ratio*yc\n \n return (yh,yc), x\n # end getPrimalWithGrad\n\n# end ForwardBraidApp\n\n##############################################################\n\nclass BackwardBraidApp(parent.BraidApp):\n\n def __init__(self,fwd_app,timer_manager,abs_tol):\n # call parent constructor\n parent.BraidApp.__init__(self,'RNN',fwd_app.getMPIComm(),\n fwd_app.local_num_steps,\n fwd_app.Tf,\n fwd_app.max_levels,\n fwd_app.max_iters,spatial_ref_pair=None,require_storage=True,abs_tol=abs_tol)\n\n self.fwd_app = fwd_app\n\n # build up the core\n self.py_core = self.initCore()\n\n # reverse ordering for adjoint/backprop\n self.setRevertedRanks(1)\n\n # force evaluation of gradients at end of up-cycle\n self.finalRelax()\n\n self.timer_manager = timer_manager\n # end __init__\n\n def __del__(self):\n self.fwd_app = None\n\n def getTensorShapes(self):\n return self.shape0\n\n def timer(self,name):\n return self.timer_manager.timer(\"BckWD::\"+name)\n\n def run(self,x):\n\n try:\n self.RNN_models = self.fwd_app.RNN_models\n\n f = self.runBraid(x)\n\n self.grads = [p.grad.detach().clone() for p in self.RNN_models.parameters()]\n\n # required otherwise we will re-add the gradients\n self.RNN_models.zero_grad() \n\n self.RNN_models = None\n except:\n print('\\n**** Torchbraid Internal Exception ****\\n')\n traceback.print_exc()\n\n return f\n # end forward\n\n def eval(self,w,tstart,tstop,level,done):\n \"\"\"\n Evaluate the adjoint problem for a single time step. Here 'w' is the\n adjoint solution. The variables 'x' and 'y' refer to the forward\n problem solutions at the beginning (x) and end (y) of the type step.\n \"\"\"\n with self.timer(\"eval\"):\n try:\n # we need to adjust the time step values to reverse with the adjoint\n # this is so that the renumbering used by the backward problem is properly adjusted\n t_y,t_x = self.fwd_app.getPrimalWithGrad(self.Tf-tstop,self.Tf-tstart,level)\n\n # play with the parameter gradients to make sure they are on apprpriately,\n # store the initial state so we can revert them later\n required_grad_state = []\n if done!=1:\n for p in self.RNN_models.parameters(): \n required_grad_state += [p.requires_grad]\n p.requires_grad = False\n\n # perform adjoint computation\n t_w = w.tensors()\n s_w = torch.stack(t_w)\n with torch.enable_grad():\n s_y = torch.stack(t_y)\n s_w.requires_grad = False\n s_y.backward(s_w,retain_graph=True)\n\n # this little bit of pytorch magic ensures the gradient isn't\n # stored too long in this calculation (in particulcar setting\n # the grad to None after saving it and returning it to braid)\n for wv,xv in zip(t_w,t_x):\n wv.copy_(xv.grad.detach()) \n xv.grad = None\n\n # revert the gradient state to where they started\n if done!=1:\n for p,s in zip(self.RNN_models.parameters(),required_grad_state):\n p.requires_grad = s\n except:\n print('\\n**** Torchbraid Internal Exception ****\\n')\n traceback.print_exc()\n # end eval\n\n# end BackwardODENetApp\n","sub_path":"torchbraid/rnn_apps.py","file_name":"rnn_apps.py","file_ext":"py","file_size_in_byte":10746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"426916947","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nZetCode PyQt5 tutorial\n\nIn this example, we determine the event sender\nobject.\n\nAuthor: Jan Bodnar\nWebsite: zetcode.com\nLast edited: August 2017\n\"\"\"\n\nimport sys\nfrom PyQt5.QtWidgets import QMainWindow\nfrom PyQt5.QtWidgets import QApplication, QDialog, QToolTip, QPushButton, QWidget, QInputDialog, QLineEdit, QFileDialog\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtGui import QFont\nfrom PyQt5 import QtCore\nimport xlrd\nimport xlwt\n\nclass Example(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.initUI()\n\n\n def initUI(self):\n\n btn1 = QPushButton(\"Button 1\", self)\n btn1.move(30, 50)\n\n btn2 = QPushButton(\"Button 2\", self)\n btn2.move(150, 50)\n\n btn1.clicked.connect(self.buttonClicked)\n btn2.clicked.connect(self.buttonClicked)\n\n self.statusBar()\n\n self.setGeometry(300, 300, 290, 150)\n self.setWindowTitle('Event sender')\n self.show()\n\n\n #def buttonClicked(self):\n # sender = self.sender()\n # self.statusBar().showMessage(sender.text() + ' was pressed')\n\n def buttonClicked(self):\n sender = self.sender()\n options = QFileDialog.Options()\n options |= QFileDialog.DontUseNativeDialog\n #fil = QFileDialog.setNameFilter(\"Excel Sheets (*.csv *.xml *.xlsx);;Images (*.png *.jpg *.jpeg);; Python Files (*.py)\")\n #print(\"options = %s\" %(options))\n print(\"I am inside openFileNameDialog\")\n fileName, NameFilter = QFileDialog.getOpenFileName(self,\"Open the File\", \"\",\"All Files (*);;Python Files (*.py)\", options=options)\n #print(\"filename = %s\" %fileName)\n if fileName:\n print(\"I Will Baby. I Will. %s\" %fileName)\n\n\nif __name__ == '__main__':\n\n app = QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())\n","sub_path":"GUI_dev/eventsource.py","file_name":"eventsource.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"484066776","text":"import helper as hlp\nfrom collections import defaultdict\nimport heapq as h\n\nclass AStar:\n\n def __init__(self):\n self._animate_visited = []\n\n def solve(self, grid, start, goal):\n visited = set()\n prev = dict()\n dist = defaultdict(lambda : float('inf'))\n pq = []\n\n prev[start] = None\n dist[start] = 0\n\n # Need to put (cost, pos) into priority queue so that pq is ordered by cost\n h.heappush(pq, (0, start))\n\n while len(pq) != 0:\n\n current_cost, current_pos = h.heappop(pq)\n\n self._animate_visited.append(current_pos)\n\n # Check we havent visited this point before\n if current_pos not in visited:\n visited.add(current_pos)\n else:\n continue\n \n # If we have reached the end get the path\n if current_pos == goal:\n return self.get_path(prev, goal)\n\n # print(pq)\n\n for nbr in hlp.nhood8(grid, *current_pos):\n new_cost = dist[current_pos] + hlp.distance(current_pos, nbr)\n heuristic = hlp.distance(nbr, goal)\n\n # If we havent visited\n if nbr not in visited:\n\n if new_cost < dist[nbr]:\n dist[nbr] = new_cost\n prev[nbr] = current_pos\n\n h.heappush(pq, (dist[nbr] + heuristic, nbr))\n\n def get_path(self, prev, goal):\n \n self.path = []\n\n current_pos = goal\n \n # Extract path from goal to start (start is the only item that has none associated with it in prev)\n while prev[current_pos] != None:\n current_pos = prev[current_pos]\n self.path.append(current_pos)\n\n # Return path reveresed and remove start node\n return self.path[:-1:-1]\n\n def animate(self, grid, cells_at_once=50):\n\n # Remove start and end points\n grid.animate(self._animate_visited[1:-1], self.path, cells_at_once)\n\n\n \n\n\n","sub_path":"astar.py","file_name":"astar.py","file_ext":"py","file_size_in_byte":2065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"433462509","text":"from model import Entity\n\n'''Contains bigger entities models, like - Movie, TV Show, Game, Music Album'''\n\nclass Album(Entity):\n\n\tdef __init__(self):\n\t\tsuper(Album, self).__init__(self)\n\t\t\n\t\tself.artist = None\n\t\tself.record_label = None\n\n\tdef build_response(self):\n\t\tsuper(Album, self).build_response()\n\t\tself.response['artist'] = self.artist\n\t\tself.response['record_label'] = self.record_label\n\nclass Game(Entity):\n\n\tdef __init__(self):\n\t\tsuper(Game, self).__init__(self)\n\t\t\n\t\tself.platforms = []\n\t\tself.platform = None\n\t\tself.publisher = None\n\t\tself.developer = None\n\n\tdef build_response(self):\n\t\tsuper(Game, self).build_response()\n\t\tself.response['platforms'] = self.platforms\n\t\tself.response['platform'] = self.platform\n\t\tself.response['publisher'] = self.publisher\n\t\tself.response['developer'] = self.developer\n\nclass Movie(Entity):\n\n\tdef __init__(self):\n\t\tsuper(Movie, self).__init__(self)\n\t\t\n\t\tself.runtime = None\n\t\tself.director = None\n\t\tself.cast = None\n\n\tdef build_response(self):\n\t\tsuper(Movie, self).build_response()\n\t\tself.response['runtime'] = self.runtime\n\t\tself.response['director'] = self.director\n\t\tself.response['cast'] = self.cast\n\nclass Show(Entity):\n\n\tdef __init__(self):\n\t\tsuper(Show, self).__init__(self)\n\t\t\n\t\tself.series_name = None\n\t\tself.series_premiere = None\n\t\tself.creator = None\n\t\tself.seasons = []\n\t\tself.air_time = None\n\t\tself.episode_length = None\n\t\tself.cast = None\n\n\tdef build_response(self):\n\t\tsuper(Show, self).build_response()\n\t\tself.response['series_name'] = self.series_name\n\t\tself.response['series_premiere'] = self.series_premiere\n\t\tself.response['creator'] = self.creator\n\t\tself.response['seasons'] = self.seasons\n\t\tself.response['air_time'] = self.air_time\n\t\tself.response['episode_length'] = self.episode_length\n\t\tself.response['cast'] = self.cast","sub_path":"models/entities.py","file_name":"entities.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"269068398","text":"import torch\nprint (torch.cuda.is_available())\nimport torch.nn as nn\nimport torchvision.datasets as dsets\nimport torchvision.models as models\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot as plt\nfrom matplotlib import gridspec as gridspec\nimport numpy as np\n\nfrom data_loader2 import iCIFAR10\nfrom data_loader2 import iCIFAR100\n#from model import iCaRLNet\nfrom iCaRL import iCaRLNet\nimport math\nimport save_load\nimport plots\nimport metrica\nimport random\n\nprint (torch.cuda.is_available())\npath = '/home/usuaris/imatge/alex.mateo/Downloads/icarl/saved_models/best_model4'\n\n# Híper paràmetres\ntotal_classes = 100 #Número total de classes de la base de dades\nnum_classes = 5 #Número de classes per tasca\nnum_epochs = 60 #Número de epochs per realitzar l'entrenament\n\n# Inicializació dels seeds\ntorch.manual_seed(0)\nnp.random.seed(0)\nrandom.seed(0)\n\n# Data augmentation sobre les dades d'entrada. Realitza un retallat, rotació i normalització\ntransform = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\ntransform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\n\n# Inicialització de la CNN\nk = 500*num_classes #2000 #Espai de memòria en número d'exemples\n#k = 10000\nicarl = iCaRLNet(2048, 1, num_epochs) #Creació del model, ResNet amb una sortida de 2048 neurones, capa de sortida separada de tamany 1 inicialment\nicarl.cuda()\n\n# Per la contabilització del nombre total de paràmetres\n#pytorch_total_params = sum(p.numel() for p in icarl.parameters())\n#print (pytorch_total_params)\n\n# Llistes per l'emmagatzematge de les precisions noves, antigues i totals en avaluació i precisió\ntr_accs_old = []\ntr_accs_new = []\nte_accs_old = []\nte_accs_new = []\ntr_accs_total = []\nte_accs_total = []\n\nmem_old = [] #Número de mostres per classe en la tasca anterior \n\n\niterable_list = np.arange(0,total_classes, num_classes) #Lista amb les tasques a iterar\n\n# Matrius per l'emmagatzematge de les precisions \nmatrix_accuracies = torch.zeros(len(iterable_list), len(iterable_list))\nmatrix_accuracies_train = torch.zeros(len(iterable_list), len(iterable_list))\n\n#Llista amb les pèrdues totals en entrenament i avaluació\nloss_total = np.zeros(shape = (len(iterable_list), num_epochs))\nloss_distilation = np.zeros(shape = (len(iterable_list), num_epochs))\nloss_classification = np.zeros(shape = (len(iterable_list), num_epochs))\nloss_total_eval = np.zeros(shape = (len(iterable_list), num_epochs))\nloss_distilation_eval = np.zeros(shape = (len(iterable_list), num_epochs))\nloss_classification_eval = np.zeros(shape = (len(iterable_list), num_epochs))\n\ncount = 0\n\nfor s in range(0, total_classes, num_classes): #Iterador del número de tasques\n print (\"number of s: %d\" %(s))\n print (\"Loading training examples for classes\", range(s,s+num_classes))\n \n #Depenent del transform triat, s'aplica o no data augmentation \n train_set = iCIFAR10(root='./data',\n train=True,\n classes=range(s,(s+num_classes)) if s != (total_classes-1) else s,\n download=True,\n transform=transform)\n train_loader = torch.utils.data.DataLoader(train_set, batch_size=100,\n shuffle=True, num_workers=1)\n \n \n test_set = iCIFAR10(root='./data',\n train=False,\n classes=range(0,(s+num_classes)) if s != (total_classes-1) else s,\n download=True,\n transform=transform_test)\n test_loader = torch.utils.data.DataLoader(test_set, batch_size=100,\n shuffle=True, num_workers=1) #Normalmente batch size en 100, evitamos problemas con cuda out of memory\n\n\n # Entrenament mitjançant back propagation\n loss_total[count], loss_classification[count], loss_distilation[count],loss_total_eval[count], loss_classification_eval[count], loss_distilation_eval[count] = icarl.update_representation(train_set, test_set)\n \n \n ##############Diferents opcions de la distribució de memòria entre classes################### \n \"\"\"\n #OPCIÓN 1\n m = math.floor(k / icarl.n_classes)\n res = (2500-m*icarl.n_classes)/5\n tot = int(m+res)\n \"\"\"\n \n \"\"\"\n #OPCIÓN 2\n \n m = math.floor(k / icarl.n_classes)\n #mem_list = np.flip(np.arange(0.5, 1.5, 1/icarl.n_classes))\n mem_list = np.arange(0.5, 1.5, 1/icarl.n_classes)\n mem_list = [int(mem_list[i]*m) for i in range(len(mem_list))]\n res = (2500-sum(mem_list))/5\n new_classes = [icarl.n_classes -5, icarl.n_classes -4, icarl.n_classes -3, icarl.n_classes -2, icarl.n_classes -1]\n for i in new_classes:\n mem_list[i] = int(mem_list[i] + res)\n res2 = (2500-sum(mem_list))\n mem_list[icarl.n_classes-1] += res2\n \"\"\"\n \n #OPCIÓN 3 TAMBIÉN CONTINUA MÁS ABAJO\n if (s>0):\n m = math.floor(k / icarl.n_classes)\n print (matrix_accuracies[:class_group, count-1])\n if (s==5):\n acc_list = np.argsort(matrix_accuracies[:class_group, count-1])\n else:\n #acc_list = np.flip(np.argsort(matrix_accuracies[:class_group, count-1].cpu().detach().numpy()))#A mayor probabilidad mas muestras\n acc_list = np.argsort(matrix_accuracies[:class_group, count-1].cpu().detach().numpy()) #A menor probabilidad mas muestras\n mem_list = np.flip(np.arange(0.5, 1.5, 5/icarl.n_known)) #Solo las clases antiguas\n mem_list_aux=np.zeros(mem_list.shape)\n for i,index in enumerate(acc_list):\n if((mem_old[index]) < (int(mem_list[i]*m))):\n mem_list_aux[index] = mem_old[index]\n else:\n mem_list_aux[index] = int(mem_list[i]*m)\n mem_old = []\n for i in mem_list_aux:\n mem_old.append(i)\n aux = 0\n mem_list2 = np.zeros(icarl.n_classes)\n for i in range(s):\n if (i%5 == 0 and i>0):\n aux+=1\n mem_list2[i] = int(mem_list_aux[aux])\n res = (2500-sum(mem_list2))/5\n new_classes = [icarl.n_classes-5, icarl.n_classes-4, icarl.n_classes-3, icarl.n_classes-2, icarl.n_classes-1]\n for i in new_classes:\n mem_list2[i] = int(mem_list2[i]+res)\n mem_old.append(mem_list2[icarl.n_classes-1])\n \n \n else:\n m = math.floor(k / icarl.n_classes)\n res = (2500-m*icarl.n_classes)/5\n tot = int(m+res)\n mem_list2 = np.zeros(icarl.n_classes)\n new_classes = [icarl.n_classes-5, icarl.n_classes-4, icarl.n_classes-3, icarl.n_classes-2, icarl.n_classes-1]\n for i in new_classes:\n mem_list2[i] = tot\n mem_old.append(tot)\n \n \n \n # Reducció de les dades de memòria per les classes ja conegudes\n #icarl.reduce_exemplar_sets(m)\n icarl.reduce_exemplar_sets(mem_list2)\n \n icarl.compute_mean(transform_test, True)\n\n # Construct exemplar sets for new classes\n for y in range(s, s+num_classes):\n print (\"Constructing exemplar set for class-%d...\" %(y))\n images = train_set.get_image_class(y) #Conjunt de mostres d'entrenament d'aquella classe\n \n #icarl.construct_exemplar_set(images, tot, transform_test, y) #Selecció de les més representatives per emmagatzemar-les\n icarl.construct_exemplar_set(images, mem_list2[y], transform_test, y)\n print (\"Done\")\n\n for y, P_y in enumerate(icarl.exemplar_sets):\n print (\"Exemplar set for class-%d:\" % (y), P_y.shape)\n\n icarl.n_known = icarl.n_classes\n print (\"iCaRL classes: %d\" % icarl.n_known)\n \n icarl = save_load.load_model(icarl, path) \n \n \"\"\"\n #####MEDICIÓ DEL NÚMERO DE PARÀMETReS########\n pytorch_total_params = sum(p.numel() for p in icarl.parameters())\n print(\"##################\")\n print(\"Total parameters in the model\")\n print (pytorch_total_params)\n print(\"##################\")\n \"\"\"\n #Mètrica\n print (\"Computing metrica....\") \n \n seen_classes = s+num_classes\n class_group = 0\n for i in range(0, seen_classes, num_classes):\n test_set = iCIFAR10(root='./data',\n train=False,\n classes=range(i,(i+num_classes)) if i != (total_classes-1) else i,\n download=True,\n transform=transform_test)\n test_loader = torch.utils.data.DataLoader(test_set, batch_size=100, shuffle=False, num_workers=1)\n matrix_accuracies[class_group,count] = metrica.test_accuracy(test_loader, icarl, transform_test)\n class_group += 1\n \n class_group = 0\n for i in range(0, seen_classes, num_classes):\n train_set = iCIFAR10(root='./data',\n train=True,\n classes=range(i,(i+num_classes)) if i != (total_classes-1) else i,\n download=True,\n transform=transform_test)\n train_loader = torch.utils.data.DataLoader(train_set, batch_size=100,\n shuffle=False, num_workers=1)\n matrix_accuracies_train[class_group,count] = metrica.train_accuracy(train_loader, icarl, transform_test)\n class_group += 1\n \n \n acc_list = matrix_accuracies[:class_group, count].cpu().detach().numpy()\n \n \n print (\"\\n ##########Train metrics###########\")\n tr_accs_new.append(matrix_accuracies_train[count, count])\n if (count > 0):\n tr_accs_old.append((sum(matrix_accuracies_train[:count,count]))/count)\n print('Old classes Accuracy: %f %%' % tr_accs_old[count-1])\n tr_accs_total.append(sum(matrix_accuracies_train[:,count])/(count + 1))\n \n \n print('New classes Accuracy: %f %%' % tr_accs_new[count])\n print('Train total Accuracy: %f %%' % tr_accs_total[count])\n \n \n print (\"\\n ###########Test metrics###########\")\n te_accs_new.append(matrix_accuracies[count, count])\n if (count > 0):\n te_accs_old.append((sum(matrix_accuracies[:count,count]))/count)\n print('Old classes Accuracy: %f %%' % te_accs_old[count-1])\n te_accs_total.append(sum(matrix_accuracies[:,count])/(count + 1))\n \n print('New classes Accuracy: %f %%' % te_accs_new[count])\n print('Test total Accuracy: %f %% \\n' % te_accs_total[count])\n \n count += 1 \n \n\nprint (\"\\n ##########Accuracies matrix train##########\")\nprint (matrix_accuracies_train)\n\nprint (\"\\n ##########Accuracies matrix test##############\")\nprint (matrix_accuracies)\n\n\nif (type(train_set) is iCIFAR10):\n fname = 'iCIFAR10pretrained' + str(num_classes) + str(0)\n fname_loss = 'iCIFAR10pretrained_loss' + str(num_classes) + str(0)\n\naux = True\nif (len(te_accs_old) == 0):\n aux = False\n\nplots.save_graphic_evaluation (iterable_list, te_accs_new, te_accs_old, te_accs_total, fname, aux, True)\nplots.save_graphic_evaluation (iterable_list, tr_accs_new, tr_accs_old, tr_accs_total, fname, aux, False)\nplots.save_loss (iterable_list, num_epochs, loss_total, loss_classification, loss_distilation, fname_loss, True)\nplots.save_loss (iterable_list, num_epochs, loss_total_eval, loss_classification_eval, loss_distilation_eval, fname_loss, False)\nplots.save_matrix(matrix_accuracies, fname)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"138495460","text":"\"\"\"\nAdd couple selenium tests\n1. Submit filled test form \nhttps://demoqa.com/text-box\n2. Click on [Code in it] button after selecting new Category \nhttps://testpages.herokuapp.com/styled/basic-ajax-test.html\n3. Print all text in Lorem/Ipsum/Dolor columns \nhttps://the-internet.herokuapp.com/challenging_dom#delete\n\"\"\"\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\n\nTEST_DATA = {\n 'Full Name': 'Alexey Kurbetyev',\n 'Email': 'alextestemail@gmail.com',\n 'Current Adress': 'Kharkiv'\n}\nurl1 = 'https://demoqa.com/text-box'\nurl2 = 'https://testpages.herokuapp.com/styled/basic-ajax-test.html'\nurl3 = 'https://the-internet.herokuapp.com/challenging_dom#delete'\n\ndriver = webdriver.Chrome()\ndriver.get(url1)\ntime.sleep(2)\ndriver.find_element(By.CSS_SELECTOR, \"#userName\").send_keys(TEST_DATA['Full Name'])\ndriver.find_element(By.CSS_SELECTOR, \"#userEmail\").send_keys(TEST_DATA['Email'])\ndriver.find_element(By.CSS_SELECTOR, \"#currentAddress\").send_keys(TEST_DATA['Current Adress'])\ndriver.find_element(By.CSS_SELECTOR, \"#permanentAddress\").send_keys(TEST_DATA['Current Adress'])\ndriver.find_element(By.CSS_SELECTOR, \"#submit\").click()\ndriver.quit()\ntime.sleep(4)\n\ndriver = webdriver.Chrome()\ndriver.get(url2)\ntime.sleep(2)\ndriver.find_element(By.CSS_SELECTOR, \"#combo1\").click()\ndriver.find_element(By.CSS_SELECTOR, \"#combo1 > option:nth-child(2)\").click()\ndriver.find_element(By.CSS_SELECTOR, \".styled-click-button\").click()\nassert 'Processed Form Details' in driver.page_source\ndriver.quit()\ntime.sleep(4)\n\ndriver = webdriver.Chrome()\ndriver.get(url3)\ntable = driver.find_elements(By.CSS_SELECTOR,'tbody tr')\nfor rows in table:\n print(rows.find_element(By.CSS_SELECTOR,'td:nth-child(1)').text)\n\nfor rows in table:\n print(rows.find_element(By.CSS_SELECTOR,'td:nth-child(2)').text)\n\nfor rows in table:\n print(rows.find_element(By.CSS_SELECTOR,'td:nth-child(3)').text)\ndriver.quit()\n\n","sub_path":"selenium_selectors.py","file_name":"selenium_selectors.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"123691182","text":"from typing import Optional, List, Dict, Any, Type\n\nfrom rdflib import Namespace, Graph, RDF, Literal, URIRef\n\nfrom altimeter.core.graph.link.base import Link\nfrom altimeter.core.graph.link.links import link_from_dict\nfrom altimeter.core.graph.node_cache import NodeCache\n\n\nclass Resource:\n \"\"\"A Resource defines a single scanned resource which is directly translatable to a graph\n node. It contains an id, type name and list of Links.\n\n Args:\n resource_id: id of this resource\n type_name: type name of this resource\n links: List of Links for this resource\n \"\"\"\n\n def __init__(self, resource_id: str, type_name: str, links: Optional[List[Link]] = None):\n self.resource_id = resource_id\n self.type_name = type_name\n self.links = [] if links is None else links\n\n def to_dict(self) -> Dict[str, Any]:\n \"\"\"Generate a dict representation of this Resource.\n\n Returns:\n dict representation of this Resource\n \"\"\"\n scan_json: Dict[str, Any] = {\"type\": self.type_name}\n if self.links:\n scan_json[\"links\"] = [link.to_dict() for link in self.links]\n return scan_json\n\n @classmethod\n def from_dict(\n cls: Type[\"Resource\"], resource_id: str, resource_data: Dict[str, Any]\n ) -> \"Resource\":\n \"\"\"Create an instances of this class from a resource_id and resource_data dict\n as generated by to_dict.\n\n Args:\n resource_id: resource id\n resource_data: dict of data for this resource\n\n Returns:\n Resource object\n \"\"\"\n type_name = resource_data[\"type\"]\n links: List[Link] = []\n for link in resource_data.get(\"links\", []):\n links.append(link_from_dict(link))\n return cls(resource_id=resource_id, type_name=type_name, links=links)\n\n def to_rdf(self, namespace: Namespace, graph: Graph, node_cache: NodeCache) -> None:\n \"\"\"Graph this Resource as a URIRef on a Graph.\n\n Args:\n namespace: RDF namespace to use for predicates and objects when graphing\n this resource's links\n graph: RDF graph\n node_cache: NodeCache to use for any cached URIRef lookups\n \"\"\"\n node = node_cache.setdefault(self.resource_id, URIRef(self.resource_id))\n graph.add((node, RDF.type, getattr(namespace, self.type_name)))\n graph.add((node, getattr(namespace, \"id\"), Literal(self.resource_id)))\n for link in self.links:\n link.to_rdf(subj=node, namespace=namespace, graph=graph, node_cache=node_cache)\n\n def to_lpg(self, vertices: List[Dict], edges: List[Dict]) -> None:\n \"\"\"Graph this Resource as a dictionary into the vertices and edges lists.\n\n Args:\n vertices: List containing dictionaries representing a vertex\n edges: List containing dictionaries representing an edge\n \"\"\"\n vertex = {\n \"~id\": self.resource_id,\n \"~label\": self.type_name,\n \"arn\": self.resource_id,\n }\n for link in self.links:\n link.to_lpg(vertex, vertices, edges, \"\")\n\n vertices.append(vertex)\n","sub_path":"altimeter/core/resource/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"300907481","text":"#!/usr/bin/env python\nfrom __future__ import (absolute_import, division, print_function)\n\nfrom unittest import TestCase\nfrom copy import deepcopy \n\nfrom collections import Counter\nfrom copy import deepcopy \n\nimport numpy as np \n\nfrom astropy.tests.helper import pytest\nfrom astropy.table import Table \n\nfrom ..value_added_halo_table_functions import *\n\nfrom ...sim_manager import FakeSim\n\nfrom ...custom_exceptions import HalotoolsError\n\n__all__ = ['TestValueAddedHaloTableFunctions']\n\nclass TestValueAddedHaloTableFunctions(TestCase):\n \"\"\" Class providing tests of the `~halotools.utils.value_added_halo_table_functions`. \n \"\"\"\n def setUp(self):\n fake_sim = FakeSim()\n self.table= fake_sim.halo_table\n\n def test_broadcast_host_halo_mass1(self):\n \"\"\"\n \"\"\"\n t = deepcopy(self.table)\n broadcast_host_halo_property(t, 'halo_mvir')\n\n assert 'halo_mvir_host_halo' in t.keys()\n\n hostmask = t['halo_hostid'] == t['halo_id']\n assert np.all(t['halo_mvir_host_halo'][hostmask] == t['halo_mvir'][hostmask])\n assert np.any(t['halo_mvir_host_halo'][~hostmask] != t['halo_mvir'][~hostmask])\n\n data = Counter(t['halo_hostid'])\n frequency_analysis = data.most_common()\n\n for igroup in xrange(0, 10):\n idx = np.where(t['halo_hostid'] == frequency_analysis[igroup][0])[0]\n idx_host = np.where(t['halo_id'] == frequency_analysis[igroup][0])[0]\n assert np.all(t['halo_mvir_host_halo'][idx] == t['halo_mvir'][idx_host])\n\n for igroup in xrange(-10, -1):\n idx = np.where(t['halo_hostid'] == frequency_analysis[igroup][0])[0]\n idx_host = np.where(t['halo_id'] == frequency_analysis[igroup][0])[0]\n assert np.all(t['halo_mvir_host_halo'][idx] == t['halo_mvir'][idx_host])\n\n del t\n\n def test_broadcast_host_halo_mass2(self):\n \"\"\"\n \"\"\"\n t = deepcopy(self.table)\n with pytest.raises(HalotoolsError) as err:\n broadcast_host_halo_property(4, 'xxx')\n substr = \"The input ``table`` must be an Astropy `~astropy.table.Table` object\"\n assert substr in err.value.message\n\n del t\n\n def test_broadcast_host_halo_mass3(self):\n \"\"\"\n \"\"\"\n t = deepcopy(self.table)\n with pytest.raises(HalotoolsError) as err:\n broadcast_host_halo_property(t, 'xxx')\n substr = \"The input table does not the input ``halo_property_key``\"\n assert substr in err.value.message\n\n del t\n\n def test_broadcast_host_halo_mass4(self):\n \"\"\"\n \"\"\"\n t = deepcopy(self.table)\n broadcast_host_halo_property(t, 'halo_mvir')\n\n with pytest.raises(HalotoolsError) as err:\n broadcast_host_halo_property(t, 'halo_mvir')\n substr = \"Your input table already has an existing new_colname column name.\"\n assert substr in err.value.message\n\n broadcast_host_halo_property(t, 'halo_mvir', delete_possibly_existing_column = True)\n \n del t\n\n def test_add_halo_hostid1(self):\n \"\"\"\n \"\"\"\n with pytest.raises(HalotoolsError) as err:\n add_halo_hostid(5, delete_possibly_existing_column = False)\n substr = \"The input ``table`` must be an Astropy `~astropy.table.Table` object\"\n assert substr in err.value.message\n\n def test_add_halo_hostid2(self):\n \"\"\"\n \"\"\"\n t = deepcopy(self.table)\n del t['halo_id']\n with pytest.raises(HalotoolsError) as err:\n add_halo_hostid(t, delete_possibly_existing_column = False)\n substr = \"The input table must have ``halo_upid`` and ``halo_id`` keys\"\n assert substr in err.value.message\n\n def test_add_halo_hostid3(self):\n \"\"\"\n \"\"\"\n t = deepcopy(self.table)\n with pytest.raises(HalotoolsError) as err:\n add_halo_hostid(t, delete_possibly_existing_column = False)\n substr = \"Your input table already has an existing ``halo_hostid`` column name.\"\n assert substr in err.value.message\n\n existing_halo_hostid = deepcopy(t['halo_hostid'].data)\n del t['halo_hostid']\n\n add_halo_hostid(t, delete_possibly_existing_column = False)\n\n assert np.all(t['halo_hostid'] == existing_halo_hostid)\n\n add_halo_hostid(t, delete_possibly_existing_column = True)\n assert np.all(t['halo_hostid'] == existing_halo_hostid)\n\n\n def tearDown(self):\n del self.table\n\n\n\n\n\n\n\n\n\n","sub_path":"halotools/utils/tests/test_value_added_halo_table_functions.py","file_name":"test_value_added_halo_table_functions.py","file_ext":"py","file_size_in_byte":4490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"167326458","text":"from PyQt5 import QtWidgets\nfrom PyQt5.QtCore import Qt, pyqtSignal\nfrom PyQt5.QtWidgets import (QFileDialog, QTableWidget, QTableWidgetItem,\n QWidget)\n\nfrom DataManager import DataManager\nfrom HelperFunctions import HelperFunction as hf, PlotType, DataAction\n\n\nclass DataManagerTab(QWidget):\n data_selection_signal = pyqtSignal(bool, DataAction)\n\n def __init__(self, tab):\n super().__init__()\n\n self.title = 'Data Manager'\n self.source_directory = \"\"\n\n self.data_manager = None\n\n self.button_width = tab.button_width\n self.element_height = tab.element_height\n self.margin = tab.horizontal_margin\n self.empty_label_width = tab.main_gui.width - 3 * self.margin\n self.height = tab.main_gui.height\n\n self.data_has_level = True\n\n self.is_updating = False\n\n self.data_action = None\n self.plot_type = None\n\n self.init_ui()\n\n def init_ui(self):\n text = \"Source Directory Path\"\n hf.create_label(self, text, self.margin, 10, self.element_height)\n\n text = \"No Source Directory Selected\"\n self.source_directory_label = hf.create_label_with_width(\n self, text, self.margin, 10 + self.element_height,\n self.empty_label_width, self.element_height)\n\n text = \"Select Source Directory\"\n self.source_directory_button = hf.create_button(\n self, text, self.margin, 10 + 2.25 * self.element_height,\n self.button_width, self.element_height)\n self.source_directory_button.clicked.connect(\n self.show_source_directory_dialog)\n\n text = \"Variable: Name\"\n self.name_label = hf.create_label_with_width(\n self, text, self.margin, 10 + 3.5 * self.element_height,\n self.empty_label_width, self.element_height)\n\n text = \"Name: Long Name\"\n self.long_name_label = hf.create_label_with_width(\n self, text, self.margin, 10 + 4.5 * self.element_height,\n self.empty_label_width, self.element_height)\n\n text = \"Units: Units\"\n self.unit_label = hf.create_label_with_width(\n self, text, self.margin, 10 + 5.5 * self.element_height,\n self.empty_label_width, self.element_height)\n\n text = \"Time Series Data\"\n self.time_series_radio_button = hf.create_radio_button(\n self, text, self.margin, 10 + 6.75 * self.element_height,\n self.button_width, self.element_height)\n\n text = \"Heat Map Data\"\n self.heat_map_radio_button = hf.create_radio_button(\n self, text, self.button_width, 10 + 6.75 * self.element_height,\n self.button_width, self.element_height)\n\n self.heat_map_radio_button.toggled.connect(\n self.update_table_on_button_toggle)\n\n text = \"Select data parameters here:\"\n hf.create_label(self, text, self.margin,\n 10 + 7.75 * self.element_height, self.element_height)\n\n self.table = QTableWidget(self)\n self.table.setSizeAdjustPolicy(\n QtWidgets.QAbstractScrollArea.AdjustToContents)\n self.table.horizontalHeader().setVisible(False)\n self.table.verticalHeader().setVisible(False)\n self.table.setRowCount(5)\n self.table.setColumnCount(6)\n\n header_list = [\n \"Parameter\", \"Unit\", \"Minimum Value\", \"Maximum Value\",\n \"Selected Min Value\", \"Selected Max Value\"\n ]\n for row in range(5):\n for col in range(6):\n if row == 0:\n item = QTableWidgetItem(header_list[col])\n item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n self.table.setItem(row, col, item)\n elif col < 4:\n item = QTableWidgetItem()\n item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n self.table.setItem(row, col, item)\n else:\n item = QTableWidgetItem()\n self.table.setItem(row, col, item)\n self.table.item(1, 0).setText(\"Time Range\")\n self.table.item(2, 0).setText(\"Latitude Range\")\n self.table.item(3, 0).setText(\"Longitude Range\")\n self.table.item(4, 0).setText(\"Level Range\")\n self.table.item(1, 1).setText(\"Date Hours\")\n\n self.table.move(self.margin, 10 + 9 * self.element_height)\n self.resize_table()\n self.table.cellChanged.connect(self.check_data_bounds)\n\n text = \"Export Data\"\n self.export_data_button = hf.create_button(\n self, text, self.margin, 10 + 15.75 * self.element_height,\n self.button_width, self.element_height)\n\n text = \"Plot Data\"\n self.plot_data_button = hf.create_button(\n self, text, 2 * self.margin + self.button_width,\n 10 + 15.75 * self.element_height, self.button_width,\n self.element_height)\n self.plot_data_button.clicked.connect(self.plot_data)\n\n self.export_data_button.clicked.connect(self.export_data)\n\n self.time_series_radio_button.toggled.connect(\n self.update_table_on_button_toggle)\n self.time_series_radio_button.setChecked(True)\n\n self.statusBar = hf.create_status_bar(self, \"Ready\", 0.5 * self.margin,\n self.height - 5.2 * self.margin,\n self.empty_label_width,\n self.element_height)\n\n self.show()\n\n def get_data_manager(self) -> DataManager:\n return self.data_manager\n\n def resize_table(self):\n self.table.resizeColumnsToContents()\n self.table.setFixedWidth(1.05 * self.table.columnWidth(0) +\n self.table.columnWidth(1) +\n self.table.columnWidth(2) +\n self.table.columnWidth(3) +\n self.table.columnWidth(4) +\n self.table.columnWidth(5))\n self.table.setFixedHeight(1.1 * self.table.rowHeight(0) +\n self.table.rowHeight(1) +\n self.table.rowHeight(2) +\n self.table.rowHeight(3) +\n self.table.rowHeight(4))\n\n def update_table_on_button_toggle(self):\n if self.heat_map_radio_button.isChecked():\n self.plot_type = PlotType.HEAT_MAP\n else:\n self.plot_type = PlotType.TIME_SERIES\n\n self.is_updating = True\n if self.time_series_radio_button.isChecked():\n self.table.item(2, 5).setFlags(Qt.ItemIsSelectable)\n self.table.item(2, 5).setText(\"------\")\n self.table.item(3, 5).setFlags(Qt.ItemIsSelectable)\n self.table.item(3, 5).setText(\"------\")\n else:\n self.table.item(2,\n 5).setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable\n | Qt.ItemIsEnabled)\n self.table.item(2, 5).setText(\"\")\n self.table.item(3,\n 5).setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable\n | Qt.ItemIsEnabled)\n self.table.item(3, 5).setText(\"\")\n\n self.is_updating = False\n\n def check_data_bounds(self):\n if not self.is_updating and isinstance(self.data_manager, DataManager):\n row = self.table.currentRow()\n col = self.table.currentColumn()\n if not self.is_cell_empty(row, col):\n if row == 1 and col == 4:\n if self.data_manager.set_begin_time(\n self.table.item(row, col).text()):\n self.table.item(row, col).setText(\n hf.get_str_from_datetime(\n self.data_manager.begin_date))\n if row == 1 and col == 5:\n if self.data_manager.set_end_time(\n self.table.item(row, col).text()):\n self.table.item(row, col).setText(\n hf.get_str_from_datetime(\n self.data_manager.end_date))\n if row == 2 and col == 4:\n if self.data_manager.set_lat_min(\n self.table.item(row, col).text()):\n self.table.item(row, col).setText(\n str(self.data_manager.lat_min))\n if row == 2 and col == 5:\n if self.data_manager.set_lat_max(\n self.table.item(row, col).text()):\n self.table.item(row, col).setText(\n str(self.data_manager.lat_max))\n if row == 3 and col == 4:\n if self.data_manager.set_lon_min(\n self.table.item(row, col).text()):\n self.table.item(row, col).setText(\n str(self.data_manager.lon_min))\n if row == 3 and col == 5:\n if self.data_manager.set_lon_max(\n self.table.item(row, col).text()):\n self.table.item(row, col).setText(\n str(self.data_manager.lon_max))\n if row == 4 and col == 4:\n if self.data_manager.set_lev_min(\n self.table.item(row, col).text()):\n self.table.item(row, col).setText(\n str(hf.round_number(self.data_manager.lev_min, 5)))\n if row == 4 and col == 5:\n if self.data_manager.set_lev_max(\n self.table.item(row, col).text()):\n self.table.item(row, col).setText(\n str(hf.round_number(self.data_manager.lev_max, 5)))\n\n def check_data_bounds_on_button_press(self):\n if self.plot_type == PlotType.TIME_SERIES:\n if not self.is_updating and isinstance(self.data_manager,\n DataManager):\n b1 = self.data_manager.set_begin_time(\n self.table.item(1, 4).text())\n b2 = self.data_manager.set_end_time(\n self.table.item(1, 5).text())\n b3 = self.data_manager.set_lat_min(\n self.table.item(2, 4).text())\n b4 = self.data_manager.set_lon_min(\n self.table.item(3, 4).text())\n if len(self.data_manager.shape) == 4:\n b5 = self.data_manager.set_lev_min(\n self.table.item(4, 4).text())\n b6 = self.data_manager.set_lev_max(\n self.table.item(4, 5).text())\n if b1 and b2 and b3 and b4 and b5 and b6:\n if self.data_manager.begin_date < self.data_manager.end_date:\n return True\n else:\n hf.show_error_message(\n self, \"Please select a non-zero time range!\")\n return False\n else:\n return False\n else:\n if b1 and b2 and b3 and b4:\n if self.data_manager.begin_date < self.data_manager.end_date:\n return True\n else:\n hf.show_error_message(\n self, \"Please select a non-zero time range!\")\n return False\n else:\n return False\n else:\n hf.show_error_message(self, \"Select a source file!\")\n return False\n elif self.plot_type == PlotType.HEAT_MAP:\n if not self.is_updating and isinstance(self.data_manager,\n DataManager):\n b1 = self.data_manager.set_begin_time(\n self.table.item(1, 4).text())\n b2 = self.data_manager.set_end_time(\n self.table.item(1, 5).text())\n b3 = self.data_manager.set_lat_min(\n self.table.item(2, 4).text())\n b4 = self.data_manager.set_lat_max(\n self.table.item(2, 5).text())\n b5 = self.data_manager.set_lon_min(\n self.table.item(3, 4).text())\n b6 = self.data_manager.set_lon_max(\n self.table.item(3, 5).text())\n if len(self.data_manager.shape) == 4:\n b7 = self.data_manager.set_lev_min(\n self.table.item(4, 4).text())\n b8 = self.data_manager.set_lev_max(\n self.table.item(4, 5).text())\n if b1 and b2 and b3 and b4 and b5 and b6 and b7 and b8:\n return True\n else:\n return False\n else:\n if b1 and b2 and b3 and b4 and b5 and b6:\n return True\n else:\n return False\n else:\n hf.show_error_message(self, \"Select a source file!\")\n return False\n else:\n return False\n\n def show_error(self, message: str):\n hf.show_error_message(self, message)\n\n def clear_table(self):\n for row in range(1, 5):\n for col in range(4, 6):\n self.table.item(row, col).setText(\"\")\n self.update_table_on_button_toggle()\n\n def export_data(self):\n if self.check_data_bounds_on_button_press():\n self.data_manager.set_data_action(self.data_action)\n self.data_manager.set_plot_type(self.plot_type)\n self.data_manager.preparation_finished.connect(\n self.export_data_signal)\n self.data_manager.message.connect(self.show_status_bar_message)\n self.data_manager.start()\n self.data_selection_signal.emit(True, DataAction.EXPORT)\n else:\n hf.show_error_message(self, \"Could not start Extraction!\")\n return\n\n def plot_data(self):\n if self.check_data_bounds_on_button_press():\n self.data_manager.set_data_action(self.data_action)\n self.data_manager.set_plot_type(self.plot_type)\n self.data_manager.preparation_finished.connect(\n self.plot_data_signal)\n self.data_manager.message.connect(self.show_status_bar_message)\n self.data_manager.start()\n self.data_selection_signal.emit(True, DataAction.PLOT)\n else:\n return\n\n def update_info(self):\n self.clear_table()\n text = \"Variable: \" + self.data_manager.metadata['name']\n self.name_label.setText(text)\n\n text = \"Name: \" + self.data_manager.metadata['long_name']\n self.long_name_label.setText(text)\n\n text = \"Units: \" + self.data_manager.metadata['units']\n self.unit_label.setText(text)\n\n data = self.data_manager.get_data_time_range_str()\n self.table.item(1, 2).setText(data[0])\n self.table.item(1, 3).setText(data[1])\n\n data = self.data_manager.get_data_lat_range_str()\n self.table.item(2, 2).setText(data[0])\n self.table.item(2, 1).setText(data[2])\n self.table.item(2, 3).setText(data[1])\n\n data = self.data_manager.get_data_lon_range_str()\n self.table.item(3, 2).setText(data[0])\n self.table.item(3, 1).setText(data[2])\n self.table.item(3, 3).setText(data[1])\n\n if self.data_has_level:\n self.table.item(4,\n 0).setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n self.table.item(4,\n 1).setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n self.table.item(4,\n 2).setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n self.table.item(4,\n 3).setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)\n self.table.item(4,\n 4).setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable\n | Qt.ItemIsEnabled)\n self.table.item(4, 4).setText(\"\")\n self.table.item(4,\n 5).setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable\n | Qt.ItemIsEnabled)\n self.table.item(4, 5).setText(\"\")\n\n data = self.data_manager.get_data_lev_range_str()\n self.table.item(4, 2).setText(data[0])\n self.table.item(4, 1).setText(data[2])\n self.table.item(4, 3).setText(data[1])\n else:\n self.table.item(4, 0).setFlags(Qt.ItemIsSelectable)\n self.table.item(4, 1).setFlags(Qt.ItemIsSelectable)\n self.table.item(4, 1).setText(\"------\")\n self.table.item(4, 2).setFlags(Qt.ItemIsSelectable)\n self.table.item(4, 2).setText(\"------\")\n self.table.item(4, 3).setFlags(Qt.ItemIsSelectable)\n self.table.item(4, 3).setText(\"------\")\n self.table.item(4, 4).setFlags(Qt.ItemIsSelectable)\n self.table.item(4, 4).setText(\"------\")\n self.table.item(4, 5).setFlags(Qt.ItemIsSelectable)\n self.table.item(4, 5).setText(\"------\")\n\n self.resize_table()\n\n def is_cell_empty(self, row: int, col: int) -> bool:\n if not self.table.item(row, col) is None:\n return self.table.item(row, col).text() == \"\" or self.table.item(\n row, col).text() == \"------\"\n return False\n\n def show_status_bar_message(self, string: str):\n self.statusBar.showMessage(string)\n\n def export_data_signal(self):\n self.data_selection_signal.emit(True, DataAction.EXPORT)\n\n def plot_data_signal(self):\n self.data_selection_signal.emit(True, DataAction.PLOT)\n\n def show_source_directory_dialog(self):\n msg = \"Select Source Directory\"\n file_name = QFileDialog.getExistingDirectory(self, msg)\n\n if file_name:\n if hf.is_valid_npz_source_directory(\n file_name) and hf.can_read_directory(file_name):\n self.source_directory = file_name\n self.source_directory_label.setText(self.source_directory)\n\n self.data_manager = DataManager(self.source_directory)\n\n self.data_manager.error.connect(self.show_error)\n\n if len(self.data_manager.shape) == 4:\n self.data_has_level = True\n else:\n self.data_has_level = False\n\n self.update_info()\n else:\n hf.show_error_message(\n self, \"The Directory is not a valid Source Directory!\")\n return\n else:\n hf.show_error_message(self, \"Directory Selection Failed!\")\n return\n","sub_path":"programs/gui_program/DataManagerTab.py","file_name":"DataManagerTab.py","file_ext":"py","file_size_in_byte":19279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"214073308","text":"#一些公共方法\nimport os\nimport re\nimport sqlite3\n\nfrom jinja2 import Environment, FileSystemLoader\nfrom prettytable import PrettyTable\nfrom pyecharts import options as opts\nfrom pyecharts.charts import Pie\nfrom pyecharts.charts import Scatter, Line\nfrom pyecharts.commons.utils import JsCode\nfrom pyecharts.globals import ThemeType\nfrom selenium import webdriver\n\nenv = Environment(\n keep_trailing_newline=True,\n trim_blocks=True,\n lstrip_blocks=True,\n loader=FileSystemLoader(\n (\n os.path.join(os.path.dirname(__file__), \"templates\")\n )\n )\n )\n#https://www.jisilu.cn/data/cbnew/cb_index/\n#转股价格中位数\nMID_X = 124.08\n#转股溢价率中位数\nMID_Y = 33.4\n#到期收益率中位数\nMID_YIELD = -3.92\n\n# MID_Y, MID_X, MID_YIELD = get_cb_sum_data()\n\n\ndef calc_yield():\n # 打开文件数据库\n con_file = sqlite3.connect('db/cb.db3')\n cur = con_file.cursor()\n cur.execute(\"\"\"\nSELECT \n\tround(sum(round((c.cb_price2_id/(1+c.cb_mov2_id) * c.cb_mov2_id)*h.hold_amount, 2)) / sum(h.sum_buy-h.sum_sell)*100,2) as '日收益率',\n\tround(sum(round(c.cb_price2_id*h.hold_amount+h.sum_sell -h.sum_buy, 3)) /sum(h.sum_buy - h.sum_sell) * 100, 2) as 累积收益率\nfrom hold_bond h , changed_bond c \nwhere h.bond_code = c.bond_code and hold_owner='me'\n \"\"\")\n\n row = cur.fetchone()\n day_yield = row[0]\n all_yield = row[1]\n return day_yield, all_yield\n\n\n# 计算可转债中位数\ndef calc_middle_info():\n\n # 打开文件数据库\n con_file = sqlite3.connect('db/cb.db3')\n cur = con_file.cursor()\n cur.execute(\"\"\"\nSELECT mid_price, mid_premium from (\n SELECT AVG(cb_price2_id) as mid_price, row_number() OVER () as rn\n FROM (SELECT cb_price2_id\n FROM changed_bond\n ORDER BY cb_price2_id\n LIMIT 2 - (SELECT COUNT(*) FROM changed_bond) % 2 -- odd 1, even 2\n OFFSET (SELECT (COUNT(*) - 1) / 2\n FROM changed_bond))) a\nleft join(\n SELECT AVG(cb_premium_id) as mid_premium, row_number() OVER () as rn\n FROM (SELECT cb_premium_id\n FROM changed_bond\n ORDER BY cb_premium_id\n LIMIT 2 - (SELECT COUNT(*) FROM changed_bond) % 2 -- odd 1, even 2\n OFFSET (SELECT (COUNT(*) - 1) / 2\n FROM changed_bond)) ) b\t\t\t \non a.rn = b.rn\n \n \"\"\")\n\n row = cur.fetchone()\n MID_X = row[0]\n MID_Y = row[1]\n print('init mid data is successful.MID_X:' + str(MID_X) + ', MID_Y:' + str(MID_Y))\n\n # for row in rows:\n\n # if key == 'mid_premium':\n # MID_Y = value\n # elif key == 'mid_price':\n # MID_X = value\n # elif key == 'mid_yield':\n # mid_yield = value\n # else:\n # raise Exception('unknow key:' + key)\n\n # return mid_y, mid_x #, mid_yield\n\n\ndef update_cb_sum_data():\n\n # 打开文件数据库\n con_file = sqlite3.connect('db/cb.db3')\n\n driver = webdriver.Chrome()\n\n driver.implicitly_wait(10)\n\n url = \"https://www.jisilu.cn/data/cbnew/cb_index/\"\n\n # fixme 需要把chromedriver放到/usr/local/bin目录下\n driver.get(url)\n\n div = driver.find_element_by_id(\"cb_index\")\n\n s = div.text\n ss = re.findall(r\"转股溢价率 (\\d+\\.?\\d*)%\", s)\n if len(ss) != 1:\n raise Exception(\"没有找到转股溢价率中位数:\" + s)\n # MID_Y = ss[0]\n result = con_file.execute(\"\"\"insert into config(key,value,field_name)values\n ('mid_premium_rate', ?, 'cb_sum_data')\"\"\",\n (ss[0])\n )\n if result.rowcount == 0:\n print(\"not insert mid_premium_rate config:\" + ss[0])\n else:\n print(\"insert mid_premium_rate is successful. count:\" + str(result.rowcount))\n\n ss = re.findall(r\"中位数价格 (\\d+\\.?\\d*)\", s)\n if len(ss) != 1:\n raise Exception(\"没有找到转股价格中位数:\" + s)\n # MID_X = ss[0]\n result = con_file.execute(\"\"\"insert into config(key,value,field_name)values\n ('mid_price', ?, 'cb_sum_data')\"\"\",\n (ss[0])\n )\n if result.rowcount == 0:\n print(\"not insert mid_price config:\" + ss[0])\n else:\n print(\"insert mid_price is successful. count:\" + str(result.rowcount))\n\n ss = re.findall(r\"到期收益率 (-?\\d+\\.?\\d*)%\", s)\n if len(ss) != 1:\n raise Exception(\"没有找到到期收益率中位数:\" + s)\n # MID_YIELD = ss[0]\n result = con_file.execute(\"\"\"insert into config(key,value,field_name)values\n ('mid_yield_rate', ?, 'cb_sum_data')\"\"\",\n (ss[0])\n )\n if result.rowcount == 0:\n print(\"not insert mid_yield_rate config:\" + ss[0])\n else:\n print(\"insert mid_yield_rate is successful. count:\" + str(result.rowcount))\n\n # print(\"MID_Y = \" + MID_Y + ' \\nMID_X = ' + MID_X + '\\nMID_YIELD = ' + MID_YIELD)\n\n driver.close()\n\ndef get_up_down_data():\n\n driver = webdriver.Chrome()\n\n driver.implicitly_wait(10)\n\n url = \"https://www.ninwin.cn/index.php?m=cb&c=idx\"\n\n # fixme 需要把chromedriver放到/usr/local/bin目录下\n driver.get(url)\n\n div = driver.find_elements_by_xpath(\"//div[contains(@style,'font-size: 12px;color: gray;margin: 10px 20px;clear: both')]\")[0]\n\n # 最新涨跌:可转债等权:1.57%,上证转债:0.87%,正股等权:2.22%,沪深300:0.67%,中证500:1.33%说明快照'\n s = div.text\n cb_value = re.findall(r\"可转债等权:(-?\\d+\\.?\\d*)%\", s)\n if len(cb_value) != 1:\n raise Exception(\"没有找到可转债等权:\" + s)\n\n hs_value = re.findall(r\"沪深300:(-?\\d+\\.?\\d*)%\", s)\n if len(hs_value) != 1:\n raise Exception(\"没有找到沪深300:\" + s)\n\n driver.close()\n return float(cb_value[0]), float(hs_value[0])\n\n\ndef generate_pie_html(dict_rows, key, value):\n data = []\n for row in dict_rows:\n data.append([row[key], round(row[value], 2)])\n\n pie = Pie(init_opts=opts.InitOpts(theme=ThemeType.SHINE))\n pie.add(\"\", data)\n # pie.set_global_opts(title_opts=opts.TitleOpts(title=\"我的摊大饼策略分布\"))\n pie.set_global_opts(legend_opts=opts.LegendOpts(is_show=False))\n pie.set_series_opts(label_opts=opts.LabelOpts(formatter=\"{b}: {d}%\"))\n pie_html = pie.render_embed('template.html', env)\n return pie_html\n\n\ndef generate_line_html(rows, select=None):\n # 用散点图展示\n line = Line(opts.InitOpts(height='700px', width='1524px', theme=ThemeType.LIGHT))\n\n x = []\n y1 = []\n y2 = []\n y3 = []\n\n for row in rows:\n x.append(row['时间'])\n # y.append([row['累积收益率'], row['日收益率']])\n y1.append(row['我的净值'])\n y2.append(row['等权指数净值'])\n y3.append(row['沪深300净值'])\n\n line.add_xaxis(x)\n\n line.add_yaxis(\"我的净值\", y1)\n line.add_yaxis(\"等权指数净值\", y2)\n line.add_yaxis(\"沪深300净值\", y3)\n\n line.set_global_opts(\n title_opts=opts.TitleOpts(title=\"收益率曲线\", pos_left='center', pos_top=-5),\n tooltip_opts=opts.TooltipOpts(\n formatter=JsCode(\n \"function (params) {return '累积收益率
' + params.value[1] + '%';}\"\n # \"function (params) {return '累积收益率:' + params.value[1] + '%' + '
日收益率:' + params.value[2] + '%';}\"\n )\n ),\n legend_opts=opts.LegendOpts(\n pos_top=20,\n # selected_mode='single'\n ),\n datazoom_opts={'start': 0, 'end': 100},\n toolbox_opts=opts.ToolboxOpts(feature={\n 'dataZoom': {},\n }\n ),\n # visualmap_opts=opts.VisualMapOpts(\n # type_=\"color\", max_=150, min_=20, dimension=1\n # ),\n xaxis_opts=opts.AxisOpts(\n # data=None,\n type_='time',\n name='时间',\n name_gap=30,\n is_scale=True,\n name_location='middle',\n splitline_opts=opts.SplitLineOpts(is_show=False),\n # axislabel_opts=opts.LabelOpts(formatter=\"{value}\"), #echarts.format.formatTime('yy-MM-dd', value*1000)\n axisline_opts=opts.AxisLineOpts(\n is_on_zero=False,\n symbol=['none', 'arrow']\n )\n ),\n yaxis_opts=opts.AxisOpts(\n type_='value',\n name='收益率(%)',\n name_rotate=90,\n name_gap=55,\n name_location='middle',\n is_scale=True,\n axislabel_opts=opts.LabelOpts(formatter='{value}%'),\n splitline_opts=opts.SplitLineOpts(is_show=False),\n axisline_opts=opts.AxisLineOpts(\n is_on_zero=False,\n symbol=['none', 'arrow']\n )\n )\n )\n line.set_series_opts(\n # symbol='none',\n smooth=True,\n label_opts=opts.LabelOpts(is_show=False)\n )\n line_html = line.render_embed('template.html', env)\n return line_html\n\n\ndef generate_scatter_html(tables, select=None):\n # 用散点图展示\n scatter = Scatter(opts.InitOpts(height='700px', width='1624px', theme=ThemeType.LIGHT))\n\n # x = []\n # y = []\n\n for label, table in tables.items():\n if select is not None and label not in select:\n continue\n\n x = []\n y = []\n\n rows = table._rows\n for row in rows:\n record = get_record(table, row)\n x.append(record['转债价格'])\n y.append([record['溢价率'].replace('%', '')*1, record['名称'].replace('转债', '')])\n\n scatter.add_xaxis(x)\n\n scatter.add_yaxis(\n label,\n y,\n label_opts=opts.LabelOpts(\n position='bottom',\n formatter=JsCode( # 调用js代码设置方法提取参数第2个值和参数第3个值\n \"function(params){return params.value[2];}\"\n )\n ),\n # markarea_opts=opts.MarkAreaOpts(\n # is_silent=True,\n # itemstyle_opts=opts.ItemStyleOpts(\n # color='transparent',\n # border_type='dashed',\n # border_width=1,\n # ),\n # data=[\n # [\n # {\n # 'name': label,\n # 'xAxis': 'min',\n # 'yAxis': 'min',\n # },\n # {\n # 'xAxis': 'max',\n # 'yAxis': 'max'\n # }\n # ]\n #\n # ]\n # ),\n # markpoint_opts=opts.MarkPointOpts(\n # data=[\n # {'type': 'max', 'name': 'Max'},\n # {'type': 'min', 'name': 'Min'}\n # ]\n # ),\n markline_opts=opts.MarkLineOpts(\n linestyle_opts=opts.LineStyleOpts(type_='dashed'),\n is_silent=True,\n data=[\n opts.MarkLineItem(x=MID_X, name='转债价格中位数'),\n opts.MarkLineItem(y=MID_Y, name='转债溢价率中位数'),\n ]\n )\n )\n\n # scatter.add_xaxis(x)\n\n scatter.set_global_opts(\n title_opts=opts.TitleOpts(title=\"可转债分布情况\", pos_left='center'),\n tooltip_opts=opts.TooltipOpts(\n formatter=JsCode(\n \"function (params) {return '价格:' + params.value[0] + '元
溢价率:' + params.value[1] + '%';}\"\n )\n ),\n legend_opts=opts.LegendOpts(\n pos_bottom=-8,\n # selected_mode='single'\n ),\n toolbox_opts=opts.ToolboxOpts(feature={\n 'dataZoom': {},\n }\n ),\n # visualmap_opts=opts.VisualMapOpts(\n # type_=\"color\", max_=150, min_=20, dimension=1\n # ),\n xaxis_opts=opts.AxisOpts(\n # data=None,\n type_='value',\n name='转债价格(元)',\n name_gap=30,\n is_scale=True,\n name_location='middle',\n splitline_opts=opts.SplitLineOpts(is_show=False),\n axislabel_opts=opts.LabelOpts(formatter='{value}元'),\n axisline_opts=opts.AxisLineOpts(\n is_on_zero=False,\n symbol=['none', 'arrow']\n )\n ),\n yaxis_opts=opts.AxisOpts(\n type_='value',\n name='转股溢价率(%)',\n name_rotate=90,\n name_gap=35,\n name_location='middle',\n is_scale=True,\n axislabel_opts=opts.LabelOpts(formatter='{value}%'),\n splitline_opts=opts.SplitLineOpts(is_show=False),\n axisline_opts=opts.AxisLineOpts(\n is_on_zero=False,\n symbol=['none', 'arrow']\n )\n )\n )\n # scatter.set_series_opts(emphasis={\n # 'focus': 'series'\n # })\n scatter_html = scatter.render_embed('template.html', env)\n return scatter_html\n\n\ndef generate_table(type, cur, html, need_title=True, field_names=None, rows=None,\n remark_fields_color=[],\n htmls={},\n tables=None,\n subtitle='',\n ignore_fields=[],\n field_links={},\n is_login_user=False,\n table_width=None\n ):\n\n table = from_db(cur, field_names, rows)\n\n if len(table._rows) == 0:\n return table, html\n\n if tables is not None:\n tables[type] = table\n\n add_nav_html(htmls, type)\n\n title = ''\n title_suffix = ''\n if need_title:\n # 首行加两个换行, 避免被但导航栏遮挡\n title = \"\"\"\n
\"\"\" + ('' if len(html) > 0 else '

') + \"\"\"\n

=========我的\"\"\" + type + \"\"\"账户=========
\"\"\" \\\n + ('' if len(subtitle) == 0 else \"\"\"
\"\"\" + subtitle + \"\"\"
\"\"\") + \"\"\"
\"\"\"\n title_suffix = \"\"\"
\"\"\"\n\n return table, html + title + get_html_string(table, remark_fields_color, ignore_fields, is_login_user, field_links, table_width=table_width) + title_suffix\n\n\ndef generate_table_html(type, cur, html, need_title=True, field_names=None, rows=None,\n remark_fields_color=[],\n htmls={},\n tables=None,\n subtitle='',\n ignore_fields=[],\n field_links={},\n is_login_user=False):\n table, html = generate_table(type, cur, html, need_title, field_names, rows, remark_fields_color, htmls, tables, subtitle, ignore_fields, field_links, is_login_user)\n return html\n\ndef from_db(cursor, field_names, rows, **kwargs):\n if cursor.description:\n table = PrettyTable(**kwargs)\n table.field_names = [col[0] for col in cursor.description]\n if field_names is not None:\n table.field_names.extend(field_names)\n if rows is None:\n rows = cursor.fetchall()\n for row in rows:\n table.add_row(row)\n return table\n\n\ndef default_edit_link_maker(hold_id, bond_code):\n if hold_id is not None:\n return '/sync_trade_data.html/' + str(hold_id) + '/'\n\n return '/new_sync_trade_data.html/' + bond_code + '/'\n\n\ndef get_html_string(table, remark_fields_color=[],\n ignore_fields=[], is_login_user=False,\n field_links={},\n table_rows_size=10,\n table_width=None\n ):\n options = table._get_options({})\n rows = table._get_rows(options)\n table_height_style_content = ''\n if table_width is not None:\n table_height_style_content = 'width: ' + table_width\n\n if len(rows) > table_rows_size:\n table_height_style_content = ',height: ' + str(50*10) + 'px' #'style:' + str(50*15) + 'px'\n\n table_height_style = \"\"\"style=\" \"\"\" + table_height_style_content + \"\"\" \" \"\"\"\n\n ignore_fields.extend(['nid', 'id', 'hold_id', 'bond_code', 'stock_code', '持有', '持有成本', '持有数量', 'cb_mov2_id'])\n lines = []\n linebreak = \"
\"\n\n lines.append(\"
\")\n lines.append(\"
\")\n lines.append(\"\")\n\n # Headers\n lines.append(\" \")\n lines.append(\" \")\n\n for field in table._field_names:\n if ignore_fields.count(field) > 0:\n continue\n\n lines.append(\n \" \" % field.replace(\"\\n\", linebreak)\n )\n lines.append(\" \")\n lines.append(\" \")\n\n # Data\n lines.append(\" \")\n # formatted_rows = table._format_rows(rows, options)\n for row in rows:\n lines.append(\" \")\n record = get_record(table, row)\n for field, datum in record.items():\n if ignore_fields.count(field) > 0:\n continue\n\n if datum is not None:\n datum = str(datum)\n else:\n datum = ''\n\n remark_color = ''\n if remark_fields_color.count(field) > 0:\n if datum.startswith('-'):\n remark_color = 'class=\"remarked-down\"'\n else:\n remark_color = 'class=\"remarked-up\"'\n\n if len(field_links) > 0 and id is not None:\n for key, value in field_links.items():\n if field == key:\n datum = value(datum, record)\n\n prefix, prefix_append, suffix = generate_head_tail_html(field, is_login_user, record)\n\n lines.append(\n (\" \") % datum.replace(\"\\n\", linebreak)\n # fixme 重构成函数变量\n .replace('转债标的 ', '')\n .replace('标准普尔 ', '')\n .replace('富时罗素 ', '')\n .replace('上证380 ', '')\n .replace('央视50_ ', '')\n .replace('中证500 ', '')\n .replace('深成500 ', '')\n .replace('融资融券 ', '')\n .replace('上证180_ ', '')\n .replace('HS300_ ', '')\n .replace('MSCI中国 ', '')\n .replace('深股通 ', '')\n .replace('创业板综 ', '')\n .replace('沪股通 ', '')\n )\n lines.append(\" \")\n lines.append(\" \")\n lines.append(\"
%s
\" + prefix + \"%s\" + prefix_append + \"\" + suffix + \"
\")\n lines.append(\"
\")\n lines.append(\"
\")\n\n return \"\\n\".join(lines)\n\n\ndef generate_head_tail_html(field, is_login_user, record):\n # 标题增加链接\n # 可转债: http://quote.eastmoney.com/bond/sz128051.html\n # 正股: http://quote.eastmoney.com/sz002741.html\n prefix = ''\n prefix_append = ''\n suffix = ''\n if field == '名称':\n bond_code = record.get('bond_code')\n nid = record['nid']\n stock_code = record['stock_code']\n market = 'sz'\n if bond_code.startswith('11'):\n market = 'sh'\n prefix = \"\"\n\n prefix_append += \" 宁稳网\"\n\n prefix_append += \" 集思录\"\n\n # https://xueqiu.com/S/SH600998\n suffix = \"
雪球\"\n suffix += \" 东方财富 \"\n suffix += \"同花顺\"\n\n # http://www.ninwin.cn/index.php?m=cb&c=graph_k&a=graph_k&id=157\n suffix += \" 走势图\"\n\n if is_login_user:\n hold_id = record.get('hold_id', None)\n suffix += \" 交易\"\n return prefix, prefix_append, suffix\n\n\ndef add_nav_html(htmls, type):\n if type is not None:\n # 增加导航\n nav_html = htmls.get('nav', '')\n nav_html += get_sub_nav_html(type)\n htmls['nav'] = nav_html\n\n\ndef add_nav_html_to_head(htmls, type, prefix_nav = ''):\n # 'nav': '
  • Home
  • '\n # 增加导航\n nav_html = htmls.get('nav', '')\n nav_html = '
  • Home
  • ' + prefix_nav + get_sub_nav_html(type) + nav_html\n htmls['nav'] = nav_html\n\n\ndef add_sub_nav_html(htmls, title, s):\n # 增加导航\n nav_html = htmls.get('nav', '')\n\n nav_html += \"\"\"\n
  • \n \"\"\" + title + \"\"\"\n
      \n \"\"\" + s + \"\"\"\n
    \n
  • \n \"\"\"\n htmls['nav'] = nav_html\n\n\ndef get_sub_nav_html(type):\n return '
  • ' + type + '
  • '\n\n\ndef get_record(table, row):\n return dict(zip(table._field_names, row))\n\n\ndef get_dict_row(cursor, row):\n if cursor.description:\n field_names = [col[0] for col in cursor.description]\n return dict(zip(field_names, row))\n\n raise Exception('not convert to dict row')\n\n\ndef rebuild_stock_code(stock_code):\n # 沪市A股票买卖的代码是以600、601或603打头, 688创业板\n # 深市A股票买卖的代码是以000打头, 中小板股票代码以002打头, 创业板股票代码以300打头\n if stock_code.startswith('600') or stock_code.startswith('601') or \\\n stock_code.startswith('605') or stock_code.startswith('603') or stock_code.startswith('688'):\n stock_code = 'SH' + stock_code\n elif stock_code.startswith('000') or stock_code.startswith('001') or stock_code.startswith(\n '002') or stock_code.startswith('300'):\n stock_code = 'SZ' + stock_code\n else:\n raise Exception(\"未知股票类型。\" + stock_code)\n return stock_code\n\ndef rebuild_bond_code(bond_code):\n market = 'sz'\n if bond_code.startswith('11'):\n market = 'sh'\n return market + bond_code\n\nif __name__ == \"__main__\":\n get_up_down_data()","sub_path":"common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":23869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"27042050","text":"# -*-coding:utf-8-*-\nimport glob\nimport os\nimport sys\nimport unittest\nimport warnings\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\nsys.path.append(os.path.dirname(cur_dir))\n\n\nclass PredictionTestCase(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n \"\"\"所有测例之前运行一次\"\"\"\n print(\"-test start-\")\n\n @classmethod\n def tearDownClass(cls):\n # 所有测例之后运行一次\n print(\"{} 测试完成!\".format(cls.__name__))\n print(\"**\" * 40)\n\n def tearDown(self):\n # 每个测试用例执行之后做操作\n print('--' * 10)\n\n def setUp(self):\n # 每个测试用例执行之前做操作\n print(\"* {}.{}\".format(self.__class__.__name__, self.__dict__['_testMethodName']))\n\n def test_01_prediction(self):\n from video_classifacation.video_classification_01.prediction import Prediction\n from video_classifacation.video_classification_01.config_01 import Config_01 as Config\n\n saved_model_path = os.path.join(Config.checkpoint_dir, \"lstm.009-0.900.hdf5\")\n prediction = Prediction(saved_model_path)\n results = []\n print(\"\\n\", \"**\" * 20)\n for video_path in glob.glob(os.path.join(Config.videos_dir, \"*\", \"*.mp4\"))[20:25]: # 四个视频\n predict_label = prediction.readable_predict(video_path)\n results.append(predict_label)\n print(\"\\n ***\", \"-\" * 10)\n print(\"video_path: {}\".format(video_path))\n print(\"predict_label: {}\".format(predict_label))\n print(\"***\", \"-\" * 10, \"\\n\")\n print(results)\n\n\nif __name__ == \"__main__\":\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', category=ImportWarning)\n warnings.simplefilter('ignore', category=PendingDeprecationWarning)\n unittest.main()\n","sub_path":"tests/test_prediction.py","file_name":"test_prediction.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"597971386","text":"# -*- coding: UTF-8 -*-\n#! python3\n\n\"\"\"\n Name: Script to migration report for \"SIG50\" workgroup metadatas\n Author: Isogeo\n Purpose: Script using the migrations-toolbelt package to perform metadata matching.\n Logs are willingly verbose.\n Python: 3.7+\n\"\"\"\n\n# ##############################################################################\n# ########## Libraries #############\n\n# Standard Library\nimport logging\nfrom logging.handlers import RotatingFileHandler\nfrom os import environ\nfrom pathlib import Path\nfrom timeit import default_timer\nfrom datetime import datetime\nimport csv\n\n# 3rd party\nfrom dotenv import load_dotenv\nfrom halo import Halo\n\n# Isogeo\nfrom isogeo_pysdk import Isogeo\n\n# load .env file\nload_dotenv(\"./env/manche.env\", override=True)\n\nif __name__ == \"__main__\":\n # instanciate log\n # logs\n logger = logging.getLogger()\n # ------------ Log & debug ----------------\n logging.captureWarnings(True)\n logger.setLevel(logging.INFO)\n\n log_format = logging.Formatter(\n \"%(asctime)s || %(levelname)s \"\n \"|| %(module)s - %(lineno)d ||\"\n \" %(funcName)s || %(message)s\"\n )\n\n # debug to the file\n log_file_handler = RotatingFileHandler(\n Path(\"./scripts/manche/_logs/create_migration_report_2021.log\"),\n \"a\",\n 5000000,\n 1,\n )\n log_file_handler.setLevel(logging.INFO)\n log_file_handler.setFormatter(log_format)\n\n # info to the console\n log_console_handler = logging.StreamHandler()\n log_console_handler.setLevel(logging.INFO)\n log_console_handler.setFormatter(log_format)\n\n logger.addHandler(log_file_handler)\n logger.addHandler(log_console_handler)\n\n # Retrieve informations about Isogeo ressources from .env file\n wg_uuid = environ.get(\"ISOGEO_ORIGIN_WORKGROUP\")\n src_cat_uuid = environ.get(\"ISOGEO_CATALOG_SOURCE\")\n src_cat_tag = \"catalog:{}\".format(src_cat_uuid)\n\n # ##################################################################################\n # prepare csv reading\n csv_input_path = Path(r\"./scripts/manche/csv/Migration_Serveur_SIG50_avecIds.csv\")\n readCSV_spinner = Halo(text=\"Fetching infos from '{}' file...\".format(csv_input_path), spinner='dots')\n readCSV_spinner.start()\n fieldnames = [\n \"Name\",\n \"Status\",\n \"IsogeoId\"\n ]\n\n # Fetching info from csv file\n li_tup = []\n li_scanned_md_uuid = []\n with csv_input_path.open() as csvfile:\n reader = csv.DictReader(csvfile, delimiter=\";\", fieldnames=fieldnames)\n\n for row in reader:\n data_name = row.get(\"Name\", \"NR\")\n status = row.get(\"Status\", \"NR\")\n md_uuid = row.get(\"IsogeoId\", \"\")\n\n if reader.line_num > 1 and md_uuid != \"\":\n li_tup.append(\n (\n data_name, status, md_uuid\n )\n )\n li_scanned_md_uuid.append(md_uuid)\n else:\n pass\n\n readCSV_spinner.text = \"{} records fetched from '{}' file.\".format(len(li_tup), csv_input_path)\n readCSV_spinner.succeed()\n\n # ##################################################################################\n\n # API client instanciation\n auth_spinner = Halo(text='Authenticating to Isogeo API...', spinner='dots')\n auth_spinner.start()\n isogeo = Isogeo(\n client_id=environ.get(\"ISOGEO_API_USER_LEGACY_CLIENT_ID\"),\n client_secret=environ.get(\"ISOGEO_API_USER_LEGACY_CLIENT_SECRET\"),\n auth_mode=\"user_legacy\",\n auto_refresh_url=\"{}/oauth/token\".format(environ.get(\"ISOGEO_ID_URL\")),\n platform=environ.get(\"ISOGEO_PLATFORM\", \"qa\"),\n )\n isogeo.connect(\n username=environ.get(\"ISOGEO_USER_NAME\"),\n password=environ.get(\"ISOGEO_USER_PASSWORD\"),\n )\n auth_timer = default_timer()\n\n wg = isogeo.workgroup.get(wg_uuid)\n\n auth_spinner.text = \"Authentication to Isogeo API succeed.\"\n auth_spinner.succeed()\n\n # ##################################################################################\n\n search_spinner = Halo(text=\"Searching for '{}' workgroup metadatas...\".format( wg.name), spinner='dots')\n search_spinner.start()\n\n src_search = isogeo.search(\n group=wg._id,\n whole_results=True,\n include=(\"tags\", )\n )\n li_md = [md for md in src_search.results if md.get(\"name\")]\n\n search_spinner.text = \"{} metadatas found into '{}' workgroup.\".format(len(li_md), wg.name)\n search_spinner.succeed()\n\n isogeo.close()\n\n # # ##################################################################################\n\n report_spinner = Halo(text=\"Looking for new or missing metadatas...\", spinner='dots')\n report_spinner.start()\n\n app_base_url = \"https://app.isogeo.com/groups/{}/resources/\".format(wg._id)\n csv_content = []\n nb_new = 0\n nb_missing = 0\n for md in li_md:\n if src_cat_tag in md.get(\"tags\") and md.get(\"_id\") not in li_scanned_md_uuid:\n nb_missing += 1\n csv_content.append(\n [\n md.get(\"title\", \"NR\"),\n md.get(\"name\"),\n md.get(\"_id\"),\n \"missing\",\n app_base_url + md.get(\"_id\") + \"/identification\"\n ]\n )\n elif md.get(\"_id\") in li_scanned_md_uuid and src_cat_tag not in md.get(\"tags\"):\n nb_new += 1\n csv_content.append(\n [\n md.get(\"title\", \"NR\"),\n md.get(\"name\"),\n md.get(\"_id\"),\n \"new\",\n app_base_url + md.get(\"_id\") + \"/identification\"\n ]\n )\n else:\n pass\n\n report_spinner.text = \"{} missing and {} new metadatas detected.\".format(nb_missing, nb_new)\n report_spinner.succeed()\n\n # ##################################################################################\n\n writeCSV_spinner = Halo(text='Writing report table...', spinner='dots')\n writeCSV_spinner.start()\n\n csv_report_path = Path(\"./scripts/manche/csv/report_migration_{}.csv\".format(int(datetime.now().timestamp())))\n with open(csv_report_path, \"w\", newline=\"\") as csvfile:\n writer = csv.writer(csvfile, delimiter=\";\")\n writer.writerow(\n [\n \"title\",\n \"name\",\n \"uuid\",\n \"issue\",\n \"app_url\"\n ]\n )\n for data in csv_content:\n writer.writerow(data)\n\n writeCSV_spinner.text = \"Report table writed into {} CSV file.\".format(csv_report_path)\n writeCSV_spinner.succeed()\n","sub_path":"scripts/manche/create_migration_report_2021.py","file_name":"create_migration_report_2021.py","file_ext":"py","file_size_in_byte":6696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"284438049","text":"import pandas as pd \nimport numpy as np\nimport json\nimport gzip\nimport tarfile\nimport glob\nimport tracemalloc\n\n\ndef process_a_year(folderPath:str, year:int) -> tuple:\n # tracemalloc.start()\n # current, peak = tracemalloc.get_traced_memory()\n # print(f\"Current memory usage is {current / 10**6}MB; Peak was {peak / 10**6}MB\")\n\n df = pd.read_csv(f\"{folderPath}/{year}.tar.gz\", compression='gzip')\n df = df.rename({df.columns[0]: 'STATION'}, axis=1)\n df = df[df[\"DATE\"] != \"DATE\"]\n df = df.dropna()\n\n # current, peak = tracemalloc.get_traced_memory()\n # print(f\"Current memory usage is {current / 10**6}MB; Peak was {peak / 10**6}MB\")\n # tracemalloc.stop()\n\n # type conversion\n float_columns = [\"LATITUDE\", \"LONGITUDE\", \"ELEVATION\", \"TEMP\", \"MAX\", \"MIN\", \n \"DEWP\", \"VISIB\", \"WDSP\", \"MXSPD\", \"PRCP\", \"SNDP\"]\n df[float_columns] = df[float_columns].astype(np.float32)\n df[\"STATION\"] = df[\"STATION\"].astype(np.int64)\n df[\"DATE\"] = pd.to_datetime(df[\"DATE\"])\n\n country_listPath = \"data/climat/country_list.json\"\n with open(country_listPath, 'rb') as file:\n country_dict = json.load(file)\n\n # df[\"COUNTRY\"] = df[\"NAME\"].str[-2:]\n df[[\"NAME\", \"COUNTRY\"]] = df[\"NAME\"].str.split(\", \", n=2, expand=True)\n df = df[df[\"COUNTRY\"].isin([key for key in country_dict.keys()])]\n df[\"COUNTRY\"] = df[\"COUNTRY\"].map(country_dict)\n df = df[(df[\"LATITUDE\"] > 35) & (df[\"LATITUDE\"] < 72)]\n df = df[~((df[\"COUNTRY\"] == \"Portugal\") & (df[\"LONGITUDE\"] < -15))]\n\n #STP, SLP, GUST, VISIB missing to much values\n df = df[[\"DATE\", \"STATION\", \"COUNTRY\", \"LATITUDE\", \"LONGITUDE\", \"ELEVATION\", \"NAME\", \"TEMP\", \"MAX\", \"MIN\",\n \"DEWP\", \"WDSP\", \"MXSPD\", \"PRCP\", \"SNDP\", \"FRSHTT\"]]\n \n df[[\"TEMP\", \"DEWP\", \"MAX\", \"MIN\"]] = df[[\"TEMP\", \"DEWP\", \"MAX\", \"MIN\"]].replace(9999.9, np.nan)\n df[[\"WDSP\", \"MXSPD\"]] = df[[\"WDSP\", \"MXSPD\"]].replace(999.9, np.nan)\n df[\"SNDP\"] = df[\"SNDP\"].replace(999.9, 0)\n df[\"PRCP\"] = df[\"PRCP\"].replace(99.9, 0)\n df[[\"FOG\", \"RAIN\", \"SNOW\", \"HAIL\", \"THUN\", \"TORN\"]] = df[\"FRSHTT\"].str.extract(r\"(.)(.)(.)(.)(.)(.)\")\n df[[\"FOG\", \"RAIN\", \"SNOW\", \"HAIL\", \"THUN\", \"TORN\"]] = df[[\"FOG\", \"RAIN\", \"SNOW\", \"HAIL\", \"THUN\", \"TORN\"]].astype(np.int8)\n df = df.drop(\"TORN\", axis=1)\n\n # conversion Fahrenheit en Celsius, DWEP = point de rose\n df[[\"TEMP\", \"MAX\", \"MIN\", \"DEWP\"]] = (df[[\"TEMP\", \"MAX\", \"MIN\", \"DEWP\"]] -32) * 5/9\n # knots en kilometre par heure\n df[[\"WDSP\", \"MXSPD\"]] = df[[\"WDSP\", \"MXSPD\"]] * 1.852\n # inche en millimetre\n df[\"SNDP\"] = df[\"SNDP\"] * 2.54\n # inche and hundredths en millimetre\n df[\"PRCP\"] = df[\"PRCP\"] * 0.254\n\n # group by month: [df[\"DATE\"].dt.to_period('m')] or pd.Grouper(key=\"DATE\", freq=\"M\")\n # aggregation\n df = df.groupby([df[\"DATE\"].dt.to_period('m'), df[\"STATION\"]]).agg( \n NAME=(\"NAME\",\"last\"), COUNTRY=(\"COUNTRY\",\"last\"), \n LATITUDE=(\"LATITUDE\",\"last\"), LONGITUDE=(\"LONGITUDE\",\"last\"), \n ELEVATION=(\"ELEVATION\",\"last\"), DAYS_WITH_MEASURES=('TEMP','count'), TEMP=('TEMP','mean'), \n MAX=(\"MAX\",'max'), MIN=(\"MIN\",'min'), DEWP=(\"DEWP\",'mean'), WDSP=(\"WDSP\",'mean'), \n MXSPD=(\"MXSPD\",'max'), SNDP=(\"SNDP\",'sum'), PRCP=(\"PRCP\",'sum'), FOG=(\"FOG\",'sum'), \n RAIN=(\"RAIN\",'sum'), SNOW=(\"SNOW\",'sum'), HAIL=(\"HAIL\",'sum'), THUN=(\"THUN\",'sum'))\n df = df.reset_index()\n \n df = df.groupby([df[\"DATE\"], df[\"NAME\"], df[\"COUNTRY\"]]).agg( \n STATION=(\"STATION\",\"last\"), LATITUDE=(\"LATITUDE\",\"last\"), LONGITUDE=(\"LONGITUDE\",\"last\"), \n DAYS_WITH_MEASURES=(\"DAYS_WITH_MEASURES\",\"sum\"), ELEVATION=(\"ELEVATION\",\"last\"), TEMP=('TEMP','mean'), \n MAX=(\"MAX\",'max'), MIN=(\"MIN\",'min'), DEWP=(\"DEWP\",'mean'), WDSP=(\"WDSP\",'mean'), \n MXSPD=(\"MXSPD\",'max'), SNDP=(\"SNDP\",'mean'), PRCP=(\"PRCP\",'mean'), FOG=(\"FOG\",'mean'), \n RAIN=(\"RAIN\",'mean'), SNOW=(\"SNOW\",'mean'), HAIL=(\"HAIL\",'mean'), THUN=(\"THUN\",'mean'))\n df = df.reset_index()\n \n df = df.groupby([df[\"DATE\"], df[\"LATITUDE\"], df[\"LONGITUDE\"]]).agg( \n STATION=(\"STATION\",\"last\"), NAME=(\"NAME\",\"last\"), COUNTRY=(\"COUNTRY\",\"last\"), \n DAYS_WITH_MEASURES=(\"DAYS_WITH_MEASURES\",\"sum\"), ELEVATION=(\"ELEVATION\",\"last\"), TEMP=('TEMP','mean'), \n MAX=(\"MAX\",'max'), MIN=(\"MIN\",'min'), DEWP=(\"DEWP\",'mean'), WDSP=(\"WDSP\",'mean'), \n MXSPD=(\"MXSPD\",'max'), SNDP=(\"SNDP\",'mean'), PRCP=(\"PRCP\",'mean'), FOG=(\"FOG\",'mean'), \n RAIN=(\"RAIN\",'mean'), SNOW=(\"SNOW\",'mean'), HAIL=(\"HAIL\",'mean'), THUN=(\"THUN\",'mean'))\n df = df.reset_index()\n\n df_drop = df[df[\"DAYS_WITH_MEASURES\"] < 25]\n df = df[df[\"DAYS_WITH_MEASURES\"] >= 25]\n df = df.drop(\"DAYS_WITH_MEASURES\", axis=1)\n\n return df\n\n\ndef process_years(folderPath:str, begin_year:int, end_year:int, destinationPath:str):\n df_list = []\n for year in range(begin_year, end_year + 1):\n df = process_a_year(folderPath, year)\n df_list.append(df)\n dfs = pd.concat(df_list, ignore_index=True)\n\n # on maj les valeurs d'identification sur l'ensemble des annees pour correspondre au données les plus récentes\n dfs[[\"NAME\", \"COUNTRY\", \"LATITUDE\", \"LONGITUDE\", \"ELEVATION\"]] = dfs[[\"NAME\", \"COUNTRY\", \"STATION\", \n \"LATITUDE\", \"LONGITUDE\", \"ELEVATION\"]].groupby([\"STATION\"]).transform('last') \n # sert dans le cas où l'id STATION a changés dans le temps\n dfs[[\"STATION\", \"LATITUDE\", \"LONGITUDE\", \"ELEVATION\"]] = dfs[[\"NAME\", \"COUNTRY\", \"STATION\", \n \"LATITUDE\", \"LONGITUDE\", \"ELEVATION\"]].groupby([\"NAME\", \"COUNTRY\"]).transform('last')\n # sert dans le cas ou une station(même emplacement en LAT et LONG) a changé d'id STATION et de NAME\n dfs[[\"NAME\", \"COUNTRY\", \"STATION\", \"ELEVATION\"]] = dfs[[\"NAME\", \"COUNTRY\", \"STATION\", \n \"LATITUDE\", \"LONGITUDE\", \"ELEVATION\"]].groupby([\"LATITUDE\", \"LONGITUDE\"]).transform('last')\n\n # nombre de mois avec des mesures par station\n months_with_measures = dict(dfs[\"STATION\"].value_counts())\n dfs[\"MONTHS_WITH_MEASURES\"] = dfs[\"STATION\"].map(months_with_measures)\n dfs_drop = dfs[dfs[\"MONTHS_WITH_MEASURES\"] < 6]\n dfs = dfs[dfs[\"MONTHS_WITH_MEASURES\"] >= 6]\n\n dfs_geo_dim = dfs[[\"STATION\", \"NAME\", \"COUNTRY\", \"LATITUDE\", \"LONGITUDE\", \"ELEVATION\"]].drop_duplicates(\"STATION\")\n dfs_fact = dfs.drop([\"NAME\", \"COUNTRY\", \"LATITUDE\", \"LONGITUDE\", \"ELEVATION\",\n \"MONTHS_WITH_MEASURES\"], axis=1)\n\n dfs_fact.to_csv(f\"{destinationPath}/ClimatFACT.csv\", index=False)\n dfs_geo_dim.to_csv(f\"{destinationPath}/StationDIM.csv\", index=False)\n\n\nif __name__ == \"__main__\":\n pd.set_option('display.float_format', lambda x: '%.5f' % x)\n pd.set_option('display.max_columns', None)\n pd.set_option('display.width', 120)\n pd.set_option('display.max_rows', 100)\n pd.set_option('display.min_rows', 30)\n\n process_years(\"data/climat/daily_raw\", 2000, 2020, \"data/climat/clean_for_bi\")\n","sub_path":"src/climat/traitement_donnees.py","file_name":"traitement_donnees.py","file_ext":"py","file_size_in_byte":6909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"163657133","text":"# -*- coding: utf-8 -*-\n# @StartTime : 2018/7/17 22:48\n# @EndTime : 2018/7/17 22:48\n# @Author : Andy\n# @Site : \n# @File : 059_180717.py\n# @Software: PyCharm\n\n\"\"\"\n请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,\n第三行按照从左到右的顺序打印,其他行以此类推。\n\"\"\"\n\n# -*- coding:utf-8 -*-\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 Print(self, pRoot):\n # write code here\n if not pRoot:\n return []\n deque = [pRoot]\n reverse = False\n res = []\n\n while deque:\n count = len(deque)\n next_deque = []\n temp = []\n if not reverse:\n for _ in range(count):\n this = deque.pop()\n if this.left:\n next_deque.append(this.left)\n if this.right:\n next_deque.append(this.right)\n temp.append(this.val)\n deque = next_deque[:]\n res.append(temp)\n reverse = ~reverse\n else:\n for _ in range(count):\n this = deque.pop()\n if this.right:\n next_deque.append(this.right)\n if this.left:\n next_deque.append(this.left)\n temp.append(this.val)\n # del deque[0]\n deque = next_deque[:]\n res.append(temp)\n reverse = ~reverse\n\n return res\n\nroot = TreeNode(1)\nroot.left = TreeNode(2)\nroot.right = TreeNode(3)\nroot.left.left = TreeNode(4)\nroot.left.left.right = TreeNode(5)\n# root.right = TreeNode(6)\nroot.right.right = TreeNode(7)\nprint(Solution().Print(root))","sub_path":"nowcoder/059_180717.py","file_name":"059_180717.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"535740758","text":"#!/usr/bin/python\n\nimport math\n\ndef recipe_batches(recipe, ingredients):\n # make lists from values of passed in dictionaries\n recipe_quantities = list(recipe.values())\n ingredients_quantities = list(ingredients.values())\n # add 0 for each left off ingredient (specifically for the first test)\n while len(recipe_quantities) != len(ingredients_quantities):\n ingredients_quantities.append(0)\n # create a new list and add the ratio of eligible batches, rounded down to an int\n minimum_case = list()\n for i in range(0, len(recipe_quantities)):\n minimum_case.append(int(ingredients_quantities[i] / recipe_quantities[i]))\n # return the minimum value (least number of batches) from the above operation\n return min(minimum_case)\n\n\nif __name__ == '__main__':\n # Change the entries of these dictionaries to test\n # your implementation with different inputs\n recipe = { 'milk': 100, 'butter': 50, 'flour': 5 }\n ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 }\n print(\"{batches} batches can be made from the available ingredients: {ingredients}.\".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))\n","sub_path":"recipe_batches/recipe_batches.py","file_name":"recipe_batches.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"34159127","text":"from tigershark import X12_4010_X061A1\nfrom tigershark import X12_4010_X070\nfrom tigershark import X12_4010_X091A1\nfrom tigershark import X12_4010_X092A1\nfrom tigershark import X12_4010_X093A1\nfrom tigershark import X12_4010_X094A1\nfrom tigershark import X12_4010_X095A1\nfrom tigershark import X12_4010_X096A1\nfrom tigershark import X12_4010_X097A1\nfrom tigershark import X12_4010_X098A1\nfrom tigershark import X12_4010_XXXC\nfrom tigershark import X12_5010_X221A1\nfrom tigershark import X12_5010_X279A1\nfrom tigershark.extras import standardSegment\nfrom tigershark.X12.parse import Loop\nfrom tigershark.X12.parse import Message\nfrom tigershark.X12.parse import ParseError\nfrom tigershark.X12.parse import Properties\n\n# Transaction Set ID -> X12VersionTuple -> [(parser module, parser name)]\nPARSER_MAP = {\n '270': {\n X12_4010_X092A1: [('M270_4010_X092_A1', 'parsed_270')],\n X12_5010_X279A1: [('M270_5010_X279_A1', 'parsed_270')],\n },\n '271': {\n X12_4010_X092A1: [('M271_4010_X092_A1', 'parsed_271')],\n X12_5010_X279A1: [('M271_5010_X279_A1', 'parsed_271')],\n },\n '276': {\n X12_4010_X093A1: [('M276_4010_X093_A1', 'parsed_276')],\n },\n '277U': {\n X12_4010_X070: [('M277U_4010_X070', 'parsed_277U')],\n },\n '277': {\n X12_4010_X093A1: [('M277_4010_X093_A1', 'parsed_277')],\n },\n '278': {\n X12_4010_X094A1: [('M278_4010_X094_27_A1', 'parsed_278'),\n ('M278_4010_X094_A1', 'parsed_278')],\n },\n '820': {\n X12_4010_X061A1: [('M820_4010_X061_A1', 'parsed_820')],\n },\n '834': {\n X12_4010_X095A1: [('M834_4010_X095_A1', 'parsed_834')],\n },\n '835': {\n X12_4010_X091A1: [('M835_4010_X091_A1', 'parsed_835')],\n X12_5010_X221A1: [('M835_5010_X221_A1', 'parsed_835')],\n },\n '837': {\n X12_4010_X096A1: [('M837_4010_X096_A1', 'parsed_837')],\n X12_4010_X097A1: [('M837_4010_X097_A1', 'parsed_837')],\n X12_4010_X098A1: [('M837_4010_X098_A1', 'parsed_837')],\n },\n '841': {\n X12_4010_XXXC: [('M841_4010_XXXC', 'parsed_841')],\n },\n}\n\n\ndef get_parsers(transaction_set_id, version_tuple):\n \"\"\"\n Generate the parsers to try for a given transaction_set and version.\n\n The parsers should be tried in the given order.\n \"\"\"\n try:\n parsers = PARSER_MAP[transaction_set_id][version_tuple]\n except KeyError:\n raise ValueError(\"Unsupported transaction set and version.\",\n transaction_set_id, version_tuple)\n\n for index, (module_name, parser_name) in enumerate(parsers):\n module = __import__('tigershark.parsers.' + module_name,\n fromlist=[parser_name])\n yield getattr(module, parser_name)\n\n\nclass SimpleParser(object):\n \"\"\"\n A parser for a particular transaction set and version.\n \"\"\"\n def __init__(self, transaction_set_id, version_tuple):\n self.transaction_set_id = transaction_set_id\n self.version_tuple = version_tuple\n\n def unmarshall(self, x12_contents, **kwargs):\n for parser in get_parsers(self.transaction_set_id, self.version_tuple):\n try:\n return parser.unmarshall(x12_contents, **kwargs)\n except ParseError:\n continue\n else:\n # Let the last parser raise.\n return parser.unmarshall(x12_contents, **kwargs)\n\n\nSTLoop = Loop(\n u'ST_LOOP',\n Properties(\n position=u'0200',\n looptype=u'explicit',\n repeat=u'>1',\n req_sit=u'R',\n desc=u'Transaction Set Header',\n ),\n standardSegment.st,\n)\n\nGSLoop = Loop(\n u'GS_LOOP',\n Properties(\n position=u'0200',\n looptype=u'explicit',\n repeat=u'>1',\n req_sit=u'R',\n desc=u'Functional Group Header',\n ),\n standardSegment.gs,\n STLoop,\n)\n\nISALoop = Loop(\n u'ISA_LOOP',\n Properties(\n position=u'0010',\n looptype=u'explicit',\n repeat=u'>1',\n req_sit=u'R',\n desc=u'Interchange Control Header',\n ),\n standardSegment.isa,\n GSLoop,\n)\n\nControlParser = Message(\n u'ASC X12 Interchange Control Structure',\n Properties(\n desc=u'ASC X12 Control Structure',\n ),\n ISALoop,\n)\n\n\ndef parse_control_headers(x12_contents):\n \"\"\"Parse only the control headers of an X12 message.\n\n This parses the three outer control headers of the given X12 message:\n\n * Interchange Control (ISA)\n * Functional Group (GS)\n * Transaction Set (ST).\n\n These can be used to identify the X12 versions and transaction set types\n contained in the message.\n \"\"\"\n return ControlParser.unmarshall(x12_contents, ignoreExtra=True)\n","sub_path":"tigershark/parsers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"244703165","text":"import pandas as pd\nimport os\nimport csv\nfrom csv import writer as csv_writer\n\n\ndf = pd.read_csv('/Users/student/Dropbox/PhD/2020 Winter/Dissertation_v9/Africa/Blue_Nile/Blue_Nile_Stations.csv')\n\nCOMIDs = df['COMID'].tolist()\nNames = df['Station'].tolist()\nRivers = df['Stream'].tolist()\n\nfor name, comid in zip(Names, COMIDs):\n\n\tdata = pd.read_csv(\"/Users/student/Dropbox/PhD/2020 Winter/Dissertation_v9/Africa/Blue_Nile/Data/Historical/simulated_data/ERA_5/Hourly/{0}_{1}.csv\".format(comid,name), index_col=0)\n\n\tdata.index = pd.to_datetime(data.index)\n\n\tdaily_df = data.groupby(data.index.strftime(\"%Y/%m/%d\")).mean()\n\tdaily_df.index = pd.to_datetime(daily_df.index)\n\tprint(daily_df)\n\n\tdaily_df.to_csv(\"/Users/student/Dropbox/PhD/2020 Winter/Dissertation_v9/Africa/Blue_Nile/Data/Historical/simulated_data/ERA_5/Daily/{0}_{1}.csv\".format(comid,name), index_label=\"Datetime\")","sub_path":"GRDC_Africa/get_DailyData_Blue_Nile.py","file_name":"get_DailyData_Blue_Nile.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"602144221","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 ('blog', '0002_post_caption'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='post',\n name='drunk',\n field=models.BooleanField(default=False),\n ),\n migrations.AddField(\n model_name='post',\n name='garbage',\n field=models.IntegerField(default=0),\n ),\n migrations.AddField(\n model_name='post',\n name='love',\n field=models.IntegerField(default=0),\n ),\n migrations.AlterField(\n model_name='post',\n name='caption',\n field=models.CharField(max_length=200, default='You should add a caption'),\n ),\n ]\n","sub_path":"blog/migrations/0003_auto_20170711_1514.py","file_name":"0003_auto_20170711_1514.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"470363988","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 26 13:03:54 2019\n\n@author: larakamal\n\"\"\"\nimport csv \n\ndef duplicate(items): \n unique = [] \n dup = []\n for item in items: \n if item not in unique: \n unique.append(item) \n else:\n dup.append(item)\n return unique, dup\n\n\n#find the transpose of a matrix \ndef matrixTranspose(matrix):\n if not matrix: \n return []\n else:\n try:\n return [ [ row[ i ] for row in matrix ] for i in range( len( matrix[ 0 ] ) ) ]\n except:\n result = []\n for i in matrix:\n result.append([i])\n return result\nagn1 = []\nR1 = []\nn1 = []\nU1 = []\nZ1 = []\nNH1 = []\nrest1 = []\n\nZ2 = []\nU2 = []\nn2 = []\nNH2 =[]\nR2 = []\nagn2 = []\nredshift = []\nrest2 = []\n\nfile_reader = open('/Users/larakamal/Desktop/argo/combinedFileV5.csv', \"r\")\nread = csv.reader(file_reader)\nfor row in read:\n if(row[3] != ''):\n agn1.append(row[1:2])\n Z1.append(row[2:3])\n n1.append(row[3:4])\n R1.append(row[4:5])\n NH1.append(row[5:6])\n U1.append(row[6:7])\n rest1.append(row[7:])\n \n\nfile_reader = open('/Users/larakamal/Desktop/argo/grid_colors_with_R_V4.csv', \"r\")\nread = csv.reader(file_reader)\nfor row in read:\n #separate training and target\n if(row[0] != ''):\n Z2.append(row[0:1])\n U2.append(row[1:2])\n R2.append(row[2:3])\n n2.append(row[3:4])\n NH2.append(row[4:5])\n agn2.append(row[5:6])\n redshift.append(row[6:7])\n rest2.append(row[7:])\n \n\nnames = ['Z', 'U', 'NH', 'n', 'R', 'agn', 'redshift']\n#combine labeling row \nnames = names + rest2[0] + rest1[0]\nmatrix = []\nmatrix.append(names)\n\n#remove label row \nagn1 = agn1[1:] \nR1 = R1[1:] \nNH1 = NH1[1:] \nU1 = U1[1:] \nZ1 = Z1[1:] \nn1 = n1[1:] \nrest1 = rest1[1:] \n\nZ2 = Z2[1:] \nU2 = U2[1:] \nNH2 = NH2[1:] \nn2 = n2[1:] \nR2 = R2[1:] \nagn2 = agn2[1:]\nredshift = redshift[1:]\nrest2 = rest2[1:] \n\n#create a matrix with Z, U, etc\ntest = []\nfor i in range(len(Z2)):\n curr= [Z2[i][0],U2[i][0],NH2[i][0],n2[i][0],R2[i][0],agn2[i][0]]\n test.append(curr)\n\n#unique, dup = duplicate(test)\n#for i in d:\n # print(i)\n \ntest2 = []\nfor i in range(len(Z1)):\n curr= [Z1[i][0],U1[i][0],NH1[i][0],n1[i][0],R1[i][0],agn1[i][0]]\n test.append(curr)\n\n#unique2, dup2 = duplicate(test2)\n#for i in d2:\n# print(i)\n \nprint('done')\n\"\"\"\n\n[N11] = matrixTranspose(R1)\n[NH1] = matrixTranspose(R2)\n\nN111 = set(N11)\nNH11 = set(NH1)\n#print(N111)\n#print(\"\")\n#print(NH11)\na = set(N11).intersection(set(NH1))\nprint(a)\nprint(len(Z1))\nprint(len(R1))\nprint(len(N1))\nprint(len(U1))\nprint(len(n1))\nprint(len(agn1))\nprint(len(rest1))\n\nprint(len(U2))\nprint(len(Z2))\nprint(len(NH))\nprint(len(n2))\nprint(len(agn2))\nprint(len(rest2))\n\n\n\"\"\"\n\nnonMatching = []\nnum = []\n#print(Z1[4][0])\nplace = 0 \nrounding = 7\nfor i in range(len(Z1)):\n for j in range(len(Z2)):\n if (float(Z1[i][0]) == float(Z2[j][0]) and float(U1[i][0]) == float(U2[j][0]) and float(agn1[i][0]) == float(agn2[j][0]) and float(n1[i][0]) == float(n2[j][0]) and float(NH1[i][0]) == float(NH2[j][0]) and float(R1[i][0]) == float(R2[j][0])):\n num.append(j)\n \n curr = []\n curr.append(Z2[j][0])\n curr.append(U2[j][0])\n curr.append(NH2[j][0])\n curr.append(n2[j][0])\n curr.append(R2[j][0])\n curr.append(agn2[j][0])\n curr.append(redshift[j][0])\n curr = curr + rest2[j] + rest1[i]\n if (curr not in matrix):\n matrix.append(curr)\n place = place +1\n print(place)\n elif (j == len(Z2) -1):\n nonMatching.append([Z2[j][0],U2[j][0], NH2[j][0],n2[j][0],R2[j][0],agn2[j][0]])\n \n \n\"\"\"\nprint(len(R1))\nprint(len(R2))\nprint(len(matrix))\nprint(len(num))\nnum2, dup = duplicate(num)\nprint(len(dup))\nprint(dup)\n\"\"\"\n\nwith open('colorgridoutput6.csv', mode='w') as file:\n outputwriter = csv.writer(file, delimiter=',')\n for i in range(len(matrix)):\n outputwriter.writerow(matrix[i])\nfile.close()\n \nwith open('nonMatching.csv', mode='w') as file2:\n outputwriter = csv.writer(file2, delimiter=',')\n for i in range(len(nonMatching)):\n outputwriter.writerow(nonMatching[i])\nfile2.close() \n \nprint(\"file is done\")","sub_path":"generatingfile.py","file_name":"generatingfile.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"78154417","text":"# coding: utf-8\n\nfrom flask import Flask, jsonify\nfrom webargs import fields\nfrom webargs.flaskparser import use_kwargs\n\nfrom model.click_count import ClickCountModule\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return jsonify({'data': 'haha', 'success': True})\n\n\n@app.route('/click_counts', methods=['POST'])\n@use_kwargs({'open_id': fields.Str(required=True, allow_none=False)})\ndef create_click_count(open_id):\n ClickCountModule().create_click_count(open_id)\n return jsonify({'success': True})\n\n\n@app.route('/click_counts/', methods=['PUT'])\ndef inc_click_count(open_id):\n count = ClickCountModule().inc_click_count(open_id)\n return jsonify({'success': True, 'count': count})\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"374092373","text":"import telebot\nimport threading\nimport time\nimport os\nimport logging\nimport json\nfrom flask import Flask, request\n\nimport models as m\nfrom renderers import *\nfrom custom_errors import *\nimport utils\n\nfrom dotenv import load_dotenv\nload_dotenv()\n\n__token__ = os.getenv(\"TG_TOKEN\")\ntelebot.logger.setLevel(logging.INFO)\nbot = telebot.AsyncTeleBot(__token__)\n\nguilds = m.Guilds.load()\n\nwith open('feature_whitelist.json') as f:\n __feature_whitelist__ = json.load(f)\n\nwith open('sauron.json') as f:\n __sauron__ = json.load(f)\nprint(__sauron__)\n\n\n################################\n# Middleware #\n################################\ndef needs_to_be_sauroned(message):\n try:\n return message.chat.id in __sauron__[\"target\"] and message.text is not None and message.text[0] is not \"/\"\n except Exception as e:\n logging.exception(e)\n return False\n\n\n@bot.message_handler(func=needs_to_be_sauroned)\ndef handle_sauron(message):\n nazgul = \"[({}){}]:{}\".format(message.chat.title, message.from_user.username, message.text)\n print(nazgul)\n bot.send_message(__sauron__[\"out\"], nazgul)\n\n\n# TODO: This is hack to keep fort feature only for ascent\ndef ensure_feature_whitelisted(command, message):\n command = command.replace(\"/\", \"\", 1)\n whitelist = __feature_whitelist__.get(command, None)\n if whitelist is not None and message.chat.id not in whitelist:\n raise FeatureForbidden(message.chat.id)\n\n\ndef _update_pinned_msg(guild):\n if guild.pinned_message_id is not None:\n bot.edit_message_text(render_guild_admin(guild),\n chat_id=guild.chat_id,\n message_id=guild.pinned_message_id,\n parse_mode=\"Markdown\",\n reply_markup=render_poll_markup(guild))\n\n\ndef process_command(commands, message, doc):\n try:\n parts = message.text.split(' ')\n ensure_feature_whitelisted(parts[0], message)\n guild = guilds.get(message.chat.id)\n if len(parts) >= 2 and parts[1] in commands:\n command_str = parts[1]\n answer = commands[command_str](message)\n _update_pinned_msg(guild)\n guilds.save()\n else:\n raise WrongCommandError(doc)\n except Exception as e:\n if issubclass(type(e), GuildError):\n answer = m.MessageReply(e.message)\n else:\n logging.exception(e)\n answer = m.MessageReply(\"Unknown error\")\n return answer\n\n\ndef handle_command(commands, message, doc):\n answer = process_command(commands, message, doc)\n if answer is not None and len(answer.message) > 0:\n sent = (bot.send_message(message.chat.id, answer.message,\n parse_mode=\"Markdown\",\n disable_notification=True,\n reply_markup=answer.reply_markup,\n )).wait()\n if answer.temporary:\n delete_command_and_reply(message, sent)\n\n\ndef handle_callback(commands, call):\n # monkey patch message data to format of text commands\n call.message.text = call.data\n call.message.from_user = call.from_user\n answer = process_command(commands, call.message, \"Command received: {}\".format(call.data))\n bot.answer_callback_query(call.id, text=answer.message)\n\n\ndef delete_command_and_reply(message, reply):\n def _delete_messages(msg, rep):\n if type(rep) is tuple:\n logging.error(\"Could not delete reply: {}\".format(reply[1]))\n return\n time.sleep(5)\n bot.delete_message(msg.chat.id, msg.message_id)\n bot.delete_message(msg.chat.id, reply.message_id)\n del_task = threading.Thread(target=_delete_messages, args=(message, reply), daemon=True)\n del_task.start()\n\n\n################################\n# Callback Handlers #\n################################\n@bot.callback_query_handler(func=lambda c: True)\ndef cb_query_handler(call):\n cb_handlers = {\n 'reg': exped_reg,\n 'mark': fort_mark,\n 'check': fort_check,\n 'ready': exped_ready,\n 'reassign': fort_reassign,\n }\n handle_callback(cb_handlers, call)\n\n\n################################\n# Expedition Handlers #\n################################\ndef exped_new(message):\n doc = \"\"\"Example:\n/exped new team1 1500\n/exped new team1 1500 description\n \"\"\"\n parts = message.text.split(' ', 4)\n if len(parts) not in [4, 5]:\n raise WrongCommandError(doc)\n time = parts[3]\n title = parts[2]\n try:\n description = parts[4]\n except IndexError:\n description = \"\"\n\n try:\n guild = guilds.get(message.chat.id)\n e = guild.new_expedition(title, time, description)\n return m.MessageReply(\"Expedition created: {} {}\".format(escape_for_markdown(e.title), time))\n except ValueError:\n raise WrongCommandError(doc)\n\n\ndef exped_title(message):\n doc = \"\"\"Example:\n/exped title oldtitle newtitle\n \"\"\"\n parts = message.text.split(' ')\n if len(parts) != 4:\n raise WrongCommandError(doc)\n\n guild = guilds.get(message.chat.id)\n guild.set_expedition_title(parts[2], parts[3])\n return m.MessageReply(\"{} updated to {}\".format(escape_for_markdown(parts[2]), escape_for_markdown(parts[3])))\n\n\ndef exped_description(message):\n doc = \"\"\"Example:\n/exped desc name description\n \"\"\"\n parts = message.text.split(' ', 3)\n if len(parts) < 3:\n raise WrongCommandError(doc)\n if len(parts) == 3:\n parts = parts + [\"\"]\n\n guild = guilds.get(message.chat.id)\n e = guild.set_expedition_description(parts[2], parts[3])\n return m.MessageReply(\"{} description updated\".format(escape_for_markdown(e.title)))\n\n\ndef exped_time(message):\n doc = \"\"\"Example:\n/exped time team HHMM\n \"\"\"\n parts = message.text.split(' ')\n if len(parts) != 4:\n raise WrongCommandError(doc)\n try:\n guild = guilds.get(message.chat.id)\n e = guild.set_expedition_time(parts[2], parts[3])\n return m.MessageReply(\"{} updated to {}\".format(escape_for_markdown(e.title), parts[3]))\n except ValueError:\n raise WrongCommandError(doc)\n\n\ndef exped_delete(message):\n doc = \"\"\"Example:\n/exped delete team\n \"\"\"\n parts = message.text.split(' ')\n if len(parts) == 3:\n guild = guilds.get(message.chat.id)\n guild.delete_expedition(parts[2])\n return m.MessageReply(\"{} deleted.\".format(parts[2]))\n else:\n raise WrongCommandError(doc)\n\n\ndef exped_reg(message):\n doc = \"\"\"Example:\n/exped reg team\n/exped reg team [label]\n \"\"\"\n parts = message.text.split(' ')\n if len(parts) == 4:\n label = parts[3]\n elif len(parts) == 3:\n label = \"\"\n else:\n raise WrongCommandError(doc)\n\n title = parts[2]\n handle = message.from_user.first_name\n handle_id = message.from_user.id\n guild = guilds.get(message.chat.id)\n\n try:\n e, member = guild.checkin_expedition(title, handle_id, handle, label)\n answer_text = \"{} checked in to {}\".format(member.tg_handle, e.title)\n except ExpedMemberAlreadyExists:\n e, member = guild.checkout_expedition(title, handle_id, handle, label)\n answer_text = \"{} checked out of {}\".format(member.tg_handle, e.title)\n return m.MessageReply(answer_text)\n\n\ndef exped_daily(message):\n doc = \"\"\"Example:\n/exped daily team\n/exped daily team [label]\n \"\"\"\n parts = message.text.split(' ')\n if len(parts) == 4:\n label = parts[3]\n elif len(parts) == 3:\n label = \"\"\n else:\n raise WrongCommandError(doc)\n\n title = parts[2]\n handle = message.from_user.first_name\n handle_id = message.from_user.id\n guild = guilds.get(message.chat.id)\n\n e, success = guild.daily_expedition(title, handle_id, handle, label)\n word = \"in to\" if success else \"out of\"\n return m.MessageReply(\"{} checked {} daily {}\".format(handle, word, e.title))\n \n\ndef exped_view(message):\n doc = \"\"\"Example:\n/exped view\n/exped view [team]\n \"\"\"\n parts = message.text.split(' ')\n if len(parts) == 3:\n team = parts[2]\n else:\n team = None\n guild = guilds.get(message.chat.id)\n if team:\n exped = guild.get_expedition(team)\n return m.MessageReply(render_expedition_detail(exped), temporary=False)\n else:\n expeds = list(guild.expeditions.values())\n return m.MessageReply(render_expeditions(expeds,\n guild_reset_time=guild.daily_reset_time,\n filter=False\n ),\n temporary=False)\n\n\ndef exped_ready(message):\n doc = \"\"\"Example:\n/exped ready team\n/exped ready team [label]\n \"\"\"\n parts = message.text.split(' ')\n if len(parts) == 4:\n label = parts[3]\n elif len(parts) == 3:\n label = \"\"\n else:\n raise WrongCommandError(doc)\n\n title = parts[2]\n handle = message.from_user.first_name\n handle_id = message.from_user.id\n guild = guilds.get(message.chat.id)\n\n e, result = guild.ready_expedition(title, handle_id, handle, label)\n bot.edit_message_text(render_expedition_reminder(e),\n chat_id=guild.chat_id,\n message_id=message.message_id,\n parse_mode=\"Markdown\",\n reply_markup=render_ready_markup(e))\n\n ready_string = \"ready\" if result else \"not ready\"\n return m.MessageReply(\"You are marked as {} for {}.\".format(ready_string, e.title))\n\n\n@bot.edited_message_handler(commands=['exped'])\n@bot.message_handler(commands=['exped'])\ndef exped(message):\n exped_commands = {\n 'reg': exped_reg,\n 'new': exped_new,\n 'delete': exped_delete,\n 'time': exped_time,\n 'title': exped_title,\n 'desc': exped_description,\n 'view': exped_view,\n 'daily': exped_daily\n }\n doc = \"\"\"\n/exped command [arguments...]\nAvailable commands are : {}\n \"\"\".format([a for a in exped_commands.keys()])\n handle_command(exped_commands, message, doc)\n\n\n################################\n# Fort Handlers #\n################################\ndef fort_mark(message):\n doc = \"\"\"Example:\n/fort mark\n/fort mark \n\"\"\"\n parts = message.text.split(' ')\n if len(parts) == 3:\n label = parts[2]\n elif len(parts) == 2:\n label = \"\"\n else:\n raise WrongCommandError(doc)\n\n guild = guilds.get(message.chat.id)\n handle = message.from_user.first_name\n handle_id = message.from_user.id\n\n try:\n guild.fort_mark(handle_id, handle, label)\n answer_text = \"Attendance added for {}\".format(handle)\n except FortAttendanceExistsError:\n guild.fort_unmark(handle_id, handle, label)\n answer_text = \"Attendance removed for {}\".format(handle)\n return m.MessageReply(answer_text)\n\n\ndef fort_check(message):\n doc = \"\"\"Example:\n/fort check\n/fort check \n \"\"\"\n parts = message.text.split(' ')\n if len(parts) == 3:\n label = parts[2]\n elif len(parts) == 2:\n label = \"\"\n else:\n raise WrongCommandError(doc)\n\n guild = guilds.get(message.chat.id)\n handle = message.from_user.first_name\n handle_id = message.from_user.id\n\n today = int(guild.get_attendance_today(handle_id, handle, label))\n try:\n result = guild.get_history_of(handle_id, handle, label)\n except FortAttendanceNotFoundError:\n result = 0\n return m.MessageReply(\"Fort count for {}: {}\".format(handle, result + today))\n\n\ndef fort_reset_history(message):\n doc = \"\"\"Example:\n/fort reset_history\n \"\"\"\n guild = guilds.get(message.chat.id)\n guild.reset_fort_history()\n guilds.save()\n return m.MessageReply(\"Fort history reset.\", temporary=False)\n\n\ndef fort_get_history(message):\n doc = \"\"\"Example:\n/fort get_history\n \"\"\"\n guild = guilds.get(message.chat.id)\n history = guild.get_history_all()\n current_day = dt.datetime.now().date()\n msg = \"*Fort history {}/{}*\\n\".format(current_day.month, current_day.day)\n for p in history:\n msg += \"{} : {}\\n\".format(p.tg_handle, history[p])\n msg += \"\\nIf your name is not here, your recorded count is 0.\"\n return m.MessageReply(msg, temporary=False)\n\n\ndef fort_get_roster(message):\n doc = \"\"\"Example:\n/fort get_roster\n \"\"\"\n guild = guilds.get(message.chat.id)\n roster = guild.fort.get_roster()\n msg = render_fort_roster(roster)\n\n # Todo: escape markdown characters in message\n return m.MessageReply(msg,\n temporary=False,\n # reply_markup=render_fort_roster_markup()\n )\n\n\ndef fort_reassign(message):\n doc = \"\"\"Example:\n/fort reassign\n/fort reassign \n/fort reassign \n\n \"\"\"\n player_in = None\n player_out = None\n parts = message.text.split(' ')\n if len(parts) == 2:\n player_out = message.from_user.username or message.from_user.first_name\n if len(parts) >= 3:\n player_out = parts[2]\n if len(parts) == 4:\n player_in = parts[3]\n if len(parts) > 5:\n raise WrongCommandError(doc)\n return m.MessageReply(\"{} {}\".format(player_in, player_out), temporary=False)\n\n\n@bot.edited_message_handler(commands=['fort'])\n@bot.message_handler(commands=['fort'])\ndef fort(message):\n fort_commands = {\n 'mark': fort_mark,\n 'check': fort_check,\n 'reset_history': fort_reset_history,\n 'get_history': fort_get_history,\n 'get_roster': fort_get_roster,\n # 'reassign': fort_reassign,\n }\n doc = \"\"\"\n/fort command [arguments...]\nAvailable commands are : {}\n \"\"\".format([a for a in fort_commands.keys()])\n handle_command(fort_commands, message, doc)\n\n\n################################\n# Admin Handlers #\n################################\ndef _guild_pin(chat_id):\n guild = guilds.get(chat_id)\n guild_msg = render_guild_admin(guild)\n sent = bot.send_message(guild.chat_id,\n guild_msg,\n parse_mode=\"Markdown\",\n reply_markup=render_poll_markup(guild),\n disable_notification=True).wait()\n\n if type(sent) is tuple:\n if \"blocked\" in sent[1].result.text:\n _guild_stop(chat_id)\n else:\n logging.error(sent[1].result.text)\n else:\n guild.pinned_message_id = sent.message_id\n bot.pin_chat_message(guild.chat_id, guild.pinned_message_id)\n return None\n\n\ndef guild_pin(message):\n return _guild_pin(message.chat.id)\n\n\n@bot.edited_message_handler(commands=['admin'])\n@bot.message_handler(commands=['admin'])\ndef admin(message):\n admin_commands = {\n \"pin\": guild_pin,\n }\n doc = \"\"\"\n/admin command [arguments...]\nAvailable commands are : {}\n \"\"\".format([a for a in admin_commands.keys()])\n handle_command(admin_commands, message, doc)\n\n\ndef _guild_stop(chat_id):\n g = guilds.get(chat_id)\n setattr(g, \"stopped\", True)\n\n\n@bot.message_handler(commands=['stop'])\ndef stop(message):\n try:\n _guild_stop(message.chat.id)\n bot.send_message(message.chat.id, \"Guild bot stopped.\")\n guilds.save()\n except GuildNotFoundError:\n bot.send_message(message.chat.id, \"Guild bot already stopped.\")\n\n\n@bot.message_handler(commands=['start'])\ndef start(message):\n try:\n g = guilds.get(message.chat.id, ignore_stopped=True)\n setattr(g, \"stopped\", False)\n bot.send_message(message.chat.id, \"Guild bot ready.\")\n except GuildNotFoundError:\n guild = m.Guild()\n guilds.set(message.chat.id, guild)\n guild.chat_id = message.chat.id\n guild.title = message.chat.title\n bot.send_message(message.chat.id, \"Guild bot initialized.\")\n finally:\n guilds.save()\n\n\n@bot.message_handler(commands=['reset_guild'])\ndef reset(message):\n guilds.guilds.pop(message.chat.id, None)\n start(message)\n\n\nclass GuildAutomation(object):\n def __init__(self):\n tasks = [\n self.daily_reset,\n self.exped_reminder,\n self.fort_reminder,\n ]\n for task in tasks:\n thread = threading.Thread(target=task, args=())\n thread.daemon = True\n thread.start()\n\n def exped_reminder(self):\n while True:\n now = utils.get_singapore_time_now()\n two_mins = now + dt.timedelta(minutes=2)\n for guild in guilds.values():\n if getattr(guild, \"stopped\", False):\n continue\n for e in guild.expeditions.values():\n if utils.equal_hour_minute(e.get_time(), two_mins) and len(e.members) != 0:\n ready_markup = types.InlineKeyboardMarkup()\n ready_markup.add(\n types.InlineKeyboardButton(\n \"Im ready!\",\n callback_data=\"/exped ready {}\".format(e.title)\n )\n )\n bot.send_message(guild.chat_id,\n render_expedition_reminder(e),\n parse_mode=\"Markdown\",\n reply_markup=ready_markup,\n )\n time.sleep(60)\n\n def daily_reset(self):\n while True:\n now = utils.get_singapore_time_now()\n for guild in guilds.values():\n if getattr(guild, \"stopped\", False):\n continue\n if now.hour == guild.daily_reset_time:\n guild.reset_expeditions()\n guild.update_fort_history()\n _guild_pin(guild.chat_id)\n guilds.save()\n time.sleep(60 * 60)\n\n def fort_reminder(self):\n while True:\n ascent_chat_id = -1001235725395\n guild = guilds.get(ascent_chat_id)\n roster = guild.fort.get_roster()\n now = utils.get_singapore_time_now()\n if now.hour == 20 and now.minute == 55:\n bot.send_message(ascent_chat_id, # hard coded ascent chat id\n \"Fort Reminder:\\n\\n\" + render_fort_roster(roster),\n parse_mode=\"Markdown\",\n )\n time.sleep(60)\n\n\nGuildAutomation()\n\nif __name__ == \"__main__\":\n\n if os.getenv(\"LISTEN_MODE\") == \"webhook\":\n server = Flask(__name__)\n\n @server.route('/' + __token__, methods=['POST'])\n def getMessage():\n bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode(\"utf-8\"))])\n return \"!\", 200\n\n\n @server.route(\"/\")\n def webhook():\n bot.remove_webhook()\n bot.set_webhook(url=\"{}/{}\".format(os.environ.get('WEBHOOK_HOST', 'localhost:5000'), __token__))\n return \"!\", 200\n\n\n server.run(host=\"0.0.0.0\", port=int(os.environ.get('PORT', 5000)))\n\n else:\n bot.remove_webhook()\n bot.polling(none_stop=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":19264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"21869187","text":"from numpy import*\n\nx = array(eval(input(\"Glicose:\")))\n\ni = 0\nsoma = 0\n\nwhile(i < size(x)):\n\tif(x[i]>99):\n\t\tprint(i)\n\t\tsoma = soma + 1\n\ti = i + 1\n\nprint(soma)","sub_path":"5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4137/codes/1758_1185.py","file_name":"1758_1185.py","file_ext":"py","file_size_in_byte":158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"465298801","text":"\n\n#calss header\nclass _SHUTTER():\n\tdef __init__(self,): \n\t\tself.name = \"SHUTTER\"\n\t\tself.definitions = [u'the part of a camera that opens temporarily to allow light to reach the film when a photograph is being taken', u'a wooden cover on the outside of a window that prevents light or heat from going into a room or heat from leaving it: ', u'a metal covering that protects the windows and entrance of a shop from thieves when it is closed']\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/_shutter.py","file_name":"_shutter.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"465222488","text":"import sys\nimport os\nimport templates\n\ndef main(path, logged = False, name = '', output = '', special = ''):\n\tcode = 200\n\n\tif logged == 'True':\n\t\tlogged = True\n\telse:\n\t\tlogged = False\n\n\tif path == '/':\n\t\tbody = \"\"\"\t

    Home

    \n\t\t\n\t\t\"\"\"\n\n\telif path == '/files/':\n\t\tsearchPath = 'files/'\n\t\tdirFiles = os.listdir(searchPath)\n\t\tdirFilesDecoded = ''\n\n\t\tfor direct in dirFiles:\n\t\t\tdirFilesDecoded += direct + '
    '\n\n\t\tbody = '
    Directory {} contains:

    {}'.format(searchPath, dirFilesDecoded)\n\n\telif path == '/sumNumbers/' and logged:\n\t\tbody = \"\"\"\t

    Sum Numbers

    \n\t\t
    \n\t\t\tNumber1
    \n\t\t\tNumber2
    \n\t\t\t\n\t\t
    \n\t\t\"\"\"\n\n\telif path == '/upload/' and logged:\n\t\tbody = \"\"\"\t

    Upload a file

    \n\t\t
    \n\t\t\tFile
    \n\t\t\t\n\t\t
    \n\t\t\"\"\"\n\n\telif path == '/login/' and not logged:\n\t\tbody = \"\"\"

    Log In

    \n\t\t
    \n\t\t\tUsername
    \n\t\t\tPassword
    \n\t\t\t\n\t\t
    \n\t\tDon't have an account? Register now!\n\t\t\"\"\"\n\n\telif path == '/register/' and not logged:\n\t\tbody = \"\"\"

    Register

    \n\t\t
    \n\t\t\tUsername
    \n\t\t\tPassword
    \n\t\t\tRepeat Password
    \n\t\t\tE-mail
    \n\t\t\t\n\t\t
    \n\t\t\"\"\"\n\n\telse:\n\n\t\ttry:\n\t\t\tcode = int(path)\n\t\texcept Exception as e:\n\t\t\tcode = 404\n\n\t\tif code == 400:\n\t\t\tmessage = 'Bad request'\n\t\telif code == 403:\n\t\t\tmessage = 'Wrong Argument'\n\t\telif code == 503:\n\t\t\tmessage = 'Internal Server Error'\n\t\telse:\n\t\t\tmessage = 'Not Found'\n\n\t\tbody = \"

    {} {}

    \".format(code, message)\n\n\tif logged:\n\t\tmenu = templates.menu_logged.format(name)\n\telse:\n\t\tmenu = templates.menu\n\t\t\n\n\tif output != '':\n\t\toutput = '
    {}
    '.format(output)\n\t\treturn templates.http_headers.format(code, 'localhost', 'text/html', special) + templates.start + menu + body + output + templates.end\n\n\telse:\n\t\treturn templates.http_headers.format(code, 'localhost', 'text/html', special) + templates.start + menu + body + templates.end\n\nif __name__ == \"__main__\":\n\tif len(sys.argv) == 6:\n\t\tx = main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])\n\telse:\n\t\tprint (len(sys.argv))\n\t\tprint (\"ERROR: Wrong arguments\")\n\t\tsys.exit(1)\n\n\tprint(x)","sub_path":"web_server/scripts/router.py","file_name":"router.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"264884115","text":"\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\nfrom tkinter import *\r\n\r\ndef test01():\r\n window = tk.Tk()\r\n window.title(\"tkinter\")\r\n window.geometry('600x500')\r\n\r\n var = tk.StringVar()\r\n l = ttk.Label(master=window, textvariable=var,\r\n background=\"red\", font=(\"Aria\", 40), width=20)\r\n l.pack()\r\n\r\n on_hid = False\r\n\r\n def hid_me():\r\n nonlocal on_hid # 函数使用和修改外层的变量 nonlocal 函数使用和修改全局的变 global\r\n if on_hid:\r\n on_hid = False\r\n var.set(\"\")\r\n else:\r\n on_hid = True\r\n var.set(\"hello\\n world\")\r\n\r\n b = ttk.Button(master=window, text=\"隐藏\", width=20, command=hid_me, style=ttk.Style().configure(\"TButton\", padding=5,font=(\"Aria\", 20), relief=\"flat\",background=\"#ccc\"))\r\n\r\n b.pack()\r\n window.mainloop()\r\n\r\n\r\n\r\ndef test02():\r\n window = tk.Tk()\r\n window.title(\"tkinter\")\r\n window.geometry('600x500')\r\n\r\n e=ttk.Entry(window,show=\"*\")\r\n e.pack()\r\n\r\n def insert_point():\r\n var=e.get()\r\n t.insert('insert',var)\r\n\r\n def insert_end():\r\n var=e.get()\r\n t.insert('end',var) \r\n\r\n b = tk.Button(master=window, text=\"point\", width=20, command=insert_point,height=2 )\r\n b.pack()\r\n\r\n b1 = tk.Button(master=window, text=\"end\", width=20, command=insert_end,height=2 )\r\n b1.pack()\r\n t=tk.Text(window,width=20,height=5)\r\n t.pack()\r\n \r\n window.mainloop()\r\n\r\ndef test03():\r\n window = tk.Tk()\r\n window.title(\"tkinter\")\r\n window.geometry('600x500')\r\n var1=tk.StringVar()\r\n l1=tk.Label(window,width=10,height=2,textvariable=var1,font=(\"Aria\", 15),bg='red')\r\n l1.pack()\r\n\r\n def show_select():\r\n show=lbox.get(lbox.curselection())\r\n var1.set(show)\r\n\r\n b=tk.Button(window,text=\"show\",font=(\"Aria\", 15),command=show_select)\r\n b.pack()\r\n\r\n var2=tk.StringVar()\r\n var2.set((11,88,99,51,3))\r\n lbox=tk.Listbox(window,listvariable=var2,font=(\"Aria\", 15))\r\n list_item=['one','two','three']\r\n for item in list_item:\r\n lbox.insert('end',item)\r\n lbox.pack()\r\n window.mainloop()\r\n\r\nif __name__ == '__main__':\r\n # test01()\r\n\r\n # test02()\r\n\r\n # test03()\r\n\r\n\r\n pass\r\n","sub_path":"EngineLearning/__pycache__/tkinterTest.py","file_name":"tkinterTest.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"410460858","text":"import random\nfrom enum import Enum\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport attr\n\nfrom core_draft.booster import Booster\nfrom core_draft.cog_exceptions import UserFeedbackException\nfrom core_draft.draft_player import DraftPlayer\n\nDraftEffect = Enum('DraftEffect', 'no_immediate_effect add_booster_to_draft')\nStage = Enum('Stage', 'draft_registration draft_in_progress draft_complete')\n\nplayer_card_drafteffect = Tuple[DraftPlayer, str, DraftEffect]\n\nCARDS_WITH_FUNCTION = {\"Cogwork Librarian\", \"Leovold's Operative\"}\n\n@attr.s(auto_attribs=True)\nclass PickReturn():\n updates: Dict[DraftPlayer, List[str]]\n draft_effect: List[player_card_drafteffect]\n\n@attr.s(auto_attribs=True)\nclass Draft:\n \"\"\"\n The internals of a draft. This represents the abstract state of the draft.\n This is where all the logic of a Booster Draft happens.\n \"\"\"\n players: List[int]\n cards: List[str]\n _state: List[DraftPlayer] = attr.ib(factory=list)\n _opened_packs: int = 0\n number_of_packs: int = 3\n cards_per_booster: int = 15\n metadata: dict[str, Any] = attr.ib(factory=dict)\n stage: Stage = Stage.draft_registration\n spare_cards: int = 0 # number of cards left in the cube after allocating boosters\n\n def player_by_id(self, player_id: int) -> DraftPlayer:\n state = self._state[self.players.index(player_id)]\n if (state.id != player_id):\n raise KeyError(f\"Player {player_id} not found, found {state.id} instead\")\n return state\n\n def pack_of(self, player_id: int) -> Optional[Booster]:\n try:\n return self.player_by_id(player_id).current_pack\n except IndexError:\n return None\n\n def deck_of(self, player_id: int) -> List[str]:\n return self.player_by_id(player_id).deck\n\n def start(self, number_of_packs: int, cards_per_booster: int) -> List[DraftPlayer]:\n used_cards = number_of_packs * cards_per_booster * len(self.players)\n self.spare_cards = len(self.cards) - used_cards\n if self.spare_cards < 0:\n raise UserFeedbackException(f\"Not enough cards {len(self.cards)} for {len(self.players)} with {number_of_packs} of {cards_per_booster}\")\n self.number_of_packs = number_of_packs\n self.cards_per_booster = cards_per_booster\n random.shuffle(self.players)\n random.shuffle(self.cards)\n for i, player in enumerate(self.players):\n db = DraftPlayer(player, i)\n if player < 100:\n db.draftbot = True\n self._state.append(db)\n self.open_boosters_for_all_players()\n return self._state # return all players to update\n\n def open_booster(self, player: DraftPlayer, number: int) -> Booster:\n card_list = [self.cards.pop() for _ in range(0, self.cards_per_booster)]\n booster = Booster(card_list, number)\n player.push_pack(booster, True)\n return booster\n\n def open_boosters_for_all_players(self) -> None:\n self._opened_packs += 1\n for player in self._state:\n self.open_booster(player, self._opened_packs)\n print(\"Opening pack for all players\")\n\n def get_pending_players(self) -> List[DraftPlayer]:\n return [x for x in self._state if x.has_current_pack()]\n\n def is_draft_finished(self) -> bool:\n return (self.is_pack_finished() and (self._opened_packs >= self.number_of_packs)) or self.stage == Stage.draft_complete\n\n def is_pack_finished(self) -> bool:\n return len(self.get_pending_players()) == 0\n\n def pick(self, player_id: int, position: int) -> PickReturn:\n player = self.player_by_id(player_id)\n pack = player.pick(position)\n if pack is None:\n return PickReturn({}, [])\n\n users_to_update: List[DraftPlayer] = []\n\n pick = player.last_pick()\n print(f\"Player {player_id} picked {pick}\")\n\n pick_effects = []\n effect = self.check_if_draft_matters(player, pack)\n if effect:\n player.face_up.append(pick)\n pick_effects.append(effect)\n\n # push to next player\n if not was_last_pick_of_pack(pack):\n next_player_id = self.get_next_player(player, pack)\n next_player = self.player_by_id(next_player_id)\n has_new_pack = next_player.push_pack(pack)\n if has_new_pack:\n users_to_update.append(next_player)\n\n if player.has_current_pack() and player not in users_to_update:\n users_to_update.append(player)\n\n result: Dict[DraftPlayer, List[str]] = {}\n new_booster = False\n for player in users_to_update:\n result[player] = []\n if player.has_one_card_in_current_pack():\n new_booster, effect = self.autopick(player)\n if effect:\n player.face_up.append(player.last_pick())\n pick_effects.append(effect)\n result[player].append(player.last_pick())\n\n if new_booster:\n for player in self._state:\n if player not in users_to_update:\n result[player] = []\n\n return PickReturn(result, pick_effects)\n\n def check_if_draft_matters(self, player: DraftPlayer, pack: Booster) -> Optional[player_card_drafteffect]:\n pick = player.last_pick()\n if pick == 'Lore Seeker': # Reveal Lore Seeker as you draft it. After you draft Lore Seeker, you may add a booster pack to the draft\n if self.spare_cards < self.cards_per_booster:\n # Don't add a booster if we don't have enough cards\n # revisit this when we have support for generating magic boosters\n return None\n self.spare_cards -= self.cards_per_booster\n self.open_booster(player, pack.number)\n return (player, pick, DraftEffect.add_booster_to_draft)\n if pick in ['Cogwork Librarian', \"Leovold's Operative\"]: # Swap me into a later booster!\n return (player, pick, DraftEffect.no_immediate_effect)\n\n return None\n\n def autopick(self, player: DraftPlayer) -> Tuple[bool, Optional[player_card_drafteffect]]:\n if player.has_one_card_in_current_pack():\n pack = player.autopick()\n if not pack:\n return False, None\n pick_effect = self.check_if_draft_matters(player, pack)\n nextbooster = False\n if self.is_pack_finished() and not self.is_draft_finished():\n self.open_boosters_for_all_players()\n nextbooster = True\n return nextbooster, pick_effect\n return False, None\n\n def get_next_player(self, player: DraftPlayer, pack: Booster) -> int:\n i = player.seat\n if pack.number % 2 == 1:\n return self.players[(i + 1) % len(self.players)]\n return self.players[i - 1]\n\ndef was_last_pick_of_pack(pack: Booster) -> bool:\n return pack.is_empty()\n","sub_path":"core_draft/draft.py","file_name":"draft.py","file_ext":"py","file_size_in_byte":6941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"17"} +{"seq_id":"71026201","text":"from urllib.request import urlopen\r\nimport re\r\n\r\n\r\nurl = \"http://www.naver.com\"\r\ns = urlopen(url).read().decode('utf-8')\r\ns = re.findall(r'', s, re.DOTALL)[0]\r\noptions = re.findall(r'