\"\n\nimport json\n\nfrom django.db import transaction\n\nfrom ..logger import logger\nfrom ..models import Address, Shop, User, Region\n\n\ndef get_region_tree(start_node_code=u'330000000000', end_level=u'village'):\n \"\"\"从数据库取出一棵地址树。\n\n 通过递归实现,最终返回字典。\n \"\"\"\n #logger.debug(u'CODE: %s', code)\n #logger.debug('END_LEVEL: %s', end_level)\n parent = Region.objects.get(code=start_node_code)\n parent_node = {u'name': parent.name, u'code': parent.code}\n if parent.level != end_level and parent.name != u'市辖区':\n parent_node[u'sub'] = []\n children = Region.objects.filter(parent=start_node_code)\n for child in children:\n child_node = get_region_tree(start_node_code=child.code, end_level=end_level)\n parent_node[u'sub'].append(child_node)\n return parent_node\n\n\ndef get_region_json(start_node_name, end_level):\n start_node = Region.objects.filter(name=start_node_name)\n if start_node.exists():\n start_node_code = start_node[0].code\n logger.debug('START_NODE: %s', start_node_code)\n else:\n start_node_code = '330102000000'\n tree = get_region_tree(start_node_code=start_node_code, end_level=end_level)\n #写json文件\n #data = json.dumps(tree, sort_keys=True, indent=4, ensure_ascii=False)\n #logger.debug(type(data))\n #f = codecs.open('./nanxun/region.json', 'w', 'utf-8')\n #f.write(data)\n #f.close()\n #如果使用下面的方法,可以存入文件,但是是中文是unicode的形式。\n #with open(u'region.json', u'w') as f:\n # f.write(data)\n return tree\n\n\ndef modify_page(from_page, openid, start_node_code, end_level):\n if from_page == 'my_info':\n address = User.objects.get(openid=openid).address\n else:\n address = Shop.objects.get(seller__openid=openid).address\n logger.debug('ADDRESS: %s', address)\n address = address.get_str() if address else u'未设置'\n tree = get_region_tree(start_node_code, end_level)\n region_tree = json.dumps(tree, ensure_ascii=False, encoding='utf-8')\n return {u'region_tree': region_tree, 'current_address': address}\n\n\n@transaction.atomic\ndef modify(from_page, openid, id, province, city, county, town, village, address_detail):\n if from_page == 'shop':\n old_address_id = Shop.objects.get(id=id).address.id\n logger.debug(old_address_id)\n old_address = Address.objects.filter(id=old_address_id)\n #logger.debug('old_address:', old_address)\n logger.debug('UPDATED ROW: %s', Address.objects.filter(id=old_address_id).update(province=province, city=city, county=county, town=town, village=village, detail=address_detail))\n #old_address.save(Province=province)\n else:\n user = User.objects.get(openid=openid)\n if user.address:\n Address.objects.filter(id=user.address.id).update(province=province, city=city, county=county, town=town, village=village, detail=address_detail)\n else:\n new_address = Address.objects.create(province=province, city=city, county=county, town=town, village=village, detail=address_detail)\n user.address = new_address\n user.save()\n return {'success': True}\n","sub_path":"weixin_inner/inner_app/service/address.py","file_name":"address.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"440548943","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport re\nimport os\n\n\n# 网页文档\nhtmltext = ''\n\n# 需要剔除的特殊单标签\nspecial = ['','','
','','
','
','']\n\n# 筛选结果\nres = []\n# 未处理标签\ntemp = []\n\n# 栈的实现\nclass Stack(object):\n\n # 初始化\n def __init__(self):\n self.stack = []\n\n # 空栈\n def isEmpty(self):\n return self.stack == []\n\n # 入栈\n def push(self, item):\n self.stack.append(item)\n\n # # 出栈\n # def pop(self):\n # if self.isEmpty():\n # raise IndexError, 'empty'\n # return self.stack.pop()\n\n # 栈的长度\n def size(self):\n return len(self.stack)\n\n\n# 前标签栈\ns1 = Stack()\n# 后标签栈\ns2 = Stack()\n\n\n# 主界面\ndef main_menu():\n # 菜单界面\n print('*******************************************************')\n print('|---------------------------------------------------- |')\n print('|--------------简易HTML文档标记匹配工具-------------- |')\n print('|--------------------1.读取文本内容------------------ |')\n print('|--------------------2.验证文档标记------------------ |')\n print('|--------------------0.退出系统---------------------- |')\n print('|---------------------------------------------------- |')\n print('*******************************************************')\n\n# 读取文本\ndef input_menu():\n doc_in()\n # 界面\n print('*---------------------------------------------------- *')\n print('*读取成功! *')\n print('*---------------------------------------------------- *')\n print('*内容:--------------------------------------------- *')\n print(s1.stack + s2.stack)\n print('*---------------------------------------------------- *')\n\n # 选项\n n = input('请输入选项:(1.退出 2.返回主界面)')\n try:\n while(True):\n if n == 1:\n print('退出系统\\n')\n os.exit(0)\n elif n == 2:\n main_menu()\n break\n else:\n n = input('输入有误,重新输入:')\n except:\n pass\n print('\\n' * 10)\n\n# 文档读入\ndef doc_in():\n global htmltext\n\n # 网页文档的存储文件 :C:\\\\Users\\\\ASUS\\\\Desktop\\\\111.txt\n with open('C:\\\\Users\\\\ASUS\\\\Desktop\\\\111.txt', 'r') as fileopen:\n htmltext += fileopen.read()\n print('读取成功')\n read()\n\n# 验证_界面\ndef match_menu():\n\n opt()\n print(\"*---------------------------------------------------- *\")\n\n if len(htmltext) == 0:\n print('未输入文档')\n else:\n print('验证结果:')\n if len(res) == 0:\n print('文档规范')\n else:\n print('文档出现问题,问题标签如下:')\n print(res)\n print('*---------------------------------------------------- *')\n\n # 选项\n n = input('请输入选项:(1.退出 2.返回主界面)')\n try:\n while (True):\n if n == 1:\n print('退出系统\\n')\n os.exit(0)\n elif n == 2:\n main_menu()\n break\n else:\n n = input('输入有误,重新输入:')\n except:\n pass\n print('\\n' * 10)\n\n# 读取入栈 前标签栈s1 后标签栈s2\ndef read():\n\n # 使用全局声明的栈存取便签对\n global s1, s2\n\n # 正则筛选所有便签\n result = re.findall('?[^><]+>', htmltext)\n\n # 存储剔除空格的结果\n ress = []\n for i in result:\n # 剔除所有空格\n ress.append(i.replace('\\x00',''))\n\n with open('C:\\\\Users\\\\ASUS\\\\Desktop\\\\777.txt', 'a') as ee:\n for i in ress:\n # 剔除便签的内嵌样式\n st = i.replace('\\x00', '').split()\n mid = ''\n if '>' in st[0]:\n str = st.pop()\n if '!' not in str:\n ee.write(str)\n mid = str\n else:\n str = st[0] + '>'\n if '!' not in str:\n ee.write(str)\n mid = str\n if '/' in mid:\n s2.push(mid)\n else:\n s1.push(mid)\n\n\n\n# 标签分堆结果写入文件\ndef write():\n read()\n # 此处使用全局变量\n global s1, s2\n\n # 前标签\n with open('C:\\\\Users\\\\ASUS\\\\Desktop\\\\s1.txt', 'w') as s11:\n for i in s1.stack:\n s11.write(i+'\\n')\n\n # 后标签\n with open('C:\\\\Users\\\\ASUS\\\\Desktop\\\\s2.txt', 'w') as s22:\n for i in s2.stack:\n s22.write(i+'\\n')\n\n\n# 验证操作\ndef opt():\n\n global res\n write()\n t1 = s1.stack\n t2 = s2.stack\n\n for i in range(0,len(t1)):\n if t1[i] in special:\n t1[i] = ''\n\n for i in range(0,len(t2)):\n if t2[i] in special:\n t2[i] = ''\n\n while '' in t1:\n t1.remove('')\n while '' in t2:\n t2.remove('')\n\n for i in range(0,len(t1)):\n for j in range(0,len(t2)):\n if t2[j].replace('/','') == t1[i]:\n t1[i] = ''\n t2[j] = ''\n\n while '' in t1:\n t1.remove('')\n while '' in t2:\n t2.remove('')\n\n # 最终结果\n result = []\n for i in t1:\n result.append(i)\n for i in t2:\n result.append(i)\n\n print('结果-----》(问题标签对:)')\n print(result)\n\n # 结果赋值给去全局结果\n res = result\n return t1,t2\n\n\n# 验证界面\ndef match_menu():\n\n\n r1,r2 = opt()\n print('*---------------------------------------------------- *')\n print('前标签筛选结果:')\n\n if len(r1) == 0:\n print('全部筛出')\n else:\n print(r1)\n\n print('*---------------------------------------------------- *')\n print('后标签筛选结果:')\n\n if len(r2) == 0:\n print('全部筛出')\n else:\n print(r2)\n\n print('*---------------------------------------------------- *')\n print('\\n' * 10)\n\nif __name__ == '__main__':\n main_menu()\n while True:\n key = input(\"请输入你要选择的操作:\")\n if key == 1:\n input_menu()\n elif key == 2:\n match_menu()\n elif str(key) == 'g':\n os._exit(0)\n","sub_path":"datastruct design/htmlTag_match.py","file_name":"htmlTag_match.py","file_ext":"py","file_size_in_byte":6303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"174361972","text":"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport unittest\n\nfrom threatexchange.signal_type import tlsh_pdf\n\nTEST_PDF_COMPLETE_TLSH = (\n \"T145B2859FE708266211A3026277C7AEE5FF76402C636AD5BA2C2CC11C23A1F2957773D5\"\n)\n\n\nclass TLSHHasherModuleUnitTest(unittest.TestCase):\n def test_tlsh_from_file(self):\n tlsh_complete_data_hash = tlsh_pdf.TLSHSignal.hash_from_file(\n \"data/test_pdf_complete.pdf\"\n )\n tlsh_half_data_hash = tlsh_pdf.TLSHSignal.hash_from_file(\n \"data/test_pdf_half.pdf\"\n )\n tlsh_complete_match = tlsh_pdf.TLSHSignal.match_hash(\n self, tlsh_complete_data_hash\n )\n tlsh_half_complete_match = tlsh_pdf.TLSHSignal.match_hash(\n self, tlsh_half_data_hash\n )\n assert tlsh_complete_data_hash == TEST_PDF_COMPLETE_TLSH\n assert tlsh_complete_match != []\n assert tlsh_half_complete_match != []\n","sub_path":"python-threatexchange/threatexchange/signal_type/tests/test_tlsh_hash_and_match.py","file_name":"test_tlsh_hash_and_match.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"540954173","text":"def GrapeOrBanana():\n from sklearn import tree\n a=int(input('\\nenter the weight of the fruit: '))\n b=input('is the Shape is sphere or elliptic cylinder: ')\n d=input('is the color is yellow or green/violet: ')\n if 'sphere' in b:\n c=0\n else:\n c=1\n if 'green' in d:\n e=0\n elif 'violet' in d:\n e=0\n else:\n e=1\n features = [[20, 0, 0],\n [30, 0, 0],\n [40, 0, 0],\n [50, 0, 0],\n [80, 0, 1],\n [90, 1, 1],\n [100, 1, 1],\n [110, 1, 1],\n [120, 1, 1],\n [130, 1, 1]] ##the [#1,#2,#3] #1 is weight ,#2 is shape, #3 is color\n \n labels = [0,0,0,0,1,1,1,1,1,1] #the 0 is apple and 1 is orange\n \n clf = tree.DecisionTreeClassifier()\n clf = clf.fit(features,labels)\n rst = clf.predict([[a, c, e]])\n\n print('\\n +----------------+ ')\n if 0 in rst:\n print(' | its Grapes |')\n else:\n print(' | its Banana |')\n print(' +----------------+ ')\n\n#GrapeOrBanana() \n","sub_path":"Machine Learning/fruits/GrapeOrBanana.py","file_name":"GrapeOrBanana.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"401851688","text":"#!/usr/bin/python3\nimport asyncio\nimport datetime\n\nimport discord\nfrom discord.ext import commands\n\nimport BotFunctions as bf\nimport FuelTracker\nimport FuzzworksFunctions as Fzw\nimport ZkillFunctions as Zkbf\n\n# get token from file\ntokenFile = open('token', 'r')\ntoken = tokenFile.read()\n# strip off any training whitespaces or newlines from end of file\ntoken = token.rstrip()\nbot = commands.Bot(command_prefix='!')\n\nfuel_tracker = FuelTracker.FuelTracker()\n\nonline_time = datetime.datetime.now()\n\n# bot channel ID\nchannel = discord.Object(id='449651065051283476')\n\n\nalertRunning = False\n\n\n@bot.event\nasync def on_ready():\n print('Logged in as')\n print(bot.user.name)\n print(bot.user.id)\n print(bf.roll_out_init())\n print('------')\n\n\n@bot.command()\nasync def ping(ctx):\n await ctx.send(\"pong\")\n\n\n@bot.command()\nasync def upTime(ctx):\n await ctx.send(\"Online for: \" + str(datetime.datetime.now() - online_time))\n\n# zkill related functions\n\n\n@bot.command()\nasync def kills(ctx, *, corp_name):\n await ctx.send(Zkbf.get_corp_current_month_stats(corp_name))\n\n\n@bot.command()\nasync def ships(ctx, amount: int, *, corp_name):\n await ctx.send(Zkbf.get_killer_summary(amount, corp_name))\n\n\n@bot.command()\nasync def stats(ctx, *, corp_name):\n await ctx.send(Zkbf.get_fleet_size_stats(corp_name))\n\n\n@bot.command()\nasync def rankings(ctx):\n await ctx.send(bf.get_ranked_isk_killed())\n\n\n@bot.command()\nasync def intel(ctx, *, corp_name):\n await ctx.send(Zkbf.get_intel(corp_name))\n\n\n@bot.command()\nasync def fit(ctx, ship: str, *, corp):\n await ctx.send(Zkbf.get_last_fit(ship, corp))\n\n\n# market functions\n\n\n@bot.command()\nasync def pc(ctx, *, a):\n await ctx.send(Fzw.get_item_value(a))\n\n\n@bot.command()\nasync def fuel(ctx):\n await ctx.send(Fzw.get_fuel_prices())\n\n# Fuel commands **********************************************\n\n\n@bot.command()\nasync def addStructure(ctx, name: str, consumption):\n await ctx.send(fuel_tracker.add_structure(name, consumption))\n\n\n@bot.command()\nasync def updateStructure(ctx, name: str, consumption):\n await ctx.send(fuel_tracker.update_structure(name, consumption))\n\n\n@bot.command()\nasync def listStructures(ctx):\n await ctx.send(fuel_tracker.list_structures())\n\n\n@bot.command()\nasync def updateFuel(ctx, name: str, amount):\n await ctx.send(fuel_tracker.update_fuel(name, amount))\n\n\n@bot.command()\nasync def fuelReport(ctx):\n await ctx.send(fuel_tracker.fuel_status())\n\n\n# background fuel checker\n@bot.command()\n@commands.has_role(\"Director\")\nasync def fuelAlert(ctx):\n while True:\n\n output = fuel_tracker.fuel_status()\n await ctx.send(output)\n\n now = datetime.datetime.now()\n target_time = datetime.timedelta(microseconds=-now.microsecond,\n seconds=-now.second,\n minutes=-now.minute,\n hours=15 - now.hour)\n if now.hour > 15:\n target_time += datetime.timedelta(days=1)\n\n await asyncio.sleep(target_time.seconds)\n\n# Rollout Tracker ---------------------------------\n\n\n@bot.command()\nasync def rolled(ctx, name: str):\n await ctx.send(bf.update_rolled_out(name))\n\n\n@bot.command()\nasync def lastRolled(ctx):\n await ctx.send(bf.get_rolled_out_date())\n\n\n# ping-command -----------------------------------\n@bot.command()\nasync def batphone(ctx, ping_text):\n target_channel = \"440447527905394689\"\n # await ctx.send(\"Ping Sending\")\n ctx.send_message(discord.Object(id=target_channel), \"@everyone \" + ping_text)\n # await ctx.send(\"Ping Sent\")\n\n\n@bot.event\nasync def on_command_error(ctx, error):\n if isinstance(error, commands.CommandNotFound):\n print(\"Command Not Found\")\n bot.send_message(channel, \"Command Not Found\")\n return\n\n\n\n\nbot.run(token)\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"27028234","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\n\nfrom Model.Attention import Attention\nfrom Model.Decoder import Decoder\nfrom Model.Encoder import Encoder\nfrom Model.Seq2Seq import Seq2Seq\nfrom Utilities.Constants import *\nfrom Utilities.Convert import strings_to_index_tensor\nfrom Utilities.NameDS import NameDataset\n\nBATCH_SZ = 256\nEPOCH = 1000\nPLOT_EVERY = 2\nINPUT_DIM = len(ENCODER_INPUT)\nOUTPUT_DIM = len(DECODER_INPUT)\nEMBED_DIM = 5\nHIDD_DIM = 512\nDROPOUT = 0.5\nCLIP = 1\nLR = 0.005\nSRC_PAD_IDX = ENCODER_INPUT['']\nTRG_PAD_IDX = DECODER_INPUT['']\n\n\ndef plot_losses(loss, folder: str = \"Results\", filename: str = None):\n x = list(range(len(loss)))\n plt.plot(x, loss, 'b--', label=\"Cross Entropy Loss\")\n plt.title(\"Losses\")\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Loss\")\n plt.legend(loc='upper left')\n plt.savefig(f\"{folder}/{filename}\")\n plt.close()\n\n\ndef run_epochs(model: Seq2Seq, iterator: DataLoader, optimizer: torch.optim.Optimizer,\n criterion: torch.nn.CrossEntropyLoss, clip: int):\n total_loss = 0\n all_losses = []\n for i in range(EPOCH):\n loss = train(model, iterator, optimizer, criterion, clip)\n total_loss += loss\n\n if i % PLOT_EVERY == 0:\n all_losses.append(total_loss / PLOT_EVERY)\n plot_losses(all_losses, filename=\"test\")\n\n\ndef train(model: Seq2Seq, iterator: DataLoader, optimizer: torch.optim.Optimizer, criterion: torch.nn.CrossEntropyLoss,\n clip: int):\n model.train()\n epoch_loss = 0\n\n for x in iterator:\n optimizer.zero_grad()\n\n max_len = len(max(x, key=len))\n src, src_len = strings_to_index_tensor(x, max_len, ENCODER_INPUT, SRC_PAD_IDX)\n trg, _ = strings_to_index_tensor(x, max_len, DECODER_INPUT, TRG_PAD_IDX)\n sos_tensor = torch.ones(1, len(x)).type(torch.LongTensor).to(DEVICE) * ENCODER_INPUT['']\n\n output = model(src, src_len, trg, sos_tensor)\n # trg = [trg len, batch size]\n # output = [trg len, batch size, output dim]\n\n output_dim = output.shape[-1]\n output = output[1:].view(-1, output_dim)\n trg = trg[1:].view(-1)\n # trg = [(trg len - 1) * batch size]\n # output = [(trg len - 1) * batch size, output dim]\n\n loss = criterion(output, trg)\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), clip)\n optimizer.step()\n\n return loss.item()\n\n\ndef evaluate(model, iterator, criterion):\n model.eval()\n epoch_loss = 0\n\n with torch.no_grad():\n for i, batch in enumerate(iterator):\n src, src_len = batch.src\n trg = batch.trg\n\n output = model(src, src_len, trg, 0)\n # turn off teacher forcing\n # trg = [trg len, batch size]\n # output = [trg len, batch size, output dim]\n\n output_dim = output.shape[-1]\n output = output[1:].view(-1, output_dim)\n trg = trg[1:].view(-1)\n # trg = [(trg len - 1) * batch size]\n # output = [(trg len - 1) * batch size, output dim]\n\n loss = criterion(output, trg)\n epoch_loss += loss.item()\n\n return epoch_loss / len(iterator)\n\n\ndf = pd.read_csv('Data/first.csv')\nname_ds = NameDataset(df, \"name\")\ndl = DataLoader(name_ds, batch_size=BATCH_SZ, shuffle=True)\n\nattention = Attention(HIDD_DIM, HIDD_DIM)\nencoder = Encoder(INPUT_DIM, EMBED_DIM, HIDD_DIM, HIDD_DIM, DROPOUT)\ndecoder = Decoder(OUTPUT_DIM, EMBED_DIM, HIDD_DIM, HIDD_DIM, DROPOUT, attention)\n\nmodel = Seq2Seq(encoder, decoder, SRC_PAD_IDX, DEVICE).to(DEVICE)\n\noptimizer = optim.Adam(model.parameters(), lr=LR)\ncriterion = nn.CrossEntropyLoss(ignore_index=TRG_PAD_IDX)\n\nrun_epochs(model, dl, optimizer, criterion, CLIP)\n","sub_path":"Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"121417525","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom sqlalchemy import *\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom settings import DATABASE\n\n\nclass ORM(object):\n Base = declarative_base()\n engine = None\n Session = sessionmaker()\n\n @staticmethod\n def init():\n ORM.engine = create_engine(DATABASE)\n ORM.engine.execute(\"select 1\")\n ORM.Base.metadata.create_all(ORM.engine)\n ORM.Session.configure(bind=ORM.engine)\n\n @staticmethod\n def session():\n return ORM.Session()\n\n\nclass File(ORM.Base):\n __tablename__ = 'file'\n id = Column(String, primary_key=True)\n name = Column(String, nullable=False)\n hash = Column(String)\n filesize = Column(BigInteger)\n isdir = Column(Boolean)\n date = Column(DateTime)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"243515685","text":"import socket\nimport http.client\nimport ssl\n#from urllib.request import Request, urlopen\nimport struct\nimport json\nimport base64\n\nclass HashcatAPI(object):\n\n def __init__(self, ip, port, username, password):\n self.ip = ip\n self.port = port\n self.key = base64.b64encode((\"%s:%s\" % (username, password)).encode(\"ascii\")).decode(\"ascii\")\n\n def get_hashcat_info(self):\n return self.send(\"/hashcatInfo\")\n\n def create_rule_session(self, session_name, hash_type_id, rule, wordlist, hashes, username_included):\n payload = {\n \"name\": session_name,\n \"crack_type\": \"rule\",\n \"hash_mode_id\": hash_type_id,\n \"rule\": rule,\n \"wordlist\": wordlist,\n \"hashes\": hashes,\n \"username_included\": username_included,\n }\n\n return self.send(\"/createSession\", data=payload)\n\n def create_mask_session(self, session_name, hash_type_id, mask, hashes, username_included):\n payload = {\n \"name\": session_name,\n \"crack_type\": \"mask\",\n \"hash_mode_id\": hash_type_id,\n \"mask\": mask,\n \"hashes\": hashes,\n \"username_included\": username_included,\n }\n\n return self.send(\"/createSession\", data=payload)\n\n\n def action(self, session_name, action):\n payload = {\n \"session\": session_name,\n \"action\": action,\n }\n\n return self.send(\"/action\", data=payload)\n\n def get_session_info(self, session_name):\n return self.send(\"/sessionInfo/%s\" % session_name)\n\n def remove(self, session_name):\n return self.send(\"/removeSession/%s\" % session_name)\n\n def get_cracked_file(self, session_name):\n return self.send(\"/cracked/%s\" % session_name)\n\n def get_hashcat_output(self, session_name):\n return self.send(\"/hashcatOutput/%s\" % session_name)\n\n def get_hashes(self, session_name):\n return self.send(\"/hashes/%s\" % session_name)\n\n\n def upload_rule(self, name, rule_file):\n payload = {\n \"name\": name,\n \"rules\": rule_file,\n }\n\n return self.send(\"/uploadRule\", data=payload)\n\n def upload_mask(self, name, mask_file):\n payload = {\n \"name\": name,\n \"masks\": mask_file,\n }\n\n return self.send(\"/uploadMask\", data=payload)\n\n def upload_wordlist(self, name, wordlist_file):\n payload = {\n \"name\": name,\n \"wordlists\": wordlist_file,\n }\n\n return self.send(\"/uploadWordlist\", data=payload)\n\n def send(self, url, data=None):\n headers = {\n \"Content-Type\": \"text/plain; charset=utf-8\",\n \"Accept-Encoding\": \"text/plain\",\n \"Authorization\": \"Basic %s\" % self.key,\n }\n\n gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1) # disable certif validation\n conn = http.client.HTTPSConnection(self.ip, self.port, context=gcontext)\n\n if data == None:\n conn.request(\"GET\", url, headers=headers)\n else:\n conn.request(\"POST\", url, \"%s\\r\\n\\r\\n\" % json.dumps(data), headers)\n\n res = conn.getresponse()\n\n data = res.read()\n\n conn.close()\n return json.loads(data.decode(\"ascii\"))\n\n","sub_path":"WebHashcat/Utils/hashcatAPI.py","file_name":"hashcatAPI.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"547965866","text":"# Rects Fight\n\nimport pygame\nimport os\nimport time\nfrom pygame.math import Vector2\n\n\nprint('''\n _ _ _ _ _\n | _ _ |\n | | | | | |\n | |_| |_| |\n | 1.1 |\n |_ _ _ _ _|\n''')\n\n# Init\n\npygame.init()\nscreen = pygame.display.set_mode((500, 500))\nplayarea = pygame.Rect(5, 5, 490, 490)\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\ngrey = (192, 192, 192)\nvel_reset = 0\nvel = 8\nleft_vel = (-8, 0)\nright_vel = (8, 0)\nup_vel = (0, -8)\ndown_vel = (0, 8)\n\n \n# Loading media\n\nbluestage1 = pygame.image.load(os.path.join('media', 'blue1.png')).convert_alpha()\nbluestage2 = pygame.image.load(os.path.join('media', 'blue2.png')).convert_alpha()\nbluestage3 = pygame.image.load(os.path.join('media', 'blue3.png')).convert_alpha()\norangestage1 = pygame.image.load(os.path.join('media', 'orange1.png')).convert_alpha()\norangestage2 = pygame.image.load(os.path.join('media', 'orange2.png')).convert_alpha()\norangestage3 = pygame.image.load(os.path.join('media', 'orange3.png')).convert_alpha()\nbluebullet = pygame.image.load(os.path.join('media', 'bulletblue.png')).convert_alpha()\norangebullet = pygame.image.load(os.path.join('media', 'bulletorange.png')).convert_alpha()\nstartlogo = pygame.image.load(os.path.join('media', 'startscreen.png')).convert_alpha()\npausescreen = pygame.image.load(os.path.join('media', 'paused.png')).convert_alpha()\nwindowicon = pygame.image.load(os.path.join('media', 'icon.png')).convert_alpha()\n\npausesound = pygame.mixer.Sound(os.path.join('media', 'pause.wav'))\nshootsound = pygame.mixer.Sound(os.path.join('media', 'shoot.wav'))\nhitsound = pygame.mixer.Sound(os.path.join('media', 'hit.wav'))\ndiesound = pygame.mixer.Sound(os.path.join('media', 'die.wav'))\nfightsound = pygame.mixer.Sound(os.path.join('media', 'fight.wav'))\n\npygame.display.set_caption('Rects Fight!')\npygame.display.set_icon(windowicon)\n \n# Player Sprite\n\nclass Player(pygame.sprite.Sprite):\n\n def __init__(self, pos, enemy_bullets, image, *groups):\n\n super().__init__(*groups)\n\n self.image = image\n self.rect = self.image.get_rect(center=pos)\n self.vel = Vector2(0, 0)\n self.pos = Vector2(pos)\n self.fire_direction = (8, 0)\n self.health = 3\n self.enemy_bullets = enemy_bullets\n self.toggle = False\n\n # Checking for collisions\n \n def update(self):\n self.pos += self.vel\n self.rect.center = self.pos\n self.rect.clamp_ip(playarea)\n \n collided_bullets = pygame.sprite.spritecollide(self, self.enemy_bullets, True)\n for bullet in collided_bullets:\n self.health -= 1\n hitsound.play()\n if self.health <= 0:\n self.kill()\n self.toggle = True\n diesound.play()\n \n# Bullet Sprite\n\nclass Bullet(pygame.sprite.Sprite):\n\n def __init__(self, pos, vel, image):\n\n super().__init__()\n\n self.image = image\n self.rect = self.image.get_rect(center=pos)\n self.pos = pos\n self.vel = vel\n self.toggle = False\n\n def update(self):\n if self.toggle == False:\n self.pos += self.vel\n self.rect.center = self.pos\n \n if not playarea.contains(self):\n self.kill()\n\n def stop(self):\n self.toggle = True\n\n def start(self):\n self.toggle = False\n \n# Start Screen\n\ndef start():\n startScreen=False\n pygame.display.set_caption('Rects Fight!')\n \n while startScreen == False:\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n \n if event.type == pygame.KEYDOWN:\n\n if event.key == pygame.K_SPACE: \n startScreen = True\n elif event.key == pygame.K_ESCAPE:\n pygame.quit()\n \n screen.fill(black) \n screen.blit(startlogo, (0, 0))\n \n pygame.display.flip()\n\n# ----- Main Game -----\ndef main():\n \n # Defining Variables\n \n screen = pygame.display.set_mode((500, 500))\n clock = pygame.time.Clock()\n all_sprites = pygame.sprite.Group()\n bullets1 = pygame.sprite.Group()\n bullets2 = pygame.sprite.Group()\n player1 = Player((35, 35), bullets2, bluestage1, all_sprites)\n player2 = Player((465, 465), bullets1, orangestage1, all_sprites)\n confirm = False\n onStart = True\n loop = True\n\n \n# ---- Game loop -----\n while loop:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n loop = False\n # Keymap \n if event.type == pygame.KEYDOWN:\n\n # Player 1 Shooting\n \n if event.key == pygame.K_e and player1.toggle == False:\n bullet = Bullet(player1.rect.center, Vector2(player1.fire_direction), bluebullet)\n shootsound.play()\n bullets1.add(bullet)\n all_sprites.add(bullet)\n \n # Player 2 Shooting\n \n if event.key == pygame.K_SPACE and player2.toggle == False:\n bullet = Bullet(player2.rect.center, Vector2(player2.fire_direction), orangebullet)\n shootsound.play()\n bullets2.add(bullet)\n all_sprites.add(bullet)\n\n # Player 1 Movement\n\n if event.key == pygame.K_d and player1.toggle == False:\n player1.vel.x = 5\n player1.fire_direction = (vel, 0)\n\n if event.key == pygame.K_a and player1.toggle == False:\n player1.vel.x = -5\n player1.fire_direction = (-vel, 0)\n \n if event.key == pygame.K_s and player1.toggle == False:\n player1.vel.y = 5\n player1.fire_direction = (0, vel)\n\n if event.key == pygame.K_w and player1.toggle == False:\n player1.vel.y = -5\n player1.fire_direction = (0, -vel)\n \n # Player 2 Movement\n \n if event.key == pygame.K_RIGHT and player2.toggle == False:\n player2.vel.x = 5\n player2.fire_direction = (vel, 0)\n\n if event.key == pygame.K_LEFT and player2.toggle == False:\n player2.vel.x = -5\n player2.fire_direction = (-vel, 0)\n\n if event.key == pygame.K_DOWN and player2.toggle == False:\n player2.vel.y = 5\n player2.fire_direction = (0, vel)\n\n if event.key == pygame.K_UP and player2.toggle == False:\n player2.vel.y = -5\n player2.fire_direction = (0, -vel)\n\n # Toggling off movement\n if event.type == pygame.KEYUP:\n\n # Player 1 Toggles\n\n if event.key == pygame.K_d:\n player1.vel.x = vel_reset\n\n if event.key == pygame.K_a:\n player1.vel.x = vel_reset\n\n if event.key == pygame.K_s:\n player1.vel.y = vel_reset\n\n if event.key == pygame.K_w:\n player1.vel.y = vel_reset\n\n # Player 2 Toggles\n\n if event.key == pygame.K_RIGHT:\n player2.vel.x = vel_reset\n\n if event.key == pygame.K_LEFT:\n player2.vel.x = vel_reset\n\n if event.key == pygame.K_DOWN:\n player2.vel.y = vel_reset\n\n if event.key == pygame.K_UP:\n player2.vel.y = vel_reset\n \n # Main Game Logic\n \n if onStart == True:\n fightsound.play()\n onStart = False\n \n keys = pygame.key.get_pressed()\n\n if keys[pygame.K_TAB] and confirm == False:\n pausesound.play()\n player1.toggle = True\n player2.toggle = True\n confirm = True\n for bullet in bullets1:\n bullet.stop()\n \n for bullet in bullets2:\n bullet.stop()\n \n if keys[pygame.K_ESCAPE] and confirm == True:\n loop = False\n \n elif keys[pygame.K_LSHIFT] and confirm == True:\n confirm = False\n player1.toggle = False\n player2.toggle = False\n for bullet in bullets1:\n bullet.start()\n \n for bullet in bullets2:\n bullet.start()\n\n if player1.health == 2:\n player1.image = bluestage2\n \n elif player1.health == 1:\n player1.image = bluestage3\n \n elif player1.health == 0:\n pygame.display.set_caption('Orange Wins!')\n \n if keys[pygame.K_ESCAPE] and confirm == False:\n loop = False\n\n if player2.health == 2:\n player2.image = orangestage2\n \n elif player2.health == 1:\n player2.image = orangestage3\n \n elif player2.health == 0: \n pygame.display.set_caption('Blue Wins!') \n \n if keys[pygame.K_ESCAPE] and confirm == False:\n loop = False \n\n if player1.health == 0 and player2.health == 0:\n pygame.display.set_caption('They destroyed eachother!')\n \n # Drawing Code\n \n all_sprites.update()\n screen.fill(black)\n if confirm == True:\n screen.blit(pausescreen, (145, 210))\n \n pygame.draw.rect(screen, grey, pygame.Rect(0, 0, 500, 5))\n pygame.draw.rect(screen, grey, pygame.Rect(0, 0, 5, 500))\n pygame.draw.rect(screen, grey, pygame.Rect(0, 495, 500, 5))\n pygame.draw.rect(screen, grey, pygame.Rect(495, 0, 5, 500))\n all_sprites.draw(screen)\n \n pygame.display.flip()\n clock.tick(60)\n \n# Game Sequence\n\nif __name__ == '__main__':\n start()\n main()\n pygame.quit()\n\n# ~SnivyDroid\n\n\n \n \n","sub_path":"Rects Fight Archive/Rects Fight + Python install/Rects Fight! 1.1/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":10297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"351909992","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\n\r\nhits = np.genfromtxt('hitmap.txt', unpack=True)\r\nkanal = np.arange(1, 129,1)\r\n\r\nprint(hits)\r\nprint(kanal)\r\n\r\nplt.bar(kanal, hits, color='mediumslateblue')\r\nplt.xlabel(r'Kanalnummer')\r\nplt.ylabel(r'Häufigkeit')\r\nplt.yscale('log')\r\nplt.xlim(0,129)\r\nplt.savefig('hitmap.pdf')\r\n","sub_path":"Si_Streifensensor/plots/Grosser_Quellenscan/hitmap.py","file_name":"hitmap.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"172388033","text":"import numpy as np\nimport gym\nfrom nuro_arm import RobotArm\n\n\nclass GridWorldEnv(gym.Env):\n def __init__(self,\n mode='sim',\n n_grids=10,\n seed=None,\n ):\n self.seed(seed)\n\n self.n_grids = n_grids\n self.observation_space = gym.spaces.Box(0, n_grids, (2,), dtype=int)\n\n self.robot = RobotArm(mode)\n\n x_range = np.linspace(0.1, 0.3, self.n_grids)\n y_range = np.linspace(-0.1, 0.1, self.n_grids)\n z_val = 0.05\n self.grid_positions = np.dstack(np.meshgrid(x_range, y_range, [z_val]))\n\n # move in cardinal directions and noop\n self.action_deltas = ((0, 0), (1, 0), (0, 1), (-1, 0), (0, 1))\n self.action_space = gym.spaces.Discrete(5)\n\n self.goal = np.array((self.n_grids-1, self.n_grids-1))\n\n def reset(self):\n self.state = np.array((1, 1))\n\n return self.get_obs()\n\n def step(self, a):\n assert self.action_space.contains(a)\n\n new_state = np.add(self.state, self.action_deltas[a])\n self.state = np.clip(new_state, 0, self.n_grids-1)\n\n self.move_hand_to_state(self.state)\n\n obs = self.get_obs()\n reward = (self.state == self.goal).all()\n done = reward\n info = {}\n\n return obs, reward, done, info\n\n def get_obs(self):\n return self.state.copy()\n\n def move_hand_to_state(self, state):\n pos = self.grid_positions[state[0], state[1]]\n self.robot.move_hand_to(pos)\n\n","sub_path":"nuro_arm/examples/gym_envs/grid_world_env.py","file_name":"grid_world_env.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"385819576","text":"from utils.data_util import load_ml_1m\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nfrom utils.data_util import build_dictionary, extract_test_df\nfrom CF.CF_model import cal_item_similarity,cal_user_similarity,UserCF_prediction,ItemCF_prediction\nfrom sklearn.metrics import mean_squared_error\n\n\ndef predict(test_user_id_list, test_item_id_list, test_rating_list, CF_F,\n item_user_dic, user_item_dic, item_map_dic,similarity,user_item_matrix_np,k_num_list):\n loss_list = []\n for K in tqdm(k_num_list):\n pred_rating_list = []\n for num in range(len(test_user_id_list)): # (2:41,k=3) (1:11与1:03)\n pred_rating_list.append(CF_F(test_user_id_list[num],\n test_item_id_list[num],\n item_user_dic, user_item_dic,\n item_map_dic,\n similarity,\n user_item_matrix_np,\n K_num=K))\n MSE_loss = mean_squared_error(test_rating_list, pred_rating_list)\n loss_list.append(MSE_loss)\n return loss_list\n\n\nif __name__ == \"__main__\":\n path = './data/'\n train_df = pd.read_csv(path + 'train_df.csv')\n test_df = pd.read_csv(path + 'test_df.csv')\n user_item_matrix = pd.read_csv(path + 'user_item_matrix.csv')\n user_item_matrix_np = user_item_matrix.values\n user_item_dic, item_user_dic = build_dictionary(train_df)\n test_user_id_list, test_item_id_list, test_rating_list = extract_test_df(test_df)\n item_id_list = user_item_matrix.columns\n item_map_dic = {} # 用于用户评分矩阵是无序的,建立item_id-->index的映射\n for i, col_id in enumerate(item_id_list):\n item_map_dic[int(col_id)] = i\n\n user_similarity = cal_user_similarity(user_item_dic,item_user_dic,user_item_matrix)\n item_similarity = cal_item_similarity(user_item_dic, item_user_dic, user_item_matrix, item_map_dic)\n print(user_similarity.shape)\n print(item_similarity.shape)\n k_num_list = [5,10,15,20,25,30,45] # 最为相似的用户/物品数目K\n MSE_list_user = predict(test_user_id_list, test_item_id_list, test_rating_list, UserCF_prediction,\n item_user_dic, user_item_dic, item_map_dic,\n user_similarity, user_item_matrix_np,\n k_num_list)\n MSE_list_item = predict(test_user_id_list, test_item_id_list, test_rating_list, ItemCF_prediction,\n item_user_dic, user_item_dic, item_map_dic,\n item_similarity, user_item_matrix_np,\n k_num_list)\n print(\"User CF MSE:\")\n print(MSE_list_user)\n print(\"Item CF MSE:\")\n print(MSE_list_item)","sub_path":"recommend_system_homework/01_UserCF_ItemCF_MF/CF_MF_homework/CF_test.py","file_name":"CF_test.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"453375323","text":"import os\nfrom PySide import QtCore, QtGui\nfrom BrowseTasks import Ui_BrowseTasks\nimport ftrack\ntry:\n from ftrackplugin.ftrackConnector import HelpFunctions\nexcept:\n pass\n\n\nclass BrowseTasksItem(QtGui.QStandardItem):\n def __init__(self, text, version=False):\n QtGui.QStandardItem.__init__(self, text)\n self.version = version\n\n def __lt__(self, other):\n if self.version:\n return QtGui.QStandardItem.__lt__(self, other)\n else:\n return QtGui.QStandardItem.__lt__(self, other)\n\n\nclass BrowseTasksWidget(QtGui.QWidget):\n clickedIdSignal = QtCore.Signal(str, name='clickedIdSignal')\n\n def __init__(self, parent, task=None, startId=None, browseMode='Shot'):\n QtGui.QWidget.__init__(self, parent)\n self.ui = Ui_BrowseTasks()\n self.ui.setupUi(self)\n self.parentIds = []\n\n self.browseMode = browseMode\n self.showShots = True\n\n self.currentPath = None\n\n if startId:\n self.startId = startId\n self.setStartId(startId)\n else:\n self.startId = None\n\n self.ui.horizontalLayout.setContentsMargins(0, 0, 0, 0)\n self.ui.verticalLayout.setContentsMargins(0, 0, 0, 0)\n self.currentId = None\n \n self.ui.BrowseTasksViewModel = QtGui.QStandardItemModel()\n\n self.ui.BrowseTasksSelectionModel = QtGui.QItemSelectionModel(self.ui.BrowseTasksViewModel)\n\n self.ui.BrowseProjectComboBoxModel = QtGui.QStandardItemModel()\n self.ui.BrowseProjectComboBox.setModel(self.ui.BrowseProjectComboBoxModel)\n\n itemProjCombo = BrowseTasksItem('Show All')\n itemProjCombo.id = ''\n itemProjCombo.type = 'show'\n\n self.ui.BrowseProjectComboBoxModel.appendRow(itemProjCombo)\n\n projects = ftrack.getProjects()\n filterOnThis = ''\n projects = sorted(projects, key=lambda a: a.getName().lower())\n for proj in projects:\n projName = '[' + proj.getName() + '] ' + proj.getFullName()\n projId = proj.getId()\n projType = 'show'\n\n itemProj = BrowseTasksItem(projName)\n itemProj.id = projId\n itemProj.type = projType\n\n self.ui.BrowseTasksViewModel.appendRow(itemProj)\n\n itemProjCombo = BrowseTasksItem(projName)\n itemProjCombo.id = projId\n itemProjCombo.type = projType\n\n self.ui.BrowseProjectComboBoxModel.appendRow(itemProjCombo)\n\n shot = ftrack.Task(os.environ['FTRACK_SHOTID'])\n proj_root = shot.getProject().getName()\n\n if proj_root == proj.getName():\n self.ui.BrowseProjectComboBox.setCurrentIndex(self.ui.BrowseProjectComboBoxModel.rowCount() - 1)\n filterOnThis = projName\n\n self.setProjectFilter(filterOnThis)\n\n self.ui.BrowseTasksTreeView.setModel(self.ui.BrowseTasksViewModel)\n self.ui.BrowseTasksTreeView.setSelectionModel(self.ui.BrowseTasksSelectionModel)\n self.ui.BrowseTasksTreeView.setSortingEnabled(False)\n \n if startId:\n self.currentId = startId\n\n @QtCore.Slot(QtCore.QModelIndex, bool)\n def updateAssetView(self, modelindex, updateCurrentPath=True):\n clickedItem = self.ui.BrowseTasksViewModel.itemFromIndex(modelindex)\n expand = None\n select = None\n \n if clickedItem.type == 'show':\n clickedTask = ftrack.Project(clickedItem.id)\n elif clickedItem.type == 'task':\n clickedTask = ftrack.Task(clickedItem.id)\n elif clickedItem.type == 'asset':\n clickedTask = ftrack.Asset(clickedItem.id)\n elif clickedItem.type == 'asset_version':\n clickedTask = ftrack.AssetVersion(clickedItem.id)\n elif clickedItem.type == 'assettake':\n clickedTask = ftrack.Component(clickedItem.id)\n else:\n pass\n try:\n clickedObjectType = clickedTask.getObjectType()\n except:\n clickedObjectType = 'Unset'\n\n if not clickedItem.hasChildren():\n childList = []\n\n if clickedItem.type in ['show', 'task']:\n if clickedObjectType != 'Sequence' or self.showShots:\n children = clickedTask.getChildren()\n\n expand, select, expandItem, selectItem, retchildList = self.getTreeChildren(clickedItem, children)\n childList += retchildList\n\n if self.browseMode == 'Task':\n tasks = clickedTask.getTasks()\n expandTask, selectTask, expandItemTask, selectItemTask, retchildList = self.getTreeChildren(clickedItem, tasks)\n childList += retchildList\n\n if not expand:\n expandItem = expandItemTask\n expand = expandTask\n\n if not select:\n selectItem = selectItemTask\n select = selectTask\n\n if len(childList) > 0:\n sortedchildlist = sorted(childList, key=lambda a: a.text().lower())\n clickedItem.appendColumn(sortedchildlist)\n\n self.ui.BrowseTasksTreeView.setModel(self.ui.BrowseTasksViewModel)\n self.ui.BrowseTasksTreeView.expand(modelindex)\n\n self.currentId = clickedItem.id\n if expand:\n self.updateAssetView(self.ui.BrowseTasksViewModel.indexFromItem(expandItem))\n elif select:\n sortIndex = self.ui.BrowseTasksViewModel.indexFromItem(selectItem)\n self.ui.BrowseTasksSelectionModel.select(sortIndex, QtGui.QItemSelectionModel.Clear | QtGui.QItemSelectionModel.Select)\n self.currentId = self.startId\n self.clickedIdSignal.emit(self.startId)\n task = ftrack.Task(self.startId)\n self.currentPath = HelpFunctions.getPath(task)\n else:\n if updateCurrentPath==True:\n self.currentPath = HelpFunctions.getPath(clickedTask)\n self.clickedIdSignal.emit(clickedItem.id)\n\n def getTreeChildren(self, clickedItem, children):\n expand = None\n select = None\n expandItem = None\n selectItem = None\n childList = []\n if len(children) > 0:\n childList = list()\n for child in children:\n if clickedItem.type == 'asset':\n childName = 'v' + str(child.getVersion()).zfill(4)\n else:\n childName = child.getName()\n if childName == '':\n continue\n itemChild = BrowseTasksItem(childName)\n itemChild.id = child.getId()\n\n try:\n itemChild.type = child.get('entityType')\n except:\n itemChild.type = 'asset_version'\n itemChild.version = True\n if itemChild.id != clickedItem.id:\n childList.append(itemChild)\n if itemChild.id in self.parentIds:\n expand = itemChild.id\n expandItem = itemChild\n elif itemChild.id == self.startId:\n select = itemChild.id\n selectItem = itemChild\n return expand, select, expandItem, selectItem, childList\n\n @QtCore.Slot(str)\n def setProjectFilter(self, projectfilter):\n if projectfilter == 'Show All':\n projectfilter = ''\n\n rowCount = self.ui.BrowseTasksViewModel.rowCount()\n for i in range(rowCount):\n tableItem = self.ui.BrowseTasksViewModel.item(i, 0)\n rootItem = self.ui.BrowseTasksViewModel.invisibleRootItem().index()\n #print tableItem.text().encode('ascii', 'ignore')\n if projectfilter not in tableItem.text():\n showMe = True\n else:\n showMe = False\n self.ui.BrowseTasksTreeView.setRowHidden(i, rootItem, showMe)\n\n #self.ui.BrowseTasksSortModel.setFilterFixedString(projectfilter)\n foundItems = self.ui.BrowseTasksViewModel.findItems(projectfilter)\n if len(foundItems) > 0:\n for item in foundItems:\n #self.updateAssetView(self.ui.BrowseTasksSortModel.mapFromSource(item.index()))\n self.updateAssetView(item.index(), updateCurrentPath=False)\n\n def getCurrentId(self):\n return self.currentId\n\n def getCurrentPath(self):\n return self.currentPath\n try:\n task = ftrack.Task(self.currentId)\n shotpath = task.getName()\n taskParents = task.getParents()\n\n for parent in taskParents:\n shotpath = parent.getName() + '.' + shotpath\n\n self.currentPath = shotpath\n return self.currentPath\n except:\n return None\n\n def setStartId(self, fid):\n shot = ftrack.Task(fid)\n parents = shot.getParents()\n self.parentIds = [x.getId() for x in parents]\n\n def setShowTasks(self, val):\n if val == True:\n self.browseMode = 'Task'\n else:\n self.browseMode = 'Shot'\n\n def setShowShots(self, val):\n self.showShots = val\n","sub_path":"linux/ftrack-connect-package/resource/legacy_plugins/ftrackplugin/ftrackWidgets/BrowseTasksWidget.py","file_name":"BrowseTasksWidget.py","file_ext":"py","file_size_in_byte":9269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"133020189","text":"import numpy as np\nimport matplotlib.pyplot as plt\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\n\nb = -120\nw = -4\n\nlr = 1\niteration = 100000\n\nb_history=[b]\nw_history=[w]\n\nlr_b = 0\nlr_w = 0\n\nfor i in range(iteration):\n\tb_grad = 0.0\n\tw_grad = 0.0\n\tfor i in range(len(x_data)):\n\t\tb_grad = b_grad - 2.0*(y_data[i] - b - w*x_data[i])*1.0\n\t\tw_grad = w_grad - 2.0*(y_data[i] - b - w*x_data[i])*x_data[i]\n\n\tlr_b = lr_b + b_grad ** 2\n\tlr_w = lr_w + w_grad **2\n\n\tb = b - lr/np.sqrt(lr_b)*b_grad\n\tw = w - lr/np.sqrt(lr_w)*w_grad\n\n\tb_history.append(b)\n\tw_history.append(w)\n\nprint(b, w)\nplt.plot(range(iteration+1), b_history, 'r--',range(iteration+1), w_history, 'b')\nplt.show()\n","sub_path":"LHY-ML/demo-1.py","file_name":"demo-1.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"329582","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass DoingMath:\n\t\n\tdef __init__(self, h=None, g=None, m=None, b=None, l=None, ampl=None, p=1, w=None, fi0=None):\n\t\tself.h = h\n\t\tself.t = np.arange(0, 5, self.h)\n\t\tself.fi = np.zeros(1)\n\t\tself.u = np.zeros(1) # u = fi'\n\t\tself.sigM = np.zeros(self.t.shape) # moment napedowy silnika\n\t\t\n\t\tself.fi0 = fi0\n\t\tself.w = w\n\t\tself.ampl = ampl\n\t\tself.p = p\n\t\tself.m = m\n\t\tself.g = g\n\t\tself.b = b\n\t\tself.l = l\n\t\tself.I = None\n\t\n\tdef square_signal(self):\n\t\tx = []\n\t\t\n\t\tsize = int(self.t.shape[0])\n\t\tsamples = int(self.p / self.h)\n\t\tflag = True\n\t\tcount = 0\n\t\twhile True:\n\t\t\tif size <= 0:\n\t\t\t\tbreak\n\t\t\tif (count == int(self.t.shape[0])):\n\t\t\t\tbreak\n\t\t\tif self.w == 1:\n\t\t\t\tx.append(self.ampl)\n\t\t\t\tcount += 1\n\t\t\t\tsize -= 1\n\t\t\telif self.w == 0:\n\t\t\t\tx.append(0)\n\t\t\t\tcount += 1\n\t\t\t\tsize -= 1\n\t\t\telif flag:\n\t\t\t\tfor i in range(int(self.w * samples)):\n\t\t\t\t\tif (count == int(self.t.shape[0])):\n\t\t\t\t\t\tbreak\n\t\t\t\t\tx.append(self.ampl)\n\t\t\t\t\tcount += 1\n\t\t\t\tflag = False\n\t\t\t\tsize -= int(self.w * samples)\n\t\t\telse:\n\t\t\t\tfor i in range(int((1 - self.w) * samples)):\n\t\t\t\t\tif (count == int(self.t.shape[0])):\n\t\t\t\t\t\tbreak\n\t\t\t\t\tx.append(0)\n\t\t\t\t\tcount += 1\n\t\t\t\tflag = True\n\t\t\t\tsize -= int((1 - self.w) * samples)\n\t\t\n\t\treturn x\n\t\n\tdef triangle_signal(self):\n\t\tx = np.zeros(self.t.shape)\n\t\tfor i in range(1, 99, 2):\n\t\t\tfor a, b in enumerate(self.t):\n\t\t\t\tx[a] += self.ampl * (8 / pow(np.pi, 2)) * (pow(-1, (i - 1) / 2) / pow(i, 2)) * np.sin(\n\t\t\t\t\t2 * np.pi * i * b / self.p)\n\t\t\n\t\treturn x\n\t\n\tdef sinusoid_signal(self):\n\t\tx = np.zeros(self.t.shape)\n\t\tfor i, j in enumerate(self.t):\n\t\t\tx[i] = self.ampl * np.sin(2 * np.pi * j / self.p)\n\t\t\n\t\treturn x\n\t\n\tdef calculate(self):\n\t\tself.I = 1 / 3 * self.m * pow(self.l, 2)\n\t\tself.fi = np.zeros(self.t.shape)\n\t\tself.u = np.zeros(self.t.shape)\n\t\tself.fi[0] = self.fi0\n\t\tfor i, j in enumerate(self.t): # i - indeksy, j - czasy\n\t\t\tk1 = self.h * self.u[i]\n\t\t\tq1 = self.h * self.func(self.I, self.b, self.m, self.g, self.l, self.sigM[i], 0, 0, self.fi[i], self.u[i])\n\t\t\tk2 = self.h * (self.u[i] + q1 / 2)\n\t\t\tq2 = self.h * self.func(self.I, self.b, self.m, self.g, self.l, self.sigM[i], k1 / 2, q1 / 2, self.fi[i],\n\t\t\t\t\t\t\t\t\tself.u[i])\n\t\t\tk3 = self.h * (self.u[i] + q2 / 2)\n\t\t\tq3 = self.h * self.func(self.I, self.b, self.m, self.g, self.l, self.sigM[i], k2 / 2, q2 / 2, self.fi[i],\n\t\t\t\t\t\t\t\t\tself.u[i])\n\t\t\tk4 = self.h * (self.u[i] + q3)\n\t\t\tq4 = self.h * self.func(self.I, self.b, self.m, self.g, self.l, self.sigM[i], k3, q3, self.fi[i], self.u[i])\n\t\t\t\n\t\t\tif i < len(self.t) - 1:\n\t\t\t\tself.fi[i + 1] = self.fi[i] + 1 / 6 * (k1 + 2 * k2 + 2 * k3 + k4)\n\t\t\t\tif self.fi[i + 1] > 360:\n\t\t\t\t\tself.fi[i + 1] -= 360\n\t\t\t\telif self.fi[i + 1] < -360:\n\t\t\t\t\tself.fi[i + 1] += 360\n\t\t\t\tself.u[i + 1] = self.u[i] + 1 / 6 * (q1 + 2 * q2 + 2 * q3 + q4)\n\t\n\tdef func(self, I, b, m, g, l, sigM, k, q, fi, u):\n\t\treturn (-sigM - b * (u + q) + m * g * l / 2 * np.sin((fi + k) * np.pi / 180)) / I\n\t\n\n\t\n\tdef get_output(self):\n\t\treturn self.fi","sub_path":"DoMath.py","file_name":"DoMath.py","file_ext":"py","file_size_in_byte":2962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"633550521","text":"from django.db import models\nfrom django.utils import timezone\nimport datetime\nfrom dateutil.relativedelta import relativedelta\n\n# レッスンのオブジェクト\nclass Lesson(models.Model):\n\n GENRE_CHOICES = (\n (1, '英語'),\n (2, 'ファイナンス'),\n (3, 'プログラミング'),\n )\n\n genre = models.IntegerField(verbose_name='ジャンル', choices=GENRE_CHOICES, blank=True, null=True)\n charge = models.CharField(max_length=200, verbose_name='基本料金')\n usage_fee = models.CharField(max_length=200, verbose_name='従量料金')\n\n def __int__(self):\n return self.genre\n\n def get_lesson_history(self):\n today = datetime.date.today()\n first_of_thismonth = today + relativedelta(day=1)\n nextmonth = today + relativedelta(months=1)\n end_of_thismonth = nextmonth + relativedelta(day=1)\n\n eng_m = []\n eng_w = []\n eng_m_unique_customer = []\n eng_w_unique_customer = []\n finance_m = []\n finance_w = []\n finance_m_unique_customer = []\n finance_w_unique_customer = []\n programing_m = []\n programing_w = []\n programing_m_unique_customer = []\n programing_w_unique_customer = []\n unique = []\n zenbu = []\n test = []\n zenbu = []\n price = []\n i = 0\n while i < 24:\n first_of_Nmonth_ago = first_of_thismonth - relativedelta(months=i)\n next_Nmonth = first_of_thismonth - relativedelta(months=(i-1))\n end_of_Nmonth_ago = next_Nmonth - relativedelta(days=1)\n lesson_per_month = Lesson_history.objects.filter(date__range=(first_of_Nmonth_ago, end_of_Nmonth_ago)) # 月毎の受講データを取得\n\n em_price = 0\n ew_price = 0\n fm_price = 0\n fw_price = 0\n pm_price = 0\n pw_price = 0\n\n for history in lesson_per_month:\n if history.lesson.genre == 1: # 英語の受講者\n if history.customer.gender == 1: # 英語を受講する男\n eng_m.append(history)\n eng_m_unique_customer.append(history.customer)\n fee = history.calculate_price()\n em_price += fee\n elif history.customer.gender == 2: # 英語を受講する女\n eng_w.append(history)\n eng_w_unique_customer.append(history.customer)\n fee = history.calculate_price()\n ew_price += fee\n\n elif history.lesson.genre == 2: # ファイナンスの受講者\n if history.customer.gender == 1: # ファイナンスを受講する男\n finance_m.append(history)\n finance_m_unique_customer.append(history.customer)\n fee = history.calculate_price()\n fm_price += fee\n elif history.customer.gender == 2: # ファイナンスを受講する女\n finance_w.append(history)\n finance_w_unique_customer.append(history.customer)\n fee = history.calculate_price()\n fw_price += fee\n\n elif history.lesson.genre == 3: # プログラミングを受講者\n if history.customer.gender == 1: # プログラミングを受講する男\n programing_m.append(history)\n programing_m_unique_customer.append(history.customer)\n fee = history.calculate_price()\n pm_price += fee\n elif history.customer.gender == 2: # プログラミングを受講する女\n programing_w.append(history)\n programing_w_unique_customer.append(history.customer)\n fee = history.calculate_price()\n pw_price += fee\n\n zenbu.append(((eng_m, eng_w), (finance_m, finance_w), (programing_m, programing_w)))\n price.append(((em_price, ew_price), (fm_price, fw_price), (pm_price, pw_price)))\n\n eng_m_unique_customer = list(set(eng_m_unique_customer))\n eng_w_unique_customer = list(set(eng_w_unique_customer))\n finance_m_unique_customer = list(set(finance_m_unique_customer))\n finance_w_unique_customer = list(set(finance_w_unique_customer))\n programing_m_unique_customer = list(set(programing_m_unique_customer))\n programing_w_unique_customer = list(set(programing_w_unique_customer))\n\n unique.append(((eng_m_unique_customer, eng_w_unique_customer), (finance_m_unique_customer, finance_w_unique_customer), (programing_m_unique_customer, programing_w_unique_customer)))\n\n test.append((first_of_Nmonth_ago, zenbu, unique, price))\n\n eng_m = []\n eng_w = []\n finance_m = []\n finance_w = []\n programing_m = []\n programing_w = []\n eng_m_unique_customer = []\n eng_w_unique_customer = []\n finance_m_unique_customer = []\n finance_w_unique_customer = []\n programing_m_unique_customer = []\n programing_w_unique_customer = []\n zenbu = []\n unique = []\n price = []\n\n i += 1\n return test\n\n\n# 顧客のオブジェクト\nclass Customer(models.Model):\n\n GENDER_CHOICES = (\n (1, '男'),\n (2, '女'),\n (3, 'その他'),\n )\n name = models.CharField(max_length=255, verbose_name='名前')\n gender = models.IntegerField(verbose_name='性別', choices=GENDER_CHOICES, blank=True, null=True)\n age = models.CharField(max_length=200, verbose_name='年齢')\n\n def __str__(self):\n return self.name\n\n def getLessonHistory(self): # 受講履歴を取得\n today = datetime.date.today()\n first_of_thismonth = today + relativedelta(day=1)\n first_of_onemonth_ago = first_of_thismonth - relativedelta(months=1)\n first_of_twomonth_ago = first_of_thismonth - relativedelta(months=2)\n first_of_threemonth_ago = first_of_thismonth - relativedelta(months=3)\n nextmonth = today + relativedelta(months=1)\n end_of_thismonth = nextmonth + relativedelta(day=1)\n end_of_onemonth_ago = first_of_thismonth - relativedelta(days=1)\n end_of_twomonth_ago = first_of_onemonth_ago - relativedelta(days=1)\n end_of_threemonth_ago = first_of_twomonth_ago - relativedelta(days=1)\n\n thismonth_lesson = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_thismonth, end_of_thismonth))\n onemonth_ago_lesson = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_onemonth_ago, end_of_onemonth_ago))\n twomonth_ago_lesson = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_twomonth_ago, end_of_twomonth_ago))\n threemonth_ago_lesson = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_threemonth_ago, end_of_threemonth_ago))\n lesson_history = (thismonth_lesson, onemonth_ago_lesson, twomonth_ago_lesson, threemonth_ago_lesson)\n return lesson_history\n\n def getCountPerLesson(self): # 受講履歴カウント\n today = datetime.date.today()\n first_of_thismonth = today + relativedelta(day=1)\n first_of_onemonth_ago = first_of_thismonth - relativedelta(months=1)\n first_of_twomonth_ago = first_of_thismonth - relativedelta(months=2)\n first_of_threemonth_ago = first_of_thismonth - relativedelta(months=3)\n nextmonth = today + relativedelta(months=1)\n end_of_thismonth = nextmonth + relativedelta(day=1)\n end_of_onemonth_ago = first_of_thismonth - relativedelta(days=1)\n end_of_twomonth_ago = first_of_onemonth_ago - relativedelta(days=1)\n end_of_threemonth_ago = first_of_twomonth_ago - relativedelta(days=1)\n\n thismonth_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_thismonth, end_of_thismonth))\n onemonth_ago_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_onemonth_ago, end_of_onemonth_ago))\n twomonth_ago_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_twomonth_ago, end_of_twomonth_ago))\n threemonth_ago_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_threemonth_ago, end_of_threemonth_ago))\n history_per_month = [thismonth_history, onemonth_ago_history, twomonth_ago_history, threemonth_ago_history] # リストに各月毎のデータを格納\n\n countGenre_per_month = [] # 月毎にジャンルの受講回数をカウントして格納\n for histories in history_per_month:\n english = 0\n finance = 0\n programing = 0\n for history in histories:\n if history.lesson.genre == 1:\n english += 1\n elif history.lesson.genre == 2:\n finance += 1\n elif history.lesson.genre == 3:\n programing += 1\n\n genre_count = []\n if english >= 1:\n genre_count.append('英語(' + str(english) + ')')\n if finance >= 1:\n genre_count.append('ファイナンス(' + str(finance) + ')')\n if programing >= 1:\n genre_count.append('プログラム(' + str(programing) + ')')\n countGenre_per_month.append(genre_count)\n return countGenre_per_month\n\n def calculate_total_price(self): # 請求金額を計算\n today = datetime.date.today()\n first_of_thismonth = today + relativedelta(day=1)\n first_of_onemonth_ago = first_of_thismonth - relativedelta(months=1)\n first_of_twomonth_ago = first_of_thismonth - relativedelta(months=2)\n first_of_threemonth_ago = first_of_thismonth - relativedelta(months=3)\n nextmonth = today + relativedelta(months=1)\n first_of_nextmonth = nextmonth + relativedelta(day=1)\n end_of_thismonth = first_of_nextmonth - relativedelta(days=1)\n end_of_onemonth_ago = first_of_thismonth - relativedelta(days=1)\n end_of_twomonth_ago = first_of_onemonth_ago - relativedelta(days=1)\n end_of_threemonth_ago = first_of_twomonth_ago - relativedelta(days=1)\n\n thismonth_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_thismonth, end_of_thismonth))\n onemonth_ago_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_onemonth_ago, end_of_onemonth_ago))\n twomonth_ago_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_twomonth_ago, end_of_twomonth_ago))\n threemonth_ago_history = Lesson_history.objects.filter(customer=self.id, date__range=(first_of_threemonth_ago, end_of_threemonth_ago))\n history_per_month = [thismonth_history, onemonth_ago_history, twomonth_ago_history, threemonth_ago_history] # リストに各月毎のデータを格納\n\n total_price_per_month = [] # 月毎の請求金額を格納する空リスト\n for histories in history_per_month:\n total_price = 0\n for history in histories:\n price_per_lesson = 0\n hour = int(history.hour)\n charge = int(history.lesson.charge)\n usage_fee = int(history.lesson.usage_fee)\n\n # ---------------英語の価格計算--------------------\n if history.lesson.genre == 1:\n price_per_lesson = charge + (usage_fee * hour)\n\n # ------------ファイナンスの価格計算----------------\n elif history.lesson.genre == 2:\n volume_discount = 2800\n volume_discount_two = 2500\n\n if hour > 20 and 50 >= hour: #20万円を超え、50万円以下の時\n price_per_lesson = charge + (usage_fee * 20) + (volume_discount * (hour - 20))\n elif hour > 50: #50万円を超える時\n price_per_lesson = charge + (usage_fee * 20) + (volume_discount * 30) + (volume_discount_two * (hour - 50))\n else:\n price_per_lesson = charge + (usage_fee * hour)\n\n # ------------プログラミングの価格計算--------------\n elif history.lesson.genre == 3:\n volume_discount = 3000\n volume_discount_two = 2800\n volume_discount_three = 2500\n if hour <= 5: #5万円以下の時\n price_per_lesson = charge\n elif hour > 5 and 20 >= hour: #5万円を超え、20万円以下の時\n price_per_lesson = charge + (usage_fee * (hour - 5))\n elif hour > 20 and 35 >= hour: #20万円を超え、35万円以下の時\n price_per_lesson = charge + (usage_fee * 15) + (volume_discount * (hour - 20))\n elif hour > 35 and 50 >= hour: #35万円を超え、50万円以下の時\n price_per_lesson = charge + (usage_fee * 15) + (volume_discount * 15) + (volume_discount_two * (hour - 35))\n elif hour > 50: #50万円を超える時\n price_per_lesson = charge + (usage_fee * 15) + (volume_discount * 15) + (volume_discount_two * 15) + (volume_discount_three * (hour - 50))\n total_price += price_per_lesson\n total_price_per_month.append(total_price)\n return total_price_per_month\n\n# 受講記録のオブジェクト\nclass Lesson_history(models.Model):\n customer = models.ForeignKey(Customer, verbose_name=\"顧客名\")\n lesson = models.ForeignKey(Lesson, verbose_name=\"ジャンル\")\n date = models.DateField(default=timezone.now, verbose_name=\"受講日\")\n hour = models.CharField(max_length=200, verbose_name='受講時間(h)')\n\n def __int__(self):\n return self.date\n\n def calculate_price(self):\n hour = int(self.hour)\n charge = int(self.lesson.charge)\n usage_fee = int(self.lesson.usage_fee)\n\n if self.lesson.genre == 2: #ファイナンスの価格計算\n volume_discount = 2800\n volume_discount_two = 2500\n if hour > 20 and 50 >= hour:\n return charge + (usage_fee * 20) + (volume_discount * (hour - 20))\n elif hour > 50:\n return charge + (usage_fee * 20) + (volume_discount * 30) + (volume_discount_two * (hour - 50))\n\n elif self.lesson.genre == 3: #プログラミングの価格計算\n volume_discount = 3000\n volume_discount_two = 2800\n volume_discount_three = 2500\n if hour <= 5:\n return charge\n elif hour > 5 and 20 >= hour:\n return charge + (usage_fee * (hour - 5))\n elif hour > 20 and 35 >= hour:\n return charge + (usage_fee * 15) + (volume_discount * (hour - 20))\n elif hour > 35 and 50 >= hour:\n return charge + (usage_fee * 15) + (volume_discount * 15) + (volume_discount_two * (hour - 35))\n elif hour > 50:\n return charge + (usage_fee * 15) + (volume_discount * 15) + (volume_discount_two * 15) + (volume_discount_three * (hour - 50))\n return charge + (usage_fee * hour)\n","sub_path":"school/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":14017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"45147154","text":"#!/usr/bin/python3\n\nimport sys\nimport math\n\ndef findbest(score):\n\t# Corner case\n\tif score == 0: return (0, 0)\n\n\tbest = math.ceil(score / 3)\n\tbestsurp = round(score / 3) + 1\n\n\treturn (best, bestsurp)\n\t\n# Ignore the number of cases\nsys.stdin.readline()\n\ncasenum = 0\nfor line in sys.stdin:\n\tcasenum += 1\n\n\tdata = line.strip().split(' ')\n\tmaxsurprising = int(data[1])\n\tp = int(data[2])\n\tscores = data[3:]\n\tmaxgooglers = 0\n\n\tfor s in scores:\n\t\t(best, bestsurp) = findbest(int(s))\n\t\tif best >= p:\n\t\t\tmaxgooglers += 1\n\t\telse:\n\t\t\tif bestsurp >= p and maxsurprising > 0:\n\t\t\t\tmaxgooglers += 1\n\t\t\t\tmaxsurprising -= 1\n\n\tprint(\"Case #%d: %d\" % (casenum, maxgooglers))\n","sub_path":"solutions_1595491_1/Python/netsuso/Q_B.py","file_name":"Q_B.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"207012340","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nUtility file for collecting frequently used constants and helper functions.\n\nCreated on Wed Sep 29 10:50:36 2021\n\n@author: lbechberger\n\"\"\"\n\n# column names for the original data frame\nCOLUMN_TWEET = \"tweet\"\nCOLUMN_LIKES = \"likes_count\"\nCOLUMN_RETWEETS = \"retweets_count\"\nCOLUMN_MONTH = \"date\"\nCOLUMN_PHOTOS = \"photos\"\nCOLUMN_MENTIONS = \"mentions\"\nCOLUMN_URL = \"urls\"\nCOLUMN_REPLIES = \"replies_count\"\nCOLUMN_HASHTAG = \"hashtags\"\nCOLUMN_LIKES = \"likes_count\"\nCOLUMN_TIME = \"time\"\n\n# column names of novel columns for preprocessing\nCOLUMN_LABEL = \"label\"\nCOLUMN_PUNCTUATION = \"tweet_no_punctuation\"\n\nSUFFIX_TOKENIZED = \"_tokenized\"\nSUFFIX_STOPWORDS = \"_stopwords_removed\"\nSUFFIX_LEMMATIZED = \"_lemmatized\"\nSUFFIX_PUNCTUATION = \"_punct_removed\"","sub_path":"code/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"239418468","text":"#!/usr/bin/python\n\nimport logging\nimport sys\nimport socket\nimport config\nimport parsemessage as ps\n\n\ndef main(message):\n logging.basicConfig(filename='postrecord.log',\n filemode='w',\n level=logging.ERROR,\n format='[%(asctime)s] %(levelname)s:%(message)s',\n datefmt='%d/%m/%Y %H:%M:%S')\n logging.info(\"App start\")\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n s.connect((config.server_address, config.server_port))\n except Exception:\n logging.exception(\"Connect to pms server failed\")\n sys.exit(1)\n\n s.send(ps.generate_link_start_message())\n result1= ps.parse(message)\n if len(result1) == 3:\n s.send(message)\n else:\n logging.critical(\"Posting Record: '%s' is wrong\", message)\n s.close()\n sys.exit(2)\n\n answer = s.recv(1024)\n s.send(ps.generate_link_end_message())\n s.close()\n\n print(\"Answer is '{}'\".format(answer))\n result2 = ps.parse(answer)\n if (len(result2) != 4):\n logging.critical(\"Answer is wrong.\\n\"\n \"Posting Answer Record: '%s'\\n\"\n \"Posting Record: '%s'\",\n answer, message)\n sys.exit(3)\n\n if cmp(result1[1:2], result2[1:2]) != 0:\n logging.critical(\"Answer is wrong 2.\\n\"\n \"Posting Answer Record: '%s'\\n\"\n \"Posting Record: '%s'\",\n answer, message)\n sys.exit(3)\n\n if result2[3] != \"OK\":\n logging.error(\"Posting record is failed\")\n sys.exit(-1)\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print(\"Usage: postrecord record_message\")\n sys.exit(4)\n main(sys.argv[1])\n","sub_path":"pmsc/postrecord.py","file_name":"postrecord.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"142596570","text":"import glob\r\nimport sys\r\n\r\n\r\nsys.stdout = open('./Modules/modules.cpp', 'w')\r\npattern = \"// [[not imported module]]\"\r\nprint(pattern)\r\nfiles = glob.glob(\"./Modules/*.cpp\")\r\nresult = []\r\nprint(\"#include \\\"modules.h\\\"\")\r\nprint(\"#include \\\"all.h\\\"\")\r\nprint()\r\nprint(\"bool try_import_module(std::string name){\")\r\nfor file in files:\r\n\twith open(file, 'r') as fd:\r\n\t\ttext = fd.read()\r\n\tif text[0:26] != pattern:\r\n\t\tresult.append(file)\r\nfor i in range(len(result)):\r\n\tname = result[i][10:-4].lower()\r\n\tmodule_name = name[0].upper() + name[1:]\r\n\tif module_name == 'Modules':\r\n\t\tcontinue\r\n\tstart = \"else if\"\r\n\tif i == 0:\r\n\t\tstart = \"if\"\r\n\tprint(\"\\t\" + start + \" (name == \\\"\" + name + \"\\\") \" + module_name + \"::init();\")\r\nprint(\"\\telse return false;\")\r\nprint(\"\\treturn true;\")\r\nprint(\"}\")\r\ninput()\r\n","sub_path":"modules_updater.py","file_name":"modules_updater.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"198003607","text":"import numpy as np\nfrom joblib import Parallel, delayed\n\n\ndef _check_input(codes, times) -> tuple:\n # I don't want to work with subclass of ndarray, as subclasses actually have some undesired effects.\n codes = np.asarray(codes)\n times = np.asarray(times)\n assert codes.shape == times.shape\n assert codes.ndim == 1\n\n times = times.astype(np.float64, copy=False, casting='safe')\n codes = codes.astype(np.int16, copy=False, casting='safe')\n return codes, times\n\n\ndef _check_output(result: dict) -> None:\n \"\"\"\n\n Parameters\n ----------\n result\n\n Returns\n -------\n\n \"\"\"\n float64_set = {'start_times', 'end_times',\n 'trial_start_time', 'trial_end_time', 'trial_length'}\n for x in float64_set:\n assert result[x].dtype == np.float64\n assert result['condition_number'].dtype == np.int16\n for x in result['event_times']:\n assert x.dtype == np.float64\n for x in result['event_codes']:\n assert x.dtype == np.int16\n\n\ndef _get_times_one_sub_trial(codes: np.ndarray, times: np.ndarray, trial_info: dict) -> tuple:\n start_time = times[np.flatnonzero(codes == trial_info['start_code'])[0]]\n if 'end_time' in trial_info:\n end_time = start_time + trial_info['end_time']\n elif 'end_code' in trial_info:\n end_time = times[np.flatnonzero(codes == trial_info['end_code'])[0]]\n else:\n raise RuntimeError('unsupported mode for finding end of subtrial!')\n return start_time, end_time\n\n\ndef _get_times_subtrials(codes: np.ndarray, times: np.ndarray, params: dict) -> tuple:\n # find (abs) subtrial start/stop times.\n start_times = []\n end_times = []\n for trial_info in params:\n start_time, end_time = _get_times_one_sub_trial(codes, times, trial_info)\n start_times.append(start_time)\n end_times.append(end_time)\n start_times = np.asarray(start_times)\n end_times = np.asarray(end_times)\n assert np.all(start_times <= end_times)\n return start_times, end_times\n\n\ndef _get_times_trial(codes: np.ndarray, times: np.ndarray,\n start_times: np.ndarray, end_times: np.ndarray, params: dict) -> tuple:\n # find trial start/end times\n if 'trial_start_code' in params:\n trial_start_time = times[np.flatnonzero(codes == params['trial_start_code'])[0]]\n if 'trial_end_code' in params:\n trial_end_time = times[np.flatnonzero(codes == params['trial_end_code'])[0]]\n elif 'trial_end_time' in params:\n trial_end_time = trial_start_time + params['trial_end_time']\n else:\n raise RuntimeError('unsupported mode for finding end of trial!')\n else:\n trial_start_time = start_times[0]\n trial_end_time = end_times[-1]\n\n assert trial_start_time <= trial_end_time\n trial_start_time -= params['margin_before']\n trial_end_time += params['margin_after']\n return trial_start_time, trial_end_time\n\n\ndef _split_events_per_trial(t_idx, codes: np.ndarray, times: np.ndarray, params: dict) -> dict:\n \"\"\"roughly a rewrite of import_one_trial_startstoptime\n\n Parameters\n ----------\n codes\n times\n params\n\n Returns\n -------\n\n \"\"\"\n codes, times = _check_input(codes, times)\n trial_to_condition_func = eval(params['trial_to_condition_func'], {}, {})\n cnd_number = np.int16(trial_to_condition_func(codes, t_idx))\n assert np.isscalar(cnd_number)\n\n start_times, end_times = _get_times_subtrials(codes, times, params['subtrials'])\n trial_start_time, trial_end_time = _get_times_trial(codes, times, start_times, end_times, params)\n\n # this is due to ill design of trial window and subtrial window due to human error.\n assert np.all(trial_start_time <= start_times)\n assert np.all(trial_end_time >= end_times)\n\n event_code_idx = np.logical_and(times >= trial_start_time, times <= trial_end_time)\n\n return {\n 'start_times': start_times, # absolute\n 'end_times': end_times, # absolute\n 'trial_start_time': trial_start_time,\n 'trial_end_time': trial_end_time,\n 'event_times': times[event_code_idx],\n 'event_codes': codes[event_code_idx],\n 'condition_number': cnd_number\n }\n\n\ndef _assemble_result(split_result, n_trial):\n fields_to_be_ndarray = {\n 'start_times', 'end_times', 'trial_start_time', 'trial_end_time', 'condition_number'\n }\n\n result = {}\n for field in fields_to_be_ndarray:\n result[field] = np.asarray([x[field] for x in split_result])\n\n result['trial_length'] = result['trial_end_time'] - result['trial_start_time']\n\n # normalize time w.r.t trial start.\n result['start_times'] -= result['trial_start_time'][:, np.newaxis]\n result['end_times'] -= result['trial_start_time'][:, np.newaxis]\n\n # create object arrays.\n event_times = np.empty(n_trial, dtype=np.object_)\n event_codes = np.empty(n_trial, dtype=np.object_)\n\n for idx in range(n_trial):\n event_times[idx] = split_result[idx]['event_times'] - result['trial_start_time'][idx]\n event_codes[idx] = split_result[idx]['event_codes']\n\n result['event_times'] = event_times\n result['event_codes'] = event_codes\n\n return result\n\n\ndef split_events(event_data: dict, event_splitting_params: dict, n_jobs=-1) -> dict:\n \"\"\"extract event codes according to event splitting params.\n basically, this code replicates half the of `+cdttable/import_one_trial.m` in the original matlab package.\n the other half should go to the splitter.\n\n Parameters\n ----------\n event_data\n event_splitting_params\n n_jobs\n\n Returns\n -------\n\n \"\"\"\n # check that event_data is of good form.\n assert {'event_codes', 'event_times'} == set(event_data.keys())\n n_trial = len(event_data['event_codes'])\n assert n_trial == len(event_data['event_times'])\n assert n_trial >= 1\n\n # no memmaping, since trials are usually short.\n pool = Parallel(n_jobs=n_jobs, max_nbytes=None)\n split_result = pool(\n delayed(_split_events_per_trial)(t_idx, codes, times, event_splitting_params) for t_idx, (codes, times) in\n enumerate(zip(event_data['event_codes'],\n event_data['event_times'])))\n\n result = _assemble_result(split_result, n_trial)\n _check_output(result)\n\n return result\n","sub_path":"cdttable/core/io_event.py","file_name":"io_event.py","file_ext":"py","file_size_in_byte":6295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"343917223","text":"import collections\nimport six\nimport sys\nimport unicodedata\n\nimport tensorflow as tf\nimport sentencepiece as sp\n\nSENTPIECE_MODEL = 'ja_wiki_sentpiece/wiki-ja.model'\nSENTPIECE_VOCAB = 'ja_wiki_sentpiece/wiki-ja.vocab'\n\ndef load_vocab(vocab_file):\n \"\"\"Loads a vocabulary file into a dictionary.\"\"\"\n vocab = collections.OrderedDict()\n index = 0\n with tf.io.gfile.GFile(vocab_file, \"r\") as reader:\n while True:\n token = convert_to_unicode(reader.readline())\n if not token:\n break\n token, _ = token.split(\"\\t\")\n token = token.strip()\n vocab[token] = index\n index += 1\n return vocab\n\ndef convert_to_unicode(text):\n \"\"\"Converts `text` to Unicode (if it's not already), assuming utf-8 input.\"\"\"\n if six.PY3:\n if isinstance(text, str):\n return text\n elif isinstance(text, bytes):\n return text.decode(\"utf-8\", \"ignore\")\n else:\n raise ValueError(\"Unsupported string type: %s\" % (type(text)))\n elif six.PY2:\n if isinstance(text, str):\n return text.decode(\"utf-8\", \"ignore\")\n elif isinstance(text, unicode):\n return text\n else:\n raise ValueError(\"Unsupported string type: %s\" % (type(text)))\n else:\n raise ValueError(\"Not running on Python2 or Python 3?\")\n\ndef convert_by_vocab(vocab, items, unk_info):\n \"\"\"Converts a sequence of [tokens|ids] using the vocab.\"\"\"\n output = []\n for item in items:\n if item in vocab:\n output.append(vocab[item])\n else:\n output.append(unk_info)\n return output\n\nclass FullTokenizer(object):\n \"\"\"Runs end-to-end tokenziation.\"\"\"\n\n def __init__(self, path, do_lower_case=True):\n model_file = path + SENTPIECE_MODEL\n vocab_file = path + SENTPIECE_VOCAB\n self.tokenizer = SentencePieceTokenizer(model_file, do_lower_case=do_lower_case)\n self.vocab = load_vocab(vocab_file)\n self.inv_vocab = {v: k for k, v in self.vocab.items()}\n\n def parse(self, text):\n split_tokens = self.tokenizer.tokenize(text)\n return split_tokens\n\n def convert_tokens_to_ids(self, tokens):\n \"\"\"Id of is assumed as 0 accroding to sentencepiece\"\"\"\n return convert_by_vocab(self.vocab, tokens, unk_info=0)\n\n def convert_ids_to_tokens(self, ids):\n \"\"\"Token of unknown word is assumed as according to sentencepiece\"\"\"\n return convert_by_vocab(self.inv_vocab, ids, unk_info=\"\")\n\nclass SentencePieceTokenizer(object):\n \"\"\"Runs SentencePiece tokenization (from raw text to tokens list)\"\"\"\n\n def __init__(self, model_file=None, do_lower_case=True):\n \"\"\"Constructs a SentencePieceTokenizer.\"\"\"\n self.tokenizer = sp.SentencePieceProcessor()\n if self.tokenizer.Load(model_file):\n print(\"Loaded a trained SentencePiece model.\")\n else:\n print(\"You have to give a path of trained SentencePiece model.\")\n sys.exit(1)\n self.do_lower_case = do_lower_case\n\n def tokenize(self, text):\n \"\"\"Tokenizes a piece of text.\"\"\"\n text = convert_to_unicode(text)\n if self.do_lower_case:\n text = text.lower()\n output_tokens = self.tokenizer.EncodeAsPieces(text)\n return ' '.join(output_tokens)","sub_path":"projects/jp_dialogue/ja_sentpiece_tokenizer.py","file_name":"ja_sentpiece_tokenizer.py","file_ext":"py","file_size_in_byte":3357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"592246757","text":"import time\r\nfrom tkinter import *\r\nfrom threading import Thread\r\nfrom time import sleep\r\n\r\nclass runApp:\r\n def __init__(self, instance, appName):\r\n if __name__ == '__main__':\r\n pass\r\n Game = Pong(instance, appName)\r\n\r\nclass Pong:\r\n def __init__(self, instance, appName):\r\n self.MainInterface = instance\r\n self.Window1 = self.MainInterface.AppScreen\r\n self.InterfaceWindow = self.MainInterface.InterfaceWindow\r\n self.FontArray = self.MainInterface.Fonts\r\n\r\n self.width1 = self.MainInterface.windowWidth\r\n self.height1 = self.MainInterface.windowHeight\r\n\r\n self.width = self.width1\r\n self.height = (350 / 400) * self.height1\r\n self.Window1.config(bg='#040404')\r\n\r\n self.Window = Canvas(self.Window1, bg=\"#141414\")\r\n self.Window.place(relx=0, rely=0, width=self.width, height=self.height)\r\n\r\n self.Game_Active = True\r\n self.Game_Information = Label(self.Window, bg='#141414', font=('MS PGothic', 18, 'bold'), fg='#16a085')\r\n self.Paddle_1 = Paddle(self, [0.05, 0.35])\r\n self.Paddle_2 = Paddle(self, [0.95, 0.35])\r\n self.Ball_Position = [0.45, 0.45]\r\n self.Ball_Direction = [0.0025, 0.0075]\r\n self.Ball = Label(self.Window, height=1, width=2)\r\n self.Ball.place(relx=self.Ball_Position[0], rely=self.Ball_Position[1])\r\n\r\n self.InterfaceWindow.bind('', lambda event: self.Paddle_2.movePaddle(-0.03))\r\n self.InterfaceWindow.bind('', lambda event: self.Paddle_2.movePaddle(0.03))\r\n self.InterfaceWindow.bind('', lambda event: self.Paddle_1.movePaddle(-0.03))\r\n self.InterfaceWindow.bind('', lambda event: self.Paddle_1.movePaddle(0.03))\r\n self.InterfaceWindow.bind('', lambda event: self.Paddle_1.movePaddle(-0.03))\r\n self.InterfaceWindow.bind('', lambda event: self.Paddle_1.movePaddle(0.03))\r\n\r\n self.Game_Scores = Scores(self, 11, [self.width, self.height])\r\n\r\n\r\n timeNow = time.strftime(\"%H:%M\")\r\n\r\n Thread(target=self.ballMovement).start()\r\n\r\n def ballMovement(self):\r\n while self.Game_Active:\r\n self.Ball_Position[0] += self.Ball_Direction[0]\r\n self.Ball_Position[1] += self.Ball_Direction[1]\r\n self.Ball.place(relx=self.Ball_Position[0], rely=self.Ball_Position[1])\r\n if self.Ball_Position[1] > 0.95 or self.Ball_Position[1] < 0.05:\r\n self.Ball_Direction[1] *= -1\r\n if self.Ball_Position[0] >= self.Paddle_2.Paddle_Location[0] - 0.01:\r\n if self.Paddle_2.Paddle_Location[0] + 0.22 > self.Ball_Position[1] > self.Paddle_2.Paddle_Location[1]:\r\n self.Ball_Direction[0] *= -1\r\n if self.Ball_Position[0] <= self.Paddle_1.Paddle_Location[0]:\r\n if self.Paddle_1.Paddle_Location[1] + 0.22 > self.Ball_Position[1] > self.Paddle_1.Paddle_Location[1]:\r\n self.Ball_Direction[0] *= -1\r\n if self.Ball_Position[0] > 1.0:\r\n self.Ball_Position = [0.45, 0.45]\r\n self.Game_Scores.incrementScore(0)\r\n elif self.Ball_Position[0] < 0.0:\r\n self.Ball_Position = [0.45, 0.45]\r\n self.Game_Scores.incrementScore(1)\r\n sleep(0.009)\r\n else:\r\n self.Ball.place_forget()\r\n self.Game_Information.config(text=f'{self.Game_Scores.Game_Winner.upper()} SIDE WINS THE GAME!')\r\n self.Game_Information.place(relx=.3, rely=.4)\r\n\r\n\r\nclass Scores:\r\n def __init__(self, instance, score, sizing):\r\n self.width = sizing[0]\r\n \r\n self.Game_Instance = instance\r\n self.Game_Winner = None\r\n self.Game_Scores = [0, 0]\r\n self.Game_Strings = ['Left', 'Right']\r\n self.Score_Limit = score\r\n self.Score_Frame = Frame(self.Game_Instance.Window, bg='#141414')\r\n self.Score_Frame.place(relx=.425, rely=.0, width=.15*self.Game_Instance.width, height=self.Game_Instance.height * .15)\r\n self.Score_A = Label(self.Score_Frame, font=('Franklin Gothic Heavy', instance.FontArray[6], ''), text='0', bg='#141414', fg='#95A5A6')\r\n self.Score_A.place(relx=.08, rely=.1)\r\n self.Score_B = Label(self.Score_Frame, font=('Franklin Gothic Heavy', instance.FontArray[6], ''), text='0', bg='#141414', fg='#95A5A6')\r\n self.Score_B.place(relx=.72, rely=.1)\r\n self.Score_Splitter = Label(self.Score_Frame, font=('Franklin Gothic Heavy', instance.FontArray[6], ''), text='-', bg='#141414', fg='#95A5A6')\r\n self.Score_Splitter.place(relx=.44, rely=.1)\r\n self.Score_Information = Label(self.Score_Frame, text=f'FIRST TO {self.Score_Limit}', font=('Franklin Gothic Heavy', 12, ''), bg='#141414', fg='#95a5a6', justify=CENTER)\r\n self.Score_Information.place(relx=.08, rely=.65)\r\n\r\n def incrementScore(self, index):\r\n self.Game_Scores[index] += 1\r\n self.updateScores()\r\n self.checkWinner()\r\n\r\n def updateScores(self):\r\n self.Score_A.config(text=self.Game_Scores[0])\r\n self.Score_B.config(text=self.Game_Scores[1])\r\n\r\n def checkWinner(self):\r\n for scores in self.Game_Scores:\r\n if scores == self.Score_Limit:\r\n self.Game_Instance.Game_Active = False\r\n self.Game_Winner = self.Game_Strings[self.Game_Scores.index(scores)]\r\n\r\n\r\n\r\nclass Paddle:\r\n def __init__(self, instance, position):\r\n self.Game_Instance = instance\r\n self.Paddle_Location = position\r\n self.Game_Paddle = Label(self.Game_Instance.Window)\r\n self.Game_Paddle.place(relx=self.Paddle_Location[0], rely=self.Paddle_Location[1], height=75, width=15)\r\n\r\n def movePaddle(self, direction):\r\n self.Paddle_Location[1] += direction\r\n self.Game_Paddle.place(relx=self.Paddle_Location[0], rely=self.Paddle_Location[1])\r\n\r\n\r\n","sub_path":"Apps/Downloaded/Pong/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":5890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"598425239","text":"# coding=utf-8\n# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n unicode_literals, with_statement)\n\nimport os\nfrom contextlib import contextmanager\n\n\n@contextmanager\ndef setup_pexrc_with_pex_python_path(pexrc_path, interpreter_paths):\n \"\"\"A helper function for writing interpreter paths to a PEX_PYTHON_PATH variable\n in a .pexrc file. This function raise an error if a .pexrc file already exists at\n `pexrc_path`.\n\n :param pexrc_path (str): a path to a temporary .pexrc to write for testing purposes.\n :param interpreter_paths (list): a list of paths to interpreter binaries to include on \n PEX_PYTHON_PATH.\n \"\"\"\n pexrc_path = os.path.expanduser(pexrc_path)\n if os.path.exists(pexrc_path):\n raise RuntimeError(\"A pexrc file already exists in {}\".format(pexrc_path))\n\n # Write a temp .pexrc in pexrc_dir.\n with open(pexrc_path, 'w') as pexrc:\n pexrc.write(\"PEX_PYTHON_PATH=%s\" % ':'.join(interpreter_paths))\n \n try:\n yield\n finally:\n # Cleanup temporary .pexrc.\n os.remove(pexrc_path)\n","sub_path":"tests/python/pants_test/testutils/pexrc_util.py","file_name":"pexrc_util.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"434019928","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nfrom azure.cli.core.commands import cli_command\n\nfrom azure.cli.command_modules.batch_extensions._client_factory import (\n account_mgmt_client_factory, batch_data_service_factory)\n\ncustom_path = 'azure.cli.command_modules.batch_extensions.custom#{}'\n\n# pylint: disable=line-too-long\n# NCJ Commands\n\ncli_command(__name__, 'batch file upload', custom_path.format('upload_file'), account_mgmt_client_factory)\ncli_command(__name__, 'batch file download', custom_path.format('download_file'), account_mgmt_client_factory)\n\ncli_command(__name__, 'batch pool create', custom_path.format('create_pool'), batch_data_service_factory)\ncli_command(__name__, 'batch job create', custom_path.format('create_job'), batch_data_service_factory)\n","sub_path":"azure/cli/command_modules/batch_extensions/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"454054070","text":"import click\nfrom pyspark import SparkConf, SparkContext\n\nfrom qanta.util.constants import FEATURE_NAMES\nfrom qanta.util.environment import QB_SPARK_MASTER\nfrom qanta.util import spark_features\nimport qanta.extract_features as ef\n\nCONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])\n\n\n@click.group(context_settings=CONTEXT_SETTINGS)\ndef cli():\n pass\n\n\ndef create_spark_context(app_name=\"Quiz Bowl\", configs=None) -> SparkContext:\n spark_conf = SparkConf()\\\n .set('spark.rpc.message.maxSize', 300)\\\n .setAppName(app_name)\\\n .setMaster(QB_SPARK_MASTER)\n if configs is not None:\n for key, value in configs:\n spark_conf = spark_conf.set(key, value)\n return SparkContext.getOrCreate(spark_conf)\n\n\ndef extract_features(features):\n if 'lm' in features:\n # This deals with out of memory problems when using the language model\n configs = [('spark.executor.cores', 10)]\n else:\n configs = None\n create_spark_context(\n app_name='Quiz Bowl: ' + ' '.join(features), configs=configs\n )\n ef.spark_batch(features)\n\n\ndef extract_guess_features():\n create_spark_context(\n app_name='Quiz Bowl: guessers',\n configs=[('spark.executor.cores', 10)]\n )\n ef.generate_guesser_feature()\n\n\n@cli.command(name='extract_features')\n@click.argument('features', nargs=-1, type=click.Choice(FEATURE_NAMES), required=True)\ndef extract_features_cli(**kwargs):\n extract_features(kwargs['features'])\n\n\ndef merge_features():\n create_spark_context(app_name='Quiz Bowl Merge')\n spark_features.create_output('output/features')\n\n\n@cli.command(name='merge_features')\ndef merge_features_cli(**kwargs):\n merge_features()\n\n\nif __name__ == '__main__':\n cli()\n","sub_path":"qanta/spark_execution.py","file_name":"spark_execution.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"138001601","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@author: HuRuiFeng\n@file: module.py\n@time: 2020/8/18 16:50\n@project: wasm-python-book\n@desc: Wasm模块定义\n\"\"\"\n\n# 小端方式编码数值,魔数:0asm\nfrom ch07.binary.types import BlockTypeI32, BlockTypeI64, BlockTypeF32, BlockTypeF64, BlockTypeEmpty, FuncType, ValTypeI32, \\\n ValTypeI64, ValTypeF32, ValTypeF64\n\nMagicNumber = 0x6D736100\n# 版本号:1\nVersion = 0x00000001\n\n# 12种段\n# 自定义段ID\nSecCustomID = 0\n# 类型段ID\nSecTypeID = 1\n# 导入段ID\nSecImportID = 2\n# 函数段ID\nSecFuncID = 3\n# 表段ID\nSecTableID = 4\n# 内存段ID\nSecMemID = 5\n# 全局段ID\nSecGlobalID = 6\n# 导出段ID\nSecExportID = 7\n# 起始段ID\nSecStartID = 8\n# 元素段ID\nSecElemID = 9\n# 代码段ID\nSecCodeID = 10\n# 数据段ID\nSecDataID = 11\n\nImportTagFunc = 0\nImportTagTable = 1\nImportTagMem = 2\nImportTagGlobal = 3\n\nExportTagFunc = 0\nExportTagTable = 1\nExportTagMem = 2\nExportTagGlobal = 3\n\n# 内存页大小\nPageSize = 65536 # 64KB\n# 最大内存页数\nMaxPageCount = 65536 # 2^16\n\n# 索引空间\n# 类型索引:类型段的有效索引范围就是类型索引空间\nTypeIdx = int\n# 函数索引:由外部函数和内部函数共同构成\nFuncIdx = int\n# 表和内存索引:只能导入或定义一份表和内存,所以索引空间内的唯一有效索引为0\nTableIdx = int\nMemIdx = int\n# 全局变量索引:由外部和内部全局变量共同构成\nGlobalIdx = int\n# 局部变量索引:由函数的参数和局部变量共同构成\nLocalIdx = int\n# 跳转标签索引:每个函数有自己的跳转标签索引空间\nLabelIdx = int\n\n\nclass Module:\n \"\"\"模型\"\"\"\n\n def __init__(self):\n # 魔数\n self.magic = 0\n # 版本号\n self.version = 0\n # 自定义段 0\n # custom_sec: 0x00|byte_count|name|byte*\n self.custom_secs = []\n # 类型段 1\n # type_sec: 0x01|byte_count|vec\n self.type_sec = []\n # 导入段 2\n # import_sec : 0x02|byte_count|vec\n self.import_sec = []\n # 函数段 3\n # func_sec: 0x03|byte_count|vec\n self.func_sec = []\n # 表段 4\n # table_sec : 0x04|byte_count|vec\n self.table_sec = []\n # 内存段 5\n # mem_sec : 0x05|byte_count|vec 目前vec长度只能是1\n self.mem_sec = []\n # 全局段 6\n # global_sec : 0x06|byte_count|vec\n self.global_sec = []\n # 导出段 7\n # export_sec : 0x07|byte_count|vec\n self.export_sec = []\n # 起始段 8\n # start_sec: 0x08|byte_count|func_idx\n self.start_sec = None\n # 元素段 9\n # elem_sec: 0x09|byte_count|vec\n self.elem_sec = []\n # 代码段 10\n # code_sec: 0x0A|byte_count|vec\n self.code_sec = []\n # 数据段 11\n # data_sec: 0x0B|byte_count|vec\n self.data_sec = []\n\n def get_block_type(self, bt):\n if bt == BlockTypeI32:\n return FuncType(result_types=[ValTypeI32])\n elif bt == BlockTypeI64:\n return FuncType(result_types=[ValTypeI64])\n elif bt == BlockTypeF32:\n return FuncType(result_types=[ValTypeF32])\n elif bt == BlockTypeF64:\n return FuncType(result_types=[ValTypeF64])\n elif bt == BlockTypeEmpty:\n return FuncType()\n else:\n return self.type_sec[bt]\n\n\nclass CustomSec:\n \"\"\"自定义段\"\"\"\n\n def __init__(self, name=\"\", custom_sec_bytes=None):\n if custom_sec_bytes is None:\n custom_sec_bytes = []\n self.name = name\n self.bytes = custom_sec_bytes\n\n\nclass Import:\n \"\"\"\n 导入类型:函数、表、内存、全局变量\n import : module_name|member_name|import_desc\n \"\"\"\n\n def __init__(self, module=\"\", name=\"\", desc=None):\n # 模块名(从哪个模块导入)\n self.module = module\n # 成员名\n self.name = name\n # 具体描述信息\n self.desc = desc\n\n\nclass ImportDesc:\n \"\"\"\n import_desc: tag|[type_idx, table_type, mem_type, global_type]\n \"\"\"\n\n def __init__(self, tag):\n # 0表示函数、1表示表、2表示内存、3表示全局变量\n self.tag = tag\n self.func_type = TypeIdx\n self.table = None\n self.mem = None\n self.global_type = None\n\n\nclass Global:\n \"\"\"\n global : global_type|init_expr\n \"\"\"\n\n def __init__(self, global_type=None, init=None):\n self.type = global_type\n self.init = init\n\n\nclass Export:\n \"\"\"\n export : name|export_desc\n \"\"\"\n\n def __init__(self, name=\"\", export_desc=None):\n self.name = name\n self.desc = export_desc\n\n\nclass ExportDesc:\n \"\"\"\n export_desc: tag|[func_idx, table_idx, mem_idx, global_idx]\n \"\"\"\n\n def __init__(self, tag=0, idx=0):\n self.tag = tag\n self.idx = idx\n\n\nclass Elem:\n \"\"\"\n elem : table_idx|offset_expr|vec\n \"\"\"\n\n def __init__(self, table_idx=0, offset_expr=None, vec_init=None):\n if vec_init is None:\n vec_init = []\n self.table = table_idx\n self.offset = offset_expr\n self.init = vec_init\n\n\nclass Code:\n \"\"\"\n code : byte_count|vec|expr\n \"\"\"\n\n def __init__(self, locals_vec=None, expr=None):\n if locals_vec is None:\n locals_vec = []\n self.locals = locals_vec\n self.expr = expr\n\n def get_local_count(self) -> int:\n n = 0\n for locals_item in self.locals:\n n += locals_item.n\n return n\n\n\nclass Locals:\n \"\"\"\n locals : local_count|val_type\n \"\"\"\n\n def __init__(self, local_count=0, val_type=0):\n self.n = local_count\n self.type = val_type\n\n\nclass Data:\n \"\"\"\n data : mem_idx|offset_expr|vec\n \"\"\"\n\n def __init__(self, mem_idx=0, offset_expr=None, vec_init=None):\n if vec_init is None:\n vec_init = []\n self.mem = mem_idx\n self.offset = offset_expr\n self.init = vec_init\n","sub_path":"src/ch07/binary/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":6106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"186339342","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun May 12 23:04:56 2019\r\n\r\n@author: binxi\r\n\"\"\"\r\n\r\nclass Solution(object):\r\n def partition(self, s):\r\n \"\"\"\r\n :type s: str\r\n :rtype: List[List[str]]\r\n \"\"\"\r\n if s == '':\r\n return []\r\n exit\r\n \r\n lst = []\r\n \r\n for i in range(len(s)):\r\n if s[:i+1] == s[:i+1][::-1]:\r\n if i+1 == len(s):\r\n lst.append([s])\r\n else:\r\n for j in self.partition(s[i+1:]):\r\n lst.append([s[:i+1]]+j)\r\n return lst","sub_path":"Leetcode/#131 Palindrome Partitioning.py","file_name":"#131 Palindrome Partitioning.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"539713799","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 ('adverts', '0005_auto_20151203_2337'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='UsersProfiles',\n fields=[\n ('id', models.AutoField(serialize=False, auto_created=True, primary_key=True, verbose_name='ID')),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, unique=True)),\n ],\n ),\n migrations.DeleteModel(\n name='UserLogin',\n ),\n migrations.DeleteModel(\n name='UserRegistration',\n ),\n ]\n","sub_path":"src/adverts/migrations/0006_auto_20151205_1838.py","file_name":"0006_auto_20151205_1838.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"373346716","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 2 11:43:14 2021\n\n@author: EduardoR\n\"\"\"\n\nimport streamlit as st\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nst.write(\"\"\"\n # Monthly Adverse Event report\n\"\"\")\n\nae_data = pd.read_csv('NOAEs_ImportTemplate.csv')\nae_data['start_date'] = pd.to_datetime(ae_data['start_date'])\nae_data['start_date'] = ae_data['start_date'].dt.date\n\nae_data['end_date'] = pd.to_datetime(ae_data['end_date'])\nae_data['end_date'] = ae_data['end_date'].dt.date\n\n\n\n#with st.beta_container():\n# hist_values = np.histogram(ae_data['start_date'].dt.month, bins=15, range=(0,13))[0]\n# st.write('Adverse Event by grade of severity')\n# st.bar_chart(hist_values)\n \nst.sidebar.header('Select The data to display')\n\ninput_sdate = st.sidebar.date_input('Select Start date')\ninput_edate = st.sidebar.date_input ('Select End date')\ninput_study = st.sidebar.selectbox('Only SAEs?', ('Yes','No'))\n\n\nfiltered_df = ae_data[ae_data['start_date'] > input_sdate &(ae_data['start_date'] < input_edate)]\n\n\n\nsae_df = ae_data[ae_data['serious']==1]\nsae_df = sae_df[['id','ae_term','ongoing','relationship']]\n\nif st.checkbox('SAEs'):\n st.subheader('Displaying only SAEs')\n st.write(sae_df)\n fig, ax = plt.subplots()\n ax.hist(sae_df['ae_term'])\n st.pyplot(fig)\n#Create the sidebar the first parameter in the slider is the minimum value, the \n#second parameter is the maximum value and the last is the default value\n'''\ndef user_input_features():\n sepal_length = st.sidebar.slider('Sepal length', 4.3, 7.9, 5.4)\n sepal_width = st.sidebar.slider('Sepal width', 2.0, 4.4, 3.4)\n petal_length = st.sidebar.slider('Petal length',1.0, 6.9, 1.3)\n petal_width = st.sidebar.slider('Petal width',0.1, 2.5, 0.2)\n data = {'sepal_length': sepal_length,\n 'sepal_width': sepal_width,\n 'petal_length': petal_length,\n 'petal_width': petal_width}\n features = pd.DataFrame(data, index=[0])\n return features\n\n\n#Assign the input parameters to a variable 'df'\n\ndf = user_input_features()\n\nst.subheader('User Input Parameters')\n\n#write the df variable into the app (creates a printout of the dataframe)\nst.write(df)\n\n\n#import the dataset to use the randomforest classifier\niris = datasets.load_iris()\nX = iris.data\nY = iris.target\n\n\n#Built and compile the random forest classifier using the iris data\nclf = RandomForestClassifier()\nclf.fit(X, Y)\n\n#the predictions are out of the user input\nprediction = clf.predict(df)\nprediction_proba = clf.predict_proba(df)\n\n#Create a printout of the class label and probability\n\nst.subheader('Prediction')\nst.write(iris.target_names[prediction])\n\nst.subheader('Prediction Probability')\nst.write(prediction_proba)\n'''","sub_path":"AE_webapp.py","file_name":"AE_webapp.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"525731470","text":"import subprocess\nimport shlex\nimport sys\nimport dendropy\nimport pandas\nimport pysam\nfrom random import shuffle\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\n\nfrom pathfinder.plots import plot_date_randomisation, plot_regression\n\n\ndef run_cmd(cmd, callback=None, watch=False, background=False, shell=False):\n\n \"\"\" Runs the given command and gathers the output.\n\n If a callback is provided, then the output is sent to it, otherwise it\n is just returned.\n\n Optionally, the output of the command can be \"watched\" and whenever new\n output is detected, it will be sent to the given `callback`.\n\n Returns:\n A string containing the output of the command, or None if a `callback`\n was given.\n Raises:\n RuntimeError: When `watch` is True, but no callback is given.\n\n \"\"\"\n\n if watch and not callback:\n raise RuntimeError(\n \"You must provide a callback when watching a process.\"\n )\n\n output = None\n try:\n if shell:\n proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n else:\n proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)\n\n if background:\n # Let task run in background and return pmid for monitoring:\n return proc.pid, proc\n\n if watch:\n while proc.poll() is None:\n line = proc.stdout.readline()\n if line != \"\":\n callback(line)\n\n # Sometimes the process exits before we have all of the output, so\n # we need to gather the remainder of the output.\n remainder = proc.communicate()[0]\n if remainder:\n callback(remainder)\n else:\n output = proc.communicate()[0]\n except:\n err = str(sys.exc_info()[1]) + \"\\n\"\n output = err\n\n if callback and output is not None:\n return callback(output)\n\n return output\n\n\n# Survey support functions\n\ndef get_aspera_key() -> Path:\n\n \"\"\" Return path to aspera key for connections to ENA \"\"\"\n\n return Path(__file__).parent / \"resources\" / \"asperaweb_id_dsa.openssh\"\n\n\ndef get_genome_sizes() -> pandas.DataFrame:\n\n \"\"\" Return a dataframe from the `genome.size` file in `pathfinder.resources`\n\n Genome sizes are computed as media genome size for given taxonomic\n identifier from the NCBI Prokaryot DB.\n\n :return Dataframe with one column size and row index taxid\n\n \"\"\"\n\n genome_sizes = Path(__file__).parent / \"resources\" / \"genome.sizes\"\n genome_sizes = pandas.read_csv(genome_sizes, index_col=0)\n\n return genome_sizes\n\n\n# Alignment support functions\n\ndef remove_sample(alignment: Path, outfile: Path, remove: str or list) -> None:\n\n \"\"\" Remove any sequence from the alignment file by sequence names\n\n :param alignment: alignment file (.fasta)\n :param outfile: output file (.fasta)\n :param remove: sequence identifiers to remove\n\n :return: None, outputs alignment file with sequences removed\n\n \"\"\"\n\n if isinstance(remove, str):\n remove = [remove]\n\n with pysam.FastxFile(alignment) as fin, outfile.open('w') as fout:\n for entry in fin:\n if entry.name not in remove:\n fout.write(str(entry) + '\\n')\n\n\n# Phylogenetics support functions\n\ndef get_tree_dates(newick_file: Path) -> pandas.DataFrame:\n\n \"\"\" Get the leaf names and dates from the input tree\n\n :param newick_file: tree file in newick format\n\n :returns `pandas.DataFrame` with two columns: name, date\n\n \"\"\"\n\n tree = dendropy.Tree.get(path=newick_file, schema=\"newick\")\n\n return pandas.DataFrame(\n data=[taxon.label.split() for taxon in tree.taxon_namespace],\n columns=['name', 'date']\n )\n\n\n# Phybeast support functions\n\n\n\ndef phybeast_randomise_date_file(\n date_file: Path,\n output_file: Path = None\n) -> pandas.DataFrame:\n\n \"\"\" Randomise order of dates in file\n\n DataFrame input options can be passed as **kwargs\n\n :param date_file: path to date file with columns: name and date\n :param output_file: path to tab-delimited output file for randomised dates\n\n :returns DataFrame with shuffled dates\n\n :raises ValueError if date and name not in column headers\n\n \"\"\"\n\n df = pandas.read_csv(date_file, sep='\\t')\n\n if 'date' not in df.columns or 'name' not in df.columns:\n raise ValueError('Could not find date and name in columns')\n\n # Suppress warning\n with pandas.option_context('mode.chained_assignment', None):\n dates = df.date\n shuffle(dates)\n df.date = dates\n\n if output_file is not None:\n df.to_csv(output_file, sep='\\t', header=True, index=False)\n\n return df\n\n\ndef phybeast_prepare_metadata_file(\n meta_file: Path,\n prep: str = 'lsd2',\n output_file: Path = Path.cwd() / 'lsd2.meta'\n) -> None:\n\n \"\"\" Prepare the tab-delimited input file for pf-phybeast\n\n :param meta_file: tab-delimited meta data file with columns: name, date\n :param prep: output file type to prepare for: lsd2, treetime\n :param output_file: output file path\n\n :returns None, writes to file :param out_file\n\n \"\"\"\n\n df = pandas.read_csv(meta_file, sep='\\t')\n\n if 'date' not in df.columns or 'name' not in df.columns:\n raise ValueError('Could not find date and name in columns')\n\n if prep == 'treetime':\n df.to_csv(output_file, header=True, sep=',', index=False)\n\n if prep == 'lsd2':\n with output_file.open('w') as outfile:\n outfile.write(\n f'{len(df)}\\n'\n )\n\n # TODO: document no spaces in unique ids\n df[['name', 'date']].to_csv(\n outfile, header=False, sep=' ', index=False\n )\n\n\ndef phybeast_extract_rate(\n result_file: Path,\n prep: str = 'lsd2',\n output_file: Path = Path.cwd() / 'rate.txt'\n) -> None:\n\n \"\"\" Prepare the tab-delimited input file for pf-phybeast\n\n :param result_file: path to summary output file from: lsd2 or treetime\n :param prep: output file type to prepare for: lsd2 or treetime\n :param output_file: Output file path\n\n :returns None, writes to file :param output_file\n\n \"\"\"\n\n if prep == 'lsd2':\n\n with result_file.open('r') as infile, output_file.open('w') as outfile:\n for line in infile:\n if line.strip().startswith('rate'):\n rate = float(\n line.strip().split()[1].strip(',')\n )\n tmrca = float(\n line.strip().split()[3].strip(',')\n )\n print(rate, tmrca)\n outfile.write(f\"{rate}\\t{tmrca}\\n\")\n\n\ndef phybeast_plot_date_randomisation(\n replicate_file: Path,\n rate_file: Path,\n output_file: Path = Path(\"date_randomisation.png\"),\n regression_file: Path = None\n) -> None:\n\n \"\"\" Plot distribution of date randomised substitution rates\n\n :param replicate_file: `rates.tab` with replicates from `DateRandomisationPlot`\n :param rate_file: `rate.txt` containing true rate from `MolecularClock`\n :param output_file: output plot file, format by extension\n :param regression_file: `rtt.csv` file from TimeTree clock regression\n\n :returns None, writes to file :param output_file\n\n \"\"\"\n\n # one panel:\n if regression_file is None:\n fig, ax1 = plt.subplots(figsize=(27.0, 9))\n ax2 = None\n else:\n fig, axes = plt.subplots(ncols=2, figsize=(27.0, 9))\n ax2, ax1 = axes.flatten() # observe order\n\n # Date Randomisation\n\n replicate_df = pandas.read_csv(\n replicate_file, sep='\\t', names=['replicate', 'tmrca']\n )\n\n replicates = replicate_df.replicate.tolist()\n\n rate_df = pandas.read_csv(\n rate_file, sep='\\t', names=['rate', 'tmrca']\n )\n\n rate = float(rate_df.iloc[0, 0])\n\n plot_date_randomisation(\n ax=ax1, replicates=replicates, rate=rate\n )\n\n # Regression plot\n if regression_file is not None:\n # Regression file from TimeTree\n data = pandas.read_csv(\n regression_file, skiprows=2, header=None,\n names=['name', 'date', 'distance']\n )\n plot_regression(\n ax=ax2, regression_data=data.iloc[:, 1:]\n )\n\n fig.savefig(output_file)\n\n\n\n\n","sub_path":"pathfinder/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"212189402","text":"from .dpipe import subprocesses, Dummy\nimport unittest\n\n####### subprocesses tests\n\n\nclass SanityCheck(unittest.TestCase):\n\n dummy = Dummy()\n template = ['echo', dummy]\n\n def test_fail_template(self):\n '''sanity check should fail with non-list template'''\n template = ('echo', self.dummy)\n iterable = ['hello', 'world!']\n with self.assertRaises(TypeError):\n s = subprocesses(template, iterable, run=False)\n\n def test_fail_iterable_types(self):\n '''sanity check should fail if iterable is not all strings or all lists'''\n iterable = ['hello', ('world',)]\n with self.assertRaises(TypeError):\n s = subprocesses(self.template, iterable, run=False)\n\n def test_fail_iterable_length(self):\n '''sanity check should fail if items in iterable not uniform in length'''\n iterable = [('how', 'are'), ('you?',)]\n with self.assertRaises(AssertionError):\n s = subprocesses(self.template, iterable, run=False)\n\n def test_fail_dummy_count(self):\n '''should fail if iterable item length does not match number of dummy values'''\n iterable = [('a', 'b', 'c'), ('d', 'e', 'f')]\n template = ['echo', self.dummy, 'something', self.dummy, self.dummy, self.dummy]\n with self.assertRaises(AssertionError):\n s = subprocesses(template, iterable, run=False)\n\n\nclass CommandsCheck(unittest.TestCase):\n\n dummy = Dummy()\n\n def test_good_string(self):\n '''should pass with known string inputs'''\n knowninputs = (['echo', self.dummy], ['hello', 'world!', 'goodbye', 'now'])\n knownoutput = [\n ['echo', 'hello'],\n ['echo', 'world!'],\n ['echo', 'goodbye'],\n ['echo', 'now']\n ]\n output = subprocesses(*knowninputs, run=False)._get_commands()\n self.assertEqual(knownoutput, output)\n\n def test_good_tuple(self):\n '''should pass with known tuple inputs'''\n knowninputs = (['hey', self.dummy, 'name', self.dummy, self.dummy],\n [('my', 'is', 'drew'),\n ('joels', 'aint', 'drew'),\n ('johns', 'isgottabe', 'johnny')])\n knownoutput = [\n ['hey', 'my', 'name', 'is', 'drew'],\n ['hey', 'joels', 'name', 'aint', 'drew'],\n ['hey', 'johns', 'name', 'isgottabe', 'johnny'],\n ]\n output = subprocesses(*knowninputs, run=False)._get_commands()\n self.assertEqual(knownoutput, output)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test_dpipe.py","file_name":"test_dpipe.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"163724215","text":"import os\nimport tempfile\n\nimport requests\n\nfrom .core import GirderFS\nfrom .utils import _lstrip_path, logger\n\n\nclass RESTGirderFS(GirderFS):\n \"\"\"\n Filesystem for locally mounting a remote Girder folder\n\n :param folder_id: Folder id\n :type folder_id: str\n :param gc: Authenticated instance of GirderClient\n :type gc: girder_client.GriderClient\n \"\"\"\n\n def read(self, path, size, offset, fh):\n logger.debug(\"-> read({})\".format(path))\n obj, _ = self._get_object_from_root(_lstrip_path(path))\n cacheKey = \"#\".join((obj[\"_id\"], obj.get(\"updated\", obj[\"created\"])))\n fp = self.cache.get(cacheKey, read=True)\n if fp:\n logger.debug(\"-> hitting cache {} {} {}\".format(path, size, offset))\n fp.seek(offset)\n return fp.read(size)\n else:\n logger.debug(\"-> downloading\")\n req = requests.get(\n \"%sitem/%s/download\" % (self.girder_cli.urlBase, obj[\"_id\"]),\n headers={\"Girder-Token\": self.girder_cli.token},\n stream=True,\n )\n with tempfile.NamedTemporaryFile(prefix=\"wtdm\", delete=False) as tmp:\n for chunk in req.iter_content(chunk_size=65536):\n tmp.write(chunk)\n with open(tmp.name, \"rb\") as fp:\n self.cache.set(cacheKey, fp, read=True)\n os.remove(tmp.name)\n fp.seek(offset)\n return fp.read(size)\n\n def open(self, path, mode=\"r\", **kwargs):\n logger.debug(\"-> open({}, {})\".format(path, self.fd))\n self.fd += 1\n return self.fd\n\n def destroy(self, private_data):\n super().destroy(self, private_data)\n\n def release(self, path, fh): # pylint: disable=unused-argument\n logger.debug(\"-> release({}, {})\".format(path, self.fd))\n self.fd -= 1\n return self.fd\n","sub_path":"girderfs/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"524159835","text":"import base64\nimport time\nimport hashlib\nimport json\nfrom flask import Flask, request, send_file\nfrom werkzeug.utils import secure_filename\nfrom pprint import pprint\n\nfrom fantopia import Fantopia\n# from fantopia_offline import Fantopia\n\nimport sys\nsys.path.append('../../caller/')\nfrom NFT import NFT\nfrom ST import ServiceToken\nfrom utils import get_transaction_info\n\n\napp = Flask('app')\n\n\n@app.route('/adduser', methods=['POST'])\ndef adduser():\n params = json.loads(request.get_data(), encoding='utf-8')\n if len(params) == 0:\n return 'No parameter'\n\n fantopia.add_user(params)\n\n return 'Success'\n\n\n@app.route('/addartist', methods=['POST'])\ndef addartist():\n params = json.loads(request.get_data(), encoding='utf-8')\n if len(params) == 0:\n return 'No parameter'\n\n fantopia.add_artist(params)\n\n return 'Success'\n\n\n# depricated\n# @app.route('/uploadimage', methods=['POST', 'PUT'])\n# def uploadimage():\n# _who = request.form['who']\n# _name = request.form['name']\n# _file = request.files['file']\n# _amount = 1 if 'amount' not in request.form else int(request.form['amount'])\n# _price = None if 'price' not in request.form else int(request.form['price'])\n\n# res = fantopia.upload_image(\n# who=_who,\n# name=_name,\n# image_bytes=_file.read(),\n# # description=_description\n# amount=_amount,\n# price=_price\n# )\n# pprint(res)\n\n# return json.dumps(res) or 'Success'\n\n\n# # depricated\n# @app.route('/uploadproduct', methods=['POST'])\n# def uploadproduct():\n# params = json.loads(request.get_data(), encoding='utf-8')\n# if len(params) == 0:\n# return 'No parameter'\n\n# fantopia.upload_product(\n# name=params['name'],\n# nft_number=params['nft_number'],\n# nft_name=params['nft_name'],\n# )\n\n# return 'Success'\n\n\n@app.route('/getimage', methods=['POST'])\ndef getimage():\n params = json.loads(request.get_data(), encoding='utf-8')\n if len(params) == 0:\n return 'No parameter'\n\n pk = params['pk']\n\n res = fantopia.getImage(pk)\n\n return json.dumps(res)\n\n\n@app.route('/getallimages', methods=['POST'])\ndef getdetail():\n params = {}\n try:\n params = json.loads(request.get_data(), encoding='utf-8')\n except:\n pass\n\n startNum = params['startNum'] if 'startNum' in params else 0\n endNum = params['endNum'] if 'endNum' in params else 100\n\n res = fantopia.getAllImages(startNum=startNum, endNum=endNum)\n\n return json.dumps(res)\n\n\n@app.route('/updatefavorite', methods=['POST'])\ndef updatefavorite():\n params = json.loads(request.get_data(), encoding='utf-8')\n if len(params) == 0:\n return 'No parameter'\n\n pk = params['pk']\n favor = params['favor'] if 'favor' in params else True\n\n fantopia.updateFavorite(pk, favor)\n\n return 'Success'\n\n\n@app.route('/sellreset', methods=['POST'])\ndef sellreset():\n params = {}\n try:\n params = json.loads(request.get_data(), encoding='utf-8')\n except:\n pass\n\n startNum = params['startNum'] if 'startNum' in params else 0\n endNum = params['endNum'] if 'endNum' in params else 100\n\n res = fantopia.sellReset(startNum=startNum, endNum=endNum)\n\n return 'Success'\n\n\n@app.route('/buyimage', methods=['POST'])\ndef buyimage():\n params = json.loads(request.get_data(), encoding='utf-8')\n if len(params) == 0:\n return 'No parameter'\n\n tokenIndex = params['tokenIndex'] if 'tokenIndex' in params else None\n price = params['price'] if 'price' in params else None\n\n res = fantopia.buy(\n pk=params['pk'],\n fromAddress=params['fromAddress'],\n toAddress=params['toAddress'],\n tokenIndex=tokenIndex,\n price=price,\n )\n pprint(res)\n\n return json.dumps(res) or 'Success'\n\n\n@app.route('/buygoods', methods=['POST'])\ndef buygoods():\n params = json.loads(request.get_data(), encoding='utf-8')\n if len(params) == 0:\n return 'No parameter'\n\n fantopia.buyGoods(pk=params['pk'])\n\n return 'Success'\n\n\n@app.route('/gettx', methods=['POST'])\ndef gettx():\n params = json.loads(request.get_data(), encoding='utf-8')\n if len(params) == 0:\n return 'No parameter'\n\n res = get_transaction_info(\n server_url=fantopia.config['server_url'],\n service_api_key=fantopia.config['service_api_key'],\n service_api_secret=fantopia.config['service_api_secret'],\n txHash=params['txHash']\n )\n pprint(res)\n\n return json.dumps(res) or 'Success'\n\n\n@app.route('/getinfo', methods=['POST'])\ndef getinfo():\n params = json.loads(request.get_data(), encoding='utf-8')\n if len(params) == 0:\n return 'No parameter'\n\n res = fantopia.nft.get_info(number=params['tokenIndex'])['responseData']['meta']\n pprint(res)\n\n return json.dumps(res) or 'Success'\n\n\n@app.route('/getbalance', methods=['POST'])\ndef getbalance():\n params = json.loads(request.get_data(), encoding='utf-8')\n if len(params) == 0:\n return 'No parameter'\n\n address = params['address']\n reses = fantopia.st.holders()['responseData']\n for res in reses:\n if res['address'] == address:\n pprint(res['amount'])\n return json.dumps(res['amount']) or 'Success'\n\n return json.dumps(\"\")\n\n\n# @app.route('/test', methods=['GET'])\n# def test():\n# ress = []\n\n# # Load info.\n# with open('./users.json') as f:\n# users = json.load(f)\n\n# owner = users['Owner']\n# artist = users['Artist']\n# user_A = users['Customer_A']\n# user_B = users['Customer_B']\n\n# with open('./config.json') as f:\n# config = json.load(f)\n\n# # Add artist\n# fantopia.add_artist(artist)\n\n# # Add user\n# fantopia.add_user(user_A)\n# fantopia.add_user(user_B)\n\n# # Buy image\n# res = fantopia.buy(\n# fromAddress=user_B['address'],\n# toAddress=user_A['address'],\n# tokenIndex='00000085',\n# price='10000'\n# )\n# pprint(res)\n# ress.append(res)\n\n# res = get_transaction_info(\n# server_url=config['server_url'],\n# service_api_key=config['service_api_key'],\n# service_api_secret=config['service_api_secret'],\n# txHash=\"DCD0B2D32E9329D77AA642A55DC10469A876767493D2F60254A70E4DCD099202\"\n# )\n# pprint(res)\n# ress.append(res)\n\n# return json.dumps(ress) or 'Success'\n\n\nif __name__ == \"__main__\":\n # Load info.\n with open('./users.json') as f:\n users = json.load(f)\n\n owner = users['Owner']\n\n with open('./config.json') as f:\n config = json.load(f)\n\n # Set Fantopia service\n fantopia = Fantopia(owner, config)\n\n app.run(host='0.0.0.0', debug=False)\n","sub_path":"example/server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"608752635","text":"# -*- coding: utf-8 -*-\nimport os\nimport scrapy\nimport requests\n\nclass ImglySpider(scrapy.Spider):\n name = \"imgly\"\n allowed_domains = [\"img.ly/images\"]\n start_urls = ['http://img.ly/images/']\n\n def start_requests(self):\n screen_name = getattr(self, 'screen_name', None)\n if screen_name is not None:\n img_dir = 'img_' + screen_name\n if not os.path.exists(img_dir):\n os.makedirs(img_dir)\n \n url = self.start_urls[0] + screen_name\n yield scrapy.Request(url, callback=self.parse, dont_filter=True, meta=dict(img_dir=img_dir))\n\n def parse(self, response):\n for url in response.css('#image-list-detailed a::attr(href)').extract():\n url = response.urljoin(url)\n yield scrapy.Request(url, callback=self.parse_detail_page, dont_filter=True, meta=response.meta)\n\n next_page = response.css('a.next_page::attr(href)').extract_first()\n if next_page is not None:\n next_page = response.urljoin(next_page)\n yield scrapy.Request(next_page, callback=self.parse, dont_filter=True, meta=response.meta)\n\n def parse_detail_page(self, response):\n img_url = response.css('img#the-image::attr(src)').extract_first() \\\n .replace('large_', 'original_')\n description = response.css('p#image-description::text').extract_first().strip()\n \n filepath = self.download_image(response.meta['img_dir'], img_url, description)\n \n yield {\n 'img_url': img_url,\n 'description': description,\n 'filepath': filepath,\n }\n\n def download_image(self, img_dir, img_url, description):\n filename = description + os.path.splitext(img_url)[1]\n filepath = os.path.join(img_dir, filename)\n if not os.path.exists(filepath):\n r = requests.get(img_url)\n with open(filepath, 'wb') as f:\n f.write(r.content)\n return filepath","sub_path":"imgly_downloader/spiders/imgly.py","file_name":"imgly.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"61098185","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/6/16 下午4:27\n# @Author : Huang HUi\n# @Site : \n# @File : Same Tree.py\n# @Software: PyCharm\n\n# Definition for a binary tree node.\nclass 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 isSameTree(self, p, q):\n \"\"\"\n :type p: TreeNode\n :type q: TreeNode\n :rtype: bool\n \"\"\"\n if not p and not q:\n return True\n elif not p or not q:\n return False\n elif p.val !=q.val :\n return False\n else:\n return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)\n\nif __name__ == '__main__':\n\n\n\n Solution().isSameTree()\n","sub_path":"Same Tree.py","file_name":"Same Tree.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"22359365","text":"cont = True\nwhile cont:\n i = input('\\nInput the measurements of the three sides of the triangle in any order with a \",\" betewen each value:\\n')\n\n tri_sides = [int(x) for x in i.split(',')]\n c = max(tri_sides)\n tri_sides.remove(max(tri_sides))\n a = tri_sides.pop()\n b = tri_sides.pop()\n\n if (a**2 + b**2) == (c**2):\n print('-\\n{}, {}, and {} creates a Pythagorean triple!\\n-\\n'.format(a,b,c))\n else:\n print('-\\n{}, {}, and {} is not a Pythagorean triple!\\n-\\n'.format(a,b,c))\n \n i = input('Try again?\\nType \"y\" or \"n\"\\n\\n')\n if i.lower() == 'n':\n cont = False","sub_path":"pythagorean-triples.py","file_name":"pythagorean-triples.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"3226872","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#file h2cc.py\n#author pku_goldenlock@qq.com\n#date 20150625\n\n#.h convert to interface only.h\n\n\nimport sys,re,getopt,os\n\ndef usage():\n \"\"\" \n Run the program like this\n \n ./h2cc.py abc.h ok.cc\n It will read abc.h and append the fuctions \n to be implemented to ok.cc\n \n or \n ./h2cc.py abc.h #will create abc.cc\n ./h2cc.py abc.h cpp #will create abc.cpp\n \"\"\"\n\n\npattern_comment = re.compile(r'^\\s*//')\n#传入一个打开的文件(我们要生成的或者已经存在要分析处理)的handle,如abc.cc\n#调用该函数者负责关闭该文件,该函数只负责处理\nstack_class = [] #----存储class name\nstack_namespace = []\n\nabstract_classes = set()\nabstract_class_out = open('abstract_class.txt', 'a')\n\ninput_file = ''\n\n\n# value_type& Value(index_type index) ----------- line\n# { -------------------------------here and below as content\n# return values[index];\n# }\ndef pyplusplus_hack(line, content):\n global abstract_class_out\n global abstract_classes\n global stack_class\n global input_file\n\n #@FIXME hack Float _min = std::numeric_limits::max(); \n if line.find('=') > 0 and line.rstrip().endswith('()') and line.find('operator') == -1 and not line.startswith('virtual'):\n l = line.split()\n if len(l) > 2 and l[2] == '=':\n return line.rstrip() + ';\\n'\n\n vec_ref_pattern = re.compile(r'return.+?\\[.+?\\];') \n lines = line.split('\\n')\n need_comment = False\n return_nonconst_ref = False\n for i in range(len(lines)):\n lines[i] = lines[i].replace('override', '')\n lines[i] = lines[i].replace('= default', '').replace('=default', '')\n line = lines[i].strip().replace('inline', '').strip()\n l = line.split()\n #non const static ref\n if len(l) > 1 and l[0] == 'static' and (l[1].endswith('&') or l[1].endswith('*')):\n need_comment = True\n break\n #rvalue\n if line.find('&&') >= 0:\n need_comment = True \n break \n\n if line.find('ostream') >= 0 or line.find('fstream') >= 0 or line.find('ofstream') >= 0:\n need_comment = True\n break\n\n #real virtual\n if line.replace(' ','').endswith(')=0'):\n full_class_name = '::'.join(stack_namespace) + '::' + '::'.join(stack_class) \n if not full_class_name in abstract_classes:\n abstract_class_out.write(\"%s\\t%s\\n\"%(full_class_name, input_file))\n abstract_classes.add(full_class_name)\n need_comment = True\n break \n #return iterator\n if len(l) > 1 and (l[1] == 'begin()' or l[1] == 'end()' or l[1] == 'cbegin()' or l[1] == 'cend()'):\n need_comment = True\n break \n if len(l) > 1 and (l[0].endswith('&') or l[0].endswith('*')):\n return_nonconst_ref = True\n if return_nonconst_ref:\n contents = content.split('\\n')\n i = len(contents) -1\n find = False\n while i >= 0:\n #确保最后一个return是正确书写的没有干扰\n if vec_ref_pattern.search(contents[i]):\n find = True\n break\n i -= 1\n if find:\n need_comment = True\n if need_comment:\n lines = ['//' + line for line in lines if line != '']\n for i in range(len(lines) - 2):\n lines[i] = lines[i] + '//func'\n return '\\n'.join(lines).strip() + ';//func\\n'\n\n\ndef count_pair(line, pl, pr, nl, nr):\n pos = -1\n i = 0\n for item in line:\n if item == pl:\n nl += 1\n elif item == pr:\n nr += 1\n if nl == nr and pos == -1:\n pos = i\n i += 1\n return nl,nr,pos\n\ndef count_bracket(line, nl, nr):\n return count_pair(line, '(', ')', nl, nr)\n\ndef count_pair_reverse(line, pl, pr, nl, nr):\n pos = -1\n i = len(line) - 1\n while i >= 0:\n item = line[i]\n if item == pl:\n nl += 1\n elif item == pr:\n nr += 1\n if nl == nr and pos == -1:\n pos = i\n i -= 1\n return nl,nr,pos\n\n\n\n\n#基本实现就是按照栈处理名称,区分是否class域的函数,忽略.h中已经实现函数{}内部的内容\n#@TODO 类构造函数特殊处理 结果按照函数处理 去掉所有实现和赋值\n#另外有些复杂写法的第三方库会运行脚本失败 @FIXME 不过对于python封装目前整体是work的\n#构造函数 当前如果没有: 也会正确按照函数处理, 注意如果 Abc(int x ): x(3)这种会处理失败 要求:必须换行写\n#特殊处理构造函数吧\n#不处理{与函数名同行的情况,可以预处理脚本先处理\ndef h2interface(input_file, output_file = ''):\n \"\"\"\n kernal function given a .h file\n convert to a .cc one with\n all the functions properly listed\n \"\"\"\n global pattern_comment\n\n global abstract_class_out\n global abstract_classes\n\n #----核心的函数匹配模式,不包括类构造函数\n pattern = re.compile(r\"\"\"(^[\\s]*) #leading withe space,we will find and delete after\n \t\t ([a-zA-Z~_] # void int likely the first caracter v or i...\n \t\t\t\t\t\t.* \n \t\t\t\t\t\t[)] #we find )\n \t\t\t\t\t\t#(?!\\s*=\\s*0) #if we find = 0 which means pur virtual we will not match after\n #(?=\\s*=\\s*0) \n \t\t\t\t\t\t(?!.*{) # we do not want the case int abc() const { return 1;}\n .*)\n \t\t\t\t\t\t(;.*) #we want to find ; and after for we will replace these later\n \t\t\t\t\t\t\\n$\n \t\t\t\t\t\t\"\"\",re.VERBOSE | re.MULTILINE | re.DOTALL)\n \n #----处理virtual,explicit,friend,static \n pattern2 = re.compile(r'(virtual\\s+|explicit\\s+|friend\\s+|static\\s+)') \n \n #我们默认函数都会有 如 abc( abc ( 这样的模式存在\n #但是operator 是个例外,类名要加在operaotr前面,而且不存在上面的模式\n #operator = () ClassName::operator = ()\n #pattern_func_name = re.compile(r'([a-zA-Z0-9~_\\-]+\\s*[(]|operator.*[(])') \n #难道替换不是仅仅替换括号里面的 而是全部替换? 恩,大括号 必须的 然后用\\1没有\\0 \n pattern_func_name = re.compile(r'([a-zA-Z0-9~_\\-]+\\s*|operator.*)[(]') \n\n pattern_template = re.compile('^\\s*template')\n #pattern_template_end = re.compile('^\\s*>\\s*$') #TODO why wrong?\n pattern_template_end = re.compile('>\\s*$')\n\n pattern_namespace = re.compile(r'namespace\\s+([a-zA-Z0-9~_\\-]+)\\s*{') #判断该行是否是 namespace出现 \n #p2 = re.compile(r'class\\s*(.*?)\\s*{|struct\\s*(.*?)\\s*{') \n #.*? 最小匹配 是否class出现,并记录class 名称\n #pattern_class = re.compile(r'^[\\s]*(class|struct)\\s+([a-zA-Z0-9_\\-]+)(?!.*;)') \n #匹配后面的;会造成流程错误,比如下面 gebp_traits;\n #template\n # class gebp_traits;\n # /** \\internal \\returns b if a<=0, and returns a otherwise. */\n # inline std::ptrdiff_t manage_caching_sizes_helper(std::ptrdiff_t a, std::ptrdiff_t b)\n # {\n # return a<=0 ? b : a;\n # }\n pattern_class = re.compile(r'^[\\s]*(class|struct|interface)\\s+([a-zA-Z0-9_\\-]+)') \n #modify 09.6.6 可以处理classa a 和 { 不在同一行,但是如果class 后发现;不处理\n #class一定是行开始或者前面可有空白\n\n pattern_start = re.compile('{')\n pattern_end = re.compile('}')\n \n stack = [] #----状态可能是normal_now(位于{}中间的时候),class_now,namespace_now\n #stack_class = [] #----存储class name\n global stack_class\n global stack_namespace\n stack_template = [] #----存储template name\n stack_typedef = [] #----存储当前class 作用域下的所有typedef得到的名称,函数返回类型需要\n \n first_convert = True #是否是第一次生成的实现文件\n \n #--------------------------------------文件处理\n func_sum = 0\n namespace_num = 0\n write_define = 0\n #--------------------------------------------------核心处理循环,逐行处理输入.h文件\n with open(input_file,'r') as f:\n if output_file == '':\n output_file\n f2 = open(output_file,'w')\n m = f.readlines()\n i = 0\n while i < len(m):\n #m[i] = m[i][:m[i].find('//')]\n line = m[i]\n if line.strip() == '':\n i += 1\n continue\n #-------------------------------------------判断是注释则略过 re.search(r'^s*$',line) 空行判断\n if re.search(r'^s*$',line) or pattern_comment.search(line): #/n or comment using //\n f2.write(m[i])\n i += 1\n continue\n if re.search('^\\s*/[*]', line): #comment using /* \n while (not re.search('[*]/\\s*$',line)): # */\n f2.write(m[i])\n i += 1\n line = m[i]\n f2.write(m[i])\n i += 1\n continue\n #---------------------------------------------判断是则define略过\n #define_match = re.search(r'^\\s*#define',line)\n define_match = line.lstrip().startswith('#define') \n if define_match:\n #while re.search(r'^\\s*$',line) or re.search(r'\\\\\\s*$', line):\n while line.rstrip().endswith('\\\\'):\n f2.write(m[i])\n i += 1\n line = m[i]\n f2.write(m[i])\n i += 1\n continue\n #-----------------------------------------------判断是否namespace\n match_namespace = pattern_namespace.search(line)\n two_lines = ''\n if not match_namespace:\n #--尝试看是否两行代表一个namespace\n if i + 1 < len(m) and m[i + 1].lstrip().startswith('{'):\n two_lines = line.rstrip() + '{'\n match_namespace = pattern_namespace.search(two_lines)\n if match_namespace: #we face namespace\n stack.append('namespace_now')\n namespace_num += 1\n stack_namespace.append(match_namespace.group(1))\n f2.write(m[i])\n i += 1\n if two_lines != '':\n f2.write(m[i])\n i += 1\n continue \n\n #----------------------------------------------------判断并处理类里面的typedef\n if (len(stack) > 0 and stack[-1] == 'class_now'):\n pattern_typedef = re.compile(r'typedef\\s+.*\\s+(.*);')\n match_typedef = pattern_typedef.search(line)\n if match_typedef:\n stack_typedef.append(match_typedef.group(1))\n #----------------------------------------------------判断并处理模板情况\n match_template = pattern_template.search(line)\n template_string = ''\n if match_template:\n template_string = line\n find1, find2, pos= count_pair(line, '<', '>', 0, 0)\n while(not find1):\n #f2.write(m[i])\n i += 1\n line = m[i]\n template_string += line \n find1, find2, pos = count_pair(m[i], '<', '>', find1, find2)\n while (pos == -1):\n #f2.write(m[i])\n i += 1\n line = m[i]\n template_string += line\n find1, find2, pos = count_pair(m[i], '<', '>', find1, find2)\n #f2.write(m[i])\n i += 1\n line = m[i]\n #--------------------------------------------判断是否是class 或者遇到 { start\n match_class = pattern_class.search(line) \n match_start = pattern_start.search(line)\n sentence_ends = line.rstrip().endswith(';')\n if match_class: #we face a class \n if template_string != '':\n f2.write(template_string)\n template_string = ''\n if not sentence_ends:\n stack_template.append(template_string)\n stack.append('class_now')\n class_name = match_class.group(2) #TODO f2.group(1)如果为空则异常\n #-----------模板类特化或者偏特化的情况 如 class A > 为了获得整个名称\n if '<' in class_name: \n k = line.index('<')\n fit = 1;\n for l in range(k+1, len(line)):\n if line[l] == '<':\n fit += 1\n if line[l] == '>':\n fit -= 1\n if (fit == 0):\n break\n class_name += line[k+1:l+1]\n stack_class.append(class_name)\n while not match_start:\n f2.write(m[i])\n i += 1\n line = m[i]\n match_start = pattern_start.search(line)\n\n if match_class.group(1) == 'interface':\n full_class_name = '::'.join(stack_namespace) + '::' + '::'.join(stack_class) \n if not full_class_name in abstract_classes:\n abstract_class_out.write(\"%s\\t%s\\n\"%(full_class_name, input_file))\n abstract_classes.add(full_class_name)\n f2.write(m[i])\n i += 1\n continue\n\n #-------------------------------------------------判断是否是结束符号 }\n match_end = pattern_end.search(line)\n if match_start:\n stack.append('normal_now')\n if match_end:\n #print '$$$', line, len(stack)\n top_status = stack.pop()\n if top_status == 'namespace_now':\n namespace_num -= 1\n stack_namespace.pop()\n elif top_status == 'class_now':\n stack_class.pop()\n stack_template.pop()\n stack_typedef = []\n if match_start or match_end:\n f2.write(m[i]) #already done in if match_end\n i += 1\n continue\n #注意我判断是函数只是根据 我看到该行有) 然后 后面有; important!!\n #------------------------------------------------就像忽略注释一样忽略normal_now状态下的行,因为那是在{}中间的实现\n if len(stack) >0 and stack[-1] == 'normal_now': \n f2.write(m[i])\n i += 1\n continue\n #---------------------------------------------------------下面我们该处理需要生成实体框架的函数了,\n #deal with\n #int abc(int a,\n # \t\t int b) #能够处理这种(与)不在同一行的情况\n find1 = line.find('(') >= 0\n if not find1:\n f2.write(m[i])\n i += 1\n continue\n start_i = i\n \n find1, find2, pos = count_bracket(line, 0, 0)\n while (pos == -1):\n i += 1\n line2 = m[i].lstrip()\n line += line2\n find1, find2, pos = count_bracket(m[i], find1, find2)\n\n is_constructor = False\n if len(stack_class) > 0 and len(stack) > 0 and stack[-1] == 'class_now':\n class_name = stack_class[-1]\n if line.lstrip().startswith(class_name + '('):\n is_constructor = True\n\n match_start = pattern_start.search(m[i])\n match_end = pattern_end.search(m[i])\n if (match_start): # like ) { or ) {} int the last line\n if not match_end:\n stack.append('normal_now')\n j = start_i #fixed 09.11.17\n while (j <= i):\n f2.write(m[j])\n j += 1\n i += 1\n continue\n\n #here we do the kernel sub #--------------------------------如果找到,先进行了替换abc();->abc(){}\n #this is important without these will -> #if __GNUC__ > 3 || defined(WIN32) -> #if __GNUC__ > 3 || defined(WIN32); as function..\n #(line,match) = pattern.subn(r'\\2 \\n{\\n\\n}\\n\\n',line) \n no_mark = 0\n func_line_temp = line \n if not re.search(';\\s*$', line): #默认情况下将加上;使得它可以被转移到实现文件中\n line = line.rstrip()\n line += ';\\n'\n no_mark = 1\n func_line_temp = line\n\n if is_constructor:\n if line.find('):') > 0 or line.find(') :') > 0:\n line = line[:line.rfind(':')] + ';\\n'\n m[i] = m[i][:m[i].rfind(':')]\n\n if no_mark:\n if not re.search(r'^\\s*{\\s*$', m[i+1]):\n if not is_constructor:\n j = start_i \n while (j <= i):\n f2.write(m[j])\n j += 1\n i += 1\n continue\n else:\n while (not re.search(r'^\\s*{\\s*$', m[i+1])):\n m[i + 1] = ''\n i += 1\n\n (line,match) = pattern.subn(r'\\2\\n',line) #key sub!!! 比如最后的; 去掉void play(); -> void play()\n\n #print '^^^', line\n #print '[' + line + ']' + '(' + str(match) + ')'\n #temp add 尝试兼容返回值在单独一行的情况\n if re.search(r'^\\s*(inline)?\\s*[a-zA-Z0-9_]+\\s*$', m[start_i - 1]):\n line = m[start_i - 1] + line\n line = line.lstrip() \n #match = 1\n if (not match): \n f2.write(m[i]) \n i += 1\n continue\n #-------------------------------------------------------------OK,找到了函数,下面进行处理后输出\n friend_match = re.search('friend ',line)\n #line = pattern2.sub('',line) #--------------------delete virtural explict friend! 由于现在只是输出interface 所以不去掉!\n func_name = ''\n template_line = ''\n if len(stack_class) > 0 and not friend_match : #-----类成员函数class status if friend we will not add class name\n line = template_line + template_string + line; \n #line = template_line + template_string + line2; #must use line2.. \n func_name = re.search('^.*\\)',line,re.MULTILINE|re.DOTALL).group()\n else: #--------------------------------普通函数(非类成员函数)的情况!\n stack_template.append(template_string)\n if (stack_template[-1] != ''):\n template_line = re.sub(r'\\s*template','template',stack_template[-1])\n #------------------delete < class T = a, class U = A(3)> -> \n template_line = re.sub('\\s*=.*>(\\s*)$',r'>\\1',template_line) #代码重复,TODO以后整合 \n template_line = re.sub(r'\\s*=.*,',',',template_line)\n template_line = re.sub(r'\\s*=.*','',template_line)\n line = template_line + line\n #line = template_line + line2\n stack_template.pop()\n func_name = re.search('^.*\\)',line,re.MULTILINE|re.DOTALL).group()\n\n #--------------------------------------------------------把已经在头文件定义的代码也拷贝过去\n content = ''\n lmatch = 0\n #特殊的写法对于{单独一行的情况把其上函数在头文件定义的代码也拷贝过去\n #@NOTICE 注意 }}; 会有问题 , 预处理format-cplusplus.py会处理去掉这种可能,多个{}都加回车转移到单独的行\n if i + 1 < len(m) and re.search(r'^\\s*{\\s*$', m[i+1]): \n i = i + 2\n lmatch = 1\n while (lmatch != 0):\n if (not pattern_comment.search(m[i])) and re.search('{', m[i]): #唯一可能的问题是注释 // if (n > 1) {i\n lmatch += 1\n if (not pattern_comment.search(m[i])) and re.search(r'}',m[i]):\n lmatch -= 1\n content += m[i].lstrip()\n i += 1\n i -= 1\n\t\t\t\t\t\t#-------------------------------------------------------------------------加上上面的注释也拷贝过去 \n #----------------------------------------------如果函数已经在实现文件中存在,不输出\n #@NOTICE 查看结果debug重要的打印\n #print '----', line, i #完整的函数 带有上面template\n #print '####',func_line_temp, i #只有函数 不带template,\n line = pyplusplus_hack(line, content)\n f2.write(line)\n i += 1 #-----------------------------------------------------------------------next line处理下一行\n #------------------------------loop done 处理结束 \n #print('Added %d functions'%func_sum)\n f2.close()\n\n\n#-----------------------------------------------------------user input\ndef main(argv): \n global input_file \n try: \n opts, args = getopt.getopt(argv, \"h\", [\"help\"]) \n except getopt.GetoptError: \n print(usage.__doc__) \n sys.exit(2)\n\n if len(opts) > 0:\n for o, a in opts: \n if o in (\"-h\", \"--help\"): \n print(usage.__doc__) \n sys.exit()\n if len(args) > 0:\n input_file = args[0]\n output_file = input_file.replace('.h', '.i')\n if len(args) > 1:\n output_file = args[1]\n h2interface(input_file, output_file)\n else:\n print(usage.__doc__)\n sys.exit()\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"python-wrapper-gccxml/h2interface.py","file_name":"h2interface.py","file_ext":"py","file_size_in_byte":22784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"535350262","text":"\"\"\"Given a singly linked list of size N. The task is to swap elements in the linked list pairwise.\nFor example, if the input list is 1 2 3 4, the resulting list after swaps will be 2 1 4 3.\nNote: You need to swap the nodes, not only the data. If only data is swapped then driver will print -1.\n\nExample 1:\n\nInput:\nLinkedList: 1->2->2->4->5->6->7->8\nOutput: 2 1 4 2 6 5 8 7\nExplanation: After swapping each pair\nconsidering (1,2), (2, 4), (5, 6).. so\non as pairs, we get 2, 1, 4, 2, 6, 5,\n8, 7 as a new linked list.\"\"\"\n\nclass Solution:\n def pairWiseSwap(self, head):\n if head.next is None and head:\n return head\n\n p = head\n new_head = p.next\n\n while(p):\n q = p.next\n temp = q.next\n q.next = p\n if temp == None or temp.next == None:\n p.next = temp\n break\n p.next = temp.next\n p = temp\n return new_head\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n self.tail = None\n\n def insert(self, val):\n if self.head == None:\n self.head = Node(val)\n self.tail = self.head\n else:\n self.tail.next = Node(val)\n self.tail = self.tail.next\n\ndef printList(n):\n while(n):\n print(n.data, end = \" \")\n n = n.next\n print(\" \")\n\nt = int(input())\nfor i in range(t):\n n = int(input())\n arr = list(map(int, input().strip().split()))\n lis = LinkedList()\n for i in arr:\n lis.insert(i)\n\n dict1 = {}\n temp = lis.head\n while(temp):\n dict1[temp] = temp.data\n temp = temp.next\n\n failure = LinkedList()\n failure.insert(-1)\n\n head = Solution().pairWiseSwap(lis.head)\n\n temp = head\n f = 0\n while(temp):\n if dict1[temp] != temp.data:\n f = 1\n temp = temp.next\n\n if f:\n printList(failure)\n else:\n printList(head)\n","sub_path":"Linked_List/pairwise_swap_linked_list.py","file_name":"pairwise_swap_linked_list.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"212650424","text":"# -*- coding: utf-8 -*-\r\n# Автор: Пензов Сергей\r\n# картинки 400 х 400 маркировка правой нижней клетки серым цветом + шум\r\n\r\n# Подключение модулей\r\n\r\nimport os, tkinter, random\r\nfrom PIL import Image, ImageTk, ImageDraw\r\n\r\n# dir_name = \"nums\"\r\nSIDE = 4\r\n#IMG = \"23.jpg\"\r\nimages_list = (\"1.jpg\",\"2.jpg\",\"3.jpg\",\"4.jpg\",\"5.jpg\",\"6.jpg\",\"7.jpg\",\"8.jpg\",\r\n \"9.jpg\",\"10.jpg\",\"11.jpg\",\"12.jpg\",\"13.jpg\",\"14.jpg\",\"15.jpg\",\"16.jpg\",\r\n \"17.jpg\",\"18.jpg\",\"19.jpg\",\"20.jpg\",\"21.jpg\",\"22.jpg\",\"23.jpg\",\"24.jpg\",\r\n \"25.jpg\",\"26.jpg\",\"27.jpg\",\"28.jpg\",\"29.jpg\",\"30.jpg\",\"31.jpg\",\"32.jpg\",\"33.jpg\",\"34.jpg\")\r\n\r\nIMG = images_list[random.randint(0,len(images_list)-1)]\r\nmoves = 0\r\n\r\n# Окончание игры путем сравнения расположения фишек\r\n# с первоначальным положением индексов картинок\r\np=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] # начальный список индексов\r\ndef IsSolution():\r\n result = True\r\n for i in p:\r\n if p[i] != i:\r\n result = False\r\n break\r\n return result\r\n\r\n\r\ndef label_above(curr):\r\n ''' Вернуть соседа сверху\r\n '''\r\n return labels[(curr.row - 1) * SIDE + curr.column]\r\n\r\n\r\ndef label_under(curr):\r\n ''' Вернуть соседа снизу\r\n '''\r\n return labels[(curr.row + 1) * SIDE + curr.column]\r\n\r\n\r\ndef label_left(curr):\r\n ''' Вернуть соседа слева\r\n '''\r\n return labels[curr.row * SIDE + curr.column - 1]\r\n\r\n\r\ndef label_right(curr):\r\n ''' Вернуть соседа справа\r\n '''\r\n return labels[curr.row * SIDE + curr.column + 1]\r\n\r\n\r\ndef render(curr, near):\r\n ''' Отрисовка расположения двух клеток\r\n '''\r\n # if near is not None:\r\n if near:\r\n curr.grid(row=curr.row, column=curr.column)\r\n near.grid(row=near.row, column=near.column)\r\n\r\n\r\ndef exchange(curr, near):\r\n ''' Обмен местами клеток в общем списке\r\n '''\r\n # if near is not None:\r\n global EndOfGame\r\n global p\r\n global moves\r\n if near:\r\n ci = curr.row * SIDE + curr.column\r\n ni = near.row * SIDE + near.column\r\n labels[ci], labels[ni] = labels[ni], labels[ci]\r\n\r\n p[ci],p[ni] = p[ni],p[ci] # обмен индексов\r\n\r\n # Вывод количества ходов\r\n\r\n moves += 1\r\n label_3 = tkinter.Label(main_window, text=str(moves))\r\n label_3.grid(row=5, column=1)\r\n if IsSolution() and moves>0:\r\n label_4 = tkinter.Label(main_window, text='Победа!')\r\n label_4.grid(row=6, column=0)\r\n EndOfGame=True\r\n\r\n\r\ndef key_press(btn):\r\n ''' Основная логика перемещения на игровом поле.\r\n Основной элемент логики - пустая клетка - от неё определяем соседа.\r\n Потом меняем координаты пустой клетки и соседа.\r\n '''\r\n near = None # <- None - специальное значение в Питоне - \"ничто\"\r\n\r\n global EndOfGame # При окончании игры отключаем клавиши\r\n # EndOfGame = False\r\n if not(EndOfGame):\r\n if btn == 'r' and curr.column > 0:\r\n # print('Вправо')\r\n near = label_left(curr)\r\n curr.column -= 1\r\n near.column += 1\r\n elif btn == 'l' and curr.column < SIDE - 1:\r\n # print('Влево')\r\n near = label_right(curr)\r\n curr.column += 1\r\n near.column -= 1\r\n elif btn == 'u' and curr.row < SIDE - 1:\r\n # print('Вверх')\r\n near = label_under(curr)\r\n curr.row += 1\r\n near.row -= 1\r\n elif btn == 'd' and curr.row > 0:\r\n # print('Вниз')\r\n near = label_above(curr)\r\n curr.row -= 1\r\n near.row += 1\r\n\r\n exchange(curr, near)\r\n render(curr, near)\r\n\r\n\r\ndef mix_up():\r\n ''' Перемешивание клеток\r\n SIDE ** 4 - взято для лучшего перемешивания,\r\n т.к. не все вызовы функции нажатия кнопок\r\n будут приводить к движению клеток на поле\r\n '''\r\n global moves\r\n buttons = ['d', 'u', 'l', 'r']\r\n for i in range(SIDE ** 4):\r\n x = random.choice(buttons) # <- choice - функция из модуля random\r\n # print('ход {}: {}'.format(i, x))\r\n key_press(x)\r\n moves = -1\r\n\r\n'''\r\n# выделение правого нижнего квадратика серым цветом для новых картинок\r\n\r\ndef markir():\r\n image = Image.open(IMG)\r\n\r\n draw = ImageDraw.Draw(image)\r\n width = image.size[0]\r\n height = image.size[1]\r\n pix = image.load()\r\n\r\n for i in range(width-width//4,width):\r\n for j in range(height-height//4,height):\r\n a = pix[i, j][0]\r\n b = pix[i, j][1]\r\n c = pix[i, j][2]\r\n s = (a + b + c) // 3\r\n draw.point((i, j), (s, s, s))\r\n image.save(IMG)\r\n\r\n# добавление шумов в правый нижний угол\r\n\r\ndef shum():\r\n image = Image.open(IMG)\r\n factor = 50\r\n draw = ImageDraw.Draw(image)\r\n width = image.size[0]\r\n height = image.size[1]\r\n pix = image.load()\r\n\r\n for i in range(width-width//4,width):\r\n for j in range(height-height//4,height):\r\n rand = random.randint(-factor, factor)\r\n a = pix[i, j][0] + rand\r\n b = pix[i, j][1] + rand\r\n c = pix[i, j][2] + rand\r\n if (a < 0):\r\n a = 0\r\n if (b < 0):\r\n b = 0\r\n if (c < 0):\r\n c = 0\r\n if (a > 255):\r\n a = 255\r\n if (b > 255):\r\n b = 255\r\n if (c > 255):\r\n c = 255\r\n draw.point((i, j), (a, b, c))\r\n image.save(IMG)\r\n'''\r\ndef get_regions(image):\r\n ''' Функция разбиения изображения на квадратики.\r\n На входе ожидает объект PIL.Image\r\n Возвращает список картинок-квадратиков ImageTk.PhotoImage\r\n '''\r\n regions = []\r\n pixels = image.width // SIDE\r\n for i in range(SIDE):\r\n for j in range(SIDE):\r\n x1 = j * pixels\r\n y1 = i * pixels\r\n x2 = j * pixels + pixels\r\n y2 = i * pixels + pixels\r\n box = (x1, y1, x2, y2)\r\n region = image.crop(box)\r\n region.load()\r\n regions.append(ImageTk.PhotoImage(region))\r\n return regions\r\n\r\n\r\nmain_window = tkinter.Tk()\r\nmain_window.title(\"Puzzle 15\")\r\n\r\n# Включить обе процедуры для новых картинок\r\n# markir()\r\n# shum()\r\n\r\nimage=Image.open(IMG)\r\nimage_objects_list = get_regions(image)\r\n\r\n\r\nlabels = []\r\n\r\nfor i in range(SIDE):\r\n for j in range(SIDE):\r\n # переход от 2D в 1D\r\n x = i * SIDE + j\r\n label = tkinter.Label(main_window, image=image_objects_list[x])\r\n label.grid(row=i, column=j)\r\n # дополнительные атрибуты объекта label\r\n label.row = i\r\n label.column = j\r\n label.x = x\r\n labels.append(label)\r\n\r\ncurr = labels[-1]\r\n\r\n\r\n\r\nlabel_2 = tkinter.Label(main_window, text='Ходов = ')\r\nlabel_2.grid(row=5,column=0)\r\n\r\n# mix_up\r\nEndOfGame=False\r\n# if moves<=0 and IsSolution():\r\nmain_window.after(2000, mix_up) # Перемешивание после временной задержки\r\n\r\n\r\nmain_window.bind('', lambda x: key_press('u'))\r\nmain_window.bind('', lambda x: key_press('d'))\r\nmain_window.bind('', lambda x: key_press('l'))\r\nmain_window.bind('', lambda x: key_press('r'))\r\n# main_window.bind('', lambda x: exit(0)) # Почему-то не работало\r\n\r\nmain_window.mainloop()\r\n","sub_path":"game15_img.py","file_name":"game15_img.py","file_ext":"py","file_size_in_byte":8244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"444972397","text":"import maya.cmds as cmds\nimport maya.OpenMayaAnim as animAPI\n\nclass AlembicExporter:\n def __init__(self):\n pass\n\n def create(self):\n self.BuildLayout()\n\n def BuildLayout(self):\n # Setting up window and layout stuff.\n self.window = cmds.window(widthHeight=(400,100), title=\"Alembic Exporter\", resizeToFitChildren=1)\n cmds.columnLayout(rowSpacing=5)\n cmds.rowLayout(numberOfColumns=3)\n cmds.text(label=\"Repository Path:\")\n self.pathField = cmds.textField(placeholderText=\"E:\\Git Repos\\senior-kaiju-film\",width=200)\n self.fileButton = cmds.button(label=\"Find Directory\", command=lambda x: self.openFileDialog())\n cmds.setParent('..')\n cmds.rowLayout(numberOfColumns=3)\n cmds.text(label=\"File Depth\")\n self.depthCollection = cmds.radioCollection()\n self.depth01 = cmds.radioButton(label=\"1\")\n self.depth02 = cmds.radioButton(label=\"2\")\n cmds.setParent('..')\n cmds.rowLayout(numberOfColumns=3)\n self.checkBoxGroup = cmds.checkBoxGrp(numberOfCheckBoxes=3, labelArray3=['Zilla','Kong','Princess'])\n cmds.setParent('..')\n cmds.button(label=\"Execute\",command=lambda x: self.Execute())\n cmds.setParent('..')\n cmds.setParent('..')\n \n #allowedAreas = ['right', 'left']\n #cmds.dockControl( area='left', content=myWindow, allowedArea=allowedAreas )\n cmds.showWindow(self.window)\n\n def Export(self, repoDirectory, depth, value1, value2, value3):\n selection = cmds.ls(geometry=True) # Restrict by characters\n # Start and end are determined by the time slider.\n start = animAPI.MAnimControl.minTime().value()\n end = animAPI.MAnimControl.maxTime().value()\n\n # Picking which geometry will be exported.\n rootZilla = [\"Zilla:LowerTeeth_Combined_geo\",\"Zilla:Body_highPoly_9_28_geo\",\"Zilla:Body_highPoly_9_28_geo1\",\"Zilla:L_Eye_geo\",\"Zilla:R_Eye_geo\",\"Zilla:Tongue_highPoly_geo\",\"Zilla:UpperGums_lowPoly_geo\",\"Zilla:UpperTeeth_Combined_geo\",\"Zilla:LowerGums_lowPoly_geo\",\"Zilla:LowerTeethFinal\",\"Zilla:UpperTeethFinal\",\"Zilla:Zilla_MultiUdim:R_Eye_geo\",\"Zilla:Zilla_MultiUdim:L_Eye_geo\",\"Zilla:Zilla_MultiUdim:Tongue_highPoly_geo\",\"Zilla:Zilla_MultiUdim:LowerTeethFinal\",\"Zilla:Zilla_MultiUdim:UpperTeethFinal\"]\n rootKong = [\"Kong:Kong_HighPoly_geo_Copy\",\"Kong:R_TempEye_geo\",\"Kong:L_TempEye_geo\",\"Kong:Kong_Model_05:Tongue\",\"Kong:Kong_Model_05:UpperteethFinal\",\"Kong:Kong_Model_05:lowerTeethFinal\"]\n rootPrincess = [\"Princess:Top_Teeth\",\"Princess:Bottom_Teeth\",\"Princess:Tongue\",\"Princess:L_Eye_Gloss_Geo\",\"Princess:Eye_White_Geo\",\"Princess:Eye_Pupil_Geo\",\"Princess:R_Eye_Gloss_Geo\",\"Princess:Eye_White_Geo\",\"Princess:Eye_Pupil_Geo\",\"Princess:Princess_Mesh_New\"]\n root = \"\"\n if value1 == True:\n for x in rootZilla:\n root += \" -root \" + x\n if value2 == True:\n for x in rootKong:\n root += \" -root \" + x\n if value3 == True:\n for x in rootPrincess:\n root += \" -root \" + x\n\n # Creating string describing file path of new alembic.\n self.filename = cmds.file(query=True,sn=1) # Querying filename of current scene to isolate scene number.\n splitFilename = self.filename.split('/')\n holding = splitFilename[depth]\n holding2 = holding.split(' ')\n shotNum = holding2[1] # Isolate shot number, eg. 05\n targetFolder = \"Shot \" + shotNum\n save_name = \"\\\"\" + repoDirectory + \"/Senior Project Big Files/Animation/Alembic/\" + targetFolder + \"/Shot\" + shotNum + \"_Alembic.abc\\\"\"\n\n # Assembling final AbcExport command arguments\n command = \"-frameRange \" + str(int(start)) + \" \" + str(int(end)) +\" -uvWrite -worldSpace -writeUVSets -stripNamespaces -renderableOnly\" + root + \" -file \" + save_name\n cmds.AbcExport ( j = command ) # Export\n\n # Controls the file browser\n def openFileDialog(self, *args):\n filePath = cmds.fileDialog2(fileMode=3)\n cmds.textField(self.pathField, edit = True, tx = filePath[0])\n\n def Execute(self):\n repoInput = cmds.textField(self.pathField, query=1, text=1) # File path of repo\n depth01 = cmds.radioButton(self.depth01, query=True, select=True)\n if depth01 == True:\n depth = -2\n else:\n depth = -3\n value1 = cmds.checkBoxGrp(self.checkBoxGroup, query=True, value1=1) # Zilla checked?\n value2 = cmds.checkBoxGrp(self.checkBoxGroup, query=True, value2=1) # Kong checked?\n value3 = cmds.checkBoxGrp(self.checkBoxGroup, query=True, value3=1) # Princess checked?\n print(depth)\n self.Export(repoInput, depth, value1, value2, value3)\n\ntest = AlembicExporter()\ntest.create()","sub_path":"AlembicExporter.py","file_name":"AlembicExporter.py","file_ext":"py","file_size_in_byte":4794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"437120134","text":"\"\"\"\n写入数据库示例2\n\"\"\"\n\nimport pymysql\n\n# 链接数据库\ndb = pymysql.connect(host = \"localhost\",\n port = 3306,\n user=\"root\",\n password='123456',\n database=\"stu\",\n charset=\"utf8\")\n\n# 创建游标 (调用sql语句,获取执行结果)\ncur = db.cursor()\n\n# 写数据操作\nl = [\n ('Dave',15,'m',81),\n ('Ala',16,'w',82),\n ('Baron',17,'m',83)\n]\ntry:\n sql = \"insert into cls (name,age,sex,score) values (%s,%s,%s,%s);\"\n\n # for i in l:\n # cur.execute(sql,i)\n\n cur.executemany(sql,l) # 执行多次sql语句\n\n db.commit() # 提交\nexcept Exception as e:\n print(e)\n db.rollback() # 回滚\n\n\n\n# 关闭游标和数据库\ncur.close()\ndb.close()","sub_path":"day10/write_db2.py","file_name":"write_db2.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"430628839","text":"from email.mime.application import MIMEApplication\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nfrom email.utils import formatdate\r\nfrom email import message_from_string\r\nimport smtplib\r\nimport imaplib\r\nimport os\r\n\r\n\r\nclass Email:\r\n\r\n def __init__(self, email_type='error', use_tag=True):\r\n self.__recipients = 'vitaliy.ch@mserverone.com'\r\n self.__smtp = 'mail.mserverone.com'\r\n self.__port = 465\r\n self.__sender = 'autotest@mserverone.com'\r\n self.__subject = '[AUTOMATED]'\r\n self.__email_type = email_type\r\n self.__body_title = ''\r\n self.__body_settings = ''\r\n self.__use_tag = use_tag\r\n\r\n def set_recipients(self, recipients):\r\n self.__recipients = recipients\r\n\r\n def set_subject(self, subject):\r\n self.__subject = ' '.join((self.__subject, subject)) if self.__use_tag else subject\r\n\r\n def set_body_title(self, title):\r\n self.__body_title = title.capitalize()\r\n\r\n def set_body_settings(self, settings):\r\n self.__body_settings = settings\r\n\r\n def __set_error_style(self, message):\r\n if self.__body_title == '':\r\n self.__body_title = self.__subject\r\n return '%s:\\n\\n%s\\n\\nError text:\\n%s' % (self.__body_title, self.__body_settings, message)\r\n\r\n def __set_notification_style(self, message):\r\n if self.__body_title != '':\r\n self.__body_title += '\\n\\n'\r\n return '%s%s' % (self.__body_title, message)\r\n\r\n def __set_message_style(self, message):\r\n if self.__email_type == 'error':\r\n return self.__set_error_style(message)\r\n if self.__email_type == 'notification':\r\n return self.__set_notification_style(message)\r\n return message\r\n\r\n def send(self, message, file=None):\r\n msg = MIMEMultipart()\r\n msg['Subject'] = self.__subject\r\n msg['From'] = self.__sender\r\n msg['To'] = self.__recipients\r\n msg[\"Date\"] = formatdate(localtime=True)\r\n msg.attach(MIMEText(self.__set_message_style(message)))\r\n if file is not None:\r\n if isinstance(file, (list, tuple)):\r\n for f in file:\r\n part = MIMEApplication(open(f, 'rb').read(), _subtype='application/x-mobipocket-ebook')\r\n part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(f))\r\n msg.attach(part)\r\n else:\r\n part = MIMEApplication(open(file, 'rb').read(), _subtype='application/x-mobipocket-ebook')\r\n part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))\r\n msg.attach(part)\r\n s = smtplib.SMTP_SSL(host=self.__smtp, port=self.__port)\r\n s.send_message(msg)\r\n s.quit()\r\n\r\n\r\nclass Imap:\r\n\r\n def __init__(self, host='imap.mserverone.com', login='autotest@mserverone.com', pw='OarEnIcNob6', port=993):\r\n self.imap = imaplib.IMAP4_SSL(host=host, port=port)\r\n self.imap.login_cram_md5(login, pw)\r\n self.imap.select()\r\n\r\n def __del__(self):\r\n self.imap.close()\r\n self.imap.logout()\r\n\r\n def get_emails(self, condition=('ALL', 'UNSEEN')):\r\n emails = []\r\n typ, data = self.imap.sort('REVERSE DATE', 'UTF-8', *condition)\r\n for num in data[0].split():\r\n typ, data = self.imap.fetch(num, '(RFC822)')\r\n msg = message_from_string(data[0][1].decode('utf-8'))\r\n m = {'from': msg['From'], 'to': msg['To'], 'subject': msg['Subject'], 'body': self.get_body(msg)}\r\n emails.append(m)\r\n return emails\r\n\r\n def get_emails_by_alias(self, alias):\r\n return self.get_emails(condition=('TO {}'.format(alias), ))\r\n\r\n @staticmethod\r\n def get_body(msg):\r\n if msg.is_multipart():\r\n m = []\r\n for payload in msg.get_payload():\r\n m.append(payload.get_payload())\r\n return m\r\n else:\r\n return msg.get_payload()\r\n","sub_path":"custom_library/innogroup/innogroup/tools/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"375041418","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nProblem 10:\nCreated on Fri Jun 5 08:17:22 2020\n\n@author: krishnendu\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef fun(x):\n if abs(x)<1:\n return 1\n else :\n return 0\n \n \nxmin=-50 #xmin value\nxmax=50 #xmax value\n\n \ndef fourier(n):\n \n \n numpoints=n #number of sample points\n\n dx=(xmax-xmin)/(numpoints-1) \n\n sampled_data=np.zeros(numpoints)\n\n xarr=np.zeros(numpoints)\n\n for i in range(numpoints):\n sampled_data[i]=fun(xmin+i*dx) #sampling the data\n xarr[i]=xmin+i*dx\n\n nft=np.fft.fft(sampled_data,norm='ortho') #computing dft of the data using numpy.fft.fft\n\n karr=np.fft.fftfreq(numpoints,d=dx) #computing the frequencies \n\n karr=2*np.pi*karr\n factor=np.exp(-1j*karr*xmin)\n aft=dx*np.sqrt(numpoints/(2.0*np.pi))*factor*nft\n karr=np.fft.fftshift(karr) #shifting the frequencies\n\n aft=np.fft.fftshift(aft) #shifting the fourier transform\n\n plt.plot(karr,abs(aft)) #plotting the fourier transform computed by numpy.fft.fft\n \n plt.title(\"numpoints=\"+str(n))\n plt.suptitle(\"Fourier transform of the function\")\n plt.xlabel(\"frequency(k)\",size=14)\n plt.grid()\n plt.show()\n \nx=np.linspace(-5,5,100) \nplt.plot(x,[fun(x[i]) for i in range(len(x))]) \nplt.xlabel(\"x\",size=14)\nplt.ylabel(\"f(x)\",size=14)\nplt.title(\"plot of the function\",size=18)\nplt.grid()\nplt.show()\n\nfourier(512)\nfourier(1024)\nfourier(2048)\n\n \n\n","sub_path":"Problem_10.py","file_name":"Problem_10.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"536982101","text":"import os\n\n\nlisting = os.walk('.')\nfor path, directories, files in listing:\n print(path)\n for d in directories:\n print(d)\n for file in files:\n print(file)\n\n\ndef list_directories(s):\n def list_dir(d):\n nonlocal tab_stop\n files = os.listdir(d)\n for file in files:\n current_dir = os.path.join(d, file)\n if os.path.isdir(current_dir):\n print(\"\\t\" * tab_stop + \"Directory \" + file)\n tab_stop += 1\n list_dir(current_dir)\n tab_stop -=1\n else:\n print(\"\\t\" * tab_stop + file)\n\n\n\n tab_stop = 0\n if os.path.exists(s):\n print(\"Directory listing \" + s)\n list_dir(s)\n else:\n print(s + \"does not exist\")\n\n\n# def list_directories(p):\n# files = os.listdir(p)\n# for file in files:\n# print(\"1:\", file)\n# path = os.path.join(p, file)\n# print(\"2:\", path)\n\nlist_directories('.')\n","sub_path":"hello 2/5. recursive os module.py","file_name":"5. recursive os module.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"112560262","text":"import hashlib\nimport datetime\n\n# Basic bot config, insert your token here, update description if you want\nprefixes = [\"robo:\"]\ntoken = \"token-goes-here\"\nbot_description = \"Robocop-NG, the moderation bot of SecureChat\"\n\n# If you forked robocop-ng, put your repo here\nsource_url = \"https://github.com/cheesycod/robocop-ng\"\nrules_url = \"https://reswitched.team/discord/#rules\"\n\n# The bot description to be used in .robocop embed\nembed_desc = (\n \"Robocop-NG is developed by [Ave](https://github.com/aveao)\"\n \" and [tomGER](https://github.com/tumGER), and is a rewrite \"\n \"of Robocop.\\nRobocop is based on Kurisu by 916253 and ihaveamac.\"\n)\n\n\n# The cogs the bot will load on startup.\ninitial_cogs = [\n \"cogs.common\",\n \"cogs.admin\",\n \"cogs.verification\",\n \"cogs.mod\",\n \"cogs.mod_note\",\n \"cogs.mod_reacts\",\n \"cogs.mod_userlog\",\n \"cogs.mod_timed\",\n \"cogs.mod_watch\",\n \"cogs.basic\",\n \"cogs.logs\",\n \"cogs.err\",\n \"cogs.lockdown\",\n \"cogs.legacy\",\n \"cogs.remind\",\n \"cogs.robocronp\",\n \"cogs.meme\",\n \"cogs.invites\",\n \"cogs.pin\"\n]\n\n# The following cogs are also available but aren't loaded by default:\n# cogs.imagemanip - Adds a meme command called .cox.\n# Requires Pillow to be installed with pip.\n# cogs.lists - Allows managing list channels (rules, FAQ) easily through the bot\n\n\n# Minimum account age required to join the guild\n# If user's account creation is shorter than the time delta given here\n# then user will be kicked and informed\nmin_age = datetime.timedelta(minutes=5)\n\n# The bot will only work in these guilds\nguild_whitelist = [718563359179669587] # SecureChat discord\n\n# Named roles to be used with .approve and .revoke\n# Example: .approve User hacker\nnamed_roles = {\n \"god\": 719797799381762049,\n \"immortal god\": 719798012938944572,\n}\n\n# The bot manager and staff roles\n# Bot manager can run eval, exit and other destructive commands\n# Staff can run administrative commands\nbot_manager_role_id = 721074861203783801 # Bot management role in SecureChat (Owner)\nstaff_role_ids = [\n 718564387362701352, # Co-owner role in SecureChat\n 721074861203783801, # Bot management role in SecureChat\n 360138163156549632, # Admin role in SecureChat\n]\n\n# Various log channels used to log bot and guild's activity\n# You can use same channel for multiple log types\n# Spylog channel logs suspicious messages or messages by members under watch\n# Invites created with .invite will direct to the welcome channel.\nlog_channel = 721077211075182623 # server-logs in ReSwitched\nbotlog_channel = 721077032909275137 # bot-logs channel in ReSwitched\nmodlog_channel = 721077128988196954 # mod-logs channel in ReSwitched\nspylog_channel = 721076594440929392 # spy channel in ReSwitched\nwelcome_channel = 718742612688896021 # welcome channel in ReSwitched\ngeneral_channels = []\ncommunity_channels = []\n# Controls which roles are blocked during lockdown\n# Mute role is applied to users when they're muted\n# As we no longer have mute role on ReSwitched, I set it to 0 here\nmute_role = 718587078455197696 # Mute role in ReSwitched\n\n# Channels that will be cleaned every minute/hour.\n# This feature isn't very good rn.\n# See https://github.com/reswitched/robocop-ng/issues/23\nminutely_clean_channels = []\nhourly_clean_channels = []\n\n# Edited and deletes messages in these channels will be logged\nspy_channels = general_channels\n\n# All lower case, no spaces, nothing non-alphanumeric\nsuspect_words = [\n \"marijuana\" # Illegal\n \"porn\" # NSFW\n \"pornography\" # NSFW\n \"child porn\" # NSFW\n \"child pornography\" # NSFW\n]\n\n# List of words that will be ignored if they match one of the\n# suspect_words (This is used to remove false positives)\nsuspect_ignored_words = [\n]\n\n# == For cogs.links ==\nlinks_guide_text = \"\"\"**Generic starter guides:**\nNintendo Homebrew's Guide: \n\n**Specific guides:**\nManually Updating/Downgrading (with HOS): \nManually Repairing/Downgrading (without HOS): \nHow to set up a Homebrew development environment: \nGetting full RAM in homebrew without NSPs: As of Atmosphere 0.8.6, hold R while opening any game.\nCheck if a switch is vulnerable to RCM through serial: \n\"\"\"\n\n# == For cogs.verification ==\n# ReSwitched verification system is rather unique.\n# You might want to reimplement it.\n# If you do, use a different name for easier upstream merge.\n\n# https://docs.python.org/3.7/library/hashlib.html#shake-variable-length-digests\n_welcome_blacklisted_hashes = {\"shake_128\", \"shake_256\"}\n\n# List of hashes that are to be used during verification\nwelcome_hashes = tuple(hashlib.algorithms_guaranteed - _welcome_blacklisted_hashes)\n\n# Header before rules in #newcomers - https://elixi.re/i/opviq90y.png\nwelcome_header = \"\"\"\n Hi there. This server is protected by Robocop. Please either verify or DM an admin to consent please!\n \"\"\"\n\n# Rules in #newcomers - https://elixi.re/i/dp3enq5i.png\nwelcome_rules = (\n \"\"\"\n As we all know, every server has rules and this one does too:\n Ignorance of the rules does not justify breaking them\n 1) No being annoying in general. Breaking this may result in getting the Duck role. If you have the duck role, you are liable to extra punishment\n 2) Follow Discord ToS. Note that discussion of piracy is allowed however sharing of pirated content is not allowed whatsoever\n 3) No off topic conversation\n 4) Ask questions about the rules to a mod please\n If you agree to the rules, type \"I consent\" in #consent and we will let you in\n Remember to respect each others opinions\n Also about rp: You may only do one rp per day. Once your character has died, it is dead forever. You may only kill 3 cats per day. No mass killings are allowed without the mods permission. You are liable to be muted for breaking these rules. All roleplays are continuous. You may be in only one rp at one time. Contact an admin/co-owner/owner (me) if you want to start a roleplay. \n NOTE: By one rp, I mean you can only join one rp per day\n The following things are considered NSFW and are not allowed\n > Porn\n > Gore (includes suicide, but not someone needing support, just photos of someone killing themself)\n > Anything that's overly cursed like what makes you unable to sleep for a week\n That's about it.\n Everything else is cool. Just ignore the old NSFW rules\n It is not allowed to advertise discord servers unless it is in #invite. Once again, please DM me if you want the role\n NOTE: If you get 20 warnings over a period of 2 days, you will be muted\n If you do not like someone, do not be rude about them\n Homophobic/anti-LGBTQ+/other sorts of comments is not allowed here whatsoever\n Please be polite to other people and don't use a lot of slurs\n No drama whatsoever. Keep that to private groups and DM's. Failing to follow this will result in a warn, mute, kick or even a permanent ban\n NSFW is NOT permitted\n \"\"\"\n)\n\n\n# Footer after rules in #newcomers - https://elixi.re/i/uhfiecib.png\nwelcome_footer = (\n \"\"\"\n **Note: This channel is completely automated (aside from responding to questions about the rules). If your message didn't give you access to the other channels, you failed the test. Feel free to try again or DM an admin/staff**\n \"\"\",\n)\n\n# Line to be hidden in rules\nhidden_term_line = ' • When you have finished reading all of the rules, send a message in this channel that includes the {0} hex digest of your discord \"name#discriminator\", and bot will automatically grant you access to the other channels. You can find your \"name#discriminator\" (your username followed by a ‘#’ and four numbers) under the discord channel list. Look up hex digest online for more info or ask a mod to verify you!'\n\n# == Only if you want to use cogs.pin ==\n# Used for the pinboard. Leave empty if you don't wish for a gist pinboard.\ngithub_oauth_token = \"\"\n\n# Channels and roles where users can pin messages\nallowed_pin_channels = []\nallowed_pin_roles = []\n\n# Channel to upload text files while editing list items. (They are cleaned up.)\nlist_files_channel = 0\n\n# == Only if you want to use cogs.lists ==\n# Channels that are lists that are controlled by the lists cog.\nlist_channels = []\n\n# == Only if you want to use cogs.sar ==\nself_assignable_roles = {\n}\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":8484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"136581780","text":"birthdays = {\"vijju\" : \"may 5\", \"sagar\": \"june 30\", \"dhruv\" : \"sept 14\", \"pradeep\" : \"jan 16\"}\n\nwhile True:\n print(\"Enter a name to see their birthday (blank string to quit) :\")\n name = input()\n\n if name == '':\n break\n if name in birthdays:\n print(name + \"'s birthday is on :\" + birthdays[name])\n else:\n print(\"The name not in the list\")\n print(\"please enter the birth day : \")\n bday = input()\n birthdays[name] = bday\n print(\"The birthdays db is updated\")\n\nprint(birthdays)\n\n#the updated data will last as soon as we quit the program.\n# We should learn to copy and access data into the files\n","sub_path":"ch_5/birthdays.py","file_name":"birthdays.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"432500418","text":"\nfrom mattermost import MatterMost\nfrom mattermost import logger\n\nclass Team(MatterMost):\n def __init__(self, baseurl, team):\n super(Team, self).__init__(baseurl)\n self.url = self.base + '/teams'\n self.team = team\n\n def get_hooks_url(self):\n return self.url + \"/\" + self.find_team_id_by_name(self.team) + '/hooks'\n\n def get_incoming_hooks(self):\n self.use_login_token()\n req = self.get(self.get_hooks_url() + '/incoming/list')\n logger.debug(req.json())\n return req.json()\n\n def list_teams(self):\n self.use_login_token()\n req = self.get(self.url + \"/all\")\n json_str = req.json()\n for s in json_str.keys():\n logger.debug(\"Name:\" + json_str[s]['name'])\n logger.debug(\"ID: \" + json_str[s]['id'])\n return json_str\n\n def find_team_id_by_name(self, name):\n teams = self.list_teams()\n for key, val in teams.items():\n if val['name'] == name or val['display_name'] == name:\n return val['id']\n raise ValueError(name)\n","sub_path":"src/mattermost/team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"346189541","text":"from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\n\nfrom . import views\n\napp_name = \"posts\"\n\nrouter = DefaultRouter()\nrouter.register(r\"(?P.+)/comments\", views.PostCommentViewSet, basename=\"post-comment\")\n# router.register(\"m/\", views.UserViewSet)\n\nurlpatterns = [\n path(\"\", views.PostCreateView.as_view()),\n path(\"\", views.PostView.as_view(), name=\"post-detail\"),\n path(\"feed\", views.FeedView.as_view()),\n # path(\"/comments\", views.PostCommentView.as_view(), name=\"post-comment\"),\n path(\"/likes\", views.PostLikeView.as_view(), name=\"post-like\"),\n path(\"\", include(router.urls)),\n]\n","sub_path":"src/post/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"622768872","text":"import cv2\nimg=cv2.imread(\"number_plate.jpg\")\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\ngrayshow=cv2.imshow(\"GrayImage\", gray)\ncv2.waitKey(0)\n\ncv2.imwrite(\"gray_image.png\", gray)\ngaussian_blur=cv2.GaussianBlur(gray,(7,7),20)\ncv2.imshow(\"GAUSSIAN BLUR\",gaussian_blur)\ncv2.waitKey(0)\n\nvalue,otsu_thres=cv2.threshold (gaussian_blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\nprint(\"The Threshold value = {}\".format(value))\ncv2.imshow(\"OTSU THRESHOLD\",otsu_thres)\ncv2.waitKey(0)\ncv2.imwrite(\"otsu_number_plate_with gaussian.jpg\",otsu_thres)\n","sub_path":"number_plate_otsu_thresholding/otsu_thres.py","file_name":"otsu_thres.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"85860987","text":"from qgis.core import (QgsVectorLayer, QgsWkbTypes)\n\nfrom los_tools.processing.analyse_los.tool_extract_los_visibility_parts import ExtractLoSVisibilityPartsAlgorithm\nfrom los_tools.constants.field_names import FieldNames\n\nfrom tests.AlgorithmTestCase import QgsProcessingAlgorithmTestCase\n\nfrom tests.utils_tests import (get_data_path, get_data_path_results)\n\n\nclass ExtractPointsLoSAlgorithmTest(QgsProcessingAlgorithmTestCase):\n\n def setUp(self) -> None:\n\n super().setUp()\n\n self.los_global = QgsVectorLayer(get_data_path(file=\"los_global.gpkg\"))\n\n self.los_local = QgsVectorLayer(get_data_path(file=\"los_local.gpkg\"))\n\n self.los_no_target = QgsVectorLayer(get_data_path(file=\"no_target_los.gpkg\"))\n\n self.alg = ExtractLoSVisibilityPartsAlgorithm()\n self.alg.initAlgorithm()\n\n def test_parameters(self) -> None:\n\n self.assertQgsProcessingParameter(self.alg.parameterDefinition(\"LoSLayer\"),\n parameter_type=\"source\")\n self.assertQgsProcessingParameter(self.alg.parameterDefinition(\"OutputLayer\"),\n parameter_type=\"sink\")\n self.assertQgsProcessingParameter(self.alg.parameterDefinition(\"CurvatureCorrections\"),\n parameter_type=\"boolean\",\n default_value=True)\n self.assertQgsProcessingParameter(self.alg.parameterDefinition(\"RefractionCoefficient\"),\n parameter_type=\"number\",\n default_value=0.13)\n\n def test_alg_settings(self) -> None:\n\n self.assertAlgSettings()\n\n def test_check_wrong_params(self) -> None:\n\n # use layer that is not correctly constructed LoS layer\n params = {\"LoSLayer\": QgsVectorLayer(get_data_path(file=\"no_target_los_wrong.gpkg\"))}\n\n self.assertCheckParameterValuesRaisesMessage(\n parameters=params,\n message=\"Fields specific for LoS not found in current layer (los_type).\")\n\n def test_run_alg(self) -> None:\n\n output_path = get_data_path_results(file=\"los_parts.gpkg\")\n\n params = {\n \"LoSLayer\": self.los_local,\n \"OutputLayer\": output_path,\n \"CurvatureCorrections\": True,\n \"RefractionCoefficient\": 0.13\n }\n\n self.assertRunAlgorithm(parameters=params)\n\n los_parts = QgsVectorLayer(output_path)\n\n self.assertQgsVectorLayer(los_parts,\n geom_type=QgsWkbTypes.MultiLineStringZ,\n crs=self.los_local.sourceCrs())\n\n self.assertFieldNamesInQgsVectorLayer(\n [FieldNames.ID_OBSERVER, FieldNames.ID_TARGET, FieldNames.VISIBLE], los_parts)\n\n self.assertEqual(los_parts.featureCount(), self.los_local.featureCount() * 2)\n\n output_path = get_data_path_results(file=\"los_parts.gpkg\")\n\n params = {\n \"LoSLayer\": self.los_global,\n \"OutputLayer\": output_path,\n \"CurvatureCorrections\": True,\n \"RefractionCoefficient\": 0.13\n }\n\n self.assertRunAlgorithm(parameters=params)\n\n los_parts = QgsVectorLayer(output_path)\n\n self.assertQgsVectorLayer(los_parts,\n geom_type=QgsWkbTypes.MultiLineStringZ,\n crs=self.los_local.sourceCrs())\n\n self.assertFieldNamesInQgsVectorLayer(\n [FieldNames.ID_OBSERVER, FieldNames.ID_TARGET, FieldNames.VISIBLE], los_parts)\n\n self.assertEqual(los_parts.featureCount(), self.los_global.featureCount() * 2)\n\n output_path = get_data_path_results(file=\"los_parts.gpkg\")\n\n params = {\n \"LoSLayer\": self.los_no_target,\n \"OutputLayer\": output_path,\n \"CurvatureCorrections\": True,\n \"RefractionCoefficient\": 0.13\n }\n\n self.assertRunAlgorithm(parameters=params)\n\n los_parts = QgsVectorLayer(output_path)\n\n self.assertQgsVectorLayer(los_parts,\n geom_type=QgsWkbTypes.MultiLineStringZ,\n crs=self.los_local.sourceCrs())\n\n self.assertFieldNamesInQgsVectorLayer(\n [FieldNames.ID_OBSERVER, FieldNames.ID_TARGET, FieldNames.VISIBLE], los_parts)\n\n self.assertEqual(los_parts.featureCount(), self.los_no_target.featureCount() * 2)\n","sub_path":"tests/processing/analyse_los/test_tool_extract_los_visibility_parts.py","file_name":"test_tool_extract_los_visibility_parts.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"295157292","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Computes stacked bar charts from the .fingerprint files collected during campaigns. The goal is \n# to evaluate the correlation that exists between some properties of the fingerprints. The script \n# uses three input parameters: a year, a date (both being used to select a dataset) and the path \n# to a text file listing the ASes that should be considered at this date.\n#\n# This script shows the proportions of fingerprints that have the following characteristics:\n# 64 & \"Healthy\" IP-ID counter, 255 and \"Echo\" counter. Last category is for everything else.\n\nimport numpy as np\nimport os\nimport sys\nfrom matplotlib import pyplot as plt\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) < 4:\n print(\"Use this command: python FingerprintsAnalysisCorrelation.py [year] [date] [path to AS file]\")\n sys.exit()\n \n yearOfMeasurements = str(sys.argv[1])\n dateOfMeasurements = str(sys.argv[2])\n ASFilePath = str(sys.argv[3])\n \n # Parses AS file\n if not os.path.isfile(ASFilePath):\n print(\"AS file does not exist\")\n sys.exit()\n\n with open(ASFilePath) as f:\n ASesRaw = f.read().splitlines()\n \n # For this particular file, we do not class by type. We remove the :[type] part.\n ASes = []\n for i in range(0, len(ASesRaw)):\n splitted = ASesRaw[i].split(':')\n ASes.append(splitted[0])\n\n # Computes the required data\n correctlyParsedASes = []\n ratioHealthy64Or128 = []\n ratioEcho255 = []\n ratioOthers = []\n \n dataPath = \"/home/jefgrailet/PhD/Campaigns\"\n for i in range(0, len(ASes)):\n dataFilePath = dataPath + \"/\" + ASes[i] + \"/\" + yearOfMeasurements + \"/\"\n dataFilePath += dateOfMeasurements + \"/\" + ASes[i] + \"_\" + dateOfMeasurements\n dataFilePath += \".fingerprint\"\n \n # Checks existence of the file\n if not os.path.isfile(dataFilePath):\n print(dataFilePath + \" does not exist\")\n sys.exit()\n else:\n correctlyParsedASes.append(ASes[i])\n \n # Parses it and analyzes fingerprints\n with open(dataFilePath) as f:\n fingerprints = f.read().splitlines()\n \n nbFingerprints = len(fingerprints)\n integerData = np.zeros((3, 1))\n for j in range(0, nbFingerprints):\n firstSplit = fingerprints[j].split(' - ')\n curFingerprint = firstSplit[1][1:-1]\n splitted = curFingerprint.split(',')\n \n # Counter type\n if splitted[2] == \"Healthy\" and (splitted[0] == \"64\" or splitted[0] == \"128\"):\n integerData[0] += 1\n elif splitted[2] == \"Echo\" and splitted[0] == \"255\":\n integerData[1] += 1\n else:\n integerData[2] += 1\n \n # Computes ratios\n ratioHealthy64Or128.append((float(integerData[0]) / float(nbFingerprints)) * 100)\n ratioEcho255.append((float(integerData[1]) / float(nbFingerprints)) * 100)\n ratioOthers.append((float(integerData[2]) / float(nbFingerprints)) * 100)\n\n ind = np.arange(len(correctlyParsedASes)) # The x locations\n width = 0.8\n center = 0.5\n padding = 0.1\n \n # Font for labels and ticks\n hfont = {'fontname':'serif',\n 'fontweight':'bold',\n 'fontsize':21}\n \n hfont2 = {'fontname':'serif',\n 'fontsize':21}\n \n bottom1 = ratioHealthy64Or128\n bottom2 = np.zeros((len(correctlyParsedASes), 1))\n for i in range(0, len(correctlyParsedASes)):\n bottom2[i] = bottom1[i] + ratioEcho255[i]\n\n plt.figure(figsize=(11,7))\n\n p1 = plt.bar(ind + padding, ratioHealthy64Or128, width, color='#F0F0F0')\n p2 = plt.bar(ind + padding, ratioEcho255, width, color='#D0D0D0', bottom=bottom1)\n p3 = plt.bar(ind + padding, ratioOthers, width, color='#888888', bottom=bottom2)\n \n plt.ylabel('Proportion (%)', **hfont)\n plt.xlabel('AS index', **hfont)\n plt.ylim([0,100])\n plt.xlim([0,len(ASes)])\n plt.xticks(ind + center, range(1,21,1), **hfont2)\n plt.yticks(np.arange(0, 101, 10), **hfont2)\n \n plt.rc('font', family='serif', size=15)\n plt.legend((p1[0], p2[0], p3[0]), \n ('64/128, Healthy', '255, Echo', 'Others'), \n bbox_to_anchor=(0.05, 1.02, 0.90, .102), \n loc=3,\n ncol=3, \n mode=\"expand\", \n borderaxespad=0.)\n\n plt.savefig(\"Correlation_\" + yearOfMeasurements + \"_\" + dateOfMeasurements + \".pdf\")\n plt.clf()\n","sub_path":"v3/Measurements/Fingerprints/Scripts_2017/FingerprintsAnalysisCorrelation.py","file_name":"FingerprintsAnalysisCorrelation.py","file_ext":"py","file_size_in_byte":4547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"261560823","text":"from configs import StudentPacmanConfig as student_config\nfrom configs import DensePacmanAgentConfig as dense_config\nfrom configs import PrunePacmanAgentConfig as prune_config\nfrom model import PacmanTargetNet, StudentPacman\nfrom utils.plot_utils import plot_graph\nfrom utils.logger_utils import get_logger\nfrom Pacman.evaluate import evaluate\nfrom train import fit_supervised\nfrom prune import iterative_pruning_policy_distilliation\nfrom argparse import ArgumentParser\nfrom Pacman.copy_weights import copy_weights\nfrom utils.tensorflow_utils import calculate_redundancy\nfrom collections import deque\nfrom Pacman.accumulate_experience_Pacman import accumulate_experience\n\n\n\nFLAGS = 0\n\n\ndef check_convergence(info):\n diff_temp = []\n for i in range(len(info) - 1):\n diff_temp.append(info[i] - info[i+1])\n mean_diff = sum(diff_temp) / len(diff_temp)\n if mean_diff < 0.5: # a change of less then 1.0 percent in size counts as a converged model\n return True\n else:\n return False\n\n\ndef main():\n logger = get_logger(FLAGS.PoPS_dir + \"/PoPS_ITERATIVE\")\n logger.info(\" ------------- START: -------------\")\n logger.info(\"Setting initial data structures\")\n accuracy_vs_size = [[], []]\n logger.info(\"Loading models\")\n teacher = PacmanTargetNet(input_size=dense_config.input_size, output_size=dense_config.output_size)\n teacher.load_model(path=FLAGS.teacher_path) # load teacher\n logger.info(\"----- evaluating teacher -----\")\n print(\"----- evaluating teacher -----\")\n teacher_score = evaluate(agent=teacher, n_epoch=FLAGS.eval_epochs)\n logger.info(\"----- teacher evaluated with {} ------\".format(teacher_score))\n print(\"----- teacher evaluated with {} -----\".format(teacher_score))\n prune_step_path = FLAGS.PoPS_dir + \"/prune_step_\"\n policy_step_path = FLAGS.PoPS_dir + \"/policy_step_\"\n initial_path = policy_step_path + \"0\"\n copy_weights(output_path=initial_path, teacher_path=FLAGS.teacher_path) # inorder to create the initial model\n compressed_agent = StudentPacman(input_size=student_config.input_size,\n output_size=student_config.output_size,\n model_path=initial_path,\n tau=student_config.tau, prune_till_death=True,\n pruning_freq=prune_config.pruning_freq,\n sparsity_end=prune_config.sparsity_end,\n target_sparsity=prune_config.target_sparsity)\n compressed_agent.load_model()\n initial_size = compressed_agent.get_number_of_nnz_params()\n accuracy_vs_size[0].append(initial_size)\n accuracy_vs_size[1].append(teacher_score)\n initial_number_of_params_at_each_layer = compressed_agent.get_number_of_nnz_params_per_layer()\n initial_number_of_nnz = sum(initial_number_of_params_at_each_layer)\n converge = False\n iteration = 0\n convergence_information = deque(maxlen=2)\n convergence_information.append(100)\n precent = 100\n arch_type = 0\n last_measure = initial_size\n while not converge:\n iteration += 1\n print(\"----- Pruning Step {} -----\".format(iteration))\n logger.info(\" ----- Pruning Step {} -----\".format(iteration))\n path_to_save_pruned_model = prune_step_path + str(iteration)\n sparsity_vs_accuracy = iterative_pruning_policy_distilliation(logger=logger, agent=compressed_agent,\n target_agent=teacher,\n iterations=FLAGS.iterations,\n config=student_config,\n best_path=path_to_save_pruned_model,\n arch_type=arch_type,\n objective_score=dense_config.OBJECTIVE_SCORE,\n lower_bound=dense_config.LOWER_BOUND,\n evaluate_fn=evaluate,\n accumulate_experience_fn=accumulate_experience)\n plot_graph(data=sparsity_vs_accuracy, name=FLAGS.PoPS_dir + \"/initial size {}%, Pruning_step number {}\"\n .format(precent, iteration), figure_num=iteration)\n\n # loading model which has reasonable score with the highest sparsity\n compressed_agent.load_model(path_to_save_pruned_model)\n # the amount of parameters that are not zero at each layer\n nnz_params_at_each_layer = compressed_agent.get_number_of_nnz_params_per_layer()\n # the amount of parameters that are not zero\n nnz_params = sum(nnz_params_at_each_layer)\n # redundancy is the parameters we dont need, nnz_params / initial is the params we need the opposite\n redundancy = (1 - nnz_params / initial_number_of_nnz) * 100\n print(\"----- Pruning Step {} finished, got {}% redundancy in net params -----\"\n .format(iteration, redundancy))\n logger.info(\"----- Pruning Step {} finished , got {}% redundancy in net params -----\"\n .format(iteration, redundancy))\n logger.info(\"----- Pruning Step {} finished with {} NNZ params at each layer\"\n .format(iteration, nnz_params_at_each_layer))\n print(\" ----- Evaluating redundancy at each layer Step {}-----\".format(iteration))\n logger.info(\" ----- Evaluating redundancy at each layer Step {} -----\".format(iteration))\n redundancy_at_each_layer = calculate_redundancy(initial_nnz_params=initial_number_of_params_at_each_layer,\n next_nnz_params=nnz_params_at_each_layer)\n logger.info(\"----- redundancy for each layer at step {} is {} -----\".format(iteration, redundancy_at_each_layer))\n\n print(\" ----- Creating Model with size according to the redundancy at each layer ----- \")\n logger.info(\"----- Creating Model with size according to the redundancy at each layer -----\")\n policy_distilled_path = policy_step_path + str(iteration)\n # creating the compact model where every layer size is determined by the redundancy measure\n compressed_agent = StudentPacman(input_size=student_config.input_size,\n output_size=student_config.output_size,\n model_path=policy_distilled_path,\n tau=student_config.tau,\n redundancy=redundancy_at_each_layer,\n pruning_freq=prune_config.pruning_freq,\n sparsity_end=prune_config.sparsity_end,\n target_sparsity=prune_config.target_sparsity,\n prune_till_death=True,\n last_measure=last_measure)\n nnz_params_at_each_layer = compressed_agent.get_number_of_nnz_params_per_layer()\n logger.info(\"----- Step {} ,Created Model with {} NNZ params at each layer\"\n .format(iteration, nnz_params_at_each_layer))\n iterative_size = compressed_agent.get_number_of_nnz_params()\n precent = (iterative_size / initial_size) * 100\n convergence_information.append(precent)\n print(\" ----- Step {}, Created Model with size {} which is {}% from original size ----- \"\n .format(iteration, iterative_size, precent))\n logger.info(\"----- Created Model with size {} which is {}% from original size -----\"\n .format(iterative_size, precent))\n if precent > 10:\n arch_type = 0\n else:\n arch_type = 1\n print(\" ----- policy distilling Step {} ----- \".format(iteration))\n logger.info(\"----- policy distilling Step {} -----\".format(iteration))\n fit_supervised(logger=logger, arch_type=arch_type, student=compressed_agent, teacher=teacher,\n n_epochs=FLAGS.n_epoch, config=student_config, objective_score=dense_config.OBJECTIVE_SCORE,\n lower_score_bound=dense_config.LOWER_BOUND,\n evaluate_fn=evaluate, accumulate_experience_fn=accumulate_experience)\n compressed_agent.load_model(path=policy_distilled_path)\n policy_distilled_score = evaluate(agent=compressed_agent, n_epoch=FLAGS.eval_epochs)\n compressed_agent.reset_global_step()\n print(\" ----- policy distilling Step {} finished with score {} ----- \"\n .format(iteration, policy_distilled_score))\n logger.info(\"----- policy distilling Step {} finished with score {} -----\"\n .format(iteration, policy_distilled_score))\n converge = check_convergence(convergence_information)\n\n accuracy_vs_size[0].append(iterative_size)\n accuracy_vs_size[1].append(policy_distilled_score)\n\n plot_graph(data=accuracy_vs_size, name=FLAGS.PoPS_dir + \"/accuracy_vs_size\", figure_num=iteration + 1, xaxis='NNZ params', yaxis='Accuracy')\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument(\n '--teacher_path',\n type=str,\n default=dense_config.ready_path,\n help=' path where to load initial model.')\n parser.add_argument(\n '--PoPS_dir',\n type=str,\n default=student_config.iterative_PoPS,\n help='Results Directory.')\n parser.add_argument(\n '--n_epoch',\n type=int,\n default=student_config.n_epochs,\n help='number of epoches to do policy distillation')\n parser.add_argument(\n '--iterations',\n type=int,\n default=student_config.n_epochs,\n help='number of iteration to do pruning')\n parser.add_argument(\n '--batch_size',\n type=int,\n default=dense_config.batch_size,\n help='number of epoches')\n parser.add_argument(\n '--eval_epochs',\n type=int,\n default=1,\n help='number of epoches to evaluate the models during the process')\n FLAGS, unparsed = parser.parse_known_args()\n main()","sub_path":"Pacman/PoPS_iterative_Pacman.py","file_name":"PoPS_iterative_Pacman.py","file_ext":"py","file_size_in_byte":10429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"74441511","text":"import socket\nimport cv2\nimport numpy as np\nimport pickle\nimport time\n\ncap = cv2.VideoCapture(0)\ncap.set(3, 200)\ncap.set(4, 150)\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind(('', 8000))\ns.listen(3)\nclt, adr = s.accept()\n\ntime.sleep(5)\nwhile (True):\n ret, frame = cap.read()\n clt.send(pickle.dumps(\"b1\"))\n frame = cv2.imencode('.jpg', frame)\n frame = pickle.dumps(frame)\n clt.sendall(frame)\n\nclt.close()\ncap.release()\n","sub_path":"sockets/servercompress.py","file_name":"servercompress.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"182299050","text":"#!/usr/bin/env python3\nfrom bs4 import BeautifulSoup\nimport requests,sys,csv,json\n\nurl=\"http://ufm.edu/Estudios\"\n\n# Make a GET request to fetch the raw HTML content\ntry:\n html_content = requests.get(url).text\nexcept:\n print(f\"unable to get {url}\")\n sys.exit(1)\n\n# Parse the html content, this is the Magic ;)\nsoup = BeautifulSoup(html_content, \"html.parser\")\n\n# print if needed, gets too noisy\n#print(soup.prettify())\n\ndef separator_items():\n print (\"-----------------------------------------------------------------------------------------------------------------------------\")\n \ndef separator_parts():\n print (\"=============================================================================================================================\")\n \n \ndef estudios():\n separator_parts() \n print(\"2. Estudios\")\n ##ITEMS\n separator_items()\n print(\"display all items from 'topmenu':\")\n topmenu=soup.find_all(\"div\",{\"id\": f\"topmenu\"}) \n for items in topmenu:\n for menuitems in items.find_all(\"li\"):\n topmenuitems=menuitems.string\n if topmenuitems is not None:\n topmenuitems=str(topmenuitems).strip()\n print(f\"- {topmenuitems}\")\n \n ##ESTUDIOS\n separator_items()\n print(\"display ALL 'Estudios':\")\n estudios=soup.find_all(\"div\",{\"class\": \"estudios\"})\n for items in estudios:\n estudiositems=items.string\n if estudiositems is not None:\n estudiositems=str(estudiositems).strip()\n print(f\"- {estudiositems}\")\n \n ##LEFTBAR\n separator_items()\n print(\"display from 'leftbar' all items:\")\n leftbar=soup.find_all(\"div\",{\"class\": f\"leftbar\"})\n for items in leftbar:\n for baritems in items.find_all(\"li\"):\n leftbaritems=baritems.string\n if leftbaritems is not None:\n leftbaritems=str(leftbaritems).strip()\n print(f\"- {leftbaritems}\")\n \n ##SOCIAL MEDIA\n separator_items()\n print(\"get and display all available social media with its links:\")\n socialmedia=soup.find('div',{\"class\": f\"social pull-right\"}).find_all(\"a\")\n for links in socialmedia:\n print(f\"- {links['href']}\")\n \n ##\n separator_items()\n count=0\n for a in soup.find_all(\"a\"):\n count=count+1\n print(\"count all : \"+str(count))\n \n separator_parts() \n \nestudios()","sub_path":"estudios.py","file_name":"estudios.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"593672824","text":"\"\"\"\n\n9. Dado un párrafo ingresado por teclado, imprima los 3 verbos más usados en él (en infinitivo,\ndel más común al menos común), junto con la cantidad de apariciones de cada uno utilizando\nCounter.\nAclaración: No importa el orden de los verbos cuando tienen igual cantidad de repeticiones.\nUtilice el módulo pattern.es.\nEjemplo:\nEste es un párrafo de prueba. El verbo ser, será el mas utilizado. El otro será\ncrear, por eso se creó la oración de esta manera. Por último, se creará esta\noración que posee el tercer verbo: poseer. Nada más que decir.\nser 4\ncrear 3\nposeer 2\n\n\"\"\"\nimport pattern.es\nfrom pattern.es import conjugate, INFINITIVE, verbs\nfrom collections import Counter\n\nparrafo = input(\"Ingrese un parrafo: \")\npalabras = parrafo.strip().lower().replace(',', '').replace('.', '').split(' ')\nverbos = []\nfor palabra in palabras:\n\tenInfinitivo = conjugate(palabra, INFINITIVE)\n\tprint(palabra + \" --> \" + enInfinitivo)\n\tif (enInfinitivo in verbs):\n\t\tverbos.append(enInfinitivo)\n\n\nprint(\"\\nLos 3 verbos mas usados son: \\n\")\nfor verbo in Counter(verbos).most_common(3):\n\tprint(verbo)\n","sub_path":"Practica2/Ejercicio9.py","file_name":"Ejercicio9.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"647837925","text":"\"\"\" \r\n.. module:: LinkedList \r\n :platform: Unix, Windows \r\n :synopsis: Load the file with the values every. The file must be in the same directory with the name \r\n >>> values.txt. \r\n.. moduleauthor:: Jaime Jimenez \r\n\"\"\"\r\n\r\nclass Node(object):\r\n \r\n def __init__(self, value=None, next=None):\r\n self.value = value\r\n self.next = next\r\n\r\nclass LinkedList(object):\r\n\r\n def __init__(self):\r\n self.head = None\r\n\r\n def add(self, value):\r\n \"\"\"Add new item to linked list. \r\n Args: \r\n value: Value of node.\r\n >>> print add(self, value)\r\n \r\n \"\"\"\r\n node = Node(value, self.head)\r\n self.head = node\r\n\r\n def remove(self, value):\r\n \"\"\"Remove item by value. \r\n Args: \r\n value: Value of node.\r\n >>> print remove(self, value)\r\n\r\n \"\"\" \r\n current = self.head\r\n previous = None\r\n # search the node with the data. \r\n # Keep in memory the previous to validate when it is head so point the new head\r\n while current:\r\n if current.value == value:\r\n break\r\n else:\r\n previous = current\r\n current = current.next\r\n if current is None:\r\n raise ValueError('No se encontró el elemento')\r\n if previous is None:\r\n self.head = current.next\r\n else:\r\n previous.next = current.next\r\n\r\n def get_prior(self):\r\n \"\"\"Return the first node. \r\n Args: \r\n value: Value of node.\r\n Returns: \r\n Node. The first node \r\n\r\n >>> print get_prior(self, value) self.head\r\n\r\n \"\"\" \r\n return self.head\r\n\r\n # Get the node next to the node with match with the value\r\n def get_next_by_value(self, value):\r\n \"\"\"Get the node immediatelly next to the first node with that match with the value. \r\n Args: \r\n value: Value of node to search.\r\n Returns: \r\n Node. The next to the node that match with the value\r\n\r\n >>> print remove(self, value) current.next\r\n\r\n \"\"\"\r\n current = self.head\r\n while current:\r\n if current.value == value:\r\n return current.next\r\n else:\r\n current = current.next\r\n\r\n if current is None:\r\n raise ValueError('No se encontró el elemento')\r\n\r\n def __getitem__(self, index):\r\n \"\"\"To able the clase as iterative. \r\n Args: \r\n index: Index of iteration.\r\n Returns: \r\n Node. Node in position = index\r\n\r\n >>> print __getitem__(self, index) nd\r\n\r\n \"\"\"\r\n nd = self.head\r\n for i in range(0,index):\r\n if nd.next is None:\r\n raise StopIteration\r\n nd = nd.next\r\n return nd\r\n","sub_path":"assignment5/assignment5_package/code/LinkedList.py","file_name":"LinkedList.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"246225611","text":"# Given masks from cellpose (from segmenting the DAPI channel of Visium IF\n# images), quantify mean fluorescence in each non-DAPI channel within each\n# nucleus (dilated to include a region around each nucleus), and save a pandas\n# DataFrame with these values for each nucleus.\n\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy.random import default_rng\nimport pandas as pd\nimport seaborn as sns\nimport tifffile\nfrom scipy.spatial import KDTree\nfrom scipy import ndimage\nfrom skimage.measure import regionprops, regionprops_table\nimport pyhere\nfrom pathlib import Path\nimport json\n\n################################################################################\n# Variable definitions\n################################################################################\n\n#-------------------------------------------------------------------------------\n# Paths\n#-------------------------------------------------------------------------------\n\nsample_info_path = pyhere.here(\n 'raw-data', 'sample_info', 'Visium_IF_DLPFC_MasterExcel_01262022.xlsx'\n)\nimg_path = pyhere.here('raw-data', 'Images', 'VisiumIF', 'VistoSeg', '{}.tif')\nmask_path = pyhere.here(\n 'processed-data', 'spot_deconvo', '02-cellpose', 'masks', '{}_mask.npy'\n)\nspot_path = pyhere.here(\n 'processed-data', '01_spaceranger_IF', '{}', 'outs', 'spatial',\n 'tissue_positions_list.csv'\n)\nscale_path = pyhere.here(\n 'processed-data', '01_spaceranger_IF', '{}', 'outs', 'spatial',\n 'scalefactors_json.json'\n)\nout_df_path = pyhere.here(\n 'processed-data', 'spot_deconvo', '02-cellpose', '{}', 'df.csv'\n)\nout_df_unfiltered_path = pyhere.here(\n 'processed-data', 'spot_deconvo', '02-cellpose', '{}', 'df_unfiltered.csv'\n)\nout_masks_path = pyhere.here(\n 'processed-data', 'spot_deconvo', '02-cellpose', '{}', 'expanded_masks.npy'\n)\nplot_dir = pyhere.here(\"plots\", \"spot_deconvo\", \"02-cellpose\", \"count_cells_no_GFAP\")\n\nPath(plot_dir).mkdir(parents=True, exist_ok=True)\n\n#-------------------------------------------------------------------------------\n# Dataset-specific variables\n#-------------------------------------------------------------------------------\n\nnames = {0: \"junk\", 1: \"dapi\", 2: \"gfap\", 3: \"neun\", 4: \"olig2\", 5: \"tmem119\"}\ncell_types = {\n \"neun\": \"neuron\",\n \"olig2\": \"oligo\",\n \"tmem119\": \"micro\"\n}\n\n# Nucleus area, in number of pixels, below which a cell is ignored. Tested by\n# eye\narea_threshold = 60\n\ndilation_radius = 15\ndilation_chunk_size = 6\n\nplot_file_type = 'png' # 'pdf' is also supported for higher-quality plots\n\n################################################################################\n# Functions\n################################################################################\n\n# Perform a dilation-like transformation on 'img' by total size\n# 'dilation_radius'. The whole transformation actually involves a series\n# of dilations by size [chunk_size / 2] followed by inversion. The idea\n# is to expand each mask equally without bias towards masks with larger-valued\n# labels (in case of overlap, which frequently happens)\ndef balanced_dilation(img, dilation_radius, chunk_size, verbose = False):\n assert chunk_size % 2 == 0, 'chunk_size must be even'\n assert 2 * dilation_radius % chunk_size == 0, 'cannot break this radius into chunks'\n \n num_chunks = int(2 * dilation_radius / chunk_size)\n dilation_chunked = int(dilation_radius / num_chunks)\n assert num_chunks % 2 == 1, 'must use an odd number of chunks'\n \n # We'll use -1 * MAX_VALUE as a placeholder, assumed to be smaller than\n # all elements in 'img'. Check this assumption\n MAX_VALUE = 2 ** 31 - 1\n assert(np.all(img < MAX_VALUE))\n \n expanded_masks = img.copy().astype(np.int32)\n \n for i in range(num_chunks):\n if verbose:\n print(f'Dilating by {dilation_chunked} pixels...')\n \n # Make sure zero-valued elements are always treated as the smallest\n # value possible for dilation\n zero_indices = expanded_masks == 0\n expanded_masks[zero_indices] = -1 * MAX_VALUE\n \n expanded_masks = ndimage.grey_dilation(\n expanded_masks,\n size = (dilation_chunked, dilation_chunked)\n )\n \n # Return \"zero-valued\" elements to a true value of 0\n zero_indices = expanded_masks == -1 * MAX_VALUE\n expanded_masks[zero_indices] = 0\n \n if i < num_chunks - 1:\n if verbose:\n print('Inverting...')\n \n expanded_masks *= -1\n \n return expanded_masks.astype(img.dtype)\n\n################################################################################\n# Analysis\n################################################################################\n\n# os.environ['SGE_TASK_ID'] = '1'\n\nrng = default_rng()\n\n#-------------------------------------------------------------------------------\n# Read in sample info and adjust paths for this particular sample ID\n#-------------------------------------------------------------------------------\n\n# Different sample IDs are used for different files associated with each\n# sample. Determine both forms of the sample ID for this sample and update\n# path variables accordingly\nsample_info = pd.read_excel(sample_info_path)[:4]\nsample_ids_img = sample_info['Slide SN #'] + '_' + sample_info['Array #']\nsample_ids_spot = 'Br' + sample_info['BrNumbr'].astype(int).astype(str) + \\\n '_' + pd.Series([x.split('_')[1] for x in sample_info['Br_Region']]) + \\\n '_IF'\n\nsample_id_img = sample_ids_img[int(os.environ['SGE_TASK_ID']) - 1]\nimg_path = str(img_path).format(sample_id_img)\nmask_path = str(mask_path).format(sample_id_img)\n\nsample_id_spot = sample_ids_spot[int(os.environ['SGE_TASK_ID']) - 1]\nspot_path = str(spot_path).format(sample_id_spot)\nout_df_path = str(out_df_path).format(sample_id_spot)\nout_df_unfiltered_path = str(out_df_unfiltered_path).format(sample_id_spot)\nout_masks_path = str(out_masks_path).format(sample_id_spot)\n\nPath(out_df_path).parents[0].mkdir(parents=True, exist_ok=True)\n\n# Path to JSON from spaceranger including spot size for this sample\njson_path = str(scale_path).format(sample_id_spot)\nwith open(json_path) as f: \n json_data = json.load(f)\n\n#-------------------------------------------------------------------------------\n# Read in spot data\n#-------------------------------------------------------------------------------\n\n# Read in all spot data\nraw = pd.read_csv(\n spot_path,\n header=None,\n names=[\"barcode\", \"included\", \"row\", \"col\", \"x\", \"y\"],\n)\n\n# Take only spots that overlap tissue\nraw = raw.iloc[raw.included[raw.included == 1].index].reset_index().drop(\n columns=[\"included\", \"index\"]\n)\n\n#-------------------------------------------------------------------------------\n# Quantify mean fluorescence for each channel at each nucleus\n#-------------------------------------------------------------------------------\n\n# Load multi-channel image and masks from segmenting DAPI channel\nimgs = tifffile.imread(img_path)\nmasks = np.load(mask_path)\n\n# Dilate the original masks\nprint(f'Dilating original masks by radius {dilation_radius} and chunk size {dilation_chunk_size}.')\nexpanded_masks = balanced_dilation(masks, dilation_radius, dilation_chunk_size)\n\n# Quantify the mean image fluorescence intensity at each nucleus\n# identified by segmenting the DAPI channel. This is done for each\n# (non-lipofuscin, non-DAPI) channel\nits = {\n names[i]: regionprops_table(\n expanded_masks, intensity_image=imgs[i], properties=[\"intensity_mean\"]\n )[\"intensity_mean\"]\n for i in range(2, 6)\n}\n\n# Create a table containing the centroids and areas of each mask\n# (nucleus), and add this info to the intensities table\ngeneral = regionprops_table(masks, properties=[\"centroid\", \"area\"])\nits[\"area\"] = general[\"area\"]\nits[\"x\"] = general[\"centroid-0\"]\nits[\"y\"] = general[\"centroid-1\"]\n\ndf = pd.DataFrame(its)\n\n#-------------------------------------------------------------------------------\n# Exploratory plot: show the distribution of masks over spots\n#-------------------------------------------------------------------------------\n\n# Plot mask spatial distribution vs. spot distribution; there should be\n# quite a bit of overlap\nplt.clf()\nplt.scatter(raw[\"x\"], raw[\"y\"], 2)\nplt.scatter(df[\"x\"], df[\"y\"], 2)\nplt.savefig(\n os.path.join(\n plot_dir, f'mask_spot_overlap_{sample_id_img}.{plot_file_type}'\n )\n)\n\n#-------------------------------------------------------------------------------\n# Filter masks that are too small or not within a spot\n#-------------------------------------------------------------------------------\n\n# Build KD tree for nearest neighbor search.\nkd = KDTree(raw[[\"x\", \"y\"]])\n\n# For each mask, assign a distance to the nearest spot ('dist') and index of\n# that spot in 'df' ('idx'). Add this info to 'df'\ndist, idx = kd.query(df[[\"x\", \"y\"]])\ndist = pd.DataFrame({\"dist\": dist, \"idx\": idx})\ndf = pd.concat([df, dist], axis=1)\n\n# Write a copy of all segmented nuclei (cells) before the upcoming filtering\n# steps. Modify column names for loading in the Loopy browser\ndf_unfiltered = df.rename(\n {\n 'x': 'y',\n 'y': 'x',\n },\n axis = 1\n)\ndf_unfiltered.index.name = 'id'\ndf_unfiltered.to_csv(out_df_unfiltered_path)\n\n# Filters out masks that are smaller than a threshold and\n# masks whose centroid is farther than the spot radius (aka not inside the\n# spot).\nfrac_kept = round(100 * np.sum(df.dist < json_data['spot_diameter_fullres'] / 2) / len(df.dist), 1)\nprint(f'Keeping {frac_kept}% of masks, which were within spots covered by tissue.')\ndf = df[df.dist < json_data['spot_diameter_fullres'] / 2]\n\nfrac_kept = round(100 * np.sum(df.area > area_threshold) / len(df.area), 1)\nprint(f'Keeping {frac_kept}% of remaining masks, which met a minimum area threshold.')\ndf = df[df.area > area_threshold]\n\n#-------------------------------------------------------------------------------\n# Save relevant data\n#-------------------------------------------------------------------------------\n\ndf.to_csv(out_df_path)\nnp.save(out_masks_path, expanded_masks)\n","sub_path":"code/spot_deconvo/02-cellpose/04-quantify_fluor.py","file_name":"04-quantify_fluor.py","file_ext":"py","file_size_in_byte":10192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"644543262","text":"class Solution:\n # @param A, a list of integers\n # @return an integer\n def firstMissingPositive(self, A):\n #key point is place the element in the right index position\n #ignore all the negative, > n\n #put the other value back to its order position A[A[i]-1]\n if len(A) == 0:\n return 1\n i = 0\n while i != len(A):\n if A[i] != i + 1 and A[i] > 0 and A[i] <= len(A) and A[A[i] -1] != A[i]:\n temp = A[i]\n A[i] = A[A[i] - 1]\n A[temp - 1] = temp\n else:\n i += 1\n for i in range(len(A)):\n if A[i] != i + 1:\n return i + 1\n return len(A)+1","sub_path":"All Code/No.41 First Missing Positive.py","file_name":"No.41 First Missing Positive.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"617737780","text":"from Graph import Graph, read_graph, write_graph, create_random_graph\r\n\r\n\"\"\"\r\nDesign and implement an abstract data type directed graph and a function (either a member function or an external one,\r\n as your choice) for reading a directed graph from a text file.\r\n\r\nThe vertices will be specified as integers from 0 to n-1, where n is the number of vertices.\r\n\r\nEdges may be specified either by the two endpoints (that is, by the source and target), or by some abstract data type\r\nEdge_id (that data type may be a pointer or reference to the edge representation, but without exposing\r\nthe implementation details of the graph).\r\n\r\nAdditionally, create a map that associates to an edge an integer value (for instance, a cost).\r\n\r\nRequired operations:\r\n\r\n-> g̶e̶t̶ ̶t̶h̶e̶ ̶n̶u̶m̶b̶e̶r̶ ̶o̶f̶ ̶v̶e̶r̶t̶i̶c̶e̶s̶;̶\r\n-̶>̶ ̶p̶a̶r̶s̶e̶ ̶(̶i̶t̶e̶r̶a̶t̶e̶)̶ ̶t̶h̶e̶ ̶s̶e̶t̶ ̶o̶f̶ ̶v̶e̶r̶t̶i̶c̶e̶s̶;̶ \r\n-̶>̶ ̶g̶i̶v̶e̶n̶ ̶t̶w̶o̶ ̶v̶e̶r̶t̶i̶c̶e̶s̶,̶ ̶f̶i̶n̶d̶ ̶o̶u̶t̶ ̶w̶h̶e̶t̶h̶e̶r̶ ̶t̶h̶e̶r̶e̶ ̶i̶s̶ ̶a̶n̶ ̶e̶d̶g̶e̶ ̶f̶r̶o̶m̶ ̶t̶h̶e̶ ̶f̶i̶r̶s̶t̶ ̶o̶n̶e̶ ̶t̶o̶ ̶t̶h̶e̶ ̶s̶e̶c̶o̶n̶d̶ ̶o̶n̶e̶,̶ ̶a̶n̶d̶ ̶r̶e̶t̶r̶i̶e̶v̶e̶ ̶t̶h̶e̶ ̶E̶d̶g̶e̶_̶i̶d̶\r\n̶i̶f̶ ̶t̶h̶e̶r̶e̶ ̶i̶s̶ ̶a̶n̶ ̶e̶d̶g̶e̶ ̶(̶t̶h̶e̶ ̶l̶a̶t̶t̶e̶r̶ ̶i̶s̶ ̶n̶o̶t̶ ̶r̶e̶q̶u̶i̶r̶e̶d̶ ̶i̶f̶ ̶a̶n̶ ̶e̶d̶g̶e̶ ̶i̶s̶ ̶r̶e̶p̶r̶e̶s̶e̶n̶t̶e̶d̶ ̶s̶i̶m̶p̶l̶y̶ ̶a̶s̶ ̶a̶ ̶p̶a̶i̶r̶ ̶o̶f̶ ̶v̶e̶r̶t̶e̶x̶ ̶i̶d̶e̶n̶t̶i̶f̶i̶e̶r̶s̶)̶;̶\r\n-̶>̶ ̶g̶e̶t̶ ̶t̶h̶e̶ ̶i̶n̶ ̶d̶e̶g̶r̶e̶e̶ ̶a̶n̶d̶ ̶t̶h̶e̶ ̶o̶u̶t̶ ̶d̶e̶g̶r̶e̶e̶ ̶o̶f̶ ̶a̶ ̶s̶p̶e̶c̶i̶f̶i̶e̶d̶ ̶v̶e̶r̶t̶e̶x̶;̶\r\n-> parse (iterate) the set of outbound edges of a specified vertex (that is, provide an iterator). For each outbound edge,\r\n the iterator shall provide the Edge_id of the current edge (or the target vertex, if no Edge_id is used).\r\n-> parse the set of inbound edges of a specified vertex (as above);\r\n-> get the endpoints of an edge specified by an Edge_id (if applicable);\r\n-> retrieve or modify the information (the integer) attached to a specified edge.\r\n-> The graph shall be modifiable: it shall be possible to add and remove an edge, and to add and remove a vertex. Think\r\nabout what should happen with the properties of existing edges and with the identification of remaining vertices.\r\nYou may use an abstract Vertex_id instead of an int in order to identify vertices; in this case, provide a way of\r\niterating the vertices of the graph.\r\n-> The graph shall be copyable, that is, it should be possible to make an exact copy of a graph, so that the original\r\ncan be then modified independently of its copy. Think about the desirable behaviour of an Edge_property attached to the\r\noriginal graph, when a copy is made.\r\n-> Read the graph from a text file (as an external function); see the format below.\r\n-> Write the graph from a text file (as an external function); see the format below.\r\n-> Create a random graph with specified number of vertices and of edges (as an external function).\r\n\"\"\"\r\n\r\n\r\nclass UI:\r\n def __init__(self, graph):\r\n self._graph = graph\r\n\r\n\r\n @property\r\n def graph(self):\r\n return self._graph\r\n\r\n def print_menu(self):\r\n print(\"1. Read a graph from a file.\\n\")\r\n print(\"2. Write the graph to a file.\\n\")\r\n print(\"3. Get the number of vertices.\\n\")\r\n print(\"4. Parse the set of vertices.\\n\")\r\n print(\"5. Is edge between 2 vertices?\\n\")\r\n print(\"6. Get the in degree of a vertex.\\n\")\r\n print(\"7. Get the out degree of a vertex.\\n\")\r\n print(\"8. Parse the outbound edges of a vertex.\\n\")\r\n print(\"9. Parse the inbound edges of a vertex.\\n\")\r\n print(\"10. Get the endpoints of an edge.\\n\")\r\n print(\"11. Get the cost of an edge.\\n\")\r\n print(\"12. Update the cost of an edge.\\n\")\r\n print(\"13. Add an edge.\\n\")\r\n print(\"14. Remove an edge.\\n\")\r\n print(\"15. Add a vertex.\\n\")\r\n print(\"16. Remove a vertex.\\n\")\r\n print(\"17. Copy the graph.\\n\")\r\n print(\"18. Create a random graph.\\n\")\r\n print(\"19. Print the graph.\\n\")\r\n print(\"20. Exit.\\n\")\r\n\r\n def read_graph_ui(self, name_of_file):\r\n read_graph(self.graph, name_of_file)\r\n print(\"Graph read successfully.\\n\")\r\n\r\n def write_graph_ui(self, name_of_file):\r\n write_graph(self.graph, name_of_file)\r\n print(\"Graph written to file successfully.\\n\")\r\n\r\n def get_number_of_vertices_ui(self):\r\n number_of_vertices = self.graph.number_of_vertices()\r\n print(\"The graph has \" + str(number_of_vertices) + \" vertices.\\n\")\r\n\r\n def parse_the_set_of_vertices_ui(self):\r\n for vertex in self.graph.parse_vertices():\r\n print(vertex)\r\n\r\n def is_edge_between_vertices_ui(self):\r\n vertex_a = int(input(\"Source vertex: \"))\r\n vertex_b = int(input(\"Target vertex: \"))\r\n edge = self.graph.is_edge_from_to(vertex_a, vertex_b)\r\n if edge:\r\n print(\"Yes. Edge \" + str(edge) + \"\\n\")\r\n else:\r\n print(\"There is no edge from \" + str(vertex_a) + \" to \" + str(vertex_b) + \".\\n\")\r\n\r\n def get_in_degree_ui(self):\r\n vertex_id = int(input(\"Enter vertex: \"))\r\n vertex_in_degree = self.graph.get_in_degree(vertex_id)\r\n print(\"The in-degree of vertex \" + str(vertex_id) + \" is \" + str(vertex_in_degree) + \".\\n\")\r\n\r\n def get_out_degree_ui(self):\r\n vertex_id = int(input(\"Enter vertex: \"))\r\n vertex_out_degree = self.graph.get_out_degree(vertex_id)\r\n print(\"The out-degree of vertex \" + str(vertex_id) + \" is \" + str(vertex_out_degree) + \".\\n\")\r\n\r\n def parse_outbound_edges_of_vertex_ui(self):\r\n vertex_id = int(input(\"Enter vertex: \"))\r\n outbound_edges = self.graph.parse_outbound_edges(vertex_id)\r\n if outbound_edges:\r\n print(\"The outbound edges are: \\n\")\r\n for edge in outbound_edges:\r\n print(edge)\r\n else:\r\n print(\"The vertex does not have outbound edges.\\n\")\r\n\r\n def parse_inbound_edges_of_vertex_ui(self):\r\n vertex_id = int(input(\"Enter vertex: \"))\r\n inbound_edges = self.graph.parse_inbound_edges(vertex_id)\r\n if inbound_edges:\r\n print(\"The inbound edges are: \\n\")\r\n for edge in inbound_edges:\r\n print(edge)\r\n else:\r\n print(\"The vertex does not have inbound edges.\\n\")\r\n\r\n def get_endpoints_of_edge_ui(self):\r\n edge_id = int(input(\"Edge id: \"))\r\n source, target = self.graph.get_endpoints_of_an_edge(edge_id)\r\n print(\"The edge \" + str(edge_id) + \" goes from \" + str(source) + \" to \" + str(target) + \".\")\r\n\r\n def get_cost_of_edge_ui(self):\r\n edge_id = int(input(\"Edge id: \"))\r\n edge_cost = self.graph.get_cost_of_edge(edge_id)\r\n print(\"The cost of the edge is \" + str(edge_cost) + \".\")\r\n\r\n def update_cost_of_edge_ui(self):\r\n edge_id = int(input(\"Edge id: \"))\r\n new_cost = int(input(\"New cost: \"))\r\n self.graph.update_cost_of_edge(edge_id, new_cost)\r\n print(\"Cost was updated successfully.\\n\")\r\n\r\n def add_edge_ui(self):\r\n source_vertex = int(input(\"Source vertex: \"))\r\n target_vertex = int(input(\"Target vertex: \"))\r\n edge_cost = int(input(\"Edge cost: \"))\r\n self.graph.add_edge(source_vertex, target_vertex, edge_cost)\r\n print(\"Edge was added successfully.\\n\")\r\n\r\n def remove_edge_ui(self):\r\n edge_id = int(input(\"Edge id: \"))\r\n self.graph.remove_edge(edge_id)\r\n print(\"Edge was removed successfully.\\n\")\r\n\r\n def add_vertex_ui(self):\r\n self.graph.add_vertex()\r\n print(\"Vertex was added successfully.\\n\")\r\n\r\n def remove_vertex_ui(self):\r\n vertex_id = int(input(\"Vertex id: \"))\r\n self.graph.remove_vertex(vertex_id)\r\n print(\"Vertex was removed successfully.\\n\")\r\n\r\n def deepcopy_ui(self):\r\n print(\"The graph was copied.\\n\")\r\n\r\n if self.graph.is_edge_from_to(2, 1) > 0:\r\n print(\"True\") # should be true\r\n else:\r\n print(\"False\")\r\n\r\n copy_of_graph = self.graph.copy()\r\n\r\n if copy_of_graph.is_edge_from_to(2, 1) > 0:\r\n print(\"True\") # should be true\r\n else:\r\n print(\"False\")\r\n copy_of_graph.remove_vertex(2)\r\n\r\n try:\r\n copy_of_graph.is_edge_from_to(2, 1)\r\n assert False\r\n except ValueError:\r\n assert True\r\n\r\n if self.graph.is_edge_from_to(2, 1) > 0:\r\n print(\"True\") # should be true\r\n else:\r\n print(\"False\")\r\n\r\n def create_random_graph_ui(self):\r\n number_of_vertices = int(input(\"Number of vertices: \"))\r\n number_of_edges = int(input(\"Number of edges: \"))\r\n print(create_random_graph(number_of_vertices, number_of_edges))\r\n\r\n def print_graph(self):\r\n print(self.graph)\r\n\r\n def start(self):\r\n self.print_menu()\r\n not_finished = 1\r\n input_file = \"input_data.txt\"\r\n output_file = \"output_data.txt\"\r\n options = {3: self.get_number_of_vertices_ui,\r\n 4: self.parse_the_set_of_vertices_ui, 5: self.is_edge_between_vertices_ui, 6: self.get_in_degree_ui,\r\n 7: self.get_out_degree_ui, 8: self.parse_outbound_edges_of_vertex_ui,\r\n 9: self.parse_inbound_edges_of_vertex_ui, 10: self.get_endpoints_of_edge_ui,\r\n 11: self.get_cost_of_edge_ui, 12: self.update_cost_of_edge_ui, 13: self.add_edge_ui,\r\n 14: self.remove_edge_ui, 15: self.add_vertex_ui, 16: self.remove_vertex_ui,\r\n 17: self.deepcopy_ui, 18: self.create_random_graph_ui, 19: self.print_graph}\r\n while not_finished:\r\n user_option = int(input(\"Enter option: \"))\r\n if user_option == 1:\r\n try:\r\n self.read_graph_ui(input_file)\r\n except Exception as exception_message:\r\n print(exception_message)\r\n elif user_option == 2:\r\n try:\r\n self.write_graph_ui(output_file)\r\n except Exception as exception_message:\r\n print(exception_message)\r\n elif user_option in options:\r\n try:\r\n options[user_option]()\r\n except Exception as exception_message:\r\n print(exception_message)\r\n elif user_option == 20:\r\n not_finished = 0\r\n else:\r\n print(\"Invalid command.\")\r\n\r\n\r\nmy_graph = Graph()\r\nui = UI(my_graph)\r\nui.start()\r\n","sub_path":"Lowest length path backward BF/UI.py","file_name":"UI.py","file_ext":"py","file_size_in_byte":10871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"85299334","text":"# Project: GameOfLife\n#\n# Created by Michal Lukaszewicz (remoteVoyager) at 2019-08-04\n# mlukaszewicz2@gmail.com\nfrom gameOfLife import *\nimport curses\nimport time\n\nboard = load_board_state(\"examples/ggg.txt\")\n\nscreen = curses.initscr()\ncurses.cbreak()\ncurses.noecho()\ncurses.nodelay(True)\nscreen.keypad(True)\n\nwhile (True):\n rboard = render_board(board)\n\n screen.clear()\n\n screen.addstr(0, 0, \"\".join(rboard))\n\n board = next_board_state(board)\n\n curses.napms(100)\n screen.refresh()\n\n if screen.getkey() == curses.KEY_BACKSPACE:\n break\n\ncurses.nocbreak()\nscreen.keypad(False)\ncurses.echo()\ncurses.endwin()\n","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"599880638","text":"import fiona\nimport numpy\nimport rasterio\nimport shapely.geometry\nimport xarray\n\nimport datacube\n\n\ndef transect(data, line, resolution, method='nearest', tolerance=None):\n \"\"\"\n Extract line transect from data along geom\n\n :param xarray.Dataset data: data loaded via `Datacube.load`\n :param shapely.geometry.LineString line: line along which to extract the transect (CRS must match data.crs)\n :param float resolution: interval used to extract points along the line (in CRS units)\n :param str method: see xarray.Dataset.sel_points\n :param float tolerance: see xarray.Dataset.sel_points\n \"\"\"\n dist = numpy.arange(0, int(line.length), resolution)\n points = zip(*[line.interpolate(d).coords[0] for d in dist])\n indexers = {\n data.crs.dimensions[0]: list(points[1]),\n data.crs.dimensions[1]: list(points[0])\n }\n return data.sel_points(xarray.DataArray(dist, name='distance', dims=['distance']),\n method=method,\n tolerance=tolerance,\n **indexers)\n\n\ndef warp_geometry(geom, src_crs, dst_crs):\n \"\"\"\n warp geometry from src_crs to dst_crs\n \"\"\"\n return shapely.geometry.shape(rasterio.warp.transform_geom(src_crs, dst_crs, shapely.geometry.mapping(geom)))\n\n\ndef main():\n with fiona.open('line.shp') as shapes:\n line_crs = str(shapes.crs_wkt)\n line = shapely.geometry.shape(next(shapes)['geometry'])\n\n query = {\n 'time': ('1990-01-01', '1991-01-01'),\n 'x': (line.bounds[0], line.bounds[2]),\n 'y': (line.bounds[1], line.bounds[3]),\n 'crs': line_crs\n }\n\n dc = datacube.Datacube()\n data = dc.load(product='ls5_nbar_albers', measurements=['red'], **query)\n\n line_albers = warp_geometry(line, query['crs'], data.crs.wkt)\n trans = transect(data, line_albers, abs(data.affine.a))\n trans.red.plot(x='distance', y='time')\n","sub_path":"docs/user/recipes/line_transect.py","file_name":"line_transect.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"163089238","text":"def EvenOddIndex(instream):\n\n evenList = list()\n oddList = list()\n index = 0\n\n for letters in instream:\n if index % 2 != 0:\n oddList.append(letters)\n else:\n evenList.append(letters)\n index += 1\n\n print(''.join(evenList) + \" \" + ''.join(oddList))\n\n\nn = int(input())\nstream = []\nfor i in range (n):\n elem = input()\n stream.append(elem)\n\nlength = len(stream)\nfor i in range (length):\n word = stream[i]\n EvenOddIndex(word)\n","sub_path":"HackerRank/30 Days of Coding/day 6.py","file_name":"day 6.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"630557720","text":"# Python language basics 7\n# Classes and Objects \n# Class fields, methods, and constructors\n# Object Instantiation\n\n# A class is just a blueprint that defines an object's attributes and behaviours\nclass GameCharacter:\n\n # A field or global variable(assigned to this value when the class is instantiated\n speed = 5\n\n # Constructor creates a new class instance and sets up the defined fields \n def __init__(self, name, width, height, x_pos, y_pos):\n self.name = name\n self.width = width\n self.height = height\n self.x_pos = x_pos\n self.y_pos = y_pos\n \n # Method is just a function that typically modifies the class's fields\n def move(self, by_x_amt, by_y_amt):\n self.x_pos += by_x_amt \n self.y_pos += by_y_amt \n\n# character_0 is a new instance of the GameCharacter class with defined attributes \ncharacter_0 = GameCharacter('char_0', 50, 100, 100, 100)\nprint(character_0.name)\ncharacter_0.name = 'char_1'\nprint(character_0.name)\n\ncharacter_0.move(50, 100)\nprint(character_0.x_pos)\nprint(character_0.y_pos)\n\n\n\n##############################################################################3\n# Python language basics 8\n# subclasses, superclasses, and inheritance\n\n\n# PlayerCharacter is a subclass of GameCharacter\n# PlayerCharacter has access to everything defined in GameCharacter\nclass PlayerCharacter(GameCharacter):\n\n speed = 10\n \n # Should still provide a constructor/initializer\n def __init__(self, name, x_pos, y_pos):\n super().__init__(name, 100, 100, x_pos, y_pos)\n\n # Method override, PlayerCharacter can only modify y_pos\n def move(self, by_y_amount):\n super().move(0, by_y_amount)\n\nclass NonPlayerCharacter(GameCharacter):\n \n speed = 20\n\n # Should still provide a constructor/initializer\n def __init__(self, name, x_pos, y_pos):\n super().__init__(name, 200, 200, x_pos, y_pos)\n \n # Method override, NonPlayerCharacter can only modify x_pos\n def move(self, by_x_amount):\n super().move(by_x_amount, 0)\n\n\n\nplayer_character = PlayerCharacter('P_character', 500, 500)\nprint(player_character.name) # 'P_character'\n\nplayer_character.move(100)\nprint(player_character.x_pos) # 500\nprint(player_character.y_pos) # 600\n\nnon_player_character = NonPlayerCharacter('NPC', 600, 600)\nprint(non_player_character.name) # 'NPC'\n\nnon_player_character.move(100)\nprint(non_player_character.x_pos) # 700\nprint(non_player_character.y_pos) # 600\n\n\n\n\n\n\n","sub_path":"python/zenva/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"469709964","text":"#\r\n\"\"\"\r\n\tScan APS logfile and extract relevant items\r\n to compare original SMB analysis vs. the determine_basal.py\r\n\"\"\"\r\n#\tVersion INIT\t\tStarted\t08.Dec.2019\t\t\tAuthor\tGerhard Zellermann\r\n# - adapted from scanAPSlog.py\r\n\r\nimport sys\r\nimport os\r\nimport glob\r\nfrom email.utils import formatdate\r\nimport datetime\r\nfrom datetime import timezone\r\nimport time\r\nimport json\r\nimport zipfile\r\nfrom decimal import *\r\nimport binascii\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.animation import FFMpegWriter\r\nfrom matplotlib.backends.backend_pdf import PdfPages\r\n\r\nimport determine_basal as detSMB\r\nfrom determine_basal import my_ce_file \r\n\r\n\r\ndef hole(sLine, Ab, Auf, Zu):\r\n #E extrahiere Substring ab der Stelle \"ab\"\r\n #E\tbeginnend mit dem Zeichen \"Auf\" bis zum Zeichen \"Zu\"\r\n #E\twobei Level gezählt werden wie in \"...[xxx[yy]]...\"\r\n offsetAnf = 0\r\n offsetEnd = 0\r\n Anf_pos = sLine[Ab:].find(Auf) + Ab\r\n #if sLine.find('[Intent')<3: print('hole gerufen mit:' , Auf, ' an Stelle', str(Anf_pos), 'in '+sLine)\r\n while Anf_pos>=0:\r\n End_pos = sLine[Anf_pos+offsetEnd+1:].find(Zu) + Anf_pos+offsetEnd+1\r\n #if sLine.find('[Intent')<3: print(str(Anf_pos)+':'+ Auf+', '+ str(End_pos)+':'+ Zu, 'in '+sLine[Anf_pos+offsetEnd+1:])\r\n if End_pos == Anf_pos+offsetEnd+1*0: break\r\n Zw_Anf = sLine[Anf_pos+offsetAnf+1:End_pos].find(Auf) + Anf_pos+offsetAnf+1\r\n #if sLine.find('[Intent')<3: print ('suche 2. Vorkommen von '+Auf+' in '+sLine[Anf_pos+offsetAnf+1:End_pos])\r\n #if sLine.find('[Intent')<3: print (str(Zw_Anf), str(offsetAnf), str(offsetEnd))\r\n if Zw_Anf==Anf_pos+offsetAnf: #+1 or Zw_Anf>End_pos:\r\n return sLine[Anf_pos:End_pos+1]\r\n break\r\n offsetAnf = Zw_Anf - Anf_pos\r\n offsetEnd = End_pos - Anf_pos #+ 1\r\n #wdhl = input('any key')\r\n return ''\r\n\r\ndef GetStr(Curly, Ab, Key):\r\n #E extrahiere Substring für Flag \"Key\" ab der Stelle Ab\r\n\r\n wo\t= Curly[Ab:].find('\"' + Key +'\"') + Ab\r\n if wo < Ab:\r\n Found = ''\r\n else:\r\n bis\t\t= Curly[wo+len(Key)+4:].find('\"') + wo+len(Key)+4\r\n Found\t= Curly[wo+len(Key)+4:bis]\r\n #print (str(wo), str(bis))\r\n return Found \r\n\r\ndef GetValStr(Curly, Ab, Key):\r\n #E extrahiere Number as String für Flag \"Key\" ab der Stelle Ab\r\n\r\n wo\t= Curly[Ab:].find('\"' + Key +'\"') + Ab\r\n if wo < Ab:\r\n Found = ''\r\n else:\r\n bis\t\t= Curly[wo+len(Key)+3:].find(',') + wo+len(Key)+3\r\n Found\t= Curly[wo+len(Key)+3:bis]\r\n #print (str(wo), str(bis))\r\n return Found \r\n\r\ndef GetUnquotedStr(Curly, Ab, Key):\r\n #E extract unquoted String für Flag \"Key\" ab der Stelle Ab up to next COMMA\r\n\r\n wo\t= Curly[Ab:].find(Key) + Ab\r\n if wo < Ab:\r\n Found = ''\r\n else:\r\n bis\t\t= Curly[wo+len(Key)+0:].find(',') + wo+len(Key)+0\r\n Found\t= Curly[wo+len(Key)+0:bis]\r\n #print (str(wo), str(bis))\r\n return Found \r\n\r\ndef printBool(treat, key, log):\r\n if 'isSMB' in treat: isSMB = treat[key]\r\n else: isSMB = False\r\n log.write(' ' + (key+' ')[:5] + '=' + str(isSMB) + '\\n')\r\n\r\ndef printStr(treat, key, log):\r\n if key in treat:\r\n myStr = treat[key]\r\n wo = myStr.find('\\n')\r\n if wo>0:\r\n myEnd = myStr[wo+1:] # \\n counts as 1 character !!\r\n myStr = myStr[:wo] + ' --> ' + myEnd # Announcements often take 2 lines\r\n else:\r\n myStr = ''\r\n log.write(' ' + (key+' ')[:10] + '=' + myStr + '\\n')\r\n\r\ndef printVal(treat, key, log):\r\n log.write(' ' + (key+' ')[:6] + '=' + str(treat[key]) + '\\n')\r\n\r\ndef getReason(reason, keyword, ending, dezi):\r\n wo_key = reason.find(keyword)\r\n #print (wo_key, reason + '\\n')\r\n if wo_key < 0:\r\n #print (keyword , 'nicht gefunden')\r\n return ''\r\n else:\r\n wo_com = reason[wo_key+len(keyword)+1:].find(ending) + wo_key+len(keyword)+1\r\n #print (reason[wo_key:])\r\n key_str = reason[wo_key+len(keyword):wo_com]\r\n #print ('complete-->', keyword, '['+key_str+']')\r\n #key_str = key_str[:-1]\r\n #print (' capped-->', keyword, '['+key_str+']')\r\n return key_str\r\n\r\ndef basalFromReason(smb, lcount):\r\n #print(str(smb))\r\n suggest = smb['openaps']['suggested']\r\n if 'rate' in suggest :\r\n rateReq = suggest['rate']\r\n elif 'TempBasalAbsoluteRate' in smb['pump']['extended']:\r\n rateReq = smb['pump']['extended']['TempBasalAbsoluteRate']\r\n else:\r\n rateReq = 0 # zero if not explicitely listed\r\n #print('rateReq in row '+str(lcount)+' from \"suggest.json\" is ['+str(rateReq)+']')\r\n\r\n return str(rateReq)\r\n\r\ndef basalFromReasonOnlyold(reason, lcount):\r\n # the method below is very difficult and still incomplete\r\n # obviously various programmers followed differnet logic how to declare the new rate \r\n if reason.find('no temp required')>1 :\r\n tempReq = '0'\r\n tempSource = \"no temp required\"\r\n else :\r\n tempReq = getReason(reason, 'maxSafeBasal:', ',', 3)\r\n tempSource = \"maxSafeBasal:...,\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp', '~<', 3)\r\n tempSource = \"temp...~<\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp', '>~', 3)\r\n tempSource = \"temp...>~\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, '<', 'U', 3)\r\n tempSource = \"<...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, '~ req', 'U', 3)\r\n tempSource = \"~ req...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp of', 'U', 3)\r\n tempSource = \"temp of...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp', '<', 3)\r\n tempSource = \"temp...<\"\r\n if tempReq != '': tempReq = str(round(eval(tempReq),4))\r\n else : tempReq = '0'\r\n log_msg('tempReq in row '+str(lcount)+' from \"'+tempSource+'\" is ['+tempReq+']')\r\n \r\n return tempReq\r\n\r\ndef basalFromReasonOnly(reason, lcount):\r\n # the method below is very difficult and still incomplete\r\n # obviously various programmers followed differnet logic how to declare the new rate \r\n if reason.find('no temp required')>1 :\r\n tempReq = '0'\r\n tempSource = \"no temp required\"\r\n else :\r\n tempReq = getReason(reason, 'maxSafeBasal:', ',', 3)\r\n tempSource = \"maxSafeBasal:...,\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp', '~<', 3)\r\n tempSource = \"temp...~<\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp', '>~', 3)\r\n tempSource = \"temp...>~\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'm low temp of', 'U', 3) # near source row 1049\r\n tempSource = \"m low temp of...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp of', 'U', 3)\r\n tempSource = \"temp of...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'setting', 'U', 3)\r\n tempSource = \"setting...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, '<', 'U', 3)\r\n tempSource = \"<...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, '~ req', 'U', 3)\r\n tempSource = \"~ req...U\"\r\n if tempReq == '':\r\n tempReq = getReason(reason, 'temp', '<', 3)\r\n tempSource = \"temp...<\"\r\n #print('tempReq in row '+str(lcount)+' from \"'+tempSource+'\" is ['+tempReq+']')\r\n if tempReq != '': tempReq = str(round(eval(tempReq),4))\r\n else : tempReq = '0'\r\n #print('tempReq in row '+str(lcount)+' from \"'+tempSource+'\" is ['+tempReq+']')\r\n \r\n return tempReq\r\n\r\ndef basalFromEmulation(returned, lcount):\r\n #returned = json.loads(reason)\r\n if 'rate' in returned:\r\n tempReq = returned['rate'] # soecific basal rate requested\r\n else:\r\n tempReq = currenttemp['rate'] # no change, keep current basal rate\r\n return str(round(tempReq,4))\r\n\r\ndef setVariant(stmp):\r\n # set the what-if scenario\r\n global autosens_data\r\n global glucose_status\r\n global bg\r\n global currenttemp\r\n global iob_data\r\n global meal_data\r\n global profile\r\n ####################################################################################################################################\r\n # additional parameters collected here\r\n # these need an according modification in \"determine_basal.py\"\r\n new_parameter = {}\r\n # first, do the AAPS standard assignments ### variations are set in the .dat file\r\n new_parameter['maxDeltaRatio'] = 0.2 ### additional parameter; AAPS is fix at 0.2\r\n new_parameter['SMBRatio'] = 0.5 ### additional parameter; AAPS is fix at 0.5; I use 0.6 as no other rig interferes\r\n new_parameter['maxBolusIOBUsual'] = True ### additional parameter; AAPS is fix at True, but my basal is too low\r\n new_parameter['maxBolusIOBRatio'] = 1 ### additional parameter; AAPS is fix at 1, but my basal is too low\r\n new_parameter['maxBolusTargetRatio'] = 1.001 ### additional parameter; AAPS is fix at 1, bit i saw rounding problems otherwise\r\n new_parameter['insulinCapBelowTarget'] = False ### additional parameter; AAPS is fix at False; enable capping below target\r\n \r\n ####################################################################################################################################\r\n STAIR = {} # for staircase type functions like basal\r\n INTERPOL = [] # for linear interpolation between values\r\n flag_staircase = False\r\n # read the variations and apply them\r\n fnam= varLabel + '.dat'\r\n var = open(varFile, 'r')\r\n for zeile in var:\r\n # get array name\r\n woEndArray = zeile.find(' ')\r\n myArray = zeile[:woEndArray]\r\n zeile = zeile[woEndArray:] # remaining stuff to be parsed\r\n while zeile[0] == ' ': zeile = zeile[1:] # truncate leading BLANKS\r\n woEndItem = zeile.find(' ')\r\n myItem = zeile[:woEndItem]\r\n zeile = zeile[woEndItem:] # remaining stuff to be parsed\r\n while zeile[0] == ' ': zeile = zeile[1:] # truncate leading BLANKS\r\n woEndVal = zeile.find('###')\r\n if woEndVal<0 and zeile[-1]=='\\n': woEndVal = len(zeile) - 1 # no trailing comment; drop \r\n myVal = zeile[:woEndVal]\r\n if myVal != '':\r\n while myVal[-1] == ' ' : myVal = myVal[:-1] # truncate trailing BLANKS\r\n #print('['+myArray+'], ['+myItem+'], ['+myVal+']')\r\n \r\n woSTAIR = myVal.find('STAIR')\r\n if woSTAIR >= 0: # get value from last valid step\r\n for STEP in STAIR:\r\n if STEP == stmp:\r\n newVal = STAIR[STEP]\r\n break\r\n elif STEP > stmp:\r\n break\r\n newVal = STAIR[STEP]\r\n myVal = myVal[:woSTAIR] + str(newVal) + myVal[woSTAIR+5:]\r\n\r\n woINTERPOL = myVal.find('INTERPOL')\r\n if woINTERPOL>= 0: # get value from last valid step\r\n (STEP, sVal) = INTERPOL[0] # low end tuple\r\n (STEPt, sValt) = INTERPOL[len(INTERPOL)-1] # high end tuple\r\n if STEP > stmp: # extrapolate backwards\r\n (STEPt, sValt) = INTERPOL[1] # second tuple\r\n lowVal = sVal\r\n topVal = sValt\r\n lowTime= ConvertSTRINGooDate(STEP)\r\n myTime = ConvertSTRINGooDate(stmp)\r\n topTime= ConvertSTRINGooDate(STEPt)\r\n newVal = lowVal + (topVal-lowVal)/(topTime-lowTime)*(myTime-lowTime)\r\n elif STEPt < stmp: # extrapolate forwards\r\n (STEP, sVal) = INTERPOL[len(INTERPOL)-2] # last but 1 tuple\r\n lowVal = sVal\r\n topVal = sValt\r\n lowTime= ConvertSTRINGooDate(STEP)\r\n myTime = ConvertSTRINGooDate(stmp)\r\n topTime= ConvertSTRINGooDate(STEPt)\r\n newVal = lowVal + (topVal-lowVal)/(topTime-lowTime)*(myTime-lowTime)\r\n else: # interpolate inside range\r\n for i in range(len(INTERPOL)):\r\n (STEP, sVal) = INTERPOL[i]\r\n if STEP == stmp:\r\n newVal = INTERPOL[STEP]\r\n break\r\n elif STEP > stmp:\r\n topVal = sVal\r\n lowTime= ConvertSTRINGooDate(lowLabl)\r\n myTime = ConvertSTRINGooDate(stmp)\r\n topTime= ConvertSTRINGooDate(STEP)\r\n newVal = lowVal + (topVal-lowVal)/(topTime-lowTime)*(myTime-lowTime)\r\n break\r\n lowVal = sVal \r\n lowLabl= STEP\r\n myVal = myVal[:woINTERPOL] + str(newVal) + myVal[woINTERPOL+8:]\r\n\r\n logmsg = 'appended new entry to'\r\n validRow = True\r\n if myArray == 'autosens_data' :\r\n if myItem in autosens_data :\r\n logmsg = 'edited old value of '+str(autosens_data[myItem])+' in'\r\n autosens_data[myItem] = eval(myVal)\r\n logres = str(autosens_data[myItem])\r\n elif myArray == 'glucose_status' :\r\n if myItem in glucose_status :\r\n logmsg = 'edited old value of '+str(glucose_status[myItem])+' in'\r\n glucose_status[myItem] = eval(myVal)\r\n logres = str(glucose_status[myItem])\r\n elif myArray == 'currenttemp' :\r\n if myItem in currenttemp :\r\n logmsg = 'edited old value of '+str(currenttemp[myItem])+' in'\r\n currenttemp[myItem] = eval(myVal)\r\n logres = str(currenttemp[myItem])\r\n elif myArray == 'iob_data' :\r\n if myItem in iob_data :\r\n logmsg = 'edited old value of '+str(iob_data[myItem])+' in'\r\n iob_data[myItem] = eval(myVal)\r\n logres = str(iob_data[myItem])\r\n elif myArray == 'meal_data' :\r\n if myItem in meal_data :\r\n logmsg = 'edited old value of '+str(meal_data[myItem])+' in'\r\n meal_data[myItem] = eval(myVal)\r\n logres = str(meal_data[myItem])\r\n elif myArray == 'profile' :\r\n if myItem in profile :\r\n logmsg = 'edited old value of '+str(profile[myItem])+' in'\r\n profile[myItem] = eval(myVal)\r\n logres = str(profile[myItem])\r\n elif myArray == 'new_parameter' :\r\n if myItem in new_parameter :\r\n logmsg = 'edited old value of '+str(new_parameter[myItem])+' in'\r\n new_parameter[myItem] = eval(myVal)\r\n logres = str(new_parameter[myItem])\r\n elif myArray == 'STAIR' :\r\n STAIR[myItem] = eval(myVal)\r\n elif myArray == 'INTERPOL' :\r\n if len(myItem) < 24: # incomplete UTC time label\r\n oldLen = len(myItem)\r\n if myItem[oldLen-1:] == 'Z':\r\n oldLen += -1\r\n myItem = myItem[:-1]\r\n myItem = myItem + '00:00:00.000Z'[oldLen-11:]\r\n INTERPOL.append((myItem, eval(myVal)) )\r\n else:\r\n validRow = False\r\n \r\n if validRow: varlog.write(logmsg+' '+myArray+' with '+myItem+'='+logres+'\\n')\r\n else: varlog.write('not actioned: ['+myArray+'], ['+myItem+'], ['+myVal+']'+'\\n')\r\n \r\n ####################################################################################################################################\r\n # final clean up\r\n profile['new_parameter'] = new_parameter ### use profile as piggyback to get parameters into determine_basal\r\n bg[-1] = glucose_status['glucose'] ### just in case it got changed \r\n global emulTarLow\r\n global emulTarHig\r\n emulTarLow[-1] = profile['min_bg'] ### please do not touch\r\n emulTarHig[-1] = profile['max_bg'] ### please do not touch\r\n global emulAs_ratio\r\n emulAs_ratio.append(autosens_data['ratio']*10)\r\n\r\ndef getOrigPred(predBGs):\r\n Fcasts = {}\r\n for BGs in predBGs:\r\n Fcasts[BGs] = predBGs[BGs]\r\n #print ('orig preds --> '+str(Fcasts))\r\n return Fcasts\r\n\r\ndef TreatLoop(Curly, log, lcount):\r\n global SMBreason\r\n global loop_mills\r\n global loop_label\r\n global origInsReq\r\n global origSMB\r\n global emulSMB\r\n global origMaxBolus\r\n global emulMaxBolus\r\n global origBasal\r\n global lastBasal\r\n global Pred\r\n global FlowChart\r\n #print('\\nentered TreatLoop for row '+str(lcount)+' ending with /'+Curly[-1]+'/ having '+Curly[780:800]+'\\n'+Curly)\r\n wo_apo = Curly.find(\"\\'\")\r\n if wo_apo>0:\r\n Curly = Curly[:wo_apo-1]+Curly[wo_apo:]\r\n #print(\"found \\' at position \"+str(wo_apo)+\"\\n\" +Curly)\r\n smb = json.loads(Curly)\r\n if 'openaps' in smb: # otherwise unknown source of entry\r\n suggest = smb['openaps']['suggested']\r\n #thisTime = int(round(time.time() * 1000)) # use as now() or the emulated execution tiume\r\n stmp = suggest['deliverAt']\r\n if t_startLabel > stmp : # too early\r\n SMBreason = {} # clear for first filtered debug list\r\n SMBreason['script'] = '---------- Script Debug --------------------\\n'\r\n return 'MORE' \r\n if t_stoppLabel < stmp : return 'STOP' # too late; send quit signal\r\n thisTime = ConvertSTRINGooDate(stmp)\r\n loop_mills.append(round(thisTime/1000, 1) ) # from millis to secs\r\n loop_label.append(stmp[11:19] + stmp[-1]) # include seconds to distinguish entries\r\n #print('len loop_mills='+str(len(loop_mills))+'; len labels='+str(len(loop_label)))\r\n reason = suggest['reason']\r\n if 'insulinReq' in suggest:\r\n log.write('\\n========== DELTA in row ' + str(lcount) + ' SMB ========== of logfile '+fn+'\\n')\r\n log.write(' created at= ' + smb['created_at'] + '\\n')\r\n log.write(SMBreason['script']) # the script debug section\r\n #printVal(suggest, 'bg', log)\r\n origcob.append(round(suggest['COB'], 1))\r\n #log.write(' COB =' + str(cob) + '\\n')\r\n #iob.append(round(suggest['IOB']*10, 1)) # done in iob-data\r\n key = 'insulinReq'\r\n ins_Req = suggest[key]\r\n #log.write(' ' + (key+' ')[:6] + '=' + str(insReq) + '\\n')\r\n if ins_Req > 0.0: # can be empty string; was >0.2 before\r\n mySMB = getReason(reason, 'Microbolusing', 'U', 1)\r\n maxBol = getReason(reason, 'maxBolus', '. ', 1)\r\n if len(maxBol) > 5 :\r\n maxBol = getReason(reason, 'maxBolus', '; ', 1)\r\n else:\r\n mySMB = '0'\r\n maxBol = '0'\r\n else:\r\n ins_Req = 0\r\n mySMB = '0'\r\n maxBol = '0'\r\n if mySMB == '' : mySMB = '0'\r\n if maxBol== '' : maxBol= '0'\r\n origSMB.append(eval(mySMB))\r\n origMaxBolus.append(eval(maxBol))\r\n log.write('---------- Reason --------------------------\\n' + str(reason) + '\\n')\r\n tempReq = basalFromReason(smb, lcount)\r\n origBasal.append(round(eval(tempReq), 4))\r\n \r\n # now we can set the remaining iob data section\r\n last_temp = {}\r\n last_temp['typeof'] = 'dummy' # may be anything\r\n last_temp['date'] = thisTime - SMBreason['lastTempAge'] *60*1000 # copy from original logfile\r\n last_temp['rate'] = currenttemp['rate']\r\n last_temp['duration'] = currenttemp['duration']\r\n iob_data['lastTemp']= last_temp\r\n lastBasal.append(currenttemp['rate'])\r\n \r\n log = open(ce_file, 'a')\r\n log.write('\\n========== '+varLabel+' loop in row ' + str(lcount) +' ========== of logfile '+fn+'\\n')\r\n log.write(' created at= ' + stmp[:-5]+stmp[-1] +'\\n')\r\n log.write('---------- Script Debug --------------------\\n')\r\n log.close()\r\n #tempBasalFunctions = set_tempBasalFunctions() # look up in profile\r\n reservoir = 47 # currently fixed\r\n tempBasalFunctionsDummy = '' # is handled inside determine_basal as import\r\n origInsReq.append(ins_Req)\r\n varlog.write('\\nloop execution in row='+str(lcount)+' of logfile '+fn+' at= ' + smb['created_at'] + '\\n')\r\n setVariant(stmp)\r\n Fcasts = getOrigPred(suggest['predBGs'])\r\n Flows = []\r\n reT = detSMB.determine_basal(glucose_status, currenttemp, iob_data, profile, autosens_data, meal_data, tempBasalFunctionsDummy, True, reservoir, thisTime, Fcasts, Flows)\r\n reason = echo_rT(reT) # overwrite the original reason\r\n maxBolStr = getReason(reason, 'maxBolus', '. ', 1)\r\n if len(maxBolStr) > 5 :\r\n maxBolStr = getReason(reason, 'maxBolus', '; ', 1)\r\n if maxBolStr == '' : maxBolStr = '0'\r\n emulMaxBolus.append(eval(maxBolStr))\r\n mySMBstr = getReason(reason, 'Microbolusing', 'U', 1)\r\n if mySMBstr == '' : mySMBstr = '0'\r\n emulSMB.append(eval(mySMBstr))\r\n\r\n if reason.find('COB: 0,') == 0: \r\n Fcasts['COBpredBGs'] = [] # clear array if COB=0\r\n Pred[round(thisTime/1000,1)] = Fcasts\r\n FlowChart[round(thisTime/1000,1)] = Flows\r\n #print(str(FlowChart))\r\n #next loop execution\r\n SMBreason = {} # clear for next debug list\r\n SMBreason['script'] = '---------- Script Debug --------------------\\n'\r\n return 'MORE'\r\n\r\ndef PrepareSMB(zeile, log, lcount):\r\n # collect SMB detail echos before actual, compacted loop protocol comes\r\n global SMBreason\r\n key_str = '[LoggerCallback.jsFunction_log():39]'\r\n what_anf = zeile.find(key_str)\r\n what = zeile[what_anf+len(key_str)+2:]\r\n SMBreason['script'] += what\r\n if what.find('SMB enabled')==0:\r\n SMBreason['rowON'] = lcount\r\n SMBreason['whyON'] = what[:-1]\r\n elif what.find('disabling SMB')>0:\r\n SMBreason['rowOFF'] = lcount\r\n SMBreason['whyOFF'] = what[:-1]\r\n elif what.find('maxBolus: ')>0:\r\n SMBreason['maxSMB'] = what[-4:-1]\r\n elif what.find('gz maximSMB: from ')==0:\r\n SMBreason['maxBolus'] = what[:-1]\r\n elif what.find('currenttemp:')==0: # unclear source of TempAge, but should be the same in emulation\r\n wo_anf = what.find('lastTempAge:')\r\n wo_end = what.find(' m tempModulus:')\r\n SMBreason['lastTempAge'] = eval(what[wo_anf+13:wo_end])\r\n\r\ndef featured(Option):\r\n # check whethter this feature was in the option list passed from OO.odb\r\n # or if ALL option were enabled\r\n # otherwise FALSE\r\n OK = 'All' in doit or Option in doit\r\n if '-'+Option in doit: OK = False # explicitly excluded\r\n return OK\r\n\r\ndef get_glucose_status(lcount, st) : # key = 80\r\n Curly = st[16:]\r\n global glucose_status\r\n global bg\r\n global newLoop\r\n newLoop = True\r\n #print('entered glucose_status for row '+str(lcount)+' with\\n'+Curly)\r\n glucose_status = json.loads(Curly)\r\n glucose_status['row'] = lcount\r\n if len(bg)==len(loop_mills) :\r\n bg.append(glucose_status['glucose']) # start next iteration\r\n else:\r\n bg[-1] = (glucose_status['glucose']) # overwrite as last loop was not finished\r\n #print ('\\nbg data found in row '+str(lcount)+', total count='+str(len(bg))\r\n pass\r\n\r\ndef get_iob_data(lcount, st, log) : # key = 81\r\n if isZip:\r\n Curly = st[16:] # zip format: dropped the earlier\r\n else:\r\n Curly = st[16:-1] # drop the \r\n global iob_data\r\n global activity\r\n iob_array = json.loads(Curly)\r\n iob_data = {}\r\n iob_data['typeof'] = 'dummy' # may be anything\r\n # get first record as current iob\r\n rec_0 = iob_array[0]\r\n for ele in rec_0 :\r\n if ele != 'iobWithZeroTemp': iob_data[ele] = rec_0[ele]\r\n if ele == 'iob':\r\n act = rec_0[ele]\r\n if len(origiob) ==len(loop_mills):\r\n origiob.append(act*10)\r\n else:\r\n origiob[-1] = (act*10)\r\n if ele == 'activity':\r\n act = rec_0[ele]\r\n if len(activity) ==len(loop_mills):\r\n activity.append(act*1000)\r\n else:\r\n activity[-1] = (act*1000)\r\n \r\n iob_data['iobArray']= iob_array\r\n #print ('preliminary iob data json --> '+str(lcount) +' : '+ str(iob_data))\r\n #for ele in iob_array:\r\n # log.write(str(ele)+':'+'\\n')\r\n #print ('iob data found in row '+str(lcount)+', total count='+str(len(iob_data)))\r\n pass\r\n\r\ndef get_currenttemp(lcount, st) : # key = 82\r\n Curly = st[16:]\r\n global currenttemp\r\n currenttemp = json.loads(Curly)\r\n currenttemp[\"typeof\"] =\"dummy\" # may be anything\r\n currenttemp[\"row\"] = lcount\r\n #print ('currenttemp json --> '+str(currenttemp))\r\n pass\r\n\r\ndef get_profile(lcount, st) : # key = 83\r\n Curly = st[16:]\r\n global profile\r\n global origTarLow\r\n global origTarHig\r\n global emulTarLow\r\n global emulTarHig\r\n profile = json.loads(Curly)\r\n profile['maxDeltaRatio'] = 0.2 ### additional parameter; define standard\r\n profile['row'] = lcount\r\n # unknown source, use apparent default:\r\n profile['remainingCarbsFraction'] = 1\r\n #profile['temptargetSet'] = True # historical logfiles say FALSE !!!!!!!!!!!!!!!!\r\n profile['sensitivity_raises_target'] = False # missing from historical logfiles !!!!!!!!!!!!!!!!\r\n if len(origTarLow)==len(loop_mills) : # start next iteration\r\n origTarLow.append(profile['min_bg'])\r\n emulTarLow.append(origTarLow[-1])\r\n origTarHig.append(profile['max_bg'])\r\n emulTarHig.append(origTarHig[-1])\r\n else: # overwrite as last loop was not finished\r\n origTarLow[-1] = profile['min_bg']\r\n emulTarLow[-1] = origTarLow[-1]\r\n origTarHig[-1] = profile['max_bg']\r\n emulTarHig[-1] = origTarHig[-1]\r\n #print ('master profile json in row '+str(lcount)+' --> '+str(profile))\r\n #print ('target data found in row '+str(lcount)+', total count origTarLow='+str(len(origTarLow)))\r\n #print ('target data found in row '+str(lcount)+', total count emulTarLow='+str(len(origTarLow)))\r\n pass\r\n\r\ndef get_meal_data(lcount, st) : # key = 84\r\n Curly = st[16:]\r\n global meal_data\r\n meal_data = json.loads(Curly)\r\n meal_data['row'] = lcount\r\n # use fixed settings for the time being ...\r\n meal_data['bwCarbs'] = False # bolus wizzard carbs\r\n meal_data['bwFound'] = False # bolus wizzard used ?\r\n #print ('meal data json --> '+str(meal_data))\r\n pass\r\n\r\ndef get_autosens_data(lcount, st) : # key = 86\r\n Curly = st[16:]\r\n global autosens_data\r\n global As_ratio\r\n autosens_data = json.loads(Curly)\r\n autosens_data['typeof'] = 'dummy' # may be anything\r\n autosens_data['row'] = lcount\r\n if len(origAs_ratio) ==len(loop_mills) :\r\n origAs_ratio.append(autosens_data['ratio']*10)\r\n else:\r\n origAs_ratio[-1] = (autosens_data['ratio']*10)\r\n pass\r\n\r\ndef ConvertSTRINGooDate(stmp) :\r\n # stmp is datetime string incl millis, i.e. like \"2019-05-22T12:06:48.091Z\"\r\n if stmp < \"2019-10-27T03:00:00.000Z\":\r\n dlst = 3600 # dlst period summer 2019\r\n elif stmp < \"2020-03-29T02:00:00.000Z\":\r\n dlst = 0 # no dlst period winter 2019/20\r\n else:\r\n dlst = 3600 # dlst period summer 2020\r\n MSJahr\t\t= eval( stmp[ 0:4])\r\n MSMonat\t\t= eval('1'+stmp[ 5:7]) -100\r\n MSTag\t\t= eval('1'+stmp[ 8:10])-100\r\n MSStunde\t= eval('1'+stmp[11:13])-100\r\n MSMinute\t= eval('1'+stmp[14:16])-100\r\n MSSekunde\t= eval('1'+stmp[17:19])-100\r\n MSmillis = eval('1'+stmp[20:23])-1000\r\n #print ('millis aus '+stmp+' = '+str(MSmillis))\r\n NumericDate= datetime.datetime(MSJahr, MSMonat, MSTag, MSStunde, MSMinute, MSSekunde, MSmillis*1000)\r\n #imestamp = NumericDate.replace(tzinfo=timezone.utc).timestamp() + 3600 # 1h MEZ offset\r\n #print('entered Convert.. with stmp='+stmp+'\\n NumericDate='+str(NumericDate))\r\n timestamp = int( (NumericDate.timestamp() + 3600 + dlst) * 1000 ) # 1h MEZ offset\r\n #print(' timestamp='+str(timestamp))\r\n #print(\"Eingang: \" + stmp + \"\\nAusgang: \" + str(timestamp) )\r\n return timestamp\r\n\r\ndef scanLogfile(fn):\r\n global SMBreason\r\n global xyf\r\n global fn_base # keep first match in case of wild card file list\r\n global log\r\n global varlog\r\n global newLoop\r\n global dataType_offset\r\n \r\n if not newLoop: # otherwise continued from provious logfile\r\n SMBreason = {}\r\n SMBreason['script'] = '---------- Script Debug --------------------\\n'\r\n dataType_offset = 1 #################### used for V2.6.1\r\n if filecount == 0 : # initalize file loop\r\n fn_base = fn + '.' + varLabel\r\n xyf = open(fn + '.' + varLabel + '.tab', 'w')\r\n varlog = open(fn + '.' + varLabel + '.log', 'w')\r\n log = open(fn + '.orig.txt', 'w')\r\n varlog.write('\\n========== Echo of what-if definitions actioned for variant '+varLabel+'\\n========== created on '+formatdate(localtime=True) + '\\n========== for loop events found in logfile '+fn+'\\n')\r\n log.write('AAPS scan from AAPS Logfile for SMB comparison created on ' + formatdate(localtime=True) + '\\n')\r\n log.write('FILE='+fn + '\\n')\r\n global lcount\r\n #isZip = True # testwise fix\r\n lcount = 0\r\n if isZip:\r\n with zipfile.ZipFile(fn) as z:\r\n for filename in z.namelist():\r\n lf = z.open(filename) # has only 1 member file\r\n else:\r\n lf = open(fn, 'r')\r\n #lf = open(fn, 'r')\r\n notEOF = True # needed because \"for zeile in lf\" does not work with AAPS 2.5\r\n \r\n while notEOF: # needed because \"for zeile in lf\" does not work with AAPS 2.5\r\n try: # needed because \"for zeile in lf\" does not work with AAPS 2.5\r\n zeile = lf.readline() # needed because \"for zeile in lf\" does not work with AAPS 2.5\r\n if isZip: zeile = str(zeile)[2:-3]# strip off the \"'b....'\\n\" remaining from the bytes to str conversion\r\n if zeile == '': # needed because \"for zeile in lf\" does not work with AAPS 2.5\r\n notEOF = False # needed because \"for zeile in lf\" does not work with AAPS 2.5\r\n break # needed because \"for zeile in lf\" does not work with AAPS 2.5\r\n lcount += 1\r\n #print(zeile)\r\n if lcount>100000: \r\n print('no end found at row '+str(lcount)+ ' reading /'+zeile+'/')\r\n return 'STOP'\r\n if len(zeile)>13:\r\n headerKey = zeile[2] + zeile[5] + zeile[8] + zeile[12]\r\n if headerKey == '::. ':\r\n sLine = zeile[13:]\r\n Action = hole(sLine, 0, '[', ']')\r\n sOffset = len(Action)\r\n Block2 = hole(sLine, 1+sOffset, '[', ']')\r\n if Block2 == '[DataService.onHandleIntent():54]' \\\r\n or Block2 == '[DataService.onHandleIntent():55]': # token :54 added for AAPS version 2.5\r\n pass\r\n elif Block2[:-3] == '[DetermineBasalAdapterSMBJS.invoke():': # various input items for loop\r\n dataStr = sLine[sLine.find(']: ')+3:]\r\n dataType = eval(Block2[len(Block2)-3:-1]) # extract last 2 digits as type key\r\n if dataType == 79 : # start counter in V2.5.1 only\r\n dataType_offset = 0 #################### used for V2.5.1\r\n elif dataType == dataType_offset+80 : get_glucose_status(lcount, dataStr)\r\n elif dataType == dataType_offset+81 : get_iob_data(lcount, dataStr, log)\r\n elif dataType == dataType_offset+82 : get_currenttemp(lcount, dataStr)\r\n elif dataType == dataType_offset+83 : get_profile(lcount, dataStr)\r\n elif dataType == dataType_offset+84 : get_meal_data(lcount, dataStr)\r\n elif dataType == dataType_offset+86 : get_autosens_data(lcount, dataStr)\r\n elif Block2 == '[LoggerCallback.jsFunction_log():39]': # script debug info from console.error\r\n PrepareSMB(sLine, log, lcount) \r\n elif Block2 == '[DbLogger.dbAdd():29]': ################## flag for V2.5.1\r\n Curly = hole(sLine, 1+sOffset+len(Block2), '{', '}')\r\n #print('calling TreatLoop in row '+str(lcount)+' with\\n'+Curly)\r\n if Curly.find('{\"device\":\"openaps:')==0: \r\n cont = TreatLoop(Curly, log, lcount)\r\n if cont == 'STOP' : return cont\r\n elif zeile.find('data:{\"device\":\"openaps:') == 0 : ################## flag for V2.6.1\r\n Curly = hole(zeile, 5, '{', '}')\r\n #print('calling TreatLoop in row '+str(lcount)+' with\\n'+Curly)\r\n if Curly.find('{\"device\":\"openaps:')==0: \r\n cont = TreatLoop(Curly, log, lcount)\r\n if cont == 'STOP' : return cont\r\n\r\n except UnicodeDecodeError: # needed because \"for zeile in lf\" does not work with AAPS 2.5 containing non-printing ASCII codes\r\n lcount += 1 # skip this line, it contains non-ASCII characters!\r\n \r\n lf.close()\r\n return cont\r\n\r\ndef echo_rT(reT): # echo the unusual SMB result\r\n global emulInsReq\r\n global emulBasal\r\n log = open(ce_file, 'a')\r\n #log.write ('\\nreT --> '+str(reT)+'\\n')\r\n \r\n if 'error' in reT :\r\n log_msg ('returned \"error\" with ...\\n ' + reT['error'])\r\n reason = reT['error']\r\n elif 'setTempBasal' in reT: # normal finish\r\n sub_names = ['rate', 'duration', 'profile', 'rT', 'currenttemp']\r\n ele = reT['setTempBasal']\r\n reason = ele[3]['reason']\r\n log.write('---------- Reason --------------------------\\n' + str(reason) + '\\n')\r\n emulInsReq.append(ele[3]['insulinReq'])\r\n emulBasal.append(max(0,ele[0]))\r\n elif 'reason' in reT: # normal finish\r\n reason = reT['reason']\r\n log.write('---------- Reason --------------------------\\n' + str(reason) + '\\n')\r\n emulInsReq.append(reT['insulinReq'])\r\n tempReq = basalFromEmulation(reT, lcount)\r\n emulBasal.append(eval(tempReq))\r\n else :\r\n log_msg ('returned \"unexpected content\" with ...\\n ' + str(reT))\r\n reason = str(reT)\r\n\r\n log.close()\r\n return reason\r\n\r\ndef BGValPlot(ax, BGcount, BGtype, BGlevel, BGedge, BGcol):\r\n if BGlevel+len(BGtype)/2 > 30: # otherwise BG axis scale gets funny\r\n BGarrow = dict(arrowstyle='-', fc=BGcol, ec=BGcol, linestyle='dotted')\r\n posBG = (BGlevel, BGedge+2000+400*BGcount) # vertical position of BG name\r\n posLine = (BGlevel, BGedge+ 0) # vertical pos of fcast block\r\n ax.annotate(BGtype, xy=posLine, xytext=posBG, ha='center',\r\n arrowprops=BGarrow, color=BGcol)\r\n\r\ndef AdrPlot(ax, ele, row, drow, col, dchar): # add source row number above top left\r\n if 'adr' in ele: \r\n ax.annotate(ele['adr'], xy=(col-dchar*0.31-1, row+drow*3.5+2), fontsize=5)\r\n\r\ndef getBoxSize(title): # rows and width for flowchart box\r\n tx = title\r\n #dchar = tx.find('\\n')\r\n #if dchar < 1: dchar = len(title)\r\n dchar = 1\r\n drow = 1\r\n #print('--------------------------------------\\n'+tx+'\\n has initial size('+str(dchar)+','+str(drow)+')')\r\n #tx = tx[dchar+1:]\r\n while tx.find('\\n')>0: # get count of chars and rows\r\n drow += 1\r\n eol = tx.find('\\n')\r\n if eol>dchar: dchar = eol\r\n tx = tx[eol+1:]\r\n #print(' has interim size('+str(dchar)+','+str(drow)+')')\r\n eol = len(tx)\r\n if eol>dchar: dchar = eol\r\n #print(' has final size('+str(dchar)+','+str(drow)+')')\r\n return dchar, drow\r\n\r\ndef XYplots(loopCount) :\r\n # --- ensure that last loop was finished -------------\r\n if len(loop_mills) < len(bg) : bg.pop()\r\n if len(loop_mills) < len(origTarLow) : origTarLow.pop()\r\n if len(loop_mills) < len(origTarHig) : origTarHig.pop()\r\n if len(loop_mills) < len(origInsReq) : origInsReq.pop()\r\n if len(loop_mills) < len(origMaxBolus) : origMaxBolus.pop()\r\n if len(loop_mills) < len(origSMB) : origSMB.pop()\r\n if len(loop_mills) < len(origBasal) : origBasal.pop()\r\n \r\n if len(loop_mills) < len(emulTarLow) : emulTarLow.pop()\r\n if len(loop_mills) < len(emulTarHig) : emulTarHig.pop()\r\n if len(loop_mills) < len(emulInsReq) : emulInsReq.pop()\r\n if len(loop_mills) < len(emulMaxBolus) : emulMaxBolus.pop()\r\n if len(loop_mills) < len(emulSMB) : emulSMB.pop()\r\n if len(loop_mills) < len(emulBasal) : emulBasal.pop()\r\n \r\n if len(loop_mills) < len(origcob) : origcob.pop()\r\n if len(loop_mills) < len(origiob) : origiob.pop()\r\n if len(loop_mills) < len(origAs_ratio) : origAs_ratio.pop()\r\n if len(loop_mills) < len(emulAs_ratio) : emulAs_ratio.pop()\r\n if len(loop_mills) < len(activity) : activity.pop()\r\n\r\n # --- complete the curves to close the polygon for area fill\r\n cob_area = []\r\n iob_area = []\r\n looparea = []\r\n cob_area.append(0) # top left corner\r\n iob_area.append(0) # top left corner\r\n looparea.append(loop_mills[0])\r\n i = 0\r\n for lopmil in loop_mills:\r\n cob_area.append(origcob[i]) # the regular data\r\n iob_area.append(origiob[i]) # the regular data\r\n looparea.append(lopmil)\r\n i += 1\r\n cob_area.append(0) # bottom left corner\r\n iob_area.append(0) # bottom left corner\r\n looparea.append(loop_mills[-1])\r\n cob_area.append(0) # close polygon at top left corner\r\n iob_area.append(0) # close polygon at top left corner\r\n looparea.append(loop_mills[0])\r\n \r\n # --- plot the comparisons -------------------------\r\n if loopCount <= 30 : # step size for y-axis (time)\r\n yStep = 3 # every 15 minutes\r\n elif loopCount <=60:\r\n yStep = 6 # every 30 minutes#\r\n else :\r\n yStep = 12 # every 60 minutes#\r\n yTicks = []\r\n yLabels= []\r\n \r\n for i in range(0, loopCount, yStep) : # the time labels\r\n yTicks.append(loop_mills[i])\r\n yLabels.append(loop_label[i])\r\n if loop_mills[-1] != yTicks[-1]:\r\n yTicks.append(loop_mills[-1]) # last tick could be missed out\r\n yLabels.append(loop_label[-1])\r\n if featured('pred'): # extend time axis for predictions\r\n for i in range(30, 241, 30):\r\n yTicks.append(loop_mills[-1]+i*60) # append 4 hours\r\n yLabels.append('+'+str(i)+'mins')\r\n maxframes = len(loop_mills)\r\n else:\r\n maxframes = 1\r\n thickness = (loop_mills[-1]-loop_mills[0])/loopCount/4\r\n\r\n maxPlots = 0\r\n frameIns = featured('insReq') or featured('maxBolus') or featured('SMB') or featured('basal')\r\n if frameIns : # we need frame for insulin type graph(s)\r\n maxPlots += 1\r\n frameBG = featured('bg') or featured('target') or featured('pred') or featured('as ratio') or featured ('cob') or featured('iob') or featured('activity')\r\n if frameBG : # we need frame for bg type graph(s)\r\n bgOffset = maxPlots\r\n maxPlots += 2\r\n frameFlow = featured('flowchart')\r\n if frameFlow : # we need frame for decision flow chart\r\n flowOffset = maxPlots\r\n maxPlots += 6\r\n plt.rcParams['savefig.dpi'] = 200\r\n #lt.rcParams['figure.figsize'] = (9, 18) #6*maxPlots) # h,w in inches\r\n plt.rcParams['figure.dpi'] = 200\r\n plt.rcParams['legend.fontsize'] = 'small'\r\n plt.rcParams['legend.facecolor'] = 'grey'\r\n plt.rcParams['font.size'] = 8\r\n colFav = {'bg':'red', 'ZT':'cyan', 'IOB':'blue', 'COB':'orange', 'UAM':'brown'}\r\n bbox = dict(boxstyle=\"round\", fc=\"0.8\")\r\n flowForward = dict(arrowstyle='<|-') # points to current box\r\n\r\n log_msg('Emulation finished; generating graphics pages\\n')\r\n pdfFile = fn_first + '.' + varLabel + '.pdf'\r\n pdfCleared = False\r\n while True: # wait if old pdf is still loaded in pdf viewer\r\n try:\r\n os.remove(pdfFile)\r\n if pdfCleared: log_msg('continuing ...')\r\n break\r\n except PermissionError:\r\n asleep = 10\r\n log_msg('Your graphics file seems blocked by other process. Checking again in '+str(asleep)+' sec.'+chr(7)) # sometimes I can hear that BELL\r\n time.sleep(asleep)\r\n pdfCleared=True\r\n except FileNotFoundError:\r\n break\r\n xyf = open(fn_base + '.tab', 'r')\r\n zeile = xyf.readline() # header row 1\r\n log_msg(zeile[:-1])\r\n zeile = xyf.readline() # header row 2\r\n log_msg(zeile[:-1])\r\n\r\n with PdfPages(pdfFile) as pdf:\r\n for iFrame in range(0, maxframes): # the loop instances\r\n zeile = xyf.readline() # table row \r\n log_msg(zeile[:-1]) # print it as heart beat\r\n #fig, axes = plt.subplots(1, maxPlots, constrained_layout=True, figsize=(9, 15)) #6*maxPlots) ) \r\n fig = plt.figure(constrained_layout=True, figsize=(2.2*max(6,maxPlots), 11))# w, h paper size in inches; double width if no flowchart\r\n gs = fig.add_gridspec(1,maxPlots) # 1 horizontal; 1+2+6 vertical strips\r\n fig.set_constrained_layout_pads(w_pad=0., h_pad=0., hspace=0., wspace=0.) # space to edge and between frames\r\n fig.suptitle('\\nCompare original \"' + fn + '\" vs emulation case \"' + varLabel + '\"\\n', weight='bold') # incl. for space below Headeer\r\n if frameIns : # anything related to insulin\r\n axin = fig.add_subplot(gs[0,0]) # 1 strip wide\r\n axin.xaxis.label.set_color('blue')\r\n axin.tick_params(axis='x', colors='blue')\r\n axin.set_xlabel('Insulin', weight='bold')\r\n if featured('pred'):\r\n axin.set_ylim(loop_mills[-1]+thickness*2+48*5*60+45*60, loop_mills[0]-thickness*2) # add thickness*2 so markers fit into plot frame + 45min space for BG labels\r\n else:\r\n axin.set_ylim(loop_mills[-1]+thickness*2, loop_mills[0]-thickness*2) # add thickness*2 so markers fit into plot frame\r\n axin.set_yticks(yTicks)\r\n axin.set_yticklabels(yLabels)\r\n\r\n if featured('insReq') :\r\n axin.plot(emulInsReq, loop_mills, linestyle='None', marker='o', color='red', label='insulin Req, emulated')\r\n axin.plot(origInsReq, loop_mills, linestyle='solid', marker='.', color='orange',label='insulin Req, original')\r\n if featured('maxBolus') :\r\n axin.plot(emulMaxBolus,loop_mills,linestyle='None', marker='o', color='green', label='maxBolus, emulated')\r\n axin.plot(origMaxBolus,loop_mills,linestyle='solid', color='green', label='maxBolus, orig')\r\n if featured('SMB') :\r\n axin.plot(emulSMB, loop_mills, linestyle='None', marker='o', color='black', label='SMB, emulated')\r\n axin.plot(origSMB, loop_mills, linestyle='solid', marker='.', color='yellow',label='SMB, original')\r\n if featured('basal') :\r\n axin.barh(y=loop_mills, height=thickness*2, width=emulBasal, color='white', label='tempBasal, emulated', edgecolor='blue')\r\n axin.barh(y=loop_mills, height=thickness , width=origBasal, color='blue', label='tempBasal, original')\r\n\r\n #axin.plot([0,0], [loop_mills[0],loop_mills[-1]], linestyle='dotted', color='black') # grid line for insulin=0 \r\n axin.legend(loc='lower right')\r\n \r\n if frameBG : # anything related to glucose\r\n axbg = fig.add_subplot(gs[0, bgOffset:bgOffset+2]) # 2 strips wide\r\n axbg.xaxis.label.set_color('red')\r\n axbg.tick_params(axis='x', colors='red')\r\n axbg.set_xlabel('....IOB.....Autosense.....COB... Glucose', weight='bold')\r\n if frameIns: # already annotated in insulin frame\r\n axbg.set_yticklabels(['','']) # dummy axis labels\r\n axbg.set_yticks([-1,9e99]) # off scale to suppress ticks\r\n else: # not yet annotated in insulin frame\r\n axbg.set_yticks(yTicks)\r\n axbg.set_yticklabels(yLabels)\r\n axbg.set_ylim(loop_mills[-1]+thickness*2, loop_mills[0]-thickness*2)\r\n\r\n if featured('target') : # plot targets\r\n axbg.plot(emulTarHig, loop_mills, linestyle='None', marker='o', color='black', label='target high, emulated')\r\n axbg.plot(emulTarLow, loop_mills, linestyle='None', marker='o', color='black', label='target low, emulated')\r\n axbg.plot(origTarHig, loop_mills, linestyle='dashed', marker='.', color='yellow', label='target high, original')\r\n axbg.plot(origTarLow, loop_mills, linestyle='dashed', marker='.', color='yellow', label='target low, original')\r\n\r\n if featured('bg') : # plot bg\r\n axbg.plot(bg, loop_mills, linestyle='solid', marker='o', color='red', label='blood glucose')\r\n\r\n if featured('as ratio') : # plot autosense ratio\r\n axbg.plot([10,10],[loop_mills[0],loop_mills[-1]],linestyle='dotted',color='black',label='Autosense(x10) OFF')\r\n axbg.plot(origAs_ratio,loop_mills,linestyle='solid', color='black',label='Autosense(x10), original')\r\n axbg.plot(emulAs_ratio,loop_mills,linestyle='none', marker='.', color='black',label='Autosense(x10), emulated')\r\n\r\n if featured('activity') : # plot activity\r\n axbg.plot(activity, loop_mills, linestyle='solid', color='yellow', label='Activity(x1000)')\r\n\r\n if featured('iob') : # plot IOB\r\n axbg.plot(origiob, loop_mills, linestyle='solid', color='blue', label='IOB(x10)')\r\n axbg.fill(iob_area, looparea, c='blue', alpha=0.2)\r\n \r\n if featured('cob') : # plot COB\r\n axbg.plot(origcob, loop_mills, linestyle='solid', color='orange', label='COB')\r\n axbg.fill(cob_area, looparea, c='orange', alpha=0.4)\r\n\r\n if featured('pred') : # plot the predictions\r\n thisTime = loop_mills[iFrame]\r\n loopCount = 48+1\r\n fcastmills = []\r\n for lp in range(loopCount):\r\n fcastmills.append(round(thisTime/1.000 + lp*5*60, 1 )) # from millis to secs\r\n bbox_props = dict(boxstyle='larrow', fc='grey', alpha=0.7) # slider with time label\r\n if featured('pred') : # set scale of y-axis (time)\r\n axbg.set_ylim(loop_mills[-1]+thickness*2+48*5*60+45*60, loop_mills[0]-thickness*2) # incl 45min space for BG labels\r\n else : \r\n axbg.set_ylim(loop_mills[-1]+thickness*2, loop_mills[0]-thickness*2)\r\n axbg.set_xlim(0,250) # otherwise we need to find scale over all time steps\r\n bg_min, bg_max = axbg.get_xlim()\r\n axbg.text(bg_min+3, fcastmills[0], loop_label[iFrame], va='center', size=8, bbox=bbox_props)\r\n axbg.fill_between([bg_min,bg_max], fcastmills[0]-2*thickness, fcastmills[-1]+2*thickness, fc='grey', alpha=0.6) # time window\r\n if frameIns:\r\n in_min, in_max = axin.get_xlim()\r\n axin.plot([in_min,in_max], [fcastmills[0],fcastmills[0]], linestyle='dotted', color='grey', lw=0.5) # time line\r\n\r\n Fcasts = Pred[thisTime]\r\n Levels = Fcasts['Levels']\r\n\r\n #print (str(loop_label[iFrame]), str(Levels))\r\n if 'minPredBG' in Levels:\r\n BGValPlot(axbg,-1, 'minPredBG', Levels['minPredBG'], fcastmills[-1], colFav['bg'])\r\n if 'minZTGuardBG' in Levels:\r\n BGValPlot(axbg, 1, 'minZTGuardBG', Levels['minZTGuardBG'], fcastmills[-1], colFav['ZT'])\r\n if 'minIOBPredBG' in Levels:\r\n BGValPlot(axbg, 2, 'minIOBPredBG', Levels['minIOBPredBG'], fcastmills[-1], colFav['IOB'])\r\n if 'minCOBPredBG' in Levels:\r\n BGValPlot(axbg, 3, 'minCOBPredBG', Levels['minCOBPredBG'], fcastmills[-1], colFav['COB'])\r\n if 'minUAMPredBG' in Levels:\r\n BGValPlot(axbg, 4, 'minUAMPredBG', Levels['minUAMPredBG'], fcastmills[-1], colFav['UAM'])\r\n if 'avgPredBG' in Levels:\r\n BGValPlot(axbg, 0, 'avgPredBG', Levels['avgPredBG'], fcastmills[-1], 'black')\r\n if 'naive_eventualBG' in Levels:\r\n BGValPlot(axbg,-2, 'naive_eventualBG', Levels['naive_eventualBG'], fcastmills[-1], 'purple')\r\n if 'eventualBG' in Levels:\r\n BGValPlot(axbg,-3, 'eventualBG', Levels['eventualBG'], fcastmills[-1], 'green')\r\n \r\n if 'SMBoff' in Levels:\r\n SMBmsg = 'SMB disabled:\\n' + Levels['SMBoff']\r\n threshold = Levels['value']\r\n label = Levels['type']\r\n SMBsource = Levels['source']\r\n couleur = colFav[SMBsource]\r\n minGuardBG = Levels['minGuardBG1'] # get maxin/only contributioon\r\n SMBarrow = dict(arrowstyle='<|-|>', fc=couleur, ec=couleur)\r\n if label == 'maxDelta' :\r\n Tmin = thisTime - 3*5*60\r\n Tmax = thisTime + 3*5*60\r\n posText = (minGuardBG+2, thisTime)\r\n posArrow= (threshold, thisTime)\r\n else: # why SMB is disabled\r\n Tmin = fcastmills[0]\r\n Tmax = fcastmills[-1]\r\n when_mills = Levels['timePos']\r\n if minGuardBG < 0 : # off screen location supresses all\r\n minGuardBG = 20\r\n SMBarrow = dict(arrowstyle='<|-', fc=couleur, ec=couleur)\r\n axbg.plot([0,20], [fcastmills[when_mills],fcastmills[when_mills]], linestyle='dotted', color=couleur)\r\n posText = (threshold+2, fcastmills[when_mills])\r\n posArrow= (minGuardBG, fcastmills[when_mills])\r\n axbg.plot([threshold,threshold], [Tmin,Tmax], linestyle='dashed', color='grey', label=label)\r\n if not 'source2' in Levels: # single source\r\n axbg.annotate(SMBmsg, xy=posArrow, xytext=posText, va='center',\r\n arrowprops=SMBarrow ) # no alignment option: va='center') )\r\n else: # blended minGuard case !\r\n SMBsource2 = Levels['source2']\r\n minGuardBG2 = Levels['minGuardBG2']\r\n hub_bg = Levels['minGuardBG'] # bg position of hub for \"balance\"\r\n couleur2 = colFav[SMBsource2]\r\n when_mills2 = Levels['timePos2']\r\n share2 = (minGuardBG2-hub_bg)/(minGuardBG2-minGuardBG) # fraction of BG2\r\n hub_mills = fcastmills[when_mills2]+(fcastmills[when_mills]-fcastmills[when_mills2])*share2 # time of hub for \"balance\"\r\n posText = (threshold+2, hub_mills)\r\n posArrow= (hub_bg, hub_mills)\r\n axbg.annotate(SMBmsg, xy=posArrow, xytext=posText, va='center',\r\n arrowprops=SMBarrow ) # no alignment option: va='center') )\r\n axbg.plot((hub_bg,minGuardBG2), (hub_mills,fcastmills[when_mills2]),\r\n linestyle='dotted', marker='o', color=couleur2) # plot the lever arm of lesser contribution\r\n axbg.plot((hub_bg,minGuardBG), (hub_mills,fcastmills[when_mills]), \r\n linestyle='dotted', marker='o', color=couleur) # plot the lever arm of lesser contribution\r\n else:\r\n SMBsource = ''\r\n axbg.plot([0,0], [0,0], linestyle='dashed', color='grey', label='...')# inactive, i.e. off screen; placeholder for legend\r\n \r\n if 'COB' in Fcasts: # assume same logic as in original\r\n origCOB = Fcasts['COB'] # the initial array before cleanup\r\n initCOB = Fcasts['COBinitBGs'] # the initial array before cleanup\r\n predCOB = Fcasts['COBpredBGs'] # is empty if COB=0\r\n axbg.plot(origCOB, fcastmills[:len(origCOB)], linestyle='solid', color=colFav['COB'], label='predCOB, original')\r\n axbg.plot(initCOB, fcastmills[:len(initCOB)], linestyle='None', marker='.', color=colFav['COB'], fillstyle='none')\r\n axbg.plot(predCOB, fcastmills[:len(predCOB)], linestyle='None', marker='.', color=colFav['COB'], label='predCOB, emulated')\r\n else:\r\n axbg.plot([0,0], [0,0], linestyle='none', color=colFav['COB'], label='no COB active') # inactive\r\n \r\n if 'UAM' in Fcasts : # same logic as in original or minGuard source\r\n origUAM = Fcasts['UAM'] # the initial array before cleanup\r\n axbg.plot(origUAM, fcastmills[:len(origUAM)], linestyle='solid', color=colFav['UAM'], label='predUAM, original')\r\n elif 'UAM'==SMBsource :\r\n initUAM = Fcasts['UAMinitBGs'] # the initial array before cleanup\r\n predUAM = Fcasts['UAMpredBGs']\r\n axbg.plot(initUAM, fcastmills[:len(initUAM)], linestyle='None', marker='.', color=colFav['UAM'], fillstyle='none')\r\n axbg.plot(predUAM, fcastmills[:len(predUAM)], linestyle='None', marker='.', color=colFav['UAM'], label='predUAM, emulated')\r\n else:\r\n axbg.plot([0,0], [0,0], linestyle='none', color=colFav['UAM'], label='no UAM active') # inactive\r\n \r\n if 'IOB' in Fcasts: # assume same logic as in original\r\n origIOB = Fcasts['IOB'] # the initial array before cleanup\r\n initIOB = Fcasts['IOBinitBGs'] # the initial array before cleanup\r\n predIOB = Fcasts['IOBpredBGs']\r\n axbg.plot(origIOB, fcastmills[:len(origIOB)], linestyle='solid', color=colFav['IOB'], label='predIOB, original')\r\n axbg.plot(initIOB, fcastmills[:len(initIOB)], linestyle='None', marker='.', color=colFav['IOB'], fillstyle='none')\r\n axbg.plot(predIOB, fcastmills[:len(predIOB)], linestyle='None', marker='.', color=colFav['IOB'], label='predIOB, emulated')\r\n else:\r\n axbg.plot([0,0], [0,0], linestyle='none', color=colFav['IOB'], label='no IOB active') # inactive\r\n \r\n if 'ZT' in Fcasts: # assume same logic as in original\r\n origZT = Fcasts['ZT'] # from the orig loop\r\n initZT = Fcasts['ZTinitBGs'] # the initial array before cleanup\r\n predZT = Fcasts['ZTpredBGs']\r\n axbg.plot(origZT, fcastmills[:len(origZT)], linestyle='solid', color=colFav['ZT'], label='predZT, original')\r\n axbg.plot(initZT, fcastmills[:len(initZT)], linestyle='None', marker='.', color=colFav['ZT'], fillstyle='none')\r\n axbg.plot(predZT, fcastmills[:len(predZT)], linestyle='None', marker='.', Color=colFav['ZT'], label='predZT, emulated')\r\n else:\r\n axbg.plot([0,0], [0,0], linestyle='none', color=colFav['ZT'], label='no ZT active') # inactive\r\n \r\n axbg.legend(loc='lower right')\r\n \r\n if frameFlow : # anything related to flow chart\r\n axfl = fig.add_subplot(gs[0, flowOffset:])\r\n axfl.set_xticklabels(['','']) # dummy axis labels\r\n axfl.set_xticks([-99,99999]) # off scale to suppress ticks\r\n axfl.set_xlim(10, 200)\r\n axfl.set_yticklabels(['','']) # dummy axis labels\r\n axfl.set_yticks([-99999,99]) # off scale to suppress ticks\r\n axfl.set_ylim(-700, 0)\r\n axfl.set_xlabel('Flowchart and decision logic at time ' + loop_label[iFrame], weight='bold')\r\n \r\n thisTime = loop_mills[iFrame]\r\n Flows = FlowChart[thisTime]\r\n row = +20 # start row, i.e. where the arrow starts\r\n row_dist = 50\r\n col = 20 # start col, i.e. initial horizontal center\r\n col_dist = 25\r\n old_Thigh = 5 # short start arrow\r\n stripOffset = 0 # later offset into second strip\r\n for ele in Flows: \r\n row_old = row\r\n col_old = col\r\n title = ele['title']\r\n indent = ele['indent']\r\n dchar, drow = getBoxSize(title)\r\n if eval(indent) == 0 :\r\n row -= row_dist\r\n col_offset = 0\r\n arr_offset = 1 + old_Thigh*4\r\n if indent == '0' : col = 20 + stripOffset\r\n else:\r\n col += eval(indent)*col_dist\r\n col_offset = 1 + old_Tlen*0.3\r\n arr_offset = 0\r\n\r\n if row<-680: # later : 650? check for bottom of first strip\r\n row = 20 - row_dist\r\n stripOffset += 100 - 5 # half of frame width\r\n col += stripOffset\r\n\r\n if col0 and row>row_old: # switch to 2nd strip\r\n flowBackwrd = dict(arrowstyle='<|-', linestyle='dotted',\r\n connectionstyle='bar, angle=90, fraction='+str(-5/(col_old-col)))\r\n axfl.annotate(ele['title'], xy=(col_old+old_Tlen*0.3, row_old-arr_offset*0), xytext=(col, row),\r\n ha='center', va='center', bbox=bbox, arrowprops=flowBackwrd, fontsize=6)\r\n AdrPlot(axfl, ele, row, drow, col, dchar)\r\n\r\n else: # normal situation\r\n axfl.annotate(ele['title'], xy=(col_old+col_offset, row_old-arr_offset), xytext=(col, row),\r\n ha='center', va='center', bbox=bbox, arrowprops=flowForward, fontsize=6)\r\n AdrPlot(axfl, ele, row, drow, col, dchar)\r\n\r\n old_Tlen = dchar\r\n old_Thigh= drow\r\n\r\n pdf.savefig()\r\n if not featured('pred'):\r\n for i in range(iFrame+1, len(loop_mills)+2):\r\n zeile = xyf.readline() # table row i\r\n log_msg(zeile[:-1]) # w/o the \r\n if how_to_print != 'GUI': plt.show() # otherwise conflict with root.mainloop() in tkinter\r\n plt.close() # end of current page\r\n #pdf.close() # not needed due to \"with ...\" method triggered above\r\n if featured('pred'):\r\n zeile = xyf.readline() # summary row 1\r\n log_msg(zeile[:-1])\r\n zeile = xyf.readline() # summary row 2\r\n log_msg(zeile[:-1])\r\n xyf.close()\r\n\r\ndef parameters_known(myseek, arg2, variantFile, startLabel, stoppLabel):\r\n # start of top level analysis\r\n \r\n global fn\r\n global ce_file\r\n global varLabel\r\n global doit\r\n global fn_first\r\n\r\n global loop_mills\r\n global loop_label\r\n global bg\r\n global origTarLow\r\n global emulTarLow\r\n global origTarHig\r\n global emulTarHig\r\n global origAs_ratio\r\n global emulAs_ratio\r\n global origiob\r\n global origcob\r\n global activity\r\n global origInsReq\r\n global emulInsReq\r\n global origSMB\r\n global emulSMB\r\n global origMaxBolus\r\n global emulMaxBolus\r\n global origBasal\r\n global emulBasal\r\n global lastBasal\r\n global Pred \r\n global FlowChart \r\n global filecount\r\n global t_startLabel\r\n global t_stoppLabel\r\n global varFile\r\n \r\n global isZip # flag for input file type\r\n global newLoop # flag whether data collection for new loop started\r\n \r\n loop_mills = []\r\n loop_label = []\r\n bg = []\r\n origTarLow = []\r\n emulTarLow = []\r\n origTarHig = []\r\n emulTarHig = []\r\n \r\n origAs_ratio= []\r\n emulAs_ratio= []\r\n origiob = []\r\n origcob = []\r\n activity = []\r\n \r\n origInsReq = []\r\n emulInsReq = []\r\n origSMB = []\r\n emulSMB = []\r\n origMaxBolus= []\r\n emulMaxBolus= []\r\n origBasal = []\r\n emulBasal = []\r\n lastBasal = []\r\n \r\n Pred = {} # holds all loop predictions\r\n FlowChart = {} # holds all loop decisions for flow chart\r\n \r\n t_startLabel= startLabel\r\n t_stoppLabel= stoppLabel\r\n filecount = 0\r\n newLoop = False\r\n \r\n myfile = ''\r\n arg2 = arg2.replace('_', ' ') # get rid of the UNDERSCOREs\r\n doit = arg2.split('/')\r\n varFile = variantFile\r\n varLabel = os.path.basename(varFile) # do not overwrite the calling arg value\r\n if varLabel[len(varLabel)-4:] == '.dat' : # drop the tail coming from DOS type ahead\r\n varLabel = varLabel[:-4]\r\n \r\n logListe = glob.glob(myseek+myfile, recursive=False)\r\n filecount = 0\r\n for fn in logListe:\r\n ftype = fn[len(fn)-3:]\r\n if ftype=='zip' or ftype.find('.')>0: # valid logfiles should end with \"_.0\" thru \"_.99\" or \"zip\"\r\n isZip = ( ftype == 'zip')\r\n if filecount == 0 : # initalize file loop\r\n ce_file = fn + '.' + varLabel + '.txt'\r\n cel = open(ce_file, 'w')\r\n cel.write('AAPS scan from ' + varLabel + ' for SMB comparison created on ' + formatdate(localtime=True) + '\\n')\r\n cel.write('FILE='+fn + '\\n')\r\n cel.close()\r\n my_ce_file(ce_file) # exports name to determine_basal.py\r\n fn_first = fn\r\n log_msg ('Scanning logfile '+fn)\r\n cont = scanLogfile(fn)\r\n filecount += 1\r\n if cont == 'STOP': break # end of time window reached\r\n \r\n if filecount == 0 :\r\n log_msg ('no such logfile: \"'+myseek+'\"')\r\n return\r\n loopCount = len(loop_mills)\r\n if loopCount == 0 :\r\n log_msg ('no entries found in logfile: \"'+myseek+'\"')\r\n return #sys.exit()\r\n log.write('ENDE\\n')\r\n log.close()\r\n varlog.close()\r\n \r\n # --- print the comparisons -------------------------\r\n head= \" ----time formated as--- -Autosens- -----target----- insulin Req -maxBolus- ---SMB--- ---tmpBasal---\\n\" \\\r\n + \"id UTC UNIX bg cob iob act orig emul orig emul orig emul orig emul orig emul orig emul\"\r\n #print('\\n' + head)\r\n xyf.write(head + '\\n')\r\n \r\n origBasalint = 0.0\r\n emulBasalint = 0.0\r\n origSMBsum = 0.0\r\n emulSMBsum = 0.0\r\n \r\n for i in range(loopCount) :\r\n tabz= f'{i:>2} {loop_label[i]} {loop_mills[i]:>13} {bg[i]:>4} ' \\\r\n + f'{origcob[i]:>6} {round(origiob[i]/10,2):>5} {round(activity[i]/1000,3):>6} ' \\\r\n + f'{round(origAs_ratio[i]/10,2):>5} {round(emulAs_ratio[i]/10,2):>5}' \\\r\n + f'{origTarLow[i]:>6}-{origTarHig[i]:>3} {emulTarLow[i]:>4}-{emulTarHig[i]:>3} ' \\\r\n + f'{origInsReq[i]:>8} {emulInsReq[i]:>6} ' \\\r\n + f'{origMaxBolus[i]:>9} {emulMaxBolus[i]:>4} {origSMB[i]:>8} {emulSMB[i]:>4} ' \\\r\n + f'{origBasal[i]:>10} {emulBasal[i]:>7}' \r\n #print(tabz)\r\n origSMBsum += origSMB[i]\r\n emulSMBsum += emulSMB[i]\r\n if i==loopCount-1: # last time step\r\n fraction = 5 / 60 # next 5 min per hour\r\n else:\r\n fraction = (loop_mills[i+1] - loop_mills[i]) / 3600\r\n #print (str(fraction*60))\r\n origBasalint += origBasal[i]*fraction\r\n emulBasalint += emulBasal[i]*fraction \r\n xyf.write(tabz + '\\n')\r\n \r\n sepLine = ''\r\n for i in range(146):\r\n sepLine += '-'\r\n tabz = 'Totals:'+f'{round(origSMBsum,1):>115} {round(emulSMBsum,1):>4} {round(origBasalint,2):>10} {round(emulBasalint,2):>7}'\r\n #print(sepLine + '\\n' + tabz)\r\n xyf.write(sepLine + '\\n' + tabz + '\\n')\r\n xyf.close()\r\n \r\n XYplots(loopCount)\r\n \r\n\r\ndef set_tty(printframe, txtbox, channel): # for GIU\r\n global how_to_print\r\n how_to_print = channel\r\n global runframe\r\n runframe = printframe\r\n global lfd\r\n lfd = txtbox\r\n \r\ndef log_msg(msg): # for GUI\r\n if how_to_print == 'GUI':\r\n lfd['state'] = 'normal'\r\n lfd.insert('end', msg + '\\n')\r\n lfd['state'] = 'disabled'\r\n runframe.update() # update frame display\r\n else:\r\n print(msg)\r\n","sub_path":"vary_settings_core.py","file_name":"vary_settings_core.py","file_ext":"py","file_size_in_byte":73383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"603635327","text":"\"\"\"\nhttps://leetcode.com/explore/challenge/card/july-leetcoding-challenge/545/week-2-july-8th-july-14th/3390/\nGiven two numbers, hour and minutes. Return the smaller angle (in degrees) formed between the hour and the minute hand.\n\n\n\nExample 1:\n\n\n\nInput: hour = 12, minutes = 30\nOutput: 165\nExample 2:\n\n\n\nInput: hour = 3, minutes = 30\nOutput: 75\nExample 3:\n\n\n\nInput: hour = 3, minutes = 15\nOutput: 7.5\nExample 4:\n\nInput: hour = 4, minutes = 50\nOutput: 155\nExample 5:\n\nInput: hour = 12, minutes = 0\nOutput: 0\n\n\nConstraints:\n\n1 <= hour <= 12\n0 <= minutes <= 59\nAnswers within 10^-5 of the actual value will be accepted as correct.\n Hide Hint #1\nThe tricky part is determining how the minute hand affects the position of the hour hand.\n Hide Hint #2\nCalculate the angles separately then find the difference.\n\"\"\"\n\n\nclass Solution:\n def angleClock(self, hour: int, minutes: int) -> float:\n # Solution 1 - 36 ms\n \"\"\"\n degreeCoveredByOneHr = 30\n degreeCoveredByOneMin = 6\n\n # base position = 12:00\n # Angle sweeped by minute hand from base position\n angleMadeByMinuteHand = degreeCoveredByOneMin * minutes\n\n # Angle sweeped by hour hand from base position\n angleMadeByHrHand = (degreeCoveredByOneHr * hour) % 360\n extraAngleByHrHand = (minutes / 60) * degreeCoveredByOneHr\n\n # Take the difference of two angles\n angle = abs(angleMadeByMinuteHand - (angleMadeByHrHand + extraAngleByHrHand))\n\n # This is basically done so as to take the shorter angle out of two\n return min(abs(360 - angle), angle)\n \"\"\"\n\n # Solution 2 - 12 ms\n # divide minutes by 5\n # difference of numbers 6 apart (180)\n # difference of 3 apart (90)\n # therefore, difference of 1 apart is 30\n # 1 is 30, 2 is 60, 3 is 90, 4 is 120, 5 is 150, 6 is 180, 7 is 150 ..\n\n # calculate minute angle (minutes * 6)\n minuteAngle = float(minutes * 6)\n hourAngle = (float(hour % 12) * 30.0) + (minutes * 0.5)\n diffAngle = max(hourAngle, minuteAngle) - min(hourAngle, minuteAngle)\n if diffAngle <= 180.0:\n return max(hourAngle, minuteAngle) - min(hourAngle, minuteAngle)\n else:\n return 360 - diffAngle\n\n\n# Main Call\nsolution = Solution()\nhour = 12\nminutes = 30\nprint(solution.angleClock(hour, minutes))","sub_path":"src/integers/angleClock.py","file_name":"angleClock.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"629805262","text":"\r\n ##sports= 'soccer,basketball,football,tennis'\r\n###sports.insert(2,'rugby')\r\n##\r\n###print(sports)\r\n###badSports = sports.pop()\r\n###sports.remove('basketball')\r\n###print('I enjoy {0} but {1} is just not something i care for'.format(sports,badSports))\r\n####sports.split(',')\r\n####print(sports.split(','))\r\n##def nice_message():\r\n## return 'hello david, how are you doing today?'\r\n## print(\r\n##\r\n##blah = nice_message()\r\n##print(blah)\r\ndef master_yoda(new_sentence):\r\n # new_sentence= input('please insert saying:')\r\n st = new_sentence.split()\r\n rt = st[::-1]\r\n return ''.join(rt)\r\n\r\n#master_yoda = reverse('i am home')\r\ntext1 = master_yoda('how is your day')\r\n\r\nprint(text1)\r\n \r\n\r\n\r\n","sub_path":"night _school_methods_and_fuctions.py","file_name":"night _school_methods_and_fuctions.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"103997800","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@author: zhanghe\n@software: PyCharm\n@file: rabbit_queue.py\n@time: 2019-04-08 16:48\n\"\"\"\n\nimport pika\nfrom pika.exceptions import AMQPConnectionError, AMQPChannelError, ConnectionClosed\nimport json\nfrom retry import retry\n\n\nclass RabbitQueue(object):\n \"\"\"\n 队列\n \"\"\"\n def __init__(self, conn):\n self.conn = conn\n self.channel = self.conn.channel()\n\n def close_conn(self):\n \"\"\"\n 关闭连接\n :return:\n \"\"\"\n self.conn.close()\n\n def exchange_declare(self, exchange_name='amq.topic'):\n \"\"\"\n 交换机申明\n :param exchange_name:\n :return:\n \"\"\"\n self.channel.exchange_declare(\n exchange=exchange_name,\n exchange_type='topic',\n durable=True,\n )\n\n def queue_declare(self, queue_name='', **arguments):\n \"\"\"\n 队列申明\n :param queue_name:\n :param arguments:\n :return:\n \"\"\"\n self.channel.queue_declare(\n queue=queue_name,\n durable=True,\n arguments=arguments,\n )\n\n def queue_bind(self, exchange_name='amq.topic', queue_name='', binding_key='#'):\n \"\"\"\n 绑定队列\n :param exchange_name:\n :param queue_name:\n :param binding_key:\n :return:\n \"\"\"\n self.channel.queue_bind(\n exchange=exchange_name,\n queue=queue_name,\n routing_key=binding_key\n )\n\n def basic_qos(self):\n self.channel.basic_qos(prefetch_count=1)\n\n def basic_publish(self, message, exchange='amq.topic', routing_key='.'):\n \"\"\"\n 推送队列消息\n :param message:\n :param exchange:\n :param routing_key:\n :return:\n \"\"\"\n if isinstance(message, dict):\n message = json.dumps(message)\n self.channel.basic_publish(\n exchange=exchange,\n routing_key=routing_key,\n body=message,\n properties=pika.BasicProperties(delivery_mode=2)\n )\n print(\" [x] Sent %r\" % (message,))\n\n def ack_message(self, delivery_tag):\n \"\"\"\n Note that `channel` must be the same Pika channel instance via which\n the message being acknowledged was retrieved (AMQP protocol constraint).\n \"\"\"\n if self.channel.is_open:\n self.channel.basic_ack(delivery_tag)\n else:\n # Channel is already closed, so we can't acknowledge this message;\n # log and/or do something that makes sense for your app in this case.\n pass\n\n def basic_get(self, queue_name):\n \"\"\"\n 消费队列消息(非阻塞)\n :return:\n \"\"\"\n method_frame, header_frame, body = self.channel.basic_get(queue_name)\n if method_frame:\n print(\" [x] Get %r\" % (body,))\n print(method_frame, header_frame, body)\n self.ack_message(delivery_tag=method_frame.delivery_tag)\n else:\n print('No message returned')\n\n @retry(AMQPConnectionError, delay=5, jitter=(1, 3))\n def basic_consume(self, on_message_callback, queue_name):\n \"\"\"\n 消费队列消息(阻塞)\n \"\"\"\n self.channel.basic_consume(consumer_callback=on_message_callback, queue=queue_name)\n\n try:\n self.channel.start_consuming()\n except KeyboardInterrupt:\n self.channel.stop_consuming()\n # Don't recover connections closed by server\n except (ConnectionClosed, AMQPChannelError):\n pass\n self.close_conn()\n\n def example_basic_consume_with_callback(self):\n \"\"\"\n 示例: 消费队列消息(阻塞)\n :return:\n \"\"\"\n def callback(ch, method, properties, body):\n print(\" [x] Get %r\" % (body,))\n # raise Exception('test')\n ch.ack_message(delivery_tag=method.delivery_tag)\n\n self.basic_consume(callback)\n\n\n# class RabbitQueueDelay(object):\n# \"\"\"\n# 延时队列\n# q_d_client = RabbitQueueDelay('amq.direct', q_name, ttl=3600*24)\n# \"\"\"\n# def __init__(self, exchange, queue_name, exchange_type='direct', durable=True, **arguments):\n# self.exchange = exchange\n# self.queue_name = queue_name\n# self.delay_queue_name = '%s_delay' % queue_name\n# self.exchange_type = exchange_type\n# self.durable = durable\n# self.arguments = arguments\n# # print u'实例化附加参数:', arguments\n# self.conn = get_conn()\n#\n# self.channel = self.conn.channel()\n# self.channel.confirm_delivery()\n# self.channel.queue_declare(queue=queue_name, durable=durable)\n#\n# # We need to bind this channel to an exchange, that will be used to transfer\n# # messages from our delay queue.\n# self.channel.queue_bind(exchange=self.exchange,\n# queue=queue_name)\n#\n# # 延时队列定义\n# self.delay_channel = self.conn.channel()\n# self.delay_channel.confirm_delivery()\n#\n# # This is where we declare the delay, and routing for our delay channel.\n# self.delay_channel.queue_declare(queue=self.delay_queue_name, durable=durable, arguments={\n# 'x-message-ttl': arguments.get('ttl', 5)*1000, # Delay until the message is transferred in milliseconds.\n# 'x-dead-letter-exchange': self.exchange, # Exchange used to transfer the message from A to B.\n# 'x-dead-letter-routing-key': self.queue_name # Name of the queue we want the message transferred to.\n# })\n#\n# def get_conn(self):\n# \"\"\"\n# 获取连接\n# :return:\n# \"\"\"\n# if not _client_conn.get('conn'):\n# conn_mq = pika.BlockingConnection(\n# pika.ConnectionParameters(\n# host=RABBIT_MQ.get('host', '127.0.0.1'),\n# port=RABBIT_MQ.get('port', 5672),\n# virtual_host=RABBIT_MQ.get('virtual_host', '/'),\n# heartbeat_interval=RABBIT_MQ.get('heartbeat_interval', 0),\n# retry_delay=RABBIT_MQ.get('retry_delay', 3)\n# )\n# )\n# _client_conn['conn'] = conn_mq\n# return conn_mq\n# else:\n# return _client_conn['conn']\n#\n# def close_conn(self):\n# \"\"\"\n# 关闭连接\n# :return:\n# \"\"\"\n# if _client_conn.get('conn'):\n# self.conn.close()\n# _client_conn.pop('conn')\n#\n# def put(self, message):\n# \"\"\"\n# 推送队列消息\n# :param message:\n# :return:\n# \"\"\"\n# if isinstance(message, dict):\n# message = json.dumps(message)\n# self.delay_channel.basic_publish(exchange='',\n# routing_key=self.delay_queue_name,\n# body=message,\n# properties=pika.BasicProperties(\n# delivery_mode=2 if self.durable else 1, # make message persistent\n# ))\n# print \" [x] Sent %r\" % (message,)\n#\n# def get(self):\n# \"\"\"\n# 获取队列消息\n# :return:\n# \"\"\"\n# # data = self.channel.basic_get(self.queue_name)\n# # print data\n# method_frame, header_frame, body = self.channel.basic_get(self.queue_name)\n# if method_frame:\n# print \" [x] Get %r\" % (body,)\n# print method_frame, header_frame, body\n# self.channel.basic_ack(method_frame.delivery_tag)\n# else:\n# print('No message returned')\n#\n# def get_block(self):\n# \"\"\"\n# 获取队列消息(阻塞)\n# direct 模式下多进程消费,进程轮流获取单个消息\n# :return:\n# \"\"\"\n# def callback(ch, method, properties, body):\n# try:\n# print \" [x] Get %r\" % (body,)\n# # raise Exception('test')\n# ch.basic_ack(delivery_tag=method.delivery_tag)\n# except Exception as e:\n# print traceback.print_exc()\n# raise e\n#\n# self.consume(callback)\n#\n# def consume(self, callback):\n# \"\"\"\n# 消费\n# \"\"\"\n# # 处理队列\n# self.channel.basic_consume(consumer_callback=callback, queue=self.queue_name)\n# try:\n# self.channel.start_consuming()\n# except KeyboardInterrupt:\n# self.channel.stop_consuming()\n# self.close_conn()\n\n\nif __name__ == '__main__':\n from app_backend.clients.client_rabbitmq import rabbitmq_client\n rq = RabbitQueue(rabbitmq_client)\n rq.exchange_declare()\n rq.queue_declare()\n binding_keys = ['', '']\n for bind_key in binding_keys:\n rq.queue_bind(binding_key=bind_key)\n\n\n\"\"\"\n这种方式 如果队列中前面的消息延时时间大于后面的时间 那么后面的消息将会被堵塞 应为消息在被消费前才会去检查过期时间\n参考官方文档发现“Only when expired messages reach the head of a queue will they actually be discarded (or dead-lettered).”只有当过期的消息到了队列的顶端(队首),才会被真正的丢弃或者进入死信队列。\n\"\"\"\n","sub_path":"app_common/libs/rabbit_queue.py","file_name":"rabbit_queue.py","file_ext":"py","file_size_in_byte":9383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"454868514","text":"_author_ = \"ikambarov\"\n\nimport random\n\nrandomnumber = random.randrange(0, 10, 1)\n\nprint(\"Please enter number, try #1: \")\nnumber = int(input())\n\nfor i in range(2, 11):\n if number == randomnumber:\n print(\"You got it!\")\n found = 1\n break\n else:\n print(\"Please try again, try#{}: \".format(i))\n number = int(input())\n found = 0\n\nif found == 0:\n print(\"You tried {} times and was not able to guess the number: {}\".format(i-1, randomnumber))","sub_path":"randomnumbergenerator.py","file_name":"randomnumbergenerator.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"57498831","text":"'''Divides a observed spectrum by model spectrum of a spectrophotometric star.'''\n\nimport numpy as np \nimport matplotlib.pyplot as plt \nfrom astropy.io import fits as pyfits\nimport scipy\n\nobserved = '/Users/tomfoster/Desktop/dphil/IRAS23365/IRAS23365_counts.fits' #raw_input(\"Enter the file name of the observed spectrum:\") #Read in files\nmodel = '/Users/tomfoster/Desktop/dphil/IRAS23365/conversion_factor.dat' #raw_input(\"Enter the file name of the model spectrum\")\n\nhdulist1 = pyfits.open(observed) #Open files\n\nfactor = []\nwith open(model, 'r') as f:\n\tfor line in f:\n\t\tfactor.append(float(line))\n\ndata = hdulist1[0].data\n\nfor i in range(len(factor)):\n\tdata[i,:,:] = data[i,:,:]/factor[i]\n\nhdulist1[0].data = data\n\nhdulist1.writeto('/Users/tomfoster/Desktop/dphil/IRAS23365/IRAS23365_flux.fits')","sub_path":"flux_calibrate.py","file_name":"flux_calibrate.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"632090202","text":"from ast import literal_eval\nfrom collections import deque\nimport re\nfrom . import error, ast as _ast\n\nclass Parser:\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.source = ''\n self.pos = 0\n self.stack = deque()\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n self.reset()\n\n def feed(self, string):\n self.source += string\n\n def push_state(self):\n self.stack.append((self.source, self.pos))\n\n def pop_state(self):\n self.source, self.pos = self.stack.pop()\n\n def drop_state(self):\n self.stack.pop()\n\n @property\n def state(self):\n return (self.source, self.pos, deque(self.stack))\n\n @state.setter\n def state(self, state):\n self.source, self.pos, self.stack = state\n\n def require(self, condition, error_message):\n if not condition:\n raise error.SyntaxError(error_message, self.pos)\n\n def consume(self, count):\n self.source = self.source[count:]\n self.pos += count\n\nclass StatementParser(Parser):\n eol = re.compile(r'\\n')\n escape_eol = re.compile(r'(?\\'\",$])+')\n sqescape = re.compile(r\"(?,$])')\n\n true_false = re.compile(r'(True|False)(?![^\\s|&()\\[\\]{}<>\\'\",$])')\n none = re.compile(r'(None)(?![^\\s|&()\\[\\]{}<>\\'\",$])')\n\n identifier = re.compile(r'[a-zA-Z_][a-zA-Z0-9_-]*')\n socket_index = re.compile(r'-?\\d+')\n\n def feed(self, string):\n super().feed(string)\n return self.end_of_statement.search(self.source) == None\n\n def parse(self, source=None):\n if source != None:\n self.reset()\n self.source = source\n\n # Remove text after end of statement\n eos = self.end_of_statement.search(self.source)\n if eos:\n self.source = self.source[:eos.start(2)]\n\n # Save source\n original_source = self.source\n\n # Remove backslash from escaped eol\n self.source = self.escape_eol.sub(lambda m: (m.group(1) or '') + '\\n', self.source)\n\n # Save source\n stripped_source = self.source\n\n # source := whitespace? named_graph | pipe_expression comment?$\n\n ast = None\n\n self.whitespace()\n\n try:\n ast = self.named_graph()\n if not ast:\n ast = self.pipe_expression()\n ast = _ast.Graph(ast) if ast else ast\n\n self.comment()\n self.require(len(self.source) == 0, \"unexpected token\")\n\n except error.SyntaxError as e:\n newlines = [m.start() for m in self.eol.finditer(original_source)]\n\n line_number = stripped_source.count('\\n', 0, e.col)\n e.col = e.col - stripped_source.rfind('\\n', 0, e.col) - 1\n\n line_start = newlines[line_number-1]+1 if line_number else 0\n line_end = newlines[line_number] if line_number < len(newlines) else len(original_source)\n\n e.line = line_number\n e.source = original_source[line_start:line_end]\n\n raise\n\n return ast\n\n def literal(self, string):\n if not self.source.startswith(string):\n return False\n self.consume(len(string))\n return True\n\n def regex(self, pattern):\n m = pattern.match(self.source)\n if not m:\n return None\n s = m.group()\n self.consume(m.end())\n return s\n\n def whitespace(self):\n # whitespace := ws\n return self.regex(self.ws)\n\n def comment(self):\n if self.literal('#'):\n self.consume(len(self.source))\n return True\n\n return False\n\n def named_graph(self):\n # named_graph := identifier ( '.' identifier )? whitespace? ':' whitespace? pipe_expression\n\n self.push_state()\n\n group = ''\n name = self.regex(self.identifier)\n if not name:\n self.pop_state()\n return None\n\n if self.literal('.'):\n group = name\n name = self.regex(self.identifier)\n if not name:\n self.pop_state()\n return None\n\n self.whitespace()\n\n if not self.literal(':'):\n self.pop_state()\n return None\n\n self.drop_state()\n self.whitespace()\n\n expr = self.pipe_expression()\n self.require(expr, \"expression or node expected\")\n\n return _ast.NamedGraph(group, name, expr)\n\n def binary_expression(self, op, subexpr, ast_class):\n # binary_expression := subexpr ( op whitespace? subexpr )*\n\n side = subexpr()\n\n if side is None or not self.source.startswith(op):\n return side\n\n ast = ast_class()\n ast.append(side)\n\n while self.literal(op):\n self.whitespace()\n\n side = subexpr()\n self.require(side, \"expression or node expected\")\n\n ast.append(side)\n\n return ast\n\n def pipe_expression(self):\n # pipe_expression := pipe_and_mix_expression ( '|' whitespace? pipe_and_mix_expression )*\n return self.binary_expression('|', self.pipe_and_mix_expression, _ast.PipeExpression)\n\n def pipe_and_mix_expression(self):\n # pipe_and_mix_expression := mix_expression ( '|&' whitespace? mix_expression )*\n return self.binary_expression('|&', self.mix_expression, _ast.PipeAndMixExpression)\n\n def mix_expression(self):\n # mix_expression := pipe_and_join_expression ( '&' whitespace? pipe_and_join_expression )*\n return self.binary_expression('&', self.pipe_and_join_expression, _ast.MixExpression)\n\n def pipe_and_join_expression(self):\n # pipe_and_join_expression := join_expression ( '|&&' whitespace? join_expression )*\n return self.binary_expression('|&&', self.join_expression, _ast.PipeAndJoinExpression)\n\n def join_expression(self):\n # join_expression := expression_group ( '&' whitespace? expression_group )*\n return self.binary_expression('&&', self.expression_group, _ast.JoinExpression)\n\n def expression_group(self):\n # expression_group := ( '(' whitespace? pipe_expression ')' whitespace? ) | node\n\n if not self.literal('('):\n return self.node()\n\n self.whitespace()\n\n expr = self.pipe_expression()\n self.require(expr, \"expression or node expected\")\n\n self.require(self.literal(')'), \"')' expected\")\n self.whitespace()\n\n return expr\n\n def node(self):\n # node := socket_spec? identifier ( '.' identifier )? ( whitespace arg )* whitespace? socket_spec?\n\n input_spec = self.socket_spec()\n\n group = ''\n name = self.regex(self.identifier)\n if not name:\n return None\n\n if self.literal('.'):\n group = name\n name = self.regex(self.identifier)\n self.require(name, \"identifier expected\")\n\n ast = _ast.Node(group, name)\n\n while self.whitespace():\n arg = self.arg()\n if arg is ...:\n break\n if type(arg) is tuple:\n ast.kwargs[arg[0]] = arg[1]\n else:\n ast.args.append(arg)\n\n output_spec = self.socket_spec()\n\n if input_spec:\n ast.input_spec = input_spec\n if output_spec:\n ast.output_spec = output_spec\n\n return ast\n\n def socket_spec(self):\n # socket_spec := '<' whitespace? ( ( socket_index | identifier | '...' ) whitespace? ( ',' whitespace? ( socket_index | identifier | '...' ) whitespace? )* ','? whitespace? )? '>' whitespace?\n\n if not self.literal('<'):\n return None\n\n self.whitespace()\n\n ast = _ast.SocketSpec()\n\n socket = self.regex(self.socket_index)\n if socket:\n ast.append(int(socket))\n else:\n socket = self.regex(self.identifier)\n if socket:\n ast.append(socket)\n elif self.literal('...'):\n ast.append(-1)\n else:\n self.require(self.literal('>'), \"'>' or socket expected\")\n self.whitespace()\n\n ast.append(None) # Add None element to mark empty specifier\n\n return ast\n\n self.whitespace()\n\n while self.literal(','):\n self.whitespace()\n\n socket = self.regex(self.socket_index)\n if socket:\n ast.append(int(socket))\n else:\n socket = self.regex(self.identifier)\n if socket:\n ast.append(socket)\n elif self.literal('...'):\n ast.append(-1)\n else:\n break\n\n self.whitespace()\n\n self.require(self.literal('>'), \"'>' expected\")\n self.whitespace()\n\n return ast\n\n def arg(self):\n # arg := ( identifier '=' value ) | value\n\n self.push_state()\n\n key = self.regex(self.identifier)\n if key and self.literal('='):\n self.drop_state()\n\n value = self.value()\n self.require(value is not ..., \"argument value expected\")\n\n return (key, value)\n\n self.pop_state()\n\n return self.value()\n\n def value(self):\n # value := dict | graph | list | boolean | none | string\n\n value = self.dict()\n if value is not None:\n return value\n\n value = self.graph()\n if value:\n return _ast.Graph(value, True)\n\n value = self.list()\n if value:\n return value\n\n value = self.boolean()\n if value is not None:\n return value\n\n value = self.regex(self.none)\n if value:\n return None\n\n value = self.string()\n if value is not None:\n return value\n\n return ...\n\n def graph(self):\n # graph := '{' whitespace? pipe_expression '}'\n\n if not self.literal('{'):\n return None\n\n self.whitespace()\n\n ast = self.pipe_expression()\n self.require(ast, \"expression or node expected\")\n\n self.require(self.literal('}'), \"'}' expected\")\n\n return ast\n\n def dict(self):\n # dict := '{' whitespace? ( dict_item whitespace? ( ',' whitespace? dict_item whitespace? )* ','? whitespace? )? '}'\n\n self.push_state()\n\n if not self.literal('{'):\n self.pop_state()\n return None\n\n self.whitespace()\n\n try:\n item = self.dict_item()\n except:\n self.drop_state()\n raise\n\n if not item:\n if self.literal('}'): # Empty braces -> empty dict\n self.drop_state()\n return {}\n else:\n self.pop_state()\n return None # Fail gracefully - we could be trying to parse a graph\n\n self.drop_state()\n self.whitespace()\n\n items = [ item ]\n\n while self.literal(','):\n self.whitespace()\n\n item = self.dict_item()\n if not item:\n break\n items.insert(0, item)\n\n self.whitespace()\n\n self.require(self.literal('}'), \"'}' expected\")\n\n return dict(items)\n\n def dict_item(self):\n # dict_item := quoted_string whitespace? ':' whitespace? value\n\n key = self.quoted_string()\n if not key:\n return None\n\n self.whitespace()\n self.require(self.literal(':'), \"':' expected\")\n self.whitespace()\n\n value = self.value()\n self.require(value is not ..., \"item value expected\")\n\n return (key, value)\n\n def list(self):\n # list := '[' whitespace? ( value whitespace? ( ',' whitespace? value whitespace? )* ','? whitespace? )? ']'\n\n if not self.literal('['):\n return None\n\n self.whitespace()\n\n value = self.value()\n if value is ...:\n self.require(self.literal(']'), \"']' or value expected\")\n return []\n\n self.whitespace()\n\n values = [ value ]\n\n while self.literal(','):\n self.whitespace()\n\n value = self.value()\n if value is ...:\n break\n\n values.append(value)\n\n self.whitespace()\n\n self.require(self.literal(']'), \"']' expected\")\n\n return values\n\n def boolean(self):\n # boolean := 'true' | 'false'\n\n m = self.regex(self.true_false)\n if not m:\n return None\n elif m == 'True':\n return True\n else:\n return False\n\n def string(self):\n # string := quoted_string | free_string\n\n s = self.quoted_string()\n if s is not None:\n return s\n\n s = self.regex(self.frstr)\n if s is not None:\n return literal_eval('\"' + self.frescape.sub(r'\\1', s) + '\"')\n\n return None\n\n def quoted_string(self):\n # quoted_string := ( \"'\" sqstr \"'\" ) | ( '\"' dqstr '\"' )\n\n s = None\n\n if self.literal(\"'\"):\n s = self.regex(self.sqstr)\n\n if not self.literal(\"'\"):\n raise error.SyntaxError(\"unterminated string literal\", self.pos)\n\n s = self.sqescape.sub(\"'\", s.replace('\\n', ''))\n\n elif self.literal('\"'):\n s = self.regex(self.dqstr)\n\n if not self.literal('\"'):\n raise error.SyntaxError(\"unterminated string literal\", self.pos)\n\n s = literal_eval('\"' + s.replace('\\n', '') + '\"')\n\n return s\n\nclass DocumentParser(Parser):\n def __init__(self):\n self.parser = StatementParser()\n super().__init__()\n\n def parse(self, source=None):\n if source is not None:\n self.reset()\n self.source = source\n\n statements = []\n lines = self.source.splitlines()\n\n pos = 0\n\n for line in lines:\n pos += 1\n if not self.parser.feed(line+'\\n'):\n with self.parser:\n try:\n ast = self.parser.parse()\n if ast:\n statements.append(ast)\n except error.SyntaxError as e:\n e.line += self.pos\n raise\n self.pos = pos\n elif pos == len(lines):\n raise error.SyntaxError(\"unterminated statement\", len(line), pos-1, line)\n\n self.reset()\n\n return statements\n","sub_path":"nodish/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":14834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"532222081","text":"import stdio\nimport stdrandom\nimport sys\n\n\nclass MarkovModel(object):\n \"\"\"\n Represents a Markov model of order k from a given text string.\n \"\"\"\n\n def __init__(self, text, k):\n \"\"\"\n Create a Markov model of order k from given text (assumed\n to have length at least k).\n \"\"\"\n\n # Add first k chars of text to end to make it circular\n text = text + text[:k]\n\n # Create empty dictionary for holding frequencies\n st = dict()\n for i in range(len(text) - k):\n\n # Get next k chars and add them to dict\n s = text[i: i + k]\n if s not in st:\n st[s] = {}\n\n # Get the next char and add one to its frequency\n c = text[i + k]\n if c in st[s]:\n st[s][c] += 1\n else:\n st[s][c] = 1\n\n # Add properties to MarkovModel instance\n self.st = st\n self.k = k\n\n def order(self):\n \"\"\"\n Return order of Markov model.\n \"\"\"\n\n return self.k\n\n def kgram_freq(self, kgram):\n \"\"\"\n Return number of occurrences of kgram in text.\n \"\"\"\n\n if len(kgram) != self.order():\n raise ValueError(\"kgram length not equal to order\")\n elif kgram not in self.st:\n return 0\n else:\n return sum(v for v in self.st[kgram].values())\n\n def char_freq(self, kgram, c):\n \"\"\"\n Return number of times character c follows kgram.\n \"\"\"\n\n if len(kgram) != self.order():\n raise ValueError(\"kgram length not equal to order\")\n elif kgram not in self.st or c not in self.st[kgram]:\n return 0\n else:\n return self.st[kgram][c]\n\n def rand(self, kgram):\n \"\"\"\n Return a random character following kgram.\n \"\"\"\n\n if len(kgram) != self.order():\n raise ValueError(\"kgram length not equal to order\")\n elif kgram not in self.st:\n raise ValueError(\"kgram not in Markov model\")\n else:\n # 0 <= rand <= kgram freq\n rand_num = stdrandom.uniformInt(1, self.kgram_freq(kgram) + 1)\n\n # Decrement rand by the char_freq until it hits 0\n for c in self.st[kgram].keys():\n rand_num -= self.char_freq(kgram, c)\n if rand_num <= 0:\n return c\n\n def gen(self, kgram, T):\n \"\"\"\n Generate and return a string of length T by simulating a trajectory\n through the correspondng Markov chain. The first k (<= T) characters\n of the generated string is the argument kgram.\n \"\"\"\n\n s = kgram\n for i in range(T - self.order()):\n s += self.rand(s[len(s) - self.order():])\n\n return s\n\n def replace_unknown(self, corrupted):\n \"\"\"\n Replace unknown characters (~) in corrupted with most probable\n characters, and return that string.\n \"\"\"\n\n original = ''\n for i in range(len(corrupted)):\n if corrupted[i] == '~':\n\n # Used to keep track of the best possibility\n best_probability = 0\n best_char = None\n\n # Iterate over all possibilities\n kgram = corrupted[i - self.order():i]\n for c in self.st[kgram].keys():\n\n # Construct a possibility to test a character\n test = corrupted[:i] + c + corrupted[i + 1:]\n probability = 1.0\n\n # Perform various tests to see the probability\n for j in range(self.order() + 1):\n test_kgram = test[i + j - self.order():i + j]\n if self.kgram_freq(test_kgram) > 0:\n probability *= (\n self.char_freq(test_kgram, test[i + j])\n / self.kgram_freq(test_kgram)\n )\n else:\n probability = 0\n\n # Compare the probability of this char to the best\n if best_probability <= probability:\n best_probability = probability\n best_char = c\n\n # Add the best match to the string\n original += best_char\n\n else:\n original += corrupted[i]\n\n return original\n\n\ndef _main():\n \"\"\"\n Test client [DO NOT EDIT].\n \"\"\"\n\n text, k = sys.argv[1], int(sys.argv[2])\n model = MarkovModel(text, k)\n a = []\n while not stdio.isEmpty():\n kgram = stdio.readString()\n char = stdio.readString()\n a.append((kgram.replace(\"-\", \" \"), char.replace(\"-\", \" \")))\n for kgram, char in a:\n if char == ' ':\n stdio.writef('freq(%s) = %s\\n', kgram, model.kgram_freq(kgram))\n else:\n stdio.writef('freq(%s, %s) = %s\\n', kgram, char,\n model.char_freq(kgram, char))\n\n\nif __name__ == '__main__':\n _main()\n","sub_path":"markov_model.py","file_name":"markov_model.py","file_ext":"py","file_size_in_byte":5085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"244587909","text":"# Project Euler: Problem 23\n# Non-abundant sums\n# 2016-03-11 23:22:50\nimport time\nstartTime = time.clock()\n########################\nimport math\ndef computeProperDivisorSum(n):\n\t\"\"\"\n\tcompute the sum of proper divisor\n\t\"\"\"\n\tsqrtN = int(math.sqrt(n))\n\tsumN = 0\n\tfor x in range(2, sqrtN + 1):\n\t\tif n % x == 0:\n\t\t\tsumN += x + n // x\n\tif n != sqrtN * sqrtN:\n\t\treturn sumN + 1\n\telse:\n\t\treturn sumN + 1 - sqrtN\n\nabundantList = []\nfor x in range(12, 28123):\n\tif computeProperDivisorSum(x) > x:\n\t\tabundantList.append(x)\n\t# compute all abundant numbers\n\nsumList = {}\nfor x in range(1, 28123):\n\tsumList[x] = ''\n\t# generate a dict\n\nfor x in abundantList:\n\tfor y in abundantList:\n\t\tif (x + y) in sumList:\n\t\t\tsumList.pop(x + y)\n\t# delete Non-abundant sums\n\nprint(sum([x for x in sumList]))\n######################\nendTime = time.clock()\nprint(\"time spent: %f s\" % (endTime - startTime))","sub_path":"023.py","file_name":"023.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"176850575","text":"#coding: utf-8 \n##############################################################################\n#\n# NCTR, Nile Center for Technology Research\n# Copyright (C) 2011-2012 NCTR ().\n#\n##############################################################################\n\nimport time\nfrom report import report_sxw\nfrom datetime import timedelta,date\n\n#----------------------------------------\n# Class building insurance report\n#----------------------------------------\nclass building_insurance_report(report_sxw.rml_parse):\n def __init__(self, cr, uid, name, context):\n super(building_insurance_report, self).__init__(cr, uid, name, context)\n self.localcontext.update({\n 'time': time,\n 'line1':self._getdata1,\n })\n \n def _getdata1(self,data):\n date_from= data['form']['date_from']\n date_to= data['form']['date_to']\n building_id= data['form']['building_id']\n state= data['form']['state']\n insurance_obj = self.pool.get('building.insurance')\n insurance_line_obj = self.pool.get('building.insurance.line')\n domain = [('date','>=', date_from),('date','<=', date_to)]\n if building_id:\n insurance_line_ids = insurance_line_obj.search(self.cr, self.uid, [('building_id','=',building_id[0])])\n insurance_ids = insurance_line_ids and [line.insurance_id.id for line in insurance_line_obj.browse(self.cr, self.uid,insurance_line_ids)] or []\n domain.append(('id','in',tuple(insurance_ids)))\n if state :\n if state =='completed':\n domain.append(('state','=','done'))\n else: \n domain.append(('state','!=','done'))\n \n insurance_ids = insurance_obj.search(self.cr, self.uid, domain, order=\"id\")\n return insurance_obj.browse(self.cr,self.uid,insurance_ids)\n \nreport_sxw.report_sxw('report.building_insurance.report', 'building.insurance', 'addons/building_management/report/building_insurance_report.rml' ,parser=building_insurance_report,header=False)\n","sub_path":"v_7/NISS/shamil_v3/building_management/report/building_insurance_report.py","file_name":"building_insurance_report.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"239018997","text":"import complex\nimport vectors_matrices as vm\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Función auxiliar\ndef action(m1, v1):\n if len(m1[0]) == len(v1):\n m = [[0 for i in range(len(v1[0]))] for j in range(len(m1))]\n for row in range(len(m1)):\n for column in range(len(v1[0])):\n for aux in range(len(m1[0])):\n m[row][column] = round(m[row][column] + (m1[row][aux] * v1[aux][column]), 3)\n return m\n\n\n# Punto 1\ndef clicks_boolean(matrix, vector, t):\n \"\"\"\n Function that calculates the marbles experiment\n :param matrix:Array of n*m items, each item is boolean\n :param vector:Array of m items, each item is a real number\n :param t:Integer\n :return Array:\n \"\"\"\n for i in range(len(matrix)):\n for j in range(len(matrix)):\n if matrix[i][j]:\n matrix[i][j] = 1\n else:\n matrix[i][j] = 0\n ans = vector\n for i in range(t):\n ans = action(matrix, ans)\n return ans\n\n\n# Punto 2\ndef clicks_prob(matrix, vector, t):\n \"\"\"\n Function that calculates the probabilities of a probabilistic system in t clicks\n :param matrix:Array of n*m items, each item is a real number\n :param vector:Array of m items, each item is a real number\n :param t:Integer\n :return List:\n \"\"\"\n ans = vector\n for i in range(t):\n ans = action(matrix, ans)\n return ans\n\n\n# Punto 3\ndef clicks_cuant(matrix, vector, t):\n \"\"\"\n Function that calculates t clicks in a quantum system\n :param matrix: Array of n*m items, each item is a complex number\n :param vector: Array of m items, each item is a complex number\n :param t: Integer\n :return Array:\n \"\"\"\n ans = vector\n for i in range(t):\n ans = vm.action(matrix, ans)\n for i in range(len(ans)):\n ans[i][0] = round(complex.mod(ans[i][0]) ** 2, 3)\n return ans\n\n\n#Punto 4\ndef plot(probs):\n \"\"\"\n Function that plots the probabilities of a status vector\n :param probs: List\n \"\"\"\n estados = [x for x in range(len(probs))]\n fig, ax = plt.subplots()\n ax.set_ylabel('Probabilidades')\n ax.set_xlabel('Estados')\n ax.set_title('Sistema Cuantico')\n plt.bar(estados, probs)\n plt.savefig('probabilities.png')\n plt.show()\n","sub_path":"Classic to Quantum/classToQuan.py","file_name":"classToQuan.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"344728175","text":"import os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"7\"\nfrom keras.optimizers import Adam, SGD\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler, TerminateOnNaN, CSVLogger\nfrom keras import backend as K\nfrom keras.models import load_model\nfrom math import ceil\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport h5py\n\nfrom models.keras_ssd300 import ssd_300\nfrom keras_loss_function.keras_ssd_loss import SSDLoss\nfrom keras_layers.keras_layer_AnchorBoxes import AnchorBoxes\nfrom keras_layers.keras_layer_DecodeDetections import DecodeDetections\nfrom keras_layers.keras_layer_DecodeDetectionsFast import DecodeDetectionsFast\nfrom keras_layers.keras_layer_L2Normalization import L2Normalization\nfrom keras.engine import topology\nfrom keras.engine import saving\n\nfrom ssd_encoder_decoder.ssd_input_encoder import SSDInputEncoder\nfrom ssd_encoder_decoder.ssd_output_decoder import decode_detections, decode_detections_fast\n\nfrom data_generator.object_detection_2d_data_generator import DataGenerator\nfrom data_generator.object_detection_2d_geometric_ops import Resize\nfrom data_generator.object_detection_2d_photometric_ops import ConvertTo3Channels\nfrom data_generator.data_augmentation_chain_original_ssd import SSDDataAugmentation\nfrom data_generator.object_detection_2d_misc_utils import apply_inverse_transforms\n\n\n\ndef lr_schedule(epoch):\n if epoch < 30:\n return 0.0001\n else:\n return 0.00005\n\n\n\nimg_height = 300 # Height of the model input images\nimg_width = 300 # Width of the model input images\nimg_channels = 3 # Number of color channels of the model input images\nmean_color = [123, 117,\n 104] # The per-channel mean of the images in the dataset. Do not change this value if you're using any of the pre-trained weights.\nswap_channels = [2, 1,\n 0] # The color channel order in the original SSD is BGR, so we'll have the model reverse the color channel order of the input images.\nn_classes = 1 # Number of positive classes, e.g. 20 for Pascal VOC, 80 for MS COCO\nscales_pascal = [0.1, 0.2, 0.37, 0.54, 0.71, 0.88,\n 1.05] # The anchor box scaling factors used in the original SSD300 for the Pascal VOC datasets\nscales_coco = [0.07, 0.15, 0.33, 0.51, 0.69, 0.87,\n 1.05] # The anchor box scaling factors used in the original SSD300 for the MS COCO datasets\nscales = scales_pascal\naspect_ratios = [[1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5, 3.0, 1.0 / 3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0 / 3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0 / 3.0],\n [1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5]] # The anchor box aspect ratios used in the original SSD300; the order matters\ntwo_boxes_for_ar1 = True\nsteps = [8, 16, 32, 64, 100, 300] # The space between two adjacent anchor box center points for each predictor layer.\noffsets = [0.5, 0.5, 0.5, 0.5, 0.5,\n 0.5] # The offsets of the first anchor box center points from the top and left borders of the image as a fraction of the step size for each predictor layer.\nclip_boxes = False # Whether or not to clip the anchor boxes to lie entirely within the image boundaries\nvariances = [0.1, 0.1, 0.2,\n 0.2] # The variances by which the encoded target coordinates are divided as in the original implementation\nnormalize_coords = True\n\n# 1: Build the Keras model.\n\nK.clear_session() # Clear previous models from memory.\n\nmodel = ssd_300(image_size=(img_height, img_width, img_channels),\n n_classes=n_classes,\n mode='training',\n l2_regularization=0.0005,\n scales=scales,\n aspect_ratios_per_layer=aspect_ratios,\n two_boxes_for_ar1=two_boxes_for_ar1,\n steps=steps,\n offsets=offsets,\n clip_boxes=clip_boxes,\n variances=variances,\n normalize_coords=normalize_coords,\n subtract_mean=mean_color,\n swap_channels=swap_channels)\n\nweights_path = 'VGG_VOC0712_SSD_300x300_ft_iter_120000.h5'\n\n\nclassifier_names = ['conv4_3_norm_mbox_conf',\n 'fc7_mbox_conf',\n 'conv6_2_mbox_conf',\n 'conv7_2_mbox_conf',\n 'conv8_2_mbox_conf',\n 'conv9_2_mbox_conf']\n\n\nf = h5py.File(weights_path, mode='r')\nif 'layer_names' not in f.attrs and 'model_weights' in f:\n f = f['model_weights']\n\nlayers = model.inner_model.layers if hasattr(model, \"inner_model\") \\\n else model.layers\n\n# Exclude some layers\n\nlayers = filter(lambda l: l.name not in classifier_names, layers)\n\n\nsaving.load_weights_from_hdf5_group_by_name(f, layers)\n\nif hasattr(f, 'close'):\n f.close()\n\n\nsgd = SGD(lr=0.001, momentum=0.9, decay=0.0, nesterov=False)\nadam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\nssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0)\n\nmodel.compile(optimizer=adam, loss=ssd_loss.compute_loss)\n\ntrain_dataset = DataGenerator(load_images_into_memory=False, hdf5_dataset_path=None)\nval_dataset = DataGenerator(load_images_into_memory=False, hdf5_dataset_path=None)\n\n\nclasses = ['background',\n 'shit']\n\ntrain_dataset.parse_labelme(\n annotations_dirs=['/home/xiongxin/workspace/about_pig/img/2021-01-28'],\n classes=classes,\n include_classes='all',\n exclude_truncated=False,\n exclude_difficult=False,\n ret=False)\n\nval_dataset.parse_labelme(\n annotations_dirs=['/home/xiongxin/workspace/about_pig/img/25-26-27'],\n classes=classes,\n include_classes='all',\n exclude_truncated=False,\n exclude_difficult=True,\n ret=False)\n\ntrain_dataset.create_hdf5_dataset(file_path='trainval.h5',\n resize=False,\n variable_image_size=True,\n verbose=True)\n\nval_dataset.create_hdf5_dataset(file_path='test.h5',\n resize=False,\n variable_image_size=True,\n verbose=True)\n\nbatch_size = 2 # Change the batch size if you like, or if you run into GPU memory issues.\n\n# 4: Set the image transformations for pre-processing and data augmentation options.\n\n# For the training generator:\nssd_data_augmentation = SSDDataAugmentation(img_height=img_height,\n img_width=img_width,\n background=mean_color)\n\n# For the validation generator:\nconvert_to_3_channels = ConvertTo3Channels()\nresize = Resize(height=img_height, width=img_width)\n\n# 5: Instantiate an encoder that can encode ground truth labels into the format needed by the SSD loss function.\n\n# The encoder constructor needs the spatial dimensions of the model's predictor layers to create the anchor boxes.\npredictor_sizes = [model.get_layer('conv4_3_norm_mbox_conf').output_shape[1:3],\n model.get_layer('fc7_mbox_conf').output_shape[1:3],\n model.get_layer('conv6_2_mbox_conf').output_shape[1:3],\n model.get_layer('conv7_2_mbox_conf').output_shape[1:3],\n model.get_layer('conv8_2_mbox_conf').output_shape[1:3],\n model.get_layer('conv9_2_mbox_conf').output_shape[1:3]]\n\nssd_input_encoder = SSDInputEncoder(img_height=img_height,\n img_width=img_width,\n n_classes=n_classes,\n predictor_sizes=predictor_sizes,\n scales=scales,\n aspect_ratios_per_layer=aspect_ratios,\n two_boxes_for_ar1=two_boxes_for_ar1,\n steps=steps,\n offsets=offsets,\n clip_boxes=clip_boxes,\n variances=variances,\n matching_type='multi',\n pos_iou_threshold=0.5,\n neg_iou_limit=0.5,\n normalize_coords=normalize_coords)\n\n# 6: Create the generator handles that will be passed to Keras' `fit_generator()` function.\n\ntrain_generator = train_dataset.generate(batch_size=batch_size,\n shuffle=True,\n transformations=[ssd_data_augmentation],\n label_encoder=ssd_input_encoder,\n returns={'processed_images',\n 'encoded_labels'},\n keep_images_without_gt=False)\n\nval_generator = val_dataset.generate(batch_size=batch_size,\n shuffle=False,\n transformations=[convert_to_3_channels,\n resize],\n label_encoder=ssd_input_encoder,\n returns={'processed_images',\n 'encoded_labels'},\n keep_images_without_gt=False)\n\n# Get the number of samples in the training and validations datasets.\ntrain_dataset_size = train_dataset.get_dataset_size()\nval_dataset_size = val_dataset.get_dataset_size()\n\nmodel_checkpoint = ModelCheckpoint(filepath='train_model/ssd300_pig_epoch-{epoch:02d}_loss-{loss:.4f}_val_loss-{val_loss:.4f}.h5',\n monitor='val_loss',\n verbose=1,\n save_best_only=True,\n save_weights_only=True,\n mode='auto',\n period=1)\n# model_checkpoint.best =\n\ncsv_logger = CSVLogger(filename='ssd300_pig_training_log.csv',\n separator=',',\n append=True)\n\nlearning_rate_scheduler = LearningRateScheduler(schedule=lr_schedule,\n )\n\nterminate_on_nan = TerminateOnNaN()\n\ncallbacks = [model_checkpoint,\n csv_logger,\n learning_rate_scheduler,\n terminate_on_nan]\n\ninitial_epoch = 0\nfinal_epoch = 120\nsteps_per_epoch = 50\n\nhistory = model.fit_generator(generator=train_generator,\n steps_per_epoch=steps_per_epoch,\n epochs=final_epoch,\n callbacks=callbacks,\n validation_data=val_generator,\n validation_steps=ceil(val_dataset_size / batch_size),\n initial_epoch=initial_epoch)\n","sub_path":"ssd300_training.py","file_name":"ssd300_training.py","file_ext":"py","file_size_in_byte":10836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"449714232","text":"\"\"\"Support for displaying persistent notifications.\"\"\"\nfrom __future__ import annotations\n\nfrom collections import OrderedDict\nfrom collections.abc import Mapping, MutableMapping\nimport logging\nfrom typing import Any\n\nimport voluptuous as vol\n\nfrom homeassistant.components import websocket_api\nfrom homeassistant.const import ATTR_FRIENDLY_NAME\nfrom homeassistant.core import HomeAssistant, callback\nfrom homeassistant.exceptions import TemplateError\nfrom homeassistant.helpers import config_validation as cv\nfrom homeassistant.helpers.entity import async_generate_entity_id\nfrom homeassistant.helpers.template import Template\nfrom homeassistant.loader import bind_hass\nfrom homeassistant.util import slugify\nimport homeassistant.util.dt as dt_util\n\n# mypy: allow-untyped-calls, allow-untyped-defs\n\nATTR_CREATED_AT = \"created_at\"\nATTR_MESSAGE = \"message\"\nATTR_NOTIFICATION_ID = \"notification_id\"\nATTR_TITLE = \"title\"\nATTR_STATUS = \"status\"\n\nDOMAIN = \"persistent_notification\"\n\nENTITY_ID_FORMAT = DOMAIN + \".{}\"\n\nEVENT_PERSISTENT_NOTIFICATIONS_UPDATED = \"persistent_notifications_updated\"\n\nSERVICE_CREATE = \"create\"\nSERVICE_DISMISS = \"dismiss\"\nSERVICE_MARK_READ = \"mark_read\"\n\nSCHEMA_SERVICE_CREATE = vol.Schema(\n {\n vol.Required(ATTR_MESSAGE): vol.Any(cv.dynamic_template, cv.string),\n vol.Optional(ATTR_TITLE): vol.Any(cv.dynamic_template, cv.string),\n vol.Optional(ATTR_NOTIFICATION_ID): cv.string,\n }\n)\n\nSCHEMA_SERVICE_DISMISS = vol.Schema({vol.Required(ATTR_NOTIFICATION_ID): cv.string})\n\nSCHEMA_SERVICE_MARK_READ = vol.Schema({vol.Required(ATTR_NOTIFICATION_ID): cv.string})\n\nDEFAULT_OBJECT_ID = \"notification\"\n_LOGGER = logging.getLogger(__name__)\n\nSTATE = \"notifying\"\nSTATUS_UNREAD = \"unread\"\nSTATUS_READ = \"read\"\n\n\n@bind_hass\ndef create(hass, message, title=None, notification_id=None):\n \"\"\"Generate a notification.\"\"\"\n hass.add_job(async_create, hass, message, title, notification_id)\n\n\n@bind_hass\ndef dismiss(hass, notification_id):\n \"\"\"Remove a notification.\"\"\"\n hass.add_job(async_dismiss, hass, notification_id)\n\n\n@callback\n@bind_hass\ndef async_create(\n hass: HomeAssistant,\n message: str,\n title: str | None = None,\n notification_id: str | None = None,\n) -> None:\n \"\"\"Generate a notification.\"\"\"\n data = {\n key: value\n for key, value in [\n (ATTR_TITLE, title),\n (ATTR_MESSAGE, message),\n (ATTR_NOTIFICATION_ID, notification_id),\n ]\n if value is not None\n }\n\n hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_CREATE, data))\n\n\n@callback\n@bind_hass\ndef async_dismiss(hass: HomeAssistant, notification_id: str) -> None:\n \"\"\"Remove a notification.\"\"\"\n data = {ATTR_NOTIFICATION_ID: notification_id}\n\n hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_DISMISS, data))\n\n\nasync def async_setup(hass: HomeAssistant, config: dict) -> bool:\n \"\"\"Set up the persistent notification component.\"\"\"\n persistent_notifications: MutableMapping[str, MutableMapping] = OrderedDict()\n hass.data[DOMAIN] = {\"notifications\": persistent_notifications}\n\n @callback\n def create_service(call):\n \"\"\"Handle a create notification service call.\"\"\"\n title = call.data.get(ATTR_TITLE)\n message = call.data.get(ATTR_MESSAGE)\n notification_id = call.data.get(ATTR_NOTIFICATION_ID)\n\n if notification_id is not None:\n entity_id = ENTITY_ID_FORMAT.format(slugify(notification_id))\n else:\n entity_id = async_generate_entity_id(\n ENTITY_ID_FORMAT, DEFAULT_OBJECT_ID, hass=hass\n )\n notification_id = entity_id.split(\".\")[1]\n\n attr = {}\n if title is not None:\n if isinstance(title, Template):\n try:\n title.hass = hass\n title = title.async_render(parse_result=False)\n except TemplateError as ex:\n _LOGGER.error(\"Error rendering title %s: %s\", title, ex)\n title = title.template\n\n attr[ATTR_TITLE] = title\n attr[ATTR_FRIENDLY_NAME] = title\n\n if isinstance(message, Template):\n try:\n message.hass = hass\n message = message.async_render(parse_result=False)\n except TemplateError as ex:\n _LOGGER.error(\"Error rendering message %s: %s\", message, ex)\n message = message.template\n\n attr[ATTR_MESSAGE] = message\n\n hass.states.async_set(entity_id, STATE, attr)\n\n # Store notification and fire event\n # This will eventually replace state machine storage\n persistent_notifications[entity_id] = {\n ATTR_MESSAGE: message,\n ATTR_NOTIFICATION_ID: notification_id,\n ATTR_STATUS: STATUS_UNREAD,\n ATTR_TITLE: title,\n ATTR_CREATED_AT: dt_util.utcnow(),\n }\n\n hass.bus.async_fire(EVENT_PERSISTENT_NOTIFICATIONS_UPDATED)\n\n @callback\n def dismiss_service(call):\n \"\"\"Handle the dismiss notification service call.\"\"\"\n notification_id = call.data.get(ATTR_NOTIFICATION_ID)\n entity_id = ENTITY_ID_FORMAT.format(slugify(notification_id))\n\n if entity_id not in persistent_notifications:\n return\n\n hass.states.async_remove(entity_id, call.context)\n\n del persistent_notifications[entity_id]\n hass.bus.async_fire(EVENT_PERSISTENT_NOTIFICATIONS_UPDATED)\n\n @callback\n def mark_read_service(call):\n \"\"\"Handle the mark_read notification service call.\"\"\"\n notification_id = call.data.get(ATTR_NOTIFICATION_ID)\n entity_id = ENTITY_ID_FORMAT.format(slugify(notification_id))\n\n if entity_id not in persistent_notifications:\n _LOGGER.error(\n \"Marking persistent_notification read failed: \"\n \"Notification ID %s not found\",\n notification_id,\n )\n return\n\n persistent_notifications[entity_id][ATTR_STATUS] = STATUS_READ\n hass.bus.async_fire(EVENT_PERSISTENT_NOTIFICATIONS_UPDATED)\n\n hass.services.async_register(\n DOMAIN, SERVICE_CREATE, create_service, SCHEMA_SERVICE_CREATE\n )\n\n hass.services.async_register(\n DOMAIN, SERVICE_DISMISS, dismiss_service, SCHEMA_SERVICE_DISMISS\n )\n\n hass.services.async_register(\n DOMAIN, SERVICE_MARK_READ, mark_read_service, SCHEMA_SERVICE_MARK_READ\n )\n\n hass.components.websocket_api.async_register_command(websocket_get_notifications)\n\n return True\n\n\n@callback\n@websocket_api.websocket_command({vol.Required(\"type\"): \"persistent_notification/get\"})\ndef websocket_get_notifications(\n hass: HomeAssistant,\n connection: websocket_api.ActiveConnection,\n msg: Mapping[str, Any],\n) -> None:\n \"\"\"Return a list of persistent_notifications.\"\"\"\n connection.send_message(\n websocket_api.result_message(\n msg[\"id\"],\n [\n {\n key: data[key]\n for key in (\n ATTR_NOTIFICATION_ID,\n ATTR_MESSAGE,\n ATTR_STATUS,\n ATTR_TITLE,\n ATTR_CREATED_AT,\n )\n }\n for data in hass.data[DOMAIN][\"notifications\"].values()\n ],\n )\n )\n","sub_path":"homeassistant/components/persistent_notification/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"269978908","text":"# import sys\n# sys.path.append(r\"D:/WorkSpace/IDEA_Python_Space/intelligent/com/studies/primary/tutorials/image/cifar10\")\n# import com.studies.primary.tutorials.image.cifar10.cifar10_input as cifar10_input\nimport com.studies.primary.cifar10_input as cifar10_input\nimport tensorflow as tf\nimport pylab\n\nbatch_size = 128\ndata_dir = 'D:/WorkSpace/data/Tensorflow_cifar10_data/cifar-10-batches-bin/'\nimages_test, labels_test = cifar10_input.inputs(eval_data=True,data_dir=data_dir,batch_size=batch_size)\n\nsess = tf.InteractiveSession()\ntf.global_variables_initializer().run()\ntf.train.start_queue_runners()\nimage_batch, label_batch = sess.run([images_test, labels_test])\nprint(\"__\\n\",image_batch[0])\nprint(\"__\\n\",label_batch[0])\npylab.imshow(image_batch[0])\npylab.show()\n","sub_path":"com/studies/primary/demo40.py","file_name":"demo40.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"477836679","text":"from __future__ import annotations\n\nimport ast\nfrom typing import TYPE_CHECKING, Any, List, Optional\n\nfrom ....utils.logging import LoggingDescriptor\nfrom ...common.language import language_id\nfrom ...common.lsp_types import Diagnostic, DiagnosticSeverity, Position, Range\nfrom ...common.parts.diagnostics import DiagnosticsResult\nfrom ...common.text_document import TextDocument\nfrom ..utils.ast import Token, range_from_token\n\nif TYPE_CHECKING:\n from ..protocol import RobotLanguageServerProtocol\n\nfrom .protocol_part import RobotLanguageServerProtocolPart\n\n\nclass RobotDiagnosticsProtocolPart(RobotLanguageServerProtocolPart):\n _logger = LoggingDescriptor()\n\n def __init__(self, parent: RobotLanguageServerProtocol) -> None:\n super().__init__(parent)\n\n self.source_name = \"robotcode.diagnostics\"\n\n parent.diagnostics.collect.add(self.collect_token_errors)\n # parent.diagnostics.collect.add(self.collect_model_errors)\n parent.diagnostics.collect.add(self.collect_walk_model_errors)\n\n parent.diagnostics.collect.add(self.collect_namespace_diagnostics)\n\n parent.documents.did_open.add(self.namespace_invalidated)\n parent.documents_cache.namespace_invalidated.add(self.namespace_invalidated)\n\n async def namespace_invalidated(self, sender: Any, document: TextDocument) -> None:\n await self.parent.diagnostics.start_publish_diagnostics_task(document)\n\n def _create_error_from_node(self, node: ast.AST, msg: str, source: Optional[str] = None) -> Diagnostic:\n return Diagnostic(\n range=Range(\n start=Position(line=node.lineno - 1, character=node.col_offset),\n end=Position(line=(node.end_lineno or 1) - 1, character=node.end_col_offset or 0),\n ),\n message=msg,\n severity=DiagnosticSeverity.ERROR,\n source=source if source is not None else self.source_name,\n code=\"ModelError\",\n )\n\n def _create_error_from_token(self, token: Token, source: Optional[str] = None) -> Diagnostic:\n return Diagnostic(\n range=range_from_token(token),\n message=token.error if token.error is not None else \"Unknown Error.\",\n severity=DiagnosticSeverity.ERROR,\n source=source if source is not None else self.source_name,\n code=\"TokenError\",\n )\n\n @language_id(\"robotframework\")\n @_logger.call\n async def collect_token_errors(self, sender: Any, document: TextDocument) -> DiagnosticsResult:\n from robot.errors import VariableError\n from robot.parsing.lexer.tokens import Token\n\n result: List[Diagnostic] = []\n try:\n for token in await self.parent.documents_cache.get_tokens(document):\n if token.type in [Token.ERROR, Token.FATAL_ERROR]:\n result.append(self._create_error_from_token(token))\n\n try:\n for variable_token in token.tokenize_variables():\n if variable_token == token:\n break\n\n if variable_token.type in [Token.ERROR, Token.FATAL_ERROR]:\n result.append(self._create_error_from_token(variable_token))\n\n except VariableError as e:\n result.append(\n Diagnostic(\n range=range_from_token(token),\n message=str(e),\n severity=DiagnosticSeverity.ERROR,\n source=self.source_name,\n code=type(e).__qualname__,\n )\n )\n\n return DiagnosticsResult(self.collect_token_errors, result)\n except BaseException as e:\n return DiagnosticsResult(\n self.collect_token_errors,\n [\n Diagnostic(\n range=Range(\n start=Position(\n line=0,\n character=0,\n ),\n end=Position(\n line=len(document.lines),\n character=len(document.lines[-1] or \"\"),\n ),\n ),\n message=f\"Fatal {type(e).__qualname__}: {e}\",\n severity=DiagnosticSeverity.ERROR,\n source=self.source_name,\n code=type(e).__qualname__,\n )\n ],\n )\n\n @language_id(\"robotframework\")\n @_logger.call\n async def collect_model_errors(self, sender: Any, document: TextDocument) -> DiagnosticsResult:\n from ..utils.ast import HasError, HasErrors\n from ..utils.async_ast import AsyncVisitor\n\n class Visitor(AsyncVisitor):\n def __init__(self, parent: RobotDiagnosticsProtocolPart) -> None:\n super().__init__()\n self.parent = parent\n self.errors: List[Diagnostic] = []\n\n @classmethod\n async def find_from(cls, model: ast.AST, parent: RobotDiagnosticsProtocolPart) -> List[Diagnostic]:\n finder = cls(parent)\n await finder.visit(model)\n return finder.errors\n\n async def generic_visit(self, node: ast.AST) -> None:\n error = node.error if isinstance(node, HasError) else None\n if error is not None:\n self.errors.append(self.parent._create_error_from_node(node, error))\n errors = node.errors if isinstance(node, HasErrors) else None\n\n if errors is not None:\n for e in errors:\n self.errors.append(self.parent._create_error_from_node(node, e))\n await super().generic_visit(node)\n\n return DiagnosticsResult(\n self.collect_model_errors,\n await Visitor.find_from(await self.parent.documents_cache.get_model(document), self),\n )\n\n @language_id(\"robotframework\")\n @_logger.call\n async def collect_walk_model_errors(self, sender: Any, document: TextDocument) -> DiagnosticsResult:\n from ..utils.ast import HasError, HasErrors\n from ..utils.async_ast import walk\n\n result: List[Diagnostic] = []\n\n async for node in walk(await self.parent.documents_cache.get_model(document)):\n error = node.error if isinstance(node, HasError) else None\n if error is not None:\n result.append(self._create_error_from_node(node, error))\n errors = node.errors if isinstance(node, HasErrors) else None\n if errors is not None:\n for e in errors:\n result.append(self._create_error_from_node(node, e))\n\n return DiagnosticsResult(self.collect_walk_model_errors, result)\n\n @language_id(\"robotframework\")\n @_logger.call\n async def collect_namespace_diagnostics(self, sender: Any, document: TextDocument) -> DiagnosticsResult:\n namespace = await self.parent.documents_cache.get_namespace(document)\n if namespace is None:\n return DiagnosticsResult(self.collect_namespace_diagnostics, None)\n\n return DiagnosticsResult(self.collect_namespace_diagnostics, await namespace.get_diagnostisc())\n","sub_path":"robotcode/language_server/robotframework/parts/diagnostics.py","file_name":"diagnostics.py","file_ext":"py","file_size_in_byte":7438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"27623025","text":"\nheight = int(input('Input the height of rhombus. (Please, make it even): '))\nwhile height % 2 == 0:\n height = int(input('The number is not even. Input the height of rhombus. (Please, make it even): '))\nelse:\n width = height\nfor i in range(height):\n for j in range(width):\n if i == height//2 \\\n or (i == 0 and j == width//2) \\\n or (i == height - 1 and j == width//2) \\\n or (i <= height//2 and width//2 - i <= j <= width//2 + i) \\\n or (i == height//2 + j) \\\n or (i == height//2 + ((width-1) - j))\\\n or (j == width//2 and height//2 < i < height - 1):\n print('* ', end='')\n else:\n print(' ', end='')\n print()\n\n","sub_path":"Lesson_05/rhombus_with_diagonal.py","file_name":"rhombus_with_diagonal.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"81648556","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nfrom data_generator.batch_generator import BatchGenerator\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint, CSVLogger, EarlyStopping\nfrom models import AlexNet, LeNet\nfrom keras.applications.vgg16 import VGG16\nfrom keras import backend as K\nK.set_image_data_format('channels_last')\n\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.layers import BatchNormalization, Activation, GlobalAveragePooling2D, UpSampling2D\nfrom keras.layers.core import Flatten, Dense, Dropout\nfrom keras.models import Model\n\nimport tensorflow as tf\n\n\n# Image-treat-1: sem data augmentation, com normalização e equalização\n# \n# Image-treat-2: com data augmentation, com normalização e equalização\n# \n# Image-treat-3: com data augmentation, com normalização e com equalização\n\n# In[2]:\n\n\n#config = tf.ConfigProto(allow_soft_placement=True)\n#config.gpu_options.allocator_type = 'BFC'\n#config.gpu_options.per_process_gpu_memory_fraction = 0.9\n\n\n# In[3]:\n\n\napproach = 'abordagem6' \nactivation = 'relu'\nnet = 'vgg16'\n\nif net == 'alexnet':\n model = AlexNet\nelif net =='lenet':\n model = LeNet\nelif net == 'vgg16':\n model = VGG16 \ncsvlogger_name = 'callbacks/'+net +'/age/history-regression-' + approach + '-' + activation + '.csv'\ncheckpoint_filename = 'callbacks/'+net+'/age/class-weights-' + approach + '-' + activation + '.{epoch:02d}-{val_loss:.2f}.hdf5'\ncsvlogger_name, checkpoint_filename\n\n\n# In[4]:\n\n\ndf = pd.read_csv('dataset/csv/imdb_csv/imdb_age_regression_train_split_47950-70-10-20.csv')\n\n\n# In[5]:\n\n\ncols = list(df.columns[1:])\nin_format = list(df.columns)\ncols, in_format\n\n\n# In[6]:\n\n\ntrain_dataset = BatchGenerator(box_output_format=cols)\nvalidation_dataset = BatchGenerator(box_output_format=cols)\n\ntrain_dataset. parse_csv(labels_filename='dataset/csv/imdb_csv/imdb_age_regression_train_split_47950-70-10-20.csv', \n images_dir='dataset/imdb-hand-crop',\n input_format=in_format)\n\nvalidation_dataset.parse_csv(labels_filename='dataset/csv/imdb_csv/imdb_age_regression_val_split_47950-70-10-20.csv', \n images_dir='dataset/imdb-hand-crop',\n input_format=in_format)\n\n\n# In[7]:\n\n\nimg_height, img_width, img_depth = (224,224,3)\n\nepochs = 1000\n\ntrain_batch_size = 64\nshuffle = True\nssd_train = False\n\nvalidation_batch_size = 32\n\n\n# In[8]:\n\n\ntrain_generator = train_dataset.generate(batch_size=train_batch_size,\n shuffle=shuffle,\n ssd_train=ssd_train,\n random_rotation=20,\n translate=(0.2, 0.2),\n scale=(0.8, 1.2),\n flip=0.5,\n divide_by_stddev=255,\n returns={'processed_labels'},\n resize=(img_height, img_width))\n\nvalidation_generator = validation_dataset.generate(batch_size=validation_batch_size,\n shuffle=shuffle,\n ssd_train=ssd_train,\n divide_by_stddev=255,\n returns={'processed_labels'},\n resize=(img_height, img_width))\n\nprint(\"Number of images in the dataset:\", train_dataset.get_n_samples())\nprint(\"Number of images in the dataset:\", validation_dataset.get_n_samples())\n\n\n# In[9]:\n\n\nsteps_per_epoch = train_dataset.get_n_samples()/train_batch_size\nvalidation_steps = validation_dataset.get_n_samples()/validation_batch_size\n\n\n# In[10]:\n\n\nbase_model = VGG16(include_top=True, weights=None, input_tensor=None, \n input_shape=(img_height, img_width, img_depth), \n pooling='avg')\n\nbase_model.summary()\n\n\n# In[11]:\n\n\nbase_model.layers.pop()\n\n\n# In[12]:\n\n\nlast = base_model.layers[-1].output\n\npreds = Dense(1, activation='relu')(last)\n\nmodel = Model(base_model.input, preds)\n\n\n# In[13]:\n\n\nmodel.summary()\n\n\n# In[14]:\n\n\noptimizer = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.00001, amsgrad=True)\n\n\n# In[15]:\n\n\ncsv_logger = CSVLogger(csvlogger_name, append=True, separator=',')\n\ncheckpoint = ModelCheckpoint(checkpoint_filename,\n monitor='val_loss',\n verbose=1,\n save_best_only=False,\n period=1)\n\nearlystopping = EarlyStopping(patience=30, mode='min')\n\n#callbacks = [tensorboard, checkpoint]\ncallbacks=[checkpoint, csv_logger, earlystopping]\n\n\n# In[16]:\n\n\nmodel.compile(loss='mse', optimizer=optimizer, metrics=['mae'])\n\n\n# In[17]:\n\n\nmodel.fit_generator(train_generator, epochs=epochs, \n steps_per_epoch=128, \n validation_data=validation_generator,\n validation_steps=validation_steps,\n callbacks=callbacks)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"vgg_age_regression-Copy1.py","file_name":"vgg_age_regression-Copy1.py","file_ext":"py","file_size_in_byte":5226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"460901026","text":"#!/usr/bin/env python\nfrom jasp import *\nfrom ase.io.bader import attach_charges\nfrom ase.units import Bohr\nwith jasp('molecules/h2o-bader') as calc:\n atoms = calc.get_atoms()\n symbols = np.array(atoms.get_chemical_symbols())[calc.sort]\n pos = atoms.positions[calc.sort] * Bohr\n newatoms = Atoms(symbols, positions=pos, cell=atoms.get_cell())\n attach_charges(newatoms, 'ACF.dat')\n print('#+tblname: bader')\n print('#+caption: Bader charges for a water molecule')\n print('| atom | Bader charge|')\n print('|-')\n for atom in newatoms:\n print('|{0} | {1} |'.format(atom.symbol, atom.charge))","sub_path":"learn/script-38.py","file_name":"script-38.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"67670575","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport json\nimport random\n\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.http import HttpRequest\nfrom django.test import TestCase\nfrom tastypie.bundle import Bundle\n\nfrom ralph.account. models import BoundPerm, Profile, Perm\nfrom ralph.business.models import Venture\nfrom ralph.cmdb import models as chdb\nfrom ralph.cmdb.api import CIChangeCMDBHistoryResource\nfrom ralph.cmdb.importer import CIImporter\nfrom ralph.cmdb.models import (\n CIChangePuppet,\n CIChangeGit,\n CIChangeCMDBHistory,\n CIChange,\n CILayer,\n CI_RELATION_TYPES,\n)\nfrom ralph.cmdb.models_ci import (\n CIOwnershipType,\n CIOwnership,\n CI,\n CIOwner,\n CIType,\n CIRelation,\n)\nfrom ralph.ui.tests.global_utils import create_user\n\nCURRENT_DIR = settings.CURRENT_DIR\n\n\nclass CMDBApiTest(TestCase):\n def setUp(self):\n self.user = create_user('api_user', 'test@mail.local', 'password')\n self.layers = CILayer.objects.all()\n self.types = CIType.objects.all()\n self.create_owners()\n self.create_cis()\n self.create_ownerships()\n self.create_relations()\n self.data = {\n 'format': 'json',\n 'username': self.user.username,\n 'api_key': self.user.api_key.key\n }\n cache.delete(\"api_user_accesses\")\n\n def create_owners(self):\n self.owner1 = CIOwner(\n first_name='first_name_owner1',\n last_name='last_name_owner1',\n email='first_name_owner1.last_name_owner1@ralph.local',\n )\n self.owner1.save()\n self.owner2 = CIOwner(\n first_name='first_name_owner2',\n last_name='last_name_owner2',\n email='first_name_owner2.last_name_owner2@ralph.local',\n )\n self.owner2.save()\n\n def create_cis(self):\n self.ci1 = CI(\n uid='uid-ci1',\n type=self.types[0],\n barcode='barcodeci1',\n name='ciname1',\n )\n self.ci1.save()\n self.ci1.layers = [self.layers[0].id, self.layers[1].id]\n self.ci1.save()\n self.ci2 = CI(\n uid='uid-ci2',\n type=self.types[1],\n barcode='barcodeci2',\n name='ciname2',\n )\n self.ci2.save()\n self.ci2.layers = [self.layers[0].id]\n self.ci2.save()\n self.ci3 = CI(\n uid='other-ci3',\n type=self.types[1],\n barcode='otherbarcodeci3',\n name='otherci',\n )\n self.ci3.save()\n self.ci3.layers = [self.layers[1].id]\n self.ci3.save()\n\n def create_ownerships(self):\n self.ciownership1 = CIOwnership(\n ci=self.ci1,\n owner=self.owner1,\n type=CIOwnershipType.technical,\n )\n self.ciownership1.save()\n self.ciownership2 = CIOwnership(\n ci=self.ci1,\n owner=self.owner2,\n type=CIOwnershipType.business,\n )\n self.ciownership2.save()\n self.ciownership3 = CIOwnership(\n ci=self.ci2,\n owner=self.owner2,\n type=CIOwnershipType.business,\n )\n self.ciownership3.save()\n\n def create_relations(self):\n self.relation1 = CIRelation(\n parent=self.ci1,\n child=self.ci2,\n type=CI_RELATION_TYPES.CONTAINS,\n )\n self.relation1.save()\n self.relation2 = CIRelation(\n parent=self.ci2,\n child=self.ci3,\n type=CI_RELATION_TYPES.HASROLE,\n )\n self.relation2.save()\n\n def test_layers(self):\n path = \"/api/v0.9/cilayers/\"\n response = self.client.get(path=path, data=self.data, format='json')\n json_string = response.content\n json_data = json.loads(json_string)\n resource_uris = [ci_layer['resource_uri'] for ci_layer in json_data['objects']]\n\n response = self.client.get(\n path=resource_uris[0], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['name'], self.layers[0].name)\n\n response = self.client.get(\n path=resource_uris[1], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['name'], self.layers[1].name)\n\n def test_types(self):\n path = \"/api/v0.9/citypes/\"\n response = self.client.get(path=path, data=self.data, format='json')\n json_string = response.content\n json_data = json.loads(json_string)\n resource_uris = [ci_type['resource_uri'] for ci_type in json_data['objects']]\n\n response = self.client.get(\n path=resource_uris[0], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n\n self.assertEqual(json_data['name'], self.types[0].name)\n\n response = self.client.get(\n path=resource_uris[1], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['name'], self.types[1].name)\n\n def test_ci(self):\n path = \"/api/v0.9/ci/\"\n response = self.client.get(path=path, data=self.data, format='json')\n json_string = response.content\n json_data = json.loads(json_string)\n resource_uris = [ci['resource_uri'] for ci in json_data['objects']]\n\n response = self.client.get(\n path=resource_uris[0], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['layers'][0]['name'], self.layers[0].name)\n self.assertEqual(json_data['layers'][1]['name'], self.layers[1].name)\n self.assertEqual(json_data['barcode'], self.ci1.barcode)\n self.assertEqual(json_data['name'], self.ci1.name)\n self.assertEqual(json_data['type']['name'], self.ci1.type.name)\n self.assertEqual(json_data['uid'], self.ci1.uid)\n self.assertEqual(\n json_data['technical_owners'][0]['username'],\n '{}.{}'.format(self.owner1.first_name, self.owner1.last_name)\n )\n self.assertEqual(\n json_data['business_owners'][0]['username'],\n '{}.{}'.format(self.owner2.first_name, self.owner2.last_name)\n )\n\n response = self.client.get(\n path=resource_uris[1], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['layers'][0]['name'], self.layers[0].name)\n self.assertEqual(json_data['barcode'], self.ci2.barcode)\n self.assertEqual(json_data['name'], self.ci2.name)\n self.assertEqual(json_data['type']['name'], self.ci2.type.name)\n self.assertEqual(json_data['uid'], self.ci2.uid)\n self.assertFalse(json_data['technical_owners'])\n self.assertEqual(\n json_data['business_owners'][0]['username'],\n '{}.{}'.format(self.owner2.first_name, self.owner2.last_name)\n )\n\n def test_relations(self):\n path = \"/api/v0.9/cirelation/\"\n response = self.client.get(path=path, data=self.data, format='json')\n json_string = response.content\n json_data = json.loads(json_string)\n resource_uris = [ci_relation['resource_uri'] for ci_relation in json_data['objects']]\n\n response = self.client.get(\n path=resource_uris[0], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['parent'], self.ci1.id)\n self.assertEqual(json_data['child'], self.ci2.id)\n self.assertEqual(json_data['type'], CI_RELATION_TYPES.CONTAINS)\n\n response = self.client.get(\n path=resource_uris[1], data=self.data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['parent'], self.ci2.id)\n self.assertEqual(json_data['child'], self.ci3.id)\n self.assertEqual(json_data['type'], CI_RELATION_TYPES.HASROLE)\n\n def test_ci_filter_exact(self):\n path = \"/api/v0.9/ci/\"\n data = self.data.copy()\n data['name__exact'] = 'otherci'\n response = self.client.get(path=path, data=data, format='json')\n json_string = response.content\n json_data = json.loads(json_string)\n resource_uris = [ci['resource_uri'] for ci in json_data['objects']]\n self.assertEqual(len(resource_uris), 1)\n response = self.client.get(\n path=resource_uris[0], data=data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['layers'][0]['name'], self.layers[1].name)\n self.assertEqual(json_data['barcode'], self.ci3.barcode)\n self.assertEqual(json_data['name'], self.ci3.name)\n self.assertEqual(json_data['type']['name'], self.ci3.type.name)\n self.assertEqual(json_data['uid'], self.ci3.uid)\n\n def test_ci_filter_startswith(self):\n data = self.data.copy()\n path = \"/api/v0.9/ci/\"\n data['name__startswith'] = 'ciname'\n response = self.client.get(path=path, data=data, format='json')\n json_string = response.content\n json_data = json.loads(json_string)\n resource_uris = [ci['resource_uri'] for ci in json_data['objects']]\n self.assertEqual(len(resource_uris), 2)\n response = self.client.get(\n path=resource_uris[0], data=data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['layers'][0]['name'], self.layers[0].name)\n self.assertEqual(json_data['barcode'], self.ci1.barcode)\n self.assertEqual(json_data['name'], self.ci1.name)\n self.assertEqual(json_data['type']['name'], self.ci1.type.name)\n self.assertEqual(json_data['uid'], self.ci1.uid)\n\n response = self.client.get(\n path=resource_uris[1], data=data, format='json',\n )\n json_string = response.content\n json_data = json.loads(json_string)\n self.assertEqual(json_data['layers'][0]['name'], self.layers[0].name)\n self.assertEqual(json_data['barcode'], self.ci2.barcode)\n self.assertEqual(json_data['name'], self.ci2.name)\n self.assertEqual(json_data['type']['name'], self.ci2.type.name)\n self.assertEqual(json_data['uid'], self.ci2.uid)\n\n\nclass CIApiTest(TestCase):\n def setUp(self):\n self.user = create_user(\n 'api_user',\n 'test@mail.local',\n 'password',\n is_superuser=True\n )\n self.puppet_cv = \"v%s\" % random.randrange(0, 1000)\n self.post_data_puppet = {\n 'configuration_version': self.puppet_cv,\n 'host': 's11111.dc2',\n 'kind': 'apply',\n 'status': 'failed',\n 'time': '2012-11-14 13:00:00',\n }\n\n self.git_changeset = \"change:%s\" % random.randrange(0, 1000)\n self.git_comment = \"comment:%s\" % random.randrange(0, 1000)\n self.post_data_git = {\n 'author': 'Jan Kowalski',\n 'changeset': self.git_changeset,\n 'comment': self.git_comment,\n 'file_paths': '/some/path',\n }\n\n temp_venture = Venture.objects.create(name='TempTestVenture')\n if settings.AUTOCI:\n self.ci = CI.get_by_content_object(temp_venture)\n else:\n CIImporter().import_single_object(temp_venture)\n self.ci = CI.objects.create(\n name='TempTestVentureCI',\n uid=CI.get_uid_by_content_object(temp_venture),\n type_id=4,\n )\n\n self.cmdb_new_value = 'nv_%s' % random.randrange(0, 1000)\n self.cmdb_old_value = 'ov_%s' % random.randrange(0, 1000)\n self.post_data_cmdb_change = {\n 'ci': '/api/v0.9/ci/%d/' % self.ci.pk,\n 'comment': 'test api',\n 'field_name': 'child',\n 'new_value': self.cmdb_new_value,\n 'old_value': self.cmdb_old_value,\n 'time': '2012-11-15 12:00:00',\n }\n cache.clear()\n\n def test_ci_change_puppet_registration(self):\n response = self.client.post(\n '/api/v0.9/cichangepuppet/?username={}&api_key={}'.format(\n self.user.username,\n self.user.api_key.key,\n ),\n json.dumps(self.post_data_puppet),\n content_type='application/json'\n )\n self.assertEqual(response.status_code, 201)\n puppet_change = None\n try:\n puppet_change = CIChangePuppet.objects.get(\n host='s11111.dc2', configuration_version=self.puppet_cv)\n except CIChangePuppet.DoesNotExist:\n pass\n self.assertNotEqual(puppet_change, None)\n self.assertEqual(puppet_change.kind, 'apply')\n self.assertEqual(puppet_change.status, 'failed')\n self.assertEqual(\n CIChange.objects.filter(\n object_id=puppet_change.id,\n type=chdb.CI_CHANGE_TYPES.CONF_AGENT.id).count(), 1)\n\n def test_ci_change_git_registration(self):\n response = self.client.post(\n '/api/v0.9/cichangegit/?username={}&api_key={}'.format(\n self.user.username,\n self.user.api_key.key,\n ),\n json.dumps(self.post_data_git),\n content_type='application/json'\n )\n self.assertEqual(response.status_code, 201)\n git_change = None\n try:\n git_change = CIChangeGit.objects.get(changeset=self.git_changeset,\n comment=self.git_comment)\n except CIChangePuppet.DoesNotExist:\n pass\n self.assertNotEqual(git_change, None)\n self.assertEqual(git_change.author, 'Jan Kowalski')\n self.assertEqual(git_change.file_paths, '/some/path')\n self.assertEqual(\n CIChange.objects.filter(\n object_id=git_change.id,\n type=chdb.CI_CHANGE_TYPES.CONF_GIT.id,\n ).count(),\n 1,\n )\n\n def test_ci_change_cmdbhistory_registration(self):\n request = HttpRequest()\n request.user = self.user\n cmdb_bundle = Bundle(data=self.post_data_cmdb_change, request=request)\n cmdb_resource = CIChangeCMDBHistoryResource()\n cmdb_resource.obj_create(bundle=cmdb_bundle)\n\n cmdb_change = None\n try:\n cmdb_change = CIChangeCMDBHistory.objects.get(\n ci_id=self.ci.id, old_value=self.cmdb_old_value,\n new_value=self.cmdb_new_value)\n except CIChangeCMDBHistory.DoesNotExist:\n pass\n self.assertNotEqual(cmdb_change, None)\n self.assertEqual(\n CIChange.objects.filter(\n object_id=cmdb_change.id,\n type=chdb.CI_CHANGE_TYPES.CI.id\n ).count(),\n 1,\n )\n\n\nclass AccessToCMDBApiTest(TestCase):\n def setUp(self):\n self.user = create_user(\n 'api_user',\n 'test@mail.local',\n 'password',\n is_staff=False,\n is_superuser=False,\n )\n self.api_login = {\n 'format': 'json',\n 'username': self.user.username,\n 'api_key': self.user.api_key.key,\n }\n cache.delete(\"api_user_accesses\")\n\n\n def get_response(self, resource):\n path = \"/api/v0.9/%s/\" % resource\n response = self.client.get(\n path=path,\n data=self.api_login,\n format='json',\n )\n return response\n\n def add_perms(self, perms):\n user_profile = Profile.objects.get(user=self.user)\n for perm in perms:\n BoundPerm(profile=user_profile, perm=perm).save()\n\n def test_businessline_resource(self):\n resource = 'businessline'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_service_resource(self):\n resource = 'service'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_cirelation_resource(self):\n resource = 'cirelation'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_ci_resource(self):\n resource = 'ci'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_cilayers_resource(self):\n resource = 'cilayers'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_cichange_resource(self):\n resource = 'cichange'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_cichangezabbixtrigger_resource(self):\n resource = 'cichangezabbixtrigger'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_cichangegit_resource(self):\n resource = 'cichangegit'\n perms = [Perm.read_configuration_item_info_git,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_cichangepuppet_resource(self):\n resource = 'cichangepuppet'\n perms = [Perm.read_configuration_item_info_puppet,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_cichangecmdbhistory_resource(self):\n resource = 'cichangecmdbhistory'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_citypes_resource(self):\n resource = 'citypes'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n\n def test_ciowners_resource(self):\n resource = 'ciowners'\n perms = [Perm.read_configuration_item_info_generic,]\n\n schema = '%s/schema' % resource\n response = self.get_response(schema)\n self.assertEqual(response.status_code, 200)\n\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 401)\n\n # Add perms to display resources\n self.add_perms(perms=perms)\n response = self.get_response(resource)\n self.assertEqual(response.status_code, 200)\n","sub_path":"src/ralph/cmdb/tests/unit/tests_api.py","file_name":"tests_api.py","file_ext":"py","file_size_in_byte":22891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"65289442","text":"birthdays = {'Alice': 'April 1', 'Bob' : 'Dec 12', 'Alex': 'Sept 28'} # The dictionary of names available.\n\nwhile True:\n\tprint (\"Enter a name: (blank to quit)\") # Prompt the user.\n\tname = input () # Ask the user to enter the name.\n\tif name == ' ': # If the user doesn't type anything, it stops the program.\n\t\tbreak\n\n\tif name in birthdays: # Checks to see if the thing you entered is in the dictionary.\n\t\tprint (birthdays[name] + ' is the birthday of ' + name) # Say whose birthday it is.\n\n\telse: # If the user enters something invalid, tell them you do not recognize the name.\n\t\tprint ('I do not have the birthday information for ' + name) # Tell the user you don't have the name.\n\t\tprint ('What is their birthday?')\n\t\tbday = input\n\t\tbirthdays[name] = bday\n\t\tprint(\"Birthday database updated.\")\n","sub_path":"birthdays.py","file_name":"birthdays.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"171041549","text":"# coding: utf-8\nfrom .plot_layer import PlotLayer\nfrom nuwe_data_viewer.plugin.plot_renderer.grid_data import GridData\n\n\nclass ContourLayer(PlotLayer):\n def __init__(self, name, core_id=None, fill=False):\n PlotLayer.__init__(self, name, core_id)\n self.grid_data = None\n self.fill = fill\n\n self.levels = None\n self.colors = None\n self.color_map = None\n self.line_width = None\n self.line_type = None\n\n def set_data(self, grid_data: GridData):\n self.grid_data = grid_data\n","sub_path":"nuwe_data_viewer/plugin/plot_renderer/plot/contour_layer.py","file_name":"contour_layer.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"599748991","text":"import pytest\nfrom app.notify_client.notification_api_client import NotificationApiClient\n\n\n@pytest.mark.parametrize(\"arguments,expected_call\", [\n (\n {},\n {'url': '/service/abcd1234/notifications', 'params': {}}\n ),\n (\n {'page': 99},\n {'url': '/service/abcd1234/notifications', 'params': {'page': 99}}\n ),\n (\n {'include_jobs': False},\n {'url': '/service/abcd1234/notifications', 'params': {'include_jobs': False}}\n ),\n (\n {'include_from_test_key': True},\n {'url': '/service/abcd1234/notifications', 'params': {'include_from_test_key': True}}\n ),\n (\n {'job_id': 'efgh5678'},\n {'url': '/service/abcd1234/job/efgh5678/notifications', 'params': {}}\n ),\n (\n {'job_id': 'efgh5678', 'page': 48},\n {'url': '/service/abcd1234/job/efgh5678/notifications', 'params': {'page': 48}}\n )\n])\ndef test_client_gets_notifications_for_service_and_job_by_page(mocker, arguments, expected_call):\n\n mock_get = mocker.patch('app.notify_client.notification_api_client.NotificationApiClient.get')\n NotificationApiClient().get_notifications_for_service('abcd1234', **arguments)\n mock_get.assert_called_once_with(**expected_call)\n\n\ndef test_send_notification(mocker, logged_in_client, active_user_with_permissions):\n mock_post = mocker.patch('app.notify_client.notification_api_client.NotificationApiClient.post')\n NotificationApiClient().send_notification('foo', template_id='bar', recipient='07700900001', personalisation=None)\n mock_post.assert_called_once_with(\n url='/service/foo/send-notification',\n data={\n 'template_id': 'bar',\n 'to': '07700900001',\n 'personalisation': None,\n 'created_by': active_user_with_permissions.id\n }\n )\n\n\ndef test_get_notification(mocker):\n mock_get = mocker.patch('app.notify_client.notification_api_client.NotificationApiClient.get')\n NotificationApiClient().get_notification('foo', 'bar')\n mock_get.assert_called_once_with(\n url='/service/foo/notifications/bar'\n )\n","sub_path":"tests/app/notify_client/test_notification_client.py","file_name":"test_notification_client.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"168268848","text":"#!/usr/bin/env python\n\nfrom setuptools import setup\n\nVERSION = None\nwith open('ipxeplease/__init__.py') as f:\n for line in f:\n if line.startswith('__version__'):\n VERSION = line.replace(\"'\", '').split('=')[1].strip()\n break\nif VERSION is None:\n raise ValueError('__version__ not found in __init__.py')\n\nDOWNLOAD_URL = 'https://github.com/teran-mckinney/ipxeplease-python/tarball/{}'\n\nDESCRIPTION = 'ipxeplease Python client library'\n\nsetup(\n python_requires='>=3.3',\n name='ipxeplease',\n version=VERSION,\n author='Teran McKinney',\n author_email='sega01@go-beyond.org',\n description=DESCRIPTION,\n keywords=['ipxe'],\n license='Unlicense',\n url='https://github.com/teran-mckinney/ipxeplease-python',\n download_url=DOWNLOAD_URL.format(VERSION),\n packages=['ipxeplease'],\n install_requires=[\n 'aaargh',\n 'requests'\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"481638997","text":"import os\nimport sys\nfrom socket import gethostname\nimport openbabel\nimport re\nimport time\nimport apicall as call\nimport shlex\nimport numpy as np\nimport shutil\nimport torsiongenerator as torgen\nimport traceback\nimport warnings\nfrom rdkit.Chem import rdmolfiles\nfrom rdkit import Chem\n\ndef GeometryOPTWrapper(poltype,mol):\n try:\n optmol,error,torsionrestraints = GeometryOptimization(poltype,mol)\n except:\n redo=False\n if poltype.fullopt==True:\n if poltype.pcm==True:\n # Gaussian would have been used first if was detected. \n poltype.pcm=False\n poltype.optpcm=False\n redo=True\n else:\n if poltype.optmethod=='MP2' and (poltype.use_gaus==False and poltype.use_gausoptonly==False) and poltype.foundgauss==True:\n redo=True\n poltype.use_gausoptonly=True\n\n if redo==True:\n shutil.copy(poltype.logoptfname,poltype.logoptfname.replace('.log','_failed.log'))\n optmol,error,torsionrestraints = GeometryOPTWrapper(poltype,mol) # recursive call allows for muliple attempts\n else:\n traceback.print_exc(file=sys.stdout)\n sys.exit()\n\n return optmol,error,torsionrestraints\n \n\n\ndef CreatePsi4OPTInputFile(poltype,comfilecoords,comfilename,mol,modred,bondanglerestraints,skipscferror,chg,loose,torsionrestraints=[]):\n tempread=open(comfilecoords,'r')\n results=tempread.readlines()\n tempread.close()\n inputname=comfilename.replace('.com','.psi4')\n temp=open(inputname,'w')\n temp.write('molecule { '+'\\n')\n if chg==None:\n temp.write('%d %d\\n' % (mol.GetTotalCharge(), mol.GetTotalSpinMultiplicity()))\n else:\n temp.write('%d %d\\n' % (chg, mol.GetTotalSpinMultiplicity()))\n\n for lineidx in range(len(results)):\n line=results[lineidx]\n linesplit=line.split()\n if len(linesplit)==4 and '#' not in line:\n temp.write(line)\n temp.write('}'+'\\n')\n if poltype.optpcm==True:\n temp.write('set {'+'\\n')\n if loose==True:\n temp.write(' g_convergence GAU_LOOSE'+'\\n')\n else:\n temp.write(' g_convergence GAU'+'\\n')\n\n temp.write(' scf_type pk'+'\\n')\n temp.write(' pcm true'+'\\n')\n temp.write(' pcm_scf_type total '+'\\n')\n temp.write(' geom_maxiter '+str(poltype.optmaxcycle)+'\\n')\n temp.write('}'+'\\n')\n temp.write('pcm = {'+'\\n')\n temp.write(' Units = Angstrom'+'\\n')\n temp.write(' Medium {'+'\\n')\n temp.write(' SolverType = IEFPCM'+'\\n')\n temp.write(' Solvent = Water'+'\\n')\n temp.write(' }'+'\\n')\n temp.write(' Cavity {'+'\\n')\n temp.write(' RadiiSet = UFF'+'\\n')\n temp.write(' Type = GePol'+'\\n')\n temp.write(' Scaling = False'+'\\n')\n temp.write(' Area = 0.3'+'\\n')\n temp.write(' Mode = Implicit'+'\\n')\n temp.write(' }'+'\\n')\n temp.write('}'+'\\n')\n else:\n temp.write('set {'+'\\n')\n temp.write(' geom_maxiter '+str(poltype.optmaxcycle)+'\\n')\n if loose==True:\n temp.write(' g_convergence GAU_LOOSE'+'\\n')\n else:\n temp.write(' g_convergence GAU'+'\\n')\n\n temp.write(' dynamic_level 1'+'\\n')\n temp.write('}'+'\\n')\n\n if bondanglerestraints!=None:\n space=' '\n bondres=[bondanglerestraints[0]]\n string='frozen_distance'\n temp.write('set optking{'+'\\n')\n temp.write(' '+string+' '+'='+' '+'('+'\"'+'\\n')\n for res in bondres:\n res=[str(i) for i in res]\n resstring=' '.join(res)+'\\n'\n temp.write(' '+resstring)\n temp.write(' \"'+')'+'\\n')\n temp.write('}'+'\\n')\n \n anglerestraints=bondanglerestraints[1:]\n string='frozen_bend'\n if len(anglerestraints)!=0:\n temp.write('set optking{'+'\\n')\n temp.write(' '+string+' '+'='+' '+'('+'\"'+'\\n')\n for res in anglerestraints:\n res=[str(i) for i in res]\n resstring=' '.join(res)+'\\n'\n temp.write(' '+resstring)\n temp.write(' \"'+')'+'\\n')\n temp.write('}'+'\\n')\n if len(torsionrestraints)!=0:\n temp.write('set optking { '+'\\n')\n temp.write(' frozen_dihedral = (\"'+'\\n')\n for residx in range(len(torsionrestraints)):\n res=torsionrestraints[residx]\n rta,rtb,rtc,rtd=res[:]\n if residx>0:\n temp.write(', %d %d %d %d\\n' % (rta,rtb,rtc,rtd))\n else:\n temp.write(' %d %d %d %d\\n' % (rta,rtb,rtc,rtd))\n\n temp.write(' \")'+'\\n')\n temp.write('}'+'\\n')\n\n if poltype.allowradicals==True:\n temp.write('set reference uhf '+'\\n')\n\n\n temp.write('memory '+poltype.maxmem+'\\n')\n temp.write('set_num_threads(%s)'%(poltype.numproc)+'\\n')\n temp.write('psi4_io.set_default_path(\"%s\")'%(poltype.scrtmpdirpsi4)+'\\n')\n temp.write('for _ in range(1):'+'\\n')\n temp.write(' try:'+'\\n')\n if poltype.optpcm==True:\n temp.write(' set opt_coordinates cartesian'+'\\n')\n spacedformulastr=mol.GetSpacedFormula()\n if ('I ' in spacedformulastr):\n temp.write(' basis {'+'\\n')\n temp.write(' ['+' '+poltype.optbasissetfile+' '+poltype.iodineoptbasissetfile +' '+ ']'+'\\n')\n temp=ReadInBasisSet(poltype,temp,poltype.optbasissetfile,poltype.iodineoptbasissetfile)\n temp.write(' }'+'\\n')\n temp.write(\" optimize('%s')\" % (poltype.optmethod.lower())+'\\n')\n\n else:\n\n if modred==False:\n temp.write(' set opt_coordinates both'+'\\n')\n temp.write(\" optimize('%s/%s')\" % (poltype.optmethod.lower(),poltype.optbasisset)+'\\n')\n if poltype.freq:\n temp.write(' scf_e,scf_wfn=freq(\"%s/%s\",return_wfn=True)'%(poltype.optmethod.lower(),poltype.optbasisset)+'\\n')\n temp.write(' break'+'\\n')\n temp.write(' except OptimizationConvergenceError:'+'\\n')\n temp.write(' break'+'\\n')\n if skipscferror==True:\n temp.write(' except SCFConvergenceError:'+'\\n')\n temp.write(' pass'+'\\n')\n \n temp.write(' else:'+'\\n')\n temp.write(' try:'+'\\n')\n temp.write(' set opt_coordinates cartesian'+'\\n')\n if ('I ' in spacedformulastr):\n temp.write(\" optimize('%s')\" % (poltype.optmethod.lower())+'\\n')\n else:\n temp.write(\" optimize('%s/%s')\" % (poltype.optmethod.lower(),poltype.optbasisset)+'\\n')\n\n if poltype.freq:\n temp.write(' scf_e,scf_wfn=freq(\"%s/%s\",return_wfn=True)'%(poltype.optmethod.lower(),poltype.optbasisset)+'\\n')\n temp.write(' break'+'\\n')\n temp.write(' except OptimizationConvergenceError:'+'\\n')\n temp.write(' '+'pass'+'\\n')\n\n temp.write('clean()'+'\\n')\n temp.close()\n outputname=os.path.splitext(inputname)[0] + '.log'\n return inputname,outputname\n\ndef ReadInBasisSet(poltype,tmpfh,normalelementbasissetfile,otherelementbasissetfile):\n newtemp=open(poltype.basissetpath+normalelementbasissetfile,'r')\n results=newtemp.readlines()\n newtemp.close()\n for line in results:\n if '!' not in line:\n tmpfh.write(' '+line)\n\n\n newtemp=open(poltype.basissetpath+otherelementbasissetfile,'r')\n results=newtemp.readlines()\n newtemp.close()\n for line in results:\n if '!' not in line:\n tmpfh.write(' '+line)\n return tmpfh\n\n\n\ndef NumberInLine(poltype,line):\n numinline=False\n linesplit=line.split()\n for e in linesplit:\n try:\n float(e)\n numinline=True\n except:\n continue\n \n return numinline\n\n\ndef CheckIfPsi4Log(poltype,outputlog):\n check=False\n temp=open(outputlog,'r')\n results=temp.readlines()\n temp.close()\n for line in results:\n if 'Psi4' in line:\n check=True\n break \n return check \n\n\ndef GrabFinalXYZStructure(poltype,logname,filename,mol):\n checkifpsi4=CheckIfPsi4Log(poltype,logname)\n if checkifpsi4==True:\n temp=open(logname,'r')\n results=temp.readlines()\n temp.close()\n temp=open(filename,'w')\n temp.write(str(mol.NumAtoms())+'\\n')\n temp.write('\\n')\n finalmarker=False\n lengthchange=None\n lastsuccessidx=None\n for lineidx in range(len(results)):\n line=results[lineidx]\n if 'Successfully symmetrized geometry' in line:\n lastsuccessidx=lineidx\n if lastsuccessidx==None: # sometimes it doesnt print this but converges? \n lastsuccessidx=len(results)-1\n for lineidx in range(len(results)):\n line=results[lineidx]\n try:\n if lineidxlastidx: \n linesplit=line.split()\n if (len(linesplit)!=4 and len(linesplit)!=5) and lengthchange==False:\n lengthchange=True\n break\n foundfloat=bool(re.search(r'\\d', line))\n if (len(linesplit)==4 or len(linesplit)==5) and foundfloat==True and 'point' not in line:\n temp.write(' '.join(line.lstrip().split()[:3+1])+'\\n')\n lengthchange=False\n temp.close()\n elif checkifpsi4==False:\n obConversion = openbabel.OBConversion()\n tempmol = openbabel.OBMol()\n inFormat = obConversion.FormatFromExt(logname)\n obConversion.SetInFormat(inFormat)\n obConversion.ReadFile(tempmol, logname)\n obConversion.SetOutFormat('xyz')\n obConversion.WriteFile(tempmol, filename)\n\ndef gen_optcomfile(poltype,comfname,numproc,maxmem,maxdisk,chkname,molecule,modred=True,torsionrestraints=[]):\n \"\"\"\n Intent: Create *.com file for qm opt\n Input:\n comfname: com file name\n numproc: number of processors\n maxmem: max memory size\n chkname: chk file name\n mol: OBMol object\n Output:\n *opt-*.com is written\n Referenced By: run_gaussian\n Description: -\n \"\"\"\n restraintlist = []\n write_com_header(poltype,comfname,chkname,maxdisk,maxmem,numproc)\n tmpfh = open(comfname, \"a\")\n if len(torsionrestraints)==0:\n modred=False\n spacedformulastr=molecule.GetSpacedFormula()\n if modred==True:\n optimizeoptlist = [\"ModRedundant\",\"maxcycles=%s\"%(str(poltype.optmaxcycle)),'Loose']\n else:\n optimizeoptlist = [\"Cartesian\",\"maxcycles=%s\"%(str(poltype.optmaxcycle))]\n\n if restraintlist:\n optimizeoptlist.insert(0,poltype.gausoptcoords)\n optstr=gen_opt_str(poltype,optimizeoptlist)\n if ('I ' in spacedformulastr):\n prevoptbasisset=poltype.optbasisset\n poltype.optbasisset='gen'\n if poltype.freq==True:\n if poltype.optpcm==True:\n optstring= \"%s %s/%s freq SCRF=(PCM)\" % (optstr,poltype.optmethod,poltype.optbasisset)\n else:\n optstring= \"%s %s/%s freq\" % (optstr,poltype.optmethod,poltype.optbasisset)\n else:\n if poltype.optpcm==True:\n optstring= \"%s %s/%s SCRF=(PCM)\" % (optstr,poltype.optmethod,poltype.optbasisset)\n else:\n optstring= \"%s %s/%s\" % (optstr,poltype.optmethod,poltype.optbasisset)\n if ('I ' in spacedformulastr):\n optstring+=' pseudo=read'\n string=' MaxDisk=%s \\n'%(maxdisk)\n optstring+=string\n tmpfh.write(optstring)\n commentstr = poltype.molecprefix + \" Gaussian OPT Calculation on \" + gethostname()\n tmpfh.write('\\n%s\\n\\n' % commentstr)\n tmpfh.write('%d %d\\n' % (molecule.GetTotalCharge(), molecule.GetTotalSpinMultiplicity()))\n tmpfh.close()\n\n iteratombab = openbabel.OBMolAtomIter(molecule)\n tmpfh = open(comfname, \"a\")\n etab = openbabel.OBElementTable()\n for atm in iteratombab:\n tmpfh.write('%2s %11.6f %11.6f %11.6f\\n' % (etab.GetSymbol(atm.GetAtomicNum()), atm.x(), atm.y(), atm.z()))\n tmpfh.write('\\n')\n \n if ('I ' in spacedformulastr):\n formulalist=spacedformulastr.lstrip().rstrip().split()\n elementtobasissetlines=GenerateElementToBasisSetLines(poltype,poltype.basissetpath+poltype.optbasissetfile)\n for element,basissetlines in elementtobasissetlines.items():\n if element in spacedformulastr:\n for line in basissetlines: \n tmpfh.write(line)\n\n\n temp=open(poltype.basissetpath+poltype.iodineoptbasissetfile,'r')\n results=temp.readlines()\n temp.close()\n for line in results:\n if '!' not in line:\n tmpfh.write(line)\n\n\n \n tmpfh.write('\\n')\n tmpfh.write('\\n')\n tmpfh.close()\n if len(torsionrestraints)!=0:\n tempname=comfname.replace('.com','_temp.com')\n temp=open(comfname,'r')\n results=temp.readlines()\n temp.close()\n tmpfh = open(tempname, \"w\")\n foundatomblock=False\n writeres=False\n for k in range(len(results)):\n line=results[k]\n linesplit=line.split() \n if len(linesplit)==4 and foundatomblock==False and '#' not in line:\n foundatomblock=True\n if len(linesplit)!=4 and foundatomblock==True and writeres==False:\n writeres=True\n tmpfh.write('\\n')\n for res in torsionrestraints:\n rta,rtb,rtc,rtd=res[:]\n tmpfh.write('%d %d %d %d F\\n' % (rta,rtb,rtc,rtd))\n tmpfh.write(\"\\n\")\n else:\n tmpfh.write(line)\n\n tmpfh.close()\n os.remove(comfname)\n shutil.copy(tempname,comfname)\n\n\n\n\n\ndef GenerateElementToBasisSetLines(poltype,basissetfile):\n elementtobasissetlines={}\n temp=open(basissetfile,'r')\n results=temp.readlines()\n temp.close()\n lines=[]\n for lineidx in range(len(results)):\n line=results[lineidx]\n if lineidx==0: \n linesplit=line.split()\n element=linesplit[0]\n lines=[line]\n elementtobasissetlines[element]=lines\n elif lineidx>0 and '****' in results[lineidx-1]:\n linesplit=line.split()\n element=linesplit[0]\n lines=[line]\n elementtobasissetlines[element]=lines\n else:\n lines.append(line)\n elementtobasissetlines[element]=lines\n\n\n return elementtobasissetlines\n \n \n \ndef gen_opt_str(poltype,optimizeoptlist):\n optstr = \"#P opt\"\n if optimizeoptlist:\n optstr += \"=(\" + ','.join(optimizeoptlist) + \")\"\n return optstr\n\ndef write_com_header(poltype,comfname,chkfname,maxdisk,maxmem,numproc):\n \"\"\"\n Intent: Add header to *.com file\n Referenced By: gen_optcomfile\n \"\"\"\n tmpfh = open(comfname, \"w\")\n assert tmpfh, \"Cannot create file: \" + comfname+' '+os.getcwd()\n\n tmpfh.write('%RWF=' + poltype.scrtmpdirgau + '/,' + maxdisk + '\\n')\n tmpfh.write(\"%Nosave\\n\")\n tmpfh.write(\"%Chk=\" + os.path.splitext(comfname)[0] + \".chk\\n\")\n tmpfh.write(\"%Mem=\" + maxmem + \"\\n\")\n tmpfh.write(\"%Nproc=\" + str(numproc) + \"\\n\")\n tmpfh.close()\n\ndef AverageBondTableLength(poltype,elementsbondorder,ringbond,hybs):\n elementstobondordertolength={tuple([15,17,1]):2.043,tuple([15,8,1]):2.21,tuple([15,8,1]):1.65,tuple([1,1,1]):.74,tuple([9,9,1]):1.42,tuple([17,17,1]):1.99,tuple([35,35,1]):2.28,tuple([53,53,1]):2.67,tuple([1,6,1]):1.10,tuple([1,7,1]):1.00,tuple([1,8,1]):.97,tuple([1,9,1]):.92,tuple([6,6,1]):1.54,tuple([6,7,1]):1.47,tuple([6,8,1]):1.43,tuple([7,7,1]):1.45,tuple([8,8,1]):1.45,tuple([1,6,1]):1.10,tuple([6,6,2]):1.34,tuple([6,6,3]):1.20,tuple([6,7,2]):1.28,tuple([6,8,2]):1.20,tuple([6,8,3]):1.13,tuple([7,7,2]):1.23,tuple([7,7,3]):1.10,tuple([8,8,2]):1.21,tuple([1,9,1]):.92,tuple([1,17,1]):1.27,tuple([1,35,1]):1.41,tuple([1,53,1]):1.61,tuple([6,16,1]):1.82,tuple([1,6,1]):1.10,tuple([6,9,1]):1.35,tuple([6,17,1]):1.77,tuple([6,35,1]):1.94,tuple([6,53,1]):2.14}\n \n found=False\n length=None\n rev=tuple([elementsbondorder[1],elementsbondorder[0],elementsbondorder[2]])\n if elementsbondorder in elementstobondordertolength.keys():\n length=elementstobondordertolength[elementsbondorder]\n found=True\n elif rev in elementstobondordertolength.keys():\n length=elementstobondordertolength[rev]\n found=True\n if ringbond==True:\n if hybs[0]==2 and hybs[1]==2:\n if elementsbondorder[0]==6 and elementsbondorder[1]==6:\n length=1.41\n found=True\n else:\n found=False\n length=None\n\n\n if found==False:\n tol=.1 # extreme case if any missing above\n else:\n tol=.05 # test this may increase tolerance later\n return tol,length\n\n\ndef CompareBondLengths(poltype,inioptmol,optmol,outputlog):\n isnear=True\n for inib in openbabel.OBMolBondIter(inioptmol):\n beg = inib.GetBeginAtomIdx()\n end = inib.GetEndAtomIdx()\n b=optmol.GetBond(beg,end)\n if b==None:\n isnear=False\n break\n ringbond=inib.IsInRing()\n idxs=[beg,end]\n atoms=[inioptmol.GetAtom(i) for i in idxs]\n hybs=[a.GetHyb() for a in atoms]\n begatom=optmol.GetAtom(beg)\n endatom=optmol.GetAtom(end)\n begatomicnum=begatom.GetAtomicNum()\n endatomicnum=endatom.GetAtomicNum()\n bondorder=b.GetBondOrder()\n elementsbondorder=tuple([begatomicnum,endatomicnum,bondorder])\n tol,length=AverageBondTableLength(poltype,elementsbondorder,ringbond,hybs)\n blength=b.GetLength()\n iniblength=b.GetLength()\n if length!=None:\n diff=np.abs(length-blength)\n else:\n diff=np.abs(iniblength-blength)\n\n if diff>=tol:\n string='Bond lengths changed too much for '+str(beg)+' '+str(end)+' difference is '+str(diff)+\" tolerance is \"+str(tol)+' current bond length is '+str(blength)+' initial bond length is '+str(iniblength)+' internal table bond length is '+str(length)+'. Will try to redo QM opt for '+str(outputlog)\n poltype.WriteToLog(string)\n warnings.warn(string) \n isnear=False\n return isnear\n\n\n\ndef gen_superposeinfile(poltype):\n \"\"\"\n Intent: Initialize superpose input file (for tinker's superpose) \n \"\"\"\n poltype.WriteToLog(\"\\n\")\n poltype.WriteToLog(\"=========================================================\\n\")\n poltype.WriteToLog(\"Structure RMSD Comparison\\n\\n\")\n cmd = poltype.superposeexe + ' ' + poltype.xyzoutfile + ' ' + poltype.tmpxyzfile + '_2'+' 1 N M N 0 > '+ poltype.superposeinfile\n poltype.call_subsystem([cmd],wait=True)\n\n\ndef CheckRMSD(poltype):\n RMSD=None\n for line in open(poltype.superposeinfile,'r'):\n if 'Root Mean' in line:\n RMSD=''\n for e in line:\n if e.isdigit() or e=='.':\n RMSD+=e\n if RMSD!=None: \n if float(RMSD)>poltype.maxRMSD:\n poltype.WriteToLog('Warning: RMSD of QM and MM optimized structures is high, RMSD = '+ RMSD+' Tolerance is '+str(poltype.maxRMSD))\n\n raise ValueError(os.getcwd()+' '+'RMSD of QM and MM optimized structures is high, RMSD = '+str(RMSD))\n else:\n poltype.WriteToLog('RMSD = '+ RMSD+' Tolerance is '+str(poltype.maxRMSD))\n\ndef StructureMinimization(poltype,torsionrestraints):\n poltype.WriteToLog(\"\")\n poltype.WriteToLog(\"=========================================================\")\n poltype.WriteToLog(\"Minimizing structure\\n\")\n AddTorsionRestraints(poltype,poltype.key5fname,torsionrestraints)\n shutil.copy(poltype.xyzoutfile,poltype.tmpxyzfile)\n shutil.copy(poltype.key5fname,poltype.tmpkeyfile)\n cmd = poltype.minimizeexe+' -k '+poltype.tmpkeyfile+' '+poltype.tmpxyzfile+' 0.1 > Minimized_final.out'\n poltype.call_subsystem([cmd], True)\n\n torgen.RemoveStringFromKeyfile(poltype,poltype.key5fname,'restrain-torsion')\n torgen.RemoveStringFromKeyfile(poltype,poltype.tmpkeyfile,'restrain-torsion')\n\n\ndef AddTorsionRestraints(poltype,keyname,torsionrestraints):\n tmpfh=open(keyname,'a')\n for res in torsionrestraints:\n a,b,c,d=res[:]\n tmpfh.write('restrain-torsion %d %d %d %d %f\\n' % (a,b,c,d,poltype.torsionrestraint))\n tmpfh.close()\n\ndef FindTorsionRestraints(poltype,mol):\n torsionrestraints=[]\n atomiter=openbabel.OBMolAtomIter(mol)\n atomnum=0\n for atom in atomiter:\n atomnum+=1\n bondnum=0\n for b in openbabel.OBMolBondIter(mol):\n t2 = b.GetBeginAtom()\n t3 = b.GetEndAtom()\n t2val=t2.GetValence()\n t3val=t3.GetValence()\n if t2val<2 or t3val<2:\n continue \n ringbond=b.IsInRing()\n if ringbond==True:\n continue\n ls=[t2.GetIdx(),t3.GetIdx()]\n if ls in poltype.partialdoublebonds or ls[::-1] in poltype.partialdoublebonds:\n continue\n bondnum+=1\n \n\n if atomnum>=25 or bondnum>=2:\n for b in openbabel.OBMolBondIter(mol):\n isrot=b.IsRotor()\n t2 = b.GetBeginAtom()\n t3 = b.GetEndAtom()\n t2val=t2.GetValence()\n t3val=t3.GetValence()\n if t2val<2 or t3val<2:\n continue \n ringbond=b.IsInRing()\n if ringbond==True:\n continue\n t2idx=t2.GetIdx()\n t3idx=t3.GetIdx()\n t2 = b.GetBeginAtom()\n t3 = b.GetEndAtom()\n t1,t4 = torgen.find_tor_restraint_idx(poltype,mol,t2,t3)\n\n firstangle=mol.GetAngle(t1,t2,t3)\n secondangle=mol.GetAngle(t2,t3,t4)\n atoms=[t1,t2,t3,t4]\n indices=[i.GetIdx() for i in atoms]\n if firstangle<0:\n firstangle=firstangle+360\n if secondangle<0:\n secondangle=secondangle+360\n angletol=2\n if np.abs(180-firstangle)<=3.5 or np.abs(180-secondangle)<=3.5:\n continue\n\n t2idx=t2.GetIdx()\n t3idx=t3.GetIdx()\n babelfirst=[t2idx,t3idx]\n if (babelfirst in poltype.partialdoublebonds or babelfirst[::-1] in poltype.partialdoublebonds):\n continue\n t1idx=t1.GetIdx()\n t4idx=t4.GetIdx()\n torsionrestraints.append([t1idx,t2idx,t3idx,t4idx])\n\n\n return torsionrestraints\n\ndef GeometryOptimization(poltype,mol,loose=False,checkbonds=True,modred=True,bondanglerestraints=None,skipscferror=False,charge=None,skiperrors=False,overridecheckterm=False): # specify charge instead of reading from mol if charge!=None\n if bondanglerestraints!=None: # then vdw opt\n pass\n torsionrestraints=[]\n else: # see if need to restrain torsion in extended conformation\n torsionrestraints=FindTorsionRestraints(poltype,mol)\n if (poltype.use_gaus==True or poltype.use_gausoptonly==True): # try to use gaussian for opt\n term,error=poltype.CheckNormalTermination(poltype.logoptfname,errormessages=None,skiperrors=True)\n if not term or overridecheckterm==True:\n \n poltype.WriteToLog(\"NEED QM Density Matrix: Executing Gaussian Opt and SP\")\n mystruct = load_structfile(poltype,poltype.molstructfname)\n gen_optcomfile(poltype,poltype.comoptfname,poltype.numproc,poltype.maxmem,poltype.maxdisk,poltype.chkoptfname,mol,modred,torsionrestraints)\n cmdstr = 'GAUSS_SCRDIR=' + poltype.scrtmpdirgau + ' ' + poltype.gausexe + \" \" + poltype.comoptfname\n jobtooutputlog={cmdstr:os.getcwd()+r'/'+poltype.logoptfname}\n jobtolog={cmdstr:os.getcwd()+r'/'+poltype.logfname}\n scratchdir=poltype.scrtmpdirgau\n jobtologlistfilepathprefix=os.getcwd()+r'/'+'optimization_jobtolog_'+poltype.molecprefix \n inputfilepath=os.path.join(os.getcwd(),poltype.comoptfname)\n jobtoinputfilepaths={cmdstr:[inputfilepath]}\n jobtooutputfiles={cmdstr:[poltype.logoptfname]}\n jobtoabsolutebinpath={cmdstr:poltype.which(poltype.gausexe)}\n if poltype.checkinputonly==True:\n sys.exit()\n if os.path.isfile(poltype.chkoptfname) and os.path.isfile(poltype.logoptfname):\n os.remove(poltype.logoptfname) # if chk point exists just remove logfile, there could be error in it and we dont want WaitForTermination to catch error before job is resubmitted by daemon \n if poltype.externalapi==None:\n finishedjobs,errorjobs=poltype.CallJobsSeriallyLocalHost(jobtooutputlog,True) # have to skip errors because setting optmaxcycle to low number in gaussian causes it to crash\n else:\n if len(jobtooutputlog.keys())!=0:\n call.CallExternalAPI(poltype,jobtoinputfilepaths,jobtooutputfiles,jobtoabsolutebinpath,scratchdir,jobtologlistfilepathprefix)\n finishedjobs,errorjobs=poltype.WaitForTermination(jobtooutputlog,False)\n\n cmdstr = poltype.formchkexe + \" \" + poltype.chkoptfname\n poltype.call_subsystem([cmdstr],True)\n term,error=poltype.CheckNormalTermination(poltype.logoptfname,errormessages=None,skiperrors=True)\n if error and term==False and skiperrors==False:\n if poltype.fullopt==True:\n poltype.RaiseOutputFileError(poltype.logoptfname) \n optmol = load_structfile(poltype,poltype.logoptfname)\n optmol=rebuild_bonds(poltype,optmol,mol)\n \n \n else:\n\n gen_optcomfile(poltype,poltype.comoptfname,poltype.numproc,poltype.maxmem,poltype.maxdisk,poltype.chkoptfname,mol,modred,torsionrestraints)\n term,error=poltype.CheckNormalTermination(poltype.logoptfname,errormessages=None,skiperrors=True)\n modred=False\n\n inputname,outputname=CreatePsi4OPTInputFile(poltype,poltype.comoptfname,poltype.comoptfname,mol,modred,bondanglerestraints,skipscferror,charge,loose,torsionrestraints)\n if term==False or overridecheckterm==True:\n \n poltype.WriteToLog(\"Calling: \" + \"Psi4 Optimization\")\n cmdstr='psi4 '+inputname+' '+poltype.logoptfname\n jobtooutputlog={cmdstr:os.getcwd()+r'/'+poltype.logoptfname}\n jobtolog={cmdstr:os.getcwd()+r'/'+poltype.logfname}\n scratchdir=poltype.scrtmpdirpsi4\n jobtologlistfilepathprefix=os.getcwd()+r'/'+'optimization_jobtolog_'+poltype.molecprefix\n inputfilepath=os.path.join(os.getcwd(),inputname)\n jobtoinputfilepaths={cmdstr:[inputfilepath]}\n jobtooutputfiles={cmdstr:[poltype.logoptfname]}\n jobtoabsolutebinpath={cmdstr:poltype.which('psi4')}\n\n if poltype.checkinputonly==True:\n sys.exit()\n\n\n if os.path.isfile(poltype.logoptfname):\n os.remove(poltype.logoptfname)\n if poltype.externalapi==None:\n finishedjobs,errorjobs=poltype.CallJobsSeriallyLocalHost(jobtooutputlog,skiperrors)\n else:\n if len(jobtooutputlog.keys())!=0:\n call.CallExternalAPI(poltype,jobtoinputfilepaths,jobtooutputfiles,jobtoabsolutebinpath,scratchdir,jobtologlistfilepathprefix)\n finishedjobs,errorjobs=poltype.WaitForTermination(jobtooutputlog,False)\n\n term,error=poltype.CheckNormalTermination(poltype.logoptfname,None,skiperrors) # now grabs final structure when finished with QM if using Psi4\n if error and term==False and skiperrors==False:\n if poltype.fullopt==True: # if not doing full opt, assume it did input number of cycles and check if structure is reasonable, otherwise if doing full optcheck if error and crash\n poltype.RaiseOutputFileError(poltype.logoptfname) \n GrabFinalXYZStructure(poltype,poltype.logoptfname,poltype.logoptfname.replace('.log','.xyz'),mol)\n optmol = load_structfile(poltype,poltype.logoptfname.replace('.log','.xyz'))\n optmol=rebuild_bonds(poltype,optmol,mol)\n\n GrabFinalXYZStructure(poltype,poltype.logoptfname,poltype.logoptfname.replace('.log','.xyz'),mol)\n return optmol,error,torsionrestraints\n\n\ndef load_structfile(poltype,structfname):\n \"\"\"\n Intent: load 'structfname' as an OBMol structure\n Input:\n structfname: structure file name\n Output:\n tmpmol: OBMol object with information loaded from structfname\n Referenced By: run_gaussian, tor_opt_sp, compute_qm_tor_energy, compute_mm_tor_energy \n Description: -\n \"\"\"\n strctext = os.path.splitext(structfname)[1]\n tmpconv = openbabel.OBConversion()\n if strctext in '.fchk':\n tmpconv.SetInFormat('fchk')\n elif strctext in '.log':\n tmpconv.SetInFormat('g03')\n else:\n inFormat = openbabel.OBConversion.FormatFromExt(structfname)\n tmpconv.SetInFormat(inFormat)\n tmpmol = openbabel.OBMol()\n tmpconv.ReadFile(tmpmol, structfname)\n return tmpmol\n\ndef rebuild_bonds(poltype,newmol, refmol):\n\n for b in openbabel.OBMolBondIter(refmol):\n beg = b.GetBeginAtomIdx()\n end = b.GetEndAtomIdx()\n if not newmol.GetBond(beg,end):\n newmol.AddBond(beg,end, b.GetBO(), b.GetFlags())\n else:\n newb=newmol.GetBond(beg,end)\n bondorder=newb.GetBondOrder()\n newb.SetBondOrder(b.GetBO())\n\n return newmol\n\n\ndef PruneBonds(poltype,mol,bondtopology):\n molindexlist=[]\n atomitermol=openbabel.OBMolAtomIter(mol)\n for atom in atomitermol:\n molindexlist.append(atom.GetIdx())\n molidxtonewmolidx={}\n newmol=openbabel.OBMol() # define new OBMol object for the fragment\n atomlist=[] # list of atom objects from mol object\n newatomlist=[] # list of blank atom objects for fragment mol object\n count=1\n for index in molindexlist: # iterate over indexes in torsion\n atom=mol.GetAtom(index) # grab the atom object via index number\n molidx=atom.GetIdx()\n atomlist.append(atom) # append the atom object to list\n newatom=newmol.NewAtom()\n newatom=newatom.Duplicate(atom)\n newatomlist.append(newatom) # just put into blank atom objects\n molidxtonewmolidx[molidx]=count\n count+=1\n\n bondorderidxdic={} # key=(atom index1 of bond,atom index2 of bond), value=bondorder\n iterbond = openbabel.OBMolBondIter(mol) # iterator for all bond objects in the molecule\n for bond in iterbond:\n a = bond.GetBeginAtom()\n b = bond.GetEndAtom()\n aidx=a.GetIdx()\n bidx=b.GetIdx()\n if aidx in molindexlist and bidx in molindexlist: # check to make sure we want these atoms\n newaidx=molindexlist.index(aidx)+1 # new atom indexes are always in the order of atoms added to molecule via newatomlist above, +1 is because python starts at 0, atom indexes start at 1\n newbidx=molindexlist.index(bidx)+1\n bondorder=bond.GetBondOrder()\n bondorderidxdic[(newaidx,newbidx)]=bondorder\n\n else:\n continue\n\n for key in bondorderidxdic: # add back the bond between atoms in original mol object to the fragment mol object\n key=list(key)\n newaidx=key[0]\n newbidx=key[1]\n bondorder=bondorderidxdic[(newaidx,newbidx)]\n bondset=set([newaidx,newbidx])\n if bondset in bondtopology:\n newmol.AddBond(newaidx,newbidx,bondorder)\n\n return newmol\n","sub_path":"PoltypeModules/optimization.py","file_name":"optimization.py","file_ext":"py","file_size_in_byte":31815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"218862496","text":"import os, sys\nlib_path = os.path.abspath(os.path.join('../..'))\nsys.path.append(lib_path)\n\n\nimport gym\nfrom baselines.ppo2.ppo2 import learn\n\ndef main():\n env = gym.make(\"HopperPyBulletEnv-v0\")\n env.render()\n learn(network = 'mlp',\n env = env,\n total_timesteps = 1e6)\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"baselines/ppo2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"643108789","text":"# Q1\ndef has_cycle_rec(v, E, visited_dic):\n visited_dic[v] = True\n\n for e in E:\n if e[0] == v:\n if visited_dic[e[1]] == False:\n if(has_cycle_rec(e[1], E, visited_dic)):\n return True\n else:\n return True\n\n return False\n\n\ndef IS_DAG(V, E):\n visited_dic = {}\n\n for v in V:\n for v in V:\n visited_dic[v] = False\n if visited_dic[v] == False: # Don't recur for u if it is already visited\n if(has_cycle_rec(v, E, visited_dic)) == True:\n return False\n\n return True\n\n# Q2\n\n\ndef is_sink(v, E, ignore_lst):\n for e in E:\n if e[0] == v and e not in ignore_lst:\n return False\n return True\n\n\ndef delete_vertex(v, e_lst, v_lst, ignore_lst):\n for e in e_lst:\n if v == e[1] and e not in ignore_lst:\n ignore_lst.append(e)\n v_lst.remove(v)\n\n\ndef t_sort_rec(v_lst, e_lst, lst, ignore_lst):\n if len(v_lst) == 0:\n return\n else:\n for v in v_lst:\n if is_sink(v, e_lst, ignore_lst):\n lst.append(v)\n delete_vertex(v, e_lst, v_lst, ignore_lst)\n break\n t_sort_rec(v_lst, e_lst, lst, ignore_lst)\n\n\ndef T_SORT(V, E):\n if not IS_DAG(V, E):\n return -1\n else:\n lst = []\n e_lst = list(E)\n v_lst = list(V)\n t_sort_rec(v_lst, e_lst, lst, [])\n return lst[::-1]\n\n# Q3\n\n\ndef find_nieghbours(v, e_lst):\n lst = []\n for e in e_lst:\n if e[1] == v:\n lst.append(e[0])\n return lst\n\n\ndef long_path_helper(v_lst, e_lst, ts_dic, degree_dic):\n for v in v_lst:\n neighbours_lst = find_nieghbours(v, e_lst)\n neighbours_degree_lst = []\n for n in neighbours_lst:\n neighbours_degree_lst.append(ts_dic[n])\n degree_dic[v] = 1 + max(neighbours_degree_lst, default=0)\n\n\ndef Max_Delay(V, E):\n if not IS_DAG(V, E):\n return -1\n else:\n TS = T_SORT(V, E)\n ts_dic = {}\n for i in range(len(TS)-1):\n ts_dic[TS[i]] = i\n degree_dic = {}\n long_path_helper(list(V), list(E), ts_dic, degree_dic)\n key_max = max(degree_dic.keys(), key=(lambda k: degree_dic[k]))\n key_min = min(degree_dic.keys(), key=(lambda k: degree_dic[k]))\n return(key_min, key_max)\n\n# Q4\n\n\nV = {'a', 'b', 'f', 'p', 'q'}\nE = {('a', 'b'), ('f', 'b'), ('p', 'b'), ('b', 'q')}\n\nprint(Max_Delay(V, E))\n","sub_path":"Project A.py","file_name":"Project A.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"373357401","text":"import re\ndef main():\n file = open(\"attractor_231.txt\").read().split('\\n')\n nodes = open(\"rons_8\").read().split('\\n')\n\n for node in nodes:\n for line in file:\n row = line.split(' ')\n if row[0] == node:\n print(row[1])\n\nmain()\n","sub_path":"_site/_projects/project2/OLD/NetworkAnalysis 1/SFA/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"558886760","text":"#!/usr/bin/env python\n#\n# requires python version 3 or greater.\n#\n# @copyright 2016 Nicholas Hinsch, based on work by Arun-UB https://github.com/Arun-UB\n#\n# @license MIT\n#\n# This script supports extracting multiple email addresses in mailto links from multiple webpages on any number of supplied domains.\n# The page crawler is somewhat intelligent (it will skip assets like images, videos and documents as well as skipping offsite links.\n# It also normalizes links that don't have the FQDN in the href.\n#\n# This doesn't parse javascript, so obfuscated emails are not detected. If I get any more spare time, I will see about adding that support.\n# You can also set a crawl rate (delay) and maximum number of pages.\n#\n# Duplicate emails per domain are also stripped out. You're welcome :p\n# sample use:\n# python3 find_email_addresses.py --domains www.rapidtables.com/web/html/mailto.htm https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Email_links --delay 1 --maxpages 2 --outfile emails.txt\n#\n# Crawling www.rapidtables.com for email addresses.\n# - Found email addresses:\n# -- name1@rapidtables.com\n# -- name2@rapidtables.com\n# -- name@rapidtables.com\n# -- name3@rapidtables.com\n#\n# Crawling developer.mozilla.org for email addresses.\n# - Found email addresses:\n# -- nowhere@mozilla.org\n# -- nobody@mozilla.org\n#\n# If you run into problems, enable debug mode by supplying --verbose on the command line\n#\n\nfrom bs4 import BeautifulSoup\nimport html\nimport urllib\nimport argparse\nimport re\nimport queue\nimport time\nimport random\n\nclass Crawler(object):\n def __init__(self, url, delay, maxpages, outfile, verbose):\n\n self.delay = delay\n self.maxpages = maxpages\n self.verbose = verbose\n self.outfile = outfile\n\n # normalize the supplied url protocol\n if not re.match('https?://|www\\\\\\.', url):\n url = 'http://' + url\n\n # Strip off query string params on url\n self.url = urllib.parse.urljoin(url, urllib.parse.urlparse(url).path)\n\n # extract the domain name from the url\n self.domainName = urllib.parse.urlparse(url).netloc\n\n self.emails = []\n\n def get_emails(self):\n\n addresses = list(set(self.emails))\n\n if self.outfile:\n with open(self.outfile, \"a\") as text_file:\n for i in addresses:\n print(i, file=text_file)\n\n return addresses\n\n def extract_emails(self, page):\n for link in page.select('a[href^=mailto]'):\n\n # split apart multi-recipient mailto links\n emailaddresses = link.get('href')[7:].split(',')\n\n for addy in emailaddresses:\n #extract recipients, cc's and bcc's\n\n all_recipients = []\n\n # defeat some basic obfuscation techniques (html entities, urlencode)\n if '?' not in addy:\n if '#&' or '%' in addy:\n # obfuscated email address\n deobfus = html.unescape(addy)\n if '@' in deobfus:\n all_recipients.append(deobfus)\n\n elif '?' in addy:\n # multiple email addresses in this mailto\n pattern = re.compile(\"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+\")\n all_recipients = pattern.findall(addy)\n\n else:\n # just a standard email address, plain and simple\n all_recipients.append(addy)\n\n for i in all_recipients:\n self.emails.append(i)\n\n\n def get_links(self, page):\n links = []\n\n for link in page.find_all('a'):\n if link.get('href') is None:\n self.debug('skipping homepage link!')\n\n elif link.get('href').startswith('#'):\n self.debug('skipping anchor!')\n\n elif link.get('href').startswith('//'):\n self.debug('skipping external or protocol relative link!')\n\n elif link.get('href').startswith('/'):\n link = urllib.parse.urljoin(self.url, link.get('href'))\n links.append(link)\n\n elif self.domainName not in link.get('href'):\n self.debug('skipping external link!')\n\n else:\n link = urllib.parse.urljoin(self.url, link.get('href'))\n links.append(link)\n\n self.debug('found the following url links:')\n self.debug(links)\n\n return list(links)\n\n def crawl(self):\n pagecount = 0\n excludedExtensions = (\n '.jpg', '.jpeg', '.png', '.gif',\n '.tif', '.doc', '.docx', '.xls',\n '.xlsx', '.pdf', '.log', '.msg',\n '.odt', '.pages', '.rtf', '.tex',\n '.wpd', '.wps', '.csv', '.ppt',\n '.pptx', '.zip', '.tar', '.xml',\n '.bz', '.tgz', '.tar.gz', '.vcf',\n '.aif', '.m3u', '.m4a', '.mid',\n '.mp3', '.mpa', '.wav', '.wma',\n '.avi', '.flv', '.mpg', '.mov',\n '.m4v', '.mp4', '.rm', '.swf',\n '.wmv', '.obs', '.3dm', '.3ds',\n '.max', '.bmp', '.psd', '.ai',\n '.tiff', '.eps', '.ps', '.svg',\n '.indd', '.pct', '.xlr', '.db',\n '.sql', '.dbf', '.pdb', '.app',\n '.bat', '.jar', '.wsf', '.rom',\n '.sav', '.dwg', '.dxf', '.kmz',\n '.ini', '.cfg', '.7z', '.cbr',\n '.rar', '.pkg', '.sitx', '.zipx',\n '.bin', '.cue', '.dmg', '.iso',\n '.mdf', '.toast', '.vcd', '.c',\n '.py', '.cpp', '.class', '.java',\n '.pl', '.sh', '.vb', '.swift',\n '.bak', '.tmp', '.ics', '.exe',\n '.msi', '.torrent', '.lua', '.deb',\n '.rpm', '.hqx', '.uue', '.sys'\n )\n tocrawl = queue.Queue()\n crawled = []\n tocrawl.put(self.url)\n\n #setup some headers to fool sites that try to prevent scraping :p\n user_agents = [\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0',\n 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0',\n 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:41.0) Gecko/20100101 Firefox/41.0',\n 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:41.0) Gecko/20100101 Firefox/41.0',\n ]\n\n user_agent = random.choice(user_agents)\n\n headers = {\n 'User-Agent': user_agent,\n 'Referer': self.url\n }\n\n while tocrawl.qsize():\n\n if pagecount == self.maxpages:\n break\n\n link = str(tocrawl.get())\n\n if link.lower().endswith(excludedExtensions):\n self.debug('Skipping : ' + link + ' because it\\'s an asset, not a page!')\n\n elif link not in crawled:\n self.debug('Found a new page to crawl: ' + link)\n\n # skip dead links and pages we've already crawled\n try:\n req = urllib.request.Request(link, None, headers)\n page_content = urllib.request.urlopen(req)\n page = BeautifulSoup(page_content, 'html.parser')\n\n crawled.append(link)\n\n # queue up new links found on this page\n for l in self.get_links(page):\n if l not in crawled:\n tocrawl.put(l)\n self.debug('-- Adding link: ' + l + ' found on page')\n\n self.extract_emails(page)\n\n pagecount += 1\n\n except urllib.error.HTTPError as e:\n if e.code == 403:\n self.debug('Skipping page: ' + link + ' because the crawler was forbidden access (403)!')\n elif e.code == 404:\n self.debug('Skipping page: ' + link + ' because the link is dead (404)!')\n else:\n self.debug('Skipping page: ' + link + 'because something else went wrong. HTTP error code: ' + e.code)\n\n except urllib.error.URLError as e:\n self.debug('Skipping unknown URL type!')\n\n crawled.append(link)\n\n # wait for the specified amount of time between page requests...be nice to webservers!\n time.sleep(self.delay)\n\n else:\n self.debug('Skipping page: ' + link + ' because we\\'ve already crawled this page!')\n\n # Log all the things!\n def debug(self, msg, prefix='DEBUG'):\n if self.verbose:\n print(prefix + ' ' + str(msg))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Enter a URL\")\n\n parser.add_argument(\n '--domains', nargs='+',\n help='Space-separated list of domains to crawl'\n )\n\n parser.add_argument(\n '--delay', nargs='?',\n default=5,\n help='The delay between page requests in seconds (default is 5 seconds)'\n )\n\n parser.add_argument(\n '--maxpages', nargs='?',\n default=100,\n help='The maximum number of pages to crawl per domain (default is 100 pages)'\n )\n\n parser.add_argument(\n '--verbose',\n action='store_true',\n help='Enable verbose mode. This prints a fuck-load of debug info to stdout (your terminal).'\n )\n\n parser.add_argument(\n '--outfile',\n help='Save scraped email addresses to a txt file, newline delimited.'\n )\n\n args = parser.parse_args()\n\n domains = args.domains\n delay = int(args.delay)\n maxpages = int(args.maxpages)\n verbose = args.verbose\n outfile = args.outfile\n\n for domain in domains:\n\n c = Crawler(str(domain).strip(), delay, maxpages, outfile, verbose)\n\n print(\"\\nCrawling \" + c.domainName + \" for email addresses.\")\n c.crawl()\n\n print(\"- Found email addresses:\")\n for email in c.get_emails():\n print('-- ' + email)\n","sub_path":"find_email_addresses.py","file_name":"find_email_addresses.py","file_ext":"py","file_size_in_byte":10696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"519003966","text":"from DQN import DQN\nimport torch\nimport numpy as np \nfrom game import Game\n\nagent = DQN()\nrounds = 20000\n\nfor i in range(rounds):\n g = Game(score_to_win=1024)\n state = g.board\n while True:\n action = agent.consult(state)\n g.move(action)\n statep = g.board\n reward = g.score\n agent.store(state, action, reward, statep)\n state = statep\n\n if net.memorycnt == 0:\n net.learn()\n\n if g.end:\n break\n agent.save(path='../model/', name='CNN3.pkl')","sub_path":"game2048/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"235906896","text":"\n\nclass Campaigns:\n def __init__(self, campaign_file):\n self.keywords = {}\n self.campaigns = {}\n self.parse(campaign_file)\n\n def parse(self, campaign_file):\n contents = open(campaign_file, 'r')\n url = None\n line = contents.readline()\n while line:\n line = line.strip()\n if not url:\n url = line\n self.campaigns[url] = {}\n elif line == '':\n url = None\n else:\n self.campaigns[url][line] = None\n if self.keywords.has_key(line):\n self.keywords[line].append(url)\n else:\n self.keywords[line] = [url]\n\n line = contents.readline()\n\n def set_rank(self, url, keyword, rank):\n try:\n if not self.campaigns[url][keyword]:\n self.campaigns[url][keyword] = rank\n except:\n pass\n\n def get_campaigns(self):\n return self.campaigns\n\n def get_keywords(self):\n return self.keywords\n","sub_path":"campaigns.py","file_name":"campaigns.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"152281552","text":"\"\"\"\nProvides a simple wrapper for the 2-halo term function, which is written in \nfortran (as it is one of the most compute-intensive parts of the calculation). \n\"\"\"\nfrom twohalo import twohalo_calc as thalo\nimport numpy as np\n\ndef twohalo_wrapper(excl, sdb, m, bias, ntot, dndm, lnk, dmpower, u, r, dmcorr,\n nbar, dhalo, rhob, ncores):\n \"\"\"\n A simple wrapper for the 2-halo term calculation.\n \n Parameters\n ----------\n excl : str\n String identifier for halo-exclusion method (None,schneider,sphere,\n ng_matched,ellipsoid)\n \n sdb : bool\n Whether to use scale-dependent bias or not. \n \n m : array\n Array of masses\n \n bias : array\n The scale-independent bias function\n \n ntot : array\n The total average galaxies per halo of mass m\n \n dndm : array\n The mass function\n \n lnk : array\n Logarithmic wavenumbers\n \n dmpower : array\n Matter power spectrum\n \n u : (nk,nm)-array\n The normalised fourier transform of the density profile as a function \n of m and k.\n \n r : array\n The scales at which to evaluate the 2-halo term\n \n dmcorr : array\n The matter correlation function\n \n nbar : float\n Mean galaxy number density\n \n dhalo : float\n Definition of a halo -- overdensity with respect to background.\n \n rhob : float\n The background density\n \n ncores : int\n The number of cores to use in the calculation. NOTE: not much of a\n speedup is gained, if any.\n \"\"\"\n u = np.asfortranarray(u.T)\n\n exc_type = {\"None\":1,\n \"schneider\":2,\n \"sphere\":3,\n \"ng_matched\":4,\n \"ellipsoid\":5}\n\n corr = thalo.twohalo(m, bias, ntot, dndm, lnk, dmpower, u, r, dmcorr, nbar,\n dhalo, rhob, exc_type[excl], sdb, ncores)\n\n return corr\n\ndef dblsimps(X, dx, dy):\n return thalo.dblsimps(X, dx, dy)\n","sub_path":"halomod/fort/twohalo_wrapper.py","file_name":"twohalo_wrapper.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"400774672","text":"__author__ = 'guopei'\nimport random\nimport math\nimport matplotlib.pyplot as plt\nfrom scipy.special import beta as beta_fun\nimport numpy as np\n\nclass Node(object):\n def __init__(self, init_value, candsd, name, observed = False):\n self.value = float(init_value)\n self.candsd = float(candsd)\n self.name = name\n self.sample_values = [float(init_value)]\n self.observed = observed\n self.children = []\n\n def sample(self):\n last = self.value\n candsd = self.candsd\n cand = random.gauss(last, candsd)\n\n cand_prob = self.get_log_posterior_prob(cand)\n current_prob = self.get_log_posterior_prob(last)\n\n rand = math.log(random.random())\n\n if rand < cand_prob - current_prob:\n self.value = cand\n\n self.sample_values.append(self.value)\n\n def get_log_posterior_prob(self, eval_value):\n\n prob = self.get_log_likelihood_prob(eval_value)\n\n # temporarily set node value as value\n store_value = self.value\n self.value = eval_value\n for chld in self.children:\n prob += chld.get_log_likelihood_prob(chld.value)\n\n # then restore it.\n self.value = store_value\n\n return prob\n\n def get_log_likelihood_prob(self):\n pass\n\n def draw_mixing(self, burn_in = 0):\n fig = plt.figure()\n fig.suptitle('{} mixing'.format(self.name), fontsize=14, fontweight='bold')\n\n data = self.sample_values[burn_in:]\n plt.plot(data)\n\n plt.savefig('{}_new_mixing.png'.format(self.name))\n\n def plot_distribution(self, burn_in = 0):\n fig = plt.figure()\n fig.suptitle('{} distribution'.format(self.name), fontsize=14, fontweight='bold')\n\n data = self.sample_values[burn_in:]\n plt.hist(data, bins=100, normed=True, color=\"Green\")\n plt.xlim(0,1)\n\n #plt.show()\n plt.savefig('{}_distributionmi.png'.format(self.name))\n\n\nclass NormalNode(Node):\n def __init__(self, init_value, mean, var, candsd, name, observed = False):\n super(NormalNode, self).__init__(init_value, candsd, name, observed)\n\n # if mean is a value, then mean() method return mean\n if type(mean) == float or type(mean) == int:\n self.mean = lambda : float(mean)\n # if mean is a node class, then mean() return mean.value\n else:\n self.mean = lambda : mean.value\n mean.children.append(self)\n\n # same thing with mean\n if type(var) == float or type(var) == int:\n self.var = lambda : float(var)\n else:\n self.var = lambda : var.value\n var.children.append(self)\n\n def get_log_likelihood_prob(self, x):\n # find current value of mean and var\n miu = self.mean()\n sig2 = self.var()\n\n if sig2 <= 0:\n return -float('Inf')\n else:\n return - 0.5 * math.log(sig2) - (x - miu) ** 2 / (2 * sig2)\n\nclass InvGammaNode(Node):\n def __init__(self, init_value, alpha, beta, candsd, name, observed = False):\n super(InvGammaNode, self).__init__(init_value, candsd, name, observed)\n\n if type(alpha) == float or type(alpha) == int:\n self.alpha = lambda : float(alpha)\n else:\n self.alpha = lambda : alpha.value\n alpha.children.append(self)\n\n if type(beta) == float or type(beta) == int:\n self.beta = lambda : float(beta)\n else:\n self.beta = lambda : beta.value\n beta.children.append(self)\n\n def sample(self):\n last = self.value\n candsd = self.candsd\n cand = random.gauss(last, candsd)\n if cand <= 0:\n self.sample_values.append(self.value)\n return\n\n cand_prob = self.get_log_posterior_prob(cand)\n current_prob = self.get_log_posterior_prob(last)\n\n rand = math.log(random.random())\n\n if rand < cand_prob - current_prob:\n self.value = cand\n\n self.sample_values.append(self.value)\n\n def get_log_likelihood_prob(self, x):\n\n # find current value of mean and var\n alpha = self.alpha()\n beta = self.beta()\n\n if alpha <= 0 or beta <= 0:\n return -float('Inf')\n else:\n return alpha * math.log(beta) - math.log(math.gamma(alpha)) - (alpha + 1) * math.log(x) - (beta / x)\n\nclass BetaNode(Node):\n\n def __init__(self, init_value, alpha, beta, candsd, name, observed = False):\n super(BetaNode, self).__init__(init_value, candsd, name, observed)\n\n if type(alpha) == float or type(alpha) == int:\n self.alpha = lambda : float(alpha)\n else:\n self.alpha = lambda : alpha.value\n alpha.children.append(self)\n\n if type(beta) == float or type(beta) == int:\n self.beta = lambda : float(beta)\n else:\n self.beta = lambda : beta.value\n beta.children.append(self)\n\n def sample(self):\n last = self.value\n candsd = self.candsd\n cand = random.gauss(last, candsd)\n if cand <= 0 or cand >= 1:\n self.sample_values.append(self.value)\n return\n\n #print(last, cand)\n\n cand_prob = self.get_log_posterior_prob(cand)\n current_prob = self.get_log_posterior_prob(last)\n\n rand = math.log(random.random())\n\n if rand < cand_prob - current_prob:\n self.value = cand\n\n\n self.sample_values.append(self.value)\n\n def get_log_likelihood_prob(self, x):\n\n try:\n alpha = self.alpha()\n beta = self.beta()\n\n if alpha <= 0 or beta <= 0:\n return -float('Inf')\n else:\n return (alpha - 1) * math.log(x) + (beta - 1) * math.log(1 - x)\n except (ValueError, OverflowError):\n print(\"Beta Node too big\")\n return -float(\"inf\")\n except (OverflowError):\n return 0\n\nclass BernoulliNode(Node):\n def __init__(self, init_value, probability, candsd, name, observed = False):\n super(BernoulliNode, self).__init__(init_value, candsd, name, observed)\n self.init_value = init_value\n\n # if mean is a value, then mean() method return mean\n if type(probability) == float or type(probability) == int:\n self.probability = lambda : float(probability)\n # if mean is a node class, then mean() return mean.value\n else:\n self.probability = lambda : probability.value\n probability.children.append(self)\n\n def sample(self):\n prob = self.probability()\n rand = random.random()\n if rand < prob:\n self.value = True\n self.sample_values.append(self.value)\n else:\n self.value = False\n self.sample_values.append(self.value)\n\n def get_log_likelihood_prob(self, x):\n prob = self.probability()\n\n if prob < 0 or prob > 1:\n return -float(\"Inf\")\n\n if self.value == True:\n return math.log(prob)\n else:\n return math.log(1-prob)\n\nclass GammaNode(Node):\n def __init__(self, init_value, alpha, beta, candsd, name, observed = False):\n super(GammaNode, self).__init__(init_value, candsd, name, observed)\n\n if type(alpha) == float or type(alpha) == int:\n self.alpha = lambda : float(alpha)\n else :\n ## Shameful cheating here!!!\n ## It is mission impossible to let A**pi be an object with\n ## attribute `value` and let A add B as child at the same time.\n self.alpha = lambda : alpha.value ** math.pi\n alpha.children.append(self)\n\n if type(beta) == float or type(beta) == int:\n self.beta = lambda : float(beta)\n else:\n self.beta = lambda : beta.value\n beta.children.append(self)\n\n def sample(self):\n last = self.value\n candsd = self.candsd\n cand = random.gauss(last, candsd)\n if cand <= 0:\n self.sample_values.append(self.value)\n return\n\n cand_prob = self.get_log_posterior_prob(cand)\n current_prob = self.get_log_posterior_prob(last)\n\n rand = math.log(random.random())\n\n if rand < cand_prob - current_prob:\n self.value = cand\n\n self.sample_values.append(self.value)\n\n def get_log_likelihood_prob(self, x):\n\n try:\n\n alpha = self.alpha()\n beta = self.beta()\n\n if alpha <= 0 or beta <= 0:\n return -float('Inf')\n else:\n return alpha * math.log(beta) - math.log(math.gamma(alpha)) + (alpha - 1) * math.log(x) - (beta * x)\n\n except (ValueError, OverflowError):\n return -float(\"inf\")\n except (OverflowError):\n return 0\n\nclass PoissonNode(Node):\n def __init__(self, init_value, rate, candsd, name, observed = False):\n super(PoissonNode, self).__init__(round(init_value), candsd, name, observed)\n\n if type(rate) == float or type(rate) == int:\n self.rate = lambda : float(rate)\n else:\n self.rate = lambda : rate.value\n rate.children.append(self)\n\n def sample(self):\n last = self.value\n candsd = self.candsd\n cand = round(random.gauss(last, candsd))\n if cand < 0:\n self.sample_values.append(self.value)\n return\n\n cand_prob = self.get_log_posterior_prob(cand)\n current_prob = self.get_log_posterior_prob(last)\n\n rand = math.log(random.random())\n\n if rand < cand_prob - current_prob:\n self.value = cand\n\n self.sample_values.append(self.value)\n\n def get_log_likelihood_prob(self, x):\n\n # find current value of mean and var\n rate = self.rate()\n\n if rate <= 0:\n return -float(\"Inf\")\n else:\n return x * math.log(rate) - rate - math.log(math.factorial(int(x)))\n\n\nclass SuperBernoulliNode(Node):\n def __init__(self, init_value, name, parent_prob, candsd=0, observed=False):\n super(SuperBernoulliNode, self).__init__(init_value, candsd, name, observed)\n\n self.allprob = []\n [parent_nodes, probs] = parent_prob\n self.parents = parent_nodes\n\n for node in parent_nodes:\n node.children.append(self)\n\n for prob in probs:\n if type(prob) == float:\n self.allprob.append(lambda prob=prob: float(prob))\n else:\n self.allprob.append(lambda prob=prob: prob.value)\n prob.children.append(self)\n\n\n def sample(self):\n\n prob = 0\n #store_value = self.value\n #self.value = True\n prob += self.get_log_likelihood_prob(True)\n #for chld in self.children:\n # prob += chld.get_log_likelihood_prob(chld.value)\n\n #self.value = store_value\n\n rand = math.log(random.random())\n\n #print self.name, prob, rand,\n\n if rand < prob:\n self.value = True\n self.sample_values.append(self.value)\n else:\n self.value = False\n self.sample_values.append(self.value)\n\n def get_log_likelihood_prob(self, x):\n if type(x) == bool or type(x) == float:\n ind = 0\n total = len(self.parents)\n for i in xrange(total):\n ind += 0 if self.parents[i].value else 2 ** (total - i - 1)\n\n prob = self.allprob[ind]()\n\n if prob < 0 or prob > 1:\n return -float(\"Inf\")\n\n if x == True:\n return math.log(prob)\n else:\n return math.log(1-prob)\n elif type(x) == list:\n value_num = len(x)\n prnt_num = len(self.parents)\n nk = [[np.array([0, 0])]] * (2**prnt_num)\n prob = 0\n for num in xrange(value_num):\n\n if self.value[num] == None:\n continue\n\n ind = 0\n parent_good = True\n for i in xrange(prnt_num):\n if self.parents[i].value[num] == None:\n parent_good = False\n break\n ind += 0 if self.parents[i].value[num] else 2 ** (prnt_num - i - 1)\n\n #print(self.name, ind, num, nk)\n if parent_good:\n nk[ind] += np.array([1, x[num]])\n\n\n for ind in xrange(len(nk)):\n p = self.allprob[ind]()\n prob += nk[ind][0][1] * math.log(p) + (nk[ind][0][0] - nk[ind][0][1]) * math.log(1-p)\n\n return prob\n\n\n\n\n","sub_path":"Node.py","file_name":"Node.py","file_ext":"py","file_size_in_byte":12639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"79165337","text":"\"\"\"\n Copyright 2019 Manuel Olguín\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 json\nimport os\nfrom typing import Dict, List, Tuple\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import pylab, gridspec\n\nfrom util import *\n\n# n_runs = 25\n\nPLOT_DIM = (4.5, 3)\nSEPARATE_LEGEND = False\nPLOT_TITLES = False\n# PLOT_DIM = (8, 6)\nFEEDBACK_TIME_RANGE = (-10, 600)\nNO_FEEDBACK_TIME_RANGE = (-2, 100)\n\nFEEDBACK_BIN_RANGE = (200, 1200)\nNO_FEEDBACK_BIN_RANGE = (10, 300)\n\n\n# HIST_FEEDBACK_YRANGE = (0, 0.025)\n# HIST_NO_FEEDBACK_YRANGE = (0, 0.12)\n\ndef set_box_color(bp, color):\n plt.setp(bp['boxes'], color=color)\n plt.setp(bp['whiskers'], color=color)\n plt.setp(bp['caps'], color=color)\n plt.setp(bp['medians'], color=color)\n\n\ndef autolabel(ax: plt.Axes, rects: List[plt.Rectangle],\n y_range: Tuple[float, float],\n bottom: bool = False,\n color: str = 'black') -> None:\n \"\"\"\n Attach a text label above each bar displaying its height\n \"\"\"\n for rect in rects:\n height = rect.get_height()\n x_pos = rect.get_x() + rect.get_width() / 2.0\n\n if not bottom:\n y_pos = 0.2 * (max(*y_range) - min(*y_range))\n ax.text(x_pos, y_pos,\n '{:02.2f}'.format(height),\n ha='center', va='bottom', weight='bold',\n rotation='vertical',\n color=color)\n else:\n y_pos = rect.get_y()\n ax.text(x_pos, y_pos,\n '{:02.2f}'.format(height),\n ha='center', va='top', weight='bold',\n rotation='vertical',\n color=color)\n\n\ndef plot_box_fb_vs_nfb(experiments: Dict) -> None:\n root_dir = os.getcwd()\n ticks = []\n rtts_feedback = []\n rtts_nofeedback = []\n\n for exp_name, exp_dir in experiments.items():\n os.chdir(root_dir + '/' + exp_dir)\n data = pd.read_csv('total_frame_stats.csv')\n run_data = pd.read_csv('total_run_stats.csv')\n os.chdir(root_dir)\n\n data = filter_runs(data, run_data)\n data_fb = calculate_derived_metrics(data, feedback=True)\n data_nofb = calculate_derived_metrics(data, feedback=False)\n\n rtt_fb = data_fb['client_recv'] - data_fb['client_send']\n rtt_nofb = data_nofb['client_recv'] - data_nofb['client_send']\n\n rtts_feedback.append(rtt_fb)\n rtts_nofeedback.append(rtt_nofb)\n\n ticks.append(exp_name)\n\n fig, ax = plt.subplots()\n num_exps = len(ticks)\n bp_nofb = ax.boxplot(rtts_nofeedback,\n positions=np.array(range(num_exps)) * 2.0 - 0.2,\n sym='', widths=0.4)\n bp_fb = ax.boxplot(rtts_feedback,\n positions=np.array(range(num_exps)) * 2.0 + 0.2,\n sym='', widths=0.4)\n\n # colors here\n fb_color = 'C0'\n nofb_color = 'C1'\n\n set_box_color(bp_fb, fb_color)\n set_box_color(bp_nofb, nofb_color)\n\n # legend\n p2 = ax.plot([], c=nofb_color, label='RTT - No Transition', marker='s',\n linestyle='',\n markersize=10)\n p1 = ax.plot([], c=fb_color, label='RTT - State Transition', marker='s',\n linestyle='',\n markersize=10)\n\n ax.legend()\n\n # if SEPARATE_LEGEND:\n # dim_x, dim_y = PLOT_DIM\n # figlegend = pylab.figure(figsize=(dim_x * 2.0, .3))\n # plots = (*p1, *p2, *p3)\n # figlegend.legend(plots,\n # ('Uplink Time', 'Processing Time', 'Downlink Time'),\n # loc='center',\n # mode='expand',\n # ncol=3)\n # figlegend.tight_layout()\n # figlegend.savefig('times_box_legend.pdf', transparent=True,\n # bbox_inches='tight', pad_inches=0)\n # figlegend.show()\n # else:\n # ax.legend()\n\n ax.set_xticks(range(0, len(ticks) * 2, 2))\n ax.set_xticklabels(ticks)\n ax.set_xlim(-1, (len(ticks) * 2) - 1)\n ax.tick_params(labeltop=False,\n labelright=True,\n bottom=True,\n left=True,\n right=True)\n ax.set_ylabel('Time [ms]')\n ax.grid(True, which='major', axis='y', linestyle='--', alpha=0.8)\n\n fig.set_size_inches(*PLOT_DIM)\n plt.tight_layout()\n fig.savefig('rtt_fb_vs_nofb.pdf', bbox_inches='tight')\n\n plt.show()\n\n\ndef plot_time_taskstep(experiment: str) -> None:\n # get all frame data\n root_dir = os.getcwd()\n os.chdir(root_dir + '/' + experiment)\n data = pd.read_csv('total_frame_stats.csv')\n run_data = pd.read_csv('total_run_stats.csv')\n os.chdir(root_dir)\n\n data = calculate_derived_metrics(data, True)\n data = filter_runs(data, run_data)\n\n # separate into steps\n states = list(range(-1, data['state_index'].max() + 1, 1))\n\n rtts = [[p + u + d for p, u, d in zip(\n data.loc[data['state_index'] == state]['processing'],\n data.loc[data['state_index'] == state]['uplink'],\n data.loc[data['state_index'] == state]['downlink']\n )] for state in states]\n\n # fig, (ax_top, ax_bot) = plt.subplots(2, 1, sharex=True)\n fig = plt.figure()\n gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1])\n ax_top = plt.subplot(gs[0])\n ax_bot = plt.subplot(gs[1])\n\n color = 'C0'\n bp_top = ax_top.boxplot(rtts, positions=states, showfliers=False)\n bp_bot = ax_bot.boxplot(rtts, positions=states, showfliers=False)\n\n p = ax_bot.plot([], c=color,\n label='RTT',\n marker='s',\n linestyle='',\n markersize=10)\n set_box_color(bp_top, color)\n set_box_color(bp_bot, color)\n\n # set zoom\n ax_top.set_ylim(200, 350)\n ax_bot.set_ylim(0, 50)\n\n # hide spines\n ax_top.spines['bottom'].set_visible(False)\n ax_bot.spines['top'].set_visible(False)\n ax_top.tick_params(labeltop=False,\n labelbottom=False,\n labelright=True,\n top=False,\n bottom=False,\n left=True,\n right=True)\n ax_bot.tick_params(labeltop=False,\n labelbottom=True,\n labelright=True,\n top=False,\n bottom=True,\n left=True,\n right=True)\n\n ax_bot.legend(loc='lower right')\n\n def _state2tick(idx):\n if idx < 0:\n return 'Error'\n elif idx == 0:\n return 'Start'\n elif idx == max(states):\n return '{} to End'.format(idx - 1)\n else:\n return '{} to {}'.format(idx - 1, idx)\n\n ticks = list(map(_state2tick, states))\n ax_bot.set_xticklabels(ticks, rotation=45, ha='right')\n\n ax_bot.tick_params(labeltop=False, labelright=True)\n ax_top.set_ylabel('Time [ms]')\n ax_top.grid(True, which='major', axis='y', linestyle='--', alpha=0.8)\n ax_bot.grid(True, which='major', axis='y', linestyle='--', alpha=0.8)\n\n # add diagonal lines for break in Y axis\n d = .02 # how big to make the diagonal lines in axes coordinates\n # arguments to pass to plot, just so we don't keep repeating them\n kwargs = dict(transform=ax_top.transAxes, color='k', clip_on=False)\n ax_top.plot((-d, +d), (-d, +d), **kwargs) # top-left diagonal\n ax_top.plot((1 - d, 1 + d), (-d, +d), **kwargs) # top-right diagonal\n\n kwargs.update(transform=ax_bot.transAxes) # switch to the bottom axes\n ax_bot.plot((-d, +d), (1 - (3 * d), 1 + (3 * d)), **kwargs) # bottom-left\n # diagonal\n ax_bot.plot((1 - d, 1 + d), (1 - (3 * d), 1 + (3 * d)),\n **kwargs) # bottom-right\n # diagonal\n\n fig.set_size_inches(*PLOT_DIM)\n plt.tight_layout()\n fig.savefig('times_box_taskstep.pdf', bbox_inches='tight')\n\n plt.show()\n\n\ndef plot_time_box(experiments: Dict, feedback: bool) -> None:\n root_dir = os.getcwd()\n # results = {}\n ticks = []\n processing_times = []\n uplink_times = []\n downlink_times = []\n\n for exp_name, exp_dir in experiments.items():\n os.chdir(root_dir + '/' + exp_dir)\n data = pd.read_csv('total_frame_stats.csv')\n run_data = pd.read_csv('total_run_stats.csv')\n os.chdir(root_dir)\n\n data = calculate_derived_metrics(data, feedback)\n data = filter_runs(data, run_data)\n\n # results[exp_name] = data\n ticks.append(exp_name)\n processing_times.append(data['processing'])\n uplink_times.append(data['uplink'])\n downlink_times.append(data['downlink'])\n\n fig, ax = plt.subplots()\n num_exps = len(ticks)\n bp_proc = ax.boxplot(processing_times,\n positions=np.array(range(num_exps)) * 3.0,\n sym='', widths=0.4)\n bp_up = ax.boxplot(uplink_times,\n positions=np.array(range(num_exps)) * 3.0 - 0.5,\n sym='', widths=0.4)\n bp_down = ax.boxplot(downlink_times,\n positions=np.array(range(num_exps)) * 3.0 + 0.5,\n sym='', widths=0.4)\n\n # colors here\n set_box_color(bp_up, 'C0')\n set_box_color(bp_proc, 'C1')\n set_box_color(bp_down, 'C2')\n\n # legend\n p1 = ax.plot([], c='C0', label='Uplink Time', marker='s', linestyle='',\n markersize=10)\n p2 = ax.plot([], c='C1', label='Processing Time', marker='s', linestyle='',\n markersize=10)\n p3 = ax.plot([], c='C2', label='Downlink Time', marker='s', linestyle='',\n markersize=10)\n\n if SEPARATE_LEGEND:\n dim_x, dim_y = PLOT_DIM\n figlegend = pylab.figure(figsize=(dim_x * 2.0, .3))\n plots = (*p1, *p2, *p3)\n figlegend.legend(plots,\n ('Uplink Time', 'Processing Time', 'Downlink Time'),\n loc='center',\n mode='expand',\n ncol=3)\n figlegend.tight_layout()\n figlegend.savefig('times_box_legend.pdf', transparent=True,\n bbox_inches='tight', pad_inches=0)\n figlegend.show()\n else:\n ax.legend()\n\n ax.set_xticks(range(0, len(ticks) * 3, 3))\n ax.set_xticklabels(ticks)\n ax.set_xlim(-1, (len(ticks) * 3) - 2)\n ax.tick_params(labeltop=False,\n labelright=True,\n bottom=True,\n left=True,\n right=True)\n ax.set_ylabel('Time [ms]')\n if feedback:\n ax.set_ylim(top=FEEDBACK_TIME_RANGE[1])\n else:\n ax.set_ylim(top=NO_FEEDBACK_TIME_RANGE[1])\n ax.grid(True, which='major', axis='y', linestyle='--', alpha=0.8)\n\n fig.set_size_inches(*PLOT_DIM)\n plt.tight_layout()\n\n if feedback:\n fig.savefig('times_box_feedback.pdf', bbox_inches='tight')\n if PLOT_TITLES:\n plt.title('Time statistics for frames w/ feedback')\n else:\n fig.savefig('times_box_nofeedback.pdf', bbox_inches='tight')\n if PLOT_TITLES:\n plt.title('Time statistics for frames w/o feedback')\n\n plt.show()\n\n\ndef plot_time_dist(experiments: Dict, feedback: bool) -> None:\n root_dir = os.getcwd()\n results = {}\n\n for exp_name, exp_dir in experiments.items():\n os.chdir(root_dir + '/' + exp_dir)\n data = pd.read_csv('total_frame_stats.csv')\n run_data = pd.read_csv('total_run_stats.csv')\n os.chdir(root_dir)\n\n data = calculate_derived_metrics(data, feedback)\n data = filter_runs(data, run_data)\n\n results[exp_name] = data\n\n # bin_min = min(map(\n # operator.methodcaller('min'),\n # map(\n # operator.itemgetter('processing'),\n # results.values()\n # )\n # ))\n #\n # bin_max = max(map(\n # operator.methodcaller('max'),\n # map(\n # operator.itemgetter('processing'),\n # results.values()\n # )\n # ))\n\n fig, ax = plt.subplots()\n # bins = np.logspace(np.log10(bin_min), np.log10(bin_max), 30)\n\n if feedback:\n bins = np.logspace(np.log10(FEEDBACK_BIN_RANGE[0]),\n np.log10(FEEDBACK_BIN_RANGE[1]),\n 30)\n else:\n bins = np.logspace(np.log10(NO_FEEDBACK_BIN_RANGE[0]),\n np.log10(NO_FEEDBACK_BIN_RANGE[1]),\n 30)\n\n hists = []\n pdfs = []\n for exp_name, data in results.items():\n hists.append(ax.hist(data['processing'], bins,\n label=exp_name,\n # norm_hist=True\n alpha=0.5,\n density=True)[-1])\n\n shape, loc, scale = stats.lognorm.fit(data['processing'])\n pdf = stats.lognorm.pdf(bins, shape, loc, scale)\n pdfs.append(*ax.plot(bins, pdf,\n label=exp_name + ' lognorm PDF'))\n\n if SEPARATE_LEGEND:\n figlegend = pylab.figure(figsize=(3, 1))\n plots = (*(h[0] for h in hists), *pdfs)\n labels = (\n *(exp_name for exp_name, _ in results.items()),\n *(exp_name + ' PDF' for exp_name, _ in results.items())\n )\n figlegend.legend(plots,\n labels,\n loc='center',\n mode='expand',\n ncol=2)\n figlegend.tight_layout()\n figlegend.savefig('proc_hist_legend.pdf', transparent=True,\n bbox_inches='tight', pad_inches=0)\n figlegend.show()\n else:\n ax.legend(loc='upper right', ncol=2)\n\n ax.set_xscale(\"log\")\n ax.set_xlabel('Time [ms]')\n ax.set_ylabel('Density')\n # plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n # ax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,\n # ncol=2, mode=\"expand\", borderaxespad=0.)\n\n fig.set_size_inches(*PLOT_DIM)\n if feedback:\n # ax.set_ylim(*HIST_FEEDBACK_YRANGE)\n fig.savefig('proc_hist_feedback.pdf', bbox_inches='tight')\n if PLOT_TITLES:\n plt.title('Processing times for frames w/ feedback')\n else:\n # ax.set_ylim(*HIST_NO_FEEDBACK_YRANGE)\n fig.savefig('proc_hist_nofeedback.pdf', bbox_inches='tight')\n if PLOT_TITLES:\n plt.title('Processing times for frames w/o feedback')\n plt.show()\n\n\ndef plot_avg_times_frames(experiments: Dict, feedback: bool = False) -> None:\n root_dir = os.getcwd()\n\n stats = []\n\n for exp_dir in experiments.values():\n os.chdir(root_dir + '/' + exp_dir)\n filename = 'sampled_time_stats_feedback.json' \\\n if feedback else 'sampled_time_stats_nofeedback.json'\n with open(filename, 'r') as f:\n sampled_data = json.load(f)\n os.chdir(root_dir)\n\n stats.append(sampled_data)\n\n processing_means = [s['processing']['mean'] for s in stats]\n processing_errors = [\n [s['processing']['mean'] - s['processing']['conf_lower']\n for s in stats],\n [s['processing']['conf_upper'] - s['processing']['mean']\n for s in stats]]\n\n uplink_means = [s['uplink']['mean'] for s in stats]\n uplink_errors = [\n [s['uplink']['mean'] - s['uplink']['conf_lower']\n for s in stats],\n [s['uplink']['conf_upper'] - s['uplink']['mean']\n for s in stats]]\n\n downlink_means = [s['downlink']['mean'] for s in stats]\n downlink_errors = [\n [s['downlink']['mean'] - s['downlink']['conf_lower']\n for s in stats],\n [s['downlink']['conf_upper'] - s['downlink']['mean']\n for s in stats]]\n\n bar_width = 0.3\n r1 = np.arange(len(experiments))\n r2 = [x + bar_width for x in r1]\n r3 = [x + bar_width for x in r2]\n\n errorbar_opts = dict(\n fmt='none',\n linestyle='none',\n ecolor='black',\n lw=3, alpha=1.0,\n capsize=0, capthick=1\n )\n\n fig, ax = plt.subplots()\n up_err = ax.errorbar(r1, uplink_means, yerr=uplink_errors,\n **errorbar_opts, label='95% Confidence Interval')\n proc_err = ax.errorbar(r2, processing_means, yerr=processing_errors,\n **errorbar_opts)\n down_err = ax.errorbar(r3, downlink_means, yerr=downlink_errors,\n **errorbar_opts)\n\n up_bars = ax.bar(r1, uplink_means,\n label='Average uplink time',\n # yerr=uplink_errors,\n width=bar_width,\n edgecolor='white',\n # error_kw=dict(errorbar_opts, label='95% Confidence\n # Interval')\n )\n proc_bars = ax.bar(r2, processing_means,\n label='Average processing time',\n # yerr=processing_errors,\n width=bar_width,\n edgecolor='white',\n # error_kw=errorbar_opts\n )\n down_bars = ax.bar(r3, downlink_means,\n label='Average downlink time',\n # yerr=downlink_errors,\n width=bar_width,\n edgecolor='white',\n # error_kw=errorbar_opts\n )\n\n rects = (up_bars, proc_bars, down_bars)\n # autolabel(ax, rect1)\n # autolabel(ax, rect2)\n # autolabel(ax, rect3)\n\n ax.set_ylabel('Time [ms]')\n\n if feedback:\n list(map(lambda r: autolabel(ax, r, FEEDBACK_TIME_RANGE, bottom=True),\n rects))\n # force eval\n ax.set_ylim(*FEEDBACK_TIME_RANGE)\n else:\n list(map(lambda r: autolabel(ax, r, NO_FEEDBACK_TIME_RANGE,\n bottom=True),\n rects))\n ax.set_ylim(*NO_FEEDBACK_TIME_RANGE)\n\n # plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n # ax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,\n # ncol=2, mode=\"expand\", borderaxespad=0.)\n\n if SEPARATE_LEGEND:\n dim_x, dim_y = PLOT_DIM\n figlegend = pylab.figure(figsize=(dim_x * 2.0, .3))\n figlegend.legend((up_err, *rects),\n (up_err.get_label(), *(r.get_label() for r in rects)),\n loc='center', mode='expand', ncol=4)\n figlegend.tight_layout()\n figlegend.savefig('times_legend.pdf', transparent=True,\n bbox_inches='tight', pad_inches=0)\n figlegend.show()\n else:\n ax.legend(loc='upper left', ncol=2)\n\n # Add xticks on the middle of the group bars\n # ax.set_xlabel('Number of clients', fontweight='bold')\n ax.set_xticks([r + bar_width for r in range(len(experiments))])\n ax.set_xticklabels(experiments.keys())\n\n y_ticks = [tick for tick in ax.get_yticks() if tick >= 0]\n ax.set_yticks(y_ticks)\n\n fig.set_size_inches(*PLOT_DIM)\n if feedback:\n fig.savefig('times_feedback.pdf', bbox_inches='tight')\n if PLOT_TITLES:\n plt.title('Time statistics for frames w/ feedback')\n else:\n fig.savefig('times_nofeedback.pdf', bbox_inches='tight')\n if PLOT_TITLES:\n plt.title('Time statistics for frames w/o feedback')\n plt.show()\n\n\ndef plot_cpu_loads(experiments: Dict) -> None:\n # system_data = [load_system_data_for_experiment(x)\n # for x in experiments.values()]\n system_data_samples = []\n for exp_name, exp_dir in experiments.items():\n data = load_system_data_for_experiment(exp_dir)\n runs = data['run'].unique()\n samples = []\n for run in runs:\n df = data.loc[data['run'] == run]\n samples.append(df.sample(n=2 * SAMPLE_FACTOR))\n system_data_samples.append(pd.concat(samples))\n\n cpu_means = [x['cpu_load'].mean() for x in system_data_samples]\n cpu_stds = [x['cpu_load'].std() for x in system_data_samples]\n cpu_count = [x.shape[0] for x in system_data_samples]\n\n cpu_confs = [\n stats.norm.interval(\n CONFIDENCE,\n loc=mean,\n scale=std / math.sqrt(count)\n )\n for mean, std, count in zip(cpu_means, cpu_stds, cpu_count)\n ]\n\n err = [\n [mean - x[0] for mean, x in zip(cpu_means, cpu_confs)],\n [x[1] - mean for mean, x in zip(cpu_means, cpu_confs)]\n ]\n\n cpu_range = (0, 100)\n\n fig, ax = plt.subplots()\n rect = ax.bar(experiments.keys(), cpu_means, label='Average CPU load')\n ax.errorbar(experiments.keys(), cpu_means, yerr=err,\n fmt='none',\n linestyle='none',\n ecolor='darkblue',\n lw=10, alpha=1.0,\n capsize=0, capthick=1, label='95% Confidence Interval')\n\n autolabel(ax, rect, cpu_range, bottom=True)\n\n ax.set_ylabel('Load [%]')\n ax.set_ylim(*cpu_range)\n ax.legend(loc='upper left')\n # plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n\n fig.set_size_inches(*PLOT_DIM)\n fig.savefig('cpu_load.pdf', bbox_inches='tight')\n plt.show()\n\n\ndef plot_ram_usage(experiments: Dict) -> None:\n system_data_samples = []\n for exp_name, exp_dir in experiments.items():\n data = load_system_data_for_experiment(exp_dir)\n runs = data['run'].unique()\n samples = []\n for run in runs:\n df = data.loc[data['run'] == run]\n samples.append(df.sample(n=2 * SAMPLE_FACTOR))\n system_data_samples.append(pd.concat(samples))\n\n mem_means = [x['mem_avail'].mean() for x in system_data_samples]\n mem_stds = [x['mem_avail'].std() for x in system_data_samples]\n mem_count = [x.shape[0] for x in system_data_samples]\n\n mem_confs = [\n stats.norm.interval(\n CONFIDENCE,\n loc=mean,\n scale=std / math.sqrt(count)\n )\n for mean, std, count in zip(mem_means, mem_stds, mem_count)\n ]\n\n err = [\n [mean - x[0] for mean, x in zip(mem_means, mem_confs)],\n [x[1] - mean for mean, x in zip(mem_means, mem_confs)]\n ]\n\n # total_mem = psutil.virtual_memory().total\n conv_factor = float(1024 * 1024 * 1024) # GiB <-> MiB\n total_mem = 32 * conv_factor\n mem_usage_means = [(total_mem - m) / conv_factor for m in mem_means]\n err = [\n list(map(lambda m: m / conv_factor, err[0])),\n list(map(lambda m: m / conv_factor, err[1]))\n ]\n total_mem = total_mem / conv_factor # convert back to GiB\n\n ram_range = (0, total_mem + 3)\n\n fig, ax = plt.subplots()\n rect = ax.bar(experiments.keys(), mem_usage_means,\n label='Average RAM usage',\n color='darkblue')\n ax.errorbar(experiments.keys(), mem_usage_means, yerr=err,\n fmt='none',\n linestyle='none',\n ecolor='darkorange',\n lw=10, alpha=1.0,\n capsize=0, capthick=1, label='95% Confidence Interval')\n\n autolabel(ax, rect, ram_range, bottom=True, color='white')\n\n ax.set_ylim(*ram_range)\n ax.axhline(y=total_mem,\n color='red',\n label='Max. available memory')\n ax.set_ylabel('Usage [GiB]')\n ax.legend(loc=\"center left\")\n\n fig.set_size_inches(*PLOT_DIM)\n fig.savefig('ram_usage.pdf', bbox_inches='tight')\n\n plt.show()\n\n\ndef load_data_for_experiment(experiment_id) -> Dict:\n os.chdir(experiment_id)\n with open('total_stats.json', 'r') as f:\n os.chdir('..')\n return json.load(f)\n\n\ndef load_system_data_for_experiment(experiment_id) -> pd.DataFrame:\n os.chdir(experiment_id)\n df = pd.read_csv('total_system_stats.csv')\n os.chdir('..')\n return df\n\n\ndef print_successful_runs(experiments):\n for exp_name, exp_id in experiments.items():\n os.chdir(exp_id)\n df = pd.read_csv('total_run_stats.csv')\n os.chdir('..')\n\n print(exp_name)\n n_clients = df['client_id'].max() + 1\n total_runs = df['run_id'].max() + 1\n for c in range(n_clients):\n client_runs = df.loc[df['client_id'] == c]\n success_runs = client_runs.loc[client_runs['success']].shape[0]\n print('Client {}: \\t {} out of {} runs'\n .format(c, success_runs, total_runs))\n\n\nif __name__ == '__main__':\n with plt.style.context('tableau-colorblind10'):\n plt.rcParams['font.size'] = 10 # font size\n plt.rcParams['xtick.labelsize'] = 10\n plt.rcParams['ytick.labelsize'] = 10\n plt.rcParams['axes.labelsize'] = 10\n plt.rcParams['legend.fontsize'] = 10\n\n experiments = {\n '1 Client\\nOptimal' : '1Client_100Runs',\n '5 Clients\\nOptimal' : '5Clients_100Runs',\n '10 Clients\\nOptimal' : '10Clients_100Runs',\n '10 Clients\\nImpaired\\nWiFi': '10Clients_100Runs_BadLink' # ,\n # 'Impaired\\nCPU' : '10Clients_100Runs_0.5CPU'\n }\n\n # experiments = {\n # '1 Client' : '1Client_100Runs',\n # '5 Clients' : '5Clients_100Runs',\n # '10 Clients': '10Clients_100Runs',\n # '15 Clients': '15Clients_100Runs'\n # }\n\n # experiments = {\n # 'TCPDUMP': '1Client_10Runs_ArtificialLoad',\n # 'No TCPDUMP': '1Client_10Runs_NoTCPDUMP'\n # }\n\n # os.chdir('1Client_100Runs_BadLink')\n # frame_data = pd.read_csv('total_frame_stats.csv')\n # run_data = pd.read_csv('total_run_stats.csv')\n # os.chdir('..')\n\n # print_successful_runs(experiments)\n\n # plot_avg_times_frames(experiments, feedback=True)\n # plot_avg_times_frames(experiments, feedback=False)\n plot_time_box(experiments, feedback=True)\n # plot_time_box(experiments, feedback=False)\n plot_time_taskstep('1Client_100Runs_TaskStep')\n plot_box_fb_vs_nfb(experiments)\n # plot_time_dist(experiments, feedback=True)\n # plot_time_dist(experiments, feedback=False)\n\n # plot_cpu_loads(experiments)\n # plot_ram_usage(experiments)\n","sub_path":"plot_results.py","file_name":"plot_results.py","file_ext":"py","file_size_in_byte":26458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"573489689","text":"from dataclasses import dataclass\n\n\n@dataclass\nclass Feature:\n description: str\n\n\nFEATURES = []\n\n\nclass FeatureSectionMetaclass(type):\n def __new__(self, name, bases, attrs):\n if 'Meta' in attrs:\n section = {\n 'key': attrs['Meta'].key,\n 'description': attrs['Meta'].description,\n 'items': [],\n }\n FEATURES.append(section)\n for key, feature in attrs.items():\n if isinstance(feature, Feature):\n section['items'].append(\n {'key': key, 'description': feature.description}\n )\n return type.__new__(self, name, bases, attrs)\n\n\nclass FeatureSection(metaclass=FeatureSectionMetaclass):\n pass\n\n\nclass CustomerSection(FeatureSection):\n class Meta:\n key = 'customer'\n description = 'Organization workspace'\n\n category_resources_list = Feature(\n 'Render component usage charts in organization dashboard.'\n )\n\n project_requests = Feature(\n 'Render list of project creation requests in organization dashboard.'\n )\n\n resource_requests = Feature(\n 'Render list of resource creation requests in organization dashboard.'\n )\n\n show_subnets = Feature(\n 'Render list of subnets from where connection to '\n 'self-service is allowed in organization details dialog.'\n )\n\n show_domain = Feature('Allows to hide domain field in organization detail.')\n\n billing = Feature('Render billing menu in organization sidebar.')\n\n team = Feature('Enable team management in organization workspace.')\n\n events = Feature('Enable audit log in organization workspace.')\n\n hide_organization_billing_step = Feature(\n 'Hide billing step in organization creation wizard.'\n )\n\n payments_for_staff_only = Feature(\n 'Make payments menu visible for staff users only.'\n )\n\n\nclass ProjectSection(FeatureSection):\n class Meta:\n key = 'project'\n description = 'Project workspace'\n\n member_role = Feature('Allow to grant user a project member role.')\n\n team = Feature('Enable team management in project workspace.')\n\n estimated_cost = Feature('Render estimated cost column in projects list.')\n\n events = Feature('Enable audit log in project workspace.')\n\n oecd_fos_2007_code = Feature('Enable OECD code.')\n\n show_industry_flag = Feature('Show industry flag.')\n\n\nclass UserSection(FeatureSection):\n class Meta:\n key = 'user'\n description = 'User workspace'\n\n preferred_language = Feature('Render preferred language column in users list.')\n\n competence = Feature('Render competence column in users list.')\n\n ssh_keys = Feature('Enable SSH keys management in user workspace.')\n\n notifications = Feature(\n 'Enable email and webhook notifications management in user workspace.'\n )\n\n\nclass MarketplaceSection(FeatureSection):\n class Meta:\n key = 'marketplace'\n description = 'Marketplace offerings and resources'\n\n offering_document = Feature('Allow to attach document to marketplace offering.')\n\n flows = Feature(\n 'Allow to submit organization, project and resource creation requests simultaneously.'\n )\n\n private_offerings = Feature(\n 'Render list of private marketplace service providers in organization workspace.'\n )\n\n import_resources = Feature(\n 'Allow to import resources from service provider to project.'\n )\n\n conceal_prices = Feature('Do not render prices in shopping cart and order details.')\n\n terms_of_service = Feature('Render terms of service when offering is ordered.')\n\n review = Feature('Allow to write a review for marketplace offering.')\n\n show_experimental_ui_components = Feature(\n 'Enabled display of experimental or mocked components in marketplace.'\n )\n\n\nclass SupportSection(FeatureSection):\n class Meta:\n key = 'support'\n description = 'Support workspace'\n\n activity_stream = Feature('Render list of recent comments in support dashboard.')\n\n customers_list = Feature('Render list of organizations in support workspace.')\n\n pricelist = Feature(\n 'Render marketplace plan components pricelist in support workspace.'\n )\n\n customers_requests = Feature(\n 'Render list of organization creation requests in support workspace.'\n )\n\n users = Feature('Render list of users in support workspace.')\n\n flowmap = Feature('Render service usage as a flowmap chart in support workspace.')\n\n heatmap = Feature('Render service usage as a heatmap chart in support workspace.')\n\n sankey_diagram = Feature(\n 'Render service usage as a sankey chart in support workspace.'\n )\n\n resources_treemap = Feature(\n 'Render resource usage as a treemap chart in support workspace.'\n )\n\n shared_providers = Feature(\n 'Render overview of shared marketplace service providers in support workspace.'\n )\n\n resource_usage = Feature(\n 'Enable resource usage overview charts in support workspace.'\n )\n\n vm_type_overview = Feature('Enable VM type overview in support workspace.')\n\n offering_comments = Feature(\n 'Render comments tab in request-based item details page.'\n )\n\n conceal_change_request = Feature(\n 'Conceal \"Change request\" from a selection of issue types for non-staff/non-support users.'\n )\n\n next_branch = Feature('Render \"Try out new version\" link in toolbar.')\n\n legacy_branch = Feature('Render \"Go to old interface\" link in toolbar for new UI')\n\n\nclass InvitationsSection(FeatureSection):\n class Meta:\n key = 'invitations'\n description = 'Invitations management'\n\n conceal_civil_number = Feature(\n 'Conceal civil number in invitation creation dialog.'\n )\n\n create_missing_user = Feature(\n 'Allow to create FreeIPA user using details '\n 'specified in invitation if user does not exist yet.'\n )\n\n disable_multiple_roles = Feature(\n 'Do not allow user to grant multiple roles in the '\n 'same project or organization using invitation.'\n )\n\n show_tax_number = Feature('Show tax number field in invitation creation form.')\n\n tax_number_required = Feature(\n 'Make tax number field mandatory in invitation creation form.'\n )\n\n civil_number_required = Feature(\n 'Make civil number field mandatory in invitation creation form.'\n )\n\n require_user_details = Feature(\n 'Render \"Show user details\" button in invitation creation form.'\n )\n\n\nclass InvoiceSection(FeatureSection):\n class Meta:\n key = 'invoice'\n description = 'Invoice management'\n\n events = Feature('Render list of events related to invoice item in modal dialog.')\n\n\nclass OpenstackSection(FeatureSection):\n class Meta:\n key = 'openstack'\n description = 'OpenStack resources provisioning'\n\n volume_types = Feature(\n 'Allow to select OpenStack volume type when instance or volume is provisioned.'\n )\n\n\nclass RancherSection(FeatureSection):\n class Meta:\n key = 'rancher'\n description = 'Rancher resources provisioning'\n\n volume_mount_point = Feature(\n 'Allow to select mount point for data volume when Rancher cluster is provisioned.'\n )\n\n\nclass SlurmSection(FeatureSection):\n class Meta:\n key = 'slurm'\n description = 'SLURM resources provisioning'\n\n jobs = Feature(\n 'Render list of SLURM jobs as a separate tab in allocation details page.'\n )\n","sub_path":"src/waldur_core/core/features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":7562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"473503696","text":"from django.contrib.auth.views import logout_then_login\nfrom django.shortcuts import render\n# Create your views here.\nfrom django.shortcuts import render, redirect\nfrom .forms import userForm, profileForm, patientForm, clinicForm\nfrom django.urls import reverse\nfrom django.contrib.auth.decorators import login_required\n\n\n#For Email Verification\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.utils.encoding import force_bytes, force_text\nfrom django.contrib.auth import login\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom django.template.loader import render_to_string\nfrom .tokens import account_activation_token\nfrom django.contrib.auth.models import User\nfrom django.core.mail import EmailMessage\nfrom django.http import HttpResponse, Http404\n\n#Message Notification Alert\nfrom django.contrib import messages\n\nfrom django.http import JsonResponse\n#Authenticatio response\nfrom django.contrib.auth import authenticate, login\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import JsonResponse\nimport json\n\n# Error Logger\nimport logging\n\n#import from models\nfrom .models import *\n\n#Instantiate Error Logging\nlogger = logging.getLogger(__name__)\n\n@login_required\ndef dashboard(request):\n if request.method == 'POST':\n form = profileForm(request.POST, instance=request.user.account)\n if form.is_valid():\n form.save()\n return redirect('dashboard')\n else:\n form = profileForm(instance=request.user.account)\n\n if request.method == 'POST' and not form.is_valid():\n cform = clinicForm(request.POST, instance=request.user.account)\n if cform.is_valid():\n cform.save()\n return redirect('dashboard')\n else:\n cform = clinicForm()\n instance = request.user.account\n showclinic = Clinic.objects.filter(account_id = instance)\n context = {'form': form,\n 'cform': cform,\n 'showclinic': showclinic\n }\n return render(request, 'projectMain/dashboard.html', context)\n\n@login_required\ndef appointment(request):\n return render(request, 'projectMain/appointment.html')\n\n@login_required\ndef newsfeed(request):\n return render(request, 'projectMain/newsfeed.html')\n\n@login_required\ndef patients(request):\n if request.method == 'POST':\n pform = patientForm(request.POST)\n if pform.is_valid():\n patient = pform.save(commit=False)\n patient.save()\n patient.doctor.add(request.user.account)\n return redirect('patient')\n else:\n pform = patientForm()\n\n return render(request, 'projectMain/patient.html', {'pform': pform})\n\n@login_required\ndef profile(request):\n if request.method == 'POST':\n form = profileForm(request.POST, request.FILES, instance=request.user.account)\n if form.is_valid():\n form.save()\n return redirect('dashboard')\n else:\n form = profileForm(instance=request.user.account)\n\n return render(request, 'projectMain/profile.html', {'form': form})\n\n@csrf_exempt\ndef signin(request):\n return render(request, 'projectMain/sign-in.html')\n\n\ndef signup(request):\n if request.method == 'POST':\n form = userForm(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n user.is_staff = False\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password')\n\n user.save()\n user.accounttype.access = 1\n current_site = get_current_site(request)\n mail_subject = 'Activate your Account.'\n message = render_to_string('projectMain/acc_active_email.html', {\n 'user': user,\n 'domain': current_site.domain,\n 'uid': urlsafe_base64_encode(force_bytes(user.pk)),\n 'token': account_activation_token.make_token(user),\n })\n to_email = form.cleaned_data.get('email')\n email = EmailMessage(mail_subject, message, to=[to_email])\n email.send()\n messages.success(request, f'Please confirm your registration by going to your email')\n return redirect('sign-in')\n else:\n form = userForm()\n return render(request, 'projectMain/sign-up.html', {'form': form})\n\ndef activate(request, uidb64, token):\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = User.objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n if user is not None and account_activation_token.check_token(user, token):\n user.is_active = True\n user.save()\n login(request, user)\n return redirect('dashboard')\n #return HttpResponse('Thank you for your email confirmation. Now you can login your account.')\n else:\n return HttpResponse('Activation link is invalid!')\n\ndef forgotpw(request):\n\n return render(request, 'projectMain/forgot-password.html')\n\n@login_required\ndef logout(request):\n return logout_then_login(request, reverse('sign-in'))\n\nlogger = logging.getLogger(__name__)\n\ndef auth(request):\n if request.method == 'POST':\n uname = request.headers.get('Username')\n pword = request.headers.get('Password')\n\n # logger.error(uname)\n # logger.error(pword)\n # logger.error(request.POST)\n # logger.error(request.headers)\n # logger.error(request.body)\n user = authenticate(username=uname, password=pword)\n if user is not None:\n if user.is_active:\n login(request, user)\n return HttpResponse(json.dumps({\"message\": \"LOGIN_SUCCESS\"}), content_type=\"application/json\")\n else:\n return HttpResponse(json.dumps({\"message\": \"inactive\"}), content_type=\"application/json\")\n else:\n return HttpResponse(json.dumps({\"message\": \"invalid\"}), content_type=\"application/json\")\n return HttpResponse('')\n\n\n\n\ndef addPatient(request):\n\n return render(request,'projectMain/patient-profile.html')\n\n\ndef addClinic(request):\n if request.method == 'POST':\n cform = clinicForm(request.POST, instance=request.user.account)\n if cform.is_valid():\n logger.error(request.POST)\n logger.error(request.user.account)\n cform.save()\n logger.error(cform)\n return redirect('dashboard')\n else:\n cform = clinicForm()\n\n return render(request,'projectMain/addClinic.html', {'cform': cform})","sub_path":"projectMain/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"639389170","text":"# 선형회귀\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential # 완전연결 모델\nfrom tensorflow.keras.layers import Dense, Activation\nfrom tensorflow.keras.optimizers import Adam \nfrom sklearn.preprocessing import MinMaxScaler, minmax_scale\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nplt.rc('font', family='malgun gothic')\n\n# 자료 읽기\ndata = pd.read_csv('https://raw.githubusercontent.com/pykwon/python/master/testdata_utf8/Advertising.csv')\ndel data['no']\nprint(data.head(2))\nprint(data.corr())\n\n# 정규화 : 0 ~ 1 사이로 scaling - 정확도를 높이기 위한 작업(정규화를 하는 이유)\n#scaler = MinMaxScaler(feature_range=(0, 1)) # 기본값이 0 ~ 1\n# scaler = MinMaxScaler()\n# xy = scaler.fit_transform(data) # scaler.inverse_transform(xy) 를 사용하면 원래값으로 환원환다.\n# print(xy[:2])\n\nxy = minmax_scale(data, axis=0, copy=True) # 위랑 같지만 이게 더 편하다.\nprint(xy[:2])\n\n# 데이터 분리 : train_test_split - 과적합 방지. \nfrom sklearn.model_selection import train_test_split\nxtrain, xtest, ytrain, ytest = train_test_split(xy[:, 0:-1], xy[:,-1], # x = xy의 마지막 열을 제외한 모든 열의 모든행, y = xy의 마지막 열의 모든 행\n test_size=0.3, random_state=123) \nprint(xtrain[:2], ' ', xtrain.shape) # (140, 3)\nprint(ytrain[:2], ' ', ytrain.shape) # (140, )\n\n\n# 모델 생성\nmodel = Sequential()\nmodel.add(Dense(20, input_dim = 3, activation='linear'))\nmodel.add(Dense(10, activation='linear'))\nmodel.add(Dense(1, activation='linear')) # 레이어 3개\n\n\n# 모델 파라미터(구성정보) 확인\nprint(model.summary())\n\n\n# 모델을 사진으로 저장\ntf.keras.utils.plot_model(model, 'abc.png') # GraphBiz가 설치되어야 가능\n\n\n# 학습 process 생성(컴파일)\nmodel.compile(optimizer=Adam(lr=0.001), loss='mse', metrics=['mse'])\n\n\n# 모델 학습 (fitting)\nhistory = model.fit(xtrain, ytrain, batch_size=32, epochs=100, verbose=1, validation_split=0.2)\n # batch_size : 몇 개의 샘플로 가중치를 갱신할 것인지 지정. 속도가 빨라짐. \n # validation_split=0.2 : 학습데이터가 들어오면 알아서 k-fold작업을 한다.(나눠서 들어온 데이터가 아니여도 내부에서 나눈다.) train데이터를 다시 8:2로 나눠서 8을 학습데이터, 2를 검정데이터로 사용한다.\nprint('train loss : ', history.history['loss'])\n\n \n# 모델 평가 - 여기서 결과가 이상하면 오버피팅. 못풀면 모델을 여러 개 써보자.\nloss = model.evaluate(xtest, ytest, batch_size=32)\nprint('test loss : ', loss)\n\n# 설명력(결정계수)\nfrom sklearn.metrics import r2_score\nprint('r2_score(설명력) : ', r2_score(ytest, model.predict(xtest))) # r2_score(실제값, 예측값) : 0.916\n\n# 학습결과 예측값 출력\npred = model.predict(xtest)\nprint('실제값 : ', ytest[:5])\nprint('예측값 : ', pred[:5].flatten())\n\n\n# 시각화\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"pack/tf2/keras_ex08.py","file_name":"keras_ex08.py","file_ext":"py","file_size_in_byte":3027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"519883766","text":"# -*- coding: utf-8 -*-\nfrom typing import Text\nfrom zerver.lib.test_classes import WebhookTestCase\n\nclass HelloSignHookTests(WebhookTestCase):\n STREAM_NAME = 'hellosign'\n URL_TEMPLATE = \"/api/v1/external/hellosign?stream={stream}&api_key={api_key}\"\n FIXTURE_DIR_NAME = 'hellosign'\n\n def test_signatures_message(self):\n # type: () -> None\n expected_subject = \"NDA with Acme Co.\"\n expected_message = (\"The NDA with Acme Co. is awaiting the signature of \"\n \"Jack and was just signed by Jill.\")\n self.send_and_test_stream_message('signatures', expected_subject, expected_message,\n content_type=\"application/x-www-form-urlencoded\")\n\n def get_body(self, fixture_name):\n # type: (Text) -> Text\n return self.fixture_data(\"hellosign\", fixture_name, file_type=\"json\")\n","sub_path":"zerver/webhooks/hellosign/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"579613907","text":"import tensorflow as tf\r\nimport cifar100_input as _input\r\nimport cifar100_net as net\r\n\r\nEPOCH = 600\r\nBATCH_SIZE = 256\r\nLEARNING_RATE = 0.05\r\nDROPOUT_RATE = 0.5\r\nSUMMARY_DIR = \"summary\"\r\nCHECKPOINT_DIR = \"checkpoints\"\r\n\r\nwith tf.Graph().as_default() as graph:\r\n\r\n\tevalSet = _input.getEval()\r\n\tevalIter = evalSet.make_initializable_iterator()\r\n\ttest_examples, test_labels = evalIter.get_next()\r\n\r\n\tglobal_step = tf.Variable(0, trainable=False, name=\"global_step\")\r\n\timage_batch = tf.placeholder(tf.float32, shape=(None ,32, 32, 3))\r\n\tlabel_batch = tf.placeholder(tf.int64, shape=(None))\r\n\tdropout_rate = tf.placeholder(tf.float32, shape=(None))\r\n\tlearning_rate = tf.placeholder(tf.float32, shape=(None))\r\n\r\n\tlogits = net.inference(image_batch, dropout_rate)\r\n\tloss = net.cost(logits, label_batch)\r\n\taccuracy = net.predict(logits, label_batch)\r\n\ttrain_op = net.train(loss, learning_rate, global_step)\r\n\r\n\ttf.summary.image(\"image\", image_batch)\r\n\ttf.summary.scalar(\"loss\", loss)\r\n\ttf.summary.scalar(\"accuracy\", accuracy)\r\n\tsummary = tf.summary.merge_all()\r\n\r\n\twriter = tf.summary.FileWriter(SUMMARY_DIR, graph)\r\n\tsaver = tf.train.Saver()\r\n\r\n\twith tf.Session() as sess:\r\n\t\tsaver.restore(sess, tf.train.latest_checkpoint(CHECKPOINT_DIR))\r\n\t\tsess.run(trainIter.initializer)\r\n\t\t\r\n\t\tfor i in range(EPOCH):\r\n\t\t\tx, y = sess.run([next_examples, next_labels])\r\n\t\t\tfeed_dict={ image_batch: x,\r\n\t\t\t\t\t\tlabel_batch: y,\r\n\t\t\t\t\t\tdropout_rate: DROPOUT_RATE,\r\n\t\t\t\t\t\tlearning_rate: LEARNING_RATE}\r\n\t\t\t_, _loss, acc, step = sess.run([train_op, loss, accuracy, global_step], \r\n\t\t\t\t\t\t\t\t\t\t\tfeed_dict=feed_dict)\r\n\t\t\tprint(\"STEP <{0}>, loss:{1:3.4f}, accuracy:{2:3.2f}%\".format(step, _loss, acc*100))\r\n\r\n\t\t\tif(step % 10 == 0):\r\n\t\t\t\twriter.add_summary(sess.run(summary, feed_dict=feed_dict), step)\r\n\t\t\t\t\r\n\t\t\tif(step % 10000 == 0):\r\n\t\t\t\tsaver.save(sess, CHECKPOINT_DIR)","sub_path":"cifar100_resume.py","file_name":"cifar100_resume.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"653114515","text":"import multiprocessing\n\nfrom functools import partial\nimport pandas\n\nfrom ips.services.restricted_python import Status, ErrorStatus, SuccessfulStatus\nfrom ips.util.services_logging import log\nimport ips.persistence.sql as db\nimport numpy as np\n# for exec\n# noinspection PyUnresolvedReferences\nimport math\n# for exec\n# noinspection PyUnresolvedReferences\nfrom datetime import datetime\n\nfrom ips.persistence.persistence import insert_from_dataframe\nfrom RestrictedPython import compile_restricted\nfrom RestrictedPython import safe_builtins\n\n\nclass PVExecutionError(Exception):\n def __init__(self, message, pv):\n self.errorMessage = message\n self.PV = pv\n\n\ndef getitem(object, name, default=None): # known special case of getitem\n \"\"\"\n extend to ensure only specific items can be accessed if required\n \"\"\"\n # raise RestrictedException(\"You bad boy!\")\n return object[name]\n\n\ndef _write_wrapper():\n # Construct the write wrapper class\n def _handler(secattr, error_msg):\n # Make a class method.\n def handler(self, *args):\n try:\n f = getattr(self.ob, secattr)\n except AttributeError:\n raise TypeError(error_msg)\n f(*args)\n\n return handler\n\n class Wrapper(object):\n def __init__(self, ob):\n self.__dict__['ob'] = ob\n\n __setitem__ = _handler(\n '__guarded_setitem__',\n 'object does not support item or slice assignment')\n\n __delitem__ = _handler(\n '__guarded_delitem__',\n 'object does not support item or slice assignment')\n\n __setattr__ = _handler(\n '__guarded_setattr__',\n 'attribute-less object (assign or del)')\n\n __delattr__ = _handler(\n '__guarded_delattr__',\n 'attribute-less object (assign or del)')\n\n return Wrapper\n\n\ndef _write_guard():\n # Nested scope abuse!\n # safetypes and wrapper variables are used by guard()\n safetypes = {dict, list, pandas.DataFrame, pandas.Series}\n wrapper = _write_wrapper()\n\n def guard(ob):\n # Don't bother wrapping simple types, or objects that claim to\n # handle their own write security.\n if type(ob) in safetypes or hasattr(ob, '_guarded_writes'):\n return ob\n # Hand the object to the Wrapper instance, then return the instance.\n return wrapper(ob)\n\n return guard\n\n\nwrite_guard = _write_guard()\n\nsafe_globals = dict(__builtins__=safe_builtins)\n\nsafe_builtins['_getitem_'] = getitem\nsafe_builtins['_getattr_'] = getattr\nsafe_builtins['_write_'] = write_guard\nsafe_builtins['math'] = math\nsafe_builtins['datetime'] = datetime\n\n\ndef modify_values(row, dataset, pvs):\n \"\"\"\n Author : Thomas Mahoney\n Date : 27 / 03 / 2018\n Purpose : Applies the PV rules to the specified dataframe on a row by row basis.\n Parameters : row - the row of a dataframe passed to the function through the 'apply' statement called\n pvs - a collection of pv names and statements to be applied to the dataframe's rows.\n dataset - and identifier used in the executed pv statements.\n Returns : a modified row to be reinserted into the dataframe.\n Requirements : this function must be called through a pandas apply statement.\n Dependencies : NA\n \"\"\"\n\n for pv in pvs:\n safe_builtins['row'] = row\n safe_builtins['dataset'] = dataset\n code = pv['PROCVAR_RULE']\n log.debug(f\"Executing PV {pv['PROCVAR_NAME']}\")\n try:\n exec(code, safe_globals, None)\n except Exception as err:\n name = pv['PROCVAR_NAME']\n log.error(f\"Error in PV: {name}, Message: {str(err)}\")\n raise PVExecutionError(str(err), pv['PROCVAR_NAME'])\n\n if dataset in ('survey', 'shift'):\n row['SHIFT_PORT_GRP_PV'] = str(row['SHIFT_PORT_GRP_PV'])[:10]\n\n return row\n\n\ndef get_pvs():\n \"\"\"\n Author : Thomas Mahoney\n Date : 27 / 03 / 2018\n Purpose : Extracts the PV data from the process_variables table.\n Parameters : conn - a connection object linking the database.\n Returns : a collection of pv names and statements\n Requirements : NA\n Dependencies : NA\n \"\"\"\n\n engine = db.get_sql_connection()\n\n if engine is None:\n raise ConnectionError(\"Cannot get database connection\")\n\n with engine.connect() as conn:\n sql = \"SELECT PROCVAR_NAME,PROCVAR_RULE FROM SAS_PROCESS_VARIABLE ORDER BY PROCVAR_ORDER\"\n v = conn.engine.execute(sql)\n return v.fetchall()\n\n\ndef parallel_func(pv_df, pv_list, dataset=None):\n compile_pvs(\"\", pv_list)\n return pv_df.apply(modify_values, axis=1, args=(dataset, pv_list))\n\n\ndef compile_pvs(template, pv_list) -> Status:\n for a in pv_list:\n log.debug(f\"Compiling PV: {a['PROCVAR_NAME']}\")\n try:\n a['PROCVAR_RULE'] = compile_restricted(\n a['PROCVAR_RULE'],\n filename=a['PROCVAR_NAME'],\n mode='exec'\n )\n except Exception as err:\n return ErrorStatus(template, str(err), a['PROCVAR_NAME'])\n return SuccessfulStatus(template)\n\n\ndef parallelise_pvs(dataframe, process_variables, dataset=None):\n num_partitions = multiprocessing.cpu_count()\n df_split = np.array_split(dataframe, num_partitions)\n pool = multiprocessing.Pool(num_partitions)\n\n res = pandas.concat(\n pool.map(\n partial(parallel_func, pv_list=process_variables, dataset=dataset),\n df_split\n ),\n sort=True\n )\n\n pool.close()\n pool.join()\n\n return res\n\n\ndef process(in_table_name, out_table_name, in_id, dataset):\n # Ensure the input table name is capitalised\n in_table_name = in_table_name.upper()\n\n # Extract the table's content into a local dataframe\n df_data = db.get_table_values(in_table_name)\n\n # Fill nan values\n df_data.fillna(value=np.NaN, inplace=True)\n\n # Get the process variable statements\n process_variables = get_pvs()\n\n pvs = []\n for a in process_variables:\n c = dict(a.items())\n pvs.append(c)\n\n if dataset == 'survey':\n df_data = df_data.sort_values('SERIAL')\n\n df_data = parallelise_pvs(df_data, pvs, dataset)\n\n # Create a list to hold the PV column names\n updated_columns = []\n\n # Loop through the pv's\n for pv in process_variables:\n updated_columns.append(pv[0].upper())\n\n # Generate a column list from the in_id column and the pvs for the current run\n columns = [in_id] + updated_columns\n columns = [col.upper() for col in columns]\n # Create a new dataframe from the modified data using the columns specified\n df_out = df_data[columns]\n\n # Insert the dataframe to the output table\n insert_from_dataframe(out_table_name)(df_out)\n","sub_path":"ips/util/process_variables.py","file_name":"process_variables.py","file_ext":"py","file_size_in_byte":6861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"442299288","text":"from bs4 import BeautifulSoup\nimport requests\nimport re\nimport os\nimport csv\nimport unittest\n\n# By: Tiara Amadia & Anthony Ho // Nina Yang\n\n\ndef get_titles_from_search_results(filename):\n\n source_dir = os.path.dirname(__file__)\n fullpath = os.path.join(source_dir, filename) \n infile = open(fullpath, 'r', encoding=\"UTF-8\")\n soup = BeautifulSoup(infile, \"html.parser\")\n infile.close()\n\n list_tuple = []\n rows = soup.find_all(\"tr\", itemtype=\"http://schema.org/Book\")\n\n for row in rows: \n each_book = row.find(\"a\", class_= \"bookTitle\")\n book_title = each_book.find(\"span\", itemprop = \"name\")\n each_author = row.find(\"a\", class_= \"authorName\")\n author_name = each_author.find(\"span\", itemprop = \"name\")\n list_tuple.append((book_title.text.strip(), author_name.text.strip()))\n \n return list_tuple\n \n \"\"\"\n Write a function that creates a BeautifulSoup object on \"search_results.htm\". Parse\n through the object and return a list of tuples containing book titles (as printed on the Goodreads website) \n and authors in the format given below. Make sure to strip() any newlines from the book titles and author names.\n\n [('Book title 1', 'Author 1'), ('Book title 2', 'Author 2')...]\n \"\"\"\n\n\ndef get_search_links():\n url = \"https://www.goodreads.com/search?q=fantasy&qid=NwUsLiA2Nc\"\n r = requests.get(url)\n soup = BeautifulSoup(r.text, 'html.parser')\n\n list_links = []\n rows = soup.find_all(\"a\", class_ = \"bookTitle\")\n\n for row in rows: \n each_link = row.get('href', None)\n\n list_links.append(\"https://www.goodreads.com\" + each_link)\n\n return list_links[:10]\n\n \"\"\"\n Write a function that creates a BeautifulSoup object after retrieving content from\n \"https://www.goodreads.com/search?q=fantasy&qid=NwUsLiA2Nc\". Parse through the object and return a list of\n URLs for each of the first ten books in the search using the following format:\n\n ['https://www.goodreads.com/book/show/84136.Fantasy_Lover?from_search=true&from_srp=true&qid=NwUsLiA2Nc&rank=1', ...]\n\n Notice that you should ONLY add URLs that start with \"https://www.goodreads.com/book/show/\" to \n your list, and , and be sure to append the full path to the URL so that the url is in the format \n “https://www.goodreads.com/book/show/kdkd\".\n\n \"\"\"\n\n\ndef get_book_summary(book_url):\n\n chosen_url = book_url\n r = requests.get(chosen_url)\n soup = BeautifulSoup(r.text, 'html.parser')\n\n book_title = soup.find(\"h1\", id=\"bookTitle\")\n chosen_author = soup.find(\"a\", class_=\"authorName\")\n author_name = chosen_author.find(\"span\", itemprop=\"name\")\n page_num = soup.find(\"span\", itemprop=\"numberOfPages\")\n\n return (book_title.text.strip(), author_name.text.strip(), int(page_num.text.strip().split(\" \")[0]))\n \"\"\"\n Write a function that creates a BeautifulSoup object that extracts book\n information from a book's webpage, given the URL of the book. Parse through\n the BeautifulSoup object, and capture the book title, book author, and number \n of pages. This function should return a tuple in the following format:\n\n ('Some book title', 'the book's author', number of pages)\n\n HINT: Using BeautifulSoup's find() method may help you here.\n You can easily capture CSS selectors with your browser's inspector window.\n Make sure to strip() any newlines from the book title and number of pages.\n \"\"\"\n\ndef summarize_best_books(filepath):\n\n infile = open(filepath, 'r', encoding='UTF-8')\n soup = BeautifulSoup(infile, 'html.parser')\n infile.close()\n\n chosen_book = soup.find_all(class_ = \"category clearFix\")\n list_category = []\n\n for element in chosen_book:\n\n chosen_category = element.find(class_=\"category__copy\").text.strip()\n book_title = element.find(\"img\", class_=\"category__winnerImage\").get('alt', None)\n chosen_link = element.find(\"a\").get('href', None)\n\n list_category.append((chosen_category, book_title, chosen_link))\n \n return list_category\n\n \"\"\"\n Write a function to get a list of categories, book title and URLs from the \"BEST BOOKS OF 2020\"\n page in \"best_books_2020.htm\". This function should create a BeautifulSoup object from a \n filepath and return a list of (category, book title, URL) tuples.\n \n For example, if the best book in category \"Fiction\" is \"The Testaments (The Handmaid's Tale, #2)\", with URL\n https://www.goodreads.com/choiceawards/best-fiction-books-2020, then you should append \n (\"Fiction\", \"The Testaments (The Handmaid's Tale, #2)\", \"https://www.goodreads.com/choiceawards/best-fiction-books-2020\") \n to your list of tuples.\n \"\"\"\n pass\n\n\ndef write_csv(data, filename):\n\n with open(filename, mode='w') as csvfile:\n\n data_writer = csv.writer(csvfile, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n data_writer.writerow([\"Book title\", \"Author Name\"])\n \n for element in data:\n data_writer.writerow([element[0], element[1]])\n\n csvfile.close()\n\n \"\"\"\n Write a function that takes in a list of tuples (called data, i.e. the\n one that is returned by get_titles_from_search_results()), writes the data to a \n csv file, and saves it to the passed filename.\n\n The first row of the csv should contain \"Book Title\" and \"Author Name\", and\n respectively as column headers. For each tuple in data, write a new\n row to the csv, placing each element of the tuple in the correct column.\n\n When you are done your CSV file should look like this:\n\n Book title,Author Name\n Book1,Author1\n Book2,Author2\n Book3,Author3\n ......\n\n This function should not return anything.\n \"\"\"\n pass\n\n\ndef extra_credit(filepath):\n\n \"\"\"\n EXTRA CREDIT\n\n Please see the instructions document for more information on how to complete this function.\n You do not have to write test cases for this function.\n \"\"\"\n pass\n\nclass TestCases(unittest.TestCase):\n\n search_urls = get_search_links()\n\n #search_urls = get_search_links()\n\n # call get_search_links() and save it to a static variable: search_urls\n\n\n def test_get_titles_from_search_results(self):\n\n # call get_titles_from_search_results() on search_results.htm and save to a local variable\n local_variable_1 = get_titles_from_search_results(\"search_results.htm\")\n\n # check that the number of titles extracted is correct (20 titles)\n self.assertEqual(len(local_variable_1), 20)\n\n # check that the variable you saved after calling the function is a list\n self.assertEqual(type(local_variable_1), list)\n\n # check that each item in the list is a tuple\n for item in local_variable_1:\n self.assertEqual(type(item), tuple)\n\n # check that the first book and author tuple is correct (open search_results.htm and find it)\n self.assertEqual(local_variable_1[0][0], \"Harry Potter and the Deathly Hallows (Harry Potter, #7)\")\n self.assertEqual(local_variable_1[0][1], \"J.K. Rowling\")\n\n # check that the last title is correct (open search_results.htm and find it)\n self.assertEqual(local_variable_1[len(local_variable_1)-1][0], \"Harry Potter: The Prequel (Harry Potter, #0.5)\")\n self.assertEqual(local_variable_1[len(local_variable_1)-1][1], \"J.K. Rowling\")\n\n def test_get_search_links(self):\n\n # check that TestCases.search_urls is a list\n self.assertEqual(type(TestCases.search_urls), list)\n\n # check that the length of TestCases.search_urls is correct (10 URLs)\n self.assertEqual(len(TestCases.search_urls), 10)\n\n # check that each URL in the TestCases.search_urls is a string\n for element in TestCases.search_urls:\n self.assertEqual(type(element), str)\n\n # check that each URL contains the correct url for Goodreads.com followed by /book/show/\n for element in TestCases.search_urls:\n self.assertTrue(\"goodreads.com/book/show/\" in element)\n\n def test_get_book_summary(self):\n\n # for each URL in TestCases.search_urls (should be a list of tuples)\n list_tuple = []\n for element in TestCases.search_urls:\n list_tuple.append(get_book_summary(element))\n\n # check that the number of book summaries is correct (10)\n self.assertEqual(len(list_tuple), 10) \n\n # check that each item in the list is a tuple\n for element in list_tuple:\n self.assertEqual(type(element), tuple)\n\n # check that each tuple has 3 elements\n for element in list_tuple:\n self.assertEqual(len(element), 3)\n\n # check that the first two elements in the tuple are string\n for element in list_tuple:\n self.assertEqual(type(element[0]), str)\n self.assertEqual(type(element[1]), str)\n\n # check that the third element in the tuple, i.e. pages is an int\n for element in list_tuple:\n self.assertEqual(type(element[2]), int)\n\n # check that the first book in the search has 337 pages\n self.assertEqual(list_tuple[0][2], 337)\n\n\n def test_summarize_best_books(self):\n\n # call summarize_best_books and save it to a variable\n source_dir = os.path.dirname(__file__)\n fullpath = os.path.join(source_dir, \"best_books_2020.htm\")\n best_books = summarize_best_books(fullpath)\n\n # check that we have the right number of best books (20)\n self.assertEqual(len(best_books), 20)\n\n # assert each item in the list of best books is a tuple\n for element in best_books:\n self.assertEqual(type(element), tuple)\n\n\n # check that each tuple has a length of 3\n for element in best_books:\n self.assertEqual(len(element), 3)\n\n # check that the first tuple is made up of the following 3 strings:'Fiction', \"The Midnight Library\", 'https://www.goodreads.com/choiceawards/best-fiction-books-2020'\n self.assertEqual(best_books[0], ('Fiction', \"The Midnight Library\", 'https://www.goodreads.com/choiceawards/best-fiction-books-2020'))\n\n # check that the last tuple is made up of the following 3 strings: 'Picture Books', 'Antiracist Baby', 'https://www.goodreads.com/choiceawards/best-picture-books-2020'\n self.assertEqual(best_books[len(best_books)-1], ('Picture Books', 'Antiracist Baby', 'https://www.goodreads.com/choiceawards/best-picture-books-2020'))\n\n\n def test_write_csv(self):\n\n # call get_titles_from_search_results on search_results.htm and save the result to a variable\n chosen_titles = get_titles_from_search_results(\"search_results.htm\")\n\n # call write csv on the variable you saved and 'test.csv'\n write_csv(chosen_titles, \"test.csv\")\n\n # read in the csv that you wrote (create a variable csv_lines - a list containing all the lines in the csv you just wrote to above)\n f = open('test.csv')\n csv_reader = csv.reader(f, delimiter=',')\n csv_lines = [r for r in csv_reader]\n\n # check that there are 21 lines in the csv\n self.assertEqual(len(csv_lines), 21)\n\n # check that the header row is correct\n self.assertEqual(csv_lines[0],[\"Book title\",\"Author Name\"])\n\n # check that the next row is 'Harry Potter and the Deathly Hallows (Harry Potter, #7)', 'J.K. Rowling'\n self.assertEqual(csv_lines[1],['Harry Potter and the Deathly Hallows (Harry Potter, #7)', 'J.K. Rowling'])\n\n # check that the last row is 'Harry Potter: The Prequel (Harry Potter, #0.5)', 'J.K. Rowling'\n self.assertEqual(csv_lines[len(csv_lines)-1],['Harry Potter: The Prequel (Harry Potter, #0.5)', 'J.K. Rowling'])\n\n f.close()\n\n\nif __name__ == '__main__':\n print(extra_credit(\"extra_credit.htm\"))\n unittest.main(verbosity=2)\n\n\n\n","sub_path":"Project2.py","file_name":"Project2.py","file_ext":"py","file_size_in_byte":11842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"248615582","text":"# -*- coding: utf-8 -*-\n# Copyright 2019 Red Hat\n# GNU General Public License v3.0+\n# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\"\"\"\nThe facts class for asa\nthis file validates each subset of facts and selectively\ncalls the appropriate facts gathering function\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\n\nfrom ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts import (\n FactsBase,\n)\nfrom ansible_collections.cisco.asa.plugins.module_utils.network.asa.facts.acls.acls import (\n AclsFacts,\n)\nfrom ansible_collections.cisco.asa.plugins.module_utils.network.asa.facts.ogs.ogs import (\n OGsFacts,\n)\nfrom ansible_collections.cisco.asa.plugins.module_utils.network.asa.facts.legacy.base import (\n Default,\n Hardware,\n Config,\n)\n\n\nFACT_LEGACY_SUBSETS = dict(default=Default, hardware=Hardware, config=Config)\n\nFACT_RESOURCE_SUBSETS = dict(acls=AclsFacts, ogs=OGsFacts)\n\n\nclass Facts(FactsBase):\n \"\"\" The fact class for asa\n \"\"\"\n\n VALID_LEGACY_GATHER_SUBSETS = frozenset(FACT_LEGACY_SUBSETS.keys())\n VALID_RESOURCE_SUBSETS = frozenset(FACT_RESOURCE_SUBSETS.keys())\n\n def __init__(self, module):\n super(Facts, self).__init__(module)\n\n def get_facts(\n self, legacy_facts_type=None, resource_facts_type=None, data=None\n ):\n \"\"\" Collect the facts for asa\n :param legacy_facts_type: List of legacy facts types\n :param resource_facts_type: List of resource fact types\n :param data: previously collected conf\n :rtype: dict\n :return: the facts gathered\n \"\"\"\n if self.VALID_RESOURCE_SUBSETS:\n self.get_network_resources_facts(\n FACT_RESOURCE_SUBSETS, resource_facts_type, data\n )\n\n if self.VALID_LEGACY_GATHER_SUBSETS:\n self.get_network_legacy_facts(\n FACT_LEGACY_SUBSETS, legacy_facts_type\n )\n\n return self.ansible_facts, self._warnings\n","sub_path":"intro-ansible/venv3/lib/python3.8/site-packages/ansible_collections/cisco/asa/plugins/module_utils/network/asa/facts/facts.py","file_name":"facts.py","file_ext":"py","file_size_in_byte":2018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"395660231","text":"from equations import P_X_given_Y_statekeep\n\nclass State:\n def __init__(self, model, transitionProb, PHRED=0.1, ALPHABET='ACTG'):\n self.phred = PHRED\n self.nextState = transitionProb\n self.alphabet = ALPHABET\n self.occurence = {}\n self.model = model\n self.M_NO_ERROR = {}\n self.ERROR_SUBSTITUTIONS_DEST = {}\n self.start = {}\n self.end = {}\n\n for x in self.alphabet:\n self.occurence[x] = sum([1 if c is x else 0 for c in self.model]) / len(self.model)\n self.start[x] = 1-self.phred if model[0]==x else self.phred/(len(self.alphabet)-1)\n self.end[x] = 1-self.phred if model[-1]==x else self.phred/(len(self.alphabet)-1)\n self.ERROR_SUBSTITUTIONS_DEST[x] = {y : 0 if x==y else 1/(len(self.alphabet)-1) for y in self.alphabet}\n\n curmodel = model+model[0]\n\n for x in self.alphabet:\n self.M_NO_ERROR[x] = {}\n for y in self.alphabet:\n self.M_NO_ERROR[x][y] = 0\n\n num_pairs = len(curmodel) - 1\n for i in range(num_pairs):\n self.M_NO_ERROR[ curmodel[i] ][ curmodel[i+1] ] += 1\n\n for x in self.alphabet:\n if x not in self.model:\n for y in self.alphabet:\n self.M_NO_ERROR[x][y] = 1/len(self.alphabet)\n else:\n total_count = 0\n for y in self.alphabet:\n total_count += self.M_NO_ERROR[x][y]\n for y in self.alphabet:\n self.M_NO_ERROR[x][y] /= total_count\n\n\n # first order probability matrix\n\n self.P_X_Y = {}\n for x in self.alphabet:\n self.P_X_Y[x] = {}\n for y in self.alphabet:\n self.P_X_Y[x][y] = P_X_given_Y_statekeep(self, x, y)\n","sub_path":"HMM/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"111221442","text":"from typing import Optional\n\nfrom simsapa import PACKAGE_ASSETS_DIR, SUTTAS_CSS, SUTTAS_JS\nfrom mako.template import Template\n\nopen_sutta_links_js_tmpl = Template(filename=str(PACKAGE_ASSETS_DIR.joinpath('templates/open_sutta_links.js')))\npage_tmpl = Template(filename=str(PACKAGE_ASSETS_DIR.joinpath('templates/page.html')))\n\n\ndef html_page(content: str,\n api_url: Optional[str] = None,\n css_extra: Optional[str] = None,\n js_extra: Optional[str] = None):\n\n css = SUTTAS_CSS\n if api_url is not None:\n css = css.replace(\"http://localhost:8000\", api_url)\n\n if css_extra:\n css += \"\\n\\n\" + css_extra\n\n # NOTE not using this atm\n # js = str(open_sutta_links_js_tmpl.render(api_url=api_url))\n\n js = \"\"\n\n if js_extra:\n js += \"\\n\\n\" + js_extra\n\n if not js_extra or 'SHOW_BOOKMARKS' not in js_extra:\n js += \"const SHOW_BOOKMARKS = false;\";\n\n js += SUTTAS_JS\n\n html = str(page_tmpl.render(content=content,\n css_head=css,\n js_head=js,\n js_body='',\n api_url=api_url))\n\n return html\n","sub_path":"simsapa/layouts/html_content.py","file_name":"html_content.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"214317743","text":"import numpy as np\nfrom .simparam import SimParam\nfrom .simstate import SimState\nfrom .simresult import SimResult\nfrom .slot import TreeSlot\nfrom .treestate import TreeState\nfrom .branchnode import BranchNode\nfrom . import packetlist\n\n\nclass Simulation(object):\n \"\"\"\n This Holds the entire Simulation object, whose parameters we update according to the outcomes\n \"\"\"\n\n def __init__(self, setting):\n # Load simulation parameters\n self.sim_param = SimParam(setting)\n # Load the simulation state parameters\n self.sim_state = SimState()\n # Load the result parameters\n self.sim_result = SimResult()\n # Load the class which perfomrs all the methods governing a simple slot\n self.slot = TreeSlot()\n # Load the branch node which keeps track of a tree\n self.branch_node = BranchNode()\n # Create an array of integers of which will contain all active nodes.\n self.active_array = []\n # For gated access, the arrived packets are put into a queue\n self.queue_array = []\n # The number of packets generated in a single slot\n self.packets_gen = 0\n # THe result of a slot\n self.result = 0\n # The current slot no\n self.slot_no = 0\n # Load the parameters for single tree resolution\n self.tree_state = TreeState(self)\n\n def reset(self, setting):\n self.sim_param = SimParam(setting)\n self.sim_state = SimState()\n self.sim_result = SimResult()\n self.slot = TreeSlot()\n self.active_array = []\n self.queue_array = []\n self.packets_gen = 0\n self.result = 0\n self.slot_no = 0\n self.tree_state = TreeState(self)\n self.branch_node.reset()\n\n def do_simulation_simple_tree_static(self, collided_packets):\n \"\"\"\n Static Simulation, when the number of in initial collided packets is given, it is essentially a single tree res\n :param collided_packets: the no of packets in the resolution\n\n \"\"\"\n # Load active array with the collided packets\n if collided_packets > self.sim_param.K:\n self.packets_gen = collided_packets\n packetlist.add_packets_to_tree(self)\n self.tree_state.reset(self)\n # Run the simulation as long as all packets are processed and tree is over\n while self.tree_state.gate_open:\n # Increment the slot\n self.slot_no += 1\n # Simulate the processes that would happen in the tx and rx in one slot, update the active array\n self.slot.oneslotprocess(self)\n # Update the simstate metrics according to the result of the simulation\n self.tree_state.update_metrics(self)\n # check if all the packets are processed and the tree is at its last branch\n if len(self.active_array) == 0 and len(self.branch_node.branch_status) == 0:\n self.tree_state.gate_open = False\n # update the metrics from a tree to the simulation state\n self.sim_state.update_metrics(self)\n # Update the results\n self.sim_result.get_result(self)\n else:\n self.sim_result.throughput = 0\n self.sim_result.magic_throughput = 0\n","sub_path":"sim_scripts/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"7270039","text":"import pygame\nclock = pygame.time.Clock()\n\nscreen = pygame.display.set_mode((640,480))\n\nt = 1\nt_dir = 1\nrunning = True\nwhile running: \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n screen.fill((0,0,0))\n pygame.draw.circle(screen, (00, t, 00), (320,240),25)\n pygame.display.update()\n\n t += t_dir\n if t == 0 or t == 255:\n t_dir = t_dir * -1\n clock.tick(100)\n\npygame.quit()\n\n","sub_path":"loops/pygameq1.py","file_name":"pygameq1.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"289113634","text":"# Copyright 2016 Mirantis, 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\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport fileinput\nimport os\n\nfrom proboscis import asserts\nfrom proboscis import test\nimport yaml\n\nfrom fuelweb_test import logger\nfrom fuelweb_test.helpers.decorators import log_snapshot_after_test\nfrom fuelweb_test.helpers.ssh_manager import SSHManager\nfrom fuelweb_test.settings import DEPLOYMENT_MODE\nfrom fuelweb_test.settings import NEUTRON_SEGMENT\nfrom fuelweb_test.tests.base_test_case import SetupEnvironment\nfrom fuelweb_test.tests.base_test_case import TestBasic\n\n\n# NOTE: Setup yaml to work with puppet report\ndef construct_ruby_object(loader, suffix, node):\n \"\"\"Define a specific constructor\"\"\"\n return loader.construct_yaml_map(node)\n\n\ndef construct_ruby_sym(loader, node):\n \"\"\"Define a specific multi constructor\"\"\"\n return loader.construct_yaml_str(node)\n\n\nTASKS_BLACKLIST = [\n \"pre_hiera_config\",\n \"reboot_provisioned_nodes\",\n \"hiera\",\n \"configure_default_route\",\n \"netconfig\",\n \"upload_provision_data\"]\n\n\nSETTINGS_SKIPLIST = (\n \"dns_list\",\n \"ntp_list\",\n \"repo_setup\"\n)\n\n\nclass DeprecatedFixture(Exception):\n def __init__(self, msg):\n super(DeprecatedFixture, self).__init__(msg)\n\n\nclass LCMTestBasic(TestBasic):\n \"\"\"LCMTestBasic.\"\"\" # TODO documentation\n\n def __init__(self):\n super(LCMTestBasic, self).__init__()\n yaml.add_multi_constructor(u\"!ruby/object:\", construct_ruby_object)\n yaml.add_constructor(u\"!ruby/sym\", construct_ruby_sym)\n\n @staticmethod\n def node_roles(node):\n \"\"\"Compose a string that represents all roles assigned to given node\n\n :param node: dict, node data\n :return: str\n \"\"\"\n return \"_\".join(sorted(node[\"roles\"]))\n\n # FIXME: after implementation of the main functional of PROD-2510\n @staticmethod\n def get_nodes_tasks(node_id):\n \"\"\"\n :param node_id: an integer number of node id\n :return: a set of deployment tasks for corresponding node\n \"\"\"\n tasks = set()\n ssh = SSHManager()\n\n result = ssh.execute_on_remote(ssh.admin_ip, \"ls /var/log/astute\")\n filenames = [filename.strip() for filename in result['stdout']]\n\n for filename in filenames:\n ssh.download_from_remote(\n ssh.admin_ip,\n destination=\"/var/log/astute/{0}\".format(filename),\n target=\"/tmp/{0}\".format(filename))\n\n data = fileinput.FileInput(\n files=[\"/tmp/{0}\".format(filename) for filename in filenames],\n openhook=fileinput.hook_compressed)\n for line in data:\n if \"Task time summary\" in line \\\n and \"node {}\".format(node_id) in line:\n # FIXME: define an exact search of task\n task_name = line.split(\"Task time summary: \")[1].split()[0]\n check = any([excluded_task in task_name\n for excluded_task in TASKS_BLACKLIST])\n if check:\n continue\n tasks.add(task_name)\n return tasks\n\n @staticmethod\n def get_task_type(tasks, task_id):\n \"\"\"Get task type\n\n :param tasks: a list of dictionaries with task description\n :param task_id: a string, name of deployment task\n :return: a string of task type or a boolean value \"False\"\n \"\"\"\n for task in tasks:\n if task.get('id', '') == task_id:\n return task.get('type', False)\n return False\n\n @staticmethod\n def get_puppet_report(node):\n \"\"\"Get puppet run report from corresponding node\n\n :param node: a dictionary with node description\n :return: a dictionary with puppet report data\n \"\"\"\n ssh = SSHManager()\n ip = node['ip']\n report_file = \"/var/lib/puppet/state/last_run_report.yaml\"\n asserts.assert_true(ssh.isfile_on_remote(ip, report_file),\n 'File {!r} not found on node {!r}'\n .format(report_file, node['id']))\n with ssh.open_on_remote(ip, report_file) as f:\n data = yaml.load(f)\n ssh.rm_rf_on_remote(ip, report_file)\n return data\n\n @staticmethod\n def load_fixture(deployment_type, role, idmp=True):\n \"\"\"Load fixture for corresponding kind of deployment\n\n :param deployment_type: a string, name of the deployment kind\n :param role: a string, node role\n :param idmp: bool, indicates whether idempotency or ensurability\n fixture is loaded\n :return: a dictionary with loaded fixture data\n \"\"\"\n subdir = \"idempotency\" if idmp else \"ensurability\"\n fixture_path = os.path.join(\n os.path.dirname(__file__), \"fixtures\",\n deployment_type, subdir, \"{}.yaml\".format(role))\n with open(fixture_path) as f:\n fixture = yaml.load(f)\n\n default_attrs = {\"no_puppet_run\": False,\n \"type\": \"puppet\",\n \"skip\": []}\n\n # NOTE: Populate fixture with default values\n for task in fixture['tasks']:\n task_name, task_attrs = task.items()[0]\n if task_attrs is None:\n task_attrs = {}\n\n for default_attr, default_value in default_attrs.items():\n if default_attr not in task_attrs:\n task_attrs[default_attr] = default_value\n\n task[task_name] = task_attrs\n return fixture\n\n def get_fixture_relevance(self, actual_tasks, fixture):\n \"\"\"Get fixture relevance between actual deployment tasks\n and tasks from fixture files\n\n :param actual_tasks: a list of actual tasks\n :param fixture: a dictionary with fixture data\n :return: a tuple of task sets\n \"\"\"\n actual_tasks = set(actual_tasks)\n fixture_tasks = set([i.keys()[0] for i in fixture[\"tasks\"]])\n tasks_description = self.env.admin_actions.get_tasks_description()\n\n extra_actual_tasks = actual_tasks.difference(fixture_tasks)\n extra_fixture_tasks = fixture_tasks.difference(actual_tasks)\n\n # NOTE: in ideal case we need to avoid tasks with wrong types\n wrong_types = {}\n for task in fixture[\"tasks\"]:\n task_name, attrs = task.items()[0]\n expected_type = self.get_task_type(tasks_description, task_name)\n if not expected_type:\n logger.error(\"No type or no such task {!r}\".format(task_name))\n else:\n if expected_type != attrs[\"type\"]:\n wrong_types.update({task_name: expected_type})\n\n logger.info(\"Actual tasks {}contain extra tasks: {}\"\n .format(\"\" if extra_actual_tasks else \"don't \",\n extra_actual_tasks))\n logger.info(\"Fixture tasks {}contain extra tasks: {}\"\n .format(\"\" if extra_fixture_tasks else \"don't \",\n extra_fixture_tasks))\n\n return extra_actual_tasks, extra_fixture_tasks, wrong_types\n\n def define_pr_ctrl(self):\n \"\"\"Define primary controller\n\n :return: dict, node info\n \"\"\"\n devops_pr_controller = self.fuel_web.get_nailgun_primary_node(\n self.env.d_env.nodes().slaves[0])\n\n pr_ctrl = self.fuel_web.get_nailgun_node_by_devops_node(\n devops_pr_controller)\n return pr_ctrl\n\n def check_extra_tasks(self, slave_nodes, deployment, idmp=True, ha=False):\n \"\"\"Check existing extra tasks regarding to fixture and actual task\n or tasks with a wrong type\n\n :param slave_nodes: a list of nailgun nodes\n :param deployment: a string, name of the deployment kind\n :param idmp: bool, indicates whether idempotency or ensurability\n fixture is checked\n :param ha: bool, indicates ha mode is enabled or disabled\n :return: a list with nodes for which extra tasks regarding to fixture\n and actual task or tasks with a wrong type were found\n \"\"\"\n result = {'extra_actual_tasks': {},\n 'extra_fixture_tasks': {},\n 'wrong_types': {},\n 'failed_tasks': {}}\n\n pr_ctrl = self.define_pr_ctrl() if ha else {}\n for node in slave_nodes:\n node_roles = self.node_roles(node)\n if node.get('name') == pr_ctrl.get('name', None):\n node_roles = 'primary-' + node_roles\n node_ref = \"{}_{}\".format(node[\"id\"], node_roles)\n fixture = self.load_fixture(deployment, node_roles, idmp)\n node_tasks = self.get_nodes_tasks(node[\"id\"])\n extra_actual_tasks, extra_fixture_tasks, wrong_types = \\\n self.get_fixture_relevance(node_tasks, fixture)\n result['extra_actual_tasks'][node_ref] = extra_actual_tasks\n result['extra_fixture_tasks'][node_ref] = extra_fixture_tasks\n result['wrong_types'][node_ref] = wrong_types\n result['failed_tasks'][node_ref] = \\\n extra_actual_tasks | \\\n extra_fixture_tasks | \\\n set([task for task in wrong_types.keys()])\n\n logger.warning(\"Uncovered deployment tasks:\\n{}\"\n .format(yaml.dump(result, default_flow_style=False)))\n failed_nodes = [node_refs\n for node_refs, failed_tasks in\n result['failed_tasks'].items()\n if failed_tasks]\n return failed_nodes\n\n def generate_fixture(self, node_refs, cluster_id, slave_nodes, ha=False):\n \"\"\"Generate fixture with description of task idempotency\n\n :param node_refs: a string, refs to nailgun node\n :param cluster_id: an integer, number of cluster id\n :param slave_nodes: a list of nailgun nodes\n :param ha: bool, indicates ha mode is enabled or disabled\n :return: None\n \"\"\"\n result = {}\n pr_ctrl = self.define_pr_ctrl() if ha else {}\n for node in slave_nodes:\n node_roles = self.node_roles(node)\n if node.get('name') == pr_ctrl.get('name', None):\n node_roles = 'primary-' + node_roles\n node_ref = \"{}_{}\".format(node[\"id\"], node_roles)\n if node_ref not in node_refs:\n logger.debug('Node {!r} was skipped because the current '\n 'fixtures are actual for deployment tasks which '\n 'are executed on this node'.format(node_ref))\n continue\n node_tasks = self.get_nodes_tasks(node[\"id\"])\n tasks_description = self.env.admin_actions.get_tasks_description()\n tasks = []\n\n for task in node_tasks:\n task_type = self.get_task_type(tasks_description, task)\n if task_type != \"puppet\":\n logger.info(\"Skip checking of {!r} task,it is not puppet\"\n .format(task))\n tasks.append({task: {\"type\": task_type}})\n continue\n\n self.fuel_web.execute_task_on_node(task, node[\"id\"],\n cluster_id)\n\n try:\n report = self.get_puppet_report(node)\n except AssertionError:\n # NOTE: in ideal case we need to avoid puppet\n # tasks with \"no_puppet_run\": True\n tasks.append({task: {\"no_puppet_run\": True}})\n msg = (\"Unexpected no_puppet_run for task: {}\"\n .format(task))\n logger.info(msg)\n continue\n\n failed = False\n task_resources = []\n\n for res_name, res_stats in report['resource_statuses'].items():\n if res_stats['changed']:\n failed = True\n msg = (\"Non-idempotent task {!r}, resource: {}\"\n .format(task, res_name))\n logger.error(msg)\n task_resources.append(res_name)\n\n if failed:\n tasks.append({\n task: {\"skip\": task_resources}\n })\n else:\n tasks.append({\n task: None\n })\n logger.info(\n \"Task {!r} on node {!r} was executed successfully\"\n .format(task, node['id']))\n\n result.update(\n {\n node_ref: {\n \"role\": node_roles,\n \"tasks\": tasks\n }\n }\n )\n\n logger.info(\"Generated fixture:\\n{}\"\n .format(yaml.dump(result, default_flow_style=False)))\n\n @staticmethod\n def _parse_settings(settings):\n \"\"\"Select only values and their types from settings\n\n :param settings: dict, (env or node) settings\n :return: dict, settings in short format\n \"\"\"\n parsed = {}\n for group in settings:\n if group in SETTINGS_SKIPLIST:\n continue\n parsed[group] = {}\n for attr, params in settings[group].items():\n if attr in SETTINGS_SKIPLIST:\n continue\n try:\n parsed[group][attr] = {\n 'value': params['value'],\n 'type': params['type']\n }\n except KeyError:\n logger.debug(\"Do not include {} setting as it doesn't \"\n \"have value\".format(params['label']))\n if not parsed[group]:\n logger.debug(\"Do not include {} group as it doesn't have \"\n \"settings with values\".format(group))\n del parsed[group]\n return parsed\n\n @staticmethod\n def _get_settings_difference(settings1, settings2):\n \"\"\"Select values and/or groups of set1 that are not present in set2\n\n :param settings1: dict, group of dicts\n :param settings2: dict, group of dicts\n :return: dict, set1 items not present in set2\n \"\"\"\n diff = {}\n new_groups = set(settings1) - set(settings2)\n if new_groups:\n diff.update([(g, settings1[g]) for g in new_groups])\n for group in settings1:\n if group in new_groups:\n continue\n new_params = set(settings1[group]) - set(settings2[group])\n if new_params:\n diff[group] = {}\n diff[group].update(\n [(s, settings1[group][s]) for s in new_params])\n return diff\n\n def _cmp_settings(self, settings, fixtures):\n \"\"\"Compare current and stored settings\n\n Return values and/or groups of settings that are new, comparing to\n what is stored in fixtures.\n Return values and/or groups of settings in fixtures that are outdated,\n comparing to what is available in the cluster under test.\n\n :param settings: dict, current settings in short format\n :param fixtures: dict, stored settings in short format\n :return: tuple, (new settings, outdated settings) pair\n \"\"\"\n new_s = self._get_settings_difference(settings, fixtures)\n outdated_f = self._get_settings_difference(fixtures, settings)\n return new_s, outdated_f\n\n def get_cluster_settings(self, cluster_id):\n \"\"\"Get cluster settings and return them in short format\n\n :param cluster_id: int, ID of the cluster under test\n :return: dict, cluster settings in short format\n \"\"\"\n settings = self.fuel_web.client.get_cluster_attributes(\n cluster_id)['editable']\n return self._parse_settings(settings)\n\n def get_nodes_settings(self, cluster_id):\n \"\"\"Get node settings and return them in short format\n\n :param cluster_id: int, ID of the cluster under test\n :return: dict, node settings in short format\n \"\"\"\n nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n\n node_settings = {}\n for node in nodes:\n node_attrs = self.fuel_web.client.get_node_attributes(node['id'])\n roles = self.node_roles(node)\n node_settings[roles] = self._parse_settings(node_attrs)\n return node_settings\n\n @staticmethod\n def load_settings_fixtures(deployment):\n \"\"\"Load stored settings for the given cluster configuration\n\n :param deployment: str, name of cluster configuration\n (e.g. 1_ctrl_1_cmp_1_cinder)\n :return: tuple, (cluster, nodes) pair of stored settings\n \"\"\"\n f_path = os.path.join(os.path.dirname(__file__), \"fixtures\",\n deployment, \"ensurability\", \"{}\")\n\n with open(f_path.format(\"cluster_settings.yaml\")) as f:\n cluster_fixture = yaml.load(f)\n with open(f_path.format(\"nodes_settings.yaml\")) as f:\n nodes_fixture = yaml.load(f)\n\n return cluster_fixture, nodes_fixture\n\n def check_cluster_settings_consistency(self, settings, fixtures):\n \"\"\"Check if stored cluster settings require update\n\n :param settings: dict, settings of the cluster under test\n :param fixtures: dict, stored cluster settings\n :return: tuple, (new settings, outdated settings) pair; this indicates\n whether fixtures require update\n \"\"\"\n return self._cmp_settings(settings, fixtures)\n\n def check_nodes_settings_consistency(self, settings, fixtures):\n \"\"\"Check if stored node settings require update\n\n :param settings: dict, node settings of the cluster under test\n :param fixtures: dict, stored node settings\n :return: tuple, (new settings, outdated settings) pair; this indicates\n whether fixtures require update\n \"\"\"\n new_settings = {}\n outdated_fixtures = {}\n for node in fixtures:\n new_s, outdated_f = self._cmp_settings(\n settings[node], fixtures[node])\n if new_s:\n new_settings[node] = new_s\n if outdated_f:\n outdated_fixtures[node] = outdated_f\n return new_settings, outdated_fixtures\n\n def check_settings_consistency(self, deployment, cluster_id):\n \"\"\"Check if settings fixtures are up to date.\n\n :param cluster_id: int, env under test\n :param deployment: str, name of env configuration under test\n :return: None\n \"\"\"\n cluster_f, nodes_f = self.load_settings_fixtures(deployment)\n cluster_s = self.get_cluster_settings(cluster_id)\n nodes_s = self.get_nodes_settings(cluster_id)\n\n consistency = {}\n new_cluster_s, old_cluster_f = \\\n self.check_cluster_settings_consistency(cluster_s, cluster_f)\n new_nodes_s, old_nodes_f = \\\n self.check_nodes_settings_consistency(nodes_s, nodes_f)\n\n consistency[\"fixtures\"] = {\n 'old_cluster_fixtures': old_cluster_f,\n 'old_nodes_fixtures': old_nodes_f\n }\n consistency[\"settings\"] = {\n 'new_cluster_settings': new_cluster_s,\n 'new_nodes_settings': new_nodes_s\n }\n\n nonconsistent = False\n if new_cluster_s or new_nodes_s.values():\n logger.info(\n \"Settings fixtures require update as new options are \"\n \"available now for configuring an environment\\n{}\".format(\n yaml.safe_dump(consistency[\"settings\"],\n default_flow_style=False))\n )\n nonconsistent = True\n if old_cluster_f or old_nodes_f.values():\n logger.info(\n \"Settings fixtures require update as some options are no \"\n \"longer available for configuring an environment\\n{}\".format(\n yaml.safe_dump(consistency[\"fixtures\"],\n default_flow_style=False))\n )\n nonconsistent = True\n if nonconsistent:\n self.generate_settings_fixture(cluster_id)\n msg = ('Please update setting fixtures in the repo '\n 'according to generated data')\n raise DeprecatedFixture(msg)\n\n def generate_settings_fixture(self, cluster_id):\n \"\"\"Get environment and nodes settings, and print them to console.\n\n :return: None\n \"\"\"\n cluster_s = self.get_cluster_settings(cluster_id)\n nodes_s = self.get_nodes_settings(cluster_id)\n\n logger.info(\"Generated environment settings fixture:\\n{}\".format(\n yaml.safe_dump(cluster_s, default_flow_style=False)))\n logger.info(\"Generated nodes settings fixture:\\n{}\".format(\n yaml.safe_dump(nodes_s, default_flow_style=False)))\n\n def enable_hugepages(self, node_ids):\n \"\"\"Updates settings of the given nodes to enable hugepages\n\n :param node_ids: list, node IDs\n :return: None\n \"\"\"\n for node_id in node_ids:\n settings = self.fuel_web.client.get_node_attributes(\n node_id)\n settings['hugepages']['nova']['value']['2048'] = 10\n self.fuel_web.client.upload_node_attributes(settings, node_id)\n\n\n@test(groups=['deploy_lcm_environment'])\nclass SetupLCMEnvironment(LCMTestBasic):\n @test(depends_on=[SetupEnvironment.prepare_slaves_3],\n groups=['lcm_deploy_1_ctrl_1_cmp_1_cinder'])\n @log_snapshot_after_test\n def lcm_deploy_1_ctrl_1_cmp_1_cinder(self):\n \"\"\"Create cluster with cinder\n\n Scenario:\n 1. Revert snapshot \"ready_with_3_slaves\"\n 2. Create cluster\n 3. Add 1 controller\n 4. Add 1 compute node\n 5. Add 1 cinder node\n 6. Deploy cluster\n 7. Check extra deployment tasks\n\n Duration 180m\n Snapshot: \"lcm_deploy_1_ctrl_1_cmp_1_cinder\"\n \"\"\"\n deployment = '1_ctrl_1_cmp_1_cinder'\n snapshotname = 'lcm_deploy_{}'.format(deployment)\n self.check_run(snapshotname)\n self.show_step(1)\n self.env.revert_snapshot(\"ready_with_3_slaves\")\n\n self.show_step(2)\n segment_type = NEUTRON_SEGMENT['tun']\n cluster_id = self.fuel_web.create_cluster(\n name=self.__class__.__name__,\n mode=DEPLOYMENT_MODE,\n settings={\n \"net_segment_type\": segment_type\n }\n )\n self.show_step(3)\n self.show_step(4)\n self.show_step(5)\n self.fuel_web.update_nodes(\n cluster_id,\n {\n 'slave-01': ['controller'],\n 'slave-02': ['compute'],\n 'slave-03': ['cinder']\n }\n )\n\n self.show_step(6)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n self.enable_hugepages([node['id'] for node in slave_nodes])\n self.fuel_web.deploy_cluster_wait(cluster_id)\n self.show_step(7)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n node_refs = self.check_extra_tasks(slave_nodes, deployment)\n if node_refs:\n logger.info('Generating a new fixture . . .')\n self.generate_fixture(node_refs, cluster_id, slave_nodes)\n msg = ('Please update idempotency fixtures in the repo '\n 'according to generated fixtures')\n raise DeprecatedFixture(msg)\n self.env.make_snapshot(snapshotname, is_make=True)\n\n @test(depends_on=[SetupEnvironment.prepare_slaves_3],\n groups=['lcm_deploy_1_ctrl_1_cmp_1_mongo'])\n @log_snapshot_after_test\n def lcm_deploy_1_ctrl_1_cmp_1_mongo(self):\n \"\"\"Create cluster with Ceilometer\n\n Scenario:\n 1. Revert snapshot \"ready_with_3_slaves\"\n 2. Create cluster\n 3. Add 1 controller\n 4. Add 1 compute node\n 5. Add 1 mongo node\n 6. Deploy cluster\n 7. Check extra deployment tasks\n\n Duration 180m\n Snapshot: \"lcm_deploy_1_ctrl_1_cmp_1_mongo\"\n \"\"\"\n deployment = '1_ctrl_1_cmp_1_mongo'\n snapshotname = 'lcm_deploy_{}'.format(deployment)\n self.check_run(snapshotname)\n self.show_step(1)\n self.env.revert_snapshot(\"ready_with_3_slaves\")\n\n self.show_step(2)\n segment_type = NEUTRON_SEGMENT['vlan']\n cluster_id = self.fuel_web.create_cluster(\n name=self.__class__.__name__,\n mode=DEPLOYMENT_MODE,\n settings={\n 'ceilometer': True,\n 'net_segment_type': segment_type\n }\n )\n self.show_step(3)\n self.show_step(4)\n self.show_step(5)\n self.fuel_web.update_nodes(\n cluster_id,\n {\n 'slave-01': ['controller'],\n 'slave-02': ['compute'],\n 'slave-03': ['mongo']\n }\n )\n\n self.show_step(6)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n self.enable_hugepages([node['id'] for node in slave_nodes])\n self.fuel_web.deploy_cluster_wait(cluster_id)\n self.show_step(7)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n node_refs = self.check_extra_tasks(slave_nodes, deployment)\n if node_refs:\n logger.info('Generating a new fixture . . .')\n self.generate_fixture(node_refs, cluster_id, slave_nodes)\n msg = ('Please update idempotency fixtures in the repo '\n 'according to generated fixtures')\n raise DeprecatedFixture(msg)\n self.env.make_snapshot(snapshotname, is_make=True)\n\n @test(depends_on=[SetupEnvironment.prepare_slaves_5],\n groups=['lcm_deploy_1_ctrl_1_cmp_3_ceph'])\n @log_snapshot_after_test\n def lcm_deploy_1_ctrl_1_cmp_3_ceph(self):\n \"\"\"Create cluster with ceph\n\n Scenario:\n 1. Revert snapshot \"ready_with_5_slaves\"\n 2. Create cluster\n 3. Add 1 controller\n 4. Add 1 compute node\n 5. Add 3 ceph-osd nodes\n 6. Deploy cluster\n 7. Check extra deployment tasks\n\n Duration 240m\n Snapshot: \"lcm_deploy_1_ctrl_1_cmp_3_ceph\"\n \"\"\"\n deployment = '1_ctrl_1_cmp_3_ceph'\n snapshotname = 'lcm_deploy_{}'.format(deployment)\n self.check_run(snapshotname)\n self.show_step(1)\n self.env.revert_snapshot(\"ready_with_5_slaves\")\n\n self.show_step(2)\n segment_type = NEUTRON_SEGMENT['tun']\n cluster_id = self.fuel_web.create_cluster(\n name=self.__class__.__name__,\n mode=DEPLOYMENT_MODE,\n settings={\n 'volumes_lvm': False,\n 'volumes_ceph': True,\n 'images_ceph': True,\n 'objects_ceph': True,\n 'net_segment_type': segment_type\n }\n )\n self.show_step(3)\n self.show_step(4)\n self.show_step(5)\n self.fuel_web.update_nodes(\n cluster_id,\n {\n 'slave-01': ['controller'],\n 'slave-02': ['compute'],\n 'slave-03': ['ceph-osd'],\n 'slave-04': ['ceph-osd'],\n 'slave-05': ['ceph-osd']\n }\n )\n\n self.show_step(6)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n self.enable_hugepages([node['id'] for node in slave_nodes])\n self.fuel_web.deploy_cluster_wait(cluster_id)\n self.show_step(7)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n node_refs = self.check_extra_tasks(slave_nodes, deployment)\n if node_refs:\n logger.info('Generating a new fixture . . .')\n self.generate_fixture(node_refs, cluster_id, slave_nodes)\n msg = ('Please update idempotency fixtures in the repo '\n 'according to generated fixtures')\n raise DeprecatedFixture(msg)\n self.env.make_snapshot(snapshotname, is_make=True)\n\n @test(depends_on=[SetupEnvironment.prepare_slaves_9],\n groups=['lcm_deploy_3_ctrl_3_cmp_ceph_sahara'])\n @log_snapshot_after_test\n def lcm_deploy_3_ctrl_3_cmp_ceph_sahara(self):\n \"\"\"Create cluster with Sahara, Ceilometer, Ceph in HA mode\n\n Scenario:\n 1. Revert snapshot \"ready_with_9_slaves\"\n 2. Create cluster\n 3. Add 3 controllers with mongo role\n 4. Add 3 compute node with ceph-osd role\n 5. Deploy cluster\n 6. Check extra deployment tasks\n\n Duration 240m\n Snapshot: \"lcm_deploy_3_ctrl_3_cmp_ceph_sahara\"\n \"\"\"\n deployment = '3_ctrl_3_cmp_ceph_sahara'\n snapshotname = 'lcm_deploy_{}'.format(deployment)\n self.check_run(snapshotname)\n self.show_step(1)\n self.env.revert_snapshot(\"ready_with_9_slaves\")\n\n self.show_step(2)\n segment_type = NEUTRON_SEGMENT['tun']\n cluster_id = self.fuel_web.create_cluster(\n name=self.__class__.__name__,\n mode=DEPLOYMENT_MODE,\n settings={\n 'ceilometer': True,\n \"sahara\": True,\n 'volumes_lvm': False,\n 'volumes_ceph': True,\n 'images_ceph': True,\n 'objects_ceph': True,\n \"net_segment_type\": segment_type\n }\n )\n self.show_step(3)\n self.show_step(4)\n self.fuel_web.update_nodes(\n cluster_id,\n {\n 'slave-01': ['controller', 'mongo'],\n 'slave-02': ['controller', 'mongo'],\n 'slave-03': ['controller', 'mongo'],\n 'slave-04': ['compute', 'ceph-osd'],\n 'slave-05': ['compute', 'ceph-osd'],\n 'slave-06': ['compute', 'ceph-osd']\n }\n )\n\n self.show_step(5)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n self.enable_hugepages([node['id'] for node in slave_nodes])\n self.fuel_web.deploy_cluster_wait(cluster_id)\n self.show_step(6)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n node_refs = self.check_extra_tasks(slave_nodes, deployment, ha=True)\n if node_refs:\n logger.info('Generating a new fixture . . .')\n self.generate_fixture(node_refs, cluster_id, slave_nodes, ha=True)\n msg = ('Please update idempotency fixtures in the repo '\n 'according to generated fixtures')\n raise DeprecatedFixture(msg)\n self.env.make_snapshot(snapshotname, is_make=True)\n\n @test(depends_on=[SetupEnvironment.prepare_slaves_3],\n groups=['lcm_deploy_1_ctrl_1_cmp_1_ironic'])\n @log_snapshot_after_test\n def lcm_deploy_1_ctrl_1_cmp_1_ironic(self):\n \"\"\"Deploy cluster with Ironic:\n\n Scenario:\n 1. Create cluster\n 2. Add 1 controller node\n 3. Add 1 compute node\n 4. Add 1 ironic node\n 5. Deploy cluster\n 6. Check extra deployment tasks\n\n Duration 180m\n Snapshot: lcm_deploy_1_ctrl_1_cmp_1_ironic\n \"\"\"\n deployment = '1_ctrl_1_cmp_1_ironic'\n snapshotname = 'lcm_deploy_{}'.format(deployment)\n self.check_run(snapshotname)\n\n self.env.revert_snapshot(\"ready_with_3_slaves\")\n\n self.show_step(1)\n cluster_id = self.fuel_web.create_cluster(\n name=self.__class__.__name__,\n mode=DEPLOYMENT_MODE,\n settings={\n \"net_segment_type\": NEUTRON_SEGMENT['vlan'],\n \"ironic\": True,\n }\n )\n\n self.show_step(2)\n self.show_step(3)\n self.show_step(4)\n self.fuel_web.update_nodes(\n cluster_id,\n {\n 'slave-01': ['controller'],\n 'slave-02': ['compute'],\n 'slave-03': ['ironic'],\n }\n )\n\n self.show_step(5)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n self.enable_hugepages([node['id'] for node in slave_nodes])\n self.fuel_web.deploy_cluster_wait(cluster_id)\n self.show_step(6)\n slave_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id)\n node_refs = self.check_extra_tasks(slave_nodes, deployment)\n if node_refs:\n logger.info('Generating a new fixture . . .')\n self.generate_fixture(node_refs, cluster_id, slave_nodes)\n msg = ('Please update idempotency fixtures in the repo '\n 'according to generated fixtures')\n raise DeprecatedFixture(msg)\n self.env.make_snapshot(snapshotname, is_make=True)\n","sub_path":"fuelweb_test/tests/tests_lcm/base_lcm_test.py","file_name":"base_lcm_test.py","file_ext":"py","file_size_in_byte":33701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"268662989","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# This software is licensed as described in the README.rst and LICENSE\n# files, which you should have received as part of this distribution.\n\nimport os\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\n# noinspection PyPep8Naming\nfrom trader import __version__ as VERSION\n\n\ndef read_file(name):\n return open(os.path.join(os.path.dirname(__file__), name)).read()\n\nDEPS = [\n \"https://github.com/ricco386/template-bot/zipball/master\",\n]\n\nCLASSIFIERS = [\n 'Environment :: Console',\n 'Intended Audience :: System Administrators',\n 'Intended Audience :: Developers',\n 'Operating System :: Unix',\n 'Operating System :: POSIX :: Linux',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n 'Development Status :: 5 - Production/Stable',\n 'Topic :: Communications :: Chat',\n 'Topic :: Utilities',\n 'Topic :: Home Automation'\n]\n\nsetup(\n name='trader-bot',\n version=VERSION,\n description='Simple bot, used for Bitcoin trade via Kraken.com',\n long_description=read_file('README.rst'),\n author='Richard Kellner',\n author_email='richard.kellner [at] gmail.com',\n url='https://github.com/ricco386/trader-bot',\n license='MIT',\n packages=['trader'],\n scripts=['bin/trader-bot'],\n dependency_links=DEPS,\n platforms='any',\n classifiers=CLASSIFIERS,\n include_package_data=True\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"560672977","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: gxs\n@license: (C) Copyright 2016-2019, Light2Cloud (Beijing) Web Service Co., LTD\n@contact: dingjianfeng@light2cloud.com\n@software: AWS-DJF\n@file: download.py\n@ide: PyCharm\n@time: 2020/7/23 11:01\n@desc:\n\"\"\"\nimport os\nimport pathlib\n\nfrom baidubce.exception import BceError\nfrom initialization import BceAuthentication\nfrom common import _read_bos_file_size, _count_md5\n\n\nclass BceBOSDownload(BceAuthentication):\n\n def __init__(self):\n super().__init__()\n\n def main_function(self):\n \"\"\"\n max_keys=1000\n :return:\n \"\"\"\n bos_client = self.get_bce_connection()\n\n try:\n # 'd/2eeQ7f', 'd/1442413150028', 'd/1442754128155', 'd/1444316556440', 'd/jieINz', 'd/yayYVv'\n # file_directory_list = [\n # 'd/sinldo/bbsy/jk7oxTbYvqiq/1', 'd/sinldo/trsrmyy/XOq7eNQbyEJz/2',\n # 'd/sinldo/yzrmyy/Pu5WmamyMfYj/3', 'd/sinldo/yzrmyy/QCYljhbqaYR3/4'] # 归档\n file_directory_list = ['d/2eeQ7f', 'c/1442413150028']\n\n \"\"\"存放被遍历目录下所有子文件夹的列表\"\"\"\n sub_folder_list = []\n \"\"\"存放被遍历目录下所有文件的列表\"\"\"\n file_list = []\n size_list = []\n for _dir_list in file_directory_list:\n marker = None\n is_truncated = True\n while is_truncated:\n\n response = bos_client.list_objects(bucket_name=self.bos_src_bucket,\n max_keys=1000,\n prefix=_dir_list,\n marker=marker)\n for object in response.contents:\n if object.size == 0 and object.key[-1] == '/':\n sub_folder_list.append(object.key)\n else:\n file_list.append(object.key)\n size_list.append(object.size)\n is_truncated = response.is_truncated\n marker = getattr(response, 'next_marker', None)\n\n if sub_folder_list:\n self.makedir_directory_from_bos(file_directory_list, sub_folder_list)\n else:\n self.makedir_directory_from_bos(file_directory_list,)\n self.logger.warning(f'从 BOS 存储桶读取文件总数量:{len(file_list)} ')\n self.logger.warning(f'从 BOS 存储桶读取文件总大小:{_read_bos_file_size(size_list)} GB ')\n if _read_bos_file_size(size_list) <= str(700):\n return self.download_file_from_bos(bos_client, file_list, file_directory_list)\n else:\n self.logger.warning(f'从 BOS 存储桶读取文件总大小超过 700 GB')\n\n except BceError as e:\n self.logger.error('从 BOS 存储桶读取文件详情时,发生错误 {}'.format(e))\n return []\n\n def makedir_directory_from_bos(self, directories: list, sub_folders: list = None):\n try:\n if sub_folders:\n for directory in directories:\n if not os.path.isdir(directory):\n os.makedirs(directory)\n for sub_folder in sub_folders:\n if not os.path.isdir(sub_folder):\n os.makedirs(sub_folder)\n else:\n for directory in directories:\n if not os.path.isdir(directory):\n os.makedirs(directory)\n except FileExistsError as e:\n self.logger.error('创建对应的多级目录时,发生错误 {}'.format(e))\n\n def download_file_from_bos(self, bos_client, file_lists: list, file_directory_list: list):\n \"\"\"\n :param bos_client:\n :param file_lists: list BOS 数据列表\n :param file_directory_list: CSV 路径列表\n :return:\n \"\"\"\n try:\n for file in file_lists:\n path = pathlib.Path(file)\n if path.is_file():\n pass\n # self.logger.info(f'BOS 存储桶中的文件:{file} 在本地存在,不执行下载操作')\n else:\n if not os.path.isdir(os.path.dirname(file)):\n os.makedirs(os.path.dirname(file))\n if bos_client.get_object_meta_data(bucket_name=self.bos_src_bucket,\n key=file).metadata.bce_storage_class == 'ARCHIVE':\n self.logger.critical(f'BOS 归档文件:{file} ')\n continue\n response = bos_client.get_object_to_file(\n bucket_name=self.bos_src_bucket,\n key=file,\n file_name=file,\n )\n # self.logger.info(f'BOS 存储桶中的文件:{file} 下载到本地')\n\n content_md5 = response.metadata.content_md5\n self.check_file_md5(bos_client=bos_client, file_name=file, file_content_md5=content_md5,\n file_directory_list=file_directory_list)\n\n except BceError as e:\n self.logger.error(f'从 BOS 存储桶下载文件 时,发生错误 {e}')\n return []\n\n except Exception as e:\n self.logger.exception(f'从 BOS 存储桶下载文件时,发生错误 {e} ')\n return []\n\n def check_file_md5(self, bos_client, file_name: str, file_content_md5: str, file_directory_list: list):\n \"\"\"\n :param bos_client:\n :param file_name:\n :param file_content_md5:\n :param file_directory_list:\n :return:\n \"\"\"\n md5 = _count_md5(file_name)\n if file_content_md5 == md5[0]:\n self.logger.info(f'下载、校验文件:{file_name} 完成,数据完整,content_md5:{file_content_md5} ')\n else:\n self.logger.warning(f'下载校验文件:{file_name} 发现数据损坏..... 原始 content_md5:{file_content_md5} '\n f'下载后 content_md5:{md5[0]} ')\n # TODO: 校验失败处理\n\n\nif __name__ == '__main__':\n bos = BceBOSDownload()\n bos.main_function()","sub_path":"ConvenientMigrationTool/BceBOS/download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":6477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"223556824","text":"import pandas as pd\nimport numpy as np\nfrom statsmodels.formula.api import ols\nfrom statsmodels.stats.anova import anova_lm\nfrom sklearn.cluster import KMeans\n\ndata = pd.read_excel(r'C:\\Users\\t430\\Desktop\\Incentive\\RawData\\Agent.xlsx')\ndata = data.drop(['满意度'],axis =1)\ndf= data.drop(['策划师名称','有效回单数'],axis = 1)\npath_output = u'C:/Users/t430/Desktop/Incentive/Output/'\nclf = KMeans(n_clusters=2, random_state=0).fit(df)\n\nL = clf.labels_\nL0 = [i for i,v in enumerate(L) if v==0]\nL1 = [i for i,v in enumerate(L) if v==1]\nL2 = [i for i,v in enumerate(L) if v==2]\nL3 = [i for i,v in enumerate(L) if v==3]\nL4 = [i for i,v in enumerate(L) if v==4]\nL5 = [i for i,v in enumerate(L) if v==5]\nL6 = [i for i,v in enumerate(L) if v==6]\nprint(\"The Cluster centers are :%s\"%clf.cluster_centers_)\nprint(\"The total distance is %s\"%clf.inertia_)\nprint(\"The number of elements in cluster 1 is %s\"%np.sum(L==0))\nprint(\"The number of elements in cluster 2 is %s\"%np.sum(L==1))\nprint(\"The number of elements in cluster 3 is %s\"%np.sum(L==2))\nprint(\"The number of elements in cluster 4 is %s\"%np.sum(L==3))\nprint(\"The number of elements in cluster 5 is %s\"%np.sum(L==4))\nprint(\"The number of elements in cluster 6 is %s\"%np.sum(L==5))\nprint(\"The number of elements in cluster 7 is %s\"%np.sum(L==6))\n\ntb = pd.concat([data,pd.DataFrame(L)],axis =1)\ntb.to_excel('%sLailaoshi.xlsx'%path_output)\nprint(tb.head())\nprint(tb.info())\n","sub_path":"Laolaishi.py","file_name":"Laolaishi.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"138540595","text":"# -*- coding: utf-8 -*-\n\nfrom rest_framework import mixins\nfrom rest_framework import viewsets\n\nfrom admin_app.core.models import City\nfrom ..serializers.geo import CitySerializer\nfrom ..serializers.geo import CityListSerializer\nfrom ..viewsets import RetrieveResponseMixin\n\n\nclass MetroViewSet(\n RetrieveResponseMixin,\n mixins.RetrieveModelMixin,\n viewsets.GenericViewSet\n):\n serializer_class = CitySerializer\n queryset = City.objects.all()\n lookup_field = 'slug'\n\n def get_updated_data(self, serializer):\n data = super(MetroViewSet, self).get_updated_data(serializer)\n data['request'].update({\n '{0}_slug'.format(serializer.instance._meta.model_name):\n serializer.instance.slug,\n })\n data.pop('item')\n data.update({'items': serializer.data.get('metro')})\n return data\n\n\nclass CityViewSet(\n mixins.ListModelMixin,\n viewsets.GenericViewSet\n):\n serializer_class = CityListSerializer\n queryset = City.objects.all()\n","sub_path":"src/face_full/api_v1/views/geo.py","file_name":"geo.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"36"}
+{"seq_id":"260737242","text":"\"\"\"\nmain.py -> Die main Funktion des Börsenspiels.\n\"\"\"\n\nimport src.SPIELER as S\nimport src.DATEN as D\n\nfrom ui.main_window import Ui_Form\n\nfrom PyQt5 import QtWidgets as qtw\nfrom PyQt5 import QtCore as qtc\nimport threading, sys, os\n\n\nclass MainWindow(qtw.QWidget):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.aktuellerTicker = \"\"\n if os.listdir('./data/profile') == []:\n name, nichtCancel = self.abfrageName()\n if not nichtCancel and name == \"\":\n sys.exit()\n else:\n name = os.listdir('./data/profile')[0][:-5]\n \n self.daten = D.DATEN()\n self.spieler = S.SPIELER(name, self.daten.aktuellenTickerpreisErhalten )\n\n self.ui = Ui_Form()\n self.ui.setupUi(self)\n self.ui.tabWidget.setTabVisible(3, False)\n self.aktualisiereTabPortfolio()\n self.ui.plotWidget.setBackground('w')\n self.ui.plotWidget.setAntialiasing(True)\n\n\n # Hier können die Methoden mit den Signalen der Widgets verbunden werden\n\n self.ui.pushButton_aktiensuche.clicked.connect(self.suche)\n self.ui.listWidget_suchergebnis.itemDoubleClicked.connect(lambda listitem: self.bg(self.launchAktieninfo, (listitem, True,)))\n self.ui.listWidget_gekaufteAktien.itemDoubleClicked.connect(lambda listitem: self.bg(self.launchAktieninfo, (listitem, True,)))\n self.ui.pushButton_kaufen.clicked.connect(lambda: self.bg(self.kaufenclick, (True,)))\n self.ui.pushButton_verkaufen.clicked.connect(lambda: self.bg(self.verkaufenclick, (True,)))\n self.ui.tabWidget.currentChanged.connect(lambda x: self.bg(self.aktualisiereTabPortfolio, (x, True,)))\n self.ui.tabWidget.currentChanged.connect(self.aktualisiereTabEinstellungen)\n self.ui.pushButton_preis.clicked.connect(lambda: self.bg(self.aktualisierePreisLabel, (True,)))\n self.ui.pushButton_refresh_Gebuehr.clicked.connect(self.aktualisierenOrderGebuehren)\n self.ui.pushButton_refresh_DepotGuthaben.clicked.connect(self.aktualisierenDepotguthaben)\n self.ui.pushButton_profil_loeschen.clicked.connect(self.profilLoeschen)\n self.ui.pushButton_profil_laden.clicked.connect(self.profilLaden)\n self.ui.pushButton_neues_profil.clicked.connect(self.profilErstellen)\n self.ui.pushButton_refresh_waehrung.clicked.connect(self.aktualisiereWaehrung)\n self.ui.pushButton_ticker_aktualisieren.clicked.connect(lambda: self.bg(self.tickerAktualisieren, (True,)))\n\n # Hier die Methoden für Funktionen der Widgets (z.B. Button) einfügen\n def abfrageName( self ):\n output = qtw.QInputDialog.getText(self, \"Namenswahl\", \"Dein Name:\", qtw.QLineEdit.Normal, \"\")\n return output\n\n def profilErstellen( self ):\n name, nichtCancel = self.abfrageName()\n if nichtCancel and name != '':\n self.spieler.profil_neu(name)\n self.aktualisiereTabEinstellungen()\n \n def profilLoeschen( self ):\n current = self.ui.listWidget_profile.currentItem()\n if current.text() != self.spieler.name:\n self.spieler.profil_loeschen(current.text())\n self.ui.listWidget_profile.removeItemWidget(current)\n self.aktualisiereTabEinstellungen()\n \n def profilLaden( self ):\n name = self.ui.listWidget_profile.currentItem().text()\n self.spieler.profil_laden(name)\n self.aktualisiereTabEinstellungen()\n \n def aktualisiereTabEinstellungen( self, i=2 ):\n if i != 2: return\n self.ui.listWidget_profile.clear()\n self.ui.listWidget_profile.addItems(self.spieler.profile_auflisten())\n self.ui.spinBox_OrderGebuehr.setValue(self.spieler.OrderGebuehren)\n self.ui.groupBox_profile.setTitle(\"Profile (zurzeit %s)\" % self.spieler.name)\n\n def tickerAktualisieren( self, threaded=False):\n self.daten.tickerErneuern()\n self.daten.tickerbaum.saveToFile()\n if threaded: cursorZuruecksetzen()\n\n def kaufenclick( self, threaded=False ):\n self.spieler.wertpapierKaufen(int(self.ui.spinBox_anzahlKaufen.value()), self.aktuellerTicker)\n self.aktualisiereImBesitzLabel(threaded=False)\n if threaded: cursorZuruecksetzen()\n\n def verkaufenclick( self, threaded=False ):\n self.spieler.wertpapierVerkaufen(int(self.ui.spinBox_anzahlVerkaufen.value()), self.aktuellerTicker)\n self.aktualisiereImBesitzLabel(threaded=False)\n if threaded: cursorZuruecksetzen()\n\n def aktualisierePreisLabel( self, threaded=False ):\n tickerpreis = self.daten.aktuellenTickerpreisErhalten(self.aktuellerTicker)\n aktiensumme = self.ui.spinBox_anzahlKaufen.value() - self.ui.spinBox_anzahlVerkaufen.value()\n tickerpreis *= aktiensumme\n self.ui.label_preis.setText(\"%3.2f %s\" % (tickerpreis, self.spieler.waehrung))\n if threaded: cursorZuruecksetzen()\n\n def aktualisiereImBesitzLabel( self, threaded=False ):\n self.ui.label_imBesitz.setText(\"Im Besitz: %d\" % self.spieler.aktienAnzahlErhalten(self.aktuellerTicker))\n if threaded: cursorZuruecksetzen()\n\n def suche( self ):\n self.ui.listWidget_suchergebnis.clear()\n phrase = self.ui.plainTextEdit_aktiensuche.toPlainText()\n liste = [\"%s (%s)\" % (e['name'], e['symbol']) for e in self.daten.tickerbaum.inhaltSuchen(phrase)]\n self.ui.listWidget_suchergebnis.addItems(liste)\n\n def launchAktieninfo( self, qListItem, threaded=False ):\n label = qListItem.text()\n ticker = label.split('(')[1][:-1]\n self.aktuellerTicker = ticker\n self.ui.tabWidget.setTabText(3, label)\n self.ui.tabWidget.setTabVisible(3, True)\n self.ui.tabWidget.setCurrentIndex(3)\n self.konfiguriereAktieninfo(ticker)\n if threaded: cursorZuruecksetzen()\n\n def konfiguriereAktieninfo( self, ticker: str ):\n self.ui.label_preis.setText(self.spieler.waehrung)\n self.aktualisiereImBesitzLabel(threaded=False)\n self.ui.plotWidget.plot(self.daten.tickerpreisErhalten(ticker), pen='b', clear=True)\n #self.ui.plotWidget.plot(self.daten.tickerpreisErhalten(ticker, key='Volume'), pen='g')\n\n def aktualisiereTabPortfolio( self , i =0, threaded=False ):\n if i != 0:\n if threaded: cursorZuruecksetzen()\n return\n self.ui.label_begruessung.setText(\"Hallo, %s!\" % self.spieler.name)\n\n self.ui.listWidget_gekaufteAktien.clear()\n itemlist = [\"%s (%s)\" % (self.daten.aktiennameErhalten(e), e) for e in self.spieler.aktienliste]\n self.ui.listWidget_gekaufteAktien.addItems(itemlist)\n self.ui.listWidget_historie.clear()\n itemlist = [\"%sx %s zum Einzelpreis von %3.2f %s\" % (e['Volumen'], e['Ticker'], e['Preis'], self.spieler.waehrung) for e in self.spieler.kaufHistorie]\n itemlist.reverse()\n self.ui.listWidget_historie.addItems(itemlist)\n\n self.ui.label_depotwert.setText(\"Depotwert: %3.2f %s\" % (self.spieler.depotwertBerechnen(), self.spieler.waehrung))\n self.ui.label_guthaben.setText( \"Guthaben: %3.2f %s\" % (self.spieler.guthaben, self.spieler.waehrung))\n if threaded: cursorZuruecksetzen()\n\n def bg( self, funktion: 'funktion', arguments: tuple): # im Hintergrund ausfuehren\n cursorAufBeschaeftigt()\n x = threading.Thread(target=funktion, args=arguments)\n x.start()\n\n def aktualisierenOrderGebuehren( self ):\n self.spieler.OrderGebuehren = self.ui.spinBox_OrderGebuehr.value()\n\n def aktualisierenDepotguthaben( self ):\n self.spieler.guthaben = self.ui.spinBox_Depotguthaben.value()\n \n def aktualisiereWaehrung( self ):\n self.spieler.waehrung = self.ui.plainTextEdit_Waehrung.toPlainText()\n self.ui.label_waehrung_depotguthaben_aendern.setText(self.spieler.waehrung)\n self.ui.label_waehrung_ordergebuehren.setText(self.spieler.waehrung)\n\n\ndef main():\n pass\n\ndef cursorAufBeschaeftigt():\n app.setOverrideCursor(qtc.Qt.BusyCursor)\n\ndef cursorZuruecksetzen():\n app.restoreOverrideCursor()\n\nif __name__ == \"__main__\":\n main()\n\n app = qtw.QApplication([])\n\n widget = MainWindow()\n widget.show()\n\n app.exec_()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"597213254","text":"# def func_name(a,b,c,d):\r\n# print(a,b,c,d)\r\n# func_name(\"Saad\", \"Ahmad\", \"Dawood\", \"Shahzaib\")\r\n# agr kaal ko hum or name add akrain tw hamain function ma b changing krni pry gi sth sth har baar\r\ndef funarg(normal , *args , **kwargs): #this order very important\r\n print(normal)\r\n for item in args:\r\n print(item)\r\n print(\"\\nI would like to introduce: \")\r\n for key,value in kwargs.items():\r\n print(f\"{key} is a {value}\")\r\nnormal = \"My name is Saad\"\r\narg = [\"Saad\",\"Ahmad\", \"Dawood\", \"Shahzaib\", \"Ahmad\", \"Dawood\", \"Shahzaib\"]\r\nkargs = {\"Saad\":\"Programmer\", \"Shahzaib\":\"CA\", \"Dawood\":\"Police Officer\"}\r\nfunarg(normal,*arg,**kargs)\r\n","sub_path":"31_args_wargs.py","file_name":"31_args_wargs.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"98419292","text":"from pathlib import Path\nimport os\nimport datetime\nimport File\nimport Config\nimport shutil\nimport ExceptionManager\n\nexceptionFileName = \"Directory.py\"\n\n\nclass DirectoryManager:\n\n def __init__(self, environtment):\n self.deployPackInfo = 'DeployPackInfo.log'\n self.runLog = 'Run.log'\n # Root Path\n self.rootPath = Path(self.getRootDirectory())\n # Old klasör yapısı\n self.OldRootDir = self.getOldRootDirectory()\n self.createDirectory(self.OldRootDir)\n \n # Preprod\n self.env = environtment\n if self.env.upper() == 'PREPROD':\n self.prodDbDeployPath = self.getProdDbDeployPath()\n self.packInfoFromDbFolder = self.OldRootDir / self.deployPackInfo\n self.packInfoFromProdDbDeploy = self.prodDbDeployPath / self.deployPackInfo\n\n @staticmethod\n def getDateWithTime():\n return datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n\n def createDirectory(self, path):\n try:\n if not Path.exists(path):\n Path(path).mkdir()\n except Exception as error:\n ExceptionManager.WriteException(\n str(error), \"createDirectory\", exceptionFileName)\n\n def move(self, source, destination):\n try:\n shutil.move(str(source.resolve()),\n str(destination.resolve()))\n except Exception as error:\n ExceptionManager.WriteException(\n str(error), \"move\", exceptionFileName)\n\n def getRootDirectory(self):\n return Path(Config.getRootDirectory())\n\n def getOldRootDirectory(self):\n oldDirectory = Path(Config.getOldDirectory())\n oldDirectory = oldDirectory / self.getDateWithTime()\n return oldDirectory\n\n def getAllFiles(self, files):\n for (l_dirpath, l_dirnames, l_filenames) in os.walk(self.rootPath):\n if l_filenames:\n for fileName in l_filenames:\n filePath = Path(Path(l_dirpath).resolve(), fileName)\n files.append(File.File(fileName, filePath))\n\n def moveScriptsToOldFolder(self, files):\n for file in files:\n self.move(file.path, self.OldRootDir)\n file.path = self.OldRootDir.resolve() / file.name\n\n def prepareSpoolPath(self, files):\n for file in files:\n file.spoolPath = file.path.with_suffix('.log')\n\n def prepareRunLog(self):\n try:\n with open(self.OldRootDir.resolve() / self.runLog, \"a+\") as f:\n f.write(\"Versiyon: 0.2.1\")\n f.close()\n except Exception as error:\n ExceptionManager.WriteException(\n str(error), \"writeRunLog\", exceptionFileName)\n\n def writeRunLog(self, queryResult, errorMessage, fileName):\n try:\n with open(self.OldRootDir.resolve() / self.runLog, \"a+\") as f:\n f.write(\"\\n\")\n f.write(\"-----------------\\n\")\n f.write(fileName + \" - \" + str(queryResult))\n f.close()\n except Exception as error:\n ExceptionManager.WriteException(\n str(error), \"writeRunLog\", exceptionFileName)\n\n # PreProd\n def getProdDbDeployPath(self):\n return Path(Config.getProdDbDeployPath())\n\n def copyScriptsToProdDbFolder(self, files):\n for file in files:\n if file.name.upper() == self.deployPackInfo.upper():\n continue\n if file.name.upper() == self.runLog.upper():\n continue\n self.copy(file.path, self.prodDbDeployPath)\n file.path = self.OldRootDir.resolve() / file.name\n\n def copy(self, source, destination):\n try:\n shutil.copy(str(source.resolve()),\n str(destination.resolve()))\n except Exception as error:\n ExceptionManager.WriteException(\n str(error), \"copy\", exceptionFileName)\n\n def readDeployPackInfo(self):\n read_data = ''\n try:\n with open(self.packInfoFromDbFolder.resolve()) as f:\n read_data = f.read()\n f.close()\n except Exception as error:\n ExceptionManager.WriteException(\n str(error), \"readDeployPackInfo\", exceptionFileName)\n return read_data\n\n def appendDeployPackInfoTo09(self, content):\n try:\n with open(self.packInfoFromProdDbDeploy.resolve(), 'a+') as f:\n f.write('\\n')\n f.write(content)\n f.close()\n except Exception as error:\n ExceptionManager.WriteException(\n str(error), \"appendDeployPackInfoTo09\", exceptionFileName)\n","sub_path":"DirectoryManager.py","file_name":"DirectoryManager.py","file_ext":"py","file_size_in_byte":4676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"107248426","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @return a ListNode\n def addTwoNumbers(self, l1, l2):\n a = l1.val\n i = 1\n while l1.next != None:\n a = a + l1.next.val*(10**i)\n l1 = l1.next\n i = i + 1\n b = l2.val\n i = 1\n while l2.next != None:\n b = b + l2.next.val*(10**i)\n l2 = l2.next\n i = i + 1\n sum = a + b\n #sumstring = str(sum)[::-1]\n #length = len(sumstring)\n res = ListNode(0)\n cur = res\n while sum>=10:\n cur.val = sum%10\n sum = sum/10\n nextnode = ListNode(0)\n cur.next = nextnode\n cur = nextnode\n cur.val = sum\n cur.next = None\n return res\n","sub_path":"add-two-numbers.py","file_name":"add-two-numbers.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"495651737","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.models import AbstractUser\n\n# Create your models here.\nfrom company.models import Company\nfrom department.models import Section\n\nclass Position(models.Model):\n\tname \t\t\t\t= models.CharField(primary_key=True,max_length=50,null = False)\n\tdescription \t\t= models.TextField(null = True,blank = True)\n\n\tdef __str__(self):\n\t\treturn ('%s' % (self.name))\n\n# Techician\n# Hastler\n# Crane\n\nROLE_CHOICES = (\n ('Foreman', 'Foreman'),\n ('Leader', 'Leader'),\n ('Officer','Officer'),\n ('superintendent','superintendent'),\n ('Operator','Operator'),\n ('Manager','Manager')\n )\n\nTITLE_CHOICES = (\n ('Mr', 'Mr.'),\n ('Ms', 'Ms.'),\n ('Mrs', 'Mrs.'),\n ('Miss','Miss.'),\n )\nclass User(AbstractUser):\n\ttitle\t\t\t\t= models.CharField(max_length=10,choices=TITLE_CHOICES,default='Mr')\n\ten\t\t\t\t\t= models.CharField(max_length=50,null = False)\n\tcompany \t\t\t= models.ForeignKey(Company,\n\t\t\t\t\t\t\t\tblank=True,null=True ,on_delete=models.CASCADE,\n\t\t\t\t\t\t\t\trelated_name = 'employees' )\n\tsection\t\t\t\t= models.ForeignKey(Section,\n\t\t\t\t\t\t\t\tblank=True,null=True , on_delete=models.CASCADE,\n\t\t\t\t\t\t\t\trelated_name = 'employees')\n\tposition \t\t\t= models.ForeignKey(Position,\n\t\t\t\t\t\t\t\tblank=True,null=True , on_delete=models.CASCADE,\n\t\t\t\t\t\t\t\trelated_name = 'employees')\n\tdescription \t\t= models.TextField(null = True,blank = True)\n\tmanager \t\t\t= models.ForeignKey('self', blank = True,null=True, related_name='employees',\n\t\t\t\t\t\t\t\ton_delete=models.SET_NULL)\n\tteam\t\t\t\t= models.PositiveSmallIntegerField(default=100)\n\n\tclass Meta:\n\t\tunique_together = (('en','company'))\n\n\tdef __str__(self):\n\t\treturn ('%s %s' % (self.first_name,self.last_name))\n","sub_path":"employee/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"191830646","text":"from django.conf.urls.defaults import patterns, url\n\nfrom poll.models import Poll\n\n\nurlpatterns = patterns(\n '',\n url(\n r'^(?P[\\w-]+)/$',\n 'jmbo.generic.views.generic_object_detail',\n {'queryset':Poll.permitted.all()},\n name='poll_object_detail'\n ),\n url(\n r'^poll-detail-vote/(?P\\d+)/$',\n 'poll.views.poll_vote',\n {'template':'poll/poll_detail.html'},\n name='poll-detail-vote'\n ),\n url(\n r'^poll-widget-vote/(?P\\d+)/$',\n 'poll.views.poll_vote',\n {'template':'poll/poll_widget.html'},\n name='poll-widget-vote'\n ),\n\n)\n","sub_path":"poll/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"4913596","text":"def insertion_sort(numbers):\n for i in range(1,(len(numbers))):\n key = numbers[i]\n j = i - 1\n while (j > -1 and numbers[j] > key):\n numbers[j + 1] = numbers[j]\n j -= 1\n numbers[j + 1] = key\n return numbers\n\nif __name__ == \"__main__\":\n print(insertion_sort([2, 6, 1, 3, 11, 7, 4]))","sub_path":"insertion_sort.py","file_name":"insertion_sort.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"623665535","text":"N,C=[int(i) for i in input().split()]\r\nL=[int(input())for i in range(N)]\r\n\r\nL.sort()\r\nindexL=0\r\nindexR=len(L)-1\r\n\r\nans=0\r\nwhile indexL 0:\n index -= 1\n else:\n index += 1\n\nprint(len(line))\n","sub_path":"python/d5p1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"51515295","text":"# The MIT License (MIT)\n# Copyright (c) 2018 by EUMETSAT\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n# of the Software, and to permit persons to whom the Software is furnished to do\n# 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 asyncio\nimport json\nimport logging\nimport os\nimport signal\nimport sys\nimport time\nimport traceback\nfrom datetime import datetime\nfrom typing import Optional, List\n\nimport tornado.options\nimport yaml\nfrom tornado.ioloop import IOLoop\nfrom tornado.log import enable_pretty_logging\nfrom tornado.web import RequestHandler, Application\n\nfrom ocdb.core.roles import Roles\nfrom .context import WsContext\nfrom .defaults import DEFAULT_ADDRESS, DEFAULT_PORT, DEFAULT_CONFIG_FILE, DEFAULT_UPDATE_PERIOD, DEFAULT_LOG_PREFIX, \\\n DEFAULT_SSL\nfrom .reqparams import RequestParams\nfrom ..core import UNDEFINED\n\n_LOG = logging.getLogger('ocdb')\n_LOG_FidRadDb = logging.getLogger('fidraddb')\n\nclass WebService:\n \"\"\"\n A web service that provides a remote API to some application.\n \"\"\"\n\n def __init__(self,\n application: Application,\n address: str = DEFAULT_ADDRESS,\n port: int = DEFAULT_PORT,\n ssl: bool = DEFAULT_SSL,\n config_file: Optional[str] = None,\n update_period: Optional[float] = DEFAULT_UPDATE_PERIOD,\n log_file_prefix: str = DEFAULT_LOG_PREFIX,\n log_to_stderr: bool = False) -> None:\n\n \"\"\"\n Start a tile service.\n\n The *service_info_file*, if given, represents the service in the filesystem, similar to\n the ``/var/run/`` directory on Linux systems.\n\n If the service file exist and its information is compatible with the requested *port*, *address*, *caller*, then\n this function simply returns without taking any other actions.\n\n :param application: The Tornado web application\n :param address: the address\n :param port: the port number\n :param config_file: optional configuration file\n :param update_period: if not-None, time of idleness in seconds before service is updated\n :param log_file_prefix: Log file prefix, default is DEFAULT_LOG_PREFIX\n :param log_to_stderr: Whether logging should be shown on stderr\n :return: service information dictionary\n \"\"\"\n log_dir = os.path.dirname(log_file_prefix)\n if log_dir and not os.path.isdir(log_dir):\n os.makedirs(log_dir, exist_ok=True)\n\n options = tornado.options.options\n options.log_file_prefix = log_file_prefix or DEFAULT_LOG_PREFIX\n options.log_to_stderr = log_to_stderr\n enable_pretty_logging()\n\n self.config_file = os.path.abspath(config_file) if config_file else None\n print(f\"Using config file {self.config_file}\")\n self.config_mtime = None\n self.update_period = update_period\n self.update_timer = None\n self.config_error = None\n self.service_info = dict(port=port,\n address=address,\n started=datetime.now().isoformat(sep=' '),\n pid=os.getpid())\n self.ws_context = WsContext(base_dir=os.path.dirname(self.config_file or os.path.abspath('')))\n\n application.ws_context = self.ws_context\n application.time_of_last_activity = time.process_time()\n self.application = application\n\n from tornado.httpserver import HTTPServer\n\n if ssl:\n self.server = HTTPServer(application, ssl_options={\n \"certfile\": \"static/certs/fullchain.pem\",\n \"keyfile\": \"static/certs/privkey.pem\",\n })\n else:\n self.server = HTTPServer(application)\n\n self.server.listen(port)\n\n # Ensure we have the same event loop in all threads\n asyncio.set_event_loop_policy(_GlobalEventLoopPolicy(asyncio.get_event_loop()))\n # Register handlers for common termination signals\n signal.signal(signal.SIGINT, self._sig_handler)\n signal.signal(signal.SIGTERM, self._sig_handler)\n self._maybe_load_config()\n self._maybe_install_update_check()\n\n def start(self):\n address = self.service_info['address']\n port = self.service_info['port']\n _LOG.info(f'web service running, listening on {address}:{port} (press CTRL+C to stop service)')\n if len(self.ws_context.config.get('databases', {})) == 0:\n _LOG.warning('no databases configured')\n IOLoop.current().start()\n\n def stop(self, kill=False):\n \"\"\"\n Stops the Tornado web server.\n \"\"\"\n if kill:\n sys.exit(0)\n else:\n IOLoop.current().add_callback(self._on_shut_down)\n\n def _on_shut_down(self):\n\n _LOG.info('stopping web service...')\n\n # noinspection PyUnresolvedReferences,PyBroadException\n try:\n self.update_timer.cancel()\n except Exception:\n pass\n\n # Shutdown services such as database drivers\n self.ws_context.dispose()\n\n if self.server:\n self.server.stop()\n self.server = None\n\n IOLoop.current().stop()\n\n # noinspection PyUnusedLocal\n def _sig_handler(self, sig, frame):\n _LOG.warning(f'caught signal {sig}')\n IOLoop.current().add_callback_from_signal(self._on_shut_down)\n\n def _maybe_install_update_check(self):\n if self.update_period is None or self.update_period <= 0:\n return\n IOLoop.current().call_later(self.update_period, self._maybe_check_for_updates)\n\n def _maybe_check_for_updates(self):\n self._maybe_load_config()\n self._maybe_install_update_check()\n\n def _maybe_load_config(self):\n config_file = self.config_file\n if config_file is None:\n if os.path.isfile(DEFAULT_CONFIG_FILE):\n config_file = DEFAULT_CONFIG_FILE\n else:\n return\n try:\n stat = os.stat(config_file)\n except OSError as e:\n if self.config_error is None:\n _LOG.error(f'configuration file {config_file!r}: {e}')\n self.config_error = e\n return\n if self.config_mtime != stat.st_mtime:\n self.config_mtime = stat.st_mtime\n try:\n with open(config_file) as stream:\n # Reconfigure services such as database drivers\n self.ws_context.configure(yaml.safe_load(stream))\n self.config_error = None\n _LOG.info(f'configuration file {config_file!r} successfully loaded')\n except (yaml.YAMLError, OSError) as e:\n if self.config_error is None:\n _LOG.error(f'configuration file {config_file!r}: {e}')\n self.config_error = e\n return\n\n\n# noinspection PyAbstractClass\nclass WsRequestHandler(RequestHandler):\n\n # todo se ... not overwrite __init__ ... see documentation of superclass\n def __init__(self, application, request, **kwargs):\n super(WsRequestHandler, self).__init__(application, request, **kwargs)\n self._header = WsRequestHeader(self)\n self._query = WsRequestQuery(self)\n self._cookie = WsRequestCookie(self)\n\n @property\n def ws_context(self) -> WsContext:\n return self.application.ws_context\n\n @property\n def base_url(self):\n return self.request.protocol + '://' + self.request.host\n\n @property\n def header(self) -> RequestParams:\n return self._header\n\n @property\n def query(self) -> RequestParams:\n return self._query\n\n @property\n def cookie(self) -> RequestParams:\n return self._cookie\n\n def get_current_user(self):\n cookie = self.get_secure_cookie(\"user\")\n if cookie is not None:\n return cookie.decode(\"utf-8\")\n else:\n return None\n\n def set_default_headers(self):\n self.set_header(\"Access-Control-Allow-Origin\", \"*\")\n self.set_header(\"Access-Control-Allow-Credentials\", \"true\")\n self.set_header(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization, X-Requested-With\")\n self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')\n\n def options(self, *args, **kwargs):\n self.set_status(204)\n self.finish()\n\n def on_finish(self):\n \"\"\"\n Store time of last activity so we can measure time of inactivity and then optionally auto-exit.\n \"\"\"\n self.application.time_of_last_activity = time.process_time()\n\n @classmethod\n def to_json(cls, obj) -> str:\n \"\"\"Convert object *obj* to JSON string\"\"\"\n return json.dumps(obj, indent=2)\n\n def write_error(self, status_code, **kwargs):\n \"\"\"\n Overwrite ``RequestHandler`` default behaviour. Our implementation writes a server error response as\n JSON object using the form {\"error\": {\"code\": *status_code*, ... }}.\n\n If the \"serve_traceback\" is set and *kwargs* contains a value for keyword \"exc_info\",\n it is expected to be a traceback object from an exception handler and the error object will also contain\n a field \"traceback\" containing the traceback text lines.\n \"\"\"\n self.set_header('Content-Type', 'application/json')\n obj = dict(error=dict(code=status_code, message=self._reason))\n if self.settings.get(\"serve_traceback\") and \"exc_info\" in kwargs:\n traceback_lines = []\n for traceback_line in traceback.format_exception(*kwargs[\"exc_info\"]):\n traceback_lines.append(traceback_line)\n obj['traceback'] = traceback_lines\n self.finish(self.to_json(obj))\n\n def has_admin_rights(self):\n user_name = self.get_current_user()\n if not user_name:\n return False\n\n user = self.ws_context.get_user(user_name)\n if not Roles.is_admin(user.roles):\n return False\n\n return True\n\n def has_submit_rights(self):\n user_name = self.get_current_user()\n if not user_name:\n return False\n\n user = self.ws_context.get_user(user_name)\n if not Roles.is_submit(user.roles):\n return False\n\n return True\n\n def has_fidrad_rights(self):\n user_name = self.get_current_user()\n if not user_name:\n return False\n\n user = self.ws_context.get_user(user_name)\n if not Roles.is_fidrad(user.roles):\n return False\n\n return True\n\n def is_self(self, user_name: str):\n current_user_name = self.get_current_user()\n if not current_user_name:\n return False\n\n if user_name == current_user_name:\n return True\n else:\n return False\n\n\nclass WsRequestHeader(RequestParams):\n def __init__(self, handler: RequestHandler):\n self.handler = handler\n\n def get_param(self, name: str, default: Optional[str] = UNDEFINED) -> Optional[str]:\n \"\"\"\n Get query argument.\n :param name: Query argument name\n :param default: Default value.\n :return: the value or none\n :raise: WsBadRequestError\n \"\"\"\n if default == UNDEFINED and name not in self.handler.request.headers:\n raise self._error_missing(name)\n return self.handler.request.headers.get(name, default=default)\n\n def get_params(self, name: str) -> Optional[str]:\n \"\"\"\n Get query argument array.\n :param name: Query argument name\n :return: the values or an empyty array\n :raise: WsBadRequestError\n \"\"\"\n raise NotImplementedError()\n\n\nclass WsRequestQuery(RequestParams):\n def __init__(self, handler: RequestHandler):\n self.handler = handler\n\n def get_param(self, name: str, default: Optional[str] = UNDEFINED) -> Optional[str]:\n \"\"\"\n Get query argument.\n :param name: Query argument name\n :param default: Default value.\n :return: the value or none\n :raise: WsBadRequestError\n \"\"\"\n if default == UNDEFINED:\n return self.handler.get_query_argument(name)\n return self.handler.get_query_argument(name, default=default)\n\n def get_params(self, name: str) -> List[str]:\n \"\"\"\n Get query argument array.\n :param name: Query argument name\n :return: the values or an empty array\n :raise: WsBadRequestError\n \"\"\"\n return self.handler.get_query_arguments(name)\n\n\nclass WsRequestCookie(RequestParams):\n def __init__(self, handler: RequestHandler):\n self.handler = handler\n\n def get_param(self, name: str, default: Optional[str] = UNDEFINED) -> Optional[str]:\n \"\"\"\n Get query argument.\n :param name: Query argument name\n :param default: Default value.\n :return: the value or none\n :raise: WsBadRequestError\n \"\"\"\n if default == UNDEFINED:\n return self.handler.get_cookie(name)\n return self.handler.get_cookie(name, default=default)\n\n def get_params(self, name: str) -> Optional[str]:\n \"\"\"\n Get query argument array.\n :param name: Query argument name\n :return: the values or an empyty array\n :raise: WsBadRequestError\n \"\"\"\n raise NotImplementedError()\n\n\n# noinspection PyAbstractClass\nclass _GlobalEventLoopPolicy(asyncio.DefaultEventLoopPolicy):\n \"\"\"\n Event loop policy that has one fixed global loop for all threads.\n\n We use it for the following reason: As of Tornado 5 IOLoop.current() no longer has\n a single global instance. It is a thread-local instance, but only on the main thread.\n Other threads have no IOLoop instance by default.\n\n _GlobalEventLoopPolicy is a fix that allows us to access the same IOLoop\n in all threads.\n\n Usage::\n\n asyncio.set_event_loop_policy(_GlobalEventLoopPolicy(asyncio.get_event_loop()))\n\n \"\"\"\n\n def __init__(self, global_loop):\n super().__init__()\n self._global_loop = global_loop\n\n def get_event_loop(self):\n return self._global_loop\n\n\ndef url_pattern(pattern: str):\n \"\"\"\n Convert a string *pattern* where any occurrences of ``{{NAME}}`` are replaced by an equivalent\n regex expression which will assign matching character groups to NAME. Characters match until\n one of the RFC 2396 reserved characters is found or the end of the *pattern* is reached.\n\n The function can be used to map URLs patterns to request handlers as desired by the Tornado web server, see\n http://www.tornadoweb.org/en/stable/web.html\n\n RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists\n the following reserved characters::\n\n reserved = \";\" | \"/\" | \"?\" | \":\" | \"@\" | \"&\" | \"=\" | \"+\" | \"$\" | \",\"\n\n :param pattern: URL pattern\n :return: equivalent regex pattern\n :raise ValueError: if *pattern* is invalid\n \"\"\"\n name_pattern = '(?P<%s>[^\\;\\/\\?\\:\\@\\&\\=\\+\\$\\,]+)'\n reg_expr = ''\n pos = 0\n while True:\n pos1 = pattern.find('{', pos)\n if pos1 >= 0:\n pos2 = pattern.find('}', pos1 + 1)\n if pos2 > pos1:\n name = pattern[pos1 + 1:pos2]\n if not name.isidentifier():\n raise ValueError('name in {name} must be a valid identifier, but got \"%s\"' % name)\n reg_expr += pattern[pos:pos1] + (name_pattern % name)\n pos = pos2 + 1\n else:\n raise ValueError('no matching \"}\" after \"{\" in \"%s\"' % pattern)\n\n else:\n reg_expr += pattern[pos:]\n break\n return reg_expr\n","sub_path":"ocdb/ws/webservice.py","file_name":"webservice.py","file_ext":"py","file_size_in_byte":16587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"37"}
+{"seq_id":"229211614","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Kyle Tilbury, March 2018\n\n# This program takes a text file and produces a word2vec model.\nfrom __future__ import print_function\n\nimport timeit\nimport logging\nimport os.path\nimport sys\nfrom gensim.models import Word2Vec\nfrom gensim.models.word2vec import LineSentence\n\nif __name__ == '__main__':\n # Set up logging\n this_program = os.path.basename(sys.argv[0])\n log = logging.getLogger(this_program)\n\n logging.basicConfig(format='%(asctime)s | %(levelname)s : %(message)s')\n logging.root.setLevel(level=logging.INFO)\n log.info(\"Running %s\" % ' '.join(sys.argv))\n\n\n # Check arguments\n if len(sys.argv) != 3:\n print(\"Error. Run as \\\"TrainWord2VecModel