diff --git "a/1676.jsonl" "b/1676.jsonl" new file mode 100644--- /dev/null +++ "b/1676.jsonl" @@ -0,0 +1,663 @@ +{"seq_id":"330908222","text":"# coding: utf-8\n\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport unidecode\n\n\nponct_liste = ['.',',','!','?',';',':']\nmidi_liste = [\"midi\",\"dejeuner\",\"déjeuner\",\"dejeune\"]\ncafete_liste = [\"cafet\",\"cafeteriat\",\"cafetariat\",\"bar\",\"cafet\"]\nhoraire_liste = [\"horaire\",\"horaires\"]\n\n#DOWNLOAD MENU\ndef download_menu():\n req = urllib.request.Request('http://services.telecom-bretagne.eu/rak/')\n the_page = urllib.request.urlopen(req)\n page = the_page.read()\n soup = BeautifulSoup(page, 'html.parser')\n plats = soup.find_all(\"td\", attrs={\"class\" : \"col-md-4\"})\n nom_plats = soup.find_all(\"td\", attrs={\"align\" : \"left\"})\n result = []\n premier_plat=0\n for i in range(len(plats)):\n a = str(plats[i].getText())\n b = str(nom_plats[i].getText())\n result.append([a[1:-1],b[2:-2]])\n if b[2:-2]==\"Plat 1\":\n if premier_plat==1:\n index = i\n else:\n premier_plat+=1\n return result,index\n\n\n\n# BOITE A OUTILS\ndef depaquetage(sender,paquet,me,ponct_liste):\n if sender == me : # C'est un ack\n print('Reponse bien envoyee')\n return ['ack_msg']\n else : # Tous les messages que je reçois\n messaging = paquet['entry'][0]['messaging'][0]\n if 'message' in messaging.keys() :\n message = paquet['entry'][0]['messaging'][0]['message']\n if 'text' in message.keys():\n texte = message['text'] # Ce qu on nous a envoyé\n texte_notponct = extract_ponct(texte) # On retire la ponctuation\n mots_du_msg = texte_notponct.split(' ') # Nous séparons les mots\n return ['text_msg', texte, mots_du_msg]\n elif 'attachments' in message.keys():\n if message['attachments'][0]['type']=='location':\n location = message['attachments'][0]['payload']['coordinates']\n latitude = location['lat']\n longitude = location['long']\n return ['location_msg', latitude, longitude]\n elif message['attachments'][0]['type']=='image':\n return ['image_msg']\n else : \n print(paquet)\n print('message avec attachment inconnu!') \n elif ('attachments'in message.keys()) and ('text' in paquet['entry'][0]['messaging'][0]['message'].keys()):\n print('Rien à répondre / attachment et text présent')\n return ['unknow_msg']\n elif 'postback' in messaging.keys() :\n postback = messaging['postback']['payload']\n return ['postback_msg' , postback]\n elif 'delivery' in messaging.keys() :\n return ['delivery_msg']\n elif 'read' in messaging.keys() :\n return ['read_msg']\n else : \n print('Non identifié')\n print(paquet)\n return ['unknow_msg'] ## PAS UTILISE ENCORE\n\n\ndef similitudes (a,b):\n return list(set(a).intersection(b))\n\ndef extract_ponct(texte):\n texte = unidecode.unidecode(texte).lower()\n return texte\n\ndef build_choix():\n choix_dict = {}\n list_menu = [\"Menu midi\", \"Menu soir\", \"Menu cafet\", \"Horaires\", \"Partager\"]\n i=0\n for item in list_menu:\n choix_dict[i] = item\n i+=1\n return choix_dict\n\ndef construct_text(menu,mots_du_msg, index):\n texte = ''\n if (\"menu\" in mots_du_msg):\n if (similitudes(midi_liste, mots_du_msg) != []):\n texte = \"Menu du midi :\" + '\\n\\n'\n for i in range(index):\n texte = texte + menu[i][1] + \" : \" + menu[i][0] + '\\n\\n'\n elif (\"soir\" in mots_du_msg):\n texte = \"Menu du soir :\" + '\\n\\n'\n for i in range(index, len(menu) - 6):\n texte = texte + menu[i][1] + \" : \" + menu[i][0] + '\\n\\n'\n elif similitudes(cafete_liste, mots_du_msg) != []:\n texte = \"Menu de la cafet :\" + '\\n' + '\\n' + \\\n menu[len(menu) - 6][1] + \" : \" + \\\n menu[len(menu) - 6][0] + '\\n\\n' + \\\n menu[len(menu) - 5][1] + \" : \" + \\\n menu[len(menu) - 5][0] + '\\n\\n' + \\\n menu[len(menu) - 4][1] + \" : \" + \\\n menu[len(menu) - 4][0] + '\\n\\n' + \\\n menu[len(menu) - 3][1] + \" : \" + \\\n menu[len(menu) - 3][0] + '\\n\\n' + \\\n menu[len(menu) - 2][1] + \" : \" + \\\n menu[len(menu) - 2][0] + '\\n\\n' + \\\n menu[len(menu) - 1][1] + \" : \" + \\\n menu[len(menu) - 1][0]\n else:\n if similitudes(horaire_liste, mots_du_msg) != []:\n texte = \"RAK :\\nLundi au vendredi \\n\" \\\n \"11h30 - 13h15\\n19h15 - 20h00\\n\\n\" \\\n \"Samedi - Dimanche - Jours feries \\n\" \\\n \"12h15 - 13h\\n19h15 - 20h00\\n\\n\" \\\n \"Vacances scolaires \\n11h45 - 13h\" \\\n \"\\n19h30 - 20h\\n\\n\" \\\n \"BAR :\\nLundi au vendredi\" \\\n \" \\n7h30 - 16h45\"\n elif (\"partager\" in mots_du_msg):\n texte = \"partager\"\n elif (\"menu\" in mots_du_msg):\n texte = \"Tu veux quel type de menu ? Appuie sur les boutons ci dessous\"\n else:\n texte = \"Je suis là que pour donner le menu ne m'en demandes pas trop! 😉\"\n\n return texte\n\n\n","sub_path":"toolkit.py","file_name":"toolkit.py","file_ext":"py","file_size_in_byte":5464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"638204863","text":"\"\"\"Knowledge in learning, Chapter 19\"\"\"\n\nfrom random import shuffle\nfrom utils import powerset\nfrom collections import defaultdict\nfrom itertools import combinations\n\n# ______________________________________________________________________________\n\n\ndef current_best_learning(examples, h, examples_so_far=[]):\n \"\"\" [Figure 19.2]\n The hypothesis is a list of dictionaries, with each dictionary representing\n a disjunction.\"\"\"\n if not examples:\n return h\n\n e = examples[0]\n if is_consistent(e, h):\n return current_best_learning(examples[1:], h, examples_so_far + [e])\n elif false_positive(e, h):\n for h2 in specializations(examples_so_far + [e], h):\n h3 = current_best_learning(examples[1:], h2, examples_so_far + [e])\n if h3 != 'FAIL':\n return h3\n elif false_negative(e, h):\n for h2 in generalizations(examples_so_far + [e], h):\n h3 = current_best_learning(examples[1:], h2, examples_so_far + [e])\n if h3 != 'FAIL':\n return h3\n\n return 'FAIL'\n\n\ndef specializations(examples_so_far, h):\n \"\"\"Specialize the hypothesis by adding AND operations to the disjunctions\"\"\"\n hypotheses = []\n\n for i, disj in enumerate(h):\n for e in examples_so_far:\n for k, v in e.items():\n if k in disj or k == 'GOAL':\n continue\n\n h2 = h[i].copy()\n h2[k] = '!' + v\n h3 = h.copy()\n h3[i] = h2\n if check_all_consistency(examples_so_far, h3):\n hypotheses.append(h3)\n\n shuffle(hypotheses)\n return hypotheses\n\n\ndef generalizations(examples_so_far, h):\n \"\"\"Generalize the hypothesis. First delete operations\n (including disjunctions) from the hypothesis. Then, add OR operations.\"\"\"\n hypotheses = []\n\n # Delete disjunctions\n disj_powerset = powerset(range(len(h)))\n for disjs in disj_powerset:\n h2 = h.copy()\n for d in reversed(list(disjs)):\n del h2[d]\n\n if check_all_consistency(examples_so_far, h2):\n hypotheses += h2\n\n # Delete AND operations in disjunctions\n for i, disj in enumerate(h):\n a_powerset = powerset(disj.keys())\n for attrs in a_powerset:\n h2 = h[i].copy()\n for a in attrs:\n del h2[a]\n\n if check_all_consistency(examples_so_far, [h2]):\n h3 = h.copy()\n h3[i] = h2.copy()\n hypotheses += h3\n\n # Add OR operations\n if hypotheses == [] or hypotheses == [{}]:\n hypotheses = add_or(examples_so_far, h)\n else:\n hypotheses.extend(add_or(examples_so_far, h))\n\n shuffle(hypotheses)\n return hypotheses\n\n\ndef add_or(examples_so_far, h):\n \"\"\"Adds an OR operation to the hypothesis. The AND operations in the disjunction\n are generated by the last example (which is the problematic one).\"\"\"\n ors = []\n e = examples_so_far[-1]\n\n attrs = {k: v for k, v in e.items() if k != 'GOAL'}\n a_powerset = powerset(attrs.keys())\n\n for c in a_powerset:\n h2 = {}\n for k in c:\n h2[k] = attrs[k]\n\n if check_negative_consistency(examples_so_far, h2):\n h3 = h.copy()\n h3.append(h2)\n ors.append(h3)\n\n return ors\n\n# ______________________________________________________________________________\n\n\ndef version_space_learning(examples):\n \"\"\" [Figure 19.3]\n The version space is a list of hypotheses, which in turn are a list\n of dictionaries/disjunctions.\"\"\"\n V = all_hypotheses(examples)\n for e in examples:\n if V:\n V = version_space_update(V, e)\n\n return V\n\n\ndef version_space_update(V, e):\n return [h for h in V if is_consistent(e, h)]\n\n\ndef all_hypotheses(examples):\n \"\"\"Builds a list of all the possible hypotheses\"\"\"\n values = values_table(examples)\n h_powerset = powerset(values.keys())\n hypotheses = []\n for s in h_powerset:\n hypotheses.extend(build_attr_combinations(s, values))\n\n hypotheses.extend(build_h_combinations(hypotheses))\n\n return hypotheses\n\n\ndef values_table(examples):\n \"\"\"Builds a table with all the possible values for each attribute.\n Returns a dictionary with keys the attribute names and values a list\n with the possible values for the corresponding attribute.\"\"\"\n values = defaultdict(lambda: [])\n for e in examples:\n for k, v in e.items():\n if k == 'GOAL':\n continue\n\n mod = '!'\n if e['GOAL']:\n mod = ''\n\n if mod + v not in values[k]:\n values[k].append(mod + v)\n\n values = dict(values)\n return values\n\n\ndef build_attr_combinations(s, values):\n \"\"\"Given a set of attributes, builds all the combinations of values.\n If the set holds more than one attribute, recursively builds the\n combinations.\"\"\"\n if len(s) == 1:\n # s holds just one attribute, return its list of values\n k = values[s[0]]\n h = [[{s[0]: v}] for v in values[s[0]]]\n return h\n\n h = []\n for i, a in enumerate(s):\n rest = build_attr_combinations(s[i+1:], values)\n for v in values[a]:\n o = {a: v}\n for r in rest:\n t = o.copy()\n for d in r:\n t.update(d)\n h.append([t])\n\n return h\n\n\ndef build_h_combinations(hypotheses):\n \"\"\"Given a set of hypotheses, builds and returns all the combinations of the\n hypotheses.\"\"\"\n h = []\n h_powerset = powerset(range(len(hypotheses)))\n\n for s in h_powerset:\n t = []\n for i in s:\n t.extend(hypotheses[i])\n h.append(t)\n\n return h\n\n# ______________________________________________________________________________\n\n\ndef minimal_consistent_det(E, A):\n \"\"\"Returns a minimal set of attributes which give consistent determination\"\"\"\n n = len(A)\n\n for i in range(n + 1):\n for A_i in combinations(A, i):\n if consistent_det(A_i, E):\n return set(A_i)\n\n\ndef consistent_det(A, E):\n \"\"\"Checks if the attributes(A) is consistent with the examples(E)\"\"\"\n H = {}\n\n for e in E:\n attr_values = tuple(e[attr] for attr in A)\n if attr_values in H and H[attr_values] != e['GOAL']:\n return False\n H[attr_values] = e['GOAL']\n\n return True\n\n# ______________________________________________________________________________\n\n\ndef check_all_consistency(examples, h):\n \"\"\"Check for the consistency of all examples under h\"\"\"\n for e in examples:\n if not is_consistent(e, h):\n return False\n\n return True\n\n\ndef check_negative_consistency(examples, h):\n \"\"\"Check if the negative examples are consistent under h\"\"\"\n for e in examples:\n if e['GOAL']:\n continue\n\n if not is_consistent(e, [h]):\n return False\n\n return True\n\n\ndef disjunction_value(e, d):\n \"\"\"The value of example e under disjunction d\"\"\"\n for k, v in d.items():\n if v[0] == '!':\n # v is a NOT expression\n # e[k], thus, should not be equal to v\n if e[k] == v[1:]:\n return False\n elif e[k] != v:\n return False\n\n return True\n\n\ndef guess_value(e, h):\n \"\"\"Guess value of example e under hypothesis h\"\"\"\n for d in h:\n if disjunction_value(e, d):\n return True\n\n return False\n\n\ndef is_consistent(e, h):\n return e[\"GOAL\"] == guess_value(e, h)\n\n\ndef false_positive(e, h):\n if e[\"GOAL\"] == False:\n if guess_value(e, h):\n return True\n\n return False\n\n\ndef false_negative(e, h):\n if e[\"GOAL\"] == True:\n if not guess_value(e, h):\n return True\n\n return False\n","sub_path":"knowledge.py","file_name":"knowledge.py","file_ext":"py","file_size_in_byte":7822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"250427181","text":"import simpy\nimport functools\nimport random as np\nimport time\nfrom enum import Enum\nimport numpy\nfrom scipy.stats import norm\nimport matplotlib.pyplot as plt\n#import batch_teste as lp\nimport static_relaxILP as plp\nimport relaxation_module as rlx\nimport relaxedMainModule as rm\nimport copy\nimport sys\nimport pdb#debugging module\nimport importlib#to reload modules\n#import relaxAlgs as ra\n\n#initial number of RRHs\nminimum_rrhs = 5\nnumber_of_rrhs = 5\n#increment of each run\nrrhs_increment = 5\n#number of executions\nexec_number = 2\n#down time of live migration\nlm_downtime = 1.5\n#array of RRHs to be solved\nrrhs_array = []\nfor i in range(42):\n\trrhs_array.append(i)\namount_exec = 5\n\n#metrics for the average calculation of the static case\npower_static = []\nexecution_static = []\nredirected_static = []\nactivated_nodes_static = []\nactivated_lambdas_static = []\nactivated_dus_static = []\nactivated_switches_static = []\ncloud_use_static = []\nfog_use_static = []\nusage_lambda = []\nusage_du = []\n\n#metrics\npower = []\nredirected = []\nexternal_migrations = 0\nmigrations = []\ntotal_vm_migrations_time = {}\ntotal_down_time = {}\nlambda_usage = []\nproc_usage = []\nexecution_time = []\nactivated_nodes = []\nactivated_lambdas = []\nactivated_dus = []\nactivated_switchs = []\ncloud_use = []\nfog_use = []\nact_cloud = 0\nact_fog = 0\n#util class\nutil = plp.Util()\n\n#log the results\ndef logResults(dest_file):\n\twith open(dest_file,'w') as filehandle: \n\t\tfilehandle.write(\"Power\\n\\n\")\n\t\tfilehandle.writelines(\"%s\\n\" % p for p in average_batch_power)\n\t\tfilehandle.write(\"\\n\")\n\t\tfilehandle.write(\"Redirected\\n\\n\")\n\t\tfilehandle.writelines(\"%s\\n\" % p for p in average_redirected)\n\t\tfilehandle.write(\"\\n\") \n\t\tfilehandle.write(\"Activated nodes\\n\\n\")\n\t\tfilehandle.writelines(\"%s\\n\" % p for p in average_act_nodes)\n\t\tfilehandle.write(\"\\n\")\n\t\tfilehandle.write(\"Activated lambdas\\n\\n\")\n\t\tfilehandle.writelines(\"%s\\n\" % p for p in average_act_lambdas)\n\t\tfilehandle.write(\"\\n\")\n\t\tfilehandle.write(\"Activated dus\\n\\n\")\n\t\tfilehandle.writelines(\"%s\\n\" % p for p in average_act_dus)\n\t\tfilehandle.write(\"\\n\")\n\t\tfilehandle.write(\"Activated switches\\n\\n\")\n\t\tfilehandle.writelines(\"%s\\n\" % p for p in average_act_switches)\n\t\tfilehandle.write(\"\\n\")\n\t\tfilehandle.write(\"Cloud use\\n\\n\")\n\t\tfilehandle.writelines(\"%s\\n\" % p for p in average_cloud_use)\n\t\tfilehandle.write(\"\\n\")\n\t\tfilehandle.write(\"Fog use\\n\\n\")\n\t\tfilehandle.writelines(\"%s\\n\" % p for p in average_fog_use)\n\t\tfilehandle.write(\"\\n\")\n\t\tfilehandle.write(\"Lamba usage\\n\\n\")\n\t\tfilehandle.writelines(\"%s\\n\" % p for p in average_lambda_usage)\n\t\tfilehandle.write(\"\\n\")\n\t\tfilehandle.write(\"VDUs usage\\n\\n\")\n\t\tfilehandle.writelines(\"%s\\n\" % p for p in average_du_usage)\n\t\tfilehandle.write(\"\\n\")\n\ndef countNodes(ilp):\n\tglobal act_cloud, act_fog\n\tfor i in range(len(ilp.nodeState)):\n\t\tif ilp.nodeState[i] == 1:\n\t\t\tif i == 0:\n\t\t\t\tact_cloud += 1\n\t\t\telse:\n\t\t\t\tact_fog += 1\n\n#calculate the usage of each processing node\ndef getProcUsage(ilp):\n\ttotal_dus_capacity = sum(sim.dus_capacity)\n\tdu_usage = 0\n\t#counts the active DUs\n\tfor i in range(len(ilp.du_state)):\n\t\tdu_usage += sum(ilp.du_state[i])#*sim.dus_capacity[i]\n\t#print(\"Active DUs {}\".format(plp.du_state))\n\t#print(\"Processing Usage {}\".format(du_usage))\n\treturn du_usage/total_dus_capacity\n\n#count external migration for only batch case - this method considers each vBBU migrated to account\ndef extSingleMigrations(ilp_module, copy_state, run):\n\tglobal external_migrations\n\texternal_migrations = 0\n\tmigrating_vpons = 10000\n\tfor i in ilp_module.nodes:\n\t\tprint(i)\n\t\t#print(copy_state[i])\n\t\t#print(ilp_module.rrhs_on_nodes[i])\n\t\tif copy_state[i] > ilp_module.rrhs_on_nodes[i] and copy_state[0] < ilp_module.rrhs_on_nodes[0]:\n\t\t\t#print(copy_state[i])\n\t\t\t#print(ilp_module.rrhs_on_nodes[i])\n\t\t\tdiff = copy_state[i] - ilp_module.rrhs_on_nodes[i]\n\t\t\ttotal_down_time[run].append(diff*lm_downtime)\n\t\t\texternal_migrations += diff\n\t\t\ttotal_vm_migrations_time[run].append((diff*614.4)/migrating_vpons)\n\t\t\t#print(\"paaa\", diff)\n\t\t\t#print(total_down_time)\n\tmigrations.append(external_migrations)\n\nnetwork_copy = None\ncloud_before = []\ncloud_after = []\nnodes_before = {}\nnodes_after = {}\n#for i in plp.nodes:\n#\tnodes_before[i] = []\n#\tnodes_after[i] = []\ncount = 1\n\n#set the maximum load for a simulated scenario given the vdus capacity and the lambdas\ndef setMaximumLoad(cloud_vdu, fog_vdu, number_of_fogs, number_of_lambdas):\n\ttotal_fog = fog_vdu*number_of_lambdas*number_of_fogs\n\ttotal_vdus_load = total_fog+(cloud_vdu*number_of_lambdas)\n\treturn total_vdus_load\n\n#keep results of each iteration\npwr = []\nredir = []\nexec_t = []\nc_nodes = []\nc_lambdas = []\nc_dus = []\nc_switches = []\nl_usage = []\nd_usage = []\na_cloud = []\na_fog = []\n\n#post processing method\npostProcessingHeuristic = \"mostProbability\"\n#post processing heuristic\nrelaxHeuristic = \"firstFitVPON\"\n#number of repetitions of the relaxation\nrelax_amount = 2\n\n\n\n\nlogResults('/home/tinini/Área de Trabalho/logsTeseILP/relaxStatic/outputs.txt')\n\n","sub_path":"main_simulators/relaxations/staticRelax/staticRelax.py","file_name":"staticRelax.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"381306202","text":"from tests.integration.testcase import api, TestCase\nfrom tests.integration import random_email, random_string\n\n\nclass TestCards(TestCase):\n def test_create(self):\n customer = api.customers.create({\n 'email': random_email()\n })\n cardholder_name = random_string()\n card = api.cards.create(customer['id'], {\n 'number': '4242424242424242',\n 'expMonth': '12',\n 'expYear': '2020',\n 'cvc': '123',\n 'cardholderName': cardholder_name\n })\n card = api.cards.get(card['customerId'], card['id'])\n self.assertEqual(card['last4'], '4242')\n self.assertEqual(card['expMonth'], '12')\n self.assertEqual(card['expYear'], '2020')\n self.assertEqual(card['cardholderName'], cardholder_name)\n","sub_path":"tests/integration/test_cards.py","file_name":"test_cards.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"289721037","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\nimport pygame, random, Jefe\r\nfrom pygame.locals import *\r\n\r\nROJO=[255,0,0]\r\nAZUL=[0,0,255]\r\nVERDE=[0,255,0]\r\nAMARILLO=[255,255,0]\r\nGRIS=[128,128,128]\r\nNEGRO=[0,0,0]\r\nAlto=600\r\nAncho=800\r\npygame.init()\r\nreloj = pygame.time.Clock()\r\n\r\nFontrans=pygame.image.load(\"imagenes/01.jpg\")\r\nFontrans1=pygame.image.load(\"imagenes/11.jpg\")\r\nFontrans2=pygame.image.load(\"imagenes/3.jpg\")\r\nFontrans3=pygame.image.load(\"imagenes/nube.jpg\")\r\nFontrans4=pygame.image.load(\"imagenes/nuv.png\")\r\n\r\n\r\nclass Jugador(pygame.sprite.Sprite):\r\n velx=0\r\n vely=0\r\n sprite=0\r\n spritej=0\r\n\r\n nivel=None\r\n\r\n def __init__(self):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.stand = pygame.image.load(\"imagenes/guystatic.png\")\r\n self.run = pygame.image.load(\"imagenes/guyrun1.png\")\r\n self.run2 = pygame.image.load(\"imagenes/guyrun2.png\")\r\n self.run3 = pygame.image.load(\"imagenes/guyrun3.png\")\r\n self.run4 = pygame.image.load(\"imagenes/guyrun4.png\")\r\n self.run5 = pygame.image.load(\"imagenes/guyrun5.png\")\r\n self.run6 = pygame.image.load(\"imagenes/guyrun6.png\")\r\n self.run7 = pygame.image.load(\"imagenes/guyrun7.png\")\r\n self.run8 = pygame.image.load(\"imagenes/guyrun8.png\")\r\n self.run9 = pygame.image.load(\"imagenes/guyrun9.png\")\r\n self.jump = pygame.image.load(\"imagenes/guyjump1.png\")\r\n self.jump2 = pygame.image.load(\"imagenes/guyjump2.png\")\r\n self.jump3 = pygame.image.load(\"imagenes/guyjump3.png\")\r\n self.jump4 = pygame.image.load(\"imagenes/guyjump4.png\")\r\n self.standi = pygame.image.load(\"imagenes/guystatici.png\")\r\n self.runi = pygame.image.load(\"imagenes/guyrun1i.png\")\r\n self.run2i = pygame.image.load(\"imagenes/guyrun2i.png\")\r\n self.run3i = pygame.image.load(\"imagenes/guyrun3i.png\")\r\n self.run4i = pygame.image.load(\"imagenes/guyrun4i.png\")\r\n self.run5i = pygame.image.load(\"imagenes/guyrun5i.png\")\r\n self.run6i = pygame.image.load(\"imagenes/guyrun6i.png\")\r\n self.run7i = pygame.image.load(\"imagenes/guyrun7i.png\")\r\n self.run8i = pygame.image.load(\"imagenes/guyrun8i.png\")\r\n self.run9i = pygame.image.load(\"imagenes/guyrun9i.png\")\r\n self.jumpi = pygame.image.load(\"imagenes/guyjump1i.png\")\r\n self.jump2i = pygame.image.load(\"imagenes/guyjump2i.png\")\r\n self.jump3i = pygame.image.load(\"imagenes/guyjump3i.png\")\r\n self.jump4i = pygame.image.load(\"imagenes/guyjump4i.png\")\r\n self.fire = pygame.image.load(\"imagenes/guyfiring.png\")\r\n self.firei = pygame.image.load(\"imagenes/guyfiringi.png\")\r\n self.jumpfire = pygame.image.load(\"imagenes/guyjumpfiring.png\")\r\n self.jumpfirei = pygame.image.load(\"imagenes/guyjumpfiringi.png\")\r\n self.firebfg = pygame.image.load(\"imagenes/guyfiringbfg.png\")\r\n self.fireibfg = pygame.image.load(\"imagenes/guyfiringbfgi.png\")\r\n self.jumpfirebfg= pygame.image.load(\"imagenes/guyjumpfiringbfg.png\")\r\n self.jumpfireibfg= pygame.image.load(\"imagenes/guyjumpfiringbfgi.png\")\r\n \r\n self.first = [self.stand, self.run, self.run2, self.run3,\r\n self.run4, self.run5, self.run6, self.run7,\r\n self.run8, self.run9, self.jump, self.jump2,\r\n self.jump3, self.jump4, self.standi, self.runi,\r\n self.run2i, self.run3i, self.run4i, self.run5i,\r\n self.run6i, self.run7i, self.run8i, self.run9i,\r\n self.jumpi, self.jump2i, self.jump3i, self.jump4i,\r\n self.fire, self.firei, self.jumpfire, self.jumpfirei,\r\n self.firebfg, self.fireibfg, self.jumpfirebfg, self.jumpfireibfg]\r\n #0,14: Stand. 1-9,15-23: Walk. 10-13, 24-27: Jump.\r\n #28,29: Firing(Plasma). 30,31: Firing while jumping(Plasma).\r\n #32,33: Firing(BFG). 34,35: Firing while jumping(BFG).\r\n self.image = self.first[0]\r\n self.rect = self.image.get_rect()\r\n self.dir = 0\r\n self.isjump = 0\r\n self.isfiring = 0\r\n self.bullets = 70\r\n self.isrun = 0\r\n self.vidas = 70\r\n\r\n def update(self):\r\n\r\n self.calc_grav()\r\n\r\n self.rect.x+=self.velx\r\n\r\n bloque_col_list=pygame.sprite.spritecollide(self,self.nivel.plataforma_lista,False)\r\n for bloque in bloque_col_list:\r\n \r\n if self.velx>0:\r\n self.rect.right=bloque.rect.left\r\n elif self.velx<0:\r\n self.rect.left=bloque.rect.right\r\n\r\n self.rect.y+=self.vely\r\n\r\n bloque_col_list=pygame.sprite.spritecollide(self,self.nivel.plataforma_lista,False)\r\n for bloque in bloque_col_list:\r\n if self.vely>0:\r\n self.rect.bottom=bloque.rect.top\r\n \r\n elif self.vely<0:\r\n self.rect.top=bloque.rect.bottom\r\n\r\n self.vely=0\r\n self.isjump=0\r\n\r\n def calc_grav(self):\r\n if self.vely==0:\r\n self.vely=1\r\n if self.isfiring==0:\r\n if self.isrun==0:\r\n if self.dir==0:\r\n self.image=self.first[0]\r\n sprite=0\r\n spritej=0\r\n elif self.dir==1:\r\n self.image=self.first[14]\r\n sprite=0\r\n spritej=0\r\n elif self.isrun==1:\r\n if self.dir==0:\r\n if self.sprite==0:\r\n pygame.time.delay(10)\r\n self.image=self.first[1]\r\n self.sprite=1\r\n elif self.sprite==1:\r\n pygame.time.delay(10)\r\n self.image=self.first[2]\r\n self.sprite=2\r\n elif self.sprite==2:\r\n self.image=self.first[3]\r\n self.sprite=3\r\n elif self.sprite==3:\r\n self.image=self.first[4]\r\n self.sprite=4\r\n elif self.sprite==4:\r\n self.image=self.first[5]\r\n self.sprite=5\r\n elif self.sprite==5:\r\n self.image=self.first[6]\r\n self.sprite=6\r\n elif self.sprite==6:\r\n self.image=self.first[7]\r\n self.sprite=7\r\n elif self.sprite==7:\r\n self.image=self.first[8]\r\n self.sprite=8\r\n elif self.sprite==8:\r\n self.image=self.first[9]\r\n self.sprite=0\r\n elif self.dir==1:\r\n if self.sprite==0:\r\n self.image=self.first[15]\r\n self.sprite=1\r\n elif self.sprite==1:\r\n self.image=self.first[16]\r\n self.sprite=2\r\n elif self.sprite==2:\r\n self.image=self.first[17]\r\n self.sprite=3\r\n elif self.sprite==3:\r\n self.image=self.first[18]\r\n self.sprite=4\r\n elif self.sprite==4:\r\n self.image=self.first[19]\r\n self.sprite=5\r\n elif self.sprite==5:\r\n self.image=self.first[20]\r\n self.sprite=6\r\n elif self.sprite==6:\r\n self.image=self.first[21]\r\n self.sprite=7\r\n elif self.sprite==7:\r\n self.image=self.first[22]\r\n self.sprite=8\r\n elif self.sprite==8:\r\n self.image=self.first[23]\r\n self.sprite=0\r\n elif self.isfiring==1:\r\n if self.dir==0:\r\n self.image=self.first[28]\r\n else:\r\n self.image=self.first[29]\r\n else:\r\n if self.dir==0:\r\n self.image=self.first[32]\r\n else:\r\n self.image=self.first[33]\r\n else:\r\n self.vely+=.35\r\n if self.isfiring==0:\r\n if self.dir==0:\r\n if self.spritej==0:\r\n self.image=self.first[10]\r\n self.spritej=1\r\n elif self.spritej==1:\r\n self.image=self.first[11]\r\n self.spritej=2\r\n elif self.spritej==2:\r\n self.image=self.first[12]\r\n self.spritej=3\r\n elif self.spritej==3:\r\n self.image=self.first[13]\r\n elif self.dir==1:\r\n if self.spritej==0:\r\n self.image=self.first[24]\r\n self.spritej=1\r\n elif self.spritej==1:\r\n self.image=self.first[25]\r\n self.spritej=2\r\n elif self.spritej==2:\r\n self.image=self.first[26]\r\n self.spritej=3\r\n elif self.spritej==3:\r\n self.image=self.first[27]\r\n elif self.isfiring==1:\r\n if self.dir==0:\r\n self.image=self.first[30]\r\n else:\r\n self.image=self.first[31]\r\n else:\r\n if self.dir==0:\r\n self.image=self.first[34]\r\n else:\r\n self.image=self.first[35]\r\n \r\n\r\n if self.rect.y >= Alto - self.rect.height and self.vely >= 0:\r\n self.vely = 0\r\n self.rect.y = Alto - self.rect.height\r\n\r\n def salto(self,pantalla):\r\n self.rect.y += 2\r\n plataforma_col_lista=pygame.sprite.spritecollide(self,self.nivel.plataforma_lista,False)\r\n self.rect.y -= 2\r\n pantalla.blit(self.image, self.rect)\r\n if len(plataforma_col_lista) > 0 or self.rect.bottom >= Alto:\r\n self.isjump=1\r\n self.vely= -12\r\n \r\n def ir_izq(self,pantalla):\r\n self.velx=-6\r\n self.dir=1\r\n if self.isjump==0:\r\n if self.isrun==1:\r\n self.image=self.first[7]\r\n pantalla.blit(self.image, self.rect)\r\n\r\n def ir_der(self,pantalla):\r\n self.velx=6\r\n self.dir=0\r\n if self.isjump==0:\r\n if self.isrun==1:\r\n self.image=self.first[2]\r\n pantalla.blit(self.image, self.rect)\r\n\r\n def no_mover(self,pantalla):\r\n self.velx=0\r\n if self.isjump==0:\r\n if self.isfiring==0:\r\n if self.dir==0:\r\n self.image=self.first[0]\r\n elif self.dir==1:\r\n self.image=self.first[14]\r\n else:\r\n if self.dir==0:\r\n self.image=self.first[28]\r\n else:\r\n self.image=self.first[29]\r\n pantalla.blit(self.image, self.rect)\r\n\r\n def disparo(self,pantalla):\r\n if self.isjump==0:\r\n if self.dir==0:\r\n self.image=self.first[28]\r\n else:\r\n self.image=self.first[29]\r\n else:\r\n if self.dir==0:\r\n self.image=self.first[30]\r\n else:\r\n self.image=self.first[31]\r\n pantalla.blit(self.image, self.rect)\r\n\r\nclass Vidas():\r\n\r\n def __init__(self,nvidas, pantalla):\r\n self.alto=3\r\n self.ancho=10\r\n self.sep=0\r\n self.vidas=nvidas\r\n self.color=ROJO\r\n self.pos_x=50\r\n self.pos_yini=280\r\n self.pos_y=self.pos_yini-(nvidas*(self.alto+self.sep))\r\n pygame.draw.rect(pantalla,self.color,[self.pos_y,self.pos_x, self.alto,self.ancho])\r\n\r\nclass Poder():\r\n\r\n def __init__(self,nbal, pantalla):\r\n self.alto=3\r\n self.ancho=10\r\n self.sep=0\r\n self.vidas=nbal\r\n self.color=VERDE\r\n self.pos_x=70\r\n self.pos_yini=280\r\n self.pos_y=self.pos_yini-(nbal*(self.alto+self.sep))\r\n pygame.draw.rect(pantalla,self.color,[self.pos_y,self.pos_x,self.alto, self.ancho])\r\n\r\n\r\nclass Plataforma(pygame.sprite.Sprite):\r\n\r\n def __init__(self,ancho,alto):\r\n self.Anc=ancho\r\n self.Alt=alto\r\n pygame.sprite.Sprite.__init__(self)\r\n self.image= pygame.Surface([self.Anc,self.Alt])\r\n self.rect=self.image.get_rect()\r\n self.color1=GRIS\r\n self.image.fill(self.color1)\r\n\r\nclass Balas (pygame.sprite.Sprite):\r\n\r\n def __init__(self, posx, posy,tipo,dire):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.tipo = tipo\r\n self.dir = dire\r\n self.sprite= 0\r\n if self.tipo ==0:\r\n self.image = pygame.image.load(\"imagenes/BFGshot1.png\")\r\n self.vel = 5\r\n self.rect = self.image.get_rect()\r\n self.rect.x = posx + 25\r\n self.rect.y = posy + 10\r\n if self.tipo == 1:\r\n self.image = pygame.image.load(\"imagenes/plasma.png\")\r\n self.vel = 12\r\n self.rect = self.image.get_rect()\r\n self.rect.x = posx+25\r\n self.rect.y = posy+12\r\n if self.tipo == 2:\r\n self.image = pygame.image.load(\"imagenes/Cacoball.png\")\r\n self.vel = 10\r\n self.rect = self.image.get_rect()\r\n self.rect.x = posx\r\n self.rect.y = posy+34\r\n\r\n def derecha(self, superficie):\r\n if self.tipo==0:\r\n if self.sprite==0:\r\n self.image = pygame.image.load(\"imagenes/BFGshot1.png\")\r\n self.sprite=1\r\n elif self.sprite==1:\r\n self.image = pygame.image.load(\"imagenes/BFGshot2.png\")\r\n self.sprite=0\r\n elif self.tipo==1:\r\n if self.sprite==0:\r\n self.image = pygame.image.load(\"imagenes/plasma.png\")\r\n self.sprite=1\r\n elif self.sprite==1:\r\n self.image = pygame.image.load(\"imagenes/plasma2.png\")\r\n self.sprite=0\r\n elif self.tipo==2:\r\n if self.sprite==0:\r\n self.image = pygame.image.load(\"imagenes/Cacoball.png\")\r\n self.sprite=1\r\n elif self.sprite==1:\r\n self.image = pygame.image.load(\"imagenes/Cacoball2.png\")\r\n self.sprite=0\r\n if self.dir==0:\r\n self.rect.x = self.rect.x + self.vel\r\n superficie.blit(self.image, self.rect)\r\n else:\r\n self.rect.x = self.rect.x - self.vel\r\n superficie.blit(self.image, self.rect)\r\n\r\nclass Enemigo (pygame.sprite.Sprite):\r\n sprite=0\r\n\r\n\r\n def __init__(self, posx, posy, typee):\r\n pygame.sprite.Sprite.__init__(self)\r\n self.tipo = typee\r\n self.vidas = 0\r\n self.pasos = 0\r\n self.lanzar = 0\r\n if self.tipo == 1:\r\n self.image = pygame.image.load(\"imagenes/Cacodemon1.png\")\r\n self.vidas = random.randint(5,7)\r\n self.lanzar = random.randint(50,150)\r\n self.vel = 2\r\n elif self.tipo == 2:\r\n self.image = pygame.image.load(\"imagenes/Rocket1.png\")\r\n self.vidas = 1\r\n self.vel = random.randint(5,10)\r\n elif self.tipo == 3:\r\n self.image = pygame.image.load(\"imagenes/Painelem4.png\")\r\n self.vidas = random.randint(2,4)\r\n self.lanzar = random.randint(150,250)\r\n self.vel = 2\r\n elif self.tipo == 4:\r\n self.image = pygame.image.load(\"imagenes/Lostsoul1i.png\")\r\n self.vel = 11\r\n self.vidas = 1\r\n self.rect = self.image.get_rect()\r\n if self.tipo==4:\r\n self.rect.x = posx\r\n self.rect.y = posy+30\r\n else:\r\n self.rect.x = posx\r\n self.rect.y = posy\r\n\r\n def izquierda(self, superficie, pospl, velpl):\r\n if self.tipo==1:\r\n if self.sprite ==0:\r\n self.image = pygame.image.load(\"imagenes/Cacodemon1.png\")\r\n self.sprite=1\r\n elif self.sprite ==1:\r\n self.image = pygame.image.load(\"imagenes/Cacodemon2.png\")\r\n self.sprite=2\r\n elif self.sprite ==2:\r\n self.image = pygame.image.load(\"imagenes/Cacodemon3.png\")\r\n self.sprite=3\r\n elif self.sprite ==3:\r\n self.image = pygame.image.load(\"imagenes/Cacodemon4.png\")\r\n self.sprite=4\r\n elif self.sprite ==4:\r\n self.image = pygame.image.load(\"imagenes/Cacodemon5.png\")\r\n self.sprite=5\r\n elif self.sprite ==5:\r\n self.image = pygame.image.load(\"imagenes/Cacodemon6.png\")\r\n self.sprite=6\r\n elif self.sprite ==6:\r\n self.image = pygame.image.load(\"imagenes/Cacodemon7.png\")\r\n self.sprite=0\r\n self.rect.x = self.rect.x - self.vel\r\n elif self.tipo==2:\r\n if self.sprite ==0:\r\n self.image = pygame.image.load(\"imagenes/Rocket1.png\")\r\n self.sprite=1\r\n elif self.sprite ==1:\r\n self.image = pygame.image.load(\"imagenes/Rocket2.png\")\r\n self.sprite=2\r\n elif self.sprite ==2:\r\n self.image = pygame.image.load(\"imagenes/Rocket3.png\")\r\n self.sprite=3\r\n elif self.sprite ==3:\r\n self.image = pygame.image.load(\"imagenes/Rocket4.png\")\r\n self.sprite=4\r\n elif self.sprite ==4:\r\n self.image = pygame.image.load(\"imagenes/Rocket5.png\")\r\n self.sprite=0\r\n if pospl<=self.rect.y:\r\n self.rect.y-=4\r\n else:\r\n self.rect.y+=4\r\n elif self.tipo==3:\r\n if self.sprite ==0:\r\n self.image = pygame.image.load(\"imagenes/Painelem3.png\")\r\n self.sprite=1\r\n elif self.sprite ==1:\r\n self.image = pygame.image.load(\"imagenes/Painelem2.png\")\r\n self.sprite=2\r\n elif self.sprite ==2:\r\n self.image = pygame.image.load(\"imagenes/Painelem1.png\")\r\n self.sprite=3\r\n elif self.sprite ==3:\r\n self.image = pygame.image.load(\"imagenes/Painelem2.png\")\r\n self.sprite=0\r\n elif self.tipo==4:\r\n if self.sprite ==0:\r\n self.image = pygame.image.load(\"imagenes/Lostsoul1i.png\")\r\n self.sprite=1\r\n elif self.sprite ==1:\r\n self.image = pygame.image.load(\"imagenes/Lostsoul2i.png\")\r\n self.sprite=0\r\n self.rect.x = self.rect.x - self.vel - velpl\r\n self.pasos+=1\r\n superficie.blit(self.image, self.rect)\r\n\r\nclass Nivel(object):\r\n\r\n plataforma_lista=None\r\n enemigos_lista=None\r\n\r\n fondo1=Fontrans\r\n fondo2=Fontrans1\r\n fondo3=Fontrans2\r\n fondo4=Fontrans3\r\n fondo5=Fontrans4\r\n\r\n rect1=fondo1.get_rect()\r\n mov_fondo=0\r\n\r\n def __init__(self,jugador):\r\n self.plataforma_lista=pygame.sprite.Group()\r\n self.enemigos_lista=pygame.sprite.Group()\r\n self.jugador=jugador\r\n\r\n def update(self):\r\n self.plataforma_lista.update()\r\n self.enemigos_lista.update()\r\n\r\n def draw(self,pantalla):\r\n\r\n pantalla.fill(AZUL)\r\n pantalla.blit(self.fondo3,(self.rect1.x-800,self.rect1.y))\r\n pantalla.blit(self.fondo1,(self.rect1))\r\n pantalla.blit(self.fondo2,(self.rect1.x+800,self.rect1.y))\r\n pantalla.blit(self.fondo3,(self.rect1.x+1600,self.rect1.y))\r\n pantalla.blit(self.fondo1,(self.rect1.x+2400,self.rect1.y))\r\n pantalla.blit(self.fondo4,(self.rect1.x,self.rect1.y-800))\r\n pantalla.blit(self.fondo4,(self.rect1.x,self.rect1.y-1600))\r\n pantalla.blit(self.fondo4,(self.rect1.x,self.rect1.y-2400))\r\n pantalla.blit(self.fondo5,(self.rect1.x,self.rect1.y-2400))\r\n\r\n\r\n self.plataforma_lista.draw(pantalla)\r\n self.enemigos_lista.draw(pantalla)\r\n\r\n def Mover_fondox(self,mov_x):\r\n self.mov_fondo += mov_x\r\n for plataforma in self.plataforma_lista:\r\n plataforma.rect.x += mov_x\r\n for enemigos in self.enemigos_lista:\r\n enemigos.rect.x += mov_x\r\n self.rect1.x+=mov_x\r\n\r\n def Mover_fondoy(self,mov_y):\r\n self.mov_fondo += mov_y\r\n for plataforma in self.plataforma_lista:\r\n plataforma.rect.y += mov_y\r\n for enemigos in self.enemigos_lista:\r\n enemigos.rect.y += mov_y\r\n self.rect1.y+=mov_y\r\n\r\n\r\nclass Nivel_01(Nivel):\r\n\r\n def __init__(self,jugador):\r\n\r\n Nivel.__init__(self,jugador)\r\n \r\n self.limiteder=-1500\r\n\r\n nivel=[[10,600,-30,0],[210,10,1400,200],[210,10,500,400], [210,10,900,300],\r\n [210,10,1100,400],[210,10,1000,500],[10,300,1000,300],\r\n [210,10,1760,330],[10,260,1950,340]]\r\n\r\n\r\n for plataforma in nivel:\r\n bloque =Plataforma(plataforma[0],plataforma[1])\r\n bloque.rect.x=plataforma[2]\r\n bloque.rect.y=plataforma[3]\r\n bloque.jugador =self.jugador\r\n self.plataforma_lista.add(bloque)\r\n\r\nclass Nivel_02(Nivel):\r\n\r\n def __init__(self,jugador):\r\n\r\n Nivel.__init__(self,jugador)\r\n \r\n self.limiteder=-1600\r\n\r\n nivel=[[200,10,-200,330],[10,260,0,340],[150,10,500,500],\r\n [100,20,540,300], [50,20,600,150],[210,10,200,-50],\r\n [100,20,540,-250], [50,20,600,-450],[210,10,200,-600],\r\n [100,20,540,-750], [50,20,600,-850],[210,10,200,-1000],\r\n [100,20,540,-1100], [50,20,600,-1250],[210,10,200,-1450]]\r\n\r\n\r\n for plataforma in nivel:\r\n bloque =Plataforma(plataforma[0],plataforma[1])\r\n bloque.rect.x=plataforma[2]\r\n bloque.rect.y=plataforma[3]\r\n bloque.jugador =self.jugador\r\n self.plataforma_lista.add(bloque)\r\n\r\ndef main():\r\n pygame.init()\r\n pygame.mixer.init()\r\n fuente= pygame.font.Font(\"fuentes/zrnic___.ttf\", 30)\r\n fuentep=pygame.font.Font(\"fuentes/zrnic___.ttf\",15)\r\n pygame.display.set_caption(\"The Warrior: Ultimo Intento\")\r\n Fon = pygame.mixer.Sound(\"sonidos/Lev1.ogg\").play(-1)\r\n Enemies = pygame.mixer.Sound(\"sonidos/06.mp3\")\r\n Enemies.play(-1)\r\n Fire = pygame.mixer.Sound(\"sonidos/blow.ogg\")\r\n Plasmafire = pygame.mixer.Sound(\"sonidos/Plasmarifle.wav\")\r\n Bfgfire = pygame.mixer.Sound(\"sonidos/BFG.wav\")\r\n Bfghit = pygame.mixer.Sound(\"sonidos/BFGhit.wav\")\r\n Enemyhit = pygame.mixer.Sound(\"sonidos/Cacohit.wav\")\r\n Painehit = pygame.mixer.Sound(\"sonidos/Painhit.wav\")\r\n Cacodeath = pygame.mixer.Sound(\"sonidos/Cacodeath.wav\")\r\n Paindeath = pygame.mixer.Sound(\"sonidos/Paindeath.wav\")\r\n Lostdeath = pygame.mixer.Sound(\"sonidos/Lostdeath.wav\")\r\n tamano=[Ancho,Alto]\r\n pantalla = pygame.display.set_mode(tamano)\r\n w_score = open(\"data/puntaje.txt\", \"w\")\r\n r_score = open(\"data/puntaje.txt\", \"r\")\r\n w_temp = open(\"data/temp.txt\", \"w\")\r\n puntos=0\r\n tipobul=1\r\n dano=0\r\n bulc=0\r\n miscount=0\r\n\r\n for li in r_score:\r\n p = fuentep.render(\"Puntaje Máximo: \" +li, True, (255, 255, 255))\r\n\r\n jugador=Jugador()\r\n\r\n nivel_lista=[]\r\n nivel_lista.append(Nivel_01(jugador))\r\n nivel_lista.append(Nivel_02(jugador))\r\n nivel_tot=len(nivel_lista)\r\n\r\n nivel_actual_no=0\r\n nivel_actual=nivel_lista[nivel_actual_no]\r\n\r\n activos_sp_lista = pygame.sprite.Group()\r\n enemigos_lista = pygame.sprite.Group()\r\n enembal_lista = pygame.sprite.Group()\r\n balas_lista = pygame.sprite.Group()\r\n jugador.nivel = nivel_actual\r\n\r\n jugador.rect.x=340\r\n jugador.rect.y=Alto-jugador.rect.height\r\n activos_sp_lista.add(jugador)\r\n\r\n for i in range (7):\r\n posx=random.randint(1200,1400)\r\n posy=random.randint(50,500)\r\n entipo=random.randint(1,3)\r\n enem=Enemigo(posx,posy,entipo)\r\n enemigos_lista.add(enem)\r\n activos_sp_lista.add(enem)\r\n\r\n fin=False\r\n\r\n while not fin:\r\n for e in pygame.event.get():\r\n if e.type == pygame.QUIT:\r\n fin=True\r\n if e.type == pygame.KEYDOWN:\r\n if e.key == pygame.K_RIGHT:\r\n jugador.isfiring=0\r\n jugador.isrun=1\r\n jugador.ir_der(pantalla)\r\n if e.key ==pygame.K_LEFT:\r\n jugador.isfiring=0\r\n jugador.isrun=1\r\n jugador.ir_izq(pantalla)\r\n if e.key ==pygame.K_UP:\r\n jugador.isfiring=0\r\n jugador.salto(pantalla)\r\n if e.key ==pygame.K_SPACE:\r\n jugador.disparo(pantalla)\r\n if tipobul==0:\r\n jugador.isfiring=2\r\n if bulc < 1:\r\n if jugador.bullets>10:\r\n Bfgfire.play()\r\n Bl1 = Balas(jugador.rect.x,jugador.rect.y,tipobul, jugador.dir)\r\n balas_lista.add(Bl1)\r\n activos_sp_lista.add(Bl1)\r\n jugador.bullets-=10\r\n bulc+=1\r\n if tipobul==1:\r\n jugador.isfiring=1\r\n if bulc < 5:\r\n if jugador.bullets>0:\r\n Plasmafire.play()\r\n Bl1 = Balas(jugador.rect.x,jugador.rect.y,tipobul, jugador.dir)\r\n balas_lista.add(Bl1)\r\n activos_sp_lista.add(Bl1)\r\n jugador.bullets-=1\r\n bulc+=1\r\n if e.key ==pygame.K_1:\r\n tipobul=1\r\n if e.key ==pygame.K_2:\r\n tipobul=0\r\n elif e.key == pygame.K_RETURN:\r\n Fon.set_volume(2.0)\r\n Enemies.stop()\r\n imagen= pygame.image.load('imagenes/pause.png')\r\n\r\n pantalla.blit(imagen,(100,200))\r\n\r\n pygame.display.flip()\r\n Pausa=True\r\n while Pausa:\r\n for k in pygame.event.get():\r\n if k.type == pygame.QUIT:\r\n Pausa=False\r\n fin=True\r\n w_score.write(str(puntos) + \"\\n\")\r\n w_score.close()\r\n if k.type == pygame.KEYDOWN:\r\n if k.key == pygame.K_b:\r\n Fon.set_volume(10.0)\r\n Enemies.play(-1)\r\n Pausa=False\r\n if k.key == pygame.K_s:\r\n Pausa=False\r\n fin=True\r\n\r\n if e.type == pygame.KEYUP:\r\n if e.key == pygame.K_LEFT and jugador.velx < 0:\r\n jugador.isrun=0\r\n jugador.no_mover(pantalla)\r\n if e.key ==pygame.K_RIGHT and jugador.velx > 0:\r\n jugador.isrun=0\r\n jugador.no_mover(pantalla)\r\n\r\n activos_sp_lista.update()\r\n\r\n txt_puntos = fuentep.render(\"Puntaje: \" + str(puntos),True,(255,255,255))\r\n pantalla.blit(txt_puntos,[10,10])\r\n\r\n for en in enemigos_lista:\r\n if en.tipo==2:\r\n if nivel_actual_no==0:\r\n en.izquierda(pantalla,jugador.rect.y, jugador.velx)\r\n else:\r\n en.izquierda(pantalla,jugador.rect.y, 0)\r\n else:\r\n if nivel_actual_no==0:\r\n en.izquierda(pantalla,0, jugador.velx)\r\n else:\r\n en.izquierda(pantalla,0, 0)\r\n if en.pasos==en.lanzar:\r\n if en.tipo==1:\r\n enbl = Balas(en.rect.x, en.rect.y, 2, 1)\r\n elif en.tipo==3:\r\n enbl = Enemigo(en.rect.x, en.rect.y, 4)\r\n if enbl.tipo==4:\r\n enemigos_lista.add(enbl)\r\n else:\r\n enembal_lista.add(enbl)\r\n activos_sp_lista.add(enbl)\r\n en.pasos = 0\r\n en.lanzar = random.randint(20,100)\r\n if (en.rect.x < 0 or en.rect.y >630) and en.tipo!=4:\r\n enemigos_lista.remove(en)\r\n activos_sp_lista.remove(en)\r\n posx=random.randint(800,1200)\r\n posy=random.randint(50,500)\r\n entipo=random.randint(1,3)\r\n ene=Enemigo(posx,posy,entipo)\r\n enemigos_lista.add(ene)\r\n activos_sp_lista.add(ene)\r\n if jugador.bullets<=68:\r\n jugador.bullets+=2\r\n\r\n if jugador.vidas<=0:\r\n fin=True\r\n activos_sp_lista.remove(jugador)\r\n w_score.write(str(puntos) + \"\\n\")\r\n w_score.close()\r\n\r\n for buld in balas_lista:\r\n buld.derecha(pantalla)\r\n if buld.rect.x > 850 or buld.rect.x < 0:\r\n balas_lista.remove(buld)\r\n activos_sp_lista.remove(buld)\r\n bulc-=1\r\n bulimp = pygame.sprite.spritecollide(buld,enemigos_lista,False)\r\n for en in bulimp:\r\n if buld.tipo == 1:\r\n balas_lista.remove(buld)\r\n activos_sp_lista.remove(buld)\r\n bulc-=1\r\n if buld.tipo==0:\r\n Bfghit.play()\r\n #print en.vidas\r\n if en.vidas <=0:\r\n if en.tipo==1:\r\n Cacodeath.play()\r\n elif en.tipo==2 or en.tipo==4:\r\n Lostdeath.play()\r\n elif en.tipo==3:\r\n Paindeath.play()\r\n enemigos_lista.remove(en)\r\n activos_sp_lista.remove(en)\r\n posx=random.randint(800,1200)\r\n posy=random.randint(50,500)\r\n entipo=random.randint(1,3)\r\n ene=Enemigo(posx,posy,entipo)\r\n enemigos_lista.add(ene)\r\n activos_sp_lista.add(ene)\r\n puntos +=1000\r\n else:\r\n en.vidas-=random.randint(2,3)\r\n if en.tipo==1:\r\n Enemyhit.play()\r\n elif en.tipo==3:\r\n Painehit.play()\r\n \r\n for bule in enembal_lista:\r\n bule.derecha(pantalla)\r\n if bule.rect.x < 0:\r\n enembal_lista.remove(bule)\r\n activos_sp_lista.remove(bule)\r\n bulenimp = pygame.sprite.spritecollide(jugador,enembal_lista,False)\r\n for bl in bulenimp:\r\n enembal_lista.remove(bl)\r\n activos_sp_lista.remove(bl)\r\n jugador.vidas-=1\r\n Fire.play()\r\n \r\n golpazo=pygame.sprite.spritecollide(jugador,enemigos_lista,True)\r\n for f in golpazo:\r\n if f.tipo==1:\r\n dano=random.randint(1,3)\r\n elif f.tipo==2:\r\n dano=random.randint(3,5)\r\n elif f.tipo==3:\r\n dano=random.randint(5,7)\r\n enemigos_lista.remove(f)\r\n activos_sp_lista.remove(f)\r\n Fire.play()\r\n posx=random.randint(800,1200)\r\n posy=random.randint(50,500)\r\n entipo=random.randint(1,3)\r\n ene=Enemigo(posx,posy,entipo)\r\n enemigos_lista.add(ene)\r\n activos_sp_lista.add(ene)\r\n jugador.vidas-=dano\r\n \r\n \r\n nivel_actual.update()\r\n if nivel_actual_no==0:\r\n if jugador.rect.right >= 450:\r\n dif=jugador.rect.x - 450\r\n jugador.rect.x = 450\r\n nivel_actual.Mover_fondox(-dif)\r\n\r\n if jugador.rect.left <=120:\r\n dif=120-jugador.rect.x\r\n jugador.rect.x=120\r\n nivel_actual.Mover_fondox(dif)\r\n elif nivel_actual_no==1:\r\n if jugador.rect.top <= 100:\r\n dif=jugador.rect.y - 100\r\n jugador.rect.y = 100\r\n nivel_actual.Mover_fondoy(-dif)\r\n for en in enemigos_lista:\r\n en.rect.y-=dif\r\n for bl in balas_lista:\r\n bl.rect.y-=dif\r\n for enbl in enembal_lista:\r\n enbl.rect.y-=dif\r\n \r\n if jugador.rect.right >= 800:\r\n jugador.rect.x = jugador.rect.x - 6\r\n\r\n if jugador.rect.left <=0:\r\n jugador.rect.x= - jugador.rect.x\r\n\r\n if nivel_actual_no==0:\r\n pos_actual=jugador.rect.x + nivel_actual.mov_fondo\r\n else:\r\n pos_actual=jugador.rect.y - nivel_actual.mov_fondo\r\n nivel_actual.draw(pantalla)\r\n if pos_actual < nivel_actual.limiteder:\r\n jugador.rect.x=120\r\n if nivel_actual_no expected_size, 'Expected it to be greater than %i' \\\n ' instead got %i' % (expected_size, size)\n elif more_less_equal.lower() == 'less':\n assert size < expected_size, 'Expected it to be less than %i' \\\n ' instead got %i' % (expected_size, size)\n elif more_less_equal.lower() == 'equal':\n assert size == expected_size, 'Expected it to be equal to %i' \\\n ' instead got %i' % (expected_size, size)\n else:\n assert False, 'Unexpected value for more_less_equal, got: %s' % (\n more_less_equal\n )\n\n\n@when('I scroll the nav out of the way')\ndef scroll_nav_out_way(context):\n scroll_nav_out_of_way(context.driver)\n\n\n@when('I scroll the footer out of the way')\ndef scroll_footer_out_way(context):\n scroll_footer_out_of_way(context.driver)\n","sub_path":"qa/tests/steps/accessiblity.py","file_name":"accessiblity.py","file_ext":"py","file_size_in_byte":4874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"5095637","text":"\naccount_id = 842\nnames = [\"A\", \"B\", \"C\"]\n\ndisk_ids = []\nfor name in names:\n disk_ids.append(pcl.cloudapi.disks.create(accountId=account_id, gid=66, name=name, description=\"lsdjf\", size=10, type=\"D\"))\n\n\nids = range(1034, 1037)\nfor diskId in ids:\n api.disks.delete(diskId=diskId, detach=True, permanently=True)\n\n[(d[\"id\"], d[\"status\"]) for d in cb.disk.search({\"id\": {\"$in\": ids}})[1:]]\n\n\n[(d[\"id\"], d[\"status\"]) for d in cb.disk.search({\"name\": {\"$in\": names}, \"status\": {\"$ne\": \"DESTROYED\"}})[1:]]\n\n\n\ncb.disk.updateSearch({\"status\": \"DESTORYED\"}, {\"$set\": {\"status\": \"DESTROYED\"}})","sub_path":"debug-ovc-transition-states/local_testcases/test_disk_deletion.py","file_name":"test_disk_deletion.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"364275776","text":"import tensorflow as tf\nimport tensorflow.contrib.layers as tfc_layers\n\nfrom generic.tf_utils.abstract_network import AbstractNetwork\nfrom neural_toolbox import rnn\nfrom generic.tf_factory.fusion_factory import get_fusion_mechanism\n\n\nfrom generic.tf_factory.image_factory import get_image_features\nfrom neural_toolbox.film_stack import FiLM_Stack\nfrom neural_toolbox import regularizer_toolbox\nfrom neural_toolbox.reading_unit import create_reading_unit, create_film_layer_with_reading_unit\n\n\nclass GuesserNetwork(AbstractNetwork):\n def __init__(self, config, no_words, device='', reuse=False):\n AbstractNetwork.__init__(self, \"guesser\", device=device)\n\n with tf.variable_scope(self.scope_name, reuse=reuse):\n\n batch_size = None\n\n self._is_training = tf.placeholder(tf.bool, name=\"is_training\")\n\n dropout_keep_scalar = float(config['regularizer'].get(\"dropout_keep_prob\", 1.0))\n dropout_keep = tf.cond(self._is_training,\n lambda: tf.constant(dropout_keep_scalar),\n lambda: tf.constant(1.0))\n\n self.regularizer = regularizer_toolbox.Regularizer(config['regularizer'], self._is_training, dropout_keep, reuse)\n\n #####################\n # OBJECTS\n #####################\n\n #self._obj_mask = tf.placeholder(tf.float32, [batch_size, None], name='obj_mask')\n self._num_object = tf.placeholder(tf.int32, [batch_size], name='obj_seq_length')\n self._obj_cats = tf.placeholder(tf.int32, [batch_size, None], name='obj_cats')\n self._obj_spats = tf.placeholder(tf.float32, [batch_size, None, config[\"object\"]['spat_dim']], name='obj_spats')\n\n # Embedding object categories\n with tf.variable_scope('object_embedding'):\n\n\n self.object_cats_emb = tfc_layers.embed_sequence(\n ids=self._obj_cats,\n vocab_size=config[\"object\"]['no_categories'] + 1,\n embed_dim=config[\"object\"]['cat_emb_dim'],\n scope=\"cat_embedding\",\n reuse=reuse)\n\n # Adding spatial coordinate (should be optionnal)\n self.objects_input = tf.concat([self.object_cats_emb, self._obj_spats], axis=2)\n\n\n object_emb_hidden = tfc_layers.fully_connected(self.objects_input,\n num_outputs=config[\"object\"]['obj_emb_hidden'],\n activation_fn=tf.nn.relu,\n scope='obj_mlp_hidden_layer')\n\n # object_emb_hidden = tf.nn.dropout(object_emb_hidden, dropout_keep)\n with tf.variable_scope('object_embedding_reg'):\n object_emb_hidden = self.regularizer.apply(object_emb_hidden)\n\n self.object_embedding = tfc_layers.fully_connected(object_emb_hidden,\n num_outputs=config[\"object\"]['obj_emb_dim'],\n activation_fn=tf.nn.relu,\n scope='obj_mlp_out')\n\n #####################\n # DIALOGUE\n #####################\n use_glove = config[\"dialogue\"]['glove']\n self._dialogue = tf.placeholder(tf.int32, [batch_size, None], name='dialogue')\n self._seq_length_dialogue = tf.placeholder(tf.int32, [batch_size], name='seq_length_dialogue')\n\n if use_glove : self._glove = tf.placeholder(tf.float32, [None, None, 300], name=\"glove\")\n\n\n with tf.variable_scope('dialogue_embedding'):\n\n word_emb = tfc_layers.embed_sequence(\n ids=self._dialogue,\n vocab_size=no_words,\n embed_dim=config[\"dialogue\"][\"word_embedding_dim\"],\n scope=\"input_word_embedding\",\n reuse=reuse)\n\n if use_glove:\n word_emb = tf.concat([word_emb, self._glove], axis=2)\n\n # word_emb = tf.nn.dropout(word_emb, dropout_keep)\n with tf.variable_scope('word_embedding_reg'):\n word_emb = self.regularizer.apply(word_emb)\n\n # If specified, use a lstm, otherwise default behavior is GRU now\n if config[\"dialogue\"][\"use_lstm\"] :\n _, self.dialogue_embedding = rnn.variable_length_LSTM(word_emb,\n num_hidden=config[\"dialogue\"]['rnn_state_size'],\n seq_length=self._seq_length_dialogue,\n dropout_keep_prob=dropout_keep)\n\n else:\n _, self.dialogue_embedding = rnn.gru_factory(\n inputs=word_emb,\n seq_length=self._seq_length_dialogue,\n num_hidden=config[\"dialogue\"][\"rnn_state_size\"],\n bidirectional=config[\"dialogue\"][\"bidirectional\"],\n max_pool=config[\"dialogue\"][\"max_pool\"],\n layer_norm=config[\"dialogue\"][\"layer_norm\"],\n reuse=reuse)\n\n #self.dialogue_embedding = tf.nn.dropout(self.dialogue_embedding, dropout_keep)\n with tf.variable_scope('dialogue_reg'):\n self.dialogue_embedding = self.regularizer.apply(self.dialogue_embedding)\n\n #####################\n # IMAGES\n #####################\n\n if config['image']['use_image']:\n self._image = tf.placeholder(tf.float32, [batch_size] + config['image'][\"dim\"], name='image')\n self.image_out = get_image_features(\n image=self._image,\n question=self.dialogue_embedding,\n is_training=self._is_training,\n scope_name=\"image_processing\",\n config=config['image'],\n reuse=reuse)\n\n #####################\n # FiLM\n #####################\n\n # Use attention or use vgg features\n if len(self.image_out.get_shape()) == 2:\n self.image_embedding = self.image_out\n\n else:\n\n with tf.variable_scope(\"image_reading_cell\"):\n\n self.reading_unit = create_reading_unit(last_state=self.last_rnn_states,\n states=self.rnn_states,\n seq_length=self._seq_length,\n keep_dropout=dropout_keep,\n config=config[\"reading_unit\"],\n reuse=reuse)\n\n film_layer_fct = create_film_layer_with_reading_unit(self.reading_unit, stop_gradient=False)\n\n with tf.variable_scope(\"image_film_stack\", reuse=reuse):\n\n\n self.film_img_stack = FiLM_Stack(image=self.image_out,\n film_input=[], # Must be empty if memory cell\n attention_input=self.dialogue_embedding,\n is_training=self._is_training,\n dropout_keep=dropout_keep,\n film_layer_fct=film_layer_fct,\n config=config[\"image\"][\"film_block\"],\n reuse=reuse)\n\n self.image_embedding = self.film_img_stack.get()\n\n #self.image_embedding = tf.nn.dropout(self.image_embedding, dropout_keep)\n with tf.variable_scope(\"image_embedding_reg\"):\n self.image_embedding = self.regularizer(self.image_embedding)\n\n else:\n assert config['fusion']['mode'] == \"none\", \"If you don't want to use image, set fusion to none\"\n self.image_embedding = None\n\n #####################\n # FUSION MECHANISM\n #####################\n\n if config['dialogue']['reinject_for_fusion']:\n dialog_to_fuse = self.dialogue_embedding\n else:\n assert config['fusion']['mode'] == \"none\", \"If you don't want to reinject dialog, set fusion to none\"\n dialog_to_fuse = None\n\n\n with tf.variable_scope('fusion'):\n self.visual_dialogue_embedding, _ = get_fusion_mechanism(input1=self.image_embedding,\n input2=dialog_to_fuse,\n config=config[\"fusion\"],\n dropout_keep=dropout_keep,\n reuse=reuse)\n\n # Note: do not apply dropout here (special case because of scalar product)\n\n\n if config[\"fusion\"][\"visual_dialogue_projection\"] > 0:\n\n self.visual_dialogue_embedding = tfc_layers.fully_connected(self.visual_dialogue_embedding,\n num_outputs=config[\"fusion\"][\"visual_dialogue_projection\"],\n activation_fn=tf.nn.relu,\n scope='visual_dialogue_projection')\n\n\n\n #####################\n # SCALAR PRODUCT\n #####################\n\n with tf.variable_scope('scalar_product', reuse=reuse):\n\n # Compute vector product product\n self.visual_dialogue_embedding = tf.expand_dims(self.visual_dialogue_embedding, axis=1)\n\n self.object_dialogue_matching = self.visual_dialogue_embedding * self.object_embedding\n\n #self.object_dialogue_matching = tf.nn.dropout(self.object_dialogue_matching, keep_prob=dropout_keep)\n # self.object_dialogue_matching = tfc_layers.batch_norm(self.object_dialogue_matching,\n # is_training=self._is_training, reuse=reuse)\n with tf.variable_scope(\"scalar_product_reg\"):\n self.object_dialogue_matching = self.regularizer.apply(self.object_dialogue_matching)\n\n self.scores = self.object_dialogue_matching\n\n # Instead of doing a reduce sum, you can learn the score using a small MLP\n if config['scoring_object']['use_scoring_mlp']:\n\n size_hidden_scoring_mlp = config['scoring_object']['scoring_mlp_hidden']\n activation = eval(\"tf.nn.{}\".format(config[\"scoring_object\"]['activation']))\n\n if size_hidden_scoring_mlp > 0:\n self.scores = tfc_layers.fully_connected(self.scores,\n num_outputs=size_hidden_scoring_mlp,\n activation_fn=activation,\n scope='scoring_object_hidden_mlp')\n\n self.scores = tfc_layers.fully_connected(self.scores,\n num_outputs=1,\n activation_fn=activation,\n scope='scoring_object_output_mlp')\n\n self.scores = tf.squeeze(self.scores, axis=2)\n\n else:\n self.scores = tf.reduce_sum(self.scores, axis=2)\n\n\n\n #####################\n # OBJECT MASKING\n #####################\n\n with tf.variable_scope('object_mask', reuse=reuse):\n\n object_mask = tf.sequence_mask(self._num_object)\n score_mask_values = float(\"-inf\") * tf.ones_like(self.scores)\n\n self.score_masked = tf.where(object_mask, self.scores, score_mask_values)\n\n #####################\n # LOSS\n #####################\n\n # Targets\n self._targets = tf.placeholder(tf.int32, [batch_size], name=\"targets_index\")\n\n self.loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=self._targets, logits=self.score_masked)\n self.loss = tf.reduce_mean(self.loss)\n\n self.selected_object = tf.argmax(self.score_masked, axis=1)\n\n with tf.variable_scope('accuracy'):\n self.accuracy = tf.equal(self.selected_object, tf.cast(self._targets, tf.int64))\n self.accuracy = tf.reduce_mean(tf.cast(self.accuracy, tf.float32))\n\n def get_loss(self):\n return self.loss\n\n def get_accuracy(self):\n return self.accuracy\n\n\n\n\nif __name__ == \"__main__\":\n\n import json\n with open(\"../../../../config/guesser/config.film.json\", 'r') as f_config:\n config = json.load(f_config)\n\n GuesserNetwork(config[\"model\"], no_words=354)\n\n print(\"Done\")\n","sub_path":"src/guesswhat/models/guesser/guesser_baseline.py","file_name":"guesser_baseline.py","file_ext":"py","file_size_in_byte":13683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"12693096","text":"import unittest\n\n\ndef sort_by_occurrence(message):\n \"\"\"\n Sort a given string by the number of letter occurences\n\n ex: Aabb -> bbAa since 'b' appears twice, while 'A' and 'a' only appears once\n aabccc -> cccaab since 'c' appears 3 times, 'a' 2 times, ..etc..\n\n :param message: The message to sort\n :return: String with the most repeated characters all at the front\n \"\"\"\n\n # Count all occurrences of a letter\n occurrences = {}\n max_occurrence = 1\n for letter in message:\n if letter in occurrences:\n occurrences[letter] += 1\n max_occurrence = max(max_occurrence,occurrences[letter])\n else:\n occurrences[letter] = 1\n\n # Create buckets to hold letters of 1 occurrence to @max_occurrences occurrence\n buckets = [[] for i in xrange(max_occurrence+1)]\n\n # Add the letters to their corresponding buckets\n for k,v in occurrences.iteritems():\n buckets[v].append(k*v)\n\n # Reduce the buckets into one in a reversed manner\n result = []\n for bucket in reversed(buckets):\n if len(bucket) != 0:\n result.extend(bucket)\n\n return \"\".join(result)\n\n\nclass TestSortByOccurrence(unittest.TestCase):\n def test_normal(self):\n self.assertEquals(sort_by_occurrence(\"Aabb\"), \"bbAa\")\n self.assertEquals(sort_by_occurrence(\"aaabccccdd\"), \"ccccaaaddb\")\n self.assertEquals(sort_by_occurrence(\"AaabBBB\"), \"BBBaaAb\")\n self.assertEquals(sort_by_occurrence(\"zazaza\"), \"aaazzz\")\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"python/sort_by_occurrence.py","file_name":"sort_by_occurrence.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"175160675","text":"# \n#\tProject: \t\tc-home\n#\tModule: \t\tcdaParms\n#\tDescription:\tthis module is used to create a datastore json file\n#\tLicense: \t\tGPLv3\n#\nfrom datetime import datetime\nimport requests # http \nimport re # finds and replaces html tags\nimport ast # abstract systax converts ' to \"\nimport json\n\nwith open('cdaParm.json', 'r') as json_file:\n\tdata_in = json.load(json_file)\n\tfor cnt in data_in['config']:\n\t\tidNum = cnt['id']\n\nidNbr = 'id='+ idNum\n\nreadUrl = 'http://c-homecloud.appspot.com/readvid?' + idNbr\t\t# read current record \nr = requests.get(readUrl)\ncontent = r.text \n\nstripped = re.sub('<[^<]+?>', '', content)\nhope = filter(None, stripped) # process html returned from vidview.jsp\ndata=\"\".join(line.replace('/n',' ') for line in hope) # concatenate onto one line removing /n newline\nconn_params = \"{\" + data + \"}\" # add brackets\njsout = json.dumps(ast.literal_eval(conn_params)) # convert string to json string\nconn_params = json.loads(jsout) # create python dictionary\n \nwith open('dataStore.json', 'w') as outfile:\n\tjson.dump(conn_params, outfile) \n\t\nprint ('Local Data Store record created with key of: ', idNum)\n\t\n","sub_path":"cdaAdmin/dbaFrom.py","file_name":"dbaFrom.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"23151316","text":"\nimport sys\nimport csv\nimport cx_Oracle\nimport codecs\nimport os\nimport logging\n\nos.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.ZHS16GBK'\n#conn = cx_Oracle.connect(\"c##jaya\", \"123456\", \"192.168.1.95:1521/ORCL\")\nconn = cx_Oracle.connect('jaya/jaya123456@47.107.108.175:1521/orcl')\ncurs = conn .cursor()\n\ntabname= sys.argv[1]\ncsv_file_dest = \"G:/oracledata/\"+tabname+ \".csv\"\nlogging.info('csv_file_dest :' + csv_file_dest)\n\n\noutputFile = open(csv_file_dest,'w') # 'wb'\noutput = csv.writer(outputFile, dialect='excel')\nsql = \"select * from \"+tabname # get a list of all tables\ncurs.execute(sql)\ncols = []\n\nfor col in curs.description:\n cols.append(col[0])\noutput.writerow(cols)\nfor row_data in curs: # add table rows\n output.writerow(row_data)\noutputFile.close()\n","sub_path":"test1/export_Oracle_database_tables_to_CSV_files.py","file_name":"export_Oracle_database_tables_to_CSV_files.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"241251812","text":"import SimpleITK as sitk\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport pywt\n\npath1=\"P2897245\"\n\nreader = sitk.ImageSeriesReader()\n#print(\"reader type:{}\".format(type(reader)))\nimg_id = reader.GetGDCMSeriesIDs(path1)\nimg_names = reader.GetGDCMSeriesFileNames(path1,img_id[1])\n\nreader.SetFileNames(img_names)\n\nimage = reader.Execute()\nprint(\"image type:{}\".format(type(image)))\nimage_save=image\nimage_array = sitk.GetArrayFromImage(image)\nprint(\"image_array shape:{}\".format(image_array.shape))\n\nn =pywt.dwtn(image_array,wavelet='bior1.3')\n\n\nstring=['jjj','aaa','aad','ada','daa','dda','dad','add','ddd']\n\nfig=plt.figure()\nfor i in range(0,9):\n fig.add_subplot(3,3,i+1)\n if string[i]=='jjj':\n plt.imshow(image_array[:, :, 40], cmap='gray')\n\n else:\n plt.imshow(n[string[i]][:,:,20], cmap = 'gray')\n\n\nplt.show()\n\n\n\n\n\n","sub_path":"wavelets/wavelets.py","file_name":"wavelets.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"646107150","text":"#!/usr/bin/python\n\n\"\"\" Simple Twitter slave bot. \"\"\"\n\n__version_info__ = (0, 0, 1)\n__version__ = '.'.join(map(str, __version_info__))\n\nimport os\n\nfrom distutils.core import setup\n\nREADME = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()\nREQUIREMENTS = [\n line.strip() for line in open(os.path.join(os.path.dirname(__file__),\n 'requirements.txt')).readlines()\n ]\n\nsetup(\n name='usmanondorf',\n version=__version__,\n description=('Simple Twitter slave bot.'),\n author='Usman Masood',\n author_email='usmanm@fastmail.fm',\n license='MIT License',\n url='https://github.com/usmanm/usmanondorf/',\n packages = ['usmanondorf'],\n classifiers=[\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: Linux ',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n ],\n long_description=README,\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"593755087","text":"\"\"\"\nRaster Datasets\n---------------\n\n.. _supported_rasters:\n\nCurrently supported raster formats\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n* `GDAL `_\n* :mod:`rasterio`\n* `pysheds `_ (uses rasterio internally, but its 'grid' class has slightly different attribute names from raw rasterio)\n\n\"\"\"\nfrom importlib import import_module\nfrom functools import singledispatch\nimport numpy as np\nimport re\n\n# http://proj.maptools.org/gen_parms.html\nproj4_cartopy_projections = {\n 'tmerc': 'TransverseMercator'\n}\n\ndef proj4_parser(proj4):\n \"\"\"Helper function to parse Proj.4 strings, returns key-value pairs with the leading '+' stripped, and nothing if there's only a key without value.\n\n \"\"\"\n try:\n k, v = proj4.split('=')\n except ValueError: return\n try:\n v = int(v)\n except ValueError:\n try:\n v = float(v)\n except ValueError: pass\n return k.replace('+', ''), v\n\ndef proj2cartopy(proj4):\n \"\"\"Return :mod:`cartopy.crs.CRS` projection given a Proj.4 string.\n\n .. TODO::\n\n * Works only for the one projection I have used so far...\n \"\"\"\n crs = import_module('cartopy.crs')\n d = dict(filter(lambda i: i is not None, map(proj4_parser, proj4.split())))\n return getattr(crs, proj4_cartopy_projections[d.pop('proj')])(d)\n\ndef wkt2proj(obj):\n \"\"\"Map wkt string to Proj.4 string. Argument can be either the wkt string **or** a '.prj' filename.\n\n \"\"\"\n osr = import_module('osgeo.osr')\n try:\n with open(obj) as f:\n s = f.read()\n except FileNotFoundError:\n s = obj\n return osr.SpatialReference(s).ExportToProj4()\n\ndef coords(raster, latlon=False):\n \"\"\"Return coordinate arrays constructed from a raster dataset's affine transform.\n\n :param raster: GDAL or rasterio (including pysheds) raster dataset\n :param latlon: If `True`, return lon, lat coordinates, otherwise projected coordinates\n :returns: (lon, lat) or (i, j) coordinates corresponding to the raster dataset\n :rtype: :obj:`tuple` of :class:`ndarrays `\n\n \"\"\"\n shape, a, proj = _raster_info(raster, latlon)\n i, j = [k+.5 for k in np.mgrid[:shape[0], :shape[1]]]\n x = a[0] * j + a[1] * i + a[2]\n y = a[3] * j + a[4] * i + a[5]\n return (x, y) if proj is None else proj(x, y, inverse=True)\n\n@singledispatch\ndef _raster_info(raster, latlon):\n pass\n\ntry:\n gdal = import_module('osgeo.gdal')\n @_raster_info.register(gdal.Dataset)\n def _(ds, latlon):\n b = ds.GetRasterBand(1)\n # https://www.gdal.org/gdal_datamodel.html\n # rasterio's affine is switched relative to GDAL's GeoTransform\n a = np.array(ds.GetGeoTransform())[[1, 2, 0, 4, 5, 3]]\n if latlon:\n proj = import_module('pyproj')\n p = proj.Proj(wkt2proj(ds.GetProjection()))\n return ((b.YSize, b.XSize), a, p if latlon else None)\nexcept: pass\n\ntry:\n io = import_module('rasterio.io')\n @_raster_info.register(io.DatasetReader)\n def _(ds, latlon):\n if latlon:\n proj = import_module('pyproj')\n p = proj.Proj(ds.crs.to_proj4())\n return (ds.shape, ds.transform, p if latlon else None)\nexcept: pass\n\ntry:\n grid = import_module('pysheds.grid')\n @_raster_info.register(grid.Grid)\n def _(ds, latlon):\n return (ds.shape, ds.affine, ds.crs if latlon else None)\nexcept: pass\n\ndef mv2nan(data, value, copy=True):\n if copy:\n data = data.copy()\n if value is not None:\n try:\n data[data==value] = np.NAN\n except ValueError:\n data = np.array(data, dtype='float')\n data[data==value] = np.NAN\n return data\n\nclass Affine:\n \"\"\"Wrapper around the type of affine transformations used by raster datasets. Initialize with one of the :ref:`supported raster formats `.\n\n .. TODO::\n\n * merge with :func:`python.geo.affine`\n\n \"\"\"\n def __init__(self, raster):\n self.shape, a, self.proj = _raster_info(raster, latlon=True)\n b = np.reshape(a[:6], (2, 3))\n self.mult = b[:, :2]\n self.add = b[:, 2:]\n\n def ij(self, x, y, latlon=False):\n \"\"\"Invert the transform to get raster indexes ('i, j') from coordinates.\n\n :param x: longitude / projected x-dimension\n :type x: number or :class:`~numpy.ndarray`\n :param y: latitude / projected y-dimension\n :type y: number or :class:`~numpy.ndarray`\n :param latlon: If ``True``, ``x`` and ``y`` are lon, lat coordinates, otherwise projected (in the raster's projection)\n :returns: 'i, j' raster indexes corresponding to the coordinates ``x``, ``y``\n :rtype: :obj:`tuple` of numbers or :class:`arrays `\n\n \"\"\"\n s = np.array(x).shape\n if not projected:\n x, y = self.proj(x, y)\n xy = np.vstack([np.array(i).flatten() for i in (x, y)]) - self.add\n return [np.floor(i).reshape(s).astype(int) for i in np.linalg.inv(self.mult).dot(xy)]\n\n\nclass GeoTiff(object):\n \"\"\"Wrapper around a `GDAL Dataset `_, so far used only for GeoTiffs. Init with the filename to be opened, and optional a band number (defaults to 1). Set via :attr:`band_no` to something other than 1 (if desired) **before** using any of the other methods.\n\n .. attribute:: band_no\n\n Index (1-based) of the band to operate on. Change directly before using any of the methods if a band different from 1 is desired.\n\n .. attribute:: proj\n\n :class:`pyproj.Proj` initialized from the GDAL Dataset's :meth:`GetProjection` method.\n\n \"\"\"\n def __init__(self, filename, band=1):\n gdal = import_module('osgeo.gdal')\n osr = import_module('osgeo.osr')\n proj = import_module('pyproj')\n self._ds = gdal.Open(filename)\n self.proj = proj.Proj(osr.SpatialReference(self.wkt).ExportToProj4())\n self.band_no = band\n\n def coords(self, latlon=False):\n \"\"\"Return (lon, lat) tuple of the dataset's coordinates.\n\n :param latlon: if ``True``, return lon/lat coordinates, otherwise projected (as in the original raster)\n :returns: (lon, lat) or (i, j) in projected coordinates\n :rtype: :obj:`tuple`\n\n \"\"\"\n return coords(self._ds, latlon)\n\n @property\n def wkt(self):\n \"WKT string corresponding to dataset's projection.\"\n return self._ds.GetProjection()\n\n @property\n def proj4(self):\n \"Proj.4 string corresponding to dataset's projection.\"\n return self.proj.srs\n\n @property\n def band(self):\n \"Currently set band (corresponding to index :attr:`band_no`).\"\n try:\n return self._band[self.band_no]\n except AttributeError:\n self._band = {self.band_no: self._ds.GetRasterBand(self.band_no)}\n except KeyError:\n self._band[self.band_no] = self._ds.GetRasterBand(self.band_no)\n return self._band[self.band_no]\n\n\n @property\n def data(self):\n \"Data corresponding to band :attr:`band_no` as :class:`numpy.ndarray`, with no-value data replaced by :obj:`numpy.nan` (which means convert the data to float if it isn't already).\"\n try:\n return self._data[self.band_no]\n except AttributeError:\n self._data = {self.band_no: mv2nan(self.band.ReadAsArray(), self.band.GetNoDataValue())}\n except KeyError:\n self._data[self.band_no] = mv2nan(self.band.ReadAsArray(), self.band.GetNoDataValue())\n return self._data[self.band_no]\n\n @property\n def shape(self):\n \"data shape\"\n return (self.band.YSize, self.band.XSize)\n\n def __getattr__(self, name):\n return getattr(self._ds, name)\n\n def __getitem__(self, *args, **kwargs):\n return self.data.__getitem__(*args, **kwargs)\n\n @property\n def cartopy(self):\n \":class:`cartopy.crs.CRS` projection corresponding to dataset.\"\n return proj2cartopy(self.proj4)\n\n def pcolormesh(self, ax=None, background=None, **kwargs):\n \"\"\"Produce :meth:`~matplotlib.pyplot.pcolormesh` plot of the dataset.\n\n :param ax: existing axes or ``None`` (will be created with :func:`~matplotlib.pyplot.axes`)\n :type ax: :class:`cartopy.mpl.geoaxes.GeoAxes`\n :param background: If not ``None``, set background_path and outline_patch to colors which can be specified by passing a :obj:`dict` with values for keys ``patch`` and ``outline``, respectively. The defaults are 'none' and 'w' (transparent and white) and are used if an empte :obj:`dict` (``{}``) is passed.\n :type background: ``None`` or :obj:`dict`\n :returns: plot handle\n :rtype: :class:`~matplotlib.collections.QuadMesh`\n\n \"\"\"\n if ax is None:\n plt = import_module('matplotlib.pyplot')\n ax = plt.axes(projection=self.cartopy)\n i, j = self.coords()\n pl = ax.pcolormesh(i, j, self.data, **kwargs)\n if background is not None:\n ax.background_patch.set_color(background.get('patch', 'none'))\n ax.outline_patch.set_edgecolor(background.get('outline', 'w'))\n return pl\n","sub_path":"python/data/gdal.py","file_name":"gdal.py","file_ext":"py","file_size_in_byte":9186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"582685454","text":"from kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.label import Label\nfrom kivy.graphics import Color, Rectangle\n\nfrom iocompython import Signal\n\nclass HeadingItem(GridLayout):\n def __init__(self, **kwargs):\n self.my_level = 0\n super(HeadingItem, self).__init__(**kwargs)\n self.cols = 2\n self.padding = [8, 6]\n # self.orientation='horizontal'\n self.size_hint_y = None\n self.height = 50 \n\n def set_group_label(self, label1, label2, level):\n self.my_level = level\n if level == 1:\n my_text = '[b][size=20][color=ffffff]' + label1\n if label2 != None:\n my_text += ' ' + label2\n else:\n my_text = '[b][size=18][color=77AAff]' + label1 \n if label2 != None:\n my_text += '[/color] [color=3333ff]' + label2\n\n my_text += '[/color][/size][/b]'\n\n l = Label(text = my_text, markup = True, halign=\"left\")\n self.my_label = l\n l.bind(size=l.setter('text_size')) \n self.add_widget(l)\n\n def on_size(self, *args):\n self.my_draw_background(args)\n\n def on_pos(self, *args):\n self.my_draw_background(args)\n\n def my_draw_background(self, *args):\n self.canvas.before.clear()\n if self.my_level == 2:\n with self.canvas.before:\n Color(0.8, 0.8, 0.8, 0.40)\n mysz = self.size.copy()\n mysz[1] = 1\n Rectangle(pos=self.pos, size=mysz) \n\n","sub_path":"extensions/iocompython/examples/ispy/item_heading.py","file_name":"item_heading.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"142428767","text":"import soundfile as sf\nimport torch\nimport torch.nn.functional as F\nfrom fairseq.data import Dictionary\nfrom bol.utils.helper_functions import move_to_cuda, get_audio_duration\nfrom ._vad_for_long_audios import call_vad\nfrom bol.data import Wav2VecDataLoader\nfrom ._wav2vec2_infer_batch import get_results_for_batch\nimport os\n\ndef get_feature(filepath):\n def postprocess(feats, sample_rate):\n if feats.dim == 2:\n feats = feats.mean(-1)\n\n assert feats.dim() == 1, feats.dim()\n\n with torch.no_grad():\n feats = F.layer_norm(feats, feats.shape)\n return feats\n\n wav, sample_rate = sf.read(filepath)\n feats = torch.from_numpy(wav).float()\n feats = postprocess(feats, sample_rate)\n return feats\n\ndef post_process(sentence: str, symbol: str):\n if symbol == \"sentencepiece\":\n sentence = sentence.replace(\" \", \"\").replace(\"\\u2581\", \" \").strip()\n elif symbol == 'wordpiece':\n sentence = sentence.replace(\" \", \"\").replace(\"_\", \" \").strip()\n elif symbol == 'letter':\n sentence = sentence.replace(\" \", \"\").replace(\"|\", \" \").strip()\n elif symbol == \"_EOW\":\n sentence = sentence.replace(\" \", \"\").replace(\"_EOW\", \" \").strip()\n elif symbol is not None and symbol != 'none':\n sentence = (sentence + \" \").replace(symbol, \"\").rstrip()\n return sentence\n\n\n\ndef get_results_for_single_file(wav_path,dict_path,generator,model,use_cuda=False, half=None):\n sample = dict()\n net_input = dict()\n target_dict = Dictionary.load(dict_path)\n\n ## Experimental\n\n duration = get_audio_duration(wav_path)\n file_paths = []\n if duration > 15:\n file_paths = call_vad(wav_path)\n\n filtered_file_paths = []\n # for file in file_paths:\n # if get_audio_duration(file) > 15:\n # print(\"Skipping \", file)\n # os.system('rm '+file)\n # else:\n # filtered_file_paths.append(file)\n\n file_path = \"/\".join(file_paths[0].split('/')[:-1])\n dataloader_obj = Wav2VecDataLoader(train_batch_size = 4, num_workers= 4 ,file_data_path = file_path)\n dataloader = dataloader_obj.get_file_data_loader()\n\n\n text = get_results_for_batch(dataloader, dict_path, generator, model, use_cuda)\n complete_text = []\n local_dict = {}\n\n for filename, local_text in text:\n local_file=int(filename.split('/')[-1].split('.')[0].split('-')[1])\n local_dict[local_file] = local_text\n\n sorted_dict = dict(sorted(local_dict.items()))\n print(sorted_dict)\n for key, value in sorted_dict.items():\n complete_text.append(value)\n print(complete_text)\n\n print(\" \".join(complete_text))\n return complete_text\n\n ## Experimental\n\n\n feature = get_feature(wav_path)\n \n model.eval()\n \n if half:\n net_input[\"source\"] = feature.unsqueeze(0).half()\n else:\n net_input[\"source\"] = feature.unsqueeze(0)\n\n padding_mask = torch.BoolTensor(net_input[\"source\"].size(1)).fill_(False).unsqueeze(0)\n\n net_input[\"padding_mask\"] = padding_mask\n sample[\"net_input\"] = net_input\n sample = move_to_cuda(sample) if use_cuda else sample\n\n with torch.no_grad():\n hypo = generator.generate(model, sample, prefix_tokens=None)\n hyp_pieces = target_dict.string(hypo[0][0][\"tokens\"].int().cpu())\n text=post_process(hyp_pieces, 'letter')\n\n return text\n","sub_path":"bol/inference/_wav2vec2_infer_single.py","file_name":"_wav2vec2_infer_single.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"374166067","text":"class Solution(object):\n def minCostClimbingStairs(self, cost):\n \"\"\"\n :type cost: List[int]\n :rtype: int\n \"\"\"\n if len(cost)<=2:\n return 0\n minCost = [0, 0, 0]\n for i in range(2, len(cost)+1):\n minCost[0], minCost[1] = minCost[1], minCost[2]\n minCost[2] = min(\n cost[i-2]+minCost[0],\n cost[i-1]+minCost[1],\n )\n return minCost[2]\n\ns = Solution()\nprint(s.minCostClimbingStairs(\n [10, 15, 20]\n))","sub_path":"py.old/Prob7/Prob746.py","file_name":"Prob746.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"120028093","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:\n if not nums:\n return None\n \n max_val= max(nums)\n idx = nums.index(max_val)\n \n root = TreeNode(val=max_val, left=None, right=None)\n \n \n def create_tree(nums, root, idx):\n left_arr = nums[:idx]\n right_arr = nums[idx+1:]\n \n if left_arr:\n max_val = max(left_arr)\n idx = left_arr.index(max_val)\n root.left = TreeNode(val=max_val, left=None, right=None)\n create_tree(left_arr, root.left, idx)\n \n if right_arr:\n max_val = max(right_arr)\n idx = right_arr.index(max_val)\n root.right = TreeNode(val=max_val, left=None, right=None)\n create_tree(right_arr, root.right, idx)\n \n create_tree(nums, root, idx)\n return root\n\n\n\n# Faster - use dict to get loc w/ O(1)\nclass Solution:\n def constructMaximumBinaryTree(self, nums: List[int]) -> Optional[TreeNode]:\n if not nums:\n return None\n \n # use dict to get location w/ O(1) \n locations = dict()\n for i in range(len(nums)):\n locations[nums[i]] = i\n \n \n def helper(start, end):\n if start > end: # base case 0: invalid\n return None\n elif start == end: # base case 1: Just 1 element\n return TreeNode(nums[start])\n \n max_element = max(nums[start: end + 1]) # O(n): N will reduce each time\n max_index = locations[max_element] # O(1) lookup\n \n root = TreeNode(max_element)\n root.left, root.right = helper(start, max_index - 1), helper(max_index + 1, end)\n return root\n \n return helper(0, len(nums) - 1)\n\n","sub_path":"LeetCode-Sol/Medium/654-Maximum-Binary-Tree.py","file_name":"654-Maximum-Binary-Tree.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"295148450","text":"\nimport sys\nfrom collections import OrderedDict\n\nfrom .shared import *\n\nfetch_width_from_bits = { 8: 'byte', 16: 'word', 32: 'dword', 64: 'qword' }\n\ndef get_min_check_width(libraries, hashfn):\n minv = 8 # can't go lower\n for k, v in libraries.items():\n for sym in v:\n hv = hashfn(sym)\n #eprintf(\"hash: 0x%08x of %s\"%(hv,sym))\n if (hv & 0xffffffff) == 0:\n # this should (hopefully) NEVER happen\n error(\"E: Aiee, all-zero hash for sym '%s'!\" % sym)\n elif (hv & 0xFFFF) == 0:\n #eprintf(\"32-bit hash\")\n minv = max(minv, 32) # need at least 32 bits\n elif (hv & 0xFF) == 0:\n #eprintf(\"16-bit hash\")\n minv = max(minv, 16) # need at least 16 bits\n\n return minv\n\ndef sort_imports(libraries, hashfn):\n #eprintf(\"in: \" + str(libraries))\n\n # DON'T DO THIS: weak symbol stuff etc.\n ## sort libs by name length, then by name\n #ll = sorted(libraries.items(), key=lambda ls: (len(ls[0]), ls[0]))\n\n #for i in range(len(ll)):\n # # sort symbols by hash value\n # ll[i] = (ll[i][0], sorted(ll[i][1], key=lambda sr: hashfn(sr[0])))\n\n #eprintf(\"out:\" + str(dict(ll)))\n\n # insertion order only works with python >=3.6!\n #if sys.version_info < (3, 6): return OrderedDict(ll)\n #else: return dict(ll)\n\n for k, v in libraries.items():\n libraries[k] = OrderedDict(sorted(v.items(), key=lambda sr: hashfn(sr[0])))\n\n return libraries\n\ndef output_x86(libraries, nx, hashid, outf, det):\n outf.write('; vim: set ft=nasm:\\n') # be friendly\n\n defff = define_for_hash[hashid]\n if defff is not None:\n outf.write('%define {} 1\\n'.format(defff))\n if nx:\n outf.write('%define USE_NX 1\\n')\n\n hashfn = get_hash_fn(hashid)\n if det: libraries = sort_imports(libraries, hashfn)\n\n outf.write('%%define HASH_END_TYP %s\\n' %\n fetch_width_from_bits[get_min_check_width(libraries, hashfn)])\n\n usedrelocs = set()\n for library, symrels in libraries.items():\n for sym, reloc in symrels.items():\n usedrelocs.add(reloc)\n\n if not(nx) and 'R_386_PC32' in usedrelocs and 'R_386_GOT32X' in usedrelocs:\n error(\"Using a mix of R_386_PC32 and R_386_GOT32X relocations! \"+\\\n \"Please change a few C compiler flags and recompile your code.\")\n\n\n use_jmp_bytes = not nx and 'R_386_PC32' in usedrelocs\n if use_jmp_bytes:\n outf.write('%define USE_JMP_BYTES 1\\n')\n\n outf.write('bits 32\\n')\n\n shorts = { l: l.split('.', 1)[0].lower().replace('-', '_') for l in libraries }\n\n outf.write('%include \"header32.asm\"\\n')\n outf.write('dynamic.needed:\\n')\n for library in libraries:\n outf.write('dd 1;DT_NEEDED\\n')\n outf.write('dd (_symbols.{} - _strtab)\\n'.format(shorts[library]))\n outf.write(\"\"\"\\\ndynamic.end:\n%ifndef UNSAFE_DYNAMIC\n dd DT_NULL\n%endif\n\"\"\")\n\n outf.write('[section .rodata.neededlibs]\\n')\n outf.write('global _strtab\\n')\n outf.write('_strtab:\\n')\n for library, symrels in libraries.items():\n outf.write('\\t_symbols.{}: db \"{}\",0\\n'.format(shorts[library], library))\n\n outf.write('[section .data.smolgot]\\n')\n if not nx:\n outf.write('[section .text.smolplt]\\n')\n\n outf.write('global _symbols\\n')\n outf.write('_symbols:\\n')\n for library, symrels in libraries.items():\n for sym, reloc in symrels.items():\n # meh\n if reloc != 'R_386_PC32' and reloc != 'R_386_GOT32X':\n eprintf('Relocation type %s of symbol %s unsupported!' % (reloc, sym))\n sys.exit(1)\n\n if nx:\n outf.write(\"\\t\\t_symbols.{lib}.{name}: dd 0x{hash:x}\"\\\n .format(lib=shorts[library],name=sym,hash=hashfn(sym)).lstrip('\\n'))\n else:\n outf.write((\"\"\"\\\n\\t\\tglobal {name}\n\\t\\t{name}:\"\"\" + (\"\\n\\t\\t\\tdb 0xE9\" if use_jmp_bytes else '') + \"\"\"\n\\t\\t\\tdd 0x{hash:x}\n\"\"\").format(name=sym, hash=hashfn(sym)).lstrip('\\n'))\n\n outf.write('db 0\\n')\n outf.write('_symbols.end:\\n')\n\n if nx:\n outf.write('global _smolplt\\n')\n outf.write('_smolplt:\\n')\n for library, symrels in libraries.items():\n for sym, reloc in symrels.items():\n outf.write(\"\"\"\\\n[section .text.smolplt.{name}]\nglobal {name}\n{name}:\n\\tjmp [dword _symbols.{lib}.{name}]\n\"\"\".format(lib=shorts[library],name=sym).lstrip('\\n'))\n\n outf.write('_smolplt.end:\\n')\n\n outf.write('%include \"loader32.asm\"\\n')\n# end output_x86\n\n\ndef output_amd64(libraries, nx, hashid, outf, det):\n if hashid == HASH_BSD2:\n error(\"--hash16 not supported yet for x86_64 outputs.\")\n\n outf.write('; vim: set ft=nasm:\\n')\n outf.write('bits 64\\n')\n\n defff = define_for_hash[hashid]\n if defff is not None:\n outf.write('%define {} 1\\n'.format(defff))\n if nx:\n outf.write('%define USE_NX 1\\n')\n\n hashfn = get_hash_fn(hashid)\n if det: libraries = sort_imports(libraries, hashfn)\n\n outf.write('%%define HASH_END_TYP %s\\n' %\n fetch_width_from_bits[get_min_check_width(libraries, hashfn)])\n\n shorts = { l: l.split('.', 1)[0].lower().replace('-', '_') for l in libraries }\n\n outf.write('%include \"header64.asm\"\\n')\n outf.write('dynamic.needed:\\n')\n for library, symrels in libraries.items():\n if (len(symrels) > 0):\n outf.write(' dq 1;DT_NEEDED\\n')\n outf.write(' dq (_symbols.{} - _strtab)\\n'.format(shorts[library]))\n outf.write(\"\"\"\\\ndynamic.symtab:\n dq DT_SYMTAB ; d_tag\n dq 0 ; d_un.d_ptr\ndynamic.end:\n%ifndef UNSAFE_DYNAMIC\n dq DT_NULL\n%endif\n\"\"\")\n\n outf.write('[section .rodata.neededlibs]\\n')\n\n outf.write('global _strtab\\n')\n outf.write('_strtab:\\n')\n for library, symrels in libraries.items():\n if (len(symrels) > 0):\n outf.write('\\t_symbols.{}: db \"{}\",0\\n'.format(shorts[library], library))\n\n outf.write('[section .data.smolgot]\\n')\n\n outf.write('global _symbols\\n')\n outf.write('_symbols:\\n')\n for library, symrels in libraries.items():\n for sym, reloc in symrels.items():\n if reloc not in ['R_X86_64_PLT32', 'R_X86_64_GOTPCRELX', \\\n 'R_X86_64_REX_GOTPCRELX', 'R_X86_64_GOTPCREL']:\n error('Relocation type %s of symbol %s unsupported!' % (reloc, sym))\n\n if reloc in ['R_X86_64_GOTPCRELX', 'R_X86_64_REX_GOTPCRELX', \\\n 'R_X86_64_GOTPCREL']:\n outf.write(\"\"\"\nglobal {name}\n{name}:\n\"\"\".format(name=sym).lstrip('\\n'))\n\n outf.write('\\t\\t_symbols.{lib}.{name}: dq 0x{hash:x}\\n'\\\n .format(lib=shorts[library],name=sym,hash=hashfn(sym)))\n\n outf.write('db 0\\n')\n outf.write('_symbols.end:\\n')\n\n outf.write('global _smolplt\\n')\n outf.write('_smolplt:\\n')\n for library, symrels in libraries.items():\n for sym, reloc in symrels.items():\n if reloc == 'R_X86_64_PLT32':\n outf.write(\"\"\"\\\n[section .text.smolplt.{name}]\nglobal {name}\n{name}:\n\\tjmp [rel _symbols.{lib}.{name}]\n\"\"\".format(lib=shorts[library],name=sym).lstrip('\\n'))\n\n outf.write('_smolplt.end:\\n')\n outf.write('%include \"loader64.asm\"\\n')\n# end output_amd64\n\n\ndef output(arch, libraries, nx, hashid, outf, det):\n if arch == 'i386': output_x86(libraries, nx, hashid, outf, det)\n elif arch == 'x86_64': output_amd64(libraries, nx, hashid, outf, det)\n else:\n error(\"E: cannot emit for arch '%s'\" % str(arch))\n\n","sub_path":"smol/emit.py","file_name":"emit.py","file_ext":"py","file_size_in_byte":7566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"100743156","text":"#!/usr/bin/env python\n\n\"\"\"\nTest module for demo.py.\n\nRuns various tests on the demo module. Simply run this module to test\nthe demo.py module.\n\"\"\"\n\nimport test\nimport demo\n\ndef test_echo():\n print(\"In echo test\")\n echo = demo.echo(\"hej\")\n test.assert_equal(\"hej\", echo)\n test.assert_not_equal(None, echo)\n\ndef test_add():\n print(\"In add test\")\n added = demo.add(\"hej \", \"hopp\")\n test.assert_equal(\"hej hopp\", added)\n test.assert_not_equal(\"hej\", added)\n\ndef run_module_tests():\n test.run_tests([test_echo,\n test_add])\n\nif __name__ == \"__main__\":\n run_module_tests()\n","sub_path":"2.3/testdemo/test/demo_test.py","file_name":"demo_test.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"314126862","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# -------------------------------------#\n# YOLO: no attention version\n# -------------------------------------#\nimport os\nimport sys\nsys.path.remove('/opt/ros/melodic/lib/python2.7/dist-packages') # in order to import cv2 under python3\nimport cv2\nsys.path.append('/opt/ros/melodic/lib/python2.7/dist-packages') # append back in order to import rospyimport numpy as np\nimport colorsys\nimport os\nimport torch\nimport torch.nn as nn\nfrom noattneck import YoloBody\nfrom utils.utils import *\nfrom yolo_layer import *\nimport sys\nfrom sensor_msgs.msg import Image\nimport matplotlib.pyplot as plt\n\n\nimport rospy\nfrom cv_bridge import CvBridge\n\n\nclass Inference(object):\n def __init__(self, **kwargs):\n # ros settings\n image_topic = rospy.get_param(\"~image_topic\",\"\")\n self._cv_bridge = CvBridge()\n # self._pub = rospy.Publisher('yolo_result', Int16, queue_size=1)\n\n # yolo model settings\n self.model_path = kwargs['model_path']\n self.anchors_path = kwargs['anchors_path']\n self.classes_path = kwargs['classes_path']\n self.model_image_size = kwargs['model_image_size']\n self.confidence = kwargs['confidence']\n self.cuda = kwargs['cuda']\n\n self.class_names = self.get_class()\n self.anchors = self.get_anchors()\n print(self.anchors)\n self.net = YoloBody(3, len(self.class_names)).eval()\n self.load_model_pth(self.net, self.model_path)\n\n if self.cuda:\n self.net = self.net.cuda()\n self.net.eval()\n\n print('Finished!')\n\n self.yolo_decodes = []\n anchor_masks = [[0,1,2],[3,4,5],[6,7,8]]\n for i in range(3):\n head = YoloLayer(self.model_image_size, anchor_masks, len(self.class_names),\n self.anchors, len(self.anchors)//2).eval()\n self.yolo_decodes.append(head)\n\n\n print('{} model, anchors, and classes loaded.'.format(self.model_path))\n self._sub = rospy.Subscriber('/usb_cam/image_raw', Image, self.callback, queue_size=1)\n\n def callback(self,image_msg):\n ##############################################\n # convert format\n cv_image = self._cv_bridge.imgmsg_to_cv2(image_msg, \"rgb8\")\n # frame=np.uint8(cv_image)\n boxes = model.detect_image(cv_image)\n img=plot_boxes_cv2(cv_image, boxes, class_names=self.class_names)\n plt.ion()\n plt.figure(1)\n plt.imshow(img)\n plt.axis('off')\n plt.pause(0.5)\n plt.ioff()\n # img=cv2.cvtColor(img,cv2.COLOR_RGB2BGR)\n # cv2.imshow('YOLO',img)\n # cv2.waitKey(1)\n # cv2.destroyAllWindows()\n\n\n def main(self):\n rospy.spin()\n\n def load_model_pth(self, model, pth):\n print('Loading weights into state dict, name: %s' % (pth))\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model_dict = model.state_dict()\n pretrained_dict = torch.load(pth, map_location=device)\n matched_dict = {}\n\n for k, v in pretrained_dict.items():\n if np.shape(model_dict[k]) == np.shape(v):\n matched_dict[k] = v\n else:\n print('un matched layers: %s' % k)\n print(len(model_dict.keys()), len(pretrained_dict.keys()))\n print('%d layers matched, %d layers miss' % (\n len(matched_dict.keys()), len(model_dict) - len(matched_dict.keys())))\n model_dict.update(matched_dict)\n model.load_state_dict(pretrained_dict)\n print('Finished!')\n return model\n\n # ---------------------------------------------------#\n # get class names\n # ---------------------------------------------------#\n def get_class(self):\n classes_path = os.path.expanduser(self.classes_path)\n with open(classes_path) as f:\n class_names = f.readlines()\n class_names = [c.strip() for c in class_names]\n return class_names\n\n # ---------------------------------------------------#\n # get bounding boxes \n # ---------------------------------------------------#\n def get_anchors(self):\n anchors_path = os.path.expanduser(self.anchors_path)\n with open(anchors_path) as f:\n anchors = f.readline()\n anchors = [float(x) for x in anchors.split(',')]\n return anchors\n #return np.array(anchors).reshape([-1, 3, 2])[::-1, :, :]\n\n\n # ---------------------------------------------------#\n # making detection\n # ---------------------------------------------------#\n def detect_image(self, image_src):\n h, w, _ = image_src.shape\n image = cv2.resize(image_src, (416, 416))\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n img = np.array(image, dtype=np.float32)\n img = np.transpose(img / 255.0, (2, 0, 1))\n images = np.asarray([img])\n\n with torch.no_grad():\n images = torch.from_numpy(images)\n if self.cuda:\n images = images.cuda()\n outputs = self.net(images)\n\n output_list = []\n for i in range(3):\n output_list.append(self.yolo_decodes[i](outputs[i]))\n output = torch.cat(output_list, 1)\n print(output.shape)\n batch_detections = non_max_suppression(output, len(self.class_names),\n conf_thres=self.confidence,\n nms_thres=0.1)\n # print(batch_detections) \n # nothing is detected \n if batch_detections == [None]: \n return None \n boxes = [box.cpu().numpy() for box in batch_detections]\n print(boxes[0])\n return boxes[0]\n\nif __name__ == '__main__':\n params = {\n \"model_path\": '/home/jing/ros_project/src/robot_learning/object_detect/scripts/pth/yolo4_weights.pth',\n \"anchors_path\": '/home/jing/ros_project/src/robot_learning/object_detect/scripts/work_dir/yolo_anchors_coco.txt',\n \"classes_path\": '/home/jing/ros_project/src/robot_learning/object_detect/scripts/work_dir/coco_classes.txt',\n \"model_image_size\": (416, 416, 3),\n \"confidence\": 0.4,\n \"cuda\": False\n }\n\n global model\n model = Inference(**params)\n\n rospy.init_node('object_detect_node')\n rospy.loginfo(\"yolo has started.\")\n\n model.main()\n\n \n\n ","sub_path":"src/robot_learning/object_detect/scripts/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":6440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"512368217","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\ndef median(*args):\n if args:\n values = [float(arg) for arg in args]\n values.sort()\n\n n = len(values)\n idx = n // 2\n if n % 2:\n return values[idx]\n else:\n return (values[idx - 1] + values[idx]) / 2\n else:\n return None\n\n\nif __name__ == \"__main__\":\n print(median())\n print(median(3, 7, 1, 6, 9))\n print(median(1, 5, 8, 4, 3, 9))","sub_path":"tasks/pr_1.py","file_name":"pr_1.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"341629881","text":"#coding:utf-8\n\nimport os\nfrom flask import jsonify, Response, abort, request\nimport json\nfrom pymongo import MongoClient\nfrom app import app, db\nfrom app.routes import tweet\n\n# connection = MongoClient('localhost', 27017)\npersonal = db.personal\n\n@app.route(\"/personal_map/\", methods=[\"GET\"])\ndef show_pmap(id):\n return app.send_static_file(\"index.html\")\n\n@app.route(\"/personal/\", methods=[\"GET\"])\ndef get_personal(id):\n personal_data = personal.find_one({\"id\":int(id)})\n if personal_data == None:\n abort(404)\n del personal_data[\"_id\"]\n return json.dumps(personal_data)\n\n@app.route(\"/personal/post\", methods=[\"POST\"])\ndef post_personal():\n _id = personal.find().count() + 1\n data = json.loads(request.data)\n data[\"id\"] = _id\n personal.insert(data)\n tweet.tweet_post(_id, data[\"title\"])\n return str(_id)\n\n@app.route(\"/personal/update\", methods=[\"POST\"])\ndef update_personal():\n data = json.loads(request.data)\n personal.update({\"id\":1},data)\n return \"OK\"\n","sub_path":"gron/app/models/personal.py","file_name":"personal.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"210494904","text":"from .plugins import *\nimport time\nimport pickle\nimport os\nimport logging\nimport ws.bad as bad\nimport urllib.error\nimport http.client\nfrom .tools import misc\nimport multiprocessing\nimport datetime\n\n\ndef generate_forecast_filepath(pname, city, basepath=''):\n \"\"\"Generate forecast filepath.\n\n basepath/city/pname\n \"\"\"\n posix_time = time.time()\n utc_posix_time = posix_time + time.timezone\n\n forecast_dir = os.path.join(basepath, city, pname)\n # exist_ok=True to make the function thread safe.\n os.makedirs(forecast_dir, exist_ok=True)\n\n filename = str(utc_posix_time).replace('.', 's', 1) + '.forecast'\n forecast_path = os.path.join(forecast_dir, filename)\n\n return forecast_path\n\n\ndef get_citylist():\n \"\"\"Return list with all city names.\"\"\"\n # XXX should we use another format than pickle?\n fp = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'citylist.dump')\n citylist = pickle.load(open(fp, 'rb'))\n citylist = [str(i) for i in citylist]\n\n return citylist\n\n\ndef store_forecast(city, pname, basepath=''):\n \"\"\"Store forecast for city from plugin pname.\"\"\"\n logging.debug('args city=%s pname=%s basepath=%s', city, pname,\n basepath)\n\n forecast_data = None\n p = load_plugin(str(pname))\n\n try:\n url = p.build_url(str(city))\n except bad.City:\n logging.error('plugin %s cannot deal with city %s', pname, city)\n return -1\n\n failcounter = 0\n continue_loop = True\n while continue_loop:\n try:\n forecast_data = misc.download_from_url(url)\n continue_loop = False\n if failcounter == 0:\n logging.info('Queried %s for %s successfully', pname, city)\n except urllib.error.HTTPError as err:\n failcounter += 1\n logging.error(\"%s for url %s\", err, url)\n logging.info(\"Trying again...\")\n logging.info(\"This was attempt number \" +str(failcounter))\n except http.client.IncompleteRead as err:\n logging.error(\"%s\", err)\n\n if failcounter > 0 and continue_loop == False:\n logging.info(\"SUCCESS! This time querying %s worked\", pname)\n\n if continue_loop == False:\n break\n\n filepath = generate_forecast_filepath(pname, city, basepath)\n misc.save_to_disk(forecast_data, filepath)\n\n return forecast_data\n\n\ndef store_forecasts_loop(cities, pname, basepath=''):\n try:\n for city in list(cities):\n store_forecast(city, pname, basepath)\n except KeyboardInterrupt as err:\n raise KeyboardInterrupt(err)\n\n\ndef store_forecasts(cities, pnames, basepath=''):\n \"\"\"store_forecast but takes list of cities and plugin names.\n\n Each plugin gets its own process. This way a plugin can rate limit without\n blocking the others.\n \"\"\"\n for pname in list(pnames):\n p = multiprocessing.Process(target=store_forecasts_loop,\n args=(cities, pname, basepath))\n p.start()\n\n\ndef forecasts_newer_than(newer_than, basepath=''):\n forecast_lists = {}\n for city in os.listdir(basepath):\n for provider in os.listdir(os.path.join(basepath, city)):\n if provider not in forecast_lists:\n forecast_lists[provider] = []\n for forecast in os.listdir(os.path.join(basepath, city, provider)):\n utc_posix_time = float(forecast.replace('s', '.',\n 1)[:-len('.forecast')])\n if utc_posix_time > newer_than:\n filepath = os.path.join(basepath, city, provider, forecast)\n with open(filepath, 'r') as fd:\n forecast_lists[provider].append([fd.read(), city,\n datetime.datetime.fromtimestamp(utc_posix_time)])\n\n return forecast_lists\n\n\ndef pandize_plugin_forecasts(forecast_lists, pname, database_filepath):\n p = load_plugin(str(pname))\n for forecast_list in forecast_lists:\n logging.debug('pname %s city %s date %s', pname, forecast_list[1],\n forecast_list[2])\n pandas_table = p.pandize(*forecast_list)\n # XXX: maltimore works on this function\n #insert_into_master_frame(pandas_table, database_filepath)\n\n\ndef pandize_forecasts(pnames, database_filepath='', basepath='', newer_than=0):\n forecast_lists = forecasts_newer_than(newer_than, basepath)\n for pname in list(pnames):\n pandize_plugin_forecasts(forecast_lists[pname], pname,\n database_filepath)\n","sub_path":"ws/plugins_master.py","file_name":"plugins_master.py","file_ext":"py","file_size_in_byte":4607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"504290024","text":"import random\n\nfrom questions import PhotoMultipleChoiceQuestion\nfrom utils import get_paged_data, get_captions, get_caption, get_sized_photo, QuestionNotFeasibleException\n\ndef get_captioned_photo(photos):\n for _ in range(100):\n photo = random.choice(photos)\n if get_caption(photo):\n return photo\n raise QuestionNotFeasibleException()\n\nclass PhotoCaptionQuestion(PhotoMultipleChoiceQuestion):\n QUESTION_TEXT = \\\n 'Which of the following is the caption for the above picture?'\n\n @classmethod\n def gen(cls, self_data, friend_data):\n photos = get_paged_data(friend_data, 'photos')\n photo = get_captioned_photo(photos)\n\n return cls(\n get_sized_photo(photo),\n [get_caption(photo)],\n get_captions(photos),\n )\n","sub_path":"Lowdown_Backend/Lowdown/Facebook_App/questions/photo_caption_question.py","file_name":"photo_caption_question.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"40038237","text":"import numpy as np\nimport pandas as pd\n\ndf = pd.read_csv('DBChain.csv')\nITC = np.array(df['Introduction to Computer Science'])\nCP = np.array(df['Computer Programming'])\nDS = np.array(df['Data Structures'])\nDB = np.array(df['Database Systems'])\nAllGPAs = []\nfor i in range(len(ITC)):\n AllGPAs.append(ITC[i])\n AllGPAs.append(CP[i])\n AllGPAs.append(DS[i])\nGPAs = np.array(AllGPAs)\n\nfor i in range(len(GPAs)):\n if GPAs[i] == 1.00:\n GPAs[i] = 1\n elif GPAs[i] == 1.33:\n GPAs[i] = 2\n elif GPAs[i] == 1.67:\n GPAs[i] = 3\n elif GPAs[i] == 2.0:\n GPAs[i] = 4\n elif GPAs[i] == 2.33:\n GPAs[i] = 5\n elif GPAs[i] == 2.67:\n GPAs[i] = 6\n elif GPAs[i] == 3.0:\n GPAs[i] = 7\n elif GPAs[i] == 3.33:\n GPAs[i] = 8\n elif GPAs[i] == 3.67:\n GPAs[i] = 9\n elif GPAs[i] == 4.0:\n GPAs[i] = 10\nGPAs = GPAs.reshape(int(len(AllGPAs)/3), 3)\n\nfor i in range(len(DB)):\n if DB[i] == 1.0:\n DB[i] = 1\n elif DB[i] == 1.33:\n DB[i] = 1\n elif DB[i] == 1.67:\n DB[i] = 2\n elif DB[i] == 2.0:\n DB[i] = 2\n elif DB[i] == 2.33:\n DB[i] = 2\n elif DB[i] == 2.67:\n DB[i] = 3\n elif DB[i] == 3.0:\n DB[i] = 3\n elif DB[i] == 3.33:\n DB[i] = 3\n elif DB[i] == 3.67:\n DB[i] = 4\n elif DB[i] == 4.0:\n DB[i] = 4\nfrom sklearn.naive_bayes import GaussianNB\nclf = GaussianNB()\n\n#from sklearn.naive_bayes import MultinomialNB\n#clf = MultinomialNB()\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\nX = GPAs\ny = DB\nkf = KFold(n_splits=20)\n#kf.get_n_splits(X)\nacc = []\nfor train_index, test_index in kf.split(X):\n #print(\"TRAIN:\", train_index, \"TEST:\", test_index)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n clf.fit(X_train, y_train)\n y_test = y_test.ravel()\n prediction = clf.predict(X_test)\n prediction = prediction.ravel()\n from sklearn.metrics import accuracy_score\n acc.append(accuracy_score(y_test, prediction)*100)\n #print(accuracy_score(y_test, prediction)*100)\n #print(accuracy_score(y_test, prediction, normalize=False)) #If False, return the number of correctly classified samples. Otherwise, return the fraction of correctly classified samples.\n\nprint(np.mean(acc))\n","sub_path":"ModelDBPredictorKFold.py","file_name":"ModelDBPredictorKFold.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"635998278","text":"class Solution:\n def lengthOfLastWord(self, s):\n s=s.strip()\n l1=[]\n l1=s.split(' ')\n if(len(l1)>=1):\n return (len(l1[-1]))\n else:\n return 0\n\n\n \n\ns=Solution()\nprint(s.lengthOfLastWord('a '))\n","sub_path":"LengthofLastword.py","file_name":"LengthofLastword.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"33526997","text":"import itertools\nimport os\nimport pandas\nimport sys\nimport unittest\nimport data_summary\n\nTESTS_DIR = 'testcases/'\nACTUAL_XLS_PATH = 'actual.xls'\nEXPECTED_XLS_PATH = 'test_expected.xls'\n\nclass TestDataSummary(unittest.TestCase):\n def __init__(self, testName, dataDir, expectedXlsPath, actualXlsPath, methodName='runTest'):\n super(TestDataSummary, self).__init__(methodName)\n self.longMessage = True\n\n self.testName = testName\n self.dataDir = dataDir\n self.expectedXlsPath = expectedXlsPath\n self.actualXlsPath = actualXlsPath\n\n def tearDown(self):\n os.remove(self.actualXlsPath)\n\n def assertExcelEqual(self, actual, expected):\n # assert actual and expected excel docs have the same # of columns\n self.assertEqual(\n len(actual.columns), \n len(expected.columns), \n \"test '%s' : column count mismatch\" % (self.testName,)\n )\n\n for actual_column, expected_column in zip(actual.columns, expected.columns):\n # assert that the column names are equal\n self.assertEqual(\n actual_column, \n expected_column,\n \"test '%s' : column name mismatch\" % (self.testName,)\n )\n\n # assert that the column values are equal\n actual_series = [str(i) for i in actual[actual_column]]\n expected_series = [str(i) for i in expected[expected_column]]\n\n self.assertSequenceEqual(\n actual_series, \n expected_series, \n \"test '%s' : value mismatch at column '%s'\" % (self.testName, expected_column,)\n )\n\n def runTest(self):\n data_summary.main(self.dataDir, self.actualXlsPath)\n\n # assert that the actual excel doc was produced\n self.assertTrue(os.path.isfile(self.actualXlsPath))\n\n expected = pandas.read_excel(self.expectedXlsPath, data_summary.SHEET_NAME)\n actual = pandas.read_excel(self.actualXlsPath, data_summary.SHEET_NAME)\n\n # assert that the two excel docs are equal\n self.assertExcelEqual(expected, actual)\n\ndef tests(testsDir, actualXlsPath, expectedXlsPath):\n for f in os.listdir(testsDir):\n testName = f\n dataDir = os.path.join(testsDir, f)\n _expectedXlsPath = os.path.join(dataDir, expectedXlsPath)\n\n if os.path.isdir(dataDir) == False:\n continue\n\n if os.path.isfile(_expectedXlsPath) == False:\n continue\n\n test = TestDataSummary(testName, dataDir, _expectedXlsPath, actualXlsPath)\n yield test\n\ndef main(testsDir, actualXlsPath, expectedXlsPath):\n t = tests(testsDir, actualXlsPath, expectedXlsPath)\n suite = unittest.TestSuite(t)\n unittest.TextTestRunner().run(suite)\n\nif __name__ == '__main__':\n main(TESTS_DIR, ACTUAL_XLS_PATH, EXPECTED_XLS_PATH)\n","sub_path":"data_analysis/test_data_summary.py","file_name":"test_data_summary.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"218887999","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 22 15:32:02 2018\n\n@author: auri\n\"\"\"\n\n#### function\nimport cv2\nimport numpy as np\n\ndef test_data(x,resize_dim=None,path=None):\n\n X=[] # initialize empty list for resized images\n img=cv2.imread(path,cv2.IMREAD_COLOR) # images loaded in color (BGR)\n #img = cv2.fastNlMeansDenoisingColored(img,None,10,10,7,21)\n img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # cnahging colorspace to GRAY\n if resize_dim is not None:\n img=cv2.resize(img,(resize_dim,resize_dim),interpolation=cv2.INTER_AREA) # resize image to 28x28\n #X.append(np.expand_dims(img,axis=2)) # expand image to 28x28x1 and append to the list.\n gaussian_3 = cv2.GaussianBlur(img, (9,9), 10.0) #unblur\n img = cv2.addWeighted(img, 1.5, gaussian_3, -0.5, 0, img)\n kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]]) #filter\n img = cv2.filter2D(img, -1, kernel)\n thresh = 200\n maxValue = 255\n #th, img = cv2.threshold(img, thresh, maxValue, cv2.THRESH_BINARY);\n ret,img = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\n X.append(img) # expand image to 28x28x1 and append to the list\n # display progres\n \n X=np.array(X) # tranform list to numpy array\n # if path_label is None:\n return X\n\nx_auga_test = test_data()","sub_path":"test_image.py","file_name":"test_image.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"597808424","text":"import numpy as np\nfrom scipy.interpolate import interp1d\nfrom constants import *\nfrom math import isnan\nfrom random import shuffle\n\n\ndef read_single_data(source_path, meas_indices):\n\n # print(\"\\nRead data ...\")\n # print(\"Source path:\" + source_path)\n raw_data = np.loadtxt(source_path, skiprows=1, dtype=str, delimiter=\",\")\n\n content = raw_data[:, 1:]\n content = content.astype(np.float)\n\n data = np.reshape([content[:, meas_indices[0]]], (len(content), 1)) # after filling -> [[data1], [data2], ...]\n\n if len(meas_indices) > 1:\n for i in range(1, len(meas_indices)):\n data = np.column_stack((data, content[:, meas_indices[i]]))\n\n data = np.asarray(data, dtype=float)\n # replace nan values, that should not be in there\n data = replace_nan(data, replacement=np.zeros((len(meas_indices),)))\n\n return data\n\n\ndef find_nearest(array, value):\n\n index = np.abs((array - value)).argmin()\n return index\n\n\ndef find_inside(array, length, value):\n\n index = -1\n for i in range(len(array)):\n if array[i] < value < array[i] + length[i]:\n index = i\n break\n return index\n\n\ndef find_equal(array, value):\n\n index = -1\n for i in range(len(array)):\n if array[i] == value:\n index = i\n break\n return index\n\n\ndef ana_2_dig(data, threshold, min_val, max_val, min_duration_low, min_duration_high):\n\n new = []\n high = False\n\n # digitize data\n for i in range(len(data)):\n\n if (data[i] > threshold and not high) or (data[i] > 0 and high):\n new.append(max_val)\n high = True\n\n else:\n new.append(min_val)\n high = False\n\n # filter highs with duration shorter than minimum duration\n start_high = 0\n high = False\n new = np.asarray(new)\n\n for i in range(1, len(new)):\n\n # detect rising edge\n if new[i-1] == min_val and new[i] == max_val and not high:\n start_high = i\n high = True\n\n # detect falling edge\n elif new[i-1] == max_val and new[i] == min_val and high:\n high = False\n start_low = i\n\n # delete peak if duration shorter than minimum duration\n if (i - start_high) * SAMPLING_TIME < min_duration_high:\n new[start_high:i] = min_val\n\n # filter lows with duration shorter than min. duration\n start_low = 0\n high = False\n\n for i in range(1, len(new)):\n\n # detect rising edge\n if new[i - 1] == min_val and new[i] == max_val and not high:\n high = True\n\n # delete low if duration shorter than minimum duration\n if (i - start_low) * SAMPLING_TIME < min_duration_low:\n new[start_low:i] = max_val\n\n # detect falling edge\n elif new[i - 1] == max_val and new[i] == min_val and high:\n high = False\n start_low = i\n\n return new\n\n\ndef eff_spd_lmt_2_value(eff_spd_limit, unknown=float('nan')):\n\n # create x values\n x = np.arange(0, 30+1, 1)\n\n # create range of speed limits\n speed_limits = np.array([unknown, 5, 7])\n speed_limits = np.append(speed_limits, np.arange(10, 120+1, 5))\n speed_limits = np.append(speed_limits, np.arange(130, 160+1, 10))\n speed_limits = np.append(speed_limits, 250)\n\n # linear interpolation\n f = interp1d(x, speed_limits)\n return f(eff_spd_limit)\n\n\ndef select_breaking_points(data, categories, select):\n\n new = []\n\n for i in range(len(categories)):\n\n # check if actual category should be selected\n if find_equal(select, categories[i]) >= 0:\n\n new.append(data[i, :])\n\n return np.asarray(new)\n\n\ndef filename_2_shift(source_path):\n # get time shift of break signal from file path\n shift = source_path.split(\"/\")[-1].split(\"_\")\n shift = shift[-1].replace(\".csv\", \"\")\n return int(shift)\n\n\ndef filename_2_trip(source_path):\n # get trip number of measurement file path\n trip = source_path.split(\"/\")[-1].split(\"_\")\n return int(trip[1])\n\n\ndef filename_builder(trips, shifts, meas_files):\n filenames = []\n for trip_i in range(1, trips+1):\n for shift_i in range(0, shifts):\n bp_filename = \"Messdaten/trip_breaking_points/trip_\" + str(trip_i) + \"_breaking_points_shift_\" \\\n + str(shift_i) + \".csv\"\n filenames.append([bp_filename, meas_files[trip_i-1]])\n print(bp_filename, meas_files[trip_i-1])\n return filenames\n\n\ndef add_noise(array, factor):\n return array + factor * np.random.rand(len(array), )\n\n\n# copied from book Deep Learning with Python\ndef normalize_data(data):\n mean = data.mean(axis=0)\n data -= mean\n std = data.std(axis=0)\n data /= std\n return data\n\n\ndef generate_training_data(data, lookback, delay, step, target_index, min_index=0, max_index=None, split=None):\n if max_index is None:\n max_index = len(data)\n\n # indices\n lookback = int(lookback)\n delay = int(delay)\n target_index = int(target_index)\n\n # check split\n if split is None:\n split = [0.8, 0.2]\n if 1.0 < sum(split) < 0.0:\n print('Numbers for splitting are not correct! Default values are used [0.8, 0.2].')\n split = [0.8, 0.2]\n\n # calc number of samples per split and shuffle them\n num_train = np.zeros((int(10*split[0]), ), dtype=int)\n num_test = np.ones((int(10*split[1]), ), dtype=int)\n num = np.concatenate((num_train, num_test))\n shuffle(num)\n print(num)\n\n min_index = int(min_index + lookback)\n max_index = int(max_index - delay) # -1\n\n # calculate the indices\n indices = np.zeros(shape=(max_index - min_index, ), dtype=int) # +1\n # print(np.shape(indices))\n\n counter = 0\n len_train = 0\n len_test = 0\n for i in range(min_index, len(indices) + min_index, 1):\n # print(i)\n if num[int(counter)] == 0:\n len_train += 1\n index = 0\n elif num[int(counter)] == 1:\n len_test += 1\n index = 1\n\n if counter < 9:\n counter += 1\n else:\n counter = 0\n indices[i-min_index] = index\n\n # get the data according to the indices\n samples_train = np.zeros((len_train, lookback // step, np.shape(data)[-1]))\n targets_train = np.zeros((len_train, ))\n samples_test = np.zeros((len_test, lookback // step, np.shape(data)[-1]))\n targets_test = np.zeros((len_test, ))\n samples = [samples_train, samples_test]\n targets = [targets_train, targets_test]\n index = [0, 0]\n for i, part in enumerate(indices, min_index):\n # print(i, part)\n rows = range(i - lookback, i, step)\n samples[part][index[part]] = data[rows]\n targets[part][index[part]] = data[i + delay - 1][target_index]\n index[part] += 1\n\n return samples, targets\n\n\n# the samples must have the same shape like the training data to fit the rnn input layer\ndef generate_sequences(data, lookback, delay, step):\n # indices\n lookback = int(lookback)\n delay = int(delay)\n\n samples = np.zeros((len(data) - lookback - delay, lookback // step, np.shape(data)[-1]))\n for i in range(len(samples)):\n rows = range(i, i + lookback, step)\n samples[i] = data[rows]\n return samples\n\n\ndef replace_nan(data, replacement):\n for row in range(data.shape[0]):\n for index, number in enumerate(data[row, :]):\n if isnan(number):\n data[row, index] = replacement[index]\n # print(row, data[row, :])\n\n return data\n\n\ndef filter_trip(truth, pred, active):\n truth_new = []\n pred_new = []\n\n for i in range(len(truth)):\n if active[i]:\n truth_new.append(truth[i])\n pred_new.append(pred[i])\n\n return truth_new, pred_new\n\n","sub_path":"help_functions.py","file_name":"help_functions.py","file_ext":"py","file_size_in_byte":7774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"258364044","text":"import csv\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import animation\nfrom multi_layer_perceptrons import MultiLayerPerceptrons\n\n################################################################################\n\ndef plot(X, Y, E, title):\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))\n fig.suptitle(title, fontsize=17)\n ax1.grid(True)\n ax1.set_xlabel(\"x\")\n ax1.set_ylabel(\"y\")\n ax1.plot(X.flatten(), T.flatten(), 'o')\n curve, = ax1.plot([], [], 'r')\n\n ax2.set_xlim(0, len(E))\n ax2.set_ylim(E[-1], E[0])\n error, = ax2.plot([], [], 'c')\n ax2.set_xlabel(\"Iterations\")\n ax2.set_ylabel(\"Error\")\n ax2.grid(True)\n\n lines = [curve, error]\n xdata = []\n ydata = []\n\n anim = animation.FuncAnimation(\n fig,\n animate,\n frames=len(Y),\n interval=100,\n fargs=(X, Y, E, lines, xdata, ydata),\n blit=False,\n repeat=False\n )\n\n return anim\n\ndef animate(frame, X, Y, E, lines, xdata, ydata):\n xdata.append(frame)\n ydata.append(E[frame])\n\n lines[0].set_data(X.flatten(), Y[frame].flatten())\n lines[1].set_data(xdata, ydata)\n return lines\n\n################################################################################\n\n# Load data from the file\nX = []\nT = []\n\nwith open('data.csv') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n for row in reader:\n if row[0] == \"x\" and row[1] == \"t\":\n continue\n else:\n X.append([float(row[0])])\n T.append([float(row[1])])\n\nX = np.array(X)\nT = np.array(T)\n\n################################################################################\n\nnn1 = MultiLayerPerceptrons(numIns=1, numHiddens=2, numOuts=1)\nY1, E1 = nn1.train(X, T, maxIters=90, eta_wji=0.05, eta_wkj=0.08)\n\n################################################################################\n\n# anim = plot(\n# X,\n# Y1,\n# E1,\n# \"Demonstration of Training Neural Network Using Backpropagation Algorithm\"\n# )\n# plt.show(anim)\n","sub_path":"Chapter 4 - Exercise 13/Chapter4_Exercise13.py","file_name":"Chapter4_Exercise13.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"7187119","text":"import logging\nfrom logging.config import dictConfig\n\nimport uvicorn\n\nfrom erica.config import get_settings\n\ndebug = get_settings().debug\nlog_eric_debug_info = get_settings().log_eric_debug_info\nlog_level = logging.DEBUG if debug else logging.INFO\neric_log_level = logging.DEBUG if log_eric_debug_info else logging.INFO\n\ndictConfig({\n \"version\": 1,\n \"formatters\": {\n \"default\": {\n \"format\": \"%(asctime)s%(levelname)s%(name)s%(message)s%(module)s%(lineno)s%(process)d%(thread)d\",\n \"class\": \"pythonjsonlogger.jsonlogger.JsonFormatter\"\n }\n },\n \"handlers\": {\n \"stderr\": {\n \"class\": \"logging.StreamHandler\",\n \"stream\": \"ext://sys.stderr\",\n \"formatter\": \"default\"\n }\n },\n \"root\": {\n \"level\": log_level,\n \"handlers\": [\"stderr\"]\n },\n \"loggers\": {\n \"eric\": {\n \"level\": eric_log_level\n }\n },\n \"disable_existing_loggers\": False\n})\n\nuvicorn.run(\"erica:app\", host=\"0.0.0.0\", port=8000, log_config=None)\n","sub_path":"erica_app/erica/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"331913128","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/galaxy/jobs/metrics/instrumenters/collectl.py\n# Compiled at: 2018-09-15 08:40:24\n\"\"\"The module describes the ``collectl`` job metrics plugin.\"\"\"\nimport logging, os, shutil\nfrom galaxy import util\nfrom . import InstrumentPlugin\nfrom .. import formatting\nfrom ..collectl import cli, processes, subsystems\nlog = logging.getLogger(__name__)\nDEFAULT_PROCFILT_ON = 'username'\nDEFAULT_SUBSYSTEMS = 'process'\nDEFAULT_FLUSH_INTERVAL = '0'\nFORMATTED_RESOURCE_TITLES = {'PCT': 'Percent CPU Usage', \n 'RSYS': 'Disk Reads', \n 'WSYS': 'Disk Writes'}\nEMPTY_COLLECTL_FILE_MESSAGE = 'Skipping process summary due to empty file... job probably did not run long enough for collectl to gather data.'\n\nclass CollectlFormatter(formatting.JobMetricFormatter):\n\n def format(self, key, value):\n if key == 'pid':\n return ('Process ID', int(value))\n else:\n if key == 'raw_log_path':\n return ('Relative Path of Full Collectl Log', value)\n if key == 'process_max_AccumT':\n return ('Job Runtime (System+User)', formatting.seconds_to_str(float(value)))\n _, stat_type, resource_type = key.split('_', 2)\n if resource_type.startswith('Vm'):\n value_str = '%s KB' % int(value)\n elif resource_type in ('RSYS', 'WSYS') and stat_type in ('count', 'max',\n 'sum'):\n value_str = '%d (# system calls)' % int(value)\n else:\n value_str = str(value)\n resource_title = FORMATTED_RESOURCE_TITLES.get(resource_type, resource_type)\n return ('%s (%s)' % (resource_title, stat_type), value_str)\n\n\nclass CollectlPlugin(InstrumentPlugin):\n \"\"\" Run collectl along with job to capture system and/or process data\n according to specified collectl subsystems.\n \"\"\"\n plugin_type = 'collectl'\n formatter = CollectlFormatter()\n\n def __init__(self, **kwargs):\n self.__configure_paths(kwargs)\n self.__configure_subsystems(kwargs)\n saved_logs_path = kwargs.get('saved_logs_path', '')\n if 'app' in kwargs:\n log.debug('Found path for saved logs: %s' % saved_logs_path)\n saved_logs_path = kwargs['app'].config.resolve_path(saved_logs_path)\n self.saved_logs_path = saved_logs_path\n self.__configure_collectl_recorder_args(kwargs)\n self.summarize_process_data = util.asbool(kwargs.get('summarize_process_data', True))\n self.log_collectl_program_output = util.asbool(kwargs.get('log_collectl_program_output', False))\n if self.summarize_process_data:\n if subsystems.get_subsystem('process') not in self.subsystems:\n raise Exception('Collectl plugin misconfigured - cannot summarize_process_data without process subsystem being enabled.')\n process_statistics = kwargs.get('process_statistics', None)\n self.process_statistics = processes.parse_process_statistics(process_statistics)\n return\n\n def pre_execute_instrument(self, job_directory):\n commands = []\n commands.append('echo \"$$\" > \\'%s\\' ' % self.__pid_file(job_directory))\n commands.append(self.__collectl_record_command(job_directory))\n return commands\n\n def post_execute_instrument(self, job_directory):\n commands = []\n return commands\n\n def job_properties(self, job_id, job_directory):\n pid = open(self.__pid_file(job_directory), 'r').read().strip()\n contents = os.listdir(job_directory)\n try:\n rel_path = filter(self._is_instrumented_collectl_log, contents)[0]\n path = os.path.join(job_directory, rel_path)\n except IndexError:\n message = 'Failed to find collectl log in directory %s, files were %s' % (job_directory, contents)\n raise Exception(message)\n\n properties = dict(pid=int(pid))\n if self.saved_logs_path:\n destination_rel_dir = os.path.join(*util.directory_hash_id(job_id))\n destination_rel_path = os.path.join(destination_rel_dir, rel_path)\n destination_path = os.path.join(self.saved_logs_path, destination_rel_path)\n destination_dir = os.path.dirname(destination_path)\n if not os.path.isdir(destination_dir):\n os.makedirs(destination_dir)\n shutil.copyfile(path, destination_path)\n properties['raw_log_path'] = destination_rel_path\n if self.summarize_process_data:\n summary_statistics = self.__summarize_process_data(pid, path)\n for statistic, value in summary_statistics:\n properties['process_%s' % ('_').join(statistic)] = value\n\n return properties\n\n def __configure_paths(self, kwargs):\n collectl_path = kwargs.get('collectl_path', 'collectl')\n self.remote_collectl_path = kwargs.get('remote_collectl_path', collectl_path)\n self.local_collectl_path = kwargs.get('local_collectl_path', collectl_path)\n\n def __configure_subsystems(self, kwargs):\n raw_subsystems_str = kwargs.get('subsystems', DEFAULT_SUBSYSTEMS)\n raw_subsystems = util.listify(raw_subsystems_str, do_strip=True)\n self.subsystems = [ subsystems.get_subsystem(_) for _ in raw_subsystems ]\n\n def __configure_collectl_recorder_args(self, kwargs):\n collectl_recorder_args = kwargs.copy()\n if 'interval' in kwargs and 'interval2' not in kwargs:\n collectl_recorder_args['interval2'] = kwargs['interval']\n if 'flush' not in kwargs:\n collectl_recorder_args['flush'] = DEFAULT_FLUSH_INTERVAL\n procfilt_on = kwargs.get('procfilt_on', DEFAULT_PROCFILT_ON).lower()\n explicit_args = dict(collectl_path=self.remote_collectl_path, procfilt=procfilt_argument(procfilt_on), subsystems=self.subsystems)\n collectl_recorder_args.update(explicit_args)\n self.collectl_recorder_args = collectl_recorder_args\n\n def __summarize_process_data(self, pid, collectl_log_path):\n playback_cli_args = dict(collectl_path=self.local_collectl_path, playback_path=collectl_log_path, sep='9')\n if not os.stat(collectl_log_path).st_size:\n log.debug(EMPTY_COLLECTL_FILE_MESSAGE)\n return []\n playback_cli = cli.CollectlCli(**playback_cli_args)\n return processes.generate_process_statistics(playback_cli, pid, self.process_statistics)\n\n def __collectl_recorder_cli(self, job_directory):\n cli_args = self.collectl_recorder_args.copy()\n cli_args['destination_path'] = self._instrument_file_path(job_directory, 'log')\n return cli.CollectlCli(**cli_args)\n\n def __collectl_record_command(self, job_directory):\n collectl_cli = self.__collectl_recorder_cli(job_directory)\n if self.log_collectl_program_output:\n redirect_to = self._instrument_file_path(job_directory, 'program_output')\n else:\n redirect_to = '/dev/null'\n return '%s > %s 2>&1 &' % (\n collectl_cli.build_command_line(),\n redirect_to)\n\n def __pid_file(self, job_directory):\n return self._instrument_file_path(job_directory, 'pid')\n\n def _is_instrumented_collectl_log(self, filename):\n prefix = self._instrument_file_name('log')\n return filename.startswith(prefix) and filename.endswith('.raw.gz')\n\n\ndef procfilt_argument(procfilt_on):\n if procfilt_on == 'username':\n return 'U$USER'\n else:\n if procfilt_on == 'uid':\n return 'u$UID'\n if procfilt_on or procfilt_on.lower() != 'none':\n raise Exception('Invalid procfilt_on argument encountered')\n return ''\n\n\n__all__ = ('CollectlPlugin', )","sub_path":"pycfiles/galaxy_lib-19.5.2-py2.7/collectl.py","file_name":"collectl.py","file_ext":"py","file_size_in_byte":7903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"355101157","text":"import re\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom congressional_data.data_filling.utils.utils import (\n extract_tags,\n get_wiki_article_name,\n ignored,\n parse_date,\n wiki_stub,\n brute_force_infobox_date,\n)\nfrom congressional_data.data_filling.utils import death_methods as dm\nfrom sqlalchemy.orm import sessionmaker\n\nfrom congressional_data.data_filling.parties import get_or_create_political_party\nfrom congressional_data.models import (\n PartyMembership,\n Person,\n Place,\n Profession,\n ProfessionMapping,\n University,\n UniversityMapping,\n WikiURL,\n engine,\n get_or_create,\n)\n\n\ndef update_with_other_models(session, person, personal_details):\n if 'birthplace' in personal_details:\n personal_details['birthplace'] = get_or_create(\n session, Place, url=WikiURL.get_wiki_url(session, personal_details['birthplace'])\n ).id\n if 'deathplace' in personal_details:\n personal_details['deathplace'] = get_or_create(\n session, Place, url=WikiURL.get_wiki_url(session, personal_details['deathplace'])\n ).id\n if 'parties' in personal_details:\n for url in personal_details['parties']:\n party_id = get_or_create_political_party(session, url)\n get_or_create(session, PartyMembership, person_id=person.id, political_party_id=party_id)\n if 'profession' in personal_details:\n professions = personal_details['profession']\n for profession in professions:\n profession_obj = get_or_create(session, Profession, name=profession.lower())\n get_or_create(session, ProfessionMapping, profession_id=profession_obj.id, person_id=person.id)\n if 'university' in personal_details:\n for university in personal_details['university']:\n uni_obj = get_or_create(session, University, url=WikiURL.get_wiki_url(session, raw_url=university))\n get_or_create(session, UniversityMapping, university_id=uni_obj.id, person_id=person.id)\n return personal_details\n\n\ndef scrape_person_data(session):\n persons_to_scrape = session.query(Person).filter(Person.name.is_(None))\n for person in persons_to_scrape:\n update_person_from_url(session, person)\n\n\ndef update_person_from_url(session, person):\n print(person)\n personal_details = scrape_person(person.url)\n update_with_other_models(session, person, personal_details)\n person.update(**personal_details)\n session.commit()\n\n\ndef profession(infobox):\n profession_tags = []\n for tagtext in ['Profession', 'Occupation']:\n with ignored(AttributeError):\n profession_tag = infobox.find('th', text=tagtext).next_sibling\n for br in profession_tag.find_all('br'):\n br.replace_with(',')\n if profession_tag.find('li'):\n profession_text = ','.join(li.text for li in profession_tag.find_all('li'))\n else:\n profession_text = profession_tag.text\n profession_text = profession_text.strip().replace('\\n', ',').strip()\n for job in profession_text.split(','):\n if job:\n profession_tags.append(job.strip())\n return {'profession': profession_tags}\n\n\ndef university(infobox):\n university_tags = []\n for tagtext in ['Alma mater', 'Education']:\n with ignored(AttributeError):\n uni_tag = infobox.find('th', text=tagtext).next_sibling\n for a in uni_tag.find_all('a'):\n if 'Bachelor' not in a.attrs.get('title') and 'Master' not in a.attrs.get('title'):\n university_tags.append(wiki_stub(a.attrs.get('href')))\n return {'university': university_tags}\n\n\ndef scrape_person(url):\n personal_details = {}\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'lxml')\n extract_tags(soup.find_all('a', attrs={'class': re.compile('external autonumber')}))\n extract_tags(soup.find_all('a', attrs={'href': re.compile('.*\\?uselang.*')}))\n extract_tags(soup.find_all('a', attrs={'href': re.compile('#cite_note.*')}))\n infobox = soup.find('table', attrs={'class': 'infobox'})\n if infobox:\n try:\n personal_details['name'] = (\n infobox.find('span', attrs={'class': 'fn'}) or infobox.find('caption', attrs={'class': 'fn'})\n ).text\n except AttributeError:\n personal_details['name'] = get_wiki_article_name(soup)\n personal_details.update(birth_details(infobox))\n personal_details.update(death_details(infobox))\n personal_details.update(party_details(infobox))\n personal_details.update(profession(infobox))\n personal_details.update(university(infobox))\n else:\n personal_details['name'] = get_wiki_article_name(soup)\n personal_details.update(get_bioguide_link(soup))\n return personal_details\n\n\ndef get_bioguide_link(soup):\n bioguide_dict = {}\n with ignored(IndexError):\n bioguide_links = soup.find_all(href=re.compile('.*bioguide.*index'))\n if len(bioguide_links) == 1:\n bioguide_dict['congress_idx'] = bioguide_links[0].attrs.get('href').split('=')[1]\n else:\n for link in bioguide_links:\n idx = link.attrs.get('href').split('=')[1]\n if idx in link.text:\n bioguide_dict['congress_idx'] = idx\n return bioguide_dict\n\n\ndef death_details(infobox):\n death_details = {}\n died = None\n try:\n died = infobox.find('th', text='Died').next_sibling\n except AttributeError as _:\n pass # I'm not dead yet!\n if died:\n dday = get_death_date(died)\n if dday:\n death_details['date_of_death'] = dday\n if died.a:\n death_details['deathplace'] = wiki_stub(died.a.get('href'))\n return death_details\n\n\ndef get_death_date(died):\n dday = None\n if died.text.strip() == 'Unknown':\n return None\n for death_method in [dm.span, dm.span_span, dm.time, dm.next_el, dm.next_el_next_el]:\n if not dday:\n with ignored(AttributeError, TypeError):\n dday = death_method(died)\n if dday and '(' in dday:\n dday = dday.split('(')[0].strip()\n try:\n death_date = parse_date(dday)\n except ValueError:\n death_date = brute_force_infobox_date(died)\n return death_date\n\n\ndef birth_details(infobox):\n born_details = {}\n born = None\n with ignored(AttributeError):\n born = infobox.find('th', text='Born').next_sibling\n if born:\n with ignored(AttributeError): # No nicknames, thanks\n born_details['birthname'] = born.find('span', attrs={'class': 'nickname'}).text\n try:\n parsed_birth_date = parse_date(born.find('span', attrs={'class': 'bday'}).text.strip('()'))\n except AttributeError as _:\n elem = born\n parsed_birth_date = brute_force_infobox_date(elem)\n born_details['date_of_birth'] = parsed_birth_date\n with ignored(AttributeError):\n born_details['birthplace'] = wiki_stub(born.a.get('href'))\n return born_details\n\n\ndef party_details(infobox):\n parties = []\n for text_string in ['Political party']:\n with ignored(AttributeError):\n party_list = infobox.find('th', text=text_string).next_sibling\n for party in party_list.find_all('a'):\n parties.append(wiki_stub(party.get('href')))\n return {'parties': parties}\n\n\nif __name__ == '__main__':\n Session = sessionmaker()\n Session.configure(bind=engine)\n session = Session()\n scrape_person_data(session)\n session.close()\n","sub_path":"data_filling/persons.py","file_name":"persons.py","file_ext":"py","file_size_in_byte":7629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"46736911","text":"from django.urls import path\nfrom . import views\n\n# Defines all url patterns. First has the relative link, then the views function to call, and the url name that can be used later.\n\nurlpatterns = [\n path('old', views.old_home, name = 'blog-old-home'),\n path('about/', views.about, name = 'blog-about'),\n path('', views.home, name = 'blog-home'),\n path('transactions/', views.transactions, name = 'blog-transactions'),\n path('topholdings/', views.top_holdings, name = 'blog-top-holdings'),\n\n\n]\n","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"560092779","text":"import unittest\nimport json\nimport os\nfrom flask import current_app, url_for\nfrom app import create_app\nfrom app.structures.LocationsKDTree import LocationsKDTree\nfrom app.structures.InvertedPointLocationIndex import InvertedPointLocationIndex\n\nclass test_GET_Film_Locations_Near_Me_API(unittest.TestCase):\n def setUp(self):\n self.app = create_app('testing')\n self.app_context = self.app.app_context()\n self.app_context.push()\n self.client = self.app.test_client()\n\n # An inverted index, mapping UTM (Universal Transverse Mercator) lat/lng\n # values geolocating each film, to a LIST of films that were filmed\n # at that location.\n #\n # IMPORTANT!: This is a shared data-structure, built only at startup,\n # that is READ-ONLY by all, and so can be safely shared.\n invertedPointLocationIndex = InvertedPointLocationIndex()\n invertedPointLocationIndex.build_inverted_location_index()\n\n # A KD tree, implemented using the scipy package's kdtree implementation\n # under the hood, to allow for fast O(ln) queries of 2D point data. The\n # points that it stores are geocoded locations coded in UTM to allow them\n # to be treated as 2D points to an approximation.\n #\n # IMPORTANT!: This is a shared data-structure, built only at startup,\n # that is READ-ONLY by all, and so can be safely shared.\n filmLocationsKDTree = LocationsKDTree()\n filmLocationsKDTree.load_point_data()\n filmLocationsKDTree.build_kd_tree()\n\n self.app_context.g.filmlocationsKDTree = filmLocationsKDTree\n self.app_context.g.invertedPointLocationIndex = invertedPointLocationIndex\n\n def tearDown(self):\n self.app_context.pop()\n\n def test_request_7_locations_near_me(self):\n\n\n \"\"\" TESTING IF redis will return all 'Locations' which are closest\n to the steps of San Francisco City Hall\n\n COMPARING WITH the 7 locations manually calculated using\n the 'haversine' formulay on the original lat/lng coordinates\n provided by Google Maps API\n\n The comparison data was retrieved by calling '__get_expected_7_locations_near_me':\n \"\"\"\n response = self.client.get(url_for('films_near_me',lat=37.779390,lat_sign='p',lng=122.418432,lng_sign='n'))\n expected_response = self.__get_expected_7_locations_near_me()\n self.assertEquals(expected_response,json.loads(response.get_data()))\n\n def __get_expected_7_locations_near_me(self):\n \"\"\"\n The known 7 locations are included in this file: '_7film_locations_near_me_test.txt'\n This file is read and the contents converted to json array.\n \"\"\"\n basepath = os.path.dirname(__file__)\n locations_coord_filepath = os.path.abspath(os.path.join(basepath, \"../app\", \"data\", \"_7film_locations_near_me_test.txt\"))\n\n expected_response = \"\"\n with open(locations_coord_filepath, 'r') as f:\n for row in f:\n expected_response = expected_response + row\n\n return json.loads(expected_response)","sub_path":"tests/test_GET_Film_Locations_Near_me_API.py","file_name":"test_GET_Film_Locations_Near_me_API.py","file_ext":"py","file_size_in_byte":3156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"2313457","text":"\n\nfrom xai.brain.wordbase.nouns._flicker import _FLICKER\n\n#calss header\nclass _FLICKERS(_FLICKER, ):\n\tdef __init__(self,): \n\t\t_FLICKER.__init__(self)\n\t\tself.name = \"FLICKERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"flicker\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_flickers.py","file_name":"_flickers.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"57836613","text":"# Copyright lowRISC contributors.\n# Licensed under the Apache License, Version 2.0, see LICENSE for details.\n# SPDX-License-Identifier: Apache-2.0\n\n'''Support code for reading the instruction database in insns.yml'''\n\nimport re\nfrom typing import (Callable, Dict, List, Optional,\n Sequence, Set, Tuple, TypeVar)\n\nimport yaml\n\n\nT = TypeVar('T')\n\n\ndef check_keys(obj: object,\n what: str,\n required_keys: List[str],\n optional_keys: List[str]) -> Dict[str, object]:\n '''Check that obj is a dict object with the expected keys\n\n If not, raise a ValueError; the what argument names the object.\n\n '''\n if not isinstance(obj, dict):\n raise ValueError(\"{} is expected to be a dict, but was actually a {}.\"\n .format(what, type(obj).__name__))\n\n allowed = set()\n missing = []\n for key in required_keys:\n assert key not in allowed\n allowed.add(key)\n if key not in obj:\n missing.append(key)\n\n for key in optional_keys:\n assert key not in allowed\n allowed.add(key)\n\n unexpected = []\n for key in obj:\n if key not in allowed:\n unexpected.append(key)\n\n if missing or unexpected:\n mstr = ('The following required fields were missing: {}.'\n .format(', '.join(missing)) if missing else '')\n ustr = ('The following unexpected fields were found: {}.'\n .format(', '.join(unexpected)) if unexpected else '')\n raise ValueError(\"{} doesn't have the right keys. {}{}{}\"\n .format(what,\n mstr,\n ' ' if mstr and ustr else '',\n ustr))\n\n return obj\n\n\ndef check_str(obj: object, what: str) -> str:\n '''Check that the given object is a string\n\n If not, raise a ValueError; the what argument names the object.\n\n '''\n if not isinstance(obj, str):\n raise ValueError('{} is of type {}, not a string.'\n .format(what, type(obj).__name__))\n return obj\n\n\ndef check_optional_str(obj: object, what: str) -> Optional[str]:\n '''Check that the given object is a string or None\n\n If not, raise a ValueError; the what argument names the object.\n\n '''\n if obj is not None and not isinstance(obj, str):\n raise ValueError('{} is of type {}, not a string.'\n .format(what, type(obj).__name__))\n return obj\n\n\ndef check_bool(obj: object, what: str) -> bool:\n '''Check that the given object is a bool\n\n If not, raise a ValueError; the what argument names the object.\n\n '''\n if obj is not True and obj is not False:\n raise ValueError('{} is of type {}, not a string.'\n .format(what, type(obj).__name__))\n return obj\n\n\ndef check_list(obj: object, what: str) -> List[object]:\n '''Check that the given object is a list\n\n If not, raise a ValueError; the what argument names the object.\n\n '''\n if not isinstance(obj, list):\n raise ValueError('{} is of type {}, not a list.'\n .format(what, type(obj).__name__))\n return obj\n\n\ndef index_list(what: str,\n objs: Sequence[T],\n get_key: Callable[[T], str]) -> Dict[str, T]:\n ret = {}\n for obj in objs:\n key = get_key(obj)\n if key in ret:\n raise ValueError('Duplicate object with key {} in {}.'\n .format(key, what))\n ret[key] = obj\n return ret\n\n\nclass InsnGroup:\n def __init__(self, yml: object) -> None:\n yd = check_keys(yml, 'insn-group', ['key', 'title', 'doc'], [])\n self.key = check_str(yd['key'], 'insn-group key')\n self.title = check_str(yd['title'], 'insn-group title')\n self.doc = check_str(yd['doc'], 'insn-group doc')\n\n\nclass InsnGroups:\n def __init__(self, yml: object) -> None:\n self.groups = [InsnGroup(y) for y in check_list(yml, 'insn-groups')]\n if not self.groups:\n raise ValueError('Empty list of instruction groups: '\n 'we need at least one as a base group.')\n self.key_to_group = index_list('insn-groups',\n self.groups, lambda ig: ig.key)\n\n def default_group(self) -> str:\n '''Get the name of the default instruction group'''\n assert self.groups\n return self.groups[0].key\n\n\nclass OperandType:\n '''The base class for some sort of operand type'''\n def __init__(self) -> None:\n pass\n\n def markdown_doc(self) -> Optional[str]:\n '''Generate any (markdown) documentation for this operand type\n\n The base class returns None, but subclasses might return something\n useful.\n\n '''\n return None\n\n\nclass RegOperandType(OperandType):\n '''A class representing a register operand type'''\n TYPES = ['gpr', 'wdr', 'csr', 'wsr']\n\n def __init__(self, reg_type: str, is_dest: bool):\n assert reg_type in RegOperandType.TYPES\n self.reg_type = reg_type\n self.is_dest = is_dest\n\n\nclass ImmOperandType(OperandType):\n '''A class representing an immediate operand type'''\n def __init__(self, width: Optional[int]):\n if width is not None:\n assert width > 0\n self.width = width\n\n def markdown_doc(self) -> Optional[str]:\n # Override from OperandType base class\n if self.width is None:\n return None\n\n return 'Valid range: `0..{}`'.format((1 << self.width) - 1)\n\n\nclass EnumOperandType(ImmOperandType):\n '''A class representing an enum operand type'''\n def __init__(self, items: List[str]):\n assert items\n super().__init__(int.bit_length(len(items) - 1))\n self.items = items\n\n def markdown_doc(self) -> Optional[str]:\n # Override from OperandType base class\n parts = ['Syntax table:\\n\\n'\n '| Syntax | Value of immediate |\\n'\n '|--------|--------------------|\\n']\n for idx, item in enumerate(self.items):\n parts.append('| `{}` | `{}` |\\n'\n .format(item, idx))\n return ''.join(parts)\n\n\nclass OptionOperandType(ImmOperandType):\n '''A class representing an option operand type'''\n def __init__(self, option: str):\n super().__init__(1)\n self.option = option\n\n def markdown_doc(self) -> Optional[str]:\n # Override from OperandType base class\n return 'To specify, use the literal syntax `{}`\\n'.format(self.option)\n\n\ndef parse_operand_type(fmt: str) -> OperandType:\n '''Make sense of the operand type syntax'''\n # Registers\n if fmt == 'grs':\n return RegOperandType('gpr', False)\n if fmt == 'grd':\n return RegOperandType('gpr', True)\n if fmt == 'wrs':\n return RegOperandType('wdr', False)\n if fmt == 'wrd':\n return RegOperandType('wdr', True)\n if fmt == 'csr':\n return RegOperandType('csr', True)\n if fmt == 'wsr':\n return RegOperandType('wsr', True)\n\n # Immediates\n if fmt == 'imm':\n return ImmOperandType(None)\n m = re.match(r'imm([1-9][0-9]*)$', fmt)\n if m:\n return ImmOperandType(int(m.group(1)))\n m = re.match(r'enum\\(([^\\)]+)\\)$', fmt)\n if m:\n return EnumOperandType([item.strip()\n for item in m.group(1).split(',')])\n m = re.match(r'option\\(([^\\)]+)\\)$', fmt)\n if m:\n return OptionOperandType(m.group(1).strip())\n\n raise ValueError(\"Operand type description {!r} \"\n \"didn't match any recognised format.\"\n .format(fmt))\n\n\ndef infer_operand_type(name: str) -> OperandType:\n '''Try to guess an operand's type from its name'''\n\n if re.match(r'grs[0-9]*$', name):\n return parse_operand_type('grs')\n if name in ['grd', 'wrd', 'csr', 'wsr']:\n return parse_operand_type(name)\n if re.match(r'wrs[0-9]*$', name):\n return parse_operand_type('wrs')\n if re.match(r'imm[0-9]*$', name):\n return parse_operand_type('imm')\n if name == 'offset':\n return parse_operand_type('imm')\n\n raise ValueError(\"Operand name {!r} doesn't imply an operand type: \"\n \"you'll have to set the type explicitly.\"\n .format(name))\n\n\ndef make_operand_type(yml: object, operand_name: str) -> OperandType:\n '''Construct a type for an operand\n\n This is either based on the type, if given, or inferred from the name\n otherwise.\n\n '''\n return (parse_operand_type(check_str(yml,\n 'type for {} operand'\n .format(operand_name)))\n if yml is not None\n else infer_operand_type(operand_name))\n\n\ndef get_optional_str(data: Dict[str, object],\n key: str, what: str) -> Optional[str]:\n return check_optional_str(data.get(key), '{} field for {}'.format(key, what))\n\n\nclass Operand:\n def __init__(self, yml: object, insn_name: str) -> None:\n # The YAML representation should be a string (a bare operand name) or a\n # dict.\n what = 'operand for {!r} instruction'.format(insn_name)\n if isinstance(yml, str):\n name = yml\n op_type = None\n doc = None\n elif isinstance(yml, dict):\n yd = check_keys(yml, what, ['name'], ['type', 'doc'])\n name = check_str(yd['name'], 'name of ' + what)\n\n op_what = '{!r} {}'.format(name, what)\n op_type = get_optional_str(yd, 'type', op_what)\n doc = get_optional_str(yd, 'doc', op_what)\n\n op_what = '{!r} {}'.format(name, what)\n self.name = name\n self.op_type = make_operand_type(op_type, name)\n self.doc = doc\n\n\nclass InsnSyntax:\n def __init__(self, raw: str) -> None:\n # The raw syntax looks something like \" + (baz )\". We\n # need to check that each <..> holds an operand name. We want to\n # tokenize the string to split out the operands. The easiest way to\n # encode this in the types is as a string followed by zero or more\n # pairs, (operand, string).\n #\n # Conveniently, re.split does exactly what we need, always yielding an\n # odd number of parts and starting with an empty string if there's a\n # match at the start.\n parts = re.split(r'<([^>]+)>', raw)\n self.prefix = parts[0]\n self.pairs = list(zip(parts[1::2], parts[2::2]))\n\n assert len(parts) == 1 + 2 * len(self.pairs)\n\n # Collect up the named operands that we've seen, checking for\n # duplicates\n self.operands = set() # type: Set[str]\n for operand, _ in self.pairs:\n if operand in self.operands:\n raise ValueError('Instruction syntax ({!r}) has duplicate '\n 'occurrence of the {!r} operand.'\n .format(raw, operand))\n self.operands.add(operand)\n\n def raw_string(self) -> str:\n '''Return the raw string of the syntax'''\n parts = [self.prefix]\n for operand, suffix in self.pairs:\n parts.append('<{}>'.format(operand))\n parts.append(suffix)\n return ''.join(parts)\n\n\nclass Insn:\n def __init__(self, yml: object, groups: InsnGroups) -> None:\n yd = check_keys(yml, 'instruction',\n ['mnemonic', 'operands'],\n ['group', 'rv32i', 'synopsis',\n 'syntax', 'doc', 'note', 'trailing-doc',\n 'decode', 'operation'])\n\n self.mnemonic = check_str(yd['mnemonic'], 'mnemonic for instruction')\n\n what = 'instruction with mnemonic {!r}'.format(self.mnemonic)\n self.operands = [Operand(y, self.mnemonic)\n for y in check_list(yd['operands'],\n 'operands for ' + what)]\n self.name_to_operand = index_list('operands for ' + what,\n self.operands,\n lambda op: op.name)\n\n raw_group = get_optional_str(yd, 'group', what)\n self.group = groups.default_group() if raw_group is None else raw_group\n\n if self.group not in groups.key_to_group:\n raise ValueError('Unknown instruction group, {!r}, '\n 'for mnemonic {!r}.'\n .format(self.group, self.mnemonic))\n\n self.rv32i = check_bool(yd.get('rv32i', False),\n 'rv32i flag for ' + what)\n self.synopsis = get_optional_str(yd, 'synopsis', what)\n self.doc = get_optional_str(yd, 'doc', what)\n self.note = get_optional_str(yd, 'note', what)\n self.trailing_doc = get_optional_str(yd, 'trailing-doc', what)\n self.decode = get_optional_str(yd, 'decode', what)\n self.operation = get_optional_str(yd, 'operation', what)\n\n raw_syntax = get_optional_str(yd, 'syntax', what)\n self.syntax = None # type: Optional[InsnSyntax]\n if raw_syntax is not None:\n self.syntax = InsnSyntax(raw_syntax)\n\n # Make sure we have exactly the operands we expect.\n if set(self.name_to_operand.keys()) != self.syntax.operands:\n raise ValueError(\"Operand syntax for {!r} doesn't have the \"\n \"same list of operands as given in the \"\n \"operand list. The syntax uses {}, \"\n \"but the list of operands gives {}.\"\n .format(self.mnemonic,\n list(sorted(self.syntax.operands)),\n list(sorted(self.name_to_operand))))\n\n\nclass InsnsFile:\n def __init__(self, yml: object) -> None:\n yd = check_keys(yml, 'top-level',\n ['insn-groups', 'insns'],\n [])\n\n self.groups = InsnGroups(yd['insn-groups'])\n self.insns = [Insn(i, self.groups)\n for i in check_list(yd['insns'], 'insns')]\n self.mnemonic_to_insn = index_list('insns', self.insns,\n lambda insn: insn.mnemonic)\n\n def grouped_insns(self) -> List[Tuple[InsnGroup, List[Insn]]]:\n '''Return the instructions in groups'''\n grp_to_insns = {} # type: Dict[str, List[Insn]]\n for insn in self.insns:\n grp_to_insns.setdefault(insn.group, []).append(insn)\n\n ret = []\n for grp in self.groups.groups:\n ret.append((grp, grp_to_insns.get(grp.key, [])))\n\n # We should have picked up all the instructions, because we checked\n # that each instruction has a valid group in the Insn constructor. Just\n # in case something went wrong, check that the counts match.\n gti_count = sum(len(insns) for insns in grp_to_insns.values())\n ret_count = sum(len(insns) for _, insns in ret)\n assert ret_count == gti_count\n\n return ret\n\n\ndef load_file(path: str) -> InsnsFile:\n '''Load the YAML file at path.\n\n Raises a RuntimeError on syntax or schema error.\n\n '''\n try:\n with open(path, 'r') as handle:\n return InsnsFile(yaml.load(handle, Loader=yaml.SafeLoader))\n except yaml.YAMLError as err:\n raise RuntimeError('Failed to parse YAML file at {!r}: {}'\n .format(path, err)) from None\n except ValueError as err:\n raise RuntimeError('Invalid schema in YAML file at {!r}: {}'\n .format(path, err)) from None\n","sub_path":"hw/ip/otbn/util/insn_yaml.py","file_name":"insn_yaml.py","file_ext":"py","file_size_in_byte":15747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"150908671","text":"import pickle\nimport numpy as np\n# db = pickle.load(open('bert_fine_tune.p', 'rb'))\nfrom utils import Config, safe_pickle_dump, strip_version\ndb = pickle.load(open(Config.db_path, 'rb'))\norig = pickle.load(open('elmo_embed.p', 'rb'))\n# db = pickle.load(open('bert_out.p', 'rb'))\n# print(len(db))\n# X = np.array(list(db.values()))\n# normalization\nX = orig / np.linalg.norm(orig, axis=1, keepdims=1)\n# print(X.shape)\npids = list(db.keys())\n# B = N\nds = -np.asarray(np.dot(X, X.T)) #NxD * DxB => NxB\n# print(ds[0][0])\nIX = np.argsort(ds, axis=0) # NxB\n# pid = '1407.2515'\n# pid = '1904.05856'\n# pid = '1904.07460'\n# ID = pids.index(pid)\n# print(IX.shape)\nARXIV_PATH = 'https://arxiv.org/abs/'\n# print(ARXIV_PATH + pids[ID])\n# print(orig[ID])\n# for i in range(0,6):\n# # print(IX[ID][i])\n# # print(orig[IX[i][ID]])\n# # print(1+ds[ID][IX[i][ID]], end=' ')\n# sim_pid = pids[IX[i][ID]]\n# print(ARXIV_PATH + sim_pid)\n# # print(db[sim_pid]['title'])\n# print('-----')\n\ndef get_similar(pid):\n pid = strip_version(pid)\n ID = pids.index(pid)\n return [pids[IX[i][ID]] for i in range(1, 11)]\n\n# pid = '1904.07460' \n# print(get_similar(pid))","sub_path":"elmo_nn.py","file_name":"elmo_nn.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"376608009","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@CreateTime: 2018-10-10T12:16:31+09:00\n@Email: guozhilingty@gmail.com\n@Copyright: Chokurei\n@License: MIT\n\nGeosr - A Computer Vision Package for Remote Sensing Image Super Resolution\n\"\"\"\nfrom __future__ import print_function\nimport argparse\nimport os\nimport torch\nimport torch.optim as optim\nfrom archs.vdsr import VDSR\nfrom utils.loader import get_training_set, get_val_set, get_eval_set\nfrom utils.trainer import Trainer\nfrom utils.tester import Tester\n\nDIR = os.path.dirname(os.path.abspath(__file__))\nmethod = os.path.basename(__file__).split(\".\")[0]\n\n#def main(args):\n# print(args)\n# if args.cuda and not torch.cuda.is_available():\n# raise Exception(\"No GPU found, please run without --cuda\")\n# torch.manual_seed(args.seed)\n# device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n# \n# print('===> Loading datasets')\n# train_set = get_training_set(args.band_mode, args.data_dir, args.aug, args.aug_mode, args.crop_size, args.upscale_factor)\n# # tensor, len = 600, for each : (input, target) \n# val_set = get_val_set(args.band_mode, args.data_dir, args.aug, args.aug_mode, args.crop_size, args.upscale_factor)\n# test_set = get_test_set(args.band_mode, args.data_dir, args.aug, args.aug_mode, args.crop_size, args.upscale_factor)\n# \n# datasets = [train_set, val_set]\n# \n# print('===> Building model')\n# model = ESPCN(nb_channel=args.nb_channel, upscale_factor=args.upscale_factor, base_kernel=args.base_kernel).to(device)\n# #criterion = nn.MSELoss()\n# model.optimizer = optim.Adam(model.parameters(), lr=args.lr)\n# \n# run = Trainer(args, method)\n# run.training(model, datasets)\n# run.save_log()\n# run.learning_curve()\n# \n# run.evaluating(model, train_set, 'train')\n# run.evaluating(model, val_set, 'val')\n# run.evaluating(model, test_set, \"test\")\n# print('===> Complete training')\n# run.save_checkpoint(model)\n \n\nif __name__ == '__main__':\n # Training settings\n parser = argparse.ArgumentParser(description='PyTorch Super Res Example')\n parser.add_argument('--train', type=lambda x: (str(x).lower() == 'true'), default=True, help='train or not?')\n parser.add_argument('--band_mode', type=str, default='Y', choices=['Y', 'YCbCr', 'RGB'], help=\"band mode\")\n parser.add_argument('--data_dir', type=str, default=os.path.join(DIR, 'dataset','map-str'), help=\"data directory for training\")\n parser.add_argument('--crop_size', type=int, default=224, help='crop size from each data. Default=224 (same to image size)')\n parser.add_argument('--nb_channel', type=int, default=1, help=\"input image band, based on band_mode\")\n parser.add_argument('--interpolation', type=lambda x: (str(x).lower() == 'true'), default=True, help=\"conduct pre-interpolation or not\")\n parser.add_argument('--upscale_factor', type=int, default=2, help=\"super resolution upscale factor\")\n parser.add_argument('--aug', type=lambda x: (str(x).lower() == 'true'), default=True, help='data augmentation or not') \n parser.add_argument('--aug_mode', type=str, default='c', choices=['a', 'b', 'c', 'd', 'e'], \n help='data augmentation mode: a, b, c, d, e')\n parser.add_argument('--base_kernel', type=int, default=64, help=\"base kernel\")\n parser.add_argument('--batch_size', type=int, default=64, help='training batch size')\n parser.add_argument('--valbatch_size', type=int, default=10, help='validation batch size')\n parser.add_argument('--evalbatch_size', type=int, default=10, help='evaluation batch size')\n# parser.add_argument('--testbatch_size', type=int, default=1, help='testing batch size')\n parser.add_argument('--nEpochs', type=int, default=2, help='number of epochs to train for')\n parser.add_argument('--lr', type=float, default=0.01, help='Learning Rate. Default=0.01')\n parser.add_argument('--trigger', type=str, default='epoch', choices=['epoch', 'iter'],\n help='trigger type for logging')\n parser.add_argument('--interval', type=int, default=1,\n help='interval for logging')\n parser.add_argument('--middle_checkpoint', type=lambda x: (str(x).lower() == 'true'), default=True, help='save middle checkpoint of model or not')\n\n parser.add_argument('--cuda', type=lambda x: (str(x).lower() == 'true'), default=True, help='use cuda?') \n parser.add_argument('--threads', type=int, default=6, help='number of threads for data loader to use')\n parser.add_argument('--seed', type=int, default=123, help='random seed to use. Default=123')\n \n parser.add_argument('--test', type=lambda x: (str(x).lower() == 'true'), default=True, help='test or not?')\n# parser.add_argument('--test_dir', type=str, default=os.path.join(DIR, 'dataset','runway-alloc','images','test'), help=\"testing data directory\")\n parser.add_argument('--test_dir', type=str, default=os.path.join(DIR, 'dataset','map-str_test','images'), help=\"testing data directory\")\n parser.add_argument('--test_model_name', type=str, default='up2_ESPCN_epoch_200_Nov15_10.pth', help='model used for testing')\n\n parser.add_argument('--ground_truth', type=lambda x: (str(x).lower() == 'true'), default=False, help='have ground truth or not')\n parser.add_argument('--test_model', type=lambda x: (str(x).lower() == 'true'), default=True, help='test different models')\n parser.add_argument('--test_middle_checkpoint', type=lambda x: (str(x).lower() == 'true'), default=True, help='have middle checkpoints of one model')\n \n \n args = parser.parse_args()\n# result = main(args)\n \n print(args)\n if args.cuda and not torch.cuda.is_available():\n raise Exception(\"No GPU found, please run without --cuda\")\n torch.manual_seed(args.seed)\n device = torch.device(\"cuda\" if args.cuda else \"cpu\")\n if args.train:\n print('===> Loading datasets')\n train_set = get_training_set(args.band_mode, args.data_dir, args.interpolation, args.aug, args.aug_mode, args.crop_size, args.upscale_factor)\n # tensor, len = 600, for each : (input, target) \n val_set = get_val_set(args.band_mode, args.data_dir, args.interpolation, args.aug, args.aug_mode, args.crop_size, args.upscale_factor)\n eval_set = get_eval_set(args.band_mode, args.data_dir, args.interpolation, args.aug, args.aug_mode, args.crop_size, args.upscale_factor)\n \n datasets = [train_set, val_set]\n \n print('===> Building model')\n model = VDSR(nb_channel=args.nb_channel, base_kernel=args.base_kernel, num_residuals=8).to(device)\n #criterion = nn.MSELoss()\n model.optimizer = optim.Adam(model.parameters(), lr=args.lr)\n \n trainer = Trainer(args, method)\n trainer.training(model, datasets)\n trainer.save_log()\n trainer.learning_curve()\n \n trainer.evaluating(model, train_set, 'train')\n trainer.evaluating(model, val_set, 'val')\n trainer.evaluating(model, eval_set, \"test\")\n print('===> Complete training')\n model_name = trainer.save_checkpoint(model) \n\n if args.test: \n if args.train:\n args.test_model_name = model_name\n model_name = args.test_model_name\n test_dir = args.test_dir\n tester = Tester(args)\n if args.test_model:\n tester.testing_model(model_name, test_dir)\n if args.test_middle_checkpoint:\n tester.testing_middle_checkpoint(model_name, test_dir)\n\n \n ","sub_path":"VDSR.py","file_name":"VDSR.py","file_ext":"py","file_size_in_byte":7523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"388923769","text":"import socket\nimport asyncio\nimport time\nimport random\nimport json\nimport boto3\nimport botocore\nfrom botocore.config import Config\n\nfrom walkoff_app_sdk.app_base import AppBase\n\nclass AWSEC2(AppBase):\n __version__ = \"1.0.0\"\n app_name = \"AWS ec2\" \n\n def __init__(self, redis, logger, console_logger=None):\n \"\"\"\n Each app should have this __init__ to set up Redis and logging.\n :param redis:\n :param logger:\n :param console_logger:\n \"\"\"\n super().__init__(redis, logger, console_logger)\n\n async def auth_ec2(self, access_key, secret_key, region):\n my_config = Config(\n region_name = region,\n signature_version = 'v4',\n retries = {\n 'max_attempts': 10,\n 'mode': 'standard'\n },\n )\n\n self.ec2 = boto3.resource(\n 'ec2', \n config=my_config, \n aws_access_key_id=access_key,\n aws_secret_access_key=secret_key,\n )\n\n return self.ec2\n\n # Write your data inside this function\n async def get_rules(self, access_key, secret_key, region, ACL_id):\n self.ec2 = await self.auth_ec2(access_key, secret_key, region)\n\n network_acl = self.ec2.NetworkAcl(ACL_id)\n return network_acl.entries\n\n # Write your data inside this function\n async def block_ip(self, access_key, secret_key, region, ACL_id, ip, direction):\n self.ec2 = await self.auth_ec2(access_key, secret_key, region)\n network_acl = self.ec2.NetworkAcl(ACL_id)\n\n if \"/\" not in ip:\n ip = \"%s/32\" % ip\n\n egress = True \n if direction == \"inbound\":\n egress = False\n\n # This is a shitty system :)\n minimum = 100\n max_range = 30000\n numbers = []\n found = False\n for item in network_acl.entries:\n if egress != item[\"Egress\"]:\n continue\n\n if ip == item[\"CidrBlock\"]:\n raise Exception(\"IP %s is already being blocked.\" % ip)\n\n numbers.append(item[\"RuleNumber\"])\n\n\n for index in range(minimum, max_range):\n if index in numbers:\n continue\n\n minimum = index\n break\n\n print(\"New number: %d\" % minimum)\n\n try:\n return network_acl.create_entry(\n CidrBlock=ip,\n DryRun=False,\n Egress=egress,\n IcmpTypeCode={\n 'Code': 123,\n 'Type': 123\n },\n PortRange={\n 'From': 0,\n 'To': 65535\n },\n Protocol=\"6\",\n RuleAction=\"DENY\",\n RuleNumber=minimum,\n )\n except botocore.exceptions.ClientError as e:\n print(\"Error: %s\" % e)\n return \"%s\" % e\n\n\n # Write your data inside this function\n async def create_acl_entry(self, access_key, secret_key, region, ACL_id, cidr_block, dryrun, direction, portrange_from, portrange_to, protocol, rule_action, rule_number):\n self.ec2 = await self.auth_ec2(access_key, secret_key, region)\n\n network_acl = self.ec2.NetworkAcl(ACL_id)\n if protocol.lower() == \"tcp\":\n protocol = \"6\"\n elif protocol.lower() == \"udp\":\n protocol = \"17\"\n\n egress = True \n if direction == \"inbound\":\n egress = False\n else:\n egress = True\n\n if dryrun.lower() == \"false\":\n dryrun = False\n else:\n dryrun = True\n\n try:\n return network_acl.create_entry(\n CidrBlock=cidr_block,\n DryRun=dryrun,\n Egress=egress,\n IcmpTypeCode={\n 'Code': 123,\n 'Type': 123\n },\n PortRange={\n 'From': int(portrange_from),\n 'To': int(portrange_to)\n },\n Protocol=protocol,\n RuleAction=rule_action,\n RuleNumber=int(rule_number),\n )\n except botocore.exceptions.ClientError as e:\n print(\"Error: %s\" % e)\n return \"%s\" % e\n\n\nif __name__ == \"__main__\":\n asyncio.run(AWSEC2.run(), debug=True)\n","sub_path":"aws-ec2/1.0.0/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"241010221","text":"pos = (0, 0)\ndirection = (0, 1)\nvisited = {pos}\nfirst_revisit = None\n\n\ndef turn(LR):\n global direction\n if LR == 'L':\n direction = (-direction[1], direction[0])\n elif LR == 'R':\n direction = (direction[1], -direction[0])\n\n\nwith open('day1.txt') as f:\n steps = f.read().split(', ')\n\nfor step in steps:\n d, num = step[0], int(step[1:])\n turn(d)\n for _ in range(num):\n pos = (pos[0] + direction[0], pos[1] + direction[1])\n if pos in visited and first_revisit is None:\n first_revisit = pos\n visited.add(pos)\n\nprint(first_revisit)\nprint(pos)\n\nprint(abs(pos[0]) + abs(pos[1]))\nprint(abs(first_revisit[0]) + abs(first_revisit[1]))\n","sub_path":"2016/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"94816321","text":"import socket\n# half-duplex\ndef send_msg(udp_socket):\n\t# get the info\n\tmsg = input(\"send info:\")\n\tdest_ip = input(\"dest_ip:\")\n\tdest_port = int(input(\"dest_port:\"))\n\tudp_socket.sendto(msg.encode(\"utf-8\"), (dest_ip, dest_port))\n\ndef recv_msg(udp_socket):\n\trecv_data = udp_socket.recvfrom(1024)\n\tmsg = recv_data[0].decode(\"utf-8\")\n\tip_and_port = recv_data[1]\n\tprint(\"%s : %s\" % (str(ip_and_port), msg.decode(\"utf-8\")))\n\n\ndef main():\n\t# create socket\n\tudp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\t# local ip and port\n\tlocaladdr = (\"\", 7880)\n\tudp_socket.bind(localaddr)\n\t# chat\n\twhile True:\n\t\t# send\n\t\tsend_msg(udp_socket)\n\t\t# receive\n\t\trecv_msg(udp_socket)\n\n\tudp_socket.close()\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"Udp_Tcp/udp_half-duple.py","file_name":"udp_half-duple.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"193907155","text":"import numpy as np\n\n\nclass Mcsrch():\n infoc = [0]\n j = 0\n dg = 0\n dgm = 0\n dginit = 0\n dgtest = 0\n dgx = [0.0]\n dgxm = [0.0]\n dgy = [0.0]\n dgym = [0.0]\n finit = 0\n ftest1 = 0\n fm = 0\n fx = [0.0]\n fxm = [0.0]\n fy = [0.0]\n fym = [0.0]\n p5 = 0\n p66 = 0\n stx = [0.0]\n sty = [0.0]\n stmin = 0\n stmax = 0\n width = 0\n width1 = 0\n xtrapf = 0\n brackt = [False]\n stage1 = False\n\n @staticmethod\n def sqr(x):\n return x*x\n\n @staticmethod\n def max3(x, y, z):\n return np.max([x, y, z])\n\n @staticmethod\n def mcsrch(n, x, f, g, s, is0, stp, ftol, xtol, maxfev, info, nfev, wa, gtol, stpmin, stpmax):\n p5 = 0.5\n p66 = 0.66\n xtrapf = 4\n\n if info[0] != - 1:\n Mcsrch.infoc[0] = 1\n if n <= 0 or stp[0] <= 0 or ftol < 0 or gtol < 0 or xtol < 0 or stpmin < 0 or stpmax < stpmin or maxfev <= 0:\n return\n\n # Compute the initial gradient in the search direction\n # and check that s is a descent direction.\n\n Mcsrch.dginit = 0\n\n for j in range(1, n+1):\n Mcsrch.dginit = Mcsrch.dginit + g[j - 1] * s[is0 + j - 1]\n\n if Mcsrch.dginit >= 0:\n print(\"The search direction is not a descent direction.\")\n return\n\n Mcsrch.brackt[0] = False\n Mcsrch.stage1 = True\n nfev[0] = 0\n Mcsrch.finit = f\n Mcsrch.dgtest = ftol * Mcsrch.dginit\n Mcsrch.width = stpmax - stpmin\n Mcsrch.width1 = Mcsrch.width / p5\n\n for j in range(1, n+1):\n wa[j - 1] = x[j - 1]\n\n # The variables stx, fx, dgx contain the values of the step,\n # function, and directional derivative at the best step.\n # The variables sty, fy, dgy contain the value of the step,\n # function, and derivative at the other endpoint of\n # the interval of uncertainty.\n # The variables stp, f, dg contain the values of the step,\n # function, and derivative at the current step.\n\n Mcsrch.stx[0] = 0\n Mcsrch.fx[0] = Mcsrch.finit\n Mcsrch.dgx[0] = Mcsrch.dginit\n Mcsrch.sty[0] = 0\n Mcsrch.fy[0] = Mcsrch.finit\n Mcsrch.dgy[0] = Mcsrch.dginit\n\n while True:\n if info[0] != -1:\n # Set the minimum and maximum steps to correspond\n # to the present interval of uncertainty.\n\n if Mcsrch.brackt[0]:\n Mcsrch.stmin = np.min([Mcsrch.stx[0], Mcsrch.sty[0]])\n Mcsrch.stmax = np.max([Mcsrch.stx[0], Mcsrch.sty[0]])\n else:\n Mcsrch.stmin = Mcsrch.stx[0]\n Mcsrch.stmax = stp[0] + xtrapf * (stp[0] - Mcsrch.stx[0])\n\n # Force the step to be within the bounds stpmax and stpmin.\n stp[0] = np.max([stp[0], stpmin])\n stp[0] = np.min([stp[0], stpmax])\n\n # If an unusual termination is to occur then let\n # stp be the lowest point obtained so far.\n\n if (Mcsrch.brackt[0] and (stp[0] <= Mcsrch.stmin or stp[0] >= Mcsrch.stmax)) or nfev[0] >= maxfev - 1 or Mcsrch.infoc[0] == 0 or (Mcsrch.brackt[0] and Mcsrch.stmax - Mcsrch.stmin <= xtol * Mcsrch.stmax):\n stp[0] = Mcsrch.stx[0]\n\n # Evaluate the function and gradient at stp\n # and compute the directional derivative.\n # We return to main program to obtain F and G.\n\n for j in range(1, n+1):\n x[j - 1] = wa[j - 1] + stp[0] * s[is0 + j - 1]\n\n info[0] = -1\n return\n\n info[0] = 0\n nfev[0] = nfev[0] + 1\n Mcsrch.dg = 0\n\n for j in range(1, n+1):\n Mcsrch.dg = Mcsrch.dg + g[j - 1] * s[is0 + j - 1]\n\n ftest1 = Mcsrch.finit + stp[0] * Mcsrch.dgtest\n\n # Test for convergence.\n\n if (Mcsrch.brackt[0] and (stp[0] <= Mcsrch.stmin or stp[0] >= Mcsrch.stmax)) or Mcsrch.infoc[0] == 0:\n info[0] = 6\n\n if stp[0] == stpmax and f <= ftest1 and Mcsrch.dg <= Mcsrch.dgtest:\n info[0] = 5\n\n if stp[0] == stpmin and (f > ftest1 or Mcsrch.dg >= Mcsrch.dgtest):\n info[0] = 4\n\n if nfev[0] >= maxfev:\n info[0] = 3\n\n if Mcsrch.brackt[0] and Mcsrch.stmax - Mcsrch.stmin <= xtol * Mcsrch.stmax:\n info[0] = 2\n\n if f <= ftest1 and np.abs(Mcsrch.dg) <= gtol * (- Mcsrch.dginit):\n info[0] = 1\n\n # Check for termination.\n\n if info[0] != 0:\n return\n\n # In the first stage we seek a step for which the modified\n # function has a nonpositive value and nonnegative derivative.\n\n if Mcsrch.stage1 and f <= ftest1 and Mcsrch.dg >= np.min([ftol, gtol]) * Mcsrch.dginit:\n Mcsrch.stage1 = False\n\n # A modified function is used to predict the step only if\n # we have not obtained a step for which the modified\n # function has a nonpositive function value and nonnegative\n # derivative, and if a lower function value has been\n # obtained but the decrease is not sufficient.\n\n if Mcsrch.stage1 and f <= Mcsrch.fx[0] and f > ftest1:\n # Define the modified function and derivative values.\n\n Mcsrch.fm = f - stp[0] * Mcsrch.dgtest\n Mcsrch.fxm[0] = Mcsrch.fx[0] - Mcsrch.stx[0] * Mcsrch.dgtest\n Mcsrch.fym[0] = Mcsrch.fy[0] - Mcsrch.sty[0] * Mcsrch.dgtest\n Mcsrch.dgm = Mcsrch.dg - Mcsrch.dgtest\n Mcsrch.dgxm[0] = Mcsrch.dgx[0] - Mcsrch.dgtest\n Mcsrch.dgym[0] = Mcsrch.dgy[0] - Mcsrch.dgtest\n\n # Call cstep to update the interval of uncertainty\n # and to compute the new step.\n Mcsrch.mcstep(Mcsrch.stx, Mcsrch.fxm, Mcsrch.dgxm, Mcsrch.sty, Mcsrch.fym, Mcsrch.dgym,\n stp, Mcsrch.fm, Mcsrch.dgm, Mcsrch.brackt, Mcsrch.stmin, Mcsrch.stmax, Mcsrch.infoc)\n\n # Reset the function and gradient values for f.\n\n Mcsrch.fx[0] = Mcsrch.fxm[0] + Mcsrch.stx[0] * Mcsrch.dgtest\n Mcsrch.fy[0] = Mcsrch.fym[0] + Mcsrch.sty[0] * Mcsrch.dgtest\n Mcsrch.dgx[0] = Mcsrch.dgxm[0] + Mcsrch.dgtest\n Mcsrch.dgy[0] = Mcsrch.dgym[0] + Mcsrch.dgtest\n else:\n # Call mcstep to update the interval of uncertainty\n # and to compute the new step.\n Mcsrch.mcstep(Mcsrch.stx, Mcsrch.fx, Mcsrch.dgx, Mcsrch.sty, Mcsrch.fy, Mcsrch.dgy,\n stp, f, Mcsrch.dg, Mcsrch.brackt, Mcsrch.stmin, Mcsrch.stmax, Mcsrch.infoc)\n\n # Force a sufficient decrease in the size of the\n # interval of uncertainty.\n\n if Mcsrch.brackt[0]:\n if np.abs(Mcsrch.sty[0] - Mcsrch.stx[0]) >= p66 * Mcsrch.width1:\n stp[0] = Mcsrch.stx[0] + p5 * \\\n (Mcsrch.sty[0] - Mcsrch.stx[0])\n Mcsrch.width1 = Mcsrch.width\n Mcsrch.width = np.abs(Mcsrch.sty[0] - Mcsrch.stx[0])\n\n @staticmethod\n def mcstep(stx, fx, dx, sty, fy, dy, stp, fp, dp, brackt, stpmin, stpmax, info):\n info[0] = 0\n\n if (Mcsrch.brackt[0] and (stp[0] <= np.min([Mcsrch.stx[0], Mcsrch.sty[0]]) or stp[0] >= np.max([Mcsrch.stx[0], Mcsrch.sty[0]]))) or dx[0] * (stp[0] - Mcsrch.stx[0]) >= 0.0 or stpmax < stpmin:\n return\n\n sgnd = dp * (dx[0] / np.abs(dx[0]))\n\n if fp > Mcsrch.fx[0]:\n # First case\n info[0] = 1\n bound = True\n theta = 3 * (Mcsrch.fx[0] - fp) / \\\n (stp[0] - Mcsrch.stx[0]) + dx[0] + dp\n s = Mcsrch.max3(np.abs(theta), np.abs(dx[0]), np.abs(dp))\n gamma = s * np.sqrt(Mcsrch.sqr(theta / s) - (dx[0] / s) * (dp / s))\n if stp[0] < Mcsrch.stx[0]:\n gamma = - gamma\n p = (gamma - dx[0]) + theta\n q = ((gamma - dx[0]) + gamma) + dp\n r = p / q\n stpc = Mcsrch.stx[0] + r * (stp[0] - Mcsrch.stx[0])\n stpq = Mcsrch.stx[0] + ((dx[0] / ((Mcsrch.fx[0] - fp) / (\n stp[0] - Mcsrch.stx[0]) + dx[0])) / 2) * (stp[0] - Mcsrch.stx[0])\n if np.abs(stpc - Mcsrch.stx[0]) < np.abs(stpq - Mcsrch.stx[0]):\n stpf = stpc\n else:\n stpf = stpc + (stpq - stpc) / 2\n Mcsrch.brackt[0] = True\n elif sgnd < 0.0:\n # Second case\n info[0] = 2\n bound = False\n theta = 3 * (Mcsrch.fx[0] - fp) / \\\n (stp[0] - Mcsrch.stx[0]) + dx[0] + dp\n s = Mcsrch.max3(np.abs(theta), np.abs(dx[0]), np.abs(dp))\n gamma = s * np.sqrt(Mcsrch.sqr(theta / s) - (dx[0] / s) * (dp / s))\n if stp[0] > Mcsrch.stx[0]:\n gamma = - gamma\n p = (gamma - dp) + theta\n q = ((gamma - dp) + gamma) + dx[0]\n r = p / q\n stpc = stp[0] + r * (Mcsrch.stx[0] - stp[0])\n stpq = stp[0] + (dp / (dp - dx[0])) * (Mcsrch.stx[0] - stp[0])\n if np.abs(stpc - stp[0]) > np.abs(stpq - stp[0]):\n stpf = stpc\n else:\n stpf = stpq\n Mcsrch.brackt[0] = True\n elif np.abs(dp) < np.abs(dx[0]):\n # Third case\n info[0] = 3\n bound = True\n theta = 3 * (Mcsrch.fx[0] - fp) / \\\n (stp[0] - Mcsrch.stx[0]) + dx[0] + dp\n s = Mcsrch.max3(np.abs(theta), np.abs(dx[0]), np.abs(dp))\n gamma = s * \\\n np.sqrt(\n np.max([0, Mcsrch.sqr(theta / s) - (dx[0] / s) * (dp / s)]))\n if stp[0] > Mcsrch.stx[0]:\n gamma = - gamma\n p = (gamma - dp) + theta\n q = (gamma + (dx[0] - dp)) + gamma\n r = p / q\n if r < 0.0 and gamma != 0.0:\n stpc = stp[0] + r * (Mcsrch.stx[0] - stp[0])\n elif stp[0] > Mcsrch.stx[0]:\n stpc = stpmax\n else:\n stpc = stpmin\n\n stpq = stp[0] + (dp / (dp - dx[0])) * (Mcsrch.stx[0] - stp[0])\n if Mcsrch.brackt[0]:\n if np.abs(stp[0] - stpc) < np.abs(stp[0] - stpq):\n stpf = stpc\n else:\n stpf = stpq\n else:\n if np.abs(stp[0] - stpc) > np.abs(stp[0] - stpq):\n stpf = stpc\n else:\n stpf = stpq\n else:\n # Fourth case.\n info[0] = 4\n bound = False\n if Mcsrch.brackt[0]:\n theta = 3 * (fp - Mcsrch.fy[0]) / \\\n (Mcsrch.sty[0] - stp[0]) + dy[0] + dp\n s = Mcsrch.max3(np.abs(theta), np.abs(dy[0]), np.abs(dp))\n gamma = s * np.sqrt(Mcsrch.sqr(theta / s) -\n (dy[0] / s) * (dp / s))\n if stp[0] > Mcsrch.sty[0]:\n gamma = - gamma\n p = (gamma - dp) + theta\n q = ((gamma - dp) + gamma) + dy[0]\n r = p / q\n stpc = stp[0] + r * (Mcsrch.sty[0] - stp[0])\n stpf = stpc\n elif stp[0] > Mcsrch.stx[0]:\n stpf = stpmax\n else:\n stpf = stpmin\n\n # Update the interval of uncertainty. This update does not\n # depend on the new step or the case analysis above.\n\n if fp > Mcsrch.fx[0]:\n Mcsrch.sty[0] = stp[0]\n Mcsrch.fy[0] = fp\n dy[0] = dp\n else:\n if sgnd < 0.0:\n Mcsrch.sty[0] = Mcsrch.stx[0]\n Mcsrch.fy[0] = Mcsrch.fx[0]\n dy[0] = dx[0]\n Mcsrch.stx[0] = stp[0]\n Mcsrch.fx[0] = fp\n dx[0] = dp\n\n # Compute the new step and safeguard it.\n\n stpf = np.min([stpmax, stpf])\n stpf = np.max([stpmin, stpf])\n stp[0] = stpf\n\n if Mcsrch.brackt[0] and bound:\n if Mcsrch.sty[0] > Mcsrch.stx[0]:\n stp[0] = np.min(\n [Mcsrch.stx[0] + 0.66 * (Mcsrch.sty[0] - Mcsrch.stx[0]), stp[0]])\n else:\n stp[0] = np.max(\n [Mcsrch.stx[0] + 0.66 * (Mcsrch.sty[0] - Mcsrch.stx[0]), stp[0]])\n\n return\n","sub_path":"LARA_LDA_Python/src/Mcsrch.py","file_name":"Mcsrch.py","file_ext":"py","file_size_in_byte":12684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"493412237","text":"import constants\r\nfrom random import randrange\r\nimport os \r\nimport cv2 \r\nimport numpy as np \r\nimport matplotlib.pyplot as plt \r\n\r\n#Insights on Image sizes\r\ndef image_size(data_dir):\r\n \r\n\r\n return dataframe\r\n\r\n# zero normalization \r\n\r\n# z-score \r\n\r\n#Image Analysis \r\n\r\n#Append all images to img_list and labels to \r\nimg_list, img_label = [], []\r\n\r\n#max_val is how many pictures from each category do you want to load for example max_val = 1100 means 2200 total images\r\nmax_val=1100\r\nimg_size=256\r\n\r\nfolder = []\r\nfor val in os.listdir(constants.TRAIN_DATA):\r\n path = os.path.join(constants.TRAIN_DATA, val)\r\n if os.path.isdir(path):\r\n folder.append(val)\r\n \r\nprint('Labels found in the Dataset: ',folder)\r\n\r\nj=0\r\nfor folder in folder:\r\n for img_file in os.listdir(os.path.join(constants.TRAIN_DATA,folder)):\r\n img_path = os.path.join(constants.TRAIN_DATA,folder)\r\n image= cv2.imread(os.path.join(img_path,img_file)) \r\n if image is not None:\r\n img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) \r\n img= cv2.resize(img,(img_size, img_size))\r\n image= cv2.GaussianBlur(img,(5,5),0) \r\n img_list.append(image)\r\n if folder == 'NORMAL':\r\n img_label.append(0)\r\n else:\r\n img_label.append(1)\r\n j=j+1\r\n if j >= max_val:\r\n j=0\r\n break\r\n \r\nimg_list,img_label=np.array(img_list),np.array(img_label)\r\n\r\n#Print a random image\r\ni = randrange(max_val*2)\r\nprint(\"Image NUmber: \", i)\r\n\r\n#Original Image\r\nplt.imshow(img_list[i],cmap='gray')\r\nplt.xticks([])\r\nplt.yticks([])\r\nplt.title(\"Original Image\")\r\nplt.show()\r\n\r\n#Histogram\r\nplt.hist(img_list[i].ravel(),256,[0,256])\r\nplt.title(\" Histogram of pixels in image\")\r\nplt.show()\r\n\r\n#Laplacian\r\nlaplacian = cv2.Laplacian(img_list[i],cv2.CV_8UC1)\r\nplt.imshow(laplacian,cmap='gray')\r\nplt.xticks([])\r\nplt.yticks([])\r\nplt.title(\" Laplacian Image\")\r\nplt.show()\r\n\r\n#Canny\r\ncanny = cv2.Canny(img_list[i],40,200)\r\nplt.imshow(canny,cmap='gray')\r\nplt.xticks([])\r\nplt.yticks([])\r\nplt.title(\"Canny edge detection\")\r\nplt.show()\r\n\r\n#SobelX\r\nSobelX = cv2.Sobel(img_list[i],cv2.CV_8UC1,1,0,ksize=5)\r\nplt.imshow(SobelX,cmap='gray')\r\nplt.xticks([])\r\nplt.yticks([])\r\nplt.title(\"SobelX filter\")\r\nplt.show()\r\n\r\n#SobelY\r\nsobelY = cv2.Sobel(img_list[i],cv2.CV_8UC1,0,1,ksize=5)\r\nplt.imshow(sobelY,cmap='gray')\r\nplt.xticks([])\r\nplt.yticks([])\r\nplt.title(\"SobelY filter\")\r\nplt.show()\r\n\r\n#SobelXY\r\nsobelXY = cv2.Sobel(img_list[i],cv2.CV_8UC1,1,1,ksize=5)\r\nplt.imshow(sobelXY,cmap='gray')\r\nplt.xticks([])\r\nplt.yticks([])\r\nplt.title(\"SobelXY filter\")\r\nplt.show()\r\n\r\n#thresholding\r\nret, th1 = cv2.threshold(img_list[i],100,255,cv2.THRESH_TOZERO)\r\nplt.imshow(th1,cmap='gray')\r\nplt.xticks([])\r\nplt.yticks([])\r\nplt.title(\" Thresholding on Image\")\r\nplt.show()\r\n\r\nblurr = cv2.GaussianBlur(img_list[i],(5,5),0)\r\nret, th2 = cv2.threshold(img_list[i],120,255,cv2.THRESH_BINARY)\r\nplt.imshow(th2,cmap='gray')\r\nplt.xticks([])\r\nplt.yticks([])\r\nplt.title(\"Gaussian Blur\")\r\nplt.show()\r\n\r\n#Sharpening\r\nkernel_sharpening = np.array([[-1,-1,-1], \r\n [-1, 9,-1],\r\n [-1,-1,-1]])\r\nsharpened = cv2.filter2D(img_list[i], -1, kernel_sharpening)\r\nplt.imshow(sharpened,cmap='gray')\r\nplt.xticks([])\r\nplt.yticks([])\r\nplt.title(\" Sharpening of Image\")\r\nplt.show()","sub_path":"insights.py","file_name":"insights.py","file_ext":"py","file_size_in_byte":3385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"308163552","text":"import sys\ndef solution(liq):\n l=0\n r=len(liq)-1\n ans = [abs(liq[l]+liq[r]),(liq[l],liq[r])]\n\n while l 0:\n r-=1\n elif mix < 0:\n l += 1\n else:\n return ans[1]\n return ans[1]\n\nif __name__== \"__main__\":\n n = map(int,sys.stdin.readline().split())\n liq = list(map(int,sys.stdin.readline().split()))\n ans = solution(liq)\n print(\"{} {}\".format(ans[0],ans[1]))\n","sub_path":"beakjoon/2468 용액/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"255424082","text":"import argparse\n\nimport lasagne.nonlinearities as NL\nimport sys\n\nfrom rllab.algos.dqn import DQN\nfrom rllab.envs.gym_env import GymEnv\nfrom rllab.envs.preprocess_env import PreprocessEnv\nfrom rllab.envs.sliding_mem_env import SlidingMemEnv\nfrom rllab.exploration_strategies.epsilon_strategy import EpsilonGreedyStrategy\nfrom rllab.misc.instrument import run_experiment_lite\nfrom rllab.policies.deterministic_conv_policy import DeterministicConvPolicy\n\nenv_name = 'SpaceInvaders-v0'\nn_epochs = 200\nparser = argparse.ArgumentParser()\nparser.add_argument('--env', type=str, default=env_name,\n help='Name of the environment. Deefault value is SpaceInvaders-v0')\nparser.add_argument('--n_epochs', type=int, default=n_epochs,\n help='Number of epochs. Default value is 200')\nargs = parser.parse_args(sys.argv[1:])\n\nif args.env:\n env_name = args.env\nif args.n_epochs:\n n_epochs = args.n_epochs\n\n\ndef run_task(*_):\n agent_history_length = 4\n resized_shape = (84, 84)\n\n env = GymEnv(env_name=env_name, record_video=False, record_log=False, force_reset=True)\n env = PreprocessEnv(env, new_shape=resized_shape)\n env = SlidingMemEnv(env, n_steps=agent_history_length)\n\n policy = DeterministicConvPolicy(\n env_spec=env.spec,\n conv_filters=(32, 64, 64),\n conv_filter_sizes=(8, 4, 3),\n conv_strides=(4, 2, 1),\n conv_pads=('valid', 'valid', 'valid'),\n hidden_sizes=[512],\n hidden_nonlinearity=NL.rectify,\n output_nonlinearity=NL.linear\n )\n\n es = EpsilonGreedyStrategy(\n env_spec=env.spec,\n eps_start=1.0,\n eps_final=0.1,\n eps_itr_start=0, # 200,\n eps_itr_final=1000000,\n )\n\n algo_lite = DQN(\n env,\n policy,\n es,\n n_epochs=n_epochs,\n epoch_length=1000, # 1000,\n batch_size=2,\n discount=0.99,\n replay_memory_size=20000, # 20000 #10^5=11gb\n min_replay_memory_size=5000, # 2000, #50000\n target_network_update_frequency=500, # 500, #10000,\n agent_history_length=agent_history_length,\n resized_shape=resized_shape,\n eval_max_samples=5000, # 10000,#50000,\n eval_max_path_length=500, # 1000,s\n update_method='rmsprop',\n update_method_kwargs=dict(\n learning_rate=0.00025, rho=0.95, epsilon=1e-2),\n # plot=True,\n )\n\n algo = DQN(\n env,\n policy,\n es,\n n_epochs=n_epochs,\n epoch_length=50000, #1000,\n batch_size=32,\n discount=0.99,\n replay_memory_size=1000000, #20000 #10^5=11gb\n min_replay_memory_size=50000, #2000, #50000\n target_network_update_frequency=10000, #500, #10000,\n agent_history_length=agent_history_length,\n resized_shape=resized_shape,\n eval_max_samples=100000,#10000,#50000,\n eval_max_path_length=2000,#1000,s\n # plot=True,\n )\n\n # TODO: dont forget to train your algorithm\n algo_lite.train()\n\n\n# run experiment\nrun_experiment_lite(\n run_task,\n exp_prefix=env_name,\n exp_name=\"dqn\",\n # Number of parallel workers for sampling.\n n_parallel=1,\n # Only keep the snapshot parameters for the last iteration\n snapshot_mode=\"all\",\n mode=\"local\",\n use_gpu=True, # TODO True\n # Specifies the seed for the experiment. If this is not provided, a random seed\n # will be used\n seed=717836484,\n # plot=True,\n)\n","sub_path":"experiments/dqn_demo.py","file_name":"dqn_demo.py","file_ext":"py","file_size_in_byte":3444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"421602842","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/PIL/JpegImagePlugin.py\n# Compiled at: 2007-09-25 20:00:35\n__version__ = '0.5'\nimport array, string, Image, ImageFile\n\ndef i16(c, o=0):\n return ord(c[(o + 1)]) + (ord(c[o]) << 8)\n\n\ndef i32(c, o=0):\n return ord(c[(o + 3)]) + (ord(c[(o + 2)]) << 8) + (ord(c[(o + 1)]) << 16) + (ord(c[o]) << 24)\n\n\ndef Skip(self, marker):\n n = i16(self.fp.read(2)) - 2\n ImageFile._safe_read(self.fp, n)\n\n\ndef APP(self, marker):\n n = i16(self.fp.read(2)) - 2\n s = ImageFile._safe_read(self.fp, n)\n app = 'APP%d' % (marker & 15)\n self.app[app] = s\n self.applist.append((app, s))\n if marker == 65504 and s[:4] == 'JFIF':\n self.info['jfif'] = version = i16(s, 5)\n self.info['jfif_version'] = divmod(version, 256)\n try:\n jfif_unit = ord(s[7])\n jfif_density = (i16(s, 8), i16(s, 10))\n except:\n pass\n else:\n if jfif_unit == 1:\n self.info['dpi'] = jfif_density\n self.info['jfif_unit'] = jfif_unit\n self.info['jfif_density'] = jfif_density\n elif marker == 65505 and s[:5] == 'Exif\\x00':\n self.info['exif'] = s\n elif marker == 65506 and s[:5] == 'FPXR\\x00':\n self.info['flashpix'] = s\n elif marker == 65518 and s[:5] == 'Adobe':\n self.info['adobe'] = i16(s, 5)\n try:\n adobe_transform = ord(s[1])\n except:\n pass\n else:\n self.info['adobe_transform'] = adobe_transform\n\n\ndef COM(self, marker):\n n = i16(self.fp.read(2)) - 2\n s = ImageFile._safe_read(self.fp, n)\n self.app['COM'] = s\n self.applist.append(('COM', s))\n\n\ndef SOF(self, marker):\n n = i16(self.fp.read(2)) - 2\n s = ImageFile._safe_read(self.fp, n)\n self.size = (i16(s[3:]), i16(s[1:]))\n self.bits = ord(s[0])\n if self.bits != 8:\n raise SyntaxError('cannot handle %d-bit layers' % self.bits)\n self.layers = ord(s[5])\n if self.layers == 1:\n self.mode = 'L'\n elif self.layers == 3:\n self.mode = 'RGB'\n elif self.layers == 4:\n self.mode = 'CMYK'\n else:\n raise SyntaxError('cannot handle %d-layer images' % self.layers)\n if marker in (65474, 65478, 65482, 65486):\n self.info['progression'] = 1\n for i in range(6, len(s), 3):\n t = s[i:i + 3]\n self.layer.append((t[0], ord(t[1]) / 16, ord(t[1]) & 15, ord(t[2])))\n\n\ndef DQT(self, marker):\n n = i16(self.fp.read(2)) - 2\n s = ImageFile._safe_read(self.fp, n)\n while len(s):\n if len(s) < 65:\n raise SyntaxError('bad quantization table marker')\n v = ord(s[0])\n if v / 16 == 0:\n self.quantization[v & 15] = array.array('b', s[1:65])\n s = s[65:]\n else:\n return\n\n\nMARKER = {65472: (\n 'SOF0', 'Baseline DCT', SOF), \n 65473: (\n 'SOF1', 'Extended Sequential DCT', SOF), \n 65474: (\n 'SOF2', 'Progressive DCT', SOF), \n 65475: (\n 'SOF3', 'Spatial lossless', SOF), \n 65476: (\n 'DHT', 'Define Huffman table', Skip), \n 65477: (\n 'SOF5', 'Differential sequential DCT', SOF), \n 65478: (\n 'SOF6', 'Differential progressive DCT', SOF), \n 65479: (\n 'SOF7', 'Differential spatial', SOF), \n 65480: ('JPG', 'Extension', None), \n 65481: (\n 'SOF9', 'Extended sequential DCT (AC)', SOF), \n 65482: (\n 'SOF10', 'Progressive DCT (AC)', SOF), \n 65483: (\n 'SOF11', 'Spatial lossless DCT (AC)', SOF), \n 65484: (\n 'DAC', 'Define arithmetic coding conditioning', Skip), \n 65485: (\n 'SOF13', 'Differential sequential DCT (AC)', SOF), \n 65486: (\n 'SOF14', 'Differential progressive DCT (AC)', SOF), \n 65487: (\n 'SOF15', 'Differential spatial (AC)', SOF), \n 65488: ('RST0', 'Restart 0', None), \n 65489: ('RST1', 'Restart 1', None), \n 65490: ('RST2', 'Restart 2', None), \n 65491: ('RST3', 'Restart 3', None), \n 65492: ('RST4', 'Restart 4', None), \n 65493: ('RST5', 'Restart 5', None), \n 65494: ('RST6', 'Restart 6', None), \n 65495: ('RST7', 'Restart 7', None), \n 65496: ('SOI', 'Start of image', None), \n 65497: ('EOI', 'End of image', None), \n 65498: (\n 'SOS', 'Start of scan', Skip), \n 65499: (\n 'DQT', 'Define quantization table', DQT), \n 65500: (\n 'DNL', 'Define number of lines', Skip), \n 65501: (\n 'DRI', 'Define restart interval', Skip), \n 65502: (\n 'DHP', 'Define hierarchical progression', SOF), \n 65503: (\n 'EXP', 'Expand reference component', Skip), \n 65504: (\n 'APP0', 'Application segment 0', APP), \n 65505: (\n 'APP1', 'Application segment 1', APP), \n 65506: (\n 'APP2', 'Application segment 2', APP), \n 65507: (\n 'APP3', 'Application segment 3', APP), \n 65508: (\n 'APP4', 'Application segment 4', APP), \n 65509: (\n 'APP5', 'Application segment 5', APP), \n 65510: (\n 'APP6', 'Application segment 6', APP), \n 65511: (\n 'APP7', 'Application segment 7', APP), \n 65512: (\n 'APP8', 'Application segment 8', APP), \n 65513: (\n 'APP9', 'Application segment 9', APP), \n 65514: (\n 'APP10', 'Application segment 10', APP), \n 65515: (\n 'APP11', 'Application segment 11', APP), \n 65516: (\n 'APP12', 'Application segment 12', APP), \n 65517: (\n 'APP13', 'Application segment 13', APP), \n 65518: (\n 'APP14', 'Application segment 14', APP), \n 65519: (\n 'APP15', 'Application segment 15', APP), \n 65520: ('JPG0', 'Extension 0', None), \n 65521: ('JPG1', 'Extension 1', None), \n 65522: ('JPG2', 'Extension 2', None), \n 65523: ('JPG3', 'Extension 3', None), \n 65524: ('JPG4', 'Extension 4', None), \n 65525: ('JPG5', 'Extension 5', None), \n 65526: ('JPG6', 'Extension 6', None), \n 65527: ('JPG7', 'Extension 7', None), \n 65528: ('JPG8', 'Extension 8', None), \n 65529: ('JPG9', 'Extension 9', None), \n 65530: ('JPG10', 'Extension 10', None), \n 65531: ('JPG11', 'Extension 11', None), \n 65532: ('JPG12', 'Extension 12', None), \n 65533: ('JPG13', 'Extension 13', None), \n 65534: (\n 'COM', 'Comment', COM)}\n\ndef _accept(prefix):\n return prefix[0] == b'\\xff'\n\n\nclass JpegImageFile(ImageFile.ImageFile):\n format = 'JPEG'\n format_description = 'JPEG (ISO 10918)'\n\n def _open(self):\n s = self.fp.read(1)\n if ord(s[0]) != 255:\n raise SyntaxError('not a JPEG file')\n self.bits = self.layers = 0\n self.layer = []\n self.huffman_dc = {}\n self.huffman_ac = {}\n self.quantization = {}\n self.app = {}\n self.applist = []\n while 1:\n s = s + self.fp.read(1)\n i = i16(s)\n if MARKER.has_key(i):\n (name, description, handler) = MARKER[i]\n if handler is not None:\n handler(self, i)\n if i == 65498:\n rawmode = self.mode\n if self.mode == 'CMYK':\n rawmode = 'CMYK;I'\n self.tile = [\n (\n 'jpeg', (0, 0) + self.size, 0, (rawmode, ''))]\n break\n s = self.fp.read(1)\n elif i == 0 or i == 65535:\n s = b'\\xff'\n else:\n raise SyntaxError('no marker found')\n\n return\n\n def draft(self, mode, size):\n if len(self.tile) != 1:\n return\n (d, e, o, a) = self.tile[0]\n scale = 0\n if a[0] == 'RGB' and mode in ('L', 'YCbCr'):\n self.mode = mode\n a = (mode, '')\n if size:\n scale = max(self.size[0] / size[0], self.size[1] / size[1])\n for s in [8, 4, 2, 1]:\n if scale >= s:\n break\n\n e = (\n e[0], e[1], (e[2] - e[0] + s - 1) / s + e[0], (e[3] - e[1] + s - 1) / s + e[1])\n self.size = ((self.size[0] + s - 1) / s, (self.size[1] + s - 1) / s)\n scale = s\n self.tile = [(d, e, o, a)]\n self.decoderconfig = (scale, 1)\n return self\n\n def load_djpeg(self):\n import tempfile, os\n file = tempfile.mktemp()\n os.system('djpeg %s >%s' % (self.filename, file))\n try:\n self.im = Image.core.open_ppm(file)\n finally:\n try:\n os.unlink(file)\n except:\n pass\n\n self.mode = self.im.mode\n self.size = self.im.size\n self.tile = []\n\n def _getexif(self):\n import TiffImagePlugin, StringIO\n\n def fixup(value):\n if len(value) == 1:\n return value[0]\n return value\n\n try:\n data = self.info['exif']\n except KeyError:\n return\n else:\n file = StringIO.StringIO(data[6:])\n head = file.read(8)\n exif = {}\n info = TiffImagePlugin.ImageFileDirectory(head)\n info.load(file)\n for (key, value) in info.items():\n exif[key] = fixup(value)\n\n file.seek(exif[34665])\n info = TiffImagePlugin.ImageFileDirectory(head)\n info.load(file)\n for (key, value) in info.items():\n exif[key] = fixup(value)\n\n try:\n file.seek(exif[34853])\n except KeyError:\n pass\n else:\n info = TiffImagePlugin.ImageFileDirectory(head)\n info.load(file)\n exif[34853] = gps = {}\n for (key, value) in info.items():\n gps[key] = fixup(value)\n\n return exif\n\n\nRAWMODE = {'1': 'L', \n 'L': 'L', \n 'RGB': 'RGB', \n 'RGBA': 'RGB', \n 'RGBX': 'RGB', \n 'CMYK': 'CMYK;I', \n 'YCbCr': 'YCbCr'}\n\ndef _save(im, fp, filename):\n try:\n rawmode = RAWMODE[im.mode]\n except KeyError:\n raise IOError('cannot write mode %s as JPEG' % im.mode)\n\n info = im.encoderinfo\n dpi = info.get('dpi', (0, 0))\n im.encoderconfig = (\n info.get('quality', 0),\n info.has_key('progressive') or info.has_key('progression'),\n info.get('smooth', 0),\n info.has_key('optimize'),\n info.get('streamtype', 0),\n dpi[0], dpi[1])\n ImageFile._save(im, fp, [('jpeg', (0, 0) + im.size, 0, rawmode)])\n\n\ndef _save_cjpeg(im, fp, filename):\n import os\n file = im._dump()\n os.system('cjpeg %s >%s' % (file, filename))\n try:\n os.unlink(file)\n except:\n pass\n\n\nImage.register_open('JPEG', JpegImageFile, _accept)\nImage.register_save('JPEG', _save)\nImage.register_extension('JPEG', '.jfif')\nImage.register_extension('JPEG', '.jpe')\nImage.register_extension('JPEG', '.jpg')\nImage.register_extension('JPEG', '.jpeg')\nImage.register_mime('JPEG', 'image/jpeg')","sub_path":"pycfiles/Omelette-1.1.6-py2.6-linux-i686/JpegImagePlugin.py","file_name":"JpegImagePlugin.py","file_ext":"py","file_size_in_byte":11013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"545487294","text":"import discord\r\nfrom messages import misc_msg\r\nfrom discord.ext import commands\r\nfrom utils.database import Database\r\n\r\n\r\nclass Misc(commands.Cog):\r\n def __init__(self, client):\r\n self.client = client\r\n\r\n @commands.command()\r\n async def ping(self, ctx):\r\n await ctx.send(f':ping_pong: **Logker** latency is {round(self.client.latency * 1000)}ms!')\r\n\r\n @commands.command()\r\n async def donate(self, ctx):\r\n owner = self.client.get_user(254515724804947969)\r\n await ctx.send(embed=misc_msg.donate(owner))\r\n\r\n @commands.command()\r\n async def info(self, ctx):\r\n try:\r\n db = Database(ctx.guild.id) # Create a new instance\r\n\r\n info = await db.find_info()\r\n config_lang = info['logs_language'] if info is not None else 'en'\r\n\r\n except Exception:\r\n config_lang = 'en'\r\n\r\n owner = self.client.get_user(254515724804947969)\r\n\r\n await ctx.send(\r\n embed=misc_msg.info_en(ctx, owner, self.client) if config_lang == 'en'\r\n else misc_msg.info_en(ctx, owner, self.client)\r\n )\r\n\r\n await ctx.send(file=discord.File('assets/chaewon_muah.gif'))\r\n\r\n @commands.command()\r\n async def invite(self, ctx):\r\n owner = self.client.get_user(254515724804947969)\r\n await ctx.send(embed=misc_msg.invite(owner))\r\n\r\n @commands.command()\r\n async def github(self, ctx):\r\n owner = self.client.get_user(254515724804947969)\r\n await ctx.send(embed=misc_msg.github(owner))\r\n\r\n\r\ndef setup(client):\r\n client.add_cog(Misc(client))\r\n","sub_path":"cogs/Misc.py","file_name":"Misc.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"193168772","text":"import requests #importera requests\n\nnummer = input(\"ange ett nummer: \") # input variabel\nr = requests.get('http://77.238.56.27/examples/numinfo/?integer='+ str(nummer))# använder get request för att hämta värden från den urlen, och sedan lagrar de i variabel r\nres = r.json #använder r.json för att få en json object, alltså en dictionarie\n\nif res ['even']: # om even är san\n print(\"talet är jämt\") #print talet är jämt \nelse :\n print(\"talet är udda\")\n\nif res ['prime']: \n print(\"talet är ett primtal\")\nelse: \n print(\"talet är inte ett primtal\")\nprint (\"talet faktorer är: \")\n\nfor nummer0 in res['factors']: \n print (nummer0)\n","sub_path":"Python/kompendium/Kapitel 6/6,1.py","file_name":"6,1.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"149623051","text":"\"\"\" Trie-based parser for constructing queries \"\"\"\nimport logging as root_logger\nimport pyparsing as pp\n\nfrom acab.abstract.parsing import util as PU\nfrom acab.abstract.core.sentence import Sentence\nfrom acab.abstract.rule.query import Query, QueryOp, QueryComponent\nfrom acab.abstract.data.contexts import CTX_OP\n\nfrom acab.working_memory.trie_wm import util as WMU\n\nfrom acab.error.acab_parse_exception import AcabParseException\nfrom acab.config import AcabConfig\n\nfrom .FactParser import PARAM_CORE, PARAM_SEN, BASIC_SEN\n\nlogging = root_logger.getLogger(__name__)\n\nutil = AcabConfig.Get()\nCONSTRAINT_S = util(\"Parsing.Structure\", \"CONSTRAINT_S\")\nOPERATOR_S = util(\"Parsing.Structure\", \"OPERATOR_S\")\nVALUE_S = util(\"Parsing.Structure\", \"VALUE_S\")\nQUERY_S = util(\"Parsing.Structure\", \"QUERY_S\")\nNEGATION_S = util(\"Parsing.Structure\", \"NEGATION_S\")\nFALLBACK_S = util(\"Parsing.Structure\", \"FALLBACK_S\")\nMAIN_CLAUSE_S = util(\"WorkingMemory.TrieWM\", \"MAIN_CLAUSE_S\")\n\ndef build_constraint_list(toks):\n \"\"\" Build a constraint list \"\"\"\n return (CONSTRAINT_S, [x[1] for x in toks[:]])\n\ndef build_query_component(toks):\n \"\"\" Build a comparison \"\"\"\n op = toks[OPERATOR_S][0]\n return (CONSTRAINT_S, QueryComponent(op, param=toks[VALUE_S]))\n\ndef build_clause(toks):\n # detect negation and annotate the clause with it\n data = { QUERY_S : True,\n NEGATION_S : False,\n FALLBACK_S : None }\n if FALLBACK_S in toks:\n if NEGATION_S in toks:\n raise AcabParseException(\"Negated Fallback clauses don't make sense\")\n data[FALLBACK_S] = toks[FALLBACK_S][:]\n if NEGATION_S in toks:\n data[NEGATION_S] = True\n\n return Sentence(toks[MAIN_CLAUSE_S][:], data=data)\n\ndef build_query(toks):\n query = Query(toks[:])\n return (query.type, query)\n\ndef build_assignment(toks):\n return (toks[0][1], toks[1])\n\n\n# Build After comparison operators have been constructed:\nHOTLOAD_QUERY_OP = pp.Forward()\nHOTLOAD_QUERY_ANNOTATIONS = pp.Forward()\n\nop_path = pp.Or([HOTLOAD_QUERY_OP, PU.OP_PATH_C(BASIC_SEN)])\n\nQUERY_OP_Internal = PU.N(OPERATOR_S, op_path) \\\n + PU.N(VALUE_S, PARAM_CORE(end=True))\n\n# defined earlier to work with named copies\nQUERY_OP_Internal.setParseAction(build_query_component)\n\nCOLLAPSE_CONTEXT = PU.COLLAPSE_CONTEXT\nCOLLAPSE_CONTEXT.setParseAction(lambda x: (None, CTX_OP.collapse))\n\nquery_or_annotation = pp.Or([QUERY_OP_Internal, COLLAPSE_CONTEXT, HOTLOAD_QUERY_ANNOTATIONS])\n\nconstraints = pp.delimitedList(query_or_annotation, delim=PU.COMMA)\n\nassignment = PU.BIND + PU.COLON + PARAM_SEN\nassignmentList = pp.delimitedList(assignment, delim=PU.COMMA)\nfallback = PU.DOUBLEBAR + assignmentList\n\n# core component of a query, a modified PARAM_SEN\nQueryCore = PARAM_CORE(constraints)\nQueryCore_end = PARAM_CORE(constraints, end=True)\n\n# TODO add syntax for binding a sentence\n# a.test.query..<$x?\n# a.test.query..<$x(::Rule)?\n# Core Query Chain\nclause = PU.op(PU.NEGATION_SYMBOL) + PU.N(MAIN_CLAUSE_S, pp.ZeroOrMore(QueryCore)\n + QueryCore_end) \\\n + PU.QUERY_SYMBOL\\\n + PU.N(FALLBACK_S,\n PU.op(fallback))\n\nclauses = pp.delimitedList(clause, delim=PU.DELIM)\n\nquery_statement = PU.STATEMENT_CONSTRUCTOR(PU.QUERY_HEAD,\n BASIC_SEN,\n clauses + PU.component_gap)\n\n# Actions\nconstraints.setParseAction(build_constraint_list)\nclause.setParseAction(build_clause)\nclauses.setParseAction(build_query)\nassignment.setParseAction(build_assignment)\n\n# NAMING\nHOTLOAD_QUERY_OP.setName(\"QueryOperators\")\nHOTLOAD_QUERY_ANNOTATIONS.setName(\"QueryAnnotation\")\nQUERY_OP_Internal.setName(\"Query_Statements\")\nquery_or_annotation.setName(\"QueryOrAnnotation\")\nconstraints.setName(\"ConstraintList\")\nassignment.setName(\"FallbackAssignment\")\nassignmentList.setName(\"FallbackAssignmentList\")\nfallback.setName(\"QueryFallbackStatement\")\nQueryCore.setName(\"QueryCoreStatement\")\nQueryCore_end.setName(\"QueryCoreEndStatement\")\nclause.setName(\"QueryComponent\")\nclauses.setName(\"QueryComponentContainer\")\nquery_statement.setName(\"QueryDefinition\")\n\n\n# parse_point = clauses.ignore(PU.COMMENT)\nparse_point = clauses\n\n# Main parser:\ndef parseString(in_string, parse_point=parse_point):\n \"\"\" .a.b(>20)!d.$X, ... -> Query \"\"\"\n return parse_point.parseString(in_string)[0][1]\n","sub_path":"acab/working_memory/trie_wm/parsing/QueryParser.py","file_name":"QueryParser.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"399448476","text":"from pyspark.sql.types import ArrayType\nfrom pyspark.sql.types import StringType\nfrom pyspark.sql.functions import udf\nfrom pyspark.sql.functions import explode\nfrom pyspark.sql import SparkSession\nimport datetime\n\nspark=SparkSession.builder.getOrCreate()\ncurr_date = str(datetime.date.today())\n\n############ Config ############\n# This should be the HDFS_PATH location set in the first script\nHDFS_PATH=\"/tmp/fsimage/\"\n\n# The database name\ndbName = \"default\"\ntblName = \"fsimage_tbl\"\n################################\n\ntsvFilePath = HDFS_PATH + \"fsimage_\"+curr_date+\".tsv\"\ntsvDF = spark.read.option(\"header\",\"true\").csv(tsvFilePath,sep='\\t')\ntsvDF = tsvDF.select(\"Path\", \"Replication\", \"PreferredBlockSize\", \"BlocksCount\", \"FileSize\").filter(\"BlocksCount!=0\")\n\n# Split the paths such that eg: /tmp/tables/tbl1 is split to /, /tmp, /tmp/tables, /tmp/tables/tbl1\ndef splitPaths(str):\n index= 1\n paths = []\n while (index > 0):\n paths.append(str[:index])\n index = str.find(\"/\", index+1)\n return paths\n \nsplitPathsUDF = udf(splitPaths, ArrayType(StringType(),False))\nexplodedPaths = tsvDF.withColumn(\"Path\", explode(splitPathsUDF(tsvDF[\"Path\"])))\nexplodedPaths.createOrReplaceTempView(\"explodedpaths\")\n\nsmallBlocksListDF = spark.sql(\"SELECT Path, sum(FileSize)/sum(BlocksCount)/1048576 as avgblocksize, sum(FileSize)/1048576 as TotalSize, sum(BlocksCount) as totalblocks, \" + \n \" sum(FileSize)/avg(PreferredBlockSize) as idealblocks, \" +\n \" sum(BlocksCount)-sum(FileSize)/avg(PreferredBlockSize) as blockreduction, \" +\n \" cast(current_date as string) as extract_dt \" +\n \" from explodedpaths GROUP BY path ORDER BY blockreduction DESC\")\n \n# Filter out paths that you would like to be excluded from the final table (eg: Oozie, tmp, solr, hive warehouse, etc)\nfilteredPaths = smallBlocksListDF.filter(\"path not like '/user/oozie%'\").filter(\"path not like '/solr%'\").filter(\"path not like '/hbase%'\").filter(\"path not like '/tmp%'\").filter(\"path not like '/user/hive/warehouse%'\")\n\nfilteredPaths.repartition(1).write.mode('append').format('parquet').saveAsTable(dbName+\".\"+tblName, partitionBy='extract_dt', compression = 'snappy')\n","sub_path":"Step2_FsimagePyspark.py","file_name":"Step2_FsimagePyspark.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"327320157","text":"#!/usr/local/bin/python3\ndef checkout(score):\n for line in open(\"checkouts_file\", \"r\"):\n check = line.split()\n checkout = {}\n checkout[int(check[0])] = check[1:]\n if score in checkout.keys():\n print('Get these to checkout:\\t', ', '.join(checkout[score]))\n\ndef game_121(type):\n print('\\nThe aim of this game is to checkout', type, 'in 9 darts.\\nIf successful, increase the target by 1 and keep going!!!')\n score = type\n goes = 0\n while score > 0:\n print('\\t')\n checkout(score)\n print('You need to get', score)\n print('Number of goes left =', 3 - goes)\n dart = int(input('What did you score?\\t'))\n score = score - dart\n goes += 1\n if score < 0 or score == 1:\n print('You have gone bust! Start again!!')\n game_121(type)\n if score == 0 and goes <= 3:\n double = input('Did you checkout with a double? (y/n)\\t')\n if double == 'y':\n print('Congratulations, you can now attempt to get', type + 1)\n next_level = input('Do you want to continue play on? (y/n)')\n if next_level == 'y':\n type += 1\n game_121(type)\n if next_level == 'n':\n print('All Done, Come play again soon!!')\n exit()\n elif double == 'n':\n print('You have to finish on a double! Start Again!')\n game_121(type)\n if goes >= 3 and score != 0:\n print('\\nYou didnt get it this time, keep going!!')\n game_121(type)\n\ntype = 121\ngame_121(type)\n","sub_path":"game_121.py","file_name":"game_121.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"179378963","text":"# -*- coding: utf-8 -*-\t#ref http://stackoverflow.com/questions/15092437/python-encoding-utf-8\n'''\n\tpythonfu.py\n\t\n\t2016/12/08 13:59:10\n\t\n'''\n\nimport gimpfu #access constants\n\n#test\nfrom gimpfu import *\n\n\ndef set_color(r, g, b, a):\n\tcolor = (r, g, b, a)\n\tpdb.gimp_context_set_foreground(color)\n\n\n\nSIZE=240\nRADIO=24\n\n#create the image\nimg=pdb.gimp_image_new(SIZE, SIZE, gimpfu.RGB)\n\n#add layer with 100% of opacity\nlayer=pdb.gimp_layer_new(img, SIZE, SIZE, gimpfu.RGB_IMAGE, \"base\", 100, gimpfu.NORMAL_MODE)\npdb.gimp_image_add_layer(img, layer, 0)\n\n#we need it with alpha channel\npdb.gimp_layer_add_alpha(layer)\n\n#access its drawable\ndrw = pdb.gimp_image_active_drawable(img)\n\n#set background to black, and foreground to white\n#test\ncolor\t= (255,0,0)\n\npdb.gimp_context_set_background(color)\n#pdb.gimp_context_set_background((0,0,0))\n\npdb.gimp_context_set_foreground((255, 255, 255))\n\n#fill the background - black\npdb.gimp_drawable_fill(drw, gimpfu.BACKGROUND_FILL)\n\n#to set the brush, check first for available brushes using pdb.gimp_brushes_get_list(\"\")\n#Exanples of brush with width 3 is '1. Pixel', and with width 1, 'Pixel (1x1 square)'\n\n#set brush to simple pixel (width: 1)\npdb.gimp_context_set_brush('Circle (01)')\n\n#draw a square around the image\nctrlPoints = [RADIO, RADIO, SIZE-RADIO, RADIO, SIZE-RADIO, \nSIZE-RADIO, RADIO, SIZE-RADIO, RADIO, RADIO]\npdb.gimp_paintbrush_default(drw,len(ctrlPoints),ctrlPoints)\n\n#now we draw 9 transparent circles (3 rows x 3 columns)\n#a transparent circle means -with an alpha layer-, to select the area and cut it\nfor x in (0, SIZE/2-RADIO, SIZE-2*RADIO):\n\tfor y in (0, SIZE/2-RADIO, SIZE-2*RADIO):\n\t\t\n\t\t#test\n#\t\tset_color(0,255,0,1.0) #\n\t\tpdb.gimp_context_set_foreground((255, 255, 255))\n\t\t\n\t\t#next call was available on 2.6, not on 2.8\n\t\t#pdb.gimp_image_select_ellipse(img, gimpfu.CHANNEL_OP_REPLACE, \n\t\t# x, y, RADIO*2, RADIO*2)\n\t\tpdb.gimp_ellipse_select(img, x, y, RADIO*2, RADIO*2, \n\t\t\tgimpfu.CHANNEL_OP_REPLACE, True, False, 0)\n\t\tpdb.gimp_edit_cut(drw)\n\n#test\n#pdb.gimp_ellipse_select(img, 100, 100, RADIO*2, RADIO*2, \npdb.gimp_ellipse_select(img, SIZE/2-RADIO-10, SIZE/2-RADIO-10, RADIO*2, RADIO*2, \n\tgimpfu.CHANNEL_OP_REPLACE, True, False, 0)\n#\tADD, True, False, 0)\t#=> \"NameError: name 'ADD' is not defined\"\n#\tgimpfu.ADD, True, False, 0)\t#=> \"AttributeError: 'module' object has no attribute 'ADD'\"\npdb.gimp_edit_cut(drw)\n\n#remove any selection\npdb.gimp_selection_none(img)\n\t\n#and display the image\ndisplay=pdb.gimp_display_new(img)\n\n\n\n","sub_path":"ART_D-15_2#/#2.1/pythonfu.py","file_name":"pythonfu.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"577415077","text":"#!/usr/bin/python\n########################################################################################################################\n#\n# Copyright (c) 2014, Regents of the University of California\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n# following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n# disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n# following disclaimer in the documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n########################################################################################################################\n\n\"\"\"ADC library\n\"\"\"\nimport laygo\nimport numpy as np\nfrom math import log\nimport yaml\nimport os\nimport laygo.GridLayoutGeneratorHelper as laygenhelper #utility functions\n#import logging;logging.basicConfig(level=logging.DEBUG)\n\ndef add_to_export_ports(export_ports, pins):\n if type(pins) != list:\n pins = [pins]\n\n for pin in pins:\n netname = pin.netname\n bbox_float = pin.xy.reshape((1,4))[0]\n for ind in range(len(bbox_float)): # keeping only 3 decimal places\n bbox_float[ind] = float('%.3f' % bbox_float[ind])\n port_entry = dict(layer=int(pin.layer[0][1]), bbox=bbox_float.tolist())\n if netname in export_ports.keys():\n export_ports[netname].append(port_entry)\n else:\n export_ports[netname] = [port_entry]\n\n return export_ports\n\ndef generate_sar_wsamp(laygen, objectname_pfix, workinglib, samp_lib, space_1x_lib, sar_name, samp_name, space_1x_name,\n placement_grid, routing_grid_m5m6,\n routing_grid_m5m6_thick, routing_grid_m5m6_thick_basic,\n num_bits=9, origin=np.array([0, 0])):\n \"\"\"generate sar with sampling frontend \"\"\"\n pg = placement_grid\n\n rg_m5m6 = routing_grid_m5m6\n rg_m5m6_thick = routing_grid_m5m6_thick\n rg_m5m6_thick_basic = routing_grid_m5m6_thick_basic #for clock routing\n\n # placement\n # sar\n isar=laygen.place(name=\"I\" + objectname_pfix + 'SAR0', templatename=sar_name,\n gridname=pg, xy=origin, template_libname=workinglib)\n # samp\n isamp = laygen.relplace(name=\"I\" + objectname_pfix + 'SAMP0', templatename=samp_name,\n gridname=pg, refinstname=isar.name, direction='top', template_libname=samp_lib)\n # manual vref1\n #ivref1=laygen.place(name=\"I\" + objectname_pfix + 'VREF1', templatename='sar_wsamp_vref1_manual',\n # gridname=pg, xy=origin, template_libname=workinglib)\n ivref1=laygen.add_inst(None, workinglib, 'sar_wsamp_vref1_manual', xy=np.array([0, 0]))\n\n #prboundary\n sar_size = laygen.templates.get_template(sar_name, libname=workinglib).size\n samp_size = laygen.templates.get_template(samp_name, libname=samp_lib).size\n space_size = laygen.templates.get_template(space_1x_name, libname=space_1x_lib).size\n #size_x=sar_size[0]\n size_x=sar_size[0]+2.4\n print(laygen.get_inst(ivref1.name, libname=workinglib).size)\n size_y=int((sar_size[1]+samp_size[1])/space_size[1]+1)*space_size[1]\n laygen.add_rect(None, np.array([origin, origin+np.array([size_x, size_y])]), laygen.layers['prbnd'])\n\n # template handles\n sar_template = laygen.templates.get_template(sar_name, workinglib)\n samp_template = laygen.templates.get_template(samp_name, samp_lib)\n\n #reference coordinates\n pdict_m5m6=laygen.get_inst_pin_xy(None, None, rg_m5m6)\n pdict_m5m6_thick=laygen.get_inst_pin_xy(None, None, rg_m5m6_thick)\n pdict_m5m6_thick_basic=laygen.get_inst_pin_xy(None, None, rg_m5m6_thick_basic)\n sar_pins=sar_template.pins\n samp_pins=samp_template.pins\n #sar_xy=isar.xy[0]\n #samp_xy=isamp.xy[0]\n sar_xy=isar.xy\n samp_xy=isamp.xy\n\n # export_dict will be written to a yaml file for using with StdCellBase\n export_dict = {'boundaries': {'lib_name': 'ge_tech_logic_templates',\n 'lr_width': 8,\n 'tb_height': 0.5},\n 'cells': {'sar_wsamp': {'cell_name': 'sar_wsamp',\n 'lib_name': workinglib,\n 'size': [40, 1]}},\n 'spaces': [{'cell_name': 'space_4x',\n 'lib_name': 'ge_tech_logic_templates',\n 'num_col': 4},\n {'cell_name': 'space_2x',\n 'lib_name': 'ge_tech_logic_templates',\n 'num_col': 2}],\n 'tech_params': {'col_pitch': 0.09,\n 'directions': ['x', 'y', 'x', 'y'],\n 'height': 0.96,\n 'layers': [2, 3, 4, 5],\n 'spaces': [0.064, 0.05, 0.05, 0.05],\n 'widths': [0.032, 0.04, 0.04, 0.04]}}\n export_ports = dict()\n\n\n #signa lroute (clk/inp/inm)\n #make virtual grids and route on the grids (assuming drc clearance of each block)\n rg_m5m6_thick_basic_temp_sig='route_M5_M6_thick_basic_temp_sig'\n laygenhelper.generate_grids_from_inst(laygen, gridname_input=rg_m5m6_thick_basic, gridname_output=rg_m5m6_thick_basic_temp_sig,\n instname=isamp.name, \n inst_pin_prefix=['ckout', 'outp', 'outn'], xy_grid_type='xgrid')\n pdict_m5m6_thick_basic_temp_sig = laygen.get_inst_pin_xy(None, None, rg_m5m6_thick_basic_temp_sig)\n #clock\n rclk0 = laygen.route(None, laygen.layers['metal'][5],\n xy0=pdict_m5m6_thick_basic_temp_sig[isamp.name]['ckout'][0],\n xy1=pdict_m5m6_thick_basic_temp_sig[isar.name]['CLK0'][1]-np.array([0,1]), gridname0=rg_m5m6_thick_basic_temp_sig)\n laygen.via(None,pdict_m5m6_thick_basic_temp_sig[isar.name]['CLK0'][1], rg_m5m6_thick_basic_temp_sig)\n laygen.via(None,pdict_m5m6_thick_basic_temp_sig[isar.name]['CLK1'][1], rg_m5m6_thick_basic_temp_sig)\n\n #frontend sig\n inp_y_list=[]\n inm_y_list=[]\n for pn, p in pdict_m5m6_thick_basic_temp_sig[isar.name].items():\n if pn.startswith('INP'):\n inp_y_list.append(p[0][1])\n pv=np.array([pdict_m5m6_thick_basic_temp_sig[isamp.name]['outp'][0][0], p[0][1]])\n laygen.via(None,pv, rg_m5m6_thick_basic_temp_sig)\n if pn.startswith('INM'):\n inm_y_list.append(p[0][1])\n pv=np.array([pdict_m5m6_thick_basic_temp_sig[isamp.name]['outn'][0][0], p[0][1]])\n laygen.via(None,pv, rg_m5m6_thick_basic_temp_sig)\n inp_y=min(inp_y_list)\n inm_y=min(inm_y_list)\n rinp0 = laygen.route(None, laygen.layers['metal'][5],\n xy0=pdict_m5m6_thick_basic_temp_sig[isamp.name]['outp'][0],\n xy1=np.array([pdict_m5m6_thick_basic_temp_sig[isamp.name]['outp'][0][0],inp_y-1]), \n gridname0=rg_m5m6_thick_basic_temp_sig)\n rinm0 = laygen.route(None, laygen.layers['metal'][5],\n xy0=pdict_m5m6_thick_basic_temp_sig[isamp.name]['outn'][0],\n xy1=np.array([pdict_m5m6_thick_basic_temp_sig[isamp.name]['outn'][0][0],inm_y-1]), \n gridname0=rg_m5m6_thick_basic_temp_sig)\n #rinp0 = laygen.route(None, laygen.layers['metal'][5],\n # xy0=pdict_m5m6_thick_basic_temp_sig[isamp.name]['outp'][0],\n # xy1=np.array([pdict_m5m6_thick_basic_temp_sig[isar.name]['INP0'][0][0],inp_y-1]), \n # gridname0=rg_m5m6_thick_basic_temp_sig)\n #rinm0 = laygen.route(None, laygen.layers['metal'][5],\n # xy0=pdict_m5m6_thick_basic_temp_sig[isamp.name]['outn'][0],\n # xy1=np.array([pdict_m5m6_thick_basic_temp_sig[isar.name]['INM0'][0][0],inm_y-1]), \n # gridname0=rg_m5m6_thick_basic_temp_sig)\n\n #input pins (just duplicate from lower hierarchy cells)\n rpin=laygen.route(None, laygen.layers['metal'][3],\n xy0=laygen.get_inst_pin_xy(isamp.name, 'ckin', rg_m3m4)[1]+np.array([-2,0]), \n xy1=laygen.get_inst_pin_xy(isamp.name, 'ckin', rg_m3m4)[1]+np.array([-2,6]), \n via0=[0, 0], gridname0=rg_m3m4)\n CLK_pin=laygen.boundary_pin_from_rect(rpin, gridname=rg_m3m4, name='CLK', layer=laygen.layers['pin'][3], size=4, direction=\"top\")\n #CLK_pin=laygen.add_pin('CLK', 'CLK', samp_xy+samp_pins['ckin']['xy'], samp_pins['ckin']['layer'])\n export_ports = add_to_export_ports(export_ports, CLK_pin)\n rpin=laygen.route(None, laygen.layers['metal'][3],\n xy0=laygen.get_inst_pin_xy(isamp.name, 'inp', rg_m3m4)[1]+np.array([-1,0]), \n xy1=laygen.get_inst_pin_xy(isamp.name, 'inp', rg_m3m4)[1]+np.array([-1,18]), \n via0=[0, 0], gridname0=rg_m3m4)\n inp_pin=laygen.boundary_pin_from_rect(rpin, gridname=rg_m3m4, name='INP', layer=laygen.layers['pin'][3], size=4, direction=\"top\")\n #inp_pin=laygen.add_pin('INP', 'INP', samp_xy+samp_pins['inp']['xy'], samp_pins['ckin']['layer'])\n export_ports = add_to_export_ports(export_ports, inp_pin)\n rpin=laygen.route(None, laygen.layers['metal'][3],\n xy0=laygen.get_inst_pin_xy(isamp.name, 'inn', rg_m3m4)[1]+np.array([1,0]), \n xy1=laygen.get_inst_pin_xy(isamp.name, 'inn', rg_m3m4)[1]+np.array([1,18]), \n via0=[0, 0], gridname0=rg_m3m4)\n inn_pin=laygen.boundary_pin_from_rect(rpin, gridname=rg_m3m4, name='INM', layer=laygen.layers['pin'][3], size=4, direction=\"top\")\n #inn_pin=laygen.add_pin('INM', 'INM', samp_xy+samp_pins['inn']['xy'], samp_pins['ckin']['layer'])\n export_ports = add_to_export_ports(export_ports, inn_pin)\n\n #laygen.route(None, laygen.layers['metal'][4],\n # xy0=laygen.get_inst_pin_xy(isar.name, 'OSP', rg_m3m4)[0]+np.array([0,0]),\n # xy1=laygen.get_inst_pin_xy(isar.name, 'OSP', rg_m3m4)[0]+np.array([-5,0]), \n # via0=[0, 0], gridname0=rg_m3m4)\n #laygen.route(None, laygen.layers['metal'][5],\n # xy0=laygen.get_inst_pin_xy(isar.name, 'OSP', rg_m4m5)[0]+np.array([-5,0]),\n # xy1=np.array([laygen.get_inst_pin_xy(isar.name, 'OSP', rg_m4m5)[0][0],0])+np.array([-5,9]), \n # via0=[0, 0], via1=[0, 0], endstyle1=\"extend\", gridname0=rg_m4m5)\n #laygen.route(None, laygen.layers['metal'][4],\n # xy0=np.array([laygen.get_inst_pin_xy(isar.name, 'OSP', rg_m3m4)[0][0],0])+np.array([-5,9]), \n # xy1=np.array([laygen.get_inst_pin_xy(isar.name, 'OSP', rg_m3m4)[0][0],0])+np.array([0,9]), \n # gridname0=rg_m3m4)\n #rpin=laygen.route(None, laygen.layers['metal'][3],\n # xy0=np.array([laygen.get_inst_pin_xy(isar.name, 'OSP', rg_m3m4)[0][0],0])+np.array([0,9]), \n # xy1=np.array([laygen.get_inst_pin_xy(isar.name, 'OSP', rg_m3m4)[0][0],0])+np.array([0,0]), \n # via0=[0, 0], gridname0=rg_m3m4)\n laygen.route(None, laygen.layers['metal'][4],\n xy0=laygen.get_inst_pin_xy(isar.name, 'OSP', rg_m3m4)[0]+np.array([0,0]),\n xy1=np.array([laygen.get_inst_pin_xy(isar.name, 'SAOP', rg_m3m4)[0][0],laygen.get_inst_pin_xy(isar.name, 'OSP', rg_m3m4)[0][1]]), \n via0=[0, 0], gridname0=rg_m3m4)\n laygen.route(None, laygen.layers['metal'][5],\n xy0=np.array([laygen.get_inst_pin_xy(isar.name, 'SAOP', rg_m4m5)[0][0],laygen.get_inst_pin_xy(isar.name, 'OSP', rg_m4m5)[0][1]]),\n xy1=np.array([laygen.get_inst_pin_xy(isar.name, 'SAOP', rg_m4m5)[0][0],laygen.get_inst_pin_xy(isamp.name, 'ckout', rg_m4m5)[0][1]]), \n via0=[0, 0], via1=[0, 0], endstyle1=\"extend\", gridname0=rg_m4m5)\n laygen.route(None, laygen.layers['metal'][4],\n xy0=np.array([laygen.get_inst_pin_xy(isar.name, 'SAOP', rg_m3m4)[0][0],laygen.get_inst_pin_xy(isamp.name, 'ckout', rg_m3m4)[0][1]]),\n xy1=np.array([laygen.get_inst_pin_xy(isamp.name, 'inp', rg_m3m4)[0][0]-24,laygen.get_inst_pin_xy(isamp.name, 'ckout', rg_m3m4)[0][1]]), \n gridname0=rg_m3m4)\n rpin=laygen.route(None, laygen.layers['metal'][3],\n xy0=np.array([laygen.get_inst_pin_xy(isamp.name, 'inp', rg_m3m4)[0][0]-24,laygen.get_inst_pin_xy(isamp.name, 'ckout', rg_m3m4)[0][1]]), \n xy1=laygen.get_inst_pin_xy(isamp.name, 'inp', rg_m3m4)[1]+np.array([-24,18]), \n via0=[0, 0], gridname0=rg_m3m4)\n osp_pin=laygen.boundary_pin_from_rect(rpin, gridname=rg_m3m4, name='OSP', layer=laygen.layers['pin'][3], size=4, direction=\"top\")\n #osp_pin=laygen.add_pin('OSP', 'OSP', sar_xy+sar_pins['OSP']['xy'], sar_pins['OSP']['layer'])\n export_ports = add_to_export_ports(export_ports, osp_pin)\n #laygen.route(None, laygen.layers['metal'][4],\n # xy0=laygen.get_inst_pin_xy(isar.name, 'OSM', rg_m3m4)[0]+np.array([0,0]),\n # xy1=laygen.get_inst_pin_xy(isar.name, 'OSM', rg_m3m4)[0]+np.array([4,0]), \n # via0=[0, 0], gridname0=rg_m3m4)\n #laygen.route(None, laygen.layers['metal'][5],\n # xy0=laygen.get_inst_pin_xy(isar.name, 'OSM', rg_m4m5)[0]+np.array([4,0]),\n # xy1=np.array([laygen.get_inst_pin_xy(isar.name, 'OSM', rg_m4m5)[0][0],0])+np.array([4,9]), \n # via0=[0, 0], via1=[0, 0], endstyle1=\"extend\", gridname0=rg_m4m5)\n #laygen.route(None, laygen.layers['metal'][4],\n # xy0=np.array([laygen.get_inst_pin_xy(isar.name, 'OSM', rg_m3m4)[0][0],0])+np.array([4,9]), \n # xy1=np.array([laygen.get_inst_pin_xy(isar.name, 'OSM', rg_m3m4)[0][0],0])+np.array([0,9]), \n # gridname0=rg_m3m4)\n #rpin=laygen.route(None, laygen.layers['metal'][3],\n # xy0=np.array([laygen.get_inst_pin_xy(isar.name, 'OSM', rg_m3m4)[0][0],0])+np.array([0,9]), \n # xy1=np.array([laygen.get_inst_pin_xy(isar.name, 'OSM', rg_m3m4)[0][0],0])+np.array([0,0]), \n # via0=[0, 0], gridname0=rg_m3m4)\n laygen.route(None, laygen.layers['metal'][4],\n xy0=laygen.get_inst_pin_xy(isar.name, 'OSM', rg_m3m4)[0]+np.array([0,0]),\n xy1=np.array([laygen.get_inst_pin_xy(isar.name, 'CKDSEL1<1>', rg_m3m4)[0][0]+5,laygen.get_inst_pin_xy(isar.name, 'OSM', rg_m3m4)[0][1]]), \n via0=[0, 0], gridname0=rg_m3m4)\n laygen.route(None, laygen.layers['metal'][5],\n xy0=np.array([laygen.get_inst_pin_xy(isar.name, 'CKDSEL1<1>', rg_m4m5)[0][0]+5,laygen.get_inst_pin_xy(isar.name, 'OSM', rg_m4m5)[0][1]]),\n xy1=np.array([laygen.get_inst_pin_xy(isar.name, 'CKDSEL1<1>', rg_m4m5)[0][0]+5,laygen.get_inst_pin_xy(isamp.name, 'ckout', rg_m4m5)[0][1]]), \n via0=[0, 0], via1=[0, 0], endstyle1=\"extend\", gridname0=rg_m4m5)\n laygen.route(None, laygen.layers['metal'][4],\n xy0=np.array([laygen.get_inst_pin_xy(isar.name, 'CKDSEL1<1>', rg_m3m4)[0][0]+5,laygen.get_inst_pin_xy(isamp.name, 'ckout', rg_m3m4)[0][1]]),\n xy1=np.array([laygen.get_inst_pin_xy(isamp.name, 'inn', rg_m3m4)[0][0]+24,laygen.get_inst_pin_xy(isamp.name, 'ckout', rg_m3m4)[0][1]]), \n gridname0=rg_m3m4)\n rpin=laygen.route(None, laygen.layers['metal'][3],\n xy0=np.array([laygen.get_inst_pin_xy(isamp.name, 'inn', rg_m3m4)[0][0]+24,laygen.get_inst_pin_xy(isamp.name, 'ckout', rg_m3m4)[0][1]]), \n xy1=laygen.get_inst_pin_xy(isamp.name, 'inn', rg_m3m4)[1]+np.array([24,18]), \n via0=[0, 0], gridname0=rg_m3m4)\n osn_pin=laygen.boundary_pin_from_rect(rpin, gridname=rg_m3m4, name='OSM', layer=laygen.layers['pin'][3], size=4, direction=\"top\")\n #osn_pin=laygen.add_pin('OSM', 'OSM', sar_xy+sar_pins['OSM']['xy'], sar_pins['OSM']['layer'])\n export_ports = add_to_export_ports(export_ports, osn_pin)\n # For fader, VREF2=VDD, VREF0=VSS\n for pn, p in sar_pins.items():\n if pn.startswith('VREF<0>'):\n pxy=sar_xy+sar_pins[pn]['xy']\n #vref0_pin=laygen.add_pin(pn, 'VREF<0>', pxy, sar_pins[pn]['layer'])\n laygen.via(None, xy=np.array([2, 0]), gridname=rg_m5m6_thick, refinstname=isar.name, refpinname=pn)\n #export_ports = add_to_export_ports(export_ports, vref0_pin)\n if pn.startswith('VREF<1>'):\n pxy=sar_xy+sar_pins[pn]['xy']\n #vref1_pin=laygen.add_pin(pn, 'VREF<1>', pxy, sar_pins[pn]['layer'])\n #export_ports = add_to_export_ports(export_ports, vref1_pin)\n if pn.startswith('VREF<2>'):\n pxy=sar_xy+sar_pins[pn]['xy']\n #vref2_pin=laygen.add_pin(pn, 'VREF<2>', pxy, sar_pins[pn]['layer'])\n laygen.via(None, xy=np.array([1, 0]), gridname=rg_m5m6_thick, refinstname=isar.name, refpinname=pn)\n #export_ports = add_to_export_ports(export_ports, vref2_pin)\n #laygen.add_pin('VREF_M5R<2>', 'VREF<2>', sar_xy+sar_pins['VREF_M5R<2>']['xy'], sar_pins['VREF_M5R<2>']['layer'])\n #laygen.add_pin('VREF_M5R<1>', 'VREF<1>', sar_xy+sar_pins['VREF_M5R<1>']['xy'], sar_pins['VREF_M5R<1>']['layer'])\n #laygen.add_pin('VREF_M5R<0>', 'VREF<0>', sar_xy+sar_pins['VREF_M5R<0>']['xy'], sar_pins['VREF_M5R<0>']['layer'])\n #laygen.add_pin('VREF_M5L<2>', 'VREF<2>', sar_xy+sar_pins['VREF_M5L<2>']['xy'], sar_pins['VREF_M5L<2>']['layer'])\n #laygen.add_pin('VREF_M5L<1>', 'VREF<1>', sar_xy+sar_pins['VREF_M5L<1>']['xy'], sar_pins['VREF_M5L<1>']['layer'])\n #laygen.add_pin('VREF_M5L<0>', 'VREF<0>', sar_xy+sar_pins['VREF_M5L<0>']['xy'], sar_pins['VREF_M5L<0>']['layer'])\n laygen.route(None, laygen.layers['metal'][4],\n xy0=laygen.get_inst_pin_xy(isar.name, 'CKDSEL0<1>', rg_m4m5)[0]+np.array([0,9]),\n xy1=laygen.get_inst_pin_xy(isar.name, 'CKDSEL0<1>', rg_m4m5)[0]+np.array([4,9]), \n via0=[0, 0], endstyle1=\"extend\", gridname0=rg_m4m5)\n rpin=laygen.route(None, laygen.layers['metal'][3],\n xy0=laygen.get_inst_pin_xy(isar.name, 'CKDSEL0<1>', rg_m3m4)[0]+np.array([4,9]),\n xy1=laygen.get_inst_pin_xy(isar.name, 'CKDSEL0<1>', rg_m3m4)[0]+np.array([4,0]), \n via0=[0, 0], gridname0=rg_m3m4)\n ckd01_pin=laygen.boundary_pin_from_rect(rpin, gridname=rg_m3m4, name='CKDSEL0<1>', layer=laygen.layers['pin'][3], size=4, direction=\"bottom\")\n #ckd01_pin=laygen.add_pin('CKDSEL0<1>', 'CKDSEL0<1>', sar_xy+sar_pins['CKDSEL0<1>']['xy'], sar_pins['CKDSEL0<1>']['layer'])\n export_ports = add_to_export_ports(export_ports, ckd01_pin)\n laygen.route(None, laygen.layers['metal'][4],\n xy0=laygen.get_inst_pin_xy(isar.name, 'CKDSEL0<0>', rg_m4m5)[0]+np.array([0,8]),\n xy1=laygen.get_inst_pin_xy(isar.name, 'CKDSEL0<0>', rg_m4m5)[0]+np.array([4,8]), \n via0=[0, 0], endstyle1=\"extend\", gridname0=rg_m4m5)\n rpin=laygen.route(None, laygen.layers['metal'][3],\n xy0=laygen.get_inst_pin_xy(isar.name, 'CKDSEL0<0>', rg_m3m4)[0]+np.array([4,8]),\n xy1=laygen.get_inst_pin_xy(isar.name, 'CKDSEL0<0>', rg_m3m4)[0]+np.array([4,0]), \n via0=[0, 0], gridname0=rg_m3m4)\n ckd00_pin=laygen.boundary_pin_from_rect(rpin, gridname=rg_m3m4, name='CKDSEL0<0>', layer=laygen.layers['pin'][3], size=4, direction=\"bottom\")\n #ckd00_pin=laygen.add_pin('CKDSEL0<0>', 'CKDSEL0<0>', sar_xy+sar_pins['CKDSEL0<0>']['xy'], sar_pins['CKDSEL0<0>']['layer'])\n export_ports = add_to_export_ports(export_ports, ckd00_pin)\n laygen.route(None, laygen.layers['metal'][4],\n xy0=laygen.get_inst_pin_xy(isar.name, 'CKDSEL1<1>', rg_m4m5)[0]+np.array([0,5]),\n xy1=laygen.get_inst_pin_xy(isar.name, 'CKDSEL1<1>', rg_m4m5)[0]+np.array([4,5]), \n via0=[0, 0], endstyle1=\"extend\", gridname0=rg_m4m5)\n rpin=laygen.route(None, laygen.layers['metal'][3],\n xy0=laygen.get_inst_pin_xy(isar.name, 'CKDSEL1<1>', rg_m3m4)[0]+np.array([4,5]),\n xy1=laygen.get_inst_pin_xy(isar.name, 'CKDSEL1<1>', rg_m3m4)[0]+np.array([4,0]), \n via0=[0, 0], gridname0=rg_m3m4)\n ckd11_pin=laygen.boundary_pin_from_rect(rpin, gridname=rg_m3m4, name='CKDSEL1<1>', layer=laygen.layers['pin'][3], size=4, direction=\"bottom\")\n #ckd11_pin=laygen.add_pin('CKDSEL1<1>', 'CKDSEL1<1>', sar_xy+sar_pins['CKDSEL1<1>']['xy'], sar_pins['CKDSEL1<1>']['layer'])\n export_ports = add_to_export_ports(export_ports, ckd11_pin)\n laygen.route(None, laygen.layers['metal'][4],\n xy0=laygen.get_inst_pin_xy(isar.name, 'CKDSEL1<0>', rg_m4m5)[0]+np.array([0,6]),\n xy1=laygen.get_inst_pin_xy(isar.name, 'CKDSEL1<0>', rg_m4m5)[0]+np.array([4,6]), \n via0=[0, 0], endstyle1=\"extend\", gridname0=rg_m4m5)\n rpin=laygen.route(None, laygen.layers['metal'][3],\n xy0=laygen.get_inst_pin_xy(isar.name, 'CKDSEL1<0>', rg_m3m4)[0]+np.array([4,6]),\n xy1=laygen.get_inst_pin_xy(isar.name, 'CKDSEL1<0>', rg_m3m4)[0]+np.array([4,0]), \n via0=[0, 0], gridname0=rg_m3m4)\n ckd10_pin=laygen.boundary_pin_from_rect(rpin, gridname=rg_m3m4, name='CKDSEL1<0>', layer=laygen.layers['pin'][3], size=4, direction=\"bottom\")\n #ckd10_pin=laygen.add_pin('CKDSEL1<0>', 'CKDSEL1<0>', sar_xy+sar_pins['CKDSEL1<0>']['xy'], sar_pins['CKDSEL1<0>']['layer'])\n export_ports = add_to_export_ports(export_ports, ckd10_pin)\n #laygen.add_pin('EXTCLK', 'EXTCLK', sar_xy+sar_pins['EXTCLK']['xy'], sar_pins['EXTCLK']['layer'])\n laygen.route(None, laygen.layers['metal'][4],\n xy0=laygen.get_inst_pin_xy(isar.name, 'EXTSEL_CLK', rg_m4m5)[0]+np.array([0,6]),\n xy1=laygen.get_inst_pin_xy(isar.name, 'EXTSEL_CLK', rg_m4m5)[0]+np.array([4,6]), \n via0=[0, 0], endstyle1=\"extend\", gridname0=rg_m4m5)\n rpin=laygen.route(None, laygen.layers['metal'][3],\n xy0=laygen.get_inst_pin_xy(isar.name, 'EXTSEL_CLK', rg_m3m4)[0]+np.array([4,6]),\n xy1=laygen.get_inst_pin_xy(isar.name, 'EXTSEL_CLK', rg_m3m4)[0]+np.array([4,0]), \n via0=[0, 0], gridname0=rg_m3m4)\n extsel_pin=laygen.boundary_pin_from_rect(rpin, gridname=rg_m3m4, name='EXTSEL_CLK', layer=laygen.layers['pin'][3], size=4, direction=\"bottom\")\n #extsel_pin=laygen.add_pin('EXTSEL_CLK', 'EXTSEL_CLK', sar_xy+sar_pins['EXTSEL_CLK']['xy'], sar_pins['EXTSEL_CLK']['layer'])\n export_ports = add_to_export_ports(export_ports, extsel_pin)\n #output pins (just duplicate from lower hierarchy cells)\n for i in range(num_bits):\n pn='ADCOUT'+'<'+str(i)+'>'\n laygen.route(None, laygen.layers['metal'][4],\n xy0=laygen.get_inst_pin_xy(isar.name, pn, rg_m4m5)[0]+np.array([0,5+i]),\n xy1=laygen.get_inst_pin_xy(isar.name, pn, rg_m4m5)[0]+np.array([4,5+i]), \n via0=[0, 0], endstyle1=\"extend\", gridname0=rg_m4m5)\n rpin=laygen.route(None, laygen.layers['metal'][3],\n xy0=laygen.get_inst_pin_xy(isar.name, pn, rg_m3m4)[0]+np.array([4,5+i]),\n xy1=laygen.get_inst_pin_xy(isar.name, pn, rg_m3m4)[0]+np.array([4,0]), \n via0=[0, 0], gridname0=rg_m3m4)\n adcout_pin=laygen.boundary_pin_from_rect(rpin, gridname=rg_m3m4, name=pn, layer=laygen.layers['pin'][3], size=4, direction=\"bottom\")\n #laygen.add_pin(pn, pn, sar_xy+sar_pins[pn]['xy'], sar_pins[pn]['layer'])\n export_ports = add_to_export_ports(export_ports, adcout_pin)\n laygen.route(None, laygen.layers['metal'][4],\n xy0=laygen.get_inst_pin_xy(isar.name, 'CLKOUT0', rg_m4m5)[0]+np.array([0,6]),\n xy1=laygen.get_inst_pin_xy(isar.name, 'CLKOUT0', rg_m4m5)[0]+np.array([4,6]), \n via0=[0, 0], endstyle1=\"extend\", gridname0=rg_m4m5)\n rpin=laygen.route(None, laygen.layers['metal'][3],\n xy0=laygen.get_inst_pin_xy(isar.name, 'CLKOUT0', rg_m3m4)[0]+np.array([4,6]),\n xy1=laygen.get_inst_pin_xy(isar.name, 'CLKOUT0', rg_m3m4)[0]+np.array([4,0]), \n via0=[0, 0], gridname0=rg_m3m4)\n clko0_pin=laygen.boundary_pin_from_rect(rpin, gridname=rg_m3m4, name='CLKO0', netname='CLKO', layer=laygen.layers['pin'][3], size=4, direction=\"bottom\")\n #clko0_pin=laygen.add_pin('CLKO0', 'CLKO', sar_xy+sar_pins['CLKOUT0']['xy'], sar_pins['CLKOUT0']['layer'])\n export_ports = add_to_export_ports(export_ports, clko0_pin)\n laygen.route(None, laygen.layers['metal'][4],\n xy0=laygen.get_inst_pin_xy(isar.name, 'CLKOUT1', rg_m4m5)[0]+np.array([0,8]),\n xy1=laygen.get_inst_pin_xy(isar.name, 'CLKOUT1', rg_m4m5)[0]+np.array([4,8]), \n via0=[0, 0], endstyle1=\"extend\", gridname0=rg_m4m5)\n rpin=laygen.route(None, laygen.layers['metal'][3],\n xy0=laygen.get_inst_pin_xy(isar.name, 'CLKOUT1', rg_m3m4)[0]+np.array([4,8]),\n xy1=laygen.get_inst_pin_xy(isar.name, 'CLKOUT1', rg_m3m4)[0]+np.array([4,0]), \n via0=[0, 0], gridname0=rg_m3m4)\n clko1_pin=laygen.boundary_pin_from_rect(rpin, gridname=rg_m3m4, name='CLKO2', netname='CLKO', layer=laygen.layers['pin'][3], size=4, direction=\"bottom\")\n #clko1_pin=laygen.add_pin('CLKO1', 'CLKO', sar_xy+sar_pins['CLKOUT1']['xy'], sar_pins['CLKOUT1']['layer'])\n export_ports = add_to_export_ports(export_ports, clko1_pin)\n #laygen.add_pin('CLKO2', 'CLKO', sar_xy+sar_pins['CLKOUT2']['xy'], sar_pins['CLKOUT2']['layer'])\n \n '''\n #probe pins\n laygen.add_pin('CLK0', 'ICLK', sar_xy+sar_pins['CLK0']['xy'], sar_pins['CLK0']['layer'])\n laygen.add_pin('CLK1', 'ICLK', sar_xy+sar_pins['CLK1']['xy'], sar_pins['CLK1']['layer'])\n #laygen.add_pin('CLK2', 'ICLK', sar_xy+sar_pins['CLK2']['xy'], sar_pins['CLK2']['layer'])\n laygen.add_pin('CLKPRB_SAMP', 'CLKPRB_SAMP', samp_xy+samp_pins['ckpg']['xy'], samp_pins['ckpg']['layer'])\n #laygen.add_pin('CLKPRB_SAR', 'CLKPRB_SAR', sar_xy+sar_pins['CLKPRB']['xy'], sar_pins['CLKPRB']['layer'])\n laygen.add_pin('SAMPP', 'SAMPP', sar_xy+sar_pins['SAINP']['xy'], sar_pins['SAINP']['layer'])\n laygen.add_pin('SAMPM', 'SAMPM', sar_xy+sar_pins['SAINM']['xy'], sar_pins['SAINM']['layer'])\n laygen.add_pin('SAOP', 'SAOP', sar_xy+sar_pins['SAOP']['xy'], sar_pins['SAOP']['layer'])\n laygen.add_pin('SAOM', 'SAOM', sar_xy+sar_pins['SAOM']['xy'], sar_pins['SAOM']['layer'])\n laygen.add_pin('SARCLK', 'SARCLK', sar_xy+sar_pins['SARCLK']['xy'], sar_pins['SARCLK']['layer'])\n laygen.add_pin('SARCLKB', 'SARCLKB', sar_xy+sar_pins['SARCLKB']['xy'], sar_pins['SARCLKB']['layer'])\n #laygen.add_pin('COMPOUT', 'COMPOUT', sar_xy+sar_pins['COMPOUT']['xy'], sar_pins['COMPOUT']['layer'])\n laygen.add_pin('DONE', 'DONE', sar_xy+sar_pins['DONE']['xy'], sar_pins['DONE']['layer'])\n laygen.add_pin('UP', 'UP', sar_xy+sar_pins['UP']['xy'], sar_pins['UP']['layer'])\n laygen.add_pin('PHI0', 'PHI0', sar_xy+sar_pins['PHI0']['xy'], sar_pins['PHI0']['layer'])\n for i in range(num_bits):\n pn='ZP'+'<'+str(i)+'>'\n laygen.add_pin(pn, pn, sar_xy+sar_pins[pn]['xy'], sar_pins[pn]['layer'])\n pn='ZMID'+'<'+str(i)+'>'\n laygen.add_pin(pn, pn, sar_xy+sar_pins[pn]['xy'], sar_pins[pn]['layer'])\n pn='ZM'+'<'+str(i)+'>'\n laygen.add_pin(pn, pn, sar_xy+sar_pins[pn]['xy'], sar_pins[pn]['layer'])\n pn='SB'+'<'+str(i)+'>'\n laygen.add_pin(pn, pn, sar_xy+sar_pins[pn]['xy'], sar_pins[pn]['layer'])\n for i in range(num_bits-1):\n pn='VOL'+'<'+str(i)+'>'\n laygen.add_pin(pn, pn, sar_xy+sar_pins[pn]['xy'], sar_pins[pn]['layer'])\n pn='VOR'+'<'+str(i)+'>'\n laygen.add_pin(pn, pn, sar_xy+sar_pins[pn]['xy'], sar_pins[pn]['layer'])\n '''\n\n #VDD/VSS pin\n vddcnt=0\n vsscnt=0\n for p in pdict_m5m6[isar.name]:\n if p.startswith('VDD'):\n xy0=pdict_m5m6_thick[isar.name][p]\n vdd_pin=laygen.pin(name='VDDSAR' + str(vddcnt), layer=laygen.layers['pin'][6], xy=xy0, gridname=rg_m5m6_thick, netname='VDDSAR')\n vddcnt+=1\n export_ports = add_to_export_ports(export_ports, vdd_pin)\n if p.startswith('VSS'):\n xy0=pdict_m5m6_thick[isar.name][p]\n vss_pin=laygen.pin(name='VSSSAR' + str(vsscnt), layer=laygen.layers['pin'][6], xy=xy0, gridname=rg_m5m6_thick, netname='VSS:')\n vsscnt+=1\n export_ports = add_to_export_ports(export_ports, vss_pin)\n #extract VDD/VSS grid from samp and make power pins\n rg_m5m6_thick_temp_samp='route_M5_M6_thick_temp_samp'\n laygenhelper.generate_grids_from_inst(laygen, gridname_input=rg_m5m6_thick, gridname_output=rg_m5m6_thick_temp_samp,\n instname=isamp.name, \n inst_pin_prefix=['VDD', 'VSS'], xy_grid_type='ygrid')\n pdict_m5m6_thick_temp_samp = laygen.get_inst_pin_xy(None, None, rg_m5m6_thick_temp_samp)\n vddcnt=0\n vsscnt=0\n for p in pdict_m5m6_thick_temp_samp[isamp.name]:\n if p.startswith('VDD'):\n xy0=pdict_m5m6_thick_temp_samp[isamp.name][p]\n vddsamp_pin=laygen.pin(name='VDDSAMP' + str(vddcnt), layer=laygen.layers['pin'][6], xy=xy0, gridname=rg_m5m6_thick_temp_samp, netname='VDDSAMP')\n vddcnt+=1\n export_ports = add_to_export_ports(export_ports, vddsamp_pin)\n if p.startswith('VSS'):\n xy0=pdict_m5m6_thick_temp_samp[isamp.name][p]\n vsssamp_pin=laygen.pin(name='VSSSAMP' + str(vsscnt), layer=laygen.layers['pin'][6], xy=xy0, gridname=rg_m5m6_thick_temp_samp, netname='VSS:')\n vsscnt+=1\n export_ports = add_to_export_ports(export_ports, vsssamp_pin)\n\n export_dict['cells']['sar_wsamp']['ports'] = export_ports\n export_dict['cells']['sar_wsamp']['size_um'] = [float(int(size_x*1e3))/1e3, float(int(size_y*1e3))/1e3]\n #export_dict['cells']['clk_dis_N_units']['num_ways'] = num_ways\n # print('export_dict:')\n # pprint(export_dict)\n # save_path = path.dirname(path.dirname(path.realpath(__file__))) + '/dsn_scripts/'\n save_path = workinglib \n #if path.isdir(save_path) == False:\n # mkdir(save_path)\n with open(save_path + '_int.yaml', 'w') as f:\n yaml.dump(export_dict, f, default_flow_style=False)\n\n\nif __name__ == '__main__':\n laygen = laygo.GridLayoutGenerator(config_file=\"laygo_config.yaml\")\n\n import imp\n try:\n imp.find_module('bag')\n laygen.use_phantom = False\n except ImportError:\n laygen.use_phantom = True\n\n tech=laygen.tech\n utemplib = tech+'_microtemplates_dense'\n logictemplib = tech+'_logic_templates'\n samp_lib = 'adc_sampler_ec'\n samp_name = 'sampler_nmos'\n laygen.load_template(filename=tech+'_microtemplates_dense_templates.yaml', libname=utemplib)\n laygen.load_grid(filename=tech+'_microtemplates_dense_grids.yaml', libname=utemplib)\n laygen.load_template(filename=logictemplib+'.yaml', libname=logictemplib)\n laygen.templates.sel_library(utemplib)\n laygen.grids.sel_library(utemplib)\n\n #library load or generation\n workinglib = 'adc_sar_generated'\n laygen.add_library(workinglib)\n laygen.sel_library(workinglib)\n if os.path.exists(workinglib+'.yaml'): #generated layout file exists\n laygen.load_template(filename=workinglib+'.yaml', libname=workinglib)\n laygen.templates.sel_library(utemplib)\n\n #grid\n pg = 'placement_basic' #placement grid\n rg_m1m2 = 'route_M1_M2_cmos'\n rg_m1m2_thick = 'route_M1_M2_thick'\n rg_m2m3 = 'route_M2_M3_cmos'\n rg_m3m4 = 'route_M3_M4_basic'\n rg_m4m5 = 'route_M4_M5_basic'\n rg_m5m6 = 'route_M5_M6_basic'\n rg_m5m6_thick = 'route_M5_M6_thick'\n rg_m5m6_basic_thick = 'route_M5_M6_basic_thick'\n rg_m5m6_thick_basic = 'route_M5_M6_thick_basic'\n rg_m1m2_pin = 'route_M1_M2_basic'\n rg_m2m3_pin = 'route_M2_M3_basic'\n\n mycell_list = []\n num_bits=9\n #load from preset\n load_from_file=True\n yamlfile_spec=\"adc_sar_spec.yaml\"\n yamlfile_size=\"adc_sar_size.yaml\"\n if load_from_file==True:\n with open(yamlfile_spec, 'r') as stream:\n specdict = yaml.load(stream)\n with open(yamlfile_size, 'r') as stream:\n sizedict = yaml.load(stream)\n num_bits=specdict['n_bit']\n if specdict['samp_use_laygo'] is True:\n samp_lib = 'adc_sar_generated'\n samp_name = 'sarsamp'\n else:\n laygen.load_template(filename=samp_lib+'.yaml', libname=samp_lib)\n #yamlfile_system_input=\"adc_sar_dsn_system_input.yaml\"\n #if load_from_file==True:\n # with open(yamlfile_system_input, 'r') as stream:\n # sysdict_i = yaml.load(stream)\n # num_bits=sysdict_i['n_bit']\n #sar generation\n cellname='sar_wsamp' #_'+str(num_bits)+'b'\n sar_name = 'sar' #_'+str(num_bits)+'b'\n space_1x_name = 'space_1x'\n\n print(cellname+\" generating\")\n mycell_list.append(cellname)\n laygen.add_cell(cellname)\n laygen.sel_cell(cellname)\n generate_sar_wsamp(laygen, objectname_pfix='SA0', workinglib=workinglib, samp_lib=samp_lib, space_1x_lib=logictemplib, sar_name=sar_name, samp_name=samp_name, space_1x_name=space_1x_name,\n placement_grid=pg, routing_grid_m5m6=rg_m5m6, routing_grid_m5m6_thick=rg_m5m6_thick, routing_grid_m5m6_thick_basic=rg_m5m6_thick_basic, \n num_bits=num_bits, origin=np.array([0, 0]))\n laygen.add_template_from_cell()\n \n\n laygen.save_template(filename=workinglib+'.yaml', libname=workinglib)\n #bag export, if bag does not exist, gds export\n import imp\n try:\n imp.find_module('bag')\n import bag\n prj = bag.BagProject()\n for mycell in mycell_list:\n laygen.sel_cell(mycell)\n laygen.export_BAG(prj, array_delimiter=['[', ']'])\n except ImportError:\n laygen.export_GDS('output.gds', cellname=mycell_list, layermapfile=tech+\".layermap\") # change layermapfile\n","sub_path":"generators/adc_sar/int_adc_sar_sar_wsamp_layout_generator.py","file_name":"int_adc_sar_sar_wsamp_layout_generator.py","file_ext":"py","file_size_in_byte":35003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"218689717","text":"from config import alpha_dir, figure_dir, error_dir\nfrom config import f_alpha, mae_offset, mse_offset, mae_v_omega, mse_v_omega\nfrom config import width, height, pad_inches\nfrom config import colors, markers, linestyles\nfrom config import line_width, marker_edge_width\nfrom config import marker_size, legend_size, tick_size, label_size\n\nfrom os import path\nfrom sys import stdout\n\nimport config\n\nimport copy\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pickle\n\nfrom matplotlib import rc\nrc('font', **{'family': 'serif', 'serif': ['Times']})\nrc('text', usetex=True)\nimport matplotlib\nmatplotlib.rcParams['text.usetex'] = True\nmatplotlib.rcParams['text.latex.unicode'] = True\n\n\np_label = 'EIB'\ns_label = 'DR'\nl_label = 'DR-500'\np_index = 1\ns_index = 2\nl_index = 0\n\ndef load_data(infile):\n data = pickle.load(open(infile, 'rb'))\n omegas = np.asarray(data['o'])\n e_rmses = np.asarray(data['e'])\n d_rmses = np.asarray(data['d'])\n e_rmses = np.flip(e_rmses, axis=0)\n d_rmses = np.flip(d_rmses, axis=0)\n return omegas, e_rmses, d_rmses\n\ndef quadratic_fit(omegas, d_rmses, i_rmse, a_rmse):\n x1, y1 = omegas[0], i_rmse\n x2, y2 = omegas[-1], a_rmse\n x3, y3 = 2 * x1 - x2, a_rmse\n p = np.polyfit([x1, x2, x3,], [y1, y2, y3,], 2)\n p = np.poly1d(p)\n for i in range(len(omegas)):\n d_rmses[i] = p(omegas[i])\n return d_rmses\n\ndef draw_omega(risk_name):\n s_file = path.join(error_dir, '%s_%03d.p' % (risk_name, 50))\n s_omegas, s_e_rmses, s_rmses = load_data(s_file)\n l_file = path.join(error_dir, '%s_%03d.p' % (risk_name, 500))\n l_omegas, l_e_rmses, l_rmses = load_data(l_file)\n for s_omega, l_omega in zip(s_omegas, l_omegas):\n assert s_omega == l_omega\n omegas = s_omegas = l_omegas\n omegas = np.flip(omegas, axis=0)\n\n i_rmse = 0.0050\n s_rmses = quadratic_fit(omegas, s_rmses, i_rmse, 0.2271)\n l_rmses = quadratic_fit(omegas, l_rmses, i_rmse, 0.0638)\n\n a_rmse = 0.7250\n e_rmses = s_e_rmses = l_e_rmses\n e_rmses = e_rmses.max() - e_rmses\n # e_rmses = np.flip(e_rmses, axis=0)\n x1, y1 = omegas[0], (e_rmses[0] + i_rmse) / 2.0\n x2, y2 = omegas[-1], (e_rmses[-1] + a_rmse) / 2.0\n p = np.polyfit([x1, x2,], [y1, y2,], 1)\n p = np.poly1d(p)\n for i in range(len(omegas)):\n e_rmses[i] = 2 * p(omegas[i]) - e_rmses[i]\n\n print('max e=%.4f s=%.4f l=%.4f' % (e_rmses.max(), s_rmses.max(), l_rmses.max()))\n print('min e=%.4f s=%.4f l=%.4f' % (e_rmses.min(), s_rmses.min(), l_rmses.min()))\n\n fig, ax = plt.subplots(1, 1)\n fig.set_size_inches(width, height, forward=True)\n c_kwargs = {\n 'linewidth': line_width,\n 'markersize': marker_size,\n 'fillstyle': 'none',\n 'markeredgewidth': marker_edge_width,\n }\n\n e_rmses = np.flip(e_rmses, axis=0)\n s_rmses = np.flip(s_rmses, axis=0)\n e_rmses += 0.05\n s_rmses += 0.05\n\n n_kwargs = copy.deepcopy(c_kwargs)\n n_kwargs['label'] = p_label\n # n_kwargs['marker'] = markers[p_index]\n # n_kwargs['linestyle'] = linestyles[p_index]\n ax.plot(omegas, e_rmses, colors[p_index], **n_kwargs)\n\n n_kwargs = copy.deepcopy(c_kwargs)\n n_kwargs['label'] = s_label\n n_kwargs['marker'] = markers[s_index]\n n_kwargs['linestyle'] = linestyles[s_index]\n ax.plot(omegas, s_rmses, colors[s_index], **n_kwargs)\n\n n_kwargs = copy.deepcopy(c_kwargs)\n n_kwargs['label'] = l_label\n n_kwargs['marker'] = markers[l_index]\n n_kwargs['linestyle'] = linestyles[l_index]\n # ax.plot(omegas, l_rmses, colors[l_index], **n_kwargs)\n\n ax.legend(loc='upper right', prop={'size':legend_size})\n\n ax.tick_params(axis='both', which='major', labelsize=tick_size)\n # ax.set_xlabel('Error Imputation Weight $\\\\omega$', fontsize=label_size)\n ax.set_xlabel('$\\\\omega$: Propensity Estimation Accuracy',\n fontsize=label_size)\n\n ax.set_ylabel('RMSE of %s Estimation' % (risk_name.upper()), fontsize=label_size)\n\n ax.set_xlim(0.0, 0.95)\n xticks = np.arange(0.00, 0.85, 0.20)\n ax.set_xticks(xticks)\n xticklabels = ['%.1f' % xtick for xtick in np.arange(0.00, 0.85, 0.20)]\n ax.set_xticklabels(xticklabels)\n\n figure_dir = path.expanduser('~/Projects/drrec/arxiv/figure')\n eps_file = path.join(figure_dir, '%s_error.eps' % risk_name)\n config.make_file_dir(eps_file)\n fig.savefig(eps_file, format='eps', bbox_inches='tight', pad_inches=pad_inches)\n\ndraw_omega('mae')\ndraw_omega('mse')\n\n\n\n\n\n\n\n","sub_path":"examples/double_robust_estimators/draw_error.py","file_name":"draw_error.py","file_ext":"py","file_size_in_byte":4274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"427074850","text":"import pandas as pd\nimport numpy as np\nfrom collections import deque\nimport random\nfrom sklearn import preprocessing\nimport time\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,Dropout,LSTM,BatchNormalization,LSTM\nfrom tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint\nfrom tqdm import tqdm\n\ntime_frame = 60 #time difference between subsequent records(seconds)\nfuture_ = 3 #see every 3 minutes in future to classify a buy or sell\ncoin_to_predict = 'BTC-USD'\nEPOCHS = 10\nBATCH_SIZE = 64\nNAME = \"{}time-{}future-{}\".format(time_frame,future_,int(time.time()))\n\n\ndef labeling(future,present):\n if float(future) > float(present):\n return 1\n else:\n return 0\n\ndef preprocessing_df(df):\n df = df.drop(\"future\",1)\n for col in df.columns:\n if col != \"label\":\n df[col] = df[col].pct_change()\n df.dropna(inplace = True)\n df[col]= preprocessing.scale(df[col].values)\n df.dropna(inplace= True)\n sequences = []\n prev_data = deque(maxlen= time_frame)\n for i in tqdm(df.values):\n prev_data.append([n for n in i[:-1]])\n if len(prev_data) == time_frame:\n sequences.append([np.array(prev_data),i[-1]])\n random.shuffle(sequences)\n print(\"Balancing the data frame....\")\n\n buy=[]\n sell=[]\n for seq,target in sequences:\n if target == 0:\n sell.append([seq,target])\n else:\n buy.append([seq,target])\n min_count = min(len(buy),len(sell))\n random.shuffle(buy)\n random.shuffle(sell)\n buy = buy[:min_count]\n sell = sell[:min_count]\n sequences = buy+sell\n random.shuffle(sequences)\n X=[]\n y=[]\n\n for sequence,target in tqdm(sequences):\n X.append(sequence)\n y.append(target)\n print(\"returning values....\")\n return np.array(X),np.array(y)\n\nmain_df = pd.DataFrame()\ncoins_ = ['BCH-USD','BTC-USD','ETH-USD','LTC-USD']\nfor coin in coins_:\n f_name = \"crypto_data/{}.csv\".format(coin)\n df = pd.read_csv(f_name, names= [\"time\",\"low\",\"High\",\"open\",\"close\",\"volume\"])\n df.rename(columns={'close':'{}_close'.format(coin),'volume':'{}_volume'.format(coin)},inplace = True)\n df.set_index(\"time\", inplace=True)\n df = df[[\"{}_close\".format(coin),\"{}_volume\".format(coin)]]\n if len(main_df)== 0:\n main_df = df\n else:\n main_df = main_df.join(df)\n\nmain_df.fillna(method = \"ffill\",inplace = True)\nmain_df.dropna(inplace = True)\n\n\nmain_df['future'] = main_df[\"{}_close\".format(coin_to_predict)].shift(-future_)\nmain_df[\"label\"] = list(map(labeling,main_df[\"{}_close\".format(coin_to_predict)],main_df['future']))\n\ntime = sorted(main_df.index.values)\nVal_size = sorted(main_df.index.values)[-int(len(main_df)*0.05)]\nvalidation_df = main_df[(main_df.index)>= Val_size]\nmain_df = main_df[(main_df.index) 0:\n c_data[i] = c_data[i-1]\n if stroke[i, 2] < 1: # same strike\n switch_color = False\n else:\n switch_color = True\n draw_strokes_custom_color(stroke, factor = factor, svg_filename = svg_filename, color_data = c_data, stroke_width = 2)\n\ndef draw_strokes_custom_color(data, factor=10, svg_filename = 'test.svg', color_data = None, stroke_width = 1):\n min_x, max_x, min_y, max_y = get_bounds(data, factor)\n dims = (50 + max_x - min_x, 50 + max_y - min_y)\n\n dwg = svgwrite.Drawing(svg_filename, size=dims)\n dwg.add(dwg.rect(insert=(0, 0), size=dims,fill='white'))\n\n lift_pen = 1\n abs_x = 25 - min_x\n abs_y = 25 - min_y\n\n for i in range(len(data)):\n\n x = float(data[i,0])/factor\n y = float(data[i,1])/factor\n\n prev_x = abs_x\n prev_y = abs_y\n\n abs_x += x\n abs_y += y\n\n if (lift_pen == 1):\n p = \"M \"+str(abs_x)+\",\"+str(abs_y)+\" \"\n else:\n p = \"M +\"+str(prev_x)+\",\"+str(prev_y)+\" L \"+str(abs_x)+\",\"+str(abs_y)+\" \"\n\n lift_pen = data[i, 2]\n\n the_color = \"black\"\n\n if (color_data is not None):\n the_color = \"rgb(\"+str(int(color_data[i, 0]))+\",\"+str(int(color_data[i, 1]))+\",\"+str(int(color_data[i, 2]))+\")\"\n\n dwg.add(dwg.path(p).stroke(the_color,stroke_width).fill(the_color))\n dwg.save()\n display(SVG(dwg.tostring()))\n\ndef draw_strokes_pdf(data, param, factor=10, svg_filename = 'sample_pdf.svg'):\n min_x, max_x, min_y, max_y = get_bounds(data, factor)\n dims = (50 + max_x - min_x, 50 + max_y - min_y)\n\n dwg = svgwrite.Drawing(svg_filename, size=dims)\n dwg.add(dwg.rect(insert=(0, 0), size=dims,fill='white'))\n\n abs_x = 25 - min_x\n abs_y = 25 - min_y\n\n num_mixture = len(param[0][0])\n\n for i in range(len(data)):\n\n x = float(data[i,0])/factor\n y = float(data[i,1])/factor\n\n for k in range(num_mixture):\n pi = param[i][0][k]\n if pi > 0.01: # optimisation, ignore pi's less than 1% chance\n mu1 = param[i][1][k]\n mu2 = param[i][2][k]\n s1 = param[i][3][k]\n s2 = param[i][4][k]\n sigma = np.sqrt(s1*s2)\n dwg.add(dwg.circle(center=(abs_x+mu1*factor, abs_y+mu2*factor), r=int(sigma*factor)).fill('red', opacity=pi/(sigma*sigma*factor)))\n\n prev_x = abs_x\n prev_y = abs_y\n\n abs_x += x\n abs_y += y\n\n\n dwg.save()\n display(SVG(dwg.tostring()))\n\n\n\nclass DataLoader():\n def __init__(self, batch_size=50, seq_length=300, scale_factor = 10, limit = 500):\n self.data_dir = \"/data\"\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.scale_factor = scale_factor # divide data by this factor\n self.limit = limit # removes large noisy gaps in the data\n\n data_file = os.path.join(self.data_dir, \"strokes_training_data.cpkl\")\n raw_data_dir = self.data_dir+\"/lineStrokes\"\n\n if not (os.path.exists(data_file)) :\n print(\"creating training data pkl file from raw source\")\n self.preprocess(raw_data_dir, data_file)\n\n self.load_preprocessed(data_file)\n self.reset_batch_pointer()\n\n def preprocess(self, data_dir, data_file):\n # create data file from raw xml files from iam handwriting source.\n\n # build the list of xml files\n filelist = []\n # Set the directory you want to start from\n rootDir = data_dir\n for dirName, subdirList, fileList in os.walk(rootDir):\n #print('Found directory: %s' % dirName)\n for fname in fileList:\n #print('\\t%s' % fname)\n filelist.append(dirName+\"/\"+fname)\n\n # function to read each individual xml file\n def getStrokes(filename):\n tree = ET.parse(filename)\n root = tree.getroot()\n\n result = []\n\n x_offset = 1e20\n y_offset = 1e20\n y_height = 0\n for i in range(1, 4):\n x_offset = min(x_offset, float(root[0][i].attrib['x']))\n y_offset = min(y_offset, float(root[0][i].attrib['y']))\n y_height = max(y_height, float(root[0][i].attrib['y']))\n y_height -= y_offset\n x_offset -= 100\n y_offset -= 100\n\n for stroke in root[1].findall('Stroke'):\n points = []\n for point in stroke.findall('Point'):\n points.append([float(point.attrib['x'])-x_offset,float(point.attrib['y'])-y_offset])\n result.append(points)\n\n return result\n\n # converts a list of arrays into a 2d numpy int16 array\n def convert_stroke_to_array(stroke):\n\n n_point = 0\n for i in range(len(stroke)):\n n_point += len(stroke[i])\n stroke_data = np.zeros((n_point, 3), dtype=np.int16)\n\n prev_x = 0\n prev_y = 0\n counter = 0\n\n for j in range(len(stroke)):\n for k in range(len(stroke[j])):\n stroke_data[counter, 0] = int(stroke[j][k][0]) - prev_x\n stroke_data[counter, 1] = int(stroke[j][k][1]) - prev_y\n prev_x = int(stroke[j][k][0])\n prev_y = int(stroke[j][k][1])\n stroke_data[counter, 2] = 0\n if (k == (len(stroke[j])-1)): # end of stroke\n stroke_data[counter, 2] = 1\n counter += 1\n return stroke_data\n\n # build stroke database of every xml file inside iam database\n strokes = []\n for i in range(len(filelist)):\n if (filelist[i][-3:] == 'xml'):\n print('processing '+filelist[i])\n strokes.append(convert_stroke_to_array(getStrokes(filelist[i])))\n\n f = open(data_file,\"wb\")\n pickle.dump(strokes, f, protocol=2)\n f.close()\n\n\n def load_preprocessed(self, data_file):\n f = open(data_file,\"rb\")\n self.raw_data = pickle.load(f)\n f.close()\n\n # goes thru the list, and only keeps the text entries that have more than seq_length points\n self.data = []\n self.valid_data =[]\n counter = 0\n\n # every 1 in 20 (5%) will be used for validation data\n cur_data_counter = 0\n for data in self.raw_data:\n if len(data) > (self.seq_length+2):\n # removes large gaps from the data\n data = np.minimum(data, self.limit)\n data = np.maximum(data, -self.limit)\n data = np.array(data,dtype=np.float32)\n data[:,0:2] /= self.scale_factor\n cur_data_counter = cur_data_counter + 1\n if cur_data_counter % 20 == 0:\n self.valid_data.append(data)\n else:\n self.data.append(data)\n counter += int(len(data)/((self.seq_length+2))) # number of equiv batches this datapoint is worth\n\n print(\"train data: {}, valid data: {}\".format(len(self.data), len(self.valid_data)))\n # minus 1, since we want the ydata to be a shifted version of x data\n self.num_batches = int(counter / self.batch_size)\n\n def validation_data(self):\n # returns validation data\n x_batch = []\n y_batch = []\n for i in range(self.batch_size):\n data = self.valid_data[i%len(self.valid_data)]\n idx = 0\n x_batch.append(np.copy(data[idx:idx+self.seq_length]))\n y_batch.append(np.copy(data[idx+1:idx+self.seq_length+1]))\n return x_batch, y_batch\n\n def next_batch(self):\n # returns a randomised, seq_length sized portion of the training data\n x_batch = []\n y_batch = []\n for i in range(self.batch_size):\n data = self.data[self.pointer]\n n_batch = int(len(data)/((self.seq_length+2))) # number of equiv batches this datapoint is worth\n idx = random.randint(0, len(data)-self.seq_length-2)\n x_batch.append(np.copy(data[idx:idx+self.seq_length]))\n y_batch.append(np.copy(data[idx+1:idx+self.seq_length+1]))\n if random.random() < (1.0/float(n_batch)): # adjust sampling probability.\n #if this is a long datapoint, sample this data more with higher probability\n self.tick_batch_pointer()\n return x_batch, y_batch\n\n def tick_batch_pointer(self):\n self.pointer += 1\n if (self.pointer >= len(self.data)):\n self.pointer = 0\n def reset_batch_pointer(self):\n self.pointer = 0\n\ndata_loader = DataLoader(50, 300, 20)\nprint (data_loader.num_batches)\n\n'''\nseq_length = 300\nbatch_size = 3\nH = 256\nnum_layers = 2\nnum_epochs = 500\nnum_mixture = 20\nNOUT = 1 + num_mixture * 6\nlearning_rate = 0.0005\ndecay_rate = 0.95\nsave_every = 1\nmodel_dir = ''\n'''\nclass FakeArgParse():\n def __init__(self):\n pass\nargs = FakeArgParse()\n\nargs.rnn_size = 256\nargs.num_layers = 2\nargs.batch_size = 50\nargs.seq_length = 300\nargs.num_epochs = 30\nargs.save_every = 100\nargs.model_dir = '/output/'\nargs.grad_clip = 10\nargs.learning_rate = 0.0001\nargs.decay_rate = 0.95\nargs.num_mixture = 20\nargs.data_scale = 20\n\nclass Model():\n def __init__(self, args, infer=False):\n self.args = args\n\n if infer:\n args.batch_size = 1\n args.seq_length = 1\n\n tf.reset_default_graph()\n self.input_x = tf.placeholder(tf.float32, [None,args.seq_length,3], name='x_batch')\n self.input_y = tf.placeholder(tf.float32, [None,args.seq_length,3], name='y_batch')\n N = tf.shape(self.input_x)[0]\n NOUT = 1 + args.num_mixture * 6\n W = tf.Variable(np.random.rand(args.rnn_size,NOUT),dtype=tf.float32)\n b = tf.Variable(np.zeros((1,NOUT)), dtype=tf.float32)\n\n def lstm_cell():\n return tf.contrib.rnn.BasicLSTMCell(args.rnn_size, state_is_tuple=True, reuse=tf.get_variable_scope().reuse)\n cell = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(args.num_layers)], state_is_tuple=True)\n self.cell = cell\n init_state = cell.zero_state(N, tf.float32)\n self.init_state = init_state\n states_series, current_state = tf.nn.dynamic_rnn(cell, self.input_x, initial_state=self.init_state)\n states_series = tf.reshape(states_series, [-1, args.rnn_size])\n self.state_out = tf.identity(current_state, name='state_out')\n output = tf.matmul(states_series, W) + b\n #[x1, x2, eos] = tf.split(axis=1, num_or_size_splits=3, value=flat_data)\n #eos = tf.sigmoid(eos)\n\n flat_target_data = tf.reshape(self.input_y,[-1, 3])\n [x1_data, x2_data, eos_data] = tf.split(axis=1, num_or_size_splits=3, value=flat_target_data)\n\n #x1_loss = tf.losses.mean_squared_error(x1_data, x1)\n #x2_loss = tf.losses.mean_squared_error(x2_data, x2)\n #eos_loss = tf.losses.softmax_cross_entropy(eos_data, eos)\n\n def tf_2d_normal(x1, x2, mu1, mu2, s1, s2, rho):\n # eq # 24 and 25 of http://arxiv.org/abs/1308.0850\n norm1 = tf.subtract(x1, mu1)\n norm2 = tf.subtract(x2, mu2)\n s1s2 = tf.multiply(s1, s2)\n z = tf.square(tf.div(norm1, s1))+tf.square(tf.div(norm2, s2))-2*tf.div(tf.multiply(rho, tf.multiply(norm1, norm2)), s1s2)\n negRho = 1-tf.square(rho)\n result = tf.exp(tf.div(-z,2*negRho))\n denom = 2*np.pi*tf.multiply(s1s2, tf.sqrt(negRho))\n result = tf.div(result, denom)\n return result\n\n def get_lossfunc(z_pi, z_mu1, z_mu2, z_sigma1, z_sigma2, z_corr, z_eos, x1_data, x2_data, eos_data):\n result0 = tf_2d_normal(x1_data, x2_data, z_mu1, z_mu2, z_sigma1, z_sigma2, z_corr)\n # implementing eq # 26 of http://arxiv.org/abs/1308.0850\n epsilon = 1e-20\n result1 = tf.multiply(result0, z_pi)\n result1 = tf.reduce_sum(result1, 1, keep_dims=True)\n result1 = -tf.log(tf.maximum(result1, 1e-20)) # at the beginning, some errors are exactly zero.\n\n result2 = tf.multiply(z_eos, eos_data) + tf.multiply(1-z_eos, 1-eos_data)\n result2 = -tf.log(result2)\n\n result = result1 + result2\n return tf.reduce_sum(result)\n\n # below is where we need to do MDN splitting of distribution params\n def get_mixture_coef(output):\n # returns the tf slices containing mdn dist params\n # ie, eq 18 -> 23 of http://arxiv.org/abs/1308.0850\n z = output\n z_eos = z[:, 0:1]\n z_pi, z_mu1, z_mu2, z_sigma1, z_sigma2, z_corr = tf.split(axis=1, num_or_size_splits=6, value=z[:, 1:])\n\n # process output z's into MDN paramters\n\n # end of stroke signal\n z_eos = tf.sigmoid(z_eos) # should be negated, but doesn't matter.\n\n # softmax all the pi's:\n max_pi = tf.reduce_max(z_pi, 1, keep_dims=True)\n z_pi = tf.subtract(z_pi, max_pi)\n z_pi = tf.exp(z_pi)\n normalize_pi = tf.reciprocal(tf.reduce_sum(z_pi, 1, keep_dims=True))\n z_pi = tf.multiply(normalize_pi, z_pi)\n\n # exponentiate the sigmas and also make corr between -1 and 1.\n z_sigma1 = tf.exp(z_sigma1)\n z_sigma2 = tf.exp(z_sigma2)\n z_corr = tf.tanh(z_corr)\n\n return [z_pi, z_mu1, z_mu2, z_sigma1, z_sigma2, z_corr, z_eos]\n\n [o_pi, o_mu1, o_mu2, o_sigma1, o_sigma2, o_corr, o_eos] = get_mixture_coef(output)\n\n self.pi = o_pi\n self.mu1 = o_mu1\n self.mu2 = o_mu2\n self.sigma1 = o_sigma1\n self.sigma2 = o_sigma2\n self.corr = o_corr\n self.eos = o_eos\n\n lossfunc = get_lossfunc(o_pi, o_mu1, o_mu2, o_sigma1, o_sigma2, o_corr, o_eos, x1_data, x2_data, eos_data)\n self.cost = lossfunc / (args.batch_size * args.seq_length)\n\n self.lr = tf.Variable(0.0, trainable=False)\n tvars = tf.trainable_variables()\n grads, _ = tf.clip_by_global_norm(tf.gradients(self.cost, tvars), 10.)\n optimizer = tf.train.AdamOptimizer(self.lr)\n self.train_op = optimizer.apply_gradients(zip(grads, tvars))\n\n def sample(self, sess, num=1200):\n def get_pi_idx(x, pdf):\n N = pdf.size\n accumulate = 0\n for i in range(0, N):\n accumulate += pdf[i]\n if (accumulate >= x):\n return i\n print('error with sampling ensemble')\n return -1\n\n def sample_gaussian_2d(mu1, mu2, s1, s2, rho):\n mean = [mu1, mu2]\n cov = [[s1*s1, rho*s1*s2], [rho*s1*s2, s2*s2]]\n x = np.random.multivariate_normal(mean, cov, 1)\n return x[0][0], x[0][1]\n\n prev_x = np.zeros((1, 1, 3), dtype=np.float32)\n prev_x[0, 0, 2] = 1 # initially, we want to see beginning of new stroke\n prev_state = sess.run(self.cell.zero_state(1, tf.float32))\n strokes = np.zeros((num, 3), dtype=np.float32)\n mixture_params = []\n\n for i in range(num):\n\n feed = {self.input_x: prev_x, self.init_state:prev_state}\n\n [o_pi, o_mu1, o_mu2, o_sigma1, o_sigma2, o_corr, o_eos, next_state] = sess.run([self.pi, self.mu1, self.mu2, self.sigma1, self.sigma2, self.corr, self.eos, self.state_out],feed)\n\n idx = get_pi_idx(random.random(), o_pi[0])\n\n eos = 1 if random.random() < o_eos[0][0] else 0\n\n next_x1, next_x2 = sample_gaussian_2d(o_mu1[0][idx], o_mu2[0][idx], o_sigma1[0][idx], o_sigma2[0][idx], o_corr[0][idx])\n\n strokes[i,:] = [next_x1, next_x2, eos]\n\n params = [o_pi[0], o_mu1[0], o_mu2[0], o_sigma1[0], o_sigma2[0], o_corr[0], o_eos[0]]\n mixture_params.append(params)\n\n prev_x = np.zeros((1, 1, 3), dtype=np.float32)\n prev_x[0][0] = np.array([next_x1, next_x2, eos], dtype=np.float32)\n\n prev_state = tuple(\n [tf.contrib.rnn.LSTMStateTuple(next_state[idx][0],next_state[idx][1])\n for idx in range(args.num_layers)]\n )\n\n strokes[:,0:2] *= self.args.data_scale\n return strokes, mixture_params\n\nmodel = Model(args)\n\n#saver = tf.train.Saver(tf.global_variables())\n\nwith tf.Session() as sess:\n saver = tf.train.Saver()\n\n ckpt = tf.train.get_checkpoint_state('/model_data/')\n print(\"loading model: \", ckpt.model_checkpoint_path)\n\n saver.restore(sess, ckpt.model_checkpoint_path)\n #tf.global_variables_initializer().run()\n #sess.run(tf.assign(lr, learning_rate))\n for e in range(args.num_epochs):\n sess.run(tf.assign(model.lr, args.learning_rate * (args.decay_rate ** e)))\n data_loader.reset_batch_pointer()\n\n #v_x, v_y = data_loader.validation_data()\n #valid_feed = {x_batch: v_x, y_batch: v_y}\n #for b in range(2):\n # i = e * 1 + b\n for b in range(data_loader.num_batches):\n i = e * data_loader.num_batches + b\n start = time.time()\n x, y = data_loader.next_batch()\n feed = {model.input_x: x, model.input_y: y}\n train_loss, _ = sess.run([model.cost, model.train_op], feed)\n #valid_loss, _ = sess.run([total_loss, train_step], valid_feed)\n end = time.time()\n print(\n \"{}/{} (epoch {}), train_loss = {:.3f}, time/batch = {:.3f}\" \\\n .format(\n i,\n args.num_epochs * data_loader.num_batches,\n e,\n train_loss, end - start))\n if (e * data_loader.num_batches + b) % args.save_every == 0 and ((e * data_loader.num_batches + b) > 0):\n checkpoint_path = os.path.join(args.model_dir, 'model')\n saver.save(sess, checkpoint_path)\n print(\"model saved to {}\".format(checkpoint_path))\n","sub_path":"hand.py","file_name":"hand.py","file_ext":"py","file_size_in_byte":19280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"310276120","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('exhibit', '0002_exhibit_title'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='wall',\n name='next',\n field=models.OneToOneField(related_name='prev_wall', null=True, to='exhibit.Wall'),\n ),\n migrations.AddField(\n model_name='wall',\n name='prev',\n field=models.OneToOneField(related_name='next_wall', null=True, to='exhibit.Wall'),\n ),\n migrations.AlterField(\n model_name='wall',\n name='order',\n field=models.IntegerField(default=1),\n ),\n ]\n","sub_path":"project/exhibit/migrations/0003_auto_20151101_0135.py","file_name":"0003_auto_20151101_0135.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"362493144","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('site_app', '0010_auto_20150806_0755'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='sales',\n name='sales_item',\n ),\n migrations.AddField(\n model_name='sales',\n name='sale_items',\n field=models.CharField(default=datetime.datetime(2015, 8, 6, 10, 28, 16, 963935, tzinfo=utc), max_length=200),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='items',\n name='body',\n field=models.TextField(verbose_name=b'\\xd0\\x9e\\xd0\\xbf\\xd0\\xb8\\xd1\\x81'),\n ),\n migrations.AlterField(\n model_name='items',\n name='title',\n field=models.CharField(max_length=250, verbose_name=b'\\xd0\\x9d\\xd0\\xb0\\xd0\\xb7\\xd0\\xb2\\xd0\\xb0'),\n ),\n migrations.AlterField(\n model_name='posts',\n name='date',\n field=models.DateTimeField(verbose_name=datetime.datetime(2015, 8, 6, 10, 27, 46, 108338)),\n ),\n migrations.AlterField(\n model_name='sales',\n name='body',\n field=models.TextField(blank=True),\n ),\n ]\n","sub_path":"la_reine/site_app/migrations/0011_auto_20150806_1028.py","file_name":"0011_auto_20150806_1028.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"214727697","text":"#!/usr/bin/env python\n\"\"\"\n_Request.Priority_\n\nAPI for adjusting the priority of a request\n\n\"\"\"\n\n\n\nfrom WMCore.Database.DBFormatter import DBFormatter\n\nclass Priority(DBFormatter):\n \"\"\"\n _Priority_\n\n Change the priority of the request provided\n\n \"\"\"\n def execute(self, requestId, priority, conn = None, trans = False):\n \"\"\"\n _execute_\n\n Add the priorityMod to the requests priority for the request id\n provided.\n\n \"\"\"\n self.sql = \"\"\"\n UPDATE reqmgr_request SET request_priority = :priority\n WHERE request_id = :request_id\"\"\"\n binds = {\"priority\": int(priority), \"request_id\": requestId}\n result = self.dbi.processData(self.sql, binds,\n conn = conn, transaction = trans)\n return\n","sub_path":"src/python/WMCore/RequestManager/RequestDB/MySQL/Request/Priority.py","file_name":"Priority.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"608537198","text":"import random\n\npoints_for_player1=0\npoints_for_player2=0\n\nprint(\"This is a simulated card game called War, between 2 players\")\nplayer1=input(\"Player 1, please enter your name\")\nplayer2=input(\"Player 2, please enter your name\")\n\nbasic_deck = list(range(2, 15)) * 4\nrandom.shuffle(basic_deck)\n\ndef player_turn(turn):\n card = None\n if turn==1:\n print(\"\\nIt is \" + player1 + \"'s turn\")\n print(player1 + \" drew card \" + str(basic_deck[0]))\n card=basic_deck[0]\n basic_deck.pop(0)\n else:\n print(\"\\nIt is \" + player2 + \"'s turn\")\n print(player2 + \" drew card \" + str(basic_deck[0]))\n card=basic_deck[0]\n basic_deck.pop(0)\n return card\n\ndef compare_scores(card1, card2):\n global points_for_player1, points_for_player2\n if card1>card2:\n print(player1 + \" had the higher card, so they get a point\")\n points_for_player1+=1\n elif card1points_for_player2:\n print(\"\\n\" + player1 + \" won, because he/she had the most points\")\nelif points_for_player1[A-Z][LS])(?P.*?)(?P\\d+)$')\n flowers_re = regex.compile(r'^((?P\\d+)(?P[a-z]+))+$')\n\n designs = dict()\n designs['S'] = dict()\n designs['L'] = dict()\n\n for input_line in sys.stdin:\n line = input_line.rstrip()\n\n if line == '':\n break\n\n # Parse one design\n design = design_re.search(line)\n if design:\n design_name = design.group('name')\n design_flowers = design.group('flowers')\n design_count = design.group('count')\n\n designs[design_name[1]][design_name[0]] = dict()\n designs[design_name[1]][design_name[0]]['count'] = int(design_count)\n\n # Parse flowers in the design\n flowers = flowers_re.search(design_flowers)\n if flowers:\n f_counts = flowers.captures('count')\n f_types = flowers.captures('type')\n\n result_str = \"\\t\\t\"\n for f_count, f_type in zip(f_counts, f_types):\n result_str += \"{0}-{1}\".format(f_count, f_type)\n designs[design_name[1]][design_name[0]][f_type] = int(f_count)\n\n return designs;\n\n\ndef check_flower(flower, flowers, designs):\n f_type = flower[0]\n f_size = flower[1]\n flowers[f_size]['count'] = flowers[f_size]['count'] + 1\n if flowers[f_size].get(f_type) == None:\n flowers[f_size][f_type] = 0\n flowers[f_size][f_type] = flowers[f_size][f_type] + 1\n\n\n # Loop over all designs\n for key in designs[f_size]:\n bouquet = dict()\n bouquet['count'] = 0\n # Skip if have no enough flowers\n if designs[f_size][key]['count'] > flowers[f_size]['count']:\n continue\n\n\n # Check if we have enough needed types of flowers\n is_enough = True\n for i in designs[f_size][key]:\n if i == 'count':\n continue\n if flowers[f_size][i] < designs[f_size][key][i]:\n is_enough = False\n break\n bouquet[i] = designs[f_size][key][i]\n bouquet['count'] = bouquet['count'] + designs[f_size][key][i];\n\n if not is_enough:\n continue\n\n # We can create bouquet\n\n # Remove flowers from current flowers list\n for i in bouquet:\n flowers[f_size][i] = flowers[f_size][i] - bouquet[i]\n\n # Do we need to add more flowers?\n delta = designs[f_size][key]['count'] - bouquet['count']\n if delta > 0:\n for i in sorted(flowers[f_size], key = flowers[f_size].get, reverse=True):\n if i == 'count':\n continue\n if flowers[f_size][i] > 0:\n if bouquet.get(i) == None:\n bouquet[i] = 0\n if flowers[f_size][i] <= delta:\n delta = delta - flowers[f_size][i]\n bouquet[i] = bouquet[i] + flowers[f_size][i]\n else:\n bouquet[i] = bouquet[i] + delta\n delta = 0\n if delta == 0:\n break\n\n # New bouquet output\n print(\"{0}{1}\".format(key, f_size), end='')\n for i in sorted(bouquet):\n if i == 'count':\n continue\n print(\"{0}{1}\".format(bouquet[i], i), end='')\n print()\n\n\n\ndef process_flowers(designs):\n flower_re = regex.compile(r'^(?P[a-z][LS])$')\n\n flowers = dict()\n flowers['S'] = dict()\n flowers['L'] = dict()\n flowers['S']['count'] = 0\n flowers['L']['count'] = 0\n\n for input_line in sys.stdin:\n line = input_line.rstrip()\n\n tmp = flower_re.search(line)\n if tmp:\n check_flower(tmp.group('flower'), flowers, designs)\n\n\ndesigns = parse_bouquet_designs()\n\nprocess_flowers(designs)\n","sub_path":"challenge.py","file_name":"challenge.py","file_ext":"py","file_size_in_byte":3953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"307993845","text":"from __future__ import print_function\nimport tensorflow as tf\n\n\ndef add_layer(inputs, in_size, out_size, activition_function=None):\n\t # add one more layer and return the output of this layer\n\t # define layer name \n\twith tf.name_scope('layer'):\n\t\t # define weights name\n\t\twith tf.name_scope('weights'): \n\t\t\tWeights = tf.Variable(tf.random_normal([in_size, out_size]),name='W')\n\t\t # define biases \n\t\twith tf.name_scope('biases'):\n\t\t\tbiases = tf.Variable(tf.zeros([1,out_size]) + 0.1, name='b') \n\t\t # define Wx_plus_b \n\t\twith tf.name_scope('Wx_plus_b'):\n\t\t\tWx_plus_b = tf.add(tf.matmul(inputs,Weights),biases)\t\n\t\tif activition_function is None:\n\t\t\toutputs = Wx_plus_b\n\t\telse:\n\t\t\toutputs = activition_function(Wx_plus_b)\n\t\treturn outputs\n\n # define placeholder for inputs to network\nwith tf.name_scope('inputs'):\n\txs = tf.placeholder(tf.float32, [None, 1], name='x_input')\n\tys = tf.placeholder(tf.float32, [None, 1], name='y_input')\n\n # add hidden layer\t\nlayer1 = add_layer(xs, 1, 10, activition_function=tf.nn.relu)\n # add output layer\nprediction = add_layer(layer1, 10, 1, activition_function=None)\n\n # the error between prediction and real data\nwith tf.name_scope('loss'):\n\tloss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),\n\t\t\t\t\t\t\treduction_indices=[1]))\n\n\nwith tf.name_scope('train'):\n\ttrain_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)\t\n\nsess = tf.Session()\n\n # tf.train.summaryWriter soon be de\nwriter = tf.summary.FileWriter(\"E:\\\\python_program\\\\machine_learing_tensorflow\\\\my_code\",\n sess.graph)\n \n #initilizer variables \ninit = tf.global_variables_initializer()\nsess.run(init)","sub_path":"create_tensorboard.py","file_name":"create_tensorboard.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"418557731","text":"\"\"\"\noverview:\n solve small NOP using natural policy gradint\n\noutput:\n update policy\n\nusage-example:\n python3 natural_polciy_gradient_method.py\n\"\"\"\n\n# import module\nimport numpy as np\nimport copy\nimport matplotlib.pyplot as plt\nimport sys\n\n# parameter of policy\ntheta_choice = np.array([[-5,-5],[-4,-4],[-3,-3],[-2.25,-3.25],[-1.5,-1],[-1.0, -2.5]])\ncolor_list = [\"forestgreen\", \"darkgreen\", \"seagreen\", \"mediumaquamarine\", \"turquoise\", \"darkturquoise\"]\n\n# reward function\nr = np.zeros((2, 2))\nr[0, 0] = 1.0\nr[0, 1] = 0.0\nr[1, 0] = 2.0\nr[1, 1] = 0.0\n\n# policy\npi = np.zeros((2,2))\n\n# anther parameter\nalpha = 0.03\ngamma = 1\nepisode = 20\nepoch = 100000\n\n# 方策パラメータ可視化用のインスタンス\nfig = plt.figure(figsize=(12, 8))\nax = fig.add_subplot(111)\n\n# シグモイド関数\ndef sigmoid(s, theta):\n sigmoid_range = 34.5\n\n if theta[s] <= -sigmoid_range:\n return 1e-15\n if theta[s] >= sigmoid_range:\n return 1.0 - 1e-15\n\n return 1.0 / (1.0 + np.exp(-theta[s]))\n\ndef differential_log_pi(s_t, a_t, theta):\n nabla_theta = np.zeros(2)\n if a_t == 0:\n nabla_theta[s_t] = 1.0 - sigmoid(s_t, theta)\n nabla_theta[(s_t+1)%2] = 0\n else:\n nabla_theta[s_t] = (-1.0) * sigmoid(s_t, theta)\n nabla_theta[(s_t+1)%2] = 0\n\n return nabla_theta\n\ndef act(s, theta):\n pi[s, 0] = sigmoid(s, theta)\n pi[s, 1] = 1 - pi[s, 0]\n\n p = np.random.rand()\n if p <= pi[s, 0]:\n action = 0\n else:\n action = 1\n\n return action\n\ndef vanilla_polciy_gradient(theta, nabla_eta, alpha):\n delta_theta = nabla_eta\n theta_new = list(np.array(theta) + alpha * delta_theta)\n\n return theta_new\n\ndef step(s, a, r):\n if a == 0:\n s_next = s\n elif a == 1:\n s_next = (s + 1)%2\n\n return s_next, r[s, a]\n\n# 等高線の表示\ntheta1 = np.arange(-7.5, 10, 0.05)\ntheta2 = np.arange(-7.5, 10, 0.05)\n\nR_ = np.zeros((len(theta1), len(theta2)))\n# R_ = np.load('./R.npy')\ni = 0\n\nfor x in theta1:\n j = 0\n for y in theta2:\n # 初期状態の観測\n for k in range(10):\n p_s = np.random.rand()\n if p_s <= 0.8:\n s = 0\n else:\n s = 1\n theta = [x,y]\n rewards = []\n scores_deque = []\n scores = []\n\n for t in range(episode):\n a = act(s, theta)\n s, reward = step(s, a, r)\n rewards.append(reward)\n\n scores_deque.append(sum(rewards))\n scores.append(sum(rewards))\n \n discounts = [gamma**i for i in range(len(rewards)+1)]\n R_[j,i] += sum([a*b for a,b in zip(discounts, rewards)]) / 10\n j = j + 1\n i = i + 1\n\nim = ax.pcolormesh(theta1, theta2, R_, cmap='PuOr',alpha=0.3)\nim = ax.contourf(theta1, theta2, R_, cmap=\"inferno\")\nfig.colorbar(im, ax=ax)\n\ni = 0\nfor theta in theta_choice:\n\n print(theta)\n\n print(color_list[i])\n\n ax.scatter(theta[0], theta[1], s=40, marker='o', color = color_list[i])\n\n theta_total = []\n R_total = []\n\n for epoch_ in range(epoch):\n rewards = []\n scores_deque = []\n scores = []\n states = []\n actions = []\n q_values = []\n\n # 初期状態の観測\n p_s = np.random.rand()\n if p_s <= 0.8:\n s = 0\n else:\n s = 1\n\n states.append(s)\n theta_total.append(theta)\n\n # 1 episode分の状態・行動をサンプリング\n for t in range(episode):\n a = act(s, theta)\n next_state, reward = step(s, a, r)\n q = q_table[s, a]\n # 各要素の保存\n s = next_state\n rewards.append(reward)\n actions.append(a)\n states.append(s)\n q_values.append(q)\n\n # 収益の計算\n scores_deque.append(sum(rewards))\n scores.append(sum(rewards))\n\n # 各時間ステップの割引報酬和を計算\n G = []\n for t in range(episode):\n discounts = [gamma**i for i in range(episode-t+1)]\n G.append(sum([a*b for a,b in zip(discounts, rewards[t:])]))\n \n discounts = [gamma**i for i in range(len(rewards)+1)]\n R = sum([a*b for a,b in zip(discounts, rewards)]) / episode\n \n saved_nabla_log_pi = []\n policy_gradient = []\n\n # log(pi)の勾配計算\n for t in range(episode):\n saved_nabla_log_pi.append(list(np.array(differential_log_pi(states[t], actions[t], theta)).T))\n\n # モンテカルロによる勾配近似(REINFOCE)\n for nabla_log_pi_, r_ in zip(saved_nabla_log_pi, G): \n policy_gradient.append(list(np.array(nabla_log_pi_) * r_))\n \n # 方策パラメータの更新\n nabla_eta = np.sum(np.array(policy_gradient).T, axis=1) / episode\n theta = vanilla_polciy_gradient(theta, nabla_eta, alpha)\n\n R_total.append(R)\n\n theta_total_T = list(np.array(theta_total).T)\n ax.plot(theta_total_T[0], theta_total_T[1], linewidth=3, color = color_list[i])\n i = i + 1\n\n# 方策パラメータの可視化\nplt.title('Vannila Policy Gradient (100000 episode)')\nplt.xlabel('theta 1')\nplt.ylabel('theta 2')\nplt.ylim(-7.5, 10)\nplt.xlim(-7.5, 10)\n\nplt.savefig('Vanilla_Policy_Gradient.png')","sub_path":"tests/vanilla_policy_gradient_method.py","file_name":"vanilla_policy_gradient_method.py","file_ext":"py","file_size_in_byte":5371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"368638502","text":"#106 - Área Inferior\n\nM = []\nSouM = input('').upper()\n\nfor l in range(12):\n for c in range(12):\n valor = float(input(''))\n if l >= 7 and l+c >= 12 and c < l:\n M.append(valor)\n\nif SouM == 'S':\n print('%.1f' %sum(M))\nelif SouM == 'M':\n print('%.1f' %(sum(M)/len(M)))","sub_path":"URI/106[URI 1188] - Área Inferior.py","file_name":"106[URI 1188] - Área Inferior.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"117458243","text":"from ekphrasis.classes.preprocessor import TextPreProcessor\nfrom ekphrasis.classes.tokenizer import SocialTokenizer\nfrom ekphrasis.dicts.emoticons import emoticons\n\ntext_processor = TextPreProcessor(\n # terms that will be normalized\n normalize=['url', 'email', 'percent', 'money', 'phone', 'user',\n 'time', 'url', 'date', 'number'],\n # terms that will be annotated\n annotate={\"hashtag\", \"allcaps\", \"elongated\", \"repeated\",\n 'emphasis', 'censored'},\n fix_html=True, # fix HTML tokens\n\n # corpus from which the word statistics are going to be used\n # for word segmentation\n segmenter=\"twitter\",\n\n # corpus from which the word statistics are going to be used\n # for spell correction\n corrector=\"twitter\",\n\n unpack_hashtags=True, # perform word segmentation on hashtags\n unpack_contractions=True, # Unpack contractions (can't -> can not)\n spell_correct_elong=False, # spell correction for elongated words\n\n # select a tokenizer. You can use SocialTokenizer, or pass your own\n # the tokenizer, should take as input a string and return a list of tokens\n tokenizer=SocialTokenizer(lowercase=True).tokenize,\n\n # list of dictionaries, for replacing tokens extracted from the text,\n # with other expressions. You can pass more than one dictionaries.\n dicts=[emoticons]\n)\n\"\"\"\nsentences = [\n \"CANT WAIT for the new season of #TwinPeaks \(^o^)/!!! #davidlynch #tvseries :)))\",\n \"I saw the new #johndoe movie and it suuuuucks!!! WAISTED $10... #badmovies :/\",\n \"@SentimentSymp: can't wait for the Nov 9 #Sentiment talks! YAAAAAAY !!! :-D http://sentimentsymposium.com/.\"\n]\n\nfor s in sentences:\n print(\" \".join(text_processor.pre_process_doc(s)))\n\"\"\"\n\ntsv_path = \"/home/zewen/repo/res/Sem2018/en-pped/V-reg/\"\nin_files = [\"2018-Valence-reg-En-train.txt\",\n \"2018-Valence-reg-En-test.txt\",\n \"2018-Valence-reg-En-dev.txt\"]\nout_files = [s + \".pped\" for s in in_files]\n\nSPLIT = \"\\t\"\n\nfor i in range(len(in_files)):\n fi = tsv_path + in_files[i]\n fo = tsv_path + out_files[i]\n with open(fi) as ofi:\n lines = ofi.read().split(\"\\n\")\n head = lines[0]\n lines = lines[1:]\n if lines[-1] == \"\": lines = lines[:-1]\n #lines = lines[:10]\n lines = [line.split(SPLIT) for line in lines]\n for j in range(len(lines)):\n lines[j][1] = \" \".join(text_processor.pre_process_doc(lines[j][1]))\n lines[j] = SPLIT.join(lines[j])\n with open(fo, 'w') as ofo:\n ofo.write(head + \"\\n\")\n for j in range(len(lines)):\n ofo.write(lines[j] + \"\\n\")\n print(\"write \" + out_files[i] + \" finfished.\")\n\n","sub_path":"tweets/pre_frm_tsv.py","file_name":"pre_frm_tsv.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"248418936","text":"import sys\nsys.path.append(\n '/Users/rileylittlefield/Desktop/notes/readingnotes/python-ml/data-science-from-scratch/06-exercises'\n)\nsys.path.append(\n '/Users/rileylittlefield/Desktop/notes/readingnotes/python-ml/data-science-from-scratch/07-exercises'\n)\nfrom dispersion import standard_deviation\nfrom multiple_regression import estimate_beta, trainer_beta\nfrom bootstrap_samples import bootstrap_statistic\nfrom pokemon_trainers import trainer_party_stats, trainer_badge_counts\nfrom prob import normal_cdf\nimport random\n\ndef estimate_sample_beta(sample):\n x_sample, y_sample = zip(*sample)\n return estimate_beta(x_sample, y_sample)\n\n\n# Repeatedly take a bootstrap sample\n# If coefficient of one of the indpendent vars doesn't vary much across samples,\n# then we can be confident that our estimate is relatively tight.\n# If the coefficient varies greatly across samples, then we can't be at all\n# confident in our estimate.\nrandom.seed(0)\nbootstrap_betas = bootstrap_statistic(\n list(zip(trainer_party_stats, trainer_badge_counts)),\n estimate_sample_beta,\n 10\n)\n\nprint('bootstrap betas:')\nfor beta in bootstrap_betas:\n print('beta = %s' % beta)\n\nbootstrap_standard_errors = [\n standard_deviation([ \n beta[index] \n for beta \n in bootstrap_betas\n ])\n for index \n in range(3)\n]\n\nprint('standard errors: %s' % bootstrap_standard_errors)\n\n# We can then evaluate the meaningfulness of the betas \n# with the following calculations\ndef p_value(beta_hat_j, sigma_hat_j):\n if beta_hat_j > 0:\n return 2 * (1 - normal_cdf(beta_hat_j / sigma_hat_j))\n else:\n return 2 * normal_cdf(beta_hat_j / sigma_hat_j)\n\nactual_beta = trainer_beta\n\np_values = [\n p_value(trainer_beta_component, bootstrap_error_component)\n for trainer_beta_component , bootstrap_error_component\n in zip(actual_beta, bootstrap_standard_errors)\n]\n\nprint('actual_beta: %s' % actual_beta)\n\nprint('p values: %s' % p_values)\n# In this case, average level tends to be a good predictor of badge counts,\n# because it's p value is close to zero. alpha and number of pokemon types in \n# party are appreciably larger than 0, suggesting they are not reliable \n# indicators in this model\n","sub_path":"16-exercises/estimate_beta_with_bootstrap_data.py","file_name":"estimate_beta_with_bootstrap_data.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"72448870","text":"\"\"\"empty message\n\nRevision ID: a9851f087c3e\nRevises: bb4d3ada63a2\nCreate Date: 2019-12-17 15:24:34.576373\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'a9851f087c3e'\ndown_revision = 'bb4d3ada63a2'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('api_test_case', sa.Column('request_return_result', sa.String(length=200), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('api_test_case', 'request_return_result')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/a9851f087c3e_.py","file_name":"a9851f087c3e_.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"107545474","text":"import inspect\nimport string\n\ndef is_str(value):\n return isinstance(value, str)\n\ndef main():\n for name, value in inspect.getmembers(string, is_str):\n if name.startswith('_'):\n continue\n print('%s=%r\\n' % (name, value))\n\nif __name__ == \"__main__\":\n main()","sub_path":"PythonBasic/base_pkg/python-06-stdlib-review/chapter-01-Text/1.1-string/py_04_stringConstants.py","file_name":"py_04_stringConstants.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"329070423","text":"# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# License: GNU General Public License v3. See license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe import _\nfrom frappe.utils import flt\n\ndef execute(filters=None):\n\tif not filters: filters = {}\n\n\tcolumns = get_columns()\n\tdata = get_data(filters)\n\n\treturn columns, data\n\ndef get_columns():\n\treturn [\n\t\t_(\"Client\") + \":Link/Customer:100\", _(\"Appointment\")+ \":Link/Client Appointment CT:120\",\n\t\t_(\"Date\") + \":Date:90\", _(\"Doctor\") + \":Link/Doctor:100\",_(\"Doctor Name\") + \":Link/Doctor:100\",\n\t\t_(\"Clinic\") + \":Link/Department:120\", _(\"Treatment\") + \"::170\", _(\"Medical Assistant\") + \":Link/Doctor:120\",\n\t\t_(\"Medical Assistant Name\") + \":Link/Doctor:150\", _(\"Status\") + \"::70\", _(\"Cell No\") + \"::110\", _(\"Email\") + \"::110\"\n\t]\n\ndef get_data(filters):\n\tconditions = get_conditions(filters)\n\tdata=[]\n\tappointment_data=frappe.db.sql(\"\"\"select client,name,appointment_date,physician,doctor_name,clinic from `tabClient Appointment CT` where docstatus=0 %s\"\"\" % conditions)\n\tif appointment_data:\n\t\tfor appointment in appointment_data:\n\t\t\trow=[]\n\t\t\trow=[appointment[0],appointment[1],appointment[2],appointment[3],appointment[4],appointment[5]]\n\t\t\ttreatment_data=frappe.db.sql(\"\"\"select name,medical_assistant,medical_assistant_name,status from `tabClient Treatment` where appointment=%s\"\"\",appointment[1])\n\t\t\tfor treatment in treatment_data:\n\t\t\t\trow.append(treatment[0])\n\t\t\t\trow.append(treatment[1])\n\t\t\t\trow.append(treatment[2])\n\t\t\t\trow.append(treatment[3])\n\t\t\t\n\t\t\tclient_data=frappe.db.sql(\"\"\"select cell_phone,email from `tabCustomer` where name=%s\"\"\",appointment[0])\n\t\t\tfor client in client_data:\n\t\t\t\trow.append(client[0])\n\t\t\t\trow.append(client[1])\n\t\t\tdata.append(row)\n\t\treturn data\n\telse:\n\t\treturn data\t\n\n\ndef get_conditions(filters):\n\tconditions = \"\"\n\tif filters.get(\"from_date\"):\n\t\tconditions += \" and appointment_date >= '%s'\" % filters[\"from_date\"]\n\tif filters.get(\"to_date\"):\n\t\tconditions += \" and appointment_date <= '%s'\" % filters[\"to_date\"]\n\treturn conditions\t\n\n\n","sub_path":"clinic/clinic/report/client_treatment_history/client_treatment_history.py","file_name":"client_treatment_history.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"368636260","text":"import numpy as np\nimport cv2\nimport glob\nimport shutil\nimport gc\n\n\nclass FeatureMatching:\n\n def compare_photos(self):\n MIN_MATCH_COUNT = 20 # Min amount of keypoints matched, for image considered to be alike.\n\n original_image = cv2.imread('original/origin.jpg', 0)\n for image in glob.iglob(\"compare/*.jpg\"):\n\n comparison_image = cv2.imread(image)\n\n # Initiate SIFT detector\n orb = cv2.ORB_create()\n\n # find the keypoints and descriptors with SIFT\n kp1, des1 = orb.detectAndCompute(original_image, None)\n kp2, des2 = orb.detectAndCompute(comparison_image, None)\n\n # FLANN parameters\n #FLANN_INDEX_KDTREE = 1\n #index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\n #search_params = dict(checks=50) # or pass empty dictionary\n bf = cv2.BFMatcher()\n matches = bf.knnMatch(des1, des2, k=2)\n\n\n good_matches = []\n for m, n in matches:\n if m.distance < 0.7 * n.distance:\n good_matches.append(m)\n # If the amount of matches is greater than the minimal match count(accepted amount of matches)\n if len(good_matches) >= MIN_MATCH_COUNT:\n src_pts = np.float32([kp1[m.queryIdx].pt for m in good_matches]).reshape(-1, 1, 2)\n dst_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches]).reshape(-1, 1, 2)\n\n M, mask = cv2.findHomography(src_pts, dst_pts, 0, 5.0) # Find homography\n matchesMask = mask.ravel().tolist()\n\n h, w = original_image.shape\n pts = np.float32([[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]).reshape(-1, 1, 2)\n dst = cv2.perspectiveTransform(pts, M)\n\n comparison_image = cv2.polylines(comparison_image, [np.int32(dst)], True, 255, 3, cv2.LINE_AA)\n\n else:\n print(\"Not enough matches ({}) found. Minimum is {}\".format(len(good_matches), MIN_MATCH_COUNT))\n matchesMask = None\n\n draw_params = dict(matchColor=(255, 0, 0), # draw matches in green color\n singlePointColor=None,\n matchesMask=matchesMask, # draw only inliers\n flags=2)\n # Draw the matches.\n cv2.drawMatches(original_image, kp1, comparison_image, kp2, good_matches, None, **draw_params)\n amount = len(good_matches)\n if amount >= MIN_MATCH_COUNT:\n gc.collect()\n destination = 'compare2/'\n shutil.copy(image, destination)\n","sub_path":"image-search/featurematching.py","file_name":"featurematching.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"318404786","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.15-x86_64/egg/foxylib/tools/env/env_tool.py\n# Compiled at: 2020-01-06 01:07:42\n# Size of source mod 2**32: 2312 bytes\nimport logging, os, sys, yaml\nfrom future.utils import lmap, lfilter\nfrom foxylib.tools.collections.collections_tool import DictTool\nfrom foxylib.tools.jinja2.jinja2_tool import Jinja2Tool\nfrom foxylib.tools.log.foxylib_logger import FoxylibLogger\nfrom foxylib.tools.native.native_tool import BooleanTool\nfrom foxylib.tools.string.string_tool import str2strip\n\nclass EnvTool:\n\n class K:\n ENV = 'ENV'\n\n @classmethod\n def kv_list2str_export(cls, kv_list):\n str_export = '\\n'.join(['export {0}=\"{1}\"'.format(k, v_yaml) for k, v_yaml in kv_list])\n return str_export\n\n @classmethod\n def yaml_str2kv_list(cls, tmplt_str, envname_list):\n logger = FoxylibLogger.func2logger(cls.yaml_str2kv_list)\n j = yaml.load(tmplt_str)\n l = []\n for k, v in j.items():\n if not isinstance(v, dict):\n l.append((k, v))\n continue\n vv = DictTool.keys2v_first_or_default(v, envname_list)\n if vv is None:\n continue\n l.append((k, vv))\n\n logger.info({'l':l, 'tmplt_str':tmplt_str})\n return l\n\n @classmethod\n def k2v(cls, key, default=None):\n return os.environ.get(key, default)\n\n @classmethod\n def k_list2v(cls, key_list, default=None):\n for key in key_list:\n if key not in os.environ:\n continue\n return os.environ[key]\n\n return default\n\n @classmethod\n def key2nullboolean(cls, key):\n v = cls.k2v(key)\n nb = BooleanTool.parse2nullboolean(v)\n return nb\n\n @classmethod\n def key2is_true(cls, key):\n nb = cls.key2nullboolean(key)\n return nb is True\n\n @classmethod\n def key2is_not_true(cls, key):\n return not cls.key2is_true(key)","sub_path":"pycfiles/foxylib-0.3.96-py3.7/env_tool.cpython-37.py","file_name":"env_tool.cpython-37.py","file_ext":"py","file_size_in_byte":2088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"639902201","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nclass MillerRobinTest(object):\n\n def __init__(self, numberOfPrimesUsedForLargeN=16):\n def testPrimeForInitializzation(n):\n for x in range(3,n,2):\n if n % x == 0: return False\n return True\n self._knownPrimes = [2, 3]\n self._knownPrimes += [x for x in range(5, 1000, 2) if testPrimeForInitializzation(x)]\n print(self._knownPrimes)\n self._numberOfPrimesUsedForLargeN = numberOfPrimesUsedForLargeN\n \n def _testComposite(self,a, d, n, s):\n if pow(a, d, n) == 1:\n return False\n for i in range(s):\n if pow(a, 2**i * d, n) == n-1:\n return False\n return True\n \n def isPrime(self, n):\n\n if n <= 1: \n return False\n\n if n in self._knownPrimes:\n return True\n\n if any((n % p) == 0 for p in self._knownPrimes):\n return False\n \n d, s = n - 1, 0\n while (d % 2 == 0):\n d, s = d // 2, s + 1\n\n if n < 2047:\n baseOfPrimes = [2]\n elif n < 1373653:\n baseOfPrimes = [2, 3]\n elif n < 9080191:\n baseOfPrimes = [31, 73]\n elif n < 25326001:\n baseOfPrimes = [2, 3, 5]\n elif n < 4759123141:\n baseOfPrimes = [2, 7, 61]\n elif n < 3474749660383:\n baseOfPrimes = [2, 3, 5, 7, 11, 13]\n elif n < 341550071728321:\n baseOfPrimes = [2, 3, 5, 7, 11, 13, 17]\n elif n < 3825123056546413051:\n baseOfPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23]\n elif n < 318665857834031151167461:\n baseOfPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]\n elif n < 3317044064679887385961981:\n baseOfPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]\n else:\n baseOfPrimes = self._knownPrimes[:self._numberOfPrimesUsedForLargeN]\n\n return not any(self._testComposite(a, d, n, s) for a in baseOfPrimes)\n\nif __name__ == \"__main__\":\n \n Test = MillerRobinTest()\n numberOfPrimes = 0\n\n for n in range(1,2**20):\n if Test.isPrime(n):\n numberOfPrimes += 1\n if n in (10**i for i in range(1,25)):\n print(\"Arrivato al passo: \" + str(n))\n\n print(\"Numero di primi trovati: \" + str(numberOfPrimes))\n","sub_path":"Python/MillerRobin.py","file_name":"MillerRobin.py","file_ext":"py","file_size_in_byte":2364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"111602764","text":"from twisted.plugin import IPlugin\nfrom twisted.words.protocols import irc\nfrom txircd.module_interface import Command, ICommand, IMode, IModuleData, Mode, ModuleData\nfrom txircd.utils import ModeType\nfrom zope.interface import implements\nimport re\n\nirc.RPL_BADWORDADDED = \"927\"\nirc.RPL_BADWORDREMOVED = \"928\"\nirc.ERR_NOSUCHBADWORD = \"929\"\n\nclass Censor(ModuleData):\n\timplements(IPlugin, IModuleData)\n\n\tname = \"Censor\"\n\texemptLevel = 100\n\tbadwords = None\n\n\tdef userCommands(self):\n\t\treturn [ (\"CENSOR\", 1, UserCensorCommand(self)) ]\n\n\tdef serverCommands(self):\n\t\treturn [ (\"CENSOR\", 1, ServerCensorCommand(self))]\n\n\tdef channelModes(self):\n\t\treturn [ (\"G\", ModeType.NoParam, ChannelCensor(self)) ]\n\n\tdef userModes(self):\n\t\treturn [ (\"G\", ModeType.NoParam, UserCensor(self)) ]\n\n\tdef actions(self):\n\t\treturn [ (\"modeactioncheck-channel-G-commandmodify-PRIVMSG\", 10, self.channelHasMode),\n\t\t (\"modeactioncheck-channel-G-commandmodify-NOTICE\", 10, self.channelHasMode),\n\t\t (\"modeactioncheck-user-G-commandmodify-PRIVMSG\", 10, self.userHasMode),\n\t\t (\"modeactioncheck-user-G-commandmodify-NOTICE\", 10, self.userHasMode),\n\t\t (\"commandpermission-CENSOR\", 1, self.restrictToOpers),\n\t\t (\"statsruntype-censor\", 1, self.listStats),\n\t\t (\"burst\", 10, self.propgateOnBurst) ]\n\n\tdef restrictToOpers(self, user, data):\n\t\tif not self.ircd.runActionUntilValue(\"userhasoperpermission\", user, \"command-censor\", users=[user]):\n\t\t\tuser.sendMessage(irc.ERR_NOPRIVILEGES, \"Permission denied - You do not have the correct operator privileges\")\n\t\t\treturn False\n\t\treturn None\n\n\tdef channelHasMode(self, channel, user, data):\n\t\tif \"G\" in channel.modes:\n\t\t\treturn True\n\t\treturn None\n\n\tdef userHasMode(self, user, fromUser, *params):\n\t\tif \"G\" in user.modes:\n\t\t\treturn True\n\t\treturn None\n\n\tdef listStats(self):\n\t\treturn self.badwords\n\n\tdef propgateOnBurst(self, server):\n\t\tfor badword, replacement in self.badwords.iteritems():\n\t\t\tserver.sendMessage(\"CENSOR\", badword, replacement, prefix=self.ircd.serverID)\n\n\tdef propagateBadword(self, badword, replacement):\n\t\tif replacement:\n\t\t\tself.ircd.broadcastToServers(None, \"CENSOR\", badword, replacement, prefix=self.ircd.serverID)\n\t\telse:\n\t\t\tself.ircd.broadcastToServers(None, \"CENSOR\", badword, prefix=self.ircd.serverID)\n\n\tdef load(self):\n\t\tif \"badwords\" not in self.ircd.storage:\n\t\t\tself.ircd.storage[\"badwords\"] = {}\n\t\tself.badwords = self.ircd.storage[\"badwords\"]\n\nclass ChannelCensor(Mode):\n\timplements(IMode)\n\n\taffectedActions = {\n\t\t\"commandmodify-PRIVMSG\": 10,\n\t\t\"commandmodify-NOTICE\": 10\n\t}\n\n\tdef __init__(self, censor):\n\t\tself.censor = censor\n\t\tself.ircd = censor.ircd\n\n\tdef apply(self, actionName, channel, param, user, data):\n\t\tif \"targetchans\" not in data:\n\t\t\treturn\n\t\tif channel in data[\"targetchans\"] and not self.ircd.runActionUntilValue(\"checkexemptchanops\", \"censor\", channel, user):\n\t\t\tmessage = data[\"targetchans\"][channel]\n\t\t\tfor mask, replacement in self.censor.badwords.iteritems():\n\t\t\t\tmessage = re.sub(mask, replacement, message, flags=re.IGNORECASE)\n\t\t\tdata[\"targetchans\"][channel] = message\n\nclass UserCensor(Mode):\n\timplements(IMode)\n\n\taffectedActions = {\n\t\t\"commandmodify-PRIVMSG\": 10,\n\t\t\"commandmodify-NOTICE\": 10\n\t}\n\n\tdef __init__(self, censor):\n\t\tself.censor = censor\n\n\tdef apply(self, actionName, targetUser, param, user, data):\n\t\tif \"targetusers\" not in data:\n\t\t\treturn\n\t\tif targetUser in data[\"targetusers\"]: \n\t\t\tmessage = data[\"targetusers\"][targetUser]\n\t\t\tfor mask, replacement in self.censor.badwords.iteritems():\n\t\t\t\tmessage = re.sub(mask, replacement, message, flags=re.IGNORECASE)\n\t\t\tdata[\"targetusers\"][targetUser] = message\n\nclass UserCensorCommand(Command):\n\timplements(ICommand)\n\n\tdef __init__(self, censor):\n\t\tself.censor = censor\n\n\tdef parseParams(self, user, params, prefix, tags):\n\t\tif not params or not params[0]:\n\t\t\tuser.sendSingleError(\"CensorCmd\", irc.ERR_NEEDMOREPARAMS, \"CENSOR\", \"Not enough parameters\")\n\t\t\treturn None\n\t\tif len(params) == 1:\n\t\t\t# Removing a badword\n\t\t\treturn {\n\t\t\t\t\"badword\": params[0]\n\t\t\t}\n\t\telse:\n\t\t\t# Adding a badword\n\t\t\treturn {\n\t\t\t\t\"badword\": params[0],\n\t\t\t\t\"replacement\": params[1]\n\t\t\t}\n\n\tdef execute(self, user, data):\n\t\tbadword = data[\"badword\"]\n\t\tif \"replacement\" in data:\n\t\t\treplacement = data[\"replacement\"]\n\t\t\tself.censor.badwords[badword] = replacement\n\t\t\tself.censor.ircd.storage[\"badwords\"] = self.censor.badwords\n\t\t\tself.censor.propagateBadword(badword, replacement)\n\t\t\tuser.sendMessage(irc.RPL_BADWORDADDED, badword, replacement)\n\t\telse:\n\t\t\tif badword not in self.censor.badwords:\n\t\t\t\tuser.sendMessage(irc.ERR_NOSUCHBADWORD, badword, \"That's not a bad word on the badword list\")\n\t\t\t\treturn True\n\t\t\tdel self.censor.badwords[badword]\n\t\t\tself.censor.ircd.storage[\"badwords\"] = self.censor.badwords\n\t\t\tself.censor.propagateBadword(badword, None)\n\t\t\tuser.sendMessage(irc.RPL_BADWORDREMOVED, badword, \"Badword removed\")\n\t\treturn True\n\nclass ServerCensorCommand(Command):\n\timplements(ICommand)\n\n\tdef __init__(self, censor):\n\t\tself.censor = censor\n\n\tdef parseParams(self, server, params, prefix, tags):\n\t\tif len(params) == 1:\n\t\t\t# Removing a badword\n\t\t\tbadword = params[0]\n\t\t\tif badword not in self.censor.badwords:\n\t\t\t\treturn None\n\t\t\treturn {\n\t\t\t\t\"badword\": params[0]\n\t\t\t}\n\t\tif len(params) == 2:\n\t\t\t# Adding a badword\n\t\t\treturn {\n\t\t\t\t\"badword\": params[0],\n\t\t\t\t\"replacement\": params[1]\n\t\t\t}\n\t\treturn None\n\n\tdef execute(self, server, data):\n\t\tbadword = data[\"badword\"]\n\t\tif \"replacement\" in data:\n\t\t\treplacement = data[\"replacement\"]\n\t\t\tself.censor.badwords[badword] = replacement\n\t\t\tself.censor.ircd.storage[\"badwords\"] = self.censor.badwords\n\t\t\tfor remoteServer in self.censor.ircd.servers.itervalues():\n\t\t\t\tif remoteServer.nextClosest == self.censor.ircd.serverID and remoteServer != server:\n\t\t\t\t\tremoteServer.sendMessage(\"CENSOR\", badword, replacement, prefix=self.censor.ircd.serverID)\n\t\telse:\n\t\t\tdel self.censor.badwords[badword]\n\t\t\tself.censor.ircd.storage[\"badwords\"] = self.censor.badwords\n\t\t\tfor remoteServer in self.censor.ircd.servers.itervalues():\n\t\t\t\tif remoteServer.nextClosest == self.censor.ircd.serverID and remoteServer != server:\n\t\t\t\t\tremoteServer.sendMessage(\"CENSOR\", badword, prefix=self.censor.ircd.serverID)\n\t\treturn True\n\ncensorModule = Censor()","sub_path":"txircd/modules/extra/censor.py","file_name":"censor.py","file_ext":"py","file_size_in_byte":6214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"76653871","text":"from flask import Flask, request, render_template, url_for, redirect\nimport playlistr_main as playlistr\n\napp = Flask(__name__)\nnotfound = 'No videos found'\n\n@app.route('/')\ndef form():\n\tcss = url_for('static',filename='css/bootstrap.min.css')\n\treturn render_template('form.html',s=css)\n\n@app.route('/', methods=['POST'])\ndef form_post():\n\tpl = playlistr.make_playlist(request.form.get('text'))\n\tif pl == notfound: return notfound\n\telse: return redirect(pl, code=302)\n\nif __name__ == \"__main__\":\n\tapp.run(debug=True)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"460510137","text":"import battlemat\nimport character\nimport combat\nimport equip\nimport items\nimport sys\n\njaya = character.Character(charClass=\"Bard\", level=10, str=11, dex=18, con=14, int=13, wis=10, cha=16, feat_list=[\"Improved Initiative\", \"Point-Blank Shot\", \"Precise Shot\", \"Bullseye Shot\", \"Rapid Shot\", \"Arcane Strike\"], ambi=True, name=\"Jaya\", loc=[1,2], hp=67, AC=19)\n\njaya.add_weapon(items.shortbow.copy(), active=True)\njaya.add_weapon(items.guisarme.copy())\n\njaya.add_armor(items.studded_leather.copy(), active=True)\n\n#jaya.add_shield(items.buckler.copy(), active=True)\n\nmonster = character.Character(charClass=\"Fighter\", level=10, str=18, dex=10, con=8, int=14, wis=10, cha=12, feat_list=[\"Combat Expertise\", \"Critical Focus\", \"Dodge\", \"Improved Critical (guisarme)\", \"Improved Trip\", \"Intimidating Prowess\", \"Leadership\", \"Persuasive\", \"Power Attack\", \"Run\", \"Toughness\"], ambi=True, name=\"Warlord\", loc=[10,10], hp=55, AC=23, side=2)\n\nmonster.set_fighter_weap_train([\"Polearms\",\"Close\"])\n\nguisarme = items.guisarme.copy()\nguisarme.set_bon(1)\n\nmonster.add_weapon(guisarme, active=True)\n\nmonsterarm = items.full_plate.copy()\nmonsterarm.set_bon(1)\n\nmonster.add_armor(monsterarm, active=True)\n\nquinn = character.Character(charClass=\"Ranger\", level=10, str=12, dex=22, con=12, int=10, wis=14, cha=15, feat_list=[\"Precise Shot\", \"Weapon Finesse\", \"Deadly Aim\", \"Power Attack\", \"Combat Expertise\", \"Magical Tail\", \"Point-Blank Shot\", \"Rapid Shot\", \"Endurance\", \"Favored Defense (Undead)\", \"Manyshot\", \"Fox Shape\", \"Snap Shot\", \"Improved Snap Shot\"], ambi=True, name=\"Quinn\", loc=[10,10], hp=75, AC=20, side=2)\n\nquinn.set_ranger_favored_enemy([[\"Undead\",6], [\"Humanoid\",2,\"human\"], [\"Aberration\",2]])\n\nquinn.add_weapon(items.longbow.copy(), active=True)\n\nquinnarm = equip.Armor(name=\"+2 undead-defiant darkleaf leather armor\", type=\"Light\", armor_bon=4, max_dex=8, armor_check=0)\n\nquinn.add_armor(quinnarm, active=True)\n\n##########################################################\n\ntest_ftr1 = character.Character(charClass=\"Fighter\", level=1, str=17, dex=14, con=12, int=8, wis=13, cha=10, feat_list=[\"Iron Will\", \"Power Attack\", \"Toughness\"], name=\"Corwyn Klas\", loc=[1,2], hp=10, ambi=False, side=1)\n\ntest_ftr1.add_weapon(items.longsword.copy(), active=True)\n\nci_dagger = items.dagger.copy()\nci_dagger.set_mat(\"cold iron\")\ntest_ftr1.add_weapon(ci_dagger)\n\nhcb = items.crossbow_heavy.copy()\nhcb.set_ammo(20)\n\ntest_ftr1.add_weapon(hcb)\n\ntest_ftr1.add_armor(items.breastplate.copy(), active=True)\n\ntest_ftr1.add_shield(items.wooden_shield_heavy.copy(), active=True)\n\n##########################################################\n\ntest_ftr1_2h = character.Character(charClass=\"Fighter\", level=1, str=17, dex=15, con=12, int=8, wis=13, cha=10, feat_list=[\"Iron Will\", \"Power Attack\", \"Toughness\", \"Two-Weapon Fighting\"], name=\"Corwyn Klas (2h)\", loc=[1,2], hp=10, ambi=False, side=1)\n\ntest_ftr1_2h.add_weapon(items.longsword.copy(), active=True)\n\nci_dagger = items.dagger.copy()\nci_dagger.set_mat(\"cold iron\")\ntest_ftr1_2h.add_weapon(ci_dagger, off=True)\n\nhcb = items.crossbow_heavy.copy()\nhcb.set_ammo(20)\n\ntest_ftr1_2h.add_weapon(hcb)\n\ntest_ftr1_2h.add_armor(items.breastplate.copy(), active=True)\n\n##########################################################\n\ntest_barb1 = character.Character(charClass=\"Barbarian\", level=1, str=17, dex=13, con=14, int=10, wis=12, cha=8, feat_list=[\"Cleave\", \"Power Attack\"], name=\"Arjana\", loc=[5,5], hp=12, ambi=False, fc=[\"h\"], side=2)\n\ntest_barb1.add_weapon(items.greatsword.copy())\ntest_barb1.add_weapon(items.flail_heavy.copy(), active=True)\ntest_barb1.add_weapon(items.sling.copy())\n\ntest_barb1.add_armor(items.breastplate.copy(), active=True)\n\ntest_barb1.set_rage()\n\n##########################################################\n\ntest_monk1 = character.Character(charClass=\"Monk\", level=1, str=12, dex=16, con=10, int=13, wis=15, cha=8, feat_list=[\"Combat Reflexes\", \"Dodge\", \"Improved Unarmed Strike\", \"Stunning Fist\", \"Weapon Finesse\"], name=\"Careful Initiate\", loc=[4,5], hp=9, ambi=False, side=3)\n\ntest_monk1.add_weapon(items.kama.copy())\ntest_monk1.add_weapon(items.crossbow_light.copy())\n\nshuriken = items.shuriken.copy()\nshuriken.set_ammo(5)\n\ntest_monk1.add_weapon(items.shuriken)\n\n##########################################################\n\nfighter1 = test_monk1\nfighter2 = test_ftr1\n\nprint(\"{}:\".format(test_ftr1_2h.name))\nprint(fighter1.print_AC_line())\nprint(fighter1.print_save_line())\nprint(fighter1.print_all_atks())\nprint(\"\\n\\n\")\nprint(\"{}:\".format(fighter2.name))\nprint(fighter2.print_AC_line())\nprint(fighter2.print_save_line())\nprint(fighter2.print_all_atks())\nprint(\"\")\n\nmat = battlemat.Battlemat()\nfight = combat.Combat()\n\nfight.set_mat(mat)\n\nfight.add_fighter(fighter1)\nfight.add_fighter(fighter2)\n\nfight.set_tactic(fighter1,\"Close\")\nfight.set_tactic(fighter2,\"Close\")\n\nfight.set_init()\n\nroundcount = 0\n\nwhile not fight.check_combat_end() and roundcount < 50:\n# try:\n roundcount += 1\n fight.combat_round()\n# except:\n# print(\"Unexpected error: {}\".format(sys.exc_info()))\n\nprint(fight.output_log())\nprint(fighter1.get_atk_bon(0, True, fighter2.type, fighter2.subtype))\nprint(fighter1.avg_weap_dmgs(fighter2))\nprint(fighter1.avg_weap_dmgs(fighter2,prn=True))\nprint(fighter1.best_dual_wield(fighter2,prn=True))\nprint(fighter1.best_melee_equip(fighter2,prn=True))\nprint(fighter1.best_melee_opt(fighter2,prn=True))\nprint(fighter1.weap_name(fighter1.best_melee_weap(fighter2)))\nprint(fighter1.weap_name(fighter1.best_ranged_weap(fighter2)))\nprint(fighter2.get_atk_bon(0, True, fighter1.type, fighter1.subtype))\nprint(fighter2.avg_weap_dmgs(fighter1))\nprint(fighter2.avg_weap_dmgs(fighter1,prn=True))\nprint(fighter2.best_melee_equip(fighter1,prn=True))\nprint(fighter2.best_melee_opt(fighter1,prn=True))\nprint(fighter2.weap_name(fighter2.best_melee_weap(fighter1)))\nprint(fighter2.weap_name(fighter2.best_ranged_weap(fighter1)))","sub_path":"test_script.py","file_name":"test_script.py","file_ext":"py","file_size_in_byte":5888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"159548726","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport logging\n\nfrom sklearn.utils import shuffle\n\nfrom src.util import getBinaryData, sigmoid, sigmoid_cost, error_rate\n\nOUTPUT_FILE_NAME = 'ann_sigmoid_output'\n\nlogger = logging.getLogger(__file__)\nlogger.setLevel(logging.INFO)\n\n# create file handler which logs even debug messages\nfh = logging.FileHandler('../logs/' + OUTPUT_FILE_NAME + '.log')\nfh.setLevel(logging.DEBUG)\n\n# create console handler with a higher log level\nch = logging.StreamHandler()\nch.setLevel(logging.ERROR)\n\n# create formatter and add it to the handlers\nformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\nch.setFormatter(formatter)\nfh.setFormatter(formatter)\n\n# add the handlers to logger\nlogger.addHandler(ch)\nlogger.addHandler(fh)\n\n\nclass ANN(object):\n \"\"\"ANN\"\"\"\n\n def __init__(self, M):\n \"\"\"\n\n :param M: number of hidden units\n \"\"\"\n self.M = M\n\n def fit(self, X, Y, learning_rate=5*10e-7, reg=1.0, epochs=10000, show_fig=False):\n \"\"\"fit\"\"\"\n\n X, Y = shuffle(X, Y)\n Xvalid, Yvalid = X[-1000:], Y[-1000:]\n X, Y = X[:-1000], Y[:-1000]\n\n N, D = X.shape\n\n logger.info(\"**************************************************************\")\n logger.info(\"init weights\")\n logger.info(\"**************************************************************\")\n self.W1 = np.random.randn(D, self.M) / np.sqrt(D + self.M)\n self.W2 = np.random.randn(self.M) / np.sqrt(self.M)\n\n logger.info(\"**************************************************************\")\n logger.info(\"calculating bias term\")\n logger.info(\"**************************************************************\")\n self.b1 = np.zeros(self.M)\n self.b2 = 0\n\n costs = []\n best_validation_error = 1\n\n logger.info(\"**************************************************************\")\n logger.info(\"beginning for loop\")\n logger.info(\"**************************************************************\")\n for i in range(epochs):\n\n # forward propagation and cost calculation\n pY, Z = self.forward(X)\n\n # gradient descent step\n pY_Y = pY - Y\n self.W2 -= learning_rate*(Z.T.dot(pY_Y) + reg*self.W2)\n self.b2 -= learning_rate*((pY_Y).sum() + reg*self.b2)\n\n dZ = np.outer(pY_Y, self.W2) * (1 - Z*Z)\n self.W1 -= learning_rate*(X.T.dot(dZ) + reg*self.W1)\n self.b1 -= learning_rate*(np.sum(dZ, axis=0) + reg*self.b1)\n\n if i % 20 == 0:\n pYvalid, _ = self.forward(Xvalid)\n c = sigmoid_cost(Yvalid, pYvalid)\n costs.append(c)\n e = error_rate(Yvalid, np.round(pYvalid))\n print(\"i:\", i, \"cost:\", c, \"error:\", e)\n logger.info(\"i: {itr}, cost: {cost}, error: {error}\".format(itr=i, cost=c, error=e))\n if e < best_validation_error:\n best_validation_error = e\n logger.info(\"best_validation_error:{best}\".format(best=best_validation_error))\n\n self.showFig(costs, show_fig)\n\n def showFig(self, costs, show_fig=True, fileName=OUTPUT_FILE_NAME):\n \"\"\"\n\n :param costs:\n :param show_fig:\n :param fileName:\n :return:\n \"\"\"\n if show_fig:\n logger.info(\"**************************************************************\")\n logger.info(\"Generating pyplot.\")\n logger.info(\"**************************************************************\")\n plt.plot(costs)\n plt.savefig(fileName, bbox_inches='tight')\n plt.show()\n\n def forward(self, X):\n \"\"\"\n forward propagationn using tanh()\n :param X:\n :return:\n \"\"\"\n Z = np.tanh(X.dot(self.W1) + self.b1)\n return sigmoid(Z.dot(self.W2) + self.b2), Z\n\n def predict(self, X):\n \"\"\"\n predict\n :param X:\n :return:\n \"\"\"\n pY = self.forward(X)\n return np.round(pY)\n\n def score(self, X, Y):\n \"\"\"\n score\n :param X:\n :param Y:\n :return:\n \"\"\"\n prediction = self.predict(X)\n return 1 - error_rate(Y, prediction)\n\n\ndef main():\n\n logger.info(\"**************************************************************\")\n logger.info(\"getting binary data\")\n logger.info(\"**************************************************************\")\n X, Y = getBinaryData()\n\n X0 = X[Y==0, :]\n X1 = X[Y==1, :]\n\n logger.info(\"**************************************************************\")\n logger.info(\"duplicating X1 so both sets of data are roughly equal\")\n logger.info(\"**************************************************************\")\n X1 = np.repeat(X1, 9, axis=0)\n X = np.vstack([X0, X1])\n Y = np.array([0]*len(X0) + [1]*len(X1))\n\n logger.info(\"**************************************************************\")\n logger.info(\"Running ANN\")\n logger.info(\"**************************************************************\")\n model = ANN(100)\n\n logger.info(\"**************************************************************\")\n logger.info(\"fitting\")\n logger.info(\"**************************************************************\")\n model.fit(X, Y, show_fig=True)\n logger.info(\"model score: {}\".format(model.score(X, Y)))\n\n scores = cross_val_score(model, X, Y, cv=5)\n logger.info(\"score mean: {score} stdev: {stdev}\".format(score=np.mean(scores), stdev=np.std(scores)))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/ann_sigmoid.py","file_name":"ann_sigmoid.py","file_ext":"py","file_size_in_byte":5612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"92945000","text":"\"\"\" Module containing utility and helper functions\"\"\"\n\nimport time\n\n\ndef get_curr_time():\n\t\"\"\" Returns current time\"\"\"\n\treturn time.time()\n\n\ndef get_framerate(has_already_started,\n\t\t\t\t start_time,\n\t\t\t\t frame_counter,\n\t\t\t\t frame_rate,\n\t\t\t\t frame_num=5,\n\t\t\t\t decimal_round_num=2):\n\t\"\"\" Returns current framerate of video based on\n\ttime elapsed in frame_num frames.\n\n\tWorks in a while loop for each frame\"\"\"\n\tif has_already_started:\n\t\tif frame_counter % 5 == 0:\n\t\t\tcurr_time = time.time()\n\t\t\tframe_rate = frame_counter/(curr_time - start_time)\n\t\t\tframe_rate = round(frame_rate, decimal_round_num)\n\t\tframe_counter += 1\n\t\treturn has_already_started, start_time, frame_counter, frame_rate\n\n\n\telse:\n\t\thas_already_started = True\n\t\tstart_time = time.time()\n\t\tframe_counter = 0\n\t\tframe_rate = 0\n\n\t\treturn has_already_started, start_time, frame_counter, frame_rate","sub_path":"vision/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"471418321","text":"\"\"\"\n4\n7 8 2 3\n\n17\n\n3\n10 10 10\n\n20\n\n\"\"\"\nimport sys\n\ninput = lambda: sys.stdin.readline().rstrip()\n\n\nn = int(input())\ntabs = input()\n\nblanks = tabs.count(\" \")\n\nprint(sum(list(map(int, tabs.split()))) - blanks)\n","sub_path":"구름레벨/goorm_멀티탭사용.py","file_name":"goorm_멀티탭사용.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"78557284","text":"import numpy as np\nfrom scipy.optimize import minimize\n\nclass Neural_Network(object):\n \n def configureNN(self, inputSize, hiddenSize, outputSize, W1 = np.array([0]), W2 = np.array([0]), \n maxiter = 20, lambd = 0.1):\n #parameters\n self.inputSize = inputSize\n self.outputSize = outputSize\n self.hiddenSize = hiddenSize\n \n #initialize weights / random by default\n if(not W1.any()): \n self.W1 = np.random.randn(\n self.hiddenSize,\n self.inputSize + 1) # weight matrix from input to hidden layer\n else: self.W1 = W1\n if (not W2.any()): \n self.W2 = np.random.randn(\n self.outputSize,\n self.hiddenSize + 1) # weight matrix from hidden to output layerself.W2 = W2\n else: self.W2 = W2\n \n # maximum number of iterations for optimization algorithm\n self.maxiter = maxiter\n # regularization penalty\n self.lambd = lambd\n \n def addBias(self, X):\n #adds a column of ones to the beginning of an array\n if (X.ndim == 1): return np.insert(X, 0, 1)\n return np.concatenate((np.ones((len(X), 1)), X), axis=1)\n \n def delBias(self, X):\n #deletes a column from the beginning of an array\n if (X.ndim == 1): return np.delete(X, 0)\n return np.delete(X, 0, 1)\n \n def unroll(self, X1, X2):\n #unrolls two matrices into one vector \n return np.concatenate((X1.reshape(X1.size), X2.reshape(X2.size)))\n \n def sigmoid(self, s):\n # activation function\n return 1 / (1 + np.exp(-s))\n\n def sigmoidPrime(self, s):\n #derivative of sigmoid\n return s * (1 - s)\n \n def forward(self, X):\n #forward propagation through our network\n X = self.addBias(X)\n self.z = np.dot(\n X,\n self.W1.T) # dot product of X (input) and first set of 3x2 weights\n self.z2 = self.sigmoid(self.z) # activation function\n self.z2 = self.addBias(self.z2)\n self.z3 = np.dot(\n self.z2, \n self.W2.T) # dot product of hidden layer (z2) and second set of 3x1 weights\n o = self.sigmoid(self.z3) # final activation function\n return o\n\n def backward(self, X, y, o):\n # backward propgate through the network\n self.o_delta = o - y # error in output\n \n self.z2_error = self.o_delta.dot(\n self.W2\n ) # z2 error: how much our hidden layer weights contributed to output error\n self.z2_delta = np.multiply(self.z2_error, self.sigmoidPrime(\n self.z2)) # applying derivative of sigmoid to z2 error\n self.z2_delta = self.delBias(self.z2_delta)\n \n self.W1_delta += np.dot(\n np.array([self.z2_delta]).T, np.array([self.addBias(X)])) # adjusting first set (input --> hidden) weights\n self.W2_delta += np.dot(\n np.array([self.o_delta]).T, np.array([self.z2])) # adjusting second set (hidden --> output) weights\n \n def cost(self, nn_params, X, y):\n #computing how well the function does. Less = better\n self.W1_delta = 0\n self.W2_delta = 0\n m = len(X)\n \n o = self.forward(X)\n J = -1/m * sum(sum(y * np.log(o) + (1 - y) * np.log(1 - o))); #cost function\n reg = (sum(sum(np.power(self.delBias(self.W1), 2))) + sum(\n sum(np.power(self.delBias(self.W2), 2)))) * (self.lambd/(2*m)); #regularization: more precise\n J = J + reg;\n\n for i in range(m):\n o = self.forward(X[i])\n self.backward(X[i], y[i], o)\n self.W1_delta = (1/m) * self.W1_delta + (self.lambd/m) * np.concatenate(\n (np.zeros((len(self.W1),1)), self.delBias(self.W1)), axis=1)\n self.W2_delta = (1/m) * self.W2_delta + (self.lambd/m) * np.concatenate(\n (np.zeros((len(self.W2),1)), self.delBias(self.W2)), axis=1)\n \n grad = self.unroll(self.W1_delta, self.W2_delta)\n \n return J, grad\n\n def train(self, X, y):\n # using optimization algorithm to find best fit W1, W2\n nn_params = self.unroll(self.W1, self.W2)\n results = minimize(self.cost, x0=nn_params, args=(X, y), \n options={'disp': True, 'maxiter':self.maxiter}, method=\"L-BFGS-B\", jac=True)\n \n self.W1 = np.reshape(results[\"x\"][:self.hiddenSize * (self.inputSize + 1)],\n (self.hiddenSize, self.inputSize + 1))\n\n self.W2 = np.reshape(results[\"x\"][self.hiddenSize * (self.inputSize + 1):],\n (self.outputSize, self.hiddenSize + 1))\n\n def saveWeights(self):\n #sio.savemat('myWeights.mat', mdict={'W1': self.W1, 'W2' : self.W2})\n np.savetxt('data/TrainedW1.in', self.W1, delimiter=',')\n np.savetxt('data/TrainedW2.in', self.W2, delimiter=',')\n\n def predict(self, X):\n o = self.forward(X)\n i = np.argmax(o)\n o = o * 0\n o[i] = 1\n return o\n \n def predictClass(self, X):\n #printing out the number of the class, starting from 1\n print(\"Predicted class out of\", self.outputSize,\"classes based on trained weights: \")\n print(\"Input: \\n\" + str(X))\n print(\"Class number: \" + str(np.argmax( np.round(self.forward(X)) ) + 1))\n \n def accuracy(self, X, y):\n #printing out the accuracy\n p = 0\n m = len(X)\n for i in range(m):\n if (np.all(self.predict(X[i]) == y[i])): p += 1\n\n print('Training Set Accuracy: {:.2f}%'.format(p * 100 / m))\n ","sub_path":"NN.py","file_name":"NN.py","file_ext":"py","file_size_in_byte":5661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"536925795","text":"def b_distancey(baddies):\n validy = []\n \n for b in baddies[:]:\n if b['rect'].bottom > 0 and b['rect'].top < WINDOWHEIGHT:\n validy.append(abs(b['rect'].centery-player.centery))\n\n minv(validy)\n return validy[0]\n\ndef minv(valid):\n for i in range(len(valid)):\n for j in range(0, len(valid)-1-i):\n if valid[j]> valid[j+1]:\n valid[j],valid[j+1] = valid[j+1], valid[j]\n","sub_path":"remainder2.py","file_name":"remainder2.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"525666158","text":"key = ['ten', 'twenty','thirty']\r\nvalue = [10,20,30]\r\n\r\nsampleDict = dict(zip(key,value))\r\nprint(sampleDict)\r\n\r\ndict1 = {'ten':10, 'twenty': 20,'thirty':30}\r\ndict2 = {'thirty': 30, 'fourty': 40,'fifty': 50}\r\n#dic 합 구하기\r\ndict3 = {**dict1, **dict2}\r\nprint(dict3)\r\n\r\nsamDic = {\"class\":{\r\n \"student\": {\r\n \"name\" : \"Mike\",\r\n \"marks\":{\r\n \"physics\":70,\r\n \"history\":80\r\n }\r\n }\r\n}}\r\n#dict의 밑에 밑에 구하기\r\nprint(samDic['class']['student']['marks']['history'])\r\n\r\nsamDic2 = {\"name\": \"Kelly\",\"age\" : 25,\"salary\":8000,\"city\": \"new york\"}\r\nkeys = [\"name\",\"salary\"]\r\n#키 값으로 값 뽑아서 dic 만들기\r\nnewsamDic2 = {k : samDic2[k] for k in keys}\r\nprint(newsamDic2)\r\n\r\nsampleDict3 = {\r\n \"name\": \"Kelly\",\r\n \"age\": 25,\r\n \"salary\": 8000,\r\n \"city\": \"New york\"\r\n}\r\n#키 값으로 제거하기\r\nkeysToRemove = [\"name\", \"salary\"]\r\nnewsamdic3 = {k: sampleDict3[k] for k in sampleDict3.keys()-keysToRemove}\r\nprint(newsamdic3)\r\n\r\nsampleDict4 = {'a': 100, 'b': 200, 'c': 300}\r\nprint(200 in sampleDict4.values())\r\n\r\n#키값 변경하기\r\nsampleDict5 = {\r\n \"name\": \"Kelly\",\r\n \"age\":25,\r\n \"salary\": 8000,\r\n \"city\": \"New york\"\r\n}\r\nsampleDict5['location'] = sampleDict5.pop('city')\r\nprint(sampleDict5)\r\n\r\n#최소값 찾아내기\r\nsampleDict6 = {\r\n 'Physics': 82,\r\n 'Math': 65,\r\n 'history': 75\r\n}\r\nprint(min(sampleDict6, key=sampleDict6.get))\r\n\r\ndef calc(operation, *nums):\r\n sum = 0\r\n for num in nums:\r\n if operation == \"+\":\r\n sum += num\r\n elif operation ==\"*\":\r\n if sum == 0:\r\n sum =1\r\n sum *= num\r\n return sum\r\nsum = calc(\"*\",1,2,3,4,5)\r\nprint(sum)\r\n\r\ndef test(end):\r\n if end ==0:\r\n return\r\n print('재귀함수')\r\n end -= 1\r\n test(end)\r\ntest(5)\r\n#알고 있는 값에서 update\r\nsampleDict6 = {\r\n 'emp1': {'name': 'Jhon', 'salary': 7500},\r\n 'emp2': {'name': 'Emma', 'salary': 8000},\r\n 'emp3': {'name': 'Brad', 'salary': 6500}\r\n}\r\nsampleDict6['emp3']['salary'] = 8500\r\nprint(sampleDict6)\r\n\r\ndef f_sum(n):\r\n if n==0:\r\n return 0\r\n return n + f_sum(n-1)\r\nprint(f_sum(5))\r\n#이거 중요!! 제일 마지막부터 나옴\r\ndef f_number(na):\r\n if na == 0:\r\n return\r\n#재귀 ��수를 앞에 두고 프린트를 하면 앞에서 나옴\r\n f_number(int(na/10))\r\n print(na%10)\r\n\r\nf_number(1234)","sub_path":"호영스 공부/딕셔너리 공부.py","file_name":"딕셔너리 공부.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"170951212","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nnp.set_printoptions(precision=3)\r\nea = lambda x_new, x_old : np.abs((x_new - x_old) / x_new) * 100\r\n\r\n\r\nfun_z2 = lambda x : 0.95*x**3-5.9*x**2+10.9*x-6\r\nfun_nr = lambda x : x - (0.95*x**3-5.9*x**2+10.9*x-6)/(2.85*x**2-11.8*x+10.9)\r\n\r\nxx = np.linspace(3, 5, 101)\r\nyy = fun_z2(xx)\r\nplt.figure()\r\nplt.grid()\r\nplt.plot(xx, yy, label='f(x)')\r\nplt.plot([3, 5], [0, 0], 'r', label='f(x) = 0')\r\nplt.xlabel('x')\r\nplt.ylabel('f(x)')\r\nplt.legend()\r\nplt.show()\r\n\r\nx_old = 4.4\r\n\r\nfor i in range(1, 7):\r\n xi = fun_nr(x_old)\r\n yi = fun_z2(xi)\r\n print('Iteracja: {:d} | xi: {:.3e} | yi: {:.3e} | blad wzgledny: {:.2f}'.format(i, xi, yi, ea(xi, x_old)))\r\n x_old = np.copy(xi)\r\n\r\nprint(\"\\n\")\r\nfun_sec = lambda x, xp, fun : x - (fun(x) * (xp-x))/(fun(xp) - fun(x))\r\n\r\nx_old_old = 2.5\r\nx_old = 3.44\r\n\r\n\r\nfor i in range(1, 7):\r\n xi = fun_sec(x_old, x_old_old, fun_z2)\r\n yi = fun_z2(xi)\r\n print('Iteracja: {:d} | xi: {:.3e} | yi: {:.3e} | blad wzgledny: {:.2f}'.format(i, xi, yi, ea(xi, x_old)))\r\n x_old_old = np.copy(x_old)\r\n x_old = np.copy(xi)\r\n","sub_path":"metoda_Falsi_2.py","file_name":"metoda_Falsi_2.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"181862851","text":"import OrcidBaseTest\nimport properties\nimport re\nimport local_properties\n\nclass Api30AllEndPoints(OrcidBaseTest.OrcidBaseTest):\n \n xml_data_files_path = 'post_files/'\n\n def setUp(self):\n #0000-0002-7361-1027\n if properties.type == \"actions\":\n self.test_server = properties.test_server\n self.client_id = properties.memberClientId\n self.client_secret = properties.memberClientSecret\n self.notify_token = properties.notifyToken\n self.orcid_id = properties.staticId\n self.access = properties.staticAccess\n self.group_access = self.orcid_generate_member_token(self.client_id, self.client_secret, \"/group-id-record/update\")\n else:\n self.test_server = local_properties.test_server\n self.orcid_id = local_properties.orcid_id\n self.access = local_properties.step_1_access\n self.group_access = local_properties.group_access\n\n#3.0\n# The following tests post, get put code, read and check post is in response, then delete for every end-point on the 3.0 API\n def post20(self, file_name, endpoint):\n curl_params = ['-L', '-i', '-k', '-H', 'Authorization: Bearer ' + self.access, '-H', 'Content-Type: application/vnd.orcid+xml', '-H', 'Accept: application/xml', '-d', '@' + self.xml_data_files_path + file_name, '-X', 'POST']\n post_response = self.orcid_curl(\"https://api.\" + self.test_server + \"/v3.0/%s/%s\" % (self.orcid_id, endpoint), curl_params)\n return post_response\n\n def put20(self, putjson, endpoint, putcode):\n curl_params = ['-L', '-i', '-k', '-H', 'Authorization: Bearer ' + self.access, '-H', 'Content-Type: application/vnd.orcid+json', '-H', 'Accept: application/json', '-d', self.putjson, '-X', 'PUT']\n put_response = self.orcid_curl(\"https://api.\" + self.test_server + \"/v3.0/%s/%s/%s\" % (self.orcid_id, endpoint, putcode), curl_params)\n return put_response\n\n def read20(self, endpoint):\n \tcurl_params = ['-L', '-i', '-k', '-H', 'Authorization: Bearer ' + self.access, '-H', 'Content-Type: application/vnd.orcid+xml', '-H', 'Accept: application/xml', '-X', 'GET']\n \tread_response = self.orcid_curl(\"https://api.\" + self.test_server + \"/v3.0/%s/%s\" % (self.orcid_id, endpoint), curl_params)\n \treturn read_response\n\n def delete20(self, endpoint, putcode):\n curl_params = ['-L', '-i', '-k', '-H', 'Authorization: Bearer ' + self.access, '-H', 'Content-Type: application/vnd.orcid+xml', '-H', 'Accept: application/xml', '-X', 'DELETE']\n delete_response = self.orcid_curl(\"https://api.\" + self.test_server + \"/v3.0/%s/%s/%s\" % (self.orcid_id, endpoint, putcode), curl_params)\n return delete_response\n\n def getputcode(self, post_response):\n for header in post_response.split('\\n'):\n if(\"Location:\" in header):\n location_chunks = header.split('/')\n putcode = location_chunks[-1].strip()\n return putcode\n\n def issn_group(self, group_access, issn):\n \t#search\n curl_params = ['-L', '-i', '-k', '-H', 'Authorization: Bearer ' + self.group_access, '-H', 'Content-Type: application/vnd.orcid+xml', '-H', 'Accept: application/xml', '-X', 'GET']\n post_response = self.orcid_curl(\"https://api.%s/v3.0/group-id-record/?group-id=%s\" % (self.test_server, issn), curl_params)\n self.assertTrue(\"group-id\" in post_response, \"response: \" + post_response)\n #read\n read_response = self.orcid_curl(\"https://api.%s/v3.0/group-id-record/1104\" % (self.test_server), curl_params)\n self.assertTrue(\"issn:love\" in read_response, \"response: \" + read_response)\n \n def other_group(self, group_access, xmlfile):\n #post new group\n post_params = ['-L', '-i', '-k', '-H', 'Authorization: Bearer ' + self.group_access, '-H', 'Content-Type: application/vnd.orcid+xml', '-H', 'Accept: application/xml', '-d', '@' + self.xml_data_files_path + xmlfile, '-X', 'POST']\n post_response = self.orcid_curl(\"https://api.%s/v3.0/group-id-record\" % (self.test_server), post_params)\n self.assertTrue(\"HTTP/1.1 201\" in post_response, \"response: \" + post_response)\n #put-code\n putcode = self.getputcode(post_response)\n #read\n curl_params = ['-L', '-i', '-k', '-H', 'Authorization: Bearer ' + self.group_access, '-H', 'Content-Type: application/vnd.orcid+xml', '-H', 'Accept: application/xml', 'GET']\n read_response = self.orcid_curl(\"https://api.%s/v3.0/group-id-record/%s\" % (self.test_server, putcode), curl_params)\n self.assertTrue(\"orcid-generated:ind\" in read_response, \"response: \" + read_response)\n #delete\n delete_params = ['-L', '-i', '-k', '-H', 'Authorization: Bearer ' + self.group_access, '-H', 'Content-Type: application/vnd.orcid+xml', '-H', 'Accept: application/xml', '-X', 'DELETE']\n delete_response = self.orcid_curl(\"https://api.%s/v3.0/group-id-record/%s\" % (self.test_server, putcode), delete_params)\n self.assertTrue(\"HTTP/1.1 204\" in delete_response, \"response: \" + delete_response)\n \n def bio20(self, xmlfile, postendpoint, readendpoint, jsontext, postname, putname, manualname):\n #Post\n post_response = self.post20(xmlfile, postendpoint)\n self.assertTrue(\"HTTP/1.1 201\" in post_response, \"response: \" + post_response)\n #Get put-code\n putcode = self.getputcode(post_response)\n #Update\n self.putjson = '{\"put-code\":' + str(putcode) + ',' +jsontext\n put_response = self.put20(self.putjson, postendpoint, putcode)\n self.assertTrue(\"HTTP/1.1 200\" in put_response, \"response: \" + put_response)\n #Read check it was updated\n read_response = self.read20(readendpoint)\n self.assertTrue(putname in read_response and manualname in read_response and postname not in read_response, \"response: \" + read_response)\n #Delete\n delete_response = self.delete20(postendpoint, putcode)\n self.assertTrue(\"HTTP/1.1 204\" in delete_response, \"response: \" + delete_response)\n #Read check it was deleted\n read_response = self.read20(readendpoint)\n self.assertTrue(manualname in read_response and putname not in read_response, \"response: \" + read_response)\n\n def works20(self, xmlfile, postendpoint, readendpoint, jsontext, postname, putname, manualname):\n #Post\n post_response = self.post20(xmlfile, postendpoint)\n self.assertTrue(\"HTTP/1.1 201\" in post_response, \"response: \" + post_response)\n #Read Check for group\n read_response = self.read20(readendpoint)\n self.assertTrue(postname in read_response and '' not in re.sub(r'[\\s+]', '', read_response), \"response: \" + read_response)\n print (read_response)\n #Get put-code\n putcode = self.getputcode(post_response)\n # Check creation date after posting the item\n search_pattern = \"%s(.+?)\" % putcode\n creation_date_post = re.search(search_pattern, re.sub(r'[\\s+]', '', read_response))\n creation_date_post = creation_date_post.group(1)\n creation_date_post = creation_date_post.split('')[1]\n #Update\n self.putjson = '{\"put-code\":' + str(putcode) + ',' +jsontext\n put_response = self.put20(self.putjson, postendpoint, putcode)\n self.assertTrue(\"HTTP/1.1 200\" in put_response, \"response: \" + put_response)\n #Read Check there is no group\n read_response = self.read20(readendpoint)\n # Check creation date after updating the item\n creation_date_put = re.search(search_pattern, re.sub(r'[\\s+]', '', read_response))\n creation_date_put = creation_date_put.group(1)\n creation_date_put = creation_date_put.split('')[1]\n self.assertTrue(putname in read_response and '' in re.sub(r'[\\s+]', '', read_response), \"response: \" + read_response)\n self.assertTrue(creation_date_put == creation_date_post, \"post: \" + creation_date_post + \"; put: \" + creation_date_put)\n print (read_response)\n #Delete\n delete_response = self.delete20(postendpoint, putcode)\n self.assertTrue(\"HTTP/1.1 204\" in delete_response, \"response: \" + delete_response)\n #Read check it was deleted\n read_response = self.read20(readendpoint)\n self.assertTrue(manualname in read_response and putname not in read_response, \"response: \" + read_response)\n\n# Each test has josn to put and the parameters are: xml file to post, endpoint to post to, endpoint to read, json to put, text that is in the posted file, text that is in the json put update, manually added text\n def test_othername30(self):\n jsontext = '\"display-index\":0,\"content\":\"Second Name\"}'\n self.bio20('20postname.xml', 'other-names', 'other-names', jsontext, 'First name', 'Second Name', 'Other name')\n\n # https://github.com/ORCID/orcid-cypress_tests-private/blob/main/cypress/e2e/mapi/v3_0/crud_address_v30.cy.js\n\n # https://github.com/ORCID/orcid-cypress_tests-private/blob/main/cypress/e2e/mapi/v3_0/crud_keywords_v30.cy.js\n\n def test_researcherurls30(self):\n jsontext = '\"url-name\":\"Bing\",\"url\":{\"value\":\"www.bing.com\"}}'\n self.bio20('20posturl.xml', 'researcher-urls', 'researcher-urls', jsontext, 'Yahoo', 'Bing', 'Google')\n\n # https://github.com/ORCID/orcid-cypress_tests-private/blob/main/cypress/e2e/mapi/v3_0/crud_externalids_v30.cy.js\n\n # https://github.com/ORCID/orcid-cypress_tests-private/blob/main/cypress/e2e/mapi/v3_0/crud_education_v30.cy.js\n \n # https://github.com/ORCID/orcid-cypress_tests-private/blob/main/cypress/e2e/mapi/v3_0/crud_employment_v30.cy.js\n \n # https://github.com/ORCID/orcid-cypress_tests-private/blob/main/cypress/e2e/mapi/v3_0/crud_distinction_v30.cy.js\n \n # https://github.com/ORCID/orcid-cypress_tests-private/blob/main/cypress/e2e/mapi/v3_0/crud_invited_position_v30.cy.js\n \n # https://github.com/ORCID/orcid-cypress_tests-private/blob/main/cypress/e2e/mapi/v3_0/crud_membership_v30.cy.js\n \n def test_qualification30(self):\n jsontext = '\"department-name\":\"Rocket Science\",\"role-title\":\"BA\",\"start-date\" : {\"year\" : {\"value\" : \"2001\"}},\"organization\":{\"name\":\"University of Oxford \",\"address\":{\"city\":\"Oxford\",\"region\":\"Oxfordshire\",\"country\":\"GB\"},\"disambiguated-organization\" : {\"disambiguated-organization-identifier\":\"6396\",\"disambiguation-source\" : \"RINGGOLD\"}}}'\n self.bio20('30postqualify.xml', 'qualification', 'qualifications', jsontext, 'Annapolis', 'Oxford', 'AFL-CIO')\n \n def test_service30(self):\n jsontext = '\"department-name\":\"Rocket Science\",\"role-title\":\"BA\",\"start-date\" : {\"year\" : {\"value\" : \"2001\"}},\"organization\":{\"name\":\"University of Oxford\",\"address\":{\"city\":\"Oxford\",\"region\":\"Oxfordshire\",\"country\":\"GB\"},\"disambiguated-organization\" : {\"disambiguated-organization-identifier\":\"6396\",\"disambiguation-source\" : \"RINGGOLD\"}}}'\n self.bio20('30postservice.xml', 'service', 'services', jsontext, 'Annapolis', 'Oxford', 'ORCID')\n\n # https://github.com/ORCID/orcid-cypress_tests-private/blob/main/cypress/e2e/mapi/v3_0/crud_funding_v30.cy.js\n\n # https://github.com/ORCID/orcid-cypress_tests-private/blob/main/cypress/e2e/mapi/v3_0/crud_research_resource_v30.cy.js\n\n # https://github.com/ORCID/orcid-cypress_tests-private/blob/main/cypress/e2e/mapi/v3_0/crud_work_v30.cy.js \n \n # https://github.com/ORCID/orcid-cypress_tests-private/blob/main/cypress/e2e/mapi/v3_0/crud_peerReview_v30.cy.js\n\n def test_peerreview_group(self):\n #search for and read a peer-review group with an issn group id\n self.issn_group(self.group_access, '1741-4857')\n \n def test_other_group(self):\n #create, read, delete a peer-review group with a non issn group id\n \t self.other_group(self.group_access, 'group.xml')\n\n def test_client_endpoint(self):\n #check response of the client endpoint\n curl_params = ['-i', '-L', '-k', '-H', \"Accept: application/json\"]\n response = self.orcid_curl(\"https://pub.\" + self.test_server + \"/v3.0/client/APP-7M3CGDKMQE36J56N\", curl_params)\n self.assertTrue(\"secret\" not in response, \"Unexpected response: \" + response)\n \n def test_client_endpoint(self):\n #check response of the client endpoint in xml\n curl_params = ['-i', '-L', '-k', '-H', \"Accept: application/vnd.orcid+xml\"]\n response = self.orcid_curl(\"https://pub.\" + self.test_server + \"/v3.0/client/APP-7M3CGDKMQE36J56N\", curl_params)\n self.assertTrue(\"secret\" not in response, \"Unexpected response: \" + response)\n","sub_path":"orcid/test_30api_all_endpoints.py","file_name":"test_30api_all_endpoints.py","file_ext":"py","file_size_in_byte":12800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"396086503","text":"# -*- encoding: utf-8 -*-\n\"\"\"\ntest.py\nCreated on 2018/8/9 14:36\nCopyright (c) 2018/8/9, \n@author: 马家树(majstx@163.com)\n\"\"\"\nimport openpyxl\n\nwb = openpyxl.load_workbook(\"C:/Users/meridian/Desktop/test/test.xlsx\")\nws = wb.get_active_sheet()\nval = ws.cell(row=1, column=1).value\n\nworkbook = openpyxl.Workbook()\nsheet = workbook.active\nsheet.cell(row=1, column=1).value = val","sub_path":"excelpro3/tfdxlsx2xlsx/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"590089451","text":"# -*- coding: utf-8 -*-\n\nfrom nwae.utils.Log import Log\nimport nwae.utils.StringUtils as su\nfrom inspect import currentframe, getframeinfo\nfrom nwae.lang.preprocessing.BasicPreprocessor import BasicPreprocessor\nimport nwae.lang.LangHelper as langhelper\nimport nwae.lang.characters.LangCharacters as langchar\nimport nwae.lang.LangFeatures as langfeatures\nimport nwae.lang.nlp.sajun.SpellCheckSentence as spellcor\nimport nwae.lang.nlp.lemma.Lemmatizer as lmtz\nimport re\nfrom mex.MexBuiltInTypes import MexBuiltInTypes\nfrom mex.MatchExpression import MatchExpression\n\n\n#\n# Самая важная и основная обработка тесктов в первом этапе любой обработки NLP, Машинного Обучения или\n# Искусственного Интеллекта.\n# Только предварительная обработка исходных текстовых данных в \"чистую\" форму текста без кодирования в числа.\n#\n# The method process_text() takes in a string, and outputs a list of split tokens, and cleaned with the\n# listed processes below.\n# However these split tokens are still in string form, and further processing is still required to convert\n# them to label, one-hot encodings, or word embeddings to be suitable for further ML/AI processing.\n#\n# 1. Replace special tokens like URLs with special symbols\n# 2. Segment text or word tokenization\n# For languages like English, Spanish, Korean, etc, this is easy, only split by space.\n# But for languages with no spaces like Chinese, Japanese, Thai, Lao, Cambodian,\n# or languages that have only syllable boundaries like Vietnamese & Chinese,\n# this is a complicated process.\n# 3. Convert to lowercase, clean/separate common punctuations from words\n# 4. Normalize text, replacing synonyms with single word\n# 5. Spelling correction\n# 6. Remove stopwords\n# 7. Stemming or Lemmatization\n# Stemming does not necessarily generate a dictionary/valid word, its sole purpose is just to\n# reduce conjugated words to the same root.\n# Thus if the meaning of a word is important, it needs to be lemmatized instead of stemmed\n#\n# When model updates, this also need to update. So be careful.\n#\nclass TxtPreprocessor:\n\n def __init__(\n self,\n identifier_string,\n # If None, will not do spelling correction\n dir_path_model,\n # If None, will not replace any word with unknown symbol W_UNK\n model_features_list,\n lang,\n dirpath_synonymlist,\n postfix_synonymlist,\n dir_wordlist,\n postfix_wordlist,\n dir_wordlist_app,\n postfix_wordlist_app,\n # For certain languages like English, it is essential to include this,\n # otherwise predict accuracy will drop drastically.\n # But at the same time must be very careful. By adding manual rules, for\n # example we include words 'it', 'is'.. But \"It is\" could be a very valid\n # training data that becomes excluded wrongly.\n stopwords_list = None,\n do_spelling_correction = False,\n do_word_stemming = True,\n do_profiling = False\n ):\n self.identifier_string = identifier_string\n self.dir_path_model = dir_path_model\n self.model_features_list = model_features_list\n \n self.lang = langfeatures.LangFeatures.map_to_lang_code_iso639_1(\n lang_code = lang\n )\n self.dirpath_synonymlist = dirpath_synonymlist\n self.postfix_synonymlist = postfix_synonymlist\n self.dir_wordlist = dir_wordlist\n self.postfix_wordlist = postfix_wordlist\n self.dir_wordlist_app = dir_wordlist_app\n self.postfix_wordlist_app = postfix_wordlist_app\n # Allowed root words are just the model features list\n self.allowed_root_words = self.model_features_list\n self.stopwords_list = stopwords_list\n self.do_spelling_correction = do_spelling_correction\n self.do_word_stemming = do_word_stemming\n self.do_profiling = do_profiling\n\n Log.info(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Using wordlist dir \"' + str(self.dir_wordlist)\n + '\", app wordlist dir \"' + str(self.dir_wordlist_app)\n + '\", synonym dir \"' + str(self.dirpath_synonymlist) + '\"'\n )\n\n self.words_no_replace_with_special_symbols = \\\n list(langchar.LangCharacters.UNICODE_BLOCK_WORD_SEPARATORS) + \\\n list(langchar.LangCharacters.UNICODE_BLOCK_SENTENCE_SEPARATORS) + \\\n list(langchar.LangCharacters.UNICODE_BLOCK_PUNCTUATIONS) + \\\n list(BasicPreprocessor.ALL_SPECIAL_SYMBOLS)\n\n self.words_no_replace_with_special_symbols = list(set(self.words_no_replace_with_special_symbols))\n Log.important(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': For model \"' + str(self.identifier_string)\n + '\", words that will not replace with special symbols: '\n + str(self.words_no_replace_with_special_symbols)\n )\n\n #\n # We initialize word segmenter and synonym list after the model is ready\n # because it requires the model features so that root words of synonym lists\n # are only from the model features\n #\n self.wseg = None\n self.synonymlist = None\n self.spell_correction = None\n # Stemmer/Lemmatizer\n self.lang_have_verb_conj = False\n self.word_stemmer_lemmatizer = None\n\n ret_obj = langhelper.LangHelper.get_word_segmenter(\n lang = self.lang,\n dirpath_wordlist = self.dir_wordlist,\n postfix_wordlist = self.postfix_wordlist,\n dirpath_app_wordlist = self.dir_wordlist_app,\n postfix_app_wordlist = self.postfix_wordlist_app,\n dirpath_synonymlist = self.dirpath_synonymlist,\n postfix_synonymlist = self.postfix_synonymlist,\n # We can only allow root words to be words from the model features\n allowed_root_words = self.model_features_list,\n do_profiling = self.do_profiling\n )\n self.wseg = ret_obj.wseg\n self.synonymlist = ret_obj.snnlist\n\n #\n # For spelling correction\n #\n if self.do_spelling_correction:\n try:\n self.spell_correction = spellcor.SpellCheckSentence(\n lang = self.lang,\n words_list = self.model_features_list,\n dir_path_model = self.dir_path_model,\n identifier_string = self.identifier_string,\n do_profiling = self.do_profiling\n )\n Log.important(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Spelling Correction for model \"' + str(self.identifier_string)\n + '\" initialized successfully.'\n )\n except Exception as ex_spellcor:\n self.spell_correction = None\n errmsg = str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno) \\\n + ': Error initializing spelling correction for model \"' \\\n + str(self.identifier_string) \\\n + '\", got exception \"' + str(ex_spellcor) + '\".'\n Log.error(errmsg)\n\n #\n # For stemmer / lemmatization\n #\n if self.do_word_stemming:\n lfobj = langfeatures.LangFeatures()\n self.lang_have_verb_conj = lfobj.have_verb_conjugation(lang=self.lang)\n Log.important(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Lang \"' + str(self.lang) + '\" verb conjugation = ' + str(self.lang_have_verb_conj) + '.'\n )\n self.word_stemmer_lemmatizer = None\n if self.lang_have_verb_conj:\n try:\n self.word_stemmer_lemmatizer = lmtz.Lemmatizer(\n lang=self.lang\n )\n Log.important(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Lang \"' + str(self.lang) + '\" stemmer/lemmatizer initialized successfully.'\n )\n except Exception as ex_stemmer:\n errmsg = str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno) \\\n + ': Lang \"' + str(self.lang) + ' stemmer/lemmatizer failed to initialize: ' \\\n + str(ex_stemmer) + '.'\n Log.error(errmsg)\n self.word_stemmer_lemmatizer = None\n\n self.mex_username_nonword = MatchExpression(\n pattern = 'u,' + MexBuiltInTypes.MEX_TYPE_USERNAME_NONWORD + ',',\n lang = None\n )\n return\n\n def __is_username_nonword_type(\n self,\n word\n ):\n params_dict = self.mex_username_nonword.get_params(\n sentence=word,\n return_one_value=True # if False will return both (left,right) values\n )\n is_username_nonword_type = params_dict['u'] is not None\n return is_username_nonword_type\n\n def __remove_stopwords(\n self,\n word_list\n ):\n if self.stopwords_list:\n word_list_remove = []\n for w in word_list:\n if w not in self.stopwords_list:\n word_list_remove.append(w)\n Log.debug(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Lang \"' + str(self.lang) + '\", Word list \"' + str(word_list)\n + '\", removed stopwords to \"' + str(word_list_remove) + '\".'\n )\n return word_list_remove\n else:\n return word_list\n\n def preprocess_list(\n self,\n sentences_list,\n ):\n return [self.process_text(inputtext=s, return_as_string=False) for s in sentences_list]\n\n #\n # Some things we do\n # 1. Replace special tokens like URLs with special symbols\n # 2. Segment text or word tokenization\n # 3. Convert to lowercase, clean/separate common punctuations from words\n # 4. Normalize text, replacing synonyms with single word\n # 5. Spelling correction\n # 6. Remove stopwords\n # 7. Stemming or Lemmatization\n #\n def process_text(\n self,\n inputtext,\n return_as_string = False,\n use_special_symbol_username_nonword = False\n ):\n #\n # 1st Round replace with very special symbols first, that must be done before\n # word segmentation or cleaning.\n # Be careful here, don't simply replace things.\n # For symbols that can wait until after word segmentation like numbers, unknown\n # words, we do later.\n #\n pat_rep_list = [\n {\n 'pattern': MexBuiltInTypes.REGEX_URI,\n 'repl': ' ' + BasicPreprocessor.W_URI + ' '\n },\n ]\n inputtext_sym = su.StringUtils.trim(str(inputtext))\n for pat_rep in pat_rep_list:\n inputtext_sym = re.sub(\n pattern = pat_rep['pattern'],\n repl = pat_rep['repl'],\n string = inputtext_sym\n )\n Log.debug(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Lang \"' + str(self.lang) + '\", Text \"' + str(inputtext)\n + '\" special pattern replacement to: ' + str(inputtext_sym)\n )\n\n #\n # Segment words\n #\n # Returns a word array, e.g. ['word1', 'word2', 'x', 'y',...]\n text_segmented_arr = self.wseg.segment_words(\n text = inputtext_sym,\n return_array_of_split_words = True\n )\n Log.debug(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Lang \"' + str(self.lang) + '\", Text \"' + str(inputtext)\n + '\" segmented to: ' + str(text_segmented_arr)\n )\n\n #\n # Remove basic punctuations stuck to word\n #\n # Will return None on error\n tmp_arr = BasicPreprocessor.clean_punctuations(\n sentence = text_segmented_arr\n )\n if type(tmp_arr) in [list, tuple]:\n text_segmented_arr = tmp_arr\n Log.debug(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Lang \"' + str(self.lang) + '\", Text \"' + str(inputtext)\n + '\" clean punctuations to: ' + str(text_segmented_arr)\n )\n\n #\n # Replace words with root words\n # This step uses synonyms and replaces say \"красивая\", \"милая\", \"симпатичная\", all with \"красивая\"\n # This will reduce training data without needing to put all versions of the same thing.\n #\n text_normalized_arr = self.synonymlist.normalize_text_array(\n text_segmented_array = text_segmented_arr\n )\n\n text_normalized_arr_lower = [s.lower() for s in text_normalized_arr]\n\n Log.debug(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Lang \"' + str(self.lang) + '\", Text \"' + str(inputtext)\n + '\", normalized to \"' + str(text_normalized_arr_lower) + '\"'\n )\n\n #\n # Spelling correction\n #\n if self.do_spelling_correction:\n if self.spell_correction is not None:\n text_normalized_arr_lower = self.spell_correction.check(\n text_segmented_arr = text_normalized_arr_lower\n )\n Log.info(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Lang \"' + str(self.lang) + '\", Text \"' + str(inputtext)\n + '\", corrected spelling to \"' + str(text_normalized_arr_lower) + '\".'\n )\n\n #\n # Remove stopwords before stemming\n #\n text_normalized_arr_lower = self.__remove_stopwords(\n word_list = text_normalized_arr_lower\n )\n\n #\n # Stemming / Lemmatization\n #\n Log.debug(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Lang \"' + str(self.lang)\n + '\" do stemming = ' + str(self.do_word_stemming)\n + ', have verb conjugation = ' + str(self.lang_have_verb_conj)\n )\n if self.do_word_stemming and self.lang_have_verb_conj:\n if self.word_stemmer_lemmatizer:\n for i in range(len(text_normalized_arr_lower)):\n text_normalized_arr_lower[i] = self.word_stemmer_lemmatizer.stem(\n word = text_normalized_arr_lower[i]\n )\n Log.debug(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Lang \"' + str(self.lang) + '\", Text \"' + str(inputtext)\n + '\", stemmed to \"' + str(text_normalized_arr_lower) + '\".'\n )\n\n #\n # 2nd round replace with special symbols for numbers, unrecognized vocabulary, etc.\n # MUST NOT accidentally replace our earlier special symbols like _uri, etc.\n #\n for i in range(len(text_normalized_arr_lower)):\n word = text_normalized_arr_lower[i]\n\n #\n # Punctuations, special symbols themselves, etc, will not undergo this process\n #\n if word in self.words_no_replace_with_special_symbols:\n continue\n\n # Check numbers first, re.match() is fast enough\n # Replace numbers with separate symbol\n if re.match(pattern='^[0-9]+$', string=word):\n Log.debugdebug(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Found for number in word \"' + str(word) + '\"'\n )\n text_normalized_arr_lower[i] = BasicPreprocessor.W_NUM\n elif self.model_features_list is not None:\n if word not in self.model_features_list:\n text_normalized_arr_lower[i] = BasicPreprocessor.W_UNK\n if use_special_symbol_username_nonword:\n # Check if it is a username_nonword form\n if self.__is_username_nonword_type(word=word):\n text_normalized_arr_lower[i] = BasicPreprocessor.W_USERNAME_NONWORD\n else:\n if use_special_symbol_username_nonword:\n if self.__is_username_nonword_type(word=word):\n text_normalized_arr_lower[i] = BasicPreprocessor.W_USERNAME_NONWORD\n\n #\n # Remove stopwords again after stemming\n #\n text_normalized_arr_lower = self.__remove_stopwords(\n word_list = text_normalized_arr_lower\n )\n\n #\n # Finally remove empty words in array\n #\n text_normalized_arr_lower = [x for x in text_normalized_arr_lower if x != '']\n\n Log.info(\n str(self.__class__) + ' ' + str(getframeinfo(currentframe()).lineno)\n + ': Lang \"' + str(self.lang)\n + '\", Done text processing to: ' + str(text_normalized_arr_lower)\n + ' from \"' + str(inputtext) + '\".'\n )\n\n if return_as_string:\n print_separator = BasicPreprocessor.get_word_separator(\n lang = self.lang\n )\n return print_separator.join(text_normalized_arr_lower)\n else:\n return text_normalized_arr_lower\n\n\nif __name__ == '__main__':\n from nwae.lang.config.Config import Config\n config = Config.get_cmdline_params_and_init_config_singleton(\n Derived_Class = Config,\n default_config_file = '/usr/local/git/nwae/nwae.lang/app.data/config/default.cf'\n )\n\n from nwae.lang.LangFeatures import LangFeatures\n Log.LOGLEVEL = Log.LOG_LEVEL_DEBUG_2\n\n obj = TxtPreprocessor(\n identifier_string = 'test',\n # Don't need directory path for model, as we will not do spelling correction\n dir_path_model = None,\n # Don't need features/vocabulary list from model\n model_features_list = None,\n lang = LangFeatures.LANG_TH,\n dirpath_synonymlist = config.get_config(param=Config.PARAM_NLP_DIR_SYNONYMLIST),\n postfix_synonymlist = config.get_config(param=Config.PARAM_NLP_POSTFIX_SYNONYMLIST),\n dir_wordlist = config.get_config(param=Config.PARAM_NLP_DIR_WORDLIST),\n postfix_wordlist = config.get_config(param=Config.PARAM_NLP_POSTFIX_WORDLIST),\n dir_wordlist_app = config.get_config(param=Config.PARAM_NLP_DIR_APP_WORDLIST),\n postfix_wordlist_app = config.get_config(param=Config.PARAM_NLP_POSTFIX_APP_WORDLIST),\n do_spelling_correction = False,\n do_word_stemming = False,\n do_profiling = False\n )\n\n texts = [\n 'ปั่นสล็อต100ครั้ง',\n 'อูเสอgeng.mahk_mahk123ได้'\n ]\n\n for txt in texts:\n obj.process_text(inputtext = txt)\n\n #\n # Must be able to handle without word lists\n #\n obj = TxtPreprocessor(\n identifier_string = 'test',\n # Don't need directory path for model, as we will not do spelling correction\n dir_path_model = None,\n # Don't need features/vocabulary list from model\n model_features_list = None,\n lang = LangFeatures.LANG_RU,\n dirpath_synonymlist = None,\n postfix_synonymlist = None,\n dir_wordlist = None,\n postfix_wordlist = None,\n dir_wordlist_app = None,\n postfix_wordlist_app = None,\n do_spelling_correction = False,\n do_word_stemming = False,\n do_profiling = False,\n )\n texts = [\n 'Аккаунт популярного южнокорейского чат-бота был заблокирован',\n 'после жалоб на ненавистнические высказывания в адрес сексуальных меньшинств',\n ]\n for txt in texts:\n obj.process_text(inputtext = txt)\n\n texts = [\n '存款10次http://abc.com',\n ]\n obj = TxtPreprocessor(\n identifier_string = 'test',\n # Don't need directory path for model, as we will not do spelling correction\n dir_path_model = None,\n # Don't need features/vocabulary list from model\n model_features_list = None,\n lang = LangFeatures.LANG_EN,\n dirpath_synonymlist = config.get_config(param=Config.PARAM_NLP_DIR_SYNONYMLIST),\n postfix_synonymlist = config.get_config(param=Config.PARAM_NLP_POSTFIX_SYNONYMLIST),\n dir_wordlist = config.get_config(param=Config.PARAM_NLP_DIR_WORDLIST),\n postfix_wordlist = config.get_config(param=Config.PARAM_NLP_POSTFIX_WORDLIST),\n dir_wordlist_app = config.get_config(param=Config.PARAM_NLP_DIR_APP_WORDLIST),\n postfix_wordlist_app = config.get_config(param=Config.PARAM_NLP_POSTFIX_APP_WORDLIST),\n do_spelling_correction = False,\n do_word_stemming = False,\n do_profiling = False\n )\n for txt in texts:\n obj.process_text(inputtext = txt)\n\n exit(0)\n","sub_path":"build/lib/nwae/lang/preprocessing/TxtPreprocessor.py","file_name":"TxtPreprocessor.py","file_ext":"py","file_size_in_byte":21970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"77705925","text":"\"\"\"\ns3 upload -> rekognition face-detection -> sns\n環境変数\n - SLACK_API_KEY: slack通知のためのAPIキー\n - SNS_TOPIC_ARN: rekognition解析後の通知先SNSのARN\n - ROLE_ARN: rekognitionからSNSに通知を飛ばすためのrole\n\"\"\"\nimport os\nimport boto3\nfrom slacker import Slacker # pylint: disable=import-error\n\n\ndef send_slack(message, channel='#general', user='顔面みっけ君', icon=':eyes:'):\n \"\"\"\n slack nortification\n \"\"\"\n slack_api_key = os.environ['SLACK_API_KEY']\n if slack_api_key != \"\":\n slack = Slacker(slack_api_key)\n slack.chat.post_message(\n channel,\n message,\n username=user,\n icon_emoji=icon)\n\n\ndef rekognition(bucket, video_path):\n \"\"\"\n call rekognition\n \"\"\"\n client = boto3.client('rekognition', region_name='ap-northeast-1')\n response = client.start_face_detection(\n Video={\n 'S3Object': {\n 'Bucket': bucket,\n 'Name': video_path\n }\n },\n NotificationChannel={\n 'SNSTopicArn': os.environ['SNS_TOPIC_ARN'],\n 'RoleArn': os.environ['ROLE_ARN']\n }\n )\n message = '顔面みっけてくるね\\n動画: s3://{0}/{1}\\njobID: {2}'.format(\n bucket, video_path, response['JobId']\n )\n send_slack(message)\n return response['JobId']\n\n\ndef main(event, _):\n \"\"\"\n eventから動画のあるバケットとファイル名を取得して、rekognitionに投げる\n \"\"\"\n rekognition(\n event['Records'][0]['s3']['bucket']['name'],\n event['Records'][0]['s3']['object']['key']\n )\n","sub_path":"face_detection/start-face-detection/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"389933198","text":"#!/usr/bin/env python3\n# pyre-strict\n\nfrom collections import defaultdict\nfrom typing import DefaultDict, Dict, Iterable, List, Optional, Set, Tuple\n\nfrom sapp.bulk_saver import BulkSaver\nfrom sapp.models import (\n DBID,\n Issue,\n IssueInstance,\n IssueInstanceFixInfo,\n Postcondition,\n Precondition,\n SharedText,\n SharedTextKind,\n Sink,\n Source,\n TraceFrame,\n TraceFrameAnnotation,\n)\n\n\nclass TraceGraph(object):\n \"\"\"Represents a graph of the Zoncolan trace steps. Nodes of the graph are\n the issues, preconditions, postconditions, sources and sinks. Edges are\n the the assocs, and for pre/postconditions, the map of 'caller->callee'\n gives a one direction edge to the next pre/postcondition, and the map of\n 'callee->caller' gives the reverse edge.\n \"\"\"\n\n def __init__(self) -> None:\n self._issues: Dict[int, Issue] = {}\n self._issue_instances: Dict[int, IssueInstance] = {}\n self._trace_annotations: Dict[int, TraceFrameAnnotation] = {}\n\n # Remove after we remove Sources/Sinks table, currently deprecated and\n # replaced by the SharedText table (T30720232)\n self._sources: Dict[int, Source] = {}\n self._sinks: Dict[int, Sink] = {}\n self._shared_text_to_source: Dict[int, Source] = {}\n self._shared_text_to_sink: Dict[int, Sink] = {}\n\n self._precondition_to_trace_frame: Dict[int, TraceFrame] = {}\n self._trace_frame_to_precondition: Dict[int, Precondition] = {}\n\n self._postcondition_to_trace_frame: Dict[int, TraceFrame] = {}\n self._trace_frame_to_postcondition: Dict[int, Postcondition] = {}\n\n # Create a mapping of (caller, caller_port) to the corresponding\n # pre/postcondition's id.\n self._preconditions_map: DefaultDict[ # pyre-ignore: T41307149\n Tuple[str, str], Set[int]\n ] = defaultdict(set)\n self._postconditions_map: DefaultDict[ # pyre-ignore: T41307149\n Tuple[str, str], Set[int]\n ] = defaultdict(set)\n self._trace_frames_map: DefaultDict[ # pyre-ignore: T41307149\n Tuple[str, str], Set[int]\n ] = defaultdict(set)\n\n # Similar to pre/postconditions_map, but maps the reverse direction\n # of the trace graph, i.e. (callee[, callee_port]) to the\n # pre/postcondition_id.\n self._preconditions_rev_map: DefaultDict[ # pyre-ignore: T41307149\n Tuple[str, str], Set[int]\n ] = defaultdict(set)\n self._postconditions_rev_map: DefaultDict[ # pyre-ignore: T41307149\n Tuple[str, str], Set[int]\n ] = defaultdict(set)\n self._trace_frames_rev_map: DefaultDict[ # pyre-ignore: T41307149\n Tuple[str, str], Set[int]\n ] = defaultdict(set)\n\n self._preconditions: Dict[int, Precondition] = {}\n self._postconditions: Dict[int, Postcondition] = {}\n self._trace_frames: Dict[int, TraceFrame] = {}\n\n self._shared_texts: Dict[int, SharedText] = {}\n # pyre-fixme[8]: Attribute has type `DefaultDict[SharedTextKind, Dict[str, in...\n self._shared_text_lookup: (\n DefaultDict[SharedTextKind, Dict[str, int]]\n ) = defaultdict(dict)\n\n self._precondition_sink_assoc: DefaultDict[ # pyre-ignore: T41307149\n int, Set[Tuple[int, int]]\n ] = defaultdict(set)\n self._postcondition_source_assoc: DefaultDict[ # pyre-ignore: T41307149\n int, Set[Tuple[int, int]]\n ] = defaultdict(set)\n self._trace_frame_leaf_assoc: DefaultDict[ # pyre-ignore: T41307149\n int, Set[Tuple[int, int]]\n ] = defaultdict(set)\n\n self._postcondition_issue_instance_assoc: DefaultDict[ # pyre-ignore: T41307149\n int, Set[int]\n ] = defaultdict(set)\n self._issue_instance_postcondition_assoc: DefaultDict[ # pyre-ignore: T41307149\n int, Set[int]\n ] = defaultdict(set)\n self._precondition_issue_instance_assoc: DefaultDict[ # pyre-ignore: T41307149\n int, Set[int]\n ] = defaultdict(set)\n self._issue_instance_precondition_assoc: DefaultDict[ # pyre-ignore: T41307149\n int, Set[int]\n ] = defaultdict(set)\n self._trace_frame_issue_instance_assoc: DefaultDict[ # pyre-ignore: T41307149\n int, Set[int]\n ] = defaultdict(set)\n self._issue_instance_trace_frame_assoc: DefaultDict[ # pyre-ignore: T41307149\n int, Set[int]\n ] = defaultdict(set)\n\n self._issue_instance_shared_text_assoc: DefaultDict[ # pyre-ignore: T41307149\n int, Set[int]\n ] = defaultdict(set)\n self._shared_text_issue_instance_assoc: DefaultDict[ # pyre-ignore: T41307149\n int, Set[int]\n ] = defaultdict(set)\n\n self._issue_instance_fix_info: Dict[int, IssueInstanceFixInfo] = {}\n\n # !!!!! IMPORTANT !!!!!\n # IF YOU ARE ADDING MORE FIELDS/EDGES TO THIS GRAPH, CHECK IF\n # TrimmedTraceGraph NEEDS TO BE UPDATED AS WELL.\n #\n # TrimmedTraceGraph will populate itself from this object. It searches\n # TrimmedGraph for nodes and edges of 'affected_files' and copies them\n # over. If new fields/edges are added, these may need to be copied in\n # TrimmedTraceGraph as well.\n\n def add_issue(self, issue: Issue) -> None:\n assert issue.id.local_id not in self._issues, \"Issue already exists\"\n self._issues[issue.id.local_id] = issue\n\n def get_issue(self, issue_id: DBID) -> Issue:\n return self._issues[issue_id.local_id]\n\n def add_issue_instance(self, instance: IssueInstance) -> None:\n assert (\n instance.id.local_id not in self._issue_instances\n ), \"Instance already exists\"\n self._issue_instances[instance.id.local_id] = instance\n\n def get_issue_instances(self) -> Iterable[IssueInstance]:\n return (instance for instance in self._issue_instances.values())\n\n def add_issue_instance_fix_info(\n self, instance: IssueInstance, fix_info: IssueInstanceFixInfo\n ) -> None:\n assert (\n instance.id.local_id not in self._issue_instance_fix_info\n ), \"Instance fix info already exists\"\n self._issue_instance_fix_info[instance.id.local_id] = fix_info\n\n def get_shared_text(\n self, kind: SharedTextKind, content: str\n ) -> Optional[SharedText]:\n if kind in self._shared_text_lookup:\n contents = self._shared_text_lookup[kind]\n if content in contents and contents[content] in self._shared_texts:\n return self._shared_texts[contents[content]]\n return None\n\n def add_trace_annotation(self, annotation: TraceFrameAnnotation) -> None:\n self._trace_annotations[annotation.id.local_id] = annotation\n\n def get_precondition_annotations(self, pre_id: int) -> List[TraceFrameAnnotation]:\n return [\n t\n for t in self._trace_annotations.values()\n if t.trace_frame_id.local_id == pre_id\n ]\n\n def add_postcondition(self, post: Postcondition) -> None:\n key = (post.caller, post.caller_condition)\n rev_key = (post.callee, post.callee_condition)\n self._postconditions_map[key].add(post.id.local_id)\n self._postconditions_rev_map[rev_key].add(post.id.local_id)\n self._postconditions[post.id.local_id] = post\n\n def has_postconditions_with_caller(self, caller: str, caller_port: str) -> bool:\n key = (caller, caller_port)\n return key in self._postconditions_map\n\n def get_postconditions_from_caller(\n self, caller: str, caller_port: str\n ) -> List[Postcondition]:\n if self.has_postconditions_with_caller(caller, caller_port):\n key = (caller, caller_port)\n return [\n self._postconditions[post_id]\n for post_id in self._postconditions_map[key]\n ]\n else:\n return []\n\n def get_postcondition_from_id(self, id: int) -> Postcondition:\n return self._postconditions[id]\n\n def add_precondition(self, pre: Precondition) -> None:\n key = (pre.caller, pre.caller_condition)\n rev_key = (pre.callee, pre.callee_condition)\n self._preconditions_map[key].add(pre.id.local_id)\n self._preconditions_rev_map[rev_key].add(pre.id.local_id)\n self._preconditions[pre.id.local_id] = pre\n\n def has_precondition_with_caller(self, caller: str, caller_port: str) -> bool:\n key = (caller, caller_port)\n return key in self._preconditions_map\n\n def get_preconditions_from_caller(\n self, caller: str, caller_port: str\n ) -> List[Precondition]:\n if self.has_precondition_with_caller(caller, caller_port):\n key = (caller, caller_port)\n return [\n self._preconditions[pre_id] for pre_id in self._preconditions_map[key]\n ]\n else:\n return []\n\n def get_precondition_from_id(self, id: int) -> Precondition:\n return self._preconditions[id]\n\n def add_trace_frame(self, trace_frame: TraceFrame) -> None:\n key = (trace_frame.caller, trace_frame.caller_port)\n rev_key = (trace_frame.callee, trace_frame.callee_port)\n self._trace_frames_map[key].add(trace_frame.id.local_id)\n self._trace_frames_rev_map[rev_key].add(trace_frame.id.local_id)\n self._trace_frames[trace_frame.id.local_id] = trace_frame\n\n def has_trace_frame_with_caller(self, caller: str, caller_port: str) -> bool:\n key = (caller, caller_port)\n return key in self._trace_frames_map\n\n def get_trace_frames_from_caller(\n self, caller: str, caller_port: str\n ) -> List[TraceFrame]:\n if self.has_trace_frame_with_caller(caller, caller_port):\n key = (caller, caller_port)\n return [\n self._trace_frames[trace_frame_id]\n for trace_frame_id in self._trace_frames_map[key]\n ]\n else:\n return []\n\n def get_trace_frame_from_id(self, id: int) -> TraceFrame:\n return self._trace_frames[id]\n\n def add_trace_frame_to_precondition(\n self, trace_frame: TraceFrame, precondition: Precondition\n ) -> None:\n self._trace_frame_to_precondition[trace_frame.id.local_id] = precondition\n self._precondition_to_trace_frame[precondition.id.local_id] = trace_frame\n\n def add_trace_frame_to_postcondition(\n self, trace_frame: TraceFrame, postcondition: Postcondition\n ) -> None:\n self._trace_frame_to_postcondition[trace_frame.id.local_id] = postcondition\n self._postcondition_to_trace_frame[postcondition.id.local_id] = trace_frame\n\n def add_shared_text(self, shared_text: SharedText) -> None:\n assert (\n shared_text.id.local_id not in self._shared_texts\n ), \"Shared text already exists\"\n\n # Remove this block when we finally remove sources/sinks table\n # (T30720232). For now, the corresponding source/sink entries\n # still need to be present.\n if shared_text.kind == SharedTextKind.SOURCE:\n # New source added, make sure we keep track of it\n source_rec = Source.Record(id=DBID(), name=shared_text.contents)\n self._sources[source_rec.id.local_id] = source_rec\n self._shared_text_to_source[shared_text.id.local_id] = source_rec\n elif shared_text.kind == SharedTextKind.SINK:\n # New sink added, make sure we keep track of it\n sink_rec = Sink.Record(id=DBID(), name=shared_text.contents)\n self._sinks[sink_rec.id.local_id] = sink_rec\n self._shared_text_to_sink[shared_text.id.local_id] = sink_rec\n\n self._shared_texts[shared_text.id.local_id] = shared_text\n\n # Allow look up of SharedTexts by name and kind (to optimize\n # get_shared_text which is called when parsing each issue instance)\n self._shared_text_lookup[shared_text.kind][\n shared_text.contents\n ] = shared_text.id.local_id\n\n def add_issue_instance_sink_assoc(\n self, instance: IssueInstance, sink: SharedText\n ) -> None:\n assert sink.kind == SharedTextKind.SINK\n self.add_issue_instance_shared_text_assoc(instance, sink)\n\n def add_issue_instance_source_assoc(\n self, instance: IssueInstance, source: SharedText\n ) -> None:\n assert source.kind == SharedTextKind.SOURCE\n self.add_issue_instance_shared_text_assoc(instance, source)\n\n def add_postcondition_source_assoc(\n self, postcondition: Postcondition, source: SharedText, depth: int\n ) -> None:\n # T30720232: Replace with trace_frame_leaf_assoc\n source_rec = self._shared_text_to_source[source.id.local_id]\n self._postcondition_source_assoc[postcondition.id.local_id].add(\n (source_rec.id.local_id, depth)\n )\n\n def get_postcondition_source_ids(self, postcondition: Postcondition) -> Set[int]:\n ids: Set[int] = {\n id\n for (id, _depth) in self._postcondition_source_assoc[\n postcondition.id.local_id\n ]\n }\n return ids\n\n def add_precondition_sink_assoc(\n self, precondition: Precondition, sink: SharedText, depth: int\n ) -> None:\n # T30720232: Replace with trace_frame_leaf_assoc\n sink_rec = self._shared_text_to_sink[sink.id.local_id]\n self._precondition_sink_assoc[precondition.id.local_id].add(\n (sink_rec.id.local_id, depth)\n )\n\n def get_precondition_sink_ids(self, precondition: Precondition) -> Set[int]:\n ids: Set[int] = {\n id\n for (id, _depth) in self._precondition_sink_assoc[precondition.id.local_id]\n }\n return ids\n\n def add_trace_frame_leaf_assoc(\n self, trace_frame: TraceFrame, leaf: SharedText, depth: int\n ) -> None:\n self._trace_frame_leaf_assoc[trace_frame.id.local_id].add(\n (leaf.id.local_id, depth)\n )\n\n def get_trace_frame_leaf_ids(self, trace_frame: TraceFrame) -> Set[int]:\n ids: Set[int] = {\n id for (id, depth) in self._trace_frame_leaf_assoc[trace_frame.id.local_id]\n }\n return ids\n\n def add_issue_instance_postcondition_assoc(\n self, instance: IssueInstance, post: Postcondition\n ) -> None:\n self._issue_instance_postcondition_assoc[instance.id.local_id].add(\n post.id.local_id\n )\n self._postcondition_issue_instance_assoc[post.id.local_id].add(\n instance.id.local_id\n )\n\n def get_issue_instance_postconditions(\n self, instance: IssueInstance\n ) -> List[Postcondition]:\n if instance.id.local_id in self._issue_instance_postcondition_assoc:\n return [\n self.get_postcondition_from_id(id)\n for id in self._issue_instance_postcondition_assoc[instance.id.local_id]\n ]\n else:\n return []\n\n def add_issue_instance_precondition_assoc(\n self, instance: IssueInstance, pre: Precondition\n ) -> None:\n self._issue_instance_precondition_assoc[instance.id.local_id].add(\n pre.id.local_id\n )\n self._precondition_issue_instance_assoc[pre.id.local_id].add(\n instance.id.local_id\n )\n\n def get_issue_instance_preconditions(\n self, instance: IssueInstance\n ) -> List[Precondition]:\n if instance.id.local_id in self._issue_instance_precondition_assoc:\n return [\n self.get_precondition_from_id(id)\n for id in self._issue_instance_precondition_assoc[instance.id.local_id]\n ]\n else:\n return []\n\n def add_issue_instance_trace_frame_assoc(\n self, instance: IssueInstance, trace_frame: TraceFrame\n ) -> None:\n self._issue_instance_trace_frame_assoc[instance.id.local_id].add(\n trace_frame.id.local_id\n )\n self._trace_frame_issue_instance_assoc[trace_frame.id.local_id].add(\n instance.id.local_id\n )\n\n def get_issue_instance_trace_frames(\n self, instance: IssueInstance\n ) -> List[TraceFrame]:\n if instance.id.local_id in self._issue_instance_trace_frame_assoc:\n return [\n self.get_trace_frame_from_id(id)\n for id in self._issue_instance_trace_frame_assoc[instance.id.local_id]\n ]\n else:\n return []\n\n def add_issue_instance_shared_text_assoc(\n self, instance: IssueInstance, shared_text: SharedText\n ) -> None:\n self._issue_instance_shared_text_assoc[instance.id.local_id].add(\n shared_text.id.local_id\n )\n self._shared_text_issue_instance_assoc[shared_text.id.local_id].add(\n instance.id.local_id\n )\n\n def get_issue_instance_shared_texts(\n self, instance_id: int, kind: SharedTextKind\n ) -> List[SharedText]:\n return [\n self._shared_texts[msg_id]\n for msg_id in self._issue_instance_shared_text_assoc[instance_id]\n if self._shared_texts[msg_id].kind == kind\n ]\n\n def update_bulk_saver(self, bulk_saver: BulkSaver) -> None:\n bulk_saver.add_all(list(self._issues.values()))\n bulk_saver.add_all(list(self._issue_instances.values()))\n bulk_saver.add_all(list(self._preconditions.values()))\n bulk_saver.add_all(list(self._postconditions.values()))\n bulk_saver.add_all(list(self._trace_frames.values()))\n bulk_saver.add_all(list(self._sources.values()))\n bulk_saver.add_all(list(self._sinks.values()))\n bulk_saver.add_all(list(self._issue_instance_fix_info.values()))\n bulk_saver.add_all(list(self._trace_annotations.values()))\n bulk_saver.add_all(list(self._shared_texts.values()))\n\n self._save_issue_instance_postcondition_assoc(bulk_saver)\n self._save_issue_instance_precondition_assoc(bulk_saver)\n self._save_issue_instance_trace_frame_assoc(bulk_saver)\n self._save_precondition_sink_assoc(bulk_saver)\n self._save_postcondition_source_assoc(bulk_saver)\n self._save_trace_frame_leaf_assoc(bulk_saver)\n self._save_issue_instance_shared_text_assoc(bulk_saver)\n\n def _save_issue_instance_postcondition_assoc(self, bulk_saver: BulkSaver) -> None:\n for post_id, instance_ids in self._postcondition_issue_instance_assoc.items():\n for instance_id in instance_ids:\n bulk_saver.add_issue_instance_postcondition_assoc(\n self._issue_instances[instance_id], self._postconditions[post_id]\n )\n\n def _save_issue_instance_precondition_assoc(self, bulk_saver: BulkSaver) -> None:\n for pre_id, instance_ids in self._precondition_issue_instance_assoc.items():\n for instance_id in instance_ids:\n bulk_saver.add_issue_instance_precondition_assoc(\n self._issue_instances[instance_id], self._preconditions[pre_id]\n )\n\n def _save_issue_instance_trace_frame_assoc(self, bulk_saver: BulkSaver) -> None:\n for (\n trace_frame_id,\n instance_ids,\n ) in self._trace_frame_issue_instance_assoc.items():\n for instance_id in instance_ids:\n bulk_saver.add_issue_instance_trace_frame_assoc(\n self._issue_instances[instance_id],\n self._trace_frames[trace_frame_id],\n )\n\n def _save_precondition_sink_assoc(self, bulk_saver: BulkSaver) -> None:\n for pre_id, sink_ids in self._precondition_sink_assoc.items():\n for (sink_id, depth) in sink_ids:\n bulk_saver.add_precondition_sink_assoc(\n self._sinks[sink_id], self._preconditions[pre_id], depth\n )\n\n def _save_postcondition_source_assoc(self, bulk_saver: BulkSaver) -> None:\n for post_id, source_ids in self._postcondition_source_assoc.items():\n for (source_id, depth) in source_ids:\n bulk_saver.add_postcondition_source_assoc(\n self._sources[source_id], self._postconditions[post_id], depth\n )\n\n def _save_trace_frame_leaf_assoc(self, bulk_saver: BulkSaver) -> None:\n for trace_frame_id, leaf_ids in self._trace_frame_leaf_assoc.items():\n for (leaf_id, depth) in leaf_ids:\n bulk_saver.add_trace_frame_leaf_assoc(\n self._shared_texts[leaf_id],\n self._trace_frames[trace_frame_id],\n depth,\n )\n\n def _save_issue_instance_shared_text_assoc(self, bulk_saver: BulkSaver) -> None:\n for (\n shared_text_id,\n instance_ids,\n ) in self._shared_text_issue_instance_assoc.items():\n for instance_id in instance_ids:\n bulk_saver.add_issue_instance_shared_text_assoc(\n self._issue_instances[instance_id],\n self._shared_texts[shared_text_id],\n )\n","sub_path":"sapp/sapp/trace_graph.py","file_name":"trace_graph.py","file_ext":"py","file_size_in_byte":21088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"618897410","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# Libraries\n\nimport random\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport time\nfrom sklearn.model_selection import train_test_split\nfrom scipy.optimize import minimize\nimport operator\nimport itertools\nfrom scipy.interpolate import griddata\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import axes3d\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom sklearn.cluster import KMeans\nfrom sklearn import preprocessing \n\n\n# In[2]:\n\n\n# Directories\n\nd = pd.read_csv(open(\"DATA.csv\",\"r\"))\n\n\n# In[3]:\n\n\n# Transform columns of data frame in array\n\nX = d.iloc[:,0:2].values\ny = d.iloc[:,2].values\n\n\n# ## Functions\n\n# In[4]:\n\n\n# Create train (75% of data) and test (25% of data) using \"Matricola\" as seed\n\nx_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=1656079)\n\n\n# In[5]:\n\n\ndef x_c(x,c,N):\n n = len(x)\n nd = len(x.T)\n \n c = np.array(c)\n c = c.reshape(N,nd,1)\n \n x = x.reshape(n,nd,1)\n \n return x-c.T\n\n\n# In[6]:\n\n\ndef gaussian(xc,sigma):\n \n return np.exp(-(np.linalg.norm(xc, axis = 1)/sigma) ** 2)\n\n\n# In[7]:\n\n\n# Define the RBF network\n## wants the argouments: \n### c, w (the parameters of the network)\n### N: # of neurons in the hidden layer\n### sigma: variance used in the gaussian function\n### x: input data\n\ndef y_x(v, c, sigma, x, N):\n y=np.dot(gaussian(x_c(x,c,N),sigma),v)\n \n return y \n\n\n# In[8]:\n\n\n# Define the error function to be optimized\n\ndef error_v(pars, args,params = 1):\n \n N = args[0]\n x = args[1]\n y = args[2]\n rho = args[3]\n sigma = args[4]\n c = args[5]\n P = len(x)\n \n v = pars\n \n # predict the y\n y_rbf = y_x(v, c, sigma, x, N)\n \n \n # compute the error\n if params == 0:\n return (1/(2*P))*(np.linalg.norm(y_rbf - y))**2\n if params ==1:\n return (1/(2*P))*(np.linalg.norm(y_rbf - y))**2 + (rho*(np.linalg.norm(v))**2)\n\n\n# In[9]:\n\n\n# Define the error function refer to c to be optimized\n\ndef error_c(pars, args,params = 1):\n \n N = args[0]\n x = args[1]\n y = args[2]\n rho = args[3]\n sigma = args[4]\n v = args[5]\n P = len(x)\n \n c = pars\n \n # predict the y\n y_rbf = y_x(v, c, sigma, x, N)\n \n \n # compute the error\n if params == 0:\n return (1/(2*P))*(np.linalg.norm(y_rbf - y))**2\n if params ==1:\n return (1/(2*P))*(np.linalg.norm(y_rbf - y))**2 + (rho*(np.linalg.norm(c))**2)\n\n\n# In[10]:\n\n\n#Gradient_c\n\ndef grad_wrt_c(pars, args):\n \n N = args[0]\n x = args[1]\n y = args[2]\n rho = args[3]\n sigma = args[4]\n v = args[5]\n \n c = pars[0:2*N]\n\n n=len(x)\n v=np.array(v)\n c=np.array(c)\n\n c = c.reshape(N, 2)\n x_reshaped = np.array(x).reshape(n, 1, 2)\n\n g = gaussian(x_c(x, c, N), sigma)[:, :, np.newaxis]\n arg_g = x_reshaped - c\n arg_g = g * arg_g * (2/sigma**2)\n \n vv = v.reshape(1, N, 1)\n rest = y_x(v, c, sigma, x, N) - y\n d_c = rest[:, np.newaxis, np.newaxis] * arg_g\n d_c = d_c * vv\n d_c = np.mean(d_c, axis = 0) + 2 * rho * c\n \n return d_c.reshape((N * 2, ))\n\n\n# In[11]:\n\n\n# Gradient_v\n\ndef grad_wrt_v(pars, args):\n \n N = args[0]\n x = args[1]\n y = args[2]\n rho = args[3]\n sigma = args[4]\n c = args [5]\n \n v = pars\n \n n=len(x)\n v=np.array(v)\n c=np.array(c)\n\n \n res = np.dot(gaussian(x_c(x,c,N),sigma),v)[:, np.newaxis] - y.reshape(n, 1)\n d_v = (np.dot(gaussian(x_c(x,c,N).T, sigma), res))/n\n d_v = d_v + 2 * rho * v.reshape(N,1)\n \n return d_v[:, 0]\n\n\n# In[12]:\n\n\n# Function to find the best parameters with fixed rho\n\ndef decomposition (x_train,y_train,x_test,y_test,N=50,rho=0.00001,error=0.001,stop=None, sigma=1):\n ''' x_train = x_train set\n y_train = y_train set\n x_test = x_test set\n y_test = y_test set\n N = numbers of hidden layers, def=50\n rho = initial rho values, def=0.00001 (min rho)\n error= target error, def = 0.001\n stop= early stopping, def = None\n sigma= sigma values, def=1\n '''\n \n \n random.seed(1656079)\n \n #set the initial parameters\n \n v_init = [random.uniform(0, 1) for i in range(N)]\n kmeans=KMeans(n_clusters=N, random_state=1656079)\n a=kmeans.fit(x_train)\n c_init=a.cluster_centers_\n c_init = list(itertools.chain(*c_init))\n \n \n # calculate the initial training error\n params = (v_init)\n err_args = [N, x_train, y_train, rho, sigma, c_init]\n \n ini_training_erro = error_v(v_init, err_args, 0)\n error_check = ini_training_erro\n \n #create the dictionary for results\n results = {}\n nfev = 0\n contatore = 0 #Number of outer iterations\n \n \n start_time = time.time()\n \n \n while error_check > error:\n \n #optimaze just v\n \n params = (v_init)\n err_args = [N, x_train, y_train, rho, sigma,c_init]\n res = minimize(error_v, params, args=err_args, method='BFGS', jac=grad_wrt_v)\n grad = np.linalg.norm(res[\"jac\"])\n nfev += res[\"nfev\"]\n \n v_init = res.x.tolist()\n contatore +=1\n \n params = (v_init) #upload for right values in test error\n err_args = [N, x_test, y_test, rho, sigma, c_init]\n \n error_check = res['fun']\n \n \n \n \n if error_check < error:\n break\n \n if stop != None:\n if contatore == stop:\n print(\"Early Stopping after %s iterations \" %(contatore))\n break\n \n \n #optimaze c\n \n params = (c_init)\n err_args = [N, x_train, y_train, rho , sigma, v_init]\n res = minimize(error_c, params, args=err_args, method='BFGS',jac=grad_wrt_c)\n grad = np.linalg.norm(res[\"jac\"])\n nfev += res[\"nfev\"]\n \n c_init = res.x.tolist()\n contatore +=1\n \n params = (c_init)\n err_args = [N, x_test, y_test, rho , sigma, v_init]\n \n error_check = res['fun']\n \n if stop != None:\n if contatore == stop:\n print(\"Early Stopping after %s iterations \" %(contatore))\n break\n \n \n \n end_time = time.time()\n tempo=(end_time - start_time)\n \n try:\n test_error = error_v(params, err_args, 0)\n except:\n test_error = error_c(params, err_args, 0)\n \n results[N, rho, sigma] = {'v': v_init, 'c': c_init, 'Train Error': res['fun'], 'Test Error': test_error,\n \"Gradient\": grad}\n \n \n return (N,ini_training_erro,rho,results,tempo,nfev,test_error,contatore,sigma)\n\n\n# In[13]:\n\n\nresults=decomposition(x_train,y_train,x_test,y_test,stop=115,N=50)\n\n\n# In[14]:\n\n\nprint(\"Number of Neurons N:... %s\" %(results[0]))\nprint(\"Initial Training Error:... %s\" %(results[1]))\nprint(\"Final Training Error:... %s\" %(results[3][(results[0],results[2],results[8])][\"Train Error\"]))\nprint(\"Final Test Error:... %s\" %(results[6]))\nprint(\"Optimization solver chosen:... BFGS\")\nprint(\"Norm of the gradient at the optimal point:... %s\" %(results[3][(results[0],results[2],results[8])][\"Gradient\"]))\nprint(\"Total Time for optimizing the network:... %s seconds\" %(results[4]))\nprint(\"Number of function evaluations:... %s\" %(results[5]))\nprint(\"Value of sigma:... %s\" %(results[8]))\nprint(\"Value of rho:... %s\" %(results[2]))\nprint(\"Other hyperparameters:... \\n Number of outer iterations: %s\" %(results[7]))\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Point 3.py","file_name":"Point 3.py","file_ext":"py","file_size_in_byte":7555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"171140881","text":"import cv2\nimport numpy as np\n\nprint(\"OpenCV Imported\")\ncap = cv2.VideoCapture(\"Resources/test.mp4\") # make (0) to use webcam\nprint(\"Video Assigned\")\nret, frame1 = cap.read() # Frame 1\nret, frame2 = cap.read() # Frame 2\n\nwhile cap.isOpened():\n diff = cv2.absdiff(frame1, frame2)\n gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray, (5, 5), 0)\n _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)\n dilated = cv2.dilate(thresh, None, iterations=3)\n contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n # Get Rid of noise (if you want all the noise comment out for loop and uncomment .drawContours)\n for contour in contours:\n (x, y, w, h) = cv2.boundingRect(contour)\n if cv2.contourArea(contour) < 900:\n continue\n cv2.rectangle(frame1, (x, y), (x + w, y + h), (0, 255, 0), 2)\n cv2.putText(frame1, \"Status: {}\".format('Movement'), (20, 30), cv2.FONT_ITALIC,\n .9\n , (0, 0, 255), 3)\n # cv2.drawContours(frame1, contours, -1, (0, 255, 0), 2)\n\n cv2.imshow(\"motion detection\", frame1)\n frame1 = frame2\n ret, frame2 = cap.read()\n\n if cv2.waitKey(30) == 27: # Exit is escape button\n break\ncv2.destroyAllWindows()\ncap.release()\nexit()\n","sub_path":"motiondetection.py","file_name":"motiondetection.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"217446298","text":"import itertools\nimport geoalchemy2.shape\n\nfrom pyramid.view import view_config\nfrom pyramid.httpexceptions import HTTPBadRequest\n\nfrom sqlalchemy.orm import aliased\nfrom sqlalchemy import and_\n\nfrom geoalchemy2.shape import to_shape\n\nfrom ..models import (\n DBSession,\n AdminLevelType,\n AdministrativeDivision,\n CategoryType,\n HazardCategory,\n HazardType)\n\n\n# An object for the \"no data\" category type.\n_categorytype_nodata = CategoryType()\n_categorytype_nodata.mnemonic = 'no-data'\n_categorytype_nodata.title = 'No data available'\n_categorytype_nodata.description = 'No data for this hazard type.'\n_categorytype_nodata.order = float('inf')\n\n\n@view_config(route_name='report_overview', renderer='templates/report.jinja2')\n@view_config(route_name='report_overview_slash',\n renderer='templates/report.jinja2')\n@view_config(route_name='report', renderer='templates/report.jinja2')\ndef report(request):\n try:\n division_code = request.matchdict.get('divisioncode')\n except:\n raise HTTPBadRequest(detail='incorrect value for parameter '\n '\"divisioncode\"')\n\n hazard = request.matchdict.get('hazardtype', None)\n\n # Query 1: get the administrative division whose code is division_code.\n _alias = aliased(AdministrativeDivision)\n division = DBSession.query(AdministrativeDivision) \\\n .outerjoin(_alias, _alias.code == AdministrativeDivision.parent_code) \\\n .filter(AdministrativeDivision.code == division_code).one()\n\n # Query 2: get all the hazard types.\n hazardtype_query = DBSession.query(HazardType)\n\n # Create a dict containing the data sent to the report template. The keys\n # are the hazard type mnemonics.\n hazard_data = {hazardtype.mnemonic: {'hazardtype': hazardtype,\n 'categorytype': _categorytype_nodata,\n 'description': None,\n 'recommendation_associations': None,\n 'additionalinfo_associations': None}\n for hazardtype in hazardtype_query}\n\n # Query 3: get the hazard categories corresponding to the administrative\n # division whose code is division_code.\n hazardcategories = DBSession.query(HazardCategory) \\\n .join(HazardCategory.administrativedivisions) \\\n .join(HazardType) \\\n .join(CategoryType) \\\n .filter(AdministrativeDivision.code == division_code)\n\n # Udpate the data (hazard_data).\n for hazardcategory in hazardcategories:\n key = hazardcategory.hazardtype.mnemonic\n hazard_data[key]['categorytype'] = hazardcategory.categorytype\n hazard_data[key]['description'] = hazardcategory.description\n hazard_data[key]['recommendation_associations'] = \\\n hazardcategory.recommendation_associations\n hazard_data[key]['additionalinfo_associations'] = \\\n hazardcategory.additionalinformation_associations\n\n if hazard is not None:\n hazard = hazard_data[hazard]\n # Order the hazard data by category type (hazard types with the highest\n # risk are first in the UI).\n hazard_data = hazard_data.values()\n hazard_data = sorted(hazard_data, key=lambda d: d['categorytype'].order)\n\n # Get the geometry for division and compute its extent\n division_shape = geoalchemy2.shape.to_shape(division.geom)\n division_bounds = list(division_shape.bounds)\n\n parents = []\n if division.leveltype_id >= 2:\n parents.append(division.parent)\n if division.leveltype_id == 3:\n parents.append(division.parent.parent)\n\n return {'hazards': hazard_data,\n 'current_hazard': hazard,\n 'division': division,\n 'bounds': division_bounds,\n 'parents': parents,\n 'parent_division': division.parent}\n\n\n@view_config(route_name='report_json', renderer='geojson')\n@view_config(route_name='report_overview_json', renderer='geojson')\ndef report_json(request):\n\n try:\n division_code = request.matchdict.get('divisioncode')\n except:\n raise HTTPBadRequest(detail='incorrect value for parameter '\n '\"divisioncode\"')\n\n hazard_type = request.matchdict.get('hazardtype', None)\n\n division_leveltype, = DBSession.query(AdminLevelType.mnemonic) \\\n .join(AdministrativeDivision.leveltype) \\\n .filter(AdministrativeDivision.code == division_code).one()\n\n _filter = None\n if division_leveltype == u'REG':\n _filter = AdministrativeDivision.code == division_code\n else:\n _filter = AdministrativeDivision.parent_code == division_code\n\n if hazard_type is not None:\n subdivisions = DBSession.query(AdministrativeDivision) \\\n .add_columns(CategoryType.mnemonic) \\\n .outerjoin(AdministrativeDivision.hazardcategories) \\\n .outerjoin(HazardType)\\\n .outerjoin(CategoryType) \\\n .filter(and_(_filter, HazardType.mnemonic == hazard_type))\n else:\n subdivisions = itertools.izip(\n DBSession.query(AdministrativeDivision).filter(_filter),\n itertools.cycle(('NONE',)))\n\n return [{\n 'type': 'Feature',\n 'geometry': to_shape(subdivision.geom),\n 'properties': {\n 'name': subdivision.name,\n 'code': subdivision.code,\n 'hazardLevel': categorytype\n }\n } for subdivision, categorytype in subdivisions]\n","sub_path":"thinkhazard/views/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":5506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"291676139","text":"# -*- coding: utf-8 -*-\r\n\r\n# Copyright 2011 Fanficdownloader team\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n#\r\n\r\nimport logging\r\nimport string\r\n\r\nfrom base_writer import *\r\n\r\nclass HTMLWriter(BaseStoryWriter):\r\n\r\n @staticmethod\r\n def getFormatName():\r\n return 'html'\r\n\r\n @staticmethod\r\n def getFormatExt():\r\n return '.html'\r\n\r\n def __init__(self, config, story):\r\n BaseStoryWriter.__init__(self, config, story)\r\n \r\n self.HTML_FILE_START = string.Template('''\r\n\r\n\r\n\r\n${title} by ${author}\r\n\r\n\r\n\r\n

${title} by ${authorHTML}

\r\n''')\r\n\r\n self.HTML_COVER = string.Template('''\r\n\"cover\"\r\n''')\r\n \r\n self.HTML_TITLE_PAGE_START = string.Template('''\r\n\r\n''')\r\n\r\n self.HTML_TITLE_ENTRY = string.Template('''\r\n\r\n''')\r\n\r\n self.HTML_TITLE_PAGE_END = string.Template('''\r\n
${label}:${value}
\r\n''')\r\n\r\n self.HTML_TOC_PAGE_START = string.Template('''\r\n

Table of Contents

\r\n

\r\n''')\r\n\r\n self.HTML_TOC_ENTRY = string.Template('''\r\n${chapter}
\r\n''')\r\n \r\n self.HTML_TOC_PAGE_END = string.Template('''\r\n

\r\n''')\r\n\r\n self.HTML_CHAPTER_START = string.Template('''\r\n

${chapter}

\r\n''')\r\n\r\n self.HTML_CHAPTER_END = string.Template('')\r\n\r\n self.HTML_FILE_END = string.Template('''\r\n\r\n''')\r\n\r\n\r\n def writeStoryImpl(self, out):\r\n\r\n if self.hasConfig(\"cover_content\"):\r\n COVER = string.Template(self.getConfig(\"cover_content\"))\r\n else:\r\n COVER = self.HTML_COVER\r\n\r\n if self.hasConfig('file_start'):\r\n FILE_START = string.Template(self.getConfig(\"file_start\"))\r\n else:\r\n FILE_START = self.HTML_FILE_START\r\n\r\n if self.hasConfig('file_end'):\r\n FILE_END = string.Template(self.getConfig(\"file_end\"))\r\n else:\r\n FILE_END = self.HTML_FILE_END\r\n \r\n self._write(out,FILE_START.substitute(self.story.getAllMetadata()))\r\n\r\n if self.getConfig('include_images') and self.story.cover:\r\n self._write(out,COVER.substitute(dict(self.story.getAllMetadata().items()+{'coverimg':self.story.cover}.items())))\r\n \r\n self.writeTitlePage(out,\r\n self.HTML_TITLE_PAGE_START,\r\n self.HTML_TITLE_ENTRY,\r\n self.HTML_TITLE_PAGE_END)\r\n\r\n self.writeTOCPage(out,\r\n self.HTML_TOC_PAGE_START,\r\n self.HTML_TOC_ENTRY,\r\n self.HTML_TOC_PAGE_END)\r\n\r\n if self.hasConfig('chapter_start'):\r\n CHAPTER_START = string.Template(self.getConfig(\"chapter_start\"))\r\n else:\r\n CHAPTER_START = self.HTML_CHAPTER_START\r\n \r\n if self.hasConfig('chapter_end'):\r\n CHAPTER_END = string.Template(self.getConfig(\"chapter_end\"))\r\n else:\r\n CHAPTER_END = self.HTML_CHAPTER_END\r\n \r\n for index, (url,title,html) in enumerate(self.story.getChapters()):\r\n if html:\r\n logging.debug('Writing chapter text for: %s' % title)\r\n vals={'url':url, 'chapter':title, 'index':\"%04d\"%(index+1), 'number':index+1}\r\n self._write(out,CHAPTER_START.substitute(vals))\r\n self._write(out,html)\r\n self._write(out,CHAPTER_END.substitute(vals))\r\n\r\n self._write(out,FILE_END.substitute(self.story.getAllMetadata()))\r\n\r\n if self.getConfig('include_images'):\r\n for imgmap in self.story.getImgUrls():\r\n self.writeFile(imgmap['newsrc'],imgmap['data'])\r\n \r\n","sub_path":"fanficdownloader/writers/writer_html.py","file_name":"writer_html.py","file_ext":"py","file_size_in_byte":4642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"152473950","text":"l,r = map(int, input().split())\nif l//2019 != r//2019:\n print(0)\n exit(0)\nl = l%2019\nr = r%2019\na = 2019\nfor i in range(l,r+1):\n for j in range(l,i):\n a = min(a,(i*j)%2019)\nprint(a)\n","sub_path":"Python_codes/p02983/s336181986.py","file_name":"s336181986.py","file_ext":"py","file_size_in_byte":188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"51874092","text":"#import nltk\n#nltk.download('wordnet_ic')\n\n#nltk.download('averaged_perceptron_tagger')\n#nltk.download('punkt')\nfrom nltk.corpus import wordnet as wn\nfrom nltk.corpus import wordnet_ic\nfrom nltk import word_tokenize, pos_tag\nfrom text_similarity.tfidf import TFIDF\nfrom functools import reduce\nimport spacy\nimport numpy as np\n\nbrown_ic = wordnet_ic.ic('ic-brown.dat') #load the brown corpus to compute the IC\n\nclass WordNetSimilarity:\n \"\"\"\"\"\"\n\n def __init__(self, intents, focus_sent):\n self.nlp = spacy.load('en_core_web_sm')\n self.compute_idf(intents, focus_sent)\n self.intents = intents\n self.focus_sent = focus_sent\n\n def compute_idf(self, intents, focus_sent):\n t = TFIDF(intents)\n t.compute_similarity(focus_sent)\n self.idf = t.idf\n self.vocabulary = t.vocabulary\n\n\n def tag_to_wn(self, tag):\n \"\"\" Convert between a Penn Treebank tag to a simplified Wordnet tag \"\"\"\n if tag.startswith('N'):\n return 'n'\n\n if tag.startswith('V'):\n return 'v'\n\n if tag.startswith('J'):\n return 'a'\n\n if tag.startswith('R'):\n return 'r'\n\n return None\n\n def tagged_to_synset(self, word, tag):\n \"\"\" Returns the first synset of the word given as parameter\"\"\"\n\n wn_tag = self.tag_to_wn(tag)\n if wn_tag is None:\n return None\n\n try:\n return wn.synsets(word, wn_tag)[0]\n except:\n return None\n\n def compute_sim(self, synsets1, synsets2):\n\n score, idf_sum = 0.0, 0\n\n # print(synsets2)\n # For each word in the first sentence\n for w,synset in synsets1:\n # Get the similarity value of the most similar word in the other sentence\n word_idf = self.idf[self.vocabulary[w]] if w in self.vocabulary else 1\n best_score = max([0 if synset.wup_similarity(ss[1]) is None else synset.wup_similarity(ss[1]) for ss in synsets2]) * word_idf\n\n score += best_score\n idf_sum += word_idf\n\n # Average the values\n score /= idf_sum\n return score\n\n def sentence_similarity(self, sentence1, sentence2):\n \"\"\" compute the sentence similarity using Wordnet \"\"\"\n\n if sentence1.lower() == sentence2.lower():\n return 2\n # Tokenize and tag\n sentence1 = pos_tag(word_tokenize(sentence1.lower()))\n sentence2 = pos_tag(word_tokenize(sentence2.lower()))\n\n\n\n # Get the synsets for the tagged words\n # Filter out the Nones\n synsets1 = reduce(lambda acc, w: acc if self.tagged_to_synset(*w) is None else acc + [(w[0], self.tagged_to_synset(*w))], sentence1, [])\n synsets2 = reduce(lambda acc, w: acc if self.tagged_to_synset(*w) is None else acc + [(w[0], self.tagged_to_synset(*w))], sentence2, [])\n\n return (self.compute_sim(synsets1, synsets2) + self.compute_sim(synsets2, synsets1)) / 2\n\n def compute_similarity(self):\n scores = []\n for intent in self.intents:\n scores.append(self.sentence_similarity(self.focus_sent, intent))\n sim_scores = np.array(scores)\n\n return self.intents[sim_scores.argmax()], sim_scores.max()\n","sub_path":"text_similarity/wordnet.py","file_name":"wordnet.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"217963230","text":"\n\nfrom xai.brain.wordbase.nouns._blackguard import _BLACKGUARD\n\n#calss header\nclass _BLACKGUARDS(_BLACKGUARD, ):\n\tdef __init__(self,): \n\t\t_BLACKGUARD.__init__(self)\n\t\tself.name = \"BLACKGUARDS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"blackguard\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_blackguards.py","file_name":"_blackguards.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"422504716","text":"import pytest\n\nfrom kolas.container import Container\nfrom kolas.endpoints import HttpEndpoint\nfrom kolas.exceptions import Http401, Http405\nfrom kolas.middleware import ErrorsMiddleware\nfrom kolas.responses import Response\nfrom kolas.templating import Renderer\nfrom starlette.testclient import TestClient\nfrom tests.conftest import create_renderer\n\n\nclass _View(HttpEndpoint):\n exception_to_status = {TypeError: 400, ValueError: 405}\n\n async def on_error_401(self, *args, **kwargs):\n return Response(b'401', status_code=401)\n\n async def on_error_405(self, *args, **kwargs):\n return Response(b'405', status_code=405)\n\n\ndef _app(app):\n async def inner(scope, receive, send):\n container = Container()\n container[Renderer] = create_renderer()\n scope['container'] = container\n await app(scope, receive, send)\n\n return inner\n\n\ndef test_raises_in_debug():\n \"\"\" In debug not handlers has to be called. \"\"\"\n\n async def app(scope, receive, send):\n raise RuntimeError('Internal Server Error')\n\n app = _app(ErrorsMiddleware(app, _View, True))\n with pytest.raises(RuntimeError):\n client = TestClient(app)\n client.get('/')\n\n\ndef test_calls_mapped_handler():\n \"\"\" Must map exception to http exception via `exception_to_status`. \"\"\"\n\n async def app(scope, receive, send):\n raise TypeError('Internal Server Error')\n\n app = _app(ErrorsMiddleware(app, _View, False))\n client = TestClient(app)\n response = client.get('/')\n assert response.status_code == 400\n\n\ndef test_calls_http_handler():\n \"\"\" Must call defined on_error_401 on Http401. \"\"\"\n\n async def app(scope, receive, send):\n raise Http401()\n\n app = _app(ErrorsMiddleware(app, _View, False))\n client = TestClient(app)\n response = client.get('/')\n assert response.status_code == 401\n assert response.content == b'401'\n\n\ndef test_calls_http_handler_via_mapped():\n \"\"\" Must call defined on_error_405\n which is mapped via exception_to_status. \"\"\"\n\n async def app(scope, receive, send):\n raise Http405()\n\n app = _app(ErrorsMiddleware(app, _View, False))\n client = TestClient(app)\n response = client.get('/')\n assert response.status_code == 405\n assert response.content == b'405'\n\n\ndef test_raises_if_not_http():\n \"\"\" Ignore non-http requests. \"\"\"\n\n async def app(scope, receive, send):\n raise RuntimeError('Internal Server Error')\n\n app = _app(ErrorsMiddleware(app, _View, False))\n with pytest.raises(RuntimeError):\n client = TestClient(app)\n client.websocket_connect('/')\n\n\ndef test_debug_after_response_sent():\n async def app(scope, receive, send):\n response = Response(b\"\", status_code=204)\n await response(scope, receive, send)\n raise RuntimeError(\"Something went wrong\")\n\n app = _app(ErrorsMiddleware(app, error_view=_View))\n client = TestClient(app)\n with pytest.raises(RuntimeError):\n client.get(\"/\")\n","sub_path":"kolas/tests/middleware/test_errors.py","file_name":"test_errors.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"131072802","text":"import collections\r\n\r\ntest=int(input())\r\n\r\nfor i in range(0,test):\r\n string=input()\r\n\r\n if(len(string)%2!=0):\r\n print('-1')\r\n else:\r\n string=list(string)\r\n s1=str(string[0:len(string)//2])\r\n s2=str(string[len(string)//2:len(string)])\r\n x=collections.Counter(s1)-collections.Counter(s2)\r\n print(sum(x.values()))","sub_path":"New folder/Anagram.py","file_name":"Anagram.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"184475916","text":"'''\n394. Decode String\n\nQuestion: Given an encoded string, return it's decoded string.\n\nThe encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. \nNote that k is guaranteed to be a positive integer.\ns = \"3[a]2[bc]\", return \"aaabcbc\".\ns = \"3[a2[c]]\", return \"accaccacc\".\ns = \"2[abc]3[cd]ef\", return \"abcabccdcdcdef\".\n\nSolution: Use stack\n\nCreated on May 12, 2019\n\n@author: smaiya\n'''\n\nclass Solution:\n def decodeString(self, s):\n \n num, pattern = '', ''\n num_stack, pattern_stack = [], []\n for c in s:\n if c.isdigit():\n num+=c\n if c.isalpha():\n pattern+=c\n if c=='[':\n num_stack.append(num)\n pattern_stack.append(pattern)\n num, pattern = '', ''\n if c==']':\n n = num_stack.pop()\n p = pattern_stack.pop()\n pattern = p+pattern*int(n)\n \n return pattern\n","sub_path":"LeetCode_python/src/stacks_and_queues/decodeString_M.py","file_name":"decodeString_M.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"651529572","text":"# from gsmSerialio import *\nimport configparser, os, re\nfrom datetime import datetime as dt, timedelta as td\nimport time, sys, memcache\nimport powermon as pmon\nimport gsmio\nimport common\nimport argparse\nimport raindetect as rd\nimport xbeegate as xb\nimport dbio\n\ndef main():\n parser = argparse.ArgumentParser(description = \"Health routine [-options]\")\n parser.add_argument(\"-r\", \"--read_only\", \n help = \"do not save data to memory\", action = 'store_true')\n\n try:\n args = parser.parse_args()\n except IndexError:\n print('>> Error in parsing arguments')\n error = parser.format_help()\n print(error)\n sys.exit()\n\n mc = common.get_mc_server()\n\n ts = dt.today()\n ts_str = ts.strftime(\"%x,%X,\")\n\n try:\n if mc.get('rst_gsm_done') * mc.get('init_gsm_done') * mc.get('send_sms_done'):\n gsmio.check_csq()\n csq = int(mc.get(\"csq_val\"))\n csq = str(csq)\n else:\n print(\">> GSM is busy\")\n csq = \"98\"\n except Exception as e:\n print(\">> Error reading GSM CSQ. Setting CSQ to error value\",e)\n csq = \"98\"\n\n cfg = mc.get(\"server_config\")\n \n try:\n mmpertip = float(cfg['rain']['mmpertip'])\n except:\n os.system('python3 /home/pi/gateway3/gateway.py -ir')\n sys.exit()\n\n rainval = \"%0.2f\" % (rd.check_rain_value(reset_rain = True) * mmpertip) \n sysvol = \"%0.2f\" % (pmon.read()[\"bus_voltage\"])\n \n temp = os.popen(\"vcgencmd measure_temp\").readline()\n tempval = temp.replace(\"temp=\",\"\").replace(\"'C\\n\",\"\")\n print(\"Temperature: {0}\".format(tempval))\n\n msgtosend = cfg[\"coordinfo\"][\"name\"] + \"W,\" + ts_str\n msgtosend += \"0,000,\" + tempval + \",\" + rainval + \",\"\n msgtosend += sysvol + \",\"\n msgtosend += csq\n\n if not args.read_only:\n print(\">> Saving to memory:\")\n time.sleep(5)\n print(msgtosend)\n #common.save_sms_to_memory(msgtosend)\n dbio.write_sms_to_outbox(msgtosend)\n #dbio.write_sms_to_outbox(msgtosend,pb_id='639175972526')\n\n \nif __name__=='__main__':\n try:\n main()\n except KeyboardInterrupt:\n print(\"Aborting ...\")\n # gsmClosePortAndHandle()\n","sub_path":"gateway3/health.py","file_name":"health.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"204033695","text":"import sys\n\nprimes = [2] # the first prime\n\ndef count_primes(n1, n2):\n if n2 > primes[-1]:\n x = primes[-1]\n while x < n2:\n x += 1\n for p in primes:\n if x % p == 0:\n break\n else:\n primes.append(x)\n print(len([x for x in primes if n1 <= x <= n2]))\n\nf = open(sys.argv[1], \"r\")\ntdata = ((int(y[0]), int(y[1])) for y in (x.rstrip(\"\\n\").split(\",\") for x in f))\n_ = list(map(lambda z: count_primes(*z), tdata))\nf.close()","sub_path":"Moderate/counting_primes.py","file_name":"counting_primes.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"390347984","text":"# Default imports\nfrom sklearn.feature_selection import SelectFromModel\nfrom sklearn.ensemble import RandomForestClassifier\nimport pandas as pd\nimport numpy as np\n\ndata = pd.read_csv('data/house_prices_multivariate.csv')\n\n\n# Your solution code here\ndef select_from_model(data):\n X = data.iloc[:,:-1]\n y = data.iloc[:,-1]\n cols = X.columns\n np.random.seed(9)\n #print cols\n rf = RandomForestClassifier()\n rf.fit(X,y)\n model = SelectFromModel(rf, prefit=True)\n #print model.get_support()\n #print rf.get_support()\n features = cols[model.get_support()]\n #features = [cols[x] for x in rfe.support_ if x==True]\n return features.tolist()\n","sub_path":"q04_select_from_model/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"582060605","text":"from typing import Any, Dict, Sequence\n\nfrom sentry.snuba.dataset import Dataset\nfrom sentry.snuba.events import Columns\nfrom sentry.types.issues import GroupCategory\n\n\"\"\"\nIssue category specific components to computing a preview for a set of rules.\n\nTo add support for a new issue category/dataset:\n 1. Add mapping from GroupCategory to Dataset\n 2. Add mapping from Dataset to snuba column name\n a. The column name should be a field in sentry.snuba.events.Column\n 3. Add category-specific query params for UPDATE_KWARGS_FOR_GROUPS and UPDATE_KWARGS_FOR_GROUP\n\"\"\"\n\n# Maps group category to dataset\nGROUP_CATEGORY_TO_DATASET: Dict[GroupCategory, Dataset] = {\n GroupCategory.ERROR: Dataset.Events,\n GroupCategory.PERFORMANCE: Dataset.Transactions,\n}\n\n# Maps datasets to snuba column name\nDATASET_TO_COLUMN_NAME: Dict[Dataset, str] = {\n Dataset.Events: \"event_name\",\n Dataset.Transactions: \"transaction_name\",\n}\n\n\n# Given a list of Column Enum objects, return their actual column name in each dataset that is supported\ndef get_dataset_columns(columns: Sequence[Columns]) -> Dict[Dataset, Sequence[str]]:\n dataset_columns: Dict[Dataset, Sequence[str]] = {}\n for dataset, column_name in DATASET_TO_COLUMN_NAME.items():\n dataset_columns[dataset] = [\n getattr(column.value, column_name)\n for column in columns\n if getattr(column.value, column_name) is not None\n ]\n\n return dataset_columns\n\n\ndef _events_from_groups_kwargs(\n group_ids: Sequence[int], kwargs: Dict[str, Any], has_issue_state_condition: bool = True\n) -> Dict[str, Any]:\n if has_issue_state_condition:\n kwargs[\"conditions\"] = [(\"group_id\", \"IN\", group_ids)]\n return kwargs\n\n\ndef _transactions_from_groups_kwargs(\n group_ids: Sequence[int], kwargs: Dict[str, Any], has_issue_state_condition: bool = True\n) -> Dict[str, Any]:\n if has_issue_state_condition:\n kwargs[\"having\"] = [(\"group_id\", \"IN\", group_ids)]\n kwargs[\"conditions\"] = [[[\"hasAny\", [\"group_ids\", [\"array\", group_ids]]], \"=\", 1]]\n if \"aggregations\" not in kwargs:\n kwargs[\"aggregations\"] = []\n kwargs[\"aggregations\"].append((\"arrayJoin\", [\"group_ids\"], \"group_id\"))\n return kwargs\n\n\n\"\"\"\nReturns the rows that contain the group id.\nIf there's a many-to-many relationship, the group id column should be arrayjoined.\nIf there are no issue state changes (causes no group ids), then do not filter by group ids.\n\"\"\"\nUPDATE_KWARGS_FOR_GROUPS = {\n Dataset.Events: _events_from_groups_kwargs,\n Dataset.Transactions: _transactions_from_groups_kwargs,\n}\n\n\ndef _events_from_group_kwargs(group_id: int, kwargs: Dict[str, Any]) -> Dict[str, Any]:\n kwargs[\"conditions\"] = [(\"group_id\", \"=\", group_id)]\n return kwargs\n\n\ndef _transactions_from_group_kwargs(group_id: int, kwargs: Dict[str, Any]) -> Dict[str, Any]:\n kwargs[\"conditions\"] = [[[\"has\", [\"group_ids\", group_id]], \"=\", 1]]\n return kwargs\n\n\n\"\"\"\nReturns the rows that reference the group id without arrayjoining.\n\"\"\"\nUPDATE_KWARGS_FOR_GROUP = {\n Dataset.Events: _events_from_group_kwargs,\n Dataset.Transactions: _transactions_from_group_kwargs,\n}\n","sub_path":"src/sentry/rules/history/preview_strategy.py","file_name":"preview_strategy.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"348486938","text":"#!/usr/bin/python\n# -*- coding:UTF-8 -*-\n\nimport json\nimport jieba\nimport os\nimport cPickle;\nfilename = \"all_train.json\"\nstopwords_list = cPickle.load(open(\"stopwords_list.pkl\",\"rb\"));\nstopwords_list = set(stopwords_list);\n\ndef cal_wordco1(l1 , l2):\n return len(set(l1)&set(l2));\n\ndef cal_wordco2(l1 , l2):\n l3 = set(l1) & set(l2);\n return len(l3) - len(l3 & stopwords_list);\n\ndef cal_Jaccard1(l1, l2):\n l3 = set(l1) & set(l2)\n l4 = set(l1) | set(l2);\n return len(l3) * 1.0 / (len(l4) + 1.0);\n\ndef cal_Jaccard2(l1, l2):\n l3 = set(l1) & set(l2)\n l4 = set(l1) | set(l2);\n return (len(l3) - len(l3 & stopwords_list))* 1.0 / (len(l4) - len(l4 & stopwords_list) + 1.0);\n\ndef cal_4features(l1 , l2):\n return cal_wordco1(l1,l2) , cal_wordco2(l1,l2) , cal_Jaccard1(l1,l2) , cal_Jaccard2(l1 ,l2);\n\n\ndef read_json_file(filename):\n with open(filename , \"r\") as json_file:\n json_data = json_file.read();\n json_data = json_data.split(\"\\n\");#转化为列表\n que_cutted , ans_cutted , labels = [] , [] , [];#这里的que都还只是str的形式的,只不过分完词了\n qids ,aids = [] , [] ;\n wordco1 , wordco2 = [] , [];\n Jaccard1 , Jaccard2 = [] , [];\n \n sentence_to_get_wordvec = [];#这是为了得到单词对应的词向量而存的问题和答案,每个问题只存储一次\n all_together = [];#qid que aid ans label(0,1,2) wordco1 wordco2 j1 j2\n item = [];#qid que aid ans label(0,1,2) wordco1 wordco2 j1 j2\n for line in json_data:\n #line现在是字符串\n if len(line) == 0 :\n continue;\n line = json.loads(line);#是dict. query_id ,query , passages\n #passages是个列表一般有10个元素,至少有一个元素,\n #每个元素都是一个字典:passage_id,url,passage_text,label\n qid = int(line[\"query_id\"]);\n que = line[\"query\"];\n que = que.strip(\" \");\n que = \" \".join(jieba.cut(que , cut_all = False));#分完词了,不是str是unicode\n que = que.split(\" \");\n new_que = [];\n for word in que:\n if len(word) > 0 :\n new_que.append(word);\n sentence_to_get_wordvec.append(new_que);\n for ans_line in line[\"passages\"]:\n #ans_line是列表中的一个元素,也是字典\n aid = int(ans_line[\"passage_id\"])\n ans = ans_line[\"passage_text\"];\n ans = \" \".join(jieba.cut(ans , cut_all = False));\n ans = ans.split(\" \");\n new_ans = [];\n for word in ans:\n if len(word) > 0:\n new_ans.append(word);\n sentence_to_get_wordvec.append(new_ans);\n label = int(ans_line[\"label\"])\n qids.append(qid)\n que_cutted.append(new_que)\n aids.append(aid)\n ans_cutted.append(new_ans)\n labels.append(label)\n\n wco1,wco2,ja1,ja2 = cal_4features(new_que , new_ans);\n wordco1.append(wco1)\n wordco2.append(wco2)\n Jaccard1.append(ja1)\n Jaccard2.append(ja2)\n item = [qid ,new_que , aid ,new_ans , label , wco1 , wco2 , ja1 , ja2];\n all_together.append(item);\n return sentence_to_get_wordvec , qids , que_cutted , aids , ans_cutted , labels , wordco1 , wordco2 , Jaccard1 , Jaccard2, all_together;\n\n\nif __name__ == \"__main__\":\n sentence_to_get_wordvec , qids , que_cutted , aids , ans_cutted , labels , wordco1 , wordco2 , Jaccard1 , Jaccard2 ,all_together = read_json_file(filename);\n cPickle.dump(sentence_to_get_wordvec , open(\"sentence_to_get_wordvec.pkl\",\"wb\"));\n cPickle.dump(qids , open(\"qids.pkl\",\"wb\"))\n cPickle.dump(que_cutted , open(\"que_cutted.pkl\",\"wb\"))\n cPickle.dump(aids , open(\"aids.pkl\",\"wb\"))\n cPickle.dump(ans_cutted , open(\"ans_cutted.pkl\",\"wb\"))\n cPickle.dump(labels , open(\"labels.pkl\",\"wb\"))\n cPickle.dump(wordco1, open(\"wordco1.pkl\",\"wb\"));\n cPickle.dump(wordco2, open(\"wordco2.pkl\",\"wb\"));\n cPickle.dump(Jaccard1,open(\"Jaccard1.pkl\",\"wb\"));\n cPickle.dump(Jaccard2,open(\"Jaccard2.pkl\",\"wb\"));\n cPickle.dump(all_together , open(\"all_together.pkl\",\"wb\"));\n\n","sub_path":"get_json_data_and_cut_word.py","file_name":"get_json_data_and_cut_word.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"173027185","text":"#Here we built a 3 layer deep neural network to predict number of emergency visits for eplilepsy patients\n#the model has been built using tensorflow and Keras sequential model\n#same parametres have been used as the other machine learning models\n#We have used a batch size of 50 and total epochs = 1000\n#Final mean squared error has been reported\n\n\nfrom __future__ import absolute_import, division, print_function\n\nimport tensorflow as tf\nfrom tensorflow import keras\nimport keras.losses\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import mean_squared_error\n\nprint(tf.__version__)\n\nxtrin = pd.read_csv(\"xtrin_final.csv\")\nxtest = pd.read_csv(\"xtest_final.csv\")\nytrain = pd.read_csv(\"ytrain_final.csv\", header = None)\nytest = pd.read_csv(\"ytest_final.csv\", header = None)\n\nxtrin = xtrin.drop(xtrin.columns[0], axis = 1)\nxtest = xtest.drop(xtest.columns[0], axis = 1)\nytrain = ytrain.drop(ytrain.columns[0], axis = 1)\nytest = ytest.drop(ytest.columns[0], axis = 1)\n\n#3 layer deep Neural Network with relu activation\nmodel = keras.Sequential([\n keras.layers.Dense(13, activation = 'relu'),\n keras.layers.Dense(8, activation = 'relu'),\n keras.layers.Dense(1, activation = 'linear')\n ])\n\nmodel.compile(optimizer= 'adam', loss= 'mean_absolute_percentage_error', metrics = ['accuracy'])\n\nepinn = model.fit(xtrin.values, ytrain.values, epochs = 1000, batch_size = 50)\n\nmean_squared_error(ytest.values, model.predict(xtest.values)) #27.70\n","sub_path":"src/data/epilepsy_nn.py","file_name":"epilepsy_nn.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"614543921","text":"# Author: Jab (or 40BlocksUnder) | Joshua Edwards\n# Link for more info: http://theindiestone.com/forums/index.php/topic/12864-blender\n# Exports models to Zomboid format.\n\nimport io, math, bmesh, bpy\nfrom bpy_extras.io_utils import ExportHelper\nfrom bpy.props import StringProperty, BoolProperty, EnumProperty, FloatProperty\nfrom bpy.types import Operator\nfrom mathutils import Vector, Euler, Quaternion, Matrix\n\n\nclass ZomboidExportAnimation(Operator, ExportHelper):\n bl_idname = \"zomboid.export_animation\"\n bl_label = \"Export a Zomboid Animation\"\n filename_ext = \".pza\"\n filter_glob = StringProperty(\n default=\"*.pza\",\n options={'HIDDEN'},\n )\n\n animation_time = FloatProperty(\n name=\"Animation Speed\",\n description=\"How fast the animation runs in-game.\",\n default=1.0,\n )\n \n # REVERSE THESE STEPS:\n # 1) Turn the translation and rotation into a Frame Matrix\n # 2) Create a World Matrix by multiplying the Parent World Matrix with the Frame Matrix\n # 3) Create the Product Matrix by multiplying the World Matrix with the Bone Matrix\n def prepare(self):\n bpy.ops.object.mode_set(mode = 'POSE')\n \n # Grab the start, end, and range for the frames in the action.\n self.frame_first = get_first_frame(self.action)\n self.frame_last = get_last_frame(self.action)\n self.frame_count = get_frame_count(self.action)\n # Create Animation object.\n self.animation = Animation(self.action.name)\n \n for index in range(self.frame_first, self.frame_last):\n # Sets the world to this frame.\n set_frame(index)\n # Create Frame Object\n frame = Frame(index)\n \n for b in self.object.pose.bones:\n bone = Bone(b.name, self.object[b.name])\n \n bip_offset = b.bone.matrix_local.copy()\n bip_offset_inv = bip_offset.copy().inverted()\n# print('Offset Matrix: ')\n# print(to_lwjgl_matrix(bip_offset_inv))\n bip_basis = b.matrix_basis\n \n t1 = bip_basis * bip_offset_inv\n \n loc1 = (bip_offset).decompose()[0]\n loc2 = (bip_basis.copy()).decompose()[0]\n \n loc = Vector((loc1[0] - loc2[2], loc1[1] + loc2[1], loc1[2] - loc2[0]))\n rot = t1.decompose()[1]\n \n bone.loc = loc\n bone.rot = rot\n \n frame.bones.append(bone)\n \n frame.organize_bones()\n # Add the Frame to the Animation\n self.animation.frames.append(frame)\n \n \n def write(self):\n with io.open(self.filepath, 'w') as file:\n write_line(file, '#Animation Name')\n write_line(file, self.action.name)\n write_line(file, '#Animation Time')\n write_line(file, efloat(self.animation_time * (self.frame_count / 30)))\n write_line(file, '#Animation Frame Count')\n write_line(file, str(self.frame_count))\n write_line(file, '# Start of Frame Data')\n # Frame Data\n for frame in self.animation.frames:\n for bone in frame.bones:\n write_line(file, str(bone.id))\n write_line(file, bone.name)\n # NOTE: 3DS at the time of exporting the \n # vanilla models is 30 frames per second. \n write_line(file, efloat((((frame.id - self.frame_first)) / 30) * self.animation_time))\n write_vec3(file, bone.loc)\n write_quat(file, bone.rot) \n \n def execute(self, context):\n try:\n bpy.ops.object.mode_set(mode = 'OBJECT')\n except:\n ok = None\n armature = self.object = bpy.context.active_object\n # Checks to see if selection is avaliable AND a Mesh.\n if armature == None:\n print(\"No armature selected.\")\n return {'FINISHED'}\n if armature.type != 'ARMATURE':\n print(\"Object selected is not a armature: \" + str(armature.type))\n return {'FINISHED'}\n self.armature = armature\n self.object = bpy.data.objects[armature.name]\n self.action = self.object.animation_data.action\n self.prepare()\n self.write()\n return {'FINISHED'}\n\n def __init__(self):\n # Object for the Armature\n self.object = None\n # Armature to export.\n self.armature = None\n # Action with animation\n self.action = None\n # Animation Object\n self.animation = None\n\n\nclass Animation:\n \n def __init__(self, name):\n self.name = name\n self.frames = [ ]\n \n \nclass Frame:\n \n def __init__(self, id):\n self.id = id\n self.bones = [ ]\n \n def organize_bones(self):\n \n # Lowest ID number\n low = 65535\n # Highest ID number\n high = 0\n \n for bone in self.bones:\n id = bone.id\n if id < low:\n low = id\n if id > high:\n high = id\n \n new_bones = [ ]\n for index in range(low, high):\n for bone in self.bones:\n if bone.id is index:\n new_bones.append(bone)\n break\n self.bones = new_bones\n \n\nclass Bone:\n \n def __init__(self, name, id):\n self.name = name\n self.rot = None\n self.loc = None\n self.scale = None\n self.id = id\n \n\ndef menu_func_export(self, context):\n self.layout.operator(ZomboidExportAnimation.bl_idname, text=\"Text Export Operator\")\n\ndef register():\n bpy.utils.register_class(ZomboidExportAnimation)\n bpy.types.INFO_MT_file_export.append(menu_func_export)\n\n\ndef unregister():\n bpy.utils.unregister_class(ZomboidExportAnimation)\n bpy.types.INFO_MT_file_export.remove(menu_func_export)\n\n\nif __name__ == \"__main__\":\n register()\n bpy.ops.zomboid.export_animation('INVOKE_DEFAULT')\n\n\ndef get_last_frame(action):\n return int(round(action.frame_range[1]))\n\ndef get_first_frame(action):\n return int(round(action.frame_range[0]))\n\ndef get_frame_count(action):\n return get_last_frame(action) - get_first_frame(action) + 1\n \ndef set_frame(frame):\n bpy.context.scene.frame_current = int(round(frame))\n\ndef efloat(float):\n return \"%0.8f\" % float\n\nclass Matrix4f():\n \n def __init__(self):\n self.m00 = 1.0\n self.m01 = 0.0\n self.m02 = 0.0\n self.m03 = 0.0\n self.m10 = 0.0\n self.m11 = 1.0\n self.m12 = 0.0\n self.m13 = 0.0\n self.m20 = 0.0\n self.m21 = 0.0\n self.m22 = 1.0\n self.m23 = 0.0\n self.m30 = 0.0\n self.m31 = 0.0\n self.m32 = 0.0\n self.m33 = 1.0\n \n def __str__(self):\n return 'M`atrix4f' + '\\n[' + efloat(self.m00) + ', ' + efloat(self.m01) + ', ' + efloat(self.m02) + ', ' + efloat(self.m03) + '],\\n[' + efloat(self.m10) + ', ' + efloat(self.m11) + ', ' + efloat(self.m12) + ', ' + efloat(self.m13) + '],\\n[' + efloat(self.m20) + ', ' + efloat(self.m21) + ', ' + efloat(self.m22) + ', ' + efloat(self.m23) + '],\\n[' + efloat(self.m30) + ', ' + efloat(self.m31) + ', ' + efloat(self.m32) + ', ' + efloat(self.m33) + ']'\n \n def set_identity(self):\n self.m00 = 1.0\n self.m01 = 0.0\n self.m02 = 0.0\n self.m03 = 0.0\n self.m10 = 0.0\n self.m11 = 1.0\n self.m12 = 0.0\n self.m13 = 0.0\n self.m20 = 0.0\n self.m21 = 0.0\n self.m22 = 1.0\n self.m23 = 0.0\n self.m30 = 0.0\n self.m31 = 0.0\n self.m32 = 0.0\n self.m33 = 1.0\n \n def copy(self):\n nm = Matrix4f()\n nm.m00 = self.m00\n nm.m01 = self.m01\n nm.m02 = self.m02\n nm.m03 = self.m03\n nm.m10 = self.m10\n nm.m11 = self.m11\n nm.m12 = self.m12\n nm.m13 = self.m13\n nm.m20 = self.m20\n nm.m21 = self.m21\n nm.m22 = self.m22\n nm.m23 = self.m23\n nm.m30 = self.m30\n nm.m31 = self.m31\n nm.m32 = self.m32\n nm.m33 = self.m33\n return nm\n \n def to_blender_matrix(self):\n m = Matrix(\n ([self.m00, self.m10, self.m20, self.m30],\n [self.m01, self.m11, self.m21, self.m31],\n [self.m02, self.m12, self.m22, self.m32],\n [self.m03, self.m13, self.m23, self.m33]))\n return m.transposed()\n \ndef to_lwjgl_matrix(self, blender_matrix):\n m = Matrix4f()\n b = blender_matrix.copy().transposed()\n m.m00 = b[0][0]\n m.m01 = b[1][0]\n m.m02 = b[2][0]\n m.m03 = b[3][0]\n m.m10 = b[0][1]\n m.m11 = b[1][1]\n m.m12 = b[2][1]\n m.m13 = b[3][1]\n m.m20 = b[0][2]\n m.m21 = b[1][2]\n m.m22 = b[2][2]\n m.m23 = b[3][2]\n m.m30 = b[0][3]\n m.m31 = b[1][3]\n m.m32 = b[2][3]\n m.m33 = b[3][3]\n return m\n\ndef translate(vec, src, dest):\n if dest == None:\n dest = Matrix4f()\n \n dest.m30 += src.m00 * vec.x + src.m10 * vec.y + src.m20 * vec.z\n dest.m31 += src.m01 * vec.x + src.m11 * vec.y + src.m21 * vec.z\n dest.m32 += src.m02 * vec.x + src.m12 * vec.y + src.m22 * vec.z\n dest.m33 += src.m03 * vec.x + src.m13 * vec.y + src.m23 * vec.z\n \n return dest\n\ndef mul(left,right,dest):\n if dest == None:\n dest = Matrix4f()\n \n m00 = left.m00 * right.m00 + left.m10 * right.m01 + left.m20 * right.m02 + left.m30 * right.m03\n m01 = left.m01 * right.m00 + left.m11 * right.m01 + left.m21 * right.m02 + left.m31 * right.m03\n m02 = left.m02 * right.m00 + left.m12 * right.m01 + left.m22 * right.m02 + left.m32 * right.m03\n m03 = left.m03 * right.m00 + left.m13 * right.m01 + left.m23 * right.m02 + left.m33 * right.m03\n m10 = left.m00 * right.m10 + left.m10 * right.m11 + left.m20 * right.m12 + left.m30 * right.m13\n m11 = left.m01 * right.m10 + left.m11 * right.m11 + left.m21 * right.m12 + left.m31 * right.m13\n m12 = left.m02 * right.m10 + left.m12 * right.m11 + left.m22 * right.m12 + left.m32 * right.m13\n m13 = left.m03 * right.m10 + left.m13 * right.m11 + left.m23 * right.m12 + left.m33 * right.m13\n m20 = left.m00 * right.m20 + left.m10 * right.m21 + left.m20 * right.m22 + left.m30 * right.m23\n m21 = left.m01 * right.m20 + left.m11 * right.m21 + left.m21 * right.m22 + left.m31 * right.m23\n m22 = left.m02 * right.m20 + left.m12 * right.m21 + left.m22 * right.m22 + left.m32 * right.m23\n m23 = left.m03 * right.m20 + left.m13 * right.m21 + left.m23 * right.m22 + left.m33 * right.m23\n m30 = left.m00 * right.m30 + left.m10 * right.m31 + left.m20 * right.m32 + left.m30 * right.m33\n m31 = left.m01 * right.m30 + left.m11 * right.m31 + left.m21 * right.m32 + left.m31 * right.m33\n m32 = left.m02 * right.m30 + left.m12 * right.m31 + left.m22 * right.m32 + left.m32 * right.m33\n m33 = left.m03 * right.m30 + left.m13 * right.m31 + left.m23 * right.m32 + left.m33 * right.m33\n dest.m00 = m00\n dest.m01 = m01\n dest.m02 = m02\n dest.m03 = m03\n dest.m10 = m10\n dest.m11 = m11\n dest.m12 = m12\n dest.m13 = m13\n dest.m20 = m20\n dest.m21 = m21\n dest.m22 = m22\n dest.m23 = m23\n dest.m30 = m30\n dest.m31 = m31\n dest.m32 = m32\n dest.m33 = m33\n \n return dest\n\ndef transpose(src, dest):\n if dest == None:\n dest = Matrix4f()\n \n m00 = src.m00\n m01 = src.m10\n m02 = src.m20\n m03 = src.m30\n m10 = src.m01\n m11 = src.m11\n m12 = src.m21\n m13 = src.m31\n m20 = src.m02\n m21 = src.m12\n m22 = src.m22\n m23 = src.m32\n m30 = src.m03\n m31 = src.m13\n m32 = src.m23\n m33 = src.m33\n dest.m00 = m00\n dest.m01 = m01\n dest.m02 = m02\n dest.m03 = m03\n dest.m10 = m10\n dest.m11 = m11\n dest.m12 = m12\n dest.m13 = m13\n dest.m20 = m20\n dest.m21 = m21\n dest.m22 = m22\n dest.m23 = m23\n dest.m30 = m30\n dest.m31 = m31\n dest.m32 = m32\n dest.m33 = m33\n \n return dest\n\n#####################################################################################\n### ###\n### File I/O methods ###\n### ###\n##################################################################################### \n\n# Writes a line to the file.\ndef write_line(file, line, new_line=True):\n \n # Converts any arbitrary primitives into a String just in-case.\n finished_line = str(line)\n \n # If new_line is true, add a newline marker at the end.\n if new_line:\n finished_line = finished_line + \"\\n\"\n \n # Write the line to a file.\n file.write(finished_line)\n \ndef write(file, line):\n write_line(file, line, new_line=False)\n \n \n# Writes a comment to the file.\ndef write_comment(file, comment):\n \n final_comment = \"# \" + str(comment)\n \n write_line(file, final_comment)\n \n \ndef write_vec3(file, vector):\n string = efloat(round((vector[0]), 8)) + \", \" + efloat(round((vector[1]), 8)) + \", \" + efloat(round((vector[2]), 8))\n write_line(file, string)\n \ndef write_quat(file, q):\n string = efloat(round((q.x), 8)) + \", \" + efloat(round((q.y), 8)) + \", \" + efloat(round((q.z), 8)) + \", \" + efloat(round((q.w), 8))\n write_line(file, string)\n \n \ndef write_array(file, array):\n string = \"\"\n for element in array:\n string += str(element) + \", \"\n write_line(file, string[:-2])\n \n \ndef write_face(file, face):\n string = \"\"\n for index in face.vert_ids:\n string += str(index) + \", \"\n \n write_line(file, string[:-2])\n \n#####################################################################################\n### ###\n### Helper Methods ###\n### ###\n##################################################################################### \n\nclass prettyfloat(float):\n def __repr__(self):\n return \"%0.2f\" % self\n\ndef get_bone_id_table(armature):\n arm = armature.data\n bone_names = [bone.name for bone in arm.bones]\n bone_ids = dict()\n for bone_name in bone_names:\n try:\n bone_ids[bone_name] = int(armature[bone_name])\n print(bone_ids[bone_name])\n except:\n continue\n return bone_ids \n\nmatrix_3_transform_z_positive = Matrix((( 1, 0, 0 ) ,( 0, 0,-1 ) ,( 0, 1, 0 ) ))\nmatrix_4_transform_z_positive = Matrix((( 1, 0, 0, 0 ),( 0, 0,-1, 0 ),( 0, 1, 0, 0 ),( 0, 0, 0, 1 )))","sub_path":"ZomboidExportAnimation.py","file_name":"ZomboidExportAnimation.py","file_ext":"py","file_size_in_byte":15033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"301733534","text":"#!/usr/bin/python\n# -*- codding: utf-8 -*-\nimport os\nimport sys\nsys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))\nfrom common.execute_command import write_two_parameter\n\n# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/attach-static-ip.html\nif __name__ == '__main__':\n \"\"\"\n\tallocate-static-ip : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/allocate-static-ip.html\n\tdetach-static-ip : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/detach-static-ip.html\n\tget-static-ip : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-static-ip.html\n\tget-static-ips : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-static-ips.html\n\trelease-static-ip : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/release-static-ip.html\n \"\"\"\n\n parameter_display_string = \"\"\"\n # static-ip-name : The name of the static IP.\n # instance-name : The instance name to which you want to attach the static IP address.\n \"\"\"\n add_option_dict = {}\n add_option_dict[\"parameter_display_string\"] = parameter_display_string\n # ex: add_option_dict[\"no_value_parameter_list\"] = \"--single-parameter\"\n write_two_parameter(\"lightsail\", \"attach-static-ip\", \"static-ip-name\", \"instance-name\", add_option_dict)\n","sub_path":"lightsail_write_2/static-ip_attach.py","file_name":"static-ip_attach.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"351311059","text":"from cicada.analysis.cicada_analysis import CicadaAnalysis\n\n\nclass CicadaCellsCount(CicadaAnalysis):\n def __init__(self):\n \"\"\"\n A list of\n :param data_to_analyse: list of data_structure\n :param family_id: family_id indicated to which family of analysis this class belongs. If None, then\n the analysis is a family in its own.\n :param data_format: indicate the type of data structure. for NWB, NIX\n \"\"\"\n super().__init__(name=\"count cells\", family_id=\"counter\",\n short_description=\"Count the number of cells\")\n\n def check_data(self):\n \"\"\"\n Check the data given one initiating the class and return True if the data given allows the analysis\n implemented, False otherwise.\n :return: a boolean\n \"\"\"\n\n if self._data_format != \"nwb\":\n # non NWB format compatibility not yet implemented\n return False\n\n for data in self._data_to_analyse:\n # check is there is at least one processing module\n if len(data.processing) == 0:\n return False\n\n # in our case, we will use 'ophys' module\n if \"ophys\" not in data.processing:\n return False\n return True\n\n def update_original_data(self):\n \"\"\"\n To be called if the data to analyse should be updated after the analysis has been run.\n :return: boolean: return True if the data has been modified\n \"\"\"\n pass\n\n def get_params_for_gui(self):\n return [\n {'name': 'cells_alive', 'type': bool, 'doc': 'only count the cells that spikes', 'default': False}]\n\n def run_analysis(self, **kwargs):\n \"\"\"\n Run the analysis: just printing the number of cells in each session\n :param kwargs:\n :return:\n \"\"\"\n n_cells_dict = {}\n for data in self._data_to_analyse:\n mod = data.modules['ophys']\n rrs = mod['Fluorescence'].get_roi_response_series()\n\n # get the data...\n rrs_data = rrs.data\n n_cells_dict[data.identifier] = rrs.data.shape[0]\n # rrs_timestamps = rrs.timestamps\n # rrs_rois = rrs.rois\n print(f\"N cells by session: {n_cells_dict}\")\n","sub_path":"src/cicada/analysis/cicada_cells_count.py","file_name":"cicada_cells_count.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"271339124","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2007-2011 Edgewall Software\n# All rights reserved.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at http://babel.edgewall.org/wiki/License.\n#\n# This software consists of voluntary contributions made by many\n# individuals. For the exact contribution history, see the revision\n# history and logs, available at http://babel.edgewall.org/log/.\n\n\nimport sys\n\nPY2 = sys.version_info[0] == 2\n\n_identity = lambda x: x\n\n\nif not PY2:\n text_type = str\n string_types = (str,)\n integer_types = (int, )\n unichr = chr\n\n text_to_native = lambda s, enc: s\n\n iterkeys = lambda d: iter(d.keys())\n itervalues = lambda d: iter(d.values())\n iteritems = lambda d: iter(d.items())\n\n from io import StringIO, BytesIO\n import pickle\n\n izip = zip\n imap = map\n range_type = range\n\n cmp = lambda a, b: (a > b) - (a < b)\n\nelse:\n text_type = unicode\n string_types = (str, unicode)\n integer_types = (int, long)\n\n text_to_native = lambda s, enc: s.encode(enc)\n unichr = unichr\n\n iterkeys = lambda d: d.iterkeys()\n itervalues = lambda d: d.itervalues()\n iteritems = lambda d: d.iteritems()\n\n from cStringIO import StringIO as BytesIO\n from StringIO import StringIO\n import cPickle as pickle\n\n from itertools import izip, imap\n range_type = xrange\n\n cmp = cmp\n\n\nnumber_types = integer_types + (float,)\n","sub_path":"babel/_compat.py","file_name":"_compat.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"110607212","text":"\"\"\"\r\n * Licensed to DSecure.me under one or more contributor\r\n * license agreements. See the NOTICE file distributed with\r\n * this work for additional information regarding copyright\r\n * ownership. DSecure.me licenses this file to you under\r\n * the Apache License, Version 2.0 (the \"License\"); you may\r\n * not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing,\r\n * software distributed under the License is distributed on an\r\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\n * KIND, either express or implied. See the License for the\r\n * specific language governing permissions and limitations\r\n * under the License.\r\n *\r\n\"\"\"\r\n\r\nfrom unittest.mock import patch, Mock, MagicMock\r\n\r\nfrom django.test import TestCase\r\n\r\nfrom vmc.assets.models import Asset, Port\r\nfrom vmc.ralph.api import Ralph, AssetIdException\r\nfrom vmc.ralph.models import Config\r\nimport json\r\nfrom vmc.common.tests import get_fixture_location\r\n\r\nfrom vmc.ralph.tasks import load_all_assets\r\n\r\n\r\nclass ResponseMock:\r\n\r\n def __init__(self, resp, status_code):\r\n self.text = resp\r\n self.status_code = status_code\r\n\r\n def json(self):\r\n return self.text\r\n\r\n\r\nclass RalphTest(TestCase):\r\n fixtures = ['config.json']\r\n\r\n def setUp(self):\r\n self.config = Config.objects.get(pk=1)\r\n self.uut = Ralph(self.config)\r\n\r\n @patch('vmc.ralph.api.requests')\r\n def test_call_get_token(self, request_mock):\r\n request_mock.request.return_value = ResponseMock({'token': '79ee13720dbf474399dde532daad558aaeb131c3'}, 200)\r\n\r\n token = self.uut.get_token()\r\n self.assertEqual(token, '79ee13720dbf474399dde532daad558aaeb131c3')\r\n\r\n @patch('vmc.ralph.api.requests')\r\n def test_call_get_host_by_id(self, request_mock):\r\n\r\n with open(get_fixture_location(__file__, 'host_response.json')) as f:\r\n j = f.read()\r\n api_response = json.loads(j)\r\n api_response_json = json.dumps(json.loads(j))\r\n\r\n self.uut.get_token = Mock(return_value='79ee13720dbf474399dde532daad558aaeb131c3')\r\n request_mock.request.return_value = ResponseMock(json.dumps(api_response), 200)\r\n result = self.uut.get_host_data_by_id(62)\r\n\r\n self.assertEqual(result, api_response_json)\r\n\r\n @patch('vmc.ralph.api.requests')\r\n def test_call_no_such_host_exception(self, request_mock):\r\n\r\n self.uut.get_token = Mock(return_value='79ee13720dbf474399dde532daad558aaeb131c3')\r\n request_mock.request.return_value = ResponseMock('{\"detail\":\"Not found.\"}', 200)\r\n\r\n result = self.uut.get_host_data_by_id('a')\r\n self.assertEqual(result, 'Such asset doesn\\'t exist')\r\n\r\n @patch('vmc.ralph.api.requests')\r\n def test_call_get_all_assets(self, request_mock):\r\n\r\n self.uut.get_token = Mock(return_value='79ee13720dbf474399dde532daad558aaeb131c3')\r\n\r\n with open(get_fixture_location(__file__, 'all_hosts_response.json')) as f:\r\n j = f.read()\r\n api_response = j\r\n request_mock.request.return_value = ResponseMock(api_response, 200)\r\n result = self.uut.get_all_assets()\r\n self.assertIs(type(result), list)\r\n self.assertIs(type(result[0]), dict)\r\n self.assertEqual(len(result), 1)\r\n\r\n\r\nclass LoadAllAssetsTest(TestCase):\r\n\r\n def setUp(self) -> None:\r\n with open(get_fixture_location(__file__, 'host_response.json')) as f:\r\n self.hosts = json.loads(f.read())\r\n\r\n @patch('vmc.ralph.tasks.Ralph')\r\n def test_call(self, mock_api):\r\n\r\n mock_api().get_all_assets.return_value = [self.hosts]\r\n load_all_assets()\r\n self.assertEqual(2, Asset.objects.count())\r\n","sub_path":"src/vmc/ralph/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"131095763","text":"\nclass Distribution:\n\n def __init__(self, x, y, z,name_labels):\n \"\"\"\n Wapper distribution\n :param x: coordinate x\n :param y: coordinate y\n :param z: value\n :param name_labels: string list of labels names\n \"\"\"\n self.original = None\n self.x = x\n self.y = y\n self.z = z\n self.labels = name_labels\n","sub_path":"src/python_code/Visualizer/distribution_wrapper.py","file_name":"distribution_wrapper.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"199983272","text":"#!/usr/bin/env python\n# coding=utf-8\n###########################################\n# File: MobilephoneCreater.py\n# Desc: 手机号生成器视图层\n# Author: 张羽锋\n# History: 2015/01/01 张羽锋 新建\n###########################################\n\nfrom django.template import RequestContext\nfrom django.shortcuts import render_to_response\nimport simplejson\nfrom django.http.response import HttpResponse\nimport random\nimport logging\n\nlogger = logging.getLogger(\"DreamStar.app\")\n\n\n# 功能菜单-手机号生成功能页面视图接口\ndef cellphone_number_creater(request):\n try:\n # context_instance=RequestContext(request)进行csrf认证\n return render_to_response(\"mobilePhoneCreater.html\", context_instance=RequestContext(request))\n except Exception as e:\n logger.error(e)\n logger.exception(u\"手机号生成页面错误如下:\")\n\n\n# 随机手机号生成\ndef create_cellphone_number(request):\n try:\n prelist = [\"130\", \"131\", \"132\", \"133\", \"134\", \"135\", \"136\", \"137\", \"138\", \"139\", \"147\", \"150\", \"151\", \"152\",\n \"153\", \"155\", \"156\", \"157\", \"158\", \"159\", \"186\", \"187\", \"188\"]\n mobile_phone = random.choice(prelist) + \"\".join(random.choice(\"0123456789\") for i in range(8))\n return HttpResponse(simplejson.dumps(mobile_phone))\n except Exception as e:\n logger.error(e)\n logger.exception(u\"手机号生成错误如下:\")\n","sub_path":"totest/views/MobilephoneCreater.py","file_name":"MobilephoneCreater.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"332820849","text":"\"\"\"resource.py contains the base resource classes that user-created\nresources depend on in steno3d\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom json import dumps\nfrom pprint import pformat\nfrom six import string_types\n\nimport properties\n\nfrom .client import Comms, needs_login, pause, plot\nfrom .props import HasSteno3DProps\n\n\nclass classproperty(property):\n \"\"\"class decorator to enable property behavior in classmethods\"\"\"\n def __get__(self, cls, owner):\n return self.fget.__get__(None, owner)()\n\n\nclass UserContent(HasSteno3DProps):\n \"\"\"Base class for everything user creates and uploads in steno3d\"\"\"\n title = properties.String(\n doc='Title of the model.',\n default='',\n required=False\n )\n description = properties.String(\n doc='Description of the model.',\n default='',\n required=False\n )\n _sync = False\n _upload_data = None\n _upload_size = 0\n _upload_count = 0\n _upload_total_size = 0\n _upload_total_count = 0\n\n @classproperty\n @classmethod\n def _resource_class(cls):\n \"\"\"name of the class of resource\"\"\"\n if getattr(cls, '__resource_class', None) is None:\n cls.__resource_class = cls.__name__.lower()\n return cls.__resource_class\n\n @classproperty\n @classmethod\n def _model_api_location(cls):\n \"\"\"api destination for resource\"\"\"\n if getattr(cls, '__model_api_location', None) is None:\n cls.__model_api_location = 'resource/{className}'.format(\n className=cls._resource_class\n )\n return cls.__model_api_location\n\n def _upload(self, **kwargs):\n if getattr(self, '_uploading', False):\n return\n try:\n verbose = kwargs.get('verbose', True)\n sync = kwargs.get('sync', False)\n self._uploading = True\n pause()\n assert self.validate()\n self._upload_dirty(**kwargs)\n if getattr(self, '_upload_data', None) is None:\n self._post(\n self._get_dirty_data(force=True),\n self._get_dirty_files(force=True)\n )\n else:\n dirty_data = self._get_dirty_data()\n dirty_files = self._get_dirty_files()\n if len(dirty_data) > 0 or len(dirty_files) > 0:\n self._put(dirty_data, dirty_files)\n self._mark_clean(recurse=False)\n self._sync = sync\n progress_callback = kwargs.get('progress_callback', None)\n if verbose and progress_callback is None:\n progress_callback = self._progress_report\n if progress_callback is not None:\n if (\n isinstance(self, BaseResource) and\n not isinstance(self, CompositeResource)\n ):\n UserContent._upload_size += self._nbytes()\n else:\n UserContent._upload_count += 1\n progress = 0.9 * (\n UserContent._upload_size /\n UserContent._upload_total_size\n ) + 0.1 * (\n UserContent._upload_count /\n UserContent._upload_total_count\n )\n message = 'Uploading: {cls} {title}'.format(\n cls=self._resource_class,\n title=self.title\n )\n progress_callback({'progress': progress, 'message': message})\n\n except Exception as err:\n if self._sync and verbose:\n print('Upload failed, turning off syncing. To restart '\n 'syncing, upload() again.')\n self._sync = False\n else:\n raise err\n finally:\n self._uploading = False\n\n @staticmethod\n def _progress_report(status):\n print('\\rTotal progress: {:>3}% - {}'.format(\n int(round(status['progress']*100)), status['message']\n ), end='')\n\n def _get_dirty_data(self, force=False):\n dirty = self._dirty_props\n datadict = dict()\n if 'title' in dirty or force:\n datadict['title'] = self.title\n if 'description' in dirty or force:\n datadict['description'] = self.description\n return datadict\n\n def _get_dirty_files(self, force=False):\n return {}\n\n def _upload_dirty(self, **kwargs):\n pass\n\n @properties.observer(properties.everything)\n def _on_property_change(self, change):\n if getattr(self, '_sync', False):\n self._upload(sync=self._sync)\n\n def _post(self, datadict=None, files=None):\n self._client_upload(Comms.post, 'api/' + self._model_api_location,\n datadict, files)\n\n def _put(self, datadict=None, files=None):\n pause()\n api_uid = 'api/{mapi}/{uid}'.format(mapi=self._model_api_location,\n uid=self._upload_data['uid'])\n self._client_upload(Comms.put, api_uid, datadict, files)\n\n def _client_upload(self, request_fcn, url,\n datadict=None, files=None):\n req = request_fcn(\n url,\n data=datadict if datadict else tuple(),\n files=files if files else tuple(),\n )\n if isinstance(req, list):\n for rq in req:\n if rq['status_code'] != 200:\n try:\n resp = pformat(rq['json'])\n except ValueError:\n resp = rq\n\n raise UploadError(\n 'Upload failed: {location}'.format(\n location=url,\n ) +\n '\\ndata: {datadict}\\nfiles: {filedict}'.format(\n datadict=pformat(datadict),\n filedict=pformat(files),\n ) +\n '\\nresponse: {response}'.format(\n response=resp,\n )\n )\n self._upload_data = [rq['json'] for rq in req]\n else:\n if req['status_code'] != 200:\n raise UploadError(\n 'Upload failed: {location}'.format(\n location=url,\n ) +\n '\\ndata: {datadict}\\nfiles: {filedict}'.format(\n datadict=pformat(datadict),\n filedict=pformat(files),\n ) +\n '\\nresponse: {response}'.format(\n response=req['json'],\n )\n )\n self._upload_data = req['json']\n\n @property\n def _json(self):\n \"\"\"Return a JSON representation of the object\"\"\"\n json = getattr(self, '_upload_data', None)\n if json is None:\n raise ValueError('JSON not available: Data not uploaded')\n return json\n\n @classmethod\n def _json_from_uid(cls, uid, using=None):\n if not isinstance(uid, string_types) or len(uid) != 20:\n raise ValueError('{}: invalid uid'.format(uid))\n resp = Comms.get('api/{mapi}/{uid}{using}'.format(\n mapi=cls._model_api_location,\n uid=uid,\n using='?using={}'.format(using) if using else '',\n ))\n if resp['status_code'] != 200:\n raise ValueError('{uid}: {cls} query failed'.format(\n uid=uid,\n cls=cls._resource_class\n ))\n return resp['json']\n\n @classmethod\n def _build(cls, src, copy=True, tab_level='', **kwargs):\n verbose = kwargs.get('verbose', True)\n if isinstance(src, properties.HasProperties):\n raise NotImplementedError('Copying instances not supported')\n if verbose:\n print('{tl}Downloading {cls}'.format(\n tl=tab_level,\n cls=cls._resource_class\n ), end=': ')\n if isinstance(src, string_types):\n json = cls._json_from_uid(src, using=kwargs.get('using', None))\n else:\n json = src\n title = '' if json['title'] is None else json['title']\n desc = '' if json['description'] is None else json['description']\n if verbose:\n print(title)\n res = cls._build_from_json(json, copy=copy, tab_level=tab_level,\n title=title, description=desc, **kwargs)\n if not copy:\n res._upload_data = json\n if verbose:\n print('{}...Complete!'.format(tab_level))\n return res\n\n @classmethod\n def _build_from_json(cls, json, copy=True, tab_level='', **kwargs):\n raise NotImplementedError('Cannot build raw UserContent from json')\n\n\nclass BaseResource(UserContent):\n \"\"\"Base class for all resources that are added to projects and\n uploaded to steno3d\n \"\"\"\n\n def _get_dirty_data(self, force=False):\n datadict = super(BaseResource, self)._get_dirty_data(force)\n dirty = self._dirty\n if 'opts' in dirty or (force and hasattr(self, 'opts')):\n datadict['meta'] = self.opts._json\n return datadict\n\n\n def _validate_file_size(self, name, arr):\n if Comms.user.logged_in:\n file_limit = Comms.user.file_size_limit\n if self._nbytes(arr) > file_limit:\n raise FileSizeLimitExceeded(\n '{name} file size ({file} bytes) exceeds limit: '\n '{lim} bytes'.format(name=name,\n file=self._nbytes(arr),\n lim=file_limit)\n )\n return True\n\n\nclass CompositeResource(BaseResource):\n \"\"\"A composite resource that stores references to lower-level objects.\"\"\"\n project = properties.List(\n doc='Project containing the resource',\n prop=UserContent,\n coerce=True,\n default=list,\n )\n\n def __init__(self, project=None, **kwargs):\n if project is None:\n raise TypeError('Resource must be constructed with its '\n 'containing project(s)')\n super(CompositeResource, self).__init__(**kwargs)\n self.project = project\n\n @classmethod\n def _url_view_from_uid(cls, uid):\n \"\"\"Get full url from a uid\"\"\"\n url = '{base}{mapi}/{uid}'.format(\n base=Comms.base_url,\n mapi=cls._model_api_location,\n uid=uid)\n return url\n\n @properties.validator\n def _validate_proj(self):\n for proj in self.project:\n if self not in proj.resources:\n raise ValueError('Project/resource pointers misaligned: '\n 'Ensure that projects contain all the '\n 'resources that point to them.')\n return True\n\n\n @needs_login\n def upload(self, sync=False, verbose=True, print_url=True):\n \"\"\"Upload the resource through its containing project(s)\"\"\"\n for proj in self.project:\n proj.upload(sync=sync, verbose=verbose, print_url=False)\n if verbose and print_url:\n print(self._url)\n return self._url\n\n\n\n def _get_dirty_data(self, force=False):\n datadict = super(CompositeResource, self)._get_dirty_data(force)\n dirty = self._dirty_props\n if 'mesh' in dirty or force:\n datadict['mesh'] = dumps({\n 'uid': self.mesh._json['longUid']\n })\n if 'data' in dirty or force:\n datadict['data'] = dumps([\n {\n 'location': d.location,\n 'uid': d.data._json['longUid']\n } for d in self.data\n ])\n if 'textures' in dirty or (force and hasattr(self, 'textures')):\n datadict['textures'] = dumps([\n {\n 'uid': t._json['longUid']\n } for t in self.textures\n ])\n return datadict\n\n def _upload_dirty(self, **kwargs):\n dirty = self._dirty\n if 'mesh' in dirty:\n self.mesh._upload(**kwargs)\n if 'data' in dirty:\n [d.data._upload(**kwargs) for d in self.data]\n if 'textures' in dirty:\n [t._upload(**kwargs) for t in self.textures]\n\n @properties.observer('project')\n def _fix_proj_res(self, change):\n before = change['previous']\n after = change['value']\n if before in (None, properties.undefined):\n before = []\n if after in (None, properties.undefined):\n after = []\n for proj in after:\n if proj not in before and self not in proj.resources:\n proj.resources += [self]\n for proj in before:\n if proj not in after and self in proj.resources:\n proj.resources = [r for r in proj.resources\n if r is not self]\n if len(set(after)) != len(after):\n post_post = []\n for p in after:\n if p not in post_post:\n post_post += [p]\n self.project = post_post\n\n @property\n def _url(self):\n if getattr(self, '_upload_data', None) is not None:\n return self._url_view_from_uid(self._upload_data['uid'])\n\n @property\n @needs_login\n def url(self):\n \"\"\"steno3d.com url of project if uploaded\"\"\"\n if getattr(self, '_upload_data', None) is None:\n print('Resource not uploaded: Please upload() '\n 'before accessing the URL.')\n return self._url\n\n @needs_login\n def plot(self):\n \"\"\"Display the 3D representation of the content\"\"\"\n if getattr(self.project, '_upload_data', None) is None:\n print('Resource not uploaded: Please upload() '\n 'before plotting.')\n return\n return self.project.plot()\n\n @classmethod\n def _build_from_json(cls, json, copy=True, tab_level='', **kwargs):\n if 'project' not in kwargs:\n raise KeyError('Building CompositeResource from json requires '\n 'project input.')\n res = cls(\n project=kwargs['project'],\n title=kwargs['title'],\n description=kwargs['description'],\n opts=json['meta']\n )\n (mesh_string, mesh_uid) = (\n json['mesh']['uid'].split('Resource')[-1].split(':')\n )\n mesh_class = UserContent._REGISTRY[mesh_string]\n\n res.mesh = mesh_class._build(mesh_uid, copy, tab_level + ' ',\n using=kwargs.get('using', None))\n\n if 'textures' in json:\n res.textures = []\n for t in json['textures']:\n (tex_string, tex_uid) = (\n t['uid'].split('Resource')[-1].split(':')\n )\n tex_class = UserContent._REGISTRY[tex_string]\n res.textures += [tex_class._build(\n tex_uid, copy, tab_level + ' ',\n using=kwargs.get('using', None),\n )]\n\n if 'data' in json:\n res.data = []\n for d in json['data']:\n (data_string, data_uid) = (\n d['uid'].split('Resource')[-1].split(':')\n )\n data_class = UserContent._REGISTRY[data_string]\n res.data += [dict(\n location=d['location'],\n data=data_class._build(\n data_uid, copy, tab_level + ' ',\n using=kwargs.get('using', None),\n )\n )]\n\n return res\n\n @classmethod\n def _build_from_omf(cls, omf_element, omf_project, project, verbose=False):\n mesh_map = {\n 'PointSetGeometry': 'Mesh0D',\n 'LineSetGeometry': 'Mesh1D',\n 'SurfaceGeometry': 'Mesh2D',\n 'SurfaceGridGeometry': 'Mesh2DGrid',\n 'VolumeGridGeometry': 'Mesh3DGrid'\n }\n mesh_class = UserContent._REGISTRY[mesh_map[\n omf_element.geometry.__class__.__name__\n ]]\n res = cls(\n project=project,\n title=omf_element.name,\n description=omf_element.description,\n mesh=mesh_class._build_from_omf(omf_element.geometry, omf_project),\n opts={'color': omf_element.color}\n )\n if hasattr(omf_element, 'textures'):\n res.textures = []\n for tex in omf_element.textures:\n res.textures += [\n UserContent._REGISTRY['Texture2DImage']._build_from_omf(\n tex, omf_project\n )\n ]\n if hasattr(omf_element, 'data'):\n data_map = {\n 'ScalarData': 'DataArray',\n 'MappedData': 'DataCategory',\n }\n res.data = []\n for dat in omf_element.data:\n if dat.__class__.__name__ not in data_map:\n if verbose:\n print('Data of class {} ignored'.format(\n dat.__class__.__name__\n ))\n continue\n data_class = UserContent._REGISTRY[data_map[\n dat.__class__.__name__\n ]]\n res.data += [data_class._build_from_omf(dat)]\n return res\n\n\n\nclass BaseMesh(BaseResource):\n \"\"\"Base class for all mesh resources. These are contained within\n each composite resources and define its structure\n \"\"\"\n\n @properties.validator\n def _validate_mesh(self):\n if Comms.user.logged_in:\n file_limit = Comms.user.file_size_limit\n if self._nbytes() > file_limit:\n raise FileSizeLimitExceeded(\n '{name} size ({file} bytes) exceeds limit: '\n '{lim} bytes'.format(name=self.__class__.__name__,\n file=self._nbytes(),\n lim=file_limit)\n )\n return True\n\nclass BaseData(BaseResource):\n \"\"\"Base class for all data resources. These can be contained within\n each composite resource and define data corresponding to the mesh\n \"\"\"\n @classproperty\n @classmethod\n def _model_api_location(cls):\n \"\"\"api destination for texture resource\"\"\"\n if getattr(cls, '__model_api_location', None) is None:\n cls.__model_api_location = 'resource/data/{class_name}'.format(\n class_name=cls._resource_class)\n return cls.__model_api_location\n\n\nclass BaseTexture2D(BaseResource):\n \"\"\"Base class for all texture resources. These can be contained\n within some composite resources and define data in space that gets\n mapped to the mesh.\n \"\"\"\n @classproperty\n @classmethod\n def _model_api_location(cls):\n \"\"\"api destination for texture resource\"\"\"\n if getattr(cls, '__model_api_location', None) is None:\n cls.__model_api_location = 'resource/texture2d/{cls_name}'.format(\n cls_name=cls._resource_class)\n return cls.__model_api_location\n\n\nclass ResourceSizeError(Exception):\n \"\"\"Exception for exceeding size limits\"\"\"\n\n\nclass FileSizeLimitExceeded(ResourceSizeError):\n \"\"\"Exception when a file to upload exceeds limits\"\"\"\n\n\nclass ProjectResourceLimitExceeded(ResourceSizeError):\n \"\"\"Exception when number of resources in a project exceeds limits\"\"\"\n\n\nclass ProjectSizeLimitExceeded(ResourceSizeError):\n \"\"\"Exception when total size of project exceeds limits\"\"\"\n\n\nclass ProjectQuotaExceeded(Exception):\n \"\"\"Exception when an upload past the project quota is attempted\"\"\"\n\n\nclass UploadError(Exception):\n \"\"\"Exception when upload fails\"\"\"\n","sub_path":"steno3d/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":20032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"341128944","text":"import os\nimport sys\nimport cv2\nimport argparse\nimport real_time_face_recognition_v9 as model_detect\n\ndef runTest(args):\n total = 0\n right = 0\n unknown = 0\n detector = model_detect.Detector()\n for folder in os.listdir(path):\n folder_path = os.path.join(path,folder)\n for file in os.listdir(folder_path):\n total += 1\n file_path = os.path.join(folder_path,file)\n Image = cv2.imread(file_path)\n #这里加上人脸识别代码\n image,predict = detector.model_detect(Image, None) \n #结束\n if perdict == folder:\n right += 1\n elif predict == 'Unknown':\n unknown += 1\n #准确率\n accuracy = float(right / total)\n print(\"准确度:\", accuracy)\n #这里加上人脸识别代码\n loss = float(unknown / total)\n print(\"丢失值:\", loss)\n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n \n parser.add_argument('--testSet', type=str, help='Directory where to run the accuracy test.', default='./testset/')\n return parser.parse_args(argv)\n \n\nif __name__ == '__main__':\n runTest(parse_arguments(sys.argv[1:]))\n\n\n\n\n\n\n\n\n\n\n","sub_path":"data/testset_run.py","file_name":"testset_run.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"19340858","text":"#\n# Copyright (c) 2020-2021 Arm Limited and Contributors. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n\"\"\"Project management commands: new, import_, deploy and libs.\"\"\"\nimport os\nimport pathlib\n\nfrom typing import Any, List\n\nimport click\nimport tabulate\n\nfrom mbed_tools.project import initialise_project, import_project, get_known_libs, deploy_project\nfrom mbed_tools.project._internal import git_utils\n\n\n@click.command()\n@click.option(\"--create-only\", \"-c\", is_flag=True, show_default=True, help=\"Create a program without fetching mbed-os.\")\n@click.argument(\"path\", type=click.Path(resolve_path=True))\ndef new(path: str, create_only: bool) -> None:\n \"\"\"Creates a new Mbed project at the specified path. Downloads mbed-os and adds it to the project.\n\n PATH: Path to the destination directory for the project. Will be created if it does not exist.\n \"\"\"\n click.echo(f\"Creating a new Mbed program at path '{path}'.\")\n if not create_only:\n click.echo(\"Downloading mbed-os and adding it to the project.\")\n\n initialise_project(pathlib.Path(path), create_only)\n\n\n@click.command()\n@click.argument(\"url\")\n@click.argument(\"path\", type=click.Path(), default=\"\")\n@click.option(\n \"--skip-resolve-libs\",\n \"-s\",\n is_flag=True,\n show_default=True,\n help=\"Skip resolving program library dependencies after cloning.\",\n)\ndef import_(url: str, path: Any, skip_resolve_libs: bool) -> None:\n \"\"\"Clone an Mbed project and library dependencies.\n\n URL: The git url of the remote project to clone.\n\n PATH: Destination path for the clone. If not given the destination path is set to the project name in the cwd.\n \"\"\"\n click.echo(f\"Cloning Mbed program '{url}'\")\n if not skip_resolve_libs:\n click.echo(\"Resolving program library dependencies.\")\n\n if path:\n click.echo(f\"Destination path is '{path}'\")\n path = pathlib.Path(path)\n\n dst_path = import_project(url, path, not skip_resolve_libs)\n if not skip_resolve_libs:\n libs = get_known_libs(dst_path)\n _print_dependency_table(libs)\n\n\n@click.command()\n@click.argument(\"path\", type=click.Path(), default=os.getcwd())\n@click.option(\n \"--force\",\n \"-f\",\n is_flag=True,\n show_default=True,\n help=\"Forces checkout of all library repositories at specified commit in the .lib file, overwrites local changes.\",\n)\ndef deploy(path: str, force: bool) -> None:\n \"\"\"Checks out Mbed program library dependencies at the revision specified in the \".lib\" files.\n\n Ensures all dependencies are resolved and the versions are synchronised to the version specified in the library\n reference.\n\n PATH: Path to the Mbed project [default: CWD]\n \"\"\"\n click.echo(\"Checking out all libraries to revisions specified in .lib files. Resolving any unresolved libraries.\")\n root_path = pathlib.Path(path)\n deploy_project(root_path, force)\n libs = get_known_libs(root_path)\n _print_dependency_table(libs)\n\n\ndef _print_dependency_table(libs: List) -> None:\n click.echo(\"The following library dependencies were fetched: \\n\")\n table = []\n for lib in libs:\n table.append(\n [\n lib.reference_file.stem,\n lib.get_git_reference().repo_url,\n lib.source_code_path,\n git_utils.get_default_branch(git_utils.get_repo(lib.source_code_path))\n if not lib.get_git_reference().ref\n else lib.get_git_reference().ref,\n ]\n )\n\n headers = (\"Library Name\", \"Repository URL\", \"Path\", \"Git Reference\")\n click.echo(tabulate.tabulate(table, headers=headers))\n","sub_path":"src/mbed_tools/cli/project_management.py","file_name":"project_management.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"105960785","text":"import numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport pylab\n\nimport glob\n\ndef plotDIR(dir,distortion=3):\n\t''' pieplots all the TSVs in that directory '''\n\tfiles = glob.glob(dir+'/*.tsv')\n\tfor f in files:\n\t\tpieplot(f,distortion=distortion)\n\t\t#colplot(f)\n\t\t\ndef wrap(txt, linelength=15):\n\t'''turns a line of text into a wraped block'''\n\twords = txt.split()\n\tout = ''\n\tlength = 0\n\tfor word in words:\n\t\tif length > linelength:\n\t\t\tout +='\\n'\n\t\t\tlength = 0\n\t\tout += ' '+word\n\t\tlength += len(word)+1\n\treturn out\n\ndef color(txt):\n\t'''given a string returns a random number consistently'''\n\th = str(hash(txt)**4)\n\tr = float(h[-3:-1])/100\n\tg = float(h[-5:-3])/100\n\tb = float(h[-7:-5])/100\n\treturn r,g,b\ndef readTSV(tsv,wraplabel=10):\n\n\tf = open(tsv,'r')\n\texon = f.read()\n\tf.close()\n\tlines = exon.splitlines()\n\thead,data = lines[:2], lines[2:]\n\thead ='\\n'.join(head)\n\tvals , labels, colors = [],[],[]\n\tfor line in data:\n\t\tlabel,val = line.split('\\t')[:2]\n\t\tval = float(val)\n\t\tif val > 0:\n\t\t\tc = color(label)\n\t\t\tcolors.append(c)\n\t\t\tlabels.append(wrap(label.replace('_',' ')+' '+str(round(val,2)),wraplabel))\n\t\t\tvals.append(val)\n\treturn vals,labels,colors\n\t\ndef pieplot(tsv,show=False,distortion=3,wraplabel=10):\n\t'''pieplots atsv file with a header'''\n\tf = open(tsv,'r')\n\texon = f.read()\n\tf.close()\n\tlines = exon.splitlines()\n\thead,data = lines[:2], lines[2:]\n\thead ='\\n'.join(head)\n\tvals , labels, colors = [],[],[]\n\tfor line in data:\n\t\tlabel,val = line.split('\\t')[:2]\n\t\tval = float(val)\n\t\tif val > 0:\n\t\t\tc = color(label)\n\t\t\tcolors.append(c)\n\t\t\tlabels.append(wrap(label.replace('_',' ')+' '+str(round(val,2)),wraplabel))\n\t\t\tvals.append(val**distortion)\n\tpylab.close('all')\n\t#pylab.figure(figsize=(13,13))\n\tax = pylab.axes(aspect=1)\n\t#f, ax = pylab.subplots(figsize(10,10))\n\tpylab.pie(vals, labels=labels,colors=colors,)\n\tax.set_title(head)\n\tfname = tsv[:-4]+'_pie.png'\n\tpylab.savefig(fname)\n\tif show:pylab.show()\n\t\ndef colplot(tsv):\n\tvals,labels,colors = readTSV(tsv,wraplabel=1000)\n\tpylab.close('all')\n\tpylab.figure(figsize=[.7+len(vals),10])\n\tax = pylab.axes()\n\tindex = np.arange(len(vals))\n\tbarwidth = 1\n\tax.bar(index,\n\t\tvals,\n\t\twidth=barwidth,\n\t\t)\n\tpylab.xticks(index+barwidth,labels,rotation=90)\n\tfname = tsv[:-4]+'_bar.png'\n\tpylab.savefig(fname,dpi=200)\n\ndef main():\n\timport sys\n\tdir = sys.argv[-2]\n\tdistortion = sys.argv[-1]\n\tplotDIR(dir)\n\nif __name__==\"__main__\": main()\n","sub_path":"eon/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"580693056","text":"import requests\nimport json\n\ndef checkIfMessageIsGreeting(message):\n\tif message.startswith('hi') or message.startswith('hey') or message.startswith('hello'):\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef sendReplyToGreeting(params, sender_id):\n\theaders = {\n\t\t\"Content-Type\": \"application/json\"\n\t\t}\n\t\t\n\tdata = json.dumps({\n\t\t\t'recipient': {\n\t\t\t\t'id': sender_id\n\t\t\t},\n\t\t\t'message': {\"text\":\"Hey there! I'll help you with recent news doing the rounds around any topic. Just type in some keywords you would want to fetch news for.\"}\n\t})\n\tr = requests.post(\"https://graph.facebook.com/me/messages\", params=params, headers=headers, data=data)\n\tif r.status_code != 200:\n\t\tprint(r.status_code)\n\t\tprint(r.text)\n\treturn \"ok\"","sub_path":"zebra/packages/default/webhook/greeting.py","file_name":"greeting.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"485710069","text":"# Support for funding txs.\nfrom typing import Tuple, Any, Optional, Union, Callable, Dict, List\nfrom .utils import Side, privkey_expand, regtest_hash\nfrom .event import Event, ResolvableInt, ResolvableStr\nfrom .namespace import namespace\nfrom .runner import Runner\nfrom .signature import Sig\nfrom pyln.proto.message import Message\nfrom hashlib import sha256\nimport coincurve\nimport io\nfrom bitcoin.core import COutPoint, CScript, CTxIn, CTxOut, CMutableTransaction, CTxWitness, CTxInWitness, CScriptWitness, Hash160, CTransaction\nimport bitcoin.core.script as script\nfrom bitcoin.wallet import P2WPKHBitcoinAddress\n\nResolvableFunding = Union['Funding', Callable[['Runner', 'Event', str], 'Funding']]\n\n\ndef txid_raw(tx: str) -> str:\n \"\"\"Helper to get the txid of a tx: note this is in wire protocol order, not bitcoin order!\"\"\"\n return CTransaction.deserialize(bytes.fromhex(tx)).GetTxid().hex()\n\n\nclass Funding(object):\n def __init__(self,\n funding_txid: str,\n funding_output_index: int,\n funding_amount: int,\n local_node_privkey: str,\n local_funding_privkey: str,\n remote_node_privkey: str,\n remote_funding_privkey: str,\n chain_hash: str = regtest_hash,\n locktime: int = 0):\n self.chain_hash = chain_hash\n self.txid = funding_txid\n self.output_index = funding_output_index\n self.amount = funding_amount\n self.bitcoin_privkeys = [privkey_expand(local_funding_privkey),\n privkey_expand(remote_funding_privkey)]\n self.node_privkeys = [privkey_expand(local_node_privkey),\n privkey_expand(remote_node_privkey)]\n self.tx = None\n self.locktime = locktime\n self.outputs: List[Dict[str, Any]] = []\n self.inputs: List[Dict[str, Any]] = []\n\n def tx_hex(self) -> str:\n if not self.tx:\n return ''\n return self.tx.serialize().hex()\n\n @staticmethod\n def sort_by_keys(key_one: coincurve.PublicKey, key_two: coincurve.PublicKey,\n val_one: Any, val_two: Any) -> Tuple[Any, Any]:\n \"\"\"In many places we have to sort elements into key or nodeid order\"\"\"\n # BOLT #3:\n # ## Funding Transaction Output\n #\n # * The funding output script is a P2WSH to: `2 2\n # OP_CHECKMULTISIG`\n # * Where `pubkey1` is the lexicographically lesser of the two\n # `funding_pubkey` in compressed format, and where `pubkey2` is the\n # lexicographically greater of the two.\n if key_one.format() < key_two.format():\n return val_one, val_two\n else:\n return val_two, val_one\n\n def node_id_sort(self, local: Any, remote: Any) -> Tuple[Any, Any]:\n \"\"\"Sorts these two items into lexicographical node id order\"\"\"\n # BOLT #7:\n # - MUST set `node_id_1` and `node_id_2` to the public keys of the two\n # nodes operating the channel, such that `node_id_1` is the\n # lexicographically-lesser of the two compressed keys sorted in\n # ascending lexicographic order.\n return self.sort_by_keys(self.node_id(Side.local),\n self.node_id(Side.remote),\n local, remote)\n\n @staticmethod\n def redeemscript_keys(key_one: coincurve.PublicKey, key_two: coincurve.PublicKey) -> CScript:\n return CScript([script.OP_2]\n + [k.format() for k in Funding.sort_by_keys(key_one, key_two, key_one, key_two)]\n + [script.OP_2,\n script.OP_CHECKMULTISIG])\n\n def redeemscript(self) -> CScript:\n key_a, key_b = self.funding_pubkeys_for_tx()\n return self.redeemscript_keys(key_a, key_b)\n\n @staticmethod\n def locking_script_keys(key_one: coincurve.PublicKey, key_two: coincurve.PublicKey) -> CScript:\n return CScript([script.OP_0, sha256(Funding.redeemscript_keys(key_one, key_two)).digest()])\n\n def locking_script(self) -> CScript:\n a, b = self.funding_pubkeys_for_tx()\n return self.locking_script_keys(a, b)\n\n @staticmethod\n def start(local_node_privkey: str,\n local_funding_privkey: str,\n remote_node_privkey: str,\n remote_funding_privkey: str,\n funding_sats: int,\n locktime: int,\n chain_hash: str = regtest_hash) -> 'Funding':\n\n # Create dummy one to start: we will fill in txid at the end\n return Funding('', 0, funding_sats,\n local_node_privkey,\n local_funding_privkey,\n remote_node_privkey,\n remote_funding_privkey,\n chain_hash, locktime)\n\n def add_input(self,\n serial_id: int,\n prevtx: str,\n prevtx_vout: int,\n script_sig: str,\n sequence: int,\n privkey: str = None) -> None:\n # the dummy runner sends empty info, skip\n if len(prevtx) == 0:\n return\n\n # Find the txid of the transaction\n prev_tx = CTransaction.deserialize(bytes.fromhex(prevtx))\n txin = CTxIn(COutPoint(prev_tx.GetTxid(), prevtx_vout),\n nSequence=sequence)\n\n # Get the previous output for its outscript + value\n prev_vout = prev_tx.vout[prevtx_vout]\n\n self.inputs.append({'input': txin,\n 'serial_id': serial_id,\n 'sats': prev_vout.nValue,\n 'prev_outscript': prev_vout.scriptPubKey.hex(),\n 'redeemscript': script_sig,\n 'privkey': privkey,\n })\n\n def add_output(self,\n serial_id: int,\n script: str,\n sats: int) -> None:\n txout = CTxOut(sats, CScript(bytes.fromhex(script)))\n self.outputs.append({'output': txout,\n 'serial_id': serial_id})\n\n def our_witnesses(self) -> str:\n \"\"\" Extract expected witness data for our node \"\"\"\n witnesses = []\n # these were sorted in `build_tx`\n for _in in self.inputs:\n if not _in['privkey']:\n continue\n\n wit = _in['sig']\n print('witness is ... ', wit)\n elems = []\n for e in wit.scriptWitness.stack:\n elems.append('{{witness={0}}}'.format(e.hex()))\n witnesses.append('{{witness_element=[{0}]}}'.format(','.join(elems)))\n val = '[{}]'.format(','.join(witnesses))\n print('witnesses are', val)\n return val\n\n def sign_our_inputs(self) -> None:\n assert self.tx is not None\n for idx, _in in enumerate(self.inputs):\n privkey = _in['privkey']\n\n if privkey and 'sig' not in _in:\n print('signing our input for tx', self.tx.serialize().hex())\n inkey = privkey_expand(privkey)\n inkey_pub = coincurve.PublicKey.from_secret(inkey.secret)\n\n # Really horrid hack to produce a signature for the\n # multisig utxo in tests/helpers.py\n if privkey == '38204720bc4f9647fd58c6d0a4bd3a6dd2be16d8e4273c4d1bdd5774e8c51eaf':\n redeemscript = bytes.fromhex('51210253cdf835e328346a4f19de099cf3d42d4a7041e073cd4057a1c4fd7cdbb1228f2103ae903722f21f85e651b8f9b18fc854084fb90eeb76452bdcfd0cb43a16a382a221036c264d68a9727afdc75949f7d7fa71910ae9ae8001a1fbffa6f7ce000976597c21036429fa8a4ef0b2b1d5cb553e34eeb90a32ab19fae1f0024f332ab4f74283a7282103d4232f19ea85051e7b76bf5f01d03e17eea8751463dee36d71413a739de1a92755ae')\n else:\n address = P2WPKHBitcoinAddress.from_scriptPubKey(CScript([script.OP_0, Hash160(inkey_pub.format())]))\n redeemscript = address.to_redeemScript()\n\n sighash = script.SignatureHash(redeemscript,\n self.tx, idx, script.SIGHASH_ALL,\n amount=_in['sats'],\n sigversion=script.SIGVERSION_WITNESS_V0)\n sig = inkey.sign(sighash, hasher=None) + bytes([script.SIGHASH_ALL])\n\n if privkey == '38204720bc4f9647fd58c6d0a4bd3a6dd2be16d8e4273c4d1bdd5774e8c51eaf':\n _in['sig'] = CTxInWitness(CScriptWitness([bytes([]), sig, redeemscript]))\n else:\n _in['sig'] = CTxInWitness(CScriptWitness([sig, inkey_pub.format()]))\n\n def add_witnesses(self, witness_stack: List[Dict[str, Any]]) -> str:\n assert self.tx is not None\n wits = []\n for idx, _in in enumerate(self.inputs):\n if 'sig' in _in:\n wits.append(_in['sig'])\n continue\n\n if not len(witness_stack):\n continue\n\n elems = witness_stack.pop(0)['witness_element']\n stack = []\n for elem in elems:\n stack.append(bytes.fromhex(elem['witness']))\n\n wits.append(CTxInWitness(CScriptWitness(stack)))\n\n self.tx.wit = CTxWitness(wits)\n return self.tx.serialize().hex()\n\n def build_tx(self) -> str:\n # Sort inputs/outputs by serial number\n self.inputs = sorted(self.inputs, key=lambda k: k['serial_id'])\n self.outputs = sorted(self.outputs, key=lambda k: k['serial_id'])\n\n self.tx = CMutableTransaction([i['input'] for i in self.inputs],\n [o['output'] for o in self.outputs],\n nVersion=2, nLockTime=self.locktime)\n assert self.tx is not None\n self.txid = self.tx.GetTxid().hex()\n\n # Set the output index for the funding output\n locking_script = self.locking_script()\n for i, out in enumerate([o['output'] for o in self.outputs]):\n if out.scriptPubKey == locking_script:\n self.output_index = i\n self.amount = out.nValue\n\n return self.tx.serialize().hex()\n\n @staticmethod\n def from_utxo(txid_in: str,\n tx_index_in: int,\n sats: int,\n privkey: str,\n fee: int,\n local_node_privkey: str,\n local_funding_privkey: str,\n remote_node_privkey: str,\n remote_funding_privkey: str,\n chain_hash: str = regtest_hash) -> Tuple['Funding', str]:\n \"\"\"Make a funding transaction by spending this utxo using privkey: return Funding, tx.\"\"\"\n\n # Create dummy one to start: we will fill in txid at the end.\n funding = Funding('', 0, sats - fee,\n local_node_privkey,\n local_funding_privkey,\n remote_node_privkey,\n remote_funding_privkey,\n chain_hash)\n\n # input private key.\n inkey = privkey_expand(privkey)\n inkey_pub = coincurve.PublicKey.from_secret(inkey.secret)\n\n # use RBF'able input (requirement for dual-funded things)\n txin = CTxIn(COutPoint(bytes.fromhex(txid_in), tx_index_in), nSequence=0xFFFFFFFD)\n txout = CTxOut(sats - fee, CScript([script.OP_0, sha256(funding.redeemscript()).digest()]))\n tx = CMutableTransaction([txin], [txout], nVersion=2, nLockTime=funding.locktime)\n\n # now fill in funding txid.\n funding.txid = tx.GetTxid().hex()\n funding.tx = tx\n\n # while we're here, sign the transaction.\n address = P2WPKHBitcoinAddress.from_scriptPubKey(CScript([script.OP_0, Hash160(inkey_pub.format())]))\n\n sighash = script.SignatureHash(address.to_redeemScript(),\n tx, 0, script.SIGHASH_ALL, amount=sats,\n sigversion=script.SIGVERSION_WITNESS_V0)\n sig = inkey.sign(sighash, hasher=None) + bytes([script.SIGHASH_ALL])\n\n tx.wit = CTxWitness([CTxInWitness(CScriptWitness([sig, inkey_pub.format()]))])\n return funding, tx.serialize().hex()\n\n def channel_id(self) -> str:\n # BOLT #2: This message introduces the `channel_id` to identify the\n # channel. It's derived from the funding transaction by combining the\n # `funding_txid` and the `funding_output_index`, using big-endian\n # exclusive-OR (i.e. `funding_output_index` alters the last 2 bytes).\n chanid = bytearray.fromhex(self.txid)\n chanid[-1] ^= self.output_index % 256\n chanid[-2] ^= self.output_index // 256\n return chanid.hex()\n\n @staticmethod\n def funding_pubkey_key(privkey: coincurve.PrivateKey) -> coincurve.PublicKey:\n return coincurve.PublicKey.from_secret(privkey.secret)\n\n def funding_pubkey(self, side: Side) -> coincurve.PublicKey:\n return self.funding_pubkey_key(self.bitcoin_privkeys[side])\n\n def funding_pubkeys_for_tx(self) -> Tuple[coincurve.PublicKey, coincurve.PublicKey]:\n \"\"\"Returns funding pubkeys, in tx order\"\"\"\n # BOLT #3:\n # ## Funding Transaction Output\n #\n # * The funding output script is a P2WSH to: `2 2\n # OP_CHECKMULTISIG`\n # * Where `pubkey1` is the lexicographically lesser of the two\n # `funding_pubkey` in compressed format, and where `pubkey2` is the\n # lexicographically greater of the two.\n return self.sort_by_keys(self.funding_pubkey(Side.local),\n self.funding_pubkey(Side.remote),\n self.funding_pubkey(Side.local),\n self.funding_pubkey(Side.remote))\n\n def funding_privkeys_for_tx(self) -> Tuple[coincurve.PrivateKey, coincurve.PrivateKey]:\n \"\"\"Returns funding private keys, in tx order\"\"\"\n return self.sort_by_keys(self.funding_pubkey(Side.local),\n self.funding_pubkey(Side.remote),\n self.bitcoin_privkeys[Side.local],\n self.bitcoin_privkeys[Side.remote])\n\n def node_id(self, side: Side) -> coincurve.PublicKey:\n return coincurve.PublicKey.from_secret(self.node_privkeys[side].secret)\n\n def node_ids(self) -> Tuple[coincurve.PublicKey, coincurve.PublicKey]:\n \"\"\"Returns node pubkeys, in order\"\"\"\n return self.node_id_sort(self.node_id(Side.local),\n self.node_id(Side.remote))\n\n def node_id_privkeys(self) -> Tuple[coincurve.PrivateKey, coincurve.PrivateKey]:\n \"\"\"Returns node private keys, in order\"\"\"\n return self.node_id_sort(self.node_privkeys[Side.local],\n self.node_privkeys[Side.remote])\n\n def funding_pubkeys_for_gossip(self) -> Tuple[coincurve.PublicKey, coincurve.PublicKey]:\n \"\"\"Returns funding public keys, in gossip order\"\"\"\n return self.node_id_sort(self.funding_pubkey(Side.local),\n self.funding_pubkey(Side.remote))\n\n def funding_privkeys_for_gossip(self) -> Tuple[coincurve.PublicKey, coincurve.PublicKey]:\n \"\"\"Returns funding private keys, in gossip order\"\"\"\n return self.node_id_sort(self.bitcoin_privkeys[Side.local],\n self.bitcoin_privkeys[Side.remote])\n\n def _unsigned_channel_announcment(self,\n features: str,\n short_channel_id: str) -> Message:\n \"\"\"Produce a channel_announcement message with dummy sigs\"\"\"\n node_ids = self.node_ids()\n bitcoin_keys = self.funding_pubkeys_for_gossip()\n return Message(namespace().get_msgtype('channel_announcement'),\n node_signature_1=Sig(bytes(64)),\n node_signature_2=Sig(bytes(64)),\n bitcoin_signature_1=Sig(bytes(64)),\n bitcoin_signature_2=Sig(bytes(64)),\n features=features,\n chain_hash=self.chain_hash,\n short_channel_id=short_channel_id,\n node_id_1=node_ids[0].format(),\n node_id_2=node_ids[1].format(),\n bitcoin_key_1=bitcoin_keys[0].format(),\n bitcoin_key_2=bitcoin_keys[1].format())\n\n def channel_announcement(self,\n short_channel_id: str,\n features: str) -> Message:\n \"\"\"Produce a (signed) channel_announcement message\"\"\"\n ann = self._unsigned_channel_announcment(features, short_channel_id)\n # BOLT #7:\n # - MUST compute the double-SHA256 hash `h` of the message, beginning\n # at offset 256, up to the end of the message.\n # - Note: the hash skips the 4 signatures but hashes the rest of the\n # message, including any future fields appended to the end.\n buf = io.BytesIO()\n ann.write(buf)\n # Note the first two 'type' bytes!\n h = sha256(sha256(buf.getvalue()[2 + 256:]).digest()).digest()\n\n # BOLT #7:\n # - MUST set `node_signature_1` and `node_signature_2` to valid\n # signatures of the hash `h` (using `node_id_1` and `node_id_2`'s\n # respective secrets).\n node_privkeys = self.node_id_privkeys()\n ann.set_field('node_signature_1', Sig(node_privkeys[0].secret.hex(), h.hex()))\n ann.set_field('node_signature_2', Sig(node_privkeys[1].secret.hex(), h.hex()))\n\n bitcoin_privkeys = self.funding_privkeys_for_gossip()\n # - MUST set `bitcoin_signature_1` and `bitcoin_signature_2` to valid\n # signatures of the hash `h` (using `bitcoin_key_1` and\n # `bitcoin_key_2`'s respective secrets).\n ann.set_field('bitcoin_signature_1', Sig(bitcoin_privkeys[0].secret.hex(), h.hex()))\n ann.set_field('bitcoin_signature_2', Sig(bitcoin_privkeys[1].secret.hex(), h.hex()))\n\n return ann\n\n def channel_update(self,\n short_channel_id: str,\n side: Side,\n disable: bool,\n cltv_expiry_delta: int,\n htlc_minimum_msat: int,\n fee_base_msat: int,\n fee_proportional_millionths: int,\n timestamp: int,\n htlc_maximum_msat: Optional[int]) -> Message:\n # BOLT #7: The `channel_flags` bitfield is used to indicate the\n # direction of the channel: it identifies the node that this update\n # originated from and signals various options concerning the\n # channel. The following table specifies the meaning of its individual\n # bits:\n #\n # | Bit Position | Name | Meaning |\n # | ------------- | ----------- | -------------------------------- |\n # | 0 | `direction` | Direction this update refers to. |\n # | 1 | `disable` | Disable the channel. |\n\n # BOLT #7:\n # - if the origin node is `node_id_1` in the message:\n # - MUST set the `direction` bit of `channel_flags` to 0.\n # - otherwise:\n # - MUST set the `direction` bit of `channel_flags` to 1.\n if self.funding_pubkey(side) == self.funding_pubkeys_for_gossip()[0]:\n channel_flags = 0\n else:\n channel_flags = 1\n\n if disable:\n channel_flags |= 2\n\n # BOLT #7: The `message_flags` bitfield is used to indicate the\n # presence of optional fields in the `channel_update` message:\n #\n # | Bit Position | Name | Field |\n # | ------------- | ------------------------- | -------------------------------- |\n # | 0 | `option_channel_htlc_max` | `htlc_maximum_msat` |\n message_flags = 0\n if htlc_maximum_msat:\n message_flags |= 1\n\n # Begin with a fake signature.\n update = Message(namespace().get_msgtype('channel_update'),\n short_channel_id=short_channel_id,\n signature=Sig(bytes(64)),\n chain_hash=self.chain_hash,\n timestamp=timestamp,\n message_flags=message_flags,\n channel_flags=channel_flags,\n cltv_expiry_delta=cltv_expiry_delta,\n htlc_minimum_msat=htlc_minimum_msat,\n fee_base_msat=fee_base_msat,\n fee_proportional_millionths=fee_proportional_millionths)\n if htlc_maximum_msat:\n update.set_field('htlc_maximum_msat', htlc_maximum_msat)\n\n # BOLT #7:\n # - MUST set `signature` to the signature of the double-SHA256 of the\n # entire remaining packet after `signature`, using its own `node_id`.\n buf = io.BytesIO()\n update.write(buf)\n # Note the first two 'type' bytes!\n h = sha256(sha256(buf.getvalue()[2 + 64:]).digest()).digest()\n\n update.set_field('signature', Sig(self.node_privkeys[side].secret.hex(), h.hex()))\n\n return update\n\n def node_announcement(self,\n side: Side,\n features: str,\n rgb_color: Tuple[int, int, int],\n alias: str,\n addresses: bytes,\n timestamp: int) -> Message:\n # Begin with a fake signature.\n ann = Message(namespace().get_msgtype('node_announcement'),\n signature=Sig(bytes(64)),\n features=features,\n timestamp=timestamp,\n node_id=self.node_id(side).format().hex(),\n rgb_color=bytes(rgb_color).hex(),\n alias=bytes(alias, encoding='utf-8').zfill(32),\n addresses=addresses)\n\n # BOLT #7:\n # - MUST set `signature` to the signature of the double-SHA256 of the entire\n # remaining packet after `signature` (using the key given by `node_id`).\n buf = io.BytesIO()\n ann.write(buf)\n # Note the first two 'type' bytes!\n h = sha256(sha256(buf.getvalue()[2 + 64:]).digest()).digest()\n\n ann.set_field('signature', Sig(self.node_privkeys[side].secret.hex(), h.hex()))\n return ann\n\n def close_tx(self, fee: int, privkey_dest: str) -> str:\n \"\"\"Create a (mutual) close tx\"\"\"\n txin = CTxIn(COutPoint(bytes.fromhex(self.txid), self.output_index))\n\n out_privkey = privkey_expand(privkey_dest)\n\n txout = CTxOut(self.amount - fee,\n CScript([script.OP_0,\n Hash160(coincurve.PublicKey.from_secret(out_privkey.secret).format())]))\n\n tx = CMutableTransaction(vin=[txin], vout=[txout])\n sighash = script.SignatureHash(self.redeemscript(), tx, inIdx=0,\n hashtype=script.SIGHASH_ALL,\n amount=self.amount,\n sigversion=script.SIGVERSION_WITNESS_V0)\n\n sigs = [key.sign(sighash, hasher=None) for key in self.funding_privkeys_for_tx()]\n # BOLT #3:\n # ## Closing Transaction\n # ...\n # * `txin[0]` witness: `0 `\n witness = CScriptWitness([bytes(),\n sigs[0] + bytes([script.SIGHASH_ALL]),\n sigs[1] + bytes([script.SIGHASH_ALL]),\n self.redeemscript()])\n tx.wit = CTxWitness([CTxInWitness(witness)])\n return tx.serialize().hex()\n\n\nclass AcceptFunding(Event):\n \"\"\"Event to accept funding information from a peer. Stashes 'Funding'.\"\"\"\n def __init__(self,\n funding_txid: ResolvableStr,\n funding_output_index: ResolvableInt,\n funding_amount: ResolvableInt,\n local_node_privkey: ResolvableStr,\n local_funding_privkey: ResolvableStr,\n remote_node_privkey: ResolvableStr,\n remote_funding_privkey: ResolvableStr,\n chain_hash: str = regtest_hash):\n super().__init__()\n self.funding_txid = funding_txid\n self.funding_output_index = funding_output_index\n self.funding_amount = funding_amount\n self.local_node_privkey = local_node_privkey\n self.local_funding_privkey = local_funding_privkey\n self.remote_node_privkey = remote_node_privkey\n self.remote_funding_privkey = remote_funding_privkey\n self.chain_hash = chain_hash\n\n def action(self, runner: Runner) -> bool:\n super().action(runner)\n\n funding = Funding(chain_hash=self.chain_hash,\n **self.resolve_args(runner,\n {'funding_txid': self.funding_txid,\n 'funding_output_index': self.funding_output_index,\n 'funding_amount': self.funding_amount,\n 'local_node_privkey': self.local_node_privkey,\n 'local_funding_privkey': self.local_funding_privkey,\n 'remote_node_privkey': self.remote_node_privkey,\n 'remote_funding_privkey': self.remote_funding_privkey}))\n runner.add_stash('Funding', funding)\n return True\n\n\nclass CreateFunding(Event):\n \"\"\"Event to create a funding tx from a P2WPKH UTXO. Stashes 'Funding' and 'FundingTx'.\"\"\"\n def __init__(self,\n txid_in: str,\n tx_index_in: int,\n sats_in: int,\n spending_privkey: str,\n fee: int,\n local_node_privkey: ResolvableStr,\n local_funding_privkey: ResolvableStr,\n remote_node_privkey: ResolvableStr,\n remote_funding_privkey: ResolvableStr,\n chain_hash: str = regtest_hash):\n super().__init__()\n self.txid_in = txid_in\n self.tx_index_in = tx_index_in\n self.sats_in = sats_in\n self.spending_privkey = spending_privkey\n self.fee = fee\n self.local_node_privkey = local_node_privkey\n self.local_funding_privkey = local_funding_privkey\n self.remote_node_privkey = remote_node_privkey\n self.remote_funding_privkey = remote_funding_privkey\n self.chain_hash = chain_hash\n\n def action(self, runner: Runner) -> bool:\n super().action(runner)\n\n funding, tx = Funding.from_utxo(self.txid_in,\n self.tx_index_in,\n self.sats_in,\n self.spending_privkey,\n self.fee,\n chain_hash=self.chain_hash,\n **self.resolve_args(runner,\n {'local_node_privkey': self.local_node_privkey,\n 'local_funding_privkey': self.local_funding_privkey,\n 'remote_node_privkey': self.remote_node_privkey,\n 'remote_funding_privkey': self.remote_funding_privkey}))\n\n runner.add_stash('Funding', funding)\n runner.add_stash('FundingTx', tx)\n return True\n\n\nclass CreateDualFunding(Event):\n \"\"\"Event to create a 'dual-funded' funding tx. Stashes 'Funding'\"\"\"\n def __init__(self,\n fee: int,\n funding_sats: ResolvableInt,\n locktime: ResolvableInt,\n local_node_privkey: str,\n local_funding_privkey: str,\n remote_node_privkey: str,\n remote_funding_privkey: ResolvableStr,\n chain_hash: str = regtest_hash):\n super().__init__()\n\n self.funding_sats = funding_sats\n self.locktime = locktime\n self.local_node_privkey = local_node_privkey\n self.local_funding_privkey = local_funding_privkey\n self.remote_node_privkey = remote_node_privkey\n self.remote_funding_privkey = remote_funding_privkey\n self.chain_hash = chain_hash\n\n def action(self, runner: Runner) -> bool:\n super().action(runner)\n\n funding = Funding.start(local_node_privkey=self.local_node_privkey,\n local_funding_privkey=self.local_funding_privkey,\n chain_hash=self.chain_hash,\n **self.resolve_args(runner,\n {\n 'funding_sats': self.funding_sats,\n 'remote_funding_privkey': self.remote_funding_privkey,\n 'remote_node_privkey': self.remote_node_privkey,\n 'locktime': self.locktime\n }))\n\n runner.add_stash('Funding', funding)\n\n return True\n\n\nclass AddInput(Event):\n def __init__(self,\n funding: ResolvableFunding,\n serial_id: ResolvableInt,\n prevtx: ResolvableStr,\n prevtx_vout: ResolvableInt,\n script_sig: ResolvableStr,\n sequence: ResolvableInt = 0xFFFFFFFD,\n privkey: str = None):\n super().__init__()\n self.funding = funding\n self.privkey = privkey\n self.serial_id = serial_id\n self.prevtx = prevtx\n self.prevtx_vout = prevtx_vout\n self.script_sig = script_sig\n self.sequence = sequence\n\n def action(self, runner: Runner) -> bool:\n super().action(runner)\n funding = self.resolve_arg('funding', runner, self.funding)\n funding.add_input(**self.resolve_args(runner,\n {'serial_id': self.serial_id,\n 'prevtx': self.prevtx,\n 'prevtx_vout': self.prevtx_vout,\n 'script_sig': self.script_sig,\n 'sequence': self.sequence,\n 'privkey': self.privkey}))\n return True\n\n\nclass AddOutput(Event):\n def __init__(self,\n funding: ResolvableFunding,\n serial_id: ResolvableInt,\n sats: ResolvableInt,\n script: ResolvableStr):\n super().__init__()\n self.funding = funding\n self.serial_id = serial_id\n self.sats = sats\n self.script = script\n\n def action(self, runner: Runner) -> bool:\n super().action(runner)\n funding = self.resolve_arg('funding', runner, self.funding)\n funding.add_output(**self.resolve_args(runner,\n {'serial_id': self.serial_id,\n 'sats': self.sats,\n 'script': self.script}))\n return True\n\n\nclass FinalizeFunding(Event):\n def __init__(self, funding: ResolvableFunding):\n self.funding = funding\n\n def action(self, runner: Runner) -> bool:\n funding = self.resolve_arg('funding', runner, self.funding)\n\n tx = funding.build_tx()\n funding.sign_our_inputs()\n # FIXME: sanity checks?\n print('finalized funding', tx)\n return True\n\n\nclass AddWitnesses(Event):\n def __init__(self,\n funding: ResolvableFunding,\n witness_stack: Union[List[Dict[str, Any]],\n Callable[['Runner', 'Event', str],\n List[Dict[str, Any]]]]):\n self.funding = funding\n self.witness_stack = witness_stack\n\n def action(self, runner: Runner) -> bool:\n funding = self.resolve_arg('funding', runner, self.funding)\n stack = self.resolve_arg('witness_stack', runner, self.witness_stack)\n # FIXME: is there a way to resolve this more .. nicely?\n # Convert from string to python obj\n wit_stack = eval(stack)\n tx_hex = funding.add_witnesses(wit_stack)\n runner.add_stash('FundingTx', tx_hex)\n return True\n","sub_path":"lnprototest/funding.py","file_name":"funding.py","file_ext":"py","file_size_in_byte":33161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"611028127","text":"\"\"\"\nView Component of the application\n\"\"\"\n\nimport logging\nimport types\nimport tkinter\n\nfrom main_panel import fill_word_word, fill_idiom_word, fill_idiom_idiom\nfrom side_panel import SidePanel\n\n\nclass View(object):\n \"\"\"View class\"\"\"\n\n def __init__(self, root, debug=False, scaling=2.0):\n self.debug = debug\n self.root = root\n self.current_action = \"word_word\"\n self.scaling = scaling\n self.root.tk.call('tk', 'scaling', self.scaling)\n self.main_panel = None\n self.create_base()\n\n def load_data(self):\n \"\"\"Loads the necessary data for the GUI\"\"\"\n if self.debug:\n print(\"Loading data\")\n\n def create_base(self):\n \"\"\"Creates the base for the root window\"\"\"\n if self.debug:\n print(\"Creating base\")\n self.console_panel = ConsolePanel(self.root)\n self.side_panel = SidePanel(self.root, self.populate_main_panel)\n self.side_panel.set_separator(\"word_word\")\n self.main_panel = MainPanel(self.root, action=\"word_word\")\n\n def populate_main_panel(self, action: str):\n \"\"\"Populates the main panel depending on the desired option\"\"\"\n self.main_panel.destroy()\n\n actions = dict(\n word_word=fill_word_word,\n idiom_word=fill_idiom_word,\n idiom_idiom=fill_idiom_idiom)\n\n self.main_panel = MainPanel(self.root, action, actions[action])\n self.side_panel.set_separator(action)\n self.current_action = action\n\n\nclass MainPanel():\n \"\"\"Main panel\"\"\"\n\n def __init__(self, root, action=\"\", func=None):\n self.action = action\n self.frame = tkinter.Frame(root, name=action)\n self.frame.grid(row=0, column=2)\n self.items = {}\n if func is not None:\n self.fill_panel = types.MethodType(func, self)\n self.fill_panel()\n\n def fill_panel(self):\n \"\"\"Fills the panel\"\"\"\n text = \" Select a query form\"\n tkinter.Label(self.frame, text=text).grid(row=1)\n\n def get_inputs(self):\n \"\"\"Gets the inputs from the frame\"\"\"\n for widget in self.frame.winfo_children():\n if isinstance(widget, tkinter.Entry):\n entry_name = str(widget).split('.')[-1]\n entry_value = widget.get()\n self.items[entry_name] = entry_value\n return self.items\n\n def set_inputs(self, inputs: dict):\n \"\"\"Sets the values displayed on the frame\"\"\"\n for name in inputs:\n try:\n self.frame.nametowidget(name).delete(0, tkinter.END)\n self.frame.nametowidget(name).insert(0, inputs[name])\n except BaseException:\n continue\n\n def reset_inputs(self):\n \"\"\"Sets the values displayed on the frame\"\"\"\n for widget in self.frame.winfo_children():\n if isinstance(widget, tkinter.Entry):\n widget.delete(0, tkinter.END)\n widget.insert(0, \"\")\n elif isinstance(widget, tkinter.Checkbutton):\n widget.deselect()\n\n def destroy(self):\n \"\"\"Destroys the frame\"\"\"\n for widget in self.frame.winfo_children():\n widget.destroy()\n self.frame.pack_forget()\n self.items = {}\n\n\nclass TextHandler(logging.Handler):\n \"\"\"This class allows you to log to tkinter\"\"\"\n\n def __init__(self, console):\n # run the regular Handler __init__\n logging.Handler.__init__(self)\n # Store a reference to the Text it will log to\n self.console = console\n\n def emit(self, record):\n \"\"\"Emits a messege to the console\"\"\"\n msg = self.format(record)\n self.console.print(msg)\n\n\nclass ConsolePanel():\n \"\"\"Side panel with a console output\"\"\"\n\n def __init__(self, root):\n self.console = tkinter.Frame(root)\n self.console.grid(row=0, column=0, sticky=\"N\" + \"S\" + \"E\" + \"W\")\n\n tkinter.Text(\n self.console,\n bg=\"black\",\n fg=\"white\",\n width=75,\n height=42,\n font=\"Consolas 6\",\n name=\"console\").pack()\n self.console.nametowidget(\"console\").insert(\n tkinter.INSERT, \"Output Log Console\\n\")\n\n def print(self, *args):\n \"\"\"\n Prints in the console\n \"\"\"\n string = \"\"\n for arg in args:\n string += str(arg) + ' '\n string = string[:-1] + '\\n'\n self.console.nametowidget(\"console\").insert(tkinter.END, string)\n self.console.nametowidget(\"console\").see(tkinter.END)\n return True\n\n def clear(self):\n self.console.nametowidget(\"console\").delete('1.0', tkinter.END)\n","sub_path":"no-install/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":4678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"226483328","text":"import requests, json, static_vars, pytz\nfrom datetime import datetime, date, timedelta, time\nfrom pytz import timezone, datetime, tzinfo\n\n# Connectwise headers for connecting to API throughout\nheaders = static_vars.BASE_HEADERS\n\n\n# Tickets in Status >Send a Survey\nSurveyTicketsURL = static_vars.BASE_URL+'/Service/Tickets?conditions=status/name=\">Send a Survey\"&pageSize=1000'\nresponse = requests.request(\"GET\", SurveyTicketsURL, headers=headers)\nSurveyTicketsData = json.loads(response.text)\n\nif 'last' in response.links:\n maxPages = response.links['last']['url']\n maxPages = int(maxPages.split('=')[3])\nelse: \n maxPages = 1\n\nj = 1\n\ntotalSurveyTicketsData = []\n\nwhile j <= maxPages:\n SurveyTicketsURL = static_vars.BASE_URL+'/Service/Tickets?conditions=status/name=\">Send a Survey\"&pageSize=1000&page=' + str(j)\n # SurveyTicketsURL = static_vars.BASE_URL+'/Service/Tickets/822061?conditions=status/name=\">Send a Survey\"&pageSize=300&page=' + str(j)\n response = requests.request(\"GET\", SurveyTicketsURL, headers=headers)\n SurveyTicketsData = json.loads(response.text)\n totalSurveyTicketsData = totalSurveyTicketsData + SurveyTicketsData\n j += 1\n\n# totalSurveyTicketsData = sorted(totalSurveyTicketsData, key=lambda k: k['company']['name'])\n\nActiveEmail = \"Tickets Processed
\\n\"\n\nj = 0\n\nwhile j < len(totalSurveyTicketsData):\n TicketURL = static_vars.BASE_URL+ \"/Service/Tickets/\" + str(totalSurveyTicketsData[j]['id'])\n TicketLink = static_vars.BASE_LINK + str(totalSurveyTicketsData[j]['id']) + static_vars.BASE_LINKEND\n TicketID = str(totalSurveyTicketsData[j]['id'])\n payload = [{\n \"op\": \"replace\", \n \"path\": \"status\", \n \"value\": {\n \"name\" : \">Closed\",\n },\n }]\n payload = json.dumps(payload, ensure_ascii=False).encode('utf8')\n response = requests.patch(TicketURL, data=payload, headers=headers,)\n res = json.loads(response.text)\n if res['status']['name'] == \">Closed\":\n j += 1\n else:\n try: #Mother Mail if required\n today = date.today()\n today = str(today)\n\n payload = {\n \"APIKey\": static_vars.MOTHER_KEY,\n \"Subject\": \"Send Survey to Closed Report FAILED\" + today,\n \"emailBody\": '''\n \n \n
\n
\n Failed to change status for ticket ''' \n + TicketID + \n '''\n
\n \n ''',\n \"To\": static_vars.MY_EMAIL,\n \"BCC\": static_vars.MY_EMAIL\n }\n\n print(\"Email prepared, sending to mother.\")\n MotherData = json.dumps(payload)\n\n MotherURI = static_vars.MOTHER_URI\n response = requests.post(MotherURI, data=MotherData)\n print(\"Message away.\")\n print(response)\n #end of mother\n except:\n j += 1\n ActiveEmail = ActiveEmail + \"\" + TicketID + \"
\" #+ totalSurveyTicketsData[j]['company']['name'] + \" - \" + totalSurveyTicketsData[j]['summary'] + \"
\"\n j += 1\n\nActiveEmail = ActiveEmail + \"

\"\n\n#Mother Mail if required\ntoday = date.today()\ntoday = str(today)\n\npayload = {\n\"APIKey\": static_vars.MOTHER_KEY,\n\"Subject\": \"Send Survey to Closed Report \" + today,\n\"emailBody\": '''\n\n\n
\n
'''\n + ActiveEmail +\n '''

For issues with the report, email: ''' + static_vars.MY_EMAIL + '''
\n \n ''',\n\"To\": static_vars.MY_EMAIL,\n\"BCC\": static_vars.MY_EMAIL\n}\n\nprint(\"Email prepared, sending to mother.\")\nMotherData = json.dumps(payload)\n\nMotherURI = static_vars.MOTHER_URI\nresponse = requests.post(MotherURI, data=MotherData)\nprint(\"Message away.\")\nprint(response)","sub_path":"SurveyToCloseWorkflow/SurveytoClose.py","file_name":"SurveytoClose.py","file_ext":"py","file_size_in_byte":4527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"321067256","text":"import numpy as np\nimport numpy.matlib as mat\nfrom scipy import linalg\nfrom scipy.optimize import curve_fit\nimport math\nfrom kineticmodel import KineticModel\nfrom kineticmodel import integrate as km_integrate\n\nclass SRTM_Zhou2003(KineticModel):\n '''\n Compute binding potential (BP) and relative delivery (R1) kinetic parameters\n from dynamic PET data based on simplified reference tissue model (SRTM).\n The nonlinear SRTM equations are linearized using integrals of time\n activity curves (TACs) of the reference and target tissues. Kinetic\n parameters are then estimated by weighted linear regression (WLR).\n If provided, the spatially smoothed TAC of the target region is used in\n the computation of BP as part of the linear regression with spatial\n constraint (LRSC) approach.\n\n To obtain the R1 estimate that incorporates spatial smoothness based on\n LRSC, run refine_R1() after running fit().\n\n Reference:\n Zhou Y, Endres CJ, Brašić JR, Huang S-C, Wong DF.\n Linear regression with spatial constraint to generate parametric images of\n ligand-receptor dynamic PET studies with a simplified reference tissue model.\n Neuroimage. 2003;18:975–989.\n '''\n\n\n def __init__(self, t, dt, TAC, refTAC, startActivity,\n smoothTAC=None):\n '''\n Initialize Zhou 2003 SRTM model.\n\n Args\n ----\n smoothTAC : np.array\n spatially smoothed time activity curve of the region/voxel/vertex\n of interest (optional - if not provided, [unsmoothed] TAC is used)\n '''\n super().__init__(t, dt, TAC, refTAC, startActivity)\n self.smoothTAC = smoothTAC\n\n def fit(self):\n n = len(self.t)\n m = 3\n\n # diagonal matrix with diagonal elements corresponding to the duration\n # of each time frame\n W = mat.diag(self.dt)\n\n # Numerical integration of target TAC\n intTAC = km_integrate(self.TAC,self.t,self.startActivity)\n # Numerical integration of reference TAC\n intrefTAC = km_integrate(self.refTAC,self.t,self.startActivity)\n\n # ----- Get DVR, BP -----\n # Set up the weighted linear regression model\n # based on Eq. 9 in Zhou et al.\n # Per the recommendation in first paragraph on p. 979 of Zhou et al.,\n # smoothed TAC is used in the design matrix, if provided.\n if self.smoothTAC is None:\n X = np.mat(np.column_stack((intrefTAC, self.refTAC, self.TAC)))\n else:\n X = np.mat(np.column_stack((intrefTAC, self.refTAC, self.smoothTAC)))\n y = np.mat(intTAC).T\n b = linalg.solve(X.T * W * X, X.T * W * y)\n residual = y - X * b\n var_b = residual.T * W * residual / (n-m)\n\n DVR = b[0]\n BP = DVR - 1\n\n # ----- Get R1 -----\n # Set up the weighted linear regression model\n # based on Eq. 8 in Zhou et al.\n X = np.mat(np.column_stack((self.refTAC,intrefTAC,-intTAC)))\n y = np.mat(self.TAC).T\n b = linalg.solve(X.T * W * X, X.T * W * y)\n residual = y - X * b\n var_b = residual.T * W * residual / (n-m)\n\n R1 = b[0]\n\n self.BP = BP\n self.R1 = R1\n\n return self\n\n def refine_R1(smoothb):\n # to be implemented\n raise NotImplementedError()\n\nclass SRTM_Lammertsma1996(KineticModel):\n '''\n Compute binding potential (BP) and relative delivery (R1) kinetic parameters\n from dynamic PET data based on simplified reference tissue model (SRTM).\n Reference:\n Simplified reference tissue model for PET receptor studies.Lammertsma AA1,\n Hume SP. Neuroimage. 1996 Dec;4(3 Pt 1):153-8.\n '''\n def __init__(self, t, dt, TAC, refTAC, startActivity):\n super().__init__(t, dt, TAC, refTAC, startActivity)\n\n def fit(self):\n n = len(self.t)\n m = 4 # 3 model parameters + noise variance\n\n def make_srtm_est(startActivity):\n '''\n Wrapper to construct the SRTM TAC estimation function with a given\n startActivity.\n Args\n ----\n startActivity : determines initial condition for integration.\n See integrate in kineticmodel.py\n '''\n\n def srtm_est(X, BPnd, R1, k2):\n '''\n Compute fitted TAC given t, refTAC, BP, R1, k2.\n\n Args\n ----\n X : tuple where first element is t, and second element is intrefTAC\n BPnd : binding potential\n R1 : R1\n k2 : k2\n '''\n t, refTAC = X\n\n k2a=k2/(BPnd+1)\n # Convolution of reference TAC and exp(-k2a) = exp(-k2a) * Numerical integration of\n # refTAC(t)*exp(k2at).\n integrant = refTAC * np.exp(k2a*t)\n conv = np.exp(-k2a*t) * km_integrate(integrant,t,startActivity)\n TAC_est = R1*refTAC + (k2-R1*k2a)*conv\n return TAC_est\n return srtm_est\n\n X = (self.t, self.refTAC)\n # upper bounds for kinetic parameters in optimization\n BP_upper, R1_upper, k2_upper = (20.,10.,8.)\n\n srtm_fun = make_srtm_est(self.startActivity)\n popt, pcov = curve_fit(srtm_fun, X, self.TAC,\n bounds=(0,[BP_upper, R1_upper, k2_upper]))\n y_est = srtm_fun(X, *popt)\n\n sos=np.sum(np.power(self.TAC-y_est,2))\n err = np.sqrt(sos)/n\n mse = sos / (n-m) # 3 par + std err\n fpe = sos * (n+m) / (n-m)\n\n SigmaSqr = np.var( self.TAC-y_est )\n logl = -0.5*n* math.log( 2* math.pi * SigmaSqr) - 0.5*sos/SigmaSqr\n akaike = -2*logl + 2*m # 4 parameters: 3 model parameters + noise variance\n\n self.BP, self.R1, self.k2 = popt\n\n return self\n","sub_path":"kineticmodel/srtm.py","file_name":"srtm.py","file_ext":"py","file_size_in_byte":5876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"130229111","text":"# coding=utf-8\n__author__ = 'Archer'\n\nfrom sqlalchemy import Column, Integer, String, func\nfrom marka.database import Base, db_session\n\n\nclass Sample(Base):\n __tablename__ = 'sample'\n\n id = Column(Integer, primary_key=True)\n name = Column(String(50))\n\n def __init__(self, name=None):\n self.name = name\n\n def __repr__(self):\n return '' % self.name\n\n @classmethod\n def create(cls, name):\n \"\"\"\n create sample\n :param name\n \"\"\"\n sample = Sample(name)\n db = db_session()\n db.add(sample)\n db.commit()\n db.close\n\n\ndef create(sample):\n \"\"\"\n create object\n :param object\n \"\"\"\n db = db_session()\n db.add(sample)\n db.commit()\n db.close()\n\n\ndef delete(object, param):\n \"\"\"\n delete object\n :param object 实体\n :param param 查询参数列表 tuple\n \"\"\"\n session = db_session()\n ret = session.query(object).filter(*param).delete()\n session.commit()\n session.close()\n\n\ndef update(object, param, value):\n \"\"\"\n update object\n :param object 实体\n :param param 查询参数列表 tuple\n :param value 修改参数集合 dict\n \"\"\"\n session = db_session()\n ret = session.query(object).filter(*param).update(value)\n session.commit()\n session.close()\n return ret\n\n\ndef query(object, param):\n \"\"\"\n query object\n :param object 实体\n :param param 查询参数列表 tuple\n \"\"\"\n session = db_session()\n ret = session.query(object).filter(*param).one()\n session.close()\n return ret\n\n\ndef list(object, param):\n \"\"\"\n query list\n :param object 实体\n :param param 查询参数列表 tuple\n \"\"\"\n session = db_session()\n ret = session.query(object).filter(*param).all()\n session.close()\n return ret\n\n\ndef page(object, param, limit):\n \"\"\"\n query page of object\n :param object 实体\n :param param 查询参数列表 tuple\n :param limit 分页参数 tuple (offset, limit)\n \"\"\"\n session = db_session()\n rows = session.query(func.count(object.id)).one()[0]\n data = session.query(object).filter(*param).offset(limit[0]).limit(limit[1]).all()\n if len(data) > 0:\n ret = {\n \"rows\": rows,\n \"data\": data\n }\n session.close()\n return ret","sub_path":"marka/models/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"586058016","text":"import sys\nimport tkinter as tk\nfrom tkinter import BooleanVar, IntVar\nfrom game import GUI\nfrom PIL import Image, ImageTk\n\nbutton_font = (\"Helvetica\", 20, 'bold')\nlabel_font = (\"Helvetica\", 25, 'bold')\nLARGE_FONT = (\"Verdana\", 20)\n\nclass ALLRGB(tk.Tk):\n\n def __init__(self):\n tk.Tk.__init__(self)\n\n tk.Tk.wm_title(self,\"Virtual Robot Game\")\n\n\n container = tk.Frame(self)\n container.pack(side=\"top\", fill=\"both\", expand = True)\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n canvas = tk.Frame(width=500, height=200)\n canvas.pack()\n\n menu = tk.Menu(self)\n self.config(menu=menu)\n submenu = tk.Menu(menu)\n menu.add_cascade(label=\"Music\", menu=submenu)\n submenu.add_command(label=\"Next\", command=self.quit) #changes songs\n submenu.add_command(label=\"Stop\", command=self.quit)\n quitmenu = tk.Menu(menu)\n\n menu.add_command(label=\"Quit\", command=exit) # quits progr\n\n\n\n\n self.frames = {} #adds all pages to this dictionary, recall dict to bring up page\n\n for F in (mainPage, Start, Options, Instructions, Highscores):\n frame = F(container, self)\n self.frames[F] = frame\n frame.grid(row=0, column = 0, sticky=\"nsew\")\n\n self.show_frame(mainPage)\n\n def show_frame(self, cont):\n\n frame = self.frames[cont]\n frame.tkraise() #raises a new page to the front\n\n\n\n\n\nclass mainPage(tk.Frame):\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self,parent)\n canvas = tk.Canvas(self, width=1000, height=1000)\n canvas.pack()\n mainscreenImg = Image.open('mainscreen.png')\n mainscreenImg = mainscreenImg.resize((1000, 1000), Image.ANTIALIAS) #Individual Bit (Adhitama Azmii)\n mainscreenLoad = ImageTk.PhotoImage(mainscreenImg)\n canvas.create_image(500, 500, image = mainscreenLoad)\n canvas.image = mainscreenLoad\n #label = tk.Label(image=mainscreenLoad) #\n #label.image = mainscreenLoad #\n #label.place(x = 1, y = 1, relwidth=1, relheight=1) #\n #self, text =\"Bargain Hunt\", bg = 'white', fg = 'black', font=label_font\n #mainPage.config(self, bg = 'white')\n #label.place(x=350, y=25)\n \n\n\n\n button1 = tk.Button(self, text = \"Start\", bg = 'pink', font = button_font,\n command= lambda: controller.show_frame(Start), width = 18, height = 5)\n\n button2 = tk.Button(self, text = \"Instructions\", bg = 'pink', font = button_font,\n command = lambda: controller.show_frame(Instructions), width = 18, height = 5) #opens new window\n\n button3 = tk.Button(self, text = \"Highscores\", bg = 'pink', font = button_font,\n command = lambda: controller.show_frame(Highscores), width = 18, height = 5)\n\n button4 = tk.Button(self, text =\"Quit\", bg = 'pink', font = button_font,\n command = lambda:self.quit, width = 18, height = 5)\n\n\n\n button1_window = canvas.create_window(499, 315, window=button1)\n button2_window = canvas.create_window(170, 549, window=button2)\n button3_window = canvas.create_window(825, 540, window=button3)\n button4_window = canvas.create_window(499, 780, window=button4)\n #button1.pack(padx=50, pady=125,ipadx=50, ipady=50)\n #seperator = tk.Frame(height=200, width=200, bd=1, relief=\"flat\")\n #button2.pack(side=\"left\",padx=50, pady=25, ipadx=50, ipady=50)\n #button3.pack(side=\"right\",padx=50, pady=25, ipadx=50, ipady=50)\n #button4.pack(side=\"bottom\", padx=50, pady=25, ipadx=50, ipady=50)\n\n\n\n\nclass Start(tk.Frame): # Needed to be revised/ Cannot send an int to the game\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n tk.Frame.__init__(self,parent)\n canvas = tk.Canvas(self, width=1000, height=1000)\n canvas.pack()\n mainscreenImg = Image.open('loadingscreen.png')\n mainscreenImg = mainscreenImg.resize((1000, 1000), Image.ANTIALIAS) #Individual Bit (Adhitama Azmii)\n mainscreenLoad = ImageTk.PhotoImage(mainscreenImg)\n canvas.create_image(500, 500, image = mainscreenLoad)\n canvas.image = mainscreenLoad\n #label = tk.Label(self, text = \"Main Game\", font=LARGE_FONT)\n #label.pack()\n\n \n #game = [entry1.get(), entry2.get(), entry3.get(), entry4.get(), entry5.get(), entry6.get(), entry7.get(), entry8.get(), entry9.get(), entry10.get(), entry11.get(), entry12.get(), entry13.get(), entry14.get(), entry15.get(), entry16.get()]\n #boolean_value = []\n\n randomPlaceBool = BooleanVar()\n resX_int = IntVar()\n resY_int = IntVar()\n fpsInt = IntVar()\n listSearch_int= IntVar()\n itemOneInt = IntVar()\n quantity_item1 = IntVar()\n itemTwoInt = IntVar()\n quantity_item2 = IntVar()\n itemThreeInt = IntVar()\n quantity_item3 = IntVar()\n itemFourInt = IntVar()\n quantity_item4 = IntVar()\n itemFiveInt = IntVar()\n quantity_item5 = IntVar()\n time_limitInt = IntVar()\n \n randomPlaceBool.set(\"True\")\n resX_int.set(1000)\n resY_int.set(1000)\n fpsInt.set(300)\n listSearch_int.set(5)\n itemOneInt.set(10)\n quantity_item1.set(10)\n itemTwoInt.set(20)\n quantity_item2.set(20)\n itemThreeInt.set(30) \n quantity_item3.set(30) \n itemFourInt.set(40) \n quantity_item4.set(40) \n itemFiveInt.set(50) \n quantity_item5.set(50) \n time_limitInt.set(60)\n \n randomPlaceLabel = tk.Label(self, text=\"Random Place\")\n randomPlaceLabel.pack()\n entry1 = tk.Entry(self, textvariable = randomPlaceBool)\n entry1.pack()\n #boolean_value.append(entry1)\n \n resolutionXlabel = tk.Label(self, text=\"Resolution X\")\n resolutionXlabel.pack()\n entry2 = tk.Entry(self, textvariable=resX_int)\n entry2.pack()\n #game.append(entry2)\n \n resolutionYlabel = tk.Label(self, text=\"Resolution Y\")\n resolutionYlabel.pack()\n entry3 = tk.Entry(self, textvariable=resY_int)\n entry3.pack()\n #game.append(entry3)\n \n fpsLabel = tk.Label(self, text=\"FPS\")\n fpsLabel.pack()\n entry4 = tk.Entry(self, textvariable=fpsInt)\n entry4.pack()\n #game.append(entry4)\n\n listSearchLabel = tk.Label(self, text=\"List Search\")\n listSearchLabel.pack()\n entry5 = tk.Entry(self, textvariable=listSearch_int)\n entry5.pack()\n #game.append(entry5)\n \n itemOneLabel = tk.Label(self, text=\"Item 1\")\n itemOneLabel.pack()\n entry6 = tk.Entry(self, textvariable=itemOneInt)\n entry6.pack()\n #game.append(entry6)\n \n itemOneQuantity = tk.Label(self, text=\"Quantity\")\n itemOneQuantity.pack()\n entry7 = tk.Entry(self,textvariable=quantity_item1)\n entry7.pack()\n #game.append(entry7)\n \n itemTwoLabel = tk.Label(self, text=\"Item 2\")\n itemTwoLabel.pack()\n entry8 = tk.Entry(self, textvariable=itemTwoInt)\n entry8.pack()\n #game.append(entry8)\n \n itemTwoQuantity = tk.Label(self, text=\"Quantity\")\n itemTwoQuantity.pack()\n entry9 = tk.Entry(self, textvariable=quantity_item2)\n entry9.pack()\n #game.append(entry9)\n \n itemThreeLabel = tk.Label(self, text=\"Item 3\")\n itemThreeLabel.pack()\n entry10 = tk.Entry(self, textvariable=itemThreeInt)\n entry10.pack()\n #game.append(entry10)\n \n itemThreeQuantity = tk.Label(self, text=\"Quantity\")\n itemThreeQuantity.pack()\n entry11 = tk.Entry(self, textvariable=quantity_item3)\n entry11.pack()\n #game.append(entry11)\n \n itemFourLabel = tk.Label(self, text=\"Item 4\")\n itemFourLabel.pack()\n entry12 = tk.Entry(self, textvariable=itemFourInt)\n entry12.pack()\n #game.append(entry12)\n \n itemFourQuantity = tk.Label(self, text=\"Quantity\")\n itemFourQuantity.pack()\n entry13 = tk.Entry(self,textvariable=quantity_item4)\n entry13.pack()\n #game.append(entry13)\n \n itemFiveLabel = tk.Label(self, text=\"Item 5\")\n itemFiveLabel.pack()\n entry14 = tk.Entry(self, textvariable=itemFiveInt)\n entry14.pack()\n #game.append(entry14)\n \n itemFiveQuantity = tk.Label(self, text=\"Quantity\")\n itemFiveQuantity.pack()\n entry15 = tk.Entry(self, textvariable=quantity_item5)\n entry15.pack()\n #game.append(entry15)\n \n timeLimitLabel = tk.Label(self, text=\"Time Limit\")\n timeLimitLabel.pack()\n entry16 = tk.Entry(self, textvariable=time_limitInt)\n entry16.pack()\n #game.append(entry16)\n\n #game = [entry1.get(), entry2.get(), entry3.get(), entry4.get(), entry5.get(), entry6.get(), entry7.get(), entry8.get(), entry9.get(), entry10.get(), entry11.get(), entry12.get(), entry13.get(), entry14.get(), entry15.get(), entry16.get()]\n randomPlace = True\n resX = 500\n resY = 500\n FPS = 200\n listSearch = 1\n oneVal = 100\n oneQuant = 100\n twoVal = 100\n twoQuant = 100\n threeVal = 100\n threeQuant = 100\n fourVal = 100\n fourQuant = 100\n fiveVal = 100\n fiveQuant = 100\n timeLimit = 60\n \n if entry1 == \"True\" or entry1== \"true\":\n randomPlace = True\n elif entry1 == \"False\" or entry1 == \"false\":\n randomPlace = False\n else:\n randomPlace = True\n if entry2 is int:\n if entry2 >= 500:\n resX = 500\n else:\n resX = entry2.get()\n else:\n resX = 500\n if entry3 is int:\n if entry3 >= 500:\n resX = 500\n else:\n resX = entry3.get()\n else:\n resX = 500\n\n if entry4 is int:\n if entry4 > 0 and entry4 < 6:\n listSearch = entry4.get()\n else:\n listSearch = 1\n else:\n listSearch = 1\n \n \n if entry5 is int:\n if entry5 >= 60:\n FPS = entry5.get()\n else:\n FPS = 160\n else:\n FPS = 160\n if entry6 is int:\n oneVal = entry6.get()\n else:\n oneVal = 100\n if entry7 is int:\n oneQuant = entry7.get()\n else:\n oneQuant = 100\n if entry8 is int:\n twoVal = entry8.get()\n else:\n twoVal = 100\n if entry9 is int:\n twoQuant = entry9.get()\n else:\n twoQuant = 100\n if entry10 is int:\n threeVal = entry10.get()\n else:\n threeVal = 100\n if entry11 is int:\n threeQuant = entry11.get()\n else:\n threeQuant = 100\n if entry12 is int:\n fourVal = entry12.get()\n else:\n fourVal = 100\n if entry13 is int:\n fourQuant = entry13.get()\n else:\n fourQuant = 100\n if entry14 is int:\n fiveVal = entry14.get()\n else:\n fiveVal = 100\n if entry15 is int:\n fiveQuant = entry15.get()\n else:\n fiveQuant = 100\n if entry16 is int:\n if entry16 > 0:\n timeLimit = entry16.get()\n else:\n timeLimit = 60\n else:\n timeLimit = 60\n \n button1 = tk.Button(self, text=\"Start Game\", bg = 'pink', font = button_font,\n command = lambda: startgamegui(randomPlace,resX,resY,FPS,listSearch,oneVal,oneQuant,twoVal,twoQuant,threeVal,threeQuant,fourVal,fourQuant,fiveVal,fiveQuant,timeLimit), width = 10, height = 2)\n #button2 = tk.Button(self, text = \"Update\",\n #command = self.get_list )\n#(randomPlace,resX,resY,FPS,listSearch,firstValue,firstQuant,secondValue,secondQuant,thirdValue,thirdQuant,fourthValue,fourthQuant,fifthValue,fifthQuant,timeLimit)\n\n button3 = tk.Button(self, text=\"Back\", bg = 'pink', font = button_font,\n command = lambda: controller.show_frame(mainPage), width = 10, height = 2)\n \n\n button1_window = canvas.create_window(300, 900, window=button1)\n button3_window = canvas.create_window(600, 900, window=button3)\n \n entry1_label = canvas.create_window(400, 100, window=randomPlaceLabel)\n entry1_window = canvas.create_window(520, 100, window=entry1)\n \n entry2_label = canvas.create_window(400, 120, window=resolutionXlabel)\n entry2_window = canvas.create_window(520, 120, window=entry2)\n \n entry3_label = canvas.create_window(400, 140, window=resolutionYlabel)\n entry3_window = canvas.create_window(520, 140, window=entry3)\n \n entry4_label = canvas.create_window(400, 160, window=fpsLabel)\n entry4_window = canvas.create_window(520, 160, window=entry4)\n \n entry5_label = canvas.create_window(400, 180, window=listSearchLabel)\n entry5_window = canvas.create_window(520, 180, window=entry5)\n \n entry6_label = canvas.create_window(400, 200, window=itemOneLabel)\n entry6_window = canvas.create_window(520, 200, window=entry6)\n \n entry7_label = canvas.create_window(400, 220, window=itemOneQuantity)\n entry7_window = canvas.create_window(520, 220, window=entry7)\n \n entry8_label = canvas.create_window(400, 240, window=itemTwoLabel)\n entry8_window = canvas.create_window(520, 240, window=entry8)\n \n entry9_label = canvas.create_window(400, 260, window=itemTwoQuantity)\n entry9_window = canvas.create_window(520, 260, window=entry9)\n \n entry10_label = canvas.create_window(400, 280, window=itemThreeLabel)\n entry10_window = canvas.create_window(520, 280, window=entry10)\n \n entry11_label = canvas.create_window(400, 300, window=itemThreeQuantity)\n entry11_window = canvas.create_window(520, 300, window=entry11)\n \n entry12_label = canvas.create_window(400, 320, window=itemFourLabel)\n entry12_window = canvas.create_window(520, 320, window=entry12)\n \n entry13_label = canvas.create_window(400, 340, window=itemFourQuantity)\n entry13_window = canvas.create_window(520, 340, window=entry13)\n \n entry14_label = canvas.create_window(400, 360, window=itemFiveLabel)\n entry14_window = canvas.create_window(520, 360, window=entry14)\n \n entry15_label = canvas.create_window(400, 380, window=itemFiveQuantity)\n entry15_window = canvas.create_window(520, 380, window=entry15)\n \n entry16_label = canvas.create_window(400, 400, window=timeLimitLabel)\n entry16_window = canvas.create_window(520, 400, window=entry16)\n \n #button3.pack(side=\"bottom\", ipadx=25, ipady=35)\n #button1.pack(side=\"bottom\", ipadx=25, ipady=35)\n #button2.pack(side=\"bottom\", ipadx=25, ipady=35)\n\ndef startgamegui(randomPlace,resX,resY,FPS,listSearch,oneVal,oneQuant,twoVal,twoQuant,threeVal,threeQuant,fourVal,fourQuant,fiveVal,fiveQuant,timeLimit):\n GUI.main(randomPlace,resX,resY,FPS,listSearch,oneVal,oneQuant,twoVal,twoQuant,threeVal,threeQuant,fourVal,fourQuant,fiveVal,fiveQuant,timeLimit)\n #GUI.main(bool(entry1.get()), int(entry2.get()), int(entry3.get()), int(entry4.get()), int(entry5.get()), int(entry6.get()), int(entry7.get()), int(entry8.get()), int(entry9.get()), int(entry10.get()), int(entry11.get()), int(entry12.get()), int(entry13.get()), int(entry14.get()), int(entry15.get()), int(entry16.get()))\n\n #(boolean_value[0],game[0],game[1],game[2],game[3],game[4],game[5],game[6],game[7],game[8],game[9],game[10],game[11],game[12],game[13], game[14])\n #GUI.main(game[0],game[1],game[2],game[3],game[4],game[5],game[6],game[7],game[8],game[9],game[10],game[11],game[12],game[13],game[14], game[15])\n #GUI.main(True,1000,1000,300,5,10,10,20,20,30,30,40,40,50,50,60)\n \n'''def list_start():\n \n randomPlaceLabel = tk.Label(self, text=\"Random Place\"). grid(row=0)\n resolutionXlabel = tk.Label(self, text=\"Resolution X\"). grid(row=1)\n resolutionYlabel = tk.Label(self, text=\"Resolution Y\"). grid(row=2)\n fpsLabel = tk.Label(self, text=\"FPS\"). grid(row=3)\n itemOneLabel = tk.Label(self, text=\"Item 1\"). grid(row=4)\n itemOneQuantity = tk.Label(self, text=\"Quantity\").grid(row=5)\n itemTwoLabel = tk.Label(self, text=\"Item 2\"). grid(row=6)\n itemTwoQuantity = tk.Label(self, text=\"Quantity\").grid(row=7)\n itemThreeLabel = tk.Label(self, text=\"Item 3\"). grid(row=8)\n itemThreeQuantity = tk.Label(self, text=\"Quantity\").grid(row=9)\n itemFourLabel = tk.Label(self, text=\"Item 4\"). grid(row=10)\n itemFourQuantity = tk.Label(self, text=\"Quantity\").grid(row=11)\n itemFiveLabel = tk.Label(self, text=\"Item 5\"). grid(row=12)\n itemFiveQuantity = tk.Label(self, text=\"Quantity\").grid(row=13)\n timeLimit = tk.Label(self, text=\"Time Limit\"). grid(row=14)\n \n entry1 = Entry(self)\n entry2 = Entry(self)\n entry3 = Entry(self)\n entry4 = Entry(self)\n entry5 = Entry(self)\n entry6 = Entry(self)\n entry7 = Entry(self)\n entry8 = Entry(self)\n entry9 = Entry(self)\n entry10 = Entry(self)\n entry11 = Entry(self)\n entry12 = Entry(self)\n entry13 = Entry(self)\n entry14 = Entry(self)\n entry15 = Entry(self)\n \n entry1.grid(row=0, column=1)\n entry2.grid(row=1, column=1)\n entry3.grid(row=2, column=1)\n entry4.grid(row=3, column=1)\n entry5.grid(row=4, column=1)\n entry6.grid(row=5, column=1)\n entry7.grid(row=6, column=1)\n entry8.grid(row=7, column=1)\n entry9.grid(row=8, column=1)\n entry10.grid(row=9, column=1)\n entry11.grid(row=10, column=1)\n entry12.grid(row=11, column=1)\n entry13.grid(row=12, column=1)\n entry14.grid(row=13, column=1)\n entry15.grid(row=14, column=1)\n \n button1 = tk.Button(self, text=\"Start Game\",\n command = GUI.main(True,1000,1000,360,10,20,30,40,50,100))\n button2 = tk.Button(self, text=\"Back\",\n command = lambda: controller.show_frame(mainPage))'''\n \nclass Options(tk.Frame): \n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n tk.Frame.__init__(self,parent)\n label = tk.Label(self, text=\"Options Screen\", font=LARGE_FONT)\n label.pack()\n\n label2= tk.Label(self, text=\"Start Location\")\n label2.pack()\n\n\n\n\n #setting up the variable\n button1 = tk.Button(self, text=\"Reset\")\n button2 = tk.Button(self, text=\"Stop\")\n button3 = tk.Button(self, text=\"Instructions\")\n button4 = tk.Button(self, text=\"Start\")\n listbox1 = tk.Listbox(self)\n entry1 = tk.Entry(self)\n entry2 = tk.Entry(self, text=\"X\")\n entry3 = tk.Entry(self, text=\"Y\")\n\n button1.pack(ipadx=50, ipady=300)\n button2.pack(ipadx=300, ipady=300)\n button3.pack(ipadx=50, ipady=400)\n button4.pack(ipadx=300, ipady=400)\n separator = tk.Frame(self, height=200, width=200, bd=1, relief=\"flat\")\n listbox1.pack(ipadx=50, ipady=70)\n entry1.pack(ipadx=50, ipady=260)\n entry2.pack(ipadx=50, ipady=42)\n entry3.pack(ipadx=260, ipady=42)\n\n\nclass main(tk.Frame):\n pass\n\n\n\n\n\n\n\nclass Instructions(tk.Frame):\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n tk.Frame.__init__(self,parent)\n canvas = tk.Canvas(self, width=1000, height=1000)\n canvas.pack()\n mainscreenImg = Image.open('instructionnew.png')\n mainscreenImg = mainscreenImg.resize((1000, 1000), Image.ANTIALIAS) #Individual Bit (Adhitama Azmii)\n mainscreenLoad = ImageTk.PhotoImage(mainscreenImg)\n canvas.create_image(500, 500, image = mainscreenLoad)\n canvas.image = mainscreenLoad\n #label = tk.Label(self, text =\"Instructions\", font=LARGE_FONT)\n #label.pack()\n\n\n\n button2 = tk.Button(self, text = \"Back\", bg = 'pink', font = button_font,\n command = lambda: controller.show_frame(mainPage), width = 15, height = 3)\n #button2.pack(side=\"bottom\", ipadx=50,ipady=50)\n #label = tk.Label(self, text=\"Instructions go here\")\n #label.pack()\n\n button2_window = canvas.create_window(490, 940, window=button2)\n\n\n\n\n\n\n\n\n\nclass Highscores(tk.Frame):\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n tk.Frame.__init__(self,parent)\n label = tk.Label(self, text =\"Highscores\", font=LARGE_FONT)\n label.pack(pady=10, padx=10)\n\n button2 = tk.Button(self, text = \"Main Page\",\n command = lambda: controller.show_frame(mainPage))\n button2.pack(side=\"bottom\", ipadx=50, ipady=50)\n\n\n#GUI.main(True,1000,1000,360,10,20,30,40,50,100)\n\napp = ALLRGB()\napp.mainloop()\n","sub_path":"allGamesCompileFinal.py","file_name":"allGamesCompileFinal.py","file_ext":"py","file_size_in_byte":21370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"155231813","text":"import requests;\nimport os;\nfrom getpass import getpass;\n\n'''\nFORMAT:\n\t- action: \"tunnel\"\n\t- sub-action: \"get\"|\"post\"|\"session\"|\"login_session\"\n'''\n\nclass Tunnel:\n\t\n\tdef __init__(self,url=None):\n\t\tself.url=\"https://www.google.com\";\n\t\tself.session = None; #to be a requests.session object\n\t\treturn;\n\t\t\n\tdef get(self,url=None):\n\t\tif url == None:\n\t\t\turl=self.url;\n\t\tresp=None;\n\t\ttry:\n\t\t\tresp = requests.get(url);\n\t\texcept requests.exceptions.SSLError:\n\t\t\tresp = requests.get(url,verify=False);\n\t\treturn(resp.content); \n\t\t\n\tdef post(self,url=None):\n\t\tif url == None:\n\t\t\turl=self.url;\n\t\tresp=None;\n\t\ttry:\n\t\t\tresp = requests.post(url);\n\t\texcept requests.exceptions.SSLError:\n\t\t\tresp = requests.post(url,verify=False);\n\t\treturn(resp.content);\n\t\t\n\tdef session(self,url=None):\n\t\tif url == None:\n\t\t\turl = self.url;\n\t\tif self.session == None:\n\t\t\treturn(self.start_session(url).content);\n\t\telse:\n\t\t\tret = None;\n\t\t\ttry:\n\t\t\t\tret = self.session.get(url).content;\n\t\t\texcept requests.exceptions.SSLError:\n\t\t\t\tret = self.session.get(url,verify=False).content;\n\t\t\treturn(ret);\n\t\t\n\tdef login_session(self,url=None,data=None):\n\t\tif url == None:\n\t\t\turl = self.url;\n\t\tif self.session == None:\n\t\t\treturn(self.start_session(url,data).content);\n\t\telse:\n\t\t\tret = None;\n\t\t\ttry:\n\t\t\t\tret = self.session.get(url).content;\n\t\t\texcept requests.exceptions.SSLError:\n\t\t\t\tret = self.session.get(url,verify=False).content;\n\t\t\treturn(ret);\n\t\n\t''' supplementary methods '''\n\t\n\tdef start_session(self,url,data=None):\n\t\tself.session = requests.Session();\n\t\tret = None; #returning data\n\t\tif data != None:\n\t\t\ttry:\n\t\t\t\tret = self.session.post(url,data=data);\n\t\t\texcept requests.exceptions.SSLError:\n\t\t\t\tret = self.session.post(url,data=data,verify=False);\n\t\telse:\n\t\t\ttry:\n\t\t\t\tret = self.session.get(url);\n\t\t\texcept requests.exceptions.SSLError:\n\t\t\t\tret = self.session.get(url);\n\t\treturn(ret);\n\t\n\n''' MAIN '''\nif __name__ == \"__main__\":\n\tt = Tunnel(\"http://moodle.dbit.in\");\n\tt.get();\n\tusername = input(\"username -> \");\n\tpassword = getpass(\"Password ->\");\n\tdata = t.login_session(\"https://moodle.dbit.in/login/index.php\",{\"username\":username,\"password\":password});\n\tf = open(\"op.html\",\"wb\");\n\tf.write(data);\n\tf.close();\n\tos.system(\"xdg-open op.html 1> /dev/null\");\n","sub_path":"modules/Tunnel/tunnel.py","file_name":"tunnel.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"278601875","text":"from .coco import CocoDataset\nfrom typing import List\nimport numpy as np\nimport scipy\nfrom ..utils import maskutils\n\n__all__ = ['SemanticCocoDataset']\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n\nclass SemanticCocoDataset(CocoDataset):\n \"\"\"\n An extension of the coco dataset to handle the output of a semantic segmentation model\n\n \"\"\"\n\n def add_annotations(self,\n img_id: int,\n masks: np.ndarray,\n probs: np.ndarray,\n start_index=1) -> List[int]:\n \"\"\"\n add the annotation from the given masks\n\n Args:\n img_id (int): the id of the image to associate the annotations\n masks (np.ndarray): a mask of shape [Height, Width]\n probs (np.ndarray): an array of shape [NClasses, Height, Width]\n cats_idxs (List, optional): A list that maps the. Defaults to None.\n start_index (int, optional): the index to start generating the coco polygons.\n Normally, 0 encodes the background. Defaults to 1.\n\n Raises:\n ValueError: if the shape of masks is different than 2\n ValueError: if the shape of probs is different than 3\n\n Returns:\n List[int]: [the idx of the annotations added]\n \"\"\"\n\n if np.count_nonzero(masks) == 0:\n return None\n\n if len(masks.shape) != 2:\n raise ValueError('masks.shape should equal to 2')\n\n if len(probs.shape) != 3:\n raise ValueError('masks.shape should equal to 3')\n\n annotation_ids = []\n # for each class\n for i, class_idx in enumerate(\n np.unique(masks)[start_index:], start_index):\n class_mask = (masks == class_idx).astype(np.uint8)\n class_probs = probs[i]\n cat_id = int(class_idx)\n\n if cat_id not in self.cats:\n raise ValueError(f'cats {cat_id} not in dataset categories')\n\n groups, n_groups = scipy.ndimage.label(class_mask)\n\n # get the groups starting from label 1\n for group_idx in range(1, n_groups + 1):\n group_mask = (groups == group_idx).astype(np.uint8)\n polygons = maskutils.mask_to_polygon(group_mask)\n if len(polygons) == 0:\n continue\n\n bbox = maskutils.bbox(polygons, *masks.shape).tolist()\n # an exception is generated when the mask has less than 3 points\n area = int(maskutils.area(group_mask))\n if area == 0:\n continue\n segment_probs_mask = group_mask * class_probs\n score = float(\n np.mean(segment_probs_mask[segment_probs_mask > 0]))\n annotation_ids.append(\n self.add_annotation(img_id, cat_id, polygons, area, bbox, 0,\n score))\n return annotation_ids\n\n def add_annotations_from_scores(self,\n img_id: int,\n mask_logits: np.ndarray,\n start_index=1) -> List[int]:\n \"\"\"add the annotations from the logit masks\n\n Args:\n img_id (int): the id of the image to associate the annotations\n mask_logits (np.ndarray): the logits from the semantic model\n start_index (int, optional): the index to start generating the coco polygons.\n Normally, 0 encodes the background. Defaults to 1.\n\n Returns:\n List[int]: [the idx of the annotations added]]\n \"\"\"\n masks = np.argmax(mask_logits, axis=0)\n probs = sigmoid(mask_logits)\n return self.add_annotations(img_id, masks, probs, start_index)\n","sub_path":"polimorfo/datasets/semanticcoco.py","file_name":"semanticcoco.py","file_ext":"py","file_size_in_byte":3824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"25357864","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nimport math\nimport numpy as np\nimport scipy as sp\nimport pandas\nimport matplotlib.pyplot as plt\nfrom progressbar import ProgressBar\nfrom scipy.sparse import csr_matrix\nfrom scipy.sparse import linalg as sparse_linalg\nimport sys\nfile_dir = '/localhome/pykb/physics_code/Exact_Diagonalization/Classes/'\nsys.path.append(file_dir)\nfile_dir = '/localhome/pykb/physics_code/Exact_Diagonalization/functions/'\nsys.path.append(file_dir)\n\nfrom Hamiltonian_Classes import Hamiltonian,H_table,clock_Hamiltonian,spin_Hamiltonian\nfrom System_Classes import unlocking_System\nfrom Symmetry_Classes import translational,parity,model_sym_data,charge_conjugation\n# from Plotting_Classes import eig_overlap,fidelity,entropy,energy_basis\nfrom Non_observables import zm\nfrom Construction_functions import bin_to_int_base_m,int_to_bin_base_m,cycle_bits_state\nfrom Search_functions import find_index_bisection\nfrom State_Classes import zm_state,sym_state,prod_state,bin_state,ref_state\nfrom rw_functions import save_obj,load_obj\nfrom Calculations import level_stats,fidelity,eig_overlap,entropy,site_precession,site_projection,time_evolve_state\n\nfrom matplotlib import rc\nrc('font',**{'family':'sans-serif','sans-serif':['Computer Modern'],'size':26})\n## for Palatino and other serif fonts use:\n#rc('font',**{'family':'serif','serif':['Palatino']})\nrc('text', usetex=True)\n# matplotlib.rcParams['figure.dpi'] = 400\n\ndef find_hamming_sectors(state_bits):\n #organize states via hamming distance from Neel\n hamming_sectors = dict()\n for n in range(0,pxp.N+1):\n hamming_sectors[n] = []\n for n in range(0,pxp.dim):\n h = 0\n for m in range(0,pxp.N,1):\n if pxp.basis[n][m] != state_bits[m]:\n h = h+1\n hamming_sectors[int(h)] = np.append(hamming_sectors[int(h)],pxp.basis_refs[n])\n return hamming_sectors\n\n#init small hypercube\nN_main = 6\nN_coupling = 6\n\npxp = unlocking_System([0,1],\"periodic\",2,N_main)\npxp_coupling = unlocking_System([0,1],\"periodic\",2,N_coupling)\npxp.gen_basis()\npxp_coupling.gen_basis()\n\nH_main = spin_Hamiltonian(pxp,\"x\")\nH_main.gen()\n\nH_coupling = spin_Hamiltonian(pxp_coupling,\"x\")\nH_coupling.gen()\n\nplt.matshow(np.abs(H_main.sector.matrix()))\nplt.show()\n\nplt.matshow(np.abs(H_coupling.sector.matrix()))\nplt.show()\n\n\nH_total = np.zeros((2*pxp.dim+pxp_coupling.dim,2*pxp.dim+pxp_coupling.dim))\n\nH_total[0:pxp.dim,0:pxp.dim] = H_main.sector.matrix()\nH_total[pxp.dim:pxp.dim+pxp_coupling.dim,pxp.dim:pxp.dim+pxp_coupling.dim] = H_coupling.sector.matrix()\nH_total[pxp.dim+pxp_coupling.dim:,pxp.dim+pxp_coupling.dim:] = H_main.sector.matrix()\n\n#insert random connections into small hypercube tunnel\nk=0.001\nbase_index = pxp.dim\nfor n in range(pxp.dim,pxp.dim+np.size(H_coupling.sector.matrix(),axis=0)):\n for m in range(0,pxp.dim):\n a=np.random.uniform(0,1)\n if a < k:\n H_total[n,m] = 1\n H_total[m,n] = 1\n for m in range(pxp.dim+pxp_coupling.dim,np.size(H_total,axis=0)):\n a=np.random.uniform(0,1)\n if a < k:\n H_total[n,m] = 1\n H_total[m,n] = 1\n\nplt.matshow(np.abs(H_total))\nplt.show()\n\ne,u = np.linalg.eigh(H_total)\npbar=ProgressBar()\n\nz=zm_state(2,1,pxp)\nz_energy = np.conj(u[pxp.keys[z.ref],:])\nt=np.arange(0,20,0.01)\nf = np.zeros(np.size(t))\nfor n in range(0,np.size(t,axis=0)):\n evolved_state = time_evolve_state(z_energy,e,t[n])\n f[n] = np.abs(np.vdot(evolved_state,z_energy))**2\nplt.plot(t,f)\nplt.show()\n\nt=np.arange(0,20,0.1)\nfor n in pbar(range(0,np.size(pxp.basis_refs,axis=0))):\n z=ref_state(pxp.basis_refs[n],pxp)\n z_energy = np.conj(u[pxp.keys[z.ref],:])\n f = np.zeros(np.size(t))\n for n in range(0,np.size(t,axis=0)):\n evolved_state = time_evolve_state(z_energy,e,t[n])\n f[n] = np.abs(np.vdot(evolved_state,z_energy))**2\n plt.plot(t,f)\nplt.show()\n","sub_path":"projects/hypercube,random_cuts/column_space_decay/hypercube_bipartite_disorder.py","file_name":"hypercube_bipartite_disorder.py","file_ext":"py","file_size_in_byte":3909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"56322488","text":"from bs4 import BeautifulSoup\nfrom urllib2 import urlopen\n\ndef retrieveRecipe(url):\n\trecipePage = urlopen(url)\n\tsoup = BeautifulSoup(recipePage.read())\n\trecipeInfo = {}\n\n\t# Recipe Components\n\trecipeInfo[\"title\"] = soup.find(id=\"itemTitle\").string\n\trecipeInfo[\"rating\"] = soup.find(itemprop=\"ratingValue\")[\"content\"]\n\trecipeInfo[\"author\"] = soup.find(\"span\", {\"id\": \"lblSubmitter\"}).text\n\trecipeInfo[\"servings\"] = soup.find(id=\"lblYield\").string\n\trecipeInfo[\"time\"] = soup.find_all(\"span\", {\"class\":\"time\"})\n\tif recipeInfo[\"time\"]:\n\t\trecipeInfo[\"time\"] = recipeInfo[\"time\"][0].text\n\n\tingredientsListing = soup.findAll(itemprop=\"ingredients\")\n\tingredients = []\n\tfor ingredient in ingredientsListing:\n\t\tif ingredient.find_next(id=\"lblIngName\"):\n\t\t\tnextEl = ingredient.find_next(id=\"lblIngName\")\n\t\t\tif nextEl[\"class\"][0] == \"ingred-heading\" or nextEl.string.replace(u'\\xa0', u' ') == \" \":\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tamount = \"\"\n\t\t\t\tname = \"\"\n\t\t\t\tif ingredient.find_next(id=\"lblIngAmount\"):\n\t\t\t\t\tamount = ingredient.find_next(id=\"lblIngAmount\").string\n\t\t\t\tif ingredient.find_next(id=\"lblIngName\"):\n\t\t\t\t\tname = ingredient.find_next(id=\"lblIngName\").string\n\t\t\t\tingredients.append({\"name\": name, \"amount\": amount})\n\trecipeInfo[\"ingredients\"] = ingredients\n\n\tdirectionsListing = soup.find_all(\"span\", {\"class\":\"plaincharacterwrap break\"})\n\tdirections = []\n\tfor direction in directionsListing:\n\t\tdirections.append(direction.string)\n\trecipeInfo[\"directions\"] = directions\n\n\n\treturn recipeInfo\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"270700060","text":"#!/usr/bin/env python\n\"\"\"\n This script finds duplicate names and can count the number of times\n each occurs in a sequence file. Also can produce a\n new file with the records with duplicate names removed, or with the\n names changed to non-duplicated versions.\n\n Note that if the input is stdin, the duplicate and unduplicated files\n will not be written (but they will be created).\n\n Renaming of duplicated records is done by appending '_[INT]' to the\n end of either the id (the first word of the record name) or the \n description (the part after the first word of a fasta record name), \n where INT is the the number of the duplicate in the file. No output\n aside from the names of duplicate records is produced if the input\n is stdin.\n\n Also, output files are appended to, not overwritten.\n\n Brendan Epstein 06 May 2012\n\"\"\" \n\ndef get_seq_name(seq_rec, slot):\n if slot == \"name\":\n return seq_rec.name\n elif slot == \"description\":\n return seq_rec.description\n elif slot == \"id\":\n return seq_rec.id\n\ndef find_dups(handle, file_format, slot):\n \"\"\" Make a single pass through the file to find duplicate names \n handle is a file handle, file_format is a string. \n Returns a dictionary in which the keys are the duplicated names and\n the values are the number of occurences.\"\"\"\n \n from Bio import SeqIO\n import re\n from collections import Counter\n\n rec_it = SeqIO.parse(handle, file_format)\n\n all_names = [] \n duplicated = set()\n\n name_count = Counter(get_seq_name(rec, slot) for rec in rec_it)\n duplicated = dict((k, v) for k, v in name_count.iteritems() if v > 1)\n\n return duplicated\n \n\ndef revise_duplicates(duplicates, in_handle, revised_handle,\n dup_handle, file_format, slot, \n rename=True, rename_id=True):\n \"\"\"Remove or rename the records with duplicated names.\n duplicates is a dictionary of duplicated names (from find_dups)\n in_handle is the input file, revised_handle is the output file\n with duplicate records removed or renamed,\n dup_handle is the file with duplicated records,\n file_format is a string giving the file format,\n and rename is whether to rename or remove the duplicates.\"\"\"\n\n from Bio import SeqIO\n from collections import defaultdict\n\n rec_it = SeqIO.parse(in_handle, file_format)\n\n dup_count = defaultdict(int)\n for rec in rec_it:\n if get_seq_name(rec, slot) in duplicates:\n if dup_handle is not None:\n SeqIO.write(rec, dup_handle, file_format)\n if rename:\n dup_count[get_seq_name(rec, slot)] += 1\n if rename_id:\n if rec.id == rec.description:\n rec.description = \"\"\n rec.id = rec.id + \"_\" + \\\n str(dup_count[get_seq_name(rec, slot)])\n else:\n rec.description = rec.description + \"_\" + \\\n str(dup_count[get_seq_name(rec, slot)])\n SeqIO.write(rec, revised_handle, file_format)\n else:\n if revised_handle is not None:\n SeqIO.write(rec, revised_handle, file_format)\n\n\nif __name__ == \"__main__\":\n\n import argparse\n import sys\n import os\n\n parser = argparse.ArgumentParser(description='Filter duplicates from sequence files')\n parser.add_argument(\"--doc\", dest=\"doc\", action=\"store_true\", default=False,\n help=\"Print documentation (use '-' as input file)\")\n parser.add_argument(\"--undup\", dest=\"undupfile\", type=argparse.FileType('a'),\n default=None,\n help=\"Output file with unduplicated records\", metavar=\"FILE\")\n parser.add_argument(\"--dup\", dest=\"dupfile\", type=argparse.FileType('a'),\n default=None, metavar=\"FILE\",\n help=\"Output file for duplicated records\")\n parser.add_argument(\"-o\", dest=\"outfile\", type=argparse.FileType('w'),\n default=sys.stdout, metavar=\"FILE\",\n help=\"Output file with duplicated names and counts\")\n parser.add_argument(\"-l\", dest=\"logfile\", metavar=\"FILE\",\n help=\"Logging file (if logging is desired\")\n parser.add_argument(\"--rename\", dest=\"rename\", action=\"store_true\",\n default=False,\n help=\"Rename the duplicated records\")\n parser.add_argument(\"--rename-by\", dest=\"renameby\", default=\"id\", \n metavar=\"STRING\",\n help=\"Rename by the id or the description\")\n parser.add_argument(\"input\", type=argparse.FileType('r'), nargs=1,\n help=\"Input file\", default=\"-\")\n parser.add_argument(\"format\", help=\"Input file format\", nargs=1)\n args = parser.parse_args()\n\n if args.doc:\n parser.print_help()\n print(\"\\n\" + __doc__)\n exit()\n\n dups = find_dups(args.input[0], args.format[0], \"id\")\n args.outfile.write(\"Name\\tCount\\n\")\n for k, v in dups.iteritems():\n args.outfile.write(k + \"\\t\" + str(v) + \"\\n\")\n\n \n # Cannot call seek() on a pipe\n try:\n args.input[0].seek(0)\n\n use_id = (args.renameby.lower() == \"id\")\n\n if args.undupfile != None:\n if args.rename:\n revise_duplicates(dups, args.input[0], args.undupfile,\n args.dupfile, args.format[0], \"id\", \n True, use_id)\n else:\n revise_duplicates(dups, args.input[0], args.undupfile,\n args.dupfile, args.format[0], \"id\", \n False, use_id)\n elif args.dupfile != None:\n revise_duplicates(dups, args.input[0], None,\n args.dupfile, args.format[0], \"id\", \n False, use_id)\n except:\n ()\n \n if(args.logfile != None):\n execfile(os.path.dirname(__file__) + os.sep + \"PyLogger.py\")\n l = args.logfile\n if args.dupfile is None: \n args.dupfile = \"\"\n else:\n args.dupfile = args.dupfile.name\n if args.undupfile is None: \n args.undupfile = \"\"\n else:\n args.undupfile = args.undupfile.name\n logger(l, [args.input[0].name], \n [args.outfile.name, args.dupfile, args.undupfile]) \n","sub_path":"duplicate_names.py","file_name":"duplicate_names.py","file_ext":"py","file_size_in_byte":6545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"358016292","text":"# \"\"\"\n# This is ArrayReader's API interface.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n#class ArrayReader:\n# def get(self, index: int) -> int:\n\nclass Solution:\n def search(self, reader, target):\n low=0\n high=1\n while target>reader.get(high):\n high=high*2\n while low<=high:\n mid =(low+high)//2\n if reader.get(mid)==target:\n return mid\n else:\n if reader.get(mid)/', views.post_detail, name='post_detail'),\n path('urun/', views.urunsayfas, name='urunsayfas'),\n path('urun//', views.urunsayfa, name='urunsayfa'),\n path('blog/', views.contentblog, name='contentblog'),\n path('blog//', views.contentblogdetail, name='contentblogdetail'),\n path('instagram/', views.inputtags, name='inputtags'),\n]\n\n\n\n\n","sub_path":"Shopist/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"113927671","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 5 15:23:33 2019\n\n@author: mbattley\n\"\"\"\n\nimport lightkurve\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport astropy.units as u\nfrom astropy.stats import BoxLeastSquares\nfrom astropy.coordinates import SkyCoord\nfrom glob import glob\nfrom lightkurve import KeplerTargetPixelFile, TessTargetPixelFile\nfrom TESSselfflatten import TESSflatten\nfrom astroquery.mast import Tesscut\nfrom photutils import MMMBackground, MeanBackground, MedianBackground, ModeEstimatorBackground, SExtractorBackground\nfrom photutils import CircularAperture\nfrom astropy.stats import SigmaClip\n\ntpf1 = lightkurve.search.open('TESS_Sector_1_cutouts/tess-s0001-3-1_20.79808333_-69.36066667_11x11_astrocut.fits')\ntpf2 = lightkurve.search.open('TESS_Sector_1_cutouts/tess-s0002-3-3_20.79808333_-69.36066667_11x11_astrocut.fits')\n\nmedian_image1 = np.nanmedian(tpf1.flux, axis=0)\nmedian_image2 = np.nanmedian(tpf2.flux, axis=0)\n\n# Select pixels which are brighter than the 85th percentile of the median image\n#aperture_mask1 = median_image1 > np.nanpercentile(median_image1, 85)\n#aperture_mask2 = median_image2 > np.nanpercentile(median_image2, 85)\n\n# Make center aperture for crowded fields\ncrowded_field_aperture = np.zeros((11,11))\ncrowded_field_aperture2 = np.zeros((11,11))\ncrowded_field_aperture[5:8,4:7] = 1\ncrowded_field_aperture2[4:7,5:8] = 1\ncrowded_field_aperture = crowded_field_aperture.astype(np.bool)\ncrowded_field_aperture2 = crowded_field_aperture2.astype(np.bool)\naperture_mask1 = crowded_field_aperture\naperture_mask2 = crowded_field_aperture2\n\n\ntpf1.plot(aperture_mask = aperture_mask1)\ntpf2.plot(aperture_mask = aperture_mask2)\n\n# Plot separate lightcurves\ntpf1.to_lightcurve(aperture_mask = aperture_mask1).plot()\ntpf2.to_lightcurve(aperture_mask = aperture_mask2).plot()\n\n# Convert to lightcurves\nlc1 = tpf1.to_lightcurve(aperture_mask = aperture_mask1)\nlc2 = tpf2.to_lightcurve(aperture_mask = aperture_mask2)\n\nend_lc1 = lc1.time[-1]\nstart_lc2 = lc2.time[0]\n\nprint('End of lc1 = {}'.format(end_lc1))\nprint('Start of lc1 = {}'.format(start_lc2))\n\n# Combine and plot lightcurves\ncombined_lc = lc1\ncombined_lc = combined_lc.append(lc2)\ncombined_lc.plot()\n\n# Remove outliers\n#sigma_clipped_lc = combined_lc.remove_outliers(sigma = 3)\n#sigma_clipped_lc.plot()\n\n# Perform Dave's flattening on combined lightcurve\ntime_from_zero = combined_lc.time - combined_lc.time[0]\nlcurve = np.vstack((time_from_zero, combined_lc.flux, combined_lc.flux_err)).T\nTESSflatten_lc = TESSflatten(lcurve, winsize = 3.5, stepsize = 0.15, gapthresh = 0.1)\n\n# Plot result\nplt.figure()\nplt.scatter(combined_lc.time[0:2477], TESSflatten_lc, c = 'k', s = 1, label = 'TESSflatten flux')\nplt.title('2MASS J01231125-6921379 with TESSflatten - Sectors 1&2')\nplt.ylabel('Normalized Flux')\nplt.xlabel('Time - 2457000 [BTJD days]')","sub_path":"quick_combine_lightkurves.py","file_name":"quick_combine_lightkurves.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"1858979","text":"# Momijigaoka (807000000)\n\nfrom net.swordie.ms.constants import JobConstants\n\n# Relevant to Hayato only. For some reason, Kanna is unaffected.\n# Certain NPCs in Momijigaoka are meant to be unhidden as Hayato progresses through his 1st job questline.\n# Since Hayato's quests are not completely scripted, this script will bypass certain npc-enabling quests by leveling.\n# This will allow Hayato to see the quests' corresponding NPCs, and accept his mount quest from Shingen.\n\nquestList = [\n (57113, 17), # Cutting a Swath\n (57119, 21), # Fox Tail Mystery\n (57141, 29), # Honnou-ji Infiltration 2 [Hayato]\n (57143, 30) # Internal Affairs [Hayato]\n]\n\njob = chr.getJob()\n\nif JobConstants.isHayato(job):\n currentLevel = chr.getLevel()\n for quest in questList:\n if currentLevel >= quest[1] and not sm.hasQuestCompleted(quest[0]):\n sm.completeQuestNoRewards(quest[0])","sub_path":"scripts/field/momiji_Enter.py","file_name":"momiji_Enter.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"365246410","text":"import base64\nfrom pathlib import Path\nimport yaml\nimport torch\n\n\ndef load_settings(root_path):\n with open(root_path / \"settings.yaml\") as file:\n # The FullLoader parameter handles the conversion from YAML\n # scalar values to Python the dictionary format\n return yaml.load(file, Loader=yaml.FullLoader)\n\n\ndef load_model(model_string):\n # Write to temp file for kaggle submission\n with open(\"model.dat\", \"wb\") as f:\n f.write(base64.b64decode(model_string))\n f.close()\n return torch.load('model.dat')\n\n\nROOT_PATH = Path(__file__).resolve().parent.parent\nSETTINGS = load_settings(ROOT_PATH)\n\n_model_path = ROOT_PATH / SETTINGS[\"learn\"][\"models\"][\"save_dir\"]\n_robot_agent_model_path = _model_path / SETTINGS[\"learn\"][\"models\"][\"robot_agent_file\"]\n\nROBOT_AGENT_STATE_DICT = torch.load(_robot_agent_model_path)\n\n\nTORCH_DEVICE = torch.device(\"cuda\")\n","sub_path":"src/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"422032931","text":"# -*- mode: python -*-\n\nblock_cipher = None\n\n\na = Analysis(['gui_server.py'],\n pathex=['C:\\\\sinftools\\\\Miniconda3\\\\Lib\\\\site-packages\\\\PyQt5\\\\Qt\\\\bin', 'C:\\\\sinftools\\\\tools\\\\report4\\\\reader'],\n binaries=[],\n datas=[('templates', 'templates'), ('static', 'static'), ('reader_server\\\\resources', 'reader_server\\\\resources'), ('report_docx\\\\templates', 'report_docx\\\\templates')],\n hiddenimports=['sqlalchemy.ext.baked', 'PyQt5.sip', 'inflection'],\n hookspath=[],\n runtime_hooks=[],\n excludes=[],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher)\npyz = PYZ(a.pure, a.zipped_data,\n cipher=block_cipher)\nexe = EXE(pyz,\n a.scripts,\n exclude_binaries=True,\n name='gui_server',\n debug=False,\n strip=False,\n upx=True,\n console=False )\ncoll = COLLECT(exe,\n a.binaries,\n a.zipfiles,\n a.datas,\n strip=False,\n upx=True,\n name='gui_server')\n","sub_path":"reader/gui_server.spec","file_name":"gui_server.spec","file_ext":"spec","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"151119784","text":"# -*- coding: utf-8 -*-\n\nimport unittest\n\nfrom testbase import TestCase\nfrom model import ViewedHairSalonEs\nimport common_test\n\n\nclass ModelViewedHairSalonEsTest(TestCase):\n\n def setUp(self):\n \"\"\"\"\"\"\n super(ModelViewedHairSalonEsTest, self).setUp()\n\n def tearDown(self):\n \"\"\"\"\"\"\n super(ModelViewedHairSalonEsTest, self).tearDown()\n\n def test_push(self):\n \"\"\"Test that I can't add two times the same id,\n that the last added is the first in the list\n and can't have more than 10 results\n\n \"\"\"\n list_name = ViewedHairSalonEs.list_name\n ViewedHairSalonEs.push(1, 2)\n viewed_list = ViewedHairSalonEs.get_by_id(1)\n assert 2 == viewed_list[list_name][0]\n ViewedHairSalonEs.push(1, 3)\n viewed_list = ViewedHairSalonEs.get_by_id(1)\n assert 3 == viewed_list[list_name][0]\n assert 2 == viewed_list[list_name][1]\n #I'll add again 2 so it must be removed and put at the beggining\n ViewedHairSalonEs.push(1, 2)\n viewed_list = ViewedHairSalonEs.get_by_id(1)\n assert 2 == viewed_list[list_name][0]\n assert 3 == viewed_list[list_name][1]\n #check that I don' get mote than 10 results\n for x in range(4, 20):\n ViewedHairSalonEs.push(1, x)\n viewed_list = ViewedHairSalonEs.get_by_id(1)\n assert len(viewed_list[list_name]) == 10\n\n\nif __name__ == '__main__':# pragma: no cover\n unittest.main()\n","sub_path":"test/model_viewed_hair_salon_es.py","file_name":"model_viewed_hair_salon_es.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"583258469","text":"__author__ = 'gabriel'\n\n\nfrom Enxame import *\nfrom geraParticula import *\nimport copy\n\n\n\n\ndef geraEnxame(patio, demanda, qtdParticulas):\n\n lstParticulas = []\n cont = 0\n while(cont < qtdParticulas):\n\n p = geraParticula(copy.deepcopy(patio), copy.deepcopy(demanda))\n if(p != None):\n lstParticulas.append(p)\n if(cont == 0):\n melhor_part = lstParticulas[0]\n else:\n if(p.custo < melhor_part.custo):\n melhor_part = p\n cont+=1\n enxame = Enxame(qtdParticulas,patio, demanda, melhor_part, lstParticulas)\n\n return enxame\n\n\n\n\n\n\n\n\n","sub_path":"geraEnxame.py","file_name":"geraEnxame.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"644885667","text":"from PySide2.QtCore import *\nfrom PySide2.QtGui import *\nfrom PySide2.QtWidgets import *\nimport functools\nimport maya.cmds as cmds\nimport maya.mel as mm\nimport logging\nfrom an_classControllers import AnControllers\nfrom an_Procedures.joints import jntOnCurvNonSpline\nfrom an_Procedures.connect import an_connectRigVis\nfrom maya.app.general.mayaMixin import MayaQWidgetBaseMixin # for parent ui to maya\n\nABOUT_SCRIPT = \"\\n\" \\\n \"Latest updates: \\n\" \\\n \"26.02.2021 -added ability to scale \\n\" \\\n \"24.02.2021 -added choice of solvers \\n\" \\\n \"03.02.2021 -added attribut prefix to control \\n\" \\\n \"27.01.2021 -start writing \\n\" \\\n \" \\n\" \\\n \"Created by Andrey Belyaev \\n\" \\\n \"andreikin@mail.ru\"\n\nHELP_LABEL = \"Select a chain of bones (more than two joints) on the basis of which will be\\n\" \\\n \"created FK controllers and a dynamic curve\\n\"\n\nHELP_TEXT = \"\\n\" \\\n \"1 Build the bone chain by placing the joints where the controllers should be.\\n\" \\\n \"2 Adjust their orientation - the controllers will be oriented in a similar way\\n\" \\\n \"3 Make sure the bones are out of the collision objects \\n\" \\\n \"4 The root joint must have a parent, to which the system will be attached later\\n\" \\\n \"5 Choose 'Create dynanmics sistem'\\n\" \\\n \"\\n\" \\\n \"For normal scaling, create a scale constraint for the group with Fk controllers\\n\" \\\n \"\\n\" \\\n \"To create driver attribute on a switch - select the nucleus, then the switch and\\n\" \\\n \"press the button 'Connect nucleus'\"\n\nlogging.basicConfig( format=\"%(asctime)s line: %(lineno)s - function %(funcName)s() %(message)s\")\nlogger = logging.getLogger()\nlogger.handlers = []\nlogger.setLevel(logging.WARNING)\n\nDEFAULT_PREFIX = \"hairsStrand\"\nMAX_VERTEX_NUM = 40\nDEFAULT_VERTEX_NUM = 4\nMAX_JOINT_NUM = 40\nDEFAULT_JOINT_NUM = 12\nPOINT_NUM_IN_DYN_CONSTRAINT = 2\n\n\nclass HairStrand_UI(MayaQWidgetBaseMixin, QMainWindow):\n def __init__(self):\n super(HairStrand_UI, self).__init__()\n self.setWindowTitle(\"Hair strand rigging system\")\n self.centralwidget = QWidget(self)\n self.setCentralWidget(self.centralwidget)\n self.verticalLayout = QVBoxLayout(self.centralwidget)\n \n # menu_bar\n menu_bar = QMenuBar()\n self.setMenuBar(menu_bar)\n menu = QMenu(\"Help\")\n menu_bar.addMenu(menu)\n help_action = QAction(\"Help\", self)\n menu.addAction(help_action)\n help_action.triggered.connect(functools.partial(self.text_dialog, \"Help\"))\n about_script_action = QAction(\"About script\", self)\n menu.addAction(about_script_action)\n about_script_action.triggered.connect(functools.partial(self.text_dialog, \"ABOUT_PROGRAM\"))\n \n # text \n self.help_label = QLabel(HELP_LABEL)\n self.verticalLayout.addWidget(self.help_label)\n\n # option_box \n self.option_box = QGroupBox(\"Options:\")\n self.option_box_layout = QVBoxLayout(self.option_box)\n self.form_layout = QFormLayout()\n \n # text line Prefix\n self.pfx_lineEdit = QLineEdit(DEFAULT_PREFIX)\n regexp = QRegExp('^([A-Za-z_]+[0-9]+)$')\n validator = QRegExpValidator(regexp)\n self.pfx_lineEdit.setValidator(validator)\n label_prefix = QLabel(\"Prefix:\")\n self.form_layout.addRow(label_prefix,self.pfx_lineEdit)\n \n # combobox\n self.solver_combobox = QComboBox()\n self.solver_combobox.addItem(\"New solver\")\n self.getSolvers()\n label_connect = QLabel(\"Connect to:\")\n self.form_layout.addRow(label_connect,self.solver_combobox)\n self.option_box_layout.addLayout(self.form_layout)\n \n # line\n self.line = QFrame() \n self.line.setFrameShape(QFrame.HLine)\n self.line.setFrameShadow(QFrame.Sunken)\n self.option_box_layout.addWidget(self.line)\n \n # slider Points number\n self.curve_hLayout = QHBoxLayout()\n self.curve_label = QLabel(\"Points number :\")\n self.curve_hLayout.addWidget(self.curve_label)\n self.curve_horizontal_slider = QSlider()\n self.curve_horizontal_slider.setMinimum(1)\n self.curve_horizontal_slider.setMaximum(MAX_VERTEX_NUM)\n self.curve_horizontal_slider.setSliderPosition(DEFAULT_VERTEX_NUM)\n self.curve_horizontal_slider.setOrientation(Qt.Horizontal)\n self.curve_hLayout.addWidget(self.curve_horizontal_slider)\n self.curve_spin_box = QSpinBox()\n self.curve_spin_box.setMinimum(1)\n self.curve_spin_box.setMaximum(MAX_VERTEX_NUM)\n self.curve_spin_box.setValue(DEFAULT_VERTEX_NUM)\n self.curve_hLayout.addWidget(self.curve_spin_box)\n self.curve_horizontal_slider.valueChanged.connect(self.curve_spin_box.setValue)\n self.curve_spin_box.valueChanged.connect(self.curve_horizontal_slider.setValue)\n self.option_box_layout.addLayout(self.curve_hLayout)\n \n # slider Joints number\n self.horizontalLayout_2 = QHBoxLayout()\n self.joints_label = QLabel(\"Joints number :\")\n self.horizontalLayout_2.addWidget(self.joints_label)\n self.joints_horizontal_slider = QSlider()\n self.joints_horizontal_slider.setMinimum(3)\n self.joints_horizontal_slider.setMaximum(MAX_JOINT_NUM)\n self.joints_horizontal_slider.setSliderPosition(DEFAULT_JOINT_NUM)\n self.joints_horizontal_slider.setOrientation(Qt.Horizontal)\n self.horizontalLayout_2.addWidget(self.joints_horizontal_slider)\n self.joints_spin_box = QSpinBox()\n self.joints_spin_box.setObjectName(u\"joints_spin_box\")\n self.joints_spin_box.setMinimum(3)\n self.joints_spin_box.setMaximum(MAX_JOINT_NUM)\n self.joints_spin_box.setValue(DEFAULT_JOINT_NUM)\n self.horizontalLayout_2.addWidget(self.joints_spin_box)\n self.joints_horizontal_slider.valueChanged.connect(self.joints_spin_box.setValue)\n self.joints_spin_box.valueChanged.connect(self.joints_horizontal_slider.setValue)\n self.option_box_layout.addLayout(self.horizontalLayout_2)\n self.verticalLayout.addWidget(self.option_box)\n\n # buttons \n self.buttons_layout = QHBoxLayout()\n self.connect_nucleus_button = QPushButton(\"Connect nucleus\")\n self.buttons_layout.addWidget(self.connect_nucleus_button)\n self.connect_nucleus_button.clicked.connect(self.connect_nucleus)\n self.create_button = QPushButton(\"Create dynamics system\")\n self.buttons_layout.addWidget(self.create_button)\n self.verticalLayout.addLayout(self.buttons_layout)\n self.create_button.clicked.connect(self.create_rig)\n logger.debug(\"ui executed\")\n\n def text_dialog(self, text_type):\n help_dialog = QMessageBox()\n help_dialog.setWindowFlags(Qt.WindowStaysOnTopHint)\n if text_type == \"Help\":\n help_dialog.setWindowTitle(\"Help window\")\n help_dialog.setText(HELP_TEXT)\n else:\n help_dialog.setWindowTitle(\"About program\")\n help_dialog.setText(ABOUT_SCRIPT)\n help_dialog.setStandardButtons(QMessageBox.Cancel)\n help_dialog.exec_()\n logger.debug(\" executed\")\n\n\nclass HairStrandRig(HairStrand_UI):\n def create_rig(self):\n self.get_data_from_ui()\n if self.get_objects_and_chek_it():\n self.rig_grp = cmds.group(empty=True, name=self.prefx + 'Rig_grp')\n self.fk_rigging()\n self.building_base_curve()\n self.building_dynamic_curve()\n self.fk_dynamics_mix_system()\n self.add_skin_joints()\n an_connectRigVis(self.rig_grp,\n [self.input_curve, self.hair_sys, self.dyn_curve_grp, self.dyn_constraint, self.loc, ])\n print(\"Strand rigging successfully complete.\")\n\n def get_data_from_ui(self):\n self.prefx = self.pfx_lineEdit.text()\n if not self.prefx:\n logging.getLogger().warning(\"You did not enter a prefix, the default value will be used!\")\n self.prefx = DEFAULT_PREFIX\n self.point_number = self.curve_horizontal_slider.value()\n self.joint_number = self.joints_horizontal_slider.value()\n\n def get_objects_and_chek_it(self):\n self.joints = cmds.ls(sl=True)\n if cmds.objExists(self.prefx+'Rig_grp'):\n cmds.error(\"Scene already contains objects with this prefix, choose another \")\n if len(self.joints) < 3 :\n logging.getLogger().error(\"Necessary to select at least three joints!\")\n return False\n for jnt in self.joints:\n if not cmds.nodeType(jnt)==\"joint\":\n cmds.error(\"Necessary to select at least three joints!\")\n return False\n # get an object to which the entire system will be bound by the constraint\n try:\n self.parent_object = cmds.listRelatives(self.joints[0], parent=True)[0]\n except TypeError:\n self.parent_object = None\n logging.getLogger().warning(\"No parent, so the system will not be attached!\")\n return True\n\n def fk_rigging(self):\n self.controls = []\n self.fk_grp = cmds.group(empty=True, name=self.prefx + 'FK_grp')\n cmds.parent(self.fk_grp, self.rig_grp)\n if self.parent_object:\n cmds.parentConstraint(self.parent_object, self.fk_grp)\n for i, jnt in enumerate(self.joints[:-1]):\n ctrl = AnControllers(self.prefx + str(i) + \"_CT\")\n ctrl.makeController(shapeType=\"fk\", orient=\"X\", pos=jnt)\n ctrl.hideAttr(['sx', 'sy', 'sz', 'v'])\n self.controls.append(ctrl)\n if i == 0:\n cmds.parent(ctrl.oriGrp, self.fk_grp)\n else:\n cmds.parent(ctrl.oriGrp, self.controls[i - 1].name)\n cmds.parentConstraint(ctrl.name, jnt)\n # add attribute to determine whether the controller belongs to dynamic system\n cmds.addAttr(ctrl.name, longName='prefix', dt='string', keyable=False)\n cmds.setAttr(ctrl.name + \".prefix\", self.prefx, type=\"string\")\n logger.debug(\" executed\")\n\n def building_base_curve(self):\n point_position = []\n for jnt in self.joints:\n jnt_coordinates = cmds.xform(jnt, query=True, translation=True, worldSpace=True)\n point_position.append(jnt_coordinates)\n self.base_curve = cmds.curve(p=point_position, degree=2, name=self.prefx + 'FK_crv')\n cmds.skinCluster(self.joints, self.base_curve, toSelectedBones=True, normalizeWeights=True)\n cmds.rebuildCurve(self.base_curve,\n rebuildType=0,\n spans=self.point_number,\n constructionHistory=True)\n cmds.parent(self.base_curve, self.rig_grp)\n logger.debug(\" executed\")\n\n def building_dynamic_curve(self):\n \n existing_solvers = cmds.ls(type= \"nucleus\")\n self.input_curve = cmds.duplicate(name=self.prefx + 'Input_crv', inputConnections=True)[0]\n mm.eval('makeCurvesDynamic 2 { \"0\", \"0\", \"1\", \"1\", \"0\"};')\n crv_shape = cmds.listRelatives(self.input_curve, shapes=True)[1]\n # getting names of all dynamics objects and rename it\n follicle = cmds.listConnections(crv_shape + \".local\")[0]\n follicle = cmds.rename(follicle, self.prefx + '_follicle')\n cmds.setAttr(follicle + \".pointLock\", 0)\n fol_shape = cmds.listRelatives(follicle, shapes=True)[0]\n dyn_curve_shape = cmds.connectionInfo(fol_shape + \".outCurve\", destinationFromSource=True)[0].split('.')[0]\n self.dyn_curve = cmds.listRelatives(dyn_curve_shape, parent=True)[0]\n self.hair_sys_shape = cmds.connectionInfo(fol_shape + \".outHair\", destinationFromSource=True)[0].split('.')[0]\n self.hair_sys = cmds.listRelatives(self.hair_sys_shape, parent=True)[0]\n self.setup_mix_attribut()\n self.hair_sys = cmds.rename(self.hair_sys, self.prefx + '_hairSystem')\n self.dyn_curve_grp = cmds.listRelatives(self.dyn_curve, parent=True)[0]\n self.dyn_curve = cmds.rename(self.dyn_curve, self.prefx + 'Dynamics_crv')\n cmds.select(self.dyn_curve + '.cv[0:{}]'.format(POINT_NUM_IN_DYN_CONSTRAINT))\n dynamicConstraintShape = mm.eval('createNConstraint transform 0;')[0]\n self.dyn_constraint = cmds.listRelatives(dynamicConstraintShape, parent=True)[0]\n cmds.parentConstraint(self.controls[0].name, self.dyn_constraint)\n cmds.parent(self.hair_sys, self.dyn_curve_grp, self.dyn_constraint, self.rig_grp)\n \n # handling solver\n combo_box_value = self.solver_combobox.currentText()\n if combo_box_value == \"New solver\":\n if existing_solvers:\n cmds.select(self.hair_sys)\n mm.eval('assignNSolver \"\"')\n else:\n cmds.select(self.hair_sys)\n mm.eval('assignNSolver \"{}\"'.format(combo_box_value)) \n self.refresh_combo_box_list() \n logger.debug(\" executed\")\n \n def refresh_combo_box_list(self):\n self.solver_combobox.clear()\n self.solver_combobox.addItem(\"New solver\")\n self.getSolvers()\n \n def getSolvers(self):\n solvers = cmds.ls(type= \"nucleus\")\n for solver in solvers:\n self.solver_combobox.addItem(solver)\n \n def setup_mix_attribut(self):\n soft_suffix = \"_soft\"\n hard_suffix = \"_hard\"\n atributes = {\"stretchResistance\": (0, 200),\n \"compressionResistance\": (0, 200),\n \"bendResistance\": (0, 200),\n \"mass\": (0, 10),\n \"drag\": (0, 1),\n \"damp\": (0, 10)}\n self.controls[0].addDevideAttr()\n driver_attr = self.controls[0].name\n cmds.addAttr(driver_attr, longName=\"stiffness\", keyable=True, minValue=0, maxValue=1)\n for atrribut in atributes:\n default_val = cmds.getAttr(self.hair_sys_shape + \".\" + atrribut)\n cmds.addAttr(self.hair_sys,\n longName=atrribut + soft_suffix,\n keyable=True,\n minValue=atributes[atrribut][0],\n maxValue=atributes[atrribut][1],\n defaultValue=default_val)\n cmds.addAttr(self.hair_sys,\n longName=atrribut + hard_suffix,\n keyable=True,\n minValue=atributes[atrribut][0],\n maxValue=atributes[atrribut][1],\n defaultValue=default_val * 4)\n blend_node = cmds.createNode('blendTwoAttr', n=atrribut + 'Blend_nod')\n cmds.connectAttr(self.hair_sys + \".\" + atrribut + soft_suffix, blend_node + \".input[0]\")\n cmds.connectAttr(self.hair_sys + \".\" + atrribut + hard_suffix, blend_node + \".input[1]\")\n cmds.connectAttr(blend_node + \".output\", self.hair_sys_shape + \".\" + atrribut)\n cmds.connectAttr(driver_attr + \".stiffness\", blend_node + \".attributesBlender\")\n logger.debug(\" executed\")\n\n def fk_dynamics_mix_system(self):\n cmds.addAttr(self.controls[0].name,\n longName=\"fk_dyn_mix\",\n keyable=True,\n defaultValue=1,\n minValue=0,\n maxValue=1)\n bldShape = cmds.blendShape(self.dyn_curve, self.base_curve,\n origin=\"world\",\n name=self.prefx + 'blendShape')[0]\n cmds.connectAttr(self.controls[0].name + \".fk_dyn_mix\", bldShape + \".\" + self.dyn_curve)\n logger.debug(\" executed\")\n\n def add_skin_joints(self):\n self.loc, self.jointsNames, skin_jnt_grp = jntOnCurvNonSpline(self.base_curve, self.joint_number, self.prefx)\n cmds.parent(skin_jnt_grp, self.rig_grp)\n cmds.parent(self.loc, self.controls[0].name)\n an_connectRigVis(self.rig_grp, self.jointsNames)\n logger.debug(\" executed\")\n for jnt in self.jointsNames:\n cmds.connectAttr(self.fk_grp+\".scale\", jnt +\".scale\")\n \n\n def connect_nucleus(self):\n try:\n nucleus, switch = cmds.ls(sl=True)\n except ValueError:\n cmds.error(\"Select nucleus, then switch and click the 'connect' button \")\n \n if not cmds.objExists(switch + \".haer_dynamics\"):\n cmds.addAttr(switch, ln=\"haer_dynamics\", at=\"enum\", en=\"off:on\", keyable=True)\n cmds.connectAttr(switch + \".haer_dynamics\", nucleus + \".enable\")\n logger.debug(\" executed\")\n\n\ndef hair_strand_rig():\n global dyn_win\n try:\n dyn_win.deleteLater()\n except NameError:\n pass\n dyn_win = HairStrandRig()\n dyn_win.show()\n logger.debug(\" window is opened\")\n\n\nif __name__ == '__main__':\n hair_strand_rig()\n \n \n \n","sub_path":"hair_strand_rig/hair_strand_rig.py","file_name":"hair_strand_rig.py","file_ext":"py","file_size_in_byte":17214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"79190125","text":"#!/usr/bin/env python\nimport re\nfrom random import choice\n\n\ndef fake_ai(msg):\n yes_or_no = ['是', '不是!']\n answer = ['我不知道你在说什么', '我无法回答你的问题', '这是什么?']\n\n if (msg == '你好') or ('晚上好' in msg) or ('早上好' in msg):\n return '你好, 很高兴见到你!'\n elif ('再见' in msg) or ('bye' in msg):\n return '好的, 祝你有个愉快的一天'\n elif ('谢谢' in msg) or ('谢谢你' in msg):\n return '不客气哦'\n elif ('hi' in msg) or ('hello' in msg):\n return 'hi'\n elif '是不是' in msg:\n return choice(yes_or_no)\n elif ('你' in msg) and ('吗' in msg):\n msg = re.sub('你', '我', msg)\n return msg.strip('吗?') + '!'\n elif '我' in msg:\n msg = re.sub('我', '你', msg)\n return msg.strip('吗?') + '!'\n elif '吗' in msg:\n return msg.strip('吗?') + '!'\n elif re.match(r'.{1,3}\\?', msg):\n return msg.strip('?') + '!'\n elif ('好' in msg) or ('真' in msg) or ('太' in msg):\n return '谢谢!'\n else:\n return choice(answer)\n\n\nif __name__ == '__main__':\n print('你好, 我是 Lucy.')\n while True:\n msg = input()\n f = fake_ai(msg)\n print(f)\n if (msg == '再见') or (msg == 'bye'):\n break\n","sub_path":"book_01_Python核心編程/chapter_02_网络编程/ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"531600082","text":"\"\"\"---------------------------------------------------------------------------------------------------------------------\nMODULE\n EnvironmentFunctions.\n\nDESCRIPTION\n This module contains functionality for obtaining information about the current\n Front Arena environment.\n\n------------------------------------------------------------------------------------------------------------------------\nHISTORY\n========================================================================================================================\nDate Change no Developer Description\n------------------------------------------------------------------------------------------------------------------------\n2018-11-23 Cuen Edwards Initial implementation providing central services for logic\n that was duplicated in several places.\n2019-04-05 FAOPS-448 Cuen Edwards Addition of Operations STP parameters.\n2019-09-17 FAOPS-460 Cuen Edwards Addition of Document Processing parameters.\n2020-07-29 FAOPS-866 Cuen Edwards Addition of supported client versions for an environment.\n2020-10-21 FAOPS-959 Ncediso Nkambule Addition of Operations NeoX activity report parameter.\n------------------------------------------------------------------------------------------------------------------------\n\"\"\"\n\nimport xml.etree.ElementTree as ElementTree\n\nimport acm\n\n\ndef get_environment_name():\n \"\"\"\n Get the name of the current environment.\n \"\"\"\n return acm.FDhDatabase['ADM'].InstanceName()\n\n\ndef is_production_environment():\n \"\"\"\n Determine whether or not the current environment is a production\n environment.\n\n Please note that while DR uses different environment settings, it\n is also considered a production environment as it becomes the\n production environment in the event of a disaster.\n \"\"\"\n settings_name = get_environment_settings_name()\n return settings_name in ['PRODSetting', 'DRSetting']\n\n\ndef get_supported_client_versions():\n \"\"\"\n Get the client versions supported by the current environment.\n \"\"\"\n return _get_environment_parameters('Client_Version_Config_Settings', 'client version settings',\n 'Version', base_xpath='Supported_Versions', minimum_occurrences=1)\n\n\ndef get_environment_settings_name():\n \"\"\"\n Get the name of the settings to use for the current environment.\n \"\"\"\n root_element = ElementTree.fromstring(acm.GetDefaultValueFromName(acm.GetDefaultContext(),\n acm.FObject, 'EnvironmentSettings'))\n ads_address = acm.ADSAddress()\n all_host_elements = root_element.findall('Environment/Host')\n ads_host_elements = [\n ads_host_element for ads_host_element in all_host_elements\n if ads_host_element.get('Name').lower() == ads_address.lower()\n ]\n if len(ads_host_elements) == 0:\n raise ValueError('No environment settings name found for ADS address {ads_address}'.format(\n ads_address=ads_address\n ))\n elif len(ads_host_elements) > 1:\n raise ValueError('More than one environment settings name found for ADS address {ads_address}'.format(\n ads_address=ads_address\n ))\n return str(ads_host_elements[0].get('Setting'))\n\n\ndef get_confirmation_parameter(parameter_name):\n \"\"\"\n Get an FConfirmationParameter for the current environment.\n \"\"\"\n return _get_single_required_environment_parameter('FConfirmation_Config_Settings', 'confirmation settings',\n parameter_name)\n\n\ndef get_documentation_parameter(parameter_name):\n \"\"\"\n Get an FDocumentationParameter for the current environment.\n\n Please note that these parameters are for the core FDocumentationParameters\n and not the custom documentation solution built on top of business processes.\n \"\"\"\n return _get_single_required_environment_parameter('FDocumentation_Config_Settings', 'documentation settings',\n parameter_name)\n\n\ndef get_settlement_parameter(parameter_name):\n \"\"\"\n Get an FSettlementParameter for the current environment.\n \"\"\"\n return _get_single_required_environment_parameter('FSettlement_Config_Settings', 'settlement settings',\n parameter_name)\n\n\ndef get_operations_stp_parameter(parameter_name):\n \"\"\"\n Get an OperationsSTPParameter for the current environment.\n \"\"\"\n return _get_single_required_environment_parameter('OperationsSTP_Config_Settings', 'operations STP settings',\n parameter_name)\n\n\ndef get_neox_activity_report_parameter(parameter_name):\n \"\"\"\n Get an NeoXActivityReportParameters for the current environment.\n \"\"\"\n return _get_single_required_environment_parameter(\n config_settings_name='NeoXActivityReport_Config_Settings',\n config_settings_display_name='neox activity reports settings',\n parameter_name=parameter_name)\n\n\ndef get_document_processing_parameter(parameter_name):\n \"\"\"\n Get a DocumentProcessingParameter for the current environment.\n\n Please note that these parameters are for the custom documentation\n solution built on top of business processes and not the core\n FDocumentationParameters.\n \"\"\"\n return _get_single_required_environment_parameter('DocumentProcessing_Config_Settings',\n 'document processing settings', parameter_name)\n\n\ndef _get_single_required_environment_parameter(config_settings_name, config_settings_display_name, parameter_name):\n \"\"\"\n Get a single required environment parameter for the current environment.\n \"\"\"\n return _get_environment_parameters(config_settings_name, config_settings_display_name, parameter_name,\n minimum_occurrences=1, maximum_occurrences=1)[0]\n\n\ndef _get_environment_parameters(config_settings_name, config_settings_display_name, parameter_name, base_xpath='',\n minimum_occurrences=None, maximum_occurrences=None):\n \"\"\"\n Get environment parameters for the current environment.\n \"\"\"\n environment_element = _get_environment_config_element(config_settings_name, config_settings_display_name)\n xpath = parameter_name\n if len(base_xpath) > 0:\n xpath = base_xpath + '/' + xpath\n parameter_elements = environment_element.findall(xpath)\n number_of_elements = len(parameter_elements)\n if minimum_occurrences is not None and number_of_elements < minimum_occurrences:\n if number_of_elements == 0:\n error_message = 'No environment {display_name} {parameter_name} parameter found for ADS '\n error_message += 'address {ads_address}.'\n raise ValueError(error_message.format(\n display_name=config_settings_display_name,\n parameter_name=parameter_name,\n ads_address=acm.ADSAddress()\n ))\n else:\n plural_suffix = ''\n if minimum_occurrences > 1:\n plural_suffix = 's'\n error_message = 'Less than {minimum_occurrences} environment {display_name} {parameter_name} '\n error_message += 'parameter{plural_suffix} found for ADS address {ads_address}.'\n raise ValueError(error_message.format(\n minimum_occurrences=minimum_occurrences,\n display_name=config_settings_display_name,\n parameter_name=parameter_name,\n plural_suffix=plural_suffix,\n ads_address=acm.ADSAddress()\n ))\n if maximum_occurrences is not None and number_of_elements > maximum_occurrences:\n plural_suffix = ''\n if maximum_occurrences > 1:\n plural_suffix = 's'\n error_message = 'More than {maximum_occurrences} environment {display_name} {parameter_name} '\n error_message += 'parameter{plural_suffix} found for ADS address {ads_address}.'\n raise ValueError(error_message.format(\n maximum_occurrences=maximum_occurrences,\n display_name=config_settings_display_name,\n parameter_name=parameter_name,\n plural_suffix=plural_suffix,\n ads_address=acm.ADSAddress()\n ))\n return [\n parameter_element.text for parameter_element in parameter_elements\n ]\n\n\ndef _get_environment_config_element(config_settings_name, config_settings_display_name):\n \"\"\"\n Get the environment element for a particular configuration and\n the current environment.\n\n Exactly one element is expected to exist for an environment (either\n explicitly defined for the environment, via the settings name mapped\n for the environment, or implicitly defined, via default settings).\n \"\"\"\n root_element = ElementTree.fromstring(acm.GetDefaultValueFromName(acm.GetDefaultContext(), acm.FObject,\n config_settings_name))\n # Look for settings defined for the current environments settings name.\n environment_elements = _get_environment_element(config_settings_display_name, root_element,\n get_environment_settings_name())\n if len(environment_elements) == 0:\n # Fallback on any default settings (if present).\n environment_elements = _get_environment_element(config_settings_display_name, root_element, 'DefaultSetting')\n if len(environment_elements) == 0:\n error_message = 'No environment {display_name} found for ADS address {ads_address}.'\n raise ValueError(error_message.format(\n display_name=config_settings_display_name,\n ads_address=acm.ADSAddress()\n ))\n return environment_elements[0]\n\n\ndef _get_environment_element(config_settings_display_name, root_element, environment_settings_name):\n \"\"\"\n Get the environment element for a particular configuration and\n settings name.\n\n Zero or one element is expected to exist for a settings name.\n \"\"\"\n select_expression = \"Environment[@ArenaDataServer='{environment_settings_name}']\".format(\n environment_settings_name=environment_settings_name\n )\n environment_elements = root_element.findall(select_expression)\n if len(environment_elements) > 1:\n error_message = 'More than one {display_name} environment element found for settings {settings_name}.'\n raise ValueError(error_message.format(\n display_name=config_settings_display_name,\n settings_name=environment_settings_name\n ))\n return environment_elements\n","sub_path":"Extensions/ABSAIntegrationConfigSettings/FPythonCode/EnvironmentFunctions.py","file_name":"EnvironmentFunctions.py","file_ext":"py","file_size_in_byte":10414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"75295735","text":"from math import sqrt\n\n\ndef numSquares(n):\n dp = [0x7fffffff for _ in range(n+1)]\n dp[0] = 0\n for i in range(1, n+1):\n for j in range(1, int(sqrt(i))+1):\n dp[i] = min(dp[i-j*j]+1, dp[i])\n return dp[-1]","sub_path":"google/279_pefect_squares.py","file_name":"279_pefect_squares.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"479497738","text":"import re\nimport os\nimport time\nimport chardet\nimport requests\nfrom urllib import parse\n\n\"\"\"\n下载整个网站的 js、css、img、html 文件\n\"\"\"\n\n\ndef write_file(names, files, char):\n \"\"\" 写入到文件 \"\"\"\n name = names.split('/')[-1]\n path = ''\n if '.html' in name:\n if '?' in name:\n name = name.split('?')\n name2 = name[0].split('.')\n path = name2[0] + '_' + name[1] + '.' + name2[1]\n else:\n path = name\n elif '.js' in name:\n path = 'js\\\\' + name\n elif '.css' in name:\n path = 'css\\\\' + name\n else:\n path = 'images\\\\' + name\n if char == 'bytes':\n with open(path, 'wb') as f:\n f.write(files)\n else:\n with open(path, 'w', encoding=char) as f:\n f.write(files)\n\n\ndef down_html(url, h=True):\n \"\"\" 下载文件 \"\"\"\n html = requests.get(url).content\n if not h:\n return html, 'bytes'\n char = chardet.detect(html)\n html = html.decode(char['encoding']) # 转换编码\n return html, char['encoding']\n\n\ndef get_index_a(index_url, index=False):\n \"\"\" 获取主页面的所有a标签,js,css,图片 \"\"\"\n alls = []\n # is_downs = []\n if '.html' in index_url or index:\n html, char = down_html(index_url)\n else:\n html, char = down_html(index_url, h=False)\n url = index_url.split('/')[-1]\n write_file(url, html, char)\n return alls\n # 抽取 a 标签\n comp = re.compile(r'.*?)href=\".*/(?P.*?).html')\n html = bold.sub(r'href=\"\\g.html', html)\n\n # 把所有页面的 a 标签的 href 改变成能在本地访问的\n bold = re.compile(r'.*)href=\"(?P.*).html\\?tid=(?P.*)\"')\n html = bold.sub(r'href=\"\\g_tid=\\g.html\"', html)\n\n # 抽取 css 链接\n css = re.findall(r'.*?)href=\".*/(?P.*?).css')\n html = bold.sub(r'href=\"css/\\g.css', html)\n\n # 抽取 js 链接\n js = re.findall(r'\n \n \n \n \n \n
HomeInsert root
\"\"\"\n\ndef footer():\n return \"\"\n ","sub_path":"htmlHelper.py","file_name":"htmlHelper.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"643235811","text":"from django.conf import settings\nfrom django.db import models\n\n\nclass Lesson(models.Model):\n class Meta:\n permissions = ((\"view_diary\", \"Can view student diary\"),)\n\n school = models.ForeignKey(\n \"schools.School\", on_delete=models.CASCADE, related_name=\"lessons\"\n )\n subject = models.ForeignKey(\n \"schools.Schedule\", on_delete=models.SET_NULL, null=True, related_name=\"lessons\"\n )\n grade = models.ForeignKey(\n \"schools.Grade\", on_delete=models.SET_NULL, null=True, related_name=\"lessons\"\n )\n\n date = models.DateField(verbose_name=\"дата урока\")\n theme = models.TextField(verbose_name=\"тема\")\n homework = models.TextField(verbose_name=\"домашнее задание\")\n\n\nclass Mark(models.Model):\n class Meta:\n permissions = ((\"view_reports\", \"Can view student reports\"),)\n\n school = models.ForeignKey(\n \"schools.School\", on_delete=models.CASCADE, related_name=\"marks\"\n )\n lesson = models.ForeignKey(\n \"Lesson\", on_delete=models.SET_NULL, null=True, related_name=\"marks\"\n )\n student = models.ForeignKey(\n settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name=\"marks\"\n )\n\n ATTENDANCE_CHOICES = (\n (\"УП\", \"Уважительная причина\"),\n (\"Б\", \"Болеет\"),\n (\"ОП\", \"Опоздал\"),\n (\"ОТ\", \"Отсутствует\"),\n )\n\n mark = models.PositiveSmallIntegerField(verbose_name=\"оценка\")\n attendance = models.CharField(\n max_length=2, null=True, verbose_name=\"посещаемость\", choices=ATTENDANCE_CHOICES\n )\n","sub_path":"diaryspace/journal/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"31266558","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Aug 9 22:07:31 2020\n@author: Goutam Dadhich\n\"\"\"\n\n\"\"\"\nStatement :- you are given a integer n and your task is to return number \nof binary patterns that don't have 2 continue 1's in it.\n\n\"\"\"\n\ndef stringCount_rec(n, last_digit):\n pass\n\ndef stringCount_dp(n):\n T = [[0 for i in range(2)] for i in range(n+1)]\n T[0][0] = 0\n T[0][1] = 0\n \n T[1][0] = 2\n T[1][1] = 1\n \n for i in range(2, n+1):\n T[i][0] = T[i-1][0] + T[i-1][1]\n T[i][1] = T[i-1][0]\n \n #print(T) \n return T[n][0]\n\nif __name__ == '__main__':\n n = 3\n print('-'*10 + '*'*5 + '-'*10)\n print('Using recurssion :- ')\n print('Number of term is :- ', stringCount_rec(n, 0))\n print('-'*10 + '*'*5 + '-'*10)\n print('Using Dynamic programming :- ')\n print('Number of term is :- ', stringCount_dp(n))\n print('-'*10 + '*'*5 + '-'*10)\n ","sub_path":"DynamicProgramming/stringCountInBinary.py","file_name":"stringCountInBinary.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"127486056","text":"from __palette__ import Palette, show_palette, Action\r\n\r\nfrom pkg.package import LocalPackage\r\nfrom pkg.package.repo import get_online_packages\r\nfrom pkg.util import register_action\r\n\r\n\r\n@register_action('Packages: Install Package')\r\ndef install_plugins():\r\n actions = get_online_packages()\r\n actions = [(lambda _: Action(id=_.name, description=_.name, handler=lambda action: _.install()))(item)\r\n for item in actions]\r\n show_palette(Palette('install', \"Enter package name to install...\", actions))\r\n\r\n\r\n@register_action('Packages: Remove Package')\r\ndef remove_plugins():\r\n actions = LocalPackage.all()\r\n actions = [(lambda _: Action(id=_.name, description='%s %s' % (_.name, _.version),\r\n handler=lambda action: _.remove()))(item) for item in actions]\r\n\r\n show_palette(Palette('remove', \"Enter package name to remove...\", actions))\r\n","sub_path":"pkg/actions/packagemanager.py","file_name":"packagemanager.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"308116641","text":"from tweepy import API\nfrom tweepy import OAuthHandler\nfrom textblob_ar import TextBlob\n\nfrom projectIT499 import kays_twitter, regexarabic as ra, gulfstates as gs\n\nimport time\n\n\n# # # # TWITTER CLIENT # # # #\nclass TwitterClient():\n def __init__(self):\n self.auth = TwitterAuthenticator().authenticate_twitter_app()\n self.twitter_client = API(self.auth)\n\n def get_twitter_client_api(self):\n return self.twitter_client\n\n def get_saudi_arabia(self):\n result_SA = api.trends_place(23424938)\n file_SA = 'TRENDS_SA'\n df_SA = gs.get_data_to_frame(result_SA, file_SA)\n\n return df_SA\n\n def get_kuwait(self):\n result_KW = api.trends_place(23424870)\n file_KW = 'TRENDS_KW'\n df_KW = gs.get_data_to_frame(result_KW, file_KW)\n\n return df_KW\n\n def get_bahrain(self):\n result_BH = api.trends_place(23424753)\n file_BH = 'TRENDS_BH'\n df_BH = gs.get_data_to_frame(result_BH, file_BH)\n\n return df_BH\n\n def get_qatar(self):\n result_QA = api.trends_place(23424930)\n file_QA = 'TRENDS_QA'\n df_QA = gs.get_data_to_frame(result_QA, file_QA)\n\n return df_QA\n\n def get_united_arab_emirates(self):\n result_AE = api.trends_place(23424738)\n file_AE = 'TRENDS_AE'\n df_AE = gs.get_data_to_frame(result_AE, file_AE)\n\n return df_AE\n\n def get_oman(self):\n result_OM = api.trends_place(23424898)\n file_OM = 'TRENDS_OM'\n df_OM = gs.get_data_to_frame(result_OM, file_OM)\n\n return df_OM\n\n\n# # # # TWITTER AUTHENTICATER # # # #\nclass TwitterAuthenticator():\n\n def authenticate_twitter_app(self):\n auth = OAuthHandler(kays_twitter.consumer_key, kays_twitter.consumer_secret)\n auth.set_access_token(kays_twitter.access_key, kays_twitter.access_secret)\n return auth\n\n\nclass TweetAnalyzer():\n \"\"\"\n Functionality for analyzing and categorizing content from tweets.\n \"\"\"\n def clean_tweet(self, tweet):\n argword = ra.remove(tweet)\n argword = ra.harakat(argword)\n argword = ra.WordsFiltires(argword)\n return argword\n\n def analyze_sentiment(self, tweet):\n\n try:\n analysis = TextBlob(self.clean_tweet(tweet))\n time.sleep(0.2)\n if analysis.sentiment.polarity > 0:\n return 'positive'\n elif analysis.sentiment.polarity == 0:\n return 'natural'\n else:\n return 'negative'\n\n except BaseException as e:\n print(\"Error on_data %s\" % str(e))\n return True\n\n\nif __name__ == '__main__':\n twitter_client = TwitterClient()\n tweet_analyzer = TweetAnalyzer()\n api = twitter_client.get_twitter_client_api()\n\n while True:\n try:\n # extract tweets from top trend in Saudi Arabia\n df_SA = twitter_client.get_saudi_arabia()\n print('Start sa sentiment')\n df_SA['sentiment'] = df_SA['Tweets'].apply(lambda x: tweet_analyzer.analyze_sentiment(x))\n df_SA.to_csv('data_SA.csv', encoding='utf-16', sep='\\t', index=False)\n print('waiting for avoid rate limit')\n time.sleep(100) # Google Translate API also has a default limit 100,000 characters per 100 second.\n except BaseException as e:\n print(\"Error get_saudi_arabia %s\" % str(e))\n time.sleep(1)\n pass\n\n try:\n # extract tweets from top trend in Kuwait\n df_KW = twitter_client.get_kuwait()\n print(\"Start kw sentiment\")\n df_KW['sentiment'] = df_KW['Tweets'].apply(lambda x: tweet_analyzer.analyze_sentiment(x))\n df_KW.to_csv('data_KW.csv', encoding='utf-16', sep='\\t', index=False)\n print('waiting for avoid rate limit')\n time.sleep(100) # Google Translate API also has a default limit 100,000 characters per 100 second.\n except BaseException as e:\n print(\"Error get_kuwait %s\" % str(e))\n time.sleep(1)\n pass\n\n try:\n # extract tweets from top trend in Bahrain\n df_BH = twitter_client.get_bahrain()\n print('Start bh sentiment')\n df_BH['sentiment'] = df_BH['Tweets'].apply(lambda x: tweet_analyzer.analyze_sentiment(x))\n df_BH.to_csv('data_BH.csv', encoding='utf-16', sep='\\t', index=False)\n print('waiting for avoid rate limit')\n time.sleep(100) # Google Translate API also has a default limit 100,000 characters per 100 second.\n except BaseException as e:\n print(\"Error get_bahrain %s\" % str(e))\n time.sleep(1)\n pass\n\n try:\n # extract tweets from top trend in Qatar\n df_QA = twitter_client.get_qatar()\n print('Start qa sentiment')\n df_QA['sentiment'] = df_QA['Tweets'].apply(lambda x: tweet_analyzer.analyze_sentiment(x))\n df_QA.to_csv('data_QA.csv', encoding='utf-16', sep='\\t', index=False)\n print('waiting for avoid rate limit')\n time.sleep(100) # Google Translate API also has a default limit 100,000 characters per 100 second.\n except BaseException as e:\n print(\"Error get_qatar %s\" % str(e))\n time.sleep(1)\n pass\n\n try:\n # extract tweets from top trend in United Arab Emirates\n df_AE = twitter_client.get_united_arab_emirates()\n print('Start ae sentiment')\n df_AE['sentiment'] = df_AE['Tweets'].apply(lambda x: tweet_analyzer.analyze_sentiment(x))\n df_AE.to_csv('data_AE.csv', encoding='utf-16', sep='\\t', index=False)\n print('waiting for avoid rate limit')\n time.sleep(100) # Google Translate API also has a default limit 100,000 characters per 100 second.\n except BaseException as e:\n print(\"Error get_united_arab_emirates %s\" % str(e))\n time.sleep(1)\n pass\n\n try:\n # extract tweets from top trend in Oman\n df_OM = twitter_client.get_oman()\n print('Start om sentiment')\n df_OM['sentiment'] = df_OM['Tweets'].apply(lambda x: tweet_analyzer.analyze_sentiment(x))\n df_OM.to_csv('data_OM.csv', encoding='utf-16', sep='\\t', index=False)\n print('waiting for avoid rate limit')\n # Google Translate API also has a default limit 2 million characters per day.\n except BaseException as e:\n print(\"Error get_oman %s\" % str(e))\n time.sleep(1)\n pass\n\n print('Done for now')\n print('redo the process')\n time.sleep(100)\n\n # TODO learn about matplotlib\n","sub_path":"projectIT499/main_streamer.py","file_name":"main_streamer.py","file_ext":"py","file_size_in_byte":6718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"255968862","text":"#!/usr/bin/env python3\r\nimport os\r\nimport socket \r\nimport multiprocessing\r\nimport subprocess\r\nimport os\r\n\r\n\r\ndef pinger(job_q, results_q):\r\n \"\"\"\r\n Do Ping\r\n :param job_q:\r\n :param results_q:\r\n :return:\r\n \"\"\"\r\n DEVNULL = open(os.devnull, 'w')\r\n while True:\r\n\r\n ip = job_q.get()\r\n\r\n if ip is None:\r\n break\r\n\r\n try:\r\n subprocess.check_call(['ping', '-c1', ip],\r\n stdout=DEVNULL)\r\n results_q.put(ip)\r\n except:\r\n pass\r\n\r\n\r\ndef get_my_ip():\r\n \"\"\"\r\n Find my IP address\r\n :return:\r\n \"\"\"\r\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n s.connect((\"8.8.8.8\", 80))\r\n ip = s.getsockname()[0]\r\n s.close()\r\n return ip\r\n\r\n\r\ndef map_network(pool_size=255):\r\n \"\"\"\r\n Maps the network\r\n :param pool_size: amount of parallel ping processes\r\n :return: list of valid ip addresses\r\n \"\"\"\r\n\r\n ip_list = list()\r\n\r\n # get my IP and compose a base like 192.168.1.xxx\r\n ip_parts = get_my_ip().split('.')\r\n base_ip = ip_parts[0] + '.' + ip_parts[1] + '.' + ip_parts[2] + '.'\r\n\r\n # prepare the jobs queue\r\n jobs = multiprocessing.Queue()\r\n results = multiprocessing.Queue()\r\n\r\n pool = [multiprocessing.Process(target=pinger, args=(jobs, results)) for i in range(pool_size)]\r\n\r\n for p in pool:\r\n p.start()\r\n\r\n # cue hte ping processes\r\n for i in range(2, 255):\r\n jobs.put(base_ip + '{0}'.format(i))\r\n\r\n for p in pool:\r\n jobs.put(None)\r\n\r\n for p in pool:\r\n p.join()\r\n\r\n # collect he results\r\n while not results.empty():\r\n ip = results.get()\r\n ip_list.append(ip)\r\n\r\n return ip_list\r\n\r\n\r\ndef run():\r\n rows, columns = os.popen('stty size', 'r').read().split()\r\n rows = int(rows)\r\n str1 = \"Active Connections \"\r\n t1 = \"=\"*(len(str1)+2)\r\n t2 = t1.center(rows*2)\r\n str1 = str1.center(rows*2)\r\n print('Mapping...')\r\n listed = map_network()\r\n print(t2)\r\n print(\"\\33[1;92m\",str1,\"\\33[1;00m\")\r\n for lst in listed:\r\n lst1 = str(lst)\r\n lst1 =\"\\33[92m [*] \\33[00m\" + lst1\r\n rw = rows *2 + 6\r\n lst1 = lst1.center(rw)\r\n print(\" \" + lst1) \r\n print(t2)\r\n\r\n","sub_path":"tool/discover.py","file_name":"discover.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"475444657","text":"import tweepy\nimport sys, os, time\nimport csv\nimport json\nimport jsonpickle\n#import numpy as np\nimport pandas as pd\nimport kasg as ks\nfrom tkinter import *\nfrom tkinter import messagebox\n\n\naccess_token = '1151196229683929088-86wOu9aaxdYWgNvalp2pkNqucaXp5d'\naccess_token_secret ='NUfnsWNcgfbCPHotYT4LS6fXXfrRgHCQfALFsCi5NrjyH'\nconsumer_key = 'CN9YzSn3CqC9KT9bcByUCv8Kp'\nconsumer_secret = '0iiSCqbKO6IDCP5uG2qfreTZcuxICeLcIU1zwD6KwpOWItt02R'\n \ndef connect_to_twitter_OAuth():\n auth = tweepy.OAuthHandler(consumer_key, consumer_secret)\n auth.set_access_token(access_token, access_token_secret)\n \n api = tweepy.API(auth)\n return api\n \n# Create API object\napi = connect_to_twitter_OAuth()\n\n\n\ndef get_save_tweets(filepath, api, query, max_tweets=100,lang=\"in\"):\n\n tweetCount = 0\n\n #Open file and save tweets\n with open(filepath, 'w') as f:\n f.write(\"[\")\n # Send the query\n try:\n for tweet in tweepy.Cursor(api.search,q=query,tweet_mode='extended').items(max_tweets): \n\n #Convert to JSON format\n f.write(jsonpickle.encode(tweet._json, unpicklable=False) + ',\\n')\n tweetCount += 1\n\n #Display how many tweets we have collected\n \n print(\"Downloaded {0} tweets\".format(tweetCount))\n except:\n window =Tk()\n #window.eval('tk:: PlaceWindow %s center ' % window.wifo_toplevel())\n window.withdraw()\n messagebox.showerror(\"Error giler\", \"error nak buat macam mana\")\n window.deiconify()\n window.destroy()\n window.quit()\n\ndef cus(query):\n return query\n\nfuh=cus(\"query\");\n\nget_save_tweets('tweetshwe.json', api,fuh)\n\ndef buang_coma():\n f=open('tweetshwe.json',\"a+\")\n f.write(\"]\")\n f.close()\n with open('tweetshwe.json','rb+') as filehandle:\n filehandle.seek(-1,os.SEEK_END)\n filehandle.truncate()\n filehandle.seek(-3,os.SEEK_END)\n filehandle.truncate()\n f=open('tweetshwe.json',\"a+\")\n f.write(\"]\")\n f.close()\n\nbuang_coma()\n\npositiveList=[]\nnegativeList=[]\nks.getLexicons(positiveList, negativeList)\nham,kuym=ks.okay(positiveList, negativeList)\nks.read(ham,kuym)\n\n\n\n","sub_path":"sentistrength_id-master - Copy - Copy/ergh1.py","file_name":"ergh1.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"305779152","text":"import keras as K\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.datasets import fashion_mnist\nimport time\nfrom sklearn import metrics\nimport matplotlib.pyplot as plt\n\n\n(xTrain, yTrain), (xTest, yTest) = fashion_mnist.load_data()\n# to calculate time\nstartTime = time.time()\nnbClasses = 10\n# nb of neurons on the hidden layer\nnbNeuronsHL = 200\nxTrain = xTrain.reshape(60000, 784)\nxTest = xTest.reshape(10000, 784)\nxTrain = xTrain.astype('float32')\nxTest = xTest.astype('float32')\nxTrain /= 255\nxTest /= 255\nyTrain = K.utils.to_categorical(yTrain, nbClasses)\nyTest = K.utils.to_categorical(yTest, nbClasses)\n\nmodel = Sequential()\nmodel.add(Dense(nbNeuronsHL, input_dim=784, activation='sigmoid'))\nmodel.add(Dense(nbClasses, activation='softmax'))\n# model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])\nmodel.compile(optimizer='Adagrad', loss='categorical_crossentropy', metrics=['accuracy'])\n# model.compile(optimizer='Adadelta', loss='categorical_crossentropy', metrics=['accuracy'])\nmodel.fit(xTrain, yTrain, epochs=30, batch_size=128)\nscore = model.evaluate(xTest, yTest)\nscore_train = model.evaluate(xTrain, yTrain)\n\n# confusion matrix\ny_predicted = model.predict(xTest)\nconfusion_matrix = metrics.confusion_matrix(yTest.argmax(axis=1), y_predicted.argmax(axis=1))\n\n# validation\nhistory = model.fit(xTrain, yTrain, validation_split=0.25, epochs=30, batch_size=16, verbose=1)\n\n# visualization\n# Plot training & validation accuracy values\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\nprint(\"%s: %.2f%%\" % ('accuracy_test', score[1]*100))\nprint(\"%s: %.2f%%\" % ('test_loss', score[0]*100))\nprint(\"%s: %.2f%%\" % ('accuracy_train', score_train[1]*100))\nprint(\"%s: %.2f%%\" % ('train_loss', score_train[0]*100))\nprint('Test time: {0}'.format(time.time() - startTime))\nprint('Confusion_matrix')\nprint(confusion_matrix)\n","sub_path":"td3_p2.py","file_name":"td3_p2.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"574165363","text":"import pyshark\nimport os \n\n\ndef getSourceIP(packet):\n return packet.ip.addr\n\n# HTTP Protocal first/last messages \ndef isHTTP(packet):\n return packet.protocol == \"HTTP\"\n\n# Go thru packets sent during http to find out runtimes, num packets and files\n# sent by the server. Multiple HTTP requests can be handled\n# Sometimes there are more packets if duplicates came in \ndef processCapture(capture, file):\n cap = pyshark.FileCapture(capture, only_summaries=False)\n # 0 state means looking for first HTTP message\n # 1 state means going thru HTTP packets\n state = 0 \n lengths = [] # num bytes sent\n contents = [] # Data w/o headers sent in bytes\n times = [] # runtime from first HTTP message to last\n i = 0\n for packet in cap: # for each packet\n try:\n if state == 0 and packet.highest_layer == \"HTTP\": # Found first HTTP packet\n state = 1\n times.append(float(packet.sniff_timestamp))\n elif state == 0 and packet.highest_layer == \"DATA\": # Missed an HTTP requst packet\n print(\"pass \", i)\n continue\n elif state == 1 and packet.highest_layer == \"DATA\": # Found last HTTP packet\n try: \n state = 0\n times[i] = float(packet.sniff_timestamp) - times[i]\n lengths.append(int(packet.data.tcp_reassembled_length))\n contents.append(int(packet.http.content_length_header))\n print(i)\n i+=1\n except Exception:\n print(\"pop2 \", i)\n times.pop()\n if len(lengths) > len(contents):\n lengths.pop()\n elif len(lengths) < len(contents):\n contents.pop()\n elif state ==1 and packet.highest_layer == \"HTTP\": # Missed HTTP response packet\n print(\"pop \", i)\n times.pop()\n state = 1\n times.append(float(packet.sniff_timestamp))\n except Exception:\n pass\n \n # Save results \n print(\"Message #, total bytes sent, runtime,\\n\")\n resultsFile = \"wireshark_results/results_\" + file + \".csv\"\n print(resultsFile)\n with open(resultsFile, \"w\") as f:\n f.write(\"total bytes,data bytes,header bytes,runtime,\\n\")\n for j in range(i):\n headerLength = lengths[j] - contents[j]\n print(j, lengths[j], contents[j], headerLength, times[j])\n f.write(str(lengths[j]) + \",\" + str(contents[j]) + \n \",\" + str(headerLength) + \",\" + str(times[j]) + \",\\n\")\n\ndef main():\n ####### Set These ##############################\n capture = \"captures/100B.pcapng\" # relative capture file path\n file = \"100B\" # name of file used (used to name output file)\n ################################################\n processCapture(capture, file)\n\nmain()","sub_path":"code/HTTP/shark.py","file_name":"shark.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"56879814","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python\n\n'''\n第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。\n'''\n\nimport os\n\n\nfileName = 'filtered_words.txt'\n\nwith open(fileName,'r')as f:\n filter = [line.rstrip() for line in f]\n\nwhile True:\n text =input(\"please input:\")\n for x in filter:\n if x in text:\n Num=len(x)\n text=text.replace(x,'*'*Num)\n print(x+'is replaced!') \n print(text)\n","sub_path":"0012/0012.py","file_name":"0012.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"350035731","text":"#Napisz skrypt obliczajacy pierwiastki równania kwadratowego\r\n#wpostaci : y = ax2+bx+c. Wejsciem skryptu sawartosci: a; b; c\r\n\r\nimport math\r\n\r\na = int(input(\"Enter the coefficient a: \"))\r\nb = int(input(\"Enter the coefficient b: \"))\r\nc = int(input(\"Enter the coefficient c: \"))\r\n\r\nd = b**2-4*a*c # delta\r\n\r\nif d < 0:\r\n print(\"This equation has no real solution\")\r\nelif d == 0:\r\n x = (-b)/(2*a)\r\n print(\"This equation has one solution: \", x)\r\nelse:\r\n x1 = (-b+math.sqrt(d))/(2*a)\r\n x2 = (-b-math.sqrt(d))/(2*a)\r\n print(\"This equation has two solutions: \", x1, \" and\", x2)","sub_path":"quadratic_equation.py","file_name":"quadratic_equation.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"468244782","text":"import vk #vk API\nimport re #для работы с регулярными выражениями\nimport urllib.request #запросы \nimport time \t\t\t\t\t #время\nimport os\t\t\t\t\t #создание папок\n\nID = 221995390\n\ndef Find(pat,text):\n match = re.findall(pat,text)\n if match:return True\n else: return False\n\ndef main():\n x = []\n result = []\n lose = 0\n start_time= time.time()\n\n #создвние vk сессии\n session = vk.Session()\t\n api = vk.API(session)\n\n #создает массив со всеми картинкаи\n photo = api.photos.get(owner_id = ID , album_id = 'saved' , photo_sizes=0) \n for i in photo:\n x.append(i.get('src_big'))\n\n\n #Поиск картинки через Яндекс(Google API больше нет)\n for d in range(0,len(x)):\n url = 'https://yandex.ru/images/search?img_url='+x[d]+'&rpt=imageview'\n req = urllib.request.Request(url)\n response = urllib.request.urlopen(req)\n html = response.read().decode('utf8')\n f = Find(r'Сайты, где встречается картинка',html)\n if f == True:\n lose += 1\n else:\n result.append(x[d])\n print('Unique photo:'+str(d))\n \n print('\\nPhotos:'+str(len(x)-lose))\n print('All:'+str(len(x)))\n print('Time:'+str(time.time()-start_time)+'\\n')\n a = input('get list of photos?(y/n):')\n if a == 'y':\n print()\n for l in range(len(result)):\n print(result[l])\n \nif __name__ == '__main__':\n\tmain()\n","sub_path":"vk_api_test.py","file_name":"vk_api_test.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"135035826","text":"from tkinter import *\r\n\r\nclass End:\r\n def __init__(self,x1, y1, x2, y2, canvas, color, player):\r\n self.canvas = canvas\r\n self.color = color\r\n self.player = player\r\n self.id = canvas.create_rectangle(x1, y1, x2, y2, fill=self.color)\r\n self.canvas.move(self.id, 200, 300)\r\n self.x = 0\r\n self.y = 0\r\n self.canvas_height = canvas.winfo_height()\r\n self.canvas_width = canvas.winfo_width()\r\n def draw (self):\r\n if self.check() == True:\r\n return True\r\n def check (self):\r\n door_coords = self.canvas.coords(self.id)\r\n player_coords = self.player.canvas.coords(self.player.id)\r\n if player_coords[2] >= door_coords[0] and player_coords[0] <= door_coords[2]:\r\n if player_coords[3] >= door_coords[1] and player_coords[3] <= door_coords[3]:\r\n return True\r\n return False\r\n","sub_path":"Platformer/End.py","file_name":"End.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"620707336","text":"# Handles http responses and parses for \n# requested data.\n# This parser is currently only able to handle responses \n# from \"https://10minutemail.net/\".\n# \nimport re\nfrom bs4 import BeautifulSoup as bso\n\nclass ResponseParser():\n\n # Returns the data needed by a FakeMailAccount Object\n def getFakeAccData(self, response): \n beautifulContent = bso(response.content, \"html.parser\")\n \n mailAdress = self.getMailAdress(beautifulContent)\n cookies = self.getCookies(response)\n\n return mailAdress, cookies\n \n\n # Get the e-mail adress of the fake account\n def getMailAdress(self, content):\n inputElement = content.find(\"input\")\n mailAdress = inputElement.get(\"value\")\n\n return mailAdress\n\n\n # Return all cookies as a dictionary: [\"key\":\"value\",...]\n def getCookies(self, response):\n sessionCookies = response.cookies.get_dict()\n \n return sessionCookies\n\n\n # Return a list of the link endings for the mails \n def getInboxLinks(self, response):\n beautifulContent = bso(response.content, \"html.parser\")\n inboxElements = beautifulContent.find(\"table\")\n trimmedLinks = []\n \n for mails in inboxElements.contents:\n link = mails.attrs.get('onclick')\n if (link):\n extractedLink = re.findall(\"readmail.html.*'\", link)\n trimmedLinks.append(extractedLink[0].strip(\"'\"))\n return trimmedLinks\n\n\n# Get the validation code for twitter\n def getTwitterCode(self, response):\n beautifulContent = bso(response.content, \"html.parser\")\n codes = beautifulContent.findAll(\"td\", attrs = {\"class\":\"h1 black\",\"dir\":\"ltr\"})\n for code in codes:\n code = code.getText()\n if code.isnumeric():\n return code\n else:\n return -1\n \n \n","sub_path":"Parser/ResponseParser.py","file_name":"ResponseParser.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"44334279","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 18 09:24:55 2018\n@author: doanthanh\n\"\"\"\n\nfrom Tkinter import *\nimport Tkinter as tk\nimport ttk\nfrom PIL import ImageTk, Image\n\n\nclass Application:\n def __init__(self, master):\n \n #create regions for the main frame\n leftFrame = Frame(master, width=1000)\n leftFrame.grid(sticky=W, row=0, column=0, rowspan=500, columnspan=300)\n rightFrame = Frame(master)\n rightFrame.grid(sticky=E, row=0, column=301, rowspan=500)\n \n ToolBar = Frame(leftFrame, bg=\"grey\", width=1000, height=900)\n ToolBar.grid(sticky=N, columnspan=300)\n \n ImageHolder = Frame(leftFrame, width=900, height=800)\n ImageHolder.grid(sticky=S)\n \n PrevNext = Frame(leftFrame)\n PrevNext.grid(sticky=S)\n \n TagLabels = ttk.Notebook(rightFrame)\n TagLabels.grid(sticky=N)\n \n #Toolbar, #insert your functions in command to for events\n self.openFile = Button(ToolBar, text=\"Open File\", height=2, width=7, command=self.doNothing) \n self.openFile.grid(sticky=W, row=1, rowspan=2, column=0, columnspan=3)\n \n \n self.saveImgs = Button(ToolBar, text=\"Save\", height=2, width=7, command=self.doNothing)\n self.saveImgs.grid(sticky=E, row=1, rowspan=2, column=7, columnspan=3)\n \n #ImgHolders\n \n #tempPhoto = PhotoImage(file=\"/Users/doanthanh/CodingProjects/LKYCIC Image Labeling/Dog1.png\")\n #showPhoto = Label(ImageHolder, image=tempPhoto)\n #showPhoto.grid()\n imgHolder = Label(ImageHolder, text=\"View images here\")\n imgHolder.grid(padx=100, pady=100)\n \n #PrevNext \n prev = Button(PrevNext, text=\"<\", width=4)\n prev.grid(sticky=W, padx=20, row = 497, rowspan=2, column=10, columnspan=2)\n nxt= Button(PrevNext, text=\">\", width=4)\n nxt.grid(sticky=E, row = 497, rowspan=2, column=18, columnspan=2)\n \n #TagLabels\n generalTab = ttk.Frame(TagLabels)\n envTab = ttk.Frame(TagLabels)\n activityTab = ttk.Frame(TagLabels)\n thingTab = ttk.Frame(TagLabels)\n addTab = ttk.Frame(TagLabels)\n \n TagLabels.add(generalTab, text=\"General\")\n TagLabels.add(envTab, text=\"Location\")\n TagLabels.add(activityTab, text=\"Activity\")\n TagLabels.add(thingTab, text=\"Things\")\n TagLabels.add(addTab, text=\"+\")\n \n #General Tab\n person = Checkbutton(generalTab, text=\"Person\")\n person.grid(sticky=W)\n useless = Checkbutton(generalTab, text=\"Not useful\")\n useless.grid(sticky=W)\n \n #Locations tab\n home = Checkbutton(envTab, text=\"House\")\n park = Checkbutton(envTab, text=\"Park\")\n market = Checkbutton(envTab, text=\"Supermarket/Wet market\")\n foodstore = Checkbutton(envTab, text=\"Food center/Coffeeshop\")\n hospital = Checkbutton(envTab, text=\"Hospital\")\n common = Checkbutton(envTab, text=\"Playground/Void Deck\")\n religion = Checkbutton(envTab, text=\"Religious Venue\")\n road = Checkbutton(envTab, text=\"On Road/Street\")\n busstop = Checkbutton(envTab, text=\"Bus Stop\")\n mrtstation = Checkbutton(envTab, text=\"MRT station\")\n \n home.grid(sticky=W)\n park.grid(sticky=W)\n market.grid(sticky=W)\n foodstore.grid(sticky=W)\n hospital.grid(sticky=W)\n common.grid(sticky=W)\n religion.grid(sticky=W)\n road.grid(sticky=W)\n busstop.grid(sticky=W)\n mrtstation.grid(sticky=W)\n \n #activity\n \n walk = Checkbutton(activityTab, text=\"Walking\")\n cycle = Checkbutton(activityTab, text=\"Cycling\")\n sit = Checkbutton(activityTab, text=\"Sitting\")\n talk = Checkbutton(activityTab, text=\"Chatting\")\n eat = Checkbutton(activityTab, text=\"Eating\")\n shop = Checkbutton(activityTab, text=\"Shopping\")\n rest = Checkbutton(activityTab, text=\"Resting\")\n others = Checkbutton(activityTab, text=\"Others\")\n \n walk.grid(sticky=W)\n cycle.grid(sticky=W)\n sit.grid(sticky=W)\n talk.grid(sticky=W)\n eat.grid(sticky=W)\n shop.grid(sticky=W)\n rest.grid(sticky=W)\n others.grid(sticky=W)\n \n def doNothing(self):\n print(\"Huat Ah!\")\n \n \n\nroot = tk.Tk()\napp = Application(root)\nroot.title(\"Image Labeling Software\")\nroot.mainloop()","sub_path":"GUI01.py","file_name":"GUI01.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"444365151","text":"#!/usr/bin/env python3\n# encoding: utf-8\n\nimport argparse\nimport datetime\nimport itertools\nimport os\nimport shutil\nimport subprocess\nimport time\n\nimport pandas as pd\nfrom rmgpy.molecule.molecule import Molecule\nfrom rmgpy.chemkin import load_species_dictionary\n\nfrom easy_rmg_model.common import regularize_path\nfrom easy_rmg_model.settings import (IDT_SPECIES,\n PHIS_POST_PROCESS,\n POOL_SIZE_POST_PROCESS,\n PS_POST_PROCESS,\n RMG_PATH,\n SENS_SPECIES,\n SIM_TIME_FINAL_POST_PROCESS,\n SIM_TIME_OUT_POST_PROCESS,\n TS_POST_PROCESS)\nfrom easy_rmg_model.template_writer.input import RMGSimulateInput\nfrom easy_rmg_model.template_writer.submit import SLURMSubmitScript\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument('model_path', type=str, nargs=1,\n help='The folder path to RMG model')\n parser.add_argument('fuel', metavar='FUEL', nargs=1,\n help='The label or the smiles of the fuel')\n parser.add_argument('-T', '--temperature', nargs='+',\n help='Temperatures [K]')\n parser.add_argument('-P', '--pressure', nargs='+', help='Pressures [atm]')\n parser.add_argument('-p', '--phi', nargs='+',\n help='Fue-to-air equivalence ratio')\n parser.add_argument('-f', '--final_time', nargs=1,\n help='The t_final of the simulation')\n parser.add_argument('-s', '--simulate_path', nargs=1,\n help='Path to save simulation results')\n parser.add_argument('-S', '--sensitivity_path', nargs=1,\n help='Path to save sensitivity results')\n parser.add_argument('-F', '--flux_diagram_path', nargs=1,\n help='Path to save flux diagram results')\n parser.add_argument('--pool_size', nargs='?', type=int,\n help='The size of the job pool')\n\n args = parser.parse_args()\n\n model_path = regularize_path(args.model_path[0])\n fuel = args.fuel[0]\n Ts = [float(T) for T in args.temperature] if args.temperature else TS_POST_PROCESS\n Ps = [float(P) for P in args.pressure] if args.pressure else PS_POST_PROCESS\n phis = [float(phi) for phi in args.phi] if args.phi else PHIS_POST_PROCESS\n tf = float(args.final_time[0]) if args.final_time else SIM_TIME_FINAL_POST_PROCESS\n outputs = {}\n for job_type in ['simulate', 'sensitivity', 'flux_diagram']:\n job_path = getattr(args, f'{job_type}_path')\n outputs[job_type] = regularize_path(job_path[0]) if job_path else \\\n os.path.join(os.path.dirname(model_path), job_type)\n pool_size = POOL_SIZE_POST_PROCESS if not args.pool_size else args.pool_size[0]\n\n return model_path, fuel, Ts, Ps, phis, tf, outputs, pool_size\n\n\ndef find_molecule(molecule, spc_dict):\n # Find the molecule according to the smiles or the label information\n if molecule in spc_dict:\n return {'label': molecule, 'smiles': spc_dict[molecule].molecule[0].to_smiles()}\n try:\n mol = Molecule().from_smiles(molecule)\n except:\n raise ValueError(\n f'Invalid molecule input {molecule} should be a SMILES string or the species label')\n for label, spc in spc_dict.items():\n if spc.is_isomorphic(mol):\n return {'label': label, 'smiles': spc.molecule[0].to_smiles()}\n\n\ndef run_simulation(input_path, chemkin_path, spc_dict_path, work_dir='.'):\n py_file = f\"{RMG_PATH}/scripts/simulate.py\"\n cmd = f'python \"{py_file}\" ' \\\n f'\"{input_path}\" \"{chemkin_path}\" \"{spc_dict_path}\";'\n try:\n output = subprocess.check_output(cmd,\n stderr=subprocess.STDOUT,\n cwd=work_dir,\n shell=True,\n timeout=SIM_TIME_OUT_POST_PROCESS)\n return True\n except subprocess.CalledProcessError as e:\n print(f'Simulation failed. Got ({e.output})')\n return\n\n\ndef generate_flux_diagram(input_path, chemkin_path, spc_dict_path, work_dir='.'):\n py_file = f\"{RMG_PATH}/scripts/generateFluxDiagram.py\"\n # generate flux diagram\n cmd = f'python \"{py_file}\" ' \\\n f'\"{input_path}\" \"{chemkin_path}\" \"{spc_dict_path}\";'\n try:\n output = subprocess.check_output(cmd,\n stderr=subprocess.STDOUT,\n cwd=work_dir,\n shell=True,\n timeout=SIM_TIME_OUT_POST_PROCESS)\n except subprocess.CalledProcessError as e:\n print(f'Flux diagram failed. Got ({e.output})')\n return\n else:\n # remove the species folder\n shutil.rmtree(os.path.join(work_dir, 'species'))\n return True\n\n\ndef run_sensitivity(model_path, sens_path, Ts, Ps, phis, pool_size):\n cmd = ['python', os.path.join(os.path.dirname(__file__), 'runSens.py')]\n cmd += [model_path, sens_path, ]\n cmd += ['-T'] + [str(T) for T in Ts]\n cmd += ['-P'] + [str(P) for P in Ps]\n cmd += ['-p'] + [str(phi) for phi in phis]\n cmd += ['--pool_size', str(pool_size)]\n try:\n output = subprocess.check_output(cmd,\n stderr=subprocess.STDOUT,\n cwd=model_path)\n except subprocess.CalledProcessError as e:\n print(f'Sensitivity job terminated. Got ({e.output})')\n return\n else:\n print('Finished Sensitivity.')\n\n\ndef generate_rmg_input_file(spec: dict, save_path: str):\n \"\"\"\n A helper function to save rmg input file.\n\n Args:\n spec (dict): The specifications used to generate the rmg input file.\n save_path (str): The path to save the input file.\n \"\"\"\n spec.update({'save_path': save_path})\n rmg_sim_input = RMGSimulateInput(spec)\n rmg_sim_input.save()\n\n\ndef main():\n\n model_path, fuel, Ts, Ps, phis, tf, outputs, pool_size = parse_arguments()\n\n chemkin_path = os.path.join(model_path, 'chem_annotated.inp')\n spc_dict_path = os.path.join(model_path, 'species_dictionary.txt')\n\n spc_dict = load_species_dictionary(spc_dict_path)\n spc_num = len(spc_dict)\n\n fuel = find_molecule(fuel, spc_dict)\n idt_species = find_molecule(IDT_SPECIES[\"smiles\"], spc_dict)\n\n for T, P, phi in itertools.product(Ts, Ps, phis):\n\n print(f'Running simulation T: {T}, P: {P}, phi:{phi}')\n\n folder_name = f'{T}_{P}_{phi}'\n spec = {\n 'species_dictionary': spc_dict_path,\n 'fuel': fuel,\n 'temp': T,\n 'pressure': P,\n 'phi': phi,\n 'tf': tf,\n }\n\n # Create folder and input file\n work_dir = os.path.join(outputs['simulate'], folder_name,)\n os.makedirs(work_dir, exist_ok=True)\n input_path = os.path.join(work_dir, 'input.py')\n generate_rmg_input_file(spec, save_path=input_path)\n\n done = run_simulation(input_path, chemkin_path,\n spc_dict_path, work_dir)\n\n # Get ignition delay\n if done:\n try:\n df = pd.read_csv(os.path.join(work_dir, 'solver',\n f'simulation_1_{spc_num}.csv'))\n df = df.set_index('Time (s)')\n idt = df[idt_species[\"label\"]].idxmax()\n except:\n print(f'Cannot get ignition delay time. Use default time ({tf} seconds).')\n idt = tf\n else:\n idt = tf\n\n # Generate flux diagram\n print(f'Generating flux diagram T: {T}, P: {P}, phi: {phi}')\n work_dir = os.path.join(outputs['flux_diagram'], folder_name,)\n os.makedirs(work_dir, exist_ok=True)\n input_path = os.path.join(work_dir, 'input.py')\n spec.update({'tf': min(idt * 10, tf)})\n generate_rmg_input_file(spec, save_path=input_path)\n\n generate_flux_diagram(input_path, chemkin_path,\n spc_dict_path, work_dir)\n\n # Create sens input\n work_dir = os.path.join(outputs['sensitivity'], folder_name,)\n os.makedirs(work_dir, exist_ok=True)\n input_path = os.path.join(work_dir, 'input.py')\n spec.update({'sens_spc': SENS_SPECIES,\n 'tf': idt})\n generate_rmg_input_file(spec, save_path=input_path)\n\n # Sensitivity usually takes longer, use queue software\n run_sensitivity(\n model_path, outputs['sensitivity'], Ts, Ps, phis, pool_size)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"script/runSensAndFlux.py","file_name":"runSensAndFlux.py","file_ext":"py","file_size_in_byte":8838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"588475228","text":"\"\"\"\n normalize.py\n ~~~~~~\n\n Utility methods for normalizing Bazaarvoice API responses.\n\"\"\"\n\nimport logging\n\nimport bvapi\nfrom dictutil import O\n\nlog = logging.getLogger('bvapi')\n\nclass Normalizer(object):\n\n TYPE_METADATA = {\n 'review': O({'section': 'Reviews'}),\n 'question': O({'section': 'Questions'}),\n 'answer': O({'section': 'Answers'}),\n 'story': O({'section': 'Stories'}),\n 'author': O({'section': 'Authors'}),\n 'product': O({'section': 'Products'}),\n 'category': O({'section': 'Categories'}),\n }\n\n def __init__(self, bvapi, data_type, response, allowed_statuses=None):\n self._bvapi = bvapi\n self._data_type = data_type\n self._response = response\n self._results = response.get('Results', [])\n self._includes = response.get('Includes', {})\n self._allowed_statuses = allowed_statuses\n\n def normalize(self):\n try:\n if not self._response.HasErrors:\n md = self.TYPE_METADATA[self._data_type]\n # add the Results section to the Includes dictionary so we can resolve back references (eg. Answer.QuestionId -> Question)\n self._includes[md.section] = dict([(o.Id, o) for o in self._results])\n # normalize all the objects in the Results section. this will, in turn, normalize all referenced objects in the Includes section\n normalize_fn = getattr(self, self._data_type)\n self._response.Results = self._filter(map(normalize_fn, self._results))\n return self._response\n except (TypeError, KeyError) as e:\n # note: this could get quite noisy if it happens frequently...\n log.error('API returned bad data: %s', self._response, exc_info=True)\n return O({ 'HasErrors': True, 'TotalResults': 0, 'Limit': 0, 'Offset': 0, 'Results': [] })\n\n def question(self, question):\n if self._visit(question):\n self._normalize_timestamps(question)\n self._normalize_subjectreference(question)\n self._normalize_authorreference(question)\n if question.AnswerIds:\n question.Answers = self._filter([self.answer(self._lookup('Answers', id)) for id in question.AnswerIds])\n return question\n\n def answer(self, answer):\n if self._visit(answer):\n self._normalize_timestamps(answer)\n self._normalize_subjectreference(answer)\n self._normalize_authorreference(answer)\n return answer\n\n def review(self, review):\n if self._visit(review):\n self._normalize_timestamps(review)\n self._normalize_subjectreference(review)\n self._normalize_authorreference(review)\n return review\n\n def author(self, author):\n if self._visit(author):\n self._normalize_timestamps(author)\n return author\n\n def product(self, product):\n if self._visit(product):\n pass\n return product\n\n def category(self, category):\n if self._visit(category):\n pass\n return category\n\n def _normalize_authorreference(self, object):\n if object.AuthorId:\n object.Author = self.author(self._lookup('Authors', object.AuthorId))\n\n def _normalize_subjectreference(self, object):\n if object.ProductId:\n object.Product = self.product(self._lookup('Products', object.ProductId))\n if object.CategoryId:\n object.Category = self.category(self._lookup('Categories', object.CategoryId))\n if object.QuestionId:\n object.Question = self.question(self._lookup('Questions', object.QuestionId))\n\n def _normalize_timestamps(self, object):\n for key in ('SubmissionTime', 'LastModeratedTime', 'LastModificationTime'):\n if key in object and object[key]:\n object[key] = bvapi.parse_timestamp(object[key])\n\n def _lookup(self, section, id):\n if section not in self._includes:\n self._includes[section] = O({})\n if id not in self._includes[section]:\n self._includes[section][id] = O({ 'Id': id })\n return self._includes[section][id]\n\n def _filter(self, items):\n if self._allowed_statuses is not None:\n return [item for item in items if item.ModerationStatus is None or item.ModerationStatus in self._allowed_statuses]\n return items\n\n def _visit(self, obj):\n if obj._normalized:\n return False # already visited\n obj._normalized = True\n return True # first time visit\n","sub_path":"sample/python-tornado/bvapi/normalize.py","file_name":"normalize.py","file_ext":"py","file_size_in_byte":4614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"587510136","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 2 00:58:47 2018\nLast modified on 20181007 - added comments\n\n@author: Jing Ma\n\"\"\"\n\nimport pandas as pd\nfrom datetime import timedelta\n\nfrom scipy.stats import beta\n#y = list(beta.pdf([0.1, 0.2, 0.3, 0.4, 0.5, 0.8, 0.9], 3, 8))\n\nfrom MyHelperLib import ExecQuery\nfrom MyStatsLib import GetPdfMode\nfrom config import RunGUI_config\ndata_config = RunGUI_config['data']\nplot_config = RunGUI_config['plot']\n#symbol = 'JNJ'\n\ndef main():\n pass\n\n\n#########################################\n### The Query Functions\n#########################################\ndef QueryGUIData(data_config, symbol, data_type, normalize=False):\n \n if data_type == 'px_series':\n px_series_table = data_config['px_series_table']\n px_series_query = \"\"\"select date as date_raw, adj_close as price, volume as volume_raw \n from \"\"\"+px_series_table+\"\"\" \n where symbol = '\"\"\"+symbol+\"\"\"' \n order by symbol, date;\"\"\"\n print(px_series_query)\n px_series_df = ExecQuery(data_config['database'], px_series_query, True, True)\n \n px_series_df['date'] = pd.to_datetime(px_series_df['date_raw'], format='%Y-%m-%d') + timedelta(hours=16)\n \n volume_unit = 1e6 if px_series_df['volume_raw'].max()>1e6 else 1e3\n px_series_df['volume'] = px_series_df['volume_raw']/volume_unit\n volume_unit_str = 'M' if volume_unit==1e6 else 'K'\n\n return {'df':px_series_df[['date','price','volume']], 'volume_unit_str':volume_unit_str}\n \n elif data_type in ['px_dist_crude','px_dist_manual']:\n px_dist_table = data_config['px_dist_table']\n \n model = data_type.split('_')[-1]\n max_dt_subquery = \"\"\"(\n select symbol, price, max(asof_datetime) as max_dt\n from \"\"\"+px_dist_table+\"\"\" \n where symbol='\"\"\"+symbol+\"\"\"' \n and model='\"\"\" + model + \"\"\"'\n and not deprecated\n group by 1,2\n )\"\"\"\n px_dist_query = \"\"\" select p.price, p.prob\n from \"\"\"+px_dist_table+\"\"\" p\n join \"\"\"+max_dt_subquery+\"\"\" s \n on p.price=s.price and p.asof_datetime=s.max_dt #and p.symbol=s.symbol\n where p.symbol='\"\"\"+symbol+\"\"\"' \n and p.model='\"\"\" + model + \"\"\"'\n and not deprecated\n order by price\n ;\"\"\"\n print(px_dist_query)\n px_dist_df = ExecQuery(data_config['database'], px_dist_query, True, True)\n if normalize:\n px_dist_df['prob'] = px_dist_df['prob']/px_dist_df['prob'].sum()\n return px_dist_df\n \n elif data_type in ['px_beta_dist_autol', 'px_beta_dist_autom', 'px_beta_dist_autor', 'px_beta_dist_cust']:\n #symbol = 'IBM'\n #data_type = 'px_beta_dist_autol'\n px_beta_dist_table = data_config['px_beta_dist_table']\n \n model = data_type.split('_')[-1]\n max_dt_subquery = \"\"\"(\n select symbol, max(asof_datetime) as max_dt\n from \"\"\"+px_beta_dist_table+\"\"\" \n where symbol='\"\"\"+symbol+\"\"\"' \n and model='\"\"\" + model + \"\"\"'\n and not deprecated\n group by 1\n )\"\"\"\n px_dist_query = \"\"\" select p.price_mode, p.price_band, p.alpha, p.beta\n from \"\"\"+px_beta_dist_table+\"\"\" p\n join \"\"\"+max_dt_subquery+\"\"\" s \n on p.asof_datetime=s.max_dt #and p.symbol=s.symbol\n where p.symbol='\"\"\"+symbol+\"\"\"' \n and p.model='\"\"\" + model + \"\"\"'\n and not deprecated\n ;\"\"\"\n print(px_dist_query)\n \n px_dist_base_df = ExecQuery(data_config['database'], px_dist_query, True, True)\n \n if len(px_dist_base_df)==0:\n model = 'autom'\n max_dt_subquery = \"\"\"(\n select symbol, max(asof_datetime) as max_dt\n from \"\"\"+px_beta_dist_table+\"\"\" \n where symbol='\"\"\"+symbol+\"\"\"' \n and model='\"\"\" + model + \"\"\"'\n and not deprecated\n group by 1\n )\"\"\"\n px_dist_query = \"\"\" select p.price_mode, p.price_band, p.alpha, p.beta\n from \"\"\"+px_beta_dist_table+\"\"\" p\n join \"\"\"+max_dt_subquery+\"\"\" s \n on p.asof_datetime=s.max_dt #and p.symbol=s.symbol\n where p.symbol='\"\"\"+symbol+\"\"\"' \n and p.model='\"\"\" + model + \"\"\"'\n and not deprecated\n ;\"\"\"\n px_dist_base_df = ExecQuery(data_config['database'], px_dist_query, True, True)\n \n px_mode = px_dist_base_df['price_mode'][0]\n px_band = round(px_dist_base_df['price_band'][0],2)\n a = px_dist_base_df['alpha'][0]\n b = px_dist_base_df['beta'][0]\n \n dist_mode = GetPdfMode('beta', {'alpha':a,'beta':b})\n px_lower = round(px_mode - px_band*dist_mode,2)\n px_list = [i/100.0 for i in range(int(px_lower*100), int(px_lower*100+px_band*100+1))]\n px_dist_df = pd.DataFrame.from_items([('price', px_list)])\n #px_dist_df['price_norm'] = (px_dist_df['price']-px_lower)/px_band\n px_dist_df['prob'] = beta.pdf((px_dist_df['price']-px_lower)/px_band, a, b) #pdf\n #if normalize: px_dist_df['prob'] = px_dist_df['prob']/px_dist_df['prob'].sum()\n return px_dist_df\n \n\ndef InsertPXDistManual(data_config, symbol, raw_str):\n \"\"\"\n the input should look like \"123.12 0.1;123.23 0.15\" \n - if duplicated, will take the latter one\n - if not able to convert to float, will skip\n \"\"\"\n #raw_str = \"123.12 0.1;123.23 0.15;123.12 0.3;123df 0.2\" ###DEBUG\n #symbol = 'JNJ' ###DEBUG\n \n # 1. process the string\n # 1.1 if the string is \"clear all\", mark everything for this symbol to be deprecated\n if raw_str == 'clear all':\n deprecate_query = 'update '+data_config['px_dist_table']+\" set deprecated=True where symbol = '\"+symbol+\"' and model = 'manual'; commit;\"\n print(deprecate_query)\n ExecQuery(data_config['database'], deprecate_query, False, False)\n \n # 1.2 subtract numbers, and proceed if there is any ligit numbers\n px_dist_dict = {x.split(' ')[0]:x.split(' ')[1] for x in raw_str.split(';') if CanToFloat(x.split(' ')[0]) and CanToFloat(x.split(' ')[1])}\n if len(px_dist_dict)==0: return None\n \n # 2. construct the query\n query_list = []\n query_prepend = ', '.join(['current_timestamp() as asof_datetime',\"'manual' as model\", \"'\"+symbol+\"' as symbol\"])\n \n for i in px_dist_dict.keys():\n query_list.append('(select ' +str(i)+' as price, '+str(px_dist_dict[i])+' as prob)')\n \n select_query = 'select '+query_prepend+', temp.*, false as deprecated from (\\n'+ '\\nUNION ALL\\n'.join(query_list) +'\\n) as temp'\n insert_query = 'insert into '+data_config['px_dist_table']+' \\n'+ select_query + '; commit;'\n \n print(insert_query)\n ExecQuery(data_config['database'], insert_query, False, False)\n\n\ndef InsertPxDistCrude(data_config, symbol):\n deprecate_query = 'update '+data_config['px_dist_table']+\" set deprecated=True where symbol = '\"+symbol+\"' and model = 'crude'; commit;\"\n print(deprecate_query)\n ExecQuery(data_config['database'], deprecate_query, False, False)\n \n query_list = []\n px_dist_dict = {'0':'0.1',\n '0.1':'0.1','-0.1':'0.1',\n '0.2':'0.08','-0.2':'0.08',\n '0.3':'0.06','-0.3':'0.06',\n '0.5':'0.05','-0.5':'0.05',\n '1':'0.04','-1':'0.04',\n '2':'0.03','-2':'0.03'\n }\n for i in px_dist_dict.keys():\n query_list.append('(select avg(adj_close)+('+i+'*stddev(adj_close)) as price, '+px_dist_dict[i]+' as prob from '+data_config['px_series_table']+\" where symbol='\"+symbol+\"')\")\n \n \n insert_query = \"\"\"insert into \"\"\" +data_config['px_dist_table']+ \"\"\"\n select current_timestamp() as asof_datetime, 'crude' as model, '\"\"\"+symbol+\"\"\"' as symbol, temp.*, false as deprecated\n from\n (\\n\"\"\" + '\\nUNION ALL\\n'.join(query_list) + \"\"\"\\n) as temp\n ; commit;\n \"\"\"\n print(insert_query)\n ExecQuery(data_config['database'], insert_query, False, False) \n\n\ndef InsertPxBetaDist(data_config, symbol, model, para_dict):\n # conviction should be a string that can be translated into float\n if model in ['cust']:\n insert_query = \"\"\"insert into \"\"\" +data_config['px_beta_dist_table']+ \"\"\"\n select current_timestamp() as asof_datetime\n , '\"\"\"+model+\"\"\"' as model\n , '\"\"\"+symbol+\"\"\"' as symbol\n , \"\"\"+para_dict['price_mode']+\"\"\" as price_mode\n , \"\"\"+para_dict['price_band']+\"\"\" as price_band\n , \"\"\"+para_dict['price_shape']+\"\"\" as price_shape\n , \"\"\"+para_dict['price_skew']+\"\"\" as price_skew\n , least(2*exp(4*\"\"\"+para_dict['price_shape']+\"\"\")-1\n , greatest(1,exp(4*\"\"\"+para_dict['price_shape']+\"\"\")*(1+\"\"\"+para_dict['price_skew']+\"\"\"))) \n as alpha\n , least(2*exp(4*\"\"\"+para_dict['price_shape']+\"\"\")-1\n , greatest(1,exp(4*\"\"\"+para_dict['price_shape']+\"\"\")*(1-\"\"\"+para_dict['price_skew']+\"\"\"))) \n as beta\n , false as deprecated; commit;\n \"\"\"\n elif model in ['autol','autom','autor','all']:\n insert_query = \"\"\"insert into \"\"\" +data_config['px_beta_dist_table']+ \"\"\"\n select current_timestamp() as asof_datetime, temp.*, false\n from\n (\n \t(\n \t\tselect 'autom' as model, symbol, avg(adj_close) as price_mode, 5*stddev(adj_close) as price_band\n \t\t\t, 0.5 as price_shape\n , 0 as price_skew\n , least(2*exp(4*0.5)-1, greatest(1,exp(4*0.5)*(1+0))) as alpha\n , least(2*exp(4*0.5)-1, greatest(1,exp(4*0.5)*(1-0))) as beta\n from us.equity_daily_recent_alphav\n where date>=current_date()- INTERVAL 60 DAY\n and symbol = '\"\"\"+symbol+\"\"\"'\n group by 1,2,5,6,7\n )\n union all\n (\n \t\tselect 'autol' as model, symbol, avg(adj_close) as price_mode, 5*stddev(adj_close) as price_band\n \t\t\t, 0.5 as price_shape\n \t\t\t, 0.5 as price_skew\n , least(2*exp(4*0.5)-1, greatest(1,exp(4*0.5)*(1+0.5))) as alpha\n , least(2*exp(4*0.5)-1, greatest(1,exp(4*0.5)*(1-0.5))) as beta\n from us.equity_daily_recent_alphav\n where date>=current_date()- INTERVAL 60 DAY\n and symbol = '\"\"\"+symbol+\"\"\"'\n group by 1,2,5,6,7\n )\n union all\n (\n \t\tselect 'autor' as model, symbol, avg(adj_close) as price_mode, 5*stddev(adj_close) as price_band\n \t\t , 0.5 as price_shape\n , -0.5 as price_skew\n , least(2*exp(4*0.5)-1, greatest(1,exp(4*0.5)*(1-0.5))) as alpha\n , least(2*exp(4*0.5)-1, greatest(1,exp(4*0.5)*(1+0.5))) as beta\n from us.equity_daily_recent_alphav\n where date>=current_date()- INTERVAL 60 DAY\n and symbol = '\"\"\"+symbol+\"\"\"'\n group by 1,2,5,6,7\n )\n ) as temp\n where model = '\"\"\" +model+ \"\"\"'\n ; commit;\n \"\"\"\n print(insert_query)\n ExecQuery(data_config['database'], insert_query, False, False) \n\n\ndef InsertPxDistConviction(data_config, symbol, model, conviction):\n # conviction should be a string that can be translated into float\n insert_query = \"\"\"insert into \"\"\" +data_config['px_dist_conviction_table']+ \"\"\"\n select current_timestamp() as asof_datetime, \n '\"\"\"+model+\"\"\"' as model, \n '\"\"\"+symbol+\"\"\"' as symbol, \n \"\"\"+conviction+\"\"\" as conviction, \n false as deprecated; commit;\n \"\"\"\n print(insert_query)\n ExecQuery(data_config['database'], insert_query, False, False) \n\n\n#########################################\n### The Helper Functions\n#########################################\ndef StrToFloat(str):\n try:\n f = float(str)\n except ValueError:\n f = None\n return f\n\ndef CanToFloat(str):\n try:\n float(str)\n return True\n except ValueError:\n return False\n \n\n\n#########################################\n### Execute\n#########################################\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/Python/RunGUI_help.py","file_name":"RunGUI_help.py","file_ext":"py","file_size_in_byte":14371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"367506534","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nMódulo encargado de realizar imprimir información a la salida estándar (STDOUT)\n\"\"\"\n\nimport datetime\n\ndef imprime_registros(registros, titulo=None):\n \"\"\"\n Imprime la lista de registros en la salida estándar en formato texto, cada\n registro es de tipo lista.\n\n titulo - Es de tipo str y si es proporcionado se imprime como título\n \"\"\"\n # Se calcula el ancho máximo para cada columna\n anchos = [[len(str(campo)) for campo in reg] for reg in registros]\n anchos = [max(col) for col in zip(*anchos)]\n\n # Se imprime la lista\n print()\n if titulo: print(titulo)\n print(\"-\" * len(titulo))\n for reg in registros:\n # Se cambia los valores None por cademas vacias para impresión\n reg = tuple(r if r != None else \"\" for r in reg)\n # Se combierten las fechas a str\n reg = tuple(str(r) if type(r) == datetime.date else r for r in reg)\n # Se formatea cada registro en una línea de texto\n reg = zip(reg, anchos)\n reg = [\"{:{}}\".format(*campo) for campo in reg]\n print(\" | \".join(reg))\n print(\"-\" * len(titulo))\n print()\n\ndef imprime_registros_html(registros, titulo=None):\n \"\"\"\n Imprime la lista de registros en la salida estándar en formato HTML, cada\n registro es de tipo lista.\n\n titulo - Es de tipo str y si es proporcionado se imprime como título\n \"\"\"\n # Se calcula el ancho máximo para cada columna\n anchos = [[len(str(campo)) for campo in reg] for reg in registros]\n anchos = [max(col) for col in zip(*anchos)]\n\n # Se crea la variable de tipo plantilla\n html = \"\"\"\n\n\n {titulo}\n \n \n\n\n

{titulo}

\n
\n \n \n {renglones}\n
\n\n\n \"\"\"\n data = {\n \"titulo\":titulo,\n }\n renglones = []\n for reg in registros:\n linea = \"\"\n for campo in reg:\n # Se cambia los valores None por cademas vacias para impresión\n campo = \"\" if campo == None else campo\n linea += \"{}\".format(campo)\n linea += \"\"\n renglones.append(linea)\n data[\"renglones\"] = \"\\n\".join(renglones)\n html = html.format(**data)\n print(html)\n\n # reg = tuple(str(r) if type(r) == datetime.date else r for r in reg)\n #reg = zip(reg, anchos)\n","sub_path":"Clase-06/Postwork/stdout.py","file_name":"stdout.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"412353436","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\nfrom django.db import models\nfrom datetime import datetime\n# Create your models here.\nfrom django.db import models\nfrom django.utils import timezone\n\nclass Noticia(models.Model):\n autor = models.ForeignKey('auth.User')\n titulo = models.CharField(max_length=200)\n texto = models.TextField()\n textolimpo = models.TextField()\n data_criacao = models.DateTimeField(default=timezone.now)\n data_publicacao = models.DateTimeField(blank=True, null=True)\n imagem_url = models.TextField()\n\n def publish(self):\n self.data_publicacao = timezone.now()\n self.save()\n\n def __str__(self):\n return self.titulo\n\n\nclass Album(models.Model):\n class Meta:\n ordering = ('titulo',)\n titulo = models.CharField(max_length=255,null=False)\n noticia = models.ForeignKey('Noticia')\n\ndef imagedir(instance, filename):\n # file will be uploaded to MEDIA_ROOT/user_/\n from django.core.files.uploadedfile import SimpleUploadedFile\n import os\n DJANGO_TYPE = instance.imagem.file.content_type\n\n if DJANGO_TYPE == 'image/jpeg':\n PIL_TYPE = 'jpeg'\n FILE_EXTENSION = 'jpg'\n elif DJANGO_TYPE == 'image/png':\n PIL_TYPE = 'png'\n FILE_EXTENSION = 'png'\n return 'noticias/original/{0}/{1}'.format(instance.album.noticia.id,'%s.%s'%(instance.album.noticia.id,FILE_EXTENSION))\n\ndef thumbdir(instance, filename):\n # file will be uploaded to MEDIA_ROOT/user_/\n return 'noticias/miniatura/{0}/{1}'.format(instance.album.noticia.id, filename)\n\nclass Imagem(models.Model):\n album = models.ForeignKey('Album')\n descricao = models.CharField(max_length=255, null=False)\n imagem = models.ImageField(upload_to=imagedir, null=True, blank=True)\n thumbnail = models.ImageField(upload_to=thumbdir, null=True, blank=True)\n publicacao = models.DateTimeField(default=datetime.now, blank=True)\n\n def criar_miniatura(self):\n if not self.imagem:\n return\n\n from PIL import Image\n from io import BytesIO\n from django.core.files.uploadedfile import SimpleUploadedFile\n import os\n\n MINIATURA_TAMANHO = (900,300)\n\n DJANGO_TYPE = self.imagem.file.content_type\n\n if DJANGO_TYPE == 'image/jpeg':\n PIL_TYPE = 'jpeg'\n FILE_EXTENSION = 'jpg'\n elif DJANGO_TYPE == 'image/png':\n PIL_TYPE = 'png'\n FILE_EXTENSION = 'png'\n\n imagem = Image.open(BytesIO(self.imagem.read()))\n imagem.thumbnail(MINIATURA_TAMANHO, Image.ANTIALIAS)\n temp_handle = BytesIO()\n imagem.save(temp_handle, PIL_TYPE)\n temp_handle.seek(0)\n\n suf = SimpleUploadedFile(os.path.split(self.imagem.name)[-1],\n temp_handle.read(), content_type=DJANGO_TYPE)\n self.thumbnail.save('%s.%s'%(self.album.noticia.id,FILE_EXTENSION), suf, save=False)\n\n def save(self):\n self.criar_miniatura()\n super(Imagem, self).save()\n","sub_path":"tower/web/noticias/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"28516187","text":"class Student:\n def __init__(self,grade,name,roll,phn):\n print('Student admitted')\n self.grade=grade\n self.name=name\n self.roll=roll\n self.phn=phn\nclass Sport(Student):\n def __init__(self,grade,name,roll,phn,sport):\n self.grade=grade\n self.name=name\n self.roll=roll\n self.phn=phn\n self.sport=sport\n def showAttributes(self):\n print('Grade :\\t',self.grade)\n print('Name :\\t',self.name)\n print('Roll No :\\t',self.roll)\n print('Phone No :\\t',self.phn)\n print('Sport :\\t',self.sport)\n print('\\n')\n def changePhn(self,phn):\n self.phn=phn\n print('Phone number changed')\n self.showAttributes()\n print('\\n')\n def showSport(self):\n print(self.name,'plays',self.sport)\n print('\\n')\n def changeSport(self,sport):\n self.sport=sport\n print('Sport changed')\n self.showAttributes()\n print('\\n')\n def __del__(self):\n print(self.name,'doesn\\'t play sports anymore.')\nst1=Student(\"2nd\",\"Venu\",\"21\",\"6301677089\") \nsp1=Sport(\"2nd\",\"Venu\",\"21\",\"6301677089\",\"Basket Ball\")\nsp1.showAttributes()\nsp1.showSport()\nsp1.changePhn(\"7993273965\")\nsp1.changeSport(\"Football\")\ndel sp1\n\n\n ","sub_path":"3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":1290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"598380734","text":"import os\nimport sys\nfrom PIL import Image\n\nsource = sys.argv[1]\nprint(source)\n\ndest = sys.argv[2]\nprint(dest)\n\nif(not os.path.isdir(source)):\n print('Source directory does not exist')\nelse:\n if(not os.path.isdir(dest)):\n os.mkdir(dest)\n for file in os.listdir(source):\n if(file.endswith(\".jpg\")):\n img = Image.open(f'./{source}/{file}')\n img.save(f'./{dest}/{file.split(\".\")[0]}.png', \"png\")\n","sub_path":"JPGToPNGConverter.py","file_name":"JPGToPNGConverter.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"94694451","text":"#!/usr/bin/env python\n\nfrom twisted.internet import reactor\nfrom twisted.web.resource import Resource\nfrom twisted.web.server import (\n NOT_DONE_YET,\n Site,\n)\n\nimport config\n\nclass ChatSpawner(Resource):\n isLeaf = True\n\n def render_GET(self, request):\n request.site.add_user(request)\n\n request.setHeader(\"Content-Type\", \"text/event-stream\")\n request.setHeader(\"Access-Control-Allow-Origin\", config.host)\n\n return NOT_DONE_YET\n\nclass SendMessage(Resource):\n isLeaf = True\n\n def render_POST(self, request):\n request.setHeader(\"Access-Control-Allow-Origin\", config.host)\n request.site.send_message(request.args[\"message\".encode()][0])\n\n return \"\".encode()\n\nclass Root(Resource):\n def __init__(self):\n super().__init__()\n\n self.putChild(\"chat-spawner\".encode(), ChatSpawner())\n self.putChild(\"send-message\".encode(), SendMessage())\n\nclass Server(Site):\n def __init__(self, root):\n self._users = []\n\n super().__init__(root)\n\n def add_user(self, user):\n self._users.append(user)\n\n def send_message(self, message):\n message = message.decode()\n for user in self._users[:]:\n try:\n data = \"data: {message}\\r\\n\\r\\n\".format(**locals())\n user.write(data.encode())\n except AttributeError: # Disconnected\n self._users.remove(user)\n\nfactory = Server(Root())\nreactor.listenTCP(10194, factory)\n\nreactor.run()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"42493972","text":"\"\"\"\nPlanarAlly backend server code.\nThis is the code responsible for starting the backend and reacting to socket IO events.\n\"\"\"\n\nimport save\n\nsave.check_save()\n\nimport asyncio\nimport sys\n\nfrom aiohttp import web\n\nimport api.http\nimport routes\n\n# Force loading of socketio routes\nfrom api.socket import *\nfrom app import app, logger, sio, state\nfrom config import config\n\n# This is a fix for asyncio problems on windows that make it impossible to do ctrl+c\nif sys.platform.startswith(\"win\"):\n\n def _wakeup():\n asyncio.get_event_loop().call_later(0.1, _wakeup)\n\n asyncio.get_event_loop().call_later(0.1, _wakeup)\n\n\nasync def on_shutdown(_):\n for sid in list(state.sid_map.keys()):\n await sio.disconnect(sid, namespace=\"/planarally\")\n\n\napp.router.add_static(\"/static\", \"static\")\napp.router.add_get(\"/api/auth\", api.http.auth.is_authed)\napp.router.add_post(\"/api/login\", api.http.auth.login)\napp.router.add_post(\"/api/register\", api.http.auth.register)\napp.router.add_post(\"/api/logout\", api.http.auth.logout)\napp.router.add_get(\"/api/rooms\", api.http.rooms.get_list)\napp.router.add_post(\"/api/rooms\", api.http.rooms.create)\napp.router.add_post(\"/api/invite\", api.http.claim_invite)\n\nif \"dev\" in sys.argv:\n app.router.add_route(\"*\", \"/{tail:.*}\", routes.root_dev)\nelse:\n app.router.add_route(\"*\", \"/{tail:.*}\", routes.root)\n# app.router.add_route(\"*\", \"/\", routes.login)\n# app.router.add_get(\"/rooms\", routes.show_rooms)\n# app.router.add_get(\"/rooms/{username}/{roomname}\", routes.show_room)\n# app.router.add_get(\"/invite/{code}\", routes.claim_invite)\n# app.router.add_post(\"/create_room\", routes.create_room)\n# app.router.add_get(\"/assets/\", routes.show_assets)\n# app.router.add_get(\"/logout\", routes.logout)\n\napp.on_shutdown.append(on_shutdown)\n\nif __name__ == \"__main__\":\n if config.getboolean(\"Webserver\", \"ssl\"):\n import ssl\n\n ctx = ssl.SSLContext()\n ctx.load_cert_chain(\n config.get(\"Webserver\", \"ssl_fullchain\"),\n config.get(\"Webserver\", \"ssl_privkey\"),\n )\n web.run_app(\n app,\n host=config.get(\"Webserver\", \"host\"),\n port=config.getint(\"Webserver\", \"port\"),\n ssl_context=ctx,\n )\n else:\n logger.warning(\" RUNNING IN NON SSL CONTEXT \")\n web.run_app(\n app,\n host=config.get(\"Webserver\", \"host\"),\n port=config.getint(\"Webserver\", \"port\"),\n )\n","sub_path":"server/planarserver.py","file_name":"planarserver.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"187485572","text":"from __future__ import print_function, division\nimport os \nimport torch \nimport pandas as pd \nfrom skimage import io, transform \nimport numpy as np \nimport matplotlib.pyplot as plt \nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\nfrom PIL import Image\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nclass BengaliTestLoader(Dataset):\n def __init__(self, image_folder, label_file = None, transform=False):\n self.image_folder = image_folder \n self.label_file = label_file \n #self.label_file = self.label_file.image_id\n self.transform = transforms.Compose([\n transforms.ToTensor(), \n transforms.Normalize(mean = [0.485, 0.456, 0.406], \n std = [0.229 ,0.224, 0.225]),\n ])\n \n def __len__(self):\n return len(os.listdir(self.image_folder)) \n \n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n trans = transforms.ToTensor()\n img_name = os.path.join(self.image_folder, '{}.png'.format(self.label_file.iloc[idx])) \n image = Image.open(img_name).convert('RGB')\n #label = self.label_file.iloc[idx] \n if self.transform:\n sample['image'] = self.transform(sample['image'])\n return sample\n \nclass BengaliDataLoader(Dataset):\n def __init__(self, image_folder, label_file, transform=False):\n self.image_folder = image_folder \n self.label_file = pd.read_csv(label_file)\n self.grapheme = self.label_file.grapheme_root\n self.vowel = self.label_file.vowel_diacritic\n self.consonant = self.label_file.consonant_diacritic\n self.label_file = self.label_file.image_id\n self.transform = transforms.Compose([\n transforms.ToTensor(), \n transforms.Normalize(mean = [0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]),\n ])\n\n def __len__(self):\n return len(self.label_file)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n trans = transforms.ToTensor()\n img_name = os.path.join(self.image_folder, '{}.png'.format(self.label_file.iloc[idx]) )\n image=Image.open(img_name).convert(\"RGB\")\n #image = trans(image) \n \n #image = transforms.ToPILImage()(image).convert(\"RGB\")\n label = self.label_file.iloc[idx]\n grapheme = self.grapheme.iloc[idx]\n vowel = self.vowel.iloc[idx]\n consonant = self.consonant[idx]\n sample = {'image' : image, 'label' : label, \n 'grapheme': grapheme, \n 'vowel' : vowel, \n 'consonant' : consonant}\n grapheme = label[0]\n vowel = label[1]\n consonant = label[2] \n if self.transform:\n sample['image'] = self.transform(sample['image'])\n return sample\n\nclass GraphemeDataset(Dataset):\n def __init__(self, fname):\n print(fname)\n self.df = pd.read_parquet(fname)\n self.data = 255 - self.df.iloc[:, 1:].values.reshape(-1, 128, 128).astype(np.uint8)\n \n def __len__(self):\n return len(self.data)\n \n def __getitem__(self, idx):\n name = self.df.iloc[idx, 0]\n img = (self.data[idx]*(255.0/self.data[idx].max())).astype(np.uint8)\n #img = crop_resize(img)\n img = cv2.resize(img, (128,128))\n img = img.astype(np.float32)/255.0 \n return img, name \n \ndef __inference(test_data = list()):\n row_id, target = [], [] \n for fname in test_data:\n test_image = GraphemeDataset(fname)\n dl = torch.utils.data.DataLoader(test_image, \n batch_size=128, shuffle=False)\n with torch.no_grad():\n for x, y in tqdm(dl):\n x = x.unsqueeze(1).float().cuda()\n p1, p2, p3 = model(x)\n p1 = p1.argmax(-1).view(-1).cpu()\n p2 = p2.argmax(-1).view(-1).cpu()\n p3 = p3.argmax(-1).view(-1).cpu()\n for idx, name in enumerate(y):\n row_id += [f'{name}_vowel_diacritic', f'{name}_grapheme_root', \n f'{name}_consonant_diacritic']\n target += [p1[idx].item(), p2[idx].item(), p3[idx].item()]\n \n sub_df = pd.DataFrame({'row_id' : row_id, 'target' : target})\n sub_df.to_csv('submission_csv', index=False)\n sub_df.head(20)\n \n \n \ndef main():\n\n pass\nif __name__ == '__main__':\n main()","sub_path":"src/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"574092387","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 13 14:45:34 2018\n\n@author: chakyu\n\"\"\"\n\n#---- Creating files ----\n\nfileHandle = open('namesfixed.csv', 'w')\n\nprint('Welcome to the phone number program')\n\nname = input('Please enter person\\'s name: ')\n\nwhile True:\n\n if name == '':\n print()\n print('-'*50)\n print('No more names entered. Program will cease and file will be closed.')\n print('Thank You')\n fileHandle.close() \n break\n else:\n number = input('Please enter %s\\'s number: ' % name)\n fileHandle.write(name.ljust(10) + number.ljust(15) + '\\n')\n\n name = input('Please enter person\\'s name: ')\n\n#---- End program ----\n","sub_path":"fileFixedWrite.py","file_name":"fileFixedWrite.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"554817925","text":"from __future__ import print_function\nfrom simtk.openmm.app import *\nfrom simtk.openmm import *\nfrom simtk.unit import *\nfrom sys import stdout\nfrom time import gmtime, strftime\nfrom datetime import datetime\n\ntemperature=323.15*kelvin\n\npdb = PDBFile('nvt_init.pdb')\nstrdir = ''\n\ninteg_md = DrudeLangevinIntegrator(temperature, 1/picosecond, 1*kelvin, 1/picosecond, 0.001*picoseconds)\ninteg_md.setMaxDrudeDistance(0.02) # this should prevent polarization catastrophe during equilibration, but shouldn't affect results afterwards ( 0.2 Angstrom displacement is very large for equil. Drudes)\n\npdb.topology.loadBondDefinitions('sapt_residues.xml')\npdb.topology.createStandardBonds();\n\nmodeller = Modeller(pdb.topology, pdb.positions)\nforcefield = ForceField('sapt.xml')\nmodeller.addExtraParticles(forcefield)\n#PDBFile.writeFile(modeller.topology, modeller.positions, open('init.pdb', 'w'))\n\nsystem = forcefield.createSystem(modeller.topology, nonbondedCutoff=1.4*nanometer, constraints=None, rigidWater=True)\nnbondedForce = [f for f in [system.getForce(i) for i in range(system.getNumForces())] if type(f) == NonbondedForce][0]\ncustomNonbondedForce = [f for f in [system.getForce(i) for i in range(system.getNumForces())] if type(f) == CustomNonbondedForce][0]\ncustombond = [f for f in [system.getForce(i) for i in range(system.getNumForces())] if type(f) == CustomBondForce][0]\ndrudeForce = [f for f in [system.getForce(i) for i in range(system.getNumForces())] if type(f) == DrudeForce][0]\nnbondedForce.setNonbondedMethod(NonbondedForce.PME)\ncustomNonbondedForce.setNonbondedMethod(min(nbondedForce.getNonbondedMethod(),NonbondedForce.CutoffPeriodic))\nprint('nbMethod : ', customNonbondedForce.getNonbondedMethod())\n\nfor i in range(system.getNumForces()):\n f = system.getForce(i)\n type(f)\n f.setForceGroup(i)\n\ntotmass = 0.*dalton\nfor i in range(system.getNumParticles()):\n totmass += system.getParticleMass(i)\n\n#system.addForce(AndersenThermostat(300*kelvin, 10/picosecond))\n\nplatform = Platform.getPlatformByName('CUDA')\n#platform = Platform.getPlatformByName('CPU')\n#platform = Platform.getPlatformByName('OpenCL')\n#properties = {'OpenCLPrecision': 'mixed'}\nproperties = {'CudaPrecision': 'mixed'}\n\n#simmd = Simulation(simeq.topology, system, integ_md, platform)\nsimmd = Simulation(modeller.topology, system, integ_md, platform, properties)\nsimmd.context.setPositions(modeller.positions)\n#simmd.context.setPositions(pdbpos.positions)\n\nplatform =simmd.context.getPlatform()\nplatformname = platform.getName();\nprint(platformname)\n\n\n#*************************************************************************************\n# This is section to create exclusions for TFSI nonbonded interactions, and update\n# Screened Drude interactions. 1-5 non-Coulomb interaction are accounted for\n# using CustomBondForce\n#*************************************************************************************\nprint('Creating Exclusions for TFSI')\n\n# map from global particle index to drudeforce object index\nparticleMap = {}\nfor i in range(drudeForce.getNumParticles()):\n particleMap[drudeForce.getParticleParameters(i)[0]] = i\n\n# can't add duplicate ScreenedPairs, so store what we already have\nflagexceptions = {}\nfor i in range(nbondedForce.getNumExceptions()):\n (particle1, particle2, charge, sigma, epsilon) = nbondedForce.getExceptionParameters(i)\n string1=str(particle1)+\"_\"+str(particle2)\n string2=str(particle2)+\"_\"+str(particle1)\n flagexceptions[string1]=1\n flagexceptions[string2]=1\n\n# can't add duplicate customNonbonded exclusions, so store what we already have\nflagexclusions = {}\nfor i in range(customNonbondedForce.getNumExclusions()):\n (particle1, particle2) = customNonbondedForce.getExclusionParticles(i)\n string1=str(particle1)+\"_\"+str(particle2)\n string2=str(particle2)+\"_\"+str(particle1)\n flagexclusions[string1]=1\n flagexclusions[string2]=1\n\n# add exclusions for all atom pairs on TFSI residues, and when a drude pair is \n# excluded add a corresponding screened thole interaction in its place\nfor res in simmd.topology.residues():\n if res.name == 'Tf2N':\n for i in range(len(res._atoms)-1):\n for j in range(i+1,len(res._atoms)):\n (indi,indj) = (res._atoms[i].index, res._atoms[j].index)\n\t # here it doesn't matter if we already have this, since we pass the \"True\" flag\n nbondedForce.addException(indi,indj,0,1,0,True)\n\t # make sure we don't already exlude this customnonbond\n string1=str(indi)+\"_\"+str(indj)\n string2=str(indj)+\"_\"+str(indi)\n if string1 in flagexclusions and string2 in flagexclusions:\n continue\n else:\n customNonbondedForce.addExclusion(indi,indj)\n print(res.index,i,j)\n # add thole if we're excluding two drudes\n if indi in particleMap and indj in particleMap:\n # make sure we don't already have this screened pair\n if string1 in flagexceptions or string2 in flagexceptions:\n continue\n else:\n drudei = particleMap[indi]\n drudej = particleMap[indj]\n drudeForce.addScreenedPair(drudei, drudej, 2.0)\n\n\n#************************************* end of TFSI section **************************\nsimmd.context.reinitialize()\nsimmd.context.setPositions(modeller.positions)\n\n# load restart files\n#simmd.loadCheckpoint('md_nvt.chk')\n\nprint('Starting Production NVT Simulation...')\nt1 = datetime.now()\nstate = simmd.context.getState(getEnergy=True,getForces=False,getVelocities=False,getPositions=True)\n\n# write initial pdb with drude oscillators\nposition = state.getPositions()\nsimmd.topology.setPeriodicBoxVectors(state.getPeriodicBoxVectors())\nPDBFile.writeFile(simmd.topology, position, open(strdir+'start_drudes.pdb', 'w'))\n\n# initial energies\nprint(str(state.getKineticEnergy()))\nprint(str(state.getPotentialEnergy()))\nfor j in range(system.getNumForces()):\n f = system.getForce(j)\n print(type(f), str(simmd.context.getState(getEnergy=True, groups=2**j).getPotentialEnergy()))\n\nsimmd.step(50000)\nprint(\"... velocity stable...\")\n\nsimmd.reporters = []\nsimmd.reporters.append(DCDReporter(strdir+'md_nvt_pos.dcd',5000,enforcePeriodicBox=False,writeVel=False))\nsimmd.reporters.append(DCDReporter(strdir+'md_nvt_vel.dcd',5000,enforcePeriodicBox=False,writeVel=True))\n\n#*************************************************\n# ChangYun created the DrudeDataReporter class, we need to pull this into this OpenMM install if we want to use it\n#*************************************************\n#simmd.reporters.append(DrudeDataReporter(strdir+'md_nvt.log', 1000, step=True, time=True, potentialEnergy=True, kineticEnergy=True, totalEnergy=True, temperature=True, langevin=True, density=False,speed=True))\n#simmd.reporters.append(DrudeDataReporter(strdir+'md_nvt_temp.log', 10000, step=True, time=True, potentialEnergy=True, kineticEnergy=True, totalEnergy=True, temperature=True, langevin=True, drudeTemperature=True,density=False,speed=True))\nsimmd.reporters.append(CheckpointReporter(strdir+'md_nvt.chk', 5000))\nsimmd.reporters[1].report(simmd,state)\n#simmd.reporters[2].report(simmd,state)\n\n#for i in range(simmd.system.getNumForces()):\n# if type(simmd.system.getForce(i)) == MonteCarloBarostat:\n# simmd.system.removeForce(i)\n\nprint('Simulating...')\n\nfor i in range(1,20001):\n simmd.step(5000)\n #print(i,strftime(\"%Y-%m-%d %H:%M:%S\", gmtime()))\n #print(i,datetime.now())\n state = simmd.context.getState(getEnergy=True,getForces=False,getPositions=False)\n print(str(state.getKineticEnergy()))\n #print(str(state.getPotentialEnergy()))\n #for j in range(system.getNumForces()):\n # f = system.getForce(j)\n # print(type(f), str(simmd.context.getState(getEnergy=True, groups=2**j).getPotentialEnergy()))\n\nt2 = datetime.now()\nt3 = t2 - t1\nprint('simulation took', t3.seconds,'seconds')\nprint('Simulating...')\nstate = simmd.context.getState(getEnergy=True,getForces=True,getPositions=True,enforcePeriodicBox=True)\nposition = state.getPositions()\nsimmd.topology.setPeriodicBoxVectors(state.getPeriodicBoxVectors())\nPDBFile.writeFile(simmd.topology, position, open(strdir+'md_nvt.pdb', 'w'))\n\nprint('Done!')\n\nexit()\n","sub_path":"py_development/md_htjung/run_openMM_nvt.py","file_name":"run_openMM_nvt.py","file_ext":"py","file_size_in_byte":8232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"23485685","text":"#!/usr/bin/python3\nfrom fabric.api import *\nimport time\n\"\"\"\n\"\"\"\n\ndef do_pack():\n \"\"\"\n Compresses a repository into a tarball, puts it into a directory with versions.\n \"\"\"\n formatstring = \"tar -vcf webstatic.\" + time.strftime(\"%Y%m%d%H%M%S\", time.localtime()) + \".tgz webstatic/\"\n return(fabric.run(formatstring))\n\nurn = do_pack()\nprint(urn)\n","sub_path":"1-pack_web_static.py","file_name":"1-pack_web_static.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"234634190","text":"import matplotlib\nimport time\n\n#setting appropriate and available library to use with plots\nmatplotlib.use('GTK3Cairo')\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef plot_one_graph(datax, datay, xlabel, ylabel, plot_label, symbol, title):\n plt.plot(datax, datay, label=plot_label, marker=symbol, linestyle='None')\n plt.xlabel(xlabel, fontsize=size_text)\n plt.ylabel(ylabel, fontsize=size_text)\n plt.title(title, fontsize=size_text)\n\ndef plot_many_graphs(datax, datay, xlabels, ylabels, plot_labels, symbols, title, export):\n f = plt.figure(figsize=(10,10))\n ax = f.add_subplot(111)\n ax.yaxis.set_ticks_position('both')\n ax.xaxis.set_ticks_position('both')\n ax.tick_params(which='both', direction='in')\n for i in range(len(datax)):\n plot_one_graph(datax[i], datay[i], xlabels[i], ylabels[i], plot_labels[i], symbols[i], title)\n\n plt.legend(prop={'size': size_text-6}, loc='upper right')\n plt.xscale('log')\n plt.grid(linestyle='dashed')\n\n dir_ext = \"comp_meth_scatter/\"\n plt.savefig(dir_ext + export)\n plt.show()\n\n\n# MAIN #\n\n#Exact values\ntrue_log_scale = -2.08\ntrue_ell = 0.5\ntrue_PA = 50\ntrue_bg = 20\n\nsize_text = 14\n\n###input data filenames###\nnames = [\"1280_bfgs_ellbg.output\", \"160_de_ellbg.output\", \"20_lbb_ellbg.output\", \"320_nm_ellbg.output\", \"40_tnc_ellbg.output\", \"80_bfgs_ellbg.output\",\n \"1280_de_ellbg.output\", \"160_lbb_ellbg.output\", \"20_nm_ellbg.output\", \"320_tnc_ellbg.output\", \"640_bfgs_ellbg.output\", \"80_de_ellbg.output\",\n \"1280_lbb_ellbg.output\", \"160_nm_ellbg.output\", \"20_tnc_ellbg.output\", \"40_bfgs_ellbg.output\", \"640_de_ellbg.output\", \"80_lbb_ellbg.output\",\n \"1280_nm_ellbg.output\", \"160_tnc_ellbg.output\", \"320_bfgs_ellbg.output\", \"40_de_ellbg.output\", \"640_lbb_ellbg.output\", \"80_nm_ellbg.output\",\n \"1280_tnc_ellbg.output\", \"20_bfgs_ellbg.output\", \"320_de_ellbg.output\", \"40_lbb_ellbg.output\", \"640_nm_ellbg.output\", \"80_tnc_ellbg.output\",\n \"160_bfgs_ellbg.output\", \"20_de_ellbg.output\", \"320_lbb_ellbg.output\", \"40_nm_ellbg.output\", \"640_tnc_ellbg.output\"]\n\nnames1 = [\"1280_bfgs_ellnobg.output\", \"160_de_ellnobg.output\", \"20_lbb_ellnobg.output\", \"320_nm_ellnobg.output\", \"40_tnc_ellnobg.output\", \"80_bfgs_ellnobg.output\",\n \"1280_de_ellnobg.output\", \"160_lbb_ellnobg.output\", \"20_nm_ellnobg.output\", \"320_tnc_ellnobg.output\", \"640_bfgs_ellnobg.output\", \"80_de_ellnobg.output\",\n \"1280_lbb_ellnobg.output\", \"160_nm_ellnobg.output\", \"20_tnc_ellnobg.output\", \"40_bfgs_ellnobg.output\", \"640_de_ellnobg.output\", \"80_lbb_ellnobg.output\",\n \"1280_nm_ellnobg.output\", \"160_tnc_ellnobg.output\", \"320_bfgs_ellnobg.output\", \"40_de_ellnobg.output\", \"640_lbb_ellnobg.output\", \"80_nm_ellnobg.output\",\n \"1280_tnc_ellnobg.output\", \"20_bfgs_ellnobg.output\", \"320_de_ellnobg.output\", \"40_lbb_ellnobg.output\", \"640_nm_ellnobg.output\", \"80_tnc_ellnobg.output\",\n \"160_bfgs_ellnobg.output\", \"20_de_ellnobg.output\", \"320_lbb_ellnobg.output\", \"40_nm_ellnobg.output\", \"640_tnc_ellnobg.output\"]\n\nnames2 = [\"1280_bfgs_noellbg.output\", \"160_de_noellbg.output\", \"20_lbb_noellbg.output\", \"320_nm_noellbg.output\", \"40_tnc_noellbg.output\", \"80_bfgs_noellbg.output\",\n \"1280_de_noellbg.output\", \"160_lbb_noellbg.output\", \"20_nm_noellbg.output\", \"320_tnc_noellbg.output\", \"640_bfgs_noellbg.output\", \"80_de_noellbg.output\",\n \"1280_lbb_noellbg.output\", \"160_nm_noellbg.output\", \"20_tnc_noellbg.output\", \"40_bfgs_noellbg.output\", \"640_de_noellbg.output\", \"80_lbb_noellbg.output\",\n \"1280_nm_noellbg.output\", \"160_tnc_noellbg.output\", \"320_bfgs_noellbg.output\", \"40_de_noellbg.output\", \"640_lbb_noellbg.output\", \"80_nm_noellbg.output\",\n \"1280_tnc_noellbg.output\", \"20_bfgs_noellbg.output\", \"320_de_noellbg.output\", \"40_lbb_noellbg.output\", \"640_nm_noellbg.output\", \"80_tnc_noellbg.output\",\n \"160_bfgs_noellbg.output\", \"20_de_noellbg.output\", \"320_lbb_noellbg.output\", \"40_nm_noellbg.output\", \"640_tnc_noellbg.output\"]\n\nnames3 = [\"1280_bfgs_noellnobg.output\", \"160_de_noellnobg.output\", \"20_lbb_noellnobg.output\", \"320_nm_noellnobg.output\", \"40_tnc_noellnobg.output\", \"80_bfgs_noellnobg.output\",\n \"1280_de_noellnobg.output\", \"160_lbb_noellnobg.output\", \"20_nm_noellnobg.output\", \"320_tnc_noellnobg.output\", \"640_bfgs_noellnobg.output\", \"80_de_noellnobg.output\",\n \"1280_lbb_noellnobg.output\", \"160_nm_noellnobg.output\", \"20_tnc_noellnobg.output\", \"40_bfgs_noellnobg.output\", \"640_de_noellnobg.output\", \"80_lbb_noellnobg.output\",\n \"1280_nm_noellnobg.output\", \"160_tnc_noellnobg.output\", \"320_bfgs_noellnobg.output\", \"40_de_noellnobg.output\", \"640_lbb_noellnobg.output\", \"80_nm_noellnobg.output\",\n \"1280_tnc_noellnobg.output\", \"20_bfgs_noellnobg.output\", \"320_de_noellnobg.output\", \"40_lbb_noellnobg.output\", \"640_nm_noellnobg.output\", \"80_tnc_noellnobg.output\",\n \"160_bfgs_noellnobg.output\", \"20_de_noellnobg.output\", \"320_lbb_noellnobg.output\", \"40_nm_noellnobg.output\", \"640_tnc_noellnobg.output\"]\n\nnames4 = [\"1280_bfgs_ellbgcen_10000.output\", \"160_de_ellbgcen_10000.output\", \"20_lbb_ellbgcen_10000.output\", \"320_nm_ellbgcen_10000.output\", \"40_tnc_ellbgcen_10000.output\", \"80_bfgs_ellbgcen_10000.output\",\n \"1280_de_ellbgcen_10000.output\", \"160_lbb_ellbgcen_10000.output\", \"20_nm_ellbgcen_10000.output\", \"320_tnc_ellbgcen_10000.output\", \"640_bfgs_ellbgcen_10000.output\", \"80_de_ellbgcen_10000.output\",\n \"1280_lbb_ellbgcen_10000.output\", \"160_nm_ellbgcen_10000.output\", \"20_tnc_ellbgcen_10000.output\", \"40_bfgs_ellbgcen_10000.output\", \"640_de_ellbgcen_10000.output\", \"80_lbb_ellbgcen_10000.output\",\n \"1280_nm_ellbgcen_10000.output\", \"160_tnc_ellbgcen_10000.output\", \"320_bfgs_ellbgcen_10000.output\", \"40_de_ellbgcen_10000.output\", \"640_lbb_ellbgcen_10000.output\", \"80_nm_ellbgcen_10000.output\",\n \"1280_tnc_ellbgcen_10000.output\", \"20_bfgs_ellbgcen_10000.output\", \"320_de_ellbgcen_10000.output\", \"40_lbb_ellbgcen_10000.output\", \"640_nm_ellbgcen_10000.output\", \"80_tnc_ellbgcen_10000.output\",\n \"160_bfgs_ellbgcen_10000.output\", \"20_de_ellbgcen_10000.output\", \"320_lbb_ellbgcen_10000.output\", \"40_nm_ellbgcen_10000.output\", \"640_tnc_ellbgcen_10000.output\"]\n\nnames5 = [\"1280_medsep_ellnobg.output\", \"160_medsep_ellnobg.output\", \"20_medsep_ellnobg.output\", \"320_medsep_ellnobg.output\", \"40_medsep_ellnobg.output\", \"640_medsep_ellnobg.output\", \"80_medsep_ellnobg.output\"]\n\nnbgal = [1280, 160, 20, 320, 40, 80, 1280, 160, 20, 320, 640, 80, 1280, 160, 20, 40, 640, 80, 1280, 160, 320, 40, 640, 80, 1280, 20, 320, 40, 640, 80, 160, 20, 320, 40, 640]\nmeth = [\"bfgs\", \"de\", \"lbb\", \"nm\", \"tnc\"]*7\ngalaxies = []\n\n#time\nstart = time.clock()\n\nscale_scatter, ell_scatter, PA_scatter, bg_scatter = [], [], [], []\nscale_scatter1, ell_scatter1, PA_scatter1, bg_scatter1 = [], [], [], []\nscale_scatter2, ell_scatter2, PA_scatter2, bg_scatter2 = [], [], [], []\nscale_scatter3, ell_scatter3, PA_scatter3, bg_scatter3 = [], [], [], []\nscale_scatter4, ell_scatter4, PA_scatter4, bg_scatter4 = [], [], [], []\nscale_scatter5 = []\n\nscale_guess_scatter, ell_guess_scatter, PA_guess_scatter, bg_guess_scatter = [], [], [], []\nscale_guess_scatter1, ell_guess_scatter1, PA_guess_scatter1, bg_guess_scatter1 = [], [], [], []\nscale_guess_scatter2, ell_guess_scatter2, PA_guess_scatter2, bg_guess_scatter2 = [], [], [], []\nscale_guess_scatter3, ell_guess_scatter3, PA_guess_scatter3, bg_guess_scatter3 = [], [], [], []\nscale_guess_scatter4, ell_guess_scatter4, PA_guess_scatter4, bg_guess_scatter4 = [], [], [], []\n\ngalaxies = []\ngalaxies2 = []\n\ndirectory = \"../ell_bg/\"\ndirectory1 = \"../ell_nobg/\"\ndirectory2 = \"../noell_bg/\"\ndirectory3 = \"../noell_nobg/\"\ndirectory4 = \"../ell_bg_cen10000/\"\ndirectory5 = \"../medsep/\"\n\n#median separation\nfor i in range(len(names5)):\n log_scale_radius = np.genfromtxt(directory5 + names5[i], usecols=(12,), unpack=True)\n N = len(log_scale_radius)\n\n scale_scatter5.append(np.median(log_scale_radius) - true_log_scale)\n\n galaxies2.append(nbgal[i+12])\n log_scale_radius = []\n\nfor j in range(1,len(meth)//7):\n for i in range(j, len(names), 5):\n\t\t#ellipticity and background\n log_scale_radius, ell, PA, log_bg, lsr_guess, ell_guess, PA_guess, log_bg_guess = np.genfromtxt(directory + names[i], usecols=(12, 13, 14, 15, 22, 23, 24, 25), unpack=True)\n N = len(log_scale_radius)\n\n scale_scatter.append(np.std(log_scale_radius))\n ell_scatter.append(np.std(ell))\n PA_scatter.append(np.std(PA))\n bg_scatter.append(np.std(log_bg))\n\n scale_guess_scatter.append(np.std(lsr_guess))\n ell_guess_scatter.append(np.std(ell_guess))\n PA_guess_scatter.append(np.std(PA_guess))\n bg_guess_scatter.append(np.std(log_bg_guess))\n\n\t\t#ellipticity no background\n log_scale_radius, ell, PA, log_bg, lsr_guess, ell_guess, PA_guess, log_bg_guess = np.genfromtxt(directory1 + names1[i], usecols=(12, 13, 14, 15, 22, 23, 24, 25), unpack=True)\n N = len(log_scale_radius)\n\n scale_scatter1.append(np.std(log_scale_radius))\n ell_scatter1.append(np.std(ell))\n PA_scatter1.append(np.std(PA))\n bg_scatter1.append(np.std(log_bg))\n\n scale_guess_scatter1.append(np.std(log_scale_radius))\n ell_guess_scatter1.append(np.std(ell))\n PA_guess_scatter1.append(np.std(PA))\n bg_guess_scatter1.append(np.std(log_bg))\n\n #no ellipticity + background\n log_scale_radius, ell, PA, log_bg, lsr_guess, ell_guess, PA_guess, log_bg_guess = np.genfromtxt(directory2 + names2[i], usecols=(12, 13, 14, 15, 22, 23, 24, 25), unpack=True)\n N = len(log_scale_radius)\n\n scale_scatter2.append(np.std(log_scale_radius))\n ell_scatter2.append(np.std(ell))\n PA_scatter2.append(np.std(PA))\n bg_scatter2.append(np.std(log_bg))\n\n scale_guess_scatter2.append(np.std(lsr_guess))\n ell_guess_scatter2.append(np.std(ell_guess))\n PA_guess_scatter2.append(np.std(PA_guess))\n bg_guess_scatter2.append(np.std(log_bg_guess))\n\n #no ellipticity and no background\n log_scale_radius, ell, PA, log_bg, lsr_guess, ell_guess, PA_guess, log_bg_guess = np.genfromtxt(directory3 + names3[i], usecols=(12, 13, 14, 15, 22, 23, 24, 25), unpack=True)\n N = len(log_scale_radius)\n\n scale_scatter3.append(np.std(log_scale_radius))\n ell_scatter3.append(np.std(ell))\n PA_scatter3.append(np.std(PA))\n bg_scatter3.append(np.std(log_bg))\n\n scale_guess_scatter3.append(np.std(lsr_guess))\n ell_guess_scatter3.append(np.std(ell_guess))\n PA_guess_scatter3.append(np.std(PA_guess))\n bg_guess_scatter3.append(np.std(log_bg_guess))\n\n #ellipticity + background + centering + Monte-Carlo\n log_scale_radius, ell, PA, log_bg, lsr_guess, ell_guess, PA_guess, log_bg_guess = np.genfromtxt(directory4 + names4[i], usecols=(12, 13, 14, 15, 22, 23, 24, 25), unpack=True)\n N = len(log_scale_radius)\n\n scale_scatter4.append(np.std(log_scale_radius))\n ell_scatter4.append(np.std(ell))\n PA_scatter4.append(np.std(PA))\n bg_scatter4.append(np.std(log_bg))\n\n scale_guess_scatter4.append(np.std(lsr_guess))\n ell_guess_scatter4.append(np.std(ell_guess))\n PA_guess_scatter4.append(np.std(PA_guess))\n bg_guess_scatter4.append(np.std(log_bg_guess))\n\n galaxies.append(nbgal[i])\n\n step = 0.05\n x_data = np.array([[i*(1- 2.5*step) for i in galaxies], [i*(1-2*step) for i in galaxies], [i*(1-1.5*step) for i in galaxies], [i*(1-step) for i in galaxies], [ i*(1-0.5*step) for i in galaxies], [i*(1+0.5*step) for i in galaxies], [i*(1+step) for i in galaxies], [i*(1+1.5*step) for i in galaxies], [ i*(1+2*step) for i in galaxies], [i*(1+2.5*step) for i in galaxies]])\n x_data2 = np.array([[i*(1- 2.5*step) for i in galaxies2], [i*(1-2*step) for i in galaxies], [i*(1-1.5*step) for i in galaxies], [i*(1-step) for i in galaxies], [ i*(1-0.5*step) for i in galaxies], [i for i in galaxies], [i*(1+0.5*step) for i in galaxies], [i*(1+step) for i in galaxies], [ i*(1+1.5*step) for i in galaxies], [i*(1+2*step) for i in galaxies], [i*(1+2.5*step) for i in galaxies]])\n\n labels_x = [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"Number of galaxies\"]\n labels_x2 = [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"Number of galaxies\"]\n labels_plots = [\"found : No bg, no ell\", \"found : no bg, ell\", \"found : no ell, bg\", \"found : ell + bg\", \"found : ell + bg + cen(MC)\", \" guess : No bg, no ell\", \"guess : no bg, ell\", \"guess : no ell, bg\", \"guess : ell + bg\", \"guess : ell + bg + cen(MC)\"]\n labels_plots2 = [\"found : median sep\", \"found : No bg, no ell\", \"found : no bg, ell\", \"found : no ell, bg\", \"found : ell + bg\", \"found : ell + bg + cen(MC)\", \" guess : No bg, no ell\", \"guess : no bg, ell\", \"guess : no ell, bg\", \"guess : ell + bg\", \"guess : ell + bg + cen(MC)\"]\n symbols = [\".\", \"*\", \"x\", \"d\", \"s\", 'o', \"v\", '^', \"<\", \">\"]\n symbols2 = [\"+\", \".\", \"*\", \"x\", \"d\", \"s\", 'o', \"v\", '^', \"<\", \">\"]\n\n y_data = np.array([scale_scatter5, scale_scatter3, scale_scatter1, scale_scatter2, scale_scatter, scale_scatter4, scale_guess_scatter3, scale_guess_scatter1, scale_guess_scatter2, scale_guess_scatter, scale_guess_scatter4])\n labels_y = [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", r'$\\mathrm{\\sigma[log_{10} (r_{-2} / r_{-2}^{true})]}$']\n plot_many_graphs(x_data2, y_data, labels_x2, labels_y, labels_plots2, symbols2, meth[j].upper() + \" method\", meth[j] + \"_comp_scale_radius_scat.pdf\")\n\n y_data = []\n y_data = np.array([ell_scatter3, ell_scatter1, ell_scatter2, ell_scatter, ell_scatter4, ell_guess_scatter3, ell_guess_scatter1, ell_guess_scatter2, ell_guess_scatter, ell_guess_scatter4])\n labels_y = [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", r'$\\mathrm{\\sigma[e - e^{true}]}$']\n plot_many_graphs(x_data, y_data, labels_x, labels_y, labels_plots, symbols, meth[j].upper() + \" method\", meth[j] + \"_comp_ell_scat.pdf\")\n\n y_data = []\n y_data = np.array([PA_scatter3, PA_scatter1, PA_scatter2, PA_scatter, PA_scatter4, PA_guess_scatter3, PA_guess_scatter1, PA_guess_scatter2, PA_guess_scatter, PA_guess_scatter4])\n labels_y = [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", r'$\\mathrm{\\sigma[PA - PA^{true}]}$' + \" (deg)\"]\n plot_many_graphs(x_data, y_data, labels_x, labels_y, labels_plots, symbols, meth[j].upper() + \" method\", meth[j] + \"_comp_PA_scat.pdf\")\n\n y_data = []\n y_data = np.array([bg_scatter3, bg_scatter1, bg_scatter2, bg_scatter, bg_scatter4, bg_guess_scatter3, bg_guess_scatter1, bg_guess_scatter2, bg_guess_scatter, bg_guess_scatter4])\n labels_y = [\"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", r'$\\mathrm{\\sigma[N_{bg} - N_{bg}^{true}]}$']\n plot_many_graphs(x_data, y_data, labels_x, labels_y, labels_plots, symbols, meth[j].upper() + \" method\", meth[j] + \"_comp_bg_scat.pdf\")\n\n scale_scatter, ell_scatter, PA_scatter, bg_scatter = [], [], [], []\n scale_scatter1, ell_scatter1, PA_scatter1, bg_scatter1 = [], [], [], []\n scale_scatter2, ell_scatter2, PA_scatter2, bg_scatter2 = [], [], [], []\n scale_scatter3, ell_scatter3, PA_scatter3, bg_scatter3 = [], [], [], []\n scale_scatter4, ell_scatter4, PA_scatter4, bg_scatter4 = [], [], [], []\n\n scale_guess_scatter, ell_guess_scatter, PA_guess_scatter, bg_guess_scatter = [], [], [], []\n scale_guess_scatter1, ell_guess_scatter1, PA_guess_scatter1, bg_guess_scatter1 = [], [], [], []\n scale_guess_scatter2, ell_guess_scatter2, PA_guess_scatter2, bg_guess_scatter2 = [], [], [], []\n scale_guess_scatter3, ell_guess_scatter3, PA_guess_scatter3, bg_guess_scatter3 = [], [], [], []\n scale_guess_scatter4, ell_guess_scatter4, PA_guess_scatter4, bg_guess_scatter4 = [], [], [], []\n\n galaxies = []\n\nprint(\"Time taken : \" + str(time.clock() - start) + \" s\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ouputs/analyse/old_MocksEm/comp_scatter.py","file_name":"comp_scatter.py","file_ext":"py","file_size_in_byte":15874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"648387684","text":"from abc import ABCMeta, abstractmethod\nimport asyncio\nimport csv\nimport datetime\nfrom distutils.util import strtobool # pylint: disable=import-error, no-name-in-module\nfrom json import JSONDecodeError\nimport re\nfrom io import TextIOWrapper, BytesIO\nimport aiohttp\nimport yarl\n\nfrom .hawk import (\n get_hawk_header,\n)\nfrom .http import (\n http_make_request,\n)\nfrom .logger import (\n logged,\n)\nfrom .metrics import (\n metric_timer,\n)\nfrom .utils import (\n json_loads,\n sub_dict_lower,\n)\nfrom .utils import (\n sleep,\n)\n\n\ndef parse_feed_config(feed_config):\n by_feed_type = {\n 'activity_stream': ActivityStreamFeed,\n 'zendesk': ZendeskFeed,\n 'maxemail': MaxemailFeed,\n 'aventri': EventFeed,\n }\n return by_feed_type[feed_config['TYPE']].parse_config(feed_config)\n\n\nclass Feed(metaclass=ABCMeta):\n \"\"\"\n Abstract base class for all feeds with default functionality defined\n \"\"\"\n down_grace_period = 60 * 60 * 48\n\n full_ingest_page_interval = 0.25\n full_ingest_interval = 120\n updates_page_interval = 1\n exception_intervals = [1, 2, 4, 8, 16, 32, 64]\n\n disable_updates = False # this is to disable updates feed, if necessary\n\n @classmethod\n @abstractmethod\n def parse_config(cls, config):\n pass\n\n @staticmethod\n def next_href(feed):\n return feed.get('next', None)\n\n @abstractmethod\n async def auth_headers(self, context, url):\n pass\n\n @classmethod\n @abstractmethod\n async def get_activities(cls, context, feed):\n pass\n\n @classmethod\n async def pages(cls, context, feed, href, ingest_type):\n \"\"\"\n async generator yielding 200 records at a time\n \"\"\"\n logger = context.logger\n\n async def fetch_page(context, href, headers):\n \"\"\"Fetch a single page of data from a feed, returning it as bytes\n\n If a non-200 response is returned, an exception is raised. However, if a\n 429 is returned with a Retry-After header, the fetch is retried after this\n time, up to 10 attempts. After 10 failed attempts, an exception is\n raised.\n\n Raised exceptions are expected to cause the current ingest cycle to fail,\n but be re-attempted some time later.\n \"\"\"\n num_attempts = 0\n max_attempts = 10\n\n while True:\n num_attempts += 1\n try:\n result = await http_make_request(\n context.session, context.metrics, 'GET', href, data=b'', headers=headers)\n result.raise_for_status()\n return result._body\n except aiohttp.ClientResponseError as client_error:\n if (num_attempts >= max_attempts or client_error.status != 429 or\n 'Retry-After' not in client_error.headers):\n raise\n logger.debug(\n 'HTTP 429 received at attempt (%s). Will retry after (%s) seconds',\n num_attempts,\n client_error.headers['Retry-After'],\n )\n await sleep(context, int(client_error.headers['Retry-After']))\n\n async def gen_source_pages(href):\n updates_href = href\n while updates_href:\n # Lock so there is only 1 request per feed at any given time\n async with feed.lock:\n with \\\n logged(logger.info, logger.warning, 'Polling page (%s)',\n [updates_href]), \\\n metric_timer(context.metrics['ingest_page_duration_seconds'],\n [feed.unique_id, ingest_type, 'pull']):\n feed_contents = await fetch_page(\n context, updates_href, await feed.auth_headers(context, updates_href),\n )\n\n with logged(logger.debug, logger.warning, 'Parsing JSON', []):\n feed_parsed = json_loads(feed_contents)\n\n with logged(logger.debug, logger.warning, 'Convert to activities', []):\n activities = await feed.get_activities(context, feed_parsed)\n\n yield activities, updates_href\n updates_href = feed.next_href(feed_parsed)\n\n async def gen_evenly_sized_pages(source_pages):\n # pylint: disable=undefined-loop-variable\n page_size = 200\n current = []\n async for activities, updates_href in source_pages:\n current.extend(activities)\n\n while len(current) >= page_size:\n to_yield, current = current[:page_size], current[page_size:]\n yield to_yield, updates_href\n\n if current:\n yield current, updates_href\n\n source_pages = gen_source_pages(href)\n evenly_sized_pages = gen_evenly_sized_pages(source_pages)\n\n # Would be nicer if could \"yield from\", but there is no\n # language support for doing that in async generator\n async for page, updates_href in evenly_sized_pages:\n yield page, updates_href\n\n\nclass ActivityStreamFeed(Feed):\n\n @classmethod\n def parse_config(cls, config):\n return cls(**sub_dict_lower(config,\n ['UNIQUE_ID', 'SEED', 'ACCESS_KEY_ID', 'SECRET_ACCESS_KEY']))\n\n def __init__(self, unique_id, seed, access_key_id, secret_access_key):\n self.lock = asyncio.Lock()\n self.unique_id = unique_id\n self.seed = seed\n self.access_key_id = access_key_id\n self.secret_access_key = secret_access_key\n\n @classmethod\n async def get_activities(cls, _, feed):\n return feed['orderedItems']\n\n async def auth_headers(self, _, url):\n parsed_url = yarl.URL(url)\n return {\n 'Authorization': get_hawk_header(\n access_key_id=self.access_key_id,\n secret_access_key=self.secret_access_key,\n method='GET',\n host=parsed_url.host,\n port=str(parsed_url.port),\n path=parsed_url.raw_path_qs,\n content_type=b'',\n content=b'',\n )\n }\n\n\nclass ZendeskFeed(Feed):\n down_grace_period = 400\n\n # The staging API is severely rate limited\n # Could be higher on prod, but KISS\n full_ingest_page_interval = 30\n updates_page_interval = 120\n exception_intervals = [120, 180, 240, 300]\n\n company_number_regex = r'Company number:\\s*(\\d+)'\n\n @classmethod\n def parse_config(cls, config):\n return cls(**sub_dict_lower(config, ['UNIQUE_ID', 'SEED', 'API_EMAIL', 'API_KEY']))\n\n def __init__(self, unique_id, seed, api_email, api_key):\n self.lock = asyncio.Lock()\n self.unique_id = unique_id\n self.seed = seed\n self.api_email = api_email\n self.api_key = api_key\n\n @staticmethod\n def next_href(feed):\n return feed['next_page']\n\n async def auth_headers(self, _, __):\n return {\n 'Authorization': aiohttp.helpers.BasicAuth(\n login=self.api_email + '/token',\n password=self.api_key,\n ).encode()\n }\n\n @classmethod\n async def get_activities(cls, _, feed):\n def company_numbers(description):\n match = re.search(cls.company_number_regex, description)\n return [match[1]] if match else []\n\n return [\n {\n 'id': 'dit:zendesk:Ticket:' + str(ticket['id']) + ':Create',\n 'type': 'Create',\n 'published': ticket['created_at'],\n 'dit:application': 'zendesk',\n 'actor': {\n 'type': [\n 'Organization',\n 'dit:company',\n ],\n 'dit:companiesHouseNumber': company_number,\n },\n 'object': {\n 'type': [\n 'Document',\n 'dit:zendesk:Ticket',\n ],\n 'id': 'dit:zendesk:Ticket:' + str(ticket['id']),\n },\n }\n for ticket in feed['tickets']\n for company_number in company_numbers(ticket['description'])\n ]\n\n\nclass EventFeed(Feed):\n\n down_grace_period = 60 * 60 * 24 * 3 # Full ingest takes ~2 days, if nothing after 3, alert\n full_ingest_page_interval = 0 # There are sleeps in tht HTTP requests in this class\n full_ingest_interval = 60 * 60\n\n updates_page_interval = 60 * 60 * 24 * 30\n exception_intervals = [120, 180, 240, 300]\n\n # This is quite small so even when we have a lot of sleeps, we still have signs that the\n # feed is working in Grafana\n ingest_page_size = 20\n\n disable_updates = True\n\n @classmethod\n def parse_config(cls, config):\n return cls(\n **sub_dict_lower(\n config, ['UNIQUE_ID', 'SEED', 'ACCOUNT_ID', 'API_KEY', 'AUTH_URL',\n 'ATTENDEES_LIST_URL', 'EVENT_QUESTIONS_LIST_URL', 'SESSIONS_LIST_URL',\n 'SESSION_REGISTRATIONS_LIST_URL']))\n\n def __init__(self, unique_id, seed, account_id, api_key, auth_url, attendees_list_url,\n event_questions_list_url, sessions_list_url, session_registrations_list_url):\n self.lock = asyncio.Lock()\n self.unique_id = unique_id\n self.seed = seed\n self.account_id = account_id\n self.api_key = api_key\n self.auth_url = auth_url\n self.attendees_list_url = attendees_list_url\n self.event_questions_list_url = event_questions_list_url\n self.sessions_list_url = sessions_list_url\n self.session_registrations_list_url = session_registrations_list_url\n self.accesstoken = None\n\n @staticmethod\n def next_href(_):\n \"\"\" aventri API does not support pagination\n returns (None)\n \"\"\"\n return None\n\n async def auth_headers(self, _, __):\n return {}\n\n async def generate_access_token(self, context):\n context.logger.info('Making aventri auth request to %s', self.auth_url)\n result = await http_make_request(\n context.session, context.metrics, 'GET', self.auth_url,\n data=b'',\n params=(\n ('accountid', str(self.account_id)),\n ('key', str(self.api_key)),\n ),\n headers={},\n )\n result.raise_for_status()\n accesstoken = str(json_loads(result._body)['accesstoken'])\n context.logger.info('fresh access token %s', accesstoken)\n return accesstoken\n\n async def http_make_auth_request(self, context, method, url, data, params=()):\n # Aventri DS APIs tokens have short expiry\n num_attempts = 0\n max_attempts = 5\n while True:\n try:\n num_attempts += 1\n if self.accesstoken is None:\n self.accesstoken = await self.generate_access_token(context)\n params_auth = params + (('accesstoken', str(self.accesstoken)),)\n context.logger.info('Making aventri request to %s with params %s', url, params)\n result = await http_make_request(\n context.session, context.metrics, method, url,\n data=data, headers={}, params=params_auth,\n )\n error_status = json_loads(result._body).get('status', None)\n error_msg = json_loads(result._body).get('msg', None)\n if error_status == 'error' and error_msg.startswith('Not authorized to access'):\n raise aiohttp.ClientResponseError(\n result.request_info, result.history, status=403)\n except (aiohttp.ClientResponseError, JSONDecodeError):\n if num_attempts < max_attempts:\n self.accesstoken = None\n continue\n return result\n\n async def http_make_aventri_request(\n self, context, method, url, data, sleep_interval=0.5, params=()):\n logger = context.logger\n\n num_attempts = 0\n max_attempts = 10\n retry_interval = 30\n\n while True:\n num_attempts += 1\n retry_interval += 60\n try:\n result = await self.http_make_auth_request(context, method, url, data, params)\n result.raise_for_status()\n\n if sleep_interval:\n await sleep(context, sleep_interval)\n results = json_loads(result._body).get('ResultSet', [])\n return results\n except aiohttp.ClientResponseError as client_error:\n if (num_attempts >= max_attempts or client_error.status not in [\n 429, 502, 504,\n ]):\n raise\n logger.debug(\n 'aventri: HTTP %s received at attempt (%s). Will retry after (%s) seconds',\n client_error.status,\n num_attempts,\n retry_interval,\n )\n context.raven_client.captureMessage(\n f'aventri: HTTP {client_error.status} received at attempt ({num_attempts}).'\n f'Will retry after ({retry_interval}) seconds',\n )\n await sleep(context, retry_interval)\n except JSONDecodeError:\n if num_attempts >= max_attempts:\n logger.debug(\n 'aventri: JSONDecodeError at attempt (%s). Will retry after (%s) seconds',\n num_attempts,\n retry_interval,\n )\n await sleep(context, retry_interval)\n\n async def pages(self, context, feed, href, ingest_type):\n # pylint: disable=too-many-statements\n logger = context.logger\n\n async def gen_activities(href):\n with \\\n logged(logger.info, logger.warning, 'Polling page (%s)',\n [href]), \\\n metric_timer(context.metrics['ingest_page_duration_seconds'],\n [feed.unique_id, ingest_type, 'pull']):\n\n async for event in gen_events():\n yield self.map_to_event_activity(event)\n\n async for attendee in gen_attendees(event):\n yield self.map_to_attendee_activity(attendee, event)\n\n async for session in gen_sessions(event):\n yield self.map_to_session_activity(session, event)\n\n async for registration in gen_registrations(event):\n yield self.map_to_registration_activity(registration, event)\n\n async def gen_event_questions(event_id):\n response = await self.http_make_aventri_request(\n context,\n 'GET',\n self.event_questions_list_url.format(event_id=event_id),\n data=b'',\n )\n return [question['ds_fieldname'] for question in response.values()]\n\n async def gen_events():\n next_page = 1\n # default is 1024, but keep it low as it becomes slow\n page_size = 200\n while True:\n params = (\n ('pageNumber', str(next_page)),\n ('pageSize', str(page_size)),\n )\n\n page_of_events = await self.http_make_aventri_request(\n context, 'GET', self.seed, data=b'', params=params,\n )\n for event in page_of_events:\n\n event['questions'] = None\n # If events are deleted, a request for questions returns a 500\n # But also, some other non-deleted events fail as well, ones\n # that have many null values. We arbitrarily choose url as the\n # sensor for this state\n event['questions'] = \\\n await gen_event_questions(event['eventid']) \\\n if event['event_deleted'] == '0' and event['url'] is not None else None\n yield event\n\n if len(page_of_events) != page_size:\n break\n\n next_page += 1\n\n async def gen_attendees(event):\n logger = context.logger\n url = self.attendees_list_url.format(event_id=event['eventid'])\n\n next_page = 1\n # Be careful of bigger: sometimes is very slow\n page_size = 200\n while True:\n params = (\n ('pageNumber', str(next_page)),\n ('pageSize', str(page_size)),\n )\n with logged(logger.debug, logger.warning, 'Fetching attendee list', []):\n attendees = await self.http_make_aventri_request(\n context, 'GET', url, data=b'', params=params,\n )\n for attendee in attendees:\n yield attendee\n\n if len(attendees) != page_size:\n break\n\n next_page += 1\n\n async def gen_sessions(event):\n logger = context.logger\n url = self.sessions_list_url.format(event_id=event['eventid'])\n\n next_page = 1\n # Be careful of bigger: sometimes is very slow\n page_size = 200\n while True:\n params = (\n ('pageNumber', str(next_page)),\n ('pageSize', str(page_size)),\n )\n with logged(logger.debug, logger.warning, 'Fetching sessions list', []):\n sessions = await self.http_make_aventri_request(\n context, 'GET', url, data=b'', params=params,\n )\n for session in sessions:\n yield session\n\n if len(sessions) != page_size:\n break\n\n next_page += 1\n\n async def gen_registrations(event):\n logger = context.logger\n url = self.session_registrations_list_url.format(event_id=event['eventid'])\n\n next_page = 1\n # Be careful of bigger: sometimes is very slow\n page_size = 200\n while True:\n params = (\n ('pageNumber', str(next_page)),\n ('pageSize', str(page_size)),\n )\n with logged(logger.debug, logger.warning, 'Fetching sessions list', []):\n sessions = await self.http_make_aventri_request(\n context, 'GET', url, data=b'', params=params,\n )\n for session in sessions:\n yield session\n\n if len(sessions) != page_size:\n break\n\n next_page += 1\n\n async def paginate(items):\n # pylint: disable=undefined-loop-variable\n page_size = self.ingest_page_size\n current = []\n async for item in items:\n current.append(item)\n\n while len(current) >= page_size:\n to_yield, current = current[:page_size], current[page_size:]\n yield to_yield\n\n if current:\n yield current\n\n activities = gen_activities(href)\n pages = paginate(activities)\n\n async for page in pages:\n yield page, href\n\n def map_to_event_activity(self, event):\n event_id = event['eventid']\n folder_name = event['folderpath'].split('/')[-1]\n published = self.format_datetime(event['event_created'])\n\n return {\n 'id': 'dit:aventri:Event:' + event_id + ':Create',\n 'published': published,\n 'type': 'dit:aventri:Event',\n 'dit:application': 'aventri',\n 'object': {\n 'id': 'dit:aventri:Event:' + event_id,\n 'name': event['eventname'],\n 'published': published,\n 'updated': self.format_datetime(event['event_lastmodified']),\n # The following mappings are used to allow great.gov.uk\n # search to filter on events.\n 'attributedTo': {\n 'type': 'dit:aventri:Folder',\n 'id': f'dit:aventri:Folder:{folder_name}'\n },\n 'content': event['event_description'],\n 'dit:public': bool(strtobool(event['include_calendar'])),\n 'dit:status': event['eventstatus'],\n 'endTime': self.format_date_and_time(\n event['enddate'], event['endtime'],\n ),\n 'startTime': self.format_date_and_time(\n event['startdate'], event['starttime'],\n ),\n 'type': ['dit:aventri:Event'] + (\n ['Tombstone'] if event['event_deleted'] == '1' else []\n ),\n 'url': event['url'],\n 'dit:aventri:approval_required': event['approval_required'],\n 'dit:aventri:approval_status': event['approval_status'],\n 'dit:aventri:city': event['event_city'],\n 'dit:aventri:clientcontact': event['clientcontact'],\n 'dit:aventri:closedate': self.format_date_and_time(\n event['closedate'], event['closetime'],\n ),\n 'dit:aventri:code': event['code'],\n 'dit:aventri:contactinfo': event['contactinfo'],\n 'dit:aventri:country': event['event_country'],\n 'dit:aventri:createdby': event['createdby'],\n 'dit:aventri:defaultlanguage': event['defaultlanguage'],\n 'dit:aventri:folderid': event['folderid'],\n 'dit:aventri:live_date': self.format_date(event['live_date']),\n 'dit:aventri:location_address1': event['event_loc_addr1'],\n 'dit:aventri:location_address2': event['event_loc_addr2'],\n 'dit:aventri:location_address3': event['event_loc_addr3'],\n 'dit:aventri:location_city': event['event_loc_city'],\n 'dit:aventri:location_country': event['event_loc_country'],\n 'dit:aventri:location_name': event['event_loc_name'],\n 'dit:aventri:location_postcode': event['event_loc_postcode'],\n 'dit:aventri:location_state': event['event_loc_state'],\n 'dit:aventri:locationname': event['locationname'],\n 'dit:aventri:max_reg': event['max_reg'],\n 'dit:aventri:modifiedby': event['modifiedby'],\n 'dit:aventri:modifieddatetime': self.format_datetime(event['event_lastmodified']),\n 'dit:aventri:price_type': event['price_type'],\n 'dit:aventri:standardcurrency': event['standardcurrency'],\n 'dit:aventri:state': event['event_state'],\n 'dit:aventri:timezone': event['timezone_name'],\n }\n }\n\n def map_to_attendee_activity(self, attendee, event):\n event_id = event['eventid']\n attendee_id = attendee['attendeeid']\n return {\n 'id': 'dit:aventri:Event:' + event_id + ':Attendee:' + attendee_id + ':Create',\n 'published': self.format_datetime(attendee['created']),\n 'type': 'dit:aventri:Attendee',\n 'dit:application': 'aventri',\n 'object': {\n 'attributedTo': {\n 'type': 'dit:aventri:Event',\n 'id': f'dit:aventri:Event:{event_id}'\n },\n 'id': 'dit:aventri:Attendee:' + attendee_id,\n 'published': self.format_datetime(attendee['created']),\n 'type': ['dit:aventri:Attendee'],\n 'dit:aventri:approvalstatus': attendee['approval_status'],\n 'dit:aventri:category': attendee['category_shortname'],\n 'dit:aventri:createdby': attendee['createdby'],\n 'dit:aventri:language': attendee['language'],\n 'dit:aventri:lastmodified': self.format_datetime(attendee['lastmodified']),\n 'dit:aventri:modifiedby': attendee['modifiedby'],\n 'dit:aventri:registrationstatus': attendee['registrationstatus'],\n 'dit:aventri:email': attendee['email'],\n 'dit:aventri:firstname': attendee['fname'],\n 'dit:aventri:lastname': attendee['lname'],\n 'dit:aventri:companyname': attendee.get('company', None),\n 'dit:aventri:virtualeventattendance': attendee['virtual_event_attendance'],\n 'dit:aventri:lastlobbylogin': self.format_datetime(\n attendee.get('last_lobby_login', None)\n ),\n 'dit:aventri:attendeeQuestions': {\n question: attendee.get(question)\n for question in event['questions']\n } if event['questions'] is not None else None,\n # although dups, below fields are used by datahub crm\n 'dit:emailAddress': attendee['email'],\n 'dit:firstName': attendee['fname'],\n 'dit:lastName': attendee['lname'],\n 'dit:registrationStatus': attendee['registrationstatus'],\n 'dit:companyName': attendee['company']\n }\n }\n\n def map_to_session_activity(self, session, event):\n event_id = event['eventid']\n session_id = session['sessionid']\n published = self.format_datetime(event['event_created'])\n return {\n 'id': 'dit:aventri:Event:' + event_id + ':Session:' + session_id + ':Create',\n 'published': published,\n 'type': 'dit:aventri:Session',\n 'dit:application': 'aventri',\n 'object': {\n 'attributedTo': {\n 'type': 'dit:aventri:Event',\n 'id': f'dit:aventri:Event:{event_id}'\n },\n 'id': 'dit:aventri:Session:' + session_id,\n 'published': published,\n 'type': ['dit:aventri:Session'],\n 'dit:aventri:starttime': session['starttime'],\n 'dit:aventri:endtime': session['endtime'],\n 'dit:aventri:name': session['name'],\n 'dit:aventri:desc': session['desc'],\n }\n }\n\n def map_to_registration_activity(self, registration, event):\n event_id = event['eventid']\n session_id = registration['sessionid']\n attendee_id = registration['attendeeid']\n published = self.format_datetime(event['event_created'])\n as_id = ':Session:' + session_id + ':Attendee:' + attendee_id\n return {\n 'id': 'dit:aventri:Event:' + event_id + as_id + ':Create',\n 'published': published,\n 'type': 'dit:aventri:SessionRegistration',\n 'dit:application': 'aventri',\n 'object': {\n 'attributedTo': {\n 'type': 'dit:aventri:Event',\n 'id': f'dit:aventri:Event:{event_id}'\n },\n 'id': 'dit:aventri:Session:' + session_id + ':Attendee:' + attendee_id,\n 'published': published,\n 'type': ['dit:aventri:SessionRegistration'],\n 'dit:aventri:session_id': session_id,\n 'dit:aventri:attendee_id': attendee_id,\n 'dit:aventri:lastmodified': self.format_datetime(registration['lastmodified']),\n 'dit:aventri:registration_status': registration['registration_status'],\n }\n }\n\n @staticmethod\n def format_datetime(aventri_datetime):\n return \\\n None if (aventri_datetime is None or aventri_datetime == '0000-00-00 00:00:00') else \\\n datetime.datetime.strptime(aventri_datetime, '%Y-%m-%d %H:%M:%S').isoformat()\n\n @staticmethod\n def format_date_and_time(aventri_date, aventri_time):\n checked_date = aventri_date if aventri_date else '0000-00-00'\n checked_time = aventri_time if aventri_time else '00:00:00'\n if checked_date == '0000-00-00':\n return None\n\n return datetime.datetime.strptime(\n f'{checked_date} {checked_time}',\n '%Y-%m-%d %H:%M:%S'\n ).isoformat()\n\n @staticmethod\n def format_date(aventri_datetime):\n return \\\n None if (aventri_datetime is None or aventri_datetime == '0000-00-00') else \\\n datetime.datetime.strptime(aventri_datetime, '%Y-%m-%d').isoformat()\n\n @classmethod\n async def get_activities(cls, _, feed):\n pass\n\n\nclass MaxemailFeed(Feed):\n\n down_grace_period = 60 * 60 * 4\n\n full_ingest_page_interval = 0.1\n updates_page_interval = 60 * 60 * 24 * 30\n exception_intervals = [120, 180, 240, 300]\n\n @classmethod\n def parse_config(cls, config):\n return cls(**sub_dict_lower(\n config,\n [\n 'UNIQUE_ID',\n 'SEED',\n 'DATA_EXPORT_URL',\n 'CAMPAIGN_URL',\n 'USERNAME',\n 'PASSWORD',\n 'PAGE_SIZE'\n ]\n ))\n\n def __init__(self, unique_id, seed, data_export_url,\n campaign_url, username, password, page_size):\n self.lock = asyncio.Lock()\n self.unique_id = unique_id\n self.seed = seed\n self.data_export_url = data_export_url\n self.campaign_url = campaign_url\n self.username = username\n self.password = password\n self.page_size = int(page_size)\n\n @staticmethod\n def next_href(_):\n \"\"\"\n Maxemail API does not support GET requests with next href for pagination\n returns (None)\n \"\"\"\n return None\n\n async def auth_headers(self, _, __):\n return {\n 'Authorization': aiohttp.helpers.BasicAuth(\n login=self.username,\n password=self.password,\n ).encode()\n }\n\n async def get_activities(self, context, feed):\n return None\n\n @classmethod\n async def pages(cls, context, feed, href, ingest_type):\n \"\"\"\n async generator for Maxemail email campaign sent records\n \"\"\"\n # pylint: disable=too-many-statements\n timestamp = href\n logger = context.logger\n campaigns = {}\n now = datetime.datetime.now()\n one_month_ago = (now - datetime.timedelta(days=31)).strftime('%Y-%m-%d 00:00:00')\n if ingest_type == 'full':\n timestamp = one_month_ago\n\n async def get_email_campaign(email_campaign_id):\n if email_campaign_id not in campaigns:\n campaigns[email_campaign_id] = await fetch_email_campaign_from_maxemail(\n email_campaign_id\n )\n return campaigns[email_campaign_id]\n\n async def fetch_email_campaign_from_maxemail(email_campaign_id):\n \"\"\"\n Retrieves email campaign data for the given id\n url: root/api/json/email_campaign\n method': 'find'\n param: 'emailId'\n \"\"\"\n url = feed.campaign_url\n payload = {'method': 'find', 'emailId': email_campaign_id}\n\n for _ in range(0, 5):\n try:\n with logged(context.logger.debug, context.logger.warning,\n 'maxemail Fetching campaign (%s) with payload (%s)',\n [url, payload]):\n result = await http_make_request(\n context.single_use_session,\n context.metrics,\n 'POST',\n url,\n data=payload,\n headers=await feed.auth_headers(None, None),\n )\n result.raise_for_status()\n except (asyncio.TimeoutError, aiohttp.ClientPayloadError):\n await asyncio.sleep(10)\n else:\n break\n if result.status != 200:\n raise Exception(\n f'Failed fetching maxemail campain {url} with payload {payload}')\n campaign = json_loads(result._body)\n year, time = campaign['start_ts'].split(' ')\n timestamp = f'{year}T{time}'\n return {\n 'type': 'dit:maxemail:Campaign',\n 'id': 'dit:maxemail:Campaign:' + email_campaign_id,\n 'name': campaign['name'],\n 'content': campaign['description'],\n 'dit:emailSubject': campaign['subject_line'],\n 'dit:maxemail:Campaign:id': int(email_campaign_id),\n 'published': timestamp\n }, {\n 'type': ['Organization', 'dit:maxemail:Sender'],\n 'id': 'dit:maxemail:Sender:' + campaign['from_address'],\n 'name': campaign['from_address_alias'],\n 'dit:emailAddress': campaign['from_address'],\n }\n\n async def get_data_export_key(timestamp, method):\n \"\"\"\n url: root/api/json/data_export_quick\n\n sample payload {'method': 'sent', 'filter': '{\"timestamp\": \"2020-09-10 17:00:00\"}'}\n \"\"\"\n payload_filter = '{\"timestamp\": \"' + timestamp + '\"}'\n payload = {\n 'method': method,\n 'filter': payload_filter\n }\n\n url = feed.seed\n num_attempts = 0\n max_attempts = 10\n\n while True:\n num_attempts += 1\n try:\n with logged(context.logger.info, context.logger.warning,\n 'maxemail export key (%s) with payload (%s)', [url, payload]):\n result = await http_make_request(\n context.single_use_session,\n context.metrics,\n 'POST',\n url,\n data=payload,\n headers=await feed.auth_headers(None, None),\n )\n key = str(await result.text()).strip('\\\"')\n return key\n except aiohttp.ClientResponseError as client_error:\n if (num_attempts >= max_attempts or client_error.status != 429 or\n 'Retry-After' not in client_error.headers):\n raise\n logger.debug(\n 'HTTP 429 received at attempt (%s). Will retry after (%s) seconds',\n num_attempts,\n client_error.headers['Retry-After'],\n )\n await sleep(context, int(client_error.headers['Retry-After']))\n\n async def gen_data_export_csv(key):\n \"\"\"\n url: root/file/key/{key}\n \"\"\"\n url = feed.data_export_url.format(key=key)\n with logged(context.logger.debug, context.logger.warning,\n 'maxemail data export csv (%s)', [url]):\n\n lines_iter = TextIOWrapper(BytesIO((await http_make_request(\n context.single_use_session,\n context.metrics,\n 'POST',\n url,\n data={},\n headers=await feed.auth_headers(None, None),\n ))._body), encoding='utf-8', newline='')\n\n for row in csv.DictReader(lines_iter, skipinitialspace=True, delimiter=',',\n quotechar='\"', quoting=csv.QUOTE_ALL):\n yield row\n\n def common(campaign_id, timestamp, email_address):\n year, time = timestamp.split(' ')\n timestamp = f'{year}T{time}'\n line_id = f'{campaign_id}:{timestamp}:{email_address}'\n return line_id, timestamp\n\n async def gen_sent_activities_and_timestamp(csv_lines):\n async for line in csv_lines:\n line_id, timestamp = common(line['email id'], line['sent timestamp'],\n line['email address'])\n activity = {\n 'id': 'dit:maxemail:Email:Sent:' + line_id + ':Create',\n 'type': 'Create',\n 'dit:application': 'maxemail',\n 'published': timestamp,\n 'object': {\n 'type': ['dit:maxemail:Email', 'dit:maxemail:Email:Sent'],\n 'id': 'dit:maxemail:Email:Sent:' + line_id,\n 'dit:emailAddress': line['email address'],\n 'attributedTo': (await get_email_campaign(line['email id']))[0]\n }\n }\n yield activity, timestamp\n\n async def gen_bounced_activities_and_timestamp(csv_lines):\n async for line in csv_lines:\n line_id, timestamp = common(line['email id'],\n line['bounce timestamp'], line['email address'])\n activity = {\n 'id': 'dit:maxemail:Email:Bounced:' + line_id + ':Create',\n 'type': 'Create',\n 'dit:application': 'maxemail',\n 'published': timestamp,\n 'object': {\n 'type': ['dit:maxemail:Email', 'dit:maxemail:Email:Bounced'],\n 'id': 'dit:maxemail:Email:Bounced:' + line_id,\n 'dit:emailAddress': line['email address'],\n 'content': line['bounce reason'],\n 'attributedTo': (await get_email_campaign(line['email id']))[0]\n }\n }\n yield activity, timestamp\n\n async def gen_opened_activities_and_timestamp(csv_lines):\n async for line in csv_lines:\n line_id, timestamp = common(line['email id'],\n line['open timestamp'], line['email address'])\n activity = {\n 'id': 'dit:maxemail:Email:Opened:' + line_id + ':Create',\n 'type': 'Create',\n 'dit:application': 'maxemail',\n 'published': timestamp,\n 'object': {\n 'type': ['dit:maxemail:Email', 'dit:maxemail:Email:Opened'],\n 'id': 'dit:maxemail:Email:Opened:' + line_id,\n 'dit:emailAddress': line['email address'],\n 'attributedTo': (await get_email_campaign(line['email id']))[0]\n }\n }\n yield activity, timestamp\n\n async def gen_clicked_activities_and_timestamp(csv_lines):\n async for line in csv_lines:\n line_id, timestamp = common(line['email id'], line['click timestamp'],\n line['email address'])\n activity = {\n 'id': 'dit:maxemail:Email:Clicked:' + line_id + ':Create',\n 'type': 'Create',\n 'dit:application': 'maxemail',\n 'published': timestamp,\n 'object': {\n 'type': ['dit:maxemail:Email', 'dit:maxemail:Email:Clicked'],\n 'id': 'dit:maxemail:Email:Clicked:' + line_id,\n 'dit:emailAddress': line['email address'],\n 'url': line['url'],\n 'attributedTo': (await get_email_campaign(line['email id']))[0]\n }\n }\n yield activity, timestamp\n\n async def gen_responded_activities_and_timestamp(csv_lines):\n async for line in csv_lines:\n # The column _is_ called \"click timestamp\" for responded\n line_id, timestamp = common(line['email id'], line['click timestamp'],\n line['email address'])\n activity = {\n 'id': 'dit:maxemail:Email:Responded:' + line_id + ':Create',\n 'type': 'Create',\n 'dit:application': 'maxemail',\n 'published': timestamp,\n 'object': {\n 'type': ['dit:maxemail:Email', 'dit:maxemail:Email:Responded'],\n 'id': 'dit:maxemail:Email:Responded:' + line_id,\n 'dit:emailAddress': line['email address'],\n 'attributedTo': (await get_email_campaign(line['email id']))[0]\n }\n }\n yield activity, timestamp\n\n async def gen_unsubscribed_activities_and_timestamp(csv_lines):\n async for line in csv_lines:\n line_id, timestamp = common(line['email id'], line['unsubscribe timestamp'],\n line['email address'])\n activity = {\n 'id': 'dit:maxemail:Email:Unsubscribed:' + line_id + ':Create',\n 'type': 'Create',\n 'dit:application': 'maxemail',\n 'published': timestamp,\n 'object': {\n 'type': ['dit:maxemail:Email', 'dit:maxemail:Email:Unsubscribed'],\n 'id': 'dit:maxemail:Email:Unsubscribed:' + line_id,\n 'dit:emailAddress': line['email address'],\n 'attributedTo': (await get_email_campaign(line['email id']))[0]\n }\n }\n yield activity, timestamp\n\n async def gen_campains_activities_and_timestamp(campaigns, timestamp):\n for campaign_obj, campaign_sender in campaigns.values():\n yield {\n 'id': campaign_obj['id'] + ':Create',\n 'type': 'Create',\n 'dit:application': 'maxemail',\n 'published': campaign_obj['published'],\n 'object': campaign_obj,\n 'actor': campaign_sender\n }, timestamp\n\n async def paginate(page_size, objs):\n page = []\n timestamp = None\n async for obj, timestamp in objs:\n page.append(obj)\n if len(page) == page_size:\n yield page, timestamp\n page = []\n\n if page:\n yield page, timestamp\n\n def get_with_default(items, index, default):\n try:\n return items[index]\n except IndexError:\n return default\n\n timestamps = timestamp.split('--')\n timestamp_sent = get_with_default(timestamps, 0, one_month_ago)\n timestamp_bounced = get_with_default(timestamps, 1, timestamp_sent)\n timestamp_opened = get_with_default(timestamps, 2, timestamp_bounced)\n timestamp_clicked = get_with_default(timestamps, 3, timestamp_opened)\n timestamp_responded = get_with_default(timestamps, 4, timestamp_clicked)\n timestamp_unsubscribed = get_with_default(timestamps, 5, timestamp_responded)\n timestamps = [timestamp_sent, timestamp_bounced, timestamp_opened,\n timestamp_clicked, timestamp_responded, timestamp_unsubscribed]\n\n sent_data_export_key = await get_data_export_key(timestamp_sent, 'sent')\n sent_csv_lines = gen_data_export_csv(sent_data_export_key)\n sent_activities_and_timestamp = gen_sent_activities_and_timestamp(sent_csv_lines)\n\n async for activity_page, timestamp in paginate(feed.page_size,\n sent_activities_and_timestamp):\n timestamps[0] = timestamp\n yield activity_page, '--'.join(timestamps)\n\n bounced_data_export_key = await get_data_export_key(timestamp_bounced, 'bounced')\n bounced_csv_lines = gen_data_export_csv(bounced_data_export_key)\n bounced_activities_and_timestamp = gen_bounced_activities_and_timestamp(bounced_csv_lines)\n\n async for activity_page, timestamp in paginate(feed.page_size,\n bounced_activities_and_timestamp):\n timestamps[1] = timestamp\n yield activity_page, '--'.join(timestamps)\n\n opened_data_export_key = await get_data_export_key(timestamp_opened, 'opened')\n opened_csv_lines = gen_data_export_csv(opened_data_export_key)\n opened_activities_and_timestamp = gen_opened_activities_and_timestamp(opened_csv_lines)\n\n async for activity_page, timestamp in paginate(feed.page_size,\n opened_activities_and_timestamp):\n timestamps[2] = timestamp\n yield activity_page, '--'.join(timestamps)\n\n clicked_data_export_key = await get_data_export_key(timestamp_clicked, 'clicked')\n clicked_csv_lines = gen_data_export_csv(clicked_data_export_key)\n clicked_activities_and_timestamp = gen_clicked_activities_and_timestamp(clicked_csv_lines)\n\n async for activity_page, timestamp in paginate(feed.page_size,\n clicked_activities_and_timestamp):\n timestamps[3] = timestamp\n yield activity_page, '--'.join(timestamps)\n\n responded_data_export_key = await get_data_export_key(timestamp_clicked, 'responded')\n responded_csv_lines = gen_data_export_csv(responded_data_export_key)\n responded_activities_and_timestamp = gen_responded_activities_and_timestamp(\n responded_csv_lines)\n\n async for activity_page, timestamp in paginate(feed.page_size,\n responded_activities_and_timestamp):\n timestamps[4] = timestamp\n yield activity_page, '--'.join(timestamps)\n\n unsubscribed_data_export_key = await get_data_export_key(timestamp_unsubscribed,\n 'unsubscribed')\n unsubscribed_csv_lines = gen_data_export_csv(unsubscribed_data_export_key)\n unsubscribed_activities_and_timestamp = gen_unsubscribed_activities_and_timestamp(\n unsubscribed_csv_lines)\n\n async for activity_page, timestamp in paginate(feed.page_size,\n unsubscribed_activities_and_timestamp):\n timestamps[5] = timestamp\n yield activity_page, '--'.join(timestamps)\n\n campaigns_activities_and_timestamp = gen_campains_activities_and_timestamp(\n campaigns, '--'.join(timestamps))\n campaigns_activity_pages_and_timestamp = paginate(\n feed.page_size, campaigns_activities_and_timestamp)\n async for activity_page, timestamp in campaigns_activity_pages_and_timestamp:\n yield activity_page, timestamp\n","sub_path":"core/app/feeds.py","file_name":"feeds.py","file_ext":"py","file_size_in_byte":47490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"498828780","text":"from django.contrib.auth import get_user_model\nfrom rest_framework.test import APITestCase\nfrom cost.models import WageCost, Bearing, ProjectCost, Test, Certificate, CertificateCost, TestCost\nfrom cost.tests.factory import factories\n\nUser = get_user_model()\n\n\nclass FactoryTest(APITestCase):\n\n def test_create_wage_cost(self):\n wage = factories.WageCostFactory.create()\n wage_obj = WageCost.objects.last()\n self.assertEqual(wage.pk, wage_obj.pk)\n\n def test_create_bearing(self):\n bearing = factories.BearingFactory.create()\n bearing_obj = Bearing.objects.last()\n self.assertEqual(bearing.pk, bearing_obj.pk)\n\n def test_create_bearing_cost(self):\n bearing = factories.BearingCostFactory.create()\n bearing_obj = Bearing.objects.last()\n self.assertEqual(bearing.pk, bearing_obj.pk)\n\n def test_create_test(self):\n test = factories.TestFactory.create()\n test_obj = Test.objects.last()\n self.assertEqual(test.pk, test_obj.pk)\n\n def test_create_test_cost(self):\n test = factories.TestCostFactory.create()\n test_obj = TestCost.objects.last()\n self.assertEqual(test.pk, test_obj.pk)\n\n def test_create_certificate(self):\n cert = factories.CertificateFactory.create()\n cert_obj = Certificate.objects.last()\n self.assertEqual(cert.pk, cert_obj.pk)\n\n def test_create_certificate_cost(self):\n cert = factories.CertificateCostFactory.create()\n cert_obj = CertificateCost.objects.last()\n self.assertEqual(cert.pk, cert_obj.pk)\n\n def test_create_project_cost(self):\n pc = factories.ProjectCostFactory.create()\n pc_obj = ProjectCost.objects.last()\n self.assertEqual(pc.pk, pc_obj.pk)\n\n def test_wage_specific_user(self):\n user = User.objects.create(\n username='me',\n password='somepass'\n )\n wage = factories.WageCostFactory(owner=user)\n wage_obj = WageCost.objects.get(pk=wage.pk)\n\n self.assertEqual(wage_obj.owner.pk, user.pk)\n self.assertEqual(wage_obj.owner.username, user.username)\n","sub_path":"app/cost/tests/test_factories.py","file_name":"test_factories.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"30284130","text":"import numpy as np\n\ndef linearReg(total_E_in, total_E_out, datasize):\n #隨機生成訓練樣本,且排序\n x0 = np.ones(datasize)\n x1 = np.random.uniform(-1,1,datasize)\n x2 = np.random.uniform(-1,1,datasize)\n x = np.array([x0,x1,x2]).T\n #判斷是否在h=圓的範圍內,且隨機增加noise\n y = []\n for i in range(datasize):\n yi = np.sign(np.power(x1[i],2) + np.power(x2[i],2) - 0.6)\n if(np.random.random_sample() < 0.1):\n yi *= -1\n y.append(yi)\n y = np.array(y)\n #計算[1,x1,x2]的虛反\n x_pinv = np.linalg.pinv(x)\n w_lin = np.dot(x_pinv,y)\n #計算預測的y,且計算E_in\n y_hat = np.sign(np.dot(x, w_lin))\n err = 0\n for i in range(datasize):\n if(y[i] != y_hat[i]): err +=1\n #print(\"error rate:\",err/datasize)\n \n return err/datasize\n\ndef main():\n total_E_in = 0.0\n total_E_out = 0.0\n datasize = 1000\n times = 1000\n for i in range(times):\n print(i)\n Ein = linearReg(total_E_in, total_E_out, datasize)\n total_E_in += Ein\n #total_E_out += Eout\n print(\"avg_E_in:\",total_E_in/times)\n #print(\"avg_E_out:\",total_E_out/times)\n\nmain()","sub_path":"linearReg.py","file_name":"linearReg.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"215564435","text":"import datetime\nimport atexit\nimport signal\n\nfrom ..api import API\n\nfrom .bot_archive import BotArchive\nfrom .bot_block import BotBlock\nfrom .bot_comment import BotComment\nfrom .bot_delete import BotDelete\nfrom .bot_direct import BotDirect\nfrom .bot_filter import BotFilter\nfrom .bot_follow import BotFollow\nfrom .bot_get import BotGet\nfrom .bot_like import BotLike\nfrom .bot_photo import BotPhoto\nfrom .bot_stats import BotStats\nfrom .bot_support import BotSupport, check_if_file_exists, read_list_from_file\nfrom .bot_unfollow import BotUnfollow\nfrom .bot_unlike import BotUnlike\nfrom .bot_video import BotVideo\nfrom .bot_checkpoint import save_checkpoint, load_checkpoint\n\n\nclass Bot(API, BotArchive, BotBlock, BotComment, BotDelete,\n BotDirect, BotFilter, BotFollow, BotGet, BotLike,\n BotPhoto, BotStats, BotSupport, BotUnfollow, BotUnlike,\n BotVideo):\n\n def __init__(self,\n whitelist=False,\n blacklist=False,\n comments_file=False,\n proxy=None,\n max_likes_per_day=1000,\n max_unlikes_per_day=1000,\n max_follows_per_day=350,\n max_unfollows_per_day=350,\n max_comments_per_day=100,\n max_blocks_per_day=100,\n max_unblocks_per_day=100,\n max_likes_to_like=100,\n filter_users=True,\n max_followers_to_follow=2000,\n min_followers_to_follow=10,\n max_following_to_follow=2000,\n min_following_to_follow=10,\n max_followers_to_following_ratio=10,\n max_following_to_followers_ratio=2,\n min_media_count_to_follow=3,\n max_following_to_block=2000,\n like_delay=10,\n unlike_delay=10,\n follow_delay=30,\n unfollow_delay=30,\n comment_delay=60,\n block_delay=30,\n unblock_delay=30,\n stop_words=None):\n super(self.__class__, self).__init__()\n self.total_liked = 0\n self.total_unliked = 0\n self.total_followed = 0\n self.total_unfollowed = 0\n self.total_commented = 0\n self.total_blocked = 0\n self.total_unblocked = 0\n self.total_archived = 0\n self.total_unarchived = 0\n self.start_time = datetime.datetime.now()\n\n # the time.time() of the last action\n self.last_like = 0\n self.last_unlike = 0\n self.last_follow = 0\n self.last_unfollow = 0\n self.last_comment = 0\n self.last_block = 0\n self.last_unblock = 0\n\n # limits - follow\n self.filter_users = filter_users\n self.max_likes_per_day = max_likes_per_day\n self.max_unlikes_per_day = max_unlikes_per_day\n self.max_follows_per_day = max_follows_per_day\n self.max_unfollows_per_day = max_unfollows_per_day\n self.max_comments_per_day = max_comments_per_day\n self.max_blocks_per_day = max_blocks_per_day\n self.max_unblocks_per_day = max_unblocks_per_day\n self.max_likes_to_like = max_likes_to_like\n self.max_followers_to_follow = max_followers_to_follow\n self.min_followers_to_follow = min_followers_to_follow\n self.max_following_to_follow = max_following_to_follow\n self.min_following_to_follow = min_following_to_follow\n self.max_followers_to_following_ratio = max_followers_to_following_ratio\n self.max_following_to_followers_ratio = max_following_to_followers_ratio\n self.min_media_count_to_follow = min_media_count_to_follow\n self.stop_words = stop_words or ['shop', 'store', 'free']\n\n # limits - block\n self.max_following_to_block = max_following_to_block\n\n # delays\n self.like_delay = like_delay\n self.unlike_delay = unlike_delay\n self.follow_delay = follow_delay\n self.unfollow_delay = unfollow_delay\n self.comment_delay = comment_delay\n self.block_delay = block_delay\n self.unblock_delay = unblock_delay\n\n # current following\n self.following = []\n\n # proxy\n self.proxy = proxy\n\n # white and blacklists\n self.whitelist = []\n if whitelist:\n self.whitelist = read_list_from_file(whitelist)\n self.blacklist = []\n if blacklist:\n self.blacklist = read_list_from_file(blacklist)\n\n # comment file\n self.comments = []\n if comments_file:\n self.comments = read_list_from_file(comments_file)\n\n self.logger.info('Instabot Started')\n\n def version(self):\n try:\n from pip._vendor import pkg_resources\n except ImportError:\n import pkg_resources\n return next((p.version for p in pkg_resources.working_set if p.project_name.lower() == 'instabot'), \"No match\")\n\n def logout(self):\n save_checkpoint(self)\n super(Bot, self).logout()\n self.logger.info(\"Bot stopped. \"\n \"Worked: %s\" % (datetime.datetime.now() - self.start_time))\n self.print_counters()\n\n def login(self, **args):\n if self.proxy:\n args['proxy'] = self.proxy\n super(Bot, self).login(**args)\n self.prepare()\n signal.signal(signal.SIGTERM, self.logout)\n atexit.register(self.logout)\n\n def prepare(self):\n storage = load_checkpoint(self)\n if storage is not None:\n self.total_liked, self.total_unliked, self.total_followed, self.total_unfollowed, self.total_commented, self.total_blocked, self.total_unblocked, self.total_requests, self.start_time, self.total_archived, self.total_unarchived = storage\n if not self.whitelist:\n self.whitelist = self.check_whitelists()\n self.whitelist = list(\n filter(None, map(self.convert_to_user_id, self.whitelist)))\n self.blacklist = list(\n filter(None, map(self.convert_to_user_id, self.blacklist)))\n\n def print_counters(self):\n if self.total_liked:\n self.logger.info(\"Total liked: %d\" % self.total_liked)\n if self.total_unliked:\n self.logger.info(\"Total unliked: %d\" % self.total_unliked)\n if self.total_followed:\n self.logger.info(\"Total followed: %d\" % self.total_followed)\n if self.total_unfollowed:\n self.logger.info(\"Total unfollowed: %d\" % self.total_unfollowed)\n if self.total_commented:\n self.logger.info(\"Total commented: %d\" % self.total_commented)\n if self.total_blocked:\n self.logger.info(\"Total blocked: %d\" % self.total_blocked)\n if self.total_unblocked:\n self.logger.info(\"Total unblocked: %d\" % self.total_unblocked)\n if self.total_archived:\n self.logger.info(\"Total archived: %d\" % self.total_archived)\n if self.total_unarchived:\n self.logger.info(\"Total unarchived: %d\" % self.total_unarchived)\n self.logger.info(\"Total requests: %d\" % self.total_requests)\n\n # support\n\n def check_if_file_exists(self, file_path):\n return check_if_file_exists(file_path)\n\n def read_list_from_file(self, file_path):\n return read_list_from_file(file_path)\n","sub_path":"instabot/bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":7333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"500852347","text":"import cards\nimport pytest\nfrom cards import Card\n\n\n@pytest.fixture(scope=\"session\")\ndef tmp_db_path(tmp_path_factory):\n \"\"\"Path to temporary database\"\"\"\n return tmp_path_factory.mktemp(\"cards_db\")\n\n\n@pytest.fixture(scope=\"session\")\ndef session_cards_db(tmp_db_path):\n \"\"\"CardsDB\"\"\"\n db_ = cards.CardsDB(tmp_db_path)\n yield db_\n db_.close()\n\n\n@pytest.fixture(scope=\"function\")\ndef cards_db(session_cards_db):\n \"\"\"Empty CardsDB\"\"\"\n db = session_cards_db\n db.delete_all()\n return db\n\n\n@pytest.fixture(scope=\"function\")\ndef cards_db_three_cards(cards_db):\n \"\"\"CardsDB with 3 cards\"\"\"\n cards_db.add_card(Card(\"foo\"))\n cards_db.add_card(Card(\"bar\"))\n cards_db.add_card(Card(\"baz\"))\n return cards_db\n","sub_path":"learning_pytest/Ch9_Coverage/project/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"455011532","text":"import re\nimport functools\n# -*- coding: UTF-8 -*-\nimport random\nfrom optparse import OptionParser\n\nusage = \"[<-n> + 数字] 确定题目条数 [<-r> + 数字] 确定数字范围 \\n 可选参数: \\n <-u> 生成有负数出现的题目 \\n [<-a> + (filename)] 回答filename文件的题目 \\n [<-j> + (filename)] 批改filename文件的题目\"\nparser = OptionParser(usage)\nparser.print_help()\nparser.add_option(\"-n\", action='store', type='int', dest='Numbers', help=\"生成Numbers条无负数结果的算式,输出文件是StandExercises.txt\")\nparser.add_option(\"-r\", action='store', type='int', dest='Range', help=\"指定数字Range范围\")\nparser.add_option(\"-u\", action='store', type='string', dest='ProExFile', help=\"生成Numbers条有负数结果的算式,输出文件时Exercises.txt\")\nparser.add_option(\"-a\", action='store', type='string', dest='AnsFile', help=\"指定题目文件,并生成答案到Answers.txt\")\nparser.add_option(\"-j\", action='store', type='string', dest='JudgeFile', help=\"指定用户答案文件,并将其和标准Answers.txt对比\")\noptions, args = parser.parse_args()\n\n\nclass Genera:\n\n def __init__(self, numbers, range):\n 'self.numbers 是生成题目总个数, self.range 是数值的范围'\n self.numbers = numbers\n self.range = range\n self.filename = 'Exercises.txt'\n self.Fomulas()\n\n def GeneralOneFormula(self):\n Range = self.range\n # OperateNumbers = random.randint(1, 3)\n X1 = int(random.random() * 10000)\n X2 = int(random.random() * 10000)\n OperateNumbers = X1 % 3 + 1\n CountNUmbers = OperateNumbers + 1\n Ostyle = ['+', '-', '*', '÷']\n\n # 生成符号list\n Operates = []\n a = 0\n while (a <= OperateNumbers):\n # Operates.append(random.choice(Ostyle))\n if (a == 0):\n Operates.append(Ostyle[X1 % 4])\n if (a == 1):\n Operates.append(Ostyle[X2 % 4])\n if (a == 2):\n Operates.append(Ostyle[(X1 + X2) % 4])\n a += 1\n # 生成数字list与括号list\n Counts = []\n i = CountNUmbers\n while (i > 0):\n X = int(random.random() * 10000) % Range + 1\n if (X % 10 != 1):\n term = str(X)\n Counts.append(term)\n else:\n term = [str(X), '/', str(int(random.random() * 10000) % Range + 1)]\n termT = ''.join(term)\n # 此处插入分数化简\n Counts.append(termT)\n i -= 1\n if ((Operates.count('-') != 0) and (Operates.count('+') != 0) and (\n int(random.random() * 10000) % 7 == 1)): # 假定1/7的括号生成概率\n leftPosition = int(random.random() * 10000) % OperateNumbers\n rightPosition = random.randint(leftPosition + 2, OperateNumbers + 1) - 1\n # rightPosition = int(random.random() * 10000) % OperateNumbers + 1\n term = '(' + str(Counts[leftPosition])\n Counts[leftPosition] = term\n term = str(Counts[rightPosition]) + ')'\n Counts[rightPosition] = term\n # 合并符号list 数字括号list\n FinalList = []\n j = 0\n k = 0\n i = OperateNumbers + CountNUmbers - 1\n while (i >= 0):\n if (i % 2 != 1):\n FinalList.append(Counts[j])\n j += 1\n else:\n FinalList.append(Operates[k])\n k += 1\n i -= 1\n FinalList = ''.join(FinalList)\n return FinalList\n\n def Fomulas(self):\n Range = self.range\n Numbers = self.numbers\n ' 生成多个Formula并写入文档 '\n file = open(\"Exercises.txt\", 'a+')\n for i in range(1, Numbers + 1):\n print(str(self.GeneralOneFormula()), file=file)\n file.close()\n\nclass Answer:\n '这是用于生成任何题目文件的结果到Answers.txt中的类'\n\n def __init__(self, FileName):\n self.file = FileName\n self.OpenAFile()\n\n def mul_divOperation(self, s):\n sub_str = re.search('(\\d+\\.?\\d*[*/]-?\\d+\\.?\\d*)', s)\n while sub_str:\n sub_str = sub_str.group()\n if sub_str.count('*'):\n l_num, r_num = sub_str.split('*')\n s = s.replace(sub_str, str(float(l_num) * float(r_num)))\n else:\n l_num, r_num = sub_str.split('/')\n s = s.replace(sub_str, str(float(l_num) / float(r_num)))\n sub_str = re.search('(\\d+\\.?\\d*[*/]\\d+\\.?\\d*)', s)\n return s\n\n def add_minusOperation(self, s):\n s = '+' + s\n tmp = re.findall('[+\\-]\\d+\\.?\\d*', s)\n s = str(functools.reduce(lambda x, y: float(x) + float(y), tmp))\n return s\n\n def compute(self, formula):\n formula = self.mul_divOperation(formula)\n formula = self.add_minusOperation(formula)\n return formula\n\n def calc(self, formula):\n \"\"\"计算程序入口\"\"\"\n if (formula[0] == '(' and formula[len(formula) - 1] == ')'):\n formula = formula.replace('(', '')\n formula = formula.replace(')', '')\n formula = re.sub('[^.()/*÷\\-+0-9]', \"\", formula) # 清除非算式符号\n a = formula.find('.')\n if (a != -1):\n formula = formula.replace(formula[0:a+1], '') # 计算含有题目序列号的标准算式\n has_parenthesise = formula.count('(')\n while has_parenthesise:\n sub_parenthesise = re.search('\\([^()]*\\)', formula) # 匹配最内层括号\n if sub_parenthesise:\n formula = formula.replace(sub_parenthesise.group(), self.compute(sub_parenthesise.group()[1:-1]))\n else:\n has_parenthesise = False\n ret = self.compute(formula)\n return ret\n\n def Transfer(self, formula):\n '这是一个把小数字符串转换成分数的函数'\n i = formula.find('.')\n if (i != -1 and formula.find('-') == -1): # 如果存在小数点,只取小数点后三位\n e = float(formula[0:i + 4])\n intE = int(e)\n term = round(e - intE, 4) # 小数部分四舍五入\n if (term == 0): return formula[:i]\n termD = term * 1000\n Deno = 1000\n if (termD % 333 == 0): Deno = 999 # 优化小学生算术题中常出现的1/3\n while (termD != Deno): # 求最大公约数以化简\n if (Deno > termD): Deno = Deno - termD\n if (termD > Deno): termD = termD - Deno\n term = int(term * 1000 / termD)\n Deno = int(1000 / termD)\n if (intE != 0): answers = [str(intE), '\\'', str(term), '/', str(Deno)]\n if (intE == 0): answers = [str(term), '/', str(Deno)]\n answers = ''.join(answers)\n return answers\n else:\n return formula\n\n def OpenAFile(self):\n fileE = open(self.file, \"r+\")\n string = fileE.read()\n fileE.close()\n string = string.replace('÷', '/')\n out = \"\"\n for line in string.splitlines():\n # out = out + self.compute(line) + '\\n'\n out = out.replace('+', '')\n out = out + self.Transfer(self.calc(line)) + '\\n'\n fileA = open(\"Answers.txt\", \"w+\")\n print(out, file=fileA)\n fileA.close()\n\n\nclass Verify:\n '这是一个用于修正有负数结果的式子,判断式子是否有重复,以及生成题目序号的类,判断/后面有没有0'\n\n # 筛选出等式中的符号\n def __init__(self, FileName):\n self.file = FileName\n self.VerifyAFile()\n\n def VerifyAFile(self):\n No = 1\n with open(self.file) as r:\n lines = r.readlines()\n with open('StandExercises.txt', 'w') as w:\n for l in lines:\n s = l\n s = s.replace('÷', '/')\n if ((self.math_compute(s) == 1)):\n position = re.search('\\Z', l).end()\n l = l.replace(l[position - 1], ' = \\n')\n l = str(No) + '. ' + l\n w.write(l)\n No += 1\n r.close()\n w.close()\n\n def filt_sym(self, e1_fs):\n sym_get = \"\"\n for sym in e1_fs:\n if sym == '+' or sym == '-' or sym == '*' or sym == '/':\n sym_get = sym_get + sym\n return sym_get\n\n # 筛选出等式中的数字\n def filt_num(self, e1_fn):\n num_get = []\n num_c = \"\"\n for num in e1_fn:\n if num != '+' and num != '-' and num != '*' and num != '/':\n flag = 1\n num_c += num\n else:\n flag = 0\n if flag == 0:\n num_get = num_get + [float(num_c)]\n num_c = \"\"\n num_get = num_get + [float(num_c)]\n return num_get\n\n # 判断优先级\n def judge_pri(self, sym_int):\n i = 0\n sym_p = []\n for sym_jp in sym_int:\n if sym_jp == '/':\n sym_p += [40 + i]\n i += 1\n elif sym_jp == '*':\n sym_p += [30 + i]\n i += 1\n else:\n i += 1\n i = 0\n for sym_jp in sym_int:\n if sym_jp == '-':\n sym_p += [20 + i]\n i += 1\n elif sym_jp == '+':\n sym_p += [10 + i]\n i += 1\n else:\n i += 1\n return sym_p\n\n # 等式运算计算细节实现\n def int_compute(self, num_int, sym_int):\n sym_p_int = self.judge_pri(sym_int)\n while sym_p_int != []:\n sym = int(sym_p_int[0])\n if sym >= 40:\n if num_int[sym - 40 + 1] == 0:\n return -1\n num_int[sym - 40] /= num_int[sym - 40 + 1]\n num = num_int[sym - 40: sym - 40 + 1]\n del num_int[sym - 40 + 1: sym - 40 + 2]\n sym_int = sym_int[:sym - 40] + sym_int[sym - 40 + 1:]\n elif sym >= 30:\n num_int[sym - 30] *= num_int[sym - 30 + 1]\n num = num_int[sym - 30: sym - 30 + 1]\n del num_int[sym - 30 + 1: sym - 30 + 2]\n sym_int = sym_int[:sym - 30] + sym_int[sym - 30 + 1:]\n elif sym >= 20:\n num_int[sym - 20] -= num_int[sym - 20 + 1]\n num = num_int[sym - 20: sym - 20 + 1]\n if num[0] < 0:\n return -1\n del num_int[sym - 20 + 1: sym - 20 + 2]\n sym_int = sym_int[:sym - 20] + sym_int[sym - 20 + 1:]\n elif sym >= 10:\n num_int[sym - 10] += num_int[sym - 10 + 1]\n num = num_int[sym - 10: sym - 10 + 1]\n del num_int[sym - 10 + 1: sym - 10 + 2]\n sym_int = sym_int[:sym - 10] + sym_int[sym - 10 + 1:]\n sym_p_int = self.judge_pri(sym_int)\n return float(num[0])\n\n # 等式运算\n def compute_c(self, e1):\n num_int = float()\n num_int = self.filt_num(e1)\n sym_int = self.filt_sym(e1)\n flag = self.int_compute(num_int, sym_int)\n if flag < 0:\n return 'f'\n else:\n return str(flag)\n\n # 将等式中括号里面的等式提取出来\n def judge_bracket(self, equ_j):\n left = equ_j.rfind('(')\n right = equ_j.find(')', left)\n e1 = equ_j[left + 1:right]\n c1 = self.compute_c(e1)\n if c1 == 'f':\n return False\n equ_j = equ_j[0:left] + str(c1) + equ_j[(left + len(c1)):]\n equ_j = equ_j[0: left + len(str(c1))] + equ_j[right + 1:]\n return equ_j\n\n def math_compute(self, equation):\n equ_m = equation\n while equ_m.find('(') != -1:\n if equ_m.find('(') != -1:\n equ_m = self.judge_bracket(equ_m)\n if not equ_m:\n break;\n else:\n break\n if not equ_m:\n return 0\n elif equ_m.find('+') != -1 or equ_m.find('-') != -1 or equ_m.find('*') != -1 or equ_m.find('/') != -1:\n val = self.compute_c(equ_m)\n if val == 'f':\n return 0\n else:\n return 1\n else:\n return 1\n\n\nclass Judge:\n '判断Exercises 和 Answers.txt ,并返回处理结果'\n\n def __init__(self, FileName, FilenameAns):\n self.user_file = FileName\n self.standAns_file = FilenameAns\n self.judge_ans(self.user_file, self.standAns_file)\n\n def judge_ans(self, user_ans, stand_ans):\n user_a = open(user_ans, 'r')\n std_a = open(stand_ans, 'r')\n i = 0\n c_sum = []\n e_sum = []\n while 1:\n equa_u = user_a.readline()\n equa_s = std_a.readline()\n if not equa_u:\n break\n ind = equa_u.rfind('=')\n if equa_u[ind + 1:].strip() == equa_s.strip():\n i += 1\n c_sum += [i]\n else:\n i += 1\n e_sum += [i]\n print(\"Correct: \", len(c_sum), c_sum)\n print(\"Wrong: \", len(e_sum), e_sum)\n\n\nif options.Numbers and options.Range and options.ProExFile:\n '生成Numbers条有负数结果的算式, 再将其标准化(去除中间过程有负数结果的算式以及/后面有0的非法算式), 输出文件是StandExercises.txt'\n fileE = Genera(options.Numbers, options.Range)\n fileStand = Verify(fileE.filename)\n\nif options.Numbers and options.Range and options.ProExFile and options.AnsFile:\n '生成Numbers条有负数结果的算式, 再将其标准化(去除中间过程有负数结果的算式以及/后面有0的非法算式), 输出文件是StandExercises.txt'\n fileE = Genera(options.Numbers, options.Range)\n fileStand = Verify(fileE.filename)\n fileA = Answer(options.AnsFile)\n\nif options.AnsFile and not options.Numbers:\n '回答-a后面的filename题目文件,并输出结果到Answers.txt文件'\n fileA = Answer(options.AnsFile)\n\nif options.ProExFile and options.Numbers and options.Range and not options.AnsFile:\n '生成Numbers条有负数结果的算式, 生成文件是Exercises.txt'\n fileE = Genera(options.Numbers, options.Range)\n\nif options.JudgeFile and not options.Numbers and not options.Range and not options.ProExFile:\n '-j 接一个用户的答案文件, 并将其和标准答案文件Answers.txt比较'\n FileA = Judge(options.JudgeFile, \"Answers.txt\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"485599609","text":"import pytest\nfrom doltpy.core.dolt import Dolt, _execute, DoltException, DoltDirectoryException\nfrom doltpy.core.write import UPDATE, import_df\nfrom doltpy.core.read import pandas_read_sql, read_table\nimport shutil\nimport pandas as pd\nimport uuid\nimport os\nfrom typing import Tuple, List\nfrom doltpy.core.tests.helpers import get_repo_path_tmp_path\nimport sqlalchemy\nfrom retry import retry\nfrom sqlalchemy.engine import Engine\n\n\nBASE_TEST_ROWS = [\n {'name': 'Rafael', 'id': 1},\n {'name': 'Novak', 'id': 2}\n]\n\n\n@pytest.fixture\ndef create_test_data(tmp_path) -> str:\n path = os.path.join(tmp_path, str(uuid.uuid4()))\n pd.DataFrame(BASE_TEST_ROWS).to_csv(path, index_label=False)\n yield path\n os.remove(path)\n\n\n@pytest.fixture\ndef create_test_table(init_empty_test_repo, create_test_data) -> Tuple[Dolt, str]:\n repo, test_data_path = init_empty_test_repo, create_test_data\n repo.sql(query='''\n CREATE TABLE `test_players` (\n `name` LONGTEXT NOT NULL COMMENT 'tag:0',\n `id` BIGINT NOT NULL COMMENT 'tag:1',\n PRIMARY KEY (`id`)\n );\n ''')\n import_df(repo, 'test_players', pd.read_csv(test_data_path), ['id'], UPDATE)\n yield repo, 'test_players'\n\n if 'test_players' in [table.name for table in repo.ls()]:\n _execute(['table', 'rm', 'test_players'], repo.repo_dir())\n\n\ndef test_init(tmp_path):\n repo_path, repo_data_dir = get_repo_path_tmp_path(tmp_path)\n assert not os.path.exists(repo_data_dir)\n Dolt.init(repo_path)\n assert os.path.exists(repo_data_dir)\n shutil.rmtree(repo_data_dir)\n\n\ndef test_bad_repo_path(tmp_path):\n bad_repo_path = tmp_path\n with pytest.raises(AssertionError):\n Dolt(bad_repo_path)\n\n\ndef test_commit(create_test_table):\n repo, test_table = create_test_table\n repo.add(test_table)\n before_commit_count = len(repo.log())\n repo.commit('Julianna, the very serious intellectual')\n assert repo.status().is_clean and len(repo.log()) == before_commit_count + 1\n\n\ndef test_dolt_log(create_test_table):\n repo, test_table = create_test_table\n message_one = 'Julianna, the very serious intellectual'\n message_two = 'Added Stan the Man'\n repo.add(test_table)\n repo.commit('Julianna, the very serious intellectual')\n repo.sql('INSERT INTO `test_players` (`name`, `id`) VALUES (\"Stan\", 4)')\n repo.add(test_table)\n repo.commit(message_two)\n commits = list(repo.log().values())\n current_commit = commits[0]\n previous_commit = commits[1]\n assert current_commit.message == message_two\n assert previous_commit.message == message_one\n\n\ndef test_get_dirty_tables(create_test_table):\n repo, test_table = create_test_table\n message = 'Committing test data'\n\n # Some test data\n initial = pd.DataFrame({'id': [1], 'name': ['Bianca'], 'role': ['Champion']})\n appended_row = pd.DataFrame({'name': ['Serena'], 'id': [2], 'role': ['Runner-up']})\n\n def _insert_row_helper(repo, table, row):\n import_df(repo, table, row, ['id'], import_mode=UPDATE)\n\n # existing, not modified\n repo.add(test_table)\n repo.commit(message)\n\n # existing, modified, staged\n modified_staged = 'modified_staged'\n import_df(repo, modified_staged, initial, ['id'])\n repo.add(modified_staged)\n\n # existing, modified, unstaged\n modified_unstaged = 'modified_unstaged'\n import_df(repo, modified_unstaged, initial, ['id'])\n repo.add(modified_unstaged)\n\n # Commit and modify data\n repo.commit(message)\n _insert_row_helper(repo, modified_staged, appended_row)\n import_df(repo, modified_staged, appended_row, ['id'], UPDATE)\n repo.add(modified_staged)\n import_df(repo, modified_unstaged, appended_row, ['id'], UPDATE)\n\n # created, staged\n created_staged = 'created_staged'\n import_df(repo, created_staged, initial, ['id'])\n repo.add(created_staged)\n\n # created, unstaged\n created_unstaged = 'created_unstaged'\n import_df(repo, created_unstaged, initial, ['id'])\n\n status = repo.status()\n\n expected_new_tables = {'created_staged': True, 'created_unstaged': False}\n expected_changes = {'modified_staged': True, 'modified_unstaged': False}\n\n assert status.added_tables == expected_new_tables\n assert status.modified_tables == expected_changes\n\n\ndef test_checkout_with_tables(create_test_table):\n repo, test_table = create_test_table\n repo.checkout(table_or_tables=test_table)\n assert repo.status().is_clean\n\n\ndef test_sql_server(create_test_table, run_serve_mode):\n \"\"\"\n This test ensures we can round-trip data to the database.\n :param create_test_table:\n :param run_serve_mode:\n :return:\n \"\"\"\n repo, test_table = create_test_table\n data = pandas_read_sql('SELECT * FROM {}'.format(test_table), repo.get_engine())\n assert list(data['id']) == [1, 2]\n\n\ndef test_sql_server_unique(create_test_table, run_serve_mode, init_other_empty_test_repo):\n \"\"\"\n This tests that if you fire up SQL server via Python, you get a connection to the SQL server instance that the repo\n is running, not another repos MySQL server instance.\n :return:\n \"\"\"\n @retry(delay=2, tries=10, exceptions=(\n sqlalchemy.exc.OperationalError,\n sqlalchemy.exc.DatabaseError,\n sqlalchemy.exc.InterfaceError,\n ))\n def get_databases(engine: Engine):\n with engine.connect() as conn:\n result = conn.execute('SHOW DATABASES')\n return [tup[0] for tup in result]\n\n repo, test_table = create_test_table\n other_repo = init_other_empty_test_repo\n other_repo.sql_server()\n\n repo_databases = get_databases(repo.get_engine())\n other_repo_databases = get_databases(other_repo.get_engine())\n\n assert {'information_schema', repo.repo_name} == set(repo_databases)\n assert {'information_schema', other_repo.repo_name} == set(other_repo_databases)\n\n\ndef test_branch(create_test_table):\n repo, _ = create_test_table\n active_branch, branches = repo.branch()\n assert [active_branch.name] == [branch.name for branch in branches] == ['master']\n\n repo.checkout('dosac', checkout_branch=True)\n repo.checkout('master')\n next_active_branch, next_branches = repo.branch()\n assert set(branch.name for branch in next_branches) == {'master', 'dosac'} and next_active_branch.name == 'master'\n\n repo.checkout('dosac')\n different_active_branch, _ = repo.branch()\n assert different_active_branch.name == 'dosac'\n\n\ndef test_remote_list(create_test_table):\n repo, _ = create_test_table\n repo.remote(add=True, name='origin', url='blah-blah')\n assert repo.remote()[0].name == 'origin'\n repo.remote(add=True, name='another-origin', url='blah-blah')\n assert set([remote.name for remote in repo.remote()]) == {'origin', 'another-origin'}\n\n\ndef test_checkout_non_existent_branch(create_test_table):\n repo, _ = create_test_table\n with pytest.raises(DoltException):\n repo.checkout('master')\n\n\ndef test_ls(create_test_table):\n repo, test_table = create_test_table\n assert [table.name for table in repo.ls()] == [test_table]\n\n\ndef test_sql(create_test_table):\n repo, test_table = create_test_table\n sql = '''\n INSERT INTO {table} (name, id)\n VALUES ('Roger', 3)\n '''.format(table=test_table)\n repo.sql(query=sql)\n\n test_data = read_table(repo, test_table)\n assert 'Roger' in test_data['name'].to_list()\n\n\ndef test_sql_json(create_test_table):\n repo, test_table = create_test_table\n result = repo.sql(query='SELECT * FROM `{table}`'.format(table=test_table), result_format='json')['rows']\n _verify_against_base_rows(result)\n\n\ndef test_sql_csv(create_test_table):\n repo, test_table = create_test_table\n result = repo.sql(query='SELECT * FROM `{table}`'.format(table=test_table), result_format='csv')\n _verify_against_base_rows(result)\n\n\ndef test_sql_tabular(create_test_table):\n repo, test_table = create_test_table\n result = repo.sql(query='SELECT * FROM `{table}`'.format(table=test_table), result_format='tabular')\n _verify_against_base_rows(result)\n\n\ndef _verify_against_base_rows(result: List[dict]):\n assert len(result) == len(BASE_TEST_ROWS)\n\n result_sorted = sorted(result, key=lambda el: el['id'])\n for left, right in zip(BASE_TEST_ROWS, result_sorted):\n assert set(left.keys()) == set(right.keys())\n for k in left.keys():\n # Unfortunately csv.DictReader is a stream reader and thus does not look at all values for a given column\n # and make type inference, so we have to cast everything to a string. JSON roundtrips, but would not\n # preserve datetime objects for example.\n assert str(left[k]) == str(right[k])\n\n\nTEST_IMPORT_FILE_DATA = '''\nname,id\nroger,1\nrafa,2\n'''.lstrip()\n\n\ndef test_schema_import_create(init_empty_test_repo, tmp_path):\n repo = init_empty_test_repo\n table = 'test_table'\n test_file = tmp_path / 'test_data.csv'\n with open(test_file, 'w') as f:\n f.writelines(TEST_IMPORT_FILE_DATA)\n repo.schema_import(table=table, create=True, pks=['id'], filename=test_file)\n\n assert repo.status().added_tables == {table: False}\n\n\ndef test_config_global(init_empty_test_repo):\n _ = init_empty_test_repo\n current_global_config = Dolt.config_global(list=True)\n test_username, test_email = 'test_user', 'test_email'\n Dolt.config_global(add=True, name='user.name', value=test_username)\n Dolt.config_global(add=True, name='user.email', value=test_email)\n updated_config = Dolt.config_global(list=True)\n assert updated_config['user.name'] == test_username and updated_config['user.email'] == test_email\n Dolt.config_global(add=True, name='user.name', value=current_global_config['user.name'])\n Dolt.config_global(add=True, name='user.email', value=current_global_config['user.email'])\n reset_config = Dolt.config_global(list=True)\n assert reset_config['user.name'] == current_global_config['user.name']\n assert reset_config['user.email'] == current_global_config['user.email']\n\n\ndef test_config_local(init_empty_test_repo):\n repo = init_empty_test_repo\n current_global_config = Dolt.config_global(list=True)\n test_username, test_email = 'test_user', 'test_email'\n repo.config_local(add=True, name='user.name', value=test_username)\n repo.config_local(add=True, name='user.email', value=test_email)\n local_config = repo.config_local(list=True)\n global_config = Dolt.config_global(list=True)\n assert local_config['user.name'] == test_username and local_config['user.email'] == test_email\n assert global_config['user.name'] == current_global_config['user.name']\n assert global_config['user.email'] == current_global_config['user.email']\n","sub_path":"doltpy/core/tests/test_dolt.py","file_name":"test_dolt.py","file_ext":"py","file_size_in_byte":10704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"336056532","text":"import json\nimport time\nimport requests\nfrom logger import logger\nfrom requests.auth import HTTPBasicAuth\n\nfrom perfrunner.helpers.cbmonitor import with_stats\nfrom perfrunner.helpers.misc import get_json_from_file\nfrom perfrunner.tests import PerfTest\n\n\nclass FTStest(PerfTest):\n\n WAIT_TIME = 1\n INDEX_WAIT_MAX = 1200\n\n def __init__(self, cluster_spec, test_config, verbose):\n super(FTStest, self).__init__(cluster_spec, test_config, verbose)\n\n self.index_definition = get_json_from_file(self.test_config.fts_settings.index_configfile)\n self.host_port = [x for x in self.cluster_spec.yield_servers()][0]\n self.host = self.host_port.split(':')[0]\n self.fts_port = 8094\n self.host_port = '{}:{}'.format(self.host, self.fts_port)\n self.fts_index = self.test_config.fts_settings.name\n self.header = {'Content-Type': 'application/json'}\n self.requests = requests.session()\n self.fts_doccount = self.test_config.fts_settings.items\n self.prepare_index()\n self.index_time_taken = 0\n self.auth = HTTPBasicAuth('Administrator', 'password')\n self.order_by = self.test_config.fts_settings.order_by\n\n @staticmethod\n def get_json_from_file(file_name):\n with open(file_name) as fh:\n return json.load(fh)\n\n @with_stats\n def access(self, *args):\n super(FTStest, self).timer()\n\n def access_bg_test(self):\n access_settings = self.test_config.access_settings\n access_settings.fts_config = self.test_config.fts_settings\n self.access_bg(access_settings)\n self.access()\n\n def load(self, *args):\n logger.info('load/restore data to bucket')\n self.remote.cbrestorefts(self.test_config.fts_settings.storage, self.test_config.fts_settings.repo)\n\n def run(self):\n self.workload = self.test_config.access_settings\n self.cleanup_and_restore()\n self.create_index()\n self.wait_for_index()\n self.check_rec_presist()\n self.access_bg_test()\n self.report_kpi()\n\n def cleanup_and_restore(self):\n self.delete_index()\n self.load()\n self.wait_for_persistence()\n self.compact_bucket()\n\n def delete_index(self):\n self.requests.delete(self.index_url,\n auth=(self.rest.rest_username,\n self.rest.rest_password),\n headers=self.header)\n\n def prepare_index(self):\n self.index_definition['name'] = self.fts_index\n self.index_definition[\"sourceName\"] = self.test_config.buckets[0]\n self.index_url = \"http://{}/api/index/{}\".\\\n format(self.host_port, self.fts_index)\n logger.info('Created the Index definition : {}'.\n format(self.index_definition))\n\n def check_rec_presist(self):\n rec_memory = self.fts_doccount\n self.fts_url = \"http://{}/api/nsstats\".format(self.host_port)\n key = ':'.join([self.test_config.buckets[0], self.fts_index, 'num_recs_to_persist'])\n while rec_memory != 0:\n logger.info(\"Record persists to be expected: %s\" % rec_memory)\n r = self.requests.get(url=self.fts_url, auth=self.auth)\n time.sleep(self.WAIT_TIME)\n rec_memory = r.json()[key]\n\n def create_index(self):\n r = self.requests.put(self.index_url,\n data=json.dumps(self.index_definition, ensure_ascii=False),\n auth=(self.rest.rest_username, self.rest.rest_password),\n headers=self.header)\n if not r.status_code == 200:\n logger.info(\"URL: %s\" % self.index_url)\n logger.info(\"data: %s\" % self.index_definition)\n logger.info(\"HEADER: %s\" % self.header)\n logger.error(r.text)\n raise RuntimeError(\"Failed to create FTS index\")\n time.sleep(self.WAIT_TIME)\n\n def wait_for_index(self):\n logger.info(' Waiting for Index to be completed')\n attempts = 0\n while True:\n r = self.requests.get(url=self.index_url + '/count', auth=self.auth)\n if r.status_code != 200:\n raise RuntimeError(\"Failed to fetch document count of index. Status {}\".format(r.status_code))\n count = int(r.json()['count'])\n if count >= self.fts_doccount:\n logger.info(\"Finished at document count {}\".format(count))\n return\n else:\n if not attempts % 10:\n logger.info(\"(progress) idexed documents count {}\".format(count))\n attempts += 1\n time.sleep(self.WAIT_TIME)\n if (attempts * self.WAIT_TIME) >= self.INDEX_WAIT_MAX:\n raise RuntimeError(\"Failed to create Index\")\n\n\nclass FtsIndexTest(FTStest):\n\n COLLECTORS = {\"fts_stats\": True}\n\n @with_stats\n def index_test(self):\n logger.info('running Index Test with stats')\n self.create_index()\n start_time = time.time()\n self.wait_for_index()\n end_time = time.time()\n self.index_time_taken = end_time - start_time\n\n def run(self):\n self.cleanup_and_restore()\n self.index_test()\n self.report_kpi()\n\n def _report_kpi(self):\n self.reporter.post_to_sf(\n *self.metric_helper.calc_ftses_index(self.index_time_taken,\n order_by=self.order_by)\n )\n\n\nclass FTSLatencyTest(FTStest):\n COLLECTORS = {'fts_latency': True,\n \"fts_query_stats\": True,\n \"fts_stats\": True}\n\n def _report_kpi(self):\n self.reporter.post_to_sf(\n *self.metric_helper.calc_latency_ftses_queries(percentile=80,\n dbname='fts_latency',\n metrics='cbft_latency_get',\n order_by=self.order_by)\n )\n self.reporter.post_to_sf(\n *self.metric_helper.calc_latency_ftses_queries(percentile=0,\n dbname='fts_latency',\n metrics='cbft_latency_get',\n order_by=self.order_by)\n )\n\n\nclass FTSThroughputTest(FTStest):\n COLLECTORS = {'fts_query_stats': True,\n \"fts_stats\": True}\n\n def _report_kpi(self):\n self.reporter.post_to_sf(\n *self.metric_helper.calc_avg_fts_queries(order_by=self.order_by)\n )\n","sub_path":"perfrunner/tests/fts.py","file_name":"fts.py","file_ext":"py","file_size_in_byte":6855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"484921252","text":"import numpy as np\nimport pytest\n\n\n\ndef find_beamwidth(the_wavel,dish_size):\n \"\"\"\n input: the_wavel : wavelength (cm)\n dish_size : antenna dish diameter (m)\n output: beamwidth : beamwidth angle (degrees)\n \"\"\"\n #\n # Stull eq. 8.13\n #\n a = 71.6 #constant (degrees)\n the_wavel = the_wavel/100. #convert cm to m\n beamwidth = a*the_wavel/dish_size #beamwitdh in degrees\n return beamwidth\n\n\n\ndef find_range(delT):\n \"\"\"\n Stull eq. 8.16\n input: delT : the round-trip travel times (micro sec)\n output: radar range (km)\n \"\"\"\n c = 3e8 #speed of light (m/s)\n delT = delT*(1.e-6) #convert microseconds to s\n radar_range = c*delT/2\n return radar_range*1.e-3 #kilometers\n\n\ndef test_a10():\n the_wavel=[20,20,10,10,10,5,5,5,5,3] #wavelength (cm)\n dish_size=[8,10,10,5,3,7,5,2,3,1] #dishsize (meters)\n input_vals=zip(the_wavel,dish_size)\n beamwidth=[find_beamwidth(wavel,dish_size) for wavel,dish_size in input_vals]\n answer = [1.790, 1.432, 0.716, 1.432, 2.387, 0.511, 0.716, 1.790, 1.193, 2.148]\n np.testing.assert_array_almost_equal(beamwidth,answer,decimal=3)\n return None\n\n\ndef test_a12():\n times=[2,5,10,25,50,75,100,150,200,300] #microseconds\n the_range=[find_range(delT) for delT in times]\n answer=[0.3 , 0.7 , 1.5 , 3.7 , 7.5 , 11.2 , 15.0 , 22.5 , 30.0 , 45.0]\n np.testing.assert_array_almost_equal(the_range,answer,decimal=1)\n return None\n\n\nif __name__ == \"__main__\":\n print('testing __file__: {}'.format(__file__))\n pytest.main([__file__, '-q'])\n","sub_path":"a301examples/a10_12_solution.py","file_name":"a10_12_solution.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"312648841","text":"##main functionality for database processing \n\n##notes: x_y=function xY=variable\n\n\n\ndef num_check(s): #num_check trys the value 's' to see if it's a float (number) or a date. If it is, it returns True, if not, returns false\n #uses dateutil package to check for the presence of a date in the row (indicating header is no longer a part of the row)\n from dateutil.parser import parse \n\n try:\n float(s)\n return True\n\n except ValueError:\n try:\n parse(s)\n return True\n\n except ValueError:\n return False\n\ndef header_check(header,headerFull,i): #header_check builds the headers into a single list \n #concatenates each row based on mox header depth in the matrix (i)\n s = 0\n\n while s < len(header):\n if i > 0:\n headerFull[s] = headerFull[s] + '_' + header[s]\n s = s+1\n\n else:\n s = s+1\n\n return headerFull\n\ndef header_format(dataIndiv,completeHeader): #header_format builds the headers into a list to be parseble into the sql server, dataIndiv is the list of values one below the header which is used to set the type\n from dateutil.parser import parse\n\n s = 0\n dataType = 'varchar(80)'\n\n while s < len(dataIndiv): #data validation and cleansing is needed as the headers are often filled with random characters that are useless to the database\n completeHeader[s] = completeHeader[s].replace(\" \",\"_\")\n completeHeader[s] = completeHeader[s].replace(\"(\",\"_\")\n completeHeader[s] = completeHeader[s].replace(\")\",\"_\")\n completeHeader[s] = completeHeader[s].replace(\".\",\"_\")\n completeHeader[s] = completeHeader[s].replace(\"/\",\"_\")\n\n try:\n float(dataIndiv[s])\n dataType = 'float'\n completeHeader[s] = completeHeader[s] + \" \" + dataType + \",\"\n s = s+1\n\n except ValueError:\n try:\n parse(dataIndiv[s])\n dataType = 'date'\n completeHeader[s] = completeHeader[s] + \" \" + dataType + \",\"\n s = s+1\n\n except ValueError:\n try:\n int(dataIndiv[s])\n dataType = 'int'\n completeHeader[s] = completeHeader[s] + \" \" + dataType + \",\"\n s = s+1\n \n except ValueError:\n dataType = 'text'\n completeHeader[s] = completeHeader[s] + \" \" + dataType + \",\"\n s = s+1\n\n completeHeader = (' '.join(completeHeader))\n completeHeader = completeHeader[:-1]\n\n return completeHeader\n\ndef table_exist(tableName, conn): #checks to see if a table exists/returns true or false\n cur = conn.cursor()\n\n exist = \"\"\"select exists(select * from information_schema.tables where table_name = '%s')\"\"\" %tableName\n print(exist)\n\n try:\n cur.execute(exist)\n exists = cur.fetchone()[0]\n print('true')\n print(exists)\n return exists\n\n except ValueError:\n print('false')\n return False\n\n\ndef csv_HeaderReader(f1,conn,tableName): #csv_reader opens a csv, calls it into memory, and checks the first 10 rows to see if data is there. If it is data, all previous rows stored to\n #memory are concatenated and become the header (completeHeader). \n import csv\n ########import psycopg2\n cur = conn.cursor()\n\n with open(f1, 'rt') as dataFILE: #opens file and sets up reader and iterator\n csvreader = csv.reader(dataFILE) #open file\n headerList = (next(csvreader)) #start iterator//calling header list calls next row\n headerFull = headerList #Stores first row\n headerVal = headerList[0] #stores first dataIndiv[s] = dataIndiv[s] + \" \" + dataType + \",\"value in called row\n \n i = 0\n\n if table_exist(tableName, conn) == True: #checks for exiting table, if present, counts headers and returns that without making a new table, if no table exists, creates table\n \n while i < 10: #amount of rows to check, change this number to check more or less rows\n if num_check(headerVal) == False: #calls num_check (see above function). If this row is not data, function saves it (incase it is the header), then\n #iterates to the next row and preps the first value for checking\n header = headerList\n completeHeader = header_check(header,headerFull,i)\n headerList = (next(csvreader))\n headerVal = headerList[0]\n \n i = i+1\n \n elif num_check(headerVal) == True: #if num_check returns true, this is where the database header building function will be called and implemented. \n #Once it is complete, the loop breaks and the function ends. This should actually ideally concatenate multiple\n #rows since it seems a lot of these files use more than one row as a header, with units and other info included\n dataRow = headerList\n formatedHeader = header_format(dataRow,completeHeader)\n \n print('I am not creating a table')\n return i #i is the number of rows the headers occupy\n \n elif table_exist(tableName, conn) == False: #table creation stream\n \n while i < 10: #amount of rows to check, change this number to check more or less rows\n if num_check(headerVal) == False: #calls num_check (see above function). If this row is not data, function saves it (incase it is the header), then\n #iterates to the next row and preps the first value for checking\n header = headerList\n completeHeader = header_check(header,headerFull,i)\n headerList = (next(csvreader))\n headerVal = headerList[0]\n \n i = i+1\n \n elif num_check(headerVal) == True: #if num_check returns true, this is where the database header building function will be called and implemented. \n #Once it is complete, the loop breaks and the function ends. This should actually ideally concatenate multiple\n #rows since it seems a lot of these files use more than one row as a header, with units and other info included\n dataRow = headerList\n formatedHeader = header_format(dataRow,completeHeader)\n print(formatedHeader)\n \n formatedHeader = \"\"\"CREATE TABLE {} ({})\"\"\".format(tableName, formatedHeader)\n cur.execute(formatedHeader)\n conn.commit()\n \n return i\n \ndef row_counter(f1): #counts total rows in the csv for iteration purpose, returns rowCount\n import csv\n \n with open(f1, 'rt') as dataFILE: #opens file and sets up reader and iterator\n csvreader = csv.reader(dataFILE)\n rowCount = sum(1 for row in csvreader) #counts amount of rows in table for max value of insertion iterator\n \n return rowCount\n\n\n\ndef csv_reader(): #heavy lifter, calls other functions for processing, then handles input itself. wraps lines into lists then joins and inputs to the table \n import psycopg2 #uses connection opened here for all writes\n import csv\n\n conn = psycopg2.connect(\"host=localhost dbname=testDB user=ndsouza password=glacier1\")\n cur = conn.cursor() #connection to database\n\n f1 = input('Enter File path:') #queries to users\n tableName = input('Enter Table name:')\n\n with open(f1, 'rt') as dataFILE: #opens file and sets up reader and iterator\n \n csvreader = csv.reader(dataFILE) #open file\n rowCount = row_counter(f1)\n headerList = (next(csvreader)) #start iterator, calling header list calls the next row\n \n i = 0\n \n s = csv_HeaderReader(f1,conn,tableName)\n \n while i < s:\n headerList = (next(csvreader))\n i = i+1\n \n while i < rowCount: #when all conditions are met, this is where each row is inserted\n print(i)\n \n headerString = \"', '\".join(headerList)\n headerString = \"'\" + headerString + \"'\"\n \n cur.execute( #wrapping of all rows occurs here\n\n 'INSERT INTO {} VALUES ({})'.format(tableName, headerString)\n )\n conn.commit() #final commit locks the string into the database\n headerList = (next(csvreader))\n \n i = i+1\n\n print(\"File loading complete, disconnecting from database\")\n \ncsv_reader()","sub_path":"csvreaderTESTENV.py","file_name":"csvreaderTESTENV.py","file_ext":"py","file_size_in_byte":9743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"205245842","text":"from skimage import exposure\nimport numpy as np\nimport cv2\nimport glob\nimport os\n\n\n# Read image\n#oriimg = cv2.imread(\"../slike/Train/kauc1.jpg\")\n# Resize\n#img = cv2.resize(oriimg,(400,300))\n#img = np.float32(img) / 255.0\n\n# Calculate gradient\n#gx = cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=1)\n#gy = cv2.Sobel(img, cv2.CV_32F, 0, 1, ksize=1)\n\n# Python Calculate gradient magnitude and direction ( in degrees )\n#mag, angle = cv2.cartToPolar(gx, gy, angleInDegrees=False)\n\n#cv2.imshow('Original Image', oriimg)\n#cv2.imshow('Resized Image', img)\n#cv2.imshow('Sobel Image', mag)\n#cv2.waitKey()\n\nprint(\"Working\")\nsrc_dir = '../slike/Train'\ndst_dir = '../SavedImages/'\n\nfor filename in glob.glob(os.path.join(src_dir, '*')):\n im = cv2.imread(filename)\n name = filename.replace(src_dir, '')\n\n img = cv2.resize(im, (400, 300))\n img = np.float32(img) / 255.0\n # Calculate gradient\n gx = cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=1)\n gy = cv2.Sobel(img, cv2.CV_32F, 0, 1, ksize=1)\n\n # Python Calculate gradient magnitude and direction ( in degrees )\n mag, angle = cv2.cartToPolar(gx, gy, angleInDegrees=False)\n\n #ovdje ispise pravilno slike ove sa Sobel filterom ali kad ih spasi spasi samo crno\n cv2.imshow('Sobel Image', mag)\n cv2.waitKey()\n cv2.imwrite( name, mag)\n\n\nprint(\"Done\")\n\n","sub_path":"Project files/EditImage.py","file_name":"EditImage.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"149614813","text":"#!/usr/bin/env python3\n\nimport sys\nsys.path.append('../client/driver')\n\nimport RPi.GPIO as GPIO\nimport DCMotor\nimport time\n\n# Initialize GPIO\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD)\n\n# Create new driver for DC motor on pins 11, 12 and 13\nDC = DCMotor.DCMotor(11, 12, 13)\n\n# Start the debug mode\nDC.start_debug_mode()\n\n# Go forward for one seconde\nDC.setSpeed(100)\ntime.sleep(1)\n\n# Go forward (half of maximum speed) for one seconde\nDC.setSpeed(50)\ntime.sleep(1)\n\n# Go backward (half of maximum speed) for one seconde\nDC.setSpeed(-50)\ntime.sleep(1)\n\n# Go backward for one seconde\nDC.setSpeed(-100)\ntime.sleep(1)\n\n# Stop the motor\nDC.stop()\n\nprint('Done !')\n","sub_path":"examples/driver_dc_motor.py","file_name":"driver_dc_motor.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"112754171","text":"import numpy\nimport pathlib\nimport freeimage\nimport scipy.ndimage as ndimage\nfrom skimage import transform\nfrom zplib.image import colorize\nfrom zplib.image import pyramid\n\ndef mode_normalize(image):\n '''normalize image by dividing by the non-zero mode\n '''\n m = numpy.bincount(image[image>0]).argmax()\n return image.astype(numpy.float32) / m\n\nbasic_bf_scaling = dict(min=0, max=1.09, gamma=0.75)\n\ndef write_mode_normalized(in_file, out_file, shrink=2, min=0, max=1.09, gamma=0.75):\n image = freeimage.read(in_file)\n #small_image = pyramid.pyr_down(image, shrink).astype(numpy.uint16)\n cropped_image = crop_img(image)\n small_image = pyr_down_set(cropped_image, (768,640)).astype(numpy.uint16)\n norm_image = mode_normalize(small_image)\n colorize.write_scaled(norm_image, out_file, min, max, gamma)\n\ndef pyr_down_set(image, shape, downscale=2, nyquist_attenuation=0.01):\n \"\"\"Return an image downsampled by the requested factor.\n\n Parameters:\n image: numpy array\n shape: dimensions you want for the output image (width, height).\n nyquist_attenuation: controls strength of low-pass filtering (see\n documentation for downsample_sigma() for detailed description).\n Larger values = more image blurring.\n\n Returns: image of type float32\n \"\"\"\n out_shape = shape\n downscale=numpy.divide(image.shape,out_shape).max().astype(int)\n print(\"downscale factor: \"+str(downscale))\n sigma = downsample_sigma(downscale, nyquist_attenuation)\n smoothed = ndimage.gaussian_filter(image.astype(numpy.float32), sigma, mode='reflect')\n return transform.resize(smoothed, out_shape, order=1, mode='reflect', preserve_range=True)\n\ndef downsample_sigma(scale_factor, nyquist_attenuation=0.05):\n \"\"\"Calculate sigma for gaussian blur that will attenuate the nyquist frequency\n of an image (after down-scaling) by the specified fraction. Surprisingly,\n attenuating by only 5-10% is generally sufficient (nyquist_attenuation=0.05\n to 0.1).\n See http://www.evoid.de/page/the-caveats-of-image-down-sampling/ .\n \"\"\"\n return scale_factor * (-8*numpy.log(1-nyquist_attenuation))**0.5\n\ndef write_mask(in_file, out_file, shape=(768,640)):\n \"\"\"Deals with worm masks (hmasks, etc.) since you\n don't need to mode normalize them\n \"\"\"\n image = freeimage.read(in_file)\n cropped_image = crop_img(image)\n #small_image = pyramid.pyr_down(image, shrink).astype(numpy.uint16)\n small_image = (pyr_down_set(image, (768,640)).astype(numpy.uint16) > 128).astype(numpy.uint8)*255\n freeimage.write(small_image, out_file)\n\ndef crop_img(img):\n '''Crop image to get rid of the weird black border thing\n '''\n return img[234:2433, 277:1832]\n\ndef preprocess(image_dir, out_dir, image_type=\"bf\"):\n '''preprocess all imamges in an image directory\n Assumes the masks are in other folders in the directory you provide it\n This is the format that I have used in the images I've been using \n\n image_type allows you to specifiy which images you want to normalize\n '''\n\n img_dir=pathlib.Path(image_dir)\n out_dir=pathlib.Path(out_dir)\n\n if image_type==\"mask\":\n #need to preprocess masks differently from regular bf files\n #Don't need to mode normalize the masks\n for i in list(img_dir.glob('**/*mask*.png')):\n #get subfolder\n print(i.name)\n subfolder=i.parts[-2]\n name=i.name\n out_folder=out_dir.joinpath(subfolder)\n #make sure out folder exists,\n #if not create it\n if not out_folder.exists():\n out_folder.mkdir()\n #print(str(out_folder))\n\n out_file=out_folder.joinpath(name)\n print('Saving file to: '+str(out_file))\n write_mask(i, out_file)\n else:\n for i in list(img_dir.glob('**/*bf.png')):\n #get subfolder\n print(i.name)\n subfolder=i.parts[-2]\n name=i.name\n out_folder=out_dir.joinpath(subfolder)\n #make sure out folder exists,\n #if not create it\n if not out_folder.exists():\n out_folder.mkdir()\n #print(str(out_folder))\n\n out_file=out_folder.joinpath(name)\n print('Saving file to: '+str(out_file))\n write_mode_normalized(i, out_file)\n\n","sub_path":"image_analysis/preprocess_images.py","file_name":"preprocess_images.py","file_ext":"py","file_size_in_byte":4381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"505441361","text":"import os\r\nimport datetime\r\nfrom datetime import datetime as dt\r\nimport inspect\r\nfrom abc import ABC, abstractclassmethod\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport paramiko\r\nimport pandas as pd\r\n\r\nimport ipso_phen.ipapi.file_handlers\r\nimport ipso_phen.ipapi.base.ip_common as ipc\r\nfrom ipso_phen.ipapi.tools.common_functions import get_module_classes, force_directories\r\nfrom ipso_phen.ipapi.tools.folders import ipso_folders\r\n\r\nimport logging\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\nclass FileHandlerBase(ABC):\r\n def __init__(self, **kwargs):\r\n self._file_path = \"\"\r\n self._exp = \"\"\r\n self._plant = \"\"\r\n self._camera = \"\"\r\n self._view_option = \"\"\r\n self._date_time = None\r\n self._linked_images = []\r\n self._database = None\r\n self._cache_file_path = \"\"\r\n self._blob_path = \"\"\r\n self.db_linked = False\r\n\r\n def __repr__(self): # Serialization\r\n return self.file_path\r\n\r\n def __str__(self): # Human readable\r\n if self._date_time:\r\n return (\r\n f\"[exp:{self.experiment}]\"\r\n f\"[plant:{self.plant}]\"\r\n f\"[date:{self.condensed_date}]\"\r\n f\"[camera:{self.camera}]\"\r\n f\"[view_option:{self.view_option}]\"\r\n )\r\n else:\r\n return self.file_name\r\n\r\n def load_from_database(self, address, port, user, pwd):\r\n if os.path.isdir(ipso_folders.get_path(\"mass_storage\", False)) and os.path.isfile(\r\n self.cache_file_path\r\n ):\r\n logger.debug(f\"Retrieved from cache: {str(self)}\")\r\n return self.load_from_harddrive(self.cache_file_path)\r\n src_img = None\r\n try:\r\n logger.debug(f\"Cache default, retrieving from server: {str(self)}\")\r\n p = paramiko.SSHClient()\r\n p.set_missing_host_key_policy(paramiko.AutoAddPolicy)\r\n p.connect(\r\n address,\r\n port=port,\r\n username=user,\r\n password=pwd,\r\n )\r\n ftp = p.open_sftp()\r\n try:\r\n with ftp.open(self.blob_path) as file:\r\n file_size = file.stat().st_size\r\n file.prefetch(file_size)\r\n file.set_pipelined()\r\n src_img = cv2.imdecode(np.fromstring(file.read(), np.uint8), 1)\r\n if os.path.isdir(ipso_folders.get_path(\"mass_storage\", False)):\r\n force_directories(os.path.dirname(self.cache_file_path))\r\n cv2.imwrite(self.cache_file_path, src_img)\r\n finally:\r\n ftp.close()\r\n p.close()\r\n src_img = self.fix_image(src_image=src_img)\r\n except Exception as e:\r\n logger.exception(f\"Failed to load {repr(self)} because {repr(e)}\")\r\n return None\r\n else:\r\n return src_img\r\n\r\n def load_from_harddrive(self, override_path: str = None):\r\n src_img = None\r\n try:\r\n fp = override_path if override_path is not None else self.file_path\r\n with open(fp, \"rb\") as stream:\r\n bytes = bytearray(stream.read())\r\n np_array = np.asarray(bytes, dtype=np.uint8)\r\n src_img = cv2.imdecode(np_array, 3)\r\n src_img = self.fix_image(src_image=src_img)\r\n except Exception as e:\r\n logger.exception(f\"Failed to load {repr(self)} because {repr(e)}\")\r\n return None\r\n else:\r\n return src_img\r\n\r\n def load_source_file(self):\r\n return self.load_from_harddrive()\r\n\r\n def update(self, **kwargs):\r\n self._file_path = kwargs.get(\"file_path\", self._file_path)\r\n self._exp = kwargs.get(\"experiment\", self._exp)\r\n self._plant = kwargs.get(\"plant\", self._plant)\r\n self._camera = kwargs.get(\"camera\", self._camera)\r\n self._view_option = kwargs.get(\"view_option\", self._view_option)\r\n if \"date_time\" in kwargs:\r\n try:\r\n ts = kwargs.get(\"date_time\")\r\n if isinstance(ts, str):\r\n self._date_time = dt.strptime(ts, \"%Y-%m-%d %Hh%Mm%Ss\")\r\n else:\r\n self._date_time = ts\r\n except Exception as e:\r\n logger.exception(\r\n f'Failed to update timestamp, please check format \"{str(e)}\"'\r\n )\r\n self._database = kwargs.get(\"database\", None)\r\n\r\n def fix_image(self, src_image):\r\n return src_image\r\n\r\n def compare_date(self, **kwargs):\r\n \"\"\"Compares wrapper's date to kwargs date\r\n\r\n Keyword arguments either date, wrapper or assortment of year, month, day:\r\n * date: date type\r\n * year: as int or str: if missing will be replaced by wrapper's data\r\n * month: as int or str: if missing will be replaced by wrapper's data\r\n * day: as int or str: if missing will be replaced by wrapper's data\r\n * wrapper: wrappers dates will be compared\r\n :return: 0 if equal, -1 if before, 1 if after\r\n \"\"\"\r\n dtc = kwargs.get(\"date\", None)\r\n if dtc is None:\r\n wrapper = kwargs.get(\"wrapper\", None)\r\n if wrapper:\r\n y, m, d = wrapper.year, wrapper.month, wrapper.day\r\n else:\r\n y = str(kwargs.get(\"year\", self.year))\r\n m = str(kwargs.get(\"month\", self.month))\r\n d = str(kwargs.get(\"day\", self.day))\r\n dtc = dt.strptime(f\"{y}_{m}_{d}\", \"%Y_%m_%d\")\r\n if dtc.date() == self.date:\r\n return 0\r\n elif self.date < dtc.date():\r\n return -1\r\n else:\r\n return 1\r\n\r\n def compare_time(self, **kwargs):\r\n \"\"\"Compares wrapper's time to kwargs time\r\n\r\n Keyword arguments either date, wrapper or assortment of year, month, day:\r\n * time: time type\r\n * hour: as int or str: if missing will be replaced by wrapper's data\r\n * minute: as int or str: if missing will be replaced by wrapper's data\r\n * second: as int or str: if missing will be replaced by wrapper's data\r\n * wrapper: wrappers times will be compared\r\n :return: 0 if equal, -1 if before, 1 if after\r\n \"\"\"\r\n ttc = kwargs.get(\"date\", None)\r\n if ttc is None:\r\n wrapper = kwargs.get(\"wrapper\", None)\r\n if wrapper:\r\n h, m, s = wrapper.hour, wrapper.minute, wrapper.second\r\n else:\r\n h = str(kwargs.get(\"hour\", self.hour))\r\n m = str(kwargs.get(\"minute\", self.minute))\r\n s = str(kwargs.get(\"second\", self.second))\r\n ttc = dt.strptime(f\"{h}-{m}-{s}\", \"%H-%M-%S\")\r\n if ttc.time() == self.time:\r\n return 0\r\n elif self.time < ttc.time():\r\n return -1\r\n else:\r\n return 1\r\n\r\n def compare_timestamp(self, **kwargs):\r\n \"\"\"Compares wrapper's time to kwargs time\r\n\r\n Keyword arguments either date, wrapper or assortment of year, month, day:\r\n * time: time type\r\n * year: as int or str: if missing will be replaced by wrapper's data\r\n * month: as int or str: if missing will be replaced by wrapper's data\r\n * day: as int or str: if missing will be replaced by wrapper's data\r\n * hour: as int or str: if missing will be replaced by wrapper's data\r\n * minute: as int or str: if missing will be replaced by wrapper's data\r\n * second: as int or str: if missing will be replaced by wrapper's data\r\n * wrapper: wrappers times will be compared\r\n :return: 0 if equal, -1 if before, 1 if after\r\n \"\"\"\r\n dtc = self.compare_date(**kwargs)\r\n if dtc == 0:\r\n return self.compare_time(**kwargs)\r\n else:\r\n return dtc\r\n\r\n def is_at_date(self, **kwargs):\r\n \"\"\"Compares wrapper's date to kwargs date\r\n\r\n Keyword arguments either date, wrapper or assortment of year, month, day:\r\n * date: date type\r\n * year: as int or str: if missing will be replaced by wrapper's data\r\n * month: as int or str: if missing will be replaced by wrapper's data\r\n * day: as int or str: if missing will be replaced by wrapper's data\r\n * wrapper: wrappers dates will be compared\r\n :return: True if equal\r\n \"\"\"\r\n return self.compare_date(**kwargs) == 0\r\n\r\n def is_after_date(self, **kwargs):\r\n \"\"\"Compares wrapper's date to kwargs date\r\n\r\n Keyword arguments either date, wrapper or assortment of year, month, day:\r\n * date: date type\r\n * year: as int or str: if missing will be replaced by wrapper's data\r\n * month: as int or str: if missing will be replaced by wrapper's data\r\n * day: as int or str: if missing will be replaced by wrapper's data\r\n * wrapper: wrappers dates will be compared\r\n :return: True if wrapper's date is after kwargs data\r\n \"\"\"\r\n return self.compare_date(**kwargs) > 0\r\n\r\n def is_before_date(self, **kwargs):\r\n \"\"\"Compares wrapper's date to kwargs date\r\n\r\n Keyword arguments either date, wrapper or assortment of year, month, day:\r\n * date: date type\r\n * year: as int or str: if missing will be replaced by wrapper's data\r\n * month: as int or str: if missing will be replaced by wrapper's data\r\n * day: as int or str: if missing will be replaced by wrapper's data\r\n * wrapper: wrappers dates will be compared\r\n :return: True if wrapper's date is before kwargs data\r\n \"\"\"\r\n return self.compare_date(**kwargs) < 0\r\n\r\n def is_at_time(self, **kwargs):\r\n \"\"\"Compares wrapper's time to kwargs time\r\n\r\n Keyword arguments either date, wrapper or assortment of year, month, day:\r\n * time: time type\r\n * hour: as int or str: if missing will be replaced by wrapper's data\r\n * minute: as int or str: if missing will be replaced by wrapper's data\r\n * second: as int or str: if missing will be replaced by wrapper's data\r\n * wrapper: wrappers times will be compared\r\n :return: True if equal\r\n \"\"\"\r\n return self.compare_time(**kwargs) == 0\r\n\r\n def is_before_time(self, **kwargs):\r\n \"\"\"Compares wrapper's time to kwargs time\r\n\r\n Keyword arguments either date, wrapper or assortment of year, month, day:\r\n * time: time type\r\n * hour: as int or str: if missing will be replaced by wrapper's data\r\n * minute: as int or str: if missing will be replaced by wrapper's data\r\n * second: as int or str: if missing will be replaced by wrapper's data\r\n * wrapper: wrappers times will be compared\r\n :return: True if wrapper's time is before kwargs data\r\n \"\"\"\r\n return self.compare_time(**kwargs) < 0\r\n\r\n def is_after_time(self, **kwargs):\r\n \"\"\"Compares wrapper's time to kwargs time\r\n\r\n Keyword arguments either date, wrapper or assortment of year, month, day:\r\n * time: time type\r\n * hour: as int or str: if missing will be replaced by wrapper's data\r\n * minute: as int or str: if missing will be replaced by wrapper's data\r\n * second: as int or str: if missing will be replaced by wrapper's data\r\n * wrapper: wrappers times will be compared\r\n :return: True if wrapper's time is after kwargs data\r\n \"\"\"\r\n return self.compare_time(**kwargs) > 0\r\n\r\n def is_at_date_time(self, **kwargs):\r\n return self.compare_timestamp(**kwargs) == 0\r\n\r\n def is_after_date_time(self, **kwargs):\r\n return self.compare_timestamp(**kwargs) > 0\r\n\r\n def is_before_date_time(self, **kwargs):\r\n return self.compare_timestamp(**kwargs) < 0\r\n\r\n def is_between_dates(\r\n self,\r\n start_date,\r\n end_date,\r\n date_format=\"%Y_%m_%d\",\r\n include_start=True,\r\n include_end=False,\r\n ):\r\n if isinstance(start_date, str):\r\n start_date = dt.strptime(start_date, date_format)\r\n if isinstance(end_date, str):\r\n end_date = dt.strptime(end_date, date_format)\r\n if include_start:\r\n start_date -= datetime.timedelta(days=1)\r\n if include_end:\r\n end_date += datetime.timedelta(days=1)\r\n\r\n return start_date.date() < self.date < end_date.date()\r\n\r\n def is_between_times(\r\n self,\r\n start_hour=\"00\",\r\n start_minute=\"00\",\r\n start_second=\"00\",\r\n end_hour=\"00\",\r\n end_minute=\"00\",\r\n end_second=\"00\",\r\n include_start=True,\r\n include_end=False,\r\n ):\r\n start = dt.strptime(f\"{start_hour}-{start_minute}-{start_second}\", \"%H-%M-%S\")\r\n end = dt.strptime(f\"{end_hour}-{end_minute}-{end_second}\", \"%H-%M-%S\")\r\n if include_start:\r\n start -= datetime.timedelta(seconds=1)\r\n if include_end:\r\n end += datetime.timedelta(seconds=1)\r\n start = start.time()\r\n end = end.time()\r\n return start < self.time < end\r\n\r\n def value_of(self, key):\r\n \"\"\"Returns value associated to key\r\n\r\n Arguments:\r\n key {str} -- key\r\n\r\n Returns:\r\n str -- value\r\n \"\"\"\r\n\r\n if key == \"exp\":\r\n return self.experiment\r\n elif key == \"plant\":\r\n return self.plant\r\n elif key == \"cam\":\r\n return self.camera\r\n elif key == \"view_option\":\r\n return self.view_option\r\n elif key == \"date\":\r\n return self.date_str\r\n elif key == \"year\":\r\n return self.year\r\n elif key == \"month\":\r\n return self.month\r\n elif key == \"day\":\r\n return self.day\r\n elif key == \"hour\":\r\n return self.hour\r\n elif key == \"minute\":\r\n return self.minute\r\n elif key == \"second\":\r\n return self.second\r\n else:\r\n return \"\"\r\n\r\n def matches(self, key, value):\r\n if isinstance(value, list):\r\n for val in value:\r\n if self.value_of(key).lower() == val.lower():\r\n return True\r\n return False\r\n else:\r\n return self.value_of(key).lower() == value.lower()\r\n\r\n @abstractclassmethod\r\n def probe(cls, file_path, database):\r\n return 0\r\n\r\n @classmethod\r\n def extract_file_name(cls, file_path):\r\n return os.path.basename(file_path)\r\n\r\n @property\r\n def file_path(self):\r\n return self._file_path\r\n\r\n @property\r\n def folder_path(self):\r\n return os.path.join(os.path.dirname(self.file_path), \"\")\r\n\r\n @property\r\n def file_name(self):\r\n return os.path.basename(self._file_path)\r\n\r\n @property\r\n def file_name_no_ext(self):\r\n fn, _ = os.path.splitext(self.file_name)\r\n return fn\r\n\r\n @property\r\n def file_ext(self):\r\n _, ext = os.path.splitext(self.file_name)\r\n return ext\r\n\r\n @property\r\n def name(self):\r\n return self.file_name_no_ext\r\n\r\n @property\r\n def date(self):\r\n return self.date_time.date()\r\n\r\n @property\r\n def time(self):\r\n return self.date_time.time()\r\n\r\n @property\r\n def date_time(self):\r\n if not self._date_time and self.db_linked:\r\n self._date_time = self._database.query_one(\r\n command=\"SELECT\",\r\n columns=\"date_time\",\r\n additional=\"ORDER BY date_time ASC\",\r\n FilePath=self.file_path,\r\n )[0]\r\n self._date_time = pd.to_datetime(self._date_time)\r\n return self._date_time\r\n\r\n @property\r\n def date_str(self):\r\n return dt.strftime(self.date_time, \"%Y-%m-%d %H:%M:%S\")\r\n\r\n @property\r\n def year(self):\r\n return self.date_time.year\r\n\r\n @property\r\n def month(self):\r\n return self.date_time.month\r\n\r\n @property\r\n def day(self):\r\n return self.date_time.day\r\n\r\n @property\r\n def hour(self):\r\n return self.date_time.hour\r\n\r\n @property\r\n def minute(self):\r\n return self.date_time.minute\r\n\r\n @property\r\n def second(self):\r\n return self.date_time.second\r\n\r\n @property\r\n def plant(self):\r\n return self._plant.lower()\r\n\r\n @property\r\n def camera(self):\r\n return self._camera.lower()\r\n\r\n @property\r\n def view_option(self):\r\n return self._view_option.lower()\r\n\r\n @property\r\n def experiment(self):\r\n return self._exp.lower()\r\n\r\n @property\r\n def condensed_date(self):\r\n return dt.strftime(self.date_time, \"%Y%m%d-%H%M%S\")\r\n\r\n @property\r\n def luid(self):\r\n return f'{self.experiment}_{self.plant}_{dt.strftime(self.date_time, \"%Y%m%d%H%M%S\")}_{self.camera}_{self.view_option}'\r\n\r\n @property\r\n def is_vis(self):\r\n return True\r\n\r\n @property\r\n def is_fluo(self):\r\n return False\r\n\r\n @property\r\n def is_nir(self):\r\n return False\r\n\r\n @property\r\n def is_msp(self):\r\n return False\r\n\r\n @property\r\n def is_cf_calc(self):\r\n return False\r\n\r\n @property\r\n def is_cf_raw(self):\r\n return False\r\n\r\n @property\r\n def is_cf_csv(self):\r\n return False\r\n\r\n @property\r\n def is_cf_pim(self):\r\n return False\r\n\r\n @property\r\n def is_heliasen(self):\r\n return False\r\n\r\n @property\r\n def channels(self):\r\n return [ci[1] for ci in self.channels_data]\r\n\r\n @property\r\n def channels_data(self):\r\n return [ci for ci in ipc.create_channel_generator()]\r\n\r\n @property\r\n def linked_images(self):\r\n return self._linked_images\r\n\r\n @property\r\n def blob_path(self):\r\n if not self._blob_path and self.db_linked is True:\r\n try:\r\n self._blob_path = self._database.query_one(\r\n command=\"SELECT\",\r\n columns=\"blob_path\",\r\n FilePath=self.file_path,\r\n )[0]\r\n except Exception as e:\r\n self._blob_path = \"\"\r\n return self._blob_path\r\n\r\n @property\r\n def cache_file_path(self):\r\n if not self._cache_file_path and self.db_linked is True:\r\n if os.path.isdir(ipso_folders.get_path(\"mass_storage\", False)):\r\n self._cache_file_path = os.path.join(\r\n ipso_folders.get_path(\"mass_storage\", False),\r\n self.experiment,\r\n self.file_name,\r\n )\r\n else:\r\n self._cache_file_path = \"\"\r\n return self._cache_file_path\r\n\r\n\r\nclass FileHandlerDefault(FileHandlerBase):\r\n def __init__(self, **kwargs):\r\n self._file_path = kwargs.get(\"file_path\", \"\")\r\n if self._file_path:\r\n self._plant = self.file_name_no_ext\r\n self._camera = \"unknown\"\r\n _, ext_ = os.path.splitext(self.file_name)\r\n self._view_option = ext_ if ext_ else \"unknown\"\r\n try:\r\n self._exp = os.path.basename(os.path.dirname(self.file_path))\r\n except Exception as e:\r\n logger.exception(f\"Unable to extract extension: {repr(e)}\")\r\n self._exp = \"\"\r\n try:\r\n self._date_time = dt.fromtimestamp(os.path.getmtime(self.file_path))\r\n except Exception as e:\r\n logger.exception(f\"Unable to extract date from file because: {repr(e)}\")\r\n self._date_time = dt.now()\r\n self._date_time = self._date_time.replace(microsecond=0)\r\n\r\n self.update(**kwargs)\r\n\r\n @classmethod\r\n def probe(cls, file_path, database):\r\n return 0\r\n\r\n\r\ndef file_handler_factory(file_path: str, database) -> FileHandlerBase:\r\n # Build unique class list\r\n file_handlers_list = get_module_classes(\r\n package=ipso_phen.ipapi.file_handlers,\r\n class_inherits_from=FileHandlerBase,\r\n remove_abstract=True,\r\n )\r\n file_handlers_list = [\r\n fh\r\n for fh in file_handlers_list\r\n if inspect.isclass(fh) and callable(getattr(fh, \"probe\", None))\r\n ]\r\n\r\n # Create objects\r\n best_score = 0\r\n best_class = None\r\n for cls in file_handlers_list:\r\n if cls.probe(file_path, database) > best_score:\r\n best_score = cls.probe(file_path, database)\r\n best_class = cls\r\n\r\n if best_class:\r\n return best_class(file_path=file_path, database=database)\r\n else:\r\n return FileHandlerDefault(file_path=file_path, database=database)\r\n","sub_path":"file_handlers/fh_base.py","file_name":"fh_base.py","file_ext":"py","file_size_in_byte":20776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"500099671","text":"import unittest\nfrom metaquant.databases import GeneOntologyDb as godb\nfrom metaquant.util.utils import DATA_DIR\nimport os\nimport shutil\n\n\nclass TestGeneOntologyDb(unittest.TestCase):\n TEST_DIR = os.path.join(DATA_DIR, 'test', 'go_cache') # downloaded 8/27/18\n db = godb.GeneOntologyDb(TEST_DIR, slim_down=True)\n\n def testDownloadGO(self):\n tmp_dir = os.path.join(DATA_DIR, 'tmp_go_data_dwnld')\n os.mkdir(tmp_dir)\n try:\n go = godb.GeneOntologyDb(tmp_dir)\n expected_contents = [os.path.join(tmp_dir, file)\n for file in ['go-basic.obo', 'goslim_generic.obo']]\n for content in expected_contents:\n self.assertTrue(os.path.exists(content))\n # make sure parsed correctly\n self.assertEqual('biological_process', go.gofull['GO:0008150'].name)\n finally:\n shutil.rmtree(tmp_dir)\n\n def testMapIdToSlim(self):\n # the case where the test term has a parent in the slim set\n testid = \"GO:0001842\" # neural fold formation\n # closest ancestor in slim is GO:0048646, anatomical structure formation involved in morphogenesis\n exp_closest = \"GO:0048646\"\n obs_closest = self.db.map_id_to_slim(testid)\n self.assertEqual(exp_closest, obs_closest)\n\n # case where test term has a grandparent in the slim set\n test_grand_id = \"GO:0007623\" # circadian rhythm\n # closest ancestor in slim is GO:0008150, biological process\n exp_grand_closest = \"GO:0008150\"\n obs_grand_closest = self.db.map_id_to_slim(test_grand_id)\n self.assertEqual(exp_grand_closest, obs_grand_closest)\n\n # case where go term is not in full set\n test_gibberish = \"gibberish\"\n exp_result = 'unknown'\n obs_result = self.db.map_id_to_slim(test_gibberish)\n self.assertEqual(exp_result, obs_result)\n\n def testMapSetToSlim(self):\n # use the same terms as in testMapIdToSlim\n test_set = {\"GO:0001842\", \"GO:0007623\", \"gibberish\"}\n exp_result = {\"GO:0001842\": \"GO:0048646\",\n \"GO:0007623\": \"GO:0008150\",\n \"gibberish\": 'unknown'}\n obs_result = self.db.map_set_to_slim(test_set)\n self.assertDictEqual(exp_result, obs_result)\n\n def testGetChildren(self):\n testid = \"GO:0098632\" # cell-cell adhesion mediator activity\n # expected children\n exp_children = {\"GO:0086080\",\n \"GO:0098641\"}\n self.assertSetEqual(exp_children, self.db.get_children(testid))\n\n def testGetChildren_Unknown(self):\n testid = \"notagoterm\"\n self.assertSetEqual(self.db.get_children(testid), set())\n\n def testGetDescendants(self):\n testid = \"GO:0007044\" # cell-substrate junction assembly\n # two children, three descendants:\n # GO:0007045\n # - GO:0048041\n # GO:0031581\n exp_descendants = {\"GO:0007045\",\n \"GO:0048041\",\n \"GO:0031581\"}\n act_descendants = self.db.get_descendants(testid)\n self.assertSetEqual(exp_descendants, act_descendants)\n\n def testGetDescendants_Unknown(self):\n testid = \"notagoterm\"\n self.assertSetEqual(self.db.get_descendants(testid), set())\n\n def testGetParents(self):\n testid = \"GO:0044406\" # cell-cell adhesion mediator activity\n # expected parents\n exp_parents = {\"GO:0022610\",\n \"GO:0051704\"}\n self.assertSetEqual(exp_parents, self.db.get_parents(testid))\n\n def testGetParents_Unknown(self):\n testid = \"notagoterm\"\n self.assertSetEqual(self.db.get_parents(testid), set())\n\n def testGetAncestors(self):\n testid = \"GO:0016043\" # cellular component organization\n # two parents and one grandparent\n exp_ancestors = {\"GO:0009987\",\n \"GO:0071840\",\n \"GO:0008150\"}\n act_ancestors = self.db.get_ancestors(testid)\n self.assertSetEqual(exp_ancestors, act_ancestors)\n\n def testGetAncestors_Unknown(self):\n testid = \"notagoterm\"\n self.assertSetEqual(self.db.get_ancestors(testid), set())\n","sub_path":"tests/testGeneOntologyDb.py","file_name":"testGeneOntologyDb.py","file_ext":"py","file_size_in_byte":4226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"593902205","text":"\"\"\"Users Urls.\"\"\"\nfrom django.contrib.auth import views as auth_views\nfrom django.urls import path\nfrom . import views\n\napp_name = 'users'\n\nurlpatterns = [\n\n # Users Views.\n path(\n 'signup/',\n views.signup,\n name='signup'\n ),\n path(\n 'logout/',\n views.logout_view,\n name='logout'\n ),\n path(\n 'login/',\n auth_views.LoginView.as_view(\n template_name='users/login.html'\n )\n ),\n\n]\n","sub_path":"src/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"62356875","text":"\"\"\"Functions to perform analysis of a flow list.\"\"\"\nimport pandas as pd\n\n\ndef count_flows_by_class(flowlist):\n \"\"\"\n Counts all and preferred flows by class.\n\n :param flowlist: A FlowList in standard format\n :return: pandas df with 'Class','No. of Flows','No. of Preferred Flows'\n \"\"\"\n fl_all = flowlist.groupby(['Class'])['Flow UUID'].count().reset_index()\n fl_pref = flowlist.groupby(['Class'])['Preferred'].sum().reset_index()\n fl_combined = pd.merge(fl_all, fl_pref, on=['Class'])\n fl_combined = fl_combined.rename(columns={'Flow UUID': 'No. of Flows',\n 'Preferred': 'No. of Preferred Flows'})\n total_flows = fl_combined['No. of Flows'].sum()\n fl_combined['Percent of Flows'] = fl_combined['No. of Flows'].\\\n apply(lambda x: str((x / total_flows) * 100) + '%')\n total_row = {'Class': 'TOTAL', 'No. of Flows': total_flows,\n 'No. of Preferred Flows': fl_combined['No. of Preferred Flows'].sum()}\n fl_combined = fl_combined.append(total_row, ignore_index=True)\n return fl_combined\n\n\ndef list_contexts(flowlist):\n \"\"\"Displays list of contexts along with 1 if the context is present for that flowclass.\n Can send a preferred list or\n :param flowlist: A FlowList in standard format\n :return: pandas df with 'Context',plus columns for all flow classes\n \"\"\"\n contexts = flowlist[['Context', 'Class']]\n contexts = contexts.drop_duplicates()\n contexts['Num'] = 1\n context_counts = contexts.pivot_table(index='Context', columns='Class',\n values='Num', aggfunc='count',\n fill_value='0').reset_index()\n return context_counts\n\n\ndef count_flowables_by_class(flowlist):\n \"\"\"\n Counts flowables by class\n :param flowlist: A FlowList in standard format\n :return: pandas df with 'Class' and counts of unique flowables\n \"\"\"\n flowables_by_class = flowlist[['Class', 'Flowable']]\n flowables_by_class = flowables_by_class.drop_duplicates()\n flowables_by_class_count = flowables_by_class.groupby('Class')['Flowable'].count().reset_index()\n total = flowables_by_class_count['Flowable'].sum()\n flowables_by_class_count['Percent'] = flowables_by_class_count['Flowable'].apply(\n lambda x: str((x / total) * 100) + '%')\n total_row = {'Class': 'TOTAL', 'Flowable': total}\n flowables_by_class_count = flowables_by_class_count.append(total_row, ignore_index=True)\n return flowables_by_class_count\n","sub_path":"fedelemflowlist/analysis/flow_list_analysis.py","file_name":"flow_list_analysis.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"176892180","text":"# Create your views here.\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom c4.board import Board, HTMLBoardView\n\n\ndef game(request, reset_game=False):\n b = Board()\n v = HTMLBoardView(b)\n\n if not reset_game and request.POST.has_key(\"state\"):\n b.fromString(request.POST[\"state\"])\n\n if request.method == \"POST\":\n column = v.extractMove(request)\n if column >= 0:\n b.gameTurn(column)\n\n return render_to_response('game-form.html',\n {'board': v.asHTML(),\n 'message': v.getMessage(),\n 'state': b.asString()\n }\n )\n\ndef newgame(request):\n return game(request, reset_game=True)","sub_path":"Connect4/c4form/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"328204687","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom tde import tde\n\n# Script to test optimization\n# tri dislocation parameters\npr = 0.25\nss = -1.\nts = 0.\nds = 0.\nN = 30\n\nsx, sy, sz = np.meshgrid(np.linspace(0, 100, N), np.linspace(0, 100, N), 0)\n\nsxr = sx.ravel(order='F')\nsyr = sy.ravel(order='F')\nszr = sz.ravel(order='F')\n\nX = np.array([40., 60., 40.])\nY = np.array([50., 50., 30.])\nZ = np.array([0., 0., 20.])\n\n# S = tde.calc_tri_strains(sxr, syr, szr, X, Y, Z, pr, ss, ts, ds)\n\nfor i in range(100):\n U = tde.calc_tri_displacements(sxr, syr, szr, X, Y, Z, pr, ss, ts, ds)\n\n","sub_path":"src/tri_dislocations/tests/test_tris_optimize.py","file_name":"test_tris_optimize.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"53500317","text":"from .form_product import *\nfrom ...models.db_product import *\nfrom .productcategory import RepoProductCategory\nfrom .subproductcategory import RepoSubProductCategory\nfrom flask import jsonify\nimport shortuuid\nimport os\n\nclass BaseSub():\n def __init__(self,app,id,detail_id):\n self.title = None\n self.app = app\n self.parent_id = int(id)\n self.detail_id = detail_id\n self.update_form_js = None\n self.allow_insert = True\n self.allow_update = True\n self.allow_delete = True\n \n def parent(self,session):\n if self.parent_id>0:\n return session.query(Product).filter(Product.id==self.parent_id).first()\n\n def form_data(self):\n with self.app.db_session.session_scope() as session: \n if self.parent_id>0:\n db_data = session.query(Product).get(self.parent_id)\n else:\n db_data = Product()\n\n return {\"name\":db_data.name,\"sku\":db_data.sku,\"description\":db_data.description,\n \"order\":db_data.order,\n \"category\":db_data.category.id if db_data.category else \"\",\n \"isvariant\":'1' if bool(db_data.isvariant) == True else '0',\n \"active\":'1' if bool(db_data.active) == True else '0'}\n \n def details(self,dict_replace,template):\n return\n \n def prepare_form(self,obj):\n return self.update_form(obj=obj)\n \n def skip_details(self):\n #有時雖有details功能, 但特殊情況下跳過, 直接進入form\n return False\n \nclass SubBasic(BaseSub):\n def __init__(self,app,id,detail_id):\n super().__init__(app,id,detail_id)\n self.update_form = Update_basic_Form\n \n def update(self,session,db_item,item):\n db_item.name = item.name\n db_item.sku = item.sku\n db_item.description = item.description\n db_item.order = item.order\n db_item.isvariant = True if item.isvariant=='1' else False\n db_item.active = True if item.active=='1' else False\n category = session.query(ProductCategory).filter(ProductCategory.id==item.category).first()\n db_item.category = category\n #raise Exception(category)\n \"\"\"todo: 如果, 要檢查什麼? sku,category,image,\n if db_item.active == True:\n \n \"\"\"\n \n\n def prepare_form(self,obj):\n if int(self.parent_id)==0:\n #編輯時使用表單(有些欄位不能再更改,但要顯示...如何做)\n self.update_form = Insert_basic_Form\n form = self.update_form(obj=obj) \n prductCategory = RepoProductCategory()\n form.category.choices = form.category.choices + prductCategory.get_tree_for_form() #get_tree()\n return form\n \nclass SubCategory(BaseSub):\n def __init__(self,app,id,detail_id):\n super().__init__(app,id,detail_id)\n self.update_form = Update_subcategory_Form\n \n def form_data(self):\n if self.detail_id and int(self.detail_id)>0:\n with self.app.db_session.session_scope() as session:\n db_data = session.query(SubProductCategory).get(self.detail_id)\n #raise Exception(db_data.id)\n return {\"subcategory\":db_data.id,\"original\":db_data.id}\n else:\n db_data = SubProductCategory()\n return {\"subcategory\":\"\",\"original\":0}\n \n def prepare_form(self,obj):\n #新增時使用表單\n\n form = self.update_form(obj=obj)\n subprductCategory = RepoSubProductCategory()\n form.subcategory.choices = form.subcategory.choices + subprductCategory.get_tree_for_form()\n return form\n\n def details(self,dict_replace,template): \n details = []\n with self.app.db_session.session_scope() as session:\n product = self.parent(session)\n for row in product.sub_categorys:\n dict_replace.update({\"parent_id\":product.id,\n \"tooltip_title\":row.name,\n \"rowid\":row.id})\n \n details.append([template(dict_replace)]+\n [row.name])\n \n return {'fields':['分類'],'data':details} \n \n def update(self,session,db_item,item):\n #若沒有改變, 則退出\n if int(item.subcategory) == int(item.original):\n raise Exception(\"分類沒有改變,取消更新\") \n \n #檢查是否己有同id\n subcategory = session.query(SubProductCategory).filter(SubProductCategory.id==item.subcategory).first()\n if subcategory not in db_item.sub_categorys:\n #刪除舊的:original, 新增新的:subcategory\n if int(item.original)>0:\n original = session.query(SubProductCategory).filter(SubProductCategory.id==item.original).first()\n db_item.sub_categorys.remove(original)\n db_item.sub_categorys.append(subcategory)\n else:\n raise Exception(\"己有同樣分類, 無法再新增\")\n \n def delete(self,session,db_item,dels):\n for _del in dels:\n subcategory = session.query(SubProductCategory).filter(SubProductCategory.id==_del).first()\n db_item.sub_categorys.remove(subcategory)\n \nclass SubVariant(BaseSub):\n def __init__(self,app,id,detail_id):\n super().__init__(app,id,detail_id)\n self.update_form = Update_variant_Form\n \n def form_data(self):\n if self.detail_id and int(self.detail_id)>0:\n with self.app.db_session.session_scope() as session:\n db_data = session.query(Variant).get(self.detail_id)\n return {\"variant\":db_data.id,\"original\":db_data.id}\n else:\n db_data = ProductSku()\n return {\"variant\":db_data.id,\"original\":0}\n \n def prepare_form(self,obj):\n form = self.update_form(obj=obj)\n with self.app.db_session.session_scope() as session:\n choices = [(str(i.id),i.variant) for i in session.query(Variant).all()]\n form.variant.choices = form.variant.choices + choices\n return form\n \n def validate_update(self,db_item,item):\n #todo: 檢查是否己有sku, 或己銷售, 若有, 則不能更新, 需視為新商品另增一個\n if db_item.skus:\n raise Exception(\"己有庫存, 屬性禁止更新, 若有不同屬性商品請另建新商品!\")\n \n def update(self,session,db_item,item):\n self.validate_update(db_item,item)\n #若沒有改變, 則退出\n if int(item.variant) == int(item.original):\n raise Exception(\"所選屬性沒有改變,取消更新\") \n \n #檢查是否己有同id\n variant = session.query(Variant).filter(Variant.id==item.variant).first()\n if variant not in db_item.variants:\n \n #刪除舊的:original, 新增新的:subcategory\n if int(item.original)>0:\n original = session.query(Variant).filter(Variant.id==item.original).first()\n db_item.variants.remove(original)\n db_item.variants.append(variant)\n else:\n raise Exception(\"己有同樣屬性, 無法再新增\")\n \n def details(self,dict_replace,template): \n details = []\n with self.app.db_session.session_scope() as session:\n product = self.parent(session)\n for row in product.variants:\n dict_replace.update({\"parent_id\":product.id,\n \"tooltip_title\":row.variant,\n \"rowid\":row.id})\n \n details.append([template(dict_replace)]+[row.variant])\n return {'fields':['屬性'],'data':details} \n \n def delete(self,session,db_item,dels):\n self.validate_update(db_item,dels)\n for _del in dels:\n variant = session.query(Variant).filter(Variant.id==_del).first()\n db_item.variants.remove(variant)\n #raise Exception(str(variant))\n\nclass SubSku(BaseSub):\n def __init__(self,app,id,detail_id):\n super().__init__(app,id,detail_id)\n self.update_form = Update_sku_Form\n self.update_form_js = 'sku.js'\n self.isvariant = False # flag 是否是多屬性商品\n with self.app.db_session.session_scope() as session:\n product = self.parent(session)\n self.isvariant = product.isvariant\n if self.isvariant:\n self.update_form = Update_skus_Form\n \n def form_data(self):\n with self.app.db_session.session_scope() as session:\n if self.detail_id and int(self.detail_id)>0:\n db_data = session.query(ProductSku).get(self.detail_id)\n else:\n db_data = ProductSku()\n \n data = {\"sku\":db_data.sku,\"price\":db_data.price,\"quantity\":db_data.quantity,\n \"lot_maintain\":'1' if bool(db_data.lot_maintain) == True else '0',\n \"active\":'1' if bool(db_data.active) == True else '0'}\n if db_data.values:\n #編輯頁時, 顯示value名稱\n data.update({\"values\":','.join([str(i.value) for i in db_data.values])})\n return data \n \n def validate_update(self,db_item,item):\n #todo: 檢查是否己有sku, 或己銷售, 若有, 則不能更新, 需視為新商品另增一個\n if db_item.skus:\n raise Exception(\"己有庫存, 屬性禁止更新, 若有不同屬性商品請另建新商品!\")\n \n def update(self,session,db_item,item):\n #self.validate_update(db_item,item)\n #values,sku 只限新增,更新不可\n if int(self.detail_id)==0:\n sku = ProductSku()\n sku.sku = item.sku\n sku.id_product = db_item.id\n \n if self.isvariant:\n #todo:新增variant values,並檢查是否都有齊全,且不得重複\n values = str(item.values).split(',')\n for v in values:\n value = session.query(VariantValues).filter(VariantValues.id==int(v)).first()\n sku.values.append(value)\n \n else:\n sku = session.query(ProductSku).filter(ProductSku.id==self.detail_id).first()\n #編輯只限更新以下... \n sku.price = int(item.price)\n sku.quantity = int(item.quantity)\n sku.lot_maintain = True if item.lot_maintain=='1' else False\n sku.active = True if item.active=='1' else False\n \n session.add(sku)\n \n \n def details(self,dict_replace,template): \n details = []\n with self.app.db_session.session_scope() as session:\n product = self.parent(session)\n for row in product.skus:\n dict_replace.update({\"parent_id\":product.id,\n \"tooltip_title\":row.sku,\n \"rowid\":row.id})\n \n details.append([template(dict_replace)]+\n [row.sku,row.price,row.quantity])\n \n return {'fields':['副型號','售價','存量'],'data':details} \n \n def prepare_form(self,obj):\n def get_variantvalues():\n #新增sku時, 提供選項, \n #若是編輯時, 則只提供sku 的values\n variants = []\n with self.app.db_session.session_scope() as session:\n \n if int(self.detail_id)>0: #編輯狀態\n sku = session.query(ProductSku).get(self.detail_id)\n for value in sku.values:\n variants.append((value.id,f'{value.Variant.variant}_{value.value}'))\n else: #新增狀態,\n product = self.parent(session)\n for variant in product.variants:\n for value in variant.values: #要如何分辨不同的variant?\n variants.append((value.id,f'{variant.variant}_{value.value}'))\n #raise Exception(variants) \n return variants\n \n\n form = self.update_form(obj=obj) \n if self.isvariant:\n choices = get_variantvalues()\n form.variantvalues_source.choices = form.variantvalues_source.choices + get_variantvalues()\n #form.variantvalues_source.default = choices[0][0]\n return form\n \n def delete(self,session,db_item,dels):\n #self.validate_update(db_item,dels)\n for _del in dels:\n #delete cascade sku.values\n sku = session.query(ProductSku).filter(ProductSku.id==_del).first()\n session.delete(sku)\n \n def skip_details(self):\n #檢查, 是否沒有屬性, 即不需進入details, 直接進入form\n #且必須填充 self.detail_id\n with self.app.db_session.session_scope() as session:\n product = self.parent(session)\n if not product.isvariant:\n self.detail_id = product.skus[0].id if product.skus else 0\n return True\n return False\n \nclass SubImage(BaseSub):\n def __init__(self,app,id,detail_id):\n super().__init__(app,id,detail_id)\n self.update_form = Update_image_Form\n self.update_form_js = 'image.js'\n self.allow_update = False\n \n def form_data(self):\n if self.detail_id and int(self.detail_id)>0:\n with self.app.db_session.session_scope() as session:\n db_data = session.query(ProductImage).get(self.detail_id)\n #raise Exception(db_data.id)\n return {\"file_name\":db_data.file_name}\n else:\n db_data = SubProductCategory()\n return {\"file_name\":\"\"}\n \n def update(self,session,db_item,item):\n from ...share.image import thumbnail,resize_paste,resize_crop,logo_watermark,text_watermark\n \"\"\"\n 此功能只限新增\n 必須有圖檔,製圖, 存id_product, active , file_name\n 不提供編輯\n \"\"\"\n #排除編輯的情況\n if int(self.detail_id)>0:\n return \n \n if int(self.detail_id)==0:\n image = ProductImage()\n image.file_name = f'{shortuuid.uuid()}.png'#short_uuid\n image.id_product = db_item.id\n \n\n if item.file:\n \"\"\"\n 處理圖檔\n \"\"\"\n #取路徑檔名\n file_path = os.path.join(\n str(os.path.dirname(self.app.instance_path)),\n 'application',\n self.app.store_config.PRODUCT_IMAGE_PATH,\n image.file_name)\n #先存檔\n \n item.file.save(file_path)\n #raise Exception(file_path)\n #取resize圖\n #raise Exception(item.fill_or_crop == \"1\")\n if item.fill_or_crop == \"1\": #fill\n resize_paste(file_path,self.app.store_config.PRODUCT_IMAGE_SIZE)\n else:#crop\n resize_crop(file_path,self.app.store_config.PRODUCT_IMAGE_SIZE)\n #raise Exception(item.watermark) \n if item.watermark:\n text_watermark(file_path,\"fuck you\")\n \n #取縮圖\n thumbnail(file_path,200)\n #raise Exception(file_path)\n session.add(image)\n\n def delete(self,session,db_item,dels):\n #self.validate_update(db_item,dels)\n for _del in dels:\n #delete cascade sku.values\n img = session.query(ProductImage).filter(ProductImage.id==_del).first()\n #若有圖檔, 刪實體檔案\n os.remove(os.path.join(str(os.path.dirname(self.app.instance_path)),\n 'application',\n self.app.store_config.PRODUCT_IMAGE_PATH,\n img.file_name))\n os.remove(os.path.join(str(os.path.dirname(self.app.instance_path)),\n 'application',\n self.app.store_config.PRODUCT_IMAGE_PATH,\n f\"{os.path.splitext(img.file_name)[0]}_thumbnail.png\"))\n session.delete(img)\n \n def details(self,dict_replace,template): \n details = []\n load_image_failed = f\"\"\"onerror=\\\"this.onerror=null;this.src='{self.app.store_config.LOAD_IMAGE_FAILED_REPLACE}';\\\"\"\"\"\n with self.app.db_session.session_scope() as session:\n product = self.parent(session)\n for row in product.images:\n dict_replace.update({\"parent_id\":product.id,\n \"tooltip_title\":row.file_name,\n \"rowid\":row.id})\n \n details.append([template(dict_replace)]+\n [' 1:\n i = min(offset + fib2, n - 1)\n if arr[i] < x:\n fib = fib1\n fib1 = fib2\n fib2 = fib - fib1\n offset = i\n elif arr[i] > x:\n fib = fib2\n fib1 = fib1 - fib2\n fib2 = fib - fib1\n else:\n return i\n if fib1 and arr[offset+1] == x:\n return offset + 1\n return -1\n\n# Тест\nsp = [23, 51, 123, 657, 12315, 668, 768, 99, 86, 234, 99, 321]\nprint(fibsearch(sp, 12315))\n# Программа выведет индекс элемента 12315\n","sub_path":"fibsearch.py","file_name":"fibsearch.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"476370249","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport pprint\nimport re\nimport subprocess\nimport json\nimport os\nimport platform\n\ntry:\n import StringIO as io\nexcept ImportError:\n import io\n\nfunction_defs = {\n '__istype': ('uint32', ('__darwin_ct_rune_t', 'uint32')),\n '__isctype': ('__darwin_ct_rune_t', ('__darwin_ct_rune_t', 'uint32')),\n '__tolower': ('__darwin_ct_rune_t', ('__darwin_ct_rune_t',)),\n '__toupper': ('__darwin_ct_rune_t', ('__darwin_ct_rune_t',)),\n '__maskrune': ('uint32', ('__darwin_ct_rune_t', 'uint32')),\n\n # These are provided by functions-Darwin.go\n '__builtin_fabs': ('double', ('double',)),\n '__builtin_fabsf': ('float', ('float',)),\n '__builtin_fabsl': ('double', ('double',)),\n '__builtin_inf': ('double', ()),\n '__builtin_inff': ('float', ()),\n '__builtin_infl': ('double', ()),\n}\n\nfunction_subs = {\n # math.h\n 'acos': 'math.Acos',\n 'asin': 'math.Asin',\n 'atan': 'math.Atan',\n 'atan2': 'math.Atan2',\n 'ceil': 'math.Ceil',\n 'cos': 'math.Cos',\n 'cosh': 'math.Cosh',\n 'exp': 'math.Exp',\n 'fabs': 'math.Abs',\n 'floor': 'math.Floor',\n 'fmod': 'math.Mod',\n 'ldexp': 'math.Ldexp',\n 'log': 'math.Log',\n 'log10': 'math.Log10',\n 'pow': 'math.Pow',\n 'sin': 'math.Sin',\n 'sinh': 'math.Sinh',\n 'sqrt': 'math.Sqrt',\n 'tan': 'math.Tan',\n 'tanh': 'math.Tanh',\n\n # stdio\n 'printf': 'fmt.Printf',\n 'scanf': 'fmt.Scanf',\n}\n\n# TODO: Some of these are based on assumtions that may not be true for all\n# architectures (like the size of an int). At some point in the future we will\n# need to find out the sizes of some of there and pick the most compatible type.\n# \n# Please keep them sorted by name.\nsimple_resolve_types = {\n 'bool': 'bool',\n 'char *': 'string',\n 'char': 'byte',\n 'char*': 'string',\n 'double': 'float64',\n 'float': 'float32',\n 'int': 'int',\n 'long double': 'float64',\n 'long int': 'int32',\n 'long long': 'int64',\n 'long unsigned int': 'uint32',\n 'long': 'int32',\n 'short': 'int16',\n 'signed char': 'int8',\n 'unsigned char': 'uint8',\n 'unsigned int': 'uint32',\n 'unsigned long long': 'uint64',\n 'unsigned long': 'uint32',\n 'unsigned short': 'uint16',\n 'void *': 'interface{}',\n 'void': '',\n\n 'const char *': 'string',\n\n # Mac specific\n '__darwin_ct_rune_t': '__darwin_ct_rune_t',\n\n # These are special cases that almost certainly don't work. I've put them\n # here becuase for whatever reason there is no suitable type or we don't\n # need these platform specific things to be implemented yet.\n '__builtin_va_list': 'int64',\n '__darwin_pthread_handler_rec': 'int64',\n '__int128': 'int64',\n '__mbstate_t': 'int64',\n '__sbuf': 'int64',\n '__sFILEX': 'interface{}',\n '__va_list_tag': 'interface{}',\n 'FILE': 'int64',\n}\n\ntypes_already_defined = set([\n # Linux specific\n '_LIB_VERSION_TYPE'\n])\n\nimports = [\"fmt\"]\n\nclass NoSuchTypeException(Exception):\n pass\n\ndef add_import(import_name):\n if import_name not in imports:\n imports.append(import_name)\n\ndef is_keyword(w):\n return w in ('char', 'long', 'struct', 'void')\n\ndef is_identifier(w):\n return not is_keyword(w) and re.match('[_a-zA-Z][_a-zA-Z0-9]*', w)\n\ndef resolve_type(s):\n # Remove any whitespace or attributes that are not relevant to Go.\n s = s.replace('const ', '')\n s = s.replace('*__restrict', '*')\n s = s.replace('*restrict', '*')\n s = s.strip(' \\t\\n\\r')\n\n # If the type is already defined we can proceed with the same name.\n if s in types_already_defined:\n return s\n\n # The simple resolve types are the types that we know there is an exact Go\n # equivalent. For example float, int, etc.\n if s in simple_resolve_types:\n return simple_resolve_types[s]\n\n # Structures are by name.\n if s[:7] == 'struct ':\n if s[-1] == '*':\n return '*' + s[7:-2]\n else:\n return s[7:]\n\n # Enums are by name.\n if s[:5] == 'enum ':\n if s[-1] == '*':\n return '*' + s[5:-2]\n else:\n return s[5:]\n\n # I have no idea how to handle this yet.\n if 'anonymous union' in s:\n return 'interface{}'\n\n # It may be a pointer of a simple type. For example, float *, int *, etc.\n try:\n if re.match(r\"[\\w ]+\\*\", s):\n return '*' + resolve_type(s[:-2].strip())\n except NoSuchTypeException:\n # Keep trying the next one.\n pass\n\n # Function pointers are not yet supported. In th mean time they will be\n # replaced with a type that certainly wont work until we can fix this\n # properly.\n search = re.search(r\"[\\w ]+\\(\\*.*?\\)\\(.*\\)\", s)\n if search:\n return 'interface{}'\n search = re.search(r\"[\\w ]+ \\(.*\\)\", s)\n if search:\n return 'interface{}'\n\n try:\n # It could be an array of fixed length.\n search = re.search(r\"([\\w ]+)\\[(\\d+)\\]\", s)\n if search:\n return '[%s]%s' % (search.group(2), resolve_type(search.group(1)))\n\n except NoSuchTypeException as e:\n # Make the nested exception message more contextual.\n raise NoSuchTypeException(e.message + \" (from '%s')\" % s)\n\n raise NoSuchTypeException(\"'%s'\" % s)\n\ndef cast(expr, from_type, to_type):\n from_type = resolve_type(from_type)\n to_type = resolve_type(to_type)\n\n if from_type == to_type:\n return expr\n\n types = ('int', 'int64', 'uint32', '__darwin_ct_rune_t', 'byte', 'float32',\n 'float64')\n if from_type in types and to_type == 'bool':\n return '%s != 0' % expr\n\n if from_type == '*int' and to_type == 'bool':\n return '%s != nil' % expr\n\n if from_type in types and to_type in types:\n return '%s(%s)' % (to_type, expr)\n\n return '__%s_to_%s(%s)' % (from_type, to_type, expr)\n\ndef print_line(out, line, indent):\n out.write('%s%s\\n' % ('\\t' * indent, line))\n\ndef render_expression(node):\n if node['node'] == 'BinaryOperator':\n operator = node['operator']\n\n left, left_type = render_expression(node['children'][0])\n right, right_type = render_expression(node['children'][1])\n\n return_type = 'bool'\n if operator in ('|', '&', '+', '-', '*', '/'):\n # TODO: The left and right type might be different\n return_type = left_type\n\n if operator == '&&':\n left = cast(left, left_type, return_type)\n right = cast(right, right_type, return_type)\n\n return '%s %s %s' % (left, operator, right), return_type\n\n if node['node'] == 'UnaryOperator':\n operator = node['operator']\n expr = render_expression(node['children'][0])\n\n if operator == '!':\n return '%s(%s)' % ('__not_%s' % expr[1], expr[0]), expr[1]\n\n if operator == '*':\n if expr[1] == 'const char *':\n return '%s[0]' % expr[0], 'char'\n\n return '*%s' % expr[0], 'int'\n\n if operator == '++':\n return '%s += 1' % expr[0], expr[1]\n\n if operator == '~':\n operator = '^'\n\n return '%s%s' % (operator, expr[0]), expr[1]\n\n if node['node'] == 'StringLiteral':\n return node['value'], 'const char *'\n\n if node['node'] == 'FloatingLiteral':\n return node['value'], 'double'\n\n if node['node'] == 'IntegerLiteral':\n literal = node['value']\n if literal[-1] == 'L':\n literal = '%s(%s)' % (resolve_type('long'), literal[:-1])\n\n return literal, 'int'\n\n if node['node'] == 'DeclRefExpr':\n name = node['name']\n\n if name == 'argc':\n name = 'len(os.Args)'\n add_import(\"os\")\n elif name == 'argv':\n name = 'os.Args'\n add_import(\"os\")\n\n return name, node['type']\n\n if node['node'] == 'ImplicitCastExpr':\n return render_expression(node['children'][0])\n\n if node['node'] == 'CallExpr':\n children = node['children']\n func_name = render_expression(children[0])[0]\n\n func_def = function_defs[func_name]\n\n if func_name in function_subs:\n func_name = function_subs[func_name]\n add_import(func_name.split('.')[0])\n\n args = []\n i = 0\n for arg in children[1:]:\n e = render_expression(arg)\n\n if i > len(func_def[1]) - 1:\n # This means the argument is one of the varargs so we don't know\n # what type it needs to be cast to.\n args.append(e[0])\n else:\n args.append(cast(e[0], e[1], func_def[1][i]))\n\n i += 1\n\n return '%s(%s)' % (func_name, ', '.join(args)), func_def[0]\n\n if node['node'] == 'ArraySubscriptExpr':\n children = node['children']\n return '%s[%s]' % (render_expression(children[0])[0],\n render_expression(children[1])[0]), 'unknown1'\n\n if node['node'] == 'MemberExpr':\n children = node['children']\n return '%s.%s' % (render_expression(children[0])[0], node['name']), children[0]['type']\n\n if node['node'] == 'CStyleCastExpr':\n children = node['children']\n return render_expression(children[0])\n\n if node['node'] == 'FieldDecl' or node['node'] == 'VarDecl':\n type = resolve_type(node['type'])\n name = node['name'].replace('used', '')\n\n # Go does not allow the name of a variable to be called \"type\". For the\n # moment I will rename this to avoid the error.\n if name == 'type':\n name = 'type_'\n\n prefix = ''\n if node['node'] == 'VarDecl':\n prefix = 'var '\n\n suffix = ''\n if 'children' in node:\n children = node['children']\n suffix = ' = %s' % render_expression(children[0])[0]\n\n return '%s%s %s%s' % (prefix, name, type, suffix), 'unknown3'\n\n if node['node'] == 'RecordDecl':\n return '/* RecordDecl */', 'unknown5'\n\n if node['node'] == 'ParenExpr':\n a, b = render_expression(node['children'][0])\n return '(%s)' % a, b\n\n raise Exception('render_expression: %s' % node['node'])\n\ndef get_function_params(nodes):\n if 'children' not in nodes:\n return []\n\n return [n for n in nodes['children'] if n['node'] == 'ParmVarDecl']\n\ndef get_function_return_type(f):\n # The type of the function will be the complete prototype, like:\n # \n # __inline_isfinitef(float) int\n # \n # will have a type of:\n #\n # int (float)\n #\n # The arguments will handle themselves, we only care about the\n # return type ('int' in this case)\n return f.split('(')[0].strip()\n\ndef render(out, node, function_name, indent=0, return_type=None):\n if node['node'] == 'TranslationUnitDecl':\n for c in node['children']:\n render(out, c, function_name, indent, return_type)\n return\n\n if node['node'] == 'FunctionDecl':\n function_name = node['name'].strip()\n\n if function_name in ('__istype', '__isctype', '__wcwidth', '__sputc',\n '__inline_signbitf', '__inline_signbitd', '__inline_signbitl'):\n return\n\n has_body = False\n if 'children' in node:\n for c in node['children']:\n if c['node'] == 'CompoundStmt':\n has_body = True\n\n args = []\n for a in get_function_params(node):\n args.append('%s %s' % (a['name'], resolve_type(a['type'])))\n\n if has_body:\n return_type = get_function_return_type(node['type'])\n\n if function_name == 'main':\n print_line(out, 'func main() {', indent)\n else:\n print_line(out, 'func %s(%s) %s {' % (function_name,\n ', '.join(args), resolve_type(return_type)), indent)\n \n for c in node['children']:\n if c['node'] == 'CompoundStmt':\n render(out, c, function_name, indent + 1, node['type'])\n\n print_line(out, '}\\n', indent)\n\n function_defs[node['name']] = (get_function_return_type(node['type']),\n [a['type'] for a in get_function_params(node)])\n\n return\n\n if node['node'] == 'CompoundStmt':\n for c in node['children']:\n render(out, c, function_name, indent, return_type)\n return\n\n if node['node'] == 'IfStmt':\n children = node['children']\n\n e = render_expression(children[0])\n print_line(out, 'if %s {' % cast(e[0], e[1], 'bool'), indent)\n\n render(out, children[1], function_name, indent + 1, return_type)\n\n if len(children) > 2:\n print_line(out, '} else {', indent)\n render(out, children[2], function_name, indent + 1, return_type)\n\n print_line(out, '}', indent)\n\n return\n\n if node['node'] == 'WhileStmt':\n children = node['children']\n\n e = render_expression(children[0])\n print_line(out, 'for %s {' % cast(e[0], e[1], 'bool'), indent)\n\n render(out, children[1], function_name, indent + 1, return_type)\n\n print_line(out, '}', indent)\n\n return\n\n if node['node'] == 'ForStmt':\n children = node['children']\n\n a, b, c = [render_expression(e)[0] for e in children[:3]]\n print_line(out, 'for %s; %s; %s {' % (a, b, c), indent)\n\n render(out, children[3], function_name, indent + 1, return_type)\n\n print_line(out, '}', indent)\n\n return\n\n if node['node'] == 'BreakStmt':\n print_line(out, 'break', indent)\n return\n\n if node['node'] == 'UnaryOperator':\n print_line(out, render_expression(node)[0], indent)\n return\n\n if node['node'] == 'ReturnStmt':\n r = 'return'\n\n if 'children' in node and function_name != 'main':\n expr, type = render_expression(node['children'][0])\n r = 'return ' + cast(expr, type, 'int')\n\n print_line(out, r, indent)\n return\n\n if node['node'] in ('BinaryOperator', 'INTEGER_LITERAL', 'CallExpr'):\n print_line(out, render_expression(node)[0], indent)\n return\n\n if node['node'] == 'TypedefDecl':\n name = node['name'].strip()\n if name in types_already_defined:\n return\n\n types_already_defined.add(name)\n\n # FIXME: All of the logic here is just to avoid errors, it needs to be\n # fixed up.\n if 'struct' in node['type'] or 'union' in node['type']:\n return\n node['type'] = node['type'].replace('unsigned', '')\n if name in ('__builtin_va_list', '__qaddr_t', 'definition',\n '_IO_lock_t', 'va_list', 'fpos_t'):\n return\n\n print_line(out, \"type %s %s\\n\" % (name, resolve_type(node['type'])), indent)\n\n return\n\n if node['node'] == 'EnumDecl':\n return\n\n if node['node'] == 'FieldDecl':\n print_line(out, render_expression(node)[0], indent + 1)\n return\n\n if node['node'] == 'RecordDecl':\n name = node['name'].strip()\n if name in types_already_defined:\n return\n\n types_already_defined.add(name)\n\n if node['kind'] == 'union':\n return\n\n # FIXME\n if name in ('definition', '_IO_FILE'):\n return\n\n print_line(out, \"type %s %s {\" % (name, node['kind']), indent)\n if 'children' in node:\n for c in node['children']:\n render(out, c, function_name, indent + 1)\n print_line(out, \"}\\n\", indent)\n return\n\n if node['node'] == 'DeclStmt':\n for child in node['children']:\n print_line(out, render_expression(child)[0], indent)\n return\n\n if node['node'] == 'VarDecl':\n # FIXME?\n return\n\n raise Exception(node['node'])\n\n# 1. Compile it first (checking for errors)\nc_file_path = sys.argv[1]\n\n# 2. Preprocess\npp = subprocess.Popen([\"clang\", \"-E\", c_file_path], stdout=subprocess.PIPE).communicate()[0]\n\npp_file_path = 'pp.c'\nwith open(pp_file_path, 'wb') as pp_out:\n pp_out.write(pp)\n\n# 3. Generate JSON from AST\nast_pp = subprocess.Popen([\"clang\", \"-Xclang\", \"-ast-dump\", \"-fsyntax-only\", pp_file_path], stdout=subprocess.PIPE)\npp = subprocess.Popen([\"python\", \"ast2json.py\"], stdin=ast_pp.stdout, stdout=subprocess.PIPE).communicate()[0]\n\njson_file_path = 'pp.json'\nwith open(json_file_path, 'w') as json_out:\n json_out.write(pp)\n\nout_file = open('out.go', 'w')\n\nwith open(json_file_path, 'r') as json_in:\n # 3. Parse C and output Go\n go_file_path = '%s.go' % c_file_path.split('/')[-1][:-2]\n go_out = io.StringIO()\n all_json = json_in.read()\n\n try:\n l = json.loads(all_json)\n except ValueError as e:\n # This occurs if the JSON cannot be parsed\n print(all_json)\n raise e\n\n render(go_out, l[0], function_name=None)\n\n out_file.write(\"package main\\n\\n\")\n out_file.write(\"import (\\n\")\n for import_name in sorted(imports):\n if os.path.exists(\"functions-%s-%s.go\" % (platform.system(), import_name)):\n print(\"functions-%s-%s.go\" % (platform.system(), import_name))\n\n out_file.write('\\t\"%s\"\\n' % import_name)\n out_file.write(\")\\n\\n\")\n out_file.write(go_out.getvalue())\n\n # 4. Compile the Go\n #subprocess.call([\"go\", \"run\", \"functions.go\", go_file_path])\n\nprint(\"out.go\")\nprint(\"functions.go\")\nprint(\"functions-%s.go\" % platform.system())\n","sub_path":"c2go.py","file_name":"c2go.py","file_ext":"py","file_size_in_byte":17319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"578923540","text":"import os\nimport sys\nROOT_DIR = os.path.abspath(\"../../../\")\nsys.path.append(ROOT_DIR)\n\nfrom webscraping_tool.scraping.common.local_resource_manager import LocalResourceManager\nfrom webscraping_tool.scraping.cache.cache_manager import CacheTypeManager,CACHE_TYPES\nfrom webscraping_tool.config.config_manager import RESOURCE_PATHS\n\nBASE_URL = \"https://www.imdb.com/\"\n\nACTOR_URL = BASE_URL + '/name/'\nMOVIE_URL = BASE_URL + '/title/'\n\nclass GlobalUrls:\n @staticmethod\n def getBase():\n return BASE_URL\n @staticmethod\n def getActorUrl():\n return ACTOR_URL\n @staticmethod\n def getMovieUrl():\n return MOVIE_URL\n\nclass ResourceLoader:\n __instance = None\n @staticmethod\n def getInstance():\n if ResourceLoader.__instance == None:\n ResourceLoader()\n return ResourceLoader.__instance\n\n def getFileResourceName(self,key):\n return key.upper()+\"_FILE\"\n def getResourceManager(self,key):\n return LocalResourceManager(RESOURCE_PATHS[self.getFileResourceName(key)])\n def getResourceEntityCount(self,key):\n resource_name = self.getFileResourceName(key)\n return CacheTypeManager.getInstance().getCache(CACHE_TYPES[\"ResourceEntityCountsCache\"])[resource_name][\"count\"]\n\n\n def __init__(self):\n if ResourceLoader.__instance != None:\n raise Exception(\"This class is a singleton!\")\n else:\n ResourceLoader.__instance = self\n\n ResourceLoader.resources = {\n \"actors\":{\n \"url_stub\":BASE_URL+'/name/'\n },\n \"movies\":{\n \"url_stub\":BASE_URL+'/title/'\n }\n }\n for reskey in ResourceLoader.resources.keys():\n ResourceLoader.resources[reskey]['count'] = self.getResourceEntityCount(reskey)\n ResourceLoader.resources[reskey]['mgr'] = self.getResourceManager(reskey)\n \n def do_on_ONE(self,func,category_name):\n mgr = self.resources[category_name]['mgr']\n count = self.resources[category_name]['count']\n rows = mgr.read_from_file_range(1, 2)\n func(rows)\n\n\n def do_on(self,func,category_name):\n mgr = self.resources[category_name]['mgr']\n count = self.resources[category_name]['count']\n\n number_of_ranges = count // 10\n if(number_of_ranges == 0):\n for r in range(1, number_of_ranges):\n rows = mgr.read_from_file_range(1, count-1)\n func(rows)\n if(number_of_ranges > 0):\n rows = mgr.read_from_file_range(1, 9)\n func(rows)\n for r in range(1, number_of_ranges):\n rows = mgr.read_from_file_range(r*10, ((r+1)*10)-1)\n func(rows)\n last = (count-1) % 10\n if last != 0:\n rows = mgr.read_from_file_range(\n number_of_ranges*10, count-1)\n func(rows)\n ","sub_path":"webscraping_tool/scraping/common/resource_loader.py","file_name":"resource_loader.py","file_ext":"py","file_size_in_byte":2971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"514441331","text":"from flask_restplus.fields import String, DateTime, Boolean\nfrom .. import api\n\n\nfields = api.model(\n 'Gallery',\n {\n 'date': DateTime(description='Date'),\n 'markdown': String(description='Markdown'),\n 'published': Boolean(description='Published', default=False),\n 'title': String(description='Title'),\n },\n)\n\nget_fields = api.clone(\n 'Get Gallery',\n fields,\n {\n 'id': String(description='ID'),\n },\n)\n","sub_path":"backend/tilda/api/fields/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"419568264","text":"import json\nimport re\nfrom urllib.parse import urlencode\n\nimport requests\nfrom requests import RequestException\nfrom bs4 import BeautifulSoup\n\n#获取主页信息\ndef get_page_index(offset, keyword):\n data = {\n 'offset': offset,\n 'format': 'json',\n 'keyword': keyword,\n 'autoload': 'true',\n 'count': 20,\n 'cur_tab': 1,\n 'from':'search_tab'\n }\n url = 'https://www.toutiao.com/search_content/?' + urlencode(data);\n try:\n response = requests.get(url)\n if response.status_code == 200:\n return response.text\n return None\n except RequestException:\n print(\"主页索引出现问题\")\n return None\n\n#json中提取数据\ndef parse_data_index(html):\n data = json.loads(html)\n if data and \"data\" in data.keys():\n for item in data.get(\"data\"):\n if \"article_url\" in item.keys():\n yield item.get(\"article_url\");\n\n#提取详情页数据\ndef get_page_detail(url):\n try:\n url = url.replace(\"http://\",\"https://www.\").replace(\"group/\",\"a\")\n print(url)\n response = requests.get(url)\n if response.status_code == 200:\n return response.text\n return None\n except RequestException:\n print(\"详情页<\"+url+\">访问出现问题\")\n return None\n\ndef parse_page_detail(html,url):\n #soup = BeautifulSoup(html, 'lxml')\n #title = soup.select('title')[0].get_text()\n #print(title)\n images_pattern = re.compile('gallery: JSON.parse\\((.*?)\\),', re.S)\n result = re.search(images_pattern, html)\n if result:\n data = json.loads(result.group(1))\n if data and isinstance(data, str) != 1 and 'sub_images' in data.keys():\n images = [obj.get('url') for obj in data.get('sub_images')]\n return {\n 'title':data.get('sub_titles')[0],\n 'url':url,\n 'images':images\n }\n return None\n\n#主方法\ndef main():\n html = get_page_index(0, \"街拍\")\n for url in parse_data_index(html):\n html = get_page_detail(url)\n imagesObj = parse_page_detail(html, url)\n print(imagesObj)\n print(\"-----------------------------\")\n\nprint(\"名字\",__name__)\nmain()\n","sub_path":"projects/PyDemo/src/com/boyu/demo7/今日头条街拍爬虫.py","file_name":"今日头条街拍爬虫.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"533576274","text":"#! /usr/bin/env python3\n\nimport numpy as np\nimport macmodel_bdiv as mac\nimport macloglib as mlog\nimport pickle as pkl\n\n# mode to simulate (longitudinal)\nm = [0]\n\n# Size of grid\nNk = 20 # Radial cells\nNl = 200 # Latitudinal cells\n\n# Define Physical Constants\nR = 3480e3 # Outer core radius in (m)\nh = [139.2e3] # layer thickness in (m)\nOmega = 2*np.pi/(23.9345*3600.0) # rotation rate in (rad/s)\nrho = 1.e4 # density in (kg/m^3)\nnu = [0.8] # momentum diffusivity in (m^2/s)\nnu_th = 0.0\neta = 0.8 # magnetic diffusivity in (m^2/s)\neta_th = 0.0\nmu_0 = 4.*np.pi*10.**-7 # vacuum permeability in (kg*m/(A^2s^2))\ng = 10. # Gravity in m/s^2\ndCyr = [65.]\n\n# background magnetic field (Tesla)\n# choices: dipole, abs_dipole, constant, set\n# constant: must specify [Br, Bth, Bph] as floats\n# abs_dipole: must specify [Bd, Brnoise, Brconst, use_Bth, Bthnoise, Bthconst]\n# dipole: must specify [Bd, use_bth]\n# set: must specify [Br, Bth, Bph] as (Nk,Nl) arrays\nB_type = 'constant'\nBd = 0.\nBr = 0.62e-3\nBrconst = 0.\nBrnoise = 0.\nBth = 0.\nBthconst = 0.\nBthnoise = 0.\nBph = 0.\nuse_Bth = False\n\n# background velocity field in (m/s)\nUphi = 0.0\n\n# Buoyancy Frequency\n# choices: constant, linear\nbuoy_type = 'constant'\nbuoy_ratio = [1.0]\n\n# model parameters\nmodel_variables = ('ur', 'uth', 'uph', 'br', 'bth', 'bph', 'p', 'r_disp')\ndir_suf = '_Buffett'\nep = 1e-3\n\nnotify_me_by_text = True\nverbose = False\nnum_threads = None","sub_path":"config/cfg_make_Buffett.py","file_name":"cfg_make_Buffett.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"542086102","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- \n \n\"\"\"\n下载喜马拉雅上节目的一个小脚本\n两种模式:\n1、下载单曲,直接在脚本后面参数形式加上节目id,下载单个节目。可以加多个,用空格分隔。\n\t如:页面链接为“http://www.ximalaya.com/#/2629577/sound/1127462”\n\t其中的“1127462”就是节目id。\n2、下载当前页面的所有节目,直接运行脚本,在提示符号后直接粘贴页面地址即可。\n \nCoding by xzap\n2014年5月26日\n\"\"\"\nimport urllib.request\nimport json\nimport os\nimport re\nimport sys\nimport time\n \nbaseurl = \"http://fdfs.xmcdn.com/\"\nnum = 0\nok = 0\ntotal = 0\ntime1 =time.time()\npath = os.path.expanduser(\"~/ximalaya\")\nif not os.path.exists(path):\n\tos.makedirs(path)\nopener = urllib.request.build_opener()\nopener.addheaders.append(('Referer', 'http://www.ximalaya.com'))\nopener.addheaders.append(('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36'))\nurllib.request.install_opener(opener)\n \ndef reporthook(blocknum, blocksize, totalsize):\n\treadsofar = blocknum * blocksize\n\tif totalsize > 0:\n\t\tpercent = readsofar * 1e2 / totalsize\n\t\ttime2 = time.time() - time1\n\t\tpp = readsofar / time2 / 1024\n\t\ttt = totalsize / 1024 /1024\n\t\ts = \"\\r%5.1f%% %*d / %d %.2fM %.2fKbps\" % (percent, len(str(totalsize)), readsofar, totalsize,tt,pp)\n\t\tsys.stderr.write(s)\n \ndef down(soundid,year=\"\") :\n\tglobal total\n\tglobal num\n\tnum += 1\n\turl = \"http://www.ximalaya.com/tracks/\" + soundid + \".json\"\n\tjc = urllib.request.urlopen(url).read().decode(\"utf-8\")\n\tif jc == \"null\" :\n\t\tprint(\"=\"*80)\n\t\tprint (num,\"/\",total)\n\t\tprint (soundid,\"is a wrong sound id\")\n\t\treturn\n\tdata = json.loads(jc)\n\talbum = data[\"album_title\"]\n\ttitle = data[\"title\"]\n\tmp3url = baseurl + data[\"play_path\"]\n\tformatted_created = data[\"formatted_created_at\"].split()[0].replace(\"日\",\"\")\n\tfc1,fc2 = formatted_created.split(\"月\") \n\tif len(fc1) == 1 :\n\t\tfc1 = \"0\" + fc1\n\tif len(fc2) == 1 :\n\t\tfc2 = \"0\" + fc2\n\tfc = year + fc1 + fc2 + \"_\" + title\n\text = os.path.splitext(mp3url)[1]\n\tfilename = fc + ext \n\tdpath = os.path.join(path,album)\n\tif not os.path.exists(dpath):\n\t\tos.makedirs(dpath)\n\tdownfile = os.path.join(dpath,filename)\n\tprint(\"=\"*80)\n\tprint (num,\"/\",total)\n\t#print (title,\"downloading......\")\n\tprint (\"URL:\", mp3url)\n\tprint (\"FILE:\", downfile)\n\tif os.path.exists (downfile):\n\t\tprint (downfile,\"is exists!!!\")\n\t\treturn\n\ttry:\n\t\tglobal time1\n\t\ttime1 = time.time()\n\t\turllib.request.urlretrieve(mp3url,downfile,reporthook)\n\t\tglobal ok\n\t\tok += 1\n\t\tprint()\n\texcept :\n\t\tprint (downfile,\"is fail !\")\n \ndef soundlist(soundurl) :\n\ttry :\n\t\tcc = urllib.request.urlopen(soundurl).read().decode(\"utf-8\")\n\texcept:\n\t\tprint (\"Are you sure it's a correct url?\")\n\t\treturn\n\tchaxun=re.findall(\"sound_id=\\\"[0-9]*\\\"\",cc)\n\tif chaxun :\n\t\tidlist = [x.split(\"\\\"\")[1] for x in chaxun]\n\t\tglobal total\n\t\tidlist2 = {}.fromkeys(idlist).keys()\n\t\ttotal = len(idlist2)\n\t\tfor i in idlist2 :\n\t\t\tdown(i)\n\telse :\n\t\tprint (\"It's a wrong url\")\n\t\treturn\n \nif len(sys.argv) > 1 :\n\ttotal = len(sys.argv[1:])\n\tfor j in sys.argv[1:] :\n\t\tdown(j,\"2014\")\nelse :\n\ttry:\n\t\treadurl = input (\"Need a ximalaya's url: \")\n \n\texcept :\n\t\tprint()\n\t\texit()\n\tprint (\"You are type is: \",readurl)\n\ttry :\n\t\treadurl2 = readurl.replace(\"#/\",\"\")\n\texcept :\n\t\tpass\n\tsoundlist(readurl2)\n \nprint (\"=\"*80)\nprint (\"All done,\",ok,\"files is downloded.\")","sub_path":"bin/ximalaya.py","file_name":"ximalaya.py","file_ext":"py","file_size_in_byte":3413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"378675417","text":"#!/usr/bin/env python\n#coding:utf-8\n# Author: mozman\n# Purpose: profile matrix44.invert\n# Created: 27.04.2010\n\nfrom timeit import Timer\n\nCOUNT = 1000000\n\nsetup_matrix = \"\"\"\nfrom geoalg.matrix44 import Matrix44\nmatrix = Matrix44([2, 3, 1, 15, 45, 23, 56, 32, 99, 2, 4, 3, 6, 2, 2, 8])\n\"\"\"\n\nsetup_cmatrix = \"\"\"\nfrom geoalg.cmatrix44 import cMatrix44\nmatrix = cMatrix44([2, 3, 1, 15, 45, 23, 56, 32, 99, 2, 4, 3, 6, 2, 2, 8])\n\"\"\"\n\ndef invert_matrix():\n matrix.inverse()\n\ndef print_result(time, text):\n print(\"Module:{1} takes {0:.2f} seconds\\n\".format(time, text))\n\ndef main():\n t = Timer(\"matrix.inverse()\", setup_matrix)\n print_result(t.timeit(COUNT), 'Matrix44')\n\n t = Timer(\"matrix.inverse()\", setup_cmatrix)\n print_result(t.timeit(COUNT), 'cMatrix44')\n\nif __name__=='__main__':\n main()","sub_path":"profile_invert.py","file_name":"profile_invert.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"345470018","text":"import argparse\nimport os\n\nfrom repo.pull import clone_repository\nfrom repo.dirs import create_dir_for_cloned_repo, delete_dir\nfrom filestat.stat import get_top_verbs_in_path\n\nBASE_DIR = os.getcwd()\n\n\ndef init_path(arguments):\n path_to_clone = create_dir_for_cloned_repo(BASE_DIR)\n clone_repository(arguments.r, path_to_clone)\n return path_to_clone\n\n\ndef destruction(path):\n delete_dir(path)\n\n\ndef main(arguments):\n path = init_path(arguments)\n print(get_top_verbs_in_path(path))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-r', '-repository', help='Repository to clone .git')\n parser.add_argument('--p', '--part_speech', nargs='?', default='v',\n help='v - for verbs, n - for nouns')\n parser.add_argument('--t', '--type', nargs='?', default='function',\n help='functions - for functions, variables - for '\n 'variables')\n parser.add_argument('--ot', '--output_type', nargs='?',\n default='json', help='Type of output. json or csv.')\n args = parser.parse_args()\n print(args)\n if args.r:\n main(args)\n else:\n print('No git repository passed.')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"286004445","text":"# Find the lowest, postive integer not present in a list of numbers\n# Ignore 0 or negative numbers\n\n\ndef solution(nums: list[int]) -> int:\n if len(nums) == 0:\n return 1\n\n for i in range(1, len(nums) + 1):\n if i not in nums:\n return i\n # if everything found, return -1\n return -1\n\n\nif __name__ == \"__main__\":\n assert solution([]) == 1\n assert solution([1, 2, 3, 4, 5]) == -1\n assert solution([6, 9, 2, 0, 1]) == 3, \"Your solution didn't work!\"\n","sub_path":"first_missing_int.py","file_name":"first_missing_int.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"256763224","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport altair as alt\nimport plotly.express as px\nimport plotly.graph_objects as go\n\n\n\n\ndef get_data(file):\n df = pd.read_csv(file)\n return df\n\ndef show_data(df):\n st.write('**Viewing History:** ')\n df =df.dropna()\n st.write(df)\n \n \n df['Date'] = pd.to_datetime(pd.Series(df['Date']))\n df['Year'], df['Month'] = df['Date'].dt.year, df['Date'].dt.month_name()\n df['Day'] = df['Date'].dt.day\n df['Day_of_week'] = df['Date'].dt.day_name()\n category = []\n for value in df['Title']:\n if ': ' in value:\n category.append('TV')\n else:\n category.append('Movie')\n df['Category'] = category\n \n\n #Tv Shows\n tv_titles= df[df['Category'] == 'TV']\n tv_titles[['Show','Episode']] = tv_titles['Title'].str.split(\": \", n=1,expand=True)\n\n n = 10\n top10= tv_titles['Show'].value_counts()[:n].rename_axis('Show').reset_index(name='EpisodeCount')\n \n top10shows = tv_titles[tv_titles['Show'].isin(top10['Show'])]\n\n####Data Vis############\n \n plot_month = alt.Chart(df).mark_bar(\n cornerRadiusTopLeft=4,\n cornerRadiusTopRight=4,\n ).encode(\n x= alt.X('Month',sort='-y'),\n y= 'count()',\n color= 'Category',\n tooltip=['Category', 'count()']\n ).properties(\n title='Month'\n ).interactive() \n \n plot_weekday = alt.Chart(df).mark_bar(\n cornerRadiusTopLeft=4,\n cornerRadiusTopRight=4\n ).encode(\n x= alt.X('Day_of_week', title=None, sort='-y'),\n y= 'count()',\n color= 'Category',\n tooltip=['Category', 'count()']\n ).properties(\n title='Day of The Week'\n ).interactive()\n\n plot_titles = alt.Chart(df).mark_circle().encode(\n x='yearmonth(Date)',\n y='Category',\n color='Category',\n tooltip=['Title', 'Date']\n ).interactive()\n\n plot_top10 = alt.Chart(top10).mark_bar(\n cornerRadiusTopLeft=3,\n cornerRadiusTopRight=3,\n opacity=1\n ).encode(\n x= alt.X('Show', sort='-y'),\n y= 'EpisodeCount',\n tooltip= ['Show', 'EpisodeCount']\n ).properties(\n title='Top 10 Shows'\n ).interactive()\n\n fig = px.strip(df, x=\"Date\",color=\"Category\",hover_name='Title')\n \n fig3= px.strip(top10shows, x='Date', y='Show', color='Show', hover_name='Episode')\n fig3 =fig3.update_layout(showlegend=False)\n config = {\n 'displaylogo': False\n \n }\n\n\n \n \n\n###show charts####\n \n #top10 charts\n #weekly and monthly charts\n left_column, right_column= st.beta_columns(2)\n with left_column:\n st.altair_chart(plot_weekday, use_container_width=True)\n with right_column:\n st.altair_chart(plot_month, use_container_width=True)\n\n\n col1, col2 = st.beta_columns([1,2])\n col1.subheader('Top 10 Shows')\n col1.write(top10)\n col2.plotly_chart(fig3, use_container_width=True, config=config)\n\n st.subheader('Viewing History Across Time')\n st.plotly_chart(fig, use_container_width=True, config=config)\n \n\n\ndef main():\n\n st.title('Analyize Your Netflix Viewing History')\n st.subheader('**A breakdown of your netflix history**')\n\n st.write('[**click here to download your netlfix viewing history**](https://www.netflix.com/viewingactivity)')\n\n file = st.file_uploader('Upload file', type=['csv'])\n \n \n if file == None:\n pass\n else:\n df = get_data(file)\n show_data(df)\n \n \n\n\n\nmain()\n \n","sub_path":"netflixAnalysis.py","file_name":"netflixAnalysis.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"290737285","text":"import pandas as pd\nimport os\nimport sys\n\n\ndef get_path_list(root_path, pattern):\n \"\"\"\n Get a list of all file paths that can be seen from rooth_path\n that matches the pattern.\n\n :params:\n root_path - the root folder to be searched\n pattern - regex pattern to be matched with filenames\n\n :return:\n path_list - list of paths that matches pattern\n \"\"\"\n path_list = []\n for root, subfolders, files in os.walk(root_path):\n for filename in files:\n if pattern.match(filename):\n path_list.append(os.path.join(root, filename))\n\n return path_list\n\n\ndef get_aggregate_data(aggregate_fxn, path_list, verbose=False):\n \"\"\"\n Applies aggregate_fxn to all files defined in path_list.\n\n :params:\n aggregate_fxn - function that aggregates the data in the\n files defined by path_list. Must take\n argument (filename) from path_list and return\n a pandas data series (data_series)\n path_list - a list of paths where aggregate_fxn will be applied\n\n :return:\n df_aggregate - a pandas dataframe with the collected (data_series)\n bad_paths - list of file paths where aggregate_fxn failed\n \"\"\"\n df_aggregate = pd.DataFrame()\n bad_paths = []\n ii_max = len(path_list)\n for ii, file_path in enumerate(path_list):\n if verbose:\n progress_bar(ii, ii_max, ' - Processing {}'.format(file_path))\n try:\n data_series = aggregate_fxn(file_path)\n df_aggregate = df_aggregate.append(data_series, ignore_index=True)\n except:\n bad_paths.append(file_path)\n\n return df_aggregate, bad_paths\n\n\ndef progress_bar(ii, ii_max, print_str):\n \"\"\"\n Simple progress bar for the terminal.\n\n :params:\n ii - current iteration\n ii_max - maximum iteration\n print_str - string to be printed after progress bar.\n \"\"\"\n sys.stdout.write('\\r')\n prog_bar = ((ii+1)*20) // ii_max\n prog_percent = ((ii+1)*100) // ii_max\n sys.stdout.write(\"[%-20s] %d%%. \" % ('='*prog_bar, prog_percent))\n sys.stdout.write(print_str)\n sys.stdout.flush()\n return\n","sub_path":"fetch_tools.py","file_name":"fetch_tools.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"284914198","text":"from __future__ import print_function\nfrom functools import reduce\nimport re\nimport sys\nimport nltk\nfrom nltk import word_tokenize,sent_tokenize\nimport re\nimport keras\n\n#from keras.layers import merge\n#from keras.engine import merge\n#from keras.layers import Dense, Merge\n#from keras.layers import add\n\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers import Dense, Dropout, RepeatVector,Merge\n\n\nfrom keras.layers import recurrent\nfrom keras.models import Sequential\nfrom keras.preprocessing.sequence import pad_sequences\nfrom collections import OrderedDict\nfrom keras.models import model_from_json\nimport h5py\nimport numpy as np\nnp.random.seed(1337) # for reproducibility\nfrom keras.models import load_model\nimport itertools\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nimport gensim\nfrom gensim.models import word2vec\n\n\n\n\n\ndef tokenize(sent):\n\tsent=sent_tokenize(sent)\n\tprint(sent)\n\treturn(sent)\n\ndef Extracting_Data(lines):\n\tdata = []\n\tfor line in lines:\n\t\tinformation=[]\n\t\tquestion=[]\n\t\tline=line.strip().split(\"\\t\")\n\t\tsent=sent_tokenize(line[0])\n\t\tanswer=line[1]\n\t\tfor i,sn in enumerate(sent):\n\t\t\tif(re.search('\\?' , sn)):\n\t\t\t\tquestion.append(word_tokenize(sn))\n\t\t\telse:\n\t\t\t\tinformation.append(word_tokenize(sn))\n\t\tinformation=list(itertools.chain(*information))\n\t\tquestion=list(itertools.chain(*question))\n\t\tdata.append((information,question,answer))\t\t\n\treturn data\n\n\ndef get_Data(f):\n\tdata = Extracting_Data(f.readlines())\n\treturn data\n\ntrain = get_Data(open('/home/priyanka/Desktop/Final_NLP_Codes/Final_codes__/stanford-parser-full-2018-10-17/DATA/train_New.txt', 'r'))\ntest = get_Data(open(\"/home/priyanka/Desktop/Final_NLP_Codes/Final_codes__/stanford-parser-full-2018-10-17/DATA/test_New.txt\", 'r'))\nprint(\"train: \",train)\nprint(\"\\n\")\n\n\n\nfc=open(\"Dataset_creation.txt\",\"w\")\n\ndef vectorize_Data(data, word_idx, word_idx_answer, story_maxlen, query_maxlen):\n\tX = []\n\tXq = []\n\tY = []\n\tprint(\"length of data\")\n\tprint(len(data))\n\tfor story, query, answer in data:\n\t\tx = [word_idx[w] for w in story]\n\t\txq = [word_idx[w] for w in query]\n\t\ty = np.zeros(len(word_idx_answer))\n\t\tfor item in answer.split():\n\t\t\tif re.search('\\+|\\-|\\*|/', item):\n\t\t\t\ty[word_idx_answer[item]] = 1\n\t\tX.append(x)\n\t\tXq.append(xq)\n\t\tY.append(y)\n\t\tfc.write(str(story)+\"\\t\")\n\t\tfc.write(str(query)+\"\\t\")\n\t\tfc.write(str(y)+\"\\t\")\n\t\tfc.write(answer+\"\\t\")\n\t\tfc.write(str(np.argmax(y))+\"\\t\")\n\t\tfc.write(\"\\n\")\n\n\treturn pad_sequences(X, maxlen=story_maxlen), pad_sequences(Xq, maxlen=query_maxlen), np.array(Y)\n\n\n\n\n\n\nRNN = recurrent.GRU\nEMBED_HIDDEN_SIZE = 50\nSENT_HIDDEN_SIZE = 100\nQUERY_HIDDEN_SIZE = 100\nBATCH_SIZE = 32\nEPOCHS = 40\nprint('RNN / Embed / Sent / Query = {}, {}, {}, {}'.format(RNN,\n EMBED_HIDDEN_SIZE, SENT_HIDDEN_SIZE, QUERY_HIDDEN_SIZE))\n\nvocab = sorted(reduce(lambda x, y: x | y,\n (set(story + q + [answer]) for story, q, answer in train + test)))\n\nvocab_size = len(vocab) + 1\nvocab_answer_set = set()\nfor story, q, answer in train + test:\n\tfor item in answer.split():\n\t\tif re.search('\\+|\\-|\\*|/', item):\n\t\t\tvocab_answer_set.add(item)\n\nvocab_answer = list(vocab_answer_set)\nvocab_answer_size = len(vocab_answer)\n\nword_idx = OrderedDict((c, i + 1) for i, c in enumerate(vocab))\nword_idx_answer = OrderedDict((c, i) for i, c in enumerate(vocab_answer))\nword_idx_operator_reverse = OrderedDict((i, c) for i, c in enumerate(vocab_answer))\nprint('a', word_idx_answer,word_idx_operator_reverse)\nstory_maxlen = max(map(len, (x for x, _, _ in train + test)))\nquery_maxlen = max(map(len, (x for _, x, _ in train+ test)))\nprint(\"query_maxlen\", query_maxlen , story_maxlen)\n\nX, Xq, Y = vectorize_Data(train, word_idx, word_idx_answer, story_maxlen, query_maxlen)\ntX, tXq, tY = vectorize_Data(test, word_idx, word_idx_answer, story_maxlen, query_maxlen)\n\n\n\n\nprint(\"word_idx_answer: \",word_idx_answer)\nprint(\"\\n\\n\")\n\nfc.close()\n\n\n\nprint('X.shape = {}'.format(X.shape), X)\nprint('Xq.shape = {}'.format(Xq.shape), Xq)\nprint('Y.shape = {}'.format(Y.shape), Y)\nprint('tX.shape = {}'.format(tX.shape))\nprint('tXq.shape = {}'.format(tXq.shape))\nprint(\"\\n\")\nprint('tY.shape = {}'.format(tY.shape),tY)\nprint('story_maxlen, query_maxlen = {}, {}'.format(story_maxlen, query_maxlen))\n\n\nprint('Build model...')\nprint(vocab_size, vocab_answer_size)\n\nsentrnn = Sequential()\nsentrnn.add(Embedding(vocab_size, EMBED_HIDDEN_SIZE,\n input_length=story_maxlen))\n\n#sentrnn.add(Dropout(0.3))\nsentrnn.add(RNN(EMBED_HIDDEN_SIZE, return_sequences=False))\n\nqrnn = Sequential()\nqrnn.add(Embedding(vocab_size, EMBED_HIDDEN_SIZE,\n input_length=query_maxlen))\nqrnn.add(Dropout(0.3))\nqrnn.add(RNN(EMBED_HIDDEN_SIZE, return_sequences=False))\n\nmodel = Sequential()\n\nmodel.add(Merge([sentrnn, qrnn], mode='sum'))\n\n#m = add([sentrnn, qrnn])\n#model.add(m)\n#model.add(Add([sentrnn, qrnn]))\n#model.add(Merge([sentrnn, qrnn], mode='concat'))\n#model.add(merge([sentrnn, qrnn], mode='concat',concat_axis=-1))\n#model.add(Concatenate([sentrnn, qrnn]))\n\n#model.add(RNN(EMBED_HIDDEN_SIZE, return_sequences=False))\n#model.add(RNN(EMBED_HIDDEN_SIZE))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(vocab_answer_size, activation='softmax'))\nmodel.compile(optimizer='adam',\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\nmodel.fit([X, Xq], Y, batch_size=BATCH_SIZE,\n nb_epoch=EPOCHS, validation_split=0.05)\nmodel.save('my_model.h5')\n\ndel model\n\nload_model = load_model('my_model.h5')\n\n\nprint(\"Training evaluation..................\")\nloss, acc = load_model.evaluate([X, Xq], Y, batch_size=BATCH_SIZE)\nprint(' loss - accuracy = {:.4f} / {:.4f}'.format(loss, acc))\nprint(\"\\n\\n\")\n\n\nprint(\"Testing..............\")\nloss, acc = load_model.evaluate([tX, tXq], tY, batch_size=BATCH_SIZE)\nprint('loss -accuracy = {:.4f} / {:.4f}'.format(loss, acc))\n\n\n\nprint(\"\\n\\n\")\nprint(\"Test Sample : \\n\")\npredicted_Labels=load_model.predict([tX, tXq])\nprint(predicted_Labels)\ntarget_names=[\"+\",\"*\",\"-\",\"/\"]\nprint(predicted_Labels)\nlabels_test=[np.argmax(lb) for lb in predicted_Labels]\nprint(\"labels_test: \",labels_test)\n\n\nexpected=[np.argmax(le) for le in tY]\nprint(\"\\n---------------------------------\\n\")\nprint(\"seq2seq Classifier Test Accuracy: \",accuracy_score(expected, labels_test)*100)\nprint(\"\\n---------------------------------\\n\")\nprint(\"\\n\")\n\n","sub_path":"word_problem_solving/WPS_Final_Codes_29_11_2018/DEEP_NN_model_.py","file_name":"DEEP_NN_model_.py","file_ext":"py","file_size_in_byte":6564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"150626238","text":"from application import db, login_manager, create_app\nfrom application.models import PreviousCAUVApp\nimport csv\n\napp = create_app()\napp.app_context().push()\ndb.session.query(PreviousCAUVApp).delete()\ndb.session.commit()\ncauv_dict = {\n 'AG_APP': None,\n 'Parcel_Change_Check': None,\n 'Parcels_Combined_Acres': None,\n 'Commodity_Acres': None,\n 'Hay_Acres': None,\n 'Perm_Pasture_Acres': None,\n 'Noncommercial_Wood_Acres': None,\n 'Commerical_Wood_Acres': None,\n 'Other_Crop_Acres': None,\n 'Homesite_Acres': None,\n 'Road_Waste_Pond_Acres': None,\n 'CRP_Acres': None,\n 'Con25_Acres': None,\n 'Other_Use_Acres': None,\n 'Stated_Total_Acres': None,\n 'Farmed_Acres_1': None,\n 'Farmed_Acres_2': None,\n 'Farmed_Acres_3': None,\n 'Use_of_Land_1': None,\n 'Use_of_Land_2': None,\n 'Use_of_Land_3': None,\n 'Units_Acre_1': None,\n 'Units_Acre_2': None,\n 'Units_Acre_3': None,\n 'Price_Unit_1': None,\n 'Price_Unit_2': None,\n 'Price_Unit_3': None,\n 'Gross_Income_1': None,\n 'Gross_Income_2': None,\n 'Gross_Income_3': None,\n}\n\nfor row in open('2019RENEWAL_CAUV_APPS_DATABASE.csv'):\n line = row.split(',')\n cauv_dict['Parcel_Change_Check'] = line[2]\n cauv_dict['Farmed_Acres_1'] = line[15]\n cauv_dict['Use_of_Land_1'] = line[16]\n cauv_dict['Units_Acre_1'] = line[17]\n cauv_dict['Price_Unit_1'] = line[18]\n cauv_dict['Gross_Income_1'] = line[19]\n cauv_dict['Farmed_Acres_2'] = line[20]\n cauv_dict['Use_of_Land_2'] = line[21]\n cauv_dict['Units_Acre_2'] = line[22]\n cauv_dict['Price_Unit_2'] = line[23]\n cauv_dict['Gross_Income_2'] = line[24]\n cauv_dict['Farmed_Acres_3'] = line[25]\n cauv_dict['Use_of_Land_3'] = line[26]\n cauv_dict['Units_Acre_3'] = line[27]\n cauv_dict['Price_Unit_3'] = line[28]\n cauv_dict['Gross_Income_3'] = line[29].strip()\n\nfor row in open('11_22_2019_RECOMMENDED.csv'):\n line = row.split(',')\n cauv_dict['AG_APP'] = line[0]\n cauv_dict['Parcels_Combined_Acres'] = line[1]\n cauv_dict['Stated_Total_Acres'] = line[2]\n cauv_dict['Commodity_Acres'] = line[3]\n cauv_dict['Hay_Acres'] = line[4]\n cauv_dict['Perm_Pasture_Acres'] = line[5]\n cauv_dict['Noncommercial_Wood_Acres'] = line[6]\n cauv_dict['Commerical_Wood_Acres'] = line[7]\n cauv_dict['Other_Crop_Acres'] = line[8]\n cauv_dict['Homesite_Acres'] = line[9]\n cauv_dict['Road_Waste_Pond_Acres'] = line[10]\n cauv_dict['CRP_Acres'] = line[11]\n cauv_dict['Con25_Acres'] = line[12]\n cauv_dict['Other_Use_Acres'] = line[13]\n\n for each in cauv_dict:\n app = PreviousCAUVApp(\n user=\"BC\",\n AG_APP=cauv_dict['AG_APP'],\n Parcel_Change_Check=cauv_dict['Parcel_Change_Check'],\n Parcels_Combined_Acres=cauv_dict['Parcels_Combined_Acres'],\n Commodity_Acres=cauv_dict['Commodity_Acres'],\n Hay_Acres=cauv_dict['Hay_Acres'],\n Perm_Pasture_Acres=cauv_dict['Perm_Pasture_Acres'],\n Noncommercial_Wood_Acres=cauv_dict['Noncommercial_Wood_Acres'],\n Commerical_Wood_Acres=cauv_dict['Commerical_Wood_Acres'],\n Other_Crop_Acres=cauv_dict['Other_Crop_Acres'],\n Homesite_Acres=cauv_dict['Homesite_Acres'],\n Road_Waste_Pond_Acres=cauv_dict['Road_Waste_Pond_Acres'],\n CRP_Acres=cauv_dict['CRP_Acres'],\n Con25_Acres=cauv_dict['Con25_Acres'],\n Other_Use_Acres=cauv_dict['Other_Use_Acres'],\n Stated_Total_Acres=cauv_dict['Stated_Total_Acres'],\n Farmed_Acres_1=cauv_dict['Farmed_Acres_1'],\n Farmed_Acres_2=cauv_dict['Farmed_Acres_2'],\n Farmed_Acres_3=cauv_dict['Farmed_Acres_3'],\n Use_of_Land_1=cauv_dict['Use_of_Land_1'],\n Use_of_Land_2=cauv_dict['Use_of_Land_2'],\n Use_of_Land_3=cauv_dict['Use_of_Land_3'],\n Units_Acre_1=cauv_dict['Units_Acre_1'],\n Units_Acre_2=cauv_dict['Units_Acre_2'],\n Units_Acre_3=cauv_dict['Units_Acre_3'],\n Price_Unit_1=cauv_dict['Price_Unit_1'],\n Price_Unit_2=cauv_dict['Price_Unit_2'],\n Price_Unit_3=cauv_dict['Price_Unit_3'],\n Gross_Income_1=cauv_dict['Gross_Income_1'],\n Gross_Income_2=cauv_dict['Gross_Income_2'],\n Gross_Income_3=cauv_dict['Gross_Income_3'],\n )\n db.session.add(app)\ndb.session.commit()\n","sub_path":"importCSV.py","file_name":"importCSV.py","file_ext":"py","file_size_in_byte":4391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"4430300","text":"#!/usr/bin/env python\n# coding=utf-8\nfrom __future__ import division, print_function, unicode_literals\n\nfrom collections import OrderedDict\n\nfrom brainstorm.layers.base_layer import Layer\nfrom brainstorm.structure.buffer_structure import (BufferStructure,\n StructureTemplate)\nfrom brainstorm.structure.construction import ConstructionWrapper\nfrom brainstorm.utils import (LayerValidationError, flatten_features,\n flatten_time, flatten_time_and_features)\n\n\ndef SquaredDifference(name=None):\n \"\"\"Create a Squared Difference layer.\"\"\"\n return ConstructionWrapper.create(SquaredDifferenceLayerImpl, name=name)\n\n\nclass SquaredDifferenceLayerImpl(Layer):\n\n expected_inputs = {'inputs_1': StructureTemplate('T', 'B', '...'),\n 'inputs_2': StructureTemplate('T', 'B', '...')}\n expected_kwargs = {}\n\n def setup(self, kwargs, in_shapes):\n # 'inputs_1' and 'inputs_2' must have same shape\n f_size1 = in_shapes['inputs_1'].feature_size\n f_size2 = in_shapes['inputs_2'].feature_size\n if f_size1 != f_size2:\n raise LayerValidationError(\n \"{}: inputs_1 and inputs_2 must have same feature sizes but \"\n \"got {} and {}\".format(self.name,\n in_shapes['inputs_1'].feature_shape,\n in_shapes['inputs_2'].feature_shape))\n\n outputs = OrderedDict()\n outputs['default'] = BufferStructure('T', 'B', 1)\n\n internals = OrderedDict()\n feature_size = self.in_shapes['inputs_1'].feature_size\n internals['squared_diff'] = BufferStructure('T', 'B', feature_size)\n internals['grad_diff'] = BufferStructure('T', 'B', feature_size,\n is_backward_only=True)\n return outputs, OrderedDict(), internals\n\n def forward_pass(self, buffers, training_pass=True):\n # prepare\n _h = self.handler\n inputs_1 = flatten_time_and_features(buffers.inputs.inputs_1)\n inputs_2 = flatten_time_and_features(buffers.inputs.inputs_2)\n diff = flatten_time_and_features(buffers.internals.squared_diff)\n diff_sum = flatten_time(buffers.outputs.default)\n\n # calculate\n _h.subtract_tt(inputs_1, inputs_2, out=diff)\n _h.mult_tt(diff, diff, out=diff)\n _h.sum_t(diff, axis=1, out=diff_sum)\n _h.mult_st(0.5, diff_sum, out=diff_sum)\n\n def backward_pass(self, buffers):\n # prepare\n _h = self.handler\n inputs_1 = flatten_time_and_features(buffers.inputs.inputs_1)\n inputs_2 = flatten_time_and_features(buffers.inputs.inputs_2)\n out_deltas = buffers.output_deltas.default\n grad_diff = buffers.internals.grad_diff\n dinputs_1 = flatten_time_and_features(buffers.input_deltas.inputs_1)\n dinputs_2 = flatten_time_and_features(buffers.input_deltas.inputs_2)\n\n tmp = _h.allocate(inputs_2.shape)\n # out_deltas has only one feature dimension due to summation,\n # so we broadcast to all feature dimensions\n _h.broadcast_t(out_deltas, 2, grad_diff)\n\n grad_diff = flatten_time(grad_diff)\n # calculate\n _h.subtract_tt(inputs_1, inputs_2, out=tmp)\n _h.mult_add_tt(grad_diff, tmp, dinputs_1)\n\n _h.subtract_tt(inputs_2, inputs_1, out=tmp)\n _h.mult_add_tt(grad_diff, tmp, dinputs_2)\n","sub_path":"brainstorm/layers/squared_difference_layer.py","file_name":"squared_difference_layer.py","file_ext":"py","file_size_in_byte":3457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"23714799","text":"def show_magicians(wizar): #lista original que se estara modificando\n for magician in wizar:\n print(magician)\n\ndef make_great(wizar): #en esta funcion agregaremos \"great\" al inicio de los nombre de los wizar en la lista\n great_wizar = [] #se crea la lista de grean wizar\n\n for magician in wizar:\n great_wizar.append(magician + ' the Great')\n return great_wizar\n\nwizar = ['Natsu', 'Lucy', 'Grey', 'Ainz'] #Lista de los magos\nshow_magicians(wizar) #Imprime el nombre de la lista\nprint(\"\\n\")\nListTemp = wizar[:] #creo la copia de la lista original\nshow_magicians(make_great(wizar)) #Imprimo lista modificada\nprint(\"\\n\")\nshow_magicians(ListTemp) #Imprimo lista original\n","sub_path":"Ago-Dic-2018/Max/Ejercicios-Primer-Parcial/8-11UnchangedMagicianMax.py","file_name":"8-11UnchangedMagicianMax.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"330274821","text":"from collections import defaultdict\nfrom datetime import timedelta\nfrom tornado import gen\n\n\n\nclass ExampleFetcherCom(object):\n ''' This is an example fetcher that does not return real data. It's just for\n demonstration of what kind of data \"fetch\" method should return.\n '''\n \n TITLE = 'Example Fetcher'\n NETWORK_ID = 'example-fetcher.com'\n \n METRICS = ['cpm', 'revenue', 'impressions']\n \n \n @gen.coroutine\n def fetch(self, parameters):\n ''' This method should return data scraped from a network.\n The \"parameters\" argument is a dictionary that contains this data:\n date-start - a datetime object representing starting date for the\n report.\n date-end - a datetime object for end date.\n login - login to use with the network.\n password - password to use.\n \n This method should return data(dictionary) in this format:\n {\n __metric__: {\n __date__: __value___,\n ...\n },\n ...\n }\n \n Where:\n __metric__ - whatever metric you want to return, most common once\n are 'cpm', 'impressions' and 'revenue'.\n __date__ - a date string in format \"%Y%m%d\" (no dashes).\n __value__ - metric's value for the date.\n \n This method should be an asynchronous one, so you cannot use a request\n library, use apps.ans.fetchers.utils.async_session.AsyncSession\n object instead. Example:\n \n # somewhere at the top\n from apps.ans.fetchers.utils.async_session import AsyncSession\n \n # then in your fetch method:\n session = AsyncSession(fetch_defaults={\n 'headers': {\n 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:38.0)'\n ' Gecko/20100101 Firefox/38.0',\n 'Accept': '*/*',\n 'Connection': 'keep-alive',\n }\n })\n # make an async request and wait for a result\n r = yield session.get('http://some-url.com', headers={\n 'Some-Header': 'header value',\n })\n # print out the response text\n print(r.body.decode()) # body is a sequence of bytes\n '''\n \n date_current = parameters.get('date-start')\n date_end = parameters.get('date-end')\n one_day = timedelta(days=1)\n \n result = defaultdict(dict)\n number = 1\n while date_current <= date_end:\n date_str = date_current.strftime('%Y%m%d')\n \n result['cpm'][date_str] = 2\n result['impressions'][date_str] = number * 1000\n result['revenue'][date_str] = (\n (result['cpm'][date_str] / 1000) *\n result['impressions'][date_str])\n \n number += 1\n date_current += one_day\n \n \n return result","sub_path":"etc/adscrape_candidates/apps/ans/fetchers/example_fetcher_com.py","file_name":"example_fetcher_com.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"2537463","text":"from django.conf.urls.defaults import patterns, include, url\nimport os\n\nurlpatterns = patterns('',\n url(r'^$', 'matrobot.public.views.index'),\n (r'^people/', include('matrobot.people.urls')), \n (r'^project/', include('matrobot.project.urls')), \n (r'^public/', include('matrobot.public.urls')), \n\n # System URLs\n url(r'^media/(?P.*)$', 'django.views.static.serve',\n {'document_root': os.path.join(os.path.dirname(__file__), 'templates/media/')}),\n)\n","sub_path":"src/matrobot/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"115936699","text":"import os\nimport sys\n\nimport numpy as np\nfrom PIL import Image\nimport torch\nimport torch.nn.functional as F\n\ndef check_paths(args, train=True):\n if train:\n try:\n if not os.path.exists(args.save_model_dir):\n os.makedirs(args.save_model_dir)\n if args.checkpoint_model_dir is not None and not (os.path.exists(args.checkpoint_model_dir)):\n os.makedirs(args.checkpoint_model_dir)\n except OSError as e:\n print(e)\n sys.exit(1)\n else:\n try:\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n except OSError as e:\n print(e)\n sys.exit(1)\n\ndef load_image(filename, size=None, scale=None):\n img = Image.open(filename)\n if size is not None:\n img = img.resize((size, size), Image.ANTIALIAS)\n elif scale is not None:\n img = img.resize((int(img.size[0] / scale), int(img.size[1] / scale)), Image.ANTIALIAS)\n return img\n\ndef save_image(filename, data):\n img = data.clone().clamp(0, 255).numpy()\n img = img.transpose(1, 2, 0).astype(\"uint8\")\n img = Image.fromarray(img)\n img.save(filename)\n\ndef gram_matrix(y):\n (b, ch, h, w) = y.size()\n features = y.view(b, ch, w * h)\n features_t = features.transpose(1, 2)\n gram = features.bmm(features_t) / (ch * h * w)\n return gram\n\ndef normalize_batch(batch):\n # normalize using imagenet mean and std\n mean = batch.new_tensor([0.485, 0.456, 0.406]).view(-1, 1, 1)\n std = batch.new_tensor([0.229, 0.224, 0.225]).view(-1, 1, 1)\n batch = batch.div_(255.0)\n return (batch - mean) / std\n\ndef original_colors(original, stylized):\n h, s, v = original.convert('HSV').split()\n hs, ss, vs = stylized.convert('HSV').split()\n return Image.merge('HSV', (h, s, vs)).convert('RGB')","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"623918862","text":"from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.common.exceptions import TimeoutException\nfrom PIL import Image\nfrom io import BytesIO\nfrom time import sleep\nimport random\n\n\"\"\"\ninfo:\nauthor:H-pinke\ngithub:https://github.com/H-pinke\nupdate_time:2019-9-1\n\"\"\"\n\n\nclass BiliBili():\n \"\"\"\n 登陆B站, 处理验证码\n 电脑的缩放比例需要为100%, 否则验证码图片的获取会出现问题\n \"\"\"\n\n def __init__(self, username, password):\n \"\"\"\n 初始化\n \"\"\"\n options = webdriver.ChromeOptions()\n # 设置为开发者模式,避免被识别\n options.add_experimental_option('excludeSwitches',\n ['enable-automation'])\n self.browser = webdriver.Chrome(options=options)\n self.url = 'https://passport.bilibili.com/login'\n self.browser.get(self.url)\n self.wait = WebDriverWait(self.browser, 5, 0.2)\n self.username = username\n self.password = password\n\n def get_button(self):\n \"\"\"\n 获取滑动块, 并且返回\n :return: button\n \"\"\"\n button1 = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'btn-login')))\n button1.click()\n button = self.wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'geetest_slider_button')))\n return button\n\n def get_screenshot(self, button):\n \"\"\"\n 获取网页两次截图:\n 1. 鼠标悬停于button的截图\n 2. 鼠标点击button后的截图\n :param button: 滑动块\n :return: 两次截图的结果\n \"\"\"\n ActionChains(self.browser).move_to_element(button).perform()\n screenshot2 = self.browser.get_screenshot_as_png()\n screenshot2 = Image.open(BytesIO(screenshot2))\n self.delete_style()\n screenshot1 = self.browser.get_screenshot_as_png()\n screenshot1 = Image.open(BytesIO(screenshot1))\n self.add_style();\n return (screenshot1, screenshot2)\n\n def get_position(self, button):\n \"\"\"\n 获取验证码图片的位置\n :return: 位置的四个点参数\n \"\"\"\n ActionChains(self.browser).move_to_element(button).perform()\n img = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'geetest_canvas_img')))\n sleep(2)\n location = img.location\n size = img.size\n print(location, size)\n top, bottom, left, right = location['y'], location['y'] + size['height'], location['x'], \\\n location['x'] + size['width']\n return top, bottom, left, right\n\n def get_geetest_image(self, button, name1='captcha1.png', name2='captcha2.png'):\n \"\"\"\n 获取两次验证码的截图:\n 1. 鼠标悬停于button的截图\n 2. 鼠标点击button后的截图\n :param button: 滑动块\n :param name1: 原始验证码保存的名字\n :param name2: 缺块验证码保存的名字\n :return: 两次验证码截图的结果\n \"\"\"\n top, bottom, left, right = self.get_position(button)\n print('验证码位置', top, bottom, left, right)\n screenshot = self.get_screenshot(button)\n captcha1 = screenshot[0].crop((left, top, right, bottom))\n captcha1.save(name1)\n captcha2 = screenshot[1].crop((left, top, right, bottom))\n captcha2.save(name2)\n return (captcha1, captcha2)\n\n def login(self):\n \"\"\"\n 打开浏览器,并且输入账号密码\n :return: None\n \"\"\"\n self.browser.get(self.url)\n username = self.wait.until(EC.element_to_be_clickable((By.ID, 'login-username')))\n password = self.wait.until(EC.element_to_be_clickable((By.ID, 'login-passwd')))\n sleep(1)\n username.send_keys(self.username)\n sleep(1)\n password.send_keys(self.password)\n\n def is_pixel_equal(self, img1, img2, x, y):\n \"\"\"\n 判断两个像素是否相同\n :param img1: 原始验证码\n :param img2: 缺块验证码\n :param x: 像素点的x坐标\n :param y: 像素点的y坐标\n :return: 像素是否相同\n \"\"\"\n pixel1 = img1.load()[x-1, y]\n pixel2 = img2.load()[x-1, y]\n threshold = 100\n if abs(pixel1[0] - pixel2[0]) < threshold and abs(pixel1[1] - pixel2[1]) < threshold and abs(\n pixel1[2] - pixel2[2]) < threshold:\n return True\n else:\n return False\n\n def get_gap(self, img1, img2):\n \"\"\"\n 获取缺口偏移量\n :param img1: 原始验证码\n :param img2: 缺块验证码\n :return: 第二个缺块的左侧的x坐标\n \"\"\"\n left = 60 # 大致忽略掉第一个缺块\n for i in range(left, img1.size[0]):\n for j in range(img1.size[1]):\n if not self.is_pixel_equal(img1, img2, i, j):\n left = i\n return left\n return left\n def delete_style(self):\n '''\n 执行js脚本,获取无滑块图\n :return None\n '''\n js = 'document.querySelectorAll(\"canvas\")[3].style=\"\"'\n self.browser.execute_script(js)\n def add_style(self):\n '''\n 执行js脚本,获取有滑块图\n :return None\n '''\n js = 'document.querySelectorAll(\"canvas\")[3].style=\"opacity: 0; display: none;\"'\n self.browser.execute_script(js)\n def get_track(self, distance):\n \"\"\"\n 获取滑块移动轨迹的列表\n :param distance: 第二个缺块的左侧的x坐标\n :return: 滑块移动轨迹列表\n \"\"\"\n v=0\n # 单位时间为0.2s来统计轨迹,轨迹即0.2内的位移\n t=0.2\n # 位移/轨迹列表,列表内的一个元素代表0.2s的位移\n tracks=[]\n # 当前的位移\n current=0\n # 到达mid值开始减速\n mid=distance * 7/8\n\n distance += 10 # 先滑过一点,最后再反着滑动回来\n # a = random.randint(1,3)\n while current < distance:\n if current < mid:\n # 加速度越小,单位时间的位移越小,模拟的轨迹就越多越详细\n a = random.randint(2,4) # 加速运动\n else:\n a = -random.randint(3,5) # 减速运动\n\n # 初速度\n v0 = v\n # 0.2秒时间内的位移\n s = v0*t+0.5*a*(t**2)\n # 当前的位置\n current += s\n # 添加到轨迹列表\n tracks.append(round(s))\n\n # 速度已经达到v,该速度作为下次的初速度\n v= v0+a*t\n\n # 反着滑动到大概准确位置\n for i in range(4):\n tracks.append(-random.randint(2,3))\n for i in range(4):\n tracks.append(-random.randint(1,3))\n print(tracks)\n return tracks\n\n def move_button(self, button, track):\n \"\"\"\n 将滑块拖动到指定位置\n :param button: 滑动块\n :param track: 滑块运动轨迹列表\n :return: None\n \"\"\"\n ActionChains(self.browser).click_and_hold(button).perform()\n for i in track:\n ActionChains(self.browser).move_by_offset(xoffset=i, yoffset=0).perform()\n sleep(0.002)\n ActionChains(self.browser).release().perform()\n\n def crack(self):\n \"\"\"\n 串接整个流程:\n 1. 输入账号密码\n 2. 获取滑动块\n 3. 获取两张验证码图片\n 4. 获取滑块移动轨迹\n 5. 将滑块拖动至指定位置\n :return:\n \"\"\"\n self.login()\n button = self.get_button()\n captcha = self.get_geetest_image(button)\n print(captcha)\n left = self.get_gap(captcha[0], captcha[1])\n print(left)\n track = self.get_track(left)\n # 如果尝试登陆失败, 则重新验证, 最多三次\n times = 0\n while times < 3:\n self.move_button(button, track)\n try:\n success = self.wait.until(EC.text_to_be_present_in_element((By.CLASS_NAME, 'geetest_success_radar_tip_content'), '通过验证'))\n print(success)\n except TimeoutException as e:\n times += 1\n print('fail')\n self.browser.refresh() #要不要刷新取决于是否有做反扒,有时候第二次滑动就会出现网络异常要你点击的情况\n self.login()\n button = self.get_button()\n captcha = self.get_geetest_image(button)\n print(captcha)\n left = self.get_gap(captcha[0], captcha[1])\n print(left)\n track = self.get_track(left)\n else:\n print('success')\n return None\n\n\nif __name__ == '__main__':\n ACCOUNT = input('请输入您的账号:')\n PASSOWRD = input('请输入您的密码:')\n\n test = BiliBili(ACCOUNT, PASSOWRD) # 输入账号和密码\n test.crack()","sub_path":"bibi.py","file_name":"bibi.py","file_ext":"py","file_size_in_byte":9319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"305118479","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport os\n\nimport DGenerator as generator\nfrom TrainingUtils import dice_loss, dice_coef, dice_coefficient_numpy_arrays\nfrom keras.models import model_from_json\n\n\nif __name__ == '__main__':\n\n data_dir = 'D:/prostate_data/Task05_Prostate/imagesTs/'\n target_dir = 'D:/prostate_data/Task05_Prostate/labelsTs/'\n model_folder = 'ModelOutputs/UNet_regularWAugcGAN_rev2/1500_syn_samples/'\n #\n # model_folder = 'ModelOutputs/UNet_regular_rev2/'\n\n\n\n # json_file_name = [i for i in os.listdir(model_folder) if i.endswith('json')][0]\n # weights_file_name = [i for i in os.listdir(model_folder) if i.startswith('model_best')][0]\n # json_file = open(''.join([model_folder, '/', json_file_name]))\n # loaded_model_json = json_file.read()\n # json_file.close()\n # model = model_from_json(loaded_model_json)\n #\n # # Load the weights to the model\n # model.load_weights(''.join([model_folder, '/', weights_file_name]))\n # model.compile(loss=dice_loss, metrics=[dice_coef],\n # optimizer='ADAM')\n\n gen = generator.DGenerator(data_dir=data_dir,\n target_dir=target_dir,\n batch_size=1,\n regular=True,\n shuffle=False)\n\n gen.batch_size = gen.__len__()\n\n test_set, test_tar = gen.__getitem__(0)\n\n # y_pred_hold = model.predict(test_set, verbose=1)\n y_pred_hold = np.load(model_folder + '/test_results/pred_TestSet.npy')\n\n y_pred = np.where(y_pred_hold >= 0.5, 1, 0)\n\n pred_shape = y_pred.shape\n\n # If prediction is accidentally channels first, fix\n if pred_shape[1] != pred_shape[2]:\n\n y_pred = np.rollaxis(y_pred, axis=1, start=4)\n\n\n dice_coefficient = []\n\n for index in range(y_pred.shape[0]):\n # prep the data\n predicted_volume = y_pred[index, :, :, :].astype('float32')\n target_volume = test_tar[index, :, :, :]\n\n dice_coefficient_hold = dice_coefficient_numpy_arrays(target_volume[:, :, 0],\n predicted_volume[:, :, 0])\n\n dice_coefficient.append(dice_coefficient_hold)\n\n\n dice_coefficient = np.array(dice_coefficient)\n\n sort_idx = np.argsort(dice_coefficient)[::-1]\n\n\n idx_hold_tot = [211, 212]\n\n fig = plt.figure(figsize=(6, 6))\n sub_plot_idx = 0\n\n for idx in range(2):\n\n idx_hold = idx_hold_tot[idx]\n\n DSC = dice_coefficient[idx_hold]\n\n ground_truth_data = test_tar[idx_hold, :, :, 0]\n pred_data = y_pred[idx_hold, :, :, 0]\n test_data = test_set[idx_hold, :, :, 0]\n\n\n ax1 = fig.add_subplot(2, 2, sub_plot_idx + 1)\n sub_plot_idx += 1\n plt1 = ax1.imshow(test_data, cmap='gray')\n\n ax1.set_title('MRI Slice of Prostate', fontsize=14, fontname='Times New Roman')\n\n\n ax2 = fig.add_subplot(2, 2, sub_plot_idx + 1)\n sub_plot_idx += 1\n\n plt1 = ax2.imshow(ground_truth_data, cmap='Greys')\n plt2 = ax2.imshow(test_data, cmap='gray', alpha=0.5)\n plt3 = ax2.contour(pred_data, colors='r', linewidths=0.5)\n\n ax2.set_title(r'DSC = {:.2f}'.format(DSC), fontsize=14, fontname='Times New Roman')\n\n ax1.axis('off')\n ax2.axis('off')\n\n\n\n red_patch = mpatches.Patch(color='red', label='Contour of Predicted Segmentation')\n black = mpatches.Patch(color='k', label='Ground Truth (GT) Segmentation')\n plt.figlegend(handles=[red_patch, black], loc='lower center', fontsize=12)\n\n\n plt.show()\n # plt.savefig('segmentation_best_regular.png', bbox_inches='tight', dpi=650)\n #\n # plt.savefig('segmentation_best.svg', box_inches='tight', dpi=650)\n","sub_path":"plot_images.py","file_name":"plot_images.py","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"555506278","text":"from django.shortcuts import render\nfrom django.utils import timezone\nfrom .models import Post\nfrom .models import Cliente\nfrom django.shortcuts import render, get_object_or_404\nfrom .forms import PostForm\nfrom .forms import ClienteForm\nfrom django.shortcuts import redirect\nfrom django.contrib.auth.models import User\n\ndef index(request):\n return render(request, 'blog/index.html', {})\n\ndef acerca(request):\n return render(request, 'blog/acerca.html', {})\n\ndef contacto(request):\n return render(request, 'blog/contacto.html', {})\n\ndef recibedatos(request):\n return render(request, 'blog/recibedatos.html', {})\n\ndef cliente_detail(request, pk):\n cliente = get_object_or_404(Cliente, pk=pk)\n return render(request, 'blog/cliente_detail.html', {'cliente': cliente})\n\ndef cliente_new(request):\n form = ClienteForm(request.POST)\n if request.method == \"POST\":\n if form.is_valid():\n cliente = form.save(commit=False)\n cliente.usuario = request.user \n cliente.save()\n return redirect('cliente_detail', cliente.id)\n return render(request, 'blog/cliente_edit.html', {'form': form})\n\ndef cliente_edit(request, pk):\n cliente = get_object_or_404(Cliente, pk=pk)\n if request.method == \"POST\":\n form = ClienteForm(request.POST, instance=cliente)\n if form.is_valid():\n cliente = form.save(commit=False)\n cliente.usuario = request.user \n cliente.save()\n return redirect('cliente_edit', pk=cliente.pk)\n else:\n form = ClienteForm(instance=cliente)\n return render(request, 'blog/cliente_edit.html', {'form': form})\n\n\n\ndef pagina_blanca(request):\n return render(request, 'blog/blanca.html', {})\n\ndef pagina_diccionario(request):\n # El siguiente es un QuerySet (conjunto de datos pareceido a SELECT * FROM POSTS)\n #posts = Post.objects.all()\n #sql_query = str(posts.query)\n #nombre_usuario = \"Ana Torres\"\n #edad_usuario = 26\n #cant_usuario = 101\n #contexto = {'posts': posts,\n # 'la_query':sql_query,\n # 'nombre_user':nombre_usuario,\n # 'edad_user':edad_usuario,\n # 'total_usuario':cant_usuario}\n \n # para enviar datos al templates debemos cargar estos valores en un diccionario python\n return render(request, 'blog/diccionario.html', contexto)\n\ndef post_detail(request, pk):\n post = get_object_or_404(Post, pk=pk)\n return render(request, 'blog/post_detail.html', {'post': post})\n\ndef post_new(request):\n form = PostForm(request.POST)\n if request.method == \"POST\":\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user \n post.published_date = timezone.now()\n post.save()\n return redirect('post_detail', post.id)\n return render(request, 'blog/post_edit.html', {'form': form})\n\ndef post_edit(request, pk):\n post = get_object_or_404(Post, pk=pk)\n if request.method == \"POST\":\n form = PostForm(request.POST, instance=post)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user \n post.published_date = timezone.now()\n post.save()\n return redirect('post_detail', pk=post.pk)\n else:\n form = PostForm(instance=post)\n return render(request, 'blog/post_edit.html', {'form': form})\n\n# Post edit con mensajes\n# def post_edit(request, pk):\n# print(\"\\nDENTRO DEL CONTROLADOR\\n\")\n# post = get_object_or_404(Post, pk=pk)\n# print(\"\\n\\n================= post_edit(entrando) =======================\\n\\n\")\n# print(post.title)\n# print (request.user)\n# print(post)\n# print(\"=================================================================\\n\\n\")\n# if request.method == \"POST\":\n# print(\"\\nDENTRO DEL POST\\n\")\n# form = PostForm(request.POST, instance=post)\n# if form.is_valid():\n# print(\"\\nDENTRO DEL FORMULARIO VALIDO\\n\")\n# post = form.save(commit=False)\n# post.author = request.user \n# # post.author = User.objects.get(id=1) # Otra alternativa es escoger un usuario específico\n# # post.author = User.objects.create('myusername', 'myemail@crazymail.com', 'mypassword') # Otra alternativa es crear un nuevo usuario\n# post.published_date = timezone.now()\n# post.save()\n# return redirect('post_detail', pk=post.pk)\n# else:\n# form = PostForm(instance=post)\n# print(\"\\n\\n=============== post_edit(cuan no es POST) ======================\")\n# print(\"CUANDO NO ES POST\")\n# print(form)\n# print(post)\n# print(\"\\n\\n=================================================================\")\n# return render(request, 'blog/post_edit.html', {'form': form})","sub_path":"Magicard/mysite/blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"607202788","text":"# -*- coding: utf-8 -*-\n''' Implement NoLimit Texas Hold'em Round class\n'''\nfrom enum import Enum\n\nfrom rlcard.games.limitholdem import PlayerStatus\nimport numpy as np\n\n\n# change proceed_round if this get changed\nclass Action(Enum):\n\n FOLD = 0\n CHECK = 1\n CALL = 2\n RAISE_1BB = 3\n RAISE_2BB = 4\n RAISE_3BB = 5\n RAISE_5BB = 6\n RAISE_HALF_POT = 7\n RAISE_POT = 8\n RAISE_2POT = 9\n RAISE_3POT = 10\n RAISE_5POT = 11\n RAISE_7POT = 12\n RAISE_10POT = 13\n ALL_IN = 14\n # SMALL_BLIND = 7\n # BIG_BLIND = 8\n\n\nclass NolimitholdemRound():\n ''' Round can call other Classes' functions to keep the game running\n '''\n\n def __init__(self, num_players, init_raise_amount, dealer, np_random):\n ''' Initilize the round class\n\n Args:\n num_players (int): The number of players\n init_raise_amount (int): The min raise amount when every round starts\n '''\n self.np_random = np_random\n self.game_pointer = None\n self.num_players = num_players\n self.init_raise_amount = init_raise_amount\n self.dealer = dealer\n\n # Count the number without raise\n # If every player agree to not raise, the round is overr\n self.not_raise_num = 0\n\n # Count players that are not playing anymore (folded or all-in)\n self.not_playing_num = 0\n\n # Raised amount for each player\n self.raised = [0 for _ in range(self.num_players)]\n\n def start_new_round(self, game_pointer, raised=None):\n ''' Start a new bidding round\n\n Args:\n raised (list): Initialize the chips for each player\n\n Note: For the first round of the game, we need to setup the big/small blind\n '''\n self.game_pointer = game_pointer\n self.not_raise_num = 0\n if raised:\n self.raised = raised\n else:\n self.raised = [0 for _ in range(self.num_players)]\n\n def get_players_hist_bets(self):\n return self.players_hist_bets\n\n\n\n def proceed_round(self, players, action):\n ''' Call other Classes's functions to keep one round running\n\n Args:\n players (list): The list of players that play the game\n action (str/int): An legal action taken by the player\n\n Returns:\n (int): The game_pointer that indicates the next player\n '''\n player = players[self.game_pointer]\n\n bet_amount = 0\n\n\n if action == Action.CALL:\n diff = max(self.raised) - self.raised[self.game_pointer]\n self.raised[self.game_pointer] = max(self.raised)\n player.bet(chips=diff)\n bet_amount = diff\n self.not_raise_num += 1\n\n elif action == Action.ALL_IN:\n all_in_quantity = player.remained_chips\n self.raised[self.game_pointer] = all_in_quantity + self.raised[self.game_pointer]\n player.bet(chips=all_in_quantity)\n bet_amount = all_in_quantity\n self.not_raise_num = 1\n\n # needs to be changed if class Action(Enum) is changed\n elif 13 >= action.value >= 3:\n if action == Action.RAISE_1BB:\n quantity = self.init_raise_amount\n elif action == Action.RAISE_2BB:\n quantity = self.init_raise_amount * 2\n elif action == Action.RAISE_3BB:\n quantity = self.init_raise_amount * 3\n elif action == Action.RAISE_5BB:\n quantity = self.init_raise_amount * 5\n elif action == Action.RAISE_POT:\n quantity = self.dealer.pot\n elif action == Action.RAISE_HALF_POT:\n quantity = int(self.dealer.pot / 2)\n elif action == Action.RAISE_2POT:\n quantity = self.dealer.pot * 2\n elif action == Action.RAISE_3POT:\n quantity = self.dealer.pot * 3\n elif action == Action.RAISE_5POT:\n quantity = self.dealer.pot * 5\n elif action == Action.RAISE_7POT:\n quantity = self.dealer.pot * 7\n else:\n quantity = self.dealer.pot * 10\n self.raised[self.game_pointer] += quantity\n player.bet(chips=quantity)\n bet_amount = quantity\n self.not_raise_num = 1\n\n elif action == Action.FOLD:\n player.status = PlayerStatus.FOLDED\n\n elif action == Action.CHECK:\n self.not_raise_num += 1\n\n if player.remained_chips < 0:\n raise Exception(\"Player in negative stake\")\n\n if player.remained_chips == 0 and player.status != PlayerStatus.FOLDED:\n player.status = PlayerStatus.ALLIN\n\n self.game_pointer = (self.game_pointer + 1) % self.num_players\n\n if player.status == PlayerStatus.ALLIN:\n self.not_playing_num += 1\n self.not_raise_num -= 1 # Because already counted in not_playing_num\n if player.status == PlayerStatus.FOLDED:\n self.not_playing_num += 1\n\n # Skip the folded players\n while players[self.game_pointer].status == PlayerStatus.FOLDED:\n self.game_pointer = (self.game_pointer + 1) % self.num_players\n\n return bet_amount, self.game_pointer\n\n def get_nolimit_legal_actions(self, players):\n ''' Obtain the legal actions for the curent player\n\n Args:\n players (list): The players in the game\n\n Returns:\n (list): A list of legal actions\n '''\n\n full_actions = list(Action)\n # If the current chips are less than that of the highest one in the round, we can not check\n if self.raised[self.game_pointer] < max(self.raised):\n full_actions.remove(Action.CHECK)\n\n # If the current player has put in the chips that are more than others, we can not call\n if self.raised[self.game_pointer] == max(self.raised):\n full_actions.remove(Action.CALL)\n\n player = players[self.game_pointer]\n\n if Action.RAISE_HALF_POT in full_actions and \\\n (int(self.dealer.pot / 2) + player.in_chips <= max(self.raised) or\n int(self.dealer.pot / 2) > player.remained_chips):\n full_actions.remove(Action.RAISE_HALF_POT)\n\n if Action.RAISE_POT in full_actions and \\\n (self.dealer.pot + player.in_chips <= max(self.raised) or\n self.dealer.pot > player.remained_chips):\n full_actions.remove(Action.RAISE_POT)\n\n if Action.RAISE_2POT in full_actions and \\\n (self.dealer.pot * 2 + player.in_chips <= max(self.raised) or\n self.dealer.pot * 2 > player.remained_chips):\n full_actions.remove(Action.RAISE_2POT)\n\n if Action.RAISE_3POT in full_actions and \\\n (self.dealer.pot * 3 + player.in_chips <= max(self.raised) or\n self.dealer.pot * 3 > player.remained_chips):\n full_actions.remove(Action.RAISE_3POT)\n\n if Action.RAISE_5POT in full_actions and \\\n (self.dealer.pot * 5 + player.in_chips <= max(self.raised) or\n self.dealer.pot * 5 > player.remained_chips):\n full_actions.remove(Action.RAISE_5POT)\n\n if Action.RAISE_7POT in full_actions and \\\n (self.dealer.pot * 7 + player.in_chips <= max(self.raised) or\n self.dealer.pot * 7 > player.remained_chips):\n full_actions.remove(Action.RAISE_7POT)\n\n if Action.RAISE_10POT in full_actions and \\\n (self.dealer.pot * 10 + player.in_chips <= max(self.raised) or\n self.dealer.pot * 10 > player.remained_chips):\n full_actions.remove(Action.RAISE_10POT)\n\n if Action.RAISE_1BB in full_actions and \\\n (self.init_raise_amount + player.in_chips <= max(self.raised) or\n self.init_raise_amount > player.remained_chips):\n full_actions.remove(Action.RAISE_1BB)\n\n if Action.RAISE_2BB in full_actions and \\\n (self.init_raise_amount * 2 + player.in_chips <= max(self.raised) or\n self.init_raise_amount * 2 > player.remained_chips):\n full_actions.remove(Action.RAISE_2BB)\n\n if Action.RAISE_3BB in full_actions and \\\n (self.init_raise_amount * 3 + player.in_chips <= max(self.raised) or\n self.init_raise_amount * 3 > player.remained_chips):\n full_actions.remove(Action.RAISE_3BB)\n\n if Action.RAISE_5BB in full_actions and \\\n (self.init_raise_amount * 5 + player.in_chips <= max(self.raised) or\n self.init_raise_amount * 5 > player.remained_chips):\n full_actions.remove(Action.RAISE_5BB)\n\n # If the current player has no more chips after call, we cannot raise\n diff = max(self.raised) - self.raised[self.game_pointer]\n if diff > 0 and player.in_chips + diff >= player.remained_chips:\n return [Action.FOLD, Action.CALL]\n\n return full_actions\n\n def is_over(self):\n ''' Check whether the round is over\n\n Returns:\n (boolean): True if the current round is over\n '''\n if self.not_raise_num + self.not_playing_num >= self.num_players:\n return True\n return False\n","sub_path":"rlcard/games/nolimitholdem/round.py","file_name":"round.py","file_ext":"py","file_size_in_byte":9288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"405573890","text":"\"\"\"Normalization of STAR quantification results.\"\"\"\nimport gzip\nimport io\nimport json\nimport shutil\nfrom pathlib import Path\n\nimport pandas as pd\nfrom plumbum import TEE\n\nfrom resolwe.process import (\n Cmd,\n DataField,\n FileField,\n IntegerField,\n JsonField,\n SchedulingClass,\n StringField,\n)\n\nfrom resolwe_bio.process.runtime import ProcessBio\n\nSTRANDEDNESS_CODES = {\n \"IU\": 0,\n \"U\": 0,\n \"non_specific\": 0,\n \"ISF\": 1,\n \"OSF\": 1,\n \"SF\": 1,\n \"forward\": 1,\n \"ISR\": 2,\n \"OSR\": 2,\n \"SR\": 2,\n \"reverse\": 2,\n}\n\n\ndef prepare_gene_counts(infile, outfile, summary, strandedness):\n \"\"\"Extract gene counts from STAR input.\"\"\"\n exp = pd.read_csv(\n infile,\n sep=\"\\t\",\n names=[\"Geneid\", 0, 1, 2],\n index_col=\"Geneid\",\n dtype={\"Geneid\": str, 0: int, 1: int, 2: int},\n )\n # Raw counts for genes\n gene_rc_df = exp.iloc[4:][[strandedness]]\n gene_rc_df.to_csv(\n outfile,\n index_label=\"FEATURE_ID\",\n header=[\"EXPRESSION\"],\n sep=\"\\t\",\n )\n\n assigned_reads = gene_rc_df.sum()\n assigned_reads = int(assigned_reads.values)\n summary_df = exp.iloc[:4][[strandedness]]\n summary_df.loc[\"N_assigned\"] = assigned_reads\n\n summary_df.to_csv(\n summary,\n index_label=\"Status\",\n header=[\"Read count\"],\n sep=\"\\t\",\n )\n return exp.iloc[4:].index.to_list()\n\n\ndef rename_columns_and_compress(infile, outfile):\n \"\"\"Rename columns and compress the expression files.\"\"\"\n exp = pd.read_csv(\n infile,\n sep=\"\\t\",\n usecols=[\"FEATURE_ID\", \"EXPRESSION\"],\n index_col=\"FEATURE_ID\",\n squeeze=True,\n float_precision=\"round_trip\",\n )\n exp.to_csv(\n outfile, index_label=\"Gene\", header=[\"Expression\"], sep=\"\\t\", compression=\"gzip\"\n )\n\n\ndef compress_outputs(input_file, output_file):\n \"\"\"Compress outputs.\"\"\"\n with open(file=input_file, mode=\"rb\") as f_in:\n with gzip.open(filename=output_file, mode=\"wb\") as f_out:\n shutil.copyfileobj(f_in, f_out)\n\n\ndef exp_to_df(exp_file, exp_type):\n \"\"\"Prepare expression file for gene sets merging.\"\"\"\n with open(exp_file) as exp:\n df = pd.read_csv(exp, sep=\"\\t\", float_precision=\"round_trip\")\n df.rename(\n index=str,\n columns={\n \"EXPRESSION\": exp_type,\n },\n inplace=True,\n )\n # Cast FEATURE_ID column to string\n df[\"FEATURE_ID\"] = df[\"FEATURE_ID\"].astype(\"str\")\n\n return df\n\n\ndef prepare_expression_set(rc, tpm, cpm, feature_dict, outfile_name):\n \"\"\"Prepare expression set output data.\"\"\"\n rc_exp = exp_to_df(rc, \"RAW_COUNT\")\n tpm_exp = exp_to_df(tpm, \"TPM\")\n cpm_exp = exp_to_df(cpm, \"CPM\")\n rc_exp[\"GENE_SYMBOL\"] = rc_exp[\"FEATURE_ID\"].map(feature_dict)\n input_features = rc_exp[\"FEATURE_ID\"].tolist()\n # Check if all of the input feature IDs could be mapped to the gene symbols\n if not all(f_id in feature_dict for f_id in input_features):\n print(\n f\"{sum(rc_exp.isnull().values.ravel())} feature(s) \"\n f\"could not be mapped to the associated feature symbols.\"\n )\n # Merge with normalized expression values\n exp_set = rc_exp.merge(tpm_exp, on=\"FEATURE_ID\")\n exp_set = exp_set.merge(cpm_exp, on=\"FEATURE_ID\")\n # Reorder columns\n columns = [\"FEATURE_ID\", \"GENE_SYMBOL\", \"RAW_COUNT\", \"TPM\", \"CPM\"]\n exp_set = exp_set[columns]\n # Replace NaN values with empty string\n exp_set.fillna(\"\", inplace=True)\n\n # Write to file\n exp_set.to_csv(\n outfile_name + \".txt.gz\",\n header=True,\n index=False,\n sep=\"\\t\",\n compression=\"gzip\",\n )\n\n # Write to JSON\n df_dict = exp_set.set_index(\"FEATURE_ID\").to_dict(orient=\"index\")\n with open(outfile_name + \".json\", \"w\") as f:\n json.dump({\"genes\": df_dict}, f, allow_nan=False)\n\n\ndef expression_to_storage(rc_input, rc_output):\n \"\"\"Convert expressions file to JSON format.\"\"\"\n\n def isfloat(value):\n \"\"\"Check if value is float.\"\"\"\n try:\n float(value)\n return True\n except ValueError:\n return False\n\n with io.TextIOWrapper(io.BufferedReader(gzip.open(rc_input))) as f:\n # Split lines by tabs\n # Ignore lines without a number in second column\n # Build a dictionary of gene-expression pairs\n exp = {\n \"genes\": {\n gene_exp[0]: float(gene_exp[1])\n for gene_exp in (l.split(\"\\t\") for l in f)\n if len(gene_exp) == 2 and isfloat(gene_exp[1])\n }\n }\n\n with open(file=rc_output, mode=\"wt\") as f:\n json.dump(exp, f)\n\n return rc_output\n\n\nclass NormalizeSTARGeneQuantification(ProcessBio):\n \"\"\"Normalize STAR quantification results.\n\n This process is based on the output of STAR aligner 'gene counts'.\n Strandedness is detected with Salmon or it can be specified manually.\n Finally, for normalization of gene counts TPM and CPM are used.\n \"\"\"\n\n slug = \"star-quantification\"\n name = \"STAR gene quantification\"\n requirements = {\n \"expression-engine\": \"jinja\",\n \"executor\": {\n \"docker\": {\n \"image\": \"public.ecr.aws/genialis/resolwebio/rnaseq:6.2.0\",\n },\n },\n \"resources\": {\n \"cores\": 2,\n \"memory\": 16384,\n \"network\": True,\n },\n }\n data_name = \"{{ aligned_reads|name|default('?') }}\"\n version = \"1.2.0\"\n process_type = \"data:expression:star\"\n category = \"Quantify\"\n entity = {\n \"type\": \"sample\",\n }\n scheduling_class = SchedulingClass.BATCH\n\n class Input:\n \"\"\"Input fields.\"\"\"\n\n aligned_reads = DataField(\n \"alignment:bam:star\",\n label=\"Aligned reads\",\n description=\"Make sure aligned object from STAR also \"\n \"includes gene counts otherwise the process will fail.\",\n )\n\n annotation = DataField(\n \"annotation\",\n label=\"Annotation\",\n description=\"GTF and GFF3 annotation formats are supported.\",\n )\n\n normalization_type = StringField(\n label=\"Normalization type\",\n default=\"TPM\",\n choices=[\n (\"TPM\", \"TPM\"),\n (\"CPM\", \"CPM\"),\n ],\n description=\"The expression normalization type.\",\n )\n\n assay_type = StringField(\n label=\"Assay type\",\n default=\"non_specific\",\n choices=[\n (\"non_specific\", \"Strand non-specific\"),\n (\"forward\", \"Strand-specific forward\"),\n (\"reverse\", \"Strand-specific reverse\"),\n (\"auto\", \"Detect automatically\"),\n ],\n description=\"Indicate if strand-specific read counting should be performed. \"\n \"For paired-end reads, strand of the first read is taken as the strand \"\n \"of the whole fragment. FLAG field is used to tell if a read is \"\n \"first or second read in a pair. Automated strand detection is enabled \"\n \"using the [Salmon](https://salmon.readthedocs.io/en/latest/library_type.html) \"\n \"tool's build-in functionality. To use this option, cDNA (transcriptome) \"\n \"index file created using the Salmon indexing tool must be provided\",\n )\n\n cdna_index = DataField(\n \"index:salmon\",\n label=\"Salmon index file\",\n required=False,\n hidden=\"assay_type != 'auto'\",\n description=\"Transcriptome index file created using the Salmon indexing tool. \"\n \"cDNA (transcriptome) sequences used for index file creation must be \"\n \"derived from the same species as the input sequencing reads to \"\n \"obtain the reliable analysis results.\",\n )\n\n n_reads = IntegerField(\n label=\"Number of reads in subsampled alignment file\",\n default=5000000,\n hidden=\"assay_type != 'auto'\",\n description=\"Alignment (.bam) file subsample size to detect \"\n \"strandedness. Increase the number of reads to make automatic \"\n \"detection more reliable. Decrease the number of reads to \"\n \"make automatic detection run faster.\",\n )\n\n class Output:\n \"\"\"Output fields.\"\"\"\n\n rc = FileField(label=\"Read counts\")\n tpm = FileField(label=\"TPM\")\n cpm = FileField(label=\"CPM\")\n exp = FileField(label=\"Normalized expression\")\n exp_json = JsonField(label=\"Expression (json)\")\n exp_type = StringField(label=\"Expression type\")\n exp_set = FileField(label=\"Expressions\")\n exp_set_json = JsonField(label=\"Expressions (json)\")\n counts_summary = FileField(label=\"Counts summary\")\n strandedness_report = FileField(\n label=\"Strandedness report file\",\n required=False,\n )\n source = StringField(label=\"Gene ID source\")\n species = StringField(label=\"Species\")\n build = StringField(label=\"Build\")\n feature_type = StringField(label=\"Feature type\")\n\n def run(self, inputs, outputs):\n \"\"\"Run the analysis.\"\"\"\n\n if not inputs.aligned_reads.output.gene_counts:\n self.error(\n \"Aligned reads should contain gene count information, but do not.\"\n )\n\n if inputs.aligned_reads.output.species != inputs.annotation.output.species:\n self.error(\n f\"Species of aligned reads {inputs.aligned_reads.output.species} \"\n f\"and annotation {inputs.annotation.output.species} do not match. Please provide \"\n \"aligned reads and annotation with the same species.\"\n )\n\n if inputs.aligned_reads.output.build != inputs.annotation.output.build:\n self.error(\n f\"Builds of aligned reads {inputs.aligned_reads.output.species} \"\n f\"and annotation {inputs.annotation.output.species} do not match. Please provide \"\n \"aligned reads and annotation with the same build.\"\n )\n\n if inputs.assay_type == \"auto\" and not inputs.cdna_index:\n self.error(\n \"cDNA sequence index must be provided to automatically detect strandedness.\"\n )\n\n if (\n inputs.cdna_index\n and inputs.aligned_reads.output.species != inputs.cdna_index.output.species\n ):\n self.error(\n f\"Species of aligned reads {inputs.aligned_reads.output.species} \"\n f\"and cDNA index {inputs.annotation.output.species} do not match. Please provide \"\n \"aligned reads and cDNA index with the same species.\"\n )\n\n bam_file = Path(inputs.aligned_reads.output.bam.path)\n\n # Set output file names\n assert bam_file.name.endswith(\".bam\")\n name = bam_file.name[:-4]\n\n # check if aligned reads are single or paired-end\n paired_end = True\n if int(Cmd[\"samtools\"][\"view\"][\"-c\", \"-f\", \"1\", bam_file]().strip()) == 0:\n paired_end = False\n\n # set strandedness\n if inputs.assay_type == \"auto\":\n all_reads = int(Cmd[\"samtools\"][\"view\"][\"-c\", bam_file]().strip())\n sampling_rate = min(inputs.n_reads / all_reads, 1)\n # subsample the BAM file\n if sampling_rate < 1:\n strand_check_bam = \"subsampled_sorted.bam\"\n (\n Cmd[\"samtools\"][\"view\"][\n f\"-@ {self.requirements.resources.cores}\",\n \"-h\",\n f\"-s {sampling_rate}\",\n bam_file,\n ]\n | Cmd[\"samtools\"][\"sort\"][\n f\"-@ {self.requirements.resources.cores}\", \"-n\", \"-\"\n ]\n > strand_check_bam\n )()\n else:\n strand_check_bam = \"sorted.bam\"\n sort_args = [\n f\"-@ {self.requirements.resources.cores}\",\n \"-n\",\n \"-o\",\n strand_check_bam,\n ]\n return_code, _, _ = Cmd[\"samtools\"][\"sort\"][sort_args][bam_file] & TEE(\n retcode=None\n )\n if return_code:\n self.error(\"Error while running Samtools sort.\")\n\n # Consider only proper paired-end reads for strandedness detection (-0, -s to /dev/null).\n # Failure to do so will result in improper strandedness detection.\n fastq_args = [f\"-@ {self.requirements.resources.cores}\", \"-N\"]\n if paired_end:\n reads_input = [\"-1\", \"mate1.fastq\", \"-2\", \"mate2.fastq\"]\n fastq_args.extend([\"-0\", \"/dev/null\", \"-s\", \"/dev/null\"])\n else:\n reads_input = [\"-0\", \"reads.fastq\"]\n\n fastq_args.extend(reads_input)\n\n return_code, _, _ = Cmd[\"samtools\"][\"fastq\"][fastq_args][\n strand_check_bam\n ] & TEE(retcode=None)\n if return_code:\n self.error(\"Samtools fastq command failed.\")\n\n salmon_out_folder = \"salmon_output\"\n\n # Run Salmon Quant\n salmon_args = [\n \"-i\",\n inputs.cdna_index.output.index.path,\n \"-l\",\n \"A\",\n reads_input if paired_end else [\"-r\", \"reads.fastq\"],\n \"-o\",\n salmon_out_folder,\n \"-p\",\n self.requirements.resources.cores,\n \"--minAssignedFrags\",\n 1,\n ]\n return_code, _, _ = Cmd[\"salmon\"][\"quant\"][salmon_args] & TEE(retcode=None)\n if return_code:\n self.error(\"Error while running Salmon Quant.\")\n\n # Extract the strandedness code from the JSON report produced by the Salmon tool\n lib_type_report = f\"{salmon_out_folder}/lib_format_counts.json\"\n outputs.strandedness_report = lib_type_report\n strand_code = json.load(open(lib_type_report)).get(\"expected_format\", \"\")\n\n if strand_code:\n try:\n strandedness = STRANDEDNESS_CODES[strand_code]\n except KeyError:\n self.error(\n f\"Unsupported strand code detected: {strand_code} \"\n \"Please re-run analysis in user-selected strandedness mode \"\n \"or try increasing the subsample size.\"\n )\n else:\n self.error(\n \"Automated detection of strandedness failed. \"\n \"Re-run analysis in user-selected strandedness mode.\"\n )\n else:\n strandedness = STRANDEDNESS_CODES[inputs.assay_type]\n\n raw_counts = \"rc.txt\"\n tpm = \"tpm.txt\"\n cpm = \"cpm.txt\"\n\n # prepare_gene_counts() has a side effect of creating csv files\n # used in 'rnanorm'.\n features = prepare_gene_counts(\n infile=inputs.aligned_reads.output.gene_counts.path,\n outfile=raw_counts,\n summary=\"summary.txt\",\n strandedness=strandedness,\n )\n\n annotation_file = inputs.annotation.output.annot.path\n if (\n inputs.annotation.output.source == \"UCSC\"\n and inputs.annotation.type.startswith(\"data:annotation:gtf\")\n ):\n with open(annotation_file, \"r\") as infile:\n filedata = infile.read()\n\n # Replace the missing gene_ids\n annot_data = filedata.replace('gene_id \"\";', 'gene_id \"unknown\";')\n\n # Write the output file\n annotation_file = \"annotation_modified.gtf\"\n with open(annotation_file, \"w\") as outfile:\n outfile.write(annot_data)\n\n # Normalize counts\n rnanorm_args = [\n raw_counts,\n \"--tpm-output\",\n tpm,\n \"--cpm-output\",\n cpm,\n \"--annotation\",\n annotation_file,\n ]\n return_code, _, _ = Cmd[\"rnanorm\"][rnanorm_args] & TEE(retcode=None)\n if return_code:\n self.error(\"Error while normalizing counts using rnanorm.\")\n\n feature_filters = {\n \"source\": inputs.annotation.output.source,\n \"species\": inputs.aligned_reads.output.species,\n \"feature_id__in\": features,\n }\n\n feature_ids_to_names = {\n f.feature_id: f.name for f in self.feature.filter(**feature_filters)\n }\n\n prepare_expression_set(\n rc=raw_counts,\n tpm=tpm,\n cpm=cpm,\n feature_dict=feature_ids_to_names,\n outfile_name=f\"{name}_expressions\",\n )\n\n # rename and compress the expression files\n rename_columns_and_compress(raw_counts, f\"{name}_rc.tab.gz\")\n rename_columns_and_compress(tpm, f\"{name}_tpm.tab.gz\")\n rename_columns_and_compress(cpm, f\"{name}_cpm.tab.gz\")\n\n exp_output = f\"{name}_{inputs.normalization_type.lower()}.tab.gz\"\n\n # Save the abundance estimates to JSON storage\n json_output = \"json.txt\"\n expression_to_storage(rc_input=exp_output, rc_output=json_output)\n\n # Save the outputs\n outputs.counts_summary = \"summary.txt\"\n outputs.rc = f\"{name}_rc.tab.gz\"\n outputs.tpm = f\"{name}_tpm.tab.gz\"\n outputs.cpm = f\"{name}_cpm.tab.gz\"\n outputs.exp = exp_output\n outputs.exp_json = json_output\n outputs.exp_set = f\"{name}_expressions.txt.gz\"\n outputs.exp_set_json = f\"{name}_expressions.json\"\n outputs.exp_type = inputs.normalization_type\n outputs.source = inputs.annotation.output.source\n outputs.species = inputs.aligned_reads.output.species\n outputs.build = inputs.aligned_reads.output.build\n outputs.feature_type = \"gene\"\n","sub_path":"resolwe_bio/processes/expression/star_quantification.py","file_name":"star_quantification.py","file_ext":"py","file_size_in_byte":18072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"567131094","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport os, sys\n\n\nparent = os.path.dirname(os.path.abspath(__file__))\n\nsys.path.insert(0, parent)\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"test_project.settings\")\n\n\nimport django\nfrom django.core.management import execute_from_command_line\n\n\nif django.VERSION < (1, 6):\n default_test_apps = [\n 'sortedm2m_tests',\n 'test_south_support',\n ]\nelse:\n default_test_apps = [\n 'sortedm2m_tests',\n ]\n\n # Only test south support for Django 1.6 and lower.\n if django.VERSION < (1, 7):\n default_test_apps += [\n 'test_south_support',\n ]\n\n\ndef runtests(*args):\n test_apps = list(args or default_test_apps)\n execute_from_command_line([sys.argv[0], 'test', '--verbosity=1'] + test_apps)\n\n\nif __name__ == '__main__':\n runtests(*sys.argv[1:])\n","sub_path":"runtests.py","file_name":"runtests.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"486065994","text":"from datetime import datetime, timedelta\nfrom django.urls import reverse\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse, HttpResponseBadRequest, Http404\n\n\ndef hello_world(request):\n return HttpResponse('Hello World')\n\n\ndef current_date(request):\n try:\n str_format = '%d, %B %Y'\n current_date_today = datetime.now().strftime(str_format)\n except ValueError:\n raise Http404\n return HttpResponse(f'Today is {current_date_today}')\n\n\ndef my_age(request, year, month, day):\n current_year = datetime.now().year\n my_age_format = current_year - year\n return HttpResponse(f'Your age is {my_age_format} years old')\n\n\ndef next_birthday(request, birthday):\n try:\n str_format = '%Y-%m-%d'\n birthday = datetime.strptime(birthday, str_format)\n # print('birthday is :', birthday)\n except ValueError:\n return HttpResponseBadRequest()\n\n today = datetime.now()\n\n nextBirthdayYear = birthday.replace(year=today.year) # override my birthday with current year\n # print('next birthday for year is :', nextBirthdayYear)\n if today > birthday:\n nextBirthdayYear = nextBirthdayYear.replace(year=today.year + 1)\n else:\n nextBirthdayYear = nextBirthdayYear.replace(year=today.year)\n\n diff = nextBirthdayYear - today\n return HttpResponse(f'Days until next birthday: {diff.days}')\n\n\ndef profile(request):\n context = {\n 'my_name':'AZGHOUR',\n 'my_age': 26\n }\n return render(request, 'profile.html', context)\n\n\n\n\"\"\"\n The goal for next task is to practice routing between two URLs.\n You will have:\n - /authors --> contains a list of Authors (template is provided to you)\n - /author/ --> contains the detail for given author,\n using the AUTHORS_INFO provided below.\n\n First view just have to render the given 'authors.html' template sending the\n AUTHORS_INFO as context.\n\n Second view has to take the authors_last_name provided in the URL, look for\n the proper author info in the dictionary, and send it as context while\n rendering the 'author.html' template. Make sure to complete the given\n 'author.html' template with the data that you send.\n\"\"\"\nAUTHORS_INFO = {\n 'poe': {\n 'full_name': 'Edgar Allan Poe',\n 'nationality': 'US',\n 'notable_work': 'The Raven',\n 'born': 'January 19, 1809',\n },\n 'borges': {\n 'full_name': 'Jorge Luis Borges',\n 'nationality': 'Argentine',\n 'notable_work': 'The Aleph',\n 'born': 'August 24, 1899',\n }\n}\n\ndef authors(request):\n context = {\n 'authors': AUTHORS_INFO\n }\n return render(request, 'authors.html', context)\n\n\ndef author(request, authors_last_name):\n if authors_last_name in AUTHORS_INFO:\n return render(request, 'author.html', AUTHORS_INFO[authors_last_name])\n return redirect(reverse('authors')) # Getting 'authors' from url's name","sub_path":"django_practice_1/django_practice_1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"434126801","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# author: bigfoolliu\n\n\n\"\"\"\nsqlalchemy orm 的使用示例\n\nhttps://www.cnblogs.com/chenxi67/p/10376617.html\n\"\"\"\n\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, String, Integer, JSON, func, desc, distinct\nfrom language.python.modules.Database.sqlalchemy.sqlalchemy_base import create_engine_by_url, read_mysql_url, \\\n create_session_by_engine\n\n# 实例化官宣基础模型,sqlalchemy 的模型类继承自一个由declarative_base()方法生成的类\nBase = declarative_base()\n# print(Base.metadata.sorted_tables)\n\nmysql_url = read_mysql_url()\nengine = create_engine_by_url(engine_url=mysql_url)\nsession = create_session_by_engine(engine=engine)\n\n# Base 自动检索所有继承 Base 的ORM模型,并且创建所有的数据表(如果表存在则不会创建)\nBase.metadata.create_all(bind=engine)\n\n\nclass User(Base):\n \"\"\"用户表\"\"\"\n __tablename__ = 'user'\n\n id = Column(Integer, primary_key=True)\n name = Column(String(50))\n age = Column(Integer)\n scores = Column(JSON)\n\n db = session\n\n def __repr__(self):\n return f'User-{self.name}-{self.age}'\n\n @classmethod\n def get_keys(cls):\n keys = ['id', 'name', 'age', 'scores']\n return keys\n\n @classmethod\n def validate_info(cls, info: dict):\n \"\"\"\n 校验 info 数据的正确性\n \"\"\"\n for key in info.keys():\n if key not in cls.get_keys():\n raise ValueError\n\n @classmethod\n def create_info(cls, info: dict):\n \"\"\"\n 创建一条数据并提交\n \"\"\"\n if not info:\n return\n\n cls.validate_info(info)\n user = User(id=info.get('id'), name=info.get('name'), age=info.get('age'), scores=info.get('scores'))\n ret = cls.db.add(user)\n cls.db.commit() # 新增,修改,删除需要提交\n cls.db.close()\n return ret\n\n @classmethod\n def update_info(cls, id_, info):\n \"\"\"\n 修改数据并提交\n \"\"\"\n cls.validate_info(info=info)\n update_info = {'name': info.get('name'), 'age': info.get('age'), 'scores': info.get('scores')}\n cls.db.query(cls).filter(cls.id == id_).update(update_info)\n cls.db.commit()\n return info\n\n @classmethod\n def delete_info(cls, id_):\n \"\"\"\n 删除数据并提交\n \"\"\"\n ret = cls.db.query(cls).filter(cls.id == id_).delete()\n cls.db.commit()\n return ret\n\n\ndef demo_insert_data():\n \"\"\"\n 插入数据示例\n \"\"\"\n ret = User.create_info({'name': 'insert', 'age': 100})\n print(ret)\n\n\ndef demo_update_data():\n \"\"\"\n 修改数据示例\n \"\"\"\n ret = User.update_info(14, {'name': 'insert_update', 'age': 50})\n print(ret)\n\n\ndef demo_delete_data():\n \"\"\"\n 删除数据示例\n \"\"\"\n ret = User.delete_info(id_=14)\n print(ret)\n\n\ndef demo_query_data():\n \"\"\"\n 查询数据示例\n \"\"\"\n # 查询所有的数据\n query = User.db.query(User) # 结果为 SELECT user.id AS user_id, user.name AS user_name ... FROM user\n infos = query.all()\n print(infos) # [User-tony-10, ...]\n\n # 返回结果集中的第二项\n query = User.db.query(User).get(2)\n print(query) # user-tony-10\n\n # 查询条件\n query = User.db.query(User).filter(User.id > 10).first()\n print(query) # user-tony-12\n infos = User.db.query(User).filter(User.scores.in_([5, 6])).all()\n print(infos)\n\n # 排序\n query = User.db.query(User).order_by(desc(User.age))\n infos = query.all()\n print(infos)\n\n # 给结果集的列取别名\n infos = User.db.query(User.name.label('user_name')).all()\n print(infos) # [('tony',), ...]\n\n # 去重查询\n infos = User.db.query(distinct(User.name).label('name')).all()\n print(infos) # [('tony',), ('jane',), ('tom',), ('jim',), ('tim1',)]\n\n # 分组查询\n query = User.db.query(func.count(User.name).label('count'), User.age).group_by(User.age)\n for user in query:\n print(f'age: {user.age}, count: {user.count}')\n\n # JSON_CONTAINS, json类型的数据包含\n infos = User.db.query(User).filter(func.json_contains(User.scores, '[5, 6]')).all()\n print(infos)\n\n # 执行原生sql语句\n cursor = session.execute(r'select * from user limit 2;')\n ret = cursor.fetchall()\n cursor.close()\n print(f'ret: {ret}')\n\n\ndef demo_roll_back_data():\n \"\"\"\n 数据回滚示例\n \"\"\"\n fake_user = User(name='john', age=11)\n session.add(fake_user) # 暂存\n session.rollback() # 回滚,取消暂存\n session.close()\n\n\nif __name__ == '__main__':\n # demo_insert_data()\n # demo_update_data()\n # demo_delete_data()\n # demo_roll_back_data()\n demo_query_data()\n","sub_path":"language/python/modules/Database/sqlalchemy/sqlalchemy_orm.py","file_name":"sqlalchemy_orm.py","file_ext":"py","file_size_in_byte":4776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"585107026","text":"# -*- coding: utf-8 -*-\n\nr\"\"\"\nDisallows to use incorrect magic comments.\n\nThat's how a basic ``comment`` type token looks like:\n\nTokenInfo(\n type=57 (COMMENT),\n string='# noqa: Z100',\n start=(1, 4),\n end=(1, 16),\n line=\"u'' # noqa: Z100\\n\",\n)\n\"\"\"\n\nimport re\nimport tokenize\nfrom typing import ClassVar\nfrom typing.re import Pattern\n\nfrom wemake_python_styleguide.violations.best_practices import (\n WrongDocCommentViolation,\n WrongMagicCommentViolation,\n)\nfrom wemake_python_styleguide.visitors.base import BaseTokenVisitor\n\n\nclass WrongCommentVisitor(BaseTokenVisitor):\n \"\"\"Checks comment tokens.\"\"\"\n\n noqa_check: ClassVar[Pattern] = re.compile(r'^noqa:?($|[A-Z\\d\\,\\s]+)')\n type_check: ClassVar[Pattern] = re.compile(\n r'^type:\\s?([\\w\\d\\[\\]\\'\\\"\\.]+)$',\n )\n\n def _get_comment_text(self, token: tokenize.TokenInfo) -> str:\n return token.string[1:].strip()\n\n def _check_noqa(self, token: tokenize.TokenInfo) -> None:\n comment_text = self._get_comment_text(token)\n match = self.noqa_check.match(comment_text)\n if not match:\n return\n\n excludes = match.groups()[0].strip()\n if not excludes:\n # We can not pass the actual line here,\n # since it will be ignored due to `# noqa` comment:\n self.add_violation(WrongMagicCommentViolation(text=comment_text))\n\n def _check_typed_ast(self, token: tokenize.TokenInfo) -> None:\n comment_text = self._get_comment_text(token)\n match = self.type_check.match(comment_text)\n if not match:\n return\n\n declared_type = match.groups()[0].strip()\n if declared_type != 'ignore':\n self.add_violation(\n WrongMagicCommentViolation(token, text=comment_text),\n )\n\n def _check_empty_doc_comment(self, token: tokenize.TokenInfo) -> None:\n comment_text = self._get_comment_text(token)\n if comment_text == ':':\n self.add_violation(WrongDocCommentViolation(token))\n\n def visit_comment(self, token: tokenize.TokenInfo) -> None:\n \"\"\"\n Performs comment checks.\n\n Raises:\n WrongDocCommentViolation\n WrongMagicCommentViolation\n\n \"\"\"\n self._check_noqa(token)\n self._check_typed_ast(token)\n self._check_empty_doc_comment(token)\n","sub_path":"wemake_python_styleguide/visitors/tokenize/comments.py","file_name":"comments.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"293206038","text":"# -*- coding: utf-8 -*-\n\n\nimport os\nimport socket\n\n\ndef create_class_instance(class_name, *args, **kwargs):\n (module_name, class_name) = class_name.rsplit('.', 1)\n\n module_meta = __import__(module_name, globals(), locals(), [class_name])\n class_meta = getattr(module_meta, class_name)\n result = class_meta(*args, **kwargs)\n\n return result\n\n\ndef add_items_into_dict(target, path='', **kwargs):\n def get_dict_item(di, pl):\n return di if not pl else get_dict_item(di[pl.pop(0)], pl)\n\n di = target if not path else get_dict_item(target, path.split(':'))\n\n for k, v in kwargs.items():\n di[k] = v\n\n return target\n\n\ndef make_dirs(path):\n if path and not os.path.exists(path):\n os.makedirs(path)\n\n\ndef get_ip_address():\n ip = ''\n\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect(('google.com', 80))\n (ip, port) = s.getsockname()\n finally:\n try:\n s.close()\n except:\n pass\n\n return ip\n\n\ndef get_file_path(file_var):\n return os.path.dirname(os.path.realpath(file_var))\n\n\ndef load_file(filename):\n with open(filename, 'r') as f:\n return f.read()\n","sub_path":"worker/qp_stat_report/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"97773917","text":"import numpy as np\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\n\n\n\nmodel=Sequential([\n Dense(32,input_shape=(100,)),\n Activation('relu'),\n Dense(10),\n Activation('softmax'),\n])\n\n# Generate dummy data to test on it.\nimport numpy as np\nx_train = np.random.random((1000, 100))\nx_test=np.random.random((100,100))\ny_test=np.random.randint(10, size=(100,1))\nlabels = np.random.randint(10, size=(1000, 1))\none_hot_labels1 = keras.utils.to_categorical(labels, num_classes=10)\none_hot_labels2=keras.utils.to_categorical(y_test,num_classes=10)\nmodel.compile(optimizer='rmsprop',\n loss='categorical_crossentropy',\n metrics=['accuracy'])\nmodel.summary()\nmodel.fit(x_train, one_hot_labels1, epochs=10, batch_size=32)\nscore=model.evaluate(x_test,one_hot_labels2,batch_size=128)","sub_path":"basics.py","file_name":"basics.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"611418493","text":"import tensorflow as tf\n\ndef weight_variable(shape):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial)\n\ndef bias_variable(shape):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial)\n\n########################################################################3\ndef CNN_comp_graph(x_in, y_in, keep_prob): # input: placeholders\n x_in = tf.reshape(x_in, [-1,28,28,1])\n\n # 1st convolution-pooling layer\n W_conv1 = weight_variable([5,5,1,32])\n b_conv1 = bias_variable([32])\n\n c1 = tf.nn.conv2d(x_in, W_conv1, strides=[1,1,1,1], padding='SAME')\n conv1 = tf.nn.relu(c1 + b_conv1)\n pool1 = tf.nn.max_pool(conv1, ksize=[1,2,2,1],\n strides=[1,2,2,1], padding='SAME')\n\n # 2nd convolution-pooling layer\n W_conv2 = weight_variable([5,5,32,64])\n b_conv2 = bias_variable([64])\n\n c2 = tf.nn.conv2d(pool1, W_conv2, strides=[1,1,1,1], padding='SAME')\n conv2 = tf.nn.relu(c2 + b_conv2)\n pool2 = tf.nn.max_pool(conv2, ksize=[1,2,2,1],\n strides=[1,2,2,1], padding='SAME')\n\n print (\"c1-shape:\", c1.shape)\n print (\"conv1-shape:\", conv1.shape)\n print (\"pool1-shape:\", pool1.shape)\n print (\"c2-shape:\", c2.shape)\n print (\"conv2-shape:\", conv2.shape)\n print (\"pool2-shape:\", pool2.shape)\n \n pool2_flat = tf.reshape(pool2, [-1, 7*7*64])\n\n # 1st full-connection layer\n W_fc1 = weight_variable([7*7*64, 1024])\n b_fc1 = bias_variable([1024])\n\n fc1 = tf.nn.relu(tf.matmul(pool2_flat, W_fc1) + b_fc1)\n\n fc1_drop = tf.nn.dropout(fc1, keep_prob)\n\n # 2nd full-connection layer\n W_fc2 = weight_variable([1024, 10])\n b_fc2 = bias_variable([10])\n\n y_conv = tf.nn.softmax(tf.matmul(fc1_drop, W_fc2) + b_fc2)\n\n # cost function for testing\n correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_in,1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n \n # cost function for training\n cross_entropy = -tf.reduce_sum(y_in*tf.log(y_conv))\n train = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n\n return accuracy, train\n","sub_path":"code/L04/mnist_TF/CNN_comp_graph.py","file_name":"CNN_comp_graph.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"486023620","text":"'''\nBuild the imbalanced testing dataset without sampling for logit\n'''\n\nimport pickle\nimport numpy as np\nimport redis\nimport time\nimport sys\nfrom sqlitedict import SqliteDict\nimport pandas as pd\nimport zlib\nimport sqlite3\nimport json\nimport re\nfrom gensim.models import KeyedVectors\nimport string\nimport random\nfrom nltk import word_tokenize\nfrom collections import defaultdict\n\nprint('Loading word2vec')\nw2v_model = KeyedVectors.load_word2vec_format('data/GoogleNews-vectors-negative300.bin.gz', binary=True)\nprint('Loaded Google pretrained embeddings')\n\n\ndef pickle_object(obj, filename):\n with open(filename+'.pickle', 'wb') as handle:\n pickle.dump(obj, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\ndef compress_set(obj):\n return sqlite3.Binary(zlib.compress(pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)))\n\ndef decompress_set(obj):\n return pickle.loads(zlib.decompress(bytes(obj)))\n\ndef add_key_to_db(key, val_list):\n claims_db[key] = val_list\n\n\ndef file_reader_generator(file_object):\n while True:\n data = file_object.readline()\n if not data:\n break\n yield data\n\nprint('Loading claimToDocsDict')\nclaimToDocsDict_f = open('claimToDocsDict_test.pickle', 'rb')\nclaimToDocsDict = pickle.load(claimToDocsDict_f)\nclaimToDocsDict_f.close()\n\ntop_10_claimIDs = [137334, 111897, 89891, 181634, 219028, 108281, 204361, 54168, 105095, 18708]\nclaimToDocsDict = {itx: claimToDocsDict[itx] for itx in top_10_claimIDs}\n\nprint('Loading Claims')\ntraining_db = SqliteDict('testing_db.sqlite', decode=decompress_set)\n\nprint('Loading wiki corpus')\nconn = sqlite3.connect('wiki_corpus.db')\nc = conn.cursor()\n\ndef flatten_list(lst):\n flattened = [item for nstd in lst for item in nstd]\n return flattened\n\ntranslator = str.maketrans('', '', string.punctuation)\n\ndef tokenise_line(line):\n line = line.replace('\\n', '')\n line = line.replace('\\t', ' ')\n tokens = word_tokenize(line)\n\n # Lowercase\n tokens = list(map(lambda x: x.lower(), tokens))\n # Remove punctuation and stem\n tokens = [val.translate(translator) for val in tokens]\n\n # tokens = set(tokens)\n if '' in tokens:\n while '' in tokens:\n tokens.remove('')\n\n tokens = list(tokens)\n return tokens\n\n\n\nX_train = []\ny_train = []\n\n'''\nBuild training dataset\n'''\nprint('Building testing dataset')\nctr_breaker = 0\nstart_time = time.time()\nfor claimId, docList in claimToDocsDict.items():\n # if ctr_breaker == 50:\n # break\n\n if ctr_breaker % 500 == 0:\n print(ctr_breaker)\n\n ctr_breaker += 1\n\n supportsOrRefutes = training_db[claimId][1]\n if supportsOrRefutes != 'NOT ENOUGH INFO':\n claim = training_db[claimId][2]\n\n claimTokens = tokenise_line(claim)\n\n claimVec = []\n\n for token in claimTokens:\n if token in w2v_model:\n claimVec.append(w2v_model[token])\n\n\n if len(claimVec) > 0:\n lenClaimVec = len(claimVec)\n claimVec = sum(claimVec)/lenClaimVec\n\n positiveExamples = training_db[claimId][-1]\n positiveExamples = flatten_list(positiveExamples)\n addedLines = []\n\n\n addedPosExamples = defaultdict(list)\n\n\n # Add positive examples\n for itx in positiveExamples:\n docname = itx[-2]\n lineNumber = itx[-1]\n\n c.execute('SELECT lines FROM wiki WHERE id = ?', (docname, ))\n\n try:\n lines = c.fetchone()[0]\n except:\n print('could not get lines for doc {} '.format(docname))\n continue\n\n lines = list(filter(lambda x: x, re.split('\\d+\\\\t', lines)))\n line = lines[lineNumber]\n addedLines.append(lineNumber)\n\n lineTokens = tokenise_line(line)\n\n lineVec = []\n\n for token in lineTokens:\n if token in w2v_model:\n lineVec.append(w2v_model[token])\n\n\n if len(lineVec) > 0:\n lenLineVec = len(lineVec)\n lineVec = sum(lineVec)/lenLineVec\n\n trainingVector = np.concatenate([claimVec, lineVec])\n X_train.append(trainingVector)\n y_train.append(1)\n\n addedPosExamples[docname].append(lineNumber)\n\n\n # Add negative examples\n\n for docItx in docList:\n c.execute('SELECT lines FROM wiki WHERE id = ?', (docname, ))\n\n try:\n lines = c.fetchone()[0]\n except:\n print('could not get lines for doc {} '.format(docname))\n continue\n\n lines = list(filter(lambda x: x, re.split('\\d+\\\\t', lines)))\n\n for lineNumber in range(len(lines)):\n if lineNumber in addedPosExamples[docItx]:\n continue\n\n line = lines[lineNumber]\n\n lineTokens = tokenise_line(line)\n\n lineVec = []\n\n for token in lineTokens:\n if token in w2v_model:\n lineVec.append(w2v_model[token])\n\n\n if len(lineVec) > 0:\n lenLineVec = len(lineVec)\n lineVec = sum(lineVec)/lenLineVec\n\n trainingVector = np.concatenate([claimVec, lineVec])\n X_train.append(trainingVector)\n y_train.append(0)\n\n\nend_time = time.time()\nprint('Time to create ds ', end_time - start_time)\nprint('Pickling testing ds')\n\nX_train = np.array(X_train)\ny_train = np.array(y_train)\n\npickle_object(X_train, 'X_test_imbalanced_top_10')\npickle_object(y_train, 'y_test_imbalanced_top_10')\n\n\nconn.close()\ntraining_db.close()\n","sub_path":"q4/imbalanced_experiment/prepare_imbalanced_test.py","file_name":"prepare_imbalanced_test.py","file_ext":"py","file_size_in_byte":5858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"67965670","text":"\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom matplotlib.colors import ColorConverter\nfrom matplotlib.figure import Figure\n\nfrom django.template import loader\nfrom django.http import HttpResponse\n\nimport math\n\ndef colorMask(v1,v2):\n\tcc=ColorConverter()\n\tmask = []\n\tfor i in range(len(v1)):\n\t\tif v1[i] == v2[i]:\n\t\t\tmask.append(cc.to_rgb('black'))\n\t\telif v1[i] < v2[i]:\n\t\t\tmask.append(cc.to_rgb('red'))\n\t\telse:\n\t\t\tmask.append(cc.to_rgb('blue'))\n\treturn mask\n\ndef makeScatter(values, titles, superTitle, xLabel, yLabel):\n\t\n\tnumPlots = len(values)\n\tfig=Figure(facecolor='w', figsize=(7.5,numPlots*7.5))\n\tfor i, v in enumerate(values):\n\t\tif len(v[0]) != 0:\n\t\t\t\n\t\t\tplot = i+1\n\t\t\t\n\t\t\t# Make a subplot for the Total Time data of a benchmark set\n\t\t\tax=fig.add_subplot(numPlots,1,plot)\n\t\t\t\t\t\n\t\t\tt1 = v[0]\n\t\t\tt2 = v[1]\n\t\t\t\n\t\t\t# Color mask: if t[1] < t[2] --> red dot in graph; else blue dot\n\t\t\tt_mask = colorMask(t1,t2)\n\t\t\t\n\t\t\t# Draw a linear function from 1 until the first power of 10 greater than max_value\n\t\t\tmax_value_t = max(max(t1),max(t2))\n\t\t\tmax_value_t = math.pow(10,math.ceil(math.log10(max_value_t)))\n\t\t\tax.plot([1,max_value_t], [1,max_value_t],'k-')\n\t\t\t\n\t\t\t# Plot data\n\t\t\tax.scatter(t1, t2, s=10, color=t_mask, marker='o')\n\t\t\t\n\t\t\t# Axes mark-up\n\t\t\tax.set_xscale('log')\n\t\t\tax.set_yscale('log')\n\t\t\t\n\t\t\tif superTitle:\n\t\t\t\tfig.suptitle(superTitle)\n\t\t\tax.set_xlabel(xLabel, color='red')\n\t\t\tax.set_ylabel(yLabel, color='blue')\n\t\t\t\n\t\t\tax.set_title(titles[i], size='small')\n\t\t\tax.grid(True)\n\t\t\n\t\t# Result set is empty\n\t\telse: \n\t\t\tfig.suptitle('Empty result set.')\n\t\t\tfig.set_size_inches(7.5,0.5)\n\t\n\treturn fig\n\ndef export(canvas, title, format='png'):\n\t\"\"\"\n\tThis function exports a matplotlib graph to a given format. Expects a FigureCanvasAgg object (a canvas) to print as a figure.\n\tReturns a HttpResponse with of the specified mimetype.\n\t@param canvas The FigureCanvasAgg object.\n\t@param format The prefered export format. Choose from (png,pdf,ps,eps,svg).\n\t@param title The title of the exported document.\n\t\"\"\"\n\t# Set the mimetype of the HttpResponse\n\tmimetype = ''\n\tif (format is 'png'):\n\t\tmimetype = 'image/png'\n\telif (format is 'pdf'):\n\t\tmimetype = 'application/pdf'\n\telif (format is ('ps' or 'eps')):\n\t\tmimetype = 'application/postscript'\n\telif (format is 'svg'):\n\t\tmimetype = 'image/svg+xml'\n\tresponse = HttpResponse(content_type=mimetype)\n\t\n\t# Show the user a 'Save as..' dialogue if the graph is not PNG.\n\tif (format is not 'png'):\n\t\tresponse['Content-Disposition'] = 'attachment; filename=%s.%s' % (title, format)\n\t# Print to canvas with the right format\n\tcanvas.print_figure(filename=response, format=format, dpi=80)\n\treturn response","sub_path":"beat/tools/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"578310140","text":"'''\nCreated on Jan 1, 2002\n\n@author: douglas\n'''\nfrom PyQt4 import QtCore, QtGui\nfrom cont_dist_func_inf import BetaDistributionInf,\\\n ExponentialDistributionInf,NormalDistributionInf,UniformDistributionInf\n\nclass TwoDoubleParamsDialog(QtGui.QDialog):\n \n __MIN_VALUE=-1000\n __MAX_VALUE=1000\n \n def __init__(self,parent=None):\n super(TwoDoubleParamsDialog,self).__init__(parent)\n self.setupUi()\n self.__setInterval()\n \n def __setInterval(self):\n self.param1.setMinimum(TwoDoubleParamsDialog.__MIN_VALUE)\n self.param2.setMinimum(TwoDoubleParamsDialog.__MIN_VALUE)\n self.param1.setMaximum(TwoDoubleParamsDialog.__MAX_VALUE)\n self.param2.setMaximum(TwoDoubleParamsDialog.__MAX_VALUE)\n \n \n \n \n def setupUi(self):\n self.layout=QtGui.QGridLayout()\n self.param1=QtGui.QDoubleSpinBox()\n self.param2=QtGui.QDoubleSpinBox()\n self.label1=QtGui.QLabel(\"Label 1:\")\n self.label2=QtGui.QLabel(\"Label 2:\")\n \n self.layout.addWidget(self.label1,0,0,1,1)\n self.layout.addWidget(self.param1,0,1,1,1)\n self.layout.addWidget(self.label2,1,0,1,1)\n self.layout.addWidget(self.param2,1,1,1,1)\n \n self.buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok|QtGui.QDialogButtonBox.Cancel)\n self.layout.addWidget(self.buttonBox,2,0,1,2)\n \n self.setLayout(self.layout)\n self.connectSignals()\n \n def connectSignals(self):\n from PyQt4.QtCore import SIGNAL,SLOT\n self.connect(self.buttonBox, SIGNAL(\"accepted()\"),self.custom_validation)\n self.connect(self.buttonBox, SIGNAL(\"rejected()\"),self, SLOT(\"reject()\"))\n \n def custom_validation(self):\n self.accept()\n \n def setLabelsName(self,label1Text,label2Text):\n self.label1.setText(label1Text)\n self.label2.setText(label2Text)\n \n def setParamsValues(self,value1,value2):\n self.param1.setValue(value1)\n self.param2.setValue(value2)\n \n @staticmethod \n def GetDistributionFunction(ContiDistFuncDialogCls,parent=None,dist_func=None):\n \"\"\"\n Este metodo muestra el dialogo y recoge a travez de el la informacion necesaria para \n crear una funcion de distribucion discreta sobre un espacio de probabilidad finito\n \"\"\"\n dialog=ContiDistFuncDialogCls(parent,dist_func)\n if dialog.exec_():\n #construir una funcion de distribucion a partir de los datos que tenemos \n function_inf=dialog.get_dist_func() \n return True,function_inf\n return False,None \n \nclass UniformDistributionDialog(TwoDoubleParamsDialog):\n \n FunctionLabelName=\"Uniform Distribution\"\n FunctionName=\"Uniform\"\n \n def __init__(self,parent=None,dist_func=None):\n super(UniformDistributionDialog,self).__init__(parent)\n self.setLabelsName(\"a:\", \"b:\")\n if dist_func is None:\n self.dist_func=None\n else:\n self.dist_func=dist_func\n self.init_from_dist_func()\n \n def init_from_dist_func(self):\n self.setParamsValues(self.dist_func.a, self.dist_func.b)\n \n def get_dist_func(self):\n return UniformDistributionInf(self.param1.value(),self.param2.value())\n \n @staticmethod \n def GetDistributionFunction(parent=None,dist_func=None):\n return TwoDoubleParamsDialog.GetDistributionFunction(UniformDistributionDialog, parent, dist_func)\n \n\n \nclass BetaDistributionDialog(TwoDoubleParamsDialog):\n \n FunctionLabelName=\"Distribucion Beta\"\n FunctionName=\"Beta\"\n \n def __init__(self,parent=None,dist_func=None):\n super(BetaDistributionDialog,self).__init__(parent)\n self.param1.setMinimum(0)\n self.param2.setMinimum(0)\n self.setLabelsName(\"a:\", \"b:\")\n if dist_func is None:\n self.dist_func=None\n else:\n self.dist_func=dist_func\n self.init_from_dist_func()\n \n def init_from_dist_func(self):\n self.setParamsValues(self.dist_func.a, self.dist_func.b)\n \n def get_dist_func(self):\n return BetaDistributionInf(self.param1.value(),self.param2.value())\n \n @staticmethod \n def GetDistributionFunction(parent=None,dist_func=None):\n return TwoDoubleParamsDialog.GetDistributionFunction(BetaDistributionDialog, parent, dist_func)\n \n def custom_validation(self):\n if self.param1.value()>0 and self.param2.value()>0: self.accept()\n else:\n QtGui.QMessageBox.question(self,\n \"Error!.\",\n \"Los parametros a y b deben ser ambos positivos.\",\n QtGui.QMessageBox.Ok)\n \nclass NormalDistributionDialog(TwoDoubleParamsDialog):\n FunctionName=\"Normal\"\n FunctionLabelName=\"Distribucion Normal\"\n \n def __init__(self,parent=None,dist_func=None):\n super(NormalDistributionDialog,self).__init__(parent)\n self.setLabelsName(\"miu:\", \"sigma:\")\n if dist_func is None:\n self.dist_func=None\n else:\n self.dist_func=dist_func\n self.init_from_dist_func()\n \n def init_from_dist_func(self):\n self.setParamsValues(self.dist_func.miu, self.dist_func.sigma)\n \n def get_dist_func(self):\n return NormalDistributionInf(self.param1.value(),self.param2.value())\n \n @staticmethod \n def GetDistributionFunction(parent=None,dist_func=None):\n return TwoDoubleParamsDialog.GetDistributionFunction(NormalDistributionDialog, parent, dist_func)\n \n \n \n \n \n \n \n","sub_path":"src/dist_func_inf/cont_dist_func_dialogs.py","file_name":"cont_dist_func_dialogs.py","file_ext":"py","file_size_in_byte":5724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"115563523","text":"from time import strftime, localtime, time\nfrom datetime import timedelta\n\nimport keras.backend as K\nfrom keras.models import Model, load_model\nfrom keras.layers import Input, Embedding, Dropout, Bidirectional, GRU, LSTM, Lambda, concatenate\nfrom keras import optimizers\n#from keras import regularizers\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nimport numpy as np\nfrom scipy.stats import pearsonr, spearmanr\nfrom sklearn.metrics import mean_squared_error\n\nfrom data_helper import Data\nfrom embedding_helper import Get_Embedding\nfrom log_helper import Logger\n\n#TIME_STAMP = strftime(\"%m%d%H%M%S\", localtime()) # to avoid duplicated file names deleting files\nTRAINING_DATA_PATH = '../STS-B/train2.tsv'\nTEST_DATA_PATH = '../STS-B/test2.tsv'\nEMBEDDING_PATH = '../model/GoogleNews-vectors-negative300.bin'\nlg = None\n\ndef build_model(hidden_size, drop, sequence_length, vocab2id, update_vocab, gru, bidir, ada, trainable):\n\n out_size = hidden_size * 1 # 2 if bi_sequential is 'concat'enated; 1 if it's 'sum'med, 'ave'raged...\n\n def exp_neg_manhattan_dist(x):\n return 5*K.exp(-K.sum(K.abs(x[:,:out_size] - x[:,out_size:]), axis=1, keepdims=True))\n\n print('Building Model')\n\n input_1 = Input(shape=(sequence_length,), dtype='int32')\n input_2 = Input(shape=(sequence_length,), dtype='int32')\n # input_ -> [batch_size, sequence_length]\n \n embedding = Get_Embedding(EMBEDDING_PATH, vocab2id, update_vocab)\n embedding_dim = embedding.matrix.shape[1]\n emb_layer = Embedding(input_dim=len(vocab2id),\n output_dim=embedding_dim,\n input_length=sequence_length, \n trainable=trainable, # TODO\n weights=[embedding.matrix])\n embedding_1 = emb_layer(input_1)\n embedding_2 = emb_layer(input_2)\n # embedding_ -> [batch_size, sequence_length, embedding_dim]\n\n ##################################################\n # Single-layer version: Due to little data #\n # May be modified for multi-layer with iteration #\n ##################################################\n #penalty = 100\n if gru:\n in_rnn = GRU( # TODO: LSTM or GRU?\n units=hidden_size, \n #kernel_regularizer=regularizers.l2(penalty),\n #bias_regularizer=regularizers.l2(penalty),\n #recurrent_regularizer=regularizers.l2(penalty),\n #activity_regularizer=regularizers.l1(penalty),\n dropout=drop, \n recurrent_dropout=drop,\n return_sequences=False, # return_sequence=False => Returns the last output only (For the last layer only in this work)\n unroll=True)\n else:\n in_rnn = LSTM( # TODO: LSTM or GRU?\n units=hidden_size, \n dropout=drop, \n recurrent_dropout=drop,\n return_sequences=False, # return_sequence=False => Returns the last output only (For the last layer only in this work)\n unroll=True)\n if bidir:\n rnn = Bidirectional(in_rnn, merge_mode='sum') # merge_mode: Mode by which outputs of the forward and backward RNNs will be combined. \n # TODO: One of {'sum', 'mul', 'concat', 'ave', None}. \n # If None, the outputs will not be combined, they will be returned as a list.\n else:\n rnn = in_rnn\n\n rnn_out_1 = rnn(embedding_1)\n rnn_out_2 = rnn(embedding_2)\n\n concat_out = concatenate([rnn_out_1, rnn_out_2], axis=-1)\n\n lambda_out = Lambda(exp_neg_manhattan_dist, output_shape=(1,))(concat_out)\n\n model = Model(inputs=[input_1, input_2], outputs=[lambda_out])\n\n # Optimizers: Adam outperforms SGD in \"deep\" neural networks\n if ada:\n optimizer = optimizers.Adam() #lr=1e-3?\n else:\n optimizer = optimizers.SGD(lr=1e-2)\n #optimizer = optimizers.SGD(lr=2e-4, clipnorm=1.)\n #optimizer = optimizers.SGD(lr=2e-4, nesterov=True, clipnorm=100)\n #optimizer = optimizers.Adadelta(clipnorm=1.) #1.25\n\n model.compile(optimizer=optimizer, loss='mean_squared_error')\n print(model.summary())\n return model\n\ndef train_model(train_ratio=0.9,\n update_vocab=True,\n batch_size = 32,\n epochs = 50,\n sequence_length = 61, # 61\n hidden_size = 100, # Rule of thumb~=100 (Concat -> 50?)\n drop = 0.5, # 0.2, 0.4 or 0.5\n gru=True,\n bidir=True,\n trainable=False,\n ada=True,\n data=None):\n \n print('Loading data.')\n if data == None:\n data = Data(data_file=TRAINING_DATA_PATH, \n update_vocab=update_vocab,\n sequence_length=sequence_length,\n mode='train', train_ratio=train_ratio)\n sequence_length = data.sequence_length\n x_train = data.x_train\n y_train = data.y_train\n x_val = data.x_val\n y_val = data.y_val\n vocabulary_size = data.vocab_size\n\n print('\\n')\n lg.pr(f'''# training samples : {len(x_train[0])}\\n'''+\\\n f\"\"\"# validation samples : {len(x_val[0])}\\n\"\"\"+\\\n f\"\"\"Maximum sequence length : {sequence_length}\\n\"\"\"+\\\n f\"\"\"Vocabulary Size : {vocabulary_size}\\n\"\"\")\n\n model = build_model(\n hidden_size, drop, sequence_length, data.vocab2id, update_vocab, gru, bidir, ada, trainable)\n \n # Save the best model\n model_fname = f'../model/{lg.ts}-{epochs}ep-{hidden_size}hs-{drop*10:.0f}dp'\n callbacks = [#EarlyStopping(monitor='val_loss', min_delta=0.001, patience=2, baseline=2.1),\n ModelCheckpoint(filepath=model_fname, monitor='val_loss', save_best_only=True)]\n\n training_start_time = time()\n history = model.fit(x_train, y_train, validation_data=(x_val, y_val),\n epochs=epochs, batch_size=batch_size, verbose=1, callbacks=callbacks)\n #verbose: Integer. 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch.\n lg.pr(f\"Training time finished.\\n{epochs} epochs in {timedelta(seconds=time()-training_start_time)}\")\n \n lg.plot_loss(history)\n lg.pr(f\"\"\"Model saved. Name: \\'{model_fname}\\'\\n\"\"\"+\\\n f\"\"\"train_ratio :{train_ratio}\\n\"\"\"+\\\n f\"\"\"update_vocab :{update_vocab}\\n\"\"\"+\\\n f\"\"\"batch_size :{batch_size}\\n\"\"\"+\\\n f\"\"\"epochs :{epochs}\\n\"\"\"+\\\n f\"\"\"sequence_length:{sequence_length}\\n\"\"\"+\\\n f\"\"\"hidden_size :{hidden_size}\\n\"\"\"+\\\n f\"\"\"drop :{drop}\\n\"\"\")\n with open(f'../logs/{lg.ts}.txt','a') as model_metadata:\n model.summary(print_fn=lambda x: model_metadata.write(x + '\\n'))\n \n return model\n\ndef test_model(model=None, model_fname='', data=None):\n if model == None:\n model = load_model(model_fname)\n \n if data == None:\n data = Data(data_file=TESTING_DATA_PATH,\n update_vocab=False,\n sequence_length=61,\n mode='test', train_ratio=0.)\n x_test = data.x_val\n y_test = data.y_val\n y_pred = np.array(model.predict(x_test))[:,0]\n\n pearson_r, pearson_p = pearsonr(y_test, y_pred)\n spearman_rho, spearman_p = spearmanr(y_test, y_pred)\n score = pearson_r + spearman_rho\n mse = mean_squared_error(y_test, y_pred)\n\n print(\"\\n\")\n lg.pr(f\"\"\"# testing samples : {len(y_test)}\\n\"\"\"+\\\n f\"\"\"Pearson correlation coefficient : {pearson_r}\\n\"\"\"+\\\n f\"\"\"Spearman rank-order correlation coefficient : {spearman_rho}\\n\"\"\"+\\\n f\"\"\"Total score : {score}\\n\"\"\"+\\\n f\"\"\"Mean squred error : {mse}\\n\"\"\")\n \n #print(\"Some results (real, predicted): \", [t for t in zip(y_test[:20], y_pred[:20])])\n\n\nif __name__ == \"__main__\":\n\n train_data = Data(data_file=TRAINING_DATA_PATH, \n update_vocab=False,\n sequence_length=61,\n mode='train', train_ratio=1-1e-1)\n test_data = Data(data_file=TEST_DATA_PATH, \n update_vocab=False,\n sequence_length=61,\n mode='test', train_ratio=1-1e-1)\n try:\n ts=strftime(\"%m%d%H%M%S\", localtime())+\"trainable\"\n lg = Logger(ts)\n model = train_model( train_ratio = 1-1e-1, update_vocab=False, hidden_size=30, epochs=50, data=train_data, trainable=True)\n test_model(model=model, data=test_data)\n lg.compare_loss('0508002641',ts)\n except Exception as e:\n lg.pr(str(e))\n try:\n ts=strftime(\"%m%d%H%M%S\", localtime())+\"lstm\"\n lg = Logger(ts) \n model = train_model( train_ratio = 1-1e-1, update_vocab=False, hidden_size=30, epochs=50, data=train_data, gru=False)\n test_model(model=model, data=test_data)\n lg.compare_loss('0508002641',ts)\n except Exception as e:\n lg.pr(str(e))\n try:\n ts=strftime(\"%m%d%H%M%S\", localtime())+\"single lstm\"\n lg = Logger(ts) \n model = train_model( train_ratio = 1-1e-1, update_vocab=False, hidden_size=30, epochs=50, data=train_data, gru=False, bidir=False)\n test_model(model=model, data=test_data)\n lg.compare_loss('0508002641',ts)\n except Exception as e:\n lg.pr(str(e))\n try:\n ts=strftime(\"%m%d%H%M%S\", localtime())+\"sgd\"\n lg = Logger(ts) \n model = train_model( train_ratio = 1-1e-1, update_vocab=False, hidden_size=30, epochs=50, data=train_data, ada=False)\n test_model(model=model, data=test_data)\n lg.compare_loss('0508002641',ts)\n except Exception as e:\n lg.pr(str(e))\n try:\n ts=strftime(\"%m%d%H%M%S\", localtime())+\"batchsize8 \"\n lg = Logger(ts) \n model = train_model( train_ratio = 1-1e-1, update_vocab=False, hidden_size=30, data=train_data, epochs=50, batch_size=8)\n test_model(model=model, data=test_data)\n lg.compare_loss('0508002641',ts)\n except Exception as e:\n lg.pr(str(e))\n try:\n ts=strftime(\"%m%d%H%M%S\", localtime())+\"200epochs \"\n lg = Logger(ts) \n model = train_model( train_ratio = 1-1e-1, update_vocab=False, hidden_size=30, data=train_data, epochs=200)\n test_model(model=model, data=test_data)\n lg.compare_loss('0508002641',ts)\n except Exception as e:\n lg.pr(str(e))","sub_path":"manhattan_lstm.py","file_name":"manhattan_lstm.py","file_ext":"py","file_size_in_byte":10462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"631262259","text":"from hangman import get_secret_word, hide_word , game ,continue_or_exit ,get_status\n \ndef test_secret_word_no_punctuation():\n with open(\"/tmp/words.txt\",\"w\") as f:\n for i in [\"word'one\", \"word_two\", \"wordthree\"]:\n f.write(i+\"\\n\")\n selected_word = get_secret_word('/tmp/words.txt')\n assert selected_word == \"wordthree\"\n \ndef test_secret_word_atleast_five():\n with open(\"/tmp/words.txt\",\"w\") as f:\n for i in [\"wo\", \"wor\", \"word\", \"bigword\"]:\n f.write(i+\"\\n\")\n selected_word = get_secret_word('/tmp/words.txt')\n assert selected_word == \"bigword\"\n \ndef test_secret_word_lowercase():\n with open(\"/tmp/words.txt\",\"w\") as f:\n for i in [\"Wording\", \"wOrding\", \"WORDING\", \"wording\"]:\n f.write(i+\"\\n\")\n selected_word = get_secret_word('/tmp/words.txt')\n assert selected_word == \"wording\"\n \ndef test_secret_word_no_repeat():\n with open(\"/tmp/words.txt\",\"w\") as f:\n for i in [\"disaster\",\"recall\",\"advise\",\"national\",\"infrastructure\",\"shots\",\"fired\", \"federation\", \"duress\"]:\n f.write(i+\"\\n\")\n l = []\n for i in range(3):\n l.append(get_secret_word('/tmp/words.txt'))\n assert len(set(l)) == 3\n\n\ndef test_hide_word_empty():\n s=\"bigger\"\n guess=[]\n assert hide_word(s,guess) == \"______\"\n\ndef test_hide_word_correct_letter():\n s=\"bigger\"\n guess=['g']\n assert hide_word(s,guess) == \"__gg__\"\n\ndef test_full_corect_word():\n s=\"bigger\"\n guess=['b','g','i','r','e']\n assert hide_word(s,guess) == \"bigger\"\n \n\ndef test_wrong_word_comes():\n s=\"bigger\"\n guess=['z']\n assert hide_word(s,guess) == \"______\"\n \ndef test_when_guessing_word():\n s=\"bigger\"\n correct_word=[]\n worng_word=[]\n guess_word=[\"i\",'g']\n\n assert game(s,correct_word,worng_word,guess_word)== (\"_igg__\",['i','g'],[])\n\ndef test_when_guessing_correct_word():\n s=\"bigger\"\n correct_word=['g']\n worng_word=[]\n guess_word=['i','g']\n\n assert game(s,correct_word,worng_word,guess_word)== (\"_igg__\",['g','i'],[])\n\ndef test_when_wrong_word():\n s=\"bigger\"\n correct_word=[]\n worng_word=['k']\n guess_word=[\"i\",'g']\n\n assert game(s,correct_word,worng_word,guess_word)== (\"_igg__\",['i','g'],['k'])\n\ndef test_when_wrong_word_repect():\n s=\"bigger\"\n correct_word=[]\n worng_word=['k']\n guess_word=[\"i\",'g','k']\n\n assert game(s,correct_word,worng_word,guess_word)== (\"_igg__\",['i','g'],['k'])\n\ndef test_when_guessing_wrong_word():\n s=\"zigger\"\n correct_word=[]\n worng_word=['k']\n guess_word=[\"i\",'g','l']\n\n assert game(s,correct_word,worng_word,guess_word)== (\"_igg__\",['i','g'],['k','l'])\n\ndef test_continue_or_exist_wrong_guess():\n s=\"bigger\"\n correct_word=['g']\n worng_word=['k']\n guess_word=['z']\n assert continue_or_exit(s,correct_word,worng_word,guess_word)==(\"__gg__\",['g'],['k','z'],1)\n\ndef test_continue_or_exist_correct_guess():\n s=\"biggel\"\n correct_word=['g']\n worng_word=['k']\n guess_word=['b']\n assert continue_or_exit(s,correct_word,worng_word,guess_word)==(\"b_gg__\",['g','b'],['k'],1)\n\n \ndef test_continue_or_exist_wrong_gues_get_exit():\n s=\"aigger\"\n correct_word=['g']\n worng_word=['k']\n guess_word=['z','p','l','q','j','y']\n assert continue_or_exit(s,correct_word,worng_word,guess_word)==(\"__gg__\",['g'],['k','z','p','l','q','j','y'],2)\n\n\ndef test_continue_or_exist_correct_full_guess():\n s=\"battlement\"\n correct_word=[]\n worng_word=[]\n guess_word=['b','a','t','l','e','m','n']\n assert continue_or_exit(s,correct_word,worng_word,guess_word)==(\"battlement\",['b','a','t','l','e','m','n'],[],3)\n \ndef test_get_status():\n s=\"bigger\"\n correct_word=['g']\n worng_word=[]\n guess_word=['i','k','z']\n assert get_status(s,correct_word,worng_word,guess_word)==\"\"\"\nguess = gikz\nturn left =5 \n\"\"\" \n","sub_path":"test_hangman.py","file_name":"test_hangman.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"277508029","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\n\n#Q1\nns = np.linspace(0,49,50)\n\n#Q2\nC = [1, 1]\nfor n in range(48):\n\tC.append(C[n]+C[n+1])\nC = np.array(C)\n\n#Q3\nfigure1 = plt.figure()\nplt.plot(ns, C)\nplt.title('l’évolution du nombre de couples de lapins en fonction du temps')\nplt.xlabel('Temps [mois]')\nplt.ylabel('Couples de lapins')\nfigure1.savefig('exo1_fig1.pdf')\n\n#Q4\nrn = np.array([C[n+1]/C[n] for n in range(49)])\n\n#Q5\nfigure2 = plt.figure()\nplt.plot(np.linspace(1, 49, 49), rn)\nplt.title('rapport rn en fonction du mois n')\nplt.xlabel('n [mois]')\nplt.ylabel('rn')\nfigure2.savefig('exo1_fig2.pdf')\n\n#Q6\nfigure3 = plt.figure()\nplt.yscale('log')\nplt.plot(ns, C)\nplt.title('Suite de fibonacci des 50 premiers termes')\nplt.xlabel('n')\nplt.ylabel('Cn')\nfigure3.savefig('exo1_fig3.pdf')\n'''\nCn tend vers une droite affine en echelle log \nOr \nA*Phi^n\nln(A*Phi^n) = ln(A) + n*ln(Phi) qui est une droite affine en echelle log\nDonc\nCn tend bien vers une suite geometrique de la forme A*Phi^n \n'''\n\n#Q7\nD = np.log(C)\n\n#Q8\nf = lambda n, P, Q : P+n*Q\npopt = curve_fit(f, ns, D)[0]\nP = popt[0]\nQ = popt[1]\nprint('Nous trouvons : P = {} et Q = {}\\nQ - ln(Phi) = {}'.format(P, Q, Q-np.log((1+(5)**(1/2))/2))) #On trouve que la difference est proche de zero.\n\n#Q9\nfigure4 = plt.figure()\nplt.yscale('log')\nplt.plot(ns, D, 'k-', label = \"Dn\")\nplt.plot(ns, f(ns, P, Q), 'r-', label = \"f(n)\")\nplt.title('Dn = ln(Cn)')\nplt.legend()\nplt.xlabel('n')\nplt.ylabel('Dn')\nfigure4.savefig('exo1_fig4.pdf')\n","sub_path":"exam 2018/exo1.py","file_name":"exo1.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"504022697","text":"import time\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n# Though the following import is not directly being used, it is required\n# for 3D projection to work\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.cluster import MeanShift\n\n\ndef wait_for_action_completion(timeout, target_pose, pos_err, or_err,\n pose_stream):\n \"\"\"\n :param timeout: allowed time to reach target pose\n :param target_pose: the pose to reach GeoPoseStamped\n :param pos_err: acceptable tolerance to assume pose has been reached\n :param or_err: acceptable tolerance to assume pose has been reached\n :param pose_stream: the constantly updated pose value: GeoPoseStamped\n :return:\n \"\"\"\n attributes = ['altitude', 'longitude', 'latitude', 'x', 'y', 'z', 'w']\n time_elapsed = time.time()\n t_pos, t_or = target_pose.pose.position, target_pose.pose.orientation\n t_pos_ranges = map(lambda a: [t_pos.__getattribute__(a) - pos_err, t_pos.__getattribute__(a) + pos_err],\n attributes[:3])\n t_or_ranges = map(lambda a: [t_or.__getattribute__(a) - or_err, t_or.__getattribute__(a) + or_err],\n attributes[3:])\n t_ranges = t_pos_ranges + t_or_ranges\n prev_c_ranges = None\n while timeout > 0:\n timeout -= time.time() - time_elapsed\n time_elapsed = time.time()\n # both positional and orientational values must be within target+-error to be accepted\n c_pos = pose_stream.pose.position\n c_or = pose_stream.pose.orientation\n c_pos_ranges = map(lambda a: c_pos.__getattribute__(a), attributes[:3])\n c_or_ranges = map(lambda a: c_or.__getattribute__(a), attributes[3:])\n c_ranges = c_pos_ranges + c_or_ranges\n if prev_c_ranges == c_ranges:\n print(\"awaiting update\")\n time.sleep(0.2)\n continue\n prev_c_ranges = c_ranges\n if np.all(map((lambda a, b: b[0] < a < b[1]), c_ranges, t_ranges)):\n return (True, \"POSE_REACHED\")\n return (False, \"OUT_OF_TIME\")\n\n\ndef wait_for_stop(timeout, vel_stream, ang_thresh, lin_thresh):\n \"\"\"\n\n :param timeout:\n :param vel_stream: Twist message\n :return:\n \"\"\"\n print(\"WAITING FOR STOP: \")\n time_elapsed = time.time()\n attributes = ['x', 'y', 'z']\n while timeout > 0:\n timeout -= time.time() - time_elapsed\n time_elapsed = time.time()\n l_xyz = map(lambda a: abs(vel_stream.twist.linear.__getattribute__(a)), attributes)\n a_xyz = map(lambda a: abs(vel_stream.twist.angular.__getattribute__(a)), attributes)\n print(l_xyz, a_xyz)\n if np.all(map(lambda a, l: a < ang_thresh and l < lin_thresh, a_xyz, l_xyz)):\n print('ARRIVED')\n break\n else:\n time.sleep(0.1)\n print(\"TIMEOUT REACHED\")\n\n\nfrom scipy.stats import gaussian_kde\n\n\ndef find_wt_pole(np_array):\n \"\"\"\n Finds all points that associate with pole\n :param np_array:\n :return:\n \"\"\"\n # if points are collapsed on a 2d plane (i.e. ignore z)\n # then the area where there are the most points will be the pole as it is a vertical wide structure.\n # collapse the points onto 2d and plot them\n arr_2d = np_array[:, :2]\n x, y = arr_2d[:, 0], np_array[:, 1]\n xy = np.vstack([x, y])\n z = gaussian_kde(xy)(xy)\n pole_coordinates = np.where(z == np.amax(z))\n pole = arr_2d[[pole_coordinates]][0]\n pole_mean = np.mean(pole, axis=0)\n print(pole_mean)\n print(z)\n print(\"POLE (MAX GAUSS)\", pole)\n\n fig, ax = plt.subplots()\n\n ax.scatter(x, y, c=z, s=100, edgecolor='')\n\n x_vals = np_array[:, 0]\n y_vals = np_array[:, 1]\n max_x, min_x = np.max(x_vals), np.min(x_vals)\n max_y, min_y = np.max(y_vals), np.min(y_vals)\n range_x = max_x - min_x\n range_y = max_y - min_y\n chosen = y_vals\n if range_x > range_y:\n chosen = x_vals\n # find index of both extremes\n result_max = np.where(chosen == np.amax(chosen))\n result_min = np.where(chosen == np.amin(chosen))\n min_vals = arr_2d[[result_min]][0]\n max_vals = arr_2d[[result_max]][0]\n print(min_vals, max_vals)\n print(\"concatenating: \", [np.mean(min_vals, axis=0)])\n to_plot = np.concatenate(([np.mean(min_vals, axis=0)], [np.mean(max_vals, axis=0)]), axis=0)\n print(to_plot)\n plt.plot(to_plot[:, 0], to_plot[:, 1], 'r')\n normal = (to_plot[1] - to_plot[0]) / (np.linalg.norm(to_plot[1] - to_plot[0]))\n print(\"normal: \", normal)\n p_v = pole_mean - to_plot[0]\n print(\"from left to pole\", p_v)\n t = np.dot(p_v, normal)\n print(\"dot product with normal: \", t)\n p_online = to_plot[0] + t * normal\n x = [pole_mean[0], p_online[0]]\n y = [pole_mean[1], p_online[1]]\n\n plt.plot(x, y, 'r')\n plt.show()\n\n\ndef get_k_means_clusters(pc, k):\n \"\"\"\n :param k: number of clusters\n :param pc: pointcloud\n :return: each cluster.\n \"\"\"\n find_wt_pole(pc)\n print(pc[0])\n print(pc.shape)\n fig = plt.figure(figsize=(20, 20))\n\n ax = Axes3D(fig)\n\n ax.set_xlim3d(-100, 100)\n ax.set_ylim3d(-50, 150)\n ax.set_zlim3d(-50, 150)\n # est2 = SpectralClustering(n_clusters=2)\n # est3=DBSCAN()\n est1 = MeanShift()\n est = est1\n X = pc\n est.fit(X[:, :2])\n labels = est.labels_\n # 0,1,2\n # 0,2,1\n # 1,0,2\n x = 0\n y = 1\n z = 2\n print(X)\n for p in X:\n print(p)\n ax.scatter(X[:, x], X[:, y], X[:, z],\n c=labels.astype(np.float), edgecolor='k')\n\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('z')\n ax.set_title('k_means where k = ' + str(k))\n fig.show()\n time.sleep(500)\n\n pass\n","sub_path":"src/uav_executive/action_servers/find_turbine/states/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"220412140","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nimport tornado.gen\nimport tornado.ioloop\nimport tornado.httpclient\n\n\nio_loop = tornado.ioloop.IOLoop.instance()\nclient = tornado.httpclient.AsyncHTTPClient(max_clients=2) # 24.3s vs 42s\n\nyandex_com_urls = list(map(\"http://yandex.com/yandsearch?text=%s\".__mod__, range(100)))\nyandex_ru_urls = list(map(\"http://yandex.by/yandsearch?text=%s\".__mod__, range(100)))\n\ncounter = 2\n\n\n@tornado.gen.coroutine\ndef get_urls(urls):\n global counter\n for url in urls:\n print(\"Fetch:\", url)\n yield client.fetch(url)\n print(\"Got:\", url)\n counter -= 1\n if counter == 0:\n io_loop.stop()\n\nio_loop.add_callback(get_urls, yandex_com_urls)\nio_loop.add_callback(get_urls, yandex_ru_urls)\n\ntry:\n io_loop.start()\nexcept KeyboardInterrupt:\n pass\n","sub_path":"test-ioloop.py","file_name":"test-ioloop.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"509904837","text":"import os\nimport json\nfrom torchvision import transforms\nfrom torch.utils.data import Dataset\nfrom other_utils.tensor_utils import *\nfrom other_utils.class_utils import Toperation\nfrom datasets.aic_info import SINGLE_ATTR\n\n\nRES = [1920, 1080]\n\nSEED = 1821\nnp.random.seed(SEED)\ntorch.cuda.manual_seed_all(SEED)\n\n\nclass AICDataset(Dataset):\n\n def __init__(self, root_dir, comp_path, type_data, train_data=True, dst_size=(320, 128),\n tran=None, random_flip=0., attr_rsd=False):\n\n self.train_data = train_data\n\n self.random_flip = random_flip\n self.attributes_eng = SINGLE_ATTR\n self.attributes_rsd = attr_rsd\n\n self.root_dir = root_dir\n self.dst_size = dst_size\n\n # json and path info\n self.json_folder = os.path.join(self.root_dir)\n self.image_path = os.path.join(self.root_dir, 'crops')\n\n self.comp_path = comp_path\n self.tran = tran\n self.all_file = {}\n self.type_data = type_data\n\n with open(os.path.join(self.json_folder, 'annotations.json')) as fn:\n self.dictionary_images = json.load(fn)\n\n with open('./config/aic/aic_split.json') as fn:\n tmp = json.load(fn)\n\n self.train_idx = np.array(tmp[0:100000])\n self.test_idx = np.array(tmp[100000:])\n\n if self.random_flip > 0:\n self.rnd_flip = transforms.RandomHorizontalFlip(self.random_flip)\n\n if self.tran:\n self.t = transforms.Compose([\n transforms.ToPILImage(),\n transforms.Resize(self.dst_size),\n transforms.ToTensor()\n ])\n\n def __len__(self):\n if self.train_data:\n return len(self.train_idx)\n else:\n return len(self.test_idx)\n\n def __getitem__(self, idx):\n\n if self.train_data:\n idx = self.train_idx[idx]\n else:\n idx = self.test_idx[idx]\n\n pinfo = self.dictionary_images[idx]\n\n oc_image_path = os.path.join(self.image_path, '{}'.format(pinfo['id']) + '_occ.jpg')\n gt_image_path = os.path.join(self.image_path, '{}'.format(pinfo['id']) + '.jpg')\n if self.comp_path is not None:\n de_image_path = os.path.join(self.comp_path, '{}.jpeg'.format(pinfo['info']))\n else:\n de_image_path = ''\n\n gt = self.read_image(gt_image_path)\n occ = self.read_image(oc_image_path)\n\n attributes = pinfo['attributes']\n name_file = '{}'.format(pinfo['id']) + '.jpg'\n\n if self.type_data == Toperation.occlusion:\n return self.deocclusion(gt, occ, attributes, name_file)\n elif self.type_data == Toperation.classification:\n return self.classification(gt, attributes, name_file)\n elif self.type_data == Toperation.metrics:\n deocc = self.read_image(de_image_path)\n return self.metrics(gt, occ, deocc, attributes, name_file)\n elif self.type_data == Toperation.demo:\n return self.demo(gt, occ, attributes, pinfo['pose'], name_file)\n else:\n print('Invalid data type')\n raise Exception\n\n def classification(self, gt, attributes, name):\n\n csize = [self.dst_size[0] // 16, self.dst_size[1] // 16]\n labels_tensor, _ = self.get_labels_tensors(attributes, concat_size=csize)\n\n if self.random_flip > 0 and np.random.rand() > 0.5:\n gt = cv2.flip(gt, 1)\n\n if self.tran:\n gt = self.t(gt)\n gt = torch.add(gt, -0.5)\n gt = torch.mul(gt, 2)\n\n return gt, labels_tensor, name\n\n def metrics(self, gt, occ, deocc, attributes, name):\n\n csize = [self.dst_size[0] // 16, self.dst_size[1] // 16]\n labels_tensor, _ = self.get_labels_tensors(attributes, concat_size=csize)\n\n if self.tran:\n gt = self.t(gt)\n occ = self.t(occ)\n deocc = self.t(deocc)\n occ = torch.add(occ, -0.5)\n occ = torch.mul(occ, 2)\n gt = torch.add(gt, -0.5)\n gt = torch.mul(gt, 2)\n deocc = torch.add(deocc, -0.5)\n deocc = torch.mul(deocc, 2)\n else:\n deocc = cv2.resize(deocc, (self.dst_size[1], self.dst_size[0]))\n occ = cv2.resize(occ, (self.dst_size[1], self.dst_size[0]))\n gt = cv2.resize(gt, (self.dst_size[1], self.dst_size[0]))\n\n return gt, occ, deocc, labels_tensor, name\n\n def deocclusion(self, gt, occ, attributes, name):\n\n csize = [self.dst_size[0] // 16, self.dst_size[1] // 16]\n labels_tensor, labels_tensor_rsd = self.get_labels_tensors(attributes, csize)\n\n if self.random_flip > 0 and np.random.rand() > 0.5:\n occ = cv2.flip(occ, 1)\n gt = cv2.flip(gt, 1)\n\n if self.tran:\n gt = self.t(gt)\n gt = torch.add(gt, -0.5)\n gt = torch.mul(gt, 2)\n occ = self.t(occ)\n occ = torch.add(occ, -0.5)\n occ = torch.mul(occ, 2)\n labels_tensor_rsd = torch.add(labels_tensor_rsd, -0.5)\n labels_tensor_rsd = torch.mul(labels_tensor_rsd, 2)\n\n return occ, gt, labels_tensor, labels_tensor_rsd, name\n\n def demo(self, gt, occ, attributes, pose, name):\n\n for elem in pose:\n if elem[3] == 0 and elem[4] == 0:\n cv2.circle(gt, (elem[1], elem[2]), 3, (0, 0, 255), thickness=-1)\n cv2.circle(occ, (elem[1], elem[2]), 3, (0, 0, 255), thickness=-1)\n else:\n cv2.circle(gt, (elem[1], elem[2]), 3, (0, 255, 0), thickness=-1)\n cv2.circle(occ, (elem[1], elem[2]), 3, (0, 255, 0), thickness=-1)\n\n csize = [self.dst_size[0] // 16, self.dst_size[1] // 16]\n labels_tensor, labels_tensor_rsd = self.get_labels_tensors(attributes, csize)\n\n if self.random_flip > 0 and np.random.rand() > 0.5:\n occ = cv2.flip(occ, 1)\n gt = cv2.flip(gt, 1)\n\n if self.tran:\n gt = self.t(gt)\n gt = torch.add(gt, -0.5)\n gt = torch.mul(gt, 2)\n occ = self.t(occ)\n occ = torch.add(occ, -0.5)\n occ = torch.mul(occ, 2)\n\n return gt, occ, labels_tensor, name\n\n def read_image(self, path):\n img = cv2.imread(path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n return img\n\n def get_labels_tensors(self, attr_labels, concat_size):\n\n labels_tensor = torch.from_numpy(np.array(attr_labels).astype(np.float32))\n\n if self.attributes_rsd:\n labels_tensor_resized = torch.zeros(len(attr_labels), concat_size[0], concat_size[1])\n for i in np.arange(0, len(attr_labels)):\n labels_tensor_resized[i, ...] = int(attr_labels[i])\n else:\n labels_tensor_resized = torch.from_numpy(np.array(attr_labels).astype(np.float32))\n\n return labels_tensor, labels_tensor_resized\n\n\n\n\n\n\n","sub_path":"datasets/aic[1].py","file_name":"aic[1].py","file_ext":"py","file_size_in_byte":6904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"559989989","text":"# Copyright (c) Microsoft Corporation and contributors.\n# Licensed under the MIT License.\n\nimport unittest\nimport numpy\nfrom graspologic.layouts.auto import _get_bounds\n\n\nclass TestAuto(unittest.TestCase):\n def test_get_bounds(self):\n y = numpy.array([(1, 2), (4, 5), (-1, -2), (10, -20)])\n minx, miny, maxx, maxy = _get_bounds(y)\n self.assertEqual(-1, minx)\n self.assertEqual(-20, miny)\n self.assertEqual(10, maxx)\n self.assertEqual(5, maxy)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/layouts/test_auto.py","file_name":"test_auto.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"14551964","text":"#!/usr/bin/env python\nimport os\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\nchrome_options = Options()\n#chrome_options.add_argument(\"--headless\")\nchrome_options.add_argument(\"--window-size=1920x1080\")\n\nchrome_driver = \"chromedriver\"\ndriver = webdriver.Chrome(chrome_options=chrome_options, executable_path=chrome_driver)\ndriver.get(\"https://en.wikipedia.org/wiki/Test\")\ntest = driver.find_element_by_id(\"mw-content-text\")\ntestP = test.text\ntestU = testP.encode(\"utf-8\",\"ignore\").strip()\nprint(testU)\ndriver.close()\n","sub_path":"simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"615657110","text":"#!/usr/bin/env python\n\nimport ast\nimport yaml\nimport time\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.utils.display import Display\nfrom ansible import constants\n\nANSIBLE_METADATA = {\n 'metadata_version': '3.0',\n 'supported_by': 'community',\n 'status': ['preview']\n}\n\nDOCUMENTATION = '''\n---\nmodule: ovh\nshort_description: Manage OVH API for DNS, monitoring and Dedicated servers\ndescription:\n - Add/Delete/Modify entries in OVH DNS\n - Add reverse on OVH dedicated servers\n - Install new dedicated servers from a template (both OVH and personal ones)\n - Create a personal OVH template from a file (with h/w and s/w raid support)\n - Monitor installation status on dedicated servers\n - Add/Remove OVH Monitoring on dedicated servers\n - Add/Remove a dedicated server from a OVH vrack\n - Restart a dedicate server on debian rescue or disk\n - List dedicated servers, personal templates\n - Create a template from a yml file inside an ansible role (see README)\n - Terminate a dedicated server (doesn't confirm termination, has to be done manually)\nauthor: Francois BRUNHES and Synthesio SRE Team\nnotes:\n - \"In /etc/ovh.conf (on host that executes module), you should add your\n OVH API credentials like:\n [default]\n ; general configuration: default endpoint\n endpoint=ovh-eu\n\n [ovh-eu]\n ; configuration specific to 'ovh-eu' endpoint\n application_key=\n application_secret=\n consumer_key=\n\n Or you can provide these values as module's attributes.\"\nrequirements:\n - ovh >= 0.4.8\noptions:\n endpoint:\n required: false\n description: The API endpoint to use\n application_key:\n required: false\n description: The application key to use to connect to the API\n application_secret:\n required: false\n description: The application secret to use to connect to the API\n consumer_key:\n required: false\n description: The consumer key to use to connect to the API\n name:\n required: true\n description: The name of the service (dedicated, dns)\n state:\n required: false\n default: present\n choices: ['present', 'absent', 'modified']\n description:\n - Determines whether the dedicated/dns is to be created/modified\n or deleted\n service:\n required: true\n choices: ['boot', 'dns', 'vrack', 'reverse', 'monitoring', 'install', 'status', 'list', 'template', 'terminate']\n description:\n - Determines the service you want to use in the module\n boot, change the bootid and can reboot the dedicated server\n dns, manage A entries in your domain\n vrack, add or remove a dedicated from a vrack\n reverse, add/modify a reverse on a dedicated server\n monitoring, add/removing a dedicated server from OVH monitoring\n install, install from a template\n status, used after install to know install status\n list, get a list of personal dedicated servers, personal templates\n template, create/delete an ovh template from a yaml file\n terminate, give back a dedicated server to OVH\n domain:\n required: false\n default: None\n description:\n - The domain used in dns and reverse services\n ip:\n required: false\n default: None\n description:\n - The public IP used in reverse and dns services\n vrack:\n required: false\n default: None\n description:\n - The vrack ID used in vrack service\n boot:\n required: false\n default: harddisk\n choices: ['harddisk','rescue']\n description:\n - Which way you want to boot your dedicated server\n force_reboot:\n required: false\n default: no\n choices: ['yes','no','true','false']\n description:\n - When you want to restart a dedicated server without changing his boot mode\n template:\n required: false\n default: None\n description:\n - One of your personal template on OVH\n hostname:\n required: false\n default: None\n description:\n - The hostname you want to replace in /etc/hostname when applying a template\n link_type:\n required: false\n default: private\n description:\n - The interface type you want to detect\n max_retry:\n required: false\n default: 10\n description:\n - Number of tries for the operation to suceed. OVH api can be lazy.\n sleep:\n required: false\n default: 10\n description:\n - seconds between to tries\n'''\n\nEXAMPLES = '''\n- name: Add server to vrack\n ovh:\n service: vrack\n vrack: \"VRACK ID\"\n name: \"HOSTNAME\"\n\n- name: Add server IP to DNS\n ovh:\n service: dns\n domain: \"example.com\"\n ip: \"192.0.21\"\n name: \"internal.bar\"\n\n- name: Refresh domain\n ovh:\n service: dns\n name: refresh\n domain: \"example.com\"\n\n- name: Change Reverse on server\n ovh:\n service: reverse\n name: \"internal.bar\"\n ip: \"192.0.2.1\"\n domain: \"example.com\"\n\n- name: Install the dedicated server\n ovh:\n service: install\n name: \"ovhname.ovh.eu\"\n hostname: \"internal.bar.example.com\"\n template: \"SOME TEMPLATE\"\n\n- name: Wait until installation is finished\n local_action:\n module: ovh\n args:\n service: status\n name: \"ovhname.ovh.eu\"\n max_retry: 150\n sleep: 10\n ovh:\n service: monitoring\n name: \"ovhname.ovh.eu\"\n state: \"present / absent\"\n\n- name: Get list of servers\n ovh:\n service: list\n name: dedicated\n register: servers\n\n- name: Get list of personal templates\n ovh:\n service: list\n name: templates\n register: templates\n\n- name: check if template is already installed\n ovh:\n service: list\n name: templates\n register: templates\n\n- name: Create template\n ovh:\n service: template\n name: custom_template\n state: \"present\"\n run_once: yes\n when: template not in templates.objects\n\n- name: Install the dedicated server\n ovh:\n service: install\n name: ovhname.ovh.eu\n hostname: \"internal.bar.example.com\"\n template: \"custom_template\"\n ssh_key_name=\"My Key\"\n use_distrib_kernel=True\n\n- name: Delete template\n ovh:\n service: template\n name: \"custom_template\"\n state: \"absent\"\n run_once: yes\n\n- name: terminate server\n ovh:\n service: terminate\n name: \"ns6666666.ip-42-422-42.eu\"\n'''\n\nRETURN = ''' # '''\n\ntry:\n import ovh\n import ovh.exceptions\n from ovh.exceptions import APIError\n HAS_OVH = True\nexcept ImportError:\n HAS_OVH = False\n\ndisplay = Display()\n\n\ndef main():\n argument_spec = dict(\n endpoint=dict(required=False, default=None),\n application_key=dict(required=False, default=None),\n application_secret=dict(required=False, default=None),\n consumer_key=dict(required=False, default=None),\n state=dict(default='present', choices=['present', 'absent', 'modified']),\n name=dict(required=True),\n service=dict(choices=['boot', 'dns', 'vrack', 'reverse', 'monitoring', 'install', 'status', 'list', 'template', 'terminate', 'getmac'], required=True),\n domain=dict(required=False, default=None),\n ip=dict(required=False, default=None),\n vrack=dict(required=False, default=None),\n boot=dict(default='harddisk', choices=['harddisk', 'rescue']),\n force_reboot=dict(required=False, type='bool', default=False),\n template=dict(required=False, default=None),\n hostname=dict(required=False, default=None),\n max_retry=dict(required=False, default=10),\n sleep=dict(required=False, default=10),\n ssh_key_name=dict(required=False, default=None),\n use_distrib_kernel=dict(required=False, type='bool', default=False),\n link_type=dict(required=False, default='private', choices=['public', 'private'])\n )\n\n module = AnsibleModule(\n argument_spec=argument_spec,\n supports_check_mode=True\n )\n\n om = OVHModule(module, module.check_mode, module.params)\n error, changed, result = om.run()\n if error is None:\n module.exit_json(changed=changed, **result)\n else:\n module.fail_json(msg=error, **result)\n\n\nclass OVHModule:\n\n def __init__(self, module, check_mode, params):\n self.module = module\n self.check_mode = check_mode\n self.params = params\n self.client = None\n\n def run(self):\n \"\"\"Return error, changed, result\"\"\"\n if not HAS_OVH:\n return self.fail('OVH Api wrapper not installed')\n\n credentials = ['endpoint', 'application_key', 'application_secret', 'consumer_key']\n credentials_in_parameters = [cred in self.params for cred in credentials]\n try:\n if all(credentials_in_parameters):\n self.client = ovh.Client(**{credential: self.params[credential] for credential in credentials})\n else:\n self.client = ovh.Client()\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n choice_map = dict(\n dns=self.change_dns,\n getmac=self.get_mac,\n terminate=self.terminate_server,\n status=self.get_status_install,\n install=self.launch_install,\n monitoring=self.change_monitoring,\n reverse=self.change_reverse,\n list=self.list_service,\n boot=self.change_boot_dedicated,\n template=self.generate_template,\n vrack=self.change_vrack,\n )\n\n return choice_map.get(self.params['service'])()\n\n def fail(self, message):\n return message, False, {}\n\n def succeed(self, message, changed=True, contents=None, objects=None):\n result = {}\n if message is not None:\n result['msg'] = message\n if contents is not None:\n result['contents'] = contents\n if objects is not None:\n result['objects'] = objects\n\n return None, changed, result\n\n def change_dns(self):\n domain = self.params['domain']\n ip = self.params['ip']\n name = self.params['name']\n state = self.params['state']\n\n msg = ''\n\n if not domain:\n return self.fail(\"Please give a domain to add your target\")\n\n if name == 'refresh':\n if self.check_mode:\n return self.succeed(\"Domain %s succesfully refreshed ! - (dry run mode)\" % domain, changed=True)\n\n try:\n self.client.post(\n '/domain/zone/%s/refresh' % domain\n )\n return self.succeed(\"Domain %s succesfully refreshed !\" % domain, changed=True)\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n if self.check_mode:\n return self.succeed(\"DNS succesfully %s on %s - (dry run mode)\" % (state, name), changed=True)\n\n if not ip:\n return self.fail(\"Please give an IP to add your target\")\n\n try:\n check = self.client.get(\n '/domain/zone/%s/record' % domain,\n fieldType='A',\n subDomain=name\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n if state == 'present':\n if check:\n return self.succeed(\"%s is already registered in domain %s\" % (name, domain), changed=False)\n\n try:\n result = self.client.post(\n '/domain/zone/%s/record' % domain,\n fieldType='A',\n subDomain=name,\n target=ip\n )\n return self.succeed(message=None, contents=result, changed=True)\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n elif state == 'modified':\n if not check:\n return self.fail(\"The target %s doesn't exist in domain %s\" % (name, domain))\n\n try:\n for ind in check:\n self.client.put(\n '/domain/zone/%s/record/%s' % (domain, ind),\n subDomain=name,\n target=ip\n )\n msg += ('{ \"fieldType\": \"A\", \"id\": \"%s\", \"subDomain\": \"%s\", \"target\": \"%s\", \"zone\": \"%s\" } '\n % (ind, name, ip, domain))\n return self.succeed(msg, changed=True)\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n elif state == 'absent':\n if not check:\n return self.succeed(\"Target %s doesn't exist on domain %s\" % (name, domain), changed=False)\n\n try:\n for ind in check:\n self.client.delete(\n '/domain/zone/%s/record/%s' % (domain, ind)\n )\n return self.succeed(\"Target %s succesfully deleted from domain %s\" % (name, domain), changed=True)\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n def get_mac(self):\n name = self.params['name']\n link_type = self.params['link_type']\n result = self.client.get(\n '/dedicated/server/%s/networkInterfaceController?linkType=%s' % (name, link_type)\n )\n return self.succeed(result, changed=False)\n\n def terminate_server(self):\n name = self.params['name']\n\n if not name:\n return self.fail(\"Please give a dedicated name to terminate\")\n\n if self.check_mode:\n return self.succeed(\"Terminate %s is done, please confirm via the email sent - (dry run mode)\" % name, changed=True)\n\n try:\n self.client.post(\n '/dedicated/server/%s/terminate' % name\n )\n return self.succeed(\"Terminate %s is done, please confirm via the email sent\" % name, changed=True)\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n def get_status_install(self):\n name = self.params['name']\n max_retry = self.params['max_retry']\n sleep = self.params['sleep']\n\n if not name:\n return self.fail(\"Please provide 'ns' server name from which installation status will be check\")\n\n if self.check_mode:\n return self.succeed(\"done - (dry run mode)\", changed=False)\n\n for i in range(1, int(max_retry)):\n # Messages cannot be displayed in real time (yet): https://github.com/ansible/proposals/issues/92\n display.display(\"%i out of %i\" % (i, int(max_retry)), constants.COLOR_VERBOSE)\n try:\n tasklist = self.client.get(\n '/dedicated/server/%s/task' % name,\n function='reinstallServer')\n result = self.client.get(\n '/dedicated/server/%s/task/%s' % (name, max(tasklist)))\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n message = \"\"\n # Get more details in installation progression\n if \"done\" in result['status']:\n return self.succeed(\"%s: %s\" % (result['status'], message), changed=False)\n\n progress_status = self.client.get(\n '/dedicated/server/%s/install/status' % name\n )\n if 'message' in progress_status and progress_status['message'] == 'Server is not being installed or reinstalled at the moment':\n message = progress_status['message']\n else:\n for progress in progress_status['progress']:\n if progress[\"status\"] == \"doing\":\n message = progress['comment']\n display.display(\"%s: %s\" % (result['status'], message), constants.COLOR_VERBOSE)\n time.sleep(float(sleep))\n return self.fail(\"Max wait time reached, about %i x %i seconds\" % (i, int(max_retry)))\n\n def launch_install(self):\n name = self.params['name']\n template = self.params['template']\n hostname = self.params['hostname']\n ssh_key_name = self.params.get('ssh_key_name')\n use_distrib_kernel = self.params.get('use_distrib_kernel', False)\n\n if not name:\n return self.fail(\"Please give the service's name you want to install\")\n if not template:\n return self.fail(\"Please give a template to install\")\n if not hostname:\n return self.fail(\"Please give a hostname for your installation\")\n\n try:\n compatible_templates = self.client.get(\n '/dedicated/server/%s/install/compatibleTemplates' % name\n )\n compatible_templates = set([tpl\n for template_type in compatible_templates.keys()\n for tpl in compatible_templates[template_type]])\n if template not in compatible_templates:\n return self.fail(\"%s doesn't exist in compatibles templates\" % template)\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n if self.check_mode:\n return self.succeed(\"Installation in progress on %s ! - (dry run mode)\" % name, changed=True)\n\n details = {\"details\": {\"language\": \"en\", \"customHostname\": hostname}, \"templateName\": template}\n if ssh_key_name:\n try:\n result = self.client.get('/me/sshKey')\n if ssh_key_name not in result:\n return self.fail(\"%s doesn't exist in public SSH keys\" % ssh_key_name)\n else:\n details['details']['sshKeyName'] = ssh_key_name\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n if use_distrib_kernel:\n details['details']['useDistribKernel'] = use_distrib_kernel\n try:\n self.client.post('/dedicated/server/%s/install/start' % name, **details)\n # TODO\n # check if details are still properly formed, even for a HW Raid config.\n # For instance:\n # {'details': {'customHostname': 'test01.test.synthesio.net',\n # 'diskGroupId': None,\n # 'installSqlServer': False,\n # 'language': 'en',\n # 'noRaid': False,\n # 'postInstallationScriptLink': None,\n # 'postInstallationScriptReturn': None,\n # 'resetHwRaid': False,\n # 'softRaidDevices': None,\n # 'sshKeyName': 'deploy',\n # 'useDistribKernel': True,\n # 'useSpla': False},\n # 'templateName': 'test'}\n return self.succeed(\"Installation in progress on %s !\" % name, changed=True)\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n def change_monitoring(self):\n name = self.params['name']\n state = self.params['state']\n max_retry = self.params['max_retry']\n sleep = self.params['sleep']\n\n if not name:\n return self.fail(\"Please give a name to change monitoring state\")\n if not state:\n return self.fail(\"Please give a state for your monitoring\")\n\n if state == 'present':\n shouldbe = True\n elif state == 'absent':\n shouldbe = False\n else:\n return self.fail(\"State %s does not match 'present' or 'absent'\" % state)\n\n if self.check_mode:\n return self.succeed(\"Monitoring %s on %s - (dry run mode)\" % (state, name), changed=True)\n\n for i in range(1, int(max_retry)):\n server_state = self.client.get(\n '/dedicated/server/%s' % name\n )\n\n if server_state['monitoring'] == shouldbe:\n if shouldbe:\n return self.succeed(\"Monitoring activated on %s after %i time(s)\" % (name, i), changed=True)\n else:\n return self.succeed(\"Monitoring deactivated on %s after %i time(s)\" % (name, i), changed=True)\n\n try:\n self.client.put(\n '/dedicated/server/%s' % name, monitoring=shouldbe\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n time.sleep(float(sleep))\n return self.fail(\"Could not change monitoring flag\")\n\n def change_reverse(self):\n name = self.params['name']\n domain = self.params['domain']\n ip = self.params['ip']\n\n if not domain:\n return self.fail(\"Please give a domain to add your target\")\n if not ip:\n return self.fail(\"Please give an IP to add your target\")\n\n fqdn = name + '.' + domain + '.'\n result = {}\n try:\n result = self.client.get('/ip/%s/reverse/%s' % (ip, ip))\n except ovh.exceptions.ResourceNotFoundError:\n result['reverse'] = ''\n\n if result['reverse'] == fqdn:\n return self.succeed(\"Reverse already set\", changed=False)\n\n if self.check_mode:\n return self.succeed(\"Reverse %s to %s succesfully set ! - (dry run mode)\" % (ip, fqdn), changed=True)\n try:\n self.client.post(\n '/ip/%s/reverse' % ip,\n ipReverse=ip,\n reverse=fqdn\n )\n return self.succeed(\"Reverse %s to %s succesfully set !\" % (ip, fqdn), changed=True)\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n def list_service(self):\n name = self.params['name']\n\n if name == 'dedicated':\n return self.list_dedicated()\n elif name == 'templates':\n return self.list_templates()\n else:\n return self.fail(\"%s not supported for 'list' service\" % name)\n\n def list_dedicated(self):\n customlist = []\n try:\n result = self.client.get(\n '/dedicated/server'\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n try:\n for i in result:\n test = self.client.get(\n '/dedicated/server/%s' % i\n )\n customlist.append('%s=%s' % (test['reverse'], i))\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n return self.succeed(message=None, changed=False, objects=customlist)\n\n def list_templates(self):\n customlist = []\n try:\n result = self.client.get(\n '/me/installationTemplate'\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n try:\n for i in result:\n if 'tmp-mgr' not in i:\n customlist.append(i)\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n return self.succeed(message=None, changed=False, objects=customlist)\n\n def change_boot_dedicated(self):\n name = self.params['name']\n boot = self.params['boot']\n force_reboot = self.params['force_reboot']\n\n bootid = {'harddisk': 1, 'rescue': 1122}\n if self.check_mode:\n return self.succeed(\"%s is now set to boot on %s. Reboot in progress... - (dry run mode)\" % (name, boot), changed=True)\n\n try:\n check = self.client.get(\n '/dedicated/server/%s' % name\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n if bootid[boot] != check['bootId']:\n try:\n self.client.put(\n '/dedicated/server/%s' % name,\n bootId=bootid[boot]\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n return self.succeed(\"%s is now set to boot on %s.\" % (name, boot), changed=True)\n\n if force_reboot:\n try:\n self.client.post(\n '/dedicated/server/%s/reboot' % name\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n return self.succeed(\"%s is now rebooting on %s\" % (name, boot))\n\n return self.succeed(\"%s already configured for boot on %s\" % (name, boot), changed=False)\n\n def generate_template(self):\n name = self.params['name']\n template = self.params['template']\n state = self.params['state']\n\n if not template:\n return self.fail(\"No template parameter given\")\n\n if self.check_mode:\n return self.succeed(\"%s succesfully %s on ovh API - (dry run mode)\" % (template, state), changed=True)\n\n if state not in ['present', 'absent']:\n return self.fail(\"State %s not supported. Only present/absent\" % state)\n\n src = template\n with open(src, 'r') as stream:\n content = yaml.load(stream)\n conf = {}\n for i, j in content.iteritems():\n conf[i] = j\n\n if state == 'absent':\n try:\n self.client.delete(\n '/me/installationTemplate/%s' % conf['templateName']\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n return self.succeed(\"Template %s succesfully deleted\" % conf['templateName'], changed=True)\n\n # state == 'present'\n try:\n result = self.client.post(\n '/me/installationTemplate',\n baseTemplateName=conf['baseTemplateName'],\n defaultLanguage=conf['defaultLanguage'],\n name=conf['templateName']\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n templates = {\n 'customization': {\"customHostname\": conf['customHostname'],\n \"postInstallationScriptLink\": conf['postInstallationScriptLink'],\n \"postInstallationScriptReturn\": conf['postInstallationScriptReturn'],\n \"sshKeyName\": conf['sshKeyName'],\n \"useDistributionKernel\": conf['useDistributionKernel']},\n 'defaultLanguage': conf['defaultLanguage'],\n 'templateName': conf['templateName']}\n try:\n result = self.client.put(\n '/me/installationTemplate/%s' % conf['templateName'], **templates\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n try:\n result = self.client.post(\n '/me/installationTemplate/%s/partitionScheme' % conf['templateName'],\n name=conf['partitionScheme'],\n priority=conf['partitionSchemePriority']\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n if conf['isHardwareRaid']:\n result = self.client.get(\n '/dedicated/server/%s/install/hardwareRaidProfile' % name\n )\n\n if len(result['controllers']) != 1:\n return self.fail(\"Failed to call OVH API: {0} Code can't handle more than one controller when using Hardware Raid setups\")\n\n # XXX: Only works with a server who has one controller.\n # All the disks in this controller are taken to form one raid\n # In the future, some of our servers could have more than one controller\n # so we will have to adapt this code\n disks = result['controllers'][0]['disks'][0]['names']\n\n # if 'raid 1' in conf['raidMode']:\n # TODO : create a list of disks like this\n # {'disks': ['[c0:d0,c0:d1]',\n # '[c0:d2,c0:d3]',\n # '[c0:d4,c0:d5]',\n # '[c0:d6,c0:d7]',\n # '[c0:d8,c0:d9]',\n # '[c0:d10,c0:d11]'],\n # 'mode': 'raid10',\n # 'name': 'managerHardRaid',\n # 'step': 1}\n # else:\n # TODO : for raid 0, it's assumed that a simple list of disks would be sufficient\n try:\n result = self.client.post(\n '/me/installationTemplate/%s/partitionScheme/%s/hardwareRaid' % (conf['templateName'], conf['partitionScheme']),\n disks=disks,\n mode=conf['raidMode'],\n name=conf['partitionScheme'],\n step=1)\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n partition = {}\n for k in conf['partition']:\n partition = ast.literal_eval(k)\n try:\n if 'raid' in partition.keys():\n self.client.post(\n '/me/installationTemplate/%s/partitionScheme/%s/partition' % (conf['templateName'], conf['partitionScheme']),\n filesystem=partition['filesystem'],\n mountpoint=partition['mountpoint'],\n raid=partition['raid'],\n size=partition['size'],\n step=partition['step'],\n type=partition['type'])\n else:\n self.client.post(\n '/me/installationTemplate/%s/partitionScheme/%s/partition' % (conf['templateName'], conf['partitionScheme']),\n filesystem=partition['filesystem'],\n mountpoint=partition['mountpoint'],\n size=partition['size'],\n step=partition['step'],\n type=partition['type'])\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n try:\n self.client.post('/me/installationTemplate/%s/checkIntegrity' % conf['templateName'])\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n return self.succeed(\"Template %s succesfully created\" % conf['templateName'], changed=True)\n\n def change_vrack(self):\n name = self.params['name']\n state = self.params['state']\n vrack = self.params['vrack']\n\n if not vrack:\n return self.fail(\"Please give a vrack name to add/remove your server\")\n\n if state not in ['present', 'absent']:\n return self.succeed(\"Vrack service only uses present/absent state\", changed=False)\n\n if self.check_mode:\n return self.succeed(\"%s succesfully %s on %s - (dry run mode)\" % (name, state, vrack), changed=True)\n\n if state == 'present':\n try:\n # There is no easy way to know if the server is on an old or new network generation.\n # So we need to call this new route to ask for virtualNetworkInterface\n # and if the answer is empty, it's on a old generation.\n # The /vrack/%s/allowedServices route used previously has availability and scaling problems.\n result = self.client.get(\n '/dedicated/server/%s/virtualNetworkInterface' % name,\n mode='vrack'\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n# XXX: In a near future, OVH will add the possibility to add multiple interfaces to the same VRACK or another one\n# This code may break at this moment because each server will have a list of dedicatedServerInterface\n\n # New generation\n if len(result):\n try:\n is_already_registered = self.client.get(\n '/vrack/%s/dedicatedServerInterfaceDetails' % vrack\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n for new_server in is_already_registered:\n if new_server['dedicatedServer'] == name:\n return self.succeed(\"%s is already registered on %s\" % (name, vrack), changed=False)\n try:\n server_interface = \"\".join(result)\n result2 = self.client.post(\n '/vrack/%s/dedicatedServerInterface' % vrack,\n dedicatedServerInterface=server_interface\n )\n return self.succeed(None, contents=result2, changed=True)\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n # Old generation\n else:\n try:\n is_already_registered = self.client.get(\n '/vrack/%s/dedicatedServer' % vrack\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n for old_server in is_already_registered:\n if old_server == name:\n return self.succeed(\"%s is already registered on %s\" % (name, vrack), changed=False)\n\n try:\n result2 = self.client.post(\n '/vrack/%s/dedicatedServer' % vrack,\n dedicatedServer=name\n )\n return self.succeed(None, contents=result2, changed=True)\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n elif state == 'absent':\n try:\n result_new = self.client.get(\n '/vrack/%s/dedicatedServerInterfaceDetails' % vrack\n )\n result_old = self.client.get(\n '/vrack/%s/dedicatedServer' % vrack\n )\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n for new_server in result_new:\n if new_server['dedicatedServer'] == name:\n try:\n result = self.client.delete(\n '/vrack/%s/dedicatedServerInterface/%s' % (vrack, new_server['dedicatedServerInterface'])\n )\n return self.succeed(None, contents=result, changed=True)\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n for old_server in result_old:\n if old_server == name:\n try:\n result = self.client.delete(\n '/vrack/%s/dedicatedServer/%s' % (vrack, name)\n )\n return self.succeed(None, contents=result, changed=True)\n except APIError as api_error:\n return self.fail(\"Failed to call OVH API: {0}\".format(api_error))\n\n return self.succeed(\"No %s in %s\" % (name, vrack), changed=False)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"plugins/modules/ovh.py","file_name":"ovh.py","file_ext":"py","file_size_in_byte":36495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"584011169","text":"#============= enthought library imports =======================\n\n#============= standard library imports ========================\nfrom threading import Thread\nimport os\nimport time\n#============= local library imports ==========================\nfrom src.loggable import Loggable\nfrom enthought.pyface.api import information\nfrom src.helpers.paths import src_root, project_home\nfrom enthought.pyface.timer.do_later import do_later\nHEAD = ''\nBASE = ''\ntry:\n import pysvn\n HEAD = pysvn.Revision(pysvn.opt_revision_kind.head)\n BASE = pysvn.Revision(pysvn.opt_revision_kind.base)\n def revision_factory(n):\n rev = pysvn.Revision(pysvn.opt_revision_kind.number, n)\n return rev\nexcept ImportError:\n pysvn = None\n\n\nVERSION_PATH = 'version_info.txt'\nclass SVNClient(Loggable):\n def __init__(self, *args, **kw):\n '''\n @type *args: C{str}\n @param *args:\n\n @type **kw: C{str}\n @param **kw:\n '''\n self.name = 'SVNClient'\n super(SVNClient, self).__init__(*args, **kw)\n self._client = pysvn.Client() if pysvn is not None else None\n if self._client is not None:\n self._client.callback_ssl_server_trust_prompt\n def _update_(self):\n '''\n '''\n revision = self._client.update(src_root)[0]\n self.info('updated to revision %i' % revision.number)\n msg = 'Restart for updates to take effect'\n self.info(msg)\n information(None, msg)\n\n def update_to_head(self):\n '''\n '''\n self.info('updating to head')\n t = Thread(target = self._update_)\n t.start()\n\n def isCurrent(self):\n status = self._client.status(src_root, get_all = False)\n\n current = True\n for pi in status:\n head, tail = os.path.splitext(pi.path)\n if tail != '.pyc':\n if pi.is_versioned:\n if str(pi.repos_text_status) != \"none\":\n current = False\n break\n return current\n\n def get_version_number(self):\n #p='http://arlab.googlecode.com/svn/branches/pychron'\n if self._client:\n entry = self._client.info(src_root)\n\n return int(entry.revision.number)\n\n def get_local_version_file(self):\n if self._client:\n p = os.path.join(src_root, VERSION_PATH)\n\n entry = self._client.info(p)\n\n return p, entry\n\n def get_remote_version_file(self, progress = None):\n if self._client:\n p = os.path.join(project_home, VERSION_PATH)\n self._inprogress = True\n if progress is not None:\n tt = Thread(target = self._timer_update, args = (progress,))\n tt.start()\n return self._get_remote_file_info(p)\n# t=Thread(target=self._get_remote_file_info, args=(p,))\n# t.start()\n\n def _timer_update(self, progress):\n\n do_later(progress.update, *(0,))\n while self._inprogress:\n time.sleep(0.1)\n\n progress.reset()\n\n def _get_remote_file_info(self, p):\n if self._client:\n self._inprogress = True\n name, info = self._client.info2(p,\n )[0]\n\n self._inprogress = False\n return name, info\n\n# def __getattr__(self, name):\n# '''\n# @type name: C{str}\n# @param name:\n# '''\n# obj = self\n# if hasattr(self._client, name):\n# obj = self._client\n#\n# return getattr(obj, name)\n#============= EOF ====================================\n","sub_path":"src/svn/svn_client.py","file_name":"svn_client.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"221889573","text":"##########################################################\n## GENERIC SUSY TREE PRODUCTION CONFIG. ##\n## no skim is applied in this configuration, as it is ##\n## meant only to check that all common modules run ok ##\n##########################################################\n\n\nimport CMGTools.RootTools.fwlite.Config as cfg\nfrom CMGTools.RootTools.fwlite.Config import printComps\nfrom CMGTools.RootTools.RootTools import *\nfrom PhysicsTools.HeppyCore.framework.heppy import getHeppyOption\n\n#Load all common analyzers\nfrom CMGTools.VVResonances.analyzers.core_cff import * \n\n#-------- SAMPLES AND TRIGGERS -----------\nfrom CMGTools.VVResonances.samples.samples_13TeV_Spring15 import * \n\n#selectedComponents = WJetsToLNuHT+QCDPt\nselectedComponents = QCDPt\n\n#-------- Analyzer\nfrom CMGTools.VVResonances.analyzers.tree_cff import * \n\n#-------- SEQUENCE\n\n\ncoreSequence = [\n #eventSelector,\n jsonAna,\n triggerAna,\n pileUpAna,\n genAna,\n# pdfwAna,\n vertexAna,\n lepAna\n]\n\n\nsequence = cfg.Sequence(coreSequence+[leptonSkimmer,leptonTreeProducer])\n\n\n#-------- HOW TO RUN\ntest = 0\nif test==1:\n # test a single component, using a single thread.\n comp = RSGravToWWToLNQQ_2000\n comp.files = comp.files[:1]\n selectedComponents = [comp]\n comp.splitFactor = 1\n\nelif test==2: \n # test all components (1 thread per component).\n for comp in selectedComponents:\n comp.splitFactor = 1\n comp.files = comp.files[:1]\n\n\n\n\n\n## output histogram\noutputService=[]\nfrom PhysicsTools.HeppyCore.framework.services.tfile import TFileService\noutput_service = cfg.Service(\n TFileService,\n 'outputfile',\n name=\"outputfile\",\n fname='vvTreeProducer/tree.root',\n option='recreate'\n ) \noutputService.append(output_service)\n\n\n\nfrom PhysicsTools.HeppyCore.framework.eventsfwlite import Events\nfrom CMGTools.TTHAnalysis.tools.EOSEventsWithDownload import EOSEventsWithDownload\nevent_class = EOSEventsWithDownload\nif getHeppyOption(\"nofetch\"):\n event_class = Events \nconfig = cfg.Config( components = selectedComponents,\n sequence = sequence,\n services = [], \n events_class = event_class)\n\n","sub_path":"VVResonances/cfg/run_LeptonAnalysis_cfg.py","file_name":"run_LeptonAnalysis_cfg.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"629727911","text":"# scraper\nfrom bs4 import BeautifulSoup\nimport requests\n\nclass IMDB_Scraper:\n '''\n This class scrapes IMDB movies directed by a list of directors.\n The script is passed a director profile url, then grabs links to all the movies they directed.\n The links are iteratively requested and scraped, with the director profile as a via.\n\n For each movie, the title, release_date, runtime, age_rating, genre(s), and review_rating is \n put into a list and written out to a csv file\n '''\n def __init__(self, dir_url, dir_index):\n '''\n The director profile url is requested from the internet as text.\n The web-scraping library BeautifulSoup then parses the requested text as the full HTML script.\n\n IMDB has different indices for the 'Director' category, where 'Producer' and 'Actor' are sometimes mentioned,\n thus each index specifically for the director category is manually input into the system.\n\n Some movies are in production, so the array of movie links from the director's profile\n are filtered out to where only movies made on or before 2019 are processed.\n All other instances of inconsistent data are filtered out in the try/except block.\n '''\n self.source = requests.get(dir_url).text\n self.soup = BeautifulSoup(self.source, 'lxml')\n \n self.links = []\n \n dir_works = [category for category in self.soup.find_all('div', class_ = 'filmo-category-section')][dir_index]\n dir_works_arr = [works for works in dir_works.find_all('div')]\n \n for element in dir_works_arr:\n try:\n date = element.find('span', class_ = 'year_column').text\n date = date.split('\\xa0')[1].split('\\n')[0].split('/')[0].split('-')[0]\n\n if not date: pass\n elif int(date) <= 2019: self.links.append('https://imdb.com' + element.find('a', href = True)['href'])\n else: pass\n\n except AttributeError: print(' --- Inconsistent data or movie not found here. Skipping... ---')\n \n \n def request_movie(self, movie_url):\n '''\n The source url is the director profile, thus it is placed in the __init__() function\n For each movie link the source processing produces, it is requested and scraped here.\n The source and soup attributes are updated accordingly\n\n The div tag with title_wrapper class has most of the data needed for this project.\n '''\n self.source = requests.get(movie_url).text\n self.soup = BeautifulSoup(self.source, 'lxml')\n self.info = self.soup.find('div', class_ = 'title_wrapper')\n \n \n def movie_title(self):\n '''\n The heading tag has the title with some extra text,\n so the tag is filtered so only the title as a string is output.\n If the info is missing, which is unlikely, 'N/A' will be output instead.\n '''\n try: return self.info.find('h1').text.split('\\xa0')[0]\n except: return 'N/A'\n \n \n def release_date(self):\n '''\n The release date is processed here...\n If the info is missing, 'N/A' will be output instead.\n '''\n try: return self.info.find('div', class_ = 'subtext').text.strip().split('\\n')[-1]\n except: return 'N/A'\n \n \n def runtime(self):\n '''\n The runtime is processed here...\n If the info is missing, 'N/A' will be output instead.\n '''\n try: return self.info.find('time').text.strip()\n except: return 'N/A'\n \n \n def age_rating(self):\n '''\n The age rating is processed here...\n The runtime may be processed as the age_rating, which is incorrect as is filtered out.\n If the info is missing, or the runtime is output as the age_rating,\n 'N/A' will be output instead.\n '''\n try:\n age_rating = self.info.find('div', class_ = 'subtext').text.strip().split('\\n')[0] \n return 'N/A' if (age_rating == self.runtime()) else age_rating\n \n except: return 'N/A'\n \n \n def genre(self):\n '''\n The genre is processed here...\n If the info is missing, 'N/A' will be output instead.\n '''\n try: return [self.info.find('div', class_ = 'subtext').text.strip().split('|')[2]]\n except: return 'N/A'\n \n \n def score(self):\n '''\n The review rating is processed here...\n If the info is missing, 'N/A' will be output instead.\n '''\n try: return self.soup.find('div', class_ = 'ratingValue').text.strip()\n except: return 'N/A'\n","sub_path":"directors_project/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":4674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"482053392","text":"#!/usr/bin/env python3\n\nimport argparse\nimport logging\nimport os\nimport subprocess\n\nfrom env_helper import GITHUB_WORKSPACE, TEMP_PATH\nfrom get_robot_token import get_best_robot_token\nfrom ssh import SSHKey\nfrom cherry_pick_utils.backport import Backport\nfrom cherry_pick_utils.cherrypick import CherryPick\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(\"Create cherry-pick and backport PRs\")\n parser.add_argument(\"--token\", help=\"github token, if not set, used from smm\")\n parser.add_argument(\"--dry-run\", action=\"store_true\", help=\"do not create anything\")\n return parser.parse_args()\n\n\ndef main():\n args = parse_args()\n token = args.token or get_best_robot_token()\n\n bp = Backport(\n token,\n os.environ.get(\"REPO_OWNER\"),\n os.environ.get(\"REPO_NAME\"),\n os.environ.get(\"REPO_TEAM\"),\n )\n\n cherry_pick = CherryPick(\n token,\n os.environ.get(\"REPO_OWNER\"),\n os.environ.get(\"REPO_NAME\"),\n os.environ.get(\"REPO_TEAM\"),\n 1,\n \"master\",\n )\n # Use the same _gh in both objects to have a proper cost\n # pylint: disable=protected-access\n for key in bp._gh.api_costs:\n if key in cherry_pick._gh.api_costs:\n bp._gh.api_costs[key] += cherry_pick._gh.api_costs[key]\n for key in cherry_pick._gh.api_costs:\n if key not in bp._gh.api_costs:\n bp._gh.api_costs[key] = cherry_pick._gh.api_costs[key]\n cherry_pick._gh = bp._gh\n # pylint: enable=protected-access\n\n def cherrypick_run(pr_data, branch):\n cherry_pick.update_pr_branch(pr_data, branch)\n return cherry_pick.execute(GITHUB_WORKSPACE, args.dry_run)\n\n try:\n bp.execute(GITHUB_WORKSPACE, \"origin\", None, cherrypick_run)\n except subprocess.CalledProcessError as e:\n logging.error(e.output)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n\n if not os.path.exists(TEMP_PATH):\n os.makedirs(TEMP_PATH)\n\n if os.getenv(\"ROBOT_CLICKHOUSE_SSH_KEY\", \"\"):\n with SSHKey(\"ROBOT_CLICKHOUSE_SSH_KEY\"):\n main()\n else:\n main()\n","sub_path":"tests/ci/cherry_pick.py","file_name":"cherry_pick.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"31703053","text":"import statistics\n\n# Print each value name for how they will appear below in order (for the user)\nprint(\"Mean,\", \"Median,\", \"Mode,\", \"Min,\", \"Max\")\n# First number line\nnums1 = [33, 5, 453, 21, 67, 657, 3425, 65, 21, 33, 44, 634, 543, 2345, 697]\n# Call the mean, median and mode using the statistics module from the first number line\nmean = statistics.mean(nums1)\nmedian = statistics.median(nums1)\nmode = statistics.mode(nums1)\n# Print results for line 1\nprint(mean, \",\", median, \",\", mode, \",\", min(nums1), \",\", max(nums1))\n\n# Second number line\nnums2 = [65, 53, 485, 65, 453, 7895, 24, 65, 531, 24, 755, 342, 32, 1, 65, 99]\n# Call the mean, median and mode using the statistics module from the second number line\nmean = statistics.mean(nums2)\nmedian = statistics.median(nums2)\nmode = statistics.mode(nums2)\n# Print results for line 2\nprint(mean, \",\", median, \",\", mode, \",\", min(nums2), \",\", max(nums2))\n\n# Third number line\nnums3 = [5435, 234, 398, 398, 534, 234, 65, 78, 66, 534, 456, 234, 54, 534, 56, 34, 77]\n# Call the mean, median and mode using the statistics module from the third number line\nmean = statistics.mean(nums3)\nmedian = statistics.median(nums3)\nmode = statistics.mode(nums3)\n# Print results for line 3\nprint(mean, \",\", median, \",\", mode, \",\", min(nums3), \",\", max(nums3))\n\n# Fourth number line\nnums4 = [555, 435, 1, 3, 54, 6, 4, 5, 87, 943, 6, 3, 45, 1, 45, 55, 2, 7, 8, 9, 700, 76, 45]\n# Call the mean, median and mode using the statistics module from the fourth number line\nmean = statistics.mean(nums4)\nmedian = statistics.median(nums4)\nmode = statistics.mode(nums4)\n# Print results for line 4\nprint(mean, \",\", median, \",\", mode, \",\", min(nums4), \",\", max(nums4))\n","sub_path":"Simple Stats.py","file_name":"Simple Stats.py","file_ext":"py","file_size_in_byte":1692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"86945779","text":"from __future__ import print_function, division\nfrom torch.utils.data import Dataset, DataLoader\nimport scipy.io as scp\nimport numpy as np\nimport torch\nimport pdb\n\nimport copy\n\n#___________________________________________________________________________________________________________________________\n\n### Dataset class for the NGSIM dataset\nclass ngsimDataset(Dataset):\n\n\n\tdef __init__(self, mat_file, t_h=30, t_f=50, d_s=2, enc_size = 64, grid_size = (13,3), newFeats=0):\n\t\tself.newFeats = newFeats\n\t\tself.D = scp.loadmat(mat_file)['traj']\n\t\tself.T = scp.loadmat(mat_file)['tracks']\n\t\tself.t_h = t_h\t# length of track history\n\t\tself.t_f = t_f\t# length of predicted trajectory\n\t\tself.d_s = d_s\t# down sampling rate of all sequences\n\t\tself.enc_size = enc_size # size of encoder LSTM\n\t\tself.grid_size = grid_size # size of social context grid\n\n\t\tself.Tx = self.t_h//self.d_s + 1\n\n\tdef __len__(self):\n\t\treturn len(self.D)\n\n\n\n\tdef __getitem__(self, idx):\n\n\t\tdsId = self.D[idx, 0].astype(int)\n\t\tvehId = self.D[idx, 1].astype(int)\n\t\tt = self.D[idx, 2]\n\t\tgrid = self.D[idx, self.newFeats + 8:]\n\t\tneighbors = []\n\n\t\t# Get track history 'hist' = ndarray, and future track 'fut' = ndarray\n\t\thist = self.getHistory(vehId,t,vehId,dsId)\n\n\t\t# ACHTUNG: this may be slow (check later)\n\t\thist_grid = np.zeros((self.Tx, self.grid_size[0], self.grid_size[1]))\n\t\ti = idx; count = 1\n\t\twhile i >= 0 and i > idx - self.Tx:\n\t\t\tpast_grid = self.D[i, self.newFeats + 8:] # First one is actually current grid\n\t\t\tpast_grid = np.reshape(past_grid, (self.grid_size[1], self.grid_size[0])).transpose()\n\t\t\tpast_grid = (past_grid > 0).astype(int) # just an occupancy grid\n\t\t\thist_grid[-count, :] = past_grid\n\t\t\ti -= 1\n\t\t\tcount += 1\n\n\t\tfut = self.getFuture(vehId,t,dsId)\n\n\t\t# Get track histories of all neighbours 'neighbors' = [ndarray,[],ndarray,ndarray]\n\t\tfor i in grid:\n\t\t\tneighbors.append(self.getHistory(i.astype(int), t,vehId,dsId))\n\n\t\t# Maneuvers 'lon_enc' = one-hot vector, 'lat_enc = one-hot vector\n\t\tlon_enc = np.zeros([2])\n\t\tlon_enc[int(self.D[idx, self.newFeats + 7] - 1)] = 1\n\t\tlat_enc = np.zeros([3])\n\t\tlat_enc[int(self.D[idx, self.newFeats + 6] - 1)] = 1\n\n\t\treturn hist,fut,neighbors,lat_enc,lon_enc,hist_grid\n\n\n\n\t## Helper function to get track history\n\tdef getHistory(self,vehId,t,refVehId,dsId):\n\t\tif vehId == 0:\n\t\t\treturn np.empty([0,2 + self.newFeats ])\n\t\telse:\n\t\t\tif self.T.shape[1]<=vehId-1:\n\t\t\t\treturn np.empty([0,2 + self.newFeats])\n\t\t\trefTrack = self.T[dsId-1][refVehId-1].transpose()\n\t\t\tvehTrack = self.T[dsId-1][vehId-1].transpose()\n\t\t\trefPos = refTrack[np.where(refTrack[:,0]==t)][0,1:3]\n\n\t\t\tif vehTrack.size==0 or np.argwhere(vehTrack[:, 0] == t).size==0:\n\t\t\t\treturn np.empty([0,2 + self.newFeats])\n\t\t\telse:\n\t\t\t\tstpt = np.maximum(0, np.argwhere(vehTrack[:, 0] == t).item() - self.t_h)\n\t\t\t\tenpt = np.argwhere(vehTrack[:, 0] == t).item() + 1\n\t\t\t\t# ACHTUNG copy is mandatory !\n\t\t\t\thist = copy.copy(vehTrack[stpt:enpt:self.d_s,1:3 + self.newFeats]) # 0:Time, 1:X, 2:Y, 3:V or A\n\t\t\t\thist[:,0:2] = hist[:,0:2] - refPos\n\t\t\t\t#hist = vehTrack[stpt:enpt:self.d_s,1:3]-refPos\n\n\t\t\tif len(hist) < self.t_h//self.d_s + 1:\n\t\t\t\treturn np.empty([0,2 + self.newFeats])\n\t\t\treturn hist\n\n\n\n\t## Helper function to get track future\n\tdef getFuture(self, vehId, t,dsId):\n\t\tvehTrack = self.T[dsId-1][vehId-1].transpose()\n\t\trefPos = vehTrack[np.where(vehTrack[:, 0] == t)][0, 1:3]\n\t\tstpt = np.argwhere(vehTrack[:, 0] == t).item() + self.d_s\n\t\tenpt = np.minimum(len(vehTrack), np.argwhere(vehTrack[:, 0] == t).item() + self.t_f + 1)\n\t\tfut = vehTrack[stpt:enpt:self.d_s,1:3]-refPos\n\t\treturn fut\n\n\n\n\t## Collate function for dataloader\n\tdef collate_fn(self, samples):\n\n\t\t# Initialize neighbors and neighbors length batches:\n\t\tnbr_batch_size = 0\n\t\tfor _,_,nbrs,_,_,_ in samples:\n\t\t\tnbr_batch_size += sum([len(nbrs[i])!=0 for i in range(len(nbrs))])\n\n\t\tmaxlen = self.t_h//self.d_s + 1\n\t\tnbrs_batch = torch.zeros(maxlen,nbr_batch_size,2 + self.newFeats)\n\n\t\t# Initialize social mask batch:\n\t\tpos = [0, 0]\n\t\tmask_batch = torch.zeros(len(samples), self.grid_size[1],self.grid_size[0],self.enc_size)\n\t\tmask_batch = mask_batch.byte()\n\n\n\t\t# Initialize history, history lengths, future, output mask, lateral maneuver and longitudinal maneuver batches:\n\t\thist_batch = torch.zeros(maxlen,len(samples),2 + self.newFeats)\n\t\tfut_batch = torch.zeros(self.t_f//self.d_s,len(samples),2)\n\t\top_mask_batch = torch.zeros(self.t_f//self.d_s,len(samples),2)\n\t\tlat_enc_batch = torch.zeros(len(samples),3)\n\t\tlon_enc_batch = torch.zeros(len(samples), 2)\n\t\thist_grid_batch = torch.zeros(len(samples), self.Tx, self.grid_size[0], self.grid_size[1])\n\n\n\t\tcount = 0\n\t\tfor sampleId,(hist, fut, nbrs, lat_enc, lon_enc, hist_grid) in enumerate(samples):\n\n\t\t\t# Set up history, future, lateral maneuver and longitudinal maneuver batches:\n\t\t\t#hist_batch[0:len(hist),sampleId,0] = torch.from_numpy(hist[:, 0])\n\t\t\t#hist_batch[0:len(hist), sampleId, 1] = torch.from_numpy(hist[:, 1])\n\t\t\tfor feat in range(2 + self.newFeats):\n\t\t\t\thist_batch[0:len(hist),sampleId, feat] = torch.from_numpy(hist[:, feat])\n\n\t\t\tfut_batch[0:len(fut), sampleId, 0] = torch.from_numpy(fut[:, 0])\n\t\t\tfut_batch[0:len(fut), sampleId, 1] = torch.from_numpy(fut[:, 1])\n\t\t\top_mask_batch[0:len(fut),sampleId,:] = 1\n\n\t\t\tlat_enc_batch[sampleId,:] = torch.from_numpy(lat_enc)\n\t\t\tlon_enc_batch[sampleId, :] = torch.from_numpy(lon_enc)\n\n\t\t\thist_grid_batch[sampleId, :, :, :] = torch.from_numpy(hist_grid)\n\n\t\t\t# Set up neighbor, neighbor sequence length, and mask batches:\n\t\t\tfor id,nbr in enumerate(nbrs):\n\t\t\t\tif len(nbr)!=0:\n\t\t\t\t\t#nbrs_batch[0:len(nbr),count,0] = torch.from_numpy(nbr[:, 0])\n\t\t\t\t\t#nbrs_batch[0:len(nbr), count, 1] = torch.from_numpy(nbr[:, 1])\n\t\t\t\t\tfor feat in range(2 + self.newFeats):\n\t\t\t\t\t\tnbrs_batch[0:len(nbr),count, feat] = torch.from_numpy(nbr[:, feat])\n\n\t\t\t\t\tpos[0] = id % self.grid_size[0]\n\t\t\t\t\tpos[1] = id // self.grid_size[0]\n\t\t\t\t\tmask_batch[sampleId,pos[1],pos[0],:] = torch.ones(self.enc_size).byte()\n\t\t\t\t\tcount+=1\n\n\t\t#print(\"DBG:\", count, \", \", nbr_batch_size)\n\n\t\t# Example with batch_size=128 grid=(13, 3) and encoding of every traj history of 3 secs of (X,Y)rel into 64 features\n\t\t# out of RNN-LSTM h_n output\n\t\t# ------------------------------------------------------------------------------------\n\t\t# Usage of masks [128, 3, 13, 64] and nbrs_enc [850, 64] in model.py soc_enc is tricky\n\t\t# ------------------------------------------------------------------------------------\n\t\t# We must tag e.g. 850 times 64 ones in [128, 3, 13, 64] to retrieve the LSTM encoding of 850 neighbors history of 3 sec ...\n\t\t# with 850 == count == nbr_batch_size\n\t\t# 850/128 => here in this batch, on average 6.6 cars in the (13,3) grid\n\t\tassert count==nbr_batch_size, \"Otherwise in model.py soc_enc.masked_scatter_(masks, nbrs_enc) WILL NOT MATCH !!!\" \n\n\t\treturn hist_batch, nbrs_batch, mask_batch, lat_enc_batch, lon_enc_batch, fut_batch, op_mask_batch, hist_grid_batch\n\n#________________________________________________________________________________________________________________________________________\n\n\n\n\n\n## Custom activation for output layer (Graves, 2015)\ndef outputActivation(x):\n\tmuX = x[:,:,0:1]\n\tmuY = x[:,:,1:2]\n\tsigX = x[:,:,2:3]\n\tsigY = x[:,:,3:4]\n\trho = x[:,:,4:5]\n\tsigX = torch.exp(sigX)\n\tsigY = torch.exp(sigY)\n\trho = torch.tanh(rho)\n\tout = torch.cat([muX, muY, sigX, sigY, rho],dim=2)\n\treturn out\n\n## Batchwise NLL loss, uses mask for variable output lengths\ndef maskedNLL(y_pred, y_gt, mask):\n\tacc = torch.zeros_like(mask)\n\tmuX = y_pred[:,:,0]\n\tmuY = y_pred[:,:,1]\n\tsigX = y_pred[:,:,2]\n\tsigY = y_pred[:,:,3]\n\trho = y_pred[:,:,4]\n\tohr = torch.pow(1-torch.pow(rho,2),-0.5)\n\tx = y_gt[:,:, 0]\n\ty = y_gt[:,:, 1]\n\tout = torch.pow(ohr, 2)*(torch.pow(sigX, 2)*torch.pow(x-muX, 2) + torch.pow(sigY, 2)*torch.pow(y-muY, 2) - 2*rho*torch.pow(sigX, 1)*torch.pow(sigY, 1)*(x-muX)*(y-muY)) - torch.log(sigX*sigY*ohr)\n\tacc[:,:,0] = out\n\tacc[:,:,1] = out\n\tacc = acc*mask\n\tlossVal = torch.sum(acc)/torch.sum(mask)\n\treturn lossVal\n\n## NLL for sequence, outputs sequence of NLL values for each time-step, uses mask for variable output lengths, used for evaluation\ndef maskedNLLTest(fut_pred, lat_pred, lon_pred, fut, op_mask, num_lat_classes=3, num_lon_classes = 2,use_maneuvers = True, avg_along_time = False):\n\tif use_maneuvers:\n\t\tacc = torch.zeros(op_mask.shape[0],op_mask.shape[1],num_lon_classes*num_lat_classes).cuda()\n\t\tcount = 0\n\t\tfor k in range(num_lon_classes):\n\t\t\tfor l in range(num_lat_classes):\n\t\t\t\twts = lat_pred[:,l]*lon_pred[:,k]\n\t\t\t\twts = wts.repeat(len(fut_pred[0]),1)\n\t\t\t\ty_pred = fut_pred[k*num_lat_classes + l]\n\t\t\t\ty_gt = fut\n\t\t\t\tmuX = y_pred[:, :, 0]\n\t\t\t\tmuY = y_pred[:, :, 1]\n\t\t\t\tsigX = y_pred[:, :, 2]\n\t\t\t\tsigY = y_pred[:, :, 3]\n\t\t\t\trho = y_pred[:, :, 4]\n\t\t\t\tohr = torch.pow(1 - torch.pow(rho, 2), -0.5)\n\t\t\t\tx = y_gt[:, :, 0]\n\t\t\t\ty = y_gt[:, :, 1]\n\t\t\t\tout = -(torch.pow(ohr, 2) * (torch.pow(sigX, 2) * torch.pow(x - muX, 2) + torch.pow(sigY, 2) * torch.pow(y - muY,2) - 2 * rho * torch.pow(sigX, 1) * torch.pow(sigY, 1) * (x - muX) * (y - muY)) - torch.log(sigX * sigY * ohr))\n\t\t\t\tacc[:, :, count] =\tout + torch.log(wts)\n\t\t\t\tcount+=1\n\t\tacc = -logsumexp(acc,dim = 2)\n\t\tacc = acc * op_mask[:,:,0]\n\t\tif avg_along_time:\n\t\t\tlossVal = torch.sum(acc) / torch.sum(op_mask[:, :, 0])\n\t\t\treturn lossVal\n\t\telse:\n\t\t\tlossVal = torch.sum(acc,dim=1)\n\t\t\tcounts = torch.sum(op_mask[:,:,0],dim=1)\n\t\t\treturn lossVal,counts\n\telse:\n\t\tacc = torch.zeros(op_mask.shape[0], op_mask.shape[1], 1).cuda()\n\t\ty_pred = fut_pred\n\t\ty_gt = fut\n\t\tmuX = y_pred[:, :, 0]\n\t\tmuY = y_pred[:, :, 1]\n\t\tsigX = y_pred[:, :, 2]\n\t\tsigY = y_pred[:, :, 3]\n\t\trho = y_pred[:, :, 4]\n\t\tohr = torch.pow(1 - torch.pow(rho, 2), -0.5)\n\t\tx = y_gt[:, :, 0]\n\t\ty = y_gt[:, :, 1]\n\t\tout = torch.pow(ohr, 2) * (\n\t\ttorch.pow(sigX, 2) * torch.pow(x - muX, 2) + torch.pow(sigY, 2) * torch.pow(y - muY, 2) - 2 * rho * torch.pow(\n\t\t\tsigX, 1) * torch.pow(sigY, 1) * (x - muX) * (y - muY)) - torch.log(sigX * sigY * ohr)\n\t\tacc[:, :, 0] = out\n\t\tacc = acc * op_mask[:, :, 0:1]\n\t\tif avg_along_time:\n\t\t\tlossVal = torch.sum(acc[:, :, 0]) / torch.sum(op_mask[:, :, 0])\n\t\t\treturn lossVal\n\t\telse:\n\t\t\tlossVal = torch.sum(acc[:,:,0], dim=1)\n\t\t\tcounts = torch.sum(op_mask[:, :, 0], dim=1)\n\t\t\treturn lossVal,counts\n\n## Batchwise MSE loss, uses mask for variable output lengths\ndef maskedMSE(y_pred, y_gt, mask):\n\tacc = torch.zeros_like(mask)\n\tmuX = y_pred[:,:,0]\n\tmuY = y_pred[:,:,1]\n\tx = y_gt[:,:, 0]\n\ty = y_gt[:,:, 1]\n\tout = torch.pow(x-muX, 2) + torch.pow(y-muY, 2)\n\tacc[:,:,0] = out\n\tacc[:,:,1] = out\n\tacc = acc*mask\n\tlossVal = torch.sum(acc)/torch.sum(mask)\n\treturn lossVal\n\n## MSE loss for complete sequence, outputs a sequence of MSE values, uses mask for variable output lengths, used for evaluation\ndef maskedMSETest(y_pred, y_gt, mask):\n\tacc = torch.zeros_like(mask)\n\tmuX = y_pred[:, :, 0]\n\tmuY = y_pred[:, :, 1]\n\tx = y_gt[:, :, 0]\n\ty = y_gt[:, :, 1]\n\tout = torch.pow(x - muX, 2) + torch.pow(y - muY, 2)\n\tacc[:, :, 0] = out\n\tacc[:, :, 1] = out\n\tacc = acc * mask\n\tlossVal = torch.sum(acc[:,:,0],dim=1)\n\tcounts = torch.sum(mask[:,:,0],dim=1)\n\treturn lossVal, counts\n\n## Quantify and catch out Big Errors (+ or - 3 stddev)\ndef maskedBIGERRTest(y_pred, y_gt, mask):\n\tacc = torch.zeros_like(mask)\n\tmuX = y_pred[:,:, 0]\n\tmuY = y_pred[:,:, 1]\n\t# ACHTUNG !!! what is called sigX/sigY is the inverse in the code\n\tsigX = 1/y_pred[:,:, 2]\n\tsigY = 1/y_pred[:,:, 3]\n\n\t# sigX typically between 0 (at 0+ sec) and 2 feets (at 5 sec)\n\t# sigY typically between 0 (at 0+ sec) and 15 feets (at 5 sec)\n\n\t# n=1 in between 20% and 33%\n\t# n=2 arround 6%\n\t# n=3 arround 2%\n\n\tn=3\n\tminX = muX - n*sigX\n\tmaxX = muX + n*sigX\n\tminY = muY - n*sigY\n\tmaxY = muY + n*sigY\n\n\tx = y_gt[:,:, 0]\n\ty = y_gt[:,:, 1]\n\n\terrX = (x < minX) + (x > maxX)\n\terrY = (y < minY) + (y > maxY)\n\tout = ((errX + errY) > 0) # [Ty, Batch] array of 0 or 1\n\n\tacc[:, :, 0] = out\n\tacc[:, :, 1] = out\n\tacc = acc * mask\n\tlossVal = torch.sum(acc[:,:,0],dim=1)\n\tcounts = torch.sum(mask[:,:,0],dim=1)\n\treturn lossVal, counts\n\n## Helper function for log sum exp calculation:\ndef logsumexp(inputs, dim=None, keepdim=False):\n\tif dim is None:\n\t\tinputs = inputs.view(-1)\n\t\tdim = 0\n\ts, _ = torch.max(inputs, dim=dim, keepdim=True)\n\toutputs = s + (inputs - s).exp().sum(dim=dim, keepdim=True).log()\n\tif not keepdim:\n\t\toutputs = outputs.squeeze(dim)\n\treturn outputs\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"316886883","text":"import numpy as np\nfrom itertools import tee\nfrom sklearn import cross_validation\nfrom scipy.stats import norm\nfrom keras.layers import Input, LSTM, RepeatVector, Flatten, Dense\nfrom keras.layers.merge import concatenate\nfrom keras.models import Model\nfrom keras import backend as K\n\n\nfrom utils import parser, image, embedding_plotter, recorder, option_visualizer\n\n\nNAME = 'Option_LSTM'\nUSE_GRU = False\nif USE_GRU:\n\tfrom keras.layers import GRU\n\n\nclass Option_LSTM:\n\n\tdef __init__(self, args):\n\t\tself.autoencoder = None\n\t\tself.encoder = None\n\t\t# self.decoder = None\n\n\t\tself.epochs = args['epochs']\n\t\tself.batch_size = args['batch_size']\n\t\tself.periods = args['periods'] if 'periods' in args else 15\n\t\tself.cv_splits = args['cv_splits'] if 'cv_splits' in args else 0.2\n\n\t\tself.timesteps = args['timesteps'] if 'timesteps' in args else 5\n\t\tself.input_dim = args['input_dim']\n\t\tself.output_dim = args['output_dim']\n\t\tself.latent_dim = args['latent_dim'] if 'latent_dim' in args else (args['input_dim']+args['output_dim'])/2\n\t\tself.option_dim = args['option_dim'] if 'option_dim' in args else 10\n\t\tself.trained = args['mode'] == 'sample' if 'mode' in args else False\n\t\tself.load_path = args['load_path']\n\t\tself.log_path = args['log_path']\n\t\tself.out_dim = self.output_dim*self.timesteps\n\t\tself.alpha = 10\n\n\t\tself.history = recorder.LossHistory()\n\n\tdef make_model(self):\t\n\t\tinputs = Input(shape=(self.timesteps, self.input_dim))\n\t\tencoded = None\n\t\tif USE_GRU:\n\t\t\tencoded = GRU(self.latent_dim)(inputs)\n\t\telse:\n\t\t\tencoded = LSTM(self.latent_dim)(inputs)\n\n\t\toptioned = RepeatVector(self.option_dim)(encoded)\n\t\toptioned = Flatten()(optioned)\n\t\t\n\t\tdecoded = RepeatVector(self.timesteps)(optioned)\n\t\tif USE_GRU:\n\t\t\tdecoded = GRU(self.output_dim*self.option_dim, return_sequences=True)(decoded)\n\t\telse:\n\t\t\tdecoded = LSTM(self.output_dim*self.option_dim, return_sequences=True)(decoded)\n\t\tdecoded = Reshape((self.option_dim, self.out_dim))(decoded)\n\n\t\tself.encoder = Model(inputs, encoded)\n\t\tself.autoencoder = Model(inputs, merged)\n\t\t\n\t\tdef min_loss(y_true, y_pred):\n\t\t\tx = np.linspace(norm.ppf(0.01),norm.ppf(0.99), self.option_dim)\n\t\t\tpx = norm().pdf(x)\n\t\t\try_true = K.tile(y_true, (1, self.option_dim))\n\t\t\try_true = K.reshape(ry_true, [-1, self.option_dim, self.out_dim])\n\t\t\tsum_sqr_ = K.sum(K.square(y_pred - ry_true), axis=2)\n\t\t\tmin_ = K.min(sum_sqr_, axis=1)\n\t\t\tclass_loss = K.dot(px, K.transpose(sum_sqr_))\n\t\t\treturn self.alpha*min_ + class_loss\n\n\t\tself.autoencoder.compile(optimizer='RMSprop', loss=min_loss)\n\n\t\tself.autoencoder.summary()\n\t\tself.encoder.summary()\n\n\tdef _match(self, y_true, y_pred):\n\t\tclass_vector = y_pred[:, -self.option_dim:]\n\t\tprediction = y_pred[:, :-self.option_dim]\n\t\try_pred = np.reshape(prediction, [-1, self.option_dim, self.out_dim])\n\t\try_true = np.tile(y_true, (1,self.option_dim))\n\t\try_true = np.reshape(ry_true, [-1, self.option_dim, self.out_dim])\n\t\tmin_loss_idx = np.argmin(np.sum(np.square(ry_pred - ry_true), axis=2), axis=1)\n\t\treturn min_loss_idx, np.reshape(ry_pred[:,min_loss_idx], [-1, self.timesteps, self.output_dim])\n\n\tdef best(self, y_true, y_pred):\n\t\treturn self._match(y_true, y_pred)[1]\n\n\tdef best_option(self, y_true, y_pred):\n\t\treturn self._match(y_true, y_pred)[0]\n\n\tdef run(self, data_iterator): \n\t\tself.make_model()\n\t\tmodel_vars = [NAME, self.latent_dim, self.timesteps, self.batch_size, self.option_dim]\n\n\t\tif self.trained:\n\t\t\tself.autoencoder.load_weights(self.load_path)\n\t\telse:\n\t\t\titer1, iter2 = tee(data_iterator)\n\t\t\tfor i in range(self.periods):\n\t\t\t\tfor x, y in iter1:\n\t\t\t\t\tx_train, x_test, y_train, y_test = cross_validation.train_test_split(x, y, test_size=self.cv_splits)\n\t\t\t\t\ty_train = np.reshape(y_train, (-1, self.out_dim))\n\t\t\t\t\ty_test = np.reshape(y_test, (-1, self.out_dim))\n\t\t\t\t\tself.autoencoder.fit(x_train, y_train,\n\t\t\t\t\t\t\t\tshuffle=True,\n\t\t\t\t\t\t\t\tepochs=self.epochs,\n\t\t\t\t\t\t\t\tbatch_size=self.batch_size,\n\t\t\t\t\t\t\t\tvalidation_data=(x_test, y_test),\n\t\t\t\t\t\t\t\tcallbacks=[self.history])\n\n\t\t\t\t\ty_test_decoded = self.autoencoder.predict(x_test[:1])\n\t\t\t\t\ty_test_sample = np.reshape(y_test[:1], (-1, self.timesteps, self.output_dim))\n\t\t\t\t\t# y_test_decoded = self.autoencoder.predict(x_test[:2])\n\t\t\t\t\t# y_test_sample = np.reshape(y_test[:2], (-1, self.timesteps, self.output_dim))\n\t\t\t\t\t# image.plot_batch_2D(y_test_sample, self.best(y_test[:1], y_test_decoded))\n\n\t\t\t\t\tclass_vector = y_test_decoded[:, -self.option_dim:]\n\t\t\t\t\tprediction = np.reshape(y_test_decoded[:, :-self.option_dim], [-1, self.option_dim, self.timesteps, self.output_dim])\n\t\t\t\t\tbest_opt = self.best_option(y_test[:1], y_test_decoded)\n\t\t\t\t\tpredict_best_opt = np.argmax(class_vector, axis=1)\n\t\t\t\t\timage.plot_batch_2D(x_test[:1], y_test_sample, prediction, best_opt, predict_best_opt)\n\n\t\t\t\t\t# image.plot_graph(x_test[:2], y_test_sample, prediction, best_opt, predict_best_opt)\n\t\t\t\t\n\t\t\t\t# self.autoencoder.save_weights(self.load_path, overwrite=True)\n\t\t\t\titer1, iter2 = tee(iter2)\n\n\t\t\t# data_iterator = iter2\n\t\t\t# self.history.record(self.log_path, model_vars)\n\n\t\t# iter1, iter2 = tee(data_iterator)\n\t\t# embedding_plotter.see_embedding(self.encoder, iter1, model_vars)\n\n\t\t# for x,y in iter2:\n\t\t# \trandom_idx = np.random.choice(len(x))\n\t\t# \tprint x[random_idx:random_idx+1]\n\t\t# \ty_test_decoded = self.autoencoder.predict(x[random_idx:random_idx+1])\n\t\t# \ty_test_decoded = np.reshape(y_test_decoded, [-1, self.option_dim, self.timesteps, self.output_dim])\n\t\t# \timage.plot_options(y[random_idx:random_idx+1], y_test_decoded)\n\n\t\t# for x, y in iter2:\n\t\t# \ty_decoded = self.autoencoder.predict(x)\n\t\t# \ty_encoded = self.encoder.predict(x)\n\t\t# \topt = self.best_option(y, y_decoded).flatten()\n\t\t# \toption_visualizer.visualize(y, y_encoded, y_decoded, opt)\n\nif __name__ == '__main__':\n\tdata_iterator, config = parser.get_parse(NAME)\n\tae = Option_LSTM(config)\n\tae.run(data_iterator)\n","sub_path":"RNN/Option_Norm_LSTM.py","file_name":"Option_Norm_LSTM.py","file_ext":"py","file_size_in_byte":5789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"560482808","text":"import os\nfrom PIL import Image\n\npath = \"./resources/training_data/\"\n\nfor filename in os.listdir(path):\n im = Image.open(os.path.join(path, filename))\n width, height = im.size\n if (width, height) != (56, 56):\n w_ratio = 56 / width\n h_ratio = 56 / height\n im = im.resize((int(width * w_ratio), int(height * h_ratio)))\n im.save(os.path.join(path, filename))\n","sub_path":"scale_up_images.py","file_name":"scale_up_images.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"635117775","text":"from Crypto.Cipher import AES\nfrom Crypto.Util.Padding import pad\nfrom pwn import *\n\nADDRESS = \"localhost\"\nPORT = 12342\n\nq = remote(ADDRESS, PORT)\nciphertext = q.recv(1024)\n\nold_block = pad(b'admin=0',AES.block_size)\nprint(old_block)\nnew_block = pad(b'admin=1',AES.block_size)\nprint(new_block)\ndelta = bytes(a ^ b for (a, b) in zip(old_block,new_block))\nprint(delta)\n\nprint(len(ciphertext))\nciphertext_array = bytearray(ciphertext)\nfor i in range(0,16):\n ciphertext_array[i]^=delta[i]\n\nq.send(ciphertext_array)\ny = q.recv(1024).decode('utf-8')\nprint(y)\nq.close()\n\n\n","sub_path":"AY1920/attacks/bit_flipping/bf_client.py","file_name":"bf_client.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"124031893","text":"import sqlite3\n\ndef connect():\n conn=sqlite3.connect(\"books.db\")\n cur=conn.cursor()\n cur.execute(\"CREATE TABLE IF NOT EXISTS book_data(id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)\")\n conn.commit()\n conn.close()\n\n\ndef insert(title, author, year, isbn):\n conn=sqlite3.connect(\"books.db\")\n cur=conn.cursor()\n cur.execute(\"INSERT INTO book_data VALUES(NULL, ?,?,?,?)\",(title, author, year, isbn))\n conn.commit()\n conn.close()\n\ndef view():\n conn=sqlite3.connect(\"books.db\")\n cur=conn.cursor()\n cur.execute(\"SELECT * FROM book_data\")\n rows=cur.fetchall()\n conn.close()\n return rows\n\ndef search(title=\"\", author=\"\", year=\"\", isbn=\"\"):\n conn=sqlite3.connect(\"books.db\")\n cur=conn.cursor()\n cur.execute(\"SELECT * FROM book_data WHERE title=? OR author=? OR year=? OR isbn=?\", (title, author, year, isbn))\n rows=cur.fetchall()\n conn.close()\n return rows\n\ndef delete(id):\n conn=sqlite3.connect(\"books.db\")\n cur=conn.cursor()\n cur.execute(\"DELETE FROM book_data WHERE id=?\",(id,))\n conn.commit()\n conn.close()\n\n\ndef update(id, title, author, year, isbn):\n conn=sqlite3.connect(\"books.db\")\n cur=conn.cursor()\n cur.execute(\"UPDATE book_data SET title=?, author=?, year=?, isbn=? WHERE id=?\", (title, author, year, isbn, id))\n conn.commit()\n conn.close()\n\nconnect()\n\n#insert(\"The Sky\", \"Henrik Gustaf\", \"2023\", \"153522\")\n#update(2, \"Grass\", \"ziele\", \"222444\", \"3244222\")\n#delete(10)\n#print(view())\n#print(search(author=\"B.J. George\"))\n","sub_path":"back_end.py","file_name":"back_end.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"163309799","text":"import numpy as np\nimport tempfile\n\nfrom typing import List\n\nfrom dnnv import logging\nfrom dnnv.nn import OperationGraph\nfrom dnnv.properties import Expression\nfrom dnnv.verifiers.common import (\n SAT,\n UNSAT,\n UNKNOWN,\n CommandLineExecutor,\n HalfspacePolytope,\n HalfspacePolytopePropertyExtractor,\n HyperRectangle,\n Property,\n as_layers,\n)\n\nfrom .errors import ReluplexError, ReluplexTranslatorError\nfrom .utils import to_nnet_file\n\n\ndef parse_results(stdout: List[str], stderr: List[str]):\n for line in stdout:\n if line.startswith(\"Solution found!\"):\n return SAT\n elif line.startswith(\"Can't solve!\"):\n return UNSAT\n raise ReluplexError(f\"No verification result found\")\n\n\ndef validate_counter_example(prop: Property, stdout: List[str], stderr: List[str]):\n shape, dtype = prop.op_graph.input_details[0]\n cex = np.zeros(np.product(shape), dtype)\n found = False\n for line in stdout:\n if found and line.startswith(\"input\"):\n index = int(line.split(\"]\", maxsplit=1)[0].split(\"[\")[-1])\n cex[index] = float(line.split()[-1][:-1])\n if line.startswith(\"Solution found!\"):\n found = True\n cex = cex.reshape(shape)\n if not prop.input_constraint.validate(cex):\n raise ReluplexError(\"Invalid counter example found: input outside bounds.\")\n output = prop.op_graph(cex)\n if not prop.output_constraint.validate(output):\n raise ReluplexError(\"Invalid counter example found: output outside bounds.\")\n\n\ndef verify(dnn: OperationGraph, phi: Expression):\n logger = logging.getLogger(__name__)\n dnn = dnn.simplify()\n phi.networks[0].concretize(dnn)\n\n result = UNSAT\n property_extractor = HalfspacePolytopePropertyExtractor(\n HyperRectangle, HalfspacePolytope\n )\n with tempfile.TemporaryDirectory() as dirname:\n for prop in property_extractor.extract_from(~phi):\n if prop.input_constraint.num_variables > 1:\n raise ReluplexTranslatorError(\n \"Unsupported network: More than 1 input variable\"\n )\n layers = as_layers(\n prop.suffixed_op_graph(), translator_error=ReluplexTranslatorError,\n )\n nnet_file_name = to_nnet_file(\n prop.input_constraint,\n layers,\n dirname=dirname,\n translator_error=ReluplexTranslatorError,\n )\n logger.debug(\"Running reluplex\")\n executor = CommandLineExecutor(\n \"reluplex\", f\"{nnet_file_name}\", verifier_error=ReluplexError\n )\n out, err = executor.run()\n logger.debug(\"Parsing results\")\n result |= parse_results(out, err)\n if result == SAT:\n logger.debug(\"SAT! Validating counter example.\")\n validate_counter_example(prop, out, err)\n if result == SAT or result == UNKNOWN:\n return result\n\n return result\n","sub_path":"dnnv/verifiers/reluplex/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"119938964","text":"'''\n DBscan algorithm as per the assginment in BT3041\n\n'''\n\nimport pickle, random\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef Dbscan(D, eps, minpts): \n '''\n D = data set\n eps = epsilon radius\n minpts = minpts in an area\n '''\n labels = [0]*D.shape[0]\n\n C = 0\n\n # check for neighbouring pts and grow cluster or identify noise point\n for p in range(len(D)):\n if labels[p] == 0:\n Neighbour_pts = check(D,p,eps)\n\n if len(Neighbour_pts) < minpts:\n labels[p] = -1 # identify noise point\n \n else:\n C += 1\n labels = update_cluster(D, labels, p, Neighbour_pts, C, eps, minpts)\n\n return labels\n\ndef check(D,p,eps):\n # check for the neighbours of a given p point and return the index of the point in the actual data\n neighbors_ind = []\n\n for k in range(len(D)):\n if np.linalg.norm(D[p]-D[k]) < eps :\n neighbors_ind.append(k)\n\n return neighbors_ind\n\n\ndef update_cluster(D, labels, p, Neighbour_pts, C, eps, minpts):\n # grow the cluster using dbscan algorithm\n labels[p] = C\n\n i = 0\n while i < len(Neighbour_pts):\n k = Neighbour_pts[i]\n\n if labels[k] == -1:\n labels[k] = C\n\n elif labels[k]==0:\n labels[k] = C\n\n k_neighbors = check(D,k,eps)\n \n if len(k_neighbors) >= minpts:\n Neighbour_pts = Neighbour_pts + k_neighbors\n \n i+=1\n return labels\n\n# upload data\nwith open(\"dbscan2000.pkl\", \"rb\") as f:\n d = pickle.load(f)\n f.close()\n\nclusters = Dbscan(d, 0.2, 20) \n# print(clusters)\nseg_pts = [] # list of all the segregated points\n\n# training and plotting\nfor j in range(1, max(clusters)+1):\n cluster_pts = []\n rgb = (random.random(), random.random(), random.random())\n for jj in range(len(clusters)):\n if clusters[jj] == j:\n cluster_pts.append(d[jj,:])\n plt.scatter(d[jj,0], d[jj,1], c=[rgb])\n seg_pts.append(cluster_pts)\n\nprint(len(seg_pts))\nplt.show()\n# plt.scatter()\n","sub_path":"dbscan_1.py","file_name":"dbscan_1.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"175799672","text":"\nglobal A\nglobal B\nA = 5\nB = 3\nglobal SIZE\nSIZE = 1000\n\nSum = 0\nfor i in range(1000):\n if ((i % A) == 0) or ((i % B) == 0):\n Sum += i\n\nprint(Sum)\n","sub_path":"projectEuler/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"619902201","text":"from wxpy import *\nimport time\nimport random\n\n# 新建机器人\nbot = Bot(cache_path = True)\n\n# 获取所有好友\n# all_friends = bot.friends()\n# print('👨👨👨 你目前的好友数:{}\\n'.format(len(all_friends)))\n\n# while循环\nwhile True:\n\n # 提示输入群名\n groupName = input('你想要给哪个群的好友加备注(按t退出):')\n\n # 输入t直接退出\n if groupName == 't':\n print('您的微信成功登出了本程序。')\n break\n \n # 进入下一步\n else:\n\n # 提示正在寻找该群\n print('\\n🔍🔍🔍 正在寻找包含 {} 的群!\\n'.format(groupName))\n\n # 找到指定的微信群组\n groups = bot.groups().search(groupName)\n\n # 通过群组长度判断是找到0/1个群/多个群\n lens = len(groups)\n print('✅✅✅ 找到指定群的数目是:{}'.format(lens))\n\n if lens != 1:\n print('⚠️️️️️⚠️⚠️ 请输入仅可找到1个群的关键词!')\n print('\\n')\n continue\n else:\n\n # 找到1个群\n group = groups[0]\n\n # 群成员数量\n nums = len(group)\n\n # 提示找到了该群\n print('✅✅✅ 已定位到 {} !'.format(group.name))\n print('👨👨👨 该群有 {} 个群成员!'.format(nums))\n\n # 改备注\n # count = 0\n # for friend in all_friends:\n # if friend in group:\n # remarkName = friend.name\n # if '魔王课' not in remarkName:\n # friend.set_remark_name(remarkName + ' 魔王课')\n # count = count + 1\n # print('正修改 -- {} -- 的备注名'.format(remarkName))\n # print('✅✅✅ 已成功修改 {} 位好友的备注!'.format(count))\n # sleeptime = random.randint(50, 70)\n # print('⌚️️️��️️⌚️⌚️ 睡眠{}秒后修改下一个好友备注!'.format(sleeptime))\n # time.sleep(sleeptime)\n\n # 该群中,多少人是你的好友 \n count_myfriend = 0\n count_rename = 0\n for member in group:\n if member.is_friend:\n count_myfriend = count_myfriend + 1\n nickName = member.nick_name\n if '魔王课' in nickName:\n count_rename = count_rename + 1\n\n print('👩👩👩 该群中,{}人是你的好友'.format(count_myfriend))\n print('👩👩👩 未改备注的好友数目是:{}\\n'.format(count_myfriend - count_rename))\n\n while True:\n # 提示输入备注名\n tag = input('🤔🤔🤔 你想要给这个群的好友加什么备注:')\n print('\"{}\" 的备注会添加在好友微信名后,以空格隔开!\\n'.format(tag))\n\n # 再次确认备注名\n iftag = input('🤔🤔🤔 按1确认添加改备注,其他键重新设置备注名!')\n if iftag == '1':\n break\n else:\n continue\n\n print('🐶🐶🐶 将在10秒后添加备注\" {}\"!\\n'.format(tag))\n time.sleep(10)\n\n # 改备注\n count = 0\n for member in group:\n if member.is_friend:\n remarkName = member.nick_name\n if tag not in remarkName:\n member.set_remark_name(remarkName + ' ' + tag)\n count = count + 1\n print('正修改 \"{}\" 的备注名'.format(remarkName))\n print('✅✅✅ 已成功修改 {} 位好友的备注!'.format(count))\n sleeptime = random.randint(50, 70)\n print('⌚️️️️️️⌚️⌚️ 睡眠{}秒后修改下一个好友备注!'.format(sleeptime))\n time.sleep(sleeptime)\n\n print('🎉🎉🎉 修改成功/全部好友都已加备注,无需修改!\\n')\n\n # 是否继续改备注\n goon = input('按1继续;按其他键退出:')\n\n if goon == '1':\n continue\n else:\n break\n# 退出微信\nbot.logout()\n\n\n","sub_path":"wxRemarkName.py","file_name":"wxRemarkName.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"560636615","text":"from django.shortcuts import render,redirect\r\nfrom django.contrib.auth.forms import UserCreationForm, AuthenticationForm\r\nfrom django.contrib import messages\r\nfrom django.http import HttpResponse\r\nfrom django.contrib.auth import authenticate,login as authorize,logout as deauth\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport json\r\nimport twint\r\nimport nest_asyncio\r\nfrom django.http import JsonResponse\r\nfrom django.http import HttpResponse\r\nfrom django.db import models\r\n# from django_countries.fields import CountryField\r\nimport subprocess \r\nimport asyncio\r\n\r\n\r\ndef Login(request):\r\n form = AuthenticationForm()\r\n if(request.method == 'POST'):\r\n form = AuthenticationForm()\r\n username=request.POST['username']\r\n password=request.POST['password']\r\n user =authenticate(username=username,password=password);\r\n if user is None:\r\n messages.add_message(request,messages.INFO,'Username or Password is not valid ')\r\n return redirect('/')\r\n else:\r\n authorize(request,user)\r\n return redirect('/app/dashboard')\r\n \r\n else:\r\n if(request.user.is_authenticated):\r\n return redirect('/app/dashboard')\r\n form = AuthenticationForm()\r\n \r\n return render(request, 'Auth_App/Login.html', {'title': 'Login', 'form': form})\r\n\r\n\r\ndef register(request):\r\n form = UserCreationForm()\r\n if request.method == 'POST':\r\n form = UserCreationForm(request.POST)\r\n if form.is_valid():\r\n form.save()\r\n messages.add_message(request,messages.SUCCESS,'User successfully registered')\r\n return redirect('/')\r\n return render(request, 'auth/register.html', {'title': 'Registration', 'form': form})\r\n\r\n\r\ndef home(request):\r\n if(request.user.is_authenticated):\r\n trends=twitterTrends()\r\n world_trends=twitterTrendsWorldwide()\r\n return render(request,'home.html',{'trends':trends,'world_trends':world_trends})\r\n return redirect('/')\r\n\r\ndef logout(request):\r\n if(request.user.is_authenticated):\r\n \r\n deauth(request)\r\n messages.add_message(request,messages.SUCCESS,'User has been successfully logged out ')\r\n else:\r\n messages.add_message(request,messages.INFO,'Login first')\r\n return redirect('/')\r\n \r\n \r\n \r\n \r\ndef twitterTrends():\r\n url='https://trends24.in/pakistan/';\r\n page = requests.get(url);\r\n status_code=page.status_code;\r\n dic={};\r\n hashtag_name=[];\r\n hashtag_href=[];\r\n hashtag_count=[];\r\n if(status_code==200):\r\n data=BeautifulSoup(page.text,'lxml')\r\n new=data.find('ol',class_=\"trend-card__list\");\r\n li=data.find_all('li')\r\n for i in li:\r\n hashtag_name.append(i.a.text)\r\n hashtag_href.append(i.a.attrs['href'])\r\n if(i.find('span')):\r\n hashtag_count.append(i.span.text)\r\n else:\r\n hashtag_count.append(\"count unavalible\")\r\n \r\n \r\n \r\n dic = []\r\n for item in zip(hashtag_name, hashtag_count, hashtag_href):\r\n \r\n dic.append({\r\n 'name':item[0],\r\n 'count':item[1],\r\n 'href':item[2]})\r\n \r\n return dic\r\n\r\n\r\ndef twitterTrendsByCountry(request):\r\n country=request.GET['country'];\r\n url='https://trends24.in/'+country;\r\n page = requests.get(url);\r\n status_code=page.status_code;\r\n dic={};\r\n hashtag_name=[];\r\n hashtag_href=[];\r\n hashtag_count=[];\r\n if(status_code==200):\r\n data=BeautifulSoup(page.text,'lxml')\r\n new=data.find('ol',class_=\"trend-card__list\");\r\n li=data.find_all('li')\r\n for i in li:\r\n hashtag_name.append(i.a.text)\r\n hashtag_href.append(i.a.attrs['href'])\r\n if(i.find('span')):\r\n hashtag_count.append(i.span.text)\r\n else:\r\n hashtag_count.append(\"count unavalible\")\r\n \r\n \r\n \r\n dic = []\r\n for i in range(len(hashtag_name)):\r\n dic.append(\r\n {\"name\":hashtag_name[i],\r\n \"count\":hashtag_count[i],\r\n \"href\":hashtag_href[i]\r\n })\r\n \r\n return JsonResponse(dic,safe=False)\r\n\r\ndef twitterTrendsWorldWide(request):\r\n url='https://trends24.in/';\r\n page = requests.get(url);\r\n status_code=page.status_code;\r\n dic={};\r\n hashtag_name=[];\r\n hashtag_href=[];\r\n hashtag_count=[];\r\n if(status_code==200):\r\n data=BeautifulSoup(page.text,'lxml')\r\n new=data.find('ol',class_=\"trend-card__list\");\r\n li=data.find_all('li')\r\n for i in li:\r\n hashtag_name.append(i.a.text)\r\n hashtag_href.append(i.a.attrs['href'])\r\n if(i.find('span')):\r\n hashtag_count.append(i.span.text)\r\n else:\r\n hashtag_count.append(\"count unavalible\")\r\n \r\n \r\n \r\n dic = []\r\n for i in range(len(hashtag_name)):\r\n dic.append(\r\n {\"name\":hashtag_name[i],\r\n \"count\":hashtag_count[i],\r\n \"href\":hashtag_href[i]\r\n })\r\n \r\n return JsonResponse(dic,safe=False)\r\n\r\n#Twitter Index\r\n \r\n ","sub_path":"django/Auth_App/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"232847091","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/dictionaryutils/dictionary.py\n# Compiled at: 2020-04-29 15:07:15\n# Size of source mod 2**32: 1790 bytes\n\"\"\"\nThis modules provide the same interface as gdcdictionary.gdcdictionary\nIt can be 'reinstialized' after it's called init() with another dictionary\nFor example, using\n``gdcdictionary.gdcdictionary`` as the dictionary:\n\n.. code-block:: python\n\n dictionary.init(gdcdictionary.gdcdictionary)\n\"\"\"\nimport sys, traceback\nfrom cdislogging import get_logger\nfrom dictionaryutils import add_default_schema\nlogger = get_logger('__name__', log_level='info')\nthis_module = sys.modules[__name__]\nrequired_attrs = [\n 'resolvers', 'schema']\noptional_attrs = [\n 'settings']\nresolvers = None\nschema = None\nsettings = None\n\ndef init(dictionary):\n \"\"\"\n Initialize this file with the same attributes as ``dictionary``\n\n Args:\n dictionary (DataDictionary): a dictionary instance\n\n Return:\n None\n \"\"\"\n for required_attr in required_attrs:\n try:\n setattr(this_module, required_attr, getattr(dictionary, required_attr))\n except AttributeError:\n raise ValueError('given dictionary does not define ' + required_attr)\n\n for optional_attr in optional_attrs:\n try:\n setattr(this_module, optional_attr, getattr(dictionary, optional_attr))\n except AttributeError:\n pass\n\n\ntry:\n from gdcdictionary import gdcdictionary\n add_default_schema(gdcdictionary)\n init(gdcdictionary)\nexcept Exception as e:\n logger.error('Unable to initialize gdcdictionary: {}\\n{}'.format(e, traceback.format_exc()))","sub_path":"pycfiles/dictionaryutils-3.1.0-py3.6/dictionary.cpython-36.py","file_name":"dictionary.cpython-36.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"244867127","text":"# Import Necessary library\nimport cv2\nimport numpy as np\n\n# Read Input image\nimg = cv2.imread(\"me.jpg\", 1)\n# Convert to grayscale\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n# Blur the image to remove noise\nblur = cv2.blur(gray, (3, 3))\n# Obtain thresholding between 50 and 255 intensity\nret, thresh = cv2.threshold(blur, 50, 255, cv2.THRESH_BINARY)\n# Finding contours for the thresholded image\ncontours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n# Create hull array for convex hull points\nhull = []\n# Calculate points for each contour\nfor i in range(len(contours)):\n # Creating Convex Hull object for each contour\n hull.append( cv2.convexHull(contours[i], False))\n\n# Create an empty black image\ndrawing = np.zeros((thresh.shape[0], thresh.shape[1], 3), np.uint8)\n# draw contours and hull points\nfor i in range(len(contours)):\n # green - color for contours\n color_contours = (0, 255, 0)\n # Blue - color for convex hull\n color = (255, 0, 0)\n # Draw its contour\n cv2.drawContours(drawing, contours, i, color_contours, 1, 8, hierarchy)\n # Draw its convex hull object\n cv2.drawContours(drawing, hull, i, color, 1, 8)\n\n\n# Draw all the contours in image\ncv2.drawContours(img, contours, -1, (255, 0, 0), 1)\n# Save image as contour1.jpg\ncv2.imwrite(\"convexHull.jpg\", img)","sub_path":"Douglas–Peucker algorithm.py","file_name":"Douglas–Peucker algorithm.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"334425530","text":"#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n\n\"\"\"\nThe Pulsar Python client library is based on the existing C++ client library.\nAll the same features are exposed through the Python interface.\n\nCurrently, the only supported Python version is 2.7.\n\n## Install from PyPI\n\nDownload Python wheel binary files for MacOS and Linux\ndirectly from the PyPI archive.\n\n #!shell\n $ sudo pip install pulsar-client\n\n## Install from sources\n\nFollow the instructions to compile the Pulsar C++ client library. This method\nwill also build the Python binding for the library.\n\nTo install the Python bindings:\n\n #!shell\n $ cd pulsar-client-cpp/python\n $ sudo python setup.py install\n\n## Examples\n\n### [Producer](#pulsar.Producer) example\n\n #!python\n import pulsar\n\n client = pulsar.Client('pulsar://localhost:6650')\n\n producer = client.create_producer('my-topic')\n\n for i in range(10):\n producer.send(('Hello-%d' % i).encode('utf-8'))\n\n client.close()\n\n#### [Consumer](#pulsar.Consumer) Example\n\n #!python\n import pulsar\n\n client = pulsar.Client('pulsar://localhost:6650')\n consumer = client.subscribe('my-topic', 'my-subscription')\n\n while True:\n msg = consumer.receive()\n try:\n print(\"Received message '%s' id='%s'\", msg.data().decode('utf-8'), msg.message_id())\n consumer.acknowledge(msg)\n except:\n consumer.negative_acknowledge(msg)\n\n client.close()\n\n### [Async producer](#pulsar.Producer.send_async) example\n\n #!python\n import pulsar\n\n client = pulsar.Client('pulsar://localhost:6650')\n\n producer = client.create_producer(\n 'my-topic',\n block_if_queue_full=True,\n batching_enabled=True,\n batching_max_publish_delay_ms=10\n )\n\n def send_callback(res, msg):\n print('Message published res=%s', res)\n\n while True:\n producer.send_async(('Hello-%d' % i).encode('utf-8'), send_callback)\n\n client.close()\n\"\"\"\n\nimport _pulsar\n\nfrom _pulsar import Result, CompressionType, ConsumerType, InitialPosition, PartitionsRoutingMode # noqa: F401\n\nfrom pulsar.functions.function import Function\nfrom pulsar.functions.context import Context\nfrom pulsar.functions.serde import SerDe, IdentitySerDe, PickleSerDe\nfrom pulsar import schema\n_schema = schema\n\nimport re\n_retype = type(re.compile('x'))\n\nimport certifi\n\nclass MessageId:\n \"\"\"\n Represents a message id\n \"\"\"\n\n 'Represents the earliest message stored in a topic'\n earliest = _pulsar.MessageId.earliest\n\n 'Represents the latest message published on a topic'\n latest = _pulsar.MessageId.latest\n\n def serialize(self):\n \"\"\"\n Returns a bytes representation of the message id.\n This bytes sequence can be stored and later deserialized.\n \"\"\"\n return self._msg_id.serialize()\n\n @staticmethod\n def deserialize(message_id_bytes):\n \"\"\"\n Deserialize a message id object from a previously\n serialized bytes sequence.\n \"\"\"\n return _pulsar.MessageId.deserialize(message_id_bytes)\n\n\nclass Message:\n \"\"\"\n Message objects are returned by a consumer, either by calling `receive` or\n through a listener.\n \"\"\"\n\n def data(self):\n \"\"\"\n Returns object typed bytes with the payload of the message.\n \"\"\"\n return self._message.data()\n\n def value(self):\n \"\"\"\n Returns object with the de-serialized version of the message content\n \"\"\"\n return self._schema.decode(self._message.data())\n\n def properties(self):\n \"\"\"\n Return the properties attached to the message. Properties are\n application-defined key/value pairs that will be attached to the\n message.\n \"\"\"\n return self._message.properties()\n\n def partition_key(self):\n \"\"\"\n Get the partitioning key for the message.\n \"\"\"\n return self._message.partition_key()\n\n def publish_timestamp(self):\n \"\"\"\n Get the timestamp in milliseconds with the message publish time.\n \"\"\"\n return self._message.publish_timestamp()\n\n def event_timestamp(self):\n \"\"\"\n Get the timestamp in milliseconds with the message event time.\n \"\"\"\n return self._message.event_timestamp()\n\n def message_id(self):\n \"\"\"\n The message ID that can be used to refere to this particular message.\n \"\"\"\n return self._message.message_id()\n\n def topic_name(self):\n \"\"\"\n Get the topic Name from which this message originated from\n \"\"\"\n return self._message.topic_name()\n\n\nclass Authentication:\n \"\"\"\n Authentication provider object. Used to load authentication from an external\n shared library.\n \"\"\"\n def __init__(self, dynamicLibPath, authParamsString):\n \"\"\"\n Create the authentication provider instance.\n\n **Args**\n\n * `dynamicLibPath`: Path to the authentication provider shared library\n (such as `tls.so`)\n * `authParamsString`: Comma-separated list of provider-specific\n configuration params\n \"\"\"\n _check_type(str, dynamicLibPath, 'dynamicLibPath')\n _check_type(str, authParamsString, 'authParamsString')\n self.auth = _pulsar.Authentication(dynamicLibPath, authParamsString)\n\n\nclass AuthenticationTLS(Authentication):\n \"\"\"\n TLS Authentication implementation\n \"\"\"\n def __init__(self, certificate_path, private_key_path):\n \"\"\"\n Create the TLS authentication provider instance.\n\n **Args**\n\n * `certificatePath`: Path to the public certificate\n * `privateKeyPath`: Path to private TLS key\n \"\"\"\n _check_type(str, certificate_path, 'certificate_path')\n _check_type(str, private_key_path, 'private_key_path')\n self.auth = _pulsar.AuthenticationTLS(certificate_path, private_key_path)\n\n\nclass AuthenticationToken(Authentication):\n \"\"\"\n Token based authentication implementation\n \"\"\"\n def __init__(self, token):\n \"\"\"\n Create the token authentication provider instance.\n\n **Args**\n\n * `token`: A string containing the token or a functions that provides a\n string with the token\n \"\"\"\n if not (isinstance(token, str) or callable(token)):\n raise ValueError(\"Argument token is expected to be of type 'str' or a function returning 'str'\")\n self.auth = _pulsar.AuthenticationToken(token)\n\n\nclass AuthenticationAthenz(Authentication):\n \"\"\"\n Athenz Authentication implementation\n \"\"\"\n def __init__(self, auth_params_string):\n \"\"\"\n Create the Athenz authentication provider instance.\n\n **Args**\n\n * `auth_params_string`: JSON encoded configuration for Athenz client\n \"\"\"\n _check_type(str, auth_params_string, 'auth_params_string')\n self.auth = _pulsar.AuthenticationAthenz(auth_params_string)\n\n\nclass Client:\n \"\"\"\n The Pulsar client. A single client instance can be used to create producers\n and consumers on multiple topics.\n\n The client will share the same connection pool and threads across all\n producers and consumers.\n \"\"\"\n\n def __init__(self, service_url,\n authentication=None,\n operation_timeout_seconds=30,\n io_threads=1,\n message_listener_threads=1,\n concurrent_lookup_requests=50000,\n log_conf_file_path=None,\n use_tls=False,\n tls_trust_certs_file_path=None,\n tls_allow_insecure_connection=False,\n tls_validate_hostname=False,\n ):\n \"\"\"\n Create a new Pulsar client instance.\n\n **Args**\n\n * `service_url`: The Pulsar service url eg: pulsar://my-broker.com:6650/\n\n **Options**\n\n * `authentication`:\n Set the authentication provider to be used with the broker. For example:\n `AuthenticationTls` or `AuthenticationAthenz`\n * `operation_timeout_seconds`:\n Set timeout on client operations (subscribe, create producer, close,\n unsubscribe).\n * `io_threads`:\n Set the number of IO threads to be used by the Pulsar client.\n * `message_listener_threads`:\n Set the number of threads to be used by the Pulsar client when\n delivering messages through message listener. The default is 1 thread\n per Pulsar client. If using more than 1 thread, messages for distinct\n `message_listener`s will be delivered in different threads, however a\n single `MessageListener` will always be assigned to the same thread.\n * `concurrent_lookup_requests`:\n Number of concurrent lookup-requests allowed on each broker connection\n to prevent overload on the broker.\n * `log_conf_file_path`:\n Initialize log4cxx from a configuration file.\n * `use_tls`:\n Configure whether to use TLS encryption on the connection. This setting\n is deprecated. TLS will be automatically enabled if the `serviceUrl` is\n set to `pulsar+ssl://` or `https://`\n * `tls_trust_certs_file_path`:\n Set the path to the trusted TLS certificate file. If empty defaults to\n certifi.\n * `tls_allow_insecure_connection`:\n Configure whether the Pulsar client accepts untrusted TLS certificates\n from the broker.\n * `tls_validate_hostname`:\n Configure whether the Pulsar client validates that the hostname of the\n endpoint, matches the common name on the TLS certificate presented by\n the endpoint.\n \"\"\"\n _check_type(str, service_url, 'service_url')\n _check_type_or_none(Authentication, authentication, 'authentication')\n _check_type(int, operation_timeout_seconds, 'operation_timeout_seconds')\n _check_type(int, io_threads, 'io_threads')\n _check_type(int, message_listener_threads, 'message_listener_threads')\n _check_type(int, concurrent_lookup_requests, 'concurrent_lookup_requests')\n _check_type_or_none(str, log_conf_file_path, 'log_conf_file_path')\n _check_type(bool, use_tls, 'use_tls')\n _check_type_or_none(str, tls_trust_certs_file_path, 'tls_trust_certs_file_path')\n _check_type(bool, tls_allow_insecure_connection, 'tls_allow_insecure_connection')\n _check_type(bool, tls_validate_hostname, 'tls_validate_hostname')\n\n conf = _pulsar.ClientConfiguration()\n if authentication:\n conf.authentication(authentication.auth)\n conf.operation_timeout_seconds(operation_timeout_seconds)\n conf.io_threads(io_threads)\n conf.message_listener_threads(message_listener_threads)\n conf.concurrent_lookup_requests(concurrent_lookup_requests)\n if log_conf_file_path:\n conf.log_conf_file_path(log_conf_file_path)\n if use_tls or service_url.startswith('pulsar+ssl://') or service_url.startswith('https://'):\n conf.use_tls(True)\n if tls_trust_certs_file_path:\n conf.tls_trust_certs_file_path(tls_trust_certs_file_path)\n else:\n conf.tls_trust_certs_file_path(certifi.where())\n conf.tls_allow_insecure_connection(tls_allow_insecure_connection)\n conf.tls_validate_hostname(tls_validate_hostname)\n self._client = _pulsar.Client(service_url, conf)\n self._consumers = []\n\n def create_producer(self, topic,\n producer_name=None,\n schema=schema.BytesSchema(),\n initial_sequence_id=None,\n send_timeout_millis=30000,\n compression_type=CompressionType.NONE,\n max_pending_messages=1000,\n max_pending_messages_across_partitions=50000,\n block_if_queue_full=False,\n batching_enabled=False,\n batching_max_messages=1000,\n batching_max_allowed_size_in_bytes=128*1024,\n batching_max_publish_delay_ms=10,\n message_routing_mode=PartitionsRoutingMode.RoundRobinDistribution,\n properties=None,\n ):\n \"\"\"\n Create a new producer on a given topic.\n\n **Args**\n\n * `topic`:\n The topic name\n\n **Options**\n\n * `producer_name`:\n Specify a name for the producer. If not assigned,\n the system will generate a globally unique name which can be accessed\n with `Producer.producer_name()`. When specifying a name, it is app to\n the user to ensure that, for a given topic, the producer name is unique\n across all Pulsar's clusters.\n * `schema`:\n Define the schema of the data that will be published by this producer.\n The schema will be used for two purposes:\n - Validate the data format against the topic defined schema\n - Perform serialization/deserialization between data and objects\n An example for this parameter would be to pass `schema=JsonSchema(MyRecordClass)`.\n * `initial_sequence_id`:\n Set the baseline for the sequence ids for messages\n published by the producer. First message will be using\n `(initialSequenceId + 1)`` as its sequence id and subsequent messages will\n be assigned incremental sequence ids, if not otherwise specified.\n * `send_timeout_seconds`:\n If a message is not acknowledged by the server before the\n `send_timeout` expires, an error will be reported.\n * `compression_type`:\n Set the compression type for the producer. By default, message\n payloads are not compressed. Supported compression types are\n `CompressionType.LZ4`, `CompressionType.ZLib`, `CompressionType.ZSTD` and `CompressionType.SNAPPY`.\n ZSTD is supported since Pulsar 2.3. Consumers will need to be at least at that\n release in order to be able to receive messages compressed with ZSTD.\n SNAPPY is supported since Pulsar 2.4. Consumers will need to be at least at that\n release in order to be able to receive messages compressed with SNAPPY.\n * `max_pending_messages`:\n Set the max size of the queue holding the messages pending to receive\n an acknowledgment from the broker.\n * `max_pending_messages_across_partitions`:\n Set the max size of the queue holding the messages pending to receive\n an acknowledgment across partitions from the broker.\n * `block_if_queue_full`: Set whether `send_async` operations should\n block when the outgoing message queue is full.\n * `message_routing_mode`:\n Set the message routing mode for the partitioned producer. Default is `PartitionsRoutingMode.RoundRobinDistribution`,\n other option is `PartitionsRoutingMode.UseSinglePartition`\n * `properties`:\n Sets the properties for the producer. The properties associated with a producer\n can be used for identify a producer at broker side.\n \"\"\"\n _check_type(str, topic, 'topic')\n _check_type_or_none(str, producer_name, 'producer_name')\n _check_type(_schema.Schema, schema, 'schema')\n _check_type_or_none(int, initial_sequence_id, 'initial_sequence_id')\n _check_type(int, send_timeout_millis, 'send_timeout_millis')\n _check_type(CompressionType, compression_type, 'compression_type')\n _check_type(int, max_pending_messages, 'max_pending_messages')\n _check_type(int, max_pending_messages_across_partitions, 'max_pending_messages_across_partitions')\n _check_type(bool, block_if_queue_full, 'block_if_queue_full')\n _check_type(bool, batching_enabled, 'batching_enabled')\n _check_type(int, batching_max_messages, 'batching_max_messages')\n _check_type(int, batching_max_allowed_size_in_bytes, 'batching_max_allowed_size_in_bytes')\n _check_type(int, batching_max_publish_delay_ms, 'batching_max_publish_delay_ms')\n _check_type_or_none(dict, properties, 'properties')\n\n conf = _pulsar.ProducerConfiguration()\n conf.send_timeout_millis(send_timeout_millis)\n conf.compression_type(compression_type)\n conf.max_pending_messages(max_pending_messages)\n conf.max_pending_messages_across_partitions(max_pending_messages_across_partitions)\n conf.block_if_queue_full(block_if_queue_full)\n conf.batching_enabled(batching_enabled)\n conf.batching_max_messages(batching_max_messages)\n conf.batching_max_allowed_size_in_bytes(batching_max_allowed_size_in_bytes)\n conf.batching_max_publish_delay_ms(batching_max_publish_delay_ms)\n conf.partitions_routing_mode(message_routing_mode)\n if producer_name:\n conf.producer_name(producer_name)\n if initial_sequence_id:\n conf.initial_sequence_id(initial_sequence_id)\n if properties:\n for k, v in properties.items():\n conf.property(k, v)\n\n conf.schema(schema.schema_info())\n\n p = Producer()\n p._producer = self._client.create_producer(topic, conf)\n p._schema = schema\n return p\n\n def subscribe(self, topic, subscription_name,\n consumer_type=ConsumerType.Exclusive,\n schema=schema.BytesSchema(),\n message_listener=None,\n receiver_queue_size=1000,\n max_total_receiver_queue_size_across_partitions=50000,\n consumer_name=None,\n unacked_messages_timeout_ms=None,\n broker_consumer_stats_cache_time_ms=30000,\n negative_ack_redelivery_delay_ms=60000,\n is_read_compacted=False,\n properties=None,\n pattern_auto_discovery_period=60,\n initial_position=InitialPosition.Latest\n ):\n \"\"\"\n Subscribe to the given topic and subscription combination.\n\n **Args**\n\n * `topic`: The name of the topic, list of topics or regex pattern.\n This method will accept these forms:\n - `topic='my-topic'`\n - `topic=['topic-1', 'topic-2', 'topic-3']`\n - `topic=re.compile('topic-.*')`\n * `subscription`: The name of the subscription.\n\n **Options**\n\n * `consumer_type`:\n Select the subscription type to be used when subscribing to the topic.\n * `schema`:\n Define the schema of the data that will be received by this consumer.\n * `message_listener`:\n Sets a message listener for the consumer. When the listener is set,\n the application will receive messages through it. Calls to\n `consumer.receive()` will not be allowed. The listener function needs\n to accept (consumer, message), for example:\n\n #!python\n def my_listener(consumer, message):\n # process message\n consumer.acknowledge(message)\n\n * `receiver_queue_size`:\n Sets the size of the consumer receive queue. The consumer receive\n queue controls how many messages can be accumulated by the consumer\n before the application calls `receive()`. Using a higher value could\n potentially increase the consumer throughput at the expense of higher\n memory utilization. Setting the consumer queue size to zero decreases\n the throughput of the consumer by disabling pre-fetching of messages.\n This approach improves the message distribution on shared subscription\n by pushing messages only to those consumers that are ready to process\n them. Neither receive with timeout nor partitioned topics can be used\n if the consumer queue size is zero. The `receive()` function call\n should not be interrupted when the consumer queue size is zero. The\n default value is 1000 messages and should work well for most use\n cases.\n * `max_total_receiver_queue_size_across_partitions`\n Set the max total receiver queue size across partitions.\n This setting will be used to reduce the receiver queue size for individual partitions\n * `consumer_name`:\n Sets the consumer name.\n * `unacked_messages_timeout_ms`:\n Sets the timeout in milliseconds for unacknowledged messages. The\n timeout needs to be greater than 10 seconds. An exception is thrown if\n the given value is less than 10 seconds. If a successful\n acknowledgement is not sent within the timeout, all the unacknowledged\n messages are redelivered.\n * `negative_ack_redelivery_delay_ms`:\n The delay after which to redeliver the messages that failed to be\n processed (with the `consumer.negative_acknowledge()`)\n * `broker_consumer_stats_cache_time_ms`:\n Sets the time duration for which the broker-side consumer stats will\n be cached in the client.\n * `is_read_compacted`:\n Selects whether to read the compacted version of the topic\n * `properties`:\n Sets the properties for the consumer. The properties associated with a consumer\n can be used for identify a consumer at broker side.\n * `pattern_auto_discovery_period`:\n Periods of seconds for consumer to auto discover match topics.\n * `initial_position`:\n Set the initial position of a consumer when subscribing to the topic.\n It could be either: `InitialPosition.Earliest` or `InitialPosition.Latest`.\n Default: `Latest`.\n \"\"\"\n _check_type(str, subscription_name, 'subscription_name')\n _check_type(ConsumerType, consumer_type, 'consumer_type')\n _check_type(_schema.Schema, schema, 'schema')\n _check_type(int, receiver_queue_size, 'receiver_queue_size')\n _check_type(int, max_total_receiver_queue_size_across_partitions,\n 'max_total_receiver_queue_size_across_partitions')\n _check_type_or_none(str, consumer_name, 'consumer_name')\n _check_type_or_none(int, unacked_messages_timeout_ms, 'unacked_messages_timeout_ms')\n _check_type(int, broker_consumer_stats_cache_time_ms, 'broker_consumer_stats_cache_time_ms')\n _check_type(int, negative_ack_redelivery_delay_ms, 'negative_ack_redelivery_delay_ms')\n _check_type(int, pattern_auto_discovery_period, 'pattern_auto_discovery_period')\n _check_type(bool, is_read_compacted, 'is_read_compacted')\n _check_type_or_none(dict, properties, 'properties')\n _check_type(InitialPosition, initial_position, 'initial_position')\n\n conf = _pulsar.ConsumerConfiguration()\n conf.consumer_type(consumer_type)\n conf.read_compacted(is_read_compacted)\n if message_listener:\n conf.message_listener(_listener_wrapper(message_listener, schema))\n conf.receiver_queue_size(receiver_queue_size)\n conf.max_total_receiver_queue_size_across_partitions(max_total_receiver_queue_size_across_partitions)\n if consumer_name:\n conf.consumer_name(consumer_name)\n if unacked_messages_timeout_ms:\n conf.unacked_messages_timeout_ms(unacked_messages_timeout_ms)\n\n conf.negative_ack_redelivery_delay_ms(negative_ack_redelivery_delay_ms)\n conf.broker_consumer_stats_cache_time_ms(broker_consumer_stats_cache_time_ms)\n if properties:\n for k, v in properties.items():\n conf.property(k, v)\n conf.subscription_initial_position(initial_position)\n\n conf.schema(schema.schema_info())\n\n c = Consumer()\n if isinstance(topic, str):\n # Single topic\n c._consumer = self._client.subscribe(topic, subscription_name, conf)\n elif isinstance(topic, list):\n # List of topics\n c._consumer = self._client.subscribe_topics(topic, subscription_name, conf)\n elif isinstance(topic, _retype):\n # Regex pattern\n c._consumer = self._client.subscribe_pattern(topic.pattern, subscription_name, conf)\n else:\n raise ValueError(\"Argument 'topic' is expected to be of a type between (str, list, re.pattern)\")\n\n c._client = self\n c._schema = schema\n self._consumers.append(c)\n return c\n\n def create_reader(self, topic, start_message_id,\n schema=schema.BytesSchema(),\n reader_listener=None,\n receiver_queue_size=1000,\n reader_name=None,\n subscription_role_prefix=None,\n is_read_compacted=False\n ):\n \"\"\"\n Create a reader on a particular topic\n\n **Args**\n\n * `topic`: The name of the topic.\n * `start_message_id`: The initial reader positioning is done by specifying a message id.\n The options are:\n * `MessageId.earliest`: Start reading from the earliest message available in the topic\n * `MessageId.latest`: Start reading from the end topic, only getting messages published\n after the reader was created\n * `MessageId`: When passing a particular message id, the reader will position itself on\n that specific position. The first message to be read will be the message next to the\n specified messageId. Message id can be serialized into a string and deserialized\n back into a `MessageId` object:\n\n # Serialize to string\n s = msg.message_id().serialize()\n\n # Deserialize from string\n msg_id = MessageId.deserialize(s)\n\n **Options**\n\n * `schema`:\n Define the schema of the data that will be received by this reader.\n * `reader_listener`:\n Sets a message listener for the reader. When the listener is set,\n the application will receive messages through it. Calls to\n `reader.read_next()` will not be allowed. The listener function needs\n to accept (reader, message), for example:\n\n def my_listener(reader, message):\n # process message\n pass\n\n * `receiver_queue_size`:\n Sets the size of the reader receive queue. The reader receive\n queue controls how many messages can be accumulated by the reader\n before the application calls `read_next()`. Using a higher value could\n potentially increase the reader throughput at the expense of higher\n memory utilization.\n * `reader_name`:\n Sets the reader name.\n * `subscription_role_prefix`:\n Sets the subscription role prefix.\n * `is_read_compacted`:\n Selects whether to read the compacted version of the topic\n \"\"\"\n _check_type(str, topic, 'topic')\n _check_type(_pulsar.MessageId, start_message_id, 'start_message_id')\n _check_type(_schema.Schema, schema, 'schema')\n _check_type(int, receiver_queue_size, 'receiver_queue_size')\n _check_type_or_none(str, reader_name, 'reader_name')\n _check_type_or_none(str, subscription_role_prefix, 'subscription_role_prefix')\n _check_type(bool, is_read_compacted, 'is_read_compacted')\n\n conf = _pulsar.ReaderConfiguration()\n if reader_listener:\n conf.reader_listener(_listener_wrapper(reader_listener, schema))\n conf.receiver_queue_size(receiver_queue_size)\n if reader_name:\n conf.reader_name(reader_name)\n if subscription_role_prefix:\n conf.subscription_role_prefix(subscription_role_prefix)\n conf.schema(schema.schema_info())\n conf.read_compacted(is_read_compacted)\n\n c = Reader()\n c._reader = self._client.create_reader(topic, start_message_id, conf)\n c._client = self\n c._schema = schema\n self._consumers.append(c)\n return c\n\n def get_topic_partitions(self, topic):\n \"\"\"\n Get the list of partitions for a given topic.\n\n If the topic is partitioned, this will return a list of partition names. If the topic is not\n partitioned, the returned list will contain the topic name itself.\n\n This can be used to discover the partitions and create Reader, Consumer or Producer\n instances directly on a particular partition.\n :param topic: the topic name to lookup\n :return: a list of partition name\n \"\"\"\n _check_type(str, topic, 'topic')\n return self._client.get_topic_partitions(topic)\n\n def close(self):\n \"\"\"\n Close the client and all the associated producers and consumers\n \"\"\"\n self._client.close()\n\n\nclass Producer:\n \"\"\"\n The Pulsar message producer, used to publish messages on a topic.\n \"\"\"\n\n def topic(self):\n \"\"\"\n Return the topic which producer is publishing to\n \"\"\"\n return self._producer.topic()\n\n def producer_name(self):\n \"\"\"\n Return the producer name which could have been assigned by the\n system or specified by the client\n \"\"\"\n return self._producer.producer_name()\n\n def last_sequence_id(self):\n \"\"\"\n Get the last sequence id that was published by this producer.\n\n This represent either the automatically assigned or custom sequence id\n (set on the `MessageBuilder`) that was published and acknowledged by the broker.\n\n After recreating a producer with the same producer name, this will return the\n last message that was published in the previous producer session, or -1 if\n there no message was ever published.\n \"\"\"\n return self._producer.last_sequence_id()\n\n def send(self, content,\n properties=None,\n partition_key=None,\n sequence_id=None,\n replication_clusters=None,\n disable_replication=False,\n event_timestamp=None,\n ):\n \"\"\"\n Publish a message on the topic. Blocks until the message is acknowledged\n\n **Args**\n\n * `content`:\n A `bytes` object with the message payload.\n\n **Options**\n\n * `properties`:\n A dict of application-defined string properties.\n * `partition_key`:\n Sets the partition key for message routing. A hash of this key is used\n to determine the message's topic partition.\n * `sequence_id`:\n Specify a custom sequence id for the message being published.\n * `replication_clusters`:\n Override namespace replication clusters. Note that it is the caller's\n responsibility to provide valid cluster names and that all clusters\n have been previously configured as topics. Given an empty list,\n the message will replicate according to the namespace configuration.\n * `disable_replication`:\n Do not replicate this message.\n * `event_timestamp`:\n Timestamp in millis of the timestamp of event creation\n \"\"\"\n msg = self._build_msg(content, properties, partition_key, sequence_id,\n replication_clusters, disable_replication, event_timestamp)\n return self._producer.send(msg)\n\n def send_async(self, content, callback,\n properties=None,\n partition_key=None,\n sequence_id=None,\n replication_clusters=None,\n disable_replication=False,\n event_timestamp=None\n ):\n \"\"\"\n Send a message asynchronously.\n\n The `callback` will be invoked once the message has been acknowledged\n by the broker.\n\n Example:\n\n #!python\n def callback(res, msg):\n print('Message published: %s' % res)\n\n producer.send_async(msg, callback)\n\n When the producer queue is full, by default the message will be rejected\n and the callback invoked with an error code.\n\n **Args**\n\n * `content`:\n A `bytes` object with the message payload.\n\n **Options**\n\n * `properties`:\n A dict of application0-defined string properties.\n * `partition_key`:\n Sets the partition key for the message routing. A hash of this key is\n used to determine the message's topic partition.\n * `sequence_id`:\n Specify a custom sequence id for the message being published.\n * `replication_clusters`: Override namespace replication clusters. Note\n that it is the caller's responsibility to provide valid cluster names\n and that all clusters have been previously configured as topics.\n Given an empty list, the message will replicate per the namespace\n configuration.\n * `disable_replication`:\n Do not replicate this message.\n * `event_timestamp`:\n Timestamp in millis of the timestamp of event creation\n \"\"\"\n msg = self._build_msg(content, properties, partition_key, sequence_id,\n replication_clusters, disable_replication, event_timestamp)\n self._producer.send_async(msg, callback)\n\n\n def flush(self):\n \"\"\"\n Flush all the messages buffered in the client and wait until all messages have been\n successfully persisted\n \"\"\"\n self._producer.flush()\n\n\n def close(self):\n \"\"\"\n Close the producer.\n \"\"\"\n self._producer.close()\n\n def _build_msg(self, content, properties, partition_key, sequence_id,\n replication_clusters, disable_replication, event_timestamp):\n data = self._schema.encode(content)\n\n _check_type(bytes, data, 'data')\n _check_type_or_none(dict, properties, 'properties')\n _check_type_or_none(str, partition_key, 'partition_key')\n _check_type_or_none(int, sequence_id, 'sequence_id')\n _check_type_or_none(list, replication_clusters, 'replication_clusters')\n _check_type(bool, disable_replication, 'disable_replication')\n _check_type_or_none(int, event_timestamp, 'event_timestamp')\n\n mb = _pulsar.MessageBuilder()\n mb.content(data)\n if properties:\n for k, v in properties.items():\n mb.property(k, v)\n if partition_key:\n mb.partition_key(partition_key)\n if sequence_id:\n mb.sequence_id(sequence_id)\n if replication_clusters:\n mb.replication_clusters(replication_clusters)\n if disable_replication:\n mb.disable_replication(disable_replication)\n if event_timestamp:\n mb.event_timestamp(event_timestamp)\n return mb.build()\n\n\nclass Consumer:\n \"\"\"\n Pulsar consumer.\n \"\"\"\n\n def topic(self):\n \"\"\"\n Return the topic this consumer is subscribed to.\n \"\"\"\n return self._consumer.topic()\n\n def subscription_name(self):\n \"\"\"\n Return the subscription name.\n \"\"\"\n return self._consumer.subscription_name()\n\n def unsubscribe(self):\n \"\"\"\n Unsubscribe the current consumer from the topic.\n\n This method will block until the operation is completed. Once the\n consumer is unsubscribed, no more messages will be received and\n subsequent new messages will not be retained for this consumer.\n\n This consumer object cannot be reused.\n \"\"\"\n return self._consumer.unsubscribe()\n\n def receive(self, timeout_millis=None):\n \"\"\"\n Receive a single message.\n\n If a message is not immediately available, this method will block until\n a new message is available.\n\n **Options**\n\n * `timeout_millis`:\n If specified, the receive will raise an exception if a message is not\n available within the timeout.\n \"\"\"\n if timeout_millis is None:\n msg = self._consumer.receive()\n else:\n _check_type(int, timeout_millis, 'timeout_millis')\n msg = self._consumer.receive(timeout_millis)\n\n m = Message()\n m._message = msg\n m._schema = self._schema\n return m\n\n def acknowledge(self, message):\n \"\"\"\n Acknowledge the reception of a single message.\n\n This method will block until an acknowledgement is sent to the broker.\n After that, the message will not be re-delivered to this consumer.\n\n **Args**\n\n * `message`:\n The received message or message id.\n \"\"\"\n if isinstance(message, Message):\n self._consumer.acknowledge(message._message)\n else:\n self._consumer.acknowledge(message)\n\n def acknowledge_cumulative(self, message):\n \"\"\"\n Acknowledge the reception of all the messages in the stream up to (and\n including) the provided message.\n\n This method will block until an acknowledgement is sent to the broker.\n After that, the messages will not be re-delivered to this consumer.\n\n **Args**\n\n * `message`:\n The received message or message id.\n \"\"\"\n if isinstance(message, Message):\n self._consumer.acknowledge_cumulative(message._message)\n else:\n self._consumer.acknowledge_cumulative(message)\n\n def negative_acknowledge(self, message):\n \"\"\"\n Acknowledge the failure to process a single message.\n\n When a message is \"negatively acked\" it will be marked for redelivery after\n some fixed delay. The delay is configurable when constructing the consumer\n with {@link ConsumerConfiguration#setNegativeAckRedeliveryDelayMs}.\n\n This call is not blocking.\n\n **Args**\n\n * `message`:\n The received message or message id.\n \"\"\"\n if isinstance(message, Message):\n self._consumer.negative_acknowledge(message._message)\n else:\n self._consumer.negative_acknowledge(message)\n\n def pause_message_listener(self):\n \"\"\"\n Pause receiving messages via the `message_listener` until\n `resume_message_listener()` is called.\n \"\"\"\n self._consumer.pause_message_listener()\n\n def resume_message_listener(self):\n \"\"\"\n Resume receiving the messages via the message listener.\n Asynchronously receive all the messages enqueued from the time\n `pause_message_listener()` was called.\n \"\"\"\n self._consumer.resume_message_listener()\n\n def redeliver_unacknowledged_messages(self):\n \"\"\"\n Redelivers all the unacknowledged messages. In failover mode, the\n request is ignored if the consumer is not active for the given topic. In\n shared mode, the consumer's messages to be redelivered are distributed\n across all the connected consumers. This is a non-blocking call and\n doesn't throw an exception. In case the connection breaks, the messages\n are redelivered after reconnect.\n \"\"\"\n self._consumer.redeliver_unacknowledged_messages()\n\n def seek(self, messageid):\n \"\"\"\n Reset the subscription associated with this consumer to a specific message id.\n The message id can either be a specific message or represent the first or last messages in the topic.\n Note: this operation can only be done on non-partitioned topics. For these, one can rather perform the\n seek() on the individual partitions.\n\n **Args**\n\n * `message`:\n The message id for seek.\n \"\"\"\n self._consumer.seek(messageid)\n\n def close(self):\n \"\"\"\n Close the consumer.\n \"\"\"\n self._consumer.close()\n self._client._consumers.remove(self)\n\n\nclass Reader:\n \"\"\"\n Pulsar topic reader.\n \"\"\"\n\n def topic(self):\n \"\"\"\n Return the topic this reader is reading from.\n \"\"\"\n return self._reader.topic()\n\n def read_next(self, timeout_millis=None):\n \"\"\"\n Read a single message.\n\n If a message is not immediately available, this method will block until\n a new message is available.\n\n **Options**\n\n * `timeout_millis`:\n If specified, the receive will raise an exception if a message is not\n available within the timeout.\n \"\"\"\n if timeout_millis is None:\n msg = self._reader.read_next()\n else:\n _check_type(int, timeout_millis, 'timeout_millis')\n msg = self._reader.read_next(timeout_millis)\n\n m = Message()\n m._message = msg\n m._schema = self._schema\n return m\n\n def has_message_available(self):\n \"\"\"\n Check if there is any message available to read from the current position.\n \"\"\"\n return self._reader.has_message_available();\n\n def close(self):\n \"\"\"\n Close the reader.\n \"\"\"\n self._reader.close()\n self._client._consumers.remove(self)\n\n\ndef _check_type(var_type, var, name):\n if not isinstance(var, var_type):\n raise ValueError(\"Argument %s is expected to be of type '%s' and not '%s'\"\n % (name, var_type.__name__, type(var).__name__))\n\n\ndef _check_type_or_none(var_type, var, name):\n if var is not None and not isinstance(var, var_type):\n raise ValueError(\"Argument %s is expected to be either None or of type '%s'\"\n % (name, var_type.__name__))\n\n\ndef _listener_wrapper(listener, schema):\n def wrapper(consumer, msg):\n c = Consumer()\n c._consumer = consumer\n m = Message()\n m._message = msg\n m._schema = schema\n listener(c, m)\n return wrapper\n","sub_path":"pulsar-client-cpp/python/pulsar/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":42967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"480023124","text":"__author__ = 'mtianyan'\n__date__ = '2018/8/20 08:51'\n\nfield_list = ['title', 'url', 'url_object_id', 'salary_min', 'salary_max', 'job_city',\n 'work_years_min', 'work_years_max', 'degree_need''job_type', 'publish_time',\n 'job_advantage', 'job_desc', 'job_addr', 'company_name', 'company_url',\n 'tags', 'crawl_time']\nduplicate_key_update = ['praise_nums', 'comment_nums', 'crawl_time', 'fav_nums']\n\n\ndef fun_sql_insert(field_list: list, duplicate_key_update: list, table_name: str):\n field_str = \"\"\n field_s = \"\"\n update_s = \"\"\n params_s = \"\"\n for field in field_list:\n field_str += field + ','\n field_s += '%s,'\n params_s += 'self[\"' + str(field) + '\"],\\n\\t'\n for duplicate_key in duplicate_key_update:\n update_s += str(duplicate_key) + \"=VALUES(\" + str(duplicate_key) + '),'\n params_txt = \"params = (\\n\" + params_s + \")\"\n sql = \"insert into {0}({1}) VALUES({2}) \\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tON DUPLICATE KEY UPDATE {3}\".format(table_name,\n field_str[:-1],\n field_s[:-1],\n update_s[:-1])\n print(sql)\n return sql, params_txt\n\n\nif __name__ == '__main__':\n print(fun_sql_insert(field_list, duplicate_key_update, \"jobbole_article\"))\n","sub_path":"FunpySpiderSearch/utils/mysql_utils.py","file_name":"mysql_utils.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"131686126","text":"import PageSourceGet, PageSourceParse, PageUrlGet\nfrom fake_useragent import UserAgent\nimport time, random, xlrd, datetime, signal\n\n\ninit_url = \"http://*************\"\nindex_url = \"http://*************\"\nbase_url = 'http://*************'\nresult_parse_rule = {'search_result_url': '//*[@id=\"advs\"]/div/div[2]/a/@href'}\nmax_click = 10\nchm_headers = ['Host=\"********\"',\n 'Connection=\"keep-alive\"',\n 'User-Agent={}'.format(UserAgent().random),\n 'Upgrade-Insecure-Requests=1',\n 'Accept=\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\"',\n 'Accept-Encoding=\"gzip, deflate\"',\n 'Accept-Language=\"zh-CN,zh;q=0.9\"']\nsearch = PageUrlGet.CorpSearch(init_url, index_url, chm_headers, max_click)\nbook = xlrd.open_workbook(r\"************\")\nsheet = book.sheet_by_index(0)\nnum = 1\nfor i in range(sheet.nrows):\n company_name = sheet.cell(i ,0).value\n company_name = company_name.replace(\"(\",\"(\").replace(\")\",\")\")\n print(str(datetime.datetime.now()) + f\",开始爬取 {company_name} 数据\")\n try:\n search.main(company_name)\n driver = search.detail_page()\n source_get = PageSourceGet.SourceGet(driver)\n source_driver, windows_list = source_get.run()\n parse = PageSourceParse.PageDetailParse(source_driver, company_name)\n print(\"开始解析HTML页面数据并存库\")\n parse.page_source_parse(windows_list)\n except Exception as e:\n with open(r\"**********\", \"a\" , encoding='utf-8') as f:\n f.write(company_name)\n f.write(\"\\n\")\n print(\"{}搜索异常\".format(company_name))\n print(\"异常原因:{}\".format(e))\n continue\n print(str(datetime.datetime.now()) + f\",{company_name}数据爬取完成\")\n num = num + 1\n time.sleep(random.randint(8, 15) / 10)\n\nprint(\"共爬取{}数据,爬虫结束!\".format(num))\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"82226775","text":"\"\"\"Tests for task\"\"\"\nfrom unittest import TestCase\nfrom timerdaemon.core.task import Task\nimport datetime\n\nclass TestHelper(object):\n \"\"\" Test helper class for task\"\"\"\n def __init__(self):\n self.called = False\n self.call_arg = None\n\n def __call__(self, arg):\n self.called = True\n self.call_arg = arg\n\nclass TaskTest(TestCase):\n \"\"\"Test case for task\"\"\"\n def test_call(self):\n \"\"\"Test callback\"\"\"\n task = Task(None)\n task.call()\n\n helper = TestHelper()\n task = Task(helper)\n\n self.assertFalse(helper.called)\n task.call()\n self.assertTrue(helper.called)\n self.assertEqual(task, helper.call_arg)\n\n def test_add_history(self):\n \"\"\"Test adding history\"\"\"\n task = Task(None)\n day1 = datetime.datetime(year=2015, month=10, day=12)\n day2 = datetime.datetime(year=2015, month=10, day=16)\n day3 = datetime.datetime(year=2015, month=11, day=10)\n\n self.assertEqual([], task.history)\n task.missed(day1)\n task.deferred(day2)\n task.done(day3)\n task.deferred(day3)\n task.done(day2)\n task.missed(day1)\n self.assertEqual([(Task.MISSED, day1),\n (Task.DEFERED, day2),\n (Task.DONE, day3),\n (Task.DEFERED, day3),\n (Task.DONE, day2),\n (Task.MISSED, day1)], task.history)\n","sub_path":"timerdaemon/core/tests/test_task.py","file_name":"test_task.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"129935928","text":"#Libraries & Packages ###############################################\nfrom .test_desing import Spell, Validate\nfrom .machineAI import Analizer_Dataset\nfrom .strategy_ML import *\n######################################################################\n'''\nThis module behaves as a command pattern, it will take other's modules to provide the final result\n\n\n'''\nclass Process():\n # def __init__(self, data_input):\n # self.data_input = data_input\n\n def stage_one(self, data_input):\n self.data_input = data_input\n word_s = Words_Analizer_Strategy()\n simi = Words_Similarity()\n fantasy = WordSmartbot(word_s)\n value_on = fantasy.Smart_Stage_One(self.data_input)\n #if (type(value_on) is tuple) == False:\n #robot_x = Analizer_Dataset()\n # robot_y = robot_x.Sentence_Category(value_on)\n # return robot_y\n # return (value_on[0])\n return value_on\n def stage_two(self,variable):\n self.variable = variable\n robotx = Analizer_Dataset()\n test_stage = Process()\n example = test_stage.stage_one(variable)\n if (type (example)is tuple) == True:\n ejemplo = robotx.Sentence_Category(example[0])\n return ejemplo\n return example\n\n # inspection = self.robot.words_in_vocabulary(self.data_input)\n # if (type(inspection) is tuple) == False :\n # return inspection\n # return inspection[0]\n\n","sub_path":"cloud_dev/Machine_Learning/strategy_calling_methods.py","file_name":"strategy_calling_methods.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"449507895","text":"\nimport numpy as np\nimport pandas as pd\n\n\"\"\"\ndef euclid_distance(a,b):\n\ta=np.array(a)\n\tb=np.array(b)\n\treturn np.sqrt((np.square(a-b)))\n\"\"\"\ndef DBSCAN2():\n\tdata=pd.read_csv(\"diabetes.csv\")\n\tdata=np.array(data)[:,:data.columns.size-1]\n\tdb = DBSCAN(eps=4, min_samples=20).fit(data)\n\tlabels = db.labels_\n\tn_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)\n\tclusters = [data[labels == i] for i in range(n_clusters_)]\n\toutliers = data[labels == -1]\n\treturn (clusters,outliers,len(clusters))\n\ndef euclid_distance1(a,b):\n\ta=np.array(a)\n\tb=np.array(b)\n\treturn np.sqrt(np.sum(np.square(a-b),axis=1))\n\nvisited=(np.array([False for i in range(811)]))\n#data=np.random.randint(-100,100,size=(100,2)).tolist()\n#data=np.array(pd.read_csv(\"/home/jayanth/Documents/DMG_Project/datasets/Sales.csv\").iloc[:,0:4]).tolist()\ndata=np.array(d3).tolist()\n#data1=np.arange(50).tolist()\n#data2=np.arange(100,150).tolist()\n#data=data1+data2\ne=10\nminpts=5\nclusters=[]\noutliers=[]\n#distance_func=np.vectorize(euclid_distance)\n\n\ndef region_fun(point):\n\tif len(point)==1:\n\t\tdistances=euclid_distance(point,data)\n\telse:\n\t\tdistances=euclid_distance1(point,data)\n\treturn distances<=e\n\ndef expand_cluster(point,neighbourhood):\n\tclusters[-1].append(point)\n\tprint(clusters[-1])\n\t#print(\"Clusters :\",clusters)\n\tfor i in neighbourhood:\n\t\tprint(i)\n\t\tprint(\"check :\",data.index(i))\n\t\tif visited[data.index(i)]==False:\n\t\t\t\n\t\t\tneighbourhood_1=np.array(data)[region_fun(i)]\n\t\t\tif len(neighbourhood_1)>minpts:\n\n\t\t\t\tvisited[data.index(i)]=True\n\t\t\t\t#neighbourhood=neighbourhood+neighbourhood_1.tolist()\n\t\t\t\texpand_cluster(i,neighbourhood_1.tolist())\n\t\t\telse:\n\t\t\t\t\n\t\t\t\tcheck=0\n\t\t\t\tvisited[data.index(i)]=True\n\t\t\t\tclusters[-1].append(i)\n\t\t\t\tprint(clusters[-1])\n\t\t\t\t\n\t\t\t\t#for j in clusters:\n\t\t\t\t#\tif j.count(i)==1:\n\t\t\t\t#\t\tcheck=1\n\t\t\t\t#\t\tbreak\n\t\t\t\t#if(check==0):\n\t\t\t\t#\tvisited[data.index(i)]=True\n\t\t\t\t#\tclusters[-1].append(i)\n\t\t\t\t#\t#print(clusters)\n\n\t\t\t\n\n\ndef DBSCAN():\n\tcount=0\n\tfor i in range(len(data)):\n\t\tif visited[i]==False:\n\t\t\t\n\t\t\t\n\t\t\tneighbourhood=np.array(data)[region_fun(data[i])]\n\t\t\tprint(\"*****************\",neighbourhood)\n\t\t\tif len(neighbourhood)>minpts:\n\t\t\t\tprint(\"visited Point :\",data[i])\n\t\t\t\tvisited[i]=True\n\t\t\t\tclusters.append([])\n\t\t\t\tprint(\"neighbourhood :\",neighbourhood)\n\t\t\t\texpand_cluster(data[i],neighbourhood.tolist())\n\t\t\t\t\n\tfor i in range(len(data)):\n\t\tif(visited[i]==False):\n\t\t\toutliers.append(data[i])\n\tfor i in clusters:\n\t\tprint(i)\n\t\tcount=count+len(i)\n\t\tprint()\n\t\tprint()\n\t\tprint()\n\tprint(\"Outliers :\",outliers);\n\tprint()\n\tprint(count)\n\tprint(len(outliers))\n\tprint(len(clusters))\n","sub_path":"Clustering/diabetes_dataset/DBSCAN.py","file_name":"DBSCAN.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"26614095","text":"'''\nCopyright (C) 2014 New York University\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n'''\n\nimport numpy as np\n\nclass NYUDepthModelDefs(object):\n def __init__(self):\n '''\n precomputed means and stdev\n '''\n\n self.vgg_image_mean = np.array((123.68, 116.779, 103.939), dtype=np.float32)\n self.images_mean = 109.31410628\n self.images_std = 76.18328376\n self.images_istd = 1.0 / self.images_std\n self.depths_mean = 2.53434899\n self.depths_std = 1.22576694\n self.depths_istd = 1.0 / self.depths_std\n self.logdepths_mean = 0.82473954\n self.logdepths_std = 0.45723134\n self.logdepths_istd = 1.0 / self.logdepths_std\n self.semantic_class_num = 40\n","sub_path":"DSGAN/dataset_defs.py","file_name":"dataset_defs.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"118184781","text":"# -*- coding: utf-8 -*-\n# @Time : 05/04/2021 21:29\n# @Author : Cao Junhao\n# @Site : \n# @File : 04_Mask_Detection_Real-Time-Stream.py\n# @Software: PyCharm\n\nimport tensorflow as tf\nimport cv2\nimport argparse\nimport numpy as np\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.applications.densenet import preprocess_input\nfrom tensorflow.keras.models import load_model\nimport imutils\nfrom imutils.video import VideoStream\n\n# Construct the environment to fit the Tensorflow_GPU\nphysical_devices = tf.config.list_physical_devices('GPU')\nfor p in physical_devices:\n tf.config.experimental.set_memory_growth(p, True)\n\n# Construct the argument parser to parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-p\", \"--prototxt\",\n default=\"D:/01_CaoJunhao/FaceDetectSSD/deploy.prototxt\",\n help=\"path to Caffe 'deploy' prototxt file\")\nap.add_argument(\"-f\", \"--face_detector\",\n type=str,\n default=\"D:/01_CaoJunhao/FaceDetectSSD/VGG_WIDERFace_SSD_300x300_iter_120000.caffemodel\",\n help=\"path to face detector model directory\")\nap.add_argument(\"-m\", \"--model\",\n type=str,\n default='DenseNet201_mask_detector.model',\n help=\"path to trained face mask detector model\")\nap.add_argument(\"-c\", \"--confidence\",\n type=float,\n default=0.5,\n help=\"minimum probability to filter weak detections\")\nargs = vars(ap.parse_args())\nprint(args)\n\n# Load the face detector from the disk\nface_net = cv2.dnn.readNetFromCaffe(prototxt=args['prototxt'],\n caffeModel=args['face_detector'])\nprint(face_net)\n\n# Load the mask detection model from the disk\nmask_model = load_model(args['model'])\n\n# Define the colour corresponding each situation of the mask respectively.\nlabels_dict = {0: 'Incorrect Mask',\n 1: 'Correct Mask',\n 2: \"No Mask\"}\ncolor_dict = {0: (255, 255, 0),\n 1: (0, 255, 0),\n 2: (0, 0, 255)}\n\n\n# Define a methode to predict the face_mask object\ndef detect_predict_mask(frame, face_net, mask_net):\n # Acquire the dimensions of the frame and construct the blob object\n print('frame shape : {}'.format(frame.shape))\n high, weight = frame.shape[:2]\n\n blob = cv2.dnn.blobFromImage(image=frame,\n scalefactor=1.0,\n size=(300, 300),\n mean=(104.0, 177.0, 123.0))\n # Pass the blob through the network and obtain the face detections\n face_net.setInput(blob)\n detections = face_net.forward()\n print('detections shape : ', detections.shape)\n print('detections shape[2] : ', detections.shape[2])\n print(detections)\n\n # Initialize the list of faces object, their corresponding locations, and the one of predictions from the face mask\n faces = []\n locations = []\n predictions = []\n\n # Loop over the detections\n for i in range(0, detections.shape[2]):\n # Extract the confidence associated with the detection\n confidence = detections[0, 0, i, 2]\n\n # Cut off weak detections by guaranteeing confidence is greater than the minimum confidence\n if confidence > args['confidence']:\n # Compute the (x,y) -- coordinates of the bounding box for each object\n bounding_box_object = detections[0, 0, i, 3:7] * np.array([weight, high, weight, high])\n start_x, start_y, end_x, end_y = bounding_box_object.astype('int')\n\n # Guaranteeing the bounding boxes fall within the frame\n (start_x, start_y) = (max(0, start_x - 7), max(0, start_y - 7))\n (end_x, end_y) = (min(weight, end_x + 7), min(high, end_y + 7))\n\n # Extract the ROI (Region of interest)\n face = frame[start_y:end_y, start_x:end_x]\n # Convert it from BGR to RGB\n face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)\n # Resize it to 224*224\n face = cv2.resize(face, (224, 224))\n # Transform face into numpy array\n face = img_to_array(face)\n # processing it\n face = preprocess_input(face)\n print(face)\n # Add the face and the location of the bounding box to respective list\n faces.append(face)\n locations.append((start_x, start_y, end_x, end_y))\n\n # To make the prediction is only in the case of at least existing one face.\n if len(faces) > 0:\n faces = np.array(faces, dtype='float32')\n predictions = mask_net.predict(faces, batch_size=32)\n\n return locations, predictions\n\n\n# Loop over the frames from video stream\nvs = VideoStream(src=0).start()\n# Initialize the video stream and allow it to warm up\nwhile True:\n # Acquire the frame from the threaded video stream\n video_stream_read = vs.read()\n # Resize it to change into a maximum width of 400 pixels\n frame = imutils.resize(video_stream_read, width=600)\n\n # Detect the face object in the frame and determine whether or not the face object is wearing the mask\n locations, predictions = detect_predict_mask(frame=frame, face_net=face_net, mask_net=mask_model)\n\n # Traverse the detected face object and corresponding locations\n for (bounding_box, prediction) in zip(locations, predictions):\n # Unbox the bounding box and prediction\n start_x, start_y, end_x, end_y = bounding_box\n print('prediction : {} '.format(prediction))\n print(type(prediction))\n (Incorrect_Mask, Correct_Mask, No_Mask) = prediction\n label_index = np.argmax(prediction)\n face_label = labels_dict[label_index]\n color_label = color_dict[label_index]\n\n # Append the probability into the label\n label = '{}: {:.4f}%'.format(face_label, max(Incorrect_Mask, Correct_Mask, No_Mask) * 100)\n\n # Display the label and bounding box on the output frame\n cv2.putText(img=frame,\n text=label,\n org=(start_x, start_y - 10),\n fontFace=cv2.FONT_HERSHEY_SIMPLEX,\n fontScale=0.50,\n color=color_label,\n thickness=2)\n cv2.rectangle(img=frame,\n pt1=(start_x, start_y),\n pt2=(end_x, end_y),\n color=color_label,\n thickness=2)\n # Show the frame\n cv2.imshow('MyFrame', frame)\n ff = 0xFF\n key = cv2.waitKey(1) & ff\n\n if key == ord('q'):\n break\n\n# Cleanup\ncv2.destroyAllWindows()\nvs.stop()\n\n","sub_path":"04_Mask_Detection_Real-Time-Stream.py","file_name":"04_Mask_Detection_Real-Time-Stream.py","file_ext":"py","file_size_in_byte":6644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"228189888","text":"from functools import partial\nimport os, json\nfrom datetime import datetime\nimport requests\nimport base64\n\nimport logging\nLOG = logging.getLogger(__name__)\n\ndef first(x):\n try:\n return x[0]\n except (IndexError, KeyError, TypeError):\n return None\n\ndef firstnn(lst):\n \"returns first non-nil value in lst or None\"\n return first(filter(None, lst))\n \ndef lookup(data, path, default=0xDEADBEEF):\n try:\n bits = path.split('.', 1)\n if len(bits) > 1:\n bit, rest = bits\n else:\n bit, rest = bits[0], []\n val = data[bit]\n if rest:\n return lookup(val, rest, default)\n return val\n except KeyError:\n if default == 0xDEADBEEF:\n raise\n return default\n\ndef once_a_day(key, func):\n \"simplistic cache that expires result once a day\"\n # ll: /tmp/salt-20151231-foobar.cache\n key = key.replace('/', '--')\n keyfile = '/tmp/salt-' + datetime.now().strftime('%Y%m%d-') + key + '.cache'\n if os.path.exists(keyfile):\n LOG.info(\"cache hit! %r\", keyfile)\n return json.load(open(keyfile, 'r'))\n LOG.info(\"cache miss! %r\", keyfile)\n resp = func()\n json.dump(resp, open(keyfile, 'w'))\n return resp\n\ndef reachable(url):\n \"return True if given url can be hit.\"\n LOG.info('hitting %r', url)\n try:\n resp = requests.head(url, allow_redirects=False, timeout=0.25)\n return resp.status_code == 200\n except (requests.ConnectionError, requests.Timeout):\n # couldn't connect for whatever reason\n return False\n\n#\n# \n#\n\ndef rev():\n \"\"\"used in the `git.latest` state for the `rev` attribute.\n Prefer a commit if specified in revision, otherwise a branch name\n and when there's nothing specified default to master\"\"\"\n return cfg('project.revision', 'project.branch', 'master')\n\ndef branch(default='master'):\n \"\"\"used in the `git.latest` state for the `branch` attribute.\n If a specific revision exists DON'T USE THE BRANCH VALUE. \n There will always be a branch value, even if it's the 'master' default\"\"\"\n if cfg('project.revision'):\n return '' # results in a None value for git.latest\n return cfg('project.branch', default)\n\ndef read_json(path):\n \"reads the json from the given `path`, detecting base64 encoded versions.\"\n if os.path.exists(path):\n contents = open(path, 'r').read()\n if path.endswith('.b64'):\n # file is base64 encoded\n contents = base64.b64decode(contents)\n try:\n return json.loads(contents)\n except ValueError:\n # there is a bug where json is not properly escaped.\n LOG.error(\"failed to deserialize %r as json: %r\", path, contents)\n\ndef project_name():\n \"salt['elife.cfg']('project.project_name') works as well, but not on vagrant machines\"\n return first(__grains__['id'].split('--'))\n\ndef cfn():\n \"returns whatever cfn output data it can find.\"\n return read_json(\"/etc/cfn-info.json\") or {}\n\ndef cfg(*paths):\n \"\"\"returns the value at the given dot-delimited path within the project config.\n if just one path is specified, the default is None.\n if more than one path is specified, the value of the last path is the default.\n THIS MEANS IF YOU SPECIFY MORE THAN ONE PATH YOU MUST SPECIFY A DEFAULT\"\"\"\n default = paths[-1] if len(paths) > 1 else None \n paths = paths[:-1] if len(paths) > 1 else paths\n data = {\n 'project': read_json('/etc/build-vars.json.b64') or {}, # template 'compile' time data\n 'cfn': cfn() # stack 'creation' time data\n }\n # don't raise exceptions if path value not found. very django-like\n return firstnn(map(lambda path: lookup(data, path, default=None), paths)) or default \n\ndef b64encode(string):\n # used by the salt/elife-website/load-tester.sh:21\n # TODO: investigate using `base64` rather than code\n return base64.b64encode(string)\n\ndef only_on_aws():\n LOG.info('cfn is %s', cfn())\n return cfn() != {}\n","sub_path":"_modules/elife.py","file_name":"elife.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"505050240","text":"#-*- coding: utf-8 -*- \r\nimport pandas as pd\r\nimport time\r\nimport sys\r\n\r\ndf=pd.read_csv(\"userdataset.csv\")\r\nprint(\"현재 userdataset.csv 파일 내용\\n\",df)\r\nprint(len(df))\r\ntime.sleep(1)\r\nprint(\"정말 삭제하시겠습니까?\")\r\nprint(\"삭제시 복구가 불가능합니다.\")\r\nprint(\"삭제하고싶으면 y 아니면 n\")\r\nwhile True:\r\n yn=input()\r\n if yn=='y' or yn=='Y':\r\n df=pd.DataFrame(columns=['user','id'])\r\n df.to_csv(\"userdataset.csv\")\r\n print(\"삭제하였습니다.\")\r\n print(\"프로그램은 자동으로 종료됩니다.\")\r\n time.sleep(1)\r\n sys.exit()\r\n elif yn=='n' or yn=='N':\r\n print(\"데이터는 그대로 보존됩니다.\")\r\n print(\"프로그램은 자동으로 종료됩니다.\")\r\n print(\"현재 userdataset.csv 파일 내용\\n\",df)\r\n time.sleep(2)\r\n sys.exit()\r\n else:\r\n print(\"입력이 잘못됬습니다. y또는 n을 입력해주세요.\")\r\n continue\r\n","sub_path":"ver0.2/static/dataset/데이터프레임 삭제_2.py","file_name":"데이터프레임 삭제_2.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"348533522","text":"import numpy as np\nimport networkx as nx\nimport argparse\nimport random\nfrom models.distance import get_dist_func\n\n\ndef get_fitness(solution, node_list):\n \"\"\"\n Get fitness of solution encoded by permutation.\n \n Args:\n solution (numpy.ndarray): Solution encoded as a permutation\n node_list (list): List of node IDs in network\n \n Returns:\n (float): Fitness of specified solution\n \"\"\"\n \n # Append path back to initial node.\n solution_aux = np.hstack((solution, solution[0]))\n\n # Compute fitness.\n return np.sum([dist_func(node_list[el[0]], node_list[el[1]]) \n for el in [(solution_aux[idx], solution_aux[idx+1]) \n for idx in range(len(solution_aux)-1)]])\n\n\ndef crossover(inst1, inst2, p_mut):\n \"\"\"\n Perform crossover operation between two solutions encoded in permutation\n lists.\n\n Args:\n inst1 (list): First solution\n inst2 (list): Second solution\n \n Returns:\n (tuple): Offspring (results) of crossover\n\n \"\"\"\n \n # Cut solutions at random points.\n c1 = inst1[:np.random.randint(1, len(inst1))]\n c2 = inst2[:np.random.randint(1, len(inst2))]\n\n # Append elements in second solution in order found.\n offspring1 = np.hstack((c1, inst2[~np.in1d(inst2, c1)]))\n offspring2 = np.hstack((c2, inst1[~np.in1d(inst1, c2)]))\n\n # Apply mutations with specified probability.\n if np.random.rand() < p_mut:\n p1 = np.random.randint(0, len(offspring1))\n p2 = np.random.randint(0, len(offspring1))\n offspring1[[p1, p2]] = offspring1[[p2, p1]]\n if np.random.rand() < p_mut:\n p1 = np.random.randint(0, len(offspring2))\n p2 = np.random.randint(0, len(offspring2))\n offspring2[[p1, p2]] = offspring2[[p2, p1]]\n \n # Return the offspring.\n return offspring1, offspring2\n\n\ndef tournament(population, num_in_group, p_mut):\n \"\"\"\n Perform tournament selection and replace worst two members of\n each tournament with results of performing crossover between two\n winning members.\n\n Args:\n population (list): Population of solutions sorted by fitness\n num_in_group (int): Number of solutions in each tournament\n p_mut (float): Mutation probability\n\n Returns:\n population (list): Population after performing tournament selection\n and crossover.\n\n \"\"\"\n \n # Go over groups.\n for idx in range(0, len(population), num_in_group):\n\n # Get next group.\n group = population[idx:idx+num_in_group]\n\n # Compute probabilities of selecting each solution.\n p = 0.9*np.ones(len(group), dtype=float)\n p_opp = 1 - p\n p_sel = p*(p_opp**np.arange(len(group)))\n\n # Get winners.\n breeders_idx = np.random.choice(range(len(group)), size=2, replace=False, p=p_sel/np.sum(p_sel))\n\n # Perform crossover of winners, replace worst solutions in group and add back to population.\n offspring1, offspring2 = crossover(*[group[idx] for idx in breeders_idx], p_mut)\n group[-2:] = [offspring1, offspring2]\n population[idx:idx+num_in_group] = group\n\n # Return population after tournament selection and crossover operations.\n return population\n\n\ndef genetic(network, max_it=300, population_size=30, method='ranked', breeding_coeff=0.5, num_in_group=4, p_mut=0.08):\n \"\"\"\n Approximate solution to travelling salesman problem using genetic algorithms.\n\n Args:\n network (object): Networkx representation of the network\n max_it (int): Maximum iterations to perform\n population_size (int): Population size\n method (str): Method used to update population. Valid values are 'ranked' and 'tournament'\n breeding_coeff (float): Fraction of best ants to use in crossover and fraction of worst ants to\n replace with offspring (ranked method)\n num_in_group (int): Number of solutions in each tournament (tournament method)\n p_mut (float): Probability of mutation\n \"\"\"\n \n # Check if method parameter value is valid.\n if method not in {'ranked', 'tournament'}:\n raise(ValueError('unknown method parameter value'))\n \n # Initialize list for storing edge lists (for animations).\n edgelists = []\n\n # Get list of node IDs.\n node_list = list(network.nodes())\n\n # Initialize population using random solutions.\n population = [np.random.permutation(np.arange(len(node_list))) \n for _ in range(population_size)]\n \n # Get initial best solution and fitness.\n initial_best = sorted([(inst, get_fitness(inst, node_list)) \n for inst in population], key=lambda x: x[1])\n \n # Initialize dictionary for storing global best solution and its fitness.\n global_best = {\n 'fitness' : initial_best[0][1],\n 'solution' : initial_best[0][0]\n }\n \n # Main iteration loop\n for it_idx in range(max_it):\n\n # Print iteration index and best fitness.\n print('iteration: {0}'.format(it_idx))\n print('best fitness: {0}'.format(global_best['fitness']))\n\n # Evaluate and sort population\n evaluated = sorted([(inst, get_fitness(inst, node_list)) \n for inst in population], key=lambda x: x[1])\n\n # Check best in population agains global best.\n if evaluated[0][1] < global_best['fitness']:\n global_best['fitness'] = evaluated[0][1]\n global_best['solution'] = evaluated[0][0]\n solution = np.hstack((global_best['solution'], global_best['solution'][0]))\n edgelists.append([(node_list[solution[idx]], node_list[solution[idx+1]]) for idx in range(len(solution)-1)])\n\n if method == 'ranked':\n # if performing ranked selection.\n\n # Get sorted population.\n sorted_population = list(map(lambda x: x[0], evaluated))\n \n # Get number of breeders and make sure number is even.\n n_breeders = int(np.ceil(breeding_coeff*len(evaluated)))\n n_breeders += n_breeders % 2\n\n # Get breeders.\n breeders = sorted_population[:n_breeders]\n\n # Initialize list for storing offspring.\n offspring = []\n\n # Perform crossover among pairs of breeders.\n for idx in range(0, len(breeders) - 1, 2):\n offspring1, offspring2 = crossover(breeders[idx], breeders[idx+1], p_mut)\n \n # Apply mutations with specified probability.\n if np.random.rand() < p_mut:\n p1 = np.random.randint(0, len(offspring1))\n p2 = np.random.randint(0, len(offspring1))\n offspring1[[p1, p2]] = offspring1[[p2, p1]]\n if np.random.rand() < p_mut:\n p1 = np.random.randint(0, len(offspring2))\n p2 = np.random.randint(0, len(offspring2))\n offspring2[[p1, p2]] = offspring2[[p2, p1]]\n \n # Add offspring to list.\n offspring.extend([offspring1, offspring2])\n\n # Replace worst solution in population with offspring of selected breeders.\n sorted_population[-n_breeders:] = offspring\n population = sorted_population\n\n elif method == 'tournament':\n # If performing tournament selection.\n\n # Perform tournament selection and crossover to get updated population.\n population = tournament(list(map(lambda x: x[0], evaluated)), num_in_group, p_mut)\n\n # Return best found solution, fitness value of best found solution, initial best fitness value and \n # edgelist of network states corresponding to global best position updates.\n return global_best['solution'], global_best['fitness'], initial_best[0][1], edgelists\n\n\nif __name__ == '__main__':\n\n ### PARSE ARGUMENTS ###\n parser = argparse.ArgumentParser(description='Approximate solution to TSP using particle swarm optimization.')\n parser.add_argument('--num-nodes', type=int, default=30, help='Number of nodes to use')\n parser.add_argument('--dist-func', type=str, default='geodesic', choices=['geodesic', 'learned'], \n help='Distance function to use')\n parser.add_argument('--prediction-model', type=str, default='gboosting', choices=['gboosting', 'rf'], \n help='Prediction model to use for learned distance function')\n parser.add_argument('--max-it', type=int, default=500, help='Number of iterations to perform')\n parser.add_argument('--population-size', type=int, default=50, help='Population size to use')\n parser.add_argument('--method', type=str, choices=['ranked', 'tournament'], default='ranked', help='Population update method to use')\n parser.add_argument('--breeding-coeff', type=float, default=0.5, \n help='Fraction of best solution for which to perform crossover and fraction of worst solution to replace by offspring (ranked method)')\n parser.add_argument('--num-in-group', type=int, default=10, help='Tournament size (tournament method)')\n parser.add_argument('--p-mut', type=float, default=0.08, help='Mutation probability')\n args = parser.parse_args()\n #######################\n\n # Parse problem network.\n network = nx.read_gpickle('./data/grid_data/grid_network.gpickle')\n \n # Number of nodes to remove from network.\n to_remove = network.number_of_nodes() - args.num_nodes\n \n # Remove randomly sampled nodes to get specified number of nodes.\n network.remove_nodes_from(random.sample(list(network.nodes), to_remove))\n\n # Get distance function.\n dist_func = get_dist_func(network, which=args.dist_func, prediction_model=args.prediction_model)\n \n # Get solution using genetic algorithm. \n solution, solution_fitness, initial_fitness, edgelists = genetic(network, max_it=args.max_it, population_size=args.population_size, \n method=args.method, breeding_coeff=args.breeding_coeff, num_in_group=args.num_in_group, p_mut=args.p_mut)\n\n # Save list of edge lists for animation.\n np.save('./results/edgelists/edgelist_tsp_genetic2.npy', list(map(np.vstack, edgelists)))\n nx.write_gpickle(network, './results/networks/network_tsp_genetic2.gpickle')\n \n # Print best solution fitness.\n print('Fitness of best found solution: {0:.3f}'.format(solution_fitness))\n \n # Print initial best fitness.\n print('Fitness of initial solution: {0:.3f}'.format(initial_fitness))\n\n # Print increase in fitness.\n print('Fitness value improved by: {0:.3f}%'.format(100*initial_fitness/solution_fitness))\n\n","sub_path":"tsp_genetic.py","file_name":"tsp_genetic.py","file_ext":"py","file_size_in_byte":10589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"118450611","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nimport os\nimport subprocess\nimport io\nimport re\nfrom glob import glob\nfrom os.path import basename\nfrom os.path import dirname\nfrom os.path import join\nfrom os.path import splitext\n\nfrom setuptools import find_packages\nfrom setuptools import setup\nfrom setuptools.command.install import install as DistutilsInstall\n\n\nclass MyInstall(DistutilsInstall):\n\n def run(self):\n\n mccortex_dir = os.path.dirname(os.path.realpath(__file__))+\"/mccortex\"\n if not os.path.exists(mccortex_dir):\n subprocess.call(\n [\"git\", \"clone\", \"--recursive\", \"-b\", \"geno_kmer_count\", \"https://github.com/phelimb/mccortex\", mccortex_dir], cwd=os.path.dirname(os.path.realpath(__file__)))\n subprocess.call(\n [\"make\", \"clean\"], cwd=mccortex_dir)\n subprocess.call(\n [\"make\"], cwd=mccortex_dir)\n subprocess.call(\n [\"cp\", \"bin/mccortex31\", \"%s/bin/\" % os.environ.get('VIRTUAL_ENV', '/usr/local/')], cwd=mccortex_dir)\n DistutilsInstall.run(self)\n\n\ndef read(*names, **kwargs):\n return io.open(\n join(dirname(__file__), *names),\n encoding=kwargs.get('encoding', 'utf8')\n ).read()\n\n\nsetup(\n name='mykrobe',\n version='0.1.1',\n license='MIT',\n description='Mykrobe atlas',\n # long_description='%s\\n%s' % (\n # re.compile('^.. start-badges.*^.. end-badges',\n # re.M | re.S).sub('', read('README.md')),\n # re.sub(':[a-z]+:`~?(.*?)`', r'``\\1``', read('CHANGELOG.rst'))\n # ),\n author='Phelim Bradley',\n author_email='wave@phel.im',\n url='https://github.com/phelimb/mykrobe-atlas-cli',\n packages=find_packages('src'),\n package_dir={'': 'src'},\n py_modules=[splitext(basename(path))[0] for path in glob(\n 'src/*.py')]+[splitext(basename(path))[0] for path in glob('src/*/*.py')]+[splitext(basename(path))[0] for path in glob('src/*/*/*.py')],\n include_package_data=True,\n zip_safe=False,\n classifiers=[\n 'Intended Audience :: Developers',\n 'Operating System :: Unix',\n 'Operating System :: POSIX',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: Implementation :: CPython',\n 'Programming Language :: Python :: Implementation :: PyPy',\n 'Topic :: Utilities',\n ],\n keywords=[\n # eg: 'keyword1', 'keyword2', 'keyword3',\n ],\n install_requires=[\n 'Biopython',\n \"pyvcf\",\n 'mongoengine',\n # eg: 'aspectlib==1.1.1', 'six>=1.7',\n ],\n extras_require={\n # eg:\n # 'rst': ['docutils>=0.11'],\n # ':python_version==\"2.6\"': ['argparse'],\n },\n entry_points={\n 'console_scripts': [\n 'mykrobe = mykrobe.cli:main',\n ]\n },\n cmdclass={'install': MyInstall}\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"293251463","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nfrom typing import List\n\n\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n dt = {}\n n = len(nums)\n for i in range(n):\n if target - nums[i] in dt:\n return [dt[target - nums[i]], i]\n dt[nums[i]] = i\n","sub_path":"字节/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"569062976","text":"import os\nimport pandas as pd\nfrom quaternions import quaternion_filtration\nfrom frequencyDomain import habitual_filtration\nimport cv2\nimport argparse\n\n# DataSet used: LIVE Image Quality Assessment Database\nparser = argparse.ArgumentParser(description='Generate a csv file with metrics to habitual and quaternionic approach')\nparser.add_argument('dir_original_images_path', help='Path to original images directory')\nparser.add_argument('dirs_modified_images_path', help='Path to dir with modified images directories')\n\n\ndef generate_dataframe(args):\n dir_original_images_path = args.dir_original_images_path\n dirs_modified_images_path = args.dirs_modified_images_path\n\n df = pd.DataFrame(\n {'Problem': [], 'Quaternion_RMSE': [], 'Habitual_RMSE': [], 'Quaternion_SSIM': [], 'Habitual_SSIM': [],\n 'Quaternion_Time': [], 'Habitual_Time': []})\n dirs = os.listdir(dirs_modified_images_path)\n\n filters = [\n {'name': 'ideal_filter', 'band': 'low_pass'},\n {},\n {},\n {},\n {},\n {}\n ]\n\n for dir in dirs:\n if not os.path.isdir(dir):\n continue\n quaternion_metric, habitual_metric = generate_metrics(dir_original_images_path,\n os.path.join(dirs_modified_images_path, dir),\n filters.pop(0))\n df.append([dir, quaternion_metric['rmse'], habitual_metric['rmse'],\n quaternion_metric['ssim'], habitual_metric['ssim'],\n quaternion_metric['time'], habitual_metric['time']])\n df.to_csv('metrics.csv', index=False)\n\n\ndef generate_metrics(dir_original_images, dir_modified_images, filter):\n images = os.listdir(dir_modified_images)\n images_relation = images.pop(\n images.index('info.txt')) # a link of modified images with its respective original images\n with open(os.path.join(dir_modified_images, images_relation)) as f:\n lines = f.readlines()\n df_images_relation = pd.DataFrame(\n {'Original': [x.split()[0] for x in lines], 'Modified': [x.split()[1] for x in lines]})\n\n quaternion_metric_values = {'rmse': [], 'ssim': [], 'time': []}\n habitual_metric_values = {'rmse': [], 'ssim': [], 'time': []}\n\n for image_name in images:\n image = cv2.imread(os.path.join(dir_modified_images, image_name))\n original_image_path = os.path.join(dir_original_images,\n df_images_relation[df_images_relation['Modified'] == image_name]['Original'])\n original_image = cv2.imread(original_image_path)\n\n quaternion_filtered_image, quaternion_time = quaternion_filtration(image, filter)\n habitual_filtered_image, habitual_time = habitual_filtration(image, filter)\n\n quaternion_metric_values['rmse'].append(rmse(original_image, quaternion_filtered_image))\n quaternion_metric_values['ssim'].append(ssim(original_image, quaternion_filtered_image))\n quaternion_metric_values['time'].append(quaternion_time)\n habitual_metric_values['rmse'].append(rmse(original_image, habitual_filtered_image))\n habitual_metric_values['ssim'].append(ssim(original_image, habitual_filtered_image))\n habitual_metric_values['time'].append(habitual_time)\n\n quaternion_metric = {'rmse': sum(quaternion_metric_values['rmse']) / len(quaternion_metric_values['rmse']),\n 'ssim': sum(quaternion_metric_values['ssim']) / len(quaternion_metric_values['ssim']),\n 'time': sum(quaternion_metric_values['time']) / len(quaternion_metric_values['time'])}\n habitual_metric = {'rmse': sum(habitual_metric_values['rmse']) / len(habitual_metric_values['rmse']),\n 'ssim': sum(habitual_metric_values['ssim']) / len(habitual_metric_values['ssim']),\n 'time': sum(quaternion_metric_values['time']) / len(quaternion_metric_values['time'])}\n\n return quaternion_metric, habitual_metric\n\n\ndef rmse(image1, image2):\n pass\n\n\ndef ssim(image1, image2):\n pass\n\n\nif __name__ == '__main__':\n generate_dataframe(parser.parse_args())\n","sub_path":"get_metrics.py","file_name":"get_metrics.py","file_ext":"py","file_size_in_byte":4168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"412442199","text":"import requests\nfrom API_ENV import YOUTUBE_API_URL, YOUTUBE_API_KEY, TAMTAM_API_URL, TAMTAM_API_KEY\n\n\ndef input_and_validation():\n print('Video 이름 입력: ', end='')\n video_name = input()\n if not video_name:\n print('ERROR: Video 이름이 입력되지 않았습니다.')\n exit()\n\n print('Video Youtube Id 입력: ', end='')\n video_youtube_id = input()\n if not video_youtube_id:\n print('ERROR: Video Youtube Id가 입력되지 않았습니다.')\n exit()\n\n print('Channel Youtube Id 입력: ', end='')\n channel_youtube_id = input()\n if not channel_youtube_id:\n print('ERROR: Channel Youtube Id가 입력되지 않았습니다.')\n exit()\n\n # channel_youtube_id로 channel_id 찾기\n url = f'{TAMTAM_API_URL}/channel/youtube/{channel_youtube_id}'\n headers = {'company_id': TAMTAM_API_KEY}\n channel_information = requests.get(url=url, headers=headers)\n if not channel_information.json():\n print('ERROR: Channel Youtube Id 정보가 잘못되었습니다.')\n exit()\n channel_id = channel_information.json()[0]['_id']\n\n # Youtube API: 비디오 정보 확인\n url = f'{YOUTUBE_API_URL}/videos'\n params = {\n 'key': YOUTUBE_API_KEY,\n 'part': 'id, snippet, statistics',\n 'id': video_youtube_id,\n }\n video_information = requests.get(url=url, params=params)\n if not video_information.json():\n print('ERROR: Video Youtube Id 정보가 잘못되었습니다.')\n exit()\n print(video_information.json())\n\n return video_name, video_youtube_id, channel_id, channel_youtube_id, video_information\n","sub_path":"AI/input_and_validation_module.py","file_name":"input_and_validation_module.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"81523765","text":"#!/usr/bin/env python\n\n# Run one of the samples through an image modification\n\nfrom PIL import Image, ImageEnhance\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--source\", help=\"Image file name\",\n type=str,required=True)\nparser.add_argument(\"--colour\", help=\"Colour scale factor\",\n type=float,default=1.0)\nparser.add_argument(\"--contrast\", help=\"Contrast scale factor\",\n type=float,default=1.0)\nparser.add_argument(\"--brightness\", help=\"Brightness scale factor\",\n type=float,default=1.0)\nparser.add_argument(\"--sharpness\", help=\"Sharpness scale factor\",\n type=float,default=1.0)\nparser.add_argument(\"--opfile\", help=\"Output file name\",\n default=\"modified.jpg\",\n type=str,required=False)\nargs = parser.parse_args()\n\nim = Image.open(args.source)\n\nif args.colour != 1.0:\n enhancer = ImageEnhance.Color(im)\n im = enhancer.enhance(args.colour)\n\nif args.contrast != 1.0:\n enhancer = ImageEnhance.Contrast(im)\n im = enhancer.enhance(args.contrast)\n\nif args.brightness != 1.0:\n enhancer = ImageEnhance.Brightness(im)\n im = enhancer.enhance(args.brightness)\n\nif args.sharpness != 1.0:\n enhancer = ImageEnhance.Sharpness(im)\n im = enhancer.enhance(args.sharpness)\n\nim.save(args.opfile)\n\n","sub_path":"analyses/OCR-weatherrescue/scripts/modify.py","file_name":"modify.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"191368624","text":"import sys\nimport os\nprint(\"adding: \", os.getcwd(), \" to path\")\nsys.path.append(os.getcwd())\nimport time\nimport pandas as pd\nimport tensorflow as tf\nimport numpy as np\nfrom tqdm import tqdm\nimport gc\n\nfrom reco_utils.recommender.ncf.ncf_singlenode import NCF\nfrom reco_utils.recommender.ncf.dataset import Dataset as NCFDataset\nfrom reco_utils.dataset import movielens\nfrom reco_utils.common.notebook_utils import is_jupyter\nfrom reco_utils.dataset.python_splitters import python_chrono_split\nfrom reco_utils.evaluation.python_evaluation import (rmse, mae, rsquared, exp_var, map_at_k, ndcg_at_k, precision_at_k, \n recall_at_k, get_top_k_items)\n\nprint(\"System version: {}\".format(sys.version))\nprint(\"Pandas version: {}\".format(pd.__version__))\nprint(\"Tensorflow version: {}\".format(tf.__version__))\n# add gpu growth flags\n# tf_config.gpu_options.allow_growth = True\n# tf_config.gpu_options.per_process_gpu_memory_fraction = 0.1\n\n# top k items to recommend\nTOP_K = 10\n\n# Model parameters\nEPOCHS = 50 \nBATCH_SIZE = 32\n\nSEED = 42\ndataset = \"ciao\"\nif dataset ==\"ciao\":\n data_path = \"/cluster/home/it_stu110/data/ciao/ciao_with_rating_timestamp/rating_with_timestamp.mat\"\n import scipy.io as scio\n data = scio.loadmat(data_path)\n # userid, productid, categoryid, rating, helpfulness and time point\n df = pd.DataFrame(data['rating'][:,[0,1,3,5]], columns=[\"userID\", \"itemID\", \"rating\", \"timestamp\"])\nelif dataset ==\"yelp_ON\":\n data_path = \"/cluster/home/it_stu110/data/yelp/state/ON_reindex.csv\"\n df = pd.read_csv(data_path,index_col = 0)[['user_id','business_id','stars','date']]\n df.columns = [\"userID\", \"itemID\", \"rating\", \"timestamp\"]\nelif dataset == \"movielens\":\n MOVIELENS_DATA_SIZE = '100k'\n df = movielens.load_pandas_df(\n size=MOVIELENS_DATA_SIZE,\n header=[\"userID\", \"itemID\", \"rating\", \"timestamp\"]\n )\n\n\n# Select MovieLens data size: 100k, 1m, 10m, or 20m\n# MOVIELENS_DATA_SIZE = '100k'\n# df = movielens.load_pandas_df(\n# size=MOVIELENS_DATA_SIZE,\n# header=[\"userID\", \"itemID\", \"rating\", \"timestamp\"]\n# )\n\n\ntrain, test = python_chrono_split(df, 0.75)\nprint(\"start getting data\")\n'''\ndata = NCFDataset(train=train, test=test, seed=SEED)\nprint(\"start getting model\")\nmodel = NCF (\n n_users=data.n_users, \n n_items=data.n_items,\n model_type=\"NeuMF\",\n n_factors=4,\n layer_sizes=[16,8,4],\n n_epochs=EPOCHS,\n batch_size=BATCH_SIZE,\n learning_rate=1e-3,\n verbose=1,\n seed=SEED\n)\nprint(\"start training data\")\nstart_time = time.time()\n\nmodel.fit(data)\n\ntrain_time = time.time() - start_time\n\nprint(\"Took {} seconds for training.\".format(train_time))\n\nsave_dir = os.getcwd() + \"/logs/{}/\".format(dataset)\nmodel.save(save_dir)\n\nstart_time = time.time()\n\nusers, items, preds = [], [], []\nitem = list(train.itemID.unique())\nfor user in train.userID.unique():\n user = [user] * len(item) \n users.extend(user)\n items.extend(item)\n preds.extend(list(model.predict(user, item, is_list=True)))\n\n\n# num_batches = len(preds/BATCH_SIZE)\n# for batch_idx in range(num_batches-1):\n# start = batch_idx * BATCH_SIZE\n# end = (batch_idx+1) * BATCH_SIZE\n# all_predictions = pd.DataFrame(data={\"userID\": users[start:end], \"itemID\":items[start:end], \"prediction\":preds[start:end]})\nall_predictions = pd.DataFrame(data={\"userID\": users, \"itemID\":items, \"prediction\":preds})\n\nall_predictions.to_csv(save_dir + \"all_predictions.csv\")\n\n################################################################\nmerged = pd.merge(train, all_predictions, on=[\"userID\", \"itemID\"], how=\"outer\")\nall_predictions = merged[merged.rating.isnull()].drop('rating', axis=1)\n\nall_predictions.to_csv(save_dir + \"all_predictions_merged.csv\")\n\ntest_time = time.time() - start_time\nprint(\"Took {} seconds for prediction.\".format(test_time))\neval_map = map_at_k(test, all_predictions, col_prediction='prediction', k=TOP_K)\neval_ndcg = ndcg_at_k(test, all_predictions, col_prediction='prediction', k=TOP_K)\neval_precision = precision_at_k(test, all_predictions, col_prediction='prediction', k=TOP_K)\neval_recall = recall_at_k(test, all_predictions, col_prediction='prediction', k=TOP_K)\n\nprint(\"MAP:\\t%f\" % eval_map,\n \"NDCG:\\t%f\" % eval_ndcg,\n \"Precision@K:\\t%f\" % eval_precision,\n \"Recall@K:\\t%f\" % eval_recall, sep='\\n')\n'''\n################################################################\nif dataset ==\"ciao\":\n csv_file = \"/cluster/home/it_stu110/proj/Rec_baseline/recommenders_ms/logs/ciao/all_predictions.csv\"\nelif dataset ==\"yelp_ON\":\n csv_file = \"/cluster/home/it_stu110/proj/Rec_baseline/recommenders_ms/logs/yelp_ON/all_predictions.csv\"\nall_predictions = pd.read_csv(csv_file)\nhr = []\nndcg = []\nrecall = []\n\nall_users = all_predictions[\"userID\"].unique()\nn_users = len(all_users)\nnum_batches = int(n_users/ BATCH_SIZE)\nfor batch_idx in tqdm(range(num_batches)):\n start = batch_idx * BATCH_SIZE\n end = min(( batch_idx +1 ) * BATCH_SIZE,n_users)\n batch_users = all_users[ start : end ]\n batch_predictions = all_predictions[all_predictions[\"userID\"].isin( batch_users)]\n batch_train = train[train[\"userID\"].isin( batch_users)]\n batch_merged = pd.merge(batch_train, batch_predictions, on=[\"userID\", \"itemID\"], how=\"outer\")\n batch_predictions = batch_merged[batch_merged.rating.isnull()].drop('rating', axis=1)\n batch_test = test[test[\"userID\"].isin( batch_users)]\n # eval_map = map_at_k(batch_test, batch_predictions, col_prediction='prediction', k=TOP_K)\n eval_ndcg = ndcg_at_k(batch_test, batch_predictions, col_prediction='prediction', k=TOP_K)\n eval_precision = precision_at_k(batch_test, batch_predictions, col_prediction='prediction', k=TOP_K)\n eval_recall = recall_at_k(batch_test, batch_predictions, col_prediction='prediction', k=TOP_K)\n ndcg.append(eval_ndcg)\n hr.append(eval_precision)\n recall.append(eval_recall)\n del batch_train\n del batch_predictions\n del batch_merged\n del batch_test\n gc.collect()\n\n\nprint(#\"MAP:\\t%f\" % eval_map,\n \"NDCG:\\t%f\" % np.mean(ndcg),\n \"Precision@K:\\t%f\" % np.mean(hr),\n \"Recall@K:\\t%f\" % np.mean(recall), sep='\\n')\n\n ","sub_path":"cornac/NCF.py","file_name":"NCF.py","file_ext":"py","file_size_in_byte":6174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"346549002","text":"class Pedido:\n\n def __init__(self):\n self.numero= input(\"Ingrese un numero:\\n\")\n\n def chequeo(self):\n\n if not self.numero:\n print(\"No ingreso ninguna palabra\")\n\n try:\n n=int(self.numero)\n print (n+int(2*str(n))+int(3*str(n)))\n\n except:\n print(\"Disculpe, solo acepto numeros\")\n\nif __name__ == \"__main__\":\n p = Pedido()\n p.chequeo()","sub_path":"alumnos/58004-Cercasi-Javier/Ejercicios_25-03/Ejercicio1_Cercasi_Javier.py","file_name":"Ejercicio1_Cercasi_Javier.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"463979415","text":"# -*- coding: utf-8 -*-\nfrom collections import namedtuple, defaultdict, OrderedDict\n\nfrom glr.grammar import Grammar\nfrom glr.utils import unique\n\n\nclass Item(namedtuple('Item', ['rule_index', 'dot_position'])):\n __slots__ = ()\n\n def __repr__(self):\n return '#%d.%d' % self\n\n\nState = namedtuple('State', ['index', 'itemset', 'follow_dict', 'parent_state_index', 'parent_lookahead'])\n\nAction = namedtuple('Action', ['type', 'state', 'rule_index'])\n\n\ndef iterate_lookaheads(itemset, grammar):\n for item in itemset:\n rule = grammar[item.rule_index]\n\n if item.dot_position == len(rule.right_symbols):\n # dot is in the end, there is no look ahead symbol\n continue\n\n lookahead = rule.right_symbols[item.dot_position]\n\n yield item, lookahead\n\n\ndef follow(itemset, grammar):\n \"\"\"\n All transitions from an item set in a dictionary [token]->item set\n \"\"\"\n result = OrderedDict()\n for item, lookahead in iterate_lookaheads(itemset, grammar):\n tmp = closure([Item(item.rule_index, item.dot_position + 1)], grammar)\n\n if lookahead not in result:\n result[lookahead] = []\n result[lookahead].extend(tmp)\n\n for lookahead, itemset in result.iteritems():\n yield lookahead, unique(itemset)\n\n\ndef closure(itemset, grammar):\n \"\"\"\n The epsilon-closure of this item set\n \"\"\"\n items_to_process = itemset\n visited_lookaheads = set()\n while True:\n for item in items_to_process:\n yield item\n\n nested_to_process = []\n for item, lookahead in iterate_lookaheads(items_to_process, grammar):\n if lookahead in grammar.nonterminals and lookahead not in visited_lookaheads:\n visited_lookaheads.add(lookahead)\n for rule_index in grammar.rules_for_symbol(lookahead):\n nested_to_process.append(Item(rule_index, 0))\n\n if not nested_to_process:\n # no changes\n return\n\n items_to_process = nested_to_process\n\n\ndef generate_state_graph(grammar):\n assert isinstance(grammar, Grammar)\n\n states = []\n state_by_itemset = {}\n\n first_itemset = closure([Item(0, 0)], grammar)\n first_itemset = tuple(sorted(first_itemset))\n stack = [(None, None, first_itemset)]\n while stack:\n parent_state_index, parent_lookahead, itemset = stack.pop(0)\n\n if itemset in state_by_itemset:\n # State already exist, just add follow link\n state = state_by_itemset[itemset]\n states[parent_state_index].follow_dict[parent_lookahead].add(state.index)\n continue\n\n state = State(len(states), itemset, defaultdict(set), parent_state_index, parent_lookahead)\n states.append(state)\n state_by_itemset[state.itemset] = state\n\n if parent_state_index is not None:\n states[parent_state_index].follow_dict[parent_lookahead].add(state.index)\n\n for lookahead, itemset in follow(state.itemset, grammar):\n itemset = tuple(sorted(itemset))\n stack.append((state.index, lookahead, itemset))\n return states\n\n\ndef generate_followers(grammar):\n assert isinstance(grammar, Grammar)\n\n def get_starters(symbol):\n result = []\n for rule_index in grammar.rules_for_symbol(symbol):\n rule = grammar[rule_index]\n if rule.right_symbols[0] in grammar.nonterminals:\n if rule.right_symbols[0] != symbol:\n result.extend(get_starters(rule.right_symbols[0]))\n else:\n result.append(rule.right_symbols[0])\n return result\n\n starters = dict((s, set(get_starters(s))) for s in grammar.nonterminals)\n\n def get_followers(symbol, seen_symbols=None):\n seen_symbols = seen_symbols or set()\n seen_symbols.add(symbol)\n\n result = []\n for rule in grammar.rules:\n if isinstance(rule, set): # TODO: remove workaround\n continue\n\n if symbol not in rule.right_symbols:\n continue\n\n index = rule.right_symbols.index(symbol)\n if index + 1 == len(rule.right_symbols):\n if rule.left_symbol != symbol and rule.left_symbol not in seen_symbols:\n result.extend(get_followers(rule.left_symbol, seen_symbols))\n else:\n next = rule.right_symbols[index + 1]\n if next in grammar.nonterminals:\n result.extend(starters[next])\n else:\n result.append(next)\n return result\n\n followers = dict((s, set(get_followers(s))) for s in grammar.nonterminals)\n return followers\n\n\ndef generate_action_goto_table(grammar):\n assert isinstance(grammar, Grammar)\n\n states = generate_state_graph(grammar)\n followers = generate_followers(grammar)\n\n result = []\n for state in states:\n actions = defaultdict(list)\n\n # Reduces\n for item in state.itemset:\n rule = grammar[item.rule_index]\n if item.dot_position == len(rule.right_symbols):\n if rule.left_symbol == '@':\n actions['$'].append(Action('A', None, None))\n else:\n for follower in followers[rule.left_symbol]:\n actions[follower].append(Action('R', None, item.rule_index))\n actions['$'].append(Action('R', None, item.rule_index))\n\n # Shifts & goto's\n for lookahead, state_indexes in state.follow_dict.items():\n for state_index in state_indexes:\n child_state = states[state_index]\n if lookahead in followers:\n actions[lookahead].append(Action('G', child_state.index, None))\n else:\n actions[lookahead].append(Action('S', child_state.index, None))\n\n result.append(actions)\n return result\n","sub_path":"glr/lr.py","file_name":"lr.py","file_ext":"py","file_size_in_byte":5940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"185372255","text":"from mrmoneytool.filters.date_filter import month_filter, year_filter\nfrom mrmoneytool.filters.spending_filter import spending_filter\n\n_ALL_FILTERS = [\n month_filter,\n year_filter,\n spending_filter]\n\n\ndef apply_filters(transactions, args):\n filtered_transactions = []\n for transaction in transactions:\n result = True\n for filter in _ALL_FILTERS:\n if not filter(transaction, args):\n result = False\n break\n if result:\n filtered_transactions.append(transaction)\n\n return filtered_transactions","sub_path":"mrmoneytool/filters/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"482949261","text":"\"\"\"\n写两个线程,一个线程打印1-52,另一个线程打印A-Z要求打印顺序为12A34B.....,\n不能使用sleep\n\"\"\"\nfrom threading import Thread,Lock\nlock1 = Lock()\nlock2 = Lock()\ndef print_number():\n for item in range(1,53,2):\n lock1.acquire()\n print(item,item+1,end=\"\")\n lock2.release()\n\ndef print_letter():\n list = [\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\"\n ,\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\"\n ,\"W\",\"X\",\"Y\" ,\"Z\"]\n for item in list:\n lock2.acquire()\n print(item ,end=\"\")\n lock1.release()\nt1 = Thread(target=print_number)\nt2 = Thread(target=print_letter)\nlock2.acquire()#def print_letter():堵塞\nt1.start()\nt2.start()\nt1.join()\nt2.join()","sub_path":"month02/exercise2/exercise01.py","file_name":"exercise01.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"346975635","text":"#!/usr/bin/env python3\n#\n# Copyright 2018 - The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport unittest\n\nfrom acts.config.config_entry_meta import ConfigEntryMeta\n\n\nclass ConfigEntryMetaTest(unittest.TestCase):\n \"\"\"Tests the ConfigEntryMeta class.\"\"\"\n\n def test_cli_kwargs_are_attributes_in_config_entry_meta_class(self):\n \"\"\"Tests that all cli_kwargs exist as attributes in ConfigEntryMeta.\"\"\"\n config_entry_meta = ConfigEntryMeta()\n for attribute_name in ConfigEntryMeta.cli_kwarg_attributes:\n if not hasattr(config_entry_meta, attribute_name):\n self.fail('Attribute %s exists in ConfigEntryMeta.cli_kwargs, '\n 'but is not an attribute in ConfigEntryMeta.' %\n attribute_name)\n\n def test_config_entry_meta_converts_str_cli_flags_to_a_list(self):\n \"\"\"Tests that ConfigEntryMeta's cli_flags will return as a list.\"\"\"\n self.assertTrue(\n type(ConfigEntryMeta(cli_flags='test').cli_flags) is list)\n\n def test_config_entry_meta_keeps_cli_flags_as_list(self):\n \"\"\"Tests that ConfigEntryMeta's cli_flags stays as a list.\"\"\"\n self.assertTrue(\n type(ConfigEntryMeta(cli_flags=['test']).cli_flags) is list)\n\n def test_get_cli_kwarg_with_prefix(self):\n \"\"\"Tests that a prefix-less cli_kwarg can be received.\"\"\"\n key = ConfigEntryMeta.attr_to_cli_kwarg('cli_nargs')\n self.assertEqual('nargs', key, 'The cli_ prefix was not removed '\n 'properly from the attribute.')\n\n def test_get_cli_kwarg_no_prefix(self):\n \"\"\"Tests that a prefix-less cli_kwarg can be received.\"\"\"\n kwarg = ConfigEntryMeta.attr_to_cli_kwarg('help')\n self.assertEqual('help', kwarg, 'The cli_ prefix was not removed '\n 'properly from the attribute.')\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"framework/tests/config/config_entry_meta_test.py","file_name":"config_entry_meta_test.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"536462826","text":"# legitimate use of raw DNS is for e-mails\nimport argparse\nimport dns.resolver\n\n\ndef resolve_hostname(hostname, indent=''):\n \"\"\"\"Print an A or AAAA record for `hostname`; follow CNAMEs if necessary\"\"\"\n indent += ' '\n\n answer = dns.resolver.query(hostname, 'A', raise_on_no_answer=False)\n if answer.rrset is not None:\n for record in answer:\n print(indent, hostname, f'has A address {record.address}')\n return\n\n answer = dns.resolver.query(hostname, 'AAAA', raise_on_no_answer=False)\n if answer.rrset is not None:\n for record in answer:\n print(indent, hostname, f'has AAAA address {record.address}')\n return\n\n answer = dns.resolver.query(hostname, 'CNAME', raise_on_no_answer=False)\n if answer.rrset is not None:\n record = answer[0]\n cname = record.address\n print(indent, hostname, f'is a CNAME alias for {cname}')\n resolve_hostname(cname, indent)\n return\n\n print(indent, f'ERROR: no A, AAAA or CNAME records for {hostname}')\n\n\ndef resolve_email_domain(domain):\n \"\"\"For an email adress `name@domain` find its mail server IP adresses.\"\"\"\n try:\n answer = dns.resolver.query(domain, 'MX', raise_on_no_answer=False)\n except dns.resolver.NXDOMAIN:\n print(f'Error no such domain `{domain}`')\n return\n\n if answer.rrset is not None:\n records = sorted(answer, key=lambda record: record.preference)\n for record in records:\n name = record.exchange.to_text(omit_final_dot=True)\n print(f'Priority {record.preference}')\n resolve_hostname(name)\n else:\n print(f'This domain has no explicit MX records')\n print(f'Attempting to resolve it as an A, AAAA or CNAME')\n resolve_hostname(domain)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Find mailserver IP address')\n parser.add_argument('domain', help='domaint that you want to send an email to')\n resolve_email_domain(parser.parse_args().domain)\n","sub_path":"Meet my pyppy/net/DNS/resolve_email.py","file_name":"resolve_email.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"408315574","text":"# Copyright 2012 Davoud Taghawi-Nejad\n#\n# Module Author: Davoud Taghawi-Nejad\n#\n# ABCE is open-source software. If you are using ABCE for your research you are\n# requested the quote the use of this software.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License and quotation of the\n# author. You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\"\"\"\nThe :class:`abce.agent.Agent` class is the basic class for creating your agents. It automatically handles the\npossession of goods of an agent. In order to produce/transforme goods you also need to subclass\nthe :class:`abceagent.Firm` [1]_ or to create a consumer the :class:`abce.agent.Household`.\n\nFor detailed documentation on:\n\nTrading:\n see :class:`abce.agent.Trade`\nLogging and data creation:\n see :class:`abce.agent.Database` and :doc:`simulation_results`\nMessaging between agents:\n see :class:`abce.agent.Messaging`.\n\n.. autoexception:: abce.tools.NotEnoughGoods\n\n.. [1] or :class:`abce.agent.FirmMultiTechnologies` for simulations with complex technologies.\n\"\"\"\nfrom __future__ import division\nfrom collections import OrderedDict, defaultdict\nimport numpy as np\nfrom abce.tools import *\nsave_err = np.seterr(invalid='ignore')\nfrom database import Database\nfrom networklogger import NetworkLogger\nfrom trade import Trade, Offer\nfrom messaging import Messaging, Message\nimport time\nfrom copy import copy\nimport random\nfrom abce.expiringgood import ExpiringGood\nfrom pprint import pprint\n\nclass Agent(Database, NetworkLogger, Trade, Messaging):\n \"\"\" Every agent has to inherit this class. It connects the agent to the simulation\n and to other agent. The :class:`abceagent.Trade`, :class:`abceagent.Database` and\n :class:`abceagent.Messaging` classes are included. You can enhance an agent, by also\n inheriting from :class:`abceagent.Firm`.:class:`abceagent.FirmMultiTechnologies`\n or :class:`abceagent.Household`.\n\n For example::\n\n class Household(abceagent.Agent, abceagent.Household):\n def __init__(self, simulation_parameters, agent_parameters, _pass_to_engine):\n abceagent.Agent.__init__(self, *_pass_to_engine)\n \"\"\"\n def __init__(self, simulation_parameters, agent_parameters, name, idn, group, trade_logging, database, logger):\n self.idn = idn\n \"\"\" self.idn returns the agents idn READ ONLY\"\"\"\n self.name = name\n \"\"\" name of the agent, combination of group name and id READ ONLY\"\"\"\n self.name = '%s_%i:' % (group, idn)\n \"\"\" self.name returns the agents name, which is the group name and the\n id seperated by '_' e.G. \"household_12\" READ ONLY!\n \"\"\"\n self.name_without_colon = '%s_%i' % (group, idn)\n self.group = group\n \"\"\" self.group returns the agents group or type READ ONLY! \"\"\"\n #TODO should be group_address(group), but it would not work\n # when fired manual + ':' and manual group_address need to be removed\n self._out = []\n self.simulation_parameters = simulation_parameters\n \"\"\" The simulation parameters and the number of agents in other groups\n\n Useful entries:\n\n 'num_rounds':\n the total number of rounds in the simulation.\n 'num_goup_name':\n the number of agents for each group in the simulation. e.G.\n 'num_myagents'\n \"\"\"\n self.agent_parameters = agent_parameters\n\n self.database_connection = database\n self.logger_connection = logger\n\n if trade_logging == 'individual':\n self.trade_logging = 1\n elif trade_logging == 'group':\n self.trade_logging = 2\n elif trade_logging == 'off':\n self.trade_logging = 0\n else:\n SystemExit('trade_logging wrongly defined in agent.__init__' + trade_logging)\n\n self._haves = defaultdict(float)\n\n #TODO make defaultdict; delete all key errors regarding self._haves as defaultdict, does not have missing keys\n self._haves['money'] = 0\n self._msgs = {}\n\n self.given_offers = OrderedDict()\n self.given_offers[None] = Offer(self.group, self.idn, '', '', '', 0, 1, buysell='', idn=None)\n self.given_offers[None]['status'] = 'accepted'\n self.given_offers[None]['status_round'] = 0\n self._open_offers = defaultdict(dict)\n self._answered_offers = OrderedDict()\n self._offer_count = 0\n self._reject_offers_retrieved_end_subround = []\n self._contract_requests = defaultdict(list)\n self._contract_offers = defaultdict(list)\n self._contracts_pay = defaultdict(list)\n self._contracts_deliver = defaultdict(list)\n self._contracts_payed = []\n self._contracts_delivered = []\n\n self._expiring_goods = []\n\n self._trade_log = defaultdict(int)\n self._data_to_observe = {}\n self._data_to_log_1 = {}\n self._quotes = {}\n self.round = 0\n \"\"\" self.round returns the current round in the simulation READ ONLY!\"\"\"\n self._perishable = []\n self._resources = []\n self.variables_to_track_panel = []\n self.variables_to_track_aggregate = []\n\n def possession(self, good):\n \"\"\" returns how much of good an agent possesses.\n\n Returns:\n A number.\n\n possession does not return a dictionary for self.log(...), you can use self.possessions([...])\n (plural) with self.log.\n\n Example:\n\n if self.possession('money') < 1:\n self.financial_crisis = True\n\n if not(is_positive(self.possession('money')):\n self.bancrupcy = True\n\n \"\"\"\n return float(self._haves[good])\n\n def possessions(self, list_of_goods):\n \"\"\" returns a dictionary of goods and the corresponding amount an agent owns\n\n Argument:\n A list with good names. Can be a list with a single element.\n\n Returns:\n A dictionary, that can be used with self.log(..)\n\n Examples::\n\n self.log('buget', self.possesions(['money']))\n\n self.log('goods', self.possesions(['gold', 'wood', 'grass']))\n\n have = self.possessions(['gold', 'wood', 'grass']))\n for good in have:\n if have[good] > 5:\n rich = True\n \"\"\"\n return {good: float(self._haves[good]) for good in list_of_goods}\n\n def possessions_all(self):\n \"\"\" returns all possessions \"\"\"\n return copy(self._haves)\n\n def possessions_filter(self, goods=None, but=None, match=None, beginswith=None, endswith=None):\n \"\"\" returns a subset of the goods an agent owns, all arguments\n can be combined.\n\n Args:\n goods (list, optional):\n a list of goods to return\n but(list, optional):\n all goods but the list of goods here.\n match(string, optional TODO):\n goods that match pattern\n beginswith(string, optional):\n all goods that begin with string\n endswith(string, optional)\n all goods that end with string\n is(string, optional TODO)\n 'resources':\n return only goods that are endowments\n 'perishable':\n return only goods that are perishable\n 'resources+perishable':\n goods that are both\n 'produced_by_resources':\n goods which can be produced by resources\n\n Example::\n\n self.consume(self.possessions_filter(but=['money']))\n # This is redundant if money is not in the utility function\n\n \"\"\"\n if not(goods):\n goods = self._haves.keys()\n if but != None:\n try:\n goods = set(goods) - set(but)\n except TypeError:\n raise SystemExit(\"goods and / or but must be a list e.G. ['element1', 'element2']\")\n if beginswith != None:\n new_goods = []\n for good in goods:\n if good.startswith(beginswith):\n new_goods.append(good)\n goods = new_goods\n if endswith != None:\n new_goods = []\n for good in goods:\n if good.endswith(endswith):\n new_goods.append(good)\n goods = new_goods\n return dict((good, self._haves[good]) for good in goods)\n\n def _offer_counter(self):\n \"\"\" returns a unique number for an offer (containing the agent's name)\n \"\"\"\n self._offer_count += 1\n return (self.name, self._offer_count)\n\n def _advance_round(self):\n #TODO replace OrderedDict with {}\n offer_iterator = self._answered_offers.iteritems()\n recent_answerd_offers = OrderedDict()\n try:\n while True:\n offer_id, offer = offer_iterator.next()\n if offer['round'] == self.round: # message from prelast round\n recent_answerd_offers[offer_id] = offer\n break\n while True:\n offer_id, offer = next(offer_iterator)\n recent_answerd_offers[offer_id] = offer\n except StopIteration:\n self._answered_offers = recent_answerd_offers\n\n keep = {}\n for key in self.given_offers:\n if not('status' in self.given_offers[key]):\n keep[key] = self.given_offers[key]\n elif self.given_offers[key]['status_round'] == self.round:\n keep[key] = self.given_offers[key]\n self.given_offers = keep\n\n # contracts\n self._contract_requests = defaultdict(list)\n self._contract_offers = defaultdict(list)\n self._contracts_payed = []\n self._contracts_delivered = []\n\n for good in self._contracts_deliver:\n self._contracts_deliver[good] = [contract for contract in self._contracts_deliver[good] if contract['end_date'] > self.round]\n\n for good in self._contracts_pay:\n self._contracts_pay[good] = [contract for contract in self._contracts_pay[good] if contract['end_date'] > self.round]\n\n # expiring goods\n for good in self._expiring_goods:\n self._haves[good]._advance_round()\n\n if self.trade_logging > 0:\n self.database_connection.put([\"trade_log\", self._trade_log, self.round])\n\n self._trade_log = defaultdict(int)\n\n if sum([len(offers) for offers in self._open_offers.values()]):\n pprint(dict(self._open_offers))\n raise SystemExit('%s_%i: There are offers an agent send that have not'\n 'been retrieved in this round get_offer(.)' % (self.group, self.idn))\n\n if sum([len(offers) for offers in self._msgs.values()]):\n pprint(dict(self._msgs))\n raise SystemExit('%s_%i: There are messages an agent send that have not'\n 'been retrieved in this round get_messages(.)' % (self.group, self.idn))\n\n self.round += 1\n\n def create(self, good, quantity):\n \"\"\" creates quantity of the good out of nothing\n\n Use create with care, as long as you use it only for labor and\n natural resources your model is macro-economically complete.\n\n Args:\n 'good': is the name of the good\n quantity: number\n \"\"\"\n self._haves[good] += quantity\n\n def create_timestructured(self, good, quantity):\n \"\"\" creates quantity of the time structured good out of nothing.\n For example::\n\n self.creat_timestructured('capital', [10,20,30])\n\n Creates capital. 10 units are 2 years old 20 units are 1 year old\n and 30 units are new.\n\n It can alse be used with a quantity instead of an array. In this\n case the amount is equally split on the years.::\n\n self.creat_timestructured('capital', 60)\n\n In this case 20 units are 2 years old 20 units are 1 year old\n and 20 units are new.\n\n Args:\n 'good':\n is the name of the good\n\n quantity:\n an arry or number\n \"\"\"\n length = len(self._haves[good].time_structure)\n try:\n for i in range(length):\n self._haves[good].time_structure[i] += quantity[i]\n except TypeError:\n for i in range(length):\n self._haves[good].time_structure[i] += quantity / length\n\n\n def _declare_expiring(self, good, duration):\n \"\"\" creates a good that has a limited duration\n \"\"\"\n self._haves[good] = ExpiringGood(duration)\n self._expiring_goods.append(good)\n\n def destroy(self, good, quantity):\n \"\"\" destroys quantity of the good,\n\n Args::\n\n 'good': is the name of the good\n quantity: number\n\n Raises::\n\n NotEnoughGoods: when goods are insufficient\n \"\"\"\n self._haves[good] -= quantity\n if self._haves[good] < 0:\n self._haves[good] = 0\n raise NotEnoughGoods(self.name, good, quantity - self._haves[good])\n\n def destroy_all(self, good):\n \"\"\" destroys all of the good, returns how much\n\n Args::\n\n 'good': is the name of the good\n \"\"\"\n quantity_destroyed = self._haves[good]\n self._haves[good] = 0\n return quantity_destroyed\n\n def execute(self, command, incomming_messages):\n self._out = []\n self._clearing__end_of_subround(incomming_messages)\n del incomming_messages[:]\n getattr(self, command)()\n self.__reject_polled_but_not_accepted_offers()\n return self._out\n\n def execute_parallel(self, command, incomming_messages):\n self._out = []\n try:\n self._clearing__end_of_subround(incomming_messages)\n getattr(self, command)()\n self.__reject_polled_but_not_accepted_offers()\n except KeyboardInterrupt:\n return None\n except:\n time.sleep(random.random())\n raise\n return self\n\n def execute_internal(self, command):\n getattr(self, command)()\n\n\n def _register_resource(self, resource, units, product):\n self._resources.append((resource, units, product))\n\n def _produce_resource(self):\n for resource, units, product in self._resources:\n if resource in self._haves:\n try:\n self._haves[product] += float(units) * self._haves[resource]\n except KeyError:\n self._haves[product] = float(units) * self._haves[resource]\n\n def _register_perish(self, good):\n self._perishable.append(good)\n\n def _perish(self):\n for good in self._perishable:\n if good in self._haves:\n self._haves[good] = 0\n\n def _register_panel(self, possessions, variables):\n self.possessions_to_track_panel = possessions\n self.variables_to_track_panel = variables\n\n def _register_aggregate(self, possessions, variables):\n self.possessions_to_track_aggregate = possessions\n self.variables_to_track_aggregate = variables\n\n def panel(self):\n data_to_track = {}\n for possession in self.possessions_to_track_panel:\n data_to_track[possession] = self._haves[possession]\n\n for variable in self.variables_to_track_panel:\n data_to_track[variable] = self.__dict__[variable]\n self.database_connection.put([\"panel\",\n data_to_track,\n str(self.idn),\n self.group,\n str(self.round)])\n\n def aggregate(self):\n data_to_track = {}\n for possession in self.possessions_to_track_aggregate:\n data_to_track[possession] = self._haves[possession]\n\n for variable in self.variables_to_track_aggregate:\n data_to_track[variable] = self.__dict__[variable]\n self.database_connection.put([\"aggregate\",\n data_to_track,\n self.group,\n self.round])\n\n def __reject_polled_but_not_accepted_offers(self):\n to_reject = []\n for offers in self._open_offers.values():\n for offer in offers.values():\n if offer['open_offer_status'] == 'polled':\n to_reject.append(offer)\n for offer in to_reject:\n self.reject(offer)\n\n def _clearing__end_of_subround(self, incomming_messages):\n \"\"\" agent receives all messages and objects that have been send in this\n subround and deletes the offers that where retracted, but not executed.\n\n '_o': registers a new offer\n '_d': delete received that the issuing agent retract\n '_a': clears a made offer that was accepted by the other agent\n '_p': counterparty partially accepted a given offer\n '_r': deletes an offer that the other agent rejected\n '_g': recive a 'free' good from another party\n \"\"\"\n for typ, msg in incomming_messages:\n if typ == '_o':\n msg['open_offer_status'] = 'received'\n self._open_offers[msg['good']][msg['idn']] = msg\n elif typ == '_d':\n del self._open_offers[msg['good']][msg['idn']]\n elif typ == '_a':\n offer = self._receive_accept(msg)\n if self.trade_logging == 2:\n self._log_receive_accept_group(offer)\n elif self.trade_logging == 1:\n self._log_receive_accept_agent(offer)\n elif typ == '_p':\n offer = self._receive_partial_accept(msg)\n if self.trade_logging == 2:\n self._log_receive_partial_accept_group(offer)\n elif self.trade_logging == 1:\n self._log_receive_partial_accept_agent(offer)\n elif typ == '_r':\n self._receive_reject(msg)\n elif typ == '_g':\n self._haves[msg[0]] += msg[1]\n elif typ == '_q':\n self._quotes[msg['idn']] = msg\n elif typ == '!o':\n if msg['makerequest'] == 'r':\n self._contract_requests[msg['good']].append(msg)\n else:\n self._contract_offers[msg['good']].append(msg)\n elif typ == '+d':\n self._contracts_deliver[msg['good']].append(msg)\n elif typ == '+p':\n self._contracts_pay[msg['good']].append(msg)\n elif typ == '!d':\n self._haves[msg['good']] += msg['quantity']\n self._contracts_delivered.append((msg['receiver_group'], msg['receiver_idn']))\n self._log_receive_accept(msg)\n elif typ == '!p':\n self._haves['money'] += msg['price']\n self._contracts_payed.append((msg['receiver_group'], msg['receiver_idn']))\n self._log_receive_accept(msg)\n else:\n self._msgs.setdefault(typ, []).append(Message(msg))\n\n\n def _send(self, receiver_group, receiver_idn, typ, msg):\n \"\"\" sends a message to 'receiver_group', who can be an agent, a group or\n 'all'. The agents receives it at the begin of each round in\n self.messages(typ) is 'm' for mails.\n typ =(_o,c,u,r) are\n reserved for internally processed offers.\n \"\"\"\n self._out.append([receiver_group, receiver_idn, (typ, msg)])\n\n def _send_to_group(self, receiver_group, typ, msg):\n \"\"\" sends a message to 'receiver_group', who can be an agent, a group or\n 'all'. The agents receives it at the begin of each round in\n self.messages(typ) is 'm' for mails.\n typ =(_o,c,u,r) are\n reserved for internally processed offers.\n \"\"\"\n raise NotImplementedError\n self._out.append([receiver_group, 'all', (typ, msg)])\n\ndef flatten(d, parent_key=''):\n items = []\n for k, v in d.items():\n try:\n items.extend(flatten(v, '%s%s_' % (parent_key, k)).items())\n except AttributeError:\n items.append(('%s%s' % (parent_key, k), v))\n return dict(items)\n\n","sub_path":"abce/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":20839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"164819310","text":"# Jessica Nguyen\n# z5018882\n# CS3331 Assignment 1\n# python3\n\n\"\"\" Receiver operating on the STP Protocol module. \"\"\"\nimport sys\n# Socket programming library.\nimport socket\n# Object serialization library.\nimport pickle\n# System time library for logging.\nfrom datetime import datetime\n# Segment module.\nfrom segment import STPSegment, STPLogger\n\nclass ReceiverState(object):\n \"\"\" An object to keep track of state variables required for processing\n STP segments.\n\n Attributes:\n receiver_port: An integer containing the port the receiver will be\n receiving STP segments from.\n file_name: A string containing the name of the data file being\n transferred.\n start_time: A datetime.datetime object storing the time the receiver\n started listening on it's port.\n time_elapsed: A float containing the number of ms that has elapsed\n since the receiver started listening on it's port. Used\n for logging.\n curr_seq_num: An integer containing the current sequence number.\n sender_addr: An (IP, port #) tuple to keep track of the current sender\n address.\n established_sender_addr: An (IP, port #) tuple to keep track of the\n sender address that has established a STP\n connection (via three way handshake).\n log_file: A file to write logs to. This file is initiated when this\n object is initiated.\n data_received_num: An integer containing the number of bytes that the\n receiver has received.\n segments_received_num: An integer containing the number of segments that\n the receiver has received.\n duplicate_segments_received_num: An integer containing the number of\n duplicate segments received.\n is_connected: A bool to keep track of current connection state.\n is_connection_being_established: A bool to keep track of whether a\n three way handshake is occurring.\n is_connection_being_terminated: A bool to keep track of whether a\n connection is in the process of being\n terminated.\n data_file: Stores the file being written to. Intialise later after\n connection has been established in:\n process_connection_establishment_type_segment()\n \"\"\"\n def __init__(self):\n \"\"\" Inits all attributes with 0 or False and opens a new file for the\n logger.\n \"\"\"\n self.receiver_port = 0\n self.file_name = ''\n self.start_time = None\n self.time_elapsed = 0\n self.curr_seq_num = 0\n self.curr_ack_num = 0\n self.sender_addr = 0\n self.established_sender_addr = 0\n self.log_file = open(LOG_FILE_NAME, \"w\")\n self.data_received_num = 0\n self.segments_received_num = 0\n self.duplicate_segments_received_num = 0\n self.is_connected = False\n self.is_connection_being_established = False\n self.is_connection_being_terminated = False\n self.is_file_transfer_complete = False\n self.data_file = None\n self.received_seq_nums = {}\n self.receiver_ip = ''\n self.last_data_segment_received = None\n\nLOG_FILE_NAME = \"Receiver_log.txt\"\nSTP_LOGGER = STPLogger()\nSTATE = ReceiverState()\nMAX_BUFFER_SIZE = 4096\n\ndef main(argv):\n \"\"\" Main function taking in commandline args. \"\"\"\n # Retrieve server port and file name from command line input args.\n STATE.receiver_port = int(argv[1])\n STATE.file_name = argv[2]\n\n STATE.receiver_ip = socket.gethostbyname(socket.gethostname())\n\n # Create a UDP socket instance using IPv4 addresses (AF_INET) and\n # UDP protocol (SOCK_DGRAM).\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n # Bind it to the input receiver port.\n sock.bind(('', STATE.receiver_port))\n STATE.start_time = datetime.now()\n except socket.error:\n print(\"Failed to complete socket.\")\n sys.exit()\n\n while not STATE.is_file_transfer_complete:\n print(\"Waiting to receive from port %d\" % STATE.receiver_port)\n data = sock.recv(MAX_BUFFER_SIZE)\n if data:\n STATE.segments_received_num += 1\n\n # Deserialize segment back into an STPSegment object.\n segment = pickle.loads(data)\n print(\"segment with seq %d and ack %d\" % (segment.seq_num, segment.ack_num))\n # Initialise a basic STP segment reply object with address params\n # (source_ip, dest_ip, source_port, dest_port) and mss field set.\n segment_reply = init_segment_reply(segment)\n\n # Store sender address extracted from segment source IP and port\n # fields.\n if segment.source_ip == STATE.receiver_ip:\n STATE.sender_addr = ('localhost', segment.source_port)\n else:\n STATE.sender_addr = (segment.source_ip, segment.source_port)\n # Connection not yet established case.\n if not STATE.is_connected:\n if segment.syn_flag:\n process_connection_establishment(sock, segment,\n segment_reply)\n # Connection established case.\n elif STATE.sender_addr == STATE.established_sender_addr:\n # Check if the segment is requesting a connection termination.\n if segment.fin_flag:\n if not STATE.is_connection_being_terminated:\n start_connection_termination(sock, segment, segment_reply)\n if STATE.is_connection_being_terminated:\n complete_connection_termination(sock, segment, segment_reply)\n # Process a data type segment.\n else:\n print(\"processing\")\n process_data_type_segment(sock, segment, segment_reply)\n sock.close()\n STATE.log_file.write(\"\\nAmount of data received (bytes): %d\\n\"\n % STATE.data_received_num)\n STATE.log_file.write(\"Number of data segments received: %d \\n\"\n % STATE.segments_received_num)\n STATE.log_file.write(\"Number of duplicate segments received: %d \\n\"\n % STATE.duplicate_segments_received_num)\n STATE.log_file.close()\n\ndef process_connection_establishment(sock, segment, segment_reply):\n \"\"\" A helper function to process segments with the syn_flag set. \"\"\"\n update_time_elapsed()\n STATE.log_file.write(STP_LOGGER.log(\"rcv\", STATE.time_elapsed, \"S\",\n segment.seq_num, len(segment.data),\n segment.ack_num))\n # If segment is the first stage of three way handshake.\n if not STATE.is_connection_being_established:\n STATE.is_connection_being_established = True\n segment_reply.syn_flag = True\n segment_reply.ack_flag = True\n STATE.curr_ack_num = segment.seq_num + 1\n segment_reply.set_seq_ack_num(STATE.curr_seq_num, STATE.curr_ack_num)\n print(\"sender_addr = (%s, %d)\" % (STATE.sender_addr[0], STATE.sender_addr[1]))\n segment_reply.send_segment(sock, STATE.sender_addr)\n STATE.log_file.write(STP_LOGGER.log(\"snd\", STATE.time_elapsed, \"SA\",\n segment_reply.seq_num,\n len(segment_reply.data),\n segment_reply.ack_num))\n STATE.curr_seq_num += 1\n STATE.established_sender_addr = STATE.sender_addr\n # If the segment is the final stage of three way\n # handshake.\n is_final_stage_of_handshake = ((STATE.is_connection_being_established) and\n (segment.ack_num == STATE.curr_seq_num))\n # and (STATE.sender_addr !=\n # STATE.established_sender_addr))\n if is_final_stage_of_handshake:\n STATE.is_connected = True\n STATE.data_file = open(STATE.file_name, \"w\")\n STATE.is_connection_being_established = False\n STATE.curr_ack_num += 1\n\ndef complete_connection_termination(sock, segment, segment_reply):\n # Check for final reply ACK to terminate connection.\n if segment.ack_num == STATE.curr_seq_num + 1:\n STATE.log_file.write(STP_LOGGER.log(\"rcv\",\n STATE.time_elapsed, \"A\",\n segment.seq_num, len(segment.data),\n segment.ack_num))\n STATE.is_connected = False\n STATE.is_connection_being_terminated = False\n STATE.data_file.close()\n STATE.is_file_transfer_complete = True\n\ndef start_connection_termination(sock, segment, segment_reply):\n \"\"\" A helper function to process segments with the fin_flag set. \"\"\"\n update_time_elapsed()\n STATE.log_file.write(STP_LOGGER.log(\"rcv\",\n STATE.time_elapsed, \"F\",\n segment.seq_num, len(segment.data),\n segment.ack_num))\n STATE.is_connection_being_terminated = True\n # First send a segment reply with an ACK.\n STATE.curr_ack_num += 1\n segment_reply.set_seq_ack_num(STATE.curr_seq_num, STATE.curr_ack_num)\n segment_reply.ack_flag = True\n segment_reply.send_segment(sock, STATE.sender_addr)\n update_time_elapsed()\n STATE.log_file.write(STP_LOGGER.log(\"snd\",\n STATE.time_elapsed, \"A\",\n segment_reply.seq_num,\n segment_reply.mss,\n segment_reply.ack_num))\n fin_segment = init_segment_reply(segment)\n fin_segment.set_seq_ack_num(STATE.curr_seq_num, STATE.curr_ack_num)\n fin_segment.fin_flag = True\n fin_segment.ack_flag = False\n fin_segment.send_segment(sock, STATE.sender_addr)\n STP_LOGGER.log(\"snd\", STATE.time_elapsed, \"F\", segment_reply.seq_num,\n segment_reply.mss, segment_reply.ack_num)\n\ndef process_data_type_segment(sock, segment, segment_reply):\n \"\"\" A helper function to process segments where the connection\n has been established which contain a data payload.\n \"\"\"\n is_reply_already_sent = False\n update_time_elapsed()\n STATE.log_file.write(STP_LOGGER.log(\"rcv\",\n STATE.time_elapsed, \"D\",\n segment.seq_num,\n len(segment.data), segment.ack_num))\n next_expected_seq_num = -1\n if STATE.last_data_segment_received:\n # last_seq_num = STATE.last_data_segment_received.seq_num\n # data_size = len(STATE.last_data_segment_received.data)\n # next_expected_seq_num = last_seq_num + data_size\n next_expected_seq_num = STATE.curr_ack_num \n\n if segment.seq_num in STATE.received_seq_nums.keys():\n STATE.received_seq_nums[segment.seq_num] += 1\n STATE.duplicate_segments_received_num += 1\n print(\"duplicate registered\")\n\n if next_expected_seq_num != -1 and next_expected_seq_num != segment.seq_num:\n # Packet arrived out of order. Resend ack.\n print(\"packet arrived out of order, resend ack\")\n segment_reply.set_seq_ack_num(STATE.curr_seq_num, STATE.curr_ack_num)\n segment_reply.send_segment(sock, STATE.sender_addr)\n is_reply_already_sent = True\n update_time_elapsed()\n STATE.log_file.write(STP_LOGGER.log(\"snd\",\n STATE.time_elapsed, \"A\",\n segment_reply.seq_num,\n len(segment_reply.data),\n segment_reply.ack_num))\n else:\n print(\"packet arrived in order\")\n STATE.data_file.write(segment.data)\n print(\"updating curr ack num %d by %d\" % (STATE.curr_ack_num, len(segment.data)))\n STATE.curr_ack_num += len(segment.data)\n STATE.curr_seq_num += 1\n # Update logger vars.\n STATE.data_received_num += len(segment.data)\n STATE.segments_received_num += 1\n\n if not is_reply_already_sent:\n segment_reply.set_seq_ack_num(STATE.curr_seq_num, STATE.curr_ack_num)\n segment_reply.send_segment(sock, STATE.sender_addr)\n update_time_elapsed()\n STATE.log_file.write(STP_LOGGER.log(\"snd\",\n STATE.time_elapsed, \"A\",\n segment_reply.seq_num,\n len(segment_reply.data),\n segment_reply.ack_num))\n\n if not(segment.seq_num in STATE.received_seq_nums.keys()):\n STATE.received_seq_nums[segment.seq_num] = 1\n\n STATE.last_data_segment_received = segment\n\ndef init_segment_reply(segment):\n \"\"\" Helper function to initialise a basic STPSegment reply with address\n params set, mss set to 0 and ack flag set.\n\n Segments sent from the receiver should always have the mss=0\n since only segments of type \"D\" do not get sent from this end.\n \"\"\"\n segment_reply = STPSegment()\n segment_reply.mss = 0\n segment_reply.ack_flag = True\n if STATE.receiver_ip == segment.source_ip:\n segment_reply.set_address_attributes('localhost',\n 'localhost',\n STATE.receiver_port,\n segment.source_port)\n else:\n segment_reply.set_address_attributes(STATE.receiver_ip,\n segment.source_ip,\n STATE.receiver_port,\n segment.source_port)\n return segment_reply\n\ndef update_time_elapsed():\n \"\"\" A helper function to assist with logging to recalculate and set\n the time elapsed.\n \"\"\"\n time_delta = ((datetime.now() - STATE.start_time).microseconds)/1000\n # STATE.time_elapsed = STP_LOGGER.get_time_elapsed(STATE.start_time)\n STATE.time_elapsed = time_delta\nif __name__ == \"__main__\":\n # sys.stdout = sys.stderr\n main(sys.argv)\n","sub_path":"assignments/ass01/receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":14677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"615206537","text":"# -*- coding: utf-8 -*-\n\n# visigoth: A lightweight Python3 library for rendering data visualizations in SVG\n# Copyright (C) 2020 Niall McCarroll\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software\n# and associated documentation files (the \"Software\"), to deal in the Software without \n# restriction, including without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or \n# substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\n# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport unittest\n\nfrom visigoth import Diagram\nfrom visigoth.utils.test_utils import TestUtils\nfrom visigoth.containers.box import Box\nfrom visigoth.containers.popup import Popup\nfrom visigoth.common.text import Text\n\nclass TestPopup(unittest.TestCase):\n\n def test_basic(self):\n d = Diagram(fill=\"white\")\n\n p0 = Popup(Text(\"Popup Content\"),\"TEST\")\n d.add(p0)\n\n p1 = Popup(Text(\"Orange Border\"),\"TEST\",stroke=\"orange\")\n d.add(p1)\n\n p2 = Popup(Text(\"Light Blue Fill\"),\"TEST\",fill=\"lightblue\")\n d.add(p2)\n\n p3 = Popup(Text(\"Thick Border\"),\"TEST\",stroke_width=5)\n d.add(p3)\n\n p4 = Popup(Text(\"Light Blue Fill\"),\"Large Font\",font_height=24,fill=\"lightblue\")\n d.add(p4)\n\n p5 = Popup(Text(\"Reduced Opacity\"),\"TEST\",fill=\"orange\",opacity=0.2)\n d.add(p5)\n\n TestUtils.draw_output(d,\"test_popup\")\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/all/containers/test_popup.py","file_name":"test_popup.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"26860909","text":"##############################################################################\n#\n# Copyright (c) 2004 Zope Corporation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Test hookup\n\n$Id$\n\"\"\"\nimport os\nimport unittest\nimport zope.event\nfrom zope.component.tests import placelesssetup\n\ndef tearDown(test):\n placelesssetup.tearDown(test)\n zope.event.subscribers.pop()\n\ndef setUp(test):\n test.globs['this_directory'] = os.path.split(__file__)[0]\n placelesssetup.setUp(test)\n\ndef test_suite():\n from zope.testing import doctest\n suite = unittest.TestSuite()\n # suite.addTest(doctest.DocTestSuite())\n suite.addTest(doctest.DocFileSuite('README.txt', tearDown=tearDown,\n setUp=placelesssetup.setUp))\n suite.addTest(doctest.DocFileSuite(\n 'xpdl.txt', tearDown=tearDown, setUp=setUp,\n optionflags=doctest.NORMALIZE_WHITESPACE))\n return suite\n\nif __name__ == '__main__':\n unittest.main(defaultTest='test_suite')\n\n","sub_path":"Zope3/branches/jhauser-filefieldwidget/src/zope/wfmc/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"29432040","text":"from GUIAssets.Scripts.GameObjects.Cards.card import Card\nfrom GUIAssets.Scripts.Utility import strings\n\n\nclass Deck:\n\n def __init__(self):\n self.card_dict = {}\n self.load_card_types()\n\n def load_card_types(self):\n suits = ['c', 'd', 'h', 's']\n values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'a', 'j', 'q', 'k']\n for s in suits:\n for v in values:\n c = s + v\n if c not in self.card_dict:\n self.card_dict[c] = None\n\n def get_card(self, card):\n if card not in self.card_dict:\n print(\"Card with value:\", card, \"not found in card dictionary.\")\n return None\n if self.card_dict[card] == None:\n ## load card and return\n path = strings.CARD_PATH + card + \".png\"\n new_card = Card(path, (0, 0))\n return new_card\n else:\n return self.card_dict[card]\n","sub_path":"Blackjack_v1/GUIAssets/Scripts/Managers/deck_manager.py","file_name":"deck_manager.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"252332039","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nMerge a list of Spherical Harmonics files.\n\nThis merges the coefficients of multiple Spherical Harmonics files\nby taking, for each coefficient, the one with the largest magnitude.\n\nCan be used to merge fODFs computed from different shells into 1, while\nconserving the most relevant information.\n\nBased on [1].\n\"\"\"\n\nimport argparse\n\nimport nibabel as nb\nimport numpy as np\n\nfrom scilpy.io.image import assert_same_resolution\nfrom scilpy.io.utils import (add_overwrite_arg, assert_inputs_exist,\n assert_outputs_exist)\n\n\nEPILOG = \"\"\"\nReference:\n [1] Garyfallidis, E., Zucchelli, M., Houde, J-C., Descoteaux, M.\n How to perform best ODF reconstruction from the Human Connectome\n Project sampling scheme?\n ISMRM 2014.\n\"\"\"\n\n\ndef _build_arg_parser():\n parser = argparse.ArgumentParser(\n description=__doc__, epilog=EPILOG,\n formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument('sh_files', nargs=\"+\",\n help='List of SH files.')\n parser.add_argument('out_sh',\n help='output SH file.')\n\n add_overwrite_arg(parser)\n\n return parser\n\n\ndef main():\n parser = _build_arg_parser()\n args = parser.parse_args()\n\n assert_inputs_exist(parser, args.sh_files)\n assert_outputs_exist(parser, args, args.out_sh)\n assert_same_resolution(args.sh_files)\n\n first_im = nb.load(args.sh_files[0])\n out_coeffs = first_im.get_data()\n\n for sh_file in args.sh_files[1:]:\n im = nb.load(sh_file)\n im_dat = im.get_data()\n\n out_coeffs = np.where(np.abs(im_dat) > np.abs(out_coeffs),\n im_dat, out_coeffs)\n\n nb.save(nb.Nifti1Image(out_coeffs, first_im.affine, first_im.header),\n args.out_sh)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/scil_merge_sh.py","file_name":"scil_merge_sh.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"419149566","text":"\"\"\"\n.. module:: soccerwiki\n :platform: Linux\n\n.. moduleauthor:: Artur Birek \n\n\n\"\"\"\n\n\nimport asyncio\nimport os\nimport sys\nimport requests\nimport time\nimport xmltodict\n\nthis_directory = os.getcwd()\nsys.path.insert(0, this_directory + \"/..\")\nprint(\"{} added to PYTHONPATH\".format(this_directory))\n\nfrom lib.database_connector import DatabaseConnector\nfrom lib.general import sys_args_parser, parse_database_conf\n\n\ndef normalize_name(name):\n first_letter = name[0]\n other_letters = name[1:]\n return first_letter + other_letters.lower()\n\n\nPLAYERS_URL = \"http://c3420952.r52.cf0.rackcdn.com/playerdata.xml\"\nINSERT_QUERY = \"\"\"INSERT INTO celebrities.football_players (id, first_name, last_name) \n VALUES ($1, $2, $3);\"\"\"\n\n\ndef prepare_list_of_rows_for_query(rows):\n \"\"\"This function does something.\n\n :param rows: dictionary of dictionaries.\n :type rows: dict.\n :returns: list of lists.\n :raises: AttributeError, KeyError\n \"\"\"\n\n list_rows_to_insert = []\n for id, row in rows.items():\n list_rows_to_insert.append([id,\n row[\"first_name\"],\n row[\"last_name\"]])\n return list_rows_to_insert\n\n\nasync def insert_batch_of_rows(conn, rows):\n data_inserting_start_time = time.time()\n print(\"Inserting {} rows ...\".format(len(rows)))\n rows_to_insert = prepare_list_of_rows_for_query(rows)\n await conn.executemany(INSERT_QUERY, rows_to_insert)\n data_inserting_end_time = time.time()\n print(\"Inserting time: {}\".format(data_inserting_end_time - data_inserting_start_time))\n\n\nasync def run(db_conf):\n engine = DatabaseConnector(db_conf[\"database\"], db_conf[\"user\"], db_conf[\"password\"])\n dbconn = await engine.connection()\n\n rows = {}\n request_start_time = time.time()\n response = requests.get(PLAYERS_URL)\n request_end_time = time.time()\n print(\"HTTP request time: {}\".format(request_end_time - request_start_time))\n\n players = xmltodict.parse(response.text)\n players = players[\"PackData\"][\"PlayerData\"][\"P\"]\n\n for player in players:\n row = dict()\n row[\"first_name\"] = player[\"@f\"]\n row[\"last_name\"] = normalize_name(player[\"@s\"])\n rows[int(player[\"@id\"])] = row\n\n await insert_batch_of_rows(dbconn, rows)\n await dbconn.close()\n\n\nif __name__ == \"__main__\":\n args = sys_args_parser().parse_args()\n db_conf = parse_database_conf(args.database_conf)\n total_time_start = time.time()\n\n loop = asyncio.get_event_loop()\n loop.run_until_complete(run(db_conf))\n\n print(\"Total time: {}\".format(time.time() - total_time_start))\n","sub_path":"celebritiesdb/soccerwiki_parser.py","file_name":"soccerwiki_parser.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"72198984","text":"import base64\nimport json\nimport logging.handlers\nimport math\nimport os\nimport re\nimport shutil\nimport sys\nimport time\nimport traceback\nimport urllib.parse\nimport uuid\nfrom datetime import datetime\nfrom threading import Event\nfrom threading import RLock\nfrom threading import Thread\nfrom threading import Timer\n\nimport m3u8\nimport pytz\nimport requests\nimport tzlocal\n\nfrom .configuration import SmoothStreamsProxyConfiguration\nfrom .enums import SmoothStreamsProxyRecordingStatus\nfrom .exceptions import DuplicateRecordingError\nfrom .exceptions import RecordingNotFoundError\nfrom .proxy import SmoothStreamsProxy\nfrom .shelf import SmoothStreamsProxyShelf\nfrom .utilities import SmoothStreamsProxyUtility\n\nlogger = logging.getLogger(__name__)\n\n\nclass SmoothStreamsProxyPVR():\n __slots__ = []\n\n _live_recordings_to_recording_thread = {}\n _live_recordings_to_recording_thread_lock = RLock()\n _recordings = []\n _recordings_directory_path = None\n _recordings_lock = RLock()\n _start_recording_timer = None\n _start_recording_timer_lock = RLock()\n\n @classmethod\n def _get_persistent_recordings(cls):\n persistent_recordings = []\n\n recordings_directory_path = cls._recordings_directory_path\n recordings_top_level_directory = [recording_top_level_directory\n for recording_top_level_directory in os.listdir(recordings_directory_path)\n if os.path.isdir(os.path.join(recordings_directory_path,\n recording_top_level_directory))]\n if recordings_top_level_directory:\n for recording_top_level_directory in recordings_top_level_directory:\n try:\n recording_top_level_directory_path = os.path.join(recordings_directory_path,\n recording_top_level_directory,\n '.MANIFEST')\n with open(recording_top_level_directory_path, 'r') as input_file:\n recording_manifest = json.load(input_file)\n if recording_manifest['status'] == 'Completed':\n recording = SmoothStreamsProxyRecording(recording_manifest['channel_name'],\n recording_manifest['channel_number'],\n datetime.strptime(\n recording_manifest[\n 'actual_end_date_time_in_utc'],\n '%Y-%m-%d %H:%M:%S%z'),\n recording_manifest['id'],\n recording_manifest['program_title'],\n datetime.strptime(\n recording_manifest[\n 'actual_start_date_time_in_utc'],\n '%Y-%m-%d %H:%M:%S%z'),\n SmoothStreamsProxyRecordingStatus.PERSISTED.value)\n recording.base_recording_directory = recording_manifest['base_recording_directory']\n persistent_recordings.append(recording)\n except OSError:\n logger.error('Failed to open .MANIFEST\\n'\n '.MANIFEST file path => {0}'.format(os.path.join(recordings_directory_path,\n recording_top_level_directory,\n '.MANIFEST')))\n\n return persistent_recordings\n\n @classmethod\n def _get_scheduled_recordings(cls):\n with cls._recordings_lock:\n return [scheduled_recording\n for scheduled_recording in cls._recordings\n if scheduled_recording.status == SmoothStreamsProxyRecordingStatus.SCHEDULED.value]\n\n @classmethod\n def _set_live_recordings_to_recording_thread(cls, live_recordings_to_recording_thread):\n with cls._live_recordings_to_recording_thread_lock:\n cls._live_recordings_to_recording_thread = live_recordings_to_recording_thread\n\n @classmethod\n def _restart_live_recording(cls):\n with cls._live_recordings_to_recording_thread_lock, cls._recordings_lock:\n cls._set_live_recordings_to_recording_thread(\n {\n recording.id: SmoothStreamsProxyRecordingThread(recording)\n for recording in cls._recordings\n if recording.status == SmoothStreamsProxyRecordingStatus.LIVE.value\n })\n\n @classmethod\n def _set_start_recording_timer(cls):\n with cls._start_recording_timer_lock:\n if cls._start_recording_timer:\n cls._start_recording_timer.cancel()\n\n soonest_scheduled_recording_start_date_time_in_utc = None\n current_date_time_in_utc = datetime.now(pytz.utc)\n\n for scheduled_recording in cls._get_scheduled_recordings():\n scheduled_recording_start_date_time_in_utc = scheduled_recording.start_date_time_in_utc\n\n if current_date_time_in_utc > scheduled_recording_start_date_time_in_utc:\n # Generate a new id for the recording when we change it's status\n scheduled_recording.id = '{0}'.format(uuid.uuid4())\n scheduled_recording.status = SmoothStreamsProxyRecordingStatus.LIVE.value\n\n SmoothStreamsProxyShelf.persist_to_shelf('recordings', cls._recordings)\n\n with cls._live_recordings_to_recording_thread_lock:\n cls._live_recordings_to_recording_thread[\n scheduled_recording.id] = SmoothStreamsProxyRecordingThread(scheduled_recording)\n elif not soonest_scheduled_recording_start_date_time_in_utc:\n soonest_scheduled_recording_start_date_time_in_utc = scheduled_recording_start_date_time_in_utc\n elif soonest_scheduled_recording_start_date_time_in_utc > scheduled_recording_start_date_time_in_utc:\n soonest_scheduled_recording_start_date_time_in_utc = scheduled_recording_start_date_time_in_utc\n\n if soonest_scheduled_recording_start_date_time_in_utc:\n interval = (soonest_scheduled_recording_start_date_time_in_utc - datetime.now(pytz.utc)).total_seconds()\n cls._start_recording_timer = Timer(interval, cls._start_recording)\n cls._start_recording_timer.start()\n\n logger.debug('Starting recording timer\\n'\n 'Interval => {0} seconds'.format(interval))\n\n @classmethod\n def _start_recording(cls):\n current_date_time_in_utc = datetime.now(pytz.utc)\n\n for scheduled_recording in cls._get_scheduled_recordings():\n scheduled_recording_start_date_time_in_utc = scheduled_recording.start_date_time_in_utc\n\n if current_date_time_in_utc > scheduled_recording_start_date_time_in_utc:\n # Generate a new id for the recording when we change it's status\n scheduled_recording.id = '{0}'.format(uuid.uuid4())\n scheduled_recording.status = SmoothStreamsProxyRecordingStatus.LIVE.value\n\n SmoothStreamsProxyShelf.persist_to_shelf('recordings', cls._recordings)\n\n with cls._live_recordings_to_recording_thread_lock:\n cls._live_recordings_to_recording_thread[\n scheduled_recording.id] = SmoothStreamsProxyRecordingThread(scheduled_recording)\n\n cls._set_start_recording_timer()\n\n @classmethod\n def add_scheduled_recording(cls, scheduled_recording):\n with cls._recordings_lock:\n if scheduled_recording not in cls._recordings:\n cls._recordings.append(scheduled_recording)\n\n SmoothStreamsProxyShelf.persist_to_shelf('recordings', cls._recordings)\n\n cls._set_start_recording_timer()\n else:\n raise DuplicateRecordingError\n\n @classmethod\n def cancel_start_recording_timer(cls):\n if cls._start_recording_timer:\n cls._start_recording_timer.cancel()\n\n @classmethod\n def delete_live_recording(cls, live_recording):\n with cls._recordings_lock:\n cls._recordings.remove(live_recording)\n\n SmoothStreamsProxyShelf.persist_to_shelf('recordings', cls._recordings)\n\n @classmethod\n def delete_persisted_recording(cls, persisted_recording):\n shutil.rmtree(os.path.join(cls._recordings_directory_path, persisted_recording.base_recording_directory))\n\n @classmethod\n def delete_scheduled_recording(cls, scheduled_recording):\n with cls._recordings_lock:\n cls._recordings.remove(scheduled_recording)\n\n SmoothStreamsProxyShelf.persist_to_shelf('recordings', cls._recordings)\n\n cls._set_start_recording_timer()\n\n @classmethod\n def generate_recording_playlist_url(cls,\n is_server_secure,\n server_hostname,\n server_port,\n client_uuid,\n base_recording_directory,\n token):\n return '{0}://{1}:{2}/vod/playlist.m3u8?client_uuid={3}&program_title={4}{5}'.format(\n 'https' if is_server_secure else 'http',\n server_hostname,\n server_port,\n client_uuid,\n urllib.parse.quote(base_recording_directory),\n '&token={0}'.format(token) if token else '')\n\n @classmethod\n def generate_vod_playlist_m3u8(cls, is_server_secure, client_ip_address, client_uuid, token):\n playlist_m3u8 = []\n\n client_ip_address_type = SmoothStreamsProxyUtility.determine_ip_address_type(client_ip_address)\n server_hostname = SmoothStreamsProxyConfiguration.get_configuration_parameter(\n 'SERVER_HOSTNAME_{0}'.format(client_ip_address_type.value))\n server_port = SmoothStreamsProxyConfiguration.get_configuration_parameter(\n 'SERVER_HTTP{0}_PORT'.format('S' if is_server_secure else ''))\n\n for persistent_recording in cls._get_persistent_recordings():\n playlist_m3u8.append(\n '#EXTINF:-1,{0} - [{1} - {2}]\\n'\n '{3}\\n'.format(\n persistent_recording.program_title,\n persistent_recording.start_date_time_in_utc.astimezone(\n tzlocal.get_localzone()).strftime('%Y-%m-%d %H:%M:%S%z'),\n persistent_recording.end_date_time_in_utc.astimezone(\n tzlocal.get_localzone()).strftime('%Y-%m-%d %H:%M:%S%z'),\n cls.generate_recording_playlist_url(is_server_secure,\n server_hostname,\n server_port,\n client_uuid,\n persistent_recording.base_recording_directory,\n token)))\n\n if playlist_m3u8:\n playlist_m3u8 = '#EXTM3U\\n{0}'.format(''.join(playlist_m3u8))\n\n logger.debug('Generated VOD playlist.m3u8')\n else:\n logger.debug('No persistent recordings found. VOD playlist.m3u8 will not be generated')\n\n return playlist_m3u8\n\n @classmethod\n def get_recording(cls, recording_id):\n with cls._recordings_lock:\n for recording in cls._recordings + cls._get_persistent_recordings():\n if recording.id == recording_id:\n return recording\n\n raise RecordingNotFoundError\n\n @classmethod\n def get_recordings(cls):\n with cls._recordings_lock:\n return cls._recordings + cls._get_persistent_recordings()\n\n @classmethod\n def get_recordings_directory_path(cls):\n return cls._recordings_directory_path\n\n @classmethod\n def initialize_from_shelf(cls):\n try:\n cls._recordings = SmoothStreamsProxyShelf.get_shelved_setting('recordings')\n except KeyError:\n pass\n\n @classmethod\n def read_ts_file(cls, path, program_title):\n ts_file_path = os.path.join(cls._recordings_directory_path,\n program_title,\n 'segments',\n re.sub(r'/vod/(.*)\\?.*', r'\\1', path))\n\n return SmoothStreamsProxyUtility.read_file(ts_file_path, in_binary=True)\n\n @classmethod\n def read_vod_playlist_m3u8(cls, client_uuid, program_title, token):\n vod_playlist_m3u8_file_path = os.path.join(cls._recordings_directory_path,\n program_title,\n 'playlist',\n 'playlist.m3u8')\n\n return re.sub(r'(\\.ts\\?)(.*)',\n r'\\1client_uuid={0}&\\2{1}'.format(client_uuid, '&token={0}'.format(token) if token else ''),\n SmoothStreamsProxyUtility.read_file(vod_playlist_m3u8_file_path))\n\n @classmethod\n def set_recordings_directory_path(cls, recordings_directory_path):\n cls._recordings_directory_path = recordings_directory_path\n\n @classmethod\n def start(cls):\n cls._restart_live_recording()\n cls._set_start_recording_timer()\n\n @classmethod\n def stop_live_recording(cls, live_recording):\n with cls._live_recordings_to_recording_thread_lock:\n cls._live_recordings_to_recording_thread[live_recording.id].force_stop()\n\n\nclass SmoothStreamsProxyRecording():\n __slots__ = ['_base_recording_directory', '_channel_name', '_channel_number', '_end_date_time_in_utc', '_id',\n '_program_title', '_start_date_time_in_utc', '_status']\n\n def __init__(self,\n channel_name,\n channel_number,\n end_date_time_in_utc,\n id_,\n program_title,\n start_date_time_in_utc,\n status):\n self._base_recording_directory = None\n self._channel_name = channel_name\n self._channel_number = channel_number\n self._end_date_time_in_utc = end_date_time_in_utc\n self._id = id_\n self._program_title = program_title\n self._start_date_time_in_utc = start_date_time_in_utc\n self._status = status\n\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n return (self.channel_number, self._end_date_time_in_utc, self._start_date_time_in_utc) == (\n other._channel_number, other._end_date_time_in_utc, other._start_date_time_in_utc)\n return False\n\n def __repr__(self):\n return '{0}('.format(self.__class__.__name__) + ', '.join(\n ['{0}={1!r}'.format(attribute_name[1:], getattr(self, attribute_name)) for attribute_name in\n self.__slots__]) + ')'\n\n def __str__(self):\n return '{0}('.format(self.__class__.__name__) + ', '.join(\n ['{0}={1!s}'.format(attribute_name, getattr(self, attribute_name)) for attribute_name in\n self.__slots__]) + ')'\n\n @property\n def base_recording_directory(self):\n return self._base_recording_directory\n\n @base_recording_directory.setter\n def base_recording_directory(self, base_recording_directory):\n self._base_recording_directory = base_recording_directory\n\n @property\n def channel_name(self):\n return self._channel_name\n\n @property\n def channel_number(self):\n return self._channel_number\n\n @property\n def end_date_time_in_utc(self):\n return self._end_date_time_in_utc\n\n @property\n def id(self):\n return self._id\n\n @id.setter\n def id(self, id_):\n self._id = id_\n\n @property\n def program_title(self):\n return self._program_title\n\n @property\n def start_date_time_in_utc(self):\n return self._start_date_time_in_utc\n\n @property\n def status(self):\n return self._status\n\n @status.setter\n def status(self, status):\n self._status = status\n\n\nclass SmoothStreamsProxyRecordingThread(Thread):\n def __init__(self, recording):\n Thread.__init__(self)\n\n self._id = uuid.uuid3(uuid.NAMESPACE_OID, 'SmoothStreamsProxyRecordingThread')\n self._recording = recording\n self._recording_directory_path = None\n\n self._stop_recording_event = Event()\n self._stop_recording_timer = Timer(\n (self._recording.end_date_time_in_utc - datetime.now(pytz.utc)).total_seconds(),\n self._set_stop_recording_event)\n self._stop_recording_timer.start()\n\n self.start()\n\n def _create_recording_directory_tree(self):\n recording_directory_suffix_counter = 0\n recording_directory_suffix = ''\n\n did_make_directory = False\n while not did_make_directory:\n # base64.urlsafe_b64encode() the base directory. This results in a valid directory name on any OS at the\n # expense of human readability.\n recording_directory_path = os.path.join(SmoothStreamsProxyPVR.get_recordings_directory_path(),\n base64.urlsafe_b64encode('{0}{1}'.format(\n self._recording.program_title,\n recording_directory_suffix).encode()).decode())\n if os.path.exists(recording_directory_path):\n recording_directory_suffix_counter += 1\n recording_directory_suffix = '_{0}'.format(recording_directory_suffix_counter)\n else:\n logger.debug('Creating recording directory tree for {0}\\n'\n 'Path => {1}'.format(self._recording.program_title, recording_directory_path))\n\n try:\n os.makedirs(recording_directory_path)\n os.makedirs(os.path.join(recording_directory_path, 'playlist'))\n os.makedirs(os.path.join(recording_directory_path, 'segments'))\n\n did_make_directory = True\n self._recording_directory_path = recording_directory_path\n self._recording.base_recording_directory = os.path.split(recording_directory_path)[-1]\n\n logger.debug('Created recording directory tree for {0}\\n'\n 'Path => {1}'.format(self._recording.program_title, recording_directory_path))\n except OSError:\n logger.error('Failed to create recording directory tree for {0}\\n'\n 'Path => {1}'.format(self._recording.program_title, recording_directory_path))\n\n recording_directory_suffix_counter += 1\n recording_directory_suffix = '_{0}'.format(recording_directory_suffix_counter)\n\n def _save_manifest_file(self,\n actual_end_date_time_in_utc,\n actual_start_date_time_in_utc,\n id_,\n playlist_file,\n status):\n manifest_file_path = os.path.join(self._recording_directory_path, '.MANIFEST')\n\n try:\n with open(manifest_file_path, 'w') as out_file:\n json.dump({\n 'actual_end_date_time_in_utc': actual_end_date_time_in_utc,\n 'actual_start_date_time_in_utc': actual_start_date_time_in_utc,\n 'channel_name': self._recording.channel_name,\n 'base_recording_directory': self._recording.base_recording_directory,\n 'channel_number': self._recording.channel_number,\n 'id': id_,\n 'playlist_directory': os.path.join(self._recording_directory_path, 'playlist'),\n 'playlist_file': playlist_file,\n 'program_title': self._recording.program_title,\n 'segments_directory': os.path.join(self._recording_directory_path, 'segments'),\n 'scheduled_end_date_time_in_utc': self._recording.end_date_time_in_utc.strftime(\n '%Y-%m-%d %H:%M:%S%z'),\n 'scheduled_start_date_time_in_utc': self._recording.start_date_time_in_utc.strftime(\n '%Y-%m-%d %H:%M:%S%z'),\n 'status': status},\n out_file,\n sort_keys=True,\n indent=4)\n\n logger.debug('Saved .MANIFEST\\n'\n 'Path => {0}'.format(manifest_file_path))\n except OSError:\n (type_, value_, traceback_) = sys.exc_info()\n logger.error('\\n'.join(traceback.format_exception(type_, value_, traceback_)))\n\n def _save_playlist_file(self, playlist_file_name, playlist_file_content):\n playlist_file_path = os.path.join(self._recording_directory_path, 'playlist', playlist_file_name)\n\n try:\n with open(playlist_file_path, 'w') as out_file:\n out_file.write(playlist_file_content)\n\n logger.debug('Saved playlist\\n'\n 'Path => {0}'.format(playlist_file_path))\n except OSError:\n (type_, value_, traceback_) = sys.exc_info()\n logger.error('\\n'.join(traceback.format_exception(type_, value_, traceback_)))\n\n def _save_segment_file(self, segment_file_name, segment_file_content):\n segment_file_path = os.path.join(self._recording_directory_path, 'segments', segment_file_name)\n\n try:\n with open(segment_file_path, 'wb') as out_file:\n out_file.write(segment_file_content)\n\n logger.debug('Saved segment\\n'\n 'Path => {0}'.format(segment_file_path))\n except OSError:\n (type_, value_, traceback_) = sys.exc_info()\n logger.error('\\n'.join(traceback.format_exception(type_, value_, traceback_)))\n\n def _set_stop_recording_event(self):\n self._stop_recording_event.set()\n\n logger.info('Stopping recording\\n'\n 'Channel name => {0}\\n'\n 'Channel number => {1}\\n'\n 'Program title => {2}\\n'\n 'Start date & time => {3}\\n'\n 'End date & time => {4}'.format(self._recording.channel_name,\n self._recording.channel_number,\n self._recording.program_title,\n self._recording.start_date_time_in_utc.astimezone(\n tzlocal.get_localzone()).strftime('%Y-%m-%d %H:%M:%S'),\n self._recording.end_date_time_in_utc.astimezone(\n tzlocal.get_localzone()).strftime('%Y-%m-%d %H:%M:%S')))\n\n def force_stop(self):\n self._set_stop_recording_event()\n\n def run(self):\n logger.info('Starting recording\\n'\n 'Channel name => {0}\\n'\n 'Channel number => {1}\\n'\n 'Program title => {2}\\n'\n 'Start date & time => {3}\\n'\n 'End date & time => {4}'.format(self._recording.channel_name,\n self._recording.channel_number,\n self._recording.program_title,\n self._recording.start_date_time_in_utc.astimezone(\n tzlocal.get_localzone()).strftime('%Y-%m-%d %H:%M:%S'),\n self._recording.end_date_time_in_utc.astimezone(\n tzlocal.get_localzone()).strftime('%Y-%m-%d %H:%M:%S')))\n actual_start_date_time_in_utc = datetime.now(pytz.utc)\n\n self._create_recording_directory_tree()\n persisted_recording_id = '{0}'.format(uuid.uuid4())\n self._save_manifest_file(None,\n actual_start_date_time_in_utc.strftime('%Y-%m-%d %H:%M:%S%z'),\n persisted_recording_id,\n None,\n 'Started')\n\n for number_of_times_attempted_to_download_playlist_m3u8 in range(1, 11):\n try:\n # \n playlist_m3u8_content = SmoothStreamsProxy.download_playlist_m3u8('127.0.0.1',\n '/live/playlist.m3u8',\n self._recording.channel_number,\n self._id,\n 'hls')\n # \n\n self._save_manifest_file(None,\n actual_start_date_time_in_utc.strftime('%Y-%m-%d %H:%M:%S%z'),\n persisted_recording_id,\n None,\n 'In Progress')\n\n playlist_m3u8_object = m3u8.loads(playlist_m3u8_content)\n chunks_url = '/live/{0}'.format(playlist_m3u8_object.data['playlists'][0]['uri'])\n\n break\n except requests.exceptions.HTTPError:\n time_to_sleep_before_next_attempt = math.ceil(\n number_of_times_attempted_to_download_playlist_m3u8 / 5) * 5\n\n logger.error('Attempt #{0}\\n'\n 'Failed to download playlist.m3u8\\n'\n 'Will try again in {1} seconds'.format(number_of_times_attempted_to_download_playlist_m3u8,\n time_to_sleep_before_next_attempt))\n\n time.sleep(time_to_sleep_before_next_attempt)\n else:\n logger.error('Exhausted attempts to download playlist.m3u8')\n\n logger.info('Canceling recording\\n'\n 'Channel name => {0}\\n'\n 'Channel number => {1}\\n'\n 'Program title => {2}\\n'\n 'Start date & time => {3}\\n'\n 'End date & time => {4}'.format(self._recording.channel_name,\n self._recording.channel_number,\n self._recording.program_title,\n self._recording.start_date_time_in_utc.astimezone(\n tzlocal.get_localzone()).strftime('%Y-%m-%d %H:%M:%S'),\n self._recording.end_date_time_in_utc.astimezone(\n tzlocal.get_localzone()).strftime('%Y-%m-%d %H:%M:%S')))\n\n self._save_manifest_file(datetime.now(pytz.utc).strftime('%Y-%m-%d %H:%M:%S%z'),\n actual_start_date_time_in_utc.strftime('%Y-%m-%d %H:%M:%S%z'),\n persisted_recording_id,\n None,\n 'Canceled')\n\n return\n\n vod_playlist_m3u8_object = None\n downloaded_segment_file_names = []\n\n while not self._stop_recording_event.is_set():\n try:\n # \n chunks_url_components = urllib.parse.urlparse(chunks_url)\n chunks_query_string_parameters = dict(urllib.parse.parse_qsl(chunks_url_components.query))\n\n channel_number_parameter_value = chunks_query_string_parameters.get('channel_number', None)\n client_uuid_parameter_value = chunks_query_string_parameters.get('client_uuid', None)\n nimble_session_id_parameter_value = chunks_query_string_parameters.get('nimblesessionid', None)\n smooth_streams_hash_parameter_value = chunks_query_string_parameters.get('wmsAuthSign', None)\n\n nimble_session_id_parameter_value = SmoothStreamsProxy.map_nimble_session_id(\n '127.0.0.1',\n channel_number_parameter_value,\n client_uuid_parameter_value,\n nimble_session_id_parameter_value,\n smooth_streams_hash_parameter_value)\n\n chunks_m3u8_content = SmoothStreamsProxy.download_chunks_m3u8('127.0.0.1',\n chunks_url_components.path,\n channel_number_parameter_value,\n client_uuid_parameter_value,\n nimble_session_id_parameter_value)\n # \n chunks_m3u8_download_date_time_in_utc = datetime.now(pytz.utc)\n chunks_m3u8_total_duration = 0\n chunks_m3u8_object = m3u8.loads(chunks_m3u8_content)\n\n if not vod_playlist_m3u8_object:\n vod_playlist_m3u8_object = chunks_m3u8_object\n\n indices_of_skipped_segments = []\n for (segment_index, segment) in enumerate(chunks_m3u8_object.segments):\n segment_url = '/live/{0}'.format(segment.uri)\n segment_url_components = urllib.parse.urlparse(segment_url)\n segment_query_string_parameters = dict(urllib.parse.parse_qsl(segment_url_components.query))\n segment_file_name = re.sub(r'(/.*)?(/)(.*\\.ts)', r'\\3', segment_url_components.path)\n\n chunks_m3u8_total_duration += segment.duration\n\n if segment_file_name not in downloaded_segment_file_names:\n try:\n # \n channel_number_parameter_value = segment_query_string_parameters.get('channel_number', None)\n client_uuid_parameter_value = segment_query_string_parameters.get('client_uuid', None)\n nimble_session_id_parameter_value = segment_query_string_parameters.get('nimblesessionid',\n None)\n\n ts_file_content = SmoothStreamsProxy.download_ts_file('127.0.0.1',\n segment_url_components.path,\n channel_number_parameter_value,\n client_uuid_parameter_value,\n nimble_session_id_parameter_value)\n # \n logger.debug('Downloaded segment\\n'\n 'Segment => {0}'.format(segment_file_name))\n\n downloaded_segment_file_names.append(segment_file_name)\n self._save_segment_file(segment_file_name, ts_file_content)\n\n segment.uri = '{0}?program_title={1}'.format(\n segment_file_name,\n urllib.parse.quote(self._recording.base_recording_directory))\n\n if segment not in vod_playlist_m3u8_object.segments:\n vod_playlist_m3u8_object.segments.append(segment)\n except requests.exceptions.HTTPError:\n logger.error('Failed to download segment\\n'\n 'Segment => {0}'.format(segment_file_name))\n else:\n logger.debug('Skipped segment since it was already downloaded\\n'\n 'Segment => {0} '.format(segment_file_name))\n\n indices_of_skipped_segments.append(segment_index)\n\n for segment_index_to_delete in indices_of_skipped_segments:\n del chunks_m3u8_object.segments[segment_index_to_delete]\n except requests.exceptions.HTTPError:\n logger.error('Failed to download chunks.m3u8')\n\n return\n\n current_date_time_in_utc = datetime.now(pytz.utc)\n wait_duration = chunks_m3u8_total_duration - (\n current_date_time_in_utc - chunks_m3u8_download_date_time_in_utc).total_seconds()\n if wait_duration > 0:\n self._stop_recording_event.wait(wait_duration)\n\n if vod_playlist_m3u8_object:\n vod_playlist_m3u8_object.playlist_type = 'VOD'\n self._save_playlist_file('playlist.m3u8', '{0}\\n'\n '{1}'.format(vod_playlist_m3u8_object.dumps(), '#EXT-X-ENDLIST'))\n\n self._save_manifest_file(datetime.now(pytz.utc).strftime('%Y-%m-%d %H:%M:%S%z'),\n actual_start_date_time_in_utc.strftime('%Y-%m-%d %H:%M:%S%z'),\n persisted_recording_id,\n 'playlist.m3u8',\n 'Completed')\n\n SmoothStreamsProxyPVR.delete_live_recording(self._recording)\n\n logger.info('Finished recording\\n'\n 'Channel name => {0}\\n'\n 'Channel number => {1}\\n'\n 'Program title => {2}\\n'\n 'Start date & time => {3}\\n'\n 'End date & time => {4}'.format(self._recording.channel_name,\n self._recording.channel_number,\n self._recording.program_title,\n self._recording.start_date_time_in_utc.astimezone(\n tzlocal.get_localzone()).strftime('%Y-%m-%d %H:%M:%S'),\n self._recording.end_date_time_in_utc.astimezone(\n tzlocal.get_localzone()).strftime('%Y-%m-%d %H:%M:%S')))\n","sub_path":"smooth_streams_proxy/recorder.py","file_name":"recorder.py","file_ext":"py","file_size_in_byte":35915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"525013471","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nfrom openpyxl import Workbook, load_workbook\nimport SessionState\nimport time\n\nclass ManualTagger:\n df_posts = None\n data_dic = None\n iterate_key = None\n curr_key = None\n session = None\n df_tags = None\n tags_list = None\n df_labeled = None\n \n def __init__(self):\n self.df_posts\n\n self.data_dic\n self.iterate_key\n self.curr_key\n self.session\n self.df_tags = pd.read_csv(\"Tags.csv\") #Gets the list of possible tags\n self.tags_list = self.df_tags.Tags.tolist()\n self.df_labeled = pd.read_csv('LabeledData.csv') #Reads in the initial empty labeled data files\n \"\"\"\n This function takes in a dataframe and returns a dictionary with the topic title as key and the leading comment as value\n \"\"\"\n #@st.cache(suppress_st_warning=True, allow_output_mutation=True) # This function will be cashed and won't be run again\n def load_data(self, unlabeled_data):\n\n def get_data_from_file(df):\n dic = {}\n for row in range(len(df)):\n dic[df['Topic Title'].iloc[row]] = df['Leading Comment'].iloc[row]\n return dic\n \n #data_dic: contains the the scrapped data: with the topic title as key and the leading comment as value\n self.data_dic = get_data_from_file(self.df_posts)\n #iterate_key: an iterater that goes to the next topic when called next(iterate_key)\n self.iterate_key = iter(self.data_dic.keys())\n #curr_key: the tracker that keeps track of the current topic title that we are on\n self.curr_key = next(self.iterate_key)\n\n def run(self, dataframe):\n self.df_posts = dataframe\n if self.df_posts.empty:\n st.write(\"\"\"\n ** ML July Team1 Manual Tagging App**\n All taggings are complete! Thank you for your help!\n \"\"\")\n return self.df_labeled\n else:\n #twoRounds = 1\n #while twoRounds <= 2:\n #Below is mainly code for StreamLit display.\n st.write(\"\"\"\n ** ML July Team1 Manual Tagging App**\n \"\"\")\n self.load_data(self.df_posts)\n #remove the tagged post from the dataset and reset\n \n st.write(\"**_Topic Title:_**\")\n st.write(self.curr_key)\n\n st.write(\"**_Leading Comment:_**\")\n st.write(self.data_dic[self.curr_key])\n \n self.session = SessionState.get(run_id=0)\n options = st.multiselect('Please select suitable tags for the above topic.', self.tags_list, key=self.session.run_id)\n st.write('**_You have selected:_**', options)\n\n #writes the tagged post to a excel file and removes the tagged post from the dataset and reset\n st.write(\"\"\"\n ** IMPORTANT: Once you hit \"Submit\" the label is perminant. Please make sure your decision is final before hitting submit! You have 2 minutes to complete the current topic tagging**\n \"\"\")\n if st.button(\"Submit\"):\n st.write(\"**You have submitted your choices**\")\n row_to_append = pd.DataFrame({self.df_labeled.columns[0]: [self.curr_key], self.df_labeled.columns[1]: [self.data_dic[self.curr_key]], self.df_labeled.columns[2]: [options]})\n self.df_labeled = self.df_labeled.append(row_to_append)\n self.df_labeled.to_csv('LabeledData.csv', index=False)\n df_posts = pd.read_csv(\"StackOverflow_new_tags.csv\")\n df_posts = df_posts.iloc[1:]\n df_posts.to_csv(\"StackOverflow_new_tags.csv\")\n \n #displays next topic\n self.session = SessionState.get(run_id=0)\n if st.button(\"Next Topic\"):\n st.write(\"**Going to the next topic**\")\n self.session.run_id += 1\n \n #time.sleep(10)\n #st.write(\"\"\"\n #** Sleep Time Over! **\n #\"\"\")\n #twoRounds += 1\n\n","sub_path":"ManualTagger/AnnotatorPythonVersion/ClassHumanTagger.py","file_name":"ClassHumanTagger.py","file_ext":"py","file_size_in_byte":4130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"255491417","text":"import vk_api\nfrom urllib.parse import urlencode\nfrom datetime import date, datetime\nimport re\nimport json\nfrom sys import exit\nfrom apps.config import cfg, client_id\n\n\nclass User:\n\n def __init__(self, user_id):\n self.id = user_id\n self.vk_api = None\n self.groups = None\n self.age = int()\n self.interest_list = None\n self.city = None\n self.sex = None\n self.token = None\n self.music = []\n self.interests = []\n self.books = []\n\n def get_main_user_data(self):\n try:\n data = self.vk_api.users.get(user_ids=self.id, fields='interests, music, books, sex, bdate, has_photo,'\n 'city, groups')\n self.id = data[0].get('id')\n except vk_api.exceptions.ApiError as e:\n print('Something went wrong', e)\n exit()\n except IndexError:\n print('Incorrectly entered ID')\n exit()\n try:\n day, month, year = data[0].get('bdate').split('.')\n self.age = calculate_age(datetime(year=int(year), month=int(month), day=int(day)))\n except ValueError:\n self.age = int(input('You must specify the age to search for a pair. Enter how old you are: '))\n except TypeError:\n self.age = int(input('You must specify the age to search for a pair. Enter how old you are: '))\n except AttributeError:\n self.age = int(input('You must specify the age to search for a pair. Enter how old you are: '))\n\n self.sex = data[0]['sex']\n if self.sex == 0:\n self.sex = input('Enter your gender to search for (1-m, 2-w): ')\n\n try:\n self.city = data[0].get('city')['id']\n except TypeError:\n look = str(input('In which city are we looking for a couple?: '))\n self.take_city_id(look)\n\n interests = data[0].get('interests')\n if interests:\n self.interests = interests_search(interests)\n else:\n self.interests = input('You have no interests, if you want to enter, then enter through a space: ') \\\n .split(' ')\n\n books = data[0].get('books')\n if interests:\n self.books = interests_search(books)\n else:\n self.books = []\n\n music = data[0].get('music')\n if interests:\n self.music = interests_search(music)\n else:\n self.music = []\n\n def take_groups(self):\n self.groups = self.vk_api.groups.get(user_id=self.id).get('items')\n\n def take_city_id(self, city):\n params = {\n 'country_id': 1,\n 'q': city,\n 'count': 1,\n 'v': '5.103'\n }\n cities = self.vk_api.database.getCities(**params)\n try:\n self.city = cities['items'][0]['id']\n except IndexError:\n print('*****City not found!')\n exit()\n\n def get_user_access(self):\n url = 'https://oauth.vk.com/authorize'\n params = {\n 'client_id': client_id,\n 'response_type': 'token',\n 'display': 'page',\n 'scope': ['groups', 'friends', 'photos'],\n 'v': '5.103',\n }\n print('?'.join((url, urlencode(params))))\n self.token = input('Enter the token from the redirect link: ')\n write_token('config.json', self.token)\n\n def create_session(self):\n try:\n configuration = take_config(cfg)\n if configuration['access_token']:\n session = vk_api.VkApi(token=configuration['access_token'])\n check = session.get_api()\n check.users.get(user_ids='1')\n self.vk_api = check\n else:\n self.get_user_access()\n session = vk_api.VkApi(token=self.token)\n self.vk_api = session.get_api()\n except vk_api.exceptions.ApiError:\n self.get_user_access()\n session = vk_api.VkApi(token=self.token)\n check = session.get_api()\n self.vk_api = check\n\n def is_member(self, groups, users):\n\n try:\n common_groups = self.vk_api.groups.isMember(group_id=groups, user_ids=users)\n common_groups += common_groups\n return common_groups\n except vk_api.exceptions.ApiError:\n common_groups = []\n return common_groups\n\n def search_all(self, count=1000):\n search_all = []\n search_all_dirt = []\n search_without_dubl = []\n if self.sex == 1:\n sex = 2\n age_from = self.age\n age_to = self.age + 10\n else:\n sex = 1\n age_from = self.age - 10\n age_to = self.age\n param = {\n 'count': count,\n 'sex': sex,\n 'age_to': age_to,\n 'has_photo': 1,\n 'city': self.city,\n 'fields': 'interests, music, movies, books, city, bdate, common_count'\n }\n for j in range(0, 1):\n search = self.vk_api.users.search(age_from=age_from + j, **param)['items']\n search_all_dirt += search\n for people in search_all_dirt:\n if people not in search_without_dubl:\n search_without_dubl.append(people)\n for people in search_without_dubl:\n if not people['is_closed']:\n people.update({'weight': 0})\n search_all.append(people)\n return search_all\n\n\ndef take_config(path_a):\n with open(path_a, 'r') as config:\n configuration = json.load(config)\n return configuration\n\n\ndef interests_search(interest):\n interest = re.sub(r'[?|$.!,:;]', r'', interest)\n match = re.findall(r'\\w+', interest)\n return [item.lower() for item in match]\n\n\ndef write_token(path, token):\n config = take_config(path)\n config.update({'access_token': token})\n with open (path, 'w') as con:\n json.dump(config, con)\n\n\ndef calculate_age(born):\n today = date.today()\n return today.year - born.year - ((today.month, today.day) < (born.month, born.day))\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"apps/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":6197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"205124725","text":"# 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。\r\n#\r\n# 你的算法时间复杂度必须是 O(log n) 级别。\r\n#\r\n# 如果数组中不存在目标值,返回 [-1, -1]。\r\n#\r\n# 示例 1:\r\n#\r\n# 输入: nums = [5,7,7,8,8,10], target = 8\r\n# 输出: [3,4]\r\n#\r\n# 示例 2:\r\n#\r\n# 输入: nums = [5,7,7,8,8,10], target = 6\r\n# 输出: [-1,-1]\r\n#\r\nfrom typing import List\r\n\r\n\r\nclass Solution:\r\n # 通过二分法找到第一个等于 target 的值, 然后以该值向左向右查找边界\r\n def searchRange(self, nums: List[int], target: int) -> List[int]:\r\n if not nums: return [-1, -1]\r\n left = 0\r\n right = len(nums) - 1\r\n while left <= right:\r\n mid = left + (right - left) // 2\r\n if target < nums[mid]:\r\n right = mid - 1\r\n elif target > nums[mid]:\r\n left = mid + 1\r\n else:\r\n left = mid\r\n right = mid\r\n while left - 1 >= 0 and nums[left - 1] == target:\r\n left -= 1\r\n while right + 1 < len(nums) and nums[right + 1] == target:\r\n right += 1\r\n return [left, right]\r\n return [-1, -1]\r\n\r\n\r\nif __name__ == '__main__':\r\n nums = [5, 7, 7, 8, 8, 10]\r\n target = 8\r\n print(Solution().searchRange(nums, target))\r\n nums = [5, 7, 7, 8, 8, 10]\r\n target = 6\r\n print(Solution().searchRange(nums, target))\r\n nums = [1]\r\n target = 1\r\n print(Solution().searchRange(nums, target))\r\n","sub_path":"31_40/034.py","file_name":"034.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"553187399","text":"\"\"\"\n@author: \")\n\tif text == \"q\":\n\t\tquit()\n\telif text == \"d\":\n\t\tcs.debug_mode = True\n\telse:\n\t\ttry:\n\t\t\tsemspecs = analyzer.parse(text)\n\t\t\tfor fs in semspecs:\n\t\t\t\ttry:\n\t\t\t\t\tntuple = cs.specialize(fs)\n\t\t\t\t\tdecoder.pprint_ntuple(ntuple)\n\t\t\t\t\tbreak\n\t\t\t\texcept Exception as e:\n\t\t\t\t\ttraceback.print_exc()\n\t\t\t\t\tprint(e)\n\t\texcept Exception as e:\n\t\t\ttraceback.print_exc()\n\t\t\tprint(e)","sub_path":"src/main/nluas/language/ntuple_visualizer.py","file_name":"ntuple_visualizer.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"364313160","text":"\"\"\"\nThis module provides helper methods for getting and returning\nthe dataframes and related objects to support the Facilty Maintenance\nDivision Key Performance Indicators reporting and exploratory analysis.\n\nIt provides methods for creating dataframes for kpis:\n1. hvac preventative maintenance to corrective maintenance\n2. customer satisfaction\n3. work orders closed on time\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\n\ndef fiscal_year(df):\n \"\"\"\n Function takes a dataframe with a DateTimeIndex and\n produces list with the corresponding fiscal year as a\n four digit year for each date on the index of the dataframe.\n\n The function is based on the Maryland Govt fiscal year which\n runs from July 1st to June 30th. It returns a list that is the\n same size as the original dataframe and allows the function call\n to be passed as a new column for fiscal year.\n \"\"\"\n fiscal_year = np.where(df.index.month >= 7,df.index.year+1, df.index.year)\n return fiscal_year\n\ndef create_satisfaction_dataframe(filepath):\n \"\"\"\n \"\"\"\n df = pd.read_excel(io=filepath,index_col='Start Date')\n df.drop(df.index[0], inplace=True)\n cols = ['finish','location','merge_left_other','area',\n 'srl_known','wr_id','past90_acknowledge_satisfaction',\n 'past90_satisfaction_comments','wait_satisfaction',\n 'wait_comments','communication_satisfaction',\n 'communication_comments','duration_satisfaction','duration_comments',\n 'past90_quality_satisfaction','quality_comments','helpfullness',\n 'friendliness','knowledge','skill','speed','professional',\n 'overall_service','room_improvement','improvement_comments',\n 'name','agency','email','phone']\n df.columns = cols\n\n # clean and merge for unified maintenance location response column\n df['location'] = np.where(df.location != 'Other (please specify)', df.location, df.merge_left_other)\n df.drop(['merge_left_other'], axis=1, inplace=True)\n df['phone'] = df['phone'].astype(str)\n\n # use fiscal_year function to update dataframe\n df['fiscal_year'] = fiscal_year(df)\n return df\n\n\ndef create_pm2cm_dataframe(filepath):\n \"\"\"\n Function takes filepath for the excel spreadsheet with archibus data\n located on the Zdrive. It returns a dataframe with a datetime index\n of work order date_requested and filters out all 'Test' work orders.\n\n The function also filters down to the most useful columns for analysis\n related to this indicator and establishes useful columns for exploratory\n data analysis such as a fiscal year column based on the City of Baltimore\n fiscal year and a column indicating the number of each type of work order\n for each fiscal year.\n\n Example usage:\n create_pm2cm_dataframe('Data/archibus_maintenance_data.xlsx')\n \"\"\"\n df = pd.read_excel(io=filepath,index_col='date_requested',\n usecols=['bl_id','date_requested','completed_by',\n 'date_assigned','date_closed','date_completed','prob_type',\n 'time_completed','wo_id','time_start','time_end'])\n df = df[df.prob_type != 'TEST(DO NOT USE)']\n df['duration'] = df['date_completed'] - df.index\n # use fiscal_year function to update dataframe\n df['fiscal_year'] = fiscal_year(df) # add column for volume by problem type per fiscal year\n df['problem_type_count_fiscal_year'] = df.groupby(['fiscal_year','prob_type'])['prob_type'].transform('count')\n return df\n\ndef create_pm2cm_kpi_values_dicts(df):\n \"\"\"\n Function takes dataframe object returned from the create_pm2cm_dataframe\n function in the fetcher module which returns a cleaned and formatted\n dataframe for analysis related to pm to cm kpi and other exploratory\n data analysis related to this hvac measure.\n\n The return value of this function is a tuple which lenght or size is\n determined by the number of fiscal years in the dataset such that the\n tupple size will always have x+1 dictionary items where x is the number of\n fiscal years present in the data. The first item in the tuple is\n a dictionary of the key: fiscal year and value: the pm to cm ratio for\n that fiscal year, the preceding dictionary item(s) returned by the fuction\n is a dictionary with key: fiscal year and value: dataframe subset filtered\n for the corresponding fiscal year. This is simply a subset of the main dataframe\n returned from the create_pm2cm_dataframe function or, in other words, a\n dataframe for each fiscal year.\n \"\"\"\n fiscal_years, fiscal_year_dataframes,pm2cm_kpi = [],[],[]\n corrective_maintenance = ['BOILER','CHILLERS','COOLING TOWERS','HVAC',\n 'HVAC INFRASTRUCTURE','HVAC|REPAIR']\n preventative_maintenance = ['PREVENTIVE MAINT','HVAC|PM']\n hvac_problemtypes = corrective_maintenance + preventative_maintenance\n\n for yr in df['fiscal_year'].unique():\n fiscal_years.append(yr)\n fiscal_year_dataframes.append(df[df['fiscal_year']==yr])\n fiscal_year_dataframes = dict(zip(fiscal_years,fiscal_year_dataframes))\n\n for key,value in fiscal_year_dataframes.items():\n # divide sum of pm counts by sum of cm counts & get pct%\n pm2cm_kpi.append(\n value[value['prob_type'].isin(preventative_maintenance)]['prob_type'].value_counts().sum()\\\n /\n value[value['prob_type'].isin(corrective_maintenance)]['prob_type'].value_counts().sum() *100\n )\n pm2cm_dict = dict(zip(fiscal_years,pm2cm_kpi))\n return pm2cm_dict, fiscal_year_dataframes\n","sub_path":"standard/FacilityMaintenanceDivision/fetcher.py","file_name":"fetcher.py","file_ext":"py","file_size_in_byte":5604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"268730996","text":"from nose.tools import *\nfrom numpy.testing import *\nimport unittest\nimport os\nimport numpy\n\nfrom pystoch.map_reduce_ops.counter_op import counter_op\nfrom pystoch.datatypes import DT, Singleton\n\nfrom pystoch.output.netcdf_out import netcdf_out\nfrom pystoch.grids import Grid\nfrom pystoch.grid_data import GridData\nfrom collections import OrderedDict\n\nfrom netCDF4 import Dataset\n\n\nFNAME = 'scratch.nc'\nclass CounterOpTest(unittest.TestCase):\n\n def setUp(self):\n \"\"\"\n Setup test\n \"\"\"\n DT(ndims=2,precision=numpy.float32,location_units='LatLon')\n \n \n def tearDown(self):\n \"\"\"\n Tear down test\n \"\"\"\n Singleton._instances.clear()\n \n try:\n os.unlink(FNAME)\n except OSError:\n pass\n \n \n def make_grid(self):\n \n extents = numpy.ndarray(1,DT.EXTENTS)\n extents['ll'][:] = 5.0\n extents['ur'][:] = 10.0\n \n grid_spacing = numpy.ndarray(1,DT.VECTOR)\n grid_spacing[:] = 1.0\n \n grid_dimensions = numpy.ndarray(1,DT.IVECTOR)\n grid_dimensions[:] = 5\n \n return Grid(extents,grid_spacing, grid_dimensions)\n\n def test_nc_from_grid_data(self):\n grid = self.make_grid()\n gd = GridData(grid)\n \n a = gd.allocate('count', numpy.int32)\n \n metadata = {'bobs':'bits'}\n dims = OrderedDict()\n dims['dim1'] = 2\n dims['dim2'] = 3 \n gd.allocate('bob', numpy.float64, grid_data_dimension=dims, initialize=1.0, metadata=metadata)\n \n \n netcdf_out(FNAME, 'scenario', 10, 'SHORE', gd)\n \n # Now read it back and make sure its right...\n \n rootgrp = Dataset(FNAME, 'r')\n assert_equal(rootgrp.title, 'Pystoch Oil Analysis')\n assert_equal(rootgrp.institution, 'RPS ASA')\n assert_equal(rootgrp.Conventions, \"CF-1.6\" )\n \n # do something weird because the keys come back in unicode\n assert_equal(tuple(str(s) for s in rootgrp.dimensions.keys()), ('latitude','longitude','dim1','dim2'))\n \n nc_var = rootgrp.variables['count']\n assert_equal(len(nc_var.ncattrs()),1)\n assert_equal(nc_var.dimensions,('longitude','latitude'))\n \n assert_array_equal(nc_var, gd.count)\n \n nc_var = rootgrp.variables['bob']\n assert_equal(len(nc_var.ncattrs()),2)\n assert_in('bobs', nc_var.ncattrs())\n assert_equal(nc_var.dimensions,('dim1','dim2','longitude','latitude',))\n \n assert_array_equal(nc_var, gd.bob)\n \n \n \n \n \n \n \n \n \n ","sub_path":"SyncModelRun/Push2ESRI/pystoch/pystoch/pystoch/output/tests/test_netcdf_out.py","file_name":"test_netcdf_out.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"209452364","text":"import time\r\nimport ExtendedStopWords as StopWordsHelper\r\nimport PyPDF2 as PDFHelper\r\nfrom nltk.tokenize import word_tokenize as WordHelper\r\nfrom nltk.stem import PorterStemmer\r\nfrom DocumentMap import DocumentMap\r\nimport xml.etree.cElementTree as xml\r\nfrom wordsegment import load, segment\r\nimport XMLWriter\r\nload()\r\n\r\n\r\nclass TermInDocPosting(object):\r\n _total_frequency = None\r\n _addresses = None\r\n _doc_id = None\r\n\r\n def __new__(cls, doc_id):\r\n instance = object.__new__(cls)\r\n # instance.__init__(doc_id)\r\n return instance\r\n\r\n def __init__(self, doc_id):\r\n self._total_frequency = 0\r\n self._doc_id = doc_id\r\n self._addresses = []\r\n\r\n def get_doc_id(self):\r\n return self._doc_id\r\n\r\n def get_doc_posting_list(self, doc_id):\r\n if self._doc_id is doc_id:\r\n return True\r\n return False\r\n\r\n def add_new_address_for_term(self, term_address, doc_id):\r\n if type(term_address) is not Address or type(doc_id) is not int:\r\n print(\"TermPosting::add_new_address_for_term - Invalid parameter type passed!\")\r\n return False\r\n if self._doc_id is not doc_id:\r\n print(\"TermPosting::add_new_address_for_term - docID mismatch!\")\r\n return False\r\n self._addresses.append(term_address)\r\n self._total_frequency += term_address.get_instances_count()\r\n return True\r\n\r\n def get_term_posted(self, page_number, doc_id):\r\n if type(page_number) is not int or type(doc_id) is not int:\r\n print(\"TermPosting::is_term_posted - Invalid parameter type passed!\")\r\n return False\r\n if self._doc_id is not doc_id:\r\n # docID mismatch, so return false\r\n return False\r\n\r\n # page_posting = [p_p.get_page_number() is page_number for p_p in self._addresses]\r\n try:\r\n # index = page_posting.index(True)\r\n return True\r\n except ValueError:\r\n # print(\"Item not in list!\")\r\n return False\r\n return False\r\n\r\n\r\nclass Address(object):\r\n _page_number = None\r\n _instance_indices = None\r\n\r\n def __new__(cls, page_number, indices):\r\n instance = object.__new__(cls)\r\n # instance.__init__(page_number, page, word)\r\n return instance\r\n\r\n def __init__(self, page_num, indices):\r\n self._page_number = page_num\r\n self._instance_indices = indices\r\n\r\n def get_page_number(self):\r\n return self._page_number\r\n\r\n def get_instances_count(self):\r\n return len(self._instance_indices)\r\n\r\n\r\nclass PDFTokenizer:\r\n _word_addresses = {\"\": []}\r\n stopWordObj = StopWordsHelper.ExtendedStopWord()\r\n StemmingHelper = PorterStemmer()\r\n StopWordsList = \"\"\r\n DocMapObj = None\r\n _term_vocabulary = None\r\n _new_term_vocabulary = None\r\n\r\n def __init__(self):\r\n self.StopWordsList = self.stopWordObj.thestopwords()\r\n self.DocMapObj = DocumentMap()\r\n self._term_vocabulary = {}\r\n self._new_term_vocabulary = {\"\": {-1: {-1: []}}}\r\n # { term1 : { doc_id : { page_num : [address_list]}}}\r\n\r\n def update_word_addresses(self, pdf_file_path, doc_id, vocab_root_node):\r\n try:\r\n pdf_file_obj = open(pdf_file_path, \"rb\")\r\n pdf_reader = PDFHelper.PdfFileReader(pdf_file_obj)\r\n for pi in range(0, pdf_reader.numPages):\r\n page_obj = pdf_reader.getPage(pi)\r\n\r\n # tokenization\r\n org_page_content = WordHelper(page_obj.extractText().lower())\r\n\r\n # stemming\r\n stemmed_content = [PorterStemmer().stem(w) for w in org_page_content]\r\n\r\n # stop word removal\r\n page_content = [w for w in stemmed_content if w not in self.StopWordsList]\r\n\r\n # TODO: ramacpr!!!!\r\n # store in xml format directly, this will be pushed later\r\n\r\n # for now store in class objects\r\n for term in page_content:\r\n # skip this term in case of website address.. for now.. \r\n # need to fix this issue \r\n if \"www\" in term: \r\n continue\r\n if \"//\" in term: \r\n continue\r\n if \"/\" in term:\r\n continue\r\n if \"=\" in term: \r\n continue\r\n if \"**\" in term: \r\n continue\r\n \r\n filter_xpath = \".//T[@W=\\\"\" + term + \"\\\"]\" \r\n term_node = vocab_root_node.find(filter_xpath)\r\n # if term is in vocab_root_node, \r\n # get the particular node and append new data to it\r\n if term_node is None:\r\n # term posting not present, so add now\r\n # get the term position in the original file content\r\n term_node = xml.Element(\"T\", W=str(term))\r\n doc_node = xml.Element(\"D\", ID=str(doc_id))\r\n page_node = xml.Element(\"P\", Num=str(pi))\r\n addr_node = xml.Element(\"A\")\r\n [addr_node.append(xml.Element(\"L\", POS=str(i)))\r\n for i, n in enumerate(stemmed_content) if n == term]\r\n page_node.append(addr_node)\r\n doc_node.append(page_node)\r\n term_node.append(doc_node)\r\n \"\"\" add this new term to root addr_node \"\"\"\r\n\r\n vocab_root_node.append(term_node)\r\n else:\r\n # check if term has term postings but\r\n # a. not for this document \r\n # b. not for this page\r\n filter_xpath = \"./D[@ID=\\\"\" + str(doc_id) + \"\\\"]\"\r\n doc_node = term_node.find(filter_xpath)\r\n if doc_node is None: \r\n # term has occured the first time in this document\r\n doc_node = xml.Element(\"D\", ID=str(doc_id))\r\n page_node = xml.Element(\"P\", Num=str(pi))\r\n addr_node = xml.Element(\"A\")\r\n [addr_node.append(xml.Element(\"L\", POS=str(i)))\r\n for i, n in enumerate(stemmed_content) if n == term]\r\n page_node.append(addr_node)\r\n doc_node.append(page_node)\r\n term_node.append(doc_node)\r\n else: \r\n # term has already occured in the document\r\n # now check if the term has posting for the current \r\n # page or not. \r\n # if yes, no need to do anything, continue\r\n filter_xpath = \"./P[@Num=\\\"\" + str(pi) + \"\\\"]\"\r\n page_node = doc_node.find(filter_xpath)\r\n if page_node is None:\r\n page_node = xml.Element(\"P\", Num=str(pi))\r\n addr_node = xml.Element(\"A\")\r\n [addr_node.append(xml.Element(\"L\", POS=str(i)))\r\n for i, n in enumerate(stemmed_content) if n == term]\r\n page_node.append(addr_node)\r\n doc_node.append(page_node)\r\n term_node.append(doc_node) \r\n else:\r\n continue \r\n finally:\r\n pdf_file_obj.close()\r\n\r\n def PublishVocabulary(self, vocab_file_name, vocab_root_node_to_publish):\r\n docMapXMLWriter = XMLWriter.XMLWriter()\r\n docMapXMLWriter.push_to_file(vocab_file_name, vocab_root_node_to_publish)\r\n return\r\n\r\n def tokenize(self, pdf_file_name_list, vocab_root_node):\r\n for pdf_file_name in pdf_file_name_list:\r\n # update the docID for this file and use the docID in all places\r\n doc_id = self.DocMapObj.AddDocToMap(pdf_file_name)\r\n if doc_id is -1:\r\n continue\r\n start = time.clock()\r\n \r\n # first fetch the term postings\r\n self.update_word_addresses(pdf_file_name, doc_id, vocab_root_node)\r\n print(\"Time Taken = \", str(time.clock() - start))\r\n \r\n # now write all term postings in a xml file \r\n self.PublishVocabulary(\"D:\\\\final_vocab.xml\", vocab_root_node)\r\n \r\n","sub_path":"SearchUtility/PDF_Tokenizer_New.py","file_name":"PDF_Tokenizer_New.py","file_ext":"py","file_size_in_byte":8718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"159372052","text":"'''\n************************************************\n[Author ]: Forrest.Gu@emc.com\n[Function]: Dict of NVRAM layout. \n Key:\n sel\n table\n bmc_redundant_image_device_id_cache\n bmc_redundant_flag\n bmc_bist_configuration_checksum\n bmc_bist_configuration\n bmc_nvram_bist_scratchpad\n bios\n post\n common_validated_firmware_rev_number\n common_usd_reserved_memory\n common_e820_memory_map\n common_smi_handler_driven_error_status\n common_bad_dimm_serial_number\n common_memory_persistence\n common_copy_of_mp_resume\n Value:\n {'Offset': int_offset, 'Length': int_length}\n\n[History ] \n - Forrest.Gu@emc.com 07/18/2014\n initial edition\n************************************************\n''' \n\ndict_nvram_layout = {\n 'sel': {'Offset': 0x000000, 'Length': 65536},\n 'table': {'Offset': 0x010000, 'Length': 768},\n 'bmc_redundant_image_device_id_cache': {'Offset': 0x010300, 'Length': 16},\n 'bmc_redundant_flag': {'Offset': 0x010310, 'Length': 1},\n 'bmc_bist_configuration_checksum': {'Offset': 0x0103fe, 'Length': 2},\n 'bmc_bist_configuration': {'Offset': 0x010400, 'Length': 64},\n 'bmc_nvram_bist_scratchpad': {'Offset': 0x010b00, 'Length': 2048-4},\n 'bios': {'Offset': 0x011300, 'Length': 4096},\n 'post': {'Offset': 0x012300, 'Length': 4096},\n 'common_validated_firmware_rev_number': {'Offset': 0x013300, 'Length': 2},\n 'common_usd_reserved_memory': {'Offset': 0x013320, 'Length': 32},\n 'common_e820_memory_map': {'Offset': 0x013360, 'Length': 1640},\n 'common_smi_handler_driven_error_status': {'Offset': 0x139d0, 'Length': 1224},\n 'common_bad_dimm_serial_number': {'Offset': 0x013ea0, 'Length': 64},\n 'common_memory_persistence': {'Offset': 0x013f00, 'Length': 12},\n 'common_copy_of_mp_resume': {'Offset': 0x014000, 'Length': 2048},\n }","sub_path":"pub/NVRAM.py","file_name":"NVRAM.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"619514934","text":"'''\r\nEx 07 da Aula 6\r\nObjetivo: Escreva um programa que calcule o MMC (mínimo múltiplo comum)\r\nentre dois números naturais.\r\nEntrada: Dois numeros naturais\r\nSaída: O MMC entre eles\r\n'''\r\n\r\nn1=-1\r\nn2=-1\r\nwhile n1<=0 or n2<=0:\r\n n1=int(input(\"Digite natural n1 (>=0):\"))\r\n n2=int(input(\"Digite natural n2 (>=0):\")) \r\naux=n1\r\nresto=aux%n2\r\nwhile resto!=0:\r\n aux=aux+n1 #multiplo\r\n resto=aux%n2\r\nprint(\"MMC(%d,%d)=%d\" %(n1,n2,aux))\r\n","sub_path":"1 semestre/Aula_06_Ex_07_MMC.py","file_name":"Aula_06_Ex_07_MMC.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"136140688","text":"import cv2\nimport sys\nimport numpy as np\nimport datetime\n# sys.path.append('.')\nfrom ssha_detector import SSHDetector\nimport lz\nfrom lz import *\n\ninit_dev(get_dev(mem_thresh=(.5, .5)))\n# scales = [1080, 1920]\nscales = [4032, 3024]\ndetector = SSHDetector('./kmodel/e2e', 0)\ntry:\n import pims\nexcept:\n print('!! no pims')\nfrom lz import *\nimport cvbase as cvb\nimport cv2, math\n\nparam_type = 'mov'\nparam_day = 'yy'\n# param_type = 'mp4'\n# param_day = 'yy2'\nprint('!! use ', param_day, param_type)\nv = pims.Video(f'face.{param_day}/video.{param_type}')\nres = lz.msgpack_load(lz.work_path + f'face.{param_day}/{param_day}.{param_type}.pk')\nvideo_writer = cv2.VideoWriter(work_path + f'/t2.{param_day}.{param_type}.avi',\n cv2.VideoWriter_fourcc(*'XVID'), 25,\n (v.frame_shape[1], v.frame_shape[0])\n if not (param_type == 'mov' and param_day == 'yy2') else (\n v.frame_shape[0], v.frame_shape[1])\n )\ncv2.namedWindow('test', cv2.WINDOW_NORMAL)\n# from deep_pose import PoseDetector\n# pose_det = PoseDetector()\n\nfrom insightface import FeaExtractor\n\nif param_day == 'yy':\n face_dir = '/home/xinglu/work/youeryuan/20180930 新中二班-缪蕾老师班-29、30/中二班9月29日-正侧背/face/'\nelse:\n face_dir = '/home/xinglu/work/youeryuan/20180930 新中二班-缪蕾老师班-29、30/中二班9月30日-正侧背/face/'\nyy_imgs = msgpack_load(f'{face_dir}/face.pk')\nyy_feas = msgpack_load(f'{face_dir}/fea.pk')\nyy_feas_norms = msgpack_load(f'{face_dir}/fea.norm.pk')\n\nextractor = FeaExtractor(day=param_day,\n yy_imgs=yy_imgs,\n yy_feas=yy_feas,\n yy_feas_norms=yy_feas_norms,\n mx=True\n )\n\nsuccs = []\n\nfor ind, faces in res.items():\n # ind = list(res.keys())[50]\n # faces = res[ind]\n frame = v[ind]\n frame = frame if not (param_type == 'mov' and param_day == 'yy2') else np.rot90(frame, ).copy()\n # plt_imshow(np.rot90(frame, 0), )\n # plt.show()\n \n frame = cvb.rgb2bgr(frame)\n # print(faces.shape)\n # img = frame.copy()\n frame_ori = frame.copy()\n frame_ori2 = frame.copy()\n img = frame\n # img = cvb.read_img('test_image/test_2.jpg').copy()\n \n for num in range(faces.shape[0]):\n score = faces[num, 4]\n if score < 0.9: continue\n # print(score)\n bbox = faces[num, 0:5]\n label_text = 'det {:.02f}'.format(bbox[4])\n cv2.putText(img, label_text, (int(bbox[0]),\n int(bbox[1] - 2)),\n cv2.FONT_HERSHEY_COMPLEX, 1., (0, 255, 0), 2, cv2.LINE_AA)\n cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2)\n # kpoint = faces[num, 5:15]\n # for knum in range(5):\n # cv2.circle(img, (kpoint[2 * knum], kpoint[2 * knum + 1]), 1, [0, 0, 255], 2)\n \n # cvb.show_img(img, win_name='', wait_time=1000 // 40)\n # cvb.show_img(img, win_name='', )\n # cv2.imwrite(\"res.jpg\".format(ind), img)\n \n flag = False\n for num, landmarks in enumerate(faces[:, 5:]):\n bbox = faces[num, 0:5]\n imgpts, modelpts, rotate_degree, nose = face_orientation(frame, landmarks) # roll, pitch, yaw\n \n \n # pose_angle = pose_det.det(frame_ori, bbox, frame) # yaw pitch roll\n \n def get_normalized_pnt(nose, pnt):\n global flag\n nose = np.asarray(nose).reshape(2, )\n pnt = np.asarray(pnt).reshape(2, )\n dir = pnt - nose\n norm = np.sqrt((dir ** 2).sum())\n if norm > 10000:\n print('pose norm is', norm)\n flag = True\n pnt = tuple(np.asarray(pnt).ravel())\n # not normalize in fact\n return pnt\n \n \n for imgpt in imgpts:\n get_normalized_pnt(nose, imgpt)\n if flag:\n break\n \n cv2.line(frame, nose, get_normalized_pnt(nose, imgpts[1]), (0, 255, 0), 3) # GREEN\n cv2.line(frame, nose, get_normalized_pnt(nose, imgpts[0]), (255, 0, 0,), 3) # BLUE\n cv2.line(frame, nose, get_normalized_pnt(nose, imgpts[2]), (0, 0, 255), 3) # RED\n remapping = [2, 3, 0, 4, 1]\n \n for index in range(len(landmarks) // 2):\n random_color = random_colors[index]\n \n cv2.circle(frame, (landmarks[index * 2], landmarks[index * 2 + 1]), 5, random_color, -1)\n # cv2.circle(frame, tuple(modelpts[remapping[index]].ravel().astype(int)), 2, random_color, -1)\n \n for j in range(len(rotate_degree)):\n color = [(0, 255, 0), (255, 0, 0), (0, 0, 255)][j]\n cv2.putText(frame,\n ('{:05.2f}').format(float(rotate_degree[j])),\n (10, 30 + 50 * j + 170 * num), cv2.FONT_HERSHEY_SIMPLEX, 1,\n color, thickness=2, lineType=2)\n score = faces[num, 4]\n if score < 0.9: continue\n bbox = faces[num, 0:4]\n width = bbox[2] - bbox[0]\n height = bbox[3] - bbox[1]\n if min(width, height) < 15: continue\n rotate_degree = np.asarray(rotate_degree, int)\n rotate_degree = np.abs(rotate_degree)\n roll, pitch, yaw = rotate_degree\n if pitch > 10 or yaw > 10: continue\n print('roll pitch yaw ', roll, pitch, yaw)\n # crop_face = cvb.crop_img(frame_ori, bbox)\n # crop_face = cvb.crop_img(frame, bbox)\n # cvb.show_img(crop_face, wait_time=1000 // 20)\n \n kps = faces[num, 5:].reshape(5, 2)\n warp_face = preprocess(frame_ori, bbox=bbox, landmark=kps)\n # cvb.show_img(warp_face, wait_time=1000 // 20)\n # cvb.show_img(warp_face, )\n sim, norm = extractor.compare(warp_face, return_norm=True)\n ind_gallery = sim.argmax()\n # if sim[0, ind_gallery] > 0.1 and norm > 2.:\n if norm > 3.5 and sim[0, ind_gallery] > 0.5:\n print('!! sim is', sim[0, ind_gallery], 'norm ', norm)\n img_gallery = list(extractor.yy_imgs.values())[ind_gallery]\n img_gallery_norm = list(extractor.yy_feas_norms.values())[ind_gallery]\n cv2.putText(img, f'id {int(ind_gallery)}', (int(bbox[0]),\n int(bbox[1] - 2 - 20)),\n cv2.FONT_HERSHEY_COMPLEX, 1.5, (0, 0, 255), 2, cv2.LINE_AA)\n max_succ = frame.shape[1] // 224\n while len(succs) > max_succ:\n succs.pop(0)\n flagp = False\n if len(succs) == 0:\n flagp = True\n if np.all([ind_gallery != succ[-1] for succ in succs]):\n flagp = True\n if flagp:\n succs.append([img_gallery, warp_face, sim, norm, ind_gallery])\n \n # out_fn = f'face.{param_day}/gallery/{param_type}_{ind}_{num}.png'\n # assert not osp.exists(out_fn)\n # cvb.write_img(warp_face, out_fn)\n if flag:\n continue\n max_succ = frame.shape[1] // 224\n while len(succs) > max_succ:\n succs.pop(0)\n for ind, (img_gallery, warp_face, sim, norm, ind_gallery) in enumerate(succs[::-1]):\n frame[- 112:, # row\n - (112 + 112 * ind * 2 + 10 * ind + 1):-(112 * ind * 2 + 10 * ind + 1), # col\n :] = img_gallery\n \n frame[-112:,\n -(112 + 112 * (ind * 2 + 1) + 10 * ind + 1): -(112 * (ind * 2 + 1) + 10 * ind + 1),\n :] = warp_face\n \n cv2.putText(frame, f'sim {sim[0, ind_gallery]:.2f}',\n (frame.shape[1] - 112 - 112 * (ind * 2 + 1), # col\n frame.shape[0] - 112), # row\n cv2.FONT_HERSHEY_COMPLEX, .9, (0, 255, 0), 2, cv2.LINE_AA)\n cv2.putText(frame, f'norm {norm:.2f}',\n (frame.shape[1] - 112 - 112 * (ind * 2 + 1), # col\n frame.shape[0] - 112 - 112 // 4), # row\n cv2.FONT_HERSHEY_COMPLEX, .9, (0, 255, 0), 2, cv2.LINE_AA)\n cv2.putText(frame, f'ind {int(ind_gallery)}',\n (frame.shape[1] - 112 - 112 * (ind * 2 + 1), # col\n frame.shape[0] - 112 - 112 // 4 * 2), # row\n cv2.FONT_HERSHEY_COMPLEX, .6, (0, 0, 255), 2, cv2.LINE_AA)\n \n cvb.show_img(frame, win_name='test', wait_time=1000 // 80)\n video_writer.write(frame)\n\nvideo_writer.release()\n","sub_path":"tools/infer_video.py","file_name":"infer_video.py","file_ext":"py","file_size_in_byte":8500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"294051218","text":"from kafka import KafkaConsumer\nimport requests\nimport logging\nimport json\n\nbootstrap_servers = ['kafka:9092']\ntopic_name = 'geolocations'\n\nlog = logging.getLogger('consumer')\nlogging.basicConfig(level=logging.INFO)\nconsumer = KafkaConsumer(topic_name, bootstrap_servers=bootstrap_servers,\n value_deserializer=lambda m: json.loads(m.decode('utf-8')))\n\nfor message in consumer:\n #log.info(message)\n payload = message.value\n log.info(payload)\n\n url = 'http://location-api:5000/api/locations'\n response = requests.post(url, json=payload)\n log.info(response)","sub_path":"modules/kafka-consumer/app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"392106716","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: ARYAMAN\n\"\"\"\n\nfrom flask import Flask, request, render_template\n\n# create smtp session\n\nimport requests\n\n# NOTE: you must manually set API_KEY below using information retrieved from your IBM Cloud account.\nAPI_KEY = \"IPaBSf1Wot6_h4V96vdPGcOgSlAq0tSiFO1ZB7cuE6b4\"\ntoken_response = requests.post('https://iam.cloud.ibm.com/identity/token', data={\"apikey\": API_KEY, \"grant_type\": 'urn:ibm:params:oauth:grant-type:apikey'})\nmltoken = token_response.json()[\"access_token\"]\n\nheader = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + mltoken}\n\n#lg_model=joblib.load('logreg.save')\n\napp = Flask(__name__)\n\n@app.route('/')\ndef home():\n return render_template('home.html')\n\n@app.route('/prediction')\ndef prediction():\n return render_template('index.html')\n\n@app.route('/info')\ndef info():\n return render_template('info.html')\n\n@app.route('/prediction/y_predict',methods=['POST'])\ndef y_predict():\n x_test=[[x for x in request.form.values()]]\n print(x_test)\n #Job duration\n if x_test[0][0] == 'Full Time':\n x_test[0][0] = 1\n else:\n x_test[0][0] = 0\n \n print(x_test)\n #Soc_id\n if x_test[0][1] == 'Administrative':\n x_test[0][1] = 0\n elif x_test[0][1] == 'Agriculture':\n x_test[0][1] = 1\n elif x_test[0][1] == 'Audit':\n x_test[0][1] = 2\n elif x_test[0][1] == 'Database':\n x_test[0][1] = 3\n elif x_test[0][1] == 'Education':\n x_test[0][1] = 4\n elif x_test[0][1] == 'Estate':\n x_test[0][1] = 5\n elif x_test[0][1] == 'Executives':\n x_test[0][1] = 6\n elif x_test[0][1] == 'Finance':\n x_test[0][1] = 7\n elif x_test[0][1] == 'H.R':\n x_test[0][1] = 8\n elif x_test[0][1] == 'IT':\n x_test[0][1] = 9\n elif x_test[0][1] == 'Manager':\n x_test[0][1] = 10\n elif x_test[0][1] == 'Mechanical':\n x_test[0][1] = 11\n elif x_test[0][1] == 'Medical':\n x_test[0][1] = 12\n elif x_test[0][1] == 'P.R':\n x_test[0][1] = 13\n elif x_test[0][1] == 'Sales & Market':\n x_test[0][1] = 14\n elif x_test[0][1] == 'others':\n x_test[0][1] = 15\n \n #prediction = lg_model.predict(x_test)\n #print(prediction)\n #output = prediction[0]\n #print(output)\n print(x_test)\n \n payload_scoring = {\"input_data\": [{\"field\": [[\"FULL_TIME_POSITION\",\"SOC_N\",\"PREVAILING_WAGE\",\"YEAR\"]], \"values\": [[int(x_test[0][0]),int(x_test[0][1]),int(x_test[0][2]),int(x_test[0][3])]]}]}\n\n response_scoring = requests.post('https://us-south.ml.cloud.ibm.com/ml/v4/deployments/435b1a86-eeea-428d-86e5-1bb8d392a672/predictions?version=2021-08-03', json=payload_scoring, headers={'Authorization': 'Bearer ' + mltoken})\n print(\"Scoring response\")\n predictions = response_scoring.json()\n output = predictions['predictions'][0]['values'][0][0]\n \n if output==0:\n pred='CERTIFIED'\n elif output==1:\n pred='CERTIFIED-WITHDRAWN'\n elif output==2:\n pred='DENIED'\n elif output==3:\n pred='WITHDRAWN'\n elif output==4:\n pred='PENDING QUALITY AND COMPLIANCE REVIEW - UNASSIGNED'\n elif output==5:\n pred='REJECTED'\n elif output==6:\n pred='INVALIDATED'\n \n return render_template('index.html',prediction_text='{}'.format(pred))\n\n\n\nif __name__=='__main__':\n app.run(debug=True)\n \n# -*- coding: utf-8 -*-\n\n","sub_path":"myProject/project_app.py","file_name":"project_app.py","file_ext":"py","file_size_in_byte":3382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"} +{"seq_id":"558351777","text":"#!/usr/bin/env python3\nimport sys\nfrom scapy.all import *\nimport codecs\n\nif len(sys.argv) != 4:\n\tprint(\"Bad format!\")\n\tprint(\"Instruction:\")\n\tprint(\"./listener [source_ip] [interface] [file]\")\n\tsys.exit()\n\nINTERFACE = sys.argv[2]\nSNIFF_FILER = 'src host ' + sys.argv[1]\nFILENAME = sys.argv[3]\nDEFAULT_TEXT_FILE_LENGTH = 75075\nDEFAULT_FILE_CHUNK_SIZE = 1440\nDEFAULT_INITIAL_CODE = \"YES\"\nDEFAULT_MESSAGE_INITIALS = codecs.encode(DEFAULT_INITIAL_CODE.encode(), \"base64\")\n\nbyte_msg = bytes()\nmsg_len_diff = DEFAULT_TEXT_FILE_LENGTH\nfile = open(FILENAME, \"w+\")\n\ndef packet_handler(pkt):\n\tglobal byte_msg\n\tglobal msg_len_diff\n\tif TCP in pkt and pkt[TCP].sport > 1024:\n\t\tpayload = bytes(pkt[TCP].payload)\n\t\tif DEFAULT_MESSAGE_INITIALS in payload:\n\t\t\tif msg_len_diff > DEFAULT_FILE_CHUNK_SIZE:\n\t\t\t\tbyte_msg += bytes(payload[-DEFAULT_FILE_CHUNK_SIZE:])\n\t\t\t\tmsg_len_diff-=DEFAULT_FILE_CHUNK_SIZE\n\t\t\telse:\n\t\t\t\tbyte_msg += bytes(payload[-msg_len_diff:])\n\ndef file_loader(pkt):\n\tglobal byte_msg\n\tif len(byte_msg) == DEFAULT_TEXT_FILE_LENGTH:\n\t\tnormal_msg = codecs.decode(bytes(byte_msg), 'base64')\n\t\tnormal_msg = normal_msg.decode()\n\t\tfile.write(normal_msg)\n\t\tfile.close()\n\t\treturn True\n\nsniff(\n\tiface=INTERFACE,\n\tstore=False,\n\tprn=packet_handler,\n\tstop_filter=file_loader,\n\tfilter=SNIFF_FILER\n)\n\n\n","sub_path":"listener.py","file_name":"listener.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"23"}