diff --git "a/190.jsonl" "b/190.jsonl" new file mode 100644--- /dev/null +++ "b/190.jsonl" @@ -0,0 +1,665 @@ +{"seq_id":"574184389","text":"# -*- coding: utf-8 -*-\nfrom selenium import webdriver\nfrom web_auto_zentao.common.FengZhuang import WrapperFunctions\nfrom web_auto_zentao.pages.login_page import ZenTaoLogin\nimport unittest\nimport time\n\nurl = 'http://127.0.0.1:82/zentao/user-login-L3plbnRhby8=.html'\n\n\nclass Login(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.driver = webdriver.Chrome()\n cls.driver.maximize_window()\n cls.zl = ZenTaoLogin(cls.driver)\n\n def setUp(self):\n self.driver.get(url)\n\n # 清空cookies 退出登陆\n self.driver.delete_all_cookies()\n # 刷新页面\n self.driver.refresh()\n\n def test_login01(self):\n '''(user='ad', psw='123456')'''\n self.zl.login(user='ad', psw='123456')\n self.zl.isAlert()\n res = self.zl.isloginName()\n self.assertTrue(res == \"\")\n\n def test_login02(self):\n '''(user='admin', psw='123456')'''\n self.zl.login(user='admin', psw='123456')\n self.zl.isAlert()\n res = self.zl.isloginName()\n self.assertTrue(res == True)\n\n def test_login03(self):\n '''(user='admin', psw='1234567')'''\n self.zl.login(user='admin', psw='1234567')\n self.zl.isAlert()\n res = self.zl.isloginName()\n self.assertTrue(res == \"\")\n\n def test_login04(self):\n '''点击忘记密码'''\n self.zl.forget_login()\n self.zl.isuserReset()\n\n @classmethod\n def tearDownClass(cls):\n cls.driver.quit()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"web_auto_zentao/case/test_login.py","file_name":"test_login.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"118712112","text":"import csv\r\nimport os\r\n\r\ncsv_path = os.path.join('Resources','election_data.csv')\r\npathout = os.path.join('Resources','election_results.txt')\r\n\r\ntotal_votes = 0\r\nwinner_votes = 0\r\nwinner = \"\"\r\ncandidate_options = []\r\ncandidate_votes = {}\r\n\r\n#read the data\r\nwith open(csv_path) as election_data:\r\n\r\n reader = csv.reader(election_data)\r\n \r\n\r\n header = next(reader)\r\n\r\n for row in reader:\r\n total_votes = total_votes + 1 \r\n candidate_name = row[2]\r\n\r\n# print(candidate_name)\r\n if candidate_name not in candidate_options:\r\n candidate_options.append(candidate_name)\r\n candidate_votes[candidate_name]=0\r\n \r\n candidate_votes[candidate_name]= candidate_votes[candidate_name] +1\r\n\r\nfor candidate in candidate_votes:\r\n votes = candidate_votes[candidate]\r\n if (votes > winner_votes):\r\n winner_votes = votes\r\n winner = candidate\r\n Percentage = float(votes)/float(total_votes)*100\r\n \r\n#print \r\nprint()\r\nprint('Election Results')\r\nprint('------------------------------')\r\nprint('Total Votes: ' + str(total_votes))\r\nprint('------------------------------')\r\n\r\nfor candidate in candidate_votes:\r\n votes = candidate_votes[candidate]\r\n Percentage = round(float(votes)/float(total_votes)*100,3)\r\n print(candidate + ': ' + str(Percentage) + '% ' + '('+ str(votes) + ')')\r\n\r\nprint('------------------------------')\r\nprint('Winner: '+str(winner))\r\nprint('------------------------------')\r\n\r\n# outputing files\r\nwith open(pathout, 'w') as txt_file:\r\n txt_file.write('Election Results')\r\n txt_file.write('\\n')\r\n txt_file.write('------------------------------')\r\n txt_file.write('\\n')\r\n txt_file.write('Total Votes: ' + str(total_votes))\r\n txt_file.write('\\n')\r\n txt_file.write('------------------------------')\r\n txt_file.write('\\n')\r\n\r\n for candidate in candidate_votes:\r\n votes = candidate_votes[candidate]\r\n Percentage = round(float(votes)/float(total_votes)*100,3)\r\n txt_file.write(candidate + ': ' + str(Percentage) + '% ' + '('+ str(votes) + ')')\r\n txt_file.write('\\n')\r\n\r\n txt_file.write('\\n')\r\n txt_file.write('------------------------------')\r\n txt_file.write('\\n')\r\n txt_file.write('Winner: ' + str(winner))\r\n txt_file.write('\\n')\r\n txt_file.write('------------------------------')\r\n ","sub_path":"PyPoll/main .py","file_name":"main .py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"48258875","text":"import re\r\nfrom datetime import datetime\r\n\r\n\r\nfirstmonth=[]\r\nfirstyear=[]\r\nsecondmonth=[]\r\nsecondyear=[]\r\nline=\" Worked as Test Analyst in Thomson Reuters from Jan’10 to Dec’14.\"\r\nx=re.findall(r\"\\b(?i)(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(?:Nov|Dec)(?:ember)?)[ ]*.[ ]*[0-9]{2,4}\",line)\r\nprint(x)\r\nif(x):\r\n if(len(x)==1):\r\n firstyear=re.findall(r\"[0-9]{2,4}\",x[0])\r\n firstmonth=re.findall(r\"\\b(?i)(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(?:Nov|Dec)(?:ember)?)\",x[0])\r\n lsecondmonth=datetime.now().strftime('%h')\r\n secondmonth=[]\r\n secondmonth.append(lsecondmonth)\r\n lsecondyear=str(datetime.now().year)\r\n secondyear=[]\r\n secondyear.append(lsecondyear)\r\n print(firstmonth)\r\n print(firstyear)\r\n print(secondmonth)\r\n print(secondyear)\r\n \r\n\r\n else:\r\n \r\n firstyear=re.findall(r\"[0-9]{2,4}\",x[0])\r\n firstmonth=re.findall(r\"\\b(?i)(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(?:Nov|Dec)(?:ember)?)\",x[0])\r\n secondyear=re.findall(r\"[0-9]{2,4}\",x[1])\r\n secondmonth=re.findall(r\"\\b(?i)(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(?:Nov|Dec)(?:ember)?)\",x[1])\r\n print(firstmonth)\r\n print(firstyear)\r\n print(secondmonth)\r\n print(secondyear)\r\ndef expcalc(firstmonth,firstyear,secondmonth,secondyear):\r\n year1=firstyear[-3:]\r\n\r\n\r\n year2=secondyear[-3:]\r\n \r\n \r\n m1=firstmonth.lower()\r\n m2=secondmonth.lower()\r\n m1=m1[0:3]\r\n \r\n m2=m2[0:3]\r\n \r\n month1=0\r\n month2=0\r\n if(m1==\"jan\"):\r\n month1=1\r\n \r\n if(m1==\"feb\"):\r\n month1=2\r\n if(m1==\"mar\"):\r\n month1=3\r\n if(m1==\"apr\"):\r\n month1=4\r\n if(m1==\"may\"):\r\n month1=5\r\n if(m1==\"jun\"):\r\n month1=6\r\n if(m1==\"jul\"):\r\n month1=7\r\n if(m1==\"aug\"):\r\n month1=8\r\n if(m1==\"sep\"):\r\n month1=9\r\n if(m1==\"oct\"):\r\n month1=10\r\n if(m1==\"nov\"):\r\n month1=11\r\n if(m1==\"dec\"):\r\n month1=12\r\n\r\n if(m2==\"jan\"):\r\n month2=1\r\n if(m2==\"feb\"):\r\n month2=2\r\n if(m2==\"mar\"):\r\n month2=3\r\n if(m2==\"apr\"):\r\n month2=4\r\n if(m2==\"may\"):\r\n month2=5\r\n if(m2==\"jun\"):\r\n month2=6\r\n if(m2==\"jul\"):\r\n month2=7\r\n if(m2==\"aug\"):\r\n month2=8\r\n if(m2==\"sep\"):\r\n month2=9\r\n if(m2==\"oct\"):\r\n month2=10\r\n if(m2==\"nov\"):\r\n month2=11\r\n if(m2==\"dec\"):\r\n month2=12\r\n\r\n \r\n years=(int(year2)-int(year1))*12\r\n \r\n months=(month2-month1)\r\n \r\n total=(months+years)/12\r\n print(total)\r\n\r\n\r\nexpcalc(firstmonth[0],firstyear[0],secondmonth[0],secondyear[0])\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n ","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"337563938","text":"from collections import Counter\n\nfilename = 'file.txt'\ni = 1\nwords = []\ntry:\n with open(filename, 'r') as f:\n for line in f:\n for word in line.split():\n words.append(word)\nexcept IOError:\n sys.stderr.write('problem reading ' + filename)\n\nfrequency = Counter(words)\nprint(frequency)","sub_path":"read_file.py","file_name":"read_file.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"636498625","text":"import os\nfrom will.unittests import TestCase\nfrom expects import * # noqa\nfrom mock import patch\nfrom will.plugins.pyplugins import PythonLoader\n\n\nclass PythonLoader_ImportName(TestCase):\n def test_ShouldReturnModuleNameSutableForImport(self):\n plugin_file = PythonLoader(\"plugin/my_plugin.py\")\n plugin_module = PythonLoader(\"plugin/my_plugin\") # Module dir\n\n expect(plugin_file.import_name()).to(equal(\"my_plugin\"))\n expect(plugin_module.import_name()).to(equal(\"my_plugin\"))\n\n\nclass PythonLoader_IsPlugin(TestCase):\n @patch('os.path.exists')\n @patch('os.path.isfile')\n def test_ShouldReturnTrueIfPluginIsFileAndExists(self, isfile, exists):\n plugin_file = PythonLoader(\"plugin/my_plugin.py\")\n isfile.return_value = True\n exists.return_value = True\n\n expect(plugin_file.is_plugin(fs_tools=os.path)).to(be_true)\n\n @patch('os.path.isfile')\n @patch('os.path.exists')\n @patch('os.path.isdir')\n def test_ShouldReturnTrueifPluginIsDirAndExists(self, isdir, exists,\n isfile):\n isfile.side_effect = [False, True]\n exists.return_value = True\n isdir.return_value = True\n plugin_module = PythonLoader(\"plugin/my_plugin\")\n\n expect(plugin_module.is_plugin(fs_tools=os.path)).to(be_true)\n\n @patch('os.path.exists')\n def test_ShouldReturnFalseIfPluginDoesNotExist(self, exists):\n exists.return_value = False\n plugin_file = PythonLoader(\"plugins/my_plugin.py\")\n\n expect(plugin_file.is_plugin(fs_tools=os.path)).to(be_false)\n\n @patch('os.path.exists')\n @patch('os.path.isfile')\n @patch('os.path.isdir')\n def test_ShouldReturnFalseIfInitFileDoesNotExistInDir(self, isdir, isfile,\n exists):\n exists.side_effect = [True, False]\n isfile.side_effect = [False, True]\n isdir.return_value = True\n plugin_file = PythonLoader(\"plugins/my_plugin\")\n\n expect(plugin_file.is_plugin(fs_tools=os.path)).to(be_false)\n\n @patch('os.path.exists')\n @patch('os.path.isfile')\n @patch('os.path.isdir')\n def test_ShouldReturnFalseIfInitIsNotAFile(self, isdir, isfile, exists):\n exists.return_value = True\n isfile.return_value = False\n isdir.return_value = True\n plugin_file = PythonLoader(\"plugins/my_plugin\")\n\n expect(plugin_file.is_plugin(fs_tools=os.path)).to(be_false)\n","sub_path":"will/plugins/test_pyplugins.py","file_name":"test_pyplugins.py","file_ext":"py","file_size_in_byte":2479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"370984931","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nIceGridImageManager.py\n\nCreated by Scott on 2012-12-24.\nCopyright (c) 2012 Scott Rice. All rights reserved.\n\nThe purpose of this class is to handle the downloading and setting of Steam\nApp Grid images for each shortcut.\n\nFunctionality should be added to this class if it involves Steam App Grid \nimages.\n\"\"\"\n\nimport urllib\nimport urllib2\nimport urlparse\nimport steam_user_manager\nimport steam_grid\nimport settings\nfrom ice_logging import ice_logger\nfrom error.config_error import ConfigError\n\nclass IceGridImageManager():\n @staticmethod\n def should_download_images():\n try:\n should_download = settings.config()[\"Grid Images\"][\"source\"] != \"\"\n return should_download\n except KeyError:\n ice_logger.warning(\"Could not find '[Grid Images] Source' in config.txt.\")\n return False\n\n def __init__(self):\n pass\n \n def provider_with_protocol(self):\n host = settings.config()[\"Grid Images\"][\"source\"]\n if not host.startswith(\"http://\"):\n host = \"http://\" + host\n return host\n \n def host_for_image_source(self):\n return urlparse.urlparse(self.provider_with_protocol()).hostname\n \n def url_for_rom(self,rom):\n host = self.provider_with_protocol()\n quoted_name = urllib.quote(rom.name())\n return \"%s?console=%s&game=%s\" % (host,rom.console.shortname,quoted_name)\n \n def find_image_for_rom(self,rom):\n \"\"\"\n Determines a suitable grid image for a given ROM.\n \"\"\"\n try:\n response = urllib2.urlopen(self.url_for_rom(rom))\n if response.getcode() == 204:\n return None\n else:\n return response.read()\n except urllib2.URLError as error:\n # Connection was refused. The config was incorrect. Let the user\n # know to change it\n raise ConfigError(\"Grid Images\", \"Source\", \"The source of game images is unavailable.\")\n \n def download_image(self,image_url):\n \"\"\"\n Downloads the image at 'image_url' and returns the path to the image on\n the local filesystem\n \"\"\"\n (path,headers) = urllib.urlretrieve(image_url)\n return path\n \n def update_user_images(self,user_id,roms):\n \"\"\"\n Sets a suitable grid image for every rom in 'roms' for the user defined\n by 'user_id'\n \"\"\"\n grid = steam_grid.SteamGrid(steam_user_manager.userdata_directory_for_user_id(user_id))\n for rom in roms:\n shortcut = rom.to_shortcut()\n if not grid.existing_image_for_filename(grid.filename_for_shortcut(shortcut.appname,shortcut.exe)):\n image = self.find_image_for_rom(rom)\n # Game not found\n if image is None:\n ice_logger.log_warning(\"No game found for %s on %s\" % (rom.name(),rom.console.fullname))\n ice_logger.log(\"The image provider has no game called %s for %s. Try going to %s and submittng the game yourself\" % (rom.name(),rom.console.fullname, self.host_for_image_source()))\n # Game found, but there is no picture\n elif image == \"\":\n ice_logger.log_warning(\"No image found for %s. The URL checked was '%s'\" % (rom.name(),self.url_for_rom(rom)))\n ice_logger.log(\"We couldn't find an image for %s. If you find one you like, upload it to %s, and next time Ice runs it will use it\" % (rom.name(),self.host_for_image_source()))\n # Game found, AND there is a picture there\n else:\n ice_logger.log(\"Setting custom image for %s\" % rom.name())\n ice_logger.log('Found grid-image for \"' + rom.name() +'\"')\n image_path = self.download_image(image)\n grid.set_image_for_shortcut(image_path,shortcut.appname,shortcut.exe)\n","sub_path":"ice/grid_image_manager.py","file_name":"grid_image_manager.py","file_ext":"py","file_size_in_byte":3974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"560089284","text":"\n\nimport pandas as pd\nimport os\n#\nfrom ..... import global_var\nfrom . import paths, transcode\n\ndef load(map_code = None):\n \"\"\"\n Loads the aggregated capacities provided by RTE.\n \n :param map_code: The zone\n :type map_code: string\n :return: The aggregated capacities\n :rtype: pd.DataFrame\n \"\"\"\n assert map_code == global_var.geography_map_code_france\n df_path = paths.fpath_tmp.format(map_code = map_code) + '.csv'\n try:\n print('Load capacity/rte - ', end = '')\n df = pd.read_csv(df_path,\n header = [0],\n sep = ';',\n )\n for col in [global_var.capacity_dt_local]:\n df.loc[:,col] = pd.to_datetime(df[col])\n print('Loaded') \n except Exception as e:\n print('fail - has to read raw data')\n print(e)\n dikt_capacity = {}\n list_files = sorted([fname\n for fname in os.listdir(paths.folder_raw)\n if os.path.splitext(fname)[1] == '.xls'\n ])\n for ii, fname in enumerate(list_files):\n print('\\r{0:3}/{1:3} - {2}'.format(ii+1,\n len(list_files),\n fname,\n ),\n end = '',\n )\n df = pd.read_csv(os.path.join(paths.folder_raw,\n fname,\n ), \n sep = '\\t', \n encoding = 'latin-1',\n na_values = [\"*\"],\n skipinitialspace = True,\n low_memory = False,\n )\n df.columns = [global_var.capacity_mw]\n df = df.dropna(axis = 0, how = 'all')\n df[global_var.capacity_year_local] = int(df.loc['Type'].item())\n df[global_var.geography_map_code] = map_code\n df = df.drop('Type',\n axis = 0,\n )\n df.index.name = global_var.production_source\n df.index = df.index.astype(str).replace(transcode.production_source)\n dikt_capacity[fname] = df\n print()\n \n df = pd.concat([dikt_capacity[key]\n for key in dikt_capacity.keys()\n ],\n axis = 0,\n )\n df = df.reset_index()\n df[global_var.geography_map_code] = map_code\n df[global_var.commodity] = global_var.commodity_electricity\n\n # Save\n print('Save')\n os.makedirs(os.path.dirname(df_path),\n exist_ok = True,\n )\n df.to_csv(df_path,\n sep = ';',\n index = False,\n )\n print('done')\n return df\n\n\n \n \n","sub_path":"pub_data_visualization/production_capacity/aggregated/load/rte/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"199071569","text":"#!/usr/bin/python3\r\nfrom helper import *\r\nimport subprocess\r\nimport sys\r\nvmCount = 2\r\nhomebase = home_dir + bad_files\r\n\r\nif len(sys.argv) == 1:\r\n print(\"Please provide executable in path \", homebase)\r\nelse:\r\n exe = sys.argv[1]\r\n#load folder of executables from config\r\nprint(\"transferring folder {} to /home/badstuff\".format(homebase))\r\ncomm = \"./utility/copyToGuest.sh {} {} {}\".format(master_vm,homebase,exe)\r\nsubprocess.run(comm, shell=True, check=True)\r\nprint(\"file list has been transferred to ./utility/fileList.txt\")\r\n\r\n\r\n\r\n","sub_path":"vBoxTest/basic/initialize.py","file_name":"initialize.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"131697591","text":"#!/usr/bin/env python\n\nfrom flask import Flask, request, make_response\nimport json\nimport settings\nimport twitter\n\napp = Flask(__name__)\n\n\n@app.route(\"/search/\")\ndef search():\n query = request.args.get('q')\n\n if not query:\n return json.dumps({\n 'error' : 'This url requires a \"q\" parameter!'\n })\n\n api = init_api()\n statuses = api.GetSearch(term=query)\n result = {\n 'statuses' : [] \n }\n for status in statuses:\n result_status = {\n 'created_at' : status.created_at,\n 'retweet_count' : status.retweet_count,\n 'id' : status.id,\n 'geo' : status.geo,\n 'user' : {\n 'name' : status.user.name,\n 'screen_name' : status.user.screen_name,\n 'url' : status.user.url,\n 'id' : status.user.id,\n 'profile_image_url' : status.user.profile_image_url,\n 'statuses_count' : status.user.statuses_count,\n 'followers_count' : status.user.followers_count,\n 'friends_count' : status.user.friends_count,\n },\n 'text' : status.text,\n }\n \n result['statuses'].append(result_status)\n \n return json.dumps(result)\n\ndef init_api():\n api = twitter.Api(\n consumer_key=settings.API_KEY,\n consumer_secret=settings.API_SECRET,\n access_token_key=settings.ACCESS_TOKEN,\n access_token_secret=settings.ACCESS_TOKEN_SECRET\n )\n return api\n\n@app.route(\"/\")\ndef main():\n return search()\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run(\"0.0.0.0\")\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"426245168","text":"from pyecharts import Geo\n# data = [(u'广州',80),(u'漳州',180)]\n#\n# geo = Geo('全国主要城市空气治理','data from pm2.5') # 主标题, 副标题\n#\n# attr,value = geo.cast(data)\n# print(attr,value)\n# geo.add('city',attr,value,visual_range=[0,200],maptype='china',visual_text_color='#fff',symbol_size=10,is_visualmap=True)\n# geo.render()\nfrom pyecharts import Geo\n\ndata = [(\"海门\", 9), (\"鄂尔多斯\", 12), (\"招远\", 12), (\"舟山\", 12), (\"齐齐哈尔\", 14), (\"盐城\", 15)]\ngeo = Geo(\"全国主要城市空气质量\", \"data from pm2.5\", title_color=\"#fff\", title_pos=\"center\", width=1200, height=600, background_color='#404a59')\nattr, value = geo.cast(data)\ngeo.add(\"\", attr, value, type=\"effectScatter\", is_random=True, effect_scale=5)\ngeo.show_config()\ngeo.render()\n\n\n","sub_path":"WorksZhang/GT_0720/pyecharts练习/地图可视化.py","file_name":"地图可视化.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"462408431","text":"from opengever.base.monkey.patching import MonkeyPatch\n\n\nclass PatchCopyContainerVerifyObjectPaste(MonkeyPatch):\n \"\"\"Patch `OFS.CopySupport.CopyContainer._verifyObjectPaste`\n to disable `Delete objects` permission check when moving items.\n \"\"\"\n\n def __call__(self):\n from AccessControl import getSecurityManager\n from AccessControl import Unauthorized\n from Acquisition import aq_inner\n from Acquisition import aq_parent\n from App.Dialogs import MessageDialog\n from cgi import escape\n from OFS.CopySupport import absattr\n from OFS.CopySupport import CopyError\n from opengever.api.not_reported_exceptions import CopyError as NotReportedCopyError\n from opengever.document.behaviors import IBaseDocument\n from ZODB.POSException import ConflictError\n from opengever.base import _\n\n def _verifyObjectPaste(self, object, validate_src=1):\n # Verify whether the current user is allowed to paste the\n # passed object into self. This is determined by checking\n # to see if the user could create a new object of the same\n # meta_type of the object passed in and checking that the\n # user actually is allowed to access the passed in object\n # in its existing context.\n #\n # Passing a false value for the validate_src argument will skip\n # checking the passed in object in its existing context. This is\n # mainly useful for situations where the passed in object has no\n # existing context, such as checking an object during an import\n # (the object will not yet have been connected to the acquisition\n # heirarchy).\n #\n # We also make sure that we are not pasting a checked-out document\n\n if IBaseDocument.providedBy(object) and object.is_checked_out():\n raise NotReportedCopyError(\n _(u'error_checked_out_cannot_be_copied',\n default=u\"Checked out documents cannot be copied.\"))\n\n if not hasattr(object, 'meta_type'):\n raise CopyError(MessageDialog(\n title = 'Not Supported',\n message = ('The object %s does not support this' \\\n ' operation' % escape(absattr(object.id))),\n action = 'manage_main'))\n\n if not hasattr(self, 'all_meta_types'):\n raise CopyError(MessageDialog(\n title = 'Not Supported',\n message = 'Cannot paste into this object.',\n action = 'manage_main'))\n\n mt_permission = None\n meta_types = absattr(self.all_meta_types)\n\n for d in meta_types:\n if d['name'] == object.meta_type:\n mt_permission = d.get('permission')\n break\n\n if mt_permission is not None:\n sm = getSecurityManager()\n\n if sm.checkPermission(mt_permission, self):\n if validate_src:\n # Ensure the user is allowed to access the object on the\n # clipboard.\n try:\n parent = aq_parent(aq_inner(object))\n except ConflictError:\n raise\n except Exception:\n parent = None\n\n if not sm.validate(None, parent, None, object):\n raise Unauthorized(absattr(object.id))\n\n # --- Patch ---\n # Disable checking for `Delete objects` permission\n\n # if validate_src == 2: # moving\n # if not sm.checkPermission(delete_objects, parent):\n # raise Unauthorized('Delete not allowed.')\n\n # --- End Patch ---\n else:\n raise CopyError(MessageDialog(\n title = 'Insufficient Privileges',\n message = ('You do not possess the %s permission in the '\n 'context of the container into which you are '\n 'pasting, thus you are not able to perform '\n 'this operation.' % mt_permission),\n action = 'manage_main'))\n else:\n raise CopyError(MessageDialog(\n title = 'Not Supported',\n message = ('The object %s does not support this '\n 'operation.' % escape(absattr(object.id))),\n action = 'manage_main'))\n\n from OFS.CopySupport import CopyContainer\n self.patch_refs(CopyContainer, '_verifyObjectPaste', _verifyObjectPaste)\n","sub_path":"opengever/base/monkey/patches/verify_object_paste.py","file_name":"verify_object_paste.py","file_ext":"py","file_size_in_byte":4982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"603750658","text":"import pygame, math, random\n\nimg = \"game_images/vermin.png\"\nimg_blue = \"game_images/vermin.png\"\nimg_pink = \"game_images/vermin.png\"\n\nclass Vermin(pygame.sprite.Sprite):\n def __init__(self, color):\n pygame.sprite.Sprite.__init__(self)\n image_orig = pygame.image.load(img).convert_alpha()\n self.image = image_orig\n self.rect = self.image.get_rect()\n self.size = image_orig.get_size()\n self.phrase = \"\"\n self.width = int(self.image.get_width())\n self.height = int(self.image.get_height())\n\n if(color == 1):\n image_orig = pygame.image.load(img).convert_alpha()\n self.image = image_orig\n self.rect = self.image.get_rect()\n\n if(color ==2):\n image_orig = pygame.image.load(img_blue).convert_alpha()\n self.image = image_orig\n self.rect = self.image.get_rect()\n\n if(color ==3):\n image_orig = pygame.image.load(img_pink).convert_alpha()\n self.image = image_orig\n self.rect = self.image.get_rect()\n \n","sub_path":"ghostboi_game/vermin.py","file_name":"vermin.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"200075213","text":"import pygame\nimport constants\nimport Animation\nfrom Utils import SpriteSheet\n\nclass Player(pygame.sprite.Sprite):\n \"\"\" This class represents the bar at the bottom that the player\n controls. \"\"\"\n\n change_x = 0\n change_y = 0\n\n walking_frames_l = []\n walking_frames_r = []\n walking_frames_m_1 = []\n\n direction = \"R\"\n\n level = None\n\n # -- Methods\n def __init__(self, x, y):\n \"\"\" Constructor function \"\"\"\n self.character_level = 0\n self.maxlevel = 13\n self.lifes = 3\n self.level_no = 0\n # Call the parent's constructor\n pygame.sprite.Sprite.__init__(self)\n\n self.sprite_sheet = SpriteSheet(\"Game-Files/Images/texturepack.png\")\n\n #Magic Level 1\n image = self.sprite_sheet.getImage(0, 256, 32, 32)\n self.walking_frames_m_1.append(image)\n image = self.sprite_sheet.getImage(32, 256, 32, 32)\n self.walking_frames_m_1.append(image)\n\n self.image = self.walking_frames_m_1[0]\n\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n\n self.direction = \"R\"\n self.anim = Animation.Animation(10)\n self.animmyst = Animation.Animation(5)\n self.time = 0\n self.current = 0\n\n self.jump_sound = pygame.mixer.Sound(\"Game-Files/Sounds/Jump.wav\")\n self.jump_sound.set_volume(constants.effect_volume)\n self.magic_sound = pygame.mixer.Sound(\"Game-Files/Sounds/Magic.wav\")\n self.magic_sound.set_volume(constants.effect_volume)\n\n def level_up(self):\n self.character_level += 1\n self.level_update()\n\n def level_update(self):\n self.walking_frames_r = []\n self.walking_frames_l = []\n image = self.sprite_sheet.getImage(((self.character_level - 1) * 32), 0, 32, 32)\n self.walking_frames_r.append(image)\n image = self.sprite_sheet.getImage(((self.character_level - 1) * 32), 0, 32, 32)\n image = pygame.transform.flip(image, True, False)\n self.walking_frames_l.append(image)\n\n def level_reset(self):\n self.character_level = 1\n self.walking_frames_r = []\n self.walking_frames_l = []\n image = self.sprite_sheet.getImage(((self.character_level - 1) * 32), 0, 32, 32)\n self.walking_frames_r.append(image)\n image = self.sprite_sheet.getImage(((self.character_level - 1) * 32), 0, 32, 32)\n image = pygame.transform.flip(image, True, False)\n self.walking_frames_l.append(image)\n\n def update(self):\n \"\"\" Move the player. \"\"\"\n # Gravity\n self.calc_grav()\n\n # Move left/right\n self.rect.x += self.change_x\n if self.direction == \"R\":\n self.image = self.anim.update(self.walking_frames_r)\n elif self.direction == \"M\":\n self.image = self.animmyst.update(self.walking_frames_m_1)\n else:\n self.image = self.anim.update(self.walking_frames_l)\n # See if we hit anything\n block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)\n for block in block_hit_list:\n # If we are moving right,\n # set our right side to the left side of the item we hit\n if self.change_x > 0:\n self.rect.right = block.rect.left\n elif self.change_x < 0:\n # Otherwise if we are moving left, do the opposite.\n self.rect.left = block.rect.right\n\n # Move up/down\n self.rect.y += self.change_y\n\n # Check and see if we hit anything\n block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)\n for block in block_hit_list:\n\n # Reset our position based on the top/bottom of the object.\n if self.change_y > 0:\n self.rect.bottom = block.rect.top\n elif self.change_y < 0:\n self.rect.top = block.rect.bottom\n\n # Stop our vertical movement\n self.change_y = 0\n\n def calc_grav(self):\n \"\"\" Calculate effect of gravity. \"\"\"\n if self.change_y == 0:\n self.change_y = 1\n else:\n self.change_y += .35\n\n # See if we are on the ground.\n if self.rect.y >= constants.SCREEN_HEIGHT - self.rect.height and self.change_y >= 0:\n self.change_y = 0\n self.rect.y = constants.SCREEN_HEIGHT - self.rect.height\n\n def jump(self):\n \"\"\" Called when user hits 'jump' button. \"\"\"\n\n # move down a bit and see if there is a platform below us.\n # Move down 2 pixels because it doesn't work well if we only move down\n # 1 when working with a platform moving down.\n self.jump_sound.set_volume(constants.effect_volume)\n self.jump_sound.play()\n self.rect.y += 2\n platform_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)\n self.rect.y -= 2\n\n # If it is ok to jump, set our speed upwards\n if len(platform_hit_list) > 0 or self.rect.bottom >= constants.SCREEN_HEIGHT:\n self.change_y = -10\n\n # Player-controlled movement:\n def go_left(self):\n \"\"\" Called when the user hits the left arrow. \"\"\"\n self.change_x = -6\n self.direction = \"L\"\n\n def go_right(self):\n \"\"\" Called when the user hits the right arrow. \"\"\"\n self.change_x = 6\n self.direction = \"R\"\n\n def stop(self):\n \"\"\" Called when the user lets off the keyboard. \"\"\"\n self.change_x = 0\n","sub_path":"Testing_Multi/Inztanz2/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":5514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"317490779","text":"import math\r\nimport numpy as np\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import gridspec\r\n\r\nxmax = 10000 # number of grid points in x-direction\r\nnx = 10000 # physical domain (m)\r\ndx = xmax/nx # grid point distance in x-direction\r\nc0 = 334 # wave speed in medium (m/s)\r\nisrc = int(nx/2) # source location in grid in x-direction\r\n#ir = isrc + 100\r\nnt = 1001 # maximum number of time steps\r\ndt = 0.001 # time step\r\n\r\n\r\nf0 = 25\r\nt0 = 4/f0\r\n\r\nidisp = 5\r\n\r\n#Plot for Source Time function\r\n\r\n#Source time function\r\n\r\nsrc = np.zeros(nt+1)\r\ntime = np.linspace(0,nt*dt,nt)\r\n\r\nsrc = -8 * (time-t0)*f0*(np.exp(-1*(4*f0)**2*(time-t0)**2))\r\n\r\nplt.ion()\r\nfig1 = plt.figure(figsize=(10,6))\r\ngs1 = gridspec.GridSpec(1,2,width_ratios=[1,1],hspace=0.3,wspace=0.3)\r\n\r\nax1 = plt.subplot(gs1[0])\r\nax1.plot(time,src)\r\nax1.set_title('Source Time Function')\r\nax1.set_xlim(time[0],time[-1])\r\nax1.set_xlabel('Time (s)')\r\nax1.set_ylabel('Amplitude')\r\n\r\nax2 = plt.subplot(gs1[1])\r\nspec = np.fft.fft(src) # source time function in frequency domain\r\nfreq = np.fft.fftfreq(spec.size, d = dt ) # time domain to frequency domain\r\nax2.plot(np.abs(freq), np.abs(spec)) # plot frequency and amplitude\r\nax2.set_xlim(0, 250) # only display frequency from 0 to 250 Hz\r\nax2.set_title('Source Spectrum')\r\nax2.set_xlabel('Frequency (Hz)')\r\nax2.set_ylabel('Amplitude')\r\n\r\nax2.yaxis.tick_right()\r\nax2.yaxis.set_label_position(\"right\")\r\n\r\nplt.show()\r\n\r\n\r\n#Plot Snapshot & Seismogram\r\n\r\np = np.zeros(nx)\r\npold = np.zeros(nx)\r\npnew = np.zeros(nx)\r\nd2px = np.zeros(nx)\r\n\r\nc = np.zeros(nx)\r\nc = c+c0\r\n\r\nx = np.arange(nx)\r\nx = x*dx\r\n\r\nplt.ion()\r\nfig2 = plt.figure(figsize=(10,6))\r\ngs2 = gridspec.GridSpec(1,1,width_ratios=[1],hspace=0.3,wspace=0.3)\r\n\r\nax3 = plt.subplot(gs2[0])\r\nleg1,= ax3.plot(isrc,0,'r*',markersize = 11)\r\nup31,= ax3.plot(p)\r\nax3.set_xlim(0,xmax)\r\nax3.set_ylim(-np.max(p),np.max(p))\r\nax3.set_title('Time Step (nt) = 0')\r\nax3.set_xlabel('x (m)')\r\nax3.set_ylabel('Pressure Amplitude')\r\n\r\nplt.show()\r\n\r\n#1-D Wave propagation (FD)\r\n\r\nfor it in range(nt):\r\n for i in range(1,nx-1):\r\n d2px[i] = (p[i+1]-2*p[i]+p[i-1])/dx**2\r\n\r\n pnew = 2*p - pold + c**2*dt**2*d2px\r\n\r\n pnew[isrc] = pnew[isrc] + src[it]/(dx)*dt**2\r\n\r\n pold,p = p,pnew\r\n\r\n if(it%idisp)==0:\r\n ax3.set_title('Time Step (nt) = %d'%it)\r\n ax3.set_ylim(-1.1*np.max(abs(p)),1.1*np.max(abs(p)))\r\n window = 100;xshift = 25\r\n ax3.set_xlim(isrc*dx+c0*it*dt-window*dx-xshift,isrc*dx+c0*it*dt+window*dx-xshift)\r\n up31.set_ydata(p)\r\n plt.gcf().canvas.draw()\r\n \r\n\r\n","sub_path":"W3_P1.py","file_name":"W3_P1.py","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"280336370","text":"from datalake_library.commons import init_logger\nfrom datalake_library.transforms.transform_handler import TransformHandler\nfrom datalake_library import octagon\nfrom datalake_library.octagon import Artifact, EventReasonEnum, peh\n\nlogger = init_logger(__name__)\n\n\ndef lambda_handler(event, context):\n \"\"\"Calls custom job waiter developed by user\n\n Arguments:\n event {dict} -- Dictionary with details on previous processing step\n context {dict} -- Dictionary with details on Lambda context\n\n Returns:\n {dict} -- Dictionary with Processed Bucket, Key(s) and Job Details\n \"\"\"\n try:\n logger.info('Fetching event data from previous step')\n bucket = event['body']['bucket']\n team = event['body']['team']\n stage = event['body']['pipeline_stage']\n dataset = event['body']['dataset']\n job_details = event['body']['job']['jobDetails']\n processed_keys_path = event['body']['job']['processedKeysPath']\n peh_id = event['body']['peh_id']\n\n logger.info('Initializing Octagon client')\n component = context.function_name.split('-')[-2].title()\n octagon_client = (\n octagon.OctagonClient()\n .with_run_lambda(True)\n .with_configuration_instance(event['body']['env'])\n .build()\n )\n\n logger.info('Checking Job Status with user custom code')\n transform_handler = TransformHandler().stage_transform(team, dataset, stage)\n response = transform_handler().check_job_status(bucket, None,\n processed_keys_path, job_details) # custom user code called\n\n if event['body']['job']['jobDetails']['jobStatus'] == 'FAILED':\n peh.PipelineExecutionHistoryAPI(\n octagon_client).retrieve_pipeline_execution(peh_id)\n octagon_client.end_pipeline_execution_failed(component=component,\n issue_comment=\"{} {} Error: Check Job Logs\".format(stage, component))\n except Exception as e:\n logger.error(\"Fatal error\", exc_info=True)\n peh.PipelineExecutionHistoryAPI(\n octagon_client).retrieve_pipeline_execution(peh_id)\n octagon_client.end_pipeline_execution_failed(component=component,\n issue_comment=\"{} {} Error: {}\".format(stage, component, repr(e)))\n raise e\n return response\n","sub_path":"sdlf-utils/pipeline-examples/dataset-dependency/stageA/lambda/stage-a-check-job/src/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"361687883","text":"import sqlite3\nimport numpy as np\nimport random\nimport scipy.io\n\n\n\ndef import_trajectories(filename,masks = 0):\n mat = scipy.io.loadmat(filename)\n trajectories = mat[\"tracks_train\"]\n trajectories = [ trajectory[0].tolist() for trajectory in trajectories]\n trajectories = [[[x,y] for x,y in zip(trajectory[0],trajectory[1])] for trajectory in trajectories]\n \n\n \n\n labels = mat[\"labels_train\"]\n labels = labels[0].tolist()\n\n if masks:\n filt = mat[\"ind_tracks_filt_l\"].reshape(-1).tolist()\n\n clust = mat[\"ind_tracks_clust_l\"].reshape(-1).tolist()\n\n return trajectories, labels, filt, clust\n\n\n return trajectories, labels\n\n\n\n\n\n\n\n\ndef get_trajectories_by_object(filename, nb_objects = -1,gather_x_y = True):\n #init database\n database = sqlite3.connect(filename)\n cursor = database.cursor()\n\n db_nb_objects = \"select count(object_id) from objects\"\n n = int(cursor.execute(db_nb_objects).fetchall()[0][0])\n\n rand_n = True\n #get number of objects\n if nb_objects == -1:\n db_nb_objects = \"select count(object_id) from objects\"\n nb_objects = n\n rand_n = False\n # get trajectories\n \n trajectories_by_object = [[] for i in range(nb_objects)]\n ids = [[] for i in range(nb_objects)]\n for i in range(nb_objects):\n\n nbo = i\n if rand_n:\n nbo = random.randint(0,n)\n db_trajectories_by_object = \" with object_trajectories \\\n as (select p.trajectory_id as id,\\\n p.x_coordinate as x,\\\n p.y_coordinate as y,\\\n p.frame_number as t\\\n from positions as p\\\n inner join objects_features as o on p.trajectory_id = o.trajectory_id\\\n where o.object_id =\" +str(nbo)+\")\\\n select id, group_concat(x,','),group_concat(y,',')\\\n from object_trajectories\\\n group by id\\\n order by t\"\n\n trajectories_by_o = cursor.execute(db_trajectories_by_object).fetchall()\n\n idx = [int(e[0]) for e in trajectories_by_o ]\n xs = [[float(c) for c in e[1].split(',')] for e in trajectories_by_o ]\n ys = [[float(c) for c in e[2].split(',')] for e in trajectories_by_o ]\n\n trajectories = []\n if gather_x_y:\n trajectories =[ [[a,b] for a,b in zip(x,y)] for x,y in zip(xs,ys)]\n else:\n trajectories =[ [x,y] for x,y in zip(xs,ys)]\n \n trajectories_by_object[i] = trajectories\n ids[i] = idx\n return trajectories_by_object,ids,nb_objects\n\n\ndef filter_trajectories(nb_longest, t_o,id_o):\n lengths = [np.array([len(t) for t in o]) for o in t_o]\n ids = [o.argsort()[-nb_longest:][::-1] for o in lengths]\n \n t_o = [[t_o[k][i] for i in ids[k]] for k in range(len(ids))]\n\n id_o = [[id_o[k][i] for i in ids[k]] for k in range(len(ids))]\n return t_o,id_o\n \n\ndef get_trajectories(filename):\n \n database = sqlite3.connect(filename)\n cursor = database.cursor()\n\n db_request1 = \"SELECT max(trajectory_id), min(trajectory_id) FROM positions\"\n max_min = cursor.execute(db_request1).fetchall()\n nb_trajectory = max_min[0][0]- max_min[0][1] +1\n\n trajectories = [cursor.execute(\n \"SELECT p.x_coordinate,p.y_coordinate \\\n FROM positions as p \\\n WHERE trajectory_id =\"+str(i)+\" ORDER BY p.frame_number ASC\"\n ).fetchall() for i in range(nb_trajectory)]\n\n \n database.close()\n return trajectories","sub_path":"libs/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":3454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"375867709","text":"## Assignment 1 Solutions\r\n# 5-Write a program to enter the number and \r\n# print \"Yes I am in the range\" if it is in the\r\n# range of 10-50 if not and then print \"Oops\".\r\n\r\nx = input(\"Enter a number : \")\r\n\r\n# flag used to track conversion exception\r\nflag = False\r\n\r\ntry:\r\n\tx = int(x)\r\nexcept:\r\n\tflag = True\r\n\r\n# Assuming 10 and 50 are part of the range\r\nif not flag and x >= 10 and x <= 50:\r\n\tprint(\"Yes I am in the range\")\r\nelse:\r\n\tprint(\"Oops\")","sub_path":"July_19/Assignment 1/Solution_5.py","file_name":"Solution_5.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"199540489","text":"# Experimental code for computing functions of the joint SFS along a sequence\n# and related things\n\nimport msprime\nimport numpy as np\n\ndef get_derived_state(site, mut_id):\n \"\"\"\n Find the derived state of the mutation with id `mut_id` at site `site`.\n \"\"\"\n if mut_id == -1:\n state = site.ancestral_state\n else:\n for m in site.mutations:\n if m.id == mut_id:\n state = m.derived_state\n return state\n\ndef tracked_samples_joint_branch_sfs(tree_sequence, pop0, pop1, begin=0.0, end=None):\n if end is None:\n end = tree_sequence.sequence_length\n n0 = len(pop0)\n n1 = len(pop1)\n S = np.zeros((n0 + 1, n1 + 1))\n tt0 = tree_sequence.trees(tracked_samples=pop0,\n sample_counts=True)\n tt1 = tree_sequence.trees(tracked_samples=pop1,\n sample_counts=True)\n for t0, t1 in zip(tt0, tt1):\n root = t0.root\n tr_len = min(end, t0.interval[1]) - max(begin, t0.interval[0])\n if tr_len > 0:\n for node in t0.nodes():\n if node != root:\n x0 = t0.num_tracked_samples(node)\n x1 = t1.num_tracked_samples(node)\n if (x0 > 0) or (x1 > 0):\n S[x0, x1] += t0.branch_length(node) * tr_len\n S /= (end-begin)\n return S\n\n\ndef variants_joint_sfs(tree_sequence, pop0, pop1, begin=0.0, end=None):\n '''\n '''\n if end is None:\n end = tree_sequence.sequence_length\n n0 = len(pop0)\n n1 = len(pop1)\n S = np.zeros((n0 + 1, n1 + 1))\n for v in tree_sequence.variants():\n if v.position >= end:\n break\n if v.position >= begin:\n for a in set(v.genotypes):\n x0 = sum(v.genotypes[pop0] == a)\n x1 = sum(v.genotypes[pop1] == a)\n if (x0 > 0) or (x1 > 0):\n S[x0, x1] += 1.0\n S /= (end - begin)\n return S\n\n\ndef joint_site_frequency_spectrum(tree_sequence, pop0, pop1, windows=None):\n '''\n Computes the joint folded site frequency spectrum between pop0 and pop1,\n independently in windows.\n\n :param list pop0: A list of IDs of samples of length n0.\n :param list pop1: A list of IDs of samples of length n1.\n :param iterable windows: The breakpoints of the windows (including start\n and end, so has one more entry than number of windows).\n :return: A list of matrices of dimension n0 x n1, one for each window,\n whose kth entry gives the number of mutations in that window at which a\n mutation is seen by exactly k of the samples, divided by the window length.\n '''\n if windows is None:\n windows = (0, tree_sequence.sequence_length)\n if ((not isinstance(pop0, list)) or\n (not isinstance(pop1, list)) or\n (len(pop0) + len(pop1) != len(set(pop0+pop1)))):\n raise ValueError(\n \"pop0 and pop1 must not contain repeated elements.\")\n if (len(pop0) == 0) or (len(pop1) == 0):\n raise ValueError(\"sample_set cannot be empty.\")\n for u in pop0 + pop1:\n if not tree_sequence.node(u).is_sample():\n raise ValueError(\"Not all elements of pop0 and pop1 are samples.\")\n num_windows = len(windows) - 1\n if windows[0] != 0.0:\n raise ValueError(\n \"Windows must start at the start of the sequence (at 0.0).\")\n if windows[-1] != tree_sequence.sequence_length:\n raise ValueError(\"Windows must extend to the end of the sequence.\")\n for k in range(num_windows):\n if windows[k + 1] <= windows[k]:\n raise ValueError(\"Windows must be increasing.\")\n num_sites = tree_sequence.num_sites\n n0 = len(pop0)\n n1 = len(pop1)\n # we store the final answers here\n S = np.zeros((num_windows, n0 + 1, n1 + 1))\n if num_sites == 0:\n return S\n N = tree_sequence.num_nodes\n # initialize: with no tree, each node is either in a sample set or not\n X0 = [int(u in pop0) for u in range(N)]\n X1 = [int(u in pop1) for u in range(N)]\n # we will construct the tree here\n pi = [-1 for j in range(N)]\n # keep track of which site we're looking at\n sites = tree_sequence.sites()\n ns = 0 # this will record number of sites seen so far\n s = next(sites)\n # index of *left-hand* end of the current window\n window_num = 0\n while s.position > windows[window_num + 1]:\n window_num += 1\n for interval, records_out, records_in in tree_sequence.edge_diffs():\n # if we've done all the sites then stop\n if ns == num_sites:\n break\n # update the tree\n for sign, records in ((-1, records_out), (+1, records_in)):\n for edge in records:\n dx1 = 0\n dx2 = 0\n if sign == +1:\n pi[edge.child] = edge.parent\n dx1+= sign * X0[edge.child]\n dx2+= sign * X1[edge.child]\n if sign == -1:\n pi[edge.child] = -1\n X0[edge.parent] += dx1\n X1[edge.parent] += dx2\n # propagate change up the tree\n u = pi[edge.parent]\n if u != -1:\n next_u = pi[u]\n while u != -1:\n X0[u] += dx1\n X1[u] += dx2\n u = next_u\n next_u = pi[next_u]\n # loop over sites in this tree\n while s.position < interval[1]:\n if s.position > windows[window_num + 1]:\n # finalize this window and move to the next\n window_length = windows[window_num + 1] - windows[window_num]\n S[window_num] /= window_length\n # may need to advance through empty windows\n while s.position > windows[window_num + 1]:\n window_num += 1\n nm = len(s.mutations)\n if nm > 0:\n U = {s.ancestral_state: [n0, n1]}\n for mut in s.mutations:\n if mut.derived_state not in U:\n U[mut.derived_state] = [0, 0]\n U[mut.derived_state][0] += X0[mut.node]\n U[mut.derived_state][1] += X1[mut.node]\n parent_state = get_derived_state(s, mut.parent)\n if parent_state not in U:\n U[parent_state] = [0, 0]\n U[parent_state][0] -= X0[mut.node]\n U[parent_state][1] -= X1[mut.node]\n for a in U:\n if max(U[a]) > 0:\n S[window_num][U[a][0], U[a][1]] += 1.0\n ns += 1\n if ns == num_sites:\n break\n s = next(sites)\n # wrap up the final window\n window_length = windows[window_num + 1] - windows[window_num]\n S[window_num] /= window_length\n return S\n\ndef joint_branch_frequency_spectrum(tree_sequence, pop0, pop1, windows=None):\n '''\n Computes the expected *derived* (unfolded) joint site frequency spectrum,\n between pop0 and pop1, based on tree lengths, separately in each window.\n\n :param list pop0: A list of IDs of samples of length n0.\n :param list pop1: A list of IDs of samples of length n1.\n :param iterable windows: The breakpoints of the windows (including start\n and end, so has one more entry than number of windows).\n :return: A list of lists of length n, one for each window, whose kth\n entry gives the total length of any branches in the marginal trees\n over that window that are ancestral to exactly k of the samples,\n divided by the length of the window.\n '''\n if windows is None:\n windows = (0, tree_sequence.sequence_length)\n if ((not isinstance(pop0, list)) or\n (not isinstance(pop1, list)) or\n (len(pop0) + len(pop1) != len(set(pop0+pop1)))):\n raise ValueError(\n \"pop0 and pop1 must not contain repeated elements.\")\n if (len(pop0) == 0) or (len(pop1) == 0):\n raise ValueError(\"sample_set cannot be empty.\")\n for u in pop0 + pop1:\n if not tree_sequence.node(u).is_sample():\n raise ValueError(\"Not all elements of pop0 and pop1 are samples.\")\n num_windows = len(windows) - 1\n if windows[0] != 0.0:\n raise ValueError(\n \"Windows must start at the start of the sequence (at 0.0).\")\n if windows[-1] != tree_sequence.sequence_length:\n raise ValueError(\"Windows must extend to the end of the sequence.\")\n for k in range(num_windows):\n if windows[k + 1] <= windows[k]:\n raise ValueError(\"Windows must be increasing.\")\n n0 = len(pop0)\n n1 = len(pop1)\n S = np.zeros((num_windows, n0 + 1, n1 + 1))\n L = np.zeros((n0 + 1, n1 + 1))\n N = tree_sequence.num_nodes\n X0 = [int(u in pop0) for u in range(N)]\n X1 = [int(u in pop1) for u in range(N)]\n # we will essentially construct the tree\n pi = [-1 for j in range(N)]\n node_time = [tree_sequence.node(u).time for u in range(N)]\n # keep track of where we are for the windows\n chrom_pos = 0.0\n # index of *left-hand* end of the current window\n window_num = 0\n for interval, records_out, records_in in tree_sequence.edge_diffs():\n length = interval[1] - interval[0]\n for sign, records in ((-1, records_out), (+1, records_in)):\n for edge in records:\n dx0 = 0\n dx1 = 0\n if sign == +1:\n pi[edge.child] = edge.parent\n dx0 += sign * X0[edge.child]\n dx1 += sign * X1[edge.child]\n dt = (node_time[pi[edge.child]] - node_time[edge.child])\n if (X0[edge.child] > 0) or (X1[edge.child] > 0):\n L[X0[edge.child], X1[edge.child]] += sign * dt\n if sign == -1:\n pi[edge.child] = -1\n old_X0 = X0[edge.parent]\n old_X1 = X1[edge.parent]\n X0[edge.parent] += dx0\n X1[edge.parent] += dx1\n if pi[edge.parent] != -1:\n dt = (node_time[pi[edge.parent]] - node_time[edge.parent])\n if (X0[edge.parent] > 0) or (X1[edge.parent] > 0):\n L[X0[edge.parent], X1[edge.parent]] += dt\n if (old_X0 > 0) or (old_X1 > 0):\n L[old_X0, old_X1] -= dt\n # propagate change up the tree\n u = pi[edge.parent]\n if u != -1:\n next_u = pi[u]\n while u != -1:\n old_X0 = X0[u]\n old_X1 = X1[u]\n X0[u] += dx0\n X1[u] += dx1\n # need to update X for the root,\n # but the root does not have a branch length\n if next_u != -1:\n dt = (node_time[pi[u]] - node_time[u])\n if (X0[u] > 0) or (X1[u] > 0):\n L[X0[u], X1[u]] += dt\n if (old_X0 > 0) or (old_X1 > 0):\n L[old_X0, old_X1] -= dt\n u = next_u\n next_u = pi[next_u]\n while chrom_pos + length >= windows[window_num + 1]:\n # wrap up the last window\n this_length = windows[window_num + 1] - chrom_pos\n window_length = windows[window_num + 1] - windows[window_num]\n S[window_num] += L * this_length\n S[window_num] /= window_length\n length -= this_length\n # start the next\n if window_num < num_windows - 1:\n window_num += 1\n chrom_pos = windows[window_num]\n else:\n # skips the else statement below\n break\n else:\n S[window_num] += L * length\n chrom_pos += length\n return S\n\n","sub_path":"treestats/sfs.py","file_name":"sfs.py","file_ext":"py","file_size_in_byte":12008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"542027059","text":"from hmm import Hmm\n\nmodel = Hmm(char2idx_path=\"dicts/otherchar2idx.json\", tag2idx_path=\"dicts/othertag2idx.json\")\nmodel.fit(\"corpus/hmm_疫情其他数据集_20000.txt\")\n\nf = open(\"corpus/疫情分句后的数据.txt\", encoding='utf-8')\nents = []\nwith open(\"hmm其他抽取结果.txt\", \"a\", encoding=\"utf-8\") as w:\n for line in f:\n line = line.strip()\n if len(line) <= 1:\n continue\n tmp = model.yq_usage(line)\n for t in tmp:\n if t in ents:\n continue\n ents.append(t)\n w.write(t + '\\n')\n print(t)\n\nf.close()\n\n\n\n\n","sub_path":"yq_use.py","file_name":"yq_use.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"569588081","text":"from zipfile import ZipFile\nfrom urllib.request import urlopen\nfrom io import BytesIO\nfrom bs4 import BeautifulSoup\n\nwordFile = urlopen(\"http://pythonscraping.com/pages/AWordDocument.docx\").read()\nwordFile = BytesIO(wordFile)\ndocument = ZipFile(wordFile)\nxml_content = document.read('word/document.xml')\n#print(xml_content) #bytes\n#print(xml_content.decode('utf-8'))\n#print(type(xml_content.decode('utf-8'))) #str\n\nsoup = BeautifulSoup(xml_content.decode('utf-8'),'html.parser')\ntextStrings = soup.findAll('w:t')\nprint(soup)\nprint(textStrings)\nfor testItem in textStrings:\n closeTag = ''\n try:\n style = testItem.parent.previousSibling.find('w:pstyle')\n if style is not None and style['w:val'] == 'Title':\n print('

')\n closeTag = '

'\n except AttributeError:\n pass\n print(testItem.text)\n print(closeTag)","sub_path":"chapter6-07.py","file_name":"chapter6-07.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"549741428","text":"#!/usr/bin/env python3\n\nimport requests\nimport os\nimport subprocess\nfrom bs4 import BeautifulSoup\nimport sys\n\ndef get(url):\n\t# Spam detection seems to block non-real browsers quickly\n\theaders = {\"user-agent\": \"Mozilla/5.0 (X11; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0\"}\n\treturn requests.get(url, headers=headers)\n\ndef detect_component(languages, module):\n\tfor lang in languages:\n\t\t# Extract all directories (components)\n\t\tsoup = BeautifulSoup(get(\"https://websvn.kde.org/trunk/l10n-kf5/{}/messages/\".format(lang)).text, features=\"lxml\")\n\t\tfor item in soup.findAll(\"a\", {\"title\": \"View directory contents\"}):\n\t\t\t# Soup extracted urls\n\t\t\tcomponentSoup = BeautifulSoup(get(\"https://websvn.kde.org/\" + item[\"href\"]).text, features=\"lxml\")\n\n\t\t\t# check whether the wanted module exists in the component\n\t\t\tfor a in componentSoup.findAll(\"a\", {\"title\": \"View file revision log\"}):\n\t\t\t\tif module in a[\"name\"]:\n\t\t\t\t\tprint(\"Got component\", item[\"name\"], \"in\", lang)\n\t\t\t\t\treturn item[\"name\"]\n\ndef detect_files(component, module):\n\tlang = \"es\" # Files seem to be the same in all languages, only check one language\n\tfiles = []\n\n\tsoup = BeautifulSoup(get(\"https://websvn.kde.org/trunk/l10n-kf5/{}/messages/{}\".format(lang, component)).text, features=\"lxml\")\n\n\tfor a in soup.findAll(\"a\", {\"title\": \"View file revision log\"}):\n\t\tif module in a[\"name\"]:\n\t\t\tfiles.append(a[\"name\"])\n\n\tprint(\"Got files\", set(files))\n\treturn set(files)\n\ndef add_i18n_to_cmake(podir):\n\tfile = open(\"CMakeLists.txt\", \"a\")\n\tfile.write(\n\t\t\"\\n\".join(\n\t\t\t[\n\t\t\t\"find_package(KF5I18n CONFIG REQUIRED)\",\n\t\t\t\"ki18n_install({})\".format(podir)\n\t\t\t]\n\t\t)\n\t)\n\ndef mkdir_if_neccesary(path):\n\tif not os.path.isdir(path):\n\t\tos.mkdir(path)\n\ndef main():\n\tprint(\"Fetching list of available languages ...\")\n\trequest = get(\"https://websvn.kde.org/*checkout*/trunk/l10n-kf5/subdirs\")\n\n\tLANGUAGES = request.text.split(\"\\n\")\n\tPODIR = \"po\"\n\n\t# Use source dir from command line arg as source dir\n\ttry:\n\t\tSOURCE_DIR = sys.argv[1]\n\texcept:\n\t\tSOURCE_DIR = os.getcwd()\n\n\tos.chdir(SOURCE_DIR)\n\n\t# Create po folder\n\tmkdir_if_neccesary(PODIR)\n\n\t# find translation modules and iterate\n\tmessage_files = list(\n\t\tfilter( # Filter out empty results\n\t\t\tNone, subprocess.check_output( # Find all Messages.sh files\n\t\t\t\t[\"find\", SOURCE_DIR, \"-name\", \"Messages.sh\"]\n\t\t\t).decode().split(\"\\n\") # Split into list\n\t\t)\n\t)\n\n\tif len(message_files) == 0:\n\t\tprint(\"No Messages.sh files found, cannot continue\")\n\t\tsys.exit(1)\n\n\tfor file in message_files:\n\t\t# Make sure path returned from find is not empty\n\t\tif file == \"\":\n\t\t\tcontinue\n\n\t\tmessagessh = open(file, \"r\").read().split(\"\\n\")\n\n\t\tfor line in messagessh:\n\t\t\t# Skip lines not writing to a message catalog\n\t\t\tif not \"-o $podir\" in line:\n\t\t\t\tcontinue\n\n\t\t\t# Extract module name\n\t\t\tmodule = line.split(\"-o\")[-1].split(\"/\")[1].replace(\".pot\", \"\").strip()\n\t\t\tprint(\"Fetching translations for\", module, \"...\")\n\n\t\t\t# detect KDE component\n\t\t\tprint(\"Detecting component ...\")\n\t\t\tcomponent = detect_component([\"de\", \"es\"] + LANGUAGES, module) # Prefer most common languages to speed up search\n\n\t\t\tprint(\"Detecting files to download ...\")\n\t\t\tfiles = detect_files(component, module)\n\n\t\t\tfor lang in LANGUAGES:\n\t\t\t\tmkdir_if_neccesary(PODIR + \"/\" + lang)\n\n\t\t\t\tfor file in files:\n\t\t\t\t\trequest = get(\"https://websvn.kde.org/*checkout*/trunk/l10n-kf5/{}/messages/{}/{}\".format(lang, component, file))\n\n\t\t\t\t\tif request.status_code == requests.codes.ok:\n\t\t\t\t\t\tprint(\"Downloading\", file, \"for\", lang)\n\t\t\t\t\t\tpofile = open(PODIR + \"/\" + lang + \"/\" + file, \"w\")\n\t\t\t\t\t\tpofile.write(request.text)\n\t\t\t\t\t\tpofile.close\n\n\tadd_i18n_to_cmake(PODIR)\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"kde-fetch-i18n.py","file_name":"kde-fetch-i18n.py","file_ext":"py","file_size_in_byte":3629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"536129057","text":"import os\nimport shutil\nfrom functools import reduce\nfrom pathlib import Path\nfrom unittest import mock\n\nimport pytest\n\nfrom antareslauncher.display.display_terminal import DisplayTerminal\nfrom antareslauncher.file_manager import file_manager\nfrom antareslauncher.study_dto import StudyDTO\n\nDATA_4_TEST_DIR = Path(__file__).parent.parent / \"data\" / \"file-manager-test\"\n\nDIR_TO_ZIP = DATA_4_TEST_DIR / \"to-zip\"\nDIR_REF = DATA_4_TEST_DIR / \"reference-without-output\" / \"to-zip\"\n\n\ndef get_dict_from_path(path):\n d = {'name': os.path.basename(path)}\n if os.path.isdir(path):\n d['type'] = \"directory\"\n d['children'] = [get_dict_from_path(os.path.join(path, x)) for x in os.listdir(path)]\n else:\n d['type'] = \"file\"\n return d\n\n\nclass TestFileManager:\n @pytest.mark.unit_test\n def test_golden_master_for_zip_study_excluding_output_dir(self):\n dir_to_zip = DIR_TO_ZIP\n zip_name = str(dir_to_zip) + \".zip\"\n display_terminal = DisplayTerminal()\n my_file_manager = file_manager.FileManager(display_terminal)\n\n my_file_manager.zip_dir_excluding_subdir(dir_to_zip, zip_name, \"output\")\n\n destination = DATA_4_TEST_DIR / \"TMP\"\n shutil.unpack_archive(zip_name, destination)\n results = destination / dir_to_zip.name\n results_dict = get_dict_from_path(results)\n reference_dict = get_dict_from_path(DIR_REF)\n\n assert results_dict == reference_dict\n result_zip_file = Path(zip_name)\n assert result_zip_file.is_file()\n result_zip_file.unlink()\n shutil.rmtree(destination)\n\n @pytest.mark.unit_test\n def test_if_zipfile_does_not_exist_then_unzip_returns_false(\n self,\n ):\n # given\n study = StudyDTO(\"path\")\n display_terminal = DisplayTerminal()\n my_file_manager = file_manager.FileManager(display_terminal)\n # when\n output = my_file_manager.unzip(study.local_final_zipfile_path)\n # then\n assert output is False\n\n @pytest.mark.unit_test\n def test_given_dir_path_and_subdir_name_when_get_list_dir_without_subdir_called_return_listdir_without_subdir(\n self,\n ):\n # given\n display_terminal = DisplayTerminal()\n my_file_manager = file_manager.FileManager(display_terminal)\n listdir = [\"dir1\", \"dir2\", \"dir42\"]\n my_file_manager.listdir_of = mock.Mock(return_value=listdir.copy())\n subdir_to_exclude = \"dir42\"\n listdir.remove(subdir_to_exclude)\n # when\n output = my_file_manager._get_list_dir_without_subdir(\"\", subdir_to_exclude)\n # then\n assert listdir == output\n","sub_path":"tests/unit/test_file_manager.py","file_name":"test_file_manager.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"270936287","text":"import pandas as pd\nimport pandas_profiling as pdp\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy import stats\nfrom pprint import pprint\nfrom collections import Counter\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.metrics import *\nfrom sklearn.preprocessing import OneHotEncoder, LabelEncoder, OrdinalEncoder, MinMaxScaler, MaxAbsScaler\nfrom sklearn.decomposition import PCA\n\ntrain_data = pd.read_csv(r\"C:\\Users\\马朝阳\\Desktop\\常用数据\\Employee_Satisfaction\\训练集.csv\")\ntest_data = pd.read_csv(r\"C:\\Users\\马朝阳\\Desktop\\常用数据\\Employee_Satisfaction\\测试集.csv\")\ntrain_data.index = train_data.id\ntest_data.index = test_data.id\nx_train = train_data.drop(columns=['satisfaction_level', 'id'], axis=1)\ny_train = train_data['satisfaction_level']\nx_test = test_data.drop('id', axis=1)\n\n\ndef encode(data, pca_comp_num=3):\n result = pd.DataFrame.copy(data, deep=True)\n division_le = OrdinalEncoder()\n package_le = OrdinalEncoder()\n salary_oe = OrdinalEncoder()\n\n result.division = division_le.fit_transform(result['division'].values.reshape(-1, 1))\n result.package = package_le.fit_transform(result['package'].values.reshape(-1, 1))\n result.salary = salary_oe.fit_transform(result['salary'].values.reshape(-1, 1))\n\n for col in ['last_evaluation', 'average_monthly_hours']:\n maxAbsEnc = MaxAbsScaler()\n result[col] = maxAbsEnc.fit_transform(result[col].values.reshape(-1, 1))\n for col in ['number_project', 'time_spend_company', 'package', 'division']:\n pca = PCA(n_components=pca_comp_num)\n new_col = pca.fit_transform(pd.get_dummies(data=result[col]).values.reshape(-1, 1))\n for i in range(pca_comp_num):\n result[col + '_' + str(i)] = new_col[:, i]\n result.drop(columns=[col], axis=1, inplace=True)\n for col in ['Work_accident', 'promotion_last_5years', 'salary']:\n one_hot_encode = pd.get_dummies(data=result[col])\n one_hot_encode.columns = [col + '_' + str(i) for i in range(len(one_hot_encode.columns))]\n result = result.join(one_hot_encode)\n result.drop(col, axis=1, inplace=True)\n return result\n\n\nx_test_cleaned = encode(x_test, 4)\nx_train_cleaned = encode(x_train, 4)\n","sub_path":"员工满意度预测.py","file_name":"员工满意度预测.py","file_ext":"py","file_size_in_byte":2279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"208679111","text":"import time\nimport subprocess\nimport digitalio\nimport board\nfrom PIL import Image, ImageDraw, ImageFont\nimport adafruit_rgb_display.st7789 as st7789\nimport random\n\n\n# Configuration for CS and DC pins (these are FeatherWing defaults on M0/M4):\ncs_pin = digitalio.DigitalInOut(board.CE0)\ndc_pin = digitalio.DigitalInOut(board.D25)\nreset_pin = None\n\n# Config for display baudrate (default max is 24mhz):\nBAUDRATE = 64000000\n\n# Setup SPI bus using hardware SPI:\nspi = board.SPI()\n\n# Create the ST7789 display:\ndisp = st7789.ST7789(\n spi,\n cs=cs_pin,\n dc=dc_pin,\n rst=reset_pin,\n baudrate=BAUDRATE,\n width=135,\n height=240,\n x_offset=53,\n y_offset=40,\n)\n\n# Create blank image for drawing.\n# Make sure to create image with mode 'RGB' for full color.\nheight = disp.width # we swap height/width to rotate it to landscape!\nwidth = disp.height\nimage = Image.new(\"RGB\", (width, height))\nrotation = 90\n\n# Get drawing object to draw on image.\ndraw = ImageDraw.Draw(image)\n\n# Draw a black filled box to clear the image.\ndraw.rectangle((0, 0, width, height), outline=0, fill=(0, 0, 0))\ndisp.image(image, rotation)\n# Draw some shapes.\n# First define some constants to allow easy resizing of shapes.\npadding = 40\ntop = padding\nbottom = height - padding\n# Move left to right keeping track of the current x position for drawing shapes.\nx = 0\n\n# Alternatively load a TTF font. Make sure the .ttf font file is in the\n# same directory as the python script!\n# Some other nice fonts to try: http://www.dafont.com/bitmap.php\nfont = ImageFont.truetype(\"/usr/share/fonts/truetype/dejavu/DejaVuSerifCondensed-BoldItalic.ttf\", 24)\n\n# Turn on the backlight\nbacklight = digitalio.DigitalInOut(board.D22)\nbacklight.switch_to_output()\nbacklight.value = True\nstart = 0\nend = 3\n\nx_center_text = width // 2\ny_center_text = height // 2\nx0, x1 = x_center_text - 60, x_center_text + 60\ny0, y1 = y_center_text - 60 , y_center_text + 60\nxy = [x0, y0, x1, y1]\nhh = [x_center_text - 45, y_center_text - 45, x_center_text + 45, y_center_text + 45]\n\ndef genTwoPts():\n random.seed()\n ret = []\n up, dw, lt, rt = [False] * 4\n while len(ret) < 2:\n ran = random.randint(0, 749)\n if ran < 240 and not up:\n up = True\n ret.append((ran, 0))\n elif ran < 375 and not lt:\n lt = True\n ret.append((0, ran - 240))\n elif ran < 615 and not dw:\n dw = True\n ret.append((ran - 375, 135))\n elif not rt:\n rt = True\n ret.append((240, ran - 615))\n return ret\n\nlines = [genTwoPts() for _ in range(60)]\nwhile True:\n # Draw a black filled box to clear the image.\n draw.rectangle((0, 0, width, height), outline=0, fill=0)\n t = time.localtime()\n h, m, s = t[3] if t[3] < 12 else t[3] - 12, t[4], t[5]\n\n # h_degree = 270 + 30 * h + m // 2\n # draw.arc(hh, h_degree-2, h_degree+2, fill=\"#FF280A\")\n # draw.pieslice(hh, h_degree-2, h_degree+2, fill=\"#FF280A\")\n # m_degree = 270 + 6 * m\n # draw.arc(xy, m_degree-2, m_degree+2, fill=\"#E2B659\")\n # draw.pieslice(xy, m_degree-2, m_degree+2, fill=\"#E2B659\")\n # s_degree = 270 + 6 * s\n # draw.arc(xy, s_degree-1, s_degree+1, fill=\"#ff0a67\")\n # draw.pieslice(xy, s_degree-1, s_degree+1, fill=\"#ff0a67\")\n if s == 0:\n lines.clear()\n lines = [genTwoPts() for _ in range(60)]\n # print(len(lines))\n else:\n for pts in lines[:s]:\n # print(pts)\n draw.line(pts, fill=\"#FF280A\", width=2)\n\n \n y = top\n draw.text((50, y), time.strftime(\"%m/%d/%Y\", t), font=font, fill=\"#FFFFFF\")\n y += 30\n draw.text((67, y), time.strftime(\"%H:%M:%S\", t), font=font, fill=\"#FFFFFF\")\n \n \n # Display image.\n disp.image(image, rotation)\n # time.sleep(1)","sub_path":"Lab 2/screen_clock.py","file_name":"screen_clock.py","file_ext":"py","file_size_in_byte":3780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"332002330","text":"import json\n\nfrom groot import logging\n\nfrom ...event_bus import EventBus\nfrom ...monitoring import AgentEventStreamCollector\nfrom ...scheduler import MasterScheduler, SchedulableCommandExecutor\nfrom ..base import BaseScheduledAlertModel # CheckedResult\n\nDEFAULT_TIMOUT = 30\n\nlogger = logging .getLogger(__name__)\n\nMAX_SIZE_OF_RESULT_TO_STORE = 1024\n\n\nclass ExecutableAlertModel(BaseScheduledAlertModel):\n \"\"\"\n document should have following subschema\n ....\n // either script or command\n script: {\n type : anyof 'shell' | 'python',\n code : ex. echo hi;sleep 5'\n },\n command : ex. 'python test.py',\n nodes : ['node1'] oR\n nodes : '$local' OR\n nodes : '$all',\n shell : // NA for scripts\n timeout : // execution in seconds\n user: // optional user name\n includeStdError: false,\n parseJsonFromStdout: true,\n ....\n \"\"\"\n\n TYPE = \"executable\"\n\n def __init__(self, document):\n BaseScheduledAlertModel.__init__(self, document)\n self.script = document.get(\"script\")\n self.command = document.get('command')\n self.shell = document.get(\"shell\", False) # NA for scripts\n self.user = document.get('user')\n self.timeout = document.get('timeout', DEFAULT_TIMOUT)\n self.stdout_as_json = document.get('stdoutAsJson')\n\n self.singleton = document['singleton'] # Make it mandatory\n self.nodes = None\n if not self.singleton:\n self.nodes = document.get('nodes', \"$all\")\n if isinstance(self.nodes, basestring):\n if self.nodes == \"$all\":\n raise NotImplementedError\n self.nodes = [self.nodes]\n\n self.event_id = None\n self._attched = None\n self.definition = document\n\n def attach(self):\n if self.singleton:\n self.event_id = \"@executable#%s\" % self.id # this should be a unique\n scheduled_executor = SchedulableCommandExecutor(self.definition)\n MasterScheduler.dock(scheduled_executor, self.schedule, self.event_id)\n # (since this is singleton, only one type of result expected.)\n ident = ('$local',)\n\n @EventBus.subscribe(event_id=self.event_id)\n def on_event(ev):\n \"\"\"subscriber for singleton(local) executable alert\"\"\"\n # ev= {id: str, result:?}\n # result is of type namedtuple('ExecutionResult', ('retcode', 'stdout', 'stderr',))\n # or an exception\n result = ev['result']\n if isinstance(result, Exception):\n logger.error(\"error while singleton alert run err=%r\", result)\n self.store_result(\n ident, {'ok': False, 'value': None, 'oops': repr(result)}\n )\n return\n self.store_result(ident,\n self.prepare_result(result.stdout, result.retcode))\n else:\n self.event_id = \"$executable#%s\" % self.id # this should be a unique\n AgentEventStreamCollector.configure_multinode_event(\n self.nodes, # list\n {\n 'type': 'executable',\n 'id': self.event_id,\n 'script': self.script,\n 'command': self.command,\n 'schedule': self.schedule,\n 'stdoutAsJson': self.stdout_as_json\n }\n )\n\n @EventBus.subscribe(event_id=self.event_id)\n def on_event(ev):\n \"\"\"subscriber for remote executable alert\"\"\"\n # ev = {stdout:?, stderr:?, retcode:int, }\n nodename = ev['node']\n ident = (nodename,) # each node event are different\n exception = ev['exception'] # tuple(type:string, message:string)?\n oops = \"%s:%s\" % exception if exception else None\n if oops:\n self.store_result(\n ident, {'ok': False, 'value': None, 'oops': oops}\n )\n return\n retcode, stdout, _ = ev['data']['result']\n self.store_result(ident, self.prepare_result(stdout, retcode, nodename))\n\n self._attched = on_event # this will ensure atleast reference to cb fn not to GCied\n\n def prepare_result(self, stdout, retcode, nodename=None):\n value = {'retcode': retcode}\n oops = None\n # sz = len(result.stdout) TODO:\n if self.stdout_as_json and (retcode or stdout):\n # only if nonzero retcode or noempty stdout, we need to parse\n try:\n jobj = json.loads(stdout)\n assert isinstance(jobj, dict)\n value.update(jobj)\n except Exception as oops:\n oops = repr(oops)\n else:\n value['stdout'] = stdout\n if nodename:\n value['nodename'] = nodename\n return {'ok': retcode == 0, 'value': value, 'oops': oops}\n\n @property\n def attached(self):\n return bool(self._attched)\n\n def detach(self):\n if not self._attched:\n return\n if self.singleton:\n # remove from local scheduler\n MasterScheduler.undock(self.event_id)\n else:\n AgentEventStreamCollector.remove_event(self.event_id, self.nodes)\n self._attched = False\n","sub_path":"groot/core/alerts/executable/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"81182342","text":"import pandas as pd\nfrom PySide2 import QtCore, QtWidgets, QtGui\nimport sys\nimport Student\nimport pandas as pd\nimport os\n\n\nglobal lstStudent\nlstStudent = list()\n\nclass parent(QtWidgets.QWidget):\n\n\n def init_ui(self, windoName):\n self.center()\n self.setWindowTitle(windoName)\n \n \n\n def center(self):\n # geometry of the main window\n qr = self.frameGeometry()\n\n # center point of screen\n cp = QtWidgets.QDesktopWidget().availableGeometry().center()\n\n # move rectangle's center point to screen's center point\n qr.moveCenter(cp)\n\n # top left of rectangle becomes top left of window centering it\n self.move(qr.topLeft())\n\n\nclass NewStdWindow(parent):\n\n \n def __init__(self, ID=0):\n super().__init__()\n self.ID = int(ID) - 1\n self.Base_UI()\n \n \n\n def Base_UI(self):\n if self.ID ==-1:\n self.init_ui(\"New Insert Studet\")\n else:\n self.init_ui(\"Edit Studet\")\n\n self.lblID = QtWidgets.QLabel()\n self.lblID.setText('ID : ' )\n self.lblID.setStyleSheet(\"font-size: 12px;\")\n\n self.ledID = QtWidgets.QSpinBox()\n if self.ID == - 1:\n self.ledID.setValue(len(lstStudent) +1)\n self.ledID.setReadOnly(True)\n \n \n\n self.lblName = QtWidgets.QLabel()\n self.lblName.setText('Name : ' )\n self.lblName.setStyleSheet(\"font-size: 12px;\")\n\n self.ledName = QtWidgets.QLineEdit()\n \n self.lblFamily = QtWidgets.QLabel()\n self.lblFamily.setText('Family : ' )\n self.lblFamily.setStyleSheet(\"font-size: 12px;\")\n\n self.ledFamily = QtWidgets.QLineEdit()\n\n self.lblGrad = QtWidgets.QLabel()\n self.lblGrad.setText('Grad : ' )\n self.lblGrad.setStyleSheet(\"font-size: 12px;\")\n\n self.ledGrad = QtWidgets.QLineEdit()\n\n #self.grbScore = QGroupBox('Score of Course : ')\n\n self.lblMath = QtWidgets.QLabel()\n self.lblMath.setText('Math : ' )\n self.lblMath.setStyleSheet(\"font-size: 12px;\")\n\n self.ledMath = QtWidgets.QDoubleSpinBox()\n self.ledMath.setMaximum(20)\n self.ledMath.setMinimum(0)\n\n self.lblScince = QtWidgets.QLabel()\n self.lblScince.setText('Scince : ' )\n self.lblScince.setStyleSheet(\"font-size: 12px;\")\n\n self.ledScince = QtWidgets.QDoubleSpinBox()\n self.ledScince.setMaximum(20)\n self.ledScince.setMinimum(0)\n\n\n self.lblAlghebra = QtWidgets.QLabel()\n self.lblAlghebra.setText('Algebra : ' )\n self.lblAlghebra.setStyleSheet(\"font-size: 12px;\")\n\n self.ledAlghebra = QtWidgets.QDoubleSpinBox()\n self.ledAlghebra.setMaximum(20)\n self.ledAlghebra.setMinimum(0)\n\n self.lblComputer = QtWidgets.QLabel()\n self.lblComputer.setText('Computer : ' )\n self.lblComputer.setStyleSheet(\"font-size: 12px;\") \n\n self.ledComputer = QtWidgets.QDoubleSpinBox()\n self.ledComputer.setMaximum(20)\n self.ledComputer.setMinimum(0)\n\n self.grdScore = QtWidgets.QGridLayout()\n self.grdScore.setSpacing(4)\n\n self.grdStd = QtWidgets.QGridLayout()\n self.grdStd.setSpacing(5)\n\n self.grdScore.addWidget(self.lblMath, 1, 0)\n self.grdScore.addWidget(self.ledMath, 1, 1)\n \n self.grdScore.addWidget(self.lblScince, 2, 0)\n self.grdScore.addWidget(self.ledScince, 2, 1)\n\n self.grdScore.addWidget(self.lblAlghebra, 3, 0)\n self.grdScore.addWidget(self.ledAlghebra, 3, 1)\n\n self.grdScore.addWidget(self.lblComputer, 4, 0)\n self.grdScore.addWidget(self.ledComputer, 4, 1)\n\n self.grdbtn = QtWidgets.QGridLayout()\n self.grdbtn.setSpacing(1)\n\n\n self.btnSave = QtWidgets.QPushButton(\"Save\")\n self.btnSave.clicked.connect(self.SaveStd)\n\n self.btnCancel = QtWidgets.QPushButton(\"Cancel\")\n self.btnCancel.clicked.connect(self.Cancel)\n\n self.grdbtn.addWidget(self.btnSave, 1, 0)\n self.grdbtn.addWidget(self.btnCancel, 1, 1)\n\n\n\n\n #self.grbScore.setLayout(self.grbScore)\n \n self.grdStd.addWidget(self.lblID, 0, 0)\n self.grdStd.addWidget(self.ledID, 0, 1)\n\n self.grdStd.addWidget(self.lblName, 1, 0)\n self.grdStd.addWidget(self.ledName, 1, 1)\n \n self.grdStd.addWidget(self.lblFamily, 2, 0)\n self.grdStd.addWidget(self.ledFamily, 2, 1)\n\n self.grdStd.addWidget(self.lblGrad, 3, 0)\n self.grdStd.addWidget(self.ledGrad, 3, 1)\n\n self.grdStd.addLayout(self.grdScore, 4, 1)\n\n self.grdStd.addLayout(self.grdbtn, 5, 2)\n\n\n\n self.setLayout(self.grdStd)\n\n if self.ID != -1:\n self.ledID.setValue(int(lstStudent[self.ID].id))\n self.ledName.setText(lstStudent[self.ID].name)\n self.ledFamily.setText(lstStudent[self.ID].family)\n self.ledGrad.setText(lstStudent[self.ID].grade)\n\n self.ledAlghebra.setValue(lstStudent[self.ID].alghebra)\n self.ledComputer.setValue(lstStudent[self.ID].computer)\n self.ledMath.setValue(lstStudent[self.ID].math)\n self.ledScince.setValue(lstStudent[self.ID].scince)\n\n\n def SaveStd(self):\n\n if self.ID == -1 :\n id = int(self.ledID.text())\n name = self.ledName.text() \n family = self.ledFamily.text()\n grade = self.ledGrad.text()\n\n math = float(self.ledMath.text())\n algebra = float(self.ledAlghebra.text())\n scince = float(self.ledScince.text())\n computer = float(self.ledComputer.text())\n std = Student.Student(id, name, family, grade, math, algebra, scince,computer)\n \n \n # reply = QtGui.QMessageBox.ok .question(self, 'Save Message',\n # \"New student succussfuly insert.\", QtGui.QMessageBox.Yes | \n # QtGui.QMessageBox.No, QtGui.QMessageBox.No)\n\n # if reply == QtGui.QMessageBox.Yes:\n # event.accept()\n # else:\n # event.ignore() \n\n lstStudent.append(std)\n\n else :\n lstStudent[self.ID].name = self.ledName.text()\n lstStudent[self.ID].family = self.ledFamily.text()\n lstStudent[self.ID].grade = self.ledGrad.text()\n\n lstStudent[self.ID].alghebra = self.ledAlghebra.text()\n lstStudent[self.ID].computer = self.ledComputer.text()\n lstStudent[self.ID].scince = self.ledScince.text()\n lstStudent[self.ID].math = self.ledMath.text()\n \n \n\n self.close()\n\n def Cancel(self):\n self.close()\n \nclass EditWindow(parent):\n global df\n def __init__(self):\n super().__init__()\n\n self.setWindowTitle(\"List of Student\")\n\n self.edit = QtWidgets.QLineEdit()\n self.edit.returnPressed.connect(self.magic)\n\n \n\n self.result = QtWidgets.QPlainTextEdit()\n self.result.setReadOnly(True)\n \n self.button = QtWidgets.QPushButton(\"Edit\")\n\n self.lblId = QtWidgets.QLabel('ID : ')\n self.lblId.setStyleSheet(\"font-size: 12px;\")\n\n self.grid2 = QtWidgets.QGridLayout()\n self.grid2.setSpacing(1)\n\n self.grid2.addWidget(self.lblId, 1,0)\n self.grid2.addWidget(self.edit, 1,1)\n\n self.grid = QtWidgets.QGridLayout()\n self.grid.setSpacing(6)\n\n self.grid.addLayout(self.grid2, 1, 0)\n self.grid.addWidget(self.button, 1, 1)\n \n \n \n\n self.grid.addWidget(self.result, 2, 0)\n\n self.button.clicked.connect(self.magic) \n\n self.setLayout(self.grid)\n\n dictoFstudent = [list(vars(a).values()) for a in lstStudent]\n \n df = pd.DataFrame(dictoFstudent, index= None)\n self.result.setPlainText(str(df.to_numpy()))\n\n\n def magic(self):\n try :\n ID = self.edit.text()\n\n if len(lstStudent)>= int(ID):\n self.newStd = NewStdWindow(ID)\n self.newStd.setFixedSize(600, 300)\n self.newStd.center()\n self.newStd.show()\n\n else :\n mb = QtWidgets.QMessageBox()\n #mb.setIcon(mb.Icon.Error)\n mb.setText(\"{0}\".format('Not exist this ID'))\n mb.setWindowTitle(\"Error\")\n mb.exec_() \n except :\n mb = QtWidgets.QMessageBox()\n #mb.setIcon(mb.Icon.Error)\n mb.setText(\"{0}\".format('ID is a number '))\n mb.setWindowTitle(\"Error\")\n mb.exec_() \n\nclass ReportWindow(parent):\n\n def __init__(self):\n super().__init__()\n\n dictoFstudent = [list(vars(a).values()) for a in lstStudent]\n df = pd.DataFrame(dictoFstudent)\n # print(df)\n studentCont = len(lstStudent)\n print(df.head(10))\n self.lblMath = QtWidgets.QLabel('Math ')\n self.lblMath.setStyleSheet(\"font-size: 14px; \")\n\n self.lblMaxMath = QtWidgets.QLabel('Min : '+ str(df.min()[4]))\n self.lblMaxMath.setStyleSheet(\"font-size: 12px; \")\n\n self.lblMinMath = QtWidgets.QLabel('Max : '+ str(df.max()[4]))\n self.lblMinMath.setStyleSheet(\"font-size: 12px; \")\n\n self.lblAveMath = QtWidgets.QLabel('Average : '+ str(df.mean()[4]))\n self.lblAveMath.setStyleSheet(\"font-size: 12px; \")\n\n self.grdMath = QtWidgets.QGridLayout()\n self.grdMath.setSpacing(4)\n\n\n self.grdMath.addWidget(self.lblMath, 1, 0)\n self.grdMath.addWidget(self.lblMaxMath, 2, 0)\n self.grdMath.addWidget(self.lblMinMath, 3, 0)\n self.grdMath.addWidget(self.lblAveMath, 4, 0)\n self.grdMath.setMargin(20)\n\n self.lblAl = QtWidgets.QLabel('Algebra ')\n self.lblAl.setStyleSheet(\"font-size: 14px; \")\n\n self.lblMaxAl = QtWidgets.QLabel('Min : ' + str(df.min()[6]))\n self.lblMaxAl.setStyleSheet(\"font-size: 12px; \" )\n\n self.lblMinAl = QtWidgets.QLabel('Max : '+ str(df.max()[6]))\n self.lblMinAl .setStyleSheet(\"font-size: 12px; \")\n\n self.lblAveAl = QtWidgets.QLabel('Average :'+ str(df.mean()[6]))\n self.lblAveAl.setStyleSheet(\"font-size: 12px; \")\n\n self.grdAl = QtWidgets.QGridLayout()\n self.grdAl.setSpacing(4)\n\n\n self.grdAl.addWidget(self.lblAl, 1, 0)\n self.grdAl.addWidget(self.lblMaxAl, 2, 0)\n self.grdAl.addWidget(self.lblMinAl, 3, 0)\n self.grdAl.addWidget(self.lblAveAl, 4, 0)\n self.grdAl.setMargin(20)\n\n self.lblSci = QtWidgets.QLabel('Science')\n self.lblSci.setStyleSheet(\"font-size: 14px; \")\n\n self.lblMaxSci = QtWidgets.QLabel('Min : '+ str(df.min()[5]))\n self.lblMaxSci.setStyleSheet(\"font-size: 12px; \")\n\n self.lblMinSci = QtWidgets.QLabel('Max : '+ str(df.max()[5]))\n self.lblMinSci .setStyleSheet(\"font-size: 12px; \")\n\n self.lblAveSci = QtWidgets.QLabel('Average :'+ str(df.mean()[5]))\n self.lblAveSci.setStyleSheet(\"font-size: 12px; \")\n\n self.grdSci = QtWidgets.QGridLayout()\n self.grdSci.setSpacing(4)\n\n\n self.grdSci.addWidget(self.lblSci, 1, 0)\n self.grdSci.addWidget(self.lblMaxSci, 2, 0)\n self.grdSci.addWidget(self.lblMinSci, 3, 0)\n self.grdSci.addWidget(self.lblAveSci, 4, 0)\n self.grdSci.setMargin(20)\n\n self.lblCmp = QtWidgets.QLabel('Computer ')\n self.lblCmp.setStyleSheet(\"font-size: 14px; \")\n\n self.lblMaxCmp = QtWidgets.QLabel('Min : '+ str(df.min()[7]))\n self.lblMaxCmp.setStyleSheet(\"font-size: 12px; \")\n\n self.lblMinCmp = QtWidgets.QLabel('Max : '+ str(df.max()[7]))\n self.lblMinCmp .setStyleSheet(\"font-size: 12px; \")\n\n self.lblAveCmp = QtWidgets.QLabel('Average :'+ str(df.mean()[7]))\n self.lblAveCmp.setStyleSheet(\"font-size: 12px; \")\n\n self.grdCmp = QtWidgets.QGridLayout()\n self.grdCmp.setSpacing(4)\n\n\n self.grdCmp.addWidget(self.lblCmp, 1, 0)\n self.grdCmp.addWidget(self.lblMaxCmp, 2, 0)\n self.grdCmp.addWidget(self.lblMinCmp, 3, 0)\n self.grdCmp.addWidget(self.lblAveCmp, 4, 0)\n self.grdCmp.setMargin(20)\n\n\n self.grdBase = QtWidgets.QGridLayout()\n self.grdBase.setSpacing(3)\n\n self.grdBase.addLayout(self.grdMath, 1, 0)\n self.grdBase.addLayout(self.grdAl, 1, 1)\n self.grdBase.addLayout(self.grdSci, 2, 0)\n self.grdBase.addLayout(self.grdCmp, 2, 1)\n\n self.setLayout(self.grdBase)\n\n\n\nclass MainWindow(parent):\n\n def __init__(self):\n super(MainWindow, self).__init__()\n self.init_ui(\"Main Window\")\n self.show()\n\n self.grid = QtWidgets.QGridLayout()\n self.grid.setSpacing(4)\n # self.grid.setAlignment(QtCore.Qt.AlignCenter)\n self.grid.setHorizontalSpacing(30)\n self.grid.setVerticalSpacing(30)\n\n\n self.btnNew = QtWidgets.QPushButton(\" New Student\")\n self.btnNew.setIcon(QtGui.QPixmap('media/student.png'))\n self.btnNew.setIconSize(QtCore.QSize(120, 120))\n self.btnNew.clicked.connect(self.OpenNewStd)\n\n\n self.btnViewStd = QtWidgets.QPushButton(\" Viwe/Edit Student\")\n self.btnViewStd.setIcon(QtGui.QPixmap('media/class.png'))\n self.btnViewStd.setIconSize(QtCore.QSize(120, 120))\n self.btnViewStd.clicked.connect(self.EditViewStd)\n\n self.btnExport = QtWidgets.QPushButton(\" Export Data\")\n self.btnExport.setIcon(QtGui.QPixmap('media/study.png'))\n self.btnExport.setIconSize(QtCore.QSize(120, 120))\n self.btnExport.clicked.connect(self.ExportWindow)\n\n\n self.btnRepo = QtWidgets.QPushButton(\" Report\")\n self.btnRepo.setIcon(QtGui.QPixmap('media/maths.png'))\n self.btnRepo.setIconSize(QtCore.QSize(120, 120))\n self.btnRepo.clicked.connect(self.RepotWindoCourse)\n\n self.grid.addWidget(self.btnNew, 1, 0)\n self.grid.addWidget(self.btnViewStd, 1, 1)\n self.grid.addWidget(self.btnExport, 2, 1)\n self.grid.addWidget(self.btnRepo, 2, 0)\n self.setLayout(self.grid)\n\n \n\n\n def OpenNewStd(self):\n #self.hide()\n self.newStd = NewStdWindow()\n self.newStd.setFixedSize(600, 300)\n self.newStd.center()\n self.newStd.show()\n\n def EditViewStd(self):\n self.editStd = EditWindow()\n self.editStd.setFixedSize(600, 300)\n self.editStd.center()\n self.editStd.show()\n\n def RepotWindoCourse(self):\n if len(lstStudent)>0:\n self.repoWindow = ReportWindow()\n self.repoWindow.setFixedSize(300, 300)\n self.repoWindow.center()\n self.repoWindow.show()\n else:\n mb = QtWidgets.QMessageBox()\n #mb.setIcon(mb.Icon.Error)\n mb.setText(\"{0}\".format('First Insert a Student'))\n mb.setWindowTitle(\"Error\")\n mb.exec_() \n \n def ExportWindow(self):\n # self.exportWindow = ExportWindow()\n # self.exportWindow.setFixedSize(200, 200)\n # self.exportWindow.center()\n # self.exportWindow.show()\n \n fname = QtWidgets.QFileDialog.getSaveFileName(caption='Export File', options=QtWidgets.QFileDialog.DontUseNativeDialog, filter=\"csv file (*.csv)\")\n dictoFstudent = [list(vars(a).values()) for a in lstStudent]\n df = pd.DataFrame(dictoFstudent)\n if not os.path.isfile(fname[0]):\n f = open(fname[0]+'.csv', 'x')\n f.write(df.to_csv())\n f.close()\n else:\n f = open(fname[0], 'w')\n f.write(df.to_csv())\n f.close()\n\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n\n widget = MainWindow()\n \n\n sys.exit(app.exec_())","sub_path":"Practices/4/GSR.py","file_name":"GSR.py","file_ext":"py","file_size_in_byte":15761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"370125268","text":"\"\"\"Test the Sonarr config flow.\"\"\"\nfrom unittest.mock import patch\n\nfrom homeassistant.components.sonarr.const import (\n CONF_UPCOMING_DAYS,\n CONF_WANTED_MAX_ITEMS,\n DEFAULT_UPCOMING_DAYS,\n DEFAULT_WANTED_MAX_ITEMS,\n DOMAIN,\n)\nfrom homeassistant.config_entries import SOURCE_REAUTH, SOURCE_USER\nfrom homeassistant.const import CONF_API_KEY, CONF_HOST, CONF_SOURCE, CONF_VERIFY_SSL\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.data_entry_flow import (\n RESULT_TYPE_ABORT,\n RESULT_TYPE_CREATE_ENTRY,\n RESULT_TYPE_FORM,\n)\n\nfrom tests.components.sonarr import (\n HOST,\n MOCK_REAUTH_INPUT,\n MOCK_USER_INPUT,\n _patch_async_setup_entry,\n mock_connection,\n mock_connection_error,\n mock_connection_invalid_auth,\n setup_integration,\n)\nfrom tests.test_util.aiohttp import AiohttpClientMocker\n\n\nasync def test_show_user_form(hass: HomeAssistant) -> None:\n \"\"\"Test that the user set up form is served.\"\"\"\n result = await hass.config_entries.flow.async_init(\n DOMAIN,\n context={CONF_SOURCE: SOURCE_USER},\n )\n\n assert result[\"step_id\"] == \"user\"\n assert result[\"type\"] == RESULT_TYPE_FORM\n\n\nasync def test_cannot_connect(\n hass: HomeAssistant, aioclient_mock: AiohttpClientMocker\n) -> None:\n \"\"\"Test we show user form on connection error.\"\"\"\n mock_connection_error(aioclient_mock)\n\n user_input = MOCK_USER_INPUT.copy()\n result = await hass.config_entries.flow.async_init(\n DOMAIN,\n context={CONF_SOURCE: SOURCE_USER},\n data=user_input,\n )\n\n assert result[\"type\"] == RESULT_TYPE_FORM\n assert result[\"step_id\"] == \"user\"\n assert result[\"errors\"] == {\"base\": \"cannot_connect\"}\n\n\nasync def test_invalid_auth(\n hass: HomeAssistant, aioclient_mock: AiohttpClientMocker\n) -> None:\n \"\"\"Test we show user form on invalid auth.\"\"\"\n mock_connection_invalid_auth(aioclient_mock)\n\n user_input = MOCK_USER_INPUT.copy()\n result = await hass.config_entries.flow.async_init(\n DOMAIN,\n context={CONF_SOURCE: SOURCE_USER},\n data=user_input,\n )\n\n assert result[\"type\"] == RESULT_TYPE_FORM\n assert result[\"step_id\"] == \"user\"\n assert result[\"errors\"] == {\"base\": \"invalid_auth\"}\n\n\nasync def test_unknown_error(\n hass: HomeAssistant, aioclient_mock: AiohttpClientMocker\n) -> None:\n \"\"\"Test we show user form on unknown error.\"\"\"\n user_input = MOCK_USER_INPUT.copy()\n with patch(\n \"homeassistant.components.sonarr.config_flow.Sonarr.update\",\n side_effect=Exception,\n ):\n result = await hass.config_entries.flow.async_init(\n DOMAIN,\n context={CONF_SOURCE: SOURCE_USER},\n data=user_input,\n )\n\n assert result[\"type\"] == RESULT_TYPE_ABORT\n assert result[\"reason\"] == \"unknown\"\n\n\nasync def test_full_reauth_flow_implementation(\n hass: HomeAssistant, aioclient_mock: AiohttpClientMocker\n) -> None:\n \"\"\"Test the manual reauth flow from start to finish.\"\"\"\n entry = await setup_integration(\n hass, aioclient_mock, skip_entry_setup=True, unique_id=\"any\"\n )\n assert entry\n\n result = await hass.config_entries.flow.async_init(\n DOMAIN,\n context={CONF_SOURCE: SOURCE_REAUTH, \"unique_id\": entry.unique_id},\n data=entry.data,\n )\n\n assert result[\"type\"] == RESULT_TYPE_FORM\n assert result[\"step_id\"] == \"reauth_confirm\"\n\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"], user_input={}\n )\n\n assert result[\"type\"] == RESULT_TYPE_FORM\n assert result[\"step_id\"] == \"user\"\n\n user_input = MOCK_REAUTH_INPUT.copy()\n with _patch_async_setup_entry() as mock_setup_entry:\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"], user_input=user_input\n )\n await hass.async_block_till_done()\n\n assert result[\"type\"] == RESULT_TYPE_ABORT\n assert result[\"reason\"] == \"reauth_successful\"\n\n assert entry.data[CONF_API_KEY] == \"test-api-key-reauth\"\n\n mock_setup_entry.assert_called_once()\n\n\nasync def test_full_user_flow_implementation(\n hass: HomeAssistant, aioclient_mock: AiohttpClientMocker\n) -> None:\n \"\"\"Test the full manual user flow from start to finish.\"\"\"\n mock_connection(aioclient_mock)\n\n result = await hass.config_entries.flow.async_init(\n DOMAIN,\n context={CONF_SOURCE: SOURCE_USER},\n )\n\n assert result[\"type\"] == RESULT_TYPE_FORM\n assert result[\"step_id\"] == \"user\"\n\n user_input = MOCK_USER_INPUT.copy()\n\n with _patch_async_setup_entry():\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"],\n user_input=user_input,\n )\n\n assert result[\"type\"] == RESULT_TYPE_CREATE_ENTRY\n assert result[\"title\"] == HOST\n\n assert result[\"data\"]\n assert result[\"data\"][CONF_HOST] == HOST\n\n\nasync def test_full_user_flow_advanced_options(\n hass: HomeAssistant, aioclient_mock: AiohttpClientMocker\n) -> None:\n \"\"\"Test the full manual user flow with advanced options.\"\"\"\n mock_connection(aioclient_mock)\n\n result = await hass.config_entries.flow.async_init(\n DOMAIN, context={CONF_SOURCE: SOURCE_USER, \"show_advanced_options\": True}\n )\n\n assert result[\"type\"] == RESULT_TYPE_FORM\n assert result[\"step_id\"] == \"user\"\n\n user_input = {\n **MOCK_USER_INPUT,\n CONF_VERIFY_SSL: True,\n }\n\n with _patch_async_setup_entry():\n result = await hass.config_entries.flow.async_configure(\n result[\"flow_id\"],\n user_input=user_input,\n )\n\n assert result[\"type\"] == RESULT_TYPE_CREATE_ENTRY\n assert result[\"title\"] == HOST\n\n assert result[\"data\"]\n assert result[\"data\"][CONF_HOST] == HOST\n assert result[\"data\"][CONF_VERIFY_SSL]\n\n\nasync def test_options_flow(hass, aioclient_mock: AiohttpClientMocker):\n \"\"\"Test updating options.\"\"\"\n with patch(\"homeassistant.components.sonarr.PLATFORMS\", []):\n entry = await setup_integration(hass, aioclient_mock)\n\n assert entry.options[CONF_UPCOMING_DAYS] == DEFAULT_UPCOMING_DAYS\n assert entry.options[CONF_WANTED_MAX_ITEMS] == DEFAULT_WANTED_MAX_ITEMS\n\n result = await hass.config_entries.options.async_init(entry.entry_id)\n\n assert result[\"type\"] == RESULT_TYPE_FORM\n assert result[\"step_id\"] == \"init\"\n\n with _patch_async_setup_entry():\n result = await hass.config_entries.options.async_configure(\n result[\"flow_id\"],\n user_input={CONF_UPCOMING_DAYS: 2, CONF_WANTED_MAX_ITEMS: 100},\n )\n await hass.async_block_till_done()\n\n assert result[\"type\"] == RESULT_TYPE_CREATE_ENTRY\n assert result[\"data\"][CONF_UPCOMING_DAYS] == 2\n assert result[\"data\"][CONF_WANTED_MAX_ITEMS] == 100\n","sub_path":"tests/components/sonarr/test_config_flow.py","file_name":"test_config_flow.py","file_ext":"py","file_size_in_byte":6767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"161327136","text":"#! /usr/bin/env python\n\n\"\"\"\nFile: Particles.py\nCopyright (c) 2016 Austin Ayers\nLicense: MIT\n\nCourse: PHYS227\nAssignment: 8.15\nDate: March 18, 2016\nEmail: ayers111@mail.chapman.edu\nName: Austin Ayers\nDescription: Framework over Object Particle, to plot and move each Particle\n\n\"\"\"\nimport matplotlib\nmatplotlib.use('Agg')\nimport random as R\nimport matplotlib.pyplot as plt\nfrom unittest import TestCase\nimport numpy as np\nimport time\nfrom Particle import *\n\n\nclass Particles:\n \"\"\"\n Moves and plots objects of type 'Particle'\n \"\"\"\n def __init__(self, particles):\n \"\"\"\n particles is an array of type 'Particle'\n \"\"\"\n self.particles = particles\n self.np = len(particles)\n self.step = 0\n def move(self, step_size = 1):\n \"\"\"\n Translates all particles uniformly by step_size\n \"\"\"\n for p in self.particles:\n p.move(step_size)\n self.step += 1\n\n def plot(self):\n \"\"\"\n Plots all particles\n \"\"\"\n xpositions = []\n ypositions = []\n for p in self.particles:\n xpositions.append(p.x)\n ypositions.append(p.y)\n plt.plot(xpositions, ypositions, 'ko',\n axis = [-100,100,-100,100],\n title = '%d particles after %d steps' %\n (self.np, self.step+1),\n savefig = 'tmp_%03d.pdf' % (self.step+1))\n\n def generate_frame(self):\n \"\"\"\n Plots the particles and outputs them to a file\n \"\"\"\n xpositions = []\n ypositions = []\n for p in self.particles:\n xpositions.append(p.x)\n ypositions.append(p.y)\n fig, ax = plt.subplots(nrows = 1, ncols = 1)\n ax.plot(xpositions, ypositions, 'ko')\n ax.set_ylim([-10,10])\n ax.set_xlim([-10,10])\n fig.savefig('tmp_%03d.png' % (self.step))\n plt.close(fig)\n\n def moves(self, N = 10, step_size = 1):\n \"\"\"\n Loops over move() and plot() function N times\n \"\"\"\n self.generate_frame()\n for i in xrange(N):\n self.move(step_size)\n self.generate_frame()\n\nclass Test_Particles(TestCase):\n def test_Particle(self):\n \"\"\"Makes sure that the particles with the same random seed move in the same manner.\"\"\"\n seed_time = int(time.time()*10 % 10000)\n particle_list = [Particle(seed_time) for _ in xrange(3)]\n particles = Particles(np.array(particle_list))\n particles.move()\n x_array = np.array([particles.particles[n].x for n in xrange(3)])\n y_array = np.array([particles.particles[n].y for n in xrange(3)])\n apt = ((x_array[0] == x_array).all() and (y_array[0] == y_array).all())\n msg = 'Particles did not move in the same way'\n assert apt, msg","sub_path":"disorder2.py","file_name":"disorder2.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"52738315","text":"# File: statements.py\n# Template file for Informatics 2A Assignment 2:\n# 'A Natural Language Query System in Python/NLTK'\n\n# John Longley, November 2012\n# Revised November 2013 and November 2014 with help from Nikolay Bogoychev\n# Revised November 2015 by Toms Bergmanis\n# Revised October 2017 by Chunchuan Lyu\n\n\n# PART A: Processing statements\n\ndef add(lst,item):\n if (item not in lst):\n lst.insert(len(lst),item)\n\nclass Lexicon:\n \"\"\"stores known word stems of various part-of-speech categories\"\"\"\n def __init__ (self):\n self.tupleList = []\n def add (self, stem, cat):\n self.tupleList.append((stem, cat))\n def getAll (self, cat):\n lst = []\n for t in self.tupleList:\n if (t[1] == cat):\n add (lst, t[0])\n return lst\n\nclass FactBase:\n def __init__ (self):\n self.unary = []\n self.binary = []\n def addUnary (self, pred, e1):\n self.unary.append((pred, e1))\n def addBinary (self, pred, e1, e2):\n self.binary.append((pred, e1, e2))\n def queryUnary (self, pred, e1):\n for u in self.unary:\n if (u == (pred, e1)):\n return True\n break\n return False\n def queryBinary (self, pred, e1, e2):\n if ((pred, e1, e2) in self.binary):\n return True\n else:\n return False\n\n\nimport re\nfrom nltk.corpus import brown\ndef verb_stem(s):\n \"\"\"extracts the stem from the 3sg form of a verb, or returns empty string\"\"\"\n ok = 0\n\n if (re.match(\"\\w*([^aeiousxyzh]|[^cs]h)s$\", s)):\n stem = s[:-1]\n elif (re.match(\"(\\w*)[aeiou]ys$\", s)):\n stem = s[:-1]\n elif (re.match(\"\\w+[^aeiou]ies$\", s)):\n stem = s[:-3]+'y'\n elif (re.match(\"[^aeiou]ies$\", s)):\n stem = s[:-1]\n elif (re.match(\"\\w*([ox]|ch|sh|ss|zz)es$\", s)):\n stem = s[:-2]\n elif (re.match(\"\\w*(([^s]se)|([^z]ze))s$\", s)):\n stem = s[:-1]\n elif (re.match(\"has\", s)):\n stem = \"have\"\n elif (re.match(\"\\w*([^iosxzh]|[^cs]h)es$\", s)):\n stem = s[:-1]\n else:\n stem = \"\"\n\n if (stem != \"\" and ok != 1):\n for (word, tag) in brown.tagged_words():\n if word == stem and tag in ('VB', 'VBZ'):\n return stem\n ok = 1\n break\n\n if (ok == 0):\n return \"\"\n\n\ndef add_proper_name (w,lx):\n \"\"\"adds a name to a lexicon, checking if first letter is uppercase\"\"\"\n if ('A' <= w[0] and w[0] <= 'Z'):\n lx.add(w,'P')\n return ''\n else:\n return (w + \" isn't a proper name\")\n\ndef process_statement (lx,wlist,fb):\n \"\"\"analyses a statement and updates lexicon and fact base accordingly;\n returns '' if successful, or error message if not.\"\"\"\n # Grammar for the statement language is:\n # S -> P is AR Ns | P is A | P Is | P Ts P\n # AR -> a | an\n # We parse this in an ad hoc way.\n msg = add_proper_name (wlist[0],lx)\n if (msg == ''):\n if (wlist[1] == 'is'):\n if (wlist[2] in ['a','an']):\n lx.add (wlist[3],'N')\n fb.addUnary ('N_'+wlist[3],wlist[0])\n else:\n lx.add (wlist[2],'A')\n fb.addUnary ('A_'+wlist[2],wlist[0])\n else:\n stem = verb_stem(wlist[1])\n if (len(wlist) == 2):\n lx.add (stem,'I')\n fb.addUnary ('I_'+stem,wlist[0])\n else:\n msg = add_proper_name (wlist[2],lx)\n if (msg == ''):\n lx.add (stem,'T')\n fb.addBinary ('T_'+stem,wlist[0],wlist[2])\n return msg\n\n# End of PART A.","sub_path":"statements.py","file_name":"statements.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"534972330","text":"import numpy as np\r\nimport pandas as pd\r\nimport PySimpleGUI as sg\r\nimport datetime as dt\r\nimport time\r\nimport threading\r\nimport traceback\r\nimport xmltodict\r\nimport urllib3\r\nfrom datetime import datetime\r\n\r\nglobal XML_m1\r\nXML_m1 = pd.DataFrame(columns=['Ask','Bid'])\r\n\r\nnow = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\r\n\r\ndef getxml():\r\n url = 'http://rates.fxcm.com/RatesXML' # define XML location\r\n\r\n http = urllib3.PoolManager()\r\n response = http.request('GET', url)\r\n try:\r\n data = xmltodict.parse(response.data)\r\n except:\r\n print('Failed')\r\n return data\r\n\r\ndef get_new_xml_data():\r\n loaded = getxml()\r\n e = loaded['Rates']['Rate'][2]\r\n global GBPUSD_Bid\r\n global GBPUSD_Ask\r\n GBPUSD_Bid = e['Bid']\r\n GBPUSD_Ask = e['Ask']\r\n now = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\r\n XML_m1.loc[now] = [GBPUSD_Bid, GBPUSD_Ask]\r\n return XML_m1\r\n\r\nsg.change_look_and_feel('Topanga')\r\n\r\nlayout = [[sg.Text('Current time: ', font='Arial 12', size=(16,2)),sg.Text(font='Arial 14', size=(30,2), key='_NOW_'), sg.Text(' '),sg.Button('Exit', size=(8,2))],\r\n\t\t[sg.Text('Live PNL: ', font='Arial 12', size=(16,2)),sg.Text(font='Arial 14', size=(30,2), key='_PNL_')],\r\n\t\t[sg.Text('Engine Status: ', font='Arial 12')], \r\n\t\t[sg.Text(size=(80,3), key='_OUTPUT1_')], \r\n\t\t[sg.Text('XML-m1 latest:', font='Arial 12')],\r\n\t\t[sg.Text(size=(80,3), key='_OUTPUT2_')],\r\n\t\t[sg.Text('Open Positions:', font='Arial 12')],\r\n\t\t[sg.Text(size=(80,5), key='_OUTPUT3_')]]\r\n\t\t\r\n\r\nwindow = sg.Window('NN_FX', layout)\r\n\r\ndef response_process():\r\n\tdf1 = pd.DataFrame()\r\n\tdf1 = pd.read_csv('C:\\\\Users\\\\GITFISHINC6\\\\AppData\\\\Roaming\\\\MetaQuotes\\\\Terminal\\\\91B85E7C52B57BF365F85A909F61CC9C\\\\MQL5\\\\Files\\\\Response.csv', index_col=None)\r\n\tdf1.to_json('Response_json.json')\r\n\r\ndef get_data():\r\n\tglobal live_status\r\n\tglobal open_pos\r\n\tglobal pnl\r\n\tlive_status = pd.read_json('live_status.json', orient='columns')\r\n\topen_pos = pd.read_json('Response_json.json', orient='columns')\r\n\tpnl = open_pos['NetProfit'].sum()\r\n\r\n\r\nget_data()\r\n\r\ndef update_data():\r\n\t\twindow['_NOW_'].update(now)\r\n\t\twindow['_PNL_'].update(pnl)\r\n\t\twindow['_OUTPUT1_'].update(live_status[0:1])\t\t\r\n\t\twindow['_OUTPUT2_'].update(XML_m1.tail(1))\r\n\t\twindow['_OUTPUT3_'].update(open_pos[:])\r\n\t\t\r\n\r\nwhile True: # Event Loop\r\n\t\r\n\ttry:\r\n\t\tget_new_xml_data()\r\n\t\tXML_m1.to_csv('XML_m1.csv', mode='a', header=False)\t\r\n\texcept:\r\n\t\tpass\r\n\t\r\n\ttry:\r\n\t\tresponse_process()\r\n\texcept:\r\n\t\tpass\r\n\r\n\ttry:\r\n\t\tget_data()\r\n\texcept:\r\n\t\tpass\r\n\r\n\ttry:\r\n\t\tupdate_data()\r\n\texcept:\r\n\t\tpass\r\n\r\n\tevent, values = window.read(timeout=1000) # can also be written as event, values = window()\r\n\tnow = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\r\n\t\r\n\r\n\tprint(event, values)\r\n\tXML_m1 = pd.DataFrame(columns=['Ask','Bid'])\r\n \r\nwindow.close()\r\n\r\n\r\n\r\n'''\r\n\r\nwhile True:\r\n\t #print(XML_m1)\r\n #time.sleep(30)\r\n for a in range(10):\r\n'''","sub_path":"SG_5.py","file_name":"SG_5.py","file_ext":"py","file_size_in_byte":2912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"599075162","text":"'''\nKeras implementation of deep embedder to improve clustering, inspired by:\n\"Unsupervised Deep Embedding for Clustering Analysis\" (Xie et al, ICML 2016)\n\nDefinition can accept somewhat custom neural networks. Defaults are from paper.\n'''\nimport sys\nimport numpy as np\nimport keras as kr\nfrom custom import ClusteringLayer\n\nfrom sklearn.utils.linear_assignment_ import linear_assignment\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import normalize\n\nimport pickle\nimport numpy as np\n\nclass DeepEmbeddingClustering(object):\n def __init__(self,n_clusters,input_dim,encoded=None,decoded=None,\n alpha=1.0,pretrained_weights=None,cluster_centers=None,\n batch_size=256,**kwargs):\n super(DeepEmbeddingClustering, self).__init__()\n self.n_clusters = n_clusters\n self.input_dim = input_dim\n self.encoded = encoded\n self.decoded = decoded\n self.alpha = alpha\n self.pretrained_weights = pretrained_weights\n self.clust_cent = cluster_centers\n self.batch_size = batch_size\n self.learning_rate = 0.1\n self.iters_lr_update = 20000\n self.lr_change_rate = 0.1\n # greedy layer-wise training before end-to-end training:\n self.encoders_dims = [self.input_dim, 500, 500, 2000, 10]\n self.input_layer = kr.layers.Input(shape=(self.input_dim,), name='input')\n dropout_fraction = 0.2\n init_stddev = 0.01\n\n self.layer_wise_autoencoders = []\n self.encoders = []\n self.decoders = []\n for i in range(1, len(self.encoders_dims)):\n if i == (len(self.encoders_dims) - 1):\n encoder_activation = 'linear'\n else:\n encoder_activation = 'relu'\n encoder = kr.layers.Dense(\n self.encoders_dims[i], \n activation=encoder_activation,\n input_shape=(self.encoders_dims[i-1],),\n kernel_initializer=kr.initializers.RandomNormal(mean=0.0, stddev=init_stddev, seed=None),\n bias_initializer='zeros', name='encoder_dense_%d'%i\n )\n self.encoders.append(encoder)\n decoder_index = len(self.encoders_dims) - i\n decoder_activation = 'linear' if i == 1 else 'relu'\n decoder = kr.layers.Dense(\n self.encoders_dims[i-1], activation=decoder_activation,\n kernel_initializer=kr.initializers.RandomNormal(mean=0.0, stddev=init_stddev, seed=None),\n bias_initializer='zeros',\n name='decoder_dense_%d'%decoder_index\n )\n self.decoders.append(decoder)\n\n autoencoder = kr.models.Sequential([\n kr.layers.Dropout(\n dropout_fraction,\n input_shape=(self.encoders_dims[i-1],),\n name='encoder_dropout_%d'%i\n ),\n encoder,\n kr.layers.Dropout(dropout_fraction,name='decoder_dropout_%d'%decoder_index),\n decoder\n ])\n autoencoder.compile(\n loss='mse',optimizer=kr.optimizers.SGD(\n lr=self.learning_rate, decay=0, momentum=0.9\n )\n )\n self.layer_wise_autoencoders.append(autoencoder)\n # build the end-to-end autoencoder for finetuning\n # Note that at this point dropout is discarded\n self.encoder = kr.models.Sequential(self.encoders)\n self.encoder.compile(\n loss='mse',\n optimizer=kr.optimizers.SGD(lr=self.learning_rate, decay=0, momentum=0.9)\n )\n self.decoders.reverse()\n self.autoencoder = kr.models.Sequential(self.encoders + self.decoders)\n self.autoencoder.compile(\n loss='mse',\n optimizer=kr.optimizers.SGD(lr=self.learning_rate, decay=0, momentum=0.9)\n )\n if cluster_centers is not None:\n assert cluster_centers.shape[0] == self.n_clusters\n assert cluster_centers.shape[1] == self.encoder.layers[-1].output_dim\n if self.pretrained_weights is not None:\n self.autoencoder.load_weights(self.pretrained_weights)\n def p_mat(self, q):\n weight = q**2 / q.sum(0)\n return (weight.T / weight.sum(1)).T\n\n def initialize_layerwise(self,X,lr_schedule,layerwise_pretrain_iters):\n iters_per_epoch = int(len(X) / self.batch_size)\n layerwise_epochs = max(int(layerwise_pretrain_iters / iters_per_epoch), 1)\n current_input = X\n AE_COUNT = len(self.layer_wise_autoencoders)\n for i, autoencoder in enumerate(self.layer_wise_autoencoders):\n if i > 0:\n print(\"training {:} of {:}\".format(i,AE_COUNT-1))\n weights = self.encoders[i-1].get_weights()\n dense_layer = kr.layers.Dense(\n self.encoders_dims[i], input_shape=(current_input.shape[1],),\n activation='relu', weights=weights,name='encoder_dense_copy_%d'%i)\n encoder_model = kr.models.Sequential([dense_layer])\n encoder_model.compile(\n loss='mse',\n optimizer=kr.optimizers.SGD(lr=self.learning_rate, decay=0, momentum=0.9))\n current_input = encoder_model.predict(current_input)\n autoencoder.fit(\n current_input, current_input,\n batch_size=self.batch_size,\n epochs=layerwise_epochs, callbacks=[lr_schedule]\n )\n w1 = autoencoder.layers[1].get_weights()\n self.autoencoder.layers[i].set_weights(w1)\n wm1 = autoencoder.layers[-1].get_weights()\n nl = len(self.autoencoder.layers)\n self.autoencoder.layers[nl-i-1].set_weights(wm1)\n\n def initialize_finetune(self,X,lr_schedule,save_autoencoder,finetune_iters):\n iters_per_epoch = int(len(X) / self.batch_size)\n finetune_epochs = max(int(finetune_iters / iters_per_epoch), 1)\n self.autoencoder.fit(X,X,batch_size=self.batch_size,epochs=finetune_epochs,callbacks=[lr_schedule])\n if save_autoencoder:\n self.autoencoder.save_weights('autoencoder.h5')\n\n def initialize(self,X,save_autoencoder=False,layerwise_pretrain_iters=50000,finetune_iters=100000):\n if self.pretrained_weights is None:\n iters_per_epoch = int(len(X) / self.batch_size)\n \n lr_epoch_update = max(1, self.iters_lr_update / float(iters_per_epoch))\n def step_decay(epoch):\n initial_rate = self.learning_rate\n factor = int(epoch / lr_epoch_update)\n lr = initial_rate / (10 ** factor)\n return lr\n lr_schedule = kr.callbacks.LearningRateScheduler(step_decay)\n \n self.initialize_layerwise(X,lr_schedule,layerwise_pretrain_iters)\n print('Finetuning autoencoder')\n self.initialize_finetune(X,lr_schedule,save_autoencoder,finetune_iters)\n else:\n print('Loading pretrained weights for autoencoder.')\n self.autoencoder.load_weights(self.pretrained_weights)\n # update encoder, decoder\n # TODO: is this needed? Might be redundant...\n for i in range(len(self.encoder.layers)):\n self.encoder.layers[i].set_weights(self.autoencoder.layers[i].get_weights())\n # initialize cluster centers using k-means\n print('Initializing cluster centers with k-means.')\n if self.clust_cent is None:\n kmeans = KMeans(n_clusters=self.n_clusters, n_init=20)\n self.y_pred = kmeans.fit_predict(self.encoder.predict(X))\n self.clust_cent = kmeans.cluster_centers_\n # prepare DEC model\n self.DEC = kr.models.Sequential(\n [\n self.encoder,\n ClusteringLayer(self.n_clusters,weights=self.clust_cent,name='clustering')\n ]\n )\n self.DEC.compile(loss='kullback_leibler_divergence', optimizer='adadelta')\n return\n def cluster_acc(self, y_true, y_pred):\n assert y_pred.size == y_true.size\n D = max(y_pred.max(), y_true.max())+1\n w = np.zeros((D, D), dtype=np.int64)\n for i in range(y_pred.size):\n w[y_pred[i], y_true[i]] += 1\n ind = linear_assignment(w.max() - w)\n return sum([w[i, j] for i, j in ind])*1.0/y_pred.size, w\n def cluster(self, X, y=None,tol=0.01, update_interval=None,iter_max=1e6,save_interval=None,**kwargs):\n if update_interval is None:\n # 1 epochs\n update_interval = X.shape[0]/self.batch_size\n print('Update interval', update_interval)\n if save_interval is None:\n # 50 epochs\n save_interval = X.shape[0]/self.batch_size*50\n print('Save interval', save_interval)\n assert save_interval >= update_interval\n train = True\n iteration, index = 0, 0\n self.accuracy = []\n num_digits = str(int(np.log10(iter_max))+1)\n fmtstr = 'Iteration {:>'+num_digits+'}, Loss {:.5}\\r'\n fmtstr1 = 'Iteration {:>'+num_digits+'}, Accuracy {:.5}'\n while train:\n #sys.stdout.write('\\r')\n # cutoff iteration\n if iter_max < iteration:\n print('Reached maximum iteration limit. Stopping training.')\n return self.y_pred\n # update (or initialize) probability distributions and propagate weight changes\n # from DEC model to encoder.\n if iteration % update_interval == 0:\n self.q = self.DEC.predict(X, verbose=0)\n self.p = self.p_mat(self.q)\n y_pred = self.q.argmax(1)\n delta_label = ((y_pred == self.y_pred).sum().astype(np.float32) / y_pred.shape[0])\n if y is not None:\n acc = self.cluster_acc(y, y_pred)[0]\n self.accuracy.append(acc)\n print(fmtstr1.format(iteration,acc))\n else:\n print('{:.5%} change in label assignments'.format(delta_label))\n #str(np.round(delta_label*100, 5))+'%% change in label assignment')\n if delta_label < tol:\n print('Reached tolerance threshold. Stopping training.')\n train = False\n continue\n else:\n self.y_pred = y_pred\n for i in range(len(self.encoder.layers)):\n self.encoder.layers[i].set_weights(\n self.DEC.layers[0].layers[i].get_weights())\n self.clust_cent = self.DEC.layers[-1].get_weights()[0]\n # train on batch\n if (index+1)*self.batch_size > X.shape[0]:\n rng = index*self.batch_size\n loss = self.DEC.train_on_batch(X[rng::],self.p[rng::])\n index = 0\n else:\n l_rng = index*self.batch_size\n r_rng = (index+1)*self.batch_size\n loss = self.DEC.train_on_batch(X[l_rng:r_rng],self.p[l_rng:r_rng])\n index += 1\n sys.stdout.write(fmtstr.format(iteration,loss))\n # save intermediate\n if iteration % save_interval == 0:\n z = self.encoder.predict(X)\n pca = PCA(n_components=2).fit(z)\n z_2d = pca.transform(z)\n clust_2d = pca.transform(self.clust_cent)\n # save states for visualization\n pickle.dump(\n {\n 'z_2d': z_2d,'clust_2d': clust_2d,\n 'q': self.q,'p': self.p,\n },open('c'+str(iteration)+'.pkl', 'wb')\n )\n # save DEC model checkpoints\n self.DEC.save('DEC_model_'+str(iteration)+'.h5')\n iteration += 1\n sys.stdout.flush()\n return\n","sub_path":"dec/dec.py","file_name":"dec.py","file_ext":"py","file_size_in_byte":10580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"192067917","text":"import json\nimport logging\n\nfrom lxml.html import fromstring, tostring\n\nfrom . import base\nfrom .base import BaseHandler, fetch_zhihu\nfrom .zhihu_stream import tidy_content, re_zhihu_img\n\npage_template = '''\\\n\n\n\n{title} - {author}\n\n

{title}

\n

作者: {author}

\n{body}\n
\n\n'''\n\nlogger = logging.getLogger(__name__)\n\nclass StaticZhihuHandler(BaseHandler):\n async def get(self, id):\n pic = self.get_argument('pic', None)\n page = await self._get_url(f'https://zhuanlan.zhihu.com/p/{id}')\n doc = fromstring(page)\n try:\n static = doc.xpath('//script[@id=\"js-initialData\"]')[0]\n except IndexError:\n logger.error('page source: %s', page)\n raise\n content = json.loads(static.text)['initialState']\n\n article = content['entities']['articles'][id]\n # used by vars()\n title = article['title']\n author = article['author']['name']\n body = article['content']\n\n doc = fromstring(body)\n body = tidy_content(doc)\n\n if pic:\n base.proxify_pic(doc, re_zhihu_img, pic)\n\n body = tostring(doc, encoding=str)\n self.set_header('Content-Type', 'text/html; charset=utf-8')\n self.finish(page_template.format_map(vars()))\n\n async def _get_url(self, url):\n res = await fetch_zhihu(url)\n return res.body.decode('utf-8')\n","sub_path":"morerss/static_zhihu.py","file_name":"static_zhihu.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"300954936","text":"import multiprocessing\nimport logging.config\nimport threading\nimport tempfile\nimport binascii\nimport retrying\nimport port_for\nimport logging\nimport pickle\nimport shutil\nimport queue\nimport etcd3\nimport time\nimport os\nimport module\n\nlogging.config.fileConfig(os.path.join(os.path.dirname(__file__), \"logging.conf\"))\nlogger = logging.getLogger(\"etcd\")\n\n\nclass _ETCDBroadcast(module.Module):\n def __init__(self, host=\"localhost\", port=\"2379\", queuesize=128):\n self.host = host\n self.port = port\n self.queuesize = queuesize\n self.queue = queue.Queue(maxsize=queuesize)\n self.cancel = None\n\n def broadcast(self, message):\n try:\n self.etcdclient.put(\"broadcast\", self._pack(message))\n except Exception as e:\n time.sleep(0.1)\n raise Exception({\"error\": \"failed to broadcast message\"})\n\n def deliver(self):\n try:\n return self.queue.get_nowait()\n except:\n raise Exception(\"nothing to deliver\")\n\n def _deliver(self, start_revision=1):\n try:\n try:\n iter, self.cancel = self.etcdclient.watch(\n \"broadcast\", start_revision=start_revision\n )\n for i, message in enumerate(iter):\n self.queue.put(self._unpack(message._event.kv.value))\n start_revision = message._event.kv.mod_revision + 1\n self.cancel()\n except etcd3.exceptions.RevisionCompactedError as e:\n iter, self.cancel = self.etcdclient.watch(\n \"broadcast\", start_revision=e.compacted_revision\n )\n for i, message in enumerate(iter):\n self.queue.put(self._unpack(message._event.kv.value))\n self.cancel()\n except etcd3.exceptions.ConnectionFailedError as e:\n time.sleep(1)\n self._deliver(start_revision=start_revision)\n\n def _start(self):\n self.etcdclient = etcd3.client(\n host=self.host,\n port=self.port,\n grpc_options={\n \"grpc.max_send_message_length\": -1,\n \"grpc.max_receive_message_length\": -1,\n }.items(),\n )\n self.etcdclient.status()\n threading.Thread(target=self._deliver, daemon=True).start()\n\n def _stop(self):\n del self.etcdclient\n\n def _create(self):\n datadir = tempfile.mkdtemp()\n self._handle_exit(lambda: shutil.rmtree(datadir, ignore_errors=True))\n self._execute_command(\n \"etcd --listen-client-urls=http://%s:%s --advertise-client-urls=http://%s:%s --data-dir=%s --listen-peer-urls=http://localhost:%s\"\n % (\n self.host,\n self.port,\n self.host,\n self.port,\n datadir,\n port_for.select_random(),\n ),\n daemon=True,\n )\n self._execute_command(\n \"etcdctl --endpoints=http://%s:%s endpoint status\" % (self.host, self.port),\n )\n\n\nclass _BatchingBroadcast(module.Module):\n def __init__(self, batchsize=128):\n self.batch = [None] * batchsize\n self.nextpos = 0\n self.batchsize = batchsize\n self.deliverbatch = [None] * batchsize\n self.delivernextpos = batchsize\n self.queue = queue.Queue(maxsize=batchsize)\n self.stop_event = threading.Event()\n\n def broadcast(self, message):\n self.batch[self.nextpos] = message\n if self.nextpos == self.batchsize - 1:\n self.southbound.broadcast(self.batch)\n self.nextpos = 0\n else:\n self.nextpos = self.nextpos + 1\n\n def deliver(self, blocking=False):\n if blocking == False:\n try:\n return self.queue.get_nowait()\n except:\n raise Exception({\"error\": \"no message to deliver\"})\n else:\n return self.queue.get()\n\n def _deliver(self):\n while not self.stop_event.is_set():\n try:\n for message in self.southbound.deliver():\n self.queue.put(message)\n except:\n pass\n\n def _start(self):\n threading.Thread(target=self._deliver, daemon=True).start()\n\n def _stop(self):\n self.stop_event.set()\n time.sleep(1)\n\n\nclass ETCD(module.Module):\n def __init__(\n self, host=None, port=None, queuesize=128, batchsize=128, create=False\n ):\n self.port = port\n self.host = host\n self.queuesize = int(queuesize)\n self.batchsize = int(batchsize)\n self.create = bool(create)\n if self.host == None:\n self.host = \"localhost\"\n if self.port == None:\n self.port = port_for.select_random()\n self.etcdbroadcast = _ETCDBroadcast(\n host=self.host, port=self.port, queuesize=self.queuesize\n )\n self.batchingbroadcast = _BatchingBroadcast(batchsize=self.batchsize)\n self.etcdbroadcast._register_northbound(self.batchingbroadcast)\n self.batchingbroadcast._register_southbound(self.etcdbroadcast)\n\n def broadcast(self, message):\n return self.batchingbroadcast.broadcast(message)\n\n def deliver(self, blocking=False):\n message = self.batchingbroadcast.deliver(blocking)\n return message\n\n def _create(self):\n if self.create:\n logger.info(\"creating etcd at %s:%s\" % (self.host, self.port))\n self.etcdbroadcast._create()\n self.batchingbroadcast._create()\n logger.info(\"finished creating etcd at %s:%s\" % (self.host, self.port))\n\n def _uncreate(self):\n if self.create:\n logger.info(\"uncreating etcd\")\n self.batchingbroadcast._uncreate()\n self.etcdbroadcast._uncreate()\n\n def _start(self):\n logger.info(\"starting etcd at %s:%s\" % (self.host, self.port))\n self.etcdbroadcast._start()\n self.batchingbroadcast._start()\n logger.info(\"finished starting etcd at %s:%s\" % (self.host, self.port))\n\n def _stop(self):\n logger.info(\"stopping etcd\")\n self.batchingbroadcast._stop()\n self.etcdbroadcast._stop()\n","sub_path":"src/etcd.py","file_name":"etcd.py","file_ext":"py","file_size_in_byte":6237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"213713288","text":"# uncompyle6 version 3.6.7\n# Python bytecode 3.5 (3351)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/pyams_form/term.py\n# Compiled at: 2020-02-23 12:53:51\n# Size of source mod 2**32: 12013 bytes\n__doc__ = \"PyAMS_form.term module\\n\\nTerms management module.\\n\\nNote: This module doesn't use snake_case for compatibility purposes with zope.schema package,\\nwhich implies many Pylint annotations...\\n\"\nfrom zope.interface import Interface\nfrom zope.schema.interfaces import IBaseVocabulary, IBool, IChoice, ICollection, IIterableSource\nfrom zope.schema.vocabulary import SimpleTerm, SimpleVocabulary\nfrom pyams_form.interfaces import IBoolTerms, ITerms, IVocabularyTerms\nfrom pyams_form.interfaces.form import IContextAware\nfrom pyams_form.interfaces.widget import IWidget\nfrom pyams_form.util import create_css_id, to_unicode\nfrom pyams_layer.interfaces import IFormLayer\nfrom pyams_utils.adapter import adapter_config\nfrom pyams_utils.interfaces.form import IDataManager\n__docformat__ = 'restructuredtext'\nfrom pyams_form import _\n\nclass Terms:\n \"\"\"Terms\"\"\"\n terms = None\n\n def getTerm(self, value):\n \"\"\"Get term matching given value\"\"\"\n return self.terms.getTerm(value)\n\n def getTermByToken(self, token):\n \"\"\"Get term matching given token\"\"\"\n return self.terms.getTermByToken(token)\n\n def getValue(self, token):\n \"\"\"Get value matching given token\"\"\"\n return self.getTermByToken(token).value\n\n def __iter__(self):\n return iter(self.terms)\n\n def __len__(self):\n return self.terms.__len__()\n\n def __contains__(self, value):\n return self.terms.__contains__(value)\n\n\nclass SourceTerms(Terms):\n \"\"\"SourceTerms\"\"\"\n\n def __init__(self, context, request, form, field, source, widget):\n self.context = context\n self.request = request\n self.form = form\n self.field = field\n self.widget = widget\n self.source = source\n self.terms = request.registry.getMultiAdapter((self.source, self.request), IVocabularyTerms)\n\n def getTerm(self, value):\n try:\n return super(SourceTerms, self).getTerm(value)\n except KeyError:\n raise LookupError(value)\n\n def getTermByToken(self, token):\n for value in self.source:\n term = self.getTerm(value)\n if term.token == token:\n return term\n\n raise LookupError(token)\n\n def getValue(self, token):\n try:\n return self.terms.getValue(token)\n except KeyError:\n raise LookupError(token)\n\n def __iter__(self):\n for value in self.source:\n yield self.terms.getTerm(value)\n\n def __len__(self):\n return len(self.source)\n\n def __contains__(self, value):\n return value in self.source\n\n\n@adapter_config(required=(Interface, IFormLayer, Interface, IChoice, IWidget), provides=ITerms)\ndef ChoiceTerms(context, request, form, field, widget):\n \"\"\"Choice terms adapter\"\"\"\n if field.context is None:\n field = field.bind(context)\n terms = field.vocabulary\n return request.registry.queryMultiAdapter((context, request, form, field, terms, widget), ITerms)\n\n\n@adapter_config(required=(Interface, IFormLayer, Interface, IChoice, IBaseVocabulary, IWidget), provides=ITerms)\nclass ChoiceTermsVocabulary(Terms):\n \"\"\"ChoiceTermsVocabulary\"\"\"\n\n def __init__(self, context, request, form, field, vocabulary, widget):\n self.context = context\n self.request = request\n self.form = form\n self.field = field\n self.widget = widget\n self.terms = vocabulary\n\n\nclass MissingTermsBase:\n \"\"\"MissingTermsBase\"\"\"\n\n def _can_query_current_value(self):\n return IContextAware.providedBy(self.widget) and not self.widget.ignore_context\n\n def _query_current_value(self):\n return self.request.registry.getMultiAdapter((self.widget.context, self.field), IDataManager).query()\n\n @staticmethod\n def _make_token(value):\n \"\"\"create a unique valid ASCII token\"\"\"\n return create_css_id(to_unicode(value))\n\n def _make_missing_term(self, value):\n \"\"\"Return a term that should be displayed for the missing token\"\"\"\n uvalue = to_unicode(value)\n return SimpleTerm(value, self._make_token(value), title=_('Missing: ${value}', mapping=dict(value=uvalue)))\n\n\nclass MissingTermsMixin(MissingTermsBase):\n \"\"\"MissingTermsMixin\"\"\"\n\n def getTerm(self, value):\n \"\"\"Get term martching given value\"\"\"\n try:\n return super(MissingTermsMixin, self).getTerm(value)\n except LookupError:\n if self._can_query_current_value():\n cur_value = self._query_current_value()\n if cur_value == value:\n pass\n return self._make_missing_term(value)\n raise\n\n def getTermByToken(self, token):\n \"\"\"Get term matching given token\"\"\"\n try:\n return super(MissingTermsMixin, self).getTermByToken(token)\n except LookupError:\n if self._can_query_current_value():\n value = self._query_current_value()\n term = self._make_missing_term(value)\n if term.token == token:\n pass\n return term\n raise LookupError(token)\n\n\n@adapter_config(required=(Interface, IFormLayer, Interface, IChoice, IBaseVocabulary, IWidget), provides=ITerms)\nclass MissingChoiceTermsVocabulary(MissingTermsMixin, ChoiceTermsVocabulary):\n \"\"\"MissingChoiceTermsVocabulary\"\"\"\n pass\n\n\n@adapter_config(required=(Interface, IFormLayer, Interface, IChoice, IIterableSource, IWidget), provides=ITerms)\nclass ChoiceTermsSource(SourceTerms):\n \"\"\"ChoiceTermsSource\"\"\"\n pass\n\n\n@adapter_config(required=(Interface, IFormLayer, Interface, IChoice, IIterableSource, IWidget), provides=ITerms)\nclass MissingChoiceTermsSource(MissingTermsMixin, ChoiceTermsSource):\n \"\"\"MissingChoiceTermsSource\"\"\"\n pass\n\n\n@adapter_config(required=(Interface, IFormLayer, Interface, IBool, IWidget), provides=IBoolTerms)\nclass BoolTerms(Terms):\n \"\"\"BoolTerms\"\"\"\n true_label = _('yes')\n false_label = _('no')\n\n def __init__(self, context, request, form, field, widget):\n self.context = context\n self.request = request\n self.form = form\n self.field = field\n self.widget = widget\n terms = [SimpleTerm(*args) for args in [(True, 'true', self.true_label),\n (\n False, 'false', self.false_label)]]\n self.terms = SimpleVocabulary(terms)\n\n\n@adapter_config(required=(Interface, IFormLayer, Interface, ICollection, IWidget), provides=ITerms)\ndef CollectionTerms(context, request, form, field, widget):\n \"\"\"Collection terms adapter\"\"\"\n terms = field.value_type.bind(context).vocabulary\n return request.registry.queryMultiAdapter((context, request, form, field, terms, widget), ITerms)\n\n\n@adapter_config(required=(Interface, IFormLayer, Interface, ICollection, IBaseVocabulary, IWidget), provides=ITerms)\nclass CollectionTermsVocabulary(Terms):\n \"\"\"CollectionTermsVocabulary\"\"\"\n\n def __init__(self, context, request, form, field, vocabulary, widget):\n self.context = context\n self.request = request\n self.form = form\n self.field = field\n self.widget = widget\n self.terms = vocabulary\n\n\nclass MissingCollectionTermsMixin(MissingTermsBase):\n \"\"\"MissingCollectionTermsMixin\"\"\"\n\n def getTerm(self, value):\n \"\"\"Get term matching given value\"\"\"\n try:\n return super(MissingCollectionTermsMixin, self).getTerm(value)\n except LookupError:\n if self._can_query_current_value() and value in self._query_current_value():\n return self._make_missing_term(value)\n raise\n\n def getTermByToken(self, token):\n \"\"\"Get term matching given token\"\"\"\n try:\n return super(MissingCollectionTermsMixin, self).getTermByToken(token)\n except LookupError:\n if self._can_query_current_value():\n for value in self._query_current_value():\n term = self._make_missing_term(value)\n if term.token == token:\n return term\n\n raise\n\n def getValue(self, token):\n \"\"\"Get value matching given token\"\"\"\n try:\n return super(MissingCollectionTermsMixin, self).getValue(token)\n except LookupError:\n if self._can_query_current_value():\n for value in self._query_current_value():\n term = self._make_missing_term(value)\n if term.token == token:\n return value\n\n raise\n\n\nclass MissingCollectionTermsVocabulary(MissingCollectionTermsMixin, CollectionTermsVocabulary):\n \"\"\"MissingCollectionTermsVocabulary\"\"\"\n pass\n\n\n@adapter_config(required=(Interface, IFormLayer, Interface, ICollection, IIterableSource, IWidget), provides=ITerms)\nclass CollectionTermsSource(SourceTerms):\n \"\"\"CollectionTermsSource\"\"\"\n pass\n\n\nclass MissingCollectionTermsSource(MissingCollectionTermsMixin, CollectionTermsSource):\n \"\"\"MissingCollectionTermsSource\"\"\"\n pass","sub_path":"pycfiles/pyamtrack-0.1.4-py3-none-manylinux1_x86_64/term.cpython-35.py","file_name":"term.cpython-35.py","file_ext":"py","file_size_in_byte":9346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"120009504","text":"import csv\n\nfrom pymongo import MongoClient\nfrom bson import ObjectId\n\ncsv_filename = 'kdi-local-elections-observations-first-round-2013.csv'\n\n# Connect to default local instance of mongo\nclient = MongoClient()\n\n# Get database and collection\ndb = client.kdi\ncollection = db.localelectionsfirstround2013\n\n# Clear data\ncollection.remove({})\n\ndef parse_csv():\n\t'''\n\tReads the KDI local election monitoring CSV file.\n\tCreates Mongo document for each observation entry.\n\tStores generated JSON documents.\n\t'''\n\twith open(csv_filename, 'rb') as csvfile:\n\t\treader = csv.reader(csvfile)\n\t\t\n\t\t# Skip the header\n\t\tnext(reader, None)\n\t\t\n\t\t# Iterate through the rows, retrieve desired values.\n\t\tfor row in reader:\n\t\t\t# POLLING STATION\n\t\t\tpolling_station_number = row[3].lower() # Column name: nrQV\n\t\t\troom_number = row[4] # Column name: NRVV\n\t\t\t\n\t\t\tcommune = row[5] # Column name: Komuna\n\t\t\tpolling_station_name = row[6] # Column name: EQV\n\t\t\t\n\t\t\t# ARRIVAL TIME\n\t\t\tarrival_time = row[9] # column name: P01KA\n\t\t\thow_to_vote_info = row[10] # column name: P02A\n\t\t\tlist_of_candidates = row[11] # column name: P02B\n\t\t\twhen_preparation_start = row[12] # column name:P03Perg\n\t\t\tnumber_KVV_members = row[13] #column name:P04KVV\n\t\t\tfemale = row[14] #column name:P04Fem\n\t\t\tUV_lamp = row[15] #column name:P05Lla\n\t\t\tspray = row[16] # column name:P05Ngj\n\t\t\tvoters_list = row[17] # column name:P05Lis\n\t\t\tballots = row[18] # column name:P05Flv\t\n\t\t\tstamp = row[19] # column name:P05Vul\n\t\t\tballot_box = row[20] # column name:P05Kut\n\t\t\tvoters_book = row[21] # column name:P05Lib\n\t\t\tvoting_cabin = row[22] # column name:P05Kab\n\t\t\tenvelops_condition_voters = row[23] # column name:P05ZFK\n\t\t\tnumber_of_accepted_ballots = row[24] # column name:P06NFP\n\t\t\tnumber_of_voters_in_voting_station_list = row[25] # column name: P07VNL\n\t\t\tnumber_of_voting_cabins=row[26] # column name:P08NKV\n\t\t\tvotingbox_shown_empty=row[27] # column name:P09TKZ\n\t\t\tclosed_with_safetystrip = row[28] # column name:P10SHS\n\t\t\tdid_they_register_serial_number_of_strips = row[29] # column name:P11NRS\n\t\t\tcabins_provided_voters_safety_and_privancy = row[30] # column name:P12KFV\n\n\t\n\n\t\t\t# VOTING MATERIAL\n\t\t\tmaterial_left_behind = row[7] # Column name: 01gja\n\t\t\thave_physical_access = row[8] # Column name: 02gja\n\t\t\t\n\t\t\t# VOTER INFORMATION\n\t\t\tultra_violet_control = row[45] # Column name: PV03UVL\n\t\t\tidentified_with_document = row[46] # Column name: PV04IDK\n\t\t\tfinger_sprayed = row[47] # Column name: PV05GSH\n\t\t\tsealed_ballot = row[48] # Column name: PV06VUL\n\t\t\t\n\t\t\thow_many_voted_by_ten_AM = row[49] # Column name: PV07-10\n\t\t\thow_many_voted_by_one_PM = row[50] # Column name: PV07-13\n\t\t\thow_many_voted_by_four_PM = row[51] # Column name: PV07-16\n\t\t\thow_many_voted_by_seven_PM = row[52] # Column name: PV07-19\n\t\t\t\n\t\t\t# IRREGULARITY AND COMPLAINTS\n\t\t\tattempt_to_vote_moreThanOnce=row[60] #Column name: PA01x1\n\t\t\tallowed_to_vote=row[61] #Column name: PA01ifPO\n\t\t\ttake_picture_ofballot=row[62] #Column name: PA02Fot\n\t\t\tinserted_more_than_one_ballot_in_the_box=row[63] #Column name: PA03M1F\n\t\t\tunauthorized_persons_stayed_at_the_voting_station=row[64] #Column name: PA04PPD\n\t\t\tviolence_in_the_voting_station=row[65] #Column name: PA05DHU\n\t\t\tpolitic_propaganda_inside_the_voting_station=row[66] #Column name: PA06PRP\n\t\t\tmore_than_one_person_behind_the_cabin=row[67] #Column name: PA07M1P\n\t\t\thas_the_voting_station_been_closed_in_any_case=row[68] #Column name: PA08MBV\n\t\t\tcase_voting_outside_the_cabin=row[69] #Column name: PA09VJK\n\t\t\thow_many_voters_complained_during_the_process=row[70] #Column name: PA10VAV\n\t\t\thow_many_voters_filled_the_complaints_form=row[71] #Column name: PA11VMF\n\t\t\tany_accident_happened_during_the_process=row[72] #Column name: PA12PAA\t\n\t\t\t\n\t\t\t# BALLOTS - MUNICIPAL ASSEMBLY ELECTIONS\n\t\t\ttotal_ballots_mae = row[101] # PAK01\n\t\t\tinvalid_ballots_in_box_mae = row[102] # PAK02\n\t\t\tballots_set_aside_mae = row[103] # PAK03\n\t\t\t# something = row[104] # PAK04\n\t\t\t\t\n\t\t\t# BALLOTS - MAYOR ELECTIONS\n\t\t\ttotal_ballots_me = row[105] # PKK01\n\t\t\tinvalid_ballots_in_box_me = row[106] # PKK02\n\t\t\tballots_set_aside_me = row[107] # PKK03\n\t\t\tbollots_put_in_transaparent_bag = row[108] # PKK04\n\t\t\t\n\t\t\t# TODO: Figure out if invalid_ballots_in_box_xxx and ballots_set_aside_xxx are redundant.\n\t\t\t# If invalid_ballots_in_box_xxx and ballots_set_aside_xxx refer to the same thing then we only need to count (invalid_ballots_in_box_xxx) and not the flag (ballots_set_aside_xxx)\n\t\t\t\n\t\t\t#FIXME: When dealing with numbers, set in document as int instead of string.\n\t\t\t#FIXME: Translate PO/YO to True/False boolean values.\n\t\t\t#FIXME: Translate mutlti-choice values to english (e.g. Gjithmone to Always)\n\t\t\t\n\t\t\tobservation = {\n\t\t\t\t'_id': str(ObjectId()),\n\t\t\t\t'pollingStation':{\n\t\t\t\t\t'number': polling_station_number,\n\t\t\t\t\t'roomNumber': room_number,\n\t\t\t\t\t'name': polling_station_name,\n\t\t\t\t\t'commune': commune\n\t\t\t\t},\n\t\t\t\t'onArrival':{\n\t\t\t\t\t'materialLeftBehind': to_boolean(material_left_behind),\n\t\t\t\t\t'havePhysicalAccess': to_boolean(have_physical_access)\n\t\t\t\t},\n\t\t\t\t'preparation':{\n\t\t\t\t\t'arrivalTime': arrival_time,\n\t\t\t\t\t'votingMaterialsPlacedInAndOutVotingStation':{\n\t\t\t\t\t\t'howToVoteInfo': to_boolean(how_to_vote_info),\n\t\t\t\t\t\t'listOfCandidates': to_boolean(list_of_candidates), \n\t\t\t\t\t\t'whenPreparationStarted': when_preparation_start,\n\t\t\t\t\t\t'kvvMembers':{\n\t\t\t\t\t\t\t'total': to_num(number_KVV_members), \n\t\t\t\t\t\t\t'female': to_num(female) \n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t'missingMaterial':{\n\t\t\t\t\t'uvLamp': to_boolean(UV_lamp), \n\t\t\t\t\t'spray':to_boolean( spray), \n\t\t\t\t\t'votersList': to_boolean(voters_list),\n\t\t\t\t\t'ballots': to_boolean(ballots),\t\n\t\t\t\t\t'stamp': to_boolean(stamp),\n\t\t\t\t\t'ballotBox':to_boolean(ballot_box),\n\t\t\t\t\t'votersBook': to_boolean(voters_book),\n\t\t\t\t\t'votingCabin': to_boolean(voting_cabin), \n\t\t\t\t\t'envelopsForConditionVoters': to_boolean(envelops_condition_voters),\n\t\t\t\t},\n\t\t\t\t'numberOfAcceptedBallots': to_num(number_of_accepted_ballots), \n\t\t\t\t'numberOfVotersInVotingStationList':to_num(number_of_voters_in_voting_station_list),\n\t\t\t\t'numberOfVotingCabins':to_num(number_of_voting_cabins),\n\t\t\t\t'votingBoxShownAsEmpty': to_boolean(votingbox_shown_empty),\n\t\t\t\t'closedWithSafetyStrip':to_boolean( closed_with_safetystrip), \n\t\t\t\t'registeredStrips': to_boolean(did_they_register_serial_number_of_strips), \n\t\t\t\t'cabinsSafetyAndPrivacy': to_boolean(cabins_provided_voters_safety_and_privancy),\n\t\t\t\t},\n\t\t\t\t'votingProcess':{\n\t\t\t\t\t'voters':{\n\t\t\t\t\t\t'ultraVioletControl': translate_frequency(ultra_violet_control),\n\t\t\t\t\t\t'identifiedWithDocument': translate_frequency(identified_with_document),\n\t\t\t\t\t\t'fingerSprayed': translate_frequency(finger_sprayed),\n\t\t\t\t\t\t'sealedBallot': to_num(sealed_ballot),\n\t\t\t\t\t\t'howManyVotedBy':{\n\t\t\t\t\t\t\t'tenAM': to_num(how_many_voted_by_ten_AM),\n\t\t\t\t\t\t\t'onePM': to_num(how_many_voted_by_one_PM),\n\t\t\t\t\t\t\t'fourPM': to_num(how_many_voted_by_four_PM),\n\t\t\t\t\t\t\t'sevenPM': to_num(how_many_voted_by_seven_PM)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t'irregularities':{\n\t\t\t\t\t'attemptToVoteMoreThanOnce':to_boolean(attempt_to_vote_moreThanOnce),\n\t\t\t\t\t'allowedToVote':to_boolean(allowed_to_vote),\n\t\t\t\t\t'photographedBallot':to_boolean(take_picture_ofballot),\n\t\t\t\t\t'insertedMoreThanOneBallot':to_boolean(inserted_more_than_one_ballot_in_the_box),\n\t\t\t\t \t'unauthorizedPersonsStayedAtTheVotingStation':to_boolean(unauthorized_persons_stayed_at_the_voting_station),\n\t\t\t\t\t'violenceInTheVotingStation':to_boolean(violence_in_the_voting_station),\n\t\t\t\t\t'politicalPropagandaInsideTheVotingStation':to_boolean(politic_propaganda_inside_the_voting_station),\n\t\t\t\t\t'moreThanOnePersonBehindTheCabin':to_boolean(more_than_one_person_behind_the_cabin),\n\t\t\t\t\t'hasTheVotingStationBeenClosedInAnyCase':to_boolean(has_the_voting_station_been_closed_in_any_case),\n\t\t\t\t\t'caseVotingOutsideTheCabin':to_num(case_voting_outside_the_cabin),\n\t\t\t\t\t'anyAccidentHappenedDuringTheProcess':to_boolean(any_accident_happened_during_the_process)\n\t\t\t\t},\t\t\t\t\t\n\t\t\t\t'complaints':{\n\t\t\t\t\t'total':to_num(how_many_voters_complained_during_the_process),\n\t\t\t\t\t'filed':how_many_voters_filled_the_complaints_form\t#FIXME: This is meant to be a number but instead it's a frequency term.\n\t\t\t\t},\n\t\t\t\t'ballots':{\n\t\t\t\t\t'municipalAssembly':{\n\t\t\t\t\t\t'total': to_num(total_ballots_mae),\n\t\t\t\t\t\t'invalid':{\n\t\t\t\t\t\t\t'inBallotBox': to_num(invalid_ballots_in_box_mae),\n\t\t\t\t\t\t\t'setAside': to_boolean(ballots_set_aside_mae)\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\t'mayoral':{\n\t\t\t\t\t\t'total': to_num(total_ballots_me),\n\t\t\t\t\t\t'invalid':{\n\t\t\t\t\t\t\t'inBallotBox': to_num(invalid_ballots_in_box_me),\n\t\t\t\t\t\t\t'setAside': to_boolean(ballots_set_aside_me)\n\t\t\t\t\t\t},\n\t\t\t\t\t\t'putInTransparentBag': to_boolean(bollots_put_in_transaparent_bag)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} \n\t\t\t\n\t\t\t# Insert document\n\t\t\tcollection.insert(observation)\n\ndef to_boolean(arg):\n\t''' Converting string to boolean\n\t:param arg: string argument to convert to boolean \n\t'''\n\tif arg == \"PO\" or arg == \"TRUE\":\n\t\treturn True\n\telif arg == \"JO\" or arg == \"FALSE\":\n\t\treturn False \n\telse:\n\t\treturn arg\n\t\t\n\ndef to_num(s):\n\t''' Converting string to integer\n\t:param arg: string argument to convert to integer\n\t'''\n\ttry:\n\t\treturn int(s)\n\texcept ValueError:\n\t\ttry:\n\t\t\treturn float(s)\n\t\texcept:\n\t\t\treturn s\n \n \ndef translate_frequency(term):\n\t''' Translate frequence term into english. e.g. 'Gjithmone' is 'always'\n\t'''\n\t# Use startswith because we don't want to deal with encoding issues (e umlaut).\n\t# There is probably a more elegant way to deal with this.\n\tif term.startswith('Gjithmon'):\n\t\treturn 'always'\n\telse:\n\t\treturn term\n\t#TODO: Cover the other terms\n\n\nparse_csv()\t\n","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":9437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"226312477","text":"from django.conf.urls import url\nfrom hollywood_videos import views\nurlpatterns = [\n url(r'^page/(?P[\\d]+)/$', views.index, name='index'),\n url(r'^hollywood_movie/(?P[\\w\\-]+)/$', views.videopage, name='videopage'),\n url(r'^filteredCategory/(?P[\\w\\-]+)/(?P[\\w\\-]+)/page/(?P[\\d]+)$', views.filterbyitem, name='filterbyitem'),\n url(r'^SearchContent/$', views.search_page, name='search_page'),\n url(r'^like_dislike/(?P[\\w\\-]+)/(?P[\\w\\-]+)/$', views.like_dislike, name='like_dislike'),\n url(r'^see/(?P[\\w\\-]+)/$', views.see, name='see'),\n\n]\n","sub_path":"hollywood_videos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"289646994","text":"\ndef eval_sarcopenia(clf, X, gender, height_squared, sarcopenia_ground_truth):\n asm_predicted = clf.predict(X)\n asm = asm_predicted\n gender = gender\n h2 = height_squared\n ground_truth = sarcopenia_ground_truth\n asm_over_h2 = asm / h2\n sarcopenia = []\n num_patients = len(asm_predicted)\n assert len(gender) == num_patients\n assert len(ground_truth) == num_patients\n assert len(h2) == num_patients\n\n for i in range(num_patients):\n if((asm_over_h2[i] - 7.0) < 0.0001 and gender[i] == 1):\n sarcopenia.append(1)\n elif((asm_over_h2[i] - 5.4) < 0.0001 and gender[i] == 2):\n sarcopenia.append(1)\n else:\n sarcopenia.append(-1)\n return sarcopenia\n\ndef observe_prediction_SVR(clf, X, y, patient_id, dont_show=True):\n y_predict = clf.predict(X)\n diff = (y_predict - y) / y\n patient_id = patient_id\n diff_percent = diff * 100\n num_examples = len(y)\n if not dont_show:\n for i in range(num_examples):\n if(np.abs(diff_percent[i])>5):\n print(\"Truth: %.2f, Predicted: %.2f, Error: %6.2f%%, patient_id: %3d\" %(y[i], y_predict[i], diff_percent[i], patient_id[i]))\n return diff\n\n\ndef test(show=False):\n #total = 0.0\n net.eval()\n test_loss = 0.0\n with torch.no_grad():\n for data in val_loader:\n inputs, targets = data['X'], data['asm_h2']\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = net(inputs).reshape(-1)\n if show:\n print(outputs)\n print(targets)\n #err = outputs - labels\n #print(err)\n loss_fn = nn.MSELoss()\n test_loss = loss_fn(outputs.data, targets.data)\n #total += torch.sum(abs(err))\n\n\n print(\"Test loss: %.8f\" % test_loss)\ntest(True)\n","sub_path":"utils/backup.py","file_name":"backup.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"60155182","text":"\"\"\"\nControlState - Control State Machine Class\n\nAuthor: Chris Ford \n\"\"\"\n\nclass ControlState(object):\n\n def __init__(self, key):\n self._key = key\n self._transition_dict = {}\n\n def __repr__(self): return self.__str__()\n\n def __str__(self): return self._key.decode()\n\n def key(self): return self._key\n\n def register(self, transition_dict):\n self._transition_dict = transition_dict\n\n def on_transition(self, transition):\n\n # In case the transition func is not found, or it returns False,\n # return the current state: self.\n retval = self\n\n if transition in self._transition_dict:\n dofunc, nextstate = self._transition_dict[transition]\n if dofunc():\n # Transition func returned True -- return new state\n retval = nextstate\n return retval\n\n\nclass StateMachine(object):\n\n def __init__(self):\n\n # Start with a default state.\n # (Subclasses should override this method)\n self._state = ControlState(b'DEFAULT')\n\n def on_transition(self, transition):\n # The next state will be the result of the on_transition function.\n self._state = self._state.on_transition(transition)\n\n def state(self):\n return self._state\n\n\nclass TestStateMachine(StateMachine):\n\n # Define transitions\n\n transition_configure = b'CONFIGURE'\n transition_unconfigure = b'UNCONFIGURE'\n transition_beginrun = b'BEGINRUN'\n transition_endrun = b'ENDRUN'\n transition_enable = b'ENABLE'\n transition_disable = b'DISABLE'\n\n # Define states\n\n state_unconfigured = ControlState(b'UNCONFIGURED')\n state_configured = ControlState(b'CONFIGURED')\n state_running = ControlState(b'RUNNING')\n state_enabled = ControlState(b'ENABLED')\n\n def __init__(self):\n\n # register callbacks for each valid state+transition combination\n\n unconfigured_dict = {\n self.transition_configure: (self.configfunc, self.state_configured)\n }\n\n configured_dict = {\n self.transition_unconfigure: (self.unconfigfunc,\n self.state_unconfigured),\n self.transition_beginrun: (self.beginrunfunc, self.state_running)\n }\n\n running_dict = {\n self.transition_endrun: (self.endrunfunc, self.state_configured),\n self.transition_enable: (self.enablefunc, self.state_enabled)\n }\n\n enabled_dict = {\n self.transition_disable: (self.disablefunc, self.state_running)\n }\n\n self.state_unconfigured.register(unconfigured_dict)\n self.state_configured.register(configured_dict)\n self.state_running.register(running_dict)\n self.state_enabled.register(enabled_dict)\n\n # Start with a default state.\n self._state = self.state_unconfigured\n\n def configfunc(self):\n print (\"Running configfunc()\")\n return True\n\n def unconfigfunc(self):\n print (\"Running unconfigfunc()\")\n return True\n\n def beginrunfunc(self):\n print (\"Running beginrunfunc()\")\n return True\n\n def endrunfunc(self):\n print (\"Running endrunfunc()\")\n return True\n\n def enablefunc(self):\n print (\"Running enablefunc()\")\n return True\n\n def disablefunc(self):\n print (\"Running disablefunc()\")\n return True\n\n\ndef test():\n\n # ControlState tests\n\n test_key = b'LIME'\n ww = ControlState(test_key)\n assert(ww.key() == test_key)\n\n xx = ww.on_transition(b'TEST')\n assert(ww == xx)\n\n print(\"ControlState OK\")\n\n # TestStateMachine tests\n\n yy = TestStateMachine()\n print(\"TestStateMachine state:\", yy.state())\n assert(yy.state() == yy.state_unconfigured)\n\n yy.on_transition(yy.transition_configure)\n print(\"TestStateMachine state:\", yy.state())\n assert(yy.state() == yy.state_configured)\n\n yy.on_transition(yy.transition_beginrun)\n print(\"TestStateMachine state:\", yy.state())\n assert(yy.state() == yy.state_running)\n\n yy.on_transition(yy.transition_enable)\n print(\"TestStateMachine state:\", yy.state())\n assert(yy.state() == yy.state_enabled)\n\n yy.on_transition(yy.transition_disable)\n print(\"TestStateMachine state:\", yy.state())\n assert(yy.state() == yy.state_running)\n\n yy.on_transition(yy.transition_endrun)\n print(\"TestStateMachine state:\", yy.state())\n assert(yy.state() == yy.state_configured)\n\n yy.on_transition(yy.transition_unconfigure)\n print(\"TestStateMachine state:\", yy.state())\n assert(yy.state() == yy.state_unconfigured)\n\n print(\"TestStateMachine OK\")\n\n return\n\nif __name__ == '__main__':\n test()\n","sub_path":"psdaq/pydaq/ControlState.py","file_name":"ControlState.py","file_ext":"py","file_size_in_byte":4700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"212664133","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jul 4 20:42:38 2016\r\n\r\n@author: SRINIVAS\r\n\"\"\"\r\nimport nltk\r\nfrom nltk.corpus import words\r\nimport itertools\r\npie=input('letters')\r\nfi=len(list(pie))\r\n\r\norca=list(itertools.permutations(list(pie), fi))\r\nfor elem in orca:\r\n \r\n leter=''.join(elem)\r\n \r\n \r\n if leter in words.words():\r\n print(leter)\r\n\r\n","sub_path":"letterpad.py","file_name":"letterpad.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"126174966","text":"#2 stack 1 array\nclass twostack:\n def __init__(self,k,n):\n self.n=n\n self.k=k\n self.top=[-1]*self.k\n self.arr=[0]*self.n\n self.next=[i for i in range(1,self.n)]\n self.next.append(-1)\n # Top of the free stack. \n self.free = 0\n # Check whether given stack is empty. \n def isEmpty(self, sn): \n return self.top[sn] == -1\n \n # Check whether there is space left for \n # pushing new elements or not. \n def isFull(self): \n return self.free == -1\n\n\n def insert(self,val,sn):\n if (self.isFull()):\n print(\"stackoverflow\")\n i=self.free\n self.free=self.next[i] \n self.arr[i]=val\n self.next[i]=self.top[sn]\n self.top[sn]=i \n def remove(self,sn):\n if self.isEmpty(sn): \n return None\n top_stack=self.top[sn]\n self.top[sn]=self.next[self.top[sn]]\n self.next[top_stack]=self.free \n self.free=top_stack \n for i in self.next:\n print(i,end=\" \");\n return self.arr[top_stack]\n\n def printarray(self):\n \t\tfor i in self.arr:\n \t\t\tprint(i,end=\" \");\n \n\n\n\ndef main():\n print(\"Enter the array size\")\n sz=int(input())\n print(\"Enter the number of linked list you want to implement\")\n k=int(input())\n st=twostack(k,sz)\n while True:\n print(\"Press1 to insert in array\")\n print(\"Press2 to pop from array\")\n print(\"Press3 to exit\")\n i=int(input())\n if(i==1):\n print(\"Enter element and stack no in which u want to insert\")\n n=int(input())\n k=int(input())\n st.insert(n,k-1)\n st.printarray()\n if(i==2):\n print(\"Enter stack no from which u want to remove\")\n k=int(input())\n print(st.remove(k-1))\n st.printarray()\n if(i==3):\n return\t\n\n\nif __name__ == '__main__':\n main()","sub_path":"Stack&Queue/KStackArray.py","file_name":"KStackArray.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"148008812","text":"from pyspark import SparkConf, SparkContext\n\ndef loadMovieNames():\n movieNames = {}\n skip_first = True\n with open(\"movies.csv\") as f:\n for line in f:\n if skip_first:\n skip_first = False\n continue\n fields = line.split(\",\")\n movieNames[int(fields[0])] = fields[1].decode('ascii', 'ignore')\n return movieNames\n\ndef map1(movie_list):\n list = []\n movie_dict = {}\n l = len(movie_list)\n movie_list = map(int, movie_list)\n movie_list = sorted(movie_list)\n for i in range(l - 1):\n for j in range(i + 1, l):\n if movie_list[j] in movie_dict:\n movie_dict[movie_list[j]] += 1\n else:\n movie_dict[movie_list[j]] = 1\n list.append([movie_list[i], movie_dict])\n movie_dict = {}\n return list\n\ndef reduce1(movie_dic, data):\n all_movies = data\n movie_dict = movie_dic\n for movie in all_movies:\n if movie in movie_dict:\n movie_dict[movie] += all_movies[movie]\n else:\n movie_dict[movie] = all_movies[movie]\n return movie_dict\n\ndef map2(data):\n movie1, movie_dict = data\n list = []\n mcount = 0\n for movie in movie_dict:\n mcount += movie_dict[movie]\n for movie in movie_dict:\n cond_prob = float(movie_dict[movie])/float(mcount)\n if cond_prob > 0.8:\n list.append(movieNameDictionary[movie1] +\",\"+ movieNameDictionary[movie] +\",\"+ str(cond_prob))\n return list\n\nconf = SparkConf().setMaster(\"local[*]\").setAppName(\"Frequent_Stripes\")\nsc = SparkContext(conf=conf)\n\ntext_file = sc.textFile(\"ratings.csv\")\nmovieNameDictionary = loadMovieNames()\nout1 = text_file.map(lambda line: line.strip().split(\",\")).zipWithIndex().filter(lambda tup: tup[1] > 1).map(lambda x:x[0])\nout2 = out1.filter(lambda a: float(a[2]) >= 4.0)\nout3 = out2.map(lambda a: (a[0], a[1])).reduceByKey(lambda x, y: x + ',' + y).map(lambda x: x[1])\nout4 = out3.map(lambda line: line.strip().split(\",\")).flatMap(map1)\nout5 = out4.reduceByKey(reduce1, numPartitions=16)\nout6 = out5.flatMap(map2)\nout6.sample(False, 20).saveAsTextFile(\"spark_output/cond_prob/100p\")","sub_path":"SourceCode/Spark Conditional Probability.py","file_name":"Spark Conditional Probability.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"246581580","text":"#!/usr/bin/env python3\n\nimport jinja2\nimport json\nimport kopf\nimport kubernetes\nimport os\n\nfrom copy import deepcopy\n\nanarchy_domain = os.environ.get('ANARCHY_DOMAIN', 'anarchy.gpte.redhat.com')\nanarchy_api_version = os.environ.get('ANARCHY_API_VERSION', 'v1')\nbabylon_domain = os.environ.get('BABYLON_DOMAIN', 'babylon.gpte.redhat.com')\nbabylon_api_version = os.environ.get('BABYLON_API_VERSION', 'v1')\npoolboy_domain = os.environ.get('POOLBOY_DOMAIN', 'poolboy.gpte.redhat.com')\npoolboy_api_version = os.environ.get('POOLBOY_API_VERSION', 'v1')\npoolboy_namespace = os.environ.get('POOLBOY_NAMESPACE', 'poolboy')\n\nif os.path.exists('/run/secrets/kubernetes.io/serviceaccount'):\n kubernetes.config.load_incluster_config()\nelse:\n kubernetes.config.load_kube_config()\n\ncore_v1_api = kubernetes.client.CoreV1Api()\ncustom_objects_api = kubernetes.client.CustomObjectsApi()\nj2env = jinja2.Environment(trim_blocks = True)\n\n@kopf.on.startup()\ndef configure(settings: kopf.OperatorSettings, **_):\n # Disable scanning for CustomResourceDefinitions\n settings.scanning.disabled = True\n\n@kopf.on.event(poolboy_domain, poolboy_api_version, 'resourceclaims')\ndef resourceclaim_event(event, logger, **_):\n resource_claim = event.get('object')\n if not resource_claim \\\n or resource_claim.get('kind') != 'ResourceClaim':\n logger.warning(event)\n return\n\n metadata = resource_claim.get('metadata')\n name = metadata.get('name')\n namespace = metadata.get('namespace')\n annotations = metadata.get('annotations', {})\n labels = metadata.get('labels', {})\n\n # Check catalog item to create for users if this is a multi-user environment\n user_catalog_item = labels.get(f\"{babylon_domain}/userCatalogItem\")\n\n # Check user catalog item value against namespace annotation\n namespace_obj = core_v1_api.read_namespace(namespace)\n allow_user_catalog_items = json.loads(namespace_obj.metadata.annotations.get(f\"{babylon_domain}/allowUserCatalogItems\", '[]'))\n if user_catalog_item \\\n and user_catalog_item not in allow_user_catalog_items \\\n and '*' not in allow_user_catalog_items:\n logger.warn(f\"{babylon_domain}/userCatalogItem label set, but not allowed in this namespace\")\n user_catalog_item = None\n\n bookbag_annotation = annotations.get(f\"{babylon_domain}/bookbag\")\n\n # Nothing to do if no configuration for bookbag or user catalog item\n if not bookbag_annotation and not user_catalog_item:\n logger.info(f\"Nothing to do, neither annotation {babylon_domain}/bookbag nor label {babylon_domain}/userCatalogItem is set\")\n return\n\n bookbag_config = json.loads(bookbag_annotation) if bookbag_annotation else None\n\n requester = annotations.get(f\"{babylon_domain}/requester\")\n\n resource_claim_status = resource_claim.get('status', {})\n resource_handle_ref = resource_claim_status.get('resourceHandle')\n if not resource_handle_ref:\n logger.info(f\"Nothing to do, no resourceHandle\")\n return\n if not resource_claim_status.get('resources'):\n logger.info(f\"Nothing to do, no resources in status\")\n return\n\n resource_handle = custom_objects_api.get_namespaced_custom_object(\n poolboy_domain, poolboy_api_version, poolboy_namespace, 'resourcehandles', resource_handle_ref['name']\n )\n resource_handle_ref['uid'] = resource_handle['metadata']['uid']\n resource_handle_ref['controller'] = True\n resource_handle_ref['blockOwnerDeletion'] = False\n\n resource_claim_ref = dict(\n apiVersion = resource_claim['apiVersion'],\n controller = True,\n blockOwnerDeletion = False,\n kind = resource_claim['kind'],\n name = name,\n uid = metadata['uid']\n )\n\n guid = resource_handle_ref['name'][5:]\n provision_data = {\n 'guid': guid,\n 'user': requester,\n }\n provision_messages = []\n users = {}\n\n for idx, resource in enumerate(resource_claim_status['resources']):\n resource_name = resource_claim['spec']['resources'][idx].get('name')\n resource_state = resource.get('state')\n if not resource_state:\n logger.info(f\"Nothing to do, missing resource state\")\n return\n if resource_state['apiVersion'] != f\"{anarchy_domain}/{anarchy_api_version}\" \\\n or resource_state['kind'] != 'AnarchySubject':\n continue\n spec_vars = resource_state.get('spec', {}).get('vars', {})\n current_state = spec_vars.get('current_state')\n if current_state not in ['started', 'stopped']:\n logger.info(f\"Nothing to do, resource current_state is {current_state}\")\n return\n for k, v in spec_vars.get('provision_data', {}).items():\n if k != 'users':\n provision_data[k] = v\n if resource_name:\n provision_data[f\"{resource_name}_{k}\"] = v\n provision_messages.extend(spec_vars.get('provision_messages', []))\n for user, user_data in spec_vars.get('provision_data').get('users', {}).items():\n if user in users:\n users[user].update(user_data)\n else:\n users[user] = deepcopy(user_data)\n if resource_name:\n for k, v in user_data.items():\n users[user][f\"{resource_name}_{k}\"] = v\n\n image = None\n image_stream = None\n if bookbag_config:\n image = bookbag_config.get('image')\n if not image:\n if bookbag_config.get('imageBuild'):\n image_stream = f\"bookbag-{guid}\"\n manage_bookbag_image_build(\n namespace,\n image_stream,\n bookbag_config,\n resource_claim_ref,\n logger,\n )\n else:\n logger.warning(\"Invalid bookbag config, no image or imageBuild\");\n bookbag_config = None\n\n resource_claim_patch = {}\n\n if users:\n lab_ui_urls = {}\n for user, user_data in users.items():\n user_data['guid'] = guid\n user_data['user'] = user\n if bookbag_config:\n bookbag_hostname = manage_bookbag_deployment(\n namespace,\n 'bookbag-{0}-{1}'.format(guid, user),\n bookbag_config,\n user_data,\n resource_claim_ref,\n image,\n image_stream,\n logger,\n )\n bookbag_url = f\"https://{bookbag_hostname}/\"\n lab_ui_urls[user] = bookbag_url\n elif 'bookbag_url' in user_data:\n lab_ui_urls[user] = user_data['bookbag_url']\n\n if user_catalog_item \\\n and not annotations.get(f\"{babylon_domain}/userResourceHandlesGenerated\"):\n user_resource_handle = {\n \"apiVersion\": f\"{poolboy_domain}/{poolboy_api_version}\",\n \"kind\": \"ResourceHandle\",\n \"metadata\": {\n \"name\": f\"guid-{guid}-{user}\",\n \"ownerReferences\": [resource_handle_ref],\n },\n \"spec\": {\n \"resources\": [{\n \"provider\": {\n \"apiVersion\": f\"{poolboy_domain}/{poolboy_api_version}\",\n \"kind\": \"ResourceProvider\",\n \"name\": \"babylon-user-configmap\",\n \"namespace\": \"poolboy\",\n },\n \"template\": {\n \"metadata\": {\n \"namespace\": namespace,\n \"labels\": {\n f\"{babylon_domain}/catalogItem\": user_catalog_item,\n },\n },\n \"data\": {\n \"userData\": json.dumps(user_data),\n }\n }\n }]\n }\n }\n if lab_ui_urls.get(user):\n user_resource_handle['spec']['resources'][0]['template']['data']['labUserInterfaceUrl'] = lab_ui_urls[user]\n try:\n custom_objects_api.create_namespaced_custom_object(\n poolboy_domain, poolboy_api_version, poolboy_namespace, 'resourcehandles', user_resource_handle\n )\n except kubernetes.client.rest.ApiException as e:\n if e.status == 409:\n pass\n else:\n raise\n\n deepmerge(resource_claim_patch, {\n \"metadata\": {\n \"annotations\": {\n f\"{babylon_domain}/userResourceHandlesGenerated\": \"true\",\n }\n }\n })\n\n if lab_ui_urls:\n lab_ui_urls = json.dumps(lab_ui_urls)\n if lab_ui_urls != annotations.get(f\"{babylon_domain}/labUserInterfaceUrls\"):\n deepmerge(resource_claim_patch, {\n \"metadata\": {\n \"annotations\": {\n f\"{babylon_domain}/labUserInterfaceUrls\": lab_ui_urls,\n }\n }\n })\n\n elif bookbag_config:\n if provision_messages:\n provision_data['user_info_messages'] = \"\\n\".join(provision_messages)\n bookbag_hostname = manage_bookbag_deployment(\n namespace,\n f\"bookbag-{guid}\",\n bookbag_config,\n provision_data,\n resource_claim_ref,\n image,\n image_stream,\n logger,\n )\n bookbag_url = f\"https://{bookbag_hostname}/\"\n if bookbag_url != annotations.get(f\"{babylon_domain}/labUserInterfaceUrl\"):\n deepmerge(resource_claim_patch, {\n \"metadata\": {\n \"annotations\": {\n f\"{babylon_domain}/labUserInterfaceUrl\": bookbag_url,\n }\n }\n })\n\n if resource_claim_patch:\n custom_objects_api.patch_namespaced_custom_object(\n poolboy_domain, poolboy_api_version, namespace, \"resourceclaims\", name, resource_claim_patch\n )\n\ndef deepmerge(d, s):\n if isinstance(d, dict) and isinstance(s, dict):\n for k, v in s.items():\n if k in d:\n if isinstance(v, dict) and isinstance(d[k], dict) \\\n or isinstance(v, list) and isinstance(d[k], list):\n deepmerge(d[k], v)\n else:\n d[k] = deepcopy(v)\n else:\n d[k] = deepcopy(v)\n elif isinstance(d, list) and isinstance(s, list):\n for i, v in enumerate(s):\n if i < len(d):\n if isinstance(v, dict) and isinstance(d[i], dict) \\\n or isinstance(v, list) and isinstance(d[i], list):\n deepmerge(d[i], v)\n else:\n d[i] = deepcopy(v)\n else:\n d[i] = deepcopy(v)\n else:\n raise Exception('Invalid types to deepmerge')\n\n return d\n\ndef get_build_config(namespace, name):\n try:\n return custom_objects_api.get_namespaced_custom_object(\n 'build.openshift.io', 'v1', namespace, 'buildconfigs', name\n )\n except kubernetes.client.rest.ApiException as e:\n if e.status == 404:\n return None\n else:\n raise\n\ndef get_deployment(namespace, name):\n try:\n return custom_objects_api.get_namespaced_custom_object(\n 'apps', 'v1', namespace, 'deployments', name\n )\n except kubernetes.client.rest.ApiException as e:\n if e.status == 404:\n return None\n else:\n raise\n\ndef get_image_stream(namespace, name):\n try:\n return custom_objects_api.get_namespaced_custom_object(\n 'image.openshift.io', 'v1', namespace, 'imagestreams', name\n )\n except kubernetes.client.rest.ApiException as e:\n if e.status == 404:\n return None\n else:\n raise\n\ndef get_role_binding(namespace, name):\n try:\n return custom_objects_api.get_namespaced_custom_object(\n 'rbac.authorization.k8s.io', 'v1', namespace, 'rolebindings', name\n )\n except kubernetes.client.rest.ApiException as e:\n if e.status == 404:\n return None\n else:\n raise\n\ndef get_route(namespace, name):\n try:\n return custom_objects_api.get_namespaced_custom_object(\n 'route.openshift.io', 'v1', namespace, 'routes', name\n )\n except kubernetes.client.rest.ApiException as e:\n if e.status == 404:\n return None\n else:\n raise\n\ndef get_service(namespace, name):\n try:\n return core_v1_api.read_namespaced_service(name, namespace)\n except kubernetes.client.rest.ApiException as e:\n if e.status == 404:\n return None\n else:\n raise\n\ndef get_service_account(namespace, name):\n try:\n return core_v1_api.read_namespaced_service_account(name, namespace)\n except kubernetes.client.rest.ApiException as e:\n if e.status == 404:\n return None\n else:\n raise\n\ndef manage_bookbag_image_build(namespace, name, bookbag_config, owner_ref, logger=None):\n \"\"\"\n Create BuildConfig and ImageStream to build Bookbag image.\n \"\"\"\n build_spec = deepcopy(bookbag_config['imageBuild'])\n build_spec['output'] = {\n \"to\": {\n \"kind\": \"ImageStreamTag\",\n \"name\": f\"{name}:latest\",\n }\n }\n if 'strategy' not in build_spec:\n build_spec['strategy'] = {\n \"type\": \"Source\",\n \"sourceStrategy\": {\n \"from\": {\n \"kind\": \"DockerImage\",\n \"name\": \"quay.io/openshifthomeroom/workshop-dashboard:5.0.0\",\n }\n }\n }\n build_spec['triggers'] = [{\"type\": \"ConfigChange\"}]\n\n image_stream = get_image_stream(namespace, name)\n if not image_stream:\n custom_objects_api.create_namespaced_custom_object(\n 'image.openshift.io', 'v1', namespace, 'imagestreams',\n {\n \"apiVersion\": \"image.openshift.io/v1\",\n \"kind\": \"ImageStream\",\n \"metadata\": {\n \"name\": name,\n \"namespace\": namespace,\n \"ownerReferences\": [owner_ref],\n },\n }\n )\n\n build_config = get_build_config(namespace, name)\n if build_config:\n merged_spec = deepmerge(deepcopy(build_config['spec']), build_spec)\n if merged_spec != build_config['spec']:\n try:\n custom_objects_api.replace_namespaced_custom_object(\n 'build.openshift.io', 'v1', namespace, 'buildconfigs', name, {\n \"apiVersion\": \"build.openshift.io/v1\",\n \"kind\": \"BuildConfig\",\n \"metadata\": build_config['metadata'],\n \"spec\": merged_spec,\n }\n )\n except kubernetes.client.rest.ApiException as e:\n if e.status == 409:\n pass\n else:\n raise\n else:\n custom_objects_api.create_namespaced_custom_object(\n 'build.openshift.io', 'v1', namespace, 'buildconfigs',\n {\n \"apiVersion\": \"build.openshift.io/v1\",\n \"kind\": \"BuildConfig\",\n \"metadata\": {\n \"name\": name,\n \"namespace\": namespace,\n \"ownerReferences\": [owner_ref],\n },\n \"spec\": build_spec,\n }\n )\n\ndef manage_bookbag_deployment(namespace, name, bookbag_config, bookbag_vars, owner_ref, image=None, image_stream=None, logger=None):\n \"\"\"\n Create Deployment, RoleBinding, Route, Service, ServiceAccount for bookbag.\n \"\"\"\n auth = bookbag_config.get('auth', {})\n auth_user = auth.get('user', '*')\n auth_password = auth.get('password', '')\n\n service_account = get_service_account(namespace, name)\n if not service_account:\n core_v1_api.create_namespaced_service_account(\n namespace,\n {\n \"apiVersion\": \"v1\",\n \"kind\": \"ServiceAccount\",\n \"metadata\": {\n \"name\": name,\n \"ownerReferences\": [owner_ref],\n }\n }\n )\n\n role_binding = get_role_binding(namespace, name)\n if not role_binding:\n custom_objects_api.create_namespaced_custom_object(\n 'rbac.authorization.k8s.io', 'v1', namespace, 'rolebindings',\n {\n \"apiVersion\": \"rbac.authorization.k8s.io/v1\",\n \"kind\": \"RoleBinding\",\n \"metadata\": {\n \"name\": name,\n \"ownerReferences\": [owner_ref],\n },\n \"roleRef\": {\n \"apiGroup\": \"rbac.authorization.k8s.io\",\n \"kind\": \"ClusterRole\",\n \"name\": \"basic-user\",\n },\n \"subjects\": [{\n \"kind\": \"ServiceAccount\",\n \"name\": name,\n \"namespace\": namespace,\n }]\n }\n )\n\n deployment = get_deployment(namespace, name)\n deployment_spec = {\n \"replicas\": 1,\n \"selector\": {\n \"matchLabels\": {\n \"name\": name,\n }\n },\n \"strategy\": {\n \"type\": \"Recreate\",\n },\n \"template\": {\n \"metadata\": {\n \"labels\": {\n \"name\": name,\n }\n },\n \"spec\": {\n \"containers\": [{\n \"name\": \"bookbag\",\n \"env\": [{\n \"name\": \"APPLICATION_NAME\",\n \"value\": name,\n }, {\n \"name\": \"AUTH_USERNAME\",\n \"value\": auth_user,\n }, {\n \"name\": \"AUTH_PASSWORD\",\n \"value\": auth_password,\n }, {\n \"name\": \"CLUSTER_SUBDOMAIN\",\n }, {\n \"name\": \"OAUTH_SERVICE_ACCOUNT\",\n \"value\": name,\n }, {\n \"name\": \"DOWNLOAD_URL\",\n }, {\n \"name\": \"WORKSHOP_FILE\",\n }, {\n \"name\": \"OC_VERSION\",\n }, {\n \"name\": \"ODO_VERSION\",\n }, {\n \"name\": \"KUBECTL_VERSION\",\n }, {\n \"name\": \"WORKSHOP_VARS\",\n \"value\": json.dumps(bookbag_vars),\n }],\n \"imagePullPolicy\": \"Always\",\n \"ports\": [{\n \"containerPort\": 10080,\n }],\n \"resources\": {},\n }],\n \"serviceAccountName\": name,\n }\n }\n }\n # If image is set then use provided value.\n if image:\n deployment_spec['template']['spec']['containers'][0]['image'] = image\n\n if deployment:\n merged_spec = deepmerge(deepcopy(deployment['spec']), deployment_spec)\n if merged_spec != deployment['spec']:\n try:\n custom_objects_api.replace_namespaced_custom_object(\n 'apps', 'v1', namespace, 'deployments', name, {\n \"apiVersion\": \"apps/v1\",\n \"kind\": \"Deployment\",\n \"metadata\": deployment['metadata'],\n \"spec\": merged_spec,\n }\n )\n except kubernetes.client.rest.ApiException as e:\n if e.status == 409:\n pass\n else:\n raise\n else:\n deployment_meta = {\n \"name\": name,\n \"namespace\": namespace,\n \"ownerReferences\": [owner_ref],\n }\n\n if not image:\n # Set image-change trigger on image stream\n deployment_meta['annotations'] = {\n \"image.openshift.io/triggers\": json.dumps([{\n \"from\": {\n \"kind\": \"ImageStreamTag\",\n \"name\": f\"{image_stream}:latest\",\n },\n \"fieldPath\": 'spec.template.spec.containers[?(@.name==\"bookbag\")].image',\n }])\n }\n # This is image value is just a place-holder, required for validation\n deployment_spec['template']['spec']['containers'][0]['image'] = \\\n f\"image-registry.openshift-image-registry.svc:5000/{namespace}/{image_stream}:latest\"\n\n custom_objects_api.create_namespaced_custom_object(\n 'apps', 'v1', namespace, 'deployments',\n {\n \"apiVersion\": \"apps/v1\",\n \"kind\": \"Deployment\",\n \"metadata\": deployment_meta,\n \"spec\": deployment_spec,\n }\n )\n\n service = get_service(namespace, name)\n if not service:\n core_v1_api.create_namespaced_service(\n namespace,\n {\n \"apiVersion\": \"v1\",\n \"kind\": \"Service\",\n \"metadata\": {\n \"name\": name,\n \"namespace\": namespace,\n \"ownerReferences\": [owner_ref],\n },\n \"spec\": {\n \"ports\": [{\n \"name\": \"10080-tcp\",\n \"port\": 10080,\n \"protocol\": \"TCP\",\n \"targetPort\": 10080,\n }],\n \"selector\": {\n \"name\": name,\n },\n \"type\": \"ClusterIP\",\n }\n }\n )\n\n route = get_route(namespace, name)\n if not route:\n route = custom_objects_api.create_namespaced_custom_object(\n 'route.openshift.io', 'v1', namespace, 'routes',\n {\n \"apiVersion\": \"route.openshift.io/v1\",\n \"kind\": \"Route\",\n \"metadata\": {\n \"name\": name,\n \"namespace\": namespace,\n \"ownerReferences\": [owner_ref],\n },\n \"spec\": {\n \"port\": {\n \"targetPort\": \"10080-tcp\",\n },\n \"tls\": {\n \"insecureEdgeTerminationPolicy\": \"Redirect\",\n \"termination\": \"edge\",\n },\n \"to\": {\n \"kind\": \"Service\",\n \"name\": name,\n },\n }\n }\n )\n return route['spec']['host']\n","sub_path":"lab-ui-manager/operator/operator.py","file_name":"operator.py","file_ext":"py","file_size_in_byte":23454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"461252982","text":"import sys\nimport os.path as op\nimport string\nimport io\nimport time\nfrom collections import defaultdict\n\nimport numpy as np\nimport pandas as pd\n\nfrom .peddy import Ped\nfrom cyvcf2 import VCF\n\nif sys.version_info[0] == 3:\n basestring = str\n\ndef run(args):\n check, pedf, vcf, plot, prefix, each, ncpus, sites = args\n # only print warnings for het_check\n p = Ped(pedf, warn=False)\n print(\"\\033[1;31m%s\\033[0m\" % check)\n\n t0 = time.time()\n sys.stdout.flush()\n background_df = None\n if plot:\n plot = prefix + \".\" + check + \".png\"\n\n if check in (\"ped_check\", \"het_check\"):\n kwargs = {'sites': sites} if check == 'ped_check' else {}\n df = getattr(p, check)(vcf, plot=plot, each=each, ncpus=ncpus,\n prefix=prefix, **kwargs)\n if check == \"het_check\":\n df, background_df = df\n else:\n df = getattr(p, check)(vcf, plot=plot)\n\n if df is None:\n return check, None, None\n\n df.to_csv(prefix + (\".%s.csv\" % check), sep=\",\", index=False, float_format=\"%.4g\")\n if 'keep' in df.columns:\n df = df.ix[df['keep'], :]\n df.drop(['keep'], axis=1, inplace=True)\n d, unit = time.time() - t0, \"seconds\"\n if d > 100:\n d /= 60\n unit = \"minutes\"\n print(\"ran in %.1f %s\" % (d, unit))\n if df.shape[0] > 50000 and check == \"ped_check\":\n # remove unknown relationships that aren't in error.\n df = df[((df.pedigree_relatedness != -1) &\n (~df.parent_error) &\n (~df.sample_duplication_error))]\n\n if check == \"ped_check\":\n # makes the plot nicer\n df.sort_values(inplace=True, by=[\"pedigree_relatedness\"])\n\n return (check, df, background_df) #\n\ndef correct_sex_errors(ped_df):\n excl = []\n if not 'sex_error' in ped_df.columns:\n return excl\n if np.any(ped_df['sex_error']):\n try:\n ped_df.pop(u'sex_fixed')\n except KeyError:\n pass\n ped_df.rename(columns={'sex_error': 'sex_fixed'}, inplace=True)\n\n sex_col = ped_df.columns[4]\n # now adjust the sex column as needed.\n sc = np.array(ped_df[sex_col])\n osc = np.array(ped_df[sex_col])\n sf = np.asarray(ped_df['sex_fixed'])\n gt = np.asarray(ped_df['sex_het_ratio'] > 0)\n if sc.dtype.char == 'S':\n sel = (gt & sf & (sc == '1'))\n sc[sel] = '2'\n if sel.sum():\n print(\"set sex of samples: %s to female in peddy.ped\" % \",\".join(map(str, ped_df.ix[1, sel])))\n\n sel = (gt & sf & (sc == '2'))\n sc[sel] = '1'\n if sel.sum():\n print(\"set sex of samples: %s to male in peddy.ped\" % \",\".join(map(str, ped_df.ix[1, sel])))\n else:\n for (ifrom, ito) in ((1, 2), (2, 1)):\n sel = (gt & sf & (sc == ifrom))\n osc[sel] = ito\n if sel.sum():\n print(\"\\nNOTE: changed sex of samples: %s to %s in peddy.ped\" % (\n \",\".join(map(str, ped_df.ix[sel, 1])),\n [\"\", \"male\", \"female\"][ito]))\n\n\n ped_df[sex_col] = osc\n else:\n excl = ['sex_error']\n return excl\n\ndef main(vcf, pedf, prefix, plot=False, each=1, ncpus=3, sites=None):\n\n tmpl = string.Template(open(op.join(op.dirname(__file__), \"tmpl.html\")).read())\n\n ped = Ped(pedf)\n prefix = prefix.rstrip(\".-\")\n\n samples = VCF(vcf).samples\n\n ped_df = pd.read_table(pedf,\n header=None,\n names=ped.header or ['family_id', 'sample_id',\n 'paternal_id', 'maternal_id',\n 'sex', 'phenotype'],\n # if there's a header, we skip it as it's inidcated\n # above.\n index_col=False,\n skiprows=1 if ped.header else None,\n sep=\"\\t\")\n\n ped_df.family_id = [str(x) for x in ped_df.family_id]\n ped_df.index = ped_df.sample_id = [str(x) for x in ped_df.sample_id]\n\n samples = set(samples)\n\n # exhaust list explicitly to get str from bytes.\n in_vcf_not_in_ped = samples - set(ped_df.index)\n in_ped_not_in_vcf = set(ped_df.index) - samples\n if in_vcf_not_in_ped:\n print(\"WARNING:\\n%d samples in vcf not in ped:\\n%s\\n\" %\n (len(in_vcf_not_in_ped), \",\".join(in_vcf_not_in_ped)))\n if in_ped_not_in_vcf:\n print(\"WARNING:\\n%d samples in ped not in vcf:\\n%s\\n\" %\n (len(in_ped_not_in_vcf), \",\".join(in_ped_not_in_vcf)))\n\n # keep order.\n samples = [s for s in ped_df['sample_id'] if s in samples]\n\n ped_df = ped_df.ix[samples, :]\n\n\n keep_cols = {\"ped_check\": [],\n \"het_check\": [\"call_rate\", \"het_ratio\", \"mean_depth\", \"idr_baf\", \"ancestry-prediction\", \"PC1\", \"PC2\", \"PC3\"],\n \"sex_check\": [\"het_ratio\", \"error\"]}\n\n vals = {'title': op.splitext(op.basename(pedf))[0], 'each': each}\n # background_df only present for het-check. It's the PC's from 1000G for\n # plotting.\n for check, df, background_df in map(run, [(check, pedf, vcf, plot, prefix, each, ncpus, sites) for check\n in (\"ped_check\", \"het_check\", \"sex_check\")]):\n if df is None:\n vals[check] = []\n continue\n columns = df.columns\n if check == \"sex_check\" and not np.any(df[\"error\"]):\n columns = [c for c in columns if not \"error\" == c]\n vals[check] = df[columns].to_json(orient='split' if check == \"ped_check\" else 'records', double_precision=3)\n\n if check != \"ped_check\":\n df.index = [str(s) for s in df['sample_id']]\n for col in keep_cols[check]:\n c = check.split(\"_\")[0] + \"_\"\n col_name = col if col.startswith((\"PC\", c, \"ancestry\")) else c + col\n ped_df[col_name] = list(df[col].ix[samples])\n elif any(df['sample_duplication_error']):\n da = df.ix[df['sample_duplication_error'], 'sample_a']\n db = df.ix[df['sample_duplication_error'], 'sample_b']\n d = defaultdict(list)\n for a, b in zip(da, db):\n d[a].append(b)\n d[b].append(a)\n d = dict(d)\n for k in d:\n d[k] = \",\".join(d[k])\n\n ped_df['duplicates'] = [d.get(s, \"\") for s in samples]\n\n if background_df is not None:\n vals[\"background_pca\"] = background_df.to_json(orient='records', double_precision=3)\n with open(\"%s.background_pca.json\" % prefix, \"w\") as fh:\n fh.write(vals[\"background_pca\"])\n\n new_pedf = prefix + \".peddy.ped\"\n cols = list(ped_df.columns)\n cols[0] = '#' + cols[0]\n ped_df.columns = cols\n\n ped_df.to_csv(new_pedf, sep=\"\\t\", index=False, mode='w', float_format=\"%.4g\")\n\n # output the new version with the extra columns.\n # avoid extra stuff to stderr\n vals['pedigree'] = Ped(new_pedf, warn=False).to_json(samples, exclude=('PC1', 'PC2', 'PC3'))\n\n excl = correct_sex_errors(ped_df)\n\n ped_df[[c for c in ped_df.columns if not c in excl]].to_csv(new_pedf, sep=\"\\t\", index=False, mode='w', float_format=\"%.4g\")\n\n\n sys.stdout.flush()\n with open(\"%s.html\" % prefix, \"w\") as fh:\n fh.write(tmpl.substitute(**vals))\n\n\nif __name__ == \"__main__\":\n from argparse import ArgumentParser\n p = ArgumentParser(prog=\"python -m peddy\")\n p.add_argument(\"--plot\", default=False, action=\"store_true\")\n p.add_argument(\"-p\", \"--procs\", type=int, default=3, help=\"number of processors to use\")\n p.add_argument(\"--prefix\", help=\"prefix for output files (default is basename of vcf)\")\n p.add_argument(\"--each\", help=\"sample every nth value from the selected sites instead of every value to speed processing.\",\n type=int, default=1)\n p.add_argument(\"--sites\", help=r\"This is rarely used. The path to a file with alternative sites to use for calculating relatedness in format 1:234234\\n1:45345345\\n...\" +\n \" with chrom:pos[:ref:alt] on each line\",\n default=op.join(op.dirname(__file__), '1kg.sites'))\n p.add_argument(\"vcf\", help=\"bgzipped and tabix'ed VCF\")\n p.add_argument(\"ped\", help=\"pedigree file\")\n a = p.parse_args()\n prefix = a.prefix or a.vcf[:-6]\n main(a.vcf, a.ped, prefix, a.plot, a.each, a.procs, a.sites)\n","sub_path":"peddy/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":8473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"457012104","text":"import requests\nfrom bs4 import BeautifulSoup\nimport tkinter as tk\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter.messagebox import showinfo\nimport webbrowser\nfrom PIL import Image, ImageTk\nfrom urllib.request import urlopen\nimport io\n\n# 爬蟲\nkkbox_url = \"https://kma.kkbox.com/charts/daily/song?cate=\"\nspotify_url = 'https://spotifycharts.com/regional/tw/daily/latest'\n\nsong_list = ['297', '390', '308', '314'] # 華語man, 英文eng, 日文jap, 韓文kor\nsong_index = -1\n\nman_rank = []\neng_rank = []\njap_rank = []\nkor_rank = []\nsp_rank = []\ntopone_cover = [] # kkbox四語言的第一名專輯照片\n\nr_spotify = requests.get(spotify_url)\nsoup_spotify = BeautifulSoup(r_spotify.text, 'html.parser')\nattr_spotify = {'class': 'chart-table-track'}\nrank_spotify = soup_spotify.find_all('td', attrs=attr_spotify) # 找到html裡面的td標籤\n\nspotify_num = 0\n\n# spotify的排名\nfor i in rank_spotify:\n song = i.get_text().strip()\n song = song.split('\\nby')\n sp_rank.append(song[0]) # 歌名\n sp_rank.append(song[1]) # 歌手\n\n # 只記錄前���名\n spotify_num += 1\n if spotify_num == 5:\n break\n\n# kkbox的排名\nfor o in (man_rank, eng_rank, jap_rank, kor_rank):\n song_index += 1\n song_url = kkbox_url + song_list[song_index]\n\n r = requests.get(song_url) # 取得網址\n\n soup = BeautifulSoup(r.text, 'html.parser')\n attr = {'name': 'description'}\n\n # 各語言第一名的專輯照片\n cover_scripts = soup.find_all('script')\n cover_scripts = cover_scripts[-2].text[:2000] # 後面一大段都不重要\n\n cover_start = cover_scripts.find('small')\n cover_end = cover_scripts.find('160x160.jpg')\n cover_url = cover_scripts[cover_start+8:cover_end+11]\n cover_url = cover_url.replace('\\\\', '')\n topone_cover.append(cover_url)\n\n # 找到前五歌名和歌手\n rank = soup.find_all('meta', attrs=attr) # 找到html裡面的meta標籤\n rank_str = rank[0]['content'] # 找到排行榜的部分\n rank_str = rank_str[(rank_str.find(':')+1):] # 只抓取歌單的部分\n rank_list = rank_str.split('、') # 把str轉成list\n\n # list中0,2,4,6,8為歌名; 1,3,5,7,9為歌手\n for i in rank_list:\n title = i[:i.find('-')] # 把歌名整理一下\n singer = i[(i.find('-')+1):] # 把歌手整理一下\n if title.find('('): # 如果歌名有(像是歌名的英文名稱)\n o.append(title[:title.find('(')]) # 只保留中文的部分\n else:\n o.append(title)\n\n if singer.find('-'):\n o.append(singer[(singer.find('-')+1):])\n else:\n o.append(singer)\n\n # 把前後有空格的整理乾淨\n for i in range(10):\n o[i] = o[i].strip()\n\nspotify_pic_url = \"http://www.scdn.co/i/_global/twitter_card-default.jpg\" # Spotify logo\n\n\n# 視窗\nclass Ranking(tk.Frame):\n\n def __init__(self, master=None):\n tk.Frame.__init__(self, master)\n self.grid()\n self.create_widgets()\n self.click(man_rank, topone_cover[0])\n\n # 建立主題按鈕&名次\n def create_widgets(self):\n\n # 主題(button)\n self.manbut = tk.Button(self, text=\"華語\", font='微軟正黑體', bg='Black', fg='White', activebackground='#00AED8', activeforeground='White', command=(lambda: self.click(man_rank, topone_cover[0])))\n self.manbut.grid(row=0, column=2, ipadx=15, pady=2, sticky=(tk.NW+tk.SE))\n self.engbut = tk.Button(self, text=\"西洋\", font='微軟正黑體', bg='Black', fg='White', activebackground='#00AED8', activeforeground='White', command=(lambda: self.click(eng_rank, topone_cover[1])))\n self.engbut.grid(row=0, column=3, ipadx=15, pady=2, sticky=(tk.NW+tk.SE))\n self.japbut = tk.Button(self, text=\"日語\", font='微軟正黑體', bg='Black', fg='White', activebackground='#00AED8', activeforeground='White', command=(lambda: self.click(jap_rank, topone_cover[2])))\n self.japbut.grid(row=0, column=4, ipadx=15, pady=2, sticky=(tk.NW+tk.SE))\n self.korbut = tk.Button(self, text=\"韓語\", font='微軟正黑體', bg='Black', fg='White', activebackground='#00AED8', activeforeground='White', command=(lambda: self.click(kor_rank, topone_cover[3])))\n self.korbut.grid(row=0, column=5, ipadx=15, pady=2, sticky=(tk.NW+tk.SE))\n self.spobut = tk.Button(self, text=\"Spotify\", font='微軟正黑體', bg='Black', fg='White', activebackground='#1ED65F', activeforeground='White', command=(lambda: self.click(sp_rank, spotify_pic_url)))\n self.spobut.grid(row=0, column=6, ipadx=15, pady=2, sticky=(tk.NW+tk.SE))\n\n # 名次(label)\n self.rank1 = tk.Label(self, text=' 1st ', font='微軟正黑體', bg='Black', fg='Gold')\n self.rank1.grid(row=2, column=0, padx=10, pady=5, sticky=(tk.NW+tk.SE))\n self.rank2 = tk.Label(self, text=' 2nd ', font='微軟正黑體', bg='Black', fg='Gold')\n self.rank2.grid(row=3, column=0, padx=10, pady=5, sticky=(tk.NW+tk.SE))\n self.rank3 = tk.Label(self, text=' 3rd ', font='微軟正黑體', bg='Black', fg='Gold')\n self.rank3.grid(row=4, column=0, padx=10, pady=5, sticky=(tk.NW+tk.SE))\n self.rank4 = tk.Label(self, text=' 4th ', font='微軟正黑體', bg='Black', fg='Gold')\n self.rank4.grid(row=5, column=0, padx=10, pady=5, sticky=(tk.NW+tk.SE))\n self.rank5 = tk.Label(self, text=' 5th ', font='微軟正黑體', bg='Black', fg='Gold')\n self.rank5.grid(row=6, column=0, padx=10, pady=5, sticky=(tk.NW+tk.SE))\n\n # 離開(button)\n self.exitbut = tk.Button(self, width=2, text='Ⓧ', font=('微軟正黑體', 12), bg='Black', fg='Gray55', activebackground='Black', activeforeground='red', relief='flat', command=(lambda: self.quit()))\n self.exitbut.grid(row=0, column=0, ipadx=10, sticky=tk.NW)\n\n # function: 各主題的排行(button)\n def click(self, rank_name, cover_url):\n self.but1 = tk.Button(self, text=(rank_name[0] + \" - \" + rank_name[1]), font='微軟正黑體', bg='Black', fg='Snow2', activebackground='LightSteelBlue4', activeforeground='White', command=(lambda: self.click_lan(rank_name, 1)))\n self.but1.grid(row=2, column=2, columnspan=6, sticky=(tk.NW+tk.SE))\n self.but2 = tk.Button(self, text=(rank_name[2] + \" - \" + rank_name[3]), font='微軟正黑體', bg='Black', fg='Snow2', activebackground='LightSteelBlue4', activeforeground='White', command=(lambda: self.click_lan(rank_name, 2)))\n self.but2.grid(row=3, column=2, columnspan=6, sticky=(tk.NW+tk.SE))\n self.but3 = tk.Button(self, text=(rank_name[4] + \" - \" + rank_name[5]), font='微軟正黑體', bg='Black', fg='Snow2', activebackground='LightSteelBlue4', activeforeground='White', command=(lambda: self.click_lan(rank_name, 3)))\n self.but3.grid(row=4, column=2, columnspan=6, sticky=(tk.NW+tk.SE))\n self.but4 = tk.Button(self, text=(rank_name[6] + \" - \" + rank_name[7]), font='微軟正黑體', bg='Black', fg='Snow2', activebackground='LightSteelBlue4', activeforeground='White', command=(lambda: self.click_lan(rank_name, 4)))\n self.but4.grid(row=5, column=2, columnspan=6, sticky=(tk.NW+tk.SE))\n self.but5 = tk.Button(self, text=(rank_name[8] + \" - \" + rank_name[9]), font='微軟正黑體', bg='Black', fg='Snow2', activebackground='LightSteelBlue4', activeforeground='White', command=(lambda: self.click_lan(rank_name, 5)))\n self.but5.grid(row=6, column=2, columnspan=6, sticky=(tk.NW+tk.SE))\n\n # 圖片\n self.url = requests.get(cover_url)\n self.imagebyte = io.BytesIO(self.url.content)\n self.imagepil = Image.open(self.imagebyte)\n self.imagepil = self.imagepil.resize((200, 200), Image.ANTIALIAS) # 重設大小\n self.image = ImageTk.PhotoImage(self.imagepil)\n\n # 圖片(Label)\n self.pic = tk.Label(self, image=self.image, bg='Black')\n self.pic.grid(row=1, columnspan=7, sticky=(tk.NW+tk.SE))\n\n # function: 按下歌曲\n def click_lan(self, language, rank):\n webbrowser.open_new_tab(\"https://www.youtube.com/results?search_query=\" + language[rank*2 - 2] + \"+\" + language[rank*2 - 1]) # 開啟Youtube搜尋頁面\n\nranking = Ranking()\nranking.master.title(\"KKbox Ranking\")\nranking.master.geometry('-30-50') # 視窗設在右下角\nranking.master.attributes('-alpha', 1) # 不透明\nranking.master.attributes('-topmost', 1) # 視窗置頂\nranking.master.resizable(0, 0) # 鎖定視窗大小\nranking.configure(bg='Black') # 背景顏色\nranking.master.overrideredirect(True) # 刪除標題欄 \nranking.mainloop()","sub_path":"final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":8641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"620628879","text":"whitesps = '\\r\\n\\v\\f\\t'\n\n\ndef rmlsp(lastr):\n for i in range(len(lastr)):\n if lastr[i] not in whitesps:\n return lastr[i:]\n else:\n return ''\n\n\nlastr = input()\nprint(rmlsp(lastr))\n\n\n####################################################\ndef bqbj(qs, js):\n for gj in range(0, qs // 5 + 1):\n for mj in range(0, (qs - 5 * gj) // 3 + 1):\n for xj in range(0, qs - 5 * gj - 3 * mj + 1):\n if qs - 5 * gj - 3 * mj - xj:\n continue\n else:\n if gj + mj + xj * 3 == js:\n print('公鸡%s只,母鸡%s只,小鸡%s只' % (gj, mj, xj * 3))\n else:\n continue\n\n\nbqbj(100, 100)\n##########################################################\n","sub_path":"day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"55128006","text":"#!/usr/bin/env python3\n\nimport os, sys\nimport time\nimport json\nimport asyncio\n\nfrom copy import deepcopy\n\nHOME_DIR = os.environ['HOME_DIR']\nsys.path.insert(0, HOME_DIR)\n\nfrom dnx_configure.dnx_constants import *\n\n\nclass Automate:\n def __init__(self, DNSProxy):\n self.DNSProxy = DNSProxy\n\n async def LogSettings(self):\n print(f'[+] Log Settings Timer')\n while True:\n with open(f'{HOME_DIR}/data/config.json', 'r') as settings:\n setting = json.load(settings)\n\n self.DNSProxy.logging_level = setting['settings']['logging']['level']\n\n await asyncio.sleep(SETTINGS_TIMER)\n\n async def DNSRecords(self):\n print(f'[+] DNS Records Timer')\n while True:\n with open(f'{HOME_DIR}/data/dns_server.json', 'r') as dns_records:\n dns_record = json.load(dns_records)\n\n self.DNSProxy.dns_records = dns_record['dns_server']['records']\n\n await asyncio.sleep(SETTINGS_TIMER)\n\n async def UserDefinedLists(self):\n print(f'[+] User Defined Lists Timer')\n while True:\n current_time = time.time()\n ## --------------------------------------------- ##\n ## -- IP WHITELIST CHECK AND CLEAN/ IF NEEDED -- ##\n with open(f'{HOME_DIR}/data/whitelist.json', 'r') as whitelists:\n whitelist = json.load(whitelists)\n self.DNSProxy.ip_whitelist = whitelist['whitelists']['ip_whitelist']\n\n ## ---------------------------------------------- ##\n ## -- DNS WHITELIST CHECK AND CLEAN/ IF NEEDED -- ##\n with open(f'{HOME_DIR}/data/whitelist.json', 'r') as whitelists:\n whitelist = json.load(whitelists)\n self.DNSProxy.dns_whitelist = whitelist['whitelists']['domains']\n\n write_whitelist = False\n dns_whitelist = deepcopy(self.DNSProxy.dns_whitelist)\n for domain, info in dns_whitelist.items():\n if current_time > info['expire']:\n self.DNSProxy.dns_whitelist.pop(domain)\n write_whitelist = True\n\n if (write_whitelist):\n with open(f'{HOME_DIR}/data/whitelist.json', 'w') as whitelists:\n json.dump(whitelist, whitelists, indent=4)\n\n ## -------------------------------------------##\n ## -- BLACKLIST CHECK AND CLEAN/ IF NEEDED -- ##\n with open(f'{HOME_DIR}/data/blacklist.json', 'r') as blacklists:\n blacklist = json.load(blacklists)\n self.DNSProxy.dns_blacklist = blacklist['blacklists']['domains']\n\n write_blacklist = False\n dns_blacklist = deepcopy(self.DNSProxy.dns_blacklist)\n for domain, info in dns_blacklist.items():\n if current_time > info['expire']:\n self.DNSProxy.dns_blacklist.pop(domain)\n write_blacklist = True\n\n if (write_blacklist):\n with open(f'{HOME_DIR}/data/blacklist.json', 'w') as blacklists:\n json.dump(blacklist, blacklists, indent=4)\n\n print('Updating white/blacklists in memory.')\n await asyncio.sleep(SETTINGS_TIMER)\n\n async def Reachability(self):\n print(f'[+] DNS Public Server Reachability Timer')\n loop = asyncio.get_running_loop()\n while True:\n for server_ip in self.DNSProxy.dns_servers:\n reach = await asyncio.create_subprocess_shell(\n f'ping -c 2 {server_ip}',\n stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE)\n\n await reach.communicate()\n\n previous_status = self.DNSProxy.dns_servers[server_ip].get('reach')\n if (reach.returncode == 0):\n self.DNSProxy.dns_servers[server_ip].update({'reach': True})\n else:\n self.DNSProxy.dns_servers[server_ip].update({'reach': False})\n current_status = self.DNSProxy.dns_servers[server_ip].get('reach')\n if (current_status != previous_status):\n message = (f'DNS Server {server_ip} reachability status changed to {current_status}.')\n await loop.run_in_executor(None, self.DNSProxy.Log.AddtoQueue, message)\n\n with open(f'{HOME_DIR}/data/dns_server_status.json', 'w') as dns_server:\n json.dump(self.DNSProxy.dns_servers, dns_server, indent=4)\n\n await asyncio.sleep(SHORT_POLL)\n\n async def Settings(self):\n print(f'[+] General Settings Timer')\n while True:\n with open(f'{HOME_DIR}/data/dns_server.json', 'r') as dns_settings:\n dns_setting = json.load(dns_settings)\n dns_servers = dns_setting['dns_server']['resolvers']\n\n if (dns_servers != self.DNSProxy.dns_servers):\n self.DNSProxy.dns_servers = {}\n dns1 = dns_servers['server1']['ip_address']\n dns2 = dns_servers['server2']['ip_address']\n self.DNSProxy.dns_servers[dns1] = {'reach': True, 'tls': True}\n self.DNSProxy.dns_servers[dns2] = {'reach': True, 'tls': True}\n\n tls_settings = dns_setting['dns_server']['tls']\n\n self.DNSProxy.tls_retry = tls_settings['retry']\n self.DNSProxy.udp_fallback = tls_settings['fallback']\n tls_enabled = tls_settings['enabled']\n if (tls_enabled):\n self.DNSProxy.DNSRelay.protocol = TCP\n else:\n self.DNSProxy.DNSRelay.protocol = UDP\n\n cache_settings = dns_setting['dns_server']['cache']\n # CLEAR DNS or TOP Domains cache\n self.DNSProxy.DNSCache.clear_dns_cache = cache_settings['standard']\n self.DNSProxy.DNSCache.clear_top_domains = cache_settings['top_domains']\n\n await asyncio.sleep(SETTINGS_TIMER)\n\n # automated process to flush the cache if expire time has been reached. runs every 1 minute.\n async def ClearCache(self):\n print(f'[+] DNS Local Cache Clearing Timer')\n while True:\n now = time.time()\n query_cache = deepcopy(self.DNSProxy.DNSCache.dns_query_cache)\n for domain, info in query_cache.items():\n if (now > info['expire']):\n self.DNSProxy.DNSCache.dns_query_cache.pop(domain, None)\n\n cache_size = sys.getsizeof(self.DNSProxy.DNSCache.dns_query_cache)\n num_records = len(self.DNSProxy.DNSCache.dns_query_cache)\n print(f'CACHE SIZE: {cache_size} | NUMBER OF RECORDS: {num_records}')\n await asyncio.sleep(SHORT_POLL)\n","sub_path":"dns_proxy/dns_proxy_automate.py","file_name":"dns_proxy_automate.py","file_ext":"py","file_size_in_byte":6693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"38769908","text":"# Kobee Raveendran\n# Common Character Count - CodeFights\n\n# Given two strings, find the number of common characters between them\n\ndef commonCharacterCount(s1, s2):\n string1 = list(s1)\n string2 = list(s2)\n\n if len(s1) < len(s2):\n shorterString = string1\n longerString = string2\n else:\n shorterString = string2\n longerString = string1\n\n endIndex = min(len(s1), len(s2))\n count = 0\n\n for i in range(endIndex):\n if shorterString[i] in longerString:\n count += 1\n longerString.remove(shorterString[i])\n\n return count\n\nprint(commonCharacterCount('abca', 'xyzbac'))","sub_path":"codefights/arcade/common-character-count.py","file_name":"common-character-count.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"147269117","text":"import torch\nfrom torchvision import transforms\nfrom torchvision.models import inception_v3\nfrom torchvision.datasets import ImageFolder\nfrom PIL import Image\n\nclass Analyzer():\n def __init__(self):\n model = inception_v3(num_classes=16)\n params = torch.load('params.pth', map_location='cpu')\n model.load_state_dict(params)\n self.model = model.cpu()\n self.model.eval()\n\n self.transform = transforms.Compose([\n transforms.Resize(299),\n transforms.CenterCrop(299),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229,0.224,0.225])\n ])\n\n self.class_list = [\n 'actinic keratosis', \n 'angioma', \n 'atypical melanocytic proliferation', \n 'basal cell carcinoma', \n 'dermatofibroma', \n 'lentigo NOS', \n 'lentigo simplex', \n 'melanoma', \n 'nevus', \n 'other', \n 'pigmented benign keratosis', \n 'seborrheic keratosis', \n 'solar lentigo', \n 'squamous cell carcinoma', \n 'vascular lesion'\n ]\n self.introduction = [\n '光线性角化病',\n '血管瘤',\n '非典型黑色素细胞增生',\n '基底细胞上皮瘤',\n '皮肤纤维瘤',\n '雀斑痣',\n '单纯性雀斑痣',\n '黑素瘤',\n '痣',\n '其他皮肤病',\n '色素性良性角化病',\n '脂溢性角化病',\n '日光性着色班',\n '鳞状细胞癌',\n '血管病变',\n ]\n\n def __call__(self, image):\n self.model.eval()\n img = Image.open(image)\n img = self.transform(img).unsqueeze(0)\n output = self.model(img)\n pred = output.max(1)[1][0]\n return (self.class_list[pred], self.introduction[pred])\n\n def pred(self, images):\n dataset = ImageFolder(images, transform=self.transform)\n dataloader = torch.utils.data.DataLoader(dataset, batch_size=50)\n for idx, (data, target) in enumerate(dataloader):\n if idx < 2:\n continue\n result = self.model(data).max(1)[1]\n print(target == result)\n print(target)\n break\n\nif __name__ == '__main__':\n analyzer = Analyzer()\n analyzer.pred('/Users/icefires/Desktop/Test Examples')\n","sub_path":"analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"119691349","text":"import dataloader2\r\nimport models.picto2d as p2d\r\nfrom torchvision import transforms\r\nfrom torch.utils.data import Dataset, DataLoader\r\nimport torch\r\nfrom torch.autograd import Variable\r\nimport numpy as np\r\n\r\ndef train(epochs = 30,batch = 8,device=torch.device('cpu')):\r\n train_data = dataloader2.PictoTwoDataset(mode=\"train\",transform=transforms.ToTensor())\r\n val_data = dataloader2.PictoTwoDataset(mode=\"val\",transform=transforms.ToTensor())\r\n train_loader = DataLoader(dataset= train_data,batch_size=batch,shuffle=True)\r\n val_loader = DataLoader(dataset= val_data,batch_size=batch)\r\n\r\n model = p2d.Picto2d().to(device)\r\n print(model)\r\n optimizer = torch.optim.Adam(model.parameters())\r\n loss_func = torch.nn.MSELoss()\r\n size = 3\r\n for epoch in range(epochs):\r\n print('epoch {}'.format(epoch+1))\r\n # start training\r\n train_loss = 0.\r\n train_acc = 0.\r\n for batch_x,batch_y,size_z in train_loader:\r\n batch_x,batch_y = Variable(batch_x.to(device)),Variable(torch.from_numpy(np.array([pointsize(batch_y,size)])).to(device))\r\n #print(batch_x)\r\n out = model(batch_x)\r\n #out=out.reshape(60)\r\n #print(out)\r\n #print(batch_y.qw)\r\n loss = loss_func(out,batch_y.float())\r\n #train_loss += loss.data\r\n #pred = torch.max(out,1)[1].double()\r\n #train_correct = (pred == batch_y).sum()\r\n #train_acc += train_correct.data\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n print('Train Loss: {:.6f}'.format(train_loss / (len(train_data))))\r\n\r\n\r\n model.eval()\r\n eval_loss = 0.\r\n eval_acc = 0.\r\n for batch_x, batch_y,size_z in val_loader:\r\n batch_x, batch_y = Variable(batch_x.to(device)),Variable(torch.from_numpy(np.array([pointsize(batch_y,size)])).to(device))\r\n with torch.no_grad():\r\n out = model(batch_x)\r\n print(out)\r\n loss = loss_func(out, batch_y.float())\r\n #eval_loss += loss.data\r\n #pred = torch.max(out, 1)[1].double()\r\n #num_correct = (pred == batch_y).sum()\r\n #eval_acc += num_correct.data\r\n print('Test Loss: {:.6f}'.format(eval_loss / (len(val_data))))\r\n # if train_loss/eval_loss > 10:\r\n # size+=1\r\n if epoch%5 == 0:\r\n torch.save(model,'multiepoch'+str(epoch)+'.pkl')\r\n torch.save(model,'multiresult.pkl')\r\n\r\n\r\ndef pointsize(x,size):\r\n result = []\r\n for k in x:\r\n a = k*(10**size)\r\n result.append(int(a)/(10**size))\r\n return x\r\n\r\ndevice_2 = torch.device('cuda:3' if torch.cuda.is_available() else 'cpu')\r\ntrain(30,1,device=device_2)\r\n","sub_path":"2dtrain.py","file_name":"2dtrain.py","file_ext":"py","file_size_in_byte":2770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"458394025","text":"# מיקי מאירסון 207349010\n# נעם תשובה 207576109\n\nimport random\n\n\nclass Node:\n \"\"\" A single node of a singly linked list \"\"\"\n\n def __init__(self, data=None, next_node=None):\n self.data = data\n self.next = next_node\n\n\nclass List:\n \"\"\" A Linked List class with a single head node \"\"\"\n\n def __init__(self, head=None):\n self.head = head\n\n def insert(self, data):\n \"\"\" insert to end of linked list \"\"\"\n new_node = Node(data)\n if self.head:\n current = self.head\n while current.next:\n current = current.next\n current.next = new_node\n else:\n self.head = new_node\n\n\ndef create_list():\n is_snake = random.randint(0, 1) # Snake - 1, Snail - 0\n\n if is_snake: # Snake list \n list = List()\n while random.randint(1, 100) != 1: # Should create another node\n list.insert(data=random.randint(1, 100))\n\n else: # Snail list\n list = List(Node(random.randint(1, 100)))\n start_of_loop = None\n curr_p = list.head\n\n # create until reaching start of loop\n while start_of_loop is None:\n\n # Set start of loop if not set yet\n if random.randint(1, 1000) <= 15 and start_of_loop is None:\n start_of_loop = curr_p\n else:\n list.insert(random.randint(1, 100))\n curr_p = curr_p.next\n\n # create until reaching last node\n while random.randint(1, 100) > 2:\n list.insert(random.randint(1, 100))\n curr_p = curr_p.next\n\n curr_p.next = start_of_loop # Close loop\n return list\n\n\ndef snake_or_snail(list):\n meet = False\n one_step = list.head\n two_step = list.head\n while one_step and two_step and two_step.next:\n if not meet: # Set first meeting - different pace\n one_step = one_step.next\n two_step = two_step.next.next\n if one_step == two_step:\n one_step = list.head\n meet = True\n else: # Set second meeting - same pace\n one_step = one_step.next\n two_step = two_step.next\n if one_step == two_step:\n return one_step\n return None\n\n\ndef print_list(head, start_of_loop):\n list_size = 0\n list_str = ''\n if start_of_loop:\n print(\"SNAIL LIST:\")\n current = head\n reached_loop = False\n loop_size = 0\n\n # Go through list until reaching start of loop for the second time\n while not (current == start_of_loop and reached_loop):\n list_size += 1\n\n # Print start of loop arrow\n if current == start_of_loop:\n reached_loop = True\n list_str = list_str[:-1]\n list_str += '↱'\n\n list_str += str(current.data) + '→'\n\n # Print end of loop arrow\n if current.next == start_of_loop and reached_loop:\n list_str = list_str[:-1]\n list_str += '↲'\n\n if reached_loop:\n loop_size += 1\n\n current = current.next\n\n print(\"Loop size: {0}\".format(loop_size))\n else:\n print(\"SNAKE LIST:\")\n current = head\n while current:\n list_size += 1\n list_str += str(current.data) + '→'\n current = current.next\n list_str += 'null'\n print(\"List size : {0}\".format(list_size))\n print(list_str)\n\n\nif __name__ == '__main__':\n list = create_list()\n start_of_loop = snake_or_snail(list)\n print_list(list.head, start_of_loop)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"62878963","text":"import numpy as np\nimport pylab as plt\nimport math\nfrom matplotlib import rcParams\n\nfig_width = 5 # width in inches\nfig_height = 4 # height in inches\nfig_size = [fig_width,fig_height]\nparams = {'backend': 'Agg',\n 'axes.labelsize': 10,\n 'axes.titlesize': 10,\n 'font.size': 10,\n 'xtick.labelsize': 10,\n 'ytick.labelsize': 10,\n 'figure.figsize': fig_size,\n 'savefig.dpi' : 600,\n 'font.family': 'sans-serif',\n 'axes.linewidth' : 0.5,\n 'xtick.major.size' : 2,\n 'ytick.major.size' : 2,\n 'font.size' : 8\n }\nrcParams.update(params)\n\nzArr = [1,2,3]\n\nfor z in zArr:\n me = 0.511\n ZA = 0.54141\n Io = 10/1000.0\n K = 0.307075\n alpha = 1.0/137.0\n rho = 1.023 #g/cm^3\n plasma = math.sqrt(rho*ZA)*28.816/1000 #MeV\n\n if z == 1:\n M = 938.0\n else:\n M = 2*z*938.0\n \n EneArr = np.logspace(1,15,100)\n\n xArr = []\n IonArr = []\n BremArr = []\n SumArr = []\n\n for Ene in EneArr:\n gamma = Ene/M + 1.0\n beta = math.sqrt(gamma*gamma-1)/gamma\n Tmax = 2*me*beta*gamma*beta*gamma/(1+2*gamma*me/M + (me/M)**2)\n\n delta = math.log(plasma/Io) + math.log(beta*gamma)-0.5\n\n Ion = math.fabs(K*(z**2)*(ZA)*(1/beta**2)*(0.5*math.log(2*me*beta*beta*gamma*gamma*Tmax/(Io**2)) - beta*beta - delta))\n\n # xArr.append(gamma*beta)\n xArr.append((Ene/1000.0))\n\n IonArr.append(math.log10(Ion))\n\n plt.plot(xArr,IonArr)\nplt.xscale('log')\n# plt.yscale('log')\n# plt.ylim(0,2)\nplt.xlim(0.25,1e6)\nplt.xlabel(r'$\\beta \\gamma$')\nplt.ylabel(' -dE/dx (arib units)')\n# plt.ylabel(r'$-\\frac{dE}{dx}$ (arib units)')\nplt.savefig('test_eneLoss.pdf',bbox_inches='tight')","sub_path":"figures/Chapter4/ene_loss.py","file_name":"ene_loss.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"411796332","text":"import pygame\nimport numpy\nfrom Limits import *\nfrom particle import *\n\nwidth = 800\nheight = 800\nsize = (width, height)\n\nclass Display:\n def __init__(self):\n pygame.init()\n self.screen = pygame.display.set_mode(size)\n \n #Random walls\n self.walls = []\n for i in range(5):\n \n x1 = numpy.random.randint(0, width)\n y1 = numpy.random.randint(0, height)\n \n x2 = numpy.random.randint(0, width)\n y2 = numpy.random.randint(0, height)\n \n x3 = numpy.random.randint(0, width)\n y3 = numpy.random.randint(0, height)\n \n self.walls.append(Limits(x1, y1, x2, y2))\n \n self.walls.append(Limits(0, 0, width, 0))\n self.walls.append(Limits(0, 0, 0, height))\n self.walls.append(Limits(0, height, width, height))\n self.walls.append(Limits(width, 0, width, height))\n self.particle = Particle()\n \n self.stop = False\n self.clock = pygame.time.Clock()\n \n def Draw(self):\n for wall in self.walls:\n wall.display(self.screen)\n self.particle.display(self.screen)\n \n def run(self):\n while not self.stop:\n self.screen.fill((0,0,0))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n self.stop = True\n \n #get the mouse position\n \n pos = pygame.mouse.get_pos()\n self.particle.pos[0] = pos[0]\n self.particle.pos[1] = pos[1] \n \n self.particle.look(self.screen, self.walls)\n self.Draw()\n self.clock.tick(100)\n pygame.display.update()\n \n pygame.quit()\n \nif __name__ == '__main__':\n a = Display()\n a.run()\n \n ","sub_path":"ray_casting.py","file_name":"ray_casting.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"595494715","text":"from __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nplt.style.use('fivethirtyeight')\nplt.rc('text', usetex=True)\n\ndef p1(x, lam):\n mask = x<0\n res = np.exp(-x/lam) / lam\n\n if np.sum(mask) > 0:\n res[mask] = 0\n\n return res\n\ndef p2(x):\n mask = (x<0)+(x>np.pi/2)\n res = np.sin(x)\n\n if np.sum(mask) > 0:\n res[mask] = 0\n return res\n\n#Graficos de las distribuciones\nx1 = np.linspace(-5, 50, 1000)\nla = np.arange(3,13,3)\ny1 = np.zeros((len(la),len(x1)))\n\n#Se generan los numeros aleatorios\nran = np.random.rand(10000)\n\naft2 = np.arccos(1.-ran)\naft1 = np.array([-l*np.log(1. - ran) for l in la])\n\nfor i in range(y1.shape[0]):\n for j in xrange(y1.shape[1]):\n y1[i] = p1(x1, la[i])\n\nx2 = np.linspace(-2*np.pi,2*np.pi,1000)\ny2 = p2(x2)\nfig, ax = plt.subplots(figsize=[4*1.5, 3*1.5])\nh, = ax.plot(x2, y2, lw=2)\nax.hist(aft2, bins=np.arange(0,2*np.pi,np.pi/20), normed=True, alpha=.4, color=h.get_color())\nax.set_xlim(-np.pi/4,3*np.pi/4)\nax.set_ylim(-0.1,1.1)\nax.set_xlabel(u'$x$')\nax.set_ylabel(u'$p_2(x)$')\nfig.tight_layout()\nfig.savefig('p2f2.png', dpi=300)\n\nfig, ax = plt.subplots(figsize=[4*1.5, 3*1.5])\nfor i in range(len(la)):\n h, = ax.plot(x1, y1[i], lw=2, label=u'$\\lambda = %d$' %la[i])\n ax.hist(aft1[i], bins=np.arange(100), normed=True, alpha=.4, color=h.get_color())\nax.set_xlim(-1,15)\nax.set_ylim(-0.05,0.35)\nax.set_xlabel(u'$x$')\nax.set_ylabel(u'$p_1(x)$')\nax.legend()\nfig.tight_layout()\nfig.savefig('p2f1.png', dpi=300)\n","sub_path":"Tarea 3/t3p2.py","file_name":"t3p2.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"201742369","text":"from django.urls import path\nfrom .views import NoteList, CreateObj, DeleteNote, SharedNoteListView, ShareNoteView, UnShareNoteView\n\napp_name = 'note'\n\nurlpatterns = [\n path('', NoteList.as_view(), name=\"index\"),\n path('note/create/', CreateObj.as_view(), name='create'),\n path('note/delete_note//', DeleteNote.as_view(), name='delete_note'),\n path('shared-note-list/', SharedNoteListView.as_view(), name='shared-note-list'),\n path('share-note/', ShareNoteView.as_view(), name='share-note'),\n path('unshare-note/', UnShareNoteView.as_view(), name='unshare-note'),\n]\n","sub_path":"zDjango_HW38/mylist/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"326677313","text":"from hdlConvertor.to.json import ToJson\nfrom hdlConvertor.hdlAst._bases import iHdlObj\nfrom hdlConvertor.hdlAst._defs import HdlIdDef\nfrom hdlConvertor.hdlAst._expr import HdlDirection\n\n\nclass ToJsonDebug(ToJson):\n \"\"\"\n HdlConverto AST -> json (dict/list/str/int/None composed object)\n An ivalid object are converted to str using its __repr__()\n \"\"\"\n def visit_HdlIdDef(self, o):\n try:\n return ToJson.visit_HdlIdDef(self, o)\n except Exception:\n if isinstance(o, HdlIdDef):\n raise\n return repr(o)\n\n def visit_HdlDirection(self, o):\n if not isinstance(o, HdlDirection):\n return repr(o)\n else:\n return super(ToJsonDebug, self).visit_HdlDirection(o)\n\n def visit_iHdlExpr(self, o):\n \"\"\"\n :type o: iHdlExpr\n :return: iHdlExpr\n \"\"\"\n try:\n return super(ToJsonDebug, self).visit_iHdlExpr(o)\n except Exception:\n if o.__class__.__repr__ is iHdlObj.__repr__:\n # in order to prevent infinite loop if there is something\n # wrong in serializer code itself\n raise\n return repr(o)\n\n\nif __name__ == \"__main__\":\n import os\n from hdlConvertor.language import Language\n from hdlConvertor import HdlConvertor\n from pprint import pprint\n BASE_DIR = os.path.join(os.path.dirname(__file__), \"..\", \"..\")\n TEST_DIR = os.path.join(BASE_DIR, 'tests', 'verilog')\n c = HdlConvertor()\n filenames = [os.path.join(TEST_DIR, \"arbiter_tb.v\")]\n d = c.parse(filenames, Language.VERILOG, [], False, True)\n tv = ToJson()\n res = tv.visit_HdlContext(d)\n pprint(res)\n","sub_path":"hdlConvertor/to/json_debug.py","file_name":"json_debug.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"188670995","text":"# -*- coding: utf-8 -*-\nprint('=' * 40)\nprint(__file__)\nfrom helper.textool import get_tmp_file\n\n################################################################################\nimport os, mapnik\nfrom gispy_helper import renderit\nshpfile='/gdata/fig_data/fig_data_poly.shp'\npolygon_symbolizer = mapnik.PolygonSymbolizer()\npolygon_symbolizer.fill = mapnik.Color('#f2eff9')\nline_symbolizer = mapnik.LineSymbolizer()\nsymbolizer = mapnik.PointSymbolizer()\nm = renderit(point_sym=symbolizer, line_sym=line_symbolizer, poly_sym=polygon_symbolizer,shpfile=shpfile)\nm.zoom_all()\n\n# mapnik.render_to_file(m, 'xx_point_sym1.png')\n\nmapnik.render_to_file(m, get_tmp_file(__file__, '1'), 'png')\nmapnik.render_to_file(m, get_tmp_file(__file__, '1',file_ext='pdf'), 'pdf')\n\n################################################################################\nsymbolizer.file = '/gdata/fig_data/turtle.png'\nsymbolizer.opacity = .8\nm = renderit(point_sym=symbolizer, line_sym=line_symbolizer, poly_sym=polygon_symbolizer,shpfile=shpfile)\nm.zoom_all()\n\n# mapnik.render_to_file(m, 'xx_point_sym2.png')\n\nmapnik.render_to_file(m, get_tmp_file(__file__, '2'), 'png')\nmapnik.render_to_file(m, get_tmp_file(__file__, '2',file_ext='pdf'), 'pdf')\n\n################################################################################\n\n################################################################################\n\n################################################################################\n\n################################################################################\n","sub_path":"part010/ch07_mapnik/sec4_mapnik_symbols/sub5_point/test_5_symbol_point_x_x.py","file_name":"test_5_symbol_point_x_x.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"575958324","text":"# -*- coding:utf-8 -*- \n# Call module: call functions with ropchains \n\nfrom ropgenerator.IO import string_special, string_bold, banner, error, string_ropg\nfrom ropgenerator.Constraints import Constraint, Assertion, BadBytes, RegsNotModified\nfrom ropgenerator.Load import loadedBinary\nfrom ropgenerator.exploit.Scanner import getFunctionAddress, getAllFunctions\nfrom ropgenerator.semantic.ROPChains import ROPChain, validAddrStr\nfrom ropgenerator.semantic.Engine import search \nfrom ropgenerator.Database import QueryType\nfrom ropgenerator.exploit.Utils import popMultiple\nimport ropgenerator.Architecture as Arch\n\n###################\n# CALL COMMAND # \n###################\n\nOPTION_OUTPUT = '--output-format'\nOPTION_OUTPUT_SHORT = '-f'\n# Options for output\nOUTPUT_CONSOLE = 'console'\nOUTPUT_PYTHON = 'python'\nOUTPUT_RAW = 'raw'\nOUTPUT = None # The one choosen \n\nOPTION_BAD_BYTES = '--bad-bytes'\nOPTION_BAD_BYTES_SHORT = '-b'\n\nOPTION_CALL = \"--call\"\nOPTION_CALL_SHORT = \"-c\"\n\nOPTION_KEEP_REGS = '--keep-regs'\nOPTION_KEEP_REGS_SHORT = '-k'\n\nOPTION_LIST = \"--list\"\nOPTION_LIST_SHORT = \"-l\"\n\nOPTION_HELP = \"--help\"\nOPTION_HELP_SHORT = \"-h\"\n\nOPTION_SHORTEST = '--shortest'\nOPTION_SHORTEST_SHORT = '-s'\n\nOPTION_LMAX = '--max-length'\nOPTION_LMAX_SHORT = '-m'\n\n\nCMD_CALL_HELP = banner([string_bold(\"'call' command\"),\\\n string_special(\"(Call functions with ROPChains)\")])\nCMD_CALL_HELP += \"\\n\\n\\t\"+string_bold(\"Usage:\")+\\\n\"\\n\\t\\tcall [OPTIONS]\"\nCMD_CALL_HELP += \"\\n\\n\\t\"+string_bold(\"Options\")+\":\"\nCMD_CALL_HELP += \"\\n\\t\\t\"+string_special(OPTION_CALL_SHORT)+\",\"+\\\n string_special(OPTION_CALL)+\" \\t Call a function\"\nCMD_CALL_HELP += \"\\n\\n\\t\\t\"+string_special(OPTION_BAD_BYTES_SHORT)+\",\"+string_special(OPTION_BAD_BYTES)+\" \\t Bad bytes for payload.\\n\\t\\t\\t\\t\\t Expected format is a list of bytes \\n\\t\\t\\t\\t\\t separated by comas (e.g '-b 0A,0B,2F')\"\nCMD_CALL_HELP += \"\\n\\n\\t\\t\"+string_special(OPTION_KEEP_REGS_SHORT)+\",\"+string_special(OPTION_KEEP_REGS)+\" \\t Registers that shouldn't be modified.\\n\\t\\t\\t\\t\\t Expected format is a list of registers \\n\\t\\t\\t\\t\\t separated by comas (e.g '-k edi,eax')\"\nCMD_CALL_HELP += \"\\n\\n\\t\\t\"+string_special(OPTION_LMAX_SHORT)+\",\"+string_special(OPTION_LMAX)+\" \\t Max length of the ROPChain in bytes\"\nCMD_CALL_HELP += \"\\n\\n\\t\\t\"+string_special(OPTION_SHORTEST_SHORT)+\",\"+string_special(OPTION_SHORTEST)+\"\\t\\t Find the shortest matching ROP-Chains\"\nCMD_CALL_HELP += \"\\n\\n\\t\\t\"+string_special(OPTION_LIST_SHORT)+\",\"+\\\n string_special(OPTION_LIST)+\"\\t\\t List available functions\"\nCMD_CALL_HELP += \"\\n\\n\\t\\t\"+string_special(OPTION_OUTPUT_SHORT)+\",\"+\\\n string_special(OPTION_OUTPUT)+\\\n \" Output format for ropchains.\\n\\t\\t\\t\\t\\t Expected format is one of the\\n\\t\\t\\t\\t\\t following: \"+\\\n string_special(OUTPUT_CONSOLE)+','+string_special(OUTPUT_PYTHON)\n \nCMD_CALL_HELP += \"\\n\\n\\t\\t\"+string_special(OPTION_HELP_SHORT)+\",\"+string_special(OPTION_HELP)+\"\\t\\t Show this help\"\nCMD_CALL_HELP += \"\\n\\n\\t\"+string_bold(\"Function format\")+\": \"+\\\n string_special(\"function\")+\"( \"+string_special(\"arg1\")+\",\"+string_special(\" ...\")+\\\n \",\" + string_special(\" argN\")+\")\"\nCMD_CALL_HELP += \"\\n\\n\\t\"+string_bold(\"Examples\")+\": \"+\\\n \"\\n\\t\\tcall strcpy(0x123456, 0x987654)\"\n \ndef print_help():\n print(CMD_CALL_HELP)\n\n\ndef call(args):\n global OUTPUT, OUTPUT_CONSOLE, OUTPUT_PYTHON\n # Parsing arguments\n if( not args):\n print_help()\n return\n OUTPUT = OUTPUT_CONSOLE\n funcName = None\n i = 0\n seenOutput = False\n seenFunction = False\n seenBadBytes = False\n seenKeepRegs = False\n seenShortest = False\n seenLmax = False\n clmax = None\n \n constraint = Constraint()\n assertion = Assertion()\n while i < len(args):\n if( args[i] in [OPTION_LIST, OPTION_LIST_SHORT]):\n func_list = getAllFunctions()\n print_functions(func_list)\n return \n if( args[i] in [OPTION_BAD_BYTES, OPTION_BAD_BYTES_SHORT]):\n if( seenBadBytes ):\n error(\"Error. '\" + args[i] + \"' option should be used only once\")\n return \n if( i+1 >= len(args)):\n error(\"Error. Missing bad bytes after option '\"+args[i]+\"'\")\n return \n seenBadBytes = True\n (success, res) = parse_bad_bytes(args[i+1])\n if( not success ):\n error(res)\n return\n i = i+2\n constraint = constraint.add(BadBytes(res))\n elif( args[i] in [OPTION_KEEP_REGS, OPTION_KEEP_REGS_SHORT]):\n if( seenKeepRegs ):\n error(\"Error. '\" + args[i] + \"' option should be used only once\")\n return \n if( i+1 >= len(args)):\n error(\"Error. Missing register after option '\"+args[i]+\"'\")\n return \n seenKeepRegs = True\n (success, res) = parse_keep_regs(args[i+1])\n if( not success ):\n error(res)\n return\n i = i+2\n constraint = constraint.add(RegsNotModified(res))\n elif( args[i] in [OPTION_CALL, OPTION_CALL_SHORT] ):\n if( not loadedBinary() ):\n error(\"Error. You should load a binary before building ROPChains\")\n return \n elif( seenFunction ):\n error(\"Option '{}' should be used only once\".format(args[i]))\n return \n userInput = ''\n i +=1\n while( i < len(args) and args[i][0] != \"-\"):\n userInput += args[i]\n i += 1\n (funcName, funcArgs ) = parseFunction(userInput)\n if( not funcName):\n return \n seenFunction = True\n elif( args[i] in [OPTION_OUTPUT, OPTION_OUTPUT_SHORT]):\n if( seenOutput ):\n error(\"Option '{}' should be used only once\".format(args[i]))\n return \n if( i+1 >= len(args)):\n error(\"Error. Missing output format after option '\"+args[i]+\"'\")\n return \n if( args[i+1] in [OUTPUT_CONSOLE, OUTPUT_PYTHON]):\n OUTPUT = args[i+1]\n seenOutput = True\n i += 2\n else:\n error(\"Error. Unknown output format: {}\".format(args[i+1]))\n return \n elif( args[i] in [OPTION_SHORTEST, OPTION_SHORTEST_SHORT]):\n if( seenShortest ):\n error(\"Option '{}' should be used only once\".format(args[i]))\n return \n seenShortest = True\n i += 1\n elif( args[i] == OPTION_LMAX or args[i] == OPTION_LMAX_SHORT ):\n if( seenLmax ):\n error(\"Option '{}' should be used only once\".format(args[i]))\n return \n if( i+1 >= len(args)):\n error(\"Error. Missing length after option '\"+args[i]+\"'\")\n return \n try:\n clmax = int(args[i+1])\n if( clmax < Arch.octets() ):\n raise Exception()\n # Convert number of bytes into number of ropchain elements\n clmax /= Arch.octets()\n except:\n error(\"Error. '\" + args[i+1] +\"' bytes is not valid\")\n return \n i += 2 \n seenLmax = True\n elif( args[i] in [OPTION_HELP, OPTION_HELP_SHORT]):\n print_help()\n return \n else:\n error(\"Error. Unknown option '{}'\".format(args[i]))\n return \n \n if( not funcName ):\n error(\"Missing function to call\")\n else:\n res = build_call(funcName, funcArgs, constraint, assertion, clmax=clmax, optimizeLen=seenShortest)\n if( isinstance(res, str) ):\n error(res)\n else:\n print_chains([res], \"Built matching ROPChain\", constraint.getBadBytes())\n\ndef build_call(funcName, funcArgs, constraint, assertion, argsDescription=None, clmax=None, optimizeLen=False):\n \"\"\"\n funcArgs : list of pairs (arg_value, arg_description)\n \"\"\"\n # Merge description and args \n if( argsDescription ):\n funcArgs = zip(funcArgs, argsDescription)\n else:\n funcArgs = [(arg,) for arg in funcArgs]\n \n if( Arch.currentBinType == Arch.BinaryType.X86_ELF ):\n return build_call_linux86(funcName, funcArgs, constraint, assertion, clmax, optimizeLen)\n elif( Arch.currentBinType == Arch.BinaryType.X64_ELF ):\n return build_call_linux64(funcName, funcArgs, constraint, assertion, clmax, optimizeLen)\n return []\n \ndef build_call_linux64(funcName, funcArgs, constraint, assertion, clmax=None, optimizeLen=False):\n # Arguments registers \n # (Args should go in these registers for x64)\n argsRegsNames = ['rdi','rsi','rdx','rcx', 'r8', 'r9']\n argsRegs = [Arch.n2r(name) for name in argsRegsNames]\n # Find the address of the fonction \n (funcName2, funcAddr) = getFunctionAddress(funcName)\n if( funcName2 is None ):\n return \"Couldn't find function '{}' in the binary\".format(funcName)\n \n # Check if bad bytes in function address \n if( not constraint.badBytes.verifyAddress(funcAddr) ):\n return \"'{}' address ({}) contains bad bytes\".format(funcName2, string_special('0x'+format(funcAddr, '0'+str(Arch.octets()*2)+'x')))\n \n # Check how many arguments \n if( len(funcArgs) > 6 ):\n return \"Doesn't support function call with more than 6 arguments with Linux X64 calling convention :(\"\n \n # Find a gadget for the fake return address\n if( funcArgs ):\n # Build the ropchain with the arguments\n args_chain = popMultiple(map(lambda x,y:(x,)+y, argsRegs[:len(funcArgs)], funcArgs), constraint, assertion, clmax=clmax, optimizeLen=optimizeLen)\n if( not args_chain):\n return \"Couldn't load arguments in registers\"\n else:\n # No arguments \n args_chain = ROPChain()\n \n # Build call chain (function address + fake return address)\n return args_chain.addPadding(funcAddr, comment=string_ropg(funcName2))\n \n\ndef build_call_linux86(funcName, funcArgs, constraint, assertion, clmax=None, optimizeLen=False):\n # Find the address of the fonction \n (funcName2, funcAddr) = getFunctionAddress(funcName)\n if( funcName2 is None ):\n return \"Couldn't find function '{}' in the binary\".format(funcName)\n \n # Check if bad bytes in function address \n if( not constraint.badBytes.verifyAddress(funcAddr) ):\n return \"'{}' address ({}) contains bad bytes\".format(funcName2, string_special('0x'+format(funcAddr, '0'+str(Arch.octets()*2)+'x')))\n \n # Check if lmax too small\n if( (1 + len(funcArgs) + (lambda x: 1 if len(x)>0 else 0)(funcArgs)) > clmax ):\n return \"Not enough bytes to call function '{}'\".format(funcName)\n \n # Find a gadget for the fake return address\n if( funcArgs ):\n offset = (len(funcArgs)-1)*Arch.octets() # Because we do +octets() at the beginning of the loop\n skip_args_chains = []\n i = 4 # Try 4 more maximum \n while( i > 0 and (not skip_args_chains)):\n offset += Arch.octets() \n skip_args_chains = search(QueryType.MEMtoREG, Arch.ipNum(), \\\n (Arch.spNum(),offset), constraint, assertion, n=1, optimizeLen=optimizeLen)\n i -= 1\n \n if( not skip_args_chains ):\n return \"Couldn't build ROP-Chain\"\n skip_args_chain = skip_args_chains[0]\n else:\n # No arguments \n skip_args_chain = None\n \n # Build the ropchain with the arguments \n args_chain = ROPChain()\n arg_n = len(funcArgs)\n for arg in reversed(funcArgs):\n if( isinstance(arg, int) ):\n args_chain.addPadding(arg, comment=\"Arg{}: {}\".format(arg_n, string_ropg(hex(arg))))\n arg_n -= 1\n else:\n return \"Type of argument '{}' not supported yet :'(\".format(arg)\n \n # Build call chain (function address + fake return address)\n call_chain = ROPChain()\n call_chain.addPadding(funcAddr, comment=string_ropg(funcName2))\n if( funcArgs ):\n skip_args_addr = int( validAddrStr(skip_args_chain.chain[0], constraint.getBadBytes(), Arch.bits()) ,16)\n call_chain.addPadding(skip_args_addr, comment=\"Address of: \"+string_bold(str(skip_args_chain.chain[0])))\n \n return call_chain.addChain(args_chain)\n \ndef parseFunction(string):\n def seek(char, string):\n for i in range(0, len(string)):\n if string[i] == char:\n return (string[:i], i)\n return ([],-1)\n \n if( not string ):\n error(\"Missing fuction to call\")\n return (None, None)\n \n # COmpress the string\n string = \"\".join(string.split())\n \n # Get the function name \n (funcName, index) = seek(\"(\", string)\n if( not funcName ):\n error(\"Invalid function call\")\n return (None, None)\n rest = string[index+1:]\n args = []\n arg = ''\n i = 0\n end = False\n while(i < len(rest)):\n c = rest[i]\n # No args\n if( c == \")\" and not args):\n end = True\n i += 1\n # String\n elif( c == '\"' or c == \"'\" ):\n (s, index)= seek(c, rest[i+1:])\n if( not s ):\n error(\"Missing closing {} for string\".format(c))\n return (None, None)\n args.append(s)\n i += index +2\n if( i >= len(rest)):\n error(\"Error. Missing ')'\")\n return (None, None)\n elif( rest[i] == ')' ):\n end = True\n i += 1\n elif( rest[i] == \",\" ):\n i += 1\n # Constant\n else:\n # Get the constant \n arg = ''\n ok = False\n for j in range(i, len(rest)):\n if( rest[j] == \")\" ):\n end = True\n ok = True\n break\n elif( rest[j] == ','):\n ok = True\n break\n else:\n arg += rest[j]\n if( not ok ):\n error(\"Missing ')' after argument\")\n return (None, None)\n if( (not arg) and args):\n error(\"Missing argument\")\n return (None, None)\n # Convert to int \n try:\n value = int(arg)\n except:\n try:\n value = int(arg, 16)\n except:\n try:\n value = int(arg, 2)\n except:\n error(\"Invalid operand: \" + arg )\n return (None, None)\n args.append(value)\n i = j+1\n if( end):\n break\n \n if( not end ):\n error(\"Error. Missing ')'\")\n return (None, None) \n if( i < len(rest)):\n error(\"Error. Extra argument: {}\".format(rest[i:]))\n return (None, None)\n\n return (funcName, args)\n\n## ------------\n## Parsing from ropgenerator.semantic.Find\ndef parse_bad_bytes(string):\n \"\"\"\n Parses a bad bytes string into a list of bad bytes\n Input: a string of format like \"00,0A,FF,32,C7\"\n Ouput if valid string : (True, list) where list = \n ['00', '0a', 'ff', '32', 'c7'] (separate them in individual strings\n and force lower case)\n Output if invalid string (False, error_message)\n \"\"\"\n hex_chars = '0123456789abcdefABCDEF'\n i = 0\n bad_bytes = []\n user_bad_bytes = [b.lower() for b in string.split(',')]\n for user_bad_byte in user_bad_bytes:\n if( not user_bad_byte ):\n return (False, \"Error. Missing bad byte after ','\")\n elif( len(user_bad_byte) != 2 ):\n return (False, \"Error. '{}' is not a valid byte\".format(user_bad_byte))\n elif( not ((user_bad_byte[i] in hex_chars) and (user_bad_byte[i+1] in hex_chars))):\n return (False, \"Error. '{}' is not a valid byte\".format(user_bad_byte))\n else:\n bad_bytes.append(user_bad_byte)\n return (True, bad_bytes)\n \ndef parse_keep_regs(string):\n \"\"\"\n Parses a 'keep registers' string into a list of register uids\n Input: a string of format like \"rax,rcx,rdi\"\n Output if valid string (True, list) where list = \n [1, 3, 4] (R1 is rax, R3 is RCX, ... )\n Output if invalid string (False, error_message)\n \"\"\"\n user_keep_regs = string.split(',')\n keep_regs = set()\n for reg in user_keep_regs:\n if( reg in Arch.regNameToNum ):\n keep_regs.add(Arch.n2r(reg))\n else:\n return (False, \"Error. '{}' is not a valid register\".format(reg))\n return (True, list(keep_regs))\n\n##########################\n# Pretty print functions #\n##########################\n\ndef print_chains(chainList, msg, badBytes=[]):\n global OUTPUT\n sep = \"------------------\"\n if( chainList):\n print(string_bold('\\n\\t'+msg))\n if( OUTPUT == OUTPUT_CONSOLE ):\n print(\"\\n\"+chainList[0].strConsole(Arch.currentArch.bits, badBytes))\n elif( OUTPUT == OUTPUT_PYTHON ):\n print('\\n' + chainList[0].strPython(Arch.currentArch.bits, badBytes))\n for chain in chainList[1:]:\n if( OUTPUT == OUTPUT_CONSOLE ):\n print('\\t'+sep + \"\\n\"+ chain.strConsole(Arch.currentArch.bits, badBytes))\n elif( OUTPUT == OUTPUT_PYTHON ):\n print('\\t'+sep + '\\n' + chain.strPython(Arch.currentArch.bits, badBytes))\n else:\n print(string_bold(\"\\n\\tNo matching ROPChain found\"))\n\ndef print_functions(func_list):\n \"\"\"\n func_list - list of pairs (str, int) = (funcName, funcAddress)\n \"\"\"\n space = 28\n print(banner([string_bold(\"Available functions\")]))\n print(\"\\tFunction\" + \" \"*(space-8) + \"Address\")\n print(\"\\t------------------------------------\")\n for (funcName, funcAddr) in sorted(func_list, key=lambda x:x[0] ):\n space2 = space - len(funcName)\n if( space2 < 0 ):\n space2 = 2\n print(\"\\t\"+string_special(funcName)+ \" \"*space2 + hex(funcAddr))\n print(\"\")\n \n","sub_path":"ropgenerator/exploit/Call.py","file_name":"Call.py","file_ext":"py","file_size_in_byte":18194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"371923382","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n[Deobfuscate WhatsApp Strings, (c) B. Kerler 2016]\n- Example JEB2 Plugin for >= V2.2.1 -\n* Change key values from switch statements, run plugin using Scripts/Run scripts with Source Tab open (Bytecode won't work), then close and reopen Source Tab to see decrypted strings *\n** Tested with Whatsapp Version 4.5.1077 **\n\"\"\"\n\nfrom com.pnfsoftware.jeb.client.api import IScript, IGraphicalClientContext\nfrom com.pnfsoftware.jeb.core import RuntimeProjectUtil\nfrom com.pnfsoftware.jeb.core.units.code import ICodeItem\nfrom com.pnfsoftware.jeb.core.units.code.android import IDexUnit\nfrom com.pnfsoftware.jeb.core.units.code.java import IJavaSourceUnit, IJavaStaticField, IJavaNewArray, IJavaConstant, IJavaCall, IJavaField, IJavaMethod, IJavaClass, IJavaArrayElt\n\n\nclass JEB2WhatsAppStringDecryptor(IScript):\n def run(self, ctx):\n self.keys = [12,18,85,49,116] #Change keys here (see switch statements), here it's for com.whatsapp-451077/util/a2\n\t\n engctx = ctx.getEnginesContext()\n if not engctx:\n print('Back-end engines not initialized')\n return\n\n projects = engctx.getProjects()\n if not projects:\n print('There is no opened project')\n return\n\n project = projects[0] # Get current project(IRuntimeProject)\n print('Decompiling code units of %s...' % project)\n\t\n self.dexunit = RuntimeProjectUtil.findUnitsByType(project, IDexUnit, False)[0] # Get dex context, needs >=V2.2.1\n self.currentunit = ctx.getFocusedView().getActiveFragment().getUnit() # Get current Source Tab in Focus\n javaclass = self.currentunit.getClassElement() # needs >V2.1.4\n curaddr=ctx.getFocusedView().getActiveFragment().getActiveAddress() # needs 2.1.4\n print('Current class: %s' % javaclass.getName())\n print('Current address: %s' % curaddr)\n self.cstbuilder = self.currentunit.getFactories().getConstantFactory() # we need a context to cstbuilder to replace strings\n self.processTargetClass(javaclass) #Call our main function\n\n def addstring(self,insn,pre): #This function gets Strings from dex instructions and decrypts them using given xor keys\n stringindex = insn.getParameters()[1].getValue() \n s=self.dexunit.getString(stringindex).getValue()\n s2=self.decode_string(s)\n if (stringindex not in self.stringlist):\n self.stringlist[stringindex]=s2\n if (pre not in self.resultlist):\n self.resultlist[pre]=s2\n print (\"Res[\"+hex(stringindex)+\"] Idx[\"+hex(pre)+\"]: \"+s2)\n\n def processTargetClass(self, javaClass):\n selclass=self.dexunit.getClass(javaClass.getName())\n addr=selclass.getAddress()\n print(\"%s\" % addr)\n code=self.getMethodName(selclass,'') #We need method, as encrypted strings are there being stored in an array\n self.stringlist = {}\n self.resultlist = {}\n lines=iter(code.getInstructions()) #get all instructions for \n idx=0\n self.searchname=\"\"\n\n for insn in lines: #Here we search for the array index for the encrypted strings, which is just before the strings as const field\n if (insn.getMnemonic()) in ('const/4','const/16'):\n pre=insn.getParameters()[1].getValue()\n insn=lines.next()\n if (insn.getMnemonic()) in ('const-string','const-string/jumbo'):\n idx=pre\n self.addstring(insn,idx)\n idx+=1\n elif (insn.getMnemonic()) in ('const-string','const-string/jumbo'):\n self.addstring(insn,idx)\n idx+=1\n\n for item in selclass.getFields(): #Here we locate the name of the string array we try to replace\n fsig = item.getSignature(1)\n if (fsig.endswith(':[LString;')):\n self.searchname=item.getName(1)\n break\n\n for methods in javaClass.getMethods(): #Get Methods from Source View and use AST to get elements\n block=methods.getBody()\n i=2\n while i < block.size():\n e = block.get(i)\n self.checkElement(block,e) #Check for our string array and replace with decrypted strings\n i+=1\n \n print('*********************** Finished ***********************')\n\n def checkElement(self, parent, e): #Here we search for our string array and replace with decrypted strings\n if isinstance(e, IJavaArrayElt):\n for sub in e.getSubElements():\n if isinstance(sub, IJavaStaticField): #Static field holds name for string array\n name=sub.getField().getName() #here name of string array\n if (name==self.searchname):\n index=e.getIndex().getInt()\t#string array index\n print(\"Replacing \"+name+\"[\"+hex(index)+\"]\")\n parent.replaceSubElement(e, self.cstbuilder.createString(self.resultlist[index])) #do our magic replace\n\n for sub in e.getSubElements(): #We need to parse all subelements, as we search down the ast tree for all string arrays whereever they may occur\n if isinstance(sub, IJavaClass) or isinstance(sub, IJavaField) or isinstance(sub, IJavaMethod):\n continue\n self.checkElement(e, sub)\n \n def getMethodName(self, javaClass, methodname):\n for statConst in javaClass.getMethods():\n if statConst.getName(0) == methodname:\n return statConst\n\n def decode_string(self,encoded_str):\n decoded_str = ''\n for i in range(len(encoded_str)):\n decoded_str += chr(ord(encoded_str[i]) ^ self.keys[i % 5])\n return decoded_str","sub_path":"scripts/analysis/JEB2WhatsAppStringDecryptor.py","file_name":"JEB2WhatsAppStringDecryptor.py","file_ext":"py","file_size_in_byte":5249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"43146339","text":"#!/usr/bin/python\n\nimport os\nimport sys\nimport yaml\n\ndef usage():\n print(\"\\nUsage: {0} \\n\".format(sys.argv[0]))\n sys.exit(1)\n\n\ndef print_value(value):\n if type(value) is dict:\n for key in value.keys():\n print(key)\n elif type(value) is list:\n for val in value:\n print(val)\n else:\n print(value)\n\n\ndef main():\n args_len = len(sys.argv)\n\n if args_len >= 2:\n\n filename = sys.argv[1]\n if not os.path.exists(filename):\n print(\"[ERROR] Can't find the file\")\n exit(1)\n\n yaml_vars = yaml.load(file(filename))\n\n if args_len == 2:\n print_value(yaml_vars)\n elif args_len == 3:\n print_value(yaml_vars[sys.argv[2]])\n elif args_len == 4:\n print_value(yaml_vars[sys.argv[2]][sys.argv[3]])\n elif args_len == 5:\n print_value(yaml_vars[sys.argv[2]][sys.argv[3]][sys.argv[4]])\n else:\n print(\"args length too long\")\n exit(1)\n else:\n usage()\n exit(1)\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/yc-yaml-get.py","file_name":"yc-yaml-get.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"384445376","text":"#!/usr/bin/python3\n# from coinbase.wallet.client import Client\nimport os\nimport requests\n\n# client = Client(\"test\", \"test\")\n\n# price = client.get_spot_price(currency_pair = 'BTC-USD', date = \"2019-07-18\")\n\ntester = requests.get('https://api.coindesk.com/v1/bpi/historical/close.json?start=2019-04-20&end=2019-07-16').json()\n\npricelist = \"\"\n\nwith open(\"prices.txt\", \"a\") as myfile:\n for key in tester['bpi']:\n pricelist = str(tester['bpi'][key]) + \"\\n\"\n myfile.write(pricelist)\n ","sub_path":"tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"365548866","text":"#!/usr/bin/env python3\n\nfrom __future__ import print_function\nimport sys\nif sys.version_info < (3,0):\n print(\"Error: Please run with python3\")\n sys.exit(1)\n\nimport pydronecode_sdk\nimport time\nimport threading\nimport signal\n\n\n\n\n# We use an event to tell the thread to stop again.\nshould_exit = threading.Event()\nthread = None\n\ndef signal_handler(sig, frame):\n print(\"You pressed Ctrl+C\")\n exit_script()\n\nsignal.signal(signal.SIGINT, signal_handler)\n\n\ndef exit_script():\n print(\"Exiting...\", end=\"\")\n should_exit.set()\n if thread:\n thread.join()\n print(\"done.\")\n sys.exit(0)\n\n\ndef listen_to_position(telemetry, should_exit):\n \"\"\"Just poll position and print it.\"\"\"\n while not should_exit.is_set():\n position = telemetry.position()\n print(\"Lat: {}, lon: {}, alt: {}\".format(\n position.latitude_deg,\n position.longitude_deg,\n position.relative_altitude_m))\n time.sleep(1)\n\n\ndef main():\n \"\"\"Connect, takeoff, and land again.\"\"\"\n dc = pydronecode_sdk.DronecodeSDK()\n\n dc.add_udp_connection(14540)\n # We need to wait to make sure a system connects in the meantime.\n time.sleep(2)\n\n if len(dc.system_uuids()) == 0:\n print(\"No system found\")\n sys.exit(1)\n\n if len(dc.system_uuids()) >= 2:\n print(\"More than one system found\")\n sys.exit(1)\n\n action = pydronecode_sdk.Action(dc.system())\n telemetry = pydronecode_sdk.Telemetry(dc.system())\n\n thread = threading.Thread(target=listen_to_position,\n args=(telemetry, should_exit))\n thread.start()\n\n action.set_takeoff_altitude(1.0)\n\n print(\"Arming...\", end=\"\")\n action.arm()\n print(\"done.\")\n\n print(\"Taking off...\", end=\"\")\n action.takeoff()\n print(\"done.\")\n\n # Let it hover briefly.\n time.sleep(5)\n\n print(\"Landing...\", end=\"\")\n action.land()\n print(\"done.\")\n\n exit_script()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/python_pybind_test.py","file_name":"python_pybind_test.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"525447901","text":"\n# **************************************************************************** #\n# #\n# ::: :::::::: #\n# run.py :+: :+: :+: #\n# +:+ +:+ +:+ #\n# By: ray +#+ +:+ +#+ #\n# +#+#+#+#+#+ +#+ #\n# Created: 2017/05/31 15:36:01 by jinjialiu #+# #+# #\n# Updated: 2017/05/31 15:37:20 by ray ### ########.fr #\n# #\n# **************************************************************************** #\n\nimport time\nimport unittest\n\nfrom app.config import config\nfrom app.constructor.create_case import CreateCase\nfrom app.constructor.use_case_operation import UseCaseOperation\nfrom app.controller.util import BSTestRunner\nfrom app.controller.util.xtest import TestReport, dict_encode_test_results\n\nCASE_PATH = CreateCase.create_unittest_files().get('case_path')\nREPORT_PATH = 'app/report/report.html'\n\n\ndef load_tests(loader, tests, pattern):\n \"\"\"\n Discover and load all unit tests in all files named\n ``test_*.py`` in ./src/app/\n \"\"\"\n start_time = time.time() # 测试启动的时刻点\n suite = unittest.defaultTestLoader.discover(CASE_PATH, pattern='test_*.py')\n if config.SWITCH:\n test_result = unittest.TextTestRunner().run(suite) # 运行测试套件,并返回测试结果\n total_time = time.time() - start_time # 测试过程整体的耗时\n test_res_dict = dict_encode_test_results(\n test_result,\n run_time=total_time,\n pro_version='1.0' # 当前被测试的系统的版本号,依据目前系统的信息,如果服务端提供接口,则可以做成自动化的\n )\n test_report = TestReport()\n auth_res = test_report.get_api_auth()\n if auth_res:\n test_report.post_unit_test_data(test_res_dict)\n else:\n raise PermissionError('auth error...')\n else:\n with open(REPORT_PATH, 'wb') as files:\n runner = BSTestRunner.BSTestRunner(\n files,\n title='TestReport_{0}'.format(int(time.time())),\n description=u'自动化生成用例测试'\n )\n runner.run(suite)\n\nif __name__ == '__main__':\n try:\n unittest.main()\n except TypeError:\n UseCaseOperation.clear_test_data()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"35472573","text":"import unittest\nimport os\nimport time\nimport threading\n\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\nfrom app import create_app, db\nfrom app.models import Product, Order, OrderProduct\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nfrom werkzeug.serving import make_server\n\nclass Ordering(unittest.TestCase):\n # Creamos la base de datos de test\n def setUp(self):\n self.app = create_app()\n self.app.config.update(\n SQLALCHEMY_DATABASE_URI='sqlite:///' + os.path.join(basedir, 'test.db'),\n SQLALCHEMY_TRACK_MODIFICATIONS=False,\n TESTING=True\n )\n\n self.app_context = self.app.app_context()\n self.app_context.push()\n\n self.baseURL = 'http://localhost:5000'\n\n db.session.commit()\n db.drop_all()\n db.create_all()\n\n self.t = threading.Thread(target=self.app.run)\n self.t.start()\n\n time.sleep(1)\n\n #self.driver = webdriver.Chrome() \n \n \n\n self.driver = webdriver.Edge()\n \n def test_title(self):\n driver = self.driver\n driver.get(self.baseURL)\n add_product_button = driver.find_element_by_xpath('/html/body/main/div[1]/div/button')\n add_product_button.click()\n modal = driver.find_element_by_id('modal')\n assert modal.is_displayed(), \"El modal no esta visible\"\n \n def test_modalEdit(self):\n \n driver = self.driver\n driver.get(self.baseURL)\n \n #Creo una orden\n orden = Order(id= 1)\n db.session.add(orden)\n \n #Creo un producto\n prod = Product(id= 1, name= 'Tenedor', price= 50)\n db.session.add(prod)\n\n #Creo el OrderProduct\n orderProduct = OrderProduct(order_id=1,product_id=1,quantity=1)\n db.session.add(orderProduct)\n db.session.commit()\n \n driver.get(self.baseURL)\n \n driver = self.driver \n driver.get(self.baseURL)\n nombreTabla=driver.find_element_by_xpath('//*[@id=\"orders\"]/table/tbody/tr[1]/td[2]').text\n cantidadTabla=driver.find_element_by_xpath('//*[@id=\"orders\"]/table/tbody/tr[1]/td[4]').text\n precioTotalTabla=driver.find_element_by_xpath('//*[@id=\"orders\"]/table/tbody/tr[1]/td[5]').text\n edit_product_button = driver.find_element_by_xpath('//*[@id=\"orders\"]/table/tbody/tr[1]/td[6]/button')\n edit_product_button.click()\n \n nombreModal = Select(driver.find_element_by_id('select-prod')).first_selected_option.text\n cantidadModal = driver.find_element_by_id('quantity').get_attribute('value')\n precioTotalModal= driver.find_element_by_id('total-price').text.replace(\"Precio total: $ \",\"\")\n assert cantidadTabla==cantidadModal, \"La cantidad no coincide\"\n assert nombreTabla==nombreModal, \"El nombre no coincide\"\n assert precioTotalTabla==precioTotalModal, \"El precio total no coincide\"\n\n def test_cantidades_negativas(self):\n driver = self.driver\n driver.get(self.baseURL)\n \n orden = Order(id= 1)\n db.session.add(orden)\n \n #Creo un producto\n prod = Product(id= 1, name= 'Tenedor', price= 50)\n db.session.add(prod)\n \n db.session.commit()\n \n \n driver.get(self.baseURL)\n \n add_product_button = driver.find_element_by_xpath('/html/body/main/div[1]/div/button')\n add_product_button.click()\n \n select = Select(driver.find_element_by_id('select-prod'))\n select.select_by_visible_text(\"Tenedor\")\n quantity= driver.find_element_by_id('quantity')\n quantity.clear()\n quantity.send_keys(\"-1\")\n save_button = driver.find_element_by_id('save-button')\n \n \n self.assertFalse(save_button.is_enabled(),\"No deberia habilitarse el boton guardar con cantidad negativa\")\n\n\n def test_repetidos_error(self):\n\n driver = self.driver\n driver.get(self.baseURL)\n \n orden = Order(id= 1)\n db.session.add(orden)\n \n #Creo un producto\n prod = Product(id= 1, name= 'Tenedor', price= 50)\n db.session.add(prod)\n\n #Creo el OrderProduct\n orderProduct = OrderProduct(order_id=1,product_id=1,quantity=1)\n db.session.add(orderProduct)\n db.session.commit()\n \n driver.get(self.baseURL)\n\n #intento agregar otro producto\n add_product_button = driver.find_element_by_xpath('/html/body/main/div[1]/div/button')\n add_product_button.click()\n \n select = Select(driver.find_element_by_id('select-prod'))\n select.select_by_visible_text(\"Tenedor\")\n quantity= driver.find_element_by_id('quantity')\n quantity.clear()\n quantity.send_keys(\"1\")\n\n save_button = driver.find_element_by_id('save-button')\n save_button.click()\n\n error= driver.find_element_by_id('errorSelect')\n time.sleep(1)\n assert(error.is_displayed())\n\n def test_eliminar_elemento(self):\n \n driver = self.driver\n driver.get(self.baseURL)\n \n #Creo una orden\n orden = Order(id= 1)\n db.session.add(orden)\n \n #Creo un producto\n prod = Product(id= 1, name= 'Tenedor', price= 50)\n db.session.add(prod)\n\n #Creo el OrderProduct\n orderProduct = OrderProduct(order_id=1,product_id=1,quantity=1)\n db.session.add(orderProduct)\n db.session.commit()\n \n driver.get(self.baseURL)\n \n \n nombreTabla1=driver.find_element_by_xpath('//*[@id=\"orders\"]/table/tbody/tr[1]/td[2]').text\n delete_product_button = driver.find_element_by_xpath('//*[@id=\"orders\"]/table/tbody/tr[1]/td[6]/button[2]')\n delete_product_button.click()\n driver.get(self.baseURL)\n nombreTabla2=driver.find_element_by_xpath('//*[@id=\"orders\"]/table/tbody/tr[1]/td[2]').text\n assert nombreTabla1!=nombreTabla2, \"No se borro el elemento\"\n \n def tearDown(self):\n self.driver.get('http://localhost:5000/shutdown')\n\n db.session.remove()\n db.drop_all()\n self.driver.close()\n self.app_context.pop()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n","sub_path":"test/test_e2e.py","file_name":"test_e2e.py","file_ext":"py","file_size_in_byte":6268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"357654780","text":"#!/usr/bin/env python\n#\n# Created by Samvel Khalatyan on Mar 27, 2014\n# Copyright (c) 2014 Samvel Khalatyan. All rights reserved\n#\n# Use of this source code is governed by a license that can be found in\n# the LICENSE file.\n\nimport unittest\n\nfrom lib import paths\nfrom lib import unigraph\n\nclass BFPaths(paths.BreadthFirstPaths):\n ''' Extend BFS paths: keep distances cached '''\n\n def __init__(self, graph, source_vertex):\n paths.BreadthFirstPaths.__init__(self, graph, source_vertex)\n\n # create a map of vertices and corresponding lengths\n self._distances = dict.fromkeys(self._paths.keys(), 0)\n for vertex in self._paths.keys():\n self._distances[vertex] = len(self.path_to(vertex))\n\n def distance_to(self, vertex):\n ''' return number of vertices in the path '''\n\n return self._distances[vertex] if vertex in self._distances else -1\n\nclass GraphProperties:\n def __init__(self, graph):\n self._eccentricies = dict.fromkeys(range(graph.vertices()), 0)\n\n for vertex in range(graph.vertices()):\n # build a map of paths\n paths_ = BFPaths(graph, vertex)\n self._eccentricies[vertex] = max(paths_._distances.values())\n\n self._diameter = max(self._eccentricies.values())\n self._radius = min(self._eccentricies.values())\n\n self._center = []\n for v, e in self._eccentricies.items():\n if e == self._radius:\n self._center.append(v)\n\n def eccentricity(self, vertex):\n ''' Eccentricity is the max length of shortest paths '''\n\n return self._eccentricies[vertex]\n\n def diameter(self):\n ''' max eccentricity in the graph '''\n\n return self._diameter\n\n def radius(self):\n ''' min eccentricity in the graph '''\n\n return self._radius\n\n def center(self):\n ''' a vertex(ies) who's eccentricity = radius '''\n\n return self._center\n\nclass GraphPropertiesTestCase1(unittest.TestCase):\n def setUp(self):\n graph = unigraph.Unigraph(7)\n graph.add_edge(0, 1)\n graph.add_edge(1, 2)\n graph.add_edge(1, 3)\n graph.add_edge(1, 5)\n graph.add_edge(3, 4)\n graph.add_edge(5, 6)\n\n self.graph = graph\n self.properties = GraphProperties(self.graph)\n\n def test_eccentricity(self):\n for vertex, eccentricity in ((0, 3),\n (1, 2),\n (2, 3),\n (3, 3),\n (4, 4),\n (5, 3),\n (6, 4)):\n self.assertEqual(eccentricity,\n self.properties.eccentricity(vertex),\n msg=(\"{0} vertex, \"\n \"{1} eccentricity\").format(vertex,\n eccentricity))\n\n def test_diameter(self):\n self.assertEqual(4, self.properties.diameter())\n\n def test_radius(self):\n self.assertEqual(2, self.properties.radius())\n\n def test_center(self):\n for vertex in [1]:\n self.assertIn(vertex, self.properties.center())\n\n\nclass GraphPropertiesTestCase2(unittest.TestCase):\n def setUp(self):\n graph = unigraph.Unigraph(7)\n graph.add_edge(0, 1)\n graph.add_edge(1, 2)\n graph.add_edge(1, 3)\n graph.add_edge(1, 4)\n graph.add_edge(1, 5)\n graph.add_edge(5, 6)\n\n self.graph = graph\n self.properties = GraphProperties(self.graph)\n\n def test_eccentricity(self):\n for vertex, eccentricity in ((0, 3),\n (1, 2),\n (2, 3),\n (3, 3),\n (4, 3),\n (5, 2),\n (6, 3)):\n self.assertEqual(eccentricity,\n self.properties.eccentricity(vertex),\n msg=(\"{0} vertex, \"\n \"{1} eccentricity\").format(vertex,\n eccentricity))\n\n def test_diameter(self):\n self.assertEqual(3, self.properties.diameter())\n\n def test_radius(self):\n self.assertEqual(2, self.properties.radius())\n\n def test_center(self):\n for vertex in [1, 5]:\n self.assertIn(vertex, self.properties.center())\n\n\nif \"__main__\" == __name__:\n unittest.main()\n","sub_path":"ch4/python/ch4_ex4.1.16.py","file_name":"ch4_ex4.1.16.py","file_ext":"py","file_size_in_byte":4598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"389121447","text":"#!/usr/bin/python\n\nimport os\nimport sys\n\ntemp_path = sys.path[0]\nif temp_path:\n sys.path.insert(0, os.path.join(temp_path, '..', '..'))\n\nimport logging\nimport logging.handlers\nimport binascii\nfrom SimEngine import SimEngine\nfrom SimCli import SimCli\n\nLOG_FORMAT = \"%(asctime)s [%(name)s:%(levelname)s] %(message)s\"\n\n#============================ logging =========================================\n\nlogFileName = 'logs/opensim.log'\nloghandler = logging.handlers.RotatingFileHandler(logFileName,\n maxBytes=2000000,\n backupCount=5,\n mode='w')\nloghandler.setFormatter(logging.Formatter(LOG_FORMAT))\n\n#============================ main ============================================\n\ndef main():\n \n # instantiate a SimEngine object\n simengine = SimEngine.SimEngine(loghandler)\n simengine.start()\n \n # instantiate the CLI interface\n cliHandler = SimCli.SimCli(simengine)\n cliHandler.start()\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"software/opensim/bin/opensim_cli/opensim_cli.py","file_name":"opensim_cli.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"132465556","text":"\"\"\"\n\nARMA Model\n===============================================================================\n\nOverview\n-------------------------------------------------------------------------------\n\nThis module contains ARMA models using SciPy's minimization method.\n\nExamples\n-------------------------------------------------------------------------------\n\nAR model using SciPy's minimization\n\nGet predicted values as a DataFrame:\n\nLoad time series\n>>> ts = load_champagne()\n\n>>> model = ARMA(p = 2, q = 3)\nARMA(p = 2, q = 3, intercept = None, phi = None, theta = None)\n\n>>> random.seed(1)\n>>> model.fit(ts) # doctest: +ELLIPSIS\nARMA(p = 2, q = 3, intercept = 2469..., phi = [-0.072... -0.620...], theta = [0.355... 0.589... 0.917...])\n\n>>> random.seed(1)\n>>> model.predict(ts, periods = 3) # doctest: +ELLIPSIS\n ci_inf ci_sup ... forecast real\n1972-10-01 3080... 9706... ... 5744... None\n1972-11-01 773... 9113... ... 4746... None\n1972-12-01 2063... 10183... ... 6043... None\n\n[3 rows x 6 columns]\n\n\n\"\"\"\n\nfrom skfore.models.BaseModel import BaseModel\n\nfrom sklearn import *\n\n\nclass ARMA(BaseModel):\n \"\"\" Moving-average model\n\n Parameter optimization method: scipy's minimization\n\n Args:\n p (int): AR order\n q (int): MA order\n intercept (boolean or double): False for set intercept to 0 or double\n phi (array): array of p-length for set parameters without optimization\n theta (array): array of q-length for set parameters without optimization\n\n\n Returns:\n ARMA model structure of order p,q\n\n \"\"\"\n\n def __init__(self, p=None, q=None, intercept=None, phi=None, theta=None):\n self.y = None\n\n if p == None:\n self.p = 0\n else:\n self.p = p\n\n if q == None:\n self.q = 0\n else:\n self.q = q\n\n if intercept == None:\n self.intercept = None\n elif intercept == False:\n self.intercept = 0\n else:\n self.intercept = intercept\n\n if phi == None:\n self.phi = None\n else:\n self.phi = phi\n\n if theta == None:\n self.theta = None\n else:\n self.theta = theta\n\n if intercept == None and theta == None and phi == None:\n self.optim_type = 'complete'\n elif intercept == None and theta != None and phi != None:\n self.optim_type = 'optim_intercept'\n elif intercept == False and theta == None and phi == None:\n self.optim_type = 'no_intercept'\n elif intercept != None and theta == None and phi == None:\n self.optim_type = 'optim_params'\n elif intercept != None and theta != None and phi != None:\n self.optim_type = 'no_optim'\n else:\n raise ValueError('Please fulfill all parameters')\n\n\n def __repr__(self):\n return 'ARMA(p = ' + str(self.p) + ', q = ' + str(self.q) + ', intercept = ' + str(self.intercept) + ', phi = ' + str(self.phi) + ', theta = ' + str(self.theta) +')'\n\n\n def params2vector(self):\n \"\"\" Parameters to vector\n\n Args:\n None.\n\n Returns:\n Vector parameters of length p+q+1 to use in optimization.\n\n \"\"\"\n params = list()\n if self.intercept == None:\n self.intercept = numpy.random.rand(1)[0]\n if self.phi == None:\n self.phi = numpy.random.rand(self.p)\n if self.theta == None:\n self.theta = numpy.random.rand(self.q)\n\n if self.optim_type == 'complete':\n params.append(self.intercept)\n for i in range(len(self.phi)):\n params.append(self.phi[i])\n for i in range(len(self.theta)):\n params.append(self.theta[i])\n return params\n elif self.optim_type == 'no_intercept' or self.optim_type == 'optim_params':\n for i in range(len(self.phi)):\n params.append(self.phi[i])\n for i in range(len(self.theta)):\n params.append(self.theta[i])\n return params\n elif self.optim_type == 'optim_intercept':\n params.append(self.intercept)\n return params\n elif self.optim_type == 'no_optim':\n pass\n\n\n def vector2params(self, vector):\n \"\"\" Vector to parameters\n\n Args:\n\n Returns:\n self\n\n \"\"\"\n\n if self.optim_type == 'complete':\n self.intercept = vector[0]\n self.phi = vector[1:self.p + 1]\n self.theta = vector[self.p + 1:]\n elif self.optim_type == 'no_intercept' or self.optim_type == 'optim_params':\n self.phi = vector[0:self.p]\n self.theta = vector[self.p:]\n elif self.optim_type == 'optim_intercept':\n self.intercept = vector[0]\n elif self.optim_type == 'no_optim':\n pass\n\n return self\n\n def forecast(self, ts):\n \"\"\" Next step\n\n Args:\n ts (pandas.Series): Time series to find next value\n\n Returns:\n Value of next time stamp\n\n \"\"\"\n lon_ts = len(ts.values)\n\n if self.p == 0:\n p_sum = 0\n elif lon_ts <= self.p:\n ts_last = ts.values[0:lon_ts]\n p_sum = self.intercept + numpy.dot(ts_last, self.phi[0:lon_ts])\n else:\n ts_last = ts.values[lon_ts-self.p:lon_ts]\n p_sum = self.intercept + numpy.dot(ts_last, self.phi)\n\n if self.q == 0:\n q_sum = 0\n else:\n history = list()\n predictions = list()\n for t in numpy.arange(0,lon_ts,1):\n length = len(history)\n\n if length <= self.q:\n yhat = numpy.mean(ts.values[0:t])\n else:\n ts_last = history[length-self.q:length]\n predicted = predictions[length-self.q:length]\n mean_predicted = numpy.mean(ts_last)\n new_predicted = self.intercept + numpy.dot(numpy.subtract(ts_last, predicted), self.theta)\n yhat = mean_predicted + new_predicted\n\n predictions.append(yhat)\n history.append(ts.values[t])\n\n if lon_ts == 1:\n q_sum = ts.values[0]\n elif lon_ts <= self.q:\n q_sum = numpy.mean(history[0:lon_ts])\n else:\n ts_last = history[lon_ts-self.q:lon_ts]\n predicted = predictions[lon_ts-self.q:lon_ts]\n mean_predicted = numpy.mean(ts_last)\n new_predicted = self.intercept + numpy.dot(numpy.subtract(ts_last, predicted), self.theta)\n q_sum = mean_predicted + new_predicted\n\n result = p_sum + q_sum\n\n return result\n\n def simulate(self, ts):\n \"\"\" Fits a time series using self model parameters\n\n Args:\n ts (pandas.Series): Time series to fit\n\n Returns:\n Fitted time series\n\n \"\"\"\n\n prediction = list()\n for i in range(len(ts)):\n if i == 0:\n result = self.intercept\n else:\n result = self.forecast(ts[0:i])\n prediction.append(result)\n prediction = pandas.Series((v for v in prediction), index = ts.index)\n return prediction\n\n\n def fit(self, ts, error_function = None):\n \"\"\" Finds optimal parameters using a given optimization function\n\n Args:\n ts (pandas.Series): Time series to fit\n error_function (function): Function to estimates error\n\n Return:\n self\n\n \"\"\"\n\n if self.optim_type == 'no_optim':\n pass\n else:\n def f(x):\n self.vector2params(x)\n return self.calc_error(ts, error_function)\n\n x0 = self.params2vector()\n optim_params = scipy.optimize.minimize(f, x0)\n self.vector2params(vector = optim_params.x)\n\n return self\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod(optionflags = doctest.ELLIPSIS)\n","sub_path":"skfore/models/ARMA.py","file_name":"ARMA.py","file_ext":"py","file_size_in_byte":8140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"127343918","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom ..items import DouguomeishiItem\n\nclass DouguoSpider(scrapy.Spider):\n name = 'douguo'\n allowed_domains = ['douguo.com']\n start_urls = ['https://www.douguo.com/caipu/%E4%B8%8B%E9%A5%AD%E8%8F%9C']\n\n def parse(self, response):\n dish_list = response.xpath('//div[@id=\"container\"]/div[@class=\"cp_box\"]')\n for dish in dish_list:\n img = dish.xpath('.//a/img/@src').extract_first('')\n title = dish.xpath('.//a/img/@alt').extract_first('')\n href = dish.xpath('.//a/@href').extract_first('')\n author = dish.xpath('.//div[@class=\"cp_msg\"]/a[@class=\"cp_author\"]/text()').extract()[1]\n author = author.replace(' ','')\n skip = dish.xpath('.//div[@class=\"cp_msg\"]/p[@class=\"cp_cate\"]/text()').extract_first('')\n print(img,title,href,author,skip)\n\n item = DouguomeishiItem()\n item['img'] = img\n item['title'] = title\n item['href'] = href\n item['author'] = author\n item['skip'] = skip\n yield item","sub_path":"Python/8.09/douguomeishi/douguomeishi/spiders/douguo.py","file_name":"douguo.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"280880214","text":"import logging\n\n\nclass VISCAController:\n def move(self, camDeviceID, direction):\n if self.hasDevice(camDeviceID):\n camera = self.devices[camDeviceID]\n if direction == CameraMove.Left:\n return camera.moveLeft()\n elif direction == CameraMove.Right:\n return camera.moveRight()\n elif direction == CameraMove.Up:\n return camera.moveUp()\n elif direction == CameraMove.Down:\n return camera.moveDown()\n elif direction == CameraMove.Stop:\n return camera.stop()\n else:\n logging.warn(\"No device with ID \" + camDeviceID)\n return -1\n\n def zoom(self, camDeviceID, zoomType):\n if self.hasDevice(camDeviceID):\n camera = self.devices[camDeviceID]\n if zoomType == CameraZoom.Tele:\n return camera.zoomIn()\n elif zoomType == CameraZoom.Wide:\n return camera.zoomOut()\n elif zoomType == CameraZoom.Stop:\n return camera.zoomStop()\n else:\n logging.warn(\"No device with ID \" + camDeviceID)\n return -1\n\n def focus(self, camDeviceID, focusType):\n if self.hasDevice(camDeviceID):\n camera = self.devices[camDeviceID]\n if focusType == CameraFocus.Auto:\n return camera.focusAuto()\n elif focusType == CameraFocus.Near:\n return camera.focusNear()\n elif focusType == CameraFocus.Far:\n return camera.focusFar()\n elif focusType == CameraFocus.Stop:\n return camera.focusStop()\n else:\n logging.warn(\"No device with ID \" + camDeviceID)\n return -1\n\n def exposure(self, camDeviceID, exposureType):\n if self.hasDevice(camDeviceID):\n camera = self.devices[camDeviceID]\n if exposureType == CameraExposure.Brighter:\n return camera.brighter()\n elif exposureType == CameraExposure.Darker:\n return camera.darker()\n elif exposureType == CameraExposure.Auto:\n return camera.autoExposure()\n else:\n logging.warn(\"No device with ID \" + camDeviceID)\n return -1\n\n def backlightComp(self, camDeviceID, compensation):\n if self.hasDevice(camDeviceID):\n camera = self.devices[camDeviceID]\n if compensation:\n return camera.backlightCompOn()\n else:\n return camera.backlightCompOff()\n else:\n logging.warn(\"No device with ID \" + camDeviceID)\n return -1\n\n def savePreset(self, camDeviceID, preset):\n if self.hasDevice(camDeviceID):\n camera = self.devices[camDeviceID]\n logging.debug(\"Saving preset \" + str(preset) + \" on device \" + camDeviceID)\n camera.storePreset(preset)\n else:\n logging.warn(\"No device with ID \" + camDeviceID)\n return -1\n\n def recallPreset(self, camDeviceID, preset):\n if self.hasDevice(camDeviceID):\n camera = self.devices[camDeviceID]\n logging.debug(\"Recalling preset \" + str(preset) + \" on device \" + camDeviceID)\n camera.recallPreset(preset)\n else:\n logging.warn(\"No device with ID \" + camDeviceID)\n return -1\n\n def whiteBalance(self, camDeviceID, wbSetting):\n if self.hasDevice(camDeviceID):\n camera = self.devices[camDeviceID]\n if wbSetting == CameraWhiteBalance.Auto:\n return camera.whiteBalanceAuto()\n elif wbSetting == CameraWhiteBalance.Indoor:\n return camera.whiteBalanceIndoor()\n elif wbSetting == CameraWhiteBalance.Outdoor:\n return camera.whiteBalanceOutdoor()\n elif wbSetting == CameraWhiteBalance.OnePush:\n return camera.whiteBalanceOnePush()\n elif wbSetting == CameraWhiteBalance.Trigger:\n return camera.whiteBalanceOnePushTrigger()\n else:\n logging.warn(\"No device with ID \" + camDeviceID)\n return -1\n\n def getPosition(self, camDeviceID):\n if self.hasDevice(camDeviceID):\n camera = self.devices[camDeviceID]\n logging.debug(\"Querying position of device \" + camDeviceID)\n return camera.getPosition()\n else:\n logging.warn(\"No device with ID \" + camDeviceID)\n return None\n\n def goto(self, camDeviceID, pos, panSpeed, tiltSpeed):\n if self.hasDevice(camDeviceID):\n camera = self.devices[camDeviceID]\n logging.debug(\"Setting position of device \" + camDeviceID)\n return camera.goto(pos, panSpeed, tiltSpeed)\n else:\n logging.warn(\"No device with ID \" + camDeviceID)\n return None\n\n def cameraCommand(self, camDeviceID, command):\n if self.hasDevice(camDeviceID):\n camera = self.devices[camDeviceID]\n return camera.execute(command)\n else:\n logging.warn(\"No device with ID \" + camDeviceID)\n return -1\n\n\nclass CameraMove():\n Left, Right, Up, Down, Stop = range(5)\n\n\nclass CameraZoom():\n Tele, Wide, Stop = range(3)\n\n\nclass CameraFocus():\n Near, Far, Auto, Stop = range(4)\n\n\nclass CameraExposure():\n Brighter, Darker, Auto = range(3)\n\n\nclass CameraWhiteBalance():\n Auto, Indoor, Outdoor, OnePush, Trigger = range(5)\n","sub_path":"src/org/muscat/staldates/aldatesx/controller/VISCAController.py","file_name":"VISCAController.py","file_ext":"py","file_size_in_byte":5466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"115994179","text":"import dash_bio as dashbio\nimport six.moves.urllib.request as urlreq\nimport base64\nimport dash_html_components as html\n\ndata = urlreq.urlopen(\"https://raw.githubusercontent.com/plotly/dash-bio/master/tests/dashbio_demos/dash-alignment-chart/data/p53.fasta\").read().decode(\"utf-8\")\n\ncomponent = dashbio.AlignmentChart(\n id='my-dashbio-alignmentchart',\n data=data,\n width='500px'\n)\n\ncomponent_image = html.Img(\n src='data:image/png;base64,{}'.format(\n base64.b64encode(\n open(\n './images/pic_alignment_chart.png', 'rb'\n ).read()\n ).decode()\n ),\n style={'width': '500px'}\n)\n\n\ndef callbacks(app):\n return\n","sub_path":"components/alignment_chart.py","file_name":"alignment_chart.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"265354444","text":"# Copyright (C) 2011 by Paolo Capriotti \n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nfrom pledger.value import ZERO\nfrom pledger.entry import Entry\nfrom pledger.transaction import Transaction\nfrom pledger.util import Observable\nfrom collections import OrderedDict\n\nclass LedgerProcessor(Observable):\n def __init__(self, ledger, rules):\n super(LedgerProcessor, self).__init__()\n self.ledger = ledger\n self.rules = rules\n self.parser = self.ledger.parser\n self.account = self.parser.accounts\n\n def run(self):\n for transaction in self.ledger.transactions:\n transaction.execute(self)\n\n def add_account_prefix(self, prefix):\n self.account = self.account[prefix]\n\n def remove_account_prefix(self):\n self.account = self.account.parent\n\n def add_transaction(self, transaction):\n entries = self.filter(transaction)\n t = self.process_transaction(transaction, entries)\n self.fire(\"transaction\", t, entries)\n\n def include(self, filename):\n filename = self.ledger.absolute_filename(filename)\n subledger = self.parser.parse_ledger(filename)\n self.create_child(subledger).run()\n\n def filter(self, transaction):\n result = []\n for entry in transaction.entries:\n account = self.account[entry.account.name]\n amount = entry.amount\n result += self.rules.apply(transaction, Entry(account, amount, tags=entry.tags))\n return self.compact(result)\n\n def process_transaction(self, transaction, entries):\n return Transaction(entries, transaction.date, transaction.label, transaction.tags)\n\n def create_child(self, ledger):\n child = self.__class__(ledger, self.rules)\n child.account = self.account\n child.listeners = self.listeners\n return child\n\n def compact(self, entries):\n result = OrderedDict()\n for entry in entries:\n key = (entry.account, tuple(sorted(entry.tags.items())))\n e = result.get(key)\n if e:\n e.amount += entry.amount\n else:\n result[key] = Entry(entry.account, entry.amount, entry.tags)\n return result.values()\n","sub_path":"pledger/ledger_processor.py","file_name":"ledger_processor.py","file_ext":"py","file_size_in_byte":3259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"349859784","text":"\"\"\"Constants for moonlight.\"\"\"\r\n# Base component constants\r\nDOMAIN = \"moonlight\"\r\nDOMAIN_DATA = \"{}_data\".format(DOMAIN)\r\nVERSION = \"0.0.1\"\r\nPLATFORMS = [\"sensor\"]\r\nREQUIRED_FILES = [\r\n \"const.py\",\r\n \"manifest.json\",\r\n \"sensor.py\",\r\n]\r\nISSUE_URL = \"https://github.com/sondregronas/MOONLIGHT-HA/issues\"\r\nSTARTUP = \"\"\"\r\n-------------------------------------------------------------------\r\n{name}\r\nVersion: {version}\r\nThis is a custom component\r\nIf you have any issues with this you need to open an issue here:\r\n{issueurl}\r\n-------------------------------------------------------------------\r\n\"\"\"\r\n\r\n# Configuration\r\nCONF_NAME = 'name'\r\nCONF_ICON = 'icon'\r\nCONF_ICON_ACTIVE = 'icon_active'\r\nCONF_HOST = 'host'\r\n\r\n# Defaults\r\nDEFAULT_NAME = 'Moonlight'\r\nDEFAULT_ICON = 'mdi:cast'\r\nDEFAULT_ICON_ACTIVE = 'mdi:cast-connected'","sub_path":"custom_components/moonlight/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"488939099","text":"from .eeg_parameters import EEGSimulationParameters\nfrom .simulation import Simulation\n\nimport sys\n\nsys.path.append('simulations')\nfrom simulations.eeg.jansen import simulate_eeg_jansen\n\nclass EEGSimulation(Simulation):\n\tdef __init__(self, title, parent):\n\t\tsuper().__init__(title, parent=parent)\n\n\t\tself.addSimAndSigParameters(EEGSimulationParameters(), props_to_remove=['P', 'DE'])\n\t\tself.sig_params.setDefaultValues(sampling_frequency=100, duration=10)\n\t\tself.setupConnections()\n\t\tself.plotEEGSignal()\n\t\tself.sig_params.setDefaultName('EEG Simulation')\n\t\tself.exec_()\n\n\tdef setupConnections(self):\n\t\tself.sim_params.preview_button.clicked.connect(self.onValueChanged)\n\t\tself.sig_params.reset_button.clicked.connect(self.onReset)\n\t\tself.sig_params.create_button.clicked.connect(self.onCreate)\n\n\tdef onValueChanged(self):\n\t\tself.plotEEGSignal()\n\n\tdef progress_handler(self, value):\n\t\tself.progress_bar.setValue(value)\n\n\tdef onCreate(self):\n\t\tself.time_series, self.output = simulate_eeg_jansen(duration=self.sig_params.end_time, fs=self.sig_params.sampling_frequency,\n\t\t\t\t\t\tC1=self.sim_params.C1, noise_magnitude=self.sig_params.noise_magnitude, callback=self.progress_handler)\n\n\t\tself.parent.datasets.loadFromSimulation(self.output, self.time_series, self.sig_params.sampling_frequency,\n\t\t\t\t\t\t\tself.sig_params.name_text_field.text(), type=self.title)\n\t\tself.close()\n\n\tdef plotEEGSignal(self):\n\t\tself.sim_graph.clear()\n\t\ttime_series, output = simulate_eeg_jansen(fs=self.sig_params.sampling_frequency, C1=self.sim_params.C1,\n\t\t\t\t\t\t\t\t\t\t\t\t noise_magnitude=self.sig_params.noise_magnitude, callback=self.progress_handler)\n\t\tself.sim_graph.plot(time_series, output, pen='k')","sub_path":"widgets/eeg_simulation_dialog.py","file_name":"eeg_simulation_dialog.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"144342023","text":"from __future__ import division\n\nfrom otree.api import (\n models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,\n Currency as c, currency_range\n)\nimport random\n\n\nclass Constants(BaseConstants):\n name_in_url = 'covid_survey'\n players_per_group = None\n num_rounds = 1\n\n IncrementChoices5DNK=[\n [1, 'Безус��овно увеличился'],\n [2, 'Скорее увеличился'],\n [3, 'Не изменился'],\n [4, 'Скорее уменьшился'],\n [5, 'Безусловно уменьшился'],\n [6, 'Затрудняюсь ответить'],\n ]\n\n AgreementChoices4DNK=[\n [1, 'Совершенно согласен'],\n [2, 'Скорее согласен'],\n [3, 'Скорее не согласен'],\n [4, 'Совершенно не согласен'],\n [5, 'Затрудняюсь ответить'],\n ]\n\n TrustChoices4DNK=[\n [1, 'Полностью доверяю'],\n [2, 'В некоторой степени доверяю'],\n [3, 'Не очень доверяю'],\n [4, 'Совсем не доверяю'],\n [5, 'Затрудняюсь ответить'],\n ]\n\n SimilarChoices6DNK=[\n [1, 'Очень похож на меня'],\n [2, 'Похож на меня'],\n [3, 'Отчасти похож на меня'],\n [4, 'Немного похож на меня'],\n [5, 'Не похож на меня'],\n [6, 'Совсем не похож на меня'],\n [7, 'Затрудняюсь ответить'],\n ]\n\n AgreementChoices5DNK=[\n [1, 'Совершенно согласен'],\n [2, 'Скорее согласен'],\n [3, 'И да и нет'],\n [4, 'Скорее не согласен'],\n [5, 'Совершенно не согласен'],\n [6, 'Затрудняюсь ответить'],\n ]\n\n Sibling4=[\n [1, '0'],\n [2, '1'],\n [3, '2'],\n [4, '3'],\n [5, '4 или более'],\n ]\n\n Region6 = [\n [1, '0'],\n [2, '1'],\n [3, '2-3'],\n [4, '4-6'],\n [5, '7 или более'],\n ]\n\n education_choices = [\n [1, 'Средняя школа'],\n [2, 'Среднее профессиональное образование'],\n [3, 'Незаконченное высшее образование'],\n [4, 'Высшее образование'],\n [5, 'Два и более диплома / Ученая степень'],\n ]\n\n #Survey1\n Inc5DNK=IncrementChoices5DNK\n #Survey2\n Agree4DNK=AgreementChoices4DNK\n #Survey3\n Trust4DNK=TrustChoices4DNK\n #Surveys4\n Similar6DNK=SimilarChoices6DNK\n #Survey5\n Agree5DNK=AgreementChoices4DNK\n #Survery6\n Sib4=Sibling4\n #Survery7\n Reg6=Region6\n\n\nclass Subsession(BaseSubsession):\n pass\n\n\nclass Group(BaseGroup):\n pass\n\n\nclass Player(BasePlayer):\n def set_payoff(self):\n \"\"\"Calculate payoff, which is zero for the survey\"\"\"\n self.payoff = 0\n\n fdb1_instructions= models.TextField(\n verbose_name= '''Были ли Вам понятны условия эксперимента, или же что-то оставалось неясным?'''\n )\n\n fdb1_yourdecision= models.TextField(\n verbose_name= '''Пожалуйста, объясните Ваше решение в этом эксперименте. Почему Вы поступили именно таким образом?'''\n )\n\n fdb1_othersdecision= models.TextField(\n verbose_name= '''Как Вы думаете, какой процент участников этого эксперимента в Вашем городе принял решение Действовать'''\n )\n\n fdb1_RussiaDecision = models.TextField(\n verbose_name='''Этот эксперимент проводится в разных городах России. Как Вы думаете, какой процент участников \n этого эксперимента в России в целом принял решение Действовать? В каких городах он будет больше, в каких меньше?'''\n )\n\n age = models.PositiveIntegerField(verbose_name='Ваш возраст (полных лет)',\n min=13, max=95,\n initial=None)\n\n gender = models.BooleanField(initial=None,\n choices=[[0,'Мужской'],[1,'Женский']],\n verbose_name='Ваш пол',\n widget=widgets.RadioSelect())\n\n height = models.PositiveIntegerField(verbose_name='Ваш рост (в сантиметрах)',\n min=100, max=240,\n initial=None)\n\n marital_status = models.PositiveIntegerField(\n verbose_name='Ваш семейный статус',\n choices=[\n [1, 'Не женаты/не замужем'],\n [2, 'Женаты/замужем'],\n [3, 'В отношениях, но официально ��е состоите в браке'],\n [4, 'Разведены'],\n [5, 'Живете отдельно от супруга/и'],\n [6, 'Вдовец/Вдова'],\n [7, 'Затрудняюсь ответить']\n ],\n widget=widgets.RadioSelect()\n )\n\n\n\n field = models.PositiveIntegerField(verbose_name='Ваша специализация (выберите наиболее подходящую)',\n choices=[[1, 'Экономика, финансы, менеджмент'], [2, 'Социальные науки, психология, политология'], [3, 'Право'], [4, 'Международные отношения'],\n [5, 'Математика, компьютерные, точные науки'], [6, 'Гуманитарные науки'], [7, 'Медиа, журналистика, дизайн'], [8, 'Другое']],\n widget=widgets.RadioSelect())\n\n\n city = models.PositiveIntegerField(\n verbose_name=''' Сколько человек (приблизительно) проживало в том населенном пункте, где Вы жили в возрасте 16 лет.''',\n min = 1, max=30000000,\n initial = None)\n\n yearsinmsc = models.PositiveIntegerField(\n verbose_name='''\n Укажите, сколько лет Вы живете в Вашем городе. Впишите число, округленное до ближайшего целого числа лет.''',\n min = 0, max=95,\n initial = None)\n\n # mscyourcity = models.PositiveIntegerField(\n # verbose_name='''\n # Можете ли вы сказать, что Москва – это ваш город?''',\n # choices=[\n # [1, 'Совершенно не соглас(ен)/(на)'],\n # [2, 'Скорее не соглас(ен)/(на)'],\n # [3, 'И не соглас(ен)/(на) и соглас(ен)/(на)'],\n # [4, 'Скорее соглас(ен)/(на)'],\n # [5, 'Совершенно соглас(ен)/(на)'],\n # ],\n # widget=widgets.RadioSelect()\n # )\n # expect= models.StringField(\n # verbose_name= '''Как Вы думаете, совпали ли Ваши ожидания относительно поведения Ваших партнеров в этой игре с тем, какие решения они принимали на самом деле?'''\n # )\n #\n # othercit= models.StringField(\n # verbose_name= '''Как Вы думаете, специфично ли поведение Ваших партнеров в этой игре для жителей из их города, или будь они из других городов России,\n # в этом эксперименте они бы делали то же самое?'''\n # )\n #\n # # univ= models.StringField(\n # verbose_name= '''Укажите ВУЗ, в котором Вы учитесь/получили Ваше наивысшее образование.'''\n # )\n #\n # study= models.StringField(\n # verbose_name= '''Укажите направление подготовки, на котором Вы обучались в этом ВУЗе.'''\n # )\n\n riskat=models.PositiveIntegerField(\n verbose_name='''Вы любите риск или боитесь риска?''',\n choices = [\n [1, 'Очень люблю рисковать'],\n [2, 'Скорее люблю рисковать'],\n [3, 'Нейтрален к риску'],\n [4, 'Скорее боюсь рисковать'],\n [5, 'Очень боюсь рисковать'],\n ],\n widget = widgets.RadioSelect()\n )\n #\n # riskHL1=models.BooleanField(\n # verbose_name='''Выберите одну из двух лотерей\n # A: [1200 рублей, 0.10; 40 рублей, 0.90] или Б: [650 рублей, 0.10; 500 рублей, 0.90]''',\n # choices = [\n # [0, 'А'],\n # [1, 'Б'],\n # ],\n # widget = widgets.RadioSelectHorizontal()\n # )\n #\n # riskHL2=models.BooleanField(\n # verbose_name='''Выберите одну из двух лотерей\n # A: [1200 рублей, 0.20; 40 рублей, 0.80] или Б: [650 рублей, 0.20; 500 рублей, 0.80]''',\n # choices = [\n # [0, 'А'],\n # [1, 'Б'],\n # ],\n # widget = widgets.RadioSelectHorizontal()\n # )\n # riskHL3=models.BooleanField(\n # verbose_name='''Выберите одну из двух лотерей\n # A: [1200 рублей, 0.30; 40 рублей, 0.70] или Б: [650 рублей, 0.30; 500 рублей, 0.70]''',\n # choices = [\n # [0, 'А'],\n # [1, 'Б'],\n # ],\n # widget = widgets.RadioSelectHorizontal()\n # )\n # riskHL4=models.BooleanField(\n # verbose_name='''Выберите одну из двух лотерей\n # A: [1200 рублей, 0.40; 40 рублей, 0.60] или Б: [650 рублей, 0.40; 500 рублей, 0.60]''',\n # choices = [\n # [0, 'А'],\n # [1, 'Б'],\n # ],\n # widget = widgets.RadioSelectHorizontal()\n # )\n # riskHL5=models.BooleanField(\n # verbose_name='''Выберите одну из двух лотерей\n # A: [1200 рублей, 0.50; 40 рублей, 0.50] или Б: [650 рублей, 0.50; 500 рублей, 0.50]''',\n # choices = [\n # [0, 'А'],\n # [1, 'Б'],\n # ],\n # widget = widgets.RadioSelectHorizontal()\n # )\n # riskHL6=models.BooleanField(\n # verbose_name='''Выберите одну из двух лотерей\n # A: [1200 рублей, 0.60; 40 рублей, 0.40] или Б: [650 рублей, 0.60; 500 рублей, 0.40]''',\n # choices = [\n # [0, 'А'],\n # [1, 'Б'],\n # ],\n # widget = widgets.RadioSelectHorizontal()\n # )\n # riskHL7=models.BooleanField(\n # verbose_name='''Выберите одну из двух лотерей\n # A: [1200 рублей, 0.70; 40 рублей, 0.30] или Б: [650 рублей, 0.70; 500 рублей, 0.30]''',\n # choices = [\n # [0, 'А'],\n # [1, 'Б'],\n # ],\n # widget = widgets.RadioSelectHorizontal()\n # )\n # riskHL8=models.BooleanField(\n # verbose_name='''Выберите одну из двух лотерей\n # A: [1200 рублей, 0.80; 40 рублей, 0.20] или Б: [650 рублей, 0.80; 500 рублей, 0.20]''',\n # choices = [\n # [0, 'А'],\n # [1, 'Б'],\n # ],\n # widget = widgets.RadioSelectHorizontal()\n # )\n # riskHL9=models.BooleanField(\n # verbose_name='''Выберите одну из двух лотерей\n # A: [1200 рублей, 0.90; 40 рублей, 0.10] или Б: [650 рублей, 0.90; 500 рублей, 0.10]''',\n # choices = [\n # [0, 'А'],\n # [1, 'Б'],\n # ],\n # widget = widgets.RadioSelectHorizontal()\n # )\n # riskHL10=models.BooleanField(\n # verbose_name='''Выберите одну из двух лотерей\n # A: [1200 рублей, 1.00; 40 рублей, 0.00] или Б: [650 рублей, 1.00; 500 рублей, 0.00]''',\n # choices = [\n # [0, 'А'],\n # [1, 'Б'],\n # ],\n # widget = widgets.RadioSelectHorizontal()\n # )\n #\n income = models.PositiveIntegerField(\n verbose_name='''Какое высказывание наиболее точно описывает финансовое положение вашей семьи?''',\n choices=[\n [1, 'Едва сводим концы с концами, денег не хватает на выживание;'],\n [2, 'Живем от зарплаты до зарплаты, денег хватает только на неотложные нужды;'],\n [3, 'На ежедневные расходы хватает денег, но уже покупка одежды требует накоплений;'],\n [4, 'Вполне хватает денег, даже имеются некоторые накопления, но крупные покупки требуется планировать заранее;'],\n [5, 'Можем позволить себе крупные траты при первой необходимости.'],\n ],\n widget=widgets.RadioSelect()\n )\n\n satis=models.PositiveIntegerField(\n verbose_name='''Учитывая все обстоятельства, насколько Вы удовлетворены вашей жизнью в целом в эти дни? (от 1 «полностью не удовлетворен» до 10 «полностью удовлетворен»)''',\n choices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n widget = widgets.RadioSelectHorizontal()\n )\n\n trust = models.PositiveIntegerField(\n verbose_name ='''Как Вы считаете, в целом большинству людей можно доверять, или же при общении с другими людьми \n осторожность никогда не повредит? Пожалуйста, отметьте позицию на шкале, где 1 означает \"Нужно быть очень осторожным с другими людьми\" и 10\n означает \"Большинству людей можно вполне доверять\" ''',\n choices=[1,2,3,4,5,6,7,8,9,10],\n widget=widgets.RadioSelectHorizontal()\n )\n\n freedom = models.PositiveIntegerField(\n verbose_name='''Некоторые люди чувствуют, что они обладают полной свободой выбора и контролируют свою жизнь, в\n то время как другие люди чувствуют, что то, что они делают, не имеет реального влияния на происходящее с ними. До какой степени эти\n характеристики применимы к Вам и Вашей жизни? Пожалуйста, отметьте позицию на шкале, где 1 означает \"у меня нет свободы выбора\" и 10\n означает \"у меня полная свобода выбора\".\n ''',\n choices=[1,2,3,4,5,6,7,8,9,10],\n widget=widgets.RadioSelectHorizontal()\n )\n #\n #\n # politics=models.PositiveIntegerField(\n # verbose_name='''До какой степени Вы интересуетесь политикой? (от 1 «Вообще не интересуюсь» до 10 «Очень интересуюсь»)''',\n # choices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n # widget = widgets.RadioSelectHorizontal()\n # )\n #\n # leftright = models.PositiveIntegerField(\n # verbose_name='''В политике говорят о людях \"левых\" (сторонники равенства и социальной справедливости) и \"правых\"\n # (сторонники либерализма и конкуренции) взглядов. Как бы Вы охарактеризовали свои взгляды на шкале от 1 «крайне левые» до\n # 10 «крайне правые»?''',\n # choices=[1,2,3,4,5,6,7,8,9,10],\n # widget=widgets.RadioSelectHorizontal()\n # )\n #\n # owner=models.PositiveIntegerField(\n # verbose_name='''До какой степени Вы согласны с утверждением: «Право собственности непоколебимо»?''',\n # choices = [\n # [1, 'Совершенно не соглас(ен)/(на)'],\n # [2, 'Скорее не соглас(ен)/(на)'],\n # [3, 'И не соглас(ен)/(на) и соглас(ен)/(на)'],\n # [4, 'Скорее соглас(ен)/(на)'],\n # [5, 'Совершенно соглас(ен)/(-на)'],\n # ],\n # widget = widgets.RadioSelect()\n # )\n #\n # ownership=models.PositiveIntegerField(\n # verbose_name='''Как Вы относитесь к утверждению «Доля государственной собственности в экономике нашей страны должна быть увеличена»?\n # Отметьте на шкале, где 1 означает, что Вы полностью не согласны с утверждением, 10 - что полностью согласны''',\n # choices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n # widget = widgets.RadioSelectHorizontal()\n # )\n #\n # responsibility = models.PositiveIntegerField(\n # verbose_name='''Как Вы относитесь к утверждению ««Правительство должно нести ответственность за благосостояние людей»?\n # Отметьте на шкале, где 1 означает, что Вы полностью не согласны с этим утверждением, 10 - что полностью согласны''',\n # choices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n # widget = widgets.RadioSelectHorizontal()\n # )\n #\n # democracy = models.PositiveIntegerField(\n # verbose_name=''' Насколько важно для Вас жить в стране, которая управляется по принципам демократии, т.е. в соответствии с волей народа?\n # Отметьте на шкале, где 1 означает «не важно», 10 «очень важно» ''',\n # choices=[1,2,3,4,5,6,7,8,9,10],\n # widget=widgets.RadioSelectHorizontal()\n # )\n #\n # democracy_today=models.PositiveIntegerField(\n # verbose_name='''Можете ли Вы сказать, что политическая система в нашей стране на сегодняшний день является демократической?\n # Отметьте на шкале, где 1 означает «совсем не демократическая» до 10 «полностью демократическая»''',\n # choices = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n # widget = widgets.RadioSelectHorizontal()\n # )\n # renovation = models.PositiveIntegerField(choices=[[0,'Нет, не знаю'],[1,'Что-то слышал, но не в деталях'],[2,'Да, знаю']],\n # verbose_name='Знаете ли вы о программе реновации (\"снос пятиэтажек\"), предложенной правительством Москвы?',\n # widget=widgets.RadioSelect()\n # )\n #\n # attitudes = models.PositiveIntegerField(verbose_name='Как вы относитесь к программе реновации, предложенной правительством Москвы?',\n # choices = [\n # [1, 'Совершенно не одобряю'],\n # [2, 'Скорее не одобряю'],\n # [3, 'В чем-то не одобряю, а в чем-то одобряю'],\n # [4, 'Скорее одобряю'],\n # [5, 'Совершенно одобряю'],\n # [6, 'Затрудняюсь ответить/ничего не знаю о ней']\n # ],\n # widget = widgets.RadioSelect()\n # )\n\n\n","sub_path":"covid_survey/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":21950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"348440861","text":"\"\"\"Render a map, simulate world.\n\nNote:\n * Needs to be separate from simulation!\n * Mostly a basic test for development purposes.\n\n\"\"\"\n\nimport os\nimport sys\nsys.path.insert(0, '../engine')\nimport pygame\nfrom pygame.locals import *\nimport sprites\nimport tiles\nimport render\nimport controllers\nimport gameblueprint\n\n__author__ = \"Lillian Lemmer\"\n__copyright__ = \"Copyright 2014, Lillian Lemmer\"\n__credits__ = [\"Lillian Lemmer\"]\n__license__ = \"MIT\"\n__maintainer__ = \"Lillian Lemmer\"\n__email__ = \"lillian.lynn.lemmer@gmail.com\"\n__status__ = \"Development\"\n\n\nFPS = 60\nFILENAME = 'debug.tilemap'\nLAYERS = 2\nROWS = 10\nWIDTH = 10\nVIEWPORT_X, VIEWPORT_Y = 50, 50\n\n\n# TILEMAP\nblueprint = [[['default' for i in xrange(WIDTH)]\n for i in xrange(ROWS)]\n for i in xrange(LAYERS)]\n\n# I'm drawing a border of water around the default tile, but I'm\n# leaving two parts of the wall open so I can have fun with nodraw.\nfor z in xrange(LAYERS):\n\n for y in xrange(ROWS):\n\n for x in xrange(WIDTH):\n\n if y == 0 and x > 0:\n blueprint[z][y][x] = 'water'\n elif y > 1 and x == 0:\n blueprint[z][y][x] = 'water'\n elif y > 1 and x == WIDTH - 1:\n blueprint[z][y][x] = 'water'\n elif y == ROWS - 1:\n blueprint[z][y][x] = 'water'\n\n if z > 0:\n blueprint[z][x][y] = 'air'\n\n# showing off layer support with column\n# z y x\nblueprint[0][2][2] = 'block-bottom'\nblueprint[1][1][2] = 'block-top'\n\n# write to file; load from file\ntilemap = tiles.TileMap('debug', blueprint)\ntilemap_string = tilemap.to_string()\n\nwith open(FILENAME, 'w') as f:\n f.write(tilemap_string)\n\nwith open(FILENAME) as f:\n tilemap = tiles.tilemap_from_string(f.read())\n\n# init screen\npygame.init()\nclock = pygame.time.Clock()\ndisplay_info = pygame.display.Info()\nscreen_size = (display_info.current_w, display_info.current_h)\nscreen = pygame.display.set_mode(\n screen_size,\n FULLSCREEN | DOUBLEBUF\n )\n\n# prepare game assets\nitems = [sprites.ExampleItem((40, 40))]\nplayer = sprites.HumanPlayer()\nplayer_controller = controllers.Controller(player, tilemap)\nviewport = render.Viewport((VIEWPORT_X, VIEWPORT_Y))\n\ngame_blueprint = gameblueprint.GameBlueprint(\n tilemap=tilemap,\n human_player=player,\n items=items,\n screen=screen,\n viewport=viewport\n )\n\n# runtime\ngame_blueprint.init()\n\nwhile True:\n game_blueprint.item_check()\n player_controller.update()\n\n game_blueprint.blit_all()\n\n # this is such a nice way to rescale to any resolution\n scaled_viewport = pygame.transform.scale(\n viewport.surface,\n screen_size\n )\n screen.blit(\n scaled_viewport,\n (0, 0)\n )\n pygame.display.flip()\n clock.tick(FPS)\n\n","sub_path":"examples/exploremap.py","file_name":"exploremap.py","file_ext":"py","file_size_in_byte":3288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"60053789","text":"import sys\nimport os\n\npostfix = sys.argv[1]\ndirectory = sys.argv[2]\nnames = sys.argv[3:]\nfull_names = [os.path.join(directory, name) for name in names]\n\nfor name in full_names:\n if os.path.isdir(name):\n os.rename(name, name + postfix)\n elif os.path.isfile(name):\n path = os.path.split(name)\n dir = path[:-1]\n file_name = path[-1]\n if '.' in file_name:\n tmp = file_name.split('.')\n base = '.'.join(tmp[:-1])\n ext = tmp[-1]\n new_file_name = '.'.join([base + postfix, ext])\n else:\n new_file_name = file_name + postfix\n new_name = os.path.join(*dir, new_file_name)\n os.rename(name, new_name)\n else:\n print(\"WARNING: file or directory %s does not exist\" % name)\n","sub_path":"learning_to_learn/experiments/add_postfix_to_names.py","file_name":"add_postfix_to_names.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"346295011","text":"# -*- coding: utf-8 -*-\nimport json\nimport unittest\n\nfrom extruct.jsonld import JsonLdExtractor\nfrom tests import get_testdata\n\nclass TestJsonLD(unittest.TestCase):\n\n def test_schemaorg_CreativeWork(self):\n body = get_testdata('schema.org', 'CreativeWork.001.html')\n expected = json.loads(get_testdata('schema.org', 'CreativeWork.001.jsonld').decode('UTF-8'))\n\n jsonlde = JsonLdExtractor()\n data = jsonlde.extract(body)\n self.assertEqual(data, expected)\n\n def test_songkick(self):\n page = \"Elysian Fields Brooklyn Tickets, The Owl Music Parlor, 31 Oct 2015\"\n body = get_testdata('songkick', '{}.html'.format(page))\n expected = json.loads(get_testdata('songkick', '{}.jsonld'.format(page)).decode('UTF-8'))\n\n jsonlde = JsonLdExtractor()\n data = jsonlde.extract(body)\n self.assertEqual(data, expected)\n\n def test_jsonld_with_comments(self):\n for prefix in ['JoinAction.001', 'AllocateAction.001']:\n body = get_testdata('schema.org.invalid', '{}.html'.format(prefix))\n name = '{}.jsonld'.format(prefix)\n expected = json.loads(get_testdata('schema.org.invalid', name).decode('UTF-8'))\n\n jsonlde = JsonLdExtractor()\n data = jsonlde.extract(body)\n self.assertEqual(data, expected)\n for prefix in ['JoinAction.001',\n 'AllocateAction.001',\n ]:\n body = get_testdata('custom.invalid', '{}.html'.format(prefix))\n expected = json.loads(get_testdata('custom.invalid', '{}.jsonld'.format(prefix)).decode('UTF-8'))\n\n jsonlde = JsonLdExtractor()\n data = jsonlde.extract(body)\n self.assertEqual(data, expected)\n","sub_path":"tests/test_jsonld.py","file_name":"test_jsonld.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"414589462","text":"import ast\nimport textwrap\nimport tokenize\n\nimport pytest\n\nfrom refactor.ast import UnparserBase, split_lines\nfrom refactor.common import position_for\n\n\ndef test_split_lines():\n source = textwrap.dedent(\n \"\"\"\\\n 1 + 2\n print(foo)\n if not (\n bar\n ):\n print(z)\n \"\"\"\n )\n\n assert list(split_lines(source)) == [\n \"1 + 2\",\n \"print(foo)\",\n \"if not (\",\n \" bar\",\n \"):\",\n \" print(z)\",\n ]\n\n\n@pytest.mark.parametrize(\n \"source\",\n [\n \"\",\n \"\\n\",\n \"\\n\\n\",\n \"\\n\\n\\n\",\n \"\\t\\n \\n \\n\",\n \"x\",\n \"x\\n\",\n \"x\\n\\n\",\n \"x\\n\\n\\n\",\n \"x\\n\\nxx\\n\\n\",\n ],\n)\ndef test_split_lines_variations(source):\n lines = split_lines(source)\n assert lines.join() == source\n\n\ndef test_unparser_base():\n\n source = \"a + b + c # comment\"\n tree = ast.parse(source)\n right_node = tree.body[0].value.right\n\n base = UnparserBase(source)\n\n assert base.unparse(right_node) == \"c\"\n assert tokenize.untokenize(base.tokens) == source\n\n assert base.token_map[position_for(right_node)].string == \"c\"\n\n\nclass CustomUnparser(UnparserBase):\n def visit_List(self, node):\n with self.delimit(\"[\", \"]\"):\n with self.indented():\n self.fill()\n self.interleave(\n lambda: self.write(\",\") or self.fill(),\n self.traverse,\n node.elts,\n )\n self.maybe_newline()\n\n\ndef test_unparser_functions():\n\n source = \"[1, 2]\"\n tree = ast.parse(source)\n\n base = CustomUnparser(source)\n assert base.unparse(tree) == textwrap.dedent(\n \"\"\"\\\n [\n 1,\n 2\n ]\"\"\"\n )\n","sub_path":"tests/test_ast.py","file_name":"test_ast.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"141227281","text":"# ROUTE index\n@app.route(\"/\")\ndef index():\n import bs4\n\n def hierarchicalise(input: list):\n def traverse(set_hierarchy, roots):\n hierarchy = {}\n for name in roots:\n hierarchy[name] = traverse(set_hierarchy, set_hierarchy[name])\n return hierarchy\n\n def sorted_hierarchy(hierarchy, i=0):\n sorted_ls = []\n for k, v in sorted(hierarchy.items()):\n sorted_ls.append((k, i))\n sorted_ls.extend(sorted_hierarchy(v, i=i + 1))\n return sorted_ls\n\n set_hierarchy = {name: set() for el in input for name in el}\n has_parent = {name: False for el in input for name in el}\n\n for parent, child in input:\n # Add child\n set_hierarchy[parent].add(child)\n # Update has_parent dict\n has_parent[child] = True\n\n no_parents = []\n for name, parents in has_parent.items():\n if not parents:\n no_parents.append(name)\n\n # No parents\n roots = [name for name, parents in has_parent.items() if not parents]\n\n # Hierarchy\n hierarchy = traverse(set_hierarchy, roots)\n\n sorted_output = sorted_hierarchy(hierarchy)\n\n return sorted_output\n\n def test_hierarchicalise():\n test_input = [\n (\"A\", \"B\"),\n (\"A\", \"C\"),\n (\"K\", \"D\"),\n (\"B\", \"D\"),\n (\"C\", \"E\"),\n (\"E\", \"F\"),\n (\"F\", \"G\"),\n (\"F\", \"H\"),\n (\"I\", \"J\"),\n (\"I\", \"X\"),\n (\"K\", \"L\"),\n (\"L\", \"M\"),\n (\"A\", \"X\"),\n (\"X\", \"Y\"),\n (\"M\", \"D\")\n ]\n actual = hierarchicalise(test_input)\n expected = [\n (\"A\", 0),\n (\"B\", 1),\n (\"D\", 2),\n (\"C\", 1),\n (\"E\", 2),\n (\"F\", 3),\n (\"G\", 4),\n (\"H\", 4),\n (\"X\", 1),\n (\"Y\", 2),\n (\"I\", 0),\n (\"J\", 1),\n (\"X\", 1),\n (\"Y\", 2),\n (\"K\", 0),\n (\"D\", 1),\n (\"L\", 1),\n (\"M\", 2),\n (\"D\", 3),\n ]\n\n assert actual == expected\n\n def make_hierarchical_list_html(parent_child_label_list: list):\n pairs = [(parent_child[0], parent_child[1]) for parent_child in parent_child_label_list if\n parent_child[0] is not None]\n labels = {}\n for (parent, child, label) in parent_child_label_list:\n labels[child] = label\n\n hierarchical_list = hierarchicalise(pairs)\n\n md = \"\"\n for i in hierarchical_list:\n md += \"{}* [{}]({})\\n\".format(i[1] * \" \", labels[i[0]], i[0])\n\n return bs4.BeautifulSoup(markdown.markdown(md), features=\"html.parser\").prettify()\n\n def test_hierarchical_list_html():\n test_input = [\n (None, \"A\", \"Aa\"),\n (None, \"I\", \"Ii\"),\n (None, \"K\", \"Kk\"),\n (\"A\", \"B\", \"Bb\"),\n (\"A\", \"C\", \"Cc\"),\n (\"K\", \"D\", \"Dd\"),\n (\"B\", \"D\", \"Dd\"),\n (\"C\", \"E\", \"Ee\"),\n (\"E\", \"F\", \"Ff\"),\n (\"F\", \"G\", \"Gg\"),\n (\"F\", \"H\", \"Hh\"),\n (\"I\", \"J\", \"Ii\"),\n (\"I\", \"X\", \"Xx\"),\n (\"K\", \"L\", \"Ll\"),\n (\"L\", \"M\", \"Mm\"),\n (\"A\", \"X\", \"Xx\"),\n (\"X\", \"Y\", \"Yy\"),\n (\"M\", \"D\", \"Dd\")\n ]\n expected = \"\"\"\"\"\"\n actual = make_hierarchical_list_html(test_input)\n\n assert expected == actual\n\n q = \"\"\"\n PREFIX skos: \n PREFIX policy: \n SELECT DISTINCT ?parent ?parentlabel ?child ?childlabel\n WHERE { \n BIND ( As ?this )\n GRAPH ?this {\n ?this a skos:ConceptScheme .\n ?parent a skos:Collection .\n ?parent skos:member ?child .\n OPTIONAL { ?parent skos:prefLabel ?ppl}\n OPTIONAL { ?parent rdfs:label ?pl }\n BIND(COALESCE(?ppl, ?pl, STR(?parent)) AS ?parentlabel )\n } \n ?cs2 policy:collectionView ?child .\n OPTIONAL { ?cs2 skos:prefLabel ?cpl}\n OPTIONAL { ?cs2 rdfs:label ?cl }\n BIND( COALESCE(?cpl, ?cl, STR(?cs2) ) AS ?childlabel )\n }\n \"\"\"\n\n parent_child_label_list = []\n seen = {}\n res = u.sparql_query(q)\n for r in res:\n p = str(r[\"parent\"][\"value\"])\n pl = str(r[\"parentlabel\"][\"value\"])\n c = str(r[\"child\"][\"value\"])\n cl = str(r[\"childlabel\"][\"value\"])\n parent_child_label_list.append(\n (p, c, cl)\n )\n seen[p] = pl\n if seen.get(c):\n del seen[c]\n\n # add in top Collections\n for p, pl in seen.items():\n parent_child_label_list.append(\n (None, p, pl)\n )\n\n h = make_hierarchical_list_html(parent_child_label_list)\n\n return render_template(\n \"index.html\",\n hierarchy=h\n )\n# END ROUTE index\n","sub_path":"app_additions.py","file_name":"app_additions.py","file_ext":"py","file_size_in_byte":6882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"353323231","text":"from abc import abstractmethod\nfrom uuid import uuid4\n\n# the first file MUST be the workflow element's file.\nFILES = [\"WorkflowElement.py\"]\n# class name that will be imported and used in workflow\nCLASSNAME = \"WorkflowElement\"\nOPTIONAL = False # if the element is optional or mandatory\nNAME = \"WORKFLOW_ELEMENT\" # name displayed to the user\n# description displayed to the user\nDESCRIPTION = \"Empty, exemplary workflow element\"\nMATERIAL_ICON = \"\" # icon displayed to the user\nINDEPENDENT = False # if this element uses results of previous elements or not\nREQUIREMENTS = [] # if any requirements are needed, put them here\n\n\nclass WorkflowElement:\n def __init__(\n self,\n name=NAME,\n description=DESCRIPTION,\n materialIcon=MATERIAL_ICON,\n optional=OPTIONAL,\n requirements=REQUIREMENTS,\n filenames=FILES,\n classname=CLASSNAME,\n independent=INDEPENDENT,\n config={},\n ):\n \"\"\"\n Initializes Workflow Element.\n It assings id to the element and allows to set it's name, description, icon, config etc.\n **name**: name of the workflow element\n **description**: description of the workflow element\n **materialIcon**: icon which could describe this workflow element\n **optional**: if the workflow element is optional or mandatory and should always be added\n **requirements**: requirements used in the workflow element (avoid repeating the same requirements in modules)\n **filenames**: name of the file where this element is placed\n **classname**: class name of the workflow element\n :config: config**: info required by the workflow element. Could contain \"data\" property for the \"fast\" method.\n \"\"\"\n self.id = str(uuid4())\n self.name = name\n self.description = description\n self.materialIcon = materialIcon\n self.optional = optional\n self.requirements = requirements\n self.filenames = filenames\n self.classname = classname\n self.independent = independent\n self.config = config\n\n @abstractmethod\n def main(self, input: str = None, output: str = None, delimiter=\",\", **kwargs):\n \"\"\"\n Main method for this Workflow Element.\n It should handle all needed operation on the input file and it's data and save it to output file.\n While there are some operations that doesn't require any input/output files you could omit them and\n save it anywhere else, but remember that other Worklow Elements will not be noticed about this file.\n IMPORTANT: remember, that even if your element is independent, you should copy your input to output, because\n another element could use this results. This allows you to avaid problems with passing the data.\n **input**: path to the input file\n **output**: path to the output file\n \"\"\"\n raise NotImplementedError\n\n @abstractmethod\n def quick_main(self, data: dict) -> dict:\n \"\"\"\n Handles fast operations on data. Should be \"demo\"/\"trial\" version of the main method.\n Usually it could be used for online purposes and operations. It should be fast and as simple as possible.\n This is optional function and if you don't want to use it just don't specify the \"data\" property\n in config of this object.\n However to allow user to use it you MUST specify \"data\" property in config e.g. config = {\"data\": {\"ekg\": []}}\n **data**: dictionary with all necessary for this Workflow Element data (e.g. list of EKG data).\n \"\"\"\n pass\n","sub_path":"wb/components/WorkflowElement.py","file_name":"WorkflowElement.py","file_ext":"py","file_size_in_byte":3623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"407358206","text":"from unittest import TestCase\nfrom unittest.mock import patch, Mock\n\nfrom alamo_scheduler.drivers.default.sender import DefaultSender\n\n\nclass TestDefaultSender(TestCase):\n\n @patch(\"alamo_scheduler.drivers.default.sender.ZeroMQQueue\", Mock())\n def setUp(self):\n self.sender = DefaultSender()\n self.check = {\n 'uuid': '997e8667-6e80-4131-a938-caa02d743550',\n 'name': 'foo bar'\n }\n\n def test_send(self):\n send_mock = Mock()\n self.sender.queue = send_mock\n\n self.sender.send(self.check)\n self.assertTrue(send_mock.send.called)\n","sub_path":"alamo_scheduler/drivers/default/test_default_sender.py","file_name":"test_default_sender.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"23309971","text":"# import cv2\nimport numpy as np\nimport random\nimport h5py\nfrom matplotlib import pyplot as plt\nimport os\nfrom PIL import Image\nimport math\nimport PIL\n\nfrom keras.models import *\nfrom keras.layers import Input, merge,Conv3D,BatchNormalization,Conv3DTranspose, UpSampling3D, MaxPooling3D, AveragePooling3D, \\\n GlobalAveragePooling3D,Dense,Flatten,Lambda,Dropout,Activation,ZeroPadding3D\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, TensorBoard\nfrom keras import backend as keras\nfrom keras.utils.vis_utils import plot_model\nfrom keras import backend as k\nimport tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\n\n\n\ndef Acc(y_true, y_pred):\n y_pred_r = K.round(y_pred)\n return K.equal(y_pred_r, y_true)\n\ndef y_t(y_true, y_pred):\n return y_true\n\ndef y_pre(y_true, y_pred):\n return y_pred\n\ndef EuiLoss(y_true, y_pred):\n y_true_f = keras.flatten(y_true)\n y_pred_f = keras.flatten(y_pred)\n d = K.sum(K.sqrt(K.square(y_true_f - y_pred_f) + 1e-12))\n a = K.cast(K.greater_equal(d, 0.5), dtype='float32')\n b = K.cast(K.greater_equal(0.12, d), dtype='float32')\n c = K.cast(K.greater_equal(0.3, d), dtype='float32')\n loss = (2 + 4 * a - 0.5 * b - 1 * c) * d + 0.2 * y_pred_f *d\n return loss\n\ndef identity_block(x, nb_filters, name, kernel_size=3):\n k1, k2, k3 = nb_filters\n convname1 = name + 'conv1'\n convname2 = name + 'conv2'\n convname3 = name + 'conv3'\n bnname1 = name + 'bn1'\n bnname2 = name + 'bn2'\n bnname3 = name + 'bn3'\n out = Conv3D(k1, 1, strides=1, kernel_initializer='he_normal', name = convname1)(x)\n out = BatchNormalization(axis = -1, epsilon = 1e-6, name = bnname1)(out)\n out = Activation('relu')(out)\n\n out = Conv3D(k2, kernel_size, strides=1, padding='same', kernel_initializer='he_normal', name = convname2)(out)\n out = BatchNormalization(axis = -1, epsilon = 1e-6, name = bnname2)(out)\n out = Activation('relu')(out)\n\n out = Conv3D(k3, 1, strides=1, kernel_initializer='he_normal', name = convname3)(out)\n out = BatchNormalization(axis = -1, epsilon = 1e-6, name = bnname3)(out)\n\n out = merge([out, x], mode='sum')\n out = BatchNormalization()(out)\n out = Activation('relu')(out)\n return out\n\n\ndef conv_block(x, nb_filters, name, kernel_size=3):\n k1, k2, k3 = nb_filters\n convname1 = name + 'conv1'\n convname2 = name + 'conv2'\n convname3 = name + 'conv3'\n convname4 = name + 'conv4'\n bnname1 = name + 'bn1'\n bnname2 = name + 'bn2'\n bnname3 = name + 'bn3'\n bnname4 = name + 'bn4'\n out = Conv3D(k1, 2, strides=2, kernel_initializer='he_normal', name = convname1)(x)\n out = BatchNormalization(axis = -1, epsilon = 1e-6, name = bnname1)(out)\n out = Activation('relu')(out)\n\n out = Conv3D(k2, kernel_size, strides=1, padding='same', kernel_initializer='he_normal', name = convname2)(out)\n out = BatchNormalization(axis = -1, epsilon = 1e-6, name = bnname2)(out)\n out = Activation('relu')(out)\n\n out = Conv3D(k3, 1, strides=1, kernel_initializer='he_normal', name = convname3)(out)\n out = BatchNormalization(axis = -1, epsilon = 1e-6, name = bnname3)(out)\n\n x = Conv3D(k3, 2, strides=2, kernel_initializer='he_normal', name = convname4)(x)\n x = BatchNormalization(axis = -1, epsilon = 1e-6, name = bnname4)(x)\n\n out = merge([out, x], mode='sum')\n out = BatchNormalization()(out)\n out = Activation('relu')(out)\n return out\n\ndef ClassNet():\n inputs = Input(shape=(280, 280, 16, 1), name='input1')\n # 256*256*128\n print(\"input shape:\", inputs.shape) # (?, 140, 140, 16, 64)\n out = Conv3D(64, 7, strides=(2, 2, 1), padding = 'same', kernel_initializer='he_normal', use_bias = False, name = 'conv1')(inputs)\n print(\"conv0 shape:\", out.shape)#(?, 140, 140, 16, 64)\n out = BatchNormalization(axis = -1, epsilon = 1e-6, name = 'bn1')(out)\n out = Activation('relu')(out)\n out = MaxPooling3D((3, 3, 3), strides=(2, 2, 1), padding = 'same')(out)\n print(\"pooling1 shape:\", out.shape)#(?, 70, 70, 16, 64)\n\n out = conv_block(out, [64, 64, 256], name = 'L1_block1')\n print(\"conv1 shape:\", out.shape)\n out = identity_block(out, [64, 64, 256], name = 'L1_block2')\n\n out = identity_block(out, [64, 64, 256], name = 'L1_block3')\n\n\n out = conv_block(out, [128, 128, 512], name = 'L2_block1')\n print(\"conv2 shape:\", out.shape)\n out = identity_block(out, [128, 128, 512], name = 'L2_block2')\n\n out = identity_block(out, [128, 128, 512], name = 'L2_block3')\n\n out = identity_block(out, [128, 128, 512], name = 'L2_block4')\n\n\n out = conv_block(out, [256, 256, 1024], name = 'L3_block1')\n print(\"conv3 shape:\", out.shape)\n out = identity_block(out, [256, 256, 1024], name = 'L3_block2')\n out = identity_block(out, [256, 256, 1024], name = 'L3_block3')\n out = identity_block(out, [256, 256, 1024], name = 'L3_block4')\n out = identity_block(out, [256, 256, 1024], name = 'L3_block5')\n out = identity_block(out, [256, 256, 1024], name = 'L3_block6')\n\n out = conv_block(out, [512, 512, 2048], name = 'L4_block1')\n print(\"conv4 shape:\", out.shape)\n out = identity_block(out, [512, 512, 2048], name = 'L4_block2')\n out = identity_block(out, [512, 512, 2048], name = 'L4_block3')\n\n out = GlobalAveragePooling3D(data_format = 'channels_last')(out)\n print(\"Gpooling shape:\", out.shape)\n out_drop = Dropout(rate=0.3)(out)\n out = Dense(1, name = 'fc1')(out_drop)\n print(\"out shape:\", out.shape)\n #out = Dense(1, name = 'fc1')(out)\n output = Activation(activation = 'sigmoid')(out)\n\n model = Model(input = inputs, output = output)\n #mean_squared_logarithmic_error or binary_crossentropy\n model.compile(optimizer=SGD(lr = 1e-6, momentum = 0.9), loss = EuiLoss, metrics= [y_t, y_pre, Acc] )\n return model","sub_path":"old/python/dl_py_code_20190116(v0.9)/Net_new.py","file_name":"Net_new.py","file_ext":"py","file_size_in_byte":5835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"183192183","text":"import random\nclass Carta:\n LLISTA_NUMEROS={1:\"As\",2:\"Dos\",3:\"Tres\",4:\"Cuatro\",5:\"Cinco\",6:\"Seis\",7:\"Siete\",8:\"Sota\",9:\"Caballo\",10:\"Rey\"}\n LLISTA_COLLS={0:\"Oro\",1:\"Copas\",2:\"Espadas\",3:\"Bastos\"}\n def __init__(self,*args):\n self.__num=0\n self.__coll=0\n longitud=len(args)\n if longitud ==2 and isinstance(args[0],int) and args[0]>0 and args[0]<11 and isinstance(args[1],int) and args[1]<4 and args[1]>-1:\n self.__num=args[0]\n self.__coll=args[1]\n elif longitud==1 and isinstance(args[0],int) and args[0]>0 and args[0]<41:\n self.__idacarta(args[0])\n else:\n raise NotImplementedError (\"Valores incorrectos\")\n\n\n def __cartaaleatoria(self):\n id=random.randint(1,40)\n self.__idacarta(id)\n\n def __idacarta(self,id):\n if id>30:\n self.__coll=3\n self.__num=id-30\n elif id>20:\n self.__coll=2\n self.__num=id-20\n elif id>10:\n self.__coll=1\n self.__num=id-10\n else:\n self.__coll=0\n self.__num=id\n\n # def __idNumColl(self,id,numero):\n # self.__coll=id//10\n # if id%10==0:\n # self.__coll-=1\n # self.__num=id-self.__coll*10\n def Numero(self):\n return self.__num\n\n def Coll(self):\n return self.__coll\n\n def nomNumero(self):\n return self.LLISTA_NUMEROS[self.__num]\n def nomColl(self):\n return self.LLISTA_COLLS[self.__coll]\n def ValorTute(self):\n if self.__num==1:\n return 11\n elif self.__num==3:\n return 10\n elif self.__num==7:\n return 2\n elif self.__num==9:\n return 3\n elif self.__num==10:\n return 10\n return 0\n def ValorMus(self):\n if self.__num==1 or self.__num==2:\n return 13\n elif self.__num>7:\n return 10\n return self.__num\n def Valor7iMig(self):\n if self.__num>7:\n return 0.5\n return self.__num\n\n def __str__ (self):\n return self.nomNumero()+\" de \"+ self.nomColl()\n","sub_path":"Python/Practicas/Clases/Carta.py","file_name":"Carta.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"58784076","text":"#!/usr/bin/env python\n# -*- coding:utf8 -*-\n\nimport smtplib\nfrom email.mime.text import MIMEText\n\nmail_from = \"lehome_notify@lejiayuan.cn\"\nmail_to = \"sunhanqi@lejiayuan.cn\"\n\nmsg = MIMEText('这是内容33', _charset='utf8')\nmsg['Subject'] = '标题 测试33'\nmsg['From'] = mail_from\nmsg['To'] = mail_to\n\nsmtp = smtplib.SMTP('smtp.lejiayuan.cn')\nsmtp.login(mail_from, 'lehome_1q2w3e4r')\n# smtp.set_debuglevel(True)\n# smtp.ehlo()\nsmtp.sendmail(mail_from, mail_to, msg.as_string())\nsmtp.quit()","sub_path":"sms/notification/test/email_test.py","file_name":"email_test.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"162606250","text":"\"\"\"\r\nx = [100, 200]\r\ny = [200, 700]\r\n\r\nif len(x) > 0:\r\n x.pop()\r\n y.pop()\r\n\r\nprint(x)\r\nprint(y)\r\n\"\"\"\r\n\r\n\r\n# Drawing the circles\r\nx = [100, 200]\r\ny = [200, 700]\r\nR = [255, 255]\r\nG = [0, 255]\r\nB = [0, 0]\r\nradius = [10, 50]\r\nmove_x = [-1, 6]\r\nmove_y = [5, -2]\r\n\r\ndef setup():\r\n size(900, 900)\r\n \r\ndef draw():\r\n background(255, 255, 255)\r\n \r\n # Loop over all the circles\r\n # DRAW CIRCLES\r\n for index in range(0, len(x)):\r\n # Draw one of the circles\r\n pushStyle()\r\n fill(R[index], G[index], B[index], 100)\r\n ellipse(x[index], y[index], radius[index], radius[index])\r\n popStyle()\r\n move_circles()\r\n \r\ndef move_circles():\r\n global x\r\n global y\r\n global move_x\r\n global move_y\r\n for index in range(0, len(x)):\r\n x[index] = x[index] + move_x[index]\r\n y[index] = y[index] + move_y[index]\r\n \r\n \r\n \r\n","sub_path":"Lessons/Term 1 Lessons/Week16/Code_to_help_you/Code_to_help_you.pyde","file_name":"Code_to_help_you.pyde","file_ext":"pyde","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"410693744","text":"from sklearn.svm import SVC\nfrom sklearn.preprocessing import StandardScaler\nfrom aif360.algorithms.preprocessing import Reweighing, DisparateImpactRemover\nfrom aif360.metrics import ClassificationMetric\nimport numpy as np\nfrom sklearn.utils.testing import ignore_warnings\nfrom sklearn.exceptions import ConvergenceWarning\n\n\ndef test_classifier(classifier, scale, test_data, fairness_metric, accuracy_metric, keep_features,\n classification_threshold, privileged_groups, unprivileged_groups):\n \"\"\"\n Test the provided classifier on specified data set, and calculate fitness scores.\n\n :param classifier: The classifier to test\n :param scale: Scaler to transform the test set\n :param test_data: The test data set to test the classifier on\n :param fairness_metric: The fairness metric to calculate\n :param accuracy_metric: The accuracy metric to calculate\n :param keep_features: The features to keep for SVC\n :param classification_threshold: The classification threshold to be used\n :param privileged_groups: The privileged group in the data set\n :param unprivileged_groups: The unprivileged group in the data set\n :return:\n \"\"\"\n dataset_orig_test = test_data\n\n # Prepare data\n dataset_test_pred = dataset_orig_test.copy(deepcopy=True)\n X_test = scale.transform(dataset_test_pred.features)\n if len(keep_features) > 0: # If keep_features empty, use all features\n X_test = X_test[:, keep_features]\n\n # Test\n pos_ind = np.where(classifier.classes_ == dataset_orig_test.favorable_label)[0][0] # positive class index\n dataset_test_pred.scores = classifier.predict_proba(X_test)[:, pos_ind].reshape(-1, 1)\n\n # Assign labels using the classification threshold\n fav_inds = dataset_test_pred.scores > classification_threshold\n dataset_test_pred.labels[fav_inds] = dataset_test_pred.favorable_label\n dataset_test_pred.labels[~fav_inds] = dataset_test_pred.unfavorable_label\n\n # Calculate metrics\n cm = ClassificationMetric(dataset_orig_test, dataset_test_pred,\n unprivileged_groups=unprivileged_groups, privileged_groups=privileged_groups)\n accuracy_score = accuracy_metric(cm)\n fairness_score = fairness_metric(cm)\n return accuracy_score, fairness_score\n\n\n@ignore_warnings(category=ConvergenceWarning)\ndef train_svm(training_data, C, gamma, keep_features, max_iter, svm_seed):\n \"\"\"\n Train SVM(SVC) classifier on specified data set, with provided parameters, and calculate fitness scores.\n\n :param training_data: The training data set to run the classifier on\n :param C: The C parameter for SVC\n :param gamma: The gamma parameter for SVC\n :param keep_features: The features to keep for SVC\n :param max_iter: Max iterations for SVM\n :param svm_seed: Seed used for RNG in SVM\n :return: The trained classifier, and the scaler\n \"\"\"\n dataset_orig_train = training_data\n\n # Prepare data\n scale = StandardScaler()\n X_train = scale.fit_transform(dataset_orig_train.features)\n y_train = dataset_orig_train.labels.ravel()\n w_train = dataset_orig_train.instance_weights\n if len(keep_features) > 0: # If keep_features empty, use all features\n X_train = X_train[:, keep_features]\n\n # Train\n clf = SVC(C=C, gamma=gamma, kernel='rbf', probability=True, max_iter=max_iter, random_state=svm_seed)\n clf.fit(X_train, y_train, sample_weight=w_train)\n\n return clf, scale\n\n\n@ignore_warnings(category=ConvergenceWarning)\ndef train_svm_reweighing(training_data, C, gamma, keep_features, privileged_groups, unprivileged_groups, max_iter,\n svm_seed):\n \"\"\"\n Train the SVM classifier with Reweighing preprocessing on specified data set,\n with provided parameters, and calculate fitness scores.\n\n :param training_data: The training data set to run the classifier on\n :param C: The C parameter for SVC\n :param gamma: The gamma parameter for SVC\n :param keep_features: The features to keep for SVC\n :param privileged_groups: The privileged group in the data set\n :param unprivileged_groups: The unprivileged group in the data set\n :param max_iter: Max iterations for SVM\n :param svm_seed: Seed used for RNG in SVM\n :return: The trained classifier and the scaler\n \"\"\"\n dataset_orig_train = training_data\n\n # Run Reweighing\n rw = Reweighing(privileged_groups=privileged_groups, unprivileged_groups=unprivileged_groups)\n dataset_transf_train = rw.fit_transform(dataset_orig_train)\n\n # Prepare data\n scale = StandardScaler()\n X_train = scale.fit_transform(dataset_transf_train.features)\n y_train = dataset_transf_train.labels.ravel()\n w_train = dataset_transf_train.instance_weights\n if len(keep_features) > 0: # If keep_features empty, use all features\n X_train = X_train[:, keep_features]\n\n # Train\n clf = SVC(C=C, gamma=gamma, kernel='rbf', probability=True, max_iter=max_iter, random_state=svm_seed)\n clf.fit(X_train, y_train, sample_weight=w_train)\n\n return clf, scale\n\n\n@ignore_warnings(category=ConvergenceWarning)\ndef train_svm_dir(training_data, C, gamma, keep_features, sensitive_attribute, max_iter, svm_seed):\n \"\"\"\n Train the SVM classifier with Disparate Impact Remover preprocessing on specified data set,\n with provided parameters, and calculate fitness scores.\n\n :param training_data: The training data set to run the classifier on\n :param C: The C parameter for SVC\n :param gamma: The gamma parameter for SVC\n :param keep_features: The features to keep for SVC\n :param sensitive_attribute: The sensitive attribute in the dataset\n :param max_iter: Max iterations for SVM\n :param svm_seed: Seed used for RNG in SVM\n :return: The trained classifier and the scaler\n \"\"\"\n dataset_orig_train = training_data\n\n # Run Disparate Impact Remover\n di = DisparateImpactRemover(repair_level=0.8, sensitive_attribute=sensitive_attribute)\n dataset_transf_train = di.fit_transform(dataset_orig_train)\n\n # Prepare data\n scale = StandardScaler()\n X_train = scale.fit_transform(dataset_transf_train.features)\n y_train = dataset_transf_train.labels.ravel()\n w_train = dataset_transf_train.instance_weights\n if len(keep_features) > 0: # If keep_features empty, use all features\n X_train = X_train[:, keep_features]\n\n # Train\n clf = SVC(C=C, gamma=gamma, kernel='rbf', probability=True, max_iter=max_iter, random_state=svm_seed)\n clf.fit(X_train, y_train, sample_weight=w_train)\n\n return clf, scale\n\n\n@ignore_warnings(category=ConvergenceWarning)\ndef train_svm_optimpreproc(training_data, C, gamma, keep_features, max_iter, svm_seed):\n \"\"\"\n Train SVM classifier with Optimized Preprocessing method on specified data set,\n with provided parameters, and calculate fitness scores.\n\n :param training_data: The training data set to run the classifier on\n :param C: The C parameter for SVC\n :param gamma: The gamma parameter for SVC\n :param keep_features: The features to keep for SVC\n :param max_iter: Max iterations for SVM\n :param svm_seed: Seed used for RNG in SVM\n :return: The trained classifier\n \"\"\"\n return train_svm(training_data=training_data, C=C, gamma=gamma, keep_features=keep_features, max_iter=max_iter,\n svm_seed=svm_seed)\n\n\n\n","sub_path":"src/experiment2/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":7354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"307719091","text":"#mua942\n#11275853\n#Assigment 1 Question 1\n#CMPT145 LO2\ndef check_diagonals(square):\n '''\n Checks the diagonals\n param square: a 3d list containing 9 ints\n return: True if all the diagonals add up to 15. False otherwise\n '''\n\n theSum = 0\n for x in range(3):\n ##because for this down-right diagonal the index of list in the list are the same\n theSum += square[x][x]\n if(theSum != 15):\n return False\n else:\n theSum = 0\n theSum += square[2][0]\n theSum += square[1][1]\n theSum += square[0][2]\n if theSum != 15:\n return False\n\n return True\ndef check_columns(square):\n '''\n Checks the same index of each list in the list thus looking at the columns\n param square: a 3d list containing 9 ints\n return: True if all the columns sum to 15. False otherwiseo\n '''\n for indice in range(3):\n ##indice keeps track of which column we are on\n theSum = 0\n for list in square:\n ##this takes the element of the row that is in the column\n ##for example take the 1th element of each row and that is the fisrt colmun\n theSum += list[indice]\n if(theSum != 15):\n return False\n return True\ndef check_rows(square):\n '''\n Takes a 3x3 list of list and takes the sum of each list in the list and returns false as soon it sees a non-15 value\n param square: a 3d list containing 9 ints\n return: True if all the rows sum to 15. False otherwise\n '''\n for list in square:\n ##a row is a list in the square. sum() gives us the row sum\n if(sum(list) != 15):\n return False\n\n return True\ndef check_range(square):\n '''\n Uses a remember-answer boolean list system to check if every number between 1 and 9 are present\n param square: a 3d list containing 9 ints\n return: True if the square contains all the integers 1 .. 9. False otherwise\n '''\n ## a list of 9 Falses\n seen = [False for x in range(9)]\n\n for dimension in square:\n for element in dimension:\n #Make sure the element is 1-9\n if(element >=1 and element <= 9):\n ##element-1 means that 1-9 number will coorespond to the index of the bool list\n seen[element - 1] = True\n else:\n return False\n if False in seen:\n return False\n else:\n return True\n\n\n\n### Use these 3 functions\ndef check_square(square):\n '''\n calls all the other check functions and returns true if and only if all other function return True. Thus being a Magic Square\n param square: a 3d list containing 9 ints\n return:True if the square has all the properties of a magic square using other functions; False otherwise\n '''\n if not check_range(square):\n return False\n if not check_rows(square):\n return False\n if not check_columns(square):\n return False\n if not check_diagonals(square):\n return False\n\n return True\ndef get_square():\n '''\n A function to get a list of 9 ints and turns them into a 3d list (3x3). This is done using a nested loop\n return: a 3x3 list of lists\n '''\n aListOfInts= []\n while len(aListOfInts) != 9:\n raw = int(input(\"Enter a single positive number\"))\n aListOfInts.append(raw)\n square = []\n\n #dimesnion meanings row in the magic square\n for dimension in range(3):\n subList = []\n for element in range(3):\n subList.append( aListOfInts[element] )\n del aListOfInts[:3]\n square.append(subList)\n\n return square\ndef main():\n '''\n This function calls get_square and check_square functions to print YES or NO depending on the return of check_square\n '''\n magicSquare = get_square()\n if(check_square(magicSquare)):\n print(\"YES\")\n else:\n print(\"NO\")\n\n\nmain()","sub_path":"a1q1.py","file_name":"a1q1.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"82299859","text":"#!/usr/bin/env python\n\nimport time\nfrom bme280 import BME280\n\ntry:\n from smbus2 import SMBus\nexcept ImportError:\n from smbus import SMBus\n\nprint(\"\"\"weather.py - Print readings from the BME280 weather sensor.\n\nPress Ctrl+C to exit!\n\n\"\"\")\n\nbus = SMBus(1)\nbme280 = BME280(i2c_dev=bus)\n\nwhile True:\n temperature = bme280.get_temperature()\n pressure = bme280.get_pressure()\n humidity = bme280.get_humidity()\n print(\"\"\"Temperature: {:05.2f} *C\nPressure: {:05.2f} hPa\nRelative humidity: {:05.2f} %\n\"\"\".format(temperature, pressure, humidity))\n time.sleep(1)\n","sub_path":"examples/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"193518228","text":"import io\nimport os.path\nimport pytest\n\nfrom astral import GoogleGeocoder\n\n@pytest.mark.webtest\ndef test_GoogleLocator():\n locator = GoogleGeocoder()\n l = locator['Eiffel Tower']\n assert l is not None\n\ndef read_contents(*names, **kwargs):\n return io.open(\n os.path.join(*names),\n encoding=kwargs.get(\"encoding\", \"utf8\")\n ).read()\n\napi_key = read_contents(os.path.dirname(__file__), '.api_key')\n@pytest.mark.webtest\ndef test_GoogleLocator_WithAPIKey():\n if api_key:\n locator = GoogleGeocoder(api_key=api_key)\n l = locator['Eiffel Tower']\n assert l is not None\n else:\n raise AssertionError('api_key not found')\n\n\nif __name__ == '__main__':\n test_GoogleLocator()\n","sub_path":"src/test/test_GoogleGeocoder.py","file_name":"test_GoogleGeocoder.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"602067872","text":"#!/usr/bin/env python\n\"\"\"ROS Node for Recording from Microphone\n\nThis node records from a microphone and saves the recorded audio to a .wav file.\nIt starts recording when it receives a message via the /keys topic and publishes the path to the recorded file\nvia to the /audio topic.\n\nVariables:\n CHUNK: The number of frames per buffer.\n FORMAT: The output sample format.\n CHANNELS: The number of channels for recording. (1 = mono)\n RATE: The sample rate in Hz.\n RECORD_SECONDS: The length of the recording in seconds.\n WAVE_OUTPUT_FILENAME: The name of the output file.\n\"\"\"\n\nimport rospy\nfrom std_msgs.msg import Bool, Int32, String\nimport pyaudio\nimport wave\nimport os\n\n\nCHUNK = 1024\nFORMAT = pyaudio.paInt32\nCHANNELS = 1\nRATE = 44100#22050\nRECORD_SECONDS = 10\nWAVE_OUTPUT_FILENAME = \"temp.wav\"\n\nclass Mic:\n\n def listen(self, key):\n '''\n source: https://gist.github.com/mabdrabo/8678538\n\n Implementation is based on source, but customized to fit requirements.\n\n Records audio data from the microphone and saves it to /home//.ros as .wav file.\n\n When recording is done, publishes the path of the file to the /audio topic.\n '''\n\n\n publisher = rospy.Publisher(\"/audio\", String, queue_size = 1)\n\n p = pyaudio.PyAudio()\n\n stream = p.open(format=FORMAT,\n channels=CHANNELS,\n rate=RATE,\n input=True,\n frames_per_buffer=CHUNK)\n\n rospy.loginfo(\"* recording\")\n\n frames = []\n\n for i in range(0, int(RATE / CHUNK * (RECORD_SECONDS + 1))):\n data = stream.read(CHUNK)\n frames.append(data)\n\n rospy.loginfo(\"* done recording\")\n\n stream.stop_stream()\n stream.close()\n p.terminate()\n\n wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')\n wf.setnchannels(CHANNELS)\n wf.setsampwidth(p.get_sample_size(FORMAT))\n wf.setframerate(RATE)\n wf.writeframes(b''.join(frames))\n wf.close()\n\n path = os.environ['HOME']\n\n rospy.loginfo(\"publishing audio\")\n publisher.publish(path + \"/.ros/\" + WAVE_OUTPUT_FILENAME)\n rospy.loginfo(\"published audio\")\n\n\ndef main():\n '''\n Initializes the mic node and a Mic object. Subscribes to the /keys topic and uses the listen method of\n the Mic class as callback.\n '''\n\n try:\n #initializes the node 'mic'\n rospy.init_node('mic', anonymous=False)\n\n #initializes a Mic object\n mic = Mic()\n\n #subscribes to the /keys topic and uses listen as callback\n rospy.Subscriber(\"/keys\", String, mic.listen)\n\n rospy.spin()\n\n except rospy.ROSInterruptException:\n pass\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"catkin_ws/src/mic/src/Mic.py","file_name":"Mic.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"155269582","text":"from .base_service import BaseService\n\n\nclass DriveService(BaseService):\n def __init__(self, *args, **kwargs):\n super().__int__(*args, **kwargs)\n self.logger = self.get_logger()\n self.conn = self.connect_sqlite()\n self.init_drive_database()\n\n def init_drive_database(self):\n try:\n with self.conn as conn:\n c = conn.cursor()\n c.execute(\n \"\"\"CREATE TABLE IF NOT EXISTS drive (\n target_type TEXT NOT NULL UNIQUE, \n drive_name TEXT NOT NULL)\"\"\")\n drives = [('mysql', 'pymysql'),\n ('mongodb', 'pymongo'),\n ('docker', 'requests'),\n ('kubernetes', 'requests')]\n c.executemany(\n \"\"\"REPLACE INTO drive VALUES(?, ?)\"\"\", drives)\n conn.commit()\n except Exception as error:\n self.logger.error(error)\n\n def create_drive(self, target_type, drive_name):\n try:\n with self.conn as conn:\n c = conn.cursor()\n c.execute(\"\"\"INSERT INTO drive VALUES (?, ?)\"\"\", (target_type, drive_name))\n conn.commit()\n return {\"query\": True}\n except Exception as error:\n self.logger.error(error)\n return False\n\n def update_drive(self, new_info, condition):\n result = self.find_drive(condition)\n if result:\n if result[\"query\"] is True:\n try:\n with self.conn as conn:\n c = conn.cursor()\n c.execute(\"\"\"UPDATE drive SET drive_name = ? WHERE target_type = ?\"\"\", (new_info, condition))\n conn.commit()\n return {\"query\": True}\n except Exception as error:\n self.logger.error(error)\n return False\n else:\n return result\n else:\n return result\n\n def delete_drive(self, condition):\n result = self.find_drive(condition)\n if result:\n if result[\"query\"] is True:\n try:\n with self.conn as conn:\n c = conn.cursor()\n c.execute(\"\"\"DELETE FROM drive WHERE target_type = ?\"\"\", (condition, ))\n conn.commit()\n return {\"query\": True}\n except Exception as error:\n self.logger.error(error)\n return False\n else:\n return result\n else:\n return result\n\n def find_drive(self, condition):\n try:\n with self.conn as conn:\n c = conn.cursor()\n c.execute(\"\"\"SELECT target_type, drive_name FROM drive WHERE target_type = ?\"\"\", (condition, ))\n result = c.fetchone()\n if result:\n return {\"query\": True, \"data\": {\"target_type\": result[0], \"drive_name\": result[1]}}\n else:\n return {\"query\": False}\n except Exception as error:\n self.logger.error(error)\n return False\n\n def find_all_drive(self):\n try:\n with self.conn as conn:\n c = conn.cursor()\n c.execute(\"\"\"SELECT target_type, drive_name FROM drive\"\"\")\n result = []\n rows = c.fetchall()\n if not rows:\n return {\"query\": False}\n for row in rows:\n record = {\n \"target_type\": row[0],\n \"drive_name\": row[1]\n }\n result.append(record)\n return {\"query\": True, \"data\": result}\n except Exception as error:\n self.logger.error(error)\n return False\n","sub_path":"MonitoredSystem/services/drive_service.py","file_name":"drive_service.py","file_ext":"py","file_size_in_byte":3961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"193647460","text":"\"\"\"private_mkt will be populated from puppet and placed in this directory\"\"\"\n\nfrom mkt.settings import *\nfrom settings_base import *\n\nimport private_mkt\n\nSERVER_EMAIL = 'zmktlandfill@addons.mozilla.org'\n\nDOMAIN = \"landfill-mkt.allizom.org\"\nSITE_URL = 'https://landfill-mkt.allizom.org'\nBROWSERID_AUDIENCES = [SITE_URL]\nSTATIC_URL = 'https://landfill-mkt-cdn.allizom.org/'\nLOCAL_MIRROR_URL = '%s_files' % STATIC_URL\nMIRROR_URL = LOCAL_MIRROR_URL\n\nCSP_STATIC_URL = STATIC_URL[:-1]\nCSP_IMG_SRC = CSP_IMG_SRC + (CSP_STATIC_URL,)\nCSP_SCRIPT_SRC = CSP_SCRIPT_SRC + (CSP_STATIC_URL,)\nCSP_STYLE_SRC = CSP_STYLE_SRC + (CSP_STATIC_URL,)\n\nADDON_ICON_URL = 'img/uploads/addon_icons/%s/%s-%s.png?modified=%s'\nPREVIEW_THUMBNAIL_URL = 'img/uploads/previews/thumbs/%s/%d.png?modified=%d'\nPREVIEW_FULL_URL = 'img/uploads/previews/full/%s/%d.%s?modified=%d'\n\nSESSION_COOKIE_SECURE = True\nSESSION_COOKIE_DOMAIN = \".%s\" % DOMAIN\n\n# paths for uploaded extensions\nUSERPICS_URL = 'img/uploads/userpics/%s/%s/%s.png?modified=%d'\n\nMEDIA_URL = STATIC_URL + 'media/'\nADDON_ICONS_DEFAULT_URL = 'img/hub'\n\nCACHE_PREFIX = 'landfill.mkt.%s' % CACHE_PREFIX\nCACHE_MIDDLEWARE_KEY_PREFIX = CACHE_PREFIX\nCACHES['default']['KEY_PREFIX'] = CACHE_PREFIX\n\nSYSLOG_TAG = \"http_app_mkt_landfill\"\nSYSLOG_TAG2 = \"http_app_mkt_landfill_timer\"\nSYSLOG_CSP = \"http_app_mkt_landfill_csp\"\n\nSTATSD_PREFIX = 'marketplace-landfill'\n\n## Celery\nBROKER_URL = private_mkt.BROKER_URL\n\nCELERY_ALWAYS_EAGER = False\nCELERY_IGNORE_RESULT = True\nCELERY_DISABLE_RATE_LIMITS = True\nCELERYD_PREFETCH_MULTIPLIER = 1\n\nES_DEFAULT_NUM_REPLICAS = 2\n\nWEBAPPS_RECEIPT_KEY = private_mkt.WEBAPPS_RECEIPT_KEY\nWEBAPPS_RECEIPT_URL = private_mkt.WEBAPPS_RECEIPT_URL\n\nWEBAPPS_UNIQUE_BY_DOMAIN = False\n\nSENTRY_DSN = private_mkt.SENTRY_DSN\n\nWEBAPPS_PUBLIC_KEY_DIRECTORY = NETAPP_STORAGE + '/public_keys'\nPRODUCT_ICON_PATH = NETAPP_STORAGE + '/product-icons'\n\nSOLITUDE_HOSTS = ('https://payments-dev.allizom.org',)\n\nVALIDATOR_IAF_URLS = ['https://marketplace.firefox.com',\n 'https://marketplace.allizom.org',\n 'https://marketplace-dev.allizom.org',\n 'https://landfill-mkt.allizom.org']\n\nAMO_LANGUAGES = AMO_LANGUAGES + ('dbg',)\nLANGUAGES = lazy(lazy_langs, dict)(AMO_LANGUAGES)\nLANGUAGE_URL_MAP = dict([(i.lower(), i) for i in AMO_LANGUAGES])\n\n#Bug 748403\nSIGNING_SERVER = private_mkt.SIGNING_SERVER\nSIGNING_SERVER_ACTIVE = True\nSIGNING_VALID_ISSUERS = ['marketplace-dev-cdn.allizom.org']\n\n#Bug 793876\nSIGNED_APPS_KEY = private_mkt.SIGNED_APPS_KEY\nSIGNED_APPS_SERVER_ACTIVE = False\n\nVALIDATOR_TIMEOUT = 110\n\nAPP_PURCHASE_KEY = DOMAIN\nAPP_PURCHASE_AUD = DOMAIN\nAPP_PURCHASE_TYP = 'mozilla-landfill/payments/pay/v1'\nAPP_PURCHASE_SECRET = private_mkt.APP_PURCHASE_SECRET\n\nFXA_OAUTH_URL = getattr(private_mkt, 'FXA_OAUTH_URL', '')\nFXA_CLIENT_ID = getattr(private_mkt, 'FXA_CLIENT_ID', '')\nFXA_CLIENT_SECRET = getattr(private_mkt, 'FXA_CLIENT_SECRET', '')\n","sub_path":"sites/landfill/settings_mkt.py","file_name":"settings_mkt.py","file_ext":"py","file_size_in_byte":2930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"378515229","text":"# better version\n# Import github.com/yousefissa\n# @devmykal helped me bc im a nut\n\nimport time\nfrom requests import Session\nimport multiprocessing\n\nsession = Session()\nsession.headers.update({\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36'\n '(KHTML, like Gecko) Chrome/56.0.2924.28 Safari/537.36'})\n\ndef mil_seconds():\n return int(round(time.time() * 1000))\n\n# MAIN\n# gets proxies and websites in a text file, rather than hard-coding them\nwith open(\"proxies.txt\") as proxies_text:\n proxies = proxies_text.read().splitlines()\nwith open(\"sitelist.txt\") as sitelist_text:\n\tsites = sitelist_text.read().splitlines()\n\nif proxies == []:\n print('You did not load proxies. Check your proxies.txt file!')\n exit()\nelse: \n\tprint('Currently loaded:', proxies)\ngood_proxies = []\n\nprint('Testing on sites ', sites)\n\ndef proxyChecker(proxy):\n session.proxies.update({\n 'http': 'http://' + proxy,\n 'https': 'https://' + proxy\n })\n for url in sites:\n start_time = mil_seconds()\n try:\n\t response = session.get(url)\n\t if response.status_code != 200:\n\t print(proxy, ' is not a good proxy.')\n\t else:\n\t print('[{}] on site {} ---- {} ms'.format(proxy, url, mil_seconds() - start_time))\n\t good_proxies.append(proxy)\n except: # broad exceptions are bad but who cares\n \tprint('Bad Proxy {} on site {}'.format(proxy, url))\n\nif __name__ == '__main__':\n\tjobs = []\n\tfor p in proxies:\n\t m = multiprocessing.Process(target=proxyChecker, args=(p,))\n\t jobs.append(m)\n\tfor j in jobs:\n\t j.start()\n\n","sub_path":"proxy_tester.py","file_name":"proxy_tester.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"283344034","text":"__all__ = [\n \"HistoryWindow\"\n]\n\nfrom .branch_tree_view import (\n BranchTreeview\n)\nfrom .gui_toplevel import (\n GUIToplevel\n)\nfrom six.moves.tkinter_ttk import (\n Scrollbar\n)\nfrom common import (\n mlget as _\n)\n\nclass HistoryWindow(GUIToplevel):\n def __init__(self, gui_project_history_tracker, *args, **kw):\n GUIToplevel.__init__(self, *args, **kw)\n\n self.guipht = gui_project_history_tracker\n\n self.attributes(\"-topmost\", 1)\n\n self.title(_(\"Editing History\"))\n\n self.grid()\n\n self.columnconfigure(0, weight = 1)\n self.columnconfigure(1, weight = 0)\n self.rowconfigure(0, weight = 1)\n self.rowconfigure(1, weight = 0)\n\n tv = self.btv = BranchTreeview(self.guipht, self)\n self.btv.grid(\n row = 0,\n column = 0,\n sticky = \"NEWS\"\n )\n\n vsb = Scrollbar(self, orient = \"vertical\", command = tv.yview)\n vsb.grid(row = 0, column = 1, sticky = \"NS\")\n\n hsb = Scrollbar(self, orient = \"horizontal\", command = tv.xview)\n hsb.grid(row = 1, column = 0, sticky = \"EW\")\n\n tv.configure(yscrollcommand = vsb.set, xscrollcommand = hsb.set)\n","sub_path":"widgets/history_window.py","file_name":"history_window.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"54967318","text":"#!/usr/bin/env python\n# license removed for brevity\n\nimport rospy\nimport actionlib\nfrom move_base_msgs.msg import MoveBaseAction, MoveBaseGoal\nimport subprocess\n\nxpos = [0.00,0.00]\ni = 0\ndef movebase_client():\n\n client = actionlib.SimpleActionClient('move_base',MoveBaseAction)\n client.wait_for_server()\n global i\n goal = MoveBaseGoal()\n goal.target_pose.header.frame_id = \"map\"\n goal.target_pose.header.stamp = rospy.Time.now()\n goal.target_pose.pose.position.x = xpos[i]\n i = i+1\n goal.target_pose.pose.orientation.w = 1.0\n\n client.send_goal(goal)\n wait = client.wait_for_result()\n if not wait:\n rospy.logerr(\"Action server not available!\")\n rospy.signal_shutdown(\"Action server not available!\")\n else:\n return client.get_result()\n\nif __name__ == '__main__':\n try:\n rospy.init_node('movebase_client_py')\n result = movebase_client()\n if result:\n rospy.loginfo(\"Goal execution done!\")\n subprocess.call(\"./sayhello.sh\", shell=True)\n except rospy.ROSInterruptException:\n rospy.loginfo(\"Navigation test finished.\")\n rospy.sleep(3)\n try:\n rospy.init_node('movebase_client_py')\n result = movebase_client()\n if result:\n rospy.loginfo(\"Goal execution done!\")\n subprocess.call(\"./sayhello.sh\", shell=True)\n except rospy.ROSInterruptException:\n rospy.loginfo(\"Navigation test finished.\")\n","sub_path":"src/robomuse-ros-master/robomuse_drivers/scripts/Old/mbsmiddle.py","file_name":"mbsmiddle.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"108103473","text":"import sys\nreader = (s.rstrip() for s in sys.stdin)\ninput = reader.__next__\n\n\nn,k=list(map(int,input().split()))\n\nboth = []\na = []\nb = []\nfor _ in range(n):\n t, ai, bi = map(int, input().split())\n if ai == 1 and bi == 1:\n both.append(t)\n elif ai == 1:\n a.append(t)\n elif bi == 1:\n b.append(t)\n \nboth.sort()\na.sort()\nb.sort()\n\nfound=True\n\nfor l in [both,a,b]:\n if len(l) < k:\n l += [10 ** 10] * (k - len(l))\n \nif len(a) > k:\n a = a[:k]\nif len(b) > k:\n b = b[:k]\nif len(both) > k:\n both = both[:k]\n \nout = 0\nfor i in range(k):\n out += min(a[i] + b[i],both[-i-1])\n \nif out >= 10 ** 10:\n print(-1)\nelse:\n print(out)\n\n\n\n \n","sub_path":"round653/nmh.py","file_name":"nmh.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"457104041","text":"class TreeNode():\n def __init__(self, key, value):\n self.left = None\n self.right = None\n self.key = key\n self.value = value\n\n def add(self, node):\n if node.key < self.key:\n if self.left is None:\n self.left = node\n else:\n self.left.add(node)\n else:\n if self.right is None:\n self.right = node\n else:\n self.right.add(node)\n\n # find the node with the specified key\n def find(self, key):\n if key == self.key:\n return self\n elif key < self.key:\n if self.left is None:\n return None\n else:\n return self.left.find(key)\n else:\n if self.right is None:\n return None\n else:\n return self.right.find(key)\n\n def child_count(self):\n count = 0\n if self.left is not None:\n count += 1\n if self.right is not None:\n count += 1\n return count\n\n def max(self):\n if self.right is None:\n return self.key\n else:\n return self.right.max()\n\n def delete(self, key):\n if key == self.key:\n # this node is being deleted\n if self.left is None and self.right is None:\n # Case 1: we can delete this node without any further action\n return None\n elif self.left is None:\n # Case 2: we've only the right child - it replaces the current node\n return self.right\n elif self.right is None:\n # Case 3: we've only the left child - it replaces the current node\n return self.left\n else:\n # Case 4: we've two children, so we need to find an\n # existing node to replace this one that is in the\n # same place in the sequence\n maxkey = self.left.max()\n maxnode = self.left.find(maxkey)\n \n #maxnode can replace this node.\n #delete it from where it currently is\n self.left = self.left.delete(maxkey)\n\n #replace contents of this node with those of maxnode\n self.key = maxnode.key\n self.value = maxnode.value\n elif key < self.key:\n if self.left is not None:\n self.left = self.left.delete(key)\n else:\n if self.right is not None:\n self.right = self.right.delete(key)\n return self\n \n def walk(self):\n if self.left is not None:\n yield from self.left.walk()\n yield (self.key, self.value)\n if self.right is not None:\n yield from self.right.walk()\n \n\nclass BinaryTree():\n def __init__(self):\n self.root = None\n self.count = 0\n\n def __len__(self):\n return self.count\n\n def add(self, key, value):\n node = TreeNode(key, value)\n if self.root is None:\n self.root = node\n else:\n self.root.add(node)\n self.count += 1\n\n \n # delete the item matching the key from the tree\n def delete(self, key):\n if self.root is None:\n return\n self.root = self.root.delete(key)\n self.count -= 1\n\n\n # return the value matching the key, or None if no match is found\n def get(self, key):\n if self.root is None:\n return None\n node = self.root.find(key)\n if node is None:\n return None\n return node.value\n\n # create a generator for walking the tree in order\n def walk(self):\n if self.root is None:\n return\n yield from self.root.walk()\n \n\n\nimport random\nimport pytest\n\n@pytest.fixture\ndef two_lists():\n items = list(range(100))\n old_items = items.copy()\n random.shuffle(items)\n return (items, old_items)\n\ndef test_basics():\n return\n tree = BinaryTree()\n tree.add(2,2)\n tree.add(1,1)\n tree.add(3,3)\n count = 1\n for key, value in tree.walk():\n assert key == count\n assert value == count\n count += 1\n assert(tree.get(1) is not None)\n assert(tree.get(2) is not None)\n assert(tree.get(3) is not None)\n tree.delete(2)\n assert(tree.get(1) is not None)\n assert(tree.get(2) is None)\n assert(tree.get(3) is not None)\n tree.delete(1)\n assert(tree.get(1) is None)\n assert(tree.get(2) is None)\n assert(tree.get(3) is not None)\n tree.delete(1) # delete something that's no there\n assert(tree.get(1) is None)\n assert(tree.get(2) is None)\n assert(tree.get(3) is not None)\n tree.delete(3)\n assert(tree.get(1) is None)\n assert(tree.get(2) is None)\n assert(tree.get(3) is None)\n\ndef test_basics2():\n tree = BinaryTree()\n tree.add(3,3)\n tree.add(2,2)\n tree.add(1,1)\n count = 1\n for key, value in tree.walk():\n assert key == count\n assert value == count\n count += 1\n assert(tree.get(1) is not None)\n assert(tree.get(2) is not None)\n assert(tree.get(3) is not None)\n tree.delete(3)\n assert(tree.get(1) is not None)\n assert(tree.get(2) is not None)\n assert(tree.get(3) is None)\n tree.delete(2)\n assert(tree.get(1) is not None)\n assert(tree.get(2) is None)\n assert(tree.get(3) is None)\n tree.delete(1) # delete something that's no there\n assert(tree.get(1) is None)\n assert(tree.get(2) is None)\n assert(tree.get(3) is None)\n\ndef test_demo():\n tree = BinaryTree()\n tree.add(\"Karp\", (\"x30406\", \"MPEB 6.20\"))\n tree.add(\"Handley\", (\"x37679\", \"MPEB 6.21\"))\n tree.add(\"Vissichio\", (\"x31397\", \"MPEB 6.19\"))\n phone, office = tree.get(\"Handley\")\n assert phone == \"x37679\"\n\ndef test_demo2():\n tree = BinaryTree()\n tree.add(\"Karp\", (\"x30406\", \"MPEB 6.20\"))\n tree.add(\"Handley\", (\"x37679\", \"MPEB 6.21\"))\n tree.add(\"Vissichio\", (\"x31397\", \"MPEB 6.19\"))\n phone, office = tree.get(\"Handley\")\n assert phone == \"x37679\"\n\n # your're fired!\n tree.delete(\"Handley\")\n assert tree.get(\"Handley\") == None\n\ndef test_add_get(two_lists):\n items, _ = two_lists\n tree = BinaryTree()\n for i in items[:50]:\n tree.add(i, i)\n\n for i in items[:50]:\n value = tree.get(i)\n assert tree.get(i) is not None\n\n for i in items[50:]:\n assert tree.get(i) is None\n\ndef test_min_delete_len(two_lists):\n items, _ = two_lists # Use a test fixture \n # returning range(100)\n # Test init and add\n tree = BinaryTree()\n for i in items:\n tree.add(i,i) # Test add\n assert tree.root.max() == 99 # Test max\n\n # Test remove, get, len\n for pos, i in enumerate(items): # Helper iterator\n assert len(tree) == 100 - pos # Test len\n assert tree.get(i) is not None # Test get\n tree.delete(i) # Test remove\n assert tree.get(i) is None # Test get\n assert(tree.root is None)\n\n\ndef test_walk(two_lists):\n items = list(range(100)) # [0, ..., 99]\n random.shuffle(items) # shuffle\n\n tree = BinaryTree()\n for i in items:\n tree.add(i,i)\n\n assert len(items) == len(tree) # Test len\n\n # Check that iterator returns elements in order\n for x,(y,z) in zip(range(100), tree.walk()):\n assert x == y # Check the order is the same\n","sub_path":"Topics/06_Dynamic_Data_Structures/src/binaryTree.py","file_name":"binaryTree.py","file_ext":"py","file_size_in_byte":7501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"110178212","text":"\"\"\"\n79. 单词搜索\n给定一个二维网格和一个单词,找出该单词是否存在于网格中。\n\n单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。\n\n \n\n示例:\n\nboard =\n[\n ['A','B','C','E'],\n ['S','F','C','S'],\n ['A','D','E','E']\n]\n\n给定 word = \"ABCCED\", 返回 true\n给定 word = \"SEE\", 返回 true\n给定 word = \"ABCB\", 返回 false\n\n\"\"\"\nclass Solution:\n def exist(self,g, w):\n def help(g, idx,x, y,m):\n if idx == len(w) - 1:#如果idx到單詞的最後一個即長度滿足,只要相等即爲true\n return g[x][y] == w[idx]\n if g[x][y] == w[idx]:#如果相等則暫時爲True,一條可行的路徑但可以回溯!\n m[x][y] = True\n for x_,y_ in directions:\n nx = x + x_\n ny = y + y_\n if 0 <= nx < row and 0 <= ny < col and not m[nx][ny] and help(g, idx + 1,nx, ny,m):\n return True\n m[x][y] = False#回溯的關鍵步驟..\n return False\n row = len(g)\n if not row:\n return False\n col = len(g[0])\n directions = [(0, -1), (-1, 0), (0, 1), (1, 0)]\n m = [[0]*col for _ in range(row)]#初始化都是False,默認都是走不通的\n for i in range(row):\n for j in range(col):\n #每個都去嘗試走如果某個i,j可以走通就是True,都走不通就是False\n if help(g, 0, i, j, m):#hepl就是去走的函數g是2d,0是idx從0開始,i和j就是對應的行和列,m就是記錄能否走通..\n return True\n return False\n\n\n","sub_path":"回溯算法2d上找單詞.py","file_name":"回溯算法2d上找單詞.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"553428882","text":"import sox\nimport os\nimport sys\n\npath=os.path.abspath('.')\noutput_path = path + \"/../../data/learn-english/oral_wav/\"\nunit_begin = 1\nunit_length = 100\n\nif __name__ == \"__main__\":\n cbn = sox.Combiner()\n for num in range(unit_begin,unit_begin + unit_length):\n out_folder = \"%s%03d\" % (output_path,num)\n out_file = \"%s%03d%s\" % (output_path,num,\".wav\")\n files = []\n for filename in os.listdir(out_folder):\n files.append(os.path.join(out_folder,filename))\n cbn.build(files,out_file, 'concatenate')","sub_path":"src/concatenate_oral.py","file_name":"concatenate_oral.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"84673857","text":"class Dog:\r\n pass\r\n \r\nmyDog = Dog () \r\nyourDog = Dog ()\r\n\r\ndef init (dog, sound, kind = None, name = 'naamloos'):\r\n dog.sound = sound\r\n dog.kind = kind\r\n dog.name = name\r\n print (f'Een {_getSpecies (dog)} is geinstantieerd, {dog.name}')\r\n \r\ndef eat (dog, food = 'wat de pot schaft'):\r\n _introduce (dog)\r\n print (f'en ik eet {food}')\r\n \r\ndef move (dog):\r\n _introduce (dog)\r\n print (f'en ik loop')\r\n\r\ndef reproduce (dog, aantal = 3):\r\n _introduce (dog)\r\n print (f'en ik krijg gemiddeld {aantal} jongen')\r\n \r\ndef wagTail (dog):\r\n _introduce (dog)\r\n print ('en ik kwispel')\r\n\r\ndef _introduce (dog):\r\n print (\r\n f'Hallo, ik ben {dog.name}, mijn soort is {_getSpecies (dog)}',\r\n end = ' '\r\n )\r\n \r\ndef _getSpecies (dog):\r\n return dog.kind\r\n\r\ninit (myDog, 'wraff', 'Retriever', 'Bello') \r\ninit (yourDog, 'kef', 'Poodle', 'Nouchka')\r\n\r\neat (myDog, 'blikvoer')\r\nwagTail (myDog)\r\neat (yourDog, 'droogvoer')\r\nreproduce (myDog, 4)\r\nmove (yourDog)\r\nreproduce (yourDog, 5)\r\nmove (myDog)\r\nwagTail (yourDog)\r\n","sub_path":"module_inleiding_programmeren_in_python/les_5_klassen/progs/prog_01_animals/animals_1.py","file_name":"animals_1.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"218935912","text":"\"\"\"Plot infrastructure exposure\n\nCount map, histogram:\nEdge exposure number of times exposed / number of models\n\nCount map, histogram\nper link, lowest return period (current euwatch) to which it is exposed\nper link, lowest return period (across any model) to which it is exposed\n\"\"\"\n# pylint: disable=C0103\nimport os\nimport sys\n\nimport cartopy.crs as ccrs\nimport cartopy.io.shapereader as shpreader\nimport matplotlib.colors\nimport matplotlib.patches as mpatches\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom shapely.geometry import LineString\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', '..'))\nfrom scripts.utils import *\n\ndef main():\n config = load_config()\n data_path = config['data_path']\n figures_path = config['figures_path']\n\n states_filename = os.path.join(data_path, 'Infrastructure', 'Boundaries',\n 'ne_10m_admin_0_countries_lakes.shp')\n\n # Roads\n road_filename = os.path.join(\n data_path, 'Analysis_results', 'spof_localfailure_results', 'tz_road_spof_geom.shp')\n\n # Rail\n rail_filename = os.path.join(\n data_path, 'Analysis_results', 'spof_localfailure_results', 'tz_rail_spof_geom.shp')\n\n # Exposure\n exposure_filename = os.path.join(\n data_path, 'Analysis_results', 'tz_flood_stats_3.xlsx')\n\n proj_lat_lon = ccrs.PlateCarree()\n\n specs = [\n # tanroads_link_flooding: link: model_frequency,rpmin_curr,rpmin_fut\n {\n 'sheet_name': 'tanroads_link_flooding',\n 'shape_filename': road_filename,\n 'id_col': 'link',\n 'val_col': 'model_frequency',\n 'legend_label': 'Proportion of models exposed',\n 'filename': 'exposure_road_links_model_frequency.png',\n 'title': 'Road link exposure to flooding'\n },\n {\n 'sheet_name': 'tanroads_link_flooding',\n 'shape_filename': road_filename,\n 'id_col': 'link',\n 'val_col': 'rpmin_curr',\n 'legend_label': 'Return period (y)',\n 'filename': 'exposure_road_links_rpmin_curr.png',\n 'title': 'Road minimum current return period exposure'\n },\n {\n 'sheet_name': 'tanroads_link_flooding',\n 'shape_filename': road_filename,\n 'id_col': 'link',\n 'val_col': 'rpmin_fut',\n 'legend_label': 'Return period (y)',\n 'filename': 'exposure_road_links_rpmin_future.png',\n 'title': 'Road minimum future return period exposure'\n },\n # rail_edge_flooding: id: model_frequency,rpmin_curr,rpmin_fut\n {\n 'sheet_name': 'rail_edge_flooding',\n 'shape_filename': rail_filename,\n 'id_col': 'id',\n 'val_col': 'model_frequency',\n 'legend_label': 'Proportion of models exposed',\n 'filename': 'exposure_rail_links_model_frequency.png',\n 'title': 'Rail link exposure to flooding'\n },\n {\n 'sheet_name': 'rail_edge_flooding',\n 'shape_filename': rail_filename,\n 'id_col': 'id',\n 'val_col': 'rpmin_curr',\n 'legend_label': 'Return period (y)',\n 'filename': 'exposure_rail_links_rpmin_curr.png',\n 'title': 'Rail minimum current return period exposure'\n },\n {\n 'sheet_name': 'rail_edge_flooding',\n 'shape_filename': rail_filename,\n 'id_col': 'id',\n 'val_col': 'rpmin_fut',\n 'legend_label': 'Return period (y)',\n 'filename': 'exposure_rail_links_rpmin_future.png',\n 'title': 'Rail minimum future return period exposure'\n },\n ]\n\n for spec in specs:\n print(spec['title'])\n # Read from excel\n excel_data = pd.read_excel(\n exposure_filename,\n sheet_name=spec['sheet_name']\n )\n lookup = {}\n for i, row in excel_data.iterrows():\n value = row[spec['val_col']]\n if spec['id_col'] == 'link':\n id_ = int(row[spec['id_col']])\n else:\n id_ = row[spec['id_col']]\n\n if spec['val_col'] == 'model_frequency':\n # convert to ratio\n lookup[id_] = float(value) / 44\n else:\n lookup[id_] = value\n\n data = []\n for record in shpreader.Reader(spec['shape_filename']).records():\n value = lookup[record.attributes[spec['id_col']]]\n if spec['val_col'] == 'model_frequency':\n data.append((record.geometry, value))\n else:\n if value > 0:\n data.append((record.geometry, value))\n\n ax = get_tz_axes()\n plot_basemap(ax, data_path)\n\n if spec['val_col'] == 'model_frequency':\n cmap_name = 'YlOrRd'\n max_value = 1\n else:\n cmap_name = 'YlOrRd_r'\n # max_value = max(value for geom, value in data)\n max_value = 1000\n\n plot_color_map_network(ax, data, proj_lat_lon, spec['legend_label'], cmap_name, max_value)\n\n output_filename = os.path.join(\n figures_path,\n spec['filename'])\n plt.savefig(output_filename)\n plt.close()\n\n\ndef plot_color_map_network(ax, data, proj, label, cmap_name, max_value):\n \"\"\"Plot line data to current map\n \"\"\"\n # Set color_map\n colors = plt.get_cmap(cmap_name)\n color_map = plt.cm.ScalarMappable(cmap=colors, norm=matplotlib.colors.Normalize(vmin=0, vmax=max_value))\n\n\n for geom, value in data:\n if value > 0:\n color = color_map.to_rgba(value)\n else:\n color = color_map.to_rgba(0)\n\n ax.add_geometries(\n [geom],\n crs=proj,\n edgecolor=color,\n facecolor='none',\n zorder=2)\n\n # Add colorbar\n color_map._A = [] # hack in array to avoid error\n cbar = plt.colorbar(color_map, ax=ax, fraction=0.05, pad=0.01, drawedges=False, orientation='horizontal')\n cbar.outline.set_color(\"none\")\n cbar.ax.set_xlabel(label)\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/3_plot/exposure/create_exposure_plots.py","file_name":"create_exposure_plots.py","file_ext":"py","file_size_in_byte":6161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"322731394","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nfrom os import path as op\nimport cv2\nimport tornado.auth\nimport tornado.escape\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.ioloop\nimport tornado.options\nimport tornado.process\nimport tornado.web\nfrom tornado.options import define, options\nimport os\nfrom monitor.FaceHandle import FaceDetector\n# from fdfs_client.client import *\n\ndefine(\"port\", default=8222, help=\"run on the given port\", type=int)\nROOT = op.normpath(op.dirname(__file__))\nSTREAM = tornado.process.Subprocess.STREAM\n\n\n\n# application configuration\nclass Application(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r\"/normal\", IndexHandler),\n (r\"/recognise\", RecogniseHandler),\n (r\"/video_streamer\", VideoStreamerHandler),\n (r\"/video_streamer_detect\", VideoStreamerDetectHandler)\n ]\n settings = dict(\n template_path=os.path.join(os.path.dirname(__file__), \"templates\"),\n static_path=os.path.join(os.path.dirname(__file__), \"static\"),\n debug=True\n )\n\n tornado.web.Application.__init__(self, handlers, **settings)\n\n# 主页\nclass IndexHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"devicetest.html\",\n hostadd=\"172.28.184.77:8222\"\n )\n\nclass RecogniseHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"devicetest2.html\",hostadd=\"172.28.184.77:8222\")\n\n# 正常视屏流\nclass VideoStreamerHandler(tornado.web.RequestHandler):\n\n def initialize(self):\n self.cam = cv2.VideoCapture(\"rtmp://172.28.184.87:1935/small/a\")\n\n def set_default_headers(self):\n self.set_header('Content-Type', 'multipart/x-mixed-replace;boundary=--frame')\n\n '''视频流处理'''\n\n @tornado.web.asynchronous\n @tornado.gen.coroutine\n def get(self):\n while True:\n ret, frame = self.cam.read()\n ret, jpeg = cv2.imencode('.jpg', frame)\n srt = (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + jpeg.tostring() + b'\\r\\n\\r\\n')\n self.write(srt)\n yield tornado.gen.Task(self.flush)\n\n# 监控视屏流\nclass VideoStreamerDetectHandler(tornado.web.RequestHandler):\n def initialize(self):\n self.cam = cv2.VideoCapture(\"rtmp://172.28.184.87:1935/small/a\")\n self.framecount=self.cam.get(cv2.CAP_PROP_FPS)\n self.nowcount = 1\n print(self.framecount)\n\n def set_default_headers(self):\n self.set_header('Content-Type', 'multipart/x-mixed-replace;boundary=--frame')\n\n '''视频流处理'''\n\n @tornado.web.asynchronous\n @tornado.gen.coroutine\n def get(self):\n while True:\n\n self.nowcount += 1\n ret, frame = self.cam.read()\n ret, jpeg = cv2.imencode('.jpg', frame)\n\n if self.nowcount%self.framecount ==0:\n print(self.nowcount)\n facehandle = FaceDetector().process_frame_with_detect(frame)\n if facehandle is not None:\n print(2)\n ret, jpeg = cv2.imencode('.jpg', facehandle)\n\n srt = (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + jpeg.tostring() + b'\\r\\n\\r\\n')\n self.write(srt)\n yield tornado.gen.Task(self.flush)\n\n# Start it up\ndef main():\n tornado.options.parse_command_line()\n ioloop = tornado.ioloop.IOLoop.instance()\n http_server = tornado.httpserver.HTTPServer(Application())\n http_server.listen(options.port)\n ioloop.start()\n\nif __name__ == '__main__':\n main()\n","sub_path":"facelib/webcam_stream.py","file_name":"webcam_stream.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"453594422","text":"from django.shortcuts import render, redirect\nfrom teacher.models import categories, Courses, VideoUploads, Sections, questions, answers, student_mark\nfrom home.models import User\nfrom student.models import student_certificate, student_register_courses\nimport sys, traceback\nfrom django.http import JsonResponse, HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt,csrf_protect\nimport os\nfrom PIL import Image\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\nfrom django.conf import settings\nimport img2pdf\nfrom datetime import datetime\nimport random, string\n\n\ndef getVideoCnt(course):\n\tssss = Sections.objects.filter(course_id=course.id).values_list(\"id\", flat=True)\n\tssss = map(str, ssss)\n\tstrr = ','.join(ssss)\n\tvideoListCnt = VideoUploads.objects.extra(where=['FIND_IN_SET(section_id, \"' + strr + '\")']).count()\n\treturn videoListCnt\n\ndef playground(request,id): \n\tif request.session.get('user_id') == None:\n\t\treturn redirect('/')\n\n\tstudent_for_video = request.session.get('user_id')\n\tfirst_list = []\n\tDict = {}\n\tsecond_list = []\n\tDict_2 = {}\n\tcourse_name = Courses.objects.get(id = id).name\n\tsection_continue_query = student_register_courses.objects.filter(course_id_id=id,student_id_id=student_for_video).values('last_completed_section_id')\n\tfor i in section_continue_query:\n\t\tsection_continue = i['last_completed_section_id']\n\tif Sections.objects.filter(course_id = id).exists():\n\t\t_obj = Sections.objects.filter(course_id = id,type = \"video\") \n\t\tcount = 0\n\t\tcount_2 = 0\n\t\tfor i in _obj:\n\t\t\tif VideoUploads.objects.filter(section_id = i.id).exists():\n\t\t\t\teleDict = []\n\t\t\t\tvideo_obj = VideoUploads.objects.filter(section_id=i.id)\n\t\t\t\tif section_continue == video_obj[0].id :\n\t\t\t\t\tsection_continue = 999\n\t\t\t\tfor j in video_obj:\n\t\t\t\t\tmyDict = {}\n\t\t\t\t\tcount += 1\n\t\t\t\t\tmyDict[\"sr_no\"] = count\n\t\t\t\t\tmyDict[\"url\"] = j.url\n\t\t\t\t\tmyDict[\"video_name\"] = j.name\n\t\t\t\t\tmyDict[\"id\"] = j.id\n\t\t\t\t\teleDict.append(myDict)\n\t\t\t\ti.videoList = eleDict\n\n\t\tobj = Sections.objects.filter(course_id = id,type = \"video\")\n\t\tcount=0\n\t\tcount_2=0\n\t\tfor i in obj:\n\t\t\tcount +=1\n\t\t\tDict[\"sr_no\"] = count\n\t\t\tDict[\"section_name\"] = i.name\n\t\t\tid_course = i.course_id\n\t\t\tif VideoUploads.objects.filter(section_id = i.id).exists():\n\t\t\t\tvideo_obj = VideoUploads.objects.filter(section_id = i.id)\n\t\t\t\tif section_continue == video_obj[0].id :\n\t\t\t\t\tsection_continue = 999\n\t\t\t\tfor j in video_obj:\n\t\t\t\t\tDict_2[\"id\"] = j.id\n\t\t\t\t\tDict[\"url\"] = j.url\n\t\t\t\t\tDict[\"video_name\"] = j.name\n\t\t\tif count < 2:\n\t\t\t\t# first_list.append(Dict)\n\t\t\t\tfirst_list = Dict\n\t\t\t\tDict = {}\n\t\t\telse:\n\t\t\t\tpass\n\t\tfor k in obj:\n\t\t\tcount_2 +=1\n\t\t\tDict_2[\"sr_no\"] = count_2\n\t\t\tDict_2[\"section_name\"] = k.name\n\t\t\tif VideoUploads.objects.filter(section_id = k.id).exists():\n\t\t\t\tvideo_obj = VideoUploads.objects.filter(section_id = k.id)\n\t\t\t\tif section_continue == video_obj[0].id :\n\t\t\t\t\tsection_continue = 999\n\t\t\t\tfor h in video_obj:\n\t\t\t\t\tDict_2[\"id\"] = h.id\n\t\t\t\t\tDict_2[\"url\"] = h.url\n\t\t\t\t\tDict_2[\"video_name\"] = h.name\n\t\t\tsecond_list.append(Dict_2)\n\t\t\tDict_2 = {}\n\t\tLength = len(second_list)\n\t\tif Length > 1 :\n\t\t\tfor e in range(len(second_list) - 1, -1, -1):\n\t\t\t\tif second_list[e]['sr_no'] == 1:\n\t\t\t\t\tsecond_list.pop(e)\n\n\t\t\t# return render(request, 'video/playground.html',{\"video_list\":video_obj,\"course_name\":course_name,\"first_video\":first_list,\"second_video\":second_list,\"course_id\":id,\"id_course\":id_course})\n\t\t\treturn render(request, 'video/playground.html',{'section_continue':section_continue,\"video_list\":video_obj,\"course_name\":course_name,\"first_video\":first_list,\"second_video\":second_list,\"course_id\":id,\"id_course\":id_course,'section_list':_obj})\n\t\telse:\n\t\t\t# return render(request, 'video/playground.html',{\"video_list\":video_obj,\"course_name\":course_name,\"first_video\":first_list,\"course_id\":id,\"id_course\":id_course})\n\t\t\treturn render(request, 'video/playground.html',{'section_continue':section_continue, \"video_list\":video_obj,\"course_name\":course_name,\"first_video\":first_list,\"course_id\":id,\"id_course\":id_course,'section_list':_obj})\n\telse:\n\t\treturn render(request, 'video/playground.html', {})\n\n@csrf_exempt\ndef addtoprogress(request,id):\n\tcurrentvidid = request.POST.get('currentvidid')\n\tstudent = request.POST.get('student')\n\tcourse = request.POST.get('course')\n\n\tcourselasrsection = Sections.objects.filter(course_id = course,type = \"video\").values('id').all().last()['id']\n\tlastvid = VideoUploads.objects.filter(section_id=courselasrsection).values('id')[0]['id']\n\n\tif currentvidid == 999:\n\t\treturn HttpResponse(\"success\");\n\n\tif currentvidid == lastvid:\n\t\tcurrentvidid = 999\n\t\taddprogress = student_register_courses.objects.filter(course_id_id=course,student_id_id=student)[0]\n\t\taddprogress.last_completed_section_id = currentvidid\n\t\taddprogress.save()\n\n\treturn HttpResponse(\"success\");\n\n\n\n\ndef video_quiz(request,id):\n\tcourse = Courses.objects.get(pk=id)\n\treturn render(request, 'video/quiz.html', {'course':course})\n\ndef video_quiz2(request):\n\tquizNo = request.POST.get('quizNo')\n\tid = request.POST.get('course_id')\n\tcourse = Courses.objects.get(pk=id)\n\n\tright = request.POST.get('right')\n\twrong = request.POST.get('wrong')\n\tskip = request.POST.get('skip')\n\n\tif right == None:\n\t\tright = 0\n\tif wrong == None:\n\t\twrong = 0\n\tif skip == None:\n\t\tskip = 0\n\n\tif quizNo == None:\n\t\tif Sections.objects.filter(course_id=course.id).filter(type='question').exists():\n\t\t\tsectionList = Sections.objects.filter(course_id=course.id).filter(type='question').values_list('id',flat=True)\n\t\t\tsectionList = map(str, sectionList)\n\t\t\tidstr = ','.join(sectionList)\n\t\t\tquesList = questions.objects.extra(where=['FIND_IN_SET(section_id, \"' + idstr + '\")']).order_by('id')\n\n\t\t\tif quesList.count() == 0:\n\t\t\t\treturn redirect(\"/courses/\")\n\t\t\telse :\n\t\t\t\tquestion = quesList[0]\n\t\t\t\tquesCnt = quesList.count()\n\t\t\t\tquesEleList = question.content.split(',')\n\t\t\t\tquesEleList.pop()\n\telse:\n\t\tif Sections.objects.filter(course_id=course.id).filter(type='question').exists():\n\t\t\tsectionList = Sections.objects.filter(course_id=course.id).filter(type='question').values_list('id',flat=True)\n\t\t\tsectionList = map(str, sectionList)\n\t\t\tidstr = ','.join(sectionList)\n\t\t\tquesList = questions.objects.extra(where=['FIND_IN_SET(section_id, \"' + idstr + '\")']).order_by('id')\n\n\t\t\tif quesList.count() == 0:\n\t\t\t\treturn redirect(\"/courses/\")\n\t\t\telse:\n\t\t\t\tquizNo = int(quizNo)\n\t\t\t\tquesCnt = quesList.count()\n\t\t\t\tif quizNo*1 >= quesCnt:\n\t\t\t\t\treturn redirect('/courses')\n\t\t\t\tquestion = quesList[quizNo]\n\t\t\t\tquesEleList = question.content.split(',')\n\t\t\t\tquesEleList.pop()\n\tif quizNo == None:\n\t\tquizNo = 0;\n\treturn render(request, 'video/quiz2.html', {'question':question, 'count':quesCnt, 'eleList':quesEleList, 'questionNo':(quizNo+1),'course_id':id, 'left':quesCnt-quizNo-1, 'right':right, 'wrong':wrong, 'skip':skip})\n\ndef video_quiz3(request,id):\n\n return render(request, 'video/quiz3.html', {})\n\ndef getQuiz(request):\n\tcourse = request.POST.get('course')\n\tquiz = request.POST.get('quiz')\n\n\ndef saveQuizAnswer(request):\n\tcourse_id = request.POST.get('id')\n\tquestion_id = request.POST.get('questionId')\n\tdata = request.POST.get('answer')\n\tresult = request.POST.get('result')\n\tid = request.user.id\n\ttype = request.POST.get('type')*1\n\n\ttry:\n\t\tif answers.objects.filter(course_id=course_id,question_id=question_id).exists():\n\t\t\tans = answers.objects.filter(course_id=course_id,question_id=question_id)[0]\n\t\t\tans.answer = data\n\t\t\tans.pending = type\n\t\t\tans.student_id = id\n\t\t\tans.result = result\n\t\t\tans.save()\n\t\telse :\n\t\t\tans = answers(\n\t\t\t\tcourse_id = course_id,\n\t\t\t\tquestion_id = question_id,\n\t\t\t\tanswer = data,\n\t\t\t\tpending = type,\n\t\t\t\tstudent_id = id,\n\t\t\t\tresult = result\n\t\t\t)\n\t\t\tans.save()\n\t\tmsg = 'success'\n\texcept:\n\t\ttb = sys.exc_info()[2]\n\t\ttbinfo = traceback.format_tb(tb)[0]\n\t\tmsg = tbinfo + \"\\n\" \": \" + str(sys.exc_info())\n\n\tto_return = {'msg': msg}\n\treturn JsonResponse(to_return)\n\ndef generateRandomChar():\n\tx = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(8))\n\treturn x\n\ndef getCertificate(request):\n\tuser_id = request.user.id\n\tid = request.POST.get('course')\n\tsrc = ''\n\tif student_mark.objects.filter(course_id=id,student_id=user_id).exists() == 1:\n\t\t#create certificate image and save it and give it to student...\n\t\turl = settings.STATICFILES_DIRS[0] + '/certificates/en.jpg'\n\t\timg = Image.open(url)\n\t\tdraw = ImageDraw.Draw(img)\n\t\tfonturl = settings.STATICFILES_DIRS[0] + '/certificates/font.ttf'\n\t\tfont = ImageFont.truetype(fonturl,110)\n\t\tname = request.user.first_name + \" \" +request.user.last_name\n\t\tstudentfullname =request.user.first_name + \" \" +request.user.last_name\n\n\t\t#drawing name to the img...\n\t\tlength = len(name)\n\t\tdif = 12 - length\n\t\tnamePos = [1250+dif*15, 705]\n\n\t\tdraw.text(namePos, name , (255, 0, 255), font=font) # this will draw text with Blackcolor and 16 size\n\n\t\t#drawing time to the img\n\n\t\tname = '60hours'\n\t\tlength = len(name)\n\t\tnamePos = [770, 830]\n\n\t\tdraw.text(namePos, name, (255, 0, 255), font=font) # this will draw text with Blackcolor and 16 size\n\n\t\t# drawing course name to the img\n\t\tcourse = Courses.objects.get(pk=id)\n\t\tname = course.name\n\t\tlength = len(name)\n\t\tdif = 12 - length\n\t\tnamePos = [1300+dif*15, 830]\n\n\t\tdraw.text(namePos, name, (255, 0, 255), font=font) # this will draw text with Blackcolor and 16 size\n\n\t\t# drawing date to the img\n\t\ttime = datetime.today().strftime(\"%b %d,%Y\")\n\t\tname = time\n\t\tlength = len(name)\n\t\tdif = 12 - length\n\t\tnamePos = [2000, 830]\n\n\t\tdraw.text(namePos, name, (255, 0, 255), font=font) # this will draw text with Blackcolor and 16 size\n\n\t\t# drawing teacher's name to the img\n\t\tteacher = User.objects.get(pk=course.user_id)\n\t\tname = teacher.first_name + \" \" + teacher.last_name\n\t\tlength = len(name)\n\t\tdif = 12 - length\n\t\tnamePos = [1250+dif*15, 1180]\n\n\t\tdraw.text(namePos, name, (255, 0, 255), font=font) # this will draw text with Blackcolor and 16 size\n\n\t\t# drawing teacher's category name to the img\n\n\t\tname = categories.objects.get(pk=course.scat_id).name\n\t\tlength = len(name)\n\t\tdif = 12 - length\n\t\tnamePos = [1200 + dif * 15, 1300]\n\n\t\tdraw.text(namePos, name, (255, 0, 255), font=font) # this will draw text with Blackcolor and 16 size\n\t\trandchar = generateRandomChar()\n\t\tsaveurl = settings.STATICFILES_DIRS[0] + '/certificates/' + randchar + '_' + studentfullname + '.jpg'\n\t\tsaveurl1 = settings.STATICFILES_DIRS[0] + '/certificates/' + randchar + '_' + studentfullname + '.pdf'\n\t\tsrc = '/certificates/' + randchar + '_' + studentfullname + '.jpg'\n\t\tsrc1 = '/certificates/' + randchar + '_' + studentfullname + '.pdf'\n\t\tfile = open(saveurl1, \"wb\")\n\t\timg.save(saveurl)\n\t\timg2 = Image.open(saveurl)\n\t\tpdf_bytes = img2pdf.convert(img2.filename)\n\t\tfile.write(pdf_bytes)\n\n\t\t#save this file url to the db;\n\t\tif student_certificate.objects.filter(course_id=id,student_id=user_id).exists() == 1:\n\t\t\tone = student_certificate.objects.filter(course_id=id,student_id=user_id)[0]\n\t\t\tone.url = src1\n\t\t\tone.save()\n\t\telse :\n\t\t\tone = student_certificate(\n\t\t\t\tcourse_id = id,\n\t\t\t\tstudent_id = user_id,\n\t\t\t\turl = src1\n\t\t\t)\n\t\t\tone.save()\n\tret = {'msg':'success', 'src':src1}\n\treturn JsonResponse(ret)\n\t# return render(request, 'video/img_view.html', {'src' : src})\n\ndef saveQuizMark(request):\n\tmark = request.POST.get('mark')\n\tid = request.user.id\n\tcourse = request.POST.get('course')\n\n\tif student_mark.objects.filter(course_id=course,student_id=id).exists() == 0 :\n\t\tnew = student_mark(\n\t\t\tcourse_id = course,\n\t\t\tstudent_id = id,\n\t\t\tmark = mark\n\t\t)\n\t\tnew.save()\n\telse :\n\t\tone = student_mark.objects.filter(course_id=course, student_id=id)\n\t\tone[0].mark = mark\n\t\tone[0].save()\n\tto_return = { 'msg':'success' }\n\treturn JsonResponse(to_return)\n\n\n","sub_path":"video/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"303500807","text":"#!/usr/bin/env python\n\n__author__ = \"Maxime Beauchamp\"\n__version__ = \"0.1\"\n__date__ = \"2020-12-10\"\n__email__ = \"maxime.beauchamp@imt-atantique.fr\"\n\nfrom pathlib import Path\n\nfrom Metrics_NATL60 import *\n\n# function to create recursive paths\nfrom ruamel import yaml\n\n#\n# AnDA_lag = sys.argv[1]\n# NN_lag = sys.argv[2]\n# type_obs = sys.argv[3]\n# domain = sys.argv[4]\n\nworkpath = Path(\"work\")\nworkpath.mkdir(exist_ok=True, parents=True)\n\nXP=2 # XP = 1....5\nworkpath = Path(\"work\")\nworkpath.mkdir(exist_ok=True, parents=True)\nsubm = 'submissions_XP'+str(XP)\nsubmissions_files = list(Path(subm).glob('*'))\nsubmission_data =[]\nfor sub_file in submissions_files:\n with open(sub_file, 'r') as f:\n submission_data.append(yaml.load(f))\n\nsub_df = pd.DataFrame(submission_data)\n(workpath / \"submission.md\").write_text(sub_df.to_markdown())\nfor domain in sub_df.domain.drop_duplicates():\n sub_domain = sub_df.loc[lambda df: df.domain == domain]\n\n ## parameters\n if domain==\"OSMOSIS\":\n extent = [-19.5,-11.5,45.,55.]\n indLat = 200\n indLon = 160\n elif domain=='GULFSTREAM':\n extent = [-65.,-55.,33.,43.]\n indLat = 200\n indLon = 200\n else:\n extent=[-65.,-55.,30.,40.]\n indLat = 200\n indLon = 200\n\n ## store all data in a list\n GT_file = \"https://s3.eu-central-1.wasabisys.com/melody/Metrics_NATL60/Datasets/XP\"+str(XP)+\"/NATL60_\"+domain+\"_XP\"+str(XP)+\"_GT.nc#mode=bytes\"\n OBS_file = \"https://s3.eu-central-1.wasabisys.com/melody/Metrics_NATL60/Datasets/XP\"+str(XP)+\"/NATL60_\"+domain+\"_XP\"+str(XP)+\"_OBS_NADIRSWOT_obs.nc#mode=bytes\"\n OI_file = \"https://s3.eu-central-1.wasabisys.com/melody/Metrics_NATL60/Datasets/XP\"+str(XP)+\"/NATL60_\"+domain+\"_XP\"+str(XP)+\"_OI_NADIRSWOT_obs.nc#mode=bytes\"\n sub_files = sub_domain['data']\n\n # Reload results\n lday = xr.open_dataset(GT_file,decode_times=False).Time.values\n GT = xr.open_dataset(GT_file,decode_times=False).ssh.values\n OBS = xr.open_dataset(OBS_file,decode_times=False).ssh.values\n OI = xr.open_dataset(OI_file,decode_times=False).ssh.values\n sub_ds = [xr.open_dataset(f\"{sub_file}#mode=bytes\",decode_times=False).ssh.values for sub_file in sub_files]\n\n # list_data (nadir+swot)\n list_data = [GT, OBS, OI, *sub_ds]\n labels_data = np.array(['GT','Obs (nadir+swot)','OI (nadir+swot)', *sub_domain['experiment_label']])\n list_suffix = np.array(['GT','Obs_nadirswot','OI_nadirswot',*sub_domain['experiment_slug']])\n colors = np.array(\n ['k', '', 'red', 'seagreen', 'steelblue', 'darkorange', '', 'red', 'seagreen', 'steelblue', 'darkorange'])[:len(list_data)]\n symbols = np.array(['k', '', 'p', 'p', 'p', 'p', 'p', '', 'o', 'o', 'o', 'o', 'o'])[:len(list_data)]\n lstyle = np.array(\n ['solid', '', 'dashed', 'dashed', 'dashed', 'dashed', 'dashed', '', 'solid', 'solid', 'solid', 'solid',\n 'solid'])[:len(list_data)]\n lwidth = np.array([2, 2, 2, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1])[:len(list_data)]\n\n # compare shapes and do appropriate downscaling with minimal resolution\n min_res=1e9\n for i in range(len(list_data)):\n min_res=min(min_res,list_data[i].shape[1])\n for i in range(len(list_data)):\n if list_data[i].shape[1]>min_res:\n dwscale = int(list_data[i].shape[1]/min_res)\n list_data[i] = einops.reduce(list_data[i], '(t t1) (h h1) (w w1) -> t h w', t1=1, h1=dwscale, w1=dwscale, reduction=np.nanmean)\n print(list_data[i].shape)\n dwscale = int(200/min_res)\n indLon = int(indLon/dwscale)\n indLat = int(indLat/dwscale)\n lon = np.arange(extent[0],extent[1],1/(20/dwscale))\n lat = np.arange(extent[2],extent[3],1/(20/dwscale))\n\n\n if domain==\"OSMOSIS\":\n ymax = [0.3,1.]\n else:\n ymax = [0.2,1.]\n resfile=workpath / f\"{domain}_TS_nRMSE_nadirswot.png\"\n plot_nRMSE(list_data,labels_data,colors,symbols,lstyle,lwidth,lday,ymax[0],resfile,gradient=False)\n resfile=workpath / f\"{domain}_TS_nRMSE_Grad_nadirswot.png\"\n plot_nRMSE(list_data,labels_data,colors,symbols,lstyle,lwidth,lday,ymax[1],resfile,gradient=True)\n\n resfile=workpath / f\"{domain}_nrmse_score.txt\"\n nRMSE_scores(list_data,labels_data,resfile,id_xp=XP,gradient=False)\n\n","sub_path":"scripts/postpro.py","file_name":"postpro.py","file_ext":"py","file_size_in_byte":4342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"490263421","text":"# import packages\nfrom __future__ import print_function, division\nfrom psychopy import visual, event, core, logging, gui, data\nfrom psychopy.tools.filetools import fromFile, toFile\nimport numpy as np\nimport pandas as pd\nimport random\nimport csv\nimport math\nimport itertools\nfrom PIL import Image\nimport PIL.ImageOps\nimport scipy\n\n\n\nbasepairs = [(3, '3i'), (4, '4i'), (5, '5i'), (6, '6i'),\n (23, 34), (36, 51), (58, 60), (78, 92)]\n\n\ndef instruction_images(text, images, width=800, delay=0.25, last=False, rect=False, double=True, duration=1):\n quick_exit()\n mywin.flip()\n instruct = visual.TextStim(mywin, text=text, wrapWidth=width,\n alignHoriz='left', pos=(-(width/2), 100))\n wrap = 'When you are ready to begin, press SPACE' if last else 'Press SPACE to continue'\n color = green if last else 'white'\n bold = True if last else False\n space = visual.TextStim(mywin, text=wrap, wrapWidth=width, colorSpace='rgb255',\n alignHoriz='center', color=color, pos=(0, -200), bold=bold)\n instruct.draw()\n space.draw()\n mywin.update()\n NoKey = True\n while NoKey:\n allKeys = event.getKeys()\n if len(allKeys) > 0:\n resp = allKeys[0]\n if resp == 'space':\n NoKey = False\n gen_image(images[0])\n if rect:\n gen_patch()\n instruct.draw()\n space.draw()\n mywin.update()\n instruct.draw()\n space.draw()\n core.wait(duration)\n mywin.flip()\n core.wait(1)\n if double:\n gen_image(images[1])\n instruct.draw()\n space.draw()\n mywin.update()\n core.wait(duration)\n mywin.flip()\n core.wait(delay)\n\n\ndef associative_inf_instruct_old():\n instruction_screen('The next task is a memory test. During the square-detection task, if you saw a certain image (A), it was ALWAYS followed by the same image (B). Each of those images was paired with a new image in the set you just studied. Image A was now paired with C, and B with D. In this next task, you will be provided with a particular image C, and will be asked to select the correct image D.')\n instruction_screen('In other words, you will be presented with a cue image, and three possible images as answers. You will need to make an inference and choose the image which was associated with the same initial pair as the cue.')\n instruction_images('To clarify, during the square detection task, a set of two images like these might always have been paired together...',\n [103, 104])\n instruction_images('In the last task, you studied pairs where the first image was newly paired with an alternate image...', [103, 108], delay=1)\n instruction_images('...and the second image was also newly paired with an alternate image.', [104, 111])\n instruction_static('For the upcoming test, you are presented with this image:', [108, 108], double=False)\n instruction_static('And the correct answer would be this image, because it was previously associated with the same intermediate pair:',\n [111, 111], double=False)\n instruction_screen('On each trial, you will be presented with a cue image, and three possible answers below. Press the left arrow to choose the image on the lefthand side, the down arrow to choose the image in the middle, or the right arrow to choose the image on the right.')\n instruction_screen('If you have any questions about this, please ask the experimenter now.', delay=2, last=True)\n\n\ndef gen_trial_vis(exposures, pairset):\n basecoord_list = []\n for i in range(len(pairset)):\n angle = np.random.uniform(0, 360)\n distance = np.random.uniform(0, 56)\n newx = int(np.round(math.cos(angle * math.pi / 180) * distance, 0))\n newy = int(np.round(math.sin(angle * math.pi / 180) * distance, 0))\n basecoord_list.append(tuple([newx, newy]))\n targ_pos = zip(pairset, basecoord_list)\n pairs = [i for i in targ_pos]\n trial_list = []\n for j in range(exposures+1):\n shuffled = pairs\n random.shuffle(shuffled)\n if j != 0:\n while shuffled[0] == lastitem:\n random.shuffle(shuffled)\n _=trial_list.extend(shuffled)\n lastitem = shuffled[-1]\n while any(i == j for i, j in zip(trial_list, trial_list[1:])):\n assert False\n learn_list = trial_list[:-len(pairset)]\n transfer_list = trial_list[-len(pairset):]\n return learn_list, transfer_list\n\n\nlearn_list, transfer_list = gen_trial_vis(4, basepairs)\n","sub_path":"old_functions_fractals.py","file_name":"old_functions_fractals.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"118632457","text":"import sys\r\nfrom collections import deque\r\n\r\nn,m,t=map(int, sys.stdin.readline().split())\r\nboard=[deque(int(x) for x in sys.stdin.readline().split()) for _ in range(n)]\r\nfor _ in range(t):\r\n x,d,k=map(int, sys.stdin.readline().split())\r\n total=0\r\n for i in range(n):\r\n total+=board[i]\r\n if (i+1)%x==0:\r\n board[i].rotate(k)\r\n else:\r\n board[i].rotate(-k)\r\n if total!=0:\r\n have_to_remove=[]\r\n for i in range(n):\r\n for j in range(m-1):\r\n if board[i][j]!=0 and board[i][j+1]!=0 and board[i][j]==board[i][j+1]:\r\n have_to_remove.append((i,j))\r\n have_to_remove.append((i,j+1))\r\n if board[i][0]!=0 and board[i][-1]!=0 and board[i][0]==board[i][-1]:\r\n have_to_remove.append((i,0))\r\n have_to_remove.append((i,m-1))\r\n for j in range(m):\r\n for i in range(n-1):\r\n if board[i][j]!=0 and board[i+1][j]!=0 and board[i][j]==board[i+1][j]:\r\n have_to_remove.append((i,j))\r\n have_to_remove.append((i+1,j))\r\n have_to_remove=list(set(have_to_remove))\r\n for i in range(len(have_to_remove)):\r\n x,y=have_to_remove[i]\r\n board[x][y]=0\r\n if len(have_to_remove)==0:\r\n avg_sum=0\r\n zero_cnt=0\r\n for i in range(n):\r\n avg_sum+=board[i]\r\n zero_cnt+=board[i].count(0)\r\n avg=avg_sum/(n*m-zero_cnt)\r\n for i in range(n):\r\n for j in range(m):\r\n if board[i][j]!=0 and board[i][j]>avg:\r\n board[i][j]-=1\r\n elif board[i][j]!=0 and board[i][j]= 5)\n\n # Connect to the hosted MongoDB instance\n client = MongoClient()\n\n # create database phx\n db = client['phx']\n\n # store the dataset into MongoDB phx under collection of review5up\n db['review5up'].insert_many(phx_review_5.to_dict('records'))\n\nif __name__ == '__main__':\n Mongo_subset()","sub_path":"src/mongo_subset.py","file_name":"mongo_subset.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"382416586","text":"import asyncio\nimport datetime\nimport typing\n\nimport aiohttp\nimport ujson\n\nfrom ..helpers import ctx\nfrom ..types import (chat, chat_enums, messages, subscription, updates,\n uploads_enums, user)\nfrom ..urls import Urls\nfrom .requests import Requester, UrlType\n\nloop = asyncio.get_event_loop()\n\n\nasync def _open_file(file: str, mode: str, event_loop: asyncio.BaseEventLoop = None):\n return await (event_loop or loop).run_in_executor(None, open, file, mode)\n\n\nclass Bot(ctx.ContextInstanceMixin):\n def __init__(\n self, token: str, timeout: int = 60, _session: aiohttp.ClientSession = None\n ):\n \"\"\"\n\n :param token:\n :param timeout:\n :param _session:\n \"\"\"\n timeout = aiohttp.ClientTimeout(total=timeout + 1) if timeout else None\n self.request = Requester(\n aiohttp.client.ClientSession(timeout=timeout) or _session,\n default_params={\"access_token\": token},\n )\n\n self.set_current(self)\n self.urls = Urls()\n\n self.__polling = False\n self.force_non_model_return = False\n self.open_file = _open_file\n\n # me zone\n async def get_me(self) -> user.User:\n \"\"\"\n\n :return:\n \"\"\"\n return await self.request.get(self.urls.get_me, model=user.User)\n\n async def set_me(self, info: user.SetInfo):\n \"\"\"\n\n :param info:\n :return:\n \"\"\"\n return await self.request(\n \"patch\",\n self.urls.set_me,\n model=user.User,\n json=info.json(skip_defaults=True),\n )\n\n # chats\n async def get_chats(self, lim: int = 50, marker: int = None) -> chat.Chats:\n \"\"\"\n\n :param lim:\n :param marker:\n :return:\n \"\"\"\n return await self.request.get(\n self.urls.get_chats,\n model=chat.Chats,\n params={\"count\": lim, \"marker\": marker},\n )\n\n async def get_chat(self, chat_id: int) -> chat.Chat:\n \"\"\"\n\n :param chat_id:\n :return:\n \"\"\"\n return await self.request.get(self.urls.get_chat(chat_id), model=chat.Chat)\n\n async def edit_chat(self, chat_id: int, edit_chat: chat.EditChatInfo) -> chat.Chat:\n return await self.request(\n \"PATCH\",\n url=self.urls.get_chat(chat_id),\n json=edit_chat.json(),\n model=chat.Chat,\n )\n\n async def action(\n self, chat_id: int, action: chat_enums.ChatAction\n ) -> typing.NoReturn:\n if chat_enums.ChatAction.has(action):\n action = action.value\n\n json = ujson.dumps({\"action\": action})\n\n await self.request.post(self.urls.send_action(chat_id), json=json)\n\n async def get_membership(self, chat_id: int) -> chat.Membership:\n return await self.request.get(\n self.urls.membership(chat_id, \"me\"), model=chat.Membership\n )\n\n async def leave_chat(self, chat_id: int) -> typing.NoReturn:\n await self.request.post(\n self.urls.membership(chat_id, \"me\"), model=chat.Membership\n )\n\n async def get_admins(self, chat_id: int) -> chat.Admins:\n return await self.request.get(\n self.urls.membership(chat_id, \"admins\"), model=chat.Admins\n )\n\n async def get_members(\n self,\n chat_id: int,\n users_ids: typing.List[int] = None,\n count: int = 20,\n marker: int = None,\n ) -> chat.Members:\n return await self.request.get(\n self.urls.membership(chat_id, None),\n model=chat.Members,\n params={\n \"users_ids\": \",\".join(map(str, users_ids) or ()),\n \"marker\": marker,\n \"count\": count,\n },\n )\n\n async def add_members(\n self, chat_id: int, users_ids: typing.List[int]\n ) -> typing.NoReturn:\n await self.request.post(\n self.urls.membership(chat_id, \"me\"),\n params={\"users_ids\": \",\".join(map(str, users_ids) or ())},\n )\n\n async def remove_member(self, chat_id: int, user_id: int):\n await self.request(\n \"DELETE\", self.urls.membership(chat_id, None), params={\"user_id\": user_id}\n )\n\n # messages\n async def get_messages(\n self,\n chat_id: int = None,\n messages_ids: typing.Optional[typing.List[int]] = None,\n from_date: typing.Optional[datetime.datetime] = None,\n to_date: typing.Optional[datetime.datetime] = None,\n lim: int = None,\n ) -> typing.List[updates.Message]:\n \"\"\"\n\n :param chat_id:\n :param messages_ids:\n :param from_date:\n :param to_date:\n :param lim:\n :return:\n \"\"\"\n return await self.request.get(\n self.urls.messages,\n params={\n \"chat_id\": chat_id,\n \"messages_ids\": messages_ids,\n \"from\": from_date.timestamp().__int__()\n if isinstance(from_date, datetime.datetime)\n else None,\n \"to\": to_date.timestamp().__int__()\n if isinstance(to_date, datetime.datetime)\n else None,\n \"count\": lim,\n },\n models_in_list=True,\n model_from_key=\"messages\",\n )\n\n async def send_message(\n self, body: messages.NewMessage, *, chat_id: int = None, user_id: int = None\n ) -> updates.Message:\n \"\"\"\n\n :param body:\n :param chat_id:\n :param user_id:\n :return:\n \"\"\"\n return await self.request.post(\n self.urls.send_message,\n params={\"chat_id\": chat_id, \"user_id\": user_id},\n json=body.json(),\n model=updates.Message,\n model_from_key=\"message\",\n )\n\n async def edit_message(\n self, cfg: messages.EditMessageConfig\n ) -> typing.List[updates.Message]:\n return await self.request(\n \"PUT\",\n self.urls.messages,\n params={\n \"chat_id\": cfg.chat_id,\n \"message_ids\": \",\".join(map(str, cfg.message_ids) or ()),\n \"from\": cfg.from_,\n \"to\": cfg.to,\n \"count\": cfg.count,\n },\n models_in_list=True,\n model_from_key=\"messages\",\n model=updates.Message,\n )\n\n async def delete_message(self, message_id: str):\n await self.request(\n \"DELETE\", self.urls.messages, params={\"message_id\": message_id}\n )\n\n async def construct_message(\n self, session_id: str, request: messages.ConstructorRequest\n ) -> typing.Dict[str, typing.Any]:\n return await self.request(\n \"POST\",\n self.urls.construct_message,\n params={\"session_id\": session_id},\n json=request.json(),\n )\n\n async def answer_callback_query(\n self,\n callback_id: str,\n *,\n edit_message: messages.NewMessage = None,\n notification: str = None\n ) -> typing.NoReturn:\n\n json = {}\n if edit_message is not None:\n json[\"message\"] = edit_message.json()\n if notification is not None:\n json[\"notification\"] = notification\n\n json = ujson.dumps(json)\n\n await self.request.post(\n self.urls.answers, params={\"callback_id\": callback_id}, json=json\n )\n\n async def get_updates(\n self,\n lim: int,\n timeout: int,\n marker: int,\n update_types: typing.Optional[str],\n ignore_old_updates: bool,\n ) -> typing.Tuple[typing.List[updates.Update], int]:\n \"\"\"\n Get Updates\n :param lim: get updates limit\n :param timeout: timeout\n :param marker: last update marker\n :param update_types: comma separated update types from UpdatesEnum\n :param ignore_old_updates: ignore pending updates\n :return:\n \"\"\"\n return await self.request.get(\n self.urls.updates,\n params={\n \"limit\": lim,\n \"timeout\": timeout,\n \"marker\": marker if not ignore_old_updates else -1,\n \"types\": \",\".join(update_types or []),\n },\n model_from_key=\"updates\",\n models_in_list=True,\n model=updates.Update,\n extra_key=\"marker\",\n )\n\n async def subscriptions(self) -> typing.List[subscription.Subscription]:\n tt_url = self.urls.subscriptions\n return await self.request.get(\n tt_url,\n model_from_key=\"subscriptions\",\n models_in_list=True,\n model=subscription.Subscription,\n )\n\n async def subscribe(self, config: subscription.NewSubscriptionConfig) -> dict:\n tt_url = self.urls.subscriptions\n return await self.request.post(tt_url, json=config.json())\n\n async def unsubscribe(self, url: UrlType) -> dict:\n tt_url = self.urls.subscriptions\n return await self.request(\"DELETE\", url=tt_url, params={\"url\": str(url)})\n\n async def make_attachments(\n self, *files: typing.Tuple[str, typing.Tuple[str, typing.Union[bytes, str]]]\n ) -> typing.List[int]:\n raise NotImplementedError()\n\n async def get_upload_url(self, type_: uploads_enums.UploadTypes) -> str:\n return (\n (await self.request.post(self.urls.get_upload_url, params={\"type\": type_}))\n or {}\n ).get(\"url\")\n\n async def __aenter__(self) -> \"Bot\":\n return self\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n await self.request.close()\n","sub_path":"tamtam/api/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":9637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"88796017","text":"from django.http import response\nfrom django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\n\nfrom .serializer import ProductSerializer\nfrom .models import Product\n\n# Create your views here.\n\ndef HomeView(request):\n return render(request, \"home.html\")\n\n@api_view(['GET'])\ndef ApiOverView(request):\n api_urls = {\n 'List' : '/product-list/',\n 'Detail View' : '/product-detail/',\n 'create' : '/create/',\n 'update' : '/update-product/',\n }\n return Response(api_urls)\n \n@api_view(['GET'])\ndef ShowAll(request):\n products = Product.objects.all()\n serializer = ProductSerializer(products, many=True)\n return Response(serializer.data)\n\n@api_view(['GET'])\ndef ShowProduct(request, pk):\n product = Product.objects.get(id=pk)\n serializer = ProductSerializer(product, many=False)\n return Response(serializer.data)\n\n\n@api_view(['POST'])\ndef CreateProduct(request):\n \n serializer = ProductSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n\n@api_view(['PUT'])\ndef UpdateProduct(request,pk):\n product = Product.objects.get(id=pk)\n serializer = ProductSerializer(instance=product, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n\n@api_view(['DELETE'])\ndef DeleteProduct(request,pk):\n product = Product.objects.get(id=pk)\n product.delete()\n return Response(\"Succesfully Deleted!\")","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"85625057","text":"#!/usr/bin/env python3\n\nfrom utest import *\nfrom pithy.util import *\n\nmomoize_tracker = []\n\n@memoize()\ndef f(x, y):\n global memoize_tracker\n momoize_tracker.append((x, y))\n return x + y\n\nf(0, 1)\nf(0, 2)\nf(0, 1)\nf(0, 2)\n\nutest_val([(0, 1), (0, 2)], momoize_tracker)\n","sub_path":"test/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"247491943","text":"# Citation: The system model is taken from https://colab.research.google.com/drive/17KJn7tVyQ3nXlGSGEJ0z6DcpRnRd0VRp\nimport csv\nimport datetime\nimport pickle\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom pyomo.environ import *\nfrom pyomo.dae import *\nfrom pyomo.solvers import *\n\nfrom simple_nn_controller import *\n\nresults_folder = \"expReplay_results/texel13-2/\"\n\n\nclass SimpleSimulator:\n def __init__(self, duration=1, x0_init=0, x1_init=-1):\n # Unique ID for savings csv and plots, based on model timestamp\n self.uid = datetime.datetime.now().strftime(\"%d-%H.%M.%S.%f\")[:-3]\n print(\"Model uid\", self.uid)\n\n # ----- SET UP THE BASIC MODEL -----\n # Set up pyomo model structure\n self.model = ConcreteModel()\n self.model.time = ContinuousSet(bounds=(0, duration))\n\n # State variables\n self.model.x0 = Var(self.model.time)\n self.model.x1 = Var(self.model.time)\n self.model.x0_dot = DerivativeVar(self.model.x0, wrt=self.model.time)\n self.model.x1_dot = DerivativeVar(self.model.x1, wrt=self.model.time)\n # Initial state\n self.model.x0[0].fix(x0_init)\n self.model.x1[0].fix(x1_init)\n\n # Controls\n self.model.u = Var(self.model.time, bounds=(-20, 20))\n\n # Lagrangian cost\n self.model.L = Var(self.model.time)\n self.model.L_dot = DerivativeVar(self.model.L, wrt=self.model.time)\n self.model.L[0].fix(0)\n\n # ODEs\n def _ode_x0(m, t):\n return m.x0_dot[t] == m.x1[t]\n self.model.ode_x0 = Constraint(self.model.time, rule=_ode_x0)\n\n def _ode_x1(m, t):\n return m.x1_dot[t] == -m.x1[t] + m.u[t]\n self.model.ode_x1 = Constraint(self.model.time, rule=_ode_x1)\n\n # Path constraint for x1\n def _path_constraint_x1(m, t):\n return m.x1[t] + 0.5 - 8 * (t - 0.5) ** 2 <= 0\n self.model.constraint_x1 = Constraint(self.model.time, rule=_path_constraint_x1)\n\n # Lagrangian cost\n def _Lagrangian(m, t):\n return m.L_dot[t] == (m.x0[t] ** 2) + (m.x1[t] ** 2) + (5E-3 * m.u[t] ** 2)\n self.model.L_integral = Constraint(self.model.time, rule=_Lagrangian)\n\n # Objective function is to minimize the Lagrangian cost integral\n def _objective(m):\n return m.L[m.time.last()] - m.L[0]\n self.model.objective = Objective(rule=_objective, sense=minimize)\n\n # ----- DISCRETIZE THE MODEL INTO FINITE ELEMENTS -----\n # We fix finite elements at 10, collocation points at 4, controls to be piecewise linear\n discretizer = TransformationFactory(\"dae.collocation\")\n discretizer.apply_to(self.model, nfe=10, ncp=4, scheme=\"LAGRANGE-RADAU\")\n\n # Make controls piecewise linear\n discretizer.reduce_collocation_points(self.model, var=self.model.u, ncp=1, contset=self.model.time)\n\n return\n\n def mpc_control(self):\n mpc_solver = SolverFactory(\"ipopt\")\n mpc_results = mpc_solver.solve(self.model)\n\n return mpc_results\n\n def parse_mpc_results(self):\n # Each t, X0, X1, U, L, instantaneous cost, cost to go, should be a column\n # Label them and return a pandas dataframe\n t = []\n x0 = []\n x1 = []\n u = []\n L = []\n inst_cost = []\n ctg = []\n\n # Record data at the intervals of finite elements only (0.1s), do not include collocation points\n timesteps = [timestep / 10 for timestep in range(11)]\n for time in self.model.time:\n if time in timesteps:\n t.append(time)\n x0.append(value(self.model.x0[time]))\n x1.append(value(self.model.x1[time]))\n u.append(value(self.model.u[time]))\n L.append(value(self.model.L[time]))\n\n # Make sure all 11 time steps are recorded; this was problematic due to Pyomo's float indexing\n assert len(t) == 11\n\n for time in range(len(t)):\n # Instantaneous cost is L[t1] - L[t0]\n if time == 0:\n inst_cost.append(0)\n else:\n inst_cost.append(L[time] - L[time-1])\n\n # Calculate cost to go\n for time in range(len(t)):\n ctg.append(inst_cost[time])\n # Sum backwards from tf\n for time in reversed(range(len(t) - 1)):\n ctg[time] += ctg[time + 1]\n\n mpc_results_df = pd.DataFrame(\n {\"t\": t, \"x0\": x0, \"x1\": x1, \"u\": u, \"L\": L, \"inst_cost\": inst_cost, \"ctg\": ctg}\n )\n mpc_results_df_dropped_t0 = mpc_results_df.drop(index=0)\n\n return mpc_results_df, mpc_results_df_dropped_t0\n\n def simulate_system_rng_controls(self):\n timesteps = [timestep / 10 for timestep in range(11)]\n u_rng = np.random.uniform(low=-20, high=20, size=11)\n\n # Create a dictionary of piecewise linear controller actions\n u_rng_profile = {timesteps[i]: u_rng[i] for i in range(len(timesteps))}\n\n self.model.var_input = Suffix(direction=Suffix.LOCAL)\n self.model.var_input[self.model.u] = u_rng_profile\n\n sim = Simulator(self.model, package=\"casadi\")\n tsim, profiles = sim.simulate(numpoints=11, varying_inputs=self.model.var_input)\n\n # For some reason both tsim and profiles contain duplicates\n # Use pandas to drop the duplicates first\n # profiles columns: x0, x1, L\n deduplicate_df = pd.DataFrame(\n {\"t\": tsim, \"x0\": profiles[:, 0], \"x1\": profiles[:, 1], \"L\": profiles[:, 2]}\n )\n deduplicate_df = deduplicate_df.round(10)\n deduplicate_df.drop_duplicates(ignore_index=True, inplace=True)\n\n # Make dataframe from the simulator results\n t = deduplicate_df[\"t\"]\n x0 = deduplicate_df[\"x0\"]\n x1 = deduplicate_df[\"x1\"]\n L = deduplicate_df[\"L\"]\n u = u_rng\n inst_cost = []\n ctg = []\n\n # Check duplicates were removed correctly\n assert len(t) == 11\n\n for time in range(len(t)):\n # Instantaneous cost is L[t1] - L[t0]\n if time == 10:\n inst_cost.append(0)\n else:\n inst_cost.append(L[time + 1] - L[time])\n\n # Calculate cost to go\n for time in range(len(t)):\n ctg.append(inst_cost[time])\n # Sum backwards from tf\n for time in reversed(range(len(t) - 1)):\n ctg[time] += ctg[time + 1]\n\n # Calculate path violations\n path = [x1[int(time * 10)] + 0.5 - 8 * (time - 0.5) ** 2 for time in t]\n path_violation = []\n for p in path:\n if max(path) > 0:\n path_violation.append(max(path))\n else:\n path_violation.append(p)\n\n rng_sim_results_df = pd.DataFrame(\n {\"t\": t, \"x0\": x0, \"x1\": x1, \"u\": u, \"L\": L,\n \"inst_cost\": inst_cost, \"ctg\": ctg, \"path_diff\": path_violation}\n )\n rng_sim_results_df_dropped_tf = rng_sim_results_df.drop(index=10)\n\n return rng_sim_results_df, rng_sim_results_df_dropped_tf\n\n def simulate_system_nn_controls(self, nn_model):\n timesteps = [timestep / 10 for timestep in range(11)]\n u_nn = np.zeros(11)\n # Initial x values to be passed to the neural net at the first loop\n current_x = [0, -1]\n\n self.model.var_input = Suffix(direction=Suffix.LOCAL)\n\n # Pyomo does not support simulating step by step, so we need to run 11 simulation loops\n # At loop i, we get state x_i and discard subsequent states\n # We call the neural net to predict the optimal u for x_i, then fix u time i\n for i in range(11):\n # Fetch optimal action, u, by calling the neural net with current_x\n u_opt = nn_model.get_u_opt(timesteps[i], current_x)\n\n # Replace the control sequence of the current timestep with u_opt\n u_nn[i] = u_opt\n\n # Create a dictionary of piecewise linear controller actions\n u_nn_profile = {timesteps[i]: u_nn[i] for i in range(len(timesteps))}\n\n # Update the control sequence to Pyomo\n self.model.var_input[self.model.u] = u_nn_profile\n\n sim = Simulator(self.model, package=\"casadi\")\n tsim, profiles = sim.simulate(numpoints=11, varying_inputs=self.model.var_input)\n\n # For some reason both tsim and profiles contain duplicates\n # Use pandas to drop the duplicates first\n # profiles columns: x0, x1, L\n deduplicate_df = pd.DataFrame(\n {\"t\": tsim, \"x0\": profiles[:, 0], \"x1\": profiles[:, 1], \"L\": profiles[:, 2]}\n )\n deduplicate_df = deduplicate_df.round(10)\n deduplicate_df.drop_duplicates(ignore_index=True, inplace=True)\n\n # Make dataframe from the simulator results\n t = deduplicate_df[\"t\"]\n x0 = deduplicate_df[\"x0\"]\n x1 = deduplicate_df[\"x1\"]\n\n # Check duplicates were removed correctly\n assert len(t) == 11\n\n # Update current_x to the next state output by the simulator\n if i < 10:\n current_x[0] = x0[i+1]\n current_x[1] = x1[i+1]\n\n # Make dataframe from the final simulator results\n t = deduplicate_df[\"t\"]\n x0 = deduplicate_df[\"x0\"]\n x1 = deduplicate_df[\"x1\"]\n L = deduplicate_df[\"L\"]\n u = u_nn\n inst_cost = []\n ctg = []\n\n for time in range(len(t)):\n # Instantaneous cost is L[t1] - L[t0]\n if time == 10:\n inst_cost.append(0)\n else:\n inst_cost.append(L[time + 1] - L[time])\n\n # Calculate cost to go\n for time in range(len(t)):\n ctg.append(inst_cost[time])\n # Sum backwards from tf\n for time in reversed(range(len(t) - 1)):\n ctg[time] += ctg[time + 1]\n\n # Calculate path violations\n path = [x1[int(time * 10)] + 0.5 - 8 * (time - 0.5) ** 2 for time in t]\n path_violation = []\n for p in path:\n if max(path) > 0:\n path_violation.append(max(path))\n else:\n path_violation.append(p)\n\n nn_sim_results_df = pd.DataFrame(\n {\"t\": t, \"x0\": x0, \"x1\": x1, \"u\": u, \"L\": L,\n \"inst_cost\": inst_cost, \"ctg\": ctg, \"path_diff\": path_violation}\n )\n nn_sim_results_df_dropped_tf = nn_sim_results_df.drop(index=10)\n\n return nn_sim_results_df, nn_sim_results_df_dropped_tf\n\n @staticmethod\n def plot(dataframe, num_rounds=0, num_run_in_round=0):\n t = dataframe[\"t\"]\n x0 = dataframe[\"x0\"]\n x1 = dataframe[\"x1\"]\n u = dataframe[\"u\"]\n ctg = dataframe[\"ctg\"]\n cst = dataframe[\"path_diff\"]\n\n if cst.max() <= 0:\n cst_status = \"Pass\"\n else:\n cst_status = \"Fail\"\n\n # Check that the cost to go is equal to the Lagrangian cost integral\n # assert np.isclose(ctg[0], dataframe[\"L\"].iloc[-1], atol=0.01)\n total_cost = round(ctg[0], 3)\n\n fig, axs = plt.subplots(3, constrained_layout=True)\n fig.set_size_inches(5, 10)\n\n axs[0].plot(t, x0, label=\"$x_0$\")\n axs[0].legend()\n\n axs[1].plot(t, x1, label=\"$x_1$\")\n axs[1].plot(t, -0.5 + 8 * (np.array(t) - 0.5) ** 2, label=\"Path constraint for $x_1$\")\n axs[1].legend()\n\n axs[2].step(t, u, label=\"Neural net controller action, u\")\n axs[2].legend()\n\n fig.suptitle(\"Control policy and system state after {} rounds of training \\n \"\n \"Run {}: Cost = {}, Constraint = {}\"\n .format(num_rounds, num_run_in_round, total_cost, cst_status))\n plt.xlabel(\"Time\")\n\n # Save plot with autogenerated filename\n svg_filename = results_folder + \"Round {} Run {} Cost {} Constraint {}\"\\\n .format(num_rounds, num_run_in_round, total_cost, cst_status) + \".svg\"\n plt.savefig(fname=svg_filename, format=\"svg\")\n\n # plt.show()\n plt.close()\n\n return\n\n\ndef generate_trajectories(save_csv=False):\n df_cols = [\"t\", \"x0\", \"x1\", \"u\", \"L\", \"inst_cost\", \"ctg\", \"path_diff\"]\n # 40 trajectories which obeyed the path constraint\n obey_path_df = pd.DataFrame(columns=df_cols)\n # 20 trajectories which violated the path constraint\n violate_path_df = pd.DataFrame(columns=df_cols)\n simple_60_trajectories_df = pd.DataFrame(columns=df_cols)\n\n num_samples = 0\n num_good = 0\n num_bad = 0\n\n while num_samples < 120:\n\n while num_good < 2:\n simple_sys = SimpleSimulator()\n _, trajectory = simple_sys.simulate_system_rng_controls()\n if trajectory[\"path_diff\"].max() <= 0:\n simple_60_trajectories_df = pd.concat([simple_60_trajectories_df, trajectory])\n obey_path_df = pd.concat([obey_path_df, trajectory])\n num_good += 1\n num_samples += 1\n\n while num_bad < 1:\n simple_sys = SimpleSimulator()\n _, trajectory = simple_sys.simulate_system_rng_controls()\n if trajectory[\"path_diff\"].max() > 0:\n simple_60_trajectories_df = pd.concat([simple_60_trajectories_df, trajectory])\n violate_path_df = pd.concat([violate_path_df, trajectory])\n num_bad += 1\n num_samples += 1\n\n # Reset\n num_good = 0\n num_bad = 0\n\n print(\"Samples: \", num_samples)\n\n simple_60_trajectories_df.to_csv(\"simple_120_trajectories_df.csv\")\n obey_path_df.to_csv(\"obey_path_df.csv\")\n violate_path_df.to_csv(\"violate_path_df.csv\")\n\n\ndef load_pickle(filename):\n with open(filename, \"rb\") as model:\n pickled_nn_model = pickle.load(model)\n print(\"Pickle loaded: \" + filename)\n return pickled_nn_model\n\n\ndef replay(trajectory_df_filename, buffer_capacity=240):\n # Use this to keep track where to push out old data\n forgotten_trajectories_count = 0\n pickle_filename = \"simple_nn_controller_120.pickle\"\n og_trajectory_df_filename = trajectory_df_filename\n\n best_cost_after_n_rounds = {}\n\n for rp_round in range(90):\n trajectory_df = pd.read_csv(results_folder + trajectory_df_filename, sep=\",\")\n nn_model = load_pickle(pickle_filename)\n run_trajectories = []\n\n best_cost_in_round = np.inf\n\n for run in range(6):\n simple_sys = SimpleSimulator()\n df_1s, df_point9s = simple_sys.simulate_system_nn_controls(nn_model)\n\n # Store the best result of this run if it passes constraints\n run_cost = df_1s[\"ctg\"][0]\n run_constraint = df_1s[\"path_diff\"].max()\n if run_cost < best_cost_in_round and run_constraint <= 0:\n best_cost_in_round = run_cost\n\n simple_sys.plot(df_1s, num_rounds=rp_round+1, num_run_in_round=run+1)\n run_trajectories.append(df_point9s)\n\n # Decide whether to push out old memories\n if trajectory_df.shape[0] >= buffer_capacity * 10:\n # Get replace the 6 oldest trajectories with new data (60 rows at a time)\n forgotten_trajectories_count = forgotten_trajectories_count % buffer_capacity\n row_slice_start = forgotten_trajectories_count * 10\n row_slice_end = row_slice_start + 60\n\n df_temp_concat = pd.DataFrame(columns=trajectory_df.columns.tolist())\n for df_temp in run_trajectories:\n df_temp_concat = pd.concat([df_temp_concat, df_temp])\n\n trajectory_df.iloc[row_slice_start:row_slice_end] = df_temp_concat.iloc[0:60]\n print(trajectory_df)\n forgotten_trajectories_count += 6\n\n else:\n for df_temp in run_trajectories:\n trajectory_df = pd.concat([trajectory_df, df_temp])\n\n trajectory_df_filename = \"R{} \".format(rp_round+1) + og_trajectory_df_filename\n trajectory_df.to_csv(results_folder + trajectory_df_filename)\n pickle_filename = train_and_pickle(rp_round, results_folder + trajectory_df_filename)\n\n # If best cost in round is better than current running best cost, add it to dictionary\n if len(best_cost_after_n_rounds) == 0:\n best_cost_after_n_rounds[rp_round] = best_cost_in_round\n else:\n best_key = min(best_cost_after_n_rounds, key=best_cost_after_n_rounds.get)\n if best_cost_in_round < best_cost_after_n_rounds[best_key]:\n best_cost_after_n_rounds[rp_round] = best_cost_in_round\n else:\n best_cost_after_n_rounds[rp_round] = best_cost_after_n_rounds[best_key]\n\n # Plot best cost against rounds\n # Unindent it to plot once, plotting every round and savings just in case anything fails\n plt.plot(*zip(*sorted(best_cost_after_n_rounds.items())))\n plt.title(\"Best cost obtained after each round\")\n plt.xlabel(\"Number of rounds\")\n plt.ylabel(\"Best cost obtained\")\n plot_filename = results_folder + \"best_cost_plot.svg\"\n plt.savefig(fname=plot_filename, format=\"svg\")\n # plt.show()\n plt.close()\n\n # Save the best cost against rounds as a csv\n best_cost_csv_filename = results_folder + \"best_cost_plot.csv\"\n with open(best_cost_csv_filename, \"w\") as csv_file:\n writer = csv.writer(csv_file)\n for k, v in best_cost_after_n_rounds.items():\n writer.writerow([k, v])\n\n return\n\n\nif __name__ == \"__main__\":\n # generate_trajectories(save_csv=True)\n\n # main_simple_sys = SimpleSimulator()\n # main_nn_model = load_pickle(\"simple_nn_controller.pickle\")\n # main_res, _ = main_simple_sys.simulate_system_nn_controls(main_nn_model)\n # main_simple_sys.plot(main_res)\n # print(main_res)\n\n replay(\"simple_120_trajectories_df.csv\")\n","sub_path":"zz_archived_cases/simple_withTimeNode/simple_pyomo_simulator.py","file_name":"simple_pyomo_simulator.py","file_ext":"py","file_size_in_byte":17899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"337761946","text":"\"\"\"\nMore plotting tools from nilearn\n================================\n\nIn this example, we demonstrate how to display results benefitting from\nmore plotting options available in nilearn.\n\nAll options demonstrated here are from existing plotting functions\n:func:nilearn.plotting.img_plotting. Particularly, we focus how to use\ndifferent display modes `display_mode` to display results in specific\nslice directions and also positioning of coordinates on the slices and\nnumber of slices to display using `cut_coords`.\n\nWe also demonstrate using various plotting objects from\n:class:nilearn.plotting.displays.OrthoSlicer consists of different types\nof display methods `add_overlay`, `add_contours`, `add_markers` for\ntwo step visualization of 3D maps.\n\nSee :ref:`plotting` for more details.\n\"\"\"\n\n###############################################################################\n# Retrieve the data from nilearn: haxby dataset to have EPI images and masks,\n# and localizer dataset to have contrast maps\n\n# Import datasets module\nfrom nilearn import datasets\n\nhaxby_dataset = datasets.fetch_haxby(n_subjects=1)\nhaxby_anat_filename = haxby_dataset.anat[0]\nhaxby_mask_filename = haxby_dataset.mask_vt[0]\nhaxby_func_filename = haxby_dataset.func[0]\n\nlocalizer_dataset = datasets.fetch_localizer_contrasts(\n [\"left vs right button press\"],\n n_subjects=2,\n get_anats=True)\nlocalizer_anat_filename = localizer_dataset.anats[1]\nlocalizer_cmap_filename = localizer_dataset.cmaps[1]\n\n########################################\n# Plotting statistical maps in three slice directions and also manually\n# positioning the location of the coordinates on each slice direction\n\n# Import plotting module for visualization\nfrom nilearn import plotting\n\n# Visualizing with default option display_mode='ortho' and coordinates given as\n# a list. display_mode='ortho' implies visualizing in three slice directions.\nplotting.plot_stat_map(localizer_cmap_filename, display_mode='ortho',\n cut_coords=[36, -27, 60],\n title=\"display_mode='ortho', cut_coords=[36, -27, 60]\")\n\n########################################\n# Now, plotting results in single direction 'z' with total number of slices to\n# be displayed=5\n\n# This visualization requires display_mode given as string 'z' and cut_coords as\n# integer.\n# Note: the difference in cut_coords as integer and as list.\nplotting.plot_stat_map(localizer_cmap_filename, display_mode='z', cut_coords=5,\n title=\"display_mode='z', cut_coords=5\")\n\n########################################\nplotting.plot_stat_map(localizer_cmap_filename, display_mode='x',\n cut_coords=(-36, 36),\n title=\"display_mode='x', cut_coords=(-36, 36)\")\n\n########################################\nplotting.plot_stat_map(localizer_cmap_filename, display_mode='y', cut_coords=1,\n title=\"display_mode='x', cut_coords=(-36, 36)\")\n\n########################################\nplotting.plot_stat_map(localizer_cmap_filename, display_mode='z',\n cut_coords=1, colorbar=False,\n title=\"display_mode='z', cut_coords=1, colorbar=False\")\n\n########################################\nplotting.plot_stat_map(localizer_cmap_filename, display_mode='xz',\n cut_coords=(36, 60),\n title=\"display_mode='xz', cut_coords=(36, 60)\")\n\n########################################\nplotting.plot_stat_map(localizer_cmap_filename, display_mode='yx',\n cut_coords=(-27, 36),\n title=\"display_mode='yx', cut_coords=(-27, 36)\")\n\n########################################\nplotting.plot_stat_map(localizer_cmap_filename, display_mode='yz',\n cut_coords=(-27, 60),\n title=\"display_mode='yz', cut_coords=(-27, 60)\")\n\n###############################################################################\n# demo display objects with add_* methods\n\n# Import image processing tool\nfrom nilearn import image\n\nmean_haxby_img = image.mean_img(haxby_func_filename)\n\n# Plot T1 outline on top of the mean EPI (useful for checking coregistration)\ndisplay = plotting.plot_anat(mean_haxby_img, title=\"add_edges\")\ndisplay.add_edges(haxby_anat_filename)\n\n########################################\n# Plotting outline of the mask on top of the EPI\ndisplay = plotting.plot_anat(mean_haxby_img, title=\"add_contours\",\n cut_coords=(28, -34, -22))\ndisplay.add_contours(haxby_mask_filename, levels=[0.5], colors='r')\n\n###############################################################################\n# demo saving plots to file\n\nplotting.plot_stat_map(localizer_cmap_filename,\n title='Using plot_stat_map output_file',\n output_file='plot_stat_map.png')\n\n########################################\ndisplay = plotting.plot_stat_map(localizer_cmap_filename,\n title='Using display savefig')\ndisplay.savefig('plot_stat_map_from_display.png')\n# In non-interactive settings make sure you close your displays\ndisplay.close()\n\nplotting.show()\n","sub_path":"python/nilearn/2016/4/plot_demo_more_plotting.py","file_name":"plot_demo_more_plotting.py","file_ext":"py","file_size_in_byte":5145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"313889199","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom django.shortcuts import render\nfrom django.core.mail import send_mail\nfrom django.template.loader import render_to_string\nfrom django.http import HttpResponse\nfrom .models import Survey\nfrom .models import Question\nfrom .models import Answer, SurveyAnswer\nfrom time import localtime, strftime\nfrom django.templatetags.static import static\nfrom pprint import pprint\nimport random\nimport json\nimport os\n\n\ndef main_view(request):\n\n\t# The response is a JSON object composed by the following attributes:\n\t\t#\t- rcode : response code for errors handling\n\t\t\t#\t\t1 - The information was succesfully saved\n\t\t\t#\t\t2 - The user is already in DB\n\t\t\t#\t\t3 - The phone is not valid\n\t\t#\t- msg : responseText for the client side app\n\n\tif request.method == \"POST\":\n\n\t\t# JSON format is used when receiving and sending information from AJAX\n\t\t# data is a JSON object\n\t\t# {\n\t\t# company_name (str) : Name of the company\n\t\t# user_name (str) : Name of the user\n\t\t# phone_number (str) : Phone number - minimum 7 digits\n\t\t# email \t (str) : email of the company or the user\n\t\t# terms \t (str) : \"on\" if the terms where agreed else \"off\"\n\t\t# answer \t (list ) : List with the codes of the answers selected by the user\n\t\t#\t\t\t\t\t\t\t\t if answers == [] none was answered\n\t\t# question_code (int) : code of the question answered by the user\n\t\t# };\n\t\t#\n\t\tif request.is_ajax():\n\t\t\tdata = json.loads(request.body)\n\t\t\tflag = True\n\t\t\tcompany_name = data['company_name']\n\t\t\tuser_name = data['user_name']\n\t\t\tphone_number = data['phone_number']\n\t\t\temail = data['email']\n\t\t\tterms = data['terms']\n\t\t\tanswer = data['answer']\n\t\t\tquestion_code = data['question_code']\n\n\t\t\tdumb_object = Survey.objects.filter(email = email)\n\n\t\t\tif dumb_object:\n\t\t\t\tflag = False\n\t\t\t\tmsg = \"El ususario ya se encuentra registrado\"\n\t\t\t\tcode = 2\n\n\t\t\tif not str(phone_number).isdigit():\n\t\t\t\tflag = False\n\t\t\t\tmsg = \"Ingrese un teléfono válido\"\n\t\t\t\tcode = 3\n\n\t\t\tif flag:\n\t\t\t\tnew_object = Survey(company_name = company_name, user_name = user_name,\n\t\t\t\t\tphone_number = phone_number, email = email, question_code = question_code)\n\t\t\t\tnew_object.save()\n\n\t\t\t\tanswers_text = []\n\t\t\t\tfor itm in answer:\n\t\t\t\t\tanswer_object = Answer.objects.filter(question_id=question_code, code=itm)[0]\n\t\t\t\t\tans = SurveyAnswer(user=new_object, answer=answer_object)\n\t\t\t\t\tans.save()\n\t\t\t\t\tanswers_text.append(answer_object.body)\n\n\t\t\t\tmsg = \"Su información fue guardada\"\n\t\t\t\tcode = 1\n\n\t\t\t\tquestion_text = answer_object.question.question\n\t\t\t\tusers_number = Survey.objects.all().count()\n\t\t\t\tgenerate_notification(email, user_name, company_name, phone_number, users_number, answers_text, question_text)\n\n\t\t\treturn HttpResponse(\n\n\t\t\t\tjson.dumps({\n\t\t\t\t\t\t\t\t\"rcode\" : code,\n\t\t\t\t\t\t\t\t\"msg\" : msg\n\t\t\t\t\t\t\t}\n\t\t\t\t),\n\t\t\t\tcontent_type='application/json')\n\n\telse:\n\n\t\tquestions = Question.objects.all()\n\t\tquestion = random.choice(questions)\n\t\tanswers = Answer.objects.filter(question_id=question.code)\n\n\t\tquestion_type = question.qtype\n\t\tquestion_code = question.code\n\t\tquestion_text = question.question\n\n\n\treturn render(request, 'landing/landing.html',\n\t\t\t\t {\n\t\t\t\t \t'question_type' : question_type,\n\t\t\t\t \t'question_code' : question_code,\n\t\t\t\t \t'question_text' : question_text,\n\t\t\t\t \t'answers' : answers\n\t\t\t\t })\n\ndef spam_view(request):\n\n\ttemplate_html = 'landing/admail.html'\n\tusername = 'Gerardo'\n\tcompany_name = 'Cargalo'\n\temail = 'gariano949@gmail.com'\n\tphone = 3016687553\n\tanswers = ('Si',)\n\tusers_number = 144\n\tquestion_text = ('¿Le gusta Cargalo?')\n\n\treturn render(request, template_html, {\n\t\t\t\t \t'username' : username,\n\t\t\t\t\t'company' : company_name,\n\t\t\t\t\t'email' : email,\n\t\t\t\t\t'phone' : phone,\n\t\t\t\t\t'answers' : answers,\n\t\t\t\t\t'users_number' : users_number,\n\t\t\t\t\t'question_text' : question_text,\n\t\t\t\t\t'date' : strftime(\"%Y-%m-%d %H:%M:%S\", localtime())})\n\n\ndef generate_notification(email, username, company_name, phone, users_number, answers, question_text):\n\tsubject = 'New notification from Landing Page'\n\tsender = 'contactocargalo@gmail.com'\n\ttemplate_html = 'landing/notification-min.html'\n\n\thtml_content = render_to_string(template_html, {\n\t\t\t\t \t'username' : username,\n\t\t\t\t\t'company' : company_name,\n\t\t\t\t\t'email' : email,\n\t\t\t\t\t'phone' : phone,\n\t\t\t\t\t'answers' : answers,\n\t\t\t\t\t'users_number' : users_number,\n\t\t\t\t\t'question_text' : question_text,\n\t\t\t\t\t'date' : strftime(\"%Y-%m-%d %H:%M:%S\", localtime())})\n\n\tsend_mail(subject, '', sender,\n\t\t['contactocargalo@gmail.com'], fail_silently=False, html_message = html_content)","sub_path":"landing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"560932175","text":"\nimport rpy2.robjects as robjects\nfrom rpy2.robjects import r, pandas2ri\nfrom rpy2.robjects.packages import importr\npandas2ri.activate()\nbase = importr('base')\nstats = importr('stats')\n\ndef funcR():\n '''\n H + LE = b1 + b2 * (Rn - G_mean)\n :param x: =Rn=,=G_mean=\n :param p: =H=,=LE=\n :return: \n '''\n return 'H + LE ~b1 + b2 * (Rn_Avg - G_mean)'\n\ndef PCA_method(data):\n '''\n calculate gradient of power close analysis\n :param data: data set including =LE=,=H=,=Rn_Avg=,=G=\n :return: the gradient and intercept\n '''\n robjects.globalenv['df'] = data\n A = stats.nls(\n funcR(),\n data=base.as_symbol('df')\n )\n intercept = base.summary(A).rx2('coefficients')[0]\n gradient = base.summary(A).rx2('coefficients')[1]\n return intercept, gradient\n\nif __name__ == '__main__':\n import init_data.opt_database as optdb\n\n db = optdb.DB()\n data = db.db_read_data('2012_yc_1_despiking')\n PCA_method(data)\n","sub_path":"despiking_function/power_close_analysis.py","file_name":"power_close_analysis.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"110058605","text":"import matplotlib.pyplot as plt\nfrom randomWalk import RandomWalk\n\nwhile True:\n rw = RandomWalk(5000)\n rw.fill_walk()\n plt.figure(figsize=(10, 6))\n point_numbers = list(range(rw.num_points))\n plt.plot(rw.x_value, rw.y_value, linewidth=10)\n \n # highlight start and end\n plt.scatter(0, 0, c='green', edgecolors='none', s=100)\n plt.scatter(rw.x_value[-1], rw.y_value[-1], c='red', edgecolors='none', s=100)\n\n \n plt.show()\n\n\n keep_running = input('Do you want running again? y/n: ')\n if keep_running == 'n':\n break\n\n\n\n","sub_path":"python_crash_course/data_visualiztion/rw_visual.py","file_name":"rw_visual.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"604538464","text":"from . import me\nimport datetime\n\n\nclass TrackedDatesEntity(me.Document):\n meta = {\n 'abstract': True,\n }\n\n created = me.DateTimeField()\n modified = me.DateTimeField()\n\n def save(self, *args, **kwargs):\n if self.id is None:\n self.created = datetime.datetime.now()\n self.modified = datetime.datetime.now()\n super().save(*args, **kwargs)\n\n\nclass User(me.Document):\n telegram_id = me.IntField(primary_key=True)\n username = me.StringField(min_length=2, max_length=128)\n first_name = me.StringField(min_length=2, max_length=128)\n phone_number = me.StringField(max_length=12)\n email = me.EmailField()\n is_blocked = me.BooleanField(default=False)\n address = me.StringField(max_length=256)\n\n def formatted_data(self):\n return f'Id - {self.telegram_id}\\nUsername - {self.username}\\nFirst name - {self.first_name}'\\\n f'\\nEmail - {self.email if self.email else \"\"}\\nPhone number - {self.phone_number}'\\\n f'\\nAddress - {self.address if self.address else \"\"}'\n\n def get_active_cart(self):\n cart = Cart.objects(user=self, is_active=True).first()\n if not cart:\n print('creating new cart...')\n cart = Cart.objects.create(user=self)\n print(cart)\n return cart\n\n\nclass Category(me.Document):\n title = me.StringField(required=True)\n description = me.StringField(max_length=512)\n parent = me.ReferenceField('self')\n subcategories = me.ListField(me.ReferenceField('self'))\n\n @classmethod\n def get_root_categories(cls):\n return cls.objects(parent=None)\n\n def get_products(self):\n return Product.objects(category=self)\n\n def is_root(self):\n return not bool(self.parent)\n\n def add_subcategory(self, category):\n category.parent = self\n category.save()\n self.subcategories.append(category)\n self.save()\n\n\nclass Parameters(me.EmbeddedDocument):\n height = me.FloatField()\n width = me.FloatField()\n weight = me.FloatField()\n additional_description = me.StringField()\n\n\nclass Product(me.Document):\n title = me.StringField(required=True, max_length=256)\n description = me.StringField(max_length=512)\n in_stock = me.BooleanField(default=True)\n discount = me.IntField(min_value=0, max_value=100, default=0)\n price = me.FloatField(required=True)\n image = me.FileField()\n category = me.ReferenceField(Category, required=True)\n parameters = me.EmbeddedDocumentField(Parameters)\n\n #file = open('apole.jpeg','rb')\n #product.image.put(file, content_type='image/jpeg')\n #product.save()\n\n @property\n def product_price(self):\n return (100 - self.discount) / 100 * self.price\n\n def formatted_data(self):\n if self.parameters:\n params = \"\\n\"\n if self.parameters.height:\n params = params + 'Height - ' + str(self.parameters.height)\n if self.parameters.width:\n if params != '\\n':\n params = params + ' '\n params = params + 'Width - ' + str(self.parameters.width)\n if self.parameters.weight:\n if params != '\\n':\n params = params + ' '\n params = params + 'Weight - ' + str(self.parameters.weight)\n if self.parameters.additional_description:\n if params != '\\n':\n params = params + ' '\n params = params + str(self.parameters.additional_description)\n else:\n params = \"\"\n return f'{self.title}{\" (\" + self.description + \")\" if self.description else \"\"}\\n'\\\n f'Price with discount: {str(self.product_price)}'\\\n f'{params}'\n\n\n# class ProductInCart(me.EmbeddedDocument):\n# product = me.ReferenceField(Product, required=True)\n# amount = me.IntField(default=1)\n# actual_price = me.FloatField(required=True)\n#\n\n# class Cart(me.Document):\n# user = me.ReferenceField(User, required=True)\n# product_in_cart = me.ListField(ProductInCart, required=True)\n\n\nclass Cart(me.Document):\n user = me.ReferenceField(User, required=True)\n products = me.ListField(me.ReferenceField(Product))\n is_active = me.BooleanField(default=True)\n created_at = me.DateTimeField()\n\n def save(self, *args, **kwargs):\n self.created_at = datetime.datetime.now()\n super().save(*args, **kwargs)\n\n def add_product(self, product):\n self.products.append(product)\n self.save()\n\n\n\n\n\nclass Order(me.Document):\n # user = me.ReferenceField(User, required=True)\n # product_ordered = me.ListField(ProductInCart, required=True)\n cart = me.ReferenceField(Cart, required=True)\n ordered_at = me.DateTimeField(default=datetime.datetime.now())\n delivery_address = me.StringField(min_length=2, max_length=256)","sub_path":"shop/models/shop_models.py","file_name":"shop_models.py","file_ext":"py","file_size_in_byte":4862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"179709810","text":"import re\n\n\ndef to_camel_case(text):\n if text == '':\n return ''\n txt_splt = re.split('; |, |\\*|\\n|-|_',text)\n camel_txt = \"\"\n if len(txt_splt) > 1:\n first = txt_splt[0]\n for i in txt_splt[1:]:\n camel_txt += i[0].upper()+i[1:]\n return first+camel_txt\n\n\nprint(to_camel_case(\"A-B-C\"))\n","sub_path":"convert_string_to_camel_case.py","file_name":"convert_string_to_camel_case.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"225359859","text":"import cv2\nimport numpy as np\n\ncap = cv2.VideoCapture(0)\n# Setting ID 3 = width / 4 = height / 10 = Brightness\ncap.set(3,600), cap.set(4,600), cap.set(10,100)\n\n# PUMA Logo Image\npumaLogo = cv2.imread(\"Logos/puma_black.png\", cv2.IMREAD_GRAYSCALE)\n\n# Face detector\nfaceCascade= cv2.CascadeClassifier(\"Resources/haarcascade_frontalface_default.xml\")\n\nwhile(True):\n # Capture frame-by-frame\n ret, frame = cap.read()\n\n # insert PUMA as Text\n # font = cv2.FONT_HERSHEY_SIMPLEX\n # cv2.putText(frame, 'PUMA', (10, 450), font, 2, (255, 255, 255), 1, cv2.LINE_AA)\n\n # Transformations\n canny_noise = cv2.Canny(frame, 100, 100)\n canny_clean = cv2.Canny(frame, 150, 200)\n frameGray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # ORB Detector\n orb = cv2.ORB_create()\n kp1, des1 = orb.detectAndCompute(pumaLogo, None)\n kp2, des2 = orb.detectAndCompute(frameGray, None)\n\n # Brute Force Matching (crossCheck True = only best match, False = more)\n bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n matches = bf.match(des1, des2)\n matches = sorted(matches, key=lambda x: x.distance)\n\n matching_result = cv2.drawMatches(pumaLogo, kp1, frameGray, kp2, matches[:50], None, flags=2)\n\n # mark detected faces\n faces = faceCascade.detectMultiScale(frameGray, 1.1, 4)\n for (x, y, w, h) in faces:\n cv2.rectangle(canny_clean, (x, y), (x + w, y + h), (255, 0, 0), 2)\n\n # Display Output\n cv2.imshow('Video Gray',frameGray)\n #cv2.imshow('Video Noise', canny_noise)\n #cv2.imshow('Video Clean', canny_clean)\n cv2.imshow(\"Matching result\", matching_result)\n # cv2.imshow('Logo Output', pumaLogo)\n\n # exit loop = q\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# When everything done, release the capture\ncap.release()\ncv2.destroyAllWindows()","sub_path":"PUMA-Step-by-Step.py","file_name":"PUMA-Step-by-Step.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"1782416","text":"import requests # для запросов на сайт\nimport re # Парсить максимальную и минимальную зарплату\nfrom bs4 import BeautifulSoup as bs # Для обработки HTML\n\n\ndef get_search_hh(vacancy: str, page: int, lang=''):\n \"\"\"\n Функция получает название вакансии, формирует запрос на сайт hh.ru и формирует ответ в видел html\n :param vacancy: srt. Вакансия для поиска\n :param page: int Номер страницы в поиске, по умолчанию 1\n :param lang: str Язык на кором пишет программист. По умолчанию все языки\n :return: str HTML странци\n \"\"\"\n headers = {'user-agent': \"Mozilla/5.0 \"\n \"(X11; Ubuntu; Linux x86_64) AppleWebKit/537.36 \"\n \"(KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36\"}\n if lang != '':\n vacancy = vacancy + '+' + lang\n url = f'https://hh.ru/search/vacancy' \\\n f'?area=1' \\\n f'&clusters=true' \\\n f'&enable_snippets=false' \\\n f'&search_field=name' \\\n f'&text={vacancy}' \\\n f'&only_with_salary=true' \\\n f'&page={page}'\n # area - город для поиска. 1 - Москва 2 - Санкт-Петербург\n # clusters - не известно\n # enable_snippets - отключение информации для поисковиков\n # search_field - тип поискового запроса. По умолчанию по имени\n # text - текс запроса. Контитенция слов через +\n # only_with_salary - поиск по вакансиям только с указанием ЗП\n # page - страница результов поиска. Вывести все на одной странице не удалось\n get = requests.get(url, headers=headers)\n return get.text\n\n\ndef get_max_page(html):\n \"\"\"\n Функция получает html запрос с hh.ru возвращает количество страниц в поиске\n :param html: str HTML страница\n :return: int Количество страниц начиня с 0\n \"\"\"\n soup = bs(html, 'lxml')\n pages = soup.findAll('a', {\"class\": \"HH-Pager-Control\",\n \"data-qa\": \"pager-page\"}) # ищем все кнопки для перехода по страницам\n if len(pages) == 0:\n return 0 # Если кнопок нет, то страниц 1, т.е 0\n return int(pages[-1]['data-page']) # Возвращаем номер последней страницы\n\n\ndef parse_compensation(compensation: str):\n \"\"\"\n Функция получает строку с зарплатой и преобразует ее в минимальную, максимальню, а так же опеделяет валюту зарплат\n\n :param compensation: строка, которая начинается на до, от или имеет вид min-max , в конце валюта\n :return: минимальная запралат, максимальная, валюта\n \"\"\"\n min_compensation, max_compensation, currency = 0, 0, False\n if compensation[:2] == 'от':\n min_compensation = int(\"\".join(re.findall(\"\\d+\", compensation[2:])))\n if compensation[:2] == 'до':\n max_compensation = int(\"\".join(re.findall(\"\\d+\", compensation[2:])))\n if len(compensation.split('-')) == 2:\n compensation_ = compensation.split('-')\n min_compensation = int(\"\".join(re.findall(\"\\d+\", compensation_[0])))\n max_compensation = int(\"\".join(re.findall(\"\\d+\", compensation_[1])))\n currency = re.findall('\\D+', compensation)[-1].replace(\" \", \"\")\n if currency == 'руб.':\n currency = 'RUR'\n return min_compensation, max_compensation, currency\n\n\ndef get_vacancies_on_page(html):\n \"\"\"\n Функцич получает вакансии на страницы и формирует список вакансий, где в каждом элемете указано название вакансии\n и зарплата максимальная и минимальная\n :param html. Страница результатов поиска\n :return: list. Список вакансий на странице с указанием имени и оплаты труда\n \"\"\"\n list_vacancy = []\n soup = bs(html, 'lxml')\n vacancies = soup.select('.vacancy-serp-item')\n for vacancy in vacancies:\n name = vacancy.find('a', {\"data-qa\": \"vacancy-serp__vacancy-title\"})\n compensation = vacancy.find(\"div\", {\"class\": \"vacancy-serp-item__compensation\"})\n link = name['href'].split('?')[0]\n min_compensation, max_compensation, currency = parse_compensation(compensation.string)\n list_vacancy.append({\n 'name': name.string, # Название вакансии\n 'min': min_compensation, # Минимальная оплата\n 'max': max_compensation, # Максимальная оплата\n 'currency': currency, # Валюта вакансии\n 'url': link # Ссылка на вакансию\n })\n return list_vacancy\n\n\ndef get_all_vacancies(vacancy_search: str, lang=''):\n \"\"\"\n Функция получает строку поика вакасий, и возвращает список ввсех ваканский\n :param lang: язык прокграммирония\n :param vacancy_search: старока поиска вакансии\n :return: list объектов вакансий\n \"\"\"\n all_vacancies = []\n html = get_search_hh(vacancy_search, 0, lang)\n max_pages = get_max_page(html)\n for i in range(max_pages + 1):\n html = get_search_hh(vacancy_search, i, lang)\n vacancies_on_page = get_vacancies_on_page(html)\n all_vacancies += vacancies_on_page\n return all_vacancies\n\n\ndef save_vacancies_to_file(vacancies: list):\n \"\"\"\n Функсция сохраняет список вакансий а форматированом виде в фаил с разделителем : для удобной загрузки\n :param vacancies: список объектов вакансий\n :return: none\n \"\"\"\n with open('output.txt', 'wt', encoding='utf-8') as output_file:\n for vacancy in vacancies:\n line = [vacancy[\"name\"], vacancy[\"min\"], vacancy[\"max\"], vacancy[\"currency\"], vacancy[\"url\"]]\n line_to_write = \"\\t\".join(str(x) for x in line)\n output_file.write(line_to_write + \"\\n\")\n # output_file.write(f'{vacancy[\"url\"]} \\n\\n')\n\n\nif __name__ == \"__main__\":\n vacancy_name = 'Программист'\n lang_ = \"Python\"\n all_ = get_all_vacancies(vacancy_name, lang_)\n print(len(all_))\n save_vacancies_to_file(all_)\n","sub_path":"collecting-and-processing-data/lesson3/hh.py","file_name":"hh.py","file_ext":"py","file_size_in_byte":7031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"592868180","text":"import sqlite3\r\n\r\ndef create_connection(db_file):\r\n conn = None\r\n try:\r\n conn = sqlite3.connect(db_file)\r\n except Error as e:\r\n print(e)\r\n\r\n return conn\r\n\r\nconn = create_connection(\"Pets.db\")\r\n\r\n\r\ndef select_all_person(conn,person_id):\r\n \"\"\"\r\n Query all rows in the tasks table\r\n :param conn: the Connection object\r\n :return:\r\n \"\"\"\r\n cur = conn.cursor()\r\n cur.execute(\"SELECT * FROM person where id =\"+str(person_id))\r\n\r\n rows = cur.fetchall()\r\n if len(rows) >= 1:\r\n for row in rows:\r\n name = row[1]+\" \"+row[2]\r\n print(name+\", \"+str(row[3])+\" year old\")\r\n \r\n cur.execute(\"SELECT * FROM pet where id =(SELECT pet_id FROM person_pet where person_id =\"+str(person_id)+\")\")\r\n pet_rows = cur.fetchall()\r\n\r\n for pet_row in pet_rows:\r\n print(name+\" owns \"+pet_row[1]+\",a \"+pet_row[2]+\" \"+str(pet_row[3])+\" year old\" )\r\n else:\r\n print(\"Error: the person doesn't exist\")\r\n\r\nwhile True:\r\n p_id = input(\"Enter person's id or -1 to exit: \")\r\n if p_id != '-1':\r\n select_all_person(conn,p_id)\r\n else:\r\n break\r\n print()\r\n","sub_path":"query_pets.py","file_name":"query_pets.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"579283548","text":"import numpy as np\r\nimport os\r\n\r\nclass Model:\r\n def __init__(self, params=None): \r\n\r\n self.ncores = 20\r\n\r\n if params is not None:\r\n self.nx = params['nx']\r\n self.ny = params['ny']\r\n self.nz = params['nz']\r\n else:\r\n raise ValueError(\"You have to provide relevant parameters\")\r\n\r\n\r\n def run_model_single(self, logHK):\r\n '''run HT in comsol\r\n '''\r\n # write K to inputK.dat\r\n ngrid = self.nx * self.ny * self.nz\r\n coor = np.zeros([ngrid, 4])\r\n os.chdir('.//input_files_single')\r\n index = 0\r\n for k in range(0, self.nz, 1):\r\n for j in range(0, self.ny, 1):\r\n for i in range(0, self.nx, 1):\r\n coor[index, 0] = i\r\n coor[index, 1] = j\r\n coor[index, 2] = k\r\n coor[index, 3] = logHK[index] # unit is ln (m/s)\r\n index = index + 1\r\n np.savetxt(\"inputK.dat\", coor, fmt=\"%f %f %f %f\")\r\n # run HT-COMSOL\r\n os.system('./run_test.sh')\r\n simul_obs=np.loadtxt('outputHT.dat')\r\n os.remove('outputHT.dat')\r\n os.chdir(\"../\")\r\n return simul_obs\r\n\r\n def run_model_parallel(self, logHK):\r\n '''run HHT in comsol\r\n '''\r\n # transform all the ensembles of s to input files of COMSOL\r\n ngrid = self.nx * self.ny * self.nz\r\n coor = np.zeros([ngrid, 4])\r\n ngroup=int(logHK.shape[1]/self.ncores)\r\n os.chdir('.//input_files_parallel')\r\n\r\n simul_obs=[]\r\n\r\n for igroup in range(0,ngroup,1):\r\n logHK_group=logHK[:,igroup*self.ncores:(igroup+1)*self.ncores]\r\n for ireaz in range(0, self.ncores, 1):\r\n str_dir = './/parallel' + str(ireaz + 1)\r\n os.chdir(str_dir)\r\n index = 0\r\n for k in range(0, self.nz, 1):\r\n for j in range(0, self.ny, 1):\r\n for i in range(0, self.nx, 1):\r\n coor[index, 0] = i\r\n coor[index, 1] = j\r\n coor[index, 2] = k\r\n coor[index, 3] = logHK_group[index,ireaz] # unit is ln (m/s)\r\n index = index + 1\r\n np.savetxt(\"inputK.dat\", coor, fmt=\"%f %f %f %f\")\r\n os.chdir(\"../\")\r\n # run HT-COMSOL\r\n os.system('./run_test.sh')\r\n\r\n # read the observation\r\n simul_obs_group = np.loadtxt('outputHT.dat') # collect all the obs (for one gruop) in this file\r\n os.remove('outputHT.dat')\r\n if simul_obs == []:\r\n simul_obs = simul_obs_group\r\n else:\r\n simul_obs=np.hstack((simul_obs,simul_obs_group))\r\n os.chdir(\"../\")\r\n\r\n return simul_obs\r\n\r\n\r\n def run(self, HK, par, ncores=None):\r\n if ncores is None:\r\n ncores = self.ncores\r\n\r\n #delet the matlabprefs.mat for comsol run\r\n #if os.path.exists('//share//home//shixq2//.matlab//R2015a//matlabprefs.mat'):\r\n # os.remove('//share//home//shixq2//.matlab//R2015a//matlabprefs.mat')\r\n\r\n #method_args = range(HK.shape[1])\r\n #args_map = [(HK[:, arg:arg + 1], arg) for arg in method_args]\r\n\r\n if par:\r\n if HK.shape[1]==2:\r\n simul_obs = self.run_model_single(HK[:,0]) #2 times of forward (3)\r\n simul_obs = np.vstack((simul_obs,self.run_model_single(HK[:, 1])))\r\n simul_obs=simul_obs.transpose()\r\n else:\r\n simul_obs = self.run_model_parallel(HK) #n_pc forward (2) parallel!\r\n else:\r\n simul_obs = self.run_model_single(HK) #initial forward (1)\r\n simul_obs.shape = (simul_obs.shape[0], 1) #transpose the 1d array\r\n return simul_obs\r\n\r\n # pool.close()\r\n # pool.join()\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n import numpy as np\r\n\r\n params = {'nx': 80, 'ny': 40}\r\n\r\n mymodel = Model(params)\r\n\r\n simul_obs = mymodel.run_model(logHK)\r\n\r\n np.savetxt('obs_true.txt',simul_obs)\r\n for i in range(0,2040,1):\r\n simul_obs[i]=simul_obs[i]+np.random.normal(0, 0.01*abs(simul_obs[i]), 1)\r\n np.savetxt('obs_noise.txt', simul_obs)","sub_path":"HT_Inv/HT_comsol.py","file_name":"HT_comsol.py","file_ext":"py","file_size_in_byte":4325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"458133673","text":"# -*- coding: utf-8 -*-\n\"\"\"Artifact related attribute container definitions.\"\"\"\n\nfrom plaso.containers import interface\nfrom plaso.containers import manager\n\n\nclass ArtifactAttributeContainer(interface.AttributeContainer):\n \"\"\"Base class to represent an artifact attribute container.\"\"\"\n\n\nclass EnvironmentVariableArtifact(ArtifactAttributeContainer):\n \"\"\"Class to represent an environment variable artifact attribute container.\n\n Also see:\n https://en.wikipedia.org/wiki/Environment_variable\n\n Attributes:\n case_sensitive (bool): True if environment variable name is case sensitive.\n name (str): environment variable name e.g. 'SystemRoot' as in\n '%SystemRoot%' or 'HOME' in '$HOME'.\n value (str): environment variable value e.g. 'C:\\\\Windows' or '/home/user'.\n \"\"\"\n CONTAINER_TYPE = u'environment_variable'\n\n def __init__(self, case_sensitive=True, name=None, value=None):\n \"\"\"Initializes an environment variable artifact.\n\n Args:\n case_sensitive (Optional[bool]): True if environment variable name\n is case sensitive.\n name (Optional[str]): environment variable name.\n value (Optional[str]): environment variable value.\n \"\"\"\n super(EnvironmentVariableArtifact, self).__init__()\n self.case_sensitive = case_sensitive\n self.name = name\n self.value = value\n\n\nclass HostnameArtifact(ArtifactAttributeContainer):\n \"\"\"Class to represent a hostname artifact attribute container.\n\n Also see:\n https://en.wikipedia.org/wiki/Hostname\n http://cybox.mitre.org/language/version2.1/xsddocs/objects/\n Hostname_Object.html\n\n Attributes:\n name (str): name of the host according to the naming schema.\n schema (str): naming schema e.g. DNS, NIS, SMB/NetBIOS.\n \"\"\"\n CONTAINER_TYPE = u'hostname'\n\n def __init__(self, name=None, schema=u'DNS'):\n \"\"\"Initializes a hostname artifact.\n\n Args:\n name (Optional[str]): name of the host according to the naming schema.\n schema (Optional[str]): naming schema.\n \"\"\"\n super(HostnameArtifact, self).__init__()\n self.name = name\n self.schema = schema\n\n\nclass SystemConfigurationArtifact(ArtifactAttributeContainer):\n \"\"\"Class to represent a system configuration artifact attribute container.\n\n The system configuration contains the configuration data of a specific\n system installation e.g. Windows or Linux.\n\n Attributes:\n code_page (str): system code page.\n hostname (HostnameArtifact): hostname.\n keyboard_layout (str): keyboard layout.\n operating_system (str): operating system for example \"Mac OS X\" or\n \"Windows\".\n operating_system_product (str): operating system product for example\n \"Windows XP\".\n operating_system_version (str): operating system version for example\n \"10.9.2\" or \"8.1\".\n time_zone (str): system time zone.\n user_accounts (list[UserAccountArtifact]): user accounts.\n \"\"\"\n CONTAINER_TYPE = u'system_configuration'\n\n def __init__(self, code_page=None, time_zone=None):\n \"\"\"Initializes a system configuration artifact.\n\n Args:\n code page (Optional[str]): system code page.\n time_zone (Optional[str]): system time zone.\n \"\"\"\n super(SystemConfigurationArtifact, self).__init__()\n self.code_page = code_page\n self.hostname = None\n self.keyboard_layout = None\n self.operating_system = None\n self.operating_system_product = None\n self.operating_system_version = None\n self.time_zone = time_zone\n self.user_accounts = []\n\n\nclass UserAccountArtifact(ArtifactAttributeContainer):\n \"\"\"Class to represent an user account artifact attribute container.\n\n Also see:\n http://cybox.mitre.org/language/version2.1/xsddocs/objects/\n User_Account_Object.html\n\n Attributes:\n full_name (str): name describing the user e.g. full name.\n group_identifier (str): identifier of the primary group the user is part of.\n identifier (str): user identifier.\n user_directory (str): path of the user (or home or profile) directory.\n username (str): name uniquely identifying the user.\n \"\"\"\n CONTAINER_TYPE = u'user_account'\n\n def __init__(\n self, full_name=None, group_identifier=None, identifier=None,\n user_directory=None, username=None):\n \"\"\"Initializes an user artifact.\n\n Args:\n full_name (Optional[str]): name describing the user e.g. full name.\n group_identifier (Optional[str]): identifier of the primary group\n the user is part of.\n identifier (Optional[str]): user identifier.\n user_directory (Optional[str]): path of the user (or home or profile)\n directory.\n username (Optional[str]): name uniquely identifying the user.\n \"\"\"\n super(UserAccountArtifact, self).__init__()\n self.full_name = full_name\n self.group_identifier = group_identifier\n self.identifier = identifier\n # TODO: add shell.\n self.user_directory = user_directory\n self.username = username\n\n\nmanager.AttributeContainersManager.RegisterAttributeContainers([\n EnvironmentVariableArtifact, HostnameArtifact, SystemConfigurationArtifact,\n UserAccountArtifact])\n","sub_path":"plaso/containers/artifacts.py","file_name":"artifacts.py","file_ext":"py","file_size_in_byte":5075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"596469994","text":"from mmdet.apis import init_detector, inference_detector\nimport mmcv\n\n# Specify the path to model config and checkpoint file\nconfig_file = 'own_configs/r50.py'\ncheckpoint_file = 'best_model.pth'\n\n# build the model from a config file and a checkpoint file\nmodel = init_detector(config_file, checkpoint_file, device='cuda:0')\n\n# test a single image and show the results\nimg = 'data/IMAGES_1024/0A0ADA58.JPG' # or img = mmcv.imread(img), which will only load it once\nresult = inference_detector(model, img)\n# visualize the results in a new window\n# model.show_result(img, result)\n# or save the visualization results to image files\nmodel.show_result(img, result, out_file='result.jpg')\n\n# test a video and show the results\n# video = mmcv.VideoReader('video.mp4')\n# for frame in video:\n# result = inference_detector(model, frame)\n# model.show_result(frame, result, wait_time=1)","sub_path":"mmdetection/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"276180467","text":"\"\"\"\nDispatcher tests.\n\n\"\"\"\nfrom hamcrest import (\n assert_that,\n equal_to,\n is_,\n)\nfrom mock import Mock\n\nfrom microcosm_pubsub.conventions import created\nfrom microcosm_pubsub.message import SQSMessage\nfrom microcosm_pubsub.tests.fixtures import (\n ExampleDaemon,\n DerivedSchema,\n)\n\n\nMESSAGE_ID = \"message-id\"\n\n\ndef test_handle():\n \"\"\"\n Test that the dispatcher handles a message and assigns context.\n\n \"\"\"\n daemon = ExampleDaemon.create_for_testing()\n graph = daemon.graph\n\n content = dict(bar=\"baz\")\n sqs_message_context = Mock(return_value=dict())\n with graph.opaque.initialize(sqs_message_context, content):\n result = graph.sqs_message_dispatcher.handle_message(\n message=SQSMessage(\n consumer=None,\n content=content,\n media_type=DerivedSchema.MEDIA_TYPE,\n message_id=MESSAGE_ID,\n receipt_handle=None,\n ),\n bound_handlers=daemon.bound_handlers,\n )\n\n assert_that(result, is_(equal_to(True)))\n sqs_message_context.assert_called_once_with(content)\n\n\ndef test_handle_with_no_context():\n \"\"\"\n Test that when no context is added the dispatcher behaves sanely.\n\n \"\"\"\n daemon = ExampleDaemon.create_for_testing()\n graph = daemon.graph\n\n # remove the sqs_message_context from the graph so we can test the dispatcher\n # defaulting logic\n graph._registry.entry_points.pop(\"sqs_message_context\")\n\n content = dict(bar=\"baz\")\n result = graph.sqs_message_dispatcher.handle_message(\n message=SQSMessage(\n consumer=None,\n content=content,\n media_type=DerivedSchema.MEDIA_TYPE,\n message_id=MESSAGE_ID,\n receipt_handle=None,\n ),\n bound_handlers=daemon.bound_handlers,\n )\n\n assert_that(result, is_(equal_to(True)))\n assert_that(graph.sqs_message_dispatcher.sqs_message_context(content), is_(equal_to(dict())))\n\n\ndef test_handle_with_skipping():\n \"\"\"\n Test that skipping works\n\n \"\"\"\n daemon = ExampleDaemon.create_for_testing()\n graph = daemon.graph\n\n content = dict(bar=\"baz\")\n result = graph.sqs_message_dispatcher.handle_message(\n message=SQSMessage(\n consumer=None,\n content=content,\n media_type=created(\"bar\"),\n message_id=MESSAGE_ID,\n receipt_handle=None,\n ),\n bound_handlers=daemon.bound_handlers,\n )\n assert_that(result, is_(equal_to(False)))\n","sub_path":"microcosm_pubsub/tests/test_dispatcher.py","file_name":"test_dispatcher.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"189980648","text":"# python爬虫实现百度翻译\r\n# urllib和request POST参数提交\r\n\r\nfrom urllib import request,parse\r\nimport json\r\n\r\ndef fanyi(keyword):\r\n base_url = 'http://fanyi.baidu.com/sug'\r\n\r\n # 构建请求对象\r\n data = {\r\n 'kw': keyword\r\n }\r\n data = parse.urlencode(data)\r\n\r\n # 模拟浏览器\r\n header = {\"User-Agent\": \"mozilla/4.0 (compatible; MSIE 5.5; Windows NT)\"}\r\n\r\n req = request.Request(url=base_url,data=bytes(data,encoding='utf-8'),headers=header)\r\n res = request.urlopen(req)\r\n\r\n # 获取响应的json字符串\r\n str_json = res.read().decode('utf-8')\r\n # 把json转换成字典\r\n myjson = json.loads(str_json)\r\n info = myjson['data'][0]['v']\r\n print(info)\r\n\r\nif __name__=='__main__':\r\n while True:\r\n keyword = input('请输入翻译的单词:')\r\n if keyword == 'q':\r\n break\r\n fanyi(keyword)\r\n\r\n","sub_path":"py爬虫/py05bdfanyi.py","file_name":"py05bdfanyi.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"298604578","text":"from __future__ import annotations\n\nfrom soda.sodacl.location import Location\nfrom soda.sodacl.metric_check_cfg import MetricCheckCfg\nfrom soda.sodacl.missing_and_valid_cfg import MissingAndValidCfg\nfrom soda.sodacl.threshold_cfg import ThresholdCfg\n\n\nclass ChangeOverTimeMetricCheckCfg(MetricCheckCfg):\n def __init__(\n self,\n source_header: str,\n source_line: str,\n source_configurations: str | None,\n location: Location,\n name: str | None,\n metric_name: str,\n metric_args: list[object] | None,\n missing_and_valid_cfg: MissingAndValidCfg | None,\n filter: str | None,\n condition: str | None,\n metric_expression: str | None,\n metric_query: str | None,\n change_over_time_cfg: ChangeOverTimeCfg | None,\n fail_threshold_cfg: ThresholdCfg | None,\n warn_threshold_cfg: ThresholdCfg | None,\n samples_limit: int | None = None,\n ):\n super().__init__(\n source_header,\n source_line,\n source_configurations,\n location,\n name,\n metric_name,\n metric_args,\n missing_and_valid_cfg,\n filter,\n condition,\n metric_expression,\n metric_query,\n change_over_time_cfg,\n fail_threshold_cfg,\n warn_threshold_cfg,\n samples_limit=samples_limit,\n )\n","sub_path":"govern/data-quality/soda-core/soda/core/soda/sodacl/change_over_time_metric_check_cfg.py","file_name":"change_over_time_metric_check_cfg.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"238484616","text":"import numpy as np\nimport xml.etree.ElementTree as ET\nfrom Bio.SVDSuperimposer import SVDSuperimposer\nfrom math import sqrt\nfrom numpy import array, dot\nimport random\nimport operator\nimport os\nimport sys\nimport pickle\nfrom sklearn.decomposition import PCA\nimport math\nimport scipy.io\n#sys.path.insert(0, '/home/localadmin/sbl/codes/general_codes')\n#import utils\n#reload(utils)\n#from utils import align\n\n\nEPSILON = 1.0 * (2**-36)\n\n\n\ndef align(coordinate_file):\n\t'''\n\tInput: File contains lines, where each line contains the coordinates of a model, e.g., if model 1 has 70 atoms, each with 3 coordinates (3*70 = 210 coordinates),\n\tthen the line corresponding model 1 is like this: 210 x1 y1 z1 x2 y2 z2 ... x70 y70 z70\n\n\tAlignes all the model with the first model in the cordinate_file.\n\n\tReturns: a dictionary of aligned models. Each model, i.e., each entry (value) in the dictionary is a flattened numpy array.\n\n\tNOTE: For my leader cluster codes, do not flatten the arrays.\n\t'''\n\n\tmodelDict = {}\n\tind = 0\n\tref = []\n\tsup = SVDSuperimposer()\n\twith open(coordinate_file) as f:\n\t\tfor line in f:\n\t\t\tif ind == 0:\n\t\t\t\tl = [float(t) for t in line.split()]\n\t\t\t\tl = l[1:] # 1ail:l[1:211]\n\t\t\t\tsamples = [l[i:i+3] for i in range(0, len(l), 3)]\n\t\t\t\tref = array(samples, 'f')\n\n\t\t\t\tmodelDict[ind] = np.ravel(ref)\n\t\t\t\tind += 1\n\t\t\telse:\n\t\t\t\tl = [float(t) for t in line.split()]\n\t\t\t\tl = l[1:] # 1ail:l[1:211]\n\t\t\t\tsamples = [l[i:i+3] for i in range(0, len(l), 3)]\n\t\t\t\tseq = array(samples, 'f')\n\t\t\t\ts = sup.set(ref, seq)\n\t\t\t\tsup.run()\n\t\t\t\tz = sup.get_transformed()\n\t\t\t\tmodelDict[ind] = np.ravel(z)\n\t\t\t\tind += 1\n\treturn modelDict, ref\n\n\n\n\ndef center(data):\n\t'''\n\tinput: a dictionary where each value is a model in the form of a flattened array, and each array contains the coordinates of the atoms of that model.\n\n\tMethod:\n\t\tConstructs an m by n array where m is the total number of coorniates of all atoms (e.g., for 1ail with 70 atoms, m = 70 * 3 = 270), and n is the number of models, i.e., n= 50,000+\n\t\tsubtracts the mean of the row elements from each value of the rows\n\n\treturns: the centered array, i.e., the result of the above method\n\t'''\n\n\tdata = data.T\n\tmean = data.mean(axis=1).reshape(-1, 1)\n\tdata = data - data.mean(axis=1).reshape(-1, 1)\n\treturn data, mean\n\n\n\ndef svd(data):\n\t'''\n\tInput: Centerd or scaled data of size m by n. n = number of models, m = total number of coordinates in each model.\n\tMethod:\n\t\t1. prepare the data: divides each element by sqrt(n-1)\n\t\t2. run sklearn's PCA on data\n\t\t3. extract the singular values, square them to get the variances\n\t\t4. extract the eigenvectors/principle_components\n\t\t5. Compute the projected data, i.e., original data projected to the priciple components\n\tOUtputs:\n\t\t1. squared singular values (variances)\n\t\t2. principle components\n\t\t3. projected data by using sklearn pca's transform()\n\t\t4. projected data by multiplying the eigenvectors/principle_components with the data\n\t'''\n\toriginal_data = data\n\t# prepare the data\n\tdata = data.T\n\tY = np.divide(data, math.sqrt((data.shape[1]-1)))\n\tpca = PCA()\n\tpca.fit(Y)\n\tpcs = pca.components_\n\texplained_var = pca.explained_variance_\n\tsingular_values = pca.singular_values_\n\tsingular_values = np.square(singular_values) # eigenvectors/PCs\n\tprojected_data_1 = pca.transform(data)\n\tprojected_data_1 = projected_data_1.T\n\n\t# multiply the principle components with the data to generate the projected data\n\tpcs = pcs.T\n\tidx = np.argsort(singular_values)[::-1]\n\tsingular_values = singular_values[idx]\n\tpcs = pcs[:, idx]\n\n\tprojected_data_2 = np.dot(pcs.T, original_data)\n\n\treturn singular_values, pcs, projected_data_1, projected_data_2\n\n\n\ndef Eig(data):\n\t'''\n\tInput: Centerd or scaled data of size m by n. n = number of models, m = total number of coordinates in each model.\n\tMethod:\n\t\t1. prepare the data: divides each element by sqrt(n-1)\n\t\t2. calculate the covariance matrix, which is a square matrix. Numpy's linalg.eig requires a square matrix\n\t\t3. run numpy's linalg.eig on data\n\t\t4. collect the eigenvalues and eigenvectors\n\t\t5. Compute the projected data by multiplying the eigenvectors/principle_components with the data\n\tOUtputs:\n\t\t1. eigenvalues\n\t\t2. eigenvectors\n\t\t3. projected data\n\t'''\n\t#calculate the covariance matrix, which is a square matrix. Numpy's linalg.eig requires a square matrix\n\tn_minus_1 = data.shape[1]-1\n\tmult = np.dot(data, np.transpose(data))\n\tcov = np.divide(mult, n_minus_1)\n\teigenvals, eigenvecs = np.linalg.eig(cov)\n\tidx = np.argsort(eigenvals)[::-1]\n\teigenvals = eigenvals[idx]\n\teigenvecs = eigenvecs[:, idx]\n\teigenvecs_all = eigenvecs\n\n\tprojected_data_eig1 = np.dot(eigenvecs.T, data)\n\n\teigenvecs = eigenvecs[:, :2] # retain only top two pcs\n\tprojected_data_eig2 = np.dot(eigenvecs.T, data)\n\treturn eigenvals, eigenvecs_all, projected_data_eig1, projected_data_eig2\n\n\ndef accSum(eigenvals):\n\t'''\n\tInput: eigenvalues as a 1D array or list\n\tMethod: Divides each eigenvalue by the highest value in the list/array, then multiplies each of them with 100 to generate percentage of accumulated variances\n\tOutput: returns the accumulated variances\n\t'''\n\tnon_zero_eigvals = eigenvals[ 0 < eigenvals ]\n\taccSum = np.cumsum(non_zero_eigvals)\n\taccSum /= accSum[ accSum.shape[0] - 1 ]\n\taccSum *= 100\n\treturn accSum\n\n\n\ndef main():\n\t'''\n\tRequires the location of the coordinate file.\n\tEach file contains lines, where each line contains the coordinates of a model, e.g., if model 1 has 70 atoms, each with 3 coordinates (3*70 = 210 coordinates),\n\tthen the line corresponding model 1 is like this: 210 x1 y1 z1 x2 y2 z2 ... x70 y70 z70\n\n\t'''\n\tcoordinate_file = '/home/localadmin/sbl/1dtja/onedtja.txt'\n\n\n\n\t# align the models with the first one in the file. No need to call this function if already pickled to disk.\n\n\taligned_dict, ref = align(coordinate_file)\n\n\n\t# center the data by subtracting the mean of the rows from each row element. No need to do it again if centered data is already pickled to disk.\n\tcentered_data, mean = center(aligned_dict)\n\tprint (centered_data.shape)\n\n\n\t# perform svd via sklearn's PCA\n\tsquared_singulars, pcs, projected_data_1, projected_data_2 = svd(centered_data)\n\n\taccSum_svd = accSum(squared_singulars)\n\t# print 'accSum from svd: '\n\t# print accSum_svd[:10]\n\t\n\t# compute the eigenvalues and eigenvectors using numpy's linalg.eig\n\teigenvalues, eigenvecs, projected_data_eig1, projected_data_eig2 = Eig(centered_data)\n\taccSum_eig = accSum(eigenvalues)\n\t# print 'accSum from eig: '\n\t# print accSum_eig[:10]\n\n\n\teigenvalues = eigenvalues.reshape(-1,1)\n\n\taccSum_eig = np.array(accSum_eig).reshape(-1,1)\n\tindices = np.array(list(range(1, len(accSum_eig)+1))).reshape(-1,1)\n\twrite_to_file = np.concatenate((indices, accSum_eig), axis = 1)\n\tref = np.ravel(ref).reshape(-1,1)\n\tref_mean_eig_pcs = np.concatenate((ref, mean, eigenvalues, eigenvecs), axis = 1)\n\n\n\tprojected_data_eig2 = projected_data_eig2.T\n\n\tenergylist = []\n\t#read the energy file\n\twith open('/home/localadmin/sbl/1dtja/onedtja_energy.txt', 'r') as f:\n\t\tfor line in f:\n\t\t\tline = float(line.strip())\n\t\t\tenergylist.append(line)\n\n\t#energylist = energylist[:-1] # only for 1aly\n\tenergyarray = np.array(energylist).reshape(-1,1)\n\n\tpc_and_energy = np.concatenate((projected_data_eig2, energyarray), axis = 1)\n\n\twith open('/home/localadmin/sbl/codes/pca/test/pc1_pc2_energy_1dtja.txt', 'w') as f:\n\t\tnp.savetxt(f, pc_and_energy, delimiter = ' ', fmt='%1.8f')\n\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":7385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"68249478","text":"\n\"\"\"\nUtility functions.\n\"\"\"\n\nfrom typing import (Union, Iterable, Iterator, Dict, List, Tuple, NamedTuple)\nfrom pathlib import Path\nimport warnings\nimport importlib\nimport pkgutil\nimport codecs\nimport re\nfrom itertools import permutations\nfrom collections import deque, defaultdict\nfrom functools import wraps\nfrom enum import IntEnum\n\n# Default modules need to import the PyDelphin version\nfrom delphin.__about__ import __version__ # noqa: F401\n\n\nPathLike = Union[str, Path]\n\n\ndef deprecated(message=None, final_version=None, alternative=None):\n if message is None:\n message = \"Function '{name}' is deprecated\"\n if final_version is not None:\n message += \" and will be removed from version {version}\"\n if alternative is not None:\n message += '; use the following instead: {alternative}'\n\n def deprecated_decorator(f):\n @wraps(f)\n def deprecated_wrapper(*args, **kwargs):\n warnings.warn(\n message.format(\n name=f.__name__,\n version=final_version,\n alternative=alternative\n ),\n DeprecationWarning,\n stacklevel=2\n )\n return f(*args, **kwargs)\n return deprecated_wrapper\n return deprecated_decorator\n\n\ndef safe_int(x):\n try:\n x = int(x)\n except ValueError:\n pass\n return x\n\n\n# inspired by NetworkX is_connected():\n# https://networkx.github.io/documentation/latest/_modules/networkx/algorithms/components/connected.html#is_connected\ndef _bfs(g, start=None):\n if not g:\n return {start} if start is not None else set()\n seen = set()\n if start is None:\n start = next(iter(g))\n agenda = deque([start])\n while agenda:\n x = agenda.popleft()\n if x not in seen:\n seen.add(x)\n agenda.extend(y for y in g.get(x, []) if y not in seen)\n return seen\n\n\ndef _connected_components(nodes, edges):\n if not edges:\n return [{node} for node in nodes]\n g = {n: set() for n in nodes}\n for n1, n2 in edges:\n g[n1].add(n2)\n g[n2].add(n1)\n # find connected components\n components = []\n seen = set()\n for n in nodes:\n if n not in seen:\n component = _bfs(g, n)\n seen.update(component)\n components.append(component)\n return components\n\n\ndef _isomorphism(g1, g2, top1, top2) -> Dict[str, str]:\n \"\"\"\n Return the first isomorphism found for graphs *g1* and *g2*.\n\n Start from *top1* and *top2*.\n\n *g1* and *g2* are dictionaries mapping each node id to inner\n dictionaries that map node ids to some data where there exists an\n edge between the two node target. The data is an arbitrary string\n used for matching heuristics.\n\n This assumes that the graphs are not multigraphs.\n \"\"\"\n _iso_inv_map(g1)\n _iso_inv_map(g2)\n\n hypothesis: Dict[str, str] = {}\n agenda: List[Tuple[str, str]] = next(\n _iso_candidates({top1: None}, {top2: None}, g1, g2, hypothesis),\n [])\n return next(_iso_vf2(hypothesis, g1, g2, agenda), {})\n\n\ndef _iso_inv_map(d):\n \"\"\"\n Augment *d* with inverse mappings.\n\n Assumes *d* is not a multigraph.\n \"\"\"\n _d = {}\n for src, d2 in d.items():\n for tgt, data in d2.items():\n if tgt is not None and src != tgt:\n if tgt not in _d:\n _d[tgt] = {}\n _d[tgt][src] = '--' + data\n for k, d2 in _d.items():\n d[k].update(d2)\n\n\ndef _iso_vf2(hyp, g1, g2, agenda):\n # base case\n if len(hyp) == len(g1) or not agenda:\n yield hyp\n n1, n2 = agenda.pop()\n # get edges, filter node data and self edges\n n1s = {n: d for n, d in g1[n1].items() if n is not None and n != n1}\n n2s = {n: d for n, d in g2[n2].items() if n is not None and n != n2}\n # update the current state\n new_hyp = dict(hyp)\n new_hyp[n1] = n2\n for c_agenda in _iso_candidates(n1s, n2s, g1, g2, new_hyp):\n yield from _iso_vf2(new_hyp, g1, g2, agenda + c_agenda)\n\n\ndef _iso_candidates(n1s, n2s, g1, g2, hyp):\n # get the inverse mapping for faster reverse lookups\n inv = {n2: n1 for n1, n2 in hyp.items()}\n for _n2s in permutations(list(n2s)):\n # filter out bad mappings\n agenda = []\n for n1, n2 in zip(list(n1s), _n2s):\n if hyp.get(n1) == n2 and inv.get(n2) == n1:\n continue # no issue, but don't add to agenda\n elif n1 in hyp or n2 in inv:\n agenda = [] # already traversed, not compatible\n break\n elif len(g1[n1]) != len(g2[n2]):\n agenda = [] # incompatible arity\n break\n elif g1[n1].get(None) != g2[n2].get(None):\n agenda = [] # incompatible node data\n break\n elif n1s[n1] != n2s[n2]:\n agenda = [] # incompatible edge data\n break\n else:\n agenda.append((n1, n2))\n if agenda:\n yield agenda\n # Finally yield an empty agenda because there's nothing to do\n yield []\n\n\n# unescaping escaped strings (potentially with unicode)\n# (disabled but left here in case a need arises)\n# thanks: http://stackoverflow.com/a/24519338/1441112\n\n# import re\n# import codecs\n\n# _ESCAPE_SEQUENCE_RE = re.compile(r'''\n# ( \\\\U........ # 8-digit hex escapes\n# | \\\\u.... # 4-digit hex escapes\n# | \\\\x.. # 2-digit hex escapes\n# | \\\\[0-7]{1,3} # Octal escapes\n# | \\\\N\\{[^}]+\\} # Unicode characters by name\n# | \\\\[\\\\'\"abfnrtv] # Single-character escapes\n# )''', re.UNICODE | re.VERBOSE\n# )\n\n# def unescape_string(s):\n# def decode_match(match):\n# return codecs.decode(match.group(0), 'unicode-escape')\n# return _ESCAPE_SEQUENCE_RE.sub(decode_match, s)\n\n\n# S-expressions\n# e.g. (:n-inputs . 3) or (S (NP (NNS Dogs)) (VP (VBZ bark)))\n\n_Val = Union[str, int, float]\n\n\nclass SExprResult(NamedTuple):\n \"\"\"The result of parsing an S-Expression.\"\"\"\n data: Union[Tuple[_Val, _Val], List[_Val]]\n remainder: str\n\n\n# escapes from https://en.wikipedia.org/wiki/S-expression#Use_in_Lisp\n_SExpr_escape_chars = r'\"\\s\\(\\)\\[\\]\\{\\}\\\\;'\n_SExpr_symbol_re = re.compile(r'(?:[^{}]+|\\\\.)+'.format(_SExpr_escape_chars))\n\n\ndef _SExpr_unescape_symbol(s):\n return re.sub(r'\\\\([{}])'.format(_SExpr_escape_chars), r'\\1', s)\n\n\ndef _SExpr_unescape_string(s):\n return re.sub(r'\\\\([\"\\\\])', r'\\1', s)\n\n\nclass _SExprParser(object):\n def parse(self, s):\n i = 0\n n = len(s)\n while i < n and s[i].isspace():\n i += 1\n if i == n:\n return SExprResult([], '')\n assert s[i] == '('\n i += 1\n while i < n and s[i].isspace():\n i += 1\n stack = [[]]\n while i < n:\n c = s[i]\n # numbers\n if c.isdigit() or c == '-' and s[i + 1].isdigit():\n j = i + 1\n while s[j].isdigit():\n j += 1\n c = s[j]\n if c in '.eE': # float\n if c == '.':\n j += 1\n while s[j].isdigit():\n j += 1\n if c in 'eE':\n j += 1\n if s[j] in '+=':\n j += 1\n while s[j].isdigit():\n j += 1\n stack[-1].append(float(s[i:j]))\n else: # int\n stack[-1].append(int(s[i:j]))\n i = j\n elif c == '\"': # quoted strings\n j = i + 1\n while s[j] != '\"':\n if s[j] == '\\\\':\n j += 2\n else:\n j += 1\n stack[-1].append(\n _SExpr_unescape_string(s[i + 1 : j])) # noqa: E203\n i = j + 1\n elif c == '(':\n stack.append([])\n i += 1\n elif c == ')':\n xs = stack.pop()\n if len(xs) == 3 and xs[1] == '.':\n xs = tuple(xs[::2])\n if len(stack) == 0:\n return SExprResult(xs, s[i + 1 :]) # noqa: E203\n else:\n stack[-1].append(xs)\n i += 1\n elif c.isspace():\n i += 1\n else:\n m = _SExpr_symbol_re.match(s, pos=i)\n if m is None:\n raise ValueError('Invalid S-Expression: ' + s)\n stack[-1].append(_SExpr_unescape_symbol(m.group(0)))\n i += len(m.group(0))\n\n def format(self, d):\n if isinstance(d, tuple) and len(d) == 2:\n return f'({d[0]} . {d[1]})'\n elif isinstance(d, (tuple, list)):\n return '({})'.format(' '.join(map(self.format, d)))\n elif isinstance(d, str):\n return d\n else:\n return repr(d)\n\n\nSExpr = _SExprParser()\n\n\nclass LookaheadIterator(object):\n \"\"\"\n Wrapper around an iterator or generator that allows for peeking\n at the nth token of any n, and the ability to skip intervening\n tokens (e.g., what is the 3rd token that is not a comment?).\n \"\"\"\n def __init__(self, iterable, n=1024):\n assert n > 0\n self._iterable = iterable\n self._n = n\n self._buffer = deque()\n self._buffer_fill()\n\n def _buffer_fill(self, n=None):\n # append up to buffer length n\n if n is None:\n n = self._n\n iterable = self._iterable\n buffer = self._buffer\n append = buffer.append\n for i in range(max(n - len(buffer), 0)):\n try:\n datum = next(iterable)\n append(datum)\n except StopIteration:\n if len(buffer) == 0:\n return False\n else:\n break\n return True\n\n def next(self, skip=None):\n \"\"\"\n Remove the next datum from the buffer and return it.\n \"\"\"\n buffer = self._buffer\n popleft = buffer.popleft\n if skip is not None:\n while True:\n try:\n if not skip(buffer[0]):\n break\n popleft()\n except IndexError:\n if not self._buffer_fill():\n raise StopIteration\n try:\n datum = popleft()\n except IndexError:\n if not self._buffer_fill():\n raise StopIteration\n datum = popleft()\n return datum\n\n def peek(self, n=0, skip=None, drop=False):\n \"\"\"\n Return the *n*th datum from the buffer.\n \"\"\"\n buffer = self._buffer\n popleft = buffer.popleft\n datum = None\n if skip is not None:\n stack = []\n stackpush = stack.append\n while n >= 0:\n try:\n datum = popleft()\n except IndexError:\n if not self._buffer_fill():\n raise StopIteration\n datum = popleft()\n if not skip(datum):\n n -= 1\n stackpush(datum)\n elif not drop:\n stackpush(datum)\n buffer.extendleft(reversed(stack))\n else:\n if not self._buffer_fill(n + 1):\n raise StopIteration\n datum = buffer[n]\n return datum\n\n\n_Token = Tuple[int, str, int, int, str]\n\n\nclass LookaheadLexer(LookaheadIterator):\n def __init__(self, iterable, error_class, n=1024):\n self._errcls = error_class\n super().__init__(iterable, n=n)\n\n def expect(self, *args, skip=None):\n vals = []\n for (ttype, tform) in args:\n gid, token, lineno, offset, line = self.next(skip=skip)\n err = None\n if ttype is not None and gid != ttype:\n err = str(ttype)\n elif tform is not None and token != tform:\n err = repr(tform)\n if err is not None:\n raise self._errcls('expected: ' + err,\n lineno=lineno,\n offset=offset,\n text=line)\n vals.append(token)\n if len(args) == 1:\n return vals[0]\n else:\n return vals\n\n def accept(self, arg, skip=None, drop=False):\n ttype, tform = arg\n gid, token, lineno, offset, line = self.peek(skip=skip, drop=drop)\n if ((ttype is None or gid == ttype)\n and (tform is None or token == tform)):\n self.next(skip=skip)\n return token\n return None\n\n def choice(self, *args, skip=None):\n gid, token, lineno, offset, line = self.next(skip=skip)\n for (ttype, tform) in args:\n if ((ttype is None or gid == ttype)\n and (tform is None or token == tform)):\n return gid, token\n errs = [str(ttype) if ttype is not None else repr(tform)\n for ttype, tform in args]\n raise self._errcls('expected one of: ' + ', '.join(errs),\n lineno=lineno, offset=offset, text=line)\n\n def expect_type(self, *args, skip=None):\n return self.expect(*((arg, None) for arg in args), skip=skip)\n\n def expect_form(self, *args, skip=None):\n return self.expect(*((None, arg) for arg in args), skip=skip)\n\n def accept_type(self, arg, skip=None, drop=False):\n return self.accept((arg, None), skip=skip, drop=drop)\n\n def accept_form(self, arg, skip=None, drop=False):\n return self.accept((None, arg), skip=skip, drop=drop)\n\n def choice_type(self, *args, skip=None):\n return self.choice(*((arg, None) for arg in args), skip=skip)\n\n def choice_form(self, *args, skip=None):\n return self.choice(*((None, arg) for arg in args), skip=skip)\n\n\nclass Lexer(object):\n def __init__(self, tokens, error_class=None):\n self.tokens = tokens\n self.tokentypes = None\n\n if error_class is None:\n from delphin.exceptions import PyDelphinSyntaxError as error_class\n self._errcls = error_class\n\n self._configure()\n\n def _configure(self):\n patterns = []\n types = []\n desc = {}\n for group, token in enumerate(self.tokens, 1):\n pattern, name = token\n\n numgroups = re.compile(pattern).groups\n if numgroups == 0:\n pattern = '(' + pattern + ')'\n elif numgroups != 1:\n raise ValueError(\n 'pattern does not have 0 or 1 group: ' + pattern)\n patterns.append(pattern)\n\n name, _, description = name.partition(':')\n if description:\n desc[name] = description\n types.append(name)\n\n self._re = re.compile('|'.join(patterns))\n e = IntEnum('TokenTypes', types)\n e.__str__ = lambda self, desc=desc: desc.get(self.name, self.name)\n self.tokentypes = e\n\n def lex(self, lineiter: Iterable[str]) -> LookaheadLexer:\n return LookaheadLexer(self.prelex(lineiter), self._errcls)\n\n def prelex(self, lineiter: Iterable[str]) -> Iterator[_Token]:\n \"\"\"\n Lex the input string\n\n Yields:\n (gid, token, line_number, offset, line) where offset is the\n character position within the line\n \"\"\"\n # loop optimizations\n finditer = self._re.finditer\n UNEXPECTED = self.tokentypes.UNEXPECTED\n\n lines = enumerate(lineiter, 1)\n lineno = 0\n try:\n for lineno, line in lines:\n matches = finditer(line)\n for m in matches:\n gid = m.lastindex\n offset = m.start()\n if gid == UNEXPECTED:\n raise self._errcls(\n 'unexpected input',\n lineno=lineno,\n offset=offset,\n text=line)\n token = m.group(gid)\n yield (gid, token, lineno, offset, line)\n except StopIteration:\n pass\n\n\n# modified from https://www.python.org/dev/peps/pep-0263/#defining-the-encoding\n_encoding_symbol_re = re.compile(\n b'^.*?coding[:=][ \\\\t]*([-_.a-zA-Z0-9]+)', re.IGNORECASE)\n\n\ndef detect_encoding(filename, default_encoding='utf-8', comment_char=b';'):\n encoding = None\n with open(filename, 'rb') as fh:\n line1 = fh.readline()\n # strip off any UTF-8 BOM and leading spaces\n if line1.startswith(codecs.BOM_UTF8):\n line1 = line1[len(codecs.BOM_UTF8):].lstrip()\n has_bom = True\n else:\n line1 = line1.lstrip()\n has_bom = False\n\n if line1.startswith(comment_char):\n re_match1 = _encoding_symbol_re.search(line1)\n if re_match1:\n match = re_match1.group(1).decode('ascii').lower()\n if codecs.lookup(match):\n encoding = match\n\n if has_bom:\n if encoding and encoding != 'utf-8':\n raise ValueError(\"Declared encoding does not match BOM\")\n else:\n encoding = 'utf-8'\n\n if not encoding:\n encoding = default_encoding\n\n return encoding\n\n\ndef namespace_modules(ns):\n \"\"\"Return the name to fullname mapping of modules in package *ns*.\"\"\"\n return {name: f'{ns.__name__}.{name}'\n for _, name, _ in pkgutil.iter_modules(ns.__path__)}\n\n\ndef inspect_codecs():\n \"\"\"\n Inspect all available codecs and return a description.\n\n The description is a mapping from a declared representation to a\n list of codecs for that representation. Each item on the list is a\n tuple of ``(codec_name, codec_module, codec_description)``. If\n there is any error when attempting to load a codec module, the\n representation will be ``(ERROR)``, the module will be ``None``,\n and the description will be the exception message.\n \"\"\"\n import delphin.codecs\n codecs = namespace_modules(delphin.codecs)\n result = defaultdict(list)\n for name, fullname in codecs.items():\n try:\n mod = importlib.import_module(fullname)\n rep = mod.CODEC_INFO['representation']\n description = mod.CODEC_INFO.get('description', '')\n except Exception as ex:\n result['(error)'].append((name, None, str(ex)))\n else:\n result[rep].append((name, mod, description))\n return result\n\n\ndef import_codec(name: str):\n \"\"\"\n Import codec *name* and return the module.\n \"\"\"\n import delphin.codecs\n codecs = namespace_modules(delphin.codecs)\n fullname = codecs[name]\n return importlib.import_module(fullname)\n\n\ndef make_highlighter(fmt):\n try:\n import pygments\n from pygments.formatters import Terminal256Formatter as _formatter\n except ImportError:\n return str\n\n highlight = str # backoff function\n\n if fmt == 'simplemrs':\n try:\n import delphin.highlight\n except ImportError:\n pass\n else:\n\n def highlight(text):\n return pygments.highlight(\n text,\n delphin.highlight.SimpleMRSLexer(),\n _formatter(style=delphin.highlight.MRSStyle))\n\n elif fmt == 'diff':\n from pygments.lexers.diff import DiffLexer\n\n def highlight(text):\n # this seems to append a newline, so remove it\n return pygments.highlight(\n text,\n DiffLexer(),\n _formatter()).rstrip('\\n')\n\n return highlight\n","sub_path":"delphin/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":19875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"268668629","text":"import os\r\nimport random\r\ndict = {\r\n 'Spot':'斑迹',\r\n 'Mold':'保护渣',\r\n 'Scratch':'划伤',\r\n 'Hole':'孔洞',\r\n 'Caterpillar':'毛毛虫',\r\n 'Flat flower':'平整花',\r\n 'Warped':'翘皮',\r\n 'Zinc ash':'锌灰',\r\n 'Zinc residue':'锌渣',\r\n 'Dirty':'脏污',\r\n 'pressing':'异物压入'\r\n}\r\n\r\nimport cv2\r\ndef preProcess(path):\r\n img = cv2.imread(path)\r\n height = img.shape[0]\r\n width = img.shape[1]\r\n\r\n img_roi = img.copy()\r\n if width > height:\r\n x_left = int((width - height) / 2)\r\n x_right = x_left + height\r\n img_roi = img[0:height,x_left:x_right]\r\n elif width < height:\r\n y_top = int((height - width) / 2)\r\n y_down = y_top + width\r\n img_roi = img[y_top:y_down,0:width]\r\n\r\n # cv2.imshow('tsy',img_roi)\r\n # cv2.waitKey(1000)\r\n\r\n return img_roi\r\n\r\ndef do_process():\r\n oldDir = 'defect2/lib-11-100'\r\n newDir = 'defect2/proLib-11-100'\r\n if not os.path.exists(newDir):\r\n os.mkdir(newDir)\r\n for dir in os.listdir(oldDir):\r\n defectPath = os.path.join(oldDir, dir)\r\n if os.path.isdir(defectPath):\r\n newPath = os.path.join(newDir, dir)\r\n if not os.path.exists(newPath):\r\n os.mkdir(newPath)\r\n for file in os.listdir(defectPath):\r\n imgPath = os.path.join(defectPath, file)\r\n newImagePath = os.path.join(newPath, file)\r\n img_roi = preProcess(imgPath)\r\n cv2.imwrite(newImagePath, img_roi)\r\n\r\ndef do_dataAugment():\r\n oldDir = 'data/proLib-11-100'\r\n newDir = 'data/augLib-11-100_4'\r\n for dir in os.listdir(oldDir):\r\n defectPath = os.path.join(oldDir, dir)\r\n if os.path.isdir(defectPath):\r\n trainPath = os.path.join(newDir, 'train/'+ dir)\r\n testPath = os.path.join(newDir, 'test/'+ dir)\r\n if not os.path.exists(trainPath):\r\n os.makedirs(trainPath)\r\n if not os.path.exists(testPath):\r\n os.makedirs(testPath)\r\n perKindList = [] # 每类中所有的图片\r\n for file in os.listdir(defectPath):\r\n perKindList.append(file)\r\n random.shuffle(perKindList)\r\n train_list = perKindList[0:-10] # 训练集\r\n test_list = perKindList[-10:-1]\r\n test_list.append(perKindList[-1]) # 测试集\r\n\r\n dataAugment(train_list, test_list, trainPath, testPath, defectPath)\r\n\r\ndef dataAugment(train_list, test_list, trainPath, testPath, defectPath):\r\n for file in train_list:\r\n imageName = file.split('.')[0]\r\n imgpath = os.path.join(defectPath,file)\r\n img = cv2.imread(imgpath, cv2.IMREAD_GRAYSCALE)\r\n\r\n # if 'pressing' in defectPath or 'Zinc residue' in defectPath:\r\n # img = centerCrop(img)\r\n\r\n # resize到统一的200*200\r\n img = cv2.resize(img, (200,200), interpolation=cv2.INTER_CUBIC).copy()\r\n\r\n # 裁剪\r\n img_cropped1 = img[0:166,0:166]\r\n img_cropped2 = img[0:166, 34:200]\r\n img_cropped3 = img[34:200, 0:166]\r\n img_cropped4 = img[34:200, 34:200]\r\n img_cropped5 = img[17:183, 17:183]\r\n\r\n # 水平翻转\r\n img_flapped1 = cv2.flip(img_cropped1, 1, dst=None)\r\n img_flapped2 = cv2.flip(img_cropped2, 1, dst=None)\r\n img_flapped3 = cv2.flip(img_cropped3, 1, dst=None)\r\n img_flapped4 = cv2.flip(img_cropped4, 1, dst=None)\r\n img_flapped5 = cv2.flip(img_cropped5, 1, dst=None)\r\n\r\n # 均值模糊和高斯模糊\r\n Blur = cv2.blur(img, (5, 5), 3)\r\n Gussian_blur = cv2.GaussianBlur(img, (5,5), 3)\r\n\r\n SaltNoise = SaltAndPepper(img, 0.1)\r\n GussianNoise = addGussianNoise(img, 0.1)\r\n\r\n RotateMatrix = cv2.getRotationMatrix2D(center=(img.shape[1]/2, img.shape[0]/2), angle=180, scale=1)\r\n RotImg_180 = cv2.warpAffine(img, RotateMatrix, (img.shape[0], img.shape[1]))\r\n\r\n img_aug = [img_cropped1, img_cropped2, img_cropped3, img_cropped4, img_cropped5,\r\n img_flapped1, img_flapped2, img_flapped3, img_flapped4, img_flapped5,\r\n Blur, Gussian_blur, SaltNoise, GussianNoise, RotImg_180]\r\n\r\n augImgList = [] #(image,name)\r\n for i in range(len(img_aug)):\r\n newName = imageName + '_aug_' + str(i+1) + '.bmp'\r\n savePath = os.path.join(trainPath, newName)\r\n img_aug[i] = cv2.resize(img_aug[i],(224, 224))\r\n cv2.imwrite(savePath, img_aug[i])\r\n\r\n for file in test_list:\r\n imgPath = os.path.join(defectPath, file)\r\n img = cv2.imread(imgPath, cv2.IMREAD_GRAYSCALE)\r\n # if 'pressing' in defectPath or 'Zinc residue' in defectPath:\r\n # img = centerCrop(img)\r\n img = cv2.resize(img, (224, 224))\r\n savePath = os.path.join(testPath, file)\r\n cv2.imwrite(savePath, img)\r\n\r\ndef centerCrop(img):\r\n height, width = img.shape[0], img.shape[1]\r\n left = int(width / 4)\r\n top = int(height / 4)\r\n img1 = img[top:int(3 * height / 4), left:int(3 * width / 4)].copy()\r\n return img1\r\n\r\n# 椒盐噪声\r\ndef SaltAndPepper(img, percentage):\r\n src = img.copy()\r\n SP_NoiseNum = int(percentage * src.shape[0] * src.shape[1])\r\n for i in range(SP_NoiseNum):\r\n randX = random.randint(0,src.shape[0]-1)\r\n randY = random.randint(0,src.shape[1]-1)\r\n if random.randint(0,1) == 0:\r\n src[randX,randY] = 0\r\n else:\r\n src[randX, randY] = 255\r\n return src\r\n\r\n# 高斯噪声\r\ndef addGussianNoise(img, percentage):\r\n src = img.copy()\r\n G_NoiseNum = int(percentage * src.shape[0] * src.shape[1])\r\n for i in range(G_NoiseNum):\r\n randX = random.randint(0,src.shape[0]-1)\r\n randY = random.randint(0,src.shape[1]-1)\r\n src[randX,randY] = 255\r\n return src\r\n\r\nif __name__ == '__main__':\r\n # do_process()\r\n do_dataAugment()\r\n print('')\r\n\r\n\r\n\r\n","sub_path":"preProcess.py","file_name":"preProcess.py","file_ext":"py","file_size_in_byte":5942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"142143460","text":"# The zip() function take iterables(can be zero or more), makes iterator that\n# aggregates elements based on the iterables passed, and returns an interator of tuples.\n\n# The syntax of zip() is:\n# zip(*iterables)\n\n# Return value from zip\n# The zip() function returns an iterator of tuples based on the iterable object.\n# if no parameters are passed, zip() returns an empty iterator\n# if a single iterable is passed, zip() returns an iterator of 1-tuple.\n# Meaning, the number of elements in each tuple is 1.\n# if mulitple iterables are passed, i th tuple contains i th Suppose,\n# two iterables are passed;\n# one iterable containing 3 and other containg 5 elements. Then, the returned\n# iterator has 3 tuples. It's because iterator stops when shorted iterable\n# is exhausted.\n\nnumberList = [1, 2, 3]\nstrList = ['one', 'two', 'three']\n\n# No iterables are passed.\nresult = zip()\n\n# Converting iterator to list\nresultList = list(result)\nprint('result list: ', resultList)\n\n# One iterable is passed\nresult = zip(numberList)\n# Converting iterator to list\nresultList = list(result)\nprint('result list:', resultList)\n\n# Two iterable is passed\nresult = zip(numberList, strList)\n# Converting iterator to list\nresultList = list(result)\nprint(resultList)\n\n\n# The * operator can be used in conjuction with zip() to unzip the list.\ncoordinate = ['x', 'y', 'z']\nvalue = [3, 4, 5, 0, 9]\n\nresult = zip(coordinate, value)\nresultList = list(result)\nprint(resultList)\n\nc, v = zip(*resultList)\nprint('c:', c)\nprint('v:', v)\n\nfor a, _ in zip(coordinate, value):\n print(a)\n","sub_path":"print_list/zip.py","file_name":"zip.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"106653853","text":"# aparent maparea aia pe multiproc e mult mai ineficienta decat map propriu-zis\nfrom multiprocessing import pool\nfrom time import time\n\ndef f(x):\n return x*x\n\nif __name__ == '__main__':\n start = time()\n with pool.Pool(10) as p:\n print(p.map(f, list(range(10))))\n print(\"Pool multiprocessing took {}\".format(time()-start))\n\n start = time()\n print(list(map(f,list(range(10)))))\n print(\"Single processing took {}\".format(time()-start))","sub_path":"basics/Python3/multiproc/pool.py","file_name":"pool.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"618864959","text":"#!/usr/bin/python3\nfrom sys import stdin\nfrom math import log10\n\ndef main ():\n read = stdin.readline\n n = int (read ())\n sm = sum (map (lambda x: log10 (int (x)), read ().split ()))\n print (int (10 ** (sm / n) + 1))\n\nif __name__ == \"__main__\": main ()\n","sub_path":"_help_fredo.py","file_name":"_help_fredo.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"528052798","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom .. import items\nfrom scrapy.http import HtmlResponse\nimport urllib2\n\n\nclass BodyPartSpider(scrapy.Spider):\n name = \"bodypart\"\n allowed_domains = [\"wikipedia.org\"]\n start_urls = (\n 'https://en.wikipedia.org/wiki/List_of_organs_of_the_human_body',\n )\n\n def parse(self, response):\n\n mw_content_text = response.xpath(\n '//div[@id=\"mw-content-text\"]')\n cat_and_ul = mw_content_text.xpath('h2|ul')\n\n for i in cat_and_ul:\n # If it's an h2 header\n if i.xpath('name()').extract()[0] == 'h2':\n # If i is the end of doc, break\n if i.xpath('span[@class=\"mw-headline\"]/@id')\\\n .extract()[0] == 'See_also':\n break\n\n # Reserve category\n category = i.xpath('span/text()').extract()[0]\n\n # If it's ul list\n elif i.xpath('name()').extract()[0] == 'ul':\n # For each li in ul\n li_list = i.xpath('li')\n for j in li_list:\n bp_name = j.xpath('a/text()').extract()\n if len(bp_name) <= 0:\n continue\n\n bp_name = bp_name[0].lower()\n bp_id = bp_name.replace(' ', '-')\n\n # Follow the inner link (if exists) and extract desc.\n\n a_url = j.xpath('a/@href').extract()\n if len(a_url) > 0:\n desc = self.parseLink(a_url[0])\n else:\n desc = ''\n\n yield self.genItem(bp_id, bp_name, category, '', desc)\n\n # Search down to child ul\n\n sub_list = j.xpath('ul/li')\n for k in sub_list:\n sub_bp_name = k.xpath('a/text()').extract()[0].lower()\n sub_bp_id = sub_bp_name.replace(' ', '-')\n\n possible_a_link = k.xpath('a/@href').extract()\n if len(possible_a_link) > 0:\n sub_desc = self.parseLink(\n possible_a_link[0])\n else:\n sub_desc = ''\n\n yield self.genItem(sub_bp_id, sub_bp_name, category,\n bp_id, sub_desc)\n\n def genItem(self, bp_id, bp_name, bp_cat, bp_parent, bp_desc):\n item = items.BodyPartItem()\n item['bodypartId'] = bp_id\n item['bodypartName'] = bp_name\n item['bodypartCategory'] = bp_cat\n item['bodypartParent'] = bp_parent\n item['bodypartDesc'] = bp_desc\n return item\n\n def parseLink(self, a_link):\n full_url = 'https://en.wikipedia.org' + a_link\n response = urllib2.urlopen(full_url)\n response = HtmlResponse(url=full_url, body=response.read())\n all_p = response.xpath('//div[@id=\"bodyContent\"]').xpath('.//p')\n all_p_text = ''.join(all_p.xpath('.//text()').extract())\n\n return all_p_text\n","sub_path":"data/crawler/mayo_clinic/mayo_clinic/spiders/bodypart.py","file_name":"bodypart.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"77214117","text":"# -*- coding: utf-8 -*-\n#\n# The MIT License (MIT)\n#\n# Copyright (c) 2014\n# Data Intensive Applications and Systems laboratory (DIAS)\n# École Polytechnique Fédérale de Lausanne\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\nimport collections\n\n\nname_types = (str, unicode)\nprimitive_types = (int, long, float, str, unicode, bool)\n\ndef is_namedtuple(x):\n t = type(x)\n b = t.__bases__\n if len(b) != 1 or b[0] != tuple:\n return False\n f = getattr(t, '_fields', None)\n if not isinstance(f, tuple):\n return False\n return all(type(n) == str for n in f)\n\ndef get_primitive_type(v):\n if isinstance(v, int): return int\n elif isinstance(v, long): return long\n elif isinstance(v, float): return float\n elif isinstance(v, str): return str\n elif isinstance(v, unicode): return unicode\n elif isinstance(v, bool): return bool\n raise TypeError\n\ndef is_table(data):\n try:\n try:\n item = next(iter(data))\n except StopIteration:\n return None\n else:\n if isinstance(item, collections.OrderedDict) \\\n and all([isinstance(k, name_types) for k in item.keys()]):\n schema = collections.OrderedDict()\n for k, v in item.items():\n schema[k] = get_primitive_type(v)\n return schema\n elif isinstance(item, dict) \\\n and all([isinstance(k, name_types) for k in item.keys()]):\n schema = dict()\n for k, v in item.items():\n schema[k] = get_primitive_type(v)\n return schema\n elif is_namedtuple(item) \\\n and all([isinstance(f, name_types) for f in item._fields]) \\\n and all([isinstance(getattr(item, f), primitive_types) for f in item._fields]):\n # List of collections.namedtuple with primitive types\n schema = collections.OrderedDict()\n for k in item._fields:\n schema[k] = get_primitive_type(getattr(item, k))\n return schema\n return None\n except TypeError:\n return None\n","sub_path":"pyrawcore/core/tablify.py","file_name":"tablify.py","file_ext":"py","file_size_in_byte":3196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"452972797","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 11 02:30:57 2017\n\n@author: SAHAJA MAHANTY\n\"\"\"\nimport hashlib\n\ndef convert(text):\n l = text.lower().split()\n add = []\n\n\n def correct(l):\n if (add[1] == 0):\n if (l[1] == \"you\" and (l[2] == \"eat\" or l[2] == \"go\")):\n l.insert(1, \"do\")\n elif ((l[1] == \"you\" or l[1] == \"they\") and (l[2] == \"eating\" or l[2] == \"going\")):\n l.insert(1, \"are\")\n elif ((l[1] == \"i\" or l[1] == \"they\") and (l[2] == \"eat\" or l[2] == \"go\")):\n l.insert(1, \"do\")\n elif (l[1] == \"i\" and (l[2] == \"eating\" or l[2] == \"going\")):\n l.insert(1, \"am\")\n elif ((l[1] == \"he\" or l[1] == \"she\") and (l[2] == \"eat\" or l[2] == \"go\")):\n l.insert(1, \"does\")\n elif ((l[1] == \"he\" or l[1] == \"she\") and (l[2] == \"eating\" or l[2] == \"going\")):\n l.insert(1, \"is\")\n elif ((l[1] == \"he\" or l[1] == \"she\") and (l[2] == \"today\")):\n l.insert(1, \"is\")\n elif ((l[1] == \"he\" or l[1] == \"she\") and (l[2] == \"yesterday\")):\n l.insert(1, \"was\")\n elif ((l[1] == \"you\") and (l[2] == \"today\")):\n l.insert(1, \"are\")\n elif ((l[1] == \"you\") and (l[2] == \"yesterday\")):\n l.insert(1, \"were\")\n\n return l\n\n\n def isQuestion(l):\n q = [\"who\", \"where\", \"what\", \"why\", \"when\", \"how\", \"which\", \"whom\"]\n z = []\n c = 0\n for word in l:\n if (word in q):\n # print(\"found \",word)\n z.append(word)\n c += 1\n if (c > 0):\n add.append(1)\n return z\n else:\n add.append(0)\n return False\n\n\n z = isQuestion(l)\n\n\n # print(z)\n\n\n def helpVerb(l):\n hp = [\"is\", \"am\", \"are\", \"was\", \"were\", \"be\", \"been\", \"being\", \"has\", \"have\", \"had\", \"does\", \"do\", \"did\", \"can\",\n \"will\", \"shall\", \"could\", \"would\", \"should\", \"must\", \"may\", \"might\"]\n c = 0\n for word in l:\n if (word in hp):\n # print(\"found \",word)\n z.append(word)\n c += 1\n if (c > 0):\n add.append(1)\n return z\n else:\n add.append(0)\n return False\n\n\n z1 = helpVerb(l)\n\n\n # print(z1)\n\n def isPronoun(l):\n pn = [\"i\", \"we\", \"you\", \"she\", \"he\", \"it\", \"they\", \"them\", \"his\", \"her\", \"me\"]\n c = 0\n for word in l:\n if (word in pn):\n # print(\"found \",word)\n z.append(word)\n c += 1\n if (c > 0):\n add.append(1)\n return z\n else:\n add.append(0)\n return False\n\n\n z2 = isPronoun(l)\n\n\n # print(z2)\n\n def isVerb(l):\n vv = [\"go\", \"eat\", \"going\", \"eating\", \"sleeping\", \"read\", \"walk\"]\n c = 0\n for word in l:\n if (word in vv):\n # print(\"found \",word)\n z.append(word)\n c += 1\n if (c > 0):\n add.append(1)\n return z\n else:\n add.append(0)\n return False\n\n\n z3 = isVerb(l)\n\n\n # print(z3)\n # print(add)\n\n\n def checkDay(l):\n days = [\"yesterday\", \"today\", \"tomorrow\"]\n c = 0\n for word in l:\n if (word in days):\n # print(\"found \",word)\n z.append(word)\n c += 1\n if (c > 0):\n add.append(1)\n return z\n else:\n add.append(0)\n return False\n\n\n z4 = checkDay(l)\n # print(z4)\n # print(add)\n if (z4 != False):\n z4c = correct(z4)\n string = ' '.join(map(str, z4c))\n # print(\"corrected >\", string)\n return string\n elif (z3 != False):\n z3c = correct(z3)\n string = ' '.join(map(str, z3c))\n # print(\"corrected >\", string)\n return string\n else:\n string = ' '.join(map(str, z2))\n # print(\"corrected >\", string)\n return string\n\n\n\n\n\n\n","sub_path":"projects/project1/sentry.py","file_name":"sentry.py","file_ext":"py","file_size_in_byte":4153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"637836215","text":"import csv\n\ndef toPrecision2(n):\n return \"%0.2f\" % (n)\n\ndef avgNumberArray(arr, days):\n sumN = 0\n for i in arr:\n sumN = i + sumN\n return toPrecision2(sumN / days)\n\ndef buyOrSell(avgArr5, avgArr20, index):\n if avgArr5[index - 1] < avgArr20[index - 1]:\n if avgArr5[index] > avgArr20[index]:\n return 'B'\n if avgArr5[index - 1] > avgArr20[index - 1]:\n if avgArr5[index] < avgArr20[index]:\n return 'S'\n return 'X'\n \n\nfname = './total.csv'\nf = open(fname,\"r\")\nindex = 0\nsumPrice = 0\nfinalResult = [\n ['Date', 'closingPrice', 'avg5', 'avg20', 'avg60', 'B_S_check'] # header\n]\narr5 = []\narr20 = []\narr60 = []\n\navgArr5 = [0]\navgArr20 = [0]\n\nfor line in f:\n if index >= 0:\n strList = line.split(',')\n date = strList[0]\n closingPrice = float(strList[4])\n sumPrice = sumPrice + closingPrice\n\n dailyResult = [date, str(closingPrice), '', '', '', 'X']\n\n arr5.append(closingPrice)\n arr20.append(closingPrice)\n arr60.append(closingPrice)\n if len(arr5) == 5:\n dailyResult[2] = avgNumberArray(arr5, 5)\n # remove head\n arr5.pop(0)\n if len(arr20) == 20:\n dailyResult[3] = avgNumberArray(arr20, 20)\n # remove head\n arr20.pop(0)\n if len(arr60) == 60:\n dailyResult[4] = avgNumberArray(arr60, 60)\n # remove head\n arr60.pop(0)\n\n if index >= 20:\n avgArr5.append(float(dailyResult[2]))\n avgArr20.append(float(dailyResult[3]))\n else:\n avgArr5.append(0)\n avgArr20.append(0)\n\n if index > 20:\n dailyResult[5] = buyOrSell(avgArr5, avgArr20, index)\n \n finalResult.append(dailyResult)\n\n index = index + 1\n\n# re-write csv file\nf = open(fname,\"w\")\nf.truncate() # clear csv file\nw = csv.writer(f) # write csv file\nw.writerows(finalResult)\nf.close()\n","sub_path":"python2/exam/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"409105620","text":"import numpy as np\nimport cv2 as cv\nfrom matplotlib import pyplot as plt\nimport sys\nimport pandas as pd\nimport argparse\nfrom pathlib import Path\n\ndef get_flann_matches(img_n1, img_n2):\n img1 = cv.imread(f'../data/house/frame000000{img_n1:02}.png')\n img2 = cv.imread(f'../data/house/frame000000{img_n2:02}.png')\n\n grey1 = cv.cvtColor(img1, cv.COLOR_RGB2GRAY)\n grey2 = cv.cvtColor(img2, cv.COLOR_RGB2GRAY)\n\n # perform sift to get keypoints and descriptors\n sift = cv.xfeatures2d.SIFT_create()\n kp1, des1 = sift.detectAndCompute(grey1, None)\n kp2, des2 = sift.detectAndCompute(grey2, None)\n\n # FLANN parameters\n FLANN_INDEX_KDTREE = 1\n index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\n search_params = dict(checks=50)\n\n flann = cv.FlannBasedMatcher(index_params,search_params)\n matches = flann.knnMatch(des1,des2,k=2)\n\n return matches, kp1, kp2\n\ndef get_matches(img_n1, img_n2, t):\n img1 = cv.imread(f'../data/house/frame000000{img_n1:02}.png')\n img2 = cv.imread(f'../data/house/frame000000{img_n2:02}.png')\n img1 = cv.cvtColor(img1, cv.COLOR_RGB2GRAY)\n img2 = cv.cvtColor(img2, cv.COLOR_RGB2GRAY)\n\n # perform sift to get keypoints and descriptors\n sift = cv.xfeatures2d.SIFT_create()\n kp1, des1 = sift.detectAndCompute(img1, None)\n kp2, des2 = sift.detectAndCompute(img2, None)\n\n # match descriptors (using L1 norm now, because it's the only one that worked...)\n matcher = cv.BFMatcher(cv.NORM_L1)\n matches = matcher.match(des1, des2)\n\n # only keep good matcjes (why? idk)\n matches.sort(key=lambda x: x.distance)\n num_good_matches = int(len(matches) * t)\n matches = matches[:num_good_matches]\n\n return matches, kp1, kp2\n\ndef set_points(pvm, img_n1, img_n2, feature_point, p, p_a):\n pvm.loc[f'x{img_n1}', feature_point] = p[-1][0]\n pvm.loc[f'y{img_n1}', feature_point] = p[-1][1]\n pvm.loc[f'x{img_n2}', feature_point] = p_a[-1][0]\n pvm.loc[f'y{img_n2}', feature_point] = p_a[-1][1]\n\n return pvm\n\ndef get_pvm(pvm, img_n1, img_n2, p, p_a):\n found = False\n for feature_point, point in enumerate(zip(pvm.loc[f'x{img_n1}'], pvm.loc[f'y{img_n1}'])):\n if nearby(p[-1], point, ARGS.nearby_filter):\n found = True\n pvm.ix[f'x{img_n2}', feature_point] = p_a[-1][0]\n pvm.ix[f'y{img_n2}', feature_point] = p_a[-1][1]\n break\n\n # when no new points are found, add a new column\n if not found:\n feature_point = f'{pvm.shape[1] + 1}'\n pvm = set_points(pvm, img_n1, img_n2, feature_point, p, p_a)\n\n return pvm\n\ndef nearby(points1, points2, t):\n x1, y1 = points1\n x2, y2 = points2\n close = x1 - t <= x2 and x2 <= x1 + t and y1 - t <= y2 and y2 <= y1 + t\n return close\n\ndef test_pvm():\n with open('PointViewMatrix.txt', 'r') as f:\n bigboi = np.zeros((202, 215))\n for i, line in enumerate(f):\n print(i)\n line = np.array(line.split(' '))\n print(line.shape)\n bigboi[i, :] = line.squeeze()\n\n bigboi = np.where(bigboi > 0, 1, 0)\n\n plt.imshow(bigboi, aspect='auto', cmap='gray')\n plt.title('Point-View Matrix from PointViewMatrix.txt')\n plt.xlabel('Feature Points (M)')\n plt.ylabel('Images (2N)')\n Path(\"../results/chaining/images\").mkdir(parents=True, exist_ok=True)\n plt.savefig('../results/chaining/images/pvm_from_PointViewMatrix_norm.png')\n plt.show()\n\n\ndef show_off():\n Path(\"../results/chaining/pvm\").mkdir(parents=True, exist_ok=True)\n pvm = pd.read_csv(f'../results/chaining/pvm/pvm_{ARGS.match_method}_{ARGS.dist_filter}_{ARGS.nearby_filter}.csv', index_col=0).values\n\n norm = np.where(np.isnan(pvm), 1, 0)\n plt.imshow(pvm, aspect='auto', cmap='gray')\n plt.title('Point-View Matrix')\n plt.xlabel('Feature Points (M)')\n plt.ylabel('Images (2N)')\n\n plt.imshow(norm, aspect='auto', cmap='gray')\n plt.title('Point-View Matrix')\n plt.xlabel('Feature Points (M)')\n plt.ylabel('Images (2N)')\n Path(\"../results/chaining/images\").mkdir(parents=True, exist_ok=True)\n plt.savefig(f'../results/chaining/images/normalized_pvm_{ARGS.match_method}_{ARGS.dist_filter}_{ARGS.nearby_filter}.pdf')\n plt.show()\n\n\ndef chaining():\n pvm = pd.DataFrame()\n\n # iterate over all images, compare 1-2, 2-3, 48-49, 49-1\n for img_n1 in range(1,50):\n if img_n1 + 1 < 50:\n img_n2 = img_n1 + 1\n else:\n img_n2 = 1\n\n print(f'Image {img_n1} and {img_n2}')\n\n p = []\n p_a = []\n\n if ARGS.match_method == 'bf':\n matches, kp1, kp2 = get_matches(img_n1, img_n2, ARGS.dist_filter)\n\n # iterate over matches and create pvm\n for i, match in enumerate(matches):\n p.append(kp1[match.queryIdx].pt)\n p_a.append(kp2[match.trainIdx].pt)\n\n # very first iteration, create first column\n if pvm.shape[1] == 0:\n feature_point = f'{i + 1}'\n pvm = set_points(pvm, img_n1, img_n2, feature_point, p, p_a)\n else:\n pvm = get_pvm(pvm, img_n1, img_n2, p, p_a)\n\n elif ARGS.match_method == 'flann':\n matches, kp1, kp2 = get_flann_matches(img_n1, img_n2)\n\n for i,(m, n) in enumerate(matches):\n # ratio test as per Lowe's paper\n if m.distance < ARGS.dist_filter*n.distance:\n p_a.append(kp2[m.trainIdx].pt)\n p.append(kp1[m.queryIdx].pt)\n\n # very first iteration, create first column\n if pvm.shape[1] == 0:\n feature_point = f'{i + 1}'\n pvm = set_points(pvm, img_n1, img_n2, feature_point, p, p_a)\n else:\n pvm = get_pvm(pvm, img_n1, img_n2, p, p_a)\n\n Path(\"../results/chaining/pvm\").mkdir(parents=True, exist_ok=True)\n pvm.to_csv(f'../results/chaining/pvm/pvm_{ARGS.match_method}_{ARGS.dist_filter}_{ARGS.nearby_filter}.csv')\n print(pvm.shape)\n pvm = pvm.values\n print(pvm.shape)\n\n if ARGS.vizualize:\n show_off()\n\n return pvm\n\nif __name__ == '__main__':\n PARSER = argparse.ArgumentParser()\n\n PARSER.add_argument('--vizualize', default=True, type=bool,\n help='whether to visualize the result')\n PARSER.add_argument('--match_method', default='bf', type=str,\n help='which method to use for matching feature points', choices=['bf', 'flann'])\n PARSER.add_argument('--dist_filter', default=0.25, type=float,\n help='initial points filtering')\n PARSER.add_argument('--nearby_filter', default=10, type=int,\n help='threshold for determining whether two points are similar')\n\n ARGS = PARSER.parse_args()\n chaining()\n","sub_path":"stucture_from_motion/code/chaining.py","file_name":"chaining.py","file_ext":"py","file_size_in_byte":6887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"242767568","text":"from socket import socket, AF_INET, SOCK_STREAM\n\nhost = ''\nport = 8889\n\nsvrobj = socket(AF_INET, SOCK_STREAM)\nsvrobj.bind((host, port))\nsvrobj.listen(5)\n\nwhile True:\n cnet, addr = svrobj.accept()\n print('Server connected by', addr)\n while True:\n data = cnet.recv(1024)\n if not data:break\n cnet.send(b'Received=>'+data)\n cnet.close()","sub_path":"test/socketserver.py","file_name":"socketserver.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"122110601","text":"from nanpy import (ArduinoApi, SerialManager, Servo)\nfrom time import sleep\n\nservoPins = [3,5,6,9,10,11]\nangleInc = 45\ncurrentChannel = 0\nbuttonPin = 13\nbuttonState = 0\n\nnumPins = len(servoPins)\ncurrentServo = 0\ncurrentAngle = 0\nservo = []\n\n\ntry:\n connection = SerialManager()\n a = ArduinoApi(connection = connection)\nexcept:\n print(\"Failed to connect to Arduino\")\n \n\n#Setup arduino pins like in arduino IDE\n\na.pinMode(buttonPin, a.INPUT)\nfor m in servoPins:\n servo.append(Servo(m))\n\ntry:\n while True:\n buttonState = a.digitalRead(buttonPin)\n print(\" Button State: {} Current Servo: {} Current Angle: {}\" .format(buttonState, currentServo, currentAngle))\n if buttonState:\n servo[currentServo].write(0)\n currentAngle = 0\n currentServo += 1\n if currentServo > numPins:\n currentServo = 0\n sleep(1)\n buttonState = False\n servo[currentServo].write(currentAngle)\n currentAngle += angleInc\n if currentAngle > 180:\n currentAngle = 0\n sleep(1)\n \nexcept:\n print(\"Servo EXITING\")\n for m in servo:\n m.detach()\n\n \n","sub_path":"RaspberryPi/old things/Misc/Nanpy/oscilsixSERVO.py","file_name":"oscilsixSERVO.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"542204737","text":"import sys\nimport ffmpeg\n\nfrom libs.task import task\n\nvalidator = {\n 'input': {\n 'type': str,\n 'required': True,\n 'help': 'Input file path',\n },\n 'output': {\n 'type': str,\n 'required': True,\n 'help': 'Output file path',\n },\n 'image_overlay': {\n 'type': str,\n 'required': True,\n 'help': 'Image overlay input file path',\n },\n 'position': {\n 'type': str,\n 'regex': r\"\\d+:\\d+\",\n 'required': True,\n 'help': 'Image overlay position',\n },\n}\n\n\n@task(\n name='overlay',\n title='Наложить картинку на видео',\n validator=validator\n)\ndef overlay(input, output, image_overlay, position):\n \"\"\"\n ffmpeg -i ./resources/24cbad87b8d4453b905a9f4865d96acb.mp4 -i ./resources/png-2093542_960_720.png \\\n -filter_complex \"[0:v][1:v] overlay=25:25\" \\\n -pix_fmt yuv420p -c:a copy \\\n output.mp4\n \"\"\"\n overlay_file = ffmpeg.input(image_overlay)\n try:\n x, y = position.split(':')\n (ffmpeg\n .input(input)\n .overlay(overlay_file, x=x, y=y)\n .output(output).overwrite_output().run(capture_stdout=True, capture_stderr=True)\n )\n return output\n # .get_args()\n # .overwrite_output().run(capture_stdout=True, capture_stderr=True)\n except ffmpeg.Error as e:\n print(e.stderr.decode(), file=sys.stderr)\n sys.exit(1)\n","sub_path":"tasks/overlay.py","file_name":"overlay.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"564255034","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@Author : YANGWEI\n@Created : 2018/07/18\n@Use : train_account like people used\n\"\"\"\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom selenium.webdriver import ActionChains\nimport time, random, datetime\nimport threading\nimport json\nimport logging\n\n\nclass TrainAccount(object):\n \"\"\"养号策略\"\"\"\n\n def __init__(self,account= 13929224780,lock = None):\n \"\"\"初始化参数\"\"\"\n\n self.account = account\n self.passwd = \"\"\n self.chrome = webdriver.Chrome(\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe\")\n self.chrome.maximize_window() # 窗口最大化\n self.url_login = \"https://acc.maimai.cn/login\" # 登录地址\n self.wait = WebDriverWait(self.chrome, 15) # 等待的最大时间\n self.add_friends_count = 0 # 本日尝试添加好友的数量\n self.have_friends_acount = 0 # 拥有的好友数\n self.accept_friends_count = 0 # 接受好友的数目\n self.send_status_count = 0 # 发送状态的数量\n self.mark_good_count = 0 # 点赞次数\n self.status = 0 # 初始状态 0表示未参加训练 1\n self.lock = lock\n self.content = ''\n # 配置日志文件\n self.logger = logging.getLogger() # 创建日志对象\n self.logger.setLevel(logging.INFO) # Log等级总开关\n self.rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time())) # 获取当前时间\n self.log_file_name = \"./logs/\" + datetime.datetime.now().strftime('%Y-%m-%d') + '.logs'\n self.fh = logging.FileHandler(self.log_file_name, mode='w', encoding=\"utf-8\")\n self.fh.setLevel(logging.INFO) # 输出到file的log等级的开关\n # 第三步,定义handler的输出格式\n self.formatter = logging.Formatter(\"%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s\")\n self.fh.setFormatter(self.formatter)\n # 第四步,将logger添加到handler里面\n self.logger.addHandler(self.fh)\n # 配置日志完成\n self.send_status_word_list = [\"...\",\"...\",\"转发\",\"get\",\"了解一下...\",\"了解一下...\",\"666\",\"收藏\",\"分享一波...\",\"默默转发一下\",\"默默转发一下\",\"长见识了\",\"惊了,还有这样的操作\"]\n self.send_status_emotion_list = [\"[微笑]\",\"[微笑]\",\"[卖萌]\",\"[赞]\",\"[赞]\",\"[得意]\",\"[做鬼脸]\",\"[肌肉]\"]\n self.res_dic = {} # 配置为空字典\n\n def login(self):\n \"\"\"实现登录\"\"\"\n\n self.chrome.get(self.url_login)\n input_phone = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, \"#form > div:nth-child(3) > div > input\"))) # 判断该元素是否加载完成\n # 输入关键字\n time.sleep(random.randint(2,4))\n input_phone.send_keys(self.account) # 填写手机号\n time.sleep(random.randint(2,4))\n input_passwd = self.chrome.find_element_by_css_selector(\"#login_pw\") # 填写密码\n input_passwd.send_keys(self.passwd)\n time.sleep(random.randint(2,4))\n # 点击登陆\n self.chrome.find_element_by_css_selector(\"#form > input.loginBtn\").click()\n # 判断是否登陆成功\n try:\n self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, \"#react_app > div > div.PCcontainer.clearfix > div.PCcontent.float-l > div.btn-primary.btn.center-block\"))) # 判断该元素是否加载完成\n self.logger.info(\"账号{}登录成功:\".format(self.account))\n except Exception as e:\n self.logger.debug(\"登录失败账号为:{} \\n error_msg:{}\".format(self.account, e))\n self.screen_shot(\".\\\\scream_shots\\\\login_error_shot\\\\err_login_{}.png\".format(self.account))\n self.chrome.quit()\n return False\n time.sleep(random.randint(5, 8))\n # 判断是否需要消除小点点 给9/10的概率会消灭\n if self.select_do_or_not(9, 10):\n # 此处点击通知按钮 ---消除红色小点点\n message_btn_css_str = \"#react_app > div > div.headerWarp > div > div.myCenter.float-r > span\"\n # todo 若果小红点这里出错 直接return\n message_btn_ele = self.chrome.find_element_by_css_selector(message_btn_css_str)\n # 定位到元素 点击触发\n # self.slip_crowd_button(message_btn_ele)\n self.move_mouse_to_click(message_btn_ele)\n time.sleep(5)\n # 刷新界面\n flush_friend_css_str = \"#react_app > div > div.headerWarp > div > ul > li.cursor-pointer.current > a\"\n self.chrome.find_element_by_css_selector(flush_friend_css_str).click()\n self.logger.info(\"账号{}消除通知成功:\".format(self.account))\n time.sleep(2)\n # 缓慢下拉滑动条 浏览界面\n for j in range(100):\n # self.chrome.execute_script('window.scrollTo({}, {})'.format((j * random.randint(46,50)), (j * random.randint(46,50) + 46)))\n self.slip_smoothly(45)\n time.sleep(0.25)\n time.sleep(2)\n return True\n\n # 暂时不用这个方法\n def add_friends(self):\n \"\"\"每次随机添加position位置的好友\"\"\"\n # 1.进入发现页面\n self.chrome.find_element_by_css_selector(\"#react_app > div > div.headerWarp > div > ul > li:nth-child(2) > a\").click()\n time.sleep(random.randint(2, 5))\n\n # 判断发现界面是否加载成功\n exist_or_not_ele_str = \"#react_app > div > div.PCcontainer.clearfix > div.PCcontent.float-l > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div.PCcardLines > p:nth-child(1) > span > span.font-16.cursor-pointer\"\n try:\n self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, exist_or_not_ele_str))) # 判断该元素是否加载完成\n except Exception as e:\n self.logger.debug(\"加好友发现界面还没加载完全 \\n error_msg:{}\".format(e))\n self.chrome.find_element_by_css_selector(\"#react_app > div > div.headerWarp > div > ul > li:nth-child(2) > a\").click() # 重新加载一次好友界面\n time.sleep(random.randint(2,5))\n\n # 1.1 下拉列表刷新更多人\n error_add_f_count = 0\n for _ in range(random.randint(3, 5)):\n # 判断是否未加载出来\n self.get_more_wrong()\n for j in range(30,150):\n self.slip_smoothly(-0.02*j**2 + 4*j)\n # self.chrome.execute_script('window.scrollTo({}, {})'.format((j * random.randint(36,40)), (j * random.randint(36,40) + 40)))\n time.sleep(0.35)\n time.sleep(random.randint(5,10))\n\n for _ in range(5,6):\n # 2.获取随机陌生人---点击姓名---跳转到详细页面(此处新开了一个标签页面)\n random_code = random.randint(1,80)\n self.logger.info(\"找到的随机好友候选人为编号:{}\".format(random_code))\n stranger_ele_css_str = \"#react_app > div > div.PCcontainer.clearfix > div.PCcontent.float-l > div:nth-child(2) > div:nth-child({}) > div:nth-child(1) > div.PCcardLines > p:nth-child(1) > span > span.font-16.cursor-pointer\".format(random_code)\n #react_app > div > div.PCcontainer.clearfix > div.PCcontent.float-l > div:nth-child(2) > div:nth-child(37) > div:nth-child(1) > div.PCcardLines > p:nth-child(1) > span > span.font-16.cursor-pointer\n try:\n stranger_ele_position = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, stranger_ele_css_str))) # 判断该元素是否加载完成\n except Exception as e:\n self.logger.debug(\"定位陌生人报错 \\n error_msg:{}\".format(e))\n # stranger_ele_position = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, stranger_ele_css_str)))\n # 定位好友报错后直接就跳过这个好友\n continue\n\n # 2.0 定位到当前元素\n self.slip_crowd_button(stranger_ele_position)\n # 将元素放置屏幕中央\n for _ in range(15):\n self.slip_smoothly(-20)\n time.sleep(0.25)\n # 2.1 将当前的chrome切换到新的标签页\n # print(\"移动鼠标至目标并且点击\")\n self.move_mouse_to_click(stranger_ele_position)\n # 切换窗口\n self.switch_to_window()\n # todo 测试 2.2 停顿3秒 下拉浏览所有信息后\n for _ in range(random.randint(30,40)):\n self.slip_smoothly(30)\n time.sleep(0.25)\n time.sleep(random.randint(3,5))\n # 2.3 定位到加好友按钮---点击加好友\n get_friend_css_str = \"#react_app > div > div.PCcontainer.clearfix > div.PCrightSide.float-r > div.m-a-lg > div:nth-child(2)\"\n try:\n get_friend_ele_posi = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, get_friend_css_str))) # 判断该元素是否加载完成\n except Exception as e:\n self.logger.debug(\"定位加好友错误信息:\\n error_msg:{}\".format(e))\n error_add_f_count += 1\n self.screen_shot(\".\\\\scream_shots\\\\add_friend_shot\\\\add_friedn_error{}_{}.png\".format(error_add_f_count, random_code))\n # 直接关闭当前页面 回到之前页面继续找下一个\n self.chrome.close()\n # 关闭当前之后将窗口切换回原来窗口\n time.sleep(2)\n self.switch_to_window()\n continue\n # 定位目标元素\n self.slip_crowd_button(get_friend_ele_posi)\n # 将元素放置屏幕中央\n for _ in range(15):\n self.slip_smoothly(-15)\n time.sleep(0.25)\n # 点击加好友动作给鼠标\n self.move_mouse_to_click(get_friend_ele_posi)\n time.sleep(random.randint(1,4))\n # print(\"点击加好友\")\n # 2.4 关闭当前窗口 并切换回原来窗口\n self.chrome.close()\n time.sleep(2)\n self.switch_to_window()\n time.sleep(5)\n\n # 3.继续下拉列表---循环步骤2 5次\n\n def switch_to_window(self):\n \"\"\"切换窗口\"\"\"\n handles_list = self.chrome.window_handles # 获取当前窗口句柄集合(列表类型)\n # print(\"handles_list is :{}\".format(handles_list))\n if len(handles_list) == 2:\n time.sleep(1)\n # print(\"切换到2号窗口\")\n self.chrome.switch_to.window(handles_list[1])\n elif len(handles_list) == 1:\n # print(\"切换到2号窗口\")\n time.sleep(1)\n self.chrome.switch_to.window(handles_list[0])\n else:\n self.logger.debug(\"当前窗口数目为:{}\".format(len(handles_list)))\n\n def click_find(self):\n \"\"\"\n 1.点击发现\n 2.下拉刷新 三次\n 3.点击点赞 随机2-4次\n \"\"\"\n\n # 点击发现\n self.chrome.find_element_by_css_selector(\"#react_app > div > div.headerWarp > div > ul > li:nth-child(2) > a\").click()\n time.sleep(random.randint(2, 4))\n # 判断是否成功加载界面\n exist_or_not_ele_str = \"#react_app > div > div.PCcontainer.clearfix > div.PCcontent.float-l > div:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div.PCcardLines > p:nth-child(1) > span > span.font-16.cursor-pointer\"\n try:\n self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, exist_or_not_ele_str))) # 判断该元素是否加载完成\n except:\n self.logger.debug(\"点击发现界面还没加载完全,重新加载。。。\")\n self.chrome.find_element_by_css_selector(\n \"#react_app > div > div.headerWarp > div > ul > li.cursor-pointer.current > a\").click() # 重新加载一次好友界面\n time.sleep(random.randint(2, 5))\n for _ in range(2,5):\n self.get_more_wrong()\n for j in range(50,120):\n self.slip_smoothly(-0.02*j**2 + 4*j)\n # self.chrome.execute_script('window.scrollTo({}, {})'.format((j * random.randint(36,40)), (j * random.randint(36,40) + 40)))\n time.sleep(0.25)\n time.sleep(random.randint(3,6))\n\n count_mark_error = 0\n for _ in range(random.randint(3,5)):\n # todo 测试 随机点赞开始\n rand_code = random.randint(5,60)\n\n # 根据产生的随机数确定点赞元素位置\n # css_str = \"#react_app > div > div.PCcontainer.clearfix > div.PCcontent.float-l > div:nth-child(2) > div:nth-child({}) > div:nth-child(1) > div.PCcardLines > p:nth-child(1) > span > span.font-16.cursor-pointer\".format(rand_code)\n css_str = \"#react_app > div > div.PCcontainer.clearfix > div.PCcontent.float-l > div:nth-child(2) > div:nth-child({}) > div.PCFeedContentContainer > div:nth-child(2) > div.clearfix > ul > li:nth-child(3) > span\".format(rand_code)\n # print(\"this is css_str:{}\".format(css_str))\n try:\n mark_good = self.chrome.find_element_by_css_selector(css_str)\n except:\n self.logger.debug(\"选择点赞标签有误,跳过此人\")\n count_mark_error += 1\n self.screen_shot(\".\\\\scream_shots\\\\mark_good_shot\\\\mark_good_error{}_{}.png\".format(count_mark_error, rand_code))\n time.sleep(3)\n continue\n # 滑动到点赞位置\n self.slip_crowd_button(mark_good)\n for _ in range(12):\n self.slip_smoothly(-20)\n time.sleep(0.15)\n time.sleep(2)\n # mark_good.send_keys(Keys.ENTER)\n ActionChains(self.chrome).move_to_element(mark_good).click().perform()\n self.mark_good_count += 1\n self.logger.debug(\"给第编号为{}点赞成功\".format(rand_code))\n self.status = 1 # 点赞完成将状态改为1\n time.sleep(random.randint(3,10))\n\n # 控制发状态的数量 做一个随机判断概率为1/4\n # 判断点赞\n print(\"判断转发状态概率\")\n if self.select_do_or_not(3, 5):\n # 随机算则一个人 转发状态\n # send_status_count = 0\n print(\"进入转发...\")\n retry_count = 0\n while True:\n if (self.send_status_count >= 1) or (retry_count >= 3):\n break\n send_status_css_str = \"#react_app > div > div.PCcontainer.clearfix > div.PCcontent.float-l > div:nth-child(2) > div:nth-child({}) > div.PCFeedContentContainer > div:nth-child(2) > div.clearfix > ul > li:nth-child(2) > span\".format(rand_code)\n rand_code -= 2 # 取上一个元素\n retry_count += 1\n try:\n send_status_ele = self.chrome.find_element_by_css_selector(send_status_css_str)\n except:\n self.logger.debug(\"选择点赞标签有误,跳过此人,随机编号为:{}\".format(rand_code))\n self.screen_shot(\".\\\\scream_shots\\\\mark_good_shot\\\\send_status_error{}_{}.png\".format(count_mark_error,rand_code))\n time.sleep(3)\n continue\n\n time.sleep(random.randint(3, 10))\n # 滑动到点赞位置\n self.slip_crowd_button(send_status_ele)\n for _ in range(12):\n self.slip_smoothly(-20)\n time.sleep(0.15)\n time.sleep(2)\n # mark_good.send_keys(Keys.ENTER)\n ActionChains(self.chrome).move_to_element(send_status_ele).click().perform()\n # 不填写内容直接转发\n make_sure_send_str = \"#popup_container > div > div > div > div:nth-child(4) > div > div:nth-child(3) > a\"\n send_words_str = \"#popup_container > div > div > div > div:nth-child(4) > div > div:nth-child(1) > div.inputPanel\"\n try:\n make_sure_send_ele = self.wait.until(\n EC.presence_of_element_located((By.CSS_SELECTOR, make_sure_send_str))) # 判断该元素是否加载完成\n send_words_ele = self.wait.until(\n EC.presence_of_element_located((By.CSS_SELECTOR, send_words_str))) # 判断该元素是否加载完成\n except Exception as e:\n self.logger.debug(\"确认发送状态失败: \\n error_msg:{}\".format(e))\n time.sleep(3)\n continue\n time.sleep(2)\n # self.send_status_word_list = [\"...\", \"...\", \"转发\", \"get\", \"了解一下...\", \"了解一下...\", \"666\", \"收藏\", \"分享一波...\",\n # \"默默转发一下\", \"默默转发一下\", \"长见识了\", \"惊了,还有这样的操作\"]\n # self.send_status_emotion_list = [\"[微笑]\", \"[微笑]\", \"[卖萌]\", \"[赞]\", \"[赞]\", \"[得意]\", \"[做鬼脸]\", \"[肌肉]\"]\n self.content = random.choice(self.send_status_word_list) + random.choice(self.send_status_emotion_list)*3\n # print(words)\n send_words_ele.send_keys(self.content)\n time.sleep(3)\n make_sure_send_ele.click()\n\n self.send_status_count += 1\n self.status = 3 # 点赞完成将状态改为3\n self.logger.info(\"转发第{}好友状态成功,内容为:{}\".format(rand_code,self.content))\n print(\"成功转发...\")\n\n def slip_smoothly(self,steps):\n \"\"\"控制滚动条移动 steps为步长 正为当前向下 负为当前向上移动\"\"\"\n self.chrome.execute_script('window.scrollBy({}, {})'.format(0, steps))\n\n def slip_crowd_button(self,aim_ele):\n \"\"\"控制滚动条直接定位到元素位置\"\"\"\n # print(\"定位到选中的元素\")\n self.chrome.execute_script(\"arguments[0].scrollIntoView();\", aim_ele)\n time.sleep(2)\n\n def move_mouse_to_click(self, ele):\n \"\"\"移动鼠标去点击元素\"\"\"\n # print(\"开始滑动鼠标到指定位置点击\")\n ActionChains(self.chrome).move_to_element(ele).click().perform()\n\n def get_more_wrong(self):\n \"\"\"加载失败的处理策略\"\"\"\n # todo 下拉时候需要判断是否出现字样 --- 加载失败点击重试\n try:\n ele_retry_str = \"#react_app > div > div.PCcontainer.clearfix > div.PCcontent.float-l > div:nth-child(2) > div.cursor-pointer\"\n # ele = \"#react_app > div > div.PCcontainer.clearfix > div.PCcontent.float-l > div:nth-child(2) > div.cursor-pointer\"\n ele_retry = self.chrome.find_element_by_css_selector(ele_retry_str) # 异常出现的位置\n time.sleep(2)\n if ele_retry:\n self.logger.debug(\"更多内容未加载出来,需要点击加载\")\n self.move_mouse_to_click(ele_retry)\n time.sleep(5)\n # 需要再次判断 回调\n self.get_more_wrong()\n except Exception as e:\n return\n\n def select_do_or_not(self, up, down):\n \"\"\"自定义一个随机事件函数 count为概率的倒数 2\"\"\"\n print(\"进入随机判断\")\n count_list = []\n for _ in range(up):\n count_list.append(1)\n for _ in range(down - up):\n count_list.append(0)\n # self.logger.info(\"概率总体为:{}/{}\".format(up, down))\n random.shuffle(count_list)\n if random.choice(count_list):\n print(\"本次概率成功\")\n return True\n else:\n print(\"本次概率失败\")\n return False\n\n def get_friend_count(self):\n \"\"\"获取好友数量以及好友更新的时间\"\"\"\n\n chat_window_ele_str = \"#react_app > div > div.headerWarp > div > ul > li:nth-child(5) > a\"\n # react_app > div > div.headerWarp > div > ul > li:nth-child(5) > a\n try:\n chat_window_ele = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,chat_window_ele_str)))\n except Exception as e:\n print(\"聊天窗口出问题\")\n return\n # 点击聊天界面\n # self.chrome.find_element_by_css_selector(chat_window_ele_str).click()\n self.slip_crowd_button(chat_window_ele)\n self.move_mouse_to_click(chat_window_ele)\n # 等待加载过程\n time.sleep(5)\n # 切换窗口\n self.switch_to_window()\n # 等待加载元素出现\n # friends_counts_ele = self.chrome.find_elements_by_xpath(\"//div[@class='msg_list clickOnSelect']//div[@class='dropdown selectable']\")\n # react_app > div > div > div > div:nth-child(1) > div:nth-child(4) > div > div:nth-child(3)\n # accept_count = 0\n while True:\n # 循环点击聊天窗口\n # react_app > div > div > div > div:nth-child(1) > div:nth-child(4) > div > div:nth-child(2)\n add_friend_recommend_str_2 = \"#react_app > div > div > div > div:nth-child(1) > div:nth-child(4) > div > div:nth-child(2)\"\n add_friend_recommend_2 = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, add_friend_recommend_str_2)))\n # 点击聊天界面\n self.slip_crowd_button(add_friend_recommend_2)\n add_friend_recommend_2.click()\n time.sleep(2)\n\n add_friend_recommend_str_1 = \"#react_app > div > div > div > div:nth-child(1) > div:nth-child(4) > div > div:nth-child(1)\"\n add_friend_recommend_1 = self.wait.until(\n EC.presence_of_element_located((By.CSS_SELECTOR, add_friend_recommend_str_1)))\n # 点击聊天界面\n self.slip_crowd_button(add_friend_recommend_1)\n add_friend_recommend_1.click()\n # 等待加载过程\n time.sleep(2)\n # 切换到内层窗口\n self.chrome.switch_to.frame(self.chrome.find_element_by_tag_name(\"iframe\"))\n\n # 第一个li标签\n accept_friend_request_str = \"#react_app > div > div > div.panel.panel-default > ul:nth-child(3) > div:nth-child(1) > li > div > div.list-group-item-heading.list-group-item-text > div.media-right.media-middle > div > div.fr > div\"\n try:\n accept_friend_request_ele = self.wait.until(\n EC.presence_of_element_located((By.CSS_SELECTOR, accept_friend_request_str)))\n self.slip_crowd_button(accept_friend_request_ele)\n self.move_mouse_to_click(accept_friend_request_ele)\n time.sleep(2)\n self.chrome.switch_to.default_content()\n self.accept_friends_count += 1\n self.logger.info(\"添加好友成功\")\n\n except Exception as e:\n self.logger.debug(\"暂时没有好友请求信息:\\n error_msg:{}\".format(e))\n self.chrome.switch_to.default_content()\n time.sleep(2)\n break\n\n self.logger.debug(\"接受{}位好友请求成功\".format(self.accept_friends_count))\n\n add_friend_recommend_str = \"#react_app > div > div > div > div:nth-child(1) > div:nth-child(4) > div > div:nth-child(1)\"\n add_friend_recommend_ele = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,add_friend_recommend_str)))\n # 聚焦到当前位置\n self.slip_crowd_button(add_friend_recommend_ele)\n # 点击聊天界面\n add_friend_recommend_ele.click()\n # 等待加载过程\n time.sleep(3)\n # 切换到内层的html中\n self.chrome.switch_to.frame(self.chrome.find_element_by_tag_name(\"iframe\"))\n # react_app > div > div > div.panel.panel-default > ul:nth-child(4) > div:nth-child(1)\n # 添加好友集合为\n add_friend_recommend_set = self.chrome.find_elements_by_css_selector(\"#react_app > div > div > div.panel.panel-default > ul:nth-child(4) > div > li> div > div.media.list-group-item-heading.list-group-item-text > div.media-right > div\")\n # print(\"推荐好友:{}\".format(add_friend_recommend_set))\n print(\"返回的好友列表长度:{}\".format(len(add_friend_recommend_set)))\n if len(add_friend_recommend_set):\n for i in add_friend_recommend_set:\n # todo 查询的列表为空的话 不会走下面的代码\n if self.add_friends_count >= 5:\n self.chrome.switch_to.default_content() # 切换回默认窗口\n break\n try:\n self.slip_crowd_button(i)\n self.move_mouse_to_click(i)\n time.sleep(2)\n self.add_friends_count += 1\n self.logger.info(\"已发送申请添加好友\")\n except Exception as e:\n self.logger.debug(\"无法定位到指定位置加好友: \\nerror_msg:{}\".format(e))\n continue\n # 判断是否加满了好友\n try:\n full_add_ele = self.chrome.find_element_by_css_selector(\"#popup_container > div > div > div > div.layerBtns.clearfix > div.leftBtn.grayBtn\")\n self.move_mouse_to_click(full_add_ele)\n self.chrome.switch_to.default_content() # 切换回默认窗口\n break\n except Exception as e:\n # self.logger.info(\"没有出现加满的情况and错误信息:\\n error_msg:{}\".format(e))\n pass\n else:\n self.chrome.switch_to.default_content() # 切换回默认窗口\n\n # 获取好友信息\n friends_counts_ele = self.chrome.find_elements_by_css_selector(\n \"#react_app > div > div > div > div:nth-child(1) > div:nth-child(4) > div > div\")\n self.have_friends_acount = len(friends_counts_ele) - 2 # 朋友的数量为总量减去2\n # print(friends_counts)\n try:\n for i in friends_counts_ele:\n try:\n self.slip_crowd_button(i)\n self.move_mouse_to_click(i)\n time.sleep(random.randint(2, 5))\n except Exception as e:\n continue\n except Exception as e:\n self.logger.debug(\"点击获取好友数量出现错误: \\n error_msg:{}\".format(e))\n self.status = 2 # 加好友完成将状态改为2\n\n\n def chat(self):\n \"\"\"随机聊天尝试\"\"\"\n # 获取好友列表第一个好友\n # 拿到好友的名字\n\n # 进行聊天\n # 聊天窗口#react_app > div > div > div > div:nth-child(2) > div > div:nth-child(3) > div.inputPanel\n #react_app > div > div > div > div:nth-child(2) > div > div:nth-child(3) > div.inputPanel\n # 发送聊天内容按钮\n # react_app > div > div > div > div:nth-child(2) > div > div:nth-child(3) > div:nth-child(4) > a\n\n chat_window_ele_str = \"#react_app > div > div.headerWarp > div > ul > li:nth-child(5) > a\"\n self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, chat_window_ele_str)))\n # 点击聊天界面\n self.chrome.find_element_by_css_selector(chat_window_ele_str).click()\n # 等待加载过程\n time.sleep(3)\n # 切换窗口\n self.switch_to_window()\n # 等待加载元素出现\n # friends_counts_ele = self.chrome.find_elements_by_xpath(\"//div[@class='msg_list clickOnSelect']//div[@class='dropdown selectable']\")\n # react_app > div > div > div > div:nth-child(1) > div:nth-child(4) > div > div:nth-child(3)\n friends_counts_ele = self.chrome.find_elements_by_css_selector(\n \"#react_app > div > div > div > div:nth-child(1) > div:nth-child(4) > div > div\")\n print(friends_counts_ele)\n\n # react_app > div > div > div > div:nth-child(1) > div:nth-child(4) > div > div > div:nth-child(3) > div:nth-child(1) > span\n # react_app > div > div > div > div:nth-child(1) > div:nth-child(4) > div > div > div:nth-child(3) > div:nth-child(1) > span:nth-child(1)\n\n names = []\n if len(friends_counts_ele):\n for friend in friends_counts_ele:\n name = friend.find_element_by_css_selector(\"div:nth-child(3) > div:nth-child(1) > span:nth-child(1)\").text\n # if name not in \"文件传输助手待处理事项招聘小助手问答小助手\":\n if name == \"问答小助手\":\n names.append(name)\n print(\"可以进行聊天\")\n # 点击好友标签 进入聊天界面\n self.slip_crowd_button(friend)\n time.sleep(1)\n self.move_mouse_to_click(friend)\n time.sleep(1)\n # 切换到内层窗口\n # self.chrome.switch_to.frame(self.chrome.find_element_by_tag_name(\"iframe\"))\n\n # 循环的进行聊天的输入 3 次\n for i in range(3):\n # 输入内容\n send_word_window_ele = self.chrome.find_element_by_css_selector('#react_app > div > div > div > div:nth-child(2) > div > div:nth-child(3) > div.inputPanel')\n time.sleep(2)\n if i == 0:\n send_word_window_ele.send_keys(\"{},你好[微笑][微笑]\".format(name))\n elif i == 1:\n send_word_window_ele.send_keys(\"我是##,您最近有考虑换工作吗?我这里有一个hr的群,需要招聘java开发工程师,如果有换工作的打算可以加一下微信,我的手机号:{}\".format(name,self.account))\n elif i == 2:\n send_word_window_ele.send_keys(\n \"如果给你您的工作带来不便,还请见谅,祝生活愉快,工作顺利[耶耶]\")\n # 点击发送\n time.sleep(2)\n send_word_sure_ele = self.chrome.find_element_by_css_selector('#react_app > div > div > div > div:nth-child(2) > div > div:nth-child(3) > div:nth-child(4) > a')\n # react_app > div > div > div > div:nth-child(2) > div > div:nth-child(3) > div.inputPanel\n # react_app > div > div > div > div:nth-child(2) > div > div:nth-child(3) > div:nth-child(4) > a\n\n send_word_sure_ele.click()\n\n # 切换回原来窗口\n # self.chrome.switch_to.default_content()\n time.sleep(random.uniform(1,3))\n print(names)\n\n def screen_shot(self,path):\n \"\"\"获取屏幕截频 path is the file name\"\"\"\n self.chrome.save_screenshot(path)\n\n def get_page_parse(self,html):\n pass\n\n def write(self):\n \"\"\"将组装的字典写入文本\"\"\"\n self.lock.acquire() # 添加锁\n with open(\"./data/account_info_{}.txt\".format(datetime.datetime.now().strftime('%Y-%m-%d')),mode=\"a\",encoding=\"utf-8\") as f:\n # self.res_dic = {\n # \"phone\": self.account,\n # \"status\": self.status, # 默认为0 表示没有运行\n # \"have_friend_count\": self.have_friends_acount, # 默认为0\n # \"accept_friends_counts\": self.accept_friends_count, # 接受好友的数量\n # \"add_friends_count\": self.add_friends_count, # 本日添加好友的次数\n # \"send_status_count\": self.send_status_count, # 发送状态的数量\n # \"send_status_content\": self.content,\n # \"mark_good_count\": self.mark_good_count, # 点赞次数\n # \"update_time\": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n # }\n\n self.res_dic['phone'] = self.account\n self.res_dic['status'] = self.status\n self.res_dic['have_friend_count'] = self.have_friends_acount\n self.res_dic['accept_friends_counts'] = self.accept_friends_count\n self.res_dic['add_friends_count'] = self.add_friends_count\n self.res_dic['send_status_count'] = self.send_status_count\n self.res_dic['send_status_content'] = self.content\n self.res_dic['mark_good_count'] = self.mark_good_count\n self.res_dic['update_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n res_json = json.dumps(self.res_dic)\n f.write(res_json + \"\\n\")\n time.sleep(0.001)\n self.lock.release() # 释放锁\n\ndef debug(count_list,lock):\n \"\"\"功能测试 account_list为传入的测试数据列表 [15973092104,18473818486,18478203160,18774442608]\"\"\"\n t1 = time.time()\n for count in count_list:\n print(\"目前开始测试的账号为:{}\".format(count))\n t = TrainAccount(count,lock) # 给类传入所需的参数\n res = t.login()\n if not res:\n continue\n if t.select_do_or_not(13,15):\n t.click_find()\n if t.select_do_or_not(19,21):\n t.get_friend_count()\n t.chrome.quit()\n t.write()\n t2 = time.time()\n print(\"本账号总共耗时:{}\".format(t2 - t1)) # 每个账号结束后休息一段时间\n time.sleep(random.randint(50,80))\n\nif __name__ == '__main__':\n t3 = time.time()\n count_list_old = [15973092104,18473818486,18478203160,18774442608,13186716394,13487997212,15973864950,18774431361,18780145067,13483172962,13104477847,13458590677,18289064362,13456762154,18334397270,15173844841,15243802791,13175733848,13184401191,13184402180]\n count_list_new = [15243861341,18373844838,18374260839,18473868687,18773899432,15604402924,13486152604,15988451427,13106064149,13186710406,15080830947,15973882054,18373892402,18374148208,18774439265,15543617742,15543647734,15584224449,15584276084,15584367647]\n # 随机打乱出场顺序\n random.shuffle(count_list_old)\n random.shuffle(count_list_new)\n count_list1 = count_list_old[:5]\n count_list2 = count_list_old[5:10]\n count_list3 = count_list_old[10:15]\n count_list4 = count_list_old[15:]\n count_list5 = count_list_new[:5]\n count_list6 = count_list_new[5:10]\n count_list7 = count_list_new[10:15]\n count_list8 = count_list_new[15:]\n count_list_old2 = [count_list1, count_list2, count_list3, count_list4]\n count_list_new2 = [count_list5, count_list6, count_list7, count_list8]\n retry_list = [[13929224780]]\n # test_list = [[13929224780,13929224780]]\n thds = []\n lock = threading.Lock() # 创建一个锁 单利最好 传入给class类使用\n for i in count_list_new2:\n # print(\"开始执行测试的账号列表是:{}\".format(i))\n thd = threading.Thread(target=debug, args=(i,lock))\n thd.start()\n thds.append(thd)\n # print(\"结束执行测试的账号列表是:{}\".format(i))\n time.sleep(60 * 1) # 每个线程隔一分钟启动\n for j in thds:\n j.join()\n t4 = time.time()\n print(\"所有账号总共耗时:{}\".format(t4 - t3))\n\n\n","sub_path":"maimai_tran_account_driver.py","file_name":"maimai_tran_account_driver.py","file_ext":"py","file_size_in_byte":35815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"343644916","text":"import numpy as np\nimport os\nimport io\n\n# import for server\nfrom flask import Flask, render_template, request, Response, send_file, jsonify\nfrom queue import Queue, Empty\nimport threading\nimport time\n\n# import for model\nfrom transformers import AutoTokenizer, AutoModelWithLMHead, top_k_top_p_filtering\nfrom torch.nn import functional as F\nimport torch\nimport time\n\n# flask server\napp = Flask(__name__)\n\n# limit input file size under 2MB\n\n# model loading\ntokenizer = AutoTokenizer.from_pretrained(\"cpierse/gpt2_film_scripts\")\nmodel = AutoModelWithLMHead.from_pretrained(\"cpierse/gpt2_film_scripts\", return_dict=True)\n\n# change cpu to gpu so that model can use gpu (because default type is cpu)\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel.to(device)\n\n# request queue setting\nrequests_queue = Queue()\nBATCH_SIZE = 1\nCHECK_INTERVAL = 0.1\n\n# static variable\n\n# request handling\ndef handle_requests_by_batch():\n try:\n while True:\n requests_batch = []\n while not (len(requests_batch) >= BATCH_SIZE):\n try:\n requests_batch.append(requests_queue.get(timeout=CHECK_INTERVAL))\n except Empty:\n continue\n \n batch_outputs = []\n\n for request in requests_batch:\n if len(request[\"input\"]) == 2:\n batch_outputs.append(run_short(request[\"input\"][0], request[\"input\"][1]))\n elif len(request[\"input\"]) == 3:\n batch_outputs.append(run_long(request[\"input\"][0], request[\"input\"][1], request[\"input\"][2]))\n\n for request, output in zip(requests_batch, batch_outputs):\n request[\"output\"] = output\n\n except Exception as e:\n while not requests_queue.empty():\n requests_queue.get()\n print(e)\n\n\n# request processing\nthreading.Thread(target=handle_requests_by_batch).start()\n\n# run short model\ndef run_short(prompt, num):\n try:\n prompt = prompt.strip()\n input_ids = tokenizer.encode(prompt, return_tensors='pt')\n \n # input_ids also need to apply gpu device!\n input_ids = input_ids.to(device)\n\n # get logits of last hidden state\n next_token_logits = model(input_ids).logits[:, -1, :]\n # filter\n filtered_next_token_logits = top_k_top_p_filtering(next_token_logits, top_k=50, top_p=1.0)\n # sample\n probs = F.softmax(filtered_next_token_logits, dim=-1)\n next_token = torch.multinomial(probs, num_samples=num)\n\n result = {}\n for idx, token in enumerate(next_token.tolist()[0]):\n result[idx] = tokenizer.decode(token)\n\n return result\n\n except Exception as e:\n print(e)\n return 500\n\n# run long model\ndef run_long(prompt, num, length):\n try:\n prompt = prompt.strip()\n input_ids = tokenizer.encode(prompt, return_tensors='pt')\n \n # input_ids also need to apply gpu device!\n input_ids = input_ids.to(device)\n\n min_length = len(input_ids.tolist()[0])\n length += min_length\n\n sample_outputs = model.generate(input_ids, pad_token_id=50256, \n do_sample=True, \n max_length=length, \n min_length=length,\n top_k=40,\n num_return_sequences=num)\n\n generated_texts = {}\n for i, sample_output in enumerate(sample_outputs):\n output = tokenizer.decode(sample_output.tolist()[min_length:], skip_special_tokens=True)\n generated_texts[i] = output\n \n return generated_texts\n\n except Exception as e:\n print(e)\n return 500\n\n# routing\n@app.route(\"/gpt2-film/\", methods=['POST'])\ndef generation(types):\n try:\n if types != 'short' and types != 'long':\n return jsonify({'message' : 'Error! Can not route short or long'}), 400\n\n # only get one request at a time\n if requests_queue.qsize() > BATCH_SIZE:\n return jsonify({'message' : 'TooManyReqeusts'}), 429\n \n # check image format\n try:\n args = []\n\n prompt = str(request.form['text'])\n num = int(str(request.form['num_samples']))\n \n args.append(prompt)\n args.append(num)\n\n if types == 'long':\n length = int(str(request.form['length']))\n args.append(length)\n \n except Exception:\n return jsonify({'message' : 'Error! Can not read args from request'}), 500\n\n # put data to request_queue\n req = {'input' : args}\n requests_queue.put(req)\n \n # wait output\n while 'output' not in req:\n time.sleep(CHECK_INTERVAL)\n \n # send output\n generated_text = req['output']\n \n if generated_text == 500:\n return jsonify({'message': 'Error! An unknown error occurred on the server'}), 500\n \n result = jsonify(generated_text)\n \n return result\n \n except Exception as e:\n print(e)\n return jsonify({'message': 'Error! Unable to process request'}), 400\n\n@app.route('/healthz')\ndef health():\n return \"ok\", 200\n\n@app.route('/')\ndef main():\n return \"ok\", 200\n\nif __name__ == \"__main__\":\n from waitress import serve\n serve(app, host='0.0.0.0', port=80)","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"8842849","text":"###############################################################################\n# Copyright (C) 2020-2021 Habana Labs, Ltd. an Intel Company\n###############################################################################\n\n\"\"\"Encapsulates the hardware configuration for scaleout training\n\nThis class encapsulates all the single-card and multi-card/multi-node training\nrun hardware constraints for scaleout.\n\"\"\"\nimport os\nimport sys\nimport shlex\nimport socket\nimport subprocess\nfrom pathlib import Path\n\nimport central.generate_hcl_config as generate_hcl_config\nfrom central.habana_model_runner_utils import (HabanaEnvVariables,\n get_canonical_path,\n get_canonical_path_str,\n get_multi_node_config_nodes,\n is_valid_multi_node_config)\nfrom central.multi_node_utils import (generate_mpi_hostfile,\n get_relevant_env_vars,\n print_file_contents,\n run_cmd_as_subprocess, run_per_ip)\n\n\nclass TrainingRunHWConfig():\n def __init__(self, scaleout=False, num_workers_per_hls=1, hls_type=\"HLS1\", kubernetes_run=False, output_filename=\"training_run_log\"):\n self.scaleout = scaleout\n self.num_workers_per_hls = num_workers_per_hls\n self.hls_type = hls_type\n self.kubernetes_run = kubernetes_run\n self.output_filename = output_filename\n self.hls_ips = ''\n self.mpirun_cmd = ''\n\n self.num_workers_total = self.num_workers_per_hls\n\n print(f\"scaleout = {self.scaleout}, num_workers_per_hls = {self.num_workers_per_hls}, hls_type = {self.hls_type}, kubernetes_run={self.kubernetes_run}\")\n\n self.run_config_env_variables = {}\n\n os.makedirs(get_canonical_path(\"$HOME/tmp/\"),\n mode=0o777, exist_ok=True)\n if self.scaleout:\n self.create_multi_worker_setup()\n else:\n self.create_single_worker_setup()\n\n def get_env_vars(self):\n return self.run_config_env_variables\n\n # This handles single-card run configuration\n def create_single_worker_setup(self):\n assert self.scaleout == False, \"Scaleout is set for single-worker run configuration\"\n if self.kubernetes_run:\n return\n\n print(f\"{self.__class__.__name__} create_single_worker_setup(): self.mpirun_cmd = {self.mpirun_cmd}\")\n\n if os.environ.get('MULTI_HLS_IPS'):\n print(\n f\"Warning: In non-scaleout scenario, variable MULTI_HLS_IPS==\\'{os.environ.get('MULTI_HLS_IPS')}\\' has no effect.\")\n\n # This handles Single-HLS and Multi-HLS scaleout run configurations\n def create_multi_worker_setup(self):\n if not self.kubernetes_run:\n assert self.scaleout and self.num_workers_per_hls > 1, \"Scaleout run requires at least 2 workers\"\n tmp_dir = get_canonical_path(\"$HOME/tmp/\")\n run_per_ip(f\"mkdir -p {str(tmp_dir)}\",\n ['MULTI_HLS_IPS', 'PYTHONPATH'], False, self.kubernetes_run)\n hcl_config_path = ''\n\n if self.kubernetes_run:\n hcl_config_path = get_canonical_path(\n os.environ.get('HCL_CONFIG_PATH'))\n print(\n f\"HCL_CONFIG_PATH = {str(os.environ.get('HCL_CONFIG_PATH'))}\")\n print(f\"hcl_config_path = {hcl_config_path} ->\")\n print_file_contents(hcl_config_path)\n return\n\n print(f\"MULTI_HLS_IPS={os.environ.get('MULTI_HLS_IPS')}\")\n\n output_file_name = str(tmp_dir.joinpath(self.output_filename))\n self.mpirun_cmd = self.create_mpi_cmdline(output_file_name)\n\n if is_valid_multi_node_config():\n hcl_config_path = self.create_multi_hls_setup(tmp_dir)\n else:\n hcl_config_path = self.create_single_hls_setup(tmp_dir)\n\n print(f\"HCL_CONFIG_PATH = {str(os.environ.get('HCL_CONFIG_PATH'))}\")\n print(f\"hcl_config_path = {hcl_config_path} ->\")\n print_file_contents(hcl_config_path)\n\n print(f\"{self.__class__.__name__} create_multi_worker_setup(): self.mpirun_cmd = {self.mpirun_cmd}\")\n\n def create_mpi_cmdline(self, output_file_name):\n # OpenMPI process bind resource type.\n mpi_map_by = \"socket\"\n\n # Get lscpu\n cmd = 'lscpu | grep \\\"CPU(s):\\\"'\n lscpu_output = []\n with subprocess.Popen(cmd, shell=True, executable='/bin/bash', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env={\"LD_PRELOAD\": \"\"}) as proc:\n lscpu_output = proc.stdout.read()\n # Determine the optimal value of resources per process of OpenMPI binding based on local lscpu.\n if mpi_map_by == \"socket\":\n mpi_map_by_pe = int(lscpu_output.split()[\n 1])//self.num_workers_per_hls//2\n elif mpi_map_by == \"slot\":\n mpi_map_by_pe = int(lscpu_output.split()[\n 1])//self.num_workers_per_hls\n else:\n raise Exception(\"mpi_map_by must be either 'socket' or 'slot'.\")\n\n print(f\"mpi_map_by_pe = {mpi_map_by_pe}\")\n mpi_cmd = \"mpirun\"\n mpi_cmd += \" --allow-run-as-root\"\n mpi_cmd += f\" --tag-output --merge-stderr-to-stdout --output-filename {output_file_name}\"\n\n if mpi_map_by_pe > 0:\n mpi_cmd += f\" --bind-to core --map-by {mpi_map_by}:PE={mpi_map_by_pe}\"\n return mpi_cmd\n\n # This handles Single-HLS run configuration\n def create_single_hls_setup(self, tmp_dir):\n #\n # Single-HLS Mode\n #\n print(f\"self.num_workers_total = {self.num_workers_total}\")\n hcl_config_path = generate_hcl_config.generate_hcl_config_r(\n str(tmp_dir), self.num_workers_per_hls, self.hls_type)\n print(\n f\"---------- Single-HLS ({self.num_workers_per_hls}-cards): HCL_CONFIG_PATH = {str(os.environ.get('HCL_CONFIG_PATH'))}\")\n self.mpirun_cmd += f\" -np {self.num_workers_per_hls}\"\n return hcl_config_path\n\n def deduce_ip_addr(self):\n \"\"\" Deduces the IP address of the host running this process used for connecting to the other machines.\n \"\"\"\n # The first method: deduce using a default network interface.\n try:\n dummy_ip_endpoint = (\"4.3.2.1\", 80)\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect(dummy_ip_endpoint)\n return s.getsockname()[0]\n except Exception:\n pass\n\n # The second method: Call 'hostname -I' and take the first IP address (unreliable in all cases).\n return subprocess.check_output([\"hostname\", \"-I\"], encoding=\"ascii\").split(\" \")[0].strip()\n\n # This handles Multi-HLS run configuration, driven by the MULTI_HLS_IPS environment variable\n def create_multi_hls_setup(self, tmp_dir):\n #\n # Multi-HLS Mode\n #\n if 'MPI_TCP_INCLUDE' in os.environ:\n mpi_tcp_include = os.environ['MPI_TCP_INCLUDE']\n print(\n f\"Setting mpi_tcp_include to '{mpi_tcp_include}' (provided with MPI_TCP_INCLUDE env var)\")\n else:\n mpi_tcp_include = self.deduce_ip_addr() + \"/24\"\n print(\n f\"Setting mpi_tcp_include to '{mpi_tcp_include}' (deduced automatically)\")\n\n gen_hcl_path = Path(__file__).parent.joinpath('generate_hcl_config.py')\n # Create HCL config on each remote IP.\n run_per_ip(f\"{sys.executable} {str(gen_hcl_path)} {str(tmp_dir)} {self.num_workers_per_hls} {self.hls_type}\", [\n 'MULTI_HLS_IPS', 'PYTHONPATH', 'HOROVOD_HIERARCHICAL_ALLREDUCE'], False)\n\n # Set HCL_CONFIG_PATH in this script, so it can be propagated in self.mpirun_cmd to remote IPs.\n hcl_config_path = generate_hcl_config.generate_hcl_config_r(\n str(tmp_dir), self.num_workers_per_hls, self.hls_type)\n\n multi_hls_nodes = get_multi_node_config_nodes()\n self.num_workers_total = len(\n multi_hls_nodes) * self.num_workers_per_hls\n print(f\"self.num_workers_total = {self.num_workers_total}\")\n print(\n f\"++++++++++ Multi-HLS ({self.num_workers_total}-cards): HCL_CONFIG_PATH = {str(os.environ.get('HCL_CONFIG_PATH'))}\")\n\n mpi_hostfile_path = generate_mpi_hostfile(\n str(tmp_dir), self.num_workers_per_hls)\n assert mpi_hostfile_path != '', \"Don\\'t have a valid mpi_hostfile_path for MULTI_HLS_IPS scenario\"\n print(f\"mpi_hostfile_path = {mpi_hostfile_path} ->\")\n print_file_contents(mpi_hostfile_path)\n\n self.mpirun_cmd += f\" -np {self.num_workers_total}\"\n if os.environ.get('DOCKER_SSHD_PORT'):\n portnum = os.environ.get('DOCKER_SSHD_PORT')\n else:\n portnum = 3022\n self.mpirun_cmd += f\" --mca plm_rsh_args -p{portnum}\"\n self.mpirun_cmd += f\" --mca btl_tcp_if_include {mpi_tcp_include}\"\n self.mpirun_cmd += f\" -hostfile {mpi_hostfile_path}\"\n self.mpirun_cmd += \" --prefix $MPI_ROOT\"\n\n for env_var in get_relevant_env_vars():\n self.mpirun_cmd += f\" -x {env_var}={shlex.quote(os.environ[env_var])}\"\n # Note that =value above in not necessary, but provides a vital information when presented this way in the log file.\n\n return hcl_config_path\n","sub_path":"central/training_run_config.py","file_name":"training_run_config.py","file_ext":"py","file_size_in_byte":9388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"258269492","text":"import pymongo\n\npath = r'F:\\Plan-for-combating-master\\week2\\2_1\\2_1code_of_video\\walden.txt'\nclient = pymongo.MongoClient('localhost',27017)\nwalden = client['walden']\nsheet_tab = walden['sheet_tab']\nwith open(path , 'r')as f:\n lines=f.readlines()\n for index,line in enumerate(lines):\n data = {\n 'index': index,\n 'line' :line,\n 'words': len(line.split())\n }\n sheet_tab.insert_one(data)\n\nfor item in sheet_tab.find({'words':0}):\n print (item)","sub_path":"mingodb.py","file_name":"mingodb.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"273199155","text":"#!/usr/bin/env python3\n\n\nimport os\nfrom base64 import b64decode\n\nfrom flask import Flask, jsonify, request, abort, Response, make_response\nfrom nacl import signing\nfrom nacl import encoding\n\nclass SVCNode:\n \"\"\"\n info on a service node\n \"\"\"\n def __init__(self):\n self._seed = os.urandom(32)\n self._ed25519_secret = signing.SigningKey(self._seed)\n\n def seed(self):\n \"\"\"\n return hex seed\n \"\"\"\n return self._ed25519_secret.encode(encoding.HexEncoder).decode('ascii') + self.pubkey()\n\n def pubkey(self):\n \"\"\"\n make hex public key\n \"\"\"\n return self._ed25519_secret.verify_key.encode(encoding.HexEncoder).decode('ascii')\n\n def toJson(self):\n \"\"\"\n make the snode a json object for jsonrpc\n \"\"\"\n return {'pubkey_ed25519': self.pubkey(), 'active': True, 'funded': True}\n\nclass MockServer:\n\n def __init__(self, numServiceNodes):\n self.app = Flask('lokid-rpc-mock')\n #self.app.config['SECRET_KEY'] = os.urandom(16)\n # populate service nodes\n self._serviceNodes = dict()\n for n in range(numServiceNodes):\n self.makeSNode(\"svc-%03d\" % n)\n\n self._handlers = {\n 'lokinet_ping': self._lokinet_ping,\n 'get_n_service_nodes' : self._get_n_service_nodes,\n 'get_service_node_privkey' : self._get_service_node_privkey\n }\n #digest = HTTPDigestAuth(realm='lokid')\n \n @self.app.route('/json_rpc', methods=[\"POST\"])\n def _jsonRPC():\n j = request.get_json()\n method = j['method']\n snode = None\n if 'authorization' in request.headers:\n user = b64decode(request.headers['authorization'][6:].encode('ascii')).decode('ascii').split(':')[0]\n self.app.logger.error(user)\n if len(user) > 0:\n snode = self._serviceNodes[user]\n result = self._handlers[method](snode)\n if result:\n resp = {'jsonrpc': '2.0', 'id': j['id'], 'result': result}\n return jsonify(resp)\n else:\n r = make_response('nope', 401)\n r.headers['www-authenticate'] = 'basic'\n return r\n def after(req):\n req.content_type = \"application/json\"\n return req\n self.app.after_request(after)\n\n def _get_n_service_nodes(self, our_snode):\n return {\n 'block_hash' : 'mock',\n 'service_node_states' : self.getSNodeList()\n }\n \n def _get_service_node_privkey(self, our_snode):\n if our_snode is None:\n return None\n return {\n 'service_node_ed25519_privkey': our_snode.seed()\n }\n\n def _lokinet_ping(self, snode):\n return {\n 'status' : \"OK\"\n }\n \n def run(self):\n \"\"\"\n run mainloop and serve jsonrpc server\n \"\"\"\n self.app.run()\n \n def makeSNode(self, name):\n \"\"\"\n make service node entry\n \"\"\"\n self._serviceNodes[name] = SVCNode()\n\n\n def getSNodeList(self):\n l = list()\n for name in self._serviceNodes:\n l.append(self._serviceNodes[name].toJson())\n return l\n \n\ndef main():\n import sys\n serv = MockServer(int(sys.argv[1]))\n serv.run()\n \nif __name__ == '__main__':\n main()\n","sub_path":"contrib/testnet/lokid.py","file_name":"lokid.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"635001253","text":"import pandas as pd\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport matplotlib.pyplot as plt\nimport time\nimport math\n\n# Step1: Load and setup training dataset\n\n# import the data from Excel File using pandas\ndata = pd.read_excel('savedata.xlsx', header=None)\n\n# drop first column\ndata.drop(data.columns[0], axis = 1, inplace = True)\ndata = data.drop(data.index[[0]])\n\n# try shuffle data\ndata = data.sample(frac=1).reset_index(drop=True)\n#print(data)\n\n# randomly split data into training set (80%) and testing set (20%)\nmsk = np.random.rand(len(data)) < 0.8\ntrain_data = data[msk]\ntest_data = data[~msk]\n\nn_features = train_data.shape[1] - 1\n\n# split training data into input and target\n# the first one is target, other columns are features\ntrain_input = train_data.iloc[:, 1:21]\ntrain_target = train_data.iloc[:, 0] - 1\n\n# split testing data into input and train_target\n# the first column is target, other columns are features\ntest_input = test_data.iloc[:, 1:21]\ntest_target = test_data.iloc[:, 0] - 1\n\n# create Tensors to hold inputs and outputs, and wrap them in Variables,\n# as Torch only trains neural network on Variables\nX = torch.Tensor(train_input.values).float()\nY = torch.Tensor(train_target.values).long()\n\n\"\"\"\nStep 2: Define a neural network\n\nHere we build a neural network with one hidden layer.\n\nThe network will be trained with Stochastic Gradient Descent (SGD) as an\noptimiser, that will hold the current state and will update the parameters\nbased on the computed gradients.\n\nIts performance will be evaluated using cross-entropy.\n\"\"\"\n\n# define the number of inputs, classes, training epochs, and learning rate\ninput_neurons = 20\nhidden_neurons = 8\noutput_neurons = 2\nlearning_rate = 0.01\nnum_epochs = 1000\n\n\n# define a customised neural network structure\nclass ThreeLayerNet(torch.nn.Module):\n\n def __init__(self, n_input, n_hidden, n_output):\n super(ThreeLayerNet, self).__init__()\n # define linear hidden layer output\n self.hidden = torch.nn.Linear(n_input, n_hidden)\n # define linear output layer output\n self.out = torch.nn.Linear(n_hidden, n_output)\n\n\n\n def forward(self, x):\n\n # get hidden layer input\n h_input = self.hidden(x)\n # define activation function for hidden layer\n h_output = torch.sigmoid(h_input)\n # get output layer output\n y_pred = self.out(h_output)\n\n return y_pred\n\n# define a neural network using the customised structure\nnet = ThreeLayerNet(input_neurons, hidden_neurons, output_neurons)\n\n# define loss function\nloss_func = torch.nn.CrossEntropyLoss()\n\n# define optimiser\noptimiser = torch.optim.Adam(net.parameters(), lr=learning_rate)\n\n# store all losses for visualisation\nall_losses = []\n\n\"\"\"\nStep 5 : Test the dataset after applying the technique\n\"\"\"\n# After calculate angle, test the accuracy of the network based on the network reduction technique\n# Each time during the test, I should modify the parameters based on the previous results \nnet.out.weight.data[:,7] += net.out.weight.data[:,1]\nnet.out.weight.data[:,7] += net.out.weight.data[:,2]\nnet.out.weight.data[:,7] += net.out.weight.data[:,5]\nnet.out.weight.data[:,1] = 0\nnet.out.weight.data[:,2] = 0\nnet.out.weight.data[:,5] = 0\n\nX_test = torch.Tensor(test_input.values).float()\nY_test = torch.Tensor(test_target.values).long()\n\n# test the neural network using testing data\n# It is actually performing a forward pass computation of predicted y\n# by passing x to the model.\n# Here, Y_pred_test contains three columns, where the index of the\n# max column indicates the class of the instance\nY_pred_test = net(X_test)\n\n# get prediction\n# convert three-column predicted Y values to one column for comparison\n_, predicted_test = torch.max(Y_pred_test, 1)\n\n# calculate accuracy\ntotal_test = predicted_test.size(0)\ncorrect_test = sum(predicted_test.data.numpy() == Y_test.data.numpy())\n\nprint('Testing Accuracy after applying the technique: %.2f %%' % (100 * correct_test / total_test))\n\n\"\"\"\nEvaluating the Results\n\nTo see how well the network performs on different categories, we will\ncreate a confusion matrix\n\n\"\"\"\n\nconfusion_test = torch.zeros(output_neurons, output_neurons)\n\nfor i in range(test_data.shape[0]):\n actual_class = Y_test.data[i]\n predicted_class = predicted_test.data[i]\n\n confusion_test[actual_class][predicted_class] += 1\n\nprint('')\nprint('Confusion matrix for testing:')\nprint(confusion_test)\n","sub_path":"Project1/code_v1/technique.py","file_name":"technique.py","file_ext":"py","file_size_in_byte":4469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"345007844","text":"import tensorflow as tf\nimport numpy as np\n\n\ndef _upsample(nn, scaling=2):\n\t\"\"\"\n\tUpsamples a tensor\n\t:param nn: TF tensor\n\t:param scaling: Scaling factor\n\t:return: TF Tensor\n\t\"\"\"\n\t_, height, width, _ = nn.shape\n\tnew_shape = np.array([height*scaling, width*scaling]).astype(np.int32)\n\treturn tf.image.resize_bilinear(nn, size=new_shape)\n\n\ndef _batch_normalization(nn, bIsTraining, axis=3, momentum=0.1, epsilon=1e-5):\n\t\"\"\"\n\tNormalizes features\n\t:param nn: TF tensor\n\t:param axis: What to normalize\n\t:param momentum: Has something to do with moving averages. Read about Batch Normalization\n\t:param epsilon: The value to add to the denonmiator to avoid division by zero\n\t:return: TF tensor\n\t\"\"\"\n\treturn tf.layers.batch_normalization(nn, axis=axis, momentum=momentum, epsilon=epsilon, training=bIsTraining)\n\n\ndef _conv2d(nn, filters, kernel_size, strides=1, padding=\"valid\"):\n\t\"\"\"\n\tAdds padding and convolves.\n\t:param nn: TF tensor\n\t:param filters: Number of filters\n\t:param kernel_size: Size of kernel\n\t:param strides: Strides\n\t:param padding: Type of padding\n\t:return: TF tensor\n\t\"\"\"\n\tnum_pad = int((kernel_size-1)/2)\n\tif num_pad != 0:\n\t\tpad_param = [[0, 0], [num_pad, num_pad], [num_pad, num_pad], [0, 0]] # Channels first\n\t\tnn = tf.pad(tensor=nn, paddings=pad_param, mode=\"constant\")\n\treturn tf.layers.conv2d(inputs=nn, filters=filters, kernel_size=kernel_size, padding=padding, strides=strides,\n\t\t\t\t\t\t\tuse_bias=True)\n\n\ndef _helper_build_deep_prior_model(i, input_tensor, bIsTraining, num_channels_down, num_channels_up, num_channels_skip,\n\t\t\t\t\t\t\t\t kernels_size_down, kernels_size_up, kernels_size_skip):\n\tskip = None\n\tif num_channels_skip[i] != 0: # START 'Skip' connection. Create a connection from here\n\t\tskip = _conv2d(nn=input_tensor, filters=num_channels_skip[i], kernel_size=kernels_size_skip[i])\n\t\tskip = _batch_normalization(skip, bIsTraining)\n\t\tskip = tf.nn.leaky_relu(skip)\n\n\tnn = _conv2d(nn=input_tensor, filters=num_channels_down[i], kernel_size=kernels_size_down[i], strides=2)\n\tnn = _batch_normalization(nn, bIsTraining)\n\tnn = tf.nn.leaky_relu(nn)\n\n\tnn = _conv2d(nn=nn, filters=num_channels_down[i], kernel_size=kernels_size_down[i])\n\tnn = _batch_normalization(nn, bIsTraining)\n\tnn = tf.nn.leaky_relu(nn)\n\n\tnn = _batch_normalization(nn, bIsTraining)\n\n\t# Recursive Call: GO DEEPER! (If not the deepest..)\n\tif i < len(num_channels_down) - 1:\n\t\tnn = _helper_build_deep_prior_model(i + 1, nn, bIsTraining, num_channels_down, num_channels_up, num_channels_skip,\n\t\t\t\t\t\t\t\t\t\t\tkernels_size_down, kernels_size_up, kernels_size_skip)\n\n\tnn = _upsample(nn, scaling=2)\n\n\tnn = _conv2d(nn=nn, filters=num_channels_up[i], kernel_size=kernels_size_up[i])\n\tnn = _batch_normalization(nn, bIsTraining)\n\tnn = tf.nn.leaky_relu(nn)\n\n\tif num_channels_skip[i] != 0: # END 'Skip' Connection. Create a connection to here.\n\t\tnn = tf.concat([nn, skip], axis=3) # 'skip' was assigned.\n\n\tnn = _conv2d(nn=nn, filters=num_channels_up[i], kernel_size=kernels_size_up[i])\n\tnn = _batch_normalization(nn, bIsTraining)\n\tnn = tf.nn.leaky_relu(nn)\n\n\treturn nn\n\n\ndef build_deep_prior_model(z, bIsTraining, num_output_channels,\n\t\t\t\t\t\t num_channels_down, num_channels_up, num_channels_skip,\n\t\t\t\t\t\t kernels_size_down, kernels_size_up, kernels_size_skip):\n\t\"\"\"\n\tBuilds the Deep Prior Model. The Architecture is 'Encoder-Decoder' with Skip connections. It's an Hourglass.\n\n\tNOTE: num_channels_up/down/skip and kernels_size_down/up must be of equal length.\n\t:param num_output_channels: Integer - The number of channels in the output\n\t:param num_channels_down: List\\Array - The number of filters in each convolution layer while going down into the net\n\t:param num_channels_up: List\\Array - The number of filters in each convolution layer while going up into the net\n\t:param num_channels_skip: List\\Array - The number of filters in each 'skip' block's convolution layers\n\t:param kernels_size_down: List\\Array - The kernel size in each convolution layer going down\n\t:param kernels_size_up: List\\Array - The kernel size in each convolution layer going up\n\t:return: Keras Model\n\t\"\"\"\n\tassert len(num_channels_down) == len(num_channels_up) == len(num_channels_skip) == \\\n\t\t len(kernels_size_down) == len(kernels_size_up) == len(kernels_size_skip)\n\n\tnn = _helper_build_deep_prior_model(0, z, bIsTraining, num_channels_down, num_channels_up, num_channels_skip, kernels_size_down,\n\t\t\t\t\t\t\t\t\t\tkernels_size_up, kernels_size_skip)\n\n\tnn = _conv2d(nn=nn, filters=num_output_channels, kernel_size=kernels_size_up[0])\n\tnn = tf.sigmoid(nn, name=\"output\")\n\treturn nn\n\n\ndef get_loss_op(y_true, y_pred):\n\tmse_loss = tf.losses.mean_squared_error(labels=y_true, predictions=y_pred)\n\treturn mse_loss\n\n\ndef get_train_op(loss_op, learning_rate, global_step):\n\topt = tf.train.AdamOptimizer(beta2=0.9, learning_rate=learning_rate)\n\tupdate_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n\twith tf.control_dependencies(update_ops):\n\t\tcompute_grads = opt.compute_gradients(loss_op)\n\t\tapply_gradients_op = opt.apply_gradients(compute_grads, global_step=global_step)\n\treturn apply_gradients_op\n\n\ndef get_input(z, img, noise_cons, batch_size=1):\n\twith tf.name_scope(\"Input\"):\n\t\tz_tf = tf.constant(z, dtype=tf.float32)\n\t\timg_tf = tf.constant(img, dtype=tf.float32)\n\n\t\tzs_dataset = tf.data.Dataset.from_tensors(z_tf)\n\t\timgs_dataset = tf.data.Dataset.from_tensors(img_tf)\n\n\t\tzs_dataset = zs_dataset.map(lambda x: x + noise_cons*tf.random_normal(z_tf.shape, dtype=tf.float32))\n\n\t\tdataset = tf.data.Dataset.zip((zs_dataset, imgs_dataset))\n\t\tdataset = dataset.repeat()\n\n\t\titerator = dataset.make_initializable_iterator()\n\n\t\tZ, IMG = iterator.get_next()\n\t\treturn Z, IMG, iterator.initializer\n","sub_path":"deep-prior-restore/nn_model.py","file_name":"nn_model.py","file_ext":"py","file_size_in_byte":5631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"468502097","text":"import threading\r\nimport time\r\n\r\n\r\nclass MyThread(threading.Thread):\r\n def __init__(self, name=None, args=(), kwargs=None, *, daemon=None):\r\n super().__init__(group=None, target=self.worker, name=name, args=args, kwargs=kwargs, daemon=daemon)\r\n self.start_time = time.perf_counter()\r\n\r\n # def run(self):\r\n # try:\r\n # if self._target:\r\n # self._target(*self._args, **self._kwargs)\r\n # finally:\r\n # # Avoid a refcycle if the thread is running a function with\r\n # # an argument that has a member that points to the thread.\r\n # del self._target, self._args, self._kwargs\r\n\r\n def worker(self):\r\n for iteration in range(10):\r\n time.sleep(1)\r\n print(f\"worker thread is working for {round(time.perf_counter() - self.start_time)} sec.\")\r\n print(f\"worker thread is done after {round(time.perf_counter() - self.start_time)} sec.\")\r\n\r\n\r\nmt = MyThread()\r\nmt.start()\r\n\r\nmt.join(3.4)\r\n\r\nprint(\"done\")","sub_path":"built_in/threading/thread_subclass.py","file_name":"thread_subclass.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"231000022","text":"\"\"\"\nImplementation of math operations on Array objects.\n\"\"\"\n\nfrom __future__ import print_function, absolute_import, division\n\nimport math\n\nfrom llvmlite import ir\nimport llvmlite.llvmpy.core as lc\nfrom llvmlite.llvmpy.core import Constant, Type\n\nimport numpy\nfrom numba import types, cgutils, typing\nfrom numba.numpy_support import as_dtype\nfrom numba.numpy_support import version as numpy_version\nfrom numba.targets.imputils import (lower_builtin, impl_ret_borrowed,\n impl_ret_new_ref, impl_ret_untracked)\nfrom numba.typing import signature\nfrom .arrayobj import make_array, load_item, store_item, _empty_nd_impl\n\n\n#----------------------------------------------------------------------------\n# Stats and aggregates\n\n@lower_builtin(numpy.sum, types.Array)\n@lower_builtin(\"array.sum\", types.Array)\ndef array_sum(context, builder, sig, args):\n zero = sig.return_type(0)\n\n def array_sum_impl(arr):\n c = zero\n for v in arr.flat:\n c += v\n return c\n\n res = context.compile_internal(builder, array_sum_impl, sig, args,\n locals=dict(c=sig.return_type))\n return impl_ret_borrowed(context, builder, sig.return_type, res)\n\n@lower_builtin(numpy.prod, types.Array)\n@lower_builtin(\"array.prod\", types.Array)\ndef array_prod(context, builder, sig, args):\n\n def array_prod_impl(arr):\n c = 1\n for v in arr.flat:\n c *= v\n return c\n\n res = context.compile_internal(builder, array_prod_impl, sig, args,\n locals=dict(c=sig.return_type))\n return impl_ret_borrowed(context, builder, sig.return_type, res)\n\n@lower_builtin(numpy.cumsum, types.Array)\n@lower_builtin(\"array.cumsum\", types.Array)\ndef array_cumsum(context, builder, sig, args):\n scalar_dtype = sig.return_type.dtype\n dtype = as_dtype(scalar_dtype)\n zero = scalar_dtype(0)\n\n def array_cumsum_impl(arr):\n size = 1\n for i in arr.shape:\n size = size * i\n out = numpy.empty(size, dtype)\n c = zero\n for idx, v in enumerate(arr.flat):\n c += v\n out[idx] = c\n return out\n\n res = context.compile_internal(builder, array_cumsum_impl, sig, args,\n locals=dict(c=scalar_dtype))\n return impl_ret_new_ref(context, builder, sig.return_type, res)\n\n\n\n@lower_builtin(numpy.cumprod, types.Array)\n@lower_builtin(\"array.cumprod\", types.Array)\ndef array_cumprod(context, builder, sig, args):\n scalar_dtype = sig.return_type.dtype\n dtype = as_dtype(scalar_dtype)\n\n def array_cumprod_impl(arr):\n size = 1\n for i in arr.shape:\n size = size * i\n out = numpy.empty(size, dtype)\n c = 1\n for idx, v in enumerate(arr.flat):\n c *= v\n out[idx] = c\n return out\n\n res = context.compile_internal(builder, array_cumprod_impl, sig, args,\n locals=dict(c=scalar_dtype))\n return impl_ret_new_ref(context, builder, sig.return_type, res)\n\n@lower_builtin(numpy.mean, types.Array)\n@lower_builtin(\"array.mean\", types.Array)\ndef array_mean(context, builder, sig, args):\n zero = sig.return_type(0)\n\n def array_mean_impl(arr):\n # Can't use the naive `arr.sum() / arr.size`, as it would return\n # a wrong result on integer sum overflow.\n c = zero\n for v in arr.flat:\n c += v\n return c / arr.size\n\n res = context.compile_internal(builder, array_mean_impl, sig, args,\n locals=dict(c=sig.return_type))\n return impl_ret_untracked(context, builder, sig.return_type, res)\n\n@lower_builtin(numpy.var, types.Array)\n@lower_builtin(\"array.var\", types.Array)\ndef array_var(context, builder, sig, args):\n def array_var_impl(arry):\n # Compute the mean\n m = arry.mean()\n\n # Compute the sum of square diffs\n ssd = 0\n for v in arry.flat:\n ssd += (v - m) ** 2\n return ssd / arry.size\n\n res = context.compile_internal(builder, array_var_impl, sig, args)\n return impl_ret_untracked(context, builder, sig.return_type, res)\n\n\n@lower_builtin(numpy.std, types.Array)\n@lower_builtin(\"array.std\", types.Array)\ndef array_std(context, builder, sig, args):\n def array_std_impl(arry):\n return arry.var() ** 0.5\n res = context.compile_internal(builder, array_std_impl, sig, args)\n return impl_ret_untracked(context, builder, sig.return_type, res)\n\n\n@lower_builtin(numpy.min, types.Array)\n@lower_builtin(\"array.min\", types.Array)\ndef array_min(context, builder, sig, args):\n ty = sig.args[0].dtype\n if isinstance(ty, (types.NPDatetime, types.NPTimedelta)):\n # NaT is smaller than every other value, but it is\n # ignored as far as min() is concerned.\n nat = ty('NaT')\n\n def array_min_impl(arry):\n min_value = nat\n it = arry.flat\n for v in it:\n if v != nat:\n min_value = v\n break\n\n for v in it:\n if v != nat and v < min_value:\n min_value = v\n return min_value\n\n else:\n def array_min_impl(arry):\n for v in arry.flat:\n min_value = v\n break\n\n for v in arry.flat:\n if v < min_value:\n min_value = v\n return min_value\n res = context.compile_internal(builder, array_min_impl, sig, args)\n return impl_ret_borrowed(context, builder, sig.return_type, res)\n\n\n@lower_builtin(numpy.max, types.Array)\n@lower_builtin(\"array.max\", types.Array)\ndef array_max(context, builder, sig, args):\n def array_max_impl(arry):\n for v in arry.flat:\n max_value = v\n break\n\n for v in arry.flat:\n if v > max_value:\n max_value = v\n return max_value\n res = context.compile_internal(builder, array_max_impl, sig, args)\n return impl_ret_borrowed(context, builder, sig.return_type, res)\n\n\n@lower_builtin(numpy.argmin, types.Array)\n@lower_builtin(\"array.argmin\", types.Array)\ndef array_argmin(context, builder, sig, args):\n ty = sig.args[0].dtype\n # NOTE: Under Numpy < 1.10, argmin() is inconsistent with min() on NaT values:\n # https://github.com/numpy/numpy/issues/6030\n\n if (numpy_version >= (1, 10) and\n isinstance(ty, (types.NPDatetime, types.NPTimedelta))):\n # NaT is smaller than every other value, but it is\n # ignored as far as argmin() is concerned.\n nat = ty('NaT')\n\n def array_argmin_impl(arry):\n min_value = nat\n min_idx = 0\n it = arry.flat\n idx = 0\n for v in it:\n if v != nat:\n min_value = v\n min_idx = idx\n idx += 1\n break\n idx += 1\n\n for v in it:\n if v != nat and v < min_value:\n min_value = v\n min_idx = idx\n idx += 1\n return min_idx\n\n else:\n def array_argmin_impl(arry):\n for v in arry.flat:\n min_value = v\n min_idx = 0\n break\n\n idx = 0\n for v in arry.flat:\n if v < min_value:\n min_value = v\n min_idx = idx\n idx += 1\n return min_idx\n res = context.compile_internal(builder, array_argmin_impl, sig, args)\n return impl_ret_untracked(context, builder, sig.return_type, res)\n\n\n@lower_builtin(numpy.argmax, types.Array)\n@lower_builtin(\"array.argmax\", types.Array)\ndef array_argmax(context, builder, sig, args):\n def array_argmax_impl(arry):\n for v in arry.flat:\n max_value = v\n max_idx = 0\n break\n\n idx = 0\n for v in arry.flat:\n if v > max_value:\n max_value = v\n max_idx = idx\n idx += 1\n return max_idx\n res = context.compile_internal(builder, array_argmax_impl, sig, args)\n return impl_ret_untracked(context, builder, sig.return_type, res)\n\n\n@lower_builtin(numpy.median, types.Array)\ndef array_median(context, builder, sig, args):\n\n def partition(A, low, high):\n mid = (low+high) // 2\n # median of three {low, middle, high}\n LM = A[low] <= A[mid]\n MH = A[mid] <= A[high]\n LH = A[low] <= A[high]\n\n if LM == MH:\n median3 = mid\n elif LH != LM:\n median3 = low\n else:\n median3 = high\n\n # choose median3 as the pivot\n A[high], A[median3] = A[median3], A[high]\n\n x = A[high]\n i = low\n for j in range(low, high):\n if A[j] <= x:\n A[i], A[j] = A[j], A[i]\n i += 1\n A[i], A[high] = A[high], A[i]\n return i\n\n sig_partition = typing.signature(types.intp, *(sig.args[0], types.intp, types.intp))\n _partition = context.compile_subroutine(builder, partition, sig_partition)\n\n def select(arry, k):\n n = arry.shape[0]\n # XXX: assuming flat array till array.flatten is implemented\n # temp_arry = arry.flatten()\n temp_arry = arry.copy()\n high = n-1\n low = 0\n # NOTE: high is inclusive\n i = _partition(temp_arry, low, high)\n while i != k:\n if i < k:\n low = i+1\n i = _partition(temp_arry, low, high)\n else:\n high = i-1\n i = _partition(temp_arry, low, high)\n return temp_arry[k]\n\n sig_select = typing.signature(sig.args[0].dtype, *(sig.args[0], types.intp))\n _select = context.compile_subroutine(builder, select, sig_select)\n\n def median(arry):\n n = arry.shape[0]\n if n % 2 == 0:\n return (_select(arry, n//2 - 1) + _select(arry, n//2))/2\n else:\n return _select(arry, n//2)\n\n res = context.compile_internal(builder, median, sig, args)\n return impl_ret_untracked(context, builder, sig.return_type, res)\n\n\n#----------------------------------------------------------------------------\n# Element-wise computations\n\ndef _np_round_intrinsic(tp):\n # np.round() always rounds half to even\n return \"llvm.rint.f%d\" % (tp.bitwidth,)\n\ndef _np_round_float(context, builder, tp, val):\n llty = context.get_value_type(tp)\n module = builder.module\n fnty = lc.Type.function(llty, [llty])\n fn = module.get_or_insert_function(fnty, name=_np_round_intrinsic(tp))\n return builder.call(fn, (val,))\n\n@lower_builtin(numpy.round, types.Float)\ndef scalar_round_unary(context, builder, sig, args):\n res = _np_round_float(context, builder, sig.args[0], args[0])\n return impl_ret_untracked(context, builder, sig.return_type, res)\n\n@lower_builtin(numpy.round, types.Integer)\ndef scalar_round_unary(context, builder, sig, args):\n res = args[0]\n return impl_ret_untracked(context, builder, sig.return_type, res)\n\n@lower_builtin(numpy.round, types.Complex)\ndef scalar_round_unary_complex(context, builder, sig, args):\n fltty = sig.args[0].underlying_float\n cplx_cls = context.make_complex(sig.args[0])\n z = cplx_cls(context, builder, args[0])\n z.real = _np_round_float(context, builder, fltty, z.real)\n z.imag = _np_round_float(context, builder, fltty, z.imag)\n res = z._getvalue()\n return impl_ret_untracked(context, builder, sig.return_type, res)\n\n@lower_builtin(numpy.round, types.Float, types.Integer)\n@lower_builtin(numpy.round, types.Integer, types.Integer)\ndef scalar_round_binary_float(context, builder, sig, args):\n def round_ndigits(x, ndigits):\n if math.isinf(x) or math.isnan(x):\n return x\n\n # NOTE: this is CPython's algorithm, but perhaps this is overkill\n # when emulating Numpy's behaviour.\n if ndigits >= 0:\n if ndigits > 22:\n # pow1 and pow2 are each safe from overflow, but\n # pow1*pow2 ~= pow(10.0, ndigits) might overflow.\n pow1 = 10.0 ** (ndigits - 22)\n pow2 = 1e22\n else:\n pow1 = 10.0 ** ndigits\n pow2 = 1.0\n y = (x * pow1) * pow2\n if math.isinf(y):\n return x\n return (numpy.round(y) / pow2) / pow1\n\n else:\n pow1 = 10.0 ** (-ndigits)\n y = x / pow1\n return numpy.round(y) * pow1\n\n res = context.compile_internal(builder, round_ndigits, sig, args)\n return impl_ret_untracked(context, builder, sig.return_type, res)\n\n@lower_builtin(numpy.round, types.Complex, types.Integer)\ndef scalar_round_binary_complex(context, builder, sig, args):\n def round_ndigits(z, ndigits):\n return complex(numpy.round(z.real, ndigits),\n numpy.round(z.imag, ndigits))\n\n res = context.compile_internal(builder, round_ndigits, sig, args)\n return impl_ret_untracked(context, builder, sig.return_type, res)\n\n\n@lower_builtin(numpy.round, types.Array, types.Integer,\n types.Array)\ndef array_round(context, builder, sig, args):\n def array_round_impl(arr, decimals, out):\n if arr.shape != out.shape:\n raise ValueError(\"invalid output shape\")\n for index, val in numpy.ndenumerate(arr):\n out[index] = numpy.round(val, decimals)\n return out\n\n res = context.compile_internal(builder, array_round_impl, sig, args)\n return impl_ret_new_ref(context, builder, sig.return_type, res)\n\n\n@lower_builtin(numpy.sinc, types.Array)\ndef array_sinc(context, builder, sig, args):\n def array_sinc_impl(arr):\n out = numpy.zeros_like(arr)\n for index, val in numpy.ndenumerate(arr):\n out[index] = numpy.sinc(val)\n return out\n res = context.compile_internal(builder, array_sinc_impl, sig, args)\n return impl_ret_new_ref(context, builder, sig.return_type, res)\n\n@lower_builtin(numpy.sinc, types.Number)\ndef scalar_sinc(context, builder, sig, args):\n scalar_dtype = sig.return_type\n def scalar_sinc_impl(val):\n if val == 0.e0: # to match np impl\n val = 1e-20\n val *= numpy.pi # np sinc is the normalised variant\n return numpy.sin(val)/val\n res = context.compile_internal(builder, scalar_sinc_impl, sig, args,\n locals=dict(c=scalar_dtype))\n return impl_ret_untracked(context, builder, sig.return_type, res)\n\n\n@lower_builtin(numpy.angle, types.Number)\n@lower_builtin(numpy.angle, types.Number, types.Boolean)\ndef scalar_angle_kwarg(context, builder, sig, args):\n deg_mult = sig.return_type(180 / numpy.pi)\n def scalar_angle_impl(val, deg):\n if deg:\n return numpy.arctan2(val.imag, val.real) * deg_mult\n else:\n return numpy.arctan2(val.imag, val.real)\n\n if len(args) == 1:\n args = args + (cgutils.false_bit,)\n sig = signature(sig.return_type, *(sig.args + (types.boolean,)))\n res = context.compile_internal(builder, scalar_angle_impl,\n sig, args)\n return impl_ret_untracked(context, builder, sig.return_type, res)\n\n@lower_builtin(numpy.angle, types.Array)\n@lower_builtin(numpy.angle, types.Array, types.Boolean)\ndef array_angle_kwarg(context, builder, sig, args):\n arg = sig.args[0]\n ret_dtype = sig.return_type.dtype\n\n def array_angle_impl(arr, deg):\n out = numpy.zeros_like(arr, dtype=ret_dtype)\n for index, val in numpy.ndenumerate(arr):\n out[index] = numpy.angle(val, deg)\n return out\n\n if len(args) == 1:\n args = args + (cgutils.false_bit,)\n sig = signature(sig.return_type, *(sig.args + (types.boolean,)))\n\n res = context.compile_internal(builder, array_angle_impl, sig, args)\n return impl_ret_new_ref(context, builder, sig.return_type, res)\n\n\n@lower_builtin(numpy.nonzero, types.Array)\n@lower_builtin(\"array.nonzero\", types.Array)\n@lower_builtin(numpy.where, types.Array)\ndef array_nonzero(context, builder, sig, args):\n aryty = sig.args[0]\n # Return type is a N-tuple of 1D C-contiguous arrays\n retty = sig.return_type\n outaryty = retty.dtype\n ndim = aryty.ndim\n nouts = retty.count\n\n ary = make_array(aryty)(context, builder, args[0])\n shape = cgutils.unpack_tuple(builder, ary.shape)\n strides = cgutils.unpack_tuple(builder, ary.strides)\n data = ary.data\n layout = aryty.layout\n\n # First count the number of non-zero elements\n zero = context.get_constant(types.intp, 0)\n one = context.get_constant(types.intp, 1)\n count = cgutils.alloca_once_value(builder, zero)\n with cgutils.loop_nest(builder, shape, zero.type) as indices:\n ptr = cgutils.get_item_pointer2(builder, data, shape, strides,\n layout, indices)\n val = load_item(context, builder, aryty, ptr)\n nz = context.is_true(builder, aryty.dtype, val)\n with builder.if_then(nz):\n builder.store(builder.add(builder.load(count), one), count)\n\n # Then allocate output arrays of the right size\n out_shape = (builder.load(count),)\n outs = [_empty_nd_impl(context, builder, outaryty, out_shape)._getvalue()\n for i in range(nouts)]\n outarys = [make_array(outaryty)(context, builder, out) for out in outs]\n out_datas = [out.data for out in outarys]\n\n # And fill them up\n index = cgutils.alloca_once_value(builder, zero)\n with cgutils.loop_nest(builder, shape, zero.type) as indices:\n ptr = cgutils.get_item_pointer2(builder, data, shape, strides,\n layout, indices)\n val = load_item(context, builder, aryty, ptr)\n nz = context.is_true(builder, aryty.dtype, val)\n with builder.if_then(nz):\n # Store element indices in output arrays\n if not indices:\n # For a 0-d array, store 0 in the unique output array\n indices = (zero,)\n cur = builder.load(index)\n for i in range(nouts):\n ptr = cgutils.get_item_pointer2(builder, out_datas[i],\n out_shape, (),\n 'C', [cur])\n store_item(context, builder, outaryty, indices[i], ptr)\n builder.store(builder.add(cur, one), index)\n\n tup = context.make_tuple(builder, sig.return_type, outs)\n return impl_ret_new_ref(context, builder, sig.return_type, tup)\n\n\ndef array_where(context, builder, sig, args):\n \"\"\"\n np.where(array, array, array)\n \"\"\"\n layouts = set(a.layout for a in sig.args)\n if layouts == set('C'):\n # Faster implementation for C-contiguous arrays\n def where_impl(cond, x, y):\n shape = cond.shape\n if x.shape != shape or y.shape != shape:\n raise ValueError(\"all inputs should have the same shape\")\n res = numpy.empty_like(x)\n cf = cond.flat\n xf = x.flat\n yf = y.flat\n rf = res.flat\n for i in range(cond.size):\n rf[i] = xf[i] if cf[i] else yf[i]\n return res\n else:\n\n def where_impl(cond, x, y):\n shape = cond.shape\n if x.shape != shape or y.shape != shape:\n raise ValueError(\"all inputs should have the same shape\")\n res = numpy.empty_like(x)\n for idx, c in numpy.ndenumerate(cond):\n res[idx] = x[idx] if c else y[idx]\n return res\n\n res = context.compile_internal(builder, where_impl, sig, args)\n return impl_ret_untracked(context, builder, sig.return_type, res)\n\n\n@lower_builtin(numpy.where, types.Any, types.Any, types.Any)\ndef any_where(context, builder, sig, args):\n cond = sig.args[0]\n if isinstance(cond, types.Array):\n return array_where(context, builder, sig, args)\n\n def scalar_where_impl(cond, x, y):\n \"\"\"\n np.where(scalar, scalar, scalar): return a 0-dim array\n \"\"\"\n scal = x if cond else y\n # This is the equivalent of numpy.full_like(scal, scal),\n # for compatibility with Numpy < 1.8\n arr = numpy.empty_like(scal)\n arr[()] = scal\n return arr\n\n res = context.compile_internal(builder, scalar_where_impl, sig, args)\n return impl_ret_new_ref(context, builder, sig.return_type, res)\n","sub_path":"pkgs/numba-0.24.0-np110py27_0/lib/python2.7/site-packages/numba/targets/arraymath.py","file_name":"arraymath.py","file_ext":"py","file_size_in_byte":20464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"530699766","text":"from interactor.options import Options\nfrom interactor.server import Server\n\nfrom photons_app.errors import UserQuit, ApplicationCancelled, ApplicationStopped\nfrom photons_app.formatter import MergedOptionStringFormatter\nfrom photons_app.actions import an_action\n\nfrom delfick_project.addons import addon_hook\nimport logging\nimport asyncio\n\nlog = logging.getLogger(\"interactor.addon\")\n\n\n@addon_hook(extras=[(\"lifx.photons\", \"core\")])\ndef __lifx__(collector, *args, **kwargs):\n collector.register_converters(\n {\"interactor\": Options.FieldSpec(formatter=MergedOptionStringFormatter)}\n )\n\n\n@an_action(needs_target=True, label=\"Interactor\")\nasync def interactor(collector, target, **kwargs):\n await migrate(collector, extra=\"upgrade head\")\n\n options = collector.configuration[\"interactor\"]\n photons_app = collector.photons_app\n with photons_app.using_graceful_future() as final_future:\n async with target.session() as sender:\n try:\n await Server(final_future).serve(\n options.host, options.port, options, sender, photons_app.cleaners,\n )\n except asyncio.CancelledError:\n raise\n except (UserQuit, ApplicationCancelled, ApplicationStopped):\n pass\n\n\n@an_action(label=\"Interactor\")\nasync def migrate(collector, extra=None, **kwargs):\n \"\"\"\n Migrate a database\n\n This task will use `Alembic `_ to perform\n database migration tasks.\n\n Usage looks like:\n\n ``migrate -- revision --autogenerate -m doing_some_change``\n\n Or\n\n ``migrate -- upgrade head``\n\n Basically, everything after the ``--`` is passed as commandline arguments\n to alembic.\n \"\"\"\n from interactor.database import database\n\n if extra is None:\n extra = collector.configuration[\"photons_app\"].extra\n await database.migrate(collector.configuration[\"interactor\"].database, extra)\n","sub_path":"apps/interactor/interactor/addon.py","file_name":"addon.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"377545125","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport arrow\nfrom scrapy import Request\nimport json\nfrom urllib import parse\nfrom pipeline.utils import spider_error, api_error, translate_request\nimport requests\nfrom pipeline.utils import upload_assets\nfrom scrapy_twitter import TwitterUserShowRequest, to_item\nfrom pipeline.items import TwitterAvatarItem\nfrom scrapy.spidermiddlewares.httperror import HttpError\nfrom twisted.internet.error import DNSLookupError\nfrom twisted.internet.error import TimeoutError, TCPTimedOutError\n\n\nclass TwitterAvatarEmptySpider(scrapy.Spider):\n name = 'twitter_avatar_empty'\n allowed_domains = [\"twitter.com\", '127.0.0.1', '35.176.110.161',\n 'lb-internalapi-1863620718.eu-west-2.elb.amazonaws.com']\n\n def __init__(self, *args, **kwargs):\n super(TwitterAvatarEmptySpider, self).__init__(*args, **kwargs)\n self.host = kwargs.get('host')\n if self.host is None:\n self.host = 'lb-internalapi-1863620718.eu-west-2.elb.amazonaws.com'\n self.base_url = 'http://{}:12306/social/accountlist'.format(self.host)\n self.commit_url = 'http://{}:12306/social/addtimeline'.format(self.host)\n self.update_url = 'http://{}:12306/social/updateaccount'.format(self.host)\n\n self.common_query = 'page_limit=50&need_pagination=1'\n # self.headers = {'Connection': 'close'}\n self.debug_screen = kwargs.get('debug_screen')\n self.debug_mode = kwargs.get('debug_mode')\n self.count = 50\n\n def start_requests(self):\n url = '{url}?page_num=1&{query}'.format(url=self.base_url, query=self.common_query)\n return [Request(url, callback=self.parse, errback=self.parse_error)]\n\n def yield_next_page_request(self, response, data):\n if len(data['data']['list']) == 0:\n return None\n\n query = dict(map(lambda x: x.split('='), parse.urlparse(response.request.url)[4].split('&')))\n page = int(query['page_num'])\n url = '{url}?page_num={page}&{query}'.format(url=self.base_url, page=page + 1, query=self.common_query)\n self.logger.info(url)\n return Request(url, callback=self.parse, errback=self.parse_error)\n\n def parse_error(self, response):\n # self.logger.error('error url {}, error{}'.format(response.request.url, repr(response)))\n api_error({'url': response.request.url})\n\n def parse(self, response):\n data = json.loads(response.body)\n if data['code'] != 0:\n # api_error({'url': response.request.url, 'response': response.body})\n self.logger.error('{} error {}'.format(response.request.url, response.body))\n return\n for item in data['data']['list']:\n if self.debug_screen is not None:\n if self.debug_screen != item['account']:\n continue\n self.logger.info('debug screen {} {}'.format(self.debug_screen, item))\n if item['source_avatar'] is not None:\n continue\n yield TwitterUserShowRequest(\n screen_name=item['account'],\n callback=self.parse_twitter_user_show,\n errback=self.parse_twitter_error,\n meta={'social_id': item['id'],\n 'source_avatar': item['source_avatar'],\n 'screen_name': item['account']})\n\n next_page_generator = self.yield_next_page_request(response, data)\n if next_page_generator is not None:\n yield next_page_generator\n\n def parse_twitter_error(self, failure):\n self.logger.error('parse twitter error {}, meta {}'.format(repr(failure), failure.request.meta))\n if failure.check(HttpError):\n response = failure.value.response\n self.logger.error('HttpError on %s', response.url)\n elif failure.check(DNSLookupError):\n request = failure.request\n self.logger.error('DNSLookupError on %s', request.url)\n elif failure.check(TimeoutError, TCPTimedOutError):\n request = failure.request\n self.logger.error('TimeoutError on %s', request.url)\n\n def parse_twitter_user_show(self, response):\n account_id = response.request.meta['social_id']\n image_url = response.user['profile_image_url']\n if image_url is not None:\n image_url = image_url.replace('_normal', '')\n\n item = TwitterAvatarItem()\n item['social_account_id'] = account_id\n item['source_avatar'] = image_url\n item['avatar'] = upload_assets(image_url)\n yield item\n\n ##############################################################\n # data format\n ##############################################################\n","sub_path":"pipeline/spiders/twitter_avatar_empty.py","file_name":"twitter_avatar_empty.py","file_ext":"py","file_size_in_byte":4715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"114867409","text":"import numpy as np\n\nclass dbm:\n\tdef __init__(self, num_layer, layer_size, binary = True):\n\t\t# default: binary states \n\t\t# num_layer: #layer\n\t\t# layer_size: a row vector (vsize, h_1size, h_2size, ..., h_nsize)\n\t\t# we also denote v as h_0\n\t\t# binary -- True if using binary states\n\t\t# h: list of layer column vectors\n\t\t# W: list of weight matrices\n\t\tself.num_layer = num_layer\n\t\tself.layer_size = layer_size\n\t\tself.binary = binary\n\t\tself.h = list()\n\t\tself.W = list()\n\t\tself.b = list()\n\t\tfor i in range(0, num_layer):\n\t\t\tself.h.append(np.zeros(layer_size[i], dtype = int).reshape(layer_size[i], 1))\n\t\t\tif i != num_layer - 1:\n\t\t\t\tself.W.append(np.random.random(layer_size[i] * layer_size[i+1]).reshape(layer_size[i+1], layer_size[i]))\n\t\t\tself.b.append(np.random.random(layer_size[i]).reshape(layer_size[i], 1))\n\n\tdef train(self, train_data, epsilon, meanfield = False):\n\t\t# train_data -- the training data (data_1, data_2, ..., data_n)^T\n\t\t# epsilon -- learning rate\n\t\t# training data distribution \\approx \\frac{1}{n}\\sum_{i = 1}^n \\delta_{data_i}(x)\n\t\t# we approximate Q(h_i|h_{i-1}, h_{i+1}) by Q(h_i|2 * h_{i-1})\n\t\t# so does P\n\t\tfor i in range(1,self.num_layer):\n\t\t\t# get the training data of h_{i-1}\n\t\t\ttrain_h = self.hidden_input(train_data, i-1, meanfield).T\n\t\t\tfor data in train_h:\n\t\t\t\t# data -- row vector of a data point in train_h\n\t\t\t\tself.update(train_h.reshape(self.layer_size[i-1], 1), epsilon, i)\n\n\tdef update(self, data, epsilon, i):\n\t\t# compute Q(h_i|h_{i-1})\n\t\tif self.binary == True:\n\t\t\tif i != self.num_layer - 1:\n\t\t\t\tQ = sigm(self.b[i] + 2 * np.dot(self.W[i-1], data))\n\t\t\telse:\n\t\t\t\tQ = sigm(self.b[i] + np.dot(self.W[i-1], data))\n\t\t# sample h_i from Q\n\t\tif self.binary == True:\n\t\t\tself.h[i] = np.array(np.random.rand(Q.size).reshape(Q.shape) < Q, dtype = int)\n\n\t\t# compute P(h_{i-1}|h_i)\n\t\tif self.binary == True:\n\t\t\tif i != 1:\n\t\t\t\tP = sigm(self.b[i-1] + 2 * np.dot(self.W[i-1].T, self.h[i]))\n\t\t\telse:\n\t\t\t\tP = sigm(self.b[i-1] + np.dot(self.W[i-1].T, self.h[i]))\n\t\t# sample h_{i-1} from P\n\t\tif self.binary == True:\n\t\t\tself.h[i-1] = np.array(np.random.rand(P.size).reshape(P.shape) < P, dtype = int)\n\n\t\t# compute Q(h_i|h_{i-1})\n\t\tif self.binary == True:\n\t\t\tif i != self.num_layer - 1:\n\t\t\t\tQ = sigm(self.b[i] + 2 * np.dot(self.W[i-1], data))\n\t\t\telse:\n\t\t\t\tQ = sigm(self.b[i] + np.dot(self.W[i-1], data))\n\n\t\t# update parameters\n\t\tif i != self.num_layer - 1:\n\t\t\tself.W[i-1] += 2 * epsilon * (np.dot(self.h[i], data.T) - np.dot(Q, self.h[i-1].T))\n\t\telse:\n\t\t\tself.W[i-1] += epsilon * (np.dot(self.h[i], data.T) - np.dot(Q, self.h[i-1].T))\n\t\tself.b_v += epsilon * (data - self.v)\n\t\tself.b_h += epsilon * (self.h - Q)\n\n\tdef hidden_input(self, train_data, i, meanfield):\n\t\t# compute h_{i} from trained network\n\t\tif i == 0:\t# untrained\n\t\t\tif len(train_data.shape) == 1:\t# row vector\n\t\t\t\treturn train_data.reshape(train_data.size, 1)\n\t\t\tif train_data.shape[1] == 1:\t# column vector\n\t\t\t\treturn train_data\n\t\t\treturn train_data.T\n\t\telse:\n\t\t\tif len(train_data.shape) == 1:\t# row vector\n\t\t\t\ttrain_h = train_data.reshape(train_data.size, 1)\n\t\t\telif train_data.shape[1] == 1:\t# column vector\n\t\t\t\ttrain_h = train_data\t\t\t\t\n\t\t\telse:\n\t\t\t\ttrain_h = train_data.T\t# h_j, here is h_0\n\n\t\t\tfor j in range(0, i):\n\t\t\t\t# compute Q(h_{j+1}|h_j)\n\t\t\t\tif self.binary == True:\n\t\t\t\t\tif j != self.num_layer - 2:\n\t\t\t\t\t\tQ = sigm(self.b[j+1] + 2 * np.dot(self.W[j], train_h))\n\t\t\t\t\telse:\n\t\t\t\t\t\tQ = sigm(self.b[j+1] + np.dot(self.W[j], train_h))\n\t\t\t\tif meanfield == False:\n\t\t\t\t\t# sample h_{j+1} from Q\n\t\t\t\t\tif self.binary == True:\n\t\t\t\t\t\ttrain_h = np.array(np.random.rand(Q.size).reshape(Q.shape) < Q, dtype = int)\n\t\t\t\telse:\n\t\t\t\t\ttrain_h = Q\n\n\t\t\treturn train_h\n\n\t# def predict(self, data, meanfield = False):\n\t\t# tricky!\n","sub_path":"dbm.py","file_name":"dbm.py","file_ext":"py","file_size_in_byte":3692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"322844769","text":"from .autoencoders import AutoEncoderTrainer\nfrom .vae import VAETrainer\nfrom .cvae import CVAETrainer\nfrom .cvae_new import CVAE_NEW_Trainer\nfrom .forward_inverse import BaseForwardModel, BaseInverseModel, BaseRewardModel, BaseRewardModel2, BasicTrainer, SelfSupClassfier\nfrom .priors import SRLConvolutionalNetwork, SRLDenseNetwork, SRLLinear\nfrom .triplet import EmbeddingNet\nfrom .gan import GANTrainer \nfrom .gan_new import GanNewTrainer\nfrom .cgan_new import CGanNewTrainer\nfrom .cgan import CGANTrainer \nimport torch\nfrom collections import OrderedDict\ntry:\n # relative import: when executing as a package: python -m ...\n from ..losses.losses import forwardModelLoss, inverseModelLoss, rewardModelLoss, spclsLoss\n from .base_trainer import BaseTrainer\n from ..utils import printRed\nexcept:\n # absolute import: when executing directly: python train.py ...\n from losses.losses import forwardModelLoss, inverseModelLoss, rewardModelLoss, spclsLoss\n from models.base_trainer import BaseTrainer\n from utils import printRed\n\n\nclass SRLModules(BaseForwardModel, BaseInverseModel, BaseRewardModel, BaseRewardModel2, SelfSupClassfier):\n def __init__(self, state_dim=2,cuda=False, class_dim=1,img_shape=None, action_dim=6, model_type=\"custom_cnn\", losses=None,\n split_dimensions=None, n_hidden_reward=16, inverse_model_type=\"linear\",ls=False,add_noise=False,only_action=False,pretrained_weights_path=None,\n debug=False, device='cpu'):\n \"\"\"\n A model that can combine AE/VAE + Inverse + Forward + Reward models\n :param state_dim: (int)\n :param img_shape: (tuple or None) channels first ! \n :param action_dim: (int)\n :param model_type: (str)\n :param losses: ([str])\n :param split_dimensions: (OrderedDict) Number of dimensions for the different losses\n :param n_hidden_reward: (int) Number of hidden units for the reward model\n :param inverse_model_type: (str) Architecture of the inverse model ('linear', 'mlp')\n \"\"\"\n self.model_type = model_type\n self.losses = losses\n BaseForwardModel.__init__(self)\n BaseInverseModel.__init__(self)\n BaseRewardModel.__init__(self)\n BaseRewardModel2.__init__(self)\n SelfSupClassfier.__init__(self)\n self.state_dim = state_dim\n if img_shape is None:\n self.img_shape = (3, 224, 224)\n else:\n self.img_shape = img_shape\n\n # For state splitting ================= TODO UGLY\n self.split_dimensions = split_dimensions\n if self.split_dimensions != -1:\n assert len(split_dimensions) == len(losses), \"Please specify as many split dimensions {} as losses {} !\". \\\n format(len(split_dimensions), len(losses))\n # TODO TO DELETE --------------\n n_dims = sum(split_dimensions.values())\n # Account for shared dimensions\n n_dims += list(split_dimensions.values()).count(-1)\n assert n_dims == state_dim, \\\n \"The sum of all splits' dimensions {} must be equal to the state dimension {}\"\\\n .format(sum(split_dimensions.values()), str(state_dim))\n # -------------------------------\n state_dim_dict = OrderedDict()\n prev_dim = 0\n for loss_name, dim in self.split_dimensions.items():\n if dim == -1:\n state_dim_dict[loss_name] = prev_dim\n else:\n state_dim_dict[loss_name] = dim\n prev_dim = dim\n else:\n state_dim_dict = {\"forward\": self.state_dim, \"inverse\": self.state_dim, \"reward\": self.state_dim, \"reward2\": self.state_dim}\n\n self.initForwardNet(state_dim_dict.get(\"forward\", self.state_dim), action_dim)\n self.initInverseNet(state_dim_dict.get(\"inverse\", self.state_dim), action_dim, model_type=inverse_model_type)\n self.initRewardNet(state_dim_dict.get(\"reward\", self.state_dim), n_hidden=n_hidden_reward)\n self.initRewardNet2(state_dim_dict.get(\"reward2\", self.state_dim), n_hidden=n_hidden_reward)\n self.initSpClsmodel(state_dim_dict.get(\"reward2\", self.state_dim), n_hidden=100)\n\n # Architecture\n if \"autoencoder\" in losses or \"dae\" in losses:\n self.model = AutoEncoderTrainer(state_dim=state_dim, img_shape=self.img_shape)\n self.model.build_model(model_type=model_type)\n elif \"vae\" in losses:\n self.model = VAETrainer(state_dim=state_dim, img_shape=self.img_shape)\n self.model.build_model(model_type=model_type)\n elif 'gan' in losses:\n self.model = GANTrainer(state_dim=state_dim, img_shape=self.img_shape)\n self.model.build_model(model_type=model_type)\n elif 'gan_new' in losses:\n\t self.model = GanNewTrainer( state_dim, self.img_shape)\n\t self.model.build_model(model_type=model_type)\n elif 'cgan' in losses:\n self.model = CGANTrainer(state_dim=state_dim,label_dim=class_dim, img_shape=self.img_shape, device=device, only_action=only_action)\n self.model.build_model(model_type=model_type)\n elif 'cgan_new' in losses:\n self.model = CGanNewTrainer(state_dim=state_dim,label_dim=class_dim, img_shape=self.img_shape, device=device, only_action=only_action)\n self.model.build_model(model_type=model_type)\n elif \"cvae\" in losses:\n self.model = CVAETrainer(state_dim=state_dim, class_dim=class_dim, img_shape=img_shape, device=device, only_action=only_action)\n self.model.build_model(model_type=model_type)\n elif \"cvae_new\" in losses:\n self.model = CVAE_NEW_Trainer(state_dim=state_dim, img_shape=img_shape, device=device)\n self.model.build_model(model_type=model_type)\n\n \n\n # elif losses is not None and \"triplet\" in losses:\n # # pretrained resnet18 with fixed weights\n # # TODO not tested yet\n # raise NotImplementedError\n # self.model = EmbeddingNet(state_dim)\n else:\n # for losses not depending on specific architecture (supervised, inverse, forward..)\n self.model = BasicTrainer(state_dim=state_dim, img_shape=self.img_shape)\n self.model.build_model(model_type=model_type) # TODO add the other model_type !!\n\n # elif model_type == \"resnet\":\n # self.model = SRLConvolutionalNetwork(state_dim, cuda)\n\n # # elif: [Add new model here !]\n\n def forward(self, x):\n if self.model_type == 'linear' or self.model_type == 'mlp':\n x = x.contiguous()\n return self.model(x)\n\n def encode(self, x):\n if \"triplet\" in self.losses:\n return self.model(x)\n else:\n raise NotImplementedError()\n\n def forwardTriplets(self, anchor, positive, negative):\n \"\"\"\n Overriding the forward function in the case of Triplet loss\n anchor : anchor observations (torch. Tensor)\n positive : positive observations (torch. Tensor)\n negative : negative observations (torch. Tensor)\n \"\"\"\n return self.model(anchor), self.model(positive), self.model(negative)\n\n def add_forward_loss(self, states, actions_st, next_states, loss_manager, weight=1.0):\n next_states_pred = self.forwardModel(states, actions_st)\n forwardModelLoss(next_states_pred, next_states, weight=weight, loss_manager=loss_manager)\n\n def add_inverse_loss(self, states, actions_st, next_states, loss_manager, weight=2.0):\n actions_pred = self.inverseModel(states, next_states)\n inverseModelLoss(actions_pred, actions_st, weight=weight, loss_manager=loss_manager)\n\n def add_reward_loss(self, states, rewards_st, next_states, loss_manager, label_weights, ignore_index=-1, weight=100.0):\n # import ipdb; ipdb.set_trace()\n rewards_pred = self.rewardModel(states, next_states)\n rewardModelLoss(rewards_pred, rewards_st, weight=weight, loss_manager=loss_manager,\n label_weights=label_weights, ignore_index=ignore_index)\n def add_reward2_loss(self, states, rewards_st, loss_manager, label_weights, ignore_index=-1, weight=100.0):\n rewards_pred = self.rewardModel2(states)\n rewardModelLoss(rewards_pred, rewards_st, weight=weight, loss_manager=loss_manager,\n label_weights=label_weights, ignore_index=ignore_index)\n \n def add_spcls_loss(self, states, cls_gt, loss_manager, weight=100.0):\n cls_pred = self.classifier(states)\n spclsLoss(cls_pred, cls_gt, weight=weight, loss_manager=loss_manager)\n","sub_path":"models/modules.py","file_name":"modules.py","file_ext":"py","file_size_in_byte":8701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"142692119","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import JsonResponse\nfrom .models import Post, Categories, Comment\nfrom django.db.models import Q\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom .forms import CommentForm\n\n# Create your views here.\n\n\ndef index(request):\n imagen = \"/static/img/sidebar.jpg\"\n posts_list = Post.objects.filter(publicado=True).select_related(\n 'autor').order_by('-fecha_publicacion')\n categories = Categories.objects.all()\n paginator = Paginator(posts_list, 5)\n page = request.GET.get('page', 1)\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n # If page is not an integer, deliver first page.\n posts = paginator.page(1)\n except EmptyPage:\n # If page is out of range (e.g. 9999), deliver last page of results.\n posts = paginator.page(paginator.num_pages)\n\n return render(request, 'blog/index.html', {'image': imagen, 'posts': posts, 'categories': categories})\n\n\ndef post(request, slug):\n\n post = get_object_or_404(Post, slug=slug)\n print('post: ' + post.titulo)\n related = Post.objects.filter(Q(categoria=post.categoria) | Q(\n autor=post.autor), ~Q(titulo=post.titulo))[:3]\n return render(request, 'blog/post/post.html', {'post': post, 'related': related})\n\n\ndef add_comment(request, slug):\n\tpost = get_object_or_404(Post, slug=slug)\n\tprint(request.POST)\n\tif request.method == 'POST':\n\t\treturn JsonResponse({\"prueba\": request.POST.get(\"text\")})\n\n\n# 13/11/2018 agregado este comando primera parte\n# def categories(request, idcategory):\n# categories = Categories.objects.get(id=idcategories)\n# posts = categories.post_set.order_by(\"-creation_date\")\n\n# return render_to_response(\n# \"home.html\",\n# {\n# \"posts\":posts,\n# },\n# )\n\n# def categories(request):\n# categories = Categories.objects.all()\n# return render(request, 'blog/categorias/index.html',{'categories':categories})\n\n# def categories(request, pk):\n# categories = get_object_or_404(Categories, pk=pk)\n# return render(request, 'blog/base.html',{'categories':categories})\n","sub_path":"techlinx/Blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"503441834","text":"#!/usr/bin/python3.x\n# -*- coding: utf-8 -*-\n# @Time : 2021/5/12 16:41\n# @Author : hike\n# @Email : hikehaidong@gmail.com\n# @File : track_data.py\n# @Software: PyCharm\nimport stomp\nimport re\nimport time\nfrom datetime import datetime\nfrom utils.getdatabyselenium import get_num_driver\n\n\n\"\"\"\n\n数据追踪\n\"\"\"\nclass TrackDataByTable():\n \"\"\"\n 直接在表中获取\n 外加一个apscheduler任务\n\n \"\"\"\n def __init__(self,db_qbb):\n self.db_qbb=db_qbb\n\n def get_track_datas_qbbb(self):\n \"\"\"\n 数据库qbbb,track_task中获取数据\n \"\"\"\n sql=\"select * from TS_track_task where is_done=0\"\n self.db_qbb.execute(sql)\n datas=self.db_qbb.execute_query()\n return datas\n\n def track_data_task(self):\n \"\"\"\n 直接扫描表\n 数据库中获取链接进行追踪\n \"\"\"\n driver=get_num_driver()\n for data in self.get_track_datas_qbbb():\n\n num = driver.get_data_it(data[1])\n create_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n # 转发、评论、点赞\n # 追踪记录\n sql_record = \"insert into TS_track_record(sn,forward_num,comment_num,good_num,create_date) values('%s','%d','%d','%d','%s')\" % (\n data[2], num[0], num[1], num[2], create_date)\n self.db_qbbb.execute(sql_record)\n # 更新值\n sql_Base = \"update TS_DataMerge_Base set Transpond_Num=%d,Comment_Num=%d,Forward_Good_Num=%d where SN='%s' \" % (\n num[0], num[1], num[2], data[2])\n self.db_qbbb.execute(sql_Base)\n # print('更新库')\n # 修改数据追踪表\n sql_track_task=\"update TS_track_task set is_done=1 where sn='%s' \"%data[2]\n self.db_qbbb.execute(sql_track_task)\n # print('追踪完毕')\n driver.close()\n\n def get_track_url(self):\n \"\"\"\n 数据库中获取追踪的url\n \"\"\"\n sql_of_extend = \"select SN from TS_DataMerge_Extend where is_Track=1\"\n datas = self.db_qbb.execute_query(sql_of_extend)\n url_list = []\n for data in datas:\n sql_of_base = \"select URL from TS_DataMerge_Base where SN='%s'\" % (data[0])\n urls = self.db_qbb.execute_query(sql_of_base)\n if \"weibo.com\" in urls[0]:\n url = {\n 'sn': data[0],\n 'url': urls[0]\n }\n url_list.append(url)\n return url_list\n\n\ndef track_data_number_sql2(sn, data,db_qbbb):\n \"\"\"\n stomp版本\n 将得到的数据插入数据库\n \"\"\"\n create_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n # 转发、评论、点赞\n sql_record = \"insert into TS_track_record(sn,forward_num,comment_num,good_num,create_date) values('%s','%d','%d','%d','%s')\" % (\n sn, data[0], data[1], data[2], create_date)\n db_qbbb.execute(sql_record)\n sql_Base = \"update TS_DataMerge_Base set Transpond_Num=%d,Comment_Num=%d,Forward_Good_Num=%d where SN='%s' \" % (\n data[0], data[1], data[2], sn)\n db_qbbb.execute(sql_Base)\n\n\n# ----------------------------数据追踪消息队列------------------------------------------------\n\nclass MyListener(stomp.ConnectionListener):\n \"\"\"\n 自己的监听队列,操作数据库\n \"\"\"\n def __init__(self,conn):\n self.conn = conn\n self.msg_list=[]\n\n def on_error(self, frame):\n print('received an error \"%s\"' % frame.body)\n\n def on_send(self, frame):\n print('received a message \"%s\"' % frame.body)\n pattern = re.compile(r'http://weibo.com(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')\n url = re.findall(pattern, frame.body)\n if url:\n self.msg_list.append(frame.body)\n print(\"处理之后的链接:\" + url[0])\n # # 爬取评论转发点赞数量\n get_url_from_stomp()\n # data = get_data_it(url[0])\n # sn = frame.body.split('\"')[3]\n # track_data_number_sql2(sn, data)\n # for x in range(5):\n # print(x)\n # time.sleep(1)\n # print('processed message')\n # print(\"监听的url:\" + url[0])\n def on_disconnected(self):\n print('disconnected')\n connect_and_subscribe(self.conn)\n def get_msg_list(self):\n print(self.msg_list)\n return self.msg_list\n\ndef connect_and_subscribe(conn):\n \"\"\"\n 连接和监听\n \"\"\"\n conn.connect('admin', 'admin', wait=True)\n conn.send(destination='aahike',body=\"hike\")\n # conn.subscribe(destination='aahike', id=1, ack='auto')\n # conn.subscribe(destination='task.msg.tracker_2.1', id=1, ack='auto')\n\n\ndef re_connect_subscribe(conn):\n \"\"\"\n 重新登记注册\n :return:\n \"\"\"\n conn.disconnect()\n time.sleep(3)\n connect_and_subscribe(conn)\n\ndef get_url_from_stomp_list(frame_body_list):\n try:\n if frame_body_list:\n print(\"开始抓数据\")\n for frame_body in frame_body_list:\n pattern = re.compile(r'http://weibo.com(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')\n url = re.findall(pattern, frame_body)\n driver=get_num_driver()\n data = driver.get_data_it(url[0])\n sn = frame_body.split('\"')[3]\n track_data_number_sql2(sn, data)\n for x in range(3):\n print(x)\n time.sleep(1)\n return True\n except Exception as e:\n print(e)\n return False\ndef get_url_from_stomp(frame_body):\n try:\n pattern = re.compile(r'http://weibo.com(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+')\n url = re.findall(pattern, frame_body)\n if url:\n driver=get_num_driver()\n data = driver.get_data_it(url[0])\n sn = frame_body.split('\"')[3]\n track_data_number_sql2(sn, data)\n for x in range(3):\n print(x)\n time.sleep(1)\n return True\n except Exception as e:\n print(e)\n return False\n\n\ndef track_data_work():\n conn = stomp.Connection(host_and_ports=[('223.223.180.10', 61613)],heartbeats=(4000, 4000))\n # conn.connect('admin', 'admin', wait=True)\n lst = MyListener(conn)\n # lst = MyListener()\n conn.set_listener('track_data', lst)\n connect_and_subscribe(conn)\n i=0\n while 1:\n i+=1\n time.sleep(10)\n if i==18:\n re_connect_subscribe()\n i=0\n # conn.unsubscribe(destination='task.msg.tracker_2.1', id=1, ack='auto')\n # time.sleep(2)\n # frame_body_list=lst.get_msg_list()\n # print(frame_body_list)\n # conn.disconnect()\n # conn.disconnect()\n # hike_flag=get_url_from_stomp(frame_body_list)\n # if hike_flag:\n # return track_data_work()\n # else:\n # conn.disconnect()\nif __name__ == '__main__':\n track_data_work()","sub_path":"apscheduler_yqt/MyTestFile/评论转发点赞/01.py","file_name":"01.py","file_ext":"py","file_size_in_byte":7092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"381412577","text":"import math\r\n\r\n\r\nclass RegularPoylygon:\r\n def __init__(self, n=3, side=1, x=0, y=0) -> None:\r\n self.n = n\r\n self.side = side\r\n self.x = x\r\n self.y = y\r\n\r\n def getPerimeter(self):\r\n print(\"Perimeter = {:.3f}\".format(self.n*self.side))\r\n\r\n def getArea(self):\r\n print(\"Area = {:.3f}\".format(self.n*self.side *\r\n self.side/math.tan(math.pi/self.n)/4))\r\n\r\n def distanceToPolygon(self, other):\r\n print(\"Distance is {:.3f}\".format(\r\n math.sqrt(pow(self.x-other.x, 2) + pow(self.y-other.y, 2))))\r\n\r\n\r\nsquare = RegularPoylygon(4, 8, 0, 0)\r\ntriangle = RegularPoylygon(3, 3, 1, 1)\r\nsquare.getArea()\r\nsquare.getPerimeter()\r\n\r\ntriangle.getArea()\r\ntriangle.getPerimeter()\r\n\r\nsquare.distanceToPolygon(triangle)\r\ntriangle.distanceToPolygon(square)\r\n","sub_path":"计算机与软件学院/Python程序设计/实验/实验8/code/代码/实验/7 (3).py","file_name":"7 (3).py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"475521442","text":"__author__ = 'Fiziev'\n\n\nEXPAND = 'E'\nCONTRACT = 'C'\nSTEADY = 'S'\n\nCLUSTER_SEPARATOR = '-'\n\nPREDICTED_STARTS = 'predicted_starts'\nPREDICTED_ENDS = 'predicted_ends'\nORIGINAL_STARTS = 'original_starts'\nORIGINAL_ENDS = 'original_ends'\n\nMISSING_OBSERVATION = -1\n\nLAMBDA = 'lambda'\nSCALE = 'scale'\nMEAN = 'mean'\nSTDDEV = 'stddev'\n\nMEAN_SQUARED = 'mean_squared'\n\nCLUSTERS = 'clusters'\nBOUNDARY_NOISE = 'boundary_noise'\nTOTAL_POSTERIORS_PER_CLUSTER = 'total_posteriors_per_cluster'\n\nLEFT_BOUNDARY = 'left_boundary'\nRIGHT_BOUNDARY = 'right_boundary'\nCHROMOSOME = 'chromosome'\n\nLEFT_BOUNDARY_IDX = 0\nRIGHT_BOUNDARY_IDX = 1\n\nHIDDEN = 'H'\nOBSERVED = 'O'\nDELTA = 'delta'\n\nPRIOR = 'prior'\nLENGTH = 'length'\n\n# ALL_FEATURES = [LEFT_BOUNDARY, RIGHT_BOUNDARY, LEFT_SIGNAL, RIGHT_SIGNAL, BLOCK_SIGNAL, LENGTH]\n# FEATURES = [LEFT_BOUNDARY, RIGHT_BOUNDARY, SIGNAL, LENGTH]\n# FEATURES = [LEFT_BOUNDARY, RIGHT_BOUNDARY, SIGNAL]\n# FEATURES = [LEFT_BOUNDARY, RIGHT_BOUNDARY]\n# FEATURES = [SIGNAL]\n\nFWD_DIRECTION = 0\nBCK_DIRECTION = 1\n\nREGULAR = 'regular'\nSINGLETON = 'singleton'\nINTERMEDIATE = 'intermediate'\n\nPEAK_TIMEPOINTS = 'peak_timepoints'\nFIRST_PEAK_TIMEPOINT = 'first_peak_timepoint'\nLAST_PEAK_TIMEPOINT = 'last_peak_timepoint'\nEFFECTIVE_FIRST_PEAK_TIMEPOINT = 'effective_first_peak_timepoint'\nEFFECTIVE_LAST_PEAK_TIMEPOINT = 'effective_last_peak_timepoint'\n\nMIDPOINT = 'midpoint'\n\nPREV_BLOCK_SIGNAL = 'block_signal_relative_to_prev_timepoint'\nPREV_LEFT_SIGNAL = 'left_signal_relative_to_prev_timepoint'\nPREV_RIGHT_SIGNAL = 'right_signal_relative_to_prev_timepoint'\nNEXT_BLOCK_SIGNAL = 'block_signal_relative_to_next_timepoint'\nNEXT_LEFT_SIGNAL = 'left_signal_relative_to_next_timepoint'\nNEXT_RIGHT_SIGNAL = 'right_signal_relative_to_next_timepoint'\n\nREG_ID = 'reg_id'\n\nNOISE = 'NOISE'\n\nBOUNDARY_DYNAMICS = 'boundary_dynamics'\nBLOCK_SIGNAL_DYNAMICS = 'block_signal_dynamics'\nBOUNDARY_SIGNAL_DYNAMICS = 'boundary_signal_dynamics'\n\nTOTAL_POSTERIORS_PER_STATE_PSEUDO_COUNT = 1\n\nLEFT = 'left'\nRIGHT = 'right'\n\nBLOCKS_FNAME = 'blocks_order'\nBLOCK_WITH_SIGNAL_FNAME = 'blocks_order.with_signal'\n\nNO_DYNAMIC = -1\nNO_PATH = -1\n\nUNKNOWN = 'UNKNOWN'\n\nUNDERFLOWN = 'UNDERFLOWN'\n","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"202860201","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport pymongo\n\n# Mongodb Pipeline\nclass TripadvisorScrapyPipeline(object):\n\n def __init__(self):\n # Create a connection to local mongodb compass\n self.connection = pymongo.MongoClient(\n 'localhost',\n 27017\n )\n # Create database 'City'\n db = self.connection['Tripadvisor']\n\n # Create table inside database\n self.collection = db['City_Details']\n \n def process_item(self, item, spider):\n # Inserts items in dictionary form\n self.collection.insert(dict(item))\n return item\n","sub_path":"tripadvisor_scrapy/tripadvisor_scrapy/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"575414564","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"register\", views.register, name=\"register\"),\n path(\"createlisting/\", views.createlisting, name='createlisting'),\n path(\"placebid/\", views.placebid, name='placebid'),\n path(\"listing//\", views.showlisting, name=\"showlisting\"),\n path(\"category//\", views.categorywise, name=\"categorywise\"),\n path(\"categories/\", views.categories, name=\"categories\"),\n path(\"addtowatchlist/\", views.addtowatchlist, name=\"addtowatchlist\"),\n path(\"watchlist/\", views.watchlist, name=\"watchlist\"),\n path(\"comment/\", views.comment, name=\"comment\"),\n path(\"listing//\", views.userlistings, name=\"userlistings\"),\n path(\"deactivate/\", views.deactivate, name=\"deactivate\"),\n]\n","sub_path":"auctions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"606398145","text":"from python_neinformirano_prebaruvanje import *\r\n\r\nclass CrnoBelo(Problem):\r\n def __init__(self,initial, goal):\r\n self.initial = initial\r\n self.goal = goal\r\n \r\n def successor(self,state):\r\n successors = dict()\r\n\r\n for x in range(n):\r\n for y in range(n):\r\n matrix = [[state[m] for m in range(n*row,n*(row+1))] for row in range(n)] \r\n #len(cols)\r\n matrix[x][y] = (1 if matrix[x][y] == 0 else 0)\r\n if x+1 < n:\r\n matrix[x+1][y] = (1 if matrix[x+1][y] == 0 else 0)\r\n if x-1 >= 0:\r\n matrix[x-1][y] = (1 if matrix[x-1][y] == 0 else 0)\r\n if y+1 < n:\r\n matrix[x][y+1] = (1 if matrix[x][y+1] == 0 else 0)\r\n if y-1 >= 0:\r\n matrix[x][y-1] = (1 if matrix[x][y-1] == 0 else 0)\r\n \r\n list_of_elements = [element for redica in matrix for element in redica]\r\n tuple_of_elements = tuple(list_of_elements)\r\n successors[f'x: {x}, y: {y}'] = tuple_of_elements\r\n \r\n return successors\r\n \r\n def actions(self,state):\r\n return self.successor(state).keys()\r\n \r\n def goal_test(self, state):\r\n return self.goal == state\r\n \r\n def result(self, state, action):\r\n possible = self.successor(state)\r\n return possible[action]\r\n\r\n #Hamingovo rastojanie\r\n #def h(self, node):\r\n # state = node.state\r\n # vrednost = 0\r\n # for i in range(0, len(state)):\r\n # if state[i] != self.goal[i]:\r\n # vrednost = vrednost + 1\r\n # return vrednost\r\n\r\n \r\n#n = int(input())\r\nn = 3\r\n#polinja = list(map(int, input().split(',')))\r\npolinja = [0,0,0,1,0,0,1,1,0]\r\n\r\npolinja = tuple(polinja)\r\n\r\ninitial = polinja \r\n\r\ngoal = tuple([1 for _ in range(n*n)])\r\n\r\ninstanca = CrnoBelo(initial, goal)\r\n\r\nanswer = breadth_first_graph_search(instanca)\r\n\r\nprint(answer.solution())","sub_path":"CrnoBelo.py","file_name":"CrnoBelo.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"625621148","text":"#Check that you are using python 3.8 or further \n#pip install -U aflr\nimport aflr \n# Make sure to import your API key\naflr.api_key =\"996463f1fb8a4683b0c0913835782d4c\"\n\n# Let's create a script and have the text as Hello World!\nscript = aflr.Script().create(scriptText=\"Hello world\", scriptName=\"hello\", moduleName=\"hello\", projectName=\"hello\")\nprint(script)\n\n# create text to speech \nresponse = aflr.Speech().create(scriptId=script.get(\"scriptId\"), voice=\"Joanna\")\nprint(response)\n\n# Now lets master the speech file with high quality and a nice background track\nresponse = aflr.Mastering().create(\n\tscriptId=script.get(\"scriptId\"),\n\tbackgroundTrackId=\"full__citynights.wav\"\n\t)\nprint(response)\n\n# retrieve mastered file and download to your local folder\nfile = aflr.Mastering().download(scriptId=script.get(\"scriptId\"), destination=\".\")\nprint(file)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"536823969","text":"#!/usr/bin/env python\nfrom GSASII import __version__ as gsas_version\nfrom GSASIIpath import GetVersionNumber as gsas_svn_number\nversion = \"%s.%s\" % (gsas_version,str(gsas_svn_number()))\n\nspec_in= \\\n\"\"\"\nName: gsasii\nVersion: $version\nRelease: 1%{?dist}\nSummary: General Structure Analysis System-II\n\nLicense: All rights reserved\nURL: https://subversion.xor.aps.anl.gov/trac/pyGSAS\nSource: %{name}-$version.tar.gz\n\nBuildRequires: scons gcc-gfortran numpy-f2py make python-sphinx python-matplotlib-wx\nPrefix: /opt/gsasii\n\nRequires: python >= 2.7\nRequires: wxPython\nRequires: python-matplotlib\nRequires: python-matplotlib-wx\nRequires: numpy\nRequires: scipy\n# pillow is new version of python imaging library\nRequires: python-pillow\nRequires: PyOpenGL\n\n%description\nPowder and single crystal diffraction Rietveld refinement\n\n%define debug_packages %{nil}\n%define debug_package %{nil}\n\n%prep\n%setup -n %{name}\n\n%build\ncd fsource\nscons\n#cd ../doc\n#make html\n\n%install\nrm -rf $RPM_BUILD_ROOT\nmkdir -p %{buildroot}%{prefix}\ncp -R %{_builddir}/%{name}/* %{buildroot}%{prefix}\nchmod 755 %{buildroot}%{prefix}/GSASII.py\n\n%clean\nexit 0\n\n\"\"\"\n\ndef getChangelog():\n # svn log -l 10\n return \"\"\"\n%changelog\n\n\"\"\"\n\ndef getFiles():\n return \"\"\"\n%files\n%defattr(-,root,root,-)\n%{prefix}\n\n\"\"\"\n\nhandle = file('gsasii.version', 'w')\nhandle.write(version)\nhandle.close()\n\nfrom string import Template\nhandle = file('gsasii.spec', 'w')\n\nspec = Template(spec_in).safe_substitute(version=version)\nspec += getChangelog()\nspec += getFiles()\n\nhandle.write(spec)\nhandle.close()\n","sub_path":"generatespec.py","file_name":"generatespec.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"120646707","text":"\nimport sys\nsys.path.append(\"././\")\n\n# Import lib\nimport pandas as pd\nimport numpy as np\nimport cv2\nimport os\nfrom tqdm import tqdm\n\nimport tensorflow as tf\nimport tensorflow_addons as tfa\n\n# Import my own lib\nimport others.utilities as my_util\n\ngpu_id = 0\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = str(gpu_id)\n# Clear GPU cache\ntf.keras.backend.clear_session()\ngpus = tf.config.experimental.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(gpus[0], True)\n\n#############################################################################################\n\n# filename_comment = 'tar0d01'\n# param = {'exp':'exp_7', \n# 'model': ['b_270_e_50_a_1', 'b_240_e_50_a_1', 'b_330_e_50_a_1', 'b_330_e_50_a_1', 'b_360_e_50_a_1', 'b_240_e_50_a_1'], \n# 'epoch': [43, 31, 35, 41, 29, 28], \n# 'class': ['female-asian', 'female-black', 'female-caucasian', 'male-asian', 'male-black', 'male-caucasian']}\n\nfilename_comment = 'eer'\nparam = {'exp':'exp_7', \n 'model': ['b_180_e_50_a_1', 'b_180_e_50_a_1', 'b_240_e_50_a_1', 'b_360_e_50_a_1', 'b_270_e_50_a_1', 'b_240_e_50_a_1'], \n 'epoch': [36, 32, 42, 25, 35, 28], \n 'class': ['female-asian', 'female-black', 'female-caucasian', 'male-asian', 'male-black', 'male-caucasian']}\n\n# filename_comment = 'eer'\n# param = {'exp':'exp_8', \n# 'model': ['b_180_e_50_a_1', 'b_180_e_50_a_1', 'b_180_e_50_a_1', 'b_180_e_50_a_1', 'b_180_e_50_a_1', 'b_180_e_50_a_1'], \n# 'epoch': [36, 36, 36, 17, 17, 17], \n# 'class': ['female-asian', 'female-black', 'female-caucasian', 'male-asian', 'male-black', 'male-caucasian'], 'class-model': ['female', 'female', 'female', 'male', 'male', 'male']}\n\ndataset_name = 'Diveface'\ndataset_exacted = 'resnet50' # vgg16 resnet50 retinaface\n\nexp = param['exp']\nexp_name = exp + '_alg_tl' + dataset_exacted\n\nrandom_seed = 0\n\n#############################################################################################\n\n# Path\n# Dataset path\ndataset_path = my_util.get_path(additional_path=['.', '.', 'mount', 'FaceRecognitionPython_data_store', 'Dataset', 'Diveface'])\n\n#############################################################################################\n\n# # Load data\nmy_data = pd.read_csv((dataset_path + dataset_name + '_' + dataset_exacted + '_nonorm.txt'), sep=\" \", header=0)\n# Label\n# class_data = my_data.id.values\n# id_data = my_data.data_id.values\ninfo_data = my_data.iloc[:,:8].values\nx_data = my_data.iloc[:,8:].values\n# y_gender_data = my_data['gender'].values\ny_race_data = (my_data['gender'] + '-' + my_data['ethnicity']).values\n\n#############################################################################################\n\n# Feature size\nif dataset_exacted == 'vgg16':\n feature_size = 4096\nelif dataset_exacted == 'resnet50':\n feature_size = 2048\nproposed_model_feature_size = 1024\n\nrace_classes = ['female-asian', 'female-black', 'female-caucasian', 'male-asian', 'male-black', 'male-caucasian']\nmy_data_columns = my_data.columns[0:8]\nmy_data_columns = np.array(my_data_columns)\nmy_data_columns = np.append(my_data_columns, np.char.add(np.tile('feature_', (proposed_model_feature_size)), np.array(range(1, proposed_model_feature_size+1)).astype('U')))\ndel my_data\n\n# Initial triplets network model\nmodel_path = {}\nproposed_model = {}\nfor class_idx, class_val in enumerate(param['class']):\n if param['exp'] == 'exp_7':\n model_path[class_val] = my_util.get_path(additional_path=['.', '.', 'mount', 'FaceRecognitionPython_data_store', 'Result', 'gridsearch', exp, exp_name + param['class'][class_idx] + '_' + param['model'][class_idx] + '_run_' + str(random_seed)])\n else:\n model_path[class_val] = my_util.get_path(additional_path=['.', '.', 'mount', 'FaceRecognitionPython_data_store', 'Result', 'gridsearch', exp, exp_name + param['class-model'][class_idx] + '_' + param['model'][class_idx] + '_run_' + str(random_seed)])\n proposed_model[class_val] = tf.keras.models.Sequential()\n proposed_model[class_val].add(tf.keras.layers.Dense(proposed_model_feature_size, input_dim=feature_size, activation='linear'))\n proposed_model[class_val].add(tf.keras.layers.Lambda(lambda x: tf.math.l2_normalize(x, axis=1)))\n proposed_model[class_val].compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), loss=tfa.losses.TripletSemiHardLoss())\n proposed_model[class_val].load_weights(model_path[class_val] + 'cp-' + str(param['epoch'][class_idx]).zfill(4) + '.ckpt')\n\nexacted_data = np.empty((y_race_data.size, proposed_model_feature_size))\nfor class_val in tqdm(param['class']):\n tmp_idx = np.where(y_race_data == class_val)[0]\n feature_embedding = x_data[tmp_idx]\n feature_embedding = proposed_model[class_val].predict(feature_embedding)\n exacted_data[tmp_idx] = feature_embedding\n del feature_embedding\n\nexacted_data = np.concatenate((info_data, exacted_data), axis=1)\nexacted_data = pd.DataFrame(exacted_data, columns=my_data_columns)\n\n# Write\n# exacted_data.to_csv((dataset_path + 'Diveface_' + dataset_exacted + '_' + exp + '_run_' + str(random_seed) + '(' + filename_comment + ').txt'), header=True, index=False, sep=' ', mode='a')\n\nprint('Finished')\n\n\n","sub_path":"run_experiments/exp_7/exp_7_selected_model_extract_features.py","file_name":"exp_7_selected_model_extract_features.py","file_ext":"py","file_size_in_byte":5170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"538990491","text":"import json\nimport os\nfrom typing import Callable, MutableMapping, MutableSequence, Optional, Sequence, Set, Union\n\nfrom semantic_version import Version\nfrom slicedimage import Collection, TileSet\nfrom slicedimage.io import Reader, resolve_path_or_url, resolve_url\nfrom slicedimage.urlpath import pathjoin\n\nfrom starfish.codebook.codebook import Codebook\nfrom starfish.imagestack.imagestack import ImageStack\nfrom validate_sptx import validate_sptx\nfrom .version import MAX_SUPPORTED_VERSION, MIN_SUPPORTED_VERSION\n\n\nclass FieldOfView:\n \"\"\"\n This encapsulates a field of view. It contains the primary image and auxiliary images that are\n associated with the field of view.\n\n Auxiliary images can be accessed using a key, i.e., FOV[aux_image_type].\n\n Properties\n -------\n name The name of the FOV. In an experiment with only a single FOV, this may\n be None.\n primary_image The primary image for this field of view.\n auxiliary_image_types A set of all the auxiliary image types.\n \"\"\"\n def __init__(\n self,\n name: str,\n primary_image: Optional[ImageStack]=None,\n auxiliary_images: Optional[MutableMapping[str, ImageStack]]=None,\n primary_image_tileset: Optional[TileSet]=None,\n auxiliary_image_tilesets: Optional[MutableMapping[str, TileSet]]=None,\n ) -> None:\n \"\"\"\n Fields of views can obtain their primary image from either an ImageStack or a TileSet (but\n only one). It can obtain their auxiliary image dictionary from either a dictionary of\n auxiliary image name to ImageStack or a dictionary of auxiliary image name to TileSet (but\n only one).\n\n Note that if the source image is from a TileSet, the decoding of TileSet to ImageStack does\n not happen until the image is accessed. Be prepared to handle errors when images are\n accessed.\n \"\"\"\n self._name = name\n self._primary_image: Union[ImageStack, TileSet]\n self._auxiliary_images: MutableMapping[str, Union[ImageStack, TileSet]]\n if primary_image is not None:\n self._primary_image = primary_image\n if primary_image_tileset is not None:\n raise ValueError(\n \"Only one of (primary_image, primary_image_tileset) should be set.\")\n elif primary_image_tileset is not None:\n self._primary_image = primary_image_tileset\n else:\n raise ValueError(\"Field of view must have a primary image\")\n if auxiliary_images is not None:\n self._auxiliary_images = auxiliary_images\n if auxiliary_image_tilesets is not None:\n raise ValueError(\n \"Only one of (auxiliary_images, auxiliary_image_tilesets) should be set.\")\n elif auxiliary_image_tilesets is not None:\n self._auxiliary_images = auxiliary_image_tilesets\n else:\n self._auxiliary_images = dict()\n\n def __repr__(self):\n auxiliary_images = '\\n '.join(f'{k}: {v}' for k, v in self._auxiliary_images.items())\n return (\n f\"\\n\"\n f\" Primary Image: {self._primary_image}\\n\"\n f\" Auxiliary Images:\\n\"\n f\" {auxiliary_images}\"\n )\n\n @property\n def name(self) -> str:\n return self._name\n\n @property\n def primary_image(self) -> ImageStack:\n if isinstance(self._primary_image, TileSet):\n self._primary_image = ImageStack(self._primary_image)\n return self._primary_image\n\n @property\n def auxiliary_image_types(self) -> Set[str]:\n return set(self._auxiliary_images.keys())\n\n def __getitem__(self, item) -> ImageStack:\n if isinstance(self._auxiliary_images[item], TileSet):\n self._auxiliary_images[item] = ImageStack(self._auxiliary_images[item])\n return self._auxiliary_images[item]\n\n\nclass Experiment:\n \"\"\"\n This encapsulates an experiment, with one or more fields of view and a codebook. An individual\n FOV can be retrieved using a key, i.e., experiment[fov_name].\n\n Constructors\n -------\n from_json Given a URL or a path to an experiment.json document, return an Experiment object\n corresponding to the document.\n\n Methods\n -------\n fov Given a callable that accepts a FOV, return the first FOVs that the callable\n returns True when passed the FOV. Because there is no guaranteed sorting for the\n FOVs, use this cautiously.\n fovs Given a callable that accepts a FOV, return all the FOVs that the callable returns\n True when passed the FOV.\n fovs_by_name Given one or more FOV names, return the FOVs that match those names.\n\n Properties\n -------\n codebook Returns the codebook associated with this experiment.\n extras Returns the extras dictionary associated with this experiment.\n \"\"\"\n def __init__(\n self,\n fovs: Sequence[FieldOfView],\n codebook: Codebook,\n extras: dict,\n *,\n src_doc: dict=None,\n ) -> None:\n self._fovs = fovs\n self._codebook = codebook\n self._extras = extras\n self._src_doc = src_doc\n\n def __repr__(self):\n\n # truncate the list of fields of view if it is longer than print_n_fov\n print_n_fov = 4\n n_fields_of_view = list(self.items())[:print_n_fov]\n fields_of_view_str = \"\\n\".join(\n f'{k}: {v}' for k, v in n_fields_of_view\n )\n\n # add an ellipsis if not all fields of view are being printed\n if len(self._fovs) > print_n_fov:\n fov_repr = f\"{{\\n{fields_of_view_str}\\n ...,\\n}}\"\n else:\n fov_repr = f\"{{\\n{fields_of_view_str}\\n}}\"\n\n # return the formatted string\n object_repr = f\"\\n\"\n return object_repr + fov_repr\n\n @classmethod\n def from_json(cls, json_url: str, strict: bool=None) -> \"Experiment\":\n \"\"\"\n Construct an `Experiment` from an experiment.json file format specifier\n\n Parameters\n ----------\n json_url : str\n file path or web link to an experiment.json file\n strict : bool\n if true, then all JSON loaded by this method will be\n passed to the appropriate validator\n\n Returns\n -------\n Experiment :\n Experiment object serving the requested experiment data\n\n Environment variables\n ---------------------\n STARFISH_STRICT_LOADING :\n If set, then all JSON loaded by this method will be\n passed to the appropriate validator. The `strict`\n parameter to this method has priority over the\n environment variable.\n\n \"\"\"\n if strict is None:\n strict = \"STARFISH_STRICT_LOADING\" in os.environ\n if strict:\n valid = validate_sptx.validate(json_url)\n if not valid:\n raise Exception(\"validation failed\")\n\n backend, name, baseurl = resolve_path_or_url(json_url)\n with backend.read_contextmanager(name) as fh:\n experiment_document = json.load(fh)\n\n cls.verify_version(experiment_document['version'])\n\n _, codebook_name, codebook_baseurl = resolve_url(experiment_document['codebook'], baseurl)\n codebook_absolute_url = pathjoin(codebook_baseurl, codebook_name)\n codebook = Codebook.from_json(codebook_absolute_url)\n\n extras = experiment_document['extras']\n\n primary_image: Collection = Reader.parse_doc(experiment_document['primary_images'], baseurl)\n auxiliary_images: MutableMapping[str, Collection] = dict()\n for aux_image_type, aux_image_url in experiment_document['auxiliary_images'].items():\n auxiliary_images[aux_image_type] = Reader.parse_doc(aux_image_url, baseurl)\n\n fovs: MutableSequence[FieldOfView] = list()\n for fov_name, primary_tileset in primary_image.all_tilesets():\n aux_image_tilesets_for_fov: MutableMapping[str, TileSet] = dict()\n for aux_image_type, aux_image_collection in auxiliary_images.items():\n aux_image_tileset = aux_image_collection.find_tileset(fov_name)\n if aux_image_tileset is not None:\n aux_image_tilesets_for_fov[aux_image_type] = aux_image_tileset\n\n fov = FieldOfView(\n fov_name,\n primary_image_tileset=primary_tileset,\n auxiliary_image_tilesets=aux_image_tilesets_for_fov,\n )\n fovs.append(fov)\n\n return Experiment(fovs, codebook, extras, src_doc=experiment_document)\n\n @classmethod\n def verify_version(cls, semantic_version_str: str) -> None:\n version = Version(semantic_version_str)\n if not (MIN_SUPPORTED_VERSION <= version <= MAX_SUPPORTED_VERSION):\n raise ValueError(\n f\"version {version} not supported. This version of the starfish library only \"\n f\"supports formats from {MIN_SUPPORTED_VERSION} to \"\n f\"{MAX_SUPPORTED_VERSION}\")\n\n def fov(\n self,\n filter_fn: Callable[[FieldOfView], bool]=lambda _: True,\n ) -> FieldOfView:\n \"\"\"\n Given a callable filter_fn, apply it to all the FOVs in this experiment. Return the first\n FOV such that filter_fn(FOV) returns True. Because there is no guaranteed order for the\n FOVs, use this cautiously.\n\n If no FOV matches, raise LookupError.\n \"\"\"\n for fov in self._fovs:\n if filter_fn(fov):\n return fov\n raise LookupError(\"Cannot find any FOV that the filter allows.\")\n\n def fovs(\n self,\n filter_fn: Callable[[FieldOfView], bool]=lambda _: True,\n ) -> Sequence[FieldOfView]:\n \"\"\"\n Given a callable filter_fn, apply it to all the FOVs in this experiment. Return a list of\n FOVs such that filter_fn(FOV) returns True.\n \"\"\"\n results: MutableSequence[FieldOfView] = list()\n for fov in self._fovs:\n if not filter_fn(fov):\n continue\n\n results.append(fov)\n return results\n\n def fovs_by_name(self, *names):\n \"\"\"\n Given a callable filter_fn, apply it to all the FOVs in this experiment. Return a list of\n FOVs such that filter_fn(FOV) returns True.\n \"\"\"\n return self.fovs(filter_fn=lambda fov: fov.name in names)\n\n def __getitem__(self, item):\n fovs = self.fovs_by_name(item)\n if len(fovs) == 0:\n raise IndexError(f\"No field of view with name \\\"{item}\\\"\")\n return fovs[0]\n\n def keys(self):\n return (fov.name for fov in self.fovs())\n\n def values(self):\n return (fov for fov in self.fovs())\n\n def items(self):\n return ((fov.name, fov) for fov in self.fovs())\n\n @property\n def codebook(self) -> Codebook:\n return self._codebook\n\n @property\n def extras(self):\n return self._extras\n","sub_path":"starfish/experiment/experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":11214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"431466090","text":"#!/usr/bin/env python3\n\n\"\"\"Module with unit tests for base.\n\n..moduleauthor:: Timothy Helton \n\"\"\"\n\nimport base\nimport nose\nfrom nose.tools import raises, with_setup, eq_, ok_\nimport numpy as np\nimport os\nimport shutil\nimport sys\nimport magic\n\n\n__version__ = '0.2.0'\nscript_name = 'Unit Tests for base Module'\n\n\nclass TestPreserveCWD:\n\n def __init__(self):\n self.original_dir = os.getcwd()\n self.working_dir = os.path.join(self.original_dir, 'junk')\n self.file_name = 'junk.txt'\n\n def setup(self):\n os.makedirs(self.working_dir, exist_ok=True)\n\n def teardown(self):\n shutil.rmtree(self.working_dir)\n\n @with_setup(setup, teardown)\n def test__no_arguments(self):\n\n @base.preserve_cwd(self.working_dir)\n def test():\n f = open(self.file_name, 'w')\n f.close()\n\n test()\n eq_(os.path.isfile(os.path.join(self.working_dir, self.file_name)),\n True)\n\n actual = os.getcwd()\n expected = self.original_dir\n eq_(actual, expected,\n '\\nactual: {}\\nexpected: {}'.format(actual, expected))\n\n\nclass TestNotifyCenter:\n\n @raises(AttributeError)\n def test__center_empty(self):\n base.Notify().center()\n\n @staticmethod\n def test__center_one_word():\n base.Notify('one').center(width=7)\n output = sys.stdout.getvalue().strip()\n eq_(output, '= one =')\n\n @staticmethod\n def test__center_two_word():\n base.Notify('one two').center(width=11)\n output = sys.stdout.getvalue().strip()\n eq_(output, '= one two =')\n\n\nclass TestNotifyHeader:\n\n @staticmethod\n def test__header_empty():\n base.Notify().header()\n output = sys.stdout.getvalue().strip()\n eq_(output, ('*' * 80 + '\\n' +\n 'Begin Execution of: None, Version None'))\n\n\nclass TestNotifyFooter:\n\n @staticmethod\n def test__header_empty():\n base.Notify().footer()\n output = sys.stdout.getvalue().strip()\n eq_(output, ('Completed Execution of: None, Version None\\n' +\n '*' * 80))\n\n\nclass TestNotifyUpdate:\n\n @raises\n def test__update_empty(self):\n base.Notify().update()\n\n @staticmethod\n def test__update_one_word():\n base.Notify('one').update(width=7)\n output = sys.stdout.getvalue().strip()\n eq_(output, '- One -')\n\n @staticmethod\n def test__update_two_word():\n base.Notify('one two').update(width=11)\n output = sys.stdout.getvalue().strip()\n eq_(output, '- One Two -')\n\n\nclass TestNotifyWarn:\n\n @raises\n def test__warn_empty(self):\n base.Notify().warn()\n\n @staticmethod\n def test__warn_one_word():\n base.Notify('one').warn()\n output = sys.stdout.getvalue().strip()\n eq_(output, '!' * 21 + ' \\x1b[5m\\x1b[31mONE\\x1b[0m ' + '!' * 21)\n\n @staticmethod\n def test__warn_two_word():\n base.Notify('one two').warn()\n output = sys.stdout.getvalue().strip()\n eq_(output, '!' * 19 + ' \\x1b[5m\\x1b[31mONE TWO\\x1b[0m ' + '!' * 19)\n\n\nclass TestOSLoadLines:\n\n @classmethod\n def setup_class(cls):\n f = open('test.txt', 'w')\n f.write('line one\\n')\n f.write('line two\\n')\n f.close()\n\n @classmethod\n def teardown_class(cls):\n os.remove(os.path.join(os.getcwd(), 'test.txt'))\n\n @staticmethod\n def test__load_file():\n o = base.OS(read_file='test.txt')\n o.load_lines()\n eq_(o.lines, ['line one\\n', 'line two\\n'])\n\n\nclass TestOSLoadText:\n\n @classmethod\n def setup_class(cls):\n lines = ['a\\tb\\tc\\td\\n', '\\n', '1\\t2\\t3\\t4\\n', '5\\t6\\t7\\t8\\n']\n\n f = open('test.txt', 'w')\n for line in lines:\n f.write(line)\n f.close()\n\n f_no_header = open('test_no_header.txt', 'w')\n for line in lines[2:]:\n f_no_header.write(line)\n f_no_header.close()\n\n @classmethod\n def teardown_class(cls):\n os.remove('test.txt')\n os.remove('test_no_header.txt')\n\n @staticmethod\n def test__load_records_header_all_columns():\n o = base.OS(read_file='test.txt', header_rows=2)\n o.load_records()\n expected_a = np.array([1.0, 5.0])\n ok_(np.all(o.array['a'] == expected_a),\n '\\nactual: {}\\nexpected: {}'.format(o.array['a'], expected_a))\n expected_d = np.array([4.0, 8.0])\n ok_(np.all(o.array['d'] == expected_d),\n '\\nactual: {}\\nexpected: {}'.format(o.array['d'], expected_d))\n\n @staticmethod\n def test__load_records_header_some_columns():\n o = base.OS(read_file='test.txt', header_rows=2, cols=[0, 3])\n o.load_records()\n expected_a = np.array([1.0, 5.0])\n ok_(np.all(o.array['a'] == expected_a),\n '\\nactual: {}\\nexpected: {}'.format(o.array['a'], expected_a))\n expected_d = np.array([4.0, 8.0])\n ok_(np.all(o.array['d'] == expected_d),\n '\\nactual: {}\\nexpected: {}'.format(o.array['d'], expected_d))\n\n @staticmethod\n def test__load_records_header_all_columns_define_formats():\n o = base.OS(read_file='test.txt', header_rows=2,\n formats=['f8', 'i4', 'f8', 'i4'])\n o.load_records()\n expected_a = np.array([1.0, 5.0])\n ok_(np.all(o.array['a'] == expected_a),\n '\\nactual: {}\\nexpected: {}'.format(o.array['a'], expected_a))\n expected_d = np.array([4, 8])\n ok_(np.all(o.array['d'] == expected_d),\n '\\nactual: {}\\nexpected: {}'.format(o.array['d'], expected_d))\n\n @staticmethod\n def test__load_records_no_header():\n o = base.OS(read_file='test_no_header.txt', cols=[0, 3])\n o.load_records()\n expected_0 = np.array([1.0, 5.0])\n ok_(np.all(o.array['0'] == expected_0),\n '\\nactual: {}\\nexpected: {}'.format(o.array['0'], expected_0))\n expected_3 = np.array([4.0, 8.0])\n ok_(np.all(o.array['3'] == expected_3),\n '\\nactual: {}\\nexpected: {}'.format(o.array['3'], expected_3))\n\n\nclass TestOSUnzipFile:\n\n def __init__(self):\n self.file_name = 'junk.txt'\n\n def setup(self):\n with open(self.file_name, 'w') as f:\n f.write('Test file')\n f.close()\n base.OS(self.file_name).zip_file()\n\n def teardown(self):\n try:\n os.remove(self.file_name)\n except OSError:\n os.remove('{}.gz'.format(self.file_name))\n\n def test__normal_operation(self):\n base.OS('{}.gz'.format(self.file_name)).unzip_file()\n with magic.Magic() as m:\n name = m.id_filename(self.file_name)\n ok_(name.startswith('ASCII'))\n\n @raises(OSError)\n def test__try_to_unzip_decompressed_file(self):\n base.OS('{}.gz'.format(self.file_name)).unzip_file()\n base.OS(self.file_name).unzip_file()\n\n @raises(OSError)\n def test__try_to_zip_nonexistent_file(self):\n base.OS('does_not_exist.txt').zip_file()\n\n\nclass TestOSZipFile:\n\n def __init__(self):\n self.file_name = 'junk.txt'\n\n def setup(self):\n with open(self.file_name, 'wb') as f:\n f.close()\n\n def teardown(self):\n try:\n os.remove(self.file_name)\n except OSError:\n os.remove('{}.gz'.format(self.file_name))\n\n def test__normal_operation(self):\n base.OS(self.file_name).zip_file()\n with magic.Magic() as m:\n name = m.id_filename('{}.gz'.format(self.file_name))\n ok_(name.startswith('gzip'))\n\n @raises(OSError)\n def test__try_to_zip_zipped_file(self):\n base.OS(self.file_name).zip_file()\n base.OS('{}.gz'.format(self.file_name)).zip_file()\n\n @raises(OSError)\n def test__try_to_zip_nonexistent_file(self):\n base.OS('does_not_exist.txt').zip_file()\n\n\nclass TestPlotCreateAxisTitle:\n\n def __init__(self):\n self.output = ''\n\n def test__create_axis_title_no_units(self):\n p = base.Plot(x_title='test')\n self.output = p.create_axis_title(p.x_title, p.x_units)\n eq_(self.output, 'Test')\n\n def test__create_axis_title_two_words(self):\n p = base.Plot(x_title='test two')\n self.output = p.create_axis_title(p.x_title, p.x_units)\n eq_(self.output, 'Test Two')\n\n def test__create_axis_title_two_words_plus_units(self):\n p = base.Plot(x_title='test two', x_units='num/den')\n self.output = p.create_axis_title(p.x_title, p.x_units)\n eq_(self.output, 'Test Two (num/den)')\n\n\nclass TestPlotCreateSuperTitle:\n\n def __init__(self):\n self.output = ''\n\n def test__create_super_title_one_word_plus_units(self):\n p = base.Plot(x_title='x', x_units='num/den',\n y_title='y', y_units='num/den')\n p.create_super_title()\n self.output = p.super_title\n eq_(self.output, 'Y vs. X')\n\n def test__create_super_title_two_words_plus_units(self):\n p = base.Plot(x_title='x x', x_units='num/den',\n y_title='y y', y_units='num/den')\n p.create_super_title()\n self.output = p.super_title\n eq_(self.output, 'Y Y vs. X X')\n\n\nif __name__ == '__main__':\n nose.main()","sub_path":"python/tests/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":9196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"182498998","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : hyper_params.py\n# @Author: harry\n# @Date : 2019/4/23 下午12:15\n# @Desc : Hyper parameters definition\n\nEMBEDDING_SIZE = 100\nLSTM_UNITS = 128\nDENSE_UNITS = 256\nLEARNING_RATE = 0.001\n\n# Gradient Clipping is IMPORTANT!!!!!!\nCLIP_NORM = 1.0\n\nMARGIN = 0.5\nREG_LAMBDA = 0.00004\n","sub_path":"MANN_SA/hyper_params.py","file_name":"hyper_params.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"397686312","text":"import numpy as np\nimport pandas as pd\nimport spotipy\nimport sys\nimport time\nimport pprint\nfrom spotipy.oauth2 import SpotifyClientCredentials\n\ndef create_spotify_instance(id_key, secret_key):\n client_credentials_manager = SpotifyClientCredentials(client_id, client_secret)\n sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\n return sp\n\n\n\ndef import_track_CSV(path):\n df = pd.read_csv(path)\n return df\n\ndef create_track_list(df):\n track_list = []\n\n for i in df['track_id']:\n track_list.append(i)\n return track_list\n\n\ndef create_audio_feature_column(df, str_aud_feature, track_list):\n if 'Unnamed: 0' in df.columns:\n df = df.drop(['Unnamed: 0'], axis=1)\n feature_dict = {}\n else:\n feature_dict = {}\n\n for i in track_list[0:10]:\n feature_dict[i] = feature_dict.get(i, sp.audio_features(i)[0][str_aud_feature])\n\n df_feature = pd.DataFrame.from_dict(feature_dict,orient='index').reset_index().rename(columns={'index': 'track_id', 0: str_aud_feature})\n df_final = df.merge(df_feature, on='track_id')\n return df_final\n\n\ndef DataFrame_to_CSV(df, path):\n return df.to_csv(path)\n\n# danceability, energy, key, loudness, mode, speechiness, acoustincess, instrumentalness, liveness, valence, tempo, duration_ms, time_signature\n\ndef main():\n client_id = 'f1e0972287e94005ab6fe832983b376c'\n client_secret = 'daf5efbba5044c5cb1362a8a3609ab2d'\n sp = create_spotify_instance(client_id, client_secret)\n df_info = import_track_CSV('~/galvanize/capstones/capstone_1/track_list.csv')\n track_list = create_track_list(df_info)\n df_danceability = create_audio_feature_column(df_info, 'danceability', track_list)\n df_energy = create_audio_feature_column(df_danceability, 'energy', track_list)\n df_key = create_audio_feature_column(df_energy, 'key', track_list)\n df_loudness = create_audio_feature_column(df_key, 'loudness', track_list)\n df_mode = create_audio_feature_column(df_loudness, 'mode', track_list)\n df_speechiness = create_audio_feature_column(df_mode, 'speechiness', track_list)\n df_acousticness = create_audio_feature_column(df_speechiness, 'acousticness', track_list)\n df_instrumentalness = create_audio_feature_column(df_acousticness, 'instrumentalness', track_list)\n df_liveness = create_audio_feature_column(df_instrumentalness, 'liveness', track_list)\n df_valence = create_audio_feature_column(df_liveness, 'valence', track_list)\n df_tempo = create_audio_feature_column(df_valence, 'tempo', track_list)\n df_duration = create_audio_feature_column(df_tempo, 'duration_ms', track_list)\n DataFrame_to_CSV(df_duration, \"~/galvanize/capstones/capstone_1/DF_w_AudioFeatres.csv\")\nif __name__ == \"__main__\":\n main()\n","sub_path":"old_code/Create_Feature_DataFrame.py","file_name":"Create_Feature_DataFrame.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"535811572","text":"##---------------------\n# Cap5 - Instruções If\n# toppings.py, p.133\n##---------------------\n\n# Lista de ingredientes\nrequested_toppings = ['mushrooms', 'green peppers', 'extra cheese']\n\n# Laço for, incluindo ingrediente faltante\nfor requested_topping in requested_toppings:\n if requested_topping == 'green peppers':\n print('Sorry, we are out of green peppers right now.')\n else:\n print('Adding ' + requested_topping + '.')\n","sub_path":"05_Instruções_if/toppings.py","file_name":"toppings.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"430402486","text":"import requests\nimport sys\n\nres = requests.post(\"http://localhost/ppm-api/upload.php\", files={'target': open(sys.argv[1],'rb')})\nif(res.text == \"UPLOADED\"):\n exit(0)\nelif(res.text == \"FILE_EXIST\"):\n exit(1)\nelse:\n exit(2)","sub_path":"src/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"77748638","text":"import numpy as np\nimport random as rd\nimport math\n\n# File created on April 15th\n# contains my own implementations of deep neural net models\n\n# implements forward/back propagation, optimization using\n# variants of gradient descent\n\n@np.vectorize # using numpy vectorization as decorator\ndef linear(x):\n return x\n@np.vectorize\ndef relu(x):\n return max(0,x)\n@np.vectorize\ndef softplus(x):\n return math.log(1+math.exp(x))\n@np.vectorize\ndef sigmoid(x):\n return 1/(1+math.exp(-x))\n@np.vectorize\ndef tanh(x):\n return math.tanh(x)\n\n# activation functions\nafuncs = [linear,\n relu,\n softplus,\n sigmoid,\n tanh]\n\n@np.vectorize\ndef dlinear(x):\n return 1\n@np.vectorize\ndef drelu(x):\n return (x>=0)*1.\n@np.vectorize\ndef dsoftplus(x):\n return 1/(1+math.exp(-x)) \n@np.vectorize\ndef dsigmoid(x):\n sigm = 1/(1+math.exp(-x))\n return sigm*(1-sigm)\n@np.vectorize\ndef dtanh(x):\n return 1-math.tanh(x)**2\n\n# derivatives of activation functions\nafuncs_prime = [dlinear,\n drelu,\n dsoftplus,\n dsigmoid,\n dtanh]\n\ndef softmax(H):\n H_stable = H - H.max(axis=0, keepdims=True) \n return np.exp(H_stable)/np.exp(H_stable).sum(axis=0,keepdims=True)\n\nclass Layer:\n # The class Layer implements a single Layer\n # of a neutral network. Specifically, it is\n # designed to carry out the following:\n # 1. Initialize a Layer with random weights\n # The constructor can create a Layer\n # given the dimension of the input and\n # the number of nodes in the Layer, and\n # automatically randomize the weights to\n # small non-zero values.\n # 2. Compute the output of the Layer\n # The output h(x) = a(Wx+b), where \"W\"\n # denotes the weights, \"b\" denotes the\n # bias, and \"a\" denotes activation\n # function\n # 3. Update the weights in back propagation\n # Given the gradient of the loss gunction with\n # respect to each node, update its corresponding\n # weights and bias\n\n \n # activation_option = 0 : linear (no activation) is used\n # activation_option = 1 : rectified linear unit is used\n # activation_option = 2 : softplus unit is used\n # activation_option = 3 : logistic sigmoidal unit is used\n # activation_option = 4 : hyperbolic tangent unit is used\n def __init__(self, input_dimension, number_of_nodes, activation_option): \n # To create an Layer object, user should provide the dimension of\n # the input vectors, the number of nodes in the Layer, and which\n # activation function should be used.\n \n #*********** guard statements against invalid inputs\n if not (isinstance(input_dimension,int) and (input_dimension>0)):\n raise ValueError(\"input_dimension must be a positive integer\")\n if not (isinstance(number_of_nodes,int) and (number_of_nodes>0)):\n raise ValueError(\"number_of_nodes must be a positive integer\")\n if not (activation_option in range(5)):\n raise ValueError(\n \"activation_option must be 0-4:\\n\\\n activation_ption = 0 : linear (no activation) is used\\n\\\n activation_ption = 1 : rectified linear unit is used\\n\\\n activation_ption = 2 : softplus unit is used\\n\\\n activation_ption = 3 : logistic sigmoidal unit is used\\n\\\n activation_ption = 4 : hyperbolic tangent unit is used\"\n )\n #***************************************************\n self.option = activation_option\n self.dim = input_dimension\n self.width = number_of_nodes\n self.reset()\n self.afunc = afuncs[self.option]\n self.afunc_prime = afuncs_prime[self.option]\n def import_parameters(self,weights,bias,activation_option):\n #Guard against invalid inputs*************************\n if not (isinstance(weights,np.ndarray) and isinstance(bias,np.ndarray)):\n raise ValueError(\"weights and bias must be rank 2 numpy arrays\")\n if (weights.shape[0]!=bias.shape[0]):\n raise ValueError(\"Invalid inputs:\\n weights and bias dimensions do not match\")\n if not (activation_option in range(5)):\n raise ValueError(\n \"activation_option must be 0-4:\\n\\\n activation_ption = 0 : linear (no activation) is used\\n\\\n activation_ption = 1 : rectified linear unit is used\\n\\\n activation_ption = 2 : softplus unit is used\\n\\\n activation_ption = 3 : logistic sigmondal unit is used\\n\\\n activation_ption = 4 : hyperbolic tangent unit is used\"\n )\n #*****************************************************\n self.weights = weights\n self.bias = bias\n self.dim = weights.shape[1]\n self.width = bias.shape[0]\n self.option = activation_option\n self.afunc = afuncs[self.option]\n self.afunc_prime = afunc_prime[self.option]\n\n def export(self):\n # returns an object that stores all the layer information\n return [self.weights, self.bias, self.option]\n \n def reset(self):\n # resets the weights to random small values and the bias to 0\n self.weights = 0.1*np.random.randn(self.width,self.dim)\n self.bias = np.zeros((self.width,1))+0.1\n \n def evaluate(self, X):\n # Calling this functino will use forward propagation\n # to compute the output of this layer given the input\n # matrix X, where each column of X represents a different\n # input.\n # The output matrix Y returned by this function is\n # strucctured such that Y[i,j] stores the output of\n # the ith node given the jth input vector\n\n # Guard against invalid inputs ***********************\n if not isinstance(X,np.ndarray):\n raise ValueError('The only supported Type for X is rank 2 numpy array')\n if X.shape[0]!=self.dim:\n raise ValueError('Input Dimension Mismatch\\nThis layer only accept {}-dimensional inputs'\\\n .format(self.dim))\n #*****************************************************\n # print('evaluating...')\n # implements y = a(Wx + b), broadcasting this equation\n # for all input vectors in X\n self.X = X\n self.Z = self.weights@X + self.bias\n return self.afunc(self.Z)\n \n def update(self,gradient,learning_rate):\n # Calling this function will update the weights and\n # bias in this Layer, given the gradient of the loss\n # function J(w,b,x) with respect to Y(W,b,x), and the\n # hyper-parameter learning_rate\n if not isinstance(gradient,np.ndarray):\n raise ValueError('The only supported Type for gradient is numpy ndarray')\n if gradient.shape != self.Z.shape:\n raise ValueError('Gradient dimension mismatch\\n This layer has {} nodes'.format(self.width))\n if learning_rate<0 or learning_rate>0.1:\n raise ValueError(\"learning rate must be a small positive value\")\n self.weights -= learning_rate*(gradient*self.afunc_prime(self.Z))@self.X.transpose() \n self.bias -= learning_rate*(gradient*self.afunc_prime(self.Z)).sum(axis=1,keepdims=True)\n \n def backprop(self,gradient):\n # Calling this function will calculate the gradient\n # of the loss function with respect to the inputs\n # to this layer, using the chain rule and back-propagation\n # technique.\n pre_gradient = self.weights.transpose()@(self.afunc_prime(self.Z)*gradient)\n return pre_gradient\n \n def __str__(self):\n afunc_names = ['linear units',\n 'rectified linear units',\n 'softplus units',\n 'logistic sigmoids',\n 'hyperbolic tangents']\n str1 = 'The weights are:\\n{}\\n'.format(self.weights)\n str2 = 'The bias are:\\n{}\\n'.format(self.bias)\n str3 = 'The activation function is: {}'.format(afunc_names[self.option])\n return str1+str2+str3\n \n \n @property\n def weights(self):\n return self.__weights\n @weights.setter\n def weights(self,weights):\n self.__weights = weights\n @property\n def bias(self):\n return self.__bias\n @bias.setter\n def bias(self,bias):\n self.__bias = bias\n @property\n def option(self):\n return self.__option\n @option.setter\n def option(self,option):\n self.__option = option\n\n\n# loss functions******************************************************\n# and gradient of loss functions\ndef MSE(H,Y):\n # defines the mean square error\n # loss function. It is the avg\n # L2 distance between predicted\n # value h_i and observed value\n # y_i\n L2 = ((H-Y)**2).sum(axis=0)\n return 0.5*L2.mean()\n\ndef gMSE(H,Y):\n # calculates the gradient of the\n # MSE loss function, used for\n # regression problems\n return (H-Y)/H.shape[1]\n \n\ndef x_entropy(H,Y):\n # defines the cross entropy loss\n # function, used for classification\n # problems.\n # calculates the cross entropy\n # between predicted distribution P\n # and observed distribution Y,\n # where H = log(P'), P' is the\n # unnormalized version of P\n if H.shape[0]==1:\n arg = H*(1-2*Y)\n return np.sum(softplus(arg))\n else:\n H_stable = H - H.max(axis = 0, keepdims = True)\n log_P = H_stable - np.log(np.exp(H_stable).sum(axis = 0, keepdims = True))\n return np.sum(Y*(-log_P))\n \n\ndef gx_entropy(H,Y):\n # calculates the gradient of the\n # cross entropy loss function\n if H.shape[0]==1:\n return sigmoid(H)-Y\n else:\n return softmax(H)-Y\n\noutput_units = [linear,\n sigmoid,\n softmax]\n\n\nclass DeepNeuralNet:\n # The class contains at least 0 hidden layer\n # and exactly 1 output layer\n\n # To create a dnn object, specify the structure\n # and the output units of the network. The class\n # will automatically initiate the weights and\n # bias in each layer. The loss function should\n # also be provided.\n \n # 'structure' has the basic type of python 'tuple',\n # the ith element of the tuple stores the\n # number of nodes that should be created in the\n # (i+1)th layer. Note that tuple index starts\n # with 0 whereas neural net layers starts with\n # 1.\n\n # output_unit_option:\n # 0--> linear units are used\n # 1--> logistic sigmoid units are used\n # 2--> softmax units are used\n\n # loss_func_option:\n # 0--> Mean square Error loss is used\n # 1--> Cross entropy loss is used\n def __init__(self, input_D, output_D, structure, output_unit_option):\n self.depth = len(structure)\n self.hidden_units = []\n iDim = input_D\n for L in structure:\n if isinstance(L,int):\n # layer uses relu activation as default\n new_layer = Layer(iDim, L, 1)\n self.hidden_units.append(new_layer)\n iDim = L\n elif isinstance(L,tuple) and len(L)==2:\n # assuming the activation function is specified\n new_layer = Layer(iDim, L[0], L[1])\n self.hidden_units.append(new_layer)\n iDim = L[0]\n else:\n raise ValueError('Invalid structure')\n\n self.output_layer = Layer(iDim,output_D,0)\n self.output_type = output_unit_option\n self.output_unit = output_units[output_unit_option]\n\n if output_unit_option==0:\n self.loss_func = MSE\n self.gloss_func = gMSE\n elif output_unit_option==1:\n self.loss_func = x_entropy\n self.gloss_func = gx_entropy\n elif output_unit_option==2:\n self.loss_func = x_entropy\n self.gloss_funnc = x_entropy\n else:\n raise ValueError('Invalid option for output unit!!')\n # gloss_func abbreviates 'gradient of the loss function'\n\n def save(self, model_id):\n model = {\n \"layers\": [x.export() for x in self.hidden_units],\n \"output_layer\": self.output_layer.export(),\n \"output_type\": self.output_type\n }\n filename = str(model_id) + \".npy\"\n np.save(filename, model)\n\n def load(self, model_id):\n filename = str(model_id) + \".npy\"\n model = np.load(filename).item()\n output_unit_option = model[\"output_type\"]\n\n self.hidden_units = []\n self.output_layer = Layer(1, 1, 0)\n for parameters in model[\"layers\"]:\n self.hidden_units.append(Layer(1, 1, 0))\n self.hidden_units[-1].import_parameters(\n parameters[0],\n parameters[1],\n parameters[2],\n )\n self.output_layer.import_parameters(\n model[\"output_layer\"][0],\n model[\"output_layer\"][1],\n model[\"output_layer\"][2]\n )\n\n if output_unit_option==0:\n self.loss_func = MSE\n self.gloss_func = gMSE\n elif output_unit_option==1:\n self.loss_func = x_entropy\n self.gloss_func = gx_entropy\n elif output_unit_option==2:\n self.loss_func = x_entropy\n self.gloss_funnc = x_entropy\n else:\n raise ValueError('Invalid option for output unit!!')\n \n def train(self,X,Y,learning_rate,iterations):\n # learns the mapping from input X to output Y,\n # using (stochastic) gradient descent\n J = []\n for i in range(iterations):\n # forward propagation:\n A = X\n for j in self.hidden_units:\n A = j.evaluate(A)\n H = self.output_layer.evaluate(A)\n J.append(self.loss_func(H,Y))\n # gH = gradient_H(J)\n gH = self.gloss_func(H,Y)\n #print(gH)\n\n # backward propagation:\n self.output_layer.update(gH,learning_rate)\n gA = self.output_layer.backprop(gH)\n\n for k in self.hidden_units[::-1]:\n k.update(gA,learning_rate)\n if k!=self.hidden_units[0]:\n gA = k.backprop(gA)\n return J\n\n def predict(self,X):\n A = X\n for j in self.hidden_units:\n A = j.evaluate(A)\n H = self.output_layer.evaluate(A)\n Y_predicted = self.output_unit(H)\n return Y_predicted\n","sub_path":"scripts/segments/neural_net.py","file_name":"neural_net.py","file_ext":"py","file_size_in_byte":14606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"469118248","text":"#\n# Copyright (c) 2019, Neptune Labs Sp. z o.o.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport os\nimport sys\n\nimport click\n\nimport neptune\nfrom neptune_mlflow.data_loader import DataLoader\n\n\ndef sync(path, project):\n if path is None:\n path = \".\"\n\n if not os.path.exists(path):\n click.echo(\"ERROR: Directory `{}` doesn't exist\".format(path), err=True)\n sys.exit(1)\n\n if not os.path.isdir(path):\n click.echo(\"ERROR: `{}` is not a directory\".format(path), err=True)\n sys.exit(1)\n\n if not os.path.exists(os.path.join(path, \"mlruns\")):\n click.echo(\"ERROR: No 'mlruns' directory in {}\".format(path), err=True)\n sys.exit(1)\n\n project = neptune.init(project_qualified_name=project)\n\n loader = DataLoader(project, path)\n loader.run()\n","sub_path":"neptune_mlflow/sync.py","file_name":"sync.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"148892479","text":"import matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\nimport pdb\nimport numpy\n\n\ndef plot_history(history):\n plt.plot(history.history['accuracy'])\n plt.plot(history.history['val_accuracy'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n # summarize history for loss\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.show()\n\nclass SetTrace(keras.callbacks.Callback):\n def on_train_begin(self, logs={}):\n pass\n\n def on_batch_end(self, batch, logs={}):\n model = self.model\n pdb.set_trace()\n\nclass ModelOutput:\n ''' Class wrapper for a metric that stores the output passed to it '''\n def __init__(self, name):\n self.name = name\n self.y_true = None\n self.y_pred = None\n\n def save_output(self, y_true, y_pred):\n self.y_true = y_true\n self.y_pred = y_pred\n return tf.constant(True)\n\nclass ModelOutputCallback(tf.keras.callbacks.Callback):\n def __init__(self, model_outputs):\n tf.keras.callbacks.Callback.__init__(self)\n self.model_outputs = model_outputs\n\n def on_train_batch_end(self, batch, logs=None):\n pass\n # use self.model_outputs to get the outputs here\n\n","sub_path":"depricated/network_debugging.py","file_name":"network_debugging.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"176702110","text":"from pandas import DataFrame\nimport sys\n\nsys.stdin = open('input.txt')\n\ndef solution(arr):\n\n for i in range(9):\n\n h_list_row = []\n h_list_col = []\n\n for j in range(9):\n\n if arr[i][j] in h_list_row:\n return 0\n else:\n h_list_row.append(arr[i][j])\n\n if arr[j][i] in h_list_col:\n return 0\n else:\n h_list_col.append(arr[j][i])\n\n for i in [0, 3, 6]:\n\n small_sq1 = []\n small_sq2 = []\n small_sq3 = []\n\n for j in range(3):\n\n for k in range(3):\n if arr[i+j][k] in small_sq1:\n return 0\n else:\n small_sq1.append(arr[i + j][k])\n\n for k in range(3, 6):\n\n if arr[i+j][k] in small_sq2:\n return 0\n else:\n small_sq2.append(arr[i + j][k])\n\n for k in range(6, 9):\n\n if arr[i+j][k] in small_sq3:\n return 0\n else:\n small_sq3.append(arr[i + j][k])\n\n return 1\n\nT = int(input())\n\nfor t in range(1, T+1):\n arr = []\n for _ in range(9):\n arr.append(list(map(int, input().split())))\n print('#{} {}'.format(t, solution(arr)))\n\n\n\n","sub_path":"python/SWEA/2021.02.25/스도쿠 검증/sol1.py","file_name":"sol1.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"103401123","text":"#!/usr/bin/env python\nimport tornado.web\n\nclass BaseHandler(tornado.web.RequestHandler):\n def get_current_user(self):\n uc = self.get_secure_cookie(\"user\")\n ret = None\n if uc is not None:\n ret = tornado.escape.json_decode(uc)\n \n return ret \n","sub_path":"QEServer/qe/handlers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"543201258","text":"# Import Required Libraries and Functions\nfrom Speech2Text import speech2Text\nfrom code import type_code\nimport threading\nimport time\n\n# +++++++++++++++++++++++++ Code Thread ++++++++++++++++++++++++++++++++++++++++++++++\nclass CodeThread(threading.Thread):\n def __init__(self,toolinfo,flag,text_box,trigger_function):\n threading.Thread.__init__(self)\n self.setDaemon(True)\n #flag to pause thread\n self.paused = False\n self.pause_cond = threading.Condition(threading.Lock())\n self.toolinfo = toolinfo\n self.flag = flag\n self.text_box = text_box\n self.trigger_function = trigger_function\n\n # [ Function to start the thread ]\n def run(self):\n while True:\n with self.pause_cond:\n while self.paused:\n self.pause_cond.wait()\n if self.flag == 1:\n self.toolinfo.configure(text='State: Listening')\n text = speech2Text()\n if text == -1:\n if self.flag == 1:\n self.toolinfo.configure(text=\"Error: Didn't understand, Please try again\")\n time.sleep(2)\n else:\n type_code(self.text_box,self.trigger_function,text)\n\n # [ Function to pause the Thread ]\n def pause(self):\n if self.flag == 1:\n self.toolinfo.configure(text=\"State: - - -\")\n self.flag = 0\n self.paused = True\n self.pause_cond.acquire()\n\n # [ Function to resume the Thread ]\n def resume(self):\n self.paused = False\n # Notify so thread will wake after lock released\n self.pause_cond.notify()\n # Now release the lock\n self.pause_cond.release()\n self.flag = 1\n\n# This is Just a Thread and doesn't work on itself\nif __name__=='__main__':\n print(\"This Process doesn't run on its own.\")","sub_path":"codeThread.py","file_name":"codeThread.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"599668410","text":"import os\n\nimport joblib\nfrom azureml.core import Datastore, Dataset, Run\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import f1_score\n\nfrom my_custom_package.utils.const import TRAINING_DATASTORE, MODEL_NAME\nfrom my_custom_package.utils.transform_data import remove_collinear_cols\n\n\n__here__ = os.path.dirname(__file__)\n\n\ndef get_df_from_datastore_path(datastore, datastore_path):\n # In our example we only have single files,\n # but these may be daily data dumps\n datastore_path = [(datastore, datastore_path)]\n dataset = Dataset.Tabular.from_delimited_files(\n path=datastore_path\n )\n dataframe = dataset.to_pandas_dataframe()\n return dataframe\n\n\ndef prepare_data(workspace):\n datastore = Datastore.get(workspace, TRAINING_DATASTORE)\n x_train = get_df_from_datastore_path(datastore, 'train/X_train.csv')\n y_train = get_df_from_datastore_path(datastore, 'train/y_train.csv')\n y_train = y_train['Target']\n x_test = get_df_from_datastore_path(datastore, 'test/X_test.csv')\n y_test = get_df_from_datastore_path(datastore, 'test/y_test.csv')\n y_test = y_test['Target']\n x_train = remove_collinear_cols(x_train)\n x_test = remove_collinear_cols(x_test)\n return x_train, y_train, x_test, y_test\n\n\ndef train_model(x_train, y_train):\n classifier = LogisticRegression()\n classifier.fit(x_train, y_train)\n return classifier\n\n\ndef evaluate_model(classifier, x_test, y_test, run):\n y_pred = classifier.predict(x_test)\n model_f1_score = f1_score(y_test, y_pred)\n run.log('F1_Score', model_f1_score)\n\n\ndef save_model(classifer):\n output_dir = os.path.join(__here__, 'outputs')\n os.makedirs(output_dir, exist_ok=True)\n model_path = os.path.join(output_dir, 'model.pkl')\n joblib.dump(classifer, model_path)\n return model_path\n\n\ndef register_model(run, model_path):\n run.upload_file(model_path, \"outputs/model.pkl\")\n model = run.register_model(\n model_name=MODEL_NAME,\n model_path=\"outputs/model.pkl\"\n )\n run.log('Model_ID', model.id)\n\n\ndef main():\n run = Run.get_context()\n workspace = run.experiment.workspace\n x_train, y_train, x_test, y_test = prepare_data(workspace)\n classifier = train_model(x_train, y_train)\n evaluate_model(classifier, x_test, y_test, run)\n model_path = save_model(classifier)\n register_model(run, model_path)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/my_custom_package/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"532849348","text":"from django import template\n\n\nregister = template.Library()\n\n\n@register.filter(name='my_date')\ndef my_date(value1, message):\n return \"Hello\" + str(value1) + message\n\n\nclass MyTag(template.Node):\n def __init__(self, name):\n self.name = name\n\n def render(self, context):\n name = context.get(self.name)\n return \"Hello, {}\".format(name)\n\n\n@register.tag()\ndef mytag(parser, token):\n try:\n tag_name, variable = token.split_contents()\n except:\n raise template.TemplateSyntaxError()\n\n return MyTag(variable)\n\n\nclass MyIfTag(template.Node):\n def __init__(self, var, truetext):\n self.var = var\n self.truetext = truetext\n\n def render(self, context):\n if self.var:\n return self.truetext[0].render(None)\n else:\n return str()\n\n\n@register.tag()\ndef myif(parser, token):\n try:\n body = parser.parse(('endmyif', ))\n parser.delete_first_token()\n tag_name, var = token.split_contents()\n except:\n raise template.TemplateSyntaxError()\n\n return MyIfTag(var, body)\n\n\nclass MyForTag(template.Node):\n def __init__(self, array, var, text):\n self.array = array\n self.text = text\n self.var = var\n\n def render(self, context):\n values = context[self.array]\n output = \"\"\n print(dir(self.text))\n for i in values:\n\n output += self.text.render({self.var: str(i)})\n return output\n\n\n@register.tag()\ndef myfor(parser, token):\n try:\n body = parser.parse(('endmyfor', ))\n parser.delete_first_token()\n var = token.split_contents()\n except Exception as e:\n raise template.TemplateSyntaxError(e)\n\n return MyForTag(var[1], var[3], body)\n","sub_path":"on_lesson/django_filters/filters/filters_app/templatetags/myfilters.py","file_name":"myfilters.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"436402117","text":"#addresses and commands for L3GD20 angular rate sensor\n#for more information see datasheet at http://www.pololu.com/file/download/L3GD20.pdf?file_id=0J563\nfrom smbus import SMBus\n\n#registers, addresses\nadr = 0x6B\t\t#I2C address of L3GD20\nwho = 0x0F\t\t#who_am_I -- 11010100 -- D4\nctrl1 = 0x20\t#ctrl_reg1 -- datarate, bandwidth, powerdown, axes enabled\nctrl2 = 0x21\t#ctrl_reg2 -- high pass filtering\nctrl3 = 0x22\t#ctrl_reg3 -- interrupt, FIFO, etc\nctrl4 = 0x23\t#ctrl_reg4 -- block, SPI, range\nctrl5 = 0x24\t#ctrl_reg5 -- boot, FIFO, etc\ntemp = 0x26\t\t#out_temp -- 2's complement temperature\nxlo = 0x28\t\t#out_x_l -- 2's complement x-axis angular rate\nxhi = 0x29\t\t#out_x_h\nylo = 0x2A\t\t#out_y_l -- 2's complement y-axis angular rate\nyhi = 0x2B\t\t#out_y_h\nzlo = 0x2C\t\t#out_z_l -- 2's complement z-axis angular rate\nzhi = 0x2D\t\t#out_z_h\n\n#commands\non = 0x0F\t\t#\ndps_250 = 0x00\t#\ndps_500 = 0x10\t#\ndps_2000 = 0x20\t#\n\n#setup functions\ndef bus_init(ID = 1):\t\t#ID = I2C bus ID (default 1)\n\treturn SMBus(ID)\t\n\ndef w_init(bus, dps = dps_250):\t#returns conversion factor / gain\n\tbus.write_byte_data(adr, ctrl1, on)\n\tbus.write_byte_data(adr, ctrl4, dps)\n\tif(dps == dps_250):\n\t\tgain = 0.00875\n\telif(dps == dps_500):\n\t\tgain = 0.01750\n\telse:\n\t\tgain = 0.070\n\treturn gain\n\n#read functions\ndef w_get(bus, gain, w_x0=0,w_y0=0,w_z0=0):\t#returns [w_x, w_y, w_z] (degrees/s)\n\tw_x = 256 * bus.read_byte_data(adr,xhi) + bus.read_byte_data(adr,xlo)\n\tif(w_x >= 32768): w_x = w_x - 65536\n\n\tw_y = 256 * bus.read_byte_data(adr,yhi) + bus.read_byte_data(adr,ylo)\n\tif(w_y >= 32768): w_y = w_y - 65536\n\n\tw_z = 256 * bus.read_byte_data(adr,yhi) + bus.read_byte_data(adr,ylo)\n\tif(w_z >= 32768): w_z = w_z - 65536\n\n\n\tw_x = (gain * w_x) - w_x0\n\tw_y = (gain * w_y) - w_y0\n\tw_z = (gain * w_z) - w_z0\n\t\n\treturn [w_x, w_y, w_z]\n\n","sub_path":"AltIMU/L3GD20.py","file_name":"L3GD20.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"622346921","text":"def spiralTraverseHelper(array, startCol, startRow, endCol, endRow, spiral):\n if startRow > endRow or startCol > endCol:\n return\n else:\n for idx in range(startCol, endCol + 1):\n spiral.append(array[startRow][idx])\n for idx in range(startRow + 1, endRow + 1):\n spiral.append(array[idx][endCol])\n for idx in reversed(range(startCol, endCol)):\n if startRow == endRow:\n break\n spiral.append(array[endRow][idx])\n for idx in reversed(range(startRow + 1, endRow)):\n if startCol == endCol:\n break\n spiral.append(array[idx][startCol])\n spiralTraverseHelper(array, startCol + 1, startRow + 1, endCol - 1, endRow - 1, spiral)\n\ndef spiralTraverse(array):\n # Write your code here.\n spiral = []\n n = len(array) - 1\n m = len(array[0]) - 1\n spiralTraverseHelper(array, 0, 0, m, n, spiral)\n return spiral\n\narray = [[1, 2, 3],\n [8, 9, 4],\n [7, 6, 5]]\n\nspiralTraverse(array)","sub_path":"Medium/SpiralTraverse.py","file_name":"SpiralTraverse.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"563278103","text":"import os, sys, time\nimport tkinter as tk\nimport yaml\nimport subprocess\nimport time\n\n\nclass UpperFrame(tk.Frame):\n def __init__(self, master=None):\n # ボタンクリックイベント\n def btn_click1():\n # num = node_var.get()\n # tkinter.messagebox.showinfo('チェックされた項目', node_list[num])\n rosbag_path1 = self.rosbag_entry1.get()\n rosbag_gen = subprocess.Popen(['python3', 'twist_filter_gen.py', rosbag_path1]) #twist_filter_gen.py\n def btn_click2():\n # num = node_var.get()\n # tkinter.messagebox.showinfo('チェックされた項目', node_list[num])\n rosbag_path2 = self.rosbag_entry2.get()\n config_gen = \"\"#subprocess.Popen(['python3', 'grep.py'])\n # config_gen = subprocess.Popen(['python3', rosbag_path2])\n super().__init__(master)\n\n self.btn = tk.Button(self, text='Generate bagfile', command=btn_click1)\n # self.btn.pack(anchor=tk.W)\n self.btn.grid(row=0, column=0, padx=2, pady=2)\n\n self.rosbag_label1 = tk.Label(self, text = \"ROSBAG\")\n self.rosbag_label1.grid(row=0, column=1, padx=2, pady=2)\n\n self.rosbag_entry1 = tk.Entry(self, width=50)\n self.rosbag_entry1.grid(row=0, column=2, padx=2, pady=2)\n\n self.btn = tk.Button(self, text='Generate config.yaml', command=btn_click2)\n # self.btn.pack(anchor=tk.W)\n self.btn.grid(row=1, column=0, padx=2, pady=2)\n\n self.rosbag_label2 = tk.Label(self, text = \"Destination\")\n self.rosbag_label2.grid(row=1, column=1, padx=2, pady=2)\n\n self.rosbag_entry2 = tk.Entry(self, width=50)\n self.rosbag_entry2.grid(row=1, column=2, padx=2, pady=2)\n\n self.tolerance_label = tk.Label(self, text = \"Tolerance(%)\")\n self.tolerance_label.grid(row=4, column=0, padx=2, pady=2)\n\n self.tolerance_entry = tk.Entry(self, width=50)\n self.tolerance_entry.grid(row=4, column=1, columnspan=2, padx=2, pady=2, sticky=tk.E)\n\nclass LowerFrame(tk.Frame):\n def __init__(self, master=None):\n # ボタンクリックイベント\n def btn_click3():\n num = node_var.get()\n # tkinter.messagebox.showinfo('チェックされた項目', node_list[num])\n rosbag_play_gen = subprocess.Popen(['python3', 'builder.py', node_list[num] ])\n def btn_click4():\n # num = node_var.get()\n # tkinter.messagebox.showinfo('チェックされた項目', node_list[num])\n rosbag_play = subprocess.Popen(['python3', 'source1.py'])\n def btn_click5():\n # num = node_var.get()\n # tkinter.messagebox.showinfo('チェックされた項目', node_list[num])\n tolerance = upper_frame.tolerance_entry.get()\n diff_gen = subprocess.Popen(['../.pyenv/versions/3.6.0/bin/python3.6', 'diff.py'])\n def btn_click6():\n # num = node_var.get()\n # tkinter.messagebox.showinfo('チェックされた項目', node_list[num])\n tolerance = upper_frame.tolerance_entry.get()\n diff_gen = subprocess.Popen(['python3', 'diff_two_dimension.py'])\n # diff_gen = subprocess.Popen(['../.pyenv/versions/3.6.0/bin/python3.6', 'diff_two_dimension.py'])\n def btn_click7():\n # num = node_var.get()\n # tkinter.messagebox.showinfo('チェックされた項目', node_list[num])\n tolerance = upper_frame.tolerance_entry.get()\n diff_gen = subprocess.Popen(['python3', 'ndt_diff.py', tolerance])\n def btn_click8():\n # num = node_var.get()\n # tkinter.messagebox.showinfo('チェックされた項目', node_list[num])\n # diff_gen = subprocess.Popen(['pyenv', 'global', '3.6.0'])\n # diff_gen = subprocess.Popen(['python3', '-V'])\n\n # time.sleep(1)\n tolerance = upper_frame.tolerance_entry.get()\n diff_gen = subprocess.Popen(['python3','ndt_diff_two_dimension.py', tolerance])\n # diff_gen = subprocess.run(['pyenv', 'global', 'system'])\n # def __init__(self, config, master=None):\n super().__init__(master)\n\n node_var = tk.IntVar()\n node_var.set(0)\n\n node_list = ['pure_pursuit', 'listener', 'ndt_matching']\n for i in range(len(node_list)):\n self.twis_filter_radio = tk.Radiobutton(self, value=i, variable=node_var, text=node_list[i]) \n self.twis_filter_radio.pack(anchor=tk.W)\n # chk.place(x=50, y=30 + (i * 24))\n\n # self.btn = tk.Button(self, text='source1.pyの生成(Jinja2による自動生成)', command=btn_click3)\n self.btn = tk.Button(self, text='Generate source1.py(Automatic Generation by Jinja2)', command=btn_click3)\n\n self.btn.pack(anchor=tk.W)\n\n # self.btn = tk.Button(self, text='source1.pyの実行(bagファイルの再生・比較用のデータ取得開始)', command=btn_click4)\n self.btn = tk.Button(self, text='Run of source1.py(Play bag File & Get Data for Comparison)', command=btn_click4)\n self.btn.pack(anchor=tk.W)\n\n # self.btn = tk.Button(self, text='diff.pyの実行(3次元グラフの生成)(twist_filter & pure_pursuit)', command=btn_click5)\n # self.btn = tk.Button(self, text='Run of diff.py(Generate 3D Graph)(twist_filter & pure_pursuit)', command=btn_click5)\n # self.btn.pack(anchor=tk.W)\n\n # # self.btn = tk.Button(self, text='diff.pyの実行(2次元グラフの生成)(twist_filter & pure_pursuit)', command=btn_click6)\n # self.btn = tk.Button(self, text='Run of diff.py(Generate 2D Graph)(twist_filter & pure_pursuit)', command=btn_click6)\n # self.btn.pack(anchor=tk.W)\n\n # # self.btn = tk.Button(self, text='diff.pyの実行(3次元グラフの生成)(ndt_matching)', command=btn_click7)\n self.btn = tk.Button(self, text='Run of diff.py(Generate 2D Graph)(pure_pursuit on kalray)', command=btn_click7)\n self.btn.pack(anchor=tk.W)\n\n # self.btn = tk.Button(self, text='diff.pyの実行(2次元グラフの生成)(ndt_matching)', command=btn_click8)\n self.btn = tk.Button(self, text='Run of diff.py(Generate 2D Graph)(pure_pursuit)', command=btn_click8)\n self.btn.pack(anchor=tk.W)\n\n\n\n # ラジオボタンをconfigにしたがって追加予定\n # self.twis_filter_radio = tk.Radiobutton(self, text='twist_filter', value=0, variable=node_var)\n # self.twis_filter_radio.pack(anchor=tk.W)\n # self.twis_filter_raw = tk.Radiobutton(self, text='pure_pursuit', value=1, variable=node_var)\n # self.twis_filter_raw.pack(anchor=tk.W)\n # self.twis_filter_raw = tk.Radiobutton(self, text='ndt_matching', value=2, variable=node_var)\n # self.twis_filter_raw.pack(anchor=tk.W)\n\n # import twist_filter_play.py\n # node_name = \n \n\n\n\n \n\n\n# with open(os.path.dirname(__file__) + \"/rosbag_test_generator.yaml\", \"r\") as f:\n# config = yaml.load(f)\n\nroot = tk.Tk()\nroot.geometry(\"800x600\")\n\nupper_frame = UpperFrame()\nupper_frame.pack(padx=2, pady=2, anchor=tk.W)\n\n# lower_frame = LowerFrame(config)\nlower_frame = LowerFrame()\nlower_frame.pack(padx=2, pady=2, anchor=tk.W)\n\n\nroot.mainloop()\n","sub_path":"src/rosbag_test_generator.py","file_name":"rosbag_test_generator.py","file_ext":"py","file_size_in_byte":7334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"591087602","text":"# -*- coding:utf-8 -*-\r\nimport datetime\r\nimport urllib\r\nimport urllib2\r\nimport jieba\r\nfrom nltk import NaiveBayesClassifier, classify\r\nimport tornado.httpserver\r\nimport tornado.ioloop\r\nimport tornado.options\r\nimport tornado.web\r\nfrom tornado.options import define, options\r\nimport json\r\nimport pickle\r\nimport re\r\n\r\ndefine(\"port\", default=12888, help=\"run on the given port\", type=int)\r\n\r\nclass_list = [u'虚拟机', u'应用系统', u'Office办公软件', u'应用软件', u'硬件故障', u'帐号权限', u'计算机网络', u'其他']\r\n# 分类器\r\nh = open('model_classifier.pickle', 'rb')\r\nclassifier = pickle.load(h)\r\nh.close()\r\n# 特征向量\r\ne = open('model_feature_word_list.pickle', 'rb')\r\nfeature_word_list = pickle.load(e)\r\ne.close()\r\n\r\n# 预处理正则\r\np_vh = re.compile('([VvWw])(\\d{2})(\\w{2})(\\d{2,6})', re.DOTALL)\r\np_mail = re.compile('([a-zA-Z_]+)@wuxiapptec.com', re.I)\r\np_ip = re.compile('([012]?)(\\d?)(\\d{1}).([012]?)(\\d?)(\\d{1}).([012]?)(\\d?)(\\d{1}).([012]?)(\\d?)(\\d{1})', re.DOTALL)\r\np_ip2 = re.compile('(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])', re.DOTALL)\r\np_url = re.compile('(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])', re.DOTALL)\r\np_browser = re.compile('IE', re.I)\r\np_usb = re.compile('USB', re.I)\r\np_id2 = re.compile('([T])(\\d{5})', re.I)\r\n\r\n\r\n# 药小明\r\nclass XiaoMingTongXueHandler(tornado.web.RequestHandler):\r\n\r\n\tdef get(self, *args, **kwargs):\r\n\t\tinput = self.get_argument('input', 'fuck')\r\n\t\tcallback = self.get_argument('callback','')\r\n\t\tcontinue_flag = True\r\n\t\t\r\n\t\tret_dict = {'output':'', 'code': 0}\r\n\t\tcallback = self.get_argument('callback','')\r\n\t\t# 第一步关键词检索 FAQ 智商为 0 \r\n\t\tif continue_flag:\r\n\t\t\t# 写死ID\r\n\t\t\tuser_id = 1\r\n\t\t\ttext = input.encode('utf-8')\r\n\t\t\tdt = datetime.datetime.now()\r\n\t\t\tds = dt.strftime('%Y-%m-%d %H:%M:%S') + ':000'\r\n\t\t\trequrl = 'http://222.66.238.85/FAQ/FAQ.ashx'\r\n\t\t\treqdata = {\"userid\": str(user_id), \"type\": \"1\", \"content\": text, \"time\": ds}\r\n\t\t\treq = urllib2.Request(url=requrl, data=urllib.urlencode(reqdata))\r\n\t\t\ttry:\r\n\t\t\t\tres_data = urllib2.urlopen(req)\r\n\t\t\t\tres = res_data.read()\r\n\t\t\t\tif res:\r\n\t\t\t\t\tret_type = res[res.index(\",\\\"restype\")+ 12]\r\n\t\t\t\t\tif ret_type == '0':\r\n\t\t\t\t\t\t# 0 表示有搜索结果\r\n\t\t\t\t\t\tcontinue_flag = False\r\n\t\t\t\t\t\tret_dict['output'] = res[res.index(\"\\\"result\")+ 10 : res.index(\"}\")- 1]\r\n\t\t\t\t\t\tret_dict['code'] = 1\r\n\t\t\t\t\t\t\r\n\t\t\t\t\telif ret_type == '4':\r\n\t\t\t\t\t\t# 4 表示没有搜索结果\r\n\t\t\t\t\t\tcontinue_flag = True\r\n\t\t\t\t\t\tret_dict['code'] = 11\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\t# 其他为异常\r\n\t\t\t\t\t\tcontinue_flag = True\r\n\t\t\t\t\t\tret_dict['code'] = 101\r\n\t\t\texcept:\r\n\t\t\t\tcontinue_flag = True\r\n\r\n\t\t\t\t\r\n\t\t# 第二步机器人分类 FAQ 智商为 30\r\n\t\tif continue_flag:\r\n\t\t\trequrl = 'http://10.111.5.33:30001/faq_prediction_service'\r\n\t\t\treqdata = {\"input\": input.encode('utf-8')}\r\n\t\t\tres_data = urllib2.urlopen(requrl + '?' + urllib.urlencode(reqdata))\r\n\t\t\tres = res_data.read()\r\n\t\t\tif res:\r\n\t\t\t\tres = json.loads(res)\r\n\t\t\t\t# 分类器能识别非其他类,完成回答即可\r\n\t\t\t\tif res['output_class_id'] != 99:\r\n\t\t\t\t\tret_dict['output'] = res['message']\r\n\t\t\t\t\tcontinue_flag = False\r\n\t\t\t\t\tret_dict['code'] = 2\r\n\t\t\t\t\t\r\n\t\t\t\t#分成其他类,进行额外判断\r\n\t\t\t\telse:\r\n\t\t\t\t\tret_dict['output'] = u'药小明现在还不会处理这个问题,请咨询It Call Center吧'\r\n\t\t\t\t\tcontinue_flag = False\r\n\t\t\t\t\tret_dict['code'] = 12\r\n\t\t\t\t\t\r\n\t\t#self.finish(json.dumps(ret_dict))\r\n\t\tself.finish(callback + '(' + str(json.dumps(ret_dict)) + ')')\r\n\t\t# 第三步机器人聊天 AIML 智商为 20\r\n\t\t# 再议\r\n\t\t\r\n\tdef getFAQ(self, input):\r\n\t\tclass_list = [u'虚拟桌面', u'Office办公软件', u'网络故障', u'操作系统', u'账号\\权限']\r\n\t\t#class_list_en = ['VDI', 'Office software', 'Network', 'Operation System', 'Accoun\\privilage']\r\n\t\tglobal classifier\r\n\t\toutput_class_id = int(classifier.classify(self.document_features(input)))\r\n\t\tglobal class_list\r\n\t\toutput = u'您的工单为[' + class_list[output_class_id] + u']类工单,您可以访问以下的信息来获取
FAQ首页:
https://faq.wuxiapptec.com|;|
例子1:
https://faq.wuxiapptec.com/DocLib14/如何更改登录虚拟桌面的密码.aspx|;|
例子2:
https://faq.wuxiapptec.com/GCSW/%E6%96%B0%E7%89%88%20Pfizer%20GCSW-IE%E6%97%A0%E6%B3%95%E8%BF%9B%E5%85%A5%E7%9A%84%E5%A4%84%E7%90%86%E6%96%B9%E6%B3%95.aspx'\r\n\t\treturn output, output_class_id\t\r\n\r\n\t# 2.2 mapping document to word bag\r\n\tdef document_features(self, document): \r\n\t\tfeatures = {}\r\n\t\tglobal feature_word_list\r\n\t\tfor word in feature_word_list: # According to dictionary each feature of document is True or False\r\n\t\t\tfeatures[word.lower()] = (word.lower() in document)\r\n\t\treturn features\r\n\t\r\n\t# 2.6 Predict class through document\r\n\tdef PredictClass(self, features):\r\n\t\treturn self.classifier.classify(features)\t\t\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\ttornado.options.parse_command_line()\r\n\tprint('parse_command_line finished')\r\n\tapp = tornado.web.Application(handlers=[(r\"/xiaomingtongxue\", xiaomingtongxueHandler)])\r\n\tprint('Application started')\r\n\thttp_server = tornado.httpserver.HTTPServer(app)\r\n\tprint('HTTPServer started')\r\n\thttp_server.listen(options.port)\r\n\tprint('Port Listening')\r\n\ttornado.ioloop.IOLoop.instance().start()\r\n\tprint('Loop End')\r\n\ttornado.autoreload.start(loop)\r\n\tprint('Autoreload')\r\n\t\r\n\t\r\n\t\r\n\t\r\n# -*- coding:utf-8 -*-\r\nimport datetime\r\nimport urllib\r\nimport urllib2\r\n#\r\n#text = u'傻逼'\r\n#user_id = 14026\r\n#text = text.encode('utf-8')\r\n#dt = datetime.datetime.now()\r\n#ds = dt.strftime('%Y-%m-%d %H:%M:%S') + ':000'\r\n#requrl = 'http://222.66.238.85/FAQ/FAQ.ashx'\r\n#reqdata = {\"userid\": str(user_id), \"type\": \"1\", \"content\": text, \"time\": ds}\r\n#req = urllib2.Request(url=requrl, data=urllib.urlencode(reqdata))\r\n#res_data = urllib2.urlopen(req)\r\n#res = res_data.read()\r\n#print res\r\n\r\n\r\n#requrl = 'http://10.111.5.33:30001/faq_prediction_service'\r\n#input = u'我的SSO系统帐号登录不了,无法上网'\r\n#reqdata = {\"input\": input.encode('utf-8')}\r\n##req = urllib2.Request(url=requrl, data=urllib.urlencode(reqdata))\r\n#req = urllib2.Request(url=requrl, data=urllib.urlencode(reqdata))\r\n#res_data = urllib2.urlopen(req)\r\n#res = res_data.read()\r\n#res\r\n#\r\n#data = {\"input\": input.encode('utf-8')}\r\n#url = 'http://10.111.5.33:30001/faq_prediction_service'\r\n#post_data = urllib.urlencode(data)\r\n#full_url = url + '?' + post_data\r\n#\r\n#reg = urllib2.urlopen(full_url)\r\n#content = reg.read()\r\n#\r\n#\r\n#content[content.index(\"\\\"message\")+ 12 : content.index(\"}\")- 1].replace()\r\n#\r\n#requrl = 'http://10.111.5.33:30001/faq_prediction_service'\r\n#input = u'我的SSO系统帐号登录不了,无法上网'\r\n#reqdata = {\"input\": input.encode('utf-8')}\r\n#res_data = urllib2.urlopen(requrl + '?' + urllib.urlencode(reqdata))\r\n#res = res_data.read()\r\n#res = json.loads(res)\r\n#ret_dict['output'] = res[res.index(\"\\\"result\")+ 10 : res.index(\"}\")- 1]\r\n#ret_dict['code'] = 0\r\n","sub_path":"betaGo/main/xiaomingtongxue.py","file_name":"xiaomingtongxue.py","file_ext":"py","file_size_in_byte":7103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"316858078","text":"# -*- coding: utf-8 -*-\nfrom sqlalchemy import create_engine, inspect, Column, String\nfrom sqlalchemy import Integer, DateTime, Float\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nimport datetime\n\ndb_name = 'db.sqlite'\ndb_url = \"sqlite:///web/\" + db_name\nengine = create_engine(db_url)\n\nBase = declarative_base()\n\n\nclass Score(Base):\n __tablename__ = 'Score'\n id = Column(Integer, primary_key=True, autoincrement=True)\n runtime = Column(String(250))\n round_no = Column(Integer)\n team_name = Column(String(250))\n score = Column(Float, default=0)\n overall_score = Column(Float, default=0)\n extra = Column(String(250))\n param_int1 = Column(Integer)\n param_int2 = Column(Integer)\n param_int3 = Column(Integer)\n param_str1 = Column(String(250))\n param_str2 = Column(String(250))\n param_str3 = Column(String(250))\n\n created_at = Column(DateTime(), default=datetime.datetime.utcnow)\n\n def __init__(self, *args, **kwargs):\n super(Score, self).__init__(*args, **kwargs)\n self.created_at = datetime.datetime.utcnow()\n\n @property\n def json(self):\n return {\n 'id': str(self.id),\n 'round_no': str(self.round_no),\n 'runtime': self.runtime,\n 'team_name': self.team_name,\n 'score': round(self.score, 4),\n 'overall_score': round(self.overall_score, 4),\n 'extra': self.extra,\n 'param_int1': str(self.param_int1),\n 'param_int2': str(self.param_int2),\n 'param_int3': str(self.param_int3),\n 'param_str1': str(self.param_str1),\n 'param_str2': str(self.param_str2),\n 'param_str3': str(self.param_str3),\n 'created_at': str(self.created_at)\n }\n\n\nins = inspect(engine)\nif len(ins.get_table_names()) <= 0:\n print('Create database')\n Base.metadata.create_all(bind=engine)\n\nSession = sessionmaker()\nSession.configure(bind=engine)\nsession = Session()\n","sub_path":"score_model.py","file_name":"score_model.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"96024915","text":"import json\r\n\r\nfrom django.test import TestCase,Client\r\nfrom unittest.mock import patch,MagicMock\r\n\r\nfrom user.models import AccountType, User\r\n\r\n\r\nclass KakaoSignInTest(TestCase):\r\n @classmethod\r\n def setUpTestData(cls):\r\n AccountType(name='kakao').save()\r\n\r\n\r\n @patch('user.utils.requests')\r\n def test_kakao_sign_in(self, mock_request):\r\n class FakeKakaoResponse:\r\n def json(self):\r\n return {\r\n \"kakao_account\":\r\n {\r\n \"email\": \"homer_the_king@homer.com\",\r\n },\r\n }\r\n\r\n User(\r\n email = \"homer_the_king@homer.com\",\r\n social_login_id = \"1234\",\r\n nickname = \"god homer\",\r\n account_type = AccountType.objects.get(name=\"kakao\"),\r\n ).save()\r\n\r\n kakao_access_token = {'kakao_access_token' : 123454321}\r\n\r\n mock_request.get = MagicMock(return_value = FakeKakaoResponse())\r\n\r\n response = Client().post('/user/kakao-signin', json.dumps(kakao_access_token), content_type='application/json')\r\n self.assertEqual(response.status_code, 200)\r\n","sub_path":"user/tests/test_kakao_signin.py","file_name":"test_kakao_signin.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"582974145","text":"import json\nfrom os import path\n\n\n# Initialize what will be out concatenated JSON string result\njsonStrRes = ''\n\nprint('Looking in ' +\n path.abspath('../../Files/Recipes/Spoonacular_Raw') +\n ' for file.\\n\\nPlease enter the name of the file of JSON arrays: ')\n\ninputfile = ''\nwhile True:\n line = input()\n if line.rstrip().split('.')[-1] != 'JSON':\n print('Please enter a valid file name (must end in .JSON): ')\n else:\n inputfile = '../../Files/Recipes/Spoonacular_RAW' + '/' + line\n break\n\n# Open raw recipe file generated from GetRandRecipe Java script\nprint('Opening file.')\nwith open(inputfile, 'r', encoding='utf8') as f:\n print('File opened. Concatenating JSON string arrays...')\n\n # State variable (first iteration check)\n firstIter = True\n\n # Iterate through each line until loop completes normally.\n for line in f:\n\n # Strip off carriage return before check\n line = line.rstrip()\n\n # If x is empty move on to next iteration in loop\n if not line: continue\n\n if firstIter:\n # Splice from first bracket of line to last curly brace in line\n jsonStrRes += line[:len(line) - 1] + ',\\n'\n firstIter = False\n else:\n # Splice from first curly brace of line to last curly brace in line\n jsonStrRes += line[1:len(line) - 1] + ',\\n'\n else:\n print('JSON string arrays concatenated. Converting to JSON object...')\n\n # Create final JSON object\n jsonRes = json.loads(jsonStrRes[:len(jsonStrRes.rstrip()) - 1] + ']')\n\n # Derive outfile name from original filename\n outfile = path.abspath(f.name + '/..') + '\\\\' + f.name.split('/')[-1].split('.')[0] + '_concat.JSON'\n\n print('Conversion finished. Writing to ' + outfile)\n\n # Write final JSON object to JSON file\n with open(outfile, 'w') as of:\n json.dump(jsonRes, of)\n print('Writing finished.')\n\n","sub_path":"Scripts/ConcatJSONArrays/concat_json.py","file_name":"concat_json.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"197176599","text":"\"\"\"\n Dataset routines.\n\"\"\"\n\n__all__ = ['get_dataset_metainfo', 'get_train_data_source', 'get_val_data_source', 'get_test_data_source']\n\nfrom chainer import iterators\n# from .datasets.imagenet1k_cls_dataset import ImageNet1KMetaInfo\n# from .datasets.cub200_2011_cls_dataset import CUB200MetaInfo\n# from .datasets.cifar10_cls_dataset import CIFAR10MetaInfo\n# from .datasets.cifar100_cls_dataset import CIFAR100MetaInfo\n# from .datasets.svhn_cls_dataset import SVHNMetaInfo\nfrom .datasets.voc_seg_dataset import VOCMetaInfo\nfrom .datasets.ade20k_seg_dataset import ADE20KMetaInfo\nfrom .datasets.cityscapes_seg_dataset import CityscapesMetaInfo\nfrom .datasets.coco_seg_dataset import COCOMetaInfo\n\n\ndef get_dataset_metainfo(dataset_name):\n dataset_metainfo_map = {\n # \"ImageNet1K\": ImageNet1KMetaInfo,\n # \"CUB200_2011\": CUB200MetaInfo,\n # \"CIFAR10\": CIFAR10MetaInfo,\n # \"CIFAR100\": CIFAR100MetaInfo,\n # \"SVHN\": SVHNMetaInfo,\n \"VOC\": VOCMetaInfo,\n \"ADE20K\": ADE20KMetaInfo,\n \"Cityscapes\": CityscapesMetaInfo,\n \"COCO\": COCOMetaInfo,\n }\n if dataset_name in dataset_metainfo_map.keys():\n return dataset_metainfo_map[dataset_name]()\n else:\n raise Exception(\"Unrecognized dataset: {}\".format(dataset_name))\n\n\ndef get_train_data_source(ds_metainfo,\n batch_size):\n predictor_class = ds_metainfo.train_transform\n dataset = ds_metainfo.dataset_class(\n root=ds_metainfo.root_dir_path,\n mode=\"train\",\n transform=None)\n iterator = iterators.SerialIterator(\n dataset=dataset,\n batch_size=batch_size,\n repeat=False,\n shuffle=False)\n return {\n \"predictor_class\": predictor_class,\n \"iterator\": iterator,\n \"ds_len\": len(dataset)\n }\n\n\ndef get_val_data_source(ds_metainfo,\n batch_size):\n predictor_class = ds_metainfo.val_transform\n dataset = ds_metainfo.dataset_class(\n root=ds_metainfo.root_dir_path,\n mode=\"val\",\n transform=None)\n iterator = iterators.SerialIterator(\n dataset=dataset,\n batch_size=batch_size,\n repeat=False,\n shuffle=False)\n return {\n \"predictor_class\": predictor_class,\n \"iterator\": iterator,\n \"ds_len\": len(dataset)\n }\n\n\ndef get_test_data_source(ds_metainfo,\n batch_size):\n predictor_class = ds_metainfo.test_transform\n dataset = ds_metainfo.dataset_class(\n root=ds_metainfo.root_dir_path,\n mode=\"test\",\n transform=None)\n iterator = iterators.SerialIterator(\n dataset=dataset,\n batch_size=batch_size,\n repeat=False,\n shuffle=False)\n return {\n \"predictor_class\": predictor_class,\n \"iterator\": iterator,\n \"ds_len\": len(dataset)\n }\n","sub_path":"chainer_/dataset_utils.py","file_name":"dataset_utils.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"603641066","text":"\"\"\"\nCreated on Fri Mar 18 00:00:34 2016\n\n@author: Ratishankar\n1.a sample program that reads in a series of images from the Spitzer\nData Challenge, identifies the brightest pixel in the images and\nproduces a pdf lightcurve (flux vs. time) for that pixel.\n\n\"\"\"\nimport numpy as np\nimport pyfits as p\nimport fitsfix as f\nimport dataredu as dr\nimport matplotlib.pyplot as plt\nimport glob\nfrom collections import namedtuple\nimport itertools\n#convert from Flux to Electron Count\n#Replace NaN\n#Trim bad rows,cols and Frames\n#backgroud substraction\n#sigma clipping\n#Gauss2DFit\n#aperture photmetry\n#Light Curve\n\n#Files location--------------------------------\nfits='/home/theone/bcd/*2_bcd.fits'\n\n#Store all filenames---------------------------\nfilename=[]\nfor files in glob.glob(fits):\n filename.append(files)\nfilename.sort() \ndatacube=namedtuple(\"datacube\", \"image header\")\n#Collection of Datacubes------------------------\ncubes=[]\nfor fi in filename:\n cubes.append(datacube(p.getdata(fi),p.getheader(fi)))\n\n\n#Plot Function---------------------------------\ndef plotLC(time,data,unitx=\"Time(AINTBEG+(AINTBEG-ATIMEEND)*I+1)-21010000 \",unity=\"Electron Count\"):\n plt.xlabel(unitx)\n plt.ylabel(unity)\n plt.plot(time,data)\n plt.savefig('lightcurve.png')\n plt.show()\n\n#Photometry---------------------------------\ndef photometry(data,header):\n#Fits Preprocessing-------------------------\n ff=f.fitsfix(data,header);#Read BCD FITS Files\n ff.getEcount()\n ff.fixnans()\n data=ff.trim(row=1,frame=[1,58])\n date=ff.getBJD()\n#Fits Data Reduction-------------------------\n drp=dr.datared(data)\n drp.bg_sub(exrad=2)#background Subtraction\n drp.sigma_clipd(sigma=4,iters=2)#Sigma Clipping\n image=drp.Gauss2Dfit()#Peak Values from 2D Gaussian fitted data\n table=drp.aper_photometry(7)#aperture Photmetry\n return [table,image,date]\n\n\n#--------------------------------------------------\nflux=[]#list to store all brightest pixel values\ntime=[]#list to store all time values\nfor c in cubes:\n t,i,d=photometry(c.image,c.header)\n flux.append(i)\n time.append(d)\nflux=list(itertools.chain(*flux))\nday=list(itertools.chain(*time))\n#Curve Plot Ecount vs BJD ------------------\nplotLC(day,flux)\n","sub_path":"LightcurvePlot.py","file_name":"LightcurvePlot.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"587265943","text":"from dataclasses import dataclass\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom webdriver_manager.firefox import GeckoDriverManager\nfrom webdriver_manager.microsoft import EdgeChromiumDriverManager, IEDriverManager\n\n\n# https://github.com/SergeyPirogov/webdriver_manager\n# https://docs.python.org/3/library/dataclasses.html#module-dataclasses\n@dataclass()\nclass WebDriverFactory():\n browser:str\n\n def get_webdriver_instance(self,url='http://www.google.com'):\n if self.browser == 'chrome':\n chrome_options = Options()\n self.driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)\n elif self.browser == 'edge':\n self.driver = webdriver.Edge(EdgeChromiumDriverManager().install())\n elif self.browser == 'ie':\n self.driver = webdriver.Ie(IEDriverManager().install())\n elif self.browser == 'firefox':\n self.driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())\n else:\n chrome_options = Options()\n chrome_options.add_argument(\"--headless\")\n chrome_options.add_argument(\"--disable-gpu\")\n self.driver = webdriver.Chrome(ChromeDriverManager().install(), options=chrome_options)\n\n self.driver.implicitly_wait(15)\n self.driver.maximize_window()\n self.driver.get(url)\n return self.driver\n\n","sub_path":"selenium_driver_factory.py","file_name":"selenium_driver_factory.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"107386107","text":"class Cloud_cards:\n \"\"\"Logic for implementing the cloud database with the flashcards\"\"\"\n def __init__(self, db, name):\n \"\"\"Creates the flash card save file\n\n Args:\n self (Cloud_flashcards): An instance of Cloud_flashcards\n db (Pyrebase): an instence of pyrebase database\n name (string): A string with the user name of the current user\n \"\"\"\n\n self.db = db\n self.name = name\n \n def create_card(self, target_word, target_scentence, naitive_word, naitive_scentence):\n \"\"\"Creates the flash card save file\n\n Args:\n self (Cloud_flashcards): An instance of Cloud_flashcards\n target_word(string): Word the user wants to learn\n target_scentence(string): Context scentence\n naitive_word (string): Word in naitive language\n naitive_scenetence (string): Contex scentence in native language\n \"\"\"\n index_length = self.get_file_list()\n card_number = index_length + 1\n data = {\"target_word\": target_word,\n \"target_scentence\": target_scentence,\n \"naitive_word\": naitive_word,\n \"naitive_scentence\": naitive_scentence,\n \"card_number\": card_number,\n \"User_name\": self.name}\n self.db.child(\"Users\").push(data)\n \n def call_card(self, current_index):\n \"\"\"Call the card and make it into a dictionary\n\n Args:\n self (Cloud_flashcards): An instance of Cloud_flashcards\n index_number (integer): Vocab card number\n \"\"\"\n card_data = self.db.child(\"Users\").order_by_child(\"User_name\").equal_to(self.name).get()\n for values in card_data.each():\n card = values.val()\n if card[\"card_number\"] == current_index:\n return card\n \n def get_file_list(self):\n \"\"\"Get the number of flash cards in the database under the current user\n\n Args:\n self (Cloud_flashcards): An instance of Cloud_flashcards\n \"\"\"\n count_me = []\n card_number_data = self.db.child(\"Users\").order_by_child(\"User_name\").equal_to(self.name).get()\n for item in card_number_data.each():\n print(item.val()[\"card_number\"])\n count_me.append(item.val())\n return len(count_me)\n \n def modify(self, current_index, data):\n \"\"\"Update the current flash card with new data\n\n Args:\n self (Cloud_flashcards): An instance of Cloud_flashcards\n current_index (int): flash card number\n data (dict): dicitonary including the data to be updated\n \"\"\"\n card_data = self.db.child(\"Users\").order_by_child(\"User_name\").equal_to(self.name).get()\n for values in card_data.each():\n card = values.val()\n if card[\"card_number\"] == current_index:\n mod_card = values.key()\n new_data = {f\"Users/{mod_card}\" : data}\n self.db.update(new_data)\n\n def delete_card(self, current_index):\n \"\"\"Delete a flash card from the cloud database\n\n Args:\n self (Cloud_flashcards): An instance of Cloud_flashcards\n current_index (int): flash card number that will be deleted\n \"\"\"\n card_data = self.db.child(\"Users\").order_by_child(\"User_name\").equal_to(self.name).get()\n for values in card_data.each():\n card = values.val()\n if card[\"card_number\"] == current_index:\n mod_card = values.key()\n \n self.db.child(\"Users\").child(mod_card).remove()","sub_path":"LanguageApp/cloud_cards.py","file_name":"cloud_cards.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"454716179","text":"import numpy as np\r\nimport math\r\n\r\n# np.array([[1,1,0]])\r\n# np.array([[0,-1,0],[0,0,-1],[-1,0,0]])\r\n\r\n\r\ndef Axistoskew(w):\r\n s_ = [\r\n [ 0.0, -w[0][2], w[0][1] ],\r\n [ w[0][2], 0.0,-w[0][0] ],\r\n [-w[0][1],w[0][0], 0.0 ]\r\n ]\r\n return s_\r\n\r\n\r\ndef SkewExp(S,theta):\r\n e_o_t = np.diag([1]*3)+np.dot(S,math.sin(theta)) + np.dot(np.dot(S,S),(1-math.cos(theta)))\r\n return e_o_t\r\n\r\n\r\ndef RotationAxis(R):\r\n theta = math.acos((np.trace(R)-1)/2)\r\n w = [\r\n [R[2][1] - R[1][2]],\r\n [R[0][2] - R[2][0]],\r\n [R[1][0] - R[0][1]]\r\n ]\r\n if theta != 0:\r\n w = np.dot((1/(2*math.sin(theta))),w)\r\n else:\r\n w = 0\r\n\r\n return np.append(w,theta)\r\n\r\ndef SkewToAxis(Sk): # a 3x3 array as input\r\n if (Sk[0][1] == (-Sk[1][0])):#&(Sk[0][2] == (-Sk[2][0]))&(Sk[1][1] == (-Sk[1][2])):\r\n # print('r Skew')\r\n w = np.array([[Sk[1][2],Sk[0][2],Sk[1][0]]])\r\n else:\r\n w=0\r\n print('wrong Skew')\r\n return w\r\n\r\ndef HomogeneousToTwist(xi): #xi is a 4x4 array as input\r\n w_ = xi[0:3,0:3]\r\n v = xi[0:3,3:]\r\n w = SkewToAxis(w_)\r\n epsilon = np.append(w,v)\r\n","sub_path":"screws.py","file_name":"screws.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"123564789","text":"#!/bin/python3\n\nfrom collections import deque\nimport os\n\n\ndef circularArrayRotation(arr, rotation_count, indexes):\n items = deque(arr)\n items.rotate(rotation_count)\n\n results = []\n for i in indexes:\n results.append(items[i])\n\n return results\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n nkq = input().split()\n\n n = int(nkq[0])\n\n k = int(nkq[1])\n\n q = int(nkq[2])\n\n a = list(map(int, input().rstrip().split()))\n\n m = []\n\n for _ in range(q):\n m_item = int(input())\n m.append(m_item)\n\n result = circularArrayRotation(a, k, m)\n\n fptr.write('\\n'.join(map(str, result)))\n fptr.write('\\n')\n\n fptr.close()\n","sub_path":"Algorithms/Implementation/circular-array-rotation.py","file_name":"circular-array-rotation.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"379791156","text":"from pico2d import *\nimport macro_constant\nimport Sound\n\nclass Enemy:\n PIXEL_PER_METER = (20.0 / 0.3) # 10 pixel 30 cm\n RUN_SPEED_KMPH = 5.0 # Km / Hour\n RUN_SPEED_MPM = (RUN_SPEED_KMPH * 1000.0 / 60.0)\n RUN_SPEED_MPS = (RUN_SPEED_MPM / 60.0)\n RUN_SPEED_PPS = (RUN_SPEED_MPS * PIXEL_PER_METER)\n\n image = None\n\n SIZE = 40\n\n WARNING, ACTIVATION = 0, 1\n\n def __init__(self, x, y, generation_number):\n self.x = x\n self.y = y\n self.dir_X = 0\n self.dir_Y = 0\n self.state = Enemy.WARNING\n self.distance = 0\n self.isAdd = False\n self.generation_number = generation_number\n self.current_time = 0.1\n self.opacity = 1.0\n self.add_opacity = 0.1\n\n self.sound = Sound.Sound()\n self.sound.enemy.play(1)\n\n if Enemy.image == None:\n Enemy.image = load_image(\"resource\\\\enemy\\\\enemy.png\")\n\n def update(self, frame_time):\n if self.state in (self.WARNING,):\n self.current_time += frame_time\n\n if self.opacity >= 1.0:\n self.add_opacity = -0.1\n elif self.opacity <= 0.1:\n self.add_opacity = 0.1\n self.opacity += self.add_opacity\n\n if (int)(self.current_time) >= macro_constant.ENEMY_WARNNING_TIME:\n self.state = self.ACTIVATION\n else:\n self.distance = (int)(self.RUN_SPEED_PPS * frame_time)\n self.x += self.dir_X * self.distance * (1 + self.generation_number / 300)\n self.y += self.dir_Y * self.distance * (1 + self.generation_number / 300)\n\n def draw(self):\n if self.state in (self.WARNING,):\n self.image.opacify(self.opacity)\n self.image.draw(self.x, self.y)\n else:\n self.image.opacify(1.0)\n self.image.draw(self.x, self.y)\n\n def handle_events(self, event):\n pass\n\n def draw_bb(self):\n draw_rectangle(*self.get_bb())\n\n def draw_bb_tile(self):\n if self.state in (self.WARNING,):\n pass\n else:\n draw_rectangle(*self.get_bb_tile())\n\n def get_bb(self):\n if self.state in (self.WARNING,):\n return 0, 0, 0, 0\n else:\n return self.x - self.SIZE / 2, self.y - self.SIZE / 2, self.x + self.SIZE / 2, self.y + self.SIZE / 2\n\n def get_bb_tile(self):\n if self.state in (self.WARNING,):\n return 0, 0, 0, 0\n else:\n return self.x - 30, self.y - 30, self.x + 30, self.y + 30\n\n def collide(self, a):\n if self.state in (self.WARNING,):\n return False\n else:\n left_self, bottom_self, right_self, top_self = self.get_bb()\n left_a, bottom_a, right_a, top_a = a.get_bb()\n if left_self > right_a: return False\n if right_self < left_a: return False\n if top_self < bottom_a: return False\n if bottom_self > top_a: return False\n return True","sub_path":"Inversus/Enemy.py","file_name":"Enemy.py","file_ext":"py","file_size_in_byte":3008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"201790342","text":"import cv2\nimport numpy as np\nfrom time import time\nimport pandas as pd\nimport seaborn as sns\nimport click\n\nfrom utils import timeit\nimport datetime\n\nclass MultiSourceCV2Gen:\n def __init__(self, *sources):\n self.sources = sources\n self.captures = [cv2.VideoCapture(x) for x in sources]\n self.last_capture_time = 0\n\n def __iter__(self):\n return self\n\n def __next__(self):\n captures = np.array([cap.read()[1] for cap in self.captures])\n\n duration_between_catures = time() - self.last_capture_time\n self.last_capture_time = time()\n\n return captures, duration_between_catures\n \n def change_res(self, width, height):\n [c.set(3, width) for c in self.captures]\n [c.set(4, height) for c in self.captures]\n\n def close(self):\n print('closing ...')\n print([x.release() for x in self.captures])\n\nif __name__ == '__main__':\n cameras = (0, 1, 2, 3 )\n print(f'initialize cameras {cameras}')\n img_gen = MultiSourceCV2Gen(*cameras)\n img_gen.change_res(width=160, height=120)\n\n print('showing ...')\n try:\n cv2.namedWindow(\"stabilized image\", cv2.WINDOW_AUTOSIZE );\n for img_batch , duration in img_gen:\n img2show = np.concatenate(img_batch, axis=1)\n # cv2.putText(img2show, f'{1 / timed.mean():0.0f} FPS (average)', (50, 50), cv2.FONT_HERSHEY_COMPLEX, 2, 255)\n cv2.putText(img2show, f'{1 / duration:0.0f} FPS (actual)', (100, 100), cv2.FONT_HERSHEY_COMPLEX, 1, 255)\n img2show = cv2.resize(img2show, (len(cameras) * 160, 120))\n cv2.imshow('stabilized image', img2show)\n print(duration)\n if cv2.waitKey(1) == ord('q'):\n break\n finally:\n cv2.destroyAllWindows()\n img_gen.close()\n\n\n print('timing ...')\n @timeit(times=10)\n def measure_capture_from_gen(gen):\n batch = next(gen)\n print(type(batch))\n\n timed = measure_capture_from_gen(img_gen)\n\n print(timed.describe())\n\n # import matplotlib.pyplot as plt\n # sns.boxplot(y=timed)\n # sns.swarmplot(y=timed, color='.2', size=5, linewidth=2.5)\n # plt.show()\n\n","sub_path":"camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"465452126","text":"import scr.RandomVariantGenerators as rndClasses\nimport scr.StatisticalClasses as Stat\nimport scr.SamplePathClasses as PathCls\nfrom enum import Enum\nimport scr.FigureSupport as Figs\nimport scr.EconEvalClasses as EconCls\nimport scr.FormatFunctions as Format\n\n\nTRANS_MATRIX = [\n [0.75, 0.15, 0, 0.1], # WELL\n [0, 0, 1, 0], # STROKE\n [0, 0.25, 0.55, 0.2], # P_STROKE\n ]\n\nTRANS_MATRIX_THERAPY = [\n [0.75, 0.15, 0, 0.1], # WELL\n [0, 0, 1, 0], # STROKE\n [0, 0.1625, 0.701, 0.1365], # P_STROKE\n ]\n\nTRANS=[[\n [0.75, 0.15, 0, 0.1], # WELL\n [0, 0, 1, 0], # STROKE\n [0, 0.25, 0.55, 0.2], # P_STROKE\n ], [\n [0.75, 0.15, 0, 0.1], # WELL\n [0, 0, 1, 0], # STROKE\n [0, 0.1625, 0.701, 0.1365], # P_STROKE\n ]\n]\n\nTRANS_UTILITY= [\n [1,0.8865,0.9,0],\n [1,0.8865,0.9,0]\n]\n\nTRANS_COST=[\n [0,5196,200,0],\n [0,5196,2200,0]\n]\n\nDiscount_Rate=0.03\n\nclass HealthStats:\n \"\"\" health states of patients with risk of stroke \"\"\"\n WELL = 0\n STROKE = 1\n P_STROKE = 2\n DEATH = 3\n\nclass THERAPY_OR_NOT (Enum):\n WITHOUT=0\n WITH=1\n\n\nclass Patient:\n def __init__(self, id, THERAPY):\n \"\"\" initiates a patient\n :param id: ID of the patient\n :param parameters: parameter object\n \"\"\"\n\n self._id = id\n # random number generator for this patient\n self._rng = None\n self.healthstat=0\n self.survival=0\n self.THERAPY = THERAPY\n self.STROKE=0\n self.totalDiscountUtility=0\n self.totalDiscountCost=0\n\n\n def simulate(self, sim_length):\n \"\"\" simulate the patient over the specified simulation length \"\"\"\n\n self._rng = rndClasses.RNG(self._id)\n\n k = 0\n\n while self.healthstat!=3 and k < sim_length:\n\n trans_probs = TRANS[self.THERAPY][self.healthstat]\n\n empirical_dist = rndClasses.Empirical(trans_probs)\n\n new_state_index = empirical_dist.sample(self._rng)\n if self.healthstat==1:\n self.STROKE+=1\n\n cost=TRANS_COST[self.THERAPY][self.healthstat]\n utility=TRANS_UTILITY[self.THERAPY][self.healthstat]\n\n self.totalDiscountCost += \\\n EconCls.pv(cost, Discount_Rate, k + 1)\n self.totalDiscountUtility += \\\n EconCls.pv(utility, Discount_Rate, k + 1)\n\n self.healthstat =new_state_index[0]\n\n k += 1\n self.survival=k\n\n def get_survival_time(self):\n \"\"\" returns the patient's survival time\"\"\"\n return self.survival\n\n def get_STROKE_time(self):\n \"\"\" returns the patient's survival time\"\"\"\n return self.STROKE\n\n def get_total_utility(self):\n return self.totalDiscountUtility\n\n def get_total_cost(self):\n return self.totalDiscountCost\n\nclass Cohort():\n def __init__(self,id,THERAPY):\n self._initial_pop_size=2000\n self.survivaltime=[]\n self.id=id\n self.THERAPY=THERAPY\n self.STROKE=[]\n self.totaldiscountedcost=[]\n self.totaldiscountedutility=[]\n\n def simulate(self):\n for i in range(self._initial_pop_size):\n patient=Patient(self.id*self._initial_pop_size+i,self.THERAPY)\n patient.simulate(1000)\n self.survivaltime.append(patient.get_survival_time())\n self.STROKE.append(patient.get_STROKE_time())\n self.totaldiscountedcost.append(patient.get_total_cost())\n self.totaldiscountedutility.append(patient.get_total_utility())\n\n def get_survival_time(self):\n return self.survivaltime\n\n def get_STROKE_time(self):\n \"\"\" returns the patient's survival time\"\"\"\n return self.STROKE\n\n def get_total_utility(self):\n return self.totaldiscountedutility\n\n def get_total_cost(self):\n return self.totaldiscountedcost\n\n\nclass CohortOutcomes:\n def __init__(self, simulated_cohort):\n \"\"\" extracts outcomes of a simulated cohort\n :param simulated_cohort: a cohort after being simulated\"\"\"\n\n self._simulatedCohort = simulated_cohort\n\n def get_ave_survival_time(self):\n \"\"\" returns the average survival time of patients in this cohort \"\"\"\n return sum(self._simulatedCohort.get_survival_time()) / len(self._simulatedCohort.get_survival_time())\n\n def get_survival_curve(self):\n \"\"\" returns the sample path for the number of living patients over time \"\"\"\n\n\n n_pop = 2000\n\n n_living_patients = PathCls.SamplePathBatchUpdate('# of living patients', 0, n_pop)\n\n for obs in self._simulatedCohort.get_survival_time():\n n_living_patients.record(time=obs, increment=-1)\n\n return n_living_patients\n\n def get_survival_times(self):\n \"\"\" :returns the survival times of the patients in this cohort\"\"\"\n return self._simulatedCohort.get_survival_time()\n\ndef print_comparative_cost(sim_output_high, sim_output_low):\n\n increase = Stat.DifferenceStatIndp(\n name='Increase in cost',\n x=sim_output_high,\n y_ref=sim_output_low\n )\n\n estimate_CI = Format.format_estimate_interval(\n estimate=increase.get_mean(),\n interval=increase.get_t_CI(alpha=0.05),\n deci=1\n )\n print(\"Average increase in cost and {:.{prec}%} confidence interval:\".format(1 - 0.05, prec=0),\n estimate_CI)\n\ndef print_comparative_utility(sim_output_high, sim_output_low):\n\n increase = Stat.DifferenceStatIndp(\n name='Increase in utility',\n x=sim_output_high,\n y_ref=sim_output_low\n )\n estimate_CI = Format.format_estimate_interval(\n estimate=increase.get_mean(),\n interval=increase.get_t_CI(alpha=0.05),\n deci=1\n )\n print(\"Average increase in utility and {:.{prec}%} confidence interval:\".format(1 - 0.05, prec=0),\n estimate_CI)\n\ndef print_comparative_stroke(sim_output_high, sim_output_low):\n\n increase = Stat.DifferenceStatIndp(\n name='Increase in stroke',\n x=sim_output_high,\n y_ref=sim_output_low\n )\n estimate_CI = Format.format_estimate_interval(\n estimate=increase.get_mean(),\n interval=increase.get_t_CI(alpha=0.05),\n deci=1\n )\n print(\"Average increase in stroke and {:.{prec}%} confidence interval:\".format(1 - 0.05, prec=0),\n estimate_CI)\n\n\ncohort_ONE=Cohort(1,THERAPY_OR_NOT.WITHOUT.value)\ncohort_ONE.simulate()\n\ncohort_TWO=Cohort(2,THERAPY_OR_NOT.WITH.value)\ncohort_TWO.simulate()\n\ncohort_ONE.get_total_utility()\ncohort_ONE.get_total_cost()\n\ncohort_TWO.get_total_utility()\ncohort_TWO.get_total_cost()\n\nsum_stat = Stat.SummaryStat(\"dsa\",cohort_ONE.get_survival_time())\nCI_of_Expected=sum_stat.get_t_CI(0.05)\nMeanSurvive=sum_stat.get_mean()\n\nsum_stat_TWO = Stat.SummaryStat(\"dsa\",cohort_TWO.get_survival_time())\nCI_of_Expected_TWO=sum_stat_TWO.get_t_CI(0.05)\nMeanSurvive_TWO=sum_stat_TWO.get_mean()\n\nprint(MeanSurvive,CI_of_Expected)\nprint(MeanSurvive_TWO,CI_of_Expected_TWO)\n\nprint_comparative_cost(cohort_ONE.get_total_cost(),cohort_TWO.get_total_cost())\nprint_comparative_utility(cohort_ONE.get_total_utility(),cohort_TWO.get_total_utility())\nprint_comparative_stroke(cohort_ONE.get_STROKE_time(),cohort_TWO.get_STROKE_time())\n","sub_path":"Q2.py","file_name":"Q2.py","file_ext":"py","file_size_in_byte":7324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"161881640","text":"\"\"\"\nCreated by Young on 2019/7/15 15:20\n\"\"\"\nfrom django.urls import path\nfrom . import views\n\napp_name = 'fwqfront'\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('/', views.save_to_excel, name='save_to_excel'),\n # path('result/', views.result, name='result'),\n]\n","sub_path":"apps/fwqfront/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"383817665","text":"import serial\r\n#import time\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\n#from datetime import datetime\r\n#dt = datetime.now()\r\n#dt.microsecond\r\nimport csv\r\n\r\nser = serial.Serial('COM13', 115200)\r\n\r\nwith open('middle.csv', 'w', newline ='') as f:\r\n writer = csv.writer(f)\r\n writer.writerow(['time','snsr_11','snsr_12','snsr_13','snsr_14',\r\n 'snsr_21','snsr_22','snsr_23','snsr_24',\r\n 'snsr_31','snsr_32','snsr_33','snsr_34', \r\n 'snsr_41','snsr_42','snsr_43','snsr_44','interupt'])\r\n \r\ndummy = np.zeros((4,4))\r\nfig, ax = plt.subplots()\r\nline = ax.imshow(dummy, vmin=-50, vmax=50)\r\n\r\ndef init():\r\n line.set_array(np.zeros((4,4)))\r\n \r\n return line,\r\n\r\ndef animate(i):\r\n s = str(ser.readline(),'utf-8')\r\n st = s.rstrip().split(',')\r\n with open('middle.csv', 'a', newline ='') as f:\r\n writer = csv.writer(f)\r\n writer.writerow(st)\r\n lis = [float(x) for x in st[1:17]]\r\n a = np.array(lis).reshape(4,4)\r\n line.set_array(a)\r\n #line.text(0,-0.6,s)\r\n #line.set_title(s)\r\n return line,\r\n\r\nani = animation.FuncAnimation(\r\n fig, animate, init_func=init, interval=5, blit=True, save_count=10)\r\n\r\nplt.show()\r\n","sub_path":"Data/ALL_Sensor.py","file_name":"ALL_Sensor.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"7238833","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pandas import Series, DataFrame, Panel\nimport datetime\n\nts = np.load('numCarsSearchingVacancyRate23.npy')\nTS = Series((ts[:,1])/(1/(1-ts[:,2])),index=ts[:,0])\nax = TS.plot(color='c',linestyle='solid')\n\nfig = ax.get_figure()\nax.set_ylabel('Number of Cars Searching')\nax.set_xlabel('Timestep')\nfig.suptitle('Number of cars searching / 1-vacancy rate' \\\n + '\\ngenerated at'+str(datetime.datetime.now().date()) \\\n + '\\n'\\\n + '\\nMean: '+str(np.mean(ts[:,1]))+' , Variance: ' + str(np.var(ts[:,1])))\nfig.text(.89, .65, ' Simulation Settings \\n' \\\n + 'Number of Spaces -- 100 \\n Occupancy Rate -- 2/3 '\\\n + '\\n Arrival Rate -- Poisson with Rate 1/30 \\n Stay Lengh -- '\\\n + 'Exponential with mean 2000 \\n Number of Observations -- 1M '\\\n + '\\n Begin to Record Time -- 10K'\\\n + '\\n Subsampled every 100 steps',\n verticalalignment='bottom', horizontalalignment='right',\n color='black', fontsize=10)\n\nfig.savefig('23_Time_Series_Cars_Searching_over_1-vacancy_rate.png',dpi=1200)\nplt.close(fig)","sub_path":"Small_Comparison_TS.py","file_name":"Small_Comparison_TS.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"327106292","text":"import pandas as pd\r\nimport numpy as np\r\nimport scipy.cluster.vq as sc \r\nfrom mpl_toolkits.basemap import Basemap\r\nimport matplotlib.pyplot as plt\r\n\r\ntabela = pd.read_csv('C:/banco_de_dados.csv')\r\n\r\ntab1 = tabela.parse('Anos')\r\ntab1['ReLenCM'].fillna(((tab1['ReWgtKG'] / 0.00068) ** 0.458), inplace = True)\r\ntab1['ReWgtKG'].fillna(((tab1['ReLenCM'] ** 2.18) * 0.00068), inplace = True)\r\ntab2 = tab1.drop(columns = ['RcYear', 'RcDate', 'RcLatY', 'RcLonX', 'RcLenCM', 'RcWgtKG'])\r\ntab2.isnull().sum()\r\ntab6 = tab2[(tab2['ReLatY'] > 34) & (tab2['ReLatY'] < 51) & (tab2['ReLonX'] < -30)]\r\nano_escolhido = tab6.groupby('ReYear')\r\n\r\ncont = 0\r\nano = 1987\r\n\r\ngrade = plt.figure(figsize = (20,24))\r\ngrade.subplots_adjust(hspace = 0)\r\n\r\nwhile ano < 2018:\r\n \r\n file = np.load('C:/media_%s_total.npy' % str(ano))\r\n file = file[::-1]\r\n file = file[160:240,1120:1280]\r\n file = file[::-1]\r\n\r\n grade.add_subplot(8,4,cont+1)\r\n \r\n fig = Basemap( llcrnrlon=-80,llcrnrlat=30,urcrnrlon=-40,urcrnrlat=50, resolution='l', lon_0 = -60, lat_0= 37.5)\r\n sst = fig.imshow(file, cmap=\"jet\", interpolation = 'bilinear', aspect='auto')\r\n fig.drawcoastlines()\r\n fig.fillcontinents(color='0.8',lake_color='white') \r\n fig.drawparallels(np.arange(-90.,91.,10.),labels=[1,0,0,0], size = 10)\r\n fig.drawmeridians(np.arange(-180.,181.,15.),labels=[0,0,0,1], size = 10)\r\n\r\n for ano_tab,dados_ano in ano_escolhido:\r\n if ano_tab == ano:\r\n tab = {'lat' : ano_escolhido.get_group(ano)['ReLatY'], 'log' : ano_escolhido.get_group(ano)['ReLonX']}\r\n tab = pd.DataFrame(tab)\r\n clust = sc.kmeans(tab, 1)\r\n \r\n fig.scatter(x = list(tab['log']), y = list(tab['lat']), marker = 'o', c = 'pink', latlon=True, s = 40, edgecolors = 'k')\r\n fig.scatter(clust[0][0][1],clust[0][0][0], c = 'k', marker = 'X', latlon=True, s = 250, edgecolors = 'w')\r\n plt.title(ano, size = 10) \r\n break\r\n else:\r\n pass\r\n cont = cont + 1\r\n ano = ano + 1\r\n\r\ncbar_ax = grade.add_axes([0.3, 0.11, 0.42, 0.012])\r\ngrade.colorbar(sst, cax = cbar_ax, orientation = \"horizontal\").ax.tick_params(labelsize=15)\r\n","sub_path":"mapa_sst_anomalia_pontos/git_mapa_sst.py","file_name":"git_mapa_sst.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"251348439","text":"import numpy as np\n\nN = 100\nD = 2\n\nX = np.random.randn(N, D)\n# bias term\nones = np.array([[1]*N]).transpose()\nXb = np.concatenate((ones, X), axis=1)\n\nw = np.random.randn(D+1)\n\nZ = np.dot(Xb, w)\n\n\ndef sigmoid(z):\n return 1/(1+np.exp(-z))\n\n\nprint(sigmoid(Z))\n","sub_path":"logistic_regression/sigmoid.py","file_name":"sigmoid.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"383006697","text":"\"\"\"\n5. Faça um programa que receba do usuário um arquivo texto. Crie outro arquivo texto contendo\no texto do arquivo de entrada, mas com as vogais substituídas por ‘*’.\n\"\"\"\nfrom time import sleep\ndef arquivo(f, n):\n with open(f, \"r+\") as abrir:\n x = abrir.read()\n texto = x.replace(\"A\", \"*\").replace(\"E\", \"*\").replace(\"I\", \"*\").replace(\"O\", \"*\").replace(\"U\", \"*\")\\\n .replace(\"a\", \"*\").replace(\"a\", \"*\").replace(\"i\", \"*\").replace(\"o\", \"*\").replace(\"u\", \"*\")\n print(\"==============Arquivo Atual==============\")\n print(x)\n print()\n print(\"Gerando um novo arquivo....\")\n sleep(2)\n print(\"==============Novo Aquivo==============\")\n\n with open(n, \"a\") as f:\n f.write(texto)\n with open(n) as novo:\n y = novo.read()\n print(y)\n abrir.closed\n f.closed\n\nprint(\"Obs: Digite o caminho do arquivo com a barra invertida [/] \\nnesse progama só aceita arquivos .txt\")\na = input(\"Informe o arquivo: \")\nnovo_arquivo = input(\"Informe o nome do arquivo que vair ser gerado: \")\nprint(\"==\"*20)\narquivo(a, novo_arquivo)","sub_path":"lista06/ex005.py","file_name":"ex005.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"201077898","text":"import sys\nfrom PyQt5.QtWidgets import QApplication, QWidget, QPushButton\nfrom PyQt5.QtGui import QIcon\n\n\nclass HelloWorld(QWidget):\n def __init__(self):\n super().__init__()\n self.buttonUI()\n self.initUI()\n\n def buttonUI(self):\n btn1 = QPushButton('Button',self)\n btn1.setToolTip('This is a Button')\n btn1.resize(btn1.sizeHint())\n btn1.move(100,100)\n\n def initUI(self):\n self.setGeometry(300,300,300,300)\n self.setWindowTitle('Hello World')\n self.show()\n\napp = QApplication(sys.argv)\nexe = HelloWorld()\n# app.setWindowIcon(QIcon('Hello-World.png'))\n\nsys.exit(app.exec_())","sub_path":"PyQt/4. multi Button.py","file_name":"4. multi Button.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"341728907","text":"import os\r\nimport time\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom matplotlib import pyplot as plt\r\nfrom tensorflow.keras import Model\r\nfrom tensorflow.keras.layers import Conv2D, Flatten, Dense, Conv2DTranspose\r\n\r\ngpus = tf.config.experimental.list_physical_devices('GPU')\r\nfor gpu in gpus:\r\n tf.config.experimental.set_memory_growth(gpu, True)\r\n\r\n\r\ndef reparameterize(mean, logvar):\r\n eps = tf.random.normal(shape=mean.shape)\r\n return eps * tf.exp(logvar * 0.5) + mean\r\n\r\n\r\nclass Vae(Model):\r\n def __init__(self):\r\n super(Vae, self).__init__()\r\n\r\n self.ec1 = Conv2D(filters=32, kernel_size=3, strides=2, activation='relu')\r\n self.ec2 = Conv2D(filters=32, kernel_size=3, strides=2, activation='relu')\r\n self.ef1 = Flatten()\r\n self.ed1 = Dense(256, activation='relu')\r\n self.edu = Dense(100)\r\n self.edv = Dense(100)\r\n\r\n self.dd1 = Dense(7*7*32, activation='relu')\r\n self.dc1 = Conv2DTranspose(64, 3, 2, padding='SAME', activation='relu')\r\n self.dc2 = Conv2DTranspose(32, 3, 2, padding='SAME', activation='relu')\r\n self.dc3 = Conv2DTranspose(1, 3, 1, padding='SAME', activation='relu')\r\n self.dc4 = Conv2DTranspose(1, 3, 1, padding='SAME')\r\n\r\n def encode(self, x):\r\n x = self.ec1(x)\r\n x = self.ec2(x)\r\n x = self.ef1(x)\r\n x = self.ed1(x)\r\n mean = self.edu(x)\r\n logvar = self.edv(x)\r\n return mean, logvar\r\n\r\n def decode(self, z):\r\n z = self.dd1(z)\r\n z = tf.reshape(z, [-1, 7, 7, 32])\r\n z = self.dc1(z)\r\n z = self.dc2(z)\r\n z = self.dc3(z)\r\n logits = self.dc4(z)\r\n return logits\r\n\r\n\r\ndef main():\r\n epochs = 1\r\n lr = 0.001\r\n batch_size = 128\r\n\r\n mnist = tf.keras.datasets.mnist\r\n (x_train, y_train), (x_test, y_test) = mnist.load_data()\r\n x_train, x_test = x_train / 255.0, x_test / 255.0\r\n x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)\r\n x_train = x_train.astype('float32')\r\n x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)\r\n x_test = x_test.astype('float32')\r\n\r\n train_db = tf.data.Dataset.from_tensor_slices(x_train).batch(batch_size)\r\n\r\n model = Vae()\r\n optimizer = tf.keras.optimizers.Adam(lr)\r\n if os.path.exists('./vae/vae.index'):\r\n print('-------------load the model-----------------')\r\n model.load_weights('./vae/vae')\r\n\r\n for epoch in range(epochs):\r\n start1 = time.perf_counter()\r\n for step, x_train in enumerate(train_db):\r\n with tf.GradientTape() as tape:\r\n mean, logvar = model.encode(x_train)\r\n z = reparameterize(mean, logvar)\r\n x_logits = model.decode(z)\r\n\r\n cross_ent = tf.nn.sigmoid_cross_entropy_with_logits(logits=x_logits, labels=x_train)\r\n marginal_likelihood = - tf.reduce_sum(cross_ent, axis=[1, 2, 3])\r\n marginal_likelihood = tf.reduce_mean(marginal_likelihood)\r\n\r\n kl_divergence = tf.reduce_sum(mean ** 2 + tf.exp(logvar) - logvar - 1, axis=1)\r\n kl_divergence = tf.reduce_mean(kl_divergence)\r\n\r\n loss = -marginal_likelihood + kl_divergence\r\n\r\n grads = tape.gradient(loss, model.trainable_variables)\r\n\r\n optimizer.apply_gradients(zip(grads, model.trainable_variables))\r\n\r\n last_loss = loss\r\n end1 = time.perf_counter()\r\n print(epoch, 'last-loss:', float(last_loss), end1 - start1, 's')\r\n\r\n model.save_weights('./vae/vae')\r\n\r\n f, a = plt.subplots(2, 10, figsize=(10, 2))\r\n\r\n rnd = np.random.randint(0, len(x_test), 10)\r\n initx = x_test[rnd]\r\n\r\n mean, logvar = model.encode(initx)\r\n z = reparameterize(mean, logvar)\r\n x_logits = model.decode(z)\r\n outputx = tf.nn.sigmoid(x_logits)\r\n\r\n initx = initx * 255.0\r\n initx = 255.0 - initx\r\n outputx = outputx * 255.0\r\n outputx = 255.0 - outputx\r\n initx = np.reshape(initx, newshape=[10, 28, 28])\r\n outputx = np.reshape(outputx, newshape=[10, 28, 28])\r\n\r\n for i in range(10):\r\n a[0][i].imshow(initx[i], cmap='gray')\r\n a[1][i].imshow(outputx[i], cmap='gray')\r\n\r\n f.show()\r\n plt.draw()\r\n plt.waitforbuttonpress()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"AI/VAE/vae.py","file_name":"vae.py","file_ext":"py","file_size_in_byte":4268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"272638976","text":"import matplotlib.pyplot as plt\nimport math\nimport random\n\nrandom.seed(0)\n# construt fake data\ns = 3\nnum = 30\nx1 = [random.random()*s+5 for _ in range(num)]\ny1 = [random.random()*s+5 for _ in range(num)]\nx2 = [random.random()*s+10 for _ in range(num)]\ny2 = [random.random()*s+10 for _ in range(num)]\nx3 = [random.random()*s+5 for _ in range(num)]\ny3 = [random.random()*s+10 for _ in range(num)]\n\ndata_x = x1 + x2 + x3\ndata_y = y1 + y2 + y3\n\n\n# start to clustering\ninit_points = 3\nstop_distance = 0.1 # 如果所有点移动的平均距离小于该值,终止迭代\ncenter_points = [(random.choice(data_x),random.choice(data_y)) for _ in range(init_points)]\n\nwhile True:\n # 计算距离\n print(center_points)\n distances = [[] for _ in range(init_points)]\n for (x, y) in zip(data_x, data_y):\n temp_dis = []\n for (center_x, center_y) in center_points:\n d = math.sqrt((x - center_x)**2 + (y - center_y)**2)\n temp_dis.append(d)\n max_index = temp_dis.index(min(temp_dis))\n distances[max_index].append((x, y))\n # 重新计算中心点\n new_center_points = []\n for index, block in enumerate(distances):\n temp_x = sum([item[0] for item in block])/(len(block)+0.000001)\n temp_y = sum([item[1] for item in block])/(len(block)+0.000001) #稳定数值\n new_center_points.append((temp_x, temp_y))\n # 计算点移动距离是否满足终止条件\n stop_value = 0\n for i in range(init_points):\n stop_value = stop_value + math.sqrt((center_points[index][0]-new_center_points[index][0])**2+\n (center_points[index][1]-new_center_points[index][1])**2)\n center_points = new_center_points\n if stop_value < stop_distance:\n break\nplt.scatter(data_x, data_y, c='b')\ncluster_x = [item[0] for item in center_points]\ncluster_y = [item[1] for item in center_points]\n#plt.scatter(cluster_x, cluster_y, c='r')\nplt.show()","sub_path":"codes/k-means.py","file_name":"k-means.py","file_ext":"py","file_size_in_byte":1919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"140097458","text":"import argparse\nimport json\n\nfrom mutaviz.models.mutaviz import Mutaviz\n\n\n# this function is for extract the sequence from the fasta file\ndef read_seq(input_file):\n with open(input_file, \"r\") as f:\n lines = f.read().splitlines(True)\n seq = [line for line in lines if not line.startswith(\">\")]\n seq = \"\".join(seq)\n seq = seq.replace(\"\\n\", \"\")\n seq = seq.replace(\"\\r\", \"\")\n return seq\n\n\n# this function is for reading the mutations from the mutations file\ndef read_mutations(mutations_file):\n with open(mutations_file, \"r\") as f:\n json_data = json.load(f)\n return {int(k): str(v) for k, v in json_data.items()}\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--fasta', help='Path of the Fasta file containing the problem sequence')\n parser.add_argument(\n '--gap-costs', help=\"BLAST gap costs, first existence and then extension. Default: '11 1'\", default=\"11 1\"\n )\n parser.add_argument('--matrix-name', help='BLAST matrix name. Default: BLOSUM62', default=\"BLOSUM62\")\n parser.add_argument(\n '--mutations', help='Path of the mutations file, format must be a json with index and mutation i.e. {10: \"A\"}'\n )\n parser.add_argument('--name', help='Name of the program run')\n parser.add_argument('--open-pymol', help='If true, opens PyMOL with both PDB files. Default false', default=\"\")\n parser.add_argument('--seq-end', help='Ending position of the given sequence. You can use GenBank info')\n parser.add_argument(\n '--seq-start', help='Starting position of the given sequence (starts at 1). You can use GenBank info'\n )\n parser.add_argument(\n '--seq-type', help='Type of the fasta sequence (DNA, RNA or PROTEIN). Default: DNA', default=\"DNA\"\n )\n parser.add_argument('--threshold', help='BLAST threshold. Default: 10', default=10)\n parser.add_argument('--word-size', help='BLAST word size. Default: 6', default=6)\n parser.add_argument('--output-path', help='Path where the output files will be stored', default='./outputs')\n args = parser.parse_args()\n\n seq_string = read_seq(args.fasta)\n mutations = read_mutations(args.mutations)\n start = args.seq_start and int(args.seq_start) - 1 or 0\n end = args.seq_end and int(args.seq_end) or None\n open_pymol = args.open_pymol == 'true'\n\n mutaviz = Mutaviz(\n seq=seq_string[start:end],\n mutations=mutations,\n seq_name=args.name,\n seq_type=args.seq_type,\n output_path=args.output_path)\n\n mutaviz.process(\n word_size=int(args.word_size), threshold=int(args.threshold),\n matrix_name=args.matrix_name, gap_costs=args.gap_costs, open_pymol=open_pymol\n )\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"588521537","text":"#\r\n# @lc app=leetcode.cn id=640 lang=python3\r\n#\r\n# [640] 求解方程\r\n#\r\n# https://leetcode-cn.com/problems/solve-the-equation/description/\r\n#\r\n# algorithms\r\n# Medium (39.01%)\r\n# Likes: 26\r\n# Dislikes: 0\r\n# Total Accepted: 1.3K\r\n# Total Submissions: 3.4K\r\n# Testcase Example: '\"x+5-3+x=6+x-2\"'\r\n#\r\n# 求解一个给定的方程,将x以字符串\"x=#value\"的形式返回。该方程仅包含'+',' - '操作,变量 x 和其对应系数。\r\n#\r\n# 如果方程没有解,请返回“No solution”。\r\n#\r\n# 如果方程有无限解,则返回“Infinite solutions”。\r\n#\r\n# 如果方程中只有一个解,要保证返回值 x 是一个整数。\r\n#\r\n# 示例 1:\r\n#\r\n# 输入: \"x+5-3+x=6+x-2\"\r\n# 输出: \"x=2\"\r\n#\r\n#\r\n# 示例 2:\r\n#\r\n# 输入: \"x=x\"\r\n# 输出: \"Infinite solutions\"\r\n#\r\n#\r\n# 示例 3:\r\n#\r\n# 输入: \"2x=x\"\r\n# 输出: \"x=0\"\r\n#\r\n#\r\n# 示例 4:\r\n#\r\n# 输入: \"2x+3x-6x=x+2\"\r\n# 输出: \"x=-1\"\r\n#\r\n#\r\n# 示例 5:\r\n#\r\n# 输入: \"x=x+2\"\r\n# 输出: \"No solution\"\r\n#\r\n#\r\n#\r\n\r\n\r\n# @lc code=start\r\nclass Solution:\r\n def solveEquation(self, equation: str) -> str:\r\n # 先parse左右系数和常数\r\n # 然后求解\r\n # 注意edge case: -x\r\n # 注意=号右边需要重置符号\r\n leftx, leftc, rightx, rightc = 0, 0, 0, 0\r\n isLeft = True\r\n sign = 1\r\n cur = ''\r\n for c in equation + 'e':\r\n if c == 'e' or c == '=' or c == '+' or c == '-':\r\n if cur:\r\n if cur[-1] == 'x':\r\n val = sign if len(cur) == 1 else sign * int(cur[:-1])\r\n if isLeft:\r\n leftx += val\r\n else:\r\n rightx += val\r\n else:\r\n val = sign * int(cur)\r\n if isLeft:\r\n leftc += val\r\n else:\r\n rightc += val\r\n if c == '=':\r\n isLeft = False\r\n sign = 1\r\n elif c == '+':\r\n sign = 1\r\n elif c == '-':\r\n sign = -1\r\n cur = ''\r\n else:\r\n cur += c\r\n if leftx == rightx:\r\n if leftc == rightc:\r\n return \"Infinite solutions\"\r\n else:\r\n return \"No solution\"\r\n return 'x=' + str((rightc - leftc) // (leftx - rightx))\r\n\r\n\r\nif __name__ == '__main__':\r\n print(Solution().solveEquation(\"-x=-1\"))\r\n print(Solution().solveEquation(\"x+5-3+x=6+x-2\"))\r\n print(Solution().solveEquation(\"x=x\"))\r\n print(Solution().solveEquation(\"2x=x\"))\r\n print(Solution().solveEquation(\"2x+3x-6x=x+2\"))\r\n print(Solution().solveEquation(\"x=x+2\"))\r\n\r\n# @lc code=end\r\n","sub_path":"Medium/640.求解方程.py","file_name":"640.求解方程.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"546447208","text":"# messing with images in python and linux\n\n#-----------------------------------------------------------------------------\n# basic colors:\n\n# values in array images are represented by a set of 3 numbers from 0-255:\n\n# red tones: [high, medium, low]\n# green tones: [medium, high, medium]\n# blue tones: [low, medium, high]\n\n\n# 0 is darker (all 0's are black)\n# 255 is light (all 255's is white)\n#-----------------------------------------------------------------------------\n# simple wholesale alterations change one color or range of colors to another\n# using boolean arrays to select only the range of values we're interested in\n# changing-- but impacts all 3 rgb values indiscriminately:\n\nimport numpy as np \nfrom skimage import io\nimport matplotlib.pyplot as plt\na1=io.imread('lidar_color_code.jpg')\n\na1=a1[::5,::5]\n\n\nb1=a1<3\na1[b1]=0\nb1=a1>252\na1[b1]=255 \n\nplt.imshow(a1) \nplt.show() \n\n#-----------------------------------------------------------------------------\n\n# specific alterations to r, g, or b in specific ways throughout image\n\na1 = io.imread('lidar_color_code.jpg')\n\nking_boo = np.zeros(a1.size,dtype=np.bool)\nking_boo.shape = (a1.shape[0],a1.shape[1],a1.shape[2])\n\n\nlong_l_out=[]\n\nfor a1_bit in a1:\n long_l_out.append(a1_bit)\n for a1_bit_of_bit in a1_bit:\n long_l_out.append(a1_bit_of_bit)\n \n \n# boo_out.write(str(a1_bit_of_bit[0])+str(a1_bit_of_bit[1])+str(a1_bit_of_bit[2])+'\\n')\n\nboo_out=open('image_array_info.txt','w')\n\nfor long_bit in long_l_out:\n boo_out.write(str(long_bit)+'\\n')\n\nboo_out.close()\n\n\n\n\n# ...so now when we want to only mess with a single column\n# we use colon (:) first to grab every single array inside \n# king_boo and then 0 to grab the first element of each array\n\n# 0 impacts red-ness, 1 impacts green-ness, 2 impacts blue-ness\n\np_reply = -1\n\nwhile(p_reply<0 or p_reply>2):\n p_reply = input('enter 0, 1, or 2 to alter how red, green or blue the photo is, respectively: ')\n p_reply = int(p_reply)\n\ncolor_selection=int(p_reply)\n\nking_boo[:, :, color_selection] = True\n\nboo_thresh_high = a1 > 125\nbooling2=boo_thresh_high & king_boo\n\nrgb_swap_pic[booling2] = 0\nplt.imshow(rgb_swap_pic)\nplt.show()\n\n#-------------------------------------\n\n\n\n\n\n\n\n","sub_path":"github_older_stuff/numpy_basics2.py","file_name":"numpy_basics2.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"415219420","text":"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport json\nimport re\nimport os\nimport time\nimport random\n\nimport yaml\nfrom jupyterhub.spawner import Spawner\nfrom google.api_core import exceptions\nfrom google.cloud import dataproc_v1beta2\nfrom google.cloud.dataproc_v1beta2.gapic.transports import (\n cluster_controller_grpc_transport)\nfrom google.cloud.dataproc_v1beta2.gapic.transports import (\n job_controller_grpc_transport)\nfrom google.cloud.dataproc_v1beta2.gapic.enums import ClusterStatus\nfrom google.cloud import storage\nfrom traitlets import List, Unicode, Tuple, Dict, Bool\nfrom google.protobuf.internal.well_known_types import Duration\n\nfrom .customize_cluster import get_base_cluster_html_form\nfrom .customize_cluster import get_custom_cluster_html_form\n\ndef url_path_join(*pieces):\n \"\"\"Join components of url into a relative url.\n\n Use to prevent double slash when joining subpath. This will leave the\n initial and final / in place.\n\n Copied from `notebook.utils.url_path_join`.\n \"\"\"\n initial = pieces[0].startswith('/')\n final = pieces[-1].endswith('/')\n stripped = [s.strip('/') for s in pieces]\n result = '/'.join(s for s in stripped if s)\n\n if initial:\n result = '/' + result\n if final:\n result = result + '/'\n if result == '//':\n result = '/'\n\n return result\n\n\nclass DataprocSpawner(Spawner):\n \"\"\"Spawner for Dataproc clusters.\n\n Reference: https://jupyterhub.readthedocs.io/en/stable/reference/spawners.html\n \"\"\"\n \n poll_interval = 5\n\n # Since creating a cluster takes longer than the 30 second default,\n # up this value so Jupyterhub can connect to the spawned server.\n # Unit is in seconds.\n http_timeout = 900\n\n################################################################################\n# Admin variables passed in jupytherhub_config.py as c.Spawner.[VARIABLE]\n################################################################################\n project = Unicode(\n config=True,\n help=\"\"\"\n The project on Google Cloud Platform that the Dataproc clusters\n should be created under.\n\n This must be configured.\n \"\"\",)\n \n region = Unicode(\n 'us-central1',\n config=True,\n help=\"\"\"\n The region in which to run the Dataproc cluster.\n Defaults to us-central1. Currently does not support using\n 'global' because the initialization for the cluster gRPC\n transport would be different.\n \"\"\",)\n\n zone = Unicode(\n 'us-central1-a',\n config=True,\n help=\"\"\" The zone in which to run the Dataproc cluster.\"\"\",)\n \n cluster_data = Dict(\n config=True,\n help=\"\"\" \n Admin provided dict for setting up Dataproc cluster. If this field is not\n provided, the cluster configuration is set using YAML files on GCE. \"\"\",)\n\n gcs_notebooks = Unicode(\n config=True,\n help=\"\"\" \n GCS location to save Notebooks for a stateful experience.\n\n This must be configured.\n \"\"\",)\n \n gcs_user_folder = Unicode(\n config=True,\n help=\"\"\" GCS location to save the user's Notebooks. \"\"\",)\n \n dataproc_configs = Unicode(\n config=True,\n help=\"\"\" \n Comma separated list of the dataproc configurations available in the user spawning form.\n Each value should contain the top bucket name (can be without gs://) and path to the files from\n that bucket name. \n \n Example 1 config file: 'bucket/configs/file.yaml' or the same value 'gs://bucket/configs/file.yaml'\n Example 2 config files: 'bucket/configs/file1.yaml,bucket/configs/file2.yaml\n\n This must be configured\n \"\"\",)\n \n dataproc_default_subnet = Unicode(\n config=True,\n help=\"\"\" \n GCP subnet where to deploy the spawned Cloud Dataproc cluster. If not \n provided in the config yaml, defaults to the same as JupyterHub.\n \"\"\",)\n \n dataproc_service_account = Unicode(\n config=True,\n help=\"\"\" \n This solution uses a default service account for all spawned cluster if\n not provided by the administrator.\n \"\"\",)\n \n dataproc_locations_list = Unicode(\n \"\",\n config=True,\n help=\"\"\" \n Comma separated list of the zone letters where to spawn Cloud Dataproc in\n the JupyterHub region.\n Example: \"a,b\"\n\n This must be configured.\n \"\"\",)\n\n idle_checker = Dict(\n {\"idle_job_path\": \"\", \"idle_path\": \"\", \"timeout\": \"60m\"},\n config=True,\n help=\"\"\"\n Set up shutdown of a cluster after some idle time.\n Base on https://github.com/blakedubois/dataproc-idle-check\n idle_job - gcs path to https://github.com/blakedubois/dataproc-idle-check/blob/master/isIdleJob.sh\n idle_path - gcs path to https://github.com/blakedubois/dataproc-idle-check/blob/master/isIdle.sh\n timeout - idle time after which cluster will be shutdown\n Check official documentation: https://github.com/blakedubois/dataproc-idle-check\n \"\"\",)\n\n allow_custom_clusters = Bool(\n False,\n config=True,\n help=\"\"\" Allow users to customize their cluster. \"\"\",)\n\n default_notebooks_gcs_path = Unicode(\n '',\n config=True,\n help=\"\"\"\n The gcs path where default notebooks stored. Don't load default \n notebooks if variable is empty.\n \"\"\",)\n\n default_notebooks_folder = Unicode(\n 'examples/',\n config=True,\n help=\"The name of folder into which service will copy default notebooks\",)\n\n machine_types_list = Unicode(\n '',\n config=True,\n help=\"Allowed machine types\",)\n\n # Overwrites the env_keep from Spawner to only include PATH and LANG\n env_keep = List(\n [\n 'PATH',\n 'LANG',\n ],\n config=True,\n help=\"\"\"\n Whitelist of environment variables for the single-user server to inherit \n from the JupyterHub process. This whitelist ensures that sensitive \n information in the JupyterHub process's environment (such as \n `CONFIGPROXY_AUTH_TOKEN`) is not passed to the single-user server's \n process.\n \"\"\",)\n\n spawner_host_type = Unicode(\n '',\n config=True,\n help=\"Host type on which the Spawner is running (e.g. gce, ain)\",)\n\n force_add_jupyter_component = Bool(\n True,\n config=True,\n help=\"\"\"\n Whether to always enable the JUPYTER and ANACONDA optional components\n even if not explicitly specified in the cluster config. It is recommended\n to set this to True, as clusters without these components will *not* function\n correctly when spawned.\n \"\"\",)\n\n def __init__(self, *args, **kwargs):\n _mock = kwargs.pop('_mock', False)\n super().__init__(*args, **kwargs)\n\n if _mock:\n # Mock the API\n self.dataproc_client = kwargs.get('dataproc')\n self.gcs_client = kwargs.get('gcs')\n else:\n self.client_transport = (\n cluster_controller_grpc_transport.ClusterControllerGrpcTransport(\n address=f'{self.region}-dataproc.googleapis.com:443'))\n self.dataproc_client = dataproc_v1beta2.ClusterControllerClient(\n self.client_transport)\n self.gcs_client = storage.Client(project=self.project)\n\n if self.gcs_notebooks:\n if self.gcs_notebooks.startswith('gs://'):\n self.gcs_notebooks = self.gcs_notebooks[5:]\n \n self.gcs_user_folder = f'gs://{self.gcs_notebooks}/{self.get_username()}'\n \n \n################################################################################\n# Required functions\n################################################################################\n async def start(self):\n \"\"\" Creates a Dataproc cluster.\n If a cluster with the same name already exists, logs a warning and returns \n the same values as if creating the cluster.\n \n Returns:\n (String, Int): FQDN of the master node and the port it's accessible at.\n \"\"\"\n if await self.get_cluster_status(self.clustername()) == ClusterStatus.State.DELETING:\n raise RuntimeError(f'Cluster {self.clustername()} is pending deletion.')\n \n elif await self.exists(self.clustername()):\n self.log.warning(f'Cluster named {self.clustername()} already exists')\n \n else:\n if self.gcs_user_folder:\n self.create_example_notebooks()\n await self.create_cluster()\n\n start_notebook_cmd = self.cmd + self.get_args()\n start_notebook_cmd = ' '.join(start_notebook_cmd)\n self.log.info(start_notebook_cmd)\n \n return (self.getDataprocMasterFQDN(), self.port)\n\n async def stop(self):\n \"\"\" Stops an existing cluster \"\"\"\n self.log.info(f'Stopping cluster with name {self.clustername()}')\n if await self.exists(self.clustername()):\n result = self.dataproc_client.delete_cluster(\n project_id=self.project,\n region=self.region,\n cluster_name=self.clustername())\n return result\n self.log.info(f'No cluster with name {self.clustername()}')\n return None\n\n async def poll(self):\n status = await self.get_cluster_status(self.clustername())\n if status is None or status in (ClusterStatus.State.ERROR, \n ClusterStatus.State.DELETING, \n ClusterStatus.State.UNKNOWN):\n return 1\n elif status == ClusterStatus.State.CREATING:\n self.log.info(f'{self.clustername()} is creating')\n return None\n elif status in (ClusterStatus.State.RUNNING, ClusterStatus.State.UPDATING):\n self.log.info(f'{self.clustername()} is up and running')\n return None\n\n################################################################################\n# User form functions\n################################################################################\n def _options_form_default(self):\n \"\"\" Builds form using values passed by administrator either in Terraform\n or in the jupyterhub_config_tpl.py file.\n \"\"\"\n \n # Skips the form if no config provided.\n if not self.dataproc_configs:\n return \"\"\n\n base_html = get_base_cluster_html_form(\n self.dataproc_configs.split(','),\n self.dataproc_locations_list.split(','),\n self.region\n )\n\n html_customize_cluster = \"\"\n if self.allow_custom_clusters:\n html_customize_cluster = get_custom_cluster_html_form(\n self._get_autoscaling_policy(),\n self.machine_types_list.split(',')\n )\n\n return \"\\n\".join([\n base_html,\n html_customize_cluster\n ])\n\n def options_from_form(self, formdata):\n \"\"\" \n Returns the selected option selected by the user. It sets self.user_options.\n \"\"\"\n self.log.info(f'''formdata is {formdata}''')\n\n options = {}\n for key, value in formdata.items():\n if value:\n if isinstance(value, list):\n value = value[0]\n else:\n value = value\n else:\n value = None\n\n if key == \"cluster_zone\":\n self.zone = value or self.zone\n\n options[key] = value\n\n self.log.info(f'''User selected cluster: {options.get('cluster_type')} \n and zone: {self.zone} in region {self.region}.''')\n\n return options\n\n################################################################################\n# Overwrite\n################################################################################\n def get_env(self):\n \"\"\" Overwrites the original function to get a new Hub URL accessible by \n Dataproc when JupyterHub runs on an AI Notebooks which by default would\n return a local address otherwise.\n \"\"\"\n env = super().get_env()\n\n # Sets in the jupyterhub_config related to ai notebook.\n if 'NEW_JUPYTERHUB_API_URL' in env:\n env['JUPYTERHUB_API_URL'] = env['NEW_JUPYTERHUB_API_URL']\n env['JUPYTERHUB_ACTIVITY_URL'] = url_path_join(\n env['NEW_JUPYTERHUB_API_URL'],\n 'users',\n # tolerate mocks defining only user.name\n getattr(self.user, 'escaped_name', self.user.name),\n 'activity',\n )\n\n self.log.info(f'env is {env}')\n return env\n\n################################################################################\n# Custom Functions\n################################################################################\n def getDataprocMasterFQDN(self):\n \"\"\" Zonal DNS is in the form [CLUSTER NAME]-m.[ZONE].c.[PROJECT ID].internal\n If the project is domain-scoped, then PROJECT ID needs to be in the form\n [PROJECT NAME].[DOMAIN]. \n More info here: \n https://cloud.google.com/compute/docs/internal-dns#instance-fully-qualified-domain-names\n\n Returns\n String: the FQDN of the master node.\n \"\"\"\n if ':' in self.project:\n # Domain-scoped project\n domain_name, domain_project = self.project.split(':')\n #return f'{self.clustername()}-m.c.{domain_project}.{domain_name}.internal'\n return f'{self.clustername()}-m.{self.zone}.c.{domain_project}.{domain_name}.internal'\n else:\n #return f'{self.clustername()}-m.c.{self.project}.internal'\n return f'{self.clustername()}-m.{self.zone}.c.{self.project}.internal'\n \n def camelcase_to_snakecase(self, cc):\n \"\"\" Converts yaml's keys from CamelCase to snake_case so the cluster config\n is understandable by the Dataproc's Python client. \"\"\"\n\n # 1. Changes the first aA starting from line beginning to a_A.\n # 2. Changes all the ones after and stops at the first :\n # 3. Lower case all the _A\n sc = re.sub('(^[_a-z \\t-]*)([a-z])([A-Z])', r'\\1\\2_\\3', cc)\n sc = re.sub('([a-z])([A-Z])(?=.+:)', r'\\1_\\2', sc)\n sc = re.sub('([a-zA-Z0-9_]+):', lambda m: m.group(0).lower(), sc)\n return sc\n\n def read_gcs_file(self, file_path) -> dict:\n file_path = file_path.replace('gs://', '').split('/')\n bn = file_path[0]\n fp = \"/\".join(file_path[1:])\n \n working_bucket = self.gcs_client.get_bucket(bn)\n config_blob = working_bucket.get_blob(fp)\n config_string = config_blob.download_as_string()\n config_string = config_string.decode('utf-8')\n return config_string\n \n def get_cluster_definition(self, file_path):\n \"\"\" Returns the content of a GCS file\n\n Usage: file_path('mybucket/subfolder/filename.yaml'). Make sure that\n there is not comment in the yaml file. Find Dataproc properties here:\n https://cloud.google.com/dataproc/docs/reference/rest/v1beta2/ClusterConfig\n https://cloud.google.com/dataproc/docs/concepts/configuring-clusters/cluster-properties\n \n Args:\n String file_path: path to the file to read. Includes bucket and folders in the bucket\n Returns:\n (bytes, dict): Content of the file both as a string and yaml dict.\n \"\"\"\n config_string = self.read_gcs_file(file_path)\n config_dict = yaml.load(config_string, Loader=yaml.FullLoader)\n\n # Properties and Metadata might have some values that needs to remain with \n # CamelCase so we remove the properties/metadata from the conversion from \n # CamelCase to snake_case and add the properties/metadata back afterwards.\n skip_properties = {}\n skip_metadata = {}\n\n if 'properties' in config_dict['config'].setdefault('softwareConfig', {}):\n skip_properties = config_dict['config']['softwareConfig']['properties']\n del config_dict['config']['softwareConfig']['properties']\n\n if 'metadata' in config_dict['config'].setdefault('gceClusterConfig', {}):\n skip_metadata = config_dict['config']['gceClusterConfig']['metadata']\n del config_dict['config']['gceClusterConfig']['metadata']\n \n config_string = yaml.dump(config_dict)\n config_string = self.camelcase_to_snakecase(config_string)\n config_dict = yaml.load(config_string, Loader=yaml.FullLoader)\n\n if skip_properties:\n config_dict['config']['software_config']['properties'] = skip_properties\n\n if skip_metadata:\n config_dict['config']['gce_cluster_config']['metadata'] = skip_metadata\n\n self.log.debug(f'config_dict is {config_dict}')\n return config_dict\n\n\n def create_example_notebooks(self):\n default_path = self.default_notebooks_gcs_path\n user_folder = self.gcs_user_folder\n if not default_path or not user_folder:\n self.log.debug(\"Nothing to copy\")\n return\n storage_client = storage.Client(project=self.project)\n bucket_name, folder_name = self._split_gcs_path(default_path)\n destination_bucket_name, destination_folder_name = self._split_gcs_path(user_folder)\n destination_folder_name += self.default_notebooks_folder\n self.log.debug(f'''Copy from {bucket_name}/{folder_name} to \n {destination_bucket_name}/{destination_folder_name}''')\n \n source_bucket = storage_client.bucket(bucket_name)\n blobs = storage_client.list_blobs(bucket_name, prefix=folder_name)\n for blob in blobs:\n if blob.name == folder_name:\n continue\n source_bucket.copy_blob(\n source_bucket.blob(blob.name),\n storage_client.bucket(destination_bucket_name),\n destination_folder_name + blob.name[len(folder_name):]\n )\n\n async def create_cluster(self):\n \"\"\" Creates a cluster using templated yaml file. \"\"\"\n self.log.info(f'Creating cluster with name {self.clustername()}')\n\n # Dumps the environment variables, including those generated after init.\n # (ex. JUPYTERHUB_API_TOKEN)\n # Manually set PATH for testing purposes\n self.temp_env = self.get_env()\n self.temp_env[\"PATH\"] = \"/opt/conda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"\n self.env_str = json.dumps(self.temp_env)\n self.args_str = ' '.join(self.get_args())\n\n # Even if an admin provides a definition, ensures it is properly formed.\n self.cluster_definition = self._build_cluster_config(self.cluster_data)\n\n cluster = await self._create_cluster(self.cluster_definition)\n\n return cluster\n\n async def _create_cluster(self, cluster_data, try_count=3):\n \"\"\" Method implements custom retry functionality in order to change zone before each recall \"\"\"\n while True:\n try:\n return self.dataproc_client.create_cluster(self.project, self.region, cluster_data)\n except (exceptions.PermissionDenied, exceptions.TooManyRequests, exceptions.ResourceExhausted) as e:\n\n if await self.get_cluster_status(self.clustername()) == ClusterStatus.State.DELETING:\n self.log.warning(f'Cluster {self.clustername()} pending deletion.')\n\n try_count -= 1\n if try_count > 0:\n cluster_data = self.change_zone_in_cluster_cfg(cluster_data)\n time.sleep(3)\n continue\n raise e\n\n def change_zone_in_cluster_cfg(self, cluster_data):\n current_zone_tmp = cluster_data['config']['gce_cluster_config']['zone_uri'].split('/')[-1]\n current_region = current_zone_tmp[0:-2]\n current_zone = current_zone_tmp[-1]\n new_zone = None\n\n locations_list = self.dataproc_locations_list.split(',')\n zones_list = []\n for zone_letter in locations_list:\n tmp_zone = f'{self.region}-{zone_letter}'\n if zone_letter != current_zone:\n new_zone = tmp_zone\n zones_list.append(tmp_zone)\n if not new_zone:\n if zones_list:\n new_zone = random.choice(zones_list)\n else:\n new_zone = current_zone_tmp\n\n cluster_data['config']['gce_cluster_config']['zone_uri'] = f'https://www.googleapis.com/' \\\n f'compute/v1/projects/' \\\n f'{self.project}/zones/' \\\n f'{new_zone}'\n return cluster_data\n\n async def get_cluster_status(self, clustername):\n cluster = await self.get_cluster(clustername)\n if cluster is not None:\n return cluster.status.state\n return None\n \n async def exists(self, clustername):\n return (await self.get_cluster(clustername)) is not None\n\n async def get_cluster(self, clustername):\n try:\n return self.dataproc_client.get_cluster(self.project, self.region, \n clustername)\n except exceptions.NotFound:\n return None\n\n################################################################################\n# Helper Functions\n################################################################################\n\n def get_username(self, raw=False):\n return self.user.name if raw else re.sub(r'[^a-zA-Z0-9=]', '-', str(self.user.name))\n\n def clustername(self, cluster_name=None):\n \"\"\" JupyterHub provides a notebook per user, so the username is used to \n distinguish between clusters. \"\"\"\n if cluster_name is None:\n return f'dataprochub-{self.get_username()}'\n return cluster_name\n \n def calculate_config_value(self, key, path, default):\n \"\"\" Checks if a key exists at a dictionary path and returns a default value\n if not. Otherwise, returns the value there.\n key: ie 'zone_uri'\n path: ie cluster_data['config']['gce_cluster_config']\n default: \n \"\"\"\n if key not in path:\n return ''\n\n return path[key]\n\n def _is_idle_checker_enable(self):\n self.log.debug(f'Idle checker settings: {self.idle_checker}')\n return True if self.idle_checker and \\\n self.idle_checker.get('idle_job_path') and \\\n self.idle_checker.get('idle_path') else False\n\n def _split_gcs_path(self, path: str):\n gcs_prefix = \"gs://\"\n if path.startswith(gcs_prefix):\n path = path[len(gcs_prefix):]\n path = path.split(\"/\")\n bucket = path[0]\n folder = \"/\".join(path[1:])\n if not folder.endswith(\"/\"):\n folder += \"/\"\n return bucket, folder\n \n def convert_string_to_duration(self, data):\n \"\"\" A cluster export exports times as string using the JSON API but creating\n but a cluster uses Duration protobuf. This function checks if the fields \n known to be affected by this behavior are present in the cluster config. \n If so, it changes their value from string to a Duration in YAML. Duration \n looks like {'seconds': 15, 'nanos': 0}. \"\"\"\n self.log.info('Converting durations for {data}')\n\n def to_sec(united):\n \"\"\" Converts a time string finishing by a time unit as the matching number\n of seconds. \"\"\"\n if united:\n time_span = united[:-1]\n time_unit = united[-1]\n if time_unit == 'm':\n return int(time_span) * 60\n elif time_unit == 'h':\n return int(time_span) * 3600\n elif time_unit == 'd':\n return int(time_span) * 86400\n else:\n return int(time_span)\n return united\n\n # Loops through initialization actions list and replace values that have \n if data['config'].setdefault(\"initialization_actions\", []):\n idx = 0\n for init_action in data['config']['initialization_actions']:\n if ('execution_timeout' in init_action\n and isinstance(init_action['execution_timeout'], str)):\n data['config']['initialization_actions'][idx]['execution_timeout'] = {\n 'seconds': to_sec(init_action['execution_timeout']),\n 'nanos': 0\n }\n idx = idx + 1\n\n # Converts durations for lifecycle_config.\n if ('idle_delete_ttl' in data['config'].setdefault('lifecycle_config', {})\n and isinstance(data['config']['lifecycle_config']['idle_delete_ttl'], str)):\n data['config']['lifecycle_config']['idle_delete_ttl'] = {\n 'seconds': to_sec(data['config']['lifecycle_config']['idle_delete_ttl']),\n 'nanos': 0\n }\n\n if ('auto_delete_ttl' in data['config'].setdefault('lifecycle_config', {})\n and isinstance(data['config']['lifecycle_config']['auto_delete_ttl'], str)):\n data['config']['lifecycle_config']['auto_delete_ttl'] = {\n 'seconds': to_sec(data['config']['lifecycle_config']['auto_delete_ttl']),\n 'nanos': 0\n }\n \n self.log.info('Converted durations are in {data}')\n\n return data.copy()\n \n def _check_uri_geo(self, uri, uri_geo_slice, expected_geo, trim_zone=False):\n uri_geo = None\n uri_data = uri.split('/')\n if len(uri_data) > 1:\n uri_geo = uri_data[uri_geo_slice]\n if trim_zone:\n uri_geo = uri_geo[:-2]\n if uri_geo not in [expected_geo, 'global']:\n raise RuntimeError(f'''The location {uri_geo} of the uri {uri} in\n the yaml file does not match the Dataproc Hub's one {expected_geo}.\n Please, contact your admnistrator. ''')\n return uri_geo or uri\n\n\n\n\n################################################################################\n# Cluster configuration\n################################################################################\n\n def _get_autoscaling_policy(self) -> list:\n \"\"\"\n Get all autopscaling policies for dataproc.\n Method use bash command 'gcloud'\n :return: list of auto scaling policies\n \"\"\"\n command = f'gcloud beta dataproc autoscaling-policies list --region {self.region}'\n a = os.popen(command)\n is_exists = False\n res = []\n for i in a:\n i = i.replace(\"\\n\", \"\")\n if not is_exists:\n if i == \"ID\":\n is_exists = True\n else:\n break\n else:\n res.append(i)\n self.log.debug(f'Available autoscaling policies res')\n return res\n\n def _apply_users_configs(self, cluster_data):\n\n config = cluster_data['config']\n config.setdefault(\"initialization_actions\", [])\n\n if self.user_options.get('pip_packages'):\n config.setdefault(\"gce_cluster_config\", {})\n config['gce_cluster_config'].setdefault(\"metadata\", {})\n config['gce_cluster_config']['metadata'].setdefault(\"PIP_PACKAGES\", \"\")\n pip_packages = set(filter(None, set(\n config['gce_cluster_config']['metadata']['PIP_PACKAGES'].split(\" \")\n + self.user_options.get('pip_packages').split(\" \"))))\n config['gce_cluster_config']['metadata']['PIP_PACKAGES'] = \" \".join(pip_packages)\n config['initialization_actions'].append(\n {\n \"executable_file\": \"gs://dataproc-initialization-actions/python/pip-install.sh\"\n }\n )\n\n if self.user_options.get('condo_packages'):\n config.setdefault(\"gce_cluster_config\", {})\n config['gce_cluster_config'].setdefault(\"metadata\", {})\n config['gce_cluster_config']['metadata'].setdefault(\"CONDA_PACKAGES\", \"\")\n conda_packages = set(filter(None, set(\n config['gce_cluster_config']['metadata']['CONDA_PACKAGES'].split(\" \")\n + self.user_options.get('condo_packages').split(\" \"))))\n config['gce_cluster_config']['metadata']['CONDA_PACKAGES'] = \" \".join(conda_packages)\n config['initialization_actions'].append(\n {\n \"executable_file\": \"gs://dataproc-initialization-actions/python/conda-install.sh\"\n }\n )\n\n if self.user_options.get('master_node_type'):\n config.setdefault(\"master_config\", {})\n config['master_config']['machine_type_uri'] = self.user_options.get('master_node_type')\n\n if self.user_options.get('worker_node_type'):\n config.setdefault(\"worker_config\", {})\n config['worker_config']['machine_type_uri'] = self.user_options.get('worker_node_type')\n\n if self.user_options.get('master_node_disc_size'):\n try:\n val = int(self.user_options.get('master_node_disc_size'))\n if val < 15:\n val = 15\n config.setdefault(\"master_config\", {})\n config['master_config'].setdefault(\"disk_config\", {})\n config['master_config']['disk_config']['boot_disk_size_gb'] = val\n except:\n pass\n\n if self.user_options.get('worker_node_disc_size'):\n try:\n val = int(self.user_options.get('worker_node_disc_size'))\n if val < 15:\n val = 15\n config.setdefault(\"worker_config\", {})\n config['worker_config'].setdefault(\"disk_config\", {})\n config['worker_config']['disk_config']['boot_disk_size_gb'] = val\n except:\n pass\n\n if self.user_options.get('worker_node_amount'):\n try:\n val = int(self.user_options.get('worker_node_amount'))\n if val < 2:\n val = 2\n config.setdefault(\"worker_config\", {})\n config['worker_config']['num_instances'] = val\n except:\n pass\n\n autoscaling_policy = self.user_options.get('autoscaling_policy', '')\n if autoscaling_policy:\n cluster_data['config']['autoscaling_config'] = {\n \"policy_uri\": (\n f'''https://www.googleapis.com/compute/v1/projects/'''\n f'''{self.project}/locations/{self.region}/'''\n f'''autoscalingPolicies/{autoscaling_policy}''')\n }\n\n if self._is_custom_hive_settings():\n config['software_config']['properties']['hive:hive.metastore.schema.verification'] = 'false'\n config['software_config']['properties']['hive:javax.jdo.option.ConnectionURL'] = \\\n f\"jdbc:mysql://{self.user_options['hive_host']}/{self.user_options['hive_db']}\"\n config['software_config']['properties']['hive:javax.jdo.option.ConnectionUserName'] = \\\n self.user_options['hive_user']\n config['software_config']['properties']['hive:javax.jdo.option.ConnectionPassword'] = \\\n self.user_options['hive_passwd']\n\n # To handle custom Java & Scala packages, use the following code to get values:\n # self.user_options.get('java_packages', '')\n # self.user_options.get('scala_packages', '')\n\n return cluster_data\n\n def _is_custom_hive_settings(self):\n return self.user_options.get('hive_host') and self.user_options.get('hive_db') \\\n and self.user_options.get('hive_user') and self.user_options.get('hive_passwd')\n \n def _build_cluster_config(self, cluster_data=None):\n \"\"\" Creates a cluster definition based on different inputs:\n 1. Required data to start a dataproc cluster (name and project ID)\n 2. Values chosen by an end user through a form if any.\n 3. Admin-provided data through a YAML file (chosen by user or default one.)\n \"\"\"\n # Default required values that can be overwritten by the YAML file content\n # but must be set in case there is no form. \n cluster_data = cluster_data or {}\n cluster_zone = self.zone\n\n # Sets the cluster definition with form data.\n if self.user_options:\n metadata = {}\n \n # Reads values chosen by the user in the form and overwrites any existing\n # ones if relevant.\n gcs_config_file = self.user_options['cluster_type']\n cluster_zone = self.user_options.get('cluster_zone')\n\n # Reads the cluster config from yaml\n self.log.info(f'Reading config file at {gcs_config_file}')\n cluster_data = self.get_cluster_definition(gcs_config_file)\n\n # Defines default values if some key is not exists\n cluster_data['config'].setdefault(\"gce_cluster_config\", {})\n cluster_data['config'].setdefault(\"master_config\", {})\n cluster_data['config'].setdefault(\"initialization_actions\", [])\n cluster_data['config'].setdefault(\"software_config\", {})\n cluster_data['config']['software_config'].setdefault(\"properties\", {})\n\n if 'metadata' in cluster_data['config']['gce_cluster_config']:\n metadata = cluster_data['config']['gce_cluster_config']['metadata']\n\n # Sets default network for the cluster if not already provided in YAML.\n if 'subnetwork_uri' not in cluster_data['config']['gce_cluster_config']:\n if self.dataproc_default_subnet:\n (cluster_data['config']['gce_cluster_config']\n ['subnetwork_uri']) = self.dataproc_default_subnet\n\n # Cluster identity and scopes\n if 'service_account' not in cluster_data['config']['gce_cluster_config']:\n if self.dataproc_service_account:\n (cluster_data['config']['gce_cluster_config']\n ['service_account']) = self.dataproc_service_account\n (cluster_data['config']['gce_cluster_config']\n ['service_account_scopes']) = [\n \"https://www.googleapis.com/auth/cloud-platform\"]\n\n init_actions = []\n if self._is_idle_checker_enable():\n init_actions.append(\n {\n \"executable_file\": self.idle_checker.get('idle_job_path'),\n 'execution_timeout': {'seconds': 1800, 'nanos': 0}\n }\n )\n idle_path = self.idle_checker.get('idle_path')\n if idle_path.endswith(\"isIdle.sh\"):\n idle_path = idle_path[:-len(\"isIdle.sh\")]\n if idle_path.endswith(\"/\"):\n idle_path = idle_path[:-len(\"/\")]\n metadata[\"script_storage_location\"] = idle_path\n metadata[\"max-idle\"] = self.idle_checker.get('timeout', '60m')\n\n cluster_data['config']['gce_cluster_config']['metadata'] = metadata\n cluster_data['config']['initialization_actions'] = (\n init_actions + cluster_data['config']['initialization_actions']\n )\n\n if self.allow_custom_clusters and self.user_options.get('custom_cluster'):\n cluster_data = self._apply_users_configs(cluster_data)\n\n # Apply label to tag which host environment this cluster was spawned from\n cluster_data.setdefault('labels', {})\n cluster_data['labels']['goog-dataproc-notebook-spawner'] = (\n self.spawner_host_type.lower() if self.spawner_host_type != \"\" else \"unknown\"\n )\n \n # Always override project id and name\n cluster_data[\"project_id\"] = self.project\n cluster_data[\"cluster_name\"] = self.clustername()\n cluster_data.setdefault(\"config\", {})\n \n # Sets the zone. Which one overwrites is decided in the form logic.\n cluster_data['config'].setdefault('gce_cluster_config', {})\n cluster_data['config']['gce_cluster_config']['zone_uri'] = (\n f'''https://www.googleapis.com/compute/v1/projects/{self.project}/'''\n f'''zones/{cluster_zone}''')\n \n # Overwrites some existing data with required values.\n cluster_data['config'].setdefault('software_config', {})\n cluster_data['config']['software_config'].setdefault('properties', {})\n \n (cluster_data['config']['software_config']['properties']\n ['dataproc:jupyter.hub.args']) = self.args_str\n (cluster_data['config']['software_config']['properties']\n ['dataproc:jupyter.hub.env']) = self.env_str\n (cluster_data['config']['software_config']['properties']\n ['dataproc:jupyter.hub.enabled']) = 'true'\n if self.gcs_user_folder:\n (cluster_data['config']['software_config']['properties']\n ['dataproc:jupyter.notebook.gcs.dir']) = self.gcs_user_folder\n \n if 'image_version' not in cluster_data['config']['software_config']:\n cluster_data['config']['software_config']['image_version'] = '1.4.16-debian9'\n\n if self.force_add_jupyter_component:\n cluster_data['config']['software_config'].setdefault('optional_components', [])\n optional_components = cluster_data['config']['software_config']['optional_components']\n if 'JUPYTER' not in optional_components:\n optional_components.append('JUPYTER')\n if 'ANACONDA' not in optional_components:\n optional_components.append('ANACONDA')\n \n # Ensures that durations match the Protobuf format ({seconds:300, nanos:0})\n cluster_data = self.convert_string_to_duration(cluster_data.copy())\n \n # Checks that cluster subnet location matches with the Hub's one.\n # Must support all string patterns for subnetworkUri:\n # https://cloud.google.com/dataproc/docs/reference/rest/v1/ClusterConfig\n if 'subnetwork_uri' in cluster_data['config']['gce_cluster_config']:\n self._check_uri_geo(\n uri=cluster_data['config']['gce_cluster_config']['subnetwork_uri'],\n uri_geo_slice=-3,\n expected_geo=self.region\n )\n \n for server_group in ['master_config', 'worker_config', 'secondary_worker_config']:\n if server_group in cluster_data['config']:\n # We do not check the zone because the user form overwrites it.\n # MachineTypes and Accelerators must be in the same zone as the Dataproc\n # Cluster. Removes the zone reference if YAML provides a full uri.\n if 'machine_type_uri' in cluster_data['config'][server_group]:\n cluster_data['config'][server_group]['machine_type_uri'] = (\n cluster_data['config'][server_group]['machine_type_uri'].split('/')[-1])\n # Accelerator types must be in the same zone as the Dataproc Cluster.\n if 'accelerators' in cluster_data['config'][server_group]:\n for acc_idx, acc_val in enumerate(cluster_data['config'][server_group]\n ['accelerators']):\n (cluster_data['config'][server_group]['accelerators'][acc_idx]\n ['accelerator_type_uri']) = (acc_val['accelerator_type_uri'].split('/')[-1])\n \n # Temporarily disable setting preemptibility field until Dataproc client\n # libraries support the enum value\n if (cluster_data['config'].setdefault('master_config', {})):\n cluster_data['config']['master_config'].pop('preemptibility', None)\n if (cluster_data['config'].setdefault('worker_config', {})):\n cluster_data['config']['worker_config'].pop('preemptibility', None)\n if (cluster_data['config'].setdefault('secondary_worker_config', {})):\n cluster_data['config']['secondary_worker_config'].pop('preemptibility', None)\n\n # Strip cluster-specific namenode properties\n if (cluster_data['config'].setdefault('software_config', {}) and\n cluster_data['config']['software_config'].setdefault('properties', {})):\n cluster_data['config']['software_config']['properties'].pop('hdfs:dfs.namenode.lifeline.rpc-address', None)\n cluster_data['config']['software_config']['properties'].pop('hdfs:dfs.namenode.servicerpc-address', None)\n\n self.log.info(f'Cluster configuration data is {cluster_data}')\n return cluster_data\n","sub_path":"dataprocspawner/spawner.py","file_name":"spawner.py","file_ext":"py","file_size_in_byte":38128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"57714939","text":"\"\"\"Class to access NCBI's ftp server and easily download databases.\"\"\"\nimport tarfile\nimport re\nfrom time import time\nfrom datetime import datetime\nfrom multiprocessing.pool import ThreadPool\nimport os\nfrom shutil import make_archive\nfrom ftplib import error_perm, all_errors\n# from progress.bar import Bar\n# TODO Create a progress bar; Integrate with Threading/downloading\n\nfrom OrthoEvol.Tools.ftp.baseftp import BaseFTPClient\nfrom OrthoEvol.Tools.logit import LogIt\n\n\nclass NcbiFTPClient(BaseFTPClient):\n \"\"\"Access NCBI's FTP servers with ease.\"\"\"\n\n def __init__(self, email):\n _ncbi = 'ftp.ncbi.nlm.nih.gov'\n super().__init__(_ncbi, email, keepalive=False, debug_lvl=0)\n self._datafmt = '%m-%d-%Y@%I:%M:%S-%p'\n self._date = str(datetime.now().strftime(self._datafmt))\n self.blastpath = '/blast/'\n self.blastdb_path = '/blast/db/'\n self.blastfasta_path = '/blast/db/FASTA/'\n self.refseqrelease_path = '/refseq/release/'\n self.windowmasker_path = self.blastpath + 'windowmasker_files/'\n self._taxdb = 'taxdb.tar.gz' # Located in self.blastdb_path\n\n # TODO Use Turn into a json file, dict, or config\n self.blastdbs = []\n self.blastfastadbs = []\n\n # TODO Create dictionary of refseqrelease dbs, seqtypes, filetypes\n self.refseqreleasedbs = []\n self.refseqrelease_seqtypes = []\n self.refseqrelease_filetypes = []\n\n # Set up logger\n self.ncbiftp_log = LogIt().default(logname=\"NCBI-FTP\", logfile=None)\n\n @classmethod\n def _pathformat(cls, path):\n \"\"\"Ensure proper formatting of the path.\n\n :param path: FTP path.\n :type path: str\n \"\"\"\n\n pattern = re.compile('^/(.*?)/$')\n if not re.match(pattern, path):\n raise ValueError('Your path is not in a proper format.')\n\n @classmethod\n def _archive(cls, archive_name, folder2archive, archive_type='gztar'):\n \"\"\"Archive all the files in the folder and compress the archive.\n\n :param archive_name: Output name of archive.\n :param folder2archive: Name of the folder to archive.\n :param archive_type: (Default value = 'gztar')\n :return:\n \"\"\"\n\n os.chdir(folder2archive) # Enter the full path\n os.chdir('..')\n archive_location = os.path.join(os.getcwd(), archive_name)\n os.chdir(folder2archive)\n make_archive(archive_location, folder2archive, archive_type)\n\n def walk(self, path):\n \"\"\"Walk the ftp server and get files and directories.\n\n :param path: FTP path to be walked.\n \"\"\"\n\n file_list, dirs, nondirs = [], [], []\n try:\n self.ftp.cwd(path)\n except error_perm as ep:\n self.ncbiftp_log.info(\"Current path: %s\" % self.ftp.pwd() + ep.__str__() + path)\n return [], []\n else:\n self.ftp.retrlines('LIST', lambda x: file_list.append(x.split()))\n for info in file_list:\n ls_type, name = info[0], info[-1]\n if ls_type.startswith('d'):\n dirs.append(name)\n else:\n nondirs.append(name)\n return dirs, nondirs\n\n def download_file(self, filename):\n \"\"\"Download the files one by one.\n\n :param filename: Name of the file to download.\n :return:\n \"\"\"\n\n with open(filename, 'wb') as localfile:\n self.ftp.retrbinary('RETR %s' % filename, localfile.write)\n self.ncbiftp_log.info('%s was downloaded.' % str(filename))\n\n def _download_windowmasker(self, windowmaskerfilepath):\n \"\"\"Download the window masker files.\n\n :param windowmaskerfilepath: FTP path to windowmasker files.\n \"\"\"\n\n wmsplit = windowmaskerfilepath.split(sep='/')\n wmdir = wmsplit[0]\n wmfile = wmsplit[1]\n\n os.makedirs(wmdir, exist_ok=True)\n\n if not os.path.exists(os.path.join(wmdir, wmfile)):\n try:\n with open(os.path.join(wmdir, wmfile), 'wb') as localfile:\n self.ftp.retrbinary('RETR %s' % windowmaskerfilepath, localfile.write)\n self.ncbiftp_log.info('%s was downloaded.' % str(windowmaskerfilepath))\n except all_errors:\n os.remove(os.path.join(wmdir, wmfile))\n err_msg = '%s could not be download and was deleted.'\n self.ncbiftp_log.error(err_msg % str(windowmaskerfilepath))\n else:\n self.ncbiftp_log.info('%s exists.' % str(windowmaskerfilepath))\n\n @classmethod\n def extract_file(cls, file2extract):\n \"\"\"Extract a tar.gz file.\n\n :param file2extract: Path to the tar.gz file to extract.\n \"\"\"\n\n if str(file2extract).endswith('tar.gz'):\n tar = tarfile.open(file2extract)\n tar.extractall()\n tar.close()\n log_msg = 'Files were successfully extracted from %s'\n cls.ncbiftp_log.info(log_msg % file2extract)\n\n def listfiles(self, path='cwd'):\n \"\"\"List all files in a path.\n\n :param path: Directory path. (Default value = 'cwd')\n :return: A list of files in a directory.\n \"\"\"\n\n if path == 'cwd':\n path = self.ftp.pwd()\n path = path\n self._pathformat(path)\n _, files = self.walk(path)\n return files\n\n def listdirectories(self, path='cwd'):\n \"\"\"List all directories in a path.\n\n :param path: Directory path. (Default value = 'cwd')\n :return: A list of subdirectories.\n \"\"\"\n\n if path == 'cwd':\n path = self.ftp.pwd()\n path = path\n self._pathformat(path)\n directories, _ = self.walk(path)\n return directories\n\n def getwindowmaskerfiles(self, taxonomy_ids, download_path):\n \"\"\"Download NCBI's window masker binary files for each taxonomy id.\n\n :param taxonomy_ids: Input list of taxonomy ids.\n :param download_path: Path to download files to.\n :return:\n \"\"\"\n\n self.ftp.cwd(self.windowmasker_path)\n taxonomy_dirs = self.listdirectories(self.windowmasker_path)\n\n # Change to directory input\n unfound_species = []\n found_species = []\n for taxonomy_id in taxonomy_ids:\n if str(taxonomy_id) not in taxonomy_dirs:\n self.ncbiftp_log.warning('%s does not exist.' % taxonomy_id)\n unfound_species.append(taxonomy_id)\n else:\n found_species.append(taxonomy_id)\n\n windowmaskerfiles = []\n for found_taxid in found_species:\n filepath = str(found_taxid) + '/wmasker.obinary'\n windowmaskerfiles.append(filepath)\n\n self.ncbiftp_log.info('You are about to download theses files: %s' %\n windowmaskerfiles)\n\n # Move to directory for file downloads\n os.chdir(download_path)\n\n # Download the files using multiprocessing\n download_time_secs = time()\n with ThreadPool(1) as download_pool:\n download_pool.map(self._download_windowmasker, windowmaskerfiles)\n minutes = round(((time() - download_time_secs) / 60), 2)\n self.ncbiftp_log.info(\"Took %s minutes to download the files.\" %\n minutes)\n return unfound_species\n\n def getrefseqrelease(self, taxon_group, seqtype, seqformat, download_path,\n extract=True):\n \"\"\"Download the refseq release database.\n\n :param taxon_group:\n :param seqtype:\n :param seqformat:\n :param download_path:\n :param extract: (Default value = True)\n :return:\n \"\"\"\n\n self.ftp.cwd(self.refseqrelease_path)\n taxon_dirs = self.listdirectories(self.refseqrelease_path)\n\n # Change to directory input\n if taxon_group not in taxon_dirs:\n raise FileNotFoundError('%s does not exist.' % taxon_group)\n\n self.ftp.cwd(taxon_group)\n curpath = self.ftp.pwd() + '/'\n releasefiles = self.listfiles(curpath)\n\n files2download = []\n pattern = re.compile('^' + taxon_group + '[.](.*?)[.]' + seqtype\n + '[.]' + seqformat + '[.]gz$')\n for releasefile in releasefiles:\n if re.match(pattern, releasefile):\n files2download.append(releasefile)\n\n self.ncbiftp_log.info('You are about to download theses files: %s' %\n files2download)\n\n # Move to directory for file downloads\n os.chdir(download_path)\n\n # Download the files using multiprocessing\n download_time_secs = time()\n with ThreadPool(1) as download_pool:\n download_pool.map(self.download_file, files2download)\n minutes = round(((time() - download_time_secs) / 60), 2)\n self.ncbiftp_log.info(\"Took %s minutes to download the files.\" %\n minutes)\n\n if extract:\n extract_time_secs = time()\n with ThreadPool(1) as extract_pool:\n extract_pool.map(self.extract_file, files2download)\n minutes = round(((time() - extract_time_secs) / 60), 2)\n self.ncbiftp_log.info(\"Took %s minutes to extract from all files.\" %\n minutes)\n\n def getblastfasta(self, database_name, download_path, extract=True):\n \"\"\"Download the fasta sequence database (not formatted).\n\n :param database_name:\n :param download_path:\n :param extract: (Default value = True)\n \"\"\"\n\n if str(database_name).startswith('est'):\n raise NotImplementedError('Est dbs cannot be downloaded yet.')\n self.ftp.cwd(self.blastfasta_path)\n blastfastafiles = self.listfiles(self.blastfasta_path)\n\n files2download = []\n for dbfile in blastfastafiles:\n if database_name in str(dbfile):\n files2download.append(dbfile)\n\n # Append the taxonomy database\n files2download.append(self._taxdb)\n self.ncbiftp_log.info('You are about to download theses files: %s' %\n files2download)\n\n # Move to directory for file downloads\n os.chdir(download_path)\n\n # Download the files using multiprocessing\n download_time_secs = time()\n with ThreadPool(1) as download_pool:\n download_pool.map(self.download_file, files2download)\n minutes = round(((time() - download_time_secs) / 60), 2)\n self.ncbiftp_log.info(\"Took %s minutes to download the files.\" %\n minutes)\n\n if extract:\n extract_time_secs = time()\n with ThreadPool(1) as extract_pool:\n extract_pool.map(self.extract_file, files2download)\n minutes = round(((time() - extract_time_secs) / 60), 2)\n self.ncbiftp_log.info(\"Took %s minutes to extract from all files.\" %\n minutes)\n\n def getblastdb(self, database_name, download_path, extract=True):\n \"\"\"Download the formatted blast database.\n\n:param database_name: Name of preformatted blastdb to download.\n :param download_path: Directory path/location to download blastdb.\n :param extract (bool): True or False for extract tar.gz db files.\n\n\n\n :param database_name:\n\n :param download_path:\n\n :param extract: (Default value = True)\n\n\n\n \"\"\"\n\n if str(database_name).startswith('est'):\n raise NotImplementedError('Est dbs cannot be downloaded yet.')\n self.ftp.cwd(self.blastdb_path)\n blastdbfiles = self.listfiles(self.blastdb_path)\n\n files2download = []\n for dbfile in blastdbfiles:\n if database_name in str(dbfile):\n files2download.append(dbfile)\n\n # Append the taxonomy database\n files2download.append(self._taxdb)\n\n # Move to directory for file downloads\n os.chdir(download_path)\n\n absentfiles = []\n\n # Ensure that files aren't already downloaded\n for file2download in files2download:\n if not os.path.exists(os.path.join(download_path, file2download)):\n absentfiles.append(file2download)\n\n if len(absentfiles) > 0:\n self.ncbiftp_log.info('You are about to download these files: %s\\n' %\n absentfiles)\n # Download the files using multiprocessing\n download_time_secs = time()\n with ThreadPool(1) as download_pool:\n download_pool.map(self.download_file, files2download)\n minutes = round(((time() - download_time_secs) / 60), 2)\n self.ncbiftp_log.info(\"Took %s minutes to download the files.\\n\" %\n minutes)\n\n if extract:\n self.ncbiftp_log.info('Now it\\'s time to extract files.')\n extract_time_secs = time()\n with ThreadPool(3) as extract_pool:\n extract_pool.map(self.extract_file, files2download)\n minutes = round(((time() - extract_time_secs) / 60), 2)\n self.ncbiftp_log.info(\"Took %s minutes to extract from all files.\\n\" %\n minutes)\n\n # Remove all tar.gz files\n curfiles = os.listdir()\n for curfile in curfiles:\n if str(curfile).endswith('tar.gz'):\n os.remove(curfile)\n\n def updatedb(self, database_path=os.getcwd(), update_days=7):\n \"\"\"Check for when the database was last updated.\n\n .. note: Refseq release databases should only be updated every few\n months.\n\n :param database_path: Directory path of existing database.\n (Default value = os.getcwd()\n :param update_days (int): Number of days to update.\n :return:\n \"\"\"\n\n # TODO Prevent users from updated refseq if certain days\n # Get a list of the files in the path\n filesinpath = os.listdir(database_path)\n for fileinpath in filesinpath:\n if str(fileinpath).endswith('.nal'):\n nalfile = str(fileinpath)\n dbname, ext = nalfile.split('.')\n filetime = datetime.fromtimestamp(os.path.getctime(nalfile))\n format_filetime = filetime.strftime(\"%b %d, %Y at %I:%M:%S %p\")\n\n elif str(fileinpath).endswith('.gbff'):\n gbff_file = str(fileinpath)\n taxon_group, _, seqtype, ext = gbff_file.split('.')\n filetime = datetime.fromtimestamp(os.path.getctime(gbff_file))\n format_filetime = filetime.strftime(\"%b %d, %Y at %I:%M:%S %p\")\n\n self.ncbiftp_log.info(\"Your database was last updated on: %s\" %\n format_filetime)\n\n time_elapsed = datetime.now() - filetime\n\n if ext == 'nal' and time_elapsed.days >= update_days:\n self.ncbiftp_log.warning('\\nYour blast database needs updating.')\n archive_name = \"blastdb_archive_\" + self._date\n self._archive(archive_name, folder2archive=database_path)\n self.getblastdb(dbname, download_path=database_path, extract=True)\n\n elif ext == 'gbff' and time_elapsed.days >= 70:\n self.ncbiftp_log.warning('\\nYour refseq release database needs updating.')\n archive_name = \"refseqrelease_archive_\" + self._date\n self._archive(archive_name, folder2archive=database_path)\n\n # TODO Create a way to get seqtype and seqformat from filename\n self.getrefseqrelease(taxon_group, seqtype, ext, database_path,\n extract=True)\n\n # TODO Add elif for handling databases not handled by this class.\n\n elif ext != 'nal' or 'gbff':\n raise NotImplementedError(\"Updating for that database is unsupported.\")\n\n else:\n self.ncbiftp_log.info('\\nYour database is still up to date.')\n","sub_path":"OrthoEvol/Tools/ftp/ncbiftp.py","file_name":"ncbiftp.py","file_ext":"py","file_size_in_byte":16064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"236747305","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def buildTree(self, preorder, inorder):\n \"\"\"\n :type preorder: List[int]\n :type inorder: List[int]\n :rtype: TreeNode\n \"\"\"\n def build_tree(preorder, pre_start, pre_end, inorder, in_start, in_end):\n if pre_start == pre_end:\n return None\n root = TreeNode(preorder[pre_start])\n root_idx = inorder.index(root.val)\n left_tree_size = root_idx - in_start\n # Split inorder array for left and right subtree.\n root.left = build_tree(\n preorder, pre_start+1, pre_start+1+left_tree_size,\n inorder, in_start, in_start+left_tree_size)\n root.right = build_tree(\n preorder, pre_start+1+left_tree_size, pre_end,\n inorder, in_start+left_tree_size+1, in_end)\n return root\n \n return build_tree(preorder, 0, len(preorder), inorder, 0, len(inorder))\n\n","sub_path":"python2/l0105_construct_binary_tree_from_preorder_and_inorder_traversal.py","file_name":"l0105_construct_binary_tree_from_preorder_and_inorder_traversal.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"485795781","text":"from django.shortcuts import render, render_to_response, get_object_or_404, redirect\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth import login as auth_login\nfrom django.contrib.auth import logout as auth_logout\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom django.template import RequestContext\nfrom .forms import AdForm, CatForm, ProdForm, FeedForm, NameForm, LoginForm\nfrom django.contrib.auth.decorators import login_required\nfrom pymongo import MongoClient\nimport random, string, imghdr, datetime\nfrom axes.decorators import watch_login\nfrom bson.json_util import dumps\nimport datetime\nfrom pymongo import MongoClient\nfrom bson.objectid import ObjectId\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.urls import reverse\nfrom django.conf import settings as django_settings\n\nimport json, random, string, ast, os\n\n\n# client = MongoClient('localhost', 27017)\n# user_db= client.insale\n\n\nclient = MongoClient(\"mongodb://prince:princesharzeel@ds129143.mlab.com:29143/insale\")\nuser_db = client.insale # define database used\n\n\ndef home(request):\n ls = user_db.ads.find({\"verified\": \"yes\"}).sort([(\"time\", -1)]).limit(5)\n return render(request, \"index.html\", {\"result\": ls})\n\n\ndef image(f, i):\n ext = imghdr.what(f)\n if ext in [\"jpeg\", \"png\", \"bmp\"]:\n a = \"\".join(\n random.SystemRandom().choice(\n string.ascii_uppercase + string.ascii_lowercase + string.digits\n )\n for _ in range(3)\n )\n\n path = \"static/media/\" + i + \".\" + ext\n try:\n with open(path, \"wb+\") as destination:\n for chunk in f.chunks():\n destination.write(chunk)\n except:\n return \"/static/media/default.jpg\"\n return \"/static/media/\" + i + \".\" + ext\n else:\n return 0\n\n\ndef index(request):\n print(\"a\")\n if request.method == \"POST\":\n print(\"b\")\n form = AdForm(request.POST, request.FILES)\n if form.is_valid():\n if \"pica\" in request.FILES:\n url = image(request.FILES[\"pica\"], \"pica\" + request.POST[\"ftitle\"])\n if url == 0:\n messages.error(request, \"Not an image\")\n return HttpResponseRedirect(request, \"/login/\")\n picture_a = url\n else:\n picture_a = \"/static/media/default.jpg\"\n\n if \"picb\" in request.FILES:\n url = image(request.FILES[\"picb\"], \"picb\" + request.POST[\"ftitle\"])\n if url == 0:\n messages.error(request, \"Not an image\")\n return HttpResponseRedirect(request, \"/login/\")\n picture_b = url\n else:\n picture_b = \"/static/media/default.jpg\"\n\n if \"picc\" in request.FILES:\n url = image(request.FILES[\"picc\"], \"picc\" + request.POST[\"ftitle\"])\n if url == 0:\n messages.error(request, \"Not an image\")\n return HttpResponseRedirect(request, \"/login/\")\n picture_c = url\n else:\n picture_c = \"/static/media/default.jpg\"\n\n print(\"c\")\n name = form.cleaned_data[\"fname\"]\n\n mobile = form.cleaned_data[\"fmobile\"]\n email = form.cleaned_data[\"femail\"]\n location = form.cleaned_data[\"flocation\"]\n room = form.cleaned_data[\"froom\"]\n title = form.cleaned_data[\"ftitle\"]\n\n desc = form.cleaned_data[\"fdesc\"]\n cat = form.cleaned_data[\"fcat\"]\n price = form.cleaned_data[\"fprice\"]\n date = form.cleaned_data[\"fdate\"]\n\n timestamp = \"{:%d-%b-%Y %H:%M:%S}\".format(datetime.datetime.now())\n\n details = {\n \"name\": name,\n \"mobile\": mobile,\n \"email\": email,\n \"location\": location,\n \"pica\": picture_a,\n \"picb\": picture_b,\n \"picc\": picture_c,\n \"time\": timestamp,\n \"room\": room,\n \"title\": title,\n \"desc\": desc,\n \"cat\": cat,\n \"price\": price,\n \"date\": date,\n \"verified\": \"no\",\n }\n\n a = user_db.ads.find_one({\"title\": title})\n\n if a is not None:\n messages.error(request, \"Select another title\")\n return render(request, \"post-ad.html\")\n\n user_db.ads.insert(details)\n\n messages.success(request, \"Product Added for Verification by Admin\")\n return HttpResponseRedirect(\"/\")\n else:\n print(form.errors)\n messages.error(request, \"Error in form filling\")\n return render(request, \"post-ad.html\")\n\n form = AdForm()\n\n return render(request, \"post-ad.html\")\n\n\ndef prod_details(request, prod_name):\n title = prod_name\n a = user_db.ads.find_one({\"title\": title})\n details = {\n \"name\": a[\"name\"],\n \"mobile\": a[\"mobile\"],\n \"email\": a[\"email\"],\n \"pica\": a[\"pica\"],\n \"picc\": a[\"picc\"],\n \"picb\": a[\"picb\"],\n \"date\": a[\"date\"],\n \"time\": a[\"time\"],\n \"location\": a[\"location\"],\n \"room\": a[\"room\"],\n \"title\": a[\"title\"],\n \"desc\": a[\"desc\"],\n \"cat\": a[\"cat\"],\n \"price\": a[\"price\"],\n }\n\n return render(request, \"single.html\", {\"form\": details})\n\n\ndef category(request, catname):\n if catname == \"All\":\n a = user_db.ads.find({\"verified\": \"yes\"})\n form = CatForm()\n ls = user_db.ads.find({\"verified\": \"yes\"}, limit=5).sort([(\"time\", -1)])\n return render(request, \"cars.html\", {\"result\": a, \"latest\": ls})\n\n a = user_db.ads.find({\"cat\": catname, \"verified\": \"yes\"})\n form = CatForm()\n ls = user_db.ads.find({\"verified\": \"yes\"}, limit=5).sort([(\"time\", -1)])\n return render(request, \"cars.html\", {\"result\": a, \"latest\": ls})\n\n\ndef searchlist(request):\n if request.method == \"POST\":\n form = CatForm(request.POST)\n print(form.errors)\n if form.is_valid():\n loc = form.cleaned_data[\"location\"]\n category = form.cleaned_data[\"category\"]\n print(loc)\n print(category)\n\n latead = user_db.ads.find({\"verified\": \"yes\"}, limit=5).sort([(\"time\", -1)])\n if loc == \"All\":\n if category == \"All\":\n ls = user_db.ads.find({\"verified\": \"yes\"})\n\n return render(\n request, \"cars.html\", {\"result\": ls, \"latest\": latead}\n )\n ls = user_db.ads.find({\"cat\": category, \"verified\": \"yes\"})\n print(\"category #####huru\")\n return render(request, \"cars.html\", {\"result\": ls, \"latest\": latead})\n\n if category == \"All\":\n ls = user_db.ads.find({\"location\": loc, \"verified\": \"yes\"})\n return render(request, \"cars.html\", {\"result\": ls, \"latest\": latead})\n prods = user_db.ads.find({\"cat\": category, \"location\": loc})\n if prods is None:\n return HttpResponseRedirect(\"/list/All\")\n return render(request, \"cars.html\", {\"result\": prods, \"latest\": latead})\n\n form = CatForm()\n\n return HttpResponseRedirect(\"/list/All\")\n\n\ndef owner(request):\n tot = user_db.ads.find({}).count()\n\n verif_prod = user_db.ads.find({\"verified\": \"yes\"})\n revenue = 0\n for i in verif_prod:\n revenue = revenue + int(i[\"price\"])\n\n ls = user_db.ads.find({\"verified\": \"no\"})\n counter = ls.count()\n\n print(revenue)\n return render(\n request,\n \"dashboard.html\",\n {\"prods\": ls, \"revenue\": revenue, \"counter\": counter, \"total\": tot},\n )\n\n\ndef product_update(request, prodname):\n\n if request.method == \"POST\":\n print(\"yes pressed it is\")\n form = ProdForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data[\"fname\"]\n\n mobile = form.cleaned_data[\"fmobile\"]\n email = form.cleaned_data[\"femail\"]\n location = form.cleaned_data[\"flocation\"]\n room = form.cleaned_data[\"froom\"]\n title = form.cleaned_data[\"ftitle\"]\n\n desc = form.cleaned_data[\"fdesc\"]\n cat = form.cleaned_data[\"fcat\"]\n price = form.cleaned_data[\"fprice\"]\n date = form.cleaned_data[\"fdate\"]\n details = {\n \"name\": name,\n \"mobile\": mobile,\n \"email\": email,\n \"location\": location,\n \"room\": room,\n \"title\": title,\n \"desc\": desc,\n \"cat\": cat,\n \"price\": price,\n \"date\": date,\n }\n\n a = user_db.ads.find_one({\"title\": prodname})\n\n user_db.ads.update_one(\n {\"title\": prodname},\n {\n \"$set\": {\n \"name\": name,\n \"mobile\": mobile,\n \"email\": email,\n \"location\": location,\n \"room\": room,\n \"title\": title,\n \"desc\": desc,\n \"cat\": cat,\n \"price\": price,\n \"date\": date,\n }\n },\n upsert=True,\n )\n\n messages.success(request, prodname + \" Updated\")\n return HttpResponseRedirect(\"/stock\")\n else:\n print(form.errors)\n messages.error(request, \"Error in form filling\")\n return render(request, \"user.html\")\n\n form = ProdForm()\n a = user_db.ads.find_one({\"title\": prodname})\n print(a)\n details = {\n \"name\": a[\"name\"],\n \"mobile\": a[\"mobile\"],\n \"email\": a[\"email\"],\n \"location\": a[\"location\"],\n \"pica\": a[\"pica\"],\n \"picc\": a[\"picc\"],\n \"picb\": a[\"picb\"],\n \"pica\": a[\"pica\"],\n \"picc\": a[\"picc\"],\n \"picb\": a[\"picb\"],\n \"room\": a[\"room\"],\n \"title\": a[\"title\"],\n \"desc\": a[\"desc\"],\n \"cat\": a[\"cat\"],\n \"price\": a[\"price\"],\n \"date\": a[\"date\"],\n }\n print(details)\n\n return render(request, \"user.html\", {\"prod\": details})\n\n\ndef click_del(request, prodname):\n user_db.ads.remove({\"title\": prodname})\n return HttpResponseRedirect(\"/owner\")\n\n\ndef verif(request, prodname):\n user_db.ads.update_one(\n {\"title\": prodname}, {\"$set\": {\"verified\": \"yes\"}}, upsert=True\n )\n return HttpResponseRedirect(\"/owner\")\n\n\ndef rempic(request, pic):\n print(pic)\n a = user_db.ads.find_one({\"pica\": pic})\n b = user_db.ads.find_one({\"picb\": pic})\n c = user_db.ads.find_one({\"picc\": pic})\n if a is not None:\n user_db.ads.update_one(\n {\"pica\": pic}, {\"$set\": {\"pica\": \"/static/media/default.jpg\"}}, upsert=True\n )\n title = a[\"title\"]\n\n if b is not None:\n user_db.ads.update_one(\n {\"picb\": pic}, {\"$set\": {\"picb\": \"/static/media/default.jpg\"}}, upsert=True\n )\n title = b[\"title\"]\n\n if c is not None:\n user_db.ads.update_one(\n {\"picc\": pic}, {\"$set\": {\"picc\": \"/static/media/default.jpg\"}}, upsert=True\n )\n title = c[\"title\"]\n return HttpResponseRedirect(\"/product/\" + title)\n\n\nfrom requests_oauthlib import OAuth2Session\nfrom requests_oauthlib.compliance_fixes import facebook_compliance_fix\n\nclient_id = \"\"\nclient_secret = \"\"\nredirect_uri = \"\"\nif django_settings.DEBUG:\n redirect_uri = \"http://localhost:8000/signup/\"\nfb_state = \"\"\n# Create your views\ndef logfb(request):\n authorization_base_url = (\n \"https://www.facebook.com/dialog/oauth/?scope=user_friends,email,public_profile\"\n )\n token_url = \"https://graph.facebook.com/oauth/access_token/\"\n # redirect_uri = 'https://pacific-shelf-88987.herokuapp.com/redirect_facebook/'\n facebook = OAuth2Session(client_id, redirect_uri=redirect_uri)\n facebook = facebook_compliance_fix(facebook)\n authorization_url, state = facebook.authorization_url(authorization_base_url)\n return HttpResponseRedirect(authorization_url)\n\n\ndef signup(request):\n if request.method == \"GET\":\n try:\n code = request.GET[\"code\"]\n request.session[\"code\"] = code\n state = request.GET[\"state\"]\n except Exception as e:\n print(e)\n return HttpResponseRedirect(\"/\")\n else:\n if True:\n authorization_base_url = (\n \"https://www.facebook.com/dialog/oauth/?scope=email,public_profile\"\n )\n token_url = \"https://graph.facebook.com/oauth/access_token\"\n\n facebook = OAuth2Session(client_id, redirect_uri=redirect_uri)\n facebook = facebook_compliance_fix(facebook)\n facebook.fetch_token(token_url, client_secret=client_secret, code=code)\n\n r3 = facebook.get(\n \"https://graph.facebook.com/v2.8/me/friends/?limit=500\"\n )\n r2 = facebook.get(\n \"https://graph.facebook.com/v2.8/me?fields=id,name,email\"\n )\n\n entry = json.loads(r3.content.decode(\"utf-8\"))\n print(entry)\n try:\n u = get_object_or_404(users, uid=entry[\"id\"])\n user = get_object_or_404(User, username=entry[\"id\"])\n try:\n friends_raw = json.loads(r3.content.decode(\"utf-8\"))\n except Exception as e:\n f = open(log_file, \"a\")\n print(\n str(getframeinfo(currentframe()).lineno) + \" - \" + str(e),\n file=f,\n )\n f.close()\n raise\n u = get_object_or_404(users, uid=entry[\"id\"])\n flag = False\n login(request, user)\n u.picture = (\n \"https://graph.facebook.com/\" + u.uid + \"/picture?type=large\"\n )\n u.save()\n if not u.address_set.all().exists():\n return HttpResponseRedirect(\"/additional-details\")\n return HttpResponseRedirect(\"/dashboard\")\n except Exception as e:\n if \"email\" not in entry:\n entry[\"email\"] = \"example@eg.com\"\n entry1 = users(\n name=entry[\"name\"],\n email=entry[\"email\"],\n uid=entry[\"id\"],\n picture=\"https://graph.facebook.com/\"\n + entry[\"id\"]\n + \"/picture?type=large\",\n )\n with transaction.atomic():\n entry1.save()\n User.objects.create_user(\n username=entry[\"id\"],\n email=entry[\"email\"],\n password=\"\".join(\n random.SystemRandom().choice(\n string.ascii_uppercase\n + string.ascii_lowercase\n + string.digits\n )\n for _ in range(12)\n ),\n )\n\n # invitable_friends = []\n # invitable_friends_raw = json.loads(r1.content.decode(\"utf-8\"))\n # for friend in invitable_friends_raw[\"data\"]:\n # invitable_friends.append(friend)\n\n friends_raw = json.loads(r3.content.decode(\"utf-8\"))\n u = get_object_or_404(users, uid=entry[\"id\"])\n flag = False\n for friend in friends_raw[\"data\"]:\n try:\n u2 = get_object_or_404(users, uid=friend[\"id\"])\n u.primary.create(secondary=u2, level=2)\n u2.primary.create(secondary=u, level=2)\n flag = True\n except Exception as e:\n f = open(log_file, \"a\")\n print(\n str(getframeinfo(currentframe()).lineno) + \" - \" + str(e),\n file=f,\n )\n f.close()\n continue\n\n user = get_object_or_404(User, username=entry[\"id\"])\n login(request, user)\n if flag:\n return HttpResponseRedirect(\"/imported-contacts\")\n else:\n return HttpResponseRedirect(\"/additional-details\")\n else:\n messages.add_message(request, messages.ERROR, \"State Mismatch\")\n return HttpResponseRedirect(\"/\")\n\n\ndef stock(request):\n\n ls = user_db.ads.find({}).distinct(\"cat\")\n mo = user_db.ads.find({\"cat\": \"Mobiles\", \"verified\": \"yes\"})\n fa = user_db.ads.find({\"cat\": \"Fashion\", \"verified\": \"yes\"})\n ex = user_db.ads.find({\"cat\": \"Extras\", \"verified\": \"yes\"})\n bsh = user_db.ads.find({\"cat\": \"Books, Sports & hobbies\", \"verified\": \"yes\"})\n ea = user_db.ads.find({\"cat\": \"Electronics & Appliances\", \"verified\": \"yes\"})\n\n fur = user_db.ads.find({\"cat\": \"Furniture\", \"verified\": \"yes\"})\n print(fa.count())\n\n return render(\n request,\n \"stock.html\",\n {\"ls\": ls, \"mo\": mo, \"fa\": fa, \"ex\": ex, \"bsh\": bsh, \"ea\": ea, \"fur\": fur},\n )\n\n\ndef feed(request):\n if request.method == \"POST\":\n print(\"yes pressed it is\")\n form = FeedForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data[\"fname\"]\n\n lname = form.cleaned_data[\"flname\"]\n email = form.cleaned_data[\"fmail\"]\n feedback = form.cleaned_data[\"fmsg\"]\n\n if len(feedback) != 0:\n print(feedback)\n try:\n user_db.feed.insert(\n {\"name\": name, \"mail\": email, \"lname\": lname, \"msg\": feedback}\n )\n except:\n messages.errors(request, \"Error occured.Please try again later\")\n return HttpResponseRedirect(\"/feed\")\n else:\n messages.success(request, \"Thanks for your feedback !!!\")\n return HttpResponseRedirect(\"/feed\")\n else:\n messages.success(request, \"Error occured.Empty Feedback\")\n return HttpResponseRedirect(\"/feed\")\n else:\n form = FeedForm()\n return render(request, \"contact.html\")\n\n\ndef feedview(request):\n feeds = user_db.feed.find({})\n return render(request, \"table.html\", {\"feeds\": feeds})\n\n\ndef namecont(request):\n if request.method == \"POST\":\n form = NameForm(request.POST)\n if form.is_valid():\n\n latead = user_db.ads.find({\"verified\": \"yes\"}, limit=5).sort([(\"time\", -1)])\n key = form.cleaned_data[\"fsearch\"]\n\n ls = user_db.ads.find(\n {\"verified\": \"yes\", \"title\": {\"$regex\": key, \"$options\": \"i\"}}\n )\n if ls is None:\n return HttpResponseRedirect(\"/searchlist\")\n return render(request, \"cars.html\", {\"result\": ls, \"latest\": latead})\n else:\n return HttpResponseRedirect(\"/searchlist\")\n\n\ndef power(request):\n if request.method == \"POST\":\n l_form = LoginForm(request.POST)\n if l_form.is_valid():\n\n email = l_form.cleaned_data[\"fail\"]\n psd = l_form.cleaned_data[\"fswd\"]\n\n if email == \"home@insale\" and psd == \"857414\":\n return HttpResponseRedirect(\"/owner\")\n else:\n messages.error(request, \"Email or Password incorrect\")\n return HttpResponseRedirect(\"/log\")\n\n messages.error(request, \"Fill the form correctly\")\n return render(request, \"log.html\", {\"l_form\": l_form})\n l_form = LoginForm()\n return render(request, \"log.html\", {\"l_form\": l_form})\n","sub_path":"ins/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":20449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"155601735","text":"import tempfile\nimport csv\nimport ast\n\nfrom django.http import HttpResponseRedirect\nfrom django import forms\nfrom django.shortcuts import render_to_response\nfrom django.template.context_processors import csrf\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\n# Could be in library of forms\nclass CsvFileUploadForm(forms.Form):\n file = forms.FileField(label=\"Address Book (csv format)\")\n\ndef handle_uploaded_file(f):\n \"\"\"Saves uploaded file to temp space (no delete)\"\"\"\n\n #fp = tempfile.NamedTemporaryFile(prefix=\"addr_\", suffix=\".csv\", dir=\"/home/marc/uploads/\", delete=False)\n fp = tempfile.NamedTemporaryFile(prefix=\"addr_\", suffix=\".csv\", delete=False)\n\n for chunk in f.chunks():\n fp.write(chunk)\n\n fp.close()\n return fp.name\n\ndef map_csvfile(csvreader, header):\n \"\"\"Normalize csv address book to our format for display and storage\"\"\"\n\n # return list of dict items\n # { \"name\": ..., \"addr\": ..., \"city\": ..., \"state\": ...,\n # \"zip\": ..., \"country\": ..., \"phone_number\": ... }\n fieldnames = csvreader.fieldnames\n\n name_map = []\n addr_map = []\n city_map = []\n state_map = []\n zip_map = []\n country_map = []\n phone_map = []\n\n if \"name\" in fieldnames:\n name_map.append(\"name\")\n # else: # different formats/mappings\n\n if \"address1\" in fieldnames:\n addr_map.append(\"address1\")\n\n if \"address2\" in fieldnames:\n addr_map.append(\"address2\")\n\n if \"city\" in fieldnames:\n city_map.append(\"city\")\n\n if \"state\" in fieldnames:\n state_map.append(\"state\")\n\n if \"postal_code\" in fieldnames:\n zip_map.append(\"postal_code\")\n\n if \"country\" in fieldnames:\n country_map.append(\"country\")\n\n if \"phone_number\" in fieldnames:\n phone_map.append(\"phone_number\")\n\n # now that mappings are set up, start consuming csv\n addr_book = []\n for row in csvreader:\n mapped_row = {}\n mapped_row['name'] = ' '.join([row[x] for x in name_map]).strip()\n mapped_row['addr'] = '\\n'.join([row[x] for x in addr_map]).strip()\n mapped_row['city'] = ' '.join([row[x] for x in city_map]).strip()\n mapped_row['state'] = ' '.join([row[x] for x in state_map]).strip()\n mapped_row['zip'] = '-'.join([row[x] for x in zip_map]).strip(' -')\n mapped_row['country'] = ' '.join([row[x] for x in country_map]).strip()\n mapped_row['phone_number'] = '-'.join([row[x] for x in phone_map]).strip()\n mapped_row['number'] = len(addr_book)\n addr_book.append(mapped_row)\n\n return addr_book\n\ndef upload_file(request):\n if request.method == \"POST\":\n form = CsvFileUploadForm(request.POST, request.FILES)\n if form.is_valid():\n request.session['upload_file'] = handle_uploaded_file(request.FILES['file'])\n try:\n # clear out session var if uploaded a file\n del request.session['preview_file']\n except KeyError:\n pass\n return HttpResponseRedirect('/preview')\n else:\n form = CsvFileUploadForm()\n\n form_dict = {'form': form}\n form_dict.update(csrf(request))\n return render_to_response('upload.html', form_dict)\n\n\ndef preview_addr_book(request):\n DISPLAY_CONTACTS = 10\n try:\n addr_file = request.session['preview_file']\n # load preview file\n try:\n fp = open(addr_file)\n except IOError:\n # possibly old session, throw error to try and load upload file\n raise KeyError\n\n contacts_full = []\n for line in fp:\n line = line.rstrip()\n if not line:\n continue\n contacts_full.append(ast.literal_eval(line))\n fp.close()\n\n except KeyError:\n # we haven't created a scrubbed file yet\n try:\n addr_file = request.session['upload_file']\n except KeyError:\n # no file, so go to upload page\n return HttpResponseRedirect('/upload')\n\n fp = open(addr_file)\n\n csvfile = csv.DictReader(fp)\n header = csvfile.next()\n # map_csvfile will parse and extract the fields we need\n contacts_full = map_csvfile(csvfile, header)\n csvfile = None\n fp.close()\n # now rewrite our address book file with our extracted fields\n import os\n os.unlink(addr_file)\n del request.session['upload_file']\n addr_file += \".list\"\n request.session['preview_file'] = addr_file\n # now save scrubbed file\n fp = open(addr_file, \"wt\")\n for contact in contacts_full:\n print >> fp, str(contact)\n fp.close()\n\n paginator = Paginator(contacts_full, DISPLAY_CONTACTS)\n\n contact_number = request.GET.get('del')\n if contact_number is not None:\n # mark item for deletion\n try:\n contacts_full[int(contact_number)]['delete'] = '1'\n # now update scrubbed file\n fp = open(addr_file, \"wt\")\n for contact in contacts_full:\n print >> fp, str(contact)\n fp.close()\n except IndexError:\n # invalid number, just continue\n pass\n\n contact_number = request.GET.get('undel')\n if contact_number is not None:\n # unmark item for deletion\n try:\n del contacts_full[int(contact_number)]['delete']\n # now update scrubbed file\n fp = open(addr_file, \"wt\")\n for contact in contacts_full:\n print >> fp, str(contact)\n fp.close()\n except IndexError:\n # invalid number, just continue\n pass\n\n page = request.GET.get('page')\n try:\n contacts = paginator.page(page)\n except PageNotAnInteger:\n contacts = paginator.page(1)\n except EmptyPage:\n contacts = paginator.page(paginator.num_pages)\n total_contacts = len(contacts_full)\n form_dict = {'contacts': contacts, 'total_contacts': total_contacts, 'display_contacts': DISPLAY_CONTACTS}\n form_dict.update(csrf(request))\n return render_to_response('preview.html', form_dict)\n","sub_path":"soctest/contactmgr/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"210932318","text":"#!/usr/bin/env python3\n\nx, k, d = list(map(int, input().split()))\n\nif x < 0:\n x *= -1\n\nnum = x//d\n\nif num >= k:\n print(x-d*k)\n exit()\nelse:\n tmp = k-num\n if tmp % 2 == 0:\n print(x-d*num)\n else:\n print(d*(num+1)-x)\n","sub_path":"abc175/c/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"275549344","text":"import csv\nimport random\nimport requests\nimport copy\nimport time\n\nclass FakeFile:\n def __init__(self, filename):\n self.name = filename \n self.contents = \"\"\n\n def write(self,contents):\n self.contents += contents\n\n def __repr__(self):\n return self.contents\n\ndef gen_csv(rows, cols, possible_headers):\n out = FakeFile(\"{}by{}.csv\".format(rows, cols))\n \n pos = copy.deepcopy(possible_headers)\n contents = []\n headers = []\n \n for i in range(cols):\n header = random.choice(pos)\n pos.pop(pos.index(header))\n headers.append(header)\n \n contents.append(tuple(headers))\n\n for i in range(rows):\n x = []\n for j in range(cols):\n x.append(random.random() * (10**random.randint(0, 6)))\n contents.append(tuple(x))\n\n w = csv.writer(out)\n for c in contents:\n w.writerow(c)\n return out\n\ndef send_csv(csv, url):\n p = requests.post(url, data=str(csv))\n\n\nif __name__ == \"__main__\":\n headers = open(\"headers\", 'r').read().split()\n for i in range(random.randint(15,260)):\n if len(headers) > 0:\n fake = gen_csv(random.randint(10,340), random.randint(1, len(headers)), headers)\n send_csv(fake, \"http://yeet.stream:42069/\")\n print(\"Sent csv number {}\".format(i))\n time.sleep(random.randint(0,14))\n","sub_path":"Forensics/TheTicker/sender/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"647836413","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\nfrom scipy.cluster.hierarchy import dendrogram,ward,leaves_list\n\nif __name__ == '__main__':\n co_list = list()\n with open('data/knock96.dump', 'rb') as i_f:\n model_dict = pickle.load(i_f)\n for num,item in enumerate(model_dict.items()):\n co_list.append(item[0])\n if num == 0:\n mat = item[1]\n continue\n mat = np.vstack((mat,item[1]))\n h_cls = ward(mat)\n dendrogram(h_cls,labels=co_list)\n plt.show()\n","sub_path":"yohta/chapter10/knock98.py","file_name":"knock98.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"177992707","text":"#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport statistics\nimport random\nimport networkx as nx\n\n\ndef read_fastq(name_file):\n \"\"\"\n Read the sequence of the fastq file\n :param name_file: name of the fastq file\n :return: yield of each sequence\n \"\"\"\n with open(name_file) as file:\n iteration = -1\n for line in file:\n if iteration != -1 and iteration % 4 == 0:\n yield line.strip()\n iteration = iteration + 1\n\n\ndef cut_kmer(seq, kmer):\n \"\"\"\n Cut the sequence in kmer of kmer_length\n :param seq: input sequence\n :param kmer: kmer length\n :return: yiel of kmer\n \"\"\"\n if len(seq) < kmer:\n print('Erreur')\n else:\n for i in range(0, len(seq) - kmer + 1):\n yield seq[i:(i + kmer)]\n\n\ndef build_kmer_dict(name_file, kmer):\n \"\"\"\n Read the fastd seq, cut it in kmer and creat a dictionnary of each kmer with their count\n :param name_file: name of fastq file\n :param kmer: kmer legth\n :return: a dictionnary a kmer with their count\n \"\"\"\n liste_seq = []\n for i in read_fastq(name_file):\n liste_seq.append(i)\n\n dico_kmer = {}\n for j in range(len(liste_seq)):\n liste_kmer = []\n for i in cut_kmer(liste_seq[j], kmer):\n liste_kmer.append(i)\n\n for i in range(len(liste_kmer)):\n if liste_kmer[i] not in dico_kmer:\n dico_kmer[liste_kmer[i]] = liste_kmer.count(liste_kmer[i])\n return dico_kmer\n\n\ndef build_graph(dico_kmer):\n \"\"\"\n Create a graphe of prefixe - suffixe of each kmer in the kmer dictionnary\n :param dico_kmer: dictionnary of kmer with their count\n :return: directed graphe build with the networkx library\n \"\"\"\n graphe = nx.DiGraph()\n for i in dico_kmer:\n graphe.add_edge(i[:-1], i[1:], weight=dico_kmer[i])\n return graphe\n\n\ndef get_starting_nodes(graphe):\n \"\"\"\n Returning all the starting nodes of a graphe\n :param graphe: DiGrah of kmer_dict\n :return: a list of starting nodes\n \"\"\"\n list_enter = []\n for i in graphe:\n if len(graphe.pred[i]) == 0:\n list_enter.append(i)\n return list_enter\n\n\ndef get_sink_nodes(graphe):\n \"\"\"\n Returning all the ending nodes of a graphe\n :param graphe: DiGrah of kmer_dict\n :return: a list of ending nodes\n \"\"\"\n list_end = []\n for i in graphe:\n if len(graphe.succ[i]) == 0:\n list_end.append(i)\n return list_end\n\n\ndef get_contigs(graphe, liste_start, liste_end):\n \"\"\"\n Create a string of a contig between two nodes in a graphe\n :param graphe: DiGraphe\n :param liste_start: list of start nodes\n :param liste_end: list of end nodes\n :return: a string of a contig\n \"\"\"\n liste_contig = []\n for i in liste_start:\n for j in liste_end:\n liste_contig.append(list(nx.all_simple_paths(graphe, i, j)))\n\n contig_final = []\n for i in range(len(liste_contig)):\n for j in range(len(liste_contig[i])):\n contig = str(liste_contig[i][j][0])\n for k in range(1, len(liste_contig[i][j])):\n lettre = liste_contig[i][j][k][-1]\n contig += lettre[-1]\n contig_final.append([contig, len(contig)])\n return contig_final\n\n\ndef fill(text, width=80):\n \"\"\"\n Format a string in the fasta format\n :param text: string\n :param width: size of a line\n :return: string formated\n \"\"\"\n return os.linesep.join(text[i:i + width] for i in range(0, len(text), width))\n\n\ndef save_contigs(liste_contig, output_name):\n \"\"\"\n Save a contig in a file with the fasta format\n :param liste_contig: list of contig\n :param output_name: file name of output\n \"\"\"\n with open(output_name, \"w\") as file:\n for i in range(len(liste_contig)):\n file.write(\">contig_\" + str(i) + \" \" + \"len=\" + str(len(liste_contig[i][0])) + '\\n')\n file.write(fill(liste_contig[i][0]))\n file.write('\\n')\n\n\ndef std(liste_val):\n \"\"\"\n Calcul of std\n :param liste_val: liste of int\n :return: std of the list of int\n \"\"\"\n return statistics.stdev(liste_val)\n\n\ndef path_average_weight(graphe, path):\n \"\"\"\n Caclul of the average weight of path\n :param graphe: DiGraphe\n :param path: path of a DiGraph\n :return: Mean of the weight of a path\n \"\"\"\n temp = []\n for edge in graphe.subgraph(path).edges(data=True):\n temp.append(edge['weight'])\n return statistics.mean(temp)\n\n\ndef remove_paths(graphe, liste_path, delete_entry_node=False, delete_sink_node=False):\n \"\"\"\n Remove a path with start or ending nodes\n :param graphe: DiGraphe\n :param liste_path: liste of path\n :param delete_entry_node: Boolean for delete or not the entry node\n :param delete_sink_node: Boolean for delete or not the ending node\n :return: Graphe cleaned\n \"\"\"\n graphe_clean = graphe\n for path in liste_path:\n if delete_entry_node and delete_sink_node:\n graphe_clean.remove_nodes_from(path)\n elif delete_entry_node is not True and delete_sink_node is not True:\n graphe_clean.remove_nodes_from(path[1:-1])\n elif delete_entry_node is not True and delete_sink_node:\n graphe_clean.remove_nodes_from(path[1:])\n elif delete_entry_node and delete_sink_node is not True:\n graphe_clean.remove_nodes_from(path[:-1])\n return graphe_clean\n\n\ndef select_best_path(graphe, liste_path, liste_len_path, liste_weight_path,\n delete_entry_node=False, delete_sink_node=False):\n \"\"\"\n Selection of the best path in a list of path\n :param graphe: DiGraphe\n :param liste_path: list of path\n :param liste_len_path: list of length of the path\n :param liste_weight_path: list of weight of the path\n :param delete_entry_node: Boolean for delete or not the entry node\n :param delete_sink_node: Boolean for delete or not the ending node\n :return: Graphe Cleaned\n \"\"\"\n random.seed(9001)\n graphe_clean = graphe\n\n w_max = 0\n liste_w_path = []\n for path in range(len(liste_path)):\n w_temp = liste_weight_path[path]\n if w_temp >= w_max:\n w_max = w_temp\n liste_w_path.append(liste_path[path])\n\n l_max = 0\n liste_l_path = []\n for path in range(len(liste_w_path)):\n l_temp = liste_len_path[path]\n if l_temp >= l_max:\n l_max = l_temp\n liste_l_path.append(liste_w_path[path])\n\n random.shuffle(liste_l_path)\n better_path = liste_l_path[0]\n\n list_pasbon_path = []\n for path in liste_path:\n if path != better_path:\n list_pasbon_path.append(path)\n\n graphe_clean = remove_paths(graphe_clean, list_pasbon_path,\n delete_entry_node, delete_sink_node)\n return graphe_clean\n\n\ndef solve_bubble(graphe, ancestor_node, desc_node):\n \"\"\"\n Delete the bubble by keeping the best path\n :param graphe: DiGraphe\n :param ancestor_node: Ancestor node\n :param desc_node: Descendant node\n :return: Graphe Cleaned\n \"\"\"\n graphe_clean = graphe\n\n list_good_path = []\n liste_len_path = []\n liste_weight_path = []\n\n for path in nx.all_simple_paths(graphe, ancestor_node, desc_node):\n list_good_path.append(path)\n liste_len_path.append(len(path))\n liste_weight_path.append(path_average_weight(graphe_clean, path))\n\n graphe_clean_clean = select_best_path(graphe, list_good_path, liste_len_path, liste_weight_path,\n delete_entry_node=False, delete_sink_node=False)\n\n return graphe_clean_clean\n\n\ndef simplify_bubbles(graphe):\n \"\"\"\n Delete all the bubble in a graphe\n :param graphe: DiGraphe\n :return: Graphe Cleaned\n \"\"\"\n graphe_clean = graphe\n liste_bubble = []\n for node in graphe_clean.nodes():\n list_pred = list(graphe.predecessors(node))\n if len(list_pred) > 1:\n ancestor = nx.lowest_common_ancestor(graphe_clean, list_pred[0], list_pred[1])\n liste_bubble.append([ancestor, node])\n for i in range(len(liste_bubble)):\n graphe_clean = solve_bubble(graphe_clean, liste_bubble[i][0], liste_bubble[i][1])\n return graphe_clean\n\n\ndef solve_entry_tips(graphe, list_enter):\n \"\"\"\n Delete the entry tips\n :param graphe: DiGraphe\n :param list_enter: Liste of entry node\n :return: Graphe cleaned\n \"\"\"\n graphe_clean = graphe.copy()\n liste_path = []\n liste_len_path = []\n liste_weight_path = []\n iteration = 0\n\n if len(list_enter) == 1:\n return graphe_clean\n\n for node in list_enter:\n while len(graphe_clean.pred[node]) < 2:\n node = list(graphe_clean.succ[node])[0]\n if len(graphe_clean.pred[node]) >= 2:\n for path in nx.all_simple_paths(graphe, list_enter[iteration], node):\n liste_path.append(path)\n liste_len_path.append(len(path))\n liste_weight_path.append(path_average_weight(graphe_clean, path))\n\n iteration = iteration + 1\n\n graphe_clean_clean = select_best_path(graphe_clean, liste_path, liste_len_path,\n liste_weight_path,\n delete_entry_node=True, delete_sink_node=False)\n\n return graphe_clean_clean\n\n\ndef solve_out_tips(graphe, list_end):\n \"\"\"\n Delete ending tips\n :param graphe: DiGraphe\n :param list_end: Liste of ending nodes\n :return: Graphe Cleaned\n \"\"\"\n graphe_clean = graphe.copy()\n liste_path = []\n liste_len_path = []\n liste_weight_path = []\n iteration = 0\n\n if len(list_end) == 1:\n return graphe_clean\n\n for node in list_end:\n while len(graphe_clean.succ[node]) < 2:\n node = list(graphe_clean.pred[node])[0]\n if len(graphe_clean.succ[node]) >= 2:\n for path in nx.all_simple_paths(graphe, node, list_end[iteration]):\n liste_path.append(path)\n liste_len_path.append(len(path))\n liste_weight_path.append(path_average_weight(graphe_clean, path))\n\n iteration = iteration + 1\n\n graphe_clean_clean = select_best_path(graphe_clean, liste_path, liste_len_path,\n liste_weight_path,\n delete_entry_node=False, delete_sink_node=True)\n\n return graphe_clean_clean\n\n\ndef main():\n \"\"\"\n Main of the script\n \"\"\"\n parser = argparse.ArgumentParser(description='Debruij')\n parser.add_argument('-i', nargs='?', type=argparse.FileType('r'))\n parser.add_argument('-k', type=int, help='taille kmer')\n parser.add_argument('-o', help='')\n\n args = parser.parse_args()\n\n if args.i is not None:\n dico_kmer = build_kmer_dict(args.i.name, args.k)\n graphe = build_graph(dico_kmer)\n\n graphe = simplify_bubbles(graphe)\n\n liste_start = get_starting_nodes(graphe)\n liste_end = get_sink_nodes(graphe)\n\n graphe = solve_entry_tips(graphe, liste_start)\n graphe = solve_out_tips(graphe, liste_end)\n\n liste_contig = get_contigs(graphe, liste_start, liste_end)\n save_contigs(liste_contig, args.o)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"debruijn/debruijn.py","file_name":"debruijn.py","file_ext":"py","file_size_in_byte":11284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"569057614","text":"\"\"\" \nCAR CONFIG \n\nThis file is read by your car application's manage.py script to change the car\nperformance. \n\nEXMAPLE\n-----------\nimport dk\ncfg = dk.load_config(config_path='~/d3/config.py')\nprint(cfg.CAMERA_RESOLUTION)\n\n\"\"\"\n\n\nimport os\n\n#PATHS\nCAR_PATH = PACKAGE_PATH = os.path.dirname(os.path.realpath(__file__))\nDATA_PATH = os.path.join(CAR_PATH, 'data')\nMODELS_PATH = os.path.join(CAR_PATH, 'models')\n\n#VEHICLE\nDRIVE_LOOP_HZ = 20\nMAX_LOOPS = 100000\n\n#CAMERA\nCAMERA_TYPE = \"PICAM\"\t\t# PICAM or WEBCAM\nIMAGE_W = 160\nIMAGE_H = 120\nIMAGE_DEPTH = 3\t\t# default RGB=3, make 1 for mono\n\t\t\t# CAMERA_RESOLUTION = (120, 160) #(height, width)\nCAMERA_FRAMERATE = DRIVE_LOOP_HZ\n\n#9865, over rides only if neeed, ie. TX2..\nPCA9685_I2C_ADDR = 0x40\nPCA9685_I2C_BUSNUM = None\n\n#STEERING\nSTEERING_CHANNEL = 1\nSTEERING_LEFT_PWM = 260 #280 #310\nSTEERING_RIGHT_PWM = 450 #440 #450 #470 #490\n\n#THROTTLE\nTHROTTLE_CHANNEL = 2\nTHROTTLE_FORWARD_PWM = 550 #575 #550\nTHROTTLE_STOPPED_PWM = 400\nTHROTTLE_REVERSE_PWM = 250\nTHROTTLE_RANGE = 20\n\n#TRAINING\nBATCH_SIZE = 128\nTRAIN_TEST_SPLIT = 0.8\nMAX_EPOCHS = 100\nSHOW_PLOT = True\nVEBOSE_TRAIN = True\nUSE_EARLY_STOP = True\nEARLY_STOP_PATIENCE = 5\nMIN_DELTA = .0005\nPRINT_MODEL_SUMMARY = True\t#print layers and weights to stdout\nOPTIMIZER = None\t\t#adam, sgd, rmsprop, etc.. None accepts default\nLEARNING_RATE = 0.001\t\t#only used when OPTIMIZER specified\nLEARNING_RATE_DECAY = 0.0\t#only used when OPTIMIZER specified\n\n# model transfer options\nFREEZE_LAYERS = False\nNUM_LAST_LAYERS_TO_TRAIN = 7\n\n#JOYSTICK\nUSE_JOYSTICK_AS_DEFAULT = True\nJOYSTICK_MAX_THROTTLE = 0.3\nJOYSTICK_STEERING_SCALE = 1.0\nAUTO_RECORD_ON_THROTTLE = True\n\n#RNN or 3D\nSEQUENCE_LENGTH = 3\n\n#IMU\nHAVE_IMU = False\n\n#LED\nHAVE_RGB_LED = False\nLED_INVERT = False\t\t#COMMON ANODE?\n\n#board pin number for pwm outputs\nLED_PIN_R = 12\nLED_PIN_G = 10\nLED_PIN_B = 16\n\n#LED status color, 0-100\nLED_R = 0\nLED_G = 0\nLED_B = 1\n\n#BEHAVIORS\nTRAIN_BEHAVIORS = False\nBEHAVIOR_LIST = ['Left_Lane', \"Right_Lane\"]\nBEHAVIOR_LED_COLORS = [ (0, 10, 0), (10, 0, 0) ] #RGB tuples 0-100 per chanel\n","sub_path":"source/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"236056580","text":"from messenger_manager import MessengerManager\nfrom constants import CMD_START_MSG\nimport socket\nimport uuid\n\n\ndef parse_feedback(fb):\n fb_exp = fb['formal']\n fb_norm = fb['verbal']\n exp = 'Экспертная обратная связь:\\nКуб: {}\\nМера: {}\\nИзмерения: {}'\n norm = 'Дататрон выделил следующие параметры (обычная обратная связь):\\n{}'\n exp = exp.format(fb_exp['cube'], fb_exp['measure'], ', '.join([i['dim'] + ': ' + i['val'] for i in fb_exp['dims']]))\n norm = norm.format('1. {}\\n'.format(\n fb_norm['measure']) + '\\n'.join([str(idx + 2) + '. ' + i for idx, i in enumerate(fb_norm['dims'])]))\n line = \"==\" * 10\n cntk_response = 'CNTK разбивка\\n{}'\n r = ['{}. {}: {}'.format(idx + 1, i['tagmeaning'].lower(), i['word'].lower()) for idx, i in enumerate(fb['cntk'])]\n cntk_response = cntk_response.format(', '.join(r))\n return '{0}\\n{1}\\n{0}\\n{2}\\n{0}\\n{3}\\n{0}'.format(line, exp, norm, cntk_response)\n\n\nprint(CMD_START_MSG)\n\nwhile True:\n text = input('Введите запрос: ')\n text = text.strip()\n if text:\n greets = MessengerManager.greetings(text)\n if greets:\n print(greets)\n continue\n\n result = None\n\n result = MessengerManager.make_request(text, 'CMD', socket.gethostname(), socket.gethostname(), uuid.uuid4())\n if not result.status:\n print(result.error)\n else:\n print(result.message)\n print(parse_feedback(result.feedback))\n print('Ответ: {}'.format(result.response))\n","sub_path":"ui_cmd.py","file_name":"ui_cmd.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"651121941","text":"\"\"\"\nTests for Operator Trigger\n\"\"\"\nfrom mock import patch\nfrom django.test import TestCase\nfrom runner.models import Run\nfrom runner.tasks import check_job_timeouts\nfrom freezegun import freeze_time\n\n\nclass TestRunnerTasks(TestCase):\n fixtures = [\n \"file_system.filegroup.json\",\n \"file_system.filetype.json\",\n \"file_system.storage.json\",\n \"runner.pipeline.json\",\n \"beagle_etl.operator.json\",\n \"runner.operator_run.json\",\n \"runner.run.json\",\n \"file_system.sample.json\",\n \"runner.operator_trigger.json\",\n ]\n\n @freeze_time(\"2018-12-12T22:59:41.044Z\")\n @patch(\"runner.tasks.fail_job\")\n def test_timeout_fails_appropriate_jobs(self, fail_job):\n runs = Run.objects.all()\n check_job_timeouts()\n self.assertEqual(fail_job.call_count, 2)\n","sub_path":"runner/tests/test_tasks.py","file_name":"test_tasks.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"439597084","text":"## Part B Task 4\nimport re\nimport pandas as pd\nimport os\nimport sys\nimport nltk\nfrom nltk.stem.porter import *\n\ndirs = os.listdir(\"cricket\")\n\ndef preposses(path):\n\n f = open(path, mode='r')\n \n new_str = ''\n \n for line in f.readlines():\n j = re.sub(r'\\W', ' ', line)\n g = ' '.join(j.split())\n new_str = new_str + ' ' + g\n \n new_str = ' '.join(new_str.split())\n new_str = new_str.lower()\n #print(new_str)\n return(new_str)\n \nporterStemmer = PorterStemmer()\n\nkeywords = []\n\nkeywords = [sys.argv[i] for i in range(1, len(sys.argv))]\nkeywords_stem = []\n\nfor i in keywords:\n stemWord = porterStemmer.stem(i)\n keywords_stem.append(stemWord)\nprint('keywords\\' stem:', keywords_stem)\n#print(keywords)\nfile_name = []\n\nfor i in dirs:\n path = str('cricket/%s'%i)\n prepossed_txt = preposses(path)\n word_list = nltk.word_tokenize(prepossed_txt)\n word_list_stem = []\n for j in word_list:\n stemWord = porterStemmer.stem(j)\n word_list_stem.append(stemWord)\n count = 0\n intersection = list(set(word_list_stem).intersection(set(keywords_stem)))\n #print(intersection)\n #print(len(intersection))\n #print(len(sys.argv))\n if len(intersection) == len(keywords):\n file_name.append(i)\n\n\nprint('file name:')\nfor j in file_name:\n print(j)\n \npartb1 = pd.read_csv('partb1.csv',encoding = 'ISO-8859-1')\n\nfile_keywords = pd.DataFrame(columns=['file name', 'document ID'])\nfile_name_1 = []\ndocument_ID_1 = []\ncount_1 = 0\nfor g in partb1['filename']:\n if g in file_name:\n file_name_1.append(g)\n document_ID_1.append(partb1.iloc[count_1,2])\n count_1 += 1\n\nfile_keywords['file name'] = file_name_1\nfile_keywords['document ID'] = document_ID_1\nprint(file_keywords)","sub_path":"partb4.py","file_name":"partb4.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"325264551","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom django.views.decorators.cache import cache_control\nfrom wall_of_fame.models import skill_karma_details\nfrom registeration.models import registeration\n\ndef about(request):\n data=registeration.objects.filter(spuser='no')\n if request.session.get('isLogged', False):\n data2=skill_karma_details.objects.get(pid=request.session.get('pid',''))\n return TemplateResponse(request,'loggedaboutus.html',{\"name\":request.session.get('name','noob'),\"num\":data.count(),\"data2\":data2})\n else:\n return TemplateResponse(request,'aboutus.html',{\"num\":data.count()})\n\ndef speciallist(request):\n data=registeration.objects.filter(spuser='yes')\n if request.session.get('isLogged', False):\n namelist=[]\n collegelist=[]\n data2=skill_karma_details.objects.get(pid=request.session.get('pid',''))\n for obj in data:\n namelist.append(obj.f_name+\" \"+obj.l_name)\n collegelist.append(obj.spcollege)\n tup=map(lambda a,b:(a,b),namelist,collegelist)\n return TemplateResponse(request,'specuserlist.html',{\"name\":request.session.get('name','noob'),\"data\":tup,\"data2\":data2})\n else:\n return HttpResponseRedirect('/') \n\n# Create your views here.\n","sub_path":"Website/oncon/AboutUs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"187550119","text":"import signal\nimport uuid\nfrom functools import partial\nfrom types import FunctionType\n\nfrom bokeh.server.server import Server\nfrom panel.io import state\nfrom panel.io.server import INDEX_HTML\n\ndef _eval_panel(panel, server_id, title, doc):\n from panel.template import Template\n from panel.pane import panel as as_panel\n\n if isinstance(panel, Template):\n return panel._modify_doc(server_id, title, doc)\n elif isinstance(panel, FunctionType):\n panel = panel(doc)\n return as_panel(panel)._modify_doc(server_id, title, doc)\n\ndef get_server_custom(panel, port=0, websocket_origin=None, loop=None,\n show=False, start=False, title=None, verbose=False, **kwargs):\n \"\"\"\n Returns a Server instance with this panel attached as the root\n app.\n Arguments\n ---------\n panel: Viewable, function or {str: Viewable}\n A Panel object, a function returning a Panel object or a\n dictionary mapping from the URL slug to either.\n port: int (optional, default=0)\n Allows specifying a specific port\n websocket_origin: str or list(str) (optional)\n A list of hosts that can connect to the websocket.\n This is typically required when embedding a server app in\n an external web site.\n If None, \"localhost\" is used.\n loop : tornado.ioloop.IOLoop (optional, default=IOLoop.current())\n The tornado IOLoop to run the Server on\n show : boolean (optional, default=False)\n Whether to open the server in a new browser tab on start\n start : boolean(optional, default=False)\n Whether to start the Server\n title: str (optional, default=None)\n An HTML title for the application\n verbose: boolean (optional, default=False)\n Whether to report the address and port\n kwargs: dict\n Additional keyword arguments to pass to Server instance\n Returns\n -------\n server : bokeh.server.server.Server\n Bokeh Server instance running this panel\n \"\"\"\n from tornado.ioloop import IOLoop\n\n server_id = kwargs.pop('server_id', uuid.uuid4().hex)\n if isinstance(panel, dict):\n apps = {slug if slug.startswith('/') else '/'+slug:\n partial(_eval_panel, p, server_id, title)\n for slug, p in panel.items()}\n else:\n apps = {'/': partial(_eval_panel, panel, server_id, title)}\n\n opts = dict(kwargs)\n if loop:\n loop.make_current()\n opts['io_loop'] = loop\n else:\n opts['io_loop'] = IOLoop.current()\n\n if 'index' not in opts:\n opts['index'] = INDEX_HTML\n\n if websocket_origin:\n if not isinstance(websocket_origin, list):\n websocket_origin = [websocket_origin]\n opts['allow_websocket_origin'] = websocket_origin\n\n server = Server(apps, port=port, **opts)\n if verbose:\n address = server.address or 'localhost'\n print(\"Launching server at http://%s:%s\" % (address, server.port))\n\n state._servers[server_id] = (server, panel, [])\n\n if show:\n def show_callback():\n server.show('/')\n server.io_loop.add_callback(show_callback)\n\n def sig_exit(*args, **kwargs):\n server.io_loop.add_callback_from_signal(do_stop)\n\n def do_stop(*args, **kwargs):\n server.io_loop.stop()\n\n try:\n signal.signal(signal.SIGINT, sig_exit)\n except ValueError:\n pass # Can't use signal on a thread\n\n if start:\n server.start()\n try:\n server.io_loop.start()\n except RuntimeError:\n pass\n return server\n","sub_path":"jupyterlab_bokeh_server/custom_bokeh_server.py","file_name":"custom_bokeh_server.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"506857314","text":"#!/usr/bin/env python2.7\n''' Module providing console output utilities, including Bash formatted output.\n'''\n\n# system modules\nimport sys\n\n# Colour code enumerations for Bash shell.\n# These are 8/16 colour codes which should work with most terminals or emulators.\n\nSET_RESET = 0\nSET_BOLD = 1\nSET_DIM = 2\nSET_UNDERLINE = 4\nFG_BLACK = 30\nFG_RED = 31\nFG_GREEN = 32\nFG_YELLOW = 33\nFG_BLUE = 34\nFG_MAGENTA = 35\nFG_CYAN = 36\nFG_LIGHTGRAY = 37\nFG_DEFAULT = 39\nFG_DARKGRAY = 90\nFG_LIGHTRED = 91\nFG_LIGHTGREEN = 92\nFG_LIGHTYELLOW = 93\nFG_LIGHTBLUE = 94\nFG_LIGHTMAGENTA = 95\nFG_LIGHTCYAN = 96\nFG_WHITE = 97\n\nclass Chatter(object):\n ''' Class providing methods for console output.\n '''\n @classmethod\n def bashformat(cls, fmtlist):\n ''' Return a code string to modify Bash output formatting using the given codes.\n '''\n fmtstring = ''\n if fmtlist:\n for fmt in fmtlist:\n fmtstring = '%s%s' % (fmtstring, '\\033[%sm' % fmt)\n return fmtstring\n\n @classmethod\n def to_stdout(cls, msg, fmtlist=None):\n ''' Prints msg to stdout, using fmt as the format code.\n '''\n sys.stdout.write('%s%s%s' % (\n Chatter.bashformat(fmtlist),\n msg,\n Chatter.bashformat([SET_RESET])\n ))\n\n @classmethod\n def to_stderr(cls, msg):\n ''' Prints msg to stdout (without any special formatting).\n '''\n sys.stderr.write(msg)\n\n","sub_path":"chatter.py","file_name":"chatter.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"130147437","text":"fruits = {\r\n \"apple\" : 50,\r\n \"banana\" : 20,\r\n \"cherry\" : 80,\r\n \"orange\" : 40,\r\n \"mango\" : 90\r\n }\r\nprint(fruits)\r\nfruitname = input(\"Enter the fruit name your are looking for : \")\r\nif(fruitname in fruits):\r\n print(\"Fruit is available\")\r\nelse:\r\n print(\"Fruit is not available\")\r\n ","sub_path":"Python/Activities/Activity11.py","file_name":"Activity11.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"287357252","text":"from scipy import signal\nimport tensorflow as tf\nimport scipy.io as sio\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\n#tf.device('/device:GPU:0')\n\ndef ext_spectrogram(epoch, fs=1000, window='hamming', nperseg=2000, noverlap=1975, nfft=3000):\n # epoch.shape = channel number, timepoint, trials\n # extract sepctrogram with time point\n\n dat = []\n for i in range(epoch.shape[2]):\n tfreq = []\n for j in range(epoch.shape[0]):\n f, t, Sxx = signal.stft(epoch[j,:,i], fs=fs, window=window, nperseg=nperseg, noverlap=noverlap, nfft=nfft)\n interval = f[-1]/(len(f)-1)\n req_len = int(40 / interval)\n # use frequency(~121th) and tiem(-41th~0)\n tfreq.append(np.abs(Sxx[:121, -41:]).transpose())\n dat.append(np.asarray(tfreq))\n\n # shape : (trials, channel number, time, freq), time and freq should be : 41, 121\n return np.array(dat)\n\ndef get_batch_num(data, batch_size):\n total_len = data.shape[0]\n return math.ceil(total_len/batch_size)\n\ndef get_batch(data, batch_size, idx):\n batch_num = get_batch_num(data, batch_size)\n if idx == batch_num - 1:\n return data[batch_size*idx:]\n else:\n return data[batch_size*idx:batch_size*(idx+1)]\n\n# input: location, ten fold number, inversion of label\n# output: train_x, train_y, test_x, test_y\ndef load_data(location = 'dataset1_parsed.mat', ten=9, inv=False, getAll = False):\n # load eeg data\n data = sio.loadmat(location)\n # get eeg data and extract spectogram\n # reshpae spectogram data as shape (num_trials, features) to use it in FC\n ep = ext_spectrogram(data['ep']).reshape(data['ep'].shape[2], -1)\n # get label data\n # reshpae it to (num_trials, 1) to use it in FC\n lb = data['lb'].T\n if inv:\n lb = np.where(lb == 0, 1, 0)\n # generate random index, for unbiased dataset\n shuffle_idx = np.arange(ep.shape[0])\n # fix the seed for consistency\n np.random.seed(2020)\n np.random.shuffle(shuffle_idx)\n # shuffle ep and lb in the same order\n ep = ep[shuffle_idx]\n lb = lb[shuffle_idx]\n if getAll:\n return ep, lb, ep, lb\n # for ten fold\n bs = ep.shape[0]//10\n return ep[(ten+1)*bs:] if ten == 0 else \\\n (ep[:ten*bs] if ten == 9 else np.concatenate((ep[:ten*bs],ep[(ten+1)*bs:]), axis = 0)), \\\n lb[(ten+1)*bs:] if ten == 0 else \\\n (lb[:ten*bs] if ten == 9 else np.concatenate((lb[:ten*bs],lb[(ten+1)*bs:]), axis = 0)), \\\n ep[ten*bs:(ten+1)*bs], \\\n lb[ten*bs:(ten+1)*bs]\n\nep_size, _, ep_test, _ = load_data()\n\n# setting\nc_learning_rate = 1e-5\nc_training_epoch = 1000\n\n# get number of input features\n# equal for all dataset because of same number of channel(which is 4)\nnum_input = ep_size.shape[1]\n\nfor data_num in (0,):\n for inv in (False,):\n for until in (0, 1, 5):\n for weight in (\"./model\",):\n # reset graph to free unused memory\n tf.reset_default_graph()\n\n # placeholder for input and label\n X = tf.placeholder(tf.float32, [None, num_input])\n Y = tf.placeholder(tf.float32, [None, 1])\n\n # build nn of leftside(fixed)\n e_W1 = tf.get_variable(\"e_W1\", shape=[num_input, 4096], initializer=tf.contrib.layers.xavier_initializer())\n e_b1 = tf.get_variable(\"e_b1\", shape=[4096], initializer=tf.contrib.layers.xavier_initializer())\n e_W2 = tf.get_variable(\"e_W2\", shape=[4096, 2048], initializer=tf.contrib.layers.xavier_initializer())\n e_b2 = tf.get_variable(\"e_b2\", shape=[2048], initializer=tf.contrib.layers.xavier_initializer())\n e_W3 = tf.get_variable(\"e_W3\", shape=[2048, 1024], initializer=tf.contrib.layers.xavier_initializer())\n e_b3 = tf.get_variable(\"e_b3\", shape=[1024], initializer=tf.contrib.layers.xavier_initializer())\n e_W4 = tf.get_variable(\"e_W4\", shape=[1024, 512], initializer=tf.contrib.layers.xavier_initializer())\n e_b4 = tf.get_variable(\"e_b4\", shape=[512], initializer=tf.contrib.layers.xavier_initializer())\n #e_W5 = tf.get_variable(\"e_W5\", shape=[512, 256], initializer=tf.contrib.layers.xavier_initializer())\n #e_b5 = tf.get_variable(\"e_b5\", shape=[256], initializer=tf.contrib.layers.xavier_initializer())\n encoder = tf.nn.tanh(tf.matmul(X, e_W1) + e_b1)\n encoder = tf.nn.tanh(tf.matmul(encoder, e_W2) + e_b2)\n encoder = tf.nn.tanh(tf.matmul(encoder, e_W3) + e_b3)\n encoder = tf.nn.tanh(tf.matmul(encoder, e_W4) + e_b4)\n #encoder = tf.nn.tanh(tf.matmul(encoder, e_W5) + e_b5)\n\n #c_W = tf.get_variable(\"c_W\", shape=[512, 256], initializer=tf.contrib.layers.xavier_initializer())\n #c_b = tf.get_variable(\"c_b\", shape=[256], initializer=tf.contrib.layers.xavier_initializer())\n c_W2 = tf.get_variable(\"c_W2\", shape=[512, 1], initializer=tf.contrib.layers.xavier_initializer())\n c_b2 = tf.get_variable(\"c_b2\", shape=[1], initializer=tf.contrib.layers.xavier_initializer())\n #c_logit = tf.nn.tanh(tf.matmul(bottleneck,c_W) + c_b)\n c_logit = tf.matmul(encoder, c_W2) + c_b2\n c_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=Y, logits=c_logit))\n # for tensorboard\n tf.summary.scalar('loss', c_loss)\n\n # optimizer\n c_optimizer = tf.train.AdamOptimizer(c_learning_rate).minimize(c_loss)\n # prediction and accuracy\n predicted = tf.cast(tf.nn.sigmoid(c_logit) > 0.5, dtype=tf.float32)\n accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))\n # for tensorboard\n tf.summary.scalar('accuracy', accuracy)\n merged = tf.summary.merge_all()\n\n with tf.Session() as sess:\n print(f'----------dataset{data_num} & inv {inv} & weight {weight} & until {until}----------')\n # use different optimizer according to datasets, and also training epoch(optional)\n #if data_num == 0:\n #c_training_epoch = 1500\n #c_optimizer = c_optimizer0\n #elif data_num == 1:\n #c_training_epoch = 1200\n #c_optimizer = c_optimizer1\n #elif data_num == 3:\n #c_training_epoch = 700\n #c_optimizer = c_optimizer3\n #elif data_num == 6:\n #c_training_epoch = 700\n #c_optimizer = c_optimizer6\n\n # for Avg of ten fold result\n total_test = 0\n # originally range(0,10)\n for ten_num in range(0, 10):\n # first, initialize all networks\n sess.run(tf.global_variables_initializer())\n saver = None\n # make saver to restore leftside nn, only not for until 0\n if until == 1:\n saver = tf.train.Saver(var_list = [e_W1, e_b1])\n elif until == 2:\n saver = tf.train.Saver(var_list = [e_W1, e_b1, e_W2, e_b2])\n elif until == 3:\n saver = tf.train.Saver(var_list = [e_W1, e_b1, e_W2, e_b2, e_W3, e_b3])\n elif until == 4:\n saver = tf.train.Saver(var_list = [e_W1, e_b1, e_W2, e_b2, e_W3, e_b3, e_W4, e_b4])\n # restore only not for until0\n if until != 0:\n ckpt = tf.train.get_checkpoint_state(weight)\n saver.restore(sess, ckpt.model_checkpoint_path)\n # load data according to dataset number, ten number, inv\n ep, lb, test_x, test_y = load_data(location = f'dataset{data_num}_parsed.mat', ten=ten_num, inv=inv)\n # fix batch_size to 32 to avoid oom\n batch_size = 32\n batch_num = get_batch_num(ep, batch_size)\n # for convenience\n feed_dict_train = {X: ep, Y: lb}\n feed_dict_val = {X: test_x, Y: test_y}\n\n # make writer for tensorboard, for each datasets, inv, until, ten_num\n train_summary_path = f\"./logs/{data_num}_{inv}_{weight}_d{until}/{ten_num}/train\"\n val_summary_path = f\"./logs/{data_num}_{inv}_{weight}_d{until}/{ten_num}/val\"\n train_writer = tf.summary.FileWriter(train_summary_path)\n val_writer = tf.summary.FileWriter(val_summary_path)\n for epoch in range(c_training_epoch):\n total_cost = 0\n for i in range(batch_num):\n batch_ep = get_batch(ep, batch_size, i)\n batch_lb = get_batch(lb, batch_size, i)\n _, batch_cost = sess.run([c_optimizer, c_loss], feed_dict={X: batch_ep, Y: batch_lb})\n total_cost += batch_cost\n # for manual logging\n #print(f'[Classifier] Epoch: {epoch+1} & Avg_cost = {total_cost/batch_num}')\n\n # write log for tensorboard\n train_summary = sess.run(merged, feed_dict=feed_dict_train)\n val_summary = sess.run(merged, feed_dict=feed_dict_val)\n train_writer.add_summary(train_summary, global_step=epoch+1)\n val_writer.add_summary(val_summary, global_step=epoch+1)\n train_writer.flush()\n val_writer.flush()\n \n # get final accuracy of tenfold\n print(f\"ten fold: {ten_num}\")\n print(f'Test Accuracy: {sess.run(accuracy * 100, feed_dict={X: test_x, Y: test_y})}')\n print(f'Train Accuracy: {sess.run(accuracy * 100, feed_dict={X: ep, Y: lb})}')\n total_test += sess.run(accuracy * 100, feed_dict={X: test_x, Y: test_y})\n # get final Avg accuracy\n print(f'Final Avg Test Accuracy: {total_test/10}')\nprint('Done!')","sub_path":"transfer.py","file_name":"transfer.py","file_ext":"py","file_size_in_byte":10189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"172135278","text":"#!/usr/bin/env python\n# vim: set fileencoding=utf-8 :\n# @author: Manuel Guenther \n# @date: Mon Dec 10 14:29:51 CET 2012\n#\n# Copyright (C) 2011-2012 Idiap Research Institute, Martigny, Switzerland\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, version 3 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\n\"\"\"This script creates the CAS-PEAL database in a single pass.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport os\n\nfrom .models import *\n\n\ndef read_all_eyes(directory, sub_dirs = ('FRONTAL', 'POSE')):\n \"\"\"Scans the image directories for files containing the hand-labeled eye positions, reads them and stores everything in one huge dictionary\"\"\"\n # scan for the directories, where we expect images\n all_sub_dirs = [[sub_dir, s] for sub_dir in sub_dirs for s in os.listdir(os.path.join(directory, sub_dir)) if os.path.isdir(os.path.join(directory, sub_dir, s))]\n\n # read eye positions\n eyes = {}\n for sub_dirs in all_sub_dirs:\n # eye position file\n eyes_file = os.path.join(directory, *(sub_dirs + [\"FaceFP_2.txt\"]))\n with open(eyes_file) as f:\n for line in f:\n # get the information\n splits = line.rstrip().split()\n # add the eyes positions, by generating keys according to the default names in the CAS-PEAL file lists\n eyes[\"\\\\\".join(sub_dirs + splits[:1])] = [int(p) for p in splits[1:]]\n return eyes\n\ndef add_all_elements(session, directory, extension, add_pose, verbose):\n \"\"\"Adds the clients, the files and the protocols of the CAS-PEAL database.\"\"\"\n list_files = {\n 'training' : os.path.join(directory, \"Evaluation Prototype\", \"Training Set\", \"Training Set.txt\"),\n 'gallery' : os.path.join(directory, \"Evaluation Prototype\", \"Gallery\", \"Gallery.txt\"),\n 'accessory' : os.path.join(directory, \"Evaluation Prototype\", \"Probe Sets\", \"Probe Set_Accessory.txt\"),\n 'aging' : os.path.join(directory, \"Evaluation Prototype\", \"Probe Sets\", \"Probe Set_Aging.txt\"),\n 'background': os.path.join(directory, \"Evaluation Prototype\", \"Probe Sets\", \"Probe Set_Background.txt\"),\n 'distance' : os.path.join(directory, \"Evaluation Prototype\", \"Probe Sets\", \"Probe Set_Distance.txt\"),\n 'expression': os.path.join(directory, \"Evaluation Prototype\", \"Probe Sets\", \"Probe Set_Expression.txt\"),\n 'lighting' : os.path.join(directory, \"Evaluation Prototype\", \"Probe Sets\", \"Probe Set_Lighting.txt\"),\n # The pose probe set is handled a bit different, see also note below\n #'pose' : os.path.join(directory, \"Evaluation Prototype\", \"Probe Sets\", \"Probe Set_Pose.txt\"),\n }\n\n # create clients (all clients are enrolled, i.e., contained in the gallery list)\n with open(list_files['gallery']) as f:\n if verbose: print(\"Adding clients ...\")\n for line in f:\n splits = line.split(\"\\\\\")[-1].split(\"_\")\n if verbose>1: print(\" Adding client '%s'\" % Client(splits[0], splits[1]).id)\n session.add(Client(splits[0], splits[1]))\n\n # create files and protocols\n eyes = read_all_eyes(directory)\n for protocol in list_files:\n if verbose: print(\"Adding protocol '%s'\" % protocol)\n # create protocol\n p = Protocol(protocol)\n # add it to the session and make it get an id\n session.add(p)\n session.flush()\n session.refresh(p)\n # read file list and add files\n with open(list_files[protocol]) as f:\n for line in f:\n file = File(line.strip(), p)\n if verbose>1: print(\" Adding file '%s'\" % file.path, end=' ')\n # make the file get an id\n session.add(file)\n session.flush()\n session.refresh(file)\n # add annotations for the file\n if verbose>1: print(\"with annotations '%s'\" % eyes[line.strip()])\n session.add(Annotation(file.id, eyes[line.strip()]))\n\n # create pose protocol\n # Note: I am not sure if this is really useful.\n # pose images are not listed, but instead we use all pose images\n # THIS ALSO MEANS, THERE IS NO TRAINING IMAGES FOR POSE!\n # additionally, the poses differ between subjects: most have a poses (0, +-15, +-30, +-45), but some have (0, +-22, +-45, +-66)\n if add_pose:\n p = Protocol('pose')\n if verbose: print(\"Adding 'pose' protocol\")\n # add it to the session and make it get an id\n session.add(p)\n session.flush()\n session.refresh(p)\n # get directories\n pose_sub_dirs = [['POSE', s] for s in os.listdir(os.path.join(directory, 'POSE')) if os.path.isdir(os.path.join(directory, 'POSE', s))]\n for sub_dirs in pose_sub_dirs:\n sub_dir = os.path.join(directory, *sub_dirs)\n files = [f for f in os.listdir(sub_dir) if os.path.isfile(os.path.join(sub_dir,f)) and os.path.splitext(f)[1] == extension]\n for f in files:\n file_in_dir = \"\\\\\".join(sub_dirs + [os.path.splitext(f)[0]])\n file = File(file_in_dir, p)\n if verbose>1: print(\" Adding file '%s'\" % file.path, end=' ')\n session.add(file)\n session.flush()\n session.refresh(file)\n if verbose>1: print(\"with annotations '%s'\" % eyes[file_in_dir])\n session.add(Annotation(file.id, eyes[file_in_dir]))\n\n\ndef create_tables(args):\n \"\"\"Creates all necessary tables (only to be used at the first time)\"\"\"\n\n from bob.db.base.utils import create_engine_try_nolock\n\n engine = create_engine_try_nolock(args.type, args.files[0], echo=(args.verbose > 2))\n Client.metadata.create_all(engine)\n File.metadata.create_all(engine)\n Protocol.metadata.create_all(engine)\n\n\n# Driver API\n# ==========\n\ndef create(args):\n \"\"\"Creates or re-creates this database\"\"\"\n\n from bob.db.base.utils import session_try_nolock\n\n dbfile = args.files[0]\n\n if args.recreate:\n if args.verbose and os.path.exists(dbfile):\n print('unlinking %s...' % dbfile)\n if os.path.exists(dbfile): os.unlink(dbfile)\n\n if not os.path.exists(os.path.dirname(dbfile)):\n os.makedirs(os.path.dirname(dbfile))\n\n # the real work...\n create_tables(args)\n s = session_try_nolock(args.type, args.files[0], echo=(args.verbose > 2))\n add_all_elements(s, args.directory, args.extension, args.poses, args.verbose)\n s.commit()\n s.close()\n\ndef add_command(subparsers):\n \"\"\"Add specific subcommands that the action \"create\" can use\"\"\"\n\n parser = subparsers.add_parser('create', help=create.__doc__)\n\n parser.add_argument('-R', '--recreate', action='store_true', help='If set, I\\'ll first erase the current database')\n parser.add_argument('-v', '--verbose', action='count', help='Do SQL operations in a verbose way?')\n parser.add_argument('-p', '--poses', action='store_true', help='Shall the pose files also be added?')\n parser.add_argument('-D', '--directory', metavar='DIR', default='/idiap/resource/database/CAS-PEAL', help='The path to the CAS-PEAL database')\n parser.add_argument('--extension', metavar='STR', default='.tif', help='The file extension of the image files from the CAS-PEAL face database')\n\n parser.set_defaults(func=create) #action\n","sub_path":"bob/db/caspeal/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":7395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"632342368","text":"import time\nfrom Common.QueueProcessor import QueueProcessor\nimport uuid\n\n\nclass RoutePath:\n def __init__(self, delay, speed):\n self.speed = speed\n self.delay = delay\n self.label = 0\n self.output_queue = []\n self.send_queue = QueueProcessor()\n self.should_stop = False\n self.__stime = time.time()\n self.__wtime = 0\n self.loading = 0\n self.send_time = None\n self.ID = uuid.uuid4()\n self.latest = time.time()\n self.time_labeldrop = 0\n self.max_speed = 1.0\n self.free_speed = self.speed\n self.send_time = time.time()\n\n def push(self, packet):\n self.__transfer_packet(packet)\n self.refresh_loading()\n\n def __transfer_packet(self, packet):\n transfer_time = 0\n if packet.size != 0:\n transfer_size = packet.size\n spd = min(self.max_speed, self.speed)\n transfer_time = self.delay + float(transfer_size) / spd\n self.free_speed -= self.max_speed\n if self.free_speed > 0:\n self.send_time = time.time() + transfer_time\n else:\n self.send_time += transfer_time\n self.__wtime += float(transfer_time) * (self.max_speed / self.speed)\n self.output_queue.append((packet, self.send_time, 'Free'))\n\n else:\n self.output_queue.append((packet, time.time() + transfer_time, 'Save'))\n\n def pop(self):\n if self.output_queue:\n current_time = time.time()\n packet, send_time, label = self.output_queue[0]\n if label == 'Free':\n self.free_speed += self.max_speed\n if send_time < current_time:\n self.output_queue = self.output_queue[1:]\n return packet\n else:\n return None\n\n def refresh_loading(self):\n self.loading = min(1, self.__wtime / (time.time() - self.__stime))\n\n def split_resource(self, new_speed):\n result = RoutePath(self.delay, new_speed)\n if self.speed < 2 or new_speed < 1:\n return None\n self.speed -= new_speed\n return result\n\n # should remove resource from queue before use that function!\n def merge_resource(self, resource):\n '''\n @type resource: ASResource\n '''\n weight_coefs = [self.speed, resource.speed]\n weight_coefs = [weight_coefs[0]/sum(weight_coefs), weight_coefs[1]/sum(weight_coefs)]\n self.speed += resource.speed\n self.delay = weight_coefs[0] * self.delay + weight_coefs[1] * resource.delay\n self.should_stop = False\n resource.should_stop = True\n self.__stime = time.time() - 1\n self.__wtime = 0\n self.send_queue.merge(resource.send_queue)\n\n def check_labeldrop(self):\n if self.label <= 0:\n return\n if self.time_labeldrop > time.time():\n self.label = 0","sub_path":"Simulator/AutonomousSystem/Router/RouterPath.py","file_name":"RouterPath.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"226985394","text":"from re import sub\nfrom flask import Flask, url_for, Blueprint, render_template, request, redirect\nfrom json import dumps, loads\napp = Flask(__name__)\nbp = Blueprint('subdomain', __name__, subdomain=\"\")\nserver_name = 'vinkkk.com'\n\n@app.route('/')\ndef index():\n user_data = loads(open('./users.json','r').read())\n return render_template('/index.html', users=user_data, host=server_name)\n\n@bp.route('/')\ndef subdom(user):\n return f\"welcome to your subdomain - {user}\"\n\n# @app.route('/test')\n# def test():\n# return url_for('index', _external=True)\n\n@app.route('/register', methods=['POST'])\ndef register():\n user_data = loads(open('./users.json','r').read())\n user_name = request.form['name']\n add_subdomain(user_name)\n user_count = len(user_data)\n user_data.update({user_count + 1: user_name})\n json_data = dumps(user_data)\n open('./users.json', 'w').write(json_data)\n\n return redirect(url_for('index', result_id=user_count))\n # return dumps({'response': True})\n\ndef add_subdomain(user):\n host_file = open('/etc/hosts', 'r').read()\n subdomain = f\"{user}.{server_name}\"\n \n if subdomain not in host_file:\n with open('/etc/hosts', 'w') as write_host:\n\n append_subdomain = f\"{host_file} \\n127.0.0.1 {subdomain}\"\n write_host.write(append_subdomain)\n\nif __name__ == \"__main__\":\n app.config['SERVER_NAME'] = f\"{server_name}:5000\"\n app.register_blueprint(bp)\n app.run(debug=True)","sub_path":"main_app.py","file_name":"main_app.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"601629963","text":"from datetime import datetime\nimport requests\nfrom .models import BProxyItem\nfrom .lib import BProxy\n\n\nclass BProxyClient(BProxy):\n\n __session = requests.Session()\n __hostname = 'https://api.best-proxies.ru/'\n __defaultMethod = 'proxylist.json'\n __expiredMethod = 'key.txt'\n\n @property\n def expiredAt(self) -> datetime:\n with self.__session.get(self.__hostname + self.__expiredMethod, params={\n 'key': self.key,\n 'format': 'seconds'\n }) as r:\n if r.status_code == 200:\n return datetime.fromtimestamp(datetime.today().timestamp() + int(r.text))\n else:\n raise Exception('Failed connection to service with status code \"{}\"'.format(r.status_code))\n\n\n \n def getProxyList(self, *args, **kwargs) -> [BProxyItem]:\n \"\"\"\n type:\t Тип выгружаемых прокси, допустимые значения: http, https, socks4, socks5. Можно указать несколько, через запятую. Если этот параметр не задан, будут выгружены прокси всех типов.\n level:\t Уровень анонимности выгружаемых прокси серверов, допустимые значения: 1, 2, 3, 1 - соответствует высоко анонимным (элитным) прокси, 2 - соответствует анонимным прокси, 3 - соответствует прозрачным прокси. Можно указать несколько, через запятую.\n ports:\t Список портов выгружаемых прокси, можно указать до пяти через запятую. Данный параметр можно использовать, если, например, необходимо выгрузить прокси на стандартных портах (80, 443, 1080, 3128, 8080). Данный парамет�� нельзя задать через веб-фильтр.\n pex:\t Если равен 1, то вернутся прокси с портами, отсутствующими в списке, заданном параметром ports.\n country:\t Двубуквенные коды стран выгружаемых прокси в соответствии с ISO 3166-1 alpha-2, можно указать до 20 через запятую.\n cex:\t Если равен 1, то вернутся прокси из стран, отсутствующих в списке, заданном параметром country.\n response:\t Числовое значение максимального времени отклика (в миллисекундах) выгружаемых прокси.\n uptime:\t Числовое значение времени непрерывной работы прокси в часах, допустимые значения находятся в диапазоне 1 - 48.\n speed:\t Скоростной грейд выгружаемых прокси серверов, в зависимости от времени, затраченного на выполнение теста прокси, допустимые значения: 1 (быстрые), 2 (средние по скорости), 3 (медленные). Можно указать несколько, через запятую.\n mail:\t Если равен 1, то вернутся прокси с открытым 25 SMTP портом. Обратите внимание, что отправки почты невозможна через обычные HTTP прокси, а только через HTTPS или SOCKS прокси.\n yandex:\t Если равен 1, то возвращаются прокси, через которые возможны запросы к ПС Яндекс без ввода капчи.\n google:\t Если равен 1, то возвращаются прокси, через которые возможны запросы к ПС Google без ввода капчи.\n mailru:\t Если равен 1, то возвращаются прокси, не забаненные на проектах Mail.Ru, (HTTP, а не SMTP доступ).\n twitter:\t Если равен 1, то возвращаются прокси, не забаненные в сервисе Twitter.\n includeType:\tДанный параметр влияет на формат выводимого списка прокси в формате TXT. Если передать этот параметр (можно даже без значения), то прокси возвращаются в формате [type]://[ip]:[port]. Если этот параметр не указан, список возвращается в формате [ip]:[port]. Подробнее о форматах вывода списка прокси читайте ниже.\n limit:\t При помощи этого параметра задаётся максимальное количество выгружаемого списка прокси. Если этот параметр равен 0, выводится список из не более чем 15.000 прокси. Если этот параметр не задан, выводится список, не более чем из 20 прокси.\n nocascade:\t Если равен 1, то возвращаемый список не содержит каскадных прокси. Данный параметр нельзя задать через веб-фильтр.\n \"\"\"\n params = kwargs\n params['key'] = self.key\n with self.__session.get(self.__hostname + self.__defaultMethod, params=params) as r:\n if r.status_code == 200:\n proxyList = []\n for item in r.json():\n proxyItem = BProxyItem()\n for key, value in item.items():\n if value == '0' or value == '1':\n value = int(value)\n if hasattr(proxyItem, key):\n setattr(proxyItem, key, value)\n proxyList.append(proxyItem)\n return proxyList\n else:\n raise Exception('Failed connection to service with status code \"{}\", body: \"{}\"'.format(r.status_code, r.text))\n","sub_path":"bproxy/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":6582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"589465452","text":"import replayparser as rp\n\n\n# set magicSource that is initial file header\nmagicSource = b'PBDEMS2\\x00'\n# open replay file and keep it open\nfile = open('replay/replay.dem', 'rb')\n# read first byte\nmagic = rp.readBytes(file, 8)\n# match it with magicSource\nif magic == magicSource:\n print('Its matched')\n# Ignore next byte\nmagic = rp.readBytes(file, 8)\n# read outer message\nallmessage = rp.readMessages(file)\n# Close the file just for funsies\nfile.close()\n","sub_path":"test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"357492595","text":"from django.shortcuts import render, redirect\nfrom django.urls import reverse\n\nfrom core.forms import FiltersForm, EmailForm\nfrom core.tasks import render_pdf_and_send_mail\n\n\ndef filter_form(request):\n filters_form = FiltersForm(request.POST or None)\n email_form = EmailForm(request.POST or None)\n if request.method == 'POST':\n if filters_form.is_valid() and email_form.is_valid():\n filters = filters_form.get_filters()\n email = email_form.get_email()\n render_pdf_and_send_mail.delay(to=email, filters=filters)\n return redirect(reverse('success'))\n context = {\n 'filters_form': filters_form,\n 'email_form': email_form\n }\n return render(request, 'core/filters_form.html', context)","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"69921352","text":"from django.shortcuts import render, redirect\nfrom django.views.generic import TemplateView\nfrom django.core.serializers import serialize\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.contrib.gis.geos import GEOSGeometry\nfrom .forms import thePitsForm, theBulbsForm, theLeaksForm\nfrom .models import Pits, Bulbs, Leaks\n\n# Create your views here.\n\nclass HomePageView(TemplateView):\n template_name = 'index.html'\n\ndef thePitsDatasetView(request):\n thePitFeatures = serialize('geojson', Pits.objects.all())\n return HttpResponse(thePitFeatures, content_type='json')\n\ndef theBulbsDatasetView(request):\n theBulbFeatures = serialize('geojson', Bulbs.objects.all())\n return HttpResponse(theBulbFeatures, content_type='json')\n\ndef theLeaksDatasetView(request):\n theLeakFeatures = serialize('geojson', Leaks.objects.all())\n return HttpResponse(theLeakFeatures, content_type='json')\n\ndef thePopupView(request):\n # If the form has been submitted\n if request.method == \"POST\":\n\n # Process the data in the cleaned_data\n theLonData = request.POST.get('p_field_lon', '')\n theLatData = request.POST.get('p_field_lat', '')\n theCommentData = request.POST.get('p_field_comment', '')\n theLayerSelection = request.POST.get('p_field_layer', '')\n\n # Make a form bound to the POST data\n thePopupModelForm = None\n if theLayerSelection == \"layer_pits\":\n thePopupModelForm = thePitsForm(request.POST)\n elif theLayerSelection == \"layer_bulbs\":\n thePopupModelForm = theBulbsForm(request.POST)\n elif theLayerSelection == \"layer_leaks\":\n thePopupModelForm = theLeaksForm(request.POST)\n\n # Make a new Point geometry object in WKT format\n thePoint = GEOSGeometry( 'POINT(' + str(theLonData) + ' ' + str(theLatData) + ')' )\n\n # All validation rules pass, therefore create a new object and add it to the database\n if thePopupModelForm.is_valid():\n if theLayerSelection == \"layer_pits\":\n thePitObject = Pits(Comment=theCommentData, Coords=thePoint)\n thePitObject.save()\n\n elif theLayerSelection == \"layer_bulbs\":\n theBulbObject = Bulbs(Comment=theCommentData, Coords=thePoint)\n theBulbObject.save()\n\n elif theLayerSelection == \"layer_leaks\":\n theLeakObject = Leaks(Comment=theCommentData, Coords=thePoint)\n theLeakObject.save()\n\n # Redirect to Home Page after POST\n return HttpResponseRedirect(reverse('theHomePageViewURL'))\n\n else:\n return HttpResponse(\"Form validation has failed\")\n\n else:\n return HttpResponse(\"Request method is not POST\")","sub_path":"eLakkouva/App_AddPoints/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"381538727","text":"import numpy as np\n\n\n# ========================================================\n# \n# Environment-specific cost functions:\n#\n\ndef cheetah_cost_fn(state, action, next_state):\n if len(state.shape) > 1:\n heading_penalty_factor = 10\n scores = np.zeros((state.shape[0],))\n\n # dont move front shin back so far that you tilt forward\n front_leg = state[:, 5]\n my_range = 0.2\n scores[front_leg >= my_range] += heading_penalty_factor\n\n front_shin = state[:, 6]\n my_range = 0\n scores[front_shin >= my_range] += heading_penalty_factor\n\n front_foot = state[:, 7]\n my_range = 0\n scores[front_foot >= my_range] += heading_penalty_factor\n\n scores -= (next_state[:, 17] - state[:, 17]) / 0.01 # + 0.1 * (np.sum(action**2, axis=1))\n return scores\n\n heading_penalty_factor = 10\n score = 0\n\n # dont move front shin back so far that you tilt forward\n front_leg = state[5]\n my_range = 0.2\n if front_leg >= my_range:\n score += heading_penalty_factor\n\n front_shin = state[6]\n my_range = 0\n if front_shin >= my_range:\n score += heading_penalty_factor\n\n front_foot = state[7]\n my_range = 0\n if front_foot >= my_range:\n score += heading_penalty_factor\n\n score -= (next_state[17] - state[17]) / 0.01 # + 0.1 * (np.sum(action**2))\n return score\n\n\ndef pendulum_cost_fn(state, action, next_state):\n if len(state.shape) > 1:\n assert state.shape[0] == action.shape[0]\n\n cos_th = state[:, 0:1]\n thdot = state[:, 2:3]\n th = np.arccos(cos_th)\n\n max_torque = 2.\n\n u = np.clip(action, -max_torque, max_torque)\n costs = angle_normalize(th) ** 2 + .1 * thdot ** 2 + .001 * (u ** 2)\n costs = np.squeeze(np.nan_to_num(costs))\n # costs = np.sum(costs)\n\n return costs\n\n cos_th = state[0]\n thdot = state[2]\n th = np.arccos(cos_th)\n\n max_torque = 2.\n\n u = np.clip(action, -max_torque, max_torque)[0]\n costs = angle_normalize(th) ** 2 + .1 * thdot ** 2 + .001 * (u ** 2)\n\n return np.nan_to_num(costs)\n\n\n# ========================================================\n# \n# Cost function for a whole trajectory:\n#\n\ndef trajectory_cost_fn(cost_fn, states, actions, next_states):\n trajectory_cost = 0\n for i in range(len(actions)):\n trajectory_cost += cost_fn(states[i], actions[i], next_states[i])\n return trajectory_cost\n\n\ndef angle_normalize(x):\n return ((x + np.pi) % (2 * np.pi)) - np.pi\n","sub_path":"hw4/cost_functions.py","file_name":"cost_functions.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"128964739","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:\n# Author: Binux\n# http://binux.me\n# Created on 2014-02-22 23:20:39\n\nimport socket\nimport math\nimport time\n\nfrom six import iteritems, itervalues\nfrom flask import render_template, request, json\n\ntry:\n import flask_login as login\nexcept ImportError:\n from flask.ext import login\n\nfrom .app import app\n\nindex_fields = ['name', 'group', 'status', 'comments', 'rate', 'burst', 'updatetime', 'remark']\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n group = 'all'\n name = None\n status = 'ALL'\n page = 1\n pageSize = 20\n if request.form:\n group = request.form['group']\n name = request.form['name']\n status = request.form['status']\n page = request.form['page']\n pageSize = request.form['pageSize']\n search_condition = {}\n search_condition[\"group\"] = group\n if name:\n search_condition[\"name\"] = name\n search_condition[\"status\"] = status\n search_condition['page'] = page\n search_condition['pageSize'] = pageSize\n projectdb = app.config['projectdb']\n projects = sorted(projectdb.get_all(fields=index_fields, search_condition=search_condition),\n key=lambda k: (0 if k['group'] else 1, k['group'] or '', k['name']))\n count = projectdb.count(search_condition)\n pages = math.ceil(int(count)/int(pageSize))\n return render_template(\"index.html\", projects=projects, group=group, name=name, status=status, count=count, page=page, pageSize=pageSize, pages=pages)\n\n\n@app.route('/queues')\ndef get_queues():\n def try_get_qsize(queue):\n if queue is None:\n return 'None'\n try:\n return queue.qsize()\n except Exception as e:\n return \"%r\" % e\n\n result = {}\n queues = app.config.get('queues', {})\n for key in queues:\n result[key] = try_get_qsize(queues[key])\n return json.dumps(result), 200, {'Content-Type': 'application/json'}\n\n@app.route('/update_remark', methods=['POST', ])\ndef remark_update():\n projectdb = app.config['projectdb']\n project = request.form['pk']\n name = request.form['name']\n remark = request.form['value']\n\n project_info = projectdb.get(project, fields=('name', 'group'))\n if not project_info:\n return \"no such project.\", 404\n if 'lock' in projectdb.split_group(project_info.get('group')) \\\n and not login.current_user.is_active():\n return app.login_response\n try:\n update = {name : remark}\n projectdb.update(project, update)\n return 'ok', 200\n except Exception as e:\n return e, 500\n\n\n\n\n@app.route('/update', methods=['POST', ])\ndef project_update():\n projectdb = app.config['projectdb']\n project = request.form['pk']\n name = request.form['name']\n value = request.form['value']\n\n if app.config['fetcherrorprojectdb'] and name == 'status' and value in ['RUNNING','DEBUG']:\n app.config['fetcherrorprojectdb'].drop(project)\n project_info = projectdb.get(project, fields=('name', 'group'))\n if not project_info:\n return \"no such project.\", 404\n if 'lock' in projectdb.split_group(project_info.get('group')) \\\n and not login.current_user.is_active():\n return app.login_response\n\n if name not in ('group', 'status', 'rate'):\n return 'unknown field: %s' % name, 400\n if name == 'rate':\n value = value.split('/')\n if len(value) != 2:\n return 'format error: rate/burst', 400\n rate = float(value[0])\n burst = float(value[1])\n update = {\n 'rate': min(rate, app.config.get('max_rate', rate)),\n 'burst': min(burst, app.config.get('max_burst', burst)),\n }\n else:\n update = {\n name: value\n }\n\n ret = projectdb.update(project, update)\n if ret:\n rpc = app.config['scheduler_rpc']\n if rpc is not None:\n try:\n rpc.update_project()\n except socket.error as e:\n app.logger.warning('connect to scheduler rpc error: %r', e)\n return 'rpc error', 200\n return 'ok', 200\n else:\n return 'update error', 500\n\n\n@app.route('/counter')\ndef counter():\n projects = str(request.values.get('projects')).split(\",\")\n rpc = app.config['scheduler_rpc']\n if rpc is None:\n return json.dumps({})\n\n result = {}\n try:\n data = rpc.webui_update(projects)\n if data.get('counter') is not None:\n for type, counters in iteritems(data['counter']):\n if counters is not None:\n for project, counter in iteritems(counters):\n result.setdefault(project, {})[type] = counter\n if data.get('pause_status') is not None:\n for project, paused in iteritems(data['pause_status']):\n result.setdefault(project, {})['paused'] = paused\n except socket.error as e:\n app.logger.warning('connect to scheduler rpc error: %r', e)\n return json.dumps({}), 200, {'Content-Type': 'application/json'}\n\n return json.dumps(result), 200, {'Content-Type': 'application/json'}\n\n\n@app.route('/run', methods=['POST', ])\ndef runtask():\n rpc = app.config['scheduler_rpc']\n if rpc is None:\n return json.dumps({})\n\n projectdb = app.config['projectdb']\n project = request.form['project']\n project_info = projectdb.get(project, fields=('name', 'group'))\n if not project_info:\n return \"no such project.\", 404\n if 'lock' in projectdb.split_group(project_info.get('group')) \\\n and not login.current_user.is_active():\n return app.login_response\n\n newtask = {\n \"project\": project,\n \"taskid\": \"on_start\",\n \"url\": \"data:,on_start\",\n \"process\": {\n \"callback\": \"on_start\",\n },\n \"schedule\": {\n \"age\": 0,\n \"priority\": 9,\n \"force_update\": True,\n },\n }\n\n try:\n ret = rpc.newtask(newtask)\n except socket.error as e:\n app.logger.warning('connect to scheduler rpc error: %r', e)\n return json.dumps({\"result\": False}), 200, {'Content-Type': 'application/json'}\n return json.dumps({\"result\": ret}), 200, {'Content-Type': 'application/json'}\n\n\n@app.route('/restartallwork', methods=['POST', ])\ndef restartallword():\n processdb = app.config['processdb']\n # 根据task_id、url、type、status取task当前状态\n project = request.args.get('project')\n group = request.args.get('group', 'self_crawler')\n status = \"1,3,11,13,14,21,23,31,33,34,35\"\n task_results = list(processdb.select(project, group, taskid='', url='', status=status, type=3))\n try:\n for result in task_results:\n task = dict()\n task['taskid'] = result['taskid']\n task['url'] = result['url']\n task['project'] = result['project']\n task['fetch'] = result['fetch']\n task['process'] = result['process']\n task['group'] = result['group']\n schedule = {'force_update': True, 'age': 0}\n task['schedule'] = schedule\n task['status'] = 1\n task['track'] = {}\n task['lastcrawltime'] = None\n task['type'] = 1\n task['project_updatetime'] = time.time()\n if result['status'] != 32 and \"placeholder.com\" not in task['url'] and \"placeholder-gcxx.com\" not in task['url']:\n app.config['queues']['scheduler2fetcher'].put(task)\n return json.dumps({\"status\": \"success\"}), 200, {'Content-Type': 'application/json'}\n except Exception as e:\n return json.dumps({\"error\": e}), 404, {'Content-Type': 'application/json'}\n\n\n@app.route('/clean', methods=['POST', ])\ndef clean():\n taskdb = app.config['taskdb']\n resultdb = app.config['resultdb']\n processdb = app.config['processdb']\n project = request.form['project']\n group = request.form['group']\n if processdb is not None:\n processdb.clean(project)\n taskdb.clean(project)\n resultdb.clean(project, group)\n return json.dumps({\"result\": True}), 200, {'Content-Type': 'application/json'}\n\n@app.route('/robots.txt')\ndef robots():\n return \"\"\"User-agent: *\nDisallow: /\nAllow: /$\nAllow: /debug\nDisallow: /debug/*?taskid=*\n\"\"\", 200, {'Content-Type': 'text/plain'}\n","sub_path":"pyspider/webui/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":8394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"233056059","text":"#__author__ = 'Luka Prebil Grintal'\nimport math\n\nfn = input(\"Filename (must be in the same dir as this script): \")\nfile = open(fn)\nlist = []\nperc = int(input(\"What percentile of the data do you want? \"))\n\nfor line in file:\n list.append(float(line))\n\nlist.sort()\n\ndef percentile(data, percentile):\n size = len(data)\n return sorted(data)[int(math.ceil((size * percentile) / 100)) - 1]\n\nprint(percentile(list, perc))\n\n","sub_path":"School/Python/percentile.py","file_name":"percentile.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"289415902","text":"from sklearn.model_selection import train_test_split\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\nimport numpy as np\nimport pandas as pd\n\nlabel = { 0: 'Aman', 1: 'Penipuan', 2: 'Promo' }\n\ndef get_label(dataset, message):\n data_train, data_test, label_train, label_test = train_test_split(\n dataset[1],\n dataset[0],\n test_size=0.2,\n random_state=40\n )\n \n pipe = Pipeline([\n ('vect', CountVectorizer()),\n ('tfidf', TfidfTransformer()),\n ('clf', MultinomialNB())\n ])\n\n pipe.fit(data_train, label_train)\n result = pipe.predict([message])\n\n # !!! for data mining purpose !!!\n f = open(\"collect.txt\", \"a\")\n f.write(result[0] + ',' + message + \"\\n\")\n f.close()\n # !!! for data mining purpose !!!\n\n return label[int(result[0])]","sub_path":"train/nlp.py","file_name":"nlp.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"314732531","text":"\"\"\"\nCoin Flip Simulation - Write some code that simulates flipping a\nsingle coin however many times the user decides. The code should\nrecord the outcomes and count the number of tails and heads.\n\"\"\"\n\nimport random\n\n\ndef coin_flip():\n\tcoin = random.randint(0,1)\n\tif coin == 0:\n\t\treturn \"Head\"\n\tif coin == 1:\n\t\treturn \"Tail\"\n\n\ndef coin_outcomes():\n\tflip = \"Y\"\n\tresults = []\n\twhile flip == \"Y\":\n\t\tflip = input(\"Flip coin? Y/N \").upper()\n\t\tthis_round = coin_flip()\n\t\tprint(\"You got \" + this_round)\n\t\tresults.append(this_round)\n\t\tif flip != \"Y\":\n\t\t\tbreak\n\t\telse:\n\t\t\tcontinue\n\theads = results.count(\"Head\")\n\ttails = results.count(\"Tail\")\n\tprint(f\"\\nYou got {heads} Heads and {tails} Tails.\")\n\nif __name__ == '__main__':\n\tcoin_outcomes()","sub_path":"python_bootcamp/coin_flip_simulation.py","file_name":"coin_flip_simulation.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"555069915","text":"# Python has types but they are not explicit. It also doesn't cast for you\n# '42' + 3 results in a type error. Not '423' like any *good* language.\n\n# Here's an expresssion. It's evaluated and prints\n2 + 2 # 4\n# this is also an expression\n2\n\n# Here are some math operators that may be different from Javascript.\n# exponentiation\n2 ** 3 # 8\n\n# modulus\n8 % 3 # 2\n\n# integer division\n22 // 8 # 2\n\n# and the old reliables\n8 + 1\n8 - 1\n8 * 2\n9 / 4\n\n# we've got integers, floating point numbers, and strings to start with.\n\n# we can indeed concatenate strings\n'Alice' + 'Bob' # AliceBob\n\n# we can also replicate strings\n'Alice' * 3 #AliceAliceAlice\n# which seems like a reasonable sort of thing to do.\n\n# lets make a variable with an assignment statement\nspam = 3\neggs = 40\n\nspam + eggs # 43\n\nspam = spam + 2 \nspam # 42\n\n#PEP 8 says to use underscores instead of camelcase\nwell_okay_then = True\n\n# length of a string\nname = 'brass'\nlen(name) # 5\n\n# converting is nice and easy\nword_number = '5'\n'The number six looks like ' + str(int(word_number) + 1)\n\n# get user input and wait for 'enter' to be pressed\nuser_input = input()\n\n# convert a value to a string\nstr(45) # '45'\n\n# convert a value to an int\nint('34') # 34\n\n# convert a value to a float\nfloat(34) # 34.0\n\n# int() floors floating points\nint(1.99999) # 1\n","sub_path":"ch1/notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"466021478","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: C:\\Users\\derek_2\\Google Drive\\nvda-addon-exploded\\notepad++\\scons-local-2.5.0\\SCons\\Tool\\javah.py\n# Compiled at: 2016-07-07 03:21:33\n\"\"\"SCons.Tool.javah\n\nTool-specific initialization for javah.\n\nThere normally shouldn't be any need to import this module directly.\nIt will usually be imported through the generic SCons.Tool.Tool()\nselection method.\n\n\"\"\"\n__revision__ = 'src/engine/SCons/Tool/javah.py rel_2.5.0:3543:937e55cd78f7 2016/04/09 11:29:54 bdbaddog'\nimport os.path, SCons.Action, SCons.Builder, SCons.Node.FS, SCons.Tool.javac, SCons.Util\n\ndef emit_java_headers(target, source, env):\n \"\"\"Create and return lists of Java stub header files that will\n be created from a set of class files.\n \"\"\"\n class_suffix = env.get('JAVACLASSSUFFIX', '.class')\n classdir = env.get('JAVACLASSDIR')\n if not classdir:\n try:\n s = source[0]\n except IndexError:\n classdir = '.'\n else:\n try:\n classdir = s.attributes.java_classdir\n except AttributeError:\n classdir = '.'\n\n classdir = env.Dir(classdir).rdir()\n if str(classdir) == '.':\n c_ = None\n else:\n c_ = str(classdir) + os.sep\n slist = []\n for src in source:\n try:\n classname = src.attributes.java_classname\n except AttributeError:\n classname = str(src)\n if c_ and classname[:len(c_)] == c_:\n classname = classname[len(c_):]\n if class_suffix and classname[-len(class_suffix):] == class_suffix:\n classname = classname[:-len(class_suffix)]\n classname = SCons.Tool.javac.classname(classname)\n\n s = src.rfile()\n s.attributes.java_classname = classname\n slist.append(s)\n\n s = source[0].rfile()\n if not hasattr(s.attributes, 'java_classdir'):\n s.attributes.java_classdir = classdir\n if target[0].__class__ is SCons.Node.FS.File:\n tlist = target\n else:\n if not isinstance(target[0], SCons.Node.FS.Dir):\n target[0].__class__ = SCons.Node.FS.Dir\n target[0]._morph()\n tlist = []\n for s in source:\n fname = s.attributes.java_classname.replace('.', '_') + '.h'\n t = target[0].File(fname)\n t.attributes.java_lookupdir = target[0]\n tlist.append(t)\n\n return (\n tlist, source)\n\n\ndef JavaHOutFlagGenerator(target, source, env, for_signature):\n try:\n t = target[0]\n except (AttributeError, IndexError, TypeError):\n t = target\n\n try:\n return '-d ' + str(t.attributes.java_lookupdir)\n except AttributeError:\n return '-o ' + str(t)\n\n\ndef getJavaHClassPath(env, target, source, for_signature):\n path = '${SOURCE.attributes.java_classdir}'\n if 'JAVACLASSPATH' in env and env['JAVACLASSPATH']:\n path = SCons.Util.AppendPath(path, env['JAVACLASSPATH'])\n return '-classpath %s' % path\n\n\ndef generate(env):\n \"\"\"Add Builders and construction variables for javah to an Environment.\"\"\"\n java_javah = SCons.Tool.CreateJavaHBuilder(env)\n java_javah.emitter = emit_java_headers\n env['_JAVAHOUTFLAG'] = JavaHOutFlagGenerator\n env['JAVAH'] = 'javah'\n env['JAVAHFLAGS'] = SCons.Util.CLVar('')\n env['_JAVAHCLASSPATH'] = getJavaHClassPath\n env['JAVAHCOM'] = '$JAVAH $JAVAHFLAGS $_JAVAHOUTFLAG $_JAVAHCLASSPATH ${SOURCES.attributes.java_classname}'\n env['JAVACLASSSUFFIX'] = '.class'\n\n\ndef exists(env):\n return env.Detect('javah')","sub_path":"pycfiles/NVDA-addonTemplate-0.5.2/javah.py","file_name":"javah.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"652378777","text":"#!/usr/bin/python\n# Copyright (c) 2015 Dell Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n#\n# THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT\n# LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS\n# FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n\nimport cps\nimport cps_utils\n\nimport nas_os_if_utils as nas_if\nimport nas_front_panel_map as fp\nimport cps_object\nimport event_log as ev\nimport time\nimport bytearray_utils as ba\n\ncps_utils.add_attr_type('base-pas/media/port', 'uint8_t')\ncps_utils.add_attr_type('base-pas/media/slot', 'uint8_t')\ncps_utils.add_attr_type('base-pas/media/present', 'uint8_t')\ncps_utils.add_attr_type('base-pas/media/type', 'uint32_t')\n\ndef get_all_media_info():\n obj = cps_object.CPSObject(module='base-pas/media', qual='observed')\n media_list = []\n cps.get([obj.get()], media_list)\n return media_list\n\ndef get_media_info(media_id):\n obj = cps_object.CPSObject(\n module='base-pas/media',\n qual='observed',\n data={'slot': 1,\n 'port': media_id})\n media_list = []\n cps.get([obj.get()], media_list)\n return media_list\n\ndef get_media_channel_info(media_id):\n obj = cps_object.CPSObject(\n module='base-pas/media-channel',\n qual='observed',\n data={'slot': 1,\n 'port': media_id})\n media_channel_list = []\n cps.get([obj.get()], media_channel_list)\n return media_channel_list\n\ndef media_led_set(slot, media_id, channel, speed):\n media_channel = cps_object.CPSObject(module='base-pas/media-channel', qual='target', data=\n {'slot': slot, 'port': media_id, 'channel': channel, 'speed': speed})\n ch = {'operation': 'set', 'change': media_channel.get()}\n nas_if.log_info(\"set speed for media Id : \"+str(media_id)+\" channel \"+str(channel)+\" speed \"+str(speed))\n cps.transaction([ch])\n\ndef media_transceiver_set(slot, media_id, channel, enable):\n media_channel = cps_object.CPSObject(module='base-pas/media-channel', qual='target', data=\n {'slot': slot, 'port': media_id, 'state': enable})\n if channel != None:\n media_channel.add_attr('channel', channel)\n ch = {'operation': 'set', 'change': media_channel.get()}\n cps.transaction([ch])\n\ndef led_control_get():\n media = cps_object.CPSObject(module='base-pas/media-config',qual='observed',data={'slot':1})\n l = []\n cps.get([media.get()],l)\n media_config = cps_object.CPSObject(obj=l[0])\n led_control = media_config.get_attr_data('led-control')\n return led_control\n","sub_path":"scripts/lib/python/nas_phy_media.py","file_name":"nas_phy_media.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"508063901","text":"from django.shortcuts import render\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom rest_framework import status \nfrom rest_framework.views import APIView\nfrom users.serializers import *\nfrom django.contrib.auth import authenticate\nfrom . import responses\nfrom drf_yasg.utils import swagger_auto_schema\nfrom utils.swagger import set_example\nfrom rest_framework.authtoken.models import Token \n\n\nclass RegistrationView(APIView):\n\n @swagger_auto_schema(\n operation_id='create_user',\n request_body=RegistrationSerializer,\n responses={\n '201': set_example({}),\n '400': set_example(responses.user_registration_400)\n },\n )\n def post(self,request):\n serializer = RegistrationSerializer(data = request.data)\n\n if serializer.is_valid():\n user = serializer.save()\n return Response({}, status.HTTP_201_CREATED)\n else:\n data = serializer.errors\n return Response(data, status.HTTP_400_BAD_REQUEST)\n\n\nclass LoginView(APIView):\n\n @swagger_auto_schema(\n operation_id='login_user',\n request_body=LoginSerializer,\n responses={\n '202': set_example(responses.login_202),\n '400': set_example(responses.login_400),\n '401': set_example(responses.login_401),\n },\n )\n def post(self,request):\n serializer = LoginSerializer(data = request.data)\n\n if serializer.is_valid():\n user = authenticate(\n username= serializer.data['email'], \n password= serializer.data['password']\n )\n \n if user:\n token,_ = Token.objects.get_or_create(user=user)\n\n return Response({\n 'token': f\"Token {token.key}\"\n }, status.HTTP_202_ACCEPTED)\n else:\n return Response({'message':'Credentials did not match'}, status.HTTP_401_UNAUTHORIZED)\n else:\n data = serializer.errors\n return Response(data, status.HTTP_400_BAD_REQUEST)\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"163995250","text":"\r\nN = int(input())\r\n\r\nstring = input().strip()\r\n\r\n\r\nparent = [i for i in range(26)]\r\n\r\ndef parOf(node):\r\n if node != parent[node]:\r\n parent[node] = parOf(parent[node])\r\n\t\r\n return parent[node]\r\n\r\n\r\n\r\ncost = 0\r\n\r\nfor a, b in zip(string[:len(string) // 2], reversed(string)):\r\n if a == b: continue\r\n\r\n \r\n cost += 1\r\n \r\n \r\n\r\nfor q in range(int(input())):\r\n query = input()\r\n if query[0] == '2':\r\n print(cost)\r\n \r\n else:\r\n a = ord(query[2]) - ord('a')\r\n b = ord(query[4]) - ord('a')\r\n \r\n if parOf(a) == parOf(b):\r\n continue\r\n \r\n parent[b] = parOf(a)\r\n \r\n cost = 0\r\n \r\n for a, b in zip(string[:len(string) // 2], reversed(string)):\r\n if parOf(a) == parOf(b): continue\r\n cost += 1","sub_path":"june easy/query2.py","file_name":"query2.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"256976803","text":"import argparse\nimport math\nimport os\nimport random\nimport time\nfrom pathlib import Path\n\nimport numpy as np\nimport paddle\nimport paddle.nn.functional as F\nimport paddle.optimizer as optim\nimport paddle.optimizer.lr as lr_scheduler\nimport yaml\nfrom paddle import amp\nfrom visualdl import LogWriter\nfrom tqdm import tqdm\n\nimport test # import test.py to get mAP after each epoch\nfrom models.yolo import Model\nfrom utils.datasets import create_dataloader\nfrom utils.general import (\n check_img_size, paddle_distributed_zero_first, labels_to_class_weights, plot_labels, check_anchors,\n labels_to_image_weights, compute_loss, plot_images, fitness, strip_optimizer, plot_results,\n get_latest_run, check_git_status, check_file, increment_dir, print_mutation, plot_evolution)\nfrom utils.paddle_utils import init_seeds, ModelEMA, intersect_dicts\nimport paddle.distributed as dist\n\n\ndef train(opt):\n dist.init_parallel_env()\n \n ###################################################################################################\n # Resume\n if opt.resume:\n last = get_latest_run() if opt.resume == 'get_last' else opt.resume # resume from most recent run\n if last and not opt.weights:\n print(f'Resuming training from {last}')\n opt.weights = last if opt.resume and not opt.weights else opt.weights\n if opt.local_rank == -1 or (\"RANK\" in os.environ and os.environ[\"RANK\"] == \"0\"):\n check_git_status()\n\n opt.hyp = opt.hyp or ('data/hyp.finetune.yaml' if opt.weights else 'data/hyp.scratch.yaml')\n opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files\n assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'\n opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test)\n opt.total_batch_size = opt.batch_size\n print(opt)\n with open(opt.hyp) as f:\n hyp = yaml.load(f, Loader=yaml.FullLoader) # load hyps\n\n tb_writer = None\n print('Start Tensorboard with \"tensorboard --logdir %s\", view at http://localhost:6006/' % opt.logdir)\n tb_writer = LogWriter(logdir=increment_dir(Path(opt.logdir) / 'exp', opt.name)) # runs/exp\n ###################################################################################################\n \n \n \n print(f'Hyperparameters {hyp}')\n logdir = Path(tb_writer.logdir) if tb_writer else Path(opt.logdir) / 'evolve' # logging directory\n wdir = str(logdir / 'weights') + os.sep # weights directory\n os.makedirs(wdir, exist_ok=True)\n last = wdir + 'last.pdparams'\n best = wdir + 'best.pdparams'\n results_file = str(logdir / 'results.txt')\n epochs, batch_size, total_batch_size, weights = \\\n opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights\n\n # TODO: Use DDP logging. Only the first process is allowed to log.\n # Save run settings\n with open(logdir / 'hyp.yaml', 'w') as f:\n yaml.dump(hyp, f, sort_keys=False)\n with open(logdir / 'opt.yaml', 'w') as f:\n yaml.dump(vars(opt), f, sort_keys=False)\n\n # Configure\n init_seeds(2)\n with open(opt.data) as f:\n data_dict = yaml.load(f, Loader=yaml.FullLoader) # model dict\n train_path = data_dict['train']\n test_path = data_dict['val']\n nc, names = (1, ['item']) if opt.single_cls else (int(data_dict['nc']), data_dict['names']) # number classes, names\n assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check\n\n # Model\n pretrained = weights.endswith('.pdparams')\n if pretrained:\n ckpt = paddle.load(weights) # load checkpoint\n model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc) # create\n exclude = ['anchor'] if opt.cfg else [] # exclude keys\n state_dict = ckpt['model'].astype('float32').state_dict() # to FP32\n state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect\n model.set_state_dict(state_dict) # load\n print('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report\n else:\n model = Model(opt.cfg, ch=3, nc=nc)# create\n # Scheduler https://arxiv.org/pdf/1812.01187.pdf\n lf = lambda x: (((1 + math.cos(x * math.pi / epochs)) / 2) ** 1.0) * 0.8 + 0.2 # cosine\n scheduler = lr_scheduler.LambdaDecay(hyp['lr0'], lr_lambda=lf)\n\n # Optimizer\n nbs = 64 # nominal batch size\n accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing\n hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay\n\n pg0, pg1, pg2 = [], [], [] # optimizer parameter groups\n for k, v in model.named_parameters():\n v.stop_gradient = False\n if '.bias' in k:\n pg2.append(v) # biases\n elif '.weight' in k and '.bn' not in k:\n pg1.append(v) # apply weight decay\n else:\n pg0.append(v) # all else\n\n if opt.adam:\n optimizer = optim.Adam(parameters=pg0+pg1+pg2, learning_rate=scheduler, beta1=hyp['momentum'], beta2=0.999, weight_decay=hyp['weight_decay']) # adjust beta1 to momentum\n else:\n optimizer = optim.Momentum(parameters=pg0+pg1+pg2, learning_rate=scheduler, momentum=hyp['momentum'], use_nesterov=True, weight_decay=hyp['weight_decay'])\n\n print('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0)))\n del pg0, pg1, pg2\n\n # Resume\n start_epoch, best_fitness = 0, 0.0\n if pretrained:\n # Optimizer\n if ckpt['optimizer'] is not None:\n optimizer.set_state_dict(ckpt['optimizer'])\n best_fitness = ckpt['best_fitness']\n\n # Results\n if ckpt.get('training_results') is not None:\n with open(results_file, 'w') as file:\n file.write(ckpt['training_results']) # write results.txt\n\n # Epochs\n start_epoch = ckpt['epoch'] + 1\n if epochs < start_epoch:\n print('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' %\n (weights, ckpt['epoch'], epochs))\n epochs += ckpt['epoch'] # finetune additional epochs\n\n del ckpt, state_dict\n \n # Image sizes\n gs = int(max(model.stride)) # grid size (max stride)\n imgsz, imgsz_test = [check_img_size(x, gs) for x in opt.img_size] # verify imgsz are gs-multiples\n\n # Exponential moving average\n ema = ModelEMA(model)\n\n\n # Trainloader\n dataloader, dataset = create_dataloader(train_path, imgsz, batch_size, gs, opt, hyp=hyp, augment=True,\n cache=opt.cache_images, rect=opt.rect)\n\n mlc = np.concatenate(dataset.labels, 0)[:, 0].max() # max label class\n nb = len(dataloader) # number of batches\n assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Possible class labels are 0-%g' % (mlc, nc, opt.data, nc - 1)\n\n # Testloader\n ema.updates = start_epoch * nb // accumulate # set EMA updates ***\n # local_rank is set to -1. Because only the first process is expected to do evaluation.\n testloader = create_dataloader(test_path, imgsz_test, batch_size, gs, opt, hyp=hyp, augment=False,\n cache=opt.cache_images, rect=True)[0]\n\n # Model parameters\n hyp['cls'] *= nc / 80. # scale coco-tuned hyp['cls'] to current dataset\n model.nc = nc # attach number of classes to model\n model.hyp = hyp # attach hyperparameters to model\n model.gr = 1.0 # giou loss ratio (obj_loss = 1.0 or giou)\n model.class_weights = labels_to_class_weights(dataset.labels, nc) # attach class weights\n model.names = names\n\n # Class frequency\n labels = np.concatenate(dataset.labels, 0)\n c = paddle.to_tensor(labels[:, 0]) # classes\n # plot_labels(labels, save_dir=logdir)\n if tb_writer:\n tb_writer.add_histogram('classes', c, 0)\n\n # Check anchors\n if not opt.noautoanchor:\n check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz)\n\n # Start training\n t0 = time.time()\n nw = max(3 * nb, 1e3) # number of warmup iterations, max(3 epochs, 1k iterations)\n # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training\n maps = np.zeros(nc) # mAP per class\n results = (0, 0, 0, 0, 0, 0, 0) # 'P', 'R', 'mAP', 'F1', 'val GIoU', 'val Objectness', 'val Classification'\n scheduler.last_epoch = start_epoch - 1 # do not move\n scaler = amp.GradScaler(enable=True, init_loss_scaling=65536.0, incr_every_n_steps=2000)\n print('Image sizes %g train, %g test' % (imgsz, imgsz_test))\n print('Using %g dataloader workers' % dataloader.num_workers)\n print('Starting training for %g epochs...' % epochs)\n model = paddle.DataParallel(model)\n model.train()\n for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------\n # Update mosaic border\n # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)\n # dataset.mosaic_border = [b - imgsz, -b] # height, width borders\n\n mloss = paddle.zeros([4]) # mean losses\n pbar = enumerate(dataloader)\n print(('\\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'GIoU', 'obj', 'cls', 'total', 'targets', 'img_size'))\n pbar = tqdm(pbar, total=nb) # progress bar\n optimizer.clear_grad()\n for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------\n ni = i + nb * epoch # number integrated batches (since train start)\n imgs = imgs.astype('float32') / 255.0 # uint8 to float32, 0-255 to 0.0-1.0\n targets = targets.astype('float32')\n # Warmup\n if ni <= nw:\n xi = [0, nw] # x interp\n accumulate = max(1, np.interp(ni, xi, [1, nbs / total_batch_size]).round())\n if 'Momentum' in str(type(optimizer)).split('.')[-1]:\n optimizer._momentum = np.interp(ni, xi, [0.9, hyp['momentum']])\n\n # Multi-scale\n if opt.multi_scale:\n sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size\n sf = sz / max(imgs.shape[2:]) # scale factor\n if sf != 1:\n ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)\n imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)\n\n # Autocast\n with amp.auto_cast(enable=True):\n # Forward \n pred = model(imgs)\n\n # Loss\n loss, loss_items = compute_loss(pred, targets, model._layers) # scaled by batch_size\n\n # Backward\n scaled = scaler.scale(loss) # scale the loss\n scaled.backward()\n\n # Optimize\n if ni % accumulate == 0:\n scaler.minimize(optimizer, scaled) # optimizer.step\n optimizer.clear_grad()\n if ema is not None:\n ema.update(model)\n\n # Print\n mloss = (mloss * i + loss_items) / (i + 1) # update mean losses\n mem = '%.3gG' % 0 # (GB)\n s = ('%10s' * 2 + '%10.4g' * 6) % (\n '%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], imgs.shape[-1])\n pbar.set_description(s)\n\n # Plot\n if ni < 3:\n f = str(logdir / ('train_batch%g.jpg' % ni)) # filename\n result = plot_images(images=imgs, targets=targets, paths=paths, fname=f)\n if tb_writer and result is not None:\n tb_writer.add_image(f, result, dataformats='HWC', step=epoch)\n # tb_writer.add_graph(model, imgs) # add model to visualDL\n\n # end batch ------------------------------------------------------------------------------------------------\n\n # Scheduler\n scheduler.step()\n\n # DDP process 0 or single-GPU\n # mAP\n if ema is not None:\n ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'gr', 'names', 'stride'])\n final_epoch = epoch + 1 == epochs\n # end epoch ----------------------------------------------------------------------------------------------------\n # end training\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--weights', type=str, default='yolov4-p5.pdparams', help='initial weights path')\n parser.add_argument('--cfg', type=str, default='', help='model.yaml path')\n parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')\n parser.add_argument('--hyp', type=str, default='', help='hyperparameters path, i.e. data/hyp.scratch.yaml')\n parser.add_argument('--epochs', type=int, default=300)\n parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs')\n parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='train,test sizes')\n parser.add_argument('--rect', action='store_true', help='rectangular training')\n parser.add_argument('--resume', nargs='?', const='get_last', default=False,\n help='resume from given path/last.pdparams, or most recent run if blank')\n parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')\n parser.add_argument('--notest', action='store_true', help='only test final epoch')\n parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check')\n parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')\n parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')\n parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')\n parser.add_argument('--name', default='', help='renames results.txt to results_name.txt if supplied')\n parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')\n parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')\n parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')\n parser.add_argument('--adam', action='store_true', help='use paddle.optimizer.Adam() optimizer')\n parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')\n parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify')\n parser.add_argument('--logdir', type=str, default='runs/', help='logging directory')\n opt = parser.parse_args()\n\n # train(hyp, opt, tb_writer)\n dist.spawn(train, args=(opt,), nprocs=4)\n","sub_path":"train_multi_gpu.py","file_name":"train_multi_gpu.py","file_ext":"py","file_size_in_byte":14866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"43114099","text":"import pytest\n\nimport stk\n\nfrom ..case_data import CaseData\n\n\ndef has_bromo(building_block):\n (fg,) = building_block.get_functional_groups(0)\n return fg.__class__ is stk.Bromo\n\n\ndef _get_case_data_1() -> CaseData:\n bb1 = stk.BuildingBlock(\"BrCCBr\", [stk.BromoFactory()])\n graph1 = stk.polymer.Linear((bb1,), \"A\", 2)\n\n bb2 = stk.BuildingBlock(\"BrCNCBr\", [stk.BromoFactory()])\n graph2 = stk.polymer.Linear((bb2,), \"A\", 2)\n\n return CaseData(\n mutator=stk.RandomMutator(\n mutators=(\n stk.RandomBuildingBlock(\n building_blocks=(bb2,),\n is_replaceable=has_bromo,\n ),\n ),\n ),\n record=stk.MoleculeRecord(graph1),\n mutation_record=stk.MutationRecord(\n molecule_record=stk.MoleculeRecord(graph2),\n mutator_name=\"RandomBuildingBlock\",\n ),\n )\n\n\n@pytest.fixture(\n scope=\"session\",\n params=(_get_case_data_1,),\n)\ndef random_mutator(request) -> CaseData:\n return request.param()\n","sub_path":"tests/ea/mutation/mutator/fixtures/random.py","file_name":"random.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"533474872","text":"import csv, sqlite3\nimport json\nimport falcon\nfrom collections import OrderedDict\n\n\ncon = sqlite3.connect(\":memory:\")\ncur = con.cursor()\n#cur.execute(\"CREATE TABLE t (id, ident, type, name, latitude, longitude, elevation, continent, country, region, municipality, service, icao, iata, locale, home, wiki, keyword);\") # use your column names here\ncur.execute(\"CREATE TABLE t (id, name, latitude, longitude, country, city, icao, iata);\")\n\nwith open('airports.csv','rt') as fin: # `with` statement available in 2.5+\n # csv.DictReader uses first line in file for column headings by default\n dr = csv.DictReader(fin) # comma is default delimiter\n #to_db = [(i['id'], i['type'],i['name'],i['latitude_deg'],i['longitude_deg'],i['elevation'],i['continent'],i['country'],i['region'],i['municipality'], i['service'],i['icao'],i['iata'],i['locale'],i['home'],i['wiki'],i['keyword']) for i in dr]\n to_db = [(i['id'], i['name'], i['latitude_deg'], i['longitude_deg'], i['iso_country'], i['municipality'], i['gps_code'], i['iata_code']) for i in dr]\n#cur.executemany(\"INSERT INTO t (id, ident, type, name, latitude, longitude, elevation, continent, country, region, municipality, service, icao, iata, locale, home, wiki, keyword) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);\", to_db)\ncur.executemany(\"INSERT INTO t (id, name, latitude, longitude, country, city, icao, iata) VALUES (?, ?, ?, ?, ?, ?, ?, ?);\", to_db)\ncur.execute(\"DELETE FROM t WHERE iata=''\")\ncon.commit()\n\nclass StorageEngine(object):\n\n def get_by_iata(self, iata):\n cursor = con.execute(\"SELECT name, latitude, longitude, city, iata, icao, country, city FROM t WHERE LOWER(iata)=?\", (iata.lower(),))\n return self.json_wrapper(cursor)\n def get_by_name(self, name):\n cursor = con.execute(\"SELECT name, latitude, longitude, city, iata, icao, country, city FROM t WHERE LOWER(name) LIKE '%' || ? || '%'\", (name.lower(),))\n return self.json_wrapper(cursor)\n\n def json_wrapper(self, cursor):\n data =[]\n for row in cursor:\n name = row[0]\n iata = row[4]\n icao = row[5]\n city = row[3]\n country = row[6]\n latitude = row[1]\n longitude = row[2]\n data.append(OrderedDict(\n [('name', name), ('iata', iata), ('icao', icao), ('city', city), ('country', country),\n ('latitude', latitude), ('longitude', longitude)]))\n if str(data)=='[]':\n raise falcon.HTTPNotFound\n else:\n return json.loads(json.dumps(data))\n","sub_path":"airportSearchApi/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"345241157","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.5-i386/egg/pyncomb/combfuncs.py\n# Compiled at: 2009-10-12 21:57:21\n\"\"\"Various combinatorial functions used by the pyncomb library, and\nuseful in and of their own right.\"\"\"\n_Cmax = 0\n_C = [[1]]\n\ndef binom(n, k, store=True):\n \"\"\"Calculate the binomial coefficient C(n,k) = n!/k!(n-k)!.\n\n This is done using dynamic programming. If store is True, the final\n result and all intermediate computations are stored in a lookup table\n so that future function calls can be done in constant time.\n\n The caching lookup table should be used unless you have very specific reasons\n not to do so, as the binomial table is used in many other functions in pyncomb.\n If store is False, the binomial coefficient is fully calculated, which is very\n inefficient.\"\"\"\n global _C\n global _Cmax\n if n <= _Cmax:\n if k >= 0 and k <= n:\n return _C[n][k]\n return 0\n else:\n if store:\n for i in xrange(_Cmax + 1, n + 1):\n _C.append([ (_C[(i - 1)][j] if j < i else 0) + (_C[(i - 1)][(j - 1)] if j > 0 else 0) for j in xrange(i + 1) ])\n\n _Cmax = n\n return _C[n][k]\n return reduce(lambda a, b: a * (n - b) / (b + 1), xrange(k), 1)\n\n\ndef permCount(n, k):\n \"\"\"Calculate P(n,k) = n!/(n-k)!, the number of permutations over n objects, taking\n k of them at a time.\"\"\"\n return binom(n, k) * reduce(lambda a, b: a * b, xrange(1, k + 1), 1)\n\n\ndef createLookup(B):\n \"\"\"Process B to create a reverse lookup scheme that is appropriate for\n any of the libraries in pyncomb that allow for one or more base sets to\n be specified.\n\n Let rev(K) be the reverse lookup dictionary of a list K, i.e. if\n K[i] = j, then rev(K)[j] = i.\n\n If B is an integer, then return B.\n If B is a flat list, then return a pair (B,rev(B)).\n If B is a list of lists / integers, then return a list Bn with:\n 1. Bn[i] = B[i] if B[i] is an integer.\n 2. Bn[i] = (B[i], rev(B[i])) if B[i] is a list.\n\n For example, createLookup can translate a base set specification of:\n [4,['a','b','c'],[11,22]]\n which represents three base sets [0,1,2,3], ['a','b','c'], [11,22].\n The returned data will consist of base sets with their reverse lookup\n data and can be used as the B parameter in any function.\"\"\"\n if type(B) == int:\n return B\n if reduce(lambda a, b: a and b, [ type(i) != list for i in B ], True):\n return (B, dict([ (B[i], i) for i in xrange(len(B)) ]))\n Bn = []\n for D in B:\n if type(D) == int:\n Bn.append(D)\n else:\n Bn.append((D, dict([ (D[i], i) for i in xrange(len(D)) ])))\n\n return Bn","sub_path":"pycfiles/pyncomb-1.0.2-py2.6/combfuncs.py","file_name":"combfuncs.py","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"473325127","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/hachterberg/dev/fastr/fastr/fastr/resources/plugins/interfaceplugins/nipypeinterface.py\n# Compiled at: 2019-06-04 03:32:43\n# Size of source mod 2**32: 9122 bytes\nfrom collections import OrderedDict, Mapping\ntry:\n import nipype, traits\n IMPORT_SUCCESS = True\n IMPORT_ERROR = ''\nexcept ImportError as e:\n IMPORT_SUCCESS = False\n IMPORT_ERROR = e.msg\n\nimport fastr\nfrom fastr import exceptions\nfrom fastr.abc.baseplugin import PluginState\nfrom fastr.core.interface import Interface, InterfaceResult, InputSpec, OutputSpec\n\nclass HiddenFieldMap(Mapping):\n\n def __init__(self, *args, **kwargs):\n self._data = OrderedDict(*args, **kwargs)\n\n def __getitem__(self, item):\n return self._data[item]\n\n def __len__(self):\n return len(self._data)\n\n def __iter__(self):\n for key, value in self._data.items():\n if not (hasattr(value, 'hidden') and value.hidden):\n yield key\n\n\nif IMPORT_SUCCESS:\n DATATYPE_MAP = {traits.trait_types.Int: 'Int', \n traits.trait_types.Long: 'Int', \n traits.trait_types.Float: 'Float', \n traits.trait_types.Bool: 'Boolean', \n traits.trait_types.Str: 'String', \n traits.trait_types.String: 'String', \n traits.trait_types.Unicode: 'String', \n traits.trait_types.List: None}\nelse:\n DATATYPE_MAP = {}\n\nclass NipypeInterface(Interface):\n __doc__ = '\\n Experimental interfaces to using ``nipype`` interfaces directly in fastr\\n tools, only using a simple reference.\\n\\n To create a tool using a nipype interface just create an interface with\\n the correct type and set the ``nipype`` argument to the correct class.\\n For example in an xml tool this would become::\\n\\n \\n nipype.interfaces.elastix.Registration\\n \\n\\n .. note::\\n\\n To use these interfaces ``nipype`` should be installed on the system.\\n\\n .. warning::\\n\\n This interface plugin is basically functional, but highly experimental!\\n '\n if IMPORT_ERROR:\n _status = (\n PluginState.failed, 'nipype could not be found!')\n\n def __init__(self, id_, nipype_cls=None, document=None):\n super(NipypeInterface, self).__init__()\n if nipype_cls is None:\n if document is None:\n raise exceptions.FastrValueError('Need to have at Nipype class set in either the nipype_cls or document argument')\n if nipype_cls is not None and document is not None:\n raise exceptions.FastrValueError('Need to have at Nipype class set in either the nipype_cls or the document argument, not both!')\n else:\n if document is not None:\n nipype_cls = document['nipype_class']\n if isinstance(nipype_cls, str):\n if '.' in nipype_cls:\n module, cls = nipype_cls.rsplit('.', 1)\n _temp = __import__(module, globals(), locals(), [cls], -1)\n nipype_cls = getattr(_temp, cls)\n else:\n raise ValueError('If a string is given, it should be a full class specification (in the form of nipype.interfaces.something.Class), got \"{}\"'.format(nipype_cls))\n self.nipype_class = nipype_cls\n self.id = id_\n self._create_inputs_outputs()\n\n def _create_inputs_outputs(self):\n nipype_object = self.nipype_class()\n ignore_inputs = ['args', 'environ', 'ignore_exception', 'terminal_output']\n inputs = []\n for id_, input_ in nipype_object.input_spec().items():\n default = input_.default\n if default == '':\n default = None\n inputs.append(InputSpec(id_=id_, cardinality=(1 if not input_.is_trait_type(traits.trait_types.List) else '1-*'),\n datatype=(self.get_type(input_)),\n required=(input_.mandatory and default is None),\n description=(input_.desc),\n default=default,\n hidden=(id_ in ignore_inputs)))\n\n outputs = []\n for id_, output in nipype_object.output_spec().items():\n outputs.append(OutputSpec(id_=id_, cardinality=(1 if not output.is_trait_type(traits.trait_types.List) else 'unknown'),\n datatype=(self.get_type(output)),\n automatic=True,\n required=False,\n description=(output.desc),\n hidden=False))\n\n self._inputs = HiddenFieldMap((input_.id, input_) for input_ in inputs)\n self._outputs = HiddenFieldMap((output_.id, output_) for output_ in outputs)\n\n def __getstate__(self):\n state = {'id':self.id, \n 'class':type(self).__name__, \n 'nipype_class':self.nipype_class}\n return state\n\n def __setstate__(self, state):\n del state['class']\n self.__dict__.update(state)\n nipype_cls = self.nipype_class\n if isinstance(nipype_cls, str):\n if '.' in nipype_cls:\n module, cls = nipype_cls.rsplit('.', 1)\n _temp = __import__(module, globals(), locals(), [cls], -1)\n nipype_cls = getattr(_temp, cls)\n else:\n raise ValueError('If a string is given, it should be a full class specification (in the form of nipype.interfaces.something.Class), got \"{}\"'.format(nipype_cls))\n self.nipype_class = nipype_cls\n self._create_inputs_outputs()\n\n def __eq__(self, other):\n if not isinstance(other, NipypeInterface):\n return NotImplemented\n else:\n return vars(self) == vars(other)\n\n def get_type(self, trait):\n datatype = DATATYPE_MAP.get(trait.trait_type, 'AnyFile')\n if datatype is None:\n new_trait = trait.inner_traits[0]\n return self.get_type(new_trait)\n else:\n return datatype\n\n @property\n def inputs(self):\n return self._inputs\n\n @property\n def outputs(self):\n return self._outputs\n\n @property\n def expanding(self):\n return 0\n\n def execute(self, target, payload):\n \"\"\"\n Execute the interface using a specific target and payload (containing\n a set of values for the arguments)\n\n :param target: the target to use\n :type target: :py:class:`SampleId `\n :param dict payload: the values for the arguments\n :return: result of the execution\n :rtype: InterfaceResult\n \"\"\"\n nipype_object = self.nipype_class()\n for id_, input_value in payload['inputs'].items():\n if len(input_value) == 0:\n fastr.log.info('Skipping non-valued input {}'.format(id_))\n else:\n value = [x.value if isinstance(x, fastr.datatypes.DataType) else x for x in input_value]\n if self.inputs[id_].cardinality == 1:\n if len(value) > 1:\n raise exceptions.FastrValueError('Expected cardinality 1, got {}'.format(len(value)))\n value = value[0]\n else:\n value = list(value)\n setattr(nipype_object.inputs, id_, value)\n\n nipype_result = nipype_object.run()\n result_data = nipype_result.outputs.get()\n fastr.log.info('NIPYPE RESULT: {}'.format(result_data))\n for key, value in result_data.items():\n if isinstance(value, list):\n value = tuple(value)\n else:\n value = (\n value,)\n result_data[key] = value\n\n fastr.log.info('RESULT DATA: {}'.format(result_data))\n result = InterfaceResult(result_data, nipype_result.runtime.dictcopy(), payload)\n return result\n\n @classmethod\n def test(cls):\n if not IMPORT_SUCCESS:\n raise ImportError('Could not load required module: {}'.format(IMPORT_ERROR))","sub_path":"pycfiles/fastr-3.1.3-py3-none-any/nipypeinterface.cpython-36.py","file_name":"nipypeinterface.cpython-36.py","file_ext":"py","file_size_in_byte":8046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"335850233","text":"import boto3\nimport json\nfrom common.json import Encoder\n\n\nclass DynamoStream:\n def __init__(self, region_name: str, endpoint_url=''):\n conf = {\n 'region_name: region_name,'\n }\n if endpoint_url:\n conf['endpoint_url'] = endpoint_url\n self.db_client = boto3.client('dynamodb', **conf)\n self.stream_client = boto3.client('dynamodbstreams', **conf)\n\n def _describe_table(self, table_name: str):\n return self.db_client.describe_table(TableName=table_name)\n\n def _describe_stream(self, stream_arn: str):\n return self.stream_client.describe_stream(StreamArn=stream_arn)\n\n def _get_shard_iterator(self, stream_arn: str, shard_id: str):\n return self.stream_client.get_shard_iterator(\n StreamArn=stream_arn,\n ShardId=shard_id,\n ShardIteratorType='LATEST',\n )\n\n def _get_records(self, shard_iterator: str):\n return self.stream_client.get_records(ShardIterator=shard_iterator)\n\n def get_records(self, table_name: str)-> iter:\n stream_arn = self._describe_table(table_name).get('Table', {}).get('LatestStreamArn', '')\n if not stream_arn:\n return []\n\n shard_ids = (\n x['ShardId'] for x in\n self._describe_stream(stream_arn).get('StreamDescription', {}).get('Shards', [])\n if 'ShardId' in x\n )\n shard_iterators = (\n self._get_shard_iterator(stream_arn=stream_arn, shard_id=x).get('ShardIterator', '')\n for x in shard_ids\n )\n\n for si in shard_iterators:\n csi = si\n while csi:\n res = self._get_records(csi)\n if res.get('Records'):\n yield res\n csi = res.get('NextShardIterator', '')\n\n\nif __name__ == '__main__':\n from argparse import ArgumentParser\n\n p = ArgumentParser(\n description='yield dynamodb stream',\n )\n p.add_argument('--region_name', action='store', type=str, required=True)\n p.add_argument('--endpoint_url', action='store', type=str)\n p.add_argument('--table_name', action='store', type=str, required=True)\n\n opt = p.parse_args()\n ds = DynamoStream(\n region_name=opt.region_name,\n endpoint_url=opt.endpoint_url,\n )\n for x in ds.get_records(opt.table_name):\n print(json.dumps(x, cls=Encoder))\n","sub_path":"py/dynamodbstreams.py","file_name":"dynamodbstreams.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"235101200","text":"\n\n\n##\n##If we list all the natural numbers below 10 that are multiples of 3 or 5,\n##we get 3, 5, 6 and 9. The sum of these multiples is 23.\n##\n##Find the sum of all the multiples of 3 or 5 below 1000.\n\n\ndef prob1(n):\n\n \"\"\"n is the number that we are going to be the ceiling for numbers we check\n \"\"\"\n answer = 0\n\n for i in range(n):\n if i%3==0 or i%5==0:\n answer += i\n\n return answer\n","sub_path":"p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"183154840","text":"import os\nfrom dotenv import load_dotenv\nfrom datetime import datetime\nimport math\n\nimport io\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nimport numpy\nimport pickle\n\nfrom dcd.entities.thing import Thing\n\n# The thing ID and access token\nload_dotenv()\nTHING_ID = os.environ['THING_ID']\nTHING_TOKEN = os.environ['THING_TOKEN']\n\n# Sitting classes\nCLASSES = [\"Not Sitting\", \"Proper Sitting\", \"Leaning Forward\",\n \"Leaning Backward\", \"Leaning Left\", \"Leaning Right\"]\n\n# Where to save the model to\nMODEL_FILE_NAME = \"model.pickle\"\n\n# Data collection time frame (in milliseconds)\nSTART_TS = 1550946000000\nEND_TS = 1550946000000+300000\n\n# Property ID\nPROPERTY_DATA = \"fsr-1ebb\"\nPROPERTY_LABEL = \"sitting-8b25\"\n\n# Instantiate a thing with its credential\nmy_thing = Thing(thing_id=THING_ID, token=THING_TOKEN)\n\n# We can fetch the details of our thing\nmy_thing.read()\n\ndef unix_time_millis(dt):\n epoch = datetime.utcfromtimestamp(0)\n return math.floor((dt - epoch).total_seconds() * 1000.0)\n\n# If you just registered your Thing on the DCD Hub,\n# it has only an id, a name and a type.\n# print(my_thing.to_json())\n\nfsr = my_thing.properties[PROPERTY_DATA]\nsitting = my_thing.properties[PROPERTY_LABEL]\nfsr.read(START_TS, END_TS)\nsitting.read(START_TS, END_TS)\n\ndata = fsr.values\nlabel = sitting.values\n\n# Split the data into training data (80%) and test data (20%)\ntrain_data = []\ntrain_label = []\ntest_data = []\ntest_label = []\n\nfor index in range(len(data)):\n # remove time\n data[index].pop(0)\n label[index].pop(0)\n if index%5 == 0:\n # 20% to test data\n test_data.append(data[index])\n test_label.append(label[index])\n else:\n # 80% to train data\n train_data.append(data[index])\n train_label.append(label[index])\n\nprint(\"nb train data: \" + str(len(data)))\nprint(\"nb train labels: \" + str(len(label)))\n\nprint(\"nb train data: \" + str(len(train_data)))\nprint(\"nb train labels: \" + str(len(train_label)))\n\nprint(\"nb test data: \" + str(len(test_data)))\nprint(\"nb test labels: \" + str(len(test_label)))\n\n# Train a k-Nearest Neighbour (kNN) algorithm\nneigh = KNeighborsClassifier(n_neighbors=1)\nneigh.fit(train_data, train_label)\n\n# Use the test data to evaluate the algorithm\npredicted = neigh.predict(test_data)\ntestLabel = numpy.array(test_label)\nresult = accuracy_score(testLabel, predicted)\nprint(result)\n\n# Report evaluation Confusion matrix\nmatrix = confusion_matrix(testLabel, predicted)\nprint(matrix)\nprint(precision_score(testLabel, predicted, average=\"macro\"))\nprint(recall_score(testLabel, predicted, average=\"macro\"))\nprint(f1_score(testLabel, predicted, average=\"weighted\"))\nprint(f1_score(testLabel, predicted, average=None))\n\nprint(classification_report(test_label, predicted, target_names=CLASSES))\n\n# Save the model in a file\nwith io.open(MODEL_FILE_NAME, \"wb\") as file:\n pickle.dump(neigh, file, protocol=2)","sub_path":"examples/process/ml/2_train_and_test.py","file_name":"2_train_and_test.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"582289012","text":"#####################################################################\n############ Code sourced from Sentence-BERT repository##############\n# @inproceedings{reimers-2019-sentence-bert,\n# title = \"Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks\",\n# author = \"Reimers, Nils and Gurevych, Iryna\",\n# booktitle = \"Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing\",\n# month = \"11\",\n# year = \"2019\",\n# publisher = \"Association for Computational Linguistics\",\n# url = \"https://arxiv.org/abs/1908.10084\",\n# }\n# https://github.com/UKPLab/sentence-transformers/blob/09c557b8b3a0618f8502550efa0c88af7fc92432/sentence_transformers/models/Transformer.py\n\nfrom torch import nn\nfrom transformers import AutoModel, AutoTokenizer, AutoConfig\nimport json\nfrom typing import List, Dict, Optional, Union, Tuple\nimport os\n\n\nclass Transformer(nn.Module):\n \"\"\"Huggingface AutoModel to generate token embeddings.\n Loads the correct class, e.g. BERT / RoBERTa etc.\n :param model_args: Arguments (key, value pairs) passed to the Huggingface Transformers model\n :param cache_dir: Cache dir for Huggingface Transformers to store/load models\n :param tokenizer_args: Arguments (key, value pairs) passed to the Huggingface Tokenizer model\n \"\"\"\n def __init__(self, args, \n model_args: Dict = {}, cache_dir: Optional[str] = None,\n tokenizer_args: Dict = {}):\n super(Transformer, self).__init__()\n # self.config_keys = ['max_seq_length']\n self.args = args\n\n tokenizer_args['do_lower_case'] = args.do_lower_case\n\n self.config = AutoConfig.from_pretrained(args.model, **model_args, cache_dir=cache_dir)\n self.auto_model = AutoModel.from_pretrained(args.model, config=self.config, cache_dir=cache_dir)\n self.tokenizer = AutoTokenizer.from_pretrained(args.model, cache_dir=cache_dir, **tokenizer_args)\n\n\n def forward(self, features):\n \"\"\"Returns token_embeddings, cls_token\"\"\"\n trans_features = {'input_ids': features['input_ids'], 'attention_mask': features['attention_mask']}\n if 'token_type_ids' in features:\n trans_features['token_type_ids'] = features['token_type_ids']\n\n output_states = self.auto_model(**trans_features, return_dict=False)\n output_tokens = output_states[0]\n\n cls_tokens = output_tokens[:, 0, :] # CLS token is first token\n features.update({'token_embeddings': output_tokens, 'cls_token_embeddings': cls_tokens, 'attention_mask': features['attention_mask']})\n\n if self.auto_model.config.output_hidden_states:\n all_layer_idx = 2\n if len(output_states) < 3: #Some models only output last_hidden_states and all_hidden_states\n all_layer_idx = 1\n\n hidden_states = output_states[all_layer_idx]\n features.update({'all_layer_embeddings': hidden_states})\n\n return features\n\n\n def get_word_embedding_dimension(self) -> int:\n return self.auto_model.config.hidden_size\n\n\n def tokenize(self, texts: Union[List[str], List[Dict], List[Tuple[str, str]]]):\n \"\"\"\n Tokenizes a text and maps tokens to token-ids\n \"\"\"\n output = {}\n if isinstance(texts[0], str):\n to_tokenize = [texts]\n elif isinstance(texts[0], dict):\n to_tokenize = []\n output['text_keys'] = []\n for lookup in texts:\n text_key, text = next(iter(lookup.items()))\n to_tokenize.append(text)\n output['text_keys'].append(text_key)\n to_tokenize = [to_tokenize]\n else:\n batch1, batch2 = [], []\n for text_tuple in texts:\n batch1.append(text_tuple[0])\n batch2.append(text_tuple[1])\n to_tokenize = [batch1, batch2]\n\n output.update(self.tokenizer(*to_tokenize, padding=True, truncation='longest_first', return_tensors=\"pt\", max_length=self.args.max_len))\n return output\n\n\n # def get_config_dict(self):\n # return {key: self.__dict__[key] for key in self.config_keys}\n\n # def save(self, output_path: str):\n # self.auto_model.save_pretrained(output_path)\n # self.tokenizer.save_pretrained(output_path)\n\n # with open(os.path.join(output_path, 'sentence_bert_config.json'), 'w') as fOut:\n # json.dump(self.get_config_dict(), fOut, indent=2)\n\n # @staticmethod\n # def load(input_path: str):\n # #Old classes used other config names than 'sentence_bert_config.json'\n # for config_name in ['sentence_bert_config.json', 'sentence_roberta_config.json', 'sentence_distilbert_config.json', 'sentence_camembert_config.json', 'sentence_albert_config.json', 'sentence_xlm-roberta_config.json', 'sentence_xlnet_config.json']:\n # sbert_config_path = os.path.join(input_path, config_name)\n # if os.path.exists(sbert_config_path):\n # break\n\n # with open(sbert_config_path) as fIn:\n # config = json.load(fIn)\n # return Transformer(model_name_or_path=input_path, **config)","sub_path":"models/Transformer.py","file_name":"Transformer.py","file_ext":"py","file_size_in_byte":5154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"459019201","text":"\"\"\"\nDjango settings for datamain project.\n\"\"\"\n\nimport json, os, re, sys\nfrom django.http import HttpResponse\n\nDEFAULT_CHARSET = 'utf-8'\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nCLIENT_BASE_DIR = os.path.join(BASE_DIR, '../client')\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'jabnsdjhansdjhbasd123123123'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = ['*']\n\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nif not DEBUG:\n SECURE_SSL_REDIRECT = True\n SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n\n# Application definition\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n # Third Party Apps\n 'corsheaders',\n # 'rest_framework',\n # Internal Apps\n]\n\nMIDDLEWARE_CLASSES = [\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.common.CommonMiddleware',\n # 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n # 'debug_panel.middleware.DebugPanelMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'django.middleware.common.BrokenLinkEmailsMiddleware',\n 'django.middleware.gzip.GZipMiddleware',\n]\n\nROOT_URLCONF = 'datamain.urls'\n\nWSGI_APPLICATION = 'datamain.wsgi.application'\n\n# DATABASES = {\n# 'default': {\n# 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n# 'NAME': os.environ.get('DATABASE_NAME'),\n# 'USER': os.environ.get('DATABASE_USER'),\n# 'PASSWORD': os.environ.get('DATABASE_PASSWORD'),\n# 'HOST': 'localhost',\n# 'PORT': '',\n# }\n# }\n\n\n# Password validation\n# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.10/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.10/howto/static-files/\n\nSTATIC_URL = '/static/'\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static/')\n\n# Static file and template locations\nif not DEBUG:\n DJANGO_TEMPLATE_DIRS = (\n os.path.join(CLIENT_BASE_DIR, 'app'),\n )\n\n STATICFILES_DIRS = (\n os.path.join(CLIENT_BASE_DIR, 'app', 'static'),\n #os.path.join(CLIENT_BASE_DIR, '.tmp', 'static') # Generated CSS files\n )\nelse:\n DJANGO_TEMPLATE_DIRS = (\n os.path.join(CLIENT_BASE_DIR, 'app'),\n )\n\n STATICFILES_DIRS = (\n os.path.join(CLIENT_BASE_DIR, 'app', 'static'),\n )\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': DJANGO_TEMPLATE_DIRS,\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n 'debug': DEBUG,\n },\n },\n]\n\nIGNORABLE_404_URLS = (\n re.compile(r'^/apple-touch-icon.*\\.png$'),\n re.compile(r'^/favicon\\.ico$'),\n re.compile(r'^/robots\\.txt$'),\n)\n\n# # MAIL\n# FORM_MAIL = 'info@fydip.com'\n\n# if True:\n# EMAIL_USE_TLS = True\n# EMAIL_HOST_USER = 'info@fydip.com'\n# EMAIL_HOST = 'smtp.gmail.com'\n# EMAIL_PORT = 587\n# EMAIL_HOST_PASSWORD = 'fydip@dmin'\n# DEFAULT_FROM_EMAIL = 'info@fydip.com'\n# SERVER_EMAIL = 'info@fydip.com'\n# else:\n# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n\n# THIRD PARTY SETTINGS\n\n# CORSHEADERS\n\nCORS_ORIGIN_ALLOW_ALL = False\nCORS_ALLOW_CREDENTIALS = True\nCORS_ORIGIN_WHITELIST = (\n 'localhost:8000'\n )\n\nCORS_ALLOW_METHODS = (\n 'GET',\n 'POST',\n 'PUT',\n 'PATCH',\n 'DELETE',\n 'OPTIONS'\n)\n \nCORS_ALLOW_HEADERS = (\n 'Access-Control-Allow-Origin',\n 'x-requested-with',\n 'content-type',\n 'accept',\n 'origin',\n 'authorization',\n 'x-csrftoken'\n)\n\n# REST FRAMEWORK\n\n# REST_FRAMEWORK = {\n# 'DEFAULT_AUTHENTICATION_CLASSES': [\n# # 'rest_framework.authentication.SessionAuthentication',\n# 'rest_framework.authentication.TokenAuthentication',\n# ],\n# # Use hyperlinked styles by default.\n# # Only used if the `serializer_class` attribute is not set on a view.\n# 'DEFAULT_MODEL_SERIALIZER_CLASS':\n# 'rest_framework.serializers.HyperlinkedModelSerializer',\n# # Use Django's standard `django.contrib.auth` permissions,\n# # or allow read-only access for unauthenticated users.\n# 'DEFAULT_PERMISSION_CLASSES': [\n# 'rest_framework.permissions.AllowAny',\n# ],\n# 'DEFAULT_RENDERER_CLASSES': [\n# 'rest_framework.renderers.JSONRenderer',\n# ]\n# }","sub_path":"datamain/datamain/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"373528183","text":"# Copyright (c) 2021. yoshida-lab. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom xenonpy.inverse.base import BaseLogLikelihood, BaseProposal, BaseResample, BaseSMC\n\n\n@pytest.fixture(scope='module')\ndef data():\n # ignore numpy warning\n import warnings\n print('ignore NumPy RuntimeWarning\\n')\n warnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\")\n warnings.filterwarnings(\"ignore\", message=\"numpy.ndarray size changed\")\n\n class LLH(BaseLogLikelihood):\n\n def log_likelihood(self, X, **target):\n return pd.DataFrame(np.asanyarray(X))\n\n class Proposal(BaseProposal):\n\n def proposal(self, X):\n return X\n\n class Resample(BaseResample):\n\n def resample(self, X, freq, size, p):\n return np.random.choice(X, size, p=p)\n\n class SMC(BaseSMC):\n\n def __init__(self):\n self._log_likelihood = LLH()\n self._proposal = Proposal()\n self._resample = Resample()\n\n # prepare test data\n yield dict(llh=LLH, prop=Proposal, smc=SMC, resample=Resample)\n\n print('test over')\n\n\ndef test_base_loglikelihood_1(data):\n llh = data['llh']()\n X = np.array([1, 2, 3, 3, 4, 4])\n ll = llh(X)\n print(ll)\n assert np.all(ll.values.flatten() == X)\n\n\ndef test_base_proposer_1(data):\n proposer = data['prop']()\n X = np.array([1, 2, 3, 4, 5])\n x = proposer(X)\n assert np.all(x == X)\n\n\ndef test_base_resammple_1(data):\n res = data['resample']()\n X = np.array([1, 2, 3, 4, 5])\n x = res(X, np.repeat(1, len(X)), 4, p=[0, 0, 1, 0, 0])\n print(x)\n assert np.all(x == [3, 3, 3, 3])\n\n\ndef test_base_smc_1():\n samples = [1, 2, 3, 4, 5]\n beta = np.linspace(0.05, 1, 5)\n\n class SMC(BaseSMC):\n pass\n\n smc = SMC()\n with pytest.raises(NotImplementedError):\n for s in smc(samples, beta=beta):\n assert s\n\n\ndef test_base_smc_2(data):\n class SMC(BaseSMC):\n pass\n\n smc = SMC()\n llh = data['llh']()\n proposer = data['prop']()\n with pytest.raises(TypeError):\n smc._log_likelihood = 1\n smc._log_likelihood = llh\n\n with pytest.raises(TypeError):\n smc._proposal = 1\n smc._proposal = proposer\n\n\ndef test_base_smc_3(data):\n smc = data['smc']()\n\n samples = [1, 2, 100, 4, 5]\n beta = np.linspace(0.05, 1, 5)\n for s, ll, p, f in smc(samples, beta=beta, yield_lpf=True):\n pass\n assert s == 100\n assert np.all(ll == np.array(100))\n assert p == 1.0\n assert f == 5\n\n\ndef test_not_implement():\n base = BaseLogLikelihood()\n with pytest.raises(NotImplementedError):\n base.log_likelihood([1, 2], a=1, b=1)\n\n base = BaseResample()\n with pytest.raises(NotImplementedError):\n base.resample([1, 2], freq=[5, 5], size=10, p=[.5, .5])\n\n base = BaseProposal()\n with pytest.raises(NotImplementedError):\n base.proposal([1, 2])\n\n\nif __name__ == \"__main__\":\n pytest.main()\n","sub_path":"tests/inverse/test_base_inverse.py","file_name":"test_base_inverse.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"401513306","text":"import torch as tc\nfrom PIL import Image\nfrom torchvision import transforms\nfrom MyCNN import CNN\n\n# Load model\ndevice = tc.device('cpu')\nmodel = CNN()\nmodel.load_state_dict(tc.load('./number.pth', map_location=device))\n\n# Load image\n# Should be 28x28 and gray level\n# You may change the path and filename\nimage = Image.open('./5.jpg')\n\ntran = transforms.Compose\\\n ([transforms.ToTensor(),\n transforms.Normalize([0.5], [0.5])])\nimage = tran(image).reshape(1, 1, 28, 28)\n\nif tc.cuda.is_available():\n image = tc.autograd.Variable(image).cuda()\nelse:\n image = tc.autograd.Variable(image)\nout = model(image)\npred = out.data.max(1, keepdim=True)[1].squeeze(1).item()\nprint(pred)\n","sub_path":"recognition.py","file_name":"recognition.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"239327180","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n# 实验数据\nx_data = [338, 333, 328, 207, 226, 25, 179, 60, 208, 606]\ny_data = [640, 633, 619, 393, 428, 27, 193, 66, 226, 1591]\n# y_data = b + w * x_data\n\n\n# bias arange生成包含-200到-100之间整数的数组\nx = np.arange(-200, -100, 1)\n\n# weights 生成-5到5之间的所有数\ny = np.arange(-5, 5, 0.1)\n\nZ = np.zeros((len(x), len(y)))\n\nX, Y = np.meshgrid(x, y)\n\nfor i in range(len(x)):\n for j in range(len(y)):\n b = x[i]\n w = y[j]\n Z[j][i] = 0\n for n in range(len(x_data)):\n Z[j][i] = Z[j][i] + (y_data[n] - b - w * x_data[n]) ** 2\n Z[j][i] = Z[j][i] / len(x_data)\n\nb = -120\nw = -4\nlr = 1\niteration = 100000\n\nb_history = [b]\nw_history = [w]\n\nfor i in range(iteration):\n grad_w = 0\n grad_b = 0\n for j in range(len(x_data)):\n grad_w += 2 * (y_data[j] - (b + w * x_data[j])) * (-x_data[j])\n grad_b += 2 * (y_data[j] - (b + w * x_data[j])) * -1\n\nplt.contourf(x, y, Z, 50, alpha=0.5, cmap=plt.get_cmap('jet'))\nplt.plot(-188.4, [2.67], 'x', ms=12, markeredgewidth=3, color='orange')\nplt.plot(b_history, w_history, 'o-', ms=3, lw=1.5, color='black')\nplt.xlim(-200, -100)\nplt.ylim(-5, 5)\nplt.xlabel(r'$b$', fontsize=23)\nplt.ylabel(r'$w$', fontsize=23)\nplt.show()\n","sub_path":"ml_study/ml_case_1.py","file_name":"ml_case_1.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"621733738","text":"from nEngine.Entities import EntityFactory, World\nfrom nEngine.common.Components import PositionComponent\nfrom nEngine.common.Systems import SimpleMoveSystem\nfrom nEngine.Events import Event \nfrom nEngine.Util import Util\nfrom planet5521.Components import FactionComponent, HarvestableResearchComponent, ResearchHarvestingComponent\nfrom planet5521.Systems import ShootingCombatSystem, EnemyAwarenessSystem, ResearchHarvestingSystem\nfrom planet5521.AI.OrderSystem import BasicAISystem, CommandExecutionSystem\nfrom sfml import Vector2\n\n\"\"\"Factions need to be made configurable. Might also use int IDs for easy comparison (eventually).\"\"\"\n\n\nclass Faction:\n def __init__(self, name, world):\n self.name = name\n self.world = world\n self.enemies = set() # Public! Change this at will!\n self.units = set()\n self.buildings = set()\n \n self.currentUnits = []\n self.currentBuildings = []\n \n def produce(self, unitName, position: Vector2):\n unit = self.world.produce(unitName, position)\n fC = unit.getComponent(FactionComponent)\n fC.factionName = self.name\n fC.faction = self\n if unitName in self.units:\n self.currentUnits.append(unit)\n hC = unit.getComponent(ResearchHarvestingComponent)\n if hC != None:\n unit._em.registerListener(Event.ENTITY_RESEARCH_DUMPED, self.addResearch, [])\n elif unitName in self.buildings:\n self.currentBuildings.append(unit)\n unit._em.registerListener(Event.ENTITY_DIED, self.removeEntityEvent)\n return unit\n \n def removeEntityEvent(self, event):\n self.currentUnits.remove(event.entity)\n \n def addResearch(self, event):\n print(self.name + \" got \" + str(event.amount) + \" research!\")\n\nclass Planet5521World(World):\n \n def __init__(self, width, height, groundLevel = None):\n World.__init__(self)\n self.size = Vector2(width, height)\n if groundLevel == None:\n self.groundLevel = self.size.y - 10\n else:\n self.groundLevel = groundLevel\n \n # Stores dead entities that have harvestable resources\n self.researchSources = []\n \n self.factions = {}\n \n self._infantryUnits = [\"Terran Grunt\", \"Terran Engineer\", \"Insect Warrior\"]\n self._buildings = [\"Terran Barracks\"]\n # Make moddable\n \n # Terrans\n terranFaction = Faction(\"Terrans\", self)\n terranFaction.units.add(\"Terran Grunt\")\n terranFaction.units.add(\"Terran Engineer\")\n terranFaction.buildings.add(\"Terran Barracks\")\n self.factions[\"Terrans\"] = terranFaction\n \n # Insects\n insectFaction = Faction(\"Insects\", self)\n insectFaction.units.add(\"Insect Warrior\")\n self.factions[\"Insects\"] = insectFaction\n \n terranFaction.enemies.add(insectFaction)\n insectFaction.enemies.add(terranFaction)\n \n self.addSystem(SimpleMoveSystem(self))\n self.addSystem(EnemyAwarenessSystem(self))\n self.addSystem(ShootingCombatSystem(self))\n self.addSystem(ResearchHarvestingSystem(self))\n self.addSystem(BasicAISystem(self))\n self.addSystem(CommandExecutionSystem(self))\n \n @property\n def width(self):\n return self.size.x\n \n @property\n def height(self):\n return self.size.y\n \n \n def produce(self, unitName, position: Vector2):\n unit = EntityFactory.getSingleton().produce(self, unitName, True)\n pC = unit.getComponent(PositionComponent)\n if pC != None:\n pC.p = position\n else:\n print(\"[ERROR] Producing \\\"\" + unitName + \"\\\" but cannot find way to set position.\")\n return None\n self.throwEntityCreatedEvent(unit)\n \n unit._em.registerListener(Event.ENTITY_DIED, self.entityDeath)\n unit._em.registerListener(Event.ENTITY_DIED, self.propagateEvent)\n unit._em.registerListener(Event.RESEARCH_DEPLETED, self.researchDepleted)\n unit._em.registerListener(Event.RESEARCH_DEPLETED, self.propagateEvent)\n \n return unit\n\n def propagateEvent(self, event):\n self._em.handleEvent(event)\n\n def researchDepleted(self, event):\n self.researchSources.remove(event.entity)\n\n def entityDeath(self, event):\n # Change it to corpse. Alters the components. A process will take care of\n # actually removing the entity afterwards, after some time.\n entity = event.entity\n componentTypeList = [e for e in entity.getComponentTypeList()]\n \n research = False\n for componentType in componentTypeList:\n if (componentType == HarvestableResearchComponent):\n research = True\n continue\n if (componentType != PositionComponent):\n entity.removeComponent(componentType)\n self.entityUpdatedComponents(entity, componentTypeList)\n \n if research:\n self.researchSources.append(entity)\n \n \n def getClosestUnitFromList(self, p, unitList):\n units = [u for u in unitList if u.getComponent(PositionComponent) != None]\n distFun = lambda other: Util.vectorToDistance(other.getComponent(PositionComponent).p - p)\n return min(units, key=distFun)\n \n def getClosestUnit(self, p, faction = None):\n if faction != None:\n return self.getClosestUnitFromList(p, faction.currentUnits)\n return self.getClosestUnitFromList(p, self._entities)\n \n \n def getUnitsWithinRectangleFromList(self, rect, unitList):\n allUnits = [u for u in unitList if u.getComponent(PositionComponent) != None]\n \n # \"Normalise\" rectangle, or contains doesn't work.\n if rect.width < 0:\n rect.width = -rect.width\n rect.left = rect.left - rect.width\n \n if rect.height < 0:\n rect.height = -rect.height\n rect.top = rect.top - rect.height\n \n filterF = lambda e: rect.contains(e.getComponent(PositionComponent).p)\n return filter(filterF, allUnits)\n \n def getUnitsWithinRectangle(self, rect, faction = None):\n if faction != None:\n return self.getUnitsWithinRectangleFromList(rect, faction.currentUnits)\n return self.getUnitsWithinRectangleFromList(rect, self._entities)\n \n \n \n \n \n \n \n \n ","sub_path":"7drl/planet5521/Planet5521World.py","file_name":"Planet5521World.py","file_ext":"py","file_size_in_byte":5891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"540349917","text":"import sys\nimport os\nimport re\nimport numpy as np\nimport pandas as pd\n\ndef performReplace(lines, replaceDatas):\n\n output = []\n for line in lines:\n print('before' + line)\n for replaceData in replaceDatas:\n className = replaceData[0]\n elementName = replaceData[1]\n japaneseName = replaceData[2]\n searchString = '\"'+ className +'\\\\n'+ elementName +'\"'\n replaceString = '\"'+ className +'\\\\n'+ elementName +'\\\\n'+ japaneseName +'\"'\n line = line.replace(searchString, replaceString)\n\n print('replace:' + line)\n output.append(line)\n\n return output\n\ndef performReplace2(lines, replaceDatas):\n\n output = []\n for line in lines:\n print('before' + line)\n for replaceData in replaceDatas:\n elementName = replaceData[0]\n japaneseName = replaceData[1]\n searchString = '\"'+ elementName +'\"'\n replaceString = '\"'+ elementName +'\\\\n'+ japaneseName +'\"'\n line = line.replace(searchString, replaceString)\n\n print('replace:' + line)\n output.append(line)\n\n return output\n\nif __name__ == '__main__':\n\n df1 = pd.read_csv(\"output81.txt\", sep='\\t', header=None).fillna('')\n df2 = pd.read_csv(\"stateSource.txt\", sep=',', header=None).fillna('')\n\n signalDatas = df1.values.tolist()\n stateDatas = df2.values.tolist()\n\n f = open('output14.txt','r')\n lines = f.readlines()\n f.close\n\n output1 = performReplace(lines, stateDatas)\n output2 = performReplace2(output1, signalDatas)\n\n f = open('output15.txt', 'w')\n for line in output2:\n f.writelines(line)\n f.close()\n\n\n\n\n","sub_path":"11graphvizMake/15addJapanese.py","file_name":"15addJapanese.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"67660530","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('questions', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Answer',\n fields=[\n ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')),\n ('answercontent', models.TextField(max_length=2000)),\n ('create_date', models.DateTimeField(auto_now_add=True)),\n ('update_date', models.DateTimeField(auto_now_add=True)),\n ('votes', models.IntegerField(default=5)),\n ('is_accepted', models.BooleanField(default=False)),\n ('question', models.ForeignKey(to='questions.Question')),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': ('is_accepted', '-votes', 'create_date'),\n 'verbose_name': 'Answer',\n 'verbose_name_plural': 'Answers',\n },\n ),\n ]\n","sub_path":"questions/migrations/0002_answer.py","file_name":"0002_answer.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"30830541","text":"import sys\nsys.setrecursionlimit(10**9)\nINF=10**18\nMOD=10**9+7\ndef input():\n return sys.stdin.readline().rstrip()\n\ndef main():\n A,B=map(int,input().split())\n if B%A==0:\n print(A+B)\n else:\n print(B-A)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python_codes/p03125/s491709671.py","file_name":"s491709671.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"502495256","text":"# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,py\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.9.1+dev\n# kernelspec:\n# display_name: Python [conda env:generic_expression_new]\n# language: python\n# name: conda-env-generic_expression_new-py\n# ---\n\n# # Identify generic genes and pathways\n#\n# Studies have found that some genes are more likely to be differentially expressed even across a wide range of experimental designs. These generic genes and subsequent pathways are not necessarily specific to the biological process being studied but instead represent a more systematic change.\n#\n# This notebook identifies generic genes and pathways and then evaluates if those identified are consistent with published findings.\n#\n# **Steps to identify generic genes:**\n# 1. Simulates N gene expression experiments using [ponyo](https://github.com/ajlee21/ponyo)\n# 2. Perform DE analysis to get association statistics for each gene\n# 3. For each gene, aggregate statsitics across all simulated experiments\n# 4. Rank genes based on this aggregated statistic (i.e. log fold change, or p-value)\n#\n#\n# **Steps to identify generic gene sets (pathways):**\n# 1. Using the same simulated experiments from above, perform GSEA analysis. This analysis will determine whether the genes contained in a gene set are clustered towards the beginning or the end of the ranked list of genes, where genes are ranked by log fold change, indicating a correlation with change in expression.\n# 2. For each gene set (pathway), aggregate statistics across all simulated experiments\n# 3. Rank gene sets based on this aggregated statistic\n#\n# **Evaluation:**\n# * We want to compare the ranking of genes identified using the above method with the ranking found from [Crow et. al.](https://www.pnas.org/content/pnas/116/13/6491.full.pdf), which identified a set of genes as generic based on how frequently they were found to be DE across 600 experiments\n# * We want to compare the ranking of pathways identified using the above method with the ranking based on the [Powers et. al.](https://www.biorxiv.org/content/10.1101/259440v1.full.pdf) data, where ranking was determined based on the fraction of 442 experiments a pathway was found to be enriched\n# * This comparison will validate our method being used as a way to automatically identify generic genes and pathways.\n\n# +\n# %load_ext autoreload\n# %load_ext rpy2.ipython\n# %autoreload 2\n# %matplotlib inline\n\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\nimport pickle\nimport glob\nimport scipy.stats as ss\nfrom keras.models import load_model\nfrom rpy2.robjects import pandas2ri\nfrom ponyo import utils, simulate_expression_data\nfrom generic_expression_patterns_modules import process, stats, ranking\n\npandas2ri.activate()\n\nnp.random.seed(123)\n\n# +\n# Read in config variables\nbase_dir = os.path.abspath(os.path.join(os.getcwd(), \"../\"))\n\nconfig_filename = os.path.abspath(\n os.path.join(base_dir, \"configs\", \"config_human_cancer.tsv\")\n)\n\nparams = utils.read_config(config_filename)\n\n# +\n# Load params\nlocal_dir = params[\"local_dir\"]\ndataset_name = params[\"dataset_name\"]\nNN_architecture = params[\"NN_architecture\"]\nlatent_dim = params[\"latent_dim\"]\nnum_runs = params[\"num_simulated\"]\nproject_id = params[\"project_id\"]\nmetadata_col_id = params[\"metadata_colname\"]\nmapped_template_filename = params[\"mapped_template_filename\"]\nprocessed_template_filename = params[\"processed_template_filename\"]\nnormalized_compendium_filename = params[\"normalized_compendium_filename\"]\nscaler_filename = params[\"scaler_filename\"]\ncol_to_rank_genes = params[\"rank_genes_by\"]\ncol_to_rank_pathways = params[\"rank_pathways_by\"]\nstatistic = params[\"gsea_statistic\"]\nlogFC_name = params[\"DE_logFC_name\"]\npvalue_name = params[\"DE_pvalue_name\"]\n\n# Load metadata file with grouping assignments for samples\nsample_id_metadata_filename = os.path.join(\n base_dir, dataset_name, \"data\", \"metadata\", f\"{project_id}_process_samples.tsv\"\n)\n\n# Load metadata file with grouping assignments for samples\ngrp_metadata_filename = os.path.join(\n base_dir, dataset_name, \"data\", \"metadata\", f\"{project_id}_groups.tsv\"\n)\n\n# Load metadata file with mapping between experiments and associated samples\nmetadata_simulate_filename = os.path.join(\n base_dir, dataset_name, \"data\", \"metadata\", \"all_experiments_sample_annotations.csv\"\n)\nmetadata_delimiter = \",\"\nexperiment_id_colname = \"gse\"\n\n# Load pickled file\nwith open(scaler_filename, \"rb\") as scaler_fh:\n scaler = pickle.load(scaler_fh)\n\n# Percentile threshold to identify generic genes\npercentile_threshold = 80.0\n\n# +\n# Output files\ngene_summary_filename = os.path.join(\n base_dir, dataset_name, f\"generic_gene_summary_{project_id}.tsv\"\n)\n\npathway_summary_filename = os.path.join(\n base_dir, dataset_name, f\"generic_pathway_summary_{project_id}.tsv\"\n)\n# -\n\n# ### Simulate experiments using selected template experiment\n#\n# Workflow:\n# 1. Get the gene expression data for the selected template experiment\n# 2. Encode this experiment into a latent space using the trained VAE model\n# 3. Linearly shift the encoded template experiment in the latent space\n# 4. Decode the samples. This results in a new experiment\n# 5. Repeat steps 1-4 to get multiple simulated experiments\n\n# Simulate multiple experiments\n# This step creates the following files in \"/pseudo_experiment/\" directory:\n# - selected_simulated_data_SRP012656_.txt\n# - selected_simulated_encoded_data_SRP012656_.txt\n# - template_normalized_data_SRP012656_test.txt\n# in which \"\" is an integer in the range of [0, num_runs-1]\nos.makedirs(os.path.join(local_dir, \"pseudo_experiment\"), exist_ok=True)\nsimulate_expression_data.shift_template_experiment(\n normalized_compendium_filename,\n NN_architecture,\n latent_dim,\n dataset_name,\n scaler,\n metadata_simulate_filename,\n metadata_delimiter,\n experiment_id_colname,\n metadata_col_id,\n project_id,\n local_dir,\n base_dir,\n num_runs,\n)\n\n# ### Process template and simulated experiments\n#\n# * Remove samples not required for comparison. Since this experiment contains multiple conditions (i.e. estradiol vs EtOH at 12, 24, and 48 hrs are each considered a different comparison) being tested, we will only include those samples within the same condition.\n# * Make sure ordering of samples matches metadata for proper comparison\n\n# +\nif not os.path.exists(sample_id_metadata_filename):\n sample_id_metadata_filename = None\n\nstats.process_samples_for_limma(\n mapped_template_filename,\n grp_metadata_filename,\n processed_template_filename,\n sample_id_metadata_filename,\n)\n\nfor i in range(num_runs):\n simulated_filename = os.path.join(\n local_dir, \"pseudo_experiment\", f\"selected_simulated_data_{project_id}_{i}.txt\"\n )\n out_simulated_filename = os.path.join(\n local_dir,\n \"pseudo_experiment\",\n f\"selected_simulated_data_{project_id}_{i}_processed.txt\",\n )\n stats.process_samples_for_limma(\n simulated_filename,\n grp_metadata_filename,\n out_simulated_filename,\n sample_id_metadata_filename,\n )\n# -\n\n# ### Differential expression analysis\n#\n# The gene expression dataset is array-based so we will use Limma in this case\n\n# Create subdirectory: \"/DE_stats/\"\nos.makedirs(os.path.join(local_dir, \"DE_stats\"), exist_ok=True)\n\n# + magic_args=\"-i grp_metadata_filename -i project_id -i processed_template_filename -i local_dir -i base_dir\" language=\"R\"\n#\n# source(paste0(base_dir, '/generic_expression_patterns_modules/DE_analysis.R'))\n#\n# # File created: \"/DE_stats/DE_stats_template_data_SRP012656_real.txt\"\n# get_DE_stats_limma(grp_metadata_filename,\n# project_id,\n# processed_template_filename,\n# \"template\",\n# local_dir,\n# \"real\")\n\n# +\n# Check number of DEGs\ntemplate_DE_stats_filename = os.path.join(\n local_dir, \"DE_stats\", f\"DE_stats_template_data_{project_id}_real.txt\"\n)\n\ntemplate_DE_stats = pd.read_csv(\n template_DE_stats_filename, sep=\"\\t\", header=0, index_col=0\n)\n\nselected = template_DE_stats[\n (template_DE_stats[\"adj.P.Val\"] < 0.05) & (abs(template_DE_stats[\"logFC\"]) > 1)\n]\nprint(selected.shape)\n\n# + magic_args=\"-i grp_metadata_filename -i project_id -i base_dir -i local_dir -i num_runs\" language=\"R\"\n#\n# source(paste0(base_dir, '/generic_expression_patterns_modules/DE_analysis.R'))\n#\n# # Files created: \"/DE_stats/DE_stats_simulated_data_SRP012656_.txt\"\n# for (i in 0:(num_runs-1)){\n# simulated_data_filename <- paste(local_dir,\n# \"pseudo_experiment/selected_simulated_data_\",\n# project_id,\n# \"_\",\n# i,\n# \"_processed.txt\",\n# sep = \"\")\n#\n# get_DE_stats_limma(grp_metadata_filename,\n# project_id,\n# simulated_data_filename,\n# \"simulated\",\n# local_dir,\n# i)\n# }\n# -\n\n# ### Rank genes\n\nanalysis_type = \"DE\"\ntemplate_DE_stats, simulated_DE_summary_stats = ranking.process_and_rank_genes_pathways(\n template_DE_stats_filename,\n local_dir,\n num_runs,\n project_id,\n analysis_type,\n col_to_rank_genes,\n logFC_name,\n pvalue_name,\n)\n\n# ### Gene summary table\n\n# +\nsummary_gene_ranks = ranking.generate_summary_table(\n template_DE_stats_filename,\n template_DE_stats,\n simulated_DE_summary_stats,\n col_to_rank_genes,\n local_dir,\n \"gene\",\n params,\n)\n\nsummary_gene_ranks.head()\n# -\n\n# Check if there is an NaN values, there should not be\nsummary_gene_ranks.isna().any()\n\n# Create `gene_summary_fielname`\nsummary_gene_ranks.to_csv(gene_summary_filename, sep=\"\\t\")\n\n# ### Compare gene ranking\n# Studies have found that some genes are more likely to be differentially expressed even across a wide range of experimental designs. These *generic genes* are not necessarily specific to the biological process being studied but instead represent a more systematic change.\n#\n# We want to compare the ability to detect these generic genes using our method vs those found by [Crow et. al. publication](https://www.pnas.org/content/pnas/116/13/6491.full.pdf). Their genes are ranked 0 = not commonly DE; 1 = commonly DE. Genes were ranked by the number differentially expressed gene sets a gene appeared in across 600 experiments.\n\n# +\n# Get generic genes identified by Crow et. al.\nDE_prior_filename = params[\"reference_gene_filename\"]\nref_gene_col = params[\"reference_gene_name_col\"]\nref_rank_col = params[\"reference_rank_col\"]\n\nfigure_filename = f\"gene_ranking_{col_to_rank_genes}.svg\"\n\ncorr, shared_ranking = ranking.compare_gene_ranking(\n summary_gene_ranks, DE_prior_filename, ref_gene_col, ref_rank_col, figure_filename\n)\n# -\n\n# Hypergeometric test:\n#\n# Given $N$ number of genes with $K$ common genes in Crow et al. SOPHIE identifies $n$ genes as being common. What is the probability that $k$ of the genes identified by SOPHIE are also common in Crow et al.? What is the probability of drawing $k$ or more concordant genes?\n#\n# This was a way for us to quantify the correlation between SOPHIE and Crow et al common findings, since the correlation coefficient wasn't very convincing since we're considering all genes in addition to the common ones\n\nnum_Crow_genes = shared_ranking.shape[0]\nnum_generic_Crow_genes = shared_ranking.query(f\"{ref_rank_col}>=80.0\").shape[0]\nnum_generic_SOPHIE_genes = shared_ranking[\n shared_ranking[\"Percentile (simulated)\"] >= percentile_threshold\n].shape[0]\nnum_concordant_generic_genes = shared_ranking[\n (shared_ranking[ref_rank_col] >= percentile_threshold)\n & (shared_ranking[\"Percentile (simulated)\"] >= percentile_threshold)\n].shape[0]\n\nprint(num_Crow_genes)\nprint(num_generic_Crow_genes)\nprint(num_generic_SOPHIE_genes)\nprint(num_concordant_generic_genes)\n\np = ss.hypergeom.sf(\n num_concordant_generic_genes,\n num_Crow_genes,\n num_generic_Crow_genes,\n num_generic_SOPHIE_genes,\n)\nprint(p)\n\n# **Takeaway:**\n# * Here we are comparing gene percentiles obtained from a SOPHIE trained on Powers et al. vs gene percentiles obtained from manual curation using Crow et al. The plot shows that there is a high correlation between those very high and low ranked genes -- high correlation at the extremes but there is a lot of noise in the middle.\n# * While the two datasets used the same array platform to generate data, the datasets have different compositions – Crow et al. is a heterogenous mixture of different types of experiments while Power et al. is specifically cancer cell lines treated with small molecules. The consistency we observe in the common DEGs despite the differences in context demonstrates that many common DEGs are differentially expressed regardless of the context.\n\n# ### GSEA\n# **Goal:** To detect modest but coordinated changes in prespecified sets of related genes (i.e. those genes in the same pathway or share the same GO term).\n#\n# 1. Rank all genes using DE association statistics.\n# 2. An enrichment score (ES) is defined as the maximum distance from the middle of the ranked list. Thus, the enrichment score indicates whether the genes contained in a gene set are clustered towards the beginning or the end of the ranked list (indicating a correlation with change in expression).\n# 3. Estimate the statistical significance of the ES by a phenotypic-based permutation test in order to produce a null distribution for the ES (i.e. scores based on permuted phenotype)\n\n# Create \"/GSEA_stats/\" subdirectory\nos.makedirs(os.path.join(local_dir, \"GSA_stats\"), exist_ok=True)\n\n# Load pathway data\nhallmark_DB_filename = params[\"pathway_DB_filename\"]\n\n# + magic_args=\"-i base_dir -i template_DE_stats_filename -i hallmark_DB_filename -i statistic -i local_dir -o template_enriched_pathways\" language=\"R\"\n#\n# source(paste0(base_dir, '/generic_expression_patterns_modules/GSEA_analysis.R'))\n#\n# out_filename <- paste(local_dir,\n# \"GSA_stats/GSEA_stats_template_data_\",\n# project_id,\n# \"_real.txt\",\n# sep = \"\")\n#\n# template_enriched_pathways <- find_enriched_pathways(template_DE_stats_filename, hallmark_DB_filename, statistic)\n# template_enriched_pathways <- as.data.frame(template_enriched_pathways[1:7])\n#\n# write.table(template_enriched_pathways, file = out_filename, row.names = F, sep = \"\\t\")\n# -\n\nprint(template_enriched_pathways.shape)\ntemplate_enriched_pathways[template_enriched_pathways[\"padj\"] < 0.05].sort_values(\n by=\"padj\"\n)\n\n# **Quick check:** Looks like enriched pathways are consistent with estradiol being estrogen hormone treatment.\n\n# + magic_args=\"-i project_id -i local_dir -i hallmark_DB_filename -i num_runs -i statistic -i base_dir\" language=\"R\"\n#\n# source(paste0(base_dir, '/generic_expression_patterns_modules/GSEA_analysis.R'))\n#\n# # New files created: \"/GSEA_stats/GSEA_stats_simulated_data__.txt\"\n# for (i in 0:(num_runs-1)) {\n# simulated_DE_stats_filename <- paste(local_dir,\n# \"DE_stats/DE_stats_simulated_data_\",\n# project_id,\n# \"_\",\n# i,\n# \".txt\",\n# sep = \"\")\n#\n# out_filename <- paste(local_dir,\n# \"GSA_stats/GSEA_stats_simulated_data_\",\n# project_id,\n# \"_\",\n# i,\n# \".txt\",\n# sep = \"\")\n#\n# enriched_pathways <- find_enriched_pathways(simulated_DE_stats_filename, hallmark_DB_filename, statistic)\n#\n# write.table(as.data.frame(enriched_pathways[1:7]), file = out_filename, row.names = F, sep = \"\\t\")\n# }\n# -\n\n# ### Rank pathways\n\nanalysis_type = \"GSA\"\ntemplate_GSEA_stats_filename = os.path.join(\n local_dir, \"GSA_stats\", f\"GSEA_stats_template_data_{project_id}_real.txt\"\n)\n(\n template_GSEA_stats,\n simulated_GSEA_summary_stats,\n) = ranking.process_and_rank_genes_pathways(\n template_GSEA_stats_filename,\n local_dir,\n num_runs,\n project_id,\n analysis_type,\n col_to_rank_pathways,\n logFC_name,\n pvalue_name,\n \"GSEA\",\n)\n\n# ### Pathway summary table\n\n# +\n# Create intermediate file: \"/gene_summary_table_.tsv\"\nsummary_pathway_ranks = ranking.generate_summary_table(\n template_GSEA_stats_filename,\n template_GSEA_stats,\n simulated_GSEA_summary_stats,\n col_to_rank_pathways,\n local_dir,\n \"pathway\",\n params,\n)\n\nsummary_pathway_ranks.sort_values(by=\"Rank (simulated)\", ascending=False).head(10)\n# -\n\n# Create `pathway_summary_filename`\nsummary_pathway_ranks.to_csv(pathway_summary_filename, sep=\"\\t\")\n\n# ### Compare pathway ranking\n\n# Studies have found that there are some pathways (gene sets) that are more likely to be significantly enriched in DEGs across a wide range of experimental designs. These generic pathways are not necessarily specific to the biological process being studied but instead represents a more systematic change.\n#\n# We want to compare the ability to detect these generic pathways using our method vs those found by [Powers et. al.](https://www.biorxiv.org/content/10.1101/259440v1.full.pdf) publication. We will use the `Hallmarks_qvalues_GSEAPreranked.csv` file from https://www.synapse.org/#!Synapse:syn11806255 as a reference. The file contains the q-value (adjusted p-value) for the test: given the enrichment score (ES) of the experiment is significant compared to the null distribution of enrichment scores, where the null set is generated from permuted gene sets. For each gene set (pathway) they calculate the q-value using this test.\n#\n#\n# To get a `reference ranking`, we calculate the fraction of experiments that a given pathway was significant (q-value <0.05) and use this rank pathways. `Our ranking` is to rank pathways based on the median q-value across the simulated experiments. We can then compare `our ranking` versus the `reference ranking.`\n\n# Load Powers et. al. results file\npowers_rank_filename = os.path.join(\n base_dir, dataset_name, \"data\", \"metadata\", \"Hallmarks_qvalues_GSEAPreranked.csv\"\n)\n\n# Read Powers et. al. data\n# This file contains qvalue results for hallmark pathways across ~400 experiments\npowers_rank_df = pd.read_csv(powers_rank_filename, header=0, index_col=0)\npowers_rank_df.drop([\"Category\"], axis=1, inplace=True)\nprint(powers_rank_df.shape)\npowers_rank_df.head()\n\n# +\n# Count the number of experiments where a given pathway was found to be enriched (qvalue < 0.05)\ntotal_num_experiments = powers_rank_df.shape[1]\nfrac_enriched_pathways = (powers_rank_df < 0.05).sum(axis=1) / total_num_experiments\n\n# Rank pathways from 0-50, 50 indicating that the pathways was frequently enriched\npathway_ranks = frac_enriched_pathways.rank()\n\npowers_rank_stats_df = pd.DataFrame(\n data={\n \"Fraction enriched\": frac_enriched_pathways.values,\n \"Powers Rank\": pathway_ranks.values,\n },\n index=powers_rank_df.index,\n)\npowers_rank_stats_df.sort_values(by=\"Powers Rank\", ascending=False).head()\n\n# +\n# Save reference file for input into comparison\npowers_rank_processed_filename = os.path.join(\n base_dir,\n dataset_name,\n \"data\",\n \"metadata\",\n \"Hallmarks_qvalues_GSEAPreranked_processed.tsv\",\n)\n\npowers_rank_stats_df.to_csv(\n powers_rank_processed_filename,\n sep=\"\\t\",\n)\n\n# +\nfigure_filename = f\"pathway_ranking_{col_to_rank_pathways}.svg\"\n\nranking.compare_pathway_ranking(\n summary_pathway_ranks, powers_rank_processed_filename, figure_filename\n)\n# -\n\n# **Takeaway:**\n# * Our method ranked pathways using median adjusted p-value score across simulated experiments.\n# * Powers et. al. ranked pathways based on the fraction of experiments they had adjusted p-value < 0.05.\n# * Here we validated that our analysis pipeline is working correctly by comparing pathway ranks obtained from a (Powers et. al.)-trained VAE model vs pathway ranking based on manual curation using Powers et. al datasets. We expect to see a high correlation between pathway ranks given that we are using the same training dataset. Indeed that is what we find.\n","sub_path":"human_cancer_analysis/2_identify_generic_genes_pathways.py","file_name":"2_identify_generic_genes_pathways.py","file_ext":"py","file_size_in_byte":20582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"307516129","text":"from django.shortcuts import render, redirect, reverse, get_object_or_404\nfrom django.contrib import messages\nfrom django.conf import settings\n\nfrom .forms import OrderForm\nfrom gadgets.models import gadgetAttr\nfrom .models import OrderDetail, OrderLineItem\nfrom cart.contexts import cartItems\n\nimport stripe\n\n\ndef checkout(request):\n stripe_public_key = settings.STRIPE_PUBLIC_KEY\n stripe_secret_key = settings.STRIPE_SECRET_KEY\n\n if request.method == 'POST':\n cart = request.session.get('cart', {})\n\n form_data = {\n 'cust_name': request.POST['cust_name'],\n 'email_id': request.POST['email_id'],\n 'contact_number': request.POST['contact_number'],\n 'address1': request.POST['address1'],\n 'address2': request.POST['address2'],\n 'town_or_city': request.POST['town_or_city'],\n 'postcode': request.POST['postcode'],\n 'country': request.POST['country'],\n 'county': request.POST['county']\n }\n order_form = OrderForm(form_data)\n if order_form.is_valid():\n order_form.save()\n for item_id, quantity in cart.items():\n try:\n product = gadgetAttr.objects.get(asins=item_id)\n order_line_item = OrderLineItem(\n order=order,\n product=product,\n quantity=quantity\n )\n order_line_item.save()\n\n except gadgetAttr.DoesNotExist:\n messages.error(request, 'Item not found in database')\n order.delete()\n return redirect(reverse('viewCart'))\n \n request.session['save-info'] = 'save-info' in request.POST\n return redirect(reverse('checkout_success',\n args=[order.order_number]))\n else:\n cart = request.session.get('cart', {})\n if not cart:\n messages.error(request, \"Your shopping cart is empty\")\n return redirect(reverse, 'gadgets')\n\n cart_present = cartItems(request)\n total = cart_present['grand_total']\n stripe_total = round(total * 100)\n stripe.api_key = stripe_secret_key\n intent = stripe.PaymentIntent.create(\n amount=stripe_total,\n currency=settings.STRIPE_CURRENCY\n )\n\n order_form = OrderForm()\n template = 'checkout/checkout.html'\n context = {\n 'order_form': order_form,\n 'stripe_public_key': stripe_public_key,\n 'client_secret': intent.client_secret\n }\n\n return render(request, template, context)\n\n\ndef checkout_success(request, order_number):\n save_info = request.session.get('save_info')\n order = get_object_or_404(OrderDetail, order_number=order_number)\n messages.success(request, f'Order {order_number} created succesfully. \\\n A confirmation email will be sent to {order.email}')\n \n if 'cart' in request.session:\n del request.session['cart']\n \n template = 'checkout/checkout_success.html'\n\n context = {\n 'order': order\n }\n\n return render(request, template, context)\n","sub_path":"checkout/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"248179935","text":"#!/usr/bin/env python\n\n# Analysis\nfrom Analysis.TMVA.Trainer import Trainer\nfrom Analysis.TMVA.Reader import Reader\nfrom Analysis.TMVA.defaults import default_methods, default_factory_settings \nimport Analysis.Tools.syncer\n\n# TopEFT\nfrom tWZ.Tools.user import plot_directory, mva_directory\nfrom tWZ.Tools.cutInterpreter import cutInterpreter\n\n# MVA configuration\nfrom tWZ.MVA.MVA_TWZ_3l import sequence, read_variables, mva_variables, all_mva_variables \nfrom tWZ.MVA.MVA_TWZ_3l import * \n\nimport argparse\nargParser = argparse.ArgumentParser(description = \"Argument parser\")\nargParser.add_argument('--plot_directory', action='store', default=None)\nargParser.add_argument('--selection', action='store', type=str, default='trilepM-onZ1')\nargParser.add_argument('--trainingFraction', action='store', type=float, default=0.5)\nargParser.add_argument('--small', action='store_true')\nargParser.add_argument('--overwrite', action='store_true')\n\nargs = argParser.parse_args()\n\n#Logger\nimport tWZ.Tools.logger as logger\nlogger = logger.get_logger(\"INFO\", logFile = None )\nimport Analysis.Tools.logger as logger_an\nlogger_an = logger_an.get_logger(\"INFO\", logFile = None )\n\nif args.plot_directory == None:\n args.plot_directory = plot_directory\n\nif args.selection == None:\n selectionString = \"(1)\"\nelse:\n selectionString = cutInterpreter.cutString( args.selection )\n\n# Samples\n#from tWZ.samples.nanoTuples_RunII_nanoAODv6_private_postProcessed import *\nfrom tWZ.samples.nanoTuples_Summer16_nanoAODv6_private_postProcessed import *\n\nsignal = TWZ_NLO_DR \n#signal.reduceFiles(factor=20)\n#TTZ.reduceFiles(factor=3)\n\n# TTZ\nbackgrounds = [ TTZ ]\n\nsamples = backgrounds + [signal]\nfor sample in samples:\n sample.setSelectionString( selectionString )\n if args.small:\n sample.reduceFiles(to = 1)\n\nmvas = [ all_mlp_np40 ] #all_mlp_np5s0c3e0c5, all_mlp_ncnc1s0c3e0c5 ]\n# all_mlp_ncnp5c1s0c3e0c5, all_mlp_ncnp5c1s0c5e1, all_mlp_ncnp5c1s0c5e0c8, all_mlp_np20, all_mlp_np30, all_mlp_np40, all_mlp_oldconfig_ncnp5c1s0c3e0c5, all_mlp_oldconfig_ncnp5c1s0c3e0c3, all_mlp_oldconfig_np7s0c3e0c8, all_mlp_oldconfig_np7c1s0c5e0c5 ]\n\n## TMVA Trainer instance\ntrainer = Trainer( \n signal = signal, \n backgrounds = backgrounds, \n output_directory = mva_directory, \n mva_variables = mva_variables,\n label = \"TWZ_3l\", \n fractionTraining = args.trainingFraction, \n )\n\nweightString = \"(1)\"\ntrainer.createTestAndTrainingSample( \n read_variables = read_variables, \n sequence = sequence,\n weightString = weightString,\n overwrite = args.overwrite,\n mva_variables = all_mva_variables \n )\n\n#trainer.addMethod(method = default_methods[\"BDT\"])\n#trainer.addMethod(method = default_methods[\"MLP\"])\n\nfor mva in mvas:\n trainer.addMethod(method = mva)\n\ntrainer.trainMVA( factory_settings = default_factory_settings )\n#trainer.plotEvaluation(plot_directory = os.path.join( plot_directory, \"MVA\", \"TWZ_3l_all\") )\ntrainer.plotEvaluation(plot_directory = os.path.join( plot_directory, \"MVA\", \"TWZ_3l_allVars\") )\n\n#reader.addMethod(method = bdt1)\n#reader.addMethod(method = default_methods[\"MLP\"])\n\n#print reader.evaluate(\"BDT\", met_pt=100, ht=-210, Z1_pt_4l=100, lnonZ1_pt=100, lnonZ1_eta=0)\n#prinMt reader.evaluate(\"BDT\", met_pt=120, ht=-210)\n","sub_path":"MVA/python/old/train_TWZ_3l.py","file_name":"train_TWZ_3l.py","file_ext":"py","file_size_in_byte":3407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"380209377","text":"try:\n from collections import OrderedDict\nexcept ImportError:\n from ordereddict import OrderedDict\n\nfrom itertools import chain\n\nfrom django.forms.models import ModelForm, ModelFormMetaclass,\\\n BaseInlineFormSet, BaseModelFormSet\n\nfrom django.forms.util import ErrorList\nfrom django.forms.widgets import Media\n\n\nclass NestedModelFormOptions(object):\n def __init__(self, options=None):\n if options is None:\n return\n\n formsets = getattr(options, 'formsets', {})\n if isinstance(formsets, dict):\n # Support dicts for backward-compatibility reasons.\n # Order will be undefined, unless it is an OrderedDict.\n formsets = formsets.items()\n\n elif not isinstance(formsets, (list, tuple)):\n # Otherwise, it must be a list or tuple of (name, FormsetClass)\n raise ValueError('NestedMeta.formsets must be an list or tuple of '\n '\"(name, FormSet)\" tuples')\n self.formsets = formsets\n self.formsets_querysets = getattr(options, 'formsets_querysets', {})\n\n related_forms = getattr(options, 'related_forms', ())\n if not isinstance(related_forms, (list, tuple)):\n # Otherwise, it must be a list or tuple of (name, FormsetClass)\n raise ValueError('NestedMeta.related_forms must be an list or '\n 'tuple of \"(name, RelatedForm)\" tuples')\n self.related_forms = related_forms\n self.related_forms_instance = getattr(options, 'related_forms_instance', {})\n\n\nclass NestedModelFormMetaclass(ModelFormMetaclass):\n def __new__(cls, name, bases, attrs):\n new_class = super(NestedModelFormMetaclass, cls).__new__(\n cls, name, bases, attrs)\n\n base_options = getattr(new_class, 'NestedMeta', None)\n new_class._nested_meta = NestedModelFormOptions(base_options)\n\n return new_class\n\n\nclass NestedModelForm(ModelForm):\n\n __metaclass__ = NestedModelFormMetaclass\n\n def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,\n initial=None, formset_extra={}, related_form_extra={},\n error_class=ErrorList,\n label_suffix=':', empty_permitted=False, instance=None):\n\n super(NestedModelForm, self).__init__(\n data, files, auto_id, prefix, initial, error_class, label_suffix,\n empty_permitted, instance)\n\n # `self.data != data` after running __init__, so we must pass it in\n self.formsets = self._init_formsets(data, files, formset_extra)\n self.related_forms = self._init_related_forms(data, files,\n related_form_extra)\n\n def _get_media(self):\n media_bits = chain(\n [super(NestedModelForm, self).media],\n (f.media for f in self.formsets.values()),\n (f.media for f in self.related_forms.values()))\n return sum(media_bits, Media())\n media = property(_get_media)\n\n @property\n def subforms(self):\n return OrderedDict(chain(self.formsets.iteritems(),\n self.related_forms.iteritems()))\n\n def _init_formsets(self, data, files, extra):\n formsets = self._nested_meta.formsets\n prefix = (self.prefix + '_') if self.prefix is not None else ''\n\n def make_formset(name, FormSet):\n kwargs = {\n 'data': data,\n 'files': files,\n 'instance': self.instance,\n 'prefix': prefix + name,\n }\n\n if name in self._nested_meta.formsets_querysets.keys():\n props = self._nested_meta.formsets_querysets.get(name)\n queryset_method = props.get('queryset')\n qs_args = props.get('args', [])\n qs_kwargs = props.get('kwargs', {})\n\n qs_args = map(lambda arg: kwargs.get(arg), qs_args)\n\n qs = queryset_method(*qs_args, **qs_kwargs)\n\n kwargs.update({\n 'queryset': qs\n })\n\n if issubclass(FormSet, BaseModelFormSet):\n del kwargs['instance']\n\n kwargs.update(extra.get(name, {}))\n return (name, FormSet(**kwargs))\n\n return OrderedDict(make_formset(name, FormSet)\n for name, FormSet in formsets)\n\n def _init_related_forms(self, data, files, extra):\n related_forms = self._nested_meta.related_forms\n prefix = (self.prefix + '_') if self.prefix is not None else ''\n\n def make_related_form(name, RelatedForm):\n if name in self._nested_meta.related_forms_instance.keys():\n gettr = self._nested_meta.related_forms_instance.get(name).get('getattr')\n instance = gettr(self.instance)\n else:\n instance = self.instance\n\n kwargs = {\n 'data': data,\n 'files': files,\n 'instance': instance,\n 'prefix': prefix + name,\n }\n kwargs.update(extra.get(name, {}))\n return (name, RelatedForm(**kwargs))\n\n return OrderedDict(make_related_form(name, RelatedForm)\n for name, RelatedForm in related_forms)\n\n def is_valid(self):\n is_valid = super(NestedModelForm, self).is_valid()\n\n for name, subform in self.subforms.items():\n is_valid = subform.is_valid() and is_valid\n\n return is_valid\n\n def _get_formset_errors(self):\n if self._formset_errors is None:\n self.full_clean()\n return self._formset_errors\n formset_errors = property(_get_formset_errors)\n\n def _get_related_form_errors(self):\n if self._related_form_errors is None:\n self.full_clean()\n return self._related_form_errors\n related_form_errors = property(_get_related_form_errors)\n\n def full_clean(self):\n super(NestedModelForm, self).full_clean()\n\n self._formset_errors = {}\n for name, formset in self.formsets.items():\n if any(formset.errors):\n self._formset_errors[name] = formset.errors\n\n self._related_form_errors = {}\n for name, related_form in self.related_forms.items():\n if any(related_form.errors):\n self._related_form_errors[name] = related_form.errors\n\n if self.is_bound:\n self.post_subform_clean()\n\n def post_subform_clean(self):\n \"\"\" A hook for subclasses that wish to do some extra `clean()` work,\n but after the subforms have all been `clean()`ed as well.\n \"\"\"\n pass\n\n def save(self, commit=True):\n\n # Prepare the instance for saving\n instance = super(NestedModelForm, self).save(commit=False)\n\n # Prepare the formsets for saving\n formset_instances = {}\n for name, formset in self.formsets.items():\n formset_instances[name] = (formset, formset.save(commit=False))\n\n # Prepare related forms for saving\n related_instances = {}\n for name, form in self.related_forms.items():\n related_instances[name] = (form, form.save(commit=False))\n\n # The subforms copy the instance when they are created, so they do\n # not know that this instance has just gotten a nice shiny new primary\n # key (if this is a create form, not an edit form). As such, we need to\n # loop through and tell all the related instances about our updated top\n # level instance\n def save_formsets():\n for formset, subinstances in formset_instances.values():\n fk_name = formset.fk.name\n for subinstance in subinstances:\n setattr(subinstance, fk_name, instance)\n subinstance.save()\n formset.save_m2m()\n\n def save_related_forms():\n for form, subinstance in related_instances.values():\n # The subinstance could be None, if the form was empty or the\n # instance was delete.\n if subinstance is not None:\n fk_name = form._related_meta.fk.name\n setattr(subinstance, fk_name, instance)\n subinstance.save()\n form.save_m2m()\n\n def save_subforms():\n save_formsets()\n save_related_forms()\n\n if commit:\n # Just save everything using the above helpers.\n instance.save()\n save_subforms()\n self.save_m2m()\n\n else:\n # if you pass `commit=False`, you have to save the formset\n # instances yourself. This helper should help. Simply call\n # `form.save_subforms()` after you call `instance.save()`\n # Just like normal forms, if you use `commit=False` you must call\n # `form.save_m2m()` when you have saved the form and all its\n # subforms.\n self.save_formsets = save_formsets\n self.save_related_forms = save_related_forms\n self.save_subforms = save_subforms\n\n instances = lambda d: dict((k, v[1]) for k, v in d.iteritems())\n self.formset_instances = instances(formset_instances)\n self.related_instances = instances(related_instances)\n\n return instance\n\n","sub_path":"nestedformsets/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":9359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"64353359","text":"\"\"\"This module contains the DownloadThread class which creates the\nthread used to manage the download of the selected video without hanging\nthe main interface.\n\"\"\"\n\nimport urllib.request\nfrom PyQt4.QtCore import pyqtSignal, QObject, pyqtSlot\n\n\nclass Downloader(QObject):\n \"\"\"A class to create a 'downloader' object meant to be run in a\n separate QThread. The entry point is the 'start_process' method. The\n class also contains two signals:\n\n reportInfo: carries an int and is emitted on download progress\n finished: emitted when download is finished.\n \"\"\"\n reportInfo = pyqtSignal(int)\n finished = pyqtSignal()\n\n def __init__(self, video_url, video_title):\n super().__init__()\n self.video_url = video_url\n self.video_title = video_title + '.mp4'\n self.exiting = False\n\n def _report(self, blocknum, blocksize, totalsize):\n \"\"\"Report hook for the download, emits a signal with downloaded\n percentage value.\n \"\"\"\n readsofar = blocknum * blocksize\n if totalsize > 0:\n percentage = readsofar * 100 / totalsize\n self.reportInfo.emit(percentage)\n\n @pyqtSlot()\n def start_process(self):\n \"\"\"Entry point and slot for the object, manages the download.\"\"\"\n block_size = 4096\n written_data = 0\n blocks_counter = 0\n\n with urllib.request.urlopen(self.video_url) as temp:\n headers = temp.info()\n totalsize = int(headers['Content-Length'])\n with open(self.video_title, 'wb') as file_to_write:\n while written_data < totalsize and self.exiting is False:\n file_to_write.write(temp.read(block_size))\n written_data += block_size\n blocks_counter += 1\n self._report(blocks_counter, block_size, totalsize)\n self.finished.emit()\n","sub_path":"phscanner/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"228391774","text":"#!/usr/bin/env python\n\n# general python packages\nimport os.path\nimport numpy as np\n\n# modules in RNAvigate\nfrom .data import Data, PDB, Log\nfrom .data import Annotation, Motif, ORFs\nfrom .data import CT, DotBracket, XRNA, VARNA, NSD, CTE, get_ss_class\nfrom .data import Interactions, RINGMaP, PAIRMaP, PairProb, SHAPEJuMP\nfrom .data import Profile, SHAPEMaP, DanceMaP, RNPMaP\nfrom .plots import AP, Circle, DistHist, Heatmap, LinReg, Mol\nfrom .plots import QC, Skyline, SM, SS\nfrom .analysis import LogCompare, LowSS\n\n\ndef create_code_button():\n from IPython.display import display, HTML\n display(HTML('''\n
\n \n
'''))\n\n\ndef get_color_list(length, default, color_regions):\n c_list = np.full(length, default, dtype=' ')\n s.sendto(send_text.encode('utf8'), (ip, port))\n # print(s.recv(1024).decode('utf8'))\n if send_text.lower() == 'bey':\n print('服务器已关闭')\n break\n\ns.close()","sub_path":"ComputerAndNetwork/Languages/Python/Socket编程/UDP_Client.py","file_name":"UDP_Client.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"131594968","text":"# Diogo Daniel Soares Ferreira\n# IIA, 2016/2017\n# diogodanielsoaresferreira@ua.pt\n# Aula pratica 2\n\nimport math\nfrom functools import reduce\n\n###################################### IV ##############################\n\nimpar = (lambda x: x%2==1)\n#print(impar(1))\n\npositive = (lambda x: x>0)\n#print(positive(-1))\n\ntwo_n = (lambda x,y: abs(x)y else x, [1,2,3,4,5,-1]))\n#ou\ndef ex9(lst, b):\n return reduce(lambda m,x: m if b(m,x) else x, lst)\n\n#print(ex9([1,2,6,9,-4],lambda x,y: xlist_in[1]:\n\t\treturn False\n\n\treturn is_sorted(list_in[1:])\n\n\ndef selection_sort(list_in):\n\n\tif list_in == []:\n\t\treturn []\n\n\tsmallest = reduce(lambda x,y: x if xlist_in[i+1]:\n\t\t\tlist_in[i+1], list_in[i] = list_in[i], list_in[i+1]\n\n\treturn bubble_sort(list_in[:-1])+[list_in[-1]]\n\n\n#print(bubble_sort(list_1))\n#print(is_sorted(bubble_sort(list_1)))\n\n\ndef quick_sort(list_in):\n\n\tif len(list_in)<=1:\n\t\treturn list_in\n\n\tpivot = list_in[0]\n\n\tprev = [p for p in list_in[1:] if p= pivot]\n\n\treturn quick_sort(prev)+[pivot]+quick_sort(nxt)\n\n\n#print(quick_sort(list_1))\n\nrelation = lambda x,y: True if x<=y else False\n\n\ndef is_sorted_2(list_in, relation):\n\t\n\tif list_in == []:\n\t\treturn True\n\n\telif len(list_in)<2:\n\t\treturn True\n\n\tif not relation(list_in[0], list_in[1]):\n\t\treturn False\n\n\treturn is_sorted_2(list_in[1:], relation)\n\n\ndef selection_sort_2(list_in, relation):\n\n\tif list_in == []:\n\t\treturn []\n\n\tsmallest = reduce(lambda x,y: x if relation(x,y) else y, list_in)\n\tidx = list_in.index(smallest)\n\tlist_in[0], list_in[idx] = list_in[idx], list_in[0]\n\treturn [list_in[0]]+selection_sort_2(list_in[1:], relation)\n\n#print(selection_sort_2(list_1, relation))\n\n\ndef bubble_sort2(list_in, relation):\n\tif is_sorted_2(list_in, relation):\n\t\treturn list_in\n\n\tlist_in = list_in[:]\n\n\tfor i in range(len(list_in)-1):\n\t\tif not relation(list_in[i], list_in[i+1]):\n\t\t\tlist_in[i], list_in[i+1] = list_in[i+1], list_in[i]\n\n\treturn bubble_sort2(list_in[:-1], relation)+[list_in[-1]]\n\n#print(bubble_sort2(list_1, relation))\n\n\ndef quick_sort2(relation, list_in):\n\tif len(list_in)<=1:\n\t\treturn list_in\n\n\tpivot = list_in[0]\n\n\tprev = [p for p in list_in[1:] if relation(p,pivot)]\n\tnxt = [n for n in list_in[1:] if not relation(n,pivot)]\n\n\treturn quick_sort(prev)+[pivot]+quick_sort(nxt)\n\n#print(quick_sort2(relation, list_1))\n","sub_path":"IIA/praticas/other_ppl/Prática/Guião 1/iia_2.py","file_name":"iia_2.py","file_ext":"py","file_size_in_byte":4666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"582366020","text":"#\n# Deep Learning\n# =============\n#\n# Assignment 6\n# ------------\n#\n# After training a skip-gram model in `5_word2vec.ipynb`, the goal of this notebook is to train a LSTM character model\n# over [Text8](http://mattmahoney.net/dc/textdata) data.\n\n# These are all the modules we'll be using later. Make sure you can import them\n# before proceeding further.\nfrom __future__ import print_function\nimport os\nimport numpy as np\nimport random\nimport string\nimport tensorflow as tf\nimport zipfile\nfrom six.moves import range\nfrom six.moves.urllib.request import urlretrieve\n\nurl = 'http://mattmahoney.net/dc/'\n\n\ndef maybe_download(filename, expected_bytes):\n \"\"\"Download a file if not present, and make sure it's the right size.\"\"\"\n if not os.path.exists(filename):\n filename, _ = urlretrieve(url + filename, filename)\n statinfo = os.stat(filename)\n if statinfo.st_size == expected_bytes:\n print('Found and verified %s' % filename)\n else:\n print(statinfo.st_size)\n raise Exception(\n 'Failed to verify ' + filename + '. Can you get to it with a browser?')\n return filename\n\n\nfilename = maybe_download('text8.zip', 31344016)\n\n\ndef read_data(filename):\n with zipfile.ZipFile(filename) as f:\n name = f.namelist()[0]\n data = tf.compat.as_str(f.read(name))\n return data\n\n\ntext = read_data(filename)\nprint('Data size %d' % len(text))\n\nvalid_size = 1000\nvalid_text = text[:valid_size]\ntrain_text = text[valid_size:]\ntrain_size = len(train_text)\nprint(train_size, train_text[:64])\nprint(valid_size, valid_text[:64])\n\n# Utility functions to map characters to vocabulary IDs and back.\n\nvocabulary_size = len(string.ascii_lowercase) + 1 # [a-z] + ' '\nfirst_letter = ord(string.ascii_lowercase[0])\n\n\ndef char2id(char):\n if char in string.ascii_lowercase:\n return ord(char) - first_letter + 1\n elif char == ' ':\n return 0\n else:\n print('Unexpected character: %s' % char)\n return 0\n\n\ndef id2char(dictid):\n if dictid > 0:\n return chr(dictid + first_letter - 1)\n else:\n return ' '\n\n\nprint(char2id('a'), char2id('z'), char2id(' '))\nprint(id2char(1), id2char(26), id2char(0))\n\n# Function to generate a training batch for the LSTM model.\n\nbatch_size = 64\nnum_unrollings = 10\n\n\nclass BatchGenerator(object):\n def __init__(self, text, batch_size, num_unrollings):\n self._text = text\n self._text_size = len(text)\n self._batch_size = batch_size\n self._num_unrollings = num_unrollings\n segment = self._text_size // batch_size\n self._cursor = [offset * segment for offset in range(batch_size)]\n self._last_batch = self._next_batch()\n\n def _next_batch(self):\n \"\"\"Generate a single batch from the current cursor position in the data.\"\"\"\n batch = np.zeros(shape=(self._batch_size, vocabulary_size), dtype=np.float)\n for b in range(self._batch_size):\n batch[b, char2id(self._text[self._cursor[b]])] = 1.0\n self._cursor[b] = (self._cursor[b] + 1) % self._text_size\n return batch\n\n def next(self):\n \"\"\"Generate the next array of batches from the data. The array consists of\n the last batch of the previous array, followed by num_unrollings new ones.\n \"\"\"\n batches = [self._last_batch]\n for step in range(self._num_unrollings):\n batches.append(self._next_batch())\n self._last_batch = batches[-1]\n return batches\n\n\ndef characters(probabilities):\n \"\"\"Turn a 1-hot encoding or a probability distribution over the possible\n characters back into its (most likely) character representation.\"\"\"\n return [id2char(c) for c in np.argmax(probabilities, 1)]\n\n\ndef batches2string(batches):\n \"\"\"Convert a sequence of batches back into their (most likely) string\n representation.\"\"\"\n s = [''] * batches[0].shape[0]\n for b in batches:\n s = [''.join(x) for x in zip(s, characters(b))]\n return s\n\n\ntrain_batches = BatchGenerator(train_text, batch_size, num_unrollings)\nvalid_batches = BatchGenerator(valid_text, 1, 1)\n\nprint(batches2string(train_batches.next()))\nprint(batches2string(train_batches.next()))\nprint(batches2string(valid_batches.next()))\nprint(batches2string(valid_batches.next()))\n\n\ndef logprob(predictions, labels):\n \"\"\"Log-probability of the true labels in a predicted batch.\"\"\"\n predictions[predictions < 1e-10] = 1e-10\n return np.sum(np.multiply(labels, -np.log(predictions))) / labels.shape[0]\n\n\ndef sample_distribution(distribution):\n \"\"\"Sample one element from a distribution assumed to be an array of normalized\n probabilities.\n \"\"\"\n r = random.uniform(0, 1)\n s = 0\n for i in range(len(distribution)):\n s += distribution[i]\n if s >= r:\n return i\n return len(distribution) - 1\n\n\ndef sample(prediction):\n \"\"\"Turn a (column) prediction into 1-hot encoded samples.\"\"\"\n p = np.zeros(shape=[1, vocabulary_size], dtype=np.float)\n p[0, sample_distribution(prediction[0])] = 1.0\n return p\n\n\ndef random_distribution():\n \"\"\"Generate a random column of probabilities.\"\"\"\n b = np.random.uniform(0.0, 1.0, size=[1, vocabulary_size])\n return b / np.sum(b, 1)[:, None]\n\n# ---\n# Problem 2\n# ---------\n#\n# We want to train a LSTM over bigrams, that is pairs of consecutive characters like 'ab' instead of single characters\n# like 'a'. Since the number of possible bigrams is large, feeding them directly to the LSTM using 1-hot encodings will\n# lead to a very sparse representation that is very wasteful computationally.\n#\n# a- Introduce an embedding lookup on the inputs, and feed the embeddings to the LSTM cell instead of the inputs\n# themselves.\n#\n# b- Write a bigram-based LSTM, modeled on the character LSTM above.\n#\n# c- Introduce Dropout. For best practices on how to use Dropout in LSTMs, refer to this\n# [article](http://arxiv.org/abs/1409.2329).\n#\n# ---\n\n\ndef bigram2id(bigram):\n return char2id(bigram[0]) * 27 + char2id(bigram[1])\n\n\ndef id2bigram(dictid):\n char_id_1 = dictid // 27\n char_id_2 = dictid % 27\n return id2char(char_id_1) + id2char(char_id_2)\n\n# import string\n# for i in range(1000):\n# test_string = random.choice(string.lowercase) + random.choice(string.lowercase)\n# assert id2bigram(bigram2id(test_string)) == test_string\n# id = int(random.uniform(0, 27*27))\n# assert bigram2id(id2bigram(id)) == id\n\n\ndef get_bigrams_from_string(string):\n return [string[i:(i+2)] for i in range(len(string) - 1)]\n\n\nclass BatchGenerator(object):\n def __init__(self, text, batch_size, num_unrollings):\n self._text = text\n self._text_size = len(text)\n self._batch_size = batch_size\n self._num_unrollings = num_unrollings\n segment = self._text_size // batch_size\n self._cursor = [offset * segment for offset in range(batch_size)]\n # self._last_batch_label = self._next_batch()\n\n def _next_batch(self):\n \"\"\"Generate a single batch from the current cursor position in the data.\"\"\"\n batch = np.zeros(shape=(self._batch_size), dtype=np.int32)\n label = np.zeros(shape=(self._batch_size), dtype=np.int32)\n for b in range(self._batch_size):\n batch[b] = bigram2id(self._text[self._cursor[b]:self._cursor[b] + 2])\n label[b] = char2id(self._text[self._cursor[b] + 2])\n self._cursor[b] = (self._cursor[b] + 1) % self._text_size\n return batch, label\n\n def next(self):\n \"\"\"Generate the next array of batches from the data. The array consists of\n the last batch of the previous array, followed by num_unrollings new ones.\n \"\"\"\n batches = []\n labels = []\n for step in range(self._num_unrollings):\n new_batch, new_label = self._next_batch()\n batches.append(new_batch)\n labels.append(new_label)\n # self._last_batch_label = (batches[-1], labels[-1])\n return batches, labels\n\ntrain_batches = BatchGenerator(train_text, batch_size, num_unrollings)\nvalid_batches = BatchGenerator(valid_text, 1, 1)\n\n[id2bigram(x) for x in train_batches.next()[0][0]]\ntrain_batches.next()[0][0]\n\nembedding_size = 32 # Size of the embedding (mapping bigrams to features of dimension 32)\nnum_nodes = 64\n\ngraph = tf.Graph()\nwith graph.as_default():\n # Parameters:\n # Input gate: input, previous output, and bias.\n embeddings = tf.Variable(tf.truncated_normal([vocabulary_size ** 2, embedding_size], -0.1, 0.1))\n W_input = tf.Variable(tf.truncated_normal([embedding_size, 4 * num_nodes], -0.1, 0.1))\n W_last_output = tf.Variable(tf.truncated_normal([num_nodes, 4 * num_nodes], -0.1, 0.1))\n b = tf.Variable(tf.zeros([1, 4 * num_nodes]))\n # Variables saving state across unrollings.\n saved_output = tf.Variable(tf.zeros([batch_size, num_nodes]), trainable=False)\n saved_state = tf.Variable(tf.zeros([batch_size, num_nodes]), trainable=False)\n # Classifier weights and biases.\n W_final = tf.Variable(tf.truncated_normal([num_nodes, vocabulary_size], -0.1, 0.1))\n b_final = tf.Variable(tf.zeros([vocabulary_size]))\n\n # Definition of the cell computation.\n def lstm_cell(input, last_output, state):\n \"\"\"Create a LSTM cell. See e.g.: http://arxiv.org/pdf/1402.1128v1.pdf\n Note that in this formulation, we omit the various connections between the\n previous state and the gates.\"\"\"\n gates = tf.matmul(input, W_input) + tf.matmul(last_output, W_last_output) + b\n input_gate, forget_gate, update, output_gate = tf.split(gates, 4, 1)\n state = tf.sigmoid(forget_gate) * state + tf.sigmoid(input_gate) * tf.tanh(update)\n return tf.sigmoid(output_gate) * tf.tanh(state), state\n\n # Input data.\n train_bigram_ids = [tf.placeholder(tf.int32, [batch_size])] * (num_unrollings)\n train_labels = [tf.placeholder(tf.float32, shape=[batch_size, vocabulary_size])] * (num_unrollings)\n\n # Unrolled LSTM loop.\n outputs = list()\n output = saved_output\n state = saved_state\n for input_ids in train_bigram_ids:\n input = tf.nn.embedding_lookup(embeddings, input_ids)\n output, state = lstm_cell(input, output, state)\n outputs.append(output)\n\n # State saving across unrollings.\n with tf.control_dependencies([saved_output.assign(output), saved_state.assign(state)]):\n # Classifier.\n logits = tf.nn.xw_plus_b(tf.concat(outputs, 0), W_final, b_final)\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n labels=tf.concat(train_labels, 0), logits=logits))\n\n # Optimizer.\n global_step = tf.Variable(0)\n learning_rate = tf.train.exponential_decay(10.0, global_step, 5000, 0.1, staircase=True)\n optimizer = tf.train.GradientDescentOptimizer(learning_rate)\n gradients, v = zip(*optimizer.compute_gradients(loss))\n gradients, _ = tf.clip_by_global_norm(gradients, 1.25)\n optimizer = optimizer.apply_gradients(zip(gradients, v), global_step=global_step)\n\n # Predictions.\n train_prediction = tf.nn.softmax(logits)\n\n # Sampling and validation eval: batch 1, no unrolling.\n sample_input_bigram_id = tf.placeholder(tf.int32, shape=[1])\n saved_sample_output = tf.Variable(tf.zeros([1, num_nodes]))\n saved_sample_state = tf.Variable(tf.zeros([1, num_nodes]))\n reset_sample_state = tf.group(saved_sample_output.assign(tf.zeros([1, num_nodes])),\n saved_sample_state.assign(tf.zeros([1, num_nodes])))\n sample_output, sample_state = lstm_cell(tf.nn.embedding_lookup(embeddings, sample_input_bigram_id),\n saved_sample_output, saved_sample_state)\n with tf.control_dependencies([saved_sample_output.assign(sample_output),\n saved_sample_state.assign(sample_state)]):\n sample_prediction = tf.nn.softmax(tf.nn.xw_plus_b(sample_output, W_final, b_final))\n\nnum_steps = 7001\nsummary_frequency = 100\n\nwith tf.Session(graph=graph) as session:\n tf.global_variables_initializer().run()\n print('Initialized')\n mean_loss = 0\n for step in range(num_steps):\n batches, labels = train_batches.next()\n feed_dict = {}\n for i in range(len(batches)):\n feed_dict[train_bigram_ids[i]] = batches[i]\n dummified_labels = np.zeros((labels[i].shape[0], vocabulary_size))\n for index in range(dummified_labels.shape[0]):\n dummified_labels[index, labels[i][index]] = 1\n feed_dict[train_labels[i]] = dummified_labels\n _, l, predictions, lr = session.run([optimizer, loss, train_prediction, learning_rate], feed_dict=feed_dict)\n mean_loss += l\n if step % summary_frequency == 0:\n if step > 0:\n mean_loss = mean_loss / summary_frequency\n # The mean loss is an estimate of the loss over the last few batches.\n print('Average loss at step %d: %f learning rate: %f' % (step, mean_loss, lr))\n mean_loss = 0\n labels = np.concatenate(list(labels))\n dummified_labels = np.zeros((labels.shape[0], vocabulary_size))\n for index in range(dummified_labels.shape[0]):\n dummified_labels[index, labels[index]] = 1\n print('Minibatch perplexity: %.2f' % float(np.exp(logprob(predictions, dummified_labels))))\n if step % (summary_frequency * 10) == 0:\n # Generate some samples.\n print('=' * 80)\n for _ in range(5):\n sentence = characters(sample(random_distribution()))[0] +\\\n characters(sample(random_distribution()))[0]\n feed = [bigram2id(sentence)]\n reset_sample_state.run()\n for _ in range(79):\n prediction = sample_prediction.eval({sample_input_bigram_id: feed})\n next_letter = sample(prediction)\n sentence += characters(next_letter)[0]\n feed = [bigram2id(sentence[-2:])]\n print(sentence)\n print('=' * 80)\n # Measure validation set perplexity.\n reset_sample_state.run()\n valid_logprob = 0\n # for _ in range(valid_size):\n # valid_batch, valid_labels = valid_batches.next()\n # predictions = sample_prediction.eval({sample_input_bigram_id: valid_batch[0]})\n # valid_labels = np.concatenate(list(valid_labels))\n # dummified_labels = np.zeros((valid_labels.shape[0], vocabulary_size))\n # for index in range(dummified_labels.shape[0]):\n # dummified_labels[index, valid_labels[index]] = 1\n # valid_logprob = valid_logprob + logprob(predictions, dummified_labels)\n # print('Validation set perplexity: %.2f' % float(np.exp(valid_logprob / valid_size)))\n\n","sub_path":"lstm_problem_2.py","file_name":"lstm_problem_2.py","file_ext":"py","file_size_in_byte":14941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"143244959","text":"from math import exp, log, sqrt, pi\nfrom typing import Tuple\n\n\nclass Rating(object):\n\n def __init__(self, mu=2000., rd=200., volatility=0.0001):\n self.mu = mu\n self.rd = rd\n self.volatility = volatility\n\n def __repr__(self):\n args = (self.mu, self.rd, self.volatility)\n return '(mu=%.3f, rd=%.3f, volatility=%.3f)' % args\n\n\nclass Glicko2(object):\n\n def __init__(self, mu=2000., rd=200., tau=1, epsilon=0.000001, is_draw_mode=True, draw_inclination=-0.2,\n draw_penalty=0.01):\n self.mu = mu\n self.rd = rd\n self.tau = tau\n self.q = log(10) / 400\n self.q1 = 400 / log(10) # 173.71\n self.epsilon = epsilon\n self.is_draw_mode = is_draw_mode\n self.draw_inclination = draw_inclination\n self.draw_penalty = draw_penalty\n\n def _convert_into_glicko2(self, rating: Rating) -> Rating:\n \"\"\"\n Step 2.\n Convert the ratings and RD’s onto the Glicko-2 scale.\n \"\"\"\n mu = ((rating.mu - self.mu) * self.q)\n phi = (rating.rd * self.q)\n return Rating(mu, phi, rating.volatility)\n\n def _convert_from_glicko2(self, rating: Rating) -> Rating:\n \"\"\"\n Step 8. Convert ratings and RD’s back to original scale.\n \"\"\"\n mu = (rating.mu * self.q1 + self.mu)\n phi = (rating.rd * self.q1)\n return Rating(mu, phi, rating.volatility)\n\n @staticmethod\n def _g(phi: float, phi_opp: float) -> float:\n \"\"\"\n Function g, which is used in step 3 and others.\n \"\"\"\n g = 1 / sqrt(1 + 1.5 * (phi ** 2 + phi_opp ** 2) / pi ** 2)\n return g\n\n @staticmethod\n def _expected_score(mu: float, mu_opp: float, g: float) -> float:\n \"\"\"\n Calculate expected score of game.\n It is used in step 3 and others.\n \"\"\"\n\n expected_score = 1 / (1 + exp(-g * (mu - mu_opp)))\n return expected_score\n\n @staticmethod\n def _v(g: float, expected_score: float) -> float:\n \"\"\"\n Step 3.\n Compute the quantity rating variance v. This is the estimated variance of the team’s/player’s\n rating based only on game outcomes.\n \"\"\"\n v = 1 / (g ** 2 * expected_score * (1 - expected_score))\n return v\n\n @staticmethod\n def _rating_improvement(v: float, g: float, outcome: float, expected_score: float) -> float:\n \"\"\"\n Step 4.\n Compute the quantity ∆, the estimated improvement in rating by comparing the\n pre-period rating to the performance rating based only on game outcomes.\n \"\"\"\n delta = (v * g * (outcome - expected_score))\n return delta\n\n def f(self, rating_improvement: float, v: float, rating: Rating, x: float) -> float:\n \"\"\"\n Used in step 5.\n \"\"\"\n phi = rating.rd\n vol = rating.volatility\n\n temp_var = (phi ** 2 + v + exp(x))\n\n first_term = exp(x) * (rating_improvement ** 2 - temp_var) / (2 * temp_var ** 2)\n second_term = (x - log(vol ** 2)) / (self.tau ** 2)\n\n return first_term - second_term\n\n def _update_volatility(self, rating: Rating, rating_opp: Rating, outcome: float) -> float:\n \"\"\"\n Step 5.\n Determine the new value σ, of the volatility. This computation requires iterations.\n \"\"\"\n mu = rating.mu\n phi = rating.rd\n\n mu_opp = rating_opp.mu\n phi_opp = rating_opp.rd\n\n g = self._g(phi, phi_opp)\n expected_score = self._expected_score(mu, mu_opp, g)\n v = self._v(g, expected_score)\n rating_improvement = self._rating_improvement(v, g, outcome, expected_score)\n\n a = log(rating.volatility ** 2)\n\n temp = (rating_improvement ** 2 - phi ** 2 - v)\n if temp > 0:\n b = log(temp)\n else:\n k = 1\n while self.f(rating_improvement, v, rating, a - k * self.tau) < 0:\n k += 1\n\n b = (a - k * self.tau)\n\n f_a = self.f(rating_improvement, v, rating, a)\n f_b = self.f(rating_improvement, v, rating, b)\n\n while abs(b - a) > self.epsilon:\n c = a + (a - b) * f_a / (f_b - f_a)\n f_c = self.f(rating_improvement, v, rating, c)\n\n if f_c * f_b < 0:\n a = b\n f_a = f_b\n else:\n f_a /= 2\n\n b = c\n f_b = f_c\n\n new_volatility = exp(a / 2)\n\n return new_volatility\n\n def _update_rating(self, rating: Rating, rating_opp: Rating, outcome: float) -> Rating:\n \"\"\"\n Run all steps.\n Step 6. Update the rating deviation to the new pre-rating period value, φ*.\n Step 7. Update the rating and RD to the new values, µ' and φ'.\n Step 8. Convert ratings and RD’s back to original scale\n \"\"\"\n\n rating = self._convert_into_glicko2(rating)\n rating_opp = self._convert_into_glicko2(rating_opp)\n\n mu = rating.mu\n phi = rating.rd\n\n mu_opp = rating_opp.mu\n phi_opp = rating_opp.rd\n\n new_volatility = self._update_volatility(rating, rating_opp, outcome)\n\n g = self._g(phi, phi_opp)\n expected_score = self._expected_score(mu, mu_opp, g)\n v = self._v(g, expected_score)\n\n # step 6\n squared_phi_star = (phi ** 2 + new_volatility ** 2)\n\n # step 7\n new_phi = 1 / sqrt((1 / squared_phi_star) + (1 / v))\n\n new_mu = mu + (new_phi ** 2) * g * (outcome - expected_score)\n\n new_rating = Rating(new_mu, new_phi, new_volatility)\n\n # step 8\n new_rating = self._convert_from_glicko2(new_rating)\n\n return new_rating\n\n @staticmethod\n def _increase_mu(rating: Rating, addition: float) -> Rating:\n \"\"\"\"\"\"\n return Rating(rating.mu + addition, rating.rd, rating.volatility)\n\n def rate(self, home_rating: Rating, away_rating: Rating, advantage: float, outcome: str) -> Tuple[Rating, Rating]:\n \"\"\"\n home_rating - rating of home team.\n away_rating - rating of away team.\n advantage - home court, injures, etc. advantage of winning team, can be negative.\n \"\"\"\n # take into account the advantage\n increased_home_rating = self._increase_mu(home_rating, advantage)\n decreased_away_rating = self._increase_mu(away_rating, -advantage)\n\n # update ratings\n if outcome == 'H':\n new_increased_home_rating = self._update_rating(increased_home_rating, decreased_away_rating, 1)\n new_decreased_away_rating = self._update_rating(decreased_away_rating, increased_home_rating, 0)\n\n elif outcome == 'D':\n new_increased_home_rating = self._update_rating(increased_home_rating, decreased_away_rating, 0.5)\n new_decreased_away_rating = self._update_rating(decreased_away_rating, increased_home_rating, 0.5)\n\n else:\n new_increased_home_rating = self._update_rating(increased_home_rating, decreased_away_rating, 0)\n new_decreased_away_rating = self._update_rating(decreased_away_rating, increased_home_rating, 1)\n\n # subtract advantage\n updated_home_rating = self._increase_mu(new_increased_home_rating, -advantage)\n updated_away_rating = self._increase_mu(new_decreased_away_rating, advantage)\n\n return updated_home_rating, updated_away_rating\n\n def probabilities(self, team: Rating, opp_team: Rating, advantage: float) -> Tuple[float, float, float]:\n \"\"\"\n Input ratings are in original scale.\n Return the probabilities of outcomes.\n \"\"\"\n\n mu = ((team.mu + advantage - self.mu) * self.q)\n mu_opp = ((opp_team.mu - advantage - self.mu) * self.q)\n\n phi = (team.rd * self.q)\n phi_opp = (opp_team.rd * self.q)\n\n g = 1 / sqrt(1 + 1.5 * (phi ** 2 + phi_opp ** 2) / pi ** 2)\n\n delta_mu = (mu - mu_opp)\n\n if self.is_draw_mode:\n draw_penalty = self.draw_penalty * max(mu, mu_opp)\n\n win_probability = 1 / (1 + exp(-g * delta_mu) + exp(self.draw_inclination - delta_mu - draw_penalty))\n loss_probability = 1 / (1 + exp(g * delta_mu) + exp(self.draw_inclination + delta_mu - draw_penalty))\n tie_probability = (1 - win_probability - loss_probability)\n\n else:\n win_probability = 1 / (1 + exp(-g * delta_mu))\n loss_probability = (1 - win_probability)\n tie_probability = 0\n\n return win_probability, tie_probability, loss_probability\n","sub_path":"glicko2.py","file_name":"glicko2.py","file_ext":"py","file_size_in_byte":8615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"401110512","text":"# -*- coding: utf-8 -*-\n# !@time: 2021-03-17 13:20:32\n# !@author: superMC @email: 18758266469@163.com\n# !@question title: distinct-subsequences\n\n# 给定一个字符串 s 和一个字符串 t ,计算在 s 的子序列中 t 出现的个数。 \n# \n# 字符串的一个 子序列 是指,通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串。(例如,\"ACE\" 是 \"ABCDE\" 的一个子序列\n# ,而 \"AEC\" 不是) \n# \n# 题目数据保证答案符合 32 位带符号整数范围。 \n# \n# \n# \n# 示例 1: \n# \n# \n# 输入:s = \"rabbbit\", t = \"rabbit\"\n# 输出:3\n# 解释:\n# 如下图所示, 有 3 种可以从 s 中得到 \"rabbit\" 的方案。\n# (上箭头符号 ^ 表示选取的字母)\n# rabbbit\n# ^^^^ ^^\n# rabbbit\n# ^^ ^^^^\n# rabbbit\n# ^^^ ^^^\n# \n# \n# 示例 2: \n# \n# \n# 输入:s = \"babgbag\", t = \"bag\"\n# 输出:5\n# 解释:\n# 如下图所示, 有 5 种可以从 s 中得到 \"bag\" 的方案。 \n# (上箭头符号 ^ 表示选取的字母)\n# babgbag\n# ^^ ^\n# babgbag\n# ^^ ^\n# babgbag\n# ^ ^^\n# babgbag\n# ^ ^^\n# babgbag\n# ^^^ \n# \n# \n# \n# 提示: \n# \n# \n# 0 <= s.length, t.length <= 1000 \n# s 和 t 由英文字母组成 \n# \n# Related Topics 字符串 动态规划 \n# 👍 392 👎 0\n\nfrom typing import List\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def numDistinct(self, s: str, t: str) -> int:\n m = len(s)\n n = len(t)\n dp = [[0] * (m + 1) for _ in range(n + 1)]\n for j in range(m + 1):\n dp[0][j] = 1\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n if t[i - 1] == s[j - 1]:\n dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1]\n else:\n dp[i][j] = dp[i][j - 1]\n # print(dp)\n return dp[-1][-1]\n\n\n# leetcode submit region end(Prohibit modification and deletion)\nif __name__ == '__main__':\n s = \"rabbbit\"\n t = \"rabbit\"\n print(Solution().numDistinct(s, t))\n","sub_path":"dp/115.py","file_name":"115.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"120504669","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nwindow = Tk()\r\nwindow.title(\"Welcome To {INSERST NAME HERE}\")\r\nwindow.geometry('400x400')\r\nwindow.configure(background = \"grey\")\r\nfname = Label(window ,text = \"First Name\").grid(row = 0,column = 0)\r\nlname = Label(window ,text = \"Last Name\").grid(row = 1,column = 0)\r\nemail = Label(window ,text = \"Email ID\").grid(row = 2,column = 0)\r\ncontact = Label(window ,text = \"Contact\").grid(row = 2,column = 0)\r\na = Entry(window).grid(row = 0,column = 1)\r\nb = Entry(window).grid(row = 1,column = 1)\r\nc = Entry(window).grid(row = 2,column = 1)\r\nd = Entry(window).grid(row = 3,column = 1)\r\ndef clicked():\r\n\tres = \"Welcome to \" + txt.get()\r\n\tlbl.configure(text= res)\r\nbtn = ttk.Button(window ,text=\"Submit\").grid(row = 4, column=0)\r\nwindow.mainloop()","sub_path":"Python/Register.py","file_name":"Register.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"31500760","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 4 10:35:39 2018\n\n@author: Michael\n\"\"\"\nimport string\nimport random\n\n\n\ndef random_string(length):\n return ''.join(random.choice(string.ascii_letters) for m in range(length))\n\nclass CardMaker(object):\n \n # Tweaked so that it will fit in 80 columns...\n #wordstring = 'add land shall glass wrap catch chapter bell spell step dress chest length shelf fill drink thick print since grip wrist doll cross block strong'\n #words example:\n #words = [\"爱\",\"世\",\"人\",\"马\",\"可\",\"福\",\"音\",\"第\",\n #\"一\",\"章\",\"节\",\"活\",\"出\",\"平\",\"安\",\"夜\",\n # \"圣\",\"善\",\"照\",\"着\",\"亲\",\"婴\",\"儿\"]\n #words = [\"add\" ,\"land\",\"shall\",\"glass\",\"wrap\",\"catch\",\"chapter\"]\n wordstring = input('Enter words with space in between')\n bingosize = int (input('Enter row number of bingo'))\n input_words = wordstring.split()\n bingo = int(bingosize**2)\n \n if bingo == len(input_words):\n words = input_words\n elif bingo < len(input_words):\n words = random.sample(input_words,bingo)\n\n elif bingo > len(input_words):\n print ('Enter', bingo-len(input_words), 'more words','or reduce row number of bingo to', int((bingosize)**(0.5)))\n words = [random_string(4) for i in range(bingo)]\n# print the words to double check \n print ('Words to play are', words)\n print ('Size of bingo is', bingosize)\n maxlen = max([len(w) for w in words])\n #row = \"|\" + (\"%%%ss|\"%maxlen)*5 +\"\\n\"\n spacer = \"+\" + (\"-\"*maxlen + \"+\")*bingosize + \"\\n\"\n #template = (spacer + row)*5 + spacer\n #83 for 3 per page\n #row = \"\" + \"%s\"*5 + \"\"\n row = \"\" + \"%s\"*bingosize + \"\"\n \n template = \"\" + row*bingosize + \"
\"+\"\"\n \n \n def __call__(self, use_wild=False, template=None):\n if not template:\n template = self.template\n words = self.words[:]\n n = int(len(words)/2)\n random.shuffle(words)\n if use_wild:\n #words[12] = \"*WILD*\"\n words[n] = \"\"\n return template % tuple(words)\n \n#Quick and dirty usage examples - may need to fix file paths:\ndef make_one_webpage():\n make_card = CardMaker()\n #people = [\"John\", \"Jane\", \"Sally\", \"Mark\"]\n# the save path need to be changed\n with open(\"C:\\\\Users\\\\Michael\\\\Documents\\\\python\\\\Bingo\\\\bingo_1.htm\", \"w\") as f:\n bingo_number = int(input('Enter bingo game numbers you want to play'))\n\n for person in range(bingo_number):\n f.write(\"%s:\"%person)\n f.write(\"\\n\")\n f.write(make_card(use_wild=True).rstrip('\\n'))\n \n #print (f, \"%s:\"%person)\n #print (f, make_card(use_wild=True))\n f.close()\nmake_one_webpage()\n\n","sub_path":"Bingo/tbingo.py","file_name":"tbingo.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"273748149","text":"\nimport io\n\nfrom functools import partial\n\nfrom .kdf import KeyDerivator\nfrom ..utils.fileobj_wrapper import FileobjWrapper\n\n\n__all__ = ['EncryptionAlgorithm', 'AuthenticatedEncryptionAlgorithm', 'Encryptor', 'Decryptor']\n\n\nclass CryptBase(FileobjWrapper):\n KEY_SIZE = None # must be set by subclasses\n\n def __init__(self, fileobj, key, *args, **kwargs):\n super().__init__(fileobj, *args, **kwargs)\n\n if isinstance(key, KeyDerivator):\n key = key.derive_key(self.KEY_SIZE)\n self.key = key\n\n\nclass Encryptor(CryptBase):\n pass\n\n\nclass Decryptor(CryptBase):\n pass\n\n\nclass EncryptionAlgorithm:\n \"\"\"\n Class of encryption algorithms.\n\n Usage example:\n\n ::\n infile = open(file_path, 'rb')\n\n password = input('Enter your password: ')\n password = password.encode()\n kdf = PBKDF2_HMAC('sha256', 500000)\n\n with AES.Decryptor(infile, kdf) as decryptor:\n # remove the password from memory as soon as possible\n del password, kdf\n\n decrypted_data = decryptor.read()\n\n :ivar name: The algorithm's name\n :ivar Encryptor: The :class:`Encryptor` class used by this algorithm\n :ivar Decryptor: The :class:`Decryptor` class used by this algorithm\n \"\"\"\n\n _instances = []\n\n @classmethod\n def list(cls):\n return cls._instances\n\n def __new__(cls, *args, **kwargs):\n obj = super().__new__(cls)\n\n cls._instances.append(obj)\n return obj\n\n def __init__(self, name, encryptor, decryptor):\n assert issubclass(encryptor, Encryptor), encryptor.__mro__\n assert issubclass(decryptor, Decryptor), decryptor.__mro__\n\n self.name = name\n self.Encryptor = encryptor\n self.Decryptor = decryptor\n\n @classmethod\n def from_name(cls, name):\n try:\n return next(algo for algo in cls.list() if algo.name == name)\n except StopIteration:\n raise ValueError(\"No {} with name {!r} found\".format(cls.__name__, name))\n\n def with_key(self, key):\n \"\"\"\n Creates a copy of an EncryptionAlgorithm instance where the Encryptor\n and Decryptor already have the :param:`key` parameter set.\n \"\"\"\n encryptor = partial(self.Encryptor, key=key)\n decryptor = partial(self.Decryptor, key=key)\n\n self_with_kdf = object.__new__(type(self))\n self_with_kdf.__init__(self.name, encryptor, decryptor)\n return self_with_kdf\n\n def encrypt(self, data, key, **kwargs):\n file = io.BytesIO(data)\n with self.Encryptor(file, key, **kwargs) as encryptor:\n return encryptor.read()\n\n def decrypt(self, data, key, **kwargs):\n file = io.BytesIO(data)\n with self.Decryptor(file, key, **kwargs) as decryptor:\n return decryptor.read()\n\n def __repr__(self):\n return '<{} encryption>'.format(self.name)\n\n\nclass AuthenticatedEncryptionAlgorithm(EncryptionAlgorithm):\n def encrypt(self, data, key, unencrypted_header=b'', **kwargs):\n file = io.BytesIO()\n with self.Encryptor(file, key, forward_context=False, **kwargs) as encryptor:\n encryptor.write_unencrypted(unencrypted_header)\n encryptor.write(data)\n\n return file.getvalue()\n\n def encrypt_and_generate_mac(self, data, key, unencrypted_header=b'', **kwargs):\n file = io.BytesIO()\n with self.Encryptor(file, key, forward_context=False, **kwargs) as encryptor:\n encryptor.write_unencrypted(unencrypted_header)\n encryptor.write(data)\n\n return file.getvalue(), encryptor.mac\n\n def decrypt_and_verify_mac(self, data, key, mac, **kwargs):\n file = io.BytesIO(data)\n with self.Decryptor(file, key, **kwargs) as decryptor: # TODO: If the algorithm allows a custom MAC size, set it automatically\n plaintext = decryptor.read()\n\n if not decryptor.verify_mac(mac):\n raise ValueError(\"Incorrect MAC\")\n\n return plaintext\n","sub_path":"file_utils/encryption/encryption_algorithm.py","file_name":"encryption_algorithm.py","file_ext":"py","file_size_in_byte":3998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"637852465","text":"class User():\n\tdef __init__(self, username, email_address):\n\t\tself.name = username\n\t\tself.email = email_address\n\t\tself.account_balance = 0\n\tdef make_deposit(self, amount):\n\t\tself.account_balance += amount\n\t\tself.display_user_balance()\n\tdef make_withdrawal(self, amount):\n\t\tself.account_balance -= amount\n\t\tself.display_user_balance()\n\tdef display_user_balance(self):\n\t\tprint(self.name,\" balance:\",self.account_balance)\n\tdef transfer_money(self, other_user, amount):\n\t\tself.account_balance -= amount\n\t\tother_user.account_balance += amount\n\t\tself.display_user_balance()\n\t\tother_user.display_user_balance()\n\nmike = User(\"mike123\",\"mike@yahoo.com\")\nandy = User(\"andy123\", \"andy@yahoo.com\")\ndave = User(\"dave123\", \"dave@yahoo.com\")\n\nmike.make_deposit(100)\nmike.make_deposit(200)\nmike.make_deposit(300)\nmike.make_withdrawal(400)\nmike.display_user_balance()\n\nandy.make_deposit(200)\nandy.make_deposit(200)\nandy.make_withdrawal(100)\nandy.display_user_balance()\n\ndave.make_deposit(900)\ndave.make_withdrawal(100)\ndave.make_withdrawal(100)\ndave.make_withdrawal(100)\n\nmike.transfer_money(andy, 200)\n\n\n","sub_path":"user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"654169","text":"from __future__ import print_function, unicode_literals, absolute_import\nfrom Xlib import X, display, Xutil\nimport mathpix, pyperclip, os, json, base64, io, gi, sys\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk, Gdk, GLib, GdkPixbuf\nfrom playsound import playsound\nfrom PIL import Image\n\nclass Snipper:\n def __init__(self): \n path = os.environ['HOME'] + '/.config/mathpixsnipper/'\n with open(path+'conf.json') as json_file:\n data = json.load(json_file)\n mathpix.default_headers['app_id'] = data['app_id'] \n mathpix.default_headers['app_key'] = data['app_key']\n \n def cdir(self):\n print(os.getcwd())\n\n def callmathpixapi(self, img): \n os.getcwd()\n r = mathpix.latex({ \n 'src': mathpix.image_uri2(img),\n 'formats': ['latex_simplified']\n })\n\n if 'error' in r: \n return 'error_info ' + json.dumps(r['error_info'])\n \n return r'$$'+r['latex_simplified']+'$$'\n \nclass ClipboardWindow(Gtk.Window):\n def __init__(self):\n Gtk.Window.__init__(self, title=\"Clipboard Example\")\n\n grid = Gtk.Grid()\n\n self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)\n self.entry = Gtk.Entry()\n self.image = Gtk.Image.new_from_icon_name(\"process-stop\", Gtk.IconSize.MENU)\n\n button_copy_text = Gtk.Button(label=\"Copy Text\")\n button_paste_text = Gtk.Button(label=\"Paste Text\")\n button_copy_image = Gtk.Button(label=\"Copy Image\")\n button_paste_image = Gtk.Button(label=\"Paste Image\")\n\n grid.add(self.entry)\n grid.attach(self.image, 0, 1, 1, 1)\n grid.attach(button_copy_text, 1, 0, 1, 1)\n grid.attach(button_paste_text, 2, 0, 1, 1)\n grid.attach(button_copy_image, 1, 1, 1, 1)\n grid.attach(button_paste_image, 2, 1, 1, 1)\n\n button_copy_text.connect(\"clicked\", self.copy_text)\n button_paste_text.connect(\"clicked\", self.paste_text)\n button_copy_image.connect(\"clicked\", self.copy_image)\n button_paste_image.connect(\"clicked\", self.paste_image)\n\n self.add(grid)\n\n def copy_text(self, widget):\n self.clipboard.set_text(self.entry.get_text(), -1)\n\n def set_text(self, text):\n self.clipboard.set_text(text, -1)\n \n def paste_text(self, widget):\n text = self.clipboard.wait_for_text()\n if text is not None:\n self.entry.set_text(text)\n else:\n print(\"No text on the clipboard.\")\n\n def copy_image(self, widget):\n if self.image.get_storage_type() == Gtk.ImageType.PIXBUF:\n self.clipboard.set_image(self.image.get_pixbuf())\n else:\n print(\"No image has been pasted yet.\")\n\n def paste_image(self, widget):\n print('paste image pressed')\n image = self.clipboard.wait_for_image()\n if image is not None:\n self.image.set_from_pixbuf(image)\n \n def get_buffer(self):\n self.img = self.clipboard.wait_for_image()\n if self.img is not None:\n print('is not none')\n print(type(self.img))\n self.image.set_from_pixbuf(self.img)\n return self.pixbuf2image(self.img)\n\n def pixbuf2image(self, pix):\n \"\"\"Convert gdkpixbuf to PIL image\"\"\"\n data = pix.get_pixels()\n w = pix.props.width\n h = pix.props.height\n stride = pix.props.rowstride\n mode = \"RGB\"\n if pix.props.has_alpha == True:\n mode = \"RGBA\"\n im = Image.frombytes(mode, (w, h), data, \"raw\", mode, stride)\n return im\n\ndef main():\n import os\n os.system('maim -s | xclip -selection clipboard -t image/png')\n\n # get image \n win = ClipboardWindow()\n pil_image = win.get_buffer()\n\n # plot\n #%pylab inline\n #import matplotlib.pyplot as plt\n #import matplotlib.image as mpimg\n #imgplot = plt.imshow(pil_image)\n #plt.show() \n\n snp = Snipper() \n buf = io.BytesIO()\n pil_image.save(buf, format='PNG')\n byte_im = buf.getvalue()\n\n r = snp.callmathpixapi(byte_im)\n import pandas as pd\n df=pd.DataFrame([r])\n df.to_clipboard(index=False,header=False)\n os.system('beep')\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"python/snipper.py","file_name":"snipper.py","file_ext":"py","file_size_in_byte":4302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"399113364","text":"class Solution(object):\n def fizzBuzz(self, n):\n \"\"\"\n :type n: int\n :rtype: List[str]\n \"\"\"\n ret = []\n for i in range(n):\n i += 1\n word = \"\"\n if i % 3 == 0:\n word += \"Fizz\"\n if i % 5 == 0:\n word += \"Buzz\"\n if len(word) == 0:\n word = str(i)\n ret.append(word)\n # print(i, \"--->>>\", word)\n return ret\n\n\ns = Solution()\nprint(s.fizzBuzz(15))\n","sub_path":"LeetCode/412. Fizz Buzz.py","file_name":"412. Fizz Buzz.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"537051295","text":"import numpy\n\nfrom collections import defaultdict\n\nfrom scipy.stats.mstats import mode\n\nfrom functools import partial\nfrom operator import itemgetter\nfrom teletext.misc.all import All\nfrom packet import Packet, HeaderPacket\nfrom subpage import Subpage\nfrom service import Service\nimport itertools\n\ndef reader(infile, start=0, stop=-1):\n \"\"\"Helper to read t42 lines from a file-like object.\"\"\"\n if start > 0:\n infile.seek(start * 42)\n lines = iter(partial(infile.read, 42), b'')\n for n,l in enumerate(lines):\n offset = n + start\n if len(l) < 42:\n return\n elif offset == stop:\n return\n else:\n p = Packet.from_bytes(l)\n p._offset = offset\n yield p\n\n\n\ndef demux(packet_iter, magazines=All, rows=All):\n \"\"\"Filters t42 stream to a subset of magazines and packets.\"\"\"\n for packet in packet_iter:\n if packet.mrag.magazine in magazines:\n if packet.mrag.row in rows:\n yield packet\n\n\n\ndef packets(packet_list):\n for p in packet_list:\n yield p\n\ndef packet_lists(packet_list):\n yield packet_list\n\ndef subpages(packet_list):\n yield Subpage.from_packets(packet_list)\n\ndef paginate(packet_iter, pages=All, yield_func=packets, drop_empty=False):\n \"\"\"Reorders lines in a t42 stream so that pages are continuous.\"\"\"\n magbuffers = [[],[],[],[],[],[],[],[]]\n for packet in packet_iter:\n mag = packet.mrag.magazine\n if type(packet) == HeaderPacket:\n if ((drop_empty==False and len(magbuffers[mag]) > 0) or len(magbuffers[mag]) > 1) and type(magbuffers[mag][0]) == HeaderPacket:\n if magbuffers[mag][0].page_str() in pages:\n magbuffers[mag].sort(key=lambda p: p.mrag.row)\n for item in yield_func(magbuffers[mag]):\n yield item\n magbuffers[mag] = []\n magbuffers[mag].append(packet)\n for mb in magbuffers:\n if ((drop_empty==False and len(mb) > 0) or len(mb) > 1) and type(mb[0]) == HeaderPacket:\n if mb[0].page_str() in pages:\n mb.sort(key=lambda p: p.mrag.row)\n for item in yield_func(mb):\n yield item\n\n\ndef subpage_squash(packet_iter, minimum_dups=3, pages=All, yield_func=packets):\n subpages = defaultdict(list)\n for pl in paginate(packet_iter, pages=pages, yield_func=packet_lists, drop_empty=True):\n subpagekey = (pl[0].mrag.magazine, pl[0].header.page, pl[0].header.subpage)\n arr = numpy.zeros((42, 32), dtype=numpy.uint8)\n for p in pl:\n arr[:,p.mrag.row] = p._original_bytes\n subpages[subpagekey].append(arr)\n\n for arrlist in subpages.itervalues():\n if len(arrlist) >= minimum_dups:\n arr = mode(numpy.array(arrlist), axis=0)[0][0].astype(numpy.uint8)\n packets = []\n\n for i in range(32):\n if arr[:,i].any():\n packets.append(Packet.from_bytes(arr[:,i]))\n\n for item in yield_func(packets):\n yield item\n\ndef split_seq(iterable, size):\n it = iter(iterable)\n item = list(itertools.islice(it, size))\n while item:\n yield item\n item = list(itertools.islice(it, size))\n\n\ndef row_squash(packet_iter, n_rows):\n\n for l_list in split_seq(packet_iter, n_rows):\n a = numpy.array([numpy.fromstring(l.to_bytes(), dtype=numpy.uint8) for l in l_list])\n best, counts = mode(a)\n best = best[0].astype(numpy.uint8)\n p = Packet.from_bytes(best)\n p._offset = l_list[0]._offset\n yield p\n\n\ndef make_service(packet_iter, pages=All):\n service = Service()\n for s in paginate(packet_iter, pages=pages, yield_func=subpages):\n service.magazines[s._original_magazine].pages[s._original_page].subpages[s._original_subpage] = s\n\n for k,v in service.magazines.iteritems():\n v.magazineno = k\n\n return service\n\n\n","sub_path":"teletext/t42/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":3950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"10704422","text":"'''\n author: yiouejv\n email: yiouejv@126.com\n time: 2019-4-3\n'''\n# 爬取小刀娱乐网文章\nimport time\n\nimport requests\nfrom lxml import etree\nimport re\nfrom apps.front.models import Post, Board, FrontUser\nfrom exts import db\nfrom flask import Flask\nimport config\nfrom .unames import names\nfrom random import choice\n\napp = Flask(__name__)\napp.config.from_object(config)\ndb.init_app(app)\n\nheaders = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',\n 'Cookie': 'fikker-kbqT-5Z9f=7LUZobe81RQf5dOTC0gpO4ORKvSDSDSN; fikker-kbqT-5Z9f=7LUZobe81RQf5dOTC0gpO4ORKvSDSDSN; UM_distinctid=169e34b2b7671-097553095a74c7-7a1437-1fa400-169e34b2b77ac; security_session_verify=5e51896ae5542abbcbf57633eae734c0; ShowoPage=sCond=+WHERE+leixing%3D494893++and+ZhuangTai%3D0+and+SuoShuWangZhanID%3D146486+&PageIndex=707; YanShiGengXin%5Fwz=1; fikker-BuT3-lJRE=DUtWjUJYfepWNKhgPWbITQKYHEI1JsIU; fikker-BuT3-lJRE=DUtWjUJYfepWNKhgPWbITQKYHEI1JsIU; CNZZDATA1274292051=1389578274-1554293935-https%253A%252F%252Fwww.baidu.com%252F%7C1554299342; ASPSESSIONIDCUQQTBTS=ADLABGMBACFLOFGHDLOPJOCH',\n 'Connection': 'keep-alive',\n 'Host': 'www.xd0.com',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',\n 'Referer': 'https://www.xd0.com/i_wz_499337.html'\n}\n\n\ndef get_first_urls(url):\n response = requests.get(\n url=url,\n headers=headers\n )\n html = response.text\n html = etree.HTML(html)\n urls = html.xpath('//h2//a/@href')\n urls = list(map(lambda url: 'https://www.xd0.com/' + url, urls))\n return urls\n\n\ndef get_page_urls(catagory, page):\n '''\n 获取当前页面文章的url\n :param catagory: 分类id\n :param page: 文章页码\n :return: 当前页面的文章\n '''\n try:\n url = 'https://www.xd0.com/i_wz.asp?id=%d&PageIndex=%d' % (catagory, page)\n response = requests.get(\n url=url,\n headers=headers\n )\n html = response.text\n html = etree.HTML(html)\n urls = html.xpath('//h2//a/@href')\n urls = list(map(lambda url: 'https://www.xd0.com/'+url, urls))\n except Exception:\n return []\n return urls\n\n\ndef parse_one_page(url):\n '''\n 解析一篇文章页\n :param url:\n :return: title, content\n '''\n try:\n html = requests.get(url=url, headers=headers).text\n html_dom = etree.HTML(html)\n title = html_dom.xpath('//h2[@class=\"post-title\"]/text()')[0]\n\n # 获取文章内容\n content = html_dom.xpath('//table[@style=\"table-layout:fixed;word-break:break-all\"]')[0]\n content = etree.tostring(content, encoding='utf-8').decode()\n\n # 将内容中的图片地址补全\n pattern = r''\n imgs_list = re.findall(pattern, content, re.S)\n\n for img in imgs_list:\n if img and img[:4]!='http':\n content = content.replace(img, 'https://www.xd0.com/'+img)\n content = content.replace('/images/loading.gif', 'https://www.xd0.com/'+img, 1)\n time.sleep(0.5)\n except Exception:\n print(url, '请求异常')\n return [],[]\n return title, content\n\n\ndef post_to_mysql(title, content, board_id):\n '''\n 文章存入数据库\n :param title: 文章标题\n :param content: 文章内容\n :param board_id: 本站的分类id\n :return: None\n '''\n try:\n post = db.session.query(Post).filter(Post.title==title).first()\n if not post and title[2:4]!='淘宝' and title[3:5]!='淘宝' and title:\n # 存入数据库\n post = Post(title=title, content=content, release=True)\n board = db.session.query(Board).filter(Board.id==board_id).first()\n user = db.session.query(FrontUser).filter(FrontUser.username == choice(names)).first()\n if board:\n post.board = board\n post.front_user = user\n db.session.add(post)\n db.session.commit()\n print('%s文章入库成功!' % title)\n else:\n print('本站不存在对应的板块!')\n else:\n print('%s-文章已存在,跳过入库操作!' % title)\n except Exception as err:\n print(err)\n\n\ndef work():\n with app.app_context():\n # 更新第一页资料\n urls = get_first_urls('https://www.xd0.com/i_wz_494893.html')\n\n for url in urls:\n title, content = parse_one_page(url)\n post_to_mysql(title, content, 3)\n\n # 抓取1页值得一看\n urls = get_first_urls('https://www.xd0.com/i_wz_497796.html')\n for url in urls:\n title, content = parse_one_page(url)\n post_to_mysql(title, content, 4)\n\n urls = get_first_urls('https://www.xd0.com/i_wz_497796_c_109373.html')\n for url in urls:\n title, content = parse_one_page(url)\n post_to_mysql(title, content, 4)\n\n urls = get_first_urls('https://www.xd0.com/i_wz_497796_c_107422.html')\n for url in urls:\n title, content = parse_one_page(url)\n post_to_mysql(title, content, 4)\n\n urls = get_first_urls('https://www.xd0.com/i_wz_497796_c_107279.htmll')\n for url in urls:\n title, content = parse_one_page(url)\n post_to_mysql(title, content, 4)\n\n # 抓取1页线报\n urls = get_first_urls('https://www.xd0.com/i_wz_306807.html')\n\n for url in urls:\n title, content = parse_one_page(url)\n post_to_mysql(title, content, 7)\n\n # 抓取1页软件\n urls = get_first_urls('https://www.xd0.com/i_wz_103904.html')\n\n for url in urls:\n title, content = parse_one_page(url)\n post_to_mysql(title, content, 9)\n\n # 抓取值得一听\n urls = get_first_urls('https://www.xd0.com/i_wz_201146.html')\n\n for url in urls:\n title, content = parse_one_page(url)\n post_to_mysql(title, content, 11)\n\n\n\n","sub_path":"utils/xiaodao_spider.py","file_name":"xiaodao_spider.py","file_ext":"py","file_size_in_byte":6174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"507257350","text":"import numpy as np\n\n\nclass RandomPlayer():\n def __init__(self, game):\n self.game = game\n\n def play(self, board, curPlayer):\n a = np.random.randint(self.game.getActionSize())\n valids = self.game.getValidMoves(board, 1)\n while valids[a]!=1:\n a = np.random.randint(self.game.getActionSize())\n return a\n\nclass Heuristic():\n def __init__(self, game):\n self.game = game\n self.N = game.row\n self.M = game.col\n self.generate_lines()\n\n def play(self, board, curPlayer):\n if(curPlayer != 0):\n mtx = self.get_field_stregth_mtx(board, 1)\n x,y = np.unravel_index(np.argmax(mtx), mtx.shape)\n if(board[x][y]!=0):\n x,y = self.greedy(board)\n #print(x, y, mtx[x][y])\n return x*self.N+y\n else:\n print(\"Invalid player!!!\", curPlayer)\n\n def random_play(self, board, curPlayer):\n if(curPlayer != 0):\n mtx = self.get_field_stregth_mtx(board, 1)\n probs = np.array(mtx).flatten()\n a = np.random.choice(range(len(probs)), p = probs)\n return a\n \n def line_sum(self, board):\n sum = 0.0\n for line in self.Lines:\n enemyLess = True\n emptyNum = 0\n for x,y in line:\n if(board[x][y]==-1):\n enemyLess = False\n break;\n elif(board[x][y]==0):\n emptyNum += 1\n if(enemyLess):\n sum += 2.0**(-emptyNum)\n return sum\n \n def greedy(self, board):\n for x in range(self.M):\n for y in range(self.N):\n if(board[x][y]==0):\n return x,y\n print(\"Board is full!!!\")\n exit()\n \n def get_field_stregth_mtx(self, board, player, verbose=False):\n mtx = np.zeros(shape = (self.M, self.N))\n for key, lines in self.pointStrengthHeuristics.items():\n x,y = key\n if(board[x][y]!=0):\n continue\n\n min_emptynum = 100\n for line in lines:\n enemyless = True\n emptynum = 0\n for (x1,y1) in line:\n if(board[x1][y1]==-player):\n enemyless = False\n break\n elif(board[x1][y1] == 0):\n emptynum +=1\n if(enemyless):\n min_emptynum = min(emptynum, min_emptynum)\n mtx[x][y] += 2.0**(-emptynum)\n\n #mtx = mtx**2\n if verbose:\n mtx = mtx.transpose()\n for row in mtx:\n for x in row:\n print(\"{0:.4f}\".format(x), end = ' ')\n print('')\n\n for row in board:\n for x in row:\n print(\"{}\".format(x), end = ' ')\n print(\"\")\n mtx = mtx.transpose()\n\n if np.max(mtx) == 0.0:\n x,y = self.greedy(board)\n mtx[x][y]=1.0\n return mtx\n\n \n def generate_lines(self, player = 1):\n self.Lines = []\n self.pointStrengthHeuristics={}\n col, row = (self.M, self.N)\n n = 7\n\n for w in range(col):\n # if the offence has a full column, he won\n line = [(w, i) for i in range(row)]\n self.Lines.append(line)\n\n # if the offence has a row of len self.n_in_row, he won\n if (w in range(1, col - n)):\n for h in range(row):\n line = [(i,h) for i in range(w, w + n)]\n self.Lines.append(line)\n\n # if the offence has a row of len 4 in the border, he won\n #half = int(math.ceil(n/2))\n half = 4\n if (w in [0,col-half]):\n for h in range(row):\n line = [(i,h) for i in range(w, w + half)]\n self.Lines.append(line)\n\n # if the offence has a full diagonal of length col, he won\n if (w in range(col - row + 1)):\n line = [(w+l,l) for l in range(row)]\n self.Lines.append(line)\n if (w in range(row-1, col)):\n line = [(w-l,l) for l in range(row)]\n self.Lines.append(line)\n\n # if the offence has 3 in a corner diagonal, he won\n self.Lines.append([(2,0),(1,1), (0,2)])\n self.Lines.append([(col-3,0),(col-2,1), (col-1,2)])\n self.Lines.append([(0, row-3),(1, row-2), (2, row-1)])\n self.Lines.append([(col-1, row-3),(col-2, row-2), (col-3, row-1)])\n\n # if the offence has two in one of the northern corner diagonals, he won\n self.Lines.append([(1,0),(0,1)])\n self.Lines.append([(col-2,0),(col-1,1)])\n\n\n # Geather the lines in each Field\n for line in self.Lines:\n for x,y in line:\n if (x,y) not in self.pointStrengthHeuristics:\n self.pointStrengthHeuristics[(x,y)]=[line]\n else:\n self.pointStrengthHeuristics[(x,y)].append(line)\n\nclass HumanGobangPlayer():\n def __init__(self, game):\n self.game = game\n\n def play(self, board, curPlayer):\n # display(board)\n verbose = False\n valid = self.game.getValidMoves(board, 1)\n for i in range(len(valid)):\n if valid[i]:\n if verbose:\n print(\"({} {}) \".format(int(i/self.game.row), int(i%self.game.row)), end=\"\")\n if verbose: print(\"\")\n while True:\n a = input()\n\n try:\n x,y = [int(x) for x in a.split(' ')]\n except:\n print(\"Bad value, try again\")\n a = input()\n x,y = [int(x) for x in a.split(' ')]\n a = self.game.row * x + y if x!= -1 else self.game.row * self.game.col\n if valid[a]:\n break\n else:\n x = int(a/self.game.row)\n y = int(a%self.game.row)\n print('\\033[1A{} {} Invalid '.format(x,y), end = '')\n #print(\" \"*30+'\\r', end = '')\n\n return a\n\n\nclass GreedyGobangPlayer():\n def __init__(self, game):\n self.game = game\n\n def play(self, board, curPlayer):\n valids = self.game.getValidMoves(board, 1)\n candidates = []\n for a in range(self.game.getActionSize()):\n if valids[a]==0:\n continue\n nextBoard, _ = self.game.getNextState(board, 1, a)\n score = self.game.getScore(nextBoard, 1)\n candidates += [(-score, a)]\n candidates.sort()\n return candidates[0][1]\n","sub_path":"gobang/GobangPlayers.py","file_name":"GobangPlayers.py","file_ext":"py","file_size_in_byte":6721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"26210236","text":"def maneuver(n1):\n\tstack=[]\n\tglobal s\n\ttemp=list(s)\n\tk=0\n\twhile k<=n1:\n\t\tif(temp[k]=='-'):\n\t\t\tstack.append('+')\n\t\telse:\n\t\t\tstack.append('-')\n\t\tk+=1 \n\tk=n1\n\twhile k>=0:\n\t\ttemp[k]=stack.pop()\t\n\t\tk-=1\n\ts=\"\".join(temp)\n\t#print s\n\treturn \n\nt=int(raw_input())\nfor i in xrange(t):\n\tflips=0\n\ts=raw_input()\n\tn=len(s)\n\tcomplete=False\n\twhile not complete:\n\t\tj=n-1\n\t\twhile(j>=0 and s[j]!='-'):\n\t\t\tj-=1\n\n\t\t#print str(j)\n\t\tif (j==-1 and s[j]=='+'):\n\t\t\tcomplete=True\n\t\t\tprint (\"Case #\"+str((i+1))+\": \"+str(flips))\n\t\t\tbreak\n\t\tif(j!=(n-1)):\n\t\t\tn=j\n\t\tj=0\n\t\t#print str(n)\n\t\twhile(j prob] = -1\n return x \n\n else:\n return input.sign()\n\n @staticmethod\n def backward(ctx, grad_output):\n \"\"\"[summary]\n \n Arguments:\n ctx {[type]} -- [description]\n grad_output {[type]} -- [description]\n \n Returns:\n [type] -- [description]\n \"\"\"\n\n return grad_output, None\n","sub_path":"functions/sign.py","file_name":"sign.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"288205223","text":"from flask import Flask, redirect, render_template, url_for, request\nimport subprocess\nimport WeedBot\nimport json\n\nserver_debug = False # This only activates Flask web server\n\ndef page_handler(input: str):\n return render_template('header.html') + render_template(input) + render_template('footer.html')\n\ndef status_handler(input: str):\n return render_template('header.html') + f\"

{input}

\" + \"\"\"\n \n \"\"\" + render_template('footer.html')\n\ndef process_textline(textline, chosen_set):\n print(f\"{textline}\\n{chosen_set}\")\n if not textline or not chosen_set:\n return status_handler(\"Why are we still here to suffer?\")\n if len(textline) > 56:\n return status_handler(\"Yooo brooo, chill!\")\n with open('sentences.json', 'r') as infile:\n data = json.load(infile)\n if textline in data[chosen_set]:\n return status_handler(\"It's already there, someone made the joke before you.\")\n data[chosen_set].append(textline)\n with open('sentences.json', 'w') as outfile:\n json.dump(data, outfile, indent=4)\n return status_handler(\"Yooooo! Poggers, fam!\")\n\napp = Flask(__name__, static_folder='web/public', template_folder='web/views')\n@app.route('/')\ndef index():\n return page_handler('index.html')\n\n@app.route('/bot')\ndef bot_invite():\n bot_id = 0\n if not server_debug:\n bot_id = WeedBot.bot_id()\n return redirect(f\"https://discordapp.com/api/oauth2/authorize?client_id={bot_id}&permissions=43024&scope=bot\")\n\n@app.route('/submit')\ndef submit_page():\n return page_handler('submit.html')\n\n@app.route('/git', methods=['POST'])\ndef git_update():\n proc = 'sh git.sh'\n subprocess.call(proc.split())\n return 200\n\n@app.route('/handle_data', methods=['POST'])\ndef handle_data():\n textline = request.form['textline']\n chosen_set = request.form['sets']\n return process_textline(textline, chosen_set)\n\n@app.route('/electronjs/api/textline', methods=['POST'])\ndef handle_data_json():\n data = request.get_json(force=True)\n textline = data['textline']\n chosen_set = data['sets']\n return process_textline(textline, chosen_set)\n\nif __name__ == \"__main__\":\n if not server_debug:\n WeedBot.bot_alive()\n app.run('0.0.0.0')","sub_path":"Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"363364463","text":"import requests\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom io import BytesIO\n\nsubscription_key = \"你的電腦視覺資源key\"\nvision_base_url = \"https://southeastasia.api.cognitive.microsoft.com/vision/v2.0/\"\nanalyze_url = vision_base_url + \"analyze\"\nimage_url = \"https://i.imgur.com/BO7tlY7.jpg\"\nheaders = {'Ocp-Apim-Subscription-Key': subscription_key }\nparams = {'visualFeatures': 'Categories,Description,Color'}\ndata = {'url': image_url}\nresponse = requests.post(analyze_url, headers=headers, params=params, json=data)\nanalysis = response.json()\n#print(analysis)\n\n#顯示圖片及圖片描述\nimage_caption = analysis[\"description\"][\"captions\"][0][\"text\"] #取得圖片描述\nimage = Image.open(BytesIO(requests.get(image_url).content))\nplt.imshow(image)\nplt.axis(\"off\")\n_ = plt.title(image_caption, size=\"x-large\", y=-0.1) #顯示圖片描述\n","sub_path":"_4.python/__code/Python自學聖經(第一版)/ch26/imgAnalyze1.py","file_name":"imgAnalyze1.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"341780381","text":"import logging\nimport os\nimport re\nfrom lintreview.tools import Tool\nfrom lintreview.tools import run_command\nfrom lintreview.utils import in_path\nfrom lintreview.utils import npm_exists\n\nlog = logging.getLogger(__name__)\n\n\nclass Gjslint(Tool):\n\n name = 'gjslint'\n\n def check_dependencies(self):\n \"\"\"\n See if gjslint is on the system path.\n \"\"\"\n return in_path('gjslint') or npm_exists('gjslint')\n\n def match_file(self, filename):\n base = os.path.basename(filename)\n name, ext = os.path.splitext(base)\n return ext == '.js'\n\n def process_files(self, files):\n \"\"\"\n Run code checks with gjslint.\n Only a single process is made for all files\n to save resources.\n \"\"\"\n log.debug('Processing %s files with %s', files, self.name)\n command = self.create_command(files)\n output = run_command(\n command,\n split=True,\n ignore_error=True)\n\n if re.search(r'no errors found', output[0]):\n log.debug('No gjslint errors found.')\n return False\n\n \"\"\"\n Lint Errors are reports as follows:\n ----- FILE : /private/tmp/workspace/repo/repo_name/pr_number/path/to/file.js -----\n Line 546, E:0007: Should have 2 blank lines between top-level blocks.\n Line 550, E:0210: Missing docs for parameter: \"parameters\"\n Line 550, E:0210: Missing docs for parameter: \"url\"\n Found 9 errors, including 1 new error, in 3 files (0 files OK).\n \"\"\"\n filename = ''\n for line in output:\n if 'FILE' in line:\n filename = self._parse_filename(line)\n elif re.match(r'Found .* errors', line):\n break;\n else:\n line_number, error = self._parse_line(line)\n self.problems.add(filename, line_number, error)\n\n def _parse_filename(self, line):\n return line.split()[3]\n\n def _parse_line(self, line):\n \"\"\"\n Split this: 'Line 546, E:0007: Should have 2 blank lines between top-level blocks' by spaces\n line = '546,' without the comma\n message = Everything after 'E:0007:' converted to a string\n \"\"\"\n parts = line.split()\n line = int(parts[1][0:-1])\n message = ' '.join(parts[3:len(parts)])\n return (line, message)\n\n def create_command(self, files):\n cmd = 'gjslint'\n if npm_exists('gjslint'):\n cmd = os.path.join(os.getcwd(), 'node_modules', '.bin', 'gjslint')\n command = [cmd, '--strict']\n command += files\n return command\n","sub_path":"lintreview/tools/gjslint.py","file_name":"gjslint.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"179170121","text":"from django.urls import re_path\n\n\nfrom apps.goods.views import IndexView,DetailView,ListView\n\n\napp_name = \"[apps.goods.urls,]\"\n\n\nurlpatterns = [\n re_path(r\"index/$\",IndexView.as_view(),name=\"index\"), # 商品首页\n re_path(\"detail/(?P\\d+)/$\",DetailView.as_view(),name=\"detail\"), # 商品详情页\n re_path(\"list/(?P\\d+)/(?P\\d+)/$\",ListView.as_view(),name=\"list\"), # 分类商品页\n]\n","sub_path":"dailyfresh/apps/goods/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"632550262","text":"import os, json\nimport requests\nimport sqlite3\nfrom datetime import datetime\n\nfrom flask import Flask, flash, jsonify, redirect, render_template, request, session, url_for\n\nfrom flask_session import Session\nfrom tempfile import mkdtemp\nfrom werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError\nfrom werkzeug.security import check_password_hash, generate_password_hash\nfrom functools import wraps\n\n\n# Configure application\napp = Flask(__name__)\n\n# Ensure templates are auto-reloade\napp.config[\"TEMPLATES_AUTO_RELOAD\"] = True\n\n\n# Ensure responses aren't cached\n@app.after_request\ndef after_request(response):\n response.headers[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate\"\n response.headers[\"Expires\"] = 0\n response.headers[\"Pragma\"] = \"no-cache\"\n return response\n\n\n# Configure session to use filesystem (instead of signed cookies)\napp.config[\"SESSION_FILE_DIR\"] = mkdtemp()\napp.config[\"SESSION_PERMANENT\"] = False\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\nSession(app)\n\n\n# Make sure API key is set\nif not os.environ.get(\"GEOAPI_KEY\"):\n raise RuntimeError(\"GEOAPI_KEY not set\")\nelse:\n GEOAPI_KEY = os.environ.get(\"GEOAPI_KEY\")\n\nif not os.environ.get(\"MAP_KEY\"):\n raise RuntimeError(\"MAP_KEY not set\")\nelse:\n MAP_KEY = os.environ.get(\"MAP_KEY\")\n\nprint(\"Connection to Database successful\")\n\nlat = \"\"\nlng = \"\"\nreal_ip = \"\"\n\n\ndef approval_required(f):\n \"\"\"\n Decorate routes to require login.\n\n http://flask.pocoo.org/docs/1.0/patterns/viewdecorators/\n \"\"\"\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if session.get(\"approved\") is None:\n return redirect(\"/approve\")\n return f(*args, **kwargs)\n return decorated_function\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\n@approval_required\ndef form():\n\n if request.method == \"POST\":\n\n with sqlite3.connect(\"location.sqlite\") as database: #COnnecting to Database\n db = database.cursor()\n\n '''\n '''\n global real_ip\n try:\n real_ip = request.headers['HTTP_X_FORWARDED_FOR']\n except KeyError:\n pass\n else:\n # HTTP_X_FORWARDED_FOR can be a comma-separated list of IPs.\n # Take just the first one.\n real_ip_list = real_ip.split(\",\")\n real_ip = real_ip_list[real_ip_list.length - 1]\n request.headers['REMOTE_ADDR'] = real_ip\n\n #get GEOAPI_KEY from WHOISXMLAPI\n r = requests.get(f\"https://ip-geolocation.whoisxmlapi.com/api/v1?apiKey={os.environ.get('GEOAPI_KEY')}&ipAddress={real_ip}\")\n j = json.loads(r.text)\n global lat\n global lng\n lat = j['location']['lat']\n lng = j['location']['lng']\n print(lat, lng)\n '''\n '''\n\n symptoms = request.values.getlist(\"symptom\") #gets symptoms values from form.html in a list\n vaccine = request.values.get(\"vaccine\") #gets vaccine values from form.html\n covidTest = request.values.get(\"covidTest\") #gets covidtest values from form.html\n riskFactor = 0 #initialize the Risk Factor\n \n\n #adds all the values/scores from the form.html and is then converted into a risk scoring for COVID 19 based on data.\n if covidTest is None: #Converts None from covidTest to 0 to avoid errors during addition\n covidTest = 0\n riskFactor = riskFactor + int(vaccine) + int(covidTest)\n for symptom in symptoms:\n riskFactor = riskFactor + int(symptom)\n\n time = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n #put all derived data from form.html to an SQL database.\n addData = db.execute(\"INSERT INTO location (lat, lng, date, risk) VALUES (?, ?, ?, ?)\",\n (lat, lng , time, riskFactor))\n\n\n session['time'] = time\n return redirect(url_for('maps'))\n else:\n return render_template(\"form.html\")\n\n\n@app.route(\"/maps\")\n@approval_required\ndef maps():\n with sqlite3.connect(\"location.sqlite\") as database:\n db = database.cursor()\n #select all locations from database from within 2 weeks ago\n locationsCursor = db.execute(\"SELECT lat, lng, risk FROM location WHERE julianday('now') - julianday(date) <= 14 ;\")\n #iniate to lists for lat and lng to be sent to HTML & JS\n locations_lat = list()\n locations_lng = list()\n locations_risk = list()\n riskScore = 0\n #adds lat, lng, and risk to respective lists from SQL cursor\n for location in locationsCursor:\n locations_lat.append(location[0])\n locations_lng.append(location[1])\n locations_risk.append(location[2])\n\n #fetches Risk Score of the current user\n riskCursor = db.execute(\"SELECT risk FROM location WHERE date=?\", (session['time'],))\n # assigns Risk Score of current user to locations_risk variable\n for risk in riskCursor:\n riskScore = risk[0]\n\n session.clear()\n #convert list to json format to be sent to maps.html and render template based on riskScore\n if riskScore <= 3:\n return render_template(\"maps_safe.html\", MAP_KEY = MAP_KEY, locations_lat = json.dumps(locations_lat), locations_lng = json.dumps(locations_lng), locations_risk = json.dumps(locations_risk), riskScore = riskScore, user_lat = lat, user_lng = lng)\n elif riskScore > 3 and riskScore <= 7:\n return render_template(\"maps_risky.html\", MAP_KEY = MAP_KEY, locations_lat = json.dumps(locations_lat), locations_lng = json.dumps(locations_lng), locations_risk = json.dumps(locations_risk), riskScore = riskScore, user_lat = lat, user_lng = lng)\n else:\n return render_template(\"maps_covid.html\", MAP_KEY = MAP_KEY, locations_lat = json.dumps(locations_lat), locations_lng = json.dumps(locations_lng), locations_risk = json.dumps(locations_risk), riskScore = riskScore, user_lat = lat, user_lng = lng)\n\n\n@app.route(\"/approve\" , methods =[\"GET\", \"POST\"])\ndef approve():\n #gets user consent for logging location\n\n session.clear() #forgets any previous session\n\n if request.method == \"POST\":\n session[\"approved\"] = 1\n return redirect(\"/\")\n else:\n return render_template(\"approve.html\")\n\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":6378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"181385903","text":"import smtpd\nimport asyncore\nimport time\n\nclass FakeSMTPServer(smtpd.SMTPServer):\n def __init__(*args, **kwargs):\n print('Running fake smtp server on port 8025')\n smtpd.SMTPServer.__init__(*args, **kwargs)\n\n def process_message(*args, **kwargs):\n mail = open('mails/' + str(time.time()) + '.eml', 'w')\n print('New mail from ' + args[2])\n print('Data:' + args[4].decode())\n mail.write(args[4].decode())\n mail.close\n pass\n\nif __name__ == '__main__':\n smtp_server = FakeSMTPServer(('0.0.0.0', 8025), None)\n try:\n asyncore.loop()\n except KeyboardInterrupt:\n smtp_server.close()\n","sub_path":"fake_smtp.py","file_name":"fake_smtp.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"169564573","text":"import os\nimport json\nimport logging\nimport tornado.httpclient\n\n_logger = logging.getLogger(__name__)\n\ndef handle_response(response):\n pass\n \ndef publish_one(receiver, notify):\n _logger.debug(\"publish_one start\")\n if not receiver or not notify:\n return\n \n publish_body = {}\n publish_body[\"receivers\"] = [\n {\"id\":receiver} \n ]\n publish_body[\"notify\"] = notify\n\n str_body = json.dumps(publish_body)\n http_client = tornado.httpclient.AsyncHTTPClient()\n http_client.fetch(\"http://localhost:8081/push\", handle_response, method='POST', headers=None, body=str_body) \n\ndef broadcast_one(user, notify):\n _logger.debug(\"broadcast %s\" % user)\n if not user or not notify:\n return\n\n publish_body = {}\n publish_body[\"changers\"] = [\n {\"id\": user}\n ]\n\n publish_body[\"notify\"] = notify\n str_body = json.dumps(publish_body)\n http_client = tornado.httpclient.AsyncHTTPClient()\n http_client.fetch(\"http://localhost:8081/notifyallsubs\", None, method='POST', headers=None, body=str_body)\n\ndef publish_one_tmp(receiver, notify):\n _logger.debug(\"publish_onetmp start\")\n if not receiver or not notify:\n return\n\n publish_body = {}\n publish_body[\"receivers\"] = [\n {\"id\":receiver}\n ]\n publish_body[\"notify\"] = notify\n\n str_body = json.dumps(publish_body)\n http_client = tornado.httpclient.AsyncHTTPClient()\n http_client.fetch(\"http://localhost:8081/tmppush\", handle_response, method='POST', headers=None, body=str_body)\n\ndef publish_multi(receivers, notify):\n _logger.debug(\"publish multi\")\n if not receivers or not notify:\n return\n\n publish_body = {}\n pub_recs = []\n for item in receivers:\n pub_recs.append({\"id\":item})\n\n publish_body[\"receivers\"] = pub_recs\n publish_body[\"notify\"] = notify\n\n str_body = json.dumps(publish_body)\n http_client = tornado.httpclient.AsyncHTTPClient()\n http_client.fetch(\"http://localhost:8081/push\", handle_response, method='POST', headers=None, body=str_body)\n","sub_path":"libs/mickey/publish.py","file_name":"publish.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"453774853","text":"# manage.py\n\n\nimport os\nimport unittest\nimport coverage\nimport datetime\nimport hashlib\nfrom project import params\n\nfrom algosdk import encoding\nfrom algosdk import transaction\nfrom algosdk import kmd\nfrom algosdk import algod\nfrom algosdk import account\nfrom algosdk import mnemonic\n\nfrom flask.ext.script import Manager\nfrom flask.ext.migrate import Migrate, MigrateCommand\n\nfrom project import app, db\nfrom project.models import User, Petition\n\n\napp.config.from_object(\"project.config.DevelopmentConfig\")\n\nmigrate = Migrate(app, db)\nmanager = Manager(app)\n\n# migrations\nmanager.add_command('db', MigrateCommand)\n\n\n@manager.command\ndef test():\n \"\"\"Runs the unit tests without coverage.\"\"\"\n tests = unittest.TestLoader().discover('tests')\n result = unittest.TextTestRunner(verbosity=2).run(tests)\n if result.wasSuccessful():\n return 0\n else:\n return 1\n\n\n@manager.command\ndef cov():\n \"\"\"Runs the unit tests with coverage.\"\"\"\n cov = coverage.coverage(branch=True, include='project/*')\n cov.start()\n tests = unittest.TestLoader().discover('tests')\n unittest.TextTestRunner(verbosity=2).run(tests)\n cov.stop()\n cov.save()\n print('Coverage Summary:')\n cov.report()\n basedir = os.path.abspath(os.path.dirname(__file__))\n covdir = os.path.join(basedir, 'tmp/coverage')\n cov.html_report(directory=covdir)\n print('HTML version: file://%s/index.html' % covdir)\n cov.erase()\n\n\n@manager.command\ndef create_db():\n \"\"\"Creates the db tables.\"\"\"\n db.create_all()\n\n\n@manager.command\ndef drop_db():\n \"\"\"Drops the db tables.\"\"\"\n db.drop_all()\n\n\n@manager.command\ndef create_admin():\n \"\"\"Creates the admin user.\"\"\"\n db.session.add(User(\n email=str(hashlib.sha256(\"ad@min.com\".encode()).hexdigest()),\n password=\"admin\",\n admin=True,\n confirmed=True,\n confirmed_on=datetime.datetime.now())\n )\n db.session.commit()\n\n@manager.command\ndef create_trashbag():\n kcl = kmd.KMDClient(params.kmd_token, params.kmd_address)\n acl = algod.AlgodClient(params.algod_token, params.algod_address)\n\n petitionWallet = \"Petitions\"\n petitionWalletPassword = \"root\"\n\n\n\n # get the wallet ID\n wallets = kcl.list_wallets()\n\n petitionWalletID = None\n for w in wallets:\n if w[\"name\"] == petitionWallet:\n petitionWalletID = w[\"id\"]\n break\n\n # if it doesn't exist, create the wallet and get its ID\n if not petitionWalletID:\n petitionWalletID = kcl.create_wallet(petitionWallet, petitionWalletPassword)[\"id\"]\n\n # get a handle for the wallet\n handle = kcl.init_wallet_handle(petitionWalletID, petitionWalletPassword)\n # generate account with account and check if it's valid\n private_key_1, address_1 = account.generate_account()\n # import generated account into the wallet\n kcl.import_key(handle, private_key_1)\n\n \"\"\"Creates trash bag account for all petitions.\"\"\"\n petition = Petition(\n name=\"Trash Bag Account\",\n publicKey=address_1,\n masterAccount = address_1,\n yesCount=0\n )\n db.session.add(petition)\n db.session.commit()\n\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"188438086","text":"\"\"\"\nGSU main functions.\n\"\"\"\n\nimport random\nimport math\nimport utils\n\n# ==================================================================================================\n\n\ndef rounded_point(p, digits=10):\n \"\"\"\n Get rounded point for constructing bags of points.\n :param p: point\n :param digits: accuracy\n :return: rounded point\n \"\"\"\n\n return round(p[0], digits), round(p[1], digits), round(p[2], digits)\n\n# --------------------------------------------------------------------------------------------------\n\n\ndef mean_nodes_point(ns):\n \"\"\"\n Get mean point of nodes.\n :param ns: nodes\n :return: mean point\n \"\"\"\n\n xs = [n.P[0] for n in ns]\n ys = [n.P[1] for n in ns]\n zs = [n.P[2] for n in ns]\n\n return sum(xs) / len(xs), sum(ys) / len(ys), sum(zs) / len(zs)\n\n# --------------------------------------------------------------------------------------------------\n\n\ndef fun_face_cx():\n \"\"\"\n Function that returns X coordinate of the face center.\n :return: function\n \"\"\"\n\n return lambda f: mean_nodes_point(f.Nodes)[0]\n\n# --------------------------------------------------------------------------------------------------\n\n\ndef fun_face_cy():\n \"\"\"\n Function that returns Y coordinate of the face center.\n :return: function\n \"\"\"\n\n return lambda f: mean_nodes_point(f.Nodes)[1]\n\n# --------------------------------------------------------------------------------------------------\n\n\ndef fun_face_cz():\n \"\"\"\n Function that returns Z coordinate of the face center.\n :return: function\n \"\"\"\n\n return lambda f: mean_nodes_point(f.Nodes)[2]\n\n# ==================================================================================================\n\n\nclass Node:\n \"\"\"\n Node of the grid.\n \"\"\"\n\n # ----------------------------------------------------------------------------------------------\n\n def __init__(self, p):\n \"\"\"\n Constructor node.\n :param p: node point (tuple of coordinates)\n \"\"\"\n\n # Global identifier (in grid numeration).\n self.GloId = -1\n\n self.P = p\n\n # Rounded coordinates for registration in set.\n self.RoundedCoords = rounded_point(p)\n\n # Links with edges and faces.\n self.Edges = []\n self.Faces = []\n\n # ----------------------------------------------------------------------------------------------\n\n def is_near(self, n):\n \"\"\"\n Check if one node is near to another.\n :param n: another node\n :return: True - if nodes are near to each other, False - otherwise\n \"\"\"\n\n return self.RoundedCoords == n.RoundedCoords\n\n# ==================================================================================================\n\n\nclass Edge:\n \"\"\"\n Edge of the grid.\n \"\"\"\n\n # ----------------------------------------------------------------------------------------------\n\n def __init__(self):\n \"\"\"\n Constructor.\n \"\"\"\n\n # Global identifier (in grid numeration).\n self.GloId = -1\n\n # Links to nodes and faces.\n self.Nodes = []\n self.Faces = []\n\n # ----------------------------------------------------------------------------------------------\n\n def is_border(self):\n \"\"\"\n Check if edge is border edge.\n :return: True - if edge is border edge, False - otherwise\n \"\"\"\n\n # Border edge has only one neighbour face.\n return len(self.Faces) == 1\n\n # ----------------------------------------------------------------------------------------------\n\n def is_cross(self):\n \"\"\"\n Check if edge is cross-zones.\n :return: True - if edge is cross-zones, False - otherwise\n \"\"\"\n\n # Cross-zone edge has two neighbour faces from different zones.\n\n faces_count = len(self.Faces)\n\n if faces_count == 1:\n return False\n elif faces_count == 2:\n return self.Faces[0].Zone != self.Faces[1].Zone\n else:\n raise Exception('Edge cannot has {0} neighbours faces.'.format(faces_count))\n\n # ----------------------------------------------------------------------------------------------\n\n def is_inner(self):\n \"\"\"\n Check if edge is inner.\n :return: True - if edge is inner, False - otherwise\n \"\"\"\n\n # Inner edge has two faces from one zone.\n\n faces_count = len(self.Faces)\n\n if faces_count == 1:\n return False\n elif faces_count == 2:\n return self.Faces[0].Zone == self.Faces[1].Zone\n else:\n raise Exception('Edge cannot has {0} neighbours faces.'.format(faces_count))\n\n # ----------------------------------------------------------------------------------------------\n\n def is_connect_zones(self, z0, z1):\n \"\"\"\n Check if edge connect two given zones.\n :param z0: first zone\n :param z1: second zone\n :return: True - if edge connects two given zones, False - otherwise\n \"\"\"\n\n if len(self.Faces) != 2:\n return False\n\n fz0, fz1 = self.Faces[0].Zone, self.Faces[1].Zone\n\n return ((z0 == fz0) and (z1 == fz1)) or ((z0 == fz1) and (z1 == fz0))\n\n# ==================================================================================================\n\n\nclass Face:\n \"\"\"\n Face of the grid.\n \"\"\"\n\n # ----------------------------------------------------------------------------------------------\n\n def __init__(self, data):\n \"\"\"\n Constructor face.\n :param data: face data (tuple)\n \"\"\"\n\n # Global identifier (in grid numeration).\n self.GloId = -1\n\n self.Data = data\n\n # Links with nodes and edges.\n self.Nodes = []\n self.Edges = []\n\n # Link to zone (each face belongs only to one single zone).\n self.Zone = None\n\n # ----------------------------------------------------------------------------------------------\n\n def get_t(self):\n \"\"\"\n Get temperature value.\n :return: temperature value\n \"\"\"\n\n return self.Data[0]\n\n # ----------------------------------------------------------------------------------------------\n\n def set_t(self, t):\n \"\"\"\n Set temperature value to face data.\n :param t: temperature\n \"\"\"\n\n self.Data[0] = t\n\n # ----------------------------------------------------------------------------------------------\n\n def get_hw(self):\n \"\"\"\n Get water height value.\n :return: water height\n \"\"\"\n\n return self.Data[1]\n\n # ----------------------------------------------------------------------------------------------\n\n def set_hw(self, hw):\n \"\"\"\n Set water height value to face data.\n :param hw: water height\n \"\"\"\n\n self.Data[1] = hw\n\n # ----------------------------------------------------------------------------------------------\n\n def get_hi(self):\n \"\"\"\n Get ice height value.\n :return: ice height\n \"\"\"\n\n return self.Data[2]\n\n # ----------------------------------------------------------------------------------------------\n\n def set_hi(self, hi):\n \"\"\"\n Set ice height value to face data.\n :param hi: ice height\n \"\"\"\n\n self.Data[2] = hi\n\n # ----------------------------------------------------------------------------------------------\n\n def get_glo_id_t_hw_hi_str(self):\n \"\"\"\n Get string with global identifier, temperature, and water and ice heights.\n :return: string\n \"\"\"\n\n # Random data for t, hw, hi.\n a = [self.get_t() + random.random(),\n self.get_hw() + random.random(),\n self.get_hi() + random.random()]\n i_list = [str(self.GloId)] + ['{0:.18e}'.format(ai) for ai in a]\n i_str = ' '.join(i_list)\n\n return i_str\n\n # ----------------------------------------------------------------------------------------------\n\n def get_neighbour(self, edge):\n \"\"\"\n Get neighbour through edge.\n :param edge: edge\n :return: neighbour\n \"\"\"\n\n incident_faces = len(edge.Faces)\n\n if incident_faces == 1:\n if edge.Faces[0] != self:\n raise Exception('Error while getting face neighbour.')\n return None\n elif incident_faces == 2:\n if edge.Faces[0] == self:\n return edge.Faces[1]\n elif edge.Faces[1] == self:\n return edge.Faces[0]\n else:\n raise Exception('Error while getting face neighbour.')\n else:\n raise Exception('Wrong edge incident faces ({0}).'.format(incident_faces))\n\n # ----------------------------------------------------------------------------------------------\n\n def unlink_from_zone(self):\n \"\"\"\n Unlink face from zone.\n \"\"\"\n\n if self.Zone is None:\n return\n\n # Face is linked.\n # Unlink it.\n self.Zone.Faces.remove(self)\n self.Zone = None\n\n # ----------------------------------------------------------------------------------------------\n\n def get_center(self):\n \"\"\"\n Get center point.\n :return: center point\n \"\"\"\n\n a, b, c, = self.Nodes[0].P, self.Nodes[1].P, self.Nodes[2].P\n\n return ((a[0] + b[0] + c[0]) / 3.0, (a[1] + b[1] + c[1]) / 3.0, (a[2] + b[2] + c[2]) / 3.0)\n\n # ----------------------------------------------------------------------------------------------\n\n def get_ab_vector(self):\n \"\"\"\n Get vector from A point to B point.\n :return: vector from A point to B point\n \"\"\"\n\n a, b = self.Nodes[0].P, self.Nodes[1].P\n\n return (b[0] - a[0], b[1] - a[1], b[2] - a[2])\n\n # ----------------------------------------------------------------------------------------------\n\n def get_bc_vector(self):\n \"\"\"\n Get vector from B point to C point.\n :return: vector from B point to C point\n \"\"\"\n\n b, c = self.Nodes[1].P, self.Nodes[2].P\n\n return (c[0] - b[0], c[1] - b[1], c[2] - b[2])\n\n # ----------------------------------------------------------------------------------------------\n\n def get_normal1(self):\n \"\"\"\n Get outer normal, normalized to 1.0.\n :return: normalized normal\n \"\"\"\n\n ab, bc = self.get_ab_vector(), self.get_bc_vector()\n n = utils.cross_product(ab, bc)\n\n return utils.normalized(n)\n\n # ----------------------------------------------------------------------------------------------\n\n def get_point_above(self, d):\n \"\"\"\n Get point above face (on distance d).\n :param d: distance\n :return: point\n \"\"\"\n\n c = self.get_center()\n n1 = self.get_normal1()\n\n return utils.a_kb(c, d, n1)\n\n# ==================================================================================================\n\n\nclass Zone:\n \"\"\"\n Zone of the grid.\n \"\"\"\n\n # ----------------------------------------------------------------------------------------------\n\n def __init__(self, name):\n \"\"\"\n Constructor.\n :param name: name of zone\n \"\"\"\n\n self.Id = -1\n\n self.Name = name\n\n # No nodes or faces in the zone yet.\n self.Nodes = []\n self.Edges = []\n self.Faces = []\n\n # Fixed zone flag.\n self.IsFixed = False\n\n # ----------------------------------------------------------------------------------------------\n\n def nodes_count(self):\n \"\"\"\n Get count of nodes.\n :return: nodes count\n \"\"\"\n\n return len(self.Nodes)\n\n # ----------------------------------------------------------------------------------------------\n\n def edges_count(self):\n \"\"\"\n Get count of edges.\n :return: edges count\n \"\"\"\n\n return len(self.Edges)\n\n # ----------------------------------------------------------------------------------------------\n\n def faces_count(self):\n \"\"\"\n Get count of faces.\n :return: faces count.\n \"\"\"\n\n return len(self.Faces)\n\n # ----------------------------------------------------------------------------------------------\n\n def get_nodes_coord_slice_str(self, i):\n \"\"\"\n Get string composed from i-th coord of all nodes.\n :param i: index of nodes coord\n :return: composed string\n \"\"\"\n\n i_list = ['{0:.18e}'.format(node.P[i]) for node in self.Nodes]\n i_str = ' '.join(i_list)\n\n return i_str\n\n # ----------------------------------------------------------------------------------------------\n\n def get_faces_data_slice_str(self, i):\n \"\"\"\n Get string composed from i-th elements of data of all faces.\n :param i: index of nodes data\n :return: composed string\n \"\"\"\n\n i_list = ['{0:.18e}'.format(face.Data[i]) for face in self.Faces]\n i_str = ' '.join(i_list)\n\n return i_str\n\n # ----------------------------------------------------------------------------------------------\n\n def get_faces_global_ids_slice_str(self):\n \"\"\"\n Get string composed from global identifiers of all faces.\n :return: composed string\n \"\"\"\n\n i_list = [str(face.GloId) for face in self.Faces]\n i_str = ' '.join(i_list)\n\n return i_str\n\n # ----------------------------------------------------------------------------------------------\n\n def add_node(self, n):\n \"\"\"\n Add node to zone.\n :param n: node\n :return: added node\n \"\"\"\n\n # Just add node.\n self.Nodes.append(n)\n\n return n\n\n # ----------------------------------------------------------------------------------------------\n\n def add_edge(self, e):\n \"\"\"\n Add edge to zone.\n :param e: edge\n :return: added edge\n \"\"\"\n\n # Just add egde.\n self.Edges.append(e)\n\n return e\n\n # ----------------------------------------------------------------------------------------------\n\n def add_face(self, f):\n \"\"\"\n Add face to zone (with link).\n :param f: face\n :return: added face\n \"\"\"\n\n # If face is already link to some zome,\n # we have to unlink it first.\n if f.Zone is not None:\n f.unlink_from_zone()\n\n # Just add and set link to the zone.\n f.Zone = self\n self.Faces.append(f)\n\n return f\n\n # ----------------------------------------------------------------------------------------------\n\n def capture_nearest_face(self):\n \"\"\"\n Capture face nearest to zone (breadth-first search).\n \"\"\"\n\n for f in self.Faces:\n for e in f.Edges:\n if not e.is_border():\n f2 = f.get_neighbour(e)\n if f2.Zone is None:\n self.add_face(f2)\n return\n\n# ==================================================================================================\n\n\nclass ZonesAdjacencyMatrix:\n \"\"\"\n Matrix of zones adjacency.\n For example if there is 3 zones matrix should be the following:\n | i00 c01 c02 br0 |\n | c01 i11 c12 br1 |\n | c02 c12 i22 br2 |\n | br0 br1 br2 0 |\n where cxy - count of cross edges between x-th and y-th zones,\n ixx - count of inner edges for x-th zone,\n brx - count of border edges for x-th zone.\n \"\"\"\n\n # ----------------------------------------------------------------------------------------------\n\n def __init__(self, es, zs):\n \"\"\"\n Constructor.\n :param es: edges list\n :param zs: zones list\n \"\"\"\n\n # Init size and zero matrix.\n zc = len(zs)\n self.ZonesCount = zc\n self.M = []\n # Do not copy arrays because we have to create arrays, not references.\n for i in range(zc + 1):\n self.M.append([0] * (zc + 1))\n\n # Calculate for each edge.\n for e in es:\n fc = len(e.Faces)\n if fc == 1:\n f0 = e.Faces[0]\n z0 = zs.index(f0.Zone)\n self.inc_border(z0)\n elif fc == 2:\n f0, f1 = e.Faces[0], e.Faces[1]\n z0, z1 = zs.index(f0.Zone), zs.index(f1.Zone)\n self.inc(z0, z1)\n else:\n raise Exception('Wrong edge faces count ({0}).'.format(fc))\n\n # ----------------------------------------------------------------------------------------------\n\n def inc(self, i, j):\n \"\"\"\n Increment matrix element value.\n :param i: first zone index\n :param j: second zone index\n \"\"\"\n\n self.M[i][j] += 1\n\n if i != j:\n self.M[j][i] += 1\n\n # ----------------------------------------------------------------------------------------------\n\n def inc_border(self, i):\n \"\"\"\n Increment value of border edges count.\n :param i: zone number\n \"\"\"\n\n self.inc(i, self.ZonesCount)\n\n # ----------------------------------------------------------------------------------------------\n\n def edges_statistics(self):\n \"\"\"\n Get edges statistics.\n Statistics is a tuple with following elements:\n ec - full edges count\n bec - border edges count\n iec - inner edges count\n cec - cross edges count\n becp - border edges count percent\n iecp - inner edges count percent\n cecp - cross edges count percent\n :return: tuple\n \"\"\"\n\n ec = 0\n bec = 0\n iec = 0\n cec = 0\n\n # Count all lines without the last one.\n for i in range(self.ZonesCount):\n line = self.M[i]\n # Border edges count for this zone is in the last row.\n # Inner edges count for this zone is on the main diagonal of the matrix.\n # All values between these two cells are cross edges.\n bec += line[self.ZonesCount]\n iec += line[i]\n cec += sum(line[(i + 1):self.ZonesCount])\n\n # Total count and percents.\n ec = bec + iec + cec\n becp, iecp, cecp = 100.0 * bec / ec, 100.0 * iec / ec, 100.0 * cec / ec\n\n return ec, bec, iec, cec, becp, iecp, cecp\n\n # ----------------------------------------------------------------------------------------------\n\n def edges_statistics_string(self):\n \"\"\"\n String of edges statistics:\n :return: string\n \"\"\"\n\n ec, bec, iec, cec, becp, iecp, cecp = self.edges_statistics()\n\n return 'edges stats: ' \\\n '{0} border ({1:.2f}%), ' \\\n '{2} inner ({3:.2f}%), ' \\\n '{4} cross ({5:.2f}%)'.format(bec, becp, iec, iecp, cec, cecp)\n\n # ----------------------------------------------------------------------------------------------\n\n def zone_cross_edges_array(self, zi):\n \"\"\"\n Array with count of cross edges.\n :param zi: zone index\n :return: array with cross edges count.\n \"\"\"\n\n line = self.M[zi]\n line2 = line[:]\n line2[zi] = 0\n line2[self.ZonesCount] = 0\n\n return line2\n\n # ----------------------------------------------------------------------------------------------\n\n def zone_max_cross_border_len(self, zi):\n \"\"\"\n Maximum border length for given zone.\n :param zi: zone index\n :return: max zone border length\n \"\"\"\n\n return max(self.zone_cross_edges_array(zi))\n\n # ----------------------------------------------------------------------------------------------\n\n def max_cross_border_len(self):\n \"\"\"\n Max value of cross zones border lengths.\n :return: max border length\n \"\"\"\n\n return max([self.zone_max_cross_border_len(zi) for zi in range(self.ZonesCount)])\n\n # ----------------------------------------------------------------------------------------------\n\n def zone_cross_edges_count(self, zi):\n \"\"\"\n Get zone cross-edges count.\n :param zi: zone index\n :return: count of cross-edges for this zone\n \"\"\"\n\n return sum(self.zone_cross_edges_array(zi))\n\n # ----------------------------------------------------------------------------------------------\n\n def zone_cross_borders_count(self, zi):\n \"\"\"\n Get borders count for given zone.\n :param zi: zone index\n :return: borders count\n \"\"\"\n\n return len([x for x in self.zone_cross_edges_array(zi) if x > 0])\n\n# ==================================================================================================\n\n\nclass Grid:\n \"\"\"\n Grid (Surface Unstructured).\n \"\"\"\n\n # ----------------------------------------------------------------------------------------------\n\n def __init__(self):\n \"\"\"\n Constructor.\n \"\"\"\n\n # Empty name.\n self.Name = ''\n\n # Mode.\n self.Mode = ''\n\n # Variables.\n self.VariablesStr = ''\n self.Variables = []\n self.FaceVariablesCount = 0\n\n # Set empty sets of nodes, faces, zones.\n self.Nodes = []\n self.Edges = []\n self.Faces = []\n self.Zones = []\n\n # Rounded coordinates\n self.RoundedCoordsBag = set()\n\n # ----------------------------------------------------------------------------------------------\n\n def clear(self):\n \"\"\"\n Clear grid.\n \"\"\"\n\n self.Nodes.clear()\n self.Edges.clear()\n self.Faces.clear()\n self.Zones.clear()\n self.RoundedCoordsBag.clear()\n\n # ----------------------------------------------------------------------------------------------\n\n def nodes_count(self):\n \"\"\"\n Get count of nodes.\n :return: nodes count\n \"\"\"\n\n return len(self.Nodes)\n\n # ----------------------------------------------------------------------------------------------\n\n def edges_count(self):\n \"\"\"\n Get count of edges.\n :return: edges count\n \"\"\"\n\n return len(self.Edges)\n\n # ----------------------------------------------------------------------------------------------\n\n def faces_count(self):\n \"\"\"\n Get count of faces.\n :return: faces count.\n \"\"\"\n\n return len(self.Faces)\n\n # ----------------------------------------------------------------------------------------------\n\n def faces_count_in_zones(self):\n \"\"\"\n Count of faces that are placed in zones.\n :return: total faces count in zones\n \"\"\"\n\n return sum([z.faces_count() for z in self.Zones])\n\n # ----------------------------------------------------------------------------------------------\n\n def faces_count_in_fixed_zones(self):\n \"\"\"\n Count of faces in fixed zones.\n :return: faces count in fixed zones\n \"\"\"\n\n return sum([z.faces_count() for z in self.Zones if z.IsFixed])\n\n # ----------------------------------------------------------------------------------------------\n\n def random_face(self):\n \"\"\"\n Get random face.\n :return: random face\n \"\"\"\n\n fc = self.faces_count()\n ind = random.randint(0, fc - 1)\n\n return self.Faces[ind]\n\n # ----------------------------------------------------------------------------------------------\n\n def print_info(self,\n is_print_edges_statistics=False,\n is_print_faces_distribution=False,\n is_print_zones_adjacency_matrix=False):\n \"\"\"\n Print information about grid.\n :param is_print_edges_statistics: flag for print edges statistics\n :param is_print_faces_distribution: flag for print faces distribution between zones\n :param is_print_zones_adjacency_matrix: flag for print zones adjacency matrix\n \"\"\"\n\n ec = self.edges_count()\n fc = self.faces_count()\n zc = len(self.Zones)\n\n print('GSU: {0}'.format(self.Name))\n print(' {0} nodes, {1} edges, '\n '{2} faces, {3} zones'.format(len(self.Nodes), ec, fc, zc))\n\n # Zones adjacency matrix.\n zam = ZonesAdjacencyMatrix(self.Edges, self.Zones)\n\n # Edges statistics.\n if is_print_edges_statistics:\n print(' ' + zam.edges_statistics_string())\n\n # Distribution faces between zones.\n if is_print_faces_distribution:\n print(' distribution faces between zones:')\n for zone in self.Zones:\n print(' {0} : {1} faces'.format(zone.Name, len(zone.Faces)))\n zones_faces_count = [len(zone.Faces) for zone in self.Zones]\n ideal_mean = len(self.Faces) / len(self.Zones)\n max_zone_faces_count = max(zones_faces_count)\n faces_distr_dev = 100.0 * (max_zone_faces_count - ideal_mean) / ideal_mean\n print(' ~ max zone faces {0}, '\n 'faces distribution deviation : {1:.2f}%'.format(max_zone_faces_count,\n faces_distr_dev))\n\n # Distribution edges between pairs of neighbours.\n if is_print_zones_adjacency_matrix:\n for i in range(zc + 1):\n print(' '.join(['{0:5}'.format(e) for e in zam.M[i]]))\n print(' ~ max cross-zones border length : {0}'.format(zam.max_cross_border_len()))\n\n # ----------------------------------------------------------------------------------------------\n\n def find_near_node(self, n):\n \"\"\"\n Find in grid nodes collection node that is near to a given node.\n :param n: node to check\n :return: near node from grid nodes collection\n \"\"\"\n\n # First try to find in bag.\n if n.RoundedCoords in self.RoundedCoordsBag:\n for node in self.Nodes:\n if node.is_near(n):\n return node\n raise Exception('We expect to find node ' \\\n 'with coordinates {0} in the grid'.format(n.RoundedCoords))\n\n return None\n\n # ----------------------------------------------------------------------------------------------\n\n def add_node(self, n, is_merge_same_nodes):\n \"\"\"\n Add node.\n :param n: node\n :param is_merge_same_nodes: flag merge same nodes\n :return: node registered in self.Nodes\n \"\"\"\n\n found_node = self.find_near_node(n)\n\n if (found_node is None) or (not is_merge_same_nodes):\n # There is no such node in the grid.\n # We have to add it.\n n.GloId = len(self.Nodes)\n self.Nodes.append(n)\n self.RoundedCoordsBag.add(n.RoundedCoords)\n return n\n else:\n # There is already such a node in the grid.\n # Just return it.\n return found_node\n\n # ----------------------------------------------------------------------------------------------\n\n def add_edge(self, e):\n \"\"\"\n Add edge to grid.\n :param e: edge\n :return: added edge\n \"\"\"\n\n # Just add edge with global id correction.\n e.GloId = len(self.Edges)\n self.Edges.append(e)\n\n return e\n\n # ----------------------------------------------------------------------------------------------\n\n def add_face(self, f):\n \"\"\"\n Add face.\n :param f: face\n :return: added face\n \"\"\"\n\n # Just correct global id and add.\n f.GloId = len(self.Faces)\n self.Faces.append(f)\n\n return f\n\n # ----------------------------------------------------------------------------------------------\n\n def set_zones_ids(self):\n \"\"\"\n Set zones identifiers.\n \"\"\"\n\n for (i, z) in enumerate(self.Zones):\n z.Id = i\n\n # ----------------------------------------------------------------------------------------------\n\n def reset_zones_ids(self):\n \"\"\"\n Reset zones identifiers.\n \"\"\"\n\n for z in self.Zones:\n z.Id = -1\n\n # ----------------------------------------------------------------------------------------------\n\n def link_node_edge(node, edge):\n \"\"\"\n Link node with edge.\n :param node: node\n :param edge: edge\n \"\"\"\n\n node.Edges.append(edge)\n edge.Nodes.append(node)\n\n # ----------------------------------------------------------------------------------------------\n\n def link_node_face(node, face):\n \"\"\"\n Link face with node.\n :param node: node\n :param face: face\n \"\"\"\n\n node.Faces.append(face)\n face.Nodes.append(node)\n\n # ----------------------------------------------------------------------------------------------\n\n def link_edge_face(edge, face):\n \"\"\"\n Link edge with face.\n :param edge: edge\n :param face: face\n \"\"\"\n\n # Check if it is enable to link the face with the edge.\n if len(edge.Faces) == 2:\n raise Exception('Too many faces linking with this edge ({0} - {1},'\n 'GloId = {2})'.format(edge.Nodes[0].P,\n edge.Nodes[1].P,\n edge.GloId))\n\n edge.Faces.append(face)\n face.Edges.append(edge)\n\n # ----------------------------------------------------------------------------------------------\n\n def find_edge(node_a, node_b):\n \"\"\"\n Find edge with given nodes.\n :param node_a: the first node\n :param node_b: the second node\n :return: edge - if it is found, None - otherwise\n \"\"\"\n\n for edge in node_a.Edges:\n if node_b in edge.Nodes:\n return edge\n\n return None\n\n # ----------------------------------------------------------------------------------------------\n\n def complex_link_face_node_node_edge(self, face, node_a, node_b):\n \"\"\"\n Complex link nodes with edge, and edge with face.\n :param face: face\n :param node_a: the first node\n :param node_b: th second node\n \"\"\"\n\n # First we need to find edge.\n edge = Grid.find_edge(node_a, node_b)\n\n if edge is None:\n # New edge and link it.\n edge = Edge()\n self.add_edge(edge)\n Grid.link_node_edge(node_a, edge)\n Grid.link_node_edge(node_b, edge)\n Grid.link_edge_face(edge, face)\n else:\n # Edge is already linked with nodes.\n # Link only with the face.\n Grid.link_edge_face(edge, face)\n\n # ----------------------------------------------------------------------------------------------\n\n def bfs_path_connectivity_component(self, start, pred):\n \"\"\"\n Connectivity component of BFS path from given face.\n :param start: start face\n :param pred: predicate for faces\n :return: path for one connectivity component (list of faces)\n \"\"\"\n\n # This function uses bfs_mark field for faces.\n\n if start.bfs_mark or not pred(start):\n # Start face does not satisfy conditions.\n return []\n\n # Initiate path.\n start.bfs_mark = True\n p = [start]\n i = 0\n\n # Walk.\n while i < len(p):\n f = p[i]\n for e in f.Edges:\n if not e.is_border():\n f2 = f.get_neighbour(e)\n if not f2.bfs_mark and pred(f2):\n f2.bfs_mark = True\n p.append(f2)\n i = i + 1\n\n return p\n\n # ----------------------------------------------------------------------------------------------\n\n def get_no_bfs_mark_face(self, pred):\n \"\"\"\n Get first no bfs mark face.\n :param pred: predicate for face\n :return: first face with false bfs mark\n \"\"\"\n\n for f in self.Faces:\n if not f.bfs_mark and pred(f):\n return f\n\n return None\n\n # ----------------------------------------------------------------------------------------------\n\n def bfs_path(self, start, pred):\n \"\"\"\n Get BFS path.\n :param start: start face\n :param pred: predicate for faces\n :return: path for whole grid (list of faces)\n \"\"\"\n\n # This function uses bfs_mark field for faces.\n\n # Reset all faces bfs marks.\n for f in self.Faces:\n f.bfs_mark = False\n\n p = []\n\n # Walk while we can.\n while True:\n p = p + self.bfs_path_connectivity_component(start, pred)\n start = self.get_no_bfs_mark_face(pred)\n if start is None:\n return p\n\n # ----------------------------------------------------------------------------------------------\n\n def load(self, filename,\n is_merge_same_nodes=True):\n \"\"\"\n Load grid from file.\n :param filename: file name\n :param is_merge_same_nodes: merge same nodes\n \"\"\"\n\n # Clear all objects of the grid.\n self.clear()\n\n # Open file and try to load it line by line.\n with open(filename, 'r') as f:\n line = f.readline()\n while line:\n\n if '# EXPORT_MODE=' in line:\n\n # Head of grid.\n mode_line = line\n title_line = f.readline()\n variables_line = f.readline()\n\n # Parse all and check.\n self.Mode = mode_line.split('=')[-1][:-1]\n if 'TITLE=' not in title_line:\n raise Exception('Wrong title line ({0}).'.format(title_line))\n self.Name = title_line.split('=')[1][1:-2]\n if 'VARIABLES=' not in variables_line:\n raise Exception('Wrong variables line ({0}).'.format(variables_line))\n self.VariablesStr = variables_line.split('=')[-1][:-1]\n self.Variables = self.VariablesStr.replace('\"', '').replace(',', '').split()\n self.FaceVariablesCount = len(self.Variables) - 3\n\n elif 'ZONE T=' in line:\n\n # Create new zone.\n zone_name = line.split('=')[-1][1:-2]\n zone = Zone(zone_name)\n self.Zones.append(zone)\n\n # Read count of nodes and faces to read.\n nodes_line = f.readline()\n faces_line = f.readline()\n packing_line = f.readline()\n zonetype_line = f.readline()\n varlocation_line = f.readline()\n if 'NODES=' not in nodes_line:\n raise Exception('Wrong nodes line ({0}).'.format(nodes_line))\n if 'ELEMENTS=' not in faces_line:\n raise Exception('Wrong faces line ({0}).'.format(faces_line))\n if 'DATAPACKING=BLOCK' != packing_line[:-1]:\n raise Exception('Wrong packing line ({0}).'.format(packing_line))\n if 'ZONETYPE=FETRIANGLE' != zonetype_line[:-1]:\n raise Exception('Wrong zonetype line ({0}).'.format(zonetype_line))\n right_varlocation_line = 'VARLOCATION=' \\\n '([4-{0}]=CELLCENTERED)'.format(len(self.Variables))\n if right_varlocation_line != varlocation_line[:-1]:\n raise Exception('Wrong varlocation line ({0}). '\n 'Right value is {1}'.format(varlocation_line,\n right_varlocation_line))\n nodes_to_read = int(nodes_line.split('=')[-1][:-1])\n # print('LOAD: zone {0}, nodes_to_read = {1}'.format(zone_name, nodes_to_read))\n faces_to_read = int(faces_line.split('=')[-1][:-1])\n\n # Read data for nodes.\n c = []\n for i in range(3):\n line = f.readline()\n c.append([float(xi) for xi in line.split()])\n for i in range(nodes_to_read):\n p = [c[0][i], c[1][i], c[2][i]]\n node = Node(p)\n node = self.add_node(node, is_merge_same_nodes)\n zone.add_node(node)\n\n # Read data for faces.\n d = []\n for i in range(self.FaceVariablesCount):\n line = f.readline()\n d.append([float(xi) for xi in line.split()])\n for i in range(faces_to_read):\n face = Face([d[j][i] for j in range(self.FaceVariablesCount)])\n self.add_face(face)\n zone.add_face(face)\n\n # Read connectivity lists.\n for i in range(faces_to_read):\n line = f.readline()\n face = zone.Faces[i]\n nodes = [zone.Nodes[int(ss) - 1] for ss in line.split()]\n if len(nodes) != 3:\n raise Exception('Wrong count of ' \\\n 'face linked nodes ({0}).'.format(len(nodes)))\n Grid.link_node_face(nodes[0], face)\n Grid.link_node_face(nodes[1], face)\n Grid.link_node_face(nodes[2], face)\n\n else:\n raise Exception('Unexpected line : {0}.'.format(line))\n\n line = f.readline()\n f.close()\n\n # Now we need to fix rest objects links.\n for face in self.Faces:\n node_a = face.Nodes[0]\n node_b = face.Nodes[1]\n node_c = face.Nodes[2]\n self.complex_link_face_node_node_edge(face, node_a, node_b)\n self.complex_link_face_node_node_edge(face, node_a, node_c)\n self.complex_link_face_node_node_edge(face, node_b, node_c)\n\n # Relink.\n self.link_nodes_and_edges_to_zones()\n\n # ----------------------------------------------------------------------------------------------\n\n def store(self, filename):\n \"\"\"\n Store grid to file.\n :param filename: file name\n \"\"\"\n\n with open(filename, 'w', newline='\\n') as f:\n\n # Store head.\n f.write('# EXPORT_MODE={0}\\n'.format(self.Mode))\n f.write('TITLE=\"{0}\"\\n'.format(self.Name))\n f.write('VARIABLES={0}\\n'.format(self.VariablesStr))\n\n # Additional structure for calculating local identifiers\n # of the nodes for connectivity lists storing.\n loc_ids = [-1] * len(self.Nodes)\n\n # Store zones.\n for zone in self.Zones:\n\n # Store zone head.\n f.write('ZONE T=\"{0}\"\\n'.format(zone.Name))\n f.write('NODES={0}\\n'.format(len(zone.Nodes)))\n f.write('ELEMENTS={0}\\n'.format(len(zone.Faces)))\n f.write('DATAPACKING=BLOCK\\n')\n f.write('ZONETYPE=FETRIANGLE\\n')\n f.write('VARLOCATION=([4-{0}]=CELLCENTERED)\\n'.format(len(self.Variables)))\n\n # Write first 3 data items (X, Y, Z coordinates).\n for i in range(3):\n f.write(zone.get_nodes_coord_slice_str(i) + ' \\n')\n\n # Write rest faces data items.\n for i in range(self.FaceVariablesCount):\n f.write(zone.get_faces_data_slice_str(i) + ' \\n')\n\n # Write connectivity lists.\n for i, node in enumerate(zone.Nodes):\n loc_ids[node.GloId] = i\n for face in zone.Faces:\n f.write(' '.join([str(loc_ids[n.GloId] + 1) for n in face.Nodes]) + '\\n')\n\n f.close()\n\n # ----------------------------------------------------------------------------------------------\n\n def store_mpi(self, filename_base, ts, sf='.cry'):\n \"\"\"\n Store grid for mpi program.\n As many processes count as zones count.\n :param filename_base: base of filename\n \"param ts: timestamp string\n :param sf: suffixes of files\n \"\"\"\n\n zam = ZonesAdjacencyMatrix(self.Edges, self.Zones)\n\n # Local identifiers.\n loc_nodes_ids = [-1] * len(self.Nodes)\n loc_edges_ids = [-1] * len(self.Edges)\n\n for (zi, z) in enumerate(self.Zones):\n with open('{0}_{1:05d}_{2}{3}'.format(filename_base, zi, ts, sf),\n 'w', newline='\\n') as file:\n\n nc = len(z.Nodes)\n ec = len(z.Edges)\n fc = len(z.Faces)\n\n # Write head information.\n file.write('TITLE=\"{0}\"\\n'.format(z.Name))\n variables = self.Variables[:3] + ['GloId'] + self.Variables[3:]\n variables = ['\"{0}\"'.format(x) for x in variables]\n variables_str = ', '.join(variables)\n file.write('VARIABLES={0}\\n'.format(variables_str))\n file.write('MPI={0}\\n'.format(zi))\n file.write('NODES={0}\\n'.format(nc))\n file.write('EDGES={0}\\n'.format(ec))\n file.write('CROSS-EDGES={0}\\n'.format(zam.zone_cross_edges_count(zi)))\n file.write('FACES={0}\\n'.format(fc))\n\n # Write nodes and faces data.\n file.write('NODES COORDINATES:\\n')\n for i in range(3):\n file.write(z.get_nodes_coord_slice_str(i) + ' \\n')\n file.write('FACES DATA:\\n')\n file.write(z.get_faces_global_ids_slice_str() + '\\n')\n for i in range(self.FaceVariablesCount):\n file.write(z.get_faces_data_slice_str(i) + ' \\n')\n\n # Write connectivity lists.\n for i, node in enumerate(z.Nodes):\n loc_nodes_ids[node.GloId] = i\n for i, edge in enumerate(z.Edges):\n loc_edges_ids[edge.GloId] = i\n file.write('FACE-NODE CONNECTIVITY LIST:\\n')\n for f in z.Faces:\n file.write(' '.join([str(loc_nodes_ids[n.GloId]) for n in f.Nodes]) + '\\n')\n file.write('FACE-EDGE CONNECTIVITY LIST:\\n')\n for f in z.Faces:\n file.write(' '.join([str(loc_edges_ids[e.GloId]) for e in f.Edges]) + '\\n')\n file.write('EDGE-NODE CONNECTIVITY LIST:\\n')\n for e in z.Edges:\n file.write(' '.join([str(loc_nodes_ids[n.GloId]) for n in e.Nodes]) + '\\n')\n\n # Write MPI-borders.\n file.write('MPI-BORDERS={0}\\n'.format(zam.zone_cross_borders_count(zi)))\n line = zam.zone_cross_edges_array(zi)\n for (li, le) in enumerate(line):\n if le > 0:\n # Border between zones with indices zi and li.\n lz = self.Zones[li]\n # Border between zones z and lz.\n file.write('[{0}] '.format(li))\n for e in z.Edges:\n if e.is_connect_zones(z, lz):\n file.write('{0} '.format(loc_edges_ids[e.GloId]))\n file.write('\\n')\n\n file.close()\n\n # ----------------------------------------------------------------------------------------------\n\n def link_nodes_and_edges_to_zones(self):\n \"\"\"\n Link nodes and edges to zones.\n \"\"\"\n\n # Clear old information.\n for z in self.Zones:\n z.Nodes.clear()\n z.Edges.clear()\n\n self.set_zones_ids()\n\n # Add nodes.\n for n in self.Nodes:\n zids = list(set([f.Zone.Id for f in n.Faces]))\n for zid in zids:\n self.Zones[zid].add_node(n)\n\n # Add edges.\n for e in self.Edges:\n zids = list(set([f.Zone.Id for f in e.Faces]))\n for zid in zids:\n self.Zones[zid].add_edge(e)\n\n self.reset_zones_ids()\n\n # ----------------------------------------------------------------------------------------------\n\n def unlink_faces_from_zones(self):\n \"\"\"\n Unlink faces from zones.\n \"\"\"\n\n for face in self.Faces:\n if not face.Zone.IsFixed:\n face.Zone = None\n\n # ----------------------------------------------------------------------------------------------\n\n def check_faces_are_linked_to_zones(self):\n \"\"\"\n Check if all faces are linked to zones.\n \"\"\"\n\n for face in self.Faces:\n if face.Zone is None:\n raise Exception('Unlinked face detected.')\n\n # ----------------------------------------------------------------------------------------------\n\n def decompose_mono(self, new_name=None):\n \"\"\"\n Create mono distribution (with 1 zone).\n :param new_name: grid new name\n \"\"\"\n\n if new_name is not None:\n self.Name = new_name\n\n # Delete all zones and create one zone with name 'mono'.\n self.Zones.clear()\n self.unlink_faces_from_zones()\n zone = Zone('mono')\n self.Zones.append(zone)\n for face in self.Faces:\n zone.add_face(face)\n\n # Link nodes.\n self.link_nodes_and_edges_to_zones()\n self.check_faces_are_linked_to_zones()\n\n # ----------------------------------------------------------------------------------------------\n\n def decompose_random(self, count=32, new_name=None):\n \"\"\"\n Create random distribution.\n :param count: zones count\n :param new_name: grid new name\n \"\"\"\n\n if new_name is not None:\n self.Name = new_name\n\n # Delete all zones.\n # Create 'count' zones and random distribute faces between them.\n self.Zones.clear()\n self.unlink_faces_from_zones()\n for i in range(count):\n zone = Zone('random ' + str(i))\n self.Zones.append(zone)\n for face in self.Faces:\n self.Zones[random.randint(0, count - 1)].add_face(face)\n\n # Link nodes.\n self.link_nodes_and_edges_to_zones()\n self.check_faces_are_linked_to_zones()\n\n # ----------------------------------------------------------------------------------------------\n\n def decompose_linear(self, count=32, new_name=None):\n \"\"\"\n Linear distribution.\n :param count: zones count\n :param new_name: grid new name\n \"\"\"\n\n if new_name is not None:\n self.Name = new_name\n\n fc = len(self.Faces)\n fcpz = fc // count\n fcrm = fc % count\n\n # Delete all zones.\n # Create 'count' zones and random distribute faces between them.\n self.Zones.clear()\n self.unlink_faces_from_zones()\n for i in range(count):\n zone = Zone('linear ' + str(i))\n self.Zones.append(zone)\n\n # Distribute faces accurately.\n cur_face_i = 0\n for (i, zone) in enumerate(self.Zones):\n faces_to_add = fcpz\n if i < fcrm:\n faces_to_add += 1\n for j in range(cur_face_i, cur_face_i + faces_to_add):\n zone.add_face(self.Faces[j])\n cur_face_i += faces_to_add\n if cur_face_i != fc:\n raise Exception('Wrong linera distribution mathematics.')\n\n # Link nodes.\n self.link_nodes_and_edges_to_zones()\n self.check_faces_are_linked_to_zones()\n\n # ----------------------------------------------------------------------------------------------\n\n def split_zone_metric(self, zone, zl, zr, fun):\n \"\"\"\n Split zone, calculate metric and roll-back.\n :param zone: zone\n :param zl: left child zone\n :param zr: right child zone\n :param fun: function for sign extraction\n :return: metric\n \"\"\"\n\n # Now all faces are in zone.\n signs = [fun(f) for f in zone.Faces]\n signs.sort()\n blade = signs[len(signs) // 2]\n\n # Distribute.\n zlc = 0\n zrc = 0\n for f in zone.Faces:\n if fun(f) < blade:\n f.Zone = zl\n zlc += 1\n else:\n f.Zone = zr\n zrc += 1\n\n # Prevent empty zone.\n if (zlc == 0) or (zrc == 0):\n return math.inf\n\n # Metric.\n r = 0\n for f in zone.Faces:\n for e in f.Edges:\n if len(e.Faces) == 2:\n ff = e.Faces[0]\n sf = e.Faces[1]\n if (ff.Zone == zl and sf.Zone == zr) or (ff.Zone == zr and sf.Zone == zl):\n r += 1\n\n # Roll back.\n for f in zone.Faces:\n f.Zone = zone\n\n return r\n\n # ----------------------------------------------------------------------------------------------\n\n def split_zone(self, zone, extract_signs_funs):\n \"\"\"\n Split zone.\n :param zone: zone\n :param extract_signs_funs: list of functions for extraction.\n \"\"\"\n\n # Do not split zone if it is fixed.\n if zone.IsFixed:\n self.Zones.remove(zone)\n self.Zones.append(zone)\n return\n\n # Do not split zone if it is impossible.\n if len(zone.Faces) < 2:\n print('Warning : not enough faces to split zone {0} ' \\\n '({1} faces).'.format(zone.Name, len(zone.Faces)))\n # Replace to the end.\n self.Zones.remove(zone)\n self.Zones.append(zone)\n return\n\n # Technical actions.\n zl = Zone(zone.Name + 'l')\n zr = Zone(zone.Name + 'r')\n self.Zones.remove(zone)\n self.Zones.append(zl)\n self.Zones.append(zr)\n\n # Explore metrics.\n metrics = [self.split_zone_metric(zone, zl, zr, extract_signs_funs[i])\n for i in range(len(extract_signs_funs))]\n min_metric = min(metrics)\n\n if min_metric is math.inf:\n print('Warning : bad metrics to split zone {0}'.format(zone.Name))\n # Replace to the end.\n self.Zones.remove(zone)\n self.Zones.append(zone)\n return\n\n spl_index = metrics.index(min_metric)\n\n # Split.\n signs = [extract_signs_funs[spl_index](f) for f in zone.Faces]\n signs.sort()\n blade = signs[len(signs) // 2]\n\n for face in zone.Faces:\n if extract_signs_funs[spl_index](face) < blade:\n zl.add_face(face)\n else:\n zr.add_face(face)\n\n # ----------------------------------------------------------------------------------------------\n\n def decompose_hierarchical(self, extract_signs_funs, levels=6, new_name=None, fixed_zones=[]):\n \"\"\"\n Hierarchical distribution with given numbers of levels.\n :param extract_signs_funs: list of functions for signs extraction\n :param levels: levels count\n :param new_name: grid new name\n :param fixed_zones: list of fixed zones\n \"\"\"\n\n # Mark fixed zones.\n for z in self.Zones:\n z.IsFixed = z.Name in fixed_zones\n\n if new_name is not None:\n self.Name = new_name\n\n # Delete all zones (not fixed) and links.\n self.Zones = [z for z in self.Zones if z.IsFixed]\n self.unlink_faces_from_zones()\n\n # Check levels.\n if levels < 1:\n raise Exception('It must be at least 1 level.')\n\n zone = Zone('h')\n self.Zones.append(zone)\n for face in self.Faces:\n if face.Zone is None:\n zone.add_face(face)\n\n for li in range(levels - 1):\n c = len(self.Zones)\n for zi in range(c):\n # nm = self.Zones[0].Name\n # print('split zone {0} -> {1}, {2}.'.format(nm, nm + 'l', nm + 'r'))\n self.split_zone(self.Zones[0], extract_signs_funs)\n\n # Links nodes.\n self.link_nodes_and_edges_to_zones()\n self.check_faces_are_linked_to_zones()\n\n # ----------------------------------------------------------------------------------------------\n\n def each_zone_capture_nearest_face(self):\n \"\"\"\n Each zone capture nearest face.\n \"\"\"\n\n for z in self.Zones:\n z.capture_nearest_face()\n\n # ----------------------------------------------------------------------------------------------\n\n def decompose_pressure(self, count=32, new_name=None, fz_names=[]):\n \"\"\"\n Create distribution based on pressure algorithm.\n :param count: zones count\n :param new_name: grid new name\n :param fz_names: list of fixed zones names\n \"\"\"\n\n # Mark fixed zones.\n for z in self.Zones:\n z.IsFixed = z.Name in fz_names\n\n if new_name is not None:\n self.Name = new_name\n\n # Keep fixed zones and create additional.\n self.Zones = [z for z in self.Zones if z.IsFixed]\n fz_count = len(self.Zones)\n self.unlink_faces_from_zones()\n for i in range(count):\n zone = Zone('pressure ' + str(i))\n self.Zones.append(zone)\n\n #\n # Distribute faces between zones.\n #\n\n fc = self.faces_count() - self.faces_count_in_fixed_zones()\n zone_sizes = [fc // count + (fc % count > i) for i in range(count)]\n\n # Put right number of faces into each zone.\n start = self.Faces[0]\n for i in range(count):\n z = self.Zones[i + fz_count]\n zone_size = zone_sizes[i]\n path = self.bfs_path(start, lambda f: (f.Zone is None))\n for fi in range(zone_size):\n z.add_face(path[fi])\n if len(path) > zone_size:\n start = path[zone_size]\n\n # Link nodes.\n self.link_nodes_and_edges_to_zones()\n self.check_faces_are_linked_to_zones()\n\n # ----------------------------------------------------------------------------------------------\n\n def box(self):\n \"\"\"\n Get box around grid (tuple with 6 values - XYZ of the left down back point\n and XYZ of the right up front point).\n :return: tuple\n \"\"\"\n\n xs = [n.P[0] for n in self.Nodes]\n ys = [n.P[1] for n in self.Nodes]\n zs = [n.P[2] for n in self.Nodes]\n\n return min(xs), min(ys), min(zs), max(xs), max(ys), max(zs)\n\n # ----------------------------------------------------------------------------------------------\n\n def move_from_mean_point(self, k=0.1):\n \"\"\"\n Move zones from mean point.\n :param k: factor while zones moving\n \"\"\"\n\n gx, gy, gz = mean_nodes_point(self.Nodes)\n\n for z in self.Zones:\n zx, zy, zz = mean_nodes_point(z.Nodes)\n vx, vy, vz = k * (zx - gz), k * (zy - gy), k * (zz - gz)\n for n in z.Nodes:\n p = n.P\n n.P = (p[0] + vx, p[1] + vy, p[2] + vz)\n\n # ----------------------------------------------------------------------------------------------\n\n def store_faces_calc_data(self, filename):\n \"\"\"\n Store calc values to file.\n :param filename: name of file\n \"\"\"\n\n with open(filename, 'w', newline='\\n') as f:\n f.write('VARIABLES=\"GloId\", \"T\", \"Hw\", \"Hi\"\\n')\n for face in self.Faces:\n p = mean_nodes_point(face.Nodes)\n f.write(face.get_glo_id_t_hw_hi_str() + '\\n')\n f.close()\n\n # ----------------------------------------------------------------------------------------------\n\n def load_faces_calc_data(self, filename):\n \"\"\"\n Load calc data from file and write it to grid.\n\n Warning!\n This function rewrite VARIABLES list of grid.\n\n :param filename: name of file\n \"\"\"\n\n with open(filename, 'r') as f:\n line = f.readline()\n\n while line:\n\n if 'VARIABLES=' in line:\n\n # Set new variables.\n\n variables_xyz = '\"X\", \"Y\", \"Z\"'\n variables_oth = line.split('=')[-1][9:-1]\n\n # We know only basic modes.\n if variables_oth == '\"T\", \"Hw\", \"Hi\"':\n self.Mode = 'BASIC'\n elif variables_oth == '\"T\", \"Hw\", \"Hi\", \"HTC\", \"Beta\", \"TauX\", \"TauY\", \"TauZ\"':\n self.Mode = 'CHECK_POINT'\n elif variables_oth == '\"MassImpinged\", \"WaterFilmHeight\", \"CurrentIceGrowth\", ' \\\n '\"TotalIceGrowth\", \"CurrentMassEvaporation\", ' \\\n '\"SurfaceTemperature\", ' \\\n '\"FilmVx\", \"FilmVy\", \"FilmVz\", \"FilmV\", ' \\\n '\"IcesolConvectiveFlux\", ' \\\n '\"EvapHeatFlux\", \"IceThickness\", \"HTC\"':\n self.Mode = 'CIAM'\n else:\n raise Exception('unknown export mode')\n\n self.VariablesStr = variables_xyz + ', ' + variables_oth\n self.Variables = self.VariablesStr.replace('\"', '').replace(',', '').split()\n self.FaceVariablesCount = len(self.Variables) - 3\n\n else:\n ss = line.split()\n glo_id = int(ss[0])\n ss = ss[1:]\n face = self.Faces[glo_id]\n face.Data = [float(x) for x in ss]\n\n line = f.readline()\n\n f.close()\n\n# ==================================================================================================\n","sub_path":"src/gsu.py","file_name":"gsu.py","file_ext":"py","file_size_in_byte":58406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"440298324","text":"import codecs #Overriding utf-8\ndef open(path, mode):\n return codecs.open(path, mode, 'utf-8')\n\n\n\n# import all needed modules\nimport time\nfrom bs4 import BeautifulSoup\nimport requests\nfrom PyQt5.QtMultimedia import QMediaPlayer, QMediaContent\nfrom PyQt5.QtCore import QUrl, QFileInfo\n\n\n# define those variables for notification\naudioFile = r\"C:\\Users\\Grzegorz\\PycharmProjects\\parser\\parser\\alert.mp3\"\nplayer = QMediaPlayer()\nplayer.setMedia(QMediaContent(QUrl.fromLocalFile(QFileInfo(audioFile).absoluteFilePath())))\n\n\ndef parser (site):\n \"\"\" Function for parsing information from web-sites\"\"\"\n response = requests.get(site)\n\n soup = BeautifulSoup(response.content, \"html.parser\")\n\n content = soup.find('div', {\"class\": \"content\"}) # Getting 'row' information for parsing\n\n for row in content.find_all('div', {\"class\": \"entry\"}):\n title = row.find_all('h3', {'class': \"entry__title\"})\n description = row.find_all('div', {\"class\": \"entry__content\"})[0].text[:-7]\n link_beta = str(row.find_all('h3', {'class': \"entry__title\"}))[35:]\n a = link_beta.index('\"')\n link = link_beta[:a]\n photo = row.find('img', {'class': 'wp-post-image'}).attrs[\"src\"]\n full = (photo[2:] + '\\n\\n' + '🌎 ' + title[0].text + '\\n\\n' + '📎 ' + description + '\\n\\n' +\n '📌 ' + link + '\\n\\n\\n\\n')\n\n result1 = open(\"fly4free.txt\", \"r\").readlines()\n check = str(result1).find(full[:50]) # Check existence information in my \"parsed collections\"\n if check == -1:\n result1.insert(0, full)\n result = open(\"fly4free.txt\", \"w\")\n for line in result1:\n result.write(line)\n result.close()\n player.play()\n\nwhile True: # \"fake\" automation\n parser(\"http://www.fly4free.pl\")\n parser(\"http://www.fly4free.com/flights/flight-deals/europe/\")\n time.sleep(60)\n","sub_path":"parser/fly4free.py","file_name":"fly4free.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"121177060","text":"\"\"\"Module for the graphical elements of the ui.\"\"\"\nimport logging\n\n# import board\n# import neopixel\nimport pygame\nfrom gpiozero import LED\n\n# BCM pin number of the left LED.\nL_LED_PIN = 5\n\n# BCM pin number of the right LED.\nR_LED_PIN = 6\n\nleftLED = LED(L_LED_PIN)\nrightLED = LED(R_LED_PIN)\n\n# pixels = neopixel.NeoPixel(board.D18, 16)\n\n\nclass Themeable():\n \"\"\"Quasi-interface to indicate that a ui_element is themable.\n\n Parameters\n ----------\n theme : dict\n Dictionary with the key-values describing colors to use in the ui.\n\n \"\"\"\n\n def __init__(self, theme):\n \"\"\"Create a new themable object.\"\"\"\n self.theme = theme\n\n\nclass Gauge(Themeable):\n \"\"\"Quasi-abstract class that holds common functionality for everything that can be described as a gauge.\n\n Parameters\n ----------\n surface : pygame.surface\n The screen surface that will ultimately be written to.\n\n canResource : can_read.CanResource\n A single \"channel\" within a compound can message that data is pulled from.\n\n theme : dict\n Dictionary with the key-values describing colors to use in the ui.\n\n x_coord : int\n The x coord of the top left of the ui_element as referenced from the top left of the screen.\n\n y_coord : int\n The y coord of the top left of the ui_element as referenced from the top left of the screen.\n\n label : string\n The label for a gauge if applicable.\n\n unit : string\n Unit of the gauge if applicable.\n\n min_value : int\n The minimum value a gauge can take on.\n\n max_value int\n The maximum value a gauge can take on.\n\n \"\"\"\n\n def __init__(self, surface, canResource, theme, x_coord=0, y_coord=0,\n label=\"no name\", unit=\"\", min_val=0, max_val=1):\n \"\"\"Create a new instance of Gauge.\"\"\"\n super().__init__(theme)\n self.surface = surface\n self.x_coord = x_coord\n self.y_coord = y_coord\n self.label = label\n self.canResource = canResource\n self.unit = unit\n self.min = min_val\n self.max = max_val\n self.theme = theme\n\n self.value = min_val\n\n def updateElement(self):\n \"\"\"Update the gauge with the current value of the can channel.\"\"\"\n self.value = self.canResource.getValue()\n self.draw()\n\n def draw(self):\n \"\"\"Draw the gauge to the screen surface. This will be unique to the implemenation.\"\"\"\n pass\n\n\n# Vertical bar gauge.\nclass BarGauge(Gauge):\n \"\"\"Bar style gauge for displaying critical information.\n\n Parameters\n ----------\n surface : pygame.surface\n The screen surface that will ultimately be written to.\n\n canResource : can_read.CanResource\n A single \"channel\" within a compound can message that data is pulled from.\n\n theme : dict\n Dictionary with the key-values describing colors to use in the ui.\n\n x_coord : int\n The x coord of the top left of the ui_element as referenced from the top left of the screen.\n\n y_coord : int\n The y coord of the top left of the ui_element as referenced from the top left of the screen.\n\n label : string\n The label for a gauge if applicable.\n\n unit : string\n Unit of the gauge if applicable.\n\n min_value : int\n The minimum value a gauge can take on.\n\n max_value : int\n The maximum value a gauge can take on.\n\n kwargs : dict\n A dictionary of any parameters not explicitly used by the BarGauge.\n\n \"\"\"\n\n # Number of pixels wide the gauge is.\n GAUGE_WIDTH = 40\n\n # Number of pixels high the gauge is.\n GAUGE_HEIGHT = 200\n\n # Number of pixels in the gauge outline.\n GAUGE_OUTLINE_WIDTH = 5\n\n # Size of the text in the gauge.\n TEXT_SIZE = 24\n\n def __init__(self, surface, canResource, theme, x_coord=0, y_coord=0,\n label=\"no name\", unit=\"\", min_val=0, max_val=1, **kwargs):\n \"\"\"Create a new BarGauge.\"\"\"\n super().__init__(surface, canResource, theme, x_coord=x_coord, y_coord=y_coord,\n label=label, unit=unit, min_val=min_val, max_val=max_val)\n\n def draw(self):\n \"\"\"Draw the graphical elements of the BarGauge.\"\"\"\n # Label\n labelFont = pygame.font.Font('freesansbold.ttf', self.TEXT_SIZE)\n labelText = labelFont.render(self.label, False, self.theme['PRIMARY_COLOR'])\n self.surface.blit(\n labelText,\n (self.x_coord + self.GAUGE_WIDTH / 2 - labelText.get_width() / 2, self.y_coord + self.GAUGE_HEIGHT)\n )\n\n # Gauge fill\n valueRange = self.max - self.min\n gaugePercentage = self.value / valueRange\n fillHeight = min(self.GAUGE_HEIGHT, round(gaugePercentage * self.GAUGE_HEIGHT))\n fillCoords = (self.x_coord, self.y_coord + self.GAUGE_HEIGHT - fillHeight)\n fillRect = pygame.Rect(fillCoords, (self.GAUGE_WIDTH, fillHeight))\n pygame.draw.rect(self.surface, self.theme['BAR_GAUGE_FILL'], fillRect)\n\n # Outline\n outlineRect = pygame.Rect((self.x_coord, self.y_coord), (self.GAUGE_WIDTH, self.GAUGE_HEIGHT))\n pygame.draw.rect(self.surface, self.theme['PRIMARY_COLOR'], outlineRect, self.GAUGE_OUTLINE_WIDTH)\n\n # Exact readout\n readoutFont = pygame.font.Font('freesansbold.ttf', self.TEXT_SIZE)\n readoutText = readoutFont.render(f'{int(self.value)} {self.unit}', False, self.theme['PRIMARY_COLOR'])\n self.surface.blit(\n readoutText,\n (self.x_coord + self.GAUGE_WIDTH / 2 - readoutText.get_width() / 2, self.y_coord - readoutText.get_height())\n )\n\n\nclass GearDisplay(Gauge):\n \"\"\"Large gear display in the center of the screen.\n\n Parameters\n ----------\n surface : pygame.surface\n The screen surface that will ultimately be written to.\n\n canResource : can_read.CanResource\n A single \"channel\" within a compound can message that data is pulled from.\n\n theme : dict\n Dictionary with the key-values describing colors to use in the ui.\n\n kwargs : dict\n Key words arguments that are optionally passed. None are used for gear display.\n\n \"\"\"\n\n # Text size of the gear readout.\n GEAR_SIZE = 256\n\n def __init__(self, surface, canResource, theme, **kwargs):\n \"\"\"Create a new GearDisplay instance.\"\"\"\n super().__init__(surface, canResource, theme)\n\n def draw(self):\n \"\"\"Draw the graphical elements of the GearDisplay.\"\"\"\n gearFont = pygame.font.Font('freesansbold.ttf', self.GEAR_SIZE)\n gearText = gearFont.render(str(int(self.value)), False, self.theme['PRIMARY_COLOR'])\n self.surface.blit(gearText, (self.surface.get_width() / 2 - gearText.get_width() / 2,\n self.surface.get_height() / 2 - gearText.get_height() / 2))\n\n\nclass VoltageBox(Gauge):\n \"\"\"Voltage box in the upper left corner of the display.\n\n Parameters\n ----------\n surface : pygame.surface\n The screen surface that will ultimately be written to.\n\n canResource : can_read.CanResource\n A single \"channel\" within a compound can message that data is pulled from.\n\n theme : dict\n Dictionary with the key-values describing colors to use in the ui.\n\n kwargs : dict\n A dictionary of any parameters not explicitly used by the VoltageBox.\n\n \"\"\"\n\n # Number of pixels in the border.\n BORDER_THICKNESS = 5\n\n # Size of the text.\n TEXT_SIZE = 64\n\n def __init__(self, surface, canResource, theme, **kwargs):\n \"\"\"Create a new voltage box instance.\"\"\"\n super().__init__(surface, canResource, theme)\n\n def draw(self):\n \"\"\"Draw the graphical elements onto the screen.\"\"\"\n backgroundRect = pygame.Rect((0, 0), (150, 80))\n pygame.draw.rect(self.surface, self.theme['VOLTAGE_BOX_BACKGROUND'], backgroundRect)\n backgroundOutline = pygame.Rect((0, 0), (150, 80))\n pygame.draw.rect(self.surface, self.theme['PRIMARY_COLOR'], backgroundOutline, self.BORDER_THICKNESS)\n voltageFont = pygame.font.Font('freesansbold.ttf', self.TEXT_SIZE)\n voltageText = voltageFont.render(str(self.value), False, self.theme['PRIMARY_COLOR'])\n self.surface.blit(voltageText, (10, 5))\n\n\nclass RPM_Display(Gauge):\n \"\"\"RPM readout at the top center of the screen.\n\n Parameters\n ----------\n surface : pygame.surface\n The screen surface that will ultimately be written to.\n\n canResource : can_read.CanResource\n A single \"channel\" within a compound can message that data is pulled from.\n\n theme : dict\n Dictionary with the key-values describing colors to use in the ui.\n\n kwargs : dict\n A dictionary of any parameters not explicitly used by the RPM_Display.\n \"\"\"\n\n # Size of the text.\n TEXT_SIZE = 64\n\n # Vertical distance, in pixels, from the top of the screen.\n VERTICAL_POS = 10\n\n # Number of Neopix LEDS.\n TOTAL_NEOPIX_LEDS = 16\n\n # Array for the color of the shift lights at different levels.\n GREEN = (50, 168, 82)\n YELLOW = (247, 255, 5)\n RED = (255, 5, 5)\n BLUE = (5, 59, 255)\n NEOPIX_COLOR_ARRAY = [\n GREEN, GREEN, YELLOW,\n YELLOW, RED, RED,\n BLUE, BLUE\n ]\n\n def __init__(self, surface, canResource, theme, threshold_val=10000, max_val=13000, **kwargs):\n \"\"\"Create a new RPM_Display.\"\"\"\n self.threshold = threshold_val\n super().__init__(surface, canResource, theme, max_val=max_val)\n\n def draw(self):\n \"\"\"Draw the graphical elements onto the screen.\"\"\"\n self.updateNeoPixels()\n rpmFont = pygame.font.Font('freesansbold.ttf', self.TEXT_SIZE)\n rpmText = rpmFont.render(f'{int(self.value)} RPM', False, self.theme['PRIMARY_COLOR'])\n self.surface.blit(rpmText, (self.surface.get_width() / 2 - rpmText.get_width() / 2, self.VERTICAL_POS))\n\n def updateNeoPixels(self):\n \"\"\"Update the neopixel sticks with the RPM.\"\"\"\n pct = (self.value - self.threshold) / (self.max - self.threshold)\n # pct = max(pct, 0)\n # pct = min(pct, 1)\n # numLeds = round(pct * self.TOTAL_NEOPIX_LEDS / 2)\n # for i in range(0, numLeds):\n # pixels[i] = self.NEOPIX_COLOR_ARRAY[i]\n # for i in range (self.TOTAL_NEOPIX_LEDS - 1, self.TOTAL_NEOPIX_LEDS - 1 - numLeds, -1):\n # colorIndex = self.TOTAL_NEOPIX_LEDS - i - 1\n # pixels[i] = self.NEOPIX_COLOR_ARRAY[colorIndex]\n\n\nclass DriverWarning(Themeable):\n \"\"\"A warning icon that will apprear if a given conditional is encountered.\n\n Parameters\n ----------\n surface : pygame.surface\n The screen surface that will ultimately be written to.\n\n channels : dict\n A dictionary of canResources with items in the following format:\n {channel_name: canResource}\n\n theme : dict\n Dictionary with the key-values describing colors to use in the ui.\n\n x_coord : int\n x_coord of the warning. Default = 0\n\n y_coord : int\n y_coord of the warning. Default = 0\n\n conditionals : list\n A list of conditionals in the form [can_channel] [operator] [value]. These\n values are space delimited.\n\n imagePath : string\n That path used by the warning to load the image for the warning.\n\n kwargs : dict\n Extra key word arguments.\n\n \"\"\"\n\n # List of valid conditional operators.\n OPERATORS = [\"<\", \">\", \"<=\", \">=\"]\n\n # Create steering_wheel logger.\n wheelLogger = logging.getLogger('wheelLogger')\n\n # Text size under warning.\n TEXT_SIZE = 14\n\n # Max length of warning text before truncating.\n TEXT_TRUNCATE_LENGTH = 9\n\n def __init__(self, surface, channels, theme, x_coord=0, y_coord=0, conditionals=[], imagePath=\"\", **kwargs):\n \"\"\"Create a new driver warning.\"\"\"\n super().__init__(theme)\n self.surface = surface\n self.channels = channels\n self.x_coord = x_coord\n self.y_coord = y_coord\n self.imagePath = imagePath\n self.image = pygame.image.load(self.imagePath)\n self.rules = []\n self.addConditions(conditionals)\n\n def updateElement(self):\n \"\"\"Check the list of conditionals and draw the icon if needed.\"\"\"\n status = self.checkRules()\n if status == 1:\n leftLED.on()\n self.draw()\n elif status == 2:\n leftLED.on()\n rightLED.on()\n self.draw()\n else:\n leftLED.off()\n rightLED.off()\n\n def draw(self):\n \"\"\"Draw the graphical elements to the surface for this icon.\"\"\"\n self.surface.blit(self.image, (self.x_coord, self.y_coord))\n\n def addConditions(self, conditionals):\n \"\"\"Parse the list of conditionals passed, adding them to an internal list of rules.\n\n Parameters\n ----------\n conditionals : list\n List of conditonals as strings that will get parsed. These conditionals\n will be in the form {can_channel} {operator} {value}. They will be\n space delimited for easy parsing.\n\n \"\"\"\n for condition in conditionals:\n parsedValues = condition.split()\n channel = parsedValues[0]\n operator = parsedValues[1]\n value = parsedValues[2]\n isCritical = len(parsedValues) == 4 and parsedValues[3] == \"critical\"\n if channel not in self.channels.keys() or operator not in self.OPERATORS:\n print(f\"Invalid contional: {condition}\")\n exit(1)\n self.rules.append([self.channels[channel], operator, value, isCritical])\n\n def checkRules(self):\n \"\"\"Check the rules of this warning against updated values of the can channels.\n\n Returns\n -------\n int\n 0 if no rules are met, 1 if a warning is met, and 2 if a critical rule is met.\n\n \"\"\"\n rtn = 0\n for rule in self.rules:\n if eval(f\"{rule[0].getValue()} {rule[1]} {rule[2]}\") and rule[3]:\n self.wheelLogger.warning(f\"{rule[0].name} {rule[1]} {rule[2]}\")\n # Put the rule's can channel below the warning.\n rpmFont = pygame.font.Font('freesansbold.ttf', self.TEXT_SIZE)\n rpmText = rpmFont.render(f\"{rule[0].name[:self.TEXT_TRUNCATE_LENGTH]}\", False,\n self.theme['PRIMARY_COLOR'])\n self.surface.blit(rpmText, (self.x_coord, self.y_coord + self.image.get_height()))\n rtn = 2\n elif eval(f\"{rule[0].getValue()} {rule[1]} {rule[2]}\"):\n self.wheelLogger.warning(f\"{rule[0].name} {rule[1]} {rule[2]}\")\n # Put the rule's can channel below the warning.\n rpmFont = pygame.font.Font('freesansbold.ttf', self.TEXT_SIZE)\n rpmText = rpmFont.render(f\"{rule[0].name[:self.TEXT_TRUNCATE_LENGTH]}\", False,\n self.theme['PRIMARY_COLOR'])\n self.surface.blit(rpmText, (self.x_coord, self.y_coord + self.image.get_height()))\n rtn = 1\n return rtn\n\n\nclass Background(Themeable):\n \"\"\"Viper-inspired background animation that activates between a given RPM threshold.\n\n Parameters\n ----------\n surface : pygame.surface\n The screen surface that will ultimately be written to.\n\n canResource : can_read.CanResource\n A single \"channel\" within a compound can message that data is pulled from.\n\n theme : dict\n Dictionary with the key-values describing colors to use in the ui.\n\n imagePath : string\n Path to the file to use as the background image.\n\n min_val : int\n Minimum value that the effect begins.\n\n max_val : int\n Maximum value of the effect.\n\n kwargs : dict\n Extra key word arguments.\n\n \"\"\"\n\n def __init__(self, surface, canResource, theme, imagePath=\"\", min_val=0, max_val=1, **kwargs):\n \"\"\"Create a new Background object.\"\"\"\n super().__init__(theme)\n self.surface = surface\n self.canResource = canResource\n self.imagePath = imagePath\n self.min_val = min_val\n self.max_val = max_val\n self.value = 0\n self.image = pygame.image.load(self.imagePath)\n\n def updateElement(self):\n \"\"\"Check to see if the background is white, if so draw the background animation.\"\"\"\n if self.theme['BACKGROUND_COLOR'] == pygame.Color(\"white\"):\n self.value = self.canResource.getValue()\n self.draw()\n\n def draw(self):\n \"\"\"Calculate the proper alpha (transparency) and draw the background.\"\"\"\n alpha = (self.value - self.min_val)/(self.max_val - self.min_val) * 255\n alpha = max(alpha, 0)\n alpha = min(alpha, 255)\n self.image.set_alpha(alpha)\n self.surface.blit(self.image, (0, 0))\n","sub_path":"ui_utils.py","file_name":"ui_utils.py","file_ext":"py","file_size_in_byte":16833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"400101256","text":"from tkinter import LabelFrame, Frame, Label\nfrom random import shuffle\nfrom Set.SetMain import Card\n\n\ndef start(self):\n self.gameState = 2\n self.puzSols = []\n self.message.config(text =\"0 of 6 sets found.\")\n\n self.start_shared() \n self.fieldFrame.config(text = \"Puzzle Mode\")\n self.foundSets = LabelFrame(self.gameFrame, text=\"Sets Found\")\n self.foundSets.grid(row=0, column=1, padx=(0,40))\n self.fsFrame = Frame(self.foundSets, bg=\"black\")\n self.fsFrame.pack()\n self.scoreboard.config(text = \"\")\n self.deckStatus.config(text = \"\")\n for ii in range(6):\n for jj in range(3):\n img = self.empty.subsample(2,2)\n self.fsLabel = Label(self.fsFrame, image=img, bg=\"white\")\n self.fsLabel.image = img #necessary to prevent image from being GC'd\n self.fsLabel.grid(row=ii, column=jj, padx=2, pady=2)\n puz_build(self)\n for ii in range(3):\n for jj in range(4):\n self.field[ii][jj].card = self.puzField.pop()\n self.update_card(ii,jj)\n\n\ndef puz_build(self):\n def the_set_maker(givenCards):\n resCard = Card(1, \"r\", \"e\", \"S\")\n cardsAttrSwitcher = {\n \"number\": ({card.number for card in givenCards}, {1, 2, 3}),\n \"color\": ({card.color for card in givenCards}, {\"r\", \"g\", \"p\"}),\n \"shading\": ({card.shading for card in givenCards}, {\"e\", \"h\", \"f\"}),\n \"shape\": ({card.shape for card in givenCards}, {\"S\", \"D\", \"O\"})\n }\n for attr, attrSets in cardsAttrSwitcher.items():\n cardAttrSet = attrSets[0]\n fullAttrSet = attrSets[1]\n if len(cardAttrSet) == 2:\n # it'll be the third unique attr val\n setattr(resCard, attr, (fullAttrSet - cardAttrSet).pop())\n else:\n # len(cardAttrSet) == 1 and it'll be the same attr val\n setattr(resCard, attr, cardAttrSet.pop())\n return resCard\n\n def sets_made_by_dealing(dealCard):\n setsMade = []\n for card1 in self.puzField:\n for card2 in [card for card in self.puzField if card != card1]:\n if the_set_maker([card1, card2]) == dealCard and {card1, card2, dealCard} not in setsMade:\n setsMade.append({card1, card2, dealCard})\n return len(setsMade)\n \n self.puzField = []\n deck = [Card(w,x,y,z) for w in self.numbers for x in self.colors for y in self.shadings for z in self.shapes]\n shuffle(deck)\n for _ in range(6):\n self.puzField.append(deck.pop()) # add cards until there are 6 in the field\n\n while len(self.puzField) < 12:\n nSets = len(self.sets_finder(self.puzField))\n nField = len(self.puzField)\n print(f\"{nField} in field, {nSets} sets.\")\n if nSets == 6:\n # deal as to not increase nSets\n for ii, dealCard in enumerate(deck):\n if sets_made_by_dealing(dealCard) == 0:\n break\n else:\n # deal as to increase nSets, but never to > 6\n for ii, dealCard in enumerate(deck):\n setsMade = sets_made_by_dealing(dealCard)\n if setsMade > 0 and nSets + setsMade <= 6:\n print(f\"plus {setsMade} sets\")\n break\n self.puzField.append(deck.pop(ii))\n nSets = len(self.sets_finder(self.puzField))\n nField = len(self.puzField)\n print(f\"{nField} in field, {nSets} sets.\")\n\n\ndef update_found_sets(self):\n ii = 0\n heldsSet = list(self.helds)\n for imgLbl in self.fsFrame.winfo_children():\n # NB: score is incremented AFTER this method gets called\n if ii < self.score*3:\n ii += 1\n elif ii < self.score*3 + 3:\n card = heldsSet[ii - self.score*3]\n img = self.imgDict[str(card.number) + card.color + card.shading + card.shape].subsample(2,2)\n imgLbl.config(image= img)\n imgLbl.image = img\n ii += 1\n else:\n break\n\n\ndef found_a_set(self):\n if frozenset(self.helds) not in self.puzSols:\n self.puzSols.append(frozenset(self.helds)) #these need to be made immutable or they get overwritten\n update_found_sets(self)\n self.score += 1\n self.messageFrame.after_cancel(self.msgUpdate)\n self.message.config(text= str(self.score) + \" of 6 sets found.\")\n else:\n self.messageFrame.after_cancel(self.msgUpdate)\n self.message.config(text= \"Already found that set ...\")\n self.msgUpdate = self.messageFrame.after(2000, self.reset_message, str(self.score) + \" of 6 sets found.\")\n if self.score > 5:\n self.game_over()\t\n self.helds = set()","sub_path":"Set/PuzzleMode.py","file_name":"PuzzleMode.py","file_ext":"py","file_size_in_byte":4718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"607063117","text":"from django.urls import path\nfrom django.contrib.auth.views import LoginView, LogoutView\n\nfrom .views import *\n\nurlpatterns = [\n path('', LoginView.as_view(\n redirect_authenticated_user=True,\n ), name=\"login\"),\n\n path('logout/', LogoutView.as_view(\n next_page=\"profile\"\n ), name=\"logout\"),\n \n path('profile/', profile_view, name='profile'),\n path('category/', category_view, name='category'),\n path('calendar/sport/', calendar_view, name=\"sport_schedule_calendar\"),\n\n path('form/meg_group', process_med_group_form, name=\"process_med_group_form\"),\n]\n","sub_path":"adminpage/sport/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"517415157","text":"\"\"\"\nThis is for annotation parsing for frame training.\n\nCreated On 9th March, 2020\nAuthor: Xiaoyu Yang\n\"\"\"\n\nimport os\nimport json\nimport pandas as pd\nfrom glob import glob\nimport argparse\nfrom tqdm import tqdm\n\ndef generate_meta_csv(file_path: str, saving_path: str):\n \"\"\"\n return:\n foldername, filename, label, original, split\n used for match with frame info\n \"\"\"\n file_list = []\n for file in tqdm(glob(os.path.join(file_path, \"*.csv\"))):\n res_df = pd.read_csv(file)\n res_df = res_df.transpose().reset_index(drop=False)\n res_df.columns = ['filename', 'label', 'split', 'original']\n res_df['foldername'] = file.split('/')[-1].split('.')[0]\n file_list.append(res_df)\n file_df = pd.concat(file_list, axis=0).reset_index(drop=True)\n file_df.to_csv(os.path.join(saving_path, 'meta_df.csv'), index=False)\n return file_df\n\n\ndef _check_name(name: str) -> str:\n if \"_\" in name:\n base = name.split(\"_\")[0] + \".mp4\"\n elif \".mp4\" in name:\n base = name\n else:\n base = name\n return base\n\n\ndef get_full_label(file_df, basename: str):\n basename = _check_name(basename)\n label = file_df.loc[file_df['filename'] == basename, ]\n label_value = label[\"label\"].values[0]\n if len(label) == 0:\n raise ValueError(\"No such video in the label file!\")\n if label_value == \"FAKE\":\n binary_label = 1\n elif label_value == \"REAL\":\n binary_label = 0\n else:\n raise ValueError(\"label in the label file is wrong!\")\n original_video = label[\"original\"].values[0]\n folder_name = label[\"foldername\"].values[0]\n return {\"label\": binary_label, \"original\": original_video, \"foldername\": folder_name}\n\n\ndef generate_label_csv(file_path: str, file_df, saving_path: str):\n \"\"\"\n Generate the meta file based on frame level\n :param file_path:\n :param label_dict:\n :param saving_path:\n :return:\n \"\"\"\n framename = []\n basename = []\n \n for file_name in tqdm(glob(os.path.join(file_path, \"*.jpg\"))):\n patch = os.path.basename(file_name)\n base = _check_name(patch)\n framename.append(patch)\n basename.append(base)\n res_df = pd.DataFrame({'subname': framename, 'filename': basename})\n res_df = res_df.merge(file_df, how = 'left', on = 'filename')\n # Column: subname,filename,label,split,original,foldername\n res_df.to_csv(saving_path, index=False)\n print('The shape of generated label file is: ', res_df.shape)\n print('The shape of empty info is: ', sum(res_df.label.isna()))\n return res_df\n\n\nif __name__ == \"__main__\":\n # file_df = generate_meta_csv('../dataset/meta_data/meta_df/', '../dataset/meta_data/')\n file_df = pd.read_csv('../dataset/meta_data/meta_df.csv')\n # Generate subfile -> file -> label file for frame level\n print ('start to process frame data')\n frame_df = generate_label_csv('../dataset/frames/', file_df, '../dataset/meta_data/frames_ori.csv')\n # Generate subfile -> file -> label file for face patch level\n print ('start to process patches data')\n patch_df = generate_label_csv('../dataset/face_patches/', file_df, '../dataset/meta_data/patches_ori.csv')\n","sub_path":"tools/anno_parse.py","file_name":"anno_parse.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"128468898","text":"import logging\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # FATAL\nlogging.getLogger('tensorflow').setLevel(logging.FATAL)\n\nfrom datetime import datetime, timedelta\nimport fire\nimport lightgbm as lgb\nimport numpy as np\nimport pandas as pd\nimport tensorflow.keras as tfk\nfrom conf import *\nfrom conf import MODELS_PATH, SUBMIT_PATH, EXTERNAL_PATH, RAW_PATH, PRICE_DTYPES, CAL_DTYPES\nfrom tf_utils import train_mlp\nfrom tqdm import tqdm\n\n# silence tensorflow importing library\nlogging.getLogger('tensorflow').setLevel(logging.FATAL)\n\n\ndef train(horizon=\"validation\", task=\"volume\"):\n df = pd.read_parquet(\n os.path.join(REFINED_PATH, \"%s_%s_fe.parquet\" % (horizon, task))\n )\n cat_feats = [\"item_id\", \"dept_id\", \"store_id\", \"cat_id\", \"state_id\"] + [\n \"event_name_1\",\n \"event_name_2\",\n \"event_type_1\",\n \"event_type_2\",\n ]\n useless_cols = [\"id\", \"date\", \"sales\", \"d\", \"wm_yr_wk\", \"weekday\", \"rate\"]\n train_cols = df.columns[~df.columns.isin(useless_cols)]\n X_train = df[train_cols]\n y_train = df[\"sales\"]\n\n train_data = lgb.Dataset(\n X_train, label=y_train, categorical_feature=cat_feats, free_raw_data=False\n )\n params = {\n \"metric\": \"rmse\",\n \"force_row_wise\": True,\n \"learning_rate\": 0.075,\n \"sub_feature\": 0.8,\n \"sub_row\": 0.75,\n \"bagging_freq\": 1,\n \"lambda_l2\": 0.1,\n \"nthread\": 16,\n \"metric\": [\"rmse\"],\n \"verbosity\": 1,\n }\n\n if task == \"volume\":\n params[\"objective\"] = \"poisson\"\n params[\"num_iterations\"] = 15000\n elif task == \"share\":\n params[\"objective\"] = \"xentropy\"\n params[\"num_iterations\"] = 2000\n\n m_lgb = lgb.train(params, train_data)\n m_lgb.save_model(os.path.join(MODELS_PATH, \"%s_%s_lgb.txt\" % (horizon, task)))\n\n\ndef create_dt(horizon=\"validation\", tr_last=1913):\n prices = pd.read_csv(os.path.join(RAW_PATH, \"sell_prices.csv\"), dtype=PRICE_DTYPES)\n for col, col_dtype in PRICE_DTYPES.items():\n if col_dtype == \"category\":\n prices[col] = prices[col].cat.codes.astype(\"int16\")\n prices[col] -= prices[col].min()\n\n cal = pd.read_csv(os.path.join(RAW_PATH, \"calendar.csv\"), dtype=CAL_DTYPES)\n cal[\"date\"] = pd.to_datetime(cal[\"date\"])\n for col, col_dtype in CAL_DTYPES.items():\n if col_dtype == \"category\":\n cal[col] = cal[col].cat.codes.astype(\"int16\")\n cal[col] -= cal[col].min()\n\n numcols = [f\"d_{day}\" for day in range(1, tr_last + 1)]\n catcols = [\"id\", \"item_id\", \"dept_id\", \"store_id\", \"cat_id\", \"state_id\"]\n dtype = {numcol: \"float32\" for numcol in numcols}\n dtype.update({col: \"category\" for col in catcols if col != \"id\"})\n dt = pd.read_csv(\n os.path.join(RAW_PATH, \"sales_train_%s.csv\" % horizon),\n usecols=catcols + numcols,\n dtype=dtype,\n )\n\n for col in catcols:\n if col != \"id\":\n dt[col] = dt[col].cat.codes.astype(\"int16\")\n dt[col] -= dt[col].min()\n\n increasing_term = dt.groupby([\"dept_id\", \"store_id\"])[numcols].sum()\n increasing_term = (\n increasing_term.T - increasing_term.T.shift(28)\n ) / increasing_term.T.shift(28)\n increasing_term = increasing_term.reset_index(drop=True).iloc[-365:, :]\n rates = increasing_term[increasing_term.abs() < 1].mean() + 1\n rates = rates.reset_index().rename(columns={0: \"rate\"})\n\n for day in range(tr_last + 1, tr_last + 2 * 28 + 1):\n dt[f\"d_{day}\"] = np.nan\n\n dt = pd.melt(\n dt,\n id_vars=catcols,\n value_vars=[col for col in dt.columns if col.startswith(\"d_\")],\n var_name=\"d\",\n value_name=\"sales\",\n )\n\n dt = dt.merge(cal, on=\"d\", copy=False)\n dt = dt.merge(prices, on=[\"store_id\", \"item_id\", \"wm_yr_wk\"], copy=False)\n dt = dt.merge(rates, how=\"left\")\n\n return dt\n\n\ndef create_fea(dt):\n lags = [7, 28]\n lag_cols = [f\"lag_{lag}\" for lag in lags]\n for lag, lag_col in zip(lags, lag_cols):\n dt[lag_col] = dt[[\"id\", \"sales\"]].groupby(\"id\")[\"sales\"].shift(lag)\n\n wins = [7, 28]\n for win in wins:\n for lag, lag_col in zip(lags, lag_cols):\n dt[f\"rmean_{lag}_{win}\"] = (\n dt[[\"id\", lag_col]]\n .groupby(\"id\")[lag_col]\n .transform(lambda x: x.rolling(win).mean())\n )\n\n date_features = {\n \"wday\": \"weekday\",\n \"week\": \"weekofyear\",\n \"month\": \"month\",\n \"quarter\": \"quarter\",\n \"year\": \"year\",\n \"mday\": \"day\",\n }\n\n for date_feat_name, date_feat_func in date_features.items():\n if date_feat_name in dt.columns:\n dt[date_feat_name] = dt[date_feat_name].astype(\"int16\")\n else:\n dt[date_feat_name] = getattr(dt[\"date\"].dt, date_feat_func).astype(\"int16\")\n return dt\n\n\ndef compute_share(dt):\n shares = (\n dt.groupby([\"dept_id\", \"store_id\", \"date\"])[\"sales\"]\n .sum()\n .reset_index()\n .rename(columns={\"sales\": \"gp_sales\"})\n )\n dt = dt.merge(shares, how=\"left\")\n dt[\"sales\"] = dt[\"sales\"] / dt[\"gp_sales\"]\n dt.drop([\"gp_sales\"], axis=1, inplace=True)\n return dt\n\ndef predict(horizon=\"validation\", task=\"volume\", ensembling_type='avg'):\n if horizon == \"validation\":\n tr_last = 1913\n fday = datetime(2016, 4, 25)\n elif horizon == \"evaluation\":\n tr_last = 1941\n fday = datetime(2016, 4, 25) + timedelta(days=28)\n else:\n raise ValueError(\"Wrong value for horizon arg.\")\n\n # gather both models (before data to avoid memory spikes )\n print('>>> load the two models ')\n m_lgb = lgb.Booster(\n model_file=os.path.join(MODELS_PATH, \"%s_%s_lgb.txt\" % (horizon, task))\n )\n print('--- lgbm ok ')\n m_tf = tfk.models.load_model((os.path.join(MODELS_PATH, \"%s_%s_tf.h5\" % (horizon, task))))\n print('--- tf ok ')\n print('>>> start to make predictions ')\n\n\n dataframe = create_dt(horizon, tr_last)\n\n if task == \"share\":\n dataframe = compute_share(dataframe)\n elif task != \"volume\":\n raise ValueError(\"Wrong value for task.\")\n\n for i in tqdm(range(0, 28)):\n day = fday + timedelta(days=i)\n tst = dataframe[\n (dataframe.date >= day - timedelta(days=366)) & (dataframe.date <= day)\n ].copy()\n\n tst = create_fea(tst)\n train_cols = tst.columns[~tst.columns.isin(useless_cols)]\n tst = tst.loc[tst.date == day, train_cols.tolist() + [\"rate\"]]\n\n if task == \"volume\":\n input_dict_predict = {f\"input_{col}\": tst[col] for col in train_cols}\n if ensembling_type == 'avg':\n predictions = tst[\"rate\"] * (m_lgb.predict(tst[train_cols]) + m_tf.predict(input_dict_predict,\n batch_size=10000).flatten()) / 2\n dataframe.loc[dataframe.date == day, \"sales\"] = predictions\n elif task == \"share\":\n dataframe.loc[dataframe.date == day, \"sales\"] = m_lgb.predict(\n tst[train_cols]\n )\n shares = (\n dataframe.groupby([\"dept_id\", \"store_id\", \"date\"])[\"sales\"]\n .sum()\n .reset_index()\n .rename(columns={\"sales\": \"gp_sales\"})\n )\n dataframe = dataframe.merge(shares, how=\"left\")\n dataframe[\"sales\"] = dataframe[\"sales\"] / dataframe[\"gp_sales\"]\n dataframe.drop([\"gp_sales\"], axis=1, inplace=True)\n\n te_sub = dataframe.loc[dataframe.date >= fday, [\"id\", \"sales\"]].copy()\n if horizon == \"validation\":\n te_sub.loc[dataframe.date >= fday + timedelta(days=28), \"id\"] = te_sub.loc[\n dataframe.date >= fday + timedelta(days=28), \"id\"\n ].str.replace(\"validation\", \"evaluation\")\n else:\n te_sub.loc[dataframe.date >= fday + timedelta(days=28), \"id\"] = te_sub.loc[\n dataframe.date >= fday + timedelta(days=28), \"id\"\n ]\n te_sub_validation = te_sub.copy()\n te_sub_validation[\"id\"] = te_sub_validation[\"id\"].str.replace(\n \"evaluation\", \"validation\"\n )\n te_sub = pd.concat([te_sub, te_sub_validation])\n\n te_sub[\"F\"] = [f\"F{rank}\" for rank in te_sub.groupby(\"id\")[\"id\"].cumcount() + 1]\n te_sub = (\n te_sub.set_index([\"id\", \"F\"])\n .unstack()[\"sales\"][[f\"F{i}\" for i in range(1, 29)]]\n .reset_index()\n )\n te_sub.fillna(0.0, inplace=True)\n\n if task == \"volume\":\n te_sub.to_csv(\n os.path.join(SUBMIT_PATH, \"ens_estim_%s.csv\" % horizon), index=False\n )\n else:\n te_sub.to_csv(\n os.path.join(EXTERNAL_PATH, \"ens_weights_%s.csv\" % horizon), index=False\n )\n\ndef ml_pipeline(horizon=\"validation\", task=\"volume\", ml=\"predict\"):\n if ml == \"train_and_predict\":\n train(horizon, task)\n train_mlp(horizon, task)\n predict(horizon, task)\n elif ml == \"predict\":\n predict(horizon, task)\n else:\n raise ValueError('ml arg must be \"train_and_predict\" or \"predict\"')\n\nif __name__ == \"__main__\":\n fire.Fire(ml_pipeline)\n","sub_path":"tf_pipeline/machine_learning_ens.py","file_name":"machine_learning_ens.py","file_ext":"py","file_size_in_byte":9144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"176724446","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport math\n\nfrom sklearn.metrics import auc\n\nfrom analysis.plot_utils import compute_roc, plot_roc, disp_learn_hist\n\ndef multi_disp_learn_hist(locations,losslim=None,show=True,titles=None,best_only=False,leg_font=10,title_font=10,xmax=None):\n '''\n Plots a grid of learning histories.\n Args:\n locations ... list of paths to directories of training dumps\n losslim ... limit of loss axis\n show ... bool, whether to show the plot\n titles ... list of titles for each plot in the grid\n best_only ... bool, whether to plot only the points where best model was saved\n leg_font ... legend font size\n author: Calum Macdonald\n June 2020\n '''\n\n ncols = 1\n nrows = math.ceil(len(locations))\n\n if nrows==1 and ncols==1:\n fig = plt.figure(facecolor='w',figsize=(12,12))\n else:\n fig = plt.figure(facecolor='w',figsize=(12, nrows*4*3))\n \n gs = gridspec.GridSpec(nrows, ncols, figure=fig)\n axes = []\n\n for i, location in enumerate(locations):\n print(\"i: \", i)\n if i == 0:\n ax1 = fig.add_subplot(gs[i],facecolor='w')\n else:\n ax1 = fig.add_subplot(gs[i],facecolor='w',sharey=axes[0])\n disp_learn_hist(location, axis=ax1, show=False)\n axes.append(ax1)\n \n gs.tight_layout(fig)\n return fig\n\ndef multi_compute_roc(softmax_out_val_list, labels_val_list, true_label, false_label):\n # Compute ROC metrics\n fprs, tprs, thrs = [], [], []\n for softmax_out_val, labels_val in zip(softmax_out_val_list, labels_val_list):\n fpr, tpr, thr = compute_roc(softmax_out_val, labels_val, true_label, false_label)\n fprs.append(fpr)\n tprs.append(tpr)\n thrs.append(thr)\n\n return fprs, tprs, thrs\n\ndef multi_plot_roc(fprs, tprs, thrs, true_label_name, false_label_name, fig_list=None, xlims=None, ylims=None, axes=None, linestyles=None, linecolors=None, plot_labels=None, show=False):\n '''\n plot_multiple_ROC(data, metric, pos_neg_labels, plot_labels = None, png_name=None,title='ROC Curve', annotate=True,ax=None, linestyle=None, leg_loc=None, xlabel=None,ylabel=None,legend_label_dict=None)\n Plot multiple ROC curves of background rejection vs signal efficiency. Can plot 'rejection' (1/fpr) or 'fraction' (tpr).\n Args:\n data ... tuple of (n false positive rates, n true positive rate, n thresholds) to plot rejection or \n (rejection fractions, true positive rates, false positive rates, thresholds) to plot rejection fraction.\n metric ... string, name of metric to plot: ('rejection' or 'fraction')\n pos_neg_labels ... array of one positive and one negative string label, or list of lists, with each list giving positive and negative label for\n one dataset\n plot_labels ... label for each run to display in legend\n png_name ... name of image to save\n title ... title of plot\n annotate ... whether or not to include annotations of critical points for each curve, default True\n ax ... matplotlib.pyplot.axes on which to place plot\n linestyle ... list of linestyles to use for each curve, can be '-', ':', '-.'\n leg_loc ... location for legend, eg 'upper right' - vertical upper, center, lower, horizontal right left\n legend_label_dict ... dictionary of display symbols for each string label, to use for displaying pretty characters in labels\n author: Calum Macdonald\n June 2020\n '''\n rejections = [1.0/(fpr+1e-10) for fpr in fprs]\n AUCs = [auc(fpr,tpr) for fpr, tpr in zip(fprs, tprs)]\n\n num_panes = len(fig_list)\n fig, axes = plt.subplots(num_panes, 1, figsize=(12,8*num_panes))\n if num_panes > 1:\n fig.suptitle(\"ROC for {} vs {}\".format(true_label_name, false_label_name), fontweight='bold',fontsize=32)\n\n # Needed for 1 plot case\n axes = np.array(axes).reshape(-1)\n\n for idx, fpr, tpr, thr in zip(range(len(fprs)), fprs, tprs, thrs):\n figs = plot_roc(fpr, tpr, thr, \n true_label_name, false_label_name, \n axes=axes, fig_list=fig_list, xlims=xlims, ylims=ylims,\n linestyle=linestyles[idx] if linestyles is not None else None,\n linecolor=linecolors[idx] if linecolors is not None else None,\n plot_label=plot_labels[idx] if plot_labels is not None else None,\n show=False)\n\n return figs","sub_path":"WatChMaL_folder/analysis/multi_plot_utils.py","file_name":"multi_plot_utils.py","file_ext":"py","file_size_in_byte":4713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"227440166","text":"# Copyright 2021 John Reese\n# Licensed under the MIT license\n\n\"\"\"\nRun things on paths\n\"\"\"\n\nimport multiprocessing\n\ncontext: multiprocessing.context.BaseContext = multiprocessing.get_context(\"spawn\")\n\n__author__ = \"John Reese\"\nfrom .__version__ import __version__\nfrom .core import (\n run,\n walk,\n walk_and_run,\n default_executor,\n thread_executor,\n TrailRunner,\n)\n","sub_path":"trailrunner/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"474956651","text":"# ■■■■■■■■■■ 데이터 ■■■■■■■■■■\nfrom keras.datasets import mnist\nimport numpy as np\nfrom keras import regularizers\nfrom keras.callbacks import EarlyStopping\nfrom sklearn.model_selection import RandomizedSearchCV, KFold\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom keras.layers import Input, Dense, Dropout, Flatten, BatchNormalization\nfrom keras.models import Model\n\n(x_train, _), (x_test, _) = mnist.load_data()\n\nx_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))\nx_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))\nprint(x_train.shape) # (60000, 784)\nprint(x_test.shape) # (10000, 784)\n\n# ■■■■■■■■■■ 모델 구성 ■■■■■■■■■■\n# 인코딩될 표현(representation)의 크기\nencoding_dim = 32\n\ndef build_network(keep_prob=0.1, optimizer='adam'):\n # 입력 플레이스홀더\n input_img = Input(shape=(784, ))\n # \"encoded\"는 입력의 인코딩된 표현\n encoded = Dense(encoding_dim, activation='relu')(input_img)\n\n encoded = Dense(144, activation='relu')(encoded) \n encoded = Dropout(keep_prob)(encoded)\n encoded = Dense(128, activation='relu')(encoded) \n \n\n # # encoded = BatchNormalization()(encoded)\n # encoded = Dense(64, activation='relu')(encoded) \n # encoded = Dropout(keep_prob)(encoded)\n # encoded = Dense(96, activation='relu')(encoded)\n # encoded = Dense(32, activation='relu')(encoded)\n # encoded = Dropout(keep_prob)(encoded)\n # encoded = Dense(64, activation='relu')(encoded)\n\n encoded = Dense(32, activation='relu')(encoded)\n decoded = Dense(784, activation='sigmoid')(encoded)\n\n # 입력을 입력의 재구성으로 매핑할 모델\n autoencoder = Model(input_img, decoded) # 784 -> 32 -> 784\n\n # 이 모델은 입력을 입력의 인코딩된 입력의 표현으로 매핑\n encoder = Model(input_img, encoded) # 784 -> 32\n\n # 인코딩된 입력을 위한 플레이스 홀더\n encoded_input = Input(shape=(encoding_dim, )) # 디코딩의 인풋레이어로 시작\n # 오토인코더 모델의 마지막 레이어 얻기\n decoder_layer = autoencoder.layers[-1]\n # 디코더 모델 생성\n decoder = Model(encoded_input, decoder_layer(encoded_input)) # 32 -> 784\n\n autoencoder = Model(inputs=input_img, outputs=decoded)\n autoencoder.compile(optimizer='adam',\n loss='binary_crossentropy', metrics=['accuracy'])\n\n return autoencoder\n\n# autoencoder.summary()\n# encoder.summary()\n# decoder.summary()\n\ndef create_hyperparameters():\n batch_sizes = [10, 20, 30, 40, 50, 60, 70 ,80, 90, 100]\n optimizers = ['rmsprop', 'adam', 'adadelta', 'SGD',\n 'Momentum', 'NAG', 'Adagrad']\n dropouts = np.linspace(0.1, 0.2, 10)\n # epochss = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\n return {\n 'batch_size':batch_sizes, \n 'optimizer':optimizers,\n 'keep_prob':dropouts\n # 'epochs':epochss\n }\n\nmodel = KerasClassifier(build_fn=build_network, verbose=1)\nhyperparameters = create_hyperparameters()\nkfold_cv = KFold(n_splits=5, shuffle=True)\n \nsearch = RandomizedSearchCV(estimator=model, param_distributions=hyperparameters,\n n_iter=10, n_jobs=-1, verbose=1, cv=kfold_cv)\n\nsearch.fit(x_train, x_train)\n\nprint('Best parameter = ', search.best_params_)\nprint('Best estimator = ', search.best_estimator_)\nprint('Accuracy = ', search.score(x_test, x_test))\n\n'''\n# 숫자들을 인코딩&디코딩\n# test set에서 숫자들을 가져왔다는 것을 유의\nencoded_imgs = encoder.predict(x_test)\ndecoded_imgs = decoder.predict(encoded_imgs)\n\nprint(encoded_imgs)\nprint(decoded_imgs)\nprint(encoded_imgs.shape) # (10000, 32)\nprint(decoded_imgs.shape) # (10000, 784)\n\n# ■■■■■■■■■■ 이미지 출력 ■■■■■■■■■■\n# Matplotlib 사용\nimport matplotlib.pyplot as plt\n\nn = 10 # 몇 개의 숫자를 나타낼 것인지\nplt.figure(figsize=(20,4))\nfor i in range(n):\n # 원본 데이터\n ax = plt.subplot(2, n, i+1)\n plt.imshow(x_test[i].reshape(28, 28))\n plt.gray()\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n # 재구성된 데이터\n ax = plt.subplot(2, n, i + 1 + n)\n plt.imshow(decoded_imgs[i].reshape(28, 28))\n plt.gray()\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\nplt.show()\n\n# ■■■■■■■■■■ 그래프 출력 ■■■■■■■■■■\ndef plot_acc(history, title=None):\n # summarize history for accuracy\n if not isinstance(history, dict):\n history = history.history\n\n plt.plot(history['acc'])\n plt.plot(history['val_acc'])\n if title is not None:\n plt.title(title)\n plt.ylabel('Accuracy')\n plt.xlabel('Epoch')\n plt.legend(['Training data', 'Validation data'], loc=0)\n # plt.show()\n\ndef plot_loss(history, title=None):\n # summarize history for accuracy\n if not isinstance(history, dict):\n history = history.history\n\n plt.plot(history['loss'])\n plt.plot(history['val_loss'])\n if title is not None:\n plt.title(title)\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n plt.legend(['Training data', 'Validation data'], loc=0)\n # plt.show()\n\nplot_acc(history, '(a) 학습 경과에 따른 정확도 변화 추이')\nplt.show()\nplot_loss(history, '(b) 학습 경과에 따른 손실값 변화 추이')\nplt.show()\n\nloss, acc = autoencoder.evaluate(x_test, x_test)\nprint(loss, acc)\n'''","sub_path":"MachineLearnig/m28_autoencoder2_hyper.py","file_name":"m28_autoencoder2_hyper.py","file_ext":"py","file_size_in_byte":5567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"275431563","text":"class CountingAmplitude:\n\n data_list = []\n while True:\n date = input(f'Enter the temperature measurement date(DD-MM-YY) or enter \"end\": ')\n if date == 'end':\n print(f'\\nYou entered the temperatures for {len(data_list)} days.')\n break\n for x in data_list:\n print(f'Day: {x[0]}, minimum temperature: {x[1]}℃, maximum temperature: {x[2]}℃.')\n \n amplituda_max = ()\n amplituda_min = ()\n first_cycle = True\n \n for x in data_list:\n amplitude_for_day_x = x[2] - x[1]\n if first_cycle == True:\n amplitude_min = (x[0], amplitude_for_day_x)\n amplitude_max = (x[0], amplitude_for_day_x)\n first_cycle = False\n elif amplitude_for_day_x > amplitude_max[1]:\n amplitude_max = (x[0], amplitude_for_day_x)\n elif amplitude_for_day_x < amplitude_min[1]:\n amplitude_min = (x[0], amplitude_for_day_x)\n \n print(f'\\nThe minimu temperature was on {amplitude_min[0]} day: {amplitude_min[1]}℃.')\n print(f'The maximum temperature was on {amplitude_max[0]} day: {amplitude_max[1]}℃.')\n break\n \n minimal = int(input(f'Enter the minimum temperature: '))\n maximal = int(input(f'Enter the maximum temperature: '))\n data = (date, minimal, maximal)\n \n data_list.append(data)","sub_path":"Counting the amplitude.py","file_name":"Counting the amplitude.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"400065946","text":"# Copyright (C) 2020 by Landmark Acoustics LLC\nr\"\"\"The command-line interface to the `ariffonriff` package.\"\"\"\n\nimport numpy as np\n\nfrom ariffonriff import WaveHeader\n\n\nt = np.linspace(0, 0.1, 4410, endpoint=False)\na = np.sin(2 * np.pi * 120 * t, dtype=np.float32)\n\nheads = {bits: WaveHeader(len(t), bits) for bits in [8, 16, 32]}\n\namps = {\n 8: np.array(2**7 * (1 + a), dtype=np.uint8),\n 16: np.array(2**15 * a, dtype=np.int16),\n 32: a,\n}\n\nfor b, h in heads.items():\n\n with open(f'wave{b:02}.wav', 'wb') as fh:\n fh.write(h.as_bytes())\n fh.write(amps[b].tobytes())\n","sub_path":"ariffonriff/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"614497414","text":"\"\"\"\r\n Power BI Report refresh history parser\r\n\r\n - extracts refresh status of a report (ok/ko)\r\n\r\n\"\"\"\r\n\r\n\r\n__author__ = 'marcel.kantor'\r\n__date__ = '2020-01-07'\r\n\r\n\r\nimport json\r\nimport sys\r\nimport os\r\nimport argparse\r\n\r\nimport os.path\r\nfrom config import *\r\n\r\n\r\n\r\n\r\ndef parseArguments():\r\n\r\n try:\r\n \r\n parser = argparse.ArgumentParser(description='Parses report refresh history and returns ok if last refresh successfull') \r\n parser.add_argument(\"-d\",\"--dataSetId\", help=\"Enter dataset id of a report\", required=True)\r\n \r\n args = parser.parse_args()\r\n \r\n if len(sys.argv) < 2:\r\n parser.print_help()\r\n parser.exit(1)\r\n\r\n return args\r\n \r\n except:\r\n\r\n print('Problem @parseArguments')\r\n print(sys.exc_info())\r\n sys.exit(1)\r\n\r\n\r\n\r\ndef getLatestRefreshId(dataSetId):\r\n\r\n try:\r\n json_file_path = file_path + \"\\\\\" + dataSetId + '.json'\r\n\r\n with open(json_file_path, encoding='utf-16', errors='ignore') as histFile:\r\n myDict = json.loads(histFile.read())\r\n \r\n return myDict['value'][0]['id']\r\n\r\n except:\r\n sys.exit(1)\r\n\r\n\r\n\r\ndef getRefreshRecord(dataSetId):\r\n\r\n try:\r\n \r\n json_file_path = file_path + \"\\\\\" + dataSetId + '.json'\r\n\r\n with open(json_file_path, encoding='utf-16', errors='ignore') as histFile:\r\n myDict = json.loads(histFile.read())\r\n \r\n return myDict['value'][0]\r\n\r\n except:\r\n sys.exit(1)\r\n\r\n\r\n\r\ndef getRefreshStatus(dictRecord):\r\n\r\n try:\r\n \r\n if dictRecord['status'] == \"Completed\" and dictRecord['refreshType'] == 'ViaApi': \r\n return \"ok\"\r\n elif dictRecord['status'] == \"Failed\" and dictRecord['refreshType'] == 'ViaApi': \r\n return \"ko\" \r\n else:\r\n return \"no\"\r\n \r\n except:\r\n print(\"Problem @getRefreshStatus\")\r\n print(sys.exc_info())\r\n sys.exit(1)\r\n\r\n\r\n\r\ndef getOldRefreshId(dataSetId):\r\n\r\n try:\r\n lastId_file_path = file_path + \"\\\\\" + dataSetId + '.id'\r\n if os.path.isfile(lastId_file_path):\r\n print(\"file exists:\", lastId_file_path)\r\n with open(lastId_file_path,'r') as lastIdFile:\r\n oldRefreshId = lastIdFile.read() \r\n\r\n return oldRefreshId\r\n \r\n except:\r\n print(\"file does not exist\")\r\n sys.exit(1)\r\n\r\n\r\n'''\r\n 1. read in lastId file & compare with latest json id\r\n if latest json id is greater than lastId -> check if status completed\r\n if true then report \"refresh successfull\"\r\n 2. save latest json id into lastId file & quit\r\n\r\n if lastId file not exists then check \r\n \r\n'''\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n myargs = parseArguments()\r\n print(getRefreshStatus(getRefreshRecord(myargs.dataSetId)))\r\n sys.exit(0)\r\n","sub_path":"PBIRefreshHistParser/pbiRefreshHistParser.py","file_name":"pbiRefreshHistParser.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"582413908","text":"class Solution:\n \"\"\"\n @param obstacleGrid: An list of lists of integers\n @return: An integer\n \"\"\"\n def uniquePathsWithObstacles(self, obstacleGrid):\n # write your code here\n m=obstacleGrid\n for i in xrange(len(m)):\n for j in xrange(len(m[0])):\n if (not i and not j) or (not i and m[0][j-1]) or (not j and m[i-1][0]):\n m[i][j]=1-m[i][j]\n elif not i or not j or m[i][j]:\n m[i][j]=0\n else:\n m[i][j]=m[i-1][j]+m[i][j-1]\n return m[-1][-1]\n \n # O(MN) O(1)\n","sub_path":"115.py","file_name":"115.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"414756659","text":"import urlparse\nimport requests\nfrom oauth_hook import OAuthHook\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render_to_response\nfrom quickbooks.models import QuickbooksToken, get_quickbooks_token\nfrom quickbooks.api import QuickbooksApi\n\nREQUEST_TOKEN_URL = 'https://oauth.intuit.com/oauth/v1/get_request_token'\nACCESS_TOKEN_URL = 'https://oauth.intuit.com/oauth/v1/get_access_token'\nAUTHORIZATION_URL = 'https://appcenter.intuit.com/Connect/Begin'\n\n\n@login_required\ndef request_oauth_token(request):\n access_token_callback = settings.QUICKBOOKS['OAUTH_CALLBACK_URL']\n quickbooks_oauth_hook = OAuthHook(consumer_key=settings.QUICKBOOKS['CONSUMER_KEY'],\n consumer_secret=settings.QUICKBOOKS['CONSUMER_SECRET'])\n response = requests.post(REQUEST_TOKEN_URL,\n params={'oauth_callback': access_token_callback},\n hooks={'pre_request': quickbooks_oauth_hook})\n qs = urlparse.parse_qs(response.text)\n request_token = qs['oauth_token'][0]\n request_token_secret = qs['oauth_token_secret'][0]\n\n request.session['qb_oauth_token'] = request_token\n request.session['qb_oauth_token_secret'] = request_token_secret\n return HttpResponseRedirect(\"%s?oauth_token=%s\" % (AUTHORIZATION_URL, request_token))\n\n\n@login_required\ndef get_access_token(request):\n realm_id = request.GET.get('realmId')\n data_source = request.GET.get('dataSource')\n oauth_verifier = request.GET.get('oauth_verifier')\n\n quickbooks_oauth_hook = OAuthHook(request.session['qb_oauth_token'],\n request.session['qb_oauth_token_secret'],\n settings.QUICKBOOKS['CONSUMER_KEY'],\n settings.QUICKBOOKS['CONSUMER_SECRET'])\n response = requests.post(ACCESS_TOKEN_URL,\n {'oauth_verifier': oauth_verifier},\n hooks={'pre_request': quickbooks_oauth_hook})\n data = urlparse.parse_qs(response.content)\n\n # Delete any existing access tokens\n request.user.quickbookstoken_set.all().delete()\n\n QuickbooksToken.objects.create(\n user = request.user,\n access_token = data['oauth_token'][0],\n access_token_secret = data['oauth_token_secret'][0],\n realm_id = realm_id,\n data_source = data_source)\n\n return render_to_response('oauth_callback.html',\n {'complete_url': settings.QUICKBOOKS['ACCESS_COMPLETE_URL']})\n\n\n@login_required\ndef blue_dot_menu(request):\n return HttpResponse(QuickbooksApi(request.user).app_menu())\n\n\n@login_required\ndef disconnect(request):\n token = get_quickbooks_token(request)\n QuickbooksApi(token).disconnect()\n request.user.quickbookstoken_set.all().delete()\n return HttpResponseRedirect(settings.QUICKBOOKS['ACCESS_COMPLETE_URL'])\n","sub_path":"quickbooks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"506365153","text":"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"No externally useful functions here. Read the `run.py` docblock instead.\"\nimport subprocess\n\nfrom fs_image.fs_utils import Path\n\n\n# Our container runtimes are required to make this the `PATH` for the user\n# command in the container. This also determines which container binaries\n# get shadowed by `--shadow-path`.\n#\n# For now, the non-booted case implicitly uses the `systemd-nspawn` default\n# `PATH`, so if that changes our test will fail. That test failure in time\n# will be an opportunity to decide whether to set our own, or follow.\nDEFAULT_SEARCH_PATHS = (\n Path(p)\n for p in (\n \"/usr/local/sbin\",\n \"/usr/local/bin\",\n \"/usr/sbin\",\n \"/usr/bin\",\n \"/sbin\",\n \"/bin\",\n )\n)\nDEFAULT_PATH_ENV = b\":\".join(DEFAULT_SEARCH_PATHS)\n\n\ndef nspawn_version() -> int:\n \"\"\"\n We now care about the version of nspawn we are running. The output of\n systemd-nspawn --version looks like:\n\n ```\n systemd 242 (v242-2.fb1)\n +PAM +AUDIT +SELINUX +IMA ...\n ```\n So we can get the major version as the second token of the first line.\n We hope that the output of systemd-nspawn --version is stable enough\n to keep parsing it like this.\n \"\"\"\n return int(\n subprocess.check_output([\"systemd-nspawn\", \"--version\"]).split()[1]\n )\n","sub_path":"fs_image/nspawn_in_subvol/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"20042439","text":"import os\nfrom dataclasses import dataclass\n@dataclass\nclass Sub_args(object):\n queue: str\n ppn: int\n node: int\n mode: str\n name: str\n fname: str\n\ndef sub_vasp(args):\n import os\n import logging\n import subprocess as sp\n\n file_doc = f\"\"\"#PBS -N {args.name}\n#PBS -l nodes={args.node}:ppn={args.ppn}\n#PBS -q {args.queue}\n#PBS -j oe\n#PBS -r n\n#PBS -o {args.fname}\n\nNP=`cat $PBS_NODEFILE |wc -l`\ncd $PBS_O_WORKDIR\n\ndate\nmpirun -np $NP -machinefile $PBS_NODEFILE /public/ltaiwb/app/vasp/{args.queue}/vasp_{args.mode} 2>&1\ndate\n\"\"\"\n\n logging.basicConfig(filename=os.path.join(os.getenv('HOME'), 'zrecords'),\n format='%(asctime)s %(message)s',\n datefmt='%m-%d %H:%M:%S',\n level=logging.INFO)\n\n with open('vasp.pbs', 'w') as f:\n f.write(file_doc)\n msg = sp.run('qsub vasp.pbs', stdout=sp.PIPE ,shell=True).stdout.decode()\n jobid = int(msg.split('.')[0])\n logging.info(f'No. {jobid}{args.queue:>7s} {os.getcwd()}')\n","sub_path":"pyvasp/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"469894998","text":"#!/usr/bin/python\r\n#\r\n# Does Voroni cluster analysis.\r\n#\r\n# Hazen 09/16\r\n#\r\n\r\nimport os\r\nimport subprocess\r\nimport sys\r\n\r\nif (len(sys.argv) != 4):\r\n print(\"usage \")\r\n exit()\r\n\r\nsrc_dir = os.path.dirname(__file__)\r\nif not (src_dir == \"\"):\r\n src_dir += \"/\"\r\n \r\n# setup\r\nbin_file = sys.argv[1]\r\noutput_directory = sys.argv[3]\r\n\r\n# defaults\r\ndensity_factor = float(sys.argv[2])\r\nmin_size = 30\r\n\r\nbin_dir = os.path.dirname(bin_file)\r\nif (len(bin_dir) == 0):\r\n bin_dir = \".\"\r\n \r\nwith open(bin_dir + \"/voroni.txt\", \"w\") as fp:\r\n fp.write(\"density factor = \" + str(density_factor) + \"\\n\")\r\n fp.write(\"min_size = \" + str(min_size) + \"\\n\")\r\n\r\n# exe files\r\nvoroni_exe = src_dir + \"/voronoi.py\"\r\ncluster_stats_exe = src_dir + \"../dbscan/cluster_stats.py\"\r\ncluster_size_exe = src_dir + \"../dbscan/cluster_size.py\"\r\n\r\ncl_bin_file = output_directory + os.path.basename(bin_file)[:-8] + \"srt_list.bin\"\r\n\r\n# find clusters\r\nif 1:\r\n subprocess.call(['python', voroni_exe, bin_file, str(density_factor), str(min_size), cl_bin_file])\r\n\r\n# cluster stats\r\nif 1:\r\n subprocess.call(['python', cluster_stats_exe, cl_bin_file, str(min_size-1)])\r\n\r\n# cluster size\r\nif 1:\r\n subprocess.call(['python', cluster_size_exe, cl_bin_file, cl_bin_file[:-8] + \"size_list.bin\"])\r\n\r\n","sub_path":"storm_analysis/voronoi/voronoi_analysis.py","file_name":"voronoi_analysis.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"558467814","text":"from math import atan2, hypot, atan2, cos, sin, ceil\nfrom Beagle import API as BGL\nfrom Newfoundland.Object import Object\n\nclass Door(Object):\n \"\"\"docstring for Door.\"\"\"\n def __init__(self, **kwargs):\n overrides = {\n \"open_coord\" : [0.0, 0.0],\n \"speed\" : 0.03,\n \"moving\" : False,\n \"opened\" : False\n }\n\n overrides.update(kwargs)\n Object.__init__(self, **overrides)\n\n def get_players(self):\n return self.floor.building.players\n\n def check_for_players(self):\n players = self.get_players()\n for player in players:\n dis = hypot(player.p[0] - self.p[0], player.p[1] - self.p[1])\n\n if dis <= 5.0 and self.opened == False:\n self.moving = True\n return\n\n def open_door(self):\n if self.moving:\n if ceil(self.open_coord[0] - self.p[0]) == 0 and ceil(self.open_coord[1] - self.p[1] == 0):\n self.moving = False\n self.opened = True;\n else:\n rad = atan2(self.open_coord[1] - self.p[1], self.open_coord[0] - self.p[0])\n self.p[0] += cos(rad) * self.speed\n self.p[1] += sin(rad) * self.speed\n\n def tick(self):\n self.check_for_players()\n self.open_door()\n return True\n","sub_path":"src/Entity/Door.py","file_name":"Door.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"34397711","text":"import abc\nimport numpy as np\n\nclass Simulator(abc.ABC):\n def __init__(self):\n super().__init__()\n\n def SimulateGame(self, authority, maximum_number_of_moves, starting_position=None,\n player=None):\n if starting_position is None:\n starting_position = authority.InitialPosition()\n players = authority.PlayersList()\n if player is None:\n player = players[0]\n\n winner = None\n number_of_moves = 0\n position = starting_position\n positionsList = [position]\n while winner is None and number_of_moves < maximum_number_of_moves:\n moveArr = self.ChooseAMove(authority, position, player)\n position, winner = authority.Move(position, player, moveArr)\n number_of_moves += 1\n positionsList.append(position)\n player = authority.OtherPlayer(player)\n return positionsList, winner\n\n\n @abc.abstractmethod\n def ChooseAMove(self, authority, position, player):\n pass\n\n\n\nclass RandomSimulator(Simulator):\n def __init__(self):\n super().__init__()\n\n def ChooseAMove(self, authority, position, player):\n legal_moves_mask = authority.LegalMovesMask(position, player)\n legal_moves_coords = np.transpose(np.nonzero(legal_moves_mask))\n # legal_moves_coords.shape = (number_of_legal_moves, 4)\n if legal_moves_coords.shape[0] == 0:\n return None\n chosen_move_ndx = np.random.randint(legal_moves_coords.shape[0])\n chosen_move = np.zeros(authority.MoveArrayShape(), dtype=np.uint8)\n chosen_move[legal_moves_coords[chosen_move_ndx, 0], legal_moves_coords[chosen_move_ndx, 1],\n legal_moves_coords[chosen_move_ndx, 2], legal_moves_coords[chosen_move_ndx, 3]] = 1\n return chosen_move","sub_path":"simulation/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"654464045","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\ncVigenerreTable = []\r\ncLetterA = ord('А')\r\ncLetters = 33\r\n\r\ndef filtered(msg):\r\n return [chr((ord(x) - cLetterA) % 32 + cLetterA) \\\r\n for x in msg \\\r\n if ord(x) in range(cLetterA, cLetterA + 2 * cLetters + 1)]\r\n\r\ndef cipher(key, msg):\r\n \r\n res = ''\r\n for i, c in enumerate(filtered(msg)):\r\n j = i % len(key)\r\n posM = ord(c) - cLetterA\r\n posK = ord(key[j]) - cLetterA\r\n print(posM, posK)\r\n res += cVigenerreTable[posM][posK]\r\n return res\r\n \r\ndef decipher(key, msg):\r\n \r\n res = ''\r\n for i, c in enumerate(filtered(msg)):\r\n j = i % len(key)\r\n posM = ord(key[j]) - cLetterA\r\n posK = cVigenerreTable[posM].index(c)\r\n res += cVigenerreTable[0][posK]\r\n return res\r\n \r\nif __name__ == \"__main__\":\r\n cVigenerreTable = []\r\n\r\n for i in range(32):\r\n dummy = ''\r\n dummy += ''.join([chr(x) for x in range(ord('А') + i, ord('Я') + 1)])\r\n dummy += ''.join([chr(x) for x in range(ord('А'), ord('А') + i)])\r\n cVigenerreTable.append(dummy)\r\n del dummy\r\n ","sub_path":"VegenerreCipher.py","file_name":"VegenerreCipher.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"557233490","text":"# Copyright 2021 Zhongyang Zhang\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport inspect\nimport importlib\nimport pickle as pkl\nimport torch\nimport pytorch_lightning as pl\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.sampler import WeightedRandomSampler\n\n\nclass DInterface(pl.LightningDataModule):\n def __init__(self, num_workers=8,\n dataset='',\n train_dataset='',\n test_dataset='',\n val_dataset='',\n batch_size = 8,\n **kwargs):\n super().__init__()\n self.num_workers = num_workers\n self.dataset = dataset\n self.num_workers = num_workers\n self.train_dataset = train_dataset\n self.test_dataset = test_dataset\n self.val_dataset = val_dataset\n self.batch_size = batch_size\n self.load_data_module()\n \n def setup(self, stage=None):\n # Assign train/val datasets for use in dataloaders\n if stage == 'fit' or stage is None:\n self.trainset = self.data_module(dataset=self.train_dataset, train=True)\n self.valset = self.data_module(dataset=self.val_dataset, train=False)\n\n # Assign test dataset for use in dataloader(s)\n if stage == 'test' or stage is None:\n self.testset = self.data_module(dataset=self.test_dataset, train=False)\n\n # # If you need to balance your data using Pytorch Sampler,\n # # please uncomment the following lines.\n \n # with open('./data/ref/samples_weight.pkl', 'rb') as f:\n # self.sample_weight = pkl.load(f)\n\n # def train_dataloader(self):\n # sampler = WeightedRandomSampler(self.sample_weight, len(self.trainset)*20)\n # return DataLoader(self.trainset, batch_size=self.batch_size, num_workers=self.num_workers, sampler = sampler)\n\n def collate_fn(self, dataset):\n img, anno = zip(*dataset)\n \n return torch.FloatTensor(img).unsqueeze(1), torch.LongTensor(anno)\n \n def train_dataloader(self):\n return DataLoader(self.trainset, batch_size=self.batch_size, num_workers=self.num_workers, collate_fn=self.collate_fn, shuffle=True)\n\n def val_dataloader(self):\n return DataLoader(self.valset, batch_size=self.batch_size, num_workers=self.num_workers, collate_fn=self.collate_fn, shuffle=False)\n\n def test_dataloader(self):\n return DataLoader(self.testset, batch_size=self.batch_size, num_workers=self.num_workers, collate_fn=self.collate_fn, shuffle=False)\n\n def load_data_module(self):\n name = self.dataset\n # Change the `snake_case.py` file name to `CamelCase` class name.\n # Please always name your model file name as `snake_case.py` and\n # class name corresponding `CamelCase`.\n camel_name = ''.join([i.capitalize() for i in name.split('_')])\n try:\n self.data_module = getattr(importlib.import_module(\n '.'+name, package=__package__), camel_name)\n except:\n raise ValueError(\n f'Invalid Dataset File Name or Invalid Class Name data.{name}.{camel_name}')\n","sub_path":"dataset/data_interface.py","file_name":"data_interface.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"615776150","text":"from data_loader import DataSet\nfrom measures import get_measures\n\n\nclass NaiveBayes:\n \"\"\"\n class NaiveBayes implements Naive Bayes algorithm\n \"\"\"\n def __init__(self, index_to_attribute):\n \"\"\"\n constructor\n :param index_to_attribute: an ordered list with attributes-id as in input label\n \"\"\"\n self._index_to_attribute = index_to_attribute\n self._attribute_to_index = {att: i for i, att in enumerate(self._index_to_attribute)}\n # P(Attribute=value | Label=y), P(Label=y)\n self._prob_feature_given_label, self._prob_labels = None, None\n\n def fit(self, ds: DataSet):\n \"\"\"\n calculate probabilities according to train-set\n :return: P(Attribute=value | Label=y), P(Label=y)\n \"\"\"\n # { attribute: possible-values }\n feature_to_values = {att: set() for att in self._index_to_attribute}\n # count_labels #(Label=y)\n # count_features_and_label #(Attribute=value /\\ Label=y)\n count_labels, count_features_and_label = {}, {}\n\n # go over the data and count the above\n for vec, label in ds:\n # #(Label=y) += 1\n count_labels[label] = count_labels.get(label, 0) + 1\n for i, att in enumerate(self._index_to_attribute):\n feature_to_values[att].add(vec[i])\n # (Attribute=value /\\ Label=y) += 1\n count_features_and_label[(att, vec[self._attribute_to_index[att]], label)] = \\\n count_features_and_label.get((att, vec[self._attribute_to_index[att]], label), 0) + 1\n\n # # { attribute: | possible-values | }\n feature_to_values = {att: len(values_set) for att, values_set in feature_to_values.items()}\n\n # P(Label=y) = #(Label=y) / #(ALL)\n self._prob_labels = {label: count / len(ds) for label, count in count_labels.items()}\n # #(Attribute=value /\\ Label=y) + 1\n # P(Attribute=value | Label=y) = ---------------------------------------\n # #(Label=y) + | Attribute-Values |\n self._prob_feature_given_label = {(att, val, label): (count + 1) /\n (count_labels[label] + feature_to_values[att])\n for (att, val, label), count in count_features_and_label.items()}\n return self._prob_labels, self._prob_feature_given_label\n\n def _multiply(self, vec):\n \"\"\"\n cant use any packages so ... :\\\n \"\"\"\n res = 1\n for v in vec:\n res *= v\n return res\n\n def predict(self, test_ds: DataSet):\n # if no probabilities were calculated\n if self._prob_labels is None:\n print(\"fit on a train set first\")\n return\n\n true, predict = [], []\n # for each example\n for vec, true_label in test_ds:\n score_labels = {}\n for label in self._prob_labels:\n # Given Vec = [A_1=v_1, A_2=v_2, .... A_n=v_n], Label=y\n # calculate for each label y, and return argmax\n # ______\n # ( | | P(A_i=v_i | Label=y) ) * P(Label=y)\n # i\n score_labels[label] = self._multiply([self._prob_feature_given_label[(att, vec[i], label)]\n for i, att in enumerate(self._index_to_attribute)] +\n [self._prob_labels[label]])\n pred = max(score_labels.items(), key=lambda x: x[1])[0]\n\n # return prediction and label\n predict.append(pred)\n true.append(true_label)\n\n return predict, true\n\n\ndef check_naive_bayes():\n ds_ = DataSet(\"dataset.txt\")\n naive_bayes_ = NaiveBayes(ds_.header)\n naive_bayes_.fit(ds_)\n predict, true = naive_bayes_.predict(ds_)\n\n TP, TN, FP, FN, acc, recall, precision, f1 = get_measures(predict, true)\n print(\"accuracy:\", acc, \"\\n\"\n \"recall:\", recall, \"\\n\"\n \"precision:\", precision, \"\\n\"\n \"f1:\", f1, \"\\n\")\n\n\nif __name__ == '__main__':\n check_naive_bayes()\n","sub_path":"naive_bayes.py","file_name":"naive_bayes.py","file_ext":"py","file_size_in_byte":4226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"567669624","text":"empty_list = []\n# 0 1 2 3 4 5 6 7 8 9 \nCityList = [\"Oakland\", \"Atlanta\", \"New York City\",\"Seattle\", \"Memphis\", \"Miami\", \"Boston\", \"Los Angeles\", \"Denver\", \"New Orleans\"]\n\n#three_cities= CityList[0:3]\n#print(three_cities)\n\nCityList[0] = \"San Francisco\"\nCityList[2] = \"Brooklyn\"\nCityList[7] = \"Hollywood\"\nCityList[5] = \"Tampa\"\nprint(CityList)\n#US_ciites = CityList[4:8]\n#print(CityList)\n\n#RestaurantList = [\"Bento&Bowls\",\"burger king\",\"T4\",\"panda\",\"chickfila\",\"Evert Jone\",\"Prima\",\"Piedology\",\"Boston Market\",\"Taqueria\"]\n#print(RestaurantList[1])\n\n#technologiesList =[\"Phone\",\"Laptop\",\"Tv\",\"Game console\"]\n#print(technologiesList)","sub_path":"list_practice.py","file_name":"list_practice.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"332604487","text":"import os\n\nimport numpy as np\nimport pytorch_lightning as pl\nimport torch\nfrom matplotlib import pyplot as plt\nfrom matplotlib.offsetbox import AnchoredText\nfrom prototorch.utils.celluloid import Camera\nfrom prototorch.utils.colors import color_scheme\nfrom prototorch.utils.utils import (gif_from_dir, make_directory,\n prettify_string)\nfrom torch.utils.data import DataLoader, Dataset\n\n\nclass VisWeights(pl.Callback):\n \"\"\"Abstract weight visualization callback.\"\"\"\n def __init__(\n self,\n data=None,\n ignore_last_output_row=False,\n label_map=None,\n project_mesh=False,\n project_protos=False,\n voronoi=False,\n axis_off=True,\n cmap=\"viridis\",\n show=True,\n display_logs=True,\n display_logs_settings={},\n pause_time=0.5,\n border=1,\n resolution=10,\n interval=False,\n save=False,\n snap=True,\n save_dir=\"./img\",\n make_gif=False,\n make_mp4=False,\n verbose=True,\n dpi=500,\n fps=5,\n figsize=(11, 8.5), # standard paper in inches\n prefix=\"\",\n distance_layer_index=-1,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.data = data\n self.ignore_last_output_row = ignore_last_output_row\n self.label_map = label_map\n self.voronoi = voronoi\n self.axis_off = True\n self.project_mesh = project_mesh\n self.project_protos = project_protos\n self.cmap = cmap\n self.show = show\n self.display_logs = display_logs\n self.display_logs_settings = display_logs_settings\n self.pause_time = pause_time\n self.border = border\n self.resolution = resolution\n self.interval = interval\n self.save = save\n self.snap = snap\n self.save_dir = save_dir\n self.make_gif = make_gif\n self.make_mp4 = make_mp4\n self.verbose = verbose\n self.dpi = dpi\n self.fps = fps\n self.figsize = figsize\n self.prefix = prefix\n self.distance_layer_index = distance_layer_index\n self.title = \"Weights Visualization\"\n make_directory(self.save_dir)\n\n def _skip_epoch(self, epoch):\n if self.interval:\n if epoch % self.interval != 0:\n return True\n return False\n\n def _clean_and_setup_ax(self):\n ax = self.ax\n if not self.snap:\n ax.cla()\n ax.set_title(self.title)\n if self.axis_off:\n ax.axis(\"off\")\n\n def _savefig(self, fignum, orientation=\"horizontal\"):\n figname = f\"{self.save_dir}/{self.prefix}{fignum:05d}.png\"\n figsize = self.figsize\n if orientation == \"vertical\":\n figsize = figsize[::-1]\n elif orientation == \"horizontal\":\n pass\n else:\n pass\n self.fig.set_size_inches(figsize, forward=False)\n self.fig.savefig(figname, dpi=self.dpi)\n\n def _show_and_save(self, epoch):\n if self.show:\n plt.pause(self.pause_time)\n if self.save:\n self._savefig(epoch)\n if self.snap:\n self.camera.snap()\n\n def _display_logs(self, ax, epoch, logs):\n if self.display_logs:\n settings = dict(\n loc=\"lower right\",\n # padding between the text and bounding box\n pad=0.5,\n # padding between the bounding box and the axes\n borderpad=1.0,\n # https://matplotlib.org/api/text_api.html#matplotlib.text.Text\n prop=dict(\n fontfamily=\"monospace\",\n fontweight=\"medium\",\n fontsize=12,\n ),\n )\n\n # Override settings with self.display_logs_settings.\n settings = {**settings, **self.display_logs_settings}\n\n log_string = f\"\"\"Epoch: {epoch:04d},\n val_loss: {logs.get('val_loss', np.nan):.03f},\n val_acc: {logs.get('val_acc', np.nan):.03f},\n loss: {logs.get('loss', np.nan):.03f},\n acc: {logs.get('acc', np.nan):.03f}\n \"\"\"\n log_string = prettify_string(log_string, end=\"\")\n # https://matplotlib.org/api/offsetbox_api.html#matplotlib.offsetbox.AnchoredText\n anchored_text = AnchoredText(log_string, **settings)\n self.ax.add_artist(anchored_text)\n\n def on_train_start(self, trainer, pl_module, logs={}):\n self.fig = plt.figure(self.title)\n self.fig.set_size_inches(self.figsize, forward=False)\n self.ax = self.fig.add_subplot(111)\n self.camera = Camera(self.fig)\n\n def on_train_end(self, trainer, pl_module, logs={}):\n if self.make_gif:\n gif_from_dir(directory=self.save_dir,\n prefix=self.prefix,\n duration=1.0 / self.fps)\n if self.snap and self.make_mp4:\n animation = self.camera.animate()\n vid = os.path.join(self.save_dir, f\"{self.prefix}animation.mp4\")\n if self.verbose:\n print(f\"Saving mp4 under {vid}.\")\n animation.save(vid, fps=self.fps, dpi=self.dpi)\n\n\nclass VisPointProtos(VisWeights):\n \"\"\"Visualization of prototypes.\n .. TODO::\n Still in Progress.\n \"\"\"\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.title = \"Point Prototypes Visualization\"\n self.data_scatter_settings = {\n \"marker\": \"o\",\n \"s\": 30,\n \"edgecolor\": \"k\",\n \"cmap\": self.cmap,\n }\n self.protos_scatter_settings = {\n \"marker\": \"D\",\n \"s\": 50,\n \"edgecolor\": \"k\",\n \"cmap\": self.cmap,\n }\n\n def on_epoch_start(self, trainer, pl_module, logs={}):\n epoch = trainer.current_epoch\n if self._skip_epoch(epoch):\n return True\n\n self._clean_and_setup_ax()\n\n protos = pl_module.prototypes\n labels = pl_module.proto_layer.prototype_labels.detach().cpu().numpy()\n\n if self.project_protos:\n protos = self.model.projection(protos).numpy()\n\n color_map = color_scheme(n=len(set(labels)),\n cmap=self.cmap,\n zero_indexed=True)\n # TODO Get rid of the assumption y values in [0, num_of_classes]\n label_colors = [color_map[l] for l in labels]\n\n if self.data is not None:\n x, y = self.data\n # TODO Get rid of the assumption y values in [0, num_of_classes]\n y_colors = [color_map[l] for l in y]\n # x = self.model.projection(x)\n if not isinstance(x, np.ndarray):\n x = x.numpy()\n\n # Plot data points.\n self.ax.scatter(x[:, 0],\n x[:, 1],\n c=y_colors,\n **self.data_scatter_settings)\n\n # Paint decision regions.\n if self.voronoi:\n border = self.border\n resolution = self.resolution\n x = np.vstack((x, protos))\n x_min, x_max = x[:, 0].min(), x[:, 0].max()\n y_min, y_max = x[:, 1].min(), x[:, 1].max()\n x_min, x_max = x_min - border, x_max + border\n y_min, y_max = y_min - border, y_max + border\n try:\n xx, yy = np.meshgrid(\n np.arange(x_min, x_max, (x_max - x_min) / resolution),\n np.arange(y_min, y_max, (x_max - x_min) / resolution),\n )\n except ValueError as ve:\n print(ve)\n raise ValueError(f\"x_min: {x_min}, x_max: {x_max}. \"\n f\"x_min - x_max is {x_max - x_min}.\")\n except MemoryError as me:\n print(me)\n raise ValueError(\"Too many points. \"\n \"Try reducing the resolution.\")\n mesh_input = np.c_[xx.ravel(), yy.ravel()]\n\n # Predict mesh labels.\n if self.project_mesh:\n mesh_input = self.model.projection(mesh_input)\n\n y_pred = pl_module.predict(torch.Tensor(mesh_input))\n y_pred = y_pred.reshape(xx.shape)\n\n # Plot voronoi regions.\n self.ax.contourf(xx, yy, y_pred, cmap=self.cmap, alpha=0.35)\n\n self.ax.set_xlim(left=x_min + 0, right=x_max - 0)\n self.ax.set_ylim(bottom=y_min + 0, top=y_max - 0)\n\n # Plot prototypes.\n self.ax.scatter(protos[:, 0],\n protos[:, 1],\n c=label_colors,\n **self.protos_scatter_settings)\n\n # self._show_and_save(epoch)\n\n def on_epoch_end(self, trainer, pl_module, logs={}):\n epoch = trainer.current_epoch\n self._display_logs(self.ax, epoch, logs)\n self._show_and_save(epoch)\n\n\nclass Vis2DAbstract(pl.Callback):\n def __init__(self,\n data,\n title=\"Prototype Visualization\",\n cmap=\"viridis\",\n border=1,\n resolution=50,\n show_protos=True,\n tensorboard=False,\n show_last_only=False,\n pause_time=0.1,\n block=False):\n super().__init__()\n\n if isinstance(data, Dataset):\n x, y = next(iter(DataLoader(data, batch_size=len(data))))\n x = x.view(len(data), -1) # flatten\n else:\n x, y = data\n self.x_train = x\n self.y_train = y\n\n self.title = title\n self.fig = plt.figure(self.title)\n self.cmap = cmap\n self.border = border\n self.resolution = resolution\n self.show_protos = show_protos\n self.tensorboard = tensorboard\n self.show_last_only = show_last_only\n self.pause_time = pause_time\n self.block = block\n\n def precheck(self, trainer):\n if self.show_last_only:\n if trainer.current_epoch != trainer.max_epochs - 1:\n return False\n return True\n\n def setup_ax(self, xlabel=None, ylabel=None):\n ax = self.fig.gca()\n ax.cla()\n ax.set_title(self.title)\n ax.axis(\"off\")\n if xlabel:\n ax.set_xlabel(\"Data dimension 1\")\n if ylabel:\n ax.set_ylabel(\"Data dimension 2\")\n return ax\n\n def get_mesh_input(self, x):\n x_min, x_max = x[:, 0].min() - self.border, x[:, 0].max() + self.border\n y_min, y_max = x[:, 1].min() - self.border, x[:, 1].max() + self.border\n xx, yy = np.meshgrid(np.arange(x_min, x_max, 1 / self.resolution),\n np.arange(y_min, y_max, 1 / self.resolution))\n mesh_input = np.c_[xx.ravel(), yy.ravel()]\n return mesh_input, xx, yy\n\n def plot_data(self, ax, x, y):\n ax.scatter(\n x[:, 0],\n x[:, 1],\n c=y,\n cmap=self.cmap,\n edgecolor=\"k\",\n marker=\"o\",\n s=30,\n )\n\n def plot_protos(self, ax, protos, plabels):\n ax.scatter(\n protos[:, 0],\n protos[:, 1],\n c=plabels,\n cmap=self.cmap,\n edgecolor=\"k\",\n marker=\"D\",\n s=50,\n )\n\n def add_to_tensorboard(self, trainer, pl_module):\n tb = pl_module.logger.experiment\n tb.add_figure(tag=f\"{self.title}\",\n figure=self.fig,\n global_step=trainer.current_epoch,\n close=False)\n\n def log_and_display(self, trainer, pl_module):\n if self.tensorboard:\n self.add_to_tensorboard(trainer, pl_module)\n if not self.block:\n plt.pause(self.pause_time)\n else:\n plt.show(block=True)\n\n def on_train_end(self, trainer, pl_module):\n plt.show()\n\n\nclass VisGLVQ2D(Vis2DAbstract):\n def on_epoch_end(self, trainer, pl_module):\n if not self.precheck(trainer):\n return True\n\n protos = pl_module.prototypes\n plabels = pl_module.prototype_labels\n x_train, y_train = self.x_train, self.y_train\n ax = self.setup_ax(xlabel=\"Data dimension 1\",\n ylabel=\"Data dimension 2\")\n self.plot_data(ax, x_train, y_train)\n self.plot_protos(ax, protos, plabels)\n x = np.vstack((x_train, protos))\n mesh_input, xx, yy = self.get_mesh_input(x)\n y_pred = pl_module.predict(torch.Tensor(mesh_input))\n y_pred = y_pred.reshape(xx.shape)\n ax.contourf(xx, yy, y_pred, cmap=self.cmap, alpha=0.35)\n\n self.log_and_display(trainer, pl_module)\n\n\nclass VisSiameseGLVQ2D(Vis2DAbstract):\n def __init__(self, *args, map_protos=True, **kwargs):\n super().__init__(*args, **kwargs)\n self.map_protos = map_protos\n\n def on_epoch_end(self, trainer, pl_module):\n if not self.precheck(trainer):\n return True\n\n protos = pl_module.prototypes\n plabels = pl_module.prototype_labels\n x_train, y_train = self.x_train, self.y_train\n x_train = pl_module.backbone(torch.Tensor(x_train)).detach()\n if self.map_protos:\n protos = pl_module.backbone(torch.Tensor(protos)).detach()\n ax = self.setup_ax()\n self.plot_data(ax, x_train, y_train)\n if self.show_protos:\n self.plot_protos(ax, protos, plabels)\n x = np.vstack((x_train, protos))\n mesh_input, xx, yy = self.get_mesh_input(x)\n else:\n mesh_input, xx, yy = self.get_mesh_input(x_train)\n y_pred = pl_module.predict_latent(torch.Tensor(mesh_input))\n y_pred = y_pred.reshape(xx.shape)\n ax.contourf(xx, yy, y_pred, cmap=self.cmap, alpha=0.35)\n\n self.log_and_display(trainer, pl_module)\n\n\nclass VisCBC2D(Vis2DAbstract):\n def on_epoch_end(self, trainer, pl_module):\n if not self.precheck(trainer):\n return True\n\n x_train, y_train = self.x_train, self.y_train\n protos = pl_module.components\n ax = self.setup_ax(xlabel=\"Data dimension 1\",\n ylabel=\"Data dimension 2\")\n self.plot_data(ax, x_train, y_train)\n self.plot_protos(ax, protos, \"w\")\n x = np.vstack((x_train, protos))\n mesh_input, xx, yy = self.get_mesh_input(x)\n y_pred = pl_module.predict(torch.Tensor(mesh_input))\n y_pred = y_pred.reshape(xx.shape)\n\n ax.contourf(xx, yy, y_pred, cmap=self.cmap, alpha=0.35)\n\n self.log_and_display(trainer, pl_module)\n\n\nclass VisNG2D(Vis2DAbstract):\n def on_epoch_end(self, trainer, pl_module):\n if not self.precheck(trainer):\n return True\n\n x_train, y_train = self.x_train, self.y_train\n protos = pl_module.prototypes\n cmat = pl_module.topology_layer.cmat.cpu().numpy()\n\n ax = self.setup_ax(xlabel=\"Data dimension 1\",\n ylabel=\"Data dimension 2\")\n self.plot_data(ax, x_train, y_train)\n self.plot_protos(ax, protos, \"w\")\n\n # Draw connections\n for i in range(len(protos)):\n for j in range(i, len(protos)):\n if cmat[i][j]:\n ax.plot(\n [protos[i, 0], protos[j, 0]],\n [protos[i, 1], protos[j, 1]],\n \"k-\",\n )\n\n self.log_and_display(trainer, pl_module)\n","sub_path":"prototorch/models/vis.py","file_name":"vis.py","file_ext":"py","file_size_in_byte":15633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"550548720","text":"from django.core.urlresolvers import reverse_lazy\nfrom django.shortcuts import render\nfrom django.views.generic import edit\nfrom forms.forms import IncidentReportForm\nfrom forms.models import Terms, IncidentReport\n\ndef HomeView(request):\n \"\"\"\n Site metadata, lists latest forms.\n \"\"\"\n\n context_dict = {}\n return render(request, 'forms/index.html', context_dict)\n\nclass CreateIncidentView(edit.FormView):\n \"\"\"\n Create report form.\n \"\"\"\n\n form_class = IncidentReportForm\n template_name = 'forms/add_incident.html'\n saved_form_object = ''\n success_url = reverse_lazy('home')\n\n def form_valid(self, form):\n saved_form_object = form.save()\n return super(CreateIncidentView, self).form_valid(form)\n\n# def CreateIncidentView(request):\n# context_dict = {}\n\n# if request.method == 'POST':\n# form=IncidentReportForm(request.POST)\n\n# if form.is_valid():\n# form.save(commit=True)\n# return HomeView(request)\n# else:\n# print (form.errors)\n\n# else:\n# form = IncidentReportForm()\n\n# return render(request, 'forms/add_incident.html', {'form': form})\n\n\ndef IncidentReportView(request):\n \"\"\"\n Summarizes report, produces pdf, emails recipient.\n \"\"\"\n\n context_dict = {}\n return render(request, 'forms/incident.html', context_dict)\n\n\ndef AboutView(request):\n \"\"\"\n Mission statement.\n \"\"\"\n\n context_dict = {}\n return render(request, 'forms/about.html', context_dict)\n\n\ndef ContactView(request):\n \"\"\"\n How to reach us.\n \"\"\"\n\n context_dict = {}\n return render(request, 'forms/contact.html', context_dict)\n","sub_path":"RA/forms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"378020247","text":"import random\n\n\n# Define all values that the game needs in the data structure\ndata = {\n \"easy\":{\n \"question\":[\n \"I __?__ dropped the camera\",\n \"The dressing room was __?__ ,blindingly bright.\",\n \"measure the impact of the tusnami __?__\",\n \"This book is __?__ by any standards.\"\n ],\n \"answer\":[\n [\"accidentally\",\"hypothetically\",\"punctuality\",\"decently\"],\n [\"brilliantly\" , \"spiritually\", \"sincerely\",\"friendly\"],\n [\"accurately\",\"ironically\",\"intentionally\",\"friendly\"],\n [\"extraordinary\",\"accidentally\",\"brilliantly\",\"barely\"]\n ]},\n \"medium\":{\n \"question\":[\n \"it is easy to see great opportunity in the __?__ future.\",\n \"There was a little __?__ in her description.\",\n \"one must present a __?__ source of annual income.\",\n \"What kind of services does the job __?__ office provide?\"\n ],\n \"answer\":[\n [\"foreseeable\",\"obtainable\",\"assorted\",\"persuasive\"],\n [\"exaggeration\",\"strain\",\"propety\",\"collision\"],\n [\"verifiable\",\"foreseeable\",\"sizable\",\"preceded\"],\n [\"placement\", \"behalf\", \"diversification\",\"subtraction\"]\n ]},\n \"hard\":{\n \"question\":[\n \"What do you think is a __?__ for succeeding in business?\",\n \"he was trying hard to __?__ the code himself.\",\n \"The object appears __?__ to the naked eye , but with glasses it's clear.\",\n \"The boss tends to decide __?__ without listening to other opinion.\"\n ],\n \"answer\":[\n [\"prerequisite\",\"collateral\",\"disclaimer\",\"vault\"],\n [\"decipher\",\"demoralize\",\"waive\",\"pertain\"],\n [\"blurry\",\"expedient\",\"looming\",\"volatile\"],\n [\"arbitrarily\",\"detrimental\",\"futile\",\"sturdy\"]\n ]\n }\n}\n\n\n\ndef level_selection():\n user_input = raw_input(\"Choose the difficulty of quize in number or string: (1.Easy 2.Medium 3.Hard)\").lower()\n game_level = [\"easy\",\"medium\",\"hard\"]\n max = 4\n if user_input in game_level:\n return user_input\n elif user_input in str(range(1,max)):\n return game_level[int(user_input) - 1]\n else:\n print(\"Incorrect level! Try again!\")\n return level_selection()\n#chosse the difficulty of game level_answer\n#output:the list of questions and answers of selected level\n\n\n\ndef check_correct(user_input,random_index,game_level):\n correct_answer = data[game_level][\"answer\"][random_index][0]\n current_question = data[game_level][\"question\"][random_index]\n if user_input == correct_answer :\n print(\"Correct! The answer is '\" + current_question.replace(\"__?__\" , correct_answer) + \"' !!\")\n else:\n print(\"Wrong! Try again!\")\n user_input = raw_input()\n check_correct(user_input,random_index,game_level)\n#check whether the user_input is correct or wrong\n#argument:\n#user_input:user_input\n#random_index:used for finding the corresponding list from easy_answer list and get the correct answers\n#output:sentence varying due to correct or wrong\n\n\n\ndef show_possible_choice(random_index,game_level):\n index = 0\n alreday_exist = []\n alt = 3\n several_answer = data[game_level][\"answer\"][random_index]\n while index <= 3:\n random_index_choce = random.randint(0,alt)\n while random_index_choce in alreday_exist:\n random_index_choce = random.randint(0,alt)\n print (several_answer[random_index_choce])\n alreday_exist.append(random_index_choce)\n index += 1\n#show up every possible choices in random order.\n#argument:\n#random_index:random number for selecting question and corresponding possible choice list.\n#output:possible choices\n\n\n\ndef core_operation():\n index = 0\n len_question = len(data[game_level][\"question\"])\n alreday_given_question = []\n number_questions = 4\n while index < number_questions:\n random_index = random.randint(0,len_question-1)\n while random_index in alreday_given_question:\n random_index = random.randint(0,len_question-1)\n print (data[game_level][\"question\"][random_index])\n show_possible_choice(random_index,game_level)\n user_input = raw_input(\"Select answer from 4 choice written above: \")\n check_correct(user_input,random_index,game_level)\n alreday_given_question.append(random_index)\n index += 1\n print (\"Congratulation! You completed this quiz!!\")\n#do main operation after level selected\n#if user type correct answer , show next question and do it 4 times in a row.\n\n\ngame_level = level_selection()\ncore_operation()\n","sub_path":"fill-in-the-blanks.py","file_name":"fill-in-the-blanks.py","file_ext":"py","file_size_in_byte":4663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"534067172","text":"import matplotlib.pyplot as plt\nimport csv\n\n\ndef data(filename):\n with open(filename, encoding='utf-8') as d:\n reader = csv.reader(d)\n data = list(reader)\n\n labels = data[0]\n percents = []\n for percent in data[1]:\n percents.append(float(percent))\n return labels, percents\n\n\ndef graphic(plot, data, labels, explode, radius=1, center=(0, 0)):\n plot.pie(data, labels=labels, autopct='%1.1f%%', explode=explode, radius=radius, shadow=True, center=center)\n plot.legend(loc='lower right', labels=labels, title=\"Страны\", shadow=True)\n\n\nl1, d1 = data('data2014.csv')\nl2, d2 = data('data2019.csv')\n\nfig, (rating_2014, rating_2019) = plt.subplots(1, 2)\nfig.canvas.set_window_title('ТОП-10 стран по добыче нефти в 2014-2019 годах')\n\n# рисуем первую диаграмму\ngraphic(rating_2014, d1, l1, (0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0))\nrating_2014.set_title('Добыча нефти в 2014')\n\n# рисуем вторую диаграмму\ngraphic(rating_2019, d2, l2, (0, 0.1, 0, 0, 0, 0, 0, 0, 0, 0))\nrating_2019.set_title('Добыча нефти в 2019')\n\n# показываем график\nplt.show()\n","sub_path":"Programming-basics/Labs-for-collegues/Eyyub-Bodur/Lab8/laba8.py","file_name":"laba8.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"383984125","text":"def solve(d):\n\tif d == 0:\n\t\treturn 'INSOMNIA'\n\tseen = set()\n\ti = 1\n\twhile True:\n\t\tn = d * i\n\t\twhile n > 0:\n\t\t\tseen.add(n % 10)\n\t\t\tn /= 10\n\t\tif len(seen) == 10:\n\t\t\treturn i * d\n\t\ti += 1\n\nf = open('A.in', 'r')\nout = open('A.out', 'w')\n\nN = int(f.readline())\n\nfor i in xrange(N):\n\td = int(f.readline())\n\tout.write('Case #{0}: {1}\\n'.format(i + 1, solve(d)))\n\nf.close()\nout.close()","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_virajmahesh_A.py","file_name":"16_0_1_virajmahesh_A.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"597553550","text":"#!/usr/bin/python3\n\nimport subprocess\nimport time\nimport os\nimport glob\nimport re\n\n\ndef echo():\n print('TOB: ', tob)\n print('TOS: ', tos)\n print('Orion: ', orion)\n print('Service:', service)\n\n\nif 'TOB' in os.environ:\n tob = float(os.environ['TOB'])\nelse:\n print('TOB not found')\n exit(1)\n\nif 'TOS' in os.environ:\n tos = float(os.environ['TOS'])\nelse:\n print('TOB not found')\n exit(1)\n\nif 'ORION' in os.environ:\n orion = os.environ['ORION']\nelse:\n print('ORION not found')\n exit(1)\n\nif 'SERVICE' in os.environ:\n service = os.environ['SERVICE']\nelse:\n print('SERVICE not found')\n exit(1)\n\nfiles = sorted(glob.glob('/opt/list/*.dmo'))\ninterpreter = 'scala'\nscript = '/opt/app.jar'\n\nwhile True:\n echo()\n for file in files:\n print('processing: ', file)\n subprocess.call([interpreter, script, file, orion, service])\n log = '/opt' + file.split('/opt/list')[1] + '.log'\n for line in open(log, 'r'):\n if not re.search('204', line):\n print('result: ! 204')\n exit(1)\n else:\n print('result: 204')\n os.remove(log)\n print('sleep:', tos)\n time.sleep(tos)\n print('sleep:', tob)\n time.sleep(tob)\n\n","sub_path":"stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"196080545","text":"\"\"\"PyCodeWordStat general utils tests.\"\"\"\n\nimport unittest\n\nfrom pycodewordstat2.iterutils import flat_2d_list\n\n\nclass TestUtils(unittest.TestCase):\n \"\"\"Test cases for general utils.\"\"\"\n\n def test_flat_2d_list(self):\n \"\"\"Test for flat_2d_list().\"\"\"\n def flat_wrapped(*args, **kwargs):\n return list(flat_2d_list(*args, **kwargs))\n\n self.assertSequenceEqual(flat_wrapped([]), [])\n self.assertSequenceEqual(flat_wrapped([(1, 2), (3, 4)]), [1, 2, 3, 4])\n self.assertSequenceEqual(flat_wrapped([[1, 2], (3, 4)]), [1, 2, 3, 4])\n self.assertSequenceEqual(flat_wrapped([(1, 2, 3), (4, 5)]), [1, 2, 3, 4, 5])\n","sub_path":"pycodewordstat2/tests/test_iterutils.py","file_name":"test_iterutils.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"405731111","text":"from typing import List\n\n\nclass Solution:\n def letterCombinations(self, digits: str) -> List[str]:\n \"\"\"\n\n 1\n 0017 中在于先添加,后移除,实际只需要在最后再添加\n\n 2\n 空间降不下去,看了答案,不需要字典\n 结果还是大\n >>> Solution().letterCombinations('23')\n ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']\n \"\"\"\n if not digits:\n return []\n keyboards = [\n '',\n '',\n 'abc',\n 'def',\n 'ghi',\n 'jkl',\n 'mno',\n 'pqrs',\n 'tuv',\n 'wxyz',\n ]\n ans = []\n\n def append(pre, remains):\n if not remains:\n ans.append(pre)\n else:\n number = int(remains[0])\n remains = remains[1:]\n for c in keyboards[number]:\n append(pre + c, remains)\n\n append('', digits)\n return ans\n\n\nif __name__ == '__main__':\n import doctest\n\n doctest.testmod(verbose=True)\n","sub_path":"ToolsX/leetcode/0017/0017_2.py","file_name":"0017_2.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"239295285","text":"import matplotlib # If running over ssh \nmatplotlib.use('agg')\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nimport numpy as np\nimport pandas as pd\nimport datetime as dt\n\ndef get_bogdanova_monthly():\n \"\"\"Returns monthly corrected precipitation from Bogdanova et al. 2002.\"\"\"\n return pd.DataFrame([12.5, 9.5, 9.5, 7.4, 9.2, 12.4, 23.7, 22.4, 20.3, 15.3, 11.1, 11.1,],\n index=np.arange(1,13), columns=['P'])\n\ndef read_data():\n \"\"\"\n Reads csv file containing precipitation along trajectories\n \"\"\"\n which_season = {1: 'DJF', 2: 'DJF', 3: 'MAM', 4: 'MAM',\n 5: 'MAM', 6: 'JJA', 7: 'JJA', 8: 'JJA',\n 9: 'SON', 10: 'SON', 11: 'SON', 12: 'DJF'}\n \n filepath = 'np_reanalysis_month_comparison.csv'\n df = pd.read_csv(filepath, index_col=0)\n df['Date'] = [dt.datetime.strptime(t,'%Y-%m-%d') for t in df['Date']] # Convert date string to datetime\n df['Season'] = [which_season[m] for m in df['Date'].dt.month] # Determine season\n return df\n\ndef main():\n \"\"\"\n Makes plot of monthly precipitation from reanalysis and corrected observations \n from Yang and Bogdanova.\n \"\"\"\n\n P_Bog = get_bogdanova_monthly()\n\n P_df = read_data()\n P_mon = P_df.groupby(P_df['Date'].dt.month).mean()\n P_mon = P_mon.drop(['Lat','Lon','NP'], axis=1)\n P_mon = P_mon.rename(columns={'Pc':'Pyang'})\n P_mon['Pbog'] = P_Bog['P']\n \n # Plot data\n\n x = np.arange(1,13)\n xb = x-0.25\n xy = x+0.25\n width = 0.3\n\n fig, ax = plt.subplots(figsize=(10,7))\n\n ax.set_xlim(0.5,12.5)\n \n ax.bar(xy, P_mon['Pyang'], width=width, color='0.3', edgecolor='none',\n align='center', label='Yang')\n ax.bar(xb, P_mon['Pbog'], width=width, color='0.6', edgecolor='none',\n align='center', label=\"Bogdanova\")\n\n reanalyses = ['ERAI','MERRA2','MERRA','CFSR','JRA55']\n symbols = ['o','v','s','X','*']\n for s, r in zip(symbols,reanalyses):\n ax.plot(x, P_mon[r+'_prectot'], marker=s, linestyle='',\n markersize=10, label=r)\n# ax.plot(x, P_mon[r+'_prectot'], marker=s, linestyle='-',\n# markersize=15, linewidth=1.5, label=r)\n# ax.plot(x, P_mon[r+'_prectot'], linestyle='-', linewidth=3, label=r)\n \n ax.set_ylabel('mm', fontsize=20)\n\n # Make ticks at 'month' boundaries and ticklabels at center\n major = np.arange(1.,13.,1.)\n minor = np.arange(0.5,13.,1.)\n ax.xaxis.set_major_locator(ticker.FixedLocator(major))\n ax.xaxis.set_minor_locator(ticker.FixedLocator(minor))\n ax.set_xticklabels(['J','F','M','A','M','J','J','A','S','O','N','D'],\n fontsize=20)\n ax.tick_params('x', which='major', length=0, labelsize=20)\n ax.tick_params('x', which='minor', width=1., length=10)\n ax.tick_params('y', labelsize=20)\n\n ax.legend(fontsize=17, frameon=False, loc=(0.02,0.5))\n\n fig.savefig('drifting_station_seasonal_cycle_with_reanalysis.png')\n \nif __name__ == \"__main__\":\n main()\n \n \n \n","sub_path":"source/plot_drifting_station_seasonal_cycle.py","file_name":"plot_drifting_station_seasonal_cycle.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"21364803","text":"import pandas as pd\nimport numpy as np\nfrom lib import API, tools\nfrom lib.config import config\nimport os\n\n# concatenates csvs together, takes paths as arguments.\n# we only want to concatenate the sources\ndef concatenateCsv(list):\n df = pd.DataFrame()\n for a in list:\n try:\n if df.empty:\n df = pd.read_csv(a)\n else:\n df = df.append(pd.read_csv(a), ignore_index=True)\n except FileNotFoundError:\n print('File '+a+' not found.')\n if df.empty:\n raise ValueError('Empty dataframe. Reading sources failed.')\n else:\n return df.drop(['shared_from', 'url', 'text'], axis=1).rename({'post_id': 'postId'},axis='columns').drop_duplicates(['postId'])\n\n\n# HARMONIZES DATES AND SOURCES FOR A LIST OF DATAFRAMES, must be summary or fbcrawl output\ndef harmonize(a=[], start=config['start'], end=config['end'], source1=config['source1'], source2=config['source2']):\n start = pd.to_datetime(start, utc=True)\n end = pd.to_datetime(end, utc=True)\n\n for i in range(0, len(a)):\n\n if 'date' in a[i].columns:\n a[i] = a[i][(a[i]['date'].str.match('\\d\\d\\d\\d-\\d\\d-\\d.*', na=True)) | a[i].date.notnull()]\n a[i]['date'] = pd.to_datetime(a[i]['date'], utc=True)\n m = (a[i]['date'] >= start) & (a[i]['date'] <= end)\n a[i] = a[i].loc[m].set_index(['date']).sort_index()\n a[i] = tools.filter(source1, source2, df=a[i], what='source', kind='or')\n\n elif 'publicationTime' in a[i].columns:\n a[i] = a[i][(a[i]['publicationTime'].str.match('\\d\\d\\d\\d-\\d\\d-\\d.*', na=True)) | a[i].publicationTime.notnull()]\n a[i]['publicationTime'] = pd.to_datetime(a[i]['publicationTime'], utc=True)\n m = (a[i]['publicationTime'] >= start) & (a[i]['publicationTime'] <= end)\n a[i] = a[i].loc[m].set_index(['publicationTime']).sort_index().drop(['videoautoplay'], axis=1)\n if 'Unnamed: 0' in a[i].columns:\n a[i] = a[i].drop(['Unnamed: 0'], axis=1)\n a[i] = tools.filter(source1, source2, df=a[i], what='source', kind='or')\n\n else:\n raise ValueError('cannot find the dates column')\n return a\n\ndef mergeData(us, s):\n for i in range(0, len(us)):\n us[i] = pd.DataFrame(us[i]['postId'].value_counts()).reset_index()\n us[i] = us[i].rename({'postId': str(i) + '_count'}, axis='columns')\n us[i] = us[i].rename({'index': 'postId'}, axis='columns')\n s = s.reset_index()\n us[i]['postId'] = us[i]['postId'].astype(str).astype(int) # convert postId to be integer\n s = pd.merge(s, us[i], on='postId', how='outer').fillna(0)\n s[str(i) + '_seen'] = np.where(s[str(i) + '_count'] >= 1, 'yes', 'no')\n s = s[s.date != 0]\n s = s.set_index(['date'])\n return s\n\ndef main():\n a = API.getDf(config['token'], 'summary', config['amount'], config['skip'])\n files = [os.path.join(config['sources'], f) for f in os.listdir(config['sources']) if os.path.isfile(os.path.join(config['sources'], f)) and f.endswith(\".csv\")]\n s = concatenateCsv(files)\n s['source'] = s['source'].str.split(',').str[0] # preventing small errors\n a, s = harmonize([a, s])\n list = [a]\n df = mergeData(list, s).fillna(0)\n out = tools.uniquePath(config['path']+'/combined.csv')\n print('Saving output to '+out)\n df.to_csv(out)\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/combine.py","file_name":"combine.py","file_ext":"py","file_size_in_byte":3424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"604396332","text":"from collections.abc import Iterable\r\nfrom collections.abc import Iterator \r\n\r\n#dictGrade = {\"jiang\":11, \"bang\":23, \"yes\":44}\r\n#dictGrade['no'] = 44 \r\n#\r\n#print(dictGrade)\r\n\r\n#for k, v in dictGrade.items():\r\n# print(k, v)\r\n#print(type(dictGrade.items()))\r\n#\r\n#print(isinstance(dictGrade, Iterable))\r\n#print(isinstance([], Iterable))\r\n#print(isinstance((), Iterable))\r\n#print(isinstance({}, Iterable))\r\n#\r\n#\r\n#print(isinstance(dictGrade, Iterator))\r\n#\r\n#print(type([]))\r\n#print(type(()))\r\n#print(type({}))\r\n\r\n#print(isinstance(dictGrade.items(), Iterable))\r\n#print(dir(list))\r\n\r\n#print(type(dictGrade.keys()))\r\n#for k in dictGrade.keys():\r\n# print(k) \r\n\r\n#print(type(dictGrade.values()))\r\n#for k in dictGrade.values():\r\n# print(k) \r\n#\r\n#print('-----------------')\r\n#for k in set(dictGrade.values()):\r\n# print(k) \r\n# \r\n#l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]\r\n#\r\n#print(l[:100])\r\n\r\n\r\n\r\n\r\n#del dictGrade['jiang']\r\n\r\n#print(dictGrade)\r\n\r\n#t1 = (1, 2, 3, 4)\r\n\r\n#print(t1)\r\n#print(type(t1))\r\n\r\n#print([n*2 for n in t1])\r\n#for n in t1:\r\n# print(n)\r\n\r\n\r\n\r\n\r\n\r\n#print(dictGrade)\r\n#print(dictGrade[\"jiang\"])\r\n#dictGrade[\"jiang\"] = 0 \r\n#\r\n#print(dictGrade[\"jiang\"])\r\n#\r\n#print(dictGrade)\r\n#\r\n#print('liao' in dictGrade)\r\n#print('jiang' in dictGrade)\r\n#\r\n#print(dictGrade.get('liao'))\r\n#print(dictGrade.get('jiang'))\r\n\r\n#if dictGrade.get('liao') == None:\r\n#if not dictGrade.get('liao'):\r\n#listName=[\"jiang\"]\r\n#listName=[]\r\n#print(listName)\r\n#if listName:\r\n# print('not null')\r\n#else:\r\n# print('null')\r\n\r\n#print(dictGrade[\"jiang1\"])\r\n\r\n#setName = set(1, 2, 2, 3, [4, 5])\r\n#setName = set(())\r\n#setName = set((1, 2, (3, 4))) \r\n#setName = set((1, 2, (3, 4))) \r\n#setName = set((1, 2, 3, 4, 4))\r\n#setName = set(range(2))\r\n\r\n#setName[2][0] = 11\r\n\r\n#print(setName)\r\n\r\n#a = 10\r\n#print('{}修改之前的地址:{}'.format(type(a), id(a)))\r\n#a = 11\r\n#print('{}修改之后的地址:{}'.format(type(a), id(a)))\r\n#\r\n#a = 10.11\r\n#print('{}修改之前的地址:{}'.format(type(a), id(a)))\r\n#a = 11.12\r\n#print('{}修改之后的地址:{}'.format(type(a), id(a)))\r\n\r\n#print('{}修改之后的地址:{}'.format(type(type(a)), id(a)))\r\n#\r\n#a = 10\r\n#b = 10\r\n#print('a的类型={}, 地址:{}'.format(type(a), id(a)))\r\n#print('b的类型={}, 地址:{}'.format(type(b), id(b)))\r\n#\r\n#\r\n#if type(a) == type(b):\r\n# print('type of a equal type of b')\r\n#print('yoxi')\r\n#\r\n#a = 10.0\r\n#b = 10\r\n#print('a的类型={}, 地址:{}'.format(type(a), id(a)))\r\n#print('b的类型={}, 地址:{}'.format(type(b), id(b)))\r\n#\r\n#\r\n#if type(a) == type(b):\r\n# print('type of a equal type of b')\r\n#print('yoxi')\r\n\r\n#a = '10.11'\r\n#print('{}修改之前的地址:{}'.format(type(a), id(a)))\r\n#a = '10.11'\r\n#print('{}修改之后的地址:{}'.format(type(a), id(a)))\r\n#\r\n##a = (10.11, 10.11, ['jiang', 'bang'])\r\n#a = (10.11, 10.11 )\r\n#print('{}修改之前的地址:{}'.format(type(a), id(a)))\r\n##a = (10.11, 10.11, ['jiang', 'bang'])\r\n#a = (10.10, 10.11 )\r\n#print('{}修改之后的地址:{}'.format(type(a), id(a)))\r\n#\r\n#\r\n#a = [10.11, 10.11]\r\n#print('{}修改之前的地址:{}'.format(type(a), id(a)))\r\n#a = [10.11, 10.11]\r\n#print('{}修改之后的地址:{}'.format(type(a), id(a)))\r\n\r\n#a = set((1, 2, 3))\r\n#print('{}修改之前的地址:{}'.format(type(a), id(a)))\r\n#print('b = {}'.format(len(a)))\r\n#a =(1, [2, 3])\r\n#a = set((1, [2, 3]))\r\n#print('{}修改之后的地址:{}'.format(type(a), id(a)))\r\n#print('len={}'.format(len(a))\r\n\r\n#alien_0 = {'color':'green', 'points':5}\r\n#alien_1 = {'color':'yellow', 'points':10}\r\n#alien_2 = {'color':'red', 'points':15}\r\n#\r\n#print(alien_0)\r\n#\r\n#aliensList = [alien_0, alien_1, alien_2]\r\n#\r\n#print(aliensList )\r\n#\r\n#for alien in aliensList:\r\n# print(alien)\r\n\r\n#num = input('enter a number: ')\r\n\r\n#num = int(num)\r\n\r\n#print(num)\r\n\r\n\r\n#dict_name = {1:'jiang', 2:'bang', 3:'lian'}\r\n\r\n#print(dict_name)\r\n\r\n#if 4 in dict_name:\r\n# print('in')\r\n#else:\r\n# print('no in')\r\n\r\n\r\n#pets = ['dog', 'cat', 'dog', 'goldfish', 'dog', 'cat']\r\n#print(pets )\r\n#\r\n#while 'dog' in pets:\r\n# pets.remove('dog')\r\n#\r\n#print(pets )\r\n\r\n#def fun1(one=3, two):\r\n# print('one={}, two={}'.format(one, two))\r\n#\r\n#fun1(1, 2)\r\n#fun1(2, 1)\r\n#\r\n#fun1(two=1, one=2)\r\n\r\n#print('one={}, two={}'.format(1, 2))\r\n\r\n#a = ' '\r\n#\r\n#if a:\r\n# print('no null')\r\n#else:\r\n# print('is null')\r\n\r\n#def build_person(first_name, last_name, age=''):\r\n# person = {'first_name':first_name, 'last_name':last_name}\r\n# if age:\r\n# person['age'] = age \r\n# return person\r\n#\r\n#print(build_person('jiang', 'bang', 18))\r\n#print(type(build_person('jiang', 'bang', 18)))\r\n\r\n#print(dir([]))\r\n#print(dir(()))\r\n#print(dir(set()))\r\n#print(dir({}))\r\n\r\n#def fun(one):\r\n# print('in 1 one = {}, id(one) = {}'.format(one, id(one)))\r\n# one = [1, 2, 3] \r\n# print('in 2 one = {}, id(one) = {}'.format(one, id(one)))\r\n#\r\n#one = [1, 2] \r\n#fun(one)\r\n#print('one = {}, id(one) = {}'.format(one, id(one)))\r\n\r\n#def fun(*one):\r\n# print(type(one))\r\n# print(one)\r\n#\r\n#fun(1, 2)\r\n\r\ndef fun(first, last, **userinfo):\r\n profile = {}\r\n\r\n profile['first_name'] = first\r\n profile['last_name'] = last \r\n\r\n print(type(userinfo))\r\n print(userinfo)\r\n\r\n for k, v in userinfo.items():\r\n profile[k] = v\r\n return profile\r\n\r\nprint(fun('jiang', 'bang', age=18, shouru=1000, xingbie='nan'))\r\n\r\n\r\n\r\n","sub_path":"python/other/dict.py","file_name":"dict.py","file_ext":"py","file_size_in_byte":5282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"113620106","text":"import pandas as pd\n\n\ndef dataframe_preprocess(dataframe: pd.DataFrame) -> pd.DataFrame:\n column_headings = ['game.id', 'game.type', 'details.description', 'details.image',\n 'details.maxplayers', 'details.maxplaytime', 'details.minage', 'details.minplayers', 'details.minplaytime',\n 'details.name', 'details.playingtime', 'details.thumbnail', 'details.yearpublished', 'attributes.boardgamecategory',\n 'stats.average', 'stats.bayesaverage']\n # Select useful columns\n selected_columns = dataframe[column_headings]\n # Remove expansions from dataset\n core_dataset = selected_columns[selected_columns['game.type']\n == 'boardgame']\n # NAN filling\n cleaned_data = core_dataset.apply(lambda x: x.fillna(\n 0) if x.dtype.kind in 'biufc' else x.fillna('#'))\n # Lowercase names for ease of searching\n cleaned_data['details.searchname'] = cleaned_data['details.name'].str.lower()\n return cleaned_data\n\n\ndef search_by_name(dataframe: pd.DataFrame, name: str) -> pd.DataFrame:\n '''\n Case-insensitive search of dataframe, based on the games name and the name provided.\n Returns an empty dataframe when no items are found.\n '''\n cleaned_search = name.lower()\n result = dataframe.loc[dataframe['details.searchname'] == cleaned_search]\n if len(result.index) > 0:\n return result.iloc[:, :-1] # Do not return 'details.searchname'\n else:\n return None\n\n\ndef search_by_minplayers(dataframe: pd.DataFrame, players: int) -> pd.DataFrame:\n '''\n Searches the dataframe by minimum players, returns all entries with a minimum player amount >= amount provided.\n Returns an empty dataframe when no items are found.\n '''\n result = dataframe.loc[dataframe['details.minplayers'] >= players]\n if len(result.index) > 0:\n return result.iloc[:, :-1] # Do not return 'details.searchname'\n else:\n return None\n\n\ndef search_by_yearpublished(dataframe: pd.DataFrame, year: int) -> pd.DataFrame:\n '''\n Searches the dataframe by publish date, returns all entries with a published date >= amount provided.\n Returns an empty dataframe when no items are found.\n '''\n result = dataframe.loc[dataframe['details.yearpublished'] >= year]\n if len(result.index) > 0:\n return result.iloc[:, :-1] # Do not return 'details.searchname'\n else:\n return None\n\n\ndef search_by_specific_category(dataframe: pd.DataFrame, categories: list) -> pd.DataFrame:\n '''\n Searches the dataframe by a list of categories, returns all entries with a catergory matches all supplied list.\n Returns an empty dataframe when no items are found.\n '''\n expression = '(?=.*{})'\n result = dataframe.loc[dataframe['attributes.boardgamecategory'].str.contains(\n ''.join(expression.format(category) for category in categories), case=False)]\n if len(result.index) > 0:\n return result.iloc[:, :-1] # Do not return 'details.searchname'\n else:\n return None\n\n\ndef search_by_multiple_category(dataframe: pd.DataFrame, categories: list) -> pd.DataFrame:\n '''\n Searches the dataframe by a list of categories, returns all entries with a catergory contained within supplied list.\n Returns an empty dataframe when no items are found.\n '''\n\n result = dataframe.loc[dataframe['attributes.boardgamecategory'].str.contains(\n '|'.join(categories), case=False)]\n if len(result.index) > 0:\n return result.iloc[:, :-1] # Do not return 'details.searchname'\n else:\n return None\n\n\ndef search_by_playtime(dataframe: pd.DataFrame, playtime: float) -> pd.DataFrame:\n '''\n Searches the dataframe by max playtime, returns all entries with a maximum playtime <= amount provided.\n Returns an empty dataframe when no items are found.\n '''\n result = dataframe.loc[dataframe['details.maxplaytime'] <= playtime]\n if len(result.index) > 0:\n return result.iloc[:, :-1] # Do not return 'details.searchname'\n else:\n return None\n\n\ndef search_by_score(dataframe: pd.DataFrame, score: float) -> pd.DataFrame:\n '''\n Searches the dataframe by weighted user scores, returns all entries with a bayes average >= score provided.\n Returns an empty dataframe when no items are found.\n '''\n result = dataframe.loc[dataframe['stats.bayesaverage'] >= score]\n if len(result.index) > 0:\n return result.iloc[:, :-1] # Do not return 'details.searchname'\n else:\n return None\n","sub_path":"prep-work/preproccessing.py","file_name":"preproccessing.py","file_ext":"py","file_size_in_byte":4539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"475917696","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom ..spec import spec\nfrom ..registry import check\n\n\n# Module API\n\n@check('unique-constraint', type='schema', context='body')\nclass UniqueConstraint(object):\n\n # Public\n\n def __init__(self, **options):\n self.__row_indexes = {}\n\n def check_row(self, errors, cells, row_number):\n for cell in cells:\n\n # Skip if cell is incomplete\n if not set(cell).issuperset(['number', 'header', 'field', 'value']):\n continue\n\n # Skip if not constraint\n constraint = cell['field'].constraints.get('unique')\n if not constraint:\n continue\n\n # Get references\n rindex = self.__row_indexes.setdefault(cell['number'], {})\n references = rindex.setdefault(cell['value'], [])\n\n # Add error\n if references:\n message = spec['errors']['unique-constraint']['message']\n message = message.format(\n row_numbers=', '.join(map(str, references + [row_number])),\n column_number=cell['number'])\n errors.append({\n 'code': 'unique-constraint',\n 'message': message,\n 'row-number': row_number,\n 'column-number': cell['number'],\n })\n\n # Update references\n references.append(row_number)\n","sub_path":"goodtables/checks/unique_constraint.py","file_name":"unique_constraint.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"579747187","text":"from flask_restplus import Namespace, Resource, fields\nfrom firebase_admin import firestore\nfrom flask import request\nfrom .validate import validate\n\napi = Namespace('Workspace', description='Collection of notes', path='/workspace')\ndb = firestore.client()\n\nworkspace = api.model('Workspace', {\n 'id': fields.String(required=False, description='Uuid token'),\n # 'user_uuid': fields.String(required=True, description='User uuid'),\n 'title': fields.String(required=True, description='Workspace title'),\n 'token': fields.String(required=True, description='User unique auth token'),\n 'created_at': fields.DateTime(required=True, description='Created datetime'),\n})\n\nparser = api.parser()\nparser.add_argument(\"Authorization\", location=\"headers\", help=\"Auth token\")\n\n@api.route('/')\n@api.param('id', 'Workspace uuid')\nclass WorkspaceWithId(Resource):\n @api.expect(parser, validate=True)\n def delete(self, id):\n \"\"\"\n Deletes workspace with given id\n \"\"\"\n if not validate(request.headers['Authorization']):\n api.abort(400)\n return\n\n try:\n document = db.collection(u'workspaces').document(id)\n data = document.get().to_dict()\n if data['token'] != request.headers['Authorization']:\n api.abort(400)\n document.delete()\n return {'success': 'success'}\n except:\n api.abort(400)\n\n\n@api.route('/')\nclass Workspace(Resource):\n @api.marshal_list_with(workspace)\n @api.expect(parser, validate=True)\n def get(self):\n \"\"\"\n Returns list of workspaces\n \"\"\"\n if not validate(request.headers['Authorization']):\n api.abort(400)\n return\n\n return [{'id': u.id, **u.to_dict()}\n for u in db.collection(u'workspaces').where(u'token', u'==', request.headers['Authorization']).stream()]\n\n @api.marshal_with(workspace)\n @api.expect(workspace, parser, validate=True)\n def post(self):\n \"\"\"\n Creates new workspace\n \"\"\"\n if not validate(request.headers['Authorization']) or request.headers['Authorization'] != api.payload['token']:\n api.abort(400)\n return\n\n try:\n model = {\n 'token': api.payload['token'],\n 'title': api.payload['title'],\n 'created_at': api.payload['created_at'],\n }\n\n document = db.collection(u'workspaces').document()\n document.set(model)\n model = {'id': document.id, **model}\n return model\n except Exception as e:\n print(str(e))\n api.abort(400)\n","sub_path":"app/workspace.py","file_name":"workspace.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"15689995","text":"# coding: utf-8\n\nimport json\nimport subprocess\nimport sys\nfrom urllib import request\n\n\ndef api_json(url):\n return json.loads(request.urlopen(url).read().decode('utf-8'))\n\n\ndef read_repositories(owner):\n base_url = 'https://bitbucket.org/api/2.0/repositories/{}'\n url = base_url.format(owner)\n\n i = 1\n\n print('Loading repository list… API page {}'.format(i))\n\n values = []\n resp = api_json(url)\n\n [values.append(v) for v in resp['values']]\n\n while 'next' in resp:\n i += 1\n print('Loading repository list… API page {}'.format(i))\n url = resp['next']\n resp = api_json(url)\n [values.append(v) for v in resp['values']]\n\n print('Successfully read repositoy list ({} repos).'.format(len(values)))\n\n return values\n\n\ndef clone_repository(url):\n print('Cloning {}…'.format(url))\n subprocess.check_call(['git', 'clone', url, '--bare'])\n\n\ndef usage():\n print('usage: bb_reaper ')\n\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) != 2:\n usage()\n sys.exit(1)\n\n owner = sys.argv[1]\n repos = read_repositories(owner)\n\n for r in repos:\n clones = r['links']['clone']\n for clone in clones:\n if clone['name'] == 'https':\n clone_repository(clone['href'])\n","sub_path":"bb_reaper.py","file_name":"bb_reaper.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"595665058","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 1 17:22:28 2019\n\n@author: navas\n\"\"\"\n\nimport numpy as np\n\nentradas = np.array([1, 7, 5])\npesos = np.array([0.8, 0.1, 0])\n\n\ndef soma(e, p):\n # dot product / produto escalar soma(ei*pi)\n\n return e.dot(p)\n\n\ns = soma(entradas, pesos)\n\n\ndef stepFunction(soma):\n if soma >= 1:\n return 1\n return 0\n\n\nr = stepFunction(s)\n\nprint(r)","sub_path":"redes_neurais/perceptron_uma_camada/Uma_camada_with_numpy.py","file_name":"Uma_camada_with_numpy.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"68879114","text":"#!/usr/bin/env\n# coding:utf-8\nimport logging\nimport logging.handlers\nimport time\nimport os\n\nclass Logger(logging.Logger):\n\n def __init__(self, filename=None):\n super(Logger, self).__init__(self)\n # 日志文件名\n if filename is None:\n filename = 'my.log'\n if not os.path.exists(filename):\n os.makedirs(filename)\n self.filename = filename+'/'+str(int(time.time()))\n\n # 创建一个handler,用于写入日志文件 (每天生成1个,保留7天的日志)\n fh = logging.handlers.TimedRotatingFileHandler(self.filename, 'midnight', 1, 7)\n fh.suffix = \"%Y%m%d.log\"\n fh.setLevel(logging.DEBUG)\n\n # 再创建一个handler,用于输出到控制台\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n\n # 定义handler的输出格式\n formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s[line:%(lineno)d] - %(message)s')\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n\n # 给logger添加handler\n self.addHandler(fh)\n self.addHandler(ch)\n\nif __name__ == '__main__':\n logger_data = Logger('client_logs')\n for i in range(0, 10):\n logger_data.info('Test')\n sleep(1)","sub_path":"ycfspider/ycfspider-manager/ycfspider_monitor_manager/utils/model_logger.py","file_name":"model_logger.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"521830584","text":"from components.decorators import check_screen_permission, collect_menu_data\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom appSchool.models.modelExamMarkSheet import mdlClsExamMarkSheetDML, mdlClsExamMarkSheetGetData\nfrom appSchool.forms import frmClsExamMarkSheet\nfrom django.http import JsonResponse\nfrom django.http import HttpResponseRedirect\nfrom django.http import HttpResponse\n\n@login_required(login_url='/login')\n@check_screen_permission(screen_name='mark-sheet')\n@collect_menu_data\ndef vwfnExamMarkSheetIndex(request):\n errors = []\n\n dictExamMarkSheetGridData = dict()\n\n dictExamMarkSheetGridData['exams'] = mdlClsExamMarkSheetGetData.objIstMainExam.mdlFnLkpSprocSchMainExam()\n\n try:\n eid = int(request.GET.get('eid', 0))\n except:\n eid = 0\n dictExamMarkSheetGridData['eid'] = eid\n\n\n if(eid):\n dictExamMarkSheetGridData['marksheet'] = mdlClsExamMarkSheetDML.objIstExamMarkSheetGridData.mdlFnLkpSprocSchExamMarkSheetGrid(request, eid)\n return render(request, 'apps/school/MarkSheet/list.html', dictExamMarkSheetGridData)\n\n@login_required(login_url='/login')\n@check_screen_permission(screen_name='mark-sheet')\n@collect_menu_data\ndef vwfnExamMarkSheetEdit(request):\n errors = []\n\n dictExamMarkSheetGridData = dict()\n\n\n try:\n eid = int(request.GET.get('eid', 0))\n except:\n eid = 0\n dictExamMarkSheetGridData['eid'] = eid\n\n try:\n cid = int(request.GET.get('cid', 0))\n except:\n cid = 0\n dictExamMarkSheetGridData['cid'] = cid\n\n try:\n sid = int(request.GET.get('sid', 0))\n except:\n sid = 0\n dictExamMarkSheetGridData['sid'] = sid\n\n if(eid):\n dictExamMarkSheetGridData['marksheet'] = mdlClsExamMarkSheetDML.objIstExamMarkSheetGridData.mdlFnLkpSprocSchExamMarkSheetGrid1(request, eid, cid, sid)\n\n return render(request, 'apps/school/MarkSheet/form.html', dictExamMarkSheetGridData)\n\n@login_required(login_url='/login')\n@check_screen_permission(screen_name='mark-sheet')\n@collect_menu_data\ndef vwfnExamMarkSheetUnlock(request):\n\n dictExamMarkSheetUnlockData = request.POST.dict()\n dictExamMarkSheetUnlockData['exam_entity_id'] = request.GET.get('eid', None)\n dictExamMarkSheetUnlockData['class_entity_id'] = request.GET.get('cid', None)\n dictExamMarkSheetUnlockData['subject_entity_id'] = request.GET.get('sid', None)\n\n objFrmExamMarkSheetUnlock = frmClsExamMarkSheet(dictExamMarkSheetUnlockData)\n\n if (not objFrmExamMarkSheetUnlock.is_valid()):\n return JsonResponse({'error': objFrmExamMarkSheetUnlock.first_error()})\n\n objExamMarkSheetUnlock = mdlClsExamMarkSheetDML(**objFrmExamMarkSheetUnlock.cleaned_data)\n\n try:\n objExamMarkSheetUnlock.mdlFnSprocExamMarkSheetUnlock(request)\n messages.success(request, 'MarkSheet Unlocked')\n return HttpResponseRedirect(request.META.get('HTTP_REFERER'))\n except Exception as e:\n return JsonResponse({'error': str(e)})\n","sub_path":"appSchool/views/viewExamMarkSheet.py","file_name":"viewExamMarkSheet.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"639211456","text":"import numpy as np\nimport math\nimport scipy.linalg\nimport matplotlib.pyplot as plt\n\n\nmie_omegas = np.loadtxt('../mie_omegas_eV.txt')\n''' So all the units are cgs, but the hamiltonian gets loaded up with energies in eVs, so the first constant below is the charge of an electron in coulombs and the rest of the units are cgs. Every constant should be labeled.'''\ndipole = [] # doubly degenerate\nno_dipole = [] # doubly degenerate\nall_N = [] #all north\nout_N_in_S = [] # that weird \"excited state\"\nalt_NS = [] # maximally out of phase magnets\ncenter = np.zeros(7,dtype=object)\nfor r in range(1,2):\n\telec = 1.60217662e-19 # regular coulombs\n\tnumPart = 24; #number of particles\n\ta0 = r*10**-7; #sphere radius in cm\n\tindex = (r - 1) * 10\n\t''' now determine geometry.'''\n\n\t# make unit vectors in centimeters.\n\te1 = float(1)/float(2) * (3*a0) ; #short side of 30-60-90 triangle\n\te2 = float(math.sqrt(3))/float(2) * (3*a0); #long side of 30-60-90 triangle\n\tLoc = [np.array([0,2*e1]),np.array([-e2,e1]),np.array([-e2,-e1]),np.array([0,-2*e1]),\n\t\t np.array([e2,-e1]),np.array([e2,e1]),np.array([2*e2,2*e1]),np.array([3*e2,e1]),\n\t\t np.array([3*e2,-e1]),np.array([2*e2,-2*e1]),np.array([2*e2,-4*e1]),np.array([e2,-5*e1]),\n\t\t np.array([0,-4*e1]),np.array([-e2,-5*e1]),np.array([-2*e2,-4*e1]),np.array([-2*e2,-2*e1]),\n\t\t np.array([-3*e2,-e1]),np.array([-3*e2,e1]),np.array([-2*e2,2*e1]),np.array([-2*e2,4*e1]),\n\t\t np.array([-e2,5*e1]),np.array([0, 4*e1]),np.array([e2,5*e1]),np.array([2*e2,4*e1])] #location vectors for center of each sphere - they go counterclockwise, with one being the top center particle and six being the bottom center particle.\n\tcenter[0] = (Loc[0]+Loc[3])*0.5\n\tcenter[1] = (Loc[6]+Loc[9])*0.5\n\tcenter[2] = (Loc[9]+Loc[12])*0.5\n\tcenter[3] = (Loc[12]+Loc[15])*0.5\n\tcenter[4] = (Loc[15]+Loc[18])*0.5\n\tcenter[5] = (Loc[18]+Loc[21])*0.5\n\tcenter[6] = (Loc[21]+Loc[6])*0.5\n\tQ = [np.array([1,0]),np.array([0,1])] #dipole moments: 1st in x-direction, 2nd in y-direction\n\n\t'''This part builds the Hamiltonian. We start by initializing and choosing an initial omega value.'''\n\tH = np.zeros((2*numPart,2*numPart)) #initialize Hammy with zeros, twenty by twenty in this case.\n\n\t'''More constants'''\n\n\tme = 9.10938291e-28; # electron mass in g\n\tch = 4.80326e-10; # electron charge in g^1/2 cm^3/2 s^-1\n\thbar = 1.054571726e-34; # modified Planck in J*s\n\tc = 2.99e10; # speed of light in cm/s\n\teps0 = 8.85418782e-12; # permittivity of free space\n\tepsb = 1; # background dielectric - right now we're in vacuum\n\tepsinf = 3.77; # does this have units?\n\t'''Properties for silver.'''\n\tEplasma = 1.46599161e-18; # J\n\tgamma = 0.05*elec/(hbar*16)\n\twplasma = Eplasma/hbar; # plasma frequency (rad/s)\n\t#wsp_0 = math.sqrt((wplasma/math.sqrt(epsinf+2*epsb))**2 - (gamma/2)**2);\n\twsp_0 = mie_omegas[index]*elec/hbar\n\t'''initialize w_0 and eigen'''\n\tw_0 = 3*elec/hbar\n\teigen = np.ones(2*numPart)\n\tcount = 1\n\tfor mode in range(0,7):\n\t\twhile np.sqrt(np.square(w_0*hbar/elec - eigen[2*numPart-(mode+1)])) > 0.00000001:\n\t\t\tif count == 1:\n\t\t\t\tw_0 = 0\n\t\t\t\twsp = wsp_0\n\t\t\t\tcount = count + 1\n\t\t\telse:\n\t\t\t\tw_0 = eigen[2*numPart-(mode+1)]*elec/hbar\n\t\t\t\tcount = count + 1\n\t\t\t#print count\n\t\t\t#print eigen[2*numPart-(mode+1)]\n\t\t\talphasp = (a0**3)*(3/(epsinf+2)); # polarizability (cm^3)\n\t\t\twavenumber = (w_0)/(c*math.sqrt(epsb))\n\t\t\talpha = alphasp/(1 - 1j*(2./3.)*(wavenumber**3)*alphasp)\n\t\t\tmsp = (ch**2)/(alphasp*((wsp)**2)); # sp mass (grams)\n\t\t\ttau = (2*ch**2)/(3*msp*c**3) # radiation damping time\n\t\t\tgamma_ret = gamma+tau*(wsp**2) # I pulled this from the beats paper\n\t\t\tgamma_eV = gamma_ret*hbar/elec\n\t\t\twsp = wsp_0#math.sqrt((wsp_0)**2 - (gamma_ret/2)**2); # sp frequency (rad/s) corrected for radiation damping\n\t\t\tfor n in range (0,2*numPart):\n\t\t\t\tfor m in range (0,2*numPart):\n\t\t\t\t\tif m == n: #if m and n are the same, the hammy gets the plasmon energy\n\t\t\t\t\t\tH[n,m] = 1#(hbar*wsp/elec)\n\t\t\t\t\telif m == n+1 and n%2 == 0: #if m and n are on the same particle, they don't couple\n\t\t\t\t\t\tH[n,m] = 0\n\t\t\t\t\telif n == m+1 and m%2 == 0: #if m and n are on the same particle, they don't couple\n\t\t\t\t\t\tH[n,m] = 0\n\t\t\t\t\telse: # all other dipoles are fair game\n\t\t\t\t\t\tR = Loc[(n/2)]-Loc[(m/2)] #pick out the location of each dipole, comute the distance between them\n\t\t\t\t\t\tRmag = math.sqrt(R[0]**2+R[1]**2) #compute magnitude of distance\n\t\t\t\t\t\tnhat = (Loc[(n/2)]-Loc[(m/2)])/float(Rmag) #compute unit vector between dipoles\n\t\t\t\t\t\tp_dot_p = np.dot(Q[n%2],Q[m%2]) # this is one dipole dotted into the other\n\t\t\t\t\t\tp_nn_p = np.dot(Q[n%2],nhat)*np.dot(nhat,Q[m%2]) # this is one dipole dotted into the unit vector, times the other dipole dotted into the unit vector\n\t\t\t\t\t\tr_cubed = alpha/Rmag**3 #this is the 1/r^3 term (static)\n\t\t\t\t\t\tr_squared = (alpha*w_0)/(c*(Rmag**2)) #this is the 1/r^2 term (imaginary part)\n\t\t\t\t\t\tr_unit = (alpha*w_0**2)/(Rmag*(c**2)) #this is the 1/r term (goes with the cross products)\n\t\t\t\t\t\t#space_exp = np.exp(1j*w_0*Rmag/c)\n\t\t\t\t\t\tspace_cos = np.cos(w_0*Rmag/c) #this is the real part of the e^ikr\n\t\t\t\t\t\tspace_sin = np.sin(w_0*Rmag/c) #this is the imaginary part of the e^ikr\n\t\t\t\t\t\tge = (r_unit *space_cos* (p_dot_p - p_nn_p) + (r_cubed*space_cos + r_squared*space_sin) * (3*p_nn_p - p_dot_p)) #this is p dot E\n\t\t\t\t\t\tgm = 0 #set magnetic coupling to zero. we can include this later if necessary.\n\t\t\t\t\t\tH[n,m] = -np.real(ge) #this has the minus sign we need.\n\t\t\t#diag = np.diag(np.diag(H)) # this produces a matrix of only the diagonal terms of H\n\t\t\t#Ht = np.matrix.transpose(H) # this is the transpose of H\n\t\t\t#Hedit = diag - Ht # this produces a matrix with zeros on the diagonal and the upper triangle, and the lower triangle has all the leftover values of H with the opposite sign\n\t\t\t#Hfull = H - Hedit # this combines H with the lower triangle (all negative) to produce a symmetric, full matrix\n\t\t\tw,v = scipy.linalg.eigh(H) #this solves the eigenvalue problem, producing eigenvalues w and eigenvectors v.\n\t\t\tidx = w.argsort()[::-1] # this is the idx that sorts the eigenvalues from largest to smallest\n\t\t\teigenValues = w[idx] # sorting\n\t\t\teigenVectors = v[:,idx] # sorting\n\t\t\teigen=np.sqrt(eigenValues)*wsp*hbar/elec # the eigenvalues have units of energy^2, so we take the square root\n\t\t\t#print eigen\n\t\tvec = np.reshape(eigenVectors[:,2*numPart-(mode+1)],(numPart,2))\n\t\tx,y = zip(*Loc)\n\t\tu,v = zip(*vec)\n\t\tplt.title(''.join(['mode = ',str(mode+1)]))\n\t\tplt.quiver(x,y,u,v)\n\t\tplt.show()\n\t\t#np.savetxt('coro_' + str(mode) + '_vec',vec)\n\t\t'''mag_dipole = []\n\t\tfor cent in range(0,7):\n\t\t\tcr_pr = []\n\t\t\tfor num in range(0,numPart):\n\t\t\t\tif num == numPart-1:\n\t\t\t\t\tidx = num - 1\n\t\t\t\telse:\n\t\t\t\t\tidx = num + 1\n\t\t\t\tif abs(np.linalg.norm(center[cent]-Loc[num]) - np.linalg.norm(Loc[num]-Loc[idx])) < 10**-10:\n\t\t\t\t\tcr_pr.append(np.cross(Loc[num]-center[cent],vec[num]))\n\t\t\t\telse:\n\t\t\t\t\tcontinue\n\t\t\tmag_dipole.append(np.sum(cr_pr))\n\t\tif abs(np.sum(vec)) < 10**-10:\n\t\t\tif abs(np.sum(mag_dipole)) < 10**-12:\n\t\t\t\tif abs(mag_dipole[0]) < 10**-12:\n\t\t\t\t\tif np.dot(vec[12],vec[21]) > 0: \n\t\t\t\t\t\talt_NS.append(np.real(eigen[2*numPart-(mode+1)]))\n\t\t\t\t\telse:\n\t\t\t\t\t\tno_dipole.append(np.real(eigen[2*numPart-(mode+1)]))\n\t\t\t\telse:\n\t\t\t\t\talt_NS.append\n\t\t\telse:\n\t\t\t\tif np.dot(vec[0],vec[21]) * np.dot(vec[0],vec[3]) < 0 :\n\t\t\t\t\tall_N.append(np.real(eigen[2*numPart-(mode+1)]))\n\t\t\t\telif abs(np.sum(vec[21])) < 10**-5:\n\t\t\t\t\tall_N.append(np.real(eigen[2*numPart-(mode+1)]))\n\t\t\t\telif np.dot(vec[0],vec[21]) > 0:\n\t\t\t\t\tall_N.append(np.real(eigen[2*numPart-(mode+1)]))\n\t\t\t\telif mag_dipole[0] * mag_dipole[1] > 0:\n\t\t\t\t\tall_N.append(np.real(eigen[2*numPart-(mode+1)]))\n\t\t\t\telse:\n\t\t\t\t\tout_N_in_S.append(np.real(eigen[2*numPart-(mode+1)]))\n\t\telse:\n\t\t\tdipole.append(np.real(eigen[2*numPart-(mode+1)]))\n\tif len(out_N_in_S) > len(all_N):\n\t\tall_N.append(out_N_in_S[index])\n\t\tdel out_N_in_S[index]\n\tif len(alt_NS) > len(all_N):\n\t\tall_N.append(alt_NS[index])\n\t\tdel alt_NS[index]\n\tif len(all_N) > len(out_N_in_S):\n\t\tout_N_in_S.append(all_N[index])\n\t\tdel all_N[index]\n\tif len(out_N_in_S) > alt_NS:\n\t\talt_NS.append(out_N_in_S[index])\n\t\tdel out_N_in_S[index]\n\tif len(out_N_in_S) > index + 1:\n\t\tif len(out_N_in_S) > len(no_dipole)*0.5:\n\t\t\tprint len(out_N_in_S)\n\t\t\tprint len(no_dipole)\n\t\t\tprint index\n\t\t\tdel out_N_in_S[index]\n\tif len(dipole)*.5 > len(alt_NS):\n\t\talt_NS.append(dipole[index*2])\n\t\tdel dipole[index*2]\n\tif out_N_in_S[index-1] - out_N_in_S[index] > 0.01:\n\t\tall_N.append(out_N_in_S[index])\n\t\tout_N_in_S.append(all_N[index])\n\t\tdel all_N[index]\n\t\tdel out_N_in_S[index]'''\n\t'''if index == 290:\n\t\tall_N.append(out_N_in_S[index])\n\t\talt_NS.append(all_N[index])\n\t\tout_N_in_S.append(alt_NS[index])\n\t\tdel all_N[index]\n\t\tdel alt_NS[index]\n\t\tdel out_N_in_S[index]'''\n\t'''if out_N_in_S[index-1] < all_N[index-1]:\n\t\tprint index\n\t\tprint len(out_N_in_S)\n\t\tprint len(all_N)\n\t\tif out_N_in_S[index] > all_N[index]:\n\t\t\tcrossing = ((index+index-1)*0.5*0.1)+1\n\tif len(out_N_in_S) > index+1:\n\t\tdel out_N_in_S[index]\n\tprint len(dipole)\n\tprint len(no_dipole)\n\tprint len(alt_NS)\n\tprint len(out_N_in_S)\n\tprint len(all_N)'''\n\t#raw_input(\"press enter\")\n\n\n'''print crossing\nprint len(dipole)\nprint len(no_dipole)\nprint len(alt_NS)\nprint len(out_N_in_S)\nprint len(all_N)\ndipole = np.reshape(dipole,[291,2])\nno_dipole = np.reshape(no_dipole,[291,2])\nr = np.linspace(1,30,291)\nplt.plot(r,alt_NS,r,out_N_in_S,r,all_N,r,dipole[:,0],r,no_dipole[:,0],linewidth=3)\nplt.ylabel('Energy (eV)')\nplt.xlabel('Particle Radius (nm) / Scale Factor')\nplt.legend(['Alternating North-South','South-Inside-North-Outside','All-North','Net Electric Dipole','No Net Dipoles'],loc=3)\nplt.show()\n\nnp.savetxt('dipole_eigen',dipole)\nnp.savetxt('nodipole_eigen',no_dipole)\nnp.savetxt('alt_NS_eigen',alt_NS)\nnp.savetxt('altl_N_eigen',all_N)\nnp.savetxt('out_N_in_S_eigen',out_N_in_S)\n#np.savetxt('crossing',crossing)'''","sub_path":"coronine_ret/6mer.py","file_name":"6mer.py","file_ext":"py","file_size_in_byte":9707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"313826205","text":"from typing import List\r\n\r\n# Rotate n x n matrix\r\n# O(n^2), O(1)\r\ndef rotate(matrix: List[List[int]]) -> None:\r\n n = len(matrix[0])\r\n\r\n for row in range(n // 2 + n % 2):\r\n for col in range(n // 2):\r\n tmp = matrix[n - 1 - col][row]\r\n matrix[n - 1 - col][row] = matrix[n - 1 - row][n - 1 - col]\r\n matrix[n - 1 - row][n - 1 - col] = matrix[col][n - 1 - row]\r\n matrix[col][n - 1 - row] = matrix[row][col]\r\n matrix[row][col] = tmp\r\n\r\nmatrix = [[1,2,3],[4,5,6],[7,8,9]]\r\nrotate(matrix)\r\nprint(matrix)","sub_path":"python/matrix/rotate.py","file_name":"rotate.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"312490972","text":"f = open(\"biterm_degrees_bydoc.csv\")\nOUTDIR = \"./biterm-nets\"\nfout = -1\nfor l in f:\n if l[0] == '>':\n if fout != -1 and not fout.closed:\n fout.close()\n fout = open(OUTDIR+\"/\"+l[1:].strip(),\"w\")\n else:\n fout.write(l)\nfout.close()\nf.close()\n","sub_path":"separate_biterm_docs.py","file_name":"separate_biterm_docs.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"522436139","text":"from pathlib import Path\n\nimport miniflask # noqa: E402\n\nmf = miniflask.init(\n module_dirs=str(Path(__file__).parent / \"modules\"),\n debug=True\n)\n\n\ndef test_mf_python():\n\n mf.load(\"module1\")\n from modules.module1 import func as func2 # noqa: F401,E402\n\n def func(x):\n return x\n\n a = 0\n for i in range(10000000):\n a += func(42)\n","sub_path":"util/miniflask/tests/speedtest/test_mf_python.py","file_name":"test_mf_python.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"78316002","text":"from brian import *\r\nfrom scipy import signal, weave, random\r\nfrom filterbank import Filterbank, RestructureFilterbank\r\nfrom ..bufferable import Bufferable\r\ntry:\r\n import numexpr\r\nexcept ImportError:\r\n numexpr = None\r\n\r\n# TODO: test all the buffered version of apply_linear_filterbank here\r\n# So far, they seem to more or less work, but probably need more thorough\r\n# testing.\r\n\r\n__all__ = ['LinearFilterbank','apply_linear_filterbank']\r\n\r\ndef apply_linear_filterbank(b, a, x, zi):\r\n '''\r\n Parallel version of scipy lfilter command for a bank of n sequences of length 1\r\n \r\n In scipy.lfilter, you can apply a filter to multiple sounds at the same time,\r\n but you can't apply a bank of filters at the same time. This command does\r\n that. The coeffs b, a must be of shape (n,m,p), x must be of shape (s, n),\r\n and zi must be of shape (n,m-1,p). Here n is the number of channels in the\r\n filterbank, m is the order of the filter, p is the number of filters in\r\n a chain (cascade) to apply (you do first with (:,:,0) then (:,:,1), etc.),\r\n and s is the size of the buffer segment.\r\n '''\r\n X = x\r\n output = empty_like(X)\r\n for sample in xrange(X.shape[0]):\r\n x = X[sample]\r\n for curf in xrange(zi.shape[2]):\r\n y = b[:, 0, curf]*x+zi[:, 0, curf]\r\n for i in xrange(b.shape[1]-2):\r\n zi[:, i, curf] = b[:, i+1, curf]*x+zi[:, i+1, curf]-a[:, i+1, curf]*y\r\n i = b.shape[1]-2\r\n zi[:, i, curf] = b[:, i+1, curf]*x-a[:, i+1, curf]*y\r\n x = y\r\n output[sample] = y\r\n return output\r\n\r\nif True:\r\n from itertools import izip\r\n alf_cache = {}\r\n def apply_linear_filterbank(b, a, x, zi):\r\n '''\r\n Parallel version of scipy lfilter command for a bank of n sequences of length 1\r\n \r\n In scipy.lfilter, you can apply a filter to multiple sounds at the same time,\r\n but you can't apply a bank of filters at the same time. This command does\r\n that. The coeffs b, a must be of shape (n,m,p), x must be of shape (s, n),\r\n and zi must be of shape (n,m-1,p). Here n is the number of channels in the\r\n filterbank, m is the order of the filter, p is the number of filters in\r\n a chain (cascade) to apply (you do first with (:,:,0) then (:,:,1), etc.),\r\n and s is the size of the buffer segment.\r\n '''\r\n if id(zi) in alf_cache:\r\n alf_cache_a, alf_cache_b, alf_cache_zi = alf_cache[id(zi)]\r\n else:\r\n alf_cache_b = [[0]*zi.shape[2] for _ in xrange(b.shape[1])]\r\n alf_cache_a = [[0]*zi.shape[2] for _ in xrange(b.shape[1])]\r\n alf_cache_zi = [[0]*zi.shape[2] for _ in xrange(b.shape[1])]\r\n for curf in xrange(zi.shape[2]):\r\n alf_cache_b[0][curf] = b[:, 0, curf]\r\n alf_cache_zi[0][curf] = zi[:, 0, curf]\r\n for i in xrange(b.shape[1]-2):\r\n alf_cache_b[i+1][curf] = b[:, i+1, curf]\r\n alf_cache_zi[i+1][curf] = zi[:, i+1, curf]\r\n alf_cache_a[i+1][curf] = a[:, i+1, curf]\r\n i = b.shape[1]-2\r\n alf_cache_b[i+1][curf] = b[:, i+1, curf]\r\n alf_cache_a[i+1][curf] = a[:, i+1, curf]\r\n X = x\r\n output = empty_like(X)\r\n num_cascade = zi.shape[2]\r\n b_loop_size = b.shape[1]-2\r\n for sample, (x, o) in enumerate(izip(X, output)):\r\n for curf in xrange(num_cascade):\r\n #y = b[:, 0, curf]*x+zi[:, 0, curf]\r\n y = alf_cache_b[0][curf]*x\r\n add(y, alf_cache_zi[0][curf], y)\r\n for i in xrange(b_loop_size):\r\n #zi[:, i, curf] = b[:, i+1, curf]*x+zi[:, i+1, curf]-a[:, i+1, curf]*y\r\n t = alf_cache_b[i+1][curf]*x\r\n add(t, alf_cache_zi[i+1][curf], t)\r\n subtract(t, alf_cache_a[i+1][curf]*y, t)\r\n alf_cache_zi[i][curf][:] = t\r\n i = b.shape[1]-2\r\n #zi[:, i, curf] = b[:, i+1, curf]*x-a[:, i+1, curf]*y\r\n t = alf_cache_b[i+1][curf]*x\r\n subtract(t, alf_cache_a[i+1][curf]*y, t)\r\n alf_cache_zi[i][curf][:] = t\r\n x = y\r\n #output[sample] = y\r\n o[:] = y\r\n return output\r\n\r\nif numexpr is not None and False:\r\n def apply_linear_filterbank(b, a, x, zi):\r\n X = x\r\n output = empty_like(X)\r\n for sample in xrange(X.shape[0]):\r\n x = X[sample]\r\n for curf in xrange(zi.shape[2]):\r\n #y = b[:, 0, curf]*x+zi[:, 0, curf]\r\n y = numexpr.evaluate('b*x+zi', local_dict={\r\n 'b':b[:, 0, curf],\r\n 'x':x,\r\n 'zi':zi[:, 0, curf]})\r\n for i in xrange(b.shape[1]-2):\r\n #zi[:, i, curf] = b[:, i+1, curf]*x+zi[:, i+1, curf]-a[:, i+1, curf]*y\r\n zi[:, i, curf] = numexpr.evaluate('b*x+zi-a*y', local_dict={\r\n 'b':b[:, i+1, curf],\r\n 'x':x,\r\n 'zi':zi[:, i+1, curf],\r\n 'a':a[:, i+1, curf],\r\n 'y':y})\r\n i = b.shape[1]-2\r\n #zi[:, i, curf] = b[:, i+1, curf]*x-a[:, i+1, curf]*y\r\n zi[:, i, curf] = numexpr.evaluate('b*x-a*y', local_dict={\r\n 'b':b[:, i+1, curf],\r\n 'x':x,\r\n 'a':a[:, i+1, curf],\r\n 'y':y})\r\n x = y\r\n output[sample] = y\r\n return output\r\n \r\n\r\n# TODO: accelerate this even more using SWIG instead of weave?\r\nif get_global_preference('useweave'):\r\n _cpp_compiler = get_global_preference('weavecompiler')\r\n _extra_compile_args = ['-O3']\r\n if _cpp_compiler=='gcc':\r\n _extra_compile_args += get_global_preference('gcc_options')\r\n _old_apply_linear_filterbank = apply_linear_filterbank\r\n \r\n def apply_linear_filterbank(b, a, x, zi):\r\n if zi.shape[2]>1:\r\n # we need to do this so as not to alter the values in x in the C code below\r\n # but if zi.shape[2] is 1 there is only one filter in the chain and the\r\n # copy operation at the end of the C code will never happen.\r\n x = array(x, copy=True)\r\n y = empty_like(x)\r\n n, m, p = b.shape\r\n n1, m1, p1 = a.shape\r\n numsamples = x.shape[0]\r\n if n1!=n or m1!=m or p1!=p or x.shape!=(numsamples, n) or zi.shape!=(n, m-1, p):\r\n raise ValueError('Data has wrong shape.')\r\n if numsamples>1 and not x.flags['C_CONTIGUOUS']:\r\n raise ValueError('Input data must be C_CONTIGUOUS')\r\n if not b.flags['F_CONTIGUOUS'] or not a.flags['F_CONTIGUOUS'] or not zi.flags['F_CONTIGUOUS']:\r\n raise ValueError('Filter parameters must be F_CONTIGUOUS')\r\n code = '''\r\n #define X(s,i) x[(s)*n+(i)]\r\n #define Y(s,i) y[(s)*n+(i)]\r\n #define A(i,j,k) a[(i)+(j)*n+(k)*n*m]\r\n #define B(i,j,k) b[(i)+(j)*n+(k)*n*m]\r\n #define Zi(i,j,k) zi[(i)+(j)*n+(k)*n*(m-1)]\r\n for(int s=0; s> median(abs(concat_wav)) = 0.0376\n\nn_data=data.shape[1];\n#input_dim =int(fs/25); # Frames size of speech signal\ninput_dim =100;\n\nn_data=n_data - n_data % input_dim; # make length divisible by input_dim\ndata=data[0,0:n_data]; # clipping teh rest\n# Reshaping data\ndata=data.reshape([int(n_data/input_dim), input_dim])\nn_data=data.shape[0];\n\n\ntraining_percentage=90;\nn_training= int(np.floor(training_percentage/100.*n_data));\ntraining_data=data[ 0:n_training , : ];\n\ntest_data=data[ n_training:n_data, : ];\nn_test=test_data.shape[0];\n\n\n\n\n#%% Global config variables\n\nlearning_rate = 0.1\n\nfull_width=512;\n\nhidden_width = 512\nnumber_of_layers=2\n\nn_hidden_binary=16;\n\nnum_steps = 2 # number of truncated backprop steps ('n' in the discussion above)\nbatch_size = 100\n\n\nn_batch = 2000; # int(n_training/batch_size)\n\n\ntraining_epochs = 1\ndisplay_step = 100\n\n#%% ##############################################################################\n# tf Graph input\n\nX = tf.placeholder(\"float\", [None, input_dim])\nprevious_state_enc=tf.placeholder(\"float\", [1, hidden_width])\nprevious_state_dec=tf.placeholder(\"float\", [1, hidden_width])\n\n\nstd_init_W=0.1;\nstd_init_bias=0.01;\n\nweights={};\nbiases={};\n\nweights['encoder_h'+str(1)]= tf.Variable(tf.random_normal([input_dim, full_width], mean=0.0, stddev=std_init_W)); \nbiases['encoder_b'+str(1)]= tf.Variable(tf.random_normal([full_width], mean=0.0, stddev=std_init_bias));\n\nweights['middle']=tf.Variable(tf.random_normal( [hidden_width, n_hidden_binary], mean=0.0, stddev=std_init_W));\nbiases['middle']= tf.Variable(tf.random_normal( [n_hidden_binary], mean=0.0, stddev=std_init_bias));\n\nweights['last']=tf.Variable(tf.random_normal( [hidden_width, full_width], mean=0.0, stddev=std_init_W));\nbiases['last']= tf.Variable(tf.random_normal( [full_width], mean=0.0, stddev=std_init_bias));\n\nweights['output']= tf.Variable(tf.random_normal([full_width, input_dim], mean=0.0, stddev=std_init_W));\nbiases['output']=tf.Variable(tf.random_normal([input_dim], mean=0.0, stddev=std_init_bias));\n\n\n#%%\n# Batch normalization\n\n\ndef BatchNormalization(x, W, num_neurons):\n epsilon=1e-3;\n z_BN = tf.matmul(x,W)\n batch_mean, batch_var = tf.nn.moments(z_BN,[0])\n scale = tf.Variable(tf.ones([num_neurons]))\n beta = tf.Variable(tf.zeros([num_neurons]))\n x_BN = tf.nn.batch_normalization(z_BN,batch_mean,batch_var,beta,scale,epsilon)\n\n return x_BN\n\n\n#%% RNN layer definition\n\n#def rnn_layer_gen(state_size):\n# layer= tf.contrib.rnn.BasicRNNCell (state_size,\\\n# input_size=input_dim,\\\n# activation=tf.tanh)\n# return layer\n\n\nwith tf.variable_scope('rnn_cell'):\n W = tf.get_variable('W', [num_classes + state_size, state_size])\n b = tf.get_variable('b', [state_size], initializer=tf.constant_initializer(0.0))\n\ndef rnn_cell(rnn_input, state):\n with tf.variable_scope('rnn_cell', reuse=True):\n W = tf.get_variable('W', [num_classes + state_size, state_size])\n b = tf.get_variable('b', [state_size], initializer=tf.constant_initializer(0.0))\n return tf.tanh(tf.matmul(tf.concat([rnn_input, state], 1), W) + b)\n#%%##############################################################################\n# Building the encoder\n\ndef encoder(x, previous_state):\n \n # layer[str(1)] = tf.nn.tanh(tf.add(tf.matmul(x, weights['encoder_h'+str(1)]), biases['encoder_b'+str(1)]))\n layer_1 = BatchNormalization(x, weights['encoder_h'+str(1)],hidden_width);\n layer_1 = tf.nn.tanh(layer_1);\n \n \n rnn_layer=rnn_layer_gen(hidden_width)\n rnn_net=tf.contrib.rnn.MultiRNNCell( [rnn_layer] * number_of_layers,\\\n state_is_tuple=True)\n# initial_state=state = tf.zeros([batch_size, rnn_net.state_size])\n \n # Critical part where we get the state of rnn\n output_rnn, state_rnn = rnn_net(layer_1, previous_state)\n\n \n #layer_middle=tf.nn.tanh(tf.add(tf.matmul(layer[str(n_hid)],weights['middle']), biases['middle']));\n layer_middle=BatchNormalization(output_rnn, weights['middle'], n_hidden_binary)\n layer_middle=tf.nn.tanh(layer_middle)\n\n \n return layer_middle, state_rnn\n\n#%% Building the decoder\ndef decoder(x, previous_state):\n \n \n rnn_layer=rnn_layer_gen(hidden_width)\n \n rnn_net=tf.contrib.rnn.MultiRNNCell( [rnn_layer] * number_of_layers,\\\n state_is_tuple=True)\n \n \n # Critical part where we get the state of rnn\n output_rnn, state_rnn = rnn_net(x, previous_state)\n\n\n layer_last=BatchNormalization(output_rnn, weights['last'], full_width)\n layer_last=tf.nn.tanh(layer_last) \n \n \n layer_output=BatchNormalization(layer_last, weights['output'], input_dim)\n layer_output=tf.nn.tanh(layer_output) \n \n return layer_last, state_rnn\n \n\n#%%#############################################################################\n# Construct teh residual model\n\nencoder_op={};\ndecoder_op={};\nresidue={};\n\n\n# fisrt step\n\n#previous_state_enc =tf.zeros([batch_size, hidden_width])\nencoder_op, state_enc = encoder(X, previous_state_enc)\ndecoder_op, state_dec = decoder(encoder_op,previous_state_dec) \n\ny_pred, _=decoder_op;\nresidue=tf.subtract(X, y_pred);\n\n# Ground truth\ny_true = X; # Targets (Labels) are the input data. Cause it's an Autoencoder!!\n\n# Define loss and optimizer, minimize the squared error\ncost = tf.reduce_mean( tf.pow(y_true - y_pred, 2))\n\n#optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n#optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost)\noptimizer = tf.train.AdamOptimizer(learning_rate, epsilon=1e-8).minimize(cost)\n\n\n#%%##############################################################################\n# Initializing the variables\ninit = tf.global_variables_initializer()\n\n# Launch the graph, mean=0.0, stddev=1))\n\n#with tf.Session() as sess:\n#sess=tf.Session();\nsess = tf.Session(config=tf.ConfigProto(log_device_placement=True))\n\n\nsess.run(init)\n\n\n# Training cycle\ncost_vector=[];\n\nfor epoch in range(training_epochs):\n \n \n for mini_batch in range(n_batch):\n \n start_ind=np.random.randint(0, n_training-batch_size*num_steps ,1) \n \n \n batch_xs= training_data[ start_ind : start_ind + batch_size*num_steps, :]; \n \n state_enc_tmp = state_dec_tmp = tf.zeros([batch_size, hidden_width])\n residue_tmp = tf.zeros([ batch_size, input_dim])\n \n for step in range(num_steps):\n \n net_input=batch_xs[ step * batch_size : (step+1) * batch_size, : ]\n net_input=net_input-residue_tmp;\n \n residue_tmp, state_enc_tmp, state_dec_tmp=sess.run([residue, state_enc, state_dec],\n feed_dict={X: net_input, \n previous_state_enc: state_enc_tmp,\n previous_state_dec: state_dec_tmp })\n \n \n c, _ = sess.run([cost, optimizer], feed_dict={X: batch_xs,\\\n previous_state_enc: state_enc_tmp,\\\n previous_state_dec: state_dec_tmp })\n \n # Display logs per epoch step\n if mini_batch % display_step == 0:\n print(\"Epoch:\", '%02d' % (epoch+1),\n \"i:\", '%04d' % (mini_batch+1),\n \"cost=\", \"{:.9f}\".format(c)) \n \n cost_vector+=[c]\n\nprint(\"Optimization Finished!\")\n\n#%%##########################################################################\n# Testing the network performance\n\ntraining_error=sess.run(cost, feed_dict={X: training_data})**0.5\n\ny_pred_test, y_true_test, test_error = sess.run([y_pred, y_true, cost], feed_dict={X: test_data})\n\ntest_error=test_error**0.5\n\n#_, test_error = sess.run([optimizer, cost], feed_dict={X: test_data})\nprint( 'training_error', \"{:.9f}\".format(training_error))\nprint( 'test_error', \"{:.9f}\".format(test_error))\n\n\nprint('architecture ', [[hidden_width]*number_of_layers, n_hidden_binary, [hidden_width]*number_of_layers ])\nprint('learning_rate= ', learning_rate)\nprint('n_hidden_binary= ', n_hidden_binary)\nprint('num_steps= ', num_steps)\n\n# Plotting results\n#plt.plot(cost_vector)\n\n#%%##########################################################################\n# Savings network\n#saver = tf.train.Saver()\n#save_path = saver.save(sess, \"/home/hsadeghi/Dropbox/research codes/\",\n# \"binary_full_2step_4bit_AE.ckpt\")\n\n# print(\"Model saved in file: %s\" % save_path)\nAE_output={};\nAE_output['y_pred_test']=y_pred_test;\nAE_output['y_true_test']=y_true_test;\n\nsi.savemat(\"/home/hsadeghi/Dropbox/research codes/AE_output.mat\",\n AE_output);\n\n\n#%% Building graph\n\n#writer = tf.summary.FileWriter('/Dropbox/research codes/log', sess.graph)\n","sub_path":"March/r2rt_lstm_with_bn.py","file_name":"r2rt_lstm_with_bn.py","file_ext":"py","file_size_in_byte":9993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"599976287","text":"import sys\ninput = sys.stdin.readline\n\ndef money():\n lst = sorted(list(map(int, input().split())))\n\n if len(set(lst)) == 1:\n return 50000 + lst[0] * 5000\n elif len(set(lst)) == 2:\n return 10000 + lst[1] * 1000 if lst[1] == lst[2] else 2000 + (lst[1] + lst[2]) * 500\n for i in range(3):\n if lst[i] == lst[i+1]: \n return 1000 + lst[i] * 100\n return lst[-1] * 100\n\nprint(max(money() for _ in range(int(input()))))\n\n# n = int(input())\n\n# dices = [list(map(int, input().split())) for _ in range(n)]\n\n# result = -sys.maxsize\n\n# def getMoney(dice):\n# _sum = 0\n# arr = [0] * 6\n# for num in dice:\n# arr[num - 1] += 1\n \n# for i in range(6):\n# if arr[i] == 4:\n# _sum += 50000 + (i + 1) * 5000\n# break\n# elif arr[i] == 1 or arr[i] == 3:\n# if 3 in arr:\n# target = arr.index(3)\n# _sum += 10000 + (target + 1) * 1000\n# break\n# elif arr.count(1) == 4:\n# for j in range(5, -1, -1):\n# if arr[j] == 1:\n# _sum += (j + 1) * 100\n# break\n# break\n# elif arr.count(1) == 2:\n# target = arr.index(2)\n# _sum += 1000 + (target + 1) * 100\n# break\n# elif arr[i] == 2:\n# if arr.count(2) == 2:\n# one, two = list(filter(lambda x: arr[x] == 2, range(6)))\n# _sum += 2000 + (one + 1) * 500 + (two + 1) * 500\n# break\n# else:\n# _sum += 1000 + (i + 1) * 100\n# break\n\n# return _sum\n\n# for dice in dices:\n# result = max(result, getMoney(dice))\n\n# print(result)","sub_path":"backjoon/2484.py","file_name":"2484.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"530165613","text":"import tkinter as tk\n\n#from functolls import partial\nfrom tkinter import *\nimport tkinter\n\nKeyboard_App = tkinter.Tk()\nKeyboard_App.title(\"Typing Challenge\")\nKeyboard_App ['bg'] = 'sky blue'\nKeyboard_App.resizable(0,0)\n\ndef key_pressed(event):\n print(event.char)\n\ndef select(value):\n if value == \" Space \":\n entry.insert(tkinter.END, ' ')\n elif value == \"Tab\":\n entry.insert(tkinter.END, ' ')\n else:\n entry.insert(tkinter.END, value)\n\nlabel1 = Label(Keyboard_App, text=\"Typing Challenge\", font=('arial', 30, 'bold'),bg='powder blue', fg=\"#000000\").grid(row=0, columnspan=40)\nentry = Text(Keyboard_App, width=138, font=('arial', 12, 'bold'))\nentry.grid(row=1, columnspan=40)\n\nbuttons = [\n '`','1','2','3','4','5','6','7','8','9','0','-','=',' <- ',\n 'Tab','q','w','e','r','t','y','u','i','o','p','[',']','\\\\',\n 'Caps','a','s','d','f','g','h','j','k','l',';','\\'','Enter',' ',\n ' ','Shift','z','x','c','v','b','n','m',',','.','/','Shift',' ',\n ' Space '\n]\nvarRow = 3\nvarColumn = 0\n\nfor button in buttons:\n command = lambda x=button: select(x)\n if button != \" Space \":\n tkinter.Button(Keyboard_App, text=button, \n width=5, padx=3, pady=3, bd=12, font=('arial', 12, 'bold'),\n activebackground=\"#000990\", relief = 'raised', \n command = command).grid(row=varRow, column=varColumn)\n if button == \"Tab\":\n tkinter.Button(Keyboard_App, text=button, \n width=8, padx=3, pady=3, bd=12, font=('arial', 12, 'bold'),\n activebackground=\"#000990\", relief = 'raised', \n command = command).grid(row=varRow, column=varColumn)\n if button == \" Space \":\n tkinter.Button(Keyboard_App, text=button, \n width=118, padx=3, pady=3, bd=12, font=('arial', 12, 'bold'),\n activebackground=\"#000990\", relief = 'raised', \n command = command).grid(row=6, columnspan=16)\n\n varColumn += 1\n if varColumn > 13 and varRow == 3:\n varColumn = 0\n varRow += 1\n if varColumn > 13 and varRow == 4:\n varColumn = 0\n varRow += 1\n\nKeyboard_App.bind(\"\", key_pressed)\n\nKeyboard_App.mainloop()","sub_path":"virtual-keyboard/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"211701627","text":"from datetime import date\nfrom datetime import datetime as dt\nimport time # performance test\nfrom tempfile import mkstemp\nfrom os import path\nimport subprocess\nfrom subprocess import CalledProcessError\n\nfrom flyingpigeon.datafetch import _PRESSUREDATA_\nfrom flyingpigeon.datafetch import reanalyses as rl\nfrom flyingpigeon.ocgis_module import call\nfrom flyingpigeon import analogs\nfrom flyingpigeon.utils import rename_complexinputs\n\nfrom pywps import Process\nfrom pywps import LiteralInput, LiteralOutput\nfrom pywps import ComplexInput, ComplexOutput\nfrom pywps import Format, FORMATS\nfrom pywps.app.Common import Metadata\nfrom flyingpigeon.log import init_process_logger\n\nimport logging\nLOGGER = logging.getLogger(\"PYWPS\")\n\n\nclass AnalogsreanalyseProcess(Process):\n def __init__(self):\n inputs = [\n\n LiteralInput(\"reanalyses\", \"Reanalyses Data\",\n abstract=\"Choose a reanalyses dataset for comparison\",\n default=\"NCEP_slp\",\n data_type='string',\n min_occurs=1,\n max_occurs=1,\n allowed_values=_PRESSUREDATA_\n ),\n\n # self.BBox = self.addBBoxInput(\n # identifier=\"BBox\",\n # title=\"Bounding Box\",\n # abstract=\"coordinates to define the region to be analysed\",\n # minOccurs=1,\n # maxOccurs=1,\n # crss=['EPSG:4326']\n # )\n\n LiteralInput('dateSt', 'Start date of analysis period',\n data_type='date',\n abstract='First day of the period to be analysed',\n default='2013-07-15',\n min_occurs=1,\n max_occurs=1,\n ),\n\n LiteralInput('dateEn', 'End date of analysis period',\n data_type='date',\n abstract='Last day of the period to be analysed',\n default='2013-12-31',\n min_occurs=1,\n max_occurs=1,\n ),\n\n LiteralInput('refSt', 'Start date of reference period',\n data_type='date',\n abstract='First day of the period where analogues being picked',\n default='2013-01-01',\n min_occurs=1,\n max_occurs=1,\n ),\n\n LiteralInput('refEn', 'End date of reference period',\n data_type='date',\n abstract='Last day of the period where analogues being picked',\n default='2014-12-31',\n min_occurs=1,\n max_occurs=1,\n ),\n\n LiteralInput(\"normalize\", \"normalization\",\n abstract=\"Normalize by subtraction of annual cycle\",\n default='base',\n data_type='string',\n min_occurs=1,\n max_occurs=1,\n allowed_values=['None', 'base', 'sim', 'own']\n ),\n\n LiteralInput(\"seasonwin\", \"Seasonal window\",\n abstract=\"Number of days befor and after the date to be analysed\",\n default='30',\n data_type='integer',\n min_occurs=0,\n max_occurs=1,\n ),\n\n LiteralInput(\"nanalog\", \"Nr of analogues\",\n abstract=\"Number of analogues to be detected\",\n default='20',\n data_type='integer',\n min_occurs=0,\n max_occurs=1,\n ),\n\n LiteralInput(\"dist\", \"Distance\",\n abstract=\"Distance function to define analogues\",\n default='euclidean',\n data_type='string',\n min_occurs=1,\n max_occurs=1,\n allowed_values=['euclidean', 'mahalanobis', 'cosine', 'of']\n ),\n\n LiteralInput(\"outformat\", \"output file format\",\n abstract=\"Choose the format for the analogue output file\",\n default=\"ascii\",\n data_type='string',\n min_occurs=1,\n max_occurs=1,\n allowed_values=['ascii', 'netCDF4']\n ),\n\n LiteralInput(\"timewin\", \"Time window\",\n abstract=\"Number of days following the analogue day the distance will be averaged\",\n default='1',\n data_type='integer',\n min_occurs=0,\n max_occurs=1,\n ),\n ]\n\n outputs = [\n ComplexOutput(\"config\", \"Config File\",\n abstract=\"Config file used for the Fortran process\",\n supported_formats=[Format(\"text/plain\")],\n as_reference=True,\n ),\n\n ComplexOutput(\"analogs\", \"Analogues File\",\n abstract=\"mulit-column text file\",\n supported_formats=[Format(\"text/plain\")],\n as_reference=True,\n ),\n\n ComplexOutput(\"formated_analogs\", \"Formated Analogues File\",\n abstract=\"Formated analogues file for viewer\",\n supported_formats=[Format(\"text/plain\")],\n as_reference=True,\n ),\n\n ComplexOutput('output_netcdf', 'Subsets for one dataset',\n abstract=\"Prepared netCDF file as input for weatherregime calculation\",\n as_reference=True,\n supported_formats=[Format('application/x-netcdf')]\n ),\n\n ComplexOutput(\"output_html\", \"Analogues Viewer html page\",\n abstract=\"Interactive visualization of calculated analogues\",\n supported_formats=[Format(\"text/html\")],\n as_reference=True,\n ),\n\n ComplexOutput('output_log', 'Logging information',\n abstract=\"Collected logs during process run.\",\n as_reference=True,\n supported_formats=[Format('text/plain')]\n ),\n ]\n\n super(AnalogsreanalyseProcess, self).__init__(\n self._handler,\n identifier=\"analogs_reanalyse\",\n title=\"Analogues of circulation (based on reanalyses data)\",\n abstract='Search for days with analogue pressure pattern for reanalyses data sets',\n version=\"0.10\",\n metadata=[\n Metadata('LSCE', 'http://www.lsce.ipsl.fr/en/index.php'),\n Metadata('Doc', 'http://flyingpigeon.readthedocs.io/en/latest/'),\n ],\n inputs=inputs,\n outputs=outputs,\n status_supported=True,\n store_supported=True,\n )\n\n def _handler(self, request, response):\n init_process_logger('log.txt')\n response.outputs['output_log'].file = 'log.txt'\n\n LOGGER.info('Start process')\n response.update_status('execution started at : {}'.format(dt.now()), 5)\n\n process_start_time = time.time() # measure process execution time ...\n start_time = time.time() # measure init ...\n\n ################################\n # reading in the input arguments\n ################################\n\n try:\n response.update_status('read input parameter : %s ' % dt.now(), 5)\n\n refSt = request.inputs['refSt'][0].data\n refEn = request.inputs['refEn'][0].data\n dateSt = request.inputs['dateSt'][0].data\n dateEn = request.inputs['dateEn'][0].data\n seasonwin = request.inputs['seasonwin'][0].data\n nanalog = request.inputs['nanalog'][0].data\n bbox = [-80, 20, 50, 70]\n # if bbox_obj is not None:\n # LOGGER.info(\"bbox_obj={0}\".format(bbox_obj.coords))\n # bbox = [bbox_obj.coords[0][0],\n # bbox_obj.coords[0][1],\n # bbox_obj.coords[1][0],\n # bbox_obj.coords[1][1]]\n # LOGGER.info(\"bbox={0}\".format(bbox))\n # else:\n # bbox = None\n # region = self.getInputValues(identifier='region')[0]\n # bbox = [float(b) for b in region.split(',')]\n # bbox_obj = self.BBox.getValue()\n\n normalize = request.inputs['normalize'][0].data\n distance = request.inputs['dist'][0].data\n outformat = request.inputs['outformat'][0].data\n timewin = request.inputs['timewin'][0].data\n\n model_var = request.inputs['reanalyses'][0].data\n model, var = model_var.split('_')\n\n # experiment = self.getInputValues(identifier='experiment')[0]\n # dataset, var = experiment.split('_')\n # LOGGER.info('environment set')\n LOGGER.info('input parameters set')\n response.update_status('Read in and convert the arguments', 5)\n except Exception as e:\n msg = 'failed to read input prameter %s ' % e\n LOGGER.error(msg)\n raise Exception(msg)\n\n ######################################\n # convert types and set environment\n ######################################\n try:\n response.update_status('Preparing enviroment converting arguments', 7)\n LOGGER.debug('date: %s %s %s %s ' % (type(refSt), refEn, dateSt, dateSt))\n\n start = min(refSt, dateSt)\n end = max(refEn, dateEn)\n\n #\n # refSt = dt.strftime(refSt, '%Y-%m-%d')\n # refEn = dt.strftime(refEn, '%Y-%m-%d')\n # dateSt = dt.strftime(dateSt, '%Y-%m-%d')\n # dateEn = dt.strftime(dateEn, '%Y-%m-%d')\n\n if normalize == 'None':\n seacyc = False\n else:\n seacyc = True\n\n if outformat == 'ascii':\n outformat = '.txt'\n elif outformat == 'netCDF':\n outformat = '.nc'\n else:\n LOGGER.error('output format not valid')\n\n except Exception as e:\n msg = 'failed to set environment %s ' % e\n LOGGER.error(msg)\n raise Exception(msg)\n\n ###########################\n # set the environment\n ###########################\n\n response.update_status('fetching data from archive', 10)\n\n try:\n if model == 'NCEP':\n if 'z' in var:\n level = var.strip('z')\n conform_units_to = None\n else:\n level = None\n conform_units_to = 'hPa'\n elif '20CRV2' in model:\n if 'z' in var:\n level = var.strip('z')\n conform_units_to = None\n else:\n level = None\n conform_units_to = 'hPa'\n else:\n LOGGER.error('Reanalyses dataset not known')\n LOGGER.info('environment set for model: %s' % model)\n except:\n msg = 'failed to set environment'\n LOGGER.exception(msg)\n raise Exception(msg)\n\n ##########################################\n # fetch Data from original data archive\n ##########################################\n\n try:\n model_nc = rl(start=start.year,\n end=end.year,\n dataset=model,\n variable=var)\n LOGGER.info('reanalyses data fetched')\n except:\n msg = 'failed to get reanalyses data'\n LOGGER.exception(msg)\n raise Exception(msg)\n\n response.update_status('subsetting region of interest', 17)\n # from flyingpigeon.weatherregimes import get_level\n LOGGER.debug(\"start and end time: %s - %s\" % (start, end))\n time_range = [start, end]\n\n model_subset = call(resource=model_nc, variable=var,\n geom=bbox, spatial_wrapping='wrap', time_range=time_range,\n # conform_units_to=conform_units_to\n )\n LOGGER.info('Dataset subset done: %s ', model_subset)\n\n response.update_status('dataset subsetted', 19)\n\n ############################################################\n # get the required bbox and time region from resource data\n ############################################################\n #\n #\n # try:\n # if dataset == 'NCEP':\n # if 'z' in var:\n # variable = 'hgt'\n # level = var.strip('z')\n # # conform_units_to=None\n # else:\n # variable = 'slp'\n # level = None\n # # conform_units_to='hPa'\n # elif '20CRV2' in var:\n # if 'z' in level:\n # variable = 'hgt'\n # level = var.strip('z')\n # # conform_units_to=None\n # else:\n # variable = 'prmsl'\n # level = None\n # # conform_units_to='hPa'\n # else:\n # LOGGER.error('Reanalyses dataset not known')\n # LOGGER.info('environment set')\n # except Exception as e:\n # msg = 'failed to set environment %s ' % e\n # LOGGER.error(msg)\n # raise Exception(msg)\n #\n # LOGGER.debug(\"init took %s seconds.\", time.time() - start_time)\n # response.update_status('Read in and convert the arguments done', 8)\n #\n # #################\n # # get input data\n # #################\n # start_time = time.time() # measure get_input_data ...\n # response.update_status('fetching input data', 7)\n # try:\n # input = reanalyses(start=start.year, end=end.year,\n # variable=var, dataset=dataset)\n # LOGGER.info('input files %s' % input)\n # nc_subset = call(resource=input, variable=var,\n # geom=bbox, spatial_wrapping='wrap')\n # except Exception as e:\n # msg = 'failed to fetch or subset input files %s' % e\n # LOGGER.error(msg)\n # raise Exception(msg)\n\n LOGGER.debug(\"get_input_subset_dataset took %s seconds.\",\n time.time() - start_time)\n response.update_status('**** Input data fetched', 10)\n\n ########################\n # input data preperation\n ########################\n response.update_status('Start preparing input data', 12)\n start_time = time.time() # measure data preperation ...\n\n try:\n # Construct descriptive filenames for the three files\n # listed in config file\n refDatesString = dt.strftime(refSt, '%Y-%m-%d') + \"_\" + dt.strftime(refEn, '%Y-%m-%d')\n simDatesString = dt.strftime(dateSt, '%Y-%m-%d') + \"_\" + dt.strftime(dateEn, '%Y-%m-%d')\n archiveNameString = \"base_\" + var + \"_\" + refDatesString + '_%.1f_%.1f_%.1f_%.1f' \\\n % (bbox[0], bbox[2], bbox[1], bbox[3])\n simNameString = \"sim_\" + var + \"_\" + simDatesString + '_%.1f_%.1f_%.1f_%.1f' \\\n % (bbox[0], bbox[2], bbox[1], bbox[3])\n archive = call(resource=model_subset,\n time_range=[refSt, refEn],\n prefix=archiveNameString)\n simulation = call(resource=model_subset, time_range=[dateSt, dateEn],\n prefix=simNameString)\n LOGGER.info('archive and simulation files generated: %s, %s'\n % (archive, simulation))\n except Exception as e:\n msg = 'failed to prepare archive and simulation files %s ' % e\n LOGGER.debug(msg)\n raise Exception(msg)\n\n try:\n if seacyc is True:\n LOGGER.info('normalization function with method: %s '\n % normalize)\n seasoncyc_base, seasoncyc_sim = analogs.seacyc(\n archive,\n simulation,\n method=normalize)\n else:\n seasoncyc_base = seasoncyc_sim = None\n except Exception as e:\n msg = 'failed to generate normalization files %s ' % e\n LOGGER.debug(msg)\n raise Exception(msg)\n\n ip, output_file = mkstemp(dir='.', suffix='.txt')\n files = [path.abspath(archive), path.abspath(simulation), output_file]\n LOGGER.debug(\"Data preperation took %s seconds.\",\n time.time() - start_time)\n\n ############################\n # generate the config file\n ############################\n response.update_status('writing config file', 15)\n start_time = time.time() # measure write config ...\n try:\n config_file = analogs.get_configfile(\n files=files,\n seasoncyc_base=seasoncyc_base,\n seasoncyc_sim=seasoncyc_sim,\n timewin=timewin,\n varname=var,\n seacyc=seacyc,\n cycsmooth=91,\n nanalog=nanalog,\n seasonwin=seasonwin,\n distfun=distance,\n outformat=outformat,\n calccor=True,\n silent=False,\n period=[dt.strftime(refSt, '%Y-%m-%d'),\n dt.strftime(refEn, '%Y-%m-%d')],\n bbox=\"%s,%s,%s,%s\" % (bbox[0],\n bbox[2],\n bbox[1],\n bbox[3]))\n except Exception as e:\n msg = 'failed to generate config file %s ' % e\n LOGGER.debug(msg)\n raise Exception(msg)\n LOGGER.debug(\"write_config took %s seconds.\", time.time() - start_time)\n #######################\n # CASTf90 call\n #######################\n start_time = time.time() # measure call castf90\n\n response.update_status('Start CASTf90 call', 20)\n try:\n # response.update_status('execution of CASTf90', 50)\n cmd = ['analogue.out', path.relpath(config_file)]\n LOGGER.debug(\"castf90 command: %s\", cmd)\n output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)\n LOGGER.info('analogue output:\\n %s', output)\n response.update_status('**** CASTf90 suceeded', 90)\n except CalledProcessError as e:\n msg = 'CASTf90 failed:\\n{0}'.format(e.output)\n LOGGER.error(msg)\n raise Exception(msg)\n LOGGER.debug(\"castf90 took %s seconds.\", time.time() - start_time)\n\n ########################\n # generate analog viewer\n ########################\n response.update_status('preparting output', 50)\n response.outputs['config'].file = config_file\n response.outputs['analogs'].file = output_file\n response.outputs['output_netcdf'].file = simulation\n\n try:\n formated_analogs_file = analogs.reformat_analogs(output_file)\n response.outputs['formated_analogs'].file = formated_analogs_file\n LOGGER.info('analogs reformated')\n response.update_status('Successfully reformatted analog file', 60)\n except Exception as e:\n msg = 'Failed to reformat analogs file.' % e\n LOGGER.error(msg)\n raise Exception(msg)\n\n try:\n output_av = analogs.get_viewer(\n formated_analogs_file,\n path.basename(config_file))\n response.outputs['output_html'].file = output_av.name\n response.update_status('Successfully generated analogs viewer', 90)\n LOGGER.info('output_av: %s ', output_av)\n except Exception as e:\n msg = 'Failed to generate viewer: %s' % e\n LOGGER.error(msg)\n raise Exception(msg)\n\n response.update_status('execution ended', 100)\n LOGGER.debug(\"total execution took %s seconds.\",\n time.time() - process_start_time)\n return response\n","sub_path":"flyingpigeon/processes/wps_analogs_reanalyse.py","file_name":"wps_analogs_reanalyse.py","file_ext":"py","file_size_in_byte":21097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"244035797","text":"\"\"\"HelloWorld URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.urls import include, path\r\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.urls import path\r\nfrom django.conf.urls import url\r\nfrom book import views\r\nfrom . import view\r\nurlpatterns = [\r\n url(r'login_user',views.login_user),\r\n url(r'admin', views.jinru),\r\n url(r'html', view.html),\r\n url(r'updown', view.kugou),\r\n url(r'insert', views.insert),\r\n url(r'truncate', views.truncate),\r\n url(r'update', views.update),\r\n url(r'test',views.test),\r\n url(r'mohuselect', views.get),\r\n url(r'qqmusic', views.qqmusic),\r\n \r\n \r\n]\r\n","sub_path":"HelloWorld/HelloWorld/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"30007495","text":"from Element import *\nimport copy\nfrom clockdeco import clock\nclass Edge:\n\t\"\"\" Edge labels are assumed to be function-free and ground, and there can be no edge otherwise\"\"\"\n\t__slots__ = 'source', 'sink', 'label'\n\tdef __init__(self, source, sink, label):\n\t\tself.source= source\n\t\tself.sink = sink\n\t\tself.label = label\n\t\t\n\tdef isConsistent(self, other):\n\t\tif self.source.isConsistent(other.source) and self.sink.isConsistent(other.sink) and self.label == other.label:\n\t\t\treturn True\n\t\treturn False\n\n\tdef isEquivalent(self, other):\n\t\tif self.source.isEquivalent(other.source) and self.sink.isEquivalent(other.sink) and self.label == other.label:\n\t\t\treturn True\n\t\treturn False\n\t\t\n\tdef __eq__(self, other):\n\t\tif other is None:\n\t\t\treturn False\n\t\tif self.source.ID == other.source.ID and self.sink.ID == other.sink.ID and self.label == other.label:\n\t\t\treturn True\n\t\treturn False\n\t\t\n\tdef __ne__(self, other):\n\t\treturn (not self.__eq__(other))\n\t\t\n\tdef __hash__(self):\n\t\treturn hash(self.source.ID) ^ hash(self.sink.ID) ^ hash(self.label)\n\n\tdef assign(self, endpoint, new_val):\n\t\tnew_val.ID = self.endpoint.ID\n\t\tself.endpoint = new_val\n\t\t\n\tdef merge(self, other):\n\t\t\"\"\"Merges source and sink\"\"\"\n\n\t\tif not self.isConsistent(other):\n\t\t\treturn None\n\t\t\t\n\t\tself.source.merge(other.source)\n\t\tself.sink.merge(other.sink)\n\t\t\n\t\treturn self\n\t\n\tdef swapSink(self,sink):\n\t\tself.sink = sink\n\t\treturn self\n\t\t\n\tdef __repr__(self):\n\t\treturn 'Edge {} --{}--> {}'.format(self.source, self.label, self.sink)\n\nclass Graph(Element):\n\t\"\"\"A graph is an element with elements, edges, and restrictions\"\"\"\n\tdef __init__(self, ID, typ, name=None, Elements=None, Edges=None, Restrictions=None):\n\t\tif Elements == None:\n\t\t\tElements = set()\n\t\tif Edges == None:\n\t\t\tEdges = set()\n\t\tif Restrictions == None:\n\t\t\tRestrictions = set()\n\t\t\n\t\tsuper(Graph, self).__init__(ID, typ, name)\n\t\tself.elements = Elements\n\t\tself.edges = Edges\n\t\tself.subgraphs = Restrictions\n\n\tdef __len__(self):\n\t\treturn len(self.elements)\n\n\tdef __iter__(self):\n\t\telms = iter(self.elements)\n\t\tyield next(elms)\n\t\n\tdef getElementById(self, ID):\n\t\tfor element in self.elements:\n\t\t\tif element.ID == ID:\n\t\t\t\treturn element\n\t\treturn None\n\t\n\tdef getElmByRID(self, ID):\n\t\tfor element in self.elements:\n\t\t\tif element.replaced_ID == ID:\n\t\t\t\treturn element\n\t\tfor edge in self.edges:\n\t\t\tif edge.source.replaced_ID == ID:\n\t\t\t\treturn edge.source\n\t\t\tif edge.sink.replaced_ID == ID:\n\t\t\t\treturn edge.sink\n\t\treturn None\n\n\n\tdef replaceWith(self, oldsnk, newsnk):\n\t\t''' removes oldsnk from self.elements, replaces all edges with snk = oldsnk with newsnk'''\n\n\t\tif oldsnk == newsnk:\n\t\t\treturn\n\t\tif self.getElementById(newsnk.ID) is None:\n\t\t\traise NameError('newsnk replacer is not found in self')\n\t\tif oldsnk in self.elements:\n\t\t\tself.elements.remove(oldsnk)\n\t\tfor incoming in (edge for edge in self.edges if edge.sink == oldsnk):\n\t\t\tincoming.sink = newsnk\n\t\t#update constraint edges which might reference specific elements being replaced\n\t\tfor r in self.subgraphs:\n\t\t\tfor r_edge in r.edges:\n\t\t\t\tif r_edge.source == oldsnk:\n\t\t\t\t\tif r_edge.source in r.elements:\n\t\t\t\t\t\tr.elements.add(newsnk)\n\t\t\t\t\tr.replaceWith(r_edge.source, newsnk)\n\t\t\t\tif r_edge.sink == oldsnk:\n\t\t\t\t\tif r_edge.sink in r.elements:\n\t\t\t\t\t\tr.elements.add(newsnk)\n\t\t\t\t\tr.replaceWith(r_edge.sink, newsnk)\n\t\treturn self\n\n\tdef assign(self, old_elm_in_edge, new_elm, remove_old=True):\n\t\tif new_elm not in self.elements:\n\t\t\tself.elements.add(new_elm)\n\t\tif remove_old:\n\t\t\tself.elements.remove(old_elm_in_edge)\n\t\tedges = iter(self.edges)\n\t\tfor edge in edges:\n\t\t\tif edge.source == old_elm_in_edge:\n\t\t\t\tself.edges.add(Edge(new_elm, edge.sink, edge.label))\n\t\t\t\tself.edges.remove(edge)\n\t\t\tif edge.sink == old_elm_in_edge:\n\t\t\t\tself.edges.add(Edge(edge.source, new_elm, edge.label))\n\t\t\t\tself.edges.remove(edge)\n\t\tfor r in self.subgraphs:\n\t\t\tif r.name == 'Restriction':\n\t\t\t\tr.assign(old_elm_in_edge, new_elm)\n\n\n\tdef getEdgesByLabel(self, label):\n\t\treturn {edge for edge in self.edges if edge.label == label}\n\t\t\t\n\tdef getEdgesByIdsAndLabel(self, source_id, sink_id, label):\n\t\treturn {edge for edge in self.edges if edge.source.ID == source_id and edge.sink.ID == sink_id and edge.label == label}\n\n\n\tdef getIncidentEdges(self, element):\n\t\treturn {edge for edge in self.edges if edge.source == element}\n\tdef getNeighbors(self, element):\n\t\treturn {edge.sink for edge in self.edges if edge.source.ID == element.ID}\n\tdef getEstablishingParent(self, element):\n\t\treturn next(iter(edge.source for edge in self.edges if edge.sink == element and edge.label == 'effect-of'))\n\tdef getParents(self, element):\n\t\treturn set(edge.source for edge in self.edges if edge.sink == element)\n\tdef getNeighborsByLabel(self, element, label):\n\t\treturn {edge.sink for edge in self.edges if edge.source.ID == element.ID and edge.label == label}\n\tdef getIncidentEdgesByLabel(self, element, label):\n\t\treturn {edge for edge in self.edges if edge.source.ID == element.ID and edge.label == label}\n\tdef getParentsByLabel(self, element, label):\n\t\treturn set(edge.source for edge in self.edges if edge.sink is element and edge.label is label)\n\tdef getIncomingEdges(self, element):\n\t\treturn {edge for edge in self.edges if edge.sink == element}\n\tdef getIncomingEdgesByType(self, element, typ):\n\t\treturn {edge for edge in self.edges if edge.sink == element and edge.source.typ == typ}\n\tdef getIncomingEdgesByTypeAndLabel(self, element, typ, label):\n\t\treturn {edge for edge in self.edges if edge.sink == element and edge.source.typ == typ and edge.label == label}\n\t\t\n\t###### rGet ####################\n\tdef rGetDescendants(self, element, Descendants=None):\n\t\tif Descendants == None:\n\t\t\tDescendants = set()\n\t\t\t\n\t\tDescendants.add(element)\n\t\t\n\t\t#Base Case\n\t\tincidentEdges = self.getIncidentEdges(element)\n\t\tif len(incidentEdges) == 0:\n\t\t\treturn Descendants\n\t\t\t\n\t\t#Induction\n\t\tfor edge in incidentEdges:\n\t\t\t#Descendants.add(edge.sink)\n\t\t\tDescendants = self.rGetDescendants(edge.sink, Descendants)\n\t\treturn Descendants\n\n\tdef rGetDescendantEdges(self, element, Descendant_Edges=None):\n\t\tif Descendant_Edges == None:\n\t\t\tDescendant_Edges = set()\n\t\t#Base Case\n\t\tincident_Edges = self.getIncidentEdges(element)\n\t\tif len(incident_Edges) == 0:\n\t\t\treturn Descendant_Edges\n\t\t\n\t\t#Induction\n\t\tDescendant_Edges= Descendant_Edges.union(incident_Edges)\n\t\tfor edge in incident_Edges:\n\t\t\tDescendant_Edges = self.rGetDescendantEdges(edge.sink, Descendant_Edges)\n\t\t\t\n\t\treturn Descendant_Edges\n\n\tdef isConsistentSubgraph(self, cndt_subgraph, return_map=False):\n\t\t\"\"\"\n\t\t@param other: a graph which may be a consistent subgraph of self\n\t\t@param return_map\n\t\t@return: if for each other.edge, there is a consistent self.edge, following the shared-endpoints rule of edge sets\n\t\t\"\"\"\n\t\tpossible_map = isConsistentEdgeSet(Rem=copy.deepcopy(cndt_subgraph.edges), Avail=copy.deepcopy(self.edges),\n\t\t\t\t\t\t\t\t\t\t return_map=return_map)\n\t\tif not possible_map is False:\n\t\t\t#returns True when return_map is False\n\t\t\t#return_map = possible_map\n\t\t\treturn possible_map\n\t\treturn False\n\n\tdef findConsistentSubgraph(self, cndt_subgraph):\n\t\treturn findConsistentEdgeMap(Rem = copy.deepcopy(cndt_subgraph.edges), Avail = copy.deepcopy(self.edges))\n\t\t\n\tdef isInternallyConsistent(self):\n\t\treturn not self.equivalentWithRestrictions()\n\n\tdef equivalentWithRestrictions(self):\n\t\tif not hasattr(self, 'subplans') or len(self.subplans) == 0:\n\t\t\treturn False\n\n\t\tfor restriction in self.subgraphs:\n\t\t\tif restriction.type_graph != 'Restriction':\n\t\t\t\tcontinue\n\t\t\tif restriction.isIsomorphicSubgraphOf(self):\n\t\t\t\treturn True\n\t\treturn False\n\n\tdef __repr__(self):\n\t\tedges = str([edge for edge in self.edges])\n\t\telms = str([elm for elm in self.elements])\n\t\treturn '\\n' + edges + '\\n\\n_____\\n\\n ' + elms + '\\n'\n\n\n################################################################\n# consistent edge sets following shared endpoints clause ####\n################################################################\n\ndef isConsistentEdgeSet(Rem, Avail, map_=None, return_map=False):\n\tif map_ == None:\n\t\tmap_ = {}\n\n\t#Base Case - all Remaining edges\n\tif len(Rem) == 0:\n\t\tif return_map:\n\t\t\treturn map_\n\t\treturn True\n\n\tedge_match = Rem.pop()\n\n\tcndt_edges = {edge for edge in Avail if edge.isConsistent(edge_match)}\n\n\tif edge_match.source in map_:\n\t\tcndt_edges -= {edge for edge in cndt_edges if not edge.source == map_[edge_match.source]}\n\tif edge_match.sink in map_:\n\t\tcndt_edges -= {edge for edge in cndt_edges if not edge.sink == map_[edge_match.sink]}\n\n\tif len(cndt_edges) == 0:\n\t\treturn False\n\n\tfor cndt in cndt_edges:\n\t\tMap_ = copy.deepcopy(map_)\n\t\tif not cndt.source in map_:\n\t\t\tMap_[edge_match.source] = cndt.source\n\t\tif not cndt.sink in map_:\n\t\t\tMap_[edge_match.sink] = cndt.sink\n\t\t_Map = isConsistentEdgeSet(copy.deepcopy(Rem), Avail-{cndt}, Map_, return_map)\n\t\tif not _Map is False:\n\t\t\tif return_map:\n\t\t\t\treturn _Map\n\t\t#if isConsistentEdgeSet(copy.deepcopy(Rem), Avail-{cndt}, Map_):\n\t\t#\tif return_map:\n\t\t#\t\treturn Map_\n\t\t#\treturn True\n\treturn False\n\n\n\ndef findConsistentEdgeMap(Rem, Avail, map_ = None, Super_Maps = None):\n\tif map_ is None:\n\t\tmap_ = {}\n\tif Super_Maps is None:\n\t\tSuper_Maps = []\n\n\t#Base Case - all Remaining edges\n\tif len(Rem) == 0:\n\t\tSuper_Maps.append(map_)\n\t\treturn Super_Maps\n\n\tedge_match = Rem.pop()\n\n\tcndt_edges = {edge for edge in Avail if edge.isConsistent(edge_match)}\n\n\tif edge_match.source in map_:\n\t\tcndt_edges -= {edge for edge in cndt_edges if not edge.source == map_[edge_match.source]}\n\tif edge_match.sink in map_:\n\t\tcndt_edges -= {edge for edge in cndt_edges if not edge.sink == map_[edge_match.sink]}\n\n\tif len(cndt_edges) == 0:\n\t\treturn Super_Maps\n\n\tfor cndt in cndt_edges:\n\t\tMap_ = copy.deepcopy(map_)\n\t\tif not cndt.source in map_:\n\t\t\tMap_[edge_match.source] = cndt.source\n\t\tif not cndt.sink in map_:\n\t\t\tMap_[edge_match.sink] = cndt.sink\n\t\tfindConsistentEdgeMap(copy.deepcopy(Rem), Avail, Map_, Super_Maps)\n\n\treturn Super_Maps\n\n#A method - unify - which given two graphs, will merge. currently performed by mergeGraph\n# def UnifyActions(_Map = None, R = None, A = None):\n# \t\"\"\"\n#\n# \t@param _Map: dictonary\n# \t@param R: edges to account for\n# \t@param A: edges which account as\n# \t@return: dictionary _Map\n# \t\"\"\"\n#\n# \tif _Map ==None:\n# \t\t_Map = {} \t;#_Map is a 1:1 mapping (r : a) for r in \"R\" for a in \"A\" s.t. every edge in \"R\" has one partner in \"A\"\n# \t\t\t\t\t#Mapping is a dictionary.\n# \tif R == None:\n# \t\tR = []\t\t;#\"R\" is the set of edges all of whose edges must be accounted for\n# \tif A == None:\n# \t\tA = []\t\t;#\"A\" is the set of edges which account for edges in \"R\".\n#\n# \tif len(R) == 0:\n# \t\treturn _Map\n#\n# \trem = R.pop()\n# \tcndts = {edge for edge in A if edge.isConsistent(rem)}\n#\n# \tif rem.source in _Map:\n# \t\tcndts -= {edge for edge in cndts if not edge.source == _Map[rem.source]}\n# \tif rem.sink in _Map:\n# \t\tcndts -= {edge for edge in cndts if not edge.sink == _Map[rem.sink]}\n#\n# \tif len(cndts) == 0:\n# \t\treturn []\n#\n# \tMbins = []\n# \tfor cndt in cndts:\n# \t\tMap_ = copy.deepcopy(_Map)\n# \t\tif not cndt.source in _Map:\n# \t\t\tMap_[rem.source] = cndt.source\n# \t\tif not cndt.sink in _Map:\n# \t\t\tMap_[rem.sink] = cndt.sink\n#\n# \t\t#if this 'cndt' was to account for 'rem', recursively solve for rest of R and append all possible worlds in []\n# \t\tM_ = isConsistentEdgeSet(Map_ = _Map, R = copy.deepcopy(R), A = A-{cndt})\n# \t\tMbins = consistentMaps(prior_maps=Map_,cndt_maps = M_, Mbins = Mbins)\n#\n# \tif len(Mbins) == 0:\n# \t\treturn []\n#\n# \treturn _Map.extend(Mbins)\n\n\nimport unittest\n\nclass TestGraph(unittest.TestCase):\n\tpass\n\t# def test_consistent_edge_set(self):\n\t# \t\"\"\"\n\t# \t\t\tFull Graph\n\t# \t\t\t1 --> 2 --> 3 --> 5\n\t# \t\t\t\t 2 --> 4 --> 5\n\t#\n\t# \t\t\tRequirements\n\t# \t\t\t[2] --> [3]\n\t# \t\t\t[2] --> [4]\n\t#\n\t#\n\t# \t\t\"\"\"\n\t# \tG = \t ['buffer',\n\t# \t\t\t Element(ID=1,name=1, typ='1'),\n\t# \t\t\t Element(ID=2,name=2, typ='2'),\n\t# \t\t\t Element(ID=3,name=3, typ='3'),\n\t# \t\t\t Element(ID=4,name=4, typ='4'),\n\t# \t\t\t Element(ID=5,name=5, typ='5')]\n\t# \tO =\t\t [Element(ID=20, typ='2'),\n\t# \t\t\t Element(ID=30, typ='3'),\n\t# \t\t\t Element(ID=40, typ='4')]\n\t#\n\t# \tAvail = {Edge(G[1],G[2],'a'),\n\t# \t\t Edge(G[2],G[3], 'b'),\n\t# \t\t Edge(G[2],G[4], 'c'),\n\t# \t\t Edge(G[3],G[5], 'd'),\n\t# \t\t Edge(G[4],G[5], 'e')}\n\t# \tRem = {\n\t# \t\t\tEdge(O[0],O[1], 'b'),\n\t# \t\t\tEdge(O[0],O[2], 'c')}\n\t#\n\t#\n\t# \tisit = isConsistentEdgeSet(Rem, Avail)\n\t# \tassert(isit)\n\t# \tassert(not isConsistentEdgeSet(Avail, Rem))\n\t# \tprint(isit)\n\t#\n\t# \t#With LARGER example to look through\n\t# \tG = ['buffer']\n\t# \tG+= [Element(ID=i, name=i, typ=str(i)) for i in range(1,900)]\n\t# \tAvail = {Edge(G[i],G[i+1],'m') for i in range(1,700)}\n\t# \tAvail.update({Edge(G[1],G[2],'a'),\n\t# \t\t Edge(G[2],G[3], 'b'),\n\t# \t\t Edge(G[2],G[4], 'c'),\n\t# \t\t Edge(G[3],G[5], 'd'),\n\t# \t\t Edge(G[4],G[5], 'e')})\n\t#\n\t# \tisit = isConsistentEdgeSet(Rem, Avail)\n\t# \tassert (isit)\n\t# \tprint(isit)\n\nif __name__ == '__main__':\n\tpass\n\t#unittest.main()","sub_path":"Graph.py","file_name":"Graph.py","file_ext":"py","file_size_in_byte":12765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"278546140","text":"#!/usr/bin/env python\n\n__copyright__ = \"Copyright 2018, The PICRUSt Project\"\n__license__ = \"GPL\"\n__version__ = \"2.0.0-b.3\"\n\nfrom os import path, chdir, getcwd\nfrom picrust2.util import (system_call_check, make_output_dir, read_fasta,\n read_phylip, write_fasta, write_phylip)\n\n\ndef place_seqs_pipeline(study_fasta,\n ref_msa,\n tree,\n out_tree,\n threads,\n papara_output,\n out_dir,\n chunk_size,\n print_cmds):\n '''Full pipeline for running sequence placement.'''\n\n # Read in ref seqs FASTA as a dict.\n ref_msa = read_fasta(ref_msa)\n\n # Either read in PaPaRa output or run it.\n if papara_output:\n # Read in PaPaRa output if already done.\n papara_out = read_phylip(papara_output, check_input=True)\n\n else:\n # Run PaPaRa to place study sequences and read in Phylip file.\n papara_out = run_papara(tree=tree, ref_msa=ref_msa,\n study_fasta=study_fasta, out_dir=out_dir,\n threads=threads, print_cmds=print_cmds)\n\n # Specify split FASTA files to be created.\n study_msa_fastafile = path.join(out_dir, \"study_seqs_papara.fasta\")\n ref_msa_fastafile = path.join(out_dir, \"ref_seqs_papara.fasta\")\n\n # Split PaPaRa output into two FASTA files containging study and reference\n # sequences respectively.\n split_ref_study_papara(papara_out=papara_out,\n ref_seqnames=set(list(ref_msa.keys())),\n study_fasta=study_msa_fastafile,\n ref_fasta=ref_msa_fastafile)\n\n # Run EPA-NG to output .jplace file.\n epa_out_dir = path.join(out_dir, \"epa_out\")\n\n run_epa_ng(tree=tree, ref_msa_fastafile=ref_msa_fastafile,\n study_msa_fastafile=study_msa_fastafile, chunk_size=chunk_size,\n threads=threads, out_dir=epa_out_dir, print_cmds=print_cmds)\n\n jplace_outfile = path.join(epa_out_dir, \"epa_result.jplace\")\n\n gappa_jplace_to_newick(jplace_file=jplace_outfile, outfile=out_tree,\n print_cmds=print_cmds)\n\n\ndef run_papara(tree: str, ref_msa: dict, study_fasta: str, out_dir: str,\n threads=1, print_cmds=False):\n '''Run PaPaRa to place study sequences into reference multiple-sequence\n alignment (MSA). Will return dictionary of the the output MSA (sequence ids\n as keys). Expects path to tree and study FASTA as strings. Expects\n reference MSA as a dictionary output by read_fasta. This MSA will be\n converted to phylip format before running PaPaRa.'''\n\n # Get absolute paths to input files.\n tree = path.abspath(tree)\n study_fasta = path.abspath(study_fasta)\n\n # Change working directory to out directory (but keep track of original).\n # This is necessary because PaPaRa outputs into the current working\n # directory.\n orig_wd = getcwd()\n chdir(out_dir)\n\n # Convert ref sequences from MSA FASTA to phylip.\n write_phylip(ref_msa, \"ref_seqs.phylip\")\n\n # Make call to papara to place sequences (outputs phylip format).\n system_call_check(\"papara -t \" + tree + \" -s ref_seqs.phylip \" +\n \"-q \" + study_fasta + \" -j \" + str(threads) +\n \" -n out\", print_out=print_cmds)\n\n # Change back to original working directory.\n chdir(orig_wd)\n\n # Read in papara phylip output and return.\n return(read_phylip(path.join(out_dir, \"papara_alignment.out\"),\n check_input=True))\n\n\ndef split_ref_study_papara(papara_out: dict, ref_seqnames: set, ref_fasta: str,\n study_fasta: str):\n '''Split PaPaRa phylip output into FASTA MSA files of study sequences and\n reference sequences separately. Expects PaPaRa output already read in\n as dictionary. Takes in the PaPaRa output as a dictionary, a set that\n contains all sequence ids in reference MSA, and the output FASTA\n filenames.'''\n\n # Determine study sequence id based on those found in the all and ref sets.\n all_seqnames = set(list(papara_out.keys()))\n study_seqnames = all_seqnames.difference(ref_seqnames)\n\n # Get subsets of PaPaRa output MSA of reference study sequences only.\n ref_papara_subset = {seq: papara_out[seq] for seq in ref_seqnames}\n study_papara_subset = {seq: papara_out[seq] for seq in study_seqnames}\n\n write_fasta(ref_papara_subset, ref_fasta)\n write_fasta(study_papara_subset, study_fasta)\n\n\ndef run_epa_ng(tree: str, ref_msa_fastafile: str, study_msa_fastafile: str,\n out_dir: str, chunk_size=5000, threads=1, print_cmds=False):\n '''Run EPA-NG on specified tree, reference MSA, and study sequence MSA.\n Will opath.joinutput a .jplace file in out_dir.'''\n\n make_output_dir(out_dir)\n\n system_call_check(\"epa-ng --tree \" + tree + \" --ref-msa \" +\n ref_msa_fastafile + \" --query \" + study_msa_fastafile +\n \" --chunk-size \" + str(chunk_size) + \" -T \" +\n str(threads) + \" -w \" + out_dir, print_out=print_cmds)\n\n\ndef gappa_jplace_to_newick(jplace_file: str, outfile: str, print_cmds=False):\n '''System call to gappa binary to convert jplace object to newick\n treefile (with specified filename).'''\n\n gappa_out_dir = path.dirname(jplace_file)\n\n # Run gappa to convert jplace to newick.\n system_call_check(\"gappa analyze graft --jplace-path \" + jplace_file +\n \" --fully-resolve --out-dir \" + gappa_out_dir,\n print_out=print_cmds)\n\n # Expected name of output newick file.\n newick_file = jplace_file.replace(\".jplace\", \".newick\")\n\n # Rename newick file to be specified outfile.\n system_call_check(\"mv \" + newick_file + \" \" + outfile,\n print_out=print_cmds)\n","sub_path":"picrust2/build/lib/picrust2/place_seqs.py","file_name":"place_seqs.py","file_ext":"py","file_size_in_byte":5922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"233955897","text":"# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom timeit import default_timer as timer\r\nimport random\r\nimport math\r\nfrom Fundamental_Calculation_Functions import weighted_reindeer_weariness\r\n\r\n\r\n### import the sampled datasets\r\n\r\ngifts1= pd.read_csv('gifts1.csv')\r\ngifts2= pd.read_csv('gifts2.csv')\r\ngifts3= pd.read_csv('gifts3.csv')\r\n\r\n\r\n\r\n### implmentation of the Random Search algorithm\r\n\r\n ### the output of this function is the best weariness(objective function) found \r\ndef Random_Search(gifts): ### for 1000xN solution evaluations where N is the size of the problem\r\n \r\n ### at first we generate and evaluate one random solution\r\n \r\n y = weighted_reindeer_weariness(gifts)\r\n \r\n opt_total_weariness = y\r\n \r\n s_best = opt_total_weariness\r\n \r\n maximum_eval = 1000*gifts.shape[0] ### define the maximum number of evaluations\r\n for i in range(maximum_eval): ### as 1000xN \r\n x1 = weighted_reindeer_weariness(gifts)\r\n if (x1 < s_best):\r\n s_best = x1\r\n \r\n \r\n return int(s_best) \r\n \r\n\r\n\r\n\r\n \r\ndef RandomSeed_RandomSearch(gifts): ### with this function we can run Random_Search\r\n ### for 30 different seeds\r\n weariness_set = []\r\n time = []\r\n \r\n \r\n for i in range(30,60):\r\n np.random.seed(i)\r\n start_time = timer()\r\n x = Random_Search(gifts)\r\n stop_time = timer()\r\n weariness_set.append(x)\r\n time.append(round(stop_time - start_time,2))\r\n \r\n time = np.array(time) \r\n weariness_set = np.array(weariness_set)\r\n \r\n\r\n return weariness_set,time\r\n\r\n\r\n### we will save the results in a dataframe\r\nRandomSearch_results = pd.DataFrame()\r\n\r\nx1,x2 = RandomSeed_RandomSearch(gifts1)\r\nRandomSearch_results.loc[:,'gifts1'] = x1\r\nRandomSearch_results.loc[:,'gifts1_time'] = x2\r\n\r\ny1,y2 = RandomSeed_RandomSearch(gifts2)\r\nRandomSearch_results.loc[:,'gifts2'] = y1\r\nRandomSearch_results.loc[:,'gifts2_time'] = y2\r\n \r\nz1,z2 = RandomSeed_RandomSearch(gifts3)\r\nRandomSearch_results.loc[:,'gifts3'] = z1\r\nRandomSearch_results.loc[:,'gifts3_time'] = z2\r\n \r\n\r\nRandomSearch_results.iloc[:,::2].min() \r\nRandomSearch_results.iloc[:,::2].max() \r\nRandomSearch_results.iloc[:,::2].mean() \r\nRandomSearch_results.iloc[:,::2].std() \r\nRandomSearch_results.iloc[:,1::2].mean()\r\n\r\n\r\n\r\n\r\nRandomSearch_results.to_csv('RandomSearch_results.csv', encoding='utf-8')\r\n","sub_path":"Random_Search.py","file_name":"Random_Search.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"75518738","text":"# coding=utf-8\n\n\"\"\"First Bad Version.\"\"\"\n\nfrom __future__ import print_function\n\n\ndef isBadVersion(version):\n \"\"\"API.\"\"\"\n bad_version = 3\n if version < bad_version:\n return False\n return True\n\n\ndef _solve(n):\n start, end = 1, n\n while start <= end:\n mid = start + (end - start) / 2\n if isBadVersion(mid):\n end = mid - 1\n else:\n start = mid + 1\n return start\n\n\nif __name__ == '__main__':\n for i in xrange(10):\n print (i, '->', _solve(i))\n","sub_path":"easy/278.py","file_name":"278.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"627358689","text":"\"\"\"\nDataLoaders to take parquet directories and create feature vectors suitable\nfor use by models found in this project.\n\"\"\"\nfrom collections import defaultdict\nfrom pathlib import Path\n\nimport numpy as np\nimport psutil\nimport torch\nfrom torch.nn.functional import one_hot\nfrom torch.utils.data import DataLoader\nfrom torch_geometric.data import DataLoader as GeoDataLoader, Data\n\nfrom point_vs.preprocessing.preprocessing import make_box, \\\n concat_structs, make_bit_vector, uniform_random_rotation, generate_edges\nfrom point_vs.utils import load_yaml\n\n\nclass PointCloudDataset(torch.utils.data.Dataset):\n \"\"\"Class for feeding structure parquets into network.\"\"\"\n\n def __init__(\n self, base_path, radius=12,\n polar_hydrogens=True, use_atomic_numbers=False,\n compact=True, rot=False, augmented_active_count=0,\n augmented_active_min_angle=90, max_active_rms_distance=None,\n min_inactive_rms_distance=None, fname_suffix='parquet',\n types_fname=None, edge_radius=None, estimate_bonds=False,\n prune=False, bp=None, **kwargs):\n \"\"\"Initialise dataset.\n\n Arguments:\n base_path: path containing the 'receptors' and 'ligands'\n directories, which in turn contain .parquets files\n and folders called _[active|decoy] which in turn\n contain .parquets files. All parquets files from\n this directory are recursively loaded into the dataset.\n radius: size of the bounding box; all atoms further than \n Angstroms from the mean ligand atom position are discarded.\n polar_hydrogens: include polar hydrogens as input\n use_atomic_numbers: use atomic numbers rather than sminatypes\n compact: compress 1hot vectors by using a single bit to\n signify whether atoms are from the receptor or ligand rather\n than using two input bits per atom type\n rot: random rotation of inputs\n augmented_active_count: number of actives to be rotated randomly\n and used as decoys (per active in the training set)\n augmented_active_min_angle: minimum angle of rotation for each\n augmented active (as specified in augmented_active_count)\n max_active_rms_distance: (pose selection) maximum rmsd between\n relaxed crystal structure and crystal structure\n min_inactive_rms_distance: (pose selection) minimum rmsd between\n redocked and relaxed crystal structure\n include_relaxed: (pose selection) include the relaxed crystal\n structure as an active\n types_fname:\n edge_radius:\n estimate_bonds:\n kwargs: keyword arguments passed to the parent class (Dataset).\n \"\"\"\n\n assert not ((max_active_rms_distance is None) != (\n min_inactive_rms_distance is None))\n super().__init__()\n self.radius = radius\n self.estimate_bonds = estimate_bonds\n self.base_path = Path(base_path).expanduser()\n self.prune = prune\n self.bp = bp\n if edge_radius > 0:\n self.edge_radius = edge_radius\n\n self.fname_suffix = fname_suffix\n if not self.base_path.exists():\n raise FileNotFoundError(\n 'Dataset {} does not exist.'.format(self.base_path))\n self.polar_hydrogens = polar_hydrogens\n self.use_atomic_numbers = use_atomic_numbers\n self.compact = compact\n\n labels = []\n self.use_types = False if types_fname is None else True\n if max_active_rms_distance is not None \\\n or min_inactive_rms_distance is not None:\n label_by_rmsd = True\n else:\n label_by_rmsd = False\n\n aug_recs, aug_ligs = [], []\n confirmed_ligs = []\n confirmed_recs = []\n if self.use_types:\n _labels, rmsds, receptor_fnames, ligand_fnames = \\\n types_to_list(types_fname)\n\n # Do we use provided labels or do we generate our own using rmsds?\n labels = [] if label_by_rmsd else _labels\n for path_idx, (receptor_fname, ligand_fname) in enumerate(\n zip(receptor_fnames, ligand_fnames)):\n if label_by_rmsd:\n # Pose selection, filter by max/min active/inactive rmsd\n # from xtal poses\n rmsd = rmsds[path_idx]\n if rmsd < 0:\n continue\n elif rmsd < max_active_rms_distance:\n labels.append(1)\n aug_ligs += [ligand_fname] * augmented_active_count\n aug_recs += [receptor_fname] * augmented_active_count\n elif rmsd >= min_inactive_rms_distance:\n labels.append(0)\n else: # discard this entry (do not add to confirmed_ligs)\n continue\n elif labels[path_idx]:\n aug_ligs += [ligand_fname] * augmented_active_count\n aug_recs += [receptor_fname] * augmented_active_count\n confirmed_ligs.append(ligand_fname)\n confirmed_recs.append(receptor_fname)\n self.receptor_fnames = confirmed_recs + aug_recs\n else:\n print('Loading all structures in', self.base_path)\n ligand_fnames = list(\n (self.base_path / 'ligands').glob('**/*.' + fname_suffix))\n if label_by_rmsd:\n rmsd_info_fname = Path(self.base_path, 'rmsd_info.yaml')\n rmsd_info = load_yaml(rmsd_info_fname)\n\n for path_idx, ligand_fname in enumerate(ligand_fnames):\n if label_by_rmsd:\n if str(ligand_fname.parent.name).find('active') != -1:\n continue\n pdbid = ligand_fname.parent.name.split('_')[0]\n idx = int(Path(ligand_fname.name).stem.split('_')[-1])\n try:\n rmsd = rmsd_info[pdbid]['docked_wrt_crystal'][idx]\n except KeyError:\n continue\n if rmsd < 0:\n continue\n if rmsd < max_active_rms_distance:\n labels.append(1)\n aug_ligs += [ligand_fname] * augmented_active_count\n elif rmsd >= min_inactive_rms_distance:\n labels.append(0)\n else: # discard this entry (do not add to confirmed_ligs)\n continue\n else:\n if str(ligand_fname.parent.name).find('active') == -1:\n labels.append(0)\n else:\n labels.append(1)\n aug_ligs += [ligand_fname] * augmented_active_count\n confirmed_ligs.append(ligand_fname)\n self.receptor_fnames = None\n\n self.pre_aug_ds_len = len(ligand_fnames)\n self.ligand_fnames = confirmed_ligs + aug_ligs\n\n labels += [0] * len(aug_ligs)\n labels = np.array(labels)\n active_count = np.sum(labels)\n class_sample_count = np.array(\n [len(labels) - active_count, active_count])\n if np.sum(labels) == len(labels) or np.sum(labels) == 0:\n self.sampler = None\n else:\n weights = 1. / class_sample_count\n self.sample_weights = torch.from_numpy(\n np.array([weights[i] for i in labels]))\n self.sampler = torch.utils.data.WeightedRandomSampler(\n self.sample_weights, len(self.sample_weights)\n )\n self.labels = labels\n print('There are', len(labels), 'training points in', base_path)\n\n # apply random rotations to ALL coordinates?\n self.transformation = uniform_random_rotation if rot else lambda x: x\n\n if use_atomic_numbers:\n # H C N O F P S Cl\n recognised_atomic_numbers = (6, 7, 8, 9, 15, 16, 17)\n # various metal ions/halogens which share valence properties\n other_groupings = ((35, 53), (3, 11, 19), (4, 12, 20), (26, 29, 30))\n atomic_number_to_index = {\n num: idx for idx, num in enumerate(recognised_atomic_numbers)\n }\n for grouping in other_groupings:\n atomic_number_to_index.update({elem: max(\n atomic_number_to_index.values()) + 1 for elem in grouping})\n if self.polar_hydrogens:\n atomic_number_to_index.update({\n 1: max(atomic_number_to_index.values()) + 1\n })\n\n # +1 to accommodate for unmapped elements\n self.max_feature_id = max(atomic_number_to_index.values()) + 1\n\n # Any other elements not accounted for given a category of their own\n self.atomic_number_to_index = defaultdict(\n lambda: self.max_feature_id)\n self.atomic_number_to_index.update(atomic_number_to_index)\n\n elif polar_hydrogens:\n self.max_feature_id = 11 # FID = 10 if polar hydrogen\n else:\n self.max_feature_id = 10 # No polar hydrogens\n\n if compact:\n self.feature_dim = self.max_feature_id + 2\n else:\n self.feature_dim = (self.max_feature_id + 1) * 2\n\n self.augmented_active_min_angle = augmented_active_min_angle\n\n def __len__(self):\n \"\"\"Return the total size of the dataset.\"\"\"\n return len(self.ligand_fnames)\n\n def index_to_parquets(self, item):\n label = self.labels[item]\n if self.use_types:\n lig_fname = Path(self.ligand_fnames[item])\n rec_fname = Path(self.receptor_fnames[item])\n else:\n lig_fname = self.ligand_fnames[item]\n rec_name = lig_fname.parent.name.split('_')[0]\n try:\n rec_fname = next((self.base_path / 'receptors').glob(\n '{0}*.{1}'.format(rec_name, self.fname_suffix)))\n except StopIteration:\n raise RuntimeError(\n 'Receptor for ligand {0} not found. Looking for file '\n 'named {1}'.format(\n lig_fname, rec_name + '.' + self.fname_suffix))\n return lig_fname, rec_fname, label\n\n def parquets_to_inputs(self, lig_fname, rec_fname, item=None):\n\n # Are we using an active and labelling it as a decoy through random\n # rotation? This determination is made using the index, made possible\n # due to the construction of the filenames class variable in the\n # constructor: all actives labelled as decoys are found at the end.\n if item is None or item < self.pre_aug_ds_len:\n aug_angle = 0\n else:\n aug_angle = self.augmented_active_min_angle\n\n if self.use_types:\n rec_fname = self.base_path / rec_fname\n lig_fname = self.base_path / lig_fname\n\n struct = make_box(concat_structs(\n rec_fname, lig_fname, min_lig_rotation=aug_angle),\n radius=self.radius, relative_to_ligand=True)\n\n if not self.polar_hydrogens:\n struct = struct[struct['atomic_number'] > 1]\n\n if self.use_atomic_numbers:\n struct.types = struct['atomic_number'].map(\n self.atomic_number_to_index) + struct.bp * (\n self.max_feature_id + 1)\n\n p = torch.from_numpy(\n self.transformation(\n np.vstack([struct['x'], struct['y'], struct['z']]).T))\n\n v = make_bit_vector(\n struct.types.to_numpy(), self.max_feature_id + 1, self.compact)\n\n return p, v, struct\n\n def __getitem__(self, item):\n \"\"\"Given an index, locate and preprocess relevant parquet file.\n\n Arguments:\n item: index in the list of filenames denoting which ligand and\n receptor to fetch\n\n Returns:\n Tuple containing (a) a tuple with a list of tensors: cartesian\n coordinates, feature vectors and masks for each point, as well as\n the number of points in the structure and (b) the label \\in \\{0, 1\\}\n denoting whether the structure is an active or a decoy.\n \"\"\"\n lig_fname, rec_fname, label = self.index_to_parquets(item)\n p, v, struct = self.parquets_to_inputs(lig_fname, rec_fname, item=item)\n\n return (p, v, len(struct)), lig_fname, rec_fname, label\n\n\nclass PygPointCloudDataset(PointCloudDataset):\n \"\"\"Class for feeding structure parquets into network.\"\"\"\n\n def __getitem__(self, item):\n \"\"\"Given an index, locate and preprocess relevant parquet file.\n\n Arguments:\n item: index in the list of filenames denoting which ligand and\n receptor to fetch\n\n Returns:\n Tuple containing (a) a tuple with a list of tensors: cartesian\n coordinates, feature vectors and masks for each point, as well as\n the number of points in the structure and (b) the label \\in \\{0, 1\\}\n denoting whether the structure is an active or a decoy.\n \"\"\"\n lig_fname, rec_fname, label = self.index_to_parquets(item)\n p, v, struct = self.parquets_to_inputs(lig_fname, rec_fname, item=item)\n\n if hasattr(self, 'edge_radius'):\n edge_radius = self.edge_radius\n else:\n edge_radius = 4\n intra_radius = 2.0 if self.estimate_bonds else edge_radius\n\n if self.bp is not None:\n struct = struct[struct.bp == self.bp]\n\n struct, edge_indices, edge_attrs = generate_edges(\n struct, inter_radius=edge_radius, intra_radius=intra_radius,\n prune=self.prune)\n\n edge_indices = torch.from_numpy(np.vstack(edge_indices)).long()\n edge_attrs = one_hot(torch.from_numpy(edge_attrs).long(), 3)\n\n return Data(\n x=v,\n edge_index=edge_indices,\n edge_attr=edge_attrs,\n pos=p,\n y=torch.from_numpy(np.array(label)).long(),\n rec_fname=rec_fname,\n lig_fname=lig_fname,\n )\n\n\ndef get_data_loader(\n data_root, dataset_class, receptors=None, batch_size=32, compact=True,\n use_atomic_numbers=False, radius=6, rot=True,\n augmented_actives=0, min_aug_angle=30,\n polar_hydrogens=True, mode='train',\n max_active_rms_distance=None, fname_suffix='parquet',\n min_inactive_rms_distance=None, types_fname=None, edge_radius=None,\n prune=False, estimate_bonds=False, bp=None, **kwargs):\n \"\"\"Give a DataLoader from a list of receptors and data roots.\"\"\"\n ds = dataset_class(\n data_root, compact=compact, receptors=receptors,\n augmented_active_count=augmented_actives,\n augmented_active_min_angle=min_aug_angle,\n polar_hydrogens=polar_hydrogens,\n max_active_rms_distance=max_active_rms_distance,\n min_inactive_rms_distance=min_inactive_rms_distance,\n use_atomic_numbers=use_atomic_numbers,\n fname_suffix=fname_suffix,\n types_fname=types_fname,\n edge_radius=edge_radius,\n estimate_bonds=estimate_bonds,\n prune=prune, bp=bp, radius=radius, rot=rot,\n **kwargs)\n sampler = ds.sampler if mode == 'train' else None\n if dataset_class == PointCloudDataset:\n collate = get_collate_fn(ds.feature_dim)\n return DataLoader(\n ds, batch_size, False, sampler=sampler,\n collate_fn=collate, drop_last=False, pin_memory=True,\n num_workers=min(4, psutil.cpu_count()))\n else:\n return GeoDataLoader(\n ds, batch_size, False, sampler=sampler,\n drop_last=False, pin_memory=True,\n num_workers=min(4, psutil.cpu_count()))\n\n\ndef types_to_list(types_fname):\n \"\"\"Take a types file and returns four lists containing paths and labels.\n\n Types files should be of the format:\n